@tangle-network/agent-app 0.60.31 → 0.60.33

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/agent-surfaces/cli.js +1 -1
  2. package/dist/agent-surfaces/index.js +1 -1
  3. package/dist/assistant/index.js +7 -7
  4. package/dist/chat-react/index.js +3 -3
  5. package/dist/chat-routes/index.js +15 -12
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-routes/turn-routes.d.ts +2 -0
  8. package/dist/chat-routes/wire.d.ts +2 -0
  9. package/dist/chat-store/index.js +4 -4
  10. package/dist/chat-store/parts.d.ts +2 -0
  11. package/dist/{chunk-HWJOTTEI.js → chunk-4EVEBEJX.js} +9 -4
  12. package/dist/chunk-4EVEBEJX.js.map +1 -0
  13. package/dist/{chunk-FCON65I2.js → chunk-6VQCFJWP.js} +3 -3
  14. package/dist/{chunk-FCON65I2.js.map → chunk-6VQCFJWP.js.map} +1 -1
  15. package/dist/{chunk-XGPINAHY.js → chunk-AVR6CAPX.js} +14 -3
  16. package/dist/chunk-AVR6CAPX.js.map +1 -0
  17. package/dist/{chunk-WTGSLW5X.js → chunk-FPCIJCS3.js} +3 -3
  18. package/dist/chunk-FPCIJCS3.js.map +1 -0
  19. package/dist/{chunk-H6MKILMQ.js → chunk-FZJRATBY.js} +4 -4
  20. package/dist/{chunk-NJA6X7JI.js → chunk-GBGSC42G.js} +2 -2
  21. package/dist/{chunk-GYDFGEJ2.js → chunk-HOZMP3AR.js} +1 -1
  22. package/dist/chunk-HOZMP3AR.js.map +1 -0
  23. package/dist/{chunk-DECJLOS4.js → chunk-TCPRFFZK.js} +2 -2
  24. package/dist/{chunk-6VRVRWYN.js → chunk-UKZMJND6.js} +2 -2
  25. package/dist/{chunk-N56FWDSP.js → chunk-ZGUXI5SI.js} +2 -2
  26. package/dist/interactions/contract.d.ts +3 -1
  27. package/dist/interactions/index.js +2 -2
  28. package/dist/operator/chat-adapter.d.ts +6 -1
  29. package/dist/operator/index.js +4 -2
  30. package/dist/operator/index.js.map +1 -1
  31. package/dist/public-consultation/index.js +6 -6
  32. package/dist/stream/index.js +2 -2
  33. package/dist/web-react/index.js +7 -7
  34. package/package.json +1 -1
  35. package/dist/chunk-GYDFGEJ2.js.map +0 -1
  36. package/dist/chunk-HWJOTTEI.js.map +0 -1
  37. package/dist/chunk-WTGSLW5X.js.map +0 -1
  38. package/dist/chunk-XGPINAHY.js.map +0 -1
  39. /package/dist/{chunk-H6MKILMQ.js.map → chunk-FZJRATBY.js.map} +0 -0
  40. /package/dist/{chunk-NJA6X7JI.js.map → chunk-GBGSC42G.js.map} +0 -0
  41. /package/dist/{chunk-DECJLOS4.js.map → chunk-TCPRFFZK.js.map} +0 -0
  42. /package/dist/{chunk-6VRVRWYN.js.map → chunk-UKZMJND6.js.map} +0 -0
  43. /package/dist/{chunk-N56FWDSP.js.map → chunk-ZGUXI5SI.js.map} +0 -0
@@ -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 let started = await post('/cross-site/device/start', request)\n // Tangle caps the approval emails one owner receives. Past the cap the\n // owner approves from the link the agent hands them instead.\n let emailCapped = false\n if (started.status === 429 && started.body.error === 'owner_notification_throttled' && request.owner_email) {\n emailCapped = true\n delete request.owner_email\n started = await post('/cross-site/device/start', request)\n }\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 if (emailCapped) {\n console.log('Tangle has already sent this owner the most approval emails it allows for now, so none was sent.')\n }\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. When Tangle has already sent that owner the most approval emails it allows, `start` says so and prints the link without emailing it: send it to the owner 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 install = config.install.length > 0 ? ', install the client' : ''\n const description = `Set up ${config.name} for this agent end to end: get a scoped API key with one owner approval${install}, make the first successful call, and verify it.`\n // Signup is step 1; the sections a product has are numbered on from there,\n // so a product with nothing to install reads 1, 2, 3.\n const sections = ([\n ['Install', config.install],\n ['Make the first call', config.firstCall],\n ['Verify it worked', config.verify],\n ] as const).filter(([, steps]) => steps.length > 0)\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 ...sections.flatMap(([title, steps], index) => stepsSection(`## ${index + 2}. ${title}`, steps)),\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAyF9C;AAEA,SAAS,cAAc,QAAsC;AAC3D,QAAM,MAAM,OAAO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,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":[]}
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  mentionKindForPath
3
- } from "./chunk-GYDFGEJ2.js";
3
+ } from "./chunk-HOZMP3AR.js";
4
4
  import {
5
5
  persistedPartToWorkProduct
6
6
  } from "./chunk-ZVEEWGDK.js";
