@tangle-network/agent-app 0.63.44 → 0.63.46

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 (63) hide show
  1. package/dist/{DesignCanvas-VKZ7Y3JU.js → DesignCanvas-Q65UV4D5.js} +3 -2
  2. package/dist/{DesignCanvasEditor-3V53YLLZ.js → DesignCanvasEditor-THEFESEX.js} +3 -2
  3. package/dist/app-auth/index.js +2 -1
  4. package/dist/app-auth/index.js.map +1 -1
  5. package/dist/chat-routes/index.js +10 -8
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/chat-routes/route-storage.d.ts +1 -0
  8. package/dist/chat-routes/turn-ownership.d.ts +1 -1
  9. package/dist/chat-routes/turn-route-contracts.d.ts +2 -0
  10. package/dist/{chunk-ZGGEYYEQ.js → chunk-4E2MUVGL.js} +3 -3
  11. package/dist/chunk-5VE4IDSU.js +75 -0
  12. package/dist/chunk-5VE4IDSU.js.map +1 -0
  13. package/dist/{chunk-CTREXL3O.js → chunk-67CSI5PU.js} +2 -65
  14. package/dist/chunk-67CSI5PU.js.map +1 -0
  15. package/dist/{chunk-DPTNKH22.js → chunk-H6BRJU5M.js} +1 -73
  16. package/dist/chunk-H6BRJU5M.js.map +1 -0
  17. package/dist/{chunk-XTQLZG6M.js → chunk-HHIEHETJ.js} +3 -3
  18. package/dist/{chunk-RZMQ2J5P.js → chunk-IMFJMFHK.js} +14 -27
  19. package/dist/chunk-IMFJMFHK.js.map +1 -0
  20. package/dist/chunk-INW4FSID.js +66 -0
  21. package/dist/chunk-INW4FSID.js.map +1 -0
  22. package/dist/{chunk-N5RWYR5N.js → chunk-ZTGITMYQ.js} +10 -1
  23. package/dist/chunk-ZTGITMYQ.js.map +1 -0
  24. package/dist/design-canvas/index.js +2 -1
  25. package/dist/design-canvas/index.js.map +1 -1
  26. package/dist/design-canvas-react/engine.js +2 -1
  27. package/dist/design-canvas-react/index.js +3 -2
  28. package/dist/design-canvas-react/index.js.map +1 -1
  29. package/dist/design-canvas-react/lazy.js +1 -1
  30. package/dist/platform/index.js +2 -1
  31. package/dist/platform/index.js.map +1 -1
  32. package/dist/preset-cloudflare/index.js +1 -1
  33. package/dist/public-consultation/index.js +7 -5
  34. package/dist/public-consultation/index.js.map +1 -1
  35. package/dist/sandbox/index.js +8 -6
  36. package/dist/sequences/index.js +2 -1
  37. package/dist/sequences/index.js.map +1 -1
  38. package/dist/skills-placement/box.js +4 -2
  39. package/dist/skills-placement/box.js.map +1 -1
  40. package/dist/turn-stream/adapters.d.ts +6 -6
  41. package/dist/turn-stream/core.d.ts +1 -0
  42. package/dist/turn-stream/index.js +7 -3
  43. package/dist/turn-stream/index.js.map +1 -1
  44. package/dist/vault/store/box-state.d.ts +125 -0
  45. package/dist/vault/store/coordinator.d.ts +9 -1
  46. package/dist/vault/store/index.d.ts +4 -0
  47. package/dist/vault/store/index.js +1227 -4
  48. package/dist/vault/store/index.js.map +1 -1
  49. package/dist/vault/store/sandbox-engine.d.ts +19 -0
  50. package/dist/vault/store/sandbox-hydrate.d.ts +59 -0
  51. package/dist/vault/store/sandbox-reconcile.d.ts +55 -0
  52. package/dist/vault/store/sandbox-sync.d.ts +37 -1
  53. package/dist/vault/store/store.d.ts +10 -1
  54. package/dist/web/index.js +7 -5
  55. package/package.json +1 -1
  56. package/dist/chunk-CTREXL3O.js.map +0 -1
  57. package/dist/chunk-DPTNKH22.js.map +0 -1
  58. package/dist/chunk-N5RWYR5N.js.map +0 -1
  59. package/dist/chunk-RZMQ2J5P.js.map +0 -1
  60. /package/dist/{DesignCanvas-VKZ7Y3JU.js.map → DesignCanvas-Q65UV4D5.js.map} +0 -0
  61. /package/dist/{DesignCanvasEditor-3V53YLLZ.js.map → DesignCanvasEditor-THEFESEX.js.map} +0 -0
  62. /package/dist/{chunk-ZGGEYYEQ.js.map → chunk-4E2MUVGL.js.map} +0 -0
  63. /package/dist/{chunk-XTQLZG6M.js.map → chunk-HHIEHETJ.js.map} +0 -0
