@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
@@ -11,14 +11,15 @@ import { mergeTokenUsage } from './backends/token_usage.js';
11
11
  import { createUsageSnapshot, mergeUsageSnapshots, parseUsageSnapshot, recordUsageReceipt } from '../usage_snapshot.js';
12
12
  import { IncompleteStreamError, isIncompleteStreamError, isTransportCodeError, isTransportMessageError } from './backends/transport_errors.js';
13
13
  import { BackendHttpError, redactErrorText, retryAfterDelayMs } from './backends/http_error.js';
14
- import { formatRouterRefusal, readRouterRefusal, ROUTER_USAGE_REFUSED, RouterRefusalError, withHttpStatus } from './backends/router_refusal.js';
14
+ import { cleanRouterText, formatRouterRefusal, readRouterRefusal, ROUTER_USAGE_REFUSED, RouterRefusalError, withHttpStatus } from './backends/router_refusal.js';
15
15
  import { inferDefaultProvider, getDefaultApiKeyForProvider, getDefaultModelForProvider } from '../config/defaults.js';
16
16
  import { apiRetryDelayMs, resolveApiRetrySettings } from '../config/api_retry.js';
17
17
  import { resolveExecutionSettings } from '../config/execution.js';
18
18
  import { createRecoveryGuard } from './runtime/recovery.js';
19
19
  import { filesNamedIn } from './runtime/request_files.js';
20
- import { listCommandJobs, interruptCommandJobs } from './runtime/command_jobs.js';
20
+ import { listCommandJobs, interruptCommandJobs, startedHere } from './runtime/command_jobs.js';
21
21
  import { awaitManagedCommandProgress, formatManagedCommandObservations } from './runtime/command_wait.js';
22
+ import { quietJobNote } from './runtime/quiet_job.js';
22
23
  import { describeExecutionContext, DELETION_EVIDENCE_GUIDANCE } from './runtime/execution_context.js';
23
24
  import { batchOverLimit, scheduleToolBatch, describeBlockingResult, unfinishedCommand } from './runtime/tool_scheduler.js';
24
25
  import { describeRun, handoffRunRows, listRuns, openFailures } from './runtime/run_log.js';
@@ -49,16 +50,18 @@ import { RequestEncoder, STABLE_RESULT_LIMIT, nativeHistoryContextId } from './r
49
50
  import { presentToolResult } from './tool_result_presentation.js';
50
51
  import { BackgroundWorkers, formatWorkerReports } from './background_workers.js';
51
52
  import { parseImageToolResult } from './tool_result_parsing.js';
52
- import { announcesNextStep, completionCheckDue, createRepeatGuard, isAnnouncementOnly, needsCompletionCheck, pinnedTaskSystem } from './loop_policy.js';
53
+ import { announcesNextStep, clipTask, completionCheckDue, createCommandRepeatGuard, createNoProgressGuard, createRepeatGuard, isAnnouncementOnly, isShellToolName, needsCompletionCheck, NO_PROGRESS_NUDGE, noProgressStalledMessage, pinnedTaskSystem, restateTaskNote } from './loop_policy.js';
53
54
  import { extractSourcePath } from './tool_compression.js';
54
55
  import { executeToolWithRuntime } from './runtime/tool_runtime.js';
55
56
  import { createToolProgressAccumulator } from './runtime/tool_progress.js';
56
57
  import { ToolCapability } from './runtime/capabilities.js';
57
58
  import { buildUserSubprocessEnv } from '../utils/subprocess_env.js';
58
- import { projectHandoffHistory, resolvePromptPrefixId } from '../utils/compaction.js';
59
+ import { projectHandoffHistory, resolvePromptPrefixId, selectRealUserMessages } from '../utils/compaction.js';
59
60
  import { hostModelContextBudget, hostModelContextError } from './host_model_context.js';
60
61
  import { estimateConversationTokens, getContextWindowSize } from '../utils/context.js';
61
62
  import { shouldCompactMidTurn } from '../utils/mid_turn_compaction.js';
63
+ import { unattendedCompactTokens } from '../utils/unattended_compaction.js';
64
+ import { doneWhenItems } from './runtime/done_report.js';
62
65
  import { clampCompletionTokens } from '../utils/deepseek.js';
63
66
  import { resolveToolEffect } from './runtime/tool_effects.js';
64
67
  import { INCOMPLETE_MODEL_RESPONSE_CODE, INCOMPLETE_MODEL_RESPONSE_MESSAGE, incompleteModelResponseMessage, isIncompleteModelResponse, isOutputLimitStop, OUTPUT_LIMIT_RETRY_NOTE, outputLimitRetryEffort, repeatedRunawayMessage, RUNAWAY_OUTPUT_CODE, runawayRetryNote, } from './completion_state.js';
