@tangle-network/agent-app 0.60.18 → 0.60.20

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.
@@ -1,5 +1,5 @@
1
- import type { OperatorApproval, OperatorAssetRef, OperatorFile, OperatorFileEntry, OperatorJournalEntry, OperatorRole, OperatorScorecard } from './contract';
2
- import { type OperatorAdapter, type OperatorContext } from './server';
1
+ import type { OperatorApproval, OperatorAssetRef, OperatorFile, OperatorFileEntry, OperatorJournalEntry, OperatorRole, OperatorScorecard } from './contract.js';
2
+ import { type OperatorAdapter, type OperatorContext } from './server.js';
3
3
  /** The message fields the adapter reads; agent-app's chat-store rows satisfy it. */
4
4
  export interface ChatOperatorMessage {
5
5
  id: string;
@@ -1,4 +1,4 @@
1
- import { type OperatorApproval, type OperatorAppInfo, type OperatorFile, type OperatorFileEntry, type OperatorJournalEntry, type OperatorPrincipalInfo, type OperatorScorecard, type OperatorThread, type OperatorTurn, type OperatorWorkspace, type StartTurnInput } from './contract';
1
+ import { type OperatorApproval, type OperatorAppInfo, type OperatorFile, type OperatorFileEntry, type OperatorJournalEntry, type OperatorPrincipalInfo, type OperatorScorecard, type OperatorThread, type OperatorTurn, type OperatorWorkspace, type StartTurnInput } from './contract.js';
2
2
  export type OperatorResult<T> = {
3
3
  succeeded: true;
4
4
  value: T;
@@ -3,8 +3,8 @@
3
3
  * mounts, a scoped-key authority model, and a typed client for outside agents.
4
4
  * Web-standard Request/Response only.
5
5
  */
6
- export * from './contract';
7
- export * from './server';
8
- export * from './client';
9
- export * from './chat-adapter';
10
- export * from './platform-agent-keys';
6
+ export * from './contract.js';
7
+ export * from './server.js';
8
+ export * from './client.js';
9
+ export * from './chat-adapter.js';
10
+ export * from './platform-agent-keys.js';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/operator/contract.ts","../../src/operator/server.ts","../../src/operator/client.ts","../../src/operator/chat-adapter.ts","../../src/operator/platform-agent-keys.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\nexport const OPERATOR_API_VERSION = 'v1'\nexport const OPERATOR_API_BASE_PATH = '/api/operator/v1'\n\n/** Key permissions, with the labels an app's API access page shows. */\nexport const OPERATOR_ACCESS = [\n {\n scope: 'operator:read',\n label: 'Read workspaces',\n description: 'Read workspaces, conversations, files, approvals, scorecards, and run status.',\n },\n {\n scope: 'operator:write',\n label: 'Create and edit',\n description: 'Create workspaces and conversations, and write files.',\n },\n {\n scope: 'operator:run',\n requires: ['operator:read'],\n label: 'Run agents',\n description: 'Requires read access. Start, continue, and interrupt agent turns, and answer their questions and tool-permission requests. Agents can modify workspace files. Uses your plan and budget.',\n },\n] as const\n\nexport type OperatorScope = typeof OPERATOR_ACCESS[number]['scope']\n\nexport const OPERATOR_API_SCOPES: readonly OperatorScope[] = OPERATOR_ACCESS.map(({ scope }) => scope)\n\nexport const OPERATOR_SCOPE_DEPENDENCIES: Readonly<Record<string, readonly string[]>> = Object.fromEntries(\n OPERATOR_ACCESS.flatMap((option) => 'requires' in option ? [[option.scope, option.requires]] : []),\n)\n\n/**\n * A key carrying one or more of these scopes reaches only the named\n * workspaces and cannot create workspaces. Keys without one keep the owner's\n * ordinary workspace access.\n */\nexport const OPERATOR_WORKSPACE_SCOPE_PREFIX = 'operator:workspace:'\n\nconst WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function operatorWorkspaceScope(workspaceId: string): string {\n if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError('Workspace ids contain only letters, digits, - and _')\n return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`\n}\n\n/** The workspaces a key is restricted to, or null when it is unrestricted. A malformed restriction restricts to nothing. */\nexport function operatorKeyWorkspaces(scopes: readonly string[]): readonly string[] | null {\n const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX))\n if (restricted.length === 0) return null\n return restricted\n .map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length))\n .filter((id) => WORKSPACE_ID.test(id))\n}\n\nexport type OperatorRole = 'owner' | 'admin' | 'editor' | 'viewer'\n\nexport interface OperatorAppInfo {\n /** Stable app identifier, such as `gtm` or `tax`. */\n app: string\n name: string\n apiVersion: typeof OPERATOR_API_VERSION\n /** Optional operations this app implements; absent ones answer 501. */\n capabilities: OperatorCapability[]\n}\n\nexport type OperatorCapability =\n | 'workspaces.create'\n | 'threads.read'\n | 'files.read'\n | 'journal.read'\n | 'assets.read'\n | 'scorecard.read'\n\nexport interface OperatorPrincipalInfo {\n keyId: string\n scopes: string[]\n /** Workspaces the key is restricted to, or null for the owner's ordinary access. */\n workspaces: string[] | null\n}\n\nexport interface OperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n /** Browser link for a person to open the workspace. */\n url?: string\n createdAt?: string\n}\n\nexport interface OperatorThread {\n id: string\n title: string\n updatedAt?: string\n url?: string\n}\n\n/**\n * `succeeded` and `failed` are settled. `input-required` waits on a person or\n * an operator decision listed in `approvals`. `unknown` means the app cannot\n * establish the state; it is never evidence of success.\n */\nexport type OperatorTurnState = 'queued' | 'working' | 'input-required' | 'succeeded' | 'failed' | 'unknown'\n\nexport const OPERATOR_SETTLED_STATES: readonly OperatorTurnState[] = ['succeeded', 'failed']\n\nexport interface OperatorAssetRef {\n id: string\n /** Root-relative operator route that returns the bytes. */\n path: string\n mediaType?: string\n name?: string\n}\n\nexport interface OperatorFileChange {\n path: string\n action: 'created' | 'updated' | 'deleted' | 'changed'\n}\n\nexport type OperatorApprovalKind = 'question' | 'permission' | 'plan' | 'hub' | 'asset' | 'review'\n\nexport interface OperatorApproval {\n id: string\n kind: OperatorApprovalKind\n title: string\n detail?: string\n threadId?: string\n /** Browser link where an authorized person decides it. */\n url?: string\n createdAt?: string\n expiresAt?: string\n /** Who can decide: an operator key with run access, an editor, or the workspace owner. */\n decidedBy: 'operator' | 'editor' | 'owner'\n}\n\nexport interface OperatorTurn {\n workspaceId: string\n threadId: string\n turnId: string\n state: OperatorTurnState\n url?: string\n executionId?: string\n model?: string\n costUsd?: number\n completedAt?: string\n /** The settled answer; null until the turn settles. */\n reply: { content: string; mediaType: string } | null\n failure: { code?: string; message: string } | null\n assets: OperatorAssetRef[]\n files: OperatorFileChange[]\n /** Decisions open on this turn's conversation. */\n approvals: OperatorApproval[]\n}\n\nexport interface OperatorJournalEntry {\n path: string\n /** `YYYY-MM-DD` the entry belongs to. */\n date: string\n title?: string\n updatedAt?: string\n}\n\nexport interface OperatorFileEntry {\n path: string\n updatedAt?: string\n bytes?: number\n}\n\nexport interface OperatorFile {\n path: string\n content: string\n mediaType: string\n revision?: string\n}\n\nexport interface OperatorMetric {\n key: string\n label: string\n /** Null when the app has no measurement; never a guessed zero. */\n value: number | null\n unit: 'count' | 'usd' | 'ratio' | 'ms'\n note?: string\n}\n\nexport interface OperatorScorecard {\n workspaceId: string\n generatedAt: string\n window: { start: string; end: string; days: number }\n /** Work the agent did in the window. */\n metrics: OperatorMetric[]\n /** Business results recorded in the window, such as clicks, signups, or replies. */\n outcomes: OperatorMetric[]\n /** How the numbers are measured and what they exclude. */\n measurement: string\n}\n\nexport interface OperatorErrorBody {\n error: string\n code: string\n retryable?: boolean\n}\n\nexport interface StartTurnInput {\n /** Client-generated UUID. Reuse it to retry the same turn; it never starts twice. */\n turnId: string\n content: string\n /** Continue this conversation; omitted starts a new one. */\n threadId?: string\n /** Title for a new conversation. */\n title?: string\n model?: string\n}\n\n/** Route table: method, path pattern under the base path, and required scopes. */\nexport const OPERATOR_ROUTES = [\n { id: 'describe', method: 'GET', path: '', scopes: ['operator:read'] },\n { id: 'workspaces.list', method: 'GET', path: '/workspaces', scopes: ['operator:read'] },\n { id: 'workspaces.create', method: 'POST', path: '/workspaces', scopes: ['operator:write'] },\n { id: 'workspaces.get', method: 'GET', path: '/workspaces/:workspaceId', scopes: ['operator:read'] },\n { id: 'turns.start', method: 'POST', path: '/workspaces/:workspaceId/turns', scopes: ['operator:read', 'operator:run'] },\n { id: 'threads.list', method: 'GET', path: '/workspaces/:workspaceId/threads', scopes: ['operator:read'] },\n { id: 'threads.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId', scopes: ['operator:read'] },\n { id: 'turns.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId', scopes: ['operator:read'] },\n { id: 'approvals.list', method: 'GET', path: '/workspaces/:workspaceId/approvals', scopes: ['operator:read'] },\n { id: 'journal.list', method: 'GET', path: '/workspaces/:workspaceId/journal', scopes: ['operator:read'] },\n { id: 'files.list', method: 'GET', path: '/workspaces/:workspaceId/files', scopes: ['operator:read'] },\n { id: 'files.read', method: 'GET', path: '/workspaces/:workspaceId/file', scopes: ['operator:read'] },\n { id: 'assets.read', method: 'GET', path: '/workspaces/:workspaceId/assets/:assetId', scopes: ['operator:read'] },\n { id: 'scorecard.get', method: 'GET', path: '/workspaces/:workspaceId/scorecard', scopes: ['operator:read'] },\n] as const satisfies ReadonlyArray<{ id: string; method: 'GET' | 'POST'; path: string; scopes: readonly OperatorScope[] }>\n\nexport type OperatorRouteId = typeof OPERATOR_ROUTES[number]['id']\n\nconst SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/\n\n/** Match a pathname under the base path to its route and decoded parameters. */\nexport function matchOperatorRoute(\n method: string,\n pathname: string,\n basePath: string = OPERATOR_API_BASE_PATH,\n): { route: typeof OPERATOR_ROUTES[number]; params: Record<string, string> } | null {\n if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null\n const rest = pathname.slice(basePath.length).replace(/\\/$/, '')\n const actual = rest ? rest.split('/').slice(1) : []\n for (const route of OPERATOR_ROUTES) {\n if (route.method !== method) continue\n const pattern = route.path ? route.path.split('/').slice(1) : []\n if (pattern.length !== actual.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index++) {\n const expected = pattern[index]!\n const segment = actual[index]!\n if (expected.startsWith(':')) {\n if (!SEGMENT.test(segment)) { matched = false; break }\n let decoded: string\n try { decoded = decodeURIComponent(segment) } catch { matched = false; break }\n if (!decoded || decoded.includes('/')) { matched = false; break }\n params[expected.slice(1)] = decoded\n } else if (expected !== segment) {\n matched = false\n break\n }\n }\n if (matched) return { route, params }\n }\n return null\n}\n","import { createApiKeyRequestAuth, type RequestApiKey } from '../platform/api-key-auth'\nimport {\n OPERATOR_API_BASE_PATH,\n OPERATOR_API_VERSION,\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'\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 /** 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 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'])\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>): 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 return {\n turnId: body.turnId.toLowerCase(),\n content: body.content,\n ...(threadId === undefined ? {} : { threadId }),\n ...(title === undefined ? {} : { title }),\n ...(model === undefined ? {} : { model }),\n }\n}\n\nfunction capabilities<Identity>(adapter: OperatorAdapter<Identity>): OperatorCapability[] {\n const present: Array<[OperatorCapability, unknown]> = [\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 return present.filter(([, implemented]) => typeof implemented === 'function').map(([name]) => name)\n}\n\nfunction unsupported(): never {\n throw new OperatorError('operator.unsupported', 501, 'This app does not implement this operation')\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 turn.state === 'succeeded' || turn.state === 'failed' || 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 workspace = await adapter.authorizeWorkspace(ctx, workspaceId, route.id === 'turns.start' ? 'run' : 'read')\n if (!workspace) throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n\n switch (route.id) {\n case 'workspaces.get':\n return json({ workspace })\n case 'turns.start': {\n const input = parseStartTurn(await readJsonBody(request))\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 const deadline = Date.now() + wait * 1000\n let turn = await adapter.getTurn(ctx, workspace, target)\n while (turn && !needsAttention(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 json({ turn })\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 { createApiKeyFetch } from '../web/api-key-fetch'\nimport {\n OPERATOR_API_BASE_PATH,\n type OperatorApproval,\n type OperatorAppInfo,\n type OperatorErrorBody,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorPrincipalInfo,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract'\n\nexport type OperatorResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; code: string; error: string; retryable: boolean }\n\nexport interface OperatorClientOptions {\n /** The app's origin, such as `https://gtm.tangle.tools`. */\n origin: string\n /** Resolve the key from trusted secret storage on each request; never from model output. */\n getApiKey(): string | Promise<string>\n fetchImpl?: typeof fetch\n allowHttpLoopback?: boolean\n basePath?: string\n}\n\nexport interface WaitForTurnOptions {\n /** Total time to follow the turn. */\n timeoutMs: number\n /** Server hold per request, in seconds; the server caps it. */\n waitSeconds?: number\n signal?: AbortSignal\n}\n\nexport interface OperatorClient {\n describe(): Promise<OperatorResult<{ app: OperatorAppInfo; principal: OperatorPrincipalInfo }>>\n listWorkspaces(): Promise<OperatorResult<OperatorWorkspace[]>>\n createWorkspace(input: { name: string }): Promise<OperatorResult<OperatorWorkspace>>\n getWorkspace(workspaceId: string): Promise<OperatorResult<OperatorWorkspace>>\n /** Omitting turnId generates one; retry with the returned turn's id. */\n startTurn(workspaceId: string, input: Omit<StartTurnInput, 'turnId'> & { turnId?: string }): Promise<OperatorResult<OperatorTurn>>\n getTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /** Follow until the turn settles, waits on a decision, or the timeout passes; the last read is returned. */\n waitForTurn(workspaceId: string, threadId: string, turnId: string, options: WaitForTurnOptions): Promise<OperatorResult<OperatorTurn>>\n listThreads(workspaceId: string, query?: { cursor?: string; limit?: number }): Promise<OperatorResult<{ threads: OperatorThread[]; nextCursor: string | null }>>\n getThread(workspaceId: string, threadId: string): Promise<OperatorResult<{ thread: OperatorThread; latestTurn: OperatorTurn | null }>>\n listApprovals(workspaceId: string): Promise<OperatorResult<OperatorApproval[]>>\n listJournal(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorJournalEntry[]>>\n listFiles(workspaceId: string, query?: { prefix?: string }): Promise<OperatorResult<OperatorFileEntry[]>>\n readFile(workspaceId: string, path: string): Promise<OperatorResult<OperatorFile>>\n /** The raw asset response; the caller reads and bounds its body. */\n readAsset(workspaceId: string, assetId: string, init?: { signal?: AbortSignal }): Promise<OperatorResult<Response>>\n getScorecard(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorScorecard>>\n}\n\nfunction segment(value: string): string {\n return encodeURIComponent(value)\n}\n\nasync function failure(response: Response): Promise<OperatorResult<never>> {\n let body: Partial<OperatorErrorBody> = {}\n try { body = await response.json() as Partial<OperatorErrorBody> } catch { /* A non-JSON refusal keeps its status. */ }\n return {\n succeeded: false,\n status: response.status,\n code: typeof body.code === 'string' ? body.code : `http_${response.status}`,\n error: typeof body.error === 'string' ? body.error : `HTTP ${response.status}`,\n retryable: body.retryable === true || response.status === 429 || response.status >= 500,\n }\n}\n\nfunction transportFailure(error: unknown): OperatorResult<never> {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n succeeded: false,\n status: 0,\n code: aborted ? 'operator.aborted' : 'operator.transport_failed',\n // createApiKeyFetch never forwards transport diagnostics, which could carry the key.\n error: error instanceof Error ? error.message : 'Operator transport failed',\n retryable: !aborted,\n }\n}\n\nconst SETTLED = new Set(['succeeded', 'failed', 'input-required'])\n\n/** A typed client for one app's operator API. */\nexport function createOperatorClient(options: OperatorClientOptions): OperatorClient {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const request = createApiKeyFetch({\n origin: options.origin,\n getApiKey: options.getApiKey,\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n ...(options.allowHttpLoopback ? { allowHttpLoopback: true } : {}),\n })\n\n async function call<T>(\n path: string,\n pick: (body: Record<string, unknown>) => T,\n init: RequestInit = {},\n ): Promise<OperatorResult<T>> {\n let response: Response\n try {\n response = await request(`${basePath}${path}`, {\n ...init,\n headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}) },\n })\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n try {\n return { succeeded: true, value: pick(await response.json() as Record<string, unknown>) }\n } catch {\n return { succeeded: false, status: response.status, code: 'operator.invalid_response', error: 'The response was not the expected JSON', retryable: true }\n }\n }\n\n const query = (params: Record<string, string | number | undefined>) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(params)) if (value !== undefined && value !== '') search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n }\n\n const client: OperatorClient = {\n describe: () => call('', (body) => body as unknown as { app: OperatorAppInfo; principal: OperatorPrincipalInfo }),\n listWorkspaces: () => call('/workspaces', (body) => body.workspaces as OperatorWorkspace[]),\n createWorkspace: (input) => call('/workspaces', (body) => body.workspace as OperatorWorkspace, {\n method: 'POST', body: JSON.stringify({ name: input.name }),\n }),\n getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace as OperatorWorkspace),\n startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn as OperatorTurn, {\n method: 'POST', body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() }),\n }),\n getTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n opts.signal ? { signal: opts.signal } : {},\n ),\n async waitForTurn(workspaceId, threadId, turnId, opts) {\n const deadline = Date.now() + opts.timeoutMs\n const waitSeconds = opts.waitSeconds ?? 25\n let last: OperatorResult<OperatorTurn> | null = null\n while (true) {\n const remaining = Math.floor((deadline - Date.now()) / 1000)\n const started = Date.now()\n last = await client.getTurn(workspaceId, threadId, turnId, {\n waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n if (!last.succeeded) {\n if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last\n await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, Math.max(0, deadline - Date.now()))))\n continue\n }\n if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last\n if (Date.now() >= deadline || opts.signal?.aborted) return last\n // A server that does not hold the read still gets a bounded request rate.\n if (Date.now() - started < 1_000) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(2_000, Math.max(0, deadline - Date.now()))))\n }\n }\n },\n listThreads: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,\n (body) => ({ threads: body.threads as OperatorThread[], nextCursor: (body.nextCursor as string | null) ?? null }),\n ),\n getThread: (workspaceId, threadId) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,\n (body) => ({ thread: body.thread as OperatorThread, latestTurn: (body.latestTurn as OperatorTurn | null) ?? null }),\n ),\n listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals as OperatorApproval[]),\n listJournal: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,\n (body) => body.entries as OperatorJournalEntry[],\n ),\n listFiles: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,\n (body) => body.files as OperatorFileEntry[],\n ),\n readFile: (workspaceId, path) => call(\n `/workspaces/${segment(workspaceId)}/file${query({ path })}`,\n (body) => body.file as OperatorFile,\n ),\n async readAsset(workspaceId, assetId, init = {}) {\n let response: Response\n try {\n response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {})\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n return { succeeded: true, value: response }\n },\n getScorecard: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,\n (body) => body.scorecard as OperatorScorecard,\n ),\n }\n return client\n}\n","import { messageHasTurnId } from '../stream/turn-identity'\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'\nimport { OperatorError, type OperatorAdapter, type OperatorContext } from './server'\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}\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\nexport interface ChatOperatorAdapterOptions<Identity> {\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 */\n runTurn(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string; content: string; model?: string }): Promise<Response>\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 /** A reply's failure; defaults to a `turn-failure` notice or an `error` part. */\n failureOf?(message: ChatOperatorMessage): { code?: string; message: string } | null\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 notice = 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 return { ...(typeof part.code === 'string' ? { code: part.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\nasync function sha256Hex(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\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 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 (state !== 'working') {\n const failure = (options.failureOf ?? defaultFailure)(assistant)\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' && !latest) {\n state = 'failed'\n turn.failure = { 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 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 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 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 response = await options.runTurn(ctx, {\n workspaceId: workspace.id, threadId, turnId: input.turnId, content: input.content,\n ...(input.model === undefined ? {} : { model: input.model }),\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 throw new OperatorError(\n typeof body.code === 'string' ? body.code : typeof nested.code === 'string' ? nested.code : `operator.chat_${response.status}`,\n response.status,\n typeof body.error === 'string' ? body.error : typeof nested.message === 'string' ? nested.message : 'The app refused the turn',\n response.status === 429 || response.status >= 500,\n )\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 return turnOf(ctx, workspace.id, target.threadId, target.turnId)\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'\nimport type { RequestApiKey } from '../platform/api-key-auth'\nimport type { TangleSsoAccountStore } from '../platform/sso'\nimport type { OperatorKeyStore } from './server'\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":";;;;;;;;;;;;;AAOO,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB;AAG/B,IAAM,kBAAkB;AAAA,EAC7B;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,OAAO;AAAA,I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Q,OAAO,aAAa;AAC9E,YAAM,WAAW,MAAM,OAAO,SAAS,OAAO,GAAG;AACjD,UAAI,CAAC,SAAS,GAAI,OAAM,QAAQ,SAAS,QAAQ,SAAS,MAAM,SAAS,OAAO;AAChF,YAAM,SAAS,oBAAoB,SAAS,QAAQ,OAAO,SAAS,gBAAgB;AACpF,UAAI,OAAO,WAAW,GAAG;AACvB,cAAM,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":["segment","segment","text","workspace","text","failure"]}
1
+ {"version":3,"sources":["../../src/operator/contract.ts","../../src/operator/server.ts","../../src/operator/client.ts","../../src/operator/chat-adapter.ts","../../src/operator/platform-agent-keys.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\nexport const OPERATOR_API_VERSION = 'v1'\nexport const OPERATOR_API_BASE_PATH = '/api/operator/v1'\n\n/** Key permissions, with the labels an app's API access page shows. */\nexport const OPERATOR_ACCESS = [\n {\n scope: 'operator:read',\n label: 'Read workspaces',\n description: 'Read workspaces, conversations, files, approvals, scorecards, and run status.',\n },\n {\n scope: 'operator:write',\n label: 'Create and edit',\n description: 'Create workspaces and conversations, and write files.',\n },\n {\n scope: 'operator:run',\n requires: ['operator:read'],\n label: 'Run agents',\n description: 'Requires read access. Start, continue, and interrupt agent turns, and answer their questions and tool-permission requests. Agents can modify workspace files. Uses your plan and budget.',\n },\n] as const\n\nexport type OperatorScope = typeof OPERATOR_ACCESS[number]['scope']\n\nexport const OPERATOR_API_SCOPES: readonly OperatorScope[] = OPERATOR_ACCESS.map(({ scope }) => scope)\n\nexport const OPERATOR_SCOPE_DEPENDENCIES: Readonly<Record<string, readonly string[]>> = Object.fromEntries(\n OPERATOR_ACCESS.flatMap((option) => 'requires' in option ? [[option.scope, option.requires]] : []),\n)\n\n/**\n * A key carrying one or more of these scopes reaches only the named\n * workspaces and cannot create workspaces. Keys without one keep the owner's\n * ordinary workspace access.\n */\nexport const OPERATOR_WORKSPACE_SCOPE_PREFIX = 'operator:workspace:'\n\nconst WORKSPACE_ID = /^[A-Za-z0-9_-]{1,128}$/\n\nexport function operatorWorkspaceScope(workspaceId: string): string {\n if (!WORKSPACE_ID.test(workspaceId)) throw new TypeError('Workspace ids contain only letters, digits, - and _')\n return `${OPERATOR_WORKSPACE_SCOPE_PREFIX}${workspaceId}`\n}\n\n/** The workspaces a key is restricted to, or null when it is unrestricted. A malformed restriction restricts to nothing. */\nexport function operatorKeyWorkspaces(scopes: readonly string[]): readonly string[] | null {\n const restricted = scopes.filter((scope) => scope.startsWith(OPERATOR_WORKSPACE_SCOPE_PREFIX))\n if (restricted.length === 0) return null\n return restricted\n .map((scope) => scope.slice(OPERATOR_WORKSPACE_SCOPE_PREFIX.length))\n .filter((id) => WORKSPACE_ID.test(id))\n}\n\nexport type OperatorRole = 'owner' | 'admin' | 'editor' | 'viewer'\n\nexport interface OperatorAppInfo {\n /** Stable app identifier, such as `gtm` or `tax`. */\n app: string\n name: string\n apiVersion: typeof OPERATOR_API_VERSION\n /** Optional operations this app implements; absent ones answer 501. */\n capabilities: OperatorCapability[]\n}\n\nexport type OperatorCapability =\n | 'workspaces.create'\n | 'threads.read'\n | 'files.read'\n | 'journal.read'\n | 'assets.read'\n | 'scorecard.read'\n\nexport interface OperatorPrincipalInfo {\n keyId: string\n scopes: string[]\n /** Workspaces the key is restricted to, or null for the owner's ordinary access. */\n workspaces: string[] | null\n}\n\nexport interface OperatorWorkspace {\n id: string\n name: string\n role?: OperatorRole\n /** Browser link for a person to open the workspace. */\n url?: string\n createdAt?: string\n}\n\nexport interface OperatorThread {\n id: string\n title: string\n updatedAt?: string\n url?: string\n}\n\n/**\n * `succeeded` and `failed` are settled. `input-required` waits on a person or\n * an operator decision listed in `approvals`. `unknown` means the app cannot\n * establish the state; it is never evidence of success.\n */\nexport type OperatorTurnState = 'queued' | 'working' | 'input-required' | 'succeeded' | 'failed' | 'unknown'\n\nexport const OPERATOR_SETTLED_STATES: readonly OperatorTurnState[] = ['succeeded', 'failed']\n\nexport interface OperatorAssetRef {\n id: string\n /** Root-relative operator route that returns the bytes. */\n path: string\n mediaType?: string\n name?: string\n}\n\nexport interface OperatorFileChange {\n path: string\n action: 'created' | 'updated' | 'deleted' | 'changed'\n}\n\nexport type OperatorApprovalKind = 'question' | 'permission' | 'plan' | 'hub' | 'asset' | 'review'\n\nexport interface OperatorApproval {\n id: string\n kind: OperatorApprovalKind\n title: string\n detail?: string\n threadId?: string\n /** Browser link where an authorized person decides it. */\n url?: string\n createdAt?: string\n expiresAt?: string\n /** Who can decide: an operator key with run access, an editor, or the workspace owner. */\n decidedBy: 'operator' | 'editor' | 'owner'\n}\n\nexport interface OperatorTurn {\n workspaceId: string\n threadId: string\n turnId: string\n state: OperatorTurnState\n url?: string\n executionId?: string\n model?: string\n costUsd?: number\n completedAt?: string\n /** The settled answer; null until the turn settles. */\n reply: { content: string; mediaType: string } | null\n failure: { code?: string; message: string } | null\n assets: OperatorAssetRef[]\n files: OperatorFileChange[]\n /** Decisions open on this turn's conversation. */\n approvals: OperatorApproval[]\n}\n\nexport interface OperatorJournalEntry {\n path: string\n /** `YYYY-MM-DD` the entry belongs to. */\n date: string\n title?: string\n updatedAt?: string\n}\n\nexport interface OperatorFileEntry {\n path: string\n updatedAt?: string\n bytes?: number\n}\n\nexport interface OperatorFile {\n path: string\n content: string\n mediaType: string\n revision?: string\n}\n\nexport interface OperatorMetric {\n key: string\n label: string\n /** Null when the app has no measurement; never a guessed zero. */\n value: number | null\n unit: 'count' | 'usd' | 'ratio' | 'ms'\n note?: string\n}\n\nexport interface OperatorScorecard {\n workspaceId: string\n generatedAt: string\n window: { start: string; end: string; days: number }\n /** Work the agent did in the window. */\n metrics: OperatorMetric[]\n /** Business results recorded in the window, such as clicks, signups, or replies. */\n outcomes: OperatorMetric[]\n /** How the numbers are measured and what they exclude. */\n measurement: string\n}\n\nexport interface OperatorErrorBody {\n error: string\n code: string\n retryable?: boolean\n}\n\nexport interface StartTurnInput {\n /** Client-generated UUID. Reuse it to retry the same turn; it never starts twice. */\n turnId: string\n content: string\n /** Continue this conversation; omitted starts a new one. */\n threadId?: string\n /** Title for a new conversation. */\n title?: string\n model?: string\n}\n\n/** Route table: method, path pattern under the base path, and required scopes. */\nexport const OPERATOR_ROUTES = [\n { id: 'describe', method: 'GET', path: '', scopes: ['operator:read'] },\n { id: 'workspaces.list', method: 'GET', path: '/workspaces', scopes: ['operator:read'] },\n { id: 'workspaces.create', method: 'POST', path: '/workspaces', scopes: ['operator:write'] },\n { id: 'workspaces.get', method: 'GET', path: '/workspaces/:workspaceId', scopes: ['operator:read'] },\n { id: 'turns.start', method: 'POST', path: '/workspaces/:workspaceId/turns', scopes: ['operator:read', 'operator:run'] },\n { id: 'threads.list', method: 'GET', path: '/workspaces/:workspaceId/threads', scopes: ['operator:read'] },\n { id: 'threads.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId', scopes: ['operator:read'] },\n { id: 'turns.get', method: 'GET', path: '/workspaces/:workspaceId/threads/:threadId/turns/:turnId', scopes: ['operator:read'] },\n { id: 'approvals.list', method: 'GET', path: '/workspaces/:workspaceId/approvals', scopes: ['operator:read'] },\n { id: 'journal.list', method: 'GET', path: '/workspaces/:workspaceId/journal', scopes: ['operator:read'] },\n { id: 'files.list', method: 'GET', path: '/workspaces/:workspaceId/files', scopes: ['operator:read'] },\n { id: 'files.read', method: 'GET', path: '/workspaces/:workspaceId/file', scopes: ['operator:read'] },\n { id: 'assets.read', method: 'GET', path: '/workspaces/:workspaceId/assets/:assetId', scopes: ['operator:read'] },\n { id: 'scorecard.get', method: 'GET', path: '/workspaces/:workspaceId/scorecard', scopes: ['operator:read'] },\n] as const satisfies ReadonlyArray<{ id: string; method: 'GET' | 'POST'; path: string; scopes: readonly OperatorScope[] }>\n\nexport type OperatorRouteId = typeof OPERATOR_ROUTES[number]['id']\n\nconst SEGMENT = /^[A-Za-z0-9_:.%-]{1,256}$/\n\n/** Match a pathname under the base path to its route and decoded parameters. */\nexport function matchOperatorRoute(\n method: string,\n pathname: string,\n basePath: string = OPERATOR_API_BASE_PATH,\n): { route: typeof OPERATOR_ROUTES[number]; params: Record<string, string> } | null {\n if (pathname !== basePath && !pathname.startsWith(`${basePath}/`)) return null\n const rest = pathname.slice(basePath.length).replace(/\\/$/, '')\n const actual = rest ? rest.split('/').slice(1) : []\n for (const route of OPERATOR_ROUTES) {\n if (route.method !== method) continue\n const pattern = route.path ? route.path.split('/').slice(1) : []\n if (pattern.length !== actual.length) continue\n const params: Record<string, string> = {}\n let matched = true\n for (let index = 0; index < pattern.length; index++) {\n const expected = pattern[index]!\n const segment = actual[index]!\n if (expected.startsWith(':')) {\n if (!SEGMENT.test(segment)) { matched = false; break }\n let decoded: string\n try { decoded = decodeURIComponent(segment) } catch { matched = false; break }\n if (!decoded || decoded.includes('/')) { matched = false; break }\n params[expected.slice(1)] = decoded\n } else if (expected !== segment) {\n matched = false\n break\n }\n }\n if (matched) return { route, params }\n }\n return null\n}\n","import { createApiKeyRequestAuth, type RequestApiKey } from '../platform/api-key-auth.js'\nimport {\n OPERATOR_API_BASE_PATH,\n OPERATOR_API_VERSION,\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 /** 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 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'])\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>): 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 return {\n turnId: body.turnId.toLowerCase(),\n content: body.content,\n ...(threadId === undefined ? {} : { threadId }),\n ...(title === undefined ? {} : { title }),\n ...(model === undefined ? {} : { model }),\n }\n}\n\nfunction capabilities<Identity>(adapter: OperatorAdapter<Identity>): OperatorCapability[] {\n const present: Array<[OperatorCapability, unknown]> = [\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 return present.filter(([, implemented]) => typeof implemented === 'function').map(([name]) => name)\n}\n\nfunction unsupported(): never {\n throw new OperatorError('operator.unsupported', 501, 'This app does not implement this operation')\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 turn.state === 'succeeded' || turn.state === 'failed' || 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 workspace = await adapter.authorizeWorkspace(ctx, workspaceId, route.id === 'turns.start' ? 'run' : 'read')\n if (!workspace) throw new OperatorError('operator.workspace_not_found', 404, 'Workspace not found')\n\n switch (route.id) {\n case 'workspaces.get':\n return json({ workspace })\n case 'turns.start': {\n const input = parseStartTurn(await readJsonBody(request))\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 const deadline = Date.now() + wait * 1000\n let turn = await adapter.getTurn(ctx, workspace, target)\n while (turn && !needsAttention(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 json({ turn })\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 { createApiKeyFetch } from '../web/api-key-fetch.js'\nimport {\n OPERATOR_API_BASE_PATH,\n type OperatorApproval,\n type OperatorAppInfo,\n type OperatorErrorBody,\n type OperatorFile,\n type OperatorFileEntry,\n type OperatorJournalEntry,\n type OperatorPrincipalInfo,\n type OperatorScorecard,\n type OperatorThread,\n type OperatorTurn,\n type OperatorWorkspace,\n type StartTurnInput,\n} from './contract.js'\n\nexport type OperatorResult<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; status: number; code: string; error: string; retryable: boolean }\n\nexport interface OperatorClientOptions {\n /** The app's origin, such as `https://gtm.tangle.tools`. */\n origin: string\n /** Resolve the key from trusted secret storage on each request; never from model output. */\n getApiKey(): string | Promise<string>\n fetchImpl?: typeof fetch\n allowHttpLoopback?: boolean\n basePath?: string\n}\n\nexport interface WaitForTurnOptions {\n /** Total time to follow the turn. */\n timeoutMs: number\n /** Server hold per request, in seconds; the server caps it. */\n waitSeconds?: number\n signal?: AbortSignal\n}\n\nexport interface OperatorClient {\n describe(): Promise<OperatorResult<{ app: OperatorAppInfo; principal: OperatorPrincipalInfo }>>\n listWorkspaces(): Promise<OperatorResult<OperatorWorkspace[]>>\n createWorkspace(input: { name: string }): Promise<OperatorResult<OperatorWorkspace>>\n getWorkspace(workspaceId: string): Promise<OperatorResult<OperatorWorkspace>>\n /** Omitting turnId generates one; retry with the returned turn's id. */\n startTurn(workspaceId: string, input: Omit<StartTurnInput, 'turnId'> & { turnId?: string }): Promise<OperatorResult<OperatorTurn>>\n getTurn(workspaceId: string, threadId: string, turnId: string, options?: { waitSeconds?: number; signal?: AbortSignal }): Promise<OperatorResult<OperatorTurn>>\n /** Follow until the turn settles, waits on a decision, or the timeout passes; the last read is returned. */\n waitForTurn(workspaceId: string, threadId: string, turnId: string, options: WaitForTurnOptions): Promise<OperatorResult<OperatorTurn>>\n listThreads(workspaceId: string, query?: { cursor?: string; limit?: number }): Promise<OperatorResult<{ threads: OperatorThread[]; nextCursor: string | null }>>\n getThread(workspaceId: string, threadId: string): Promise<OperatorResult<{ thread: OperatorThread; latestTurn: OperatorTurn | null }>>\n listApprovals(workspaceId: string): Promise<OperatorResult<OperatorApproval[]>>\n listJournal(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorJournalEntry[]>>\n listFiles(workspaceId: string, query?: { prefix?: string }): Promise<OperatorResult<OperatorFileEntry[]>>\n readFile(workspaceId: string, path: string): Promise<OperatorResult<OperatorFile>>\n /** The raw asset response; the caller reads and bounds its body. */\n readAsset(workspaceId: string, assetId: string, init?: { signal?: AbortSignal }): Promise<OperatorResult<Response>>\n getScorecard(workspaceId: string, query?: { days?: number }): Promise<OperatorResult<OperatorScorecard>>\n}\n\nfunction segment(value: string): string {\n return encodeURIComponent(value)\n}\n\nasync function failure(response: Response): Promise<OperatorResult<never>> {\n let body: Partial<OperatorErrorBody> = {}\n try { body = await response.json() as Partial<OperatorErrorBody> } catch { /* A non-JSON refusal keeps its status. */ }\n return {\n succeeded: false,\n status: response.status,\n code: typeof body.code === 'string' ? body.code : `http_${response.status}`,\n error: typeof body.error === 'string' ? body.error : `HTTP ${response.status}`,\n retryable: body.retryable === true || response.status === 429 || response.status >= 500,\n }\n}\n\nfunction transportFailure(error: unknown): OperatorResult<never> {\n const aborted = error instanceof Error && error.name === 'AbortError'\n return {\n succeeded: false,\n status: 0,\n code: aborted ? 'operator.aborted' : 'operator.transport_failed',\n // createApiKeyFetch never forwards transport diagnostics, which could carry the key.\n error: error instanceof Error ? error.message : 'Operator transport failed',\n retryable: !aborted,\n }\n}\n\nconst SETTLED = new Set(['succeeded', 'failed', 'input-required'])\n\n/** A typed client for one app's operator API. */\nexport function createOperatorClient(options: OperatorClientOptions): OperatorClient {\n const basePath = (options.basePath ?? OPERATOR_API_BASE_PATH).replace(/\\/$/, '')\n const request = createApiKeyFetch({\n origin: options.origin,\n getApiKey: options.getApiKey,\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n ...(options.allowHttpLoopback ? { allowHttpLoopback: true } : {}),\n })\n\n async function call<T>(\n path: string,\n pick: (body: Record<string, unknown>) => T,\n init: RequestInit = {},\n ): Promise<OperatorResult<T>> {\n let response: Response\n try {\n response = await request(`${basePath}${path}`, {\n ...init,\n headers: { accept: 'application/json', ...(init.body ? { 'content-type': 'application/json' } : {}) },\n })\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n try {\n return { succeeded: true, value: pick(await response.json() as Record<string, unknown>) }\n } catch {\n return { succeeded: false, status: response.status, code: 'operator.invalid_response', error: 'The response was not the expected JSON', retryable: true }\n }\n }\n\n const query = (params: Record<string, string | number | undefined>) => {\n const search = new URLSearchParams()\n for (const [name, value] of Object.entries(params)) if (value !== undefined && value !== '') search.set(name, String(value))\n const text = search.toString()\n return text ? `?${text}` : ''\n }\n\n const client: OperatorClient = {\n describe: () => call('', (body) => body as unknown as { app: OperatorAppInfo; principal: OperatorPrincipalInfo }),\n listWorkspaces: () => call('/workspaces', (body) => body.workspaces as OperatorWorkspace[]),\n createWorkspace: (input) => call('/workspaces', (body) => body.workspace as OperatorWorkspace, {\n method: 'POST', body: JSON.stringify({ name: input.name }),\n }),\n getWorkspace: (workspaceId) => call(`/workspaces/${segment(workspaceId)}`, (body) => body.workspace as OperatorWorkspace),\n startTurn: (workspaceId, input) => call(`/workspaces/${segment(workspaceId)}/turns`, (body) => body.turn as OperatorTurn, {\n method: 'POST', body: JSON.stringify({ ...input, turnId: input.turnId ?? crypto.randomUUID() }),\n }),\n getTurn: (workspaceId, threadId, turnId, opts = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}/turns/${segment(turnId)}${query({ wait: opts.waitSeconds })}`,\n (body) => body.turn as OperatorTurn,\n opts.signal ? { signal: opts.signal } : {},\n ),\n async waitForTurn(workspaceId, threadId, turnId, opts) {\n const deadline = Date.now() + opts.timeoutMs\n const waitSeconds = opts.waitSeconds ?? 25\n let last: OperatorResult<OperatorTurn> | null = null\n while (true) {\n const remaining = Math.floor((deadline - Date.now()) / 1000)\n const started = Date.now()\n last = await client.getTurn(workspaceId, threadId, turnId, {\n waitSeconds: Math.max(0, Math.min(waitSeconds, remaining)),\n ...(opts.signal ? { signal: opts.signal } : {}),\n })\n if (!last.succeeded) {\n if (!last.retryable || Date.now() >= deadline || opts.signal?.aborted) return last\n await new Promise((resolve) => setTimeout(resolve, Math.min(5_000, Math.max(0, deadline - Date.now()))))\n continue\n }\n if (SETTLED.has(last.value.state) || last.value.approvals.length > 0) return last\n if (Date.now() >= deadline || opts.signal?.aborted) return last\n // A server that does not hold the read still gets a bounded request rate.\n if (Date.now() - started < 1_000) {\n await new Promise((resolve) => setTimeout(resolve, Math.min(2_000, Math.max(0, deadline - Date.now()))))\n }\n }\n },\n listThreads: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/threads${query({ cursor: q.cursor, limit: q.limit })}`,\n (body) => ({ threads: body.threads as OperatorThread[], nextCursor: (body.nextCursor as string | null) ?? null }),\n ),\n getThread: (workspaceId, threadId) => call(\n `/workspaces/${segment(workspaceId)}/threads/${segment(threadId)}`,\n (body) => ({ thread: body.thread as OperatorThread, latestTurn: (body.latestTurn as OperatorTurn | null) ?? null }),\n ),\n listApprovals: (workspaceId) => call(`/workspaces/${segment(workspaceId)}/approvals`, (body) => body.approvals as OperatorApproval[]),\n listJournal: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/journal${query({ days: q.days })}`,\n (body) => body.entries as OperatorJournalEntry[],\n ),\n listFiles: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/files${query({ prefix: q.prefix })}`,\n (body) => body.files as OperatorFileEntry[],\n ),\n readFile: (workspaceId, path) => call(\n `/workspaces/${segment(workspaceId)}/file${query({ path })}`,\n (body) => body.file as OperatorFile,\n ),\n async readAsset(workspaceId, assetId, init = {}) {\n let response: Response\n try {\n response = await request(`${basePath}/workspaces/${segment(workspaceId)}/assets/${segment(assetId)}`, init.signal ? { signal: init.signal } : {})\n } catch (error) {\n return transportFailure(error)\n }\n if (!response.ok) return failure(response)\n return { succeeded: true, value: response }\n },\n getScorecard: (workspaceId, q = {}) => call(\n `/workspaces/${segment(workspaceId)}/scorecard${query({ days: q.days })}`,\n (body) => body.scorecard as OperatorScorecard,\n ),\n }\n return client\n}\n","import { 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'\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}\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\nexport interface ChatOperatorAdapterOptions<Identity> {\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 */\n runTurn(ctx: OperatorContext<Identity>, input: { workspaceId: string; threadId: string; turnId: string; content: string; model?: string }): Promise<Response>\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 /** A reply's failure; defaults to a `turn-failure` notice or an `error` part. */\n failureOf?(message: ChatOperatorMessage): { code?: string; message: string } | null\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 notice = 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 return { ...(typeof part.code === 'string' ? { code: part.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\nasync function sha256Hex(value: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\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 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 (state !== 'working') {\n const failure = (options.failureOf ?? defaultFailure)(assistant)\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' && !latest) {\n state = 'failed'\n turn.failure = { 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 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 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 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 response = await options.runTurn(ctx, {\n workspaceId: workspace.id, threadId, turnId: input.turnId, content: input.content,\n ...(input.model === undefined ? {} : { model: input.model }),\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 throw new OperatorError(\n typeof body.code === 'string' ? body.code : typeof nested.code === 'string' ? nested.code : `operator.chat_${response.status}`,\n response.status,\n typeof body.error === 'string' ? body.error : typeof nested.message === 'string' ? nested.message : 'The app refused the turn',\n response.status === 429 || response.status >= 500,\n )\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 return turnOf(ctx, workspace.id, target.threadId, target.turnId)\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":";;;;;;;;;;;;;AAOO,IAAM,uBAAuB;AAC7B,IAAM,yBAAyB;AAG/B,IAAM,kBAAkB;AAAA,EAC7B;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IACE,OAAO;AAAA,IACP,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AAAA,EACA;AAAA,IAC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O,GAAG;AACjD,UAAI,CAAC,SAAS,GAAI,OAAM,QAAQ,SAAS,QAAQ,SAAS,MAAM,SAAS,OAAO;AAChF,YAAM,SAAS,oBAAoB,SAAS,QAAQ,OAAO,SAAS,gBAAgB;AACpF,UAAI,OAAO,WAAW,GAAG;AACvB,cAAM,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":["segment","segment","text","workspace","text","failure"]}
@@ -22,10 +22,10 @@
22
22
  * - Which workspaces: the app's ordinary roles, through the operator
23
23
  * adapter's `authorizeWorkspace`. The key confers no workspace access.
24
24
  */
25
- import { type PlatformAgentKeyVerifier } from '../platform/agent-keys';
26
- import type { RequestApiKey } from '../platform/api-key-auth';
27
- import type { TangleSsoAccountStore } from '../platform/sso';
28
- import type { OperatorKeyStore } from './server';
25
+ import { type PlatformAgentKeyVerifier } from '../platform/agent-keys.js';
26
+ import type { RequestApiKey } from '../platform/api-key-auth.js';
27
+ import type { TangleSsoAccountStore } from '../platform/sso.js';
28
+ import type { OperatorKeyStore } from './server.js';
29
29
  export interface PlatformAgentKeyAccess<Identity> {
30
30
  verifier: PlatformAgentKeyVerifier;
31
31
  /** This app's Platform product id, e.g. `gtm-agent`. */
@@ -1,5 +1,5 @@
1
- import { type RequestApiKey } from '../platform/api-key-auth';
2
- import { type OperatorApproval, type OperatorFile, type OperatorFileEntry, type OperatorJournalEntry, type OperatorRouteId, type OperatorScorecard, type OperatorThread, type OperatorTurn, type OperatorWorkspace, type StartTurnInput } from './contract';
1
+ import { type RequestApiKey } from '../platform/api-key-auth.js';
2
+ import { type OperatorApproval, type OperatorFile, type OperatorFileEntry, type OperatorJournalEntry, type OperatorRouteId, type OperatorScorecard, type OperatorThread, type OperatorTurn, type OperatorWorkspace, type StartTurnInput } from './contract.js';
3
3
  /** The verified caller of one operator request. */
4
4
  export interface OperatorContext<Identity> {
5
5
  identity: Identity;
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Bill work an agent app runs for a Platform agent key to that key's one cap.
3
+ *
4
+ * An owner approves an agent key with one lifetime cap shared across every
5
+ * product. Work the app runs for the key must spend that cap, even when the
6
+ * owner already has their own credential in the app:
7
+ *
8
+ * - Model calls: `modelKey` delegates a Router key from the agent key that
9
+ * spends its cap directly ("spend-through"). Router refuses every call once
10
+ * the cap is spent, so a turn cannot run past it.
11
+ * - Work the app cannot route through the key, such as compute in a sandbox
12
+ * the owner's own credential pays for: `hold` reserves the work's maximum
13
+ * against the cap before it starts, and `consume` spends what it measured,
14
+ * up to the hold, without charging the owner's wallet again.
15
+ *
16
+ * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`, so an
17
+ * app refuses the work before it starts. Web-standard fetch only.
18
+ */
19
+ export interface AgentSpendRefusal {
20
+ status: 402 | 403 | 503;
21
+ code: string;
22
+ message: string;
23
+ }
24
+ export type AgentSpendOutcome<T> = {
25
+ succeeded: true;
26
+ value: T;
27
+ } | {
28
+ succeeded: false;
29
+ error: AgentSpendRefusal;
30
+ };
31
+ export interface PlatformAgentSpendOptions {
32
+ /** Platform origin, e.g. `https://id.tangle.tools`. */
33
+ platformUrl: string;
34
+ /** This app's Platform service name. */
35
+ serviceName: string;
36
+ serviceToken: string | (() => string);
37
+ /** The Platform product this app bills, e.g. `gtm-agent`. */
38
+ product: string;
39
+ fetch?: typeof fetch;
40
+ }
41
+ export interface PlatformAgentSpend {
42
+ /**
43
+ * A Router key whose charges spend the agent key's cap. `name` must start
44
+ * `auto:`; give each piece of work its own.
45
+ */
46
+ modelKey(input: {
47
+ agentKey: string;
48
+ name: string;
49
+ expiresAt: Date;
50
+ }): Promise<AgentSpendOutcome<{
51
+ key: string;
52
+ keyId: string | null;
53
+ }>>;
54
+ /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */
55
+ hold(input: {
56
+ keyId: string;
57
+ amountUsd: number;
58
+ referenceId: string;
59
+ expiresAt: Date;
60
+ }): Promise<AgentSpendOutcome<{
61
+ authorizationId: string;
62
+ }>>;
63
+ /** Spend what the work measured, at most the hold. A retry repeats the amount. */
64
+ consume(input: {
65
+ authorizationId: string;
66
+ amountUsd: number;
67
+ }): Promise<AgentSpendOutcome<{
68
+ consumedUsd: number;
69
+ }>>;
70
+ /** Return a hold whose work never ran. */
71
+ release(authorizationId: string): Promise<AgentSpendOutcome<null>>;
72
+ }
73
+ export declare function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend;
@@ -9,3 +9,4 @@ export * from './billing.js';
9
9
  export * from './guards.js';
10
10
  export * from './api-key-auth.js';
11
11
  export * from './agent-keys.js';
12
+ export * from './agent-spend.js';
@@ -463,6 +463,100 @@ function createTanglePlatformBillingClient(http, identity) {
463
463
  deduct: (input) => http.deduct(input)
464
464
  };
465
465
  }
466
+
467
+ // src/platform/agent-spend.ts
468
+ var REQUEST_TIMEOUT_MS = 1e4;
469
+ var budgetExhausted = {
470
+ status: 402,
471
+ code: "agent_key.budget_exhausted",
472
+ message: "The key has spent, or cannot cover, the cap its owner approved."
473
+ };
474
+ function refusal(status, code) {
475
+ if (code === "KEY_BUDGET_EXHAUSTED" || code === "KEY_BUDGET_EXCEEDED" || code === "PRODUCT_BUDGET_EXCEEDED") return budgetExhausted;
476
+ if (code === "INSUFFICIENT_BALANCE") {
477
+ return { status: 402, code: "agent_key.payment_required", message: "The key owner's Tangle account has no credit." };
478
+ }
479
+ if (code === "EMAIL_VERIFICATION_REQUIRED") {
480
+ return { status: 403, code: "agent_key.owner_unverified", message: "The key owner must verify their Tangle email." };
481
+ }
482
+ if (status >= 500 || status === 429 || code === "PLATFORM_BUSY") {
483
+ return { status: 503, code: "agent_key.spend_unavailable", message: "Platform could not record the spend; retry." };
484
+ }
485
+ return { status: 403, code: "agent_key.spend_refused", message: "Platform refused to bill this work to the key." };
486
+ }
487
+ function createPlatformAgentSpend(options) {
488
+ const fetchImpl = options.fetch ?? fetch;
489
+ const base = options.platformUrl.replace(/\/+$/, "");
490
+ async function call(path, body2) {
491
+ const token = typeof options.serviceToken === "function" ? options.serviceToken() : options.serviceToken;
492
+ try {
493
+ const response = await fetchImpl(`${base}${path}`, {
494
+ method: "POST",
495
+ headers: {
496
+ authorization: `Bearer ${token}`,
497
+ "x-service-name": options.serviceName,
498
+ "content-type": "application/json"
499
+ },
500
+ body: JSON.stringify(body2),
501
+ redirect: "manual",
502
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
503
+ });
504
+ return { status: response.status, body: await response.json().catch(() => ({})) };
505
+ } catch {
506
+ return null;
507
+ }
508
+ }
509
+ const unavailable = () => ({ succeeded: false, error: refusal(503, null) });
510
+ return {
511
+ async modelKey({ agentKey, name, expiresAt }) {
512
+ const result = await call("/v1/keys/delegate", {
513
+ sourceKey: agentKey,
514
+ name,
515
+ product: "router",
516
+ spendThrough: true,
517
+ expiresAt: expiresAt.toISOString()
518
+ });
519
+ if (!result) return unavailable();
520
+ const key = result.body.data?.key;
521
+ if (result.status !== 201 || typeof key !== "string") {
522
+ return { succeeded: false, error: refusal(result.status, result.body.error?.code) };
523
+ }
524
+ const keyId = result.body.data?.id;
525
+ return { succeeded: true, value: { key, keyId: typeof keyId === "string" ? keyId : null } };
526
+ },
527
+ async hold({ keyId, amountUsd, referenceId, expiresAt }) {
528
+ const result = await call("/v1/billing/authorizations", {
529
+ keyId,
530
+ amount: amountUsd,
531
+ type: "key_cap",
532
+ product: options.product,
533
+ referenceId,
534
+ expiresAt: expiresAt.toISOString()
535
+ });
536
+ if (!result) return unavailable();
537
+ const id = result.body.data?.id;
538
+ if (result.status !== 201 || typeof id !== "string") {
539
+ return { succeeded: false, error: refusal(result.status, result.body.error?.code) };
540
+ }
541
+ return { succeeded: true, value: { authorizationId: id } };
542
+ },
543
+ async consume({ authorizationId, amountUsd }) {
544
+ const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd });
545
+ if (!result) return unavailable();
546
+ const consumed = result.body.data?.consumedAmount;
547
+ if (result.status !== 200 || typeof consumed !== "number") {
548
+ return { succeeded: false, error: refusal(result.status, result.body.error?.code) };
549
+ }
550
+ return { succeeded: true, value: { consumedUsd: consumed } };
551
+ },
552
+ async release(authorizationId) {
553
+ const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {});
554
+ if (!result) return unavailable();
555
+ if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error?.code) };
556
+ return { succeeded: true, value: null };
557
+ }
558
+ };
559
+ }
466
560
  export {
467
561
  DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
468
562
  DEFAULT_TANGLE_TIER_POLICY,
@@ -480,6 +574,7 @@ export {
480
574
  createBetterAuthSessionCookieMinter,
481
575
  createHubSettingsRoutes,
482
576
  createPlatformAgentKeyVerifier,
577
+ createPlatformAgentSpend,
483
578
  createPlatformBillingHttp,
484
579
  createSignedSsoState,
485
580
  createTanglePlatformBillingClient,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,8BAA8B,CAAC,YAAY,SAAS,SAAS;AAG5D,SAAS,wBAAwB,WAAgB,cAAsB,UAA2B;AACvG,MAAI,UAAU,aAAa,gBAAgB,UAAU,K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MAAM,KAAK,gBAAgB,MAAM,GAAG;AAAA,IAChE,YAAY,OAAO,WAAW;AAC5B,YAAM,WAAW,MAAM,KAAK,WAAW,MAAM;AAC7C,aAAO,EAAE,SAAS,SAAS,SAAS,eAAe,SAAS,cAAc;AAAA,IAC5E;AAAA,IACA,mBAAmB,CAAC,WAAW,KAAK,kBAAkB,MAAM;AAAA,IAC5D,QAAQ,CAAC,UAAU,KAAK,OAAO,KAAK;AAAA,EACtC;AACF;","names":["body","body"]}
1
+ {"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/agent-spend.ts"],"sourcesContent":["/**\n * The OAuth return contract shared by the browser popup and the settings\n * server. The popup appends exactly these parameters to the host's callback\n * path; the server accepts a return URL only in that shape.\n */\nconst HUB_CONNECT_CALLBACK_PARAMS = ['provider', 'nonce', 'context'] as const\n\n/** True when `returnUrl` is the host's callback for `provider`, as the popup builds it. */\nexport function isHubConnectCallbackUrl(returnUrl: URL, callbackPath: string, provider: string): boolean {\n if (returnUrl.pathname !== callbackPath || returnUrl.hash) return false\n const keys = [...returnUrl.searchParams.keys()]\n if (keys.length !== HUB_CONNECT_CALLBACK_PARAMS.length) return false\n if (!HUB_CONNECT_CALLBACK_PARAMS.every((key) => returnUrl.searchParams.getAll(key).length === 1)) return false\n const opaque = (value: string | null) => !!value && value.length <= 128 && /^[A-Za-z0-9_-]+$/.test(value)\n return returnUrl.searchParams.get('provider') === provider\n && opaque(returnUrl.searchParams.get('nonce'))\n && opaque(returnUrl.searchParams.get('context'))\n}\n","/** Finite, application-authorized account settings over the existing Hub SDK. */\nimport { parseJsonObjectBody } from '../web/core'\nimport { isHubConnectCallbackUrl } from './hub-connect-callback'\n\n/** Non-secret API-key setup shapes supported by the Hub SDK. */\nexport type HubSettingsApiKeyMetadata =\n | { propertyId: string; currency?: string }\n | { listings: Array<{ id: string; pms: string }> }\n\n/** Browser OAuth setup, excluding CLI mode and identity/credential overrides. */\nexport interface HubSettingsOAuthInput {\n returnUrl: string\n connectionParameters?: Record<string, string>\n}\n\ntype PolicyDecision = 'allow' | 'ask' | 'deny'\n\n/**\n * Structural subset of the existing SDK, with no execution methods. Keeping\n * this structural avoids imposing a Hub SDK peer on existing platform imports.\n */\nexport interface HubSettingsClient {\n connections: {\n providers(): Promise<unknown>\n list(): Promise<unknown>\n start(provider: string, input: HubSettingsOAuthInput): Promise<unknown>\n connectApiKey(provider: string, apiKey: string, metadata?: HubSettingsApiKeyMetadata): Promise<unknown>\n revoke(connectionId: string): Promise<unknown>\n health(connectionId: string): Promise<unknown>\n }\n tools: {\n search(query: string, options: { provider: string; limit: number }): Promise<unknown>\n }\n permissions: {\n list(connectionId: string): Promise<unknown>\n set(input: { connectionId: string; actionPath: string; decision: PolicyDecision }): Promise<unknown>\n delete(input: { connectionId: string; actionPath: string }): Promise<unknown>\n }\n}\n\n/** Validated, exact intent. The provider API key is deliberately not copied here. */\nexport type HubSettingsOperation =\n | { readonly operation: 'providers.list' | 'connections.list'; readonly target: 'caller-account' }\n | { readonly operation: 'oauth.start'; readonly provider: string; readonly input: Readonly<HubSettingsOAuthInput> }\n | { readonly operation: 'api-key.connect'; readonly provider: string; readonly metadata?: HubSettingsApiKeyMetadata }\n | { readonly operation: 'connection.revoke' | 'connection.health' | 'policies.list'; readonly connectionId: string }\n | { readonly operation: 'provider.actions'; readonly provider: string; readonly query: string; readonly limit: number }\n | { readonly operation: 'policy.set'; readonly connectionId: string; readonly actionPath: string; readonly decision: PolicyDecision }\n | { readonly operation: 'policy.reset'; readonly connectionId: string; readonly actionPath: string }\n\n/** Server-derived application identity, not fields read from browser input. */\nexport interface HubSettingsPrincipal {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsGrant {\n readonly authorized: true\n readonly principal: HubSettingsPrincipal\n}\n\nexport interface HubSettingsClientBinding {\n readonly client: HubSettingsClient\n /** Reassert the identity against which the credential was actually resolved. */\n readonly principal: HubSettingsPrincipal\n /** Never env/admin credentials, another owner's key, or a brokered execution token. */\n readonly credentialSource: 'caller-account'\n}\n\nexport interface HubSettingsContext {\n /** Application-owned mount path, without a trailing slash. Default /api/hub/settings. */\n basePath?: string\n /**\n * Local path of the page that renders `HubConnectCallbackPage`. When set, an\n * OAuth start must return to exactly this path with the provider, nonce and\n * context that the integrations panel adds, and nothing else.\n */\n oauthCallbackPath?: string\n /**\n * Required on EVERY valid operation, including reads. Validate the current\n * session, CSRF protection, workspace role and exact target/decision here.\n * Return a denial Response or throw the app's auth Response to reject.\n * The body has been consumed; use the validated intent, not request.json().\n * OAuth success, connection ownership/policy, app consent and workspace\n * binding are separate facts. An execution grant is not a settings grant.\n */\n authorize(request: Request, operation: HubSettingsOperation): Promise<HubSettingsGrant | Response>\n /** Called only after authorization. Resolve the caller's linked account SDK client server-side. */\n resolveClient(principal: HubSettingsPrincipal): Promise<HubSettingsClientBinding>\n}\n\nexport interface HubSettingsRoutes {\n /** Exact method/path allowlist under basePath; never forwards request headers or arbitrary paths. */\n handle(request: Request): Promise<Response>\n}\n\nfunction json(value: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return Response.json(value, { status, headers: { 'Cache-Control': 'no-store', ...headers } })\n}\n\nfunction invalid(): never {\n // Do not reflect request values: API keys and OAuth parameters can be sensitive.\n throw json({ error: 'Invalid Hub settings request', code: 'HUB_INVALID_INPUT' }, 400)\n}\n\nfunction record(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) invalid()\n return value as Record<string, unknown>\n}\n\nfunction onlyKeys(value: Record<string, unknown>, allowed: readonly string[]): void {\n if (Object.keys(value).some((key) => !allowed.includes(key))) invalid()\n}\n\nfunction text(value: unknown, max = 256): string {\n if (typeof value !== 'string' || !value.trim() || value.length > max || /[\\u0000-\\u001f\\u007f]/.test(value)) invalid()\n return value\n}\n\nfunction identifier(value: unknown): string {\n const id = text(value, 128)\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(id)) invalid()\n return id\n}\n\nfunction action(value: unknown): string {\n const path = text(value)\n // An exact dotted action, never a provider wildcard, path, glob or pattern.\n if (!/^[A-Za-z0-9_-]+(?:\\.[A-Za-z0-9_-]+)+$/.test(path)) invalid()\n return path\n}\n\nfunction metadata(value: unknown): HubSettingsApiKeyMetadata {\n const input = record(value)\n if ('propertyId' in input) {\n onlyKeys(input, ['propertyId', 'currency'])\n return { propertyId: text(input.propertyId), ...(input.currency === undefined ? {} : { currency: text(input.currency) }) }\n }\n onlyKeys(input, ['listings'])\n if (!Array.isArray(input.listings) || input.listings.length === 0 || input.listings.length > 200) invalid()\n return { listings: input.listings.map((item) => {\n const listing = record(item)\n onlyKeys(listing, ['id', 'pms'])\n return { id: text(listing.id), pms: text(listing.pms) }\n }) }\n}\n\nfunction oauthInput(body: Record<string, unknown>, url: URL, provider: string, callbackPath: string | undefined): HubSettingsOAuthInput {\n onlyKeys(body, ['returnUrl', 'connectionParameters'])\n const returnUrl = text(body.returnUrl, 2048)\n let destination: URL\n try { destination = new URL(returnUrl) } catch { invalid() }\n if (!['https:', 'http:'].includes(destination.protocol) || destination.origin !== url.origin || destination.username || destination.password) invalid()\n if (callbackPath !== undefined && !isHubConnectCallbackUrl(destination, callbackPath, provider)) invalid()\n const input: HubSettingsOAuthInput = { returnUrl }\n if (body.connectionParameters !== undefined) {\n const parameters = record(body.connectionParameters)\n if (Object.keys(parameters).length > 20) invalid()\n input.connectionParameters = Object.fromEntries(Object.entries(parameters).map(([key, value]) => {\n identifier(key)\n // These are non-secret provider setup values, never Hub auth or identity overrides.\n if (/^(?:user|userid|owner|ownerid|workspace|workspaceid|team|teamid|principal|principalid|session|sessionid|authorization|headers|cookie|apikey|token|accesstoken|refreshtoken|clientsecret|secret|credentials?|appid|clientid)$/.test(key.replace(/[_-]/g, '').toLowerCase())) invalid()\n return [key, text(value, 1024)]\n }))\n }\n return input\n}\n\nfunction query(url: URL, allowed: readonly string[]): void {\n for (const key of url.searchParams.keys()) {\n if (!allowed.includes(key) || url.searchParams.getAll(key).length !== 1) invalid()\n }\n}\n\nasync function body(request: Request): Promise<Record<string, unknown>> {\n if ((request.headers.get('content-type')?.split(';')[0] ?? '').trim().toLowerCase() !== 'application/json') {\n throw json({ error: 'Expected application/json', code: 'HUB_INVALID_INPUT' }, 415)\n }\n const [value, error] = await parseJsonObjectBody(request, { maxBytes: 64 * 1024 })\n if (error) { error.headers.set('Cache-Control', 'no-store'); throw error }\n return value\n}\n\n/** Snapshot nested intent before application callbacks can observe it. */\nfunction freeze<T>(value: T): T {\n if (value !== null && typeof value === 'object') {\n for (const child of Object.values(value)) freeze(child)\n Object.freeze(value)\n }\n return value\n}\n\nfunction isPrincipal(value: unknown): value is HubSettingsPrincipal {\n if (value === null || typeof value !== 'object') return false\n const principal = value as Partial<HubSettingsPrincipal>\n return [principal.userId, principal.sessionId, principal.workspaceId].every((part) => typeof part === 'string' && part.trim().length > 0)\n}\n\ninterface Prepared {\n intent: HubSettingsOperation\n call(client: HubSettingsClient): Promise<unknown>\n}\n\nconst ROUTES = [\n { kind: 'providers', path: /^\\/providers$/, methods: ['GET'] },\n { kind: 'connections', path: /^\\/connections$/, methods: ['GET'] },\n { kind: 'oauth', path: /^\\/connections\\/([^/]+)\\/start$/, methods: ['POST'] },\n { kind: 'api-key', path: /^\\/connections\\/([^/]+)\\/connect-key$/, methods: ['POST'] },\n { kind: 'revoke', path: /^\\/connections\\/([^/]+)$/, methods: ['DELETE'] },\n { kind: 'health', path: /^\\/connections\\/([^/]+)\\/health$/, methods: ['POST'] },\n { kind: 'actions', path: /^\\/providers\\/([^/]+)\\/actions$/, methods: ['GET'] },\n { kind: 'policies', path: /^\\/policies$/, methods: ['GET', 'PUT', 'DELETE'] },\n] as const\n\nasync function prepare(request: Request, basePath: string, callbackPath: string | undefined): Promise<Prepared | Response> {\n const url = new URL(request.url)\n if (!url.pathname.startsWith(`${basePath}/`)) return json({ error: 'Not found' }, 404)\n const path = url.pathname.slice(basePath.length)\n const route = ROUTES.find((candidate) => candidate.path.test(path))\n if (!route) return json({ error: 'Not found' }, 404)\n if (!(route.methods as readonly string[]).includes(request.method)) {\n return json({ error: 'Method not allowed' }, 405, { Allow: route.methods.join(', ') })\n }\n const target = route.path.exec(path)?.[1]\n const isPolicyRead = route.kind === 'policies' && request.method === 'GET'\n const isActions = route.kind === 'actions'\n query(url, isPolicyRead ? ['connectionId'] : isActions ? ['query', 'limit'] : [])\n const hasJson = route.kind === 'oauth' || route.kind === 'api-key' || (route.kind === 'policies' && !isPolicyRead)\n if (!hasJson && request.body !== null) {\n // Workers may expose an empty body stream for a bodyless POST.\n const reader = request.body.getReader()\n let emptyChunks = 0\n try {\n for (;;) {\n const chunk = await reader.read()\n if (chunk.done) break\n if (chunk.value.byteLength > 0) invalid()\n // Limit empty chunks before authorization; bodyless requests reach EOF.\n if (++emptyChunks > 16) invalid()\n }\n } finally {\n await reader.cancel().catch(() => undefined)\n reader.releaseLock()\n }\n }\n\n if (route.kind === 'providers') return { intent: { operation: 'providers.list', target: 'caller-account' }, call: (hub) => hub.connections.providers() }\n if (route.kind === 'connections') return { intent: { operation: 'connections.list', target: 'caller-account' }, call: (hub) => hub.connections.list() }\n if (isPolicyRead) {\n const connectionId = identifier(url.searchParams.get('connectionId'))\n return { intent: { operation: 'policies.list', connectionId }, call: (hub) => hub.permissions.list(connectionId) }\n }\n if (route.kind === 'policies') {\n const input = await body(request)\n onlyKeys(input, request.method === 'PUT' ? ['connectionId', 'actionPath', 'decision'] : ['connectionId', 'actionPath'])\n const connectionId = identifier(input.connectionId)\n const actionPath = action(input.actionPath)\n if (request.method === 'DELETE') return { intent: { operation: 'policy.reset', connectionId, actionPath }, call: (hub) => hub.permissions.delete({ connectionId, actionPath }) }\n const decision = input.decision\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') invalid()\n return { intent: { operation: 'policy.set', connectionId, actionPath, decision }, call: (hub) => hub.permissions.set({ connectionId, actionPath, decision }) }\n }\n const id = identifier(target)\n if (isActions) {\n const search = url.searchParams.get('query') ?? ''\n if (search.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(search)) invalid()\n const rawLimit = url.searchParams.get('limit') ?? '200'\n if (!/^[1-9][0-9]*$/.test(rawLimit)) invalid()\n const limit = Number(rawLimit)\n if (limit > 200) invalid()\n return { intent: { operation: 'provider.actions', provider: id, query: search, limit }, call: (hub) => hub.tools.search(search, { provider: id, limit }) }\n }\n if (route.kind === 'oauth') {\n const input = freeze(oauthInput(await body(request), url, id, callbackPath))\n return { intent: { operation: 'oauth.start', provider: id, input }, call: (hub) => hub.connections.start(id, input) }\n }\n if (route.kind === 'api-key') {\n const input = await body(request)\n onlyKeys(input, ['apiKey', 'metadata'])\n const apiKey = text(input.apiKey, 16 * 1024)\n const setup = input.metadata === undefined ? undefined : freeze(metadata(input.metadata))\n return { intent: { operation: 'api-key.connect', provider: id, ...(setup === undefined ? {} : { metadata: setup }) }, call: (hub) => hub.connections.connectApiKey(id, apiKey, setup) }\n }\n if (route.kind === 'health') return { intent: { operation: 'connection.health', connectionId: id }, call: (hub) => hub.connections.health(id) }\n if (route.kind === 'revoke') return { intent: { operation: 'connection.revoke', connectionId: id }, call: (hub) => hub.connections.revoke(id) }\n return invalid()\n}\n\n/** Build the finite, application-authorized Hub settings server boundary. */\nexport function createHubSettingsRoutes(ctx: HubSettingsContext): HubSettingsRoutes {\n if (typeof ctx.authorize !== 'function' || typeof ctx.resolveClient !== 'function') {\n throw new TypeError('Hub settings requires authorize and resolveClient callbacks')\n }\n const basePath = ctx.basePath ?? '/api/hub/settings'\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath')\n const callbackPath = ctx.oauthCallbackPath\n if (callbackPath !== undefined && !/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(callbackPath)) throw new TypeError('Invalid Hub OAuth callback path')\n\n return { async handle(request) {\n let prepared: Prepared | Response\n try { prepared = await prepare(request, basePath, callbackPath) } catch (error) {\n if (error instanceof Response) return error\n throw error\n }\n if (prepared instanceof Response) return prepared\n // Auth throws intentionally propagate. No SDK/client lookup has occurred.\n const grant = await ctx.authorize(request, freeze(prepared.intent))\n if (grant instanceof Response) return grant\n if (grant?.authorized !== true || !isPrincipal(grant.principal)) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n const principal = Object.freeze({ userId: grant.principal.userId, sessionId: grant.principal.sessionId, workspaceId: grant.principal.workspaceId })\n try {\n const bound = await ctx.resolveClient(principal)\n if (bound?.credentialSource !== 'caller-account' || !isPrincipal(bound.principal) ||\n bound.principal.userId !== principal.userId || bound.principal.sessionId !== principal.sessionId || bound.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings caller binding mismatch', code: 'HUB_FORBIDDEN' }, 403)\n }\n // Client resolution can outlive a session or role grant. Recheck before the Hub effect.\n const renewed = await ctx.authorize(request, prepared.intent)\n if (renewed instanceof Response) return renewed\n if (renewed?.authorized !== true || !isPrincipal(renewed.principal) ||\n renewed.principal.userId !== principal.userId || renewed.principal.sessionId !== principal.sessionId || renewed.principal.workspaceId !== principal.workspaceId) {\n return json({ error: 'Hub settings authorization required', code: 'HUB_FORBIDDEN' }, 403)\n }\n return json(await prepared.call(bound.client))\n } catch (error) {\n // Structural detection survives SDK copies without a runtime peer import.\n if (error instanceof Error && error.name === 'HubSdkError' && typeof (error as { code?: unknown }).code === 'string') {\n const { code, status } = error as Error & { code: string; status?: number }\n const fallback = code === 'HUB_INVALID_INPUT' ? 400 : code === 'HUB_UNAUTHENTICATED' ? 401 : code === 'HUB_FORBIDDEN' ? 403 : 502\n const httpStatus = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599 ? status : fallback\n // Never echo upstream details/message: they can contain submitted credentials.\n return json({ error: 'Hub settings request failed', code }, httpStatus)\n }\n throw error\n }\n } }\n}\n","/**\n * Platform billing HTTP transport + tier state for apps on the shared\n * Tangle balance model (id.tangle.tools). Reads authenticate as the user via\n * their per-user platform key (the platform resolves the caller from the\n * key; service or impersonation headers on read routes are rejected). The\n * deduct write authenticates as the product service (`Bearer <serviceToken>`\n * + `X-Service-Name`) and names the target user in the body. Also provides a\n * fetch-backed implementation of the `/billing` module's\n * `PlatformBillingClient` seam (type-only import — no runtime coupling).\n */\n\nimport type { PlatformBillingClient, PlatformIdentity } from '../billing/index'\nimport { resolveTangleExecutionEnvironment } from '../runtime/model'\n\n/** Define available subscription tiers for the TanglePlan service */\nexport type TanglePlanTier = 'free' | 'pro' | 'enterprise'\n\n/** 'pro' | 'enterprise' pass through; anything else (null, unknown) → 'free'. */\nexport function normalizeTanglePlanTier(plan: string | null | undefined): TanglePlanTier {\n return plan === 'pro' || plan === 'enterprise' ? plan : 'free'\n}\n\n/** Represent platform billing HTTP errors with status code and detailed message */\nexport class PlatformBillingHttpError extends Error {\n constructor(\n readonly status: number,\n detail: string,\n ) {\n super(`Platform request failed (${status}): ${detail}`)\n this.name = 'PlatformBillingHttpError'\n }\n}\n\n/** Structural guard (name + numeric status) — robust across module instances. */\nexport function isPlatformBillingHttpError(error: unknown): error is PlatformBillingHttpError {\n return (\n error instanceof Error &&\n error.name === 'PlatformBillingHttpError' &&\n typeof (error as { status?: unknown }).status === 'number'\n )\n}\n\n/** Define HTTP options for platform billing including base URL, service token, product slug, fetch implementation, and timeout */\nexport interface PlatformBillingHttpOptions {\n /** Platform root, e.g. https://id.tangle.tools (trailing slashes stripped). */\n baseUrl: string\n /** Used only by `deduct()`; resolved lazily so reads never require it.\n * Throws at call time when empty. */\n serviceToken: string | (() => string)\n /** Product slug — the `X-Service-Name` header and the deduct `product` field. */\n productSlug: string\n fetchImpl?: typeof fetch\n /** Default 10 000. */\n timeoutMs?: number\n}\n\n/** Describe subscription tier and status information for a platform user */\nexport interface PlatformSubscriptionInfo {\n tier: TanglePlanTier\n status: string | null\n}\n\n/** Describe the platform balance and lifetime spending with an optional update timestamp */\nexport interface PlatformBalanceSnapshot {\n balance: number\n lifetimeSpent: number\n updatedAt?: string\n}\n\n/** Describe a product's usage and spending metrics on the platform */\nexport interface PlatformUsageProductRow {\n product: string | null\n totalSpent: number\n count: number\n}\n\n/** Lifecycle of a per-product seat subscription, mirroring the Stripe states\n * the platform persists. 'none' = the user has never held this seat. */\nexport type SeatStatus = 'none' | 'active' | 'trialing' | 'past_due' | 'canceled'\n\n/** Price and included shared-wallet credit for one seat billing period. */\nexport interface ProductSeatOfferPeriod {\n priceCents: number\n includedCreditsCents: number\n}\n\n/** Commercial terms returned by the platform's product catalog. Products use\n * this exact object for display instead of duplicating prices in UI copy. */\nexport interface ProductSeatOffer {\n currency: 'usd'\n interval: 'month'\n recurring: ProductSeatOfferPeriod\n introductory: ProductSeatOfferPeriod | null\n}\n\n/**\n * Per-product entitlement snapshot from the platform — the single read that\n * tells a product whether to show its workspace or the seat paywall. Shape\n * matches `GET /v1/billing/product-entitlement?product=<id>`.\n *\n * `hasSeat` is computed platform-side from the raw seat row.\n * It is true for an active or trialing seat whose period has not lapsed.\n * `onFreeTier` remains in the wire shape for compatibility, but this client\n * always returns false and never uses it for access.\n */\nexport interface ProductEntitlement {\n seatStatus: SeatStatus\n /** ISO timestamp the active seat's paid period runs until; null when none. */\n currentPeriodEnd: string | null\n /** Cumulative inference spend across the whole suite, in dollars. */\n lifetimeSpentUsd: number\n hasSeat: boolean\n /** Platform access decision, including funded balance and identity policy. */\n paidAccess?: boolean\n onFreeTier: boolean\n /** Present when the platform exposes catalog-backed commercial terms. */\n offer?: ProductSeatOffer\n}\n\nfunction productSeatOffer(value: unknown): ProductSeatOffer | undefined {\n if (!value || typeof value !== 'object') return undefined\n const candidate = value as Record<string, unknown>\n if (candidate.currency !== 'usd' || candidate.interval !== 'month') return undefined\n\n const period = (input: unknown, allowZeroPrice: boolean): ProductSeatOfferPeriod | undefined => {\n if (!input || typeof input !== 'object') return undefined\n const data = input as Record<string, unknown>\n const priceCents = data.priceCents\n const includedCreditsCents = data.includedCreditsCents\n if (\n typeof priceCents !== 'number' ||\n !Number.isSafeInteger(priceCents) ||\n (allowZeroPrice ? priceCents < 0 : priceCents <= 0) ||\n typeof includedCreditsCents !== 'number' ||\n !Number.isSafeInteger(includedCreditsCents) ||\n includedCreditsCents < 0\n ) {\n return undefined\n }\n return { priceCents, includedCreditsCents }\n }\n\n const recurring = period(candidate.recurring, false)\n const introductory =\n candidate.introductory === null\n ? null\n : period(candidate.introductory, true)\n if (!recurring || introductory === undefined) return undefined\n return {\n currency: 'usd',\n interval: 'month',\n recurring,\n introductory,\n }\n}\n\n/** Define methods to interact with platform billing endpoints using user or service authentication */\nexport interface PlatformBillingHttp {\n /** GET /v1/plans/current (user bearer). */\n getSubscription(userApiKey: string): Promise<PlatformSubscriptionInfo>\n /** GET /v1/billing/balance (user bearer). */\n getBalance(userApiKey: string): Promise<PlatformBalanceSnapshot>\n /** GET /v1/billing/usage (user bearer). */\n getUsageByProduct(userApiKey: string): Promise<PlatformUsageProductRow[]>\n /** GET /v1/billing/product-entitlement?product=<id> (user bearer). */\n getProductEntitlement(userApiKey: string, productId: string): Promise<ProductEntitlement>\n /** POST /v1/billing/deduct (service token). */\n deduct(input: {\n platformUserId: string\n amountUsd: number\n type: string\n description: string\n referenceId: string\n }): Promise<void>\n /** Absolute URL of the platform's billing-management surface. */\n billingUrl(): string\n /** Absolute URL of the catalog-backed seat checkout for `productId`. */\n seatCheckoutUrl(productId: string): string\n}\n\n/** Create a PlatformBillingHttp instance configured with given options and default behaviors */\nexport function createPlatformBillingHttp(opts: PlatformBillingHttpOptions): PlatformBillingHttp {\n const baseUrl = opts.baseUrl.replace(/\\/+$/, '')\n if (!baseUrl) throw new Error('PlatformBillingHttpOptions.baseUrl is required')\n if (!opts.productSlug) throw new Error('PlatformBillingHttpOptions.productSlug is required')\n const fetchImpl = opts.fetchImpl ?? fetch\n const timeoutMs = opts.timeoutMs ?? 10_000\n\n function resolveServiceToken(): string {\n const token = typeof opts.serviceToken === 'function' ? opts.serviceToken() : opts.serviceToken\n if (!token) throw new Error('A platform service token is required for deduct')\n return token\n }\n\n async function request<T>(path: string, init: RequestInit, headers: Headers): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n ...init,\n headers,\n signal: AbortSignal.timeout(timeoutMs),\n })\n if (!res.ok) {\n const body = (await res.json().catch(() => null)) as { error?: { message?: string } } | null\n throw new PlatformBillingHttpError(res.status, body?.error?.message ?? res.statusText)\n }\n return res.json() as Promise<T>\n }\n\n function userRead<T>(userApiKey: string, path: string): Promise<T> {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${userApiKey}`)\n return request<T>(path, {}, headers)\n }\n\n return {\n async getSubscription(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { subscription?: { plan?: string | null; status?: string | null } | null }\n }>(userApiKey, '/v1/plans/current')\n const sub = body.data?.subscription ?? null\n return { tier: normalizeTanglePlanTier(sub?.plan), status: sub?.status ?? null }\n },\n\n async getBalance(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: { balance?: number; lifetimeSpent?: number; updatedAt?: string }\n }>(userApiKey, '/v1/billing/balance')\n return {\n balance: body.data?.balance ?? 0,\n lifetimeSpent: body.data?.lifetimeSpent ?? 0,\n updatedAt: body.data?.updatedAt,\n }\n },\n\n async getUsageByProduct(userApiKey) {\n const body = await userRead<{\n success: boolean\n data?: Array<{ product?: string | null; totalSpent?: number; count?: number }>\n }>(userApiKey, '/v1/billing/usage')\n return (body.data ?? []).map((row) => ({\n product: row.product ?? null,\n totalSpent: row.totalSpent ?? 0,\n count: row.count ?? 0,\n }))\n },\n\n async getProductEntitlement(userApiKey, productId) {\n const slug = encodeURIComponent(productId)\n const body = await userRead<{\n success: boolean\n data?: {\n seatStatus?: SeatStatus | null\n currentPeriodEnd?: string | null\n lifetimeSpentUsd?: number | null\n hasSeat?: boolean | null\n paidAccess?: unknown\n onFreeTier?: boolean | null\n offer?: unknown\n }\n }>(userApiKey, `/v1/billing/product-entitlement?product=${slug}`)\n const data = body.data ?? {}\n const hasSeat = data.hasSeat === true\n const offer = productSeatOffer(data.offer)\n return {\n seatStatus: data.seatStatus ?? 'none',\n currentPeriodEnd: data.currentPeriodEnd ?? null,\n lifetimeSpentUsd: data.lifetimeSpentUsd ?? 0,\n hasSeat,\n ...('paidAccess' in data ? { paidAccess: data.paidAccess === true } : {}),\n // Product-funded free access is retired. Ignore stale server signals.\n onFreeTier: false,\n ...(offer ? { offer } : {}),\n }\n },\n\n async deduct(input) {\n const headers = new Headers()\n headers.set('Authorization', `Bearer ${resolveServiceToken()}`)\n headers.set('X-Service-Name', opts.productSlug)\n headers.set('Content-Type', 'application/json')\n await request('/v1/billing/deduct', {\n method: 'POST',\n body: JSON.stringify({\n userId: input.platformUserId,\n amount: input.amountUsd,\n type: input.type,\n product: opts.productSlug,\n description: input.description,\n referenceId: input.referenceId,\n }),\n }, headers)\n },\n\n billingUrl() {\n return `${baseUrl}/app/billing`\n },\n\n seatCheckoutUrl(productId) {\n return seatCheckoutUrl(baseUrl, productId)\n },\n }\n}\n\n/**\n * Platform Stripe checkout URL for a product's catalog-backed seat. The\n * platform resolves the product-specific price and introductory offer from the\n * `product` query param. Mirrors the `billingUrl()` shape — a deterministic\n * platform-rooted URL with no client-side pricing decisions.\n */\nexport function seatCheckoutUrl(baseUrl: string, productId: string): string {\n const root = baseUrl.replace(/\\/+$/, '')\n return `${root}/app/billing/seat/checkout?product=${encodeURIComponent(productId)}`\n}\n\n// ── Tier policy + composed state ────────────────────────────────────────────\n\n/** Define policy settings for concurrency and overage allowance in a tangle tier */\nexport interface TangleTierPolicy {\n concurrency: number\n overageAllowed: boolean\n}\n\n/** Define default concurrency and overage policies for each TanglePlanTier level */\nexport const DEFAULT_TANGLE_TIER_POLICY: Record<TanglePlanTier, TangleTierPolicy> = {\n free: { concurrency: 1, overageAllowed: false },\n pro: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n enterprise: { concurrency: Number.POSITIVE_INFINITY, overageAllowed: true },\n}\n\n/** Describe the state of a Tangle plan tier including subscription, balance, spending, and concurrency details */\nexport interface TangleTierState {\n tier: TanglePlanTier\n subscriptionStatus: string | null\n remainingBalanceUsd: number\n lifetimeSpentUsd: number\n concurrency: number\n overageAllowed: boolean\n}\n\n/**\n * Read subscription + balance and project them onto the tier policy. A\n * null/absent key fails CLOSED (free tier, zero balance) — a billable run is\n * never started against an unknown balance. Platform errors throw; callers\n * on the billable path choose their posture explicitly.\n */\nexport async function readTangleTierState(\n http: PlatformBillingHttp,\n userApiKey: string | null | undefined,\n policy: Record<TanglePlanTier, TangleTierPolicy> = DEFAULT_TANGLE_TIER_POLICY,\n): Promise<TangleTierState> {\n if (!userApiKey) {\n return {\n tier: 'free',\n subscriptionStatus: null,\n remainingBalanceUsd: 0,\n lifetimeSpentUsd: 0,\n ...policy.free,\n }\n }\n const [subscription, balance] = await Promise.all([\n http.getSubscription(userApiKey),\n http.getBalance(userApiKey),\n ])\n return {\n tier: subscription.tier,\n subscriptionStatus: subscription.status,\n remainingBalanceUsd: balance.balance,\n lifetimeSpentUsd: balance.lifetimeSpent,\n ...policy[subscription.tier],\n }\n}\n\n// ── Per-product seat entitlement ────────────────────────────────────────────\n\n/** Product-funded free inference spend is disabled. */\nexport const FREE_TIER_SPEND_CAP_USD = 0\n\n/**\n * Default name of the per-app feature flag that controls seat billing.\n * Explicit values override the environment default.\n */\nexport const DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR = 'SEAT_BILLING_ENABLED'\n\n/** Define options to configure seat billing flag environment variables and override flag name */\nexport interface SeatBillingFlagOptions {\n env?: Record<string, string | undefined>\n /** Override the flag name; default {@link DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR}. */\n flagEnvVar?: string\n}\n\n/**\n * An explicit flag controls seat billing in every environment.\n * Without a flag, known development and test environments default to OFF.\n * Deployed and unknown environments default to ON.\n */\nexport function isSeatBillingEnabled(opts: SeatBillingFlagOptions = {}): boolean {\n const env =\n opts.env ??\n (typeof process !== 'undefined' ? (process.env as Record<string, string | undefined>) : undefined)\n if (!env) return true\n const flag = env[opts.flagEnvVar ?? DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR]?.trim().toLowerCase()\n if (flag) return !['false', '0', 'off', 'disabled', 'no'].includes(flag)\n const environment = resolveTangleExecutionEnvironment(env)\n return environment !== 'development' && environment !== 'test'\n}\n\n/**\n * Read a user's entitlement for one product.\n * An absent key or disabled flag returns no access.\n * Transport failures propagate so the product can return a retryable error.\n *\n * @param flag — pass {@link isSeatBillingEnabled} (or your own boolean) so the\n * product owns when the gate engages. When false, no network call is made.\n */\nexport async function getProductEntitlement(\n http: Pick<PlatformBillingHttp, 'getProductEntitlement'>,\n userApiKey: string | null | undefined,\n productId: string,\n flag = true,\n): Promise<ProductEntitlement> {\n if (!flag) return unavailableEntitlement()\n if (!userApiKey) return unavailableEntitlement()\n return http.getProductEntitlement(userApiKey, productId)\n}\n\nfunction unavailableEntitlement(): ProductEntitlement {\n return {\n seatStatus: 'none',\n currentPeriodEnd: null,\n lifetimeSpentUsd: 0,\n hasSeat: false,\n onFreeTier: false,\n }\n}\n\n/** Honor platform access policy; older endpoints provide only seat authority. */\nexport function isProductEntitled(ent: ProductEntitlement): boolean {\n return ent.paidAccess === undefined ? ent.hasSeat === true : ent.paidAccess === true\n}\n\n// ── Bridge onto the /billing seam ───────────────────────────────────────────\n\n/** Define a contract for resolving platform identities based on user identifiers */\nexport interface PlatformIdentityStore {\n resolveIdentity(userId: string): Promise<PlatformIdentity | null>\n}\n\n/** Concrete fetch-backed `PlatformBillingClient<TanglePlanTier>` for\n * `createPlatformBalanceManager` (from `/billing`). */\nexport function createTanglePlatformBillingClient(\n http: PlatformBillingHttp,\n identity: PlatformIdentityStore,\n): PlatformBillingClient<TanglePlanTier> {\n return {\n resolveIdentity: (userId) => identity.resolveIdentity(userId),\n getPlan: async (apiKey) => (await http.getSubscription(apiKey)).tier,\n getBalance: async (apiKey) => {\n const snapshot = await http.getBalance(apiKey)\n return { balance: snapshot.balance, lifetimeSpent: snapshot.lifetimeSpent }\n },\n getUsageByProduct: (apiKey) => http.getUsageByProduct(apiKey),\n deduct: (input) => http.deduct(input),\n }\n}\n","/**\n * Bill work an agent app runs for a Platform agent key to that key's one cap.\n *\n * An owner approves an agent key with one lifetime cap shared across every\n * product. Work the app runs for the key must spend that cap, even when the\n * owner already has their own credential in the app:\n *\n * - Model calls: `modelKey` delegates a Router key from the agent key that\n * spends its cap directly (\"spend-through\"). Router refuses every call once\n * the cap is spent, so a turn cannot run past it.\n * - Work the app cannot route through the key, such as compute in a sandbox\n * the owner's own credential pays for: `hold` reserves the work's maximum\n * against the cap before it starts, and `consume` spends what it measured,\n * up to the hold, without charging the owner's wallet again.\n *\n * A spent or insufficient cap answers 402 `agent_key.budget_exhausted`, so an\n * app refuses the work before it starts. Web-standard fetch only.\n */\n\nexport interface AgentSpendRefusal {\n status: 402 | 403 | 503\n code: string\n message: string\n}\n\nexport type AgentSpendOutcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: AgentSpendRefusal }\n\nexport interface PlatformAgentSpendOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name. */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app bills, e.g. `gtm-agent`. */\n product: string\n fetch?: typeof fetch\n}\n\nexport interface PlatformAgentSpend {\n /**\n * A Router key whose charges spend the agent key's cap. `name` must start\n * `auto:`; give each piece of work its own.\n */\n modelKey(input: { agentKey: string; name: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ key: string; keyId: string | null }>>\n /** Reserve up to `amountUsd` of the agent key's cap for work billed elsewhere. */\n hold(input: { keyId: string; amountUsd: number; referenceId: string; expiresAt: Date }): Promise<AgentSpendOutcome<{ authorizationId: string }>>\n /** Spend what the work measured, at most the hold. A retry repeats the amount. */\n consume(input: { authorizationId: string; amountUsd: number }): Promise<AgentSpendOutcome<{ consumedUsd: number }>>\n /** Return a hold whose work never ran. */\n release(authorizationId: string): Promise<AgentSpendOutcome<null>>\n}\n\nconst REQUEST_TIMEOUT_MS = 10_000\n\nconst budgetExhausted: AgentSpendRefusal = {\n status: 402,\n code: 'agent_key.budget_exhausted',\n message: 'The key has spent, or cannot cover, the cap its owner approved.',\n}\n\nfunction refusal(status: number, code: unknown): AgentSpendRefusal {\n if (code === 'KEY_BUDGET_EXHAUSTED' || code === 'KEY_BUDGET_EXCEEDED' || code === 'PRODUCT_BUDGET_EXCEEDED') return budgetExhausted\n if (code === 'INSUFFICIENT_BALANCE') {\n return { status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit.\" }\n }\n if (code === 'EMAIL_VERIFICATION_REQUIRED') {\n return { status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n if (status >= 500 || status === 429 || code === 'PLATFORM_BUSY') {\n return { status: 503, code: 'agent_key.spend_unavailable', message: 'Platform could not record the spend; retry.' }\n }\n return { status: 403, code: 'agent_key.spend_refused', message: 'Platform refused to bill this work to the key.' }\n}\n\ninterface PlatformBody {\n success?: unknown\n data?: { key?: unknown; id?: unknown; consumedAmount?: unknown }\n error?: { code?: unknown }\n}\n\nexport function createPlatformAgentSpend(options: PlatformAgentSpendOptions): PlatformAgentSpend {\n const fetchImpl = options.fetch ?? fetch\n const base = options.platformUrl.replace(/\\/+$/, '')\n\n async function call(path: string, body: unknown): Promise<{ status: number; body: PlatformBody } | null> {\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n try {\n const response = await fetchImpl(`${base}${path}`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify(body),\n redirect: 'manual',\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n })\n return { status: response.status, body: (await response.json().catch(() => ({}))) as PlatformBody }\n } catch {\n return null\n }\n }\n\n const unavailable = (): { succeeded: false; error: AgentSpendRefusal } => ({ succeeded: false, error: refusal(503, null) })\n\n return {\n async modelKey({ agentKey, name, expiresAt }) {\n const result = await call('/v1/keys/delegate', {\n sourceKey: agentKey, name, product: 'router', spendThrough: true, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const key = result.body.data?.key\n if (result.status !== 201 || typeof key !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n const keyId = result.body.data?.id\n return { succeeded: true, value: { key, keyId: typeof keyId === 'string' ? keyId : null } }\n },\n async hold({ keyId, amountUsd, referenceId, expiresAt }) {\n const result = await call('/v1/billing/authorizations', {\n keyId, amount: amountUsd, type: 'key_cap', product: options.product, referenceId, expiresAt: expiresAt.toISOString(),\n })\n if (!result) return unavailable()\n const id = result.body.data?.id\n if (result.status !== 201 || typeof id !== 'string') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { authorizationId: id } }\n },\n async consume({ authorizationId, amountUsd }) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/consume`, { amount: amountUsd })\n if (!result) return unavailable()\n const consumed = result.body.data?.consumedAmount\n if (result.status !== 200 || typeof consumed !== 'number') {\n return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n }\n return { succeeded: true, value: { consumedUsd: consumed } }\n },\n async release(authorizationId) {\n const result = await call(`/v1/billing/authorizations/${encodeURIComponent(authorizationId)}/release`, {})\n if (!result) return unavailable()\n if (result.status !== 200) return { succeeded: false, error: refusal(result.status, result.body.error?.code) }\n return { succeeded: true, value: null }\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,8BAA8B,CAAC,YAAY,SAAS,SAAS;AAG5D,SAAS,wBAAwB,WAAgB,cAAsB,UAA2B;AACvG,MAAI,UAAU,aAAa,gBAAgB,UAAU,KAAM,QAAO;AAClE,QAAM,OAAO,CAAC,GAAG,UAAU,aAAa,KAAK,CAAC;AAC9C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,OAAO,WAAW,OAAO,OAAO,OAAO,UAAU;AACnD,eAAO,EAAE,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE;AAAA,MACpF;AACA,aAAO,EAAE,WAAW,MAAM,OAAO,EAAE,iBAAiB,GAAG,EAAE;AAAA,IAC3D;AAAA,IACA,MAAM,QAAQ,EAAE,iBAAiB,UAAU,GAAG;AAC5C,YAAM,SAAS,MAAM,KAAK,8BAA8B,mBAAmB,eAAe,CAAC,YAAY,EAAE,QAAQ,UAAU,CAAC;AAC5H,UAAI,CAAC,OAAQ,QAAO,YAAY;AAChC,YAAM,WAAW,OAAO,KAAK,MAAM;AACnC,UAAI,OAAO,WAAW,OAAO,OAAO,aAAa,UAAU;AACzD,eAAO,EAAE,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE;AAAA,MACpF;AACA,aAAO,EAAE,WAAW,MAAM,OAAO,EAAE,aAAa,SAAS,EAAE;AAAA,IAC7D;AAAA,IACA,MAAM,QAAQ,iBAAiB;AAC7B,YAAM,SAAS,MAAM,KAAK,8BAA8B,mBAAmB,eAAe,CAAC,YAAY,CAAC,CAAC;AACzG,UAAI,CAAC,OAAQ,QAAO,YAAY;AAChC,UAAI,OAAO,WAAW,IAAK,QAAO,EAAE,WAAW,OAAO,OAAO,QAAQ,OAAO,QAAQ,OAAO,KAAK,OAAO,IAAI,EAAE;AAC7G,aAAO,EAAE,WAAW,MAAM,OAAO,KAAK;AAAA,IACxC;AAAA,EACF;AACF;","names":["body","body","body"]}
@@ -102,8 +102,8 @@ interface GatewayConsultationContext {
102
102
  /** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */
103
103
  export declare function createPublicConsultation(options: PublicConsultationOptions): {
104
104
  authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer): Promise<{
105
- allow: true;
106
105
  reason?: undefined;
106
+ allow: true;
107
107
  code?: undefined;
108
108
  } | {
109
109
  allow: false;
@@ -121,9 +121,9 @@ export declare function createPublicConsultation(options: PublicConsultationOpti
121
121
  executionBudget?: ChatTurnExecutionLimits;
122
122
  maxOutputTokens?: number;
123
123
  }) => Promise<{
124
+ start?: undefined;
124
125
  status: 'unsupported';
125
126
  reason: string;
126
- start?: undefined;
127
127
  } | {
128
128
  reason?: undefined;
129
129
  status: 'prepared';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.60.18",
3
+ "version": "0.60.20",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [