@zergai/ztc 0.19.0-beta.1 → 0.20.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 (196) hide show
  1. package/README.md +222 -6
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +2 -2
  7. package/dist/agent/agent.d.ts +17 -0
  8. package/dist/agent/agent.js +77 -4
  9. package/dist/agent/backends/index.js +5 -3
  10. package/dist/agent/backends/zrouter_stream.js +8 -4
  11. package/dist/agent/commands/goal.d.ts +2 -0
  12. package/dist/agent/commands/goal.js +7 -2
  13. package/dist/agent/factory.d.ts +2 -0
  14. package/dist/agent/factory.js +1 -0
  15. package/dist/agent/request_encoder.d.ts +2 -1
  16. package/dist/agent/request_encoder.js +4 -3
  17. package/dist/agent/runtime/policy.d.ts +1 -0
  18. package/dist/agent/runtime/policy.js +23 -3
  19. package/dist/agent/runtime/tool_runtime.js +13 -12
  20. package/dist/agent/subagent.js +2 -1
  21. package/dist/agent/tools/ask_user.d.ts +1 -1
  22. package/dist/agent/tools/ask_user.js +15 -8
  23. package/dist/agent/tools/pane.d.ts +6 -0
  24. package/dist/agent/tools/pane.js +18 -4
  25. package/dist/agent/tools/search.js +1 -1
  26. package/dist/agent/tools/sim_domain_tools.d.ts +4 -0
  27. package/dist/agent/tools/sim_domain_tools.js +28 -2
  28. package/dist/agent/tools/types.d.ts +3 -0
  29. package/dist/app/correlated_turn.d.ts +14 -0
  30. package/dist/app/correlated_turn.js +78 -0
  31. package/dist/app/prompt_turn.d.ts +2 -1
  32. package/dist/app/prompt_turn.js +15 -2
  33. package/dist/app/session_manager.d.ts +17 -11
  34. package/dist/app/session_manager.js +74 -30
  35. package/dist/app/tool_callbacks.d.ts +1 -1
  36. package/dist/app/workspace_layout_controller.d.ts +21 -2
  37. package/dist/app/workspace_layout_controller.js +61 -10
  38. package/dist/app/workspace_monitor.js +67 -7
  39. package/dist/app/workspace_presets.d.ts +1 -0
  40. package/dist/app/workspace_presets.js +2 -2
  41. package/dist/cli.js +6 -2
  42. package/dist/cli_args.js +1 -0
  43. package/dist/cli_main.js +48 -2
  44. package/dist/cli_ratatui.d.ts +56 -8
  45. package/dist/cli_ratatui.js +689 -109
  46. package/dist/config/permissions.js +1 -1
  47. package/dist/config/router_required.d.ts +11 -0
  48. package/dist/config/router_required.js +23 -0
  49. package/dist/config/types.d.ts +5 -0
  50. package/dist/config.d.ts +3 -1
  51. package/dist/config.js +66 -49
  52. package/dist/desktop/daily/broker.d.ts +26 -0
  53. package/dist/desktop/daily/broker.js +140 -0
  54. package/dist/desktop/daily/codex_config.d.ts +2 -0
  55. package/dist/desktop/daily/codex_config.js +119 -0
  56. package/dist/desktop/daily/codex_exec_adapter.d.ts +42 -0
  57. package/dist/desktop/daily/codex_exec_adapter.js +251 -0
  58. package/dist/desktop/daily/control_client.d.ts +4 -0
  59. package/dist/desktop/daily/control_client.js +214 -0
  60. package/dist/desktop/daily/control_credentials.d.ts +15 -0
  61. package/dist/desktop/daily/control_credentials.js +85 -0
  62. package/dist/desktop/daily/control_hello.d.ts +10 -0
  63. package/dist/desktop/daily/control_hello.js +6 -0
  64. package/dist/desktop/daily/control_protocol.d.ts +39 -0
  65. package/dist/desktop/daily/control_protocol.js +4 -0
  66. package/dist/desktop/daily/control_schema.d.ts +9 -0
  67. package/dist/desktop/daily/control_schema.js +25 -0
  68. package/dist/desktop/daily/control_server.d.ts +44 -0
  69. package/dist/desktop/daily/control_server.js +286 -0
  70. package/dist/desktop/daily/daily_store.d.ts +71 -0
  71. package/dist/desktop/daily/daily_store.js +290 -0
  72. package/dist/desktop/daily/delegated_ztc_contract.d.ts +37 -0
  73. package/dist/desktop/daily/delegated_ztc_contract.js +90 -0
  74. package/dist/desktop/daily/desktop_wiring.d.ts +112 -0
  75. package/dist/desktop/daily/desktop_wiring.js +1048 -0
  76. package/dist/desktop/daily/enrollment.d.ts +74 -0
  77. package/dist/desktop/daily/enrollment.js +77 -0
  78. package/dist/desktop/daily/file_facts.d.ts +2 -0
  79. package/dist/desktop/daily/file_facts.js +41 -0
  80. package/dist/desktop/daily/lease.d.ts +57 -0
  81. package/dist/desktop/daily/lease.js +332 -0
  82. package/dist/desktop/daily/legacy_codex_homes.d.ts +1 -0
  83. package/dist/desktop/daily/legacy_codex_homes.js +26 -0
  84. package/dist/desktop/daily/native_pane_launcher.d.ts +31 -0
  85. package/dist/desktop/daily/native_pane_launcher.js +226 -0
  86. package/dist/desktop/daily/native_records.d.ts +13 -0
  87. package/dist/desktop/daily/native_records.js +81 -0
  88. package/dist/desktop/daily/native_status.d.ts +4 -0
  89. package/dist/desktop/daily/native_status.js +28 -0
  90. package/dist/desktop/daily/native_tool.d.ts +134 -0
  91. package/dist/desktop/daily/native_tool.js +91 -0
  92. package/dist/desktop/daily/owner_files.d.ts +3 -0
  93. package/dist/desktop/daily/owner_files.js +88 -0
  94. package/dist/desktop/daily/owner_seals.d.ts +9 -0
  95. package/dist/desktop/daily/owner_seals.js +56 -0
  96. package/dist/desktop/daily/process_identity.d.ts +13 -0
  97. package/dist/desktop/daily/process_identity.js +137 -0
  98. package/dist/desktop/daily/profile_bootstrap.d.ts +60 -0
  99. package/dist/desktop/daily/profile_bootstrap.js +194 -0
  100. package/dist/desktop/daily/raw_receipts.d.ts +1 -0
  101. package/dist/desktop/daily/raw_receipts.js +18 -0
  102. package/dist/desktop/daily/recipes.d.ts +36 -0
  103. package/dist/desktop/daily/recipes.js +177 -0
  104. package/dist/desktop/daily/router_state.d.ts +33 -0
  105. package/dist/desktop/daily/router_state.js +39 -0
  106. package/dist/desktop/daily/schema_registry.d.ts +19 -0
  107. package/dist/desktop/daily/schema_registry.js +71 -0
  108. package/dist/desktop/daily/source_baseline.d.ts +13 -0
  109. package/dist/desktop/daily/source_baseline.js +44 -0
  110. package/dist/desktop/daily/status_restore.d.ts +9 -0
  111. package/dist/desktop/daily/status_restore.js +114 -0
  112. package/dist/desktop/daily/summary.d.ts +59 -0
  113. package/dist/desktop/daily/summary.js +75 -0
  114. package/dist/desktop/daily/worker_provenance.d.ts +2 -0
  115. package/dist/desktop/daily/worker_provenance.js +18 -0
  116. package/dist/desktop/daily/worker_stop.d.ts +2 -0
  117. package/dist/desktop/daily/worker_stop.js +26 -0
  118. package/dist/desktop/daily/ztc_headless_adapter.d.ts +40 -0
  119. package/dist/desktop/daily/ztc_headless_adapter.js +194 -0
  120. package/dist/domain.d.ts +1 -1
  121. package/dist/domain.js +1 -1
  122. package/dist/events.d.ts +23 -1
  123. package/dist/headless.d.ts +9 -0
  124. package/dist/headless.js +161 -26
  125. package/dist/headless_approval.d.ts +29 -0
  126. package/dist/headless_approval.js +69 -0
  127. package/dist/headless_cli.js +2 -0
  128. package/dist/headless_cli_args.d.ts +4 -0
  129. package/dist/headless_cli_args.js +5 -0
  130. package/dist/library.d.ts +20 -0
  131. package/dist/library.js +66 -12
  132. package/dist/mcp/client.d.ts +16 -1
  133. package/dist/mcp/client.js +11 -5
  134. package/dist/mcp/registry.d.ts +3 -1
  135. package/dist/mcp/registry.js +10 -1
  136. package/dist/panes/pane_registry.js +14 -3
  137. package/dist/panes/types.d.ts +7 -1
  138. package/dist/panes/ztc_launch.d.ts +5 -0
  139. package/dist/panes/ztc_launch.js +30 -14
  140. package/dist/session.d.ts +6 -3
  141. package/dist/session.js +21 -2
  142. package/dist/simulation/domain_types.d.ts +2 -0
  143. package/dist/simulation/domains/loader.d.ts +7 -1
  144. package/dist/simulation/domains/loader.js +33 -1
  145. package/dist/simulation/living/context.d.ts +19 -19
  146. package/dist/simulation/living/definition.d.ts +2 -2
  147. package/dist/simulation/living/frame.d.ts +1 -1
  148. package/dist/simulation/living/open-world.d.ts +3 -3
  149. package/dist/simulation/living/types.d.ts +24 -24
  150. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  151. package/dist/skills/bundled/init-context/SKILL.md +16 -0
  152. package/dist/skills/registry.js +7 -3
  153. package/dist/tools.d.ts +6 -0
  154. package/dist/tools.js +14 -0
  155. package/dist/types.d.ts +30 -0
  156. package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
  157. package/dist/ui/ratatui/mux_persistence.js +9 -2
  158. package/dist/ui/ratatui/pane_credential_broker.d.ts +8 -4
  159. package/dist/ui/ratatui/pane_credential_broker.js +26 -11
  160. package/dist/ui/ratatui/pane_relay.d.ts +2 -0
  161. package/dist/ui/ratatui/process.d.ts +6 -0
  162. package/dist/ui/ratatui/process.js +104 -6
  163. package/dist/ui/ratatui/protocol.d.ts +13 -0
  164. package/dist/ui/ratatui/protocol.js +1 -0
  165. package/dist/utils/compaction.js +6 -4
  166. package/dist/utils/subprocess_env.js +2 -0
  167. package/dist/web/browser_events.d.ts +10 -0
  168. package/dist/web/browser_events.js +9 -0
  169. package/dist/web/mirror_stream.d.ts +17 -5
  170. package/dist/web/mirror_stream.js +105 -13
  171. package/dist/web/pane_credentials.d.ts +6 -3
  172. package/dist/web/pane_credentials.js +20 -12
  173. package/dist/web/pane_registry.js +1 -0
  174. package/dist/workspace_agent.d.ts +2 -1
  175. package/dist/workspace_agent.js +7 -1
  176. package/dist/workspace_collision.d.ts +3 -0
  177. package/dist/workspace_collision.js +1 -1
  178. package/dist/workspace_layout.d.ts +3 -2
  179. package/dist/workspace_layout.js +8 -2
  180. package/dist/workspace_runtime.d.ts +7 -1
  181. package/dist/workspace_runtime.js +3 -3
  182. package/dist/zerg/manifest_builder_tools.js +35 -4
  183. package/dist/zerg/manifest_validator.js +55 -0
  184. package/dist/zlm-embed.mjs +261 -116
  185. package/node_modules/@zerg/model-contracts/README.md +19 -0
  186. package/node_modules/@zerg/model-contracts/index.js +19 -1
  187. package/node_modules/@ztc/sim-graph/dist/index.d.ts +1 -0
  188. package/node_modules/@ztc/sim-graph/dist/index.js +1 -0
  189. package/node_modules/@ztc/sim-graph/dist/sim_graph.d.ts +351 -0
  190. package/node_modules/@ztc/sim-graph/dist/sim_graph.js +795 -0
  191. package/node_modules/@ztc/sim-graph/package.json +37 -0
  192. package/node_modules/@ztc/sim-graph/src/index.ts +1 -0
  193. package/node_modules/@ztc/sim-graph/src/sim_graph.ts +1305 -0
  194. package/package.json +25 -24
  195. package/packages/model-contracts/README.md +19 -0
  196. package/packages/model-contracts/index.js +19 -1