@@ -96,6 +99,49 @@ function simpleDiff(diff, change) {
96
99
  function getTool(name, tools) {
97
100
  return tools.find(tool => tool.definition.name === name);
98
101
  }
102
+ function findLastBriefIndex(messages) {
103
+ for (let i = messages.length - 1; i >= 0; i--) {
104
+ const message = messages[i];
105
+ if (message.role === 'user' && !message.metadata?.synthetic && !message.metadata?.hostContext)
106
+ return i;
107
+ }
108
+ return -1;
109
+ }
110
+ function longSessionNoteIndex(messages) {
111
+ let afterSummary = 0;
112
+ for (let i = messages.length - 1; i >= 0; i--) {
113
+ if (messages[i].metadata?.compactionSummary) {
114
+ afterSummary = i + 1;
115
+ break;
116
+ }
117
+ }
118
+ const brief = findLastBriefIndex(messages);
119
+ return Math.max(afterSummary, brief < 0 ? 0 : brief);
120
+ }
121
+ function isLongSessionNote(message) {
122
+ return message.id.startsWith('long_session_');
123
+ }
124
+ function isCommandCall(input) {
125
+ if (input === null || typeof input !== 'object')
126
+ return false;
127
+ const row = input;
128
+ return typeof row.command === 'string' || row.checked !== undefined;
129
+ }
130
+ function commandTimedOut(content, managedCommand) {
131
+ if (managedCommand?.result.status === 'timed_out')
132
+ return true;
133
+ try {
134
+ const parsed = JSON.parse(content);
135
+ return parsed.status === 'timed_out';
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ }
141
+ function normalizedToolInput(input) {
142
+ return input !== null && typeof input === 'object' && !Array.isArray(input)
143
+ ? input : {};
144
+ }
99
145
  export class AgentError extends Error {
100
146
  code;
101
147
  constructor(message, code, options) {
@@ -168,6 +214,13 @@ const HEADLESS_AUTONOMY_NUDGE = 'No human is available in this run, so nobody wi
168
214
  + 'by something you cannot resolve yourself, and then say exactly what blocks you. '
169
215
  + 'Stay within what the task asked for: leave steps beyond it, such as publishing, deploying or messaging people, '
170
216
  + 'to whoever reads the result.';
217
+ const END_PROTOCOL_NUDGE = 'No outcome has been declared, so this run cannot end yet. If the task is done, call '
218
+ + 'declare_outcome with outcome "done" and the final answer in its text argument. If something only someone else '
219
+ + 'can resolve blocks you, call declare_outcome with outcome "blocked" and the reason in text. If you need input '
220
+ + 'from the user, call declare_outcome with outcome "needs_input" and what you need in text. Otherwise continue '
221
+ + 'working on the task now. '
222
+ + 'Stay within what the task asked for: leave steps beyond it, such as publishing, deploying or messaging people, '
223
+ + 'to whoever reads the result.';
171
224
  /**
172
225
  * Resolve the per-attempt request timeout.
173
226
  *
@@ -270,6 +323,9 @@ export const API_TIMEOUT_CODE = 'API_TIMEOUT';
270
323
  export const RECOVERY_EXHAUSTED_CODE = 'RECOVERY_EXHAUSTED';
271
324
  /** The AgentError code of a run nobody watches that stopped because the provider stayed rate-limited (apiRetry.rateLimitWaitMs). */
272
325
  export const RATE_LIMITED_CODE = 'RATE_LIMITED';
326
+ function newRunTurn() {
327
+ return { retry: null, usedTools: false, endProtocol: { request: '', inARow: 0, total: 0 }, doneWhen: { items: [] } };
328
+ }
273
329
  // --- Agent Class ---
274
330
  export class Agent {
275
331
  config;
@@ -322,16 +378,10 @@ export class Agent {
322
378
  _lastResponseStreamed = false;
323
379
  _cwd;
324
380
  _autoContinue;
381
+ _runawayEscalationLimit;
325
382
  modelSupportsTools;
326
- /** Auto-continues spent since the last tool run; reset per turn and per tool. */
327
- _consecutiveAutoContinues = 0;
328
- _turnAutoContinues = 0;
329
- _turnToolBatches = 0;
330
- _turnToolChangedState = false;
331
- _turnCommandsRun = new Set();
332
- /** What this turn has read, by tool and arguments: reading something new is progress for the auto-continue budget. */
333
- _turnReadsSeen = new Set();
334
- _turnCheckAsked = false;
383
+ /** The newest run's count of the end protocol's nudges: a run that asks the same request again (a stall's retry) goes on from it. */
384
+ _endProtocol = newRunTurn().endProtocol;
335
385
  _subprocessEnv;
336
386
  commandPolicy;
337
387
  toolEffectObserver;
@@ -527,6 +577,8 @@ export class Agent {
527
577
  jobsEndWithTurn: config.jobsEndWithTurn ?? (() => false),
528
578
  maxConsecutiveAutoContinues: config.maxConsecutiveAutoContinues ?? 3,
529
579
  noHumanAvailable: config.noHumanAvailable ?? false,
580
+ unattended: config.unattended ?? false,
581
+ endProtocol: config.endProtocol ?? false,
530
582
  pinTaskHeader: config.pinTaskHeader ?? true,
531
583
  deferToolSchemas: config.deferToolSchemas ?? true,
532
584
  };
@@ -575,6 +627,8 @@ export class Agent {
575
627
  } };
576
628
  this._cwd = this.config.cwd;
577
629
  this._autoContinue = this.config.autoContinue;
630
+ this._runawayEscalationLimit = config.execution?.runawayEscalations === undefined
631
+ ? 1 : resolveExecutionSettings(config.execution).runawayEscalations;
578
632
  this.hooks = config.hooks;
579
633
  this.approvalRequester = config.approvalRequester;
580
634
  this.approvalRequiredCapabilities = [...(config.approvalRequiredCapabilities ?? [])];
@@ -1185,6 +1239,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1185
1239
  return repaired;
1186
1240
  }
1187
1241
  buildRequest(messages, availableTools = this.config.tools, run = this.activeRun) {
1242
+ this.noteDoneWhen(messages, run);
1188
1243
  // A host policy may replace the starting model. Keep configured tools and
1189
1244
  // caller intent intact; filter the effective surface for the selected turn.
1190
1245
  if (!this.modelSupportsTools)
@@ -1670,7 +1725,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1670
1725
  _workChecked = false;
1671
1726
  /** Whether this run was told about jobs still running as its turn ended (jobsEndWithTurn). */
1672
1727
  _jobsChecked = false;
1673
- _turnUsedTools = false;
1728
+ /** The request the long session's note was last placed for: one note per request, whatever runs ask it again. */
1729
+ _longSessionGuardFor = null;
1674
1730
  /** The session's run log, or undefined when the session keeps none. */
1675
1731
  recordedRuns() {
1676
1732
  const path = this.toolResponseStore.runLogPath();
@@ -1690,6 +1746,56 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1690
1746
  unreportedRunFailures() {
1691
1747
  return openFailures(this.recordedRuns() ?? []).filter(run => !this._reportedRunFailures.has(run.run_id));
1692
1748
  }
1749
+ /** The host check, if any, that holds RUN's final answer: the run log's, then its jobs', then the repository's. */
1750
+ nextHostCompletionCheck(run, answer) {
1751
+ // A pass the run log contradicts never stands as the last word: two of four agents reported one.
1752
+ if (this.config.runCheck()) {
1753
+ const failing = this.unreportedRunFailures();
1754
+ if (failing.length > 0) {
1755
+ for (const failed of failing)
1756
+ this._reportedRunFailures.add(failed.run_id);
1757
+ return { reason: 'run check',
1758
+ note: '[Host run check] ZTC\'s run log shows commands whose latest run did not pass, with no later run of the '
1759
+ + `same command that exited 0:\n${failing.map(failed => `- ${describeRun(failed)}`).join('\n')}\n`
1760
+ + 'If the task needs them to pass, run them again now. Otherwise say plainly in your answer that they still fail; '
1761
+ + 'do not report them as passing.' };
1762
+ }
1763
+ }
1764
+ // A headless run stops the jobs it started when it ends; one stage ended saying its two-hour job "is still
1765
+ // running", and the job died with it (scan-lab, 2026-11-13). Tell the model once, before it ends. One that another
1766
+ // ZTC on the session runs goes on.
1767
+ const runningJobs = !this._jobsChecked && this.config.jobsEndWithTurn() && this.config.sessionId
1768
+ ? listCommandJobs(this.config.sessionId).filter(job => job.status === 'running' && startedHere(job)) : [];
1769
+ if (runningJobs.length > 0) {
1770
+ this._jobsChecked = true;
1771
+ return { reason: 'job check',
1772
+ note: '[Host job check] These commands you started are still running, and this run stops them when it ends:\n'
1773
+ + runningJobs.map(job => `- job ${job.job_id}: \`${job.command}\` (log ${job.log_path})`).join('\n')
1774
+ + '\nWait for each one you need with read_command (until: \'exit\'), or stop it with stop_command. Then say in your '
1775
+ + 'answer which finished and which were stopped; do not describe a job as still running.' };
1776
+ }
1777
+ // A "done" from a session that changed nothing may be someone else's work: one agent took the base
1778
+ // commit's report, another unit's, for its own and quit (forge3d, 2026-11-03). A session that can neither write
1779
+ // files nor run a command that writes (a read-only review: its commands run in an OS sandbox that allows no
1780
+ // writes) cannot change the repository, so it is not asked.
1781
+ const workBase = this.toolResponseStore.workBasePath();
1782
+ const permissions = this.config.runtimeFacts.permissions;
1783
+ const allowed = permissions?.capabilities;
1784
+ const commandsWriteNothing = allowed?.file_write === false && permissions?.commandSandbox.requested === true
1785
+ && permissions.commandSandbox.enforcement === 'os';
1786
+ const canChangeRepository = !allowed || allowed.file_write !== false || (allowed.shell_exec !== false && !commandsWriteNothing);
1787
+ const unchanged = !this._workChecked && run.usedTools && workBase && this.config.cwd && canChangeRepository
1788
+ && this.config.runCheck() && claimsDone(answer) ? unchangedWork(workBase, this.config.cwd) : null;
1789
+ if (unchanged) {
1790
+ this._workChecked = true;
1791
+ return { reason: 'work check',
1792
+ note: `[Host work check] Nothing in this repository has changed during this session: HEAD is still `
1793
+ + `${unchanged.head.slice(0, 11)} ("${unchanged.subject.slice(0, 120)}"), as when the session began, and the worktree has `
1794
+ + 'no new changes. Work already there may belong to another task or branch. If this task was really finished before '
1795
+ + 'this session, name the commit or file that shows it and the part of the task\'s instructions it meets. Otherwise do the task now.' };
1796
+ }
1797
+ return undefined;
1798
+ }
1693
1799
  /** The checkpoint row heading the conversation; `requestId` is the message the latest request answered. */
1694
1800
  taskHandoffTurn = null;
1695
1801
  /** What the checkpoint learned since that row, each sent just before the message it arrived with. */
@@ -1786,6 +1892,30 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1786
1892
  const trimmed = task.trim();
1787
1893
  this._taskHeader = trimmed.length > 0 ? trimmed : null;
1788
1894
  }
1895
+ /** What RUN's done report is held against: the person's newest Done-when items in its messages, else the pinned task's. */
1896
+ taskDoneWhen(run) {
1897
+ const items = run?.doneWhen.items ?? [];
1898
+ return items.length > 0 ? items : doneWhenItems(this._taskHeader ?? '');
1899
+ }
1900
+ /** The Done-when items of the person's newest message in RUN's MESSAGES that has any, kept on RUN: no other run's. */
1901
+ noteDoneWhen(messages, run) {
1902
+ if (!run)
1903
+ return;
1904
+ // The host's own completion checks are user messages too, and a job check quotes the commands it names.
1905
+ const authored = selectRealUserMessages(messages)
1906
+ .filter(message => !message.metadata?.hostContext && !/^\[Host (?:run|job|work) check\]/.test(message.content));
1907
+ const newest = authored[0]?.id;
1908
+ if (newest === run.doneWhen.readAt)
1909
+ return;
1910
+ run.doneWhen = { items: [], readAt: newest };
1911
+ for (const message of authored) {
1912
+ const items = doneWhenItems(message.content);
1913
+ if (items.length > 0) {
1914
+ run.doneWhen = { items, readAt: newest };
1915
+ return;
1916
+ }
1917
+ }
1918
+ }
1789
1919
  /** Append the pinned task header (R7) to the static system prompt. */
1790
1920
  getExecutionContext() {
1791
1921
  return this.executionContext(this.activeRun);
@@ -1897,7 +2027,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1897
2027
  const attempt = { pending: this.personRequestPending };
1898
2028
  this.personRequestPending = false;
1899
2029
  // What this run prepares for its requests is its own too: a run unwinding after this one starts never clears it.
1900
- const run = { retry: null };
2030
+ const run = newRunTurn();
1901
2031
  this.activeRun = run;
1902
2032
  // Only an admission the take itself makes (the person's steering it hands over) is this run's. One already
1903
2033
  // pending belongs to the person's next message: a cancelled run still takes steering as it unwinds.
@@ -1957,7 +2087,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1957
2087
  }
1958
2088
  }
1959
2089
  }
1960
- async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = { retry: null }) {
2090
+ async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = newRunTurn()) {
1961
2091
  const binding = this.#conversationBinding;
1962
2092
  if (!binding)
1963
2093
  return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt, run);
@@ -2039,7 +2169,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2039
2169
  }
2040
2170
  }
