@zergai/ztc 0.26.6-dev.202611240947 → 0.27.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 (268) hide show
  1. package/README.md +629 -167
  2. package/RUST_THIRD_PARTY_LICENSES.txt +5 -5
  3. package/bin/zmux-darwin-arm64 +0 -0
  4. package/bin/zmux-linux-x64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-tui-linux-x64 +0 -0
  12. package/bin/zterm-darwin-arm64 +2 -2
  13. package/dist/App.js +6 -1
  14. package/dist/agent/agent.d.ts +21 -15
  15. package/dist/agent/agent.js +389 -163
  16. package/dist/agent/backends/codex_app_server.d.ts +7 -1
  17. package/dist/agent/backends/codex_app_server.js +11 -1
  18. package/dist/agent/backends/gemini.js +22 -8
  19. package/dist/agent/commands/batch.js +8 -0
  20. package/dist/agent/commands/config.js +10 -0
  21. package/dist/agent/commands/environment.js +5 -5
  22. package/dist/agent/commands/goal.d.ts +1 -0
  23. package/dist/agent/commands/goal.js +2 -1
  24. package/dist/agent/commands/index.js +2 -1
  25. package/dist/agent/commands/manifest.js +4 -0
  26. package/dist/agent/commands/optimize.js +5 -2
  27. package/dist/agent/commands/pane_cli.d.ts +29 -0
  28. package/dist/agent/commands/pane_cli.js +303 -0
  29. package/dist/agent/commands/settings.js +13 -3
  30. package/dist/agent/commands/shannon.js +8 -0
  31. package/dist/agent/commands/update.js +15 -3
  32. package/dist/agent/commands/zerg.js +31 -1
  33. package/dist/agent/commands/ztc_pane.js +3 -1
  34. package/dist/agent/factory.d.ts +4 -0
  35. package/dist/agent/factory.js +11 -1
  36. package/dist/agent/loop_policy.d.ts +42 -5
  37. package/dist/agent/loop_policy.js +206 -3
  38. package/dist/agent/runtime/command_jobs.d.ts +5 -0
  39. package/dist/agent/runtime/command_jobs.js +241 -31
  40. package/dist/agent/runtime/command_wait.d.ts +2 -0
  41. package/dist/agent/runtime/command_wait.js +1 -0
  42. package/dist/agent/runtime/done_report.d.ts +18 -0
  43. package/dist/agent/runtime/done_report.js +130 -0
  44. package/dist/agent/runtime/execution_context.js +4 -1
  45. package/dist/agent/runtime/failure_cause.d.ts +2 -0
  46. package/dist/agent/runtime/failure_cause.js +35 -0
  47. package/dist/agent/runtime/policy.d.ts +14 -2
  48. package/dist/agent/runtime/policy.js +104 -12
  49. package/dist/agent/runtime/quiet_job.d.ts +18 -0
  50. package/dist/agent/runtime/quiet_job.js +48 -0
  51. package/dist/agent/runtime/recovery.d.ts +1 -5
  52. package/dist/agent/runtime/recovery.js +2 -44
  53. package/dist/agent/runtime/tool_runtime.d.ts +1 -0
  54. package/dist/agent/runtime/tool_runtime.js +2 -0
  55. package/dist/agent/subagent.js +6 -1
  56. package/dist/agent/tools/deferred.js +1 -0
  57. package/dist/agent/tools/index.d.ts +2 -0
  58. package/dist/agent/tools/index.js +1 -0
  59. package/dist/agent/tools/outcome.d.ts +15 -0
  60. package/dist/agent/tools/outcome.js +107 -0
  61. package/dist/agent/tools/pane.d.ts +2 -1
  62. package/dist/agent/tools/pane.js +21 -3
  63. package/dist/agent/tools/registry.js +2 -0
  64. package/dist/agent/tools/shell.d.ts +1 -0
  65. package/dist/agent/tools/shell.js +128 -17
  66. package/dist/agent/tools/sim_domain_tools.js +4 -2
  67. package/dist/agent/tools/supervision.js +4 -2
  68. package/dist/agent/tools/types.d.ts +3 -0
  69. package/dist/app/command_context.js +5 -9
  70. package/dist/app/conversation_compaction.d.ts +4 -2
  71. package/dist/app/conversation_compaction.js +16 -5
  72. package/dist/app/headless_shell_mode.d.ts +14 -0
  73. package/dist/app/headless_shell_mode.js +7 -0
  74. package/dist/app/hosted_resident.d.ts +356 -0
  75. package/dist/app/hosted_resident.js +677 -0
  76. package/dist/app/restart.js +11 -2
  77. package/dist/app/session_manager.d.ts +5 -0
  78. package/dist/app/session_manager.js +21 -6
  79. package/dist/app/session_messages.js +6 -6
  80. package/dist/app/workspace_layout_controller.js +7 -0
  81. package/dist/batch/worktree.d.ts +10 -0
  82. package/dist/batch/worktree.js +15 -0
  83. package/dist/bench/registry.js +4 -2
  84. package/dist/cli_args.js +1 -1
  85. package/dist/cli_main.js +80 -10
  86. package/dist/cli_ratatui.d.ts +75 -0
  87. package/dist/cli_ratatui.js +485 -84
  88. package/dist/components/InputArea.js +4 -4
  89. package/dist/config/execution.d.ts +10 -0
  90. package/dist/config/execution.js +10 -0
  91. package/dist/config/hosted_runtime.d.ts +4 -1
  92. package/dist/config/hosted_runtime.js +4 -1
  93. package/dist/config/permission_pin.d.ts +34 -2
  94. package/dist/config/permission_pin.js +52 -2
  95. package/dist/config/person_command_policy.d.ts +38 -0
  96. package/dist/config/person_command_policy.js +11 -0
  97. package/dist/config/profiles.d.ts +21 -0
  98. package/dist/config/profiles.js +56 -2
  99. package/dist/config/types.d.ts +4 -1
  100. package/dist/config.js +34 -19
  101. package/dist/desktop/daily/codex_exec_adapter.js +7 -2
  102. package/dist/desktop/daily/desktop_wiring.d.ts +7 -1
  103. package/dist/desktop/daily/desktop_wiring.js +11 -3
  104. package/dist/desktop/daily/recipes.js +20 -4
  105. package/dist/desktop/health.d.ts +24 -0
  106. package/dist/desktop/health.js +151 -0
  107. package/dist/desktop/native_dialogs.d.ts +37 -0
  108. package/dist/desktop/native_dialogs.js +105 -0
  109. package/dist/diagnostics/session_export.d.ts +1 -0
  110. package/dist/diagnostics/session_export.js +28 -0
  111. package/dist/embedded/registry.js +4 -2
  112. package/dist/emulation/tool_adapters.js +9 -4
  113. package/dist/emulation/ztc_addendum.js +3 -0
  114. package/dist/headless.d.ts +11 -4
  115. package/dist/headless.js +99 -34
  116. package/dist/headless_approval.d.ts +6 -0
  117. package/dist/headless_cli.js +1 -1
  118. package/dist/hooks/runner.js +7 -6
  119. package/dist/library.d.ts +4 -0
  120. package/dist/library.js +3 -0
  121. package/dist/mcp/client.js +3 -3
  122. package/dist/modes/registry.js +13 -4
  123. package/dist/onboarding/setup_environment.js +13 -1
  124. package/dist/optimize/adapters/kernelbench.js +88 -10
  125. package/dist/optimize/adapters/types.d.ts +5 -0
  126. package/dist/optimize/executor.js +21 -0
  127. package/dist/panes/cli_install.d.ts +54 -0
  128. package/dist/panes/cli_install.js +157 -0
  129. package/dist/panes/model_catalog.js +3 -0
  130. package/dist/panes/new_pane_choices.d.ts +6 -2
  131. package/dist/panes/new_pane_choices.js +24 -12
  132. package/dist/panes/pane_cli_launch.d.ts +50 -0
  133. package/dist/panes/pane_cli_launch.js +124 -0
  134. package/dist/panes/pane_clis.d.ts +171 -0
  135. package/dist/panes/pane_clis.js +325 -0
  136. package/dist/panes/person_only_panes.d.ts +45 -0
  137. package/dist/panes/person_only_panes.js +117 -0
  138. package/dist/plugin/simulation_living.js +0 -2
  139. package/dist/plugin/simulation_living_engine.d.ts +1 -0
  140. package/dist/plugin/simulation_living_engine.js +1 -0
  141. package/dist/plugin/simulation_living_labels.d.ts +3 -0
  142. package/dist/plugin/simulation_living_labels.js +2 -0
  143. package/dist/router_auth.js +12 -1
  144. package/dist/session.js +26 -1
  145. package/dist/simulation/art/gemini_image.js +11 -5
  146. package/dist/simulation/domains/loader.js +25 -3
  147. package/dist/simulation/living/cold.d.ts +23 -0
  148. package/dist/simulation/living/cold.js +41 -0
  149. package/dist/simulation/living/context.d.ts +591 -1283
  150. package/dist/simulation/living/context.js +378 -244
  151. package/dist/simulation/living/contradictions.d.ts +14 -0
  152. package/dist/simulation/living/contradictions.js +282 -0
  153. package/dist/simulation/living/core/ids.d.ts +53 -0
  154. package/dist/simulation/living/core/ids.js +39 -0
  155. package/dist/simulation/living/core/kind.d.ts +20 -0
  156. package/dist/simulation/living/core/kind.js +15 -0
  157. package/dist/simulation/living/core/laws.d.ts +179 -0
  158. package/dist/simulation/living/core/laws.js +184 -0
  159. package/dist/simulation/living/core/ops.d.ts +257 -0
  160. package/dist/simulation/living/core/ops.js +34 -0
  161. package/dist/simulation/living/definer.d.ts +17 -1
  162. package/dist/simulation/living/definer.js +130 -51
  163. package/dist/simulation/living/definition.d.ts +174 -65
  164. package/dist/simulation/living/definition.js +287 -180
  165. package/dist/simulation/living/director.d.ts +80 -0
  166. package/dist/simulation/living/director.js +363 -0
  167. package/dist/simulation/living/frame.d.ts +108 -21
  168. package/dist/simulation/living/frame.js +111 -66
  169. package/dist/simulation/living/identifiers.d.ts +0 -1
  170. package/dist/simulation/living/identifiers.js +0 -3
  171. package/dist/simulation/living/index.d.ts +18 -9
  172. package/dist/simulation/living/index.js +18 -9
  173. package/dist/simulation/living/inference.d.ts +92 -50
  174. package/dist/simulation/living/inference.js +319 -175
  175. package/dist/simulation/living/knowledge.d.ts +28 -0
  176. package/dist/simulation/living/knowledge.js +73 -0
  177. package/dist/simulation/living/library.json +1177 -0
  178. package/dist/simulation/living/mechanics.d.ts +31 -34
  179. package/dist/simulation/living/mechanics.js +222 -138
  180. package/dist/simulation/living/model-input.d.ts +6 -3
  181. package/dist/simulation/living/model-input.js +18 -26
  182. package/dist/simulation/living/open-world.d.ts +74 -94
  183. package/dist/simulation/living/open-world.js +151 -30
  184. package/dist/simulation/living/phrases.d.ts +3 -0
  185. package/dist/simulation/living/phrases.js +37 -0
  186. package/dist/simulation/living/phrases.json +560 -0
  187. package/dist/simulation/living/projection.d.ts +316 -2
  188. package/dist/simulation/living/projection.js +50 -2
  189. package/dist/simulation/living/prompts/example-spec.json +11 -0
  190. package/dist/simulation/living/prompts/role-text.json +14 -0
  191. package/dist/simulation/living/prompts.d.ts +5 -0
  192. package/dist/simulation/living/prompts.js +275 -0
  193. package/dist/simulation/living/recall.d.ts +2 -2
  194. package/dist/simulation/living/reduce.d.ts +51 -14
  195. package/dist/simulation/living/reduce.js +941 -579
  196. package/dist/simulation/living/replay.d.ts +5 -4
  197. package/dist/simulation/living/replay.js +10 -9
  198. package/dist/simulation/living/runtime.d.ts +135 -25
  199. package/dist/simulation/living/runtime.js +1641 -583
  200. package/dist/simulation/living/scale.d.ts +96 -0
  201. package/dist/simulation/living/scale.js +124 -0
  202. package/dist/simulation/living/script.d.ts +5 -0
  203. package/dist/simulation/living/script.js +115 -0
  204. package/dist/simulation/living/shared-kinds.d.ts +4 -11
  205. package/dist/simulation/living/shared-kinds.js +11 -81
  206. package/dist/simulation/living/space.d.ts +14 -0
  207. package/dist/simulation/living/space.js +132 -0
  208. package/dist/simulation/living/state.d.ts +100 -0
  209. package/dist/simulation/living/state.js +393 -0
  210. package/dist/simulation/living/types.d.ts +829 -512
  211. package/dist/simulation/living/types.js +162 -187
  212. package/dist/simulation/living/world-rules.d.ts +100 -0
  213. package/dist/simulation/living/world-rules.js +267 -0
  214. package/dist/simulation/plugins/loader.js +11 -0
  215. package/dist/skills/loader.js +4 -0
  216. package/dist/tools.d.ts +1 -0
  217. package/dist/tools.js +1 -0
  218. package/dist/ui/ratatui/headless_pane_manager.d.ts +4 -1
  219. package/dist/ui/ratatui/headless_pane_manager.js +13 -9
  220. package/dist/ui/ratatui/pane_relay.js +29 -0
  221. package/dist/ui/ratatui/pane_type.d.ts +10 -0
  222. package/dist/ui/ratatui/pane_type.js +11 -0
  223. package/dist/ui/ratatui/process.d.ts +30 -0
  224. package/dist/ui/ratatui/process.js +133 -19
  225. package/dist/ui/ratatui/protocol.d.ts +124 -2
  226. package/dist/ui/ratatui/protocol.js +35 -0
  227. package/dist/ui/ratatui/relay_policy.js +3 -0
  228. package/dist/ui/ratatui/ztc_launch_trust.d.ts +2 -1
  229. package/dist/ui/ratatui/ztc_launch_trust.js +8 -1
  230. package/dist/ui/terminal_image.d.ts +12 -0
  231. package/dist/ui/terminal_image.js +21 -1
  232. package/dist/utils/codex_project_trust.d.ts +19 -0
  233. package/dist/utils/codex_project_trust.js +37 -0
  234. package/dist/utils/compaction.js +103 -20
  235. package/dist/utils/git_program_files.d.ts +19 -12
  236. package/dist/utils/git_program_files.js +411 -83
  237. package/dist/utils/host_shell.d.ts +10 -1
  238. package/dist/utils/host_shell.js +14 -1
  239. package/dist/utils/mid_turn_compaction.d.ts +2 -0
  240. package/dist/utils/mid_turn_compaction.js +2 -0
  241. package/dist/utils/models.js +6 -1
  242. package/dist/utils/sandbox.d.ts +109 -8
  243. package/dist/utils/sandbox.js +981 -187
  244. package/dist/utils/shell.d.ts +2 -0
  245. package/dist/utils/shell.js +10 -4
  246. package/dist/utils/subprocess_env.d.ts +47 -11
  247. package/dist/utils/subprocess_env.js +107 -15
  248. package/dist/utils/system_ps.d.ts +8 -0
  249. package/dist/utils/system_ps.js +39 -7
  250. package/dist/utils/unattended_compaction.d.ts +9 -0
  251. package/dist/utils/unattended_compaction.js +13 -0
  252. package/dist/utils/ztc_own_state.d.ts +8 -5
  253. package/dist/utils/ztc_own_state.js +17 -11
  254. package/dist/web/mirror_client.js +1 -0
  255. package/dist/web/mirror_stream.d.ts +50 -6
  256. package/dist/web/mirror_stream.js +160 -15
  257. package/dist/workflows/registry.js +3 -1
  258. package/dist/workspace/controller.js +12 -0
  259. package/dist/workspace_collision.d.ts +3 -0
  260. package/dist/workspace_collision.js +14 -1
  261. package/dist/workspace_session_context.js +2 -1
  262. package/dist/zlm-embed.mjs +3823 -1970
  263. package/node_modules/@zerg/model-contracts/README.md +16 -4
  264. package/node_modules/@zerg/model-contracts/index.js +6 -1
  265. package/npm-shrinkwrap.json +1 -1
  266. package/package.json +42 -24
  267. package/packages/model-contracts/README.md +16 -4
  268. package/packages/model-contracts/index.js +6 -1
@@ -5,7 +5,7 @@ import { CapabilityPolicy } from '../runtime/policy.js';
5
5
  import { pipelineWarning, runShellCommand } from '../../utils/shell.js';
6
6
  import { hostShell } from '../../utils/host_shell.js';
7
7
  import { TurnTimeLimit } from '../runtime/turn_limit.js';
8
- import { adoptCommandJob, startCommandJob, readCommandJob, stopCommandJob, waitForCommandProgress } from '../runtime/command_jobs.js';
8
+ import { adoptCommandJob, listCommandJobs, startCommandJob, readCommandJob, stopCommandJob, waitForCommandProgress } from '../runtime/command_jobs.js';
9
9
  import { resolveExecutionSettings } from '../../config/execution.js';
10
10
  import { configStore } from '../../config.js';
11
11
  import { assertTemporaryRootSafe, isPathWithinRoot } from '../../utils/temporary_write_root.js';
@@ -16,6 +16,7 @@ import { containerPath, dockerTarget } from '../../utils/docker_target.js';
16
16
  import { isEphemeralToolCall } from '../../utils/ephemeral_tools.js';
17
17
  import { COPY_ADVICE, copyNote, saveCopy, unnamedCopy } from '../../utils/tool_output_copies.js';
18
18
  import { isReadOnlyShellCommand } from '../runtime/read_only_command.js';
19
+ import { quietJobNote } from '../runtime/quiet_job.js';
19
20
  import { beginRun, endRun } from '../runtime/run_log.js';
20
21
  // Output kept for a command until it moves to the background; the job log's own cap applies after that.
21
22
  const MOVED_OUTPUT_LIMIT = 16 * 1024 * 1024;
@@ -34,6 +35,40 @@ export function summarizeCommandFailure(output, limit = FAILURE_OUTPUT_LIMIT, co
34
35
  const named = copies.length ? `; ${copies.join('; ')}; ${COPY_ADVICE}` : '';
35
36
  return `${output.slice(0, headLength)}\n… [${omitted} characters omitted${named}] …\n${output.slice(-tailLength)}`;
36
37
  }
38
+ function withArgumentNote(output, note) {
39
+ if (!note)
40
+ return output;
41
+ if (output.startsWith('{')) {
42
+ try {
43
+ const parsed = JSON.parse(output);
44
+ return JSON.stringify({ ...parsed, note: parsed.note ? `${note} ${parsed.note}` : note });
45
+ }
46
+ catch { /* not a JSON receipt */ }
47
+ }
48
+ return `${note}\n${output}`;
49
+ }
50
+ function normalizeRunCommandArguments(args, context) {
51
+ if (!Object.prototype.hasOwnProperty.call(args, 'timeout'))
52
+ return { args };
53
+ const raw = Number(args.timeout);
54
+ if (!Number.isFinite(raw) || typeof args.timeout === 'boolean')
55
+ return { args };
56
+ const temporaryWriteRoot = context?.temporaryWriteRoot === undefined ? undefined : resolve(context.temporaryWriteRoot);
57
+ const canBackground = args.background === undefined && context?.sessionId !== undefined && temporaryWriteRoot === undefined;
58
+ const requested = Math.round(raw);
59
+ if (requested < 1)
60
+ return { args };
61
+ const longTimeoutToBackground = canBackground && requested > FOREGROUND_TIMEOUT_MAX_MS;
62
+ const maximum = args.background === true || longTimeoutToBackground ? BACKGROUND_TIMEOUT_MAX_MS : FOREGROUND_TIMEOUT_MAX_MS;
63
+ const value = Math.min(requested, maximum);
64
+ if (value === raw)
65
+ return { args };
66
+ const note = raw > maximum
67
+ ? `run_command: timeout ${raw}ms is outside the allowed 1–${maximum}ms range; used ${value}ms.`
68
+ : `run_command: timeout ${raw}ms is not a whole number; used ${value}ms.`;
69
+ return { args: { ...args, timeout: value },
70
+ note };
71
+ }
37
72
  /**
38
73
  * R6/F7: actionable hints require observed diagnostics or executor evidence.
39
74
  * A nonzero predicate outcome alone establishes neither cause nor completeness.
@@ -94,7 +129,7 @@ function resolveRunCommandCwd(args, context) {
94
129
  }
95
130
  /** Which shell runs shell text here, so the model writes text that shell reads. */
