Multiplayer agent harness for work.
Compress large capability tokens behind a staged rollout switch (#1578)
Regan Bell00ba79959426
diff --git a/.env.example b/.env.exampleindex 0ac372aad..848ee54ed 100644--- a/.env.example+++ b/.env.example@@ -30,6 +30,7 @@ PORT=8080CORE_SIGNING_SECRET=CAPABILITY_SECRET=+CAPABILITY_TOKEN_COMPRESSION=0PORTAL_IDENTITY_SECRET=CONNECTOR_SECRET_KEY=SKILL_SIGNING_SECRET=diff --git a/docs/capability-tokens.md b/docs/capability-tokens.mdnew file mode 100644index 000000000..fcb412770--- /dev/null+++ b/docs/capability-tokens.md@@ -0,0 +1,32 @@+# Capability token encoding and rollout++Room capabilities carry participant assertions for authorization. Large rosters appear+in both the publishing and keychain audiences, so uncompressed tokens can exceed HTTP+header limits before a request reaches core. Increasing core's header limit does not+fix limits imposed by upstream proxies.++`CAPABILITY_TOKEN_COMPRESSION=1` enables compression of claim payloads larger than+4096 bytes for every capability audience. The signed envelope contains a base64url+raw-DEFLATE payload. Verification authenticates the envelope before inflating it,+limits decoded claims to 1 MiB, and applies the existing claim checks. Small tokens+retain their existing encoding. Tokens remain self-contained across replicas and+restarts; no authorization state is moved into a process-local cache. Compression+reduces roster repetition but is not a fixed-size token: unusually large or poorly+compressible claims can still exceed a deployment's header limit.++Compression is off by default for a staged protocol rollout:++1. Keep `CAPABILITY_TOKEN_COMPRESSION` unset or `0` while deploying this verifier to+ every core API replica, worker, and separately deployed egress proxy. Complete the+ blue-green drain of older replicas before enabling issuance.+2. Refresh saved copies of the file upload helper from `/v1/files/upload-client`;+ older copies cannot decode compressed tokens.+3. Set `CAPABILITY_TOKEN_COMPRESSION=1` on every process that issues capabilities,+ including core and workers, and restart them. New turns receive compact tokens;+ already-issued oversized tokens are not rewritten, so retry in a new turn.++To disable issuance, set the switch to `0`. Both encodings remain readable regardless+of that switch. Do not roll verifiers back to a version predating compression until+all compressed tokens have expired or been revoked. Sandbox tokens normally live+48 hours; other capability audiences may have longer lifetimes, so inventory those+before rolling back. Leaving the updated verifiers in place is the safe rollback.diff --git a/src/api/deps.ts b/src/api/deps.tsindex 33320b9a7..5d2b22766 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -85,6 +85,7 @@ export interface ServerDeps {allowUnauthenticatedCore?: boolean;signingSecret?: string;capabilitySecret?: string;+ capabilityTokenCompression?: boolean;portalIdentitySecret?: string;requireSignedPortalIdentity?: boolean;control: ControlService;diff --git a/src/api/routes/context.ts b/src/api/routes/context.tsindex 6bcb30f0d..24c1e1538 100644--- a/src/api/routes/context.ts+++ b/src/api/routes/context.ts@@ -185,6 +185,7 @@ function awaitFileFulfillment(ctx: ApiCtx, requestId: string): Promise<void> {exp: Date.now() + FILE_DOWNLOAD_TTL_MS,},(ctx.deps.capabilitySecret ?? secret)!,+ ctx.deps.capabilityTokenCompression,);const { blobId, ...meta } = file;return sendJson(res, 200, {diff --git a/src/api/routes/secret-drop.ts b/src/api/routes/secret-drop.tsindex 4f113cf9f..dedd0a1cf 100644--- a/src/api/routes/secret-drop.ts+++ b/src/api/routes/secret-drop.ts@@ -248,6 +248,7 @@ async function mintDrop(ctx: ApiCtx): Promise<void> {exp: Date.now() + SECRET_DROP_TTL_MS,},capSecret,+ deps.capabilityTokenCompression,);const formPath = `/drop/${dropId}/form?t=${encodeURIComponent(linkToken)}`;const base = (deps.portalUrl ?? deps.publicUrl)?.replace(/\/$/, "");diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex 0e6518d62..9a20f8019 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -701,6 +701,7 @@ async function sessionCapability(ctx: ApiCtx): Promise<void> {const token = await mintCapabilityToken({ actorId: actor.p, scopeId: makeScopeId("personal", actor.p), exp: Date.now() + CAPABILITY_TTL_MS },secret,+ deps.capabilityTokenCompression,);return sendJson(res, 200, { token });}diff --git a/src/auth/capability-token.ts b/src/auth/capability-token.tsindex f5ede207c..ba33a6c15 100644--- a/src/auth/capability-token.ts+++ b/src/auth/capability-token.ts@@ -1,3 +1,5 @@+import { promisify } from "node:util";+import { deflateRaw, inflateRaw } from "node:zlib";import { orgId as configOrgId } from "../config.ts";import type { CandidateDestination, Destination, EgressPolicy, Principal, ScopeId } from "../types.ts";import { mintSignedPayload, verifySignedPayload } from "./signed-token.ts";@@ -52,8 +54,37 @@ export interface CapabilityClaims {exp: number;}-export function mintCapabilityToken(claims: CapabilityClaims, secret: string): Promise<string> {- return mintSignedPayload({ orgId: configOrgId(), ...claims }, secret);+const compress = promisify(deflateRaw);+const decompress = promisify(inflateRaw);+const MAX_CLAIMS_BYTES = 1024 * 1024;++export async function mintCapabilityToken(+ claims: CapabilityClaims,+ secret: string,+ compressionEnabled = false,+): Promise<string> {+ const value = { orgId: configOrgId(), ...claims };+ const bytes = Buffer.from(JSON.stringify(value));+ if (bytes.length > MAX_CLAIMS_BYTES) throw new Error("Capability claims exceed size limit");+ return mintSignedPayload(+ compressionEnabled && bytes.length > 4096+ ? { encoding: "deflate-raw", claims: (await compress(bytes)).toString("base64url") }+ : value,+ secret,+ );+}++async function readCapabilityClaims(token: string, secret: string | string[]): Promise<CapabilityClaims | null> {+ const value = await verifySignedPayload(token, secret);+ if (!value || typeof value !== "object") return null;+ if (!("encoding" in value)) return value as CapabilityClaims;+ if (value.encoding !== "deflate-raw" || !("claims" in value) || typeof value.claims !== "string") return null;+ try {+ const bytes = await decompress(Buffer.from(value.claims, "base64url"), { maxOutputLength: MAX_CLAIMS_BYTES });+ return JSON.parse(bytes.toString("utf8")) as CapabilityClaims;+ } catch {+ return null;+ }}export function isValidCapabilityTimezone(timezone: unknown): timezone is string {@@ -72,7 +103,7 @@ export async function verifyCapabilityToken(secret: string | string[],now: number = Date.now(),): Promise<CapabilityClaims | null> {- const claims = (await verifySignedPayload(token, secret)) as CapabilityClaims | null;+ const claims = await readCapabilityClaims(token, secret);if (!claims ||typeof claims.actorId !== "string" ||diff --git a/src/config.ts b/src/config.tsindex 675062deb..e6399f211 100644--- a/src/config.ts+++ b/src/config.ts@@ -127,6 +127,7 @@ export interface Config {monitorHeartbeatMs: number;signingSecret?: string;capabilitySecret?: string;+ capabilityTokenCompression?: boolean;portalIdentitySecret?: string;requireSignedPortalIdentity?: boolean;connectorSecretKey?: string;@@ -1539,6 +1540,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {...((env.PORTAL_IDENTITY_SECRET ?? env.CORE_SIGNING_SECRET)? { portalIdentitySecret: env.PORTAL_IDENTITY_SECRET ?? env.CORE_SIGNING_SECRET }: {}),+ capabilityTokenCompression:+ boolEnvStrict("CAPABILITY_TOKEN_COMPRESSION", env.CAPABILITY_TOKEN_COMPRESSION) ?? false,requireSignedPortalIdentity: env.REQUIRE_SIGNED_PORTAL_IDENTITY === "1",...(env.CONNECTOR_SECRET_KEY ? { connectorSecretKey: env.CONNECTOR_SECRET_KEY } : {}),...(slackEventsPort !== undefined ? { slackEventsPort } : {}),diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex 8b6d66ba0..85f9ac273 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -1619,6 +1619,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {connectorEnv.AGENT_API_TOKEN = await mintCapabilityToken(controlClaims,deps.capabilitySecret ?? deps.signingSecret,+ deps.capabilityTokenCompression,);connectorEnv.AGENT_OAUTH_CONSENT_TOKEN = await mintCapabilityToken({@@ -1627,6 +1628,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {exp: Date.now() + SANDBOX_CAPABILITY_TTL_MS,},deps.capabilitySecret ?? deps.signingSecret,+ deps.capabilityTokenCompression,);if (deps.serviceCreds) {const records = serviceCredRecords;@@ -1687,6 +1689,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {exp: Date.now() + SANDBOX_CAPABILITY_TTL_MS,},egressSecret,+ deps.capabilityTokenCompression,);}const registerServiceCredentials = async (@@ -1729,6 +1732,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {exp: Date.now() + SANDBOX_CAPABILITY_TTL_MS,},(deps.capabilitySecret ?? deps.signingSecret)!,+ deps.capabilityTokenCompression,);})());for (const credential of available) {diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex 9bf4c3a0c..9ac0d8a6f 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -143,6 +143,7 @@ export interface OrchestratorDeps {harness: Harness;signingSecret?: string;capabilitySecret?: string;+ capabilityTokenCompression?: boolean;apiBaseUrl?: string;publicWebUrl?: string;/** The public base for an inbound webhook URL (PUBLIC_WEB_URL ?? api url) — what the webhookdiff --git a/src/files/upload-client.py b/src/files/upload-client.pyindex e20c1cead..4d238f9a3 100644--- a/src/files/upload-client.py+++ b/src/files/upload-client.py@@ -9,6 +9,7 @@ import timeimport urllib.errorimport urllib.requestimport uuid+import zlibfrom pathlib import PathPART_SIZE = 64 * 1024 * 1024@@ -70,6 +71,14 @@ def main():checksums.append(base64.b64encode(hashlib.sha256(b"").digest()).decode())token_parts = os.environ["AGENT_API_TOKEN"].split(".")claims = json.loads(base64.urlsafe_b64decode(token_parts[1 if len(token_parts) == 3 else 0] + "==="))+ if "encoding" in claims:+ if claims["encoding"] != "deflate-raw":+ raise RuntimeError("unsupported capability encoding")+ inflater = zlib.decompressobj(-zlib.MAX_WBITS)+ decoded = inflater.decompress(base64.urlsafe_b64decode(claims["claims"] + "==="), 1024 * 1024 + 1)+ if len(decoded) > 1024 * 1024 or not inflater.eof:+ raise RuntimeError("invalid or oversized capability claims")+ claims = json.loads(decoded)destination = {"origin": os.environ["AGENT_API_URL"].rstrip("/"), "actor": claims["actorId"], "scope": args.scope or claims["scopeId"]}manifest = {"name": args.name or args.file.name, "mimetype": mimetypes.guess_type(args.file.name)[0] or "application/octet-stream", "sizeBytes": size, "checksums": checksums}if args.scope:diff --git a/src/wiring.ts b/src/wiring.tsindex d3ef5adfe..3a87636bb 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1134,6 +1134,7 @@ export function buildApp(exp: Date.now() + CAPABILITY_TTL_MS,},secret,+ config.capabilityTokenCompression,);return { egressToken };},@@ -1166,6 +1167,7 @@ export function buildApp(exp: Date.now() + CAPABILITY_TTL_MS,},egressSecret,+ config.capabilityTokenCompression,);return { egressToken };},@@ -1701,6 +1703,7 @@ export function buildApp(exp: Date.now() + DEPLOYMENT_CREDENTIAL_TTL_MS,},config.capabilitySecret ?? deployGitSecret,+ config.capabilityTokenCompression,);}return env;@@ -1876,6 +1879,7 @@ export function buildApp(backgroundJobTtlMaxMs: config.backgroundJobTtlMaxMs,...(config.signingSecret ? { signingSecret: config.signingSecret } : {}),...(config.capabilitySecret ? { capabilitySecret: config.capabilitySecret } : {}),+ capabilityTokenCompression: config.capabilityTokenCompression,...(config.apiBaseUrl ? { apiBaseUrl: config.apiBaseUrl } : {}),...(config.publicWebUrl ? { publicWebUrl: config.publicWebUrl } : {}),...(config.publicUrl ? { webhookPublicUrl: config.publicUrl } : {}),@@ -2767,6 +2771,7 @@ export function serverDeps(allowUnauthenticatedCore: config.allowUnauthenticatedCore,...(config.signingSecret ? { signingSecret: config.signingSecret } : {}),...(config.capabilitySecret ? { capabilitySecret: config.capabilitySecret } : {}),+ capabilityTokenCompression: config.capabilityTokenCompression,...(config.portalIdentitySecret ? { portalIdentitySecret: config.portalIdentitySecret } : {}),...(config.requireSignedPortalIdentity ? { requireSignedPortalIdentity: true } : {}),...(built.replayDedupe ? { replayDedupe: built.replayDedupe } : {}),diff --git a/test/admin-agent-capability.test.ts b/test/admin-agent-capability.test.tsindex 5e5280175..3c68e4315 100644--- a/test/admin-agent-capability.test.ts+++ b/test/admin-agent-capability.test.ts@@ -19,6 +19,7 @@ import {EGRESS_PROXY_AUD,} from "../src/auth/capability-token.ts";import { testConfig } from "./support/test-config.ts";+import { mintSignedPayload } from "../src/auth/signed-token.ts";const SECRET = "agent-admin-test-secret".repeat(3);const ORG = scopeId("org", "default-org");@@ -106,6 +107,56 @@ test("an org admin's capability token can read and rewrite a scope's notebook vi}});+test("a large channel's capability passes HTTP parsing and retains admin authorization", async () => {+ const s = start();+ try {+ const members = Array.from({ length: 120 }, (_, i) => ({+ id: `channel-member-${i}@example.test`,+ type: "internal" as const,+ displayName: `Channel Member ${i}`,+ teamIds: ["engineering"],+ }));+ const claims = {+ actorId: "admin-alice",+ scopeId: "channel:C1",+ aud: CONTROL_PLANE_AUD,+ liveActor: true,+ liveAuthor: true,+ members,+ keychainMembers: members,+ exp: Date.now() + CAPABILITY_TTL_MS,+ };+ const url = `${s.base}/v1/admin/memory?scope=${encodeURIComponent(ORG)}`;+ const legacy = await mintSignedPayload({ orgId: "default-org", ...claims }, SECRET);+ const rejected = await fetch(url, { headers: { "x-agent-capability": legacy } });+ assert.equal(rejected.status, 431);+ await rejected.text();+ const token = await mintCapabilityToken(claims, SECRET, true);+ const response = await fetch(url, {+ method: "PUT",+ headers: { "x-agent-capability": token, "content-type": "application/json" },+ body: JSON.stringify({ content: "# Memory\n\n- Large channel standing rule." }),+ });+ assert.equal(response.status, 200);+ await response.text();+ const read = await fetch(url, { headers: { "x-agent-capability": token } });+ assert.equal(read.status, 200);+ assert.match(((await read.json()) as { content: string }).content, /Large channel standing rule/);+ const denied = await fetch(url, {+ method: "PUT",+ headers: {+ "x-agent-capability": await mintCapabilityToken({ ...claims, actorId: "U1" }, SECRET, true),+ "content-type": "application/json",+ },+ body: JSON.stringify({ content: "unauthorized overwrite" }),+ });+ assert.equal(denied.status, 403);+ await denied.text();+ } finally {+ await s.close();+ }+});+test("whoami answers an agent capability token for admins and non-admins alike", async () => {const s = start();try {diff --git a/test/capability-token.test.ts b/test/capability-token.test.tsindex 1c3f1e100..7086bc018 100644--- a/test/capability-token.test.ts+++ b/test/capability-token.test.ts@@ -1,5 +1,8 @@import { test } from "node:test";import assert from "node:assert/strict";+import { createHash } from "node:crypto";+import { deflateRawSync } from "node:zlib";+import { mintSignedPayload } from "../src/auth/signed-token.ts";import {BLOB_TRANSFER_AUD,CAPABILITY_TTL_MS,@@ -18,6 +21,56 @@ const claims = (over: Partial<CapabilityClaims> = {}): CapabilityClaims => ({...over,});+test("large room capabilities fit an 8 KiB header without losing authorization claims", async () => {+ const members = Array.from({ length: 120 }, (_, i) => ({+ id: `${createHash("sha256").update(String(i)).digest("hex").slice(0, 16)}@example.test`,+ type: i === 119 ? ("guest" as const) : ("internal" as const),+ displayName: `Member ${i}`,+ teamIds: ["engineering", `team-${i % 4}`],+ }));+ const c = claims({ members, keychainMembers: members.filter((p) => p.type === "internal"), grants: ["read"] });+ const value = { orgId: "default-org", ...c };+ const legacy = await mintSignedPayload(value, SECRET);+ assert.ok(Buffer.byteLength(legacy) > 16 * 1024);+ assert.equal(await mintCapabilityToken(c, SECRET), legacy);+ assert.equal(await mintCapabilityToken(c, SECRET, false), legacy);+ const token = await mintCapabilityToken(c, SECRET, true);+ assert.ok(Buffer.byteLength(`x-agent-capability: ${token}\r\n`) < 8 * 1024);+ assert.deepEqual(await verifyCapabilityToken(token, SECRET), value);+ assert.deepEqual(await verifyCapabilityToken(legacy, SECRET), value);+ assert.deepEqual(await verifyCapabilityToken(token, ["rotated-secret", SECRET]), value);+ assert.equal(await verifyCapabilityToken(token, "wrong-secret"), null);+ assert.equal(await verifyCapabilityToken(token, SECRET, c.exp), null);+ const [header, payload, signature] = token.split(".");+ const altered = Buffer.from(signature!, "base64url");+ altered[0] = altered[0]! ^ 1;+ assert.equal(await verifyCapabilityToken(`${header}.${payload}.${altered.toString("base64url")}`, SECRET), null);+});++test("compressed capability envelopes reject malformed and oversized claims", async () => {+ for (const value of [+ { encoding: "unknown", claims: "e30" },+ { encoding: "deflate-raw", claims: 42 },+ { encoding: "deflate-raw", claims: "not-compressed" },+ { encoding: "deflate-raw", claims: deflateRawSync("not-json").toString("base64url") },+ { encoding: "deflate-raw", claims: deflateRawSync("null").toString("base64url") },+ { encoding: "deflate-raw", claims: deflateRawSync("x".repeat(1024 * 1024 + 1)).toString("base64url") },+ ]) {+ assert.equal(await verifyCapabilityToken(await mintSignedPayload(value, SECRET), SECRET), null);+ }+ await assert.rejects(mintCapabilityToken(claims({ threadRef: "x".repeat(1024 * 1024) }), SECRET), /size limit/);+ for (const invalid of [{ timezone: "not-a-zone" }, { grants: [1] }, { runAttempt: 0 }]) {+ const token = await mintSignedPayload(+ {+ encoding: "deflate-raw",+ claims: deflateRawSync(JSON.stringify(claims(invalid as Partial<CapabilityClaims>))).toString("base64url"),+ },+ SECRET,+ );+ assert.equal(await verifyCapabilityToken(token, SECRET), null);+ }+});+test("mint → verify round-trips the claims", async () => {const c = claims();const got = await verifyCapabilityToken(await mintCapabilityToken(c, SECRET), SECRET);diff --git a/test/config.test.ts b/test/config.test.tsindex a560af84e..ccc45bfe7 100644--- a/test/config.test.ts+++ b/test/config.test.ts@@ -21,6 +21,13 @@ const productionEnv = {SANDBOX_BACKEND: "local",} as const;+test("capability compression is explicitly enabled after verifier rollout", () => {+ assert.equal(loadConfig({}).capabilityTokenCompression, false);+ assert.equal(loadConfig({ CAPABILITY_TOKEN_COMPRESSION: "0" }).capabilityTokenCompression, false);+ assert.equal(loadConfig({ CAPABILITY_TOKEN_COMPRESSION: "1" }).capabilityTokenCompression, true);+ assert.throws(() => loadConfig({ CAPABILITY_TOKEN_COMPRESSION: "invalid" }), /CAPABILITY_TOKEN_COMPRESSION/);+});+test("ORG_BRAND_* parses into a validated branding default", () => {assert.equal(loadConfig({}).brandingDefault, undefined);assert.deepEqual(diff --git a/test/file-upload-client.test.ts b/test/file-upload-client.test.tsindex e11295eef..6c5b7d298 100644--- a/test/file-upload-client.test.ts+++ b/test/file-upload-client.test.ts@@ -6,6 +6,8 @@ import { mkdtemp, writeFile, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { fileURLToPath } from "node:url";+import { deflateRawSync } from "node:zlib";+import { mintSignedPayload } from "../src/auth/signed-token.ts";test("publisher resumes an existing transfer after new uploads are disabled", async () => {const directory = await mkdtemp(join(tmpdir(), "qm-publisher-"));@@ -49,6 +51,8 @@ test("publisher resumes an existing transfer after new uploads are disabled", asorigin = `http://127.0.0.1:${address.port}`;const source = join(directory, "empty.txt");await writeFile(source, "");+ let token =+ Buffer.from(JSON.stringify({ actorId: "user", scopeId: "personal:user" })).toString("base64url") + ".signature";const run = () =>new Promise<string>((resolve, reject) => {const child = spawn(@@ -58,9 +62,7 @@ test("publisher resumes an existing transfer after new uploads are disabled", asenv: {...process.env,AGENT_API_URL: origin,- AGENT_API_TOKEN:- Buffer.from(JSON.stringify({ actorId: "user", scopeId: "personal:user" })).toString("base64url") +- ".signature",+ AGENT_API_TOKEN: token,},},);@@ -77,11 +79,34 @@ test("publisher resumes an existing transfer after new uploads are disabled", as});try {assert.equal(JSON.parse(await run()).file.id, "published");+ token = await mintSignedPayload(+ {+ encoding: "deflate-raw",+ claims: deflateRawSync(JSON.stringify({ actorId: "user", scopeId: "personal:user" })).toString("base64url"),+ },+ "upload-test-secret",+ );enabled = false;complete = false;assert.equal(JSON.parse(await run()).file.id, "published");assert.equal(begins, 1);assert.equal(puts, 1);+ token = await mintSignedPayload(+ {+ encoding: "deflate-raw",+ claims: deflateRawSync(JSON.stringify({ actorId: "other", scopeId: "personal:other" })).toString("base64url"),+ },+ "upload-test-secret",+ );+ await assert.rejects(run(), /destination changed/);+ token = await mintSignedPayload(+ {+ encoding: "deflate-raw",+ claims: deflateRawSync("x".repeat(1024 * 1024 + 1)).toString("base64url"),+ },+ "upload-test-secret",+ );+ await assert.rejects(run(), /oversized capability/);} finally {await new Promise<void>((resolve) => server.close(() => resolve()));await rm(directory, { recursive: true, force: true });diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.tsindex 8abb0454b..dae688bca 100644--- a/test/orchestrator.test.ts+++ b/test/orchestrator.test.ts@@ -494,6 +494,52 @@ test("a per-turn egress-proxy token is minted and passed to provision, carryingassert.deepEqual(captured!.egress, { allowedHosts: [], deniedHosts: [] });});+test("large channel turns apply the compression rollout setting to every sandbox token", async () => {+ for (const capabilityTokenCompression of [false, true]) {+ const { app, sandbox } = buildApp(+ testConfig({+ dataDir: mkdtempSync(join(tmpdir(), "ap-")),+ signingSecret: "test-secret",+ apiBaseUrl: "https://core.example.com",+ capabilityTokenCompression,+ }),+ );+ let captured: ProvisionOptions | undefined;+ const provision = sandbox.provision.bind(sandbox);+ sandbox.provision = (layers, opts) => {+ captured = opts;+ return provision(layers, opts);+ };+ const members = Array.from({ length: 120 }, (_, i) => ({+ externalId: i === 0 ? "U1" : `U${i + 1}-compression-fixture`,+ }));+ const result = await app.turn(+ channel("!run echo compact", {+ conversation: {+ kind: "channel",+ threadRef: "ch:C1:compact",+ channelRef: "C1",+ audience: members,+ publishMembers: members,+ },+ }),+ );+ assert.equal(result.status, "ok");+ for (const token of [+ captured?.env?.AGENT_API_TOKEN,+ captured?.env?.AGENT_OAUTH_CONSENT_TOKEN,+ captured?.egressToken,+ ]) {+ assert.ok(token);+ const payload = JSON.parse(Buffer.from(token.split(".")[1]!, "base64url").toString("utf8"));+ assert.equal(payload.encoding, capabilityTokenCompression ? "deflate-raw" : undefined);+ if (capabilityTokenCompression) assert.ok(token.length < 8 * 1024);+ const verified = await verifyCapabilityToken(token, TEST_CAPABILITY_SECRET);+ assert.equal(verified?.members?.length, 120);+ }+ }+});+test("live bot attestation reaches control, OAuth, and egress capabilities", async () => {const config = testConfig({dataDir: mkdtempSync(join(tmpdir(), "ap-")),