2041
2171
  // Main execution loop shared by hosted and standalone turns.
2042
- async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = { retry: null }) {
2172
+ async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }, run = newRunTurn()) {
2043
2173
  if (!this.hasApiKey()) {
2044
2174
  throw new AgentError('No API key configured. Use /config key <key> to set one.', 'NO_API_KEY');
2045
2175
  }
@@ -2057,16 +2187,24 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2057
2187
  const allToolCalls = [];
2058
2188
  const turnMessages = [];
2059
2189
  let iterations = 0;
2060
- // Each turn gets its own auto-continue budget; a long-running Agent must
2061
- // not inherit one spent by the previous turn.
2062
- this._consecutiveAutoContinues = 0;
2063
- this._turnAutoContinues = 0;
2064
- this._turnToolBatches = 0;
2065
- this._turnCommandsRun.clear();
2066
- this._turnReadsSeen.clear();
2067
- this._turnCheckAsked = false;
2068
- this._turnUsedTools = false;
2190
+ // Each turn gets its own auto-continue budget and completion checks; a long-running Agent must not inherit one spent
2191
+ // by the previous turn, nor have it changed by a cancelled one that is still unwinding.
2192
+ /** Auto-continues spent since the last tool run; reset per tool. */
2193
+ let consecutiveAutoContinues = 0;
2194
+ let turnAutoContinues = 0;
2195
+ let turnToolBatches = 0;
2196
+ let turnToolChangedState = false;
2197
+ let turnCheckAsked = false;
2198
+ const turnCommandsRun = new Set();
2199
+ /** What this turn has read, by tool and arguments: reading something new is progress for the auto-continue budget. */
2200
+ const turnReadsSeen = new Set();
2201
+ // A request's nudges are counted across the runs that ask it (a stall's retry), each run by a count of its own.
2202
+ const asked = authored?.id ?? '';
2203
+ run.endProtocol = this._endProtocol.request === asked ? { ...this._endProtocol } : { request: asked, inARow: 0, total: 0 };
2204
+ if (this.activeRun === run)
2205
+ this._endProtocol = run.endProtocol;
2069
2206
  let finalContent = '';
2207
+ let finalOutcome;
2070
2208
  // Provider-opaque reasoning trace for the turn the caller will persist.
2071
2209
  // Reasoning models (Kimi K3, DeepSeek) expect the assistant message replayed
2072
2210
  // "as-is, including any reasoning_content"; without this the trace survives
@@ -2087,7 +2225,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2087
2225
  // continue but ran out of iterations — a silent stall today (C5/F8).
2088
2226
  let stopReason = 'max_iterations';
2089
2227
  let outputLimitRetried = false;
2090
- let runawayRetried = false;
2228
+ let runawayRetries = 0;
2229
+ const runawayEscalationLimit = this._runawayEscalationLimit;
2091
2230
  let midTurnMessagesSinceCompaction = 0;
2092
2231
  // The first answer a host check questioned (see AgentRunResult.answerBeforeHostChecks).
2093
2232
  let answerBeforeHostChecks;
@@ -2113,7 +2252,33 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2113
2252
  // reproduced a byte-identical result as non-progressing (F8 churn / F1
2114
2253
  // re-fire). Result-equality (not raw repeat count) spares legitimate polling.
2115
2254
  const applyRepeatGuard = createRepeatGuard();
2255
+ const applyNoProgressGuard = createNoProgressGuard({
2256
+ nudgeAfter: resolveExecutionSettings(this.config.execution).noProgressNudgeAfter,
2257
+ stopAfter: resolveExecutionSettings(this.config.execution).noProgressStopAfter,
2258
+ });
2259
+ const executionSettings = resolveExecutionSettings(this.config.execution);
2260
+ const commandRepeatGuard = createCommandRepeatGuard(executionSettings.commandRepeatLimit, executionSettings.commandRepeatLongRunningMs);
2116
2261
  const recovery = createRecoveryGuard(this.config.execution);
2262
+ // Restate a new request at the end of the history it describes, never inside an earlier block, so the request
2263
+ // prefix stays a prefix across turns. One guard and one note per user message.
2264
+ const longSessionAfter = resolveExecutionSettings(this.config.execution).longSessionCompactAfter;
2265
+ if (authored && !signal?.aborted && messages.length >= longSessionAfter && this._longSessionGuardFor !== authored.id) {
2266
+ this._longSessionGuardFor = authored.id;
2267
+ for (let i = messages.length - 1; i >= 0; i--)
2268
+ if (isLongSessionNote(messages[i]))
2269
+ messages.splice(i, 1);
2270
+ for (let i = turnMessages.length - 1; i >= 0; i--)
2271
+ if (isLongSessionNote(turnMessages[i]))
2272
+ turnMessages.splice(i, 1);
2273
+ const task = typeof authored.content === 'string' ? authored.content : '';
2274
+ const note = { id: `long_session_${randomUUID()}`, role: 'user',
2275
+ content: `[Host note] This is a long session (${messages.length} messages). The current request is:\n${clipTask(task, 4000)}\n`
2276
+ + 'Do the work this request asks for now. Do not answer with an earlier report or repeat work the conversation already records.',
2277
+ timestamp: new Date(), metadata: { synthetic: true, hostContext: true } };
2278
+ messages.splice(longSessionNoteIndex(messages), 0, note);
2279
+ turnMessages.splice(longSessionNoteIndex(turnMessages), 0, note);
2280
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
2281
+ }
2117
2282
  try {
2118
2283
  while (iterations < this.config.maxIterations) {
2119
2284
  if (signal?.aborted) {
@@ -2164,6 +2329,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2164
2329
  messages.splice(0, messages.length, ...compacted);
2165
2330
  turnMessages.splice(0, turnMessages.length, ...compacted);
2166
2331
  applyRepeatGuard.forget();
2332
+ applyNoProgressGuard.reset();
2333
+ commandRepeatGuard.forget();
2167
2334
  this.emit({ type: 'history_checkpoint', messages: [...turnMessages], replacesHistory: true });
2168
2335
  request = this.buildRequest(messages, availableTools, run);
2169
2336
  budget = hostModelContextBudget(this.turnBackend(run), request);
@@ -2238,11 +2405,45 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2238
2405
  this.retainUsageReceipt({ ...identity, observedAt: new Date().toISOString(),
2239
2406
  source: 'unavailable', usage: null, costUsd: null });
2240
2407
  // A runaway response was stopped while streaming and is never accepted.
2241
- // Partial tool calls in it never run. Retry once per turn with a note.
2408
+ // Partial tool calls in it never run.
2242
2409
  if (error instanceof RunawayOutputError) {
2243
- if (runawayRetried)
2410
+ if (runawayRetries >= runawayEscalationLimit) {
2244
2411
  throw new AgentError(repeatedRunawayMessage(error), RUNAWAY_OUTPUT_CODE);
2245
- runawayRetried = true;
2412
+ }
2413
+ runawayRetries++;
2414
+ const restate = runawayRetries >= 2 ? restateTaskNote(messages, this._taskHeader) : undefined;
2415
+ if (this.onMidTurnCompact) {
2416
+ try {
2417
+ // The window of the model the host chose for this run, when it chose one.
2418
+ const compacted = await this.onMidTurnCompact({ messages: [...messages],
2419
+ usedTokens: estimateConversationTokens(messages),
2420
+ windowTokens: (run.prepared ? undefined : this.midTurnCompactWindow)
2421
+ ?? this.turnBackend(run).getModelCapabilities?.(request.model)?.context_window,
2422
+ signal });
2423
+ if (signal?.aborted)
2424
+ throw new AgentError('Cancelled', 'CANCELLED');
2425
+ if (compacted?.length) {
2426
+ messages.splice(0, messages.length, ...compacted);
2427
+ turnMessages.splice(0, turnMessages.length, ...compacted);
2428
+ applyRepeatGuard.forget();
2429
+ applyNoProgressGuard.reset();
2430
+ commandRepeatGuard.forget();
2431
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages], replacesHistory: true });
2432
+ }
2433
+ }
2434
+ catch (failure) {
2435
+ if (signal?.aborted)
2436
+ throw failure;
2437
+ // The retry is the recovery; compaction is an aid.
2438
+ }
2439
+ }
2440
+ if (restate) {
2441
+ const note = { id: `runaway_restate_${randomUUID()}`, role: 'user', content: restate,
2442
+ timestamp: new Date(), metadata: { synthetic: true, hostContext: true } };
2443
+ messages.push(note);
2444
+ turnMessages.push(note);
2445
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
2446
+ }
2246
2447
  run.retry = { note: runawayRetryNote(error.runaway.kind), effort: outputLimitRetryEffort(this.turnBackend(run).getModelCapabilities?.(request.model)?.reasoning?.choices, this._codexEffort) };
2247
2448
  this.emit({ type: 'api_retry', attempt: 1, maxAttempts: 1, delay: 0, phase: 'retry', elapsedMs: 0,
2248
2449
  reason: error.runaway.kind === 'garbled' ? 'The response turned into unreadable characters and was stopped; retrying'
@@ -2337,9 +2538,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2337
2538
  const occupiedIds = new Set([...this.recordedToolCalls.keys(), ...requestedIds]);
2338
2539
  const toolUseBlocks = [];
2339
2540
  for (const block of requestedToolBlocks) {
2541
+ const input = normalizedToolInput(block.input);
2340
2542
  if (/^[A-Za-z0-9_-]{1,256}$/.test(block.id)
2341
2543
  && !this.recordedToolCalls.has(block.id) && !await this.hasStoredToolIdentity(block.id)) {
2342
- toolUseBlocks.push(block);
2544
+ toolUseBlocks.push({ ...block, input });
2343
2545
  continue;
2344
2546
  }
2345
2547
  let id;
@@ -2351,7 +2553,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2351
2553
  id = `tool_${randomUUID()}`;
2352
2554
  } while (occupiedIds.has(id) || await this.hasStoredToolIdentity(id));
2353
2555
  occupiedIds.add(id);
2354
- toolUseBlocks.push({ ...block, id });
2556
+ toolUseBlocks.push({ ...block, id, input });
2355
2557
  }
2356
2558
  if (this.turnBackend(run).preservesNativeHistory && toolUseBlocks.length > 0) {
2357
2559
  // Native replay keeps opaque signed blocks unchanged. Its tool-use
@@ -2412,6 +2614,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2412
2614
  }
2413
2615
  messages.push(...steering);
2414
2616
  turnMessages.push(...steering);
2617
+ applyNoProgressGuard.reset();
2415
2618
  this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
2416
2619
  if (signal?.aborted)
2417
2620
  throw new AgentError('Cancelled', 'CANCELLED');
@@ -2424,23 +2627,30 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2424
2627
  continue;
2425
2628
  }
2426
2629
  }
2427
- // Check if we should auto-continue. Bounded: every continuation is a
2428
- // full-context request, so a model that keeps narrating an intention
2429
- // instead of calling a tool must not be able to spend maxIterations
2430
- // round trips on it. The budget is reset by any executed tool.
2431
- const unattended = this.needsAutonomousContinuation(iterationText);
2630
+ const endProtocol = this.modelSupportsTools && this.config.endProtocol && this.config.runCheck();
2631
+ const autonomous = !endProtocol && this.needsAutonomousContinuation(iterationText);
2432
2632
  const announced = this.shouldContinue(iterationText);
2433
- if (!this.remoteResourceSession && (unattended || announced)
2434
- && this._consecutiveAutoContinues < this.config.maxConsecutiveAutoContinues) {
2435
- this._consecutiveAutoContinues++;
2633
+ const endProtocolDue = endProtocol
2634
+ && run.endProtocol.inARow < (this.config.execution.endProtocolNudges ?? 3)
2635
+ && run.endProtocol.total < (this.config.execution.endProtocolTotalNudges ?? 12);
2636
+ const autoContinueDue = (autonomous || announced)
2637
+ && consecutiveAutoContinues < this.config.maxConsecutiveAutoContinues;
2638
+ if (!this.remoteResourceSession && (endProtocolDue || autoContinueDue)) {
2639
+ if (endProtocolDue) {
2640
+ run.endProtocol.inARow++;
2641
+ run.endProtocol.total++;
2642
+ }
2643
+ else
2644
+ consecutiveAutoContinues++;
2436
2645
  const acTodos = getLatestTodos();
2437
2646
  const incomplete = acTodos.filter(t => t.status !== 'completed');
2438
- let continueMsg = unattended ? HEADLESS_AUTONOMY_NUDGE : 'continue';
2439
- let reason = unattended ? 'no human available to answer' : '';
2647
+ let continueMsg = endProtocolDue ? END_PROTOCOL_NUDGE : autonomous ? HEADLESS_AUTONOMY_NUDGE : 'continue';
2648
+ let reason = endProtocolDue ? 'end protocol' : autonomous ? 'no human available to answer' : '';
2440
2649
  if (incomplete.length > 0) {
2441
2650
  const remaining = incomplete.map(t => t.content).join(', ');
2442
2651
  const todoMsg = `You still have ${incomplete.length} incomplete task(s): ${remaining}. Continue working on them.`;
2443
- continueMsg = unattended ? `${HEADLESS_AUTONOMY_NUDGE} ${todoMsg}` : todoMsg;
2652
+ continueMsg = endProtocolDue ? `${END_PROTOCOL_NUDGE} ${todoMsg}`
2653
+ : autonomous ? `${HEADLESS_AUTONOMY_NUDGE} ${todoMsg}` : todoMsg;
2444
2654
  reason = `${incomplete.length} incomplete task(s): ${remaining}`;
2445
2655
  }
2446
2656
  keepNudgedAnswer(iterationText);
@@ -2469,16 +2679,16 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2469
2679
  continue; // Don't break, keep looping
2470
2680
  }
2471
2681
  if (!this.remoteResourceSession
2472
- && needsCompletionCheck({ usedTools: this._turnToolBatches > 0, hasPendingToolCall: false })
2473
- && completionCheckDue({ autoContinue: this.getAutoContinue() && this.config.completionCheck === true, toolBatches: this._turnToolBatches,
2474
- changedState: this._turnToolChangedState,
2475
- askedSinceProgress: this._turnCheckAsked,
2476
- turnChecks: this._turnAutoContinues, hardCap: this.config.maxConsecutiveAutoContinues,
2682
+ && needsCompletionCheck({ usedTools: turnToolBatches > 0, hasPendingToolCall: false })
2683
+ && completionCheckDue({ autoContinue: this.getAutoContinue() && this.config.completionCheck === true, toolBatches: turnToolBatches,
2684
+ changedState: turnToolChangedState,
2685
+ askedSinceProgress: turnCheckAsked,
2686
+ turnChecks: turnAutoContinues, hardCap: this.config.maxConsecutiveAutoContinues,
2477
2687
  reply: iterationText })) {
2478
2688
  const hardCap = this.config.maxConsecutiveAutoContinues;
2479
- this._turnAutoContinues++;
2480
- this._turnCheckAsked = this._turnAutoContinues < hardCap;
2481
- this._turnToolBatches = 0;
2689
+ turnAutoContinues++;
2690
+ turnCheckAsked = turnAutoContinues < hardCap;
2691
+ turnToolBatches = 0;
2482
2692
  const acTodos = getLatestTodos();
2483
2693
  const incomplete = acTodos.filter(t => t.status !== 'completed');
2484
2694
  const remaining = incomplete.length > 0
@@ -2515,83 +2725,11 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2515
2725
  turnMessages.push(completionPrompt);
2516
2726
  continue; // Don't break, keep looping
2517
2727
  }
2518
- // A pass the run log contradicts never stands as the last word: two of four agents reported one.
2519
- const failing = !this.remoteResourceSession && this._autoContinue && this.config.completionCheck === true
2520
- && this.config.runCheck() ? this.unreportedRunFailures() : [];
2521
- if (failing.length > 0) {
2522
- for (const failed of failing)
2523
- this._reportedRunFailures.add(failed.run_id);
2524
- keepCheckedAnswer(iterationText);
2525
- this.emit({ type: 'auto_continue', reason: 'run check' });
2526
- messages.push({
2527
- id: `assistant_${Date.now()}`,
2528
- role: 'assistant',
2529
- turn: requestUsage?.getTurn?.(),
2530
- content: iterationText,
2531
- ...(this.turnBackend(run).preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(run), nativeContextId: this._nativeContextId } : {}),
2532
- timestamp: new Date(),
2533
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2534
- });
2535
- messages.push({
2536
- id: `run_check_${Date.now()}`,
2537
- role: 'user',
2538
- content: '[Host run check] ZTC\'s run log shows commands whose latest run did not pass, with no later run of the '
2539
- + `same command that exited 0:\n${failing.map(failed => `- ${describeRun(failed)}`).join('\n')}\n`
2540
- + 'If the task needs them to pass, run them again now. Otherwise say plainly in your answer that they still fail; '
2541
- + 'do not report them as passing.',
2542
- turn: requestUsage?.getTurn?.(),
2543
- timestamp: new Date(),
2544
- });
2545
- continue;
2546
- }
2547
- // A headless run stops the jobs it started when it ends; one stage ended saying its two-hour job "is still
2548
- // running", and the job died with it (scan-lab, 2026-11-13). Tell the model once, before it ends.
2549
- const runningJobs = !this.remoteResourceSession && !this._jobsChecked && this._autoContinue
2550
- && this.config.completionCheck === true && this.config.jobsEndWithTurn() && this.config.sessionId
2551
- ? listCommandJobs(this.config.sessionId).filter(job => job.status === 'running') : [];
2552
- if (runningJobs.length > 0) {
2553
- this._jobsChecked = true;
2554
- keepCheckedAnswer(iterationText);
2555
- this.emit({ type: 'auto_continue', reason: 'job check' });
2556
- messages.push({
2557
- id: `assistant_${Date.now()}`,
2558
- role: 'assistant',
2559
- turn: requestUsage?.getTurn?.(),
2560
- content: iterationText,
2561
- ...(this.turnBackend(run).preservesNativeHistory ? { nativeContent: structuredClone(response.content), nativeModel: this.turnModel(run), nativeContextId: this._nativeContextId } : {}),
2562
- timestamp: new Date(),
2563
- metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2564
- });
2565
- messages.push({
2566
- id: `job_check_${Date.now()}`,
2567
- role: 'user',
2568
- content: '[Host job check] These commands you started are still running, and this run stops them when it ends:\n'
2569
- + runningJobs.map(job => `- job ${job.job_id}: \`${job.command}\` (log ${job.log_path})`).join('\n')
2570
- + '\nWait for each one you need with read_command (until: \'exit\'), or stop it with stop_command. Then say in your '
2571
- + 'answer which finished and which were stopped; do not describe a job as still running.',
2572
- turn: requestUsage?.getTurn?.(),
2573
- timestamp: new Date(),
2574
- });
2575
- continue;
2576
- }
2577
- // A "done" from a session that changed nothing may be someone else's work: one agent took the base
2578
- // commit's report, another unit's, for its own and quit (forge3d, 2026-11-03). A session that can neither write
2579
- // files nor run a command that writes (a read-only review: its commands run in an OS sandbox that allows no
2580
- // writes) cannot change the repository, so it is not asked.
2581
- const workBase = this.toolResponseStore.workBasePath();
2582
- const permissions = this.config.runtimeFacts.permissions;
2583
- const allowed = permissions?.capabilities;
2584
- const commandsWriteNothing = allowed?.file_write === false && permissions?.commandSandbox.requested === true
2585
- && permissions.commandSandbox.enforcement === 'os';
2586
- const canChangeRepository = !allowed || allowed.file_write !== false || (allowed.shell_exec !== false && !commandsWriteNothing);
2587
- const unchanged = !this.remoteResourceSession && !this._workChecked && this._turnUsedTools && workBase && this.config.cwd
2588
- && canChangeRepository
2589
- && this._autoContinue && this.config.completionCheck === true && this.config.runCheck() && claimsDone(iterationText)
2590
- ? unchangedWork(workBase, this.config.cwd) : null;
2591
- if (unchanged) {
2592
- this._workChecked = true;
2728
+ const hostCheck = !this.remoteResourceSession && this._autoContinue && this.config.completionCheck === true
2729
+ ? this.nextHostCompletionCheck(run, iterationText) : undefined;
2730
+ if (hostCheck) {
2593
2731
  keepCheckedAnswer(iterationText);
2594
- this.emit({ type: 'auto_continue', reason: 'work check' });
2732
+ this.emit({ type: 'auto_continue', reason: hostCheck.reason });
2595
2733
  messages.push({
2596
2734
  id: `assistant_${Date.now()}`,
2597
2735
  role: 'assistant',
@@ -2602,18 +2740,14 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2602
2740
  metadata: { ...(response.responseItems ? { openaiResponseItems: response.responseItems, openaiResponseModel: this.turnModel(run) } : {}), ...(this.config.runtimeFacts.mode === 'plan' ? { planMode: true } : {}), ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
2603
2741
  });
2604
2742
  messages.push({
2605
- id: `work_check_${Date.now()}`,
2743
+ id: `${hostCheck.reason.replace(' ', '_')}_${Date.now()}`,
2606
2744
  role: 'user',
2607
- content: `[Host work check] Nothing in this repository has changed during this session: HEAD is still `
2608
- + `${unchanged.head.slice(0, 11)} ("${unchanged.subject.slice(0, 120)}"), as when the session began, and the worktree has `
2609
- + 'no new changes. Work already there may belong to another task or branch. If this task was really finished before '
2610
- + 'this session, name the commit or file that shows it and the part of the task\'s instructions it meets. Otherwise do the task now.',
2745
+ content: hostCheck.note,
2611
2746
  turn: requestUsage?.getTurn?.(),
2612
2747
  timestamp: new Date(),
2613
2748
  });
2614
2749
  continue;
2615
2750
  }
2616
- this._turnToolBatches = 0;
2617
2751
  stopReason = 'complete';
2618
2752
  break;
2619
2753
  }
@@ -2671,24 +2805,34 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2671
2805
  toolCall.args = effectiveArgs;
2672
2806
  toolCall.status = 'complete';
2673
2807
  toolCall.result = content;
2674
- const guarded = applyRepeatGuard(toolBlock.name, toolBlock.input, content, managedCommand);
2675
- await retainToolResult(toolCall, content, guarded, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
2808
+ // Per call, not per response: a fix and the same command may share one. A read-only command changes nothing.
2809
+ const tool = this.config.tools.find(candidate => candidate.definition.name === toolBlock.name);
2810
+ if (isShellToolName(toolBlock.name) ? tool?.readOnlyCall?.(toolBlock.input) !== true
2811
+ : tool !== undefined && resolveToolEffect(tool) === 'write')
2812
+ commandRepeatGuard.forget();
2813
+ const observed = applyRepeatGuard(toolBlock.name, toolBlock.input, content, managedCommand);
2814
+ await retainToolResult(toolCall, content, observed, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
2676
2815
  this.emit({ type: 'tool_end', tool: toolBlock.name, result: content, toolCallId: toolBlock.id });
2677
2816
  this.tracer.event({
2678
2817
  type: 'tool_end',
2679
2818
  timestamp: new Date(),
2680
2819
  data: this.toolTraceData(toolCall),
2681
2820
  });
2682
- return { toolCall, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision, rawContent: content, toolResult: { tool_use_id: toolBlock.id, content: guarded, is_error: false } };
2821
+ return { toolCall, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision, rawContent: content, toolResult: { tool_use_id: toolBlock.id, content: observed, is_error: false } };
2683
2822
  };
2684
- const recordToolError = async (toolBlock, toolCall, error, effectiveArgs, managedCommand, contentTruncated = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision) => {
2823
+ const recordToolError = async (toolBlock, toolCall, error, effectiveArgs, managedCommand, contentTruncated = false, verificationReceipt, verifierDecision, benchmarkComparisonDecision, timedOut = false) => {
2685
2824
  toolCall.completedAt = new Date();
2686
2825
  if (effectiveArgs !== undefined)
2687
2826
  toolCall.args = effectiveArgs;
2688
2827
  toolCall.status = 'error';
2689
2828
  toolCall.error = error;
2690
- const guarded = applyRepeatGuard(toolBlock.name, toolBlock.input, `Error: ${error}`);
2691
- await retainToolResult(toolCall, `Error: ${error}`, guarded, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
2829
+ const raw = `Error: ${error}`;
2830
+ const guarded = applyRepeatGuard(toolBlock.name, toolBlock.input, raw);
2831
+ const repeatNote = isCommandCall(toolBlock.input)
2832
+ && !/^(?:Refused:|Skipped|finish_task|not_executed)/.test(error)
2833
+ ? commandRepeatGuard.observe(toolBlock.name, toolBlock.input, raw, timedOut || commandTimedOut(raw, managedCommand)) : raw;
2834
+ const observed = repeatNote === raw ? guarded : `${guarded}${repeatNote.slice(raw.length)}`;
2835
+ await retainToolResult(toolCall, raw, observed, managedCommand, contentTruncated, verificationReceipt, verifierDecision, benchmarkComparisonDecision);
2692
2836
  this.emit({ type: 'tool_error', tool: toolBlock.name, error, toolCallId: toolBlock.id });
2693
2837
  this.tracer.event({
2694
2838
  type: 'tool_error',
@@ -2702,10 +2846,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2702
2846
  verificationReceipt,
2703
2847
  verifierDecision,
2704
2848
  benchmarkComparisonDecision,
2705
- rawContent: `Error: ${error}`,
2849
+ rawContent: raw,
2706
2850
  toolResult: {
2707
2851
  tool_use_id: toolBlock.id,
2708
- content: guarded,
2852
+ content: observed,
2709
2853
  is_error: true,
2710
2854
  },
2711
2855
  };
@@ -2741,13 +2885,17 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2741
2885
  this.emit({ type: 'tool_start', tool: toolBlock.name, args: toolBlock.input, toolCallId: toolBlock.id });
2742
2886
  if (skipReason)
2743
2887
  return recordToolError(toolBlock, toolCall, skipReason);
2888
+ const commandRefusal = isCommandCall(toolBlock.input)
2889
+ ? commandRepeatGuard.refuse(toolBlock.name, toolBlock.input) : null;
2890
+ if (commandRefusal)
2891
+ return recordToolError(toolBlock, toolCall, commandRefusal);
2744
2892
  if (exclusiveTransitionId !== null
2745
2893
  && toolBlock.id !== exclusiveTransitionId) {
2746
2894
  return recordToolError(toolBlock, toolCall, 'Skipped because plan_mode is an exclusive safety transition; retry after the plan agent is active.');
2747
2895
  }
2748
2896
  const tool = this.config.tools.find(tool => tool.definition.name === toolBlock.name);
2749
2897
  if (tool?.finalResponse && toolUseBlocks.length !== 1) {
2750
- return recordToolError(toolBlock, toolCall, 'finish_task must be the only tool call; observe other results before completing the task.');
2898
+ return recordToolError(toolBlock, toolCall, `${toolBlock.name} must be the only tool call; observe other results before completing the task.`);
2751
2899
  }
2752
2900
  // Selector intent does not prove visibility: the encoder may cap or
2753
2901
  // compress the result. Acknowledge only when the request holds the
@@ -2802,6 +2950,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2802
2950
  discoveredTools: this.discoveredTools,
2803
2951
  backgroundWorkers: this.backgroundWorkers,
2804
2952
  leadBrief: { task: this.turnInstruction, environment: this.runtimeContext ?? undefined },
2953
+ doneWhen: this.taskDoneWhen(run),
2805
2954
  availableTools: this.config.tools,
2806
2955
  subprocessEnv: this.copySubprocessEnv(),
2807
2956
  commandPolicy: this.commandPolicy,
@@ -2837,6 +2986,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2837
2986
  discoveredTools: this.discoveredTools,
2838
2987
  backgroundWorkers: this.backgroundWorkers,
2839
2988
  leadBrief: { task: this.turnInstruction, environment: this.runtimeContext ?? undefined },
2989
+ doneWhen: this.taskDoneWhen(run),
2840
2990
  availableTools: this.config.tools,
2841
2991
  subprocessEnv: this.copySubprocessEnv(),
2842
2992
  commandPolicy: this.commandPolicy,
@@ -2855,7 +3005,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2855
3005
  }
2856
3006
  outputObserver.close();
2857
3007
  if (result.isError) {
2858
- return recordToolError(toolBlock, toolCall, result.content, result.effectiveArgs, result.managedCommand, result.contentTruncated, result.verificationReceipt, result.verifierDecision, result.benchmarkComparisonDecision);
3008
+ return recordToolError(toolBlock, toolCall, result.content, result.effectiveArgs, result.managedCommand, result.contentTruncated, result.verificationReceipt, result.verifierDecision, result.benchmarkComparisonDecision, result.timedOut);
2859
3009
  }
2860
3010
  return recordToolSuccess(toolBlock, toolCall, result.content, result.effectiveArgs, result.managedCommand, result.contentTruncated, result.verificationReceipt, result.verifierDecision, result.benchmarkComparisonDecision);
2861
3011
  }
@@ -2879,21 +3029,22 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2879
3029
  const command = typeof result.toolCall.args?.command === 'string' ? result.toolCall.args.command : undefined;
2880
3030
  if (command === undefined)
2881
3031
  return true;
2882
- if (this._turnCommandsRun.has(command))
3032
+ if (turnCommandsRun.has(command))
2883
3033
  return false;
2884
- this._turnCommandsRun.add(command);
3034
+ turnCommandsRun.add(command);
2885
3035
  return true;
2886
3036
  });
2887
- this._turnToolChangedState = changedState;
2888
- this._turnUsedTools = true;
3037
+ turnToolChangedState = changedState;
3038
+ run.usedTools = true;
2889
3039
  // The run went on working after a nudge: the answer it gave before is a draft its next answer replaces.
2890
3040
  if (questionedByNudge) {
2891
3041
  answerBeforeHostChecks = undefined;
2892
3042
  questionedByNudge = false;
2893
3043
  }
2894
3044
  if (changedState) {
2895
- this._consecutiveAutoContinues = 0;
2896
- this._turnCheckAsked = false;
3045
+ consecutiveAutoContinues = 0;
3046
+ run.endProtocol.inARow = 0;
3047
+ turnCheckAsked = false;
2897
3048
  }
2898
3049
  else {
2899
3050
  // A read-only run makes progress by reading: a DeepSeek review spent the whole budget on announcements between
@@ -2903,21 +3054,43 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2903
3054
  if (result.toolCall.status !== 'complete' || result.toolResult.is_error)
2904
3055
  continue;
2905
3056
  const key = `${result.toolCall.name}:${JSON.stringify(result.toolCall.args ?? {})}`;
2906
- if (this._turnReadsSeen.has(key))
3057
+ if (turnReadsSeen.has(key))
2907
3058
  continue;
2908
- this._turnReadsSeen.add(key);
3059
+ turnReadsSeen.add(key);
2909
3060
  readSomethingNew = true;
2910
3061
  }
2911
- if (readSomethingNew)
2912
- this._consecutiveAutoContinues = 0;
3062
+ if (readSomethingNew) {
3063
+ consecutiveAutoContinues = 0;
3064
+ run.endProtocol.inARow = 0;
3065
+ }
2913
3066
  }
2914
3067
  if (changedState)
2915
- this._turnToolBatches += 1;
3068
+ turnToolBatches += 1;
2916
3069
  // Add assistant message with tool use
2917
3070
  const textContent = this.remoteResourceSession
2918
3071
  ? combined.filter(result => result.toolCall.name === 'remote_resource' && result.toolCall.status === 'complete')
2919
3072
  .flatMap(result => remoteDeletionReport(result.toolResult.content) ?? []).join('\n')
2920
3073
  : response.content.filter(this.isTextBlock).map(b => b.text).join('\n');
3074
+ // A cancelled run ends as cancelled (below), whatever its last calls learned.
3075
+ const noProgress = signal?.aborted ? 'continue' : applyNoProgressGuard(combined.map(result => {
3076
+ const tool = this.config.tools.find(candidate => candidate.definition.name === result.toolCall.name);
3077
+ return { name: result.toolCall.name, input: result.toolCall.args, content: result.toolResult.content,
3078
+ isError: result.toolResult.is_error, effect: tool ? resolveToolEffect(tool) : 'external',
3079
+ managedCommand: result.managedCommand };
3080
+ }), { text: textContent.trim().length > 0 });
3081
+ if (noProgress === 'nudge') {
3082
+ const note = { id: `no_progress_${randomUUID()}`, role: 'user', content: NO_PROGRESS_NUDGE,
3083
+ timestamp: new Date(), metadata: { synthetic: true, hostContext: true } };
3084
+ messages.push(note);
3085
+ turnMessages.push(note);
3086
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
3087
+ }
3088
+ else if (noProgress === 'stalled') {
3089
+ stopReason = 'stalled';
3090
+ finalContent = noProgressStalledMessage(applyNoProgressGuard.windowSize());
3091
+ this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
3092
+ break;
3093
+ }
2921
3094
  toolUseMessage.content = textContent || '[Using tools...]';
2922
3095
  toolUseMessage.turn = requestUsage?.getTurn?.();
2923
3096
  this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
@@ -2945,7 +3118,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2945
3118
  this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
2946
3119
  }
2947
3120
  const recoveryAction = recovery(combined.map(result => ({ name: result.toolCall.name,
2948
- content: result.toolResult.content, isError: result.toolResult.is_error, managedCommand: result.managedCommand })));
3121
+ content: result.toolResult.content, isError: result.toolResult.is_error, managedCommand: result.managedCommand }))
3122
+ .filter(result => !/^Error: Refused:/.test(result.content)));
2949
3123
  if (recoveryAction === 'stop')
