@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/dist/headless.js CHANGED
@@ -26,6 +26,9 @@ import { randomUUID } from 'node:crypto';
26
26
  import { writeFile } from 'fs/promises';
27
27
  import { existsSync, truncateSync } from 'node:fs';
28
28
  import { configStore } from './config.js';
29
+ import { effectiveHeadlessPolicy } from './desktop/daily/delegated_ztc_contract.js';
30
+ import { fileFactsTool } from './desktop/daily/file_facts.js';
31
+ import { defaultTools } from './agent/tools/index.js';
29
32
  import { isRetiredModel, isRetiredProvider, retiredProviderMessage, ROUTE_AWAITS_A_CHOICE, RouteAwaitingChoiceError } from './config/retired_routes.js';
30
33
  import { formatTaskHandoffContext, projectTaskHandoff } from './session_handoff_contract.js';
31
34
  import { RouterConfigurationError } from './router_auth.js';
@@ -79,11 +82,13 @@ import { isSimulationSubsystemLoaded } from './simulation/subsystem_loaded.js';
79
82
  import { getCurrentBatch, clearCurrentBatch } from './batch/index.js';
80
83
  import { EmbeddedController } from './embedded/controller.js';
81
84
  import { BenchController } from './bench/controller.js';
82
- import { applyAgentEventToState, buildActivityDisplayState } from './app/activity.js';
85
+ import { applyAgentEventToState, buildActivityDisplayState, formatApiRetryNotice } from './app/activity.js';
83
86
  import { HookLifecycle } from './hooks/lifecycle.js';
84
87
  import { runtimePluginRegistry } from './plugin/runtime_registry.js';
88
+ import { RemoteApprovalClient } from './headless_approval.js';
85
89
  import { getWorkflowRegistry } from './workflows/registry_handle.js';
86
90
  import { workflowsEnabled, workflowNaturalLanguageTriggerEnabled } from './workflows/config.js';
91
+ import { activeProfile, profileConfigDir } from './config/profiles.js';
87
92
  /** Exit status when the only failure was a final message that never satisfied --output-schema. */
88
93
  export const HEADLESS_EXIT_OUTPUT_SCHEMA = 3;
89
94
  /** Exit status for an unusable --output-schema or --trajectory-jsonl, before any inference. */
@@ -94,6 +99,32 @@ export const HEADLESS_EXIT_USAGE = 2;
94
99
  * are on stderr. 2 is taken by usage errors and the retired-route refusal, 3 by --output-schema.
95
100
  */
96
101
  export const HEADLESS_EXIT_ROUTER_REFUSED = 4;
