zidane 6.5.1 → 6.5.3

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 (110) hide show
  1. package/dist/{acp-o-LQAjFw.js → acp-CIpD8UIw.js} +4 -4
  2. package/dist/{acp-o-LQAjFw.js.map → acp-CIpD8UIw.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.d.ts.map +1 -1
  6. package/dist/acp.js +1 -1
  7. package/dist/{agent-BVNkC1h4.js → agent-8kfGIDb_.js} +755 -586
  8. package/dist/agent-8kfGIDb_.js.map +1 -0
  9. package/dist/agent.d.ts +1 -1
  10. package/dist/agent.js +1 -1
  11. package/dist/{anthropic-Dov2mC5e.js → anthropic-_Hn1YiWr.js} +2 -2
  12. package/dist/{anthropic-Dov2mC5e.js.map → anthropic-_Hn1YiWr.js.map} +1 -1
  13. package/dist/{auth-B8ZuBcKC.js → auth-CS_e8ng1.js} +6 -5
  14. package/dist/{auth-B8ZuBcKC.js.map → auth-CS_e8ng1.js.map} +1 -1
  15. package/dist/chat/pure.d.ts +4 -4
  16. package/dist/chat/pure.js +3 -3
  17. package/dist/chat.d.ts +124 -10
  18. package/dist/chat.d.ts.map +1 -1
  19. package/dist/chat.js +6 -6
  20. package/dist/{context-breakdown-BLF10tOO.js → context-segments-1mcqSCM3.js} +110 -2
  21. package/dist/context-segments-1mcqSCM3.js.map +1 -0
  22. package/dist/{context-transport-D-daWOmp.js → context-transport-Bco9Wo0b.js} +3 -3
  23. package/dist/{context-transport-D-daWOmp.js.map → context-transport-Bco9Wo0b.js.map} +1 -1
  24. package/dist/contexts/daytona.d.ts +1 -1
  25. package/dist/contexts/daytona.d.ts.map +1 -1
  26. package/dist/contexts/daytona.js +5 -2
  27. package/dist/contexts/daytona.js.map +1 -1
  28. package/dist/contexts/e2b.d.ts +1 -1
  29. package/dist/eval.d.ts +1 -1
  30. package/dist/extensions.d.ts +1 -1
  31. package/dist/extensions.js +1 -1
  32. package/dist/headless.d.ts +1 -1
  33. package/dist/headless.js +1 -1
  34. package/dist/{index-CWBSrqI6.d.ts → index-BKyWhILQ.d.ts} +179 -7
  35. package/dist/index-BKyWhILQ.d.ts.map +1 -0
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +7 -7
  38. package/dist/{login-CR3fDHXh.js → login-D3CKhgbI.js} +2 -2
  39. package/dist/{login-CR3fDHXh.js.map → login-D3CKhgbI.js.map} +1 -1
  40. package/dist/{mcp-C6IkXNOS.js → mcp-D9fqOQo5.js} +3 -3
  41. package/dist/{mcp-C6IkXNOS.js.map → mcp-D9fqOQo5.js.map} +1 -1
  42. package/dist/mcp.d.ts +1 -1
  43. package/dist/mcp.js +1 -1
  44. package/dist/{oauth-bkEOybqm.js → oauth-BYjlFR-J.js} +49 -10
  45. package/dist/oauth-BYjlFR-J.js.map +1 -0
  46. package/dist/output/stream-json.d.ts +1 -1
  47. package/dist/output/terminal.d.ts +1 -1
  48. package/dist/plugins.d.ts +1 -1
  49. package/dist/presets.d.ts +1 -1
  50. package/dist/presets.js +1 -1
  51. package/dist/providers/anthropic.d.ts +1 -1
  52. package/dist/providers/anthropic.js +1 -1
  53. package/dist/providers/arcee.d.ts +1 -1
  54. package/dist/providers/baseten.d.ts +1 -1
  55. package/dist/providers/cerebras.d.ts +1 -1
  56. package/dist/providers/local.d.ts +1 -1
  57. package/dist/providers/openai-compat.d.ts +1 -1
  58. package/dist/providers/openai.d.ts +1 -1
  59. package/dist/providers/openai.js +1 -1
  60. package/dist/providers/openrouter.d.ts +1 -1
  61. package/dist/providers/xai.d.ts +1 -1
  62. package/dist/providers/xai.js +68 -1
  63. package/dist/providers/xai.js.map +1 -0
  64. package/dist/{providers-B6mFe7OD.js → providers-VypZh7rD.js} +3 -3
  65. package/dist/{providers-B6mFe7OD.js.map → providers-VypZh7rD.js.map} +1 -1
  66. package/dist/providers.d.ts +2 -2
  67. package/dist/providers.js +4 -4
  68. package/dist/restate.d.ts +1 -1
  69. package/dist/restate.js +1 -1
  70. package/dist/rolldown-runtime-BhDjJH2R.js +15 -0
  71. package/dist/session/sqlite.d.ts +1 -1
  72. package/dist/session.d.ts +1 -1
  73. package/dist/skills.d.ts +1 -1
  74. package/dist/{stdio-DzUUkkhS.js → stdio-DPpBDPx5.js} +13 -4
  75. package/dist/{stdio-DzUUkkhS.js.map → stdio-DPpBDPx5.js.map} +1 -1
  76. package/dist/{stdio-loader-BILyUGmi.js → stdio-loader-CI4sPFve.js} +11 -6
  77. package/dist/stdio-loader-CI4sPFve.js.map +1 -0
  78. package/dist/{tool-formatters-gFqQbzPY.d.ts → tool-formatters-DMr62Hpy.d.ts} +3 -3
  79. package/dist/{tool-formatters-gFqQbzPY.d.ts.map → tool-formatters-DMr62Hpy.d.ts.map} +1 -1
  80. package/dist/tools/fetch-url.d.ts +1 -1
  81. package/dist/tools/web-search.d.ts +1 -1
  82. package/dist/tools.d.ts +1 -1
  83. package/dist/tools.js +1 -1
  84. package/dist/{transcript-anchors-qCs3wZpu.d.ts → transcript-anchors-BHihk9nf.d.ts} +2 -2
  85. package/dist/{transcript-anchors-qCs3wZpu.d.ts.map → transcript-anchors-BHihk9nf.d.ts.map} +1 -1
  86. package/dist/{transcript-anchors-DEIr0tJC.js → transcript-anchors-uU_KZLsp.js} +161 -36
  87. package/dist/transcript-anchors-uU_KZLsp.js.map +1 -0
  88. package/dist/tui.d.ts +74 -3
  89. package/dist/tui.d.ts.map +1 -1
  90. package/dist/tui.js +823 -81
  91. package/dist/tui.js.map +1 -1
  92. package/dist/{turn-operations-M9-jUyDd.d.ts → turn-operations-BgqVUjtl.d.ts} +3 -3
  93. package/dist/{turn-operations-M9-jUyDd.d.ts.map → turn-operations-BgqVUjtl.d.ts.map} +1 -1
  94. package/dist/{turn-operations-C3IijXMW.js → turn-operations-iGu5J08j.js} +2 -2
  95. package/dist/{turn-operations-C3IijXMW.js.map → turn-operations-iGu5J08j.js.map} +1 -1
  96. package/dist/types.d.ts +1 -1
  97. package/dist/{xai-Du6Wfnlb.js → xai-CfmI5Y5k.js} +10 -67
  98. package/dist/xai-CfmI5Y5k.js.map +1 -0
  99. package/docs/CHAT.md +42 -1
  100. package/docs/INTERACTIONS.md +39 -0
  101. package/docs/RESTATE.md +7 -0
  102. package/docs/TUI.md +28 -2
  103. package/package.json +18 -17
  104. package/dist/agent-BVNkC1h4.js.map +0 -1
  105. package/dist/context-breakdown-BLF10tOO.js.map +0 -1
  106. package/dist/index-CWBSrqI6.d.ts.map +0 -1
  107. package/dist/oauth-bkEOybqm.js.map +0 -1
  108. package/dist/stdio-loader-BILyUGmi.js.map +0 -1
  109. package/dist/transcript-anchors-DEIr0tJC.js.map +0 -1
  110. package/dist/xai-Du6Wfnlb.js.map +0 -1
@@ -381,6 +381,114 @@ function buildContextBreakdown(snapshot) {
381
381
  };
382
382
  }
383
383
  //#endregion
384
- export { styleReplacementForVia as a, stripLineNumberPrefixes as i, describeVia as n, resolveOldString as r, buildContextBreakdown as t };
384
+ //#region src/chat/context-segments.ts
385
+ /**
386
+ * Context segments — pure transforms.
387
+ *
388
+ * Sibling to `context-breakdown.ts`: where that module answers "how many
389
+ * tokens is each part of my context", this one answers "what IS each part,
390
+ * and where did it come from". It turns the same assembled-prompt pieces into
391
+ * a flat list of {@link ContextSegment}s carrying the actual TEXT plus its
392
+ * provenance, so a UI can list every chunk loaded by default in a session,
393
+ * let the user read it, and open the file behind it when there is one.
394
+ *
395
+ * No React, no node — a browser-context renderer imports these via
396
+ * `zidane/chat/pure`.
397
+ *
398
+ * Provenance is honest about what can and can't be opened:
399
+ * - `'file'` — a real path on disk (AGENTS.md / CLAUDE.md / ruler md).
400
+ * The only origin that carries `path`, hence the only one
401
+ * a host can hand to `$EDITOR`.
402
+ * - `'built-in'` — compiled into the binary (base doctrine, subagent defs).
403
+ * - `'generated'` — assembled at prompt time from discovered state (the
404
+ * skills catalog is rendered from the skill manifests).
405
+ * - `'mcp'` — served by a remote MCP server at connect time.
406
+ */
407
+ /**
408
+ * Remove the first occurrence of `part` from `whole`, collapsing the seam.
409
+ *
410
+ * Used to carve the rules block out of the base system so the "System prompt"
411
+ * segment reports only doctrine + env. Substring-based because that's the
412
+ * contract the assembly documents (`rulesBlock` IS a substring of
413
+ * `baseSystem`); a miss leaves `whole` untouched, which degrades to
414
+ * over-reporting the base row rather than dropping text on the floor.
415
+ */
416
+ function removeFirst(whole, part) {
417
+ if (!part) return whole;
418
+ const at = whole.indexOf(part);
419
+ if (at < 0) return whole;
420
+ return `${whole.slice(0, at)}${whole.slice(at + part.length)}`.replace(/\n{3,}/g, "\n\n").trim();
421
+ }
422
+ /**
423
+ * Best-effort display name for an instruction file: its basename, with the
424
+ * parent directory prefixed when the basename alone would be ambiguous
425
+ * (`AGENTS.md` appears at up to four paths per scope). Path-separator handling
426
+ * covers both POSIX and Windows so this stays node-free.
427
+ */
428
+ function fileLabel(path) {
429
+ const parts = path.split(/[/\\]/).filter(Boolean);
430
+ const base = parts.at(-1) ?? path;
431
+ const parent = parts.at(-2);
432
+ return parent?.startsWith(".") ? `${parent}/${base}` : base;
433
+ }
434
+ /**
435
+ * Shape assembled-prompt pieces into a flat, render-ready segment list.
436
+ *
437
+ * Order is prompt order — base doctrine, then instruction files (broadest
438
+ * scope first, as `discoverAgentsMd` returns them), then the appended
439
+ * catalogs. Empty / whitespace-only pieces are dropped so the list never
440
+ * shows a zero-byte row.
441
+ */
442
+ function buildContextSegments(input) {
443
+ const segments = [];
444
+ const push = (seg) => {
445
+ if (!seg.text.trim()) return;
446
+ segments.push({
447
+ ...seg,
448
+ tokens: estimateTokens(seg.text)
449
+ });
450
+ };
451
+ const base = input.baseSystem ?? input.system ?? "";
452
+ const overridden = input.systemPath !== void 0;
453
+ push({
454
+ id: "system",
455
+ label: "System prompt",
456
+ origin: overridden ? "file" : "built-in",
457
+ detail: overridden ? "SYSTEM.md override + environment" : "doctrine + environment",
458
+ text: input.rulesBlock ? removeFirst(base, input.rulesBlock) : base,
459
+ ...input.systemPath !== void 0 ? { path: input.systemPath } : {}
460
+ });
461
+ for (const file of input.rulesFiles ?? []) push({
462
+ id: `rules:${file.path}`,
463
+ label: fileLabel(file.path),
464
+ origin: "file",
465
+ ...file.source ? { detail: file.source } : {},
466
+ text: file.contents,
467
+ path: file.path
468
+ });
469
+ push({
470
+ id: "skills",
471
+ label: "Skills catalog",
472
+ origin: "generated",
473
+ detail: "name + description per skill (bodies load on activation)",
474
+ text: input.skillsCatalog ?? ""
475
+ });
476
+ push({
477
+ id: "mcp-instructions",
478
+ label: "MCP instructions",
479
+ origin: "mcp",
480
+ detail: "served by the connected servers",
481
+ text: input.mcpInstructions ?? ""
482
+ });
483
+ push({
484
+ id: "subagent-defs",
485
+ label: "Subagent definitions",
486
+ origin: "built-in",
487
+ text: input.subagentDefs ?? ""
488
+ });
489
+ return segments;
490
+ }
491
+ //#endregion
492
+ export { stripLineNumberPrefixes as a, resolveOldString as i, buildContextBreakdown as n, styleReplacementForVia as o, describeVia as r, buildContextSegments as t };
385
493
 