2950
3124
  throw new AgentError('Automatic recovery budget exhausted after repeated tool failures. Inspect the retained results and current capabilities before retrying.', RECOVERY_EXHAUSTED_CODE);
2951
3125
  if (recoveryAction === 'recover') {
@@ -2964,11 +3138,32 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2964
3138
  const answer = tool?.finalResponse?.(call.result ?? '');
2965
3139
  if (answer?.trim()) {
2966
3140
  finalContent = answer;
3141
+ finalOutcome = tool?.finalOutcome?.(call.result ?? '');
2967
3142
  finalReasoning = response.reasoning;
2968
3143
  finalReasoningModel = request.model;
2969
3144
  await this.emitStreamText(answer, signal);
2970
3145
  if (signal?.aborted)
2971
3146
  throw new AgentError('Cancelled', 'CANCELLED');
3147
+ if (finalOutcome === 'done' && !this.remoteResourceSession
3148
+ && this._autoContinue && this.config.completionCheck === true) {
3149
+ const check = this.nextHostCompletionCheck(run, answer);
3150
+ if (check) {
3151
+ keepCheckedAnswer(answer);
3152
+ this.emit({ type: 'auto_continue', reason: check.reason });
3153
+ messages.push({
3154
+ id: `assistant_${Date.now()}`, role: 'assistant', turn: requestUsage?.getTurn?.(),
3155
+ content: answer, timestamp: new Date(),
3156
+ metadata: { ...(response.reasoning ? { reasoningContent: response.reasoning, reasoningModel: this.turnModel(run) } : {}) },
3157
+ });
3158
+ messages.push({
3159
+ id: `${check.reason.replace(' ', '_')}_${Date.now()}`, role: 'user', content: check.note,
3160
+ turn: requestUsage?.getTurn?.(), timestamp: new Date(),
3161
+ });
3162
+ finalContent = '';
3163
+ finalOutcome = undefined;
3164
+ continue;
3165
+ }
3166
+ }
2972
3167
  stopReason = 'complete';
2973
3168
  break;
2974
3169
  }
@@ -2990,7 +3185,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2990
3185
  return result ? !result.content.startsWith('Error:') : false;
2991
3186
  });
