@tangle-network/agent-app 0.60.5 → 0.60.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/{DesignCanvas-OWE67ZX3.js → DesignCanvas-TW45DTK7.js} +3 -2
  2. package/dist/{DesignCanvasEditor-4FPLJ3YJ.js → DesignCanvasEditor-3DL3PF6P.js} +3 -2
  3. package/dist/app-auth/index.js +2 -1
  4. package/dist/app-auth/index.js.map +1 -1
  5. package/dist/assistant/index.js +1 -1
  6. package/dist/chat-routes/index.js +3 -2
  7. package/dist/chat-routes/index.js.map +1 -1
  8. package/dist/{chunk-4NBOPJHX.js → chunk-2BAASFJS.js} +1 -1
  9. package/dist/{chunk-4NBOPJHX.js.map → chunk-2BAASFJS.js.map} +1 -1
  10. package/dist/{chunk-DWUSVC3U.js → chunk-CN5HNTU6.js} +3 -3
  11. package/dist/chunk-MLDKEEFQ.js +48 -0
  12. package/dist/chunk-MLDKEEFQ.js.map +1 -0
  13. package/dist/chunk-RN4WPTBH.js +62 -0
  14. package/dist/chunk-RN4WPTBH.js.map +1 -0
  15. package/dist/{chunk-YNSPVKMS.js → chunk-UTAIRVOK.js} +1 -60
  16. package/dist/chunk-UTAIRVOK.js.map +1 -0
  17. package/dist/design-canvas/index.js +2 -1
  18. package/dist/design-canvas/index.js.map +1 -1
  19. package/dist/design-canvas-react/engine.js +2 -1
  20. package/dist/design-canvas-react/index.js +6 -5
  21. package/dist/design-canvas-react/index.js.map +1 -1
  22. package/dist/design-canvas-react/lazy.js +1 -1
  23. package/dist/operator/client.d.ts +76 -0
  24. package/dist/operator/contract.d.ts +255 -0
  25. package/dist/operator/index.d.ts +8 -0
  26. package/dist/operator/index.js +533 -0
  27. package/dist/operator/index.js.map +1 -0
  28. package/dist/operator/server.d.ts +101 -0
  29. package/dist/platform/index.js +5 -45
  30. package/dist/platform/index.js.map +1 -1
  31. package/dist/public-consultation/index.js +2 -1
  32. package/dist/public-consultation/index.js.map +1 -1
  33. package/dist/sandbox/index.js +1 -1
  34. package/dist/sandbox/recovery.d.ts +8 -3
  35. package/dist/sequences/index.js +2 -1
  36. package/dist/sequences/index.js.map +1 -1
  37. package/dist/web/index.js +4 -2
  38. package/dist/web-react/index.js +4 -4
  39. package/package.json +6 -1
  40. package/dist/chunk-YNSPVKMS.js.map +0 -1
  41. /package/dist/{DesignCanvas-OWE67ZX3.js.map → DesignCanvas-TW45DTK7.js.map} +0 -0
  42. /package/dist/{DesignCanvasEditor-4FPLJ3YJ.js.map → DesignCanvasEditor-3DL3PF6P.js.map} +0 -0
  43. /package/dist/{chunk-DWUSVC3U.js.map → chunk-CN5HNTU6.js.map} +0 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/operator/contract.ts","../../src/operator/server.ts","../../src/operator/client.ts"],"sourcesContent":["/**\n * The standard operator API contract every agent app mounts at\n * `/api/operator/v1`. An outside agent (a Claude Code or Codex session, or\n * another app's agent) holds one scoped key per app and drives workspaces\n * through these routes; the app supplies only storage and execution.\n */\n\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"],"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,IACE,OAAO;AAAA,IACP,UAAU,CAAC,eAAe;AAAA,IAC1B,OAAO;AAAA,IACP,aAAa;AAAA,EACf;AACF;AAIO,IAAM,sBAAgD,gBAAgB,IAAI,CAAC,EAAE,MAAM,MAAM,KAAK;AAE9F,IAAM,8BAA2E,OAAO;AAAA,EAC7F,gBAAgB,QAAQ,CAAC,WAAW,cAAc,SAAS,CAAC,CAAC,OAAO,OAAO,OAAO,QAAQ,CAAC,IAAI,CAAC,CAAC;AACnG;AAOO,IAAM,kCAAkC;AAE/C,IAAM,eAAe;AAEd,SAAS,uBAAuB,aAA6B;AAClE,MAAI,CAAC,aAAa,KAAK,WAAW,EAAG,OAAM,IAAI,UAAU,qDAAqD;AAC9G,SAAO,GAAG,+BAA+B,GAAG,WAAW;AACzD;AAGO,SAAS,sBAAsB,QAAqD;AACzF,QAAM,aAAa,OAAO,OAAO,CAAC,UAAU,MAAM,WAAW,+BAA+B,CAAC;AAC7F,MAAI,WAAW,WAAW,EAAG,QAAO;AACpC,SAAO,WACJ,IAAI,CAAC,UAAU,MAAM,MAAM,gCAAgC,MAAM,CAAC,EAClE,OAAO,CAAC,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O;AACd,eAAO,iBAAiB,KAAK;AAAA,MAC/B;AACA,UAAI,CAAC,SAAS,GAAI,QAAO,QAAQ,QAAQ;AACzC,aAAO,EAAE,WAAW,MAAM,OAAO,SAAS;AAAA,IAC5C;AAAA,IACA,cAAc,CAAC,aAAa,IAAI,CAAC,MAAM;AAAA,MACrC,eAAe,QAAQ,WAAW,CAAC,aAAa,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC;AAAA,MACvE,CAAC,SAAS,KAAK;AAAA,IACjB;AAAA,EACF;AACA,SAAO;AACT;","names":["segment","segment","workspace"]}
