@zergai/ztc 0.23.1-dev.202611152321 → 0.24.0-beta.1

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 (149) hide show
  1. package/README.md +299 -13
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +2 -2
  10. package/dist/agent/agent.js +57 -14
  11. package/dist/agent/backends/http_error.d.ts +2 -0
  12. package/dist/agent/backends/http_error.js +2 -0
  13. package/dist/agent/backends/router_gate.d.ts +3 -2
  14. package/dist/agent/backends/router_gate.js +5 -4
  15. package/dist/agent/backends/router_keys.d.ts +14 -0
  16. package/dist/agent/backends/router_keys.js +19 -0
  17. package/dist/agent/backends/router_refusal.d.ts +5 -3
  18. package/dist/agent/backends/router_refusal.js +28 -6
  19. package/dist/agent/backends/types.d.ts +1 -1
  20. package/dist/agent/backends/zrouter_stream.js +10 -6
  21. package/dist/agent/commands/agent_cli.d.ts +11 -1
  22. package/dist/agent/commands/agent_cli.js +295 -38
  23. package/dist/agent/commands/diff.js +4 -1
  24. package/dist/agent/commands/help.js +4 -1
  25. package/dist/agent/commands/plan.js +3 -1
  26. package/dist/agent/commands/session_redaction.d.ts +16 -0
  27. package/dist/agent/commands/session_redaction.js +77 -0
  28. package/dist/agent/commands/settings.js +144 -0
  29. package/dist/agent/commands/types.d.ts +5 -0
  30. package/dist/agent/commands/usage_spec.d.ts +4 -0
  31. package/dist/agent/commands/usage_spec.js +10 -4
  32. package/dist/agent/runtime/policy.d.ts +25 -0
  33. package/dist/agent/runtime/policy.js +154 -26
  34. package/dist/agent/runtime/source_verification.js +6 -2
  35. package/dist/agent/runtime/tool_runtime.js +81 -3
  36. package/dist/agent/tools/apply_patch.js +678 -131
  37. package/dist/agent/tools/bus_message.d.ts +26 -1
  38. package/dist/agent/tools/bus_message.js +126 -10
  39. package/dist/agent/tools/file.d.ts +16 -1
  40. package/dist/agent/tools/file.js +43 -5
  41. package/dist/agent/tools/index.d.ts +1 -1
  42. package/dist/agent/tools/index.js +1 -1
  43. package/dist/agent/tools/pane.js +5 -0
  44. package/dist/agent/tools/search.js +5 -1
  45. package/dist/agent/tools/supervision.js +16 -2
  46. package/dist/agent/tools/types.d.ts +22 -0
  47. package/dist/app/mirror_startup.d.ts +7 -5
  48. package/dist/app/mirror_startup.js +7 -5
  49. package/dist/app/navigator_mirrors.d.ts +20 -0
  50. package/dist/app/navigator_mirrors.js +36 -0
  51. package/dist/app/workspace_layout_controller.d.ts +11 -2
  52. package/dist/app/workspace_layout_controller.js +13 -2
  53. package/dist/batch/worktree.js +9 -1
  54. package/dist/cli_ratatui.d.ts +264 -12
  55. package/dist/cli_ratatui.js +1198 -103
  56. package/dist/config/types.d.ts +29 -0
  57. package/dist/desktop/daily/source_baseline.js +3 -1
  58. package/dist/diagnostics/session_export.d.ts +1 -0
  59. package/dist/diagnostics/session_export.js +229 -26
  60. package/dist/emulation/tool_adapters.js +42 -5
  61. package/dist/headless.js +24 -5
  62. package/dist/instance_registry.d.ts +7 -0
  63. package/dist/mcp/workspace_server.d.ts +12 -1
  64. package/dist/mcp/workspace_server.js +75 -8
  65. package/dist/panes/agent_cli.d.ts +60 -3
  66. package/dist/panes/agent_cli.js +169 -16
  67. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  68. package/dist/panes/agent_pane_sessions.js +111 -0
  69. package/dist/panes/agent_panes.d.ts +77 -3
  70. package/dist/panes/agent_panes.js +199 -10
  71. package/dist/panes/agent_profiles.d.ts +5 -0
  72. package/dist/panes/agent_profiles.js +7 -0
  73. package/dist/panes/agent_resume.d.ts +134 -0
  74. package/dist/panes/agent_resume.js +155 -0
  75. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  76. package/dist/panes/agent_sessions/claude_head.js +122 -0
  77. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  78. package/dist/panes/agent_sessions/claude_store.js +223 -0
  79. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  80. package/dist/panes/agent_sessions/codex_head.js +161 -0
  81. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  82. package/dist/panes/agent_sessions/codex_store.js +187 -0
  83. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  84. package/dist/panes/agent_sessions/controller.js +110 -0
  85. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  86. package/dist/panes/agent_sessions/cut_json.js +109 -0
  87. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  88. package/dist/panes/agent_sessions/limits.js +48 -0
  89. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  90. package/dist/panes/agent_sessions/scan.js +86 -0
  91. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  92. package/dist/panes/agent_sessions/store_fs.js +128 -0
  93. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  94. package/dist/panes/agent_sessions/stores.js +89 -0
  95. package/dist/panes/agent_sessions/title.d.ts +9 -0
  96. package/dist/panes/agent_sessions/title.js +51 -0
  97. package/dist/panes/agent_sessions/types.d.ts +48 -0
  98. package/dist/panes/agent_sessions/types.js +2 -0
  99. package/dist/panes/reply_arbitrator.d.ts +39 -0
  100. package/dist/panes/reply_arbitrator.js +185 -0
  101. package/dist/panes/reply_modes.d.ts +291 -0
  102. package/dist/panes/reply_modes.js +598 -0
  103. package/dist/runtime_info.js +11 -2
  104. package/dist/session.js +4 -2
  105. package/dist/simulation/living/context.d.ts +8 -8
  106. package/dist/simulation/living/types.d.ts +5 -5
  107. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  108. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  109. package/dist/ui/ratatui/ipc_path.js +23 -3
  110. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  111. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  112. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  113. package/dist/ui/ratatui/pane_relay.js +86 -19
  114. package/dist/ui/ratatui/process.js +3 -0
  115. package/dist/ui/ratatui/protocol.d.ts +50 -1
  116. package/dist/ui/ratatui/protocol.js +56 -0
  117. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  118. package/dist/ui/ratatui/relay_policy.js +94 -0
  119. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  120. package/dist/ui/ratatui/screen_privacy.js +24 -0
  121. package/dist/ui/scrollback.js +8 -0
  122. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  123. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  124. package/dist/ui/widgets/log_view.d.ts +5 -1
  125. package/dist/ui/widgets/log_view.js +40 -4
  126. package/dist/utils/atomic_write.js +9 -11
  127. package/dist/utils/canonical_path.d.ts +19 -0
  128. package/dist/utils/canonical_path.js +44 -0
  129. package/dist/utils/compaction.d.ts +2 -1
  130. package/dist/utils/compaction.js +3 -1
  131. package/dist/utils/git_directory_names.d.ts +51 -0
  132. package/dist/utils/git_directory_names.js +429 -0
  133. package/dist/utils/temporary_write_root.d.ts +6 -1
  134. package/dist/utils/temporary_write_root.js +32 -2
  135. package/dist/utils/tool_result_message.d.ts +4 -1
  136. package/dist/utils/tool_result_message.js +6 -2
  137. package/dist/web/bus_hold.d.ts +70 -0
  138. package/dist/web/bus_hold.js +118 -0
  139. package/dist/web/mirror_client.d.ts +7 -3
  140. package/dist/web/mirror_client.js +61 -23
  141. package/dist/web/mirror_route_gate.d.ts +40 -0
  142. package/dist/web/mirror_route_gate.js +71 -0
  143. package/dist/web/mirror_stream.d.ts +147 -22
  144. package/dist/web/mirror_stream.js +350 -83
  145. package/dist/web/pane_credentials.d.ts +32 -1
  146. package/dist/web/pane_credentials.js +62 -2
  147. package/dist/workspace_collision.js +11 -2
  148. package/dist/zlm-embed.mjs +940 -273
  149. package/package.json +39 -7