2992
3187
  if (resolvedTurn)
2993
- this._turnToolBatches = 0;
3188
+ turnToolBatches = 0;
2994
3189
  // A busy user message belongs after the completed tool-use/result pair
2995
3190
  // and before the next inference. Keep terminal tools and exhausted turns
2996
3191
  // on the normal next-turn path because no model request remains here.
@@ -2999,6 +3194,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2999
3194
  ? [{ ...result.managedCommand, toolCallId: result.toolCall.id }] : []);
3000
3195
  const consumedSteering = [];
3001
3196
  let waited;
3197
+ const waitStartedAt = Date.now();
3002
3198
  try {
3003
3199
  waited = observations.length === combined.length
3004
3200
  ? await awaitManagedCommandProgress(observations, { signal, deadlineAt: Date.now() + 60_000,
@@ -3019,8 +3215,14 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3019
3215
  throw error;
3020
3216
  }
3021
3217
  if (waited.waited) {
3218
+ // The model reads a job's quiet here: its own read_command returned at once, and the host did the waiting.
3219
+ const waitedMs = Date.now() - waitStartedAt;
3220
+ const noted = waited.observations.map(item => {
3221
+ const note = quietJobNote(item.result, this.commandPolicy?.profile, waitedMs);
3222
+ return note ? { ...item, note } : item;
3223
+ });
3022
3224
  const observation = { id: `command_observation_${randomUUID()}`, role: 'user',
3023
- content: formatManagedCommandObservations(waited.observations), timestamp: new Date(),
3225
+ content: formatManagedCommandObservations(noted), timestamp: new Date(),
3024
3226
  metadata: { synthetic: true, hostContext: true, managedCommandObservation: true } };
3025
3227
  for (const [index, item] of waited.observations.entries()) {
3026
3228
  this.toolResponseStore.put(`${observation.id}_${index}`, 'read_command', JSON.stringify(item.result), item.result.has_more || Boolean(item.result.output_truncated), {
@@ -3036,6 +3238,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3036
3238
  if (steering.length > 0) {
3037
3239
  messages.push(...steering);
3038
3240
  turnMessages.push(...steering);
3241
+ applyNoProgressGuard.reset();
3039
3242
  this.emit({ type: 'history_checkpoint', messages: [...turnMessages] });
3040
3243
  if (signal?.aborted)
3041
3244
  throw new AgentError('Cancelled', 'CANCELLED');
@@ -3044,12 +3247,16 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3044
3247
  throw new AgentError('Cancelled', 'CANCELLED');
3045
3248
  }
3046
3249
  }
3250
+ const compactWindow = getContextWindowSize(this.turnModel(run), run.prepared ? this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.context_window ?? null
3251
+ : this.midTurnCompactWindow !== undefined ? this.midTurnCompactWindow : usage.contextWindow);
3047
3252
  if (this.onMidTurnCompact && shouldCompactMidTurn({
3048
3253
  usedTokens: contextTokens > 0 ? contextTokens : estimateConversationTokens(messages),
3049
- windowTokens: getContextWindowSize(this.turnModel(run), run.prepared ? this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.context_window ?? null
3050
- : this.midTurnCompactWindow !== undefined ? this.midTurnCompactWindow : usage.contextWindow),
3254
+ windowTokens: compactWindow,
3051
3255
  thresholdPercent: this.midTurnCompactThresholdPercent ?? 90,
3052
3256
  tokenBudget: this.midTurnCompactTokenBudget,
3257
+ // One prompt can be the whole of an unattended run, so its early compaction is here, between tool batches.
3258
+ earlyTokens: this.config.unattended || this.config.noHumanAvailable
3259
+ ? unattendedCompactTokens(compactWindow, executionSettings.unattendedCompactPercent) : undefined,
3053
3260
  reservedOutputTokens: clampCompletionTokens(this.turnModel(run), this.turnMaxTokens(run)
3054
3261
  ?? this.turnBackend(run).getModelCapabilities?.(this.turnModel(run))?.max_output_tokens),
3055
3262
  messagesSinceLastCompaction: midTurnMessagesSinceCompaction,
@@ -3066,6 +3273,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3066
3273
  turnMessages.length = 0;
3067
3274
  turnMessages.push(...compacted);
3068
3275
  applyRepeatGuard.forget();
3276
+ applyNoProgressGuard.reset();
3277
+ commandRepeatGuard.forget();
3069
3278
  midTurnLastFreedTokens = before - after;
3070
3279
  midTurnMessagesSinceCompaction = 0;
3071
3280
  // A request that keeps its scope in a file loses it to the summary; have the model read it again.
@@ -3143,6 +3352,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3143
3352
  toolCalls: allToolCalls,
3144
3353
  usage: totalUsage || undefined,
3145
3354
  stopReason,
3355
+ ...(finalOutcome ? { outcome: finalOutcome } : {}),
3146
3356
  ...(finalReasoning ? { reasoning: finalReasoning, reasoningModel: finalReasoningModel } : {}),
3147
3357
  responseItems: finalResponseItems,
3148
3358
  ...(finalResponseItems ? { nativeModel: finalResponseModel } : {}),
@@ -3194,7 +3404,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3194
3404
  throw error;
3195
3405
  }
3196
3406
  }
3197
- async executeHarnessToolCallWithCheckpoint(name, args, options, context) {
3407
+ async executeHarnessToolCallWithCheckpoint(name, args, options, context, run = this.activeRun) {
3198
3408
  if (this.toolCheckpointFailure)
3199
3409
  throw this.toolCheckpointFailure;
3200
3410
  options.onActivity?.();
@@ -3258,6 +3468,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3258
3468
  discoveredTools: this.discoveredTools,
3259
3469
  backgroundWorkers: this.backgroundWorkers,
3260
3470
  leadBrief: { task: this.turnInstruction, environment: this.runtimeContext ?? undefined },
3471
+ doneWhen: this.taskDoneWhen(run),
3261
3472
  availableTools: this.config.tools,
3262
3473
  subprocessEnv: this.copySubprocessEnv(),
3263
3474
  commandPolicy: this.commandPolicy,
@@ -3331,7 +3542,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3331
3542
  const known = new Set(this.getEvidenceSnapshot().records.map(record => record.id));
3332
3543
  for (const message of messages) {
3333
3544
  if (message.role !== 'user' || message.metadata?.synthetic || message.metadata?.toolResult
3334
- || message.metadata?.compactionSummary || message.metadata?.managedCommandObservation)
3545
+ || message.metadata?.compactionSummary || message.metadata?.managedCommandObservation
3546
+ || message.metadata?.compactionSourceId)
3335
3547
  continue;
3336
3548
  const id = `instruction_${message.id}`;
3337
3549
  if (known.has(id))
@@ -3504,7 +3716,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3504
3716
  signal: signal ? AbortSignal.any([signal, attemptController.signal]) : attemptController.signal,
3505
3717
  onActivity: touchActivity,
3506
3718
  onUsage,
3507
- }, checkpointContext);
3719
+ }, checkpointContext, run);
3508
3720
  return result.output;
3509
3721
  },
3510
3722
  };
@@ -3706,7 +3918,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3706
3918
  }
3707
3919
  rateLimitedAttempts = kind === 'rate_limit' ? rateLimitedAttempts + 1 : 0;
3708
3920
  rateLimitedSince = kind === 'rate_limit' ? rateLimitedSince ?? Date.now() : undefined;
3709
- if (this.config.noHumanAvailable) {
3921
+ if (this.config.unattended || this.config.noHumanAvailable) {
3710
3922
  // Nobody can send the message that tries again, so an overload is waited out for rateLimitWaitMs, not ten
3711
3923
  // tries (forge3d and scan-lab, 2026-11-17: Morph overloaded for about twenty minutes ended every run).
3712
3924
  const waitedMs = rateLimitedSince === undefined ? 0 : Date.now() - rateLimitedSince;
@@ -3730,6 +3942,16 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3730
3942
  // Keep the exact pending inference alive. Never resubmit the user turn
3731
3943
  // or revisit already checkpointed tool results to recover an endpoint.
3732
3944
  let delay = Math.max(apiRetryDelayMs(attempt, this.config.apiRetry), retryAfterDelayMs(error));
3945
+ if ((this.config.unattended || this.config.noHumanAvailable) && kind === 'rate_limit' && rateLimitedSince !== undefined) {
3946
+ const remainingBudget = this.config.apiRetry.rateLimitWaitMs - (Date.now() - rateLimitedSince);
3947
+ const retryAfter = retryAfterDelayMs(error);
3948
+ if (retryAfter > remainingBudget) {
3949
+ throw new AgentError(`${failureReason.replace(/\.?\s*$/, '.')} The provider asked to wait `
3950
+ + `${formatDuration(retryAfter)}, longer than the ${formatDuration(Math.max(0, remainingBudget))} left of this run's `
3951
+ + `rate-limit wait, so ZTC stopped waiting.`, RATE_LIMITED_CODE);
3952
+ }
3953
+ delay = Math.min(delay, Math.max(1, remainingBudget));
3954
+ }
3733
3955
  if (recovering) {
3734
3956
  delay = Math.max(1, delay);
3735
3957
  if (recoveryWindowMs !== null)
@@ -3939,6 +4161,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3939
4161
  return { retryable: false, reason: authenticationFailure(this.keyProvider, message) };
3940
4162
  }
3941
4163
  if (statusCode === 403 || errorType === 'PERMISSION_DENIED') {
4164
+ const modelAccessWords = cleanRouterText(admissionMessage || errorMessage);
4165
+ if ((errorCode === 'model_access_denied' || admissionCode === 'model_access_denied') && modelAccessWords) {
4166
+ return { retryable: false, reason: modelAccessWords };
4167
+ }
3942
4168
  return { retryable: false, reason: admissionMessage || 'Permission denied' };
3943
4169
  }
3944
4170
  // Router billing admission (402 billing_required) is the first thing an