96
131
  export const SHELL_TEXT_NOTE = process.platform !== 'win32'
97
- ? 'Local macOS/Linux only; shell text runs under /bin/bash, not /bin/sh, so echo prints \\n as written: use printf for escapes.'
132
+ ? 'Local macOS/Linux only; shell text runs under bash when the host has it (/bin/sh otherwise), so echo prints \\n as written: use printf for escapes.'
98
133
  : hostShell('').kind === 'git-bash'
99
134
  ? 'Checked plans run on macOS/Linux only. On this Windows host shell text runs under Git Bash (Git for Windows): write bash, '
100
135
  + 'with Windows paths as C:/dir or /c/dir; echo prints \\n as written: use printf for escapes.'
@@ -103,6 +138,32 @@ export const SHELL_TEXT_NOTE = process.platform !== 'win32'
103
138
  /** The longest a foreground command may run, and the longest a background job may. */
104
139
  const FOREGROUND_TIMEOUT_MAX_MS = 600_000;
105
140
  const BACKGROUND_TIMEOUT_MAX_MS = 86_400_000;
141
+ const SLEEP_POLL_MIN_MS = 30_000;
142
+ const FOREGROUND_WAIT_MS = 30_000;
143
+ const READ_ONLY_STAGE = /^(?:tail|head|cat|less|more|grep|egrep|wc|ls|stat|file|date|echo|printf|test|true|false|\[)$/;
144
+ export function sleepPollingRefusal(command, timeoutMs) {
145
+ if (timeoutMs === undefined || timeoutMs < FOREGROUND_WAIT_MS)
146
+ return null;
147
+ const lead = /^\s*(?:cd\s+[^;&|\n]+?\s*(?:&&|;)\s*)?sleep\s+(\d+(?:\.\d+)?)(ms|s|m|h|)?\s*(?:;|&&|\|\|)\s*([\s\S]*)$/.exec(command);
148
+ if (!lead)
149
+ return null;
150
+ const factor = lead[2] === 'ms' ? 1 : lead[2] === 'm' ? 60_000 : lead[2] === 'h' ? 3_600_000 : 1_000;
151
+ if (Number(lead[1]) * factor < SLEEP_POLL_MIN_MS)
152
+ return null;
153
+ const rest = lead[3].trim().replace(/;\s*$/, '');
154
+ if (!rest)
155
+ return null;
156
+ if (/(?:^|[^&])&(?:\s|$)/.test(rest))
157
+ return null;
158
+ const stages = rest.split(/\s*(?:;|&&|\|\||\n)\s*/).filter(Boolean);
159
+ const readsOnly = stages.length > 0 && stages.every(stage => READ_ONLY_STAGE.test(stage.split(/\s+/)[0]));
160
+ if (!readsOnly)
161
+ return null;
162
+ return 'Refused: `sleep ...` in the foreground blocks this turn and learns nothing sooner than a job '
163
+ + 'receipt does. Start the work you are waiting for with background: true, then call read_command with its '
164
+ + "job_id and until: 'exit' — that returns as soon as the job ends instead of polling its log — and "
165
+ + 'stop_command stops it. If the work already finished, read its result now.';
166
+ }
106
167
  export const runCommandTool = {
107
168
  sandboxedCommands: true,
108
169
  isErrorResult: failedCommandReceipt,
@@ -172,7 +233,19 @@ export const runCommandTool = {
172
233
  // which failed every Claude model through OpenRouter (2026-10-27). execute enforces it, and both say so.
173
234
  }),
174
235
  },