7
7
  import {
8
8
  persistedPartToInteraction
9
- } from "./chunk-FCON65I2.js";
9
+ } from "./chunk-6VQCFJWP.js";
10
10
  import {
11
11
  persistedPartToPlan,
12
12
  planToPersistedPart
@@ -135,4 +135,4 @@ export {
135
135
  buildAttachmentPromptBlock,
136
136
  historyContentWithAttachments
137
137
  };
138
- //# sourceMappingURL=chunk-WTGSLW5X.js.map
138
+ //# sourceMappingURL=chunk-FPCIJCS3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-store/parts.ts"],"sourcesContent":["/**\n * The stored shape of `message.parts` — one typed vocabulary for every part a\n * product persists into a chat transcript. NOT an ad-hoc union reverse-\n * engineered from product schemas; each member is matched field-for-field to\n * its canonical source:\n *\n * - `text` / `reasoning` / `tool`: the persisted projection `/stream`'s\n * `normalizePersistedPart` produces from the harness lane's\n * `message.part.updated` events (ADC sidecar\n * `apps/sidecar/src/events/session-events.ts:56` wraps the canonical part in\n * an `{id, sessionID, messageID}` envelope; the projection strips the\n * session/message ids and keeps the per-segment part id).\n * - `file` / `image` / `step-start` / `step-finish`: the sidecar's canonical\n * `MessagePartSchema` members (ADC\n * `apps/sidecar/src/schemas/agent-schemas.ts:50-154`); `step-finish` carries\n * the harness's per-step usage receipt — tokens\n * `{total, input, output, reasoning, cache{write, read}}` + `cost` — which is\n * also the shape the message-level token/cost columns mirror.\n * - `subtask`: `@tangle-network/agent-interface`'s `SubtaskPart` (a spawned\n * sub-agent task).\n * - `interaction` / `notice`: the persisted-part codecs in\n * `/web-react`'s chat-interactions contract (`interactionToPersistedPart`,\n * `noticePart`) — type-only imports, one source of truth for their statuses\n * and field shapes.\n * - `plan`: the durable-plan projection in `/plans`, derived from the sandbox\n * SDK's authoritative plan lifecycle.\n * - `work_product`: the persisted work-product anchor card in\n * `/work-product`'s contract (`workProductToPersistedPart` /\n * `persistedPartToWorkProduct`) — SYSTEM-authored on the ready transition\n * and updated on a reviewer verdict; no prompt teaches an agent to author\n * one.\n * - `mention`: an `@`-picked reference to a file that already lives in the\n * workspace sandbox (`FileMention` in `/chat-routes`'s wire contract, plus\n * the image/file discriminant). Neither transport lane produces it — the\n * turn route persists it from the request's `mentions` field — but it is a\n * part a product persists into a transcript, so it belongs in this\n * vocabulary rather than in a parallel one.\n *\n * `@tangle-network/agent-interface` exports the canonical wire `Part` union,\n * but its `PartBase` requires the `sessionID`/`messageID` stream envelope that\n * is deliberately NOT persisted, so the stored union is defined here as the\n * envelope-free projection (a type-level coverage check against the peer's\n * `Part['type']` lives in the tests). Contribute-down candidate: if\n * agent-interface grows envelope-free persisted-part types, re-export them\n * here and delete these definitions.\n *\n * Two transport lanes serialize into this SAME stored shape:\n * - harness lane: canonical `message.part.updated` parts, merged/normalized by\n * `/stream` (`mergePersistedPart`, `finalizeAssistantParts`);\n * - router/openai-compat lane: `text_delta`/`tool_call` stream events are\n * mapped INTO canonical part events first (`/runtime`'s `toLoopEvents` +\n * `/stream`'s `normalizeToolEvent`) and then persisted identically — the\n * store never sees a router-specific shape.\n */\n\nimport type { Part as HarnessWirePart } from '@tangle-network/agent-interface'\nimport type {\n ChatInteractionField,\n ChatInteractionStatus,\n InteractionAnswers,\n InteractionPersistedPart,\n NoticeKind,\n NoticePersistedPart,\n} from '../web-react/chat-interactions'\nimport { persistedPartToInteraction } from '../interactions/contract'\nimport {\n persistedPartToWorkProduct,\n type WorkProductPersistedPart,\n} from '../work-product/types'\nimport {\n persistedPartToPlan,\n planToPersistedPart,\n type ChatPlanPersistedPart,\n} from '../plans/index'\n// `./wire` is import-free by construction, so this edge costs the store\n// nothing and keeps ONE image-extension table for the whole mention layer.\nimport {\n mentionKindForPath,\n type ChatAttachmentInput,\n type ChatAttachmentKind,\n type ChatMentionKind,\n type FileMention,\n} from '../chat-routes/wire'\n\nexport type { ChatMentionKind, ChatAttachmentKind }\n\n/** Start/end wall-clock millis, as normalized by `/stream`'s `normalizeTime`. */\nexport interface ChatPartTime {\n start?: number\n end?: number\n}\n\n/** `id` is the harness's per-segment identity; absent on legacy/router parts,\n * which collapse to a single logical text stream. Never invented client-side. */\nexport interface ChatTextPart {\n type: 'text'\n text: string\n id?: string\n}\n\n/** Define a reasoning part of a chat with text content and optional metadata fields */\nexport interface ChatReasoningPart {\n type: 'reasoning'\n text: string\n id?: string\n time?: ChatPartTime\n}\n\n/** Superset of the sidecar's status enum (`pending|running|completed|failed`)\n * and agent-interface's `ToolState` statuses; `error` is the persisted\n * terminal form `/stream`'s `normalizePersistedPart` settles on. */\nexport type ChatToolStatus = 'pending' | 'running' | 'completed' | 'error' | 'failed'\n\n/** Describe the current state and data of a chat tool including status, input, output, and metadata */\nexport interface ChatToolState {\n status: ChatToolStatus\n input?: unknown\n output?: unknown\n error?: string\n title?: string\n metadata?: Record<string, unknown>\n time?: ChatPartTime\n}\n\n/** Define a chat component representing a tool with its state and optional call identifier */\nexport interface ChatToolPart {\n type: 'tool'\n id: string\n tool: string\n callID?: string\n state: ChatToolState\n}\n\n/** Union of the sidecar's legacy (path-based) and AI-SDK (url-based) file\n * shapes; response-side every field besides `type` is optional. `name` is the\n * attachment-flavored display label an uploaded/promoted file carries (see\n * {@link ChatAttachmentPart}) — absent on a harness-emitted file part, which\n * uses `filename`. */\nexport interface ChatFilePart {\n type: 'file'\n id?: string\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n content?: string\n}\n\n/** Define properties for an image part within a chat message including optional metadata fields */\nexport interface ChatImagePart {\n type: 'image'\n filename?: string\n name?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Define a subtask part of a chat with prompt, description, agent, and optional identifier */\nexport interface ChatSubtaskPart {\n type: 'subtask'\n prompt: string\n description: string\n agent: string\n id?: string\n}\n\n/** OpenCode step-boundary marker — no renderable text; preserved so mappers\n * never coerce it into a \"[object Object]\" text part. */\nexport interface ChatStepStartPart {\n type: 'step-start'\n}\n\n/** Per-step usage receipt as the harness reports it (sidecar\n * `StepFinishPartSchema`). The message-level token/cost columns are this\n * shape flattened. */\nexport interface ChatUsageTokens {\n total?: number\n input?: number\n output?: number\n reasoning?: number\n cache?: {\n write?: number\n read?: number\n }\n}\n\n/** Define a chat step finish part indicating completion with optional reason, tokens, and cost */\nexport interface ChatStepFinishPart {\n type: 'step-finish'\n reason?: string\n tokens?: ChatUsageTokens\n cost?: number\n}\n\n/** Persisted human-in-the-loop ask — byte-matches\n * `interactionToPersistedPart` in `/web-react`'s chat-interactions contract. */\nexport interface ChatInteractionPart {\n type: 'interaction'\n id: string\n kind: string\n title: string\n body?: string\n answerSpec: { fields: ChatInteractionField[] }\n status: ChatInteractionStatus\n answers?: InteractionAnswers\n cancelReason?: string\n}\n\n/** Resolve a chat plan part by aliasing it to the persisted chat plan part type */\nexport type ChatPlanPart = ChatPlanPersistedPart\n\n/** Persisted work-product anchor card — byte-matches\n * `workProductToPersistedPart` in `/work-product`'s contract. Written by the\n * PLATFORM on the ready transition (and updated on a verdict); never\n * authored by a prompt. */\nexport type ChatWorkProductPart = WorkProductPersistedPart\n\n/** Persisted one-line transcript notice — byte-matches `noticePart` in\n * `/web-react`'s chat-interactions contract. */\nexport interface ChatNoticePart {\n type: 'notice'\n id: string\n noticeKind: NoticeKind\n text: string\n /** Typed reason for an `error` notice, e.g. the sandbox or upstream error code. */\n code?: string\n}\n\n/**\n * A file the user `@`-mentioned on this turn: a workspace-relative path into\n * the sandbox, never bytes. `type: 'mention'` is its own discriminant\n * precisely so it does NOT collide with the `file`/`image` attachment parts —\n * an attachment carries content the product uploaded, a mention points at\n * something the box already has, and a transcript renders them differently\n * (an inline pill, not an attachment card).\n *\n * `path` is the identity: mentioning one file twice in a turn folds to one\n * part. `turnId` is optional and set by products that rebuild a turn's\n * mentions on retry.\n */\nexport interface ChatMentionPart {\n type: 'mention'\n mentionKind: ChatMentionKind\n path: string\n name: string\n size?: number\n turnId?: string\n}\n\n// The \"byte-matches\" claims above, enforced at compile time: the interaction\n// contract's codec output types and the stored part types must stay mutually\n// assignable, so a codec field added on one side without the other fails here.\ntype MutuallyAssignable<A extends B, B> = A\ntype _CodecEmitsStorableInteractionPart = MutuallyAssignable<InteractionPersistedPart, ChatInteractionPart>\ntype _StoredInteractionPartFeedsCodec = MutuallyAssignable<ChatInteractionPart, InteractionPersistedPart>\ntype _CodecEmitsStorableNoticePart = MutuallyAssignable<NoticePersistedPart, ChatNoticePart>\ntype _StoredNoticePartFeedsCodec = MutuallyAssignable<ChatNoticePart, NoticePersistedPart>\ntype _CodecEmitsStorablePlanPart = MutuallyAssignable<ChatPlanPersistedPart, ChatPlanPart>\ntype _StoredPlanPartFeedsCodec = MutuallyAssignable<ChatPlanPart, ChatPlanPersistedPart>\ntype _CodecEmitsStorableWorkProductPart = MutuallyAssignable<WorkProductPersistedPart, ChatWorkProductPart>\ntype _StoredWorkProductPartFeedsCodec = MutuallyAssignable<ChatWorkProductPart, WorkProductPersistedPart>\n\n/** Represent parts of a chat message including text, reasoning, tools, files, images, subtasks, steps, interactions, notices, plans, and mentions */\nexport type ChatMessagePart =\n | ChatTextPart\n | ChatReasoningPart\n | ChatToolPart\n | ChatFilePart\n | ChatImagePart\n | ChatSubtaskPart\n | ChatStepStartPart\n | ChatStepFinishPart\n | ChatInteractionPart\n | ChatNoticePart\n | ChatPlanPart\n | ChatWorkProductPart\n | ChatMentionPart\n\n/** Every canonical harness wire-part kind must be storable — compile-time\n * guarantee that a new agent-interface part kind cannot silently fall out of\n * the persisted vocabulary. */\nexport type StorableHarnessPartKind = HarnessWirePart['type'] & ChatMessagePart['type']\n\n/**\n * The typed projection at the `/stream` → `/chat-store` boundary. The stream\n * normalizers (`normalizePersistedPart`/`mergePersistedPart`/\n * `finalizeAssistantParts`) deliberately produce untyped `JsonRecord`s — they\n * normalize wire shapes and do not own the stored vocabulary. THIS module\n * owns it, so this is where rows gain the `ChatMessagePart` type: each entry\n * is validated against its kind's required fields and narrowed, junk is\n * dropped, and — enforced by the exhaustiveness check below — no storable\n * kind can silently fall out (the step-finish/interaction trap).\n */\nexport function toChatMessageParts(parts: Array<Record<string, unknown>>): ChatMessagePart[] {\n const out: ChatMessagePart[] = []\n for (const part of parts) {\n const typed = toChatMessagePart(part)\n if (typed) out.push(typed)\n }\n return out\n}\n\nconst str = (value: unknown): value is string => typeof value === 'string'\n\nfunction toChatMessagePart(part: Record<string, unknown>): ChatMessagePart | null {\n if (!part || typeof part !== 'object') return null\n const type = part.type as ChatMessagePart['type'] | undefined\n switch (type) {\n case 'text':\n case 'reasoning':\n return str(part.text) ? (part as unknown as ChatTextPart | ChatReasoningPart) : null\n case 'tool':\n return str(part.id) && str(part.tool) && part.state && typeof part.state === 'object'\n ? (part as unknown as ChatToolPart)\n : null\n case 'file':\n case 'image':\n return part as unknown as ChatFilePart | ChatImagePart\n case 'subtask':\n return str(part.prompt) && str(part.description) && str(part.agent)\n ? (part as unknown as ChatSubtaskPart)\n : null\n case 'step-start':\n return { type: 'step-start' }\n case 'step-finish':\n return part as unknown as ChatStepFinishPart\n case 'interaction':\n return persistedPartToInteraction(part) ? (part as unknown as ChatInteractionPart) : null\n case 'notice':\n return str(part.id) && str(part.noticeKind) && str(part.text)\n ? (part as unknown as ChatNoticePart)\n : null\n case 'plan': {\n const plan = persistedPartToPlan(part)\n return plan ? ({ ...part, ...planToPersistedPart(plan) } as ChatPlanPart) : null\n }\n case 'work_product':\n // Validate via the codec but keep the original row (extra fields the\n // product persisted round-trip, matching the interaction case).\n return persistedPartToWorkProduct(part) ? (part as unknown as ChatWorkProductPart) : null\n case 'mention':\n return isChatMentionPart(part) ? part : null\n case undefined:\n return null\n default: {\n // Compile-time exhaustiveness: a new ChatMessagePart kind that is not\n // handled above makes `type` non-never here and this line fails.\n const _exhaustive: never = type\n void _exhaustive\n return null\n }\n }\n}\n/** Resolve whether a ChatMessagePart is a ChatInteractionPart based on its type property */\nexport function isChatInteractionPart(part: ChatMessagePart): part is ChatInteractionPart {\n return part.type === 'interaction'\n}\n/** Widened to `unknown` — unlike its siblings this guard also runs over raw\n * untyped stored rows (a transcript renderer reads `message.parts` before the\n * typed projection), which is exactly what {@link mentionPartsFromMessageParts}\n * needs. `path` and `name` carry the pill; a row missing either is unrenderable.\n *\n * Mirrors the write contract exactly (`parseFileMention` in `/chat-routes`,\n * then {@link mentionInputToPart}): a blank `name` is rejected there and so is\n * rejected here, and `size` — optional, but typed `number` once present — is\n * type-checked so `'12'` or `null` cannot ride through the guard wearing a\n * type it does not have. Negative sizes are NOT re-rejected: the wire screens\n * them, `mentionInputToPart` trusts its input, and a read guard stricter than\n * what the writer can emit would drop rows it produced itself. */\nexport function isChatMentionPart(part: unknown): part is ChatMentionPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n if (record.size !== undefined && (typeof record.size !== 'number' || !Number.isFinite(record.size))) {\n return false\n }\n return (\n record.type === 'mention' &&\n typeof record.path === 'string' &&\n record.path.length > 0 &&\n typeof record.name === 'string' &&\n record.name.trim().length > 0 &&\n (record.mentionKind === 'image' || record.mentionKind === 'file')\n )\n}\n\n/** Every mention part on one message, in stored order. The projection a\n * transcript renderer runs before deciding which mentions the message text\n * already shows inline (see `segmentMentionContent` in `/web-react`). */\nexport function mentionPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | ReadonlyArray<ChatMessagePart> | null | undefined,\n): ChatMentionPart[] {\n if (!parts) return []\n return (parts as ReadonlyArray<unknown>).filter(isChatMentionPart)\n}\n\n/** A validated wire mention (`parseFileMentions` in `/chat-routes`) as the\n * part the turn route persists. An absent/non-finite `size` is DROPPED rather\n * than stored as `undefined`, so a stored row never carries a key that means\n * nothing. */\nexport function mentionInputToPart(input: FileMention): ChatMentionPart {\n const part: ChatMentionPart = {\n type: 'mention',\n mentionKind: mentionKindForPath(input.path),\n path: input.path,\n name: input.name,\n }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n return part\n}\n\n// ── attachments ──────────────────────────────────────────────────────────\n//\n// An attachment is a file the product uploaded into its own store (vault /\n// object-store) ahead of the turn — content the box did not already have,\n// unlike a `@`-mention. It persists NOT as a new `ChatMessagePart` union\n// member but as an attachment-flavored `file`/`image` part: `type` is the\n// existing `image`/`file` discriminant, with `path` + `name` load-bearing.\n// That reuse is deliberate — a transcript already renders `file`/`image`\n// parts, and `toChatMessagePart` passes them through by cast (fields survive),\n// so an attachment slots into the same stored `parts` array without a parallel\n// vocabulary. These helpers own the input→part projection, the path-keyed\n// stream key, and the agent-facing prompt block, all byte-identical to the gtm\n// source they were lifted from (gtm-agent#618 adoption reproduces its rows and\n// dispatched prompt bytes through them).\n\n/** `image` for any `image/*` mime, `file` for everything else (including an\n * absent/empty mime) — the same split the composer and the persisted-part\n * discriminant both key on. */\nexport function attachmentKindForMime(mime?: string): ChatAttachmentKind {\n return mime?.startsWith('image/') ? 'image' : 'file'\n}\n\n/** Stream/transcript part key for an attachment — ONE declaration, owned by\n * `/stream`'s normalizer (whose `getPartKey` routes path-bearing file/image\n * parts through it). Re-exported here (not redefined) so the root barrel's\n * star-exports of both modules resolve to the same symbol instead of\n * colliding (TS2308 in the dts build). */\nexport { attachmentPartKey } from '../stream/stream-normalizer'\n\n/**\n * Persisted attachment part: structurally an attachment-flavored `ChatFilePart`\n * / `ChatImagePart` (`path` + `name` promoted to required) rather than a\n * separate union member — see the section note above. The index signature keeps\n * it a `Record<string, unknown>` so it drops into the same untyped `parts`\n * arrays every other stored part rides in, and lets the `type`-driven\n * constructors below build it without union-discriminant gymnastics.\n */\nexport interface ChatAttachmentPart {\n type: ChatAttachmentKind\n path: string\n name: string\n size?: number\n mediaType?: string\n turnId?: string\n [key: string]: unknown\n}\n\n/** True for any `image`/`file` part carrying a non-empty string `path`.\n * DELIBERATELY also matches a sidecar path-bearing file part (a mention-style\n * `file` part with only `path`) — the guard is a structural attachment shape,\n * not proof of provenance; a caller that needs to exclude those filters\n * upstream. The `path.length > 0` check diverges from gtm's original guard\n * (which only checked `typeof`), mirroring sibling {@link isChatMentionPart}:\n * read-side robustness against a stored `{type:'file', path:''}` row — which\n * would otherwise render a malformed `(vault: )` pointer line — justifies the\n * small divergence from byte-for-byte gtm parity here; no legitimate write\n * path ever produces an empty `path`. */\nexport function isChatAttachmentPart(part: unknown): part is ChatAttachmentPart {\n if (!part || typeof part !== 'object') return false\n const record = part as Record<string, unknown>\n return (\n (record.type === 'image' || record.type === 'file') &&\n typeof record.path === 'string' &&\n record.path.length > 0\n )\n}\n\n/** Drop absent/empty optional fields rather than persisting `undefined`/`''`\n * — keeps stored parts minimal. */\nexport function attachmentInputToPart(input: ChatAttachmentInput): ChatAttachmentPart {\n const part: ChatAttachmentPart = { type: input.kind, path: input.path, name: input.name }\n if (typeof input.size === 'number' && Number.isFinite(input.size)) part.size = input.size\n if (input.mediaType) part.mediaType = input.mediaType\n return part\n}\n\n/** Every attachment part on one message's stored `parts`, in stored order. */\nexport function attachmentPartsFromMessageParts(\n parts: ReadonlyArray<Record<string, unknown>> | null | undefined,\n): ChatAttachmentPart[] {\n if (!parts) return []\n return parts.filter(isChatAttachmentPart)\n}\n\n/** gtm's exact default header for {@link buildAttachmentPromptBlock} — kept\n * byte-identical because it feeds dispatched prompts (gtm-agent#618\n * reproduces the prompt bytes through this module). Override only with intent. */\nexport const DEFAULT_ATTACHMENT_PROMPT_HEADER =\n 'Attached files (already saved to the workspace vault — read them from these paths):'\n\n/** Same C0-control/DEL sweep as `/chat-routes`'s `resolve-attachments.ts`\n * (kept as a separate literal rather than a shared import — this module is\n * the read side and must stay usable over PERSISTED rows the wire validator\n * never saw). Replaced with a single space, not stripped or collapsed: this\n * is defense-in-depth for legacy/corrupt stored rows that bypassed wire\n * validation, not the primary control — a name/path a `resolveChatAttachments`\n * call validated today never contains one, so this is a no-op on legitimate\n * input and gtm byte-compat holds. */\nconst PROMPT_BLOCK_CONTROL_CHARS = /[\\x00-\\x1F\\x7F]/g\n\n/**\n * The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in `message.content`. Empty array → `''` so callers can append\n * unconditionally. The sole producer of this text: both the current turn's\n * dispatch and history projection ({@link historyContentWithAttachments}) build\n * it from here, so the two can never drift. `header` overrides the first line\n * ({@link DEFAULT_ATTACHMENT_PROMPT_HEADER}); the per-file line format is fixed.\n *\n * Every interpolated `name`/`path` is swept for control characters first\n * (newline/carriage-return/tab included) and each one replaced with a single\n * space — a single-line-per-file guarantee. Without it, a control character\n * riding through on a PERSISTED row (`historyContentWithAttachments` reads\n * whatever is already stored; a legacy or hand-edited row was never re-checked\n * against `resolveChatAttachments`) could inject extra lines — fabricated\n * pointer entries or instructions — into a prompt the agent trusts verbatim.\n * The wire-side validator is the primary control; this is the backstop for\n * rows it never saw.\n */\nexport function buildAttachmentPromptBlock(\n atts: ReadonlyArray<Pick<ChatAttachmentPart, 'name' | 'path'>>,\n header: string = DEFAULT_ATTACHMENT_PROMPT_HEADER,\n): string {\n if (atts.length === 0) return ''\n const clean = (value: string) => value.replace(PROMPT_BLOCK_CONTROL_CHARS, ' ')\n const lines = atts.map((a) => `- ${clean(a.name)} (vault: ${clean(a.path)})`)\n return `\\n\\n${header}\\n${lines.join('\\n')}`\n}\n\n/**\n * History projection for a persisted message: `content` unchanged when it\n * carries no attachment parts, else the block is appended once. The\n * no-double-annotation guarantee holds under the invariant that the block is\n * never persisted INTO `message.content` — it is appended only at read time,\n * by this function and the current turn's dispatch, both sourcing from\n * `attachmentPartsFromMessageParts` — never by content inspection. This\n * function does not (and cannot) detect an already-embedded block by scanning\n * `content` for its text: a message whose stored `content` happens to already\n * contain the block's bytes, alongside attachment parts, still gets the block\n * appended a second time. See the pinned test for that boundary.\n */\nexport function historyContentWithAttachments(\n message: {\n content: string\n parts?: ReadonlyArray<Record<string, unknown>> | null\n },\n header?: string,\n): string {\n const attachmentParts = attachmentPartsFromMessageParts(message.parts)\n if (attachmentParts.length === 0) return message.content\n return `${message.content}${buildAttachmentPromptBlock(attachmentParts, header)}`\n}\n"],"mappings":";;;;;;;;;;;;;;;AAuSO,SAAS,mBAAmB,OAA0D;AAC3F,QAAM,MAAyB,CAAC;AAChC,aAAW,QAAQ,OAAO;AACxB,UAAM,QAAQ,kBAAkB,IAAI;AACpC,QAAI,MAAO,KAAI,KAAK,KAAK;AAAA,EAC3B;AACA,SAAO;AACT;AAEA,IAAM,MAAM,CAAC,UAAoC,OAAO,UAAU;AAElE,SAAS,kBAAkB,MAAuD;AAChF,MAAI,CAAC,QAAQ,OAAO,SAAS,SAAU,QAAO;AAC9C,QAAM,OAAO,KAAK;AAClB,UAAQ,MAAM;AAAA,IACZ,KAAK;AAAA,IACL,KAAK;AACH,aAAO,IAAI,KAAK,IAAI,IAAK,OAAuD;AAAA,IAClF,KAAK;AACH,aAAO,IAAI,KAAK,EAAE,KAAK,IAAI,KAAK,IAAI,KAAK,KAAK,SAAS,OAAO,KAAK,UAAU,WACxE,OACD;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,IAAI,KAAK,MAAM,KAAK,IAAI,KAAK,WAAW,KAAK,IAAI,KAAK,KAAK,IAC7D,OACD;AAAA,IACN,KAAK;AACH,aAAO,EAAE,MAAM,aAAa;AAAA,IAC9B,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,2BAA2B,IAAI,IAAK,OAA0C;AAAA,IACvF,KAAK;AACH,aAAO,IAAI,KAAK,EAAE,KAAK,IAAI,KAA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terAcceptedFiles
17
- } from "./chunk-DECJLOS4.js";
17
+ } from "./chunk-TCPRFFZK.js";
18
18
  import {
19
19
  joinClasses
20
20
  } from "./chunk-L7MB2LLM.js";