386
- //# sourceMappingURL=context-breakdown-BLF10tOO.js.map
494
+ //# sourceMappingURL=context-segments-1mcqSCM3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context-segments-1mcqSCM3.js","names":[],"sources":["../src/tools/edit-utils.ts","../src/chat/context-breakdown.ts","../src/chat/context-segments.ts"],"sourcesContent":["/**\n * Internal helpers shared between the `edit` and `multi_edit` tools.\n *\n * Not part of the public API — intentionally not re-exported from `tools/index.ts`\n * or the package barrel.\n */\n\n/**\n * Count exact (non-overlapping) occurrences of `needle` in `haystack`.\n * Returns 0 for an empty needle — both edit tools reject empty `old_string`\n * up front, so this branch is defensive rather than semantic.\n */\nexport function countExactMatches(haystack: string, needle: string): number {\n if (needle.length === 0)\n return 0\n let count = 0\n let idx = 0\n while (true) {\n const next = haystack.indexOf(needle, idx)\n if (next === -1)\n break\n count++\n idx = next + needle.length\n }\n return count\n}\n\n// ---------------------------------------------------------------------------\n// Curly-quote normalization + SDK-sanitization fallbacks\n// ---------------------------------------------------------------------------\n//\n// Models can't reliably emit Unicode curly quotes, and the Anthropic API\n// silently sanitizes a handful of XML-like tags before they hit the model\n// (`<name>` → `<n>`, etc.). When `old_string` doesn't match exactly, we retry\n// against the same content with both transforms applied so an \"old_string not\n// found\" failure that's only typographical resolves on the second pass.\n//\n// Mirrors the Claude Code Edit tool's recovery strategy. Verbatim port of the\n// quote constants and the desanitization table; the resolve loop below is\n// reorganized to share state between exact / quote-normalized / desanitized.\n\nexport const LEFT_SINGLE_CURLY_QUOTE = '\\u2018'\nexport const RIGHT_SINGLE_CURLY_QUOTE = '\\u2019'\nexport const LEFT_DOUBLE_CURLY_QUOTE = '\\u201C'\nexport const RIGHT_DOUBLE_CURLY_QUOTE = '\\u201D'\n\n/** Map curly quotes (any of the four) to their straight ASCII equivalents. */\nexport function normalizeQuotes(str: string): string {\n return str\n .replaceAll(LEFT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(RIGHT_SINGLE_CURLY_QUOTE, '\\'')\n .replaceAll(LEFT_DOUBLE_CURLY_QUOTE, '\"')\n .replaceAll(RIGHT_DOUBLE_CURLY_QUOTE, '\"')\n}\n\n/**\n * Substitutions Anthropic's API applies to assistant output before the model\n * sees it. The model emits the sanitized form; the file on disk contains the\n * unsanitized form. We undo the substitutions on `old_string` so the search\n * lands on the actual file contents.\n *\n * Verbatim from `claude-code/tools/FileEditTool/utils.ts`.\n */\nconst DESANITIZATIONS: ReadonlyArray<readonly [string, string]> = [\n ['<fnr>', '<function_results>'],\n ['<n>', '<name>'],\n ['</n>', '</name>'],\n ['<o>', '<output>'],\n ['</o>', '</output>'],\n ['<e>', '<error>'],\n ['</e>', '</error>'],\n ['<s>', '<system>'],\n ['</s>', '</system>'],\n ['<r>', '<result>'],\n ['</r>', '</result>'],\n ['< META_START >', '<META_START>'],\n ['< META_END >', '<META_END>'],\n ['< EOT >', '<EOT>'],\n ['< META >', '<META>'],\n ['< SOS >', '<SOS>'],\n ['\\n\\nH:', '\\n\\nHuman:'],\n ['\\n\\nA:', '\\n\\nAssistant:'],\n]\n\n/**\n * Apply the SDK desanitization table to a string. Exported so the edit tools\n * can apply it to `new_string` whenever `old_string` matched via a\n * desanitize-class fallback — keeps the file's unsanitized form on disk\n * instead of writing the model's abbreviated form back.\n */\nexport function desanitize(s: string): string {\n let out = s\n for (const [from, to] of DESANITIZATIONS)\n out = out.replaceAll(from, to)\n return out\n}\n\n/**\n * Strip line-number prefixes from each line of a needle, used as a recovery\n * fallback when the model pastes a `read_file` chunk verbatim into\n * `old_string` — the on-disk file doesn't carry the metadata prefix.\n *\n * Accepts three separator characters so a model that learned on a different\n * agent stack still works here: `\\t` (Claude Code compact, our default),\n * `|`, and `→`. Pattern: optional leading whitespace, 1-9 digits, then one\n * of `\\t | →`. The 9-digit ceiling covers files up to ~1B lines without\n * overshooting into legitimate `\\d{N}<sep>` content like Markdown table\n * cells with long numeric IDs.\n */\nconst LINE_NUMBER_PREFIX_RE = /^[ \\t]*\\d{1,9}[\\t|\\u2192]/gm\nexport function stripLineNumberPrefixes(s: string): string {\n return s.replace(LINE_NUMBER_PREFIX_RE, '')\n}\n\n/**\n * Locate the actual substring in `haystack` that corresponds to `needle`,\n * recovering from typographical mismatch on six escalating fallbacks:\n *\n * 1. Exact substring match (the happy path — no transformation).\n * 2. Curly-quote normalization on both sides — when the model emits straight\n * quotes but the file has curly ones (or vice versa), the slice of the\n * file at the matched position carries the file's actual typography.\n * 3. Anthropic-sanitization undo on the needle — the model's `<n>` becomes\n * the file's `<name>`, etc.\n * 4. Combined: desanitize + quote normalization on the needle.\n * 5. Line-number-prefix strip — when the model pasted a numbered `read_file`\n * chunk verbatim into `old_string` and the file carries no such prefix.\n * 6. Combined: line-number strip + quote normalization — paste-back of a\n * numbered chunk against a file whose typography differs from the model's.\n *\n * Returns `{ actual, occurrences }` — `actual` is the string that exists in\n * the file (use this to do the actual replace; preserves the file's\n * typography). `occurrences` is the count of those matches in the file.\n *\n * Fallbacks 3-4 (desanitize-class) only fire when the transformed needle is\n * UNIQUE in the file — they rewrite the needle's meaning rather than its\n * typography, so an ambiguous match risks silently retargeting the wrong\n * text (see the inline comment at step 3).\n *\n * Returns `null` when no recovery worked.\n */\nexport interface ResolvedMatch {\n actual: string\n occurrences: number\n /** Recovery path — `'exact'` when no transformation was applied. */\n via: 'exact' | 'quotes' | 'desanitize' | 'quotes+desanitize' | 'line-numbers' | 'quotes+line-numbers'\n}\n\n/**\n * Search `target` in `normFile` and slice the matching span out of the\n * original `haystack`, counting all non-overlapping occurrences. `normFile`\n * is the haystack with whatever transform (quotes / desanitize / combined)\n * was applied to make the indices align — slicing the original haystack\n * preserves the file's actual typography so `replace_all` writes back the\n * file's form, not the model's.\n *\n * Pre-condition: `normFile.length === haystack.length` (every transform\n * we use is one-to-one). Returns null on miss.\n */\nfunction locateAndCount(\n haystack: string,\n normFile: string,\n target: string,\n via: ResolvedMatch['via'],\n): ResolvedMatch | null {\n const idx = normFile.indexOf(target)\n if (idx === -1)\n return null\n const actual = haystack.slice(idx, idx + target.length)\n let occ = 0\n let cursor = 0\n while (true) {\n const next = normFile.indexOf(target, cursor)\n if (next === -1)\n break\n occ++\n cursor = next + target.length\n }\n return { actual, occurrences: occ, via }\n}\n\nexport function resolveOldString(haystack: string, needle: string): ResolvedMatch | null {\n // 1. Exact match — happy path.\n const exact = countExactMatches(haystack, needle)\n if (exact > 0)\n return { actual: needle, occurrences: exact, via: 'exact' }\n\n // 2. Curly-quote normalization. Either side can carry curly quotes:\n // model emitted straight + file has curly, OR model emitted curly +\n // file has straight. Normalize both and look there. Slice the original\n // haystack to recover the actual file-side typography.\n const normNeedle = normalizeQuotes(needle)\n const normFile = normalizeQuotes(haystack)\n if (normNeedle !== needle || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, normNeedle, 'quotes')\n if (m)\n return m\n }\n\n // 3. Desanitize the needle — model-side substitution undo (`<n>` → `<name>`,\n // etc.) The file always has the unsanitized form; only the model emits\n // the abbreviated version.\n //\n // Desanitize-class fallbacks additionally require a UNIQUE transformed\n // match. Unlike the quote / line-number transforms (typography-only /\n // verbatim paste-back), this one rewrites the needle's meaning — a model\n // that genuinely meant the literal `<n>` against a file full of `<name>`\n // would otherwise silently retarget every occurrence under `replace_all`.\n // A unique hit bounds the blast radius to one visible replacement.\n const desan = desanitize(needle)\n if (desan !== needle) {\n const desanCount = countExactMatches(haystack, desan)\n if (desanCount === 1)\n return { actual: desan, occurrences: desanCount, via: 'desanitize' }\n }\n\n // 4. Combined: desanitize + quote normalization. Hit when the model\n // emitted both sanitized tokens and straight quotes, but the file has\n // the unsanitized form with curly quotes. Same uniqueness requirement\n // as #3.\n const combo = desanitize(normNeedle)\n if (combo !== needle) {\n const m = locateAndCount(haystack, normFile, combo, 'quotes+desanitize')\n if (m && m.occurrences === 1)\n return m\n }\n\n // 5. Line-number-prefix strip. When `read_file` returns line-numbered\n // output and the model pasted the chunk verbatim into `old_string`,\n // the on-disk file doesn't carry those prefixes. Strip them and\n // retry; the file-side `actual` is the prefix-free needle so the\n // replacement lands on real bytes.\n //\n // Guard against a needle that strips down to whitespace-only (e.g.\n // `1\\t\\n2\\t\\n3\\t` → `\\n\\n`). Searching for `\\n\\n` would match arbitrary\n // blank-line patterns anywhere in the file — a high false-positive risk.\n // Require the stripped needle to carry at least one non-whitespace\n // character before we trust the result.\n const stripped = stripLineNumberPrefixes(needle)\n if (stripped !== needle && stripped.trim().length > 0) {\n const count = countExactMatches(haystack, stripped)\n if (count > 0)\n return { actual: stripped, occurrences: count, via: 'line-numbers' }\n\n // 6. Combined: line-number strip + curly-quote normalization. The\n // typography mismatch may live in the file, the needle, or both.\n const strippedNorm = normalizeQuotes(stripped)\n if (strippedNorm !== stripped || normFile !== haystack) {\n const m = locateAndCount(haystack, normFile, strippedNorm, 'quotes+line-numbers')\n if (m)\n return m\n }\n }\n\n return null\n}\n\n/**\n * Short human-readable label for a recovery path, used by `edit` /\n * `multi_edit` to flag non-exact matches in their result messages — when a\n * fallback mistargets, the model (and the user reading the transcript) can\n * see WHICH transform fired instead of silently trusting the edit.\n */\nexport function describeVia(via: ResolvedMatch['via']): string {\n switch (via) {\n case 'exact': return 'exact match'\n case 'quotes': return 'curly-quote normalization'\n case 'desanitize': return 'sanitization recovery (e.g. <n> → <name>)'\n case 'quotes+desanitize': return 'sanitization recovery + curly-quote normalization'\n case 'line-numbers': return 'line-number-prefix stripping'\n case 'quotes+line-numbers': return 'line-number-prefix stripping + curly-quote normalization'\n }\n}\n\n/**\n * Apply the same recovery transforms used to find `old_string` to\n * `new_string`, so the file gets back its native form: desanitize when\n * the model emitted `<n>` for `<name>`, strip line-number prefixes when\n * the match required them, then re-curlify when the match required\n * quote normalization. Shared between `edit` and `multi_edit`.\n */\nexport function styleReplacementForVia(\n replacement: string,\n via: ResolvedMatch['via'],\n actual: string,\n): string {\n let out = replacement\n if (via === 'desanitize' || via === 'quotes+desanitize')\n out = desanitize(out)\n if (via === 'line-numbers' || via === 'quotes+line-numbers')\n out = stripLineNumberPrefixes(out)\n if (via === 'quotes' || via === 'quotes+desanitize' || via === 'quotes+line-numbers')\n out = preserveQuoteStyle(actual, out)\n return out\n}\n\n/**\n * When `old_string` matched via curly-quote normalization, re-style\n * `new_string` so the file's typography is preserved across the edit.\n * Detects whether the matched file region had curly singles, doubles, or\n * both, and applies the matching curlification to the replacement.\n *\n * Apostrophes in contractions (`don't`, `it's`) get the right-single curly\n * quote regardless of opening context — that's the canonical typographer's\n * convention for English. Other quotes use a simple\n * preceded-by-whitespace-or-opening-punctuation heuristic.\n */\nexport function preserveQuoteStyle(actual: string, replacement: string): string {\n const hasDouble = actual.includes(LEFT_DOUBLE_CURLY_QUOTE) || actual.includes(RIGHT_DOUBLE_CURLY_QUOTE)\n const hasSingle = actual.includes(LEFT_SINGLE_CURLY_QUOTE) || actual.includes(RIGHT_SINGLE_CURLY_QUOTE)\n if (!hasDouble && !hasSingle)\n return replacement\n\n let out = replacement\n if (hasDouble)\n out = applyCurly(out, '\"', LEFT_DOUBLE_CURLY_QUOTE, RIGHT_DOUBLE_CURLY_QUOTE, false)\n if (hasSingle)\n out = applyCurly(out, '\\'', LEFT_SINGLE_CURLY_QUOTE, RIGHT_SINGLE_CURLY_QUOTE, true)\n return out\n}\n\nfunction applyCurly(\n s: string,\n straight: string,\n left: string,\n right: string,\n contractionAware: boolean,\n): string {\n const chars = [...s]\n const result: string[] = []\n for (let i = 0; i < chars.length; i++) {\n if (chars[i] !== straight) {\n result.push(chars[i])\n continue\n }\n if (contractionAware) {\n const prev = i > 0 ? chars[i - 1] : ''\n const next = i < chars.length - 1 ? chars[i + 1] : ''\n // Letter-quote-letter is a contraction, not a quote — always right.\n if (/\\p{L}/u.test(prev) && /\\p{L}/u.test(next)) {\n result.push(right)\n continue\n }\n }\n result.push(isOpeningContext(chars, i) ? left : right)\n }\n return result.join('')\n}\n\nfunction isOpeningContext(chars: string[], i: number): boolean {\n if (i === 0)\n return true\n const prev = chars[i - 1]\n return prev === ' ' || prev === '\\t' || prev === '\\n' || prev === '\\r'\n || prev === '(' || prev === '[' || prev === '{'\n || prev === '\\u2014' || prev === '\\u2013' // em / en dash\n}\n","/**\n * Context-usage breakdown — pure transforms.\n *\n * Turns a {@link ContextSnapshot} (the raw pieces the agent assembled for a\n * run: system prompt, wire tools, deferred tools, MCP tools/instructions,\n * skills catalog, ...) plus the real last-turn token total into a categorized\n * {@link ContextBreakdown} the TUI panel / GUI popover render.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`. The snapshot is captured main-side (TUI direct, GUI in\n * `main/chat`) because building it reads provider/agent state; only the pure\n * shaping lives here.\n *\n * Accuracy: per-category counts are estimates when no provider `countTokens`\n * is available — the heuristic ({@link estimateTokens}, ~4 bytes/token) sizes\n * each static segment and the bar is reconciled so it always sums to the real\n * last-turn total (`conversation = realTotal - sum(static)`). When a provider\n * exposes exact counts (Anthropic, OpenAI), the caller passes them in via\n * {@link ContextSnapshot.exact} and the corresponding categories drop their\n * `estimated` flag. Exact buckets (free space, autocompact buffer) are never\n * estimated.\n */\n\nimport type { SessionTurn } from '../types'\nimport { estimateTokens } from '../compact/utils'\n\n/**\n * Stable identifiers for each breakdown category. Drives swatch color +\n * ordering in both UIs. `*Deferred` buckets are tools/MCP that exist but are\n * NOT currently on the wire (lazy disclosure); `autocompactBuffer` is the\n * reserved output headroom; `freeSpace` is the remaining window.\n */\nexport type ContextCategoryId\n = | 'systemPrompt'\n | 'rules'\n | 'tools'\n | 'mcpTools'\n | 'mcpInstructions'\n | 'skills'\n | 'subagentDefs'\n | 'conversation'\n | 'mcpToolsDeferred'\n | 'toolsDeferred'\n | 'autocompactBuffer'\n | 'freeSpace'\n\n/**\n * Exact last-turn token usage split (provider-reported — always exact). Drives\n * the cache breakdown shown below the categories. `cacheRead + cacheCreation +\n * input` equals the live context total (`used`).\n */\nexport interface ContextUsageSplit {\n /** Fresh, uncached input tokens this turn. */\n input: number\n /** Tokens served from the prompt cache (the cached prefix). */\n cacheRead: number\n /** Tokens written to the cache this turn. */\n cacheCreation: number\n /** Assistant output tokens (not part of the input window; informational). */\n output: number\n}\n\n/** One display row contributed by an extension to the context panel. */\nexport interface ContextExtensionRow {\n label: string\n value: string\n}\n\n/** Extension-owned context panel section. Core treats rows as opaque display data. */\nexport interface ContextExtensionSection {\n id: string\n label: string\n /** Optional section-title foreground color. UIs fall back to their theme accent. */\n accentColor?: string\n rows: readonly ContextExtensionRow[]\n}\n\n/** Data exposed to extension context-breakdown contributors. */\nexport interface ContextBreakdownContributionContext {\n turns: readonly SessionTurn[]\n}\n\n/** Extension hook for adding opaque rows to the context panel. */\nexport type ContextBreakdownContributor\n = (ctx: ContextBreakdownContributionContext) =>\n | ContextExtensionSection\n | readonly ContextExtensionSection[]\n | null\n | undefined\n | Promise<ContextExtensionSection | readonly ContextExtensionSection[] | null | undefined>\n\n/** One expandable child row under a category (e.g. a single MCP tool / memory file). */\nexport interface ContextItem {\n /** Stable-ish key for rendering (tool name, file path). */\n id: string\n /** Display label. */\n label: string\n /** Token count for this item. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n}\n\n/** One category row in the breakdown. */\nexport interface ContextCategory {\n id: ContextCategoryId\n /** Display label (e.g. \"Tool definitions\"). */\n label: string\n /** Token count for the category. */\n tokens: number\n /** True when `tokens` came from the heuristic rather than an exact count. */\n estimated: boolean\n /**\n * True for buckets that are NOT counted against the live window total\n * (deferred tools, free space, autocompact buffer) — the UI renders these\n * dimmed / below a divider, mirroring Claude Code's layout.\n */\n deferred?: boolean\n /** Optional expandable child rows (per MCP tool, per memory file, ...). */\n items?: ContextItem[]\n}\n\n/** The shaped, render-ready breakdown. */\nexport interface ContextBreakdown {\n /** Model id the snapshot was built for. */\n modelId: string\n /**\n * Real last-turn context size (provider-reported `input + cacheRead +\n * cacheCreation`) — the SAME number the footer/orb shows. The non-deferred\n * categories always sum to this.\n */\n used: number\n /** Effective window (raw - output reserve), the bar's denominator. */\n effectiveWindow: number\n /** `used / effectiveWindow`, clamped to [0, 1]. */\n fraction: number\n /** Live categories (sum to `used`) followed by deferred + free-space buckets. */\n categories: ContextCategory[]\n /** True when ANY live category is estimated (drives the panel's footnote). */\n hasEstimates: boolean\n /**\n * Exact last-turn usage split (cache read / write / fresh input / output),\n * when the host supplied it. Always exact — rendered as an informational\n * section below the categories. Absent when no usage is available yet.\n */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /**\n * Names of currently-active skills. Informational — an activated skill's body\n * lands in the conversation (tool-results), so its tokens are already counted\n * under Conversation; this just surfaces \"which skills are loaded\". Empty/absent\n * when none are active.\n */\n activeSkills?: string[]\n}\n\n/** Host-supplied options for `agent.getContextBreakdown`. */\nexport interface ContextBreakdownOptions {\n /**\n * Effective context window (`rawWindow - outputReserve`) for the active\n * model, resolved by the host via the chat model registry. Drives free-space\n * + fraction. When omitted, defaults to `used` (no headroom shown).\n */\n effectiveWindow?: number\n /**\n * Active model id — used for the exact `countTokens` call + the header label.\n * Only consulted on the PRE-RUN path (no snapshot yet); once a run has fired,\n * the snapshot's own model wins. When omitted, the provider default is used.\n */\n model?: string\n /** Tokens reserved for output (autocompact buffer). Defaults to 0. */\n autocompactBuffer?: number\n /**\n * Auto-compact threshold as a fraction of the window (0–1), when enabled.\n * When set, the \"Autocompact buffer\" bucket represents the ENTIRE tail from\n * the threshold to the end of the window (`(1 − threshold) × window`) rather\n * than just the reserved-output tokens — so the bar/row show exactly where\n * compaction fires. When omitted, `autocompactBuffer` is used as-is.\n */\n compactThreshold?: number\n /** Abort signal forwarded to the provider's `countTokens`. */\n signal?: AbortSignal\n}\n\n/** Tools grouped by MCP server, for the expandable per-server rows. */\nexport interface ContextMcpGroup {\n server: string\n /** Wire tool specs for this server (their JSON size is measured). */\n tools: { name: string, json: string }[]\n}\n\n/**\n * Exact per-segment counts from a provider's `countTokens`, when available.\n * Each field is the count of the cumulative payload up to and including that\n * segment, so categories are derived by differencing (see\n * {@link buildContextBreakdown}). Any subset may be present; missing fields\n * fall back to the heuristic for that category.\n */\nexport interface ContextExactCounts {\n /** Tokens for system prompt alone. */\n system?: number\n /** Tokens for system + tools (so tools = systemAndTools - system). */\n systemAndTools?: number\n /** Tokens for the full payload (system + tools + messages) = the real total. */\n full?: number\n}\n\n/**\n * Raw inputs captured at agent prompt-assembly time. Everything here is what\n * actually went on (or was withheld from) the wire for the last run.\n */\nexport interface ContextSnapshot {\n modelId: string\n /** Full rendered system prompt (marker-stripped, as sent). */\n system: string\n /**\n * Host-composed base system BEFORE the agent appended skills / searchable /\n * MCP-instructions catalogs. Includes the rules block. The \"System prompt\"\n * (base doctrine) bucket = base − rules − env-noise. Defaults to `system`\n * when not provided (back-compat).\n */\n baseSystem?: string\n /** Rendered AGENTS.md/CLAUDE.md rules block (a substring of `baseSystem`). */\n rulesBlock?: string\n /** Source files behind the rules block, for per-file rows. */\n rulesFiles?: { path: string, source: string }[]\n /** Wire tool specs currently disclosed to the model, as JSON strings. */\n toolsJson: string[]\n /** Lazy tool entries NOT currently disclosed (deferred), as JSON strings. */\n deferredToolsJson: string[]\n /** MCP tools grouped by server (disclosed ones). */\n mcpGroups: ContextMcpGroup[]\n /** Deferred (undisclosed) MCP tools grouped by server. */\n deferredMcpGroups: ContextMcpGroup[]\n /** Rendered MCP instructions block, if any. */\n mcpInstructions?: string\n /** Rendered skills catalog text, if any. */\n skillsCatalog?: string\n /** Searchable / subagent (spawn) tool definitions text, if any. */\n subagentDefs?: string\n /** Memory / rules files in context. */\n /** Real last-turn total (input + cacheRead + cacheCreation). */\n used: number\n /** Effective window (raw - output reserve). */\n effectiveWindow: number\n /** Tokens reserved for output (autocompact buffer). */\n autocompactBuffer: number\n /** Exact per-segment counts from the provider, when available. */\n exact?: ContextExactCounts\n /** Exact last-turn usage split, when available (passed straight through). */\n usage?: ContextUsageSplit\n /** Extension-owned context panel sections. */\n extensionSections?: readonly ContextExtensionSection[]\n /** Names of currently-active skills (passed straight through). */\n activeSkills?: string[]\n}\n\nconst LABELS: Record<ContextCategoryId, string> = {\n systemPrompt: 'System prompt',\n rules: 'Rules (AGENTS.md)',\n tools: 'Tool definitions',\n mcpTools: 'MCP tools',\n mcpInstructions: 'MCP instructions',\n skills: 'Skills',\n subagentDefs: 'Subagent definitions',\n conversation: 'Conversation',\n mcpToolsDeferred: 'MCP tools (deferred)',\n toolsDeferred: 'System tools (deferred)',\n autocompactBuffer: 'Autocompact buffer',\n freeSpace: 'Free space',\n}\n\n/** Sum the heuristic token sizes of a list of strings. */\nfunction sumEstimate(parts: readonly string[]): number {\n let total = 0\n for (const p of parts)\n total += estimateTokens(p)\n return total\n}\n\nfunction mcpGroupTokens(group: ContextMcpGroup): { total: number, items: ContextItem[] } {\n const items: ContextItem[] = group.tools.map(t => ({\n id: `${group.server}:${t.name}`,\n label: t.name,\n tokens: estimateTokens(t.json),\n estimated: true,\n }))\n let total = 0\n for (const it of items)\n total += it.tokens\n return { total, items }\n}\n\n/**\n * Shape a {@link ContextSnapshot} into a render-ready {@link ContextBreakdown}.\n *\n * Live categories (system prompt, tools, MCP tools/instructions, skills,\n * memory, subagent defs, conversation) sum to `snapshot.used` — `conversation`\n * absorbs the remainder so the bar matches the provider-reported total exactly.\n * Deferred + autocompact + free-space buckets follow.\n *\n * When `snapshot.exact` carries provider counts, the matching categories use\n * them (system, tools) and drop their `estimated` flag; everything else stays\n * on the heuristic.\n */\nexport function buildContextBreakdown(snapshot: ContextSnapshot): ContextBreakdown {\n const exact = snapshot.exact\n const systemExact = typeof exact?.system === 'number'\n\n // --- System-embedded sub-sections (heuristic) ----------------------------\n // The exact `count_tokens` system number covers the WHOLE system text. The\n // appended catalogs (rules / skills / MCP instructions / subagent defs) all\n // live inside it, so we size each heuristically and let the \"System prompt\"\n // (base doctrine) bucket absorb the remainder — keeping the system group's\n // sum exact while still attributing each section.\n const rulesTokens = snapshot.rulesBlock ? estimateTokens(snapshot.rulesBlock) : 0\n const rulesItems: ContextItem[] = (snapshot.rulesFiles ?? []).map(f => ({\n id: f.path,\n label: f.path,\n // Per-file size isn't separable from the rendered block; show the path only\n // (tokens 0, not estimated — there's nothing to estimate) so the row lists\n // sources without implying a per-file count or a `~` marker.\n tokens: 0,\n estimated: false,\n }))\n const skillsTokens = snapshot.skillsCatalog ? estimateTokens(snapshot.skillsCatalog) : 0\n const mcpInstructionsTokens = snapshot.mcpInstructions ? estimateTokens(snapshot.mcpInstructions) : 0\n const subagentTokens = snapshot.subagentDefs ? estimateTokens(snapshot.subagentDefs) : 0\n const embeddedSubsections = rulesTokens + skillsTokens + mcpInstructionsTokens + subagentTokens\n\n // System TOTAL (whole system text) — exact when available.\n const systemTotal = systemExact ? exact!.system! : estimateTokens(snapshot.system)\n // Base doctrine = system total minus the attributed sub-sections.\n const baseSystemTokens = Math.max(0, systemTotal - embeddedSubsections)\n\n // --- Native tool definitions (non-MCP, disclosed) ------------------------\n // When exact `systemAndTools` is available it covers BOTH native + MCP tools,\n // so we split that combined number proportionally by heuristic weight rather\n // than claiming exactness per sub-bucket.\n const nativeToolsEst = sumEstimate(snapshot.toolsJson)\n const mcpDisclosed = snapshot.mcpGroups.map(mcpGroupTokens)\n const mcpToolsEst = mcpDisclosed.reduce((a, g) => a + g.total, 0)\n\n let nativeToolsTokens = nativeToolsEst\n let mcpToolsTokens = mcpToolsEst\n let toolsEstimated = true\n if (systemExact && typeof exact?.systemAndTools === 'number') {\n const exactToolsTotal = Math.max(0, exact.systemAndTools - exact.system!)\n const estTotal = nativeToolsEst + mcpToolsEst\n if (estTotal > 0) {\n nativeToolsTokens = Math.round(exactToolsTotal * (nativeToolsEst / estTotal))\n mcpToolsTokens = exactToolsTotal - nativeToolsTokens\n }\n else {\n nativeToolsTokens = exactToolsTotal\n mcpToolsTokens = 0\n }\n toolsEstimated = false\n }\n\n // --- Live categories -----------------------------------------------------\n // Detailed split. The system-embedded sub-sections (rules / skills / MCP\n // instructions / subagent defs) are heuristic; the \"System prompt\" base\n // bucket carries the exact remainder so the whole system group still sums to\n // the exact system count. Tools/MCP-tools/conversation are split as before.\n const live: ContextCategory[] = []\n const push = (id: ContextCategoryId, tokens: number, estimated: boolean, items?: ContextItem[]) => {\n if (tokens <= 0 && !items?.length)\n return\n live.push({ id, label: LABELS[id], tokens: Math.max(0, tokens), estimated, ...(items?.length ? { items } : {}) })\n }\n\n // System group: base doctrine (exact remainder) + attributed sub-sections.\n push('systemPrompt', baseSystemTokens, !systemExact)\n push('rules', rulesTokens, true, rulesItems)\n push('skills', skillsTokens, true)\n push('mcpInstructions', mcpInstructionsTokens, true)\n push('subagentDefs', subagentTokens, true)\n // Tools.\n push('tools', nativeToolsTokens, toolsEstimated)\n push('mcpTools', mcpToolsTokens, toolsEstimated, mcpDisclosed.flatMap(g => g.items))\n\n // --- Conversation = remainder (keeps the bar summing to `used`) ----------\n const accountedStatic = live.reduce((a, c) => a + c.tokens, 0)\n const conversationTokens = Math.max(0, snapshot.used - accountedStatic)\n // Exact when both system AND tools were exactly counted — then the remainder\n // (used − exactSystem − exactTools) is itself exact, since `used` is the\n // provider-reported total.\n const conversationEstimated = !(systemExact && !toolsEstimated)\n push('conversation', conversationTokens, conversationEstimated)\n\n // --- Deferred buckets (not counted against `used`) -----------------------\n const deferred: ContextCategory[] = []\n const deferredNativeTools = sumEstimate(snapshot.deferredToolsJson)\n if (deferredNativeTools > 0) {\n deferred.push({ id: 'toolsDeferred', label: LABELS.toolsDeferred, tokens: deferredNativeTools, estimated: true, deferred: true })\n }\n const deferredMcp = snapshot.deferredMcpGroups.map(mcpGroupTokens)\n const deferredMcpTotal = deferredMcp.reduce((a, g) => a + g.total, 0)\n if (deferredMcpTotal > 0) {\n deferred.push({\n id: 'mcpToolsDeferred',\n label: LABELS.mcpToolsDeferred,\n tokens: deferredMcpTotal,\n estimated: true,\n deferred: true,\n items: deferredMcp.flatMap(g => g.items),\n })\n }\n\n // --- Autocompact buffer + free space (exact) -----------------------------\n if (snapshot.autocompactBuffer > 0) {\n deferred.push({ id: 'autocompactBuffer', label: LABELS.autocompactBuffer, tokens: snapshot.autocompactBuffer, estimated: false, deferred: true })\n }\n const free = Math.max(0, snapshot.effectiveWindow - snapshot.used)\n deferred.push({ id: 'freeSpace', label: LABELS.freeSpace, tokens: free, estimated: false, deferred: true })\n\n const categories = [...live, ...deferred]\n const hasEstimates = live.some(c => c.estimated && c.tokens > 0)\n const fraction = snapshot.effectiveWindow > 0\n ? Math.max(0, Math.min(1, snapshot.used / snapshot.effectiveWindow))\n : 0\n\n return {\n modelId: snapshot.modelId,\n used: snapshot.used,\n effectiveWindow: snapshot.effectiveWindow,\n fraction,\n categories,\n hasEstimates,\n ...(snapshot.usage ? { usage: snapshot.usage } : {}),\n ...(snapshot.extensionSections?.length ? { extensionSections: snapshot.extensionSections } : {}),\n ...(snapshot.activeSkills?.length ? { activeSkills: snapshot.activeSkills } : {}),\n }\n}\n","/**\n * Context segments — pure transforms.\n *\n * Sibling to `context-breakdown.ts`: where that module answers \"how many\n * tokens is each part of my context\", this one answers \"what IS each part,\n * and where did it come from\". It turns the same assembled-prompt pieces into\n * a flat list of {@link ContextSegment}s carrying the actual TEXT plus its\n * provenance, so a UI can list every chunk loaded by default in a session,\n * let the user read it, and open the file behind it when there is one.\n *\n * No React, no node — a browser-context renderer imports these via\n * `zidane/chat/pure`.\n *\n * Provenance is honest about what can and can't be opened:\n * - `'file'` — a real path on disk (AGENTS.md / CLAUDE.md / ruler md).\n * The only origin that carries `path`, hence the only one\n * a host can hand to `$EDITOR`.\n * - `'built-in'` — compiled into the binary (base doctrine, subagent defs).\n * - `'generated'` — assembled at prompt time from discovered state (the\n * skills catalog is rendered from the skill manifests).\n * - `'mcp'` — served by a remote MCP server at connect time.\n */\n\nimport { estimateTokens } from '../compact/utils'\n\n/** Where a segment's text came from. Only `'file'` segments carry a `path`. */\nexport type ContextSegmentOrigin = 'built-in' | 'file' | 'generated' | 'mcp'\n\n/** One chunk of text present in the session's default context. */\nexport interface ContextSegment {\n /** Stable key for rendering (`'system'`, `'rules:<path>'`, `'skills'`, ...). */\n id: string\n /** Display label (e.g. \"System prompt\", or the file's basename). */\n label: string\n origin: ContextSegmentOrigin\n /**\n * Short right-hand qualifier — the instruction scope for files, the server\n * list for MCP, a count for the skills catalog. Absent when there's nothing\n * useful to add beyond the origin badge.\n */\n detail?: string\n /** The text itself, as it sits in the prompt. Empty segments are dropped. */\n text: string\n /**\n * Absolute path of the file backing this segment. Present only for\n * `origin: 'file'` — a host uses it as the \"open in $EDITOR\" target.\n */\n path?: string\n /**\n * Heuristic token size (~4 bytes/token). Always an estimate: exact\n * per-segment counts aren't separable from the single system-prompt string\n * the provider counts, which is why {@link ContextSegment} carries no\n * `estimated` flag — every value here is one.\n */\n tokens: number\n}\n\n/**\n * A host-discovered instruction file. Structurally compatible with\n * `AgentsMdFile` from `./agents-md` (whose `source` field is the SCOPE, not\n * the text — `contents` is the text), so callers can pass those straight in.\n */\nexport interface ContextSegmentFile {\n path: string\n /** Instruction scope — `'project'` / `'user'`, surfaced as the row detail. */\n source?: string\n contents: string\n}\n\n/**\n * The assembled-prompt pieces {@link buildContextSegments} shapes. Mirrors the\n * subset of the agent's `ContextAssembly` that carries text, plus host-side\n * instruction files (which the assembly only knows as paths).\n */\nexport interface ContextSegmentsInput {\n /**\n * Host-composed base system BEFORE the agent appended its catalogs. The\n * rules block is a substring of this; the \"System prompt\" segment is the\n * remainder. Falls back to `system` when absent, which over-attributes the\n * appended catalogs into the base row rather than losing them.\n */\n baseSystem?: string\n /** Full rendered system prompt as sent. Used as the `baseSystem` fallback. */\n system?: string\n /**\n * Rendered instruction block (a substring of `baseSystem`). Subtracted from\n * the base so its text isn't reported twice — once as doctrine and once as\n * per-file rows.\n */\n rulesBlock?: string\n /** The files behind `rulesBlock`, each with its own text. */\n rulesFiles?: readonly ContextSegmentFile[]\n /**\n * Absolute path of a `SYSTEM.md` override backing the base prompt. When set,\n * the \"System prompt\" segment reports `origin: 'file'` and becomes openable\n * — the doctrine is the user's file, not compiled-in text.\n */\n systemPath?: string\n /** Rendered skills catalog (the per-skill blurbs, not skill bodies). */\n skillsCatalog?: string\n /** Rendered MCP instructions block. */\n mcpInstructions?: string\n /** Searchable / subagent (spawn) tool catalog text. */\n subagentDefs?: string\n}\n\n/**\n * Remove the first occurrence of `part` from `whole`, collapsing the seam.\n *\n * Used to carve the rules block out of the base system so the \"System prompt\"\n * segment reports only doctrine + env. Substring-based because that's the\n * contract the assembly documents (`rulesBlock` IS a substring of\n * `baseSystem`); a miss leaves `whole` untouched, which degrades to\n * over-reporting the base row rather than dropping text on the floor.\n */\nfunction removeFirst(whole: string, part: string): string {\n if (!part)\n return whole\n const at = whole.indexOf(part)\n if (at < 0)\n return whole\n return `${whole.slice(0, at)}${whole.slice(at + part.length)}`.replace(/\\n{3,}/g, '\\n\\n').trim()\n}\n\n/**\n * Best-effort display name for an instruction file: its basename, with the\n * parent directory prefixed when the basename alone would be ambiguous\n * (`AGENTS.md` appears at up to four paths per scope). Path-separator handling\n * covers both POSIX and Windows so this stays node-free.\n */\nfunction fileLabel(path: string): string {\n const parts = path.split(/[/\\\\]/).filter(Boolean)\n const base = parts.at(-1) ?? path\n const parent = parts.at(-2)\n // A dotted parent (`.agents`, `.zidane`, `.claude`, `.ruler`) is the\n // meaningful discriminator between same-named instruction files.\n return parent?.startsWith('.') ? `${parent}/${base}` : base\n}\n\n/**\n * Shape assembled-prompt pieces into a flat, render-ready segment list.\n *\n * Order is prompt order — base doctrine, then instruction files (broadest\n * scope first, as `discoverAgentsMd` returns them), then the appended\n * catalogs. Empty / whitespace-only pieces are dropped so the list never\n * shows a zero-byte row.\n */\nexport function buildContextSegments(input: ContextSegmentsInput): ContextSegment[] {\n const segments: ContextSegment[] = []\n const push = (seg: Omit<ContextSegment, 'tokens'>) => {\n if (!seg.text.trim())\n return\n segments.push({ ...seg, tokens: estimateTokens(seg.text) })\n }\n\n // --- Base doctrine -------------------------------------------------------\n // `baseSystem` minus the rules block. The per-file rows below carry the\n // instruction text, so leaving the block in would double-report it.\n const base = input.baseSystem ?? input.system ?? ''\n const overridden = input.systemPath !== undefined\n push({\n id: 'system',\n label: 'System prompt',\n // An override makes this a real file on disk; without one it's compiled in.\n origin: overridden ? 'file' : 'built-in',\n detail: overridden ? 'SYSTEM.md override + environment' : 'doctrine + environment',\n text: input.rulesBlock ? removeFirst(base, input.rulesBlock) : base,\n ...(input.systemPath !== undefined ? { path: input.systemPath } : {}),\n })\n\n // --- Instruction files ---------------------------------------------------\n // The only file-backed segments, and so the only openable ones.\n for (const file of input.rulesFiles ?? []) {\n push({\n id: `rules:${file.path}`,\n label: fileLabel(file.path),\n origin: 'file',\n ...(file.source ? { detail: file.source } : {}),\n text: file.contents,\n path: file.path,\n })\n }\n\n // --- Appended catalogs ---------------------------------------------------\n push({\n id: 'skills',\n label: 'Skills catalog',\n origin: 'generated',\n detail: 'name + description per skill (bodies load on activation)',\n text: input.skillsCatalog ?? '',\n })\n push({\n id: 'mcp-instructions',\n label: 'MCP instructions',\n origin: 'mcp',\n detail: 'served by the connected servers',\n text: input.mcpInstructions ?? '',\n })\n push({\n id: 'subagent-defs',\n label: 'Subagent definitions',\n origin: 'built-in',\n text: input.subagentDefs ?? '',\n })\n\n return segments\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,SAAgB,kBAAkB,UAAkB,QAAwB;CAC1E,IAAI,OAAO,WAAW,GACpB,OAAO;CACT,IAAI,QAAQ;CACZ,IAAI,MAAM;CACV,OAAO,MAAM;EACX,MAAM,OAAO,SAAS,QAAQ,QAAQ,GAAG;EACzC,IAAI,SAAS,IACX;EACF;EACA,MAAM,OAAO,OAAO;CACtB;CACA,OAAO;AACT;;AAsBA,SAAgB,gBAAgB,KAAqB;CACnD,OAAO,IACJ,WAAA,KAAoC,GAAI,CAAC,CACzC,WAAA,KAAqC,GAAI,CAAC,CAC1C,WAAA,KAAoC,IAAG,CAAC,CACxC,WAAA,KAAqC,IAAG;AAC7C;;;;;;;;;AAUA,MAAM,kBAA4D;CAChE,CAAC,SAAS,oBAAoB;CAC9B,CAAC,OAAO,QAAQ;CAChB,CAAC,QAAQ,SAAS;CAClB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,SAAS;CACjB,CAAC,QAAQ,UAAU;CACnB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,OAAO,UAAU;CAClB,CAAC,QAAQ,WAAW;CACpB,CAAC,kBAAkB,cAAc;CACjC,CAAC,gBAAgB,YAAY;CAC7B,CAAC,WAAW,OAAO;CACnB,CAAC,YAAY,QAAQ;CACrB,CAAC,WAAW,OAAO;CACnB,CAAC,UAAU,YAAY;CACvB,CAAC,UAAU,gBAAgB;AAC7B;;;;;;;AAQA,SAAgB,WAAW,GAAmB;CAC5C,IAAI,MAAM;CACV,KAAK,MAAM,CAAC,MAAM,OAAO,iBACvB,MAAM,IAAI,WAAW,MAAM,EAAE;CAC/B,OAAO;AACT;;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AUA,SAAgB,qBAAqB,OAA+C;CAClF,MAAM,WAA6B,CAAC;CACpC,MAAM,QAAQ,QAAwC;EACpD,IAAI,CAAC,IAAI,KAAK,KAAK,GACjB;EACF,SAAS,KAAK;GAAE,GAAG;GAAK,QAAQ,eAAe,IAAI,IAAI;EAAE,CAAC;CAC5D;CAKA,MAAM,OAAO,MAAM,cAAc,MAAM,UAAU;CACjD,MAAM,aAAa,MAAM,eAAe,KAAA;CACxC,KAAK;EACH,IAAI;EACJ,OAAO;EAEP,QAAQ,aAAa,SAAS;EAC9B,QAAQ,aAAa,qCAAqC;EAC1D,MAAM,MAAM,aAAa,YAAY,MAAM,MAAM,UAAU,IAAI;EAC/D,GAAI,MAAM,eAAe,KAAA,IAAY,EAAE,MAAM,MAAM,WAAW,IAAI,CAAC;CACrE,CAAC;CAID,KAAK,MAAM,QAAQ,MAAM,cAAc,CAAC,GACtC,KAAK;EACH,IAAI,SAAS,KAAK;EAClB,OAAO,UAAU,KAAK,IAAI;EAC1B,QAAQ;EACR,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;EAC7C,MAAM,KAAK;EACX,MAAM,KAAK;CACb,CAAC;CAIH,KAAK;EACH,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,MAAM,MAAM,iBAAiB;CAC/B,CAAC;CACD,KAAK;EACH,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,QAAQ;EACR,MAAM,MAAM,mBAAmB;CACjC,CAAC;CACD,KAAK;EACH,IAAI;EACJ,OAAO;EACP,QAAQ;EACR,MAAM,MAAM,gBAAgB;CAC9B,CAAC;CAED,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { r as createStderrLineEmitter } from "./mcp-C6IkXNOS.js";
1
+ import { r as createStderrLineEmitter } from "./mcp-D9fqOQo5.js";
2
2
  import { Buffer } from "node:buffer";