@@ -0,0 +1,101 @@
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';
3
+ /** The verified caller of one operator request. */
4
+ export interface OperatorContext<Identity> {
5
+ identity: Identity;
6
+ key: {
7
+ keyId: string;
8
+ scopes: readonly string[];
9
+ };
10
+ request: Request;
11
+ }
12
+ /**
13
+ * The app's side of the operator API: storage and execution only. Scope,
14
+ * workspace restriction, input validation, and response shapes belong to the
15
+ * shared handler, so every app answers the same way.
16
+ */
17
+ export interface OperatorAdapter<Identity> {
18
+ /**
19
+ * Apply the app's workspace roles: `read` needs viewer access, `run` needs
20
+ * the role that may start agent work. Null answers 404, so a key cannot
21
+ * probe workspaces it cannot reach.
22
+ */
23
+ authorizeWorkspace(ctx: OperatorContext<Identity>, workspaceId: string, access: 'read' | 'run'): Promise<OperatorWorkspace | null>;
24
+ listWorkspaces(ctx: OperatorContext<Identity>): Promise<OperatorWorkspace[]>;
25
+ createWorkspace?(ctx: OperatorContext<Identity>, input: {
26
+ name: string;
27
+ }): Promise<OperatorWorkspace>;
28
+ /** Admit the turn durably and return without waiting for it; the same turnId never starts twice. */
29
+ startTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, input: StartTurnInput): Promise<OperatorTurn>;
30
+ getTurn(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, target: {
31
+ threadId: string;
32
+ turnId: string;
33
+ }): Promise<OperatorTurn | null>;
34
+ listThreads?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: {
35
+ cursor?: string;
36
+ limit: number;
37
+ }): Promise<{
38
+ threads: OperatorThread[];
39
+ nextCursor: string | null;
40
+ }>;
41
+ getThread?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, threadId: string): Promise<{
42
+ thread: OperatorThread;
43
+ latestTurn: OperatorTurn | null;
44
+ } | null>;
45
+ listApprovals(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace): Promise<OperatorApproval[]>;
46
+ listJournal?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: {
47
+ days: number;
48
+ }): Promise<OperatorJournalEntry[]>;
49
+ listFiles?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: {
50
+ prefix: string;
51
+ }): Promise<OperatorFileEntry[]>;
52
+ readFile?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, path: string): Promise<OperatorFile | null>;
53
+ /** The stored bytes, or null when the asset is not in this workspace. */
54
+ readAsset?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, assetId: string): Promise<Response | null>;
55
+ getScorecard?(ctx: OperatorContext<Identity>, workspace: OperatorWorkspace, query: {
56
+ days: number;
57
+ }): Promise<OperatorScorecard>;
58
+ }
59
+ export interface OperatorKeyStore<Key extends RequestApiKey, Identity> {
60
+ /** Verify against the app's existing key store, including revocation. */
61
+ verify(authorization: string): Promise<Key | null>;
62
+ /** Load the key owner; throw a Response to refuse a key class, such as spending-capped keys. */
63
+ resolveIdentity(key: Key): Promise<Identity | null>;
64
+ /** Atomically count the request against the key's limits. */
65
+ claimRequest(key: Key, requestId: string): Promise<{
66
+ allowed: boolean;
67
+ retryAfterSeconds?: number;
68
+ }>;
69
+ }
70
+ export interface OperatorApiOptions<Key extends RequestApiKey, Identity> {
71
+ app: {
72
+ id: string;
73
+ name: string;
74
+ };
75
+ keys: OperatorKeyStore<Key, Identity>;
76
+ adapter: OperatorAdapter<Identity>;
77
+ basePath?: string;
78
+ /** Longest hold for a turn read with `?wait=`, in seconds. */
79
+ maxWaitSeconds?: number;
80
+ /** Interval between state reads during a held turn read. */
81
+ pollIntervalMs?: number;
82
+ /** Unexpected adapter failures; responses never carry their detail. */
83
+ onError?(error: unknown, route: OperatorRouteId): void;
84
+ }
85
+ export interface OperatorApi {
86
+ /** True when the request addresses this API's base path. */
87
+ matches(request: Request): boolean;
88
+ handle(request: Request): Promise<Response>;
89
+ }
90
+ /** A refusal with a stable code; adapters throw it for expected failures. */
91
+ export declare class OperatorError extends Error {
92
+ readonly code: string;
93
+ readonly status: number;
94
+ readonly retryable: boolean;
95
+ constructor(code: string, status: number, message?: string, retryable?: boolean);
96
+ }
97
+ /**
98
+ * Mount the standard operator API. Requests must carry a Bearer key: there is
99
+ * no browser-cookie fallback, so a page session never reaches these routes.
100
+ */
101
+ export declare function createOperatorApi<Key extends RequestApiKey, Identity>(options: OperatorApiOptions<Key, Identity>): OperatorApi;
@@ -1,3 +1,6 @@
1
+ import {
2
+ createApiKeyRequestAuth
3
+ } from "../chunk-MLDKEEFQ.js";
1
4
  import {
2
5
  TangleSsoAccountConflictError,
3
6
  TangleSsoUserCreateError,
@@ -17,7 +20,8 @@ import {
17
20
  import {
18
21
  resolveTangleExecutionEnvironment
19
22
  } from "../chunk-D6UJEOZQ.js";
20
- import "../chunk-YNSPVKMS.js";
23
+ import "../chunk-UTAIRVOK.js";
24
+ import "../chunk-RN4WPTBH.js";
21
25
  import {
22
26
  parseJsonObjectBody
23
27
  } from "../chunk-3NCPXNBZ.js";
@@ -454,50 +458,6 @@ function createTanglePlatformBillingClient(http, identity) {
454
458
  deduct: (input) => http.deduct(input)
455
459
  };
456
460
  }
457
-
458
- // src/platform/api-key-auth.ts
459
- function createApiKeyRequestAuth(options) {
460
- return async (request) => {
461
- const authorization = request.headers.get("Authorization");
462
- if (authorization === null) return null;
463
- const bearer = /^Bearer +(\S+)$/i.exec(authorization);
464
- if (!bearer) {
465
- throw denied(401, "api_key.invalid", "Invalid API key");
466
- }
467
- const requiredScope = options.requiredScope(request);
468
- const requiredScopes = typeof requiredScope === "string" ? [requiredScope] : Array.from(requiredScope ?? []);
469
- if (!requiredScopes?.length || !requiredScopes.every((scope) => typeof scope === "string" && scope.trim())) {
470
- throw denied(403, "api_key.route_denied", "API key access is not enabled for this route");
471
- }
472
- const key = await options.verify(`Bearer ${bearer[1]}`);
473
- if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {
474
- throw denied(401, "api_key.invalid", "Invalid API key");
475
- }
476
- if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {
477
- throw denied(401, "api_key.expired", "An unexpired API key with a finite expiry is required");
478
- }
479
- if (!Array.isArray(key.scopes) || !requiredScopes.every((scope) => key.scopes.includes(scope))) {
480
- throw denied(403, "api_key.insufficient_scope", `API key requires scopes: ${requiredScopes.join(", ")}`);
481
- }
482
- const identity = await options.resolveIdentity(key);
483
- if (!identity) throw denied(401, "api_key.invalid_owner", "API key owner is unavailable");
484
- const claim = await options.claimRequest(key, crypto.randomUUID());
485
- if (claim.allowed !== true) {
486
- const headers = new Headers();
487
- if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds > 0) {
488
- headers.set("Retry-After", String(Math.ceil(claim.retryAfterSeconds)));
489
- }
490
- throw denied(429, "api_key.request_limit_exceeded", "API key request limit exceeded", headers);
491
- }
492
- if (key.expiresAt <= Date.now()) {
493
- throw denied(401, "api_key.expired", "API key expired during authorization");
494
- }
495
- return identity;
496
- };
497
- }
498
- function denied(status, code, error, headers) {
499
- return Response.json({ error, code }, { status, headers });
500
- }
501
461
  export {
502
462
  DEFAULT_SEAT_BILLING_ENABLED_ENV_VAR,
503
463
  DEFAULT_TANGLE_TIER_POLICY,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/platform/hub-connect-callback.ts","../../src/platform/hub-settings.ts","../../src/platform/billing.ts","../../src/platform/api-key-auth.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","/** Verified key fields required to enter a product's private API routes. */\nexport interface RequestApiKey {\n keyId: string\n ownerId: string\n scopes: readonly string[]\n /** Unix epoch milliseconds. Private API credentials must expire. */\n expiresAt: number\n}\n\nexport interface ApiKeyRequestAuthOptions<Key extends RequestApiKey, Identity> {\n /** Verify against the existing key store, including revocation and spending limits. */\n verify(authorization: string): Promise<Key | null>\n /** Return one scope or all required scopes; null or an empty list denies the route. */\n requiredScope(request: Request): string | readonly string[] | null\n /** Load the owner from product storage; retain normal workspace and tenant authorization. */\n resolveIdentity(key: Key): Promise<Identity | null>\n /** Atomically enforce the existing key's request quotas before admitting the request. */\n claimRequest(key: Key, requestId: string): Promise<{ allowed: boolean; retryAfterSeconds?: number }>\n}\n\n/**\n * Adapt existing Bearer keys to private product routes without issuing sessions.\n * Only absent authorization returns null; supplied invalid credentials never\n * fall through to cookie authentication. Callers retain their ordinary RBAC.\n */\nexport function createApiKeyRequestAuth<Key extends RequestApiKey, Identity>(\n options: ApiKeyRequestAuthOptions<Key, Identity>,\n): (request: Request) => Promise<Identity | null> {\n return async (request) => {\n const authorization = request.headers.get('Authorization')\n if (authorization === null) return null\n const bearer = /^Bearer +(\\S+)$/i.exec(authorization)\n if (!bearer) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n const requiredScope = options.requiredScope(request)\n const requiredScopes = typeof requiredScope === 'string' ? [requiredScope] : Array.from(requiredScope ?? [])\n if (!requiredScopes?.length || !requiredScopes.every(scope => typeof scope === 'string' && scope.trim())) {\n throw denied(403, 'api_key.route_denied', 'API key access is not enabled for this route')\n }\n const key = await options.verify(`Bearer ${bearer[1]}`)\n if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {\n throw denied(401, 'api_key.invalid', 'Invalid API key')\n }\n if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'An unexpired API key with a finite expiry is required')\n }\n if (!Array.isArray(key.scopes) || !requiredScopes.every(scope => key.scopes.includes(scope))) {\n throw denied(403, 'api_key.insufficient_scope', `API key requires scopes: ${requiredScopes.join(', ')}`)\n }\n const identity = await options.resolveIdentity(key)\n if (!identity) throw denied(401, 'api_key.invalid_owner', 'API key owner is unavailable')\n const claim = await options.claimRequest(key, crypto.randomUUID())\n if (claim.allowed !== true) {\n const headers = new Headers()\n if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds! > 0) {\n headers.set('Retry-After', String(Math.ceil(claim.retryAfterSeconds!)))\n }\n throw denied(429, 'api_key.request_limit_exceeded', 'API key request limit exceeded', headers)\n }\n if (key.expiresAt <= Date.now()) {\n throw denied(401, 'api_key.expired', 'API key expired during authorization')\n }\n return identity\n }\n}\n\nfunction denied(status: number, code: string, error: string, headers?: Headers): Response {\n return Response.json({ error, code }, { status, headers })\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,MAAI,KAAK,WAAW,4BAA4B,OAAQ,QAAO;AAC/D,MAAI,CAAC,4BAA4B,MAAM,CAAC,QAAQ,UAAU,aAAa,OAAO,GAAG,EAAE,WAAW,CAAC,EAAG,QAAO;AACzG,QAAM,SAAS,CAAC,UAAyB,CAAC,CAAC,SAAS,MAAM,UAAU,OAAO,mBAAmB,KAAK,KAAK;AACxG,SAAO,UAAU,aAAa,IAAI,UAAU,MAAM,YAC7C,OAAO,UAAU,aAAa,IAAI,OAAO,CAAC,KAC1C,OAAO,UAAU,aAAa,IAAI,SAAS,CAAC;AACnD;;;ACgFA,SAAS,KAAK,OAAgB,SAAS,KAAK,UAAkC,CAAC,GAAa;AAC1F,SAAO,SAAS,KAAK,OAAO,EAAE,QAAQ,SAAS,EAAE,iBAAiB,YAAY,GAAG,QAAQ,EAAE,CAAC;AAC9F;AAEA,SAAS,UAAiB;AAExB,QAAM,KAAK,EAAE,OAAO,gCAAgC,MAAM,oBAAoB,GAAG,GAAG;AACtF;AAEA,SAAS,OAAO,OAAyC;AACvD,MAAI,UAAU,QAAQ,OAAO,UAAU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AE,OAAO,KAAK,GAAG,EAAE,QAAQ,QAAQ,CAAC;AAC3D;","names":["body","body"]}
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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gB,MAAM;AAAA,IAC5D,SAAS,OAAO,YAAY,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"]}
@@ -3,7 +3,8 @@ import {
3
3
  streamChatRouteAsSandboxEvents
4
4
  } from "../chunk-FNRUXPXE.js";
5
5
  import "../chunk-6VRVRWYN.js";
6
- import "../chunk-YNSPVKMS.js";
6
+ import "../chunk-UTAIRVOK.js";
7
+ import "../chunk-RN4WPTBH.js";
7
8
  import "../chunk-3NCPXNBZ.js";
8
9
  import "../chunk-53K4S3K6.js";
9
10
  import "../chunk-OEHEHPPA.js";