@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
@@ -1,3 +1,4 @@
1
+ import { captureCorrelatedTurns, mergeCorrelatedTurns } from './correlated_turn.js';
1
2
  /**
2
3
  * SessionManager — shared session persistence, auto-save, and compaction.
3
4
  *
@@ -18,29 +19,36 @@ import { prepareSessionMessages } from './session_messages.js';
18
19
  */
19
20
  export class SessionManager {
20
21
  deps;
22
+ promptTurns = [];
21
23
  diagnostics = createDiagnosticSnapshot();
22
24
  usage = createUsageSnapshot();
23
25
  jobDiagnosticStates = new Map();
24
26
  autoSaveTimer = null;
25
27
  saveQueue = Promise.resolve();
26
- muxSnapshot;
27
- muxCapture = null;
28
- muxGeneration = 0;
28
+ layoutSnapshot;
29
+ layoutCapture = null;
30
+ layoutGeneration = 0;
29
31
  cleanupPromise = null;
30
32
  constructor(deps) {
31
33
  this.deps = deps;
32
34
  }
33
35
  setSessionId(sessionId) {
34
36
  if (this.deps.sessionId !== sessionId) {
37
+ this.promptTurns = [];
35
38
  this.diagnostics = createDiagnosticSnapshot();
36
39
  this.usage = createUsageSnapshot();
37
40
  this.jobDiagnosticStates.clear();
38
- this.muxSnapshot = undefined;
39
- this.muxCapture = null;
40
- this.muxGeneration++;
41
+ this.layoutSnapshot = undefined;
42
+ this.layoutCapture = null;
43
+ this.layoutGeneration++;
41
44
  }
42
45
  this.deps.sessionId = sessionId;
43
46
  }
47
+ restoreLayout(layout) {
48
+ if (!layout.muxState && this.layoutSnapshot?.muxState)
49
+ return;
50
+ this.layoutSnapshot = structuredClone(layout);
51
+ }
44
52
  /** Capture the current agent before replacement, then return detached canonical facts. */
45
53
  getDiagnostics() {
46
54
  const current = this.deps.getRuntimeState?.().diagnostics;
@@ -53,6 +61,14 @@ export class SessionManager {
53
61
  if (snapshot)
54
62
  this.diagnostics = mergeDiagnosticSnapshots(this.diagnostics, snapshot);
55
63
  }
64
+ getPromptTurns() {
65
+ this.promptTurns = captureCorrelatedTurns(this.deps.getMessages(), this.promptTurns);
66
+ return structuredClone(this.promptTurns);
67
+ }
68
+ restorePromptTurns(turns) {
69
+ if (turns)
70
+ this.promptTurns = mergeCorrelatedTurns(this.promptTurns, turns);
71
+ }
56
72
  getUsageSnapshot() {
57
73
  const current = this.deps.getRuntimeState?.().usage;
58
74
  if (current)
@@ -114,7 +130,7 @@ export class SessionManager {
114
130
  // if the renderer is unavailable; a responsive renderer supplies its current
115
131
  // layout even on the first required save.
116
132
  if (options.captureLayout ?? true) {
117
- const capture = this.refreshMuxState();
133
+ const capture = this.refreshLayout();
118
134
  if (options.required && options.captureLayout !== true) {
119
135
  let timer;
120
136
  try {
@@ -132,36 +148,63 @@ export class SessionManager {
132
148
  this.saveQueue = pendingSave.catch(() => { });
133
149
  return pendingSave;
134
150
  }
135
- async refreshMuxState() {
136
- if (!this.deps.getMuxState)
137
- return;
138
- if (this.muxCapture)
139
- return this.muxCapture;
140
- const generation = this.muxGeneration;
141
- const read = this.deps.getMuxState;
151
+ async saveBackground(read, muxOnly = false) {
152
+ const generation = this.layoutGeneration;
153
+ const layout = await read();
154
+ if (generation === this.layoutGeneration)
155
+ this.restoreLayout(layout);
156
+ const pending = this.saveQueue.then(async () => {
157
+ const muxState = this.layoutSnapshot?.muxState;
158
+ if (muxOnly && muxState) {
159
+ try {
160
+ if (await saveMuxStateOnly(this.deps.sessionId, this.deps.getSessionCwd?.() ?? process.cwd(), structuredClone(muxState)))
161
+ return;
162
+ }
163
+ catch (error) {
164
+ this.deps.debugLog(`[SessionManager.saveBackground] Mux save failed: ${String(error)}`);
165
+ }
166
+ }
167
+ await this.writeCurrentSession({});
168
+ });
169
+ this.saveQueue = pending.catch(() => { });
170
+ return pending;
171
+ }
172
+ async readLayout() {
173
+ if (this.deps.getLayoutSnapshot)
174
+ return this.deps.getLayoutSnapshot();
175
+ const muxState = await this.deps.getMuxState?.();
176
+ if (this.deps.getMuxState && !muxState)
177
+ return undefined;
178
+ return structuredClone({ muxState, paneSpecs: this.deps.getPaneSpecs?.() ?? [] });
179
+ }
180
+ async refreshLayout() {
181
+ if (this.layoutCapture)
182
+ return this.layoutCapture;
183
+ const generation = this.layoutGeneration;
142
184
  const capture = (async () => {
143
185
  try {
144
- const state = await read.call(this.deps);
145
- if (generation === this.muxGeneration && state !== undefined)
146
- this.muxSnapshot = structuredClone(state);
186
+ const layout = await this.readLayout();
187
+ if (generation === this.layoutGeneration && layout !== undefined)
188
+ this.restoreLayout(layout);
147
189
  }
148
190
  catch (error) {
149
191
  this.deps.debugLog(`[SessionManager.save] Optional layout unavailable: ${String(error)}`);
150
192
  }
151
193
  })();
152
- this.muxCapture = capture;
194
+ this.layoutCapture = capture;
153
195
  try {
154
196
  await capture;
155
197
  }
156
198
  finally {
157
- if (this.muxCapture === capture)
158
- this.muxCapture = null;
199
+ if (this.layoutCapture === capture)
200
+ this.layoutCapture = null;
159
201
  }
160
202
  }
161
203
  async writeCurrentSession(options) {
162
204
  options.signal?.throwIfAborted();
163
205
  await this.deps.flushToolResponses?.();
164
- const muxState = structuredClone(this.muxSnapshot);
206
+ const layout = structuredClone(this.layoutSnapshot);
207
+ const muxState = layout?.muxState;
165
208
  // Capture transcript and runtime together after raw receipt durability;
166
209
  // optional layout replies never gate required restart state.
167
210
  const messages = structuredClone(this.deps.getMessages());
@@ -176,13 +219,14 @@ export class SessionManager {
176
219
  const hasUsage = this.usage.receipts.length > 0 || this.usage.omittedReceipts > 0;
177
220
  const runtimeState = {
178
221
  ...capturedRuntime,
222
+ promptTurns: this.getPromptTurns(),
179
223
  authMode: configStore.getResolvedAuthMode(),
180
224
  routerOrigin: configStore.getResolvedAuthMode() === 'direct' ? undefined : configStore.get().zergProxyUrl,
181
225
  ...(hasUsage ? { usage: structuredClone(this.usage) } : {}),
182
226
  ...(hasDiagnostics ? { diagnostics: structuredClone(this.diagnostics) } : {}),
183
227
  };
184
228
  const hostedSettings = this.deps.getHostedSettings ? structuredClone(this.deps.getHostedSettings()) : undefined;
185
- const paneSpecs = this.deps.getPaneSpecs ? structuredClone(this.deps.getPaneSpecs()) : undefined;
229
+ const paneSpecs = layout?.paneSpecs;
186
230
  const hasRuntimeState = runtimeState !== undefined && (runtimeState.environment != null
187
231
  || runtimeState.mode !== undefined
188
232
  || runtimeState.planFile !== undefined
@@ -192,7 +236,8 @@ export class SessionManager {
192
236
  || runtimeState.goal != null
193
237
  || Boolean(runtimeState.evidence?.records.length)
194
238
  || hasDiagnostics
195
- || hasUsage);
239
+ || hasUsage
240
+ || runtimeState.promptTurns.length > 0);
196
241
  if (messages.length === 0 && !muxState && !hasRuntimeState && !options.persistEmpty)
197
242
  return;
198
243
  const persistMessages = prepareSessionMessages(messages);
@@ -261,10 +306,8 @@ export class SessionManager {
261
306
  * Returns true if the mux file was written, false if no dedicated mux dir exists (non-colony).
262
307
  */
263
308
  async saveMuxOnly() {
264
- if (!this.deps.getMuxState)
265
- return false;
266
- await this.refreshMuxState();
267
- const muxState = structuredClone(this.muxSnapshot);
309
+ await this.refreshLayout();
310
+ const muxState = structuredClone(this.layoutSnapshot?.muxState);
268
311
  if (!muxState)
269
312
  return false;
270
313
  try {
@@ -383,7 +426,7 @@ export class SessionManager {
383
426
  const messages = sourceMessages ?? this.deps.getMessages();
384
427
  if (messages.length < 3 || signal?.aborted)
385
428
  return null;
386
- const model = configStore.getModel();
429
+ const model = this.deps.getModel?.() ?? configStore.getModel();
387
430
  const onUsage = this.deps.getUsageObserver?.();
388
431
  const activityFinished = onUsage?.workerStarted?.();
389
432
  const summarizer = this.buildSummarizer(onUsage, signal, messages);
@@ -420,11 +463,11 @@ export class SessionManager {
420
463
  /**
421
464
  * Start periodic auto-save.
422
465
  */
423
- startAutoSave(intervalMs) {
466
+ startAutoSave(intervalMs, save = () => this.save()) {
424
467
  this.stopAutoSave();
425
468
  this.autoSaveTimer = setInterval(() => {
426
469
  // ZTC exits on an unhandled rejection; a failed background save once closed it mid-turn (2026-10-27).
427
- void this.save().catch(error => this.deps.debugLog(`[SessionManager.save] Background save failed: ${String(error)}`));
470
+ void save().catch(error => this.deps.debugLog(`[SessionManager.save] Background save failed: ${String(error)}`));
428
471
  }, intervalMs);
429
472
  }
430
473
  /**
@@ -438,6 +481,7 @@ export class SessionManager {
438
481
  }
439
482
  /** Capture source signatures before awaiting, including IDs of ordinary rows. */
440
483
  captureCheckpointSources(messages) {
484
+ this.promptTurns = captureCorrelatedTurns(messages, this.promptTurns);
441
485
  // A summarizer may evict settled calls. Retain their actual sources first.
442
486
  this.getDiagnostics();
443
487
  return new Map(messages.map(message => [message.id, this.checkpointSourceState(message)]));
@@ -31,7 +31,7 @@ export interface ToolCallbackDeps {
31
31
  * TUI: stores data and sets pendingAskUser flag.
32
32
  * Headless: auto-selects the first option.
33
33
  */
34
- onAskUser: (questions: AskUserQuestion[]) => string | null;
34
+ onAskUser: (questions: AskUserQuestion[]) => string | null | Promise<string | null>;
35
35
  /**
36
36
  * Optional guard for plan re-entry after approval.
37
37
  * TUI returns true if plan was just approved (blocks re-entry).
@@ -1,9 +1,28 @@
1
+ import type { SessionLayoutSnapshot } from './session_manager.js';
2
+ import { type NativeRecords } from '../desktop/daily/native_records.js';
1
3
  import type { PaneCommandTransport } from '../ui/ratatui/pane_relay.js';
2
4
  import type { PaneSessionSpec } from '../panes/types.js';
3
- import type { RustEvent } from '../ui/ratatui/protocol.js';
5
+ import type { MuxSessionState, RustEvent } from '../ui/ratatui/protocol.js';
4
6
  import { type WorkspacePresetHost } from './workspace_presets.js';
5
7
  /** Owner entry point; process I/O remains on the canonical pane transport. */
6
- export declare function createWorkspaceLayoutController(transport: PaneCommandTransport, specs: () => PaneSessionSpec[], resume: (paneId: number) => Promise<void>, presetHost?: WorkspacePresetHost): {
8
+ export declare function createWorkspaceLayoutController(transport: PaneCommandTransport, specs: () => PaneSessionSpec[], resume: (paneId: number) => Promise<void>, presetHost?: WorkspacePresetHost, nativeOwner?: {
9
+ isRestoring?: () => boolean;
10
+ beginRestore?: () => () => void;
11
+ snapshot?: () => Promise<SessionLayoutSnapshot | undefined>;
12
+ records: () => NativeRecords;
13
+ restore: (records: NativeRecords, state?: MuxSessionState, prepared?: () => Promise<void>) => Promise<void>;
14
+ prepareRecords?: (records: NativeRecords) => Promise<{
15
+ restore: () => Promise<void>;
16
+ close: () => Promise<void>;
17
+ }>;
18
+ beforeRestore: () => void;
19
+ afterRestore?: () => void;
20
+ preservePaneIds?: (state: MuxSessionState) => number[] | Promise<number[]>;
21
+ prepareRestore?: (state: MuxSessionState) => Promise<{
22
+ state: MuxSessionState;
23
+ preservePaneIds: number[];
24
+ }>;
25
+ }, restoreSpecs?: (state: MuxSessionState) => void): {
7
26
  execute: (args: string[]) => Promise<string>;
8
27
  restoreSnapshot: (state: unknown) => Promise<Extract<RustEvent, {
9
28
  type: 'session_restored';
@@ -1,9 +1,12 @@
1
+ import { savedBrokerUrl } from '../desktop/daily/native_records.js';
1
2
  import { WorkspaceLayoutStore } from '../workspace_layout.js';
2
3
  import { linkWorkspaceAgentSessions } from '../workspace_agent.js';
3
- import { sanitizeMuxSessionState, resolveMuxPersistenceOptions, validateWorkspaceState } from '../ui/ratatui/mux_persistence.js';
4
+ import { sanitizeMuxSessionState, resolveMuxPersistenceOptions, validateWorkspaceState, MAX_WORKSPACE_PANES } from '../ui/ratatui/mux_persistence.js';
4
5
  import { openWorkspacePreset } from './workspace_presets.js';
5
6
  /** Owner entry point; process I/O remains on the canonical pane transport. */
6
- export function createWorkspaceLayoutController(transport, specs, resume, presetHost) {
7
+ export function createWorkspaceLayoutController(transport, specs, resume, presetHost, nativeOwner, restoreSpecs) {
8
+ const requireStable = () => { if (nativeOwner?.isRestoring?.())
9
+ throw new Error('A workspace restore is in progress; try again when it finishes.'); };
7
10
  const requireInactive = () => { if (!transport.hasCapability?.('inactive_workspace_restore'))
8
11
  throw new Error('Update the renderer to support inactive workspace restoration before loading this layout.'); };
9
12
  const request = (command, match) => new Promise((resolve, reject) => {
@@ -24,21 +27,68 @@ export function createWorkspaceLayoutController(transport, specs, resume, preset
24
27
  }
25
28
  });
26
29
  const snapshot = async () => {
30
+ requireStable();
27
31
  requireInactive();
32
+ if (nativeOwner?.snapshot) {
33
+ const pair = await nativeOwner.snapshot();
34
+ requireStable();
35
+ if (!pair?.muxState)
36
+ throw new Error('Workspace renderer snapshot is unavailable');
37
+ return pair.muxState;
38
+ }
28
39
  const event = await request({ type: 'get_session_state' }, e => e.type === 'session_state');
40
+ requireStable();
29
41
  if (event.type !== 'session_state')
30
42
  throw new Error('Unexpected workspace snapshot response');
31
43
  validateWorkspaceState(event.state);
32
- return sanitizeMuxSessionState(linkWorkspaceAgentSessions(event.state, specs()), resolveMuxPersistenceOptions());
44
+ const linked = linkWorkspaceAgentSessions(event.state, specs());
45
+ if (nativeOwner)
46
+ linked.native_tools = Object.fromEntries(Object.entries(nativeOwner.records()).filter(([key]) => linked.panes.some(pane => String(pane.id) === key)));
47
+ return sanitizeMuxSessionState(linked, resolveMuxPersistenceOptions());
33
48
  };
34
49
  const restoreSnapshot = async (value) => {
35
- requireInactive();
36
- validateWorkspaceState(value);
37
- const state = sanitizeMuxSessionState(linkWorkspaceAgentSessions(value, specs()), resolveMuxPersistenceOptions());
38
- const event = await request({ type: 'restore_session_state', state }, e => e.type === 'session_restored');
39
- if (event.type !== 'session_restored')
40
- throw new Error('Unexpected workspace restoration response');
41
- return event;
50
+ requireStable();
51
+ const finish = nativeOwner?.beginRestore?.();
52
+ try {
53
+ requireInactive();
54
+ validateWorkspaceState(value);
55
+ let state = sanitizeMuxSessionState(value, resolveMuxPersistenceOptions());
56
+ const plan = await nativeOwner?.prepareRestore?.(state);
57
+ if (plan) {
58
+ state = plan.state;
59
+ validateWorkspaceState(state);
60
+ }
61
+ const preserved = plan?.preservePaneIds ?? (nativeOwner?.preservePaneIds ? await nativeOwner.preservePaneIds(state) : []);
62
+ if (preserved.length && !transport.hasCapability?.('desktop_preserved_restore_v2'))
63
+ throw new Error('Update the renderer to preserve live desktop panes during restoration.');
64
+ const completedPaneIds = new Set([...state.panes.map(pane => pane.id), ...preserved].filter(id => id !== 0));
65
+ if (completedPaneIds.size > MAX_WORKSPACE_PANES)
66
+ throw new Error(`Restored workspace exceeds ${MAX_WORKSPACE_PANES} panes after restoring desktop panes`);
67
+ const { native_tools, ...rendererState } = state;
68
+ savedBrokerUrl(native_tools ?? {});
69
+ nativeOwner?.beforeRestore();
70
+ const recordPlan = await nativeOwner?.prepareRecords?.(native_tools ?? {});
71
+ try {
72
+ const event = await request({ type: 'restore_session_state', state: rendererState, ...(preserved.length ? { preserve_pane_ids: preserved } : {}) }, e => e.type === 'session_restored');
73
+ if (event.type !== 'session_restored')
74
+ throw new Error('Unexpected workspace restoration response');
75
+ restoreSpecs?.(rendererState);
76
+ if (nativeOwner)
77
+ await nativeOwner.restore(native_tools ?? {}, rendererState, recordPlan?.restore);
78
+ return event;
79
+ }
80
+ finally {
81
+ try {
82
+ await recordPlan?.close();
83
+ }
84
+ finally {
85
+ nativeOwner?.afterRestore?.();
86
+ }
87
+ }
88
+ }
89
+ finally {
90
+ finish?.();
91
+ }
42
92
  };
43
93
  return { restoreSnapshot, execute: async (args) => {
44
94
  const action = args[0];
@@ -49,6 +99,7 @@ export function createWorkspaceLayoutController(transport, specs, resume, preset
49
99
  return names.length ? names.join('\n') : 'No named workspaces saved.';
50
100
  }
51
101
  if (action === 'restore') {
102
+ requireStable();
52
103
  requireInactive();
53
104
  if (!name)
54
105
  throw new Error('Workspace restore requires a name');
@@ -1,3 +1,4 @@
1
+ import { nativeStatusLines } from '../desktop/daily/native_status.js';
1
2
  import { emitKeypressEvents } from 'node:readline';
2
3
  import { formatAskUserResponse } from './ask_user_response.js';
3
4
  import { sanitizeTerminalText } from '../ui/core/text_width.js';
@@ -26,6 +27,8 @@ const headers = { ...credential, 'x-ztc-workspace-owner': ownerId };
26
27
  let snapshot = null;
27
28
  let selected = 0;
28
29
  let scroll = 0;
30
+ let nativeFirst = 0;
31
+ let expandedPane = null;
29
32
  let activeDecision = null;
30
33
  let message = 'Loading runtime observations…';
31
34
  let fetching = false;
@@ -87,22 +90,31 @@ function render() {
87
90
  `Tokens: ${pane.usage.total_tokens ?? 'unknown'}${pane.usage.total_tokens === null ? '' : ' (observed minimum)'}; est ${pane.usage.estimated_tokens ?? 'unknown'}`,
88
91
  ]);
89
92
  const count = Math.max(1, rows - 4);
90
- scroll = Math.max(0, Math.min(scroll, Math.max(0, digest.length - count)));
91
- lines = ['Status · runtime observations', ...digest.slice(scroll, scroll + count)];
93
+ const childCount = snapshot?.children?.length ?? 0;
94
+ selected = Math.max(0, Math.min(selected, childCount - 1));
95
+ const native = snapshot?.children !== undefined ? nativeStatusLines(snapshot, selected) : null;
96
+ const nativeRows = Math.min(childCount, digest.length ? Math.max(1, Math.floor(count / 2)) : count);
97
+ nativeFirst = Math.max(0, selected - nativeRows + 1);
98
+ const workerRows = Math.max(1, count - nativeRows);
99
+ scroll = Math.max(0, Math.min(scroll, Math.max(0, digest.length - workerRows)));
100
+ lines = [native?.[0] ?? 'Status · runtime observations',
101
+ ...(native?.slice(1 + nativeFirst, 1 + nativeFirst + nativeRows) ?? []), ...digest.slice(scroll, scroll + workerRows)];
92
102
  if (snapshot && !panes.length)
93
103
  lines.push('No agent workers observed.');
94
104
  if (snapshot?.omitted_panes)
95
105
  lines.push(`${snapshot.omitted_panes} panes omitted.`);
96
- lines.push('', message || `Updated ${snapshot?.observed_at ?? 'unknown'}`, 'r refresh · ↑/↓ scroll');
106
+ lines.push('', message || `Updated ${snapshot?.observed_at ?? 'unknown'}`, childCount
107
+ ? '↑/↓ select · Enter expand · Esc/Backspace collapse · PgUp/PgDn workers · r refresh'
108
+ : 'r refresh · ↑/↓ scroll');
97
109
  }
98
110
  process.stdout.write(`\x1b[H\x1b[2J${lines.slice(0, rows).map(line => clean(line).slice(0, cols - 1)).join('\n')}`);
99
111
  }
100
- async function refresh() {
112
+ async function refresh(onDemand = false) {
101
113
  if (fetching || stopped)
102
114
  return;
103
115
  fetching = true;
104
116
  try {
105
- const value = await request('/workspace/runtime');
117
+ const value = await request(onDemand ? '/workspace/runtime?refresh=1' : '/workspace/runtime');
106
118
  if (value === null || typeof value !== 'object' || !('schema_version' in value) || value.schema_version !== 1
107
119
  || !('owner_id' in value) || value.owner_id !== ownerId || !('panes' in value) || !Array.isArray(value.panes)
108
120
  || !('decisions' in value) || !Array.isArray(value.decisions))
@@ -183,7 +195,7 @@ function input(value, key) {
183
195
  return;
184
196
  }
185
197
  if (value === 'r') {
186
- void refresh();
198
+ void refresh(true);
187
199
  return;
188
200
  }
189
201
  if (mode === 'decisions') {
@@ -196,6 +208,24 @@ function input(value, key) {
196
208
  return;
197
209
  }
198
210
  }
211
+ else if (snapshot?.children?.length) {
212
+ if (event.upArrow || value === 'k')
213
+ selected--;
214
+ else if (event.downArrow || value === 'j')
215
+ selected++;
216
+ else if (event.pageUp)
217
+ scroll--;
218
+ else if (event.pageDown)
219
+ scroll++;
220
+ else if (event.return) {
221
+ void paneAction('zoom');
222
+ return;
223
+ }
224
+ else if (event.escape || event.backspace) {
225
+ void paneAction('collapse');
226
+ return;
227
+ }
228
+ }
199
229
  else {
200
230
  if (event.upArrow || value === 'k')
201
231
  scroll--;
@@ -204,6 +234,31 @@ function input(value, key) {
204
234
  }
205
235
  render();
206
236
  }
237
+ async function paneAction(action) {
238
+ const paneId = action === 'collapse' ? expandedPane : snapshot?.children?.[selected]?.paneId;
239
+ if (!Number.isSafeInteger(paneId))
240
+ return;
241
+ try {
242
+ await request('/workspace/pane-action', { action, pane_id: paneId });
243
+ expandedPane = action === 'zoom' ? paneId : null;
244
+ }
245
+ catch {
246
+ message = 'Native pane action unavailable';
247
+ render();
248
+ }
249
+ }
250
+ function mouse(bytes) {
251
+ if (mode !== 'status' || !snapshot?.children)
252
+ return;
253
+ const hit = /\x1b\[<0;\d+;(\d+)M/.exec(bytes.toString());
254
+ if (!hit)
255
+ return;
256
+ const index = Number(hit[1]) - 2 + nativeFirst;
257
+ if (index >= 0 && index < snapshot.children.length) {
258
+ selected = index;
259
+ void paneAction('zoom');
260
+ }
261
+ }
207
262
  const interval = setInterval(() => { void refresh(); }, mode === 'decisions' ? 1000 : refreshMs);
208
263
  function stop() {
209
264
  if (stopped)
@@ -211,10 +266,11 @@ function stop() {
211
266
  stopped = true;
212
267
  clearInterval(interval);
213
268
  process.stdin.off('keypress', input);
269
+ process.stdin.off('data', mouse);
214
270
  process.stdout.off('resize', render);
215
271
  if (process.stdin.isTTY)
216
272
  process.stdin.setRawMode(false);
217
- process.stdout.write('\x1b[?25h\x1b[?1049l');
273
+ process.stdout.write('\x1b[?1000l\x1b[?1006l\x1b[?25h\x1b[?1049l');
218
274
  process.stdin.pause();
219
275
  }
220
276
  process.once('SIGTERM', stop);
@@ -223,6 +279,10 @@ emitKeypressEvents(process.stdin);
223
279
  if (process.stdin.isTTY)
224
280
  process.stdin.setRawMode(true);
225
281
  process.stdin.on('keypress', input);
282
+ if (mode === 'status') {
283
+ process.stdin.on('data', mouse);
284
+ process.stdout.write('\x1b[?1000h\x1b[?1006h');
285
+ }
226
286
  process.stdout.on('resize', render);
227
287
  process.stdin.resume();
228
288
  process.stdout.write('\x1b[?1049h\x1b[?25l');
@@ -24,6 +24,7 @@ export interface WorkspacePreset {
24
24
  };
25
25
  }
26
26
  export declare function loadWorkspacePreset(cwd: string, name: string): WorkspacePreset;
27
+ export declare const workspaceMonitorEntry: string;
27
28
  export declare function buildWorkspaceMonitorLaunch(mode: 'decisions' | 'status', host: WorkspacePresetHost, preset: WorkspacePreset): ProcessPaneLaunchSpec;
28
29
  /** Creates only new panes; authored processes in an earlier window remain running. */
29
30
  export declare function openWorkspacePreset(transport: PaneCommandTransport, host: WorkspacePresetHost, args: string[]): Promise<string>;
@@ -72,11 +72,11 @@ export function loadWorkspacePreset(cwd, name) {
72
72
  throw new Error(`${filename ? `${filename}: ` : ''}${error instanceof Error ? error.message : String(error)}`);
73
73
  }
74
74
  }
75
+ export const workspaceMonitorEntry = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? './workspace_monitor.ts' : './workspace_monitor.js', import.meta.url));
75
76
  export function buildWorkspaceMonitorLaunch(mode, host, preset) {
76
- const entry = fileURLToPath(new URL(import.meta.url.endsWith('.ts') ? './workspace_monitor.ts' : './workspace_monitor.js', import.meta.url));
77
77
  const loader = import.meta.url.endsWith('.ts') ? ['--import', import.meta.resolve('tsx')] : [];
78
78
  return { kind: 'process', command: process.execPath,
79
- args: [...loader, entry, mode, String(host.mirrorPort), host.workspaceOwnerId, String(preset.refresh_ms)],
79
+ args: [...loader, workspaceMonitorEntry, mode, String(host.mirrorPort), host.workspaceOwnerId, String(preset.refresh_ms)],
80
80
  cwd: host.cwd, title: preset.titles[mode], paneType: 'process' };
81
81
  }
82
82
  const leaves = (node) => node.type === 'leaf' ? [node.pane_id]
package/dist/cli.js CHANGED
@@ -11,7 +11,7 @@ import { getVersion } from './utils/version.js';
11
11
  // --- CLI Entry Point ---
12
12
  // Parse command line args
13
13
  const args = process.argv.slice(2);
14
- if (args.includes('--help') || args.includes('-h')) {
14
+ if (!args.includes('--headless') && (args.includes('--help') || args.includes('-h'))) {
15
15
  const version = getVersion();
16
16
  console.log(`
17
17
  ZTC - Zerg Terminal Client v${version}
@@ -51,7 +51,7 @@ if (args.includes('--version') || args.includes('-v')) {
51
51
  process.exit(0);
52
52
  }
53
53
  const cwdIndex = args.lastIndexOf('--cwd');
54
- if (cwdIndex >= 0) {
54
+ if (cwdIndex >= 0 && !args.includes('--headless')) {
55
55
  const target = args[cwdIndex + 1];
56
56
  if (!target) {
57
57
  console.error('Error: --cwd requires a path');
@@ -71,6 +71,10 @@ if (cwdIndex >= 0) {
71
71
  }
72
72
  }
73
73
  async function main() {
74
+ if (args.includes('--headless')) {
75
+ await import('./cli_main.js');
76
+ return;
77
+ }
74
78
  await configStore.load(true);
75
79
  const isTty = Boolean(process.stdout.isTTY);
76
80
  const useAltScreen = isTty
package/dist/cli_args.js CHANGED
@@ -3,6 +3,7 @@ const BOOLEAN_FLAGS = new Set([
3
3
  '--detach-environment', '--no-pin-task-header', '--help', '-h', '--version', '-v', '--list-sessions', '--plan', '--desktop', '--mux', '--no-mux', '--new-window', '--fullscreen', '--pane', '--human-sim-pane', '--zlicky', '--computer-use', '--ml', '--sfx-list', '--voyager-loop', '--mirror', '--open-mirror', '--mirror-open', '--no-browser-open', '--navigator-hidden', '--headless-mirror', '--headless-mirror-open', '--headless-interactive', '--headless', '--json', '--json-stream', '--quiet', '-q', '--timestamps', '--verbose', '--colony',
4
4
  ]);
5
5
  const REQUIRED_VALUE_FLAGS = new Set([
6
+ '--approval-url',
6
7
  '--layout', '--layout-refresh-ms', '--layout-workers',
7
8
  '--cwd', '--name', '--session-id', '--session-file', '--mode', '--agent-domain', '--domain-paths', '--embedded', '--embedded-rom', '--embedded-workflow', '--embedded-runtime-tick-ms', '--embedded-runtime-frame-budget', '--bench', '--bench-workflow', '--num-zergs', '--provider', '--model', '--auth-mode', '--router-url', '--profile', '--effort', '--thinking', '--emulation', '--prompt', '--max-iterations', '--timeout', '--output', '--output-schema', '--trajectory-jsonl', '--voyager-task', '--voyager-max-rounds', '--mirror-port', '--navigator-group', '--connect-zerg',
8
9
  ]);