3
3
  //#region src/mcp/context-transport.ts
4
4
  /**
@@ -10,7 +10,7 @@ import { Buffer } from "node:buffer";
10
10
  async function createContextStdioTransport(options) {
11
11
  const { name, context, handle, command, cwd, env, hooks } = options;
12
12
  if (!context.execStream) throw new Error(`MCP server "${name}" is configured with \`scope: 'context'\`, but the '${context.type}' execution context does not support live streams (\`execStream\`). Use \`scope: 'host'\` for this server, or switch to a context that advertises \`capabilities.stream\`.`);
13
- const { ReadBuffer, serializeMessage } = await import("./stdio-DzUUkkhS.js").then((n) => n.r);
13
+ const { ReadBuffer, serializeMessage } = await import("./stdio-DPpBDPx5.js").then((n) => n.r);
14
14
  const readBuffer = new ReadBuffer();
15
15
  let stream = null;
16
16
  let closed = false;
@@ -81,4 +81,4 @@ async function createContextStdioTransport(options) {
81
81
  //#endregion
82
82
  export { createContextStdioTransport };
83
83
 
84
- //# sourceMappingURL=context-transport-D-daWOmp.js.map
84
+ //# sourceMappingURL=context-transport-Bco9Wo0b.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-transport-D-daWOmp.js","names":[],"sources":["../src/mcp/context-transport.ts"],"sourcesContent":["/**\n * An MCP `Transport` that speaks stdio JSON-RPC to a server running INSIDE\n * an `ExecutionContext`, rather than as a child of the host process.\n *\n * Why this exists\n * ---------------\n * An MCP server is an ordinary program. When it calls `fs.readFileSync` or\n * `fs.writeFile`, those hit whatever filesystem it was spawned on. The\n * default `StdioClientTransport` spawns on the HOST, so with a sandboxed\n * execution context (Daytona / E2B / Docker) the agent's own tools and its\n * MCP servers end up looking at two different filesystems: a path the model\n * discovered via `list_files` does not exist for the MCP server, and an MCP\n * write lands somewhere `read_file` cannot see.\n *\n * Routing the server through `ExecutionContext.execStream` puts both on the\n * same filesystem. Note what this does NOT buy: isolation. Remote-transport\n * MCP servers are unreachable by this mechanism by construction, so\n * \"everything the agent touches runs in the execution context\" can never be\n * a true invariant. This is about coherence, not containment.\n *\n * Framing\n * -------\n * Delegated to the SDK's own `ReadBuffer` / `serializeMessage`, the exact\n * pair `StdioClientTransport` uses. That matters beyond code reuse:\n * `ReadBuffer` concatenates raw bytes and only decodes at newline\n * boundaries, so a multibyte codepoint split across two chunks survives.\n * Decoding each chunk independently would corrupt it irrecoverably — which\n * is precisely why `StreamHandle` carries bytes rather than strings.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { ExecutionContext, ExecutionHandle } from '../contexts/types'\nimport { Buffer } from 'node:buffer'\nimport { createStderrLineEmitter } from './index'\n\n/**\n * Structural subset of the MCP SDK's `Transport` that we implement. Declared\n * locally rather than imported as a type so this module keeps the optional\n * peer-dependency contract (see the note atop `./index.ts`) — the SDK is only\n * ever touched through a runtime `await import(...)`.\n */\nexport interface ContextStdioTransportLike {\n /**\n * Brand marking this transport's process as living OUTSIDE the host.\n * `stdioPidOf` keys off it to refuse handing any pid from here to\n * `killStdioChild`, which signals host pids: a sandbox pid like `77`\n * names a real, unrelated host process. Termination for this transport\n * goes through `StreamHandle.kill()`, which signals inside the context.\n */\n readonly __contextScoped: true\n start: () => Promise<void>\n send: (message: unknown) => Promise<void>\n close: () => Promise<void>\n onclose?: () => void\n onerror?: (error: Error) => void\n onmessage?: (message: unknown) => void\n}\n\nexport interface ContextStdioTransportOptions {\n /** Server name, used for `mcp:warn` attribution. */\n name: string\n context: ExecutionContext\n handle: ExecutionHandle\n /** Full command line, run through the context's shell. */\n command: string\n cwd?: string\n env?: Record<string, string>\n hooks?: Hookable<AgentHooks>\n}\n\n/**\n * Build the transport. Throws if the context can't stream — deliberately\n * loudly, because the alternative (quietly spawning on the host) would\n * reintroduce the split-filesystem bug this transport exists to fix, and\n * would do it invisibly.\n */\nexport async function createContextStdioTransport(\n options: ContextStdioTransportOptions,\n): Promise<ContextStdioTransportLike> {\n const { name, context, handle, command, cwd, env, hooks } = options\n\n if (!context.execStream) {\n throw new Error(\n `MCP server \"${name}\" is configured with \\`scope: 'context'\\`, but the `\n + `'${context.type}' execution context does not support live streams `\n + `(\\`execStream\\`). Use \\`scope: 'host'\\` for this server, or switch to a `\n + `context that advertises \\`capabilities.stream\\`.`,\n )\n }\n\n const { ReadBuffer, serializeMessage } = await import('@modelcontextprotocol/sdk/shared/stdio.js')\n\n const readBuffer = new ReadBuffer()\n let stream: Awaited<ReturnType<NonNullable<ExecutionContext['execStream']>>> | null = null\n let closed = false\n\n const transport: ContextStdioTransportLike = {\n __contextScoped: true,\n\n async start() {\n if (stream)\n throw new Error(`MCP context transport for \"${name}\" already started`)\n\n // cwd is defaulted HERE, not left to the context: process and docker\n // fall back to `handle.cwd` on their own, but the sandbox providers\n // forward `cwd` only when set, so their SDK default would win (E2B's\n // `/home/user`, Daytona's PTY login dir). A `scope: 'context'` server\n // without an explicit `cwd` — e.g. server-filesystem rooted at '.' —\n // would then serve the workspace on two contexts and the home\n // directory on the others: the exact silent path divergence this\n // transport exists to close. Redundant-but-harmless on contexts that\n // already default to `handle.cwd`.\n stream = await context.execStream!(handle, command, {\n cwd: cwd ?? handle.cwd,\n ...(env !== undefined ? { env } : {}),\n })\n\n const active = stream\n\n // stdout → framed JSON-RPC. Runs detached from `start()`; awaiting it\n // would never resolve, since the server lives as long as the session.\n void (async () => {\n try {\n for await (const chunk of active.stdout) {\n readBuffer.append(Buffer.from(chunk))\n for (;;) {\n // A malformed frame must not kill the pump: report it and keep\n // reading. Servers that interleave stray output with protocol\n // frames (a PTY-backed context that lost the `stty raw` race,\n // a server logging to stdout) would otherwise wedge the\n // connection permanently on the first bad line.\n let message: unknown\n try {\n message = readBuffer.readMessage()\n }\n catch (err) {\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n continue\n }\n if (message === null)\n break\n transport.onmessage?.(message)\n }\n }\n }\n catch (err) {\n if (!closed)\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n }\n })()\n\n // stderr → `mcp:warn`, when the context provides it separately. A\n // PTY-backed context cannot split it from the terminal stream, so it\n // redirects to a file and may surface it here out-of-band (Daytona\n // polls) or not at all — absence is expected, not an error.\n if (active.stderr) {\n const emitter = createStderrLineEmitter(name, hooks)\n // Streaming decoder for the same reason `ReadBuffer` exists on the\n // stdout side: a per-chunk decode corrupts any multibyte codepoint\n // split across a chunk boundary. Diagnostic-only here, but free to\n // get right.\n const decoder = new TextDecoder('utf-8')\n void (async () => {\n try {\n for await (const chunk of active.stderr!)\n emitter.push(decoder.decode(chunk, { stream: true }))\n }\n catch {\n // Diagnostic channel — a failure here must not surface as a\n // protocol error.\n }\n finally {\n emitter.push(decoder.decode())\n emitter.flush()\n }\n })()\n }\n\n // The child dying is the connection ending. Surface it once.\n void active.exited.then(() => {\n if (closed)\n return\n closed = true\n transport.onclose?.()\n })\n },\n\n async send(message: unknown) {\n if (!stream)\n throw new Error(`MCP context transport for \"${name}\" not started`)\n await stream.write(new TextEncoder().encode(serializeMessage(message as never)))\n },\n\n async close() {\n if (closed) {\n // Still ensure the child is gone: `closed` may have been set by the\n // exit watcher, but an explicit close after a half-dead stream\n // should not leave a process running in the sandbox.\n await stream?.kill()\n return\n }\n closed = true\n readBuffer.clear()\n await stream?.kill()\n transport.onclose?.()\n },\n }\n\n return transport\n}\n"],"mappings":";;;;;;;;;AA6EA,eAAsB,4BACpB,SACoC;CACpC,MAAM,EAAE,MAAM,SAAS,QAAQ,SAAS,KAAK,KAAK,UAAU;CAE5D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,eAAe,KAAK,sDACd,QAAQ,KAAK,2KAGrB;CAGF,MAAM,EAAE,YAAY,qBAAqB,MAAM,OAAO,sBAA4C,CAAA,MAAA,MAAA,EAAA,CAAA;CAElG,MAAM,aAAa,IAAI,WAAW;CAClC,IAAI,SAAkF;CACtF,IAAI,SAAS;CAEb,MAAM,YAAuC;EAC3C,iBAAiB;EAEjB,MAAM,QAAQ;GACZ,IAAI,QACF,MAAM,IAAI,MAAM,8BAA8B,KAAK,kBAAkB;GAWvE,SAAS,MAAM,QAAQ,WAAY,QAAQ,SAAS;IAClD,KAAK,OAAO,OAAO;IACnB,GAAI,QAAQ,KAAA,IAAY,EAAE,IAAI,IAAI,CAAC;GAC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CACF;CAEA,OAAO;AACT"}
1
+ {"version":3,"file":"context-transport-Bco9Wo0b.js","names":[],"sources":["../src/mcp/context-transport.ts"],"sourcesContent":["/**\n * An MCP `Transport` that speaks stdio JSON-RPC to a server running INSIDE\n * an `ExecutionContext`, rather than as a child of the host process.\n *\n * Why this exists\n * ---------------\n * An MCP server is an ordinary program. When it calls `fs.readFileSync` or\n * `fs.writeFile`, those hit whatever filesystem it was spawned on. The\n * default `StdioClientTransport` spawns on the HOST, so with a sandboxed\n * execution context (Daytona / E2B / Docker) the agent's own tools and its\n * MCP servers end up looking at two different filesystems: a path the model\n * discovered via `list_files` does not exist for the MCP server, and an MCP\n * write lands somewhere `read_file` cannot see.\n *\n * Routing the server through `ExecutionContext.execStream` puts both on the\n * same filesystem. Note what this does NOT buy: isolation. Remote-transport\n * MCP servers are unreachable by this mechanism by construction, so\n * \"everything the agent touches runs in the execution context\" can never be\n * a true invariant. This is about coherence, not containment.\n *\n * Framing\n * -------\n * Delegated to the SDK's own `ReadBuffer` / `serializeMessage`, the exact\n * pair `StdioClientTransport` uses. That matters beyond code reuse:\n * `ReadBuffer` concatenates raw bytes and only decodes at newline\n * boundaries, so a multibyte codepoint split across two chunks survives.\n * Decoding each chunk independently would corrupt it irrecoverably — which\n * is precisely why `StreamHandle` carries bytes rather than strings.\n */\n\nimport type { Hookable } from 'hookable'\nimport type { AgentHooks } from '../agent'\nimport type { ExecutionContext, ExecutionHandle } from '../contexts/types'\nimport { Buffer } from 'node:buffer'\nimport { createStderrLineEmitter } from './index'\n\n/**\n * Structural subset of the MCP SDK's `Transport` that we implement. Declared\n * locally rather than imported as a type so this module keeps the optional\n * peer-dependency contract (see the note atop `./index.ts`) — the SDK is only\n * ever touched through a runtime `await import(...)`.\n */\nexport interface ContextStdioTransportLike {\n /**\n * Brand marking this transport's process as living OUTSIDE the host.\n * `stdioPidOf` keys off it to refuse handing any pid from here to\n * `killStdioChild`, which signals host pids: a sandbox pid like `77`\n * names a real, unrelated host process. Termination for this transport\n * goes through `StreamHandle.kill()`, which signals inside the context.\n */\n readonly __contextScoped: true\n start: () => Promise<void>\n send: (message: unknown) => Promise<void>\n close: () => Promise<void>\n onclose?: () => void\n onerror?: (error: Error) => void\n onmessage?: (message: unknown) => void\n}\n\nexport interface ContextStdioTransportOptions {\n /** Server name, used for `mcp:warn` attribution. */\n name: string\n context: ExecutionContext\n handle: ExecutionHandle\n /** Full command line, run through the context's shell. */\n command: string\n cwd?: string\n env?: Record<string, string>\n hooks?: Hookable<AgentHooks>\n}\n\n/**\n * Build the transport. Throws if the context can't stream — deliberately\n * loudly, because the alternative (quietly spawning on the host) would\n * reintroduce the split-filesystem bug this transport exists to fix, and\n * would do it invisibly.\n */\nexport async function createContextStdioTransport(\n options: ContextStdioTransportOptions,\n): Promise<ContextStdioTransportLike> {\n const { name, context, handle, command, cwd, env, hooks } = options\n\n if (!context.execStream) {\n throw new Error(\n `MCP server \"${name}\" is configured with \\`scope: 'context'\\`, but the `\n + `'${context.type}' execution context does not support live streams `\n + `(\\`execStream\\`). Use \\`scope: 'host'\\` for this server, or switch to a `\n + `context that advertises \\`capabilities.stream\\`.`,\n )\n }\n\n const { ReadBuffer, serializeMessage } = await import('@modelcontextprotocol/sdk/shared/stdio.js')\n\n const readBuffer = new ReadBuffer()\n let stream: Awaited<ReturnType<NonNullable<ExecutionContext['execStream']>>> | null = null\n let closed = false\n\n const transport: ContextStdioTransportLike = {\n __contextScoped: true,\n\n async start() {\n if (stream)\n throw new Error(`MCP context transport for \"${name}\" already started`)\n\n // cwd is defaulted HERE, not left to the context: process and docker\n // fall back to `handle.cwd` on their own, but the sandbox providers\n // forward `cwd` only when set, so their SDK default would win (E2B's\n // `/home/user`, Daytona's PTY login dir). A `scope: 'context'` server\n // without an explicit `cwd` — e.g. server-filesystem rooted at '.' —\n // would then serve the workspace on two contexts and the home\n // directory on the others: the exact silent path divergence this\n // transport exists to close. Redundant-but-harmless on contexts that\n // already default to `handle.cwd`.\n stream = await context.execStream!(handle, command, {\n cwd: cwd ?? handle.cwd,\n ...(env !== undefined ? { env } : {}),\n })\n\n const active = stream\n\n // stdout → framed JSON-RPC. Runs detached from `start()`; awaiting it\n // would never resolve, since the server lives as long as the session.\n void (async () => {\n try {\n for await (const chunk of active.stdout) {\n readBuffer.append(Buffer.from(chunk))\n for (;;) {\n // A malformed frame must not kill the pump: report it and keep\n // reading. Servers that interleave stray output with protocol\n // frames (a PTY-backed context that lost the `stty raw` race,\n // a server logging to stdout) would otherwise wedge the\n // connection permanently on the first bad line.\n let message: unknown\n try {\n message = readBuffer.readMessage()\n }\n catch (err) {\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n continue\n }\n if (message === null)\n break\n transport.onmessage?.(message)\n }\n }\n }\n catch (err) {\n if (!closed)\n transport.onerror?.(err instanceof Error ? err : new Error(String(err)))\n }\n })()\n\n // stderr → `mcp:warn`, when the context provides it separately. A\n // PTY-backed context cannot split it from the terminal stream, so it\n // redirects to a file and may surface it here out-of-band (Daytona\n // polls) or not at all — absence is expected, not an error.\n if (active.stderr) {\n const emitter = createStderrLineEmitter(name, hooks)\n // Streaming decoder for the same reason `ReadBuffer` exists on the\n // stdout side: a per-chunk decode corrupts any multibyte codepoint\n // split across a chunk boundary. Diagnostic-only here, but free to\n // get right.\n const decoder = new TextDecoder('utf-8')\n void (async () => {\n try {\n for await (const chunk of active.stderr!)\n emitter.push(decoder.decode(chunk, { stream: true }))\n }\n catch {\n // Diagnostic channel — a failure here must not surface as a\n // protocol error.\n }\n finally {\n emitter.push(decoder.decode())\n emitter.flush()\n }\n })()\n }\n\n // The child dying is the connection ending. Surface it once.\n void active.exited.then(() => {\n if (closed)\n return\n closed = true\n transport.onclose?.()\n })\n },\n\n async send(message: unknown) {\n if (!stream)\n throw new Error(`MCP context transport for \"${name}\" not started`)\n await stream.write(new TextEncoder().encode(serializeMessage(message as never)))\n },\n\n async close() {\n if (closed) {\n // Still ensure the child is gone: `closed` may have been set by the\n // exit watcher, but an explicit close after a half-dead stream\n // should not leave a process running in the sandbox.\n await stream?.kill()\n return\n }\n closed = true\n readBuffer.clear()\n await stream?.kill()\n transport.onclose?.()\n },\n }\n\n return transport\n}\n"],"mappings":";;;;;;;;;AA6EA,eAAsB,4BACpB,SACoC;CACpC,MAAM,EAAE,MAAM,SAAS,QAAQ,SAAS,KAAK,KAAK,UAAU;CAE5D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,eAAe,KAAK,sDACd,QAAQ,KAAK,2KAGrB;CAGF,MAAM,EAAE,YAAY,qBAAqB,MAAM,OAAO,sBAA4C,CAAA,MAAA,MAAA,EAAA,CAAA;CAElG,MAAM,aAAa,IAAI,WAAW;CAClC,IAAI,SAAkF;CACtF,IAAI,SAAS;CAEb,MAAM,YAAuC;EAC3C,iBAAiB;EAEjB,MAAM,QAAQ;GACZ,IAAI,QACF,MAAM,IAAI,MAAM,8BAA8B,KAAK,kBAAkB;GAWvE,SAAS,MAAM,QAAQ,WAAY,QAAQ,SAAS;IAClD,KAAK,OAAO,OAAO;IACnB,GAAI,QAAQ,KAAA,IAAY,EAAE,IAAI,IAAI,CAAC;GACrC,CAAC;GAED,MAAM,SAAS;GAIf,CAAM,YAAY;IAChB,IAAI;KACF,WAAW,MAAM,SAAS,OAAO,QAAQ;MACvC,WAAW,OAAO,OAAO,KAAK,KAAK,CAAC;MACpC,SAAS;OAMP,IAAI;OACJ,IAAI;QACF,UAAU,WAAW,YAAY;OACnC,SACO,KAAK;QACV,UAAU,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;QACvE;OACF;OACA,IAAI,YAAY,MACd;OACF,UAAU,YAAY,OAAO;MAC/B;KACF;IACF,SACO,KAAK;KACV,IAAI,CAAC,QACH,UAAU,UAAU,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;IAC3E;GACF,EAAA,CAAG;GAMH,IAAI,OAAO,QAAQ;IACjB,MAAM,UAAU,wBAAwB,MAAM,KAAK;IAKnD,MAAM,UAAU,IAAI,YAAY,OAAO;IACvC,CAAM,YAAY;KAChB,IAAI;MACF,WAAW,MAAM,SAAS,OAAO,QAC/B,QAAQ,KAAK,QAAQ,OAAO,OAAO,EAAE,QAAQ,KAAK,CAAC,CAAC;KACxD,QACM,CAGN,UACQ;MACN,QAAQ,KAAK,QAAQ,OAAO,CAAC;MAC7B,QAAQ,MAAM;KAChB;IACF,EAAA,CAAG;GACL;GAGA,OAAY,OAAO,WAAW;IAC5B,IAAI,QACF;IACF,SAAS;IACT,UAAU,UAAU;GACtB,CAAC;EACH;EAEA,MAAM,KAAK,SAAkB;GAC3B,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,8BAA8B,KAAK,cAAc;GACnE,MAAM,OAAO,MAAM,IAAI,YAAY,CAAC,CAAC,OAAO,iBAAiB,OAAgB,CAAC,CAAC;EACjF;EAEA,MAAM,QAAQ;GACZ,IAAI,QAAQ;IAIV,MAAM,QAAQ,KAAK;IACnB;GACF;GACA,SAAS;GACT,WAAW,MAAM;GACjB,MAAM,QAAQ,KAAK;GACnB,UAAU,UAAU;EACtB;CACF;CAEA,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { Wu as Logger } from "../index-CWBSrqI6.js";
1
+ import { Wu as Logger } from "../index-BKyWhILQ.js";
2
2
  import { s as ExecResult } from "../types-M2DauK2D.js";
3
3
  import { t as SandboxProvider } from "../sandbox-DLY6uah7.js";
4
4
  import { Buffer } from "node:buffer";
@@ -1 +1 @@
1
- {"version":3,"file":"daytona.d.ts","names":[],"sources":["../../src/contexts/daytona.ts"],"mappings":";;;;;;UA+BU,sBAAA;EACR,QAAA;EACA,MAAA;EACA,MAAA;EACA,MAAA;EACA,MAAA;EACA,SAAA;IAAc,MAAA;EAAA;AAAA;AAAA,UAGN,gBAAA;EACR,IAAA;EAmByB;EAjBzB,KAAK;AAAA;;;;;;;;;UAWG,gBAAA;EACR,GAAA;EACA,iBAAA,QAAyB,OAAA;EACzB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ExecOutput } from "../output-cap-C9zukcCj.js";
2
+ import { u as errorMessage } from "../errors-BwBxu3zD.js";
2
3
  import { r as createLogger, t as consoleSink } from "../logger-DBX9uYOw.js";
3
4
  import { t as StreamQueue } from "../stream-queue-Cd9OJxl7.js";
4
5
  import { Buffer } from "node:buffer";
@@ -139,8 +140,10 @@ function createDaytonaProvider(options = {}) {
139
140
  async function loadSdk() {
140
141
  try {
141
142
  return (await import("@daytona/sdk")).Daytona;
142
- } catch {
143
- throw new Error("@daytona/sdk is required for the Daytona sandbox provider. Install it with: bun add @daytona/sdk");
143
+ } catch (err) {
144
+ const message = errorMessage(err);
145
+ const notInstalled = /cannot find (?:module|package)|module not found|failed to resolve/i.test(message);
146
+ throw new Error(notInstalled ? "@daytona/sdk is required for the Daytona sandbox provider. Install it with: bun add @daytona/sdk" : `@daytona/sdk is installed but failed to load: ${message}. If this mentions tslib, pin it with a root override: "overrides": { "tslib": "^2.8.1" } — see docs/RESTATE.md.`, { cause: err });
144
147
  }
145
148
  }
146
149
  function get(sandboxId) {
@@ -1 +1 @@
1
- {"version":3,"file":"daytona.js","names":[],"sources":["../../src/contexts/daytona.ts"],"sourcesContent":["/**\n * Daytona sandbox provider.\n *\n * Implements {@link SandboxProvider} on top of Daytona sandboxes. Pair it with\n * {@link createSandboxContext} to run an agent's shell + filesystem tools\n * inside a Daytona sandbox:\n *\n * ```ts\n * import { createSandboxContext } from 'zidane/contexts'\n * import { createDaytonaProvider } from 'zidane/contexts/daytona'\n *\n * const execution = createSandboxContext(createDaytonaProvider())\n * ```\n *\n * Requires `@daytona/sdk` as an optional peer dependency:\n * `bun add @daytona/sdk`.\n */\n\nimport type { Logger } from '../logger'\nimport type { SandboxProvider } from './sandbox'\nimport type { ExecResult, SpawnConfig, StreamHandle } from './types'\nimport { Buffer } from 'node:buffer'\nimport { consoleSink, createLogger } from '../logger'\nimport { capBufferedExecOutput } from './output-cap'\nimport { StreamQueue } from './stream-queue'\n\n// ---------------------------------------------------------------------------\n// Minimal structural views of the `@daytona/sdk` surface we touch. Declared\n// locally so zidane typechecks without the optional peer dependency installed.\n// ---------------------------------------------------------------------------\n\ninterface DaytonaExecuteResponse {\n exitCode?: number | null\n result?: string | null\n output?: string | null\n stdout?: string | null\n stderr?: string | null\n artifacts?: { stdout?: string | null }\n}\n\ninterface DaytonaFileEntry {\n name: string\n /** Present in the Daytona SDK's FileInfo; used for the `/` dir suffix. */\n isDir?: boolean\n}\n\n/**\n * Structural subset of Daytona's `PtyHandle`.\n *\n * Daytona's process/session API has NO stdin channel at all — sessions are\n * fire-and-forget with log streaming — so a PTY is the only way to reach a\n * long-lived process interactively. See the `execStream` implementation for\n * what that costs.\n */\ninterface DaytonaPtyHandle {\n pid?: number\n waitForConnection: () => Promise<unknown>\n sendInput: (data: string | Uint8Array) => Promise<unknown>\n wait: () => Promise<{ exitCode?: number }>\n kill?: () => Promise<unknown>\n disconnect: () => Promise<unknown>\n}\n\ninterface DaytonaSandbox {\n id: string\n state?: string\n process: {\n executeCommand: (command: string, cwd?: string, env?: Record<string, string>, timeout?: number) => Promise<DaytonaExecuteResponse>\n /** Present in recent SDKs; only `execStream` uses it. */\n createPty?: (options: {\n /**\n * REQUIRED by the API despite reading like a convenience handle: the\n * SDK forwards it as the session id and the control plane rejects the\n * create with 400 `session ID is required` when it is absent.\n */\n id: string\n cwd?: string\n envs?: Record<string, string>\n onData?: (data: Uint8Array) => void\n }) => Promise<DaytonaPtyHandle>\n }\n fs: {\n downloadFile: (path: string) => Promise<Uint8Array | ArrayBuffer | { toString: (encoding?: BufferEncoding) => string }>\n uploadFile: (content: Uint8Array | Buffer, path: string) => Promise<unknown>\n listFiles: (path: string) => Promise<DaytonaFileEntry[]>\n }\n getWorkDir?: () => Promise<string>\n start?: (timeout?: number) => Promise<unknown>\n delete: (timeout?: number) => Promise<unknown>\n stop?: (timeout?: number) => Promise<unknown>\n archive?: () => Promise<unknown>\n}\n\ninterface DaytonaClientConfig {\n apiKey?: string\n apiUrl?: string\n target?: string\n}\n\ninterface DaytonaResources {\n cpu?: number\n memory?: number\n disk?: number\n gpu?: number\n [key: string]: unknown\n}\n\ninterface DaytonaCreateParams {\n language?: string\n snapshot?: string\n image?: unknown\n resources?: DaytonaResources\n envVars?: Record<string, string>\n [key: string]: unknown\n}\n\ninterface DaytonaClient {\n create: (params?: DaytonaCreateParams) => Promise<DaytonaSandbox>\n get: (sandboxIdOrName: string) => Promise<DaytonaSandbox>\n}\n\ntype DaytonaConstructor = new (config?: DaytonaClientConfig) => DaytonaClient\n\n// ---------------------------------------------------------------------------\n// Provider options\n// ---------------------------------------------------------------------------\n\nexport type DaytonaOnDestroy = 'delete' | 'kill' | 'stop' | 'pause' | 'archive' | 'leave'\n\nexport interface DaytonaProviderOptions {\n /** Daytona API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n apiKey?: string\n /** Daytona API URL. Falls back to `DAYTONA_API_URL`, then Daytona's hosted default. */\n apiUrl?: string\n /** Daytona target / region. Falls back to `DAYTONA_TARGET`, then the org default. */\n target?: string\n /**\n * Attach to a pre-existing sandbox by id or name instead of creating a fresh\n * one. By default the provider treats attached sandboxes as externally owned\n * and leaves them running on destroy/failure (set {@link ownAttached} to take\n * over the lifecycle).\n */\n sandboxId?: string\n /**\n * Take ownership of an attached ({@link sandboxId}) sandbox's lifecycle, so\n * `destroy()` applies {@link onDestroy} to it (stop / archive / delete)\n * instead of leaving it running.\n *\n * The intended caller is a durable host that *owns* the sandbox across\n * invocations: mint it once, journal its id, re-attach via `sandboxId` on\n * every replay/resume, and clean it up at the end of the logical run. Without\n * this an attached sandbox can never be stopped/deleted through the provider —\n * a leak for host-owned sandboxes. No effect when creating a fresh sandbox\n * (those are always owned). Spawn-time failures (readiness timeout, pregame\n * error) still never delete a pre-existing attached sandbox — only sandboxes\n * this provider *created* are auto-cleaned on spawn failure.\n *\n * Default: `false`.\n */\n ownAttached?: boolean\n /** Daytona snapshot used when creating a fresh sandbox. */\n snapshot?: string\n /** Runtime used for Daytona's code tooling. Shell execution works either way. */\n language?: string\n /** Daytona image/declarative builder input used when creating a fresh sandbox. */\n image?: unknown\n /** Daytona sandbox resources. */\n resources?: DaytonaResources\n /** Default working directory, applied when a spawn doesn't set `SpawnConfig.cwd`. */\n cwd?: string\n /** Environment variables baked into the sandbox and re-sent on every command. */\n env?: Record<string, string>\n /** Logger for provider-level lifecycle lines. */\n logger?: Logger\n /** Total deadline, in seconds, for the post-create readiness probe. Defaults to `60`. */\n readinessTimeoutSeconds?: number\n /** Setup script to upload and run once the sandbox is ready. */\n pregame?: { name: string, content: string }\n /**\n * What to do with an owned sandbox on destroy:\n *\n * - `'delete'` / `'kill'` (default) — call `sandbox.delete()`.\n * - `'stop'` / `'pause'` — call `sandbox.stop()` so Daytona preserves state\n * according to the runner's stop semantics.\n * - `'archive'` — stop, then archive for longer-term persistence.\n * - `'leave'` — make no API call.\n */\n onDestroy?: DaytonaOnDestroy\n}\n\n/** Per-probe timeout for the readiness `true` command. */\nconst READINESS_PROBE_TIMEOUT_SECONDS = 5\n/** Pause between readiness probes while the sandbox is still warming up. */\nconst READINESS_BACKOFF_MS = 250\n/** Setup scripts commonly install dependencies, so give them a generous cap. */\nconst PREGAME_TIMEOUT_SECONDS = 30 * 60\n\nexport interface DaytonaReadinessOptions {\n /** Total deadline in seconds. `<= 0` disables the probe entirely. */\n timeoutSeconds: number\n /** Optional cleanup for owned sandboxes that never become ready. */\n cleanupOnTimeout?: () => Promise<void>\n /** Clock source — injectable for deterministic tests. */\n now?: () => number\n /** Sleep between probes — injectable for deterministic tests. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport function resolveDaytonaEnv(\n optionEnv: Record<string, string> | undefined,\n perSpawnEnv: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n const merged = { ...optionEnv, ...perSpawnEnv }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nexport function normalizeDaytonaExecResult(response: DaytonaExecuteResponse): ExecResult {\n return {\n stdout: response.stdout ?? response.artifacts?.stdout ?? response.result ?? response.output ?? '',\n stderr: response.stderr ?? '',\n exitCode: typeof response.exitCode === 'number' ? response.exitCode : 0,\n }\n}\n\nfunction capExecResult(result: ExecResult): ExecResult {\n return { ...capBufferedExecOutput(result.stdout, result.stderr), exitCode: result.exitCode }\n}\n\nfunction normalizeDaytonaExecError(error: unknown): ExecResult {\n const err = error as { exitCode?: unknown, stdout?: unknown, stderr?: unknown, result?: unknown, output?: unknown, message?: unknown }\n if (typeof err.exitCode === 'number') {\n return {\n stdout: typeof err.stdout === 'string'\n ? err.stdout\n : typeof err.result === 'string'\n ? err.result\n : typeof err.output === 'string'\n ? err.output\n : '',\n stderr: typeof err.stderr === 'string' ? err.stderr : typeof err.message === 'string' ? err.message : '',\n exitCode: err.exitCode,\n }\n }\n return { stdout: '', stderr: error instanceof Error ? error.message : String(error), exitCode: 124 }\n}\n\nfunction bufferToString(value: Uint8Array | ArrayBuffer | { toString: (encoding?: BufferEncoding) => string }): string {\n if (Buffer.isBuffer(value))\n return value.toString('utf8')\n if (value instanceof ArrayBuffer)\n return new TextDecoder().decode(new Uint8Array(value))\n if (value instanceof Uint8Array)\n return new TextDecoder().decode(value)\n return value.toString('utf8')\n}\n\nfunction toClientConfig(apiKey?: string, apiUrl?: string, target?: string): DaytonaClientConfig | undefined {\n const config: DaytonaClientConfig = {}\n if (apiKey !== undefined)\n config.apiKey = apiKey\n if (apiUrl !== undefined)\n config.apiUrl = apiUrl\n if (target !== undefined)\n config.target = target\n return Object.keys(config).length > 0 ? config : undefined\n}\n\nfunction takeString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nexport function resolveDaytonaCreateParams(\n sandboxConfig: Record<string, unknown>,\n options: DaytonaProviderOptions,\n envVars: Record<string, string> | undefined,\n): DaytonaCreateParams | undefined {\n const reserved = new Set(['provider', 'apiKey', 'apiUrl', 'target', 'sandboxId'])\n const params: DaytonaCreateParams = {}\n\n for (const [key, value] of Object.entries(sandboxConfig)) {\n if (!reserved.has(key) && value !== undefined)\n params[key] = value\n }\n\n const language = takeString(sandboxConfig.language) ?? options.language\n const snapshot = takeString(sandboxConfig.snapshot) ?? options.snapshot\n const image = sandboxConfig.image ?? options.image\n const resources = (sandboxConfig.resources as DaytonaResources | undefined) ?? options.resources\n const configEnvVars = sandboxConfig.envVars as Record<string, string> | undefined\n const mergedEnvVars = resolveDaytonaEnv(envVars, configEnvVars)\n\n if (language !== undefined)\n params.language = language\n if (snapshot !== undefined)\n params.snapshot = snapshot\n if (image !== undefined)\n params.image = image\n if (resources !== undefined)\n params.resources = resources\n if (mergedEnvVars !== undefined)\n params.envVars = mergedEnvVars\n\n return Object.keys(params).length > 0 ? params : undefined\n}\n\nexport async function waitForDaytonaReady(\n sandbox: DaytonaSandbox,\n logger: Logger,\n opts: DaytonaReadinessOptions,\n): Promise<void> {\n if (opts.timeoutSeconds <= 0)\n return\n\n const now = opts.now ?? Date.now\n const sleep = opts.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)))\n const start = now()\n const deadline = start + opts.timeoutSeconds * 1000\n\n logger.info('waiting for Daytona sandbox to initialize', { sandboxId: sandbox.id })\n\n while (true) {\n try {\n await sandbox.process.executeCommand('true', undefined, undefined, READINESS_PROBE_TIMEOUT_SECONDS)\n logger.info('Daytona sandbox ready', { sandboxId: sandbox.id, elapsedMs: now() - start })\n return\n }\n catch {\n if (now() >= deadline) {\n await opts.cleanupOnTimeout?.().catch(() => {})\n throw new Error(`Daytona sandbox ${sandbox.id} did not become ready within ${opts.timeoutSeconds}s`)\n }\n await sleep(READINESS_BACKOFF_MS)\n }\n }\n}\n\nexport async function runDaytonaPregame(\n sandbox: DaytonaSandbox,\n logger: Logger,\n opts: { name: string, content: string, cwd?: string, envVars?: Record<string, string> },\n): Promise<void> {\n const path = `/tmp/${opts.name}`\n logger.info('running Daytona pregame script', { sandboxId: sandbox.id, path })\n await sandbox.fs.uploadFile(Buffer.from(opts.content), path)\n\n const quoted = JSON.stringify(path)\n let result: ExecResult\n try {\n result = normalizeDaytonaExecResult(\n await sandbox.process.executeCommand(`chmod +x ${quoted} && ${quoted}`, opts.cwd, opts.envVars, PREGAME_TIMEOUT_SECONDS),\n )\n }\n catch (err) {\n result = normalizeDaytonaExecError(err)\n }\n\n if (result.exitCode !== 0) {\n logger.error('Daytona pregame script failed', { sandboxId: sandbox.id, exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr })\n throw new Error(`Daytona pregame script ${opts.name} failed with exit code ${result.exitCode}`)\n }\n\n logger.info('Daytona pregame ready', { sandboxId: sandbox.id, stdout: result.stdout, stderr: result.stderr })\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport function createDaytonaProvider(options: DaytonaProviderOptions = {}): SandboxProvider {\n const live = new Map<string, { sandbox: DaytonaSandbox, env?: Record<string, string>, owned: boolean }>()\n const logger = options.logger ?? createLogger(consoleSink())\n const readinessTimeoutSeconds = options.readinessTimeoutSeconds ?? 60\n\n async function loadSdk(): Promise<DaytonaConstructor> {\n try {\n const mod = await import('@daytona/sdk') as { Daytona: DaytonaConstructor }\n return mod.Daytona\n }\n catch {\n throw new Error('@daytona/sdk is required for the Daytona sandbox provider. Install it with: bun add @daytona/sdk')\n }\n }\n\n function get(sandboxId: string): { sandbox: DaytonaSandbox, env?: Record<string, string>, owned: boolean } {\n const entry = live.get(sandboxId)\n if (!entry)\n throw new Error(`Daytona sandbox ${sandboxId} is not tracked by this provider`)\n return entry\n }\n\n async function deleteOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n try {\n await sandbox.delete()\n }\n catch {\n // Already gone — nothing to clean up.\n }\n }\n\n async function stopOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n if (!sandbox.stop) {\n logger.error('cannot stop Daytona sandbox: this @daytona/sdk install exposes no stop() method; leaving it running', { sandboxId: sandbox.id })\n return\n }\n try {\n await sandbox.stop()\n logger.info('stopped Daytona sandbox; reconnect later via the sandboxId option (CLI: --sandbox)', { sandboxId: sandbox.id })\n }\n catch (err) {\n logger.error('failed to stop Daytona sandbox; it will run until Daytona lifecycle policy stops it', { sandboxId: sandbox.id, error: err instanceof Error ? err.message : String(err) })\n }\n }\n\n async function archiveOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n if (!sandbox.stop || !sandbox.archive) {\n logger.error('cannot archive Daytona sandbox: this @daytona/sdk install exposes no stop() and archive() pair; leaving it running', { sandboxId: sandbox.id })\n return\n }\n try {\n await sandbox.stop()\n await sandbox.archive()\n logger.info('archived Daytona sandbox; reconnect later via the sandboxId option (CLI: --sandbox)', { sandboxId: sandbox.id })\n }\n catch (err) {\n logger.error('failed to archive Daytona sandbox; it will run until Daytona lifecycle policy stops it', { sandboxId: sandbox.id, error: err instanceof Error ? err.message : String(err) })\n }\n }\n\n async function startAttachedSandboxIfNeeded(sandbox: DaytonaSandbox): Promise<void> {\n if (sandbox.state !== 'stopped' && sandbox.state !== 'archived')\n return\n if (!sandbox.start) {\n logger.error('cannot start Daytona sandbox before attach readiness probe: this @daytona/sdk install exposes no start() method', { sandboxId: sandbox.id, state: sandbox.state })\n return\n }\n logger.info('starting Daytona sandbox before attach readiness probe', { sandboxId: sandbox.id, state: sandbox.state })\n await sandbox.start(readinessTimeoutSeconds > 0 ? readinessTimeoutSeconds : undefined)\n }\n\n return {\n name: 'daytona',\n\n async spawn(config: SpawnConfig = {}): Promise<{ id: string, cwd: string }> {\n const Daytona = await loadSdk()\n const sb: Record<string, unknown> = config.sandbox ?? {}\n\n const apiKey = takeString(sb.apiKey) ?? options.apiKey\n const apiUrl = takeString(sb.apiUrl) ?? options.apiUrl\n const target = takeString(sb.target) ?? options.target\n const connectId = takeString(sb.sandboxId) ?? options.sandboxId\n const envVars = resolveDaytonaEnv(options.env, config.env)\n\n const daytona = new Daytona(toClientConfig(apiKey, apiUrl, target))\n const attached = connectId !== undefined\n // Lifecycle ownership drives `destroy()` (onDestroy). A created sandbox is\n // always owned; an attached one is owned only when the host opts in via\n // `ownAttached`. Spawn-FAILURE cleanup is separate (see below) and keyed\n // on `!attached` so a pre-existing sandbox is never auto-deleted.\n const owned = !attached || options.ownAttached === true\n const sandbox = attached\n ? await daytona.get(connectId)\n : await daytona.create(resolveDaytonaCreateParams(sb, options, envVars))\n\n if (attached)\n await startAttachedSandboxIfNeeded(sandbox)\n\n live.set(sandbox.id, { sandbox, env: envVars, owned })\n\n try {\n await waitForDaytonaReady(sandbox, logger, {\n timeoutSeconds: readinessTimeoutSeconds,\n // Only auto-delete a sandbox we CREATED on readiness failure — never a\n // pre-existing attached one, even when we own its lifecycle.\n ...(!attached ? { cleanupOnTimeout: () => deleteOwnedSandbox(sandbox) } : {}),\n })\n }\n catch (err) {\n live.delete(sandbox.id)\n throw err\n }\n\n const requestedCwd = config.cwd ?? options.cwd\n let cwd: string\n if (requestedCwd) {\n cwd = requestedCwd\n await sandbox.process.executeCommand(`mkdir -p ${JSON.stringify(cwd)}`).catch(() => {})\n }\n else if (sandbox.getWorkDir) {\n cwd = await sandbox.getWorkDir().catch(() => '')\n if (!cwd)\n cwd = await sandbox.process.executeCommand('pwd').then(r => normalizeDaytonaExecResult(r).stdout.trim()).catch(() => '') || '/home/daytona'\n }\n else {\n cwd = await sandbox.process.executeCommand('pwd').then(r => normalizeDaytonaExecResult(r).stdout.trim()).catch(() => '') || '/home/daytona'\n }\n\n if (options.pregame) {\n try {\n await runDaytonaPregame(sandbox, logger, { name: options.pregame.name, content: options.pregame.content, cwd, envVars })\n }\n catch (err) {\n // Spawn-failure cleanup: only delete a sandbox we created, never a\n // pre-existing attached one (the host owns its prior state).\n if (!attached)\n await deleteOwnedSandbox(sandbox)\n live.delete(sandbox.id)\n throw err\n }\n }\n\n return { id: sandbox.id, cwd }\n },\n\n async exec(sandboxId, command, opts): Promise<ExecResult> {\n const { sandbox, env } = get(sandboxId)\n const timeoutSeconds = opts?.timeout ?? 30\n try {\n // The SDK buffers the streams uncapped (see the KNOWN RESIDUAL note\n // on `ExecutionContext.fileSize`) — cap host-side before the strings\n // propagate into tool results and session history.\n return capExecResult(normalizeDaytonaExecResult(\n await sandbox.process.executeCommand(\n command,\n opts?.cwd,\n resolveDaytonaEnv(env, opts?.env),\n timeoutSeconds > 0 ? timeoutSeconds : undefined,\n ),\n ))\n }\n catch (err) {\n return capExecResult(normalizeDaytonaExecError(err))\n }\n },\n\n /**\n * Live bidirectional stream — see `ExecutionContext.execStream`.\n *\n * PTY-backed, and not by preference: Daytona's process + session API\n * exposes no stdin at all (sessions are fire-and-forget with log\n * streaming), so a pseudo-terminal is the only interactive channel the\n * platform offers. That forces three mitigations, all in the launch\n * wrapper below, because a PTY is a terminal and a protocol stream is\n * not:\n *\n * 1. `stty -echo` — a terminal echoes everything written to stdin back\n * onto stdout. Without this the caller reads its own requests back\n * as if they were responses.\n * 2. `stty raw` — canonical mode rewrites `\\n`→`\\r\\n` and caps a line\n * at ~4096 bytes. Protocol frames routinely exceed that and would\n * be silently truncated mid-message.\n * 3. `2><file>` — a PTY has ONE stream, so the child's stderr would\n * otherwise interleave into the protocol data and corrupt framing.\n * It is redirected to a file inside the sandbox and surfaced on the\n * returned handle by polling that file through the exec API.\n *\n * The mitigations must run before the child's first byte — but the\n * launch line ITSELF is typed into a canonical-mode terminal, so it is\n * echoed once (a short non-JSON line the transport's tolerant framing\n * discards) and subject to the ~4096-byte line cap. That is why the\n * real command lives in an uploaded script and the typed line stays\n * short and constant: a long command line would be truncated before\n * `stty` ever ran. The script also restores `sh` compound-command\n * semantics that a bare `exec <command>` would break.\n */\n async execStream(sandboxId, command, opts): Promise<StreamHandle> {\n const { sandbox, env } = get(sandboxId)\n\n if (!sandbox.process.createPty) {\n throw new Error(\n 'Daytona SDK is too old: `process.createPty` is required for execStream '\n + '(used to run stdio MCP servers inside the sandbox).',\n )\n }\n\n opts?.signal?.throwIfAborted()\n\n const token = Math.random().toString(36).slice(2, 10)\n const stderrPath = `/tmp/.zidane-stream-${token}.err`\n const scriptPath = `/tmp/.zidane-stream-${token}.sh`\n\n // `exec 2>` rebinds the shell's stderr before the command runs, so\n // the command text needs no rewriting and stays compound-safe.\n await sandbox.fs.uploadFile(\n Buffer.from(`exec 2>${stderrPath}\\n${command}\\n`),\n scriptPath,\n )\n\n // See the E2B counterpart: the PTY's `onData` is a sync `void`\n // callback, so a stalled consumer can only be reported, never slowed.\n const warnBacklog = (which: string) => (bytes: number) =>\n logger.warn('execStream consumer is not draining output', { sandboxId, stream: which, bufferedBytes: bytes })\n const stdout = new StreamQueue(warnBacklog('stdout'))\n const stderr = new StreamQueue(warnBacklog('stderr'))\n\n // Everything the shell emits before the child is actually running is\n // NOISE that must never reach the caller: the echo of our own launch\n // line (typed before `-echo` takes effect), the login shell's prompt,\n // and its line-editor redraw escapes. `createPty` is `lazyStart`, so\n // the shell frequently does not exist yet when we type — it boots\n // afterwards and REPLAYS the buffered input through its line editor.\n // Observed on a stock sandbox: the stream opened with the echoed\n // launch line, the echoed first request, `\\u001b[?2004h` bracketed\n // paste, and a `%` prompt. An MCP client parses that echoed request\n // as a message and the handshake collapses.\n //\n // So: gate the stream on a sentinel the CHILD side prints, and drop\n // every byte before it. The sentinel is assembled by `printf` at\n // runtime (`Z-%s-READY` + token) so the echoed *source* line, which\n // contains the format string rather than the result, cannot match it.\n const sentinel = `Z-${token}-READY`\n let gateOpen = false\n let gateBuffer = ''\n let openGate: () => void = () => {}\n const gateReady = new Promise<void>((r) => { openGate = r })\n\n const pty = await sandbox.process.createPty({\n id: `zidane-stream-${token}`,\n ...(opts?.cwd ? { cwd: opts.cwd } : {}),\n envs: resolveDaytonaEnv(env, opts?.env) ?? {},\n onData: (data: Uint8Array) => {\n if (gateOpen) {\n stdout.push(data)\n return\n }\n gateBuffer += Buffer.from(data).toString('utf8')\n const at = gateBuffer.indexOf(sentinel)\n if (at === -1) {\n // Bounded: never let pre-gate noise grow without limit, but keep\n // a tail longer than the sentinel so it can't be split away.\n if (gateBuffer.length > 64 * 1024)\n gateBuffer = gateBuffer.slice(-1024)\n return\n }\n gateOpen = true\n openGate()\n // Everything after the sentinel's trailing newline is real output.\n const rest = gateBuffer.slice(at + sentinel.length).replace(/^\\r?\\n/, '')\n gateBuffer = ''\n if (rest.length > 0)\n stdout.push(new TextEncoder().encode(rest))\n },\n })\n await pty.waitForConnection()\n\n // Short, constant, and under any canonical line cap. `exec` replaces\n // the login shell so the PTY's lifetime is the script's lifetime and\n // no shell prompt can reach stdout.\n await pty.sendInput(`stty raw -echo; printf 'Z-%s-READY\\\\n' ${token}; exec sh ${scriptPath}\\n`)\n\n // Block until the child is genuinely live. Without this the caller can\n // write its first frame into a shell that hasn't started, where it is\n // echoed back and misread as a response.\n let gateTimer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n gateReady,\n new Promise<void>((r) => { gateTimer = setTimeout(r, 30_000) }),\n ])\n clearTimeout(gateTimer)\n if (!gateOpen) {\n // Full teardown, not just a disconnect: Daytona PTY sessions persist\n // server-side after the websocket drops, so a bare disconnect leaks\n // one login shell plus two /tmp files per attempt — a bootstrap\n // retry loop against a broken image would stack them until the\n // sandbox dies.\n await (pty.kill?.() ?? Promise.resolve()).catch(() => {})\n await pty.disconnect().catch(() => {})\n await sandbox.process.executeCommand(`rm -f ${scriptPath} ${stderrPath}`).catch(() => {})\n throw new Error(\n `Daytona execStream: PTY did not reach the ready sentinel within 30s `\n + `(sandbox ${sandboxId}). The login shell may not have started.`,\n )\n }\n\n // stderr file → handle.stderr. Poll rather than stream: the exec API\n // is the only other channel into the sandbox, and diagnostics don't\n // need latency. Byte offsets keep re-reads incremental.\n //\n // The offset comes from the FILE (`wc -c`), never from measuring the\n // returned content: an exec API that trims a trailing newline from\n // command output would make a content-derived offset under-advance by\n // one byte per poll, re-emitting the tail byte forever. The size rides\n // back on the same round trip as a `ZEOF-<token>:` suffix; content is\n // whatever precedes it, so content-side transforms can't drift the\n // cursor either.\n let stderrOffset = 0\n let torndown = false\n const eofMark = `ZEOF-${token}:`\n const drainStderr = async (): Promise<void> => {\n try {\n const res = normalizeDaytonaExecResult(await sandbox.process.executeCommand(\n `tail -c +${stderrOffset + 1} ${stderrPath} 2>/dev/null; printf '${eofMark}%s' \"$(wc -c < ${stderrPath} 2>/dev/null || echo 0)\"`,\n ))\n const at = res.stdout.lastIndexOf(eofMark)\n if (at === -1)\n return\n const content = res.stdout.slice(0, at)\n const size = Number.parseInt(res.stdout.slice(at + eofMark.length).trim(), 10)\n if (content.length > 0)\n stderr.push(new TextEncoder().encode(content))\n if (Number.isFinite(size) && size > stderrOffset)\n stderrOffset = size\n }\n catch {\n // Diagnostic channel — polling failures must never surface as\n // protocol errors.\n }\n }\n const stderrTimer = setInterval(() => { void drainStderr() }, 2000)\n // Guarded: Bun/Node timers support unref, test fakes may not.\n ;(stderrTimer as { unref?: () => void }).unref?.()\n\n // Shared teardown for both exit paths (natural exit and kill): one\n // final stderr drain so a crash message isn't lost, then remove the\n // script + stderr files that would otherwise accumulate in /tmp for\n // the sandbox's lifetime.\n const teardown = async (): Promise<void> => {\n if (torndown)\n return\n torndown = true\n clearInterval(stderrTimer)\n await drainStderr()\n await sandbox.process.executeCommand(`rm -f ${scriptPath} ${stderrPath}`).catch(() => {})\n stdout.close()\n stderr.close()\n }\n\n const exited = pty.wait()\n .then(result => result?.exitCode ?? 0)\n .catch(() => 137)\n .finally(teardown)\n\n const kill = async (): Promise<void> => {\n // A PTY login shell never exits on its own — killing it IS the\n // normal termination path here, not an error path.\n await (pty.kill?.() ?? Promise.resolve()).catch(() => {})\n await pty.disconnect().catch(() => {})\n await teardown()\n }\n\n if (opts?.signal) {\n if (opts.signal.aborted) {\n void kill()\n }\n else {\n // Detach on exit — the (typically run-long) signal otherwise\n // retains the `kill` closure and the PTY handle for the rest of\n // the run, one dead closure per exec.\n const onAbort = () => { void kill() }\n const detach = () => opts.signal!.removeEventListener('abort', onAbort)\n opts.signal.addEventListener('abort', onAbort, { once: true })\n exited.then(detach, detach)\n }\n }\n\n return {\n pid: pty.pid ?? -1,\n stdout,\n stderr,\n write: async (data: Uint8Array): Promise<void> => {\n await pty.sendInput(data)\n },\n kill,\n exited,\n }\n },\n\n async readFile(sandboxId, path): Promise<string> {\n return bufferToString(await get(sandboxId).sandbox.fs.downloadFile(path))\n },\n\n async writeFile(sandboxId, path, content): Promise<void> {\n await get(sandboxId).sandbox.fs.uploadFile(Buffer.from(content), path)\n },\n\n async listFiles(sandboxId, path): Promise<string[]> {\n const entries = await get(sandboxId).sandbox.fs.listFiles(path)\n // Trailing `/` on directories — parity with process/docker contexts.\n return entries.map(e => (e.isDir ? `${e.name}/` : e.name))\n },\n\n async destroy(sandboxId): Promise<void> {\n const entry = live.get(sandboxId)\n if (!entry)\n return\n if (entry.owned) {\n const action = options.onDestroy ?? 'delete'\n if (action === 'stop' || action === 'pause')\n await stopOwnedSandbox(entry.sandbox)\n else if (action === 'archive')\n await archiveOwnedSandbox(entry.sandbox)\n else if (action === 'delete' || action === 'kill')\n await deleteOwnedSandbox(entry.sandbox)\n }\n live.delete(sandboxId)\n },\n }\n}\n"],"mappings":";;;;;;AA+LA,MAAM,kCAAkC;;AAExC,MAAM,uBAAuB;;AAE7B,MAAM,0BAA0B;AAahC,SAAgB,kBACd,WACA,aACoC;CACpC,MAAM,SAAS;EAAE,GAAG;EAAW,GAAG;CAAY;CAC9C,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS,KAAA;AACnD;AAEA,SAAgB,2BAA2B,UAA8C;CACvF,OAAO;EACL,QAAQ,SAAS,UAAU,SAAS,WAAW,UAAU,SAAS,UAAU,SAAS,UAAU;EAC/F,QAAQ,SAAS,UAAU;EAC3B,UAAU,OAAO,SAAS,aAAa,WAAW,SAAS,WAAW;CACxE;AACF;AAEA,SAAS,cAAc,QAAgC;CACrD,OAAO;EAAE,GAAG,sBAAsB,OAAO,QAAQ,OAAO,MAAM;EAAG,UAAU,OAAO;CAAS;AAC7F;AAEA,SAAS,0BAA0B,OAA4B;CAC7D,MAAM,MAAM;CACZ,IAAI,OAAO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,aAAa;IACpC,IAAI,WAAW,UAAU,WAAW,SAClC,MAAM,iBAAiB,MAAM,OAAO;SACjC,IAAI,WAAW,WAClB,MAAM,oBAAoB,MAAM,OAAO;SACpC,IAAI,WAAW,YAAY,WAAW,QACzC,MAAM,mBAAmB,MAAM,OAAO;GAC1C;GACA,KAAK,OAAO,SAAS;EACvB;CACF;AACF"}
1
+ {"version":3,"file":"daytona.js","names":[],"sources":["../../src/contexts/daytona.ts"],"sourcesContent":["/**\n * Daytona sandbox provider.\n *\n * Implements {@link SandboxProvider} on top of Daytona sandboxes. Pair it with\n * {@link createSandboxContext} to run an agent's shell + filesystem tools\n * inside a Daytona sandbox:\n *\n * ```ts\n * import { createSandboxContext } from 'zidane/contexts'\n * import { createDaytonaProvider } from 'zidane/contexts/daytona'\n *\n * const execution = createSandboxContext(createDaytonaProvider())\n * ```\n *\n * Requires `@daytona/sdk` as an optional peer dependency:\n * `bun add @daytona/sdk`.\n */\n\nimport type { Logger } from '../logger'\nimport type { SandboxProvider } from './sandbox'\nimport type { ExecResult, SpawnConfig, StreamHandle } from './types'\nimport { Buffer } from 'node:buffer'\nimport { errorMessage } from '../errors'\nimport { consoleSink, createLogger } from '../logger'\nimport { capBufferedExecOutput } from './output-cap'\nimport { StreamQueue } from './stream-queue'\n\n// ---------------------------------------------------------------------------\n// Minimal structural views of the `@daytona/sdk` surface we touch. Declared\n// locally so zidane typechecks without the optional peer dependency installed.\n// ---------------------------------------------------------------------------\n\ninterface DaytonaExecuteResponse {\n exitCode?: number | null\n result?: string | null\n output?: string | null\n stdout?: string | null\n stderr?: string | null\n artifacts?: { stdout?: string | null }\n}\n\ninterface DaytonaFileEntry {\n name: string\n /** Present in the Daytona SDK's FileInfo; used for the `/` dir suffix. */\n isDir?: boolean\n}\n\n/**\n * Structural subset of Daytona's `PtyHandle`.\n *\n * Daytona's process/session API has NO stdin channel at all — sessions are\n * fire-and-forget with log streaming — so a PTY is the only way to reach a\n * long-lived process interactively. See the `execStream` implementation for\n * what that costs.\n */\ninterface DaytonaPtyHandle {\n pid?: number\n waitForConnection: () => Promise<unknown>\n sendInput: (data: string | Uint8Array) => Promise<unknown>\n wait: () => Promise<{ exitCode?: number }>\n kill?: () => Promise<unknown>\n disconnect: () => Promise<unknown>\n}\n\ninterface DaytonaSandbox {\n id: string\n state?: string\n process: {\n executeCommand: (command: string, cwd?: string, env?: Record<string, string>, timeout?: number) => Promise<DaytonaExecuteResponse>\n /** Present in recent SDKs; only `execStream` uses it. */\n createPty?: (options: {\n /**\n * REQUIRED by the API despite reading like a convenience handle: the\n * SDK forwards it as the session id and the control plane rejects the\n * create with 400 `session ID is required` when it is absent.\n */\n id: string\n cwd?: string\n envs?: Record<string, string>\n onData?: (data: Uint8Array) => void\n }) => Promise<DaytonaPtyHandle>\n }\n fs: {\n downloadFile: (path: string) => Promise<Uint8Array | ArrayBuffer | { toString: (encoding?: BufferEncoding) => string }>\n uploadFile: (content: Uint8Array | Buffer, path: string) => Promise<unknown>\n listFiles: (path: string) => Promise<DaytonaFileEntry[]>\n }\n getWorkDir?: () => Promise<string>\n start?: (timeout?: number) => Promise<unknown>\n delete: (timeout?: number) => Promise<unknown>\n stop?: (timeout?: number) => Promise<unknown>\n archive?: () => Promise<unknown>\n}\n\ninterface DaytonaClientConfig {\n apiKey?: string\n apiUrl?: string\n target?: string\n}\n\ninterface DaytonaResources {\n cpu?: number\n memory?: number\n disk?: number\n gpu?: number\n [key: string]: unknown\n}\n\ninterface DaytonaCreateParams {\n language?: string\n snapshot?: string\n image?: unknown\n resources?: DaytonaResources\n envVars?: Record<string, string>\n [key: string]: unknown\n}\n\ninterface DaytonaClient {\n create: (params?: DaytonaCreateParams) => Promise<DaytonaSandbox>\n get: (sandboxIdOrName: string) => Promise<DaytonaSandbox>\n}\n\ntype DaytonaConstructor = new (config?: DaytonaClientConfig) => DaytonaClient\n\n// ---------------------------------------------------------------------------\n// Provider options\n// ---------------------------------------------------------------------------\n\nexport type DaytonaOnDestroy = 'delete' | 'kill' | 'stop' | 'pause' | 'archive' | 'leave'\n\nexport interface DaytonaProviderOptions {\n /** Daytona API key. Falls back to the `DAYTONA_API_KEY` env var when omitted. */\n apiKey?: string\n /** Daytona API URL. Falls back to `DAYTONA_API_URL`, then Daytona's hosted default. */\n apiUrl?: string\n /** Daytona target / region. Falls back to `DAYTONA_TARGET`, then the org default. */\n target?: string\n /**\n * Attach to a pre-existing sandbox by id or name instead of creating a fresh\n * one. By default the provider treats attached sandboxes as externally owned\n * and leaves them running on destroy/failure (set {@link ownAttached} to take\n * over the lifecycle).\n */\n sandboxId?: string\n /**\n * Take ownership of an attached ({@link sandboxId}) sandbox's lifecycle, so\n * `destroy()` applies {@link onDestroy} to it (stop / archive / delete)\n * instead of leaving it running.\n *\n * The intended caller is a durable host that *owns* the sandbox across\n * invocations: mint it once, journal its id, re-attach via `sandboxId` on\n * every replay/resume, and clean it up at the end of the logical run. Without\n * this an attached sandbox can never be stopped/deleted through the provider —\n * a leak for host-owned sandboxes. No effect when creating a fresh sandbox\n * (those are always owned). Spawn-time failures (readiness timeout, pregame\n * error) still never delete a pre-existing attached sandbox — only sandboxes\n * this provider *created* are auto-cleaned on spawn failure.\n *\n * Default: `false`.\n */\n ownAttached?: boolean\n /** Daytona snapshot used when creating a fresh sandbox. */\n snapshot?: string\n /** Runtime used for Daytona's code tooling. Shell execution works either way. */\n language?: string\n /** Daytona image/declarative builder input used when creating a fresh sandbox. */\n image?: unknown\n /** Daytona sandbox resources. */\n resources?: DaytonaResources\n /** Default working directory, applied when a spawn doesn't set `SpawnConfig.cwd`. */\n cwd?: string\n /** Environment variables baked into the sandbox and re-sent on every command. */\n env?: Record<string, string>\n /** Logger for provider-level lifecycle lines. */\n logger?: Logger\n /** Total deadline, in seconds, for the post-create readiness probe. Defaults to `60`. */\n readinessTimeoutSeconds?: number\n /** Setup script to upload and run once the sandbox is ready. */\n pregame?: { name: string, content: string }\n /**\n * What to do with an owned sandbox on destroy:\n *\n * - `'delete'` / `'kill'` (default) — call `sandbox.delete()`.\n * - `'stop'` / `'pause'` — call `sandbox.stop()` so Daytona preserves state\n * according to the runner's stop semantics.\n * - `'archive'` — stop, then archive for longer-term persistence.\n * - `'leave'` — make no API call.\n */\n onDestroy?: DaytonaOnDestroy\n}\n\n/** Per-probe timeout for the readiness `true` command. */\nconst READINESS_PROBE_TIMEOUT_SECONDS = 5\n/** Pause between readiness probes while the sandbox is still warming up. */\nconst READINESS_BACKOFF_MS = 250\n/** Setup scripts commonly install dependencies, so give them a generous cap. */\nconst PREGAME_TIMEOUT_SECONDS = 30 * 60\n\nexport interface DaytonaReadinessOptions {\n /** Total deadline in seconds. `<= 0` disables the probe entirely. */\n timeoutSeconds: number\n /** Optional cleanup for owned sandboxes that never become ready. */\n cleanupOnTimeout?: () => Promise<void>\n /** Clock source — injectable for deterministic tests. */\n now?: () => number\n /** Sleep between probes — injectable for deterministic tests. */\n sleep?: (ms: number) => Promise<void>\n}\n\nexport function resolveDaytonaEnv(\n optionEnv: Record<string, string> | undefined,\n perSpawnEnv: Record<string, string> | undefined,\n): Record<string, string> | undefined {\n const merged = { ...optionEnv, ...perSpawnEnv }\n return Object.keys(merged).length > 0 ? merged : undefined\n}\n\nexport function normalizeDaytonaExecResult(response: DaytonaExecuteResponse): ExecResult {\n return {\n stdout: response.stdout ?? response.artifacts?.stdout ?? response.result ?? response.output ?? '',\n stderr: response.stderr ?? '',\n exitCode: typeof response.exitCode === 'number' ? response.exitCode : 0,\n }\n}\n\nfunction capExecResult(result: ExecResult): ExecResult {\n return { ...capBufferedExecOutput(result.stdout, result.stderr), exitCode: result.exitCode }\n}\n\nfunction normalizeDaytonaExecError(error: unknown): ExecResult {\n const err = error as { exitCode?: unknown, stdout?: unknown, stderr?: unknown, result?: unknown, output?: unknown, message?: unknown }\n if (typeof err.exitCode === 'number') {\n return {\n stdout: typeof err.stdout === 'string'\n ? err.stdout\n : typeof err.result === 'string'\n ? err.result\n : typeof err.output === 'string'\n ? err.output\n : '',\n stderr: typeof err.stderr === 'string' ? err.stderr : typeof err.message === 'string' ? err.message : '',\n exitCode: err.exitCode,\n }\n }\n return { stdout: '', stderr: error instanceof Error ? error.message : String(error), exitCode: 124 }\n}\n\nfunction bufferToString(value: Uint8Array | ArrayBuffer | { toString: (encoding?: BufferEncoding) => string }): string {\n if (Buffer.isBuffer(value))\n return value.toString('utf8')\n if (value instanceof ArrayBuffer)\n return new TextDecoder().decode(new Uint8Array(value))\n if (value instanceof Uint8Array)\n return new TextDecoder().decode(value)\n return value.toString('utf8')\n}\n\nfunction toClientConfig(apiKey?: string, apiUrl?: string, target?: string): DaytonaClientConfig | undefined {\n const config: DaytonaClientConfig = {}\n if (apiKey !== undefined)\n config.apiKey = apiKey\n if (apiUrl !== undefined)\n config.apiUrl = apiUrl\n if (target !== undefined)\n config.target = target\n return Object.keys(config).length > 0 ? config : undefined\n}\n\nfunction takeString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined\n}\n\nexport function resolveDaytonaCreateParams(\n sandboxConfig: Record<string, unknown>,\n options: DaytonaProviderOptions,\n envVars: Record<string, string> | undefined,\n): DaytonaCreateParams | undefined {\n const reserved = new Set(['provider', 'apiKey', 'apiUrl', 'target', 'sandboxId'])\n const params: DaytonaCreateParams = {}\n\n for (const [key, value] of Object.entries(sandboxConfig)) {\n if (!reserved.has(key) && value !== undefined)\n params[key] = value\n }\n\n const language = takeString(sandboxConfig.language) ?? options.language\n const snapshot = takeString(sandboxConfig.snapshot) ?? options.snapshot\n const image = sandboxConfig.image ?? options.image\n const resources = (sandboxConfig.resources as DaytonaResources | undefined) ?? options.resources\n const configEnvVars = sandboxConfig.envVars as Record<string, string> | undefined\n const mergedEnvVars = resolveDaytonaEnv(envVars, configEnvVars)\n\n if (language !== undefined)\n params.language = language\n if (snapshot !== undefined)\n params.snapshot = snapshot\n if (image !== undefined)\n params.image = image\n if (resources !== undefined)\n params.resources = resources\n if (mergedEnvVars !== undefined)\n params.envVars = mergedEnvVars\n\n return Object.keys(params).length > 0 ? params : undefined\n}\n\nexport async function waitForDaytonaReady(\n sandbox: DaytonaSandbox,\n logger: Logger,\n opts: DaytonaReadinessOptions,\n): Promise<void> {\n if (opts.timeoutSeconds <= 0)\n return\n\n const now = opts.now ?? Date.now\n const sleep = opts.sleep ?? (ms => new Promise<void>(resolve => setTimeout(resolve, ms)))\n const start = now()\n const deadline = start + opts.timeoutSeconds * 1000\n\n logger.info('waiting for Daytona sandbox to initialize', { sandboxId: sandbox.id })\n\n while (true) {\n try {\n await sandbox.process.executeCommand('true', undefined, undefined, READINESS_PROBE_TIMEOUT_SECONDS)\n logger.info('Daytona sandbox ready', { sandboxId: sandbox.id, elapsedMs: now() - start })\n return\n }\n catch {\n if (now() >= deadline) {\n await opts.cleanupOnTimeout?.().catch(() => {})\n throw new Error(`Daytona sandbox ${sandbox.id} did not become ready within ${opts.timeoutSeconds}s`)\n }\n await sleep(READINESS_BACKOFF_MS)\n }\n }\n}\n\nexport async function runDaytonaPregame(\n sandbox: DaytonaSandbox,\n logger: Logger,\n opts: { name: string, content: string, cwd?: string, envVars?: Record<string, string> },\n): Promise<void> {\n const path = `/tmp/${opts.name}`\n logger.info('running Daytona pregame script', { sandboxId: sandbox.id, path })\n await sandbox.fs.uploadFile(Buffer.from(opts.content), path)\n\n const quoted = JSON.stringify(path)\n let result: ExecResult\n try {\n result = normalizeDaytonaExecResult(\n await sandbox.process.executeCommand(`chmod +x ${quoted} && ${quoted}`, opts.cwd, opts.envVars, PREGAME_TIMEOUT_SECONDS),\n )\n }\n catch (err) {\n result = normalizeDaytonaExecError(err)\n }\n\n if (result.exitCode !== 0) {\n logger.error('Daytona pregame script failed', { sandboxId: sandbox.id, exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr })\n throw new Error(`Daytona pregame script ${opts.name} failed with exit code ${result.exitCode}`)\n }\n\n logger.info('Daytona pregame ready', { sandboxId: sandbox.id, stdout: result.stdout, stderr: result.stderr })\n}\n\n// ---------------------------------------------------------------------------\n// Provider\n// ---------------------------------------------------------------------------\n\nexport function createDaytonaProvider(options: DaytonaProviderOptions = {}): SandboxProvider {\n const live = new Map<string, { sandbox: DaytonaSandbox, env?: Record<string, string>, owned: boolean }>()\n const logger = options.logger ?? createLogger(consoleSink())\n const readinessTimeoutSeconds = options.readinessTimeoutSeconds ?? 60\n\n async function loadSdk(): Promise<DaytonaConstructor> {\n try {\n const mod = await import('@daytona/sdk') as { Daytona: DaytonaConstructor }\n return mod.Daytona\n }\n catch (err) {\n // Distinguish \"not installed\" from \"installed but failed to load\". This\n // used to be a bare `catch` that reported the install hint either way,\n // which sent people to `bun add` a package that was already present. The\n // realistic load failure is a `tslib` hoist: `@daytona/sdk` declares no\n // tslib dependency of its own and reaches AWS SDK v3 through\n // `@aws-sdk/client-s3`, so a stale `@aws-crypto` v3/v4 floor\n // (`tslib: ^1.11.1`) can win the hoist and the SDK's initializer helpers\n // resolve against tslib 1.x, which lacks them. Fix with a root\n // `overrides: { \"tslib\": \"^2.8.1\" }` — see `docs/RESTATE.md`.\n const message = errorMessage(err)\n const notInstalled = /cannot find (?:module|package)|module not found|failed to resolve/i.test(message)\n throw new Error(\n notInstalled\n ? '@daytona/sdk is required for the Daytona sandbox provider. Install it with: bun add @daytona/sdk'\n : `@daytona/sdk is installed but failed to load: ${message}. If this mentions tslib, pin it with a root override: \"overrides\": { \"tslib\": \"^2.8.1\" } — see docs/RESTATE.md.`,\n { cause: err },\n )\n }\n }\n\n function get(sandboxId: string): { sandbox: DaytonaSandbox, env?: Record<string, string>, owned: boolean } {\n const entry = live.get(sandboxId)\n if (!entry)\n throw new Error(`Daytona sandbox ${sandboxId} is not tracked by this provider`)\n return entry\n }\n\n async function deleteOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n try {\n await sandbox.delete()\n }\n catch {\n // Already gone — nothing to clean up.\n }\n }\n\n async function stopOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n if (!sandbox.stop) {\n logger.error('cannot stop Daytona sandbox: this @daytona/sdk install exposes no stop() method; leaving it running', { sandboxId: sandbox.id })\n return\n }\n try {\n await sandbox.stop()\n logger.info('stopped Daytona sandbox; reconnect later via the sandboxId option (CLI: --sandbox)', { sandboxId: sandbox.id })\n }\n catch (err) {\n logger.error('failed to stop Daytona sandbox; it will run until Daytona lifecycle policy stops it', { sandboxId: sandbox.id, error: err instanceof Error ? err.message : String(err) })\n }\n }\n\n async function archiveOwnedSandbox(sandbox: DaytonaSandbox): Promise<void> {\n if (!sandbox.stop || !sandbox.archive) {\n logger.error('cannot archive Daytona sandbox: this @daytona/sdk install exposes no stop() and archive() pair; leaving it running', { sandboxId: sandbox.id })\n return\n }\n try {\n await sandbox.stop()\n await sandbox.archive()\n logger.info('archived Daytona sandbox; reconnect later via the sandboxId option (CLI: --sandbox)', { sandboxId: sandbox.id })\n }\n catch (err) {\n logger.error('failed to archive Daytona sandbox; it will run until Daytona lifecycle policy stops it', { sandboxId: sandbox.id, error: err instanceof Error ? err.message : String(err) })\n }\n }\n\n async function startAttachedSandboxIfNeeded(sandbox: DaytonaSandbox): Promise<void> {\n if (sandbox.state !== 'stopped' && sandbox.state !== 'archived')\n return\n if (!sandbox.start) {\n logger.error('cannot start Daytona sandbox before attach readiness probe: this @daytona/sdk install exposes no start() method', { sandboxId: sandbox.id, state: sandbox.state })\n return\n }\n logger.info('starting Daytona sandbox before attach readiness probe', { sandboxId: sandbox.id, state: sandbox.state })\n await sandbox.start(readinessTimeoutSeconds > 0 ? readinessTimeoutSeconds : undefined)\n }\n\n return {\n name: 'daytona',\n\n async spawn(config: SpawnConfig = {}): Promise<{ id: string, cwd: string }> {\n const Daytona = await loadSdk()\n const sb: Record<string, unknown> = config.sandbox ?? {}\n\n const apiKey = takeString(sb.apiKey) ?? options.apiKey\n const apiUrl = takeString(sb.apiUrl) ?? options.apiUrl\n const target = takeString(sb.target) ?? options.target\n const connectId = takeString(sb.sandboxId) ?? options.sandboxId\n const envVars = resolveDaytonaEnv(options.env, config.env)\n\n const daytona = new Daytona(toClientConfig(apiKey, apiUrl, target))\n const attached = connectId !== undefined\n // Lifecycle ownership drives `destroy()` (onDestroy). A created sandbox is\n // always owned; an attached one is owned only when the host opts in via\n // `ownAttached`. Spawn-FAILURE cleanup is separate (see below) and keyed\n // on `!attached` so a pre-existing sandbox is never auto-deleted.\n const owned = !attached || options.ownAttached === true\n const sandbox = attached\n ? await daytona.get(connectId)\n : await daytona.create(resolveDaytonaCreateParams(sb, options, envVars))\n\n if (attached)\n await startAttachedSandboxIfNeeded(sandbox)\n\n live.set(sandbox.id, { sandbox, env: envVars, owned })\n\n try {\n await waitForDaytonaReady(sandbox, logger, {\n timeoutSeconds: readinessTimeoutSeconds,\n // Only auto-delete a sandbox we CREATED on readiness failure — never a\n // pre-existing attached one, even when we own its lifecycle.\n ...(!attached ? { cleanupOnTimeout: () => deleteOwnedSandbox(sandbox) } : {}),\n })\n }\n catch (err) {\n live.delete(sandbox.id)\n throw err\n }\n\n const requestedCwd = config.cwd ?? options.cwd\n let cwd: string\n if (requestedCwd) {\n cwd = requestedCwd\n await sandbox.process.executeCommand(`mkdir -p ${JSON.stringify(cwd)}`).catch(() => {})\n }\n else if (sandbox.getWorkDir) {\n cwd = await sandbox.getWorkDir().catch(() => '')\n if (!cwd)\n cwd = await sandbox.process.executeCommand('pwd').then(r => normalizeDaytonaExecResult(r).stdout.trim()).catch(() => '') || '/home/daytona'\n }\n else {\n cwd = await sandbox.process.executeCommand('pwd').then(r => normalizeDaytonaExecResult(r).stdout.trim()).catch(() => '') || '/home/daytona'\n }\n\n if (options.pregame) {\n try {\n await runDaytonaPregame(sandbox, logger, { name: options.pregame.name, content: options.pregame.content, cwd, envVars })\n }\n catch (err) {\n // Spawn-failure cleanup: only delete a sandbox we created, never a\n // pre-existing attached one (the host owns its prior state).\n if (!attached)\n await deleteOwnedSandbox(sandbox)\n live.delete(sandbox.id)\n throw err\n }\n }\n\n return { id: sandbox.id, cwd }\n },\n\n async exec(sandboxId, command, opts): Promise<ExecResult> {\n const { sandbox, env } = get(sandboxId)\n const timeoutSeconds = opts?.timeout ?? 30\n try {\n // The SDK buffers the streams uncapped (see the KNOWN RESIDUAL note\n // on `ExecutionContext.fileSize`) — cap host-side before the strings\n // propagate into tool results and session history.\n return capExecResult(normalizeDaytonaExecResult(\n await sandbox.process.executeCommand(\n command,\n opts?.cwd,\n resolveDaytonaEnv(env, opts?.env),\n timeoutSeconds > 0 ? timeoutSeconds : undefined,\n ),\n ))\n }\n catch (err) {\n return capExecResult(normalizeDaytonaExecError(err))\n }\n },\n\n /**\n * Live bidirectional stream — see `ExecutionContext.execStream`.\n *\n * PTY-backed, and not by preference: Daytona's process + session API\n * exposes no stdin at all (sessions are fire-and-forget with log\n * streaming), so a pseudo-terminal is the only interactive channel the\n * platform offers. That forces three mitigations, all in the launch\n * wrapper below, because a PTY is a terminal and a protocol stream is\n * not:\n *\n * 1. `stty -echo` — a terminal echoes everything written to stdin back\n * onto stdout. Without this the caller reads its own requests back\n * as if they were responses.\n * 2. `stty raw` — canonical mode rewrites `\\n`→`\\r\\n` and caps a line\n * at ~4096 bytes. Protocol frames routinely exceed that and would\n * be silently truncated mid-message.\n * 3. `2><file>` — a PTY has ONE stream, so the child's stderr would\n * otherwise interleave into the protocol data and corrupt framing.\n * It is redirected to a file inside the sandbox and surfaced on the\n * returned handle by polling that file through the exec API.\n *\n * The mitigations must run before the child's first byte — but the\n * launch line ITSELF is typed into a canonical-mode terminal, so it is\n * echoed once (a short non-JSON line the transport's tolerant framing\n * discards) and subject to the ~4096-byte line cap. That is why the\n * real command lives in an uploaded script and the typed line stays\n * short and constant: a long command line would be truncated before\n * `stty` ever ran. The script also restores `sh` compound-command\n * semantics that a bare `exec <command>` would break.\n */\n async execStream(sandboxId, command, opts): Promise<StreamHandle> {\n const { sandbox, env } = get(sandboxId)\n\n if (!sandbox.process.createPty) {\n throw new Error(\n 'Daytona SDK is too old: `process.createPty` is required for execStream '\n + '(used to run stdio MCP servers inside the sandbox).',\n )\n }\n\n opts?.signal?.throwIfAborted()\n\n const token = Math.random().toString(36).slice(2, 10)\n const stderrPath = `/tmp/.zidane-stream-${token}.err`\n const scriptPath = `/tmp/.zidane-stream-${token}.sh`\n\n // `exec 2>` rebinds the shell's stderr before the command runs, so\n // the command text needs no rewriting and stays compound-safe.\n await sandbox.fs.uploadFile(\n Buffer.from(`exec 2>${stderrPath}\\n${command}\\n`),\n scriptPath,\n )\n\n // See the E2B counterpart: the PTY's `onData` is a sync `void`\n // callback, so a stalled consumer can only be reported, never slowed.\n const warnBacklog = (which: string) => (bytes: number) =>\n logger.warn('execStream consumer is not draining output', { sandboxId, stream: which, bufferedBytes: bytes })\n const stdout = new StreamQueue(warnBacklog('stdout'))\n const stderr = new StreamQueue(warnBacklog('stderr'))\n\n // Everything the shell emits before the child is actually running is\n // NOISE that must never reach the caller: the echo of our own launch\n // line (typed before `-echo` takes effect), the login shell's prompt,\n // and its line-editor redraw escapes. `createPty` is `lazyStart`, so\n // the shell frequently does not exist yet when we type — it boots\n // afterwards and REPLAYS the buffered input through its line editor.\n // Observed on a stock sandbox: the stream opened with the echoed\n // launch line, the echoed first request, `\\u001b[?2004h` bracketed\n // paste, and a `%` prompt. An MCP client parses that echoed request\n // as a message and the handshake collapses.\n //\n // So: gate the stream on a sentinel the CHILD side prints, and drop\n // every byte before it. The sentinel is assembled by `printf` at\n // runtime (`Z-%s-READY` + token) so the echoed *source* line, which\n // contains the format string rather than the result, cannot match it.\n const sentinel = `Z-${token}-READY`\n let gateOpen = false\n let gateBuffer = ''\n let openGate: () => void = () => {}\n const gateReady = new Promise<void>((r) => { openGate = r })\n\n const pty = await sandbox.process.createPty({\n id: `zidane-stream-${token}`,\n ...(opts?.cwd ? { cwd: opts.cwd } : {}),\n envs: resolveDaytonaEnv(env, opts?.env) ?? {},\n onData: (data: Uint8Array) => {\n if (gateOpen) {\n stdout.push(data)\n return\n }\n gateBuffer += Buffer.from(data).toString('utf8')\n const at = gateBuffer.indexOf(sentinel)\n if (at === -1) {\n // Bounded: never let pre-gate noise grow without limit, but keep\n // a tail longer than the sentinel so it can't be split away.\n if (gateBuffer.length > 64 * 1024)\n gateBuffer = gateBuffer.slice(-1024)\n return\n }\n gateOpen = true\n openGate()\n // Everything after the sentinel's trailing newline is real output.\n const rest = gateBuffer.slice(at + sentinel.length).replace(/^\\r?\\n/, '')\n gateBuffer = ''\n if (rest.length > 0)\n stdout.push(new TextEncoder().encode(rest))\n },\n })\n await pty.waitForConnection()\n\n // Short, constant, and under any canonical line cap. `exec` replaces\n // the login shell so the PTY's lifetime is the script's lifetime and\n // no shell prompt can reach stdout.\n await pty.sendInput(`stty raw -echo; printf 'Z-%s-READY\\\\n' ${token}; exec sh ${scriptPath}\\n`)\n\n // Block until the child is genuinely live. Without this the caller can\n // write its first frame into a shell that hasn't started, where it is\n // echoed back and misread as a response.\n let gateTimer: ReturnType<typeof setTimeout> | undefined\n await Promise.race([\n gateReady,\n new Promise<void>((r) => { gateTimer = setTimeout(r, 30_000) }),\n ])\n clearTimeout(gateTimer)\n if (!gateOpen) {\n // Full teardown, not just a disconnect: Daytona PTY sessions persist\n // server-side after the websocket drops, so a bare disconnect leaks\n // one login shell plus two /tmp files per attempt — a bootstrap\n // retry loop against a broken image would stack them until the\n // sandbox dies.\n await (pty.kill?.() ?? Promise.resolve()).catch(() => {})\n await pty.disconnect().catch(() => {})\n await sandbox.process.executeCommand(`rm -f ${scriptPath} ${stderrPath}`).catch(() => {})\n throw new Error(\n `Daytona execStream: PTY did not reach the ready sentinel within 30s `\n + `(sandbox ${sandboxId}). The login shell may not have started.`,\n )\n }\n\n // stderr file → handle.stderr. Poll rather than stream: the exec API\n // is the only other channel into the sandbox, and diagnostics don't\n // need latency. Byte offsets keep re-reads incremental.\n //\n // The offset comes from the FILE (`wc -c`), never from measuring the\n // returned content: an exec API that trims a trailing newline from\n // command output would make a content-derived offset under-advance by\n // one byte per poll, re-emitting the tail byte forever. The size rides\n // back on the same round trip as a `ZEOF-<token>:` suffix; content is\n // whatever precedes it, so content-side transforms can't drift the\n // cursor either.\n let stderrOffset = 0\n let torndown = false\n const eofMark = `ZEOF-${token}:`\n const drainStderr = async (): Promise<void> => {\n try {\n const res = normalizeDaytonaExecResult(await sandbox.process.executeCommand(\n `tail -c +${stderrOffset + 1} ${stderrPath} 2>/dev/null; printf '${eofMark}%s' \"$(wc -c < ${stderrPath} 2>/dev/null || echo 0)\"`,\n ))\n const at = res.stdout.lastIndexOf(eofMark)\n if (at === -1)\n return\n const content = res.stdout.slice(0, at)\n const size = Number.parseInt(res.stdout.slice(at + eofMark.length).trim(), 10)\n if (content.length > 0)\n stderr.push(new TextEncoder().encode(content))\n if (Number.isFinite(size) && size > stderrOffset)\n stderrOffset = size\n }\n catch {\n // Diagnostic channel — polling failures must never surface as\n // protocol errors.\n }\n }\n const stderrTimer = setInterval(() => { void drainStderr() }, 2000)\n // Guarded: Bun/Node timers support unref, test fakes may not.\n ;(stderrTimer as { unref?: () => void }).unref?.()\n\n // Shared teardown for both exit paths (natural exit and kill): one\n // final stderr drain so a crash message isn't lost, then remove the\n // script + stderr files that would otherwise accumulate in /tmp for\n // the sandbox's lifetime.\n const teardown = async (): Promise<void> => {\n if (torndown)\n return\n torndown = true\n clearInterval(stderrTimer)\n await drainStderr()\n await sandbox.process.executeCommand(`rm -f ${scriptPath} ${stderrPath}`).catch(() => {})\n stdout.close()\n stderr.close()\n }\n\n const exited = pty.wait()\n .then(result => result?.exitCode ?? 0)\n .catch(() => 137)\n .finally(teardown)\n\n const kill = async (): Promise<void> => {\n // A PTY login shell never exits on its own — killing it IS the\n // normal termination path here, not an error path.\n await (pty.kill?.() ?? Promise.resolve()).catch(() => {})\n await pty.disconnect().catch(() => {})\n await teardown()\n }\n\n if (opts?.signal) {\n if (opts.signal.aborted) {\n void kill()\n }\n else {\n // Detach on exit — the (typically run-long) signal otherwise\n // retains the `kill` closure and the PTY handle for the rest of\n // the run, one dead closure per exec.\n const onAbort = () => { void kill() }\n const detach = () => opts.signal!.removeEventListener('abort', onAbort)\n opts.signal.addEventListener('abort', onAbort, { once: true })\n exited.then(detach, detach)\n }\n }\n\n return {\n pid: pty.pid ?? -1,\n stdout,\n stderr,\n write: async (data: Uint8Array): Promise<void> => {\n await pty.sendInput(data)\n },\n kill,\n exited,\n }\n },\n\n async readFile(sandboxId, path): Promise<string> {\n return bufferToString(await get(sandboxId).sandbox.fs.downloadFile(path))\n },\n\n async writeFile(sandboxId, path, content): Promise<void> {\n await get(sandboxId).sandbox.fs.uploadFile(Buffer.from(content), path)\n },\n\n async listFiles(sandboxId, path): Promise<string[]> {\n const entries = await get(sandboxId).sandbox.fs.listFiles(path)\n // Trailing `/` on directories — parity with process/docker contexts.\n return entries.map(e => (e.isDir ? `${e.name}/` : e.name))\n },\n\n async destroy(sandboxId): Promise<void> {\n const entry = live.get(sandboxId)\n if (!entry)\n return\n if (entry.owned) {\n const action = options.onDestroy ?? 'delete'\n if (action === 'stop' || action === 'pause')\n await stopOwnedSandbox(entry.sandbox)\n else if (action === 'archive')\n await archiveOwnedSandbox(entry.sandbox)\n else if (action === 'delete' || action === 'kill')\n await deleteOwnedSandbox(entry.sandbox)\n }\n live.delete(sandboxId)\n },\n }\n}\n"],"mappings":";;;;;;;AAgMA,MAAM,kCAAkC;;AAExC,MAAM,uBAAuB;;AAE7B,MAAM,0BAA0B;AAahC,SAAgB,kBACd,WACA,aACoC;CACpC,MAAM,SAAS;EAAE,GAAG;EAAW,GAAG;CAAY;CAC9C,OAAO,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS,KAAA;AACnD;AAEA,SAAgB,2BAA2B,UAA8C;CACvF,OAAO;EACL,QAAQ,SAAS,UAAU,SAAS,WAAW,UAAU,SAAS,UAAU,SAAS,UAAU;EAC/F,QAAQ,SAAS,UAAU;EAC3B,UAAU,OAAO,SAAS,aAAa,WAAW,SAAS,WAAW;CACxE;AACF;AAEA,SAAS,cAAc,QAAgC;CACrD,OAAO;EAAE,GAAG,sBAAsB,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AC,QAAQ,GAAG,UAAU,IAAI,EAAA,CAE/C,KAAI,MAAM,EAAE,QAAQ,GAAG,EAAE,KAAK,KAAK,EAAE,IAAK;EAC3D;EAEA,MAAM,QAAQ,WAA0B;GACtC,MAAM,QAAQ,KAAK,IAAI,SAAS;GAChC,IAAI,CAAC,OACH;GACF,IAAI,MAAM,OAAO;IACf,MAAM,SAAS,QAAQ,aAAa;IACpC,IAAI,WAAW,UAAU,WAAW,SAClC,MAAM,iBAAiB,MAAM,OAAO;SACjC,IAAI,WAAW,WAClB,MAAM,oBAAoB,MAAM,OAAO;SACpC,IAAI,WAAW,YAAY,WAAW,QACzC,MAAM,mBAAmB,MAAM,OAAO;GAC1C;GACA,KAAK,OAAO,SAAS;EACvB;CACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { Wu as Logger } from "../index-CWBSrqI6.js";
1
+ import { Wu as Logger } from "../index-BKyWhILQ.js";
2
2
  import { t as SandboxProvider } from "../sandbox-DLY6uah7.js";
3
3
 
4
4
  //#region src/contexts/e2b.d.ts
package/dist/eval.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $t as EvalRunUsage, An as efficiencyMetricValues, Bn as functionalityMetric, Bt as EvalAgentStats, Cn as clearRegisteredEvals, Dn as createReusableExecutionContext, En as createEvalRunReporter, Fn as fileExistsOneOf, Ft as EvalAgent, Gn as runEvalCase, Gt as EvalDefinitionContext, Hn as normalizeMetric, Ht as EvalCaseOptions, In as finalizeEvalMetrics, It as EvalAgentMcpServers, Jt as EvalRunMetricAggregate, Kn as statusCompleted, Kt as EvalMetric, Ln as formatEvalCaseSummary, Lt as EvalAgentRunOptions, Mn as fileContains, Nn as fileContentQuality, Nt as CreateEvalAgentOptions, On as defineEval, Pn as fileExists, Pt as EFFICIENCY_METRICS, Qt as EvalRunSummaryCase, Rn as formatEvalRunSummary, Rt as EvalAgentRunResult, Sn as buildTrajectory, Tn as createEvalAgent, Un as registerEvalTests, Ut as EvalCaseResult, Vn as llmJudge, Vt as EvalArtifacts, Wn as relativeArtifactPath, Wt as EvalDefinition, Xt as EvalRunReporterOptions, Yt as EvalRunReporter, Zt as EvalRunSummary, _n as TrajectoryStep, an as EvalWorkspaceFile, bn as buildEvalRunSummary, cn as LlmJudgeOptions, dn as MetricSpec, en as EvalScore, fn as MetricSpecMap, gn as Trajectory, hn as ReusableExecutionContext, in as EvalVariantSummary, jn as emitEfficiencyMetrics, kn as defineMetrics, ln as MetricDirection, mn as RegisterEvalTestsOptions, nn as EvalScorerContext, on as EvalWorkspaceOptions, pn as MetricStats, qt as EvalMetricError, rn as EvalTestRunner, sn as EvalWorkspaceSnapshot, tn as EvalScorer, un as MetricEmitter, vn as TrajectoryStepKind, wn as computeEvalTagScores, xn as buildRegisteredEvals, yn as artifactPath, zn as formatTrajectoryLine, zt as EvalAgentRunStats } from "./index-CWBSrqI6.js";
1
+ import { $t as EvalRunUsage, An as efficiencyMetricValues, Bn as functionalityMetric, Bt as EvalAgentStats, Cn as clearRegisteredEvals, Dn as createReusableExecutionContext, En as createEvalRunReporter, Fn as fileExistsOneOf, Ft as EvalAgent, Gn as runEvalCase, Gt as EvalDefinitionContext, Hn as normalizeMetric, Ht as EvalCaseOptions, In as finalizeEvalMetrics, It as EvalAgentMcpServers, Jt as EvalRunMetricAggregate, Kn as statusCompleted, Kt as EvalMetric, Ln as formatEvalCaseSummary, Lt as EvalAgentRunOptions, Mn as fileContains, Nn as fileContentQuality, Nt as CreateEvalAgentOptions, On as defineEval, Pn as fileExists, Pt as EFFICIENCY_METRICS, Qt as EvalRunSummaryCase, Rn as formatEvalRunSummary, Rt as EvalAgentRunResult, Sn as buildTrajectory, Tn as createEvalAgent, Un as registerEvalTests, Ut as EvalCaseResult, Vn as llmJudge, Vt as EvalArtifacts, Wn as relativeArtifactPath, Wt as EvalDefinition, Xt as EvalRunReporterOptions, Yt as EvalRunReporter, Zt as EvalRunSummary, _n as TrajectoryStep, an as EvalWorkspaceFile, bn as buildEvalRunSummary, cn as LlmJudgeOptions, dn as MetricSpec, en as EvalScore, fn as MetricSpecMap, gn as Trajectory, hn as ReusableExecutionContext, in as EvalVariantSummary, jn as emitEfficiencyMetrics, kn as defineMetrics, ln as MetricDirection, mn as RegisterEvalTestsOptions, nn as EvalScorerContext, on as EvalWorkspaceOptions, pn as MetricStats, qt as EvalMetricError, rn as EvalTestRunner, sn as EvalWorkspaceSnapshot, tn as EvalScorer, un as MetricEmitter, vn as TrajectoryStepKind, wn as computeEvalTagScores, xn as buildRegisteredEvals, yn as artifactPath, zn as formatTrajectoryLine, zt as EvalAgentRunStats } from "./index-BKyWhILQ.js";
2
2
  export { CreateEvalAgentOptions, EFFICIENCY_METRICS, EvalAgent, EvalAgentMcpServers, EvalAgentRunOptions, EvalAgentRunResult, EvalAgentRunStats, EvalAgentStats, EvalArtifacts, EvalCaseOptions, EvalCaseResult, EvalDefinition, EvalDefinitionContext, EvalMetric, EvalMetricError, EvalRunMetricAggregate, EvalRunReporter, EvalRunReporterOptions, EvalRunSummary, EvalRunSummaryCase, EvalRunUsage, EvalScore, EvalScorer, EvalScorerContext, EvalTestRunner, EvalVariantSummary, EvalWorkspaceFile, EvalWorkspaceOptions, EvalWorkspaceSnapshot, LlmJudgeOptions, MetricDirection, MetricEmitter, MetricSpec, MetricSpecMap, MetricStats, RegisterEvalTestsOptions, ReusableExecutionContext, Trajectory, TrajectoryStep, TrajectoryStepKind, artifactPath, buildEvalRunSummary, buildRegisteredEvals, buildTrajectory, clearRegisteredEvals, computeEvalTagScores, createEvalAgent, createEvalRunReporter, createReusableExecutionContext, defineEval, defineMetrics, efficiencyMetricValues, emitEfficiencyMetrics, fileContains, fileContentQuality, fileExists, fileExistsOneOf, finalizeEvalMetrics, formatEvalCaseSummary, formatEvalRunSummary, formatTrajectoryLine, functionalityMetric, llmJudge, normalizeMetric, registerEvalTests, relativeArtifactPath, runEvalCase, statusCompleted };