@@ -50,7 +50,7 @@ import {
50
50
  } from "./chunk-B7CL7ENS.js";
51
51
  import {
52
52
  attachmentPartsFromMessageParts
53
- } from "./chunk-WTGSLW5X.js";
53
+ } from "./chunk-FPCIJCS3.js";
54
54
  import {
55
55
  cancelStatusFor,
56
56
  fieldAcceptsFreeText,
@@ -60,7 +60,7 @@ import {
60
60
  parseInteractionRequest,
61
61
  persistedPartToInteraction,
62
62
  questionInteractionContentSignature
63
- } from "./chunk-FCON65I2.js";
63
+ } from "./chunk-6VQCFJWP.js";
64
64
  import {
65
65
  parsePlanSubmittedEvent,
66
66
  persistedPartToPlan
@@ -8903,4 +8903,4 @@ export {
8903
8903
  useThinkingSeconds,
8904
8904
  ChatMessages
8905
8905
  };
8906
- //# sourceMappingURL=chunk-H6MKILMQ.js.map
8906
+ //# sourceMappingURL=chunk-FZJRATBY.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  formatBytes
3
- } from "./chunk-GYDFGEJ2.js";
3
+ } from "./chunk-HOZMP3AR.js";
4
4
 
5
5
  // src/chat-routes/binary-sniff.ts
