@tangle-network/agent-app 0.63.44 → 0.63.45

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 (51) 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 +9 -7
  6. package/dist/chat-routes/index.js.map +1 -1
  7. package/dist/{chunk-ZGGEYYEQ.js → chunk-4E2MUVGL.js} +3 -3
  8. package/dist/chunk-5VE4IDSU.js +75 -0
  9. package/dist/chunk-5VE4IDSU.js.map +1 -0
  10. package/dist/{chunk-CTREXL3O.js → chunk-67CSI5PU.js} +2 -65
  11. package/dist/chunk-67CSI5PU.js.map +1 -0
  12. package/dist/{chunk-DPTNKH22.js → chunk-H6BRJU5M.js} +1 -73
  13. package/dist/chunk-H6BRJU5M.js.map +1 -0
  14. package/dist/chunk-INW4FSID.js +66 -0
  15. package/dist/chunk-INW4FSID.js.map +1 -0
  16. package/dist/{chunk-RZMQ2J5P.js → chunk-L63GYPYY.js} +3 -3
  17. package/dist/{chunk-XTQLZG6M.js → chunk-YQUZQHAD.js} +2 -2
  18. package/dist/design-canvas/index.js +2 -1
  19. package/dist/design-canvas/index.js.map +1 -1
  20. package/dist/design-canvas-react/engine.js +2 -1
  21. package/dist/design-canvas-react/index.js +3 -2
  22. package/dist/design-canvas-react/index.js.map +1 -1
  23. package/dist/design-canvas-react/lazy.js +1 -1
  24. package/dist/platform/index.js +2 -1
  25. package/dist/platform/index.js.map +1 -1
  26. package/dist/public-consultation/index.js +6 -4
  27. package/dist/public-consultation/index.js.map +1 -1
  28. package/dist/sandbox/index.js +7 -5
  29. package/dist/sequences/index.js +2 -1
  30. package/dist/sequences/index.js.map +1 -1
  31. package/dist/skills-placement/box.js +4 -2
  32. package/dist/skills-placement/box.js.map +1 -1
  33. package/dist/vault/store/box-state.d.ts +125 -0
  34. package/dist/vault/store/coordinator.d.ts +9 -1
  35. package/dist/vault/store/index.d.ts +4 -0
  36. package/dist/vault/store/index.js +1227 -4
  37. package/dist/vault/store/index.js.map +1 -1
  38. package/dist/vault/store/sandbox-engine.d.ts +19 -0
  39. package/dist/vault/store/sandbox-hydrate.d.ts +59 -0
  40. package/dist/vault/store/sandbox-reconcile.d.ts +55 -0
  41. package/dist/vault/store/sandbox-sync.d.ts +37 -1
  42. package/dist/vault/store/store.d.ts +10 -1
  43. package/dist/web/index.js +7 -5
  44. package/package.json +1 -1
  45. package/dist/chunk-CTREXL3O.js.map +0 -1
  46. package/dist/chunk-DPTNKH22.js.map +0 -1
  47. /package/dist/{DesignCanvas-VKZ7Y3JU.js.map → DesignCanvas-Q65UV4D5.js.map} +0 -0
  48. /package/dist/{DesignCanvasEditor-3V53YLLZ.js.map → DesignCanvasEditor-THEFESEX.js.map} +0 -0
  49. /package/dist/{chunk-ZGGEYYEQ.js.map → chunk-4E2MUVGL.js.map} +0 -0
  50. /package/dist/{chunk-RZMQ2J5P.js.map → chunk-L63GYPYY.js.map} +0 -0
  51. /package/dist/{chunk-XTQLZG6M.js.map → chunk-YQUZQHAD.js.map} +0 -0
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The box↔Vault sync engine a product binds once: hydrate the workspace Vault
3
+ * into a box, reconcile what the box changed back into the Vault, and detect a
4
+ * box that lost its Vault directory. Products supply their Vault store and the
5
+ * box directory; the engine owns the baseline, the manifest diff, conflict
6
+ * parking, rename-only deletes and the request-size limits.
7
+ */
8
+ import { type VaultHydrationBox, type VaultHydrationOptions } from './sandbox-hydrate';
9
+ import { assertSandboxVaultReconciliation, type SandboxVaultSyncOptions, type VaultReconcileBox } from './sandbox-reconcile';
10
+ import type { SandboxVaultSyncConfig } from './sandbox-sync';
11
+ /** Bind the sync engine to a product's Vault store and box directory. */
12
+ export declare function createSandboxVaultSync(config: SandboxVaultSyncConfig): {
13
+ root: string;
14
+ hydrate: (box: VaultHydrationBox, workspaceId: string, options?: VaultHydrationOptions) => Promise<import("../../sandbox").Outcome<import("./sandbox-hydrate").VaultHydrationStats>>;
15
+ reconcile: (box: VaultReconcileBox, workspaceId: string, options?: SandboxVaultSyncOptions) => Promise<import("./sandbox-reconcile").SandboxVaultSyncResult>;
16
+ probeLoss: (box: VaultReconcileBox, workspaceId: string) => Promise<string[]>;
17
+ assertReconciliation: typeof assertSandboxVaultReconciliation;
18
+ };
19
+ export type SandboxVaultSync = ReturnType<typeof createSandboxVaultSync>;
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Hydration: copy the workspace Vault into the box's Vault directory and record
3
+ * what the box now holds as a baseline bound to the box's filesystem
4
+ * incarnation. The head listing is paged; every page commits its baseline, so
5
+ * an interrupted pass leaves durable progress and the next call resumes from
6
+ * the recorded cursor.
7
+ */
8
+ import type { Outcome } from '../../sandbox/outcome';
9
+ import { type SandboxVaultSyncConfig } from './sandbox-sync';
10
+ export interface VaultHydrationFileSystem {
11
+ exists(path: string): Promise<boolean>;
12
+ writeMany(files: Array<{
13
+ path: string;
14
+ content: string;
15
+ }>): Promise<void>;
16
+ delete(path: string, options?: {
17
+ recursive?: boolean;
18
+ }): Promise<void>;
19
+ mkdir(path: string, options?: {
20
+ recursive?: boolean;
21
+ }): Promise<void>;
22
+ uploadData(path: string, data: Uint8Array): Promise<{
23
+ size?: number;
24
+ sha256?: string;
25
+ } | unknown>;
26
+ }
27
+ /** The box calls hydration makes; a `@tangle-network/sandbox` instance satisfies it. */
28
+ export interface VaultHydrationBox {
29
+ id: string;
30
+ filesystemIncarnationId?: unknown;
31
+ filesystemIncarnationProvenance?: unknown;
32
+ filesystemIncarnationReadiness?: unknown;
33
+ fs: VaultHydrationFileSystem;
34
+ exec(command: string, options?: {
35
+ sessionId?: string;
36
+ }): Promise<{
37
+ exitCode: number;
38
+ stdout: string;
39
+ stderr: string;
40
+ }>;
41
+ }
42
+ export interface VaultHydrationStats {
43
+ written: number;
44
+ deleted: number;
45
+ unchanged: number;
46
+ processedHeads: number;
47
+ /** True when the coordinator's record proved the box current and nothing was listed or written. */
48
+ inSync?: boolean;
49
+ }
50
+ export interface VaultHydrationOptions {
51
+ /** Paths a reconciliation parked as conflicts; hydration leaves both copies alone. */
52
+ conflictPaths?: ReadonlySet<string>;
53
+ /** Paths the reconciliation just committed from the box; already current on the box. */
54
+ appliedPaths?: ReadonlySet<string>;
55
+ /** May still be in flight (the Vault-loss probe): hydrate awaits it only to compare heads. */
56
+ pathsMissingFromBox?: ReadonlySet<string> | Promise<ReadonlySet<string>>;
57
+ }
58
+ /** Hydrate every live Vault head into the box, page by page, until the listing ends. */
59
+ export declare function hydrateSandboxVault(config: SandboxVaultSyncConfig, box: VaultHydrationBox, workspaceId: string, options?: VaultHydrationOptions): Promise<Outcome<VaultHydrationStats>>;
@@ -0,0 +1,55 @@
1
+ import { type SandboxExecChannel } from '../../sandbox/binary-read';
2
+ import type { VaultMutationConflict } from './revisions';
3
+ import { type SandboxVaultPathRejection, type SandboxVaultSyncChange, type SandboxVaultSyncConfig, type SandboxVaultSyncProgress } from './sandbox-sync';
4
+ /** The box calls reconciliation makes; a `@tangle-network/sandbox` instance satisfies it. */
5
+ export interface VaultReconcileBox extends SandboxExecChannel {
6
+ id: string;
7
+ filesystemIncarnationId?: unknown;
8
+ filesystemIncarnationProvenance?: unknown;
9
+ filesystemIncarnationReadiness?: unknown;
10
+ read(path: string, options?: {
11
+ sessionId?: string;
12
+ }): Promise<string>;
13
+ }
14
+ export interface SandboxVaultSyncResult {
15
+ succeeded: boolean;
16
+ complete: boolean;
17
+ rejectedPaths: SandboxVaultPathRejection[];
18
+ binaryDriftPaths: string[];
19
+ refusedDeletionPaths: string[];
20
+ pathsMissingFromBox: string[];
21
+ operationId: string | null;
22
+ changes: SandboxVaultSyncChange[];
23
+ appliedPaths: string[];
24
+ conflicts: VaultMutationConflict[];
25
+ progress: SandboxVaultSyncProgress;
26
+ blockedReason?: 'filesystem_incarnation_missing' | 'filesystem_incarnation_not_ready' | 'vault_directory_missing' | 'sandbox_deletion_denied';
27
+ baselineResetReason?: 'baseline_missing' | 'filesystem_incarnation_changed';
28
+ }
29
+ /**
30
+ * Fail the caller when reconciliation could not establish what the box holds,
31
+ * and report a divergence it deliberately parked.
32
+ *
33
+ * A conflict is a steady state, not a failure: the box edit and the KV head
34
+ * both survive, and the next hydration skips the path so neither overwrites the
35
+ * other. It must not throw — the divergence persists until a human resolves it,
36
+ * so throwing would fail every later turn on the workspace for as long as the
37
+ * conflict stands. The log is the surfacing channel; `conflicts` on the result
38
+ * is the structured one.
39
+ */
40
+ export declare function assertSandboxVaultReconciliation(workspaceId: string, reconciliation: SandboxVaultSyncResult): void;
41
+ export interface SandboxVaultSyncOptions {
42
+ sessionId?: string;
43
+ operationId?: string;
44
+ onStaged?: (checkpoint: {
45
+ operationId: string;
46
+ changes: SandboxVaultSyncChange[];
47
+ }) => Promise<void>;
48
+ }
49
+ export declare function reconcileSandboxVault(config: SandboxVaultSyncConfig, box: VaultReconcileBox, workspaceId: string, options?: SandboxVaultSyncOptions): Promise<SandboxVaultSyncResult>;
50
+ /**
51
+ * The live baseline paths when the box's Vault directory holds no file at all:
52
+ * a box that lost its disk would otherwise read as a member deleting every
53
+ * file. Empty when the box still has files or the baseline is not this box's.
54
+ */
55
+ export declare function probeSandboxVaultLoss(config: SandboxVaultSyncConfig, box: VaultReconcileBox, workspaceId: string): Promise<string[]>;
@@ -1,4 +1,40 @@
1
- import type { VaultSandboxBaseline } from './revisions';
1
+ import type { VaultHeadState, VaultMutationRequest, VaultMutationResult, VaultSandboxBaseline } from './revisions';
2
+ import type { VaultFrontmatterCodec, VaultHeadListOptions, VaultHeadListPage } from './store';
3
+ import type { VaultBoxStateView, VaultBoxSyncRecord } from './box-state';
4
+ /** The store calls the sync engine makes; `createVaultStore` returns all of them. */
5
+ export interface SandboxVaultSyncStore {
6
+ codec: VaultFrontmatterCodec;
7
+ listVaultHeadPage(workspaceId: string, options?: VaultHeadListOptions): Promise<VaultHeadListPage>;
8
+ readVaultFileState(workspaceId: string, filePath: string): Promise<VaultHeadState>;
9
+ commitVaultMutation(request: VaultMutationRequest): Promise<VaultMutationResult>;
10
+ readVaultSandboxBaseline(workspaceId: string, sandboxId: string): Promise<VaultSandboxBaseline | null>;
11
+ writeVaultSandboxBaseline(baseline: VaultSandboxBaseline): Promise<void>;
12
+ readVaultBoxState(workspaceId: string): Promise<VaultBoxStateView | null>;
13
+ recordVaultBoxSync(workspaceId: string, record: VaultBoxSyncRecord): Promise<void>;
14
+ invalidateVaultBoxSync(workspaceId: string): Promise<void>;
15
+ }
16
+ export interface SandboxVaultSyncConfig {
17
+ /** The product's Vault store, bound for this request. */
18
+ vault: SandboxVaultSyncStore;
19
+ /** Absolute box directory that holds the workspace's Vault files, such as `/home/agent/vault`. */
20
+ root: string;
21
+ /** Extension to MIME type overrides for binary files the box produces (agent-app's `sniffMime` defaults otherwise). */
22
+ fileTypes?: Readonly<Record<string, string>>;
23
+ /**
24
+ * Names what hydration writes. A recorded sync is trusted only under the same
25
+ * contract, so a release that changes what lands on the box bumps it and every
26
+ * box re-hydrates on its next turn. Defaults to `SANDBOX_VAULT_SYNC_CONTRACT`.
27
+ */
28
+ contract?: string;
29
+ }
30
+ /** The engine's own hydration contract; a product appends its own when its box layout changes. */
31
+ export declare const SANDBOX_VAULT_SYNC_CONTRACT = "agent-app-sandbox-vault-sync-v1";
32
+ /** The body prefix of a Vault document whose remainder is base64-encoded binary bytes. */
33
+ export declare const VAULT_BASE64_BODY_MARKER = "[base64]\n";
34
+ /** The base64 payload of a Vault document that stores a binary file, or null for a text document. */
35
+ export declare function vaultBinaryPayload(codec: VaultFrontmatterCodec, raw: string): string | null;
36
+ /** The Vault document that stores a binary file the box produced: the product's frontmatter plus the base64 body. */
37
+ export declare function vaultBinaryDocument(codec: VaultFrontmatterCodec, fields: Record<string, unknown>, base64: string): string;
2
38
  export declare const VAULT_SANDBOX_BASELINE_SCHEMA: 'vault-sandbox-baseline-v3';
