@tangle-network/agent-app 0.60.115 → 0.60.117

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 (91) hide show
  1. package/dist/VaultPane-OWOPGPXP.js +7 -0
  2. package/dist/assistant/index.js +11 -11
  3. package/dist/chat-react/index.js +4 -4
  4. package/dist/chat-routes/index.js +13 -6
  5. package/dist/chat-routes/index.js.map +1 -1
  6. package/dist/chat-routes/wire.d.ts +3 -1
  7. package/dist/chat-store/index.js +2 -2
  8. package/dist/{chunk-Y4WLCFDZ.js → chunk-2FLSODOX.js} +6 -6
  9. package/dist/{chunk-6XE77PTT.js → chunk-2NHJNINW.js} +1 -1
  10. package/dist/chunk-2NHJNINW.js.map +1 -0
  11. package/dist/{chunk-56GPDCOJ.js → chunk-7DXRHQZO.js} +7 -7
  12. package/dist/chunk-BTEVD7HG.js +198 -0
  13. package/dist/chunk-BTEVD7HG.js.map +1 -0
  14. package/dist/{chunk-RQSYR4AV.js → chunk-CLB4IQEG.js} +5 -5
  15. package/dist/{chunk-F2FH354I.js → chunk-D52LB6UQ.js} +2 -2
  16. package/dist/chunk-FVI2MHUL.js +1152 -0
  17. package/dist/chunk-FVI2MHUL.js.map +1 -0
  18. package/dist/{chunk-4G7HH6WQ.js → chunk-GU7OZFU7.js} +2 -2
  19. package/dist/{chunk-OGDEUCNW.js → chunk-JGLK5RDK.js} +176 -1
  20. package/dist/chunk-JGLK5RDK.js.map +1 -0
  21. package/dist/{chunk-FJQUMIM6.js → chunk-JZUSVGRJ.js} +3 -3
  22. package/dist/{chunk-AB63T2LM.js → chunk-KBJZMR4E.js} +8 -1
  23. package/dist/chunk-KBJZMR4E.js.map +1 -0
  24. package/dist/{chunk-JCSHTJT6.js → chunk-MGON3FE6.js} +22 -3
  25. package/dist/chunk-MGON3FE6.js.map +1 -0
  26. package/dist/{chunk-RQSNTJTW.js → chunk-MO7PDQRZ.js} +526 -187
  27. package/dist/chunk-MO7PDQRZ.js.map +1 -0
  28. package/dist/{chunk-MEUNTJL5.js → chunk-N3CYCSKK.js} +6 -1
  29. package/dist/chunk-N3CYCSKK.js.map +1 -0
  30. package/dist/journeys/cli.d.ts +2 -0
  31. package/dist/journeys/cli.js +165 -0
  32. package/dist/journeys/cli.js.map +1 -0
  33. package/dist/journeys/config.d.ts +96 -0
  34. package/dist/journeys/index.d.ts +18 -0
  35. package/dist/journeys/index.js +731 -0
  36. package/dist/journeys/index.js.map +1 -0
  37. package/dist/journeys/journey.d.ts +173 -0
  38. package/dist/journeys/page-reading.d.ts +42 -0
  39. package/dist/journeys/report.d.ts +51 -0
  40. package/dist/journeys/score.d.ts +115 -0
  41. package/dist/journeys/scrub.d.ts +21 -0
  42. package/dist/journeys/send.d.ts +46 -0
  43. package/dist/journeys/session.d.ts +27 -0
  44. package/dist/journeys/trace-zip.d.ts +28 -0
  45. package/dist/journeys/video.d.ts +53 -0
  46. package/dist/public-consultation/index.d.ts +2 -2
  47. package/dist/public-consultation/index.js +3 -3
  48. package/dist/runtime/index.js +1 -1
  49. package/dist/runtime/router-turn.d.ts +23 -2
  50. package/dist/runtime/router-turn.js +1 -1
  51. package/dist/sandbox/index.d.ts +2 -0
  52. package/dist/sandbox/index.js +13 -1
  53. package/dist/sandbox/sandbox-exec-tool.d.ts +68 -0
  54. package/dist/sandbox/sandbox-run-tool.d.ts +70 -0
  55. package/dist/studio-react/index.js +2 -2
  56. package/dist/teams/index.js +10 -6
  57. package/dist/teams/invitations-api.js +6 -3
  58. package/dist/teams/invitations-api.js.map +1 -1
  59. package/dist/teams/invitations.d.ts +4 -0
  60. package/dist/teams/members-api.js +2 -1
  61. package/dist/teams-react/components/InviteForm.d.ts +20 -0
  62. package/dist/teams-react/contracts.d.ts +2 -0
  63. package/dist/teams-react/index.js +196 -217
  64. package/dist/teams-react/index.js.map +1 -1
  65. package/dist/vault/VaultContentResults.d.ts +29 -0
  66. package/dist/vault/VaultHistoryPanel.d.ts +20 -0
  67. package/dist/vault/VaultPane.d.ts +3 -1
  68. package/dist/vault/contracts.d.ts +38 -0
  69. package/dist/vault/index.js +1 -1
  70. package/dist/vault/lazy.js +1 -1
  71. package/dist/web-react/index.js +25 -25
  72. package/dist/workspace-export/index.js +4 -193
  73. package/dist/workspace-export/index.js.map +1 -1
  74. package/dist/workspace-react/index.js +9 -7
  75. package/dist/workspace-react/index.js.map +1 -1
  76. package/dist/workspace-react/workspace-list.d.ts +7 -1
  77. package/package.json +8 -2
  78. package/dist/VaultPane-JUSNGOV7.js +0 -7
  79. package/dist/chunk-6XE77PTT.js.map +0 -1
  80. package/dist/chunk-AB63T2LM.js.map +0 -1
  81. package/dist/chunk-JCSHTJT6.js.map +0 -1
  82. package/dist/chunk-MEUNTJL5.js.map +0 -1
  83. package/dist/chunk-OGDEUCNW.js.map +0 -1
  84. package/dist/chunk-RQSNTJTW.js.map +0 -1
  85. /package/dist/{VaultPane-JUSNGOV7.js.map → VaultPane-OWOPGPXP.js.map} +0 -0
  86. /package/dist/{chunk-Y4WLCFDZ.js.map → chunk-2FLSODOX.js.map} +0 -0
  87. /package/dist/{chunk-56GPDCOJ.js.map → chunk-7DXRHQZO.js.map} +0 -0
  88. /package/dist/{chunk-RQSYR4AV.js.map → chunk-CLB4IQEG.js.map} +0 -0
  89. /package/dist/{chunk-F2FH354I.js.map → chunk-D52LB6UQ.js.map} +0 -0
  90. /package/dist/{chunk-4G7HH6WQ.js.map → chunk-GU7OZFU7.js.map} +0 -0
  91. /package/dist/{chunk-FJQUMIM6.js.map → chunk-JZUSVGRJ.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/chat-routes/turn-progress.ts","../src/chat-routes/wire.ts"],"sourcesContent":["/**\n * Turn progress: the real stage a chat turn is in, on the turn stream.\n *\n * A turn can spend seconds before its first answer token: authorization, the\n * conversation load, the single-flight lock, the product's pre-turn work, a\n * sandbox, the harness and the model's first token. `session.run.phase` events\n * name those stages as they happen, so a chat shows where the turn is instead\n * of a spinner.\n *\n * A client that sends {@link TURN_PROGRESS_HEADER} gets the response stream as\n * soon as the route has parsed the body and `authorize` has admitted the\n * caller. Authorization never runs inside the stream: every refusal it makes\n * (400, 401, 402, 403, 404, 429) is a plain HTTP response, so an unadmitted\n * caller sees no stage, holds no stream and starts no work. After admission,\n * anything the route answers with a non-stream response (a held lock's 409, a\n * gate's own response, a handoff, a failure) arrives as one\n * {@link TURN_RESPONSE_EVENT} carrying that response's status, headers and\n * body, and {@link settleTurnResponse} turns it back into the `Response` the\n * caller already handles. A client that does not send the header gets exactly\n * the responses it got before.\n *\n * Product work that only an admitted turn may do (resolving its profile and\n * model, any write) belongs in `prepareTurn`, which runs after admission and,\n * on a progress-first stream, inside it with its own named stages.\n * `tests/chat-routes/authorize-before-stream.test.ts` is the gate that keeps\n * every shared route behind its `authorize`.\n *\n * Browser-safe and import-free: the server route and the web client share it.\n */\n\n/** Request header that asks for a progress-first turn stream. */\nexport const TURN_PROGRESS_HEADER = 'x-turn-progress'\n/** The only value of {@link TURN_PROGRESS_HEADER}. The route echoes it on a progress-first response. */\nexport const TURN_PROGRESS_FIRST = 'first'\n\n/** Stream event naming the turn's current stage. Non-terminal and never turn content. */\nexport const TURN_PHASE_EVENT = 'session.run.phase'\n\n/**\n * Stages the shared route emits before the producer runs. Products add their\n * own (a sandbox product emits `provisioning`, `starting`,\n * `awaiting-first-token`).\n * - `accepted`: the caller is admitted; the conversation and the lock are loading.\n * - `preparing`: the turn holds its lock; the product's pre-turn work is running.\n */\nexport type TurnRoutePhase = 'accepted' | 'preparing'\n\n/** The data of a {@link TURN_PHASE_EVENT}. */\nexport type TurnPhaseData = {\n /** Stage id: a {@link TurnRoutePhase} or a product's own stage. */\n phase: string\n /** Text the client shows verbatim. */\n message: string\n /** A keepalive for the current stage rather than a new stage. */\n heartbeat?: boolean\n /** Milliseconds since the current wait began. */\n elapsedMs?: number\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_PHASE_EVENT} as it crosses the wire. */\nexport type TurnPhaseEvent = { type: typeof TURN_PHASE_EVENT; data: TurnPhaseData }\n\n/** Default text for the route's own stages. Products override it through `createChatTurnRoutes({ progressMessages })`. */\nexport const TURN_ROUTE_PHASE_MESSAGES: Record<TurnRoutePhase, string> = {\n accepted: 'Loading your conversation…',\n preparing: 'Preparing the agent…',\n}\n\n/** Build a {@link TURN_PHASE_EVENT}. */\nexport function buildTurnPhaseEvent(\n phase: string,\n message: string,\n opts: { heartbeat?: boolean; elapsedMs?: number; sinceRequestMs?: number } = {},\n): TurnPhaseEvent {\n return {\n type: TURN_PHASE_EVENT,\n data: {\n phase,\n message,\n ...(opts.heartbeat ? { heartbeat: true } : {}),\n ...(typeof opts.elapsedMs === 'number' ? { elapsedMs: opts.elapsedMs } : {}),\n ...(typeof opts.sinceRequestMs === 'number' ? { sinceRequestMs: opts.sinceRequestMs } : {}),\n },\n }\n}\n\n/** True for a {@link TURN_PHASE_EVENT} with a usable `phase` and `message`. */\nexport function isTurnPhaseEvent(event: unknown): event is TurnPhaseEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { phase?: unknown; message?: unknown } }\n return candidate.type === TURN_PHASE_EVENT\n && typeof candidate.data?.phase === 'string'\n && typeof candidate.data?.message === 'string'\n}\n\n/**\n * Stream event carrying the turn's intent line: one plain sentence, written by\n * a fast model call at admission, saying what the agent is about to do (\"Looking\n * at your three competitors' pricing pages, then I'll draft the comparison.\").\n * A client shows it as a labeled status line, never as the answer, until the\n * turn's first answer text replaces it. It narrates intent; it never answers\n * or acts. Non-terminal and never turn content; at most one per turn.\n */\nexport const TURN_INTENT_EVENT = 'session.run.intent'\n\n/** The data of a {@link TURN_INTENT_EVENT}. */\nexport type TurnIntentData = {\n /** The sentence, shown verbatim. */\n text: string\n /** Milliseconds since the server received the request. */\n sinceRequestMs?: number\n}\n\n/** A {@link TURN_INTENT_EVENT} as it crosses the wire. */\nexport type TurnIntentEvent = { type: typeof TURN_INTENT_EVENT; data: TurnIntentData }\n\n/** True for a {@link TURN_INTENT_EVENT} with non-empty text. */\nexport function isTurnIntentEvent(event: unknown): event is TurnIntentEvent {\n if (!event || typeof event !== 'object') return false\n const candidate = event as { type?: unknown; data?: { text?: unknown } }\n return candidate.type === TURN_INTENT_EVENT\n && typeof candidate.data?.text === 'string'\n && candidate.data.text.trim().length > 0\n}\n\n/** Terminal event of a progress-first stream that ended without a turn: the response the route returned instead. */\nexport const TURN_RESPONSE_EVENT = 'turn.response'\n\n/** The data of a {@link TURN_RESPONSE_EVENT}. */\nexport type TurnResponseData = {\n status: number\n /** Response headers other than `set-cookie` and framing headers. */\n headers: Record<string, string>\n body: string\n}\n\n/** Headers a {@link TURN_RESPONSE_EVENT} cannot carry: cookies cannot be set after the stream opened, and framing belongs to the outer response. */\nconst UNCARRIED_HEADERS = new Set(['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'])\n\n/** Error code {@link settleTurnResponse} reports when a progress-first stream closes before the turn started. */\nexport const TURN_STREAM_LOST_CODE = 'turn_stream_lost'\n\n/** Serialize a non-stream response for a {@link TURN_RESPONSE_EVENT}. */\nexport async function turnResponseEventFor(response: Response): Promise<{ type: typeof TURN_RESPONSE_EVENT; data: TurnResponseData }> {\n const headers: Record<string, string> = {}\n response.headers.forEach((value, key) => {\n if (!UNCARRIED_HEADERS.has(key.toLowerCase())) headers[key.toLowerCase()] = value\n })\n return { type: TURN_RESPONSE_EVENT, data: { status: response.status, headers, body: await response.text() } }\n}\n\n/**\n * Settle a turn response for a client that sent {@link TURN_PROGRESS_HEADER}.\n *\n * Reads the stream's leading progress events, handing each to `onPhase` (and an\n * intent line to `onIntent`, or dropping it when there is none), until the\n * first other event. A {@link TURN_RESPONSE_EVENT} resolves to a `Response`\n * with the original status, headers and body, so the caller's existing error\n * handling runs unchanged. Any other event resolves to a `Response` whose body\n * starts at that event and continues with the rest of the stream. A response\n * that is not progress-first is returned as it is.\n */\nexport async function settleTurnResponse(\n response: Response,\n onPhase: (phase: TurnPhaseData) => void,\n onIntent?: (intent: TurnIntentData) => void,\n): Promise<Response> {\n if (response.headers.get(TURN_PROGRESS_HEADER) !== TURN_PROGRESS_FIRST || !response.body) return response\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n const encoder = new TextEncoder()\n let buffer = ''\n let ended = false\n for (;;) {\n let newline = buffer.indexOf('\\n')\n while (newline < 0) {\n if (ended) {\n // The stream closed inside the progress prefix: the turn never started.\n return Response.json(\n { error: 'The connection closed before the turn started. Try again.', code: TURN_STREAM_LOST_CODE },\n { status: 502 },\n )\n }\n const { done, value } = await reader.read()\n if (done) {\n ended = true\n buffer += decoder.decode()\n // A final line without its newline is still a line.\n if (buffer.trim()) buffer += '\\n'\n } else {\n buffer += decoder.decode(value, { stream: true })\n }\n newline = buffer.indexOf('\\n')\n }\n const line = buffer.slice(0, newline).trim()\n if (!line) {\n buffer = buffer.slice(newline + 1)\n continue\n }\n let event: unknown\n try {\n event = JSON.parse(line)\n } catch {\n event = null\n }\n if (isTurnPhaseEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onPhase(event.data)\n continue\n }\n // An intent line is progress too: a response the route answers after it\n // (a held lock's 409) still settles with its own status.\n if (isTurnIntentEvent(event)) {\n buffer = buffer.slice(newline + 1)\n onIntent?.(event.data)\n continue\n }\n const answered = event as { type?: unknown; data?: Partial<TurnResponseData> } | null\n if (answered?.type === TURN_RESPONSE_EVENT && typeof answered.data?.status === 'number') {\n await reader.cancel().catch(() => {})\n return new Response(answered.data.status === 204 || answered.data.status === 304 ? null : String(answered.data.body ?? ''), {\n status: answered.data.status,\n headers: answered.data.headers ?? {},\n })\n }\n return streamFrom(reader, buffer, encoder, response)\n }\n}\n\n/** The rest of a progress-first stream, starting with bytes already read. */\nfunction streamFrom(\n reader: ReadableStreamDefaultReader<Uint8Array>,\n pending: string,\n encoder: TextEncoder,\n original: Response,\n): Response {\n let first = pending\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n if (first) {\n controller.enqueue(encoder.encode(first))\n first = ''\n return\n }\n const { done, value } = await reader.read()\n if (done) controller.close()\n else controller.enqueue(value)\n },\n cancel(reason) {\n return reader.cancel(reason)\n },\n })\n return new Response(body, { status: original.status, headers: original.headers })\n}\n","import { isWorkspaceFileExportable } from '../web/file-export'\nimport { TURN_PROGRESS_FIRST, TURN_PROGRESS_HEADER } from './turn-progress'\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(\n payload: ChatTurnRequestPayload,\n options: { progressFirst?: boolean } = {},\n): RequestInit {\n return {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n // Ask for a progress-first stream (`./turn-progress`); settle the response with `settleTurnResponse`.\n ...(options.progressFirst ? { [TURN_PROGRESS_HEADER]: TURN_PROGRESS_FIRST } : {}),\n },\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"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AAO,KAAK,aAAa,WAAW,KAAK,SAAS,KAAK,IAAI;AAC5E,QAAI,KAAK,SAAS,UAAU,CAAC,UAAU;AACrC,YAAM,IAAI,mBAAmB,SAAS,KAAK,uCAAuC;AAAA,IACpF;AACA,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,MAC/B,GAAI,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":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/teams/invitations.ts"],"sourcesContent":["/**\n * Pure invitation helpers for the teams capability. Zero dependencies: no\n * drizzle, no env, no react, no network. The lifecycle API (`./invitations-api`)\n * and an app's own mail transport build on these; the invitation email itself\n * is `inviteEmail` from `@tangle-network/agent-app/email`.\n */\n\nimport type { AssignableWorkspaceRole } from './roles'\n\n/** The role an invitation grants — the assignable workspace ladder (never owner). */\nexport type InvitationPermission = AssignableWorkspaceRole\n\n/** Define possible states for an invitation's lifecycle including pending, accepted, expired, and revoked */\nexport type InvitationStatus = 'pending' | 'accepted' | 'expired' | 'revoked'\n/** Define possible statuses for the sending state of an invitation email */\nexport type InvitationEmailStatus = 'not_sent' | 'sent' | 'failed'\n\n/** Define the number of days before an invitation expires */\nexport const INVITATION_EXPIRY_DAYS = 7\n\nconst INVITATION_PERMISSIONS = ['admin', 'editor', 'viewer'] as const\nconst TOKEN_BYTE_LENGTH = 32\n\n/** Normalize an invitation email by trimming whitespace and converting to lowercase */\nexport function normalizeInvitationEmail(email: string): string {\n return email.trim().toLowerCase()\n}\n\n/** Resolve invitation permission from a string or return null if invalid */\nexport function parseInvitationPermission(value: string | undefined): InvitationPermission | null {\n return INVITATION_PERMISSIONS.includes(value as InvitationPermission) ? (value as InvitationPermission) : null\n}\n\n/** Calculate the expiration date of an invitation based on the given or current date */\nexport function getInvitationExpiresAt(now: Date = new Date()): Date {\n return new Date(now.getTime() + INVITATION_EXPIRY_DAYS * 24 * 60 * 60 * 1000)\n}\n\n/**\n * A cryptographically-random, URL-safe invitation token. `inv_`-prefixed so a\n * token is self-identifying and never collides with the workspaceMember invite\n * tokens minted by `members-api` (`generateInviteToken`).\n */\nexport function generateInvitationToken(): string {\n const bytes = new Uint8Array(TOKEN_BYTE_LENGTH)\n globalThis.crypto.getRandomValues(bytes)\n const token = Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')\n return `inv_${btoa(token).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/g, '')}`\n}\n\n/** Generate an invite URL by combining the origin with an encoded token */\nexport function inviteUrlForToken(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, '')}/invite/${encodeURIComponent(token)}`\n}\n"],"mappings":";AAkBO,IAAM,yBAAyB;AAEtC,IAAM,yBAAyB,CAAC,SAAS,UAAU,QAAQ;AAC3D,IAAM,oBAAoB;AAGnB,SAAS,yBAAyB,OAAuB;AAC9D,SAAO,MAAM,KAAK,EAAE,YAAY;AAClC;AAGO,SAAS,0BAA0B,OAAwD;AAChG,SAAO,uBAAuB,SAAS,KAA6B,IAAK,QAAiC;AAC5G;AAGO,SAAS,uBAAuB,MAAY,oBAAI,KAAK,GAAS;AACnE,SAAO,IAAI,KAAK,IAAI,QAAQ,IAAI,yBAAyB,KAAK,KAAK,KAAK,GAAI;AAC9E;AAOO,SAAS,0BAAkC;AAChD,QAAM,QAAQ,IAAI,WAAW,iBAAiB;AAC9C,aAAW,OAAO,gBAAgB,KAAK;AACvC,QAAM,QAAQ,MAAM,KAAK,OAAO,CAAC,SAAS,OAAO,aAAa,IAAI,CAAC,EAAE,KAAK,EAAE;AAC5E,SAAO,OAAO,KAAK,KAAK,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,QAAQ,EAAE,CAAC;AACvF;AAGO,SAAS,kBAAkB,QAAgB,OAAuB;AACvE,SAAO,GAAG,OAAO,QAAQ,QAAQ,EAAE,CAAC,WAAW,mBAAmB,KAAK,CAAC;AAC1E;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/runtime/loop.ts","../src/runtime/openai-stream.ts","../src/runtime/turn-knowledge.ts","../src/runtime/router-turn.ts"],"sourcesContent":["/**\n * The bounded agent tool-loop — owned by `@tangle-network/agent-runtime`.\n *\n * A model turn may emit tool calls (integration-hub actions, the app tools from\n * `../tools`, delegation). The loop streams a turn, collects the executable tool\n * calls, dispatches each, appends the results to history in OpenAI\n * function-calling shape, and re-runs so the model reads them — bounded by\n * `maxToolTurns`, a wall-clock `deadlineMs`, and a `maxCostUsd` budget.\n *\n * The history shape is the OpenAI function-calling contract: the assistant turn\n * that emitted tool calls is preserved as an `assistant` message carrying its\n * `tool_calls` array, and each result is its own `{ role: 'tool', tool_call_id,\n * content }` message keyed to the call. A strict model (Claude, and any\n * OpenAI-compatible provider that validates tool history) needs this to read its\n * own tool use back; folding results into a `user` message makes such models\n * re-issue the same call in a loop.\n *\n * The loop is substrate-owned (`runToolLoop` / `streamToolLoop`); the app\n * supplies `streamTurn` (wrapping its model endpoint) and `executeToolCall`\n * (routing to its integration + app-tool executors). The app-facing names below\n * are 1:1 aliases of the canonical symbols, kept so this package's consumers and\n * the in-package `createAgentRuntime` read against a single, stable vocabulary.\n *\n * This is the LEAF the runtime barrel and its children both import — keeping the\n * tool-loop vocabulary out of any import cycle. The barrel re-exports it.\n */\n\nexport {\n runToolLoop as runAppToolLoop,\n streamToolLoop as streamAppToolLoop,\n} from '@tangle-network/agent-runtime/tool-loop'\nexport type {\n ToolLoopCall as LoopToolCall,\n ToolLoopAssistantToolCall as LoopAssistantToolCall,\n ToolLoopMessage as LoopMessage,\n ToolLoopEvent,\n ToolLoopStopReason,\n ToolLoopResult,\n RunToolLoopOptions as AppToolLoopOptions,\n StreamToolLoopOptions as StreamAppToolLoopOptions,\n StreamToolLoopYield as StreamLoopYield,\n} from '@tangle-network/agent-runtime/tool-loop'\n\n/**\n * Events the app's OpenAI-compat stream adapter ({@link toLoopEvents}) yields.\n *\n * This is the app's own `Raw` event type for the streaming loop — the canonical\n * `streamToolLoop<Raw>` is generic over it. It widens the substrate's\n * tool-loop event with `reasoning` (DeepSeek/router `reasoning_content` /\n * `thinking` deltas, rendered as thinking sections) and `usage` (per-message\n * token accounting) — neither belongs in the substrate's loop contract, so they\n * stay here. The adapter maps each into the `streamTurn` seam; `text` and\n * `tool_call` drive the loop, `reasoning` / `usage` pass through to the UI.\n */\nexport type LoopEvent =\n | { type: 'text'; text: string }\n | { type: 'reasoning'; text: string }\n /** The model has begun a tool call: its name is known, its arguments are\n * still streaming. Emitted once per call, before its `tool_call`. Lets a\n * caller start slow work the call will need (resuming a sandbox box for\n * `sandbox_run`) while the arguments arrive. Consumers that do not care\n * ignore it: it never drives the loop. */\n | { type: 'tool_call_start'; toolCallId?: string; toolName: string }\n | {\n type: 'tool_call'\n call: import('@tangle-network/agent-runtime/tool-loop').ToolLoopCall\n }\n | { type: 'usage'; usage: { promptTokens: number; completionTokens: number } }\n | { type: 'other'; event: unknown }\n","/**\n * OpenAI-compatible stream → `LoopEvent` adapter, for NON-sandbox copilots.\n *\n * `streamAppToolLoop` takes a `streamTurn` seam that yields `LoopEvent`s. A\n * sandboxed agent produces those from its container; a browser/edge copilot\n * instead calls a model directly. The Tangle Router, the tcloud SDK, and most\n * providers all speak the OpenAI Chat Completions streaming shape — so the ONE\n * reusable piece is assembling that stream (content deltas + FRAGMENTED\n * tool-call deltas) into `LoopEvent`s. That assembly is the boilerplate every\n * copilot would re-write (and get wrong — OpenAI streams tool-call arguments in\n * pieces across chunks).\n *\n * This does NOT implement an HTTP client beyond a minimal `fetch` + SSE reader\n * (browser/edge/Node-safe, zero deps). For richer transport use the tcloud SDK\n * or the Vercel AI SDK and pipe their stream through {@link toLoopEvents}.\n */\nimport type { LoopEvent, LoopMessage, LoopToolCall } from './loop'\nimport { normalizeModelId } from './model-catalog'\n\n/** Minimal OpenAI Chat Completions streaming chunk (structural — no `openai` dep). */\nexport interface OpenAIStreamChunk {\n /** The model that produced this chunk. The Tangle Router reports the DATED\n * upstream id here (`gpt-5-2025-08-07`) whether or not it substituted, so\n * this is a served-model source only after id folding — see\n * {@link OpenAICompatServedModel}. */\n model?: string\n choices?: Array<{\n delta?: {\n content?: string | null\n /** Reasoning deltas — DeepSeek/router use `reasoning_content`; some proxies use `thinking`. */\n reasoning_content?: string | null\n thinking?: string | null\n tool_calls?: Array<{\n index: number\n id?: string\n function?: { name?: string; arguments?: string }\n /** Provider-specific call data the next request must echo back. Gemini 3\n * sends `{ google: { thought_signature } }` here and answers HTTP 400\n * when a later request's assistant `tool_calls` entry lacks it. */\n extra_content?: unknown\n }>\n }\n finish_reason?: string | null\n }>\n /** Token accounting (requires `stream_options.include_usage`). Cumulative for\n * the call: the Tangle Router can send it on more than one chunk. */\n usage?: {\n prompt_tokens?: number\n completion_tokens?: number\n } | null\n}\n\ninterface PartialToolCall {\n id?: string\n name: string\n args: string\n extraContent?: unknown\n announced: boolean\n}\n\n/**\n * Map an OpenAI-compat streaming chunk iterator to `LoopEvent`s: each content\n * delta → a `text` event; tool-call deltas are accumulated by index across\n * chunks and emitted as one complete `tool_call` event when the stream finishes\n * (arguments JSON-parsed; an empty/garbled args string yields `{}` rather than\n * throwing). Works for the Tangle Router, tcloud, or any OpenAI-compat source.\n *\n * A call's `extra_content` is kept as `providerFields.extra_content`, which the\n * tool loop echoes on the call's assistant `tool_calls` entry in the next request.\n * Usage is cumulative per call and may arrive on several chunks, so it is\n * yielded once, the last value, when the stream ends.\n *\n * Each call also yields one `tool_call_start` as soon as its name arrives,\n * while its arguments are still streaming, so a caller can start work the call\n * will need. Providers send the whole name in the call's first delta.\n */\nexport async function* toLoopEvents(chunks: AsyncIterable<OpenAIStreamChunk>): AsyncIterable<LoopEvent> {\n const calls = new Map<number, PartialToolCall>()\n let usage: { promptTokens: number; completionTokens: number } | undefined\n for await (const chunk of chunks) {\n // Usage can ride a chunk with an empty choices array — read it before the\n // choice guard. Each report is cumulative, so the last one is the call's.\n if (chunk.usage?.prompt_tokens != null || chunk.usage?.completion_tokens != null) {\n usage = {\n promptTokens: chunk.usage.prompt_tokens ?? 0,\n completionTokens: chunk.usage.completion_tokens ?? 0,\n }\n }\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const content = choice.delta?.content\n if (content) yield { type: 'text', text: content }\n const reasoning = choice.delta?.reasoning_content ?? choice.delta?.thinking\n if (reasoning) yield { type: 'reasoning', text: reasoning }\n for (const tc of choice.delta?.tool_calls ?? []) {\n const cur = calls.get(tc.index) ?? { name: '', args: '', announced: false }\n if (tc.id) cur.id = tc.id\n if (tc.function?.name) cur.name += tc.function.name\n if (tc.function?.arguments) cur.args += tc.function.arguments\n if (tc.extra_content !== undefined) cur.extraContent = tc.extra_content\n calls.set(tc.index, cur)\n if (!cur.announced && cur.name) {\n cur.announced = true\n yield { type: 'tool_call_start', ...(cur.id ? { toolCallId: cur.id } : {}), toolName: cur.name }\n }\n }\n }\n if (usage) yield { type: 'usage', usage }\n for (const [, c] of [...calls.entries()].sort((a, b) => a[0] - b[0])) {\n if (!c.name) continue\n yield {\n type: 'tool_call',\n call: {\n toolCallId: c.id,\n toolName: c.name,\n args: safeParse(c.args),\n ...(c.extraContent !== undefined ? { providerFields: { extra_content: c.extraContent } } : {}),\n } satisfies LoopToolCall,\n }\n }\n}\n\nfunction safeParse(s: string): Record<string, unknown> {\n if (!s.trim()) return {}\n try {\n const v = JSON.parse(s)\n return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : {}\n } catch {\n return {}\n }\n}\n\n/**\n * Which model actually served one direct-router turn.\n *\n * The router substitutes models on purpose — a quota-walled primary comes back\n * `200` answered by a different model — and says so in response headers. This\n * lane used to drop the whole `Response` after taking `.body`, so a turn\n * requested as `claude-sonnet-4-6` and answered by `openai/gpt-5` was recorded\n * by its caller as Claude: per-model quality scoring blamed the wrong model and\n * cost used the wrong price basis.\n *\n * Map this onto the shell's existing attribution contract rather than inventing\n * a second channel — `ChatTurnRouteProducer.modelAttribution()` (`/chat-routes`):\n *\n * modelAttribution: () => ({ requestedModel, servedModel, echoReceived: true })\n *\n * Leave that contract's `servedSource` unset: its union is sandbox\n * profile-resolution vocabulary with no router analogue.\n */\nexport interface OpenAICompatServedModel {\n /** The model id this turn asked for (`OpenAICompatStreamTurnOptions.model`). */\n requestedModel: string\n /** The model the router/provider reports having actually served. */\n servedModel: string\n /** Where `servedModel` was read from. The header is the router's own\n * substitution signal; the body is the backstop that survives CORS. */\n source: 'router_header' | 'response_body'\n /** True when served differs from requested after id folding. Folded, not\n * compared raw: the body reports a dated id on EVERY turn, so `!==` would\n * claim a substitution every time. */\n substituted: boolean\n /** `x-tangle-failover` `trigger=` — why the router swapped. Absent when the\n * router did not inject the substitute (a caller-supplied fallback chain\n * sets the served-model header without the failover one). */\n trigger?: string\n /** `x-tangle-failover` `degraded=`. */\n degraded?: boolean\n}\n\n/** Parse `from=…; to=…; trigger=…; degraded=…` down to the fields we report.\n * Absent/garbled segments are simply omitted — attribution is best-effort and\n * must never fail a turn that is otherwise streaming fine. */\nfunction parseFailoverHeader(raw: string | null): { trigger?: string; degraded?: boolean } {\n if (!raw) return {}\n const fields = new Map<string, string>()\n for (const segment of raw.split(';')) {\n const eq = segment.indexOf('=')\n if (eq === -1) continue\n fields.set(segment.slice(0, eq).trim().toLowerCase(), segment.slice(eq + 1).trim())\n }\n const trigger = fields.get('trigger')\n const degraded = fields.get('degraded')\n return {\n ...(trigger ? { trigger } : {}),\n ...(degraded != null ? { degraded: degraded === 'true' } : {}),\n }\n}\n\n/** Define options for configuring an OpenAI-compatible streaming chat turn including API details and tools */\nexport interface OpenAICompatStreamTurnOptions {\n /** OpenAI-compat base URL (e.g. the Tangle Router `https://router.tangle.tools/v1`). */\n baseUrl: string\n apiKey: string\n model: string\n /** OpenAI tool definitions — pass `buildAppToolOpenAITools(taxonomy)` so the\n * model can call the app tools. Omit for a tool-free copilot. */\n tools?: unknown[]\n temperature?: number\n fetchImpl?: typeof fetch\n /** Extra body fields (e.g. `max_tokens`). */\n extraBody?: Record<string, unknown>\n /** Extra request headers, e.g. a trace id the router records with the generation. */\n headers?: Record<string, string>\n /**\n * Called at most ONCE per turn, as soon as the serving model is\n * determinable, with what actually answered. Never called when neither the\n * header nor the body names a model — silence means \"learned nothing\", not\n * \"nothing was substituted\".\n *\n * `streamTurn` runs once per TOOL turn, so a multi-turn `runAppToolLoop`\n * fires this once per turn; take the last for row attribution.\n */\n onServedModel?: (served: OpenAICompatServedModel) => void\n}\n\n/**\n * Build a `streamTurn` that calls an OpenAI-compatible `/chat/completions`\n * endpoint (Tangle Router / tcloud / any compat provider) with `stream: true`\n * and yields `LoopEvent`s via {@link toLoopEvents}. Browser/edge/Node-safe —\n * just `fetch` + an SSE reader. Drop straight into `streamAppToolLoop`:\n *\n * const cfg = resolveTangleModelConfig() // or { baseUrl, apiKey, model }\n * streamAppToolLoop({ streamTurn: createOpenAICompatStreamTurn({ ...cfg, tools }), executeToolCall, ... })\n */\nexport function createOpenAICompatStreamTurn(\n opts: OpenAICompatStreamTurnOptions,\n): (messages: LoopMessage[]) => AsyncIterable<LoopEvent> {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const doFetch = opts.fetchImpl ?? fetch\n return (messages) =>\n toLoopEvents(\n streamChatCompletions(doFetch, `${base}/chat/completions`, opts.apiKey, {\n model: opts.model,\n messages,\n stream: true,\n stream_options: { include_usage: true },\n ...(opts.tools && opts.tools.length > 0 ? { tools: opts.tools } : {}),\n ...(opts.temperature != null ? { temperature: opts.temperature } : {}),\n ...opts.extraBody,\n }, opts.onServedModel ? { requestedModel: opts.model, report: opts.onServedModel } : undefined, opts.headers),\n )\n}\n\n/** Stream + parse an OpenAI-compat SSE response into chunks. Tolerates `data:`\n * framing, multi-line buffers, and the terminal `[DONE]`. */\nasync function* streamChatCompletions(\n doFetch: typeof fetch,\n url: string,\n apiKey: string,\n body: Record<string, unknown>,\n attribution?: { requestedModel: string; report: (served: OpenAICompatServedModel) => void },\n headers?: Record<string, string>,\n): AsyncIterable<OpenAIStreamChunk> {\n const res = await doFetch(url, {\n method: 'POST',\n headers: { ...headers, Authorization: `Bearer ${apiKey}`, 'Content-Type': 'application/json', Accept: 'text/event-stream' },\n body: JSON.stringify(body),\n })\n if (!res.ok || !res.body) {\n const text = res.body ? await res.text().catch(() => '') : ''\n const error = new Error(`OpenAI-compat stream failed (HTTP ${res.status})${text ? `: ${text.slice(0, 200)}` : ''}`)\n // Stamp the NUMERIC status. `isUpstreamUnavailable` (`/model-resolution`)\n // reads a numeric field first and prose only as a backstop, and a\n // Cloudflare EDGE 502 gives it nothing else to read: `content-type:\n // text/plain`, a body of `error code: 502`, and none of the router's own\n // `x-tangle-*` headers, because the origin never ran. Carrying the status\n // as data keeps THIS path — the browser/edge copilot lane, which calls the\n // router directly — out of the string-matching business entirely.\n Object.assign(error, { status: res.status })\n throw error\n }\n // Served-model attribution, fired at most once, as early as it is knowable.\n //\n // The header comes first because it is the router's OWN substitution signal:\n // `X-Tangle-Served-Model` is set only when the served model differs from the\n // requested one, so its presence is authoritative and it arrives before the\n // first byte of content. `X-Tangle-Failover` rides along only when the router\n // itself picked the substitute (a caller-supplied fallback chain sets the\n // former without the latter), which is why `trigger`/`degraded` are optional.\n //\n // The body is the backstop for when the header cannot reach us. In a BROWSER,\n // headers are invisible to JS unless the server lists them in\n // `Access-Control-Expose-Headers` — tangle-router#324 added both, but that\n // only helps once it is DEPLOYED, and any other OpenAI-compat endpoint\n // pointed at this client exposes nothing. The chunk `model` field is not\n // subject to CORS, so it keeps the browser lane attributable regardless.\n let reported = false\n const report = (served: OpenAICompatServedModel): void => {\n if (reported || !attribution) return\n reported = true\n attribution.report(served)\n }\n if (attribution) {\n const servedHeader = res.headers.get('x-tangle-served-model')\n if (servedHeader) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: servedHeader,\n source: 'router_header',\n substituted: normalizeModelId(servedHeader) !== normalizeModelId(attribution.requestedModel),\n ...parseFailoverHeader(res.headers.get('x-tangle-failover')),\n })\n }\n }\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n const lines = buffer.split('\\n')\n buffer = lines.pop() ?? ''\n for (const line of lines) {\n const trimmed = line.trim()\n if (!trimmed.startsWith('data:')) continue\n const data = trimmed.slice(5).trim()\n if (data === '[DONE]') return\n let chunk: OpenAIStreamChunk\n try {\n chunk = JSON.parse(data) as OpenAIStreamChunk\n } catch {\n continue /* skip a partial/garbled SSE frame */\n }\n // Body fallback: only when the header said nothing. Fold both ids before\n // comparing — the router reports the dated upstream id (`gpt-5-2025-08-07`)\n // for a request of `openai/gpt-5` even with NO substitution, so a raw\n // `!==` would report a swap on literally every turn.\n if (attribution && !reported && chunk.model) {\n report({\n requestedModel: attribution.requestedModel,\n servedModel: chunk.model,\n source: 'response_body',\n substituted: normalizeModelId(chunk.model) !== normalizeModelId(attribution.requestedModel),\n })\n }\n yield chunk\n }\n }\n}\n","/**\n * Knowledge in every turn: the index of an app's knowledge files, the full\n * text of the small ones, and the rule that keeps answers on them.\n *\n * Measured on Hospitality production (2026-10-11): a Router turn that had to\n * discover files through list/read tools answered 17/17 correctly but needed\n * 3 tool calls (first words 12-17 s), and a turn that skipped the tools\n * answered from model defaults (\"checkout 11:00\" when the file said 12 pm).\n * Putting the text in the prompt removes both failure modes.\n */\n/** The fields read from an agent-runtime workspace-store entry; structural so older runtimes still type-check. */\ninterface KnowledgeEntry { path: string; kind: string; content?: string; bytes?: { size: number } }\n\n/** One knowledge file a turn carries; `text` is null when it is too large or not readable here. */\nexport interface TurnKnowledgeFile {\n path: string\n size: number\n text: string | null\n}\n\nexport interface TurnKnowledgeBudget {\n /** Files at most this many bytes have their text included. Default 8 000. */\n fileBytes?: number\n /** Total text bytes across files. Default 16 000. */\n textBytes?: number\n /** Most files listed. Default 60. */\n maxFiles?: number\n}\n\nconst DEFAULT_FILE_BYTES = 8_000\nconst DEFAULT_TEXT_BYTES = 16_000\nconst DEFAULT_MAX_FILES = 60\n\n/** Apply the byte budget in path order: small files keep their text until the total is spent. */\nexport function budgetTurnKnowledge(files: readonly TurnKnowledgeFile[], budget: TurnKnowledgeBudget = {}): TurnKnowledgeFile[] {\n const fileBytes = budget.fileBytes ?? DEFAULT_FILE_BYTES\n let remaining = budget.textBytes ?? DEFAULT_TEXT_BYTES\n return [...files].sort((a, b) => a.path.localeCompare(b.path)).slice(0, budget.maxFiles ?? DEFAULT_MAX_FILES)\n .map(file => {\n const fits = file.text !== null && file.size <= fileBytes && file.size <= remaining\n if (fits) remaining -= file.size\n return { path: file.path, size: file.size, text: fits ? file.text : null }\n })\n}\n\n/**\n * The prompt lines for a turn's knowledge. `readTool` names the tool that\n * opens a listed file whose text is not shown; without one, such a file is\n * listed by name only.\n */\nexport function turnKnowledgeInstructions(files: readonly TurnKnowledgeFile[], options: { readTool?: string } = {}): string[] {\n const read = options.readTool\n return [\n 'Answer questions about this business or its work (hours, times, policies, codes, passwords, prices, contacts, amenities, procedures) only from the knowledge in these instructions, the knowledge files below, or a tool result. Never give a typical or assumed value, and do not say something is absent unless a source says so.' +\n (read ? ` When a listed file without its text may cover the question, read it with ${read} before answering.` : '') +\n ' When nothing covers it, say you do not have that information and offer to ask the owner.',\n ...files.map(file => file.text !== null ? `Knowledge file ${file.path}:\\n${file.text}`\n : `Knowledge file ${file.path} (${file.size} bytes, text not shown)${read ? `: read it with ${read} when the question may be covered by it.` : '.'}`),\n ]\n}\n\n/** A workspace store's knowledge files (kind `file` under `prefix`) as turn knowledge, within the budget. */\nexport async function workspaceKnowledgeForTurn(\n store: { list(workspaceId: string, prefix: string): Promise<readonly KnowledgeEntry[]> },\n workspaceId: string,\n options: TurnKnowledgeBudget & { prefix?: string } = {},\n): Promise<TurnKnowledgeFile[]> {\n const entries = await store.list(workspaceId, options.prefix ?? '/files/')\n return budgetTurnKnowledge(entries.filter(entry => entry.kind === 'file').map(entry => ({\n path: entry.path,\n size: entry.content !== undefined ? new TextEncoder().encode(entry.content).byteLength : entry.bytes?.size ?? 0,\n text: entry.content ?? null,\n })), options)\n}\n","/**\n * One conversational turn answered by a model through the Tangle Router, with\n * the app's own tools executed in-process — no sandbox in the path.\n *\n * This is the default runtime for conversational turns in an agent app: the\n * product supplies the principal's tools, the profile prompt and the\n * conversation; the engine streams words as the model writes them, runs tool\n * calls through the bounded `streamAppToolLoop`, and returns one outcome.\n * Long, file or code work belongs to the sandbox, reached through a tool the\n * product adds to `tools`.\n *\n * Every failure is an outcome, never a throw. A durable turn owner retries\n * thrown errors, and a retry after a tool ran would repeat that tool's effect\n * (\"never re-run a turn automatically\", docs/agent-app-lessons.md). The only\n * automatic repeat is one model call that failed before any word or tool.\n */\nimport { streamAppToolLoop, type LoopEvent, type LoopMessage, type LoopToolCall, type ToolLoopStopReason } from './loop'\nimport { DEFAULT_TANGLE_ROUTER_BASE_URL } from './model'\nimport { createOpenAICompatStreamTurn } from './openai-stream'\nimport { turnKnowledgeInstructions, type TurnKnowledgeFile } from './turn-knowledge'\nexport { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge'\n\n/** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */\nexport interface RouterTurnTool {\n name: string\n description: string\n /** JSON Schema for the arguments object. */\n inputSchema: Record<string, unknown>\n run(args: Record<string, unknown>): Promise<unknown>\n}\n\n/** What the turn is doing, in the order it happens, for a live view. */\nexport type RouterTurnEvent =\n | { type: 'text'; segment: number; delta: string }\n | { type: 'tool'; callId: string; toolName: string; status: 'running'; input: Record<string, unknown>; startedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'completed'; output: unknown; startedAt: number; endedAt: number }\n | { type: 'tool'; callId: string; toolName: string; status: 'error'; error: { code: string; message: string }; startedAt: number; endedAt: number }\n | { type: 'usage'; promptTokens: number; completionTokens: number }\n\nexport interface RouterTurnFailure {\n /** `model_http_<status>`, `model_unavailable`, `turn_<stopReason>` or `router_unconfigured`. */\n code: string\n status?: number\n message: string\n}\n\nexport interface RouterTurnOutcome {\n /** Every text segment the model wrote, joined by blank lines. */\n text: string\n /** The model the router reports having served, when it said. */\n servedModel: string | null\n toolCalls: Array<{ callId: string; toolName: string; ok: boolean }>\n /** Token use summed over every model call in the turn, as the router reported it. */\n usage: { promptTokens: number; completionTokens: number; modelCalls: number }\n failure?: RouterTurnFailure\n}\n\nexport interface RouterTurnOptions {\n apiKey: string\n model: string\n /** Defaults to the Tangle Router. */\n baseUrl?: string\n systemPrompt: string\n userMessage: string\n /** Earlier turns. Plain text messages, or OpenAI function-calling history (an assistant message\n * carrying `tool_calls` and the `tool` messages answering them) so the model sees what it did. */\n history?: Array<{ role: 'user' | 'assistant'; content: string } | LoopMessage>\n tools?: RouterTurnTool[]\n /** Wall-clock budget in ms. Default 90 s. A caller whose retry window is shorter passes less. */\n budgetMs?: number\n /** Runaway backstop on model turns. Default 12. */\n maxToolTurns?: number\n maxTokens?: number\n /** Sent as `x-tangle-trace-id` so the router's generation joins the app's trace. */\n traceId?: string\n fetchImpl?: typeof fetch\n onEvent?: (event: RouterTurnEvent) => void\n /** Map a thrown tool error to what the model reads. Default: an error carrying string `code`\n * (and numeric `status`) is reported with its message; anything else is a generic failure. */\n toolError?: (error: unknown) => { code: string; message: string; status?: number } | null\n /** Called for a tool failure the default mapping hides from the model, for the app's logs. */\n onToolFailure?: (toolName: string, error: unknown) => void\n}\n\nconst DEFAULT_BUDGET_MS = 90_000\nconst TOOL_RESULT_LIMIT = 12_000\n\n/** OpenAI-compatible function names allow only `[A-Za-z0-9_-]{1,64}`; app tool names often use dots. */\nexport function routerFunctionName(name: string): string {\n return name.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64)\n}\n\n/**\n * The lean system prompt for a Router turn: the profile's system prompt and\n * instructions, the turn's knowledge files, then caller context, with tool names rewritten to the function\n * names the model actually calls.\n */\nexport function composeRouterTurnPrompt(\n profile: { prompt?: { systemPrompt?: string; instructions?: readonly string[] } },\n options: {\n context?: readonly string[]\n toolNames?: readonly string[]\n /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. */\n knowledge?: { files: readonly TurnKnowledgeFile[]; readTool?: string }\n } = {},\n): string {\n const knowledge = options.knowledge ? turnKnowledgeInstructions(options.knowledge.files, { readTool: options.knowledge.readTool }) : []\n const text = [profile.prompt?.systemPrompt ?? '', ...(profile.prompt?.instructions ?? []), ...knowledge, ...(options.context ?? [])]\n .filter(part => part.trim()).join('\\n\\n')\n return [...(options.toolNames ?? [])].sort((a, b) => b.length - a.length)\n .reduce((out, name) => out.split(name).join(routerFunctionName(name)), text)\n}\n\nfunction defaultToolError(error: unknown): { code: string; message: string; status?: number } | null {\n const value = error as { code?: unknown; status?: unknown; message?: unknown; issues?: unknown }\n if (Array.isArray(value?.issues)) {\n return { code: 'invalid_arguments', message: JSON.stringify(value.issues).slice(0, 600) }\n }\n if (typeof value?.code === 'string' && typeof value.message === 'string') {\n return { code: value.code, message: value.message, ...(typeof value.status === 'number' ? { status: value.status } : {}) }\n }\n return null\n}\n\nfunction renderResult(outcome: { ok: true; result: unknown } | { ok: false; code: string; message: string }): string {\n if (!outcome.ok) return `Error (${outcome.code}): ${outcome.message}`\n let text: string\n try { text = typeof outcome.result === 'string' ? outcome.result : JSON.stringify(outcome.result ?? null) }\n catch { text = String(outcome.result) }\n return text.length > TOOL_RESULT_LIMIT ? `${text.slice(0, TOOL_RESULT_LIMIT)}…` : text\n}\n\nexport async function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome> {\n if (!options.apiKey) {\n return { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 },\n failure: { code: 'router_unconfigured', message: 'The model credential is not configured.' } }\n }\n const emit = options.onEvent ?? (() => {})\n const byFunction = new Map<string, RouterTurnTool>()\n for (const tool of options.tools ?? []) {\n const fn = routerFunctionName(tool.name)\n if (!byFunction.has(fn)) byFunction.set(fn, tool)\n }\n let servedModel: string | null = null\n const streamTurn = createOpenAICompatStreamTurn({\n baseUrl: options.baseUrl ?? DEFAULT_TANGLE_ROUTER_BASE_URL,\n apiKey: options.apiKey,\n model: options.model,\n tools: [...byFunction.entries()].map(([name, tool]) => ({\n type: 'function', function: { name, description: tool.description, parameters: tool.inputSchema },\n })),\n ...(options.maxTokens ? { extraBody: { max_tokens: options.maxTokens } } : {}),\n ...(options.traceId ? { headers: { 'x-tangle-trace-id': options.traceId } } : {}),\n ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),\n onServedModel: served => { servedModel = served.servedModel },\n })\n const segments: string[] = []\n const usage = { promptTokens: 0, completionTokens: 0, modelCalls: 0 }\n const toolCalls: RouterTurnOutcome['toolCalls'] = []\n const started = new Map<string, number>()\n let segmentOpen = false\n let toolsRan = 0\n const deadline = Date.now() + (options.budgetMs ?? DEFAULT_BUDGET_MS)\n const callIdOf = (id: string | undefined, toolName: string) => id ?? `${toolName}-${started.size}`\n\n const run = async (): Promise<ToolLoopStopReason> => {\n for await (const step of streamAppToolLoop<LoopEvent>({\n systemPrompt: options.systemPrompt,\n userMessage: options.userMessage,\n priorMessages: (options.history ?? []) as LoopMessage[],\n streamTurn,\n extractText: event => event.type === 'text' ? event.text : '',\n extractToolCall: event => event.type === 'tool_call' ? event.call : null,\n isExecutableTool: name => byFunction.has(name),\n deadlineMs: deadline,\n maxToolTurns: options.maxToolTurns ?? 12,\n renderResult: (_label, outcome) => renderResult(outcome),\n executeToolCall: async (call: LoopToolCall) => {\n const tool = byFunction.get(call.toolName)\n if (!tool) return { ok: false, code: 'unknown_tool', message: `No tool named ${call.toolName}` }\n toolsRan++\n try {\n return { ok: true, result: await tool.run(call.args) }\n } catch (error) {\n const mapped = (options.toolError ?? defaultToolError)(error)\n if (mapped) return { ok: false, ...mapped }\n options.onToolFailure?.(tool.name, error)\n return { ok: false, code: 'tool_failed', message: 'The tool failed; tell the user what could not be completed.' }\n }\n },\n })) {\n if (step.kind === 'event') {\n const event = step.event\n if (event.type === 'text' && event.text) {\n if (!segmentOpen) { segments.push(''); segmentOpen = true }\n segments[segments.length - 1] += event.text\n emit({ type: 'text', segment: segments.length, delta: event.text })\n } else if (event.type === 'usage') {\n usage.promptTokens += event.usage.promptTokens\n usage.completionTokens += event.usage.completionTokens\n usage.modelCalls++\n emit({ type: 'usage', ...event.usage })\n } else if (event.type === 'tool_call') {\n segmentOpen = false\n const tool = byFunction.get(event.call.toolName)\n const callId = callIdOf(event.call.toolCallId, event.call.toolName)\n started.set(callId, Date.now())\n emit({ type: 'tool', callId, toolName: tool?.name ?? event.call.toolName, status: 'running',\n input: event.call.args, startedAt: started.get(callId)! })\n }\n } else if (step.kind === 'tool_result') {\n const tool = byFunction.get(step.toolName)\n const callId = callIdOf(step.toolCallId, step.toolName)\n const startedAt = started.get(callId) ?? Date.now()\n const toolName = tool?.name ?? step.toolName\n toolCalls.push({ callId, toolName, ok: step.outcome.ok })\n emit(step.outcome.ok\n ? { type: 'tool', callId, toolName, status: 'completed', output: step.outcome.result, startedAt, endedAt: Date.now() }\n : { type: 'tool', callId, toolName, status: 'error', startedAt, endedAt: Date.now(),\n error: { code: step.outcome.code, message: step.outcome.message } })\n } else if (step.kind === 'capped') {\n return step.stopReason\n }\n }\n return 'completed'\n }\n\n const outcome = (failure?: RouterTurnFailure): RouterTurnOutcome => ({\n text: segments.map(part => part.trim()).filter(Boolean).join('\\n\\n'),\n servedModel, toolCalls, usage: { ...usage }, ...(failure ? { failure } : {}),\n })\n let stop: ToolLoopStopReason\n try {\n try {\n stop = await run()\n } catch (error) {\n // Safe to repeat only while nothing was said and no tool ran.\n if (toolsRan > 0 || segments.length > 0) throw error\n stop = await run()\n }\n } catch (error) {\n const status = (error as { status?: unknown }).status\n return outcome(typeof status === 'number'\n ? { code: `model_http_${status}`, status, message: 'The model service did not answer.' }\n : { code: 'model_unavailable', message: 'The model service did not answer.' })\n }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n // A model can end its turn with neither a word nor a tool call (gemini-2.5-flash did on 8 of\n // 53 \"remember\" turns, 2026-10-11). Nothing was said and nothing ran, so one repeat is safe;\n // an answer still blank is a typed failure, never a successful empty reply.\n if (!segments.some(part => part.trim())) {\n if (toolsRan === 0) {\n try { stop = await run() } catch { stop = 'completed' }\n if (stop !== 'completed') return outcome({ code: `turn_${stop}`, message: 'The reply was stopped before it finished.' })\n }\n if (!segments.some(part => part.trim())) {\n return outcome({ code: 'model_empty', message: 'The model finished without writing a reply.' })\n }\n }\n return outcome()\n}\n"],"mappings":";;;;;;;;AA2BA;AAAA,EACiB;AAAA,EACG;AAAA,OACb;;;AC8CP,gBAAuB,aAAa,QAAoE;AACtG,QAAM,QAAQ,oBAAI,IAA6B;AAC/C,MAAI;AACJ,mBAAiB,SAAS,QAAQ;AAGhC,QAAI,MAAM,OAAO,iBAAiB,QAAQ,MAAM,OAAO,qBAAqB,MAAM;AAChF,cAAQ;AAAA,QACN,cAAc,MAAM,MAAM,iBAAiB;AAAA,QAC3C,kBAAkB,MAAM,MAAM,qBAAqB;AAAA,MACrD;AAAA,IACF;AACA,UAAM,SAAS,MAAM,UAAU,CAAC;AAChC,QAAI,CAAC,OAAQ;AACb,UAAM,UAAU,OAAO,OAAO;AAC9B,QAAI,QAAS,OAAM,EAAE,MAAM,QAAQ,MAAM,QAAQ;AACjD,UAAM,YAAY,OAAO,OAAO,qBAAqB,OAAO,OAAO;AACnE,QAAI,UAAW,OAAM,EAAE,MAAM,aAAa,MAAM,UAAU;AAC1D,eAAW,MAAM,OAAO,OAAO,cAAc,CAAC,GAAG;AAC/C,YAAM,MAAM,MAAM,IAAI,GAAG,KAAK,KAAK,EAAE,MAAM,IAAI,MAAM,IAAI,WAAW,MAAM;AAC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AAI,UAAU,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5E;AACA,MAAI;AACJ,MAAI;AACF,QAAI;AACF,aAAO,MAAM,IAAI;AAAA,IACnB,SAAS,OAAO;AAEd,UAAI,WAAW,KAAK,SAAS,SAAS,EAAG,OAAM;AAC/C,aAAO,MAAM,IAAI;AAAA,IACnB;AAAA,EACF,SAAS,OAAO;AACd,UAAM,SAAU,MAA+B;AAC/C,WAAO,QAAQ,OAAO,WAAW,WAC7B,EAAE,MAAM,cAAc,MAAM,IAAI,QAAQ,SAAS,oCAAoC,IACrF,EAAE,MAAM,qBAAqB,SAAS,oCAAoC,CAAC;AAAA,EACjF;AACA,MAAI,SAAS,YAAa,QAAO,QAAQ,EAAE,MAAM,QAAQ,IAAI,IAAI,SAAS,4CAA4C,CAAC;AAIvH,MAAI,CAAC,SAAS,KAAK,UAAQ,KAAK,KAAK,CAAC,GAAG;AACvC,QAAI,aAAa,GAAG;AAClB,UAAI;AAAE,eAAO,MAAM,IAAI;AAAA,MAAE,QAAQ;AAAE,eAAO;AAAA,MAAY;AACtD,UAAI,SAAS,YAAa,QAAO,QAAQ,EAAE,MAAM,QAAQ,IAAI,IAAI,SAAS,4CAA4C,CAAC;AAAA,IACzH;AACA,QAAI,CAAC,SAAS,KAAK,UAAQ,KAAK,KAAK,CAAC,GAAG;AACvC,aAAO,QAAQ,EAAE,MAAM,eAAe,SAAS,8CAA8C,CAAC;AAAA,IAChG;AAAA,EACF;AACA,SAAO,QAAQ;AACjB;","names":["outcome"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/teams/members-api.ts"],"sourcesContent":["/**\n * Framework-neutral members API for the teams module: the invite / list /\n * update-role / remove / accept-invite logic, lifted out of any one app's route\n * file. Each app mounts these in its own route with its own auth — the handlers\n * take an already-authenticated `actor`, the parsed inputs, the `db` + `tables`\n * from `createTeamTables`, the product's user + workspace tables, and the\n * workspace-access API from `createWorkspaceAccess`. They return web-standard\n * `Response`s (available in Workers, Node 18+, Deno, browsers), so\n * \"framework-neutral\" is literal: no Remix/React-Router/Express import anywhere.\n *\n * Two OPTIONAL seams an app wires only if it needs them:\n * - `enforceSeat` — billing/seat-limit gate, called at invite time only when\n * the invite would consume a NEW billable seat. An app without seat billing\n * passes nothing and seats are never checked.\n * - `memberSyncSeam` — fire-and-forget propagation of membership changes to a\n * sandbox/external system (add on accept, role on update, remove on\n * delete). An app without sandbox sync passes nothing. Fail-soft by\n * contract: a thrown sync is caught and never blocks the DB mutation.\n *\n * Imports `drizzle-orm`, so this is a subpath, never re-exported from root.\n */\n\nimport { and, eq, isNull } from 'drizzle-orm'\nimport {\n type AssignableWorkspaceRole,\n type WorkspaceRole,\n canManageWorkspaceMemberRole,\n hasWorkspaceRole,\n isAssignableWorkspaceRole,\n organizationRoleGrantsWorkspaceOwner,\n} from './roles'\nimport { generateInviteToken } from './invite'\nimport type { TeamDatabase, WorkspaceAccessApi } from './drizzle/access'\nimport type { TeamParentTable, TeamTables } from './drizzle/schema'\n\n/** The authenticated caller — apps resolve this from their own session layer. */\nexport interface MembersApiActor {\n id: string\n email?: string | null\n}\n\n/**\n * The product's user table, narrowed to the columns the member queries read.\n * Adopters pass their real drizzle user table.\n */\nexport interface UserLookupTable {\n id: any\n name: any\n email: any\n}\n\n/**\n * The product's workspace table, narrowed to the columns the member queries\n * read. The handlers join it to resolve a workspace's organization (the same\n * table passed to createTeamTables as workspaceTable).\n */\nexport interface WorkspaceLookupTable {\n id: any\n organizationId: any\n}\n\n/**\n * Optional billing seat gate. The seam resolves the count input itself (it\n * owns the plan/seat model) and throws when over the limit; the handler turns a\n * thrown `SeatLimitError` into a 402. Called only when an invite would consume\n * a NEW seat (invitee is not already an org member and has no pending org\n * invite) — the same guard gtm uses, so the seam never fires on a no-op invite.\n */\nexport interface EnforceSeatSeam {\n (input: { actorId: string; organizationId: string }): Promise<void> | void\n}\n\n/** Thrown by an `enforceSeat` seam to deny an invite; serialized to a 402. */\nexport class SeatLimitError extends Error {\n readonly status: number\n readonly capability?: string\n readonly requiredPlan?: string\n constructor(message: string, opts: { status?: number; capability?: string; requiredPlan?: string } = {}) {\n super(message)\n this.name = 'SeatLimitError'\n this.status = opts.status ?? 402\n this.capability = opts.capability\n this.requiredPlan = opts.requiredPlan\n }\n}\n\n/**\n * Optional membership-change propagation to an external system (e.g. sandbox).\n * Every method is fire-and-forget and fail-soft: the handler awaits nothing and\n * swallows rejections, so an unavailable downstream never blocks the mutation.\n * Each fires only for members with a real `userId` (never email-only invites).\n */\nexport interface MemberSyncSeam {\n add?(input: { workspaceId: string; userId: string; role: WorkspaceRole }): Promise<void> | void\n role?(input: { workspaceId: string; userId: string; role: WorkspaceRole }): Promise<void> | void\n remove?(input: { workspaceId: string; userId: string }): Promise<void> | void\n}\n\n/** Define configuration options for managing team members and workspace access APIs */\nexport interface MembersApiOptions {\n db: TeamDatabase\n tables: TeamTables\n /** The product's user table (FK target passed to createTeamTables). */\n userTable: TeamParentTable & UserLookupTable\n /** The product's workspace table (FK target passed to createTeamTables). */\n workspaceTable: TeamParentTable & WorkspaceLookupTable\n /** Workspace-access API from createWorkspaceAccess — RBAC stays one source. */\n access: Pick<WorkspaceAccessApi, 'getWorkspaceAccess'>\n enforceSeat?: EnforceSeatSeam\n memberSyncSeam?: MemberSyncSeam\n}\n\n/** Define the structure of a workspace member entry with identification, role, and status details */\nexport interface MemberListEntry {\n id: string\n userId: string | null\n organizationMemberId: string | null\n role: WorkspaceRole\n name: string | null\n email: string | null\n invitedAt: Date | number | null\n acceptedAt: Date | number | null\n inherited: boolean\n}\n\n/**\n * Build the members API bound to one product's db/tables/access. Returns five\n * handlers; an app maps its route methods onto them (GET→list, POST→invite,\n * PATCH→updateRole, DELETE→remove; accept on its own route).\n */\nexport function createMembersApi(opts: MembersApiOptions) {\n const { db, tables, userTable, workspaceTable, access, enforceSeat, memberSyncSeam } = opts\n const { organizations, organizationMembers, workspaceMembers } = tables\n const users = userTable\n const workspaces = workspaceTable\n\n function fireSync(op: () => Promise<void> | void) {\n try {\n Promise.resolve(op()).catch(() => {})\n } catch {\n // seam threw synchronously — swallow; sync is best-effort by contract.\n }\n }\n\n async function listMembers(input: { workspaceId: string; actor: MembersApiActor }): Promise<Response> {\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.actor.id)\n if (!accessRow) return Response.json({ error: 'Workspace not found' }, { status: 404 })\n\n const organizationId = (accessRow.workspace as { organizationId: string }).organizationId\n\n const [projectMembers, orgAdmins] = await Promise.all([\n db\n .select({\n id: workspaceMembers.id,\n organizationMemberId: workspaceMembers.organizationMemberId,\n userId: workspaceMembers.userId,\n role: workspaceMembers.role,\n invitedAt: workspaceMembers.invitedAt,\n acceptedAt: workspaceMembers.acceptedAt,\n inviteEmail: workspaceMembers.inviteEmail,\n userName: users.name,\n userEmail: users.email,\n })\n .from(workspaceMembers)\n .leftJoin(users, eq(users.id, workspaceMembers.userId))\n .where(eq(workspaceMembers.workspaceId, input.workspaceId)),\n db\n .select({\n id: organizationMembers.id,\n userId: organizationMembers.userId,\n orgRole: organizationMembers.role,\n userName: users.name,\n userEmail: users.email,\n createdAt: organizationMembers.createdAt,\n })\n .from(organizationMembers)\n .innerJoin(users, eq(users.id, organizationMembers.userId))\n .where(eq(organizationMembers.organizationId, organizationId)),\n ])\n\n const explicitOrgMemberIds = new Set(\n projectMembers.map((m: any) => m.organizationMemberId).filter(Boolean),\n )\n const members: MemberListEntry[] = [\n ...orgAdmins\n .filter((m: any) => organizationRoleGrantsWorkspaceOwner(m.orgRole) && !explicitOrgMemberIds.has(m.id))\n .map((m: any) => ({\n id: `org:${m.id}`,\n userId: m.userId,\n organizationMemberId: m.id,\n role: 'owner' as WorkspaceRole,\n name: m.userName,\n email: m.userEmail,\n invitedAt: m.createdAt,\n acceptedAt: m.createdAt,\n inherited: true,\n })),\n ...projectMembers.map((m: any) => ({\n id: m.id,\n userId: m.userId,\n organizationMemberId: m.organizationMemberId,\n role: m.role as WorkspaceRole,\n name: m.userName,\n email: m.userEmail ?? m.inviteEmail,\n invitedAt: m.invitedAt,\n acceptedAt: m.acceptedAt,\n inherited: false,\n })),\n ]\n\n return Response.json({ members, currentRole: accessRow.role, organizationId })\n }\n\n async function inviteMember(input: {\n workspaceId: string\n actor: MembersApiActor\n email?: string\n role?: string\n }): Promise<Response> {\n if (!input.email) return Response.json({ error: 'Missing email' }, { status: 400 })\n const requestedRole = input.role ?? 'editor'\n if (!isAssignableWorkspaceRole(requestedRole)) {\n return Response.json({ error: 'Invalid role. Must be viewer, editor, or admin.' }, { status: 400 })\n }\n const assignRole: AssignableWorkspaceRole = requestedRole\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.actor.id, 'admin')\n if (!accessRow) return Response.json({ error: 'Workspace not found' }, { status: 404 })\n if (!hasWorkspaceRole(accessRow.role, assignRole)) {\n return Response.json({ error: 'Cannot assign a role higher than your own' }, { status: 403 })\n }\n\n const organizationId = (accessRow.workspace as { organizationId: string }).organizationId\n const normalizedEmail = input.email.toLowerCase().trim()\n const invitee = await getUserByEmail(normalizedEmail)\n const existingOrgMember = invitee ? await getOrganizationMember(organizationId, invitee.id) : null\n\n if (organizationRoleGrantsWorkspaceOwner(existingOrgMember?.role)) {\n return Response.json({ error: 'Organization admins already have project access' }, { status: 409 })\n }\n\n const existingInvite = await findExistingProjectInvite(input.workspaceId, normalizedEmail, invitee?.id)\n if (existingInvite) {\n return Response.json({ error: 'This collaborator is already invited to this project' }, { status: 409 })\n }\n\n if (enforceSeat && !existingOrgMember && !(await hasPendingOrgInvite(organizationId, normalizedEmail))) {\n try {\n await enforceSeat({ actorId: input.actor.id, organizationId })\n } catch (err) {\n if (err instanceof SeatLimitError) {\n return Response.json(\n { error: err.message, capability: err.capability, requiredPlan: err.requiredPlan },\n { status: err.status },\n )\n }\n throw err\n }\n }\n\n const token = generateInviteToken()\n const [member] = await db\n .insert(workspaceMembers)\n .values({\n workspaceId: input.workspaceId,\n organizationMemberId: existingOrgMember?.id ?? null,\n userId: invitee?.id ?? null,\n role: assignRole,\n invitedBy: input.actor.id,\n inviteEmail: normalizedEmail,\n inviteToken: token,\n })\n .returning()\n\n return Response.json({ member, inviteToken: token })\n }\n\n async function updateMemberRole(input: {\n workspaceId: string\n actor: MembersApiActor\n memberId?: string\n role?: string\n }): Promise<Response> {\n if (!input.memberId || !input.role) {\n return Response.json({ error: 'Missing memberId or role' }, { status: 400 })\n }\n if (input.memberId.startsWith('org:')) {\n return Response.json({ error: 'Organization owner/admin project access is managed at the organization level' }, { status: 403 })\n }\n if (!isAssignableWorkspaceRole(input.role)) {\n return Response.json({ error: 'Invalid role' }, { status: 400 })\n }\n\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.actor.id, 'admin')\n if (!accessRow) return Response.json({ error: 'Workspace not found' }, { status: 404 })\n if (!hasWorkspaceRole(accessRow.role, input.role)) {\n return Response.json({ error: 'Cannot assign a role higher than your own' }, { status: 403 })\n }\n\n const [target] = await db\n .select({ id: workspaceMembers.id, role: workspaceMembers.role, userId: workspaceMembers.userId })\n .from(workspaceMembers)\n .where(and(eq(workspaceMembers.id, input.memberId), eq(workspaceMembers.workspaceId, input.workspaceId)))\n .limit(1)\n\n if (!target) return Response.json({ error: 'Member not found' }, { status: 404 })\n if (target.userId === input.actor.id) return Response.json({ error: 'Cannot change your own role' }, { status: 403 })\n if (!canManageWorkspaceMemberRole(accessRow.role, target.role as WorkspaceRole)) {\n return Response.json({ error: 'Cannot modify a member with equal or higher role' }, { status: 403 })\n }\n\n await db.update(workspaceMembers).set({ role: input.role }).where(eq(workspaceMembers.id, input.memberId))\n if (target.userId && memberSyncSeam?.role) {\n const userId = target.userId\n const nextRole = input.role as WorkspaceRole\n fireSync(() => memberSyncSeam.role!({ workspaceId: input.workspaceId, userId, role: nextRole }))\n }\n return Response.json({ success: true })\n }\n\n async function removeMember(input: {\n workspaceId: string\n actor: MembersApiActor\n memberId?: string\n }): Promise<Response> {\n if (!input.memberId) return Response.json({ error: 'Missing memberId' }, { status: 400 })\n if (input.memberId.startsWith('org:')) {\n return Response.json({ error: 'Organization owner/admin project access is managed at the organization level' }, { status: 403 })\n }\n\n const accessRow = await access.getWorkspaceAccess(input.workspaceId, input.actor.id, 'admin')\n if (!accessRow) return Response.json({ error: 'Workspace not found' }, { status: 404 })\n\n const [target] = await db\n .select({ id: workspaceMembers.id, role: workspaceMembers.role, userId: workspaceMembers.userId })\n .from(workspaceMembers)\n .where(and(eq(workspaceMembers.id, input.memberId), eq(workspaceMembers.workspaceId, input.workspaceId)))\n .limit(1)\n\n if (!target) return Response.json({ error: 'Member not found' }, { status: 404 })\n if (target.userId === input.actor.id) return Response.json({ error: 'Cannot remove yourself from this project' }, { status: 403 })\n if (!canManageWorkspaceMemberRole(accessRow.role, target.role as WorkspaceRole)) {\n return Response.json({ error: 'Cannot remove a member with equal or higher role' }, { status: 403 })\n }\n\n await db.delete(workspaceMembers).where(eq(workspaceMembers.id, input.memberId))\n if (target.userId && memberSyncSeam?.remove) {\n const userId = target.userId\n fireSync(() => memberSyncSeam.remove!({ workspaceId: input.workspaceId, userId }))\n }\n return Response.json({ success: true })\n }\n\n async function acceptInvite(input: { token?: string; actor: MembersApiActor }): Promise<Response> {\n if (!input.token || typeof input.token !== 'string') {\n return Response.json({ error: 'Missing invite token' }, { status: 400 })\n }\n\n const [invite] = await db\n .select()\n .from(workspaceMembers)\n .where(eq(workspaceMembers.inviteToken, input.token))\n .limit(1)\n\n if (!invite) return Response.json({ error: 'Invalid or expired invite' }, { status: 404 })\n if (invite.acceptedAt) return Response.json({ error: 'Invite already accepted' }, { status: 409 })\n\n if (invite.inviteEmail && invite.inviteEmail.toLowerCase() !== input.actor.email?.toLowerCase()) {\n return Response.json(\n { error: `This invite was sent to ${invite.inviteEmail}. Please sign in with that email.` },\n { status: 403 },\n )\n }\n\n const [workspace] = await db\n .select({ id: workspaces.id, organizationId: workspaces.organizationId })\n .from(workspaces)\n .where(eq(workspaces.id, invite.workspaceId))\n .limit(1)\n\n if (!workspace) return Response.json({ error: 'Project not found' }, { status: 404 })\n const organizationId = (workspace as { organizationId: string }).organizationId\n\n // Atomic accept: only succeeds if the token still exists and is unaccepted,\n // so two concurrent accepts can't both win.\n const updated = await db\n .update(workspaceMembers)\n .set({\n userId: input.actor.id,\n acceptedAt: new Date(),\n inviteToken: null,\n })\n .where(and(\n eq(workspaceMembers.inviteToken, input.token),\n isNull(workspaceMembers.acceptedAt),\n ))\n .returning({ id: workspaceMembers.id })\n\n if (updated.length === 0) return Response.json({ error: 'Invite already accepted' }, { status: 409 })\n\n const [orgMember] = await db\n .insert(organizationMembers)\n .values({\n organizationId,\n userId: input.actor.id,\n role: 'member',\n })\n .onConflictDoUpdate({\n target: [organizationMembers.organizationId, organizationMembers.userId],\n set: { updatedAt: new Date() },\n })\n .returning()\n\n await db\n .update(workspaceMembers)\n .set({ organizationMemberId: invite.organizationMemberId ?? orgMember!.id })\n .where(eq(workspaceMembers.id, updated[0]!.id))\n\n if (memberSyncSeam?.add) {\n const role = invite.role as WorkspaceRole\n fireSync(() => memberSyncSeam.add!({ workspaceId: invite.workspaceId, userId: input.actor.id, role }))\n }\n\n return Response.json({\n success: true,\n workspaceId: invite.workspaceId,\n role: invite.role,\n })\n }\n\n // ── internal query helpers ──\n\n async function getUserByEmail(email: string) {\n const [user] = await db\n .select({ id: users.id, email: users.email })\n .from(users)\n .where(eq(users.email, email))\n .limit(1)\n return user ?? null\n }\n\n async function getOrganizationMember(organizationId: string, userId: string) {\n const [member] = await db\n .select()\n .from(organizationMembers)\n .where(and(eq(organizationMembers.organizationId, organizationId), eq(organizationMembers.userId, userId)))\n .limit(1)\n return member ?? null\n }\n\n async function findExistingProjectInvite(workspaceId: string, email: string, userId?: string) {\n const byEmail = await db\n .select({ id: workspaceMembers.id })\n .from(workspaceMembers)\n .where(and(eq(workspaceMembers.workspaceId, workspaceId), eq(workspaceMembers.inviteEmail, email)))\n .limit(1)\n if (byEmail[0]) return byEmail[0]\n if (!userId) return null\n const byUser = await db\n .select({ id: workspaceMembers.id })\n .from(workspaceMembers)\n .where(and(eq(workspaceMembers.workspaceId, workspaceId), eq(workspaceMembers.userId, userId)))\n .limit(1)\n return byUser[0] ?? null\n }\n\n async function hasPendingOrgInvite(organizationId: string, email: string): Promise<boolean> {\n const [row] = await db\n .select({ id: workspaceMembers.id })\n .from(workspaceMembers)\n .innerJoin(workspaces, eq(workspaces.id, workspaceMembers.workspaceId))\n .where(and(\n eq(workspaces.organizationId, organizationId),\n eq(workspaceMembers.inviteEmail, email),\n isNull(workspaceMembers.acceptedAt),\n ))\n .limit(1)\n return Boolean(row)\n }\n\n return { listMembers, inviteMember, updateMemberRole, removeMember, acceptInvite }\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,KAAK,IAAI,cAAc;AAmDzB,IAAM,iBAAN,cAA6B,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACT,YAAY,SAAiB,OAAwE,CAAC,GAAG;AACvG,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,KAAK,UAAU;AAC7B,SAAK,aAAa,KAAK;AACvB,SAAK,eAAe,KAAK;AAAA,EAC3B;AACF;AA8CO,SAAS,iBAAiB,MAAyB;AACxD,QAAM,EAAE,IAAI,QAAQ,WAAW,gBAAgB,QAAQ,aAAa,eAAe,IAAI;AACvF,QAAM,EAAE,eAAe,qBAAqB,iBAAiB,IAAI;AACjE,QAAM,QAAQ;AACd,QAAM,aAAa;AAEnB,WAAS,SAAS,IAAgC;AAChD,QAAI;AACF,cAAQ,QAAQ,GAAG,CAAC,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IACtC,QAAQ;AAAA,IAER;AAAA,EACF;AAEA,iBAAe,YAAY,OAA2E;AACpG,UAAM,YAAY,MAAM,OAAO,mBAAmB,MAAM,aAAa,MAAM,MAAM,EAAE;AACnF,QAAI,CAAC,UAAW,QAAO,SAAS,KAAK,EAAE,OAAO,sBAAsB,GAAG,EAAE,QAAQ,IAAI,CAAC;AAEtF,UAA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