6
6
  var OOXML_WORD_MIME = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
@@ -386,4 +386,4 @@ export {
386
386
  attachmentSizeErrorMessage,
387
387
  attachmentTotalSizeErrorMessage
388
388
  };
389
- //# sourceMappingURL=chunk-NJA6X7JI.js.map
389
+ //# sourceMappingURL=chunk-GBGSC42G.js.map
@@ -231,4 +231,4 @@ export {
231
231
  parseFileMentions,
232
232
  parseChatTurnParts
233
233
  };
234
- //# sourceMappingURL=chunk-GYDFGEJ2.js.map
234
+ //# sourceMappingURL=chunk-HOZMP3AR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/wire.ts"],"sourcesContent":["import { isWorkspaceFileExportable } from '../web/file-export'\nimport type { ReasoningEffort } from '@tangle-network/agent-interface'\n\n/**\n * Wire contract between the chat client (composer + `streamChatTurn`) and the\n * assembled server vertical (`createChatTurnRoutes`). This module must remain\n * browser-safe: `/web-react` re-exports these types into browser bundles, so\n * imports must not reach a Node builtin or an engine package.\n *\n * The client part shape permits an absolute file path until the server converts\n * it to the URL required by the sandbox SDK. It is derived here, not imported,\n * so the client bundle never touches the SDK.\n */\n\nexport interface ChatTurnTextPartInput {\n type: 'text'\n text: string\n}\n\n/** A non-text prompt part the upload route hands back and the client echoes\n * on send. `url` carries an inline `data:` URI for small files; `path` is a\n * sandbox workspace reference for large ones (the >1 MiB gateway body cap\n * makes the two-step upload mandatory). */\nexport interface ChatTurnFilePartInput {\n type: 'image' | 'file'\n filename?: string\n mediaType?: string\n url?: string\n path?: string\n}\n\n/** Resolve input as either a text part or a file part of a chat turn */\nexport type ChatTurnPartInput = ChatTurnTextPartInput | ChatTurnFilePartInput\n\n/** A chat turn's automatic sentinel plus the canonical agent reasoning levels. */\nexport type ChatReasoningEffort = 'auto' | ReasoningEffort\n\n// ── producer stream vocabulary ───────────────────────────────────────────────\n\n/** Represent a text event produced by a source with a fixed type and associated text content */\nexport interface ProducerTextEvent {\n type: 'text'\n text: string\n}\n\n/** Define an event representing reasoning output with a fixed type and associated text */\nexport interface ProducerReasoningEvent {\n type: 'reasoning'\n text: string\n}\n\n/** Represent an event triggered by a producer tool call with its identifier, name, and arguments */\nexport interface ProducerToolCallEvent {\n type: 'tool_call'\n call: {\n toolCallId: string\n toolName: string\n args: Record<string, unknown>\n }\n}\n\n/** Describe the structure of an event representing the result of a producer tool call */\nexport interface ProducerToolResultEvent {\n type: 'tool_result'\n toolCallId: string\n toolName: string\n outcome: {\n ok: boolean\n result?: unknown\n message?: string\n }\n}\n\n/** Describe cumulative provider usage reported by a producer. */\nexport interface ProducerUsageEvent {\n type: 'usage'\n usage: {\n promptTokens: number\n completionTokens: number\n reasoningTokens?: number\n toolTokens?: number\n toolCallCount?: number\n providerCostUsd?: number\n /** Present only when the provider enforced the complete execution budget. */\n budgetEnforced?: boolean\n }\n}\n\n/** Define the structure for a producer notice event with type, id, kind, and text fields */\nexport interface ProducerNoticeEvent {\n type: 'notice'\n id: string\n /** Kept inline with `/interactions`' `NoticeKind` so this file stays import-free. */\n noticeKind: 'warning' | 'auto-declined' | 'error'\n text: string\n /** Typed reason, on an `error` notice. */\n code?: string\n}\n\n/** Represent an error event emitted by a producer containing message, code, and optional details */\nexport interface ProducerErrorEvent {\n type: 'error'\n data: {\n message: string\n code?: string\n details?: Record<string, unknown>\n }\n}\n\n/** Stable raw lifecycle/interaction/plan/route events forwarded unchanged. */\nexport type ProducerPassthroughEventType =\n | 'turn'\n | 'metadata'\n | 'interaction'\n | 'interaction.cancel'\n | 'plan.submitted'\n | 'done'\n | 'warning'\n | 'session.run.started'\n | 'session.run.completed'\n | 'session.run.failed'\n | 'turn_status'\n\n/** Define an event carrying passthrough data with flexible properties for producer communication */\nexport interface ProducerPassthroughEvent {\n type: ProducerPassthroughEventType\n data?: Record<string, unknown>\n /** Route markers and raw passthroughs may carry `turnId`, `status`, `seq`, etc. */\n [key: string]: unknown\n}\n\n/** Represent events emitted by a producer during its operation for processing and handling */\nexport type ProducerWireEvent =\n | ProducerTextEvent\n | ProducerReasoningEvent\n | ProducerToolCallEvent\n | ProducerToolResultEvent\n | ProducerUsageEvent\n | ProducerNoticeEvent\n | ProducerErrorEvent\n | ProducerPassthroughEvent\n\n/** The image/file split an attachment is rendered and persisted under — the\n * same discriminant as {@link ChatMentionKind}, but a distinct name because an\n * attachment carries content the product uploaded (`ChatAttachmentInput`)\n * while a mention points at a file the box already has. Defined HERE (the\n * import-free layer) so `ChatAttachmentInput` can reference it and the client\n * composer imports it without pulling the persisted-part vocabulary;\n * `/chat-store`'s parts module re-exports it alongside the attachment helpers. */\nexport type ChatAttachmentKind = 'image' | 'file'\n\n/** `POST` turn-body entry describing a file already uploaded to the product's\n * store (vault/object-store) — distinct from an inline {@link\n * ChatTurnFilePartInput} (which carries bytes) and from a {@link FileMention}\n * (a sandbox path the box already holds). The route resolves this field with\n * {@link resolveChatAttachments}: every path is re-validated and every size is\n * re-derived from the stored body, so nothing here is trusted as sent. */\nexport interface ChatAttachmentInput {\n path: string\n name: string\n size: number\n mediaType: string\n kind: ChatAttachmentKind\n}\n\n/** POST body for the turn route. `content` may be empty when `parts` carry the\n * message (an image-only send). Product routing fields (workspaceId etc.) ride\n * alongside and are read by the product's `authorize` seam. */\nexport interface ChatTurnRequestPayload {\n threadId: string\n content?: string\n /** Non-text parts from the upload route, echoed back verbatim. */\n parts?: ChatTurnFilePartInput[]\n /** `@`-picked file mentions for this turn — path references into the\n * workspace sandbox, NOT uploads, so they travel in their own field rather\n * than as `parts` entries. A product whose `parts` field is already spoken\n * for (an attachment sentinel) can still send mentions, and mentions\n * persist as their own `ChatMentionPart`s so a retry rebuilds them. The\n * route validates this field with {@link parseFileMentions} and replaces it\n * on the payload with the validated, deduped list. */\n mentions?: FileMention[]\n /** Files uploaded to the product's store ahead of the turn — path\n * references, NOT inline bytes (those ride `parts`). Validated and\n * size-re-derived by {@link resolveChatAttachments} into persistable\n * attachment parts; a product whose `parts` field is spoken for by inline\n * uploads still sends store-backed files here. */\n attachments?: ChatAttachmentInput[]\n model?: string\n effort?: ChatReasoningEffort\n harness?: string\n /** Client-generated idempotency key for the logical turn (retry-safe). */\n turnId?: string\n /** New token for a deliberate retry; reuse it for transport retries of that attempt. */\n retryAttemptId?: string\n [key: string]: unknown\n}\n\n/** `fetch` init for the turn route — the one place the client wire shape is\n * serialized, so composer glue and products never drift from the server's\n * parser. */\nexport function chatTurnRequestInit(payload: ChatTurnRequestPayload): RequestInit {\n return {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(payload),\n }\n}\n\n// ── inline-part byte budget ─────────────────────────────────────────────────\n//\n// The sandbox gateway caps request bodies at 1 MiB; a turn body whose inline\n// `data:` parts exceed it dies at the gateway with an opaque 413. Enforce the\n// budget at the route boundary instead, with headroom for the JSON envelope\n// (same fail-loud-at-the-choke-point style as /sandbox's provision-payload and\n// env-size gates).\n\n/** Define the maximum byte size allowed for inline parts in data processing */\nexport const INLINE_PARTS_MAX_BYTES = 950_000\n\n// ── dispatch (parts[]) budget vocabulary ────────────────────────────────────\n//\n// The default caps `buildDispatchParts` sizes an attachment/mention dispatch\n// against — the sidecar/proxy limits an assembled `parts` array crosses, one\n// step past `INLINE_PARTS_MAX_BYTES` (which gates the raw turn BODY). Grouped\n// here, in the import-free layer, so the numbers are one overridable\n// vocabulary the client can read and a product can tune per call rather than\n// constants buried in the server module. NOTE: these model sidecar/proxy caps,\n// not a product's MIME accept-list or vault bucketing — those are DOMAIN\n// values the product supplies, never defaulted here.\n\n/** Hard cap on the whole `/prompt` request body as it crosses the sandbox\n * proxy — smaller in practice than a raw-file write cap because a dispatch\n * carries several inline parts plus the flattened history in one request. */\nexport const DISPATCH_REQUEST_MAX_BYTES = 1024 * 1024\n\n/** Bytes reserved off the top of {@link DISPATCH_REQUEST_MAX_BYTES} for the\n * JSON structure around the parts array (keys, delimiters, per-part\n * `type`/`filename`/`mediaType` fields) that {@link base64WireLen} does not\n * account for — keeps the inline budget off the exact proxy cap where one\n * stray byte trips the 413. */\nexport const DISPATCH_STRUCTURAL_RESERVE_BYTES = 64 * 1024\n\n/** Sidecar's hard cap on the `parts` array of one prompt request — a dispatch\n * must never assemble more parts than this or the whole turn 400s. */\nexport const DISPATCH_MAX_PARTS = 64\n\n/** Product-side cap on media parts per dispatch (current turn + carried\n * history), well under {@link DISPATCH_MAX_PARTS}. History trimming that keeps\n * a transcript's native media under this is a PRODUCT concern (the pointer\n * block keeps trimmed media reachable); `buildDispatchParts` enforces only the\n * total {@link DISPATCH_MAX_PARTS} cap. */\nexport const DISPATCH_MAX_MEDIA_PARTS = 24\n\n/** Size a base64-encoded string occupies on the wire given the raw\n * (pre-encoding) byte length: base64 packs 3 raw bytes into 4 output\n * characters, rounded up to the next multiple of 4. */\nexport function base64WireLen(byteLen: number): number {\n return Math.ceil(byteLen / 3) * 4\n}\n\n/**\n * Render a raw byte count as a human-readable size (`512B`, `3KB`, `12MB\n * 500KB`). Ported EXACTLY from gtm-agent's `attachment-limits.ts` — byte-\n * identical implementation, not a reinterpretation — so `resolve-attachments`'s\n * and `promote-file-part`'s error strings match gtm's wording verbatim. Lives\n * in the import-free wire layer (not `resolve-attachments.ts` alone) because\n * BOTH the aggregate-cap message here and the per-file oversize message in\n * `promote-file-part.ts` need it; a browser composer wanting the same\n * formatting for a client-side pre-check can also import it with no engine\n * pulled in.\n */\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes}B`\n if (bytes >= 1024 * 1024) {\n const megabytes = Math.floor(bytes / (1024 * 1024))\n const remainder = bytes % (1024 * 1024)\n return remainder === 0 ? `${megabytes}MB` : `${megabytes}MB ${formatBytes(remainder)}`\n }\n return `${Math.round(bytes / 1024)}KB`\n}\n\n/** Represent errors for invalid chat turn inputs with status and code properties */\nexport class ChatTurnInputError extends Error {\n constructor(message: string, readonly status = 400, readonly code = 'INVALID_CHAT_TURN') {\n super(message)\n this.name = 'ChatTurnInputError'\n }\n}\n\nfunction partByteSize(part: ChatTurnPartInput): number {\n let bytes = 0\n if (part.type === 'text') return part.text.length\n if (part.url) bytes += part.url.length\n if (part.path) bytes += part.path.length\n return bytes\n}\n\n/** Calculate the total byte size of an array of chat turn parts */\nexport function promptPartsByteSize(parts: ChatTurnPartInput[]): number {\n return parts.reduce((total, part) => total + partByteSize(part), 0)\n}\n\n/** Throws `ChatTurnInputError` (413) when the parts' inline payload would blow\n * the gateway cap. Path-ref parts are tiny by construction and always pass. */\nexport function assertPromptPartsWithinCap(\n parts: ChatTurnPartInput[],\n maxBytes = INLINE_PARTS_MAX_BYTES,\n): void {\n const total = promptPartsByteSize(parts)\n if (total <= maxBytes) return\n const largest = [...parts].sort((a, b) => partByteSize(b) - partByteSize(a))[0]\n const largestName = largest && largest.type !== 'text' ? largest.filename ?? largest.path ?? largest.type : 'text'\n throw new ChatTurnInputError(\n `Inline prompt parts total ${total}B, over the ${maxBytes}B budget (largest: ${largestName}, ${largest ? partByteSize(largest) : 0}B). ` +\n 'Upload large files through the upload route so they travel as sandbox path references.',\n 413,\n 'PROMPT_PARTS_TOO_LARGE',\n )\n}\n\n// ── file mentions ────────────────────────────────────────────────────────\n//\n// A file mention (`@`-picked in the composer, sandbox-ui#184) is a path\n// reference into the workspace sandbox — no byte upload. These helpers turn\n// a resolved mention list into wire parts and the prompt pointer block that\n// tells the agent where to read them from.\n\n/** A file mention resolved from the composer's `@`-picker: the\n * workspace-relative path plus enough metadata to build a prompt part and\n * pointer text. `path` is the canonical identity — the mention pill's\n * `MentionItem.id` for the file kind (`/web-react`'s `useFileMentions`). */\nexport interface FileMention {\n path: string\n name: string\n size?: number\n}\n\nconst MENTION_IMAGE_MEDIA_TYPES: ReadonlyMap<string, string> = new Map([\n ['.png', 'image/png'],\n ['.jpg', 'image/jpeg'],\n ['.jpeg', 'image/jpeg'],\n ['.gif', 'image/gif'],\n ['.webp', 'image/webp'],\n ['.svg', 'image/svg+xml'],\n ['.bmp', 'image/bmp'],\n ['.heic', 'image/heic'],\n ['.heif', 'image/heif'],\n ['.avif', 'image/avif'],\n])\n\nfunction extensionOf(path: string): string {\n const base = path.split('/').filter(Boolean).pop() ?? path\n const dot = base.lastIndexOf('.')\n return dot > 0 ? base.slice(dot).toLowerCase() : ''\n}\n\n/** The `image/*` mime for a mention path by extension, or `undefined` for\n * anything not in the known image set (dispatched as `type: 'file'`). */\nexport function mediaTypeForMentionPath(path: string): string | undefined {\n return MENTION_IMAGE_MEDIA_TYPES.get(extensionOf(path))\n}\n\n/** The image/file split a mention is rendered and persisted under — the\n * composer pill's icon, the dispatched part's `type`, and\n * `ChatMentionPart.mentionKind` are all this one value. */\nexport type ChatMentionKind = 'image' | 'file'\n\n/** `image` when the path's extension is in the known image set (the same table\n * {@link mediaTypeForMentionPath} reads), `file` otherwise. Exported so a\n * client that needs only the discriminant — a pill icon, a persisted part's\n * `mentionKind` — never re-declares the extension table; two frozen copies of\n * one mime table is how one gains a format and the other doesn't. */\nexport function mentionKindForPath(path: string): ChatMentionKind {\n return mediaTypeForMentionPath(path) ? 'image' : 'file'\n}\n\n/** Define options to resolve mention paths when converting file mentions to parts */\nexport interface FileMentionsToPartsOptions {\n /** Resolve a mention's workspace-relative path to the absolute path the\n * dispatched part should carry (e.g. a host prefixing the in-box vault\n * root). Default: identity — the path travels unchanged. */\n resolvePath?: (path: string) => string\n}\n\n/** Maps resolved file mentions to path-only `ChatTurnFilePartInput`s —\n * `image` vs `file` by extension, and always a `path`, never a `url` (the\n * url/path XOR invariant: a mention is a sandbox path reference, never\n * inline bytes). */\nexport function fileMentionsToParts(\n mentions: readonly FileMention[],\n opts: FileMentionsToPartsOptions = {},\n): ChatTurnFilePartInput[] {\n const resolvePath = opts.resolvePath ?? ((path: string) => path)\n return mentions.map((mention) => {\n const mediaType = mediaTypeForMentionPath(mention.path)\n const part: ChatTurnFilePartInput = {\n type: mediaType ? 'image' : 'file',\n filename: mention.name,\n path: resolvePath(mention.path),\n }\n if (mediaType) part.mediaType = mediaType\n return part\n })\n}\n\n/** The agent-facing pointer block appended to the dispatched prompt — never\n * persisted in message `content`. Empty array → `''` so callers can append\n * unconditionally. This is the sole producer of that text: the current\n * turn's dispatch and any history projection built from the same mention\n * list both route through here, so the two can't drift apart. */\nexport function buildMentionPromptBlock(\n mentions: readonly Pick<FileMention, 'name' | 'path'>[],\n): string {\n if (mentions.length === 0) return ''\n const lines = mentions.map((m) => `- ${m.name} (${m.path})`)\n return `\\n\\nMentioned files — read them from these paths:\\n${lines.join('\\n')}`\n}\n\n// ── mention validation ───────────────────────────────────────────────────\n//\n// This package owns BOTH ends of the mention path contract — it emits paths\n// from `createSandboxFileIndexRoute` and consumes them in `fileMentionsToParts`\n// / `buildMentionPromptBlock` — so the validation belongs here rather than in\n// each app that wires the pair up. A mention names a file that already exists\n// in the sandbox, so validation is a pure path/charset/count check with no\n// I/O: existence is proven later, when the agent reads the path and the turn\n// fails loudly if it is gone.\n\n/** Hard cap on mentions per turn. Bounds the prompt pointer block, the\n * persisted parts, and whatever media budget a dispatch draws from them. */\nexport const MENTION_MAX_COUNT = 16\n\n/** Longest mention display name accepted — bounds the pointer-block text and\n * the transcript pill label. */\nconst MAX_MENTION_NAME_LENGTH = 256\n/** Longest mention path accepted. */\nconst MAX_MENTION_PATH_LENGTH = 1024\n\n/** Represent the result of a sandbox mention path check indicating success or failure with an error message */\nexport type SandboxMentionPathCheck =\n | { succeeded: true }\n | { succeeded: false; error: string }\n\n/**\n * Validate a workspace-relative sandbox mention path. Rejects traversal (a\n * `..` path segment), absolute paths (leading `/`), backslashes, and null\n * bytes — the four ways a path picked in a client can escape the root the\n * index route scanned.\n *\n * Spaces and unicode are deliberately ALLOWED: in-box filenames are arbitrary,\n * and an ASCII-only charset would silently drop real files from a feature\n * whose whole job is naming them.\n */\nexport function validateSandboxMentionPath(path: unknown): SandboxMentionPathCheck {\n if (typeof path !== 'string' || path.length === 0) {\n return { succeeded: false, error: 'mention path must be a non-empty string' }\n }\n if (path.length > MAX_MENTION_PATH_LENGTH) {\n return { succeeded: false, error: `mention path must not exceed ${MAX_MENTION_PATH_LENGTH} characters` }\n }\n if (path.includes('\\0')) {\n return { succeeded: false, error: 'mention path must not contain null bytes' }\n }\n if (path.includes('\\\\')) {\n return { succeeded: false, error: 'mention path must not contain backslashes' }\n }\n if (path.startsWith('/')) {\n return { succeeded: false, error: 'mention path must be workspace-relative, not absolute' }\n }\n if (path.split('/').some((segment) => segment === '..')) {\n return { succeeded: false, error: 'mention path must not contain \"..\" segments' }\n }\n return { succeeded: true }\n}\n\nfunction parseFileMention(value: unknown, index: number): FileMention {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw new ChatTurnInputError(`mentions[${index}] must be an object`)\n }\n const record = value as Record<string, unknown>\n\n const pathCheck = validateSandboxMentionPath(record.path)\n if (!pathCheck.succeeded) throw new ChatTurnInputError(`mentions[${index}]: ${pathCheck.error}`)\n\n if (!isWorkspaceFileExportable(record.path as string)) {\n throw new ChatTurnInputError(`mentions[${index}]: file is not exportable`)\n }\n\n const name = record.name\n if (typeof name !== 'string' || !name.trim()) {\n throw new ChatTurnInputError(`mentions[${index}].name must be a non-empty string`)\n }\n if (name.length > MAX_MENTION_NAME_LENGTH) {\n throw new ChatTurnInputError(`mentions[${index}].name must not exceed ${MAX_MENTION_NAME_LENGTH} characters`)\n }\n\n const size = record.size\n if (size !== undefined) {\n if (typeof size !== 'number' || !Number.isFinite(size)) {\n throw new ChatTurnInputError(`mentions[${index}].size must be a finite number`)\n }\n if (size < 0) {\n throw new ChatTurnInputError(`mentions[${index}].size must not be negative`)\n }\n }\n\n return { path: record.path as string, name, ...(typeof size === 'number' ? { size } : {}) }\n}\n\n/**\n * Validates the untyped `mentions` array off the wire, mirroring\n * {@link parseChatTurnParts}: the typed list, or `ChatTurnInputError` (400)\n * naming the offending entry. Never sanitizes-and-continues — a traversal path\n * is a rejected request, not a trimmed one.\n *\n * A path repeated within one turn is deduped to its first occurrence rather\n * than rejected: mentioning the same file twice is plausible user input, not\n * an attack.\n */\nexport function parseFileMentions(raw: unknown): FileMention[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('mentions must be an array')\n if (raw.length > MENTION_MAX_COUNT) {\n throw new ChatTurnInputError(`mentions must not exceed ${MENTION_MAX_COUNT} entries`)\n }\n\n const mentions: FileMention[] = []\n const seenPaths = new Set<string>()\n for (let index = 0; index < raw.length; index += 1) {\n const mention = parseFileMention(raw[index], index)\n if (seenPaths.has(mention.path)) continue\n seenPaths.add(mention.path)\n mentions.push(mention)\n }\n return mentions\n}\n\n/** Validates the untyped `parts` array off the wire. Returns the typed parts\n * or throws `ChatTurnInputError` (400) naming the offending entry. */\nexport function parseChatTurnParts(raw: unknown): ChatTurnFilePartInput[] {\n if (raw === undefined || raw === null) return []\n if (!Array.isArray(raw)) throw new ChatTurnInputError('parts must be an array')\n return raw.map((entry, index) => {\n const part = entry as Record<string, unknown> | null\n if (!part || typeof part !== 'object') {\n throw new ChatTurnInputError(`parts[${index}] must be an object`)\n }\n if (part.type !== 'image' && part.type !== 'file') {\n throw new ChatTurnInputError(`parts[${index}].type must be 'image' or 'file'`)\n }\n for (const key of ['filename', 'mediaType', 'url', 'path'] as const) {\n if (part[key] !== undefined && typeof part[key] !== 'string') {\n throw new ChatTurnInputError(`parts[${index}].${key} must be a string`)\n }\n }\n if (part.content !== undefined) {\n throw new ChatTurnInputError(`parts[${index}].content is not supported; provide a url or path`)\n }\n\n const url = typeof part.url === 'string' && part.url.length > 0 ? part.url : undefined\n const path = typeof part.path === 'string' && part.path.length > 0 ? part.path : undefined\n if (Boolean(url) === Boolean(path)) {\n throw new ChatTurnInputError(`parts[${index}] requires exactly one url or path`)\n }\n if (path && !path.startsWith('/')) {\n throw new ChatTurnInputError(`parts[${index}].path must be absolute`)\n }\n\n const filename = typeof part.filename === 'string' ? part.filename.trim() : undefined\n if (part.type === 'file' && !filename) {\n throw new ChatTurnInputError(`parts[${index}].filename is required for file parts`)\n }\n return {\n type: part.type,\n ...(filename ? { filename } : {}),\n ...(part.mediaType !== undefined ? { mediaType: part.mediaType as string } : {}),\n ...(url ? { url } : { path: path! }),\n }\n })\n}\n"],"mappings":";;;;;AAwMO,SAAS,oBAAoB,SAA8C;AAChF,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,IAC9C,MAAM,KAAK,UAAU,OAAO;AAAA,EAC9B;AACF;AAWO,IAAM,yBAAyB;AAgB/B,IAAM,6BAA6B,OAAO;AAO1C,IAAM,oCAAoC,KAAK;AAI/C,IAAM,qBAAqB;AAO3B,IAAM,2BAA2B;AAKjC,SAAS,cAAc,SAAyB;AACrD,SAAO,KAAK,KAAK,UAAU,CAAC,IAAI;AAClC;AAaO,SAAS,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KAAK,cAAc,SAAY,EAAE,WAAW,KAAK,UAAoB,IAAI,CAAC;AAAA,MAC9E,GAAI,MAAM,EAAE,IAAI,IAAI,EAAE,KAAY;AAAA,IACpC;AAAA,EACF,CAAC;AACH;","names":[]}
@@ -30,7 +30,7 @@ import {
30
30
  checkAttachmentType,
31
31
  sanitizeAttachmentFileName,
32
32
  sniffBinary
33
- } from "./chunk-NJA6X7JI.js";
33
+ } from "./chunk-GBGSC42G.js";
34
34
  import {
35
35
  snapHarnessToModel,
36
36
  snapModelToHarness
@@ -2081,4 +2081,4 @@ export {
2081
2081
  ComposerModeControls,
2082
2082
  EntryComposer
2083
2083
  };
2084
- //# sourceMappingURL=chunk-DECJLOS4.js.map
2084
+ //# sourceMappingURL=chunk-TCPRFFZK.js.map
@@ -5,7 +5,7 @@ import {
5
5
  interactionFromWireRequest,
6
6
  isSafeInteractionFieldKey,
7
7
  questionInteractionContentSignature
8
- } from "./chunk-FCON65I2.js";
8
+ } from "./chunk-6VQCFJWP.js";
9
9
 
