@tangle-network/agent-app 0.60.13 → 0.60.14

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.
@@ -10,7 +10,7 @@ function fence(step) {
10
10
  }
11
11
  function agentSignupScript(platformOrigin = TANGLE_PLATFORM_ORIGIN) {
12
12
  return `// Requests a scoped Tangle key for this agent. The owner approves once.
13
- // node tangle-signup.mjs start --app <app> --agent-name <name> [--owner-email <email>] [--budget-usd <n>]
13
+ // node tangle-signup.mjs start --agent-name <name> [--owner-email <email>] [--budget-usd <n>] [--products a,b]
14
14
  // node tangle-signup.mjs wait (run again while it exits 3; exits 0 once approved)
15
15
  import { mkdirSync, readFileSync, writeFileSync } from ${JSON.stringify("node:fs")}
16
16
 
@@ -33,12 +33,8 @@ async function post(path, body) {
33
33
  }
34
34
 
35
35
  if (command === 'start') {
36
- const app = flag('app')
37
- if (!app) {
38
- console.error('Pass --app (for example --app sandbox)')
39
- process.exit(2)
40
- }
41
- const request = { app, agent_name: flag('agent-name') ?? 'coding-agent' }
36
+ const request = { agent_name: flag('agent-name') ?? 'coding-agent' }
37
+ if (flag('products')) request.products = flag('products').split(',').map((id) => id.trim()).filter(Boolean)
42
38
  if (flag('owner-email')) request.owner_email = flag('owner-email')
43
39
  if (flag('budget-usd')) request.budget_usd = Number(flag('budget-usd'))
44
40
  const started = await post('/cross-site/device/start', request)
@@ -48,7 +44,6 @@ if (command === 'start') {
48
44
  }
49
45
  const grant = started.body.data
50
46
  const saved = {
51
- app,
52
47
  device_code: grant.device_code,
53
48
  interval: grant.interval,
54
49
  expires_at: Date.now() + grant.expires_in * 1000,
@@ -73,11 +68,11 @@ if (command === 'wait') {
73
68
  }
74
69
  const stopAt = Math.min(saved.expires_at, Date.now() + Number(flag('seconds') ?? 8) * 1000)
75
70
  for (;;) {
76
- const polled = await post('/cross-site/device/poll', { app: saved.app, device_code: saved.device_code })
71
+ const polled = await post('/cross-site/device/poll', { device_code: saved.device_code })
77
72
  if (polled.status === 200) {
78
73
  const { api_key: apiKey, key, account } = polled.body.data
79
74
  writeFileSync('.tangle/api-key', \`\${apiKey}\\n\`, { mode: 0o600 })
80
- console.log(\`Approved. Key "\${key?.name ?? saved.app}" saved to .tangle/api-key (spend cap $\${key?.budget_usd ?? 'none'}).\`)
75
+ console.log(\`Approved. Key "\${key?.name ?? 'agent'}" saved to .tangle/api-key for \${(key?.products ?? []).join(', ') || 'the approved products'} (spend cap $\${key?.budget_usd ?? 'none'}).\`)
81
76
  if (account && !account.funded) {
82
77
  console.log(\`The owner's account has no credit yet. Ask the owner to add credits: \${account.add_credits_url}\`)
83
78
  }
@@ -99,7 +94,7 @@ if (command === 'wait') {
99
94
  }
100
95
  }
101
96
 
102
- console.error('Usage: node tangle-signup.mjs start --app <app> --agent-name <name> [--owner-email <email>] | wait')
97
+ console.error('Usage: node tangle-signup.mjs start --agent-name <name> [--owner-email <email>] [--budget-usd <n>] [--products a,b] | wait')
103
98
  process.exit(2)
104
99
  `;
105
100
  }
