@tangle-network/agent-app 4.0.1 → 4.0.3
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-EI27JMS6.js → chunk-565M7QOK.js} +1 -1
- package/dist/chunk-565M7QOK.js.map +1 -0
- package/dist/{chunk-LBMFQLBS.js → chunk-DKEIQRKT.js} +4 -2
- package/dist/chunk-DKEIQRKT.js.map +1 -0
- package/dist/{chunk-XOHE6SKU.js → chunk-EK2Y55K4.js} +2 -137
- package/dist/chunk-EK2Y55K4.js.map +1 -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-QVGDVY5U.js → chunk-I4MPG5T6.js} +2 -2
- package/dist/chunk-IJ6B5ZPU.js +141 -0
- package/dist/chunk-IJ6B5ZPU.js.map +1 -0
- package/dist/{chunk-HES3IABJ.js → chunk-JKYCXQFI.js} +2 -2
- package/dist/{chunk-U2PTQCQ3.js → chunk-NKANJSKB.js} +2 -2
- 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/index.js +2 -2
- package/dist/launch-invariants/cli.js +4 -3
- package/dist/launch-invariants/cli.js.map +1 -1
- package/dist/launch-invariants/index.js +3 -2
- package/dist/launch-invariants/index.js.map +1 -1
- package/dist/launch-invariants/testing.js +4 -3
- package/dist/operator/contract.d.ts +6 -0
- package/dist/operator/index.js +6 -1
- package/dist/operator/index.js.map +1 -1
- 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/dist/turn-health/index.js +5 -3
- package/dist/turn-health/index.js.map +1 -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-EI27JMS6.js.map +0 -1
- package/dist/chunk-JSWBJBPM.js.map +0 -1
- package/dist/chunk-LBMFQLBS.js.map +0 -1
- package/dist/chunk-XOHE6SKU.js.map +0 -1
- /package/dist/{chunk-QVGDVY5U.js.map → chunk-I4MPG5T6.js.map} +0 -0
- /package/dist/{chunk-HES3IABJ.js.map → chunk-JKYCXQFI.js.map} +0 -0
- /package/dist/{chunk-U2PTQCQ3.js.map → chunk-NKANJSKB.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[]>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/operator/contract.ts","../src/operator/client.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\nimport type { ChatAttachmentInput } from '../chat-routes/wire.js'\n\nexport const OPERATOR_API_VERSION = 'v1'\nexport const OPERATOR_API_BASE_PATH = '/api/operator/v1'\n\n/** Key permissions, with the labels an app's API access page shows. */\nexport const OPERATOR_ACCESS = [\n {\n scope: 'operator:read',\n label: 'Read workspaces',\n description: 'Read workspaces, conversations, files, approvals, scorecards, and run status.',\n },\n {\n scope: 'operator:write',\n label: 'Create and edit',\n description: 'Create workspaces and conversations, and write files.',\n },\n {\n scope: 'operator:run',\n requires: ['operator:read'],\n label: 'Run agents',\n description: 'Requires read access. Start, continue, and interrupt agent turns, and answer their questions and tool-permission requests. Agents can modify workspace files. Uses your plan and budget.',\n },\n] as const\n\nexport type OperatorScope = typeof OPERATOR_ACCESS[number]['scope']\n\nexport const OPERATOR_API_SCOPES: readonly OperatorScope[] = OPERATOR_ACCESS.map(({ scope }) => scope)\n\nexport const OPERATOR_SCOPE_DEPENDENCIES: Readonly<Record<string, readonly string[]>> = Object.fromEntries(\n OPERATOR_ACCESS.flatMap((option) => 'requires' in option ? [[option.scope, option.requires]] : []),\n)\n\n/**\n * A key carrying one or more of these scopes reaches only the named\n * workspaces and cannot create workspaces. Keys without one keep the owner's\n * ordinary workspace access.\n */\nexport const OPERATOR_WORKSPACE_SCOPE_PREFIX = 'operator:workspace:'\n\nconst WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function operatorWorkspaceScope(workspaceId: string): string {\n if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError('Workspace ids contain only letters, digits, - and _')\n return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`\n}\n\n/** The workspaces a key is restricted to, or null when it is unrestricted. A malformed restriction restricts to nothing. */\nexport function operatorKeyWorkspaces(scopes: readonly string[]): readonly string[] | null {\n const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX))\n if (restricted.length === 0) return null\n return restricted\n .map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length))\n .filter((id) => WORKSPACE_ID.test(id))\n}\n\nexport type OperatorRole = 'owner' | 'admin' | 'editor' | 'viewer'\n\nexport interface OperatorAppInfo {\n /** Stable app identifier, such as `gtm` or `tax`. */\n app: string\n name: string\n apiVersion: typeof OPERATOR_API_VERSION\n /** Optional operations this app implements; absent ones answer 501. */\n capabilities: OperatorCapability[]\n}\n\nexport type OperatorCapability =\n | 'turns.attachments'\n | 'turns.cancel'\n | 'workspaces.create'\n | 'threads.read'\n | 'files.read'\n | 'journal.read'\n | 'assets.read'\n | 'scorecard.read'\n\nexport interface OperatorPrincipalInfo {\n keyId: string\n scopes: string[]\n /** Workspaces the key is restricted to, or null for the owner's ordinary access. */\n workspaces: string[] | null\n}\n\nexport interface OperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n /** Browser link for a person to open the workspace. */\n url?: string\n createdAt?: string\n}\n\nexport interface OperatorThread {\n id: string\n title: string\n updatedAt?: string\n url?: string\n}\n\n/**\n * `succeeded` and `failed` are settled. `input-required` waits on a person or\n * an operator decision listed in `approvals`. `unknown` means the app cannot\n * establish the state; it is never evidence of success.\n */\nexport type OperatorTurnState = 'queued' | 'working' | 'input-required' | 'succeeded' | 'failed' | 'unknown'\n\nexport const OPERATOR_SETTLED_STATES: readonly OperatorTurnState[] = ['succeeded', 'failed']\n\n/** `failure.code` of a turn that settled because it was cancelled before it finished. */\nexport const OPERATOR_TURN_CANCELLED_CODE = 'turn.cancelled'\n\nexport interface OperatorAssetRef {\n id: string\n /** Root-relative operator route that returns the bytes. */\n path: string\n mediaType?: string\n name?: string\n}\n\nexport interface OperatorFileChange {\n path: string\n action: 'created' | 'updated' | 'deleted' | 'changed'\n}\n\nexport type OperatorApprovalKind = 'question' | 'permission' | 'plan' | 'hub' | 'asset' | 'review'\n\nexport interface OperatorApproval {\n id: string\n kind: OperatorApprovalKind\n title: string\n detail?: string\n threadId?: string\n /** Browser link where an authorized person decides it. */\n url?: string\n createdAt?: string\n expiresAt?: string\n /** Who can decide: an operator key with run access, an editor, or the workspace owner. */\n decidedBy: 'operator' | 'editor' | 'owner'\n}\n\nexport interface OperatorTurn {\n workspaceId: string\n threadId: string\n turnId: string\n state: OperatorTurnState\n url?: string\n executionId?: string\n model?: string\n costUsd?: number\n /** The harness's own reported token cost, kept when the ledger charged nothing (a failed turn). */\n harnessCostUsd?: number\n /** Producer-recorded basis for costUsd; catalog is an estimate, ledger is settlement evidence. */\n costSource?: 'ledger' | 'catalog' | 'reported' | 'unreported' | 'subscription'\n /** Producer-recorded billing path, not the identity of a payer. */\n billingOwner?: 'router' | 'sandbox-router' | 'subscription'\n /** Producer-recorded credential path; never inferred from costUsd or billingOwner. */\n credentialSource?: 'router' | 'subscription'\n /** Opaque producer settlement reference; its presence alone does not prove a charge or zero provider cost. */\n settlementRecord?: string\n /**\n * Token usage the app stored on the turn's reply; `operatorTurnUsage` maps\n * a chat-store row to it.\n * - `inputTokens`: prompt tokens NOT read from the provider's cache. Unlike\n * the turn trace's summary, it never includes cache reads; it is omitted\n * when the row's split is ambiguous, including when the row records no\n * cache count (see `operatorTurnUsage`).\n * - `cachedInputTokens`: prompt tokens read from the provider's cache (the\n * row's `cacheReadTokens`); with both present the whole prompt is\n * `inputTokens + cachedInputTokens`. When absent the cache share is unknown.\n * - `outputTokens`: completion tokens.\n * Each field is present only when known; never a guessed zero.\n */\n usage?: { inputTokens?: number; cachedInputTokens?: number; outputTokens?: number }\n completedAt?: string\n /** The settled answer; null until the turn settles. */\n reply: { content: string; mediaType: string } | null\n failure: { code?: string; message: string } | null\n assets: OperatorAssetRef[]\n files: OperatorFileChange[]\n /** Decisions open on this turn's conversation. */\n approvals: OperatorApproval[]\n /** Tool calls the harness refused in this turn (turn-health's `tool_call_rejected`), present only when there\n * were some: a refused call shows here even when the turn recovered and answered. */\n refusedToolCalls?: Array<{ tool: string; error: string }>\n}\n\nexport interface OperatorJournalEntry {\n path: string\n /** `YYYY-MM-DD` the entry belongs to. */\n date: string\n title?: string\n updatedAt?: string\n}\n\nexport interface OperatorFileEntry {\n path: string\n updatedAt?: string\n bytes?: number\n}\n\nexport interface OperatorFile {\n path: string\n content: string\n mediaType: string\n revision?: string\n}\n\nexport interface OperatorMetric {\n key: string\n label: string\n /** Null when the app has no measurement; never a guessed zero. */\n value: number | null\n unit: 'count' | 'usd' | 'ratio' | 'ms'\n note?: string\n}\n\nexport interface OperatorScorecard {\n workspaceId: string\n generatedAt: string\n window: { start: string; end: string; days: number }\n /** Work the agent did in the window. */\n metrics: OperatorMetric[]\n /** Business results recorded in the window, such as clicks, signups, or replies. */\n outcomes: OperatorMetric[]\n /** How the numbers are measured and what they exclude. */\n measurement: string\n}\n\nexport interface OperatorErrorBody {\n error: string\n code: string\n retryable?: boolean\n}\n\nexport interface StartTurnInput {\n /** Client-generated UUID. Reuse it to retry the same turn; it never starts twice. */\n turnId: string\n content: string\n /** Continue this conversation; omitted starts a new one. */\n threadId?: string\n /** Title for a new conversation. */\n title?: string\n model?: string\n /**\n * Files uploaded to this workspace ahead of the turn, as the app's\n * attachment upload route returned them in `{ files }`. They reach the\n * agent exactly as browser-composer attachments do; the app re-checks each\n * path against the workspace's own store. At most the app's\n * `maxAttachments` entries, `ATTACHMENT_MAX_COUNT` (`/chat-routes`) unless\n * the app sets one. Apps without the `turns.attachments` capability refuse\n * them.\n */\n attachments?: ChatAttachmentInput[]\n}\n\n/** Route table: method, path pattern under the base path, and required scopes. */\nexport const OPERATOR_ROUTES = [\n { id: 'describe', method: 'GET', path: '', scopes: ['operator:read'] },\n { id: 'workspaces.list', method: 'GET', path: '/workspaces', scopes: ['operator:read'] },\n { id: 'workspaces.create', method: 'POST', path: '/workspaces', scopes: ['operator:write'] },\n { id: 'workspaces.get', method: 'GET', path: '/workspaces/:workspaceId', scopes: ['operator:read'] },\n { id: 'turns.start', method: 'POST', path: '/workspaces/:workspaceId/turns', scopes: ['operator:read', 'operator:run'] },\n { id: 'threads.list', method: 'GET', path: '/workspaces/:workspaceId/threads', scopes: ['operator:read'] },\n { id: 'threads.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId', scopes: ['operator:read'] },\n { id: 'turns.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId', scopes: ['operator:read'] },\n { id: 'turns.cancel', method: 'POST', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId/cancel', scopes: ['operator:read', 'operator:run'] },\n { id: 'approvals.list', method: 'GET', path: '/workspaces/:workspaceId/approvals', scopes: ['operator:read'] },\n { id: 'journal.list', method: 'GET', path: '/workspaces/:workspaceId/journal', scopes: ['operator:read'] },\n { id: 'files.list', method: 'GET', path: '/workspaces/:workspaceId/files', scopes: ['operator:read'] },\n { id: 'files.read', method: 'GET', path: '/workspaces/:workspaceId/file', scopes: ['operator:read'] },\n { id: 'assets.read', method: 'GET', path: '/workspaces/:workspaceId/assets/:assetId', scopes: ['operator:read'] },\n { id: 'scorecard.get', method: 'GET', path: '/workspaces/:workspaceId/scorecard', scopes: ['operator:read'] },\n] as const satisfies ReadonlyArray<{ id: string; method: 'GET' | 'POST'; path: string; scopes: readonly OperatorScope[] }>\n\nexport type OperatorRouteId = typeof OPERATOR_ROUTES[number]['id']\n\nconst SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/\n\n/** Match a pathname under the base path to its route and decoded parameters. */\nexport function matchOperatorRoute(\n method: string,\n pathname: string,\n basePath: string = OPERATOR_API_BASE_PATH,\n): { route: typeof OPERATOR_ROUTES[number]; params: Record<string, string> } | null {\n if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null\n const rest = pathname.slice(basePath.length).replace(/\\/$/, '')\n const actual = rest ? rest.split('/').slice(1) : []\n for (const route of OPERATOR_ROUTES) {\n if (route.method !== method) continue\n const pattern = route.path ? route.path.split('/').slice(1) : []\n if (pattern.length !== actual.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index++) {\n const expected = pattern[index]!\n const segment = actual[index]!\n if (expected.startsWith(':')) {\n if (!SEGMENT.test(segment)) { matched = false; break }\n let decoded: string\n try { decoded = decodeURIComponent(segment) } catch { matched = false; break }\n if (!decoded || decoded.includes('/')) { matched = false; break }\n params[expected.slice(1)] = decoded\n } else if (expected !== segment) {\n matched = false\n break\n }\n }\n if (matched) return { route, params }\n }\n return null\n}\n","import { createApiKeyFetch } from '../web/api-key-fetch.js'\nimport {\n OPERATOR_API_BASE_PATH,\n type OperatorApproval,\n type OperatorAppInfo,\n type OperatorErrorBody,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorPrincipalInfo,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\nexport type OperatorResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; code: string; error: string; retryable: boolean }\n\nexport interface OperatorClientOptions {\n /** The app's origin, such as `https://gtm.tangle.tools`. */\n origin: string\n /** Resolve the key from trusted secret storage on each request; never from model output. */\n getApiKey(): string | Promise<string>\n fetchImpl?: typeof fetch\n allowHttpLoopback?: boolean\n basePath?: string\n}\n\nexport interface WaitForTurnOptions {\n /** Total time to follow the turn. */\n timeoutMs: number\n /** Server hold per request, in seconds; the server caps it. */\n waitSeconds?: number\n signal?: AbortSignal\n}\n\nexport interface OperatorClient {\n describe(): Promise<OperatorResult<{ app: OperatorAppInfo; principal: OperatorPrincipalInfo }>>\n listWorkspaces(): Promise<OperatorResult<OperatorWorkspace[]>>\n createWorkspace(input: { name: string }): Promise<OperatorResult<OperatorWorkspace>>\n getWorkspace(workspaceId: string): Promise<OperatorResult<OperatorWorkspace>>\n /** Omitting turnId generates one; retry with the returned turn's id. */\n startTurn(workspaceId: string, input: Omit<StartTurnInput, 'turnId'> & { turnId?: string }): Promise<OperatorResult<OperatorTurn>>\n getTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /**\n * Stop a turn. A settled turn comes back as it settled; otherwise the app\n * has been asked to stop it, and the server holds up to `waitSeconds` for\n * the turn to settle `failed` with `OPERATOR_TURN_CANCELLED_CODE`. Read it\n * with `getTurn` or `waitForTurn` until it settles.\n */\n cancelTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /** Follow until the turn settles, waits on a decision, or the timeout passes; the last read is returned. */\n waitForTurn(workspaceId: string, threadId: string, turnId: string, options: WaitForTurnOptions): Promise<OperatorResult<OperatorTurn>>\n listThreads(workspaceId: string, query?: { cursor?: string; limit?: number }): Promise<OperatorResult<{ threads: OperatorThread[]; nextCursor: string | null }>>\n getThread(workspaceId: string, threadId: string): Promise<OperatorResult<{ thread: OperatorThread; latestTurn: OperatorTurn | null }>>\n listApprovals(workspaceId: string): Promise<OperatorResult<OperatorApproval[]>>\n listJournal(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorJournalEntry[]>>\n listFiles(workspaceId: string, query?: { prefix?: string }): Promise<OperatorResult<OperatorFileEntry[]>>\n readFile(workspaceId: string, path: string): Promise<OperatorResult<OperatorFile>>\n /** The raw asset response; the caller reads and bounds its body. */\n readAsset(workspaceId: string, assetId: string, init?: { signal?: AbortSignal }): Promise<OperatorResult<Response>>\n getScorecard(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorScorecard>>\n}\n\nfunction segment(value: string): string {\n return encodeURIComponent(value)\n}\n\nasync function failure(response: Response): Promise<OperatorResult<never>> {\n let body: Partial<OperatorErrorBody> = {}\n try { body = await response.json() as Partial<OperatorErrorBody> } catch { /* A non-JSON refusal keeps its status. */ }\n return {\n succeeded: false,\n status: response.status,\n code: typeof body.code === 'string' ? body.code : `http_${response.status}`,\n error: typeof body.error === 'string' ? body.error : `HTTP ${response.status}`,\n retryable: body.retryable === true || response.status === 429 || response.status >= 500,\n }\n}\n\nfunction transportFailure(error: unknown): OperatorResult<never> {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n succeeded: false,\n status: 0,\n code: aborted ? 'operator.aborted' : 'operator.transport_failed',\n // createApiKeyFetch never forwards transport diagnostics, which could carry the key.\n error: error instanceof Error ? error.message : 'Operator transport failed',\n retryable: !aborted,\n }\n}\n\nconst SETTLED = new Set(['succeeded', 'failed', 'input-required'])\n\n/** A typed client for one app's operator API. */\nexport function createOperatorClient(options: OperatorClientOptions): OperatorClient {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const request = createApiKeyFetch({\n origin: options.origin,\n getApiKey: options.getApiKey,\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n ...(options.allowHttpLoopback ? { allowHttpLoopback: true } : {}),\n })\n\n async function call<T>(\n path: string,\n pick: (body: Record<string, unknown>) => T,\n init: RequestInit = {},\n ): Promise<OperatorResult<T>> {\n let response: Response\n try {\n response = await request(`${basePath}${path}`, {\n ...init,\n headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}) },\n })\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n try {\n return { succeeded: true, value: pick(await response.json() as Record<string, unknown>) }\n } catch {\n return { succeeded: false, status: response.status, code: 'operator.invalid_response', error: 'The response was not the expected JSON', retryable: true }\n }\n }\n\n const query = (params: Record<string, string | number | undefined>) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(params)) if (value !== undefined && value !== '') search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n }\n\n const client: OperatorClient = {\n describe: () => call('', (body) => body as unknown as { app: OperatorAppInfo; principal: OperatorPrincipalInfo }),\n listWorkspaces: () => call('/workspaces', (body) => body.workspaces as OperatorWorkspace[]),\n createWorkspace: (input) => call('/workspaces', (body) => body.workspace as OperatorWorkspace, {\n method: 'POST', body: JSON.stringify({ name: input.name }),\n }),\n getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace as OperatorWorkspace),\n startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn as OperatorTurn, {\n method: 'POST', body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() }),\n }),\n getTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n opts.signal ? { signal: opts.signal } : {},\n ),\n cancelTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}/cancel${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n { method: 'POST', ...(opts.signal ? { signal: opts.signal } : {}) },\n ),\n async waitForTurn(workspaceId, threadId, turnId, opts) {\n const deadline = Date.now() + opts.timeoutMs\n const waitSeconds = opts.waitSeconds ?? 25\n let last: OperatorResult<OperatorTurn> | null = null\n while (true) {\n const remaining = Math.floor((deadline - Date.now()) / 1000)\n const started = Date.now()\n last = await client.getTurn(workspaceId, threadId, turnId, {\n waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n if (!last.succeeded) {\n if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last\n await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, Math.max(0, deadline - Date.now()))))\n continue\n }\n if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last\n if (Date.now() >= deadline || opts.signal?.aborted) return last\n // A server that does not hold the read still gets a bounded request rate.\n if (Date.now() - started < 1_000) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(2_000, Math.max(0, deadline - Date.now()))))\n }\n }\n },\n listThreads: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,\n (body) => ({ threads: body.threads as OperatorThread[], nextCursor: (body.nextCursor as string | null) ?? null }),\n ),\n getThread: (workspaceId, threadId) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,\n (body) => ({ thread: body.thread as OperatorThread, latestTurn: (body.latestTurn as OperatorTurn | null) ?? null }),\n ),\n listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals as OperatorApproval[]),\n listJournal: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,\n (body) => body.entries as OperatorJournalEntry[],\n ),\n listFiles: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,\n (body) => body.files as OperatorFileEntry[],\n ),\n readFile: (workspaceId, path) => call(\n `/workspaces/${segment(workspaceId)}/file${query({ path })}`,\n (body) => body.file as OperatorFile,\n ),\n async readAsset(workspaceId, assetId, init = {}) {\n let response: Response\n try {\n response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {})\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n return { succeeded: true, value: response }\n },\n getScorecard: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,\n (body) => body.scorecard as OperatorScorecard,\n ),\n }\n return client\n}\n"],"mappings":";;;;;AASO,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB;AAG/B,IAAM,kBAAkB;AAAA,EAC7B;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,I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AAC,GAAG;AAC/C,UAAI;AACJ,UAAI;AACF,mBAAW,MAAM,QAAQ,GAAG,QAAQ,eAAe,QAAQ,WAAW,CAAC,WAAW,QAAQ,OAAO,CAAC,IAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC,CAAC;AAAA,MAClJ,SAAS,OAAO;AACd,eAAO,iBAAiB,KAAK;AAAA,MAC/B;AACA,UAAI,CAAC,SAAS,GAAI,QAAO,QAAQ,QAAQ;AACzC,aAAO,EAAE,WAAW,MAAM,OAAO,SAAS;AAAA,IAC5C;AAAA,IACA,cAAc,CAAC,aAAa,IAAI,CAAC,MAAM;AAAA,MACrC,eAAe,QAAQ,WAAW,CAAC,aAAa,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAAA,MACvE,CAAC,SAAS,KAAK;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;","names":["segment"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createOperatorClient
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-565M7QOK.js";
|
|
4
4
|
|
|
5
5
|
// src/conformance/session.ts
|
|
6
6
|
var Failure = class extends Error {
|
|
@@ -229,6 +229,8 @@ async function runTurn(access, title, content, turnMs, model) {
|
|
|
229
229
|
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})`);
|
|
230
230
|
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})`);
|
|
231
231
|
if (turn.state !== "succeeded") throw new Failure(`the turn had not settled after ${Math.round(turnMs / 1e3)} s (state ${turn.state}; ${where})`);
|
|
232
|
+
const refused = turn.refusedToolCalls?.[0];
|
|
233
|
+
if (refused) throw new Failure(`a tool call was refused (${refused.tool}): ${refused.error.slice(0, 200)} (${where})`);
|
|
232
234
|
return { turn, where };
|
|
233
235
|
}
|
|
234
236
|
async function plainTurn(access, turnMs) {
|
|
@@ -374,4 +376,4 @@ async function checkDeployedApp(options) {
|
|
|
374
376
|
export {
|
|
375
377
|
checkDeployedApp
|
|
376
378
|
};
|
|
377
|
-
//# sourceMappingURL=chunk-
|
|
379
|
+
//# sourceMappingURL=chunk-DKEIQRKT.js.map
|
|
@@ -0,0 +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 // A refused tool call is red even when the turn recovered and answered.\n const refused = turn.refusedToolCalls?.[0]\n if (refused) throw new Failure(`a tool call was refused (${refused.tool}): ${refused.error.slice(0, 200)} (${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;AAClI,SAAK,OAAO,KAAK,QAAQ;AACzB,WAAO;AAAA,EACT;AAAA,EAEQ,OAAO,KAAa,UAA0B;AACpD,UAAM,SAAS,IAAI,IAAI,GAAG,EAAE;AAC5B,UAAM,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,oB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M,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"]}
|
|
@@ -1,7 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
postSlackAlert
|
|
3
|
-
} from "./chunk-JRCZHDRG.js";
|
|
4
|
-
|
|
5
1
|
// src/turn-health/classify.ts
|
|
6
2
|
var ARTIFACT_PART_KINDS = /* @__PURE__ */ new Set(["file", "image", "work-product", "plan", "interaction"]);
|
|
7
3
|
var KNOWN_NON_OUTPUT_PART_KINDS = /* @__PURE__ */ new Set([
|
|
@@ -166,139 +162,8 @@ function describeReason(reason) {
|
|
|
166
162
|
}
|
|
167
163
|
}
|
|
168
164
|
|
|
169
|
-
// src/turn-health/sink.ts
|
|
170
|
-
function turnAlert(input) {
|
|
171
|
-
const kinds = [...new Set(input.reasons.map((r) => r.kind))].sort();
|
|
172
|
-
return {
|
|
173
|
-
product: input.product,
|
|
174
|
-
severity: input.severity,
|
|
175
|
-
// Keyed by product + reason kinds ONLY. A blank-completion storm across
|
|
176
|
-
// 200 turns is one incident, not 200 pages.
|
|
177
|
-
key: `turn:${input.product}:${kinds.join("+")}`,
|
|
178
|
-
title: `${input.product}: turn completed but delivered nothing (${kinds.join(", ")})`,
|
|
179
|
-
details: input.reasons.map(describeReason),
|
|
180
|
-
data: {
|
|
181
|
-
kinds,
|
|
182
|
-
...input.threadId ? { threadId: input.threadId } : {},
|
|
183
|
-
...input.turnId ? { turnId: input.turnId } : {},
|
|
184
|
-
...input.model ? { model: input.model } : {}
|
|
185
|
-
},
|
|
186
|
-
at: input.at ?? Date.now()
|
|
187
|
-
};
|
|
188
|
-
}
|
|
189
|
-
function createWebhookAlertSink(options) {
|
|
190
|
-
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
191
|
-
return {
|
|
192
|
-
async deliver(alert) {
|
|
193
|
-
const text = slackAlertText(alert);
|
|
194
|
-
const response = await fetchImpl(options.webhookUrl, {
|
|
195
|
-
method: "POST",
|
|
196
|
-
headers: { "Content-Type": "application/json" },
|
|
197
|
-
body: JSON.stringify({ text })
|
|
198
|
-
});
|
|
199
|
-
if (!response.ok) {
|
|
200
|
-
throw new Error(`alert webhook responded ${response.status}`);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
};
|
|
204
|
-
}
|
|
205
|
-
function createSlackBotAlertSink(options) {
|
|
206
|
-
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
207
|
-
return {
|
|
208
|
-
async deliver(alert) {
|
|
209
|
-
const text = slackAlertText(alert);
|
|
210
|
-
const outcome = await postSlackAlert({
|
|
211
|
-
token: options.botToken,
|
|
212
|
-
channel: options.channel,
|
|
213
|
-
text,
|
|
214
|
-
attempts: 1,
|
|
215
|
-
// Preserve the public minimal-fetch seam without owning a second Slack
|
|
216
|
-
// request builder or response parser. Real callers use native fetch.
|
|
217
|
-
fetchImpl: options.fetchImpl ? (async (url, init) => {
|
|
218
|
-
const response = await fetchImpl(String(url), {
|
|
219
|
-
method: init?.method ?? "POST",
|
|
220
|
-
headers: Object.fromEntries(new Headers(init?.headers)),
|
|
221
|
-
body: String(init?.body ?? "")
|
|
222
|
-
});
|
|
223
|
-
return new Response(await response.text?.() ?? "", { status: response.status });
|
|
224
|
-
}) : void 0
|
|
225
|
-
});
|
|
226
|
-
if (!outcome.delivered) throw new Error(`Slack alert failed (${outcome.reason}): ${outcome.detail}`);
|
|
227
|
-
}
|
|
228
|
-
};
|
|
229
|
-
}
|
|
230
|
-
function createConsoleAlertSink(log = console.error) {
|
|
231
|
-
return {
|
|
232
|
-
async deliver(alert) {
|
|
233
|
-
log(
|
|
234
|
-
`[turn-health] ${alert.severity.toUpperCase()} ${alert.title} :: ${alert.details.join(" | ")}`
|
|
235
|
-
);
|
|
236
|
-
}
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
|
-
function createMultiAlertSink(sinks) {
|
|
240
|
-
return {
|
|
241
|
-
async deliver(alert) {
|
|
242
|
-
const settled = await Promise.allSettled(sinks.map((s) => s.deliver(alert)));
|
|
243
|
-
const failures = settled.filter((r) => r.status === "rejected");
|
|
244
|
-
if (failures.length === sinks.length && sinks.length > 0) {
|
|
245
|
-
throw new Error("every alert sink failed");
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
};
|
|
249
|
-
}
|
|
250
|
-
function createMemoryThrottleStore() {
|
|
251
|
-
const seen = /* @__PURE__ */ new Map();
|
|
252
|
-
return {
|
|
253
|
-
async lastSentAt(key) {
|
|
254
|
-
return seen.get(key) ?? null;
|
|
255
|
-
},
|
|
256
|
-
async markSent(key, at) {
|
|
257
|
-
seen.set(key, at);
|
|
258
|
-
}
|
|
259
|
-
};
|
|
260
|
-
}
|
|
261
|
-
function createThrottledAlertSink(inner, options) {
|
|
262
|
-
const store = options.store ?? createMemoryThrottleStore();
|
|
263
|
-
return {
|
|
264
|
-
async deliver(alert) {
|
|
265
|
-
const last = await store.lastSentAt(alert.key);
|
|
266
|
-
if (last !== null && alert.at - last < options.windowMs) return;
|
|
267
|
-
await inner.deliver(alert);
|
|
268
|
-
await store.markSent(alert.key, alert.at);
|
|
269
|
-
}
|
|
270
|
-
};
|
|
271
|
-
}
|
|
272
|
-
function createGuardedAlertSink(inner, onError = (e) => console.error("[turn-health] alert delivery failed", e)) {
|
|
273
|
-
return {
|
|
274
|
-
async deliver(alert) {
|
|
275
|
-
try {
|
|
276
|
-
await inner.deliver(alert);
|
|
277
|
-
} catch (error) {
|
|
278
|
-
onError(error);
|
|
279
|
-
}
|
|
280
|
-
}
|
|
281
|
-
};
|
|
282
|
-
}
|
|
283
|
-
function slackAlertText(alert) {
|
|
284
|
-
const icon = alert.severity === "critical" ? ":rotating_light:" : ":warning:";
|
|
285
|
-
return [
|
|
286
|
-
`${icon} *${alert.title}*`,
|
|
287
|
-
...alert.details.map((detail) => `\u2022 ${detail}`),
|
|
288
|
-
`_${new Date(alert.at).toISOString()}_`
|
|
289
|
-
].join("\n");
|
|
290
|
-
}
|
|
291
|
-
|
|
292
165
|
export {
|
|
293
166
|
classifyTurnOutcome,
|
|
294
|
-
describeReason
|
|
295
|
-
turnAlert,
|
|
296
|
-
createWebhookAlertSink,
|
|
297
|
-
createSlackBotAlertSink,
|
|
298
|
-
createConsoleAlertSink,
|
|
299
|
-
createMultiAlertSink,
|
|
300
|
-
createMemoryThrottleStore,
|
|
301
|
-
createThrottledAlertSink,
|
|
302
|
-
createGuardedAlertSink
|
|
167
|
+
describeReason
|
|
303
168
|
};
|
|
304
|
-
//# sourceMappingURL=chunk-
|
|
169
|
+
//# sourceMappingURL=chunk-EK2Y55K4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/turn-health/classify.ts"],"sourcesContent":["/**\n * The classifier for turns that FAIL BY RETURNING SUCCESS.\n *\n * Every failure this module names shipped to a customer with HTTP 200, no\n * thrown error, and no log line anyone read. Three were measured in production\n * in a single week:\n *\n * - a turn settled `{\"outcome\":{\"type\":\"completed\"},\"finalText\":\"\",\n * \"tokenUsage\":{\"outputTokens\":0}}` — the customer saw a blank bubble;\n * - six `submit_proposal` tool calls collapsed into ONE whose arguments were\n * a 1,652-character non-JSON string, so zero proposals persisted and\n * nothing errored (agent-runtime #626);\n * - a thread took 255 user messages over 17 days and produced 2 replies,\n * both of them error text.\n *\n * A conventional health check cannot see any of these, because it probes\n * DEPENDENCIES (is the sandbox reachable, is the router up) and every one of\n * these failures happens with all dependencies green. This classifier probes\n * the OUTCOME instead.\n *\n * It is deliberately pure and structural: it reads a settled turn's own\n * projection, so the SAME function judges a live turn through the\n * `/chat-routes` lifecycle seam and a historical row read back out of the\n * store during a sweep. One definition of \"silently broken\", two call sites.\n */\n\n/** How loudly a reason should be routed. `critical` means a customer got\n * nothing usable; `warning` means the turn degraded but still produced\n * something a human could read. */\nexport type TurnHealthSeverity = 'critical' | 'warning'\n\n/** One specific way a turn returned success while failing.\n *\n * Each variant carries the evidence that identified it, so an alert can name\n * the offending value instead of asserting a verdict the reader has to take\n * on faith. */\nexport type TurnHealthReason =\n /** Settled without error and produced nothing a user can read: no text, and\n * no artifact part (file/image/work-product/plan/interaction). This is the\n * verbatim blank-completion capture. */\n | {\n kind: 'empty_completion'\n outputTokens: number | null\n partCount: number\n durationMs?: number\n }\n /** A tool call whose arguments never parsed. The engine surfaces unparseable\n * arguments as a RAW STRING rather than throwing, so the call is neither\n * dropped nor errored — it silently does nothing. Detecting a string-typed\n * tool input that fails `JSON.parse` is the exact fingerprint of the\n * index-less parallel-tool-call collapse. */\n | {\n kind: 'malformed_tool_call'\n tool: string\n inputLength: number\n /** Leading characters of the offending input, for the alert body. */\n sample: string\n }\n /** A tool call that never reached a terminal state carrying output. The call\n * was issued and then simply produced no effect. */\n | {\n kind: 'tool_call_no_effect'\n tool: string\n status: string\n }\n /** The turn failed outright. Not silent by itself — but it becomes silent\n * the moment nothing is watching, which is how 16 days of\n * `TANGLE_HUB_URL is required` reached customers unnoticed. */\n | { kind: 'turn_failed'; reason: string }\n /** A tool call the harness REJECTED, settled as `completed`.\n *\n * Found live in legal-agent production, and missed by every other rule here:\n * the model called `submit_proposal`, the harness answered \"Model tried to\n * call unavailable tool 'submit_proposal'\", and the part persisted as\n * `{\"tool\":\"invalid\",\"state\":{\"status\":\"completed\",\"input\":{\"error\":\"…\"}}}`.\n *\n * Status is `completed`, the arguments parse cleanly, and the turn has text —\n * so the blank-completion, malformed-argument and no-effect rules all pass it.\n * Six deliverables were requested and silently discarded while the product\n * reported success six times.\n *\n * Detected structurally, on the presence of an `error` in the settled state\n * rather than on any harness's name for a rejected call — `invalid` is one\n * harness's convention and must not be baked into the shell. */\n | {\n kind: 'tool_call_rejected'\n /** The tool the model was trying to reach, when the payload names it. */\n tool: string\n error: string\n }\n /** The turn was answered without the model ever running — a pre-producer gate\n * short-circuited and returned the product's own response.\n *\n * Reported as a `warning`, never `critical`: gating an unready turn is a\n * legitimate design (an intake flow SHOULD answer before spending a model\n * call). What is pathological is the RATE, which only the caller's own\n * threshold can judge — so this variant exists to be COUNTED, and alerting\n * on it is opt-in. It is the per-turn evidence behind a dead tool surface:\n * a gate that answers every turn means the agent never runs at all. */\n | { kind: 'answered_without_model' }\n /** The detector could not read this turn.\n *\n * Every part carried a type outside the vocabulary this classifier\n * understands — which is what field-level encryption at rest looks like from\n * the outside (tax-agent persists `{\"type\":\"__encrypted_parts__\"}`, its own\n * convention, and 32 of its 129 assistant rows are exactly that).\n *\n * This exists because the alternative is the bug this whole module hunts.\n * An unreadable row has no text, no artifact and no tool part, so every\n * other rule here would happily conclude \"nothing wrong\" — a detector\n * reporting health from data it cannot see. Blindness is a finding, not a\n * pass, so it gets its own reason and its own counter. */\n | { kind: 'unreadable_turn'; partTypes: string[] }\n\n/** A settled turn, in the narrowest shape both call sites can supply.\n *\n * Structural on purpose: the lifecycle seam supplies `finalText`/`usage`, a\n * store sweep supplies `content`/`parts` read back from a row, and neither\n * has to import the other's types. */\nexport interface TurnOutcomeInput {\n /** The turn's final assistant text. */\n finalText?: string | null\n /** The persisted assistant parts. Untyped by design — a sweep reads these\n * out of a JSON column and must not be forced to validate them first. */\n parts?: readonly unknown[] | null\n /** Output tokens, when the caller has usage. `null`/absent is unknown, which\n * is NOT the same as zero and is never treated as evidence. */\n outputTokens?: number | null\n /** Set when the turn surfaced a terminal error event. */\n failed?: boolean\n failureReason?: string | null\n durationMs?: number\n /** Set when a pre-producer gate answered this turn and the model never ran.\n * Supplied by `/chat-routes`' lifecycle seam, which stamps `gated` on the\n * completion it now fires for a `contextGate` short-circuit. */\n gated?: boolean\n}\n\n/** The verdict for one turn. `healthy` is exactly `reasons.length === 0`, kept\n * as a field so callers read intent rather than an array length. */\nexport interface TurnHealthVerdict {\n healthy: boolean\n severity: TurnHealthSeverity | null\n reasons: TurnHealthReason[]\n /** How many tool parts this turn carried.\n *\n * Zero is NOT a per-turn defect — plenty of good turns answer from context\n * without touching a tool, and paging on each one would be pure noise. It is\n * reported so a WINDOW can be judged: a product whose deliverable is tool\n * output and which produced zero tool calls across every turn in the\n * lookback has a dead tool surface, and that is the shape no per-turn rule\n * can see.\n *\n * Only meaningful alongside {@link interpretedParts} > 0. Zero tool calls\n * read off a row that persisted NO parts is not an observation about the\n * tool surface — it is the absence of one. */\n toolCalls: number\n /** True when nothing about this turn could be judged — no interpretable part\n * AND no visible text. Callers MUST exclude these from any healthy/unhealthy\n * ratio, because counting an unreadable turn as healthy is how a detector\n * reports green on data it never read. */\n unreadable: boolean\n /** False when this turn carried parts that could not be interpreted.\n *\n * Separate from {@link unreadable} because the two blindnesses have\n * different consequences, and production has a row that is one but not the\n * other: tax-agent persists CIPHERTEXT as `content` alongside an encrypted\n * `parts` blob, so the turn plainly delivered something (there is text) while\n * its tool calls are completely invisible.\n *\n * Any conclusion ABOUT TOOLS — above all the dead-tool-surface verdict — may\n * only be drawn over turns where this is true. Reading \"no tool parts\" off an\n * encrypted blob and declaring the tool surface dead would be the same\n * crime as declaring it healthy: a finding asserted from data never read. */\n partsReadable: boolean\n /** The part types that could not be interpreted. Empty when\n * {@link partsReadable}. Named in the alert so a reader can see EXACTLY what\n * the detector was blind to instead of taking \"unreadable\" on faith. */\n opaquePartTypes: string[]\n /** How many parts this module actually READ (text, artifact, tool, or a known\n * non-output kind).\n *\n * The third blindness, and the one that shipped a false page. `partsReadable`\n * only says nothing was *uninterpretable*; a row that persisted NO parts at\n * all satisfies that vacuously. Production: 97 of tax-agent's 156 assistant\n * rows predate parts persistence entirely and store `[]`, and reading \"zero\n * tool calls\" off them raised a critical `dead_tool_surface` against a\n * product whose own `turn_events` table holds 243 `tool_call` frames.\n *\n * So a tool verdict requires BOTH `partsReadable` AND this being > 0 —\n * evidence that was read, not merely evidence that failed to be unreadable. */\n interpretedParts: number\n}\n\n/** Part kinds that count as something a user actually receives.\n *\n * A tool part is deliberately NOT here. A turn that ran six tools and said\n * nothing, with no artifact to show for it, is the malformed-tool-call\n * disaster — counting a tool chip as output would suppress the very alert\n * this module exists to raise. */\nconst ARTIFACT_PART_KINDS = new Set(['file', 'image', 'work-product', 'plan', 'interaction'])\n\n/** Part types that carry no user-visible output but ARE understood.\n *\n * The distinction matters: a turn made of nothing but `reasoning` parts\n * thought hard and said nothing, which is a real empty completion. A turn made\n * of types this module has never heard of is a turn it cannot read. Only the\n * second is blindness — so these are enumerated rather than lumped in with the\n * unknown.\n *\n * Grounded in what the fleet actually persists, not guessed: a scan of every\n * assistant part in the gtm / legal / tax production tables returns exactly\n * `tool` (138), `text` (69), `reasoning` (26), `step-start` (3),\n * `step-finish` (3) and tax's opaque `__encrypted_parts__` (32). */\nconst KNOWN_NON_OUTPUT_PART_KINDS = new Set([\n 'reasoning',\n 'step-start',\n 'step-finish',\n 'source',\n 'source-url',\n 'data',\n])\n\nconst SAMPLE_CHARS = 120\n\nfunction asRecord(value: unknown): Record<string, unknown> | null {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim().length > 0 ? value : null\n}\n\n/** True when a string is not parseable JSON.\n *\n * Only meaningful for tool INPUT, where the engine's contract is that a\n * well-formed call carries an object (or a string that parses into one). A\n * string that fails to parse means the arguments were concatenated or\n * truncated upstream. */\nfunction isUnparseableJson(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.length === 0) return false\n try {\n JSON.parse(trimmed)\n return false\n } catch {\n return true\n }\n}\n\n/** Tool statuses that mean the call actually landed.\n *\n * Anything else — `pending`, `running`, an unknown string — left no persisted\n * effect by the time the turn settled. */\nconst SETTLED_TOOL_STATUSES = new Set(['completed', 'complete', 'success', 'done'])\n\n/** Tool statuses that ended the call by reporting its failure. The model and\n * the person saw the error, so the call is neither silently rejected nor left\n * without effect: on gtm-agent, 2,527 errored calls (HTTP statuses, missing\n * files, timeouts) in one day's 500 turns were all reported as REJECTED. */\nconst FAILED_TOOL_STATUSES = new Set(['error', 'failed'])\n\n/**\n * Judge one settled turn.\n *\n * Never throws: a malformed `parts` blob is a thing this function REPORTS on,\n * so it must not be a thing it dies on. Telemetry that can crash the turn it\n * measures is worse than no telemetry.\n */\nexport function classifyTurnOutcome(input: TurnOutcomeInput): TurnHealthVerdict {\n const reasons: TurnHealthReason[] = []\n\n if (input.failed) {\n reasons.push({\n kind: 'turn_failed',\n reason: nonEmptyString(input.failureReason) ?? 'unspecified',\n })\n }\n\n const parts = Array.isArray(input.parts) ? input.parts : []\n\n let hasVisibleText = nonEmptyString(input.finalText) !== null\n let artifactCount = 0\n let toolCalls = 0\n // Part types this module could not interpret. Tracked so blindness can be\n // reported as blindness instead of silently reading as health.\n const opaqueTypes: string[] = []\n let interpretedParts = 0\n\n for (const raw of parts) {\n const part = asRecord(raw)\n if (!part) continue\n const type = typeof part.type === 'string' ? part.type : ''\n\n if (type === 'text') {\n interpretedParts += 1\n if (nonEmptyString(part.text) !== null) hasVisibleText = true\n continue\n }\n if (ARTIFACT_PART_KINDS.has(type)) {\n interpretedParts += 1\n artifactCount += 1\n continue\n }\n if (KNOWN_NON_OUTPUT_PART_KINDS.has(type)) {\n interpretedParts += 1\n continue\n }\n if (type !== 'tool') {\n opaqueTypes.push(type || '(missing type)')\n continue\n }\n interpretedParts += 1\n toolCalls += 1\n\n const tool = nonEmptyString(part.tool) ?? 'unknown'\n const state = asRecord(part.state)\n const status = typeof state?.status === 'string' ? state.status : 'unknown'\n\n // The #626 fingerprint: arguments surfaced as a raw string because they\n // failed to parse upstream. Checked before the status gate — a malformed\n // call can still be marked completed, which is precisely why it is silent.\n // A rejected call settles as `completed` and carries its rejection in the\n // state. Checked BEFORE the status gate for the same reason as the\n // malformed case: the status is exactly what makes it silent.\n const toolInput = state?.input\n const inputRecord = asRecord(toolInput)\n const rejection =\n nonEmptyString(inputRecord?.error) ?? nonEmptyString((state as Record<string, unknown>)?.error)\n if (rejection && SETTLED_TOOL_STATUSES.has(status)) {\n reasons.push({\n kind: 'tool_call_rejected',\n // The payload names the tool the model MEANT to call; the part's own\n // `tool` is the harness's placeholder for a rejected call.\n tool: nonEmptyString(inputRecord?.tool) ?? tool,\n error: rejection.slice(0, 200),\n })\n continue\n }\n if (typeof toolInput === 'string' && isUnparseableJson(toolInput)) {\n reasons.push({\n kind: 'malformed_tool_call',\n tool,\n inputLength: toolInput.length,\n sample: toolInput.slice(0, SAMPLE_CHARS),\n })\n continue\n }\n\n if (!SETTLED_TOOL_STATUSES.has(status) && !FAILED_TOOL_STATUSES.has(status)) {\n reasons.push({ kind: 'tool_call_no_effect', tool, status })\n }\n }\n\n // A turn whose parts were ALL uninterpretable cannot be judged. Reported as\n // blindness and returned early, because every rule below would otherwise read\n // \"no text, no artifact\" off data that was simply encrypted and call it a\n // blank completion — a false page that would train readers to ignore this\n // module, which is the same ending as no detector at all.\n const partsReadable = opaqueTypes.length === 0\n const uniqueOpaque = [...new Set(opaqueTypes)]\n const unreadable = opaqueTypes.length > 0 && interpretedParts === 0 && !hasVisibleText\n if (unreadable) {\n reasons.push({ kind: 'unreadable_turn', partTypes: uniqueOpaque })\n return {\n healthy: false,\n severity: 'warning',\n reasons,\n toolCalls,\n unreadable: true,\n partsReadable: false,\n opaquePartTypes: uniqueOpaque,\n // Structurally 0 here — `unreadable` is only reached when\n // `interpretedParts === 0`. Carried rather than hardcoded so the field\n // has one source on every return path.\n interpretedParts,\n }\n }\n\n // A gate answered before the producer ran. Recorded rather than judged: see\n // `answered_without_model`. It also SUPPRESSES the empty-completion rule\n // below — the model producing no text is the expected outcome when the model\n // never ran, and firing `empty_completion` here would page on every healthy\n // intake turn.\n if (input.gated) {\n reasons.push({ kind: 'answered_without_model' })\n } else if (!input.failed && !hasVisibleText && artifactCount === 0) {\n // `outputTokens` is corroborating evidence, never the trigger: a turn can\n // spend tokens on reasoning and still deliver nothing, and a turn with\n // unknown usage can still be perfectly fine.\n reasons.push({\n kind: 'empty_completion',\n outputTokens: input.outputTokens ?? null,\n partCount: parts.length,\n ...(input.durationMs !== undefined ? { durationMs: input.durationMs } : {}),\n })\n }\n\n return {\n healthy: reasons.length === 0,\n severity: severityOf(reasons),\n reasons,\n toolCalls,\n unreadable: false,\n partsReadable,\n opaquePartTypes: uniqueOpaque,\n interpretedParts,\n }\n}\n\n/** `critical` when the customer got nothing usable out of the turn. A\n * malformed tool call alongside readable text is a `warning` — degraded, but\n * a human still received an answer. */\nfunction severityOf(reasons: TurnHealthReason[]): TurnHealthSeverity | null {\n if (reasons.length === 0) return null\n // A rejected tool call is critical even alongside readable prose: the\n // customer got words where they should have got a filed deliverable.\n const critical = reasons.some(\n (r) =>\n r.kind === 'empty_completion' ||\n r.kind === 'turn_failed' ||\n r.kind === 'tool_call_rejected',\n )\n return critical ? 'critical' : 'warning'\n}\n\n/** One-line human summary of a reason, for an alert body. */\nexport function describeReason(reason: TurnHealthReason): string {\n switch (reason.kind) {\n case 'empty_completion':\n return `completed with NO output (${reason.partCount} parts, outputTokens=${\n reason.outputTokens ?? 'unknown'\n })`\n case 'malformed_tool_call':\n return `tool \\`${reason.tool}\\` arguments did not parse (${reason.inputLength} chars): ${reason.sample}`\n case 'tool_call_no_effect':\n return `tool \\`${reason.tool}\\` left no effect (status=${reason.status})`\n case 'turn_failed':\n return `turn failed: ${reason.reason}`\n case 'tool_call_rejected':\n return `tool \\`${reason.tool}\\` was REJECTED but settled as completed: ${reason.error}`\n case 'answered_without_model':\n return 'answered by a pre-producer gate — the model never ran'\n case 'unreadable_turn':\n return `turn could not be read: every part had an uninterpretable type (${reason.partTypes.join(\n ', ',\n )})`\n }\n}\n"],"mappings":";AAwMA,IAAM,sBAAsB,oBAAI,IAAI,CAAC,QAAQ,SAAS,gBAAgB,QAAQ,aAAa,CAAC;AAc5F,IAAM,8BAA8B,oBAAI,IAAI;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAED,IAAM,eAAe;AAErB,SAAS,SAAS,OAAgD;AAChE,SAAO,OAAO,UAAU,YAAY,UAAU,OAAQ,QAAoC;AAC5F;AAEA,SAAS,eAAe,OAA+B;AACrD,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,QAAQ;AACxE;AAQA,SAAS,kBAAkB,OAAwB;AACjD,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,MAAI;AACF,SAAK,MAAM,OAAO;AAClB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM,wBAAwB,oBAAI,IAAI,CAAC,aAAa,YAAY,WAAW,MAAM,CAAC;AAMlF,IAAM,uBAAuB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AASjD,SAAS,oBAAoB,OAA4C;AAC9E,QAAM,UAA8B,CAAC;AAErC,MAAI,MAAM,QAAQ;AAChB,YAAQ,KAAK;AAAA,MACX,MAAM;AAAA,MACN,QAAQ,eAAe,MAAM,aAAa,KAAK;AAAA,IACjD,CAAC;AAAA,EACH;AAEA,QAAM,QAAQ,MAAM,QAAQ,MAAM,KAAK,IAAI,MAAM,QAAQ,CAAC;AAE1D,MAAI,iBAA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SAAS,iBACX,EAAE,SAAS;AAAA,EACf;AACA,SAAO,WAAW,aAAa;AACjC;AAGO,SAAS,eAAe,QAAkC;AAC/D,UAAQ,OAAO,MAAM;AAAA,IACnB,KAAK;AACH,aAAO,6BAA6B,OAAO,SAAS,wBAClD,OAAO,gBAAgB,SACzB;AAAA,IACF,KAAK;AACH,aAAO,UAAU,OAAO,IAAI,+BAA+B,OAAO,WAAW,YAAY,OAAO,MAAM;AAAA,IACxG,KAAK;AACH,aAAO,UAAU,OAAO,IAAI,6BAA6B,OAAO,MAAM;AAAA,IACxE,KAAK;AACH,aAAO,gBAAgB,OAAO,MAAM;AAAA,IACtC,KAAK;AACH,aAAO,UAAU,OAAO,IAAI,6CAA6C,OAAO,KAAK;AAAA,IACvF,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,mEAAmE,OAAO,UAAU;AAAA,QACzF;AAAA,MACF,CAAC;AAAA,EACL;AACF;","names":[]}
|
|
@@ -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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Y,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
|
+
{"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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C9B,cAAM,UAAU,WAAW,IAAI;AAC/B,YAAI,CAAC,UAAU,CAAC,QAAS,OAAM,OAAO,4BAA4B,wCAAwC;AAC1G,cAAM,cAAc,KAAK,IAAI,GAAG,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"]}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
createMultiAlertSink,
|
|
8
8
|
createThrottledAlertSink,
|
|
9
9
|
createWebhookAlertSink
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-IJ6B5ZPU.js";
|
|
11
11
|
import {
|
|
12
12
|
tallyD1Query
|
|
13
13
|
} from "./chunk-MM6RLOXF.js";
|
|
@@ -447,4 +447,4 @@ export {
|
|
|
447
447
|
PASTED_CODE_SAMPLES,
|
|
448
448
|
isEdgeBlock
|
|
449
449
|
};
|
|
450
|
-
//# sourceMappingURL=chunk-
|
|
450
|
+
//# sourceMappingURL=chunk-I4MPG5T6.js.map
|