10
10
  // src/interactions/sidecar.ts
11
11
  var DEFAULT_TIMEOUT_MS = 5e3;
@@ -373,4 +373,4 @@ export {
373
373
  mapInteractionRespondFailure,
374
374
  createInteractionAnswerRoute
375
375
  };
376
- //# sourceMappingURL=chunk-6VRVRWYN.js.map
376
+ //# sourceMappingURL=chunk-UKZMJND6.js.map
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  canTransitionInteractionStatus,
3
3
  persistedPartToInteraction
4
- } from "./chunk-FCON65I2.js";
4
+ } from "./chunk-6VQCFJWP.js";
5
5
  import {
6
6
  canTransitionPlanStatus,
7
7
  persistedPartToPlan,
@@ -406,4 +406,4 @@ export {
406
406
  terminalizeDanglingAssistantToolUpdates,
407
407
  encodeEvent
408
408
  };
409
- //# sourceMappingURL=chunk-N56FWDSP.js.map
409
+ //# sourceMappingURL=chunk-ZGUXI5SI.js.map
@@ -150,10 +150,12 @@ export type NoticePersistedPart = {
150
150
  id: string;
151
151
  noticeKind: NoticeKind;
152
152
  text: string;
153
+ /** Typed reason for an `error` notice, e.g. the sandbox or upstream error code. */
154
+ code?: string;
153
155
  };
154
156
  /** Builds the persisted/streamed `notice` part — a one-line transcript notice
155
157
  * explaining an out-of-band event (warning, auto-declined interaction, turn error). */
156
- export declare function noticePart(noticeKind: NoticeKind, id: string, text: string): NoticePersistedPart;
158
+ export declare function noticePart(noticeKind: NoticeKind, id: string, text: string, code?: string): NoticePersistedPart;
157
159
  /** Reads a wire request into the client's pending `ChatInteraction`. */
158
160
  export declare function interactionFromWireRequest(request: InteractionRequestWire): ChatInteraction;
159
161
  /** Builds the persisted/streamed `interaction` part from a wire request. */
@@ -7,7 +7,7 @@ import {
7
7
  mapInteractionRespondFailure,
8
8
  respondToSessionInteraction,
9
9
  validateInteractionAnswerBody
10
- } from "../chunk-6VRVRWYN.js";
10
+ } from "../chunk-UKZMJND6.js";
11
11
  import "../chunk-3NCPXNBZ.js";