@@ -2010,7 +2010,7 @@ function migrateRetiredClaudeRoutes(saved2, signals) {
2010
2010
  const activeId = (inUse && pointer(inUse)) ?? pointer("claude_code") ?? pointer("claude_code_direct");
2011
2011
  const made = [];
2012
2012
  const gone = /* @__PURE__ */ new Map();
2013
- const relative4 = [];
2013
+ const relative7 = [];
2014
2014
  const noDirectory = [];
2015
2015
  let ownSignIn = false;
2016
2016
  let activeProfile2;
@@ -2025,7 +2025,7 @@ function migrateRetiredClaudeRoutes(saved2, signals) {
2025
2025
  }
2026
2026
  const dir = expandHomePath(stored, signals.home);
2027
2027
  if (!isAbsolute(dir)) {
2028
- relative4.push({ label, path: stored, name: profileNameFrom(id) });
2028
+ relative7.push({ label, path: stored, name: profileNameFrom(id) });
2029
2029
  continue;
2030
2030
  }
2031
2031
  if (comparable(dir) === claudeHome) {
@@ -2062,7 +2062,7 @@ function migrateRetiredClaudeRoutes(saved2, signals) {
2062
2062
  accountLines.push(`Plain /claude opens Claude Code on this computer's own sign-in; /subs use claude ${activeProfile2} makes @${activeProfile2} the default.`);
2063
2063
  }
2064
2064
  if (ownSignIn) accountLines.push("Your ~/.claude account is Claude Code's own sign-in, which /claude uses.");
2065
- for (const { label, path: path2, name: name2 } of relative4) {
2065
+ for (const { label, path: path2, name: name2 } of relative7) {
2066
2066
  accountLines.push(`${label} was saved with a relative path (${path2}), so ZTC made no profile for it: add it with /accounts add claude_code ${name2} --path <full path>.`);
2067
2067
  }
2068
2068
  if (noDirectory.length > 0) {
@@ -2639,8 +2639,8 @@ async function readHttpErrorBody(response, signal) {
2639
2639
  let body = "";
2640
2640
  let bodyReadState = "complete";
2641
2641
  let stopRead;
2642
- const stopped = new Promise((resolve22) => {
2643
- stopRead = resolve22;
2642
+ const stopped = new Promise((resolve24) => {
2643
+ stopRead = resolve24;
2644
2644
  });
2645
2645
  const timer = setTimeout(() => stopRead("timeout"), BODY_TIMEOUT_MS);
2646
2646
  const aborted2 = () => stopRead("failed");
@@ -2783,6 +2783,7 @@ var init_http_error = __esm({
2783
2783
  httpError;
2784
2784
  /** Transport control only; never copied into the public body diagnostic. */
2785
2785
  retryAtMs;
2786
+ provider;
2786
2787
  /**
2787
2788
  * Router ended the turn with this error (a router_error frame): resuming the same turn id replays it, so another
2788
2789
  * attempt must start a new turn.
@@ -2797,6 +2798,7 @@ var init_http_error = __esm({
2797
2798
  this.status = status;
2798
2799
  this.body = safe.text;
2799
2800
  this.turnEnded = options.turnEnded === true;
2801
+ this.provider = options.provider;
2800
2802
  if (status === 429) {
2801
2803
  const now = Date.now();
2802
2804
  this.retryAtMs = parseRetryDeadline(options.retryAfter, now, true) ?? parseRetryDeadline(options.rateLimitReset, now, false);
@@ -3699,10 +3701,10 @@ var init_codex_buffered_recovery = __esm({
3699
3701
  return await complete();
3700
3702
  } catch (error62) {
3701
3703
  if (!this.canRecover() || !this.canPost()) throw error62;
3702
- await new Promise((resolve22, reject) => {
3704
+ await new Promise((resolve24, reject) => {
3703
3705
  const abort = () => reject(this.controller.signal.reason);
3704
3706
  this.controller.signal.addEventListener("abort", abort, { once: true });
3705
- void this.last.settled.then(resolve22, reject).finally(() => this.controller.signal.removeEventListener("abort", abort));
3707
+ void this.last.settled.then(resolve24, reject).finally(() => this.controller.signal.removeEventListener("abort", abort));
3706
3708
  if (this.controller.signal.aborted) abort();
3707
3709
  });
3708
3710
  this.controller.signal.throwIfAborted();
@@ -3734,8 +3736,8 @@ var init_codex_buffered_recovery = __esm({
3734
3736
  usage: "unknown"
3735
3737
  };
3736
3738
  let settle2;
3737
- const settled = new Promise((resolve22) => {
3738
- settle2 = resolve22;
3739
+ const settled = new Promise((resolve24) => {
3740
+ settle2 = resolve24;
3739
3741
  });
3740
3742
  this.last = { event, settled };
3741
3743
  this.emit(event);
@@ -3974,14 +3976,14 @@ function throwIfRefreshAborted(signal) {
3974
3976
  }
3975
3977
  function awaitRefresh(refresh, signal) {
3976
3978
  if (!signal) return refresh;
3977
- return new Promise((resolve22, reject) => {
3979
+ return new Promise((resolve24, reject) => {
3978
3980
  const cancelled = () => reject(new Error("Codex token refresh cancelled."));
3979
3981
  if (signal.aborted) {
3980
3982
  cancelled();
3981
3983
  return;
3982
3984
  }
3983
3985
  signal.addEventListener("abort", cancelled, { once: true });
3984
- void refresh.then(resolve22, reject).finally(() => signal.removeEventListener("abort", cancelled));
3986
+ void refresh.then(resolve24, reject).finally(() => signal.removeEventListener("abort", cancelled));
3985
3987
  });
3986
3988
  }
3987
3989
  function parseCodexAuthData(data) {
@@ -5078,8 +5080,8 @@ var init_codex_app_server = __esm({
5078
5080
  if (this.closed) {
5079
5081
  return Promise.resolve({ value: void 0, done: true });
5080
5082
  }
5081
- return new Promise((resolve22, reject) => {
5082
- this.waiters.push({ resolve: resolve22, reject });
5083
+ return new Promise((resolve24, reject) => {
5084
+ this.waiters.push({ resolve: resolve24, reject });
5083
5085
  });
5084
5086
  }
5085
5087
  };
@@ -5597,7 +5599,7 @@ var init_codex_app_server = __esm({
5597
5599
  async request(method, params, onActivity) {
5598
5600
  this.ensureTransport();
5599
5601
  const id = this.nextRequestId++;
5600
- const promise2 = new Promise((resolve22, reject) => {
5602
+ const promise2 = new Promise((resolve24, reject) => {
5601
5603
  const timer = setTimeout(() => {
5602
5604
  if (!this.pending.has(id)) return;
5603
5605
  this.pending.delete(id);
@@ -5614,7 +5616,7 @@ var init_codex_app_server = __esm({
5614
5616
  onActivity,
5615
5617
  resolve: (value) => {
5616
5618
  clearTimeout(timer);
5617
- resolve22(value);
5619
+ resolve24(value);
5618
5620
  },
5619
5621
  reject: (error62) => {
5620
5622
  clearTimeout(timer);
@@ -6450,7 +6452,7 @@ var init_kimi_code_auth = __esm({
6450
6452
  });
6451
6453
  let { status, data } = await post();
6452
6454
  if (REFRESH_RETRYABLE_STATUSES.has(status)) {
6453
- await new Promise((resolve22) => setTimeout(resolve22, 1e3));
6455
+ await new Promise((resolve24) => setTimeout(resolve24, 1e3));
6454
6456
  ({ status, data } = await post());
6455
6457
  }
6456
6458
  if (status === 200 && typeof data.access_token === "string") {
@@ -6784,14 +6786,14 @@ async function writeFileAtomic(path2, data, options = {}) {
6784
6786
  const { signal } = options;
6785
6787
  signal?.throwIfAborted();
6786
6788
  const tmp = tmpPath(path2);
6787
- const written = writeFileAsync(tmp, data);
6789
+ const written = writeFileAsync(tmp, data, { flag: "wx" });
6788
6790
  const modePromise = existingMode(path2);
6789
6791
  try {
6790
6792
  if (signal) {
6791
- await new Promise((resolve22, reject) => {
6793
+ await new Promise((resolve24, reject) => {
6792
6794
  const cancel = () => reject(signal.reason);
6793
6795
  signal.addEventListener("abort", cancel, { once: true });
6794
- void written.then(resolve22, reject).finally(() => signal.removeEventListener("abort", cancel));
6796
+ void written.then(resolve24, reject).finally(() => signal.removeEventListener("abort", cancel));
6795
6797
  if (signal.aborted) cancel();
6796
6798
  });
6797
6799
  } else {
@@ -6802,24 +6804,17 @@ async function writeFileAtomic(path2, data, options = {}) {
6802
6804
  if (mode !== void 0) await chmodAsync(tmp, mode);
6803
6805
  await renameAsync(tmp, path2);
6804
6806
  } catch (err) {
6805
- void written.then(
6806
- async () => {
6807
- try {
6808
- await unlinkAsync(tmp);
6809
- } catch {
6810
- }
6811
- },
6812
- async () => {
6813
- try {
6814
- await unlinkAsync(tmp);
6815
- } catch {
6816
- }
6807
+ const removeTemporary = async () => {
6808
+ try {
6809
+ await unlinkAsync(tmp);
6810
+ } catch {
6817
6811
  }
6812
+ };
6813
+ void written.then(
6814
+ removeTemporary,
6815
+ (error62) => error62?.code === "EEXIST" ? void 0 : removeTemporary()
6818
6816
  );
6819
- try {
6820
- await unlinkAsync(tmp);
6821
- } catch {
6822
- }
6817
+ if (err.code !== "EEXIST") await removeTemporary();
6823
6818
  throw err;
6824
6819
  }
6825
6820
  }
@@ -13082,15 +13077,23 @@ function missingRouterKeyMessage(target) {
13082
13077
  if (zergKeyOnly(target.provider)) return `Zerg Router has no key for ${name2}, so it cannot run this model. Choose another model with /model.`;
13083
13078
  return `Zerg Router has no ${name2} key for your account, so nothing was sent to ${name2}. ${routerKeyAdvice(target, `your ${name2} API key`)}`;
13084
13079
  }
13080
+ function unusableRouterKeyMessage(said, target) {
13081
+ const name2 = nameOf(target);
13082
+ if (!name2 || zergKeyOnly(target.provider)) return said;
13083
+ return `${said} ${routerKeyAdvice(target, `your new ${name2} API key`)}`;
13084
+ }
13085
13085
  function rejectedRouterKeyMessage(target) {
13086
13086
  const name2 = nameOf(target);
13087
13087
  return `${name2} didn't accept the key Zerg Router has for it on your account, so nothing came back. Check your ${name2} API key ${where(target)}, or pick another model.`;
13088
13088
  }
13089
- var PROVIDER_KEY_UNAVAILABLE, PERSONAL_ONLY_NAMES, ROUTER_PERSONAL_ONLY_PROVIDERS;
13089
+ var PROVIDER_KEY_UNAVAILABLE, PROVIDER_KEY_MALFORMED, PROVIDER_KEY_REJECTED, PROVIDER_KEY_REFUSALS, PERSONAL_ONLY_NAMES, ROUTER_PERSONAL_ONLY_PROVIDERS;
13090
13090
  var init_router_keys = __esm({
13091
13091
  "src/agent/backends/router_keys.ts"() {
13092
13092
  "use strict";
13093
13093
  PROVIDER_KEY_UNAVAILABLE = "provider_key_unavailable";
13094
+ PROVIDER_KEY_MALFORMED = "provider_key_malformed";
13095
+ PROVIDER_KEY_REJECTED = "provider_key_rejected";
13096
+ PROVIDER_KEY_REFUSALS = /* @__PURE__ */ new Set([PROVIDER_KEY_UNAVAILABLE, PROVIDER_KEY_MALFORMED, PROVIDER_KEY_REJECTED]);
13094
13097
  PERSONAL_ONLY_NAMES = Object.freeze({ morph: "Morph" });
13095
13098
  ROUTER_PERSONAL_ONLY_PROVIDERS = Object.freeze(Object.keys(PERSONAL_ONLY_NAMES));
13096
13099
  }
@@ -13148,6 +13151,12 @@ function readRouterRefusal(status, body, request2) {
13148
13151
  const named = request2 && providerNamed(fields, said) === request2.provider ? request2 : void 0;
13149
13152
  fallback = missingRouterKeyMessage({ provider: named?.provider, label: named?.providerLabel, credentialsUrl: request2?.credentialsUrl });
13150
13153
  ownWords = true;
13154
+ } else if ((code === PROVIDER_KEY_MALFORMED || code === PROVIDER_KEY_REJECTED) && dispatched === false) {
13155
+ kind = "lasting";
13156
+ const words = sentence(said || (code === PROVIDER_KEY_MALFORMED ? "The key Zerg Router holds for this provider was saved with a defect, so nothing was sent to it" : "The provider refused the key Zerg Router holds for it, so nothing was sent to it"));
13157
+ const named = request2 && providerNamed(fields, said) === request2.provider ? request2 : void 0;
13158
+ fallback = named ? unusableRouterKeyMessage(words, { provider: named.provider, label: named.providerLabel, credentialsUrl: named.credentialsUrl }) : words;
13159
+ ownWords = true;
13151
13160
  } else if (code && Object.hasOwn(ROUTER_USAGE_DENIALS, code) && dispatched !== true) {
13152
13161
  kind = code === CONCURRENCY ? "concurrency" : "lasting";
13153
13162
  fallback = ROUTER_USAGE_DENIALS[code];
@@ -13220,6 +13229,10 @@ function localRouterTime(at) {
13220
13229
  function sentence(text5) {
13221
13230
  return /[.!?…]$/.test(text5) ? text5 : `${text5}.`;
13222
13231
  }
13232
+ function withHttpStatus(label, status, provider = "") {
13233
+ const at = Number.isInteger(status) && status >= 400 && status <= 599 ? ` (HTTP ${status})` : "";
13234
+ return `${label}${at}${provider ? ` from ${provider}` : ""}`;
13235
+ }
13223
13236
  function formatRouterRefusal(refusal, now = Date.now(), retryAt) {
13224
13237
  let text5 = sentence(refusal.message);
13225
13238
  const resets = typeof refusal.resetsAt === "string" ? Date.parse(refusal.resetsAt) : NaN;
@@ -13227,7 +13240,9 @@ function formatRouterRefusal(refusal, now = Date.now(), retryAt) {
13227
13240
  else if (resets > now) text5 += ` Local reset: ${localRouterTime(resets)}.`;
13228
13241
  else if (refusal.resetsAt === void 0 && PERIOD_LIMITS.has(refusal.code)) text5 += ` ${WAIT_GUIDANCE}`;
13229
13242
  if (refusal.helpUrl && !text5.includes(refusal.helpUrl)) text5 += ` See ${refusal.helpUrl}.`;
13230
- return text5;
13243
+ if (PROVIDER_KEY_REFUSALS.has(refusal.code)) return text5;
13244
+ const label = refusal.kind !== "lasting" ? "Rate limit" : refusal.status === 429 ? "Plan limit" : "Router refused";
13245
+ return `${withHttpStatus(label, refusal.status)}: ${text5}`;
13231
13246
  }
13232
13247
  var ROUTER_COOLDOWN_TURN_WAIT_SECONDS, ROUTER_USAGE_REFUSED, RouterRefusalError, ROUTER_USAGE_DENIALS, CONCURRENCY, PERIOD_LIMITS, CREDIT, COOLDOWN, PLATFORM_TOKEN_QUOTA, PLATFORM_THROTTLE, PERIODS, ROUTER_TEXT_CHARS, WAIT_GUIDANCE, MISSING_KEY_SENTENCE;
13233
13248
  var init_router_refusal = __esm({
@@ -13362,15 +13377,16 @@ var init_router_gate = __esm({
13362
13377
  this.store?.released(hold);
13363
13378
  }
13364
13379
  /**
13365
- * Router's catalog, just sent for this route and account, lists as one it can run a model a hold for want of its
13366
- * provider's key (provider_key_unavailable) waited on: the key has been added, so that hold is over and the next
13380
+ * Router's catalog, just sent for this route and account, lists as one it can run a model a hold for want of a usable
13381
+ * key of its provider waited on (provider_key_unavailable, or a key stored broken or refused: provider_key_malformed,
13382
+ * provider_key_rejected): the key has been added or replaced, so that hold is over and the next
13367
13383
  * request for it reaches Router, a relayed one included. A model the catalog doesn't describe counts once any model
13368
13384
  * of its provider can run. Every other hold stays. Only a catalog Router has just sent says so, never a cached one.
13369
13385
  */
13370
13386
  keysListed(filter, catalog) {
13371
13387
  if (catalog.version !== 1) return;
13372
13388
  for (const [key, hold] of this.holds) {
13373
- if (hold.refusal.code !== PROVIDER_KEY_UNAVAILABLE || hold.route !== routerRoute(filter.route) || hold.account !== filter.account) continue;
13389
+ if (!PROVIDER_KEY_REFUSALS.has(hold.refusal.code) || hold.route !== routerRoute(filter.route) || hold.account !== filter.account) continue;
13374
13390
  const row = resolveRouterModel(catalog, hold.provider, hold.model);
13375
13391
  const runs = row ? row.available !== false : catalog.models.some((model) => model.owned_by === hold.provider && model.available !== false);
13376
13392
  if (!runs) continue;
@@ -13444,7 +13460,7 @@ var init_router_requests = __esm({
13444
13460
 
13445
13461
  // src/agent/backends/host_effort_policy.ts
13446
13462
  import { setTimeout as sleep } from "node:timers/promises";
13447
- async function applyHostEffortPolicy(request2, resolve22) {
13463
+ async function applyHostEffortPolicy(request2, resolve24) {
13448
13464
  const endpoint = process.env.ZTC_EFFORT_POLICY_URL;
13449
13465
  const token = process.env.ZTC_EFFORT_POLICY_TOKEN;
13450
13466
  if (!endpoint && !token) return request2;
@@ -13520,7 +13536,7 @@ async function applyHostEffortPolicy(request2, resolve22) {
13520
13536
  } else if (policy.model != null) {
13521
13537
  throw new Error("Invalid host model policy version");
13522
13538
  }
13523
- const resolved = await resolve22(model);
13539
+ const resolved = await resolve24(model);
13524
13540
  request2 = resolved.request;
13525
13541
  const supported = resolved.supported;
13526
13542
  if (policy.effort === "inherit") {
@@ -13610,7 +13626,7 @@ function routerLimits(profile, model) {
13610
13626
  };
13611
13627
  }
13612
13628
  function withTransportTurn(request2) {
13613
- return request2.transportTurnId ? request2 : { ...request2, transportTurnId: randomUUID4() };
13629
+ return request2.transportTurnId === void 0 ? { ...request2, transportTurnId: randomUUID4() } : request2;
13614
13630
  }
13615
13631
  async function fetchWithHeadersTimeout(fetcher, input2, init, timeoutMs) {
13616
13632
  const timeoutController = new AbortController();
@@ -13632,10 +13648,10 @@ function reconnectDelay(policy, attempt) {
13632
13648
  }
13633
13649
  async function waitForReconnect(delayMs, signal) {
13634
13650
  if (signal?.aborted) throw signal.reason;
13635
- await new Promise((resolve22, reject) => {
13651
+ await new Promise((resolve24, reject) => {
13636
13652
  const finish = () => {
13637
13653
  signal?.removeEventListener("abort", abort);
13638
- resolve22();
13654
+ resolve24();
13639
13655
  };
13640
13656
  const timeout = setTimeout(finish, delayMs);
13641
13657
  const abort = () => {
@@ -13688,7 +13704,8 @@ function routerFailure(status, body, options) {
13688
13704
  bodyReadState: options.bodyReadState,
13689
13705
  retryAfter,
13690
13706
  rateLimitReset: options.response?.headers.get("x-ratelimit-reset"),
13691
- turnEnded: options.turnEnded
13707
+ turnEnded: options.turnEnded,
13708
+ provider: options.provider
13692
13709
  });
13693
13710
  if (options.response) error63.message += failureHeaderSuffix(options.response);
13694
13711
  return error63;
@@ -14190,7 +14207,8 @@ var init_zrouter_stream = __esm({
14190
14207
  response,
14191
14208
  bodyReadState: failure2.bodyReadState,
14192
14209
  request: this.refusalRequest(),
14193
- ownSignIn: this.signInTarget()
14210
+ ownSignIn: this.signInTarget(),
14211
+ provider: this.provider
14194
14212
  });
14195
14213
  }
14196
14214
  const data = await response.json();
@@ -14288,7 +14306,7 @@ var init_zrouter_stream = __esm({
14288
14306
  headers,
14289
14307
  body,
14290
14308
  signal: request2.signal
14291
- }, Math.min(ZROUTER_HEADERS_TIMEOUT_MS, Math.max(1, remaining())));
14309
+ }, request2.transportTurnId ? Math.min(ZROUTER_HEADERS_TIMEOUT_MS, Math.max(1, remaining())) : ZROUTER_HEADERS_TIMEOUT_MS);
14292
14310
  if (!response.ok) {
14293
14311
  const failure2 = await readHttpErrorBody(response, request2.signal);
14294
14312
  throw routerFailure(response.status, routerErrorFrameBody(failure2.body), {
@@ -14296,7 +14314,8 @@ var init_zrouter_stream = __esm({
14296
14314
  response,
14297
14315
  bodyReadState: failure2.bodyReadState,
14298
14316
  request: this.refusalRequest(),
14299
- ownSignIn: this.signInTarget()
14317
+ ownSignIn: this.signInTarget(),
14318
+ provider: this.provider
14300
14319
  });
14301
14320
  }
14302
14321
  if (!response.body) {
@@ -14320,7 +14339,8 @@ var init_zrouter_stream = __esm({
14320
14339
  headers,
14321
14340
  turnEnded: true,
14322
14341
  request: this.refusalRequest(),
14323
- ownSignIn: this.signInTarget()
14342
+ ownSignIn: this.signInTarget(),
14343
+ provider: this.provider
14324
14344
  });
14325
14345
  }
14326
14346
  const mapped = mapEvent(ev);
@@ -14340,7 +14360,7 @@ var init_zrouter_stream = __esm({
14340
14360
  return;
14341
14361
  } catch (error62) {
14342
14362
  const retryable = !routerTurnEnded && !(error62 instanceof RouterRefusalError) && (error62 instanceof BackendHttpError ? resumeAfter !== void 0 && isRetryableResumeStatus(error62) : isTransportError(error62));
14343
- if (request2.signal?.aborted || !retryable || emittedMappedEvent && (!resumeSupported || !resumeAfter)) {
14363
+ if (request2.signal?.aborted || !retryable || !request2.transportTurnId || emittedMappedEvent && (!resumeSupported || !resumeAfter)) {
14344
14364
  throw error62;
14345
14365
  }
14346
14366
  reconnectStarted ??= Date.now();
@@ -15040,15 +15060,15 @@ var init_zlm_stdio = __esm({
15040
15060
  });
15041
15061
 
15042
15062
  // src/zlm.ts
15043
- import { realpathSync as realpathSync7 } from "node:fs";
15044
- import { resolve as resolve21 } from "node:path";
15063
+ import { realpathSync as realpathSync8 } from "node:fs";
15064
+ import { resolve as resolve23 } from "node:path";
15045
15065
  import { fileURLToPath as fileURLToPath3 } from "node:url";
15046
15066
 
15047
15067
  // src/agent/agent.ts
15048
15068
  import { createHash as createHash21, randomUUID as randomUUID13 } from "node:crypto";
15049
15069
  import { isDeepStrictEqual as isDeepStrictEqual4 } from "node:util";
15050
- import { existsSync as existsSync6, readFileSync as readFileSync11, realpathSync as realpathSync6 } from "fs";
15051
- import { extname, resolve as resolve18 } from "path";
15070
+ import { existsSync as existsSync6, readFileSync as readFileSync11, realpathSync as realpathSync7 } from "fs";
15071
+ import { extname, resolve as resolve20 } from "path";
15052
15072
 
15053
15073
  // src/session_handoff_contract.ts
15054
15074
  var TASK_HANDOFF_MAX_BYTES = 32 * 1024;
@@ -16356,7 +16376,7 @@ async function runShellCommand(command, cwd, signal, timeoutMs, sandboxOptions)
16356
16376
  let termination;
16357
16377
  const escalateKill = () => {
16358
16378
  if (termination) return;
16359
- termination = new Promise((resolve22) => {
16379
+ termination = new Promise((resolve24) => {
16360
16380
  if (child.pid) killGroup(child.pid, "SIGTERM");
16361
16381
  killTimer = setTimeout(() => {
16362
16382
  if (child.pid) {
@@ -16369,7 +16389,7 @@ async function runShellCommand(command, cwd, signal, timeoutMs, sandboxOptions)
16369
16389
  killGroup(child.pid, "SIGKILL");
16370
16390
  }
16371
16391
  }
16372
- resolve22();
16392
+ resolve24();
16373
16393
  }, executionPolicy.cleanup.term_grace_ms);
16374
16394
  });
16375
16395
  };
@@ -16557,9 +16577,10 @@ async function gitIdentity(cwd) {
16557
16577
  encoding: "utf8",
16558
16578
  env
16559
16579
  };
16580
+ const probe = ["-c", "core.fsmonitor=false", "-c", "safe.bareRepository=explicit"];
16560
16581
  const [head, status] = await Promise.all([
16561
- exec("git", ["rev-parse", "--verify", "HEAD"], options),
16562
- exec("git", ["-c", "core.fsmonitor=false", "status", "--porcelain=v1", "--untracked-files=normal"], options)
16582
+ exec("git", [...probe, "rev-parse", "--verify", "HEAD"], options),
16583
+ exec("git", [...probe, "status", "--porcelain=v1", "--untracked-files=normal"], options)
16563
16584
  ]);
16564
16585
  const commit = head.stdout.trim();
16565
16586
  return { commit: /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(commit) ? commit : null, dirty: status.stdout.length > 0 };
@@ -16997,8 +17018,8 @@ async function readCommandJob(sessionId, jobId, cursor = 0, waitMs = 0, signal,
16997
17018
  let timer;
16998
17019
  let onAbort;
16999
17020
  try {
17000
- await Promise.race([job.done, new Promise((resolve22, reject) => {
17001
- timer = setTimeout(resolve22, waitMs);
17021
+ await Promise.race([job.done, new Promise((resolve24, reject) => {
17022
+ timer = setTimeout(resolve24, waitMs);
17002
17023
  onAbort = () => reject(cancelled());
17003
17024
  signal?.addEventListener("abort", onAbort, { once: true });
17004
17025
  })]);
@@ -17051,7 +17072,7 @@ async function waitForCommandProgress(sessionId, jobId, options) {
17051
17072
  if (options.canInspectVerificationSource) job.canInspectVerificationSource = options.canInspectVerificationSource;
17052
17073
  const cancelled = () => new Error(`Command read cancelled; inspect job ${jobId} before retrying. The job may still be running.`);
17053
17074
  if (options.signal?.aborted) throw cancelled();
17054
- const progress = await new Promise((resolve22, reject) => {
17075
+ const progress = await new Promise((resolve24, reject) => {
17055
17076
  let settled = false;
17056
17077
  let timer;
17057
17078
  const cleanup = () => {
@@ -17077,7 +17098,7 @@ async function waitForCommandProgress(sessionId, jobId, options) {
17077
17098
  const reason = result2.status !== "running" ? "terminal" : result2.output.length > 0 ? "output" : deadline ? "deadline" : null;
17078
17099
  if (reason !== null) {
17079
17100
  cleanup();
17080
- resolve22({ reason, result: result2 });
17101
+ resolve24({ reason, result: result2 });
17081
17102
  }
17082
17103
  } catch (error62) {
17083
17104
  cleanup();
@@ -22328,7 +22349,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
22328
22349
  var NONE = 0;
22329
22350
  var ASSUMED = 1;
22330
22351
  var PROVEN = 2;
22331
- function isRecursive(inst, stack, resolve22) {
22352
+ function isRecursive(inst, stack, resolve24) {
22332
22353
  const cached3 = recursive.get(inst);
22333
22354
  if (cached3 !== void 0)
22334
22355
  return cached3 ? PROVEN : NONE;
@@ -22338,7 +22359,7 @@ function isRecursive(inst, stack, resolve22) {
22338
22359
  let result = NONE;
22339
22360
  const check2 = (child) => {
22340
22361
  if (result !== PROVEN && child?._zod) {
22341
- const answer = isRecursive(child, stack, resolve22);
22362
+ const answer = isRecursive(child, stack, resolve24);
22342
22363
  if (answer > result)
22343
22364
  result = answer;
22344
22365
  }
@@ -22349,7 +22370,7 @@ function isRecursive(inst, stack, resolve22) {
22349
22370
  const desc = Object.getOwnPropertyDescriptor(sh, key);
22350
22371
  if (spread && !desc.enumerable)
22351
22372
  continue;
22352
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve22) : NONE;
22373
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve24) : NONE;
22353
22374
  if (child > answer)
22354
22375
  answer = child;
22355
22376
  }
@@ -22413,7 +22434,7 @@ function isRecursive(inst, stack, resolve22) {
22413
22434
  break;
22414
22435
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
22415
22436
  case "lazy": {
22416
- const inner = def._cachedInner ?? (resolve22 ? inst._zod.innerType : void 0);
22437
+ const inner = def._cachedInner ?? (resolve24 ? inst._zod.innerType : void 0);
22417
22438
  merge2(inner ? isRecursive(inner, stack, false) : ASSUMED);
22418
22439
  break;
22419
22440
  }
@@ -37144,9 +37165,306 @@ function commandStillRunning(content2) {
37144
37165
  // src/agent/runtime/policy.ts
37145
37166
  init_capabilities();
37146
37167
  init_checked_commands();
37147
- import { realpathSync as realpathSync2 } from "node:fs";
37168
+ import { lstatSync as lstatSync4 } from "fs";
37148
37169
  import { homedir as homedir9 } from "os";
37149
- import { resolve as resolve9, isAbsolute as isAbsolute4, sep as sep3, dirname as dirname11, basename as basename4 } from "path";
37170
+ import { resolve as resolve11, isAbsolute as isAbsolute5, relative as relative3, sep as sep4 } from "path";
37171
+
37172
+ // src/utils/canonical_path.ts
37173
+ import { realpathSync as realpathSync2 } from "node:fs";
37174
+ import { basename as basename4, dirname as dirname11, resolve as resolve9 } from "node:path";
37175
+ function canonicalPath(absolute) {
37176
+ try {
37177
+ return realpathSync2.native(absolute);
37178
+ } catch (error62) {
37179
+ const code = error62.code;
37180
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error62;
37181
+ const parent = dirname11(absolute);
37182
+ if (parent === absolute) return absolute;
37183
+ return resolve9(canonicalPath(parent), basename4(absolute));
37184
+ }
37185
+ }
37186
+ var CASE_INSENSITIVE_BY_DEFAULT = process.platform === "darwin" || process.platform === "win32";
37187
+ var LONE_SURROGATE = new RegExp("\\p{Cs}", "u");
37188
+ var LONE_SURROGATES = new RegExp("\\p{Cs}", "gu");
37189
+ function isWellFormedText(text5) {
37190
+ return !LONE_SURROGATE.test(text5);
37191
+ }
37192
+ function sameFileKey(path2) {
37193
+ const composed = path2.replace(LONE_SURROGATES, "\uFFFD").normalize("NFC");
37194
+ return CASE_INSENSITIVE_BY_DEFAULT ? composed.toUpperCase().toLowerCase().normalize("NFC") : composed;
37195
+ }
37196
+
37197
+ // src/utils/git_directory_names.ts
37198
+ import { accessSync, closeSync as closeSync4, constants as constants3, fstatSync as fstatSync3, lstatSync as lstatSync3, openSync as openSync4, readlinkSync, readSync as readSync3, realpathSync as realpathSync3, statSync as statSync6 } from "fs";
37199
+ import { basename as basename5, dirname as dirname12, isAbsolute as isAbsolute4, join as join16, relative as relative2, resolve as resolve10, sep as sep3 } from "path";
37200
+ var HFS_IGNORED = /[‌-‏‪-‮-]/g;
37201
+ var GIT_DIRECTORY_NAME = /^(?:\.git|git~1)[. ]*(?::.*)?$/s;
37202
+ function isGitDirectoryName(name2) {
37203
+ return GIT_DIRECTORY_NAME.test(name2.replace(HFS_IGNORED, "").toLowerCase());
37204
+ }
37205
+ function gitDirectoryComponent(path2) {
37206
+ for (const component of path2.split(sep3 === "\\" ? /[\\/]/ : "/")) {
37207
+ if (isGitDirectoryName(component)) return component;
37208
+ }
37209
+ return null;
37210
+ }
37211
+ var MAX_POINTER_BYTES = 1024 * 1024;
37212
+ var MAX_HEAD_BYTES = 255;
37213
+ var MAX_WALK_LEVELS = 4096;
37214
+ var GIT_DIRECTORY_ENTRIES = new Set(["hooks", "info", "logs", "modules", "objects", "refs", "worktrees"].map(sameFileKey));
37215
+ var GIT_DIRECTORY_MAKERS = new Set(["HEAD", "commondir", "objects", "refs"].map(sameFileKey));
37216
+ var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
37217
+ function linkedGitDirectoryHolding(target, from) {
37218
+ const canonicalTarget = canonicalPath(resolve10(target));
37219
+ const key = sameFileKey(canonicalTarget);
37220
+ const repositories = linkedRepositories([...from, dirname12(canonicalTarget)]);
37221
+ for (const { workTree, directories } of repositories) {
37222
+ for (const directory2 of directories) {
37223
+ const root = sameFileKey(directory2);
37224
+ if (!isWithin(key, root, true)) continue;
37225
+ if (isWithin(sameFileKey(workTree), root, true) && !isGitDirectory(directory2)) {
37226
+ if (GIT_DIRECTORY_MAKERS.has(relative2(root, key).split(sep3)[0])) return directory2;
37227
+ continue;
37228
+ }
37229
+ if (!inOwnWorkTree(key, directory2, repositories)) return directory2;
37230
+ }
37231
+ }
37232
+ for (const directory2 of ancestorGitDirectories(dirname12(canonicalTarget))) {
37233
+ if (isWithin(key, sameFileKey(directory2), true) && !inOwnWorkTree(key, directory2, repositories)) return directory2;
37234
+ }
37235
+ return null;
37236
+ }
37237
+ function gitDirectoryPlantedByWriteSet(target, writeSet) {
37238
+ const index = writeSetIndex(writeSet);
37239
+ let path2 = canonicalPath(resolve10(target));
37240
+ for (let level = 0; level < MAX_WALK_LEVELS; level++) {
37241
+ if (GIT_DIRECTORY_MAKERS.has(sameFileKey(basename5(path2)))) {
37242
+ const directory2 = dirname12(path2);
37243
+ if (completesGitDirectory(directory2, index)) return directory2;
37244
+ }
37245
+ const parent = dirname12(path2);
37246
+ if (parent === path2) break;
37247
+ path2 = parent;
37248
+ }
37249
+ return null;
37250
+ }
37251
+ var WRITE_SET_INDEXES = /* @__PURE__ */ new WeakMap();
37252
+ function writeSetIndex(writeSet) {
37253
+ const known = WRITE_SET_INDEXES.get(writeSet);
37254
+ if (known !== void 0) return known;
37255
+ const written = /* @__PURE__ */ new Set();
37256
+ const holding = /* @__PURE__ */ new Set();
37257
+ for (const path2 of writeSet) {
37258
+ let key = sameFileKey(canonicalPath(resolve10(path2)));
37259
+ written.add(key);
37260
+ for (let level = 0; level < MAX_WALK_LEVELS && !holding.has(key); level++) {
37261
+ holding.add(key);
37262
+ const parent = dirname12(key);
37263
+ if (parent === key) break;
37264
+ key = parent;
37265
+ }
37266
+ }
37267
+ const index = { written, holding };
37268
+ WRITE_SET_INDEXES.set(writeSet, index);
37269
+ return index;
37270
+ }
37271
+ function writeSetWrites(index, path2) {
37272
+ return index.written.has(sameFileKey(canonicalPath(resolve10(path2))));
37273
+ }
37274
+ function writeSetWritesWithin(index, directory2) {
37275
+ return index.holding.has(sameFileKey(canonicalPath(resolve10(directory2))));
37276
+ }
37277
+ function existsOnDisk(path2) {
37278
+ try {
37279
+ lstatSync3(path2);
37280
+ return true;
37281
+ } catch {
37282
+ return false;
37283
+ }
37284
+ }
37285
+ function makerPresent(directory2, name2, index, asDirectory) {
37286
+ const path2 = join16(directory2, name2);
37287
+ if (asDirectory ? writeSetWritesWithin(index, path2) : writeSetWrites(index, path2)) return true;
37288
+ return existsOnDisk(path2);
37289
+ }
37290
+ function completesGitDirectory(directory2, index) {
37291
+ const head = join16(directory2, "HEAD");
37292
+ const hasHead = writeSetWrites(index, head) || validHead(head);
37293
+ if (!hasHead) return false;
37294
+ if (makerPresent(directory2, "commondir", index, false)) return true;
37295
+ return makerPresent(directory2, "objects", index, true) && makerPresent(directory2, "refs", index, true);
37296
+ }
37297
+ function inOwnWorkTree(key, directory2, repositories) {
37298
+ const root = sameFileKey(directory2);
37299
+ return repositories.some(({ workTree, directories: used }) => {
37300
+ const tree = sameFileKey(workTree);
37301
+ return used.includes(directory2) && isWithin(key, tree, false) && isWithin(tree, root, false) && !GIT_DIRECTORY_ENTRIES.has(relative2(root, tree).split(sep3)[0]);
37302
+ });
37303
+ }
37304
+ function ancestorGitDirectories(start) {
37305
+ const found = [];
37306
+ let directory2 = start;
37307
+ for (let level = 0; level < MAX_WALK_LEVELS; level++) {
37308
+ if (isGitDirectory(directory2)) found.push(directory2);
37309
+ const parent = dirname12(directory2);
37310
+ if (parent === directory2) break;
37311
+ directory2 = parent;
37312
+ }
37313
+ return found;
37314
+ }
37315
+ function isGitDirectory(directory2) {
37316
+ if (!validHead(join16(directory2, "HEAD"))) return false;
37317
+ const common = commonDirectory(directory2);
37318
+ if (common === UNREADABLE) return true;
37319
+ const base = common ?? directory2;
37320
+ return searchable(join16(base, "objects")) && searchable(join16(base, "refs"));
37321
+ }
37322
+ function validHead(path2) {
37323
+ let info;
37324
+ try {
37325
+ info = lstatSync3(path2);
37326
+ } catch {
37327
+ return false;
37328
+ }
37329
+ if (info.isSymbolicLink()) {
37330
+ try {
37331
+ return readlinkSync(path2).startsWith("refs/");
37332
+ } catch {
37333
+ return false;
37334
+ }
37335
+ }
37336
+ const read = readPointerFile(path2, MAX_HEAD_BYTES, true);
37337
+ if (typeof read !== "string") return false;
37338
+ const text5 = untilNul(read);
37339
+ return /^ref:[ \t\n\r]*refs\//.test(text5) || /^[0-9a-fA-F]{40}/.test(text5);
37340
+ }
37341
+ function searchable(path2) {
37342
+ try {
37343
+ accessSync(path2, constants3.X_OK);
37344
+ return true;
37345
+ } catch {
37346
+ return false;
37347
+ }
37348
+ }
37349
+ function isWithin(path2, root, orSame) {
37350
+ return orSame && path2 === root || path2.startsWith(root.endsWith(sep3) ? root : `${root}${sep3}`);
37351
+ }
37352
+ function linkedRepositories(directories) {
37353
+ const found = [];
37354
+ const visited = /* @__PURE__ */ new Set();
37355
+ for (const start of directories) {
37356
+ let directory2 = canonicalPath(resolve10(start));
37357
+ for (let level = 0; level < MAX_WALK_LEVELS && !visited.has(directory2); level++) {
37358
+ visited.add(directory2);
37359
+ const gitDirectory = dotGitDirectory(directory2);
37360
+ if (gitDirectory !== null) {
37361
+ const common = commonDirectory(gitDirectory);
37362
+ found.push({ workTree: directory2, directories: typeof common === "string" ? [gitDirectory, common] : [gitDirectory] });
37363
+ }
37364
+ const parent = dirname12(directory2);
37365
+ if (parent === directory2) break;
37366
+ directory2 = parent;
37367
+ }
37368
+ }
37369
+ return found;
37370
+ }
37371
+ function dotGitDirectory(directory2) {
37372
+ const dotGit = join16(directory2, ".git");
37373
+ let info;
37374
+ try {
37375
+ info = lstatSync3(dotGit);
37376
+ } catch {
37377
+ return null;
37378
+ }
37379
+ if (info.isDirectory()) return searchable(dotGit) ? reachablePath(dotGit) : null;
37380
+ if (info.isFile()) return gitFileDirectory(dotGit, directory2);
37381
+ if (!info.isSymbolicLink()) return null;
37382
+ let resolved;
37383
+ try {
37384
+ resolved = realpathSync3.native(dotGit);
37385
+ } catch (error62) {
37386
+ if (!isMissing(error62)) return null;
37387
+ let link;
37388
+ try {
37389
+ link = readlinkSync(dotGit);
37390
+ } catch {
37391
+ return null;
37392
+ }
37393
+ return reachablePath(isAbsolute4(link) ? link : `${directory2}${sep3}${link}`);
37394
+ }
37395
+ let target;
37396
+ try {
37397
+ target = lstatSync3(resolved);
37398
+ } catch {
37399
+ return null;
37400
+ }
37401
+ if (target.isFile()) return gitFileDirectory(resolved, directory2);
37402
+ return target.isDirectory() && searchable(resolved) ? resolved : null;
37403
+ }
37404
+ function gitFileDirectory(file2, directory2) {
37405
+ const text5 = readPointerFile(file2, MAX_POINTER_BYTES);
37406
+ if (typeof text5 !== "string" || !text5.startsWith("gitdir: ")) return null;
37407
+ const named = untilNul(text5.replace(/[\r\n]+$/, "")).slice("gitdir: ".length);
37408
+ if (named === "") return null;
37409
+ return reachablePath(isAbsolute4(named) ? named : `${directory2}${sep3}${named}`);
37410
+ }
37411
+ function commonDirectory(gitDirectory) {
37412
+ const path2 = join16(gitDirectory, "commondir");
37413
+ try {
37414
+ statSync6(path2);
37415
+ } catch {
37416
+ return null;
37417
+ }
37418
+ const text5 = readPointerFile(path2, MAX_POINTER_BYTES);
37419
+ if (text5 === null) return null;
37420
+ if (text5 === UNREADABLE) return UNREADABLE;
37421
+ const named = untilNul(text5.replace(/[\r\n]+$/, ""));
37422
+ if (named === "") return UNREADABLE;
37423
+ return reachablePath(isAbsolute4(named) ? named : `${gitDirectory}${sep3}${named}`) ?? UNREADABLE;
37424
+ }
37425
+ function untilNul(text5) {
37426
+ const nul = text5.indexOf("\0");
37427
+ return nul < 0 ? text5 : text5.slice(0, nul);
37428
+ }
37429
+ function reachablePath(path2) {
37430
+ try {
37431
+ return canonicalPath(path2);
37432
+ } catch {
37433
+ return null;
37434
+ }
37435
+ }
37436
+ function readPointerFile(path2, limit, truncate2 = false) {
37437
+ let fd;
37438
+ try {
37439
+ fd = openSync4(path2, constants3.O_RDONLY | (constants3.O_NONBLOCK ?? 0));
37440
+ } catch (error62) {
37441
+ if (isMissing(error62) || error62.code === "EISDIR") return null;
37442
+ return UNREADABLE;
37443
+ }
37444
+ try {
37445
+ const info = fstatSync3(fd);
37446
+ if (!info.isFile()) return null;
37447
+ if (info.size > limit && !truncate2) return UNREADABLE;
37448
+ const buffer = Buffer.alloc(Math.min(info.size, limit));
37449
+ let length = 0;
37450
+ while (length < buffer.length) {
37451
+ const read = readSync3(fd, buffer, length, buffer.length - length, length);
37452
+ if (read === 0) break;
37453
+ length += read;
37454
+ }
37455
+ return buffer.subarray(0, length).toString("utf8");
37456
+ } catch {
37457
+ return UNREADABLE;
37458
+ } finally {
37459
+ closeSync4(fd);
37460
+ }
37461
+ }
37462
+ function isMissing(error62) {
37463
+ const code = error62.code;
37464
+ return code === "ENOENT" || code === "ENOTDIR";
37465
+ }
37466
+
37467
+ // src/agent/runtime/policy.ts
37150
37468
  var AllowAllPolicy = class {
37151
37469
  evaluateTool() {
37152
37470
  return { allowed: true };
@@ -37156,6 +37474,8 @@ var CapabilityPolicy = class {
37156
37474
  permissions;
37157
37475
  profile;
37158
37476
  cwd;
37477
+ /** Each write set a caller names, resolved once, so admitting a call's N paths reads its set once, not N times. */
37478
+ resolvedWriteSets = /* @__PURE__ */ new WeakMap();
37159
37479
  constructor(permissions, profile, cwd = process.cwd()) {
37160
37480
  this.permissions = {
37161
37481
  file_read: true,
@@ -37184,6 +37504,10 @@ var CapabilityPolicy = class {
37184
37504
  if (!pathDecision.allowed) {
37185
37505
  return pathDecision;
37186
37506
  }
37507
+ const targetDecision = this.evaluateWriteTargets(request2);
37508
+ if (!targetDecision.allowed) {
37509
+ return targetDecision;
37510
+ }
37187
37511
  const shellDecision = this.evaluateShellPolicy(request2);
37188
37512
  if (!shellDecision.allowed) {
37189
37513
  return shellDecision;
@@ -37199,6 +37523,10 @@ var CapabilityPolicy = class {
37199
37523
  if (!this.profile || !request2.capabilities.some((capability) => capability === "file_read" /* FILE_READ */ || capability === "file_write" /* FILE_WRITE */)) {
37200
37524
  return { allowed: true };
37201
37525
  }
37526
+ const unreadable = nonStringPathArgument(request2.args);
37527
+ if (unreadable !== null) {
37528
+ return { allowed: false, reason: `Permission denied: path argument must be a string (${unreadable})` };
37529
+ }
37202
37530
  const paths = extractPathArgs(request2.args, request2.executionCwd);
37203
37531
  if (paths.length === 0) {
37204
37532
  return { allowed: true };
@@ -37206,9 +37534,12 @@ var CapabilityPolicy = class {
37206
37534
  const deniedRoots2 = (this.profile.deniedPaths || []).map((path2) => normalizeRoot2(path2, this.cwd));
37207
37535
  const allowedRoots2 = (this.profile.allowedPaths || []).map((path2) => normalizeRoot2(path2, this.cwd));
37208
37536
  for (const path2 of paths) {
37537
+ if (!isWellFormedText(path2)) {
37538
+ return { allowed: false, reason: `Permission denied: a path must be well-formed Unicode text (${JSON.stringify(path2)})` };
37539
+ }
37209
37540
  const absolutePath = normalizeRoot2(path2, this.cwd);
37210
37541
  const allowed = allowedRoots2.filter((root) => isWithinRoot(absolutePath, root));
37211
- const denied = deniedRoots2.filter((root) => isWithinRoot(absolutePath, root));
37542
+ const denied = deniedRoots2.filter((root) => isWithinRoot(sameFileKey(absolutePath), sameFileKey(root)));
37212
37543
  const exception = this.profile.pathPrecedence === "specific" && allowed.some((root) => denied.every((blocked) => root.length > blocked.length));
37213
37544
  if (denied.length > 0 && !exception) {
37214
37545
  return {
@@ -37225,13 +37556,71 @@ var CapabilityPolicy = class {
37225
37556
  }
37226
37557
  return { allowed: true };
37227
37558
  }
37559
+ /**
37560
+ * Rules for the files a call writes, under a profile that limits the agent. Such a write may not reach git's own
37561
+ * directory: a setting there (a filter, core.fsmonitor) is a command any git ZTC starts in that work tree runs as
37562
+ * ZTC, outside the profile and any OS sandbox. Nor may it replace an allowed root itself when that root is a
37563
+ * directory (or does not exist yet), since an atomic write makes its temporary file beside its target, which for
37564
+ * such a root is outside it.
37565
+ */
37566
+ evaluateWriteTargets(request2) {
37567
+ if (request2.writeTargets !== true || !this.limitsAgent()) {
37568
+ return { allowed: true };
37569
+ }
37570
+ const allowed = this.profile?.allowedPaths || [];
37571
+ const allowedRoots2 = allowed.map((path2) => normalizeRoot2(path2, this.cwd));
37572
+ const spelledRoots = allowed.map((path2) => resolve11(this.cwd, expandHome(path2)));
37573
+ const writeSet = request2.writeSet === void 0 ? extractPathArgs(request2.args, request2.executionCwd).map((path2) => resolve11(this.cwd, expandHome(path2))) : this.resolvedWriteSet(request2.writeSet);
37574
+ for (const path2 of extractPathArgs(request2.args, request2.executionCwd)) {
37575
+ if (!isWellFormedText(path2)) {
37576
+ return { allowed: false, reason: `Permission denied: a path must be well-formed Unicode text (${JSON.stringify(path2)})` };
37577
+ }
37578
+ const canonical = normalizeRoot2(path2, this.cwd);
37579
+ if (allowedRoots2.includes(canonical) && !isRegularFile(canonical)) {
37580
+ return { allowed: false, reason: `Permission denied: a write cannot replace an allowed root itself (${path2})` };
37581
+ }
37582
+ const spelled = resolve11(this.cwd, expandHome(path2));
37583
+ const gitDirectory = gitDirectoryComponent(belowRoot(spelled, spelledRoots)) ?? gitDirectoryComponent(belowRoot(canonical, allowedRoots2)) ?? linkedGitDirectoryHolding(canonical, [this.cwd]);
37584
+ if (gitDirectory !== null) {
37585
+ return {
37586
+ allowed: false,
37587
+ reason: `Permission denied: path is inside a git directory (${gitDirectory}), which a confined write may not change (${path2})`
37588
+ };
37589
+ }
37590
+ const planted = gitDirectoryPlantedByWriteSet(spelled, writeSet);
37591
+ if (planted !== null) {
37592
+ return {
37593
+ allowed: false,
37594
+ reason: `Permission denied: this write would make a git directory (${planted}), which a confined write may not create (${path2})`
37595
+ };
37596
+ }
37597
+ }
37598
+ return { allowed: true };
37599
+ }
37600
+ /** `named` resolved against this policy's working directory, once per array (a fresh one each admission pass). */
37601
+ resolvedWriteSet(named) {
37602
+ let resolved = this.resolvedWriteSets.get(named);
37603
+ if (resolved === void 0) {
37604
+ resolved = named.map((path2) => resolve11(this.cwd, expandHome(path2)));
37605
+ this.resolvedWriteSets.set(named, resolved);
37606
+ }
37607
+ return resolved;
37608
+ }
37609
+ /** Whether the agent works under limits that a command run through git could step past: paths or shell. */
37610
+ limitsAgent() {
37611
+ const profile = this.profile;
37612
+ if (this.permissions.shell_exec === false) return true;
37613
+ if (!profile) return false;
37614
+ return Boolean(profile.allowedPaths?.length || profile.deniedPaths?.length || profile.allowedShellCommands?.length || profile.deniedShellCommands?.length) || profile.capabilities?.shell_exec === false || profile.approvalRequiredCapabilities?.includes("shell_exec" /* SHELL_EXEC */) === true;
37615
+ }
37228
37616
  evaluateShellPolicy(request2) {
37229
37617
  if (!this.profile || !request2.capabilities.includes("shell_exec" /* SHELL_EXEC */)) {
37230
37618
  return { allowed: true };
37231
37619
  }
37232
- const checked = Object.hasOwn(request2.args, "checked") ? parseCheckedCommandPlan(request2.args.checked) : void 0;
37620
+ const declared = request2.executionCommand;
37621
+ const checked = declared === void 0 && Object.hasOwn(request2.args, "checked") ? parseCheckedCommandPlan(request2.args.checked) : void 0;
37233
37622
  if (checked === null) return { allowed: false, reason: "Permission denied: invalid checked command plan" };
37234
- const commands = checked ? checked.steps.flatMap((step) => step.pipeline.map(formatCheckedStageCommand)) : [typeof request2.args.command === "string" ? request2.args.command.trim() : ""];
37623
+ const commands = declared !== void 0 ? [declared.trim()] : checked ? checked.steps.flatMap((step) => step.pipeline.map(formatCheckedStageCommand)) : [typeof request2.args.command === "string" ? request2.args.command.trim() : ""];
37235
37624
  const denied = this.profile.deniedShellCommands || [];
37236
37625
  const allowed = this.profile.allowedShellCommands || [];
37237
37626
  for (const command of commands) {
@@ -37255,7 +37644,7 @@ var CapabilityPolicy = class {
37255
37644
  if (!this.profile || !request2.capabilities.includes("network" /* NETWORK */)) {
37256
37645
  return { allowed: true };
37257
37646
  }
37258
- const hosts = extractNetworkHosts(request2.args);
37647
+ const hosts = extractNetworkHosts(request2.args, request2.executionCommand);
37259
37648
  if (hosts.length === 0) {
37260
37649
  return { allowed: true };
37261
37650
  }
@@ -37278,16 +37667,18 @@ var CapabilityPolicy = class {
37278
37667
  return { allowed: true };
37279
37668
  }
37280
37669
  };
37670
+ var PATH_ARGUMENTS = ["path", "file_path", "filepath", "directory", "cwd", "workdir", "repo_path", "artifact_path"];
37671
+ function nonStringPathArgument(args) {
37672
+ for (const key of PATH_ARGUMENTS) {
37673
+ const value = args[key];
37674
+ if (value !== void 0 && value !== null && typeof value !== "string") return key;
37675
+ }
37676
+ const list2 = args.paths;
37677
+ if (list2 === void 0 || list2 === null) return null;
37678
+ return Array.isArray(list2) && list2.every((value) => typeof value === "string") ? null : "paths";
37679
+ }
37281
37680
  function extractPathArgs(args, executionCwd) {
37282
- const candidates = [
37283
- "path",
37284
- "file_path",
37285
- "filepath",
37286
- "directory",
37287
- ...executionCwd === void 0 ? ["cwd", "workdir"] : [],
37288
- "repo_path",
37289
- "artifact_path"
37290
- ];
37681
+ const candidates = PATH_ARGUMENTS.filter((key) => executionCwd === void 0 || key !== "cwd" && key !== "workdir");
37291
37682
  const paths = executionCwd === void 0 ? [] : [executionCwd];
37292
37683
  for (const key of candidates) {
37293
37684
  const value = args[key];
@@ -37305,14 +37696,31 @@ function extractPathArgs(args, executionCwd) {
37305
37696
  }
37306
37697
  return paths;
37307
37698
  }
37699
+ function expandHome(path2) {
37700
+ return path2 === "~" ? homedir9() : path2.replace(/^~(?=\/|$)/, homedir9());
37701
+ }
37308
37702
  function normalizeRoot2(path2, cwd) {
37309
- const expanded = path2 === "~" ? homedir9() : path2.replace(/^~(?=\/|$)/, homedir9());
37310
- return canonicalPolicyPath(resolve9(isAbsolute4(expanded) ? expanded : resolve9(cwd, expanded)), cwd);
37703
+ const expanded = expandHome(path2);
37704
+ return canonicalPolicyPath(resolve11(isAbsolute5(expanded) ? expanded : resolve11(cwd, expanded)), cwd);
37311
37705
  }
37312
37706
  function isWithinRoot(path2, root) {
37313
- return path2 === root || path2.startsWith(root.endsWith(sep3) ? root : `${root}${sep3}`);
37707
+ return path2 === root || path2.startsWith(root.endsWith(sep4) ? root : `${root}${sep4}`);
37708
+ }
37709
+ function belowRoot(path2, roots) {
37710
+ let holder;
37711
+ for (const root of roots) {
37712
+ if (isWithinRoot(path2, root) && (holder === void 0 || root.length > holder.length)) holder = root;
37713
+ }
37714
+ return holder === void 0 ? path2 : relative3(holder, path2);
37715
+ }
37716
+ function isRegularFile(path2) {
37717
+ try {
37718
+ return lstatSync4(path2).isFile();
37719
+ } catch {
37720
+ return false;
37721
+ }
37314
37722
  }
37315
- function extractNetworkHosts(args) {
37723
+ function extractNetworkHosts(args, executionCommand) {
37316
37724
  const hosts = /* @__PURE__ */ new Set();
37317
37725
  const candidates = ["url", "uri", "endpoint", "host", "hostname", "base_url", "baseUrl"];
37318
37726
  for (const key of candidates) {
@@ -37321,7 +37729,7 @@ function extractNetworkHosts(args) {
37321
37729
  addHost(hosts, value);
37322
37730
  }
37323
37731
  }
37324
- const command = typeof args.command === "string" ? args.command : "";
37732
+ const command = executionCommand ?? (typeof args.command === "string" ? args.command : "");
37325
37733
  for (const match of command.matchAll(/https?:\/\/[^\s'"<>]+/gi)) {
37326
37734
  addHost(hosts, match[0]);
37327
37735
  }
@@ -37354,17 +37762,7 @@ function hostMatchesPattern(host, pattern) {
37354
37762
  return normalizedHost === normalizedPattern;
37355
37763
  }
37356
37764
  function canonicalPolicyPath(path2, cwd) {
37357
- const expanded = path2 === "~" ? homedir9() : path2.replace(/^~(?=\/|$)/, homedir9());
37358
- const absolute = resolve9(cwd, expanded);
37359
- try {
37360
- return realpathSync2(absolute);
37361
- } catch (error62) {
37362
- const code = error62.code;
37363
- if (code !== "ENOENT" && code !== "ENOTDIR") throw error62;
37364
- const parent = dirname11(absolute);
37365
- if (parent === absolute) return absolute;
37366
- return resolve9(canonicalPolicyPath(parent, cwd), basename4(absolute));
37367
- }
37765
+ return canonicalPath(resolve11(cwd, expandHome(path2)));
37368
37766
  }
37369
37767
 
37370
37768
  // src/agent/runtime/tracing.ts
@@ -37687,9 +38085,128 @@ function parseDiagnosticSnapshot(value) {
37687
38085
  return null;
37688
38086
  }
37689
38087
  }
38088
+ var REDACTION_MARKER = /\[REDACTED(?: [A-Z ]+)?\]/;
38089
+ function redactionCompatible(prior, current, truncated) {
38090
+ if (prior === current) return true;
38091
+ const segments = prior.split(REDACTION_MARKER);
38092
+ if (segments.length === 1) return false;
38093
+ const first = segments[0];
38094
+ if (!current.startsWith(first)) return truncated && first.startsWith(current);
38095
+ let position = first.length;
38096
+ for (let index = 1; index < segments.length; index++) {
38097
+ const segment = segments[index];
38098
+ if (index === segments.length - 1) {
38099
+ const tail = current.slice(position);
38100
+ if (tail.length === 0) return false;
38101
+ if (truncated || segment === "") return true;
38102
+ return current.endsWith(segment) && current.length - segment.length > position;
38103
+ }
38104
+ const found = current.indexOf(segment, position + 1);
38105
+ if (found === -1) return truncated;
38106
+ position = found + segment.length;
38107
+ }
38108
+ return false;
38109
+ }
38110
+ function redactionMatches(a, b, truncated) {
38111
+ return redactionCompatible(a, b, truncated) || redactionCompatible(b, a, truncated);
38112
+ }
38113
+ function redactionJsonCompatible(prior, current) {
38114
+ if (prior === current) return true;
38115
+ if (typeof prior === "string" && typeof current === "string") return redactionMatches(prior, current, false);
38116
+ if (Array.isArray(prior) && Array.isArray(current)) {
38117
+ return prior.length === current.length && prior.every((item, index) => redactionJsonCompatible(item, current[index]));
38118
+ }
38119
+ if (isObject2(prior) && isObject2(current)) {
38120
+ const keys3 = Object.keys(prior);
38121
+ return keys3.length === Object.keys(current).length && keys3.every((key) => Object.hasOwn(current, key) && redactionJsonCompatible(prior[key], current[key]));
38122
+ }
38123
+ return false;
38124
+ }
38125
+ function contentTruncated(event) {
38126
+ return (event.truncations ?? []).some((row) => row.field === "content");
38127
+ }
38128
+ function redactionData(event) {
38129
+ if (event.data === void 0) return void 0;
38130
+ const data = { ...event.data };
38131
+ if (typeof data.isStreaming === "boolean") delete data.isStreaming;
38132
+ return Object.keys(data).length ? data : void 0;
38133
+ }
38134
+ function redactionEquivalent(prior, current) {
38135
+ const truncated = contentTruncated(prior) || contentTruncated(current);
38136
+ if (!redactionMatches(prior.content ?? "", current.content ?? "", truncated)) return false;
38137
+ for (const field of ["storedRole", "toolCallId", "toolName", "status"]) {
38138
+ const before = prior[field];
38139
+ const after = current[field];
38140
+ if (before === after) continue;
38141
+ if (typeof before !== "string" || typeof after !== "string") return false;
38142
+ if (!redactionMatches(before, after, false)) return false;
38143
+ }
38144
+ return redactionJsonCompatible(redactionData(prior), redactionData(current)) && redactionJsonCompatible(prior.args, current.args);
38145
+ }
38146
+ function redactionDrift(prior, current) {
38147
+ return prior.timestamp === current.timestamp && prior.data?.isStreaming === current.data?.isStreaming && redactionEquivalent(prior, current);
38148
+ }
38149
+ function redactionMarkers(event) {
38150
+ const text5 = `${event.content ?? ""}
38151
+ ${JSON.stringify(event.data ?? null)}
38152
+ ${JSON.stringify(event.args ?? null)}`;
38153
+ return text5.split(REDACTION_MARKER).length - 1;
38154
+ }
38155
+ function moreMasked(prior, current) {
38156
+ const truncated = contentTruncated(prior) || contentTruncated(current);
38157
+ const priorCovers = redactionCompatible(prior.content ?? "", current.content ?? "", truncated);
38158
+ if (priorCovers !== redactionCompatible(current.content ?? "", prior.content ?? "", truncated)) return priorCovers ? prior : current;
38159
+ return redactionMarkers(prior) >= redactionMarkers(current) ? prior : current;
38160
+ }
38161
+ function mergeMaskedText(prior, current) {
38162
+ const priorMasked = REDACTION_MARKER.test(prior);
38163
+ const currentMasked = REDACTION_MARKER.test(current);
38164
+ if (priorMasked !== currentMasked) return priorMasked ? prior : current;
38165
+ if (!priorMasked) return current;
38166
+ const priorCovers = redactionCompatible(prior, current, false);
38167
+ if (priorCovers !== redactionCompatible(current, prior, false)) return priorCovers ? prior : current;
38168
+ return prior.split(REDACTION_MARKER).length >= current.split(REDACTION_MARKER).length ? prior : current;
38169
+ }
38170
+ function mergeMasked(prior, current) {
38171
+ if (prior === void 0) return current;
38172
+ if (current === void 0) return prior;
38173
+ if (prior === current) return prior;
38174
+ if (typeof prior === "string" && typeof current === "string") return mergeMaskedText(prior, current);
38175
+ if (Array.isArray(prior) && Array.isArray(current)) {
38176
+ if (prior.length !== current.length) return current;
38177
+ return prior.map((item, index) => mergeMasked(item, current[index]));
38178
+ }
38179
+ if (isObject2(prior) && isObject2(current)) {
38180
+ const merged = { ...prior };
38181
+ for (const [key, value] of Object.entries(current)) {
38182
+ merged[key] = Object.hasOwn(prior, key) ? mergeMasked(prior[key], value) : value;
38183
+ }
38184
+ return merged;
38185
+ }
38186
+ return current;
38187
+ }
38188
+ function mergeAuthoredProof(prior, current, base) {
38189
+ const observedStreaming = prior.data?.isStreaming === false || current.data?.isStreaming === false ? false : prior.data?.isStreaming ?? current.data?.isStreaming;
38190
+ const merged = mergeMasked(prior.data, current.data);
38191
+ const data = {
38192
+ ...isObject2(merged) ? merged : {},
38193
+ ...observedStreaming === void 0 ? {} : { isStreaming: observedStreaming }
38194
+ };
38195
+ const reconciled = { ...base, timestamp: prior.timestamp ?? current.timestamp };
38196
+ const content2 = mergeMasked(prior.content, current.content);
38197
+ if (typeof content2 === "string") reconciled.content = content2;
38198
+ else delete reconciled.content;
38199
+ const args = mergeMasked(prior.args, current.args);
38200
+ if (args === void 0) delete reconciled.args;
38201
+ else reconciled.args = args;
38202
+ if (Object.keys(data).length) reconciled.data = data;
38203
+ else delete reconciled.data;
38204
+ return reconciled;
38205
+ }
37690
38206
  function reconcileCheckpointFact(prior, current) {
37691
38207
  if (diagnosticIdentity(prior) === diagnosticIdentity(current)) return prior;
37692
- const sameSource = prior.kind === current.kind && prior.origin === current.origin && prior.storedRole === current.storedRole && prior.toolCallId === current.toolCallId && prior.toolName === current.toolName;
38208
+ const sameText = (before, after) => before === after || typeof before === "string" && typeof after === "string" && redactionMatches(before, after, false);
38209
+ const sameSource = prior.kind === current.kind && prior.origin === current.origin && sameText(prior.storedRole, current.storedRole) && sameText(prior.toolCallId, current.toolCallId) && sameText(prior.toolName, current.toolName);
37693
38210
  if (!sameSource) throw new DiagnosticExportError(`Diagnostic canonical identity conflict: ${current.id}`, "INVALID_EXPORT");
37694
38211
  if (current.kind === "assistant" || current.kind === "reasoning") {
37695
38212
  const authoredFacts = (event) => {
@@ -37701,42 +38218,40 @@ function reconcileCheckpointFact(prior, current) {
37701
38218
  }
37702
38219
  return diagnosticIdentity(fact);
37703
38220
  };
37704
- if (authoredFacts(prior) === authoredFacts(current)) {
37705
- const observedStreaming = prior.data?.isStreaming === false || current.data?.isStreaming === false ? false : prior.data?.isStreaming ?? current.data?.isStreaming;
37706
- const data = {
37707
- ...prior.data,
37708
- ...current.data,
37709
- ...observedStreaming === void 0 ? {} : { isStreaming: observedStreaming }
37710
- };
37711
- const reconciled = { ...prior, timestamp: prior.timestamp ?? current.timestamp };
37712
- if (Object.keys(data).length) reconciled.data = data;
37713
- else delete reconciled.data;
37714
- return reconciled;
37715
- }
38221
+ if (authoredFacts(prior) === authoredFacts(current)) return mergeAuthoredProof(prior, current, prior);
38222
+ if (redactionEquivalent(prior, current)) return mergeAuthoredProof(prior, current, moreMasked(prior, current));
37716
38223
  }
37717
38224
  if (current.kind === "tool_invocation") {
37718
38225
  const terminal = (status) => status === "complete" || status === "error";
38226
+ const sameArgs = diagnosticIdentity(prior.args) === diagnosticIdentity(current.args);
38227
+ const maskedArgs = !sameArgs && redactionJsonCompatible(prior.args, current.args);
38228
+ const masked = (event) => maskedArgs ? { ...event, args: mergeMasked(prior.args, current.args) } : event;
37719
38229
  if (terminal(prior.status)) {
37720
- if (!terminal(current.status)) return prior;
37721
- if (prior.status !== current.status || diagnosticIdentity(prior.args) !== diagnosticIdentity(current.args)) {
38230
+ if (!terminal(current.status)) return masked(prior);
38231
+ if (prior.status !== current.status || !(sameArgs || maskedArgs)) {
37722
38232
  throw new DiagnosticExportError(`Diagnostic settled invocation identity conflict: ${current.id}`, "INVALID_EXPORT");
37723
38233
  }
37724
- if (diagnosticIdentity(prior.data) === diagnosticIdentity(current.data)) return prior;
37725
- if (prior.data?.completedAt === current.data?.completedAt) return { ...current, data: { ...prior.data, ...current.data } };
37726
- if (prior.data?.completedAt === null && typeof current.data?.completedAt === "string") return current;
37727
- if (current.data?.completedAt === null) return prior;
37728
- } else if (prior.status === "running" && current.status === "pending") return prior;
38234
+ if (diagnosticIdentity(prior.data) === diagnosticIdentity(current.data)) return masked(prior);
38235
+ if (prior.data?.completedAt === current.data?.completedAt) return masked({ ...current, data: { ...prior.data, ...current.data } });
38236
+ if (prior.data?.completedAt === null && typeof current.data?.completedAt === "string") return masked(current);
38237
+ if (current.data?.completedAt === null) return masked(prior);
38238
+ } else if (prior.status === "running" && current.status === "pending") return masked(prior);
37729
38239
  else if (["pending", "running", "complete", "error"].includes(current.status ?? "")) {
37730
- return { ...current, data: {
38240
+ return masked({ ...current, data: {
37731
38241
  ...current.data,
37732
- ...diagnosticIdentity(prior.args) === diagnosticIdentity(current.args) ? {} : {
38242
+ ...sameArgs || maskedArgs ? {} : {
37733
38243
  argumentsUpdatedFromPriorCheckpoint: true,
37734
38244
  argumentsSource: "latest canonical checkpoint; model proposal can differ from admitted execution input"
37735
38245
  }
37736
- } };
38246
+ } });
37737
38247
  }
37738
38248
  }
37739
38249
  if (current.kind === "tool_result" && prior.status === current.status) {
38250
+ const larger = bytes3(prior.content ?? "") >= bytes3(current.content ?? "") ? prior : current;
38251
+ const markers = (event) => (event.content ?? "").split(REDACTION_MARKER).length - 1;
38252
+ if (markers(larger) < markers(larger === prior ? current : prior) && redactionDrift(prior, current)) {
38253
+ return mergeAuthoredProof(prior, current, moreMasked(prior, current));
38254
+ }
37740
38255
  const sourceIdentity = (event) => event.truncations?.find((row) => row.field === "content")?.sha256 ?? (event.content === void 0 ? null : sha2(event.content));
37741
38256
  const priorIdentity = sourceIdentity(prior);
37742
38257
  const currentIdentity = sourceIdentity(current);
@@ -37748,6 +38263,7 @@ function reconcileCheckpointFact(prior, current) {
37748
38263
  }
37749
38264
  }
37750
38265
  if ((current.kind === "assistant" || current.kind === "reasoning") && prior.data?.isStreaming === true) return current;
38266
+ if (redactionDrift(prior, current)) return mergeAuthoredProof(prior, current, moreMasked(prior, current));
37751
38267
  throw new DiagnosticExportError(`Diagnostic canonical identity conflict: ${current.id}`, "INVALID_EXPORT");
37752
38268
  }
37753
38269
 
@@ -38004,12 +38520,12 @@ init_evidence();
38004
38520
  init_atomic_write();
38005
38521
 
38006
38522
  // src/utils/path_lock.ts
38007
- import { realpathSync as realpathSync3 } from "fs";
38008
- import { basename as basename5, dirname as dirname12, join as join16 } from "path";
38523
+ import { realpathSync as realpathSync4 } from "fs";
38524
+ import { basename as basename6, dirname as dirname13, join as join17 } from "path";
38009
38525
  var chains = /* @__PURE__ */ new Map();
38010
38526
  function canonicalKey2(path2) {
38011
38527
  try {
38012
- return join16(realpathSync3(dirname12(path2)), basename5(path2));
38528
+ return join17(realpathSync4(dirname13(path2)), basename6(path2));
38013
38529
  } catch {
38014
38530
  return path2;
38015
38531
  }
@@ -38031,25 +38547,25 @@ function withPathLock(path2, fn) {
38031
38547
  // src/session_media.ts
38032
38548
  import { createHash as createHash13, randomUUID as randomUUID9 } from "node:crypto";
38033
38549
  import {
38034
- closeSync as closeSync4,
38035
- constants as constants3,
38036
- fstatSync as fstatSync3,
38037
- lstatSync as lstatSync3,
38038
- openSync as openSync4,
38039
- readSync as readSync3,
38040
- realpathSync as realpathSync4
38550
+ closeSync as closeSync5,
38551
+ constants as constants4,
38552
+ fstatSync as fstatSync4,
38553
+ lstatSync as lstatSync5,
38554
+ openSync as openSync5,
38555
+ readSync as readSync4,
38556
+ realpathSync as realpathSync5
38041
38557
  } from "node:fs";
38042
- import { basename as basename6, dirname as dirname13, isAbsolute as isAbsolute5, join as join18, resolve as resolve11, sep as sep5 } from "node:path";
38558
+ import { basename as basename7, dirname as dirname14, isAbsolute as isAbsolute6, join as join19, resolve as resolve13, sep as sep6 } from "node:path";
38043
38559
 
38044
38560
  // src/utils/mirror_media.ts
38045
38561
  import { tmpdir as tmpdir3 } from "os";
38046
- import { join as join17, resolve as resolve10, sep as sep4 } from "path";
38047
- var MIRROR_MEDIA_ROOT = join17(tmpdir3(), "ztc-mirror-media");
38562
+ import { join as join18, resolve as resolve12, sep as sep5 } from "path";
38563
+ var MIRROR_MEDIA_ROOT = join18(tmpdir3(), "ztc-mirror-media");
38048
38564
  function isMirrorMediaPath(localPath) {
38049
38565
  if (!localPath) return false;
38050
- const root = resolve10(MIRROR_MEDIA_ROOT);
38051
- const target = resolve10(localPath);
38052
- return target === root || target.startsWith(root + sep4);
38566
+ const root = resolve12(MIRROR_MEDIA_ROOT);
38567
+ const target = resolve12(localPath);
38568
+ return target === root || target.startsWith(root + sep5);
38053
38569
  }
38054
38570
 
38055
38571
  // src/session_media.ts
@@ -38073,10 +38589,10 @@ function record10(value) {
38073
38589
  return value !== null && typeof value === "object" && !Array.isArray(value);
38074
38590
  }
38075
38591
  function canonicalCheckpoint(path2) {
38076
- if (!isAbsolute5(path2) || /[\u0000-\u001f\u007f]/u.test(path2)) {
38592
+ if (!isAbsolute6(path2) || /[\u0000-\u001f\u007f]/u.test(path2)) {
38077
38593
  throw new SessionMediaError("invalid_reference", "Image checkpoint must be an absolute canonical file path.");
38078
38594
  }
38079
- return join18(realpathSync4(dirname13(path2)), basename6(path2));
38595
+ return join19(realpathSync5(dirname14(path2)), basename7(path2));
38080
38596
  }
38081
38597
  function imageType(data) {
38082
38598
  if (data.length >= 8 && data.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) {
@@ -38097,19 +38613,19 @@ function sha2562(data) {
38097
38613
  return createHash13("sha256").update(data).digest("hex");
38098
38614
  }
38099
38615
  function checkedDirectory(path2) {
38100
- const stat5 = lstatSync3(path2);
38616
+ const stat5 = lstatSync5(path2);
38101
38617
  if (!stat5.isDirectory() || stat5.isSymbolicLink()) {
38102
38618
  throw new SessionMediaError("invalid_reference", "Image storage directory is not an owned regular directory.");
38103
38619
  }
38104
38620
  }
38105
38621
  function boundedRead(path2, maximum) {
38106
- const before = lstatSync3(path2);
38622
+ const before = lstatSync5(path2);
38107
38623
  if (!before.isFile() || before.isSymbolicLink()) {
38108
38624
  throw new SessionMediaError("invalid_reference", "Image or checkpoint reference is not a regular nonsymlink file.");
38109
38625
  }
38110
- const fd = openSync4(path2, constants3.O_RDONLY | (constants3.O_NOFOLLOW ?? 0));
38626
+ const fd = openSync5(path2, constants4.O_RDONLY | (constants4.O_NOFOLLOW ?? 0));
38111
38627
  try {
38112
- const stat5 = fstatSync3(fd);
38628
+ const stat5 = fstatSync4(fd);
38113
38629
  if (!stat5.isFile() || stat5.dev !== before.dev || stat5.ino !== before.ino) {
38114
38630
  throw new SessionMediaError("invalid_reference", "Image reference changed while it was being opened.");
38115
38631
  }
@@ -38121,7 +38637,7 @@ function boundedRead(path2, maximum) {
38121
38637
  let length = 0;
38122
38638
  while (length <= maximum) {
38123
38639
  const chunk = Buffer.alloc(Math.min(64 * 1024, maximum + 1 - length));
38124
- const count3 = readSync3(fd, chunk, 0, chunk.length, null);
38640
+ const count3 = readSync4(fd, chunk, 0, chunk.length, null);
38125
38641
  if (count3 === 0) break;
38126
38642
  parts.push(chunk.subarray(0, count3));
38127
38643
  length += count3;
@@ -38131,7 +38647,7 @@ function boundedRead(path2, maximum) {
38131
38647
  }
38132
38648
  return Buffer.concat(parts, length);
38133
38649
  } finally {
38134
- closeSync4(fd);
38650
+ closeSync5(fd);
38135
38651
  }
38136
38652
  }
38137
38653
  function checkpointAttachments(path2, sessionId) {
@@ -38175,8 +38691,8 @@ function readDurableSessionImageSync(attachment) {
38175
38691
  const root = checkpoint + ".media";
38176
38692
  const [generation2, file2] = ref.file.split("/");
38177
38693
  checkedDirectory(root);
38178
- checkedDirectory(join18(root, generation2));
38179
- const localPath = join18(root, generation2, file2);
38694
+ checkedDirectory(join19(root, generation2));
38695
+ const localPath = join19(root, generation2, file2);
38180
38696
  const data = boundedRead(localPath, SESSION_MEDIA_LIMITS.imageBytes);
38181
38697
  const detected = imageType(data);
38182
38698
  if (!detected || detected.mediaType !== attachment.mediaType || data.length !== attachment.size || sha2562(data) !== ref.sha256 || !file2.endsWith("." + detected.extension)) {
@@ -38365,7 +38881,7 @@ init_capabilities();
38365
38881
  // src/agent/tools/file.ts
38366
38882
  init_capabilities();
38367
38883
  import { readFile as readFile3, readdir as readdir2, stat as stat3 } from "fs/promises";
38368
- import { basename as basename7, dirname as dirname14, resolve as resolve13, posix as posix2 } from "path";
38884
+ import { basename as basename8, dirname as dirname15, resolve as resolve15, posix as posix2 } from "path";
38369
38885
  import { homedir as homedir10 } from "os";
38370
38886
  import { createHash as createHash15, randomBytes as randomBytes3 } from "crypto";
38371
38887
  import { exec as exec2 } from "child_process";
@@ -38579,18 +39095,32 @@ function describeEdit(beforeContent, afterContent) {
38579
39095
 
38580
39096
  // src/utils/temporary_write_root.ts
38581
39097
  import { lstat as lstat4, mkdir as mkdir4 } from "fs/promises";
38582
- import { parse as parse4, resolve as resolve12, sep as sep6 } from "path";
39098
+ import { parse as parse4, relative as relative4, resolve as resolve14, sep as sep7 } from "path";
38583
39099
  function isPathWithinRoot(path2, root) {
38584
- const normalizedPath = resolve12(path2);
38585
- const normalizedRoot = resolve12(root);
38586
- return normalizedPath === normalizedRoot || normalizedPath.startsWith(normalizedRoot.endsWith(sep6) ? normalizedRoot : `${normalizedRoot}${sep6}`);
39100
+ const normalizedPath = resolve14(path2);
39101
+ const normalizedRoot = resolve14(root);
39102
+ return normalizedPath === normalizedRoot || normalizedPath.startsWith(normalizedRoot.endsWith(sep7) ? normalizedRoot : `${normalizedRoot}${sep7}`);
38587
39103
  }
38588
- async function assertTemporaryWritePathAllowed(target, root, action) {
38589
- const resolvedRoot = resolve12(root);
38590
- const resolvedTarget = resolve12(target);
39104
+ async function assertTemporaryWritePathAllowed(target, root, action, cwd, writeSet) {
39105
+ const resolvedRoot = resolve14(root);
39106
+ const resolvedTarget = resolve14(target);
39107
+ if (!isWellFormedText(resolvedTarget)) {
39108
+ throw new Error(`${action} denied: a path must be well-formed Unicode text (${JSON.stringify(resolvedTarget)})`);
39109
+ }
38591
39110
  if (!isPathWithinRoot(resolvedTarget, resolvedRoot)) {
38592
39111
  throw new Error(`${action} denied: path is outside temporary write root (${resolvedRoot})`);
38593
39112
  }
39113
+ if (resolvedTarget === resolvedRoot) {
39114
+ throw new Error(`${action} denied: a write cannot replace the temporary write root itself (${resolvedRoot})`);
39115
+ }
39116
+ const gitDirectory = gitDirectoryComponent(relative4(resolvedRoot, resolvedTarget)) ?? linkedGitDirectoryHolding(resolvedTarget, cwd === void 0 ? [resolvedRoot] : [resolvedRoot, cwd]);
39117
+ if (gitDirectory !== null) {
39118
+ throw new Error(`${action} denied: path is inside a git directory (${gitDirectory}), which a confined write may not change (${resolvedTarget})`);
39119
+ }
39120
+ const planted = gitDirectoryPlantedByWriteSet(resolvedTarget, writeSet ?? [resolvedTarget]);
39121
+ if (planted !== null) {
39122
+ throw new Error(`${action} denied: this write would make a git directory (${planted}), which a confined write may not create (${resolvedTarget})`);
39123
+ }
38594
39124
  await assertPathComponentsHaveNoSymlinks(resolvedRoot, {
38595
39125
  allowMissingTail: false,
38596
39126
  errorPrefix: `${action} denied: temporary write root`
@@ -38601,7 +39131,7 @@ async function assertTemporaryWritePathAllowed(target, root, action) {
38601
39131
  });
38602
39132
  }
38603
39133
  async function assertTemporaryRootSafe(root, action) {
38604
- const resolvedRoot = resolve12(root);
39134
+ const resolvedRoot = resolve14(root);
38605
39135
  await assertPathComponentsHaveNoSymlinks(resolvedRoot, {
38606
39136
  allowMissingTail: false,
38607
39137
  errorPrefix: `${action} denied: temporary write root`
@@ -38609,7 +39139,7 @@ async function assertTemporaryRootSafe(root, action) {
38609
39139
  return resolvedRoot;
38610
39140
  }
38611
39141
  async function assertPathComponentsHaveNoSymlinks(path2, options) {
38612
- for (const component of pathComponentPrefixes(resolve12(path2))) {
39142
+ for (const component of pathComponentPrefixes(resolve14(path2))) {
38613
39143
  try {
38614
39144
  const info = await lstat4(component);
38615
39145
  if (info.isSymbolicLink()) {
@@ -38630,11 +39160,11 @@ async function assertPathComponentsHaveNoSymlinks(path2, options) {
38630
39160
  function pathComponentPrefixes(path2) {
38631
39161
  const parsed = parse4(path2);
38632
39162
  const relativePath2 = path2.slice(parsed.root.length);
38633
- const components = relativePath2.split(sep6).filter(Boolean);
39163
+ const components = relativePath2.split(sep7).filter(Boolean);
38634
39164
  const prefixes = [parsed.root];
38635
39165
  let current = parsed.root;
38636
39166
  for (const component of components) {
38637
- current = resolve12(current, component);
39167
+ current = resolve14(current, component);
38638
39168
  prefixes.push(current);
38639
39169
  }
38640
39170
  return prefixes;
@@ -38700,7 +39230,7 @@ function countNewlines(content2, end = content2.length) {
38700
39230
  }
38701
39231
  function expandTilde(path2) {
38702
39232
  if (path2.startsWith("~/")) {
38703
- return resolve13(homedir10(), path2.slice(2));
39233
+ return resolve15(homedir10(), path2.slice(2));
38704
39234
  }
38705
39235
  if (path2 === "~") {
38706
39236
  return homedir10();
@@ -38716,11 +39246,28 @@ function resolvePath(path2, context) {
38716
39246
  }
38717
39247
  const expanded = expandTilde(path2);
38718
39248
  const base = context?.cwd || process.cwd();
38719
- return resolve13(base, expanded);
39249
+ return resolve15(base, expanded);
39250
+ }
39251
+ function stringPathArgument(args, tool) {
39252
+ const value = args.path;
39253
+ if (value === void 0 || value === null) throw new Error(`${tool}: path argument is required but was not provided`);
39254
+ if (typeof value !== "string") throw new Error(`${tool}: path argument must be a string`);
39255
+ return value;
38720
39256
  }
38721
39257
  async function assertTemporaryWriteAllowed(path2, context) {
38722
39258
  if (context?.temporaryWriteRoot === void 0) return;
38723
- await assertTemporaryWritePathAllowed(path2, context.temporaryWriteRoot, "write_file");
39259
+ await assertTemporaryWritePathAllowed(path2, context.temporaryWriteRoot, "write_file", context.cwd);
39260
+ }
39261
+ function writeAdmissionPath(path2) {
39262
+ return DOCKER_CONTAINER2 ? posix2.relative(DOCKER_WORKDIR2, path2) || "." : path2;
39263
+ }
39264
+ async function filePathTarget(args, context) {
39265
+ if (args.path === void 0 || args.path === null) return [];
39266
+ return [{ path: writeAdmissionPath(resolvePath(String(args.path), context)), label: String(args.path) }];
39267
+ }
39268
+ async function admitLockedWrite(path2, label, context) {
39269
+ await assertTemporaryWriteAllowed(path2, context);
39270
+ context?.admitWrites?.([{ path: writeAdmissionPath(path2), label }]);
38724
39271
  }
38725
39272
  var readFileTool = {
38726
39273
  parallelSafe: true,
@@ -38756,7 +39303,7 @@ var readFileTool = {
38756
39303
  }
38757
39304
  },
38758
39305
  execute: async (args, context) => {
38759
- const path2 = resolvePath(String(args.path), context);
39306
+ const path2 = resolvePath(stringPathArgument(args, "read_file"), context);
38760
39307
  for (const name2 of ["offset", "limit"]) {
38761
39308
  const value = args[name2];
38762
39309
  if (value !== void 0 && (typeof value !== "number" || !Number.isSafeInteger(value) || value < 1)) {
@@ -38809,7 +39356,7 @@ var readFileTool = {
38809
39356
  type: "image",
38810
39357
  mediaType: image.mediaType,
38811
39358
  data: raw.toString("base64"),
38812
- description: `Read image ${basename7(path2)} (${raw.length.toLocaleString()} bytes)`,
39359
+ description: `Read image ${basename8(path2)} (${raw.length.toLocaleString()} bytes)`,
38813
39360
  path: path2
38814
39361
  });
38815
39362
  }
@@ -38895,6 +39442,7 @@ var writeFileTool = {
38895
39442
  required: ["path", "content"]
38896
39443
  }
38897
39444
  },
39445
+ writePaths: filePathTarget,
38898
39446
  execute: async (args, context) => {
38899
39447
  if (args.path === void 0 || args.path === null) {
38900
39448
  throw new Error("write_file: path argument is required but was not provided");
@@ -38915,6 +39463,7 @@ var writeFileTool = {
38915
39463
  let size = 0;
38916
39464
  if (DOCKER_CONTAINER2) {
38917
39465
  const written = await withPathLock(path2, async () => {
39466
+ await admitLockedWrite(path2, String(args.path), context);
38918
39467
  const dir = posix2.dirname(path2);
38919
39468
  await dockerExec(`mkdir -p ${shellEscape3(dir)}`);
38920
39469
  let before = "";
@@ -38939,7 +39488,8 @@ var writeFileTool = {
38939
39488
  } else {
38940
39489
  const { mkdir: mkdir5 } = await import("fs/promises");
38941
39490
  const written = await withPathLock(path2, async () => {
38942
- await mkdir5(dirname14(path2), { recursive: true });
39491
+ await admitLockedWrite(path2, String(args.path), context);
39492
+ await mkdir5(dirname15(path2), { recursive: true });
38943
39493
  let before = "";
38944
39494
  try {
38945
39495
  before = await readFile3(path2, { encoding: "utf-8" });
@@ -39023,8 +39573,9 @@ function parseBooleanFlag(value) {
39023
39573
  if (value === true) return true;
39024
39574
  return typeof value === "string" && value.trim().toLowerCase() === "true";
39025
39575
  }
39026
- async function updateFileAtomic(path2, mutate) {
39576
+ async function updateFileAtomic(path2, mutate, admit) {
39027
39577
  return withPathLock(path2, async () => {
39578
+ await admit?.();
39028
39579
  const before = await readRawFile(path2);
39029
39580
  const after = mutate(before);
39030
39581
  await writeRawFile(path2, after);
@@ -39054,6 +39605,7 @@ var editFileTool = {
39054
39605
  required: ["path", "old_string", "new_string"]
39055
39606
  }
39056
39607
  },
39608
+ writePaths: filePathTarget,
39057
39609
  execute: async (args, context) => {
39058
39610
  if (args.path === void 0 || args.path === null) {
39059
39611
  throw new Error("edit_file: path argument is required but was not provided");
@@ -39073,7 +39625,8 @@ var editFileTool = {
39073
39625
  try {
39074
39626
  const updated = await updateFileAtomic(
39075
39627
  path2,
39076
- (content2) => applyExactReplace(content2, args.old_string, args.new_string, replaceAll)
39628
+ (content2) => applyExactReplace(content2, args.old_string, args.new_string, replaceAll),
39629
+ () => admitLockedWrite(path2, String(args.path), context)
39077
39630
  );
39078
39631
  before = updated.before;
39079
39632
  after = updated.after;
@@ -39121,7 +39674,7 @@ var listDirectoryTool = {
39121
39674
  }
39122
39675
  },
39123
39676
  execute: async (args, context) => {
39124
- const path2 = resolvePath(String(args.path), context);
39677
+ const path2 = resolvePath(stringPathArgument(args, "list_directory"), context);
39125
39678
  const recursive2 = parseBooleanFlag(args.recursive);
39126
39679
  if (DOCKER_CONTAINER2) {
39127
39680
  try {
@@ -39164,7 +39717,7 @@ var listDirectoryTool = {
39164
39717
  if (entries.length > 100) truncated = true;
39165
39718
  const results = [];
39166
39719
  for (const entry of entries.slice(0, 100)) {
39167
- const entryPath = resolve13(dir, entry.name);
39720
+ const entryPath = resolve15(dir, entry.name);
39168
39721
  const info = {
39169
39722
  name: entry.name,
39170
39723
  type: entry.isDirectory() ? "directory" : "file"
@@ -39191,7 +39744,7 @@ var listDirectoryTool = {
39191
39744
 
39192
39745
  // src/agent/tools/shell.ts
39193
39746
  init_capabilities();
39194
- import { resolve as resolve14 } from "path";
39747
+ import { resolve as resolve16 } from "path";
39195
39748
  init_config();
39196
39749
  init_checked_commands();
39197
39750
  init_source_verification_contract();
@@ -39496,7 +40049,7 @@ function resolveRunCommandCwd(args, context) {
39496
40049
  const docker = dockerTarget();
39497
40050
  if (docker) return containerPath(docker, args.cwd ? String(args.cwd) : ".");
39498
40051
  const baseCwd = context?.cwd || process.cwd();
39499
- return args.cwd ? resolve14(baseCwd, String(args.cwd)) : baseCwd;
40052
+ return args.cwd ? resolve16(baseCwd, String(args.cwd)) : baseCwd;
39500
40053
  }
39501
40054
  var runCommandTool = {
39502
40055
  isErrorResult: failedCommandReceipt,
@@ -39608,7 +40161,7 @@ var runCommandTool = {
39608
40161
  throw new Error(`run_command: command argument is invalid: "${command}"`);
39609
40162
  }
39610
40163
  const cwd = resolveRunCommandCwd(args, context);
39611
- const temporaryWriteRoot = context?.temporaryWriteRoot === void 0 ? void 0 : resolve14(context.temporaryWriteRoot);
40164
+ const temporaryWriteRoot = context?.temporaryWriteRoot === void 0 ? void 0 : resolve16(context.temporaryWriteRoot);
39612
40165
  if (temporaryWriteRoot !== void 0) {
39613
40166
  await assertTemporaryRootSafe(temporaryWriteRoot, "run_command");
39614
40167
  if (!isPathWithinRoot(cwd, temporaryWriteRoot)) {
@@ -40426,8 +40979,8 @@ var BackgroundWorkers = class {
40426
40979
  if (this.running.size > 0) {
40427
40980
  const wait = Math.max(0, this.lastCheckAt + this.checkIntervalMs - this.now());
40428
40981
  let timer;
40429
- await Promise.race([all, new Promise((resolve22) => {
40430
- timer = setTimeout(resolve22, wait);
40982
+ await Promise.race([all, new Promise((resolve24) => {
40983
+ timer = setTimeout(resolve24, wait);
40431
40984
  })]);
40432
40985
  clearTimeout(timer);
40433
40986
  }
@@ -40466,8 +41019,8 @@ init_loop_policy();
40466
41019
  init_tool_compression();
40467
41020
 
40468
41021
  // src/agent/runtime/tool_runtime.ts
40469
- import { basename as basename9, dirname as dirname17, join as join22, relative as relative3, resolve as resolve17 } from "path";
40470
- import { realpathSync as realpathSync5 } from "node:fs";
41022
+ import { basename as basename10, dirname as dirname18, join as join23, relative as relative6, resolve as resolve19 } from "path";
41023
+ import { realpathSync as realpathSync6 } from "node:fs";
40471
41024
  import { appendFile } from "node:fs/promises";
40472
41025
 
40473
41026
  // src/agent/tools/helper_requirements.ts
@@ -40491,8 +41044,8 @@ init_capabilities();
40491
41044
  init_config();
40492
41045
 
40493
41046
  // src/context/intents_loader.ts
40494
- import { appendFileSync as appendFileSync5, existsSync as existsSync5, mkdirSync as mkdirSync7, readFileSync as readFileSync10, statSync as statSync6, writeFileSync as writeFileSync8 } from "fs";
40495
- import { basename as basename8, dirname as dirname15, join as join19, relative as relative2, resolve as resolve15 } from "path";
41047
+ import { appendFileSync as appendFileSync5, existsSync as existsSync5, mkdirSync as mkdirSync7, readFileSync as readFileSync10, statSync as statSync7, writeFileSync as writeFileSync8 } from "fs";
41048
+ import { basename as basename9, dirname as dirname16, join as join20, relative as relative5, resolve as resolve17 } from "path";
40496
41049
  var DEFAULT_MAX_BYTES = 32 * 1024;
40497
41050
  var DEFAULT_FILE_INTENT_THRESHOLD_LINES = 400;
40498
41051
  function loadIntentsContext(cwd = process.cwd(), settings, options = {}) {
@@ -40519,7 +41072,7 @@ function loadIntentsContextDetailed(cwd = process.cwd(), settings, options = {})
40519
41072
  bytes: loaded.bytes,
40520
41073
  truncated: loaded.truncated
40521
41074
  });
40522
- const label = relative2(cwd, candidate) || basename8(candidate);
41075
+ const label = relative5(cwd, candidate) || basename9(candidate);
40523
41076
  sections.push([
40524
41077
  `# Intent Context: ${label}`,
40525
41078
  "",
@@ -40546,14 +41099,14 @@ function maybeAutoUpdateIntents(options) {
40546
41099
  if (isIntentFile(changedPath)) {
40547
41100
  continue;
40548
41101
  }
40549
- const absolutePath = resolve15(options.cwd, changedPath);
41102
+ const absolutePath = resolve17(options.cwd, changedPath);
40550
41103
  const target = selectIntentTarget(options.cwd, absolutePath, threshold);
40551
41104
  ensureIntentFile(target);
40552
- const relChanged = relative2(options.cwd, absolutePath) || basename8(absolutePath);
41105
+ const relChanged = relative5(options.cwd, absolutePath) || basename9(absolutePath);
40553
41106
  const note = `- ${(/* @__PURE__ */ new Date()).toISOString()}: tool \`${options.toolName}\` changed \`${relChanged}\`. Keep this file's higher-level intent current if behavior changed.
40554
41107
  `;
40555
41108
  appendFileSync5(target, note, "utf-8");
40556
- updated.add(relative2(options.cwd, target) || basename8(target));
41109
+ updated.add(relative5(options.cwd, target) || basename9(target));
40557
41110
  }
40558
41111
  return [...updated];
40559
41112
  }
@@ -40561,13 +41114,13 @@ function buildIntentCandidates(cwd, relatedPaths, includeHierarchy) {
40561
41114
  const seen = /* @__PURE__ */ new Set();
40562
41115
  const candidates = [];
40563
41116
  if (includeHierarchy) {
40564
- const roots = findRootToCwd(resolve15(cwd));
41117
+ const roots = findRootToCwd(resolve17(cwd));
40565
41118
  for (const dir of roots) {
40566
- pushUnique(candidates, seen, join19(dir, ".ztc-intents.md"));
41119
+ pushUnique(candidates, seen, join20(dir, ".ztc-intents.md"));
40567
41120
  }
40568
41121
  }
40569
41122
  for (const relatedPath of relatedPaths) {
40570
- const absolutePath = resolve15(cwd, relatedPath);
41123
+ const absolutePath = resolve17(cwd, relatedPath);
40571
41124
  pushUnique(candidates, seen, fileIntentPath(absolutePath));
40572
41125
  }
40573
41126
  return candidates;
@@ -40577,10 +41130,10 @@ function findRootToCwd(cwd) {
40577
41130
  let current = cwd;
40578
41131
  for (; ; ) {
40579
41132
  chain.push(current);
40580
- if (existsSync5(join19(current, ".git"))) {
41133
+ if (existsSync5(join20(current, ".git"))) {
40581
41134
  break;
40582
41135
  }
40583
- const parent = dirname15(current);
41136
+ const parent = dirname16(current);
40584
41137
  if (parent === current) {
40585
41138
  break;
40586
41139
  }
@@ -40592,20 +41145,20 @@ function selectIntentTarget(cwd, absolutePath, threshold) {
40592
41145
  if (isLargeFile(absolutePath, threshold)) {
40593
41146
  return fileIntentPath(absolutePath);
40594
41147
  }
40595
- const dir = existsSync5(absolutePath) && statSync6(absolutePath).isDirectory() ? absolutePath : dirname15(absolutePath);
40596
- const normalizedCwd = resolve15(cwd);
40597
- const normalizedDir = resolve15(dir);
41148
+ const dir = existsSync5(absolutePath) && statSync7(absolutePath).isDirectory() ? absolutePath : dirname16(absolutePath);
41149
+ const normalizedCwd = resolve17(cwd);
41150
+ const normalizedDir = resolve17(dir);
40598
41151
  if (!isInside(normalizedDir, normalizedCwd)) {
40599
- return join19(normalizedCwd, ".ztc-intents.md");
41152
+ return join20(normalizedCwd, ".ztc-intents.md");
40600
41153
  }
40601
- return join19(normalizedDir, ".ztc-intents.md");
41154
+ return join20(normalizedDir, ".ztc-intents.md");
40602
41155
  }
40603
41156
  function ensureIntentFile(path2) {
40604
- mkdirSync7(dirname15(path2), { recursive: true });
41157
+ mkdirSync7(dirname16(path2), { recursive: true });
40605
41158
  if (existsSync5(path2)) {
40606
41159
  return;
40607
41160
  }
40608
- const title = basename8(path2) === ".ztc-intents.md" ? "ZTC Folder Intents" : `ZTC File Intents for ${basename8(path2).replace(/^\.ztc-intents-/, "").replace(/\.md$/, "")}`;
41161
+ const title = basename9(path2) === ".ztc-intents.md" ? "ZTC Folder Intents" : `ZTC File Intents for ${basename9(path2).replace(/^\.ztc-intents-/, "").replace(/\.md$/, "")}`;
40609
41162
  writeFileSync8(path2, [
40610
41163
  `# ${title}`,
40611
41164
  "",
@@ -40616,11 +41169,11 @@ function ensureIntentFile(path2) {
40616
41169
  ].join("\n") + "\n", "utf-8");
40617
41170
  }
40618
41171
  function fileIntentPath(absolutePath) {
40619
- return join19(dirname15(absolutePath), `.ztc-intents-${basename8(absolutePath)}.md`);
41172
+ return join20(dirname16(absolutePath), `.ztc-intents-${basename9(absolutePath)}.md`);
40620
41173
  }
40621
41174
  function isLargeFile(path2, threshold) {
40622
41175
  try {
40623
- if (!existsSync5(path2) || statSync6(path2).isDirectory()) {
41176
+ if (!existsSync5(path2) || statSync7(path2).isDirectory()) {
40624
41177
  return false;
40625
41178
  }
40626
41179
  const raw = readFileSync10(path2, "utf-8");
@@ -40656,7 +41209,7 @@ function loadBudgetedFile(path2, maxBytes) {
40656
41209
  }
40657
41210
  }
40658
41211
  function pushUnique(paths, seen, path2) {
40659
- const normalized = resolve15(path2);
41212
+ const normalized = resolve17(path2);
40660
41213
  if (seen.has(normalized)) {
40661
41214
  return;
40662
41215
  }
@@ -40664,7 +41217,7 @@ function pushUnique(paths, seen, path2) {
40664
41217
  paths.push(normalized);
40665
41218
  }
40666
41219
  function isIntentFile(path2) {
40667
- return basename8(path2).startsWith(".ztc-intents");
41220
+ return basename9(path2).startsWith(".ztc-intents");
40668
41221
  }
40669
41222
  function isInside(path2, root) {
40670
41223
  return path2 === root || path2.startsWith(`${root}/`);
@@ -41146,7 +41699,7 @@ var ztcCommandTool = {
41146
41699
  // src/agent/tools/verify_artifact.ts
41147
41700
  init_capabilities();
41148
41701
  import { createHash as createHash19, randomUUID as randomUUID10 } from "node:crypto";
41149
- import { join as join20 } from "node:path";
41702
+ import { join as join21 } from "node:path";
41150
41703
 
41151
41704
  // src/agent/runtime/json_verifier_recipe.ts
41152
41705
  function jsonAssertionsRecipe(inputBytes, configBytes) {
@@ -41201,9 +41754,9 @@ function jsonAssertionsRecipe(inputBytes, configBytes) {
41201
41754
  // src/agent/runtime/verifier_capture.ts
41202
41755
  init_source_verification_contract();
41203
41756
  import { createHash as createHash18 } from "node:crypto";
41204
- import { constants as constants4 } from "node:fs";
41757
+ import { constants as constants5 } from "node:fs";
41205
41758
  import { lstat as lstat5, open as open4, realpath as realpath3 } from "node:fs/promises";
41206
- import { dirname as dirname16, resolve as resolve16 } from "node:path";
41759
+ import { dirname as dirname17, resolve as resolve18 } from "node:path";
41207
41760
  var VERIFIER_INPUT_MAX_BYTES = 65536;
41208
41761
  var hash4 = (bytes4) => createHash18("sha256").update(bytes4).digest("hex");
41209
41762
  function seal(source2) {
@@ -41225,7 +41778,7 @@ async function captureVerifierInputs(context, paths) {
41225
41778
  instrumentation: "unknown"
41226
41779
  });
41227
41780
  if (!request2 || paths.length !== 2) throw new TypeError("Verifier capture requires two distinct scoped relative paths");
41228
- const cwd = await realpath3(resolve16(context.cwd));
41781
+ const cwd = await realpath3(resolve18(context.cwd));
41229
41782
  const source2 = {
41230
41783
  schema_version: 1,
41231
41784
  source_id: "0".repeat(64),
@@ -41239,15 +41792,15 @@ async function captureVerifierInputs(context, paths) {
41239
41792
  };
41240
41793
  const documents = /* @__PURE__ */ new Map();
41241
41794
  for (const row of source2.files) {
41242
- const absolute = resolve16(cwd, row.path);
41795
+ const absolute = resolve18(cwd, row.path);
41243
41796
  try {
41244
41797
  if (context.signal?.aborted || context.canInspectVerificationSource && !await context.canInspectVerificationSource(seal(structuredClone(source2)))) continue;
41245
- if (await realpath3(dirname16(absolute)) !== dirname16(absolute)) continue;
41798
+ if (await realpath3(dirname17(absolute)) !== dirname17(absolute)) continue;
41246
41799
  const location = await lstat5(absolute);
41247
41800
  row.bytes = Number.isSafeInteger(location.size) && location.size >= 0 ? location.size : 0;
41248
41801
  row.mode = location.mode & 4095;
41249
41802
  if (!location.isFile() || location.size > VERIFIER_INPUT_MAX_BYTES || context.signal?.aborted) continue;
41250
- const handle = await open4(absolute, constants4.O_RDONLY | constants4.O_NOFOLLOW | constants4.O_NONBLOCK);
41803
+ const handle = await open4(absolute, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
41251
41804
  try {
41252
41805
  const before = await handle.stat();
41253
41806
  if (!before.isFile() || before.size > VERIFIER_INPUT_MAX_BYTES || before.dev !== location.dev || before.ino !== location.ino) continue;
@@ -41261,7 +41814,7 @@ async function captureVerifierInputs(context, paths) {
41261
41814
  }
41262
41815
  const after = await handle.stat();
41263
41816
  const current = await lstat5(absolute);
41264
- if (context.signal?.aborted || used !== before.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current.dev !== before.dev || current.ino !== before.ino || await realpath3(dirname16(absolute)) !== dirname16(absolute)) continue;
41817
+ if (context.signal?.aborted || used !== before.size || before.dev !== after.dev || before.ino !== after.ino || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs || current.dev !== before.dev || current.ino !== before.ino || await realpath3(dirname17(absolute)) !== dirname17(absolute)) continue;
41265
41818
  if (context.canInspectVerificationSource && !await context.canInspectVerificationSource(seal(structuredClone(source2)))) continue;
41266
41819
  if (context.signal?.aborted) continue;
41267
41820
  const captured = bytes4.subarray(0, used);
@@ -41351,7 +41904,7 @@ var verifyArtifactTool = Object.freeze({
41351
41904
  };
41352
41905
  finished.artifact_refs = receipt2.source.files.filter((file2) => file2.kind === "file").map((file2) => ({
41353
41906
  origin: "local",
41354
- path: join20(receipt2.source.cwd, file2.path),
41907
+ path: join21(receipt2.source.cwd, file2.path),
41355
41908
  sha256: file2.sha256
41356
41909
  }));
41357
41910
  const verifier = parseVerifierDecision({
@@ -41378,7 +41931,7 @@ var verifyArtifactTool = Object.freeze({
41378
41931
  // src/agent/tools/benchmark_cpu.ts
41379
41932
  import { randomUUID as randomUUID12 } from "node:crypto";
41380
41933
  import { cpus, release } from "node:os";
41381
- import { join as join21 } from "node:path";
41934
+ import { join as join22 } from "node:path";
41382
41935
 
41383
41936
  // src/agent/runtime/cpu_benchmark.ts
41384
41937
  import { spawn as spawn3 } from "node:child_process";
@@ -41453,7 +42006,7 @@ async function runCPUWorkload(workload, context) {
41453
42006
  if (process.platform === "win32") return { outcome: "unknown", output: "", executionPolicyId: null };
41454
42007
  const plan = buildSandboxCommandPlan(`exec ${quote2(process.execPath)} --input-type=module -e ${quote2(SCRIPT)}`, context.cwd, context.commandPolicy);
41455
42008
  const executionPolicyId = cpuHash(JSON.stringify({ backend: plan.backend, enforcement: plan.enforcement, policy: context.commandPolicy ?? null }));
41456
- return new Promise((resolve22) => {
42009
+ return new Promise((resolve24) => {
41457
42010
  let outcome;
41458
42011
  let output2 = "";
41459
42012
  let outputBytes = 0;
@@ -41484,7 +42037,7 @@ async function runCPUWorkload(workload, context) {
41484
42037
  child.on("close", (code) => {
41485
42038
  clearTimeout(timer);
41486
42039
  context.signal?.removeEventListener("abort", cancel);
41487
- resolve22({ outcome: outcome ?? (code === 0 ? "passed" : "failed"), output: output2, executionPolicyId });
42040
+ resolve24({ outcome: outcome ?? (code === 0 ? "passed" : "failed"), output: output2, executionPolicyId });
41488
42041
  });
41489
42042
  if (context.signal?.aborted) cancel();
41490
42043
  else child.stdin.end(JSON.stringify(workload));
@@ -41617,7 +42170,7 @@ var benchmarkCPUTool = Object.freeze({
41617
42170
  receipt2.source_binding = receipt2.source.coverage === "complete" && receipt2.end_source.coverage === "complete" && receipt2.source.source_id === receipt2.end_source.source_id ? "observed_endpoints" : "unknown";
41618
42171
  receipt2.artifact_refs = receipt2.source.files.filter((file2) => file2.kind === "file").map((file2) => ({
41619
42172
  origin: "local",
41620
- path: join21(receipt2.source.cwd, file2.path),
42173
+ path: join22(receipt2.source.cwd, file2.path),
41621
42174
  sha256: file2.sha256
41622
42175
  }));
41623
42176
  if (decision.benchmark_eligibility === "eligible" && receipt2.source_binding !== "observed_endpoints") {
@@ -41687,10 +42240,10 @@ function isHostControlPlaneWrite(tool, args, cwd) {
41687
42240
  if (typeof tool?.hostControlPlaneWritePath !== "string" || typeof args.path !== "string") return false;
41688
42241
  try {
41689
42242
  const noFollowLeaf = (path2) => {
41690
- const absolute = resolve17(path2);
41691
- return join22(realpathSync5(dirname17(absolute)), basename9(absolute));
42243
+ const absolute = resolve19(path2);
42244
+ return join23(realpathSync6(dirname18(absolute)), basename10(absolute));
41692
42245
  };
41693
- return noFollowLeaf(resolve17(cwd, args.path)) === noFollowLeaf(tool.hostControlPlaneWritePath);
42246
+ return noFollowLeaf(resolve19(cwd, args.path)) === noFollowLeaf(tool.hostControlPlaneWritePath);
41694
42247
  } catch {
41695
42248
  return false;
41696
42249
  }
@@ -41700,13 +42253,13 @@ function canonicalSourcePath(path2) {
41700
42253
  const missing = [];
41701
42254
  while (true) {
41702
42255
  try {
41703
- return join22(realpathSync5(probe), ...missing);
42256
+ return join23(realpathSync6(probe), ...missing);
41704
42257
  } catch (error62) {
41705
42258
  const code = error62.code;
41706
42259
  if (code !== "ENOENT" && code !== "ENOTDIR") throw error62;
41707
- const parent = dirname17(probe);
42260
+ const parent = dirname18(probe);
41708
42261
  if (parent === probe) throw error62;
41709
- missing.unshift(basename9(probe));
42262
+ missing.unshift(basename10(probe));
41710
42263
  probe = parent;
41711
42264
  }
41712
42265
  }
@@ -41714,7 +42267,7 @@ function canonicalSourcePath(path2) {
41714
42267
  function sourceReadDecision(cwd, paths, policy) {
41715
42268
  let approvalRequired = false;
41716
42269
  for (const path2 of paths) {
41717
- const lexical = resolve17(cwd, path2);
42270
+ const lexical = resolve19(cwd, path2);
41718
42271
  const check2 = (target) => policy?.evaluateTool({
41719
42272
  name: "read_file",
41720
42273
  args: { path: target },
@@ -41748,7 +42301,7 @@ function prependMessages(base, messages) {
41748
42301
  ${base}` : prefix3;
41749
42302
  }
41750
42303
  function normalizeChangedPath(path2, cwd) {
41751
- const rel = relative3(cwd, resolve17(cwd, path2));
42304
+ const rel = relative6(cwd, resolve19(cwd, path2));
41752
42305
  return rel.startsWith("..") ? path2 : rel || ".";
41753
42306
  }
41754
42307
  function extractChangedPaths(capabilities, output2, cwd) {
@@ -41794,7 +42347,7 @@ ${intentContext}`;
41794
42347
  async function recordToolTrace(entry) {
41795
42348
  const configured = process.env.ZTC_TOOL_TRACE;
41796
42349
  if (!configured) return;
41797
- const target = configured === "1" ? join22(process.cwd(), "ztc-tool-trace.jsonl") : configured;
42350
+ const target = configured === "1" ? join23(process.cwd(), "ztc-tool-trace.jsonl") : configured;
41798
42351
  try {
41799
42352
  await appendFile(target, `${JSON.stringify(entry)}
41800
42353
  `, "utf-8");
@@ -41944,17 +42497,58 @@ async function executeToolWithRuntime(name2, args, options) {
41944
42497
  approvalGranted = true;
41945
42498
  }
41946
42499
  let profileApprovalRequired = false;
41947
- if (options.policy && tool && !hostControlPlaneWrite) {
42500
+ let writeTargets = [];
42501
+ const policy = options.policy;
42502
+ const refuseWrites = (targets) => {
42503
+ let approvalRequired = false;
42504
+ if (!policy) return { approvalRequired };
42505
+ const writeSet = targets.map((target) => target.path);
42506
+ for (const target of targets) {
42507
+ let decision;
42508
+ try {
42509
+ decision = policy.evaluateTool({
42510
+ name: name2,
42511
+ args: { path: target.path },
42512
+ capabilities: ["file_write" /* FILE_WRITE */],
42513
+ writeTargets: true,
42514
+ writeSet
42515
+ });
42516
+ } catch (error62) {
42517
+ decision = {
42518
+ allowed: false,
42519
+ reason: `Permission denied: path cannot be resolved for write admission (${error62 instanceof Error ? error62.message : String(error62)})`
42520
+ };
42521
+ }
42522
+ if (!decision.allowed) {
42523
+ return {
42524
+ refusal: `${decision.reason || `Permission denied: ${name2}`}. ${name2} wrote nothing: ${target.label} is refused, and every path a call writes must be allowed.`,
42525
+ approvalRequired
42526
+ };
42527
+ }
42528
+ approvalRequired ||= decision.approvalRequired === true;
42529
+ }
42530
+ return { approvalRequired };
42531
+ };
42532
+ const admitWriteTargets = () => {
42533
+ const { refusal, approvalRequired } = refuseWrites(writeTargets);
42534
+ if (refusal !== void 0) return { content: refusal, isError: true, effectiveArgs };
42535
+ profileApprovalRequired ||= approvalRequired;
42536
+ return void 0;
42537
+ };
42538
+ let policyExecutionCommand;
42539
+ if (policy && tool && !hostControlPlaneWrite) {
41948
42540
  try {
41949
42541
  policyExecutionCwd = tool.resolveExecutionCwd?.(effectiveArgs, options.context);
42542
+ policyExecutionCommand = tool.resolveExecutionCommand?.(effectiveArgs);
41950
42543
  } catch (error62) {
41951
42544
  return handleToolFailure(error62);
41952
42545
  }
41953
- const decision = options.policy.evaluateTool({
42546
+ const decision = policy.evaluateTool({
41954
42547
  name: name2,
41955
42548
  args: effectiveArgs,
41956
42549
  capabilities: callCapabilities(effectiveArgs),
41957
- ...policyExecutionCwd === void 0 ? {} : { executionCwd: policyExecutionCwd }
42550
+ ...policyExecutionCwd === void 0 ? {} : { executionCwd: policyExecutionCwd },
42551
+ ...policyExecutionCommand === void 0 ? {} : { executionCommand: policyExecutionCommand }
41958
42552
  });
41959
42553
  profileApprovalRequired = decision.approvalRequired === true;
41960
42554
  if (!decision.allowed) {
@@ -41964,6 +42558,18 @@ async function executeToolWithRuntime(name2, args, options) {
41964
42558
  effectiveArgs
41965
42559
  };
41966
42560
  }
42561
+ if (tool.writePaths) {
42562
+ try {
42563
+ writeTargets = await tool.writePaths(effectiveArgs, options.context);
42564
+ } catch (error62) {
42565
+ return handleToolFailure(error62);
42566
+ }
42567
+ const refused = admitWriteTargets();
42568
+ if (refused) return refused;
42569
+ if (writeTargets.length > 0 && !capabilities.includes("file_write" /* FILE_WRITE */)) {
42570
+ capabilities = [...capabilities, "file_write" /* FILE_WRITE */];
42571
+ }
42572
+ }
41967
42573
  }
41968
42574
  const verificationAdmission = () => {
41969
42575
  const adapter = sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool;
@@ -41981,7 +42587,7 @@ async function executeToolWithRuntime(name2, args, options) {
41981
42587
  instrumentation: measured ? "production" : "unknown"
41982
42588
  } : effectiveArgs.verification);
41983
42589
  if (!request2) return { content: `${name2}: invalid source verification request`, isError: true, effectiveArgs };
41984
- const cwd = !adapter && effectiveArgs.cwd ? resolve17(options.context.cwd, String(effectiveArgs.cwd)) : options.context.cwd;
42590
+ const cwd = !adapter && effectiveArgs.cwd ? resolve19(options.context.cwd, String(effectiveArgs.cwd)) : options.context.cwd;
41985
42591
  const decision = sourceReadDecision(cwd, request2.source_paths, options.policy);
41986
42592
  if (!decision.allowed) return {
41987
42593
  content: decision.reason || "Permission denied: source verification requires file_read.",
@@ -42068,8 +42674,15 @@ async function executeToolWithRuntime(name2, args, options) {
42068
42674
  };
42069
42675
  const dispatchAdmission = verificationAdmission();
42070
42676
  if (dispatchAdmission) return dispatchAdmission;
42677
+ const writeReadmission = admitWriteTargets();
42678
+ if (writeReadmission) return writeReadmission;
42679
+ const admitWrites = policy && tool && !hostControlPlaneWrite ? (targets) => {
42680
+ const { refusal } = refuseWrites(targets);
42681
+ if (refusal !== void 0) throw new Error(refusal);
42682
+ } : void 0;
42071
42683
  const toolContext = options.context ? {
42072
42684
  ...options.context,
42685
+ admitWrites,
42073
42686
  onOutput: sourceTool === runCommandTool || tool?.outputSource === runCommandTool ? options.context.onOutput : void 0,
42074
42687
  canInspectVerificationSource: sourceTool === runCommandTool || sourceTool === readCommandTool || sourceTool === stopCommandTool || sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool ? canInspectVerificationSource : void 0,
42075
42688
  managedCommandWaitSliceMs: sourceTool === readCommandTool || sourceTool === runCommandTool ? options.context.managedCommandWaitSliceMs : void 0,
@@ -42109,7 +42722,7 @@ async function executeToolWithRuntime(name2, args, options) {
42109
42722
  const TOOL_OUTPUT_CAP = 8e4;
42110
42723
  output2 = augmentReadResultWithIntent(name2, effectiveArgs, output2, cwd);
42111
42724
  let resultContent = output2;
42112
- const contentTruncated = resultContent.length > TOOL_OUTPUT_CAP || reportsOwnTruncation(output2);
42725
+ const contentTruncated2 = resultContent.length > TOOL_OUTPUT_CAP || reportsOwnTruncation(output2);
42113
42726
  if (resultContent.length > TOOL_OUTPUT_CAP) {
42114
42727
  const HEAD = Math.floor(TOOL_OUTPUT_CAP * 0.8);
42115
42728
  const TAIL = TOOL_OUTPUT_CAP - HEAD;
@@ -42120,7 +42733,7 @@ async function executeToolWithRuntime(name2, args, options) {
42120
42733
 
42121
42734
  ` + resultContent.slice(-TAIL);
42122
42735
  }
42123
- const changedPaths = extractChangedPaths(ordinaryCapabilities, output2, cwd);
42736
+ const changedPaths = extractChangedPaths(capabilities, output2, cwd);
42124
42737
  const intentChangedPaths = hostControlPlaneWrite ? [] : maybeAutoUpdateIntents({
42125
42738
  cwd,
42126
42739
  changedPaths,
@@ -42160,12 +42773,12 @@ async function executeToolWithRuntime(name2, args, options) {
42160
42773
  return {
42161
42774
  content: resultContent,
42162
42775
  isError: false,
42163
- contentTruncated,
42776
+ contentTruncated: contentTruncated2,
42164
42777
  effectiveArgs,
42165
42778
  ...managedCommand ? { managedCommand } : {},
42166
42779
  ...verificationReceipt ? { verificationReceipt } : {},
42167
- ...!contentTruncated && verifierDecision ? { verifierDecision } : {},
42168
- ...!contentTruncated && benchmarkComparisonDecision ? { benchmarkComparisonDecision } : {}
42780
+ ...!contentTruncated2 && verifierDecision ? { verifierDecision } : {},
42781
+ ...!contentTruncated2 && benchmarkComparisonDecision ? { benchmarkComparisonDecision } : {}
42169
42782
  };
42170
42783
  } catch (error62) {
42171
42784
  if (checkpointRejected) throw error62;
@@ -42577,6 +43190,7 @@ var ContextOverflowError = class extends AgentError {
42577
43190
  };
42578
43191
  var CONTEXT_OVERFLOW_SUBSTRINGS = [
42579
43192
  "context window",
43193
+ "context length",
42580
43194
  "prompt is too long",
42581
43195
  "too many tokens",
42582
43196
  "exceeds the context"
@@ -42607,14 +43221,14 @@ function waitForRetryDelay(milliseconds, signal) {
42607
43221
  if (signal?.aborted) {
42608
43222
  return Promise.reject(new AgentError("Cancelled", "CANCELLED"));
42609
43223
  }
42610
- return new Promise((resolve22, reject) => {
43224
+ return new Promise((resolve24, reject) => {
42611
43225
  const timer = setTimeout(finish, milliseconds);
42612
43226
  const onAbort = () => finish(new AgentError("Cancelled", "CANCELLED"));
42613
43227
  function finish(error62) {
42614
43228
  clearTimeout(timer);
42615
43229
  signal?.removeEventListener("abort", onAbort);
42616
43230
  if (error62) reject(error62);
42617
- else resolve22();
43231
+ else resolve24();
42618
43232
  }
42619
43233
  signal?.addEventListener("abort", onAbort, { once: true });
42620
43234
  if (signal?.aborted) onAbort();
@@ -42630,9 +43244,9 @@ function collapseRepeatedWholeText(text5) {
42630
43244
  if (remaining <= 0 || remaining % 2 !== 0) continue;
42631
43245
  const half = remaining / 2;
42632
43246
  const left = core.slice(0, half);
42633
- const sep7 = core.slice(half, half + sepLen);
43247
+ const sep8 = core.slice(half, half + sepLen);
42634
43248
  const right = core.slice(half + sepLen);
42635
- if (/^\s+$/.test(sep7) && left.trim() && left.trim() === right.trim()) {
43249
+ if (/^\s+$/.test(sep8) && left.trim() && left.trim() === right.trim()) {
42636
43250
  return outerLeading + left.trimEnd() + outerTrailing;
42637
43251
  }
42638
43252
  }
@@ -42834,14 +43448,14 @@ var Agent = class _Agent {
42834
43448
  let admitted = !this.remoteResourceSession && receipt2.source.origin === "local";
42835
43449
  if (admitted) {
42836
43450
  try {
42837
- admitted = realpathSync6(this._cwd) === receipt2.source.cwd;
43451
+ admitted = realpathSync7(this._cwd) === receipt2.source.cwd;
42838
43452
  } catch {
42839
43453
  admitted = false;
42840
43454
  }
42841
43455
  }
42842
43456
  if (admitted) admitted = receipt2.source.files.every((file2) => this.policy.evaluateTool({
42843
43457
  name: "read_file",
42844
- args: { path: resolve18(receipt2.source.cwd, file2.path) },
43458
+ args: { path: resolve20(receipt2.source.cwd, file2.path) },
42845
43459
  capabilities: ["file_read" /* FILE_READ */]
42846
43460
  }).allowed);
42847
43461
  coverage.push(admitted ? await projectCurrentVerification(receipt2) : {
@@ -43660,7 +44274,7 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43660
44274
  if (signal?.aborted) break;
43661
44275
  const chunk = text5.slice(i, i + this.streamChunkSize);
43662
44276
  this.emit({ type: "stream_delta", content: chunk });
43663
- await new Promise((resolve22) => setTimeout(resolve22, 10));
44277
+ await new Promise((resolve24) => setTimeout(resolve24, 10));
43664
44278
  }
43665
44279
  this.emit({ type: "stream_end" });
43666
44280
  }
@@ -43674,7 +44288,7 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43674
44288
  * visible text, so an empty or whitespace-only response emits no stream
43675
44289
  * events (EPO-622), matching emitStreamText.
43676
44290
  */
43677
- async streamAndAssemble(backend, request2, signal, onAnswerOutput, onUsage, onAnswerText) {
44291
+ async streamAndAssemble(backend, request2, signal, onAnswerOutput, onUsage, onAnswerText, onToolOutput) {
43678
44292
  let text5 = "";
43679
44293
  let reasoning = "";
43680
44294
  const toolUses = [];
@@ -43736,12 +44350,14 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43736
44350
  }
43737
44351
  break;
43738
44352
  case "tool_use_start": {
44353
+ onToolOutput?.();
43739
44354
  const existing = toolUses.find((t) => t.id === ev.id);
43740
44355
  if (existing) existing.name = ev.name;
43741
44356
  else toolUses.push({ id: ev.id, name: ev.name, inputJson: "" });
43742
44357
  break;
43743
44358
  }
43744
44359
  case "tool_use_delta": {
44360
+ onToolOutput?.();
43745
44361
  let tu = toolUses.find((t) => t.id === ev.id);
43746
44362
  if (!tu) {
43747
44363
  tu = { id: ev.id, name: "", inputJson: "" };
@@ -43751,6 +44367,7 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43751
44367
  break;
43752
44368
  }
43753
44369
  case "tool_use_end":
44370
+ onToolOutput?.();
43754
44371
  closedToolUses.add(ev.id);
43755
44372
  break;
43756
44373
  case "usage": {
@@ -44667,8 +45284,8 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44667
45284
  metadata: { toolResult: true, toolCheckpoint: true, preserveUserBoundary: true }
44668
45285
  };
44669
45286
  const completedResults = /* @__PURE__ */ new Map();
44670
- const retainToolResult = async (toolCall, rawContent, guardedContent, managedCommand, contentTruncated = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
44671
- const partial2 = Boolean(signal?.aborted || contentTruncated || managedCommand?.result.has_more || managedCommand?.result.output_truncated);
45287
+ const retainToolResult = async (toolCall, rawContent, guardedContent, managedCommand, contentTruncated2 = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
45288
+ const partial2 = Boolean(signal?.aborted || contentTruncated2 || managedCommand?.result.has_more || managedCommand?.result.output_truncated);
44672
45289
  const { rendered } = this.toolResponseStore.put(
44673
45290
  toolCall.id,
44674
45291
  toolCall.name,
@@ -44706,28 +45323,28 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44706
45323
  await this.refreshVerificationCoverage();
44707
45324
  await this.persistToolCheckpoint("terminal", toolCall.id, turnMessages, toolCheckpoint);
44708
45325
  };
44709
- const recordToolSuccess = async (toolBlock, toolCall, content2, effectiveArgs, managedCommand, contentTruncated = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
45326
+ const recordToolSuccess = async (toolBlock, toolCall, content2, effectiveArgs, managedCommand, contentTruncated2 = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
44710
45327
  toolCall.completedAt = /* @__PURE__ */ new Date();
44711
45328
  toolCall.args = effectiveArgs;
44712
45329
  toolCall.status = "complete";
44713
45330
  toolCall.result = content2;
44714
45331
  const guarded = applyRepeatGuard(toolBlock.name, toolBlock.input, content2, managedCommand);
44715
- await retainToolResult(toolCall, content2, guarded, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
45332
+ await retainToolResult(toolCall, content2, guarded, managedCommand, contentTruncated2, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
44716
45333
  this.emit({ type: "tool_end", tool: toolBlock.name, result: content2, toolCallId: toolBlock.id });
44717
45334
  this.tracer.event({
44718
45335
  type: "tool_end",
44719
45336
  timestamp: /* @__PURE__ */ new Date(),
44720
45337
  data: this.toolTraceData(toolCall)
44721
45338
  });
44722
- return { toolCall, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision, rawContent: content2, toolResult: { tool_use_id: toolBlock.id, content: guarded, is_error: false } };
45339
+ return { toolCall, managedCommand, contentTruncated: contentTruncated2, verificationReceipt, verifierDecision, benchmarkComparisonDecision, rawContent: content2, toolResult: { tool_use_id: toolBlock.id, content: guarded, is_error: false } };
44723
45340
  };
44724
- const recordToolError = async (toolBlock, toolCall, error62, effectiveArgs, managedCommand, contentTruncated = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
45341
+ const recordToolError = async (toolBlock, toolCall, error62, effectiveArgs, managedCommand, contentTruncated2 = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
44725
45342
  toolCall.completedAt = /* @__PURE__ */ new Date();
44726
45343
  if (effectiveArgs !== void 0) toolCall.args = effectiveArgs;
44727
45344
  toolCall.status = "error";
44728
45345
  toolCall.error = error62;
44729
45346
  const guarded = applyRepeatGuard(toolBlock.name, toolBlock.input, `Error: ${error62}`);
44730
- await retainToolResult(toolCall, `Error: ${error62}`, guarded, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
45347
+ await retainToolResult(toolCall, `Error: ${error62}`, guarded, managedCommand, contentTruncated2, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
44731
45348
  this.emit({ type: "tool_error", tool: toolBlock.name, error: error62, toolCallId: toolBlock.id });
44732
45349
  this.tracer.event({
44733
45350
  type: "tool_error",
@@ -44737,7 +45354,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44737
45354
  return {
44738
45355
  toolCall,
44739
45356
  managedCommand,
44740
- contentTruncated,
45357
+ contentTruncated: contentTruncated2,
44741
45358
  verificationReceipt,
44742
45359
  verifierDecision,
44743
45360
  benchmarkComparisonDecision,
@@ -45369,7 +45986,11 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45369
45986
  }
45370
45987
  const useStream = process.env.ZTC_NO_STREAM !== "1" && !backend.streamsSyntheticallyFor?.(request2);
45371
45988
  let answerOutputEmitted = false;
45989
+ let answerOutputSeen = false;
45990
+ let toolOutputEmitted = false;
45372
45991
  let effectObserved = false;
45992
+ let directProbeUsed = false;
45993
+ let lostStreamReason = "";
45373
45994
  let partialAnswer = "";
45374
45995
  let recoveryStartedAt;
45375
45996
  let rateLimitedAttempts = 0;
@@ -45475,10 +46096,14 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45475
46096
  signal,
45476
46097
  () => {
45477
46098
  answerOutputEmitted = true;
46099
+ answerOutputSeen = true;
45478
46100
  },
45479
46101
  onUsage,
45480
46102
  (text5) => {
45481
46103
  partialAnswer = text5;
46104
+ },
46105
+ () => {
46106
+ toolOutputEmitted = true;
45482
46107
  }
45483
46108
  ).then(returned),
45484
46109
  guardPromise
@@ -45539,16 +46164,42 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45539
46164
  );
45540
46165
  }
45541
46166
  const failure2 = this.parseAPIError(error62);
45542
- throw new AgentError(failure2.reason, failure2.kind === "router_refusal" ? ROUTER_USAGE_REFUSED : "API_ERROR");
46167
+ throw new AgentError(
46168
+ failure2.failure ?? failure2.reason,
46169
+ failure2.kind === "router_refusal" ? ROUTER_USAGE_REFUSED : "API_ERROR"
46170
+ );
45543
46171
  }
45544
46172
  if (useStream && answerOutputEmitted) {
45545
46173
  this.emit({ type: "stream_reset" });
45546
46174
  answerOutputEmitted = false;
45547
46175
  }
46176
+ if (request2.transportTurnId === null) {
46177
+ if (!(error62 instanceof BackendHttpError)) throw new StreamLostError(lostStreamReason, partialAnswer, { cause: error62 });
46178
+ request2 = { ...request2, transportTurnId: randomUUID13() };
46179
+ }
45548
46180
  const stalled = timedOut;
45549
- const { retryable, reason, kind } = stalled ? { retryable: true, reason: "LLM request stalled without activity", kind: void 0 } : this.parseAPIError(error62);
46181
+ const parsed = stalled ? { retryable: true, reason: "LLM request stalled without activity", kind: void 0 } : this.parseAPIError(error62);
46182
+ const { retryable, reason, kind } = parsed;
46183
+ const failureReason = parsed.failure ?? reason;
45550
46184
  if (kind === "stream_lost" && !isIncompleteStreamError(error62) && request2.transportTurnId !== void 0) {
45551
46185
  if (attempt >= maxAttempts) {
46186
+ if (!directProbeUsed && !effectObserved && !answerOutputSeen && !toolOutputEmitted) {
46187
+ directProbeUsed = true;
46188
+ lostStreamReason = reason;
46189
+ request2 = { ...request2, transportTurnId: null };
46190
+ this.emit({
46191
+ type: "api_retry",
46192
+ attempt,
46193
+ maxAttempts,
46194
+ delay: 0,
46195
+ reason: "The Router stream was interrupted",
46196
+ phase: "retry",
46197
+ elapsedMs: 0
46198
+ });
46199
+ removeAbortListener?.();
46200
+ removeAbortListener = void 0;
46201
+ continue;
46202
+ }
45552
46203
  throw new StreamLostError(reason, partialAnswer, { cause: error62 });
45553
46204
  }
45554
46205
  request2 = { ...request2, transportTurnId: randomUUID13() };
@@ -45569,7 +46220,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45569
46220
  }
45570
46221
  if (!retryable || maxAttempts === 1 || attempt >= maxAttempts && (recoveryWindowMs === 0 || stalled || isIncompleteStreamError(error62))) {
45571
46222
  if (kind === "context_overflow") {
45572
- throw new ContextOverflowError(reason, request2, error62.message);
46223
+ throw new ContextOverflowError(failureReason, request2, error62.message);
45573
46224
  }
45574
46225
  if (stalled) {
45575
46226
  throw new AgentError(
@@ -45580,21 +46231,21 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45580
46231
  if (isIncompleteStreamError(error62)) {
45581
46232
  throw new AgentError(INCOMPLETE_MODEL_RESPONSE_MESSAGE, INCOMPLETE_MODEL_RESPONSE_CODE);
45582
46233
  }
45583
- throw new AgentError(reason, kind === "router_refusal" ? ROUTER_USAGE_REFUSED : "API_ERROR");
46234
+ throw new AgentError(failureReason, kind === "router_refusal" ? ROUTER_USAGE_REFUSED : "API_ERROR");
45584
46235
  }
45585
46236
  if ((isIncompleteStreamError(error62) || error62 instanceof BackendHttpError && error62.turnEnded) && request2.transportTurnId !== void 0) {
45586
46237
  request2 = { ...request2, transportTurnId: randomUUID13() };
45587
46238
  }
45588
46239
  rateLimitedAttempts = kind === "rate_limit" ? rateLimitedAttempts + 1 : 0;
45589
46240
  if (rateLimitedAttempts >= RATE_LIMITED_ATTEMPTS) {
45590
- throw new AgentError(`${reason.replace(/\.?\s*$/, ".")} Still rate-limited after ${rateLimitedAttempts} attempts, so ZTC stopped retrying. Send a message to try again, or choose another model with /model.`, "API_ERROR");
46241
+ throw new AgentError(`${failureReason.replace(/\.?\s*$/, ".")} Still rate-limited after ${rateLimitedAttempts} attempts, so ZTC stopped retrying. Send a message to try again, or choose another model with /model.`, "API_ERROR");
45591
46242
  }
45592
- lastReason = reason;
46243
+ lastReason = failureReason;
45593
46244
  const recovering = attempt >= maxAttempts;
45594
46245
  if (recovering) recoveryStartedAt ??= Date.now();
45595
46246
  const elapsedMs = recoveryStartedAt === void 0 ? 0 : Math.max(0, Date.now() - recoveryStartedAt);
45596
46247
  if (recovering && recoveryWindowMs !== null && elapsedMs >= recoveryWindowMs) {
45597
- throw new AgentError(reason, stalled ? "API_TIMEOUT" : "API_ERROR");
46248
+ throw new AgentError(failureReason, stalled ? "API_TIMEOUT" : "API_ERROR");
45598
46249
  }
45599
46250
  let delay = Math.max(apiRetryDelayMs(attempt, this.config.apiRetry), retryAfterDelayMs(error62));
45600
46251
  if (recovering) {
@@ -45650,6 +46301,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45650
46301
  let errorMessage = "";
45651
46302
  let admissionMessage = "";
45652
46303
  let admissionCode = "";
46304
+ let routerEnvelope = false;
45653
46305
  let providerName = "";
45654
46306
  let upstreamMessage = "";
45655
46307
  try {
@@ -45680,6 +46332,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45680
46332
  errorMessage = parsed.statusMessage;
45681
46333
  }
45682
46334
  if (errorPayload === true || errorPayload === void 0 && typeof parsed.statusCode === "number") {
46335
+ routerEnvelope = true;
45683
46336
  if (typeof parsed.message === "string") admissionMessage = parsed.message;
45684
46337
  else if (typeof parsed.statusMessage === "string") admissionMessage = parsed.statusMessage;
45685
46338
  if (typeof parsed.data?.code === "string") admissionCode = parsed.data.code;
@@ -45688,6 +46341,8 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45688
46341
  } catch {
45689
46342
  }
45690
46343
  const httpError = error62 instanceof BackendHttpError;
46344
+ const status = httpError ? error62.status : statusCode;
46345
+ const failureProvider = providerName || (httpError && !routerEnvelope ? error62.provider ?? "" : "");
45691
46346
  const body = httpError ? error62.body : /API error \(\d+\): ([\s\S]*)$/.exec(message)?.[1] ?? (statusCode === 0 ? message : "");
45692
46347
  const providerSource = upstreamMessage || (typeof errorMessage === "string" ? errorMessage : "") || (body.trimStart().startsWith("{") ? "" : body);
45693
46348
  const providerText = (httpError ? providerSource : redactErrorText(providerSource)).replace(/\s+/g, " ").trim();
@@ -45697,7 +46352,12 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45697
46352
  return { retryable: false, kind: "stream_lost", reason: "The Router stream was interrupted and cannot be resumed. Send a message to continue from the existing conversation." };
45698
46353
  }
45699
46354
  if (errorCode === "context_length_exceeded" || isContextOverflowMessage(`${errorMessage} ${message}`)) {
45700
- return { retryable: false, reason: "Context window exceeded", kind: "context_overflow" };
46355
+ return {
46356
+ retryable: false,
46357
+ reason: "Context window exceeded",
46358
+ kind: "context_overflow",
46359
+ failure: `${withHttpStatus("Context window exceeded", status, failureProvider)}. Compact the conversation with /compact, or start a new session.`
46360
+ };
45701
46361
  }
45702
46362
  if (statusCode === 529 || errorType === "overloaded_error") {
45703
46363
  return { retryable: true, reason: "API is overloaded" };
@@ -45709,10 +46369,17 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45709
46369
  }
45710
46370
  const routerRateLimit = statusCode === 429 && message.startsWith("ZRouter API error (") && ROUTER_RATE_LIMIT_CODES.has(errorCode) && /^OpenRouter(?:'s)? /.test(errorMessage) ? errorMessage.trim() : "";
45711
46371
  if (routerRateLimit && errorCode === "free_model_daily_limit") {
45712
- return { retryable: false, reason: `${routerRateLimit.replace(/\.?\s*$/, ".")} Choose another model with /model, or wait for the limit to reset.` };
46372
+ const reason = `${routerRateLimit.replace(/\.?\s*$/, ".")} Choose another model with /model, or wait for the limit to reset.`;
46373
+ return { retryable: false, reason, failure: `${withHttpStatus("Plan limit", status, failureProvider)}: ${reason}` };
45713
46374
  }
45714
46375
  if (statusCode === 429 || errorType === "rate_limit_error" || errorType === "RESOURCE_EXHAUSTED") {
45715
- return { retryable: true, reason: routerRateLimit || "Rate limit exceeded", kind: "rate_limit" };
46376
+ const detail = routerRateLimit || admissionMessage || (providerDetail.toLowerCase() === "rate limit exceeded" ? "" : providerDetail);
46377
+ return {
46378
+ retryable: true,
46379
+ reason: routerRateLimit || admissionMessage || "Rate limit exceeded",
46380
+ kind: "rate_limit",
46381
+ failure: `${withHttpStatus("Rate limit", status, failureProvider)}${detail ? `: ${detail}` : ""}`
46382
+ };
45716
46383
  }
45717
46384
  if (statusCode === 504 || statusCode === 503 || statusCode === 502 || statusCode === 500 || errorType === "UNAVAILABLE" || errorType === "INTERNAL") {
45718
46385
  const requestId = /(?:fly-request-id|x-request-id)=([A-Za-z0-9._:-]{1,128})(?:[ \]]|$)/.exec(message)?.[1];
@@ -45781,7 +46448,7 @@ init_capabilities();
45781
46448
  init_logger();
45782
46449
  init_extension_discovery();
45783
46450
  import { homedir as homedir11 } from "os";
45784
- import { join as join23, resolve as resolve19, basename as basename10 } from "path";
46451
+ import { join as join24, resolve as resolve21, basename as basename11 } from "path";
45785
46452
  import { readdir as readdir3, readFile as readFile5 } from "fs/promises";
45786
46453
  var MAX_DEPTH = 4;
45787
46454
  function defaultMarkdownRoots() {
@@ -45790,10 +46457,10 @@ function defaultMarkdownRoots() {
45790
46457
  const home = homedir11();
45791
46458
  return [
45792
46459
  ...explicitRoots,
45793
- join23(process.cwd(), ".ztc", "skills"),
45794
- join23(process.cwd(), ".claude", "skills"),
45795
- join23(home, ".ztc", "skills"),
45796
- join23(home, ".claude", "skills")
46460
+ join24(process.cwd(), ".ztc", "skills"),
46461
+ join24(process.cwd(), ".claude", "skills"),
46462
+ join24(home, ".ztc", "skills"),
46463
+ join24(home, ".claude", "skills")
45797
46464
  ];
45798
46465
  }
45799
46466
  async function walk(dir, depth = 0) {
@@ -45803,7 +46470,7 @@ async function walk(dir, depth = 0) {
45803
46470
  const results = [];
45804
46471
  for (const entry of entries) {
45805
46472
  if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
45806
- const full = join23(dir, entry.name);
46473
+ const full = join24(dir, entry.name);
45807
46474
  if (entry.isDirectory()) {
45808
46475
  results.push(...await walk(full, depth + 1));
45809
46476
  } else if (entry.isFile() && entry.name.toLowerCase() === "skill.md") {
@@ -45906,13 +46573,13 @@ function deriveSkillId(path2, meta3) {
45906
46573
  if (explicit) return explicit;
45907
46574
  const name2 = meta3.name ? String(meta3.name) : "";
45908
46575
  if (name2) return name2.toLowerCase().replace(/\s+/g, "-");
45909
- return basename10(resolve19(path2, "..")) || "skill";
46576
+ return basename11(resolve21(path2, "..")) || "skill";
45910
46577
  }
45911
46578
  async function loadSkills(roots = defaultMarkdownRoots()) {
45912
46579
  const skills = [];
45913
46580
  const seenFiles = /* @__PURE__ */ new Set();
45914
46581
  for (const root of roots) {
45915
- const resolvedRoot = resolve19(root);
46582
+ const resolvedRoot = resolve21(root);
45916
46583
  const paths = await walk(root);
45917
46584
  for (const filePath of paths) {
45918
46585
  if (seenFiles.has(filePath)) continue;
@@ -45945,12 +46612,12 @@ async function loadSkills(roots = defaultMarkdownRoots()) {
45945
46612
  }
45946
46613
 
45947
46614
  // src/skills/bundled/index.ts
45948
- import { dirname as dirname18, resolve as resolve20 } from "path";
46615
+ import { dirname as dirname19, resolve as resolve22 } from "path";
45949
46616
  import { fileURLToPath as fileURLToPath2 } from "url";
45950
46617
 
45951
46618
  // src/skills/bundled/init-context.ts
45952
46619
  import { readdir as readdir4, readFile as readFile6, stat as stat4 } from "fs/promises";
45953
- import { join as join24 } from "path";
46620
+ import { join as join25 } from "path";
45954
46621
  var MAX_ENTRIES = 60;
45955
46622
  var TOP_LEVEL_DIRS_OF_INTEREST = [
45956
46623
  "src",
@@ -46011,7 +46678,7 @@ async function safeReadDir(path2) {
46011
46678
  async function detectManifests(cwd) {
46012
46679
  const found = [];
46013
46680
  for (const { file: file2, label } of MANIFESTS) {
46014
- if (await fileExists(join24(cwd, file2))) {
46681
+ if (await fileExists(join25(cwd, file2))) {
46015
46682
  found.push(`- ${file2} \u2014 ${label}`);
46016
46683
  }
46017
46684
  }
@@ -46019,7 +46686,7 @@ async function detectManifests(cwd) {
46019
46686
  }
46020
46687
  async function readClaudeMd(cwd) {
46021
46688
  for (const name2 of CLAUDE_MD_CANDIDATES) {
46022
- const path2 = join24(cwd, name2);
46689
+ const path2 = join25(cwd, name2);
46023
46690
  if (await fileExists(path2)) {
46024
46691
  try {
46025
46692
  const contents = await readFile6(path2, "utf-8");
@@ -46099,8 +46766,8 @@ var bundledCodeSkills = [
46099
46766
  initContextSkill
46100
46767
  ];
46101
46768
  function bundledMarkdownRoot() {
46102
- const here = dirname18(fileURLToPath2(import.meta.url));
46103
- return resolve20(here);
46769
+ const here = dirname19(fileURLToPath2(import.meta.url));
46770
+ return resolve22(here);
46104
46771
  }
46105
46772
 
46106
46773
  // src/skills/registry.ts
@@ -46280,7 +46947,7 @@ var invokeSkillTool = makeInvokeSkillTool(resolveAmbientSkills);
46280
46947
  // src/zlm.ts
46281
46948
  var ZLM_EMBED_API_VERSION = "zerglang.ztc-embed/1";
46282
46949
  var ZLM_STDIO_PROTOCOL = "zerglang.ztc-host/1";
46283
- var ZLM_ZTC_VERSION = true ? "0.23.1-dev.202611152321" : "development";
46950
+ var ZLM_ZTC_VERSION = true ? "0.24.0-beta.1" : "development";
46284
46951
  var ZLM_MAX_HOST_TOOLS = 64;
46285
46952
  var ZLM_MAX_SYSTEM_PROMPT_BYTES = 128 * 1024;
46286
46953
  var ZLM_HOST_APPROVAL_CAPABILITIES = Object.freeze([
@@ -46415,7 +47082,7 @@ function validateTools(input2) {
46415
47082
  });
46416
47083
  }
46417
47084
  function resolveRequired(value, label) {
46418
- return resolve21(requiredBounded(value, label, 4096));
47085
+ return resolve23(requiredBounded(value, label, 4096));
46419
47086
  }
46420
47087
  function requiredBounded(value, label, maxBytes) {
46421
47088
  const normalized = value.trim();
@@ -46537,9 +47204,9 @@ async function runDirectEntry() {
46537
47204
  var directEntry = false;
46538
47205
  if (process.argv[1]) {
46539
47206
  try {
46540
- directEntry = realpathSync7(resolve21(process.argv[1])) === realpathSync7(fileURLToPath3(import.meta.url));
47207
+ directEntry = realpathSync8(resolve23(process.argv[1])) === realpathSync8(fileURLToPath3(import.meta.url));
46541
47208
  } catch {
46542
- directEntry = resolve21(process.argv[1]) === fileURLToPath3(import.meta.url);
47209
+ directEntry = resolve23(process.argv[1]) === fileURLToPath3(import.meta.url);
46543
47210
  }
46544
47211
  }
46545
47212
  if (directEntry) {