@tokensize/agent-client 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../src/local/discovery.ts","../src/local/config.ts","../src/local/process.ts","../src/local/allowance.ts","../src/local/execution.ts"],"sourcesContent":["import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { access, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { createServer } from \"node:http\";\nimport path from \"node:path\";\nimport { execFile } from \"node:child_process\";\nimport {\n\tAGENT_ROUTER_SCHEMA_VERSION,\n\tagentRouteResponseSchema,\n\tfeaturizeAgentTask,\n\trunEventSchema,\n\ttype AgentRouteRequest,\n\ttype AgentRouteResponse,\n\ttype HarnessId,\n\ttype PermissionProfile,\n\ttype RunEvent,\n\ttype TaskRole,\n\ttype RoutingObjective,\n} from \"@tokensize/agent-router\";\nimport {\n\tallowanceReport,\n\tallowanceScopesForHarness,\n\tallowances,\n\tapplyAllowances,\n\tflattenModels,\n\thome as cliHome,\n\tinstallationId,\n\treadApiKey,\n\treadLocalPolicy,\n\trootAllowance,\n\tsaveApiKey,\n\tdiscoverHarnessesCached,\n\texecutionArgs,\n\ttype DiscoveryCacheMetadata,\n\ttype HarnessDiscovery,\n\ttype LocalPolicy,\n\trun,\n} from \"./local\";\n\nconst CLIENT_VERSION = \"0.3.0-beta.0\";\nconst MAX_OUTPUT_BYTES = 200_000;\n\nexport interface TokenSizeClientOptions {\n\tapiUrl?: string;\n\tclientSurface?: AgentRouteRequest[\"client\"][\"surface\"];\n\tclientVersion?: string;\n\trootHarness?: HarnessId;\n\trootActive?: boolean;\n\trootQualityPrior?: number;\n\tmaxDelegationDepth?: number;\n\tfetchImpl?: typeof fetch;\n\topenBrowser?: (url: string) => void;\n}\n\nexport interface RouteOptions {\n\ttask: string;\n\trole?: TaskRole;\n\tpermission?: PermissionProfile;\n\tobjective?: RoutingObjective;\n\tsharePrompt?: boolean;\n\trefresh?: boolean;\n\ttimeoutMs?: number;\n}\n\nexport interface RoutePreview {\n\treceiptId: string;\n\t/** Present when the service created a Run document for this route. */\n\trunId?: string;\n\troute: Omit<AgentRouteResponse, \"feedbackToken\">;\n\tcache: { discovery: DiscoveryCacheMetadata; allowance: Awaited<ReturnType<typeof allowances>>[\"cache\"] };\n\tharnesses: Array<ReturnType<typeof summarizeHarness>>;\n}\n\n/** Shape of a Run document as served by GET /v1/runs/:id. */\nexport interface RunDocumentView {\n\trunId: string;\n\tstatus: string;\n\tevents: Array<{ seq: number; at: string; actor: string; type: string; data: Record<string, unknown> }>;\n\tdecision: { plan: { targetId: string | null; workflow: string }; reasonCodes: string[]; confidence: number };\n\tapprovals: Array<{ kind: string; state: string; surface?: string; at: string }>;\n\tcreatedAt: string;\n\texpiresAt: string;\n\t[key: string]: unknown;\n}\n\nexport interface StatusResult {\n\tservice: { url: string; authenticated: boolean; catalog?: unknown };\n\tinstallationId: string;\n\tcache: { discovery: DiscoveryCacheMetadata; allowance: Awaited<ReturnType<typeof allowances>>[\"cache\"] };\n\tharnesses: Array<ReturnType<typeof summarizeHarness>>;\n}\n\ninterface StoredReceipt {\n\treceiptId: string;\n\ttaskDigest: string;\n\tinstallationId: string;\n\tsurface: AgentRouteRequest[\"client\"][\"surface\"];\n\tcreatedAt: string;\n\troute: AgentRouteResponse;\n\t/** The Run document this receipt is the local pointer to. */\n\trunId?: string;\n\tmac: string;\n}\n\nfunction apiUrl(value?: string): string {\n\treturn (value ?? process.env.TOKENSIZE_API_URL ?? \"https://api.tokensize.dev\").replace(/\\/$/, \"\");\n}\n\nfunction home(): string { return cliHome(); }\n\nfunction digest(value: string): string { return createHash(\"sha256\").update(value.trim().replace(/\\s+/g, \" \")).digest(\"hex\"); }\n\nfunction receiptFile(receiptId: string): string { return path.join(home(), `receipt-${receiptId}.json`); }\nfunction receiptKeyFile(): string { return path.join(home(), \"receipt-key\"); }\n\nasync function receiptKey(): Promise<Buffer> {\n\ttry {\n\t\tconst value = await readFile(receiptKeyFile());\n\t\tif (value.length >= 32) return value;\n\t} catch { /* first use */ }\n\tconst value = randomBytes(32);\n\tawait mkdir(home(), { recursive: true, mode: 0o700 });\n\tawait writeFile(receiptKeyFile(), value, { mode: 0o600 });\n\treturn value;\n}\n\nfunction receiptMac(value: Omit<StoredReceipt, \"mac\">, key: Buffer): string {\n\treturn createHmac(\"sha256\", key).update(JSON.stringify(value)).digest(\"base64url\");\n}\n\nasync function saveReceipt(route: AgentRouteResponse, task: string, surface: AgentRouteRequest[\"client\"][\"surface\"], runId?: string): Promise<string> {\n\tconst receiptId = randomUUID();\n\tconst value: Omit<StoredReceipt, \"mac\"> = {\n\t\treceiptId,\n\t\ttaskDigest: digest(task),\n\t\tinstallationId: await installationId(),\n\t\tsurface,\n\t\tcreatedAt: new Date().toISOString(),\n\t\troute,\n\t\t...(runId ? { runId } : {}),\n\t};\n\tconst stored: StoredReceipt = { ...value, mac: receiptMac(value, await receiptKey()) };\n\tconst file = receiptFile(receiptId);\n\tconst temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\n\tawait mkdir(home(), { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify(stored, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n\treturn receiptId;\n}\n\nasync function readReceipt(receiptId: string, task?: string): Promise<StoredReceipt> {\n\tif (!/^[0-9a-f-]{36}$/i.test(receiptId)) throw new Error(\"invalid route receipt\");\n\tconst value = JSON.parse(await readFile(receiptFile(receiptId), \"utf8\")) as StoredReceipt;\n\tif (value.receiptId !== receiptId || (task !== undefined && value.taskDigest !== digest(task)) || Date.parse(value.route.expiresAt) <= Date.now()) throw new Error(\"route receipt is invalid, expired, or bound to a different task\");\n\tconst { mac, ...unsigned } = value;\n\tconst expected = receiptMac(unsigned, await receiptKey());\n\tconst actualBytes = Buffer.from(mac ?? \"\", \"base64url\");\n\tconst expectedBytes = Buffer.from(expected, \"base64url\");\n\tif (actualBytes.length !== expectedBytes.length || !timingSafeEqual(actualBytes, expectedBytes)) throw new Error(\"route receipt integrity check failed\");\n\treturn value;\n}\n\nfunction summarizeHarness(item: HarnessDiscovery, verbose = false) {\n\tconst summary = {\n\t\tharness: item.harness,\n\t\tinstalled: item.installed,\n\t\tauthenticated: item.authenticated,\n\t\tversion: item.version,\n\t\tmodelCount: item.models.length,\n\t\tallowanceScopes: allowanceScopesForHarness(item),\n\t\twarnings: item.warnings,\n\t};\n\treturn verbose\n\t\t? {\n\t\t\t\t...summary,\n\t\t\t\tmodels: item.models.map(({ id, harness, nativeModelId, displayName, readiness, authMode, productUseApproved, capabilities, identityProof, qualityPrior, tokenEfficiencyPrior, latencyPrior, allowance }) => ({\n\t\t\t\t\tid, harness, nativeModelId, displayName, readiness, authMode, productUseApproved, capabilities, identityProof, qualityPrior, tokenEfficiencyPrior, latencyPrior, allowance,\n\t\t\t\t})),\n\t\t\t}\n\t\t: summary;\n}\n\nfunction parseRootHarness(value: string | undefined): HarnessId {\n\tif ([\"codex\", \"claude\", \"copilot\", \"cursor\", \"opencode\", \"custom\"].includes(value ?? \"\")) return value as HarnessId;\n\treturn \"codex\";\n}\n\nfunction parseRole(value: TaskRole | undefined): TaskRole { return value ?? \"inspect\"; }\nfunction parsePermission(value: PermissionProfile | undefined): PermissionProfile { return value ?? \"inspect\"; }\n\nexport class TokenSizeClient {\n\tprivate readonly options: Required<Pick<TokenSizeClientOptions, \"clientSurface\" | \"clientVersion\">> & TokenSizeClientOptions;\n\n\tconstructor(options: TokenSizeClientOptions = {}) {\n\t\tthis.options = {\n\t\t\t...options,\n\t\t\tclientSurface: options.clientSurface ?? \"cli\",\n\t\t\tclientVersion: options.clientVersion ?? CLIENT_VERSION,\n\t\t};\n\t}\n\n\t/**\n\t * Resolve routing defaults: explicit constructor options win, then\n\t * environment variables (CI overrides), then the local policy document at\n\t * ~/.tokensize/policy.json, then fail-closed defaults.\n\t */\n\tprivate async resolvedDefaults(): Promise<{\n\t\tpolicy: LocalPolicy;\n\t\trootHarness: HarnessId;\n\t\trootActive: boolean;\n\t\trootQualityPrior: number;\n\t\tmaxDelegationDepth: number;\n\t}> {\n\t\tconst policy = await readLocalPolicy();\n\t\treturn {\n\t\t\tpolicy,\n\t\t\trootHarness: this.options.rootHarness ?? parseRootHarness(process.env.TOKENSIZE_ROOT_HARNESS ?? policy.rootHarness),\n\t\t\trootActive: this.options.rootActive ?? process.env.TOKENSIZE_ROOT_ACTIVE === \"1\",\n\t\t\trootQualityPrior: this.options.rootQualityPrior ?? Number(process.env.TOKENSIZE_ROOT_QUALITY_PRIOR ?? policy.rootQualityPrior ?? 0.82),\n\t\t\tmaxDelegationDepth: this.options.maxDelegationDepth ?? Number(process.env.TOKENSIZE_MAX_DELEGATION_DEPTH ?? policy.maxDelegationDepth ?? 1),\n\t\t};\n\t}\n\n\tprivate async key(required = true): Promise<string | null> {\n\t\tconst value = process.env.TOKENSIZE_API_KEY ?? await readApiKey();\n\t\tif (!value && required) throw new Error(\"TokenSize API key is missing; use tokensize_connect or tokensize auth login\");\n\t\treturn value;\n\t}\n\n\tprivate async api<T>(pathname: string, options: RequestInit = {}): Promise<T> {\n\t\tconst key = await this.key();\n\t\tconst fetcher = this.options.fetchImpl ?? fetch;\n\t\tconst response = await fetcher(`${apiUrl(this.options.apiUrl)}${pathname}`, {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\tauthorization: `Bearer ${key}`,\n\t\t\t\t...(options.body ? { \"content-type\": \"application/json\" } : {}),\n\t\t\t\t...options.headers,\n\t\t\t},\n\t\t});\n\t\tconst text = await response.text();\n\t\tlet body: unknown;\n\t\ttry { body = JSON.parse(text); } catch { body = { message: text.slice(0, 500) }; }\n\t\tif (!response.ok) {\n\t\t\tconst record = body as { error?: { message?: string }; message?: string };\n\t\t\tthrow new Error(`service returned ${response.status}: ${record.error?.message ?? record.message ?? \"request failed\"}`);\n\t\t}\n\t\treturn body as T;\n\t}\n\n\tasync status(options: { refresh?: boolean; verbose?: boolean } = {}): Promise<StatusResult> {\n\t\tconst [key, discovered] = await Promise.all([\n\t\t\tthis.key(false),\n\t\t\tdiscoverHarnessesCached({ forceRefresh: options.refresh, reason: options.refresh ? \"manual\" : undefined }),\n\t\t]);\n\t\tconst allowanceSnapshot = await allowances(discovered.harnesses, options.refresh);\n\t\tconst available = applyAllowances(discovered.harnesses, allowanceSnapshot);\n\t\tconst catalog = key ? await this.api(\"/v1/agent-catalog\").catch((error) => ({ warning: error instanceof Error ? error.message : String(error) })) : undefined;\n\t\treturn {\n\t\t\tservice: { url: apiUrl(this.options.apiUrl), authenticated: Boolean(key), ...(catalog === undefined ? {} : { catalog }) },\n\t\t\tinstallationId: await installationId(),\n\t\t\tcache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache },\n\t\t\tharnesses: available.map((item) => summarizeHarness(item, options.verbose === true)),\n\t\t};\n\t}\n\n\tasync connect(surface: \"codex-plugin\" | \"opencode-plugin\" = this.options.clientSurface as \"codex-plugin\" | \"opencode-plugin\"): Promise<void> {\n\t\tconst state = randomUUID();\n\t\tlet completed = false;\n\t\tconst server = createServer((request, response) => {\n\t\t\tif (request.method === \"OPTIONS\" && request.url === `/callback/${state}`) {\n\t\t\t\tresponse.writeHead(204, { \"access-control-allow-origin\": \"https://tokensize.dev\", \"access-control-allow-methods\": \"POST\", \"access-control-allow-headers\": \"content-type\" }).end();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (request.method !== \"POST\" || request.url !== `/callback/${state}`) { response.writeHead(404).end(); return; }\n\t\t\tlet body = \"\";\n\t\t\trequest.on(\"data\", (chunk) => { if (body.length < 16_000) body += chunk; });\n\t\t\trequest.on(\"end\", async () => {\n\t\t\t\ttry {\n\t\t\t\t\tconst payload = JSON.parse(body) as { state?: string; apiKey?: string };\n\t\t\t\t\tif (payload.state !== state || typeof payload.apiKey !== \"string\" || payload.apiKey.length < 20 || /\\s/.test(payload.apiKey)) throw new Error(\"invalid callback\");\n\t\t\t\t\tawait saveApiKey(payload.apiKey);\n\t\t\t\t\tcompleted = true;\n\t\t\t\t\tresponse.writeHead(200, { \"content-type\": \"text/plain\", \"access-control-allow-origin\": \"https://tokensize.dev\" }).end(\"TokenSize connected. You can close this window.\\n\");\n\t\t\t\t\tsetTimeout(() => server.close(), 100);\n\t\t\t\t} catch { response.writeHead(400, { \"access-control-allow-origin\": \"https://tokensize.dev\" }).end(\"Invalid TokenSize callback.\\n\"); }\n\t\t\t});\n\t\t});\n\t\tawait new Promise<void>((resolve) => server.listen(0, \"127.0.0.1\", resolve));\n\t\tconst address = server.address();\n\t\tif (!address || typeof address === \"string\") throw new Error(\"could not start local authorization callback\");\n\t\tconst callback = `http://127.0.0.1:${address.port}/callback/${state}`;\n\t\tconst url = `https://tokensize.dev/authorize?callback=${encodeURIComponent(callback)}&state=${encodeURIComponent(state)}&surface=${encodeURIComponent(surface)}`;\n\t\tif (this.options.openBrowser) this.options.openBrowser(url);\n\t\telse execFile(process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\", process.platform === \"win32\" ? [\"/c\", \"start\", url] : [url]);\n\t\tconst timeout = setTimeout(() => server.close(), 10 * 60 * 1_000);\n\t\tawait new Promise<void>((resolve) => server.on(\"close\", resolve));\n\t\tclearTimeout(timeout);\n\t\tif (!completed) throw new Error(\"browser authorization timed out or was cancelled\");\n\t}\n\n\tprivate async prepare(options: RouteOptions): Promise<{ body: AgentRouteRequest; discovery: HarnessDiscovery[]; cache: RoutePreview[\"cache\"] }> {\n\t\tconst defaults = await this.resolvedDefaults();\n\t\tconst role = parseRole(options.role);\n\t\tconst permission = options.permission ?? defaults.policy.permissionCeiling ?? \"inspect\";\n\t\t// The policy document can approve subscription harnesses; the env var\n\t\t// remains an explicit override for CI and one-off shells.\n\t\tif (!process.env.TOKENSIZE_ALLOW_SUBSCRIPTION_HARNESSES && defaults.policy.subscriptionHarnesses?.length) {\n\t\t\tprocess.env.TOKENSIZE_ALLOW_SUBSCRIPTION_HARNESSES = defaults.policy.subscriptionHarnesses.join(\",\");\n\t\t}\n\t\tconst discovered = await discoverHarnessesCached({ forceRefresh: options.refresh, reason: options.refresh ? \"manual\" : undefined });\n\t\tconst allowanceSnapshot = await allowances(discovered.harnesses, options.refresh);\n\t\tconst discovery = applyAllowances(discovered.harnesses, allowanceSnapshot);\n\t\tconst delegationDepth = Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0);\n\t\tconst body: AgentRouteRequest = {\n\t\t\tschemaVersion: AGENT_ROUTER_SCHEMA_VERSION,\n\t\t\tclient: { surface: this.options.clientSurface, version: this.options.clientVersion },\n\t\t\trequestId: randomUUID(),\n\t\t\tinstallationId: await installationId(),\n\t\t\trouterMode: options.sharePrompt ? \"prompt-assisted\" : \"metadata-only\",\n\t\t\ttask: featurizeAgentTask({ task: options.task, role, permissionProfile: permission }),\n\t\t\t...(options.sharePrompt ? { prompt: options.task } : {}),\n\t\t\tcandidates: flattenModels(discovery),\n\t\t\troot: { harness: defaults.rootHarness, active: defaults.rootActive, qualityPrior: defaults.rootQualityPrior, allowance: rootAllowance(defaults.rootHarness, allowanceSnapshot) },\n\t\t\tpolicy: { objective: options.objective ?? defaults.policy.objective ?? \"balanced\", maxDelegationDepth: defaults.maxDelegationDepth, delegationDepth, permissionCeiling: permission, wallTimeBudgetMs: options.timeoutMs ?? 900_000 },\n\t\t};\n\t\treturn { body, discovery, cache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache } };\n\t}\n\n\tasync route(options: RouteOptions): Promise<RoutePreview> {\n\t\tif (!options.task.trim()) throw new Error(\"task is required\");\n\t\tconst prepared = await this.prepare(options);\n\t\tconst response = await this.api<unknown>(\"/v1/agent-routes\", { method: \"POST\", body: JSON.stringify(prepared.body) });\n\t\tconst runId = typeof (response as { runId?: unknown }).runId === \"string\" ? (response as { runId: string }).runId : undefined;\n\t\tconst route = agentRouteResponseSchema.parse(response);\n\t\tconst receiptId = await saveReceipt(route, options.task, this.options.clientSurface, runId);\n\t\tconst { feedbackToken: _feedbackToken, ...safeRoute } = route;\n\t\treturn { receiptId, ...(runId ? { runId } : {}), route: safeRoute, cache: prepared.cache, harnesses: prepared.discovery.map((item) => summarizeHarness(item)) };\n\t}\n\n\t/** List recent Run documents for this tenant. */\n\tasync runs(options: { limit?: number } = {}): Promise<unknown> {\n\t\treturn this.api(`/v1/runs?limit=${Math.min(Math.max(options.limit ?? 25, 1), 100)}`);\n\t}\n\n\t/** Read one Run document — the authoritative story of a delegation. */\n\tasync runDocument(runId: string): Promise<RunDocumentView> {\n\t\tif (!/^[0-9a-f-]{36}$/i.test(runId)) throw new Error(\"invalid run id\");\n\t\treturn this.api<RunDocumentView>(`/v1/runs/${runId}`);\n\t}\n\n\t/** Append one event to a Run. Execution-class events need the receipt token. */\n\tasync appendRunEvent(runId: string, event: Omit<RunEvent, \"seq\"> & { seq?: number }, options: { receiptToken?: string } = {}): Promise<unknown> {\n\t\tconst candidate = runEventSchema.parse({ seq: event.seq ?? 0, ...event });\n\t\treturn this.api(`/v1/runs/${runId}/events`, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tevent: candidate,\n\t\t\t\tautoSeq: event.seq === undefined,\n\t\t\t\t...(options.receiptToken ? { receiptToken: options.receiptToken } : {}),\n\t\t\t}),\n\t\t});\n\t}\n\n\t/** The human hand at the terminal: grant a pending approval on a Run. */\n\tasync approve(runId: string, kind: \"subscription-use\" | \"execute\" | \"share-prompt\" = \"subscription-use\"): Promise<unknown> {\n\t\treturn this.appendRunEvent(runId, {\n\t\t\tat: new Date().toISOString(),\n\t\t\tactor: \"human\",\n\t\t\ttype: \"approval-granted\",\n\t\t\tdata: { kind, grantedBy: \"local-cli\" },\n\t\t} as Omit<RunEvent, \"seq\">);\n\t}\n\n\t/** Cancel a Run from any surface that can authenticate. */\n\tasync cancel(runId: string): Promise<unknown> {\n\t\treturn this.appendRunEvent(runId, {\n\t\t\tat: new Date().toISOString(),\n\t\t\tactor: \"human\",\n\t\t\ttype: \"cancelled\",\n\t\t\tdata: { by: \"human\" },\n\t\t} as Omit<RunEvent, \"seq\">);\n\t}\n\n\tasync execute(options: { receiptId: string; task: string; cwd?: string }): Promise<unknown> {\n\t\tconst stored = await readReceipt(options.receiptId, options.task);\n\t\tconst route = stored.route;\n\t\tif (this.options.clientSurface === \"opencode-plugin\" && route.plan.permissionProfile !== \"inspect\") throw new Error(\"OpenCode execution is inspect-only in this release\");\n\t\tif (!route.plan.targetId) throw new Error(`no local target selected (${route.reasonCodes.join(\", \")})`);\n\t\tif (route.plan.permissionProfile === \"network\") throw new Error(\"network delegation is not supported\");\n\t\tconst discovered = await discoverHarnessesCached();\n\t\tconst snapshot = await allowances(discovered.harnesses);\n\t\tconst available = applyAllowances(discovered.harnesses, snapshot);\n\t\tconst target = available.flatMap((item) => item.models.map((model) => ({ item, model }))).find(({ model }) => model.id === route.plan.targetId);\n\t\tif (!target?.item.executable || !target.item.authenticated) throw new Error(\"selected target is no longer available; local discovery cache refreshed\");\n\t\ttry { await access(target.item.executable); } catch { throw new Error(\"selected harness executable no longer exists; local discovery cache refreshed\"); }\n\t\tif (![\"codex\", \"claude\", \"cursor\", \"opencode\"].includes(target.model.harness)) throw new Error(`${target.model.harness} execution is unavailable`);\n\t\tif ([\"cursor\", \"opencode\"].includes(target.model.harness) && route.plan.permissionProfile !== \"inspect\") throw new Error(`${target.model.harness} execution is inspect-only`);\n\t\tconst cwd = options.cwd ?? process.cwd();\n\t\tconst started = Date.now();\n\t\t// The Run document is the authority for what happened; stream lifecycle\n\t\t// events into it best-effort so the human hand can watch live. Local\n\t\t// execution never blocks on hosted availability.\n\t\tawait this.recordRunEvent(stored, {\n\t\t\tat: new Date().toISOString(),\n\t\t\tactor: \"delegate\",\n\t\t\ttype: \"execution-started\",\n\t\t\tdata: { targetId: target.model.id, permissionProfile: route.plan.permissionProfile, worktree: false },\n\t\t});\n\t\tconst result = await run(target.item.executable, executionArgs(target.model.harness, target.model.nativeModelId, route.plan.permissionProfile, cwd), {\n\t\t\tcwd,\n\t\t\tinput: options.task,\n\t\t\ttimeoutMs: route.plan.maxWallMs,\n\t\t\tenv: { ...process.env, TOKENSIZE_ROOT_HARNESS: target.model.harness, TOKENSIZE_ROOT_ACTIVE: \"1\", TOKENSIZE_DELEGATION_DEPTH: String(Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0) + 1) },\n\t\t});\n\t\tconst elapsedMs = Date.now() - started;\n\t\tawait this.recordRunEvent(stored, {\n\t\t\tat: new Date().toISOString(),\n\t\t\tactor: \"delegate\",\n\t\t\ttype: \"execution-finished\",\n\t\t\tdata: {\n\t\t\t\toutcome: result.timedOut ? \"timeout\" : result.code === 0 ? \"success\" : \"failure\",\n\t\t\t\t...(result.code === 0 && !result.timedOut ? {} : { failureCode: result.timedOut ? \"EXECUTION_TIMEOUT\" : \"EXECUTION_FAILED\" }),\n\t\t\t\telapsedMs,\n\t\t\t\tusage: { contextTokensEstimated: route.expected.contextTokens, source: \"estimated\" },\n\t\t\t},\n\t\t});\n\t\treturn { target: target.model.id, ...(stored.runId ? { runId: stored.runId } : {}), code: result.code, timedOut: result.timedOut, elapsedMs, stdout: result.stdout.slice(0, MAX_OUTPUT_BYTES), stderr: result.stderr.slice(0, MAX_OUTPUT_BYTES) };\n\t}\n\n\tprivate async recordRunEvent(stored: StoredReceipt, event: Omit<RunEvent, \"seq\">): Promise<void> {\n\t\tif (!stored.runId) return;\n\t\ttry {\n\t\t\tawait this.appendRunEvent(stored.runId, event, { receiptToken: stored.route.feedbackToken });\n\t\t} catch { /* the local receipt keeps working offline; events flush on later commands */ }\n\t}\n\n\tasync feedback(options: { receiptId: string; rating: 1 | 2 | 3 | 4 | 5; modelChoice: \"right\" | \"acceptable\" | \"wrong\"; wouldUseAgain: boolean; task?: string }): Promise<unknown> {\n\t\tconst stored = await readReceipt(options.receiptId, options.task);\n\t\treturn this.api(\"/v1/agent-feedback\", { method: \"POST\", body: JSON.stringify({ schemaVersion: AGENT_ROUTER_SCHEMA_VERSION, routeId: stored.route.routeId, feedbackToken: stored.route.feedbackToken, idempotencyKey: randomUUID(), status: options.modelChoice === \"wrong\" ? \"failed\" : \"verified\", confirmedTargetId: stored.route.plan.targetId, identityConfirmed: true, checksPassed: options.modelChoice === \"right\" ? 1 : 0, checksFailed: options.modelChoice === \"wrong\" ? 1 : 0, retries: 0, usage: { contextTokensEstimated: stored.route.expected.contextTokens, source: \"estimated\" }, timings: { totalMs: 0, routingMs: 0, executionMs: 0, verificationMs: 0 } }) });\n\t}\n}\n\nexport function createTokenSizeClient(options?: TokenSizeClientOptions): TokenSizeClient { return new TokenSizeClient(options); }\n// The local modules (discovery, allowance, config, execution, process) are the\n// single implementation; the CLI and plugin adapters consume them from here.\nexport * from \"./local\";\n","import { access, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport type { AgentModel, HarnessId } from \"@tokensize/agent-router\";\nimport { home } from \"./config\";\nimport { run, terminateProcessTree } from \"./process\";\n\nexport interface HarnessDiscovery { harness: HarnessId; installed: boolean; executable?: string; version?: string; authenticated: boolean; models: AgentModel[]; warnings: string[]; probeTimedOut?: boolean }\nexport interface DiscoveryCacheMetadata {\n\thit: boolean;\n\trefreshed?: boolean;\n\tpersisted?: boolean;\n\treason?: string;\n\tpath?: string;\n\tcreatedAt?: string;\n\texpiresAt?: string;\n\tageMs?: number;\n\twarning?: string;\n}\nexport interface DiscoveryResult { harnesses: HarnessDiscovery[]; cache: DiscoveryCacheMetadata }\nexport interface DiscoveryOptions { forceRefresh?: boolean; reason?: string }\n\nconst DISCOVERY_CACHE_VERSION = 5;\nconst DEFAULT_DISCOVERY_CACHE_TTL_MS = 6 * 60 * 60 * 1_000;\nconst INCOMPLETE_DISCOVERY_CACHE_TTL_MS = 5 * 60 * 1_000;\nconst HARNESS_PROBE_DEADLINE_MS = 12_000;\n\nasync function executable(names: string[]): Promise<string | undefined> {\n\tconst directories = [...new Set([process.env.NVM_BIN, process.env.VOLTA_HOME ? path.join(process.env.VOLTA_HOME, \"bin\") : undefined, path.dirname(process.execPath), ...(process.env.PATH ?? \"\").split(path.delimiter), path.join(os.homedir(), \".local\", \"bin\"), path.join(os.homedir(), \".opencode\", \"bin\")].filter((value): value is string => Boolean(value)))];\n\tfor (const name of names) for (const directory of directories) {\n\t\tconst candidate = path.join(directory, name);\n\t\ttry { await access(candidate); return candidate; } catch { /* continue */ }\n\t}\n}\nfunction subscriptionApproved(harness: string): boolean {\n\treturn (process.env.TOKENSIZE_ALLOW_SUBSCRIPTION_HARNESSES ?? \"\").split(\",\").map((v) => v.trim()).includes(harness);\n}\n\nfunction discoveryCacheFile(): string { return path.join(home(), \"discovery.json\"); }\nfunction discoveryCacheTtlMs(): number {\n\tconst value = Number(process.env.TOKENSIZE_DISCOVERY_CACHE_TTL_MS ?? DEFAULT_DISCOVERY_CACHE_TTL_MS);\n\treturn Number.isFinite(value) && value >= 0 ? value : DEFAULT_DISCOVERY_CACHE_TTL_MS;\n}\nfunction discoveryFingerprint(): string {\n\treturn JSON.stringify({\n\t\tpath: process.env.PATH ?? \"\",\n\t\tnvmBin: process.env.NVM_BIN ?? \"\",\n\t\tvoltaHome: process.env.VOLTA_HOME ?? \"\",\n\t\tclaudeModels: process.env.TOKENSIZE_CLAUDE_MODELS ?? \"\",\n\t\tcopilotModels: process.env.TOKENSIZE_COPILOT_MODELS ?? \"\",\n\t});\n}\nfunction model(harness: HarnessId, id: string, name: string, approved: boolean, authMode: AgentModel[\"authMode\"] = \"subscription\", priors: Partial<Pick<AgentModel, \"qualityPrior\" | \"tokenEfficiencyPrior\" | \"latencyPrior\">> = {}): AgentModel {\n\treturn { id: `${harness}:${id}`, harness, nativeModelId: id, displayName: name, readiness: \"model-listed\", authMode, productUseApproved: approved, capabilities: { tools: true, vision: harness === \"codex\" || harness === \"claude\", structuredOutput: harness === \"codex\" ? \"jsonl\" : \"json\", sessions: \"resume\", permissions: [\"inspect\", \"edit\", \"test\", \"network\"] }, identityProof: \"runtime-reported\", qualityPrior: priors.qualityPrior ?? 0.9, tokenEfficiencyPrior: priors.tokenEfficiencyPrior ?? 0.72, latencyPrior: priors.latencyPrior ?? 0.65 };\n}\n\nasync function codex(): Promise<HarnessDiscovery> {\n\tconst exe = await executable([\"codex\"]);\n\tif (!exe) return { harness: \"codex\", installed: false, authenticated: false, models: [], warnings: [] };\n\tconst [version, auth] = await Promise.all([\n\t\trun(exe, [\"--version\"], { timeoutMs: 5_000, maxBytes: 64_000 }),\n\t\trun(exe, [\"login\", \"status\"], { timeoutMs: 5_000, maxBytes: 64_000 }),\n\t]);\n\tconst child = await import(\"node:child_process\").then(({ spawn }) => spawn(exe, [\"app-server\", \"--stdio\"], {\n\t\tdetached: process.platform !== \"win32\",\n\t\tshell: false,\n\t\tstdio: [\"pipe\", \"pipe\", \"ignore\"],\n\t}));\n\tconst models = await new Promise<AgentModel[]>((resolve) => {\n\t\tlet buffer = \"\", done = false;\n\t\tconst finish = (value: AgentModel[]) => {\n\t\t\tif (done) return;\n\t\t\tdone = true;\n\t\t\tclearTimeout(timer);\n\t\t\tterminateProcessTree(child, \"SIGTERM\");\n\t\t\tresolve(value);\n\t\t};\n\t\tconst timer = setTimeout(() => finish([]), 8_000);\n\t\tchild.once(\"error\", () => finish([]));\n\t\tchild.stdout.on(\"data\", (chunk: Buffer) => {\n\t\t\tif (buffer.length >= 2_000_000) return finish([]);\n\t\t\tbuffer += chunk.toString();\n\t\t\tlet newline: number;\n\t\t\twhile ((newline = buffer.indexOf(\"\\n\")) >= 0) {\n\t\t\t\tconst line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);\n\t\t\t\ttry {\n\t\t\t\t\tconst message = JSON.parse(line) as { id?: number; result?: { data?: Array<{ id: string; displayName?: string }> } };\n\t\t\t\t\tif (message.id === 1) { child.stdin.write(JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/initialized\" }) + \"\\n\"); child.stdin.write(JSON.stringify({ jsonrpc: \"2.0\", id: 2, method: \"model/list\", params: { includeHidden: false, limit: 100 } }) + \"\\n\"); }\n\t\t\t\t\tif (message.id === 2) { const apiKey = Boolean(process.env.OPENAI_API_KEY); finish((message.result?.data ?? []).map((m, index) => model(\"codex\", m.id, m.displayName ?? m.id, apiKey || subscriptionApproved(\"codex\"), apiKey ? \"api-key\" : \"subscription\", { qualityPrior: Math.max(0.82, 0.97 - index * 0.04), tokenEfficiencyPrior: /mini/i.test(m.id) ? 0.94 : Math.min(0.88, 0.76 + index * 0.03), latencyPrior: /mini/i.test(m.id) ? 0.94 : 0.68 }))); }\n\t\t\t\t} catch { /* app-server may emit non-JSON diagnostics */ }\n\t\t\t}\n\t\t});\n\t\tchild.stdin.write(JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"initialize\", params: { clientInfo: { name: \"tokensize\", version: \"0.1.0\" }, capabilities: { experimentalApi: true } } }) + \"\\n\");\n\t});\n\treturn { harness: \"codex\", installed: true, executable: exe, version: version.stdout.trim(), authenticated: auth.code === 0, models, warnings: models.length ? [] : [\"Codex model catalog was unavailable\"] };\n}\n\nasync function generic(harness: HarnessId, names: string[]): Promise<HarnessDiscovery> {\n\tconst exe = await executable(names);\n\tif (!exe) return { harness, installed: false, authenticated: false, models: [], warnings: [] };\n\tconst [version, claudeAuth, help] = await Promise.all([\n\t\trun(exe, [\"--version\"], { timeoutMs: 5_000, maxBytes: 64_000 }),\n\t\tharness === \"claude\" ? run(exe, [\"auth\", \"status\"], { timeoutMs: 8_000, maxBytes: 64_000 }) : Promise.resolve(undefined),\n\t\tharness === \"claude\" ? run(exe, [\"--help\"], { timeoutMs: 5_000, maxBytes: 256_000 }) : Promise.resolve(undefined),\n\t]);\n\tlet authenticated = harness !== \"copilot\";\n\tif (harness === \"claude\") {\n\t\tauthenticated = claudeAuth?.code === 0;\n\t}\n\tif (harness === \"copilot\") authenticated = Boolean(process.env.GH_TOKEN || process.env.GITHUB_TOKEN);\n\tconst cliReported = harness === \"claude\"\n\t\t? [...new Set([...(help?.stdout.match(/'([a-z][a-z0-9.-]+)'/g) ?? []).map((value) => value.slice(1, -1)), ...(help?.stdout.match(/claude-[a-z0-9.-]+/g) ?? [])])].filter((id) => [\"fable\", \"opus\", \"sonnet\"].includes(id) || id.startsWith(\"claude-\"))\n\t\t: [];\n\tconst configured = [...new Set([...(process.env[`TOKENSIZE_${harness.toUpperCase()}_MODELS`] ?? \"\").split(\",\").map((v) => v.trim()).filter(Boolean), ...cliReported])];\n\tconst apiKey = harness === \"claude\" && Boolean(process.env.ANTHROPIC_API_KEY);\n\tconst approved = apiKey || subscriptionApproved(harness);\n\tconst warnings = configured.length ? [] : [`Set TOKENSIZE_${harness.toUpperCase()}_MODELS to advertise supported models`];\n\tif (harness === \"copilot\" && !authenticated) warnings.push(\"Copilot CLI has no non-interactive auth-status command; set GH_TOKEN/GITHUB_TOKEN or verify authentication before advertising models\");\n\treturn { harness, installed: true, executable: exe, version: version.stdout.trim(), authenticated, models: configured.map((id) => model(harness, id, id, approved, apiKey ? \"api-key\" : \"subscription\")), warnings };\n}\n\nasync function cursor(): Promise<HarnessDiscovery> {\n\tconst exe = await executable([\"agent\", \"cursor-agent\"]);\n\tif (!exe) return { harness: \"cursor\", installed: false, authenticated: false, models: [], warnings: [] };\n\tconst [version, auth, catalog] = await Promise.all([\n\t\trun(exe, [\"--version\"], { timeoutMs: 5_000, maxBytes: 64_000 }),\n\t\trun(exe, [\"status\"], { timeoutMs: 8_000, maxBytes: 64_000 }),\n\t\trun(exe, [\"--list-models\"], { timeoutMs: 10_000, maxBytes: 512_000 }),\n\t]);\n\tconst available = catalog.stdout.split(/\\r?\\n/).flatMap((line) => {\n\t\tconst match = /^(\\S+)\\s+-\\s+(.+)$/.exec(line.trim());\n\t\treturn match ? [{ id: match[1], name: match[2] }] : [];\n\t});\n\tconst preferred = [\n\t\t/^gpt-5\\.6-sol-high$/,\n\t\t/^claude-opus-4-8-high$/,\n\t\t/^claude-fable-5-high$/,\n\t\t/^claude-sonnet-5-high$/,\n\t\t/^cursor-grok-4\\.5-high$/,\n\t\t/^composer-2\\.5$/,\n\t\t/^gpt-5\\.5-high$/,\n\t\t/^gpt-5\\.4-high$/,\n\t];\n\tconst selected = preferred.flatMap((pattern) => available.find((item) => pattern.test(item.id)) ?? []);\n\tconst approved = subscriptionApproved(\"cursor\");\n\tconst models = selected.map((item, index) => {\n\t\tconst candidate = model(\"cursor\", item.id, item.name, approved, \"subscription\", { qualityPrior: Math.max(0.84, 0.98 - index * 0.018), tokenEfficiencyPrior: /composer|grok/i.test(item.id) ? 0.86 : 0.72, latencyPrior: /composer|grok/i.test(item.id) ? 0.82 : 0.66 });\n\t\tcandidate.capabilities.permissions = [\"inspect\"];\n\t\treturn candidate;\n\t});\n\treturn { harness: \"cursor\", installed: true, executable: exe, version: version.stdout.trim(), authenticated: auth.code === 0 && /logged in/i.test(auth.stdout), models, warnings: models.length ? [] : [\"Cursor model catalog did not contain a supported frontier model\"] };\n}\n\nfunction stripAnsi(value: string): string {\n\treturn value.replace(/\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g, \"\");\n}\n\nexport function opencodeModelIds(output: string): string[] {\n\treturn [...new Set(stripAnsi(output).split(/\\r?\\n/).map((line) => line.trim()).filter((line) => /^[a-z0-9][a-z0-9._-]*\\/[a-z0-9][a-z0-9._:/-]*$/i.test(line)))];\n}\n\nexport function isCredentialFreeOpenCodeModel(id: string): boolean {\n\treturn /^opencode\\/(?:big-pickle|[a-z0-9._:/-]+-free)$/i.test(id);\n}\n\nasync function opencode(): Promise<HarnessDiscovery> {\n\tconst exe = await executable([\"opencode\"]);\n\tif (!exe) return { harness: \"opencode\", installed: false, authenticated: false, models: [], warnings: [] };\n\tconst [version, auth, initialCatalog] = await Promise.all([\n\t\trun(exe, [\"--version\"], { timeoutMs: 5_000, maxBytes: 64_000 }),\n\t\trun(exe, [\"auth\", \"list\"], { timeoutMs: 8_000, maxBytes: 128_000 }),\n\t\trun(exe, [\"models\"], { timeoutMs: 10_000, maxBytes: 512_000 }),\n\t]);\n\tconst available = opencodeModelIds(initialCatalog.stdout);\n\tconst credentialFree = available.filter(isCredentialFreeOpenCodeModel);\n\tconst frontier = available.filter((id) => /gpt-5\\.[4-9]|opus|fable|sonnet|grok|gemini|glm|qwen|coder/i.test(id));\n\tconst ids = [...new Set([...credentialFree, ...(frontier.length ? frontier : available)])].slice(0, 48);\n\tconst authOutput = stripAnsi(`${auth.stdout}\\n${auth.stderr}`).trim();\n\tconst hasStoredCredentials = auth.code === 0 && authOutput.length > 0 && !/\\b(?:no|0)\\s+(?:credentials|providers|authentication)\\b/i.test(authOutput);\n\tconst authenticated = hasStoredCredentials || credentialFree.length > 0;\n\tconst subscriptionIsApproved = subscriptionApproved(\"opencode\");\n\tconst models = ids.map((id, index) => {\n\t\tconst isCredentialFree = isCredentialFreeOpenCodeModel(id);\n\t\tconst candidate = model(\"opencode\", id, id, isCredentialFree || subscriptionIsApproved, isCredentialFree ? \"cloud-provider\" : \"subscription\", {\n\t\t\tqualityPrior: Math.max(0.82, 0.96 - index * 0.01),\n\t\t\ttokenEfficiencyPrior: 0.76,\n\t\t\tlatencyPrior: 0.7,\n\t\t});\n\t\t// OpenCode's headless --auto flag is broader than TokenSize's edit/test\n\t\t// permission ceilings. Keep execution read-only until that boundary is exact.\n\t\tcandidate.capabilities.permissions = [\"inspect\"];\n\t\tcandidate.capabilities.vision = false;\n\t\treturn candidate;\n\t});\n\tconst warnings: string[] = [];\n\tif (!hasStoredCredentials && credentialFree.length) warnings.push(`OpenCode has no stored provider credentials; ${credentialFree.length} credential-free model(s) remain available`);\n\telse if (!hasStoredCredentials) warnings.push(\"OpenCode did not report a configured provider credential\");\n\tif (!models.length) warnings.push(\"OpenCode model catalog was unavailable; run `opencode models --refresh`\");\n\tif (!subscriptionIsApproved && models.some((item) => item.authMode === \"subscription\")) warnings.push(\"Paid/provider OpenCode models remain ineligible; set TOKENSIZE_ALLOW_SUBSCRIPTION_HARNESSES=opencode only when provider and product terms permit delegated use\");\n\treturn { harness: \"opencode\", installed: true, executable: exe, version: version.stdout.trim(), authenticated, models, warnings };\n}\n\nexport const HARNESS_IDS: readonly HarnessId[] = [\"codex\", \"claude\", \"copilot\", \"cursor\", \"opencode\"];\n\n/** Probe one harness without invoking it for task execution. */\nexport async function discoverHarness(harness: HarnessId): Promise<HarnessDiscovery> {\n\tlet probe: () => Promise<HarnessDiscovery>;\n\tswitch (harness) {\n\t\tcase \"codex\": probe = codex; break;\n\t\tcase \"claude\": probe = () => generic(\"claude\", [\"claude\"]); break;\n\t\tcase \"copilot\": probe = () => generic(\"copilot\", [\"copilot\", \"github-copilot-cli\"]); break;\n\t\tcase \"cursor\": probe = cursor; break;\n\t\tcase \"opencode\": probe = opencode; break;\n\t\tcase \"custom\": return { harness: \"custom\", installed: false, authenticated: false, models: [], warnings: [\"No custom harness adapter is configured\"] };\n\t}\n\tlet timer: NodeJS.Timeout | undefined;\n\tconst deadline = new Promise<HarnessDiscovery>((resolve) => {\n\t\ttimer = setTimeout(() => resolve({\n\t\t\tharness,\n\t\t\tinstalled: true,\n\t\t\tauthenticated: false,\n\t\t\tmodels: [],\n\t\t\twarnings: [`${harness} discovery exceeded the ${HARNESS_PROBE_DEADLINE_MS / 1_000}s safety deadline; retry with --refresh`],\n\t\t\tprobeTimedOut: true,\n\t\t}), HARNESS_PROBE_DEADLINE_MS);\n\t});\n\treturn Promise.race([probe().finally(() => { if (timer) clearTimeout(timer); }), deadline]);\n}\n\nexport async function discoverHarnesses(): Promise<HarnessDiscovery[]> {\n\t// The three catalog-oriented CLIs can each emit substantial output. Two\n\t// bounded waves keep the event loop responsive enough for safety timers while\n\t// still avoiding a fully sequential cold refresh.\n\tconst [codexResult, cursorResult] = await Promise.all([discoverHarness(\"codex\"), discoverHarness(\"cursor\")]);\n\tconst [claudeResult, copilotResult, opencodeResult] = await Promise.all([\n\t\tdiscoverHarness(\"claude\"),\n\t\tdiscoverHarness(\"copilot\"),\n\t\tdiscoverHarness(\"opencode\"),\n\t]);\n\treturn [codexResult, claudeResult, copilotResult, cursorResult, opencodeResult];\n}\n\nfunction applyCurrentApproval(harnesses: HarnessDiscovery[]): HarnessDiscovery[] {\n\treturn harnesses.map((item) => ({\n\t\t...item,\n\t\tmodels: item.models.map((candidate) => {\n\t\t\tconst apiKeyMode = (candidate.harness === \"codex\" && Boolean(process.env.OPENAI_API_KEY))\n\t\t\t\t|| (candidate.harness === \"claude\" && Boolean(process.env.ANTHROPIC_API_KEY));\n\t\t\tconst credentialFree = candidate.harness === \"opencode\" && isCredentialFreeOpenCodeModel(candidate.nativeModelId);\n\t\t\treturn {\n\t\t\t\t...candidate,\n\t\t\t\tauthMode: credentialFree ? \"cloud-provider\" as const : apiKeyMode ? \"api-key\" as const : \"subscription\" as const,\n\t\t\t\tproductUseApproved: credentialFree || apiKeyMode || subscriptionApproved(candidate.harness),\n\t\t\t};\n\t\t}),\n\t}));\n}\n\nasync function cachedExecutablesExist(harnesses: HarnessDiscovery[]): Promise<boolean> {\n\ttry {\n\t\tawait Promise.all(harnesses.filter((item) => item.installed && !item.probeTimedOut).map((item) => item.executable\n\t\t\t? access(item.executable)\n\t\t\t: Promise.reject(new Error(\"cached installed harness has no executable\"))));\n\t\treturn true;\n\t} catch { return false; }\n}\n\nasync function readDiscoveryCache(): Promise<DiscoveryResult | null> {\n\tconst file = discoveryCacheFile();\n\ttry {\n\t\tconst cached = JSON.parse(await readFile(file, \"utf8\")) as {\n\t\t\tschemaVersion?: number;\n\t\t\tfingerprint?: string;\n\t\t\tcreatedAt?: string;\n\t\t\texpiresAt?: string;\n\t\t\tharnesses?: HarnessDiscovery[];\n\t\t};\n\t\tif (cached.schemaVersion !== DISCOVERY_CACHE_VERSION\n\t\t\t|| cached.fingerprint !== discoveryFingerprint()\n\t\t\t|| !cached.createdAt\n\t\t\t|| !cached.expiresAt\n\t\t\t|| !Array.isArray(cached.harnesses)\n\t\t\t|| Date.parse(cached.expiresAt) <= Date.now()\n\t\t\t|| !(await cachedExecutablesExist(cached.harnesses))) return null;\n\t\treturn {\n\t\t\tharnesses: applyCurrentApproval(cached.harnesses),\n\t\t\tcache: { hit: true, path: file, createdAt: cached.createdAt, expiresAt: cached.expiresAt, ageMs: Math.max(0, Date.now() - Date.parse(cached.createdAt)) },\n\t\t};\n\t} catch { return null; }\n}\n\nasync function writeDiscoveryCache(harnesses: HarnessDiscovery[], reason: string): Promise<DiscoveryCacheMetadata> {\n\tconst directory = home();\n\tconst file = discoveryCacheFile();\n\tconst temporary = `${file}.${process.pid}.tmp`;\n\tconst createdAt = new Date();\n\tconst cacheTtl = harnesses.some((item) => item.probeTimedOut)\n\t\t? Math.min(discoveryCacheTtlMs(), INCOMPLETE_DISCOVERY_CACHE_TTL_MS)\n\t\t: discoveryCacheTtlMs();\n\tconst value = {\n\t\tschemaVersion: DISCOVERY_CACHE_VERSION,\n\t\tcreatedAt: createdAt.toISOString(),\n\t\texpiresAt: new Date(createdAt.getTime() + cacheTtl).toISOString(),\n\t\tfingerprint: discoveryFingerprint(),\n\t\tharnesses,\n\t};\n\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify(value, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n\treturn { hit: false, refreshed: true, reason, path: file, createdAt: value.createdAt, expiresAt: value.expiresAt, ageMs: 0 };\n}\n\nexport async function discoverHarnessesCached(options: DiscoveryOptions = {}): Promise<DiscoveryResult> {\n\tif (!options.forceRefresh) {\n\t\tconst cached = await readDiscoveryCache();\n\t\tif (cached) return cached;\n\t}\n\tconst harnesses = await discoverHarnesses();\n\tconst reason = options.reason ?? (options.forceRefresh ? \"manual\" : \"miss-or-stale\");\n\ttry {\n\t\treturn { harnesses, cache: await writeDiscoveryCache(harnesses, reason) };\n\t} catch (error) {\n\t\treturn {\n\t\t\tharnesses,\n\t\t\tcache: { hit: false, refreshed: true, persisted: false, reason, warning: `could not persist discovery cache: ${error instanceof Error ? error.message : String(error)}` },\n\t\t};\n\t}\n}\nexport function flattenModels(discovery: HarnessDiscovery[], maximum = 100): AgentModel[] {\n\tconst queues = discovery.filter((item) => item.authenticated).map((item) => [...item.models]);\n\tconst selected: AgentModel[] = [];\n\twhile (selected.length < maximum && queues.some((queue) => queue.length)) {\n\t\tfor (const queue of queues) {\n\t\t\tconst next = queue.shift();\n\t\t\tif (next) selected.push(next);\n\t\t\tif (selected.length === maximum) break;\n\t\t}\n\t}\n\treturn selected;\n}\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { randomUUID } from \"node:crypto\";\n\nexport function home(): string { return process.env.TOKENSIZE_HOME ?? path.join(os.homedir(), \".tokensize\"); }\nexport async function saveApiKey(apiKey: string): Promise<void> {\n\tconst directory = home();\n\tconst file = path.join(directory, \"credentials.json\");\n\tconst temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\n\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify({ apiKey }, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n}\nexport async function readApiKey(): Promise<string | null> {\n\ttry {\n\t\tconst value = JSON.parse(await readFile(path.join(home(), \"credentials.json\"), \"utf8\")) as { apiKey?: unknown };\n\t\treturn typeof value.apiKey === \"string\" && value.apiKey.length > 0 ? value.apiKey : null;\n\t} catch { return null; }\n}\nexport async function installationId(): Promise<string> {\n\tconst file = path.join(home(), \"config.json\");\n\ttry { const data = JSON.parse(await readFile(file, \"utf8\")) as { installationId?: string }; if (data.installationId) return data.installationId; } catch { /* first run */ }\n\tconst id = randomUUID();\n\tconst temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\n\tawait mkdir(home(), { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify({ installationId: id }, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n\treturn id;\n}\n\nexport interface LastRouteReceipt {\n\trouteId: string;\n\trunId?: string;\n\tfeedbackToken: string;\n\texpiresAt: string;\n\ttargetId: string | null;\n}\n\n/**\n * The local policy document: one owner-only file both hands edit — the human\n * through `tokensize policy` or the web UI defaults, agents by reading it.\n * Local values are ceilings; a hosted policy can only narrow them (see\n * `mergePolicy` in @tokensize/agent-router). Environment variables still\n * override for CI, but the file is the durable source.\n */\nexport interface LocalPolicy {\n\trootHarness?: string;\n\trootQualityPrior?: number;\n\tobjective?: \"quality\" | \"balanced\" | \"tokens\" | \"latency\";\n\tpermissionCeiling?: \"inspect\" | \"edit\" | \"test\" | \"network\";\n\tmaxDelegationDepth?: number;\n\tsubscriptionHarnesses?: string[];\n\tsharePromptDefault?: boolean;\n}\n\nconst OBJECTIVES = [\"quality\", \"balanced\", \"tokens\", \"latency\"] as const;\nconst PERMISSIONS = [\"inspect\", \"edit\", \"test\", \"network\"] as const;\n\nfunction policyFile(): string { return path.join(home(), \"policy.json\"); }\n\nfunction sanitizePolicy(value: Partial<LocalPolicy>): LocalPolicy {\n\tconst policy: LocalPolicy = {};\n\tif (typeof value.rootHarness === \"string\" && value.rootHarness.length > 0 && value.rootHarness.length <= 50) policy.rootHarness = value.rootHarness;\n\tif (typeof value.rootQualityPrior === \"number\" && value.rootQualityPrior >= 0 && value.rootQualityPrior <= 1) policy.rootQualityPrior = value.rootQualityPrior;\n\tif (OBJECTIVES.includes(value.objective as never)) policy.objective = value.objective;\n\tif (PERMISSIONS.includes(value.permissionCeiling as never)) policy.permissionCeiling = value.permissionCeiling;\n\tif (typeof value.maxDelegationDepth === \"number\" && Number.isInteger(value.maxDelegationDepth) && value.maxDelegationDepth >= 0 && value.maxDelegationDepth <= 3) policy.maxDelegationDepth = value.maxDelegationDepth;\n\tif (Array.isArray(value.subscriptionHarnesses)) policy.subscriptionHarnesses = value.subscriptionHarnesses.filter((item): item is string => typeof item === \"string\" && item.length > 0 && item.length <= 50).slice(0, 10);\n\tif (typeof value.sharePromptDefault === \"boolean\") policy.sharePromptDefault = value.sharePromptDefault;\n\treturn policy;\n}\n\nexport async function readLocalPolicy(): Promise<LocalPolicy> {\n\ttry {\n\t\treturn sanitizePolicy(JSON.parse(await readFile(policyFile(), \"utf8\")) as Partial<LocalPolicy>);\n\t} catch { return {}; }\n}\n\nexport async function saveLocalPolicy(patch: Partial<LocalPolicy>): Promise<LocalPolicy> {\n\tconst current = await readLocalPolicy();\n\tconst merged = sanitizePolicy({ ...current, ...patch });\n\tconst file = policyFile();\n\tconst temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\n\tawait mkdir(home(), { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify(merged, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n\treturn merged;\n}\n\nexport async function saveLastRoute(receipt: LastRouteReceipt): Promise<void> {\n\tconst directory = home();\n\tconst file = path.join(directory, \"last-route.json\");\n\tconst temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;\n\tawait mkdir(directory, { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify(receipt, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n}\n\nexport async function readLastRoute(): Promise<LastRouteReceipt> {\n\tconst value = JSON.parse(await readFile(path.join(home(), \"last-route.json\"), \"utf8\")) as Partial<LastRouteReceipt>;\n\tif (typeof value.routeId !== \"string\" || typeof value.feedbackToken !== \"string\" || typeof value.expiresAt !== \"string\") {\n\t\tthrow new Error(\"invalid local route receipt\");\n\t}\n\treturn {\n\t\trouteId: value.routeId,\n\t\t...(typeof value.runId === \"string\" ? { runId: value.runId } : {}),\n\t\tfeedbackToken: value.feedbackToken,\n\t\texpiresAt: value.expiresAt,\n\t\ttargetId: value.targetId ?? null,\n\t};\n}\n","import { spawn, type ChildProcess } from \"node:child_process\";\n\nexport interface RunResult { code: number | null; stdout: string; stderr: string; timedOut: boolean }\n\n/** Signal only the process group created for a TokenSize child command. */\nexport function terminateProcessTree(child: ChildProcess, signal: NodeJS.Signals): void {\n\tif (process.platform !== \"win32\" && child.pid) {\n\t\ttry { process.kill(-child.pid, signal); return; } catch { /* process may already have exited */ }\n\t}\n\ttry { child.kill(signal); } catch { /* process may already have exited */ }\n}\n\nexport async function run(command: string, args: string[], options: { cwd?: string; input?: string; timeoutMs?: number; maxBytes?: number; env?: NodeJS.ProcessEnv } = {}): Promise<RunResult> {\n\treturn await new Promise((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tshell: false,\n\t\t\tdetached: process.platform !== \"win32\",\n\t\t\tenv: options.env ?? process.env,\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet stdout = \"\", stderr = \"\", timedOut = false;\n\t\tlet settled = false;\n\t\tconst max = options.maxBytes ?? 8_000_000;\n\t\tchild.stdout.on(\"data\", (data: Buffer) => { if (stdout.length < max) stdout += data.toString().slice(0, max - stdout.length); });\n\t\tchild.stderr.on(\"data\", (data: Buffer) => { if (stderr.length < max) stderr += data.toString().slice(0, max - stderr.length); });\n\t\tlet forceTimer: NodeJS.Timeout | undefined;\n\t\tlet timer: NodeJS.Timeout | undefined;\n\t\tconst finish = (code: number | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (forceTimer) clearTimeout(forceTimer);\n\t\t\tresolve({ code, stdout, stderr, timedOut });\n\t\t};\n\t\tchild.on(\"error\", (error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tif (forceTimer) clearTimeout(forceTimer);\n\t\t\treject(error);\n\t\t});\n\t\ttimer = setTimeout(() => {\n\t\t\ttimedOut = true;\n\t\t\tterminateProcessTree(child, \"SIGTERM\");\n\t\t\tforceTimer = setTimeout(() => {\n\t\t\t\tterminateProcessTree(child, \"SIGKILL\");\n\t\t\t\tchild.stdin.destroy();\n\t\t\t\tchild.stdout.destroy();\n\t\t\t\tchild.stderr.destroy();\n\t\t\t\tchild.unref();\n\t\t\t\tfinish(null);\n\t\t\t}, 1_000);\n\t\t}, options.timeoutMs ?? 15_000);\n\t\tchild.on(\"close\", finish);\n\t\tif (options.input) child.stdin.end(options.input); else child.stdin.end();\n\t});\n}\n","import { spawn } from \"node:child_process\";\nimport { access, mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { AgentModel, Allowance, HarnessId } from \"@tokensize/agent-router\";\nimport { home } from \"./config\";\nimport type { HarnessDiscovery } from \"./discovery\";\n\nconst CACHE_VERSION = 1;\nconst DEFAULT_TTL_MS = 5 * 60 * 1_000;\n\nexport interface HarnessAllowance {\n\tdefault: Allowance;\n\tbyModelId?: Record<string, Allowance>;\n}\n\nexport interface AllowanceSnapshot {\n\tharnesses: Partial<Record<HarnessId, HarnessAllowance>>;\n\tcache: {\n\t\thit: boolean;\n\t\tpath: string;\n\t\tcreatedAt: string;\n\t\texpiresAt: string;\n\t};\n}\n\nfunction observed(status: Allowance[\"status\"], source: Allowance[\"source\"], remainingFraction?: number, resetsAt?: string): Allowance {\n\tconst normalized = remainingFraction === undefined\n\t\t? undefined\n\t\t: Math.round(Math.max(0, Math.min(1, remainingFraction)) * 10_000) / 10_000;\n\treturn {\n\t\tstatus,\n\t\tsource,\n\t\tobservedAt: new Date().toISOString(),\n\t\t...(normalized === undefined ? {} : { remainingFraction: normalized }),\n\t\t...(resetsAt ? { resetsAt } : {}),\n\t};\n}\n\nfunction status(remaining: number): Allowance[\"status\"] {\n\tif (remaining <= 0) return \"exhausted\";\n\tif (remaining <= 0.15) return \"low\";\n\treturn \"available\";\n}\n\nfunction unknown(): Allowance {\n\treturn observed(\"unknown\", \"unavailable\");\n}\n\nfunction cacheFile(): string {\n\treturn path.join(home(), \"allowance.json\");\n}\n\nfunction ttlMs(): number {\n\tconst value = Number(process.env.TOKENSIZE_ALLOWANCE_CACHE_TTL_MS ?? DEFAULT_TTL_MS);\n\treturn Number.isFinite(value) && value >= 0 ? value : DEFAULT_TTL_MS;\n}\n\nasync function codexAllowance(executable: string): Promise<Allowance> {\n\treturn await new Promise((resolve) => {\n\t\tconst child = spawn(executable, [\"app-server\", \"--stdio\"], { shell: false, stdio: [\"pipe\", \"pipe\", \"ignore\"] });\n\t\tlet buffer = \"\";\n\t\tlet complete = false;\n\t\tconst finish = (value: Allowance) => {\n\t\t\tif (complete) return;\n\t\t\tcomplete = true;\n\t\t\tclearTimeout(timer);\n\t\t\tchild.kill();\n\t\t\tresolve(value);\n\t\t};\n\t\tconst timer = setTimeout(() => finish(unknown()), 15_000);\n\t\tchild.once(\"error\", () => finish(unknown()));\n\t\tchild.stdout.on(\"data\", (chunk: Buffer) => {\n\t\t\tbuffer += chunk.toString();\n\t\t\tlet newline: number;\n\t\t\twhile ((newline = buffer.indexOf(\"\\n\")) >= 0) {\n\t\t\t\tconst line = buffer.slice(0, newline);\n\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\ttry {\n\t\t\t\t\tconst message = JSON.parse(line) as {\n\t\t\t\t\t\tid?: number;\n\t\t\t\t\t\tresult?: {\n\t\t\t\t\t\t\trateLimits?: {\n\t\t\t\t\t\t\t\tprimary?: { usedPercent?: number; resetsAt?: number | null } | null;\n\t\t\t\t\t\t\t\tsecondary?: { usedPercent?: number; resetsAt?: number | null } | null;\n\t\t\t\t\t\t\t\tindividualLimit?: { remainingPercent?: number; resetsAt?: number } | null;\n\t\t\t\t\t\t\t\tcredits?: { unlimited?: boolean } | null;\n\t\t\t\t\t\t\t\trateLimitReachedType?: unknown;\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t};\n\t\t\t\t\t};\n\t\t\t\t\tif (message.id === 1) {\n\t\t\t\t\t\tchild.stdin.write(`${JSON.stringify({ jsonrpc: \"2.0\", method: \"notifications/initialized\" })}\\n`);\n\t\t\t\t\t\tchild.stdin.write(`${JSON.stringify({ jsonrpc: \"2.0\", id: 2, method: \"account/rateLimits/read\" })}\\n`);\n\t\t\t\t\t}\n\t\t\t\t\tif (message.id === 2) {\n\t\t\t\t\t\tconst limits = message.result?.rateLimits;\n\t\t\t\t\t\tif (!limits) return finish(unknown());\n\t\t\t\t\t\tif (limits.rateLimitReachedType) return finish(observed(\"exhausted\", \"runtime-reported\", 0));\n\t\t\t\t\t\tconst windows = [limits.primary, limits.secondary]\n\t\t\t\t\t\t\t.filter((value): value is { usedPercent?: number; resetsAt?: number | null } => Boolean(value))\n\t\t\t\t\t\t\t.flatMap((value) => typeof value.usedPercent === \"number\"\n\t\t\t\t\t\t\t\t? [{ remaining: 1 - value.usedPercent / 100, resetsAt: value.resetsAt }]\n\t\t\t\t\t\t\t\t: []);\n\t\t\t\t\t\tif (typeof limits.individualLimit?.remainingPercent === \"number\") {\n\t\t\t\t\t\t\twindows.push({ remaining: limits.individualLimit.remainingPercent / 100, resetsAt: limits.individualLimit.resetsAt });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (!windows.length && limits.credits?.unlimited) return finish(observed(\"unmetered\", \"runtime-reported\"));\n\t\t\t\t\t\tif (!windows.length) return finish(unknown());\n\t\t\t\t\t\tconst constrained = windows.sort((a, b) => a.remaining - b.remaining)[0];\n\t\t\t\t\t\tconst remaining = Math.max(0, Math.min(1, constrained.remaining));\n\t\t\t\t\t\tconst resetsAt = constrained.resetsAt ? new Date(constrained.resetsAt * 1_000).toISOString() : undefined;\n\t\t\t\t\t\treturn finish(observed(status(remaining), \"runtime-reported\", remaining, resetsAt));\n\t\t\t\t\t}\n\t\t\t\t} catch { /* ignore diagnostics and unrelated notifications */ }\n\t\t\t}\n\t\t});\n\t\tchild.stdin.write(`${JSON.stringify({ jsonrpc: \"2.0\", id: 1, method: \"initialize\", params: { clientInfo: { name: \"tokensize\", version: \"0.1.0\" }, capabilities: { experimentalApi: true } } })}\\n`);\n\t});\n}\n\nfunction stripTerminal(value: string): string {\n\treturn value\n\t\t.replace(/\\x1B(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])/g, \"\")\n\t\t.replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]/g, \"\")\n\t\t.replace(/\\r/g, \"\\n\");\n}\n\nfunction usedPercent(text: string, label: RegExp): number | undefined {\n\tconst match = label.exec(text);\n\tif (match?.index === undefined) return undefined;\n\tconst nearby = text.slice(match.index, match.index + 260);\n\tconst percentage = /(\\d{1,3})%\\s*used/i.exec(nearby);\n\treturn percentage ? Math.max(0, Math.min(100, Number(percentage[1]))) : undefined;\n}\n\nexport function parseClaudeUsage(raw: string): HarnessAllowance {\n\tconst text = stripTerminal(raw);\n\tconst usageScreen = text.slice(Math.max(0, text.lastIndexOf(\"Settings\")));\n\tconst ordered = [...usageScreen.matchAll(/(\\d{1,3})\\s*%\\s*used/gi)]\n\t\t.map((match) => Math.max(0, Math.min(100, Number(match[1]))));\n\tconst exactSession = usedPercent(text, /Current\\s+session/i);\n\tconst exactGeneral = usedPercent(text, /Current\\s+week\\s*\\(all\\s+models\\)/i);\n\tconst exactFable = usedPercent(text, /Current\\s+week\\s*\\(Fable\\)/i);\n\t// Terminal screen redraws can overwrite parts of labels, but the Usage tab\n\t// keeps a stable order: session, all-model weekly, then model-family weekly.\n\tconst sessionUsed = exactSession ?? ordered[0];\n\tconst weeklyUsed = exactGeneral ?? ordered[1] ?? ordered[0];\n\tconst fableUsed = exactFable ?? ordered[2];\n\tconst generalUsed = [sessionUsed, weeklyUsed].filter((value): value is number => value !== undefined);\n\tconst generalRemaining = generalUsed.length ? 1 - Math.max(...generalUsed) / 100 : undefined;\n\tconst defaultAllowance = generalRemaining === undefined\n\t\t? unknown()\n\t\t: observed(status(generalRemaining), \"runtime-reported\", generalRemaining);\n\tconst byModelId: Record<string, Allowance> = {};\n\tif (fableUsed !== undefined) {\n\t\tconst remaining = Math.min(generalRemaining ?? 1, 1 - fableUsed / 100);\n\t\tbyModelId.fable = observed(status(remaining), \"runtime-reported\", remaining);\n\t}\n\treturn { default: defaultAllowance, ...(Object.keys(byModelId).length ? { byModelId } : {}) };\n}\n\nasync function claudeAllowance(executable: string): Promise<HarnessAllowance> {\n\tif (process.platform !== \"darwin\") return { default: unknown() };\n\ttry { await access(\"/usr/bin/expect\"); } catch { return { default: unknown() }; }\n\treturn await new Promise((resolve) => {\n\t\t// `expect` owns the pseudo-terminal and reaps Claude when it exits. This\n\t\t// avoids both credential access and unsafe process-group signalling.\n\t\tconst script = \"set timeout 10; log_user 1; spawn -noecho $env(TOKENSIZE_CLAUDE_EXECUTABLE) --safe-mode; after 1800; send -- \\\"/usage\\\\r\\\"; after 700; send -- \\\"\\\\r\\\"; expect -re {Current}; after 3500; exit 0\";\n\t\tconst child = spawn(\"/usr/bin/expect\", [\"-c\", script], {\n\t\t\tenv: { ...process.env, TERM: \"xterm-256color\", TOKENSIZE_CLAUDE_EXECUTABLE: executable },\n\t\t\tstdio: [\"pipe\", \"pipe\", \"pipe\"],\n\t\t});\n\t\tlet raw = \"\";\n\t\tlet complete = false;\n\t\tconst finish = () => {\n\t\t\tif (complete) return;\n\t\t\tcomplete = true;\n\t\t\tclearTimeout(timeout);\n\t\t\ttry { child.kill(\"SIGTERM\"); } catch { /* already closed */ }\n\t\t\t// Claude exposes both a short session window and a weekly window. The\n\t\t\t// most constrained applicable window is the safe routing signal.\n\t\t\tconst parsed = parseClaudeUsage(raw);\n\t\t\t// Raw terminal output may include account identity; it is intentionally\n\t\t\t// neither returned nor persisted.\n\t\t\traw = \"\";\n\t\t\tresolve(parsed);\n\t\t};\n\t\tconst timeout = setTimeout(finish, 13_000);\n\t\tchild.once(\"error\", finish);\n\t\tconst collect = (chunk: Buffer) => {\n\t\t\tif (raw.length < 256_000) raw += chunk.toString().slice(0, 256_000 - raw.length);\n\t\t};\n\t\tchild.stdout.on(\"data\", collect);\n\t\tchild.stderr.on(\"data\", collect);\n\t\tchild.once(\"close\", finish);\n\t});\n}\n\nasync function collect(discovery: HarnessDiscovery[]): Promise<Partial<Record<HarnessId, HarnessAllowance>>> {\n\tconst result: Partial<Record<HarnessId, HarnessAllowance>> = {};\n\tfor (const item of discovery) {\n\t\tif (!item.installed || !item.authenticated || !item.executable) continue;\n\t\tif (item.harness === \"codex\") {\n\t\t\tlet detected = await codexAllowance(item.executable);\n\t\t\tif (detected.status === \"unknown\") detected = await codexAllowance(item.executable);\n\t\t\tresult.codex = { default: detected };\n\t\t} else if (item.harness === \"claude\") {\n\t\t\tlet detected = await claudeAllowance(item.executable);\n\t\t\tif (detected.default.status === \"unknown\") detected = await claudeAllowance(item.executable);\n\t\t\tresult.claude = detected;\n\t\t}\n\t\telse result[item.harness] = { default: unknown() };\n\t}\n\treturn result;\n}\n\nasync function readCache(): Promise<AllowanceSnapshot | null> {\n\tconst file = cacheFile();\n\ttry {\n\t\tconst value = JSON.parse(await readFile(file, \"utf8\")) as {\n\t\t\tschemaVersion?: number;\n\t\t\tcreatedAt?: string;\n\t\t\texpiresAt?: string;\n\t\t\tharnesses?: Partial<Record<HarnessId, HarnessAllowance>>;\n\t\t};\n\t\tif (value.schemaVersion !== CACHE_VERSION || !value.createdAt || !value.expiresAt || !value.harnesses || Date.parse(value.expiresAt) <= Date.now()) return null;\n\t\treturn { harnesses: value.harnesses, cache: { hit: true, path: file, createdAt: value.createdAt, expiresAt: value.expiresAt } };\n\t} catch { return null; }\n}\n\nexport async function allowances(discovery: HarnessDiscovery[], forceRefresh = false): Promise<AllowanceSnapshot> {\n\tif (!forceRefresh) {\n\t\tconst cached = await readCache();\n\t\tif (cached) return cached;\n\t}\n\tconst harnesses = await collect(discovery);\n\tconst createdAt = new Date();\n\tconst expiresAt = new Date(createdAt.getTime() + ttlMs());\n\tconst file = cacheFile();\n\tconst temporary = `${file}.${process.pid}.tmp`;\n\tawait mkdir(home(), { recursive: true, mode: 0o700 });\n\tawait writeFile(temporary, `${JSON.stringify({ schemaVersion: CACHE_VERSION, createdAt: createdAt.toISOString(), expiresAt: expiresAt.toISOString(), harnesses }, null, 2)}\\n`, { mode: 0o600 });\n\tawait rename(temporary, file);\n\treturn { harnesses, cache: { hit: false, path: file, createdAt: createdAt.toISOString(), expiresAt: expiresAt.toISOString() } };\n}\n\nfunction forModel(model: AgentModel, snapshot: Partial<Record<HarnessId, HarnessAllowance>>): Allowance {\n\tif (model.harness === \"opencode\" && /^opencode\\/(?:big-pickle|[a-z0-9._:/-]+-free)$/i.test(model.nativeModelId)) {\n\t\treturn observed(\"unmetered\", \"credential-free\");\n\t}\n\tconst harness = snapshot[model.harness];\n\tif (!harness) return unknown();\n\tif (model.harness === \"claude\" && /fable/i.test(model.nativeModelId)) return harness.byModelId?.fable ?? unknown();\n\treturn harness.default;\n}\n\nexport function applyAllowances(discovery: HarnessDiscovery[], snapshot: AllowanceSnapshot): HarnessDiscovery[] {\n\treturn discovery.map((item) => ({\n\t\t...item,\n\t\tmodels: item.models.map((model) => ({ ...model, allowance: forModel(model, snapshot.harnesses) })),\n\t}));\n}\n\nexport function rootAllowance(harness: HarnessId, snapshot: AllowanceSnapshot): Allowance {\n\treturn snapshot.harnesses[harness]?.default ?? unknown();\n}\n\nfunction publicAllowance(value: Allowance): Allowance & { remainingPercent?: number } {\n\tconst remainingFraction = value.remainingFraction === undefined\n\t\t? undefined\n\t\t: Math.round(value.remainingFraction * 10_000) / 10_000;\n\treturn {\n\t\t...value,\n\t\t...(remainingFraction === undefined ? {} : {\n\t\t\tremainingFraction,\n\t\t\tremainingPercent: Math.round(remainingFraction * 1_000) / 10,\n\t\t}),\n\t};\n}\n\nfunction allowanceKey(value: Allowance): string {\n\treturn [value.status, value.source, value.remainingFraction ?? \"n/a\", value.resetsAt ?? \"n/a\"].join(\":\");\n}\n\nexport function allowanceScopesForHarness(item: HarnessDiscovery) {\n\tconst scopes = new Map<string, { modelIds: string[]; allowance: Allowance }>();\n\tfor (const model of item.models) {\n\t\tconst value = model.allowance ?? unknown();\n\t\tconst key = allowanceKey(value);\n\t\tconst existing = scopes.get(key);\n\t\tif (existing) existing.modelIds.push(model.nativeModelId);\n\t\telse scopes.set(key, { modelIds: [model.nativeModelId], allowance: value });\n\t}\n\treturn [...scopes.values()].map((scope) => {\n\t\tconst compact = scope.modelIds.length > 12;\n\t\treturn {\n\t\t\t...(compact ? { sampleModelIds: scope.modelIds.slice(0, 12), omittedModelCount: scope.modelIds.length - 12 } : { modelIds: scope.modelIds }),\n\t\t\tmodelCount: scope.modelIds.length,\n\t\t\tallowance: publicAllowance(scope.allowance),\n\t\t};\n\t});\n}\n\n/** A labeled, display-safe view that distinguishes harness defaults from model-scoped limits. */\nexport function allowanceReport(discovery: HarnessDiscovery[], snapshot: AllowanceSnapshot) {\n\tconst available = applyAllowances(discovery, snapshot);\n\treturn available.filter((item) => item.installed).map((item) => ({\n\t\t\tharness: item.harness,\n\t\t\tharnessDefault: publicAllowance(snapshot.harnesses[item.harness]?.default ?? unknown()),\n\t\t\tmodelScopes: allowanceScopesForHarness(item),\n\t\t}));\n}\n","import type { HarnessId } from \"@tokensize/agent-router\";\n\nexport function executionArgs(\n\tharness: HarnessId,\n\tmodel: string,\n\tpermission: \"inspect\" | \"edit\" | \"test\" | \"network\",\n\tcwd: string,\n): string[] {\n\tif (harness === \"codex\") {\n\t\treturn [\"exec\", \"-C\", cwd, \"-s\", permission === \"inspect\" ? \"read-only\" : \"workspace-write\", \"--json\", \"-m\", model, \"-\"];\n\t}\n\tif (harness === \"claude\") {\n\t\treturn [\"-p\", \"--model\", model, \"--output-format\", \"json\", \"--permission-mode\", permission === \"inspect\" ? \"plan\" : \"acceptEdits\", \"--no-session-persistence\"];\n\t}\n\tif (harness === \"cursor\") {\n\t\treturn [\"-p\", \"--output-format\", \"json\", \"--mode\", \"plan\", \"--model\", model, \"--workspace\", cwd, \"--trust\"];\n\t}\n\tif (harness === \"opencode\") {\n\t\treturn [\"run\", \"--model\", model, \"--agent\", \"plan\", \"--format\", \"json\", \"--dir\", cwd];\n\t}\n\tthrow new Error(`execution adapter for ${harness} is unavailable`);\n}\n"],"mappings":";AAAA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MAAM,GAAG,gBAAgB,EAAE;AAAA,EACjP;AAAA,EAEA,MAAc,eAAe,QAAuB,OAA6C;AAChG,QAAI,CAAC,OAAO,MAAO;AACnB,QAAI;AACH,YAAM,KAAK,eAAe,OAAO,OAAO,OAAO,EAAE,cAAc,OAAO,MAAM,cAAc,CAAC;AAAA,IAC5F,QAAQ;AAAA,IAAgF;AAAA,EACzF;AAAA,EAEA,MAAM,SAAS,SAAmK;AACjL,UAAM,SAAS,MAAM,YAAY,QAAQ,WAAW,QAAQ,IAAI;AAChE,WAAO,KAAK,IAAI,sBAAsB,EAAE,QAAQ,QAAQ,MAAM,KAAK,UAAU,EAAE,eAAe,6BAA6B,SAAS,OAAO,MAAM,SAAS,eAAe,OAAO,MAAM,eAAe,gBAAgBF,YAAW,GAAG,QAAQ,QAAQ,gBAAgB,UAAU,WAAW,YAAY,mBAAmB,OAAO,MAAM,KAAK,UAAU,mBAAmB,MAAM,cAAc,QAAQ,gBAAgB,UAAU,IAAI,GAAG,cAAc,QAAQ,gBAAgB,UAAU,IAAI,GAAG,SAAS,GAAG,OAAO,EAAE,wBAAwB,OAAO,MAAM,SAAS,eAAe,QAAQ,YAAY,GAAG,SAAS,EAAE,SAAS,GAAG,WAAW,GAAG,aAAa,GAAG,gBAAgB,EAAE,EAAE,CAAC,EAAE,CAAC;AAAA,EACjpB;AACD;AAEO,SAAS,sBAAsB,SAAmD;AAAE,SAAO,IAAI,gBAAgB,OAAO;AAAG;","names":["randomUUID","access","mkdir","readFile","rename","writeFile","path","mkdir","readFile","rename","writeFile","os","path","path","os","spawn","readFile","mkdir","writeFile","rename","spawn","access","mkdir","readFile","rename","writeFile","path","status","path","executable","spawn","access","collect","readFile","mkdir","writeFile","rename","model","model","home","path","value","readFile","mkdir","writeFile","randomUUID","rename","randomUUID","model","access"]}
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@tokensize/agent-client",
3
+ "version": "0.3.0-beta.0",
4
+ "description": "Canonical local TokenSize client for discovery, routing, authorization, execution, and feedback",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
9
+ "files": ["dist", "README.md", "LICENSE"],
10
+ "repository": { "type": "git", "url": "git+https://github.com/tokensize/tokensize.git", "directory": "packages/agent-client" },
11
+ "homepage": "https://tokensize.dev",
12
+ "keywords": ["ai", "agents", "delegation", "routing", "codex", "opencode"],
13
+ "publishConfig": { "access": "public", "provenance": true, "tag": "beta" },
14
+ "engines": { "node": ">=20" },
15
+ "scripts": {
16
+ "prebuild": "npm --prefix ../.. run build --workspace @tokensize/agent-router",
17
+ "build": "tsup",
18
+ "typecheck": "tsc --noEmit",
19
+ "test": "vitest run",
20
+ "prepack": "npm run build",
21
+ "prepublishOnly": "npm run typecheck && npm test"
22
+ },
23
+ "dependencies": {
24
+ "@tokensize/agent-router": "0.3.0-beta.0"
25
+ },
26
+ "devDependencies": {
27
+ "@types/node": "^26.1.1",
28
+ "tsup": "^8.5.0",
29
+ "typescript": "^5.5.2",
30
+ "vitest": "^4.1.10"
31
+ },
32
+ "license": "MIT"
33
+ }