@tangle-network/agent-app 0.63.30 → 0.63.32

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.
Files changed (133) hide show
  1. package/dist/{DesignCanvas-3DGZQOD7.js → DesignCanvas-VKZ7Y3JU.js} +2 -3
  2. package/dist/{DesignCanvasEditor-OG4QY5WJ.js → DesignCanvasEditor-3V53YLLZ.js} +2 -3
  3. package/dist/agent-profiles/d1.js +4 -3
  4. package/dist/agent-profiles/d1.js.map +1 -1
  5. package/dist/agent-profiles/index.js +4 -3
  6. package/dist/alerting/github.d.ts +33 -0
  7. package/dist/alerting/index.d.ts +1 -0
  8. package/dist/alerting/index.js +47 -0
  9. package/dist/alerting/index.js.map +1 -1
  10. package/dist/app-auth/index.js +1 -2
  11. package/dist/app-auth/index.js.map +1 -1
  12. package/dist/assistant/index.js +4 -4
  13. package/dist/billing/index.d.ts +15 -0
  14. package/dist/billing/index.js +5 -3
  15. package/dist/chat-routes/index.js +15 -14
  16. package/dist/chat-routes/index.js.map +1 -1
  17. package/dist/chat-store/index.js +34 -4
  18. package/dist/chat-store/index.js.map +1 -1
  19. package/dist/chat-store/schema.d.ts +286 -0
  20. package/dist/{chunk-6JEDSKFH.js → chunk-2SDX3OC4.js} +32 -24
  21. package/dist/{chunk-6JEDSKFH.js.map → chunk-2SDX3OC4.js.map} +1 -1
  22. package/dist/{chunk-QLZ6A73E.js → chunk-4CEIZZTH.js} +9 -9
  23. package/dist/{chunk-WL7PZK7Q.js → chunk-4PIN6QYQ.js} +43 -1
  24. package/dist/chunk-4PIN6QYQ.js.map +1 -0
  25. package/dist/{chunk-6UMIOEDR.js → chunk-AZRPDSRQ.js} +3 -3
  26. package/dist/{chunk-6LMM3OVX.js → chunk-BMCC2BUP.js} +3 -3
  27. package/dist/{chunk-36HSG7HU.js → chunk-CRZXEKCX.js} +2 -2
  28. package/dist/chunk-F4XBNR5L.js +16 -0
  29. package/dist/chunk-F4XBNR5L.js.map +1 -0
  30. package/dist/chunk-GY4IPYG4.js +40 -0
  31. package/dist/chunk-GY4IPYG4.js.map +1 -0
  32. package/dist/{chunk-6OG4244Y.js → chunk-MTKD2FN5.js} +2 -251
  33. package/dist/chunk-MTKD2FN5.js.map +1 -0
  34. package/dist/{chunk-5AUZR655.js → chunk-NDXQFEZQ.js} +51 -48
  35. package/dist/chunk-NDXQFEZQ.js.map +1 -0
  36. package/dist/chunk-NSWLZTJX.js +645 -0
  37. package/dist/chunk-NSWLZTJX.js.map +1 -0
  38. package/dist/chunk-PU6AWIRE.js +252 -0
  39. package/dist/chunk-PU6AWIRE.js.map +1 -0
  40. package/dist/{chunk-JKECSYDB.js → chunk-PV3GSLUY.js} +3 -3
  41. package/dist/{chunk-7Y7U7U7X.js → chunk-Q7RSHLEV.js} +5 -3
  42. package/dist/{chunk-7Y7U7U7X.js.map → chunk-Q7RSHLEV.js.map} +1 -1
  43. package/dist/{chunk-HRBF4B5L.js → chunk-TUJ4277Q.js} +1 -14
  44. package/dist/chunk-TUJ4277Q.js.map +1 -0
  45. package/dist/{chunk-57XPEL7X.js → chunk-V42C72V5.js} +25 -2
  46. package/dist/chunk-V42C72V5.js.map +1 -0
  47. package/dist/{chunk-FCYHDENJ.js → chunk-VOIVDEAV.js} +2 -2
  48. package/dist/{chunk-ACB7KOQ6.js → chunk-WSQSKYXP.js} +4 -4
  49. package/dist/{chunk-F6J5J4H6.js → chunk-WYQTPFPI.js} +26 -2
  50. package/dist/chunk-WYQTPFPI.js.map +1 -0
  51. package/dist/{chunk-PFTOGTHH.js → chunk-Z3IJ7XEW.js} +3 -3
  52. package/dist/{chunk-ZD2AUFIT.js → chunk-ZGGEYYEQ.js} +3 -3
  53. package/dist/{chunk-O5AUJQIA.js → chunk-ZNWJJRHP.js} +2 -2
  54. package/dist/design-canvas/index.js +1 -2
  55. package/dist/design-canvas/index.js.map +1 -1
  56. package/dist/design-canvas-react/engine.js +1 -2
  57. package/dist/design-canvas-react/index.js +2 -3
  58. package/dist/design-canvas-react/index.js.map +1 -1
  59. package/dist/design-canvas-react/lazy.js +1 -1
  60. package/dist/media/generate-request.d.ts +27 -1
  61. package/dist/media/index.js +36 -426
  62. package/dist/media/index.js.map +1 -1
  63. package/dist/media/router-generation.d.ts +7 -0
  64. package/dist/operator/gateway-keys.d.ts +44 -0
  65. package/dist/operator/index.d.ts +1 -0
  66. package/dist/operator/index.js +55 -1
  67. package/dist/operator/index.js.map +1 -1
  68. package/dist/plans/decision.d.ts +31 -0
  69. package/dist/plans/drizzle.js +1 -1
  70. package/dist/plans/index.js +5 -1
  71. package/dist/platform/billing.d.ts +3 -2
  72. package/dist/platform/deployment.d.ts +21 -0
  73. package/dist/platform/index.d.ts +1 -0
  74. package/dist/platform/index.js +30 -10
  75. package/dist/platform/index.js.map +1 -1
  76. package/dist/preset-cloudflare/index.js +9 -8
  77. package/dist/preset-cloudflare/index.js.map +1 -1
  78. package/dist/public-consultation/index.d.ts +1 -1
  79. package/dist/public-consultation/index.js +13 -12
  80. package/dist/public-consultation/index.js.map +1 -1
  81. package/dist/sandbox/computer-receipts.d.ts +1 -1
  82. package/dist/sandbox/index.d.ts +1 -0
  83. package/dist/sandbox/index.js +15 -8
  84. package/dist/sandbox/router-model-policy.d.ts +31 -0
  85. package/dist/sequences/index.js +1 -2
  86. package/dist/sequences/index.js.map +1 -1
  87. package/dist/spend/drizzle.d.ts +195 -0
  88. package/dist/spend/drizzle.js +22 -0
  89. package/dist/spend/drizzle.js.map +1 -1
  90. package/dist/stream/index.js +2 -2
  91. package/dist/studio/generated-media/flows.d.ts +240 -0
  92. package/dist/studio/generated-media/index.d.ts +3 -1
  93. package/dist/studio/generated-media/index.js +357 -138
  94. package/dist/studio/generated-media/index.js.map +1 -1
  95. package/dist/studio/index.js +18 -16
  96. package/dist/studio-react/index.js +28 -26
  97. package/dist/studio-react/index.js.map +1 -1
  98. package/dist/teams/index.d.ts +1 -0
  99. package/dist/teams/index.js +16 -0
  100. package/dist/teams/index.js.map +1 -1
  101. package/dist/teams/invitations-api.js +1 -1
  102. package/dist/teams/members-api.d.ts +5 -3
  103. package/dist/teams/members-api.js +1 -1
  104. package/dist/teams/thread-access.d.ts +22 -0
  105. package/dist/tools/index.js +5 -4
  106. package/dist/web/index.js +4 -6
  107. package/dist/web-react/index.js +4 -4
  108. package/dist/work-product/index.js +3 -2
  109. package/dist/work-product/index.js.map +1 -1
  110. package/dist/workspace-export/d1.d.ts +1 -1
  111. package/dist/workspace-export/index.js +9 -2
  112. package/dist/workspace-export/index.js.map +1 -1
  113. package/package.json +1 -1
  114. package/dist/chunk-57XPEL7X.js.map +0 -1
  115. package/dist/chunk-5AUZR655.js.map +0 -1
  116. package/dist/chunk-6OG4244Y.js.map +0 -1
  117. package/dist/chunk-6Z7TZVKZ.js +0 -26
  118. package/dist/chunk-6Z7TZVKZ.js.map +0 -1
  119. package/dist/chunk-F6J5J4H6.js.map +0 -1
  120. package/dist/chunk-HRBF4B5L.js.map +0 -1
  121. package/dist/chunk-WL7PZK7Q.js.map +0 -1
  122. /package/dist/{DesignCanvas-3DGZQOD7.js.map → DesignCanvas-VKZ7Y3JU.js.map} +0 -0
  123. /package/dist/{DesignCanvasEditor-OG4QY5WJ.js.map → DesignCanvasEditor-3V53YLLZ.js.map} +0 -0
  124. /package/dist/{chunk-QLZ6A73E.js.map → chunk-4CEIZZTH.js.map} +0 -0
  125. /package/dist/{chunk-6UMIOEDR.js.map → chunk-AZRPDSRQ.js.map} +0 -0
  126. /package/dist/{chunk-6LMM3OVX.js.map → chunk-BMCC2BUP.js.map} +0 -0
  127. /package/dist/{chunk-36HSG7HU.js.map → chunk-CRZXEKCX.js.map} +0 -0
  128. /package/dist/{chunk-JKECSYDB.js.map → chunk-PV3GSLUY.js.map} +0 -0
  129. /package/dist/{chunk-FCYHDENJ.js.map → chunk-VOIVDEAV.js.map} +0 -0
  130. /package/dist/{chunk-ACB7KOQ6.js.map → chunk-WSQSKYXP.js.map} +0 -0
  131. /package/dist/{chunk-PFTOGTHH.js.map → chunk-Z3IJ7XEW.js.map} +0 -0
  132. /package/dist/{chunk-ZD2AUFIT.js.map → chunk-ZGGEYYEQ.js.map} +0 -0
  133. /package/dist/{chunk-O5AUJQIA.js.map → chunk-ZNWJJRHP.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/operator/server.ts","../../src/operator/chat-adapter.ts","../../src/operator/platform-agent-keys.ts"],"sourcesContent":["import { parseChatAttachmentInputs } from '../chat-routes/attachment-validation.js'\nimport { createApiKeyRequestAuth, type RequestApiKey } from '../platform/api-key-auth.js'\nimport {\n OPERATOR_API_BASE_PATH,\n OPERATOR_API_VERSION,\n OPERATOR_SETTLED_STATES,\n matchOperatorRoute,\n operatorKeyWorkspaces,\n type OperatorApproval,\n type OperatorCapability,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorRouteId,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\n/** The verified caller of one operator request. */\nexport interface OperatorContext<Identity> {\n identity: Identity\n key: { keyId: string; scopes: readonly string[] }\n request: Request\n}\n\n/**\n * The app's side of the operator API: storage and execution only. Scope,\n * workspace restriction, input validation, and response shapes belong to the\n * shared handler, so every app answers the same way.\n */\nexport interface OperatorAdapter<Identity> {\n /**\n * Apply the app's workspace roles: `read` needs viewer access, `run` needs\n * the role that may start agent work. Null answers 404, so a key cannot\n * probe workspaces it cannot reach.\n */\n authorizeWorkspace(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<OperatorWorkspace | null>\n listWorkspaces(ctx: OperatorContext<Identity>): Promise<OperatorWorkspace[]>\n createWorkspace?(ctx: OperatorContext<Identity>, input: { name: string }): Promise<OperatorWorkspace>\n /**\n * True when `startTurn` delivers `input.attachments` to the agent, through\n * a chat route whose attachment resolver reads them from the workspace's\n * store. Otherwise the handler refuses turns that carry attachments rather\n * than letting them be dropped.\n */\n acceptsAttachments?: boolean\n /**\n * Most attachments one turn may carry. Default `ATTACHMENT_MAX_COUNT`, the\n * chat route's own default; an app whose chat route admits more per message\n * sets the same number here.\n */\n maxAttachments?: number\n /** Admit the turn durably and return without waiting for it; the same turnId never starts twice. */\n startTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, input: StartTurnInput): Promise<OperatorTurn>\n getTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, target: { threadId: string; turnId: string }): Promise<OperatorTurn | null>\n /**\n * Stop an unsettled turn through the app's own interrupt path and return the\n * turn as read afterwards. It may still read `working` until the app's turn\n * owner records the stop; once recorded, the turn settles `failed` with\n * `OPERATOR_TURN_CANCELLED_CODE`. Null when the turn is not in this\n * workspace. Throw a retryable `OperatorError` when the stop could not be\n * delivered. The handler never calls it for a settled turn.\n */\n cancelTurn?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, target: { threadId: string; turnId: string }): Promise<OperatorTurn | null>\n listThreads?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { cursor?: string; limit: number }): Promise<{ threads: OperatorThread[]; nextCursor: string | null }>\n getThread?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, threadId: string): Promise<{ thread: OperatorThread; latestTurn: OperatorTurn | null } | null>\n listApprovals(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace): Promise<OperatorApproval[]>\n listJournal?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { days: number }): Promise<OperatorJournalEntry[]>\n listFiles?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { prefix: string }): Promise<OperatorFileEntry[]>\n readFile?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, path: string): Promise<OperatorFile | null>\n /** The stored bytes, or null when the asset is not in this workspace. */\n readAsset?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, assetId: string): Promise<Response | null>\n getScorecard?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { days: number }): Promise<OperatorScorecard>\n}\n\nexport interface OperatorKeyStore<Key extends RequestApiKey, Identity> {\n /** Verify against the app's existing key store, including revocation. */\n verify(authorization: string): Promise<Key | null>\n /** Load the key owner; throw a Response to refuse a key class, such as spending-capped keys. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically count the request against the key's limits. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\nexport interface OperatorApiOptions<Key extends RequestApiKey, Identity> {\n app: { id: string; name: string }\n keys: OperatorKeyStore<Key, Identity>\n adapter: OperatorAdapter<Identity>\n basePath?: string\n /** Longest hold for a turn read with `?wait=`, in seconds. */\n maxWaitSeconds?: number\n /** Interval between state reads during a held turn read. */\n pollIntervalMs?: number\n /** Unexpected adapter failures; responses never carry their detail. */\n onError?(error: unknown, route: OperatorRouteId): void\n}\n\nexport interface OperatorApi {\n /** True when the request addresses this API's base path. */\n matches(request: Request): boolean\n handle(request: Request): Promise<Response>\n}\n\n/** A refusal with a stable code; adapters throw it for expected failures. */\nexport class OperatorError extends Error {\n constructor(\n readonly code: string,\n readonly status: number,\n message?: string,\n readonly retryable = false,\n ) {\n super(message ?? code)\n this.name = 'OperatorError'\n }\n}\n\nconst TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst THREAD_ID = /^[A-Za-z0-9_-]{1,256}$/\nconst MAX_BODY_BYTES = 128 * 1024\nconst MAX_CONTENT_BYTES = 64 * 1024\nconst START_FIELDS = new Set(['turnId', 'content', 'threadId', 'title', 'model', 'attachments'])\n\nconst NO_STORE = { 'cache-control': 'private, no-store' }\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, { status, headers: NO_STORE })\n}\n\nfunction refusal(status: number, code: string, error: string, retryable = false): Response {\n return json({ error, code, ...(retryable ? { retryable } : {}) }, status)\n}\n\nfunction boundedInteger(value: string | null, fallback: number, min: number, max: number, name: string): number {\n if (value === null || value === '') return fallback\n if (!/^\\d{1,6}$/.test(value)) throw new OperatorError('operator.invalid_input', 400, `${name} must be a whole number`)\n const parsed = Number(value)\n if (parsed < min || parsed > max) throw new OperatorError('operator.invalid_input', 400, `${name} must be between ${min} and ${max}`)\n return parsed\n}\n\n/** Workspace-relative paths only: no absolute, parent, empty, or backslash segments. */\nfunction relativePath(value: string | null, name: string, { allowEmpty }: { allowEmpty: boolean }): string {\n const path = value ?? ''\n if (path === '' && allowEmpty) return ''\n if (!path || path.length > 1024 || path.startsWith('/') || path.includes('\\\\') || /[\\u0000-\\u001f\\u007f]/.test(path)) {\n throw new OperatorError('operator.invalid_path', 400, `${name} must be a workspace-relative path`)\n }\n const segments = path.replace(/\\/$/, '').split('/')\n if (segments.some((segment) => !segment || segment === '.' || segment === '..')) {\n throw new OperatorError('operator.invalid_path', 400, `${name} must be a workspace-relative path`)\n }\n return path\n}\n\nasync function readJsonBody(request: Request): Promise<Record<string, unknown>> {\n const declared = Number(request.headers.get('content-length') ?? '0')\n if (declared > MAX_BODY_BYTES) throw new OperatorError('operator.body_too_large', 413, 'Request body is too large')\n const text = await request.text()\n if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES) {\n throw new OperatorError('operator.body_too_large', 413, 'Request body is too large')\n }\n let parsed: unknown\n try { parsed = JSON.parse(text) } catch { throw new OperatorError('operator.invalid_json', 400, 'Body must be a JSON object') }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new OperatorError('operator.invalid_json', 400, 'Body must be a JSON object')\n }\n return parsed as Record<string, unknown>\n}\n\nfunction optionalString(body: Record<string, unknown>, name: string, max: number): string | undefined {\n const value = body[name]\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string' || !value.trim() || value.length > max) {\n throw new OperatorError('operator.invalid_input', 400, `${name} must be a nonempty string of at most ${max} characters`)\n }\n return value.trim()\n}\n\n/** Identity and destination come from the key and the path; the body can only describe the work. */\nfunction parseStartTurn(body: Record<string, unknown>, maxAttachments: number | undefined): StartTurnInput {\n const unknown = Object.keys(body).filter((field) => !START_FIELDS.has(field))\n if (unknown.length) throw new OperatorError('operator.invalid_input', 400, `Unknown fields: ${unknown.join(', ')}`)\n if (typeof body.turnId !== 'string' || !TURN_ID.test(body.turnId)) {\n throw new OperatorError('operator.invalid_input', 400, 'turnId must be a client-generated UUID')\n }\n if (typeof body.content !== 'string' || !body.content.trim()) {\n throw new OperatorError('operator.invalid_input', 400, 'content must be a nonempty string')\n }\n if (new TextEncoder().encode(body.content).byteLength > MAX_CONTENT_BYTES) {\n throw new OperatorError('operator.invalid_input', 400, `content must be at most ${MAX_CONTENT_BYTES} bytes`)\n }\n const threadId = optionalString(body, 'threadId', 256)\n if (threadId !== undefined && !THREAD_ID.test(threadId)) {\n throw new OperatorError('operator.invalid_input', 400, 'threadId contains only letters, digits, - and _')\n }\n const title = optionalString(body, 'title', 200)\n const model = optionalString(body, 'model', 200)\n // The chat route's own structural rules; the app's store read re-checks\n // every path against this workspace and re-derives every size.\n const attachments = parseChatAttachmentInputs(body.attachments, maxAttachments === undefined ? {} : { maxCount: maxAttachments })\n if (!attachments.succeeded) throw new OperatorError('operator.invalid_input', 400, attachments.error)\n return {\n turnId: body.turnId.toLowerCase(),\n content: body.content,\n ...(threadId === undefined ? {} : { threadId }),\n ...(title === undefined ? {} : { title }),\n ...(model === undefined ? {} : { model }),\n ...(attachments.value.length === 0 ? {} : { attachments: attachments.value }),\n }\n}\n\nfunction capabilities<Identity>(adapter: OperatorAdapter<Identity>): OperatorCapability[] {\n const present: Array<[OperatorCapability, unknown]> = [\n ['turns.cancel', adapter.cancelTurn],\n ['workspaces.create', adapter.createWorkspace],\n ['threads.read', adapter.getThread ?? adapter.listThreads],\n ['files.read', adapter.readFile ?? adapter.listFiles],\n ['journal.read', adapter.listJournal],\n ['assets.read', adapter.readAsset],\n ['scorecard.read', adapter.getScorecard],\n ]\n const implemented = present.filter(([, method]) => typeof method === 'function').map(([name]) => name)\n return adapter.acceptsAttachments === true ? ['turns.attachments', ...implemented] : implemented\n}\n\nfunction unsupported(): never {\n throw new OperatorError('operator.unsupported', 501, 'This app does not implement this operation')\n}\n\nfunction settled(turn: OperatorTurn): boolean {\n return OPERATOR_SETTLED_STATES.includes(turn.state)\n}\n\n/** A held turn read returns as soon as the turn settles or waits on a decision. */\nfunction needsAttention(turn: OperatorTurn): boolean {\n return settled(turn) || turn.state === 'input-required' || turn.approvals.length > 0\n}\n\nconst sleep = (ms: number, signal: AbortSignal) => new Promise<void>((resolve) => {\n if (signal.aborted) return resolve()\n const timer = setTimeout(resolve, ms)\n signal.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true })\n})\n\n/**\n * Mount the standard operator API. Requests must carry a Bearer key: there is\n * no browser-cookie fallback, so a page session never reaches these routes.\n */\nexport function createOperatorApi<Key extends RequestApiKey, Identity>(\n options: OperatorApiOptions<Key, Identity>,\n): OperatorApi {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const maxWaitSeconds = Math.max(0, Math.min(options.maxWaitSeconds ?? 25, 55))\n const pollIntervalMs = Math.max(250, options.pollIntervalMs ?? 2_000)\n const { adapter } = options\n\n function matches(request: Request): boolean {\n const { pathname } = new URL(request.url)\n return pathname === basePath || pathname.startsWith(`${basePath}/`)\n }\n\n async function handle(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const match = matchOperatorRoute(request.method, url.pathname, basePath)\n if (!match) return refusal(404, 'operator.route_not_found', 'No operator route matches this method and path')\n const { route, params } = match\n if (request.headers.get('Authorization') === null) {\n return refusal(401, 'operator.unauthenticated', 'An operator API key is required')\n }\n\n let verified: { identity: Identity; key: Key }\n try {\n const authenticate = createApiKeyRequestAuth<Key, { identity: Identity; key: Key }>({\n verify: (authorization) => options.keys.verify(authorization),\n requiredScope: () => route.scopes,\n resolveIdentity: async (key) => {\n const identity = await options.keys.resolveIdentity(key)\n return identity === null || identity === undefined ? null : { identity, key }\n },\n claimRequest: (key, requestId) => options.keys.claimRequest(key, requestId),\n })\n const result = await authenticate(request)\n if (!result) return refusal(401, 'operator.unauthenticated', 'An operator API key is required')\n verified = result\n } catch (error) {\n if (error instanceof Response) return error\n options.onError?.(error, route.id)\n return refusal(503, 'operator.auth_unavailable', 'Key verification is unavailable', true)\n }\n\n const ctx: OperatorContext<Identity> = {\n identity: verified.identity,\n key: { keyId: verified.key.keyId, scopes: [...verified.key.scopes] },\n request,\n }\n const restriction = operatorKeyWorkspaces(verified.key.scopes)\n\n try {\n if (route.id === 'describe') {\n return json({\n app: {\n app: options.app.id, name: options.app.name, apiVersion: OPERATOR_API_VERSION,\n capabilities: capabilities(adapter),\n },\n principal: { keyId: ctx.key.keyId, scopes: [...ctx.key.scopes], workspaces: restriction ? [...restriction] : null },\n })\n }\n if (route.id === 'workspaces.list') {\n const listed = await adapter.listWorkspaces(ctx)\n return json({ workspaces: restriction ? listed.filter((workspace) => restriction.includes(workspace.id)) : listed })\n }\n if (route.id === 'workspaces.create') {\n if (restriction) {\n throw new OperatorError('operator.workspace_restricted', 403, 'A workspace-restricted key cannot create workspaces')\n }\n if (!adapter.createWorkspace) unsupported()\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((field) => field !== 'name')\n if (unknown.length) throw new OperatorError('operator.invalid_input', 400, `Unknown fields: ${unknown.join(', ')}`)\n const name = optionalString(body, 'name', 120)\n if (!name) throw new OperatorError('operator.invalid_input', 400, 'name is required')\n return json({ workspace: await adapter.createWorkspace(ctx, { name }) }, 201)\n }\n\n const workspaceId = params.workspaceId!\n if (restriction && !restriction.includes(workspaceId)) {\n throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n }\n const runs = route.id === 'turns.start' || route.id === 'turns.cancel'\n const workspace = await adapter.authorizeWorkspace(ctx, workspaceId, runs ? 'run' : 'read')\n if (!workspace) throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n\n /** Re-read the turn every poll interval until `done`, `wait` seconds pass, or the caller leaves. */\n const hold = async (first: OperatorTurn | null, target: { threadId: string; turnId: string }, wait: number, done: (turn: OperatorTurn) => boolean) => {\n const deadline = Date.now() + wait * 1000\n let turn = first\n while (turn && !done(turn) && Date.now() + pollIntervalMs <= deadline && !request.signal.aborted) {\n await sleep(pollIntervalMs, request.signal)\n turn = await adapter.getTurn(ctx, workspace, target)\n }\n if (!turn) throw new OperatorError('operator.turn_not_found', 404, 'Turn not found')\n return turn\n }\n\n switch (route.id) {\n case 'workspaces.get':\n return json({ workspace })\n case 'turns.start': {\n const input = parseStartTurn(await readJsonBody(request), adapter.maxAttachments)\n if (input.attachments && adapter.acceptsAttachments !== true) {\n throw new OperatorError('operator.unsupported', 501, 'This app does not accept attachments on operator turns')\n }\n return json({ turn: await adapter.startTurn(ctx, workspace, input) }, 202)\n }\n case 'threads.list': {\n if (!adapter.listThreads) unsupported()\n const limit = boundedInteger(url.searchParams.get('limit'), 25, 1, 100, 'limit')\n const cursor = url.searchParams.get('cursor') ?? undefined\n if (cursor !== undefined && (cursor.length > 512 || !cursor)) {\n throw new OperatorError('operator.invalid_input', 400, 'cursor is invalid')\n }\n return json(await adapter.listThreads(ctx, workspace, { limit, ...(cursor ? { cursor } : {}) }))\n }\n case 'threads.get': {\n if (!adapter.getThread) unsupported()\n const found = await adapter.getThread(ctx, workspace, params.threadId!)\n if (!found) throw new OperatorError('operator.thread_not_found', 404, 'Thread not found')\n return json(found)\n }\n case 'turns.get': {\n const target = { threadId: params.threadId!, turnId: params.turnId! }\n const wait = boundedInteger(url.searchParams.get('wait'), 0, 0, maxWaitSeconds, 'wait')\n return json({ turn: await hold(await adapter.getTurn(ctx, workspace, target), target, wait, needsAttention) })\n }\n case 'turns.cancel': {\n if (!adapter.cancelTurn) unsupported()\n const target = { threadId: params.threadId!, turnId: params.turnId! }\n const wait = boundedInteger(url.searchParams.get('wait'), 0, 0, maxWaitSeconds, 'wait')\n const current = await adapter.getTurn(ctx, workspace, target)\n if (!current) throw new OperatorError('operator.turn_not_found', 404, 'Turn not found')\n // Cancelling a settled turn reads it: a repeat or late cancel never fails and never reaches the app.\n if (settled(current)) return json({ turn: current })\n const turn = await hold(await adapter.cancelTurn(ctx, workspace, target), target, wait, settled)\n return json({ turn }, settled(turn) ? 200 : 202)\n }\n case 'approvals.list':\n return json({ approvals: await adapter.listApprovals(ctx, workspace) })\n case 'journal.list': {\n if (!adapter.listJournal) unsupported()\n const days = boundedInteger(url.searchParams.get('days'), 7, 1, 90, 'days')\n return json({ entries: await adapter.listJournal(ctx, workspace, { days }) })\n }\n case 'files.list': {\n if (!adapter.listFiles) unsupported()\n const prefix = relativePath(url.searchParams.get('prefix'), 'prefix', { allowEmpty: true })\n return json({ files: await adapter.listFiles(ctx, workspace, { prefix }) })\n }\n case 'files.read': {\n if (!adapter.readFile) unsupported()\n const path = relativePath(url.searchParams.get('path'), 'path', { allowEmpty: false })\n const file = await adapter.readFile(ctx, workspace, path)\n if (!file) throw new OperatorError('operator.file_not_found', 404, 'File not found')\n return json({ file })\n }\n case 'assets.read': {\n if (!adapter.readAsset) unsupported()\n const response = await adapter.readAsset(ctx, workspace, params.assetId!)\n if (!response) throw new OperatorError('operator.asset_not_found', 404, 'Asset not found')\n const headers = new Headers(response.headers)\n headers.set('cache-control', 'private, no-store')\n headers.delete('set-cookie')\n return new Response(response.body, { status: response.status, headers })\n }\n case 'scorecard.get': {\n if (!adapter.getScorecard) unsupported()\n const days = boundedInteger(url.searchParams.get('days'), 7, 1, 90, 'days')\n return json({ scorecard: await adapter.getScorecard(ctx, workspace, { days }) })\n }\n }\n return refusal(404, 'operator.route_not_found', 'No operator route matches this method and path')\n } catch (error) {\n if (error instanceof OperatorError) return refusal(error.status, error.code, error.message, error.retryable)\n if (error instanceof Response) return error\n options.onError?.(error, route.id)\n return refusal(500, 'operator.internal', 'The operation failed', true)\n }\n }\n\n return { matches, handle }\n}\n","import type { ChatAttachmentInput } from '../chat-routes/wire.js'\nimport { messageHasTurnId } from '../stream/turn-identity.js'\nimport type {\n OperatorApproval,\n OperatorAssetRef,\n OperatorFile,\n OperatorFileChange,\n OperatorFileEntry,\n OperatorJournalEntry,\n OperatorRole,\n OperatorScorecard,\n OperatorThread,\n OperatorTurn,\n OperatorTurnState,\n OperatorWorkspace,\n StartTurnInput,\n} from './contract.js'\nimport { OperatorError, type OperatorAdapter, type OperatorContext } from './server.js'\nimport { sha256Hex } from '../crypto/digest'\n\n/** The message fields the adapter reads; agent-app's chat-store rows satisfy it. */\nexport interface ChatOperatorMessage {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n /** Typed chat parts, such as chat-store's, are read field by field. */\n parts: ReadonlyArray<object> | null\n createdAt?: Date | string | number | null\n model?: string | null\n servedModel?: string | null\n costUsd?: number | null\n /** Explicit producer facts, supplied by the app's stored-row projection; metadata is not interpreted. */\n costSource?: OperatorTurn['costSource'] | null\n billingOwner?: OperatorTurn['billingOwner'] | null\n credentialSource?: OperatorTurn['credentialSource'] | null\n settlementRecord?: string | null\n /** Usage columns as chat-store stores them; see `operatorTurnUsage` for what `inputTokens` holds. */\n inputTokens?: number | null\n cacheReadTokens?: number | null\n outputTokens?: number | null\n /** The row's product metadata, for a `failureOf` that reads a stamped turn status. */\n metadata?: Record<string, unknown> | null\n}\n\nexport interface ChatOperatorThread {\n id: string\n workspaceId: string\n title: string\n updatedAt?: Date | string | number | null\n}\n\nexport interface ChatOperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n createdAt?: Date | string | number | null\n}\n\n/** A durable execution claim, separate from the chat transcript that owns results. */\nexport interface ChatOperatorAdmission {\n threadId: string\n /** Only an explicit refusal before a usable stream opened is recorded here. */\n refusal?: { code?: string; message: string }\n}\n\n/** Product-owned atomic storage for duplicate suppression across processes.\n * A claim with no transcript stays unknown after a crash; it never licenses a\n * second execution. This is not a completion ledger or an automatic retry queue.\n */\nexport interface ChatOperatorAdmissionStore<Identity> {\n get(ctx: OperatorContext<Identity>, workspaceId: string, turnId: string): Promise<ChatOperatorAdmission | null>\n claim(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string }): Promise<boolean>\n recordRefusal(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string }, refusal: { code?: string; message: string }): Promise<void>\n}\n\nexport interface ChatOperatorAdapterOptions<Identity> {\n /** Optional durable claims; without one, transcript retry detection is not an atomic admission lock. */\n admissions?: ChatOperatorAdmissionStore<Identity>\n /**\n * Set when `runTurn` forwards `attachments` in the chat request body and the\n * chat route resolves them from the workspace's store, as with\n * `resolveChatAttachments`. Without it, turns that carry attachments are refused.\n */\n acceptsAttachments?: boolean\n /** Most attachments one turn may carry; set it to the chat route's own count cap. Default `ATTACHMENT_MAX_COUNT`. */\n maxAttachments?: number\n /** The app's public origin, the base of every browser link. */\n origin: string\n /** Browser path of a conversation; defaults to `/app/<workspace>/chat/<thread>`. */\n threadPath?(workspaceId: string, threadId: string): string\n /** Browser path of a workspace; defaults to `/app/<workspace>`. */\n workspacePath?(workspaceId: string): string\n workspaces: {\n /** Apply the app's roles: `read` needs viewer access, `run` the role that may start agent work. */\n authorize(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<ChatOperatorWorkspace | null>\n list(ctx: OperatorContext<Identity>): Promise<ChatOperatorWorkspace[]>\n create?(ctx: OperatorContext<Identity>, input: { name: string }): Promise<ChatOperatorWorkspace>\n }\n threads: {\n /**\n * A thread this caller may read, or null. An app whose conversations\n * belong to one user (not the whole workspace) applies that here.\n */\n get(threadId: string, ctx: OperatorContext<Identity>): Promise<ChatOperatorThread | null>\n /** Insert a thread with this id for this caller; agent-app's chat store accepts a caller-assigned id. */\n create(ctx: OperatorContext<Identity>, input: { id: string; workspaceId: string; title: string }): Promise<ChatOperatorThread>\n /** Oldest first. */\n listMessages(threadId: string, ctx: OperatorContext<Identity>): Promise<ChatOperatorMessage[]>\n list?(ctx: OperatorContext<Identity>, workspaceId: string, query: { cursor?: string; limit: number }): Promise<{ threads: ChatOperatorThread[]; nextCursor: string | null }>\n }\n /**\n * Run one turn through the app's own chat route as this caller. The adapter\n * reads the response to its end, so the turn is driven exactly as a browser\n * holding its stream drives it, and the start request returns once it settles.\n * `attachments` arrives only when `acceptsAttachments` is set.\n */\n runTurn(ctx: OperatorContext<Identity>, input: {\n workspaceId: string; threadId: string; turnId: string; content: string; model?: string\n attachments?: ChatAttachmentInput[]\n }): Promise<Response>\n /** Optional authoritative status of this user-turn anchor. When supplied,\n * missing/running status without a live lease never promotes a partial reply to success. */\n turnStatus?(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string, user: ChatOperatorMessage): Promise<'running' | 'complete' | 'error' | null>\n /** Turn ids still running on a thread, or null when the app cannot tell. */\n runningTurns?(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string): Promise<string[] | null>\n /** Decisions open in the workspace, or on one conversation when `threadId` is set. */\n approvals?(ctx: OperatorContext<Identity>, workspaceId: string, threadId?: string): Promise<OperatorApproval[]>\n files?: {\n list(ctx: OperatorContext<Identity>, workspaceId: string, prefix: string): Promise<OperatorFileEntry[]>\n read(ctx: OperatorContext<Identity>, workspaceId: string, path: string): Promise<OperatorFile | null>\n }\n journal?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorJournalEntry[]>\n assets?: {\n /** Assets a reply references; defaults to none. */\n refs?(message: ChatOperatorMessage, workspaceId: string): OperatorAssetRef[]\n read?(ctx: OperatorContext<Identity>, workspaceId: string, assetId: string): Promise<Response | null>\n }\n scorecard?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorScorecard>\n /**\n * A reply's failure. Defaults to an `error` notice (the sandbox producer's\n * `errorNotice` mode), a `turn-failure` notice or an `error` part.\n */\n failureOf?(message: ChatOperatorMessage): { code?: string; message: string } | null\n /**\n * Whether stored rows' `inputTokens` include cache reads, for\n * `operatorTurnUsage`. A row does not say which writer or version stored\n * it, so pass a boolean only when every writer of the app's rows is known\n * to follow it. Default `'unknown'` reports `inputTokens` only on rows that\n * record zero cache reads.\n */\n inputIncludesCache?: boolean | 'unknown'\n}\n\nconst iso = (value: Date | string | number | null | undefined): string | undefined => {\n if (value === null || value === undefined) return undefined\n const date = value instanceof Date ? value : new Date(typeof value === 'number' && value < 1e12 ? value * 1000 : value)\n return Number.isNaN(date.getTime()) ? undefined : date.toISOString()\n}\n\nconst text = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value : null)\n\nfunction partsOf(message: ChatOperatorMessage): ReadonlyArray<Record<string, unknown>> {\n return (message.parts ?? []) as ReadonlyArray<Record<string, unknown>>\n}\n\nfunction defaultFailure(message: ChatOperatorMessage): { code?: string; message: string } | null {\n for (const part of partsOf(message)) {\n const errorNotice = part.type === 'notice' && part.noticeKind === 'error'\n const notice = errorNotice || (part.type === 'notice' && (part.noticeKind === 'turn-failure' || part.kind === 'turn-failure'))\n if (!notice && part.type !== 'error') continue\n const detail = text(part.message) ?? text(part.text) ?? text(part.error) ?? 'The turn failed'\n // An error notice always names a reason, so a caller can tell failures apart.\n const code = typeof part.code === 'string' ? part.code : errorNotice ? 'turn.error' : undefined\n return { ...(code ? { code } : {}), message: detail }\n }\n return null\n}\n\nfunction fileChanges(message: ChatOperatorMessage): OperatorFileChange[] {\n const files: OperatorFileChange[] = []\n for (const part of partsOf(message)) {\n if (part.type !== 'session-artifact' || typeof part.path !== 'string') continue\n const action = part.action === 'created' || part.action === 'updated' || part.action === 'deleted' ? part.action : 'changed'\n if (!files.some((file) => file.path === part.path)) files.push({ path: part.path, action })\n }\n return files\n}\n\nfunction turnIdOf(message: ChatOperatorMessage): string | null {\n for (const part of partsOf(message)) {\n if (typeof part.turnId === 'string' && part.turnId) return part.turnId\n }\n return null\n}\n\n/**\n * The operator turn usage of a stored assistant row, for `OperatorTurn.usage`.\n * `cachedInputTokens` is the row's `cacheReadTokens` and `outputTokens` its\n * `outputTokens`, each when the row has it. `inputTokens` is reported only as\n * the prompt NOT read from cache, and a row does not record whether its\n * `inputTokens` already excludes cache reads: the Router lane subtracts them\n * before storing since 0.60.248 and included them before, and the sandbox\n * lanes store the split their upstream reports. A missing `cacheReadTokens`\n * is unknown, not 0. So:\n * - `'unknown'` (the default) reports the row's `inputTokens` only when\n * `cacheReadTokens` is a recorded 0, and omits it otherwise;\n * - `inputIncludesCache: false` reports the row's `inputTokens`, with or\n * without a recorded `cacheReadTokens`;\n * - `inputIncludesCache: true` reports `inputTokens - cacheReadTokens` when\n * `cacheReadTokens` is recorded and the difference is not negative, and\n * omits it otherwise.\n * `cachedInputTokens` and `outputTokens` are reported whenever the row\n * records them, independent of `inputTokens`.\n * A count that is not a finite number is omitted, never zeroed; a row with no\n * count gives `undefined`. An app that builds its own operator turns from such\n * rows calls this rather than mapping them itself.\n */\nexport function operatorTurnUsage(\n row: Pick<ChatOperatorMessage, 'inputTokens' | 'cacheReadTokens' | 'outputTokens'>,\n options: { inputIncludesCache?: boolean | 'unknown' } = {},\n): OperatorTurn['usage'] {\n const count = (value: number | null | undefined) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)\n const input = count(row.inputTokens)\n const cached = count(row.cacheReadTokens)\n const output = count(row.outputTokens)\n const includes = options.inputIncludesCache ?? 'unknown'\n const uncached = input === undefined ? undefined\n : includes === false ? input\n : includes === true ? (cached !== undefined && input - cached >= 0 ? input - cached : undefined)\n : cached === 0 ? input\n : undefined\n const usage: NonNullable<OperatorTurn['usage']> = {\n ...(uncached !== undefined ? { inputTokens: uncached } : {}),\n ...(cached !== undefined ? { cachedInputTokens: cached } : {}),\n ...(output !== undefined ? { outputTokens: output } : {}),\n }\n return Object.keys(usage).length > 0 ? usage : undefined\n}\n\nasync function drain(response: Response, signal: AbortSignal): Promise<void> {\n if (!response.body) return\n const reader = response.body.getReader()\n const stop = () => { void reader.cancel().catch(() => {}) }\n signal.addEventListener('abort', stop, { once: true })\n try {\n while (!(await reader.read()).done) { /* The turn is driven by reading its stream. */ }\n } finally {\n signal.removeEventListener('abort', stop)\n reader.releaseLock()\n }\n}\n\n/**\n * The operator adapter for an app built on agent-app's chat stack: threads and\n * messages from its chat store, turns through its own chat route. The app\n * supplies its workspace roles and, optionally, files, journal, approvals,\n * assets, and a scorecard.\n */\nexport function createChatOperatorAdapter<Identity>(options: ChatOperatorAdapterOptions<Identity>): OperatorAdapter<Identity> {\n const origin = options.origin.replace(/\\/$/, '')\n const threadUrl = (workspaceId: string, threadId: string) =>\n origin + (options.threadPath?.(workspaceId, threadId) ?? `/app/${workspaceId}/chat/${threadId}`)\n const workspaceView = (workspace: ChatOperatorWorkspace): OperatorWorkspace => ({\n id: workspace.id,\n name: workspace.name,\n ...(workspace.role ? { role: workspace.role } : {}),\n url: origin + (options.workspacePath?.(workspace.id) ?? `/app/${workspace.id}`),\n ...(iso(workspace.createdAt) ? { createdAt: iso(workspace.createdAt)! } : {}),\n })\n const threadView = (thread: ChatOperatorThread): OperatorThread => ({\n id: thread.id, title: thread.title, url: threadUrl(thread.workspaceId, thread.id),\n ...(iso(thread.updatedAt) ? { updatedAt: iso(thread.updatedAt)! } : {}),\n })\n\n async function threadIn(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string): Promise<ChatOperatorThread | null> {\n const thread = await options.threads.get(threadId, ctx)\n return thread && thread.workspaceId === workspaceId ? thread : null\n }\n\n async function turnOf(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string, turnId: string): Promise<OperatorTurn | null> {\n const messages = await options.threads.listMessages(threadId, ctx)\n const userIndex = messages.findIndex((message) => message.role === 'user' && messageHasTurnId(message, turnId))\n if (userIndex < 0) return null\n const later = messages.slice(userIndex + 1)\n const nextUser = later.findIndex((message) => message.role === 'user')\n const window = nextUser < 0 ? later : later.slice(0, nextUser)\n const assistant = [...window].reverse().find((message) => message.role === 'assistant') ?? null\n const latest = nextUser < 0\n const running = latest && options.runningTurns ? await options.runningTurns(ctx, workspaceId, threadId) : []\n const status = options.turnStatus ? await options.turnStatus(ctx, workspaceId, threadId, messages[userIndex]!) : undefined\n const terminal = status === undefined || status === 'complete' || status === 'error'\n const turn: OperatorTurn = {\n workspaceId, threadId, turnId, state: 'unknown', url: threadUrl(workspaceId, threadId),\n reply: null, failure: null, assets: [], files: [], approvals: [],\n }\n let state: OperatorTurnState = running === null ? 'unknown' : running.length > 0 ? 'working' : 'unknown'\n if (assistant) {\n turn.files = fileChanges(assistant)\n turn.assets = options.assets?.refs?.(assistant, workspaceId) ?? []\n const model = assistant.servedModel ?? assistant.model\n if (model) turn.model = model\n if (typeof assistant.costUsd === 'number') turn.costUsd = assistant.costUsd\n if (assistant.costSource != null) turn.costSource = assistant.costSource\n if (assistant.billingOwner != null) turn.billingOwner = assistant.billingOwner\n if (assistant.credentialSource != null) turn.credentialSource = assistant.credentialSource\n if (assistant.settlementRecord != null) turn.settlementRecord = assistant.settlementRecord\n const usage = operatorTurnUsage(assistant, { inputIncludesCache: options.inputIncludesCache ?? 'unknown' })\n if (usage) turn.usage = usage\n if (state !== 'working' && terminal) {\n const failure = (options.failureOf ?? defaultFailure)(assistant) ?? (status === 'error' ? { code: 'turn.error', message: 'The turn failed; retained text may be partial' } : null)\n if (failure) {\n state = 'failed'\n turn.failure = failure\n } else if (assistant.content.trim()) {\n state = 'succeeded'\n turn.reply = { content: assistant.content, mediaType: 'text/markdown' }\n }\n const completedAt = iso(assistant.createdAt)\n if (completedAt && (state === 'succeeded' || state === 'failed')) turn.completedAt = completedAt\n }\n } else if (state !== 'working' && terminal && (!latest || status === 'error' || status === 'complete')) {\n state = 'failed'\n turn.failure = { code: status === 'error' ? 'turn.error' : 'turn.no_reply', message: 'The turn ended without a reply' }\n }\n turn.state = state\n if (state !== 'succeeded' && state !== 'failed' && options.approvals) {\n turn.approvals = await options.approvals(ctx, workspaceId, threadId)\n }\n return turn\n }\n\n async function admittedTurn(ctx: OperatorContext<Identity>, workspaceId: string, turnId: string, admission: ChatOperatorAdmission): Promise<OperatorTurn> {\n if (!(await threadIn(ctx, workspaceId, admission.threadId))) throw new OperatorError('operator.turn_identity_conflict', 409)\n const persisted = await turnOf(ctx, workspaceId, admission.threadId, turnId)\n if (persisted) return persisted\n return {\n workspaceId, threadId: admission.threadId, turnId, state: admission.refusal ? 'failed' : 'unknown',\n url: threadUrl(workspaceId, admission.threadId), reply: null, failure: admission.refusal ?? null,\n assets: [], files: [], approvals: [],\n }\n }\n\n async function ensureThread(ctx: OperatorContext<Identity>, workspaceId: string, input: StartTurnInput): Promise<string> {\n const id = (await sha256Hex(`operator-thread\\0${ctx.key.keyId}\\0${workspaceId}\\0${input.turnId}`)).slice(0, 32)\n const existing = await options.threads.get(id, ctx)\n if (existing) {\n if (existing.workspaceId !== workspaceId) throw new OperatorError('operator.turn_identity_conflict', 409, 'This turn id belongs to another conversation')\n return id\n }\n const title = (input.title ?? input.content.split('\\n').find((line) => line.trim()) ?? 'New conversation').trim().slice(0, 80)\n try {\n await options.threads.create(ctx, { id, workspaceId, title })\n } catch (error) {\n // A concurrent retry may have inserted the same id first.\n if (!(await threadIn(ctx, workspaceId, id))) throw error\n }\n return id\n }\n\n const adapter: OperatorAdapter<Identity> = {\n ...(options.acceptsAttachments === true ? { acceptsAttachments: true } : {}),\n ...(options.maxAttachments === undefined ? {} : { maxAttachments: options.maxAttachments }),\n async authorizeWorkspace(ctx, workspaceId, access) {\n const workspace = await options.workspaces.authorize(ctx, workspaceId, access)\n return workspace ? workspaceView(workspace) : null\n },\n async listWorkspaces(ctx) {\n return (await options.workspaces.list(ctx)).map(workspaceView)\n },\n async startTurn(ctx, workspace, input) {\n const priorAdmission = await options.admissions?.get(ctx, workspace.id, input.turnId)\n if (priorAdmission) {\n if (input.threadId && input.threadId !== priorAdmission.threadId) throw new OperatorError('operator.turn_identity_conflict', 409)\n return admittedTurn(ctx, workspace.id, input.turnId, priorAdmission)\n }\n let threadId = input.threadId\n if (threadId === undefined) {\n threadId = await ensureThread(ctx, workspace.id, input)\n } else if (!(await threadIn(ctx, workspace.id, threadId))) {\n throw new OperatorError('operator.thread_not_found', 404, 'Thread not found')\n }\n // A retried start whose turn is already recorded reads it instead of running again.\n const existing = await turnOf(ctx, workspace.id, threadId, input.turnId)\n if (existing) return existing\n const target = { workspaceId: workspace.id, threadId, turnId: input.turnId }\n if (options.admissions && !(await options.admissions.claim(ctx, target))) {\n const raced = await options.admissions.get(ctx, workspace.id, input.turnId)\n if (!raced) throw new OperatorError('operator.admission_unavailable', 503, 'Admission state is unavailable', true)\n if (raced.threadId !== threadId) throw new OperatorError('operator.turn_identity_conflict', 409)\n return admittedTurn(ctx, workspace.id, input.turnId, raced)\n }\n const response = await options.runTurn(ctx, {\n workspaceId: workspace.id, threadId, turnId: input.turnId, content: input.content,\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.attachments === undefined ? {} : { attachments: input.attachments }),\n })\n if (!response.ok) {\n const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown }\n // Apps answer `{ error, code }` or `{ error: { code, message } }`.\n const nested = body.error && typeof body.error === 'object' ? body.error as { code?: unknown; message?: unknown } : {}\n const failure = {\n code: typeof body.code === 'string' ? body.code : typeof nested.code === 'string' ? nested.code : `operator.chat_${response.status}`,\n message: typeof body.error === 'string' ? body.error : typeof nested.message === 'string' ? nested.message : 'The app refused the turn',\n }\n if (options.admissions) {\n await options.admissions.recordRefusal(ctx, target, failure)\n return admittedTurn(ctx, workspace.id, input.turnId, { threadId, refusal: failure })\n }\n throw new OperatorError(failure.code, response.status, failure.message, response.status === 429 || response.status >= 500)\n }\n await drain(response, ctx.request.signal)\n return await turnOf(ctx, workspace.id, threadId, input.turnId) ?? {\n workspaceId: workspace.id, threadId, turnId: input.turnId, state: 'unknown', url: threadUrl(workspace.id, threadId),\n reply: null, failure: null, assets: [], files: [], approvals: [],\n }\n },\n async getTurn(ctx, workspace, target) {\n if (!(await threadIn(ctx, workspace.id, target.threadId))) return null\n const persisted = await turnOf(ctx, workspace.id, target.threadId, target.turnId)\n if (persisted) return persisted\n const admission = await options.admissions?.get(ctx, workspace.id, target.turnId)\n return admission?.threadId === target.threadId ? admittedTurn(ctx, workspace.id, target.turnId, admission) : null\n },\n async getThread(ctx, workspace, threadId) {\n const thread = await threadIn(ctx, workspace.id, threadId)\n if (!thread) return null\n const messages = await options.threads.listMessages(threadId, ctx)\n const lastUser = [...messages].reverse().find((message) => message.role === 'user')\n const turnId = lastUser ? turnIdOf(lastUser) : null\n return { thread: threadView(thread), latestTurn: turnId ? await turnOf(ctx, workspace.id, threadId, turnId) : null }\n },\n listApprovals: (ctx, workspace) => options.approvals ? options.approvals(ctx, workspace.id) : Promise.resolve([]),\n }\n if (options.workspaces.create) {\n const create = options.workspaces.create\n adapter.createWorkspace = async (ctx, input) => workspaceView(await create(ctx, input))\n }\n if (options.threads.list) {\n const list = options.threads.list\n adapter.listThreads = async (ctx, workspace, query) => {\n const page = await list(ctx, workspace.id, query)\n return { threads: page.threads.map(threadView), nextCursor: page.nextCursor }\n }\n }\n if (options.files) {\n const files = options.files\n adapter.listFiles = (ctx, workspace, query) => files.list(ctx, workspace.id, query.prefix)\n adapter.readFile = (ctx, workspace, path) => files.read(ctx, workspace.id, path)\n }\n if (options.journal) {\n const journal = options.journal\n adapter.listJournal = (ctx, workspace, query) => journal(ctx, workspace.id, query.days)\n }\n if (options.assets?.read) {\n const read = options.assets.read\n adapter.readAsset = (ctx, workspace, assetId) => read(ctx, workspace.id, assetId)\n }\n if (options.scorecard) {\n const scorecard = options.scorecard\n adapter.getScorecard = (ctx, workspace, query) => scorecard(ctx, workspace.id, query.days)\n }\n return adapter\n}\n","/**\n * Let the operator API accept a Platform agent key next to the app's own keys.\n *\n * `withPlatformAgentKeys` wraps the app's existing `OperatorKeyStore`: a\n * Bearer key starting `sk-tan-` is verified at Platform for this app's\n * product (see `platform/agent-keys.ts`); every other key goes to the app's\n * own store unchanged, so existing `gak_` keys keep working.\n *\n * Authority for a Platform agent key:\n * - Which actions: only the key's `<product>:operator:read|write|run` scopes\n * (or `*`), mapped to `operator:read|write|run`. A key without any is\n * refused, so a key approved for other products cannot reach this API.\n * - Which user: the key owner's Tangle identity (stable Platform user id and\n * verified email), resolved through the app's own `TangleSsoAccountStore`,\n * the same account policy browser SSO applies. A first call creates the app\n * user exactly as a first browser sign-in would, and links it when the store\n * keeps links per user; an ambiguous or conflicting identity is refused.\n * Nothing in the request names the user.\n * - Which credential: `loadIdentity` receives the agent key for the request,\n * so the app acts with it and the work spends the key's one cap. It is held\n * only for the request, never on the key object.\n * - Which workspaces: the app's ordinary roles, through the operator\n * adapter's `authorizeWorkspace`. The key confers no workspace access.\n */\nimport {\n agentOperatorScopes,\n PLATFORM_KEY_PREFIX,\n type PlatformAgentKeyVerifier,\n} from '../platform/agent-keys.js'\nimport type { RequestApiKey } from '../platform/api-key-auth.js'\nimport type { TangleSsoAccountStore } from '../platform/sso.js'\nimport type { OperatorKeyStore } from './server.js'\n\nconst OPERATOR_ACTIONS = ['read', 'write', 'run'] as const\n\nexport interface PlatformAgentKeyAccess<Identity> {\n verifier: PlatformAgentKeyVerifier\n /** This app's Platform product id, e.g. `gtm-agent`. */\n product: string\n /**\n * The app's browser-SSO account store. Give `saveTangleLink` only when the\n * store keeps the Platform link per user (a link table): a first call then\n * links the user with the agent key, as a first sign-in would. A store that\n * keeps the key on the session row has no session to bind here; omit it and\n * act with `context.platformApiKey` instead.\n */\n accounts: Pick<TangleSsoAccountStore, 'resolveAccount' | 'upsertUserByEmail'>\n & Partial<Pick<TangleSsoAccountStore, 'saveTangleLink'>>\n /**\n * Load the operator identity for an app user id. `context.platformApiKey` is\n * the agent key this request came with: put it on the identity and use it as\n * the request's Platform credential. Never store or log it.\n */\n loadIdentity(userId: string, context: PlatformAgentKeyContext): Promise<Identity | null>\n /** Optional per-key request quota; by default every verified request is admitted. */\n claimRequest?(keyId: string, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/** What `loadIdentity` receives for a request made with a Platform agent key. */\nexport interface PlatformAgentKeyContext {\n /** The agent key itself, for this request only. */\n platformApiKey: string\n}\n\n/** An operator key that came from Platform agent signup. */\nexport interface PlatformAgentOperatorKey extends RequestApiKey {\n source: 'platform-agent'\n}\n\nfunction refused(status: number, code: string, error: string): Response {\n return Response.json({ error, code }, { status, headers: { 'cache-control': 'private, no-store' } })\n}\n\nfunction isPlatformAgentKey(key: RequestApiKey): key is PlatformAgentOperatorKey {\n return (key as Partial<PlatformAgentOperatorKey>).source === 'platform-agent'\n}\n\nexport function withPlatformAgentKeys<Key extends RequestApiKey, Identity>(\n appKeys: OperatorKeyStore<Key, Identity>,\n access: PlatformAgentKeyAccess<Identity>,\n): OperatorKeyStore<Key | PlatformAgentOperatorKey, Identity> {\n // The raw key for each verified key object, for this request's identity.\n const rawKeys = new WeakMap<PlatformAgentOperatorKey, string>()\n\n async function provisionOwner(verified: { platformUserId: string; email: string; name: string | null }, rawKey: string): Promise<string> {\n const resolution = await access.accounts.resolveAccount({ email: verified.email, platformUserId: verified.platformUserId })\n if (resolution.kind === 'reject') {\n throw refused(403, 'agent_key.account_conflict', `The key owner's Tangle identity conflicts with an account in this app (${resolution.reason}).`)\n }\n // A user already linked to this Platform identity is used as it is: its\n // profile and link belong to the owner's own sign-ins.\n if (resolution.kind === 'existing' && resolution.matchedBy === 'platform-id') return resolution.userId\n // A new or email-matched user is created now, the way a first browser\n // sign-in would. A link-table store also links it, with the agent key as\n // the credential the app acts with later; spend then counts against the\n // key's one cap.\n const { userId } = await access.accounts.upsertUserByEmail({\n email: verified.email,\n name: verified.name,\n tangleUserId: verified.platformUserId,\n resolution,\n })\n await access.accounts.saveTangleLink?.({\n userId,\n sessionToken: '',\n tangleUserId: verified.platformUserId,\n email: verified.email,\n name: verified.name,\n apiKey: rawKey,\n planTier: null,\n })\n return userId\n }\n\n return {\n async verify(authorization) {\n const raw = /^Bearer +(\\S+)$/i.exec(authorization)?.[1]\n if (!raw?.startsWith(PLATFORM_KEY_PREFIX)) return appKeys.verify(authorization)\n const verified = await access.verifier.verify(raw)\n if (!verified.ok) throw refused(verified.status, verified.code, verified.message)\n const scopes = agentOperatorScopes(verified.scopes, access.product, OPERATOR_ACTIONS)\n if (scopes.length === 0) {\n throw refused(403, 'agent_key.product_not_granted', \"The key's owner did not approve it for this app.\")\n }\n const ownerId = await provisionOwner(verified, raw)\n const key: PlatformAgentOperatorKey = {\n keyId: verified.keyId,\n ownerId,\n scopes,\n // The operator API requires a finite expiry. This one bounds the\n // request being authorized; the next request asks Platform again once\n // the verifier's short cache lapses.\n expiresAt: Math.max(verified.validUntil, Date.now() + 30_000),\n source: 'platform-agent',\n }\n rawKeys.set(key, raw)\n return key\n },\n async resolveIdentity(key) {\n if (!isPlatformAgentKey(key)) return appKeys.resolveIdentity(key as Key)\n const platformApiKey = rawKeys.get(key)\n return platformApiKey ? access.loadIdentity(key.ownerId, { platformApiKey }) : null\n },\n async claimRequest(key, requestId) {\n if (!isPlatformAgentKey(key)) return appKeys.claimRequest(key as Key, requestId)\n return access.claimRequest ? access.claimRequest(key.keyId, requestId) : { allowed: true }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,MACA,QACT,SACS,YAAY,OACrB;AACA,UAAM,WAAW,IAAI;AALZ;AACA;AAEA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EAPW;AAAA,EACA;AAAA,EAEA;AAKb;AAEA,IAAM,UAAU;AAChB,IAAM,YAAY;AAClB,IAAM,iBAAiB,MAAM;AAC7B,IAAM,oBAAoB,KAAK;AAC/B,IAAM,eAAe,oBAAI,IAAI,CAAC,UAAU,WAAW,YAAY,SAAS,SAAS,aAAa,CAAC;AAE/F,IAAM,WAAW,EAAE,iBAAiB,oBAAoB;AAExD,SAAS,KAAK,MAAe,SAAS,KAAe;AACnD,SAAO,SAAS,KAAK,MAAM,EAAE,QAAQ,SAAS,SAAS,CAAC;AAC1D;AAEA,SAAS,QAAQ,QAAgB,MAAc,OAAe,YAAY,OAAiB;AACzF,SAAO,KAAK,EAAE,OAAO,MAAM,GAAI,YAAY,EAAE,UAAU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M,QAAQ,KAAK,iCAAiC,kDAAkD;AAAA,MACxG;AACA,YAAM,UAAU,MAAM,eAAe,UAAU,GAAG;AAClD,YAAM,MAAgC;AAAA,QACpC,OAAO,SAAS;AAAA,QAChB;AAAA,QACA;AAAA;AAAA;AAAA;AAAA,QAIA,WAAW,KAAK,IAAI,SAAS,YAAY,KAAK,IAAI,IAAI,GAAM;AAAA,QAC5D,QAAQ;AAAA,MACV;AACA,cAAQ,IAAI,KAAK,GAAG;AACpB,aAAO;AAAA,IACT;AAAA,IACA,MAAM,gBAAgB,KAAK;AACzB,UAAI,CAAC,mBAAmB,GAAG,EAAG,QAAO,QAAQ,gBAAgB,GAAU;AACvE,YAAM,iBAAiB,QAAQ,IAAI,GAAG;AACtC,aAAO,iBAAiB,OAAO,aAAa,IAAI,SAAS,EAAE,eAAe,CAAC,IAAI;AAAA,IACjF;AAAA,IACA,MAAM,aAAa,KAAK,WAAW;AACjC,UAAI,CAAC,mBAAmB,GAAG,EAAG,QAAO,QAAQ,aAAa,KAAY,SAAS;AAC/E,aAAO,OAAO,eAAe,OAAO,aAAa,IAAI,OAAO,SAAS,IAAI,EAAE,SAAS,KAAK;AAAA,IAC3F;AAAA,EACF;AACF;","names":["text","workspace"]}
1
+ {"version":3,"sources":["../../src/operator/server.ts","../../src/operator/chat-adapter.ts","../../src/operator/platform-agent-keys.ts","../../src/operator/gateway-keys.ts"],"sourcesContent":["import { parseChatAttachmentInputs } from '../chat-routes/attachment-validation.js'\nimport { createApiKeyRequestAuth, type RequestApiKey } from '../platform/api-key-auth.js'\nimport {\n OPERATOR_API_BASE_PATH,\n OPERATOR_API_VERSION,\n OPERATOR_SETTLED_STATES,\n matchOperatorRoute,\n operatorKeyWorkspaces,\n type OperatorApproval,\n type OperatorCapability,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorRouteId,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\n/** The verified caller of one operator request. */\nexport interface OperatorContext<Identity> {\n identity: Identity\n key: { keyId: string; scopes: readonly string[] }\n request: Request\n}\n\n/**\n * The app's side of the operator API: storage and execution only. Scope,\n * workspace restriction, input validation, and response shapes belong to the\n * shared handler, so every app answers the same way.\n */\nexport interface OperatorAdapter<Identity> {\n /**\n * Apply the app's workspace roles: `read` needs viewer access, `run` needs\n * the role that may start agent work. Null answers 404, so a key cannot\n * probe workspaces it cannot reach.\n */\n authorizeWorkspace(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<OperatorWorkspace | null>\n listWorkspaces(ctx: OperatorContext<Identity>): Promise<OperatorWorkspace[]>\n createWorkspace?(ctx: OperatorContext<Identity>, input: { name: string }): Promise<OperatorWorkspace>\n /**\n * True when `startTurn` delivers `input.attachments` to the agent, through\n * a chat route whose attachment resolver reads them from the workspace's\n * store. Otherwise the handler refuses turns that carry attachments rather\n * than letting them be dropped.\n */\n acceptsAttachments?: boolean\n /**\n * Most attachments one turn may carry. Default `ATTACHMENT_MAX_COUNT`, the\n * chat route's own default; an app whose chat route admits more per message\n * sets the same number here.\n */\n maxAttachments?: number\n /** Admit the turn durably and return without waiting for it; the same turnId never starts twice. */\n startTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, input: StartTurnInput): Promise<OperatorTurn>\n getTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, target: { threadId: string; turnId: string }): Promise<OperatorTurn | null>\n /**\n * Stop an unsettled turn through the app's own interrupt path and return the\n * turn as read afterwards. It may still read `working` until the app's turn\n * owner records the stop; once recorded, the turn settles `failed` with\n * `OPERATOR_TURN_CANCELLED_CODE`. Null when the turn is not in this\n * workspace. Throw a retryable `OperatorError` when the stop could not be\n * delivered. The handler never calls it for a settled turn.\n */\n cancelTurn?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, target: { threadId: string; turnId: string }): Promise<OperatorTurn | null>\n listThreads?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { cursor?: string; limit: number }): Promise<{ threads: OperatorThread[]; nextCursor: string | null }>\n getThread?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, threadId: string): Promise<{ thread: OperatorThread; latestTurn: OperatorTurn | null } | null>\n listApprovals(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace): Promise<OperatorApproval[]>\n listJournal?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { days: number }): Promise<OperatorJournalEntry[]>\n listFiles?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { prefix: string }): Promise<OperatorFileEntry[]>\n readFile?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, path: string): Promise<OperatorFile | null>\n /** The stored bytes, or null when the asset is not in this workspace. */\n readAsset?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, assetId: string): Promise<Response | null>\n getScorecard?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: { days: number }): Promise<OperatorScorecard>\n}\n\nexport interface OperatorKeyStore<Key extends RequestApiKey, Identity> {\n /** Verify against the app's existing key store, including revocation. */\n verify(authorization: string): Promise<Key | null>\n /** Load the key owner; throw a Response to refuse a key class, such as spending-capped keys. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically count the request against the key's limits. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\nexport interface OperatorApiOptions<Key extends RequestApiKey, Identity> {\n app: { id: string; name: string }\n keys: OperatorKeyStore<Key, Identity>\n adapter: OperatorAdapter<Identity>\n basePath?: string\n /** Longest hold for a turn read with `?wait=`, in seconds. */\n maxWaitSeconds?: number\n /** Interval between state reads during a held turn read. */\n pollIntervalMs?: number\n /** Unexpected adapter failures; responses never carry their detail. */\n onError?(error: unknown, route: OperatorRouteId): void\n}\n\nexport interface OperatorApi {\n /** True when the request addresses this API's base path. */\n matches(request: Request): boolean\n handle(request: Request): Promise<Response>\n}\n\n/** A refusal with a stable code; adapters throw it for expected failures. */\nexport class OperatorError extends Error {\n constructor(\n readonly code: string,\n readonly status: number,\n message?: string,\n readonly retryable = false,\n ) {\n super(message ?? code)\n this.name = 'OperatorError'\n }\n}\n\nconst TURN_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\nconst THREAD_ID = /^[A-Za-z0-9_-]{1,256}$/\nconst MAX_BODY_BYTES = 128 * 1024\nconst MAX_CONTENT_BYTES = 64 * 1024\nconst START_FIELDS = new Set(['turnId', 'content', 'threadId', 'title', 'model', 'attachments'])\n\nconst NO_STORE = { 'cache-control': 'private, no-store' }\n\nfunction json(body: unknown, status = 200): Response {\n return Response.json(body, { status, headers: NO_STORE })\n}\n\nfunction refusal(status: number, code: string, error: string, retryable = false): Response {\n return json({ error, code, ...(retryable ? { retryable } : {}) }, status)\n}\n\nfunction boundedInteger(value: string | null, fallback: number, min: number, max: number, name: string): number {\n if (value === null || value === '') return fallback\n if (!/^\\d{1,6}$/.test(value)) throw new OperatorError('operator.invalid_input', 400, `${name} must be a whole number`)\n const parsed = Number(value)\n if (parsed < min || parsed > max) throw new OperatorError('operator.invalid_input', 400, `${name} must be between ${min} and ${max}`)\n return parsed\n}\n\n/** Workspace-relative paths only: no absolute, parent, empty, or backslash segments. */\nfunction relativePath(value: string | null, name: string, { allowEmpty }: { allowEmpty: boolean }): string {\n const path = value ?? ''\n if (path === '' && allowEmpty) return ''\n if (!path || path.length > 1024 || path.startsWith('/') || path.includes('\\\\') || /[\\u0000-\\u001f\\u007f]/.test(path)) {\n throw new OperatorError('operator.invalid_path', 400, `${name} must be a workspace-relative path`)\n }\n const segments = path.replace(/\\/$/, '').split('/')\n if (segments.some((segment) => !segment || segment === '.' || segment === '..')) {\n throw new OperatorError('operator.invalid_path', 400, `${name} must be a workspace-relative path`)\n }\n return path\n}\n\nasync function readJsonBody(request: Request): Promise<Record<string, unknown>> {\n const declared = Number(request.headers.get('content-length') ?? '0')\n if (declared > MAX_BODY_BYTES) throw new OperatorError('operator.body_too_large', 413, 'Request body is too large')\n const text = await request.text()\n if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES) {\n throw new OperatorError('operator.body_too_large', 413, 'Request body is too large')\n }\n let parsed: unknown\n try { parsed = JSON.parse(text) } catch { throw new OperatorError('operator.invalid_json', 400, 'Body must be a JSON object') }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new OperatorError('operator.invalid_json', 400, 'Body must be a JSON object')\n }\n return parsed as Record<string, unknown>\n}\n\nfunction optionalString(body: Record<string, unknown>, name: string, max: number): string | undefined {\n const value = body[name]\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string' || !value.trim() || value.length > max) {\n throw new OperatorError('operator.invalid_input', 400, `${name} must be a nonempty string of at most ${max} characters`)\n }\n return value.trim()\n}\n\n/** Identity and destination come from the key and the path; the body can only describe the work. */\nfunction parseStartTurn(body: Record<string, unknown>, maxAttachments: number | undefined): StartTurnInput {\n const unknown = Object.keys(body).filter((field) => !START_FIELDS.has(field))\n if (unknown.length) throw new OperatorError('operator.invalid_input', 400, `Unknown fields: ${unknown.join(', ')}`)\n if (typeof body.turnId !== 'string' || !TURN_ID.test(body.turnId)) {\n throw new OperatorError('operator.invalid_input', 400, 'turnId must be a client-generated UUID')\n }\n if (typeof body.content !== 'string' || !body.content.trim()) {\n throw new OperatorError('operator.invalid_input', 400, 'content must be a nonempty string')\n }\n if (new TextEncoder().encode(body.content).byteLength > MAX_CONTENT_BYTES) {\n throw new OperatorError('operator.invalid_input', 400, `content must be at most ${MAX_CONTENT_BYTES} bytes`)\n }\n const threadId = optionalString(body, 'threadId', 256)\n if (threadId !== undefined && !THREAD_ID.test(threadId)) {\n throw new OperatorError('operator.invalid_input', 400, 'threadId contains only letters, digits, - and _')\n }\n const title = optionalString(body, 'title', 200)\n const model = optionalString(body, 'model', 200)\n // The chat route's own structural rules; the app's store read re-checks\n // every path against this workspace and re-derives every size.\n const attachments = parseChatAttachmentInputs(body.attachments, maxAttachments === undefined ? {} : { maxCount: maxAttachments })\n if (!attachments.succeeded) throw new OperatorError('operator.invalid_input', 400, attachments.error)\n return {\n turnId: body.turnId.toLowerCase(),\n content: body.content,\n ...(threadId === undefined ? {} : { threadId }),\n ...(title === undefined ? {} : { title }),\n ...(model === undefined ? {} : { model }),\n ...(attachments.value.length === 0 ? {} : { attachments: attachments.value }),\n }\n}\n\nfunction capabilities<Identity>(adapter: OperatorAdapter<Identity>): OperatorCapability[] {\n const present: Array<[OperatorCapability, unknown]> = [\n ['turns.cancel', adapter.cancelTurn],\n ['workspaces.create', adapter.createWorkspace],\n ['threads.read', adapter.getThread ?? adapter.listThreads],\n ['files.read', adapter.readFile ?? adapter.listFiles],\n ['journal.read', adapter.listJournal],\n ['assets.read', adapter.readAsset],\n ['scorecard.read', adapter.getScorecard],\n ]\n const implemented = present.filter(([, method]) => typeof method === 'function').map(([name]) => name)\n return adapter.acceptsAttachments === true ? ['turns.attachments', ...implemented] : implemented\n}\n\nfunction unsupported(): never {\n throw new OperatorError('operator.unsupported', 501, 'This app does not implement this operation')\n}\n\nfunction settled(turn: OperatorTurn): boolean {\n return OPERATOR_SETTLED_STATES.includes(turn.state)\n}\n\n/** A held turn read returns as soon as the turn settles or waits on a decision. */\nfunction needsAttention(turn: OperatorTurn): boolean {\n return settled(turn) || turn.state === 'input-required' || turn.approvals.length > 0\n}\n\nconst sleep = (ms: number, signal: AbortSignal) => new Promise<void>((resolve) => {\n if (signal.aborted) return resolve()\n const timer = setTimeout(resolve, ms)\n signal.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true })\n})\n\n/**\n * Mount the standard operator API. Requests must carry a Bearer key: there is\n * no browser-cookie fallback, so a page session never reaches these routes.\n */\nexport function createOperatorApi<Key extends RequestApiKey, Identity>(\n options: OperatorApiOptions<Key, Identity>,\n): OperatorApi {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const maxWaitSeconds = Math.max(0, Math.min(options.maxWaitSeconds ?? 25, 55))\n const pollIntervalMs = Math.max(250, options.pollIntervalMs ?? 2_000)\n const { adapter } = options\n\n function matches(request: Request): boolean {\n const { pathname } = new URL(request.url)\n return pathname === basePath || pathname.startsWith(`${basePath}/`)\n }\n\n async function handle(request: Request): Promise<Response> {\n const url = new URL(request.url)\n const match = matchOperatorRoute(request.method, url.pathname, basePath)\n if (!match) return refusal(404, 'operator.route_not_found', 'No operator route matches this method and path')\n const { route, params } = match\n if (request.headers.get('Authorization') === null) {\n return refusal(401, 'operator.unauthenticated', 'An operator API key is required')\n }\n\n let verified: { identity: Identity; key: Key }\n try {\n const authenticate = createApiKeyRequestAuth<Key, { identity: Identity; key: Key }>({\n verify: (authorization) => options.keys.verify(authorization),\n requiredScope: () => route.scopes,\n resolveIdentity: async (key) => {\n const identity = await options.keys.resolveIdentity(key)\n return identity === null || identity === undefined ? null : { identity, key }\n },\n claimRequest: (key, requestId) => options.keys.claimRequest(key, requestId),\n })\n const result = await authenticate(request)\n if (!result) return refusal(401, 'operator.unauthenticated', 'An operator API key is required')\n verified = result\n } catch (error) {\n if (error instanceof Response) return error\n options.onError?.(error, route.id)\n return refusal(503, 'operator.auth_unavailable', 'Key verification is unavailable', true)\n }\n\n const ctx: OperatorContext<Identity> = {\n identity: verified.identity,\n key: { keyId: verified.key.keyId, scopes: [...verified.key.scopes] },\n request,\n }\n const restriction = operatorKeyWorkspaces(verified.key.scopes)\n\n try {\n if (route.id === 'describe') {\n return json({\n app: {\n app: options.app.id, name: options.app.name, apiVersion: OPERATOR_API_VERSION,\n capabilities: capabilities(adapter),\n },\n principal: { keyId: ctx.key.keyId, scopes: [...ctx.key.scopes], workspaces: restriction ? [...restriction] : null },\n })\n }\n if (route.id === 'workspaces.list') {\n const listed = await adapter.listWorkspaces(ctx)\n return json({ workspaces: restriction ? listed.filter((workspace) => restriction.includes(workspace.id)) : listed })\n }\n if (route.id === 'workspaces.create') {\n if (restriction) {\n throw new OperatorError('operator.workspace_restricted', 403, 'A workspace-restricted key cannot create workspaces')\n }\n if (!adapter.createWorkspace) unsupported()\n const body = await readJsonBody(request)\n const unknown = Object.keys(body).filter((field) => field !== 'name')\n if (unknown.length) throw new OperatorError('operator.invalid_input', 400, `Unknown fields: ${unknown.join(', ')}`)\n const name = optionalString(body, 'name', 120)\n if (!name) throw new OperatorError('operator.invalid_input', 400, 'name is required')\n return json({ workspace: await adapter.createWorkspace(ctx, { name }) }, 201)\n }\n\n const workspaceId = params.workspaceId!\n if (restriction && !restriction.includes(workspaceId)) {\n throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n }\n const runs = route.id === 'turns.start' || route.id === 'turns.cancel'\n const workspace = await adapter.authorizeWorkspace(ctx, workspaceId, runs ? 'run' : 'read')\n if (!workspace) throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n\n /** Re-read the turn every poll interval until `done`, `wait` seconds pass, or the caller leaves. */\n const hold = async (first: OperatorTurn | null, target: { threadId: string; turnId: string }, wait: number, done: (turn: OperatorTurn) => boolean) => {\n const deadline = Date.now() + wait * 1000\n let turn = first\n while (turn && !done(turn) && Date.now() + pollIntervalMs <= deadline && !request.signal.aborted) {\n await sleep(pollIntervalMs, request.signal)\n turn = await adapter.getTurn(ctx, workspace, target)\n }\n if (!turn) throw new OperatorError('operator.turn_not_found', 404, 'Turn not found')\n return turn\n }\n\n switch (route.id) {\n case 'workspaces.get':\n return json({ workspace })\n case 'turns.start': {\n const input = parseStartTurn(await readJsonBody(request), adapter.maxAttachments)\n if (input.attachments && adapter.acceptsAttachments !== true) {\n throw new OperatorError('operator.unsupported', 501, 'This app does not accept attachments on operator turns')\n }\n return json({ turn: await adapter.startTurn(ctx, workspace, input) }, 202)\n }\n case 'threads.list': {\n if (!adapter.listThreads) unsupported()\n const limit = boundedInteger(url.searchParams.get('limit'), 25, 1, 100, 'limit')\n const cursor = url.searchParams.get('cursor') ?? undefined\n if (cursor !== undefined && (cursor.length > 512 || !cursor)) {\n throw new OperatorError('operator.invalid_input', 400, 'cursor is invalid')\n }\n return json(await adapter.listThreads(ctx, workspace, { limit, ...(cursor ? { cursor } : {}) }))\n }\n case 'threads.get': {\n if (!adapter.getThread) unsupported()\n const found = await adapter.getThread(ctx, workspace, params.threadId!)\n if (!found) throw new OperatorError('operator.thread_not_found', 404, 'Thread not found')\n return json(found)\n }\n case 'turns.get': {\n const target = { threadId: params.threadId!, turnId: params.turnId! }\n const wait = boundedInteger(url.searchParams.get('wait'), 0, 0, maxWaitSeconds, 'wait')\n return json({ turn: await hold(await adapter.getTurn(ctx, workspace, target), target, wait, needsAttention) })\n }\n case 'turns.cancel': {\n if (!adapter.cancelTurn) unsupported()\n const target = { threadId: params.threadId!, turnId: params.turnId! }\n const wait = boundedInteger(url.searchParams.get('wait'), 0, 0, maxWaitSeconds, 'wait')\n const current = await adapter.getTurn(ctx, workspace, target)\n if (!current) throw new OperatorError('operator.turn_not_found', 404, 'Turn not found')\n // Cancelling a settled turn reads it: a repeat or late cancel never fails and never reaches the app.\n if (settled(current)) return json({ turn: current })\n const turn = await hold(await adapter.cancelTurn(ctx, workspace, target), target, wait, settled)\n return json({ turn }, settled(turn) ? 200 : 202)\n }\n case 'approvals.list':\n return json({ approvals: await adapter.listApprovals(ctx, workspace) })\n case 'journal.list': {\n if (!adapter.listJournal) unsupported()\n const days = boundedInteger(url.searchParams.get('days'), 7, 1, 90, 'days')\n return json({ entries: await adapter.listJournal(ctx, workspace, { days }) })\n }\n case 'files.list': {\n if (!adapter.listFiles) unsupported()\n const prefix = relativePath(url.searchParams.get('prefix'), 'prefix', { allowEmpty: true })\n return json({ files: await adapter.listFiles(ctx, workspace, { prefix }) })\n }\n case 'files.read': {\n if (!adapter.readFile) unsupported()\n const path = relativePath(url.searchParams.get('path'), 'path', { allowEmpty: false })\n const file = await adapter.readFile(ctx, workspace, path)\n if (!file) throw new OperatorError('operator.file_not_found', 404, 'File not found')\n return json({ file })\n }\n case 'assets.read': {\n if (!adapter.readAsset) unsupported()\n const response = await adapter.readAsset(ctx, workspace, params.assetId!)\n if (!response) throw new OperatorError('operator.asset_not_found', 404, 'Asset not found')\n const headers = new Headers(response.headers)\n headers.set('cache-control', 'private, no-store')\n headers.delete('set-cookie')\n return new Response(response.body, { status: response.status, headers })\n }\n case 'scorecard.get': {\n if (!adapter.getScorecard) unsupported()\n const days = boundedInteger(url.searchParams.get('days'), 7, 1, 90, 'days')\n return json({ scorecard: await adapter.getScorecard(ctx, workspace, { days }) })\n }\n }\n return refusal(404, 'operator.route_not_found', 'No operator route matches this method and path')\n } catch (error) {\n if (error instanceof OperatorError) return refusal(error.status, error.code, error.message, error.retryable)\n if (error instanceof Response) return error\n options.onError?.(error, route.id)\n return refusal(500, 'operator.internal', 'The operation failed', true)\n }\n }\n\n return { matches, handle }\n}\n","import type { ChatAttachmentInput } from '../chat-routes/wire.js'\nimport { messageHasTurnId } from '../stream/turn-identity.js'\nimport type {\n OperatorApproval,\n OperatorAssetRef,\n OperatorFile,\n OperatorFileChange,\n OperatorFileEntry,\n OperatorJournalEntry,\n OperatorRole,\n OperatorScorecard,\n OperatorThread,\n OperatorTurn,\n OperatorTurnState,\n OperatorWorkspace,\n StartTurnInput,\n} from './contract.js'\nimport { OperatorError, type OperatorAdapter, type OperatorContext } from './server.js'\nimport { sha256Hex } from '../crypto/digest'\n\n/** The message fields the adapter reads; agent-app's chat-store rows satisfy it. */\nexport interface ChatOperatorMessage {\n id: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n /** Typed chat parts, such as chat-store's, are read field by field. */\n parts: ReadonlyArray<object> | null\n createdAt?: Date | string | number | null\n model?: string | null\n servedModel?: string | null\n costUsd?: number | null\n /** Explicit producer facts, supplied by the app's stored-row projection; metadata is not interpreted. */\n costSource?: OperatorTurn['costSource'] | null\n billingOwner?: OperatorTurn['billingOwner'] | null\n credentialSource?: OperatorTurn['credentialSource'] | null\n settlementRecord?: string | null\n /** Usage columns as chat-store stores them; see `operatorTurnUsage` for what `inputTokens` holds. */\n inputTokens?: number | null\n cacheReadTokens?: number | null\n outputTokens?: number | null\n /** The row's product metadata, for a `failureOf` that reads a stamped turn status. */\n metadata?: Record<string, unknown> | null\n}\n\nexport interface ChatOperatorThread {\n id: string\n workspaceId: string\n title: string\n updatedAt?: Date | string | number | null\n}\n\nexport interface ChatOperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n createdAt?: Date | string | number | null\n}\n\n/** A durable execution claim, separate from the chat transcript that owns results. */\nexport interface ChatOperatorAdmission {\n threadId: string\n /** Only an explicit refusal before a usable stream opened is recorded here. */\n refusal?: { code?: string; message: string }\n}\n\n/** Product-owned atomic storage for duplicate suppression across processes.\n * A claim with no transcript stays unknown after a crash; it never licenses a\n * second execution. This is not a completion ledger or an automatic retry queue.\n */\nexport interface ChatOperatorAdmissionStore<Identity> {\n get(ctx: OperatorContext<Identity>, workspaceId: string, turnId: string): Promise<ChatOperatorAdmission | null>\n claim(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string }): Promise<boolean>\n recordRefusal(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string }, refusal: { code?: string; message: string }): Promise<void>\n}\n\nexport interface ChatOperatorAdapterOptions<Identity> {\n /** Optional durable claims; without one, transcript retry detection is not an atomic admission lock. */\n admissions?: ChatOperatorAdmissionStore<Identity>\n /**\n * Set when `runTurn` forwards `attachments` in the chat request body and the\n * chat route resolves them from the workspace's store, as with\n * `resolveChatAttachments`. Without it, turns that carry attachments are refused.\n */\n acceptsAttachments?: boolean\n /** Most attachments one turn may carry; set it to the chat route's own count cap. Default `ATTACHMENT_MAX_COUNT`. */\n maxAttachments?: number\n /** The app's public origin, the base of every browser link. */\n origin: string\n /** Browser path of a conversation; defaults to `/app/<workspace>/chat/<thread>`. */\n threadPath?(workspaceId: string, threadId: string): string\n /** Browser path of a workspace; defaults to `/app/<workspace>`. */\n workspacePath?(workspaceId: string): string\n workspaces: {\n /** Apply the app's roles: `read` needs viewer access, `run` the role that may start agent work. */\n authorize(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<ChatOperatorWorkspace | null>\n list(ctx: OperatorContext<Identity>): Promise<ChatOperatorWorkspace[]>\n create?(ctx: OperatorContext<Identity>, input: { name: string }): Promise<ChatOperatorWorkspace>\n }\n threads: {\n /**\n * A thread this caller may read, or null. An app whose conversations\n * belong to one user (not the whole workspace) applies that here.\n */\n get(threadId: string, ctx: OperatorContext<Identity>): Promise<ChatOperatorThread | null>\n /** Insert a thread with this id for this caller; agent-app's chat store accepts a caller-assigned id. */\n create(ctx: OperatorContext<Identity>, input: { id: string; workspaceId: string; title: string }): Promise<ChatOperatorThread>\n /** Oldest first. */\n listMessages(threadId: string, ctx: OperatorContext<Identity>): Promise<ChatOperatorMessage[]>\n list?(ctx: OperatorContext<Identity>, workspaceId: string, query: { cursor?: string; limit: number }): Promise<{ threads: ChatOperatorThread[]; nextCursor: string | null }>\n }\n /**\n * Run one turn through the app's own chat route as this caller. The adapter\n * reads the response to its end, so the turn is driven exactly as a browser\n * holding its stream drives it, and the start request returns once it settles.\n * `attachments` arrives only when `acceptsAttachments` is set.\n */\n runTurn(ctx: OperatorContext<Identity>, input: {\n workspaceId: string; threadId: string; turnId: string; content: string; model?: string\n attachments?: ChatAttachmentInput[]\n }): Promise<Response>\n /** Optional authoritative status of this user-turn anchor. When supplied,\n * missing/running status without a live lease never promotes a partial reply to success. */\n turnStatus?(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string, user: ChatOperatorMessage): Promise<'running' | 'complete' | 'error' | null>\n /** Turn ids still running on a thread, or null when the app cannot tell. */\n runningTurns?(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string): Promise<string[] | null>\n /** Decisions open in the workspace, or on one conversation when `threadId` is set. */\n approvals?(ctx: OperatorContext<Identity>, workspaceId: string, threadId?: string): Promise<OperatorApproval[]>\n files?: {\n list(ctx: OperatorContext<Identity>, workspaceId: string, prefix: string): Promise<OperatorFileEntry[]>\n read(ctx: OperatorContext<Identity>, workspaceId: string, path: string): Promise<OperatorFile | null>\n }\n journal?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorJournalEntry[]>\n assets?: {\n /** Assets a reply references; defaults to none. */\n refs?(message: ChatOperatorMessage, workspaceId: string): OperatorAssetRef[]\n read?(ctx: OperatorContext<Identity>, workspaceId: string, assetId: string): Promise<Response | null>\n }\n scorecard?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorScorecard>\n /**\n * A reply's failure. Defaults to an `error` notice (the sandbox producer's\n * `errorNotice` mode), a `turn-failure` notice or an `error` part.\n */\n failureOf?(message: ChatOperatorMessage): { code?: string; message: string } | null\n /**\n * Whether stored rows' `inputTokens` include cache reads, for\n * `operatorTurnUsage`. A row does not say which writer or version stored\n * it, so pass a boolean only when every writer of the app's rows is known\n * to follow it. Default `'unknown'` reports `inputTokens` only on rows that\n * record zero cache reads.\n */\n inputIncludesCache?: boolean | 'unknown'\n}\n\nconst iso = (value: Date | string | number | null | undefined): string | undefined => {\n if (value === null || value === undefined) return undefined\n const date = value instanceof Date ? value : new Date(typeof value === 'number' && value < 1e12 ? value * 1000 : value)\n return Number.isNaN(date.getTime()) ? undefined : date.toISOString()\n}\n\nconst text = (value: unknown): string | null => (typeof value === 'string' && value.trim() ? value : null)\n\nfunction partsOf(message: ChatOperatorMessage): ReadonlyArray<Record<string, unknown>> {\n return (message.parts ?? []) as ReadonlyArray<Record<string, unknown>>\n}\n\nfunction defaultFailure(message: ChatOperatorMessage): { code?: string; message: string } | null {\n for (const part of partsOf(message)) {\n const errorNotice = part.type === 'notice' && part.noticeKind === 'error'\n const notice = errorNotice || (part.type === 'notice' && (part.noticeKind === 'turn-failure' || part.kind === 'turn-failure'))\n if (!notice && part.type !== 'error') continue\n const detail = text(part.message) ?? text(part.text) ?? text(part.error) ?? 'The turn failed'\n // An error notice always names a reason, so a caller can tell failures apart.\n const code = typeof part.code === 'string' ? part.code : errorNotice ? 'turn.error' : undefined\n return { ...(code ? { code } : {}), message: detail }\n }\n return null\n}\n\nfunction fileChanges(message: ChatOperatorMessage): OperatorFileChange[] {\n const files: OperatorFileChange[] = []\n for (const part of partsOf(message)) {\n if (part.type !== 'session-artifact' || typeof part.path !== 'string') continue\n const action = part.action === 'created' || part.action === 'updated' || part.action === 'deleted' ? part.action : 'changed'\n if (!files.some((file) => file.path === part.path)) files.push({ path: part.path, action })\n }\n return files\n}\n\nfunction turnIdOf(message: ChatOperatorMessage): string | null {\n for (const part of partsOf(message)) {\n if (typeof part.turnId === 'string' && part.turnId) return part.turnId\n }\n return null\n}\n\n/**\n * The operator turn usage of a stored assistant row, for `OperatorTurn.usage`.\n * `cachedInputTokens` is the row's `cacheReadTokens` and `outputTokens` its\n * `outputTokens`, each when the row has it. `inputTokens` is reported only as\n * the prompt NOT read from cache, and a row does not record whether its\n * `inputTokens` already excludes cache reads: the Router lane subtracts them\n * before storing since 0.60.248 and included them before, and the sandbox\n * lanes store the split their upstream reports. A missing `cacheReadTokens`\n * is unknown, not 0. So:\n * - `'unknown'` (the default) reports the row's `inputTokens` only when\n * `cacheReadTokens` is a recorded 0, and omits it otherwise;\n * - `inputIncludesCache: false` reports the row's `inputTokens`, with or\n * without a recorded `cacheReadTokens`;\n * - `inputIncludesCache: true` reports `inputTokens - cacheReadTokens` when\n * `cacheReadTokens` is recorded and the difference is not negative, and\n * omits it otherwise.\n * `cachedInputTokens` and `outputTokens` are reported whenever the row\n * records them, independent of `inputTokens`.\n * A count that is not a finite number is omitted, never zeroed; a row with no\n * count gives `undefined`. An app that builds its own operator turns from such\n * rows calls this rather than mapping them itself.\n */\nexport function operatorTurnUsage(\n row: Pick<ChatOperatorMessage, 'inputTokens' | 'cacheReadTokens' | 'outputTokens'>,\n options: { inputIncludesCache?: boolean | 'unknown' } = {},\n): OperatorTurn['usage'] {\n const count = (value: number | null | undefined) => (typeof value === 'number' && Number.isFinite(value) ? value : undefined)\n const input = count(row.inputTokens)\n const cached = count(row.cacheReadTokens)\n const output = count(row.outputTokens)\n const includes = options.inputIncludesCache ?? 'unknown'\n const uncached = input === undefined ? undefined\n : includes === false ? input\n : includes === true ? (cached !== undefined && input - cached >= 0 ? input - cached : undefined)\n : cached === 0 ? input\n : undefined\n const usage: NonNullable<OperatorTurn['usage']> = {\n ...(uncached !== undefined ? { inputTokens: uncached } : {}),\n ...(cached !== undefined ? { cachedInputTokens: cached } : {}),\n ...(output !== undefined ? { outputTokens: output } : {}),\n }\n return Object.keys(usage).length > 0 ? usage : undefined\n}\n\nasync function drain(response: Response, signal: AbortSignal): Promise<void> {\n if (!response.body) return\n const reader = response.body.getReader()\n const stop = () => { void reader.cancel().catch(() => {}) }\n signal.addEventListener('abort', stop, { once: true })\n try {\n while (!(await reader.read()).done) { /* The turn is driven by reading its stream. */ }\n } finally {\n signal.removeEventListener('abort', stop)\n reader.releaseLock()\n }\n}\n\n/**\n * The operator adapter for an app built on agent-app's chat stack: threads and\n * messages from its chat store, turns through its own chat route. The app\n * supplies its workspace roles and, optionally, files, journal, approvals,\n * assets, and a scorecard.\n */\nexport function createChatOperatorAdapter<Identity>(options: ChatOperatorAdapterOptions<Identity>): OperatorAdapter<Identity> {\n const origin = options.origin.replace(/\\/$/, '')\n const threadUrl = (workspaceId: string, threadId: string) =>\n origin + (options.threadPath?.(workspaceId, threadId) ?? `/app/${workspaceId}/chat/${threadId}`)\n const workspaceView = (workspace: ChatOperatorWorkspace): OperatorWorkspace => ({\n id: workspace.id,\n name: workspace.name,\n ...(workspace.role ? { role: workspace.role } : {}),\n url: origin + (options.workspacePath?.(workspace.id) ?? `/app/${workspace.id}`),\n ...(iso(workspace.createdAt) ? { createdAt: iso(workspace.createdAt)! } : {}),\n })\n const threadView = (thread: ChatOperatorThread): OperatorThread => ({\n id: thread.id, title: thread.title, url: threadUrl(thread.workspaceId, thread.id),\n ...(iso(thread.updatedAt) ? { updatedAt: iso(thread.updatedAt)! } : {}),\n })\n\n async function threadIn(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string): Promise<ChatOperatorThread | null> {\n const thread = await options.threads.get(threadId, ctx)\n return thread && thread.workspaceId === workspaceId ? thread : null\n }\n\n async function turnOf(ctx: OperatorContext<Identity>, workspaceId: string, threadId: string, turnId: string): Promise<OperatorTurn | null> {\n const messages = await options.threads.listMessages(threadId, ctx)\n const userIndex = messages.findIndex((message) => message.role === 'user' && messageHasTurnId(message, turnId))\n if (userIndex < 0) return null\n const later = messages.slice(userIndex + 1)\n const nextUser = later.findIndex((message) => message.role === 'user')\n const window = nextUser < 0 ? later : later.slice(0, nextUser)\n const assistant = [...window].reverse().find((message) => message.role === 'assistant') ?? null\n const latest = nextUser < 0\n const running = latest && options.runningTurns ? await options.runningTurns(ctx, workspaceId, threadId) : []\n const status = options.turnStatus ? await options.turnStatus(ctx, workspaceId, threadId, messages[userIndex]!) : undefined\n const terminal = status === undefined || status === 'complete' || status === 'error'\n const turn: OperatorTurn = {\n workspaceId, threadId, turnId, state: 'unknown', url: threadUrl(workspaceId, threadId),\n reply: null, failure: null, assets: [], files: [], approvals: [],\n }\n let state: OperatorTurnState = running === null ? 'unknown' : running.length > 0 ? 'working' : 'unknown'\n if (assistant) {\n turn.files = fileChanges(assistant)\n turn.assets = options.assets?.refs?.(assistant, workspaceId) ?? []\n const model = assistant.servedModel ?? assistant.model\n if (model) turn.model = model\n if (typeof assistant.costUsd === 'number') turn.costUsd = assistant.costUsd\n if (assistant.costSource != null) turn.costSource = assistant.costSource\n if (assistant.billingOwner != null) turn.billingOwner = assistant.billingOwner\n if (assistant.credentialSource != null) turn.credentialSource = assistant.credentialSource\n if (assistant.settlementRecord != null) turn.settlementRecord = assistant.settlementRecord\n const usage = operatorTurnUsage(assistant, { inputIncludesCache: options.inputIncludesCache ?? 'unknown' })\n if (usage) turn.usage = usage\n if (state !== 'working' && terminal) {\n const failure = (options.failureOf ?? defaultFailure)(assistant) ?? (status === 'error' ? { code: 'turn.error', message: 'The turn failed; retained text may be partial' } : null)\n if (failure) {\n state = 'failed'\n turn.failure = failure\n } else if (assistant.content.trim()) {\n state = 'succeeded'\n turn.reply = { content: assistant.content, mediaType: 'text/markdown' }\n }\n const completedAt = iso(assistant.createdAt)\n if (completedAt && (state === 'succeeded' || state === 'failed')) turn.completedAt = completedAt\n }\n } else if (state !== 'working' && terminal && (!latest || status === 'error' || status === 'complete')) {\n state = 'failed'\n turn.failure = { code: status === 'error' ? 'turn.error' : 'turn.no_reply', message: 'The turn ended without a reply' }\n }\n turn.state = state\n if (state !== 'succeeded' && state !== 'failed' && options.approvals) {\n turn.approvals = await options.approvals(ctx, workspaceId, threadId)\n }\n return turn\n }\n\n async function admittedTurn(ctx: OperatorContext<Identity>, workspaceId: string, turnId: string, admission: ChatOperatorAdmission): Promise<OperatorTurn> {\n if (!(await threadIn(ctx, workspaceId, admission.threadId))) throw new OperatorError('operator.turn_identity_conflict', 409)\n const persisted = await turnOf(ctx, workspaceId, admission.threadId, turnId)\n if (persisted) return persisted\n return {\n workspaceId, threadId: admission.threadId, turnId, state: admission.refusal ? 'failed' : 'unknown',\n url: threadUrl(workspaceId, admission.threadId), reply: null, failure: admission.refusal ?? null,\n assets: [], files: [], approvals: [],\n }\n }\n\n async function ensureThread(ctx: OperatorContext<Identity>, workspaceId: string, input: StartTurnInput): Promise<string> {\n const id = (await sha256Hex(`operator-thread\\0${ctx.key.keyId}\\0${workspaceId}\\0${input.turnId}`)).slice(0, 32)\n const existing = await options.threads.get(id, ctx)\n if (existing) {\n if (existing.workspaceId !== workspaceId) throw new OperatorError('operator.turn_identity_conflict', 409, 'This turn id belongs to another conversation')\n return id\n }\n const title = (input.title ?? input.content.split('\\n').find((line) => line.trim()) ?? 'New conversation').trim().slice(0, 80)\n try {\n await options.threads.create(ctx, { id, workspaceId, title })\n } catch (error) {\n // A concurrent retry may have inserted the same id first.\n if (!(await threadIn(ctx, workspaceId, id))) throw error\n }\n return id\n }\n\n const adapter: OperatorAdapter<Identity> = {\n ...(options.acceptsAttachments === true ? { acceptsAttachments: true } : {}),\n ...(options.maxAttachments === undefined ? {} : { maxAttachments: options.maxAttachments }),\n async authorizeWorkspace(ctx, workspaceId, access) {\n const workspace = await options.workspaces.authorize(ctx, workspaceId, access)\n return workspace ? workspaceView(workspace) : null\n },\n async listWorkspaces(ctx) {\n return (await options.workspaces.list(ctx)).map(workspaceView)\n },\n async startTurn(ctx, workspace, input) {\n const priorAdmission = await options.admissions?.get(ctx, workspace.id, input.turnId)\n if (priorAdmission) {\n if (input.threadId && input.threadId !== priorAdmission.threadId) throw new OperatorError('operator.turn_identity_conflict', 409)\n return admittedTurn(ctx, workspace.id, input.turnId, priorAdmission)\n }\n let threadId = input.threadId\n if (threadId === undefined) {\n threadId = await ensureThread(ctx, workspace.id, input)\n } else if (!(await threadIn(ctx, workspace.id, threadId))) {\n throw new OperatorError('operator.thread_not_found', 404, 'Thread not found')\n }\n // A retried start whose turn is already recorded reads it instead of running again.\n const existing = await turnOf(ctx, workspace.id, threadId, input.turnId)\n if (existing) return existing\n const target = { workspaceId: workspace.id, threadId, turnId: input.turnId }\n if (options.admissions && !(await options.admissions.claim(ctx, target))) {\n const raced = await options.admissions.get(ctx, workspace.id, input.turnId)\n if (!raced) throw new OperatorError('operator.admission_unavailable', 503, 'Admission state is unavailable', true)\n if (raced.threadId !== threadId) throw new OperatorError('operator.turn_identity_conflict', 409)\n return admittedTurn(ctx, workspace.id, input.turnId, raced)\n }\n const response = await options.runTurn(ctx, {\n workspaceId: workspace.id, threadId, turnId: input.turnId, content: input.content,\n ...(input.model === undefined ? {} : { model: input.model }),\n ...(input.attachments === undefined ? {} : { attachments: input.attachments }),\n })\n if (!response.ok) {\n const body = await response.json().catch(() => ({})) as { error?: unknown; code?: unknown }\n // Apps answer `{ error, code }` or `{ error: { code, message } }`.\n const nested = body.error && typeof body.error === 'object' ? body.error as { code?: unknown; message?: unknown } : {}\n const failure = {\n code: typeof body.code === 'string' ? body.code : typeof nested.code === 'string' ? nested.code : `operator.chat_${response.status}`,\n message: typeof body.error === 'string' ? body.error : typeof nested.message === 'string' ? nested.message : 'The app refused the turn',\n }\n if (options.admissions) {\n await options.admissions.recordRefusal(ctx, target, failure)\n return admittedTurn(ctx, workspace.id, input.turnId, { threadId, refusal: failure })\n }\n throw new OperatorError(failure.code, response.status, failure.message, response.status === 429 || response.status >= 500)\n }\n await drain(response, ctx.request.signal)\n return await turnOf(ctx, workspace.id, threadId, input.turnId) ?? {\n workspaceId: workspace.id, threadId, turnId: input.turnId, state: 'unknown', url: threadUrl(workspace.id, threadId),\n reply: null, failure: null, assets: [], files: [], approvals: [],\n }\n },\n async getTurn(ctx, workspace, target) {\n if (!(await threadIn(ctx, workspace.id, target.threadId))) return null\n const persisted = await turnOf(ctx, workspace.id, target.threadId, target.turnId)\n if (persisted) return persisted\n const admission = await options.admissions?.get(ctx, workspace.id, target.turnId)\n return admission?.threadId === target.threadId ? admittedTurn(ctx, workspace.id, target.turnId, admission) : null\n },\n async getThread(ctx, workspace, threadId) {\n const thread = await threadIn(ctx, workspace.id, threadId)\n if (!thread) return null\n const messages = await options.threads.listMessages(threadId, ctx)\n const lastUser = [...messages].reverse().find((message) => message.role === 'user')\n const turnId = lastUser ? turnIdOf(lastUser) : null\n return { thread: threadView(thread), latestTurn: turnId ? await turnOf(ctx, workspace.id, threadId, turnId) : null }\n },\n listApprovals: (ctx, workspace) => options.approvals ? options.approvals(ctx, workspace.id) : Promise.resolve([]),\n }\n if (options.workspaces.create) {\n const create = options.workspaces.create\n adapter.createWorkspace = async (ctx, input) => workspaceView(await create(ctx, input))\n }\n if (options.threads.list) {\n const list = options.threads.list\n adapter.listThreads = async (ctx, workspace, query) => {\n const page = await list(ctx, workspace.id, query)\n return { threads: page.threads.map(threadView), nextCursor: page.nextCursor }\n }\n }\n if (options.files) {\n const files = options.files\n adapter.listFiles = (ctx, workspace, query) => files.list(ctx, workspace.id, query.prefix)\n adapter.readFile = (ctx, workspace, path) => files.read(ctx, workspace.id, path)\n }\n if (options.journal) {\n const journal = options.journal\n adapter.listJournal = (ctx, workspace, query) => journal(ctx, workspace.id, query.days)\n }\n if (options.assets?.read) {\n const read = options.assets.read\n adapter.readAsset = (ctx, workspace, assetId) => read(ctx, workspace.id, assetId)\n }\n if (options.scorecard) {\n const scorecard = options.scorecard\n adapter.getScorecard = (ctx, workspace, query) => scorecard(ctx, workspace.id, query.days)\n }\n return adapter\n}\n","/**\n * Let the operator API accept a Platform agent key next to the app's own keys.\n *\n * `withPlatformAgentKeys` wraps the app's existing `OperatorKeyStore`: a\n * Bearer key starting `sk-tan-` is verified at Platform for this app's\n * product (see `platform/agent-keys.ts`); every other key goes to the app's\n * own store unchanged, so existing `gak_` keys keep working.\n *\n * Authority for a Platform agent key:\n * - Which actions: only the key's `<product>:operator:read|write|run` scopes\n * (or `*`), mapped to `operator:read|write|run`. A key without any is\n * refused, so a key approved for other products cannot reach this API.\n * - Which user: the key owner's Tangle identity (stable Platform user id and\n * verified email), resolved through the app's own `TangleSsoAccountStore`,\n * the same account policy browser SSO applies. A first call creates the app\n * user exactly as a first browser sign-in would, and links it when the store\n * keeps links per user; an ambiguous or conflicting identity is refused.\n * Nothing in the request names the user.\n * - Which credential: `loadIdentity` receives the agent key for the request,\n * so the app acts with it and the work spends the key's one cap. It is held\n * only for the request, never on the key object.\n * - Which workspaces: the app's ordinary roles, through the operator\n * adapter's `authorizeWorkspace`. The key confers no workspace access.\n */\nimport {\n agentOperatorScopes,\n PLATFORM_KEY_PREFIX,\n type PlatformAgentKeyVerifier,\n} from '../platform/agent-keys.js'\nimport type { RequestApiKey } from '../platform/api-key-auth.js'\nimport type { TangleSsoAccountStore } from '../platform/sso.js'\nimport type { OperatorKeyStore } from './server.js'\n\nconst OPERATOR_ACTIONS = ['read', 'write', 'run'] as const\n\nexport interface PlatformAgentKeyAccess<Identity> {\n verifier: PlatformAgentKeyVerifier\n /** This app's Platform product id, e.g. `gtm-agent`. */\n product: string\n /**\n * The app's browser-SSO account store. Give `saveTangleLink` only when the\n * store keeps the Platform link per user (a link table): a first call then\n * links the user with the agent key, as a first sign-in would. A store that\n * keeps the key on the session row has no session to bind here; omit it and\n * act with `context.platformApiKey` instead.\n */\n accounts: Pick<TangleSsoAccountStore, 'resolveAccount' | 'upsertUserByEmail'>\n & Partial<Pick<TangleSsoAccountStore, 'saveTangleLink'>>\n /**\n * Load the operator identity for an app user id. `context.platformApiKey` is\n * the agent key this request came with: put it on the identity and use it as\n * the request's Platform credential. Never store or log it.\n */\n loadIdentity(userId: string, context: PlatformAgentKeyContext): Promise<Identity | null>\n /** Optional per-key request quota; by default every verified request is admitted. */\n claimRequest?(keyId: string, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/** What `loadIdentity` receives for a request made with a Platform agent key. */\nexport interface PlatformAgentKeyContext {\n /** The agent key itself, for this request only. */\n platformApiKey: string\n}\n\n/** An operator key that came from Platform agent signup. */\nexport interface PlatformAgentOperatorKey extends RequestApiKey {\n source: 'platform-agent'\n}\n\nfunction refused(status: number, code: string, error: string): Response {\n return Response.json({ error, code }, { status, headers: { 'cache-control': 'private, no-store' } })\n}\n\nfunction isPlatformAgentKey(key: RequestApiKey): key is PlatformAgentOperatorKey {\n return (key as Partial<PlatformAgentOperatorKey>).source === 'platform-agent'\n}\n\nexport function withPlatformAgentKeys<Key extends RequestApiKey, Identity>(\n appKeys: OperatorKeyStore<Key, Identity>,\n access: PlatformAgentKeyAccess<Identity>,\n): OperatorKeyStore<Key | PlatformAgentOperatorKey, Identity> {\n // The raw key for each verified key object, for this request's identity.\n const rawKeys = new WeakMap<PlatformAgentOperatorKey, string>()\n\n async function provisionOwner(verified: { platformUserId: string; email: string; name: string | null }, rawKey: string): Promise<string> {\n const resolution = await access.accounts.resolveAccount({ email: verified.email, platformUserId: verified.platformUserId })\n if (resolution.kind === 'reject') {\n throw refused(403, 'agent_key.account_conflict', `The key owner's Tangle identity conflicts with an account in this app (${resolution.reason}).`)\n }\n // A user already linked to this Platform identity is used as it is: its\n // profile and link belong to the owner's own sign-ins.\n if (resolution.kind === 'existing' && resolution.matchedBy === 'platform-id') return resolution.userId\n // A new or email-matched user is created now, the way a first browser\n // sign-in would. A link-table store also links it, with the agent key as\n // the credential the app acts with later; spend then counts against the\n // key's one cap.\n const { userId } = await access.accounts.upsertUserByEmail({\n email: verified.email,\n name: verified.name,\n tangleUserId: verified.platformUserId,\n resolution,\n })\n await access.accounts.saveTangleLink?.({\n userId,\n sessionToken: '',\n tangleUserId: verified.platformUserId,\n email: verified.email,\n name: verified.name,\n apiKey: rawKey,\n planTier: null,\n })\n return userId\n }\n\n return {\n async verify(authorization) {\n const raw = /^Bearer +(\\S+)$/i.exec(authorization)?.[1]\n if (!raw?.startsWith(PLATFORM_KEY_PREFIX)) return appKeys.verify(authorization)\n const verified = await access.verifier.verify(raw)\n if (!verified.ok) throw refused(verified.status, verified.code, verified.message)\n const scopes = agentOperatorScopes(verified.scopes, access.product, OPERATOR_ACTIONS)\n if (scopes.length === 0) {\n throw refused(403, 'agent_key.product_not_granted', \"The key's owner did not approve it for this app.\")\n }\n const ownerId = await provisionOwner(verified, raw)\n const key: PlatformAgentOperatorKey = {\n keyId: verified.keyId,\n ownerId,\n scopes,\n // The operator API requires a finite expiry. This one bounds the\n // request being authorized; the next request asks Platform again once\n // the verifier's short cache lapses.\n expiresAt: Math.max(verified.validUntil, Date.now() + 30_000),\n source: 'platform-agent',\n }\n rawKeys.set(key, raw)\n return key\n },\n async resolveIdentity(key) {\n if (!isPlatformAgentKey(key)) return appKeys.resolveIdentity(key as Key)\n const platformApiKey = rawKeys.get(key)\n return platformApiKey ? access.loadIdentity(key.ownerId, { platformApiKey }) : null\n },\n async claimRequest(key, requestId) {\n if (!isPlatformAgentKey(key)) return appKeys.claimRequest(key as Key, requestId)\n return access.claimRequest ? access.claimRequest(key.keyId, requestId) : { allowed: true }\n },\n }\n}\n","/**\n * The operator key store for an app whose own API keys live in the agent\n * gateway's key store, plus Platform agent keys when the deployment can verify\n * them. The app supplies the gateway calls (`verifyApiKeyFromStore` and the\n * store's `claimRequest`) and its identity loader; this owns the mapping, the\n * refusal of spending-capped keys on native routes, the rate-limit retry\n * window, and one Platform verifier per deployment configuration.\n */\nimport { createPlatformAgentKeyVerifier, type PlatformAgentKeyVerifier } from '../platform/agent-keys.js'\nimport type { RequestApiKey } from '../platform/api-key-auth.js'\nimport {\n withPlatformAgentKeys,\n type PlatformAgentKeyAccess,\n type PlatformAgentKeyContext,\n type PlatformAgentOperatorKey,\n} from './platform-agent-keys.js'\nimport type { OperatorKeyStore } from './server.js'\n\n/** An app key as the gateway's `verifyApiKeyFromStore` returns it. */\nexport interface GatewayVerifiedApiKey {\n keyId: string\n ownerId: string\n scopes: string[]\n key: { expiresAt?: Date | null }\n spendingLimitCents: number | null\n}\n\n/** The gateway key store's answer to counting one request. */\nexport interface GatewayRequestClaim {\n allowed: boolean\n reason?: string\n minuteResetAt: number\n dailyResetAt: number\n}\n\n/** An app key admitted to the operator API. */\nexport type GatewayOperatorKey = RequestApiKey & { spendingLimitCents: number | null }\n\nexport interface GatewayOperatorKeysOptions<Identity> {\n /** This app's Platform product id, e.g. `legal-agent`. */\n product: string\n /** Verify an Authorization header against the app's gateway key store. */\n verify(authorization: string): Promise<GatewayVerifiedApiKey | null>\n /** Count one request against the key's gateway limits. */\n claimRequest(keyId: string, requestId: string): Promise<GatewayRequestClaim>\n /** Load the key owner; `context` is present for a Platform agent key. */\n loadIdentity(userId: string, context?: PlatformAgentKeyContext): Promise<Identity | null>\n /**\n * Platform agent keys are accepted only when both the Platform URL and the\n * service token are configured; otherwise only the app's keys are.\n */\n platform: {\n url: string | undefined\n serviceToken: string | undefined\n accounts: PlatformAgentKeyAccess<Identity>['accounts']\n }\n}\n\nlet sharedVerifier: { config: string; verifier: PlatformAgentKeyVerifier } | null = null\n\n/** One verifier per deployment configuration, so its short cache spans requests. */\nfunction platformAgentKeyVerifier(platformUrl: string, serviceToken: string, product: string): PlatformAgentKeyVerifier {\n const config = `${platformUrl}\\n${serviceToken}\\n${product}`\n if (sharedVerifier?.config !== config) {\n sharedVerifier = {\n config,\n verifier: createPlatformAgentKeyVerifier({ platformUrl, serviceName: product, serviceToken, product }),\n }\n }\n return sharedVerifier.verifier\n}\n\nexport function createGatewayOperatorKeys<Identity>(\n options: GatewayOperatorKeysOptions<Identity>,\n): OperatorKeyStore<GatewayOperatorKey | PlatformAgentOperatorKey, Identity> {\n const appKeys: OperatorKeyStore<GatewayOperatorKey, Identity> = {\n async verify(authorization) {\n const verified = await options.verify(authorization)\n return verified ? {\n keyId: verified.keyId,\n ownerId: verified.ownerId,\n scopes: verified.scopes,\n expiresAt: verified.key.expiresAt?.getTime() ?? 0,\n spendingLimitCents: verified.spendingLimitCents,\n } : null\n },\n async resolveIdentity(key) {\n // Native routes use owner billing; capped keys stay on the gateway's reservation path.\n if (key.spendingLimitCents !== null) {\n throw Response.json({\n error: 'Capped keys must use the paid agent gateway; private APIs use owner billing',\n code: 'api_key.native_cap_unsupported',\n }, { status: 403 })\n }\n return options.loadIdentity(key.ownerId)\n },\n async claimRequest(key, requestId) {\n const result = await options.claimRequest(key.keyId, requestId)\n const resetAt = result.reason === 'daily' ? result.dailyResetAt : result.minuteResetAt\n return { allowed: result.allowed, retryAfterSeconds: Math.max(1, (resetAt - Date.now()) / 1000) }\n },\n }\n const platformUrl = options.platform.url?.trim()\n const serviceToken = options.platform.serviceToken?.trim()\n if (!platformUrl || !serviceToken) return appKeys\n return withPlatformAgentKeys(appKeys, {\n verifier: platformAgentKeyVerifier(platformUrl, serviceToken, options.product),\n product: options.product,\n accounts: options.platform.accounts,\n loadIdentity: options.loadIdentity,\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2GO,IAAM,gBAAN,cAA4B,MAAM;AAAA,EACvC,YACW,MACA,QACT,SACS,YAAY,OACrB;AACA,UAAM,WAAW,IAAI;AALZ;AACA;AAEA;AAGT,SAAK,OAAO;AAAA,E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c,QAAO;AAC1C,SAAO,sBAAsB,SAAS;AAAA,IACpC,UAAU,yBAAyB,aAAa,cAAc,QAAQ,OAAO;AAAA,IAC7E,SAAS,QAAQ;AAAA,IACjB,UAAU,QAAQ,SAAS;AAAA,IAC3B,cAAc,QAAQ;AAAA,EACxB,CAAC;AACH;","names":["text","workspace"]}
@@ -46,3 +46,34 @@ export declare function durablePlanConflictCode(error: {
46
46
  message: string;
47
47
  }): 'plan_already_decided' | 'plan_superseded' | 'plan_withdrawn' | null;
48
48
  export declare function isTerminalPlanStatus(status: ChatPlanStatus): boolean;
49
+ export type PlanLookupQuery = {
50
+ ok: true;
51
+ workspaceId: string;
52
+ threadId: string;
53
+ planId: string;
54
+ revision: number | null;
55
+ } | {
56
+ ok: false;
57
+ error: string;
58
+ };
59
+ /**
60
+ * Validate a current-plan lookup (`?workspaceId&threadId[&planId&revision]`).
61
+ * `planId` is empty when the caller asks for the thread's current plan; a
62
+ * named plan needs its positive integer revision.
63
+ */
64
+ export declare function parsePlanLookupQuery(url: URL): PlanLookupQuery;
65
+ /**
66
+ * The response for a sandbox refusal of a plan decision, or null when the
67
+ * refusal is not one the decision flow answers. A 409 means someone decided
68
+ * first: converge on the recorded outcome (`reconcile`), running `onApproved`
69
+ * when it was an approval. A plan the platform no longer knows can never be
70
+ * decided, so it is reported gone rather than retried.
71
+ */
72
+ export declare function planDecisionRefusalResponse(error: {
73
+ status?: number;
74
+ code?: string;
75
+ message: string;
76
+ }, options: {
77
+ reconcile: () => Promise<ChatPlan | null>;
78
+ onApproved: () => Promise<void>;
79
+ }): Promise<Response | null>;
@@ -2,7 +2,7 @@ import {
2
2
  canTransitionPlanStatus,
3
3
  persistedPartToPlan,
4
4
  planToPersistedPart
5
- } from "../chunk-WL7PZK7Q.js";
5
+ } from "../chunk-4PIN6QYQ.js";
6
6
 
7
7
  // src/plans/drizzle.ts
8
8
  import { and, eq, sql } from "drizzle-orm";
@@ -4,22 +4,26 @@ import {
4
4
  durablePlanConflictCode,
5
5
  isTerminalPlanStatus,
6
6
  parsePlanDecisionBody,
7
+ parsePlanLookupQuery,
7
8
  parsePlanSubmittedEvent,
8
9
  persistedPartToPlan,
10
+ planDecisionRefusalResponse,
9
11
  planFollowUpTurnId,
10
12
  planPartKey,
11
13
  planRevisionKey,
12
14
  planToPersistedPart,
13
15
  toChatPlan
14
- } from "../chunk-WL7PZK7Q.js";
16
+ } from "../chunk-4PIN6QYQ.js";
15
17
  export {
16
18
  PLAN_SUBMITTED_EVENT,
17
19
  canTransitionPlanStatus,
18
20
  durablePlanConflictCode,
19
21
  isTerminalPlanStatus,
20
22
  parsePlanDecisionBody,
23
+ parsePlanLookupQuery,
21
24
  parsePlanSubmittedEvent,
22
25
  persistedPartToPlan,
26
+ planDecisionRefusalResponse,
23
27
  planFollowUpTurnId,
24
28
  planPartKey,
25
29
  planRevisionKey,
@@ -25,8 +25,9 @@ export interface PlatformBillingHttpOptions {
25
25
  /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */
26
26
  baseUrl: string;
27
27
  /** Used only by `deduct()`; resolved lazily so reads never require it.
28
- * Throws at call time when empty. */
29
- serviceToken: string | (() => string);
28
+ * Throws at call time when empty. Default: the deployment's
29
+ * `PLATFORM_SERVICE_TOKEN`. */
30
+ serviceToken?: string | (() => string | undefined);
30
31
  /** Product slug — the `X-Service-Name` header and the deduct `product` field. */
31
32
  productSlug: string;
32
33
  fetchImpl?: typeof fetch;
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Where this deployment reaches the Tangle platform, read from its environment
3
+ * at call time so a Worker's bindings are current.
4
+ */
5
+ export declare function platformBaseUrlFromEnv(): string;
6
+ /**
7
+ * Options for the platform's cross-site SSO client: the base URL, the app id
8
+ * registered in the platform's trusted-apps registry (`TANGLE_PLATFORM_APP_ID`,
9
+ * else the product's own), and a fetch the client can call as a method. A
10
+ * Worker's `fetch` stored on an instance and called as `this.fetchImpl()`
11
+ * throws "Illegal invocation", so the global is wrapped in a free call.
12
+ */
13
+ export declare function platformAuthClientOptionsFromEnv(defaultAppId: string, overrides?: {
14
+ baseUrl?: string;
15
+ appId?: string;
16
+ fetchImpl?: typeof fetch;
17
+ }): {
18
+ baseUrl: string;
19
+ appId: string;
20
+ fetchImpl: typeof fetch;
21
+ };
@@ -15,3 +15,4 @@ export * from './billing-consent.js';
15
15
  export * from './delegated-keys.js';
16
16
  export * from './delegated-turn-keys.js';
17
17
  export * from './billable-turn-admission.js';
18
+ export * from './deployment.js';
@@ -39,9 +39,8 @@ import {
39
39
  import {
40
40
  sha256Hex
41
41
  } from "../chunk-HY57QRRW.js";
42
+ import "../chunk-V42C72V5.js";
42
43
  import "../chunk-TXD5HXLE.js";
43
- import "../chunk-6Z7TZVKZ.js";
44
- import "../chunk-57XPEL7X.js";
45
44
 
46
45
  // src/platform/sso-identity-store.ts
47
46
  var TANGLE_IDENTITY_PROVIDER_ID = "tangle";
@@ -466,6 +465,11 @@ function createPlatformBillingHttp(opts) {
466
465
  const fetchImpl = opts.fetchImpl ?? fetch;
467
466
  const timeoutMs = opts.timeoutMs ?? 1e4;
468
467
  function resolveServiceToken() {
468
+ if (opts.serviceToken === void 0) {
469
+ const token2 = (typeof process !== "undefined" ? process.env.PLATFORM_SERVICE_TOKEN : void 0)?.trim();
470
+ if (!token2) throw new Error("PLATFORM_SERVICE_TOKEN is required for platform billing calls");
471
+ return token2;
472
+ }
469
473
  const token = typeof opts.serviceToken === "function" ? opts.serviceToken() : opts.serviceToken;
470
474
  if (!token) throw new Error("A platform service token is required for deduct");
471
475
  return token;
@@ -585,11 +589,11 @@ async function readTangleTierState(http, userApiKey, policy = DEFAULT_TANGLE_TIE
585
589
  var FREE_TIER_SPEND_CAP_USD = 0;
586
590
  var DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = "SEAT_BILLING_ENABLED";
587
591
  function isSeatBillingEnabled(opts = {}) {
588
- const env = opts.env ?? (typeof process !== "undefined" ? process.env : void 0);
589
- if (!env) return true;
590
- const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase();
592
+ const env2 = opts.env ?? (typeof process !== "undefined" ? process.env : void 0);
593
+ if (!env2) return true;
594
+ const flag = env2[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase();
591
595
  if (flag) return !["false", "0", "off", "disabled", "no"].includes(flag);
592
- const environment = resolveTangleExecutionEnvironment(env);
596
+ const environment = resolveTangleExecutionEnvironment(env2);
593
597
  return environment !== "development" && environment !== "test";
594
598
  }
595
599
  async function getProductEntitlement(http, userApiKey, productId, flag = true) {
@@ -789,6 +793,21 @@ function createPlatformBillingConsent(options) {
789
793
  };
790
794
  }
791
795
 
796
+ // src/platform/deployment.ts
797
+ var env = () => globalThis.process?.env ?? {};
798
+ function platformBaseUrlFromEnv() {
799
+ const url = env().TANGLE_PLATFORM_URL ?? env().TANGLE_SSO_URL;
800
+ if (!url) throw new Error("TANGLE_PLATFORM_URL is required (or legacy TANGLE_SSO_URL)");
801
+ return url;
802
+ }
803
+ function platformAuthClientOptionsFromEnv(defaultAppId, overrides = {}) {
804
+ return {
805
+ baseUrl: overrides.baseUrl ?? platformBaseUrlFromEnv(),
806
+ appId: overrides.appId ?? env().TANGLE_PLATFORM_APP_ID ?? defaultAppId,
807
+ fetchImpl: overrides.fetchImpl ?? ((input, init) => globalThis.fetch(input, init))
808
+ };
809
+ }
810
+
792
811
  // src/platform/delegated-keys.ts
793
812
  var REQUEST_TIMEOUT_MS3 = 1e4;
794
813
  var UNAVAILABLE_BASE_DELAY_MS = 250;
@@ -873,13 +892,12 @@ function childProblem(data, request, name, serviceName, nowMs) {
873
892
  function createPlatformDelegatedKeyClient(options) {
874
893
  const fetchImpl = options.fetch ?? fetch;
875
894
  const now = options.now ?? Date.now;
876
- const env = () => globalThis.process?.env;
877
- const origin = options.platformUrl ?? env()?.TANGLE_PLATFORM_URL ?? env()?.TANGLE_SSO_URL;
878
- if (!origin) throw new Error("TANGLE_PLATFORM_URL is required for delegated product keys");
895
+ const env2 = () => globalThis.process?.env;
896
+ const origin = options.platformUrl ?? platformBaseUrlFromEnv();
879
897
  const base = options.platformUrl ? origin.replace(/\/+$/, "") : new URL(origin).origin;
880
898
  const serviceToken = () => {
881
899
  if (options.serviceToken !== void 0) return typeof options.serviceToken === "function" ? options.serviceToken() : options.serviceToken;
882
- const token = env()?.PLATFORM_SERVICE_TOKEN?.trim();
900
+ const token = env2()?.PLATFORM_SERVICE_TOKEN?.trim();
883
901
  if (!token) throw new Error("PLATFORM_SERVICE_TOKEN is required for delegated product keys");
884
902
  return token;
885
903
  };
@@ -1468,6 +1486,8 @@ export {
1468
1486
  normalizeTanglePlanTier,
1469
1487
  normalizeTangleSsoEmail,
1470
1488
  parseAdminEmails,
1489
+ platformAuthClientOptionsFromEnv,
1490
+ platformBaseUrlFromEnv,
1471
1491
  platformKeyRefusal,
1472
1492
  readTangleTierState,
1473
1493
  resolveTangleSsoAccount,