@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
@@ -348,13 +348,14 @@ export class RequestEncoder {
348
348
  };
349
349
  }
350
350
  let content = result.content;
351
- // Truncate old (non-current-turn) tool results to prevent context bloat.
352
- // Current-turn results stay full so the model can act on them.
351
+ // Preserve frozen cache bytes first, then the aggregate selector's explicit
352
+ // verdict. Only unselected historical fallback content needs another cap.
353
353
  const frozen = this.deps.frozenResultContent?.(result.tool_use_id);
354
354
  if (frozen !== undefined) {
355
355
  content = frozen;
356
356
  }
357
- else if (!this.deps.currentTurnToolIds.has(result.tool_use_id) && content.length > STABLE_RESULT_LIMIT) {
357
+ else if (!this.deps.currentTurnToolIds.has(result.tool_use_id)
358
+ && !this.deps.selectorVerdict?.has(result.tool_use_id) && content.length > STABLE_RESULT_LIMIT) {
358
359
  const copy = this.deps.saveFullResult?.(result.tool_use_id, result.source ?? content) ?? null;
359
360
  content = content.slice(0, OLD_RESULT_CAP)
360
361
  + `\n[truncated — ${content.length} chars total${copy ? `; ${resultCopyNote(result.tool_use_id, copy)}; ${COPY_ADVICE}` : ''}]`;
@@ -29,3 +29,4 @@ export declare class CapabilityPolicy implements Policy {
29
29
  private evaluateShellPolicy;
30
30
  private evaluateNetworkPolicy;
31
31
  }
32
+ export declare function canonicalPolicyPath(path: string, cwd: string): string;
@@ -1,6 +1,7 @@
1
+ import { realpathSync } from 'node:fs';
1
2
  import { ToolCapability } from './capabilities.js';
2
3
  import { homedir } from 'os';
3
- import { resolve, isAbsolute, sep } from 'path';
4
+ import { resolve, isAbsolute, sep, dirname, basename } from 'path';
4
5
  import { parseCheckedCommandPlan } from './checked_commands.js';
5
6
  import { formatCheckedStageCommand } from '../../utils/checked_shell.js';
6
7
  export class AllowAllPolicy {
@@ -63,7 +64,10 @@ export class CapabilityPolicy {
63
64
  const allowedRoots = (this.profile.allowedPaths || []).map(path => normalizeRoot(path, this.cwd));
64
65
  for (const path of paths) {
65
66
  const absolutePath = normalizeRoot(path, this.cwd);
66
- if (deniedRoots.some(root => isWithinRoot(absolutePath, root))) {
67
+ const allowed = allowedRoots.filter(root => isWithinRoot(absolutePath, root));
68
+ const denied = deniedRoots.filter(root => isWithinRoot(absolutePath, root));
69
+ const exception = this.profile.pathPrecedence === 'specific' && allowed.some(root => denied.every(blocked => root.length > blocked.length));
70
+ if (denied.length > 0 && !exception) {
67
71
  return {
68
72
  allowed: false,
69
73
  reason: `Permission denied: path is blocked by profile (${path})`,
@@ -158,7 +162,7 @@ function extractPathArgs(args, executionCwd) {
158
162
  }
159
163
  function normalizeRoot(path, cwd) {
160
164
  const expanded = path === '~' ? homedir() : path.replace(/^~(?=\/|$)/, homedir());
161
- return resolve(isAbsolute(expanded) ? expanded : resolve(cwd, expanded));
165
+ return canonicalPolicyPath(resolve(isAbsolute(expanded) ? expanded : resolve(cwd, expanded)), cwd);
162
166
  }
163
167
  function isWithinRoot(path, root) {
164
168
  return path === root || path.startsWith(root.endsWith(sep) ? root : `${root}${sep}`);
@@ -205,3 +209,19 @@ function hostMatchesPattern(host, pattern) {
205
209
  }
206
210
  return normalizedHost === normalizedPattern;
207
211
  }
212
+ export function canonicalPolicyPath(path, cwd) {
213
+ const expanded = path === '~' ? homedir() : path.replace(/^~(?=\/|$)/, homedir());
214
+ const absolute = resolve(cwd, expanded);
215
+ try {
216
+ return realpathSync(absolute);
217
+ }
218
+ catch (error) {
219
+ const code = error.code;
220
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
221
+ throw error;
222
+ const parent = dirname(absolute);
223
+ if (parent === absolute)
224
+ return absolute;
225
+ return resolve(canonicalPolicyPath(parent, cwd), basename(absolute));
226
+ }
227
+ }
@@ -161,9 +161,10 @@ async function recordToolTrace(entry) {
161
161
  }
162
162
  export async function executeToolWithRuntime(name, args, options) {
163
163
  const tool = getTool(name, options.tools);
164
+ const sourceTool = tool?.outputSource ?? tool;
164
165
  const traceStartedAt = Date.now();
165
166
  const ordinaryCapabilities = getRuntimeCapabilities(tool);
166
- const requiredCapabilities = (input) => (tool === runCommandTool && Object.hasOwn(input, 'verification')
167
+ const requiredCapabilities = (input) => (sourceTool === runCommandTool && Object.hasOwn(input, 'verification')
167
168
  ? [...new Set([...ordinaryCapabilities, ToolCapability.FILE_READ])]
168
169
  : ordinaryCapabilities);
169
170
  let capabilities = requiredCapabilities(args);
@@ -178,7 +179,7 @@ export async function executeToolWithRuntime(name, args, options) {
178
179
  // precede hooks/approval: neither a model, plugin name nor permission update
179
180
  // can turn a generic command into the verified remote broker.
180
181
  if (options.remoteResourceSession && (!tool || (!isManagedRemoteResourceTool(tool, options.remoteResourceSession)
181
- && tool !== askUserTool && tool !== recallToolResponseTool && tool !== sessionEvidenceTool))) {
182
+ && sourceTool !== askUserTool && sourceTool !== recallToolResponseTool && sourceTool !== sessionEvidenceTool))) {
182
183
  return {
183
184
  content: 'Guarded remote session: use the host-managed remote_resource tool under a required lease. Unrestricted shell, network and plugin execution is blocked.',
184
185
  isError: true, effectiveArgs,
@@ -337,9 +338,9 @@ export async function executeToolWithRuntime(name, args, options) {
337
338
  }
338
339
  }
339
340
  const verificationAdmission = () => {
340
- const adapter = tool === verifyArtifactTool || tool === benchmarkCPUTool;
341
- const measured = tool === benchmarkCPUTool;
342
- if (!adapter && (tool !== runCommandTool || !Object.hasOwn(effectiveArgs, 'verification')))
341
+ const adapter = sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool;
342
+ const measured = sourceTool === benchmarkCPUTool;
343
+ if (!adapter && (sourceTool !== runCommandTool || !Object.hasOwn(effectiveArgs, 'verification')))
343
344
  return undefined;
344
345
  if (!options.context)
345
346
  return {
@@ -453,23 +454,23 @@ export async function executeToolWithRuntime(name, args, options) {
453
454
  if (dispatchAdmission)
454
455
  return dispatchAdmission;
455
456
  const toolContext = options.context ? { ...options.context,
456
- onOutput: tool === runCommandTool || tool?.outputSource === runCommandTool
457
+ onOutput: sourceTool === runCommandTool || tool?.outputSource === runCommandTool
457
458
  ? options.context.onOutput : undefined,
458
- canInspectVerificationSource: tool === runCommandTool || tool === readCommandTool || tool === stopCommandTool || tool === verifyArtifactTool || tool === benchmarkCPUTool
459
+ canInspectVerificationSource: sourceTool === runCommandTool || sourceTool === readCommandTool || sourceTool === stopCommandTool || sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool
459
460
  ? canInspectVerificationSource : undefined,
460
- managedCommandWaitSliceMs: tool === readCommandTool || tool === runCommandTool
461
+ managedCommandWaitSliceMs: sourceTool === readCommandTool || sourceTool === runCommandTool
461
462
  ? options.context.managedCommandWaitSliceMs : undefined,
462
- onManagedCommand: tool === readCommandTool || tool === runCommandTool
463
+ onManagedCommand: sourceTool === readCommandTool || sourceTool === runCommandTool
463
464
  ? (observation) => { managedCommand = observation; }
464
465
  : undefined,
465
- onVerificationReceipt: tool === runCommandTool || tool === stopCommandTool || tool === benchmarkCPUTool
466
+ onVerificationReceipt: sourceTool === runCommandTool || sourceTool === stopCommandTool || sourceTool === benchmarkCPUTool
466
467
  ? (receipt) => { verificationReceipt = structuredClone(receipt); }
467
468
  : undefined,
468
- onHostVerifier: tool === verifyArtifactTool || tool === benchmarkCPUTool ? (receipt, decision) => {
469
+ onHostVerifier: sourceTool === verifyArtifactTool || sourceTool === benchmarkCPUTool ? (receipt, decision) => {
469
470
  verificationReceipt = structuredClone(receipt);
470
471
  verifierDecision = structuredClone(decision);
471
472
  } : undefined,
472
- onHostBenchmarkComparison: tool === compareBenchmarksTool ? (decision) => {
473
+ onHostBenchmarkComparison: sourceTool === compareBenchmarksTool ? (decision) => {
473
474
  benchmarkComparisonDecision = structuredClone(decision);
474
475
  } : undefined,
475
476
  } : undefined;
@@ -14,6 +14,7 @@ import { randomUUID } from 'node:crypto';
14
14
  import { realpathSync } from 'node:fs';
15
15
  import { getSessionPathForCwd, saveSessionToFile } from '../session.js';
16
16
  import { getDefaultModel } from '../utils/models.js';
17
+ import { requiredRouterModel } from '../config/router_required.js';
17
18
  import { debugLog } from '../utils/debug_log.js';
18
19
  import { createBackendForProvider } from './backends/index.js';
19
20
  import { accountBackendOptions } from './backends/account_pool.js';
@@ -132,7 +133,7 @@ async function generateWorkerResponse(backend, request) {
132
133
  }
133
134
  function getSubAgentModel(provider, preferredModel) {
134
135
  if (process.env.ZTC_ROUTER_REQUIRED === '1') {
135
- return configStore.resolveLLMBackendConfig({ provider, model: preferredModel ?? 'gpt-6.1-sol' }).model;
136
+ return configStore.resolveLLMBackendConfig({ provider, model: preferredModel ?? requiredRouterModel().model }).model;
136
137
  }
137
138
  if (preferredModel)
138
139
  return preferredModel;
@@ -30,7 +30,7 @@ export interface AskUserData {
30
30
  /**
31
31
  * Callback: present questions to user. Returns null on success, or an error string.
32
32
  */
33
- declare let askUserCallback: ((questions: AskUserQuestion[]) => string | null) | null;
33
+ declare let askUserCallback: ((questions: AskUserQuestion[]) => string | null | Promise<string | null>) | null;
34
34
  export declare function setAskUserCallback(cb: typeof askUserCallback): void;
35
35
  export declare function clearAskUserCallback(): void;
36
36
  /** Reset the per-turn dedup flag. Call at the start of each agent turn. */
@@ -180,13 +180,14 @@ Example: [{"question": "Which framework?", "options": [{"label": "React", "descr
180
180
  required: [],
181
181
  },
182
182
  },
183
- execute: async (args) => {
183
+ execute: async (args, context) => {
184
+ const callback = context?.askUser ?? askUserCallback;
184
185
  const question = args.question ? String(args.question) : '';
185
186
  const optionsJson = args.options_json ? String(args.options_json) : '';
186
187
  const questionsJson = args.questions_json ? String(args.questions_json) : '';
187
188
  const allowOther = args.allow_other !== undefined ? Boolean(args.allow_other) : true;
188
189
  debugLog('execute called:', { hasQuestion: !!question, hasOptionsJson: !!optionsJson, hasQuestionsJson: !!questionsJson, alreadyCalled: askUserCalledThisTurn });
189
- if (!askUserCallback) {
190
+ if (!callback) {
190
191
  debugLog('ERROR: no callback registered');
191
192
  return 'Error: ask_user is not available in this context. Use an interactive ZTC session with question input enabled.';
192
193
  }
@@ -246,11 +247,14 @@ Example: [{"question": "Which framework?", "options": [{"label": "React", "descr
246
247
  }
247
248
  questions.push({ question: q.question, options: opts, allow_other: allowOther });
248
249
  }
249
- const error = askUserCallback(questions);
250
+ const error = await callback(questions);
251
+ if (typeof error === 'object' && error !== null)
252
+ return error.answer;
250
253
  if (error !== null)
251
254
  return registrationFailure(error);
252
- const wasDuplicate = askUserCalledThisTurn;
253
- askUserCalledThisTurn = true;
255
+ const wasDuplicate = !context?.askUser && askUserCalledThisTurn;
256
+ if (!context?.askUser)
257
+ askUserCalledThisTurn = true;
254
258
  if (wasDuplicate) {
255
259
  return 'Question merged with previous ask_user call in this turn. All questions will be shown together. Do NOT call ask_user again.';
256
260
  }
@@ -271,11 +275,14 @@ Example: [{"question": "Which framework?", "options": [{"label": "React", "descr
271
275
  if (typeof parsed === 'string') {
272
276
  return `Error: ${parsed}`;
273
277
  }
274
- const error = askUserCallback([{ question, options: parsed, allow_other: allowOther }]);
278
+ const error = await callback([{ question, options: parsed, allow_other: allowOther }]);
279
+ if (typeof error === 'object' && error !== null)
280
+ return error.answer;
275
281
  if (error !== null)
276
282
  return registrationFailure(error);
277
- const wasDuplicate = askUserCalledThisTurn;
278
- askUserCalledThisTurn = true;
283
+ const wasDuplicate = !context?.askUser && askUserCalledThisTurn;
284
+ if (!context?.askUser)
285
+ askUserCalledThisTurn = true;
279
286
  if (wasDuplicate) {
280
287
  return 'Question merged with previous ask_user call in this turn. All questions will be shown together. Do NOT call ask_user again.';
281
288
  }
@@ -39,6 +39,12 @@ export declare function getPaneToolsTransport(): PaneCommandTransport | null;
39
39
  /** The renderer's current pane list, through the given transport (default: the pane tools'). */
40
40
  export declare function listWorkspacePanes(transport?: PaneCommandTransport | null, timeoutMs?: number): Promise<PaneInfo[] | Error>;
41
41
  export declare function resolvePaneIdByName(name: string): Promise<number | Error>;
42
+ /**
43
+ * Whether EVENT is a refusal of the pane mutation sent under REQUEST_ID: one the renderer names for that request, or
44
+ * one that names none, as a renderer before request-scoped refusals sent them. A refusal named for another request is
45
+ * another pane's: the pane transport queues pane mutations and names each refusal's request.
46
+ */
47
+ export declare function isPaneRefusalFor(event: RustEvent, requestId: string | undefined): boolean;
42
48
  export declare function waitForPaneCreatedOrError(tui: PaneCommandTransport, expected: {
43
49
  paneType?: string;
44
50
  title?: string;
@@ -314,8 +314,16 @@ export async function resolvePaneIdByName(name) {
314
314
  const names = others.map((pane) => `[${pane.id}] ${pane.title}`).join(', ');
315
315
  return new Error(`Error: no pane is named "${name}". ${names ? `Panes: ${names}.` : 'There are no other panes.'}`);
316
316
  }
317
+ /**
318
+ * Whether EVENT is a refusal of the pane mutation sent under REQUEST_ID: one the renderer names for that request, or
319
+ * one that names none, as a renderer before request-scoped refusals sent them. A refusal named for another request is
320
+ * another pane's: the pane transport queues pane mutations and names each refusal's request.
321
+ */
322
+ export function isPaneRefusalFor(event, requestId) {
323
+ return event.type === 'error' && (requestId === undefined || event.request_id === undefined || event.request_id === requestId);
324
+ }
317
325
  export function waitForPaneCreatedOrError(tui, expected, timeoutMs = 15000) {
318
- return waitForEvent(tui, (event) => event.type === 'error' || (event.type === 'pane_created'
326
+ return waitForEvent(tui, (event) => isPaneRefusalFor(event, expected.requestId) || (event.type === 'pane_created'
319
327
  && (!expected.requestId || event.request_id === expected.requestId)
320
328
  && (!expected.paneType || event.pane_type === expected.paneType)
321
329
  && (!expected.title || event.title === expected.title)), timeoutMs);
@@ -631,11 +639,14 @@ Returns the pane ID which you can use with read_terminal_pane, write_terminal_pa
631
639
  const paneType = childSessionId
632
640
  ? 'ztc'
633
641
  : (isShellLikeCommand(commandToRun) ? 'process' : 'command');
634
- // Send create_pane command and wait for pane_created or error event
642
+ // Send create_pane under a request id of its own, and wait for the pane or refusal named for it: the pane
643
+ // transport queues pane mutations and names the request each refusal is for (see isPaneRefusalFor).
635
644
  const expectedTitle = titleToUse || commandToRun.split(/[\\/]/).pop() || commandToRun;
636
- const eventPromise = waitForPaneCreatedOrError(tui, { paneType, title: expectedTitle }, 15000);
645
+ const requestId = `pane-create-${generateSessionId()}`;
646
+ const eventPromise = waitForPaneCreatedOrError(tui, { paneType, title: expectedTitle, requestId }, 15000);
637
647
  const sent = tui.send({
638
648
  type: 'create_pane',
649
+ request_id: requestId,
639
650
  command: commandToRun,
640
651
  args: allArgs,
641
652
  cwd,
@@ -1439,9 +1450,12 @@ export const openEditorPaneTool = {
1439
1450
  const title = args.title
1440
1451
  ? String(args.title)
1441
1452
  : shortTitle(editorName, basename(path) || path);
1442
- const eventPromise = waitForPaneCreatedOrError(tui, { paneType: 'command', title }, 15000);
1453
+ // A request id of its own, so a refusal named for another pane mutation is not taken as this one's.
1454
+ const requestId = `pane-create-${generateSessionId()}`;
1455
+ const eventPromise = waitForPaneCreatedOrError(tui, { paneType: 'command', title, requestId }, 15000);
1443
1456
  const sent = tui.send({
1444
1457
  type: 'create_pane',
1458
+ request_id: requestId,
1445
1459
  command: editor,
1446
1460
  args: paneArgs,
1447
1461
  cwd,
@@ -183,7 +183,7 @@ export const searchTool = {
183
183
  // -H forces the filename even for a single-file search; -l lists files
184
184
  // only, matching the files-mode contract. -E reads the pattern as an
185
185
  // extended regex, the grep syntax closest to ripgrep's (| + ? {n}).
186
- const grepArgs = outputMode === 'files' ? ['-R', '-E', '-l', '-H'] : ['-R', '-E', '-n', '-H'];
186
+ const grepArgs = outputMode === 'files' ? ['-r', '-E', '-l', '-H'] : ['-r', '-E', '-n', '-H'];
187
187
  if (!inRepo) {
188
188
  for (const ex of HOME_EXCLUDES) {
189
189
  grepArgs.push(`--exclude-dir=${ex}`);
@@ -83,3 +83,7 @@ export declare function buildAgentToolsFromDomain(domainName: string): Tool[];
83
83
  * points where you can `await`; fall back to the sync variant in hot paths.
84
84
  */
85
85
  export declare function buildAgentToolsFromDomainAsync(domainName: string): Promise<Tool[]>;
86
+ export declare function buildAgentToolsFromDataDomain(path: string, handlers: Readonly<Record<string, Tool>>): {
87
+ tools: Tool[];
88
+ systemPrompt: string;
89
+ };
@@ -18,6 +18,7 @@ import { join } from 'node:path';
18
18
  import { pathToFileURL } from 'node:url';
19
19
  import { createRequire } from 'node:module';
20
20
  import { runtimeDiagOnce } from '../../utils/debug_log.js';
21
+ import { ToolCapability } from '../runtime/capabilities.js';
21
22
  import { createWordDocumentTool, createSpreadsheetTool, createPresentationTool, updateDocumentTool, readDocumentTool, listDocumentsTool, commentOnDocumentTool, } from './sim_document.js';
22
23
  import { DomainFactory } from '../../simulation/domains/loader.js';
23
24
  const AGENT_HANDLERS = new Map([
@@ -206,15 +207,40 @@ export async function buildAgentToolsFromDomainAsync(domainName) {
206
207
  }
207
208
  return buildToolsFromPreset(preset.rawToolDefs);
208
209
  }
209
- function buildToolsFromPreset(rawToolDefs) {
210
+ export function buildAgentToolsFromDataDomain(path, handlers) {
211
+ const preset = DomainFactory.loadData(path);
212
+ const tools = preset.rawToolDefs.map(def => {
213
+ const builtin = Object.hasOwn(handlers, def.handler) ? handlers[def.handler] : undefined;
214
+ if (!builtin)
215
+ throw new Error(`Unknown built-in domain handler: ${def.handler}`);
216
+ if (def.name !== builtin.definition.name)
217
+ throw new Error(`Owner domain cannot rename built-in tool: ${def.name}`);
218
+ const [declared] = buildToolsFromPreset([{ ...def, effect: builtin.effect, capabilities: builtin.capabilities }], new Map([[def.handler, builtin.execute]]));
219
+ return { ...builtin, outputSource: builtin.outputSource ?? builtin, definition: declared.definition };
220
+ });
221
+ const events = Object.keys(preset.eventArtifactMap).length ? `Event artifacts:\n${JSON.stringify(preset.eventArtifactMap)}` : '';
222
+ return { tools, systemPrompt: [preset.systemPrompt, events].filter(Boolean).join('\n\n') };
223
+ }
224
+ function buildToolsFromPreset(rawToolDefs, handlers = AGENT_HANDLERS) {
210
225
  if (!rawToolDefs?.length)
211
226
  return [];
212
227
  const tools = [];
213
228
  for (const def of rawToolDefs) {
214
- const handlerFn = AGENT_HANDLERS.get(def.handler);
229
+ const handlerFn = handlers.get(def.handler);
215
230
  if (!handlerFn)
216
231
  continue;
232
+ const capabilities = def.capabilities?.map(capability => {
233
+ if (!Object.values(ToolCapability).includes(capability)) {
234
+ throw new Error(`Unknown capability for ${def.name}: ${capability}`);
235
+ }
236
+ return capability;
237
+ });
238
+ if (def.effect !== undefined && !['read', 'write', 'external'].includes(def.effect)) {
239
+ throw new Error(`Unknown effect for ${def.name}: ${def.effect}`);
240
+ }
217
241
  tools.push({
242
+ effect: def.effect,
243
+ capabilities,
218
244
  definition: {
219
245
  name: def.name,
220
246
  description: def.description,
@@ -8,6 +8,9 @@ import type { CommandVerificationReceipt, SourceSnapshot } from '../runtime/sour
8
8
  import type { HostVerifierDecision } from '../runtime/verifier_contract.js';
9
9
  import type { BenchmarkComparisonDecision } from '../runtime/benchmark_comparison.js';
10
10
  export interface ToolContext {
11
+ askUser?: (questions: import('./ask_user.js').AskUserQuestion[]) => Promise<string | null | {
12
+ answer: string;
13
+ }>;
11
14
  /** Host-owned command launch policy; never accepted from tool arguments. */
12
15
  commandPolicy?: import('../../utils/sandbox.js').SandboxCommandOptions;
13
16
  cwd: string;
@@ -0,0 +1,14 @@
1
+ import type { Message, MessageInput, PromptTurnReceipt } from '../types.js';
2
+ import type { PromptTurnMetadata } from '../types.js';
3
+ export declare const MAX_CORRELATED_TURNS = 128;
4
+ /** Canonical session data, independent of transport and removed prompt bodies. */
5
+ export declare function mergeCorrelatedTurns(...histories: readonly PromptTurnMetadata[][]): PromptTurnMetadata[];
6
+ export declare function captureCorrelatedTurns(messages: readonly Message[], retained?: PromptTurnMetadata[]): PromptTurnMetadata[];
7
+ /** Stable caller keys are data, not command lines or provider context. */
8
+ export declare function validTurnCorrelation(value: unknown): value is string;
9
+ export declare function correlatedInputDigest(input: MessageInput): string;
10
+ /** Project only canonical authored Messages, excluding transcript and provider errors. */
11
+ export declare function projectCorrelatedTurns(messages: readonly Message[], sessionId: string, retained?: PromptTurnMetadata[]): PromptTurnReceipt[];
12
+ /** A restored unfinished turn is uncertain; never dispatch it or claim completion. */
13
+ export declare function restoreCorrelatedTurns(messages: readonly Message[]): Message[];
14
+ export declare function restoreCorrelatedTurnHistory(turns: PromptTurnMetadata[]): PromptTurnMetadata[];
@@ -0,0 +1,78 @@
1
+ import { createHash } from 'node:crypto';
2
+ export const MAX_CORRELATED_TURNS = 128;
3
+ const states = new Set(['admitted', 'running', 'completed', 'failed', 'interrupted']);
4
+ const terminalStates = new Set(['completed', 'failed', 'interrupted']);
5
+ /** Canonical session data, independent of transport and removed prompt bodies. */
6
+ export function mergeCorrelatedTurns(...histories) {
7
+ const byId = new Map();
8
+ const correlations = new Map();
9
+ for (const history of histories)
10
+ for (const value of history) {
11
+ if (!value || typeof value.id !== 'string' || value.id.length === 0 || value.id.length > 256
12
+ || !validTurnCorrelation(value.correlationId) || !/^[a-f0-9]{64}$/.test(value.inputSha256 ?? '')
13
+ || !states.has(value.state ?? '') || !Number.isSafeInteger(value.revision) || value.revision < 1
14
+ || !Number.isFinite(value.startedAt) || !Number.isFinite(value.tokens) || value.tokens < 0
15
+ || typeof value.estimated !== 'boolean' || (value.finishedAt !== undefined && !Number.isFinite(value.finishedAt))
16
+ || (value.failureCode !== undefined && value.failureCode !== 'agent_run_failed')
17
+ || (value.state === 'failed' && value.failureCode !== 'agent_run_failed')) {
18
+ throw new Error('Invalid canonical prompt turn metadata');
19
+ }
20
+ const sameCorrelation = correlations.get(value.correlationId);
21
+ const previous = byId.get(value.id);
22
+ if ((sameCorrelation !== undefined && sameCorrelation !== value.id) || (previous
23
+ && (previous.correlationId !== value.correlationId || previous.inputSha256 !== value.inputSha256
24
+ || previous.startedAt !== value.startedAt || (previous.revision === value.revision && previous.state !== value.state)))) {
25
+ throw new Error('Conflicting canonical prompt turn identity');
26
+ }
27
+ if (previous && previous.revision !== value.revision) {
28
+ const earlier = previous.revision < value.revision ? previous : value;
29
+ const later = earlier === previous ? value : previous;
30
+ if (terminalStates.has(earlier.state) && earlier.state !== later.state) {
31
+ throw new Error('Conflicting canonical prompt turn transition');
32
+ }
33
+ }
34
+ const newer = previous && previous.revision > value.revision ? previous : value;
35
+ // Copy a bounded whitelist, never arbitrary session fields or transcript text.
36
+ byId.set(value.id, { id: value.id, startedAt: value.startedAt,
37
+ tokens: Math.max(previous?.tokens ?? 0, value.tokens), estimated: previous?.estimated === true || value.estimated,
38
+ correlationId: value.correlationId, inputSha256: value.inputSha256, state: newer.state, revision: newer.revision,
39
+ ...(newer.finishedAt !== undefined ? { finishedAt: newer.finishedAt } : {}),
40
+ ...(newer.failureCode ? { failureCode: newer.failureCode } : {}),
41
+ ...(previous?.usageIncomplete || value.usageIncomplete ? { usageIncomplete: true } : {}) });
42
+ correlations.set(value.correlationId, value.id);
43
+ if (byId.size > MAX_CORRELATED_TURNS)
44
+ throw new Error('Canonical prompt turn retention is full');
45
+ }
46
+ return [...byId.values()];
47
+ }
48
+ export function captureCorrelatedTurns(messages, retained = []) {
49
+ return mergeCorrelatedTurns(retained, messages.filter(message => message.role === 'user'
50
+ && message.turn?.id === message.id && message.turn.correlationId !== undefined).map(message => message.turn));
51
+ }
52
+ /** Stable caller keys are data, not command lines or provider context. */
53
+ export function validTurnCorrelation(value) {
54
+ return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/.test(value);
55
+ }
56
+ export function correlatedInputDigest(input) {
57
+ return createHash('sha256').update(JSON.stringify({ text: input.text,
58
+ attachments: input.attachments.map(attachment => attachment.id) })).digest('hex');
59
+ }
60
+ /** Project only canonical authored Messages, excluding transcript and provider errors. */
61
+ export function projectCorrelatedTurns(messages, sessionId, retained = []) {
62
+ return captureCorrelatedTurns(messages, retained).map(turn => {
63
+ return { turn_id: turn.id, session_id: sessionId, pane_id: 0,
64
+ correlation_id: turn.correlationId, state: turn.state, revision: turn.revision,
65
+ ...(turn.failureCode ? { failure_code: turn.failureCode } : {}) };
66
+ });
67
+ }
68
+ /** A restored unfinished turn is uncertain; never dispatch it or claim completion. */
69
+ export function restoreCorrelatedTurns(messages) {
70
+ return messages.map(message => message.turn?.correlationId
71
+ && (message.turn.state === 'admitted' || message.turn.state === 'running')
72
+ ? { ...message, turn: { ...message.turn, state: 'interrupted',
73
+ revision: (message.turn.revision ?? 0) + 1, usageIncomplete: true } } : message);
74
+ }
75
+ export function restoreCorrelatedTurnHistory(turns) {
76
+ return mergeCorrelatedTurns(turns).map(turn => turn.state === 'admitted' || turn.state === 'running'
77
+ ? { ...turn, state: 'interrupted', revision: turn.revision + 1, usageIncomplete: true } : turn);
78
+ }
@@ -6,9 +6,10 @@ export declare class PromptTurn {
6
6
  private mainRuns;
7
7
  private workers;
8
8
  readonly observe: ModelUsageObserver;
9
- constructor(id: string, changed: () => void, startedAt?: number);
9
+ constructor(id: string, changed: () => void, startedAt?: number, initial?: PromptTurnMetadata);
10
10
  snapshot(): PromptTurnMetadata;
11
11
  start(): void;
12
+ setOutcome(state: NonNullable<PromptTurnMetadata['state']>): void;
12
13
  finish(): void;
13
14
  private settle;
14
15
  }
@@ -5,9 +5,9 @@ export class PromptTurn {
5
5
  mainRuns = 0;
6
6
  workers = 0;
7
7
  observe;
8
- constructor(id, changed, startedAt = Date.now()) {
8
+ constructor(id, changed, startedAt = Date.now(), initial) {
9
9
  this.changed = changed;
10
- this.metadata = { id, startedAt, tokens: 0, estimated: false };
10
+ this.metadata = initial ? { ...initial, id } : { id, startedAt, tokens: 0, estimated: false };
11
11
  this.observe = Object.assign((usage) => {
12
12
  const tokens = usage.totalTokens;
13
13
  this.metadata = {
@@ -36,10 +36,23 @@ export class PromptTurn {
36
36
  }
37
37
  snapshot() { return { ...this.metadata }; }
38
38
  start() {
39
+ if (this.metadata.correlationId)
40
+ this.setOutcome('running');
39
41
  this.mainRuns++;
40
42
  this.metadata = { ...this.metadata, finishedAt: undefined };
41
43
  this.changed();
42
44
  }
45
+ setOutcome(state) {
46
+ if (!this.metadata.correlationId || this.metadata.state === state)
47
+ return;
48
+ if (this.metadata.state && ['completed', 'failed', 'interrupted'].includes(this.metadata.state)) {
49
+ throw new Error('Cannot reopen a terminal prompt turn');
50
+ }
51
+ this.metadata = { ...this.metadata, state, revision: (this.metadata.revision ?? 0) + 1,
52
+ ...(state === 'failed' ? { failureCode: 'agent_run_failed' } : {}),
53
+ ...(state === 'interrupted' ? { usageIncomplete: true } : {}) };
54
+ this.changed();
55
+ }
43
56
  finish() {
44
57
  this.mainRuns = Math.max(0, this.mainRuns - 1);
45
58
  this.settle();
@@ -1,9 +1,3 @@
1
- /**
2
- * SessionManager — shared session persistence, auto-save, and compaction.
3
- *
4
- * Eliminates duplicated session logic between TUI (cli_ratatui.ts) and headless (headless.ts).
5
- * Each renderer provides its own deps for message access and logging.
6
- */
7
1
  import { type UsageSnapshot } from '../usage_snapshot.js';
8
2
  import { type DiagnosticSnapshot, type DiagnosticEventKind, type DiagnosticJsonObject } from '../diagnostics/session_export.js';
9
3
  import type { CommandReceipt } from '../agent/runtime/command_jobs.js';
@@ -15,6 +9,7 @@ import type { MuxSessionState } from '../ui/ratatui/protocol.js';
15
9
  import type { PaneSessionSpec } from '../panes/types.js';
16
10
  import type { HostedSessionSettings } from '../hosted/session_settings.js';
17
11
  export interface SessionManagerDeps {
12
+ getModel?: () => string;
18
13
  sessionId: string;
19
14
  /** Stable session storage origin when an environment changes process.cwd(). */
20
15
  getSessionCwd?: () => string;
@@ -48,6 +43,7 @@ export interface SessionManagerDeps {
48
43
  /** Optional renderer-specific state to persist alongside the conversation. */
49
44
  getMuxState?: () => Promise<MuxSessionState | undefined>;
50
45
  getPaneSpecs?: () => PaneSessionSpec[];
46
+ getLayoutSnapshot?: () => Promise<SessionLayoutSnapshot | undefined>;
51
47
  getRuntimeState?: () => SessionRuntimeState;
52
48
  /** Await raw-source and evidence-index durability before extracting the checkpoint. */
53
49
  flushToolResponses?: () => Promise<void>;
@@ -66,25 +62,33 @@ export interface SessionSaveOptions {
66
62
  /** Retire an uncommitted admission write during normal host shutdown. */
67
63
  signal?: AbortSignal;
68
64
  }
65
+ export interface SessionLayoutSnapshot {
66
+ muxState: MuxSessionState | undefined;
67
+ paneSpecs: PaneSessionSpec[];
68
+ }
69
69
  /**
70
70
  * Manages session persistence, auto-save timers, and context compaction.
71
71
  */
72
72
  export declare class SessionManager {
73
73
  private deps;
74
+ private promptTurns;
74
75
  private diagnostics;
75
76
  private usage;
76
77
  private jobDiagnosticStates;
77
78
  private autoSaveTimer;
78
79
  private saveQueue;
79
- private muxSnapshot;
80
- private muxCapture;
81
- private muxGeneration;
80
+ private layoutSnapshot;
81
+ private layoutCapture;
82
+ private layoutGeneration;
82
83
  private cleanupPromise;
83
84
  constructor(deps: SessionManagerDeps);
84
85
  setSessionId(sessionId: string): void;
86
+ restoreLayout(layout: SessionLayoutSnapshot): void;
85
87
  /** Capture the current agent before replacement, then return detached canonical facts. */
86
88
  getDiagnostics(): DiagnosticSnapshot;
87
89
  restoreDiagnostics(snapshot: DiagnosticSnapshot | undefined): void;
90
+ getPromptTurns(): import('../types.js').PromptTurnMetadata[];
91
+ restorePromptTurns(turns: import('../types.js').PromptTurnMetadata[] | undefined): void;
88
92
  getUsageSnapshot(): UsageSnapshot;
89
93
  restoreUsageSnapshot(snapshot: UsageSnapshot | undefined): void;
90
94
  recordHostDiagnostic(kind: DiagnosticEventKind, data: DiagnosticJsonObject): void;
@@ -99,7 +103,9 @@ export declare class SessionManager {
99
103
  * Save the current session, filtering out ephemeral system messages.
100
104
  */
101
105
  save(options?: SessionSaveOptions): Promise<void>;
102
- private refreshMuxState;
106
+ saveBackground(read: () => Promise<SessionLayoutSnapshot>, muxOnly?: boolean): Promise<void>;
107
+ private readLayout;
108
+ private refreshLayout;
103
109
  private writeCurrentSession;
104
110
  /**
105
111
  * Lightweight save: only persist mux state (layout + pane content), skipping message serialization.
@@ -132,7 +138,7 @@ export declare class SessionManager {
132
138
  /**
133
139
  * Start periodic auto-save.
134
140
  */
135
- startAutoSave(intervalMs: number): void;
141
+ startAutoSave(intervalMs: number, save?: () => Promise<void>): void;
136
142
  /**
137
143
  * Stop the auto-save timer.
138
144
  */