@@ -16,6 +16,7 @@ export interface ChatTurnStoreBindings {
16
16
  export declare function createDefaultTurnLock<TContext>(store: Pick<ChatTurnStoreBindings, 'lock' | 'region'>): {
17
17
  acquire(args: import("../turn-stream").TurnLockSeamArgs<TContext>): Promise<import("../turn-stream").TurnLockSeamResult>;
18
18
  release(handle: unknown): Promise<void>;
19
+ park(handle: unknown): Promise<boolean>;
19
20
  warm(target: {
20
21
  tenantId: string;
21
22
  threadId?: string;
@@ -16,7 +16,7 @@ interface OwnershipState {
16
16
  }
17
17
  /** One transfer of terminal authority, retaining the route only as a live projector. */
18
18
  export declare function createChatTurnOwnership(state: OwnershipState, log: (message: string, meta?: Record<string, unknown>) => void, turnStreamId: string, options: {
19
- turnLock?: Pick<ChatTurnLock<unknown>, 'release'>;
19
+ turnLock?: Pick<ChatTurnLock<unknown>, 'release' | 'park'>;
20
20
  }): {
21
21
  handoffCompletion: (handoff?: NativeCompletionHandoffOptions) => Promise<void>;
22
22
  releaseLock: () => Promise<void>;
@@ -383,6 +383,8 @@ export type ChatTurnLockResult = {
383
383
  export interface ChatTurnLock<TContext, TResource = unknown> {
384
384
  acquire(args: ChatTurnProduceArgs<TContext, TResource>): ChatTurnLockResult | Promise<ChatTurnLockResult>;
385
385
  release(handle: unknown): void | Promise<void>;
386
+ /** Record a release for the durable owner to complete without freeing the lock; absent or false, the lock stays held. */
387
+ park?(handle: unknown): Promise<boolean>;
386
388
  /** Bring up whatever `acquire` will talk to, as soon as the turn is admitted
387
389
  * and while `prepareTurn` and the history read run. Never awaited; a failure
388
390
  * is logged and the turn goes on to `acquire` as usual. */
@@ -1,14 +1,14 @@
1
1
  // src/design-canvas-react/lazy.tsx
2
2
  import { lazy } from "react";
3
3
  var DesignCanvasLazy = lazy(
4
- () => import("./DesignCanvasEditor-3V53YLLZ.js").then((m) => ({ default: m.DesignCanvasEditor }))
4
+ () => import("./DesignCanvasEditor-THEFESEX.js").then((m) => ({ default: m.DesignCanvasEditor }))
5
5
  );
6
6
  var DesignCanvasChromeLazy = lazy(
7
- () => import("./DesignCanvas-VKZ7Y3JU.js").then((m) => ({ default: m.DesignCanvas }))
7
+ () => import("./DesignCanvas-Q65UV4D5.js").then((m) => ({ default: m.DesignCanvas }))
8
8
  );
9
9
 
10
10
  export {
11
11
  DesignCanvasLazy,
12
12
  DesignCanvasChromeLazy
13
13
  };
14
- //# sourceMappingURL=chunk-ZGGEYYEQ.js.map
14
+ //# sourceMappingURL=chunk-4E2MUVGL.js.map
@@ -0,0 +1,75 @@
1
+ // src/web/mime.ts
2
+ var BASE_EXT_TO_MIME = {
3
+ md: "text/markdown",
4
+ markdown: "text/markdown",
5
+ txt: "text/plain",
6
+ log: "text/plain",
7
+ csv: "text/csv",
8
+ tsv: "text/tab-separated-values",
9
+ json: "application/json",
10
+ yaml: "text/yaml",
11
+ yml: "text/yaml",
12
+ xml: "application/xml",
13
+ html: "text/html",
14
+ htm: "text/html",
15
+ pdf: "application/pdf",
16
+ png: "image/png",
17
+ jpg: "image/jpeg",
18
+ jpeg: "image/jpeg",
19
+ gif: "image/gif",
20
+ webp: "image/webp",
21
+ avif: "image/avif",
22
+ heic: "image/heic",
23
+ heif: "image/heif",
24
+ svg: "image/svg+xml",
25
+ mp4: "video/mp4",
26
+ webm: "video/webm",
27
+ mov: "video/quicktime",
28
+ mp3: "audio/mpeg",
29
+ wav: "audio/wav",
30
+ ogg: "audio/ogg",
31
+ m4a: "audio/mp4",
32
+ aac: "audio/aac"
33
+ };
34
+ var PREVIEW_EXT_TO_MIME = {
35
+ ...BASE_EXT_TO_MIME,
36
+ mdx: "text/markdown",
37
+ ts: "text/typescript",
38
+ tsx: "text/typescript-jsx",
39
+ js: "text/javascript",
40
+ jsx: "text/jsx",
41
+ py: "text/x-python",
42
+ rs: "text/x-rust",
43
+ go: "text/x-go",
44
+ java: "text/x-java",
45
+ rb: "text/x-ruby",
46
+ sh: "text/x-shellscript",
47
+ bash: "text/x-shellscript",
48
+ zsh: "text/x-shellscript",
49
+ toml: "text/x-toml",
50
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
51
+ xls: "application/vnd.ms-excel"
52
+ };
53
+ function lookup(table, filename) {
54
+ const ext = filename.split(".").pop()?.toLowerCase();
55
+ if (!ext) return "text/plain";
56
+ return table[ext] ?? "text/plain";
57
+ }
58
+ function sniffMimeFromName(filename) {
59
+ return lookup(BASE_EXT_TO_MIME, filename);
60
+ }
61
+ function sniffMime(filename, extraExtensions) {
62
+ const ext = filename.split(".").pop()?.toLowerCase();
63
+ if (ext && extraExtensions && Object.hasOwn(extraExtensions, ext)) return extraExtensions[ext];
64
+ return lookup(PREVIEW_EXT_TO_MIME, filename);
65
+ }
66
+ function isEditableMime(mime) {
67
+ return mime === "text/markdown";
68
+ }
69
+
70
+ export {
71
+ sniffMimeFromName,
72
+ sniffMime,
73
+ isEditableMime
74
+ };
75
+ //# sourceMappingURL=chunk-5VE4IDSU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/mime.ts"],"sourcesContent":["/**\n * Filename extension → media type. Browser-safe; no imports.\n *\n * `sniffMimeFromName` is the generic last-resort typing for uploads and\n * promoted agent files. `sniffMime` adds the code, MDX and spreadsheet types a\n * file preview picks its renderer from (rendered markdown, line-numbered code,\n * image, video, tabular CSV, embedded PDF, monospace text fallback). An unknown\n * extension falls to `text/plain`; it is never a rejection.\n */\n\nconst BASE_EXT_TO_MIME: Readonly<Record<string, string>> = {\n md: 'text/markdown',\n markdown: 'text/markdown',\n txt: 'text/plain',\n log: 'text/plain',\n csv: 'text/csv',\n tsv: 'text/tab-separated-values',\n json: 'application/json',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n xml: 'application/xml',\n html: 'text/html',\n htm: 'text/html',\n pdf: 'application/pdf',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n avif: 'image/avif',\n heic: 'image/heic',\n heif: 'image/heif',\n svg: 'image/svg+xml',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n}\n\nconst PREVIEW_EXT_TO_MIME: Readonly<Record<string, string>> = {\n ...BASE_EXT_TO_MIME,\n mdx: 'text/markdown',\n ts: 'text/typescript',\n tsx: 'text/typescript-jsx',\n js: 'text/javascript',\n jsx: 'text/jsx',\n py: 'text/x-python',\n rs: 'text/x-rust',\n go: 'text/x-go',\n java: 'text/x-java',\n rb: 'text/x-ruby',\n sh: 'text/x-shellscript',\n bash: 'text/x-shellscript',\n zsh: 'text/x-shellscript',\n toml: 'text/x-toml',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n xls: 'application/vnd.ms-excel',\n}\n\nfunction lookup(table: Readonly<Record<string, string>>, filename: string): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (!ext) return 'text/plain'\n return table[ext] ?? 'text/plain'\n}\n\n/** Generic extension → mime for uploads and promoted files. */\nexport function sniffMimeFromName(filename: string): string {\n return lookup(BASE_EXT_TO_MIME, filename)\n}\n\n/** Extension → mime for choosing a file preview renderer. A product's own\n * file types (e.g. `{ fountain: 'text/plain' }`) go in `extraExtensions`. */\nexport function sniffMime(filename: string, extraExtensions?: Readonly<Record<string, string>>): string {\n const ext = filename.split('.').pop()?.toLowerCase()\n if (ext && extraExtensions && Object.hasOwn(extraExtensions, ext)) return extraExtensions[ext]!\n return lookup(PREVIEW_EXT_TO_MIME, filename)\n}\n\n/** The vault editor surface is Markdown-only. */\nexport function isEditableMime(mime: string): boolean {\n return mime === 'text/markdown'\n}\n"],"mappings":";AAUA,IAAM,mBAAqD;AAAA,EACzD,IAAI;AAAA,EACJ,UAAU;AAAA,EACV,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,MAAM;AAAA,EACN,MAAM;AAAA,EACN,KA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) {
260
260
  return ok(void 0);
261
261
  }
262
262
 
263
- // src/sandbox/binary-read.ts
264
- function shellQuote(value) {
265
- return `'${value.replaceAll("'", `'"'"'`)}'`;
266
- }
267
- function base64ToBytes(base64) {
268
- const binary = atob(base64);
269
- const bytes = new Uint8Array(binary.length);
270
- for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
271
- return bytes;
272
- }
273
- function execInSandbox(box, command, options) {
274
- return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command);
275
- }
276
- async function statSandboxFileSize(box, absolutePath, options) {
277
- const quotedPath = shellQuote(absolutePath);
278
- let result;
279
- try {
280
- result = await execInSandbox(box, `wc -c < ${quotedPath}`, options);
281
- } catch (err) {
282
- return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
283
- }
284
- if (result.exitCode !== 0) {
285
- return { succeeded: false, error: result.stderr || "unknown error" };
286
- }
287
- const size = Number.parseInt(result.stdout.trim(), 10);
288
- if (!Number.isFinite(size)) {
289
- return { succeeded: false, error: `could not parse file size from "${result.stdout.trim()}"` };
290
- }
291
- return { succeeded: true, value: size };
292
- }
293
- async function readSandboxBinaryBytes(box, absolutePath, expectedSize, options) {
294
- const quotedPath = shellQuote(absolutePath);
295
- let result;
296
- try {
297
- result = await execInSandbox(box, `base64 ${quotedPath}`, options);
298
- } catch (err) {
299
- return { succeeded: false, error: err instanceof Error ? err.message : String(err) };
300
- }
301
- if (result.exitCode !== 0) {
302
- return { succeeded: false, error: result.stderr || "unknown error" };
303
- }
304
- const cleaned = result.stdout.replace(/\s+/g, "");
305
- let bytes;
306
- try {
307
- bytes = base64ToBytes(cleaned);
308
- } catch (err) {
309
- return {
310
- succeeded: false,
311
- error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`
312
- };
313
- }
314
- if (bytes.byteLength !== expectedSize) {
315
- return {
316
- succeeded: false,
317
- error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} \u2014 output truncated in transit`
318
- };
319
- }
320
- return { succeeded: true, value: { bytes, size: expectedSize } };
321
- }
322
-
323
263
  export {
324
264
  isRuntimeExecAuthError,
325
265
  isRuntimeAuthRefreshDenied,
@@ -327,9 +267,6 @@ export {
327
267
  fail,
328
268
  shellSingleQuote,
329
269
  splitDeferredProfileFiles,
330
- writeProfileFilesToBox,
331
- shellQuote,
332
- statSandboxFileSize,
333
- readSandboxBinaryBytes
270
+ writeProfileFilesToBox
334
271
  };
335
- //# sourceMappingURL=chunk-CTREXL3O.js.map
272
+ //# sourceMappingURL=chunk-67CSI5PU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/sandbox/exec-failure.ts","../src/sandbox/outcome.ts","../src/sandbox/profile-files.ts","../src/sandbox/shell-path.ts"],"sourcesContent":["\n\n// Sentinel cause for a client-side per-exec timeout (a hung/wedged proxy exec).\n// Carried as the `.cause` of the fail-loud Outcome so callers see the wedged\n// command instead of an opaque infinite hang.\nexport class ProfileWriteExecTimeoutError extends Error {\n constructor(timeoutMs: number) {\n super(`exec exceeded ${timeoutMs}ms (proxy hang/wedge)`)\n this.name = 'ProfileWriteExecTimeoutError'\n }\n}\n\nconst TRANSIENT_EXEC_STATUS_CODES = new Set([408, 409, 425, 429, 500, 502, 503, 504])\n\nconst TRANSIENT_EXEC_CODE_RE = /^(ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ECONNABORTED)$/i\n\nconst TRANSIENT_EXEC_MESSAGE_RE =\n /\\b(408|409|425|429|500|502|503|504)\\b|rate.?limit|too many requests|\\bfetch failed\\b|network error|connection reset|socket hang up|timed? out|service unavailable|bad gateway|gateway timeout|internal server error|\\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\\b.{0,80}\\bnot ready\\b|\\bnot ready\\b.{0,80}\\b(?:sidecar|runtime|exec(?:ution)?|terminal|sandbox|service|command(?:s)?|proxy)\\b/i\n\nfunction errorStatus(err: { status?: unknown; statusCode?: unknown; response?: unknown }): number | undefined {\n const rawStatus = err.status ?? err.statusCode ?? (\n err.response && typeof err.response === 'object'\n ? (err.response as { status?: unknown }).status\n : undefined\n )\n if (typeof rawStatus === 'number') return rawStatus\n if (typeof rawStatus === 'string' && /^\\d+$/.test(rawStatus)) return Number(rawStatus)\n return undefined\n}\n\nfunction retryAfterMs(err: unknown, seen = new Set<object>()): number | undefined {\n if (!err || typeof err !== 'object') return undefined\n if (seen.has(err)) return undefined\n seen.add(err)\n const e = err as { retryAfterMs?: unknown; cause?: unknown }\n if (typeof e.retryAfterMs === 'number') return e.retryAfterMs\n return retryAfterMs(e.cause, seen)\n}\n\nfunction isTransientExecError(err: unknown, seen = new Set<object>()): boolean {\n if (!err || typeof err !== 'object') return false\n if (seen.has(err)) return false\n seen.add(err)\n const e = err as {\n status?: unknown\n statusCode?: unknown\n response?: unknown\n code?: unknown\n message?: unknown\n cause?: unknown\n }\n const status = errorStatus(e)\n if (status !== undefined && TRANSIENT_EXEC_STATUS_CODES.has(status)) return true\n if (typeof e.code === 'string') {\n if (TRANSIENT_EXEC_CODE_RE.test(e.code)) return true\n if (/rate.?limit|too.?many.?requests|429|server.?error|service.?unavailable/i.test(e.code)) return true\n }\n if (typeof e.message === 'string' && TRANSIENT_EXEC_MESSAGE_RE.test(e.message)) return true\n return isTransientExecError(e.cause, seen)\n}\n\nexport function isRuntimeExecAuthError(err: unknown, seen = new Set<object>()): boolean {\n if (!err || typeof err !== 'object') return false\n if (seen.has(err)) return false\n seen.add(err)\n const e = err as {\n status?: unknown\n statusCode?: unknown\n response?: unknown\n code?: unknown\n name?: unknown\n message?: unknown\n cause?: unknown\n }\n if (errorStatus(e) === 401) return true\n if (\n typeof e.code === 'string' &&\n /^(AUTH_ERROR|AUTHENTICATION_ERROR|UNAUTHORIZED|UNAUTHENTICATED|ERR_UNAUTHORIZED|ERR_UNAUTHENTICATED|401)$/i.test(e.code)\n ) {\n return true\n }\n if (\n typeof e.name === 'string' &&\n /^(AuthError|AuthenticationError|UnauthorizedError|UnauthenticatedError|SandboxAuthError)$/i.test(e.name)\n ) {\n return true\n }\n return isRuntimeExecAuthError(e.cause, seen)\n}\n\nexport function isRuntimeAuthRefreshDenied(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false\n return (\n isRuntimeExecAuthError(err) ||\n errorStatus(err as { status?: unknown; statusCode?: unknown; response?: unknown }) === 403\n )\n}\n\n// Classify an exec failure as transient-retryable. Retryable shapes share the\n// same backoff path: rate-limit (HTTP 429 + retryAfterMs), client-side timeout,\n// and transient sidecar/transport/readiness failures surfaced as SandboxError-\n// shaped objects, fetch errors, network resets, or 5xx-ish messages. Everything\n// else fails loud. Non-zero shell exits never reach this classifier.\nexport function transientExecError(err: unknown): { retryable: boolean; retryAfterMs?: number } {\n if (err instanceof ProfileWriteExecTimeoutError) return { retryable: true }\n if (isTransientExecError(err)) return { retryable: true, retryAfterMs: retryAfterMs(err) }\n return { retryable: false }\n}\n","// Shared Outcome triple for the sandbox modules. Lives in a dependency-free\n// leaf so helpers can use it without importing the substrate-bound index.\n/** Represent success or failure of an operation with corresponding value or error information */\nexport type Outcome<T> =\n | { succeeded: true; value: T }\n | { succeeded: false; error: Error }\n\nexport const ok = <T>(value: T): Outcome<T> => ({ succeeded: true, value })\nexport const fail = (error: unknown): Outcome<never> => ({\n succeeded: false,\n error: error instanceof Error ? error : new Error(String(error)),\n})\n","import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { ExecResult } from '@tangle-network/sandbox/core'\nimport { ProfileWriteExecTimeoutError, transientExecError } from './exec-failure'\nimport { type Outcome, fail, ok } from './outcome'\nimport { createHash } from 'node:crypto'\nimport { shellPath, shellSingleQuote } from './shell-path'\n\n// Split a profile's `resources.files` into the inline mounts that can be\n// written into a running box and the rest (non-inline refs that the\n// orchestrator must resolve, so they stay in the create payload). Returns the\n// inline set to defer and a profile copy with those inline files removed.\n/** Split profile files into inline deferred files and a lean profile without them */\nexport function splitDeferredProfileFiles(\n profile: AgentProfile,\n): { leanProfile: AgentProfile; deferredFiles: AgentProfileFileMount[] } {\n const files = profile.resources?.files ?? []\n const deferredFiles: AgentProfileFileMount[] = []\n const keptFiles: AgentProfileFileMount[] = []\n for (const mount of files) {\n if (mount.resource.kind === 'inline') deferredFiles.push(mount)\n else keptFiles.push(mount)\n }\n if (deferredFiles.length === 0) return { leanProfile: profile, deferredFiles }\n const leanProfile: AgentProfile = {\n ...profile,\n resources: { ...(profile.resources ?? {}), files: keptFiles },\n }\n return { leanProfile, deferredFiles }\n}\n\n// The runtime exec proxy (`box.exec` → /terminals/commands) hangs (30s\n// timeout) on any request whose body crosses ~4096 bytes, and one oversized\n// exec wedges the channel so every later exec on the box hangs too. We slice\n// each file's base64 into appends whose full command string stays well under\n// that cap. 3000 chars of base64 leaves ~1000 bytes of headroom for the\n// surrounding `printf '%s' '<slice>' >> <path>.b64` command plus the proxy's\n// JSON request envelope — comfortably below 4096.\nconst PROFILE_WRITE_B64_CHUNK_CHARS = 3000\n\n// gtm's corpus is ~135 small execs; on a cold box the runtime exec proxy\n// hard-throttles (HTTP 429 after ~21 execs in ~34s) and, under sustained load,\n// SILENTLY HANGS instead of returning 429 — one parked exec wedges the channel\n// and `writeProfileFilesToBox` never returns, so `ensureWorkspaceSandbox`\n// parks the worker (~140s, no exception). These failures plus sidecar exec-plane\n// readiness/transport failures (5xx, reset, fetch/network errors) are transient:\n// retry the SAME exec with exponential backoff before failing loud. A non-zero\n// exit is a real command failure, never retried.\nconst PROFILE_WRITE_MAX_RETRIES = 4\n\nconst PROFILE_WRITE_RETRY_BASE_MS = 250\n\nconst PROFILE_WRITE_RETRY_MAX_MS = 2000\n\n// Client-side hard ceiling per exec. The proxy's own 30s timeout is unreliable\n// once the channel wedges (it can hang past it), so we race each exec against an\n// independent timer we control: a wedged exec is abandoned here and retried as a\n// transient transport error, never silently parked. We also pass timeoutMs to\n// the SDK as defense-in-depth, but the race is the guarantee.\nconst PROFILE_WRITE_EXEC_TIMEOUT_MS = 30_000\n\n// Pacing between execs to stay under the proxy throttle that triggers the hang.\n// The drill saw throttling at ~0.6 exec/s bursts; ~150ms between ~135 execs\n// adds well under a minute total and keeps the burst rate below the trip point.\n// On by default for the deferred path; overridable for tests/tuning.\nconst PROFILE_WRITE_PACE_MS = 150\n\nconst sleep = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))\n\n// A mount whose path sits in a bin directory is made executable. Shared so the\n// file-API eligibility check and the exec branch agree on \"executable by dir\".\nconst PROFILE_BIN_DIR_RE = /(^|\\/)(s?bin)\\//\n\n// Run a box.exec, abandoning it if it does not settle within timeoutMs. The\n// returned promise rejects with ProfileWriteExecTimeoutError on timeout so the\n// retry loop treats a hang exactly like a transient transport error. We also\n// forward timeoutMs to the SDK so the underlying request is cancelled when the\n// SDK honors it; the race covers the case where it does not.\nfunction execWithTimeout(\n box: SandboxInstance,\n cmd: string,\n timeoutMs: number,\n): Promise<ExecResult> {\n return new Promise<ExecResult>((resolve, reject) => {\n let settled = false\n const timer = setTimeout(() => {\n if (settled) return\n settled = true\n reject(new ProfileWriteExecTimeoutError(timeoutMs))\n }, timeoutMs)\n box.exec(cmd, { timeoutMs }).then(\n (res) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n resolve(res)\n },\n (err) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n reject(err)\n },\n )\n })\n}\n\n// Materialize inline profile files into a running box via `box.exec`. Uses a\n// base64 pipe so arbitrary content (scripts, unicode, special chars) lands\n// byte-exact, and writes to ANY absolute path (e.g. /usr/local/bin) or a\n// `~`-relative path — the exec runs as the sidecar, which is not bound by the\n// safe-prefix allow-list the /files/write API enforces. Sets the executable\n// bit when the mount declares it OR the target is a bin directory.\n//\n// Each file is written in several small execs (mkdir, one append per base64\n// chunk, then a decode+cleanup) so no single exec request body trips the\n// ~4 KiB proxy cap. Writes are sequential; a single bad mount stops the batch\n// and the first failure is returned (fail-loud), the rest are not attempted.\n//\n// Each exec is bounded by a client-side hard timeout and retried with backoff\n// on transient rate-limit/readiness/transport failures, so one wedged or early\n// exec-plane request can never park the caller (and thus never park provisioning).\n// A small pace between execs keeps the burst rate below the proxy throttle that\n// triggers the hang.\n/** Define options to control execution timeout, pacing, and retry behavior when writing profile files */\nexport interface WriteProfileFilesOptions {\n // Hard ceiling per exec (ms). A hung/wedged exec is abandoned and retried.\n execTimeoutMs?: number\n // Delay between execs (ms) to stay under the proxy throttle. 0 disables it.\n paceMs?: number\n // Max retries for a transient exec before failing loud.\n maxRetries?: number\n}\n\n// The workspace-relative target for a deferred inline mount when it can be\n// materialized through the sidecar file API (`box.fs.writeMany` — FILES rate\n// group, 300/min, whole-file, auto-mkdir) instead of the chunked terminal-exec\n// path (50/min); null when it must stay on exec. The file API resolves relative\n// paths from the workspace root, so eligibility is: inline and a path that\n// resolves under the workspace root with no `..`/`.sidecar` segment. `~/…` and\n// `/home/agent/…` are home-relative; agent sandboxes set $HOME to the workspace\n// root, so both map to the same relative target. Other absolute (`/…`) and bare\n// `~`/`~user` mounts stay on exec.\nfunction fileApiTarget(mount: AgentProfileFileMount): string | null {\n if (mount.resource.kind !== 'inline') return null\n let rel: string\n if (mount.path.startsWith('~/')) rel = mount.path.slice(2)\n else if (mount.path.startsWith('/home/agent/')) rel = mount.path.slice('/home/agent/'.length)\n else if (mount.path.startsWith('/') || mount.path.startsWith('~')) return null\n else rel = mount.path\n if (rel.length === 0 || rel.startsWith('/') || rel.split('/').some((seg) => seg === '..' || seg === '.sidecar')) {\n return null\n }\n return rel\n}\n\nfunction isExecutableProfileFile(mount: AgentProfileFileMount): boolean {\n return mount.executable ?? PROFILE_BIN_DIR_RE.test(mount.path)\n}\n\nfunction profileFileMode(mount: AgentProfileFileMount): number | undefined {\n return isExecutableProfileFile(mount) ? 0o755 : undefined\n}\n\n// The sandbox gateway rejects request bodies over 1 MiB, and `writeMany` sends\n// each file as one JSON string, so a file larger than one request can never\n// land through it — the SDK splits batches but not files. Such a file goes\n// through the chunked `fs.uploadData` when the SDK has it and the chunked exec\n// path otherwise: the rule the SDK's `materializeProfileFileMounts` applies.\nconst PROFILE_FILE_API_MAX_JSON_BYTES = 1024 * 1024 - 16 * 1024\n\nfunction fitsProfileFileApi(content: string): boolean {\n const encoder = new TextEncoder()\n // JSON escaping grows one byte to at most six (`\\u001f`).\n if (encoder.encode(content).byteLength * 6 <= PROFILE_FILE_API_MAX_JSON_BYTES) return true\n return encoder.encode(JSON.stringify(content)).byteLength <= PROFILE_FILE_API_MAX_JSON_BYTES\n}\n\ntype ProfileFileUpload = (remotePath: string, data: string, options?: { mode?: number }) => Promise<unknown>\n\nfunction fileApiSupportsMode(box: SandboxInstance): boolean {\n const fs = box.fs as (SandboxInstance['fs'] & { supportsWriteMode?: boolean }) | undefined\n return fs?.supportsWriteMode === true\n}\n\n/** Write profile files to a sandbox with pacing, retries, and optional execution timeout handling */\nexport async function writeProfileFilesToBox(\n box: SandboxInstance,\n files: AgentProfileFileMount[],\n options: WriteProfileFilesOptions = {},\n): Promise<Outcome<void>> {\n const execTimeoutMs = options.execTimeoutMs ?? PROFILE_WRITE_EXEC_TIMEOUT_MS\n const paceMs = options.paceMs ?? PROFILE_WRITE_PACE_MS\n const maxRetries = options.maxRetries ?? PROFILE_WRITE_MAX_RETRIES\n // The bulk of a profile corpus (skills, `~/.claude/skills/…`, config) is\n // inline and workspace-relative — write it in ONE paced,\n // retry-aware batch via the SDK's file API (`box.fs.writeMany`, FILES rate\n // group 300/min). The SDK owns the pacing + transient-retry this module used\n // to hand-roll. Absolute / bare-`~` paths can't use the file API\n // (prefix-restricted), so they stay on the chunked exec path.\n // Capability-guarded: SDKs without `writeMany` route everything through\n // exec; SDKs before @tangle-network/sandbox 0.9.4 keep executable files on\n // exec because they do not expose `supportsWriteMode` or forward file modes.\n const fileApiAvailable = typeof box.fs?.writeMany === 'function'\n const modeAwareFileApi = fileApiSupportsMode(box)\n const uploadData = (box.fs as { uploadData?: ProfileFileUpload } | undefined)?.uploadData\n const viaFileApi: { path: string; content: string; mode?: number }[] = []\n const viaUpload: { path: string; content: string; mode?: number }[] = []\n const viaExec: AgentProfileFileMount[] = []\n for (const mount of files) {\n if (mount.resource.kind !== 'inline') continue\n const fileApiPath = fileApiAvailable ? fileApiTarget(mount) : null\n const executable = isExecutableProfileFile(mount)\n if (fileApiPath !== null && (!executable || modeAwareFileApi)) {\n const mode = profileFileMode(mount)\n const content = mount.resource.content ?? ''\n const write = { path: fileApiPath, content, ...(mode !== undefined ? { mode } : {}) }\n if (fitsProfileFileApi(content)) viaFileApi.push(write)\n else if (typeof uploadData === 'function') viaUpload.push(write)\n else viaExec.push(mount)\n }\n else viaExec.push(mount)\n }\n if (viaFileApi.length > 0) {\n // `writeMany` is fail-loud on the first file it can't write. Preserve the\n // cause so the runtime-auth-refresh wrapper still detects a 401 — it\n // recurses `.cause` for an AuthError/401 shape (see isRuntimeExecAuthError).\n try {\n await box.fs.writeMany(viaFileApi, { paceMs, maxRetries })\n } catch (err) {\n return fail(new Error('writeProfileFilesToBox: file-API batch write failed', { cause: err }))\n }\n }\n for (const upload of viaUpload) {\n // The SDK paces, retries, and checksums each chunked upload session.\n try {\n await uploadData!.call(box.fs, upload.path, upload.content, upload.mode !== undefined ? { mode: upload.mode } : undefined)\n } catch (err) {\n return fail(new Error(`writeProfileFilesToBox: chunked upload failed for ${upload.path}`, { cause: err }))\n }\n }\n\n // Pace BETWEEN execs, not before the first or after the last. Shared across\n // the exec mounts so the (now smaller) executable/edge-case set stays paced.\n let execStarted = false\n\n // Pace + transient-retry ONE exec attempt: backoff/pace/fail-loud in one place.\n // `run` must be idempotent under unknown-outcome retries (exec writes\n // deterministic parts). A transient error retries with backoff up to\n // maxRetries (honoring a server Retry-After); anything else, or exhausting\n // retries, fails loud with the cause.\n const paceAndRetry = async <T>(run: () => Promise<T>, path: string): Promise<Outcome<T>> => {\n for (let attempt = 0; ; attempt++) {\n if (execStarted && paceMs > 0) await sleep(paceMs)\n execStarted = true\n try {\n return ok(await run())\n } catch (err) {\n const { retryable, retryAfterMs } = transientExecError(err)\n if (retryable && attempt < maxRetries) {\n const backoff = Math.min(PROFILE_WRITE_RETRY_BASE_MS * 2 ** attempt, PROFILE_WRITE_RETRY_MAX_MS)\n await sleep(retryAfterMs ?? backoff)\n continue\n }\n return fail(new Error(`writeProfileFilesToBox: exec failed for ${path}`, { cause: err }))\n }\n }\n }\n\n for (const mount of viaExec) {\n if (mount.resource.kind !== 'inline') continue // always true (viaExec is inline) — narrows for TS\n const content = mount.resource.content ?? ''\n const path = mount.path\n\n const b64 = Buffer.from(content, 'utf8').toString('base64')\n const b64Chunks: string[] = []\n for (let i = 0; i < b64.length; i += PROFILE_WRITE_B64_CHUNK_CHARS) {\n b64Chunks.push(b64.slice(i, i + PROFILE_WRITE_B64_CHUNK_CHARS))\n }\n const expectedSha256 = createHash('sha256').update(content, 'utf8').digest('hex')\n const dir = path.replace(/\\/[^/]*$/, '')\n const executable = isExecutableProfileFile(mount)\n const q = shellPath(path)\n const qb64 = shellPath(`${path}.b64`)\n const qtmp = shellPath(`${path}.tmp`)\n const qpartPrefix = shellPath(`${path}.b64.part.`)\n\n // Run one exec step. Transport errors (incl. a wedged-proxy timeout) are\n // paced + retried by paceAndRetry; a non-zero exit is a REAL command failure\n // — surfaced immediately, never retried.\n const step = async (cmd: string): Promise<Outcome<void>> => {\n const res = await paceAndRetry(() => execWithTimeout(box, cmd, execTimeoutMs), path)\n if (!res.succeeded) return res\n const exec = res.value\n if (exec.exitCode !== 0) {\n return fail(\n new Error(\n `writeProfileFilesToBox: failed to write ${path} (exit ${exec.exitCode}): ${exec.stderr.slice(0, 500)}`,\n ),\n )\n }\n return ok(undefined)\n }\n\n // Ensure the target directory exists. Chunk/final commands below are\n // idempotent under unknown-outcome transport retries; this no-op/mkdir is too.\n const mkdir = dir && dir !== path ? `mkdir -p ${shellPath(dir)}` : ':'\n let res = await step(mkdir)\n if (!res.succeeded) return res\n\n // Write each deterministic part with overwrite, not append. If the server\n // writes a part but the HTTP response is lost, retrying the same step lands\n // the same bytes instead of duplicating them.\n for (let i = 0; i < b64Chunks.length; i++) {\n const slice = b64Chunks[i]!\n res = await step(`printf '%s' '${slice}' > ${shellPath(`${path}.b64.part.${i}`)}`)\n if (!res.succeeded) return res\n }\n\n // Materialize from deterministic parts into a temp file, verify its content\n // hash, then atomically move into place. If the final exec succeeds but its\n // response is lost, a retry first accepts an already-correct target and only\n // re-runs idempotent chmod/cleanup. Parts are cleaned only after the target\n // hash is known-good, so a retried final step can always reconstruct.\n const chmod = executable ? `chmod +x ${q} || exit 1; ` : ''\n const checksumMismatch = shellSingleQuote(`writeProfileFilesToBox: checksum mismatch for ${path}`)\n const finalCmd =\n `expected='${expectedSha256}'; ` +\n `if [ -f ${q} ] && [ \"$(sha256sum ${q} | awk '{print $1}')\" = \"$expected\" ]; then ` +\n `${chmod}rm -f ${qb64} ${qtmp}; i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done; exit 0; fi; ` +\n `: > ${qb64} && ` +\n `i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do cat ${qpartPrefix}$i >> ${qb64} || exit 1; i=$((i+1)); done && ` +\n `base64 -d < ${qb64} > ${qtmp} && ` +\n `[ \"$(sha256sum ${qtmp} | awk '{print $1}')\" = \"$expected\" ] || { echo ${checksumMismatch} >&2; exit 1; }; ` +\n `mv ${qtmp} ${q} && ` +\n `${executable ? `chmod +x ${q} && ` : ''}` +\n `[ \"$(sha256sum ${q} | awk '{print $1}')\" = \"$expected\" ] || { echo ${checksumMismatch} >&2; exit 1; }; ` +\n `rm -f ${qb64} ${qtmp}; i=0; while [ \"$i\" -lt ${b64Chunks.length} ]; do rm -f ${qpartPrefix}$i; i=$((i+1)); done`\n res = await step(finalCmd)\n if (!res.succeeded) return res\n }\n return ok(undefined)\n}\n","\n\n// Single-quote a string for safe interpolation into a shell command.\nexport function shellSingleQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`\n}\n\n// Build a shell-safe path token that preserves tilde-home semantics. A path\n// beginning `~/` (or a bare `~`) must resolve to the box user's real `$HOME`,\n// but single-quoting the whole path suppresses shell `~` expansion and lands\n// the file in a literal directory named `~`. Expand the leading `~` to an\n// UNQUOTED `\"$HOME\"` (so the shell expands it) and single-quote only the\n// remainder. Absolute and relative paths are single-quoted unchanged.\nexport function shellPath(path: string): string {\n if (path === '~') return '\"$HOME\"'\n if (path.startsWith('~/')) {\n const rest = path.slice(2)\n return rest ? `\"$HOME\"/${shellSingleQuote(rest)}` : '\"$HOME\"'\n }\n return shellSingleQuote(path)\n}\n"],"mappings":";AAKO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EACtD,YAAY,WAAmB;AAC7B,UAAM,iBAAiB,SAAS,uBAAuB;AACvD,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IAAM,8BAA8B,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAEpF,IAAM,yBAAyB;AAE/B,IAAM,4BACJ;AAEF,SAAS,YAAY,KAAyF;AAC5G,QAAM,YAAY,IAAI,UAAU,IAAI,eAClC,IAAI,YAAY,OAAO,IAAI,aAAa,WACnC,IAAI,SAAkC,SACvC;AAEN,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,MAAI,OAAO,cAAc,YAAY,QAAQ,KAAK,SAAS,EAAG,QAAO,OAAO,SAAS;AACrF,SAAO;AACT;AAEA,SAAS,aAAa,KAAc,OAAO,oBAAI,IAAY,GAAuB;AAChF,MAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;AAC5C,MAAI,KAAK,IAAI,GAAG,EAAG,QAAO;AAC1B,OAAK,IAAI,GAAG;AACZ,QAAM,IAAI;AACV,MAAI,OAAO,EAAE,iBAAiB,SAAU,QAAO,EAAE;AACjD,SAAO,aAAa,EAAE,OAAO,IAAI;AACnC;AAEA,SAAS,qBAAqB,KAAc,OAAO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AAE;AACjG,UAAM,WACJ,aAAa,cAAc,cAChB,CAAC,wBAAwB,CAAC,+CAClC,KAAK,SAAS,IAAI,IAAI,IAAI,2BAA2B,UAAU,MAAM,gBAAgB,WAAW,yCAC5F,IAAI,6BACc,UAAU,MAAM,cAAc,WAAW,SAAS,IAAI,+CAChE,IAAI,MAAM,IAAI,sBACX,IAAI,mDAAmD,gBAAgB,uBACnF,IAAI,IAAI,CAAC,OACZ,aAAa,YAAY,CAAC,SAAS,EAAE,kBACtB,CAAC,mDAAmD,gBAAgB,0BAC7E,IAAI,IAAI,IAAI,2BAA2B,UAAU,MAAM,gBAAgB,WAAW;AAC7F,UAAM,MAAM,KAAK,QAAQ;AACzB,QAAI,CAAC,IAAI,UAAW,QAAO;AAAA,EAC7B;AACA,SAAO,GAAG,MAAS;AACrB;","names":["retryAfterMs","res"]}
@@ -105,75 +105,6 @@ function firstTouchAcquisitionCookie(request, cookieName, now = Date.now(), igno
105
105
  });
106
106
  }
107
107
 
108
- // src/web/mime.ts
109
- var BASE_EXT_TO_MIME = {
110
- md: "text/markdown",
111
- markdown: "text/markdown",
112
- txt: "text/plain",
113
- log: "text/plain",
114
- csv: "text/csv",
115
- tsv: "text/tab-separated-values",
116
- json: "application/json",
117
- yaml: "text/yaml",
118
- yml: "text/yaml",
119
- xml: "application/xml",
120
- html: "text/html",
121
- htm: "text/html",
122
- pdf: "application/pdf",
123
- png: "image/png",
124
- jpg: "image/jpeg",
125
- jpeg: "image/jpeg",
126
- gif: "image/gif",
127
- webp: "image/webp",
128
- avif: "image/avif",
129
- heic: "image/heic",
130
- heif: "image/heif",
131
- svg: "image/svg+xml",
132
- mp4: "video/mp4",
133
- webm: "video/webm",
134
- mov: "video/quicktime",
135
- mp3: "audio/mpeg",
136
- wav: "audio/wav",
137
- ogg: "audio/ogg",
138
- m4a: "audio/mp4",
139
- aac: "audio/aac"
140
- };
141
- var PREVIEW_EXT_TO_MIME = {
142
- ...BASE_EXT_TO_MIME,
143
- mdx: "text/markdown",
144
- ts: "text/typescript",
145
- tsx: "text/typescript-jsx",
146
- js: "text/javascript",
147
- jsx: "text/jsx",
148
- py: "text/x-python",
149
- rs: "text/x-rust",
150
- go: "text/x-go",
151
- java: "text/x-java",
152
- rb: "text/x-ruby",
153
- sh: "text/x-shellscript",
154
- bash: "text/x-shellscript",
155
- zsh: "text/x-shellscript",
156
- toml: "text/x-toml",
157
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
158
- xls: "application/vnd.ms-excel"
159
- };
160
- function lookup(table, filename) {
161
- const ext = filename.split(".").pop()?.toLowerCase();
162
- if (!ext) return "text/plain";
163
- return table[ext] ?? "text/plain";
164
- }
165
- function sniffMimeFromName(filename) {
166
- return lookup(BASE_EXT_TO_MIME, filename);
167
- }
168
- function sniffMime(filename, extraExtensions) {
169
- const ext = filename.split(".").pop()?.toLowerCase();
170
- if (ext && extraExtensions && Object.hasOwn(extraExtensions, ext)) return extraExtensions[ext];
171
- return lookup(PREVIEW_EXT_TO_MIME, filename);
172
- }
173
- function isEditableMime(mime) {
174
- return mime === "text/markdown";
175
- }
176
-
177
108
  // src/web/chat-stream-error.ts
178
109
  function isRecord(value) {
179
110
  return typeof value === "object" && value !== null && !Array.isArray(value);
@@ -293,13 +224,10 @@ export {
293
224
  acquisitionFromRequest,
294
225
  readFirstTouchAcquisition,
295
226
  firstTouchAcquisitionCookie,
296
- sniffMimeFromName,
297
- sniffMime,
298
- isEditableMime,
299
227
  parseRetryAfterSeconds,
300
228
  buildHttpChatStreamError,
301
229
  parseChatHttpErrorResponse,
302
230
  parseChatStreamError,
303
231
  parseChatStreamErrorEvent
304
232
  };
305
- //# sourceMappingURL=chunk-DPTNKH22.js.map
233
+ //# sourceMappingURL=chunk-H6BRJU5M.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/web/message-groups.ts","../src/web/acquisition.ts","../src/web/chat-stream-error.ts"],"sourcesContent":["/** Renderer-neutral attribution. Not a transcript merger or an execution state machine. */\nexport interface ConversationGroupItem {\n id?: string | number\n kind?: string\n role?: string\n /** A different assistant/persona must never inherit the previous speaker's label. */\n speakerId?: string\n /** Distinct threads must not be grouped if their rows share a viewport. */\n conversationId?: string\n}\nexport type GroupedConversationItem<T> = T & { isContinuation?: boolean; groupId?: string }\n\n/**\n * Annotate assistant rows until an actual user message, speaker or conversation change.\n * Tool/progress notices do not interrupt the group. The first visible assistant is\n * always labeled, including when a renderer has paged earlier history away.\n * Pass display order; stored content, IDs, timestamps and input objects are untouched.\n */\nexport function groupConversationMessages<T extends ConversationGroupItem>(items: readonly T[] = []): GroupedConversationItem<T>[] {\n let speaker: string | null = null\n let conversation: string | undefined\n let groupId: string | undefined\n return items.map((item, index) => {\n if (item.conversationId !== undefined && item.conversationId !== conversation) {\n conversation = item.conversationId\n speaker = null\n groupId = undefined\n }\n const role = item.kind === 'thinking' ? 'assistant' : (!item.kind || item.kind === 'message' ? item.role : undefined)\n if (role === 'user') { speaker = null; groupId = undefined; return { ...item, isContinuation: false } }\n if (role !== 'assistant') return item\n const current = item.speakerId ?? 'assistant'\n const isContinuation = speaker === current\n if (!isContinuation) groupId = String(item.id ?? `assistant-${index}`)\n speaker = current\n return { ...item, isContinuation, groupId }\n })\n}\n","import { readCookieValue, serializeCookie } from './core'\n\nconst RETENTION_SECONDS = 30 * 24 * 60 * 60\nconst MAX_COOKIE_BYTES = 3600\nconst CAMPAIGN_FIELDS = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const\nconst CLICK_FIELDS = ['gclid', 'gbraid', 'wbraid', 'fbclid', 'msclkid', 'ttclid', 'li_fat_id', 'twclid'] as const\nconst FIELDS = [...CAMPAIGN_FIELDS, ...CLICK_FIELDS] as const\n\n/** Untrusted acquisition hints. Never use these fields for identity or authorization. */\nexport interface FirstTouchAcquisition {\n parameters: Partial<Record<typeof FIELDS[number], string>>\n referrerOrigin: string | null\n landingPath: string\n firstSeenAt: number\n test: boolean\n}\n\nfunction bounded(value: unknown, limit = 160): string | undefined {\n if (typeof value !== 'string') return undefined\n const text = value.trim().replace(/[\\u0000-\\u001f\\u007f]/g, '').slice(0, limit)\n return text || undefined\n}\n\nfunction origin(value: string | null): string | null {\n if (!value) return null\n try {\n const url = new URL(value)\n return ['https:', 'http:'].includes(url.protocol) ? url.origin : null\n } catch { return null }\n}\n\n/** Capture only campaign fields and an external origin, never URL queries or referrer paths. */\nexport function acquisitionFromRequest(request: Request, now = Date.now(), ignoredReferrerOrigins: readonly string[] = []): FirstTouchAcquisition | null {\n const url = new URL(request.url)\n const parameters: FirstTouchAcquisition['parameters'] = {}\n for (const field of FIELDS) {\n const value = bounded(url.searchParams.get(field))\n if (value) parameters[field] = value\n }\n const referrer = origin(request.headers.get('referer'))\n const referrerOrigin = referrer === url.origin || (referrer !== null && ignoredReferrerOrigins.includes(referrer)) ? null : referrer\n if (!Object.keys(parameters).length && !referrerOrigin) return null\n return {\n parameters,\n referrerOrigin,\n landingPath: url.pathname.slice(0, 300),\n firstSeenAt: now,\n test: url.searchParams.get('attribution_test') === '1',\n }\n}\n\n/** Reject expired, future, malformed, and oversized hints without affecting authentication. */\nexport function readFirstTouchAcquisition(request: Request, cookieName: string, now = Date.now()): FirstTouchAcquisition | null {\n const raw = readCookieValue(request.headers.get('cookie'), cookieName)\n if (!raw || encodeURIComponent(raw).length > MAX_COOKIE_BYTES) return null\n try {\n const value: unknown = JSON.parse(raw)\n if (!value || typeof value !== 'object' || Array.isArray(value)) return null\n const input = value as Record<string, unknown>\n if (typeof input.firstSeenAt !== 'number' || !Number.isFinite(input.firstSeenAt)\n || input.firstSeenAt > now || input.firstSeenAt < now - RETENTION_SECONDS * 1000) return null\n if (typeof input.landingPath !== 'string' || !input.landingPath.startsWith('/')\n || input.landingPath.includes('?') || input.landingPath.includes('#')) return null\n if (!input.parameters || typeof input.parameters !== 'object' || Array.isArray(input.parameters)) return null\n const parameters: FirstTouchAcquisition['parameters'] = {}\n const source = input.parameters as Record<string, unknown>\n for (const field of FIELDS) {\n const value = bounded(source[field])\n if (value) parameters[field] = value\n }\n const referrerOrigin = typeof input.referrerOrigin === 'string' ? origin(input.referrerOrigin) : null\n if (!Object.keys(parameters).length && !referrerOrigin) return null\n return { parameters, referrerOrigin, landingPath: input.landingPath.slice(0, 300), firstSeenAt: input.firstSeenAt, test: input.test === true }\n } catch { return null }\n}\n\n/** Host-only HttpOnly cookie survives a top-level sign-in round trip. First valid touch wins. */\nexport function firstTouchAcquisitionCookie(request: Request, cookieName: string, now = Date.now(), ignoredReferrerOrigins: readonly string[] = []): string | null {\n if (readFirstTouchAcquisition(request, cookieName, now)) return null\n const acquisition = acquisitionFromRequest(request, now, ignoredReferrerOrigins)\n if (!acquisition) return null\n const raw = JSON.stringify(acquisition)\n if (encodeURIComponent(raw).length > MAX_COOKIE_BYTES) return null\n return serializeCookie(raw, {\n name: cookieName,\n httpOnly: true,\n sameSite: 'Lax',\n secure: new URL(request.url).protocol === 'https:',\n maxAgeSeconds: RETENTION_SECONDS,\n })\n}\n","/**\n * Typed chat-turn failures for a product's chat client: a non-ok HTTP response\n * from the chat submit route, or an `error` event inside the turn stream.\n * Product vocabulary (readiness-gap labels, per-code fallback messages) is\n * injected; everything else is the shared wire shape.\n */\n\n/** A chat failure the UI can render as a structured error. */\nexport interface ChatStreamError {\n message: string\n code?: string\n /** HTTP status when the failure came from a non-ok response, not a stream event. */\n status?: number\n /** Seconds to wait before retrying, parsed from a 429 Retry-After header. */\n retryAfterSeconds?: number\n /** Present on seat/billing errors so the caller can route to checkout. */\n checkoutUrl?: string\n /** SSO start route carried by a 402 `platform_link_required`. */\n connectUrl?: string\n priceUsd?: number\n includedCreditsUsd?: number\n blockingGapIds?: string[]\n recommendedActions?: string[]\n recovery?: {\n sandboxId: string\n action: string\n snapshotAvailability: string\n snapshotFreshness: string\n }\n /** Operator-facing diagnostics, rendered behind a details disclosure, never\n * inline with the human message. */\n supportDetails?: string\n /** User-facing guidance shown alongside the failure message. */\n hint?: string\n /** The turn failed mid-stream (`sandbox.stream_failed`) but the same message\n * is safe to re-send verbatim, so the caller can offer a Retry affordance. */\n retryable?: boolean\n}\n\n/** Product vocabulary for chat failures. */\nexport interface ChatStreamErrorOptions {\n /** CTA label per readiness gap id, used when `code === 'readiness.blocked'`.\n * Kept client-side so known gaps render even when the server sends no\n * `details.recommendedAction`. */\n readinessGapLabels?: Readonly<Record<string, string>>\n /** Message for an HTTP failure whose body carries a code but no message. */\n codeMessages?: Readonly<Record<string, string>>\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction stringField(source: Record<string, unknown> | undefined, key: string): string | undefined {\n const value = source?.[key]\n return typeof value === 'string' && value.trim() ? value : undefined\n}\n\nfunction numericField(source: Record<string, unknown> | undefined, key: string): number | undefined {\n const value = source?.[key]\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\nfunction stringArrayField(source: Record<string, unknown> | undefined, key: string): string[] | undefined {\n const value = source?.[key]\n if (!Array.isArray(value)) return undefined\n const strings = value.filter((item): item is string => typeof item === 'string' && item.trim().length > 0)\n return strings.length > 0 ? strings : undefined\n}\n\n/** Parse a Retry-After header in either delta-seconds or HTTP-date form. */\nexport function parseRetryAfterSeconds(value: string | null): number | undefined {\n if (!value) return undefined\n const seconds = Number(value)\n if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds)\n const timestamp = Date.parse(value)\n if (!Number.isFinite(timestamp)) return undefined\n return Math.max(0, Math.ceil((timestamp - Date.now()) / 1000))\n}\n\n/** Read status / code / Retry-After / checkout and connect routes /\n * recommended actions from a non-ok chat response body, which may nest them\n * under `error` or carry them top-level. */\nexport function buildHttpChatStreamError(\n status: number,\n retryAfterSeconds: number | undefined,\n body: unknown,\n fallbackMessage: string,\n options: ChatStreamErrorOptions = {},\n): ChatStreamError {\n const topLevel = isRecord(body) ? body : undefined\n const nested = topLevel && isRecord(topLevel.error) ? topLevel.error : undefined\n const source = nested ?? topLevel\n const code = stringField(source, 'code')\n const message = stringField(topLevel, 'error')\n ?? stringField(nested, 'message')\n ?? stringField(topLevel, 'message')\n ?? (code ? options.codeMessages?.[code] : undefined)\n ?? fallbackMessage\n const checkoutUrl = stringField(source, 'checkoutUrl')\n const connectUrl = stringField(source, 'connectUrl')\n const priceUsd = numericField(source, 'priceUsd')\n const includedCreditsUsd = numericField(source, 'includedCreditsUsd')\n const recommendedActions = stringArrayField(source, 'recommendedActions')\n const retryAction = status === 429 && retryAfterSeconds !== undefined\n ? `Try again in ${retryAfterSeconds} second${retryAfterSeconds === 1 ? '' : 's'}.`\n : undefined\n\n return {\n message,\n status,\n ...(code ? { code } : {}),\n ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),\n ...(recommendedActions || retryAction ? { recommendedActions: recommendedActions ?? [retryAction!] } : {}),\n ...(checkoutUrl ? { checkoutUrl } : {}),\n ...(connectUrl ? { connectUrl } : {}),\n ...(priceUsd !== undefined ? { priceUsd } : {}),\n ...(includedCreditsUsd !== undefined ? { includedCreditsUsd } : {}),\n }\n}\n\n/** Turn a non-ok chat submit response into a structured error. */\nexport async function parseChatHttpErrorResponse(\n res: Response,\n options: ChatStreamErrorOptions = {},\n): Promise<ChatStreamError> {\n const fallbackMessage = 'Server error'\n const retryAfterSeconds = parseRetryAfterSeconds(res.headers.get('Retry-After'))\n const text = await res.text().catch(() => fallbackMessage)\n if (!text.trim()) return buildHttpChatStreamError(res.status, retryAfterSeconds, undefined, fallbackMessage, options)\n try {\n return buildHttpChatStreamError(res.status, retryAfterSeconds, JSON.parse(text) as unknown, text, options)\n } catch {\n return buildHttpChatStreamError(res.status, retryAfterSeconds, undefined, text, options)\n }\n}\n\nfunction parseRecovery(details: Record<string, unknown>): ChatStreamError['recovery'] {\n const recovery = isRecord(details.recovery) ? details.recovery : undefined\n const snapshot = recovery && isRecord(recovery.snapshot) ? recovery.snapshot : undefined\n if (!recovery || !snapshot) return undefined\n if (typeof recovery.sandboxId !== 'string' || typeof recovery.action !== 'string') return undefined\n if (typeof snapshot.availability !== 'string' || typeof snapshot.freshness !== 'string') return undefined\n return {\n sandboxId: recovery.sandboxId,\n action: recovery.action,\n snapshotAvailability: snapshot.availability,\n snapshotFreshness: snapshot.freshness,\n }\n}\n\nfunction stringIds(value: unknown): string[] | undefined {\n return Array.isArray(value) ? value.filter((id): id is string => typeof id === 'string') : undefined\n}\n\n/** Parse the data of a stream `error` event. */\nexport function parseChatStreamError(\n data: Record<string, unknown>,\n options: ChatStreamErrorOptions = {},\n): ChatStreamError {\n const message = stringField(data, 'message') ?? stringField(data, 'error') ?? 'Unknown error'\n const code = typeof data.code === 'string' ? data.code : undefined\n const details = isRecord(data.details) ? data.details : {}\n const supportDetails = stringField(details, 'supportDetails')\n const hint = stringField(details, 'hint')\n const annotations = {\n ...(supportDetails ? { supportDetails } : {}),\n ...(hint ? { hint } : {}),\n }\n\n if (code === 'readiness.blocked') {\n const blockingGapIds = stringIds(details.blockingGapIds) ?? stringIds(data.blockingGapIds) ?? []\n const serverAction = typeof details.recommendedAction === 'string' ? details.recommendedAction : undefined\n const recommendedActions = blockingGapIds.map((id) => options.readinessGapLabels?.[id] ?? serverAction ?? message)\n return { message, code, blockingGapIds, recommendedActions, ...annotations }\n }\n\n const recommendedActions = stringArrayField(details, 'recommendedActions')\n const recovery = parseRecovery(details)\n return {\n message,\n ...(code ? { code } : {}),\n // A severed sandbox turn: the same message is safe to re-send.\n ...(code === 'sandbox.stream_failed' ? { retryable: true } : {}),\n ...(recommendedActions ? { recommendedActions } : {}),\n ...(recovery ? { recovery } : {}),\n ...annotations,\n }\n}\n\n/**\n * Normalize the error-event shapes a stream can carry: `{type:'error',\n * data:{message}}`, `{type:'error',data:{error:'...'}}` and\n * `{type:'error',error:'...'}`, so a failed turn surfaces the real failure\n * text, never 'Unknown error'.\n */\nexport function parseChatStreamErrorEvent(\n event: Record<string, unknown>,\n options: ChatStreamErrorOptions = {},\n): ChatStreamError {\n const data = isRecord(event.data) ? event.data : {}\n const source: Record<string, unknown> = isRecord(event.error) ? { ...event.error, ...data } : { ...data }\n if (!stringField(source, 'message') && typeof event.error === 'string' && event.error.trim()) {\n source.message = event.error\n }\n return parseChatStreamError(source, options)\n}\n"],"mappings":";;;;;;AAkBO,SAAS,0BAA2D,QAAsB,CAAC,GAAiC;AACjI,MAAI,UAAyB;AAC7B,MAAI;AACJ,MAAI;AACJ,SAAO,MAAM,IAAI,CAAC,MAAM,UAAU;AAChC,QAAI,KAAK,mBAAmB,UAAa,KAAK,mBAAmB,cAAc;AAC7E,qBAAe,KAAK;AACpB,gBAAU;AACV,gBAAU;AAAA,IACZ;AACA,UAAM,OAAO,KAAK,SAAS,aAAa,cAAe,CAAC,KAAK,QAAQ,KAAK,SAAS,YAAY,KAAK,OAAO;AAC3G,QAAI,SAAS,QAAQ;AAAE,gBAAU;AAAM,gBAAU;AAAW,aAAO,EAAE,GAAG,MAAM,gBAAgB,MAAM;AAAA,IAAE;AACtG,QAAI,SAAS,YAAa,QAAO;AACjC,UAAM,UAAU,KAAK,aAAa;AAClC,UAAM,iBAAiB,YAAY;AACnC,QAAI,CAAC,eAAgB,WAAU,OAAO,KAAK,MAAM,aAAa,KAAK,EAAE;AACrE,cAAU;AACV,WAAO,EAAE,GAAG,MAAM,gBAAgB,QAAQ;AAAA,EAC5C,CAAC;AACH;;;ACnCA,IAAM,oBAAoB,KAAK,KAAK,KAAK;AACzC,IAAM,mBAAmB;AACzB,IAAM,kBAAkB,CAAC,cAAc,cAAc,gBAAgB,eAAe,UAAU;AAC9F,IAAM,eAAe,CAAC,SAAS,UAAU,UAAU,UAAU,WAAW,UAAU,aAAa,QAAQ;AACvG,IAAM,SAAS,CAAC,GAAG,iBAAiB,GAAG,YAAY;AAWnD,SAAS,QAAQ,OAAgB,QAAQ,KAAyB;AAChE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,OAAO,MAAM,KAAK,EAAE,QAAQ,0BAA0B,EAAE,EAAE,MAAM,GA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AAK,UAAU,KAAK,cAAc,KAAK,CAAC;AAC/F,UAAM,eAAe,OAAO,QAAQ,sBAAsB,WAAW,QAAQ,oBAAoB;AACjG,UAAMC,sBAAqB,eAAe,IAAI,CAAC,OAAO,QAAQ,qBAAqB,EAAE,KAAK,gBAAgB,OAAO;AACjH,WAAO,EAAE,SAAS,MAAM,gBAAgB,oBAAAA,qBAAoB,GAAG,YAAY;AAAA,EAC7E;AAEA,QAAM,qBAAqB,iBAAiB,SAAS,oBAAoB;AACzE,QAAM,WAAW,cAAc,OAAO;AACtC,SAAO;AAAA,IACL;AAAA,IACA,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA;AAAA,IAEvB,GAAI,SAAS,0BAA0B,EAAE,WAAW,KAAK,IAAI,CAAC;AAAA,IAC9D,GAAI,qBAAqB,EAAE,mBAAmB,IAAI,CAAC;AAAA,IACnD,GAAI,WAAW,EAAE,SAAS,IAAI,CAAC;AAAA,IAC/B,GAAG;AAAA,EACL;AACF;AAQO,SAAS,0BACd,OACA,UAAkC,CAAC,GAClB;AACjB,QAAM,OAAO,SAAS,MAAM,IAAI,IAAI,MAAM,OAAO,CAAC;AAClD,QAAM,SAAkC,SAAS,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK;AACxG,MAAI,CAAC,YAAY,QAAQ,SAAS,KAAK,OAAO,MAAM,UAAU,YAAY,MAAM,MAAM,KAAK,GAAG;AAC5F,WAAO,UAAU,MAAM;AAAA,EACzB;AACA,SAAO,qBAAqB,QAAQ,OAAO;AAC7C;","names":["value","recommendedActions"]}
@@ -17,7 +17,7 @@ import {
17
17
  import {
18
18
  DEFAULT_TURN_LOCK_LOCATION_HINT,
19
19
  createDurableTurnLock
20
- } from "./chunk-N5RWYR5N.js";
20
+ } from "./chunk-ZTGITMYQ.js";
21
21
  import {
22
22
  createD1TurnEventStore
23
23
  } from "./chunk-3Q3UEWKK.js";
@@ -50,7 +50,7 @@ import {
50
50
  shellSingleQuote,
51
51
  splitDeferredProfileFiles,
52
52
  writeProfileFilesToBox
53
- } from "./chunk-CTREXL3O.js";
53
+ } from "./chunk-67CSI5PU.js";
54
54
  import {
55
55
  DEFAULT_HARNESS,
56
56
  assertHarnessModelCompatible,
@@ -4310,4 +4310,4 @@ export {
4310
4310
  SandboxFilesystemNotReadyError,
4311
4311
  runForegroundSandboxSingleFlight
4312
4312
  };
4313
- //# sourceMappingURL=chunk-XTQLZG6M.js.map
4313
+ //# sourceMappingURL=chunk-HHIEHETJ.js.map
@@ -27,7 +27,7 @@ import {
27
27
  sandboxRunFailureDetail,
28
28
  streamSandboxPrompt,
29
29
  turnStorageBindings
30
- } from "./chunk-XTQLZG6M.js";
30
+ } from "./chunk-HHIEHETJ.js";
31
31
  import {
32
32
  redactErrorMessage
33
33
  } from "./chunk-MH74DY2I.js";
@@ -122,7 +122,7 @@ import {
122
122
  import {
123
123
  readSandboxBinaryBytes,
124
124
  statSandboxFileSize
125
- } from "./chunk-CTREXL3O.js";
125
+ } from "./chunk-INW4FSID.js";
126
126
  import {
127
127
  parsePlanSubmittedEvent,
128
128
  planToPersistedPart
@@ -2230,6 +2230,13 @@ function createNativeTimingTransfer(read, onError) {
2230
2230
 
2231
2231
  // src/chat-routes/turn-ownership.ts
2232
2232
  function createChatTurnOwnership(state, log, turnStreamId, options) {
2233
+ const attempt = async (step, run) => {
2234
+ try {
2235
+ await run();
2236
+ } catch (err) {
2237
+ log(`[chat-routes] ${step} failed`, { turnId: turnStreamId, error: err instanceof Error ? err.message : String(err) });
2238
+ }
2239
+ };
2233
2240
  const handoffCompletion = (handoff) => {
2234
2241
  if (!state.completionHandoffPromise) {
2235
2242
  state.completionHandoffPromise = (async () => {
@@ -2241,14 +2248,7 @@ function createChatTurnOwnership(state, log, turnStreamId, options) {
2241
2248
  registrationFailed = true;
2242
2249
  throw error;
2243
2250
  } finally {
2244
- try {
2245
- await state.tap?.detach();
2246
- } catch (err) {
2247
- log("[chat-routes] turn buffer detach failed", {
2248
- turnId: turnStreamId,
2249
- error: err instanceof Error ? err.message : String(err)
2250
- });
2251
- }
2251
+ await attempt("turn buffer detach", () => state.tap?.detach());
2252
2252
  try {
2253
2253
  await state.draft?.close();
2254
2254
  } catch (err) {
@@ -2268,26 +2268,13 @@ function createChatTurnOwnership(state, log, turnStreamId, options) {
2268
2268
  const releaseLock = async () => {
2269
2269
  if (state.completionHandoff || !state.lockAcquired || state.lockReleased) return;
2270
2270
  if (state.producer?.terminalObserved && !state.producer.terminalObserved()) {
2271
+ await attempt("turnLock.park", () => options.turnLock?.park?.(state.lockHandle));
2271
2272
  await state.closeCancellation?.();
2272
2273
  return;
2273
2274
  }
2274
2275
  state.lockReleased = true;
2275
- try {
2276
- await state.closeCancellation?.();
2277
- } catch (err) {
2278
- log("[chat-routes] turn cancellation close failed", {
2279
- turnId: turnStreamId,
2280
- error: err instanceof Error ? err.message : String(err)
2281
- });
2282
- }
2283
- try {
2284
- await options.turnLock.release(state.lockHandle);
2285
- } catch (err) {
2286
- log("[chat-routes] turnLock.release failed", {
2287
- turnId: turnStreamId,
2288
- error: err instanceof Error ? err.message : String(err)
2289
- });
2290
- }
2276
+ await attempt("turn cancellation close", () => state.closeCancellation?.());
2277
+ await attempt("turnLock.release", () => options.turnLock.release(state.lockHandle));
2291
2278
  };
2292
2279
  return { handoffCompletion, releaseLock };
2293
2280
  }
@@ -3949,4 +3936,4 @@ export {
3949
3936
  createChatTurnRoutes,
3950
3937
  streamChatRouteAsSandboxEvents
3951
3938
  };
3952
- //# sourceMappingURL=chunk-RZMQ2J5P.js.map
3939
+ //# sourceMappingURL=chunk-IMFJMFHK.js.map