@zergai/ztc 0.23.0-beta.1 → 0.24.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 (146) hide show
  1. package/README.md +299 -13
  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.js +57 -14
  8. package/dist/agent/backends/http_error.d.ts +2 -0
  9. package/dist/agent/backends/http_error.js +2 -0
  10. package/dist/agent/backends/router_gate.d.ts +3 -2
  11. package/dist/agent/backends/router_gate.js +5 -4
  12. package/dist/agent/backends/router_keys.d.ts +14 -0
  13. package/dist/agent/backends/router_keys.js +19 -0
  14. package/dist/agent/backends/router_refusal.d.ts +5 -3
  15. package/dist/agent/backends/router_refusal.js +28 -6
  16. package/dist/agent/backends/types.d.ts +1 -1
  17. package/dist/agent/backends/zrouter_stream.js +10 -6
  18. package/dist/agent/commands/agent_cli.d.ts +11 -1
  19. package/dist/agent/commands/agent_cli.js +295 -38
  20. package/dist/agent/commands/diff.js +4 -1
  21. package/dist/agent/commands/help.js +4 -1
  22. package/dist/agent/commands/plan.js +3 -1
  23. package/dist/agent/commands/session_redaction.d.ts +16 -0
  24. package/dist/agent/commands/session_redaction.js +77 -0
  25. package/dist/agent/commands/settings.js +144 -0
  26. package/dist/agent/commands/types.d.ts +5 -0
  27. package/dist/agent/commands/usage_spec.d.ts +4 -0
  28. package/dist/agent/commands/usage_spec.js +10 -4
  29. package/dist/agent/runtime/policy.d.ts +25 -0
  30. package/dist/agent/runtime/policy.js +154 -26
  31. package/dist/agent/runtime/source_verification.js +6 -2
  32. package/dist/agent/runtime/tool_runtime.js +81 -3
  33. package/dist/agent/tools/apply_patch.js +678 -131
  34. package/dist/agent/tools/bus_message.d.ts +26 -1
  35. package/dist/agent/tools/bus_message.js +126 -10
  36. package/dist/agent/tools/file.d.ts +16 -1
  37. package/dist/agent/tools/file.js +43 -5
  38. package/dist/agent/tools/index.d.ts +1 -1
  39. package/dist/agent/tools/index.js +1 -1
  40. package/dist/agent/tools/pane.js +5 -0
  41. package/dist/agent/tools/search.js +5 -1
  42. package/dist/agent/tools/supervision.js +16 -2
  43. package/dist/agent/tools/types.d.ts +22 -0
  44. package/dist/app/mirror_startup.d.ts +7 -5
  45. package/dist/app/mirror_startup.js +7 -5
  46. package/dist/app/navigator_mirrors.d.ts +20 -0
  47. package/dist/app/navigator_mirrors.js +36 -0
  48. package/dist/app/workspace_layout_controller.d.ts +11 -2
  49. package/dist/app/workspace_layout_controller.js +13 -2
  50. package/dist/batch/worktree.js +9 -1
  51. package/dist/cli_ratatui.d.ts +264 -12
  52. package/dist/cli_ratatui.js +1198 -103
  53. package/dist/config/types.d.ts +29 -0
  54. package/dist/desktop/daily/source_baseline.js +3 -1
  55. package/dist/diagnostics/session_export.d.ts +1 -0
  56. package/dist/diagnostics/session_export.js +229 -26
  57. package/dist/emulation/tool_adapters.js +42 -5
  58. package/dist/headless.js +24 -5
  59. package/dist/instance_registry.d.ts +7 -0
  60. package/dist/mcp/workspace_server.d.ts +12 -1
  61. package/dist/mcp/workspace_server.js +75 -8
  62. package/dist/panes/agent_cli.d.ts +60 -3
  63. package/dist/panes/agent_cli.js +169 -16
  64. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  65. package/dist/panes/agent_pane_sessions.js +111 -0
  66. package/dist/panes/agent_panes.d.ts +77 -3
  67. package/dist/panes/agent_panes.js +199 -10
  68. package/dist/panes/agent_profiles.d.ts +5 -0
  69. package/dist/panes/agent_profiles.js +7 -0
  70. package/dist/panes/agent_resume.d.ts +134 -0
  71. package/dist/panes/agent_resume.js +155 -0
  72. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  73. package/dist/panes/agent_sessions/claude_head.js +122 -0
  74. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  75. package/dist/panes/agent_sessions/claude_store.js +223 -0
  76. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  77. package/dist/panes/agent_sessions/codex_head.js +161 -0
  78. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  79. package/dist/panes/agent_sessions/codex_store.js +187 -0
  80. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  81. package/dist/panes/agent_sessions/controller.js +110 -0
  82. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  83. package/dist/panes/agent_sessions/cut_json.js +109 -0
  84. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  85. package/dist/panes/agent_sessions/limits.js +48 -0
  86. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  87. package/dist/panes/agent_sessions/scan.js +86 -0
  88. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  89. package/dist/panes/agent_sessions/store_fs.js +128 -0
  90. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  91. package/dist/panes/agent_sessions/stores.js +89 -0
  92. package/dist/panes/agent_sessions/title.d.ts +9 -0
  93. package/dist/panes/agent_sessions/title.js +51 -0
  94. package/dist/panes/agent_sessions/types.d.ts +48 -0
  95. package/dist/panes/agent_sessions/types.js +2 -0
  96. package/dist/panes/reply_arbitrator.d.ts +39 -0
  97. package/dist/panes/reply_arbitrator.js +185 -0
  98. package/dist/panes/reply_modes.d.ts +291 -0
  99. package/dist/panes/reply_modes.js +598 -0
  100. package/dist/runtime_info.js +11 -2
  101. package/dist/session.js +4 -2
  102. package/dist/simulation/living/context.d.ts +8 -8
  103. package/dist/simulation/living/types.d.ts +5 -5
  104. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  105. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  106. package/dist/ui/ratatui/ipc_path.js +23 -3
  107. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  108. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  109. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  110. package/dist/ui/ratatui/pane_relay.js +86 -19
  111. package/dist/ui/ratatui/process.js +3 -0
  112. package/dist/ui/ratatui/protocol.d.ts +50 -1
  113. package/dist/ui/ratatui/protocol.js +56 -0
  114. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  115. package/dist/ui/ratatui/relay_policy.js +94 -0
  116. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  117. package/dist/ui/ratatui/screen_privacy.js +24 -0
  118. package/dist/ui/scrollback.js +8 -0
  119. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  120. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  121. package/dist/ui/widgets/log_view.d.ts +5 -1
  122. package/dist/ui/widgets/log_view.js +40 -4
  123. package/dist/utils/atomic_write.js +9 -11
  124. package/dist/utils/canonical_path.d.ts +19 -0
  125. package/dist/utils/canonical_path.js +44 -0
  126. package/dist/utils/compaction.d.ts +2 -1
  127. package/dist/utils/compaction.js +3 -1
  128. package/dist/utils/git_directory_names.d.ts +51 -0
  129. package/dist/utils/git_directory_names.js +429 -0
  130. package/dist/utils/temporary_write_root.d.ts +6 -1
  131. package/dist/utils/temporary_write_root.js +32 -2
  132. package/dist/utils/tool_result_message.d.ts +4 -1
  133. package/dist/utils/tool_result_message.js +6 -2
  134. package/dist/web/bus_hold.d.ts +70 -0
  135. package/dist/web/bus_hold.js +118 -0
  136. package/dist/web/mirror_client.d.ts +7 -3
  137. package/dist/web/mirror_client.js +61 -23
  138. package/dist/web/mirror_route_gate.d.ts +40 -0
  139. package/dist/web/mirror_route_gate.js +71 -0
  140. package/dist/web/mirror_stream.d.ts +147 -22
  141. package/dist/web/mirror_stream.js +350 -83
  142. package/dist/web/pane_credentials.d.ts +32 -1
  143. package/dist/web/pane_credentials.js +62 -2
  144. package/dist/workspace_collision.js +11 -2
  145. package/dist/zlm-embed.mjs +940 -273
  146. package/package.json +34 -12