175
- execute: (args, context) => recordRun(args, context, run => executeRunCommand(args, context, run)),
236
+ execute: (args, context) => {
237
+ const normalized = normalizeRunCommandArguments(args, context);
238
+ return recordRun(normalized.args, context, async (run) => {
239
+ try {
240
+ return withArgumentNote(await executeRunCommand(normalized.args, context, run), normalized.note);
241
+ }
242
+ catch (error) {
243
+ if (normalized.note && error instanceof Error)
244
+ error.message += `\n${normalized.note}`;
245
+ throw error;
246
+ }
247
+ });
248
+ },
176
249
  };
177
250
  /** Every run gets a host record of its outcome, and its result names the run so a report can cite it. */
178
251
  async function recordRun(args, context, body) {
@@ -262,6 +335,10 @@ async function executeRunCommand(args, context, run) {
262
335
  if (command === 'undefined' || command.trim() === '') {
263
336
  throw new Error(`run_command: command argument is invalid: "${command}"`);
264
337
  }
338
+ const requestedTimeout = args.background === true ? undefined : Number(args.timeout);
339
+ const sleepPoll = sleepPollingRefusal(command, Number.isFinite(requestedTimeout) ? requestedTimeout : undefined);
340
+ if (sleepPoll)
341
+ throw new Error(sleepPoll);
265
342
  const cwd = resolveRunCommandCwd(args, context);
266
343
  const temporaryWriteRoot = context?.temporaryWriteRoot === undefined
267
344
  ? undefined
@@ -513,7 +590,10 @@ async function executeRunCommand(args, context, run) {
513
590
  const hint = shellErrorHint(result.exitCode, result.stderr ?? '', Boolean(result.stdout?.trim()), result.timedOut === true);
514
591
  const stages = result.pipelineExitCodes ? `\npipe stages exited ${result.pipelineExitCodes.join(' ')}` : '';
515
592
  const sandboxSaid = result.sandboxNotes ? `\nsandbox: ${result.sandboxNotes.join(' ')}` : '';
516
- throw new Error(`Command failed (exit ${result.exitCode}):\n${outputSnippet}${stages}${sandboxSaid}${result.execution_policy ? `\nexecution: ${JSON.stringify(observation)}` : ''}${hint ? `\n\nhint: ${hint}` : ''}`);
593
+ const failure = new Error(`Command failed (exit ${result.exitCode}):\n${outputSnippet}${stages}${sandboxSaid}${result.execution_policy ? `\nexecution: ${JSON.stringify(observation)}` : ''}${hint ? `\n\nhint: ${hint}` : ''}`);
594
+ if (result.timedOut === true)
595
+ failure.timedOut = true;
596
+ throw failure;
517
597
  }
518
598
  const warning = pipelineWarning(result.pipelineExitCodes, result.earlierPipelineExitCodes);
519
599
  // Named first: output cut in the middle reads as whole, and an agent parsed 62 KB of JSON cut that way (forge3d, 2026-11-06).
@@ -544,27 +624,49 @@ export const readCommandTool = {
544
624
  definition: {
545
625
  // Its jobs come from run_command; a provider running its own shell (Codex) gets neither.
546
626
  overlapsProviderHarness: true,
547
- name: 'read_command', description: "Read a managed command receipt and up to 16KB of incremental output. Cursor is a byte offset returned by the previous receipt. Zero wait is nonblocking. A positive wait wakes on output or terminal state; the host may keep waiting on a healthy silent job between model requests. With until: 'exit' one call waits for the job to end (wait_ms up to 600000) and adds output_tail, the log's last 4KB, where build and test summaries are. Running does not mean success.",
627
+ name: 'read_command', description: "Read a managed command receipt and up to 16KB of incremental output. Cursor is a byte offset returned by the previous receipt. Zero wait is nonblocking. A positive wait wakes on output or terminal state; the host may keep waiting on a healthy silent job between model requests. With until: 'exit' one call waits for the job to end (wait_ms up to 600000) and adds output_tail, the log's last 4KB, where build and test summaries are. This is how to wait for long work: `sleep N; tail …` in the foreground is refused. Running does not mean success.",
548
628
  parameters: { type: 'object', properties: {
549
- job_id: { type: 'string', description: 'Session-owned job ID from run_command.' }, cursor: { type: 'number', description: 'Byte cursor from the previous read (default 0).' }, wait_ms: { type: 'number', description: "0–60000ms, or up to 600000 with until: 'exit'; wakes for output, terminal state or this read deadline. Zero requests an immediate inspection." },
629
+ job_id: { type: 'string', description: 'Session-owned job ID from run_command; omit to list this session\'s managed jobs with their commands and status.' }, cursor: { type: 'number', description: 'Byte cursor from the previous read (default 0).' }, wait_ms: { type: 'number', description: "0–60000ms, or up to 600000 with until: 'exit'; wakes for output, terminal state or this read deadline. Zero requests an immediate inspection." },
550
630
  until: { type: 'string', enum: ['exit'], description: "'exit' waits for the job to end instead of waking on new output." },
551
- }, required: ['job_id'] },
631
+ } },
552
632
  },
553
633
  execute: async (args, context) => {
554
634
  if (!context?.sessionId)
555
635
  throw new Error('Managed commands require a session ID.');
636
+ if (args.job_id === undefined || args.job_id === null || String(args.job_id).trim() === '') {
637
+ const jobs = listCommandJobs(context.sessionId).map(job => ({ job_id: job.job_id, status: job.status,
638
+ command: job.command, cwd: job.cwd, ...(job.exit_code === undefined ? {} : { exit_code: job.exit_code }),
639
+ started_at: job.started_at, ...(job.ended_at === undefined ? {} : { ended_at: job.ended_at }),
640
+ ...(job.elapsed_ms === undefined ? {} : { elapsed_ms: job.elapsed_ms }), log_path: job.log_path }));
641
+ return JSON.stringify({ jobs, note: jobs.length
642
+ ? 'These jobs belong to this session, including ones an earlier ZTC process started. Read one with its job_id, wait for it with until: \'exit\', or end it with stop_command.'
643
+ : 'This session has no managed jobs. run_command with background: true starts one.' });
644
+ }
556
645
  if (args.until !== undefined && args.until !== 'exit')
557
646
  throw new Error("until must be 'exit' when given.");
558
647
  const untilExit = args.until === 'exit';
559
- const requestedWaitMs = Number(args.wait_ms ?? 0);
560
648
  const waitLimit = untilExit ? 600000 : 60000;
561
- if (!Number.isSafeInteger(requestedWaitMs) || requestedWaitMs < 0 || requestedWaitMs > waitLimit) {
562
- throw new Error(`wait_ms must be an integer between 0 and ${waitLimit}.`);
563
- }
649
+ const rawWaitMs = Number(args.wait_ms ?? 0);
650
+ if (!Number.isFinite(rawWaitMs))
651
+ throw new Error(`wait_ms must be a number between 0 and ${waitLimit}.`);
652
+ const requestedWaitMs = Math.min(Math.max(Math.round(rawWaitMs), 0), waitLimit);
653
+ const waitNote = requestedWaitMs === rawWaitMs ? undefined
654
+ : rawWaitMs < 0 || rawWaitMs > waitLimit
655
+ ? `read_command: wait_ms ${rawWaitMs} is outside the allowed 0–${waitLimit}ms range; used ${requestedWaitMs}ms.`
656
+ : `read_command: wait_ms ${rawWaitMs} is not a whole number; used ${requestedWaitMs}ms.`;
657
+ const rawCursor = Number(args.cursor ?? 0);
658
+ const cursor = Number.isFinite(rawCursor) ? Math.max(0, Math.round(rawCursor)) : 0;
659
+ const cursorNote = cursor === rawCursor ? undefined
660
+ : !Number.isFinite(rawCursor) ? `read_command: cursor ${rawCursor} is not a number; used ${cursor}.`
661
+ : rawCursor < 0 ? `read_command: cursor ${rawCursor} is outside the allowed range; used ${cursor}.`
662
+ : `read_command: cursor ${rawCursor} is not a whole number; used ${cursor}.`;
663
+ const note = [waitNote, cursorNote].filter(Boolean).join(' ') || undefined;
664
+ const withNote = (value) => note
665
+ ? { ...value, note: value.note ? `${note} ${value.note}` : note } : value;
564
666
  if (untilExit) {
565
667
  const jobId = String(args.job_id);
566
- const cursor = Number(args.cursor ?? 0);
567
668
  const deadline = Date.now() + requestedWaitMs;
669
+ const waitStartedAt = Date.now();
568
670
  let result = await readCommandJob(context.sessionId, jobId, cursor, 0, context.signal, context.canInspectVerificationSource);
569
671
  while (result.status === 'running' && Date.now() < deadline) {
570
672
  result = await readCommandJob(context.sessionId, jobId, cursor, Math.min(60000, Math.max(1, deadline - Date.now())), context.signal, context.canInspectVerificationSource);
@@ -572,19 +674,21 @@ export const readCommandTool = {
572
674
  context.onManagedCommand?.({ sessionId: context.sessionId, result, requestedWaitMs, kind: 'read' });
573
675
  const profile = context.commandPolicy?.profile;
574
676
  const followed = withFollowedFile(result, profile);
575
- return JSON.stringify(result.status === 'running' ? followed
576
- : { ...followed, output_tail: logTail(result.log_path) || (result.followed_file ? followedTail(result.followed_file, result.cwd, profile) : '') });
677
+ return JSON.stringify(result.status === 'running' ? withNote(withSilence(followed, requestedWaitMs, Date.now() - waitStartedAt, profile))
678
+ : withNote({ ...followed, output_tail: logTail(result.log_path) || (result.followed_file ? followedTail(result.followed_file, result.cwd, profile) : '') }));
577
679
  }
578
680
  const slice = context.managedCommandWaitSliceMs;
579
681
  if (slice !== undefined && (!Number.isSafeInteger(slice) || slice < 0 || slice > 60000)) {
580
682
  throw new Error('managedCommandWaitSliceMs must be an integer between 0 and 60000.');
581
683
  }
582
684
  const maxWaitMs = slice === undefined ? requestedWaitMs : Math.min(requestedWaitMs, slice);
685
+ const waitStartedAt = Date.now();
583
686
  const result = requestedWaitMs === 0
584
- ? await readCommandJob(context.sessionId, String(args.job_id), Number(args.cursor ?? 0), 0, context.signal, context.canInspectVerificationSource)
585
- : (await waitForCommandProgress(context.sessionId, String(args.job_id), { cursor: Number(args.cursor ?? 0), maxWaitMs, signal: context.signal, canInspectVerificationSource: context.canInspectVerificationSource })).result;
687
+ ? await readCommandJob(context.sessionId, String(args.job_id), cursor, 0, context.signal, context.canInspectVerificationSource)
688
+ : (await waitForCommandProgress(context.sessionId, String(args.job_id), { cursor, maxWaitMs, signal: context.signal, canInspectVerificationSource: context.canInspectVerificationSource })).result;
586
689
  context.onManagedCommand?.({ sessionId: context.sessionId, result, requestedWaitMs, kind: 'read' });
587
- return JSON.stringify(withFollowedFile(result, context.commandPolicy?.profile));
690
+ const profile = context.commandPolicy?.profile;
691
+ return JSON.stringify(withNote(withSilence(withFollowedFile(result, profile), requestedWaitMs, Date.now() - waitStartedAt, profile)));
588
692
  },
589
693
  };
590
694
  /**
@@ -662,6 +766,13 @@ function logTail(path) {
662
766
  return '';
663
767
  }
664
768
  }
769
+ /** The receipt, with a note when a wait of at least half its length brought nothing from a job quiet a minute or more. */
770
+ function withSilence(result, requestedWaitMs, waitedMs, profile) {
771
+ if (requestedWaitMs <= 0 || waitedMs * 2 < requestedWaitMs)
772
+ return result;
773
+ const note = quietJobNote(result, profile, waitedMs);
774
+ return note ? { ...result, note } : result;
775
+ }
665
776
  /** macOS open(2): fail when any part of the path is a symbolic link, not only the last (macOS 11 and later). */
666
777
  const O_NOFOLLOW_ANY = 0x20000000;
667
778
  /**
@@ -17,6 +17,7 @@ import { existsSync } from 'node:fs';
17
17
  import { join } from 'node:path';
18
18
  import { pathToFileURL } from 'node:url';
19
19
  import { createRequire } from 'node:module';
20
+ import { loadsExtensionFile } from '../../app/hosted_resident.js';
20
21
  import { runtimeDiagOnce } from '../../utils/debug_log.js';
21
22
  import { ToolCapability } from '../runtime/capabilities.js';
22
23
  import { createWordDocumentTool, createSpreadsheetTool, createPresentationTool, updateDocumentTool, readDocumentTool, listDocumentsTool, commentOnDocumentTool, } from './sim_document.js';
@@ -108,7 +109,8 @@ export function loadDomainHandlersSync(sourceDir) {
108
109
  const require_ = createRequire(import.meta.url);
109
110
  for (const name of candidates) {
110
111
  const full = join(sourceDir, name);
111
- if (!existsSync(full))
112
+ // A hosted resident's ZTC pane loads none whose real path is in its workspace (app/hosted_resident.ts).
113
+ if (!existsSync(full) || !loadsExtensionFile(full))
112
114
  continue;
113
115
  if (loadedHandlerFiles.has(full))
114
116
  return 0;
@@ -145,7 +147,7 @@ export async function loadDomainHandlers(sourceDir) {
145
147
  const candidates = ['handlers.mjs', 'handlers.js', 'handlers.cjs'];
146
148
  for (const name of candidates) {
147
149
  const full = join(sourceDir, name);
148
- if (!existsSync(full))
150
+ if (!existsSync(full) || !loadsExtensionFile(full))
149
151
  continue;
150
152
  if (loadedHandlerFiles.has(full))
151
153
  return 0;
@@ -1,6 +1,7 @@
1
1
  import { request } from 'http';
2
2
  import { ToolCapability } from '../runtime/capabilities.js';
3
3
  import { configStore } from '../../config.js';
4
+ import { nestedRunEnv } from '../../config/profiles.js';
4
5
  import { ROUTE_AWAITS_A_CHOICE } from '../../config/retired_routes.js';
5
6
  import { PANE_TASK_AS_MESSAGE_ENV } from '../../panes/initial_input.js';
6
7
  import { generateSessionId } from '../../session.js';
@@ -278,8 +279,9 @@ export const createSupervisedZtcPaneTool = {
278
279
  ratio,
279
280
  target,
280
281
  pane_type: 'ztc',
281
- // Words among the child's arguments are its launch task, the agent's: a message, never the person's command.
282
- env: { [PANE_TASK_AS_MESSAGE_ENV]: '1' },
282
+ // Words among the child's arguments are its launch task, the agent's: a message, never the person's command. The
283
+ // pane is the agent's, a nested run of this ZTC (config/profiles.ts nestedRunEnv).
284
+ env: { ...nestedRunEnv(), [PANE_TASK_AS_MESSAGE_ENV]: '1' },
283
285
  }, childTitle, 'ztc');
284
286
  const feedTitle = args.feed_title
285
287
  ? String(args.feed_title)
@@ -34,6 +34,8 @@ export interface ToolContext {
34
34
  task: string;
35
35
  environment?: string;
36
36
  };
37
+ /** The task's own Done-when items, which a done report is held against. */
38
+ doneWhen?: readonly string[];
37
39
  availableTools?: Tool[];
38
40
  workflowTimeoutMs?: number;
39
41
  /** When the host stops this run (headless --timeout), in epoch ms; a foreground command must not outlive it. */
@@ -127,6 +129,7 @@ export interface Tool {
127
129
  /** Explicit successful terminal response. Only supported by the ZTC-owned
128
130
  * agent loop, and only when this is the sole tool call in a response. */
129
131
  finalResponse?: (result: string) => string | undefined;
132
+ finalOutcome?: (result: string) => 'done' | 'blocked' | 'needs_input' | undefined;
130
133
  /** Request-time availability of state-dependent tools. Execution must still
131
134
  * validate its preconditions because state can change after advertisement. */
132
135
  isAvailable?: (context: Pick<ToolContext, 'cwd'>) => boolean | Promise<boolean>;
@@ -3,6 +3,7 @@ import { lastDiscoveredModels, loadModelCatalog } from './model_catalog_cache.js
3
3
  import { getSkills } from '../skills/registry.js';
4
4
  import { runShellCommand } from '../utils/shell.js';
5
5
  import { configStore } from '../config.js';
6
+ import { personCommandPolicy } from '../config/person_command_policy.js';
6
7
  import { ToolCapability } from '../agent/runtime/capabilities.js';
7
8
  import { routerAccount, routerRefusalGate } from '../agent/backends/router_gate.js';
8
9
  // ─── Input Routing ───────────────────────────────────────────────────
@@ -204,17 +205,12 @@ export function buildShellController(getCwd, setCwd) {
204
205
  setCwd: async (path) => setCwd(path),
205
206
  run: async (command) => {
206
207
  const cwd = getCwd();
207
- const config = configStore.get();
208
- const profileId = config.permissionProfile || 'trusted';
209
208
  // Under its host's pin (ZTC_PERMISSION_PROFILE_PINNED) the person's own commands run only inside an OS sandbox, as
210
- // the agent's do, or not at all: a pinned profile that runs none of the agent's needs none, and !cmd, from the
211
- // terminal or a mirror's controller, ran outside any and wrote the config folder the pin is taken from (the
212
- // recheck of the follow-ups, 2026-11-23).
213
- const sandbox = configStore.permissionsPinned() ? { ...config.sandbox, requireOsEnforcement: true } : config.sandbox;
209
+ // the agent's do, or not at all (config/person_command_policy.ts): a pinned profile that runs none of the agent's
210
+ // needs none, and !cmd, from the terminal or a mirror's controller, ran outside any and wrote the config folder the
211
+ // pin is taken from (the recheck of the follow-ups, 2026-11-23).
214
212
  return runShellCommand(command, cwd, undefined, undefined, {
215
- profileId,
216
- profile: configStore.getEffectivePermissionProfile(profileId),
217
- sandbox,
213
+ ...personCommandPolicy(configStore),
218
214
  capabilities: [ToolCapability.SHELL_EXEC],
219
215
  });
220
216
  },
@@ -35,8 +35,10 @@ export declare function compactToRecover(messages: Message[], model: string, sum
35
35
  }): Promise<CompactionResult>;
36
36
  /**
37
37
  * Whether the context reached the configured trigger (a share of the window, or the token budget), and where the
38
- * compaction should land. `used` is the provider's count for the last request; the estimate stands in before one.
38
+ * compaction should land. `used` is the provider's count for the last request; the estimate stands in before one. An
39
+ * unattended run whose trigger is a share of the window also compacts at its early size (unattendedCompactTokens), and
40
+ * lands as it would under a token budget that size. A token budget someone set is theirs, and stays the trigger.
39
41
  */
40
- export declare function autoCompactDecision(messages: Message[], model: string, used: number, windowOverride?: number | null, threshold?: number): AutoCompactDecision;
42
+ export declare function autoCompactDecision(messages: Message[], model: string, used: number, windowOverride?: number | null, threshold?: number, unattended?: boolean): AutoCompactDecision;
41
43
  /** Compaction at the trigger, with the configured method and landing point. */
42
44
  export declare function compactAtTrigger(messages: Message[], model: string, summarizer: CompactionSummarizer, decision: AutoCompactDecision, onUsage?: ModelUsageObserver): Promise<CompactionResult>;
@@ -1,6 +1,8 @@
1
1
  import { configStore } from '../config.js';
2
2
  import { compactConversation, compactMessages, localSummarizer, modelHandoffSummarizer, smartSummarizer, } from '../utils/compaction.js';
3
- import { estimateConversationTokens, getContextWindowSize, resolveAutoCompact } from '../utils/context.js';
3
+ import { resolveExecutionSettings } from '../config/execution.js';
4
+ import { estimateConversationTokens, getContextWindowSize, isTokenTriggerActive, resolveAutoCompact } from '../utils/context.js';
5
+ import { unattendedCompactTokens } from '../utils/unattended_compaction.js';
4
6
  /** A cheap model's summary when the provider has a key, else a local one. */
5
7
  export function fallbackSummarizer(onUsage, signal) {
6
8
  const provider = configStore.getProvider();
@@ -57,10 +59,12 @@ export function compactToRecover(messages, model, summarizer, options = {}) {
57
59
  }
58
60
  /**
59
61
  * Whether the context reached the configured trigger (a share of the window, or the token budget), and where the
60
- * compaction should land. `used` is the provider's count for the last request; the estimate stands in before one.
62
+ * compaction should land. `used` is the provider's count for the last request; the estimate stands in before one. An
63
+ * unattended run whose trigger is a share of the window also compacts at its early size (unattendedCompactTokens), and
64
+ * lands as it would under a token budget that size. A token budget someone set is theirs, and stays the trigger.
61
65
  */
62
- export function autoCompactDecision(messages, model, used, windowOverride, threshold = configStore.getAutoCompactThreshold()) {
63
- return resolveAutoCompact({
66
+ export function autoCompactDecision(messages, model, used, windowOverride, threshold = configStore.getAutoCompactThreshold(), unattended = false) {
67
+ const policy = {
64
68
  used: used > 0 ? used : estimateConversationTokens(messages),
65
69
  model,
66
70
  windowOverride,
@@ -68,7 +72,14 @@ export function autoCompactDecision(messages, model, used, windowOverride, thres
68
72
  triggerMode: configStore.getCompactionTriggerMode(),
69
73
  tokenBudget: configStore.getContextTokenBudget(),
70
74
  targetPercent: configStore.getCompactionTargetPercent(),
71
- });
75
+ };
76
+ const ordinary = resolveAutoCompact(policy);
77
+ if (!unattended || isTokenTriggerActive(policy.triggerMode, policy.tokenBudget))
78
+ return ordinary;
79
+ const early = unattendedCompactTokens(ordinary.total, resolveExecutionSettings(configStore.get().execution).unattendedCompactPercent);
80
+ if (early === undefined || early >= ordinary.total * threshold / 100)
81
+ return ordinary;
82
+ return resolveAutoCompact({ ...policy, triggerMode: 'tokens', tokenBudget: early });
72
83
  }
73
84
  /** Compaction at the trigger, with the configured method and landing point. */
74
85
  export function compactAtTrigger(messages, model, summarizer, decision, onUsage) {
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The shell ZTC's slash commands (/shell, its ! shorthand, /cd) get when a
3
+ * host runs ZTC headless. ZTC_HEADLESS_SHELL_MODE=stub keeps them inert;
4
+ * real, the default, runs them on the host. Headless mode (headless.ts) and a
5
+ * headless mirror (the resident ZTC a runtime starts with --headless
6
+ * --mirror, whose controllers type into it) read the setting alike; the
7
+ * agent's own tools are not slash commands and keep running.
8
+ */
9
+ export type HeadlessShellMode = 'real' | 'stub';
10
+ export declare function headlessShellMode(env?: NodeJS.ProcessEnv): HeadlessShellMode;
11
+ /** Whether the interactive app's slash-command shell is the stub: only as a headless mirror whose host asked for it. */
12
+ export declare function stubsMirrorShell(options: {
13
+ headlessMirror: boolean;
14
+ }, env?: NodeJS.ProcessEnv): boolean;
@@ -0,0 +1,7 @@
1
+ export function headlessShellMode(env = process.env) {
2
+ return env.ZTC_HEADLESS_SHELL_MODE?.trim().toLowerCase() === 'stub' ? 'stub' : 'real';
3
+ }
4
+ /** Whether the interactive app's slash-command shell is the stub: only as a headless mirror whose host asked for it. */
5
+ export function stubsMirrorShell(options, env = process.env) {
6
+ return options.headlessMirror && headlessShellMode(env) === 'stub';
7
+ }