@tangle-network/agent-app 4.0.0 → 4.0.2
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.
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/index.d.ts +2 -1
- package/dist/agent-profiles/index.js +1 -1
- package/dist/chat-routes/index.js +12 -17
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/visible-text.d.ts +7 -0
- package/dist/{chunk-AFMLLZWU.js → chunk-GWATTXFR.js} +3 -3
- package/dist/{chunk-AFMLLZWU.js.map → chunk-GWATTXFR.js.map} +1 -1
- package/dist/{chunk-HES3IABJ.js → chunk-JKYCXQFI.js} +2 -2
- package/dist/{chunk-PABZALSD.js → chunk-LBMFQLBS.js} +9 -6
- package/dist/{chunk-PABZALSD.js.map → chunk-LBMFQLBS.js.map} +1 -1
- package/dist/{chunk-5DAEU3CP.js → chunk-SJKQUTGU.js} +11 -6
- package/dist/chunk-SJKQUTGU.js.map +1 -0
- package/dist/{chunk-JSWBJBPM.js → chunk-W5YQZEE4.js} +15 -10
- package/dist/chunk-W5YQZEE4.js.map +1 -0
- package/dist/{chunk-PISTUUEZ.js → chunk-XCUT2I52.js} +25 -12
- package/dist/{chunk-PISTUUEZ.js.map → chunk-XCUT2I52.js.map} +1 -1
- package/dist/{chunk-BRQ2SC6V.js → chunk-XKVJQVOT.js} +2 -1
- package/dist/chunk-XKVJQVOT.js.map +1 -0
- package/dist/conformance/cli.js +2 -2
- package/dist/conformance/cli.js.map +1 -1
- package/dist/conformance/index.js +1 -1
- package/dist/conformance/run.d.ts +3 -2
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +5 -3
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/index.js +4 -2
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.d.ts +15 -0
- package/dist/runtime/router-turn.js +3 -1
- package/package.json +1 -1
- package/dist/chunk-5DAEU3CP.js.map +0 -1
- package/dist/chunk-BRQ2SC6V.js.map +0 -1
- package/dist/chunk-JSWBJBPM.js.map +0 -1
- /package/dist/{chunk-HES3IABJ.js.map → chunk-JKYCXQFI.js.map} +0 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Apply a product's final-text transform (a PII redactor, for example) to every
|
|
3
|
+
* stored part a reader sees as words: the answer's text parts and the reasoning
|
|
4
|
+
* parts, which also hold a Router turn's pre-tool narration. One rule for the
|
|
5
|
+
* final row, the draft row and the detached-turn row.
|
|
6
|
+
*/
|
|
7
|
+
export declare function transformVisibleTextParts<T>(parts: readonly T[], transform: (text: string) => string | Promise<string>): Promise<T[]>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
runRouterTurn
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-XCUT2I52.js";
|
|
4
4
|
|
|
5
5
|
// src/runtime/protected-model.ts
|
|
6
6
|
var GATEWAY_ORIGIN = "https://candidate-router.tangle.tools";
|
|
@@ -139,7 +139,7 @@ async function runProtectedRouterTurn(options) {
|
|
|
139
139
|
let settlement;
|
|
140
140
|
let resolvedModel;
|
|
141
141
|
const result = (failure) => {
|
|
142
|
-
const base = turn ?? { text: "", servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [] };
|
|
142
|
+
const base = turn ?? { text: "", answer: "", servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [] };
|
|
143
143
|
const { failure: _turnFailure, continuation: _continuation, ...rest } = base;
|
|
144
144
|
return { ...rest, ...settlement ? { settlement } : {}, ...failure ? { failure } : {} };
|
|
145
145
|
};
|
|
@@ -217,4 +217,4 @@ export {
|
|
|
217
217
|
createRouterProtectedModelPort,
|
|
218
218
|
runProtectedRouterTurn
|
|
219
219
|
};
|
|
220
|
-
//# sourceMappingURL=chunk-
|
|
220
|
+
//# sourceMappingURL=chunk-GWATTXFR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/protected-model.ts","../src/runtime/protected-router-turn.ts"],"sourcesContent":["import type { AgentCandidateModelGrantClient, AgentCandidateModelPort } from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n // Runtime's candidate execution loads agent-eval and every agent-interface schema, so it loads on a protected\n // turn's first call instead of at Worker startup.\n const port = import('@tangle-network/agent-runtime/candidate-execution').then(({ createProtectedAgentCandidateModelPort }) =>\n createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n }))\n void port.catch(() => undefined)\n return {\n resolve: async (value) => (await port).resolve(value),\n reserveGrant: async (value) => (await port).reserveGrant(value),\n activateGrant: async (value) => (await port).activateGrant(value),\n settleGrant: async (value) => {\n const settlement = await (await port).settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n","/**\n * A Router turn under a protected model grant.\n *\n * Runtime resolves, reserves, activates and settles the grant around exactly\n * one `runRouterTurn` (`runProtectedAgentCandidateModelGrant`); the turn's model\n * calls use the grant's scoped key and base URL; the settled ledger is the\n * turn's only usage. GTM's bounded lane and Legal's paid consultations run here\n * through `createProtectedRuntimeChatProducer`, on the same engine as every\n * other Router turn. This module stays off the `./router-turn` entry: the grant\n * client pulls agent-runtime chunks a Worker bundle cannot build\n * (tests/router-turn-entry.test.ts).\n *\n * Every refusal and failure is a typed outcome. Codes:\n * - `grant_deadline`, `grant_model_unsupported`, `grant_activation_missing`:\n * refused before any model call.\n * - `grant_failed`: the grant could not be resolved, reserved or activated.\n * - `grant_unsettled`: the turn failed and its grant did not settle either.\n * - `settlement_over_limit`, `settlement_unauthorized_reasoning`,\n * `settlement_audit_failed`: the turn answered, but its settled ledger failed\n * a check; the answer stands and the turn still fails.\n * - `turn_deadline`: the turn reached the grant's deadline or its own budget.\n * A grant turn never continues: finishing it would need a second grant.\n * - Anything else is the turn's own failure (`turn_aborted`, `turn_tool_limit`,\n * `model_http_<status>`, ...), settled as `failed`.\n */\nimport type { RunProtectedAgentCandidateModelGrantOptions } from '@tangle-network/agent-runtime/candidate-execution'\nimport { ProtectedModelSettlementError } from './protected-model'\nimport { runRouterTurn, type RouterTurnFailure, type RouterTurnOptions, type RouterTurnOutcome } from './router-turn'\n\n/** Runtime's grant inputs for one turn: the port, the model request, the reservation and its deadline. */\nexport type RouterTurnGrant = Omit<RunProtectedAgentCandidateModelGrantOptions<void>, 'execute'>\n\ntype GrantSettlement = Awaited<ReturnType<RouterTurnGrant['port']['settleGrant']>>\n\n/** A turn under a grant. The grant supplies the key and base URL; one grant never repeats or continues a turn.\n * Placement is decided before a grant is reserved, so it is not an option here. */\nexport type ProtectedRouterTurnOptions = Omit<RouterTurnOptions, 'apiKey' | 'baseUrl' | 'repeat' | 'placement' | 'continueFrom'> & {\n grant: RouterTurnGrant\n}\n\n/** A grant turn's outcome. It carries no `continuation`: a turn at its deadline fails as `turn_deadline`. */\nexport interface ProtectedRouterTurnOutcome extends Omit<RouterTurnOutcome, 'continuation'> {\n /** What the grant settled, present whenever it settled, including for a failed turn. */\n settlement?: RouterTurnSettlement\n}\n\n/** What the grant settled for the turn. */\nexport interface RouterTurnSettlement {\n /** Runtime's settled ledger, retained even when a check on it fails. */\n receipt: GrantSettlement\n /** The model the grant resolved and reserved. */\n model?: string\n usage: { inputTokens: number; outputTokens: number; reasoningTokens: number; costUsd: number }\n /** Router certified the usage within the grant's limits, and no call reasoned under a grant\n * that disabled reasoning. */\n budgetEnforced: boolean\n}\n\n/**\n * Providers whose client function tools are verified over Chat Completions with\n * reasoning disabled. Router refuses provider-hosted tools and cache markers on\n * candidate grants, so tool-result text is billed as input and accounted input\n * covers OpenAI's automatic cached prefix.\n */\nconst GRANT_PROVIDERS: ReadonlySet<string> = new Set(['anthropic', 'openai'])\n\nclass GrantRefusal extends Error {\n constructor(readonly failure: RouterTurnFailure) {\n super(failure.message)\n this.name = 'GrantRefusal'\n }\n}\n\nconst refuse = (code: string, message: string) => new GrantRefusal({ code, message })\n\nfunction failureOf(error: unknown): RouterTurnFailure {\n if (error instanceof GrantRefusal) return error.failure\n if (error instanceof ProtectedModelSettlementError) return { code: 'settlement_audit_failed', message: error.message }\n if (error instanceof AggregateError) return { code: 'grant_unsettled', message: error.message }\n return { code: 'grant_failed', message: error instanceof Error ? error.message : 'The model grant failed.' }\n}\n\n/** Run one `runRouterTurn` under `options.grant`. */\nexport async function runProtectedRouterTurn(options: ProtectedRouterTurnOptions): Promise<ProtectedRouterTurnOutcome> {\n const { grant, ...turnOptions } = options\n let turn: RouterTurnOutcome | undefined\n let settlement: RouterTurnSettlement | undefined\n let resolvedModel: string | undefined\n const result = (failure?: RouterTurnFailure): ProtectedRouterTurnOutcome => {\n const base: RouterTurnOutcome = turn\n ?? { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [] }\n // The grant's verdict replaces the turn's own failure, and a grant turn never continues.\n const { failure: _turnFailure, continuation: _continuation, ...rest } = base\n return { ...rest, ...(settlement ? { settlement } : {}), ...(failure ? { failure } : {}) }\n }\n if (options.signal?.aborted) return result({ code: 'turn_aborted', message: 'The turn was cancelled.' })\n if (Date.now() >= grant.deadlineAtMs) return result({ code: 'grant_deadline', message: 'Protected execution deadline expired' })\n try {\n const { runProtectedAgentCandidateModelGrant } = await import('@tangle-network/agent-runtime/candidate-execution')\n await runProtectedAgentCandidateModelGrant({\n ...grant,\n port: {\n resolve: async input => {\n const resolved = await grant.port.resolve(input)\n resolvedModel = resolved.model\n return resolved\n },\n reserveGrant: input => grant.port.reserveGrant(input),\n activateGrant: input => grant.port.activateGrant(input),\n // Runtime settles failed executions before rethrowing. Retain that receipt too.\n settleGrant: async input => {\n let auditError: ProtectedModelSettlementError | undefined\n const receipt = await grant.port.settleGrant(input).catch(error => {\n if (!(error instanceof ProtectedModelSettlementError)) throw error\n auditError = error\n return error.settlement\n })\n const usage = {\n inputTokens: receipt.calls.reduce((sum, call) => sum + call.accountedInputTokens, 0),\n outputTokens: receipt.calls.reduce((sum, call) => sum + call.outputTokens, 0),\n reasoningTokens: receipt.calls.reduce((sum, call) => sum + call.reasoningTokens, 0),\n costUsd: receipt.calls.reduce((sum, call) => sum + call.costUsdNanos, 0) / 1e9,\n }\n // Execution limits carry no reasoning allowance, so a provider that\n // reasons under a disabled-reasoning grant exceeded what was authorized.\n const unauthorizedReasoning = usage.reasoningTokens > 0 && grant.resolve.reasoningEffort === 'none'\n const budgetEnforced = receipt.usageWithinLimits && !unauthorizedReasoning\n settlement = { receipt, ...(resolvedModel ? { model: resolvedModel } : {}), usage, budgetEnforced }\n if (unauthorizedReasoning) {\n throw refuse('settlement_unauthorized_reasoning', 'Provider reported reasoning tokens although reasoning was disabled')\n }\n if (!budgetEnforced) throw refuse('settlement_over_limit', 'Provider settlement exceeded execution limits')\n if (auditError) throw auditError\n return receipt\n },\n },\n execute: async ({ activation, resolved }) => {\n if (options.signal?.aborted) throw refuse('turn_aborted', 'The turn was cancelled.')\n if (Date.now() >= grant.deadlineAtMs) throw refuse('grant_deadline', 'Protected execution deadline expired')\n if (!GRANT_PROVIDERS.has(resolved.provider) || resolved.reasoningEffort !== 'none') {\n throw refuse('grant_model_unsupported', 'Protected chat currently requires an Anthropic or OpenAI model without reasoning')\n }\n const apiKey = activation.env.OPENAI_API_KEY\n const baseUrl = activation.env.OPENAI_BASE_URL\n if (!apiKey || !baseUrl) throw refuse('grant_activation_missing', 'Protected Router activation is missing')\n const remainingMs = Math.max(1, grant.deadlineAtMs - Date.now())\n // One grant is one bounded unit: no automatic second billable call, and the\n // grant's deadline ends the model call in flight.\n turn = await runRouterTurn({\n ...turnOptions, apiKey, baseUrl, repeat: false,\n budgetMs: Math.min(options.budgetMs ?? remainingMs, remainingMs),\n signal: AbortSignal.any([AbortSignal.timeout(remainingMs), ...(options.signal ? [options.signal] : [])]),\n })\n // A turn past its deadline fails here: finishing it would need a second grant.\n // At its budget the turn returns a continuation; under a grant that is the deadline.\n // The grant's timeout aborts the call in flight; that is the deadline too, not a cancellation.\n if (turn.continuation || (turn.failure?.code === 'turn_aborted' && Date.now() >= grant.deadlineAtMs)) {\n throw refuse('turn_deadline', 'Protected execution deadline expired')\n }\n if (turn.failure) throw new GrantRefusal(turn.failure)\n },\n })\n } catch (error) {\n return result(failureOf(error))\n }\n return result()\n}\n"],"mappings":";;;;;AAEA,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAAA,EACvB;AAAA,EAAuB;AAAA,EAA0B;AAAA,EAAkB;AAAA,EACnE;AAAA,EAAqB;AAAA,EAAwB;AAC/C;AAWO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAqB,YAAyE,OAAgB;AAC5G,UAAM,oEAAoE,EAAE,MAAM,CAAC;AADhE;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGO,SAAS,+BAA+B,SAAmE;AAChH,MAAI,CAAC,QAAQ,UAAU,CAAC,OAAO,SAAS,QAAQ,UAAU,KAAK,QAAQ,cAAc,KAChF,CAAC,OAAO,cAAc,KAAK,MAAM,QAAQ,aAAa,GAAa,CAAC,GAAG;AAC1E,UAAM,IAAI,MAAM,0EAA0E;AAAA,EAC5F;AACA,QAAM,WAAW,oBAAI,IAA4C;AACjE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,CAAE,CAAC;AAAA,QACzG,CAAC;AAID,YAAI,KAAK,gBAAiB,KAAK,SAAS,SAAS,kBAAkB,KAAK,IAAI,KAAK,MAAM,cAAe;AACpG,gBAAM,OAAO,iBAAiB,sCAAsC;AAAA,QACtE;AACA,YAAI,KAAK,QAAS,OAAM,IAAI,aAAa,KAAK,OAAO;AAAA,MACvD;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,WAAO,OAAO,UAAU,KAAK,CAAC;AAAA,EAChC;AACA,SAAO,OAAO;AAChB;","names":["body","value"]}
|
|
1
|
+
{"version":3,"sources":["../src/runtime/protected-model.ts","../src/runtime/protected-router-turn.ts"],"sourcesContent":["import type { AgentCandidateModelGrantClient, AgentCandidateModelPort } from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n // Runtime's candidate execution loads agent-eval and every agent-interface schema, so it loads on a protected\n // turn's first call instead of at Worker startup.\n const port = import('@tangle-network/agent-runtime/candidate-execution').then(({ createProtectedAgentCandidateModelPort }) =>\n createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n }))\n void port.catch(() => undefined)\n return {\n resolve: async (value) => (await port).resolve(value),\n reserveGrant: async (value) => (await port).reserveGrant(value),\n activateGrant: async (value) => (await port).activateGrant(value),\n settleGrant: async (value) => {\n const settlement = await (await port).settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n","/**\n * A Router turn under a protected model grant.\n *\n * Runtime resolves, reserves, activates and settles the grant around exactly\n * one `runRouterTurn` (`runProtectedAgentCandidateModelGrant`); the turn's model\n * calls use the grant's scoped key and base URL; the settled ledger is the\n * turn's only usage. GTM's bounded lane and Legal's paid consultations run here\n * through `createProtectedRuntimeChatProducer`, on the same engine as every\n * other Router turn. This module stays off the `./router-turn` entry: the grant\n * client pulls agent-runtime chunks a Worker bundle cannot build\n * (tests/router-turn-entry.test.ts).\n *\n * Every refusal and failure is a typed outcome. Codes:\n * - `grant_deadline`, `grant_model_unsupported`, `grant_activation_missing`:\n * refused before any model call.\n * - `grant_failed`: the grant could not be resolved, reserved or activated.\n * - `grant_unsettled`: the turn failed and its grant did not settle either.\n * - `settlement_over_limit`, `settlement_unauthorized_reasoning`,\n * `settlement_audit_failed`: the turn answered, but its settled ledger failed\n * a check; the answer stands and the turn still fails.\n * - `turn_deadline`: the turn reached the grant's deadline or its own budget.\n * A grant turn never continues: finishing it would need a second grant.\n * - Anything else is the turn's own failure (`turn_aborted`, `turn_tool_limit`,\n * `model_http_<status>`, ...), settled as `failed`.\n */\nimport type { RunProtectedAgentCandidateModelGrantOptions } from '@tangle-network/agent-runtime/candidate-execution'\nimport { ProtectedModelSettlementError } from './protected-model'\nimport { runRouterTurn, type RouterTurnFailure, type RouterTurnOptions, type RouterTurnOutcome } from './router-turn'\n\n/** Runtime's grant inputs for one turn: the port, the model request, the reservation and its deadline. */\nexport type RouterTurnGrant = Omit<RunProtectedAgentCandidateModelGrantOptions<void>, 'execute'>\n\ntype GrantSettlement = Awaited<ReturnType<RouterTurnGrant['port']['settleGrant']>>\n\n/** A turn under a grant. The grant supplies the key and base URL; one grant never repeats or continues a turn.\n * Placement is decided before a grant is reserved, so it is not an option here. */\nexport type ProtectedRouterTurnOptions = Omit<RouterTurnOptions, 'apiKey' | 'baseUrl' | 'repeat' | 'placement' | 'continueFrom'> & {\n grant: RouterTurnGrant\n}\n\n/** A grant turn's outcome. It carries no `continuation`: a turn at its deadline fails as `turn_deadline`. */\nexport interface ProtectedRouterTurnOutcome extends Omit<RouterTurnOutcome, 'continuation'> {\n /** What the grant settled, present whenever it settled, including for a failed turn. */\n settlement?: RouterTurnSettlement\n}\n\n/** What the grant settled for the turn. */\nexport interface RouterTurnSettlement {\n /** Runtime's settled ledger, retained even when a check on it fails. */\n receipt: GrantSettlement\n /** The model the grant resolved and reserved. */\n model?: string\n usage: { inputTokens: number; outputTokens: number; reasoningTokens: number; costUsd: number }\n /** Router certified the usage within the grant's limits, and no call reasoned under a grant\n * that disabled reasoning. */\n budgetEnforced: boolean\n}\n\n/**\n * Providers whose client function tools are verified over Chat Completions with\n * reasoning disabled. Router refuses provider-hosted tools and cache markers on\n * candidate grants, so tool-result text is billed as input and accounted input\n * covers OpenAI's automatic cached prefix.\n */\nconst GRANT_PROVIDERS: ReadonlySet<string> = new Set(['anthropic', 'openai'])\n\nclass GrantRefusal extends Error {\n constructor(readonly failure: RouterTurnFailure) {\n super(failure.message)\n this.name = 'GrantRefusal'\n }\n}\n\nconst refuse = (code: string, message: string) => new GrantRefusal({ code, message })\n\nfunction failureOf(error: unknown): RouterTurnFailure {\n if (error instanceof GrantRefusal) return error.failure\n if (error instanceof ProtectedModelSettlementError) return { code: 'settlement_audit_failed', message: error.message }\n if (error instanceof AggregateError) return { code: 'grant_unsettled', message: error.message }\n return { code: 'grant_failed', message: error instanceof Error ? error.message : 'The model grant failed.' }\n}\n\n/** Run one `runRouterTurn` under `options.grant`. */\nexport async function runProtectedRouterTurn(options: ProtectedRouterTurnOptions): Promise<ProtectedRouterTurnOutcome> {\n const { grant, ...turnOptions } = options\n let turn: RouterTurnOutcome | undefined\n let settlement: RouterTurnSettlement | undefined\n let resolvedModel: string | undefined\n const result = (failure?: RouterTurnFailure): ProtectedRouterTurnOutcome => {\n const base: RouterTurnOutcome = turn\n ?? { text: '', answer: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [] }\n // The grant's verdict replaces the turn's own failure, and a grant turn never continues.\n const { failure: _turnFailure, continuation: _continuation, ...rest } = base\n return { ...rest, ...(settlement ? { settlement } : {}), ...(failure ? { failure } : {}) }\n }\n if (options.signal?.aborted) return result({ code: 'turn_aborted', message: 'The turn was cancelled.' })\n if (Date.now() >= grant.deadlineAtMs) return result({ code: 'grant_deadline', message: 'Protected execution deadline expired' })\n try {\n const { runProtectedAgentCandidateModelGrant } = await import('@tangle-network/agent-runtime/candidate-execution')\n await runProtectedAgentCandidateModelGrant({\n ...grant,\n port: {\n resolve: async input => {\n const resolved = await grant.port.resolve(input)\n resolvedModel = resolved.model\n return resolved\n },\n reserveGrant: input => grant.port.reserveGrant(input),\n activateGrant: input => grant.port.activateGrant(input),\n // Runtime settles failed executions before rethrowing. Retain that receipt too.\n settleGrant: async input => {\n let auditError: ProtectedModelSettlementError | undefined\n const receipt = await grant.port.settleGrant(input).catch(error => {\n if (!(error instanceof ProtectedModelSettlementError)) throw error\n auditError = error\n return error.settlement\n })\n const usage = {\n inputTokens: receipt.calls.reduce((sum, call) => sum + call.accountedInputTokens, 0),\n outputTokens: receipt.calls.reduce((sum, call) => sum + call.outputTokens, 0),\n reasoningTokens: receipt.calls.reduce((sum, call) => sum + call.reasoningTokens, 0),\n costUsd: receipt.calls.reduce((sum, call) => sum + call.costUsdNanos, 0) / 1e9,\n }\n // Execution limits carry no reasoning allowance, so a provider that\n // reasons under a disabled-reasoning grant exceeded what was authorized.\n const unauthorizedReasoning = usage.reasoningTokens > 0 && grant.resolve.reasoningEffort === 'none'\n const budgetEnforced = receipt.usageWithinLimits && !unauthorizedReasoning\n settlement = { receipt, ...(resolvedModel ? { model: resolvedModel } : {}), usage, budgetEnforced }\n if (unauthorizedReasoning) {\n throw refuse('settlement_unauthorized_reasoning', 'Provider reported reasoning tokens although reasoning was disabled')\n }\n if (!budgetEnforced) throw refuse('settlement_over_limit', 'Provider settlement exceeded execution limits')\n if (auditError) throw auditError\n return receipt\n },\n },\n execute: async ({ activation, resolved }) => {\n if (options.signal?.aborted) throw refuse('turn_aborted', 'The turn was cancelled.')\n if (Date.now() >= grant.deadlineAtMs) throw refuse('grant_deadline', 'Protected execution deadline expired')\n if (!GRANT_PROVIDERS.has(resolved.provider) || resolved.reasoningEffort !== 'none') {\n throw refuse('grant_model_unsupported', 'Protected chat currently requires an Anthropic or OpenAI model without reasoning')\n }\n const apiKey = activation.env.OPENAI_API_KEY\n const baseUrl = activation.env.OPENAI_BASE_URL\n if (!apiKey || !baseUrl) throw refuse('grant_activation_missing', 'Protected Router activation is missing')\n const remainingMs = Math.max(1, grant.deadlineAtMs - Date.now())\n // One grant is one bounded unit: no automatic second billable call, and the\n // grant's deadline ends the model call in flight.\n turn = await runRouterTurn({\n ...turnOptions, apiKey, baseUrl, repeat: false,\n budgetMs: Math.min(options.budgetMs ?? remainingMs, remainingMs),\n signal: AbortSignal.any([AbortSignal.timeout(remainingMs), ...(options.signal ? [options.signal] : [])]),\n })\n // A turn past its deadline fails here: finishing it would need a second grant.\n // At its budget the turn returns a continuation; under a grant that is the deadline.\n // The grant's timeout aborts the call in flight; that is the deadline too, not a cancellation.\n if (turn.continuation || (turn.failure?.code === 'turn_aborted' && Date.now() >= grant.deadlineAtMs)) {\n throw refuse('turn_deadline', 'Protected execution deadline expired')\n }\n if (turn.failure) throw new GrantRefusal(turn.failure)\n },\n })\n } catch (error) {\n return result(failureOf(error))\n }\n return result()\n}\n"],"mappings":";;;;;AAEA,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,mBAAmB;AAAA,EACvB;AAAA,EAAuB;AAAA,EAA0B;AAAA,EAAkB;AAAA,EACnE;AAAA,EAAqB;AAAA,EAAwB;AAC/C;AAWO,IAAM,gCAAN,cAA4C,MAAM;AAAA,EACvD,YAAqB,YAAyE,OAAgB;AAC5G,UAAM,oEAAoE,EAAE,MAAM,CAAC;AADhE;AAEnB,SAAK,OAAO;AAAA,EACd;AAA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AAG,MAAM,eAAe,KAAK,IAAI,CAAC;AAG/D,eAAO,MAAM,cAAc;AAAA,UACzB,GAAG;AAAA,UAAa;AAAA,UAAQ;AAAA,UAAS,QAAQ;AAAA,UACzC,UAAU,KAAK,IAAI,QAAQ,YAAY,aAAa,WAAW;AAAA,UAC/D,QAAQ,YAAY,IAAI,CAAC,YAAY,QAAQ,WAAW,GAAG,GAAI,QAAQ,SAAS,CAAC,QAAQ,MAAM,IAAI,CAAC,CAAE,CAAC;AAAA,QACzG,CAAC;AAID,YAAI,KAAK,gBAAiB,KAAK,SAAS,SAAS,kBAAkB,KAAK,IAAI,KAAK,MAAM,cAAe;AACpG,gBAAM,OAAO,iBAAiB,sCAAsC;AAAA,QACtE;AACA,YAAI,KAAK,QAAS,OAAM,IAAI,aAAa,KAAK,OAAO;AAAA,MACvD;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,WAAO,OAAO,UAAU,KAAK,CAAC;AAAA,EAChC;AACA,SAAO,OAAO;AAChB;","names":["body","value"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
TURN_USAGE_KEYS,
|
|
3
3
|
addStepFinishUsage
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-SJKQUTGU.js";
|
|
5
5
|
import {
|
|
6
6
|
asRecord,
|
|
7
7
|
asString,
|
|
@@ -446,4 +446,4 @@ export {
|
|
|
446
446
|
TOOL_ABORTED_ERROR,
|
|
447
447
|
observeNativeCompletion
|
|
448
448
|
};
|
|
449
|
-
//# sourceMappingURL=chunk-
|
|
449
|
+
//# sourceMappingURL=chunk-JKYCXQFI.js.map
|
|
@@ -349,13 +349,16 @@ async function checkDeployedApp(options) {
|
|
|
349
349
|
if (access) {
|
|
350
350
|
const open = access;
|
|
351
351
|
await check("plain-turn", async () => ({ value: true, detail: await plainTurn(open, turnMs) }));
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
352
|
+
const proof = options.computer ?? "digest";
|
|
353
|
+
if (proof !== "none") {
|
|
354
|
+
await check("computer-turn", async () => ({
|
|
355
|
+
value: true,
|
|
356
|
+
detail: await computerTurn(open, turnMs, proof, options.fileDir ?? "proof", options.computerModel ?? DEFAULT_COMPUTER_MODEL)
|
|
357
|
+
}));
|
|
358
|
+
}
|
|
356
359
|
} else {
|
|
357
360
|
blocked("plain-turn", "blocked by operator-access");
|
|
358
|
-
blocked("computer-turn", "blocked by operator-access");
|
|
361
|
+
if (options.computer !== "none") blocked("computer-turn", "blocked by operator-access");
|
|
359
362
|
}
|
|
360
363
|
const mintedKey = minted;
|
|
361
364
|
if (mintedKey && session) {
|
|
@@ -371,4 +374,4 @@ async function checkDeployedApp(options) {
|
|
|
371
374
|
export {
|
|
372
375
|
checkDeployedApp
|
|
373
376
|
};
|
|
374
|
-
//# sourceMappingURL=chunk-
|
|
377
|
+
//# sourceMappingURL=chunk-LBMFQLBS.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/conformance/session.ts","../src/conformance/revision.ts","../src/conformance/turns.ts","../src/conformance/run.ts"],"sourcesContent":["/**\n * Sign-in for the conformance runner: the two ways a member reaches an agent app, and one question both answer,\n * \"does the app accept this session?\". Nothing here is specific to an app; a product whose sign-in differs\n * fails the check with the status it answered.\n */\n\nexport type SignInMode = 'password' | 'sso'\n\n/** A check failed for a reason worth reporting; its message is the cause. */\nexport class Failure extends Error {}\n\nexport interface MemberSession {\n origin: string\n /** A request to the app as the signed-in member; `path` is root-relative. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n}\n\nconst REQUEST_MS = 30_000\n\n/** Cookies by origin: enough of a jar for one sign-in and the calls after it. */\nclass Jar {\n private readonly byOrigin = new Map<string, Map<string, string>>()\n\n header(url: string): string {\n return [...(this.byOrigin.get(new URL(url).origin) ?? [])].map(([name, value]) => `${name}=${value}`).join('; ')\n }\n\n async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers)\n const cookie = this.header(url)\n if (cookie) headers.set('cookie', cookie)\n const response = await fetch(url, { ...init, headers, redirect: 'manual', signal: init.signal ?? AbortSignal.timeout(REQUEST_MS) })\n this.absorb(url, response)\n return response\n }\n\n private absorb(url: string, response: Response): void {\n const origin = new URL(url).origin\n const jar = this.byOrigin.get(origin) ?? new Map<string, string>()\n for (const line of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = line.split(';')\n const eq = pair.indexOf('=')\n if (eq < 1) continue\n const name = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n const attribute = (key: string) => attributes.map(item => item.trim()).find(item => item.toLowerCase().startsWith(`${key}=`))?.slice(key.length + 1)\n const maxAge = attribute('max-age')\n const expires = attribute('expires')\n const gone = !value || (maxAge !== undefined && Number(maxAge) <= 0)\n || (maxAge === undefined && expires !== undefined && Date.parse(expires) <= Date.now())\n if (gone) jar.delete(name)\n else jar.set(name, value)\n }\n this.byOrigin.set(origin, jar)\n }\n}\n\nconst snippet = async (response: Response) => (await response.text().catch(() => '')).replace(/\\s+/g, ' ').slice(0, 160)\n\n/** A sign-in POST. An auth service that answers 429 is asked again after its Retry-After (at most 20 s), twice at most. */\nasync function postSignIn(jar: Jar, origin: string, email: string, password: string): Promise<Response> {\n for (let attempt = 0; ; attempt += 1) {\n const response = await jar.send(`${origin}/api/auth/sign-in/email`, {\n method: 'POST', headers: { 'content-type': 'application/json', origin }, body: JSON.stringify({ email, password }),\n })\n if (response.status !== 429 || attempt === 2) return response\n const wait = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await new Promise(resolve => setTimeout(resolve, Math.min(20, Number.isFinite(wait) && wait > 0 ? wait : 5) * 1000))\n }\n}\n\nasync function passwordSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const response = await postSignIn(jar, origin, email, password)\n if (response.status !== 200) throw new Failure(`password sign-in answered ${response.status}: ${await snippet(response)}`)\n}\n\nconst TANGLE_AUTH_PATH = /(^|\\/)auth\\/tangle\\//\n\n/**\n * The app's \"Log in with Tangle\": its start route sends the browser to Platform, Platform signs the member in and\n * authorizes, and the app's callback sets its own session. Apps mount the start route at `/auth/tangle/start` or\n * under `/api`.\n */\nasync function ssoSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const answers: string[] = []\n let location: string | null = null\n for (const path of ['/auth/tangle/start', '/api/auth/tangle/start']) {\n const start = await jar.send(`${origin}${path}`)\n location = start.headers.get('location')\n if (location) break\n answers.push(`${path} answered ${start.status}`)\n }\n if (!location) throw new Failure(`SSO start sent the member nowhere (${answers.join('; ')})`)\n const authorize = new URL(location, origin)\n const platform = authorize.origin\n const member = await postSignIn(jar, platform, email, password)\n if (member.status !== 200) throw new Failure(`Platform sign-in answered ${member.status}: ${await snippet(member)}`)\n let next = authorize.href\n for (let hop = 0; hop < 8; hop += 1) {\n const response = await jar.send(next)\n const redirect = response.headers.get('location')\n if (!redirect) throw new Failure(`SSO stopped at ${new URL(next).pathname} with ${response.status}`)\n const url = new URL(redirect, next)\n if (url.origin === origin && !TANGLE_AUTH_PATH.test(url.pathname)) {\n if (url.pathname.startsWith('/login') || url.searchParams.has('error') || url.searchParams.get('connection') === 'failed') {\n throw new Failure(`the app's SSO callback sent the member to ${url.pathname}${url.search.slice(0, 80)}`)\n }\n return\n }\n next = url.href\n }\n throw new Failure('SSO did not return to the app within 8 redirects')\n}\n\n/** A redirect to sign-in or an error page is an app that did not accept the session. */\nasync function sessionAccepted(session: MemberSession): Promise<string> {\n const who = await session.fetch('/api/auth/get-session')\n if (who.status === 200) {\n const body = await who.json().catch(() => null) as { user?: { id?: unknown } } | null\n if (typeof body?.user?.id === 'string' && body.user.id) return 'GET /api/auth/get-session returned the user'\n }\n const workspaces = await session.fetch('/api/workspaces')\n if (workspaces.status === 200) return 'GET /api/workspaces answered 200 as the member'\n throw new Failure(`signed in, but the app does not accept the session: GET /api/auth/get-session answered ${who.status}, GET /api/workspaces ${workspaces.status}`)\n}\n\n/** Signs in and proves the app accepts the session; the detail names the proof. */\nexport async function signIn(input: { origin: string; mode: SignInMode; email: string; password: string }): Promise<{ session: MemberSession; detail: string }> {\n const jar = new Jar()\n if (input.mode === 'password') await passwordSignIn(jar, input.origin, input.email, input.password)\n else await ssoSignIn(jar, input.origin, input.email, input.password)\n const session: MemberSession = {\n origin: input.origin,\n fetch: (path, init = {}) => {\n const headers = new Headers(init.headers)\n if (!headers.has('origin')) headers.set('origin', input.origin)\n return jar.send(`${input.origin}${path}`, { ...init, headers })\n },\n }\n return { session, detail: `${input.mode}: ${await sessionAccepted(session)}` }\n}\n","/**\n * The served revision, read the way an operator reads it: from the app's own `GET /api/health` body, or from the\n * `x-<app>-revision` / `x-<app>-version` header the app puts on its responses. An app that serves neither cannot\n * say what it is running, so a release cannot be told from the one before it.\n */\n\nimport { Failure } from './session.js'\n\nconst REVISION_HEADER = /^x-[a-z0-9-]+-(revision|version)$/i\nconst REQUEST_MS = 20_000\n\nconst text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The revision a health body carries: `revision`, or what `release` carries. */\nfunction fromHealth(body: unknown): string | null {\n if (!body || typeof body !== 'object') return null\n const record = body as Record<string, unknown>\n const release = record.release && typeof record.release === 'object' ? record.release as Record<string, unknown> : {}\n return text(record.revision) ?? text(release.revision) ?? text(release.sha) ?? text(release.tag)\n}\n\nfunction fromHeaders(response: Response): { name: string; value: string } | null {\n for (const [name, value] of response.headers) if (REVISION_HEADER.test(name) && value.trim()) return { name, value: value.trim() }\n return null\n}\n\n/**\n * Reads the revision, or throws a Failure naming every place it looked. `source` says where it was read, e.g.\n * `GET /api/health` or `GET / x-creative-revision`.\n */\nexport async function readRevision(origin: string, expect?: string): Promise<{ revision: string; source: string }> {\n const looked: string[] = []\n const found = await (async (): Promise<{ revision: string; source: string } | null> => {\n for (const path of ['/api/health', '/']) {\n let response: Response\n try {\n response = await fetch(`${origin}${path}`, { headers: { accept: 'application/json' }, redirect: 'manual', signal: AbortSignal.timeout(REQUEST_MS) })\n } catch (error) {\n looked.push(`GET ${path} failed (${error instanceof Error ? error.name : 'error'})`)\n continue\n }\n const header = fromHeaders(response)\n if (path === '/api/health' && response.ok) {\n const revision = fromHealth(await response.json().catch(() => null))\n if (revision) return { revision, source: 'GET /api/health' }\n }\n if (header) return { revision: header.value, source: `GET ${path} ${header.name}` }\n await response.body?.cancel().catch(() => {})\n looked.push(`GET ${path} answered ${response.status} without a revision`)\n }\n return null\n })()\n if (!found) throw new Failure(`the app serves no readable revision (${looked.join('; ')})`)\n if (expect) {\n const [a, b] = [found.revision.toLowerCase(), expect.trim().toLowerCase()]\n if (b.length < 7 || !(a.startsWith(b) || b.startsWith(a))) {\n throw new Failure(`the app serves revision ${found.revision} (${found.source}), not the expected ${expect}`)\n }\n }\n return found\n}\n","/**\n * The conformance turns, run through the operator API every agent app mounts the same way\n * (docs/operator-api.md), so one runner drives every product. The verdict is the settled turn the app stored.\n *\n * plain a reply with text;\n * computer a turn only the workspace computer can answer: either the digest of a fresh nonce, which the model\n * cannot know without running the command, or a file the computer saves that the app then serves back.\n */\n\nimport { createHash, randomBytes, randomUUID } from 'node:crypto'\nimport { createOperatorClient, type OperatorClient } from '../operator/client.js'\nimport type { OperatorTurn, OperatorWorkspace } from '../operator/contract.js'\nimport { Failure, type MemberSession } from './session.js'\n\nexport type ComputerProof = 'digest' | 'file'\n\nconst REQUEST_MS = 30_000\nconst KEY_LIFETIME_MS = 60 * 60_000\n\nexport interface OperatorAccess {\n client: OperatorClient\n workspace: OperatorWorkspace\n /** The app's own account of what the key may do. */\n scopes: readonly string[]\n}\n\n/** An expiring key for the signed-in member, through the route every app's API access page uses. */\nexport async function mintKey(session: MemberSession): Promise<{ id: string; key: string }> {\n const response = await session.fetch('/api/keys', {\n method: 'POST', headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(REQUEST_MS),\n body: JSON.stringify({\n name: `conformance ${new Date().toISOString()}`, scopes: ['operator:read', 'operator:run'],\n expiresAt: new Date(Date.now() + KEY_LIFETIME_MS).toISOString(), workspaceIds: [],\n }),\n })\n if (response.status === 404) {\n throw new Failure('the app has no key route (POST /api/keys answered 404), so a conformance turn has no credential; give it an operator key')\n }\n const body = await response.json().catch(() => null) as { id?: unknown; key?: unknown; error?: unknown } | null\n if (!response.ok || typeof body?.id !== 'string' || typeof body.key !== 'string') {\n throw new Failure(`POST /api/keys answered ${response.status}: ${typeof body?.error === 'string' ? body.error.slice(0, 160) : 'no key in the response'}`)\n }\n return { id: body.id, key: body.key }\n}\n\n/** Revokes a key this run created. Apps accept the id in the path, or in the body of the collection route. */\nexport async function revokeKey(session: MemberSession, id: string): Promise<void> {\n const byPath = await session.fetch(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE', signal: AbortSignal.timeout(REQUEST_MS) })\n if (byPath.ok) return\n const byBody = await session.fetch('/api/keys', {\n method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), signal: AbortSignal.timeout(REQUEST_MS),\n })\n if (byBody.ok) return\n throw new Failure(`the minted key ${id} was not revoked: DELETE /api/keys/:id answered ${byPath.status}, DELETE /api/keys ${byBody.status} (it expires within the hour)`)\n}\n\n/**\n * Opens the operator API with `key` and picks the workspace the turns run in: `workspace` is its id or exact name,\n * and omitted, the key must reach exactly one. `requestMs` bounds any one request, a held turn read included.\n */\nexport async function openOperatorAccess(\n { origin, key, workspace, requestMs }: { origin: string; key: string; workspace: string | undefined; requestMs: number },\n): Promise<OperatorAccess> {\n const client = createOperatorClient({\n origin,\n getApiKey: () => key,\n fetchImpl: (url, init) => fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(requestMs)]) : AbortSignal.timeout(requestMs) }),\n })\n const described = await client.describe()\n if (!described.succeeded) throw new Failure(`GET /api/operator/v1 answered ${described.status} ${described.code}: ${described.error.slice(0, 160)}`)\n const scopes = described.value.principal.scopes\n const missing = ['operator:read', 'operator:run'].filter(scope => !scopes.includes(scope) && !scopes.includes('*'))\n if (missing.length) throw new Failure(`the operator key lacks ${missing.join(' and ')}`)\n const listed = await client.listWorkspaces()\n if (!listed.succeeded) throw new Failure(`GET /api/operator/v1/workspaces answered ${listed.status} ${listed.code}: ${listed.error.slice(0, 160)}`)\n const chosen = workspace\n ? listed.value.filter(candidate => candidate.id === workspace || candidate.name === workspace)\n : listed.value.length === 1 ? listed.value : []\n if (chosen.length !== 1) {\n const names = listed.value.slice(0, 12).map(candidate => `${candidate.name} (${candidate.id.slice(0, 8)})`).join(', ')\n throw new Failure(workspace\n ? `${chosen.length} of the key's ${listed.value.length} workspaces match \"${workspace}\": ${names}`\n : `the key reaches ${listed.value.length} workspaces; name the canary workspace: ${names}`)\n }\n return { client, workspace: chosen[0]!, scopes }\n}\n\nconst reply = (turn: OperatorTurn) => (turn.reply?.content ?? '').trim()\n\n/** One turn on a new thread, followed until it settles. */\nasync function runTurn(access: OperatorAccess, title: string, content: string, turnMs: number, model?: string): Promise<{ turn: OperatorTurn; where: string }> {\n const turnId = randomUUID()\n const started = await access.client.startTurn(access.workspace.id, { turnId, content, title, ...(model ? { model } : {}) })\n if (!started.succeeded) throw new Failure(`the turn was refused: ${started.status} ${started.code}: ${started.error.slice(0, 200)}`)\n const where = `thread ${started.value.threadId}`\n const settled = await access.client.waitForTurn(access.workspace.id, started.value.threadId, started.value.turnId, { timeoutMs: turnMs })\n if (!settled.succeeded) throw new Failure(`reading the turn answered ${settled.status} ${settled.code}: ${settled.error.slice(0, 160)} (${where})`)\n const turn = settled.value\n if (turn.state === 'failed') throw new Failure(`the turn failed${turn.failure?.code ? ` (${turn.failure.code})` : ''}: ${(turn.failure?.message ?? 'no message').slice(0, 300)} (${where})`)\n if (turn.state === 'input-required' || turn.approvals.length > 0) throw new Failure(`the turn is waiting on a decision, which no one can answer in a conformance run (${where})`)\n if (turn.state !== 'succeeded') throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1000)} s (state ${turn.state}; ${where})`)\n return { turn, where }\n}\n\nexport async function plainTurn(access: OperatorAccess, turnMs: number): Promise<string> {\n const { turn, where } = await runTurn(access, 'Conformance: plain turn',\n 'Conformance check: reply with one short sentence confirming you can answer.', turnMs)\n if (!reply(turn)) throw new Failure(`the turn succeeded with an empty reply (${where})`)\n return `${reply(turn).length} characters from ${turn.model ?? 'an unreported model'} (${where})`\n}\n\nexport async function computerTurn(access: OperatorAccess, turnMs: number, proof: ComputerProof, fileDir: string, model: string): Promise<string> {\n const nonce = `conformance-${randomBytes(12).toString('hex')}`\n if (proof === 'digest') {\n const digest = createHash('sha256').update(nonce).digest('hex')\n const { turn, where } = await runTurn(access, 'Conformance: computer turn',\n 'Conformance check: run this exact shell command on the workspace computer (sandbox_run when you have it), then reply with only '\n + `the 64-character hex digest it prints:\\nprintf %s '${nonce}' | sha256sum`, turnMs, model)\n if (!reply(turn).includes(digest)) {\n throw new Failure(`the reply does not hold the digest of the fresh nonce, so the computer did not run the command: \"${reply(turn).slice(0, 160)}\" (${where})`)\n }\n return `the reply carries the digest ${digest.slice(0, 12)}… (${where})`\n }\n const path = `${fileDir.replace(/\\/+$/, '')}/${nonce}.md`\n const { where } = await runTurn(access, 'Conformance: computer turn',\n `Conformance check: use the workspace computer to save a file at ${path} whose whole content is this one line, then reply with the word saved:\\n${nonce}`, turnMs, model)\n const read = await access.client.readFile(access.workspace.id, path)\n if (!read.succeeded) throw new Failure(`the turn succeeded, but the app does not serve ${path}: ${read.status} ${read.code} (${where})`)\n if (read.value.content.trim() !== nonce) {\n throw new Failure(`${path} holds ${JSON.stringify(read.value.content.slice(0, 80))}, not the nonce (${where})`)\n }\n return `the app serves ${path} with the nonce (${where})`\n}\n","import { readRevision } from './revision.js'\nimport { Failure, signIn, type MemberSession, type SignInMode } from './session.js'\nimport { computerTurn, mintKey, openOperatorAccess, plainTurn, revokeKey, type ComputerProof, type OperatorAccess } from './turns.js'\n\nexport type CheckName = 'sign-in' | 'revision' | 'operator-access' | 'plain-turn' | 'computer-turn' | 'key-revoke'\n\n/**\n * One check's verdict. `blocked` means an earlier check it depends on failed, so nothing was measured; a blocked\n * check fails the run like a failed one, and its cause names the check that blocked it.\n */\nexport interface CheckResult {\n /** When the check started, ISO 8601. */\n at: string\n app: string\n url: string\n check: CheckName\n status: 'pass' | 'fail' | 'blocked'\n ms: number\n /** Why a failed or blocked check is not a pass. */\n cause?: string\n /** What a passing check observed: the revision read, the thread a turn ran in. */\n detail?: string\n}\n\nexport interface ConformanceOptions {\n /** A label for the result lines, e.g. `gtm`. */\n app: string\n /** The deployed origin, e.g. `https://gtm.tangle.tools`. */\n origin: string\n /** The member that signs in. Required: sign-in is the first thing a customer does. */\n member?: { mode: SignInMode; email: string; password: string }\n /** A key that already has `operator:read` and `operator:run`; without one, the signed-in member mints a one-hour key. */\n operatorKey?: string\n /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */\n workspace?: string\n /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back. */\n computer?: ComputerProof\n /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */\n computerModel?: string\n /** Where the `file` proof is saved, relative to the workspace root. */\n fileDir?: string\n /** The budget of each turn, a cold box included. */\n turnMs?: number\n /** Fail unless the served revision starts with, or is a prefix of, this. */\n expectRevision?: string\n /** Called with each result as it lands. */\n onResult?(result: CheckResult): void\n}\n\nconst DEFAULT_TURN_MS = 300_000\n// Company spend rule: checks run on the flat-rate plan; per-token models are for product serving with real users.\nconst DEFAULT_COMPUTER_MODEL = 'glm-5.3'\n\n/** Why an unexpected error is not a pass, in a line. */\nfunction describe(error: unknown): string {\n if (error instanceof Failure) return error.message\n if (error instanceof Error) {\n const cause = error.cause as { code?: unknown } | undefined\n return `${error.name}: ${error.message}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`\n }\n return String(error)\n}\n\n/** Runs the checks against one deployed app and returns every result, in the order they ran. */\nexport async function checkDeployedApp(options: ConformanceOptions): Promise<CheckResult[]> {\n const origin = options.origin.replace(/\\/+$/, '')\n const turnMs = options.turnMs ?? DEFAULT_TURN_MS\n const secrets = [options.member?.password, options.operatorKey].filter((value): value is string => Boolean(value && value.length >= 6))\n const redact = (text: string) => secrets.reduce((out, secret) => out.split(secret).join('[redacted]'), text)\n const results: CheckResult[] = []\n\n const record = (result: CheckResult) => {\n const clean = { ...result, ...(result.cause ? { cause: redact(result.cause) } : {}), ...(result.detail ? { detail: redact(result.detail) } : {}) }\n results.push(clean)\n options.onResult?.(clean)\n }\n /** Runs `body`; whatever it returns is the passing detail, whatever it throws is the cause. */\n async function check<T>(name: CheckName, body: () => Promise<{ value: T; detail?: string }>): Promise<T | undefined> {\n const at = new Date().toISOString()\n const started = Date.now()\n const base = { at, app: options.app, url: origin, check: name }\n try {\n const { value, detail } = await body()\n record({ ...base, status: 'pass', ms: Date.now() - started, ...(detail ? { detail } : {}) })\n return value\n } catch (error) {\n record({ ...base, status: 'fail', ms: Date.now() - started, cause: describe(error) })\n return undefined\n }\n }\n const blocked = (name: CheckName, because: string) =>\n record({ at: new Date().toISOString(), app: options.app, url: origin, check: name, status: 'blocked', ms: 0, cause: because })\n\n let session: MemberSession | undefined\n if (!options.member) {\n const at = new Date().toISOString()\n record({ at, app: options.app, url: origin, check: 'sign-in', status: 'fail', ms: 0, cause: 'no member is configured: give the canary member email and password' })\n } else {\n const member = options.member\n session = await check('sign-in', async () => {\n const signedIn = await signIn({ origin, ...member })\n return { value: signedIn.session, detail: signedIn.detail }\n })\n }\n\n await check('revision', async () => {\n const served = await readRevision(origin, options.expectRevision)\n return { value: served, detail: `${served.revision} (${served.source})` }\n })\n\n let minted: { id: string } | null = null\n let access: OperatorAccess | undefined\n if (!options.operatorKey && !session) {\n blocked('operator-access', 'blocked by sign-in: no operator key is configured, and the member did not sign in to mint one')\n } else {\n access = await check('operator-access', async () => {\n let secret = options.operatorKey\n if (!secret) {\n const created = await mintKey(session!)\n secrets.push(created.key)\n secret = created.key\n minted = { id: created.id }\n }\n const opened = await openOperatorAccess({ origin, key: secret, workspace: options.workspace, requestMs: turnMs + 60_000 })\n return {\n value: opened,\n detail: `${minted ? 'a minted one-hour key' : 'the configured operator key'} reaches \"${opened.workspace.name}\" with ${opened.scopes.join(', ')}`,\n }\n })\n }\n\n if (access) {\n const open = access\n await check('plain-turn', async () => ({ value: true, detail: await plainTurn(open, turnMs) }))\n await check('computer-turn', async () => ({\n value: true, detail: await computerTurn(open, turnMs, options.computer ?? 'digest', options.fileDir ?? 'proof', options.computerModel ?? DEFAULT_COMPUTER_MODEL),\n }))\n } else {\n blocked('plain-turn', 'blocked by operator-access')\n blocked('computer-turn', 'blocked by operator-access')\n }\n\n // A key this run minted is revoked whether or not the turns ran: it names the member and would outlive the run.\n const mintedKey = minted as { id: string } | null\n if (mintedKey && session) {\n const member = session\n await check('key-revoke', async () => {\n await revokeKey(member, mintedKey.id)\n return { value: true, detail: 'the minted key was revoked' }\n })\n }\n return results\n}\n"],"mappings":";;;;;AASO,IAAM,UAAN,cAAsB,MAAM;AAAC;AAQpC,IAAM,aAAa;AAGnB,IAAM,MAAN,MAAU;AAAA,EACS,WAAW,oBAAI,IAAiC;AAAA,EAEjE,OAAO,KAAqB;AAC1B,WAAO,CAAC,GAAI,KAAK,SAAS,IAAI,IAAI,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC,CAAE,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,EACjH;AAAA,EAEA,MAAM,KAAK,KAAa,OAAoB,CAAC,GAAsB;AACjE,UAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;AACxC,UAAM,SAAS,KAAK,OAAO,GAAG;AAC9B,QAAI,OAAQ,SAAQ,IAAI,UAAU,MAAM;AACxC,UAAM,WAAW,MAAM,MAAM,KAAK,EAAE,GAAG,MAAM,SAAS,UAAU,UAAU,QAAQ,KAAK,UAAU,YAAY,QAAQ,UAAU,EAAE,CAAC;AAClI,SAAK,OAAO,KAAK,QAAQ;A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AM,UAAU,MAAM,MAAM,EAAE,EAAE;AAC9F,UAAM,MAAM,iBAAiB,aAAa;AAAA,MACxC,OAAO;AAAA,MAAM,QAAQ,MAAM,aAAa,MAAM,QAAQ,QAAQ,YAAY,UAAU,QAAQ,WAAW,SAAS,QAAQ,iBAAiB,sBAAsB;AAAA,IACjK,EAAE;AAAA,EACJ,OAAO;AACL,YAAQ,cAAc,4BAA4B;AAClD,YAAQ,iBAAiB,4BAA4B;AAAA,EACvD;AAGA,QAAM,YAAY;AAClB,MAAI,aAAa,SAAS;AACxB,UAAM,SAAS;AACf,UAAM,MAAM,cAAc,YAAY;AACpC,YAAM,UAAU,QAAQ,UAAU,EAAE;AACpC,aAAO,EAAE,OAAO,MAAM,QAAQ,6BAA6B;AAAA,IAC7D,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["REQUEST_MS","REQUEST_MS","where","text"]}
|
|
1
|
+
{"version":3,"sources":["../src/conformance/session.ts","../src/conformance/revision.ts","../src/conformance/turns.ts","../src/conformance/run.ts"],"sourcesContent":["/**\n * Sign-in for the conformance runner: the two ways a member reaches an agent app, and one question both answer,\n * \"does the app accept this session?\". Nothing here is specific to an app; a product whose sign-in differs\n * fails the check with the status it answered.\n */\n\nexport type SignInMode = 'password' | 'sso'\n\n/** A check failed for a reason worth reporting; its message is the cause. */\nexport class Failure extends Error {}\n\nexport interface MemberSession {\n origin: string\n /** A request to the app as the signed-in member; `path` is root-relative. */\n fetch(path: string, init?: RequestInit): Promise<Response>\n}\n\nconst REQUEST_MS = 30_000\n\n/** Cookies by origin: enough of a jar for one sign-in and the calls after it. */\nclass Jar {\n private readonly byOrigin = new Map<string, Map<string, string>>()\n\n header(url: string): string {\n return [...(this.byOrigin.get(new URL(url).origin) ?? [])].map(([name, value]) => `${name}=${value}`).join('; ')\n }\n\n async send(url: string, init: RequestInit = {}): Promise<Response> {\n const headers = new Headers(init.headers)\n const cookie = this.header(url)\n if (cookie) headers.set('cookie', cookie)\n const response = await fetch(url, { ...init, headers, redirect: 'manual', signal: init.signal ?? AbortSignal.timeout(REQUEST_MS) })\n this.absorb(url, response)\n return response\n }\n\n private absorb(url: string, response: Response): void {\n const origin = new URL(url).origin\n const jar = this.byOrigin.get(origin) ?? new Map<string, string>()\n for (const line of response.headers.getSetCookie()) {\n const [pair = '', ...attributes] = line.split(';')\n const eq = pair.indexOf('=')\n if (eq < 1) continue\n const name = pair.slice(0, eq).trim()\n const value = pair.slice(eq + 1).trim()\n const attribute = (key: string) => attributes.map(item => item.trim()).find(item => item.toLowerCase().startsWith(`${key}=`))?.slice(key.length + 1)\n const maxAge = attribute('max-age')\n const expires = attribute('expires')\n const gone = !value || (maxAge !== undefined && Number(maxAge) <= 0)\n || (maxAge === undefined && expires !== undefined && Date.parse(expires) <= Date.now())\n if (gone) jar.delete(name)\n else jar.set(name, value)\n }\n this.byOrigin.set(origin, jar)\n }\n}\n\nconst snippet = async (response: Response) => (await response.text().catch(() => '')).replace(/\\s+/g, ' ').slice(0, 160)\n\n/** A sign-in POST. An auth service that answers 429 is asked again after its Retry-After (at most 20 s), twice at most. */\nasync function postSignIn(jar: Jar, origin: string, email: string, password: string): Promise<Response> {\n for (let attempt = 0; ; attempt += 1) {\n const response = await jar.send(`${origin}/api/auth/sign-in/email`, {\n method: 'POST', headers: { 'content-type': 'application/json', origin }, body: JSON.stringify({ email, password }),\n })\n if (response.status !== 429 || attempt === 2) return response\n const wait = Number(response.headers.get('retry-after'))\n await response.body?.cancel().catch(() => {})\n await new Promise(resolve => setTimeout(resolve, Math.min(20, Number.isFinite(wait) && wait > 0 ? wait : 5) * 1000))\n }\n}\n\nasync function passwordSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const response = await postSignIn(jar, origin, email, password)\n if (response.status !== 200) throw new Failure(`password sign-in answered ${response.status}: ${await snippet(response)}`)\n}\n\nconst TANGLE_AUTH_PATH = /(^|\\/)auth\\/tangle\\//\n\n/**\n * The app's \"Log in with Tangle\": its start route sends the browser to Platform, Platform signs the member in and\n * authorizes, and the app's callback sets its own session. Apps mount the start route at `/auth/tangle/start` or\n * under `/api`.\n */\nasync function ssoSignIn(jar: Jar, origin: string, email: string, password: string): Promise<void> {\n const answers: string[] = []\n let location: string | null = null\n for (const path of ['/auth/tangle/start', '/api/auth/tangle/start']) {\n const start = await jar.send(`${origin}${path}`)\n location = start.headers.get('location')\n if (location) break\n answers.push(`${path} answered ${start.status}`)\n }\n if (!location) throw new Failure(`SSO start sent the member nowhere (${answers.join('; ')})`)\n const authorize = new URL(location, origin)\n const platform = authorize.origin\n const member = await postSignIn(jar, platform, email, password)\n if (member.status !== 200) throw new Failure(`Platform sign-in answered ${member.status}: ${await snippet(member)}`)\n let next = authorize.href\n for (let hop = 0; hop < 8; hop += 1) {\n const response = await jar.send(next)\n const redirect = response.headers.get('location')\n if (!redirect) throw new Failure(`SSO stopped at ${new URL(next).pathname} with ${response.status}`)\n const url = new URL(redirect, next)\n if (url.origin === origin && !TANGLE_AUTH_PATH.test(url.pathname)) {\n if (url.pathname.startsWith('/login') || url.searchParams.has('error') || url.searchParams.get('connection') === 'failed') {\n throw new Failure(`the app's SSO callback sent the member to ${url.pathname}${url.search.slice(0, 80)}`)\n }\n return\n }\n next = url.href\n }\n throw new Failure('SSO did not return to the app within 8 redirects')\n}\n\n/** A redirect to sign-in or an error page is an app that did not accept the session. */\nasync function sessionAccepted(session: MemberSession): Promise<string> {\n const who = await session.fetch('/api/auth/get-session')\n if (who.status === 200) {\n const body = await who.json().catch(() => null) as { user?: { id?: unknown } } | null\n if (typeof body?.user?.id === 'string' && body.user.id) return 'GET /api/auth/get-session returned the user'\n }\n const workspaces = await session.fetch('/api/workspaces')\n if (workspaces.status === 200) return 'GET /api/workspaces answered 200 as the member'\n throw new Failure(`signed in, but the app does not accept the session: GET /api/auth/get-session answered ${who.status}, GET /api/workspaces ${workspaces.status}`)\n}\n\n/** Signs in and proves the app accepts the session; the detail names the proof. */\nexport async function signIn(input: { origin: string; mode: SignInMode; email: string; password: string }): Promise<{ session: MemberSession; detail: string }> {\n const jar = new Jar()\n if (input.mode === 'password') await passwordSignIn(jar, input.origin, input.email, input.password)\n else await ssoSignIn(jar, input.origin, input.email, input.password)\n const session: MemberSession = {\n origin: input.origin,\n fetch: (path, init = {}) => {\n const headers = new Headers(init.headers)\n if (!headers.has('origin')) headers.set('origin', input.origin)\n return jar.send(`${input.origin}${path}`, { ...init, headers })\n },\n }\n return { session, detail: `${input.mode}: ${await sessionAccepted(session)}` }\n}\n","/**\n * The served revision, read the way an operator reads it: from the app's own `GET /api/health` body, or from the\n * `x-<app>-revision` / `x-<app>-version` header the app puts on its responses. An app that serves neither cannot\n * say what it is running, so a release cannot be told from the one before it.\n */\n\nimport { Failure } from './session.js'\n\nconst REVISION_HEADER = /^x-[a-z0-9-]+-(revision|version)$/i\nconst REQUEST_MS = 20_000\n\nconst text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value.trim() : null\n\n/** The revision a health body carries: `revision`, or what `release` carries. */\nfunction fromHealth(body: unknown): string | null {\n if (!body || typeof body !== 'object') return null\n const record = body as Record<string, unknown>\n const release = record.release && typeof record.release === 'object' ? record.release as Record<string, unknown> : {}\n return text(record.revision) ?? text(release.revision) ?? text(release.sha) ?? text(release.tag)\n}\n\nfunction fromHeaders(response: Response): { name: string; value: string } | null {\n for (const [name, value] of response.headers) if (REVISION_HEADER.test(name) && value.trim()) return { name, value: value.trim() }\n return null\n}\n\n/**\n * Reads the revision, or throws a Failure naming every place it looked. `source` says where it was read, e.g.\n * `GET /api/health` or `GET / x-creative-revision`.\n */\nexport async function readRevision(origin: string, expect?: string): Promise<{ revision: string; source: string }> {\n const looked: string[] = []\n const found = await (async (): Promise<{ revision: string; source: string } | null> => {\n for (const path of ['/api/health', '/']) {\n let response: Response\n try {\n response = await fetch(`${origin}${path}`, { headers: { accept: 'application/json' }, redirect: 'manual', signal: AbortSignal.timeout(REQUEST_MS) })\n } catch (error) {\n looked.push(`GET ${path} failed (${error instanceof Error ? error.name : 'error'})`)\n continue\n }\n const header = fromHeaders(response)\n if (path === '/api/health' && response.ok) {\n const revision = fromHealth(await response.json().catch(() => null))\n if (revision) return { revision, source: 'GET /api/health' }\n }\n if (header) return { revision: header.value, source: `GET ${path} ${header.name}` }\n await response.body?.cancel().catch(() => {})\n looked.push(`GET ${path} answered ${response.status} without a revision`)\n }\n return null\n })()\n if (!found) throw new Failure(`the app serves no readable revision (${looked.join('; ')})`)\n if (expect) {\n const [a, b] = [found.revision.toLowerCase(), expect.trim().toLowerCase()]\n if (b.length < 7 || !(a.startsWith(b) || b.startsWith(a))) {\n throw new Failure(`the app serves revision ${found.revision} (${found.source}), not the expected ${expect}`)\n }\n }\n return found\n}\n","/**\n * The conformance turns, run through the operator API every agent app mounts the same way\n * (docs/operator-api.md), so one runner drives every product. The verdict is the settled turn the app stored.\n *\n * plain a reply with text;\n * computer a turn only the workspace computer can answer: either the digest of a fresh nonce, which the model\n * cannot know without running the command, or a file the computer saves that the app then serves back.\n */\n\nimport { createHash, randomBytes, randomUUID } from 'node:crypto'\nimport { createOperatorClient, type OperatorClient } from '../operator/client.js'\nimport type { OperatorTurn, OperatorWorkspace } from '../operator/contract.js'\nimport { Failure, type MemberSession } from './session.js'\n\nexport type ComputerProof = 'digest' | 'file'\n\nconst REQUEST_MS = 30_000\nconst KEY_LIFETIME_MS = 60 * 60_000\n\nexport interface OperatorAccess {\n client: OperatorClient\n workspace: OperatorWorkspace\n /** The app's own account of what the key may do. */\n scopes: readonly string[]\n}\n\n/** An expiring key for the signed-in member, through the route every app's API access page uses. */\nexport async function mintKey(session: MemberSession): Promise<{ id: string; key: string }> {\n const response = await session.fetch('/api/keys', {\n method: 'POST', headers: { 'content-type': 'application/json' }, signal: AbortSignal.timeout(REQUEST_MS),\n body: JSON.stringify({\n name: `conformance ${new Date().toISOString()}`, scopes: ['operator:read', 'operator:run'],\n expiresAt: new Date(Date.now() + KEY_LIFETIME_MS).toISOString(), workspaceIds: [],\n }),\n })\n if (response.status === 404) {\n throw new Failure('the app has no key route (POST /api/keys answered 404), so a conformance turn has no credential; give it an operator key')\n }\n const body = await response.json().catch(() => null) as { id?: unknown; key?: unknown; error?: unknown } | null\n if (!response.ok || typeof body?.id !== 'string' || typeof body.key !== 'string') {\n throw new Failure(`POST /api/keys answered ${response.status}: ${typeof body?.error === 'string' ? body.error.slice(0, 160) : 'no key in the response'}`)\n }\n return { id: body.id, key: body.key }\n}\n\n/** Revokes a key this run created. Apps accept the id in the path, or in the body of the collection route. */\nexport async function revokeKey(session: MemberSession, id: string): Promise<void> {\n const byPath = await session.fetch(`/api/keys/${encodeURIComponent(id)}`, { method: 'DELETE', signal: AbortSignal.timeout(REQUEST_MS) })\n if (byPath.ok) return\n const byBody = await session.fetch('/api/keys', {\n method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ id }), signal: AbortSignal.timeout(REQUEST_MS),\n })\n if (byBody.ok) return\n throw new Failure(`the minted key ${id} was not revoked: DELETE /api/keys/:id answered ${byPath.status}, DELETE /api/keys ${byBody.status} (it expires within the hour)`)\n}\n\n/**\n * Opens the operator API with `key` and picks the workspace the turns run in: `workspace` is its id or exact name,\n * and omitted, the key must reach exactly one. `requestMs` bounds any one request, a held turn read included.\n */\nexport async function openOperatorAccess(\n { origin, key, workspace, requestMs }: { origin: string; key: string; workspace: string | undefined; requestMs: number },\n): Promise<OperatorAccess> {\n const client = createOperatorClient({\n origin,\n getApiKey: () => key,\n fetchImpl: (url, init) => fetch(url, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(requestMs)]) : AbortSignal.timeout(requestMs) }),\n })\n const described = await client.describe()\n if (!described.succeeded) throw new Failure(`GET /api/operator/v1 answered ${described.status} ${described.code}: ${described.error.slice(0, 160)}`)\n const scopes = described.value.principal.scopes\n const missing = ['operator:read', 'operator:run'].filter(scope => !scopes.includes(scope) && !scopes.includes('*'))\n if (missing.length) throw new Failure(`the operator key lacks ${missing.join(' and ')}`)\n const listed = await client.listWorkspaces()\n if (!listed.succeeded) throw new Failure(`GET /api/operator/v1/workspaces answered ${listed.status} ${listed.code}: ${listed.error.slice(0, 160)}`)\n const chosen = workspace\n ? listed.value.filter(candidate => candidate.id === workspace || candidate.name === workspace)\n : listed.value.length === 1 ? listed.value : []\n if (chosen.length !== 1) {\n const names = listed.value.slice(0, 12).map(candidate => `${candidate.name} (${candidate.id.slice(0, 8)})`).join(', ')\n throw new Failure(workspace\n ? `${chosen.length} of the key's ${listed.value.length} workspaces match \"${workspace}\": ${names}`\n : `the key reaches ${listed.value.length} workspaces; name the canary workspace: ${names}`)\n }\n return { client, workspace: chosen[0]!, scopes }\n}\n\nconst reply = (turn: OperatorTurn) => (turn.reply?.content ?? '').trim()\n\n/** One turn on a new thread, followed until it settles. */\nasync function runTurn(access: OperatorAccess, title: string, content: string, turnMs: number, model?: string): Promise<{ turn: OperatorTurn; where: string }> {\n const turnId = randomUUID()\n const started = await access.client.startTurn(access.workspace.id, { turnId, content, title, ...(model ? { model } : {}) })\n if (!started.succeeded) throw new Failure(`the turn was refused: ${started.status} ${started.code}: ${started.error.slice(0, 200)}`)\n const where = `thread ${started.value.threadId}`\n const settled = await access.client.waitForTurn(access.workspace.id, started.value.threadId, started.value.turnId, { timeoutMs: turnMs })\n if (!settled.succeeded) throw new Failure(`reading the turn answered ${settled.status} ${settled.code}: ${settled.error.slice(0, 160)} (${where})`)\n const turn = settled.value\n if (turn.state === 'failed') throw new Failure(`the turn failed${turn.failure?.code ? ` (${turn.failure.code})` : ''}: ${(turn.failure?.message ?? 'no message').slice(0, 300)} (${where})`)\n if (turn.state === 'input-required' || turn.approvals.length > 0) throw new Failure(`the turn is waiting on a decision, which no one can answer in a conformance run (${where})`)\n if (turn.state !== 'succeeded') throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1000)} s (state ${turn.state}; ${where})`)\n return { turn, where }\n}\n\nexport async function plainTurn(access: OperatorAccess, turnMs: number): Promise<string> {\n const { turn, where } = await runTurn(access, 'Conformance: plain turn',\n 'Conformance check: reply with one short sentence confirming you can answer.', turnMs)\n if (!reply(turn)) throw new Failure(`the turn succeeded with an empty reply (${where})`)\n return `${reply(turn).length} characters from ${turn.model ?? 'an unreported model'} (${where})`\n}\n\nexport async function computerTurn(access: OperatorAccess, turnMs: number, proof: ComputerProof, fileDir: string, model: string): Promise<string> {\n const nonce = `conformance-${randomBytes(12).toString('hex')}`\n if (proof === 'digest') {\n const digest = createHash('sha256').update(nonce).digest('hex')\n const { turn, where } = await runTurn(access, 'Conformance: computer turn',\n 'Conformance check: run this exact shell command on the workspace computer (sandbox_run when you have it), then reply with only '\n + `the 64-character hex digest it prints:\\nprintf %s '${nonce}' | sha256sum`, turnMs, model)\n if (!reply(turn).includes(digest)) {\n throw new Failure(`the reply does not hold the digest of the fresh nonce, so the computer did not run the command: \"${reply(turn).slice(0, 160)}\" (${where})`)\n }\n return `the reply carries the digest ${digest.slice(0, 12)}… (${where})`\n }\n const path = `${fileDir.replace(/\\/+$/, '')}/${nonce}.md`\n const { where } = await runTurn(access, 'Conformance: computer turn',\n `Conformance check: use the workspace computer to save a file at ${path} whose whole content is this one line, then reply with the word saved:\\n${nonce}`, turnMs, model)\n const read = await access.client.readFile(access.workspace.id, path)\n if (!read.succeeded) throw new Failure(`the turn succeeded, but the app does not serve ${path}: ${read.status} ${read.code} (${where})`)\n if (read.value.content.trim() !== nonce) {\n throw new Failure(`${path} holds ${JSON.stringify(read.value.content.slice(0, 80))}, not the nonce (${where})`)\n }\n return `the app serves ${path} with the nonce (${where})`\n}\n","import { readRevision } from './revision.js'\nimport { Failure, signIn, type MemberSession, type SignInMode } from './session.js'\nimport { computerTurn, mintKey, openOperatorAccess, plainTurn, revokeKey, type ComputerProof, type OperatorAccess } from './turns.js'\n\nexport type CheckName = 'sign-in' | 'revision' | 'operator-access' | 'plain-turn' | 'computer-turn' | 'key-revoke'\n\n/**\n * One check's verdict. `blocked` means an earlier check it depends on failed, so nothing was measured; a blocked\n * check fails the run like a failed one, and its cause names the check that blocked it.\n */\nexport interface CheckResult {\n /** When the check started, ISO 8601. */\n at: string\n app: string\n url: string\n check: CheckName\n status: 'pass' | 'fail' | 'blocked'\n ms: number\n /** Why a failed or blocked check is not a pass. */\n cause?: string\n /** What a passing check observed: the revision read, the thread a turn ran in. */\n detail?: string\n}\n\nexport interface ConformanceOptions {\n /** A label for the result lines, e.g. `gtm`. */\n app: string\n /** The deployed origin, e.g. `https://gtm.tangle.tools`. */\n origin: string\n /** The member that signs in. Required: sign-in is the first thing a customer does. */\n member?: { mode: SignInMode; email: string; password: string }\n /** A key that already has `operator:read` and `operator:run`; without one, the signed-in member mints a one-hour key. */\n operatorKey?: string\n /** Id or exact name of the workspace the turns run in: the app's canary or smoke workspace, never a customer's. */\n workspace?: string\n /** `digest` hashes a fresh nonce on the workspace computer; `file` has the computer save a file the app serves back;\n * `none` runs the plain turn only, for a check that asks exactly once (a post-serve first ask). */\n computer?: ComputerProof | 'none'\n /** The computer turn's model. The plain turn keeps the app's own model, so the served model is still checked once. */\n computerModel?: string\n /** Where the `file` proof is saved, relative to the workspace root. */\n fileDir?: string\n /** The budget of each turn, a cold box included. */\n turnMs?: number\n /** Fail unless the served revision starts with, or is a prefix of, this. */\n expectRevision?: string\n /** Called with each result as it lands. */\n onResult?(result: CheckResult): void\n}\n\nconst DEFAULT_TURN_MS = 300_000\n// Company spend rule: checks run on the flat-rate plan; per-token models are for product serving with real users.\nconst DEFAULT_COMPUTER_MODEL = 'glm-5.3'\n\n/** Why an unexpected error is not a pass, in a line. */\nfunction describe(error: unknown): string {\n if (error instanceof Failure) return error.message\n if (error instanceof Error) {\n const cause = error.cause as { code?: unknown } | undefined\n return `${error.name}: ${error.message}${typeof cause?.code === 'string' ? ` (${cause.code})` : ''}`\n }\n return String(error)\n}\n\n/** Runs the checks against one deployed app and returns every result, in the order they ran. */\nexport async function checkDeployedApp(options: ConformanceOptions): Promise<CheckResult[]> {\n const origin = options.origin.replace(/\\/+$/, '')\n const turnMs = options.turnMs ?? DEFAULT_TURN_MS\n const secrets = [options.member?.password, options.operatorKey].filter((value): value is string => Boolean(value && value.length >= 6))\n const redact = (text: string) => secrets.reduce((out, secret) => out.split(secret).join('[redacted]'), text)\n const results: CheckResult[] = []\n\n const record = (result: CheckResult) => {\n const clean = { ...result, ...(result.cause ? { cause: redact(result.cause) } : {}), ...(result.detail ? { detail: redact(result.detail) } : {}) }\n results.push(clean)\n options.onResult?.(clean)\n }\n /** Runs `body`; whatever it returns is the passing detail, whatever it throws is the cause. */\n async function check<T>(name: CheckName, body: () => Promise<{ value: T; detail?: string }>): Promise<T | undefined> {\n const at = new Date().toISOString()\n const started = Date.now()\n const base = { at, app: options.app, url: origin, check: name }\n try {\n const { value, detail } = await body()\n record({ ...base, status: 'pass', ms: Date.now() - started, ...(detail ? { detail } : {}) })\n return value\n } catch (error) {\n record({ ...base, status: 'fail', ms: Date.now() - started, cause: describe(error) })\n return undefined\n }\n }\n const blocked = (name: CheckName, because: string) =>\n record({ at: new Date().toISOString(), app: options.app, url: origin, check: name, status: 'blocked', ms: 0, cause: because })\n\n let session: MemberSession | undefined\n if (!options.member) {\n const at = new Date().toISOString()\n record({ at, app: options.app, url: origin, check: 'sign-in', status: 'fail', ms: 0, cause: 'no member is configured: give the canary member email and password' })\n } else {\n const member = options.member\n session = await check('sign-in', async () => {\n const signedIn = await signIn({ origin, ...member })\n return { value: signedIn.session, detail: signedIn.detail }\n })\n }\n\n await check('revision', async () => {\n const served = await readRevision(origin, options.expectRevision)\n return { value: served, detail: `${served.revision} (${served.source})` }\n })\n\n let minted: { id: string } | null = null\n let access: OperatorAccess | undefined\n if (!options.operatorKey && !session) {\n blocked('operator-access', 'blocked by sign-in: no operator key is configured, and the member did not sign in to mint one')\n } else {\n access = await check('operator-access', async () => {\n let secret = options.operatorKey\n if (!secret) {\n const created = await mintKey(session!)\n secrets.push(created.key)\n secret = created.key\n minted = { id: created.id }\n }\n const opened = await openOperatorAccess({ origin, key: secret, workspace: options.workspace, requestMs: turnMs + 60_000 })\n return {\n value: opened,\n detail: `${minted ? 'a minted one-hour key' : 'the configured operator key'} reaches \"${opened.workspace.name}\" with ${opened.scopes.join(', ')}`,\n }\n })\n }\n\n if (access) {\n const open = access\n await check('plain-turn', async () => ({ value: true, detail: await plainTurn(open, turnMs) }))\n const proof = options.computer ?? 'digest'\n if (proof !== 'none') {\n await check('computer-turn', async () => ({\n value: true, detail: await computerTurn(open, turnMs, proof, options.fileDir ?? 'proof', options.computerModel ?? DEFAULT_COMPUTER_MODEL),\n }))\n }\n } else {\n blocked('plain-turn', 'blocked by operator-access')\n if (options.computer !== 'none') blocked('computer-turn', 'blocked by operator-access')\n }\n\n // A key this run minted is revoked whether or not the turns ran: it names the member and would outlive the run.\n const mintedKey = minted as { id: string } | null\n if (mintedKey && session) {\n const member = session\n await check('key-revoke', async () => {\n await revokeKey(member, mintedKey.id)\n return { value: true, detail: 'the minted key was revoked' }\n })\n }\n return results\n}\n"],"mappings":";;;;;AASO,IAAM,UAAN,cAAsB,MAAM;AAAC;AAQpC,IAAM,aAAa;AAGnB,IAAM,MAAN,MAAU;AAAA,EACS,WAAW,oBAAI,IAAiC;AAAA,EAEjE,OAAO,KAAqB;AAC1B,WAAO,CAAC,GAAI,KAAK,SAAS,IAAI,IAAI,IAAI,GAAG,EAAE,MAAM,KAAK,CAAC,CAAE,EAAE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,GAAG,IAAI,IAAI,KAAK,EAAE,EAAE,KAAK,IAAI;AAAA,EACjH;AAAA,EAEA,MAAM,KAAK,KAAa,OAAoB,CAAC,GAAsB;AACjE,UAAM,UAAU,IAAI,QAAQ,KAAK,OAAO;AACxC,UAAM,SAAS,KAAK,OAAO,GAAG;AAC9B,QAAI,OAAQ,SAAQ,IAAI,UAAU,MAAM;AACxC,UAAM,WAAW,MAAM,MAAM,KAAK,EAAE,GAAG,MAAM,SAAS,UAAU,UAAU,QAAQ,KAAK,UAAU,YAAY,QAAQ,UAAU,EAAE,CAAC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AAa,EAAE,OAAO,MAAM,QAAQ,MAAM,UAAU,MAAM,MAAM,EAAE,EAAE;AAC9F,UAAM,QAAQ,QAAQ,YAAY;AAClC,QAAI,UAAU,QAAQ;AACpB,YAAM,MAAM,iBAAiB,aAAa;AAAA,QACxC,OAAO;AAAA,QAAM,QAAQ,MAAM,aAAa,MAAM,QAAQ,OAAO,QAAQ,WAAW,SAAS,QAAQ,iBAAiB,sBAAsB;AAAA,MAC1I,EAAE;AAAA,IACJ;AAAA,EACF,OAAO;AACL,YAAQ,cAAc,4BAA4B;AAClD,QAAI,QAAQ,aAAa,OAAQ,SAAQ,iBAAiB,4BAA4B;AAAA,EACxF;AAGA,QAAM,YAAY;AAClB,MAAI,aAAa,SAAS;AACxB,UAAM,SAAS;AACf,UAAM,MAAM,cAAc,YAAY;AACpC,YAAM,UAAU,QAAQ,UAAU,EAAE;AACpC,aAAO,EAAE,OAAO,MAAM,QAAQ,6BAA6B;AAAA,IAC7D,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["REQUEST_MS","REQUEST_MS","where","text"]}
|
|
@@ -41,6 +41,14 @@ function addStepFinishUsage(part, usage) {
|
|
|
41
41
|
if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost;
|
|
42
42
|
}
|
|
43
43
|
|
|
44
|
+
// src/chat-routes/visible-text.ts
|
|
45
|
+
function transformVisibleTextParts(parts, transform) {
|
|
46
|
+
return Promise.all(parts.map(async (part) => {
|
|
47
|
+
const type = String(part.type ?? "");
|
|
48
|
+
return type === "text" || type === "reasoning" ? { ...part, text: await transform(String(part.text ?? "")) } : part;
|
|
49
|
+
}));
|
|
50
|
+
}
|
|
51
|
+
|
|
44
52
|
// src/chat-routes/draft-persistence.ts
|
|
45
53
|
var CONTENT_EVENT_TYPES = /* @__PURE__ */ new Set([
|
|
46
54
|
"text",
|
|
@@ -113,11 +121,7 @@ function createAssistantDraftWriter(options) {
|
|
|
113
121
|
let parts;
|
|
114
122
|
if (snapshot.parts) {
|
|
115
123
|
const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput));
|
|
116
|
-
const redacted = transform ? await
|
|
117
|
-
capped.map(
|
|
118
|
-
async (part) => String(part.type ?? "") === "text" ? { ...part, text: await transform(String(part.text ?? "")) } : part
|
|
119
|
-
)
|
|
120
|
-
) : capped;
|
|
124
|
+
const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped;
|
|
121
125
|
parts = toChatMessageParts(redacted);
|
|
122
126
|
}
|
|
123
127
|
const usage = snapshot.usage ?? {};
|
|
@@ -227,10 +231,11 @@ export {
|
|
|
227
231
|
TURN_USAGE_KEYS,
|
|
228
232
|
measuredUsage,
|
|
229
233
|
addStepFinishUsage,
|
|
234
|
+
transformVisibleTextParts,
|
|
230
235
|
isDraftContentEvent,
|
|
231
236
|
createAssistantDraftWriter,
|
|
232
237
|
storeSupportsDraftPersistence,
|
|
233
238
|
rowIdOf,
|
|
234
239
|
assistantRowIdForTurn
|
|
235
240
|
};
|
|
236
|
-
//# sourceMappingURL=chunk-
|
|
241
|
+
//# sourceMappingURL=chunk-SJKQUTGU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/chat-routes/sandbox-turn-usage.ts","../src/chat-routes/visible-text.ts","../src/chat-routes/draft-persistence.ts"],"sourcesContent":["import { asRecord, type JsonRecord } from '../stream/index'\nimport type { ChatTurnUsage } from './turn-routes'\n\n/** Every usage field a turn can record, in column order. */\nexport const TURN_USAGE_KEYS = [\n 'inputTokens', 'outputTokens', 'reasoningTokens', 'cacheReadTokens', 'cacheWriteTokens', 'costUsd', 'harnessCostUsd',\n] as const\n\n/** The usage fields a turn measured; unknown ones stay absent, never zero. */\nexport function measuredUsage(usage: ChatTurnUsage | undefined): ChatTurnUsage {\n const measured: ChatTurnUsage = {}\n for (const key of TURN_USAGE_KEYS) if (usage?.[key] !== undefined) measured[key] = usage[key]\n return measured\n}\n\n/** Add one canonical Sandbox `step-finish` receipt to a turn total. */\nexport function addStepFinishUsage(part: JsonRecord, usage: ChatTurnUsage): void {\n const tokens = asRecord(part.tokens)\n if (tokens) {\n const cache = asRecord(tokens.cache)\n const add = (current: number | undefined, value: unknown): number | undefined => {\n const n = Number(value)\n if (!Number.isFinite(n)) return current\n return (current ?? 0) + n\n }\n usage.inputTokens = add(usage.inputTokens, tokens.input)\n usage.outputTokens = add(usage.outputTokens, tokens.output)\n usage.reasoningTokens = add(usage.reasoningTokens, tokens.reasoning)\n if (cache) {\n usage.cacheReadTokens = add(usage.cacheReadTokens, cache.read)\n usage.cacheWriteTokens = add(usage.cacheWriteTokens, cache.write)\n }\n }\n const cost = Number(part.cost)\n if (Number.isFinite(cost)) usage.harnessCostUsd = (usage.harnessCostUsd ?? 0) + cost\n}\n","/**\n * Apply a product's final-text transform (a PII redactor, for example) to every\n * stored part a reader sees as words: the answer's text parts and the reasoning\n * parts, which also hold a Router turn's pre-tool narration. One rule for the\n * final row, the draft row and the detached-turn row.\n */\nexport function transformVisibleTextParts<T>(\n parts: readonly T[],\n transform: (text: string) => string | Promise<string>,\n): Promise<T[]> {\n return Promise.all(parts.map(async (part) => {\n const type = String((part as { type?: unknown }).type ?? '')\n return type === 'text' || type === 'reasoning'\n ? { ...part, text: await transform(String((part as { text?: unknown }).text ?? '')) }\n : part\n }))\n}\n","/**\n * Incremental (\"draft\") persistence of the assistant row WHILE a turn streams.\n *\n * Why this exists — the scale argument, not a convenience:\n *\n * A live turn is readable from two places. The hot path is the session\n * gateway's in-memory/Redis event buffer, which exists so a viewer survives a\n * network blip: it is keyed one sorted set per session, refreshed on every\n * push, and expires on a TTL. Its memory cost is `arrival_rate x TTL x\n * bytes_per_session` — strictly LINEAR in the TTL. Stretching that TTL to\n * cover \"a viewer who opens the tab later\" is a category error: it buys memory\n * proportional to the increase and still serves nothing to a viewer who\n * arrives past the new horizon.\n *\n * So the hot buffer must stay SHORT (live delivery + reconnect only), and\n * durable storage must serve history. That only works if durable storage\n * actually HAS the in-flight turn — which, before this module, it did not: the\n * assistant row was written once, after the stream drained. A viewer arriving\n * mid-turn past the hot window read an empty transcript.\n *\n * This module closes that gap: the assistant row is inserted early and patched\n * on a coalesced cadence, so the durable transcript is at most one interval\n * (default 2 s) behind the live stream and the hot buffer never has to be the\n * history tier.\n *\n * Mechanism only. It owns no vocabulary: the caller supplies the snapshot\n * function, the store, and the deterministic row id.\n *\n * Four properties the cadence guarantees:\n * - **Time-floored.** At most one write per `intervalMs`, never one per token.\n * - **Dirty-gated.** Only content-bearing events arm a write; heartbeats,\n * status pings, and lifecycle envelopes never do.\n * - **Single-flight.** A write already in flight suppresses the next trigger\n * instead of queueing; the final write is authoritative regardless of how\n * many drafts landed.\n * - **Best-effort.** A store failure is logged and swallowed — a durability\n * optimization must never kill a healthy stream (the same rule\n * `withDurableChatProjection` already states).\n */\n\nimport type { ChatMessageValues } from '../chat-store/core'\nimport { toChatMessageParts, type ChatMessagePart } from '../chat-store/parts'\nimport type { ChatTurnUsage } from './turn-routes'\nimport { measuredUsage } from './sandbox-turn-usage'\nimport { transformVisibleTextParts } from './visible-text'\n\n/** Message row shape the writer reads back when re-entering a turn. */\nexport interface DraftStoredMessage extends Pick<AssistantRowValues, keyof ChatTurnUsage> {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[] | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n}\n\n/** Values written to the assistant row — the intersection of the append and\n * patch shapes, so one snapshot serves both. */\nexport interface AssistantRowValues extends ChatMessageValues {}\n\n/** The store capability incremental persistence needs on top of\n * `appendMessage`. A store without `updateMessage` cannot patch a row, so it\n * cannot draft at all — the caller keeps today's single-write behavior. */\nexport interface AssistantDraftStore {\n listMessages(threadId: string): Promise<DraftStoredMessage[]>\n appendMessage(input: AssistantRowValues & {\n id?: string\n threadId: string\n role: 'user' | 'assistant'\n }): Promise<unknown>\n updateMessage?(id: string, patch: AssistantRowValues): Promise<unknown>\n deleteMessage?(id: string): Promise<unknown>\n}\n\n/** Live snapshot of the assistant body, taken from the producer's own\n * accumulators. `parts` is the DRAFT projection (`draftParts()`), never the\n * finalized one — see `draftAssistantParts`. */\nexport interface AssistantDraftSnapshot {\n content: string\n parts?: Array<Record<string, unknown>>\n usage?: ChatTurnUsage\n model?: string\n}\n\n/** Product-tunable cadence. Defaults are stated on each field; a product with\n * a chattier or heavier workload moves them without forking the writer. */\nexport interface DraftPersistenceTuning {\n /** Minimum wall-clock gap between draft writes, in ms. Default 2000.\n *\n * Justification for 2 s, from a measured tool-heavy production run (517\n * stream events over ~90 s wall = ~5.7 events/s): a 2 s floor with the\n * dirty gate turns 517 candidate writes into <= 45, while leaving the\n * durable row at most 2 s stale — an order of magnitude below the time it\n * takes a viewer to open a tab and render, so a late viewer never perceives\n * the lag. Fleet arithmetic at 10k concurrent 60 s runs: <= 30 updates per\n * run x 167 run-starts/s = ~334 row-updates/s spread over per-tenant\n * shards. Lower it and write amplification grows with no perceptible\n * freshness gain; raise it past ~5 s and a late viewer starts seeing a\n * visibly truncated answer. */\n intervalMs?: number\n /** Serialized-parts size (bytes) past which the interval backs off, so a\n * turn accumulating a megabyte-scale `parts` blob does not rewrite it every\n * interval. Default 262144 (256 KiB) -> interval x 2.5; ten times that ->\n * interval x 5. The final write is never throttled. */\n backoffBytes?: number\n /** Per-tool-part output cap applied to DRAFTS ONLY (bytes). A tool returning\n * a large blob would otherwise be rewritten in full on every draft. The\n * final write always carries the untruncated value. Default 32768 (32 KiB);\n * 0 disables truncation. */\n maxDraftToolOutputBytes?: number\n}\n\n/** Define the inputs required to construct an assistant draft writer */\nexport interface AssistantDraftWriterOptions extends DraftPersistenceTuning {\n store: AssistantDraftStore\n threadId: string\n /** DETERMINISTIC row id for this turn's assistant message — the whole\n * idempotency mechanism. Derived from the turn's existing identity\n * (`deriveExecutionId` in the interactive lane, the turn id in the detached\n * lane), so a re-entered turn addresses the SAME row: the writer looks the\n * id up before its first insert and patches what it finds. */\n messageId: string\n /** Read the producer's live accumulators. Returns null before the producer\n * is resolved (the assembly defers box resolution into the first pull). */\n snapshot(): AssistantDraftSnapshot | null\n /** Pre-persist text transform (`/redact`'s `redactPII`). Applied to the\n * draft's scalar content AND every draft text part — parity with the final\n * write, or incremental persistence would re-open the at-rest PII leak that\n * transform closed, just seconds earlier and on every turn. */\n transformText?(text: string): string | Promise<string>\n log?: (message: string, meta?: Record<string, unknown>) => void\n}\n\n/** Coalescing writer that keeps one durable assistant row in step with a\n * streaming turn. Created per turn; not reusable. */\nexport interface AssistantDraftWriter {\n /** Arm/trigger a draft write from one engine event. Synchronous by design —\n * the write itself is fire-and-forget so the stream is never blocked on\n * store latency. */\n notify(event: { type?: unknown }): void\n /** Stop drafting and settle any in-flight write. Called before the final\n * write so a late draft can never clobber the authoritative row. */\n close(): Promise<void>\n /** Write the AUTHORITATIVE completion values onto this turn's row —\n * insert-or-patch under the same deterministic id, un-throttled and\n * un-truncated. Errors propagate: the final write is the one that must not\n * fail silently. Implies {@link close}. */\n finalize(values: AssistantRowValues): Promise<void>\n /** The durable row this turn is writing, once one exists. */\n rowId(): string | undefined\n /** Retract the row for a turn that produced nothing (mirrors the final\n * write's empty-turn skip, which leaves no row at all today). Also retracts\n * a row a PREVIOUS attempt left behind, so a re-entered turn that ends\n * empty converges on \"no row\" rather than a stale partial. */\n discard(): Promise<void>\n /** Diagnostics: how many draft writes actually reached the store. */\n writeCount(): number\n}\n\n/** Event types that carry assistant content and therefore arm a draft write.\n * An allowlist on purpose: an unknown type (a product heartbeat, a bespoke\n * passthrough) must NEVER arm a write, or a silent producer would rewrite the\n * same row forever. */\nconst CONTENT_EVENT_TYPES: ReadonlySet<string> = new Set([\n 'text',\n 'reasoning',\n 'tool_call',\n 'tool_result',\n 'usage',\n 'notice',\n 'error',\n 'file',\n 'interaction',\n 'interaction.cancel',\n 'plan.submitted',\n 'message.part.updated',\n])\n\nconst DEFAULT_INTERVAL_MS = 2000\nconst DEFAULT_BACKOFF_BYTES = 262144\nconst DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES = 32768\n\n/** True when this event should arm a draft write. */\nexport function isDraftContentEvent(event: { type?: unknown }): boolean {\n return typeof event?.type === 'string' && CONTENT_EVENT_TYPES.has(event.type)\n}\n\n/** Caps one tool part's `output` for a DRAFT write. The value is replaced by a\n * truncated string plus a marker, so a reader can tell a clipped draft from a\n * real short output; the final write restores the untruncated value. */\nfunction capDraftToolOutput(part: Record<string, unknown>, maxBytes: number): Record<string, unknown> {\n if (maxBytes <= 0) return part\n if (String(part.type ?? '') !== 'tool') return part\n const state = part.state\n if (!state || typeof state !== 'object') return part\n const record = state as Record<string, unknown>\n const output = record.output\n if (output === undefined || output === null) return part\n const serialized = typeof output === 'string' ? output : safeStringify(output)\n if (serialized.length <= maxBytes) return part\n const metadata = (record.metadata && typeof record.metadata === 'object' ? record.metadata : {}) as Record<string, unknown>\n return {\n ...part,\n state: {\n ...record,\n output: `${serialized.slice(0, maxBytes)}…[draft-truncated ${serialized.length - maxBytes} chars]`,\n metadata: { ...metadata, draftTruncated: true },\n },\n }\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value) ?? ''\n } catch {\n return String(value)\n }\n}\n\n/** Build the coalescing draft writer for one turn. */\nexport function createAssistantDraftWriter(options: AssistantDraftWriterOptions): AssistantDraftWriter {\n const log = options.log ?? (() => {})\n const baseIntervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS\n const backoffBytes = options.backoffBytes ?? DEFAULT_BACKOFF_BYTES\n const maxToolOutput = options.maxDraftToolOutputBytes ?? DEFAULT_MAX_DRAFT_TOOL_OUTPUT_BYTES\n\n let dirty = false\n let closed = false\n let inFlight: Promise<void> | undefined\n let lastWriteAt = 0\n let lastBlobBytes = 0\n let rowId: string | undefined\n let writes = 0\n\n /** Interval for the NEXT write, backed off by the size of the last blob\n * written — a turn accumulating a huge parts array rewrites it less often. */\n function currentIntervalMs(): number {\n if (lastBlobBytes >= backoffBytes * 10) return baseIntervalMs * 5\n if (lastBlobBytes >= backoffBytes) return Math.round(baseIntervalMs * 2.5)\n return baseIntervalMs\n }\n\n async function projectValues(snapshot: AssistantDraftSnapshot): Promise<AssistantRowValues> {\n const transform = options.transformText\n const content = transform ? await transform(snapshot.content) : snapshot.content\n let parts: ChatMessagePart[] | undefined\n if (snapshot.parts) {\n const capped = snapshot.parts.map((part) => capDraftToolOutput(part, maxToolOutput))\n const redacted = transform ? await transformVisibleTextParts(capped, transform) : capped\n parts = toChatMessageParts(redacted)\n }\n const usage = snapshot.usage ?? {}\n return {\n content,\n ...(parts && parts.length > 0 ? { parts } : {}),\n ...(snapshot.model ? { model: snapshot.model } : {}),\n ...measuredUsage(usage),\n }\n }\n\n /** Adopt the row a PREVIOUS attempt at this turn already inserted, if any.\n * This lookup — by the deterministic id, through the store's ordinary read\n * — is the whole crash-safety mechanism: no new state, no extra column, no\n * second index. */\n async function adoptRow(): Promise<string | undefined> {\n if (rowId) return rowId\n const existing = (await options.store.listMessages(options.threadId)).find(\n (message) => message.id === options.messageId,\n )\n if (existing) rowId = existing.id\n return rowId\n }\n\n /** Insert-or-patch one set of values onto this turn's single row. */\n async function writeOnce(values: AssistantRowValues): Promise<void> {\n if (await adoptRow()) {\n await options.store.updateMessage!(rowId!, values)\n writes += 1\n return\n }\n const inserted = await options.store.appendMessage({\n id: options.messageId,\n threadId: options.threadId,\n role: 'assistant',\n ...values,\n })\n // The `?? options.messageId` tail is valid HERE and only here: this writer\n // supplied the id, so a store that returns nothing still wrote that row.\n // A caller that did not assign an id has no such fallback — which is why\n // `rowIdOf` deliberately stops at the honest read.\n rowId = rowIdOf(inserted) ?? options.messageId\n writes += 1\n }\n\n function trigger(): void {\n if (closed) return\n if (!dirty) return\n // Single-flight: a write already in flight SUPPRESSES this trigger rather\n // than queueing behind it. `dirty` stays armed, so the next event after it\n // lands writes the newer snapshot — one write is never spent on state a\n // later one supersedes.\n if (inFlight) return\n const now = Date.now()\n // The first content event writes immediately (a late viewer sees a row at\n // once); the time floor governs every write after it.\n if (lastWriteAt !== 0 && now - lastWriteAt < currentIntervalMs()) return\n const snapshot = options.snapshot()\n if (!snapshot) return\n // Nothing to persist yet: an armed-but-empty snapshot (first event is a\n // tool call with no text and no parts) would insert a blank row.\n if (!snapshot.content && (!snapshot.parts || snapshot.parts.length === 0)) return\n dirty = false\n lastWriteAt = now\n inFlight = (async () => {\n try {\n const values = await projectValues(snapshot)\n lastBlobBytes = values.parts ? safeStringify(values.parts).length : 0\n await writeOnce(values)\n } catch (err) {\n // Best-effort by contract: a store outage degrades freshness for late\n // viewers, it does not fail a healthy turn.\n log('[chat-routes] incremental assistant persistence failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n } finally {\n inFlight = undefined\n // A trigger that arrived while this write was in flight left `dirty`\n // armed with a NEWER snapshot. Re-run it here or that state would sit\n // unwritten until the next content event — and if this was the last\n // event of a quiet stretch, until the final write.\n if (dirty && !closed) trigger()\n }\n })()\n }\n\n return {\n notify(event) {\n if (closed) return\n if (isDraftContentEvent(event)) dirty = true\n trigger()\n },\n async close() {\n closed = true\n if (inFlight) await inFlight\n },\n async finalize(values) {\n closed = true\n if (inFlight) await inFlight\n await writeOnce(values)\n },\n rowId: () => rowId,\n async discard() {\n closed = true\n if (inFlight) await inFlight\n if (!options.store.deleteMessage) return\n try {\n if (!(await adoptRow())) return\n await options.store.deleteMessage(rowId!)\n rowId = undefined\n } catch (err) {\n log('[chat-routes] draft assistant row discard failed', {\n messageId: options.messageId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n },\n writeCount: () => writes,\n }\n}\n\n/** True when a store can support incremental persistence at all. Without\n * `updateMessage` a draft row could never be patched, so the caller keeps\n * today's exact single-write behavior. */\nexport function storeSupportsDraftPersistence(store: AssistantDraftStore): boolean {\n return typeof store.updateMessage === 'function'\n}\n\n/** The row id an `appendMessage` actually returned, or `null` when the store\n * returned nothing usable. `ChatTurnMessageStore.appendMessage` is typed\n * `Promise<unknown>` so a product adapter is free to resolve `void`; every\n * caller that wants to NAME the row it just wrote has to read defensively.\n *\n * Deliberately no fallback to a caller-assigned id — see `writeOnce`, which\n * adds its own. A caller that let the store mint the id has nothing to fall\n * back TO, and guessing one would report a row that may not exist. */\nexport function rowIdOf(inserted: unknown): string | null {\n const id = (inserted as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** The default deterministic assistant-row id for a turn. Readable on purpose\n * (an operator grepping a transcript row id finds the run), and stable across\n * re-entries because every input already is. */\nexport function assistantRowIdForTurn(turnKey: string): string {\n return `assistant:${turnKey}`\n}\n"],"mappings":";;;;;;;;AAIO,IAAM,kBAAkB;AAAA,EAC7B;AAAA,EAAe;AAAA,EAAgB;AAAA,EAAmB;AAAA,EAAmB;AAAA,EAAoB;AAAA,EAAW;AACtG;AAGO,SAAS,cAAc,OAAiD;AAC7E,QAAM,WAA0B,CAAC;AACjC,aAAW,OAAO,gBAAiB,KAAI,QAAQ,GAAG,MAAM,OAAW,UAAS,GAAG,IAAI,MAAM,GAAG;AAC5F,SAAO;AACT;AAGO,SAAS,mBAAmB,MAAkB,OAA4B;AAC/E,QAAM,SAAS,SAAS,KAAK,MAAM;AACnC,MAAI,QAAQ;AACV,UAAM,QAAQ,SAAS,OAAO,KAAK;AACnC,UAAM,MAAM,CAAC,SAA6B,UAAuC;AAC/E,YAAM,IAAI,OAAO,KAAK;AACtB,UAAI,CAAC,OAAO,SAAS,CAAC,EAAG,QAAO;AAChC,cAAQ,WAAW,KAAK;AAAA,IAC1B;AACA,UAAM,cAAc,IAAI,MAAM,aAAa,OAAO,KAAK;AACvD,UAAM,eAAe,IAAI,MAAM,cAAc,OAAO,MAAM;AAC1D,UAAM,kBAAkB,IAAI,MAAM,iBAAiB,OAAO,SAAS;AACnE,QAAI,OAAO;AACT,YAAM,kBAAkB,IAAI,MAAM,iBAAiB,MAAM,IAAI;AAC7D,YAAM,mBAAmB,IAAI,MA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
44
|
-
storeSupportsDraftPersistence
|
|
45
|
-
|
|
44
|
+
storeSupportsDraftPersistence,
|
|
45
|
+
transformVisibleTextParts
|
|
46
|
+
} from "./chunk-SJKQUTGU.js";
|
|
46
47
|
import {
|
|
47
48
|
normalizeClientTurnId,
|
|
48
49
|
resolveChatTurn
|
|
@@ -117,8 +118,9 @@ import {
|
|
|
117
118
|
} from "./chunk-XELWWXJJ.js";
|
|
118
119
|
import {
|
|
119
120
|
composeRouterTurnPromptSections,
|
|
121
|
+
narratesBefore,
|
|
120
122
|
runRouterTurn
|
|
121
|
-
} from "./chunk-
|
|
123
|
+
} from "./chunk-XCUT2I52.js";
|
|
122
124
|
import {
|
|
123
125
|
createIntelligenceTurnTraceSink,
|
|
124
126
|
createTurnTrace,
|
|
@@ -577,6 +579,7 @@ function createRouterTurnProducer(options) {
|
|
|
577
579
|
const parts = [];
|
|
578
580
|
const toolParts = /* @__PURE__ */ new Map();
|
|
579
581
|
let textPart = null;
|
|
582
|
+
const narration = /* @__PURE__ */ new Set();
|
|
580
583
|
let textSegment = 0;
|
|
581
584
|
let reasoningPart = null;
|
|
582
585
|
const reasoningClock = createReasoningClock();
|
|
@@ -621,6 +624,8 @@ function createRouterTurnProducer(options) {
|
|
|
621
624
|
reasoningPart = null;
|
|
622
625
|
reasoningClock.settle(event.startedAt);
|
|
623
626
|
if (event.status === "running") {
|
|
627
|
+
if (textPart && narratesBefore(options.tools?.find((tool) => tool.name === event.toolName))) narration.add(textPart);
|
|
628
|
+
textPart = null;
|
|
624
629
|
const part = {
|
|
625
630
|
type: "tool",
|
|
626
631
|
id: event.callId,
|
|
@@ -673,9 +678,13 @@ function createRouterTurnProducer(options) {
|
|
|
673
678
|
result.failure = { code: "turn_deadline", message: "The reply was stopped before it finished." };
|
|
674
679
|
}
|
|
675
680
|
outcome = result;
|
|
681
|
+
if (parts.some((part) => part.type === "text" && !narration.has(part) && String(part.text).trim())) {
|
|
682
|
+
for (const part of narration) part.type = "reasoning";
|
|
683
|
+
}
|
|
676
684
|
const final = await options.onOutcome?.(result);
|
|
677
685
|
if (final && final.trailingText) {
|
|
678
686
|
result.text += final.trailingText;
|
|
687
|
+
result.answer += final.trailingText;
|
|
679
688
|
parts.push({ type: "text", text: final.trailingText });
|
|
680
689
|
push({ type: "text", text: final.trailingText });
|
|
681
690
|
}
|
|
@@ -742,7 +751,7 @@ function createRouterTurnProducer(options) {
|
|
|
742
751
|
stream: events,
|
|
743
752
|
// The route tracks this continuation even when failure is visible before a pending key arrives.
|
|
744
753
|
cleanup: run.then(retire, retire),
|
|
745
|
-
finalText: () => outcome?.
|
|
754
|
+
finalText: () => outcome?.answer ?? "",
|
|
746
755
|
assistantParts: snapshot,
|
|
747
756
|
draftParts: snapshot,
|
|
748
757
|
usage,
|
|
@@ -3419,11 +3428,7 @@ function createTurnEngine(identity, ctx, log, state, dispatched, produceArgs, tr
|
|
|
3419
3428
|
return;
|
|
3420
3429
|
}
|
|
3421
3430
|
const rawParts = state.producer?.assistantParts ? state.producer.assistantParts() : void 0;
|
|
3422
|
-
const projected = rawParts && options.transformFinalText ? await
|
|
3423
|
-
rawParts.map(
|
|
3424
|
-
async (part) => String(part.type ?? "") === "text" ? { ...part, text: await options.transformFinalText(String(part.text ?? "")) } : part
|
|
3425
|
-
)
|
|
3426
|
-
) : rawParts;
|
|
3431
|
+
const projected = rawParts && options.transformFinalText ? await transformVisibleTextParts(rawParts, options.transformFinalText) : rawParts;
|
|
3427
3432
|
const parts = projected ? toChatMessageParts(projected) : void 0;
|
|
3428
3433
|
if (!finalText.trim() && (!parts || parts.length === 0)) {
|
|
3429
3434
|
await state.draft?.discard();
|
|
@@ -4227,4 +4232,4 @@ export {
|
|
|
4227
4232
|
createChatTurnRoutes,
|
|
4228
4233
|
streamChatRouteAsSandboxEvents
|
|
4229
4234
|
};
|
|
4230
|
-
//# sourceMappingURL=chunk-
|
|
4235
|
+
//# sourceMappingURL=chunk-W5YQZEE4.js.map
|