12
12
  import "../chunk-TXD5HXLE.js";
13
13
  import {
@@ -34,7 +34,7 @@ import {
34
34
  persistedPartToInteraction,
35
35
  questionInteractionContentSignature,
36
36
  stampInteractionAnswers
37
- } from "../chunk-FCON65I2.js";
37
+ } from "../chunk-6VQCFJWP.js";
38
38
  export {
39
39
  INTERACTION_CANCEL_EVENT,
40
40
  INTERACTION_EVENT,
@@ -11,6 +11,8 @@ export interface ChatOperatorMessage {
11
11
  model?: string | null;
12
12
  servedModel?: string | null;
13
13
  costUsd?: number | null;
14
+ /** The row's product metadata, for a `failureOf` that reads a stamped turn status. */
15
+ metadata?: Record<string, unknown> | null;
14
16
  }
15
17
  export interface ChatOperatorThread {
16
18
  id: string;
@@ -88,7 +90,10 @@ export interface ChatOperatorAdapterOptions<Identity> {
88
90
  read?(ctx: OperatorContext<Identity>, workspaceId: string, assetId: string): Promise<Response | null>;
89
91
  };
90
92
  scorecard?(ctx: OperatorContext<Identity>, workspaceId: string, days: number): Promise<OperatorScorecard>;
91
- /** A reply's failure; defaults to a `turn-failure` notice or an `error` part. */
93
+ /**
94
+ * A reply's failure. Defaults to an `error` notice (the sandbox producer's
95
+ * `errorNotice` mode), a `turn-failure` notice or an `error` part.
96
+ */
92
97
  failureOf?(message: ChatOperatorMessage): {
93
98
  code?: string;
94
99
  message: string;
@@ -532,10 +532,12 @@ function partsOf(message) {
532
532
  }
533
533
  function defaultFailure(message) {
534
534
  for (const part of partsOf(message)) {
535
- const notice = part.type === "notice" && (part.noticeKind === "turn-failure" || part.kind === "turn-failure");
535
+ const errorNotice = part.type === "notice" && part.noticeKind === "error";
536
+ const notice = errorNotice || part.type === "notice" && (part.noticeKind === "turn-failure" || part.kind === "turn-failure");
536
537
  if (!notice && part.type !== "error") continue;
537
538
  const detail = text(part.message) ?? text(part.text) ?? text(part.error) ?? "The turn failed";
538
- return { ...typeof part.code === "string" ? { code: part.code } : {}, message: detail };
539
+ const code = typeof part.code === "string" ? part.code : errorNotice ? "turn.error" : void 0;
540
+ return { ...code ? { code } : {}, message: detail };
539
541
  }
540
542
  return null;
541
543
  }