102
+ /**
103
+ * Router sign-ins are stored per profile, so a named profile can be signed out
104
+ * while `ztc auth status` (default profile) reports signed in. Name the profile
105
+ * and the exact command instead of a generic credential error. A built-in
106
+ * preset without a directory of its own shares the default sign-in and keeps
107
+ * the default guidance. Every variant keeps the established prefix.
108
+ */
109
+ function missingCredentialsMessage(profile) {
110
+ const alternatives = 'set a provider API key for direct mode, or provide ZTC_AUTH_TOKEN for platform routing.';
111
+ if (profileConfigDir(profile) === profileConfigDir('default')) {
112
+ return `No API credentials configured. Run ztc auth login for Zerg Router, ${alternatives}`;
113
+ }
114
+ return `No API credentials configured for profile "${profile}". Router sign-ins are stored per profile: `
115
+ + `run ztc --profile ${profile} auth login for Zerg Router, ${alternatives}`;
116
+ }
117
+ /**
118
+ * A model only Zerg Router serves names itself and the step that reaches it (RouterOnlyModelError). When that step is
119
+ * a login and the profile has a sign-in of its own, the login is that profile's: it is named, with its command, after
120
+ * the established prefix, as missingCredentialsMessage names it.
121
+ */
122
+ function routerOnlyCredentialsMessage(error, profile) {
123
+ if (error.authMode === 'direct' || profileConfigDir(profile) === profileConfigDir('default'))
124
+ return error.message;
125
+ return `No API credentials configured for profile "${profile}". ${error.message} `
126
+ + `Router sign-ins are stored per profile: run ztc --profile ${profile} auth login.`;
127
+ }
97
128
  export function classifyPaneChildLine(line) {
98
129
  const trimmed = line.trim();
99
130
  // A control command is ONLY a BARE {"__ztc_cmd":...} line — the parent's
@@ -437,7 +468,12 @@ export class HeadlessApp {
437
468
  lastEmittedVerb = null;
438
469
  lastEmittedWaiting = null;
439
470
  hookLifecycle;
471
+ effectivePolicy;
472
+ approvalClient;
440
473
  constructor(options, sinks = {}) {
474
+ this.effectivePolicy = sinks.policy ?? null;
475
+ const approvalUrl = options.approvalUrl ?? process.env.ZTC_APPROVAL_URL;
476
+ this.approvalClient = approvalUrl ? new RemoteApprovalClient(approvalUrl, process.env.ZTC_APPROVAL_TOKEN) : null;
441
477
  this.outputSchema = sinks.outputSchema ?? null;
442
478
  this.trajectory = sinks.trajectory ?? null;
443
479
  this.options = {
@@ -514,7 +550,8 @@ export class HeadlessApp {
514
550
  getCwd: () => this.options.cwd ? resolve(this.options.cwd) : process.cwd(),
515
551
  getMode: () => this.currentMode,
516
552
  getPaneId: () => this.getHookPaneId(),
517
- getHooks: () => configStore.get().hooks,
553
+ getHooks: () => this.options.closedExtensions ? {} : configStore.get().hooks,
554
+ ...(options.closedExtensions ? { approvedStorePath: resolve(process.env.ZTC_CONFIG_DIR || homedir(), 'closed-hooks-unused.json') } : {}),
518
555
  getSessionStartPayload: () => ({
519
556
  provider: configStore.getProvider(),
520
557
  model: configStore.getModel(),
@@ -557,7 +594,31 @@ export class HeadlessApp {
557
594
  * different case: a human is watching the pane in the web mirror and can
558
595
  * answer via the composer/widget — see handleAskUser's paneChild branch.
559
596
  */
560
- handleAskUser(questions) {
597
+ async handleAskUser(questions) {
598
+ if (!this.approvalClient && this.options.autoAccept === false) {
599
+ this.output({ type: 'approval_denied', timestamp: new Date().toISOString(), data: { tool: 'ask_user', capabilities: [] } });
600
+ return 'Headless question denied without a human approval broker';
601
+ }
602
+ if (this.approvalClient) {
603
+ const answers = [];
604
+ for (const question of questions) {
605
+ const request = { kind: 'question', requestId: randomUUID(), sessionId: this.sessionId,
606
+ cwd: this.shellCwd || process.cwd(), question: question.question, options: question.options };
607
+ this.output({ type: 'ask_user', timestamp: new Date().toISOString(), data: this.options.autoAccept === false ? { requestId: request.requestId, tool: 'ask_user', capabilities: [] } : { ...request } });
608
+ const result = await this.approvalClient.request(request, {
609
+ timeoutMs: this.operationTimeoutMs(), signal: this.activeRunController?.signal,
610
+ });
611
+ this.output({ type: 'question_resolved', timestamp: new Date().toISOString(), data: this.options.autoAccept === false ? { requestId: request.requestId, decision: result.decision } : { ...request, ...result } });
612
+ if (result.decision !== 'answered' || result.answer === undefined)
613
+ return result.reason || 'Remote question was not answered';
614
+ answers.push(result.answer);
615
+ }
616
+ this.messages.push({ id: `msg_${randomUUID()}`, role: 'user',
617
+ content: questions.length === 1 ? answers[0] : JSON.stringify(questions.map((question, i) => ({ question: question.question, answer: answers[i] }))),
618
+ timestamp: new Date() });
619
+ this.askUserAutoAnswered = true;
620
+ return null;
621
+ }
561
622
  if (this.options.paneChild) {
562
623
  // A human is watching this pane in the web mirror. Surface the question
563
624
  // instead of auto-answering: emit an 'ask_user' event that the cli_ratatui
@@ -634,19 +695,33 @@ export class HeadlessApp {
634
695
  return Number.isFinite(paneId) ? paneId : undefined;
635
696
  }
636
697
  async requestHookApproval(request) {
698
+ if (this.approvalClient) {
699
+ const payload = { kind: 'approval', requestId: randomUUID(), sessionId: request.sessionId, cwd: request.cwd,
700
+ toolName: request.toolName, args: request.args, capabilities: request.capabilities, reason: request.reason };
701
+ this.output({ type: 'approval_requested', timestamp: new Date().toISOString(), data: this.options.autoAccept === false ? { requestId: payload.requestId, tool: payload.toolName, capabilities: payload.capabilities } : { ...payload } });
702
+ const result = await this.approvalClient.request(payload, {
703
+ timeoutMs: this.operationTimeoutMs(), signal: this.activeRunController?.signal,
704
+ });
705
+ this.output({ type: 'approval_resolved', timestamp: new Date().toISOString(), data: this.options.autoAccept === false ? { requestId: payload.requestId, decision: result.decision, tool: payload.toolName, capabilities: payload.capabilities } : { ...payload, ...result } });
706
+ if (this.options.autoAccept === false && result.decision !== 'approved')
707
+ this.output({ type: 'approval_denied', timestamp: new Date().toISOString(), data: { tool: payload.toolName, capabilities: payload.capabilities } });
708
+ return { approved: result.decision === 'approved', reason: result.reason };
709
+ }
637
710
  const approved = this.options.autoAccept !== false;
711
+ if (!approved)
712
+ this.output({ type: 'approval_denied', timestamp: new Date().toISOString(), data: { tool: request.toolName, capabilities: request.capabilities } });
638
713
  this.output({
639
714
  type: 'status',
640
715
  timestamp: new Date().toISOString(),
641
716
  data: {
642
717
  status: approved ? 'hook_auto_approved' : 'hook_auto_denied',
643
718
  tool: request.toolName,
644
- reason: request.reason,
719
+ ...(approved ? { reason: request.reason } : { capabilities: request.capabilities }),
645
720
  }
646
721
  });
647
722
  return approved
648
723
  ? { approved: true }
649
- : { approved: false, reason: request.reason || `Headless mode denied ${request.toolName}` };
724
+ : { approved: false, reason: `Headless mode denied ${request.toolName}` };
650
725
  }
651
726
  /**
652
727
  * Subscribe to agent events for activity tracking and output emission.
@@ -806,6 +881,18 @@ export class HeadlessApp {
806
881
  data: { status: 'auto_continue' },
807
882
  });
808
883
  break;
884
+ case 'api_retry':
885
+ // Without this a run retrying a failing provider prints nothing and
886
+ // looks hung until its wall-clock timeout (the TUI already shows it).
887
+ this.output({
888
+ type: 'status',
889
+ timestamp: new Date().toISOString(),
890
+ data: { status: 'api_retry', message: formatApiRetryNotice(event), attempt: event.attempt, max_attempts: event.maxAttempts,
891
+ delay_ms: event.delay, reason: event.reason, phase: event.phase ?? 'retry',
892
+ ...(event.elapsedMs === undefined ? {} : { elapsed_ms: event.elapsedMs }),
893
+ ...(event.rateLimited === undefined ? {} : { rate_limited: event.rateLimited }) },
894
+ });
895
+ break;
809
896
  case 'token_usage':
810
897
  // Capture the PER-CALL occupancy + provider window. event.contextTokens
811
898
  // is already net of the transient tool-result overage; event.usage is
@@ -929,7 +1016,7 @@ export class HeadlessApp {
929
1016
  // In quiet mode, skip status unless verbose
930
1017
  if (this.options.quiet && !this.options.verbose)
931
1018
  break;
932
- console.log(`${ts}[status] ${data.data.waiting ? 'Waiting for command' : data.data.status}`);
1019
+ console.log(`${ts}[status] ${data.data.waiting ? 'Waiting for command' : data.data.status === 'api_retry' ? data.data.message : data.data.status}`);
933
1020
  break;
934
1021
  case 'artifact':
935
1022
  console.log(`${ts}[artifact] ${data.data.path}`);
@@ -1188,6 +1275,16 @@ export class HeadlessApp {
1188
1275
  // whose real credential (for example a Codex subscription auth.json) is on
1189
1276
  // disk. `load()` is idempotent, so the CLI path is unaffected.
1190
1277
  await configStore.load();
1278
+ if (this.options.closedExtensions) {
1279
+ if (!defaultTools.some(tool => tool.definition.name === fileFactsTool.definition.name))
1280
+ defaultTools.push(fileFactsTool);
1281
+ configStore.setConfigScope('session');
1282
+ configStore.set('workflows', { enabled: false });
1283
+ configStore.set('mcpServers', {});
1284
+ configStore.set('hooks', {});
1285
+ const { closeMcpServers } = await import('./mcp/registry.js');
1286
+ await closeMcpServers();
1287
+ }
1191
1288
  // A headless run executes model-chosen commands with no human reviewing
1192
1289
  // them, so tool children never inherit the run's inference credentials.
1193
1290
  this.reserveRouteCredentials();
@@ -1201,13 +1298,15 @@ export class HeadlessApp {
1201
1298
  // Hosted native Messages supplies its own scoped transport bearer. The
1202
1299
  // backend factory validates it; provider-key discovery must not gate it.
1203
1300
  if (configStore.getProvider() !== 'bedrock' && !configStore.get().nativeAnthropicMessagesRouter && !configStore.hasApiKey() && !configStore.isAuthenticated()) {
1301
+ // A model only Zerg Router serves needs no key here: it names itself and the step that reaches it, the
1302
+ // profile's own login included (routerOnlyCredentialsMessage). Otherwise the profile whose sign-in is missing
1303
+ // is named (missingCredentialsMessage).
1304
+ const routerOnly = currentRouterOnlyModelError(configStore);
1204
1305
  this.output({
1205
1306
  type: 'error',
1206
1307
  timestamp: new Date().toISOString(),
1207
1308
  data: {
1208
- // A model only Zerg Router serves needs no key here: it names itself and the step that reaches it.
1209
- message: currentRouterOnlyModelError(configStore)?.message
1210
- ?? 'No API credentials configured. Run ztc auth login for Zerg Router, set a provider API key for direct mode, or provide ZTC_AUTH_TOKEN for platform routing.',
1309
+ message: routerOnly ? routerOnlyCredentialsMessage(routerOnly, activeProfile()) : missingCredentialsMessage(activeProfile()),
1211
1310
  }
1212
1311
  });
1213
1312
  return false;
@@ -1216,18 +1315,19 @@ export class HeadlessApp {
1216
1315
  // bench runtimes, agent-tool bundles, and modes_dir contributions
1217
1316
  // land before the mode registry / agent factory consult them.
1218
1317
  // Interactive ZTC does this in cli_main.ts; headless mirrors that.
1219
- try {
1220
- const { loadAllPlugins } = await import('./simulation/plugins/loader.js');
1221
- await loadAllPlugins();
1222
- refreshPluginCommands();
1223
- }
1224
- catch (err) {
1225
- this.output({
1226
- type: 'error',
1227
- timestamp: new Date().toISOString(),
1228
- data: { message: `[ztc/plugins] discovery failed: ${err.message}` },
1229
- });
1230
- }
1318
+ if (!this.options.closedExtensions)
1319
+ try {
1320
+ const { loadAllPlugins } = await import('./simulation/plugins/loader.js');
1321
+ await loadAllPlugins();
1322
+ refreshPluginCommands();
1323
+ }
1324
+ catch (err) {
1325
+ this.output({
1326
+ type: 'error',
1327
+ timestamp: new Date().toISOString(),
1328
+ data: { message: `[ztc/plugins] discovery failed: ${err.message}` },
1329
+ });
1330
+ }
1231
1331
  // Initialize mode registry
1232
1332
  const builtinModesDir = resolve(import.meta.dirname, 'modes', 'builtin');
1233
1333
  const registry = await initModeRegistry(builtinModesDir);
@@ -1639,6 +1739,8 @@ export class HeadlessApp {
1639
1739
  // store instance; must run BEFORE the agent's first turn so offloaded
1640
1740
  // results land in the right place.
1641
1741
  await this.awaitAgentBind();
1742
+ if (this.options.closedExtensions && this.agent)
1743
+ this.agent.discoveredTools.add(fileFactsTool.definition.name);
1642
1744
  await this.hookLifecycle.sessionStart(resumedSession);
1643
1745
  // Apply persona override if spawned as a simulation agent pane
1644
1746
  const simPersona = process.env.ZTC_SIM_PERSONA;
@@ -1698,6 +1800,12 @@ export class HeadlessApp {
1698
1800
  autoContinue: true, // Always auto-continue in headless mode
1699
1801
  maxConsecutiveAutoContinues: configStore.getMaxConsecutiveAutoContinues(),
1700
1802
  completionCheck: true,
1803
+ // Only a pane parent, a JSON stream driver, a remote answerer
1804
+ // (--approval-url) or a person typing at the terminal can answer a
1805
+ // question; a plain prompt or piped stdin run has nobody, so its turns
1806
+ // must not end on one.
1807
+ noHumanAvailable: !this.options.paneChild && !this.options.jsonStream && !this.approvalClient
1808
+ && !this.options.interactiveTerminal,
1701
1809
  maxIterations: isEvolveMode ? 200 : (this.options.maxIterations ?? Infinity),
1702
1810
  pinTaskHeader: this.options.pinTaskHeader,
1703
1811
  mode: this.currentMode,
@@ -2138,6 +2246,7 @@ export class HeadlessApp {
2138
2246
  },
2139
2247
  getDiagnostics: () => this.sessionManager.getDiagnostics(),
2140
2248
  getEvidenceSnapshot: () => this.agent?.getEvidenceSnapshot(),
2249
+ getTaskHandoff: () => this.taskHandoff,
2141
2250
  getSessionName: () => this.sessionName,
2142
2251
  setSessionName: (name) => {
2143
2252
  this.sessionName = name && name.length > 0 ? name : undefined;
@@ -2254,7 +2363,7 @@ export class HeadlessApp {
2254
2363
  */
2255
2364
  async runPrompt(prompt, opts = {}) {
2256
2365
  this.routerRefusedTurn = false;
2257
- if (process.env.ZTC_DISABLE_SLASH_COMMANDS !== '1' && routeUserInput(prompt).type === 'command') {
2366
+ if (!this.options.policyHash && process.env.ZTC_DISABLE_SLASH_COMMANDS !== '1' && routeUserInput(prompt).type === 'command') {
2258
2367
  await this.runPromptAdmitted(prompt, opts);
2259
2368
  return;
2260
2369
  }
@@ -2270,7 +2379,7 @@ export class HeadlessApp {
2270
2379
  }
2271
2380
  async runPromptAdmitted(prompt, opts = {}) {
2272
2381
  // Route input: slash command or regular message
2273
- const route = process.env.ZTC_DISABLE_SLASH_COMMANDS === '1' ? { type: 'message' } : routeUserInput(prompt);
2382
+ const route = this.options.policyHash || process.env.ZTC_DISABLE_SLASH_COMMANDS === '1' ? { type: 'message' } : routeUserInput(prompt);
2274
2383
  if (route.type === 'command') {
2275
2384
  // A pane child's prompts arrive on stdin from its parent: the overseer's write_terminal_pane, another pane or
2276
2385
  // the mux, never only the person typing. So do the prompts of any run another ZTC launched (ZTC_PARENT_PID or
@@ -2305,7 +2414,7 @@ export class HeadlessApp {
2305
2414
  }
2306
2415
  this.promptTurn += 1;
2307
2416
  // A schema-bound prompt always takes the validated agent path below.
2308
- const triggeredWorkflow = !this.outputSchema && this.workflowToolAvailableInCurrentMode()
2417
+ const triggeredWorkflow = !this.options.closedExtensions && !this.outputSchema && this.workflowToolAvailableInCurrentMode()
2309
2418
  && workflowsEnabled(configStore.get()) && workflowNaturalLanguageTriggerEnabled(configStore.get())
2310
2419
  ? await this.buildTriggeredWorkflow(prompt)
2311
2420
  : null;
@@ -2642,6 +2751,8 @@ export class HeadlessApp {
2642
2751
  }
2643
2752
  }
2644
2753
  workflowToolAvailableInCurrentMode() {
2754
+ if (this.options.closedExtensions)
2755
+ return false;
2645
2756
  if (this.currentMode === 'plan')
2646
2757
  return false;
2647
2758
  return isToolAllowed('workflow', this.currentMode);
@@ -3202,7 +3313,7 @@ export class HeadlessApp {
3202
3313
  type: 'status',
3203
3314
  timestamp: new Date().toISOString(),
3204
3315
  session_id: this.sessionId,
3205
- data: { status: 'ready', session_id: this.sessionId, mode: this.currentMode }
3316
+ data: { status: 'ready', session_id: this.sessionId, mode: this.currentMode, ...(this.options.closedExtensions ? { extensions: 'closed' } : {}), ...(this.effectivePolicy ? { policy: this.effectivePolicy } : {}) }
3206
3317
  });
3207
3318
  for (const input of parsedInputs) {
3208
3319
  if (this.fatalTurnReached)
@@ -3219,7 +3330,7 @@ export class HeadlessApp {
3219
3330
  type: 'status',
3220
3331
  timestamp: new Date().toISOString(),
3221
3332
  session_id: this.sessionId,
3222
- data: { status: 'ready', session_id: this.sessionId, mode: this.currentMode }
3333
+ data: { status: 'ready', session_id: this.sessionId, mode: this.currentMode, ...(this.options.closedExtensions ? { extensions: 'closed' } : {}), ...(this.effectivePolicy ? { policy: this.effectivePolicy } : {}) }
3223
3334
  });
3224
3335
  // A pane child restored or launched with a retired Claude Code route (an
3225
3336
  // older parent, a saved layout) runs on the configured route; its own
@@ -3416,6 +3527,9 @@ export class HeadlessApp {
3416
3527
  * Run a single prompt and exit
3417
3528
  */
3418
3529
  async runSingle(prompt) {
3530
+ if (this.options.closedExtensions || this.effectivePolicy)
3531
+ this.output({ type: 'status', timestamp: new Date().toISOString(), session_id: this.sessionId,
3532
+ data: { status: 'ready', session_id: this.sessionId, mode: this.currentMode, ...(this.options.closedExtensions ? { extensions: 'closed' } : {}), ...(this.effectivePolicy ? { policy: this.effectivePolicy } : {}) } });
3419
3533
  this.turnStartGoal = snapshotGoalForTurn();
3420
3534
  await this.runPrompt(prompt);
3421
3535
  await this.accountGoalFinalTurnAfterPrompt();
@@ -3497,6 +3611,7 @@ export class HeadlessApp {
3497
3611
  this.sessionToolResponseBinding = null;
3498
3612
  this.sessionId = session.metadata.id;
3499
3613
  this.sessionManager.setSessionId(this.sessionId);
3614
+ this.sessionManager.restoreLayout({ muxState: session.mux_state, paneSpecs: session.pane_specs ?? [] });
3500
3615
  this.sessionManager.restoreDiagnostics(session.diagnostics);
3501
3616
  this.sessionManager.restoreUsageSnapshot(session.usage);
3502
3617
  this.sessionName = session.metadata.name;
@@ -3882,10 +3997,30 @@ export async function runHeadless(options, initialPrompt) {
3882
3997
  }
3883
3998
  jsonInputLines = validatedLines;
3884
3999
  }
4000
+ if (options.closedExtensions)
4001
+ process.env.ZTC_CLOSED_EXTENSIONS = '1';
4002
+ if (options.policyHash) {
4003
+ try {
4004
+ await configStore.load(false, { strictConfig: true });
4005
+ sinks.policy = await effectiveHeadlessPolicy(configStore.get(), { ...options, approvalUrl: options.approvalUrl ?? process.env.ZTC_APPROVAL_URL });
4006
+ if (sinks.policy.policyHash !== options.policyHash)
4007
+ throw new Error('Policy mismatch');
4008
+ }
4009
+ catch {
4010
+ const data = { error: 'policy_mismatch' };
4011
+ if (options.json)
4012
+ process.stdout.write(`${JSON.stringify({ type: 'error', timestamp: new Date().toISOString(), data })}\n`);
4013
+ else
4014
+ process.stderr.write('Effective policy mismatch\n');
4015
+ process.exitCode = 4;
4016
+ return;
4017
+ }
4018
+ }
3885
4019
  const app = new HeadlessApp({
3886
4020
  ...options,
3887
4021
  deferJsonStdinStartup,
3888
4022
  jsonInputLines,
4023
+ interactiveTerminal: options.interactiveTerminal ?? (!initialPrompt && !!process.stdin.isTTY),
3889
4024
  }, sinks);
3890
4025
  let initialized;
3891
4026
  try {
@@ -0,0 +1,29 @@
1
+ export interface RemoteDecisionRequest {
2
+ kind: 'approval' | 'question';
3
+ requestId: string;
4
+ sessionId: string;
5
+ cwd: string;
6
+ toolName?: string;
7
+ args?: Record<string, unknown>;
8
+ capabilities?: string[];
9
+ reason?: string;
10
+ question?: string;
11
+ options?: Array<{
12
+ label: string;
13
+ description?: string;
14
+ }>;
15
+ }
16
+ export interface RemoteDecision {
17
+ decision: 'approved' | 'denied' | 'answered';
18
+ reason?: string;
19
+ answer?: string;
20
+ }
21
+ export declare class RemoteApprovalClient {
22
+ private readonly token?;
23
+ private readonly url;
24
+ constructor(url: string, token?: string | undefined);
25
+ request(request: RemoteDecisionRequest, options: {
26
+ timeoutMs: number;
27
+ signal?: AbortSignal;
28
+ }): Promise<RemoteDecision>;
29
+ }
@@ -0,0 +1,69 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ export class RemoteApprovalClient {
3
+ token;
4
+ url;
5
+ constructor(url, token) {
6
+ this.token = token;
7
+ const parsed = new URL(url);
8
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(parsed.hostname);
9
+ if ((parsed.protocol !== 'https:' && !(parsed.protocol === 'http:' && loopback))
10
+ || parsed.username || parsed.password || parsed.search || parsed.hash) {
11
+ throw new Error('Approval URL must use HTTPS (or HTTP on loopback), without credentials, query, or fragment');
12
+ }
13
+ this.url = parsed.href.replace(/\/+$/, '');
14
+ }
15
+ async request(request, options) {
16
+ const controller = new AbortController();
17
+ const timeout = setTimeout(() => controller.abort(new Error('Approval request timed out')), options.timeoutMs);
18
+ const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
19
+ let polling = false;
20
+ let backoff = 100;
21
+ try {
22
+ while (!signal.aborted) {
23
+ try {
24
+ const response = await fetch(polling ? `${this.url}/${encodeURIComponent(request.requestId)}` : this.url, {
25
+ method: polling ? 'GET' : 'POST',
26
+ headers: { 'content-type': 'application/json', ...(this.token ? { authorization: `Bearer ${this.token}` } : {}) },
27
+ ...(polling ? {} : { body: JSON.stringify(request) }),
28
+ signal,
29
+ redirect: 'error',
30
+ });
31
+ if (response.status >= 400 && response.status < 500 && response.status !== 404) {
32
+ const body = await response.json().catch(() => null);
33
+ return { decision: 'denied', reason: typeof body?.reason === 'string' ? body.reason : `Approval service returned HTTP ${response.status}` };
34
+ }
35
+ if (response.status === 200) {
36
+ const body = await response.json();
37
+ if (body && typeof body === 'object' && 'decision' in body
38
+ && ['approved', 'denied', 'answered'].includes(String(body.decision))) {
39
+ const result = body;
40
+ if ((result.answer !== undefined && typeof result.answer !== 'string')
41
+ || (result.reason !== undefined && typeof result.reason !== 'string')
42
+ || (request.kind === 'question' && result.decision === 'answered' && typeof result.answer !== 'string')) {
43
+ return { decision: 'denied', reason: 'Invalid approval service response' };
44
+ }
45
+ return { decision: result.decision, reason: result.reason, answer: result.answer };
46
+ }
47
+ return { decision: 'denied', reason: 'Invalid approval service response' };
48
+ }
49
+ if (response.status === 202)
50
+ polling = true;
51
+ await response.body?.cancel();
52
+ }
53
+ catch (error) {
54
+ if (signal.aborted)
55
+ throw error;
56
+ }
57
+ await delay(backoff, undefined, { signal });
58
+ backoff = Math.min(backoff * 2, 2000);
59
+ }
60
+ return { decision: 'denied', reason: 'Approval request cancelled or timed out' };
61
+ }
62
+ catch {
63
+ return { decision: 'denied', reason: 'Approval request cancelled or timed out' };
64
+ }
65
+ finally {
66
+ clearTimeout(timeout);
67
+ }
68
+ }
69
+ }
@@ -14,6 +14,7 @@ Server-host options:
14
14
  --json Emit the structured event protocol
15
15
  --json-stream Stay alive and consume JSONL prompts
16
16
  --session-file <path> Read and persist the embedder-managed session
17
+ --approval-url <url> Request remote approvals and question answers
17
18
  --provider <name> LLM provider
18
19
  --model <name> LLM model
19
20
  --auth-mode <mode> How to reach the provider: direct (its API key),
@@ -141,6 +142,7 @@ async function main() {
141
142
  }
142
143
  const { runHeadless } = await import('./headless.js');
143
144
  const headlessOptions = {
145
+ approvalUrl: options.approvalUrl,
144
146
  mode: options.mode,
145
147
  sessionFile: options.sessionFile ? resolve(options.sessionFile) : undefined,
146
148
  json: options.json,
@@ -6,6 +6,10 @@ export interface HeadlessCliOptions {
6
6
  timestamps?: boolean;
7
7
  verbose?: boolean;
8
8
  sessionFile?: string;
9
+ approvalUrl?: string;
10
+ autoAccept?: boolean;
11
+ closedExtensions?: boolean;
12
+ policyHash?: string;
9
13
  detachEnvironment?: boolean;
10
14
  provider?: string;
11
15
  model?: string;
@@ -9,6 +9,8 @@ export function parseHeadlessCliArgs(args) {
9
9
  jsonStream: false,
10
10
  };
11
11
  const booleanFlags = new Map([
12
+ ['--no-auto-accept', () => { options.autoAccept = false; }],
13
+ ['--closed-extensions', () => { options.closedExtensions = true; }],
12
14
  ['--detach-environment', () => { options.detachEnvironment = true; }],
13
15
  ['--json', () => { options.json = true; }],
14
16
  ['--json-stream', () => { options.jsonStream = true; }],
@@ -19,6 +21,9 @@ export function parseHeadlessCliArgs(args) {
19
21
  ['--no-pin-task-header', () => { options.pinTaskHeader = false; }],
20
22
  ]);
21
23
  const valueFlags = new Map([
24
+ ['--policy-hash', value => { if (!/^[a-f0-9]{64}$/.test(value))
25
+ return '--policy-hash requires a sha256 digest.'; options.policyHash = value; return undefined; }],
26
+ ['--approval-url', (value) => { options.approvalUrl = value; return undefined; }],
22
27
  ['--session-file', (value) => { options.sessionFile = value; return undefined; }],
23
28
  ['--provider', (value) => { options.provider = value; return undefined; }],
24
29
  ['--model', (value) => { options.model = value; return undefined; }],
package/dist/library.d.ts CHANGED
@@ -24,6 +24,7 @@
24
24
  * }
25
25
  */
26
26
  import { Agent } from './agent/agent.js';
27
+ import type { AgentConfig } from './agent/agent.js';
27
28
  import type { AgentBackend } from './agent/backends/types.js';
28
29
  import type { NativeAnthropicMessagesRouterConfig } from './agent/backends/index.js';
29
30
  import type { Tool } from './agent/tools/types.js';
@@ -33,10 +34,19 @@ import type { HookApprovalRequester } from './hooks/types.js';
33
34
  import type { ToolCapability } from './agent/runtime/capabilities.js';
34
35
  import type { AgentHandlerFn } from './agent/tools/sim_domain_tools.js';
35
36
  import type { AgentEvent, Message } from './types.js';
37
+ import type { ModelUsageObserver } from './types.js';
36
38
  import type { HostMetadata, InferenceCredentialProvider, ToolEffectObserver } from './host/index.js';
37
39
  import type { CodexReasoningEffort } from './config/types.js';
38
40
  export type { AgentEvent, Message, MessageRole, ToolCall } from './types.js';
39
41
  export type { AgentConfig } from './agent/agent.js';
42
+ export type { MidTurnCompactContext } from './agent/agent.js';
43
+ export type { ToolCheckpoint, ToolCheckpointHandler } from './agent/runtime/tool_checkpoints.js';
44
+ export type { RemoteResource, RemoteResourceSession, RemoteResourceTransport } from './agent/runtime/remote_resources.js';
45
+ export type { HookApprovalRequest, HookApprovalResult, HookApprovalRequester, HookApprovalKind, HookApprovalDecision, HookBaseContext, HookCommandConfig, HookDispatchResult, HookEventName, ZTCHooksConfig } from './hooks/types.js';
46
+ export { HookDispatcher } from './hooks/dispatcher.js';
47
+ export type { MCPServerConfig } from './config/types.js';
48
+ export { ToolCapability } from './agent/runtime/capabilities.js';
49
+ export { closeMcpServers } from './mcp/client.js';
40
50
  export type { AgentBackend } from './agent/backends/types.js';
41
51
  export type { NativeAnthropicMessagesRouterConfig } from './agent/backends/anthropic.js';
42
52
  export type { ContentBlock, RequestContentBlock, ThinkingBlock, RedactedThinkingBlock } from './agent/backends/types.js';
@@ -115,6 +125,8 @@ export interface CreateAgentOptions {
115
125
  * Appends to whatever `tools` resolves to.
116
126
  */
117
127
  domain?: string;
128
+ domainFile?: string;
129
+ domainHandlers?: Readonly<Record<string, Tool>>;
118
130
  /**
119
131
  * Additional handler bindings (key → fn) to register before loading `domain`
120
132
  * tools — useful for in-process hosts that want to supply handlers without
@@ -164,6 +176,14 @@ export interface CreateAgentOptions {
164
176
  approvalRequester?: HookApprovalRequester;
165
177
  approvalRequiredCapabilities?: readonly ToolCapability[];
166
178
  approvalContext?: HostApprovalContext;
179
+ toolCheckpoint?: AgentConfig['toolCheckpoint'];
180
+ onMidTurnCompact?: AgentConfig['onMidTurnCompact'];
181
+ compaction?: boolean;
182
+ onCompactionUsage?: ModelUsageObserver;
183
+ questionRequester?: AgentConfig['questionRequester'];
184
+ remoteResourceSession?: AgentConfig['remoteResourceSession'];
185
+ hooks?: AgentConfig['hooks'];
186
+ mcpServers?: import('./config/types.js').ZTCConfig['mcpServers'];
167
187
  }
168
188
  /**
169
189
  * Handle returned by `createAgent`.