3
39
  export interface NormalizedVaultSandboxBaseline {
4
40
  baseline: VaultSandboxBaseline | null;
@@ -1,7 +1,8 @@
1
1
  import type { KVStore } from '../../store';
2
2
  import { VaultPathError } from './paths';
3
- import { type VaultHeadState, type VaultMutationPolicy, type VaultMutationRequest, type VaultMutationResult, type VaultRevisionMetadata, type VaultWriter } from './revisions';
3
+ import { type VaultHeadState, type VaultMutationPolicy, type VaultMutationRequest, type VaultMutationResult, type VaultRevisionMetadata, type VaultSandboxBaseline, type VaultWriter } from './revisions';
4
4
  import { type VaultNode } from './tree';
5
+ import { type SandboxBootstrapConfirmation, type VaultBoxStateView, type VaultBoxSyncRecord } from './box-state';
5
6
  /** The Durable Object namespace surface the store calls; Cloudflare's binding satisfies it. */
6
7
  export interface VaultCoordinatorNamespace {
7
8
  idFromName(name: string): unknown;
@@ -128,6 +129,14 @@ export declare function createVaultStore<Namespace extends VaultCoordinatorNames
128
129
  enqueueLocalVaultMutation: <T>(workspaceId: string, run: () => Promise<T>) => Promise<T>;
129
130
  commitVaultMutation: (request: VaultMutationRequest) => Promise<VaultMutationResult>;
130
131
  readVaultFileState: (workspaceId: string, filePath: string) => Promise<VaultHeadState>;
132
+ readVaultSandboxBaseline: (workspaceId: string, sandboxId: string) => Promise<VaultSandboxBaseline | null>;
133
+ writeVaultSandboxBaseline: (baseline: VaultSandboxBaseline) => Promise<void>;
134
+ readVaultBoxState: (workspaceId: string) => Promise<VaultBoxStateView | null>;
135
+ recordVaultBoxSync: (workspaceId: string, record: VaultBoxSyncRecord) => Promise<void>;
136
+ invalidateVaultBoxSync: (workspaceId: string) => Promise<void>;
137
+ recordSandboxBootstrap: (workspaceId: string, confirmation: SandboxBootstrapConfirmation) => Promise<void>;
138
+ /** The product's frontmatter codec, for engines that read and write whole Vault documents. */
139
+ codec: VaultFrontmatterCodec;
131
140
  getVaultRoot: (workspaceId: string) => string;
132
141
  writeVaultFile: (workspaceId: string, filePath: string, content: {
133
142
  frontmatter: Record<string, unknown>;
package/dist/web/index.js CHANGED
@@ -3,15 +3,12 @@ import {
3
3
  buildHttpChatStreamError,
4
4
  firstTouchAcquisitionCookie,
5
5
  groupConversationMessages,
6
- isEditableMime,
7
6
  parseChatHttpErrorResponse,
8
7
  parseChatStreamError,
9
8
  parseChatStreamErrorEvent,
10
9
  parseRetryAfterSeconds,
11
- readFirstTouchAcquisition,
12
- sniffMime,
13
- sniffMimeFromName
14
- } from "../chunk-DPTNKH22.js";
10
+ readFirstTouchAcquisition
11
+ } from "../chunk-H6BRJU5M.js";
15
12
  import {
16
13
  createApiKeyFetch
17
14
  } from "../chunk-RN4WPTBH.js";
@@ -34,6 +31,11 @@ import {
34
31
  serializeCookie,
35
32
  withFreeRouteLimit
36
33
  } from "../chunk-ALIWB2P3.js";
34
+ import {
35
+ isEditableMime,
36
+ sniffMime,
37
+ sniffMimeFromName
38
+ } from "../chunk-5VE4IDSU.js";
37
39
  import {
38
40
  isBlockedFetchHostname,
39
41
  withTimeout
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.63.44",
3
+ "version": "0.63.45",
4
4
  "packageManager": "pnpm@11.24.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sandbox/exec-failure.ts","../src/sandbox/outcome.ts","../src/sandbox/profile-files.ts","../src/sandbox/shell-path.ts","../src/sandbox/binary-read.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","/**\n * Reading arbitrary bytes out of a sandbox over an exec channel that only\n * speaks text.\n *\n * `box.exec` returns stdout as a string, so a binary file has to be encoded to\n * survive the trip: `wc -c` gives the on-disk length, `base64` gives the\n * payload, and the decoded byte count is checked against the stat. That last\n * check is the point of the module — an exec channel that caps or clips its\n * output still reports `exitCode: 0` with a short buffer, which decodes into a\n * perfectly valid but TRUNCATED file. Verifying the length turns that silent\n * corruption into a loud failure at the boundary.\n *\n * Both helpers return typed outcomes; callers must inspect `succeeded` before\n * touching `value`.\n */\n\n/** The `box.exec` surface these helpers use — structural, so a caller can pass\n * the sandbox SDK's `SandboxInstance` directly or a narrower test double. */\nexport interface SandboxExecChannel {\n exec(\n command: string,\n options?: { sessionId?: string },\n ): Promise<{ stdout: string; stderr: string; exitCode: number }>\n}\n\n/** Define options to execute code within a sandbox environment with optional session control */\nexport interface SandboxExecOptions {\n /** Run inside a named session rather than the box's default one. */\n sessionId?: string\n}\n\n/** Resolve the outcome of a sandbox file size check with success status and value or error message */\nexport type SandboxFileSizeOutcome =\n | { succeeded: true; value: number }\n | { succeeded: false; error: string }\n\n/** Represent the outcome of reading sandbox file bytes with success status and corresponding data or error */\nexport type SandboxFileBytesOutcome =\n | { succeeded: true; value: { bytes: Uint8Array; size: number } }\n | { succeeded: false; error: string }\n\n/** Wraps a value in single quotes for `sh`, closing and reopening the quote\n * around each embedded quote (`'` → `'\"'\"'`). Every path these helpers\n * interpolate into a command goes through this — in-box filenames are\n * arbitrary, so spaces, quotes and `$` are ordinary content, not syntax. */\nexport function shellQuote(value: string): string {\n return `'${value.replaceAll(\"'\", `'\"'\"'`)}'`\n}\n\n/** Decodes with `atob` rather than `Buffer.from(s, 'base64')`: Buffer SKIPS\n * characters outside the alphabet, so a corrupted payload would decode to\n * something plausible instead of throwing. */\nfunction base64ToBytes(base64: string): Uint8Array {\n const binary = atob(base64)\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i)\n return bytes\n}\n\nfunction execInSandbox(box: SandboxExecChannel, command: string, options?: SandboxExecOptions) {\n return options?.sessionId ? box.exec(command, { sessionId: options.sessionId }) : box.exec(command)\n}\n\n/** Stats a sandbox file's byte length via `wc -c`. A caller enforcing a size\n * cap must check this BEFORE {@link readSandboxBinaryBytes}, so an oversize\n * file is rejected without paying for a base64 round trip of it. */\nexport async function statSandboxFileSize(\n box: SandboxExecChannel,\n absolutePath: string,\n options?: SandboxExecOptions,\n): Promise<SandboxFileSizeOutcome> {\n const quotedPath = shellQuote(absolutePath)\n let result\n try {\n result = await execInSandbox(box, `wc -c < ${quotedPath}`, options)\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n if (result.exitCode !== 0) {\n return { succeeded: false, error: result.stderr || 'unknown error' }\n }\n const size = Number.parseInt(result.stdout.trim(), 10)\n if (!Number.isFinite(size)) {\n return { succeeded: false, error: `could not parse file size from \"${result.stdout.trim()}\"` }\n }\n return { succeeded: true, value: size }\n}\n\n/** Reads a sandbox file as base64 and decodes it, verifying the decoded byte\n * length against `expectedSize` (from a prior {@link statSandboxFileSize}). A\n * mismatch is reported, never returned as a short buffer. */\nexport async function readSandboxBinaryBytes(\n box: SandboxExecChannel,\n absolutePath: string,\n expectedSize: number,\n options?: SandboxExecOptions,\n): Promise<SandboxFileBytesOutcome> {\n const quotedPath = shellQuote(absolutePath)\n let result\n try {\n result = await execInSandbox(box, `base64 ${quotedPath}`, options)\n } catch (err) {\n return { succeeded: false, error: err instanceof Error ? err.message : String(err) }\n }\n if (result.exitCode !== 0) {\n return { succeeded: false, error: result.stderr || 'unknown error' }\n }\n // GNU coreutils wraps base64 output at 76 columns; BusyBox may not wrap at\n // all. Stripping all whitespace makes both shapes decode identically.\n const cleaned = result.stdout.replace(/\\s+/g, '')\n let bytes: Uint8Array\n try {\n bytes = base64ToBytes(cleaned)\n } catch (err) {\n return {\n succeeded: false,\n error: `could not decode file contents: ${err instanceof Error ? err.message : String(err)}`,\n }\n }\n if (bytes.byteLength !== expectedSize) {\n return {\n succeeded: false,\n error: `read returned ${bytes.byteLength} bytes, expected ${expectedSize} — output truncated in transit`,\n }\n }\n return { succeeded: true, value: { bytes, size: expectedSize } }\n}\n"],"mappings":";AAKO,IAAM,+BAAN,cAA2C,MAAM;AAAA,EACtD,YAAY,WAAmB;AAC7B,UAAM,iBAAiB,SAAS,uBAAuB;AACvD,SAAK,OAAO;AAAA,EACd;AACF;AAEA,IA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AAO,GAAG,EAAE;AAAA,EACrF;AACA,MAAI,OAAO,aAAa,GAAG;AACzB,WAAO,EAAE,WAAW,OAAO,OAAO,OAAO,UAAU,gBAAgB;AAAA,EACrE;AAGA,QAAM,UAAU,OAAO,OAAO,QAAQ,QAAQ,EAAE;AAChD,MAAI;AACJ,MAAI;AACF,YAAQ,cAAc,OAAO;AAAA,EAC/B,SAAS,KAAK;AACZ,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO,mCAAmC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC;AAAA,IAC5F;AAAA,EACF;AACA,MAAI,MAAM,eAAe,cAAc;AACrC,WAAO;AAAA,MACL,WAAW;AAAA,MACX,OAAO,iBAAiB,MAAM,UAAU,oBAAoB,YAAY;AAAA,IAC1E;AAAA,EACF;AACA,SAAO,EAAE,WAAW,MAAM,OAAO,EAAE,OAAO,MAAM,aAAa,EAAE;AACjE;","names":["retryAfterMs","res"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/web/message-groups.ts","../src/web/acquisition.ts","../src/web/mime.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 * 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","/**\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,GAAG,KAAK;AAC9E,SAAO,QAAQ;AACjB;AAEA,SAAS,OAAO,OAAqC;AACnD,MAAI,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