package/README.md CHANGED
@@ -204,9 +204,9 @@ curl -fsSL https://zergai.com/install/ztc.sh | sh -s -- --preview
204
204
 
205
205
  The app carries its own Node and matching ZTC agent, so it starts from the
206
206
  icon without a global Node or ZTC install, and it uses the same accounts,
207
- configuration and saved sessions as the CLI. Its title bar names the project
208
- and branch, and holds the model (click it to choose another), the queue, Stop
209
- and Updates. Releases are signed, notarized and published in
207
+ configuration and saved sessions as the CLI. Its title bar names the project and branch, then
208
+ the delegated Router's state when native panes are up, and holds the model (click it to choose
209
+ another), the queue, Stop and Updates. Releases are signed, notarized and published in
210
210
  [`Epoch-ML/ztc-releases`](https://github.com/Epoch-ML/ztc-releases).
211
211
 
212
212
  From a terminal you can also open the desktop surface explicitly:
@@ -246,6 +246,70 @@ update installs, the next launch shows what's new in it. See
246
246
  [desktop release details](packages/zterm/RELEASES.md) for the trust, packaging
247
247
  and publication contract.
248
248
 
249
+ #### Native tool panes
250
+
251
+ In `ztc --desktop`, open the new-pane menu (Ctrl+Cmd+N at the focused pane, or
252
+ the ▾ beside the tab strip's +, or a right-click on +) and choose **More…** (or
253
+ press M) to open **New pane** in Main. The picker offers Claude Code, Codex, and
254
+ ZTC interactive panes, plus delegated Codex and ZTC workers. The existing
255
+ **bash**, **ZTC**, and custom choices remain available. **Shell (native,
256
+ leased)** is a separate choice. If native support cannot start, the existing
257
+ desktop stays usable and omits these native choices. The + and Cmd+T still open
258
+ a ZTC tab at once, and Cmd+D and Shift+Cmd+D split a shell. A pane you choose
259
+ splits the pane you opened the menu at (a delegated worker opens in its own
260
+ tab), and Escape in the picker takes you back there. While a prompt is open in
261
+ Main, such as a delegated worker's approval, the picker waits for you to answer
262
+ it.
263
+
264
+ Native choices offer a new isolated Git worktree or the current worktree.
265
+ Interactive panes accept human terminal input. A native ZTC pane joins the
266
+ mirror as itself, with a credential of its own, and starts on the route your
267
+ profile saved for new panes, as any ZTC pane does. Delegated panes ask for an
268
+ absolute task-file path and display an untrusted feed. From an admitted native
269
+ lead pane, the desktop command can also open a delegated worker:
270
+
271
+ ```bash
272
+ ztc desktop open --tool codex --mode delegated --worktree new \
273
+ --task-file /absolute/path/task.txt --schema fixture-count-v1
274
+ ztc desktop list
275
+ ztc desktop summary <pane-id>
276
+ ```
277
+
278
+ The desktop supplies the lead's authority through its launch environment.
279
+ An unrelated shell cannot use these commands without that authority. The channel
280
+ has no terminal-input operation. Results currently use the registered
281
+ `fixture-count-v1` numeric schema; arbitrary child-supplied schemas are refused.
282
+
283
+ After the project and branch, the title bar shows the delegated Router:
284
+ **Delegated Router: signed out** (or expired, rejected, unavailable) until the
285
+ `desktop-delegated` profile's login is signed in, then its funding, such as
286
+ **ready** or **needs payment**. It describes that profile, not the model chip's
287
+ route, nor Claude or Codex subscriptions. Status shows structured enrolled-child
288
+ rows alongside ordinary ZTC workers. Use Up/Down and Enter (or a click) to drill
289
+ in. Unmodified Escape or Backspace collapses that drill-in and returns focus to
290
+ Status. Interactive zooms keep those keys in their terminal.
291
+
292
+ Use `/pane stop <pane-id>` or **Stop native pane** in the picker.
293
+ Stop validates process identity before signaling. SIGKILL requires human desktop
294
+ confirmation. Lease conflicts offer **Isolate** or a human-only risk override
295
+ labelled `exclusivity unverified`. Observed exit does not prove that every
296
+ possible writer has stopped; containment remains unverified.
297
+
298
+ Layouts restore native jobs inactive. Resume uses the exact saved identity,
299
+ recipe settings, and verified lease history. Missing sessions, changed worktrees,
300
+ changed policies, unsupported CLI versions, or writable quarantines refuse resume.
301
+ Interactive panes require a fresh launch rather than this read-only resume flow.
302
+ Restored rows do not verify old results or recover old authority.
303
+
304
+ Delegated ZTC uses Router-only authentication, a locked read-only profile,
305
+ a closed extension set, and a checked effective-policy hash. Human approval
306
+ requests appear only in desktop dialogs; an absent or timed-out broker denies
307
+ them. The picker can refresh the delegated login from the default login, or
308
+ sign it out locally. Neither action changes the default login.
309
+
310
+ See [workspace restore and acceptance checks](docs/workspace-resurrection.md)
311
+ for Status recovery, resume refusals, receipt handling, and verification limits.
312
+
249
313
  ### Voice & Media
250
314
  - **Voice dictation** — Whisper transcription on this computer (Ctrl+R): the
251
315
  native dictation binary, else local whisper (`whisper` or `whisper-cpp`, with
@@ -691,12 +755,96 @@ node dist/cli_main.js --headless --prompt "Fix the tests" \
691
755
  | `--headless` | Enable headless mode | — |
692
756
  | `--prompt <text>` | Single prompt to execute | — |
693
757
  | `--json` | JSON protocol for I/O | — |
694
- | `--max-iterations <n>` | Max agent iterations | 50 |
695
- | `--timeout <ms>` | Operation timeout | 300000 |
758
+ | `--max-iterations <n>` | Max agent iterations | Unlimited |
759
+ | `--timeout <ms>` | Operation timeout | 43200000 |
696
760
  | `--output <file>` | Save response to file | — |
697
761
  | `--timestamps` | Show timestamps in output | — |
698
762
  | `--quiet` / `-q` | Suppress build output | — |
699
763
  | `--session-id <id>` | Use or create a specific session ID | — |
764
+ | `--session-file <path>` | Load and save an explicit session file | — |
765
+ | `--approval-url <url>` | Remote approvals and question answers | `ZTC_APPROVAL_URL` |
766
+
767
+ ### Remote approvals and questions
768
+
769
+ Set `--approval-url` or `ZTC_APPROVAL_URL` to hand decisions to a remote service.
770
+ The flag takes precedence over the environment variable.
771
+ Use HTTPS; HTTP is allowed for `localhost`, `127.0.0.1`, and `[::1]` tests.
772
+ The URL cannot contain credentials, a query, or a fragment.
773
+ `ZTC_APPROVAL_TOKEN` adds `Authorization: Bearer <token>` to each request.
774
+ ZTC does not forward this token to tool subprocesses or follow HTTP redirects.
775
+
776
+ ZTC sends each hook approval and each question with `POST <url>` and `Content-Type: application/json`:
777
+
778
+ ```json
779
+ {
780
+ "kind": "approval",
781
+ "requestId": "unique-request-id",
782
+ "sessionId": "active-session-id",
783
+ "cwd": "/workspace",
784
+ "toolName": "write_file",
785
+ "args": { "path": "result.txt", "content": "ready" },
786
+ "capabilities": ["file_write"],
787
+ "reason": "Review this change"
788
+ }
789
+ ```
790
+
791
+ An approval uses `toolName`, `args`, `capabilities`, and an optional `reason`.
792
+ A first-run hook approval names the hook command in `toolName`.
793
+ A question uses `kind: "question"`, `question`, and `options` instead of the tool fields.
794
+ Each option contains a `label`, a `description`, and optional `recommended` and `preview` fields.
795
+ A multi-question `ask_user` call sends one request per question, in order.
796
+
797
+ Return HTTP 200 with one of these bodies to decide inline:
798
+
799
+ ```json
800
+ { "decision": "approved", "reason": "Reviewed" }
801
+ ```
802
+
803
+ ```json
804
+ { "decision": "denied", "reason": "Change is outside this run" }
805
+ ```
806
+
807
+ ```json
808
+ { "decision": "answered", "answer": "Use the staging target" }
809
+ ```
810
+
811
+ Return HTTP 202 while a decision is pending.
812
+ ZTC then polls `GET <url>/<URL-encoded requestId>` until HTTP 200 returns a decision.
813
+ GET may return 202 or 404 while pending.
814
+ Connection failures, HTTP 5xx, and 404 retry with backoff from 100 ms to 2 seconds.
815
+ POST retries retain the same request ID; the service must deduplicate these requests.
816
+ Other HTTP 4xx responses deny the request, using the JSON `reason` when present.
817
+ Malformed decisions deny the request.
818
+ Cancellation and the active operation timeout end the wait without approval.
819
+
820
+ JSON output includes `approval_requested` and `approval_resolved` for hook decisions.
821
+ Questions emit `ask_user` and `question_resolved`.
822
+ Their `data` contains the request fields; resolved events also contain the decision fields.
823
+ Use `requestId` to pair events, and `sessionId` to associate the run.
824
+ Only `approved` allows the requested hook or tool; questions require `answered` with a string `answer`.
825
+ Without a remote URL, headless mode keeps automatic approvals and selects each question's first option.
826
+
827
+ ### Environment-only sandboxes
828
+
829
+ These variables configure a compatible endpoint without a saved user configuration:
830
+
831
+ ```sh
832
+ export ZTC_PROVIDER=openai_compatible
833
+ export ZTC_MODEL=my-model
834
+ export ZTC_API_KEY=my-endpoint-key
835
+ export ZTC_OPENAI_COMPATIBLE_BASE_URL=https://model.example/v1
836
+ export ZTC_CONFIG_DIR=/workspace/config
837
+ export ZTC_SESSIONS_DIR=/workspace/sessions
838
+ node dist/cli_main.js --headless --json --cwd /workspace --session-file /workspace/run/session.json
839
+ ```
840
+
841
+ `ZTC_OPENAI_COMPATIBLE_BASE_URL` overrides saved compatible endpoint settings.
842
+ `ZTC_CONFIG_DIR` selects the configuration directory; `ZTC_SESSIONS_DIR` selects the default session store.
843
+ `--session-file` takes precedence for the active session's load and save operations.
844
+ When `ZTC_ROUTER_REQUIRED=1`, `ZERG_PROXY_URL` and `ZERG_AUTH_TOKEN` select the required router and its credential.
845
+ The required profile permits exactly one model, `openai/gpt-6.1-sol`, for the parent, subagents and compaction.
846
+ A host can pin a different single model with `ZTC_ROUTER_REQUIRED_MODEL=provider/model`; `ZTC_PROVIDER`, `ZTC_MODEL` and callers cannot move it.
847
+ The required router path does not use direct provider credentials or fallback routes.
700
848
 
701
849
  ---
702
850
 
@@ -1297,6 +1445,25 @@ tools:
1297
1445
 
1298
1446
  ### Example: handler bundle
1299
1447
 
1448
+ Domain tools can declare `effect: read`, `write`, or `external`, plus a `capabilities` list:
1449
+
1450
+ ```yaml
1451
+ tools:
1452
+ - name: publish_report
1453
+ handler: reports:publish
1454
+ description: Publish a report
1455
+ effect: external
1456
+ capabilities: [network]
1457
+ parameters:
1458
+ report: { type: string }
1459
+ required: [report]
1460
+ ```
1461
+
1462
+ The runtime passes these fields to capability approval checks and the tool effect observer.
1463
+ Capabilities use the `ToolCapability` values: `file_read`, `file_write`, `shell_exec`, `network`, `screen_capture`, `computer_control`, and `ml_inference`.
1464
+ Unknown effects and capabilities fail domain tool construction.
1465
+ If `effect` is absent, the runtime derives it from capabilities; both fields remain optional for existing domains.
1466
+
1300
1467
  A sibling `handlers.{mjs,js,cjs}` file is auto-imported when the domain loads.
1301
1468
 
1302
1469
  > **Extension matters.** Prefer `handlers.mjs` (always ESM) or `handlers.cjs`
@@ -1357,6 +1524,53 @@ tools into any agent session — not just sim/mux panes. The existing
1357
1524
 
1358
1525
  ### Library API
1359
1526
 
1527
+ The package root exports `createAgent` for hosts that run an agent in their own process.
1528
+ Use `ambientDiscovery: false` with an explicit backend, model, and tool list for isolated runs.
1529
+
1530
+ ```ts
1531
+ import { createAgent } from 'zerg-ztc';
1532
+ import { selectTools } from 'zerg-ztc/tools';
1533
+
1534
+ const agent = await createAgent({
1535
+ provider: 'openai_compatible',
1536
+ model: 'my-model',
1537
+ apiKey: 'my-endpoint-key',
1538
+ openaiCompatibleBaseUrl: 'https://model.example/v1',
1539
+ ambientDiscovery: false,
1540
+ cwd: '/workspace',
1541
+ tools: selectTools(['read_file', 'list_directory']),
1542
+ toolCheckpoint: async checkpoint => { await saveCheckpoint(checkpoint); },
1543
+ });
1544
+ try {
1545
+ for await (const event of agent.runTurn('Inspect the workspace')) {
1546
+ consumeEvent(event);
1547
+ }
1548
+ } finally {
1549
+ agent.raw.dispose();
1550
+ }
1551
+ ```
1552
+
1553
+ The host supplies `saveCheckpoint` and `consumeEvent` in this example.
1554
+
1555
+ | Option | Host contract |
1556
+ |--------|---------------|
1557
+ | `toolCheckpoint` | Awaited before tool execution and after the terminal result. Receives `sessionId`, `toolCallId`, `messages`, and phase `before_execute` or `terminal`. Reject to stop dispatch or continuation. |
1558
+ | `onMidTurnCompact` | Receives messages, token usage, optional context window, and cancellation signal. Return replacement messages or `null` to retain history. |
1559
+ | `remoteResourceSession` | Supplies the host-owned resource list, owner identity, optional transport, and journal directory. Activates guarded remote execution. |
1560
+ | `hooks` | Supplies a `HookDispatcher` for lifecycle and tool hooks. Use `approvalRequester` to resolve tool approval requests. |
1561
+ | `mcpServers` | Uses the same server configuration and discovery as the CLI. Each named server supports HTTP or stdio transport, `disabled`, and `required`. Required connection failures reject creation. |
1562
+
1563
+ The root also exports `ToolCheckpointHandler`, `ToolCheckpoint`, `MidTurnCompactContext`, `RemoteResourceSession`, `RemoteResourceTransport`, `MCPServerConfig`, and hook types.
1564
+ It exports `HookDispatcher` and `ToolCapability` for host construction.
1565
+ MCP connections use the process-wide registry; the first initialization stays active until `closeMcpServers()` runs.
1566
+ Explicit MCP servers work with `ambientDiscovery: false`, which disables automatic colony discovery.
1567
+ Existing host tools win name collisions with MCP tools.
1568
+
1569
+ `zerg-ztc/tools` exports `defaultTools()` and `selectTools(names)`.
1570
+ `defaultTools()` returns a fresh list of the same tool objects used by the CLI before optional mode and plugin additions.
1571
+ `selectTools` preserves caller order, accepts an empty list, and throws `Unknown tool: <name>` for an unknown name.
1572
+ It also exports the `Tool`, `ToolContext`, and `ToolEffectKind` types and the `ToolCapability` enum.
1573
+
1360
1574
  The `zerg-ztc/domain` entry point exposes the external-domain surface for
1361
1575
  hosts that want to register handlers programmatically (e.g. a Nuxt server
1362
1576
  that holds a DB connection pool and wants its handlers to share it):
@@ -1412,7 +1626,9 @@ credentials. Panes need zmux (plain `ztc`) or the desktop app.
1412
1626
  - Ctrl+B c offers Claude Code and Codex next to bash and ZTC when they are
1413
1627
  installed. In the desktop app, the tab strip's + opens a ZTC tab, as Cmd+T
1414
1628
  does. The ▾ beside it, or a right-click or Ctrl-click on +, opens New tab and
1415
- Split focused pane, each for ZTC, Claude Code, Codex and Shell.
1629
+ Split focused pane, each for ZTC, Claude Code, Codex and Shell, then More…,
1630
+ which opens ZTC's New pane chooser with native panes, delegated workers and
1631
+ your custom panes (see [Native tool panes](#native-tool-panes)).
1416
1632
  Ctrl+Cmd+A and Ctrl+Cmd+O split the focused pane with Claude Code and Codex
1417
1633
  (Ctrl+Cmd+Z with ZTC, Cmd+D with a shell; Shift splits down), and Ctrl+Cmd+N
1418
1634
  opens the menu at the focused pane.
Binary file
Binary file
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/zterm-darwin-arm64
3
- size: 33779680 bytes
4
- sha256: 32f57ab167ced380d2b07fb1875d85be10cd2964ccb32b32cb5544f36c276dce
3
+ size: 33812576 bytes
4
+ sha256: a27bc07e1c58e21e0f813d21f60bb7bfe0d8ab3e5d102b5f042c5b94fe8ac5dc
@@ -13,6 +13,7 @@ import { type DiagnosticEventKind, type DiagnosticJsonObject, type DiagnosticSna
13
13
  import { type ToolGroupsConfig } from './tools/tool_groups.js';
14
14
  import type { ToolDefinition } from '../types.js';
15
15
  import type { Tool } from './tools/types.js';
16
+ import type { AskUserQuestion } from './tools/ask_user.js';
16
17
  import { ToolResponseStore } from './tool_response_store.js';
17
18
  import { type EvidenceSnapshot } from './runtime/evidence.js';
18
19
  import { BackgroundWorkers } from './background_workers.js';
@@ -86,6 +87,14 @@ export interface AgentConfig {
86
87
  * actually runs, so genuine work is never cut short. Default: 3.
87
88
  */
88
89
  maxConsecutiveAutoContinues?: number;
90
+ /**
91
+ * Nobody can answer this run (a headless prompt with no attached driver,
92
+ * pane parent or remote answerer). A turn that ends by asking the user
93
+ * something or by listing unfinished, unverified steps is then continued
94
+ * with a decide-and-continue nudge instead of ending with the question
95
+ * unanswered. Shares the maxConsecutiveAutoContinues budget. Default: false.
96
+ */
97
+ noHumanAvailable?: boolean;
89
98
  /**
90
99
  * Local task sessions: append current execution facts and any explicitly
91
100
  * pinned goal to request.system. User messages are never automatically
@@ -154,6 +163,7 @@ export interface AgentConfig {
154
163
  /** Host-declared tool groups; visibility lasts for this Agent instance. */
155
164
  toolGroups?: ToolGroupsConfig;
156
165
  onMidTurnCompact?: (context: MidTurnCompactContext) => Promise<Message[] | null>;
166
+ questionRequester?: (questions: AskUserQuestion[], signal?: AbortSignal) => Promise<string[]>;
157
167
  midTurnCompactThresholdPercent?: number;
158
168
  midTurnCompactWindow?: number | null;
159
169
  midTurnCompactTokenBudget?: number;
@@ -207,6 +217,7 @@ export type EventHandler = (event: AgentEvent) => void;
207
217
  export declare class Agent {
208
218
  #private;
209
219
  private config;
220
+ private readonly questionRequester;
210
221
  private onMidTurnCompact?;
211
222
  private midTurnCompactThresholdPercent?;
212
223
  private midTurnCompactWindow?;
@@ -288,6 +299,7 @@ export declare class Agent {
288
299
  private _hasCustomSystemPrompt;
289
300
  private readonly _authenticationManagedByBackend;
290
301
  constructor(config?: AgentConfig);
302
+ private questionHandler;
291
303
  setAutoContinue(enabled: boolean): void;
292
304
  /** Override the agent's system prompt (e.g., for simulation persona injection). */
293
305
  setSystemPrompt(prompt: string): void;
@@ -304,6 +316,11 @@ export declare class Agent {
304
316
  * Check if the response content indicates incomplete work that should trigger auto-continue
305
317
  */
306
318
  private shouldContinue;
319
+ /**
320
+ * With nobody to answer, a turn may not end on a question to the user or on a
321
+ * list of steps the model says it has not done yet.
322
+ */
323
+ private needsAutonomousContinuation;
307
324
  hasApiKey(): boolean;
308
325
  setCwd(cwd: string): void;
309
326
  getCwd(): string;
@@ -109,6 +109,13 @@ const ROUTER_RATE_LIMIT_CODES = new Set(['rate_limit_exceeded', 'free_model_dail
109
109
  */
110
110
  const RATE_LIMITED_ATTEMPTS = 10;
111
111
  const DEFAULT_LLM_REQUEST_TIMEOUT_MS = 120_000;
112
+ /** Sent when a turn ends on a question or unfinished steps and nobody can answer (see noHumanAvailable). */
113
+ const HEADLESS_AUTONOMY_NUDGE = 'No human is available in this run, so nobody will answer questions. '
114
+ + 'Decide yourself with your best judgment (state the choice and why in one line), then keep working through '
115
+ + 'your next steps until the task is complete and verified. Stop only when the work is done or you are blocked '
116
+ + 'by something you cannot resolve yourself, and then say exactly what blocks you. '
117
+ + 'Stay within what the task asked for: leave steps beyond it, such as publishing, deploying or messaging people, '
118
+ + 'to whoever reads the result.';
112
119
  /**
113
120
  * Resolve the per-attempt request timeout.
114
121
  *
@@ -199,6 +206,7 @@ function handoffSubstance(text) {
199
206
  // --- Agent Class ---
200
207
  export class Agent {
201
208
  config;
209
+ questionRequester;
202
210
  onMidTurnCompact;
203
211
  midTurnCompactThresholdPercent;
204
212
  midTurnCompactWindow;
@@ -427,9 +435,11 @@ export class Agent {
427
435
  autoContinue: config.autoContinue ?? true,
428
436
  completionCheck: config.completionCheck ?? false,
429
437
  maxConsecutiveAutoContinues: config.maxConsecutiveAutoContinues ?? 3,
438
+ noHumanAvailable: config.noHumanAvailable ?? false,
430
439
  pinTaskHeader: config.pinTaskHeader ?? true,
431
440
  deferToolSchemas: config.deferToolSchemas ?? true,
432
441
  };
442
+ this.questionRequester = config.questionRequester;
433
443
  this.onMidTurnCompact = config.onMidTurnCompact;
434
444
  this.midTurnCompactThresholdPercent = config.midTurnCompactThresholdPercent;
435
445
  this.midTurnCompactWindow = config.midTurnCompactWindow;
@@ -503,6 +513,18 @@ export class Agent {
503
513
  execution: { ...this.config.execution },
504
514
  });
505
515
  }
516
+ questionHandler(signal) {
517
+ const requester = this.questionRequester;
518
+ if (!requester)
519
+ return undefined;
520
+ return async (questions) => {
521
+ const answers = await requester(questions, signal);
522
+ signal?.throwIfAborted();
523
+ if (answers.length !== questions.length || answers.some(answer => typeof answer !== 'string'))
524
+ return 'Question answer count does not match';
525
+ return { answer: questions.length === 1 ? answers[0] : JSON.stringify(questions.map((question, index) => ({ question: question.question, answer: answers[index] }))) };
526
+ };
527
+ }
506
528
  setAutoContinue(enabled) {
507
529
  this._autoContinue = enabled && this.backend.getModelCapabilities?.(this.config.model)?.tools !== false;
508
530
  }
@@ -553,6 +575,29 @@ export class Agent {
553
575
  ];
554
576
  return continuePatterns.some(p => p.test(content));
555
577
  }
578
+ /**
579
+ * With nobody to answer, a turn may not end on a question to the user or on a
580
+ * list of steps the model says it has not done yet.
581
+ */
582
+ needsAutonomousContinuation(content) {
583
+ if (!this._autoContinue || !this.config.noHumanAvailable)
584
+ return false;
585
+ const asksUser = [
586
+ /\b(do|would) you (want|like|prefer)\b/i,
587
+ /\b(should|shall) I\b[^.?!\n]*\?/i,
588
+ /\blet me know\b/i,
589
+ /\b(need|want) your (call|input|decision|confirmation|approval|go-ahead)\b/i,
590
+ /\bplease (confirm|advise|choose|decide)\b/i,
591
+ /\bwhich (option|approach|one|variant)\b[^.?!\n]*\?/i,
592
+ ];
593
+ const unfinished = [
594
+ /\bmy next steps? (are|is|would be)\b/i,
595
+ /\bnext steps?:/i,
596
+ /\bstatus:[^\n]*\b(unverified|in progress|incomplete|pending|not yet)\b/i,
597
+ /\bI have(n't| not) (yet )?(run|built|tested|verified|measured|rendered)\b/i,
598
+ ];
599
+ return [...asksUser, ...unfinished].some(pattern => pattern.test(content));
600
+ }
556
601
  hasApiKey() {
557
602
  return this.config.runtimeCredentialsAvailable
558
603
  || this._authenticationManagedByBackend
@@ -2083,16 +2128,18 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2083
2128
  // full-context request, so a model that keeps narrating an intention
2084
2129
  // instead of calling a tool must not be able to spend maxIterations
2085
2130
  // round trips on it. The budget is reset by any executed tool.
2086
- if (!this.remoteResourceSession && this.shouldContinue(iterationText)
2131
+ const unattended = this.needsAutonomousContinuation(iterationText);
2132
+ if (!this.remoteResourceSession && (unattended || this.shouldContinue(iterationText))
2087
2133
  && this._consecutiveAutoContinues < this.config.maxConsecutiveAutoContinues) {
2088
2134
  this._consecutiveAutoContinues++;
2089
2135
  const acTodos = getLatestTodos();
2090
2136
  const incomplete = acTodos.filter(t => t.status !== 'completed');
2091
- let continueMsg = 'continue';
2092
- let reason = '';
2137
+ let continueMsg = unattended ? HEADLESS_AUTONOMY_NUDGE : 'continue';
2138
+ let reason = unattended ? 'no human available to answer' : '';
2093
2139
  if (incomplete.length > 0) {
2094
2140
  const remaining = incomplete.map(t => t.content).join(', ');
2095
- continueMsg = `You still have ${incomplete.length} incomplete task(s): ${remaining}. Continue working on them.`;
2141
+ const todoMsg = `You still have ${incomplete.length} incomplete task(s): ${remaining}. Continue working on them.`;
2142
+ continueMsg = unattended ? `${HEADLESS_AUTONOMY_NUDGE} ${todoMsg}` : todoMsg;
2096
2143
  reason = `${incomplete.length} incomplete task(s): ${remaining}`;
2097
2144
  }
2098
2145
  this.emit({ type: 'auto_continue', reason });
@@ -2347,6 +2394,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2347
2394
  sessionId: this.config.sessionId,
2348
2395
  managedCommandWaitSliceMs: 0,
2349
2396
  signal,
2397
+ askUser: this.questionHandler(signal),
2350
2398
  toolResponseStore: this.toolResponseStore,
2351
2399
  discoveredTools: this.discoveredTools,
2352
2400
  backgroundWorkers: this.backgroundWorkers,
@@ -2380,6 +2428,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2380
2428
  sessionId: this.config.sessionId,
2381
2429
  managedCommandWaitSliceMs: 0,
2382
2430
  signal,
2431
+ askUser: this.questionHandler(signal),
2383
2432
  toolResponseStore: this.toolResponseStore,
2384
2433
  discoveredTools: this.discoveredTools,
2385
2434
  backgroundWorkers: this.backgroundWorkers,
@@ -2757,6 +2806,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2757
2806
  sessionId: this.config.sessionId,
2758
2807
  signal: options.signal,
2759
2808
  onUsage: options.onUsage,
2809
+ askUser: this.questionHandler(options.signal),
2760
2810
  toolResponseStore: this.toolResponseStore,
2761
2811
  discoveredTools: this.discoveredTools,
2762
2812
  backgroundWorkers: this.backgroundWorkers,
@@ -3176,6 +3226,29 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3176
3226
  // Check for status codes in error message
3177
3227
  const statusMatch = message.match(/API error \((\d+)\)/);
3178
3228
  const statusCode = statusMatch ? parseInt(statusMatch[1], 10) : 0;
3229
+ // A depleted personal allowance cannot recover through transient backoff.
3230
+ // Only a verified code or an exact numeric quota message is public; never
3231
+ // forward arbitrary provider diagnostics or credentials with this guidance.
3232
+ if (statusCode === 429) {
3233
+ try {
3234
+ const diagnostic = message.slice(0, 64 * 1024);
3235
+ const record = (value) => value !== null
3236
+ && typeof value === 'object' && !Array.isArray(value) ? value : {};
3237
+ const payload = record(JSON.parse(diagnostic.slice(diagnostic.indexOf('{'), diagnostic.lastIndexOf('}') + 1)));
3238
+ const detail = record(payload.error);
3239
+ const data = record(payload.data);
3240
+ const counts = [payload.message, payload.statusMessage, detail.message, payload.error]
3241
+ .map(value => typeof value === 'string' ? /^Token quota exceeded ?\((\d{1,20})\/(\d{1,20})\)$/.exec(value) : null)
3242
+ .find(value => value !== null);
3243
+ if ([payload.code, detail.code, data.code].includes('personal_token_quota_exceeded') || counts) {
3244
+ const usage = counts ? ` (${counts[1]}/${counts[2]} tokens)` : '';
3245
+ return { retryable: false, reason: `Token quota exhausted${usage}. Review your Router quota or wait for its reset before retrying.` };
3246
+ }
3247
+ }
3248
+ catch {
3249
+ // Unknown/malformed envelopes retain the existing HTTP retry policy.
3250
+ }
3251
+ }
3179
3252
  // Parse JSON error body if present — supports multiple provider formats:
3180
3253
  // Anthropic/OpenAI: {"error": {"type": "...", "message": "..."}}
3181
3254
  // Google/Gemini: {"error": {"code": 400, "message": "...", "status": "INVALID_ARGUMENT"}}
@@ -27,6 +27,7 @@ import { CodexAuthManager, CodexAuthBackend } from './codex_auth.js';
27
27
  import { ClarifaiBackend } from './clarifai.js';
28
28
  import { KimiCodeAuthBackend, KimiCodeAuthManager } from './kimi_code_auth.js';
29
29
  import { ZRouterStreamBackend } from './zrouter_stream.js';
30
+ import { requiredRouterModel } from '../../config/router_required.js';
30
31
  import { CODEX_APP_SERVER_PROVIDER, CODEX_LEGACY_PROVIDER, isDirectBackendProvider, normalizeProviderId } from './provider_ids.js';
31
32
  import { writeBackendTrace } from './trace.js';
32
33
  import { assertProviderNotRetired } from '../../config/retired_routes.js';
@@ -113,8 +114,9 @@ function traced(provider, backend) {
113
114
  */
114
115
  export function createBackendForProvider(provider, opts) {
115
116
  if (process.env.ZTC_ROUTER_REQUIRED === '1') {
116
- if (provider !== 'openai')
117
- throw new Error('Required Router profile permits only openai/gpt-6.1-sol');
117
+ const required = requiredRouterModel();
118
+ if (provider !== required.provider)
119
+ throw new Error(`Required Router profile permits only ${required.provider}/${required.model}`);
118
120
  const proxyUrl = process.env.ZERG_PROXY_URL;
119
121
  const apiKey = process.env.ZERG_AUTH_TOKEN?.trim();
120
122
  if (!proxyUrl || !apiKey)
@@ -122,7 +124,7 @@ export function createBackendForProvider(provider, opts) {
122
124
  const origin = new URL(proxyUrl);
123
125
  if (origin.protocol !== 'https:' || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash)
124
126
  throw new Error('Required Router origin must be a credential-free HTTPS origin');
125
- return traced(provider, new ZRouterStreamBackend({ provider, model: 'gpt-6.1-sol', apiKey, proxyUrl: origin.origin }));
127
+ return traced(provider, new ZRouterStreamBackend({ provider, model: required.model, apiKey, proxyUrl: origin.origin }));
126
128
  }
127
129
  // Claude Code is no longer a model backend: Anthropic reserves subscription
128
130
  // sign-in for Claude Code itself. Say where to go instead of "unknown provider".
@@ -17,6 +17,7 @@ import { OpenAIResponsesBackend } from './openai_responses.js';
17
17
  import { endingRouterRefusal, readRouterRefusal, RouterRefusalError } from './router_refusal.js';
18
18
  import { routerAccount, routerRefusalGate } from './router_gate.js';
19
19
  import { countRouterRequests } from './router_requests.js';
20
+ import { requiredRouterModel } from '../../config/router_required.js';
20
21
  const ZROUTER_HEADERS_TIMEOUT_MS = 90_000;
21
22
  // A process session is descriptive telemetry, never a registered machine identity.
22
23
  const routerClientSession = randomUUID();
@@ -95,7 +96,7 @@ export class ZRouterStreamBackend {
95
96
  clientName;
96
97
  openRouterPreferences;
97
98
  constructor(config) {
98
- this.preservesNativeHistory = config.provider === 'openai' && (config.model === 'gpt-6.1-sol' || process.env.ZTC_ROUTER_REQUIRED === '1');
99
+ this.preservesNativeHistory = config.provider === 'openai' && config.model === 'gpt-6.1-sol';
99
100
  this.initialCatalog = config.catalog ? structuredClone(config.catalog) : undefined;
100
101
  this.apiKey = config.apiKey;
101
102
  this.proxyUrl = config.proxyUrl.replace(/\/+$/, '');
@@ -122,9 +123,12 @@ export class ZRouterStreamBackend {
122
123
  return !this.usesNativeResponses(request);
123
124
  }
124
125
  usesNativeResponses(request) {
125
- if (process.env.ZTC_ROUTER_REQUIRED === '1' && (this.provider !== 'openai' || request.model !== 'gpt-6.1-sol'
126
- || request.routePlan?.allow_fallbacks || request.routePlan?.fallbacks.length)) {
127
- throw new Error('Required Router profile permits only openai/gpt-6.1-sol without fallbacks');
126
+ if (process.env.ZTC_ROUTER_REQUIRED === '1') {
127
+ const required = requiredRouterModel();
128
+ if (this.provider !== required.provider || request.model !== required.model
129
+ || request.routePlan?.allow_fallbacks || request.routePlan?.fallbacks.length) {
130
+ throw new Error(`Required Router profile permits only ${required.provider}/${required.model} without fallbacks`);
131
+ }
128
132
  }
129
133
  return this.provider === 'openai' && request.model === 'gpt-6.1-sol';
130
134
  }
@@ -352,6 +352,8 @@ export declare const GOAL_BLOCKED_SENTINEL = "GOAL_BLOCKED";
352
352
  export declare const MAX_BLOCK_REASON_LEN = 300;
353
353
  /** Max objective length — keeps every continuation prompt bounded. */
354
354
  export declare const MAX_OBJECTIVE_LEN = 2000;
355
+ /** Canonical lexical admission for a persistent authored goal. */
356
+ export declare function hasSustainedGoalIntent(text: string): boolean;
355
357
  /**
356
358
  * What the agent is told when it tries to resume, replace, or clear a goal.
357
359
  *
@@ -313,6 +313,12 @@ export const GOAL_BLOCKED_SENTINEL = 'GOAL_BLOCKED';
313
313
  export const MAX_BLOCK_REASON_LEN = 300;
314
314
  /** Max objective length — keeps every continuation prompt bounded. */
315
315
  export const MAX_OBJECTIVE_LEN = 2000;
316
+ /** Canonical lexical admission for a persistent authored goal. */
317
+ export function hasSustainedGoalIntent(text) {
318
+ return text.length <= MAX_OBJECTIVE_LEN
319
+ && /\b(?:keep|continue)\s+(?:working|iterating|optimizing|doing|going)\b/iu.test(text)
320
+ && /\buntil\b[\s\S]*\b(?:interrupt|stop|done|complete|plateau)\b/iu.test(text);
321
+ }
316
322
  /**
317
323
  * What the agent is told when it tries to resume, replace, or clear a goal.
318
324
  *
@@ -815,8 +821,7 @@ export class GoalManager {
815
821
  // Steering stays ordinary user context. Replacing an existing goal requires /goal.
816
822
  if (this.goal && this.goal.status !== 'complete')
817
823
  return null;
818
- if (!/\b(?:keep|continue)\s+(?:working|iterating|optimizing|doing|going)\b/iu.test(text)
819
- || !/\buntil\b[\s\S]*\b(?:interrupt|stop|done|complete|plateau)\b/iu.test(text) || text.length > MAX_OBJECTIVE_LEN)
824
+ if (!hasSustainedGoalIntent(text))
820
825
  return null;
821
826
  const tokens = text.split(/[^\S\n]+/u);
822
827
  if (tokens.some(token => token.startsWith('--') && !SUSTAINED_GOAL_FLAGS.has(token.split('=')[0].toLowerCase())))
@@ -29,6 +29,8 @@ export interface AgentFactoryOptions {
29
29
  /** Cap on consecutive auto-continues inside one turn. See AgentConfig. */
30
30
  maxConsecutiveAutoContinues?: number;
31
31
  completionCheck?: boolean;
32
+ /** Nobody can answer this run; see AgentConfig.noHumanAvailable. */
33
+ noHumanAvailable?: boolean;
32
34
  /** Keep the first user turn in request.system for long single-task sessions. */
33
35
  pinTaskHeader?: boolean;
34
36
  /** Max iterations for agent (default: 10) */
@@ -765,6 +765,7 @@ export function createAgentFromConfig(options) {
765
765
  completionCheck: options.completionCheck,
766
766
  maxConsecutiveAutoContinues: options.maxConsecutiveAutoContinues
767
767
  ?? options.config.maxConsecutiveAutoContinues,
768
+ noHumanAvailable: options.noHumanAvailable,
768
769
  maxIterations: options.maxIterations,
769
770
  apiRetry: options.apiRetry ?? options.config.apiRetry,
770
771
  tracer: options.tracer,
@@ -29,7 +29,8 @@ export interface EncodeDeps {
29
29
  selectorVerdict: Map<string, string> | null;
30
30
  /**
31
31
  * Tool_use_ids belonging to the current turn. Current-turn results stay full so
32
- * the model can act on them; older results get capped to OLD_RESULT_CAP.
32
+ * the model can act on them. Older results follow the aggregate selector's
33
+ * budget verdict; unselected fallback content retains the legacy size cap.
33
34
  */
34
35
  currentTurnToolIds: Set<string>;
35
36
  /** Fallback renderer when the verdict has no entry for an id (the agent's tool store). */