@@ -120,7 +115,7 @@ function signupSection(config) {
120
115
  return [
121
116
  "## 1. Get a scoped key (one owner approval)",
122
117
  "",
123
- "Tangle issues each agent its own key, owned by a person who approves it once.",
118
+ "Tangle issues each agent one key, owned by a person who approves it once. The same key works for every Tangle product the owner approves: Tangle Sandbox, Tangle Router and the agent apps such as Tangle GTM Agent. If you already hold one from another Tangle product's setup, reuse it and skip to step 2.",
124
119
  `Ask your owner which email address their Tangle account uses (or should use). Nothing is charged by signing up, and there is no free credit: ${config.name} work is paid from the owner's prepaid balance.`,
125
120
  "",
126
121
  "Save this script as `tangle-signup.mjs` (Node.js 18 or newer, no dependencies):",
@@ -131,7 +126,7 @@ function signupSection(config) {
131
126
  "",
132
127
  fence({
133
128
  language: "bash",
134
- code: `node tangle-signup.mjs start --app ${config.signup.app} --agent-name "<your agent name>" --owner-email "<owner email>" --budget-usd ${budget}`
129
+ code: `node tangle-signup.mjs start --agent-name "<your agent name>" --owner-email "<owner email>" --budget-usd ${budget}${config.signup.products ? ` --products ${config.signup.products.join(",")}` : ""}`
135
130
  }),
136
131
  "",
137
132
  "It prints the approval link and a confirmation code. Tangle emails the owner the same link; if you cannot give an email, omit `--owner-email` and send the owner the printed link yourself. Tell the owner the code if you can reach them.",
@@ -142,7 +137,7 @@ function signupSection(config) {
142
137
  "",
143
138
  "What the owner does, once: sign in (or create an account and verify the email), check the confirmation code, and approve. That is the only human step.",
144
139
  "",
145
- `The key in \`.tangle/api-key\` (mode 600) can only be used for ${config.name}, can spend at most the cap you requested, and the owner can revoke it under Keys at any time. If \`wait\` says the account has no credit, ask the owner to add credits at the printed link before your first paid call.`,
140
+ `The key in \`.tangle/api-key\` (mode 600) works only for the products the owner approved, can spend at most the cap you requested across all of them, and the owner can revoke it once under Keys to stop it everywhere. If \`wait\` says the account has no credit, ask the owner to add credits at the printed link before your first paid call.`,
146
141
  "",
147
142
  "Then load the key without printing it, and keep it out of version control:",
148
143
  "",
@@ -282,18 +277,18 @@ function renderAgentManifest(config) {
282
277
  const origin = trimOrigin(config.origin);
283
278
  const signup = config.signup.kind === "device" ? {
284
279
  kind: "device_authorization",
285
- app: config.signup.app,
286
280
  start: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/start`,
287
281
  poll: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/poll`,
282
+ contract: `${TANGLE_PLATFORM_ORIGIN}/.well-known/tangle-agent.json`,
288
283
  request: {
289
- app: config.signup.app,
290
284
  agent_name: "string, 1-64 characters",
291
285
  owner_email: "optional; Tangle emails this owner the approval link",
292
- budget_usd: `optional lifetime spend cap, 1-1000, default ${config.signup.budgetUsd ?? 25}`
286
+ budget_usd: `optional lifetime spend cap shared by every granted product, 1-1000, default ${config.signup.budgetUsd ?? 25}`,
287
+ products: config.signup.products ?? 'optional; default every agent-ready product, or ["*"]'
293
288
  },
294
289
  human_inputs: ["The owner approves the request once."],
295
290
  key: {
296
- scope: `${config.signup.app} only`,
291
+ scope: "One key for every product the owner approved; use it as Bearer at each product.",
297
292
  revocable_at: `${TANGLE_PLATFORM_ORIGIN}/app/keys`
298
293
  },
299
294
  payment: "Prepaid credit on the owner account. No free credit; paid calls are refused until the owner adds credits.",
@@ -412,4 +407,4 @@ export {
412
407
  withVaryAccept,
413
408
  createAgentSurfaceHandler
414
409
  };
415
- //# sourceMappingURL=chunk-3G7IOCSV.js.map
410
+ //# sourceMappingURL=chunk-HGKDZQ52.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/agent-surfaces/index.ts"],"sourcesContent":["/**\n * Machine-readable surfaces for a Tangle product, generated from one config.\n *\n * Every product publishes the same four things an AI agent needs to become a\n * customer without a human doing the setup:\n *\n * - `/agent-setup.md`: a SKILL.md (Claude Code and Codex skill format) that\n * doubles as a copy-paste prompt. It takes a fresh agent from nothing to a\n * verified first call: one owner approval, a scoped key, install, call.\n * - `/llms.txt`: the llms.txt index, pointing at the setup skill first.\n * - `/.well-known/tangle-agent.json`: the Tangle agent manifest.\n * - Markdown for `Accept: text/markdown` on the product's pages, with\n * `Vary: Accept` on both representations so caches keep them apart.\n *\n * The signup section is rendered here, not in product config, so every\n * product describes Platform's agent signup identically and cannot drift.\n *\n * Web-standard `Request`/`Response` only: safe in Workers, Node and browsers.\n */\n\n/** Manifest schema this module emits. Additive over the 2026-06-16 shape. */\nexport const AGENT_MANIFEST_SCHEMA_VERSION = '2026-10-09'\n\nexport const TANGLE_PLATFORM_ORIGIN = 'https://id.tangle.tools'\n\nexport interface AgentSurfaceStep {\n title: string\n /** Fence language for the code block. */\n language: 'bash' | 'js' | 'ts' | 'python' | 'json'\n code: string\n /** What a successful run prints or returns. */\n expect: string\n}\n\nexport interface AgentSurfaceError {\n symptom: string\n cause: string\n fix: string\n}\n\nexport interface AgentSurfaceLink {\n label: string\n url: string\n}\n\n/**\n * How an agent obtains a key. `device` uses Platform's agent signup: the owner\n * approves once and the agent receives its own capped, revocable key.\n */\nexport type AgentSignup =\n | {\n kind: 'device'\n /**\n * Products to ask for. Omitted, the one signup asks for every\n * agent-ready product, so the same key works across Tangle.\n */\n products?: string[]\n /** Default lifetime spend cap the skill asks for, in USD. */\n budgetUsd?: number\n }\n | {\n kind: 'manual'\n /** Numbered steps the owner performs; each one is a human input. */\n steps: string[]\n }\n\nexport interface AgentSurfaceConfig {\n /** Short id used in the skill name: `tangle-<id>-setup`. */\n id: string\n name: string\n /** Public HTTPS origin, no trailing slash. */\n origin: string\n /** What the product is for, in one to three plain sentences. */\n summary: string\n useWhen: string[]\n signup: AgentSignup\n /** Environment variable the key is exported as. */\n apiKeyEnv: string\n /** Runtime prerequisites a fresh machine needs, e.g. `Node.js 20 or newer`. */\n prerequisites: string[]\n install: AgentSurfaceStep[]\n firstCall: AgentSurfaceStep[]\n verify: AgentSurfaceStep[]\n errors: AgentSurfaceError[]\n pricing: {\n /** Plain statement of how usage is charged. */\n summary: string\n /** Public, credential-free price data an agent can quote from. */\n quoteUrl?: string\n url?: string\n }\n next: AgentSurfaceLink[]\n docs?: string\n openapi?: string\n mcp?: { url: string; auth: string }\n related?: Array<{ name: string; manifest?: string; url?: string }>\n /** Extra manifest fields a product already publishes (kept verbatim). */\n manifest?: Record<string, unknown>\n}\n\nexport interface AgentSurfaceFile {\n path: string\n contentType: string\n body: string\n}\n\nconst MARKDOWN = 'text/markdown; charset=utf-8'\n\nfunction trimOrigin(origin: string): string {\n return origin.replace(/\\/+$/, '')\n}\n\nfunction fence(step: Pick<AgentSurfaceStep, 'language' | 'code'>): string {\n return ['```' + step.language, step.code.trimEnd(), '```'].join('\\n')\n}\n\n/**\n * The signup script the skill tells an agent to save and run. Node 18+ only,\n * no dependencies, in two short commands so a tool that kills long-running\n * commands cannot cut the wait: `start` returns at once with the link and the\n * confirmation code; `wait` polls for a few seconds and exits 0 once approved\n * or 3 while the owner has not approved yet. It never prints the key; it\n * writes `.tangle/api-key` with mode 0600.\n */\nexport function agentSignupScript(platformOrigin = TANGLE_PLATFORM_ORIGIN): string {\n // The specifier is interpolated so this module's own import scan (the\n // browser-safe subpath gate) does not read script text as an import.\n return `// Requests a scoped Tangle key for this agent. The owner approves once.\n// node tangle-signup.mjs start --agent-name <name> [--owner-email <email>] [--budget-usd <n>] [--products a,b]\n// node tangle-signup.mjs wait (run again while it exits 3; exits 0 once approved)\nimport { mkdirSync, readFileSync, writeFileSync } from ${JSON.stringify('node:fs')}\n\nconst command = process.argv[2]\nconst flag = (name) => {\n const index = process.argv.indexOf(\\`--\\${name}\\`)\n return index > 0 ? process.argv[index + 1] : undefined\n}\nconst platform = '${trimOrigin(platformOrigin)}'\nconst statePath = '.tangle/signup.json'\nmkdirSync('.tangle', { recursive: true, mode: 0o700 })\n\nasync function post(path, body) {\n const response = await fetch(platform + path, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(body),\n })\n return { status: response.status, body: await response.json().catch(() => ({})) }\n}\n\nif (command === 'start') {\n const request = { agent_name: flag('agent-name') ?? 'coding-agent' }\n if (flag('products')) request.products = flag('products').split(',').map((id) => id.trim()).filter(Boolean)\n if (flag('owner-email')) request.owner_email = flag('owner-email')\n if (flag('budget-usd')) request.budget_usd = Number(flag('budget-usd'))\n const started = await post('/cross-site/device/start', request)\n if (started.status !== 200) {\n console.error(\\`Signup refused (HTTP \\${started.status}): \\${JSON.stringify(started.body)}\\`)\n process.exit(1)\n }\n const grant = started.body.data\n const saved = {\n device_code: grant.device_code,\n interval: grant.interval,\n expires_at: Date.now() + grant.expires_in * 1000,\n }\n writeFileSync(statePath, JSON.stringify(saved), { mode: 0o600 })\n console.log(grant.agent?.owner_notified\n ? \\`Approval email sent to \\${request.owner_email}.\\`\n : 'Send your owner this approval link.')\n console.log(\\`Approval link: \\${grant.verification_uri_complete}\\`)\n console.log(\\`Confirmation code: \\${grant.user_code} (expires in \\${Math.round(grant.expires_in / 60)} minutes)\\`)\n console.log('Next: run \\`node tangle-signup.mjs wait\\` until it prints Approved.')\n process.exit(0)\n}\n\nif (command === 'wait') {\n let saved\n try {\n saved = JSON.parse(readFileSync(statePath, 'utf8'))\n } catch {\n console.error('No pending signup. Run \\`node tangle-signup.mjs start\\` first.')\n process.exit(1)\n }\n const stopAt = Math.min(saved.expires_at, Date.now() + Number(flag('seconds') ?? 8) * 1000)\n for (;;) {\n const polled = await post('/cross-site/device/poll', { device_code: saved.device_code })\n if (polled.status === 200) {\n const { api_key: apiKey, key, account } = polled.body.data\n writeFileSync('.tangle/api-key', \\`\\${apiKey}\\\\n\\`, { mode: 0o600 })\n console.log(\\`Approved. Key \"\\${key?.name ?? 'agent'}\" saved to .tangle/api-key for \\${(key?.products ?? []).join(', ') || 'the approved products'} (spend cap $\\${key?.budget_usd ?? 'none'}).\\`)\n if (account && !account.funded) {\n console.log(\\`The owner's account has no credit yet. Ask the owner to add credits: \\${account.add_credits_url}\\`)\n }\n process.exit(0)\n }\n if (polled.status !== 428) {\n console.error(\\`Approval failed (HTTP \\${polled.status}): \\${JSON.stringify(polled.body)}\\`)\n process.exit(1)\n }\n if (Date.now() >= saved.expires_at) {\n console.error('The approval link expired. Run \\`node tangle-signup.mjs start\\` again.')\n process.exit(1)\n }\n if (Date.now() + saved.interval * 1000 > stopAt) {\n console.log('Still waiting for the owner to approve. Run \\`node tangle-signup.mjs wait\\` again.')\n process.exit(3)\n }\n await new Promise((resolve) => setTimeout(resolve, saved.interval * 1000))\n }\n}\n\nconsole.error('Usage: node tangle-signup.mjs start --agent-name <name> [--owner-email <email>] [--budget-usd <n>] [--products a,b] | wait')\nprocess.exit(2)\n`\n}\n\nfunction signupSection(config: AgentSurfaceConfig): string[] {\n const env = config.apiKeyEnv\n if (config.signup.kind === 'manual') {\n return [\n '## 1. Get a key',\n '',\n 'This product does not yet support agent signup. Ask your owner to do the following, then continue:',\n '',\n ...config.signup.steps.map((step, index) => `${index + 1}. ${step}`),\n '',\n `Store the key outside version control and export it as \\`${env}\\`. Never print, log, or commit it.`,\n ]\n }\n const budget = config.signup.budgetUsd ?? 25\n return [\n '## 1. Get a scoped key (one owner approval)',\n '',\n 'Tangle issues each agent one key, owned by a person who approves it once. The same key works for every Tangle product the owner approves: Tangle Sandbox, Tangle Router and the agent apps such as Tangle GTM Agent. If you already hold one from another Tangle product\\'s setup, reuse it and skip to step 2.',\n `Ask your owner which email address their Tangle account uses (or should use). Nothing is charged by signing up, and there is no free credit: ${config.name} work is paid from the owner's prepaid balance.`,\n '',\n 'Save this script as `tangle-signup.mjs` (Node.js 18 or newer, no dependencies):',\n '',\n fence({ language: 'js', code: agentSignupScript() }),\n '',\n 'Start the request with your own name and the owner\\'s email. It returns at once:',\n '',\n fence({\n language: 'bash',\n code: `node tangle-signup.mjs start --agent-name \"<your agent name>\" --owner-email \"<owner email>\" --budget-usd ${budget}${config.signup.products ? ` --products ${config.signup.products.join(',')}` : ''}`,\n }),\n '',\n 'It prints the approval link and a confirmation code. Tangle emails the owner the same link; if you cannot give an email, omit `--owner-email` and send the owner the printed link yourself. Tell the owner the code if you can reach them.',\n '',\n 'Then wait for the approval. Each run returns within about 8 seconds: exit code 3 and `Still waiting` mean run it again; exit code 0 and `Approved` mean the key is saved. Keep each run short rather than wrapping it in one long blocking loop, since many agent tools stop long commands.',\n '',\n fence({ language: 'bash', code: 'node tangle-signup.mjs wait' }),\n '',\n 'What the owner does, once: sign in (or create an account and verify the email), check the confirmation code, and approve. That is the only human step.',\n '',\n `The key in \\`.tangle/api-key\\` (mode 600) works only for the products the owner approved, can spend at most the cap you requested across all of them, and the owner can revoke it once under Keys to stop it everywhere. If \\`wait\\` says the account has no credit, ask the owner to add credits at the printed link before your first paid call.`,\n '',\n 'Then load the key without printing it, and keep it out of version control:',\n '',\n fence({\n language: 'bash',\n code: `export ${env}=\"$(cat .tangle/api-key)\"\\ngrep -qxF '.tangle/' .gitignore 2>/dev/null || echo '.tangle/' >> .gitignore`,\n }),\n '',\n 'Never print, log, paste, or commit the key.',\n ]\n}\n\nfunction stepsSection(heading: string, steps: AgentSurfaceStep[]): string[] {\n if (steps.length === 0) return []\n const lines = [heading, '']\n for (const step of steps) {\n lines.push(`${step.title}:`, '', fence(step), '', `Expected: ${step.expect}`, '')\n }\n return lines\n}\n\n/** The agent setup skill: valid SKILL.md and a plain copy-paste prompt. */\nexport function renderAgentSetupSkill(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n const description = `Set up ${config.name} for this agent end to end: get a scoped API key with one owner approval, install the client, make the first successful call, and verify it.`\n const lines: string[] = [\n '---',\n `name: tangle-${config.id}-setup`,\n `description: ${description}`,\n '---',\n '',\n `# Set up ${config.name}`,\n '',\n config.summary,\n '',\n 'Use it when:',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n 'Complete every step below in order and stop at the first failure; the error table at the end names the fix.',\n 'Prerequisites: ' + config.prerequisites.join('; ') + '.',\n '',\n ...signupSection(config),\n '',\n ...stepsSection('## 2. Install', config.install),\n ...stepsSection('## 3. Make the first call', config.firstCall),\n ...stepsSection('## 4. Verify it worked', config.verify),\n '## Common errors',\n '',\n '| Symptom | Cause | Fix |',\n '| --- | --- | --- |',\n ...config.errors.map(\n (error) => `| ${error.symptom.replace(/\\|/g, '\\\\|')} | ${error.cause.replace(/\\|/g, '\\\\|')} | ${error.fix.replace(/\\|/g, '\\\\|')} |`,\n ),\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Current prices, no key needed: ${config.pricing.quoteUrl}`] : []),\n ...(config.pricing.url ? [`Pricing page: ${config.pricing.url}`] : []),\n '',\n '## Next',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n '',\n '## Machine-readable surfaces',\n '',\n `- Agent manifest: ${origin}/.well-known/tangle-agent.json`,\n `- llms.txt: ${origin}/llms.txt`,\n `- This setup skill: ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- OpenAPI: ${config.openapi}`] : []),\n ...(config.mcp ? [`- MCP server: ${config.mcp.url} (${config.mcp.auth})`] : []),\n '',\n ]\n return lines.join('\\n')\n}\n\n/** llms.txt index for the product. The setup skill is the first link. */\nexport function renderLlmsTxt(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n `> ${config.summary}`,\n '',\n `To set this product up from scratch, fetch ${origin}/agent-setup.md and follow it. It is a complete prompt and a SKILL.md: one owner approval, a scoped key, install, first call, verification.`,\n '',\n '## Start here',\n '',\n `- [Agent setup skill](${origin}/agent-setup.md): from nothing to a verified first call`,\n `- [Agent manifest](${origin}/.well-known/tangle-agent.json): machine-readable contract`,\n ...(config.openapi ? [`- [OpenAPI](${config.openapi}): HTTP API schema`] : []),\n ...(config.mcp ? [`- [MCP server](${config.mcp.url}): ${config.mcp.auth}`] : []),\n ...(config.docs ? [`- [Documentation](${config.docs})`] : []),\n '',\n '## Pricing',\n '',\n `- ${config.pricing.summary}`,\n ...(config.pricing.quoteUrl ? [`- [Machine-readable prices](${config.pricing.quoteUrl}): no key needed`] : []),\n '',\n '## Optional',\n '',\n ...config.next.map((link) => `- [${link.label}](${link.url})`),\n ...(config.related ?? []).map(\n (surface) => `- [${surface.name}](${surface.manifest ?? surface.url ?? ''})`,\n ),\n '',\n ].join('\\n')\n}\n\n/** Markdown for the product's home page, served for `Accept: text/markdown`. */\nexport function renderHomeMarkdown(config: AgentSurfaceConfig): string {\n const origin = trimOrigin(config.origin)\n return [\n `# ${config.name}`,\n '',\n config.summary,\n '',\n '## Use it when',\n '',\n ...config.useWhen.map((item) => `- ${item}`),\n '',\n '## Hand this to your agent',\n '',\n `An AI agent can set ${config.name} up by itself: fetch ${origin}/agent-setup.md and follow it. The owner approves once; nothing else needs a human.`,\n '',\n '## Pricing',\n '',\n config.pricing.summary,\n ...(config.pricing.quoteUrl ? ['', `Machine-readable prices: ${config.pricing.quoteUrl}`] : []),\n '',\n '## Machine-readable surfaces',\n '',\n `- ${origin}/llms.txt`,\n `- ${origin}/.well-known/tangle-agent.json`,\n `- ${origin}/agent-setup.md`,\n ...(config.openapi ? [`- ${config.openapi}`] : []),\n ...(config.mcp ? [`- ${config.mcp.url}`] : []),\n '',\n ].join('\\n')\n}\n\n/** The `/.well-known/tangle-agent.json` document. */\nexport function renderAgentManifest(config: AgentSurfaceConfig): Record<string, unknown> {\n const origin = trimOrigin(config.origin)\n const signup =\n config.signup.kind === 'device'\n ? {\n kind: 'device_authorization',\n start: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/start`,\n poll: `POST ${TANGLE_PLATFORM_ORIGIN}/cross-site/device/poll`,\n contract: `${TANGLE_PLATFORM_ORIGIN}/.well-known/tangle-agent.json`,\n request: {\n agent_name: 'string, 1-64 characters',\n owner_email: 'optional; Tangle emails this owner the approval link',\n budget_usd: `optional lifetime spend cap shared by every granted product, 1-1000, default ${config.signup.budgetUsd ?? 25}`,\n products: config.signup.products ?? 'optional; default every agent-ready product, or [\"*\"]',\n },\n human_inputs: ['The owner approves the request once.'],\n key: {\n scope: 'One key for every product the owner approved; use it as Bearer at each product.',\n revocable_at: `${TANGLE_PLATFORM_ORIGIN}/app/keys`,\n },\n payment: 'Prepaid credit on the owner account. No free credit; paid calls are refused until the owner adds credits.',\n add_credits: `${TANGLE_PLATFORM_ORIGIN}/app/billing`,\n }\n : { kind: 'manual', steps: config.signup.steps }\n return {\n ...config.manifest,\n schema_version: AGENT_MANIFEST_SCHEMA_VERSION,\n name: config.name,\n description: config.summary,\n homepage: `${origin}/`,\n llms: `${origin}/llms.txt`,\n agent_setup: `${origin}/agent-setup.md`,\n ...(config.docs ? { docs: config.docs } : {}),\n ...(config.openapi ? { openapi: config.openapi } : {}),\n ...(config.mcp ? { mcp: config.mcp } : {}),\n environment: { api_key: config.apiKeyEnv },\n signup,\n pricing: {\n summary: config.pricing.summary,\n ...(config.pricing.quoteUrl ? { quote: config.pricing.quoteUrl } : {}),\n ...(config.pricing.url ? { page: config.pricing.url } : {}),\n },\n ...(config.related?.length ? { related_surfaces: config.related } : {}),\n }\n}\n\n/** Every static surface as files, for products that ship them as assets. */\nexport function agentSurfaceFiles(config: AgentSurfaceConfig): AgentSurfaceFile[] {\n return [\n { path: 'agent-setup.md', contentType: MARKDOWN, body: renderAgentSetupSkill(config) },\n { path: 'llms.txt', contentType: 'text/plain; charset=utf-8', body: renderLlmsTxt(config) },\n { path: 'index.md', contentType: MARKDOWN, body: renderHomeMarkdown(config) },\n {\n path: '.well-known/tangle-agent.json',\n contentType: 'application/json; charset=utf-8',\n body: `${JSON.stringify(renderAgentManifest(config), null, 2)}\\n`,\n },\n ]\n}\n\n/**\n * True when `Accept` ranks `text/markdown` strictly above `text/html` and\n * gives it a nonzero weight. A browser's default header never does.\n */\nexport function prefersMarkdown(accept: string | null | undefined): boolean {\n if (!accept) return false\n let markdown = -1\n let html = -1\n for (const part of accept.split(',')) {\n const [rawType, ...params] = part.trim().split(';')\n const type = rawType?.trim().toLowerCase()\n let quality = 1\n for (const param of params) {\n const [key, value] = param.trim().split('=')\n if (key?.trim().toLowerCase() === 'q') {\n const parsed = Number(value)\n quality = Number.isFinite(parsed) ? parsed : 0\n }\n }\n if (type === 'text/markdown') markdown = Math.max(markdown, quality)\n if (type === 'text/html') html = Math.max(html, quality)\n }\n return markdown > 0 && markdown > html\n}\n\n/** A copy of `response` whose `Vary` includes `Accept`. */\nexport function withVaryAccept(response: Response): Response {\n const vary = response.headers.get('vary')\n if (vary && vary.split(',').some((value) => value.trim().toLowerCase() === 'accept')) {\n return response\n }\n const headers = new Headers(response.headers)\n headers.set('vary', vary ? `${vary}, Accept` : 'Accept')\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers,\n })\n}\n\nexport interface AgentSurfaceHandler {\n /**\n * Answers a surface request (`/agent-setup.md`, `/llms.txt`, the manifest,\n * or a negotiated markdown page), or `null` to let the app answer it.\n */\n handle(request: Request): Response | null\n /** Adds `Vary: Accept` when the path has a markdown representation. */\n finalize(request: Request, response: Response): Response\n}\n\n/**\n * Request handler over {@link agentSurfaceFiles}. `markdownPages` maps extra\n * HTML paths to markdown served on negotiation; `/` always maps to the home\n * markdown.\n */\nexport function createAgentSurfaceHandler(\n config: AgentSurfaceConfig,\n options: { markdownPages?: Record<string, string> } = {},\n): AgentSurfaceHandler {\n const files = new Map(agentSurfaceFiles(config).map((file) => [`/${file.path}`, file]))\n const negotiated = new Map<string, string>([\n ['/', renderHomeMarkdown(config)],\n ...Object.entries(options.markdownPages ?? {}),\n ])\n\n function respond(body: string, contentType: string, method: string, vary: boolean): Response {\n const headers = new Headers({\n 'content-type': contentType,\n 'cache-control': 'public, max-age=300',\n 'x-content-type-options': 'nosniff',\n })\n if (vary) headers.set('vary', 'Accept')\n return new Response(method === 'HEAD' ? null : body, { status: 200, headers })\n }\n\n return {\n handle(request) {\n if (request.method !== 'GET' && request.method !== 'HEAD') return null\n const path = new URL(request.url).pathname\n const file = files.get(path)\n if (file) return respond(file.body, file.contentType, request.method, false)\n const markdown = negotiated.get(path)\n if (markdown !== undefined && prefersMarkdown(request.headers.get('accept'))) {\n return respond(markdown, MARKDOWN, request.method, true)\n }\n return null\n },\n finalize(request, response) {\n return negotiated.has(new URL(request.url).pathname) ? withVaryAccept(response) : response\n },\n }\n}\n"],"mappings":";AAqBO,IAAM,gCAAgC;AAEtC,IAAM,yBAAyB;AAmFtC,IAAM,WAAW;AAEjB,SAAS,WAAW,QAAwB;AAC1C,SAAO,OAAO,QAAQ,QAAQ,EAAE;AAClC;AAEA,SAAS,MAAM,MAA2D;AACxE,SAAO,CAAC,QAAQ,KAAK,UAAU,KAAK,KAAK,QAAQ,GAAG,KAAK,EAAE,KAAK,IAAI;AACtE;AAUO,SAAS,kBAAkB,iBAAiB,wBAAgC;AAGjF,SAAO;AAAA;AAAA;AAAA,yDAGgD,KAAK,UAAU,SAAS,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,oBAO9D,WAAW,cAAc,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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;AAC3B,UAAI,KAAM,QAAO,QAAQ,KAAK,MAAM,KAAK,aAAa,QAAQ,QAAQ,KAAK;AAC3E,YAAM,WAAW,WAAW,IAAI,IAAI;AACpC,UAAI,aAAa,UAAa,gBAAgB,QAAQ,QAAQ,IAAI,QAAQ,CAAC,GAAG;AAC5E,eAAO,QAAQ,UAAU,UAAU,QAAQ,QAAQ,IAAI;AAAA,MACzD;AACA,aAAO;AAAA,IACT;AAAA,IACA,SAAS,SAAS,UAAU;AAC1B,aAAO,WAAW,IAAI,IAAI,IAAI,QAAQ,GAAG,EAAE,QAAQ,IAAI,eAAe,QAAQ,IAAI;AAAA,IACpF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,151 @@
1
+ // src/platform/api-key-auth.ts
2
+ function createApiKeyRequestAuth(options) {
3
+ return async (request) => {
4
+ const authorization = request.headers.get("Authorization");
5
+ if (authorization === null) return null;
6
+ const bearer = /^Bearer +(\S+)$/i.exec(authorization);
7
+ if (!bearer) {
8
+ throw denied(401, "api_key.invalid", "Invalid API key");
9
+ }
10
+ const requiredScope = options.requiredScope(request);
11
+ const requiredScopes = typeof requiredScope === "string" ? [requiredScope] : Array.from(requiredScope ?? []);
12
+ if (!requiredScopes?.length || !requiredScopes.every((scope) => typeof scope === "string" && scope.trim())) {
13
+ throw denied(403, "api_key.route_denied", "API key access is not enabled for this route");
14
+ }
15
+ const key = await options.verify(`Bearer ${bearer[1]}`);
16
+ if (!key || !key.keyId?.trim() || !key.ownerId?.trim()) {
17
+ throw denied(401, "api_key.invalid", "Invalid API key");
18
+ }
19
+ if (!Number.isSafeInteger(key.expiresAt) || key.expiresAt <= Date.now()) {
20
+ throw denied(401, "api_key.expired", "An unexpired API key with a finite expiry is required");
21
+ }
22
+ if (!Array.isArray(key.scopes) || !requiredScopes.every((scope) => key.scopes.includes(scope))) {
23
+ throw denied(403, "api_key.insufficient_scope", `API key requires scopes: ${requiredScopes.join(", ")}`);
24
+ }
25
+ const identity = await options.resolveIdentity(key);
26
+ if (!identity) throw denied(401, "api_key.invalid_owner", "API key owner is unavailable");
27
+ const claim = await options.claimRequest(key, crypto.randomUUID());
28
+ if (claim.allowed !== true) {
29
+ const headers = new Headers();
30
+ if (Number.isFinite(claim.retryAfterSeconds) && claim.retryAfterSeconds > 0) {
31
+ headers.set("Retry-After", String(Math.ceil(claim.retryAfterSeconds)));
32
+ }
33
+ throw denied(429, "api_key.request_limit_exceeded", "API key request limit exceeded", headers);
34
+ }
35
+ if (key.expiresAt <= Date.now()) {
36
+ throw denied(401, "api_key.expired", "API key expired during authorization");
37
+ }
38
+ return identity;
39
+ };
40
+ }
41
+ function denied(status, code, error, headers) {
42
+ return Response.json({ error, code }, { status, headers });
43
+ }
44
+
45
+ // src/platform/agent-keys.ts
46
+ var PLATFORM_KEY_PREFIX = "sk-tan-";
47
+ var PLATFORM_AGENT_KEY_PROVISIONER = "agent-signup";
48
+ var DEFAULT_CACHE_TTL_MS = 3e4;
49
+ var MAX_CACHE_TTL_MS = 12e4;
50
+ var MAX_CACHE_ENTRIES = 1e3;
51
+ var VERIFY_TIMEOUT_MS = 1e4;
52
+ var BUDGET_REASONS = /* @__PURE__ */ new Set(["budget_exhausted", "monthly_budget_exhausted"]);
53
+ var SCOPE_REASONS = /* @__PURE__ */ new Set(["verify_product_not_permitted", "product_mismatch"]);
54
+ function platformKeyRefusal(reason) {
55
+ if (reason === "paid_access_required") {
56
+ return { ok: false, status: 402, code: "agent_key.payment_required", message: "The key owner's Tangle account has no credit. Add credits at id.tangle.tools/app/billing." };
57
+ }
58
+ if (typeof reason === "string" && BUDGET_REASONS.has(reason)) {
59
+ return { ok: false, status: 402, code: "agent_key.budget_exhausted", message: "The key reached the spend cap its owner approved." };
60
+ }
61
+ if (typeof reason === "string" && SCOPE_REASONS.has(reason)) {
62
+ return { ok: false, status: 403, code: "agent_key.product_not_granted", message: "The key's owner did not approve it for this product." };
63
+ }
64
+ if (reason === "email_verification_required") {
65
+ return { ok: false, status: 403, code: "agent_key.owner_unverified", message: "The key owner must verify their Tangle email." };
66
+ }
67
+ return { ok: false, status: 401, code: "agent_key.invalid", message: "The key is invalid, revoked or expired." };
68
+ }
69
+ async function cacheKey(rawKey) {
70
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(rawKey));
71
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
72
+ }
73
+ function nonEmptyString(value) {
74
+ return typeof value === "string" && value.trim() ? value : null;
75
+ }
76
+ function createPlatformAgentKeyVerifier(options) {
77
+ const fetchImpl = options.fetch ?? fetch;
78
+ const now = options.now ?? (() => Date.now());
79
+ const ttl = Math.max(0, Math.min(options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS, MAX_CACHE_TTL_MS));
80
+ const base = options.platformUrl.replace(/\/+$/, "");
81
+ const cache = /* @__PURE__ */ new Map();
82
+ return {
83
+ async verify(rawKey) {
84
+ if (!rawKey.startsWith(PLATFORM_KEY_PREFIX)) return platformKeyRefusal("key_not_found");
85
+ const id = await cacheKey(rawKey);
86
+ const cached = cache.get(id);
87
+ if (cached && cached.validUntil > now()) return cached;
88
+ cache.delete(id);
89
+ const token = typeof options.serviceToken === "function" ? options.serviceToken() : options.serviceToken;
90
+ const response = await fetchImpl(`${base}/v1/keys/verify`, {
91
+ method: "POST",
92
+ headers: {
93
+ authorization: `Bearer ${token}`,
94
+ "x-service-name": options.serviceName,
95
+ "content-type": "application/json"
96
+ },
97
+ body: JSON.stringify({ key: rawKey, expectedProduct: options.product, includeIdentityProfile: true }),
98
+ signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS)
99
+ });
100
+ if (response.status !== 200) {
101
+ await response.body?.cancel().catch(() => {
102
+ });
103
+ throw new Error(`Platform key verification answered HTTP ${response.status}`);
104
+ }
105
+ const body = await response.json();
106
+ if (body.valid !== true) return platformKeyRefusal(body.invalidReason);
107
+ const keyId = nonEmptyString(body.keyId);
108
+ const platformUserId = nonEmptyString(body.userId);
109
+ const email = nonEmptyString(body.email);
110
+ if (!keyId || !platformUserId || !email) {
111
+ throw new Error("Platform key verification omitted the key or owner identity");
112
+ }
113
+ if (body.provisionedByService !== PLATFORM_AGENT_KEY_PROVISIONER) {
114
+ return { ok: false, status: 403, code: "agent_key.not_agent_key", message: "Use a key from Tangle agent signup, or a key created in this app." };
115
+ }
116
+ const scopes = Array.isArray(body.scopes) ? body.scopes.filter((scope) => typeof scope === "string") : [];
117
+ const accepted = {
118
+ ok: true,
119
+ keyId,
120
+ platformUserId,
121
+ email,
122
+ name: nonEmptyString(body.displayName),
123
+ scopes,
124
+ validUntil: now() + ttl
125
+ };
126
+ if (ttl > 0) {
127
+ if (cache.size >= MAX_CACHE_ENTRIES) {
128
+ const oldest = cache.keys().next().value;
129
+ if (oldest !== void 0) cache.delete(oldest);
130
+ }
131
+ cache.set(id, accepted);
132
+ }
133
+ return accepted;
134
+ }
135
+ };
136
+ }
137
+ function agentOperatorScopes(scopes, product, actions) {
138
+ if (scopes.includes("*")) return actions.map((action) => `operator:${action}`);
139
+ const prefix = `${product}:operator:`;
140
+ return actions.filter((action) => scopes.includes(`${prefix}${action}`)).map((action) => `operator:${action}`);
141
+ }
142
+
143
+ export {
144
+ createApiKeyRequestAuth,
145
+ PLATFORM_KEY_PREFIX,
146
+ PLATFORM_AGENT_KEY_PROVISIONER,
147
+ platformKeyRefusal,
148
+ createPlatformAgentKeyVerifier,
149
+ agentOperatorScopes
150
+ };
151
+ //# sourceMappingURL=chunk-XB4KZVUV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/platform/api-key-auth.ts","../src/platform/agent-keys.ts"],"sourcesContent":["/** 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","/**\n * Platform agent keys at an agent app's own API.\n *\n * One owner approval on id.tangle.tools gives an AI agent one key for every\n * product it asked for (`provisionedByService: agent-signup`). An agent app\n * accepts that key by asking Platform's key verification about it for the\n * app's own product: Platform refuses a key whose scopes do not name the\n * product, a revoked or expired key, an unfunded owner, and a spent cap, so\n * the app inherits revocation and the shared spend cap without storing the key.\n *\n * Accepted answers are cached for a short TTL (default 30 seconds) so a burst\n * of operator calls costs one verification; refusals are never cached, so a\n * revocation takes effect within one TTL. Any failure to reach Platform throws,\n * and callers answer 503: an unverifiable key is never admitted.\n *\n * Web-standard fetch and SubtleCrypto only, so it runs in Workers and Node.\n */\n\nexport const PLATFORM_KEY_PREFIX = 'sk-tan-'\n\n/** `provisionedByService` of keys minted by Platform agent signup. */\nexport const PLATFORM_AGENT_KEY_PROVISIONER = 'agent-signup'\n\nconst DEFAULT_CACHE_TTL_MS = 30_000\nconst MAX_CACHE_TTL_MS = 120_000\nconst MAX_CACHE_ENTRIES = 1_000\nconst VERIFY_TIMEOUT_MS = 10_000\n\nexport type PlatformAgentKeyVerification =\n | {\n ok: true\n keyId: string\n /** The owner's stable Platform user id. */\n platformUserId: string\n email: string\n name: string | null\n /** Every scope the key holds, across all products. */\n scopes: string[]\n /** Unix ms after which this answer must be asked again. */\n validUntil: number\n }\n | { ok: false; status: 401 | 402 | 403; code: string; message: string }\n\nexport interface PlatformAgentKeyVerifier {\n verify(rawKey: string): Promise<PlatformAgentKeyVerification>\n}\n\nexport interface PlatformAgentKeyVerifierOptions {\n /** Platform origin, e.g. `https://id.tangle.tools`. */\n platformUrl: string\n /** This app's Platform service name (one of Platform's verify-allowed services). */\n serviceName: string\n serviceToken: string | (() => string)\n /** The Platform product this app verifies for, e.g. `gtm-agent`. */\n product: string\n cacheTtlMs?: number\n fetch?: typeof fetch\n now?: () => number\n}\n\ninterface PlatformVerifyResponse {\n valid?: unknown\n keyId?: unknown\n userId?: unknown\n email?: unknown\n displayName?: unknown\n scopes?: unknown\n provisionedByService?: unknown\n invalidReason?: unknown\n}\n\nconst BUDGET_REASONS = new Set(['budget_exhausted', 'monthly_budget_exhausted'])\nconst SCOPE_REASONS = new Set(['verify_product_not_permitted', 'product_mismatch'])\n\n/** The typed refusal for a Platform rejection reason. */\nexport function platformKeyRefusal(reason: unknown): Extract<PlatformAgentKeyVerification, { ok: false }> {\n if (reason === 'paid_access_required') {\n return { ok: false, status: 402, code: 'agent_key.payment_required', message: \"The key owner's Tangle account has no credit. Add credits at id.tangle.tools/app/billing.\" }\n }\n if (typeof reason === 'string' && BUDGET_REASONS.has(reason)) {\n return { ok: false, status: 402, code: 'agent_key.budget_exhausted', message: 'The key reached the spend cap its owner approved.' }\n }\n if (typeof reason === 'string' && SCOPE_REASONS.has(reason)) {\n return { ok: false, status: 403, code: 'agent_key.product_not_granted', message: \"The key's owner did not approve it for this product.\" }\n }\n if (reason === 'email_verification_required') {\n return { ok: false, status: 403, code: 'agent_key.owner_unverified', message: 'The key owner must verify their Tangle email.' }\n }\n return { ok: false, status: 401, code: 'agent_key.invalid', message: 'The key is invalid, revoked or expired.' }\n}\n\nasync function cacheKey(rawKey: string): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(rawKey))\n return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction nonEmptyString(value: unknown): string | null {\n return typeof value === 'string' && value.trim() ? value : null\n}\n\nexport function createPlatformAgentKeyVerifier(options: PlatformAgentKeyVerifierOptions): PlatformAgentKeyVerifier {\n const fetchImpl = options.fetch ?? fetch\n const now = options.now ?? (() => Date.now())\n const ttl = Math.max(0, Math.min(options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS, MAX_CACHE_TTL_MS))\n const base = options.platformUrl.replace(/\\/+$/, '')\n const cache = new Map<string, Extract<PlatformAgentKeyVerification, { ok: true }>>()\n\n return {\n async verify(rawKey) {\n if (!rawKey.startsWith(PLATFORM_KEY_PREFIX)) return platformKeyRefusal('key_not_found')\n const id = await cacheKey(rawKey)\n const cached = cache.get(id)\n if (cached && cached.validUntil > now()) return cached\n cache.delete(id)\n\n const token = typeof options.serviceToken === 'function' ? options.serviceToken() : options.serviceToken\n const response = await fetchImpl(`${base}/v1/keys/verify`, {\n method: 'POST',\n headers: {\n authorization: `Bearer ${token}`,\n 'x-service-name': options.serviceName,\n 'content-type': 'application/json',\n },\n body: JSON.stringify({ key: rawKey, expectedProduct: options.product, includeIdentityProfile: true }),\n signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),\n })\n // A refused key answers 200 with valid:false. Anything else means the\n // verification itself failed, and an unverified key is never admitted.\n if (response.status !== 200) {\n await response.body?.cancel().catch(() => {})\n throw new Error(`Platform key verification answered HTTP ${response.status}`)\n }\n const body = (await response.json()) as PlatformVerifyResponse\n if (body.valid !== true) return platformKeyRefusal(body.invalidReason)\n\n const keyId = nonEmptyString(body.keyId)\n const platformUserId = nonEmptyString(body.userId)\n const email = nonEmptyString(body.email)\n if (!keyId || !platformUserId || !email) {\n throw new Error('Platform key verification omitted the key or owner identity')\n }\n // Only an agent-signup key carries operator scopes for agent apps; any\n // other Platform key is not an agent credential for this API.\n if (body.provisionedByService !== PLATFORM_AGENT_KEY_PROVISIONER) {\n return { ok: false, status: 403, code: 'agent_key.not_agent_key', message: 'Use a key from Tangle agent signup, or a key created in this app.' }\n }\n const scopes = Array.isArray(body.scopes) ? body.scopes.filter((scope): scope is string => typeof scope === 'string') : []\n const accepted = {\n ok: true as const,\n keyId,\n platformUserId,\n email,\n name: nonEmptyString(body.displayName),\n scopes,\n validUntil: now() + ttl,\n }\n if (ttl > 0) {\n if (cache.size >= MAX_CACHE_ENTRIES) {\n const oldest = cache.keys().next().value\n if (oldest !== undefined) cache.delete(oldest)\n }\n cache.set(id, accepted)\n }\n return accepted\n },\n }\n}\n\n/**\n * The operator scopes an agent key grants at `product`: each\n * `<product>:operator:<action>` becomes `operator:<action>`, and `*` grants\n * every action.\n */\nexport function agentOperatorScopes(scopes: readonly string[], product: string, actions: readonly string[]): string[] {\n if (scopes.includes('*')) return actions.map((action) => `operator:${action}`)\n const prefix = `${product}:operator:`\n return actions.filter((action) => scopes.includes(`${prefix}${action}`)).map((action) => `operator:${action}`)\n}\n"],"mappings":";AAyBO,SAAS,wBACd,SACgD;AAChD,SAAO,OAAO,YAAY;AACxB,UAAM,gBAAgB,QAAQ,QAAQ,IAAI,eAAe;AACzD,QAAI,kBAAkB,KAAM,QAAO;AACnC,UAAM,SAAS,mBAAmB,KAAK,aAAa;AACpD,QAAI,CAAC,QAAQ;AACX,YAAM,OAAO,KAAK,mBAAmB,iBAAiB;AAAA,IACxD;AACA,UAAM,gBAAgB,QAAQ,cAAc,OAAO;AACnD,UAAM,iBAAiB,OAAO,kBAAkB,WAAW,CAAC,aAAa,IAAI,MAAM,KAAK,iBAAiB,CAAC,CAAC;AAC3G,QAAI,CAAC,gBAAgB,UAAU,CAAC,eAAe,MAAM,WAAS,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,GAAG;AACxG,YAAM,OAAO,KAAK,wBAAwB,8CAA8C;AAAA,IAC1F;AACA,UAAM,MAAM,MAAM,QAAQ,OAAO,UAAU,OAAO,CAAC,CAAC,EAAE;AACtD,QAAI,CAAC,OAAO,CAAC,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,SAAS,KAAK,GAAG;AACtD,YAAM,OAAO,KAAK,mBAAmB,iBAAiB;AAAA,IACxD;AACA,QAAI,CAAC,OAAO,cAAc,IAAI,SAAS,KAAK,IAAI,aAAa,KAAK,I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AM,QAAQ,KAAK,MAAM,IAAI,KAAK,OAAO,OAAO,CAAC,UAA2B,OAAO,UAAU,QAAQ,IAAI,CAAC;AACzH,YAAM,WAAW;AAAA,QACf,IAAI;AAAA,QACJ;AAAA,QACA;AAAA,QACA;AAAA,QACA,MAAM,eAAe,KAAK,WAAW;AAAA,QACrC;AAAA,QACA,YAAY,IAAI,IAAI;AAAA,MACtB;AACA,UAAI,MAAM,GAAG;AACX,YAAI,MAAM,QAAQ,mBAAmB;AACnC,gBAAM,SAAS,MAAM,KAAK,EAAE,KAAK,EAAE;AACnC,cAAI,WAAW,OAAW,OAAM,OAAO,MAAM;AAAA,QAC/C;AACA,cAAM,IAAI,IAAI,QAAQ;AAAA,MACxB;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACF;AAOO,SAAS,oBAAoB,QAA2B,SAAiB,SAAsC;AACpH,MAAI,OAAO,SAAS,GAAG,EAAG,QAAO,QAAQ,IAAI,CAAC,WAAW,YAAY,MAAM,EAAE;AAC7E,QAAM,SAAS,GAAG,OAAO;AACzB,SAAO,QAAQ,OAAO,CAAC,WAAW,OAAO,SAAS,GAAG,MAAM,GAAG,MAAM,EAAE,CAAC,EAAE,IAAI,CAAC,WAAW,YAAY,MAAM,EAAE;AAC/G;","names":[]}
@@ -7,7 +7,7 @@ import {
7
7
  import {
8
8
  normalizeClientTurnId,
9
9
  resolveChatTurn
10
- } from "./chunk-53K4S3K6.js";
10
+ } from "./chunk-YG66IHDU.js";
11
11
  import {
12
12
  coalesceDeltas,
13
13
  createBufferedTurnTap,
@@ -1082,4 +1082,4 @@ export {
1082
1082
  createChatTurnRoutes,
1083
1083
  streamChatRouteAsSandboxEvents
1084
1084
  };
1085
- //# sourceMappingURL=chunk-FNRUXPXE.js.map
1085
+ //# sourceMappingURL=chunk-XPTYP3FP.js.map
@@ -0,0 +1,80 @@
1
+ // src/stream/turn-identity.ts
2
+ function normalizeClientTurnId(value) {
3
+ if (value === void 0 || value === null) return void 0;
4
+ if (typeof value !== "string") throw new Error("turnId must be a string");
5
+ const trimmed = value.trim();
6
+ if (!trimmed) throw new Error("turnId must not be blank");
7
+ if (trimmed.length > 160) throw new Error("turnId is too long");
8
+ if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {
9
+ throw new Error("turnId contains unsupported characters");
10
+ }
11
+ return trimmed;
12
+ }
13
+ function buildUserTextParts(text, turnId) {
14
+ const part = { type: "text", text };
15
+ if (turnId) part.turnId = turnId;
16
+ return [part];
17
+ }
18
+ function messageHasTurnId(message, turnId) {
19
+ for (const part of message.parts ?? []) {
20
+ if (part && typeof part === "object" && "turnId" in part && String(part.turnId ?? "") === turnId) {
21
+ return true;
22
+ }
23
+ }
24
+ return false;
25
+ }
26
+ function resolveChatTurn(input) {
27
+ const { existingMessages, userContent, turnId } = input;
28
+ const reusableIndex = findReusableUserMessageIndex(
29
+ existingMessages,
30
+ userContent,
31
+ turnId,
32
+ input.hasRunningTurn === true
33
+ );
34
+ if (reusableIndex >= 0) {
35
+ const reusedId = existingMessages[reusableIndex]?.id;
36
+ const priorMessages = existingMessages.slice(0, reusableIndex);
37
+ return {
38
+ turnIndex: countUserMessages(priorMessages),
39
+ shouldInsertUserMessage: false,
40
+ priorMessages,
41
+ userParts: buildUserTextParts(userContent, turnId),
42
+ ...typeof reusedId === "string" && reusedId ? { reusedUserMessageId: reusedId } : {}
43
+ };
44
+ }
45
+ return {
46
+ turnIndex: countUserMessages(existingMessages),
47
+ shouldInsertUserMessage: true,
48
+ priorMessages: existingMessages.slice(),
49
+ userParts: buildUserTextParts(userContent, turnId)
50
+ };
51
+ }
52
+ function findReusableUserMessageIndex(messages, userContent, turnId, hasRunningTurn) {
53
+ if (turnId) {
54
+ for (let index2 = messages.length - 1; index2 >= 0; index2 -= 1) {
55
+ const message = messages[index2];
56
+ if (message?.role === "user" && messageHasTurnId(message, turnId)) return index2;
57
+ }
58
+ return -1;
59
+ }
60
+ let index = messages.length - 1;
61
+ if (hasRunningTurn) {
62
+ while (index >= 0 && messages[index]?.role === "assistant") index -= 1;
63
+ }
64
+ const latest = index >= 0 ? messages[index] : void 0;
65
+ if (latest?.role === "user" && latest.content === userContent) return index;
66
+ return -1;
67
+ }
68
+ function countUserMessages(messages) {
69
+ let count = 0;
70
+ for (const message of messages) if (message.role === "user") count++;
71
+ return count;
72
+ }
73
+
74
+ export {
75
+ normalizeClientTurnId,
76
+ buildUserTextParts,
77
+ messageHasTurnId,
78
+ resolveChatTurn
79
+ };
80
+ //# sourceMappingURL=chunk-YG66IHDU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stream/turn-identity.ts"],"sourcesContent":["import type { JsonRecord } from './stream-normalizer'\n\n/** Minimum read-only shape; typed chat parts need no dictionary index signature. */\ninterface TurnIdentityMessage {\n readonly id: string\n readonly role: 'user' | 'assistant' | 'system' | 'tool'\n readonly content: string\n readonly parts: readonly object[] | null\n}\n\n/** Retained compatibility shape for callers using unstructured message records. */\nexport interface PersistedChatMessageForTurn extends TurnIdentityMessage {\n id: string\n role: TurnIdentityMessage['role']\n content: string\n parts: Array<Record<string, unknown>> | null\n}\n\n/** Represent a chat turn with resolved user message insertion and prior message context */\nexport interface ResolvedChatTurn<Message extends TurnIdentityMessage = PersistedChatMessageForTurn> {\n turnIndex: number\n shouldInsertUserMessage: boolean\n priorMessages: Message[]\n userParts: JsonRecord[]\n /** The id of the user row this turn REUSES (retry dedup), when one was\n * found. Absent on the insert path, where no row exists yet.\n *\n * The reused row is deliberately EXCLUDED from `priorMessages` (it is this\n * turn's own user message, not prior context), so this field is the only\n * way a caller can name it. */\n reusedUserMessageId?: string\n}\n\n/** Normalize and validate a client turn ID string ensuring it meets format and length requirements */\nexport function normalizeClientTurnId(value: unknown): string | undefined {\n if (value === undefined || value === null) return undefined\n if (typeof value !== 'string') throw new Error('turnId must be a string')\n const trimmed = value.trim()\n if (!trimmed) throw new Error('turnId must not be blank')\n if (trimmed.length > 160) throw new Error('turnId is too long')\n if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {\n throw new Error('turnId contains unsupported characters')\n }\n return trimmed\n}\n\n/** Build an array of text parts with optional turn ID for user input */\nexport function buildUserTextParts(text: string, turnId: string | undefined): JsonRecord[] {\n const part: JsonRecord = { type: 'text', text }\n if (turnId) part.turnId = turnId\n return [part]\n}\n\n/** Resolve whether a message contains any part with the specified turn ID */\nexport function messageHasTurnId(message: Pick<TurnIdentityMessage, 'parts'>, turnId: string): boolean {\n for (const part of message.parts ?? []) {\n if (part && typeof part === 'object' && 'turnId' in part && String(part.turnId ?? '') === turnId) {\n return true\n }\n }\n return false\n}\n\n/** Resolve a chat turn by determining message reuse and constructing user message parts */\nexport function resolveChatTurn<Message extends TurnIdentityMessage>(input: {\n existingMessages: readonly Message[]\n userContent: string\n turnId?: string\n /** True when the thread has a turn still RUNNING in the turn-event buffer\n * (`turnStore.listRunning(threadId)`).\n *\n * Without incremental persistence the trailing row of a thread mid-turn is\n * always the user row, so the content fallback below could assume it. With\n * incremental persistence the assistant row lands seconds into the turn, so\n * a retry of that same turn finds an ASSISTANT row trailing and would\n * insert a duplicate user row.\n *\n * This flag is the discriminator that keeps both cases right, and it needs\n * no new state: an assistant row trailing a turn that is still running is\n * that turn's in-flight draft (walk past it — this is a retry), whereas an\n * assistant row trailing a SETTLED turn is a completed answer (stop — the\n * user genuinely repeated a message and deserves a new turn). */\n hasRunningTurn?: boolean\n}): ResolvedChatTurn<Message> {\n const { existingMessages, userContent, turnId } = input\n const reusableIndex = findReusableUserMessageIndex(\n existingMessages,\n userContent,\n turnId,\n input.hasRunningTurn === true,\n )\n if (reusableIndex >= 0) {\n // Guarded read: `id` is typed `string`, but these rows come from a product\n // store the shell does not validate, so an adapter that omits it must\n // surface as \"no id\" rather than as the string \"undefined\".\n const reusedId = existingMessages[reusableIndex]?.id\n const priorMessages = existingMessages.slice(0, reusableIndex)\n return {\n turnIndex: countUserMessages(priorMessages),\n shouldInsertUserMessage: false,\n priorMessages,\n userParts: buildUserTextParts(userContent, turnId),\n ...(typeof reusedId === 'string' && reusedId ? { reusedUserMessageId: reusedId } : {}),\n }\n }\n\n return {\n turnIndex: countUserMessages(existingMessages),\n shouldInsertUserMessage: true,\n priorMessages: existingMessages.slice(),\n userParts: buildUserTextParts(userContent, turnId),\n }\n}\n\nfunction findReusableUserMessageIndex(\n messages: readonly TurnIdentityMessage[],\n userContent: string,\n turnId: string | undefined,\n hasRunningTurn: boolean,\n): number {\n if (turnId) {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role === 'user' && messageHasTurnId(message, turnId)) return index\n }\n // A caller-supplied id is authoritative. A different id with identical\n // text is a deliberate new turn, while a transport retry reuses the same\n // id and takes the match above. Falling through to content dedup here lets\n // an unrelated abandoned running row swallow an intentional repeat.\n return -1\n }\n\n // Content fallback for a client that sends no turnId. Only the trailing rows\n // of a turn still RUNNING are walked past (they are that turn's incrementally\n // persisted assistant draft); a settled assistant row still ends the scan, so\n // a user who genuinely repeats a message gets a new turn exactly as before.\n let index = messages.length - 1\n if (hasRunningTurn) {\n while (index >= 0 && messages[index]?.role === 'assistant') index -= 1\n }\n const latest = index >= 0 ? messages[index] : undefined\n if (latest?.role === 'user' && latest.content === userContent) return index\n\n return -1\n}\n\nfunction countUserMessages(messages: readonly TurnIdentityMessage[]): number {\n let count = 0\n for (const message of messages) if (message.role === 'user') count++\n return count\n}\n"],"mappings":";AAkCO,SAAS,sBAAsB,OAAoC;AACxE,MAAI,UAAU,UAAa,UAAU,KAAM,QAAO;AAClD,MAAI,OAAO,UAAU,SAAU,OAAM,IAAI,MAAM,yBAAyB;AACxE,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,OAAM,IAAI,MAAM,0BAA0B;AACxD,MAAI,QAAQ,SAAS,IAAK,OAAM,IAAI,MAAM,oBAAoB;AAC9D,MAAI,CAAC,oBAAoB,KAAK,OAAO,GAAG;AACtC,UAAM,IAAI,MAAM,wCAAwC;AAAA,EAC1D;AACA,SAAO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IAC5E;AAKA,WAAO;AAAA,EACT;AAMA,MAAI,QAAQ,SAAS,SAAS;AAC9B,MAAI,gBAAgB;AAClB,WAAO,SAAS,KAAK,SAAS,KAAK,GAAG,SAAS,YAAa,UAAS;AAAA,EACvE;AACA,QAAM,SAAS,SAAS,IAAI,SAAS,KAAK,IAAI;AAC9C,MAAI,QAAQ,SAAS,UAAU,OAAO,YAAY,YAAa,QAAO;AAEtE,SAAO;AACT;AAEA,SAAS,kBAAkB,UAAkD;AAC3E,MAAI,QAAQ;AACZ,aAAW,WAAW,SAAU,KAAI,QAAQ,SAAS,OAAQ;AAC7D,SAAO;AACT;","names":["index"]}
@@ -1,76 +1,3 @@
1
- // src/stream/turn-identity.ts
2
- function normalizeClientTurnId(value) {
3
- if (value === void 0 || value === null) return void 0;
4
- if (typeof value !== "string") throw new Error("turnId must be a string");
5
- const trimmed = value.trim();
6
- if (!trimmed) throw new Error("turnId must not be blank");
7
- if (trimmed.length > 160) throw new Error("turnId is too long");
8
- if (!/^[A-Za-z0-9:_-]+$/.test(trimmed)) {
9
- throw new Error("turnId contains unsupported characters");
10
- }
11
- return trimmed;
12
- }
13
- function buildUserTextParts(text, turnId) {
14
- const part = { type: "text", text };
15
- if (turnId) part.turnId = turnId;
16
- return [part];
17
- }
18
- function messageHasTurnId(message, turnId) {
19
- for (const part of message.parts ?? []) {
20
- if (part && typeof part === "object" && "turnId" in part && String(part.turnId ?? "") === turnId) {
21
- return true;
22
- }
23
- }
24
- return false;
25
- }
26
- function resolveChatTurn(input) {
27
- const { existingMessages, userContent, turnId } = input;
28
- const reusableIndex = findReusableUserMessageIndex(
29
- existingMessages,
30
- userContent,
31
- turnId,
32
- input.hasRunningTurn === true
33
- );
34
- if (reusableIndex >= 0) {
35
- const reusedId = existingMessages[reusableIndex]?.id;
36
- const priorMessages = existingMessages.slice(0, reusableIndex);
37
- return {
38
- turnIndex: countUserMessages(priorMessages),
39
- shouldInsertUserMessage: false,
40
- priorMessages,
41
- userParts: buildUserTextParts(userContent, turnId),
42
- ...typeof reusedId === "string" && reusedId ? { reusedUserMessageId: reusedId } : {}
43
- };
44
- }
45
- return {
46
- turnIndex: countUserMessages(existingMessages),
47
- shouldInsertUserMessage: true,
48
- priorMessages: existingMessages.slice(),
49
- userParts: buildUserTextParts(userContent, turnId)
50
- };
51
- }
52
- function findReusableUserMessageIndex(messages, userContent, turnId, hasRunningTurn) {
53
- if (turnId) {
54
- for (let index2 = messages.length - 1; index2 >= 0; index2 -= 1) {
55
- const message = messages[index2];
56
- if (message?.role === "user" && messageHasTurnId(message, turnId)) return index2;
57
- }
58
- return -1;
59
- }
60
- let index = messages.length - 1;
61
- if (hasRunningTurn) {
62
- while (index >= 0 && messages[index]?.role === "assistant") index -= 1;
63
- }
64
- const latest = index >= 0 ? messages[index] : void 0;
65
- if (latest?.role === "user" && latest.content === userContent) return index;
66
- return -1;
67
- }
68
- function countUserMessages(messages) {
69
- let count = 0;
70
- for (const message of messages) if (message.role === "user") count++;
71
- return count;
72
- }
73
-
74
1
  // src/stream/turn-observation.ts
75
2
  function parseTurnObservation(value) {
76
3
  if (value === void 0) return {
@@ -162,12 +89,8 @@ async function consumeTurnStream(body, options) {
162
89
  }
163
90
 
164
91
  export {
165
- normalizeClientTurnId,
166
- buildUserTextParts,
167
- messageHasTurnId,
168
- resolveChatTurn,
169
92
  parseTurnObservation,
170
93
  observeTurnEvent,
171
94
  consumeTurnStream
172
95
  };
173
- //# sourceMappingURL=chunk-53K4S3K6.js.map
96
+ //# sourceMappingURL=chunk-YXYQ6MJL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stream/turn-observation.ts"],"sourcesContent":["/** Read-side checkpoints for native chat NDJSON. This never submits or cancels work. */\nexport interface TurnObservation {\n schema: 'turn-observation-v1'\n streamId: string | null\n /** Replay ordinals only. Unsequenced live frames cannot advance this cursor. */\n lastSeq: number\n outcome: 'completed' | 'failed' | null\n replayStatus: string | null\n eventCount: number\n}\n\nexport function parseTurnObservation(value?: unknown): TurnObservation {\n if (value === undefined) return {\n schema: 'turn-observation-v1', streamId: null, lastSeq: 0,\n outcome: null, replayStatus: null, eventCount: 0,\n }\n if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError('Invalid turn observation')\n const v = value as Record<string, unknown>\n if (v.schema !== 'turn-observation-v1'\n || !(v.streamId === null || (typeof v.streamId === 'string' && /^[A-Za-z0-9_-]+$/.test(v.streamId)))\n || !Number.isSafeInteger(v.lastSeq) || Number(v.lastSeq) < 0\n || !Number.isSafeInteger(v.eventCount) || Number(v.eventCount) < 0\n || !(v.outcome === null || v.outcome === 'completed' || v.outcome === 'failed')\n || !(v.replayStatus === null || typeof v.replayStatus === 'string')\n || (v.streamId === null && Number(v.lastSeq) > 0)) throw new TypeError('Invalid turn observation')\n return {\n schema: 'turn-observation-v1', streamId: v.streamId as string | null,\n lastSeq: Number(v.lastSeq), outcome: v.outcome as TurnObservation['outcome'],\n replayStatus: v.replayStatus as string | null, eventCount: Number(v.eventCount),\n }\n}\n\nexport interface TurnObservationUpdate {\n checkpoint: TurnObservation\n /** False only for an already-checkpointed replay ordinal. */\n accepted: boolean\n event: Record<string, unknown>\n}\n\n/** Reduce an observed frame. Ordered replay gaps are errors, not silent lost work. */\nexport function observeTurnEvent(previous: TurnObservation, raw: unknown): TurnObservationUpdate {\n const checkpoint = parseTurnObservation(previous)\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new TypeError('Turn frame must be an object')\n const outer = raw as Record<string, unknown>\n const inner = outer.kind === 'event' ? outer.event : outer\n if (!inner || typeof inner !== 'object' || Array.isArray(inner)) throw new TypeError('Invalid turn event envelope')\n const event = inner as Record<string, unknown>\n if (typeof event.type !== 'string' || !event.type) throw new TypeError('Turn frame requires a type')\n\n // Even a duplicate marker must not switch which execution we are observing.\n if (event.type === 'turn') {\n if (typeof event.turnId !== 'string' || !/^[A-Za-z0-9_-]+$/.test(event.turnId)) throw new TypeError('Invalid stream identity')\n if (checkpoint.streamId !== null && checkpoint.streamId !== event.turnId) throw new Error('Replay stream identity changed')\n checkpoint.streamId = event.turnId\n }\n const seq = outer.seq\n if (seq !== undefined && seq !== -1) {\n if (!Number.isSafeInteger(seq) || Number(seq) < 1) throw new TypeError('Invalid replay ordinal')\n if (checkpoint.streamId === null) throw new Error('Replay ordinal arrived before stream identity')\n if (Number(seq) <= checkpoint.lastSeq) return { checkpoint, accepted: false, event }\n if (Number(seq) !== checkpoint.lastSeq + 1) throw new Error('Replay has a gap; retain the checkpoint and inspect durable history')\n checkpoint.lastSeq = Number(seq)\n } else if (seq === -1 && event.type !== 'turn_status') {\n throw new TypeError('Only a turn-status sentinel may have ordinal -1')\n }\n\n if (event.type === 'error' || event.type === 'session.run.failed') checkpoint.outcome = 'failed'\n if (event.type === 'session.run.completed' && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n if (event.type === 'turn_status') {\n if (typeof event.status !== 'string') throw new TypeError('Turn status requires a value')\n checkpoint.replayStatus = event.status\n if (['error', 'failed', 'aborted', 'cancelled'].includes(event.status)) checkpoint.outcome = 'failed'\n if (['complete', 'completed'].includes(event.status) && checkpoint.outcome !== 'failed') checkpoint.outcome = 'completed'\n }\n checkpoint.eventCount += 1\n return { checkpoint, accepted: true, event }\n}\n\nexport interface ConsumeTurnStreamOptions {\n checkpoint?: TurnObservation\n /** Commit evidence and its checkpoint durably before acknowledging this frame. */\n commit(update: TurnObservationUpdate): Promise<void>\n /** Bound untrusted frame memory, not total run duration or total transcript size. */\n maxFrameBytes?: number\n}\n\n/**\n * Consume one viewing connection. EOF without a terminal event stays incomplete.\n * A disconnect/abort propagates; the last committed checkpoint remains resumable.\n * The caller owns network observation windows separately from execution deadlines.\n */\nexport async function consumeTurnStream(\n body: AsyncIterable<Uint8Array>,\n options: ConsumeTurnStreamOptions,\n): Promise<TurnObservation> {\n const maxFrameBytes = options.maxFrameBytes ?? 4 * 1024 * 1024\n if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes < 1) throw new RangeError('Frame byte limit must be positive')\n let state = parseTurnObservation(options.checkpoint)\n const decoder = new TextDecoder('utf-8', { fatal: true })\n let pending = ''\n let frameBytes = 0\n async function accept(line: string): Promise<void> {\n if (!line.trim()) return\n const update = observeTurnEvent(state, JSON.parse(line))\n if (update.accepted) await options.commit(update)\n state = update.checkpoint\n }\n for await (const chunk of body) {\n // Count bytes before decoding: a malicious unterminated frame cannot grow\n // without bound, and splitting UTF-8 characters across chunks stays valid.\n let start = 0\n for (let end = 0; end < chunk.length; end += 1) {\n if (chunk[end] !== 10) continue\n frameBytes += end - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start, end + 1), { stream: true })\n await accept(pending)\n pending = ''; frameBytes = 0; start = end + 1\n }\n frameBytes += chunk.length - start\n if (frameBytes > maxFrameBytes) throw new RangeError('Turn frame exceeds byte limit')\n pending += decoder.decode(chunk.subarray(start), { stream: true })\n }\n pending += decoder.decode()\n await accept(pending)\n return state\n}\n"],"mappings":";AAWO,SAAS,qBAAqB,OAAkC;AACrE,MAAI,UAAU,OAAW,QAAO;AAAA,IAC9B,QAAQ;AAAA,IAAuB,UAAU;AAAA,IAAM,SAAS;AAAA,IACxD,SAAS;AAAA,IAAM,cAAc;AAAA,IAAM,YAAY;AAAA,EACjD;AACA,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,EAAG,OAAM,IAAI,UAAU,0BAA0B;AAC/G,QAAM,IAAI;AACV,MAAI,EAAE,WAAW,yBACZ,EAAE,EAAE,aAAa,QAAS,OAAO,EAAE,aAAa,YAAY,mBAAmB,KAAK,EAAE,QAAQ,MAC9F,CAAC,OAAO,cAAc,EAAE,OAAO,KAAK,OAAO,EAAE,OAAO,IAAI,KACxD,CAAC,OAAO,cAAc,EAAE,UAAU,KAAK,OAAO,EAAE,UAAU,IAAI,KAC9D,EAAE,EAAE,YAAY,QAAQ,EAAE,YAAY,eAAe,EAAE,YAA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