@@ -282,6 +282,25 @@ export interface CustomPaneOption {
282
282
  /** Command run in a shell pane, through `$SHELL -lc`. */
283
283
  command: string;
284
284
  }
285
+ /** How Main answers an agent pane by itself in an exchange; see `src/panes/reply_modes.ts`. */
286
+ export type AgentReplyMode = 'uncapped' | {
287
+ capped: number;
288
+ } | {
289
+ arbitrator: string;
290
+ };
291
+ /** An arbitrator the person set up for reply modes; see `src/panes/reply_modes.ts`. */
292
+ export type ReplyArbitratorSetting = {
293
+ name: string;
294
+ kind: 'model';
295
+ provider?: string;
296
+ model: string;
297
+ timeoutSeconds?: number;
298
+ } | {
299
+ name: string;
300
+ kind: 'http';
301
+ url: string;
302
+ timeoutSeconds?: number;
303
+ };
285
304
  /** Options for the new-pane chooser. See `src/config/panes.ts` for resolution. */
286
305
  export interface PanesSettings {
287
306
  /** Extra chooser rows, in the order they are offered. */
@@ -308,6 +327,16 @@ export interface PanesSettings {
308
327
  * wins either way, and #860's delegated workers never bypass. Unset (a profile saved before this setting): 'bypass'.
309
328
  */
310
329
  agentPermissions?: 'bypass' | 'ask';
330
+ /**
331
+ * How Main answers a Claude Code or Codex pane by itself in an exchange whose first message names no reply mode
332
+ * (panes/reply_modes.ts): 'uncapped', { capped: N } or { arbitrator: NAME }. Unset: capped at 5.
333
+ */
334
+ agentReplyMode?: AgentReplyMode;
335
+ /**
336
+ * The arbitrators the person set up, which a reply mode may name besides "model" (a model on Main's own route): a model
337
+ * with its provider, or an HTTP(S) endpoint. Only these, never one an agent names, read an exchange.
338
+ */
339
+ replyArbitrators?: ReplyArbitratorSetting[];
311
340
  /** The ZTC sign-in profile new Claude Code / Codex panes start on; unset for this computer's normal sign-in. */
312
341
  agentProfiles?: Partial<Record<'claude' | 'codex', string>>;
313
342
  /**
@@ -31,7 +31,9 @@ async function files(root) {
31
31
  }
32
32
  export async function observeSource(root) {
33
33
  const canonical = await realpath(root);
34
- const dirty = await promisify(execFile)('git', ['-C', canonical, 'status', '--porcelain', '--untracked-files=all'], { env: { PATH: process.env.PATH, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }, timeout: 5000 }).then(value => !!value.stdout.trim()).catch(() => false);
34
+ // The agent the daily driver launches writes this work tree: git runs no core.fsmonitor command from its config,
35
+ // and safe.bareRepository=explicit stops it reading a planted implicit bare repository's config.
36
+ const dirty = await promisify(execFile)('git', ['-c', 'core.fsmonitor=false', '-c', 'safe.bareRepository=explicit', '-C', canonical, 'status', '--porcelain', '--untracked-files=all'], { env: { PATH: process.env.PATH, GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }, timeout: 5000 }).then(value => !!value.stdout.trim()).catch(() => false);
35
37
  return { root: canonical, dirty, files: await files(canonical) };
36
38
  }
37
39
  export async function sourceChanged(baseline) {
@@ -88,6 +88,7 @@ export declare function parseDiagnosticSnapshot(value: unknown): DiagnosticSnaps
88
88
  * Telemetry remains immutable; only a matching canonical invocation may advance
89
89
  * its observed lifecycle, and a matching result may retain a richer same-source preview. */
90
90
  export declare function captureSessionDiagnosticSnapshot(input: SessionDiagnosticInput): DiagnosticSnapshot;
91
+ export declare function repairLoadedDiagnosticSnapshot(snapshot: DiagnosticSnapshot, messages: readonly Message[]): DiagnosticSnapshot;
91
92
  export declare function buildSessionDiagnosticDocument(input: SessionDiagnosticInput): DiagnosticDocument;
92
93
  export declare function exportSessionDiagnostics(input: SessionDiagnosticInput): string;
93
94
  export declare function parseDiagnosticExport(text: string): DiagnosticDocument;
@@ -392,6 +392,7 @@ export function admitStoredDiagnosticSnapshot(value) {
392
392
  return null;
393
393
  const kept = new Map();
394
394
  const anonymous = [];
395
+ let repaired = 0;
395
396
  for (const event of value.events) {
396
397
  if (event.id === null) {
397
398
  anonymous.push(event);
@@ -405,9 +406,11 @@ export function admitStoredDiagnosticSnapshot(value) {
405
406
  try {
406
407
  kept.set(event.id, reconcileCheckpointFact(prior, event));
407
408
  }
408
- catch { /* One irreconcilable pair drops the later fact, never the file. */ }
409
+ catch {
410
+ repaired += 1;
411
+ }
409
412
  }
410
- return boundedSnapshot([...kept.values(), ...anonymous], 0, value.omittedTextBytes, value.omittedEvents);
413
+ return boundedSnapshot([...kept.values(), ...anonymous], 0, value.omittedTextBytes, value.omittedEvents + repaired);
411
414
  }
412
415
  export function parseDiagnosticSnapshot(value) {
413
416
  if (!isObject(value) || value.schemaVersion !== 1 || !Array.isArray(value.events) || value.events.length > DIAGNOSTIC_LIMITS.events
@@ -520,11 +523,163 @@ function projectMessages(messages) {
520
523
  }
521
524
  return output;
522
525
  }
526
+ const REDACTION_MARKER = /\[REDACTED(?: [A-Z ]+)?\]/;
527
+ function redactionCompatible(prior, current, truncated) {
528
+ if (prior === current)
529
+ return true;
530
+ const segments = prior.split(REDACTION_MARKER);
531
+ if (segments.length === 1)
532
+ return false;
533
+ const first = segments[0];
534
+ if (!current.startsWith(first))
535
+ return truncated && first.startsWith(current);
536
+ let position = first.length;
537
+ for (let index = 1; index < segments.length; index++) {
538
+ const segment = segments[index];
539
+ if (index === segments.length - 1) {
540
+ const tail = current.slice(position);
541
+ if (tail.length === 0)
542
+ return false;
543
+ if (truncated || segment === '')
544
+ return true;
545
+ return current.endsWith(segment) && current.length - segment.length > position;
546
+ }
547
+ const found = current.indexOf(segment, position + 1);
548
+ if (found === -1)
549
+ return truncated;
550
+ position = found + segment.length;
551
+ }
552
+ return false;
553
+ }
554
+ function redactionMatches(a, b, truncated) {
555
+ return redactionCompatible(a, b, truncated) || redactionCompatible(b, a, truncated);
556
+ }
557
+ function redactionJsonCompatible(prior, current) {
558
+ if (prior === current)
559
+ return true;
560
+ if (typeof prior === 'string' && typeof current === 'string')
561
+ return redactionMatches(prior, current, false);
562
+ if (Array.isArray(prior) && Array.isArray(current)) {
563
+ return prior.length === current.length && prior.every((item, index) => redactionJsonCompatible(item, current[index]));
564
+ }
565
+ if (isObject(prior) && isObject(current)) {
566
+ const keys = Object.keys(prior);
567
+ return keys.length === Object.keys(current).length
568
+ && keys.every(key => Object.hasOwn(current, key) && redactionJsonCompatible(prior[key], current[key]));
569
+ }
570
+ return false;
571
+ }
572
+ function contentTruncated(event) {
573
+ return (event.truncations ?? []).some(row => row.field === 'content');
574
+ }
575
+ function redactionData(event) {
576
+ if (event.data === undefined)
577
+ return undefined;
578
+ const data = { ...event.data };
579
+ if (typeof data.isStreaming === 'boolean')
580
+ delete data.isStreaming;
581
+ return Object.keys(data).length ? data : undefined;
582
+ }
583
+ function redactionEquivalent(prior, current) {
584
+ const truncated = contentTruncated(prior) || contentTruncated(current);
585
+ if (!redactionMatches(prior.content ?? '', current.content ?? '', truncated))
586
+ return false;
587
+ for (const field of ['storedRole', 'toolCallId', 'toolName', 'status']) {
588
+ const before = prior[field];
589
+ const after = current[field];
590
+ if (before === after)
591
+ continue;
592
+ if (typeof before !== 'string' || typeof after !== 'string')
593
+ return false;
594
+ if (!redactionMatches(before, after, false))
595
+ return false;
596
+ }
597
+ return redactionJsonCompatible(redactionData(prior), redactionData(current))
598
+ && redactionJsonCompatible(prior.args, current.args);
599
+ }
600
+ /** Two observations of one fact that differ only where one of them masked a value. */
601
+ function redactionDrift(prior, current) {
602
+ return prior.timestamp === current.timestamp && prior.data?.isStreaming === current.data?.isStreaming
603
+ && redactionEquivalent(prior, current);
604
+ }
605
+ function redactionMarkers(event) {
606
+ const text = `${event.content ?? ''}\n${JSON.stringify(event.data ?? null)}\n${JSON.stringify(event.args ?? null)}`;
607
+ return text.split(REDACTION_MARKER).length - 1;
608
+ }
609
+ /** The side whose masks cover the other's text hides more, whatever its count; otherwise the side with more masks. */
610
+ function moreMasked(prior, current) {
611
+ const truncated = contentTruncated(prior) || contentTruncated(current);
612
+ const priorCovers = redactionCompatible(prior.content ?? '', current.content ?? '', truncated);
613
+ if (priorCovers !== redactionCompatible(current.content ?? '', prior.content ?? '', truncated))
614
+ return priorCovers ? prior : current;
615
+ return redactionMarkers(prior) >= redactionMarkers(current) ? prior : current;
616
+ }
617
+ function mergeMaskedText(prior, current) {
618
+ const priorMasked = REDACTION_MARKER.test(prior);
619
+ const currentMasked = REDACTION_MARKER.test(current);
620
+ if (priorMasked !== currentMasked)
621
+ return priorMasked ? prior : current;
622
+ if (!priorMasked)
623
+ return current;
624
+ // Both masked ('alpha [REDACTED]' and '[REDACTED]'): keep the one that covers the other, so neither side's mask is undone.
625
+ const priorCovers = redactionCompatible(prior, current, false);
626
+ if (priorCovers !== redactionCompatible(current, prior, false))
627
+ return priorCovers ? prior : current;
628
+ return prior.split(REDACTION_MARKER).length >= current.split(REDACTION_MARKER).length ? prior : current;
629
+ }
630
+ function mergeMasked(prior, current) {
631
+ if (prior === undefined)
632
+ return current;
633
+ if (current === undefined)
634
+ return prior;
635
+ if (prior === current)
636
+ return prior;
637
+ if (typeof prior === 'string' && typeof current === 'string')
638
+ return mergeMaskedText(prior, current);
639
+ if (Array.isArray(prior) && Array.isArray(current)) {
640
+ if (prior.length !== current.length)
641
+ return current;
642
+ return prior.map((item, index) => mergeMasked(item, current[index]));
643
+ }
644
+ if (isObject(prior) && isObject(current)) {
645
+ const merged = { ...prior };
646
+ for (const [key, value] of Object.entries(current)) {
647
+ merged[key] = Object.hasOwn(prior, key) ? mergeMasked(prior[key], value) : value;
648
+ }
649
+ return merged;
650
+ }
651
+ return current;
652
+ }
653
+ function mergeAuthoredProof(prior, current, base) {
654
+ const observedStreaming = prior.data?.isStreaming === false || current.data?.isStreaming === false
655
+ ? false : prior.data?.isStreaming ?? current.data?.isStreaming;
656
+ const merged = mergeMasked(prior.data, current.data);
657
+ const data = { ...(isObject(merged) ? merged : {}),
658
+ ...(observedStreaming === undefined ? {} : { isStreaming: observedStreaming }) };
659
+ const reconciled = { ...base, timestamp: prior.timestamp ?? current.timestamp };
660
+ const content = mergeMasked(prior.content, current.content);
661
+ if (typeof content === 'string')
662
+ reconciled.content = content;
663
+ else
664
+ delete reconciled.content;
665
+ const args = mergeMasked(prior.args, current.args);
666
+ if (args === undefined)
667
+ delete reconciled.args;
668
+ else
669
+ reconciled.args = args;
670
+ if (Object.keys(data).length)
671
+ reconciled.data = data;
672
+ else
673
+ delete reconciled.data;
674
+ return reconciled;
675
+ }
523
676
  function reconcileCheckpointFact(prior, current) {
524
677
  if (diagnosticIdentity(prior) === diagnosticIdentity(current))
525
678
  return prior;
526
- const sameSource = prior.kind === current.kind && prior.origin === current.origin && prior.storedRole === current.storedRole
527
- && prior.toolCallId === current.toolCallId && prior.toolName === current.toolName;
679
+ const sameText = (before, after) => before === after || (typeof before === 'string' && typeof after === 'string' && redactionMatches(before, after, false));
680
+ const sameSource = prior.kind === current.kind && prior.origin === current.origin
681
+ && sameText(prior.storedRole, current.storedRole) && sameText(prior.toolCallId, current.toolCallId)
682
+ && sameText(prior.toolName, current.toolName);
528
683
  if (!sameSource)
529
684
  throw new DiagnosticExportError(`Diagnostic canonical identity conflict: ${current.id}`, 'INVALID_EXPORT');
530
685
  if (current.kind === 'assistant' || current.kind === 'reasoning') {
@@ -539,47 +694,49 @@ function reconcileCheckpointFact(prior, current) {
539
694
  }
540
695
  return diagnosticIdentity(fact);
541
696
  };
542
- if (authoredFacts(prior) === authoredFacts(current)) {
543
- const observedStreaming = prior.data?.isStreaming === false || current.data?.isStreaming === false
544
- ? false : prior.data?.isStreaming ?? current.data?.isStreaming;
545
- const data = { ...prior.data, ...current.data,
546
- ...(observedStreaming === undefined ? {} : { isStreaming: observedStreaming }) };
547
- const reconciled = { ...prior, timestamp: prior.timestamp ?? current.timestamp };
548
- if (Object.keys(data).length)
549
- reconciled.data = data;
550
- else
551
- delete reconciled.data;
552
- return reconciled;
553
- }
697
+ if (authoredFacts(prior) === authoredFacts(current))
698
+ return mergeAuthoredProof(prior, current, prior);
699
+ if (redactionEquivalent(prior, current))
700
+ return mergeAuthoredProof(prior, current, moreMasked(prior, current));
554
701
  }
555
702
  if (current.kind === 'tool_invocation') {
556
703
  const terminal = (status) => status === 'complete' || status === 'error';
704
+ // Arguments that differ only where one checkpoint masked a value are the same arguments, and keep the mask.
705
+ const sameArgs = diagnosticIdentity(prior.args) === diagnosticIdentity(current.args);
706
+ const maskedArgs = !sameArgs && redactionJsonCompatible(prior.args, current.args);
707
+ const masked = (event) => maskedArgs ? { ...event, args: mergeMasked(prior.args, current.args) } : event;
557
708
  if (terminal(prior.status)) {
558
709
  if (!terminal(current.status))
559
- return prior; // A stale live checkpoint cannot reopen a settled call.
560
- if (prior.status !== current.status || diagnosticIdentity(prior.args) !== diagnosticIdentity(current.args)) {
710
+ return masked(prior); // A stale live checkpoint cannot reopen a settled call.
711
+ if (prior.status !== current.status || !(sameArgs || maskedArgs)) {
561
712
  throw new DiagnosticExportError(`Diagnostic settled invocation identity conflict: ${current.id}`, 'INVALID_EXPORT');
562
713
  }
563
714
  if (diagnosticIdentity(prior.data) === diagnosticIdentity(current.data))
564
- return prior;
715
+ return masked(prior);
565
716
  if (prior.data?.completedAt === current.data?.completedAt)
566
- return { ...current, data: { ...prior.data, ...current.data } };
717
+ return masked({ ...current, data: { ...prior.data, ...current.data } });
567
718
  if (prior.data?.completedAt === null && typeof current.data?.completedAt === 'string')
568
- return current;
719
+ return masked(current);
569
720
  if (current.data?.completedAt === null)
570
- return prior;
721
+ return masked(prior);
571
722
  }
572
723
  else if (prior.status === 'running' && current.status === 'pending')
573
- return prior;
724
+ return masked(prior);
574
725
  else if (['pending', 'running', 'complete', 'error'].includes(current.status ?? '')) {
575
- return { ...current, data: { ...current.data,
576
- ...(diagnosticIdentity(prior.args) === diagnosticIdentity(current.args) ? {} : {
726
+ return masked({ ...current, data: { ...current.data,
727
+ ...(sameArgs || maskedArgs ? {} : {
577
728
  argumentsUpdatedFromPriorCheckpoint: true,
578
729
  argumentsSource: 'latest canonical checkpoint; model proposal can differ from admitted execution input',
579
- }) } };
730
+ }) } });
580
731
  }
581
732
  }
582
733
  if (current.kind === 'tool_result' && prior.status === current.status) {
734
+ // The richer preview wins, unless it shows a value the other preview masked.
735
+ const larger = bytes(prior.content ?? '') >= bytes(current.content ?? '') ? prior : current;
736
+ const markers = (event) => (event.content ?? '').split(REDACTION_MARKER).length - 1;
737
+ if (markers(larger) < markers(larger === prior ? current : prior) && redactionDrift(prior, current)) {
738
+ return mergeAuthoredProof(prior, current, moreMasked(prior, current));
739
+ }
583
740
  const sourceIdentity = (event) => event.truncations?.find(row => row.field === 'content')?.sha256
584
741
  ?? (event.content === undefined ? null : sha(event.content));
585
742
  const priorIdentity = sourceIdentity(prior);
@@ -593,6 +750,9 @@ function reconcileCheckpointFact(prior, current) {
593
750
  }
594
751
  if ((current.kind === 'assistant' || current.kind === 'reasoning') && prior.data?.isStreaming === true)
595
752
  return current;
753
+ // Any other fact (a user message, a notice, telemetry) observed with and without a mask is one fact, and keeps the mask.
754
+ if (redactionDrift(prior, current))
755
+ return mergeAuthoredProof(prior, current, moreMasked(prior, current));
596
756
  throw new DiagnosticExportError(`Diagnostic canonical identity conflict: ${current.id}`, 'INVALID_EXPORT');
597
757
  }
598
758
  /** Capture canonical message facts before checkpoint trimming or compaction.
@@ -625,6 +785,49 @@ export function captureSessionDiagnosticSnapshot(input) {
625
785
  const fresh = boundedSnapshot(current, 0, omittedBytes(current));
626
786
  return mergeDiagnosticSnapshots(previous, fresh);
627
787
  }
788
+ export function repairLoadedDiagnosticSnapshot(snapshot, messages) {
789
+ const history = parseDiagnosticSnapshot(snapshot);
790
+ if (history === null)
791
+ return snapshot;
792
+ // The repair is best effort: messages it cannot project leave the ledger as stored, and the next capture says why.
793
+ try {
794
+ // Only a stored fact that differs from its unredacted source can conflict with it. Loads and the reloads every save
795
+ // makes then scan and redact the transcript only when such a fact exists, and bound only those sources.
796
+ const stored = new Map(history.events.flatMap(event => event.id === null ? [] : [[event.id, event]]));
797
+ // A projected id is its message's id, alone or followed by ':' parts, so only messages a stored id names are projected.
798
+ const named = new Set([...stored.keys()].flatMap(id => id.split(':').map((_, index, parts) => parts.slice(0, index + 1).join(':'))));
799
+ const sources = messages.filter(message => typeof message.id === 'string' && named.has(message.id) && retainedMessage(message));
800
+ const differing = projectMessages(sources).filter(event => {
801
+ const prior = event.id === null ? undefined : stored.get(event.id);
802
+ return prior !== undefined && diagnosticIdentity(prior) !== diagnosticIdentity(event);
803
+ });
804
+ if (differing.length === 0)
805
+ return snapshot;
806
+ const credentials = new Set();
807
+ collectCredentials([messages, history.events], credentials);
808
+ const known = [...credentials].sort((a, b) => b.length - a.length);
809
+ const fresh = new Map(differing.map(event => [event.id, boundEvent(event, known)]));
810
+ let repaired = 0;
811
+ const events = [];
812
+ for (const event of history.events) {
813
+ const source = event.id === null ? undefined : fresh.get(event.id);
814
+ if (source === undefined) {
815
+ events.push(event);
816
+ continue;
817
+ }
818
+ try {
819
+ events.push(reconcileCheckpointFact(event, source));
820
+ }
821
+ catch {
822
+ repaired += 1;
823
+ }
824
+ }
825
+ return boundedSnapshot(events, 0, history.omittedTextBytes, history.omittedEvents + repaired);
826
+ }
827
+ catch {
828
+ return snapshot;
829
+ }
830
+ }
628
831
  export function buildSessionDiagnosticDocument(input) {
629
832
  if (input.sessionId !== undefined && input.sessionId !== null
630
833
  && (typeof input.sessionId !== 'string' || bytes(input.sessionId) > DIAGNOSTIC_LIMITS.textBytes)) {
@@ -1,5 +1,5 @@
1
1
  import { ToolCapability } from '../agent/runtime/capabilities.js';
2
- import { applyExactReplace, resolvePath, updateFileAtomic } from '../agent/tools/file.js';
2
+ import { admitLockedWrite, applyExactReplace, resolvePath, updateFileAtomic, writeAdmissionPath } from '../agent/tools/file.js';
3
3
  import { buildSimpleDiffMeta } from '../utils/diff.js';
4
4
  import { runCommandTool } from '../agent/tools/shell.js';
5
5
  const CLAUDE_PROFILE_IDS = new Set(['claude-code']);
@@ -84,6 +84,8 @@ function makeClaudeAdapters(tools) {
84
84
  {
85
85
  capabilities: [ToolCapability.SHELL_EXEC, ToolCapability.FILE_WRITE],
86
86
  resolveExecutionCwd: (args, context) => resolveClaudeBashCwd(tools, args, context),
87
+ // Bash runs its command and drops any `checked` plan beside it.
88
+ resolveExecutionCommand: args => requiredString(args, ['command']),
87
89
  readOnlyCall: args => readOnlyInvocation(tools, () => ({ name: 'run_command', args: claudeBashInvocation(args) })),
88
90
  definition: {
89
91
  name: 'Bash',
@@ -134,6 +136,7 @@ function makeClaudeAdapters(tools) {
134
136
  content: 'Content to write',
135
137
  }, ['file_path', 'content']),
136
138
  },
139
+ writePaths: async (args, context) => filePathTargets(args, context),
137
140
  execute: (args, context) => callTool(tools, 'write_file', {
138
141
  path: requiredString(args, ['file_path', 'path']),
139
142
  content: requiredString(args, ['content']),
@@ -151,6 +154,7 @@ function makeClaudeAdapters(tools) {
151
154
  replace_all: 'If true, replace all occurrences',
152
155
  }, ['file_path', 'old_string', 'new_string']),
153
156
  },
157
+ writePaths: async (args, context) => filePathTargets(args, context),
154
158
  execute: async (args, context) => editFile(tools, args, context),
155
159
  },
156
160
  {
@@ -163,6 +167,7 @@ function makeClaudeAdapters(tools) {
163
167
  edits: 'Array or JSON array of {old_string,new_string,replace_all}',
164
168
  }, ['file_path', 'edits']),
165
169
  },
170
+ writePaths: async (args, context) => filePathTargets(args, context),
166
171
  execute: async (args, context) => multiEditFile(tools, args, context),
167
172
  },
168
173
  {
@@ -269,6 +274,8 @@ function makeCodexAdapters(tools) {
269
274
  }, []),
270
275
  },
271
276
  resolveExecutionCwd: (args, context) => resolveCodexShellCwd(tools, args, context),
277
+ resolveExecutionCommand: codexShellCommand,
278
+ writePaths: (args, context) => codexShellWritePaths(tools, args, context),
272
279
  readOnlyCall: args => readOnlyInvocation(tools, () => codexShellInvocation(args)),
273
280
  execute: (args, context) => executeCodexShell(tools, args, context),
274
281
  },
@@ -283,6 +290,8 @@ function makeCodexAdapters(tools) {
283
290
  }, ['command']),
284
291
  },
285
292
  resolveExecutionCwd: (args, context) => resolveCodexShellCwd(tools, args, context),
293
+ resolveExecutionCommand: codexShellCommand,
294
+ writePaths: (args, context) => codexShellWritePaths(tools, args, context),
286
295
  readOnlyCall: args => readOnlyInvocation(tools, () => codexShellInvocation(args)),
287
296
  execute: (args, context) => executeCodexShell(tools, args, context),
288
297
  },
@@ -346,13 +355,34 @@ async function executeCodexShell(tools, args, context) {
346
355
  const call = codexShellInvocation(args);
347
356
  return callTool(tools, call.name, call.args, context);
348
357
  }
358
+ /**
359
+ * The paths an `apply_patch <<EOF` heredoc writes, named by the apply_patch tool it runs, so the runtime admits them
360
+ * as it admits apply_patch's own. A plain shell command names none here.
361
+ */
362
+ async function codexShellWritePaths(tools, args, context) {
363
+ const call = codexShellInvocation(args);
364
+ const target = tools.find(tool => tool.definition.name === call.name);
365
+ return target?.writePaths ? target.writePaths(call.args, context) : [];
366
+ }
349
367
  function resolveCodexShellCwd(tools, args, context) {
350
368
  const call = codexShellInvocation(args);
351
369
  const target = tools.find(tool => tool.definition.name === call.name);
352
370
  return target?.resolveExecutionCwd?.(call.args, context) ?? (context?.cwd || process.cwd());
353
371
  }
372
+ /** The shell text a Codex shell call carries: `cmd` when given, else `command`. */
373
+ function codexShellText(args) {
374
+ return requiredString(args, ['cmd', 'command']);
375
+ }
376
+ /**
377
+ * The shell command a Codex shell call runs, for the shell policy: its text, or none for an `apply_patch <<EOF`
378
+ * heredoc, which runs the apply_patch tool and no shell. The heredoc is governed as the file write it is, by its
379
+ * written paths and the file_write capability.
380
+ */
381
+ function codexShellCommand(args) {
382
+ return codexShellInvocation(args).name === 'apply_patch' ? '' : codexShellText(args);
383
+ }
354
384
  function codexShellInvocation(args) {
355
- const command = requiredString(args, ['cmd', 'command']);
385
+ const command = codexShellText(args);
356
386
  const patch = extractApplyPatchPayload(command);
357
387
  if (patch) {
358
388
  return { name: 'apply_patch', args: { patch } };
@@ -392,7 +422,8 @@ async function editFile(tools, args, context) {
392
422
  const oldString = requiredString(args, ['old_string']);
393
423
  const newString = requiredString(args, ['new_string']);
394
424
  const replaceAll = parseReplaceAllFlag(args.replace_all);
395
- const { before, after } = await updateFileAtomic(resolvePath(path, context), content => applyExactReplace(content, oldString, newString, replaceAll));
425
+ const resolved = resolvePath(path, context);
426
+ const { before, after } = await updateFileAtomic(resolved, content => applyExactReplace(content, oldString, newString, replaceAll), () => admitLockedWrite(resolved, path, context));
396
427
  const replacements = replaceAll ? before.split(oldString).length - 1 : 1;
397
428
  const { diff, truncated } = buildSimpleDiffMeta(before, after);
398
429
  return JSON.stringify({
@@ -415,12 +446,13 @@ async function multiEditFile(tools, args, context) {
415
446
  replaceAll: parseReplaceAllFlag(record.replace_all),
416
447
  };
417
448
  });
418
- const { before, after } = await updateFileAtomic(resolvePath(path, context), content => {
449
+ const resolved = resolvePath(path, context);
450
+ const { before, after } = await updateFileAtomic(resolved, content => {
419
451
  for (const record of records) {
420
452
  content = applyExactReplace(content, record.oldString, record.newString, record.replaceAll);
421
453
  }
422
454
  return content;
423
- });
455
+ }, () => admitLockedWrite(resolved, path, context));
424
456
  const { diff, truncated } = buildSimpleDiffMeta(before, after);
425
457
  return JSON.stringify({
426
458
  path,
@@ -431,6 +463,11 @@ async function multiEditFile(tools, args, context) {
431
463
  verified: true,
432
464
  });
433
465
  }
466
+ /** The file a Claude Write, Edit or MultiEdit call writes, for the runtime's admission before dispatch. */
467
+ function filePathTargets(args, context) {
468
+ const path = requiredString(args, ['file_path', 'path']);
469
+ return [{ path: writeAdmissionPath(resolvePath(path, context)), label: path }];
470
+ }
434
471
  function parseReplaceAllFlag(value) {
435
472
  if (value === true)
436
473
  return true;
package/dist/headless.js CHANGED
@@ -33,6 +33,8 @@ import { isRetiredModel, isRetiredProvider, retiredProviderMessage, ROUTE_AWAITS
33
33
  import { formatTaskHandoffContext, projectTaskHandoff } from './session_handoff_contract.js';
34
34
  import { RouterConfigurationError } from './router_auth.js';
35
35
  import { currentRouterOnlyModelError, RouterOnlyModelError } from './agent/commands/provider_choices.js';
36
+ import { DiagnosticExportError } from './diagnostics/session_export.js';
37
+ import { redactErrorText } from './agent/backends/http_error.js';
36
38
  import { routerRefusalOf } from './agent/backends/router_refusal.js';
37
39
  import { adoptRouterRefusalRecord } from './agent/backends/router_refusal_record.js';
38
40
  import { routerAccount, routerRefusalGate } from './agent/backends/router_gate.js';
@@ -224,6 +226,24 @@ function inputLimitData(error) {
224
226
  message: error.message,
225
227
  };
226
228
  }
229
+ function stableErrorCode(error) {
230
+ if (typeof error !== 'object' || error === null || !('code' in error))
231
+ return undefined;
232
+ const code = error.code;
233
+ return typeof code === 'string' ? code : undefined;
234
+ }
235
+ function initializationFailure(error) {
236
+ if (error instanceof RouterConfigurationError || error instanceof EnvironmentRecoveryError || error instanceof RouteAwaitingChoiceError
237
+ || error instanceof RouterOnlyModelError) {
238
+ return { message: error.message };
239
+ }
240
+ if (error instanceof DiagnosticExportError)
241
+ return { message: redactErrorText(error.message), code: error.code };
242
+ if (error instanceof SessionLoadError)
243
+ return { message: redactErrorText(error.message), code: error.reason };
244
+ const code = stableErrorCode(error);
245
+ return { message: 'Headless initialization failed.', ...(code === undefined ? {} : { code }) };
246
+ }
227
247
  function assertPromptWithinLimit(prompt) {
228
248
  if (Buffer.byteLength(prompt, 'utf8') > HEADLESS_INPUT_LIMITS.promptBytes) {
229
249
  throw promptLimitError();
@@ -4088,18 +4108,17 @@ export async function runHeadless(options, initialPrompt) {
4088
4108
  }
4089
4109
  catch (error) {
4090
4110
  // A profile still waiting for a route choice has no route (see ConfigStore.routeAwaitingChoice), and says how to choose one.
4091
- // A model only Zerg Router serves says how to reach it.
4092
- const message = error instanceof RouterConfigurationError || error instanceof EnvironmentRecoveryError || error instanceof RouteAwaitingChoiceError
4093
- || error instanceof RouterOnlyModelError ? error.message : 'Headless initialization failed.';
4111
+ // A model only Zerg Router serves says how to reach it (initializationFailure).
4112
+ const failure = initializationFailure(error);
4094
4113
  if (options.json) {
4095
4114
  process.stdout.write(`${JSON.stringify({
4096
4115
  type: 'error',
4097
4116
  timestamp: new Date().toISOString(),
4098
- data: { message },
4117
+ data: failure,
4099
4118
  })}\n`);
4100
4119
  }
4101
4120
  else {
4102
- process.stderr.write(`${message}\n`);
4121
+ process.stderr.write(`${failure.message}\n`);
4103
4122
  }
4104
4123
  process.exit(1);
4105
4124
  }
@@ -50,6 +50,13 @@ export interface ZtcInstance {
50
50
  * navigator shows "no attach" and the row is non-selectable.
51
51
  */
52
52
  zmuxSocketPath?: string | null;
53
+ /**
54
+ * Whether this instance's mirror (`mirrorPort`) answers only the link its own ZTC gives: the desktop app's, and the
55
+ * one a zmux session starts by itself (MirrorStreamServer.setPaneControlCredentialRequired). Another ZTC holds no
56
+ * credential for it, so its navigator says where this instance's logs and page open instead of reaching for them
57
+ * (app/navigator_mirrors.ts). Absent on entries written before this field existed.
58
+ */
59
+ mirrorNeedsLink?: boolean;
53
60
  /**
54
61
  * ISO timestamp of this instance's most recent heartbeat.
55
62
  *
@@ -16,6 +16,7 @@
16
16
  */
17
17
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
18
18
  import { type AgentCliId, type PaneProgram } from '../panes/agent_cli.js';
19
+ import { type ReplyMode } from '../panes/reply_modes.js';
19
20
  import { PaneRelayClient, type PaneCommandTransport } from '../ui/ratatui/pane_relay.js';
20
21
  export interface WorkspaceBusMessage {
21
22
  from: {
@@ -25,9 +26,19 @@ export interface WorkspaceBusMessage {
25
26
  to: number | 'all';
26
27
  type: 'ztc_message';
27
28
  text: string;
29
+ /** For a message to pane 0: how it answers this pane by itself in their exchange (panes/reply_modes.ts). */
30
+ replyMode?: ReplyMode;
28
31
  }
29
32
  export interface WorkspaceBusSender {
30
- send(message: WorkspaceBusMessage): Promise<void>;
33
+ /**
34
+ * Post MESSAGE to the bus. It resolves with the mirror's words when the mirror holds the message for a ZTC pane that
35
+ * hasn't joined the bus yet (HELD), and with what pane 0 says of the reply mode it carried, or the exchange it is in
36
+ * (REPLY_NOTICE); it rejects, in the mirror's words, when the mirror refuses it.
37
+ */
38
+ send(message: WorkspaceBusMessage): Promise<{
39
+ held?: string;
40
+ replyNotice?: string;
41
+ } | void>;
31
42
  }
32
43
  export interface WorkspaceMcpOptions {
33
44
  /** The pane relay; null outside a ZTC workspace (every tool then says so). */