@zergai/ztc 0.23.1-dev.202611152321 → 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 (149) 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-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +2 -2
  10. package/dist/agent/agent.js +57 -14
  11. package/dist/agent/backends/http_error.d.ts +2 -0
  12. package/dist/agent/backends/http_error.js +2 -0
  13. package/dist/agent/backends/router_gate.d.ts +3 -2
  14. package/dist/agent/backends/router_gate.js +5 -4
  15. package/dist/agent/backends/router_keys.d.ts +14 -0
  16. package/dist/agent/backends/router_keys.js +19 -0
  17. package/dist/agent/backends/router_refusal.d.ts +5 -3
  18. package/dist/agent/backends/router_refusal.js +28 -6
  19. package/dist/agent/backends/types.d.ts +1 -1
  20. package/dist/agent/backends/zrouter_stream.js +10 -6
  21. package/dist/agent/commands/agent_cli.d.ts +11 -1
  22. package/dist/agent/commands/agent_cli.js +295 -38
  23. package/dist/agent/commands/diff.js +4 -1
  24. package/dist/agent/commands/help.js +4 -1
  25. package/dist/agent/commands/plan.js +3 -1
  26. package/dist/agent/commands/session_redaction.d.ts +16 -0
  27. package/dist/agent/commands/session_redaction.js +77 -0
  28. package/dist/agent/commands/settings.js +144 -0
  29. package/dist/agent/commands/types.d.ts +5 -0
  30. package/dist/agent/commands/usage_spec.d.ts +4 -0
  31. package/dist/agent/commands/usage_spec.js +10 -4
  32. package/dist/agent/runtime/policy.d.ts +25 -0
  33. package/dist/agent/runtime/policy.js +154 -26
  34. package/dist/agent/runtime/source_verification.js +6 -2
  35. package/dist/agent/runtime/tool_runtime.js +81 -3
  36. package/dist/agent/tools/apply_patch.js +678 -131
  37. package/dist/agent/tools/bus_message.d.ts +26 -1
  38. package/dist/agent/tools/bus_message.js +126 -10
  39. package/dist/agent/tools/file.d.ts +16 -1
  40. package/dist/agent/tools/file.js +43 -5
  41. package/dist/agent/tools/index.d.ts +1 -1
  42. package/dist/agent/tools/index.js +1 -1
  43. package/dist/agent/tools/pane.js +5 -0
  44. package/dist/agent/tools/search.js +5 -1
  45. package/dist/agent/tools/supervision.js +16 -2
  46. package/dist/agent/tools/types.d.ts +22 -0
  47. package/dist/app/mirror_startup.d.ts +7 -5
  48. package/dist/app/mirror_startup.js +7 -5
  49. package/dist/app/navigator_mirrors.d.ts +20 -0
  50. package/dist/app/navigator_mirrors.js +36 -0
  51. package/dist/app/workspace_layout_controller.d.ts +11 -2
  52. package/dist/app/workspace_layout_controller.js +13 -2
  53. package/dist/batch/worktree.js +9 -1
  54. package/dist/cli_ratatui.d.ts +264 -12
  55. package/dist/cli_ratatui.js +1198 -103
  56. package/dist/config/types.d.ts +29 -0
  57. package/dist/desktop/daily/source_baseline.js +3 -1
  58. package/dist/diagnostics/session_export.d.ts +1 -0
  59. package/dist/diagnostics/session_export.js +229 -26
  60. package/dist/emulation/tool_adapters.js +42 -5
  61. package/dist/headless.js +24 -5
  62. package/dist/instance_registry.d.ts +7 -0
  63. package/dist/mcp/workspace_server.d.ts +12 -1
  64. package/dist/mcp/workspace_server.js +75 -8
  65. package/dist/panes/agent_cli.d.ts +60 -3
  66. package/dist/panes/agent_cli.js +169 -16
  67. package/dist/panes/agent_pane_sessions.d.ts +22 -0
  68. package/dist/panes/agent_pane_sessions.js +111 -0
  69. package/dist/panes/agent_panes.d.ts +77 -3
  70. package/dist/panes/agent_panes.js +199 -10
  71. package/dist/panes/agent_profiles.d.ts +5 -0
  72. package/dist/panes/agent_profiles.js +7 -0
  73. package/dist/panes/agent_resume.d.ts +134 -0
  74. package/dist/panes/agent_resume.js +155 -0
  75. package/dist/panes/agent_sessions/claude_head.d.ts +32 -0
  76. package/dist/panes/agent_sessions/claude_head.js +122 -0
  77. package/dist/panes/agent_sessions/claude_store.d.ts +59 -0
  78. package/dist/panes/agent_sessions/claude_store.js +223 -0
  79. package/dist/panes/agent_sessions/codex_head.d.ts +55 -0
  80. package/dist/panes/agent_sessions/codex_head.js +161 -0
  81. package/dist/panes/agent_sessions/codex_store.d.ts +43 -0
  82. package/dist/panes/agent_sessions/codex_store.js +187 -0
  83. package/dist/panes/agent_sessions/controller.d.ts +74 -0
  84. package/dist/panes/agent_sessions/controller.js +110 -0
  85. package/dist/panes/agent_sessions/cut_json.d.ts +14 -0
  86. package/dist/panes/agent_sessions/cut_json.js +109 -0
  87. package/dist/panes/agent_sessions/limits.d.ts +48 -0
  88. package/dist/panes/agent_sessions/limits.js +48 -0
  89. package/dist/panes/agent_sessions/scan.d.ts +49 -0
  90. package/dist/panes/agent_sessions/scan.js +86 -0
  91. package/dist/panes/agent_sessions/store_fs.d.ts +51 -0
  92. package/dist/panes/agent_sessions/store_fs.js +128 -0
  93. package/dist/panes/agent_sessions/stores.d.ts +36 -0
  94. package/dist/panes/agent_sessions/stores.js +89 -0
  95. package/dist/panes/agent_sessions/title.d.ts +9 -0
  96. package/dist/panes/agent_sessions/title.js +51 -0
  97. package/dist/panes/agent_sessions/types.d.ts +48 -0
  98. package/dist/panes/agent_sessions/types.js +2 -0
  99. package/dist/panes/reply_arbitrator.d.ts +39 -0
  100. package/dist/panes/reply_arbitrator.js +185 -0
  101. package/dist/panes/reply_modes.d.ts +291 -0
  102. package/dist/panes/reply_modes.js +598 -0
  103. package/dist/runtime_info.js +11 -2
  104. package/dist/session.js +4 -2
  105. package/dist/simulation/living/context.d.ts +8 -8
  106. package/dist/simulation/living/types.d.ts +5 -5
  107. package/dist/simulation/toolkit/dynamic_state.d.ts +1 -1
  108. package/dist/ui/ratatui/ipc_path.d.ts +5 -0
  109. package/dist/ui/ratatui/ipc_path.js +23 -3
  110. package/dist/ui/ratatui/pane_credential_broker.d.ts +23 -8
  111. package/dist/ui/ratatui/pane_credential_broker.js +49 -14
  112. package/dist/ui/ratatui/pane_relay.d.ts +5 -2
  113. package/dist/ui/ratatui/pane_relay.js +86 -19
  114. package/dist/ui/ratatui/process.js +3 -0
  115. package/dist/ui/ratatui/protocol.d.ts +50 -1
  116. package/dist/ui/ratatui/protocol.js +56 -0
  117. package/dist/ui/ratatui/relay_policy.d.ts +39 -0
  118. package/dist/ui/ratatui/relay_policy.js +94 -0
  119. package/dist/ui/ratatui/screen_privacy.d.ts +15 -0
  120. package/dist/ui/ratatui/screen_privacy.js +24 -0
  121. package/dist/ui/scrollback.js +8 -0
  122. package/dist/ui/widgets/agent_sessions_panel.d.ts +139 -0
  123. package/dist/ui/widgets/agent_sessions_panel.js +542 -0
  124. package/dist/ui/widgets/log_view.d.ts +5 -1
  125. package/dist/ui/widgets/log_view.js +40 -4
  126. package/dist/utils/atomic_write.js +9 -11
  127. package/dist/utils/canonical_path.d.ts +19 -0
  128. package/dist/utils/canonical_path.js +44 -0
  129. package/dist/utils/compaction.d.ts +2 -1
  130. package/dist/utils/compaction.js +3 -1
  131. package/dist/utils/git_directory_names.d.ts +51 -0
  132. package/dist/utils/git_directory_names.js +429 -0
  133. package/dist/utils/temporary_write_root.d.ts +6 -1
  134. package/dist/utils/temporary_write_root.js +32 -2
  135. package/dist/utils/tool_result_message.d.ts +4 -1
  136. package/dist/utils/tool_result_message.js +6 -2
  137. package/dist/web/bus_hold.d.ts +70 -0
  138. package/dist/web/bus_hold.js +118 -0
  139. package/dist/web/mirror_client.d.ts +7 -3
  140. package/dist/web/mirror_client.js +61 -23
  141. package/dist/web/mirror_route_gate.d.ts +40 -0
  142. package/dist/web/mirror_route_gate.js +71 -0
  143. package/dist/web/mirror_stream.d.ts +147 -22
  144. package/dist/web/mirror_stream.js +350 -83
  145. package/dist/web/pane_credentials.d.ts +32 -1
  146. package/dist/web/pane_credentials.js +62 -2
  147. package/dist/workspace_collision.js +11 -2
  148. package/dist/zlm-embed.mjs +940 -273
  149. package/package.json +39 -7
@@ -40,9 +40,12 @@ import { readDurableSessionImageSync, SessionMediaError } from '../session_media
40
40
  import { MemoryHistoryStore, JsonlHistoryStore } from './event_history_store.js';
41
41
  import { PaneRegistry } from './pane_registry.js';
42
42
  import { buildWorkspaceRuntimeSnapshot } from '../workspace_runtime.js';
43
+ import { parseReplyMode, ReplyModeError } from '../panes/reply_modes.js';
43
44
  import { ChildPublicationLedger } from './child_publication.js';
44
45
  import { createMirrorAuthenticatorFromEnv, mirrorSignInRequired, } from './mirror_authenticator.js';
45
46
  import { PANE_CREDENTIAL_HEADER, adoptPaneCredentialStore } from './pane_credentials.js';
47
+ import { asksForThePage, paneCredentialReaches, servedWithoutCredential, supervisionCommandScope } from './mirror_route_gate.js';
48
+ import { BusHold, heldNotice, holdFullRefusal, paneExitedRefusal, undeliveredNotice, } from './bus_hold.js';
46
49
  import { areMirrorCorsRequestHeadersAllowed, getMirrorOriginPolicy, MIRROR_CORS_ALLOW_HEADERS, rejectReasonForUnsafeMirrorWrite, } from './mirror_origin_policy.js';
47
50
  import { getAccountsPayload, getAccountsPayloadWithCodexStatus, applyAccountOp, getActiveAccountsSummary } from './accounts_mirror.js';
48
51
  import { onAccountsChanged } from '../agent/backends/account_events.js';
@@ -63,7 +66,7 @@ const MAX_INTERNAL_TOOL_IMAGES = 4;
63
66
  const MIRROR_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
64
67
  /** The bus member a person in the browser mirror speaks as ("User"); panes and the coordinator are 0 and up. */
65
68
  export const BROWSER_BUS_MEMBER_ID = -1;
66
- /** The bus member of the ZTC that runs the mirror ("Overseer", or a sim's coordinator): the parent of every pane on it. */
69
+ /** The bus member of the ZTC that runs the mirror (Main, or a sim's coordinator): the parent of every pane on it. */
67
70
  export const OVERSEER_BUS_MEMBER_ID = 0;
68
71
  const MIN_PANE_BUS_MEMBER_ID = OVERSEER_BUS_MEMBER_ID;
69
72
  const MAX_BUS_MEMBER_ID = 100_000;
@@ -83,6 +86,8 @@ function loadNativeDictation() {
83
86
  }
84
87
  return nativeDictationPromise;
85
88
  }
89
+ /** Who tells a sender on the bus that a message held for a pane was dropped: ZTC itself, which runs the bus (member 0). */
90
+ const HOLD_NOTICE_SENDER = { id: OVERSEER_BUS_MEMBER_ID, name: 'ZTC' };
86
91
  // Observation exposes terminal activity, never operator settings or plugin-specific state.
87
92
  const OBSERVER_EVENT_TYPES = new Set([
88
93
  'message', 'stream_start', 'stream_delta', 'stream_end', 'stream_reset', 'reasoning_delta', 'reasoning',
@@ -91,18 +96,6 @@ const OBSERVER_EVENT_TYPES = new Set([
91
96
  'queue_state', 'command_jobs', 'command_pane', 'hook_approval_request', 'widget_prompt', 'widget_select',
92
97
  'widget_questionnaire', 'widget_dismiss', 'context_progress_bar_config',
93
98
  ]);
94
- /**
95
- * The routes a pane's own credential reaches: its bus membership and its publications (each checked against the pane
96
- * it stands for), and input, which arrives as relayed (see MirrorInputVia). A colony cell asks its overseer for its own
97
- * restart (app/restart.ts). Everything else, the person's controls included, refuses a pane credential.
98
- */
99
- const PANE_CREDENTIAL_PATHS = ['/bus/connect', '/bus/send', '/pane-publication', '/pane-events'];
100
- const PANE_CREDENTIAL_EXACT_PATHS = new Set(['/pane-store-event', '/input', '/submit', '/pane-input', '/colony/agents/restart']);
101
- /**
102
- * What a workspace monitor's credential also reaches: the runtime it shows, the decisions it answers, and, for the
103
- * desktop's Status, the native pane its row drills into and back out of.
104
- */
105
- const WORKSPACE_MONITOR_PATHS = new Set(['/workspace/runtime', '/ask-user-answer', '/workspace/pane-action']);
106
99
  /** How long a request presenting a pane credential waits for its owner to hear the pane was created. */
107
100
  const PANE_CREDENTIAL_SETTLE_MS = 10_000;
108
101
  const OBSERVER_GET_PATHS = new Set([
@@ -163,14 +156,19 @@ function endStream(res) {
163
156
  export const MIRROR_REMOTE_PEER_REFUSAL = 'Mirror access is restricted to localhost when sign-in is off. '
164
157
  + 'To connect from another machine, start ZTC with ZTC_MIRROR_REQUIRE_AUTH=1 and open the link it prints.';
165
158
  /**
166
- * What a mirror that keeps pane controls for credentialed callers (setPaneControlCredentialRequired) answers one with
167
- * none: the browser has a credential when ZTC opened it with its link.
159
+ * What a mirror that answers only credentialed callers (setPaneControlCredentialRequired) answers a request with none,
160
+ * on every route but its page's scripts and icons and /health (servedWithoutCredential): the browser has a credential
161
+ * when ZTC opened it with its link. The page itself says it (MIRROR_NEEDS_LINK_PAGE).
168
162
  */
169
- export const MIRROR_PANE_CONTROL_NEEDS_LINK = 'This mirror opens panes and takes typing only from the link ZTC gives. '
170
- + 'Open it from ZTC with /mirror open.';
171
- /** Mux commands that open a pane, start one again or type into one: what such a mirror keeps for credentialed callers. */
172
- const PANE_OPENING_MUX_COMMANDS = new Set(['create_ztc_pane', 'create_command_pane', 'create_shell_pane',
173
- 'restart_pane', 'write_pane']);
163
+ export const MIRROR_NEEDS_LINK = 'This mirror answers only the link ZTC gives. Open it from ZTC with /mirror open.';
164
+ /**
165
+ * The page such a mirror shows a browser that asks for it with no credential: one that came without the link, or whose
166
+ * link and session expired (each lasts 12 hours). The web client's page would load and then be refused everything.
167
+ */
168
+ const MIRROR_NEEDS_LINK_PAGE = '<!doctype html><html><head><meta charset="utf-8"><title>ZTC Mirror</title>'
169
+ + '<meta name="viewport" content="width=device-width, initial-scale=1"></head>'
170
+ + '<body style="font-family: system-ui, sans-serif; margin: 3rem 1rem; text-align: center">'
171
+ + `<h1 style="font-size: 1.25rem">ZTC Mirror</h1><p>${MIRROR_NEEDS_LINK}</p></body></html>`;
174
172
  /** What an open mirror says once, as it starts. */
175
173
  export const MIRROR_OPEN_ACCESS_NOTICE = 'Only this computer can open this mirror. '
176
174
  + 'To let other machines connect, start ZTC with ZTC_MIRROR_REQUIRE_AUTH=1.';
@@ -239,6 +237,7 @@ export class MirrorStreamServer {
239
237
  // user-prompt channel) so the two can never be confused by content.
240
238
  paneControlCallback = null;
241
239
  agentPaneMessageCallback = null;
240
+ busMessageCheck = null;
242
241
  muxCommandCallback = null;
243
242
  supervisionCommandCallback = null;
244
243
  paneViewportCallback = null;
@@ -374,6 +373,10 @@ export class MirrorStreamServer {
374
373
  busCallbacks = new Map();
375
374
  // Message queues for members not yet connected
376
375
  busQueues = new Map();
376
+ /** An agent's messages for a ZTC agent's pane that hasn't joined the bus yet (see waitsForJoin). */
377
+ busHold = new BusHold();
378
+ /** Fires when the next held message comes due (armBusHoldExpiry). */
379
+ busHoldTimer = null;
377
380
  // Member names
378
381
  busMembers = new Map();
379
382
  // Global observers that see ALL bus traffic (for sim coordinator observability)
@@ -522,15 +525,21 @@ export class MirrorStreamServer {
522
525
  return this.host;
523
526
  }
524
527
  /**
525
- * Whether this mirror, while sign-in is off, opens panes and takes typing only from a caller with a credential: a
526
- * pane's own, a workspace monitor's, ZTC's own, or the browser session the link ZTC gives starts (getLaunchUrl then
527
- * carries one). For the desktop owner's mirror and a zmux owner's own silent one (see
528
+ * Whether this mirror, while sign-in is off, answers only a caller with a credential: a pane's own, a workspace
529
+ * monitor's, ZTC's own, or the browser session the link ZTC gives starts (getLaunchUrl then carries one). A caller
530
+ * with none gets 401 on every route but the page's scripts and icons, and /health (servedWithoutCredential), reads
531
+ * and the page itself included (which then says how to open the mirror), and no voice stream; /health tells it only
532
+ * that the mirror is up. For the desktop owner's mirror and a zmux owner's own silent one (see
528
533
  * mirrorPaneControlNeedsCredential), which nothing is meant to reach except through ZTC. Sign-in mode has its own
529
534
  * checks, which this leaves as they are.
530
535
  */
531
536
  setPaneControlCredentialRequired(required) {
532
537
  this.paneControlCredentialRequired = required;
533
538
  }
539
+ /** Whether this mirror answers only a caller with a credential (setPaneControlCredentialRequired). */
540
+ isPaneControlCredentialRequired() {
541
+ return this.paneControlCredentialRequired;
542
+ }
534
543
  /** What to tell the person once as this mirror starts about connecting from other machines; null for nothing. */
535
544
  remoteAccessNotice() {
536
545
  return this.mirrorAuthEnabled ? null : MIRROR_OPEN_ACCESS_NOTICE;
@@ -570,7 +579,7 @@ export class MirrorStreamServer {
570
579
  url.searchParams.set(key, value);
571
580
  }
572
581
  }
573
- // A mirror that keeps pane controls for credentialed callers gives its link one, so the browser ZTC opens keeps them.
582
+ // A mirror that answers only credentialed callers gives its link one, so the browser ZTC opens keeps everything.
574
583
  if (this.auth.enabled || this.operatorIsSuperuser || this.paneControlCredentialRequired) {
575
584
  url.searchParams.set(this.auth.queryTokenName, this.auth.issueToken({ ttlMs: 12 * 60 * 60 * 1000, canInspectPrompts: this.operatorIsSuperuser }));
576
585
  }
@@ -690,6 +699,13 @@ export class MirrorStreamServer {
690
699
  onAgentPaneMessage(cb) {
691
700
  this.agentPaneMessageCallback = cb;
692
701
  }
702
+ /**
703
+ * What Main says of a message a pane posts to /bus/send before it is delivered (BusMessageCheck): it refuses a reply
704
+ * mode that names an arbitrator the person didn't set up, and tells the sender what became of its mode.
705
+ */
706
+ onBusMessageCheck(cb) {
707
+ this.busMessageCheck = cb;
708
+ }
693
709
  onMuxCommand(cb) {
694
710
  this.muxCommandCallback = cb;
695
711
  }
@@ -777,6 +793,8 @@ export class MirrorStreamServer {
777
793
  }
778
794
  this.busQueues.delete(memberId);
779
795
  }
796
+ // And what was held for it until it joined.
797
+ this.busHold.release(memberId, (message) => { callback(message); return true; });
780
798
  return () => {
781
799
  // Only remove if the same callback is still registered; a re-registration
782
800
  // by a later run with the same memberId should not be wiped by the prior
@@ -796,9 +814,43 @@ export class MirrorStreamServer {
796
814
  return () => { this.busObservers = this.busObservers.filter(o => o !== callback); };
797
815
  }
798
816
  /**
799
- * Deliver a bus message to the appropriate target(s).
817
+ * Deliver a bus message to the appropriate target(s). With `agentsOnly` (what a pane's own credential sends), a message
818
+ * goes only to an agent: Main, every bus member ('all'), a pane on the bus or running ZTC, or a Claude Code or Codex
819
+ * pane, which the owner types it into with its sender. For any other pane (a shell, a command) nothing is delivered,
820
+ * queued or typed, and the answer is 'not_an_agent'. Whoever sends it, an agent's message for a ZTC agent's pane that
821
+ * hasn't joined the bus is held until it joins, never typed into the pane, and the answer is 'held' (waitsForJoin);
822
+ * once the renderer has reported that pane's program exited, nothing is held or typed and the answer is 'pane_exited'
823
+ * (forExitedZtc), until a ZTC that joins stands for the pane again. What a pane that can no longer join held is dropped
824
+ * first (dropUnjoinable), so no message for it goes ahead of one that waits.
800
825
  */
801
- deliverBusMessage(msg) {
826
+ deliverBusMessage(msg, options = {}) {
827
+ if (typeof msg.to === 'number' && msg.to !== OVERSEER_BUS_MEMBER_ID)
828
+ this.dropUnjoinable(msg.to);
829
+ if (this.forExitedZtc(msg))
830
+ return 'pane_exited';
831
+ if (options.agentsOnly && msg.to !== 'all' && !this.isZtcBusTarget(msg.to)) {
832
+ if (!this.agentPaneMessageCallback?.(msg.to, msg))
833
+ return 'not_an_agent';
834
+ for (const obs of this.busObservers) {
835
+ try {
836
+ obs(msg);
837
+ }
838
+ catch { /* ignore */ }
839
+ }
840
+ return 'delivered';
841
+ }
842
+ if (this.waitsForJoin(msg)) {
843
+ if (!this.busHold.hold(msg.to, msg, Date.now()))
844
+ return 'hold_full';
845
+ for (const obs of this.busObservers) {
846
+ try {
847
+ obs(msg);
848
+ }
849
+ catch { /* ignore */ }
850
+ }
851
+ this.armBusHoldExpiry();
852
+ return 'held';
853
+ }
802
854
  const tag = `[BusDeliver from=${msg.from.id}:${msg.from.name} to=${String(msg.to)} port=${this.port}]`;
803
855
  // Notify global observers (sim coordinator, etc.)
804
856
  for (const obs of this.busObservers) {
@@ -839,7 +891,7 @@ export class MirrorStreamServer {
839
891
  if (process.env.ZTC_DEBUG)
840
892
  process.stderr.write(`${tag} delivered via in-process callback\n`);
841
893
  cb(msg);
842
- return;
894
+ return 'delivered';
843
895
  }
844
896
  // Try SSE connection
845
897
  const conn = this.busConnections.get(targetId);
@@ -853,7 +905,7 @@ export class MirrorStreamServer {
853
905
  if (process.env.ZTC_DEBUG)
854
906
  process.stderr.write(`${tag} delivered via SSE connection\n`);
855
907
  conn.write(`data: ${JSON.stringify(msg)}\n\n`);
856
- return;
908
+ return 'delivered';
857
909
  }
858
910
  }
859
911
  // A pane running Claude Code or Codex has no bus connection: the owner
@@ -862,10 +914,10 @@ export class MirrorStreamServer {
862
914
  && this.agentPaneMessageCallback?.(targetId, msg)) {
863
915
  if (process.env.ZTC_DEBUG)
864
916
  process.stderr.write(`${tag} delivered to an agent CLI pane\n`);
865
- return;
917
+ return 'delivered';
866
918
  }
867
- // Headless ZTC pane children read input from their own stdin — they have no
868
- // bus callback or SSE connection.
919
+ // What a pane with no bus connection still reads from its terminal (an agent's
920
+ // message for a ZTC agent's pane waits for it to join instead: waitsForJoin).
869
921
  // A ztc_message from the overseer (bus member 0, the ZTC that opened the pane)
870
922
  // is an internal control command ({"__ztc_cmd":...}), NOT user text: deliver
871
923
  // it BARE via the control channel so the child classifies it as a control
@@ -878,7 +930,7 @@ export class MirrorStreamServer {
878
930
  if (process.env.ZTC_DEBUG)
879
931
  process.stderr.write(`${tag} delivered via pane-control callback (stdin, bare)\n`);
880
932
  this.paneControlCallback(targetId, msg.text);
881
- return;
933
+ return 'delivered';
882
934
  }
883
935
  // Everything else is user input, or another member's message — route to the
884
936
  // pane-input callback, which writes it to the child's stdin as a prompt envelope.
@@ -886,11 +938,123 @@ export class MirrorStreamServer {
886
938
  if (process.env.ZTC_DEBUG)
887
939
  process.stderr.write(`${tag} delivered via pane-input callback (stdin)\n`);
888
940
  this.paneInputCallback(targetId, { text: msg.text, attachments: msg.attachments || [] });
889
- return;
941
+ return 'delivered';
890
942
  }
891
943
  // Queue for later
892
944
  this.queueBusMessage(targetId, msg, tag);
893
945
  }
946
+ return 'delivered';
947
+ }
948
+ /** What the sender of a message for TO is told of its DELIVERY (deliverBusMessage), in the mirror's words. */
949
+ busSendResult(delivery, to) {
950
+ switch (delivery) {
951
+ case 'delivered':
952
+ return { ok: true };
953
+ case 'held':
954
+ return { ok: true, held: true, notice: heldNotice(to) };
955
+ case 'hold_full':
956
+ return { ok: false, status: 429, code: 'hold_full', error: holdFullRefusal(to) };
957
+ case 'not_an_agent':
958
+ // Said to an agent, workspace-mcp's in a Claude Code or Codex pane or a ZTC pane's own: each types with its tool.
959
+ return { ok: false, status: 409, code: 'not_an_agent', error: typeof to === 'number' && !this.panes.has(to)
960
+ ? `There's no pane ${to}.`
961
+ : `Pane ${String(to)} isn't an agent: a pane's messages go to Main, ZTC panes, and Claude Code or Codex panes. `
962
+ + 'To type into a shell or a command pane, use type_into_pane (write_terminal_pane in a ZTC pane).' };
963
+ case 'pane_exited':
964
+ return { ok: false, status: 409, code: 'pane_exited', error: paneExitedRefusal(to) };
965
+ }
966
+ }
967
+ /** Whether pane TO is Main, on the bus, or a ZTC agent's pane, which gets a message when it joins (isZtcAgentPane). */
968
+ isZtcBusTarget(to) {
969
+ return to === OVERSEER_BUS_MEMBER_ID || this.busCallbacks.has(to) || this.busConnections.has(to) || this.isZtcAgentPane(to);
970
+ }
971
+ /**
972
+ * Whether pane PANE_ID runs a ZTC agent: one its owner registered as a ZTC pane, or one whose credential is that of a
973
+ * ZTC that joins the bus (PaneCredentialStore.joinsBus), whatever its type: a native ZTC pane runs as a process pane,
974
+ * and a colony cell is never registered here.
975
+ */
976
+ isZtcAgentPane(paneId) {
977
+ return this.panes.get(paneId)?.paneType === 'ztc' || this.auth.paneCredentials.joinsBus(paneId);
978
+ }
979
+ /** Whether bus member ID is on the bus: in this process, or on a stream that is still open. */
980
+ isOnBus(id) {
981
+ if (this.busCallbacks.has(id))
982
+ return true;
983
+ const conn = this.busConnections.get(id);
984
+ return conn !== undefined && !conn.destroyed;
985
+ }
986
+ /**
987
+ * Does MSG wait for its pane to join the bus? An agent's message (ztc_message) for a pane that isn't on the bus does,
988
+ * from whoever sends it, when its credential is that of a ZTC that joins the bus as it starts
989
+ * (PaneCredentialStore.joinsBus: a ZTC pane in pane mode, a native ZTC pane, a colony cell): it is held and delivered as
990
+ * a message when the pane joins, never typed into the pane as though the person had typed it. A pane that joins no
991
+ * bus, as the browser mirror's own ZTC chat panes, which read stdin, still gets it there. The owner's control commands
992
+ * ({"__ztc_cmd":...} from the ZTC that opened the pane) still go on the pane's control channel, and input
993
+ * (user_input, context_only) to its terminal, as before.
994
+ */
995
+ waitsForJoin(msg) {
996
+ return this.isAgentMessageForPane(msg) && !this.isOnBus(msg.to) && this.auth.paneCredentials.joinsBus(msg.to);
997
+ }
998
+ /**
999
+ * Is MSG one that would wait for its pane to join the bus (waitsForJoin), for a ZTC pane off the bus whose program the
1000
+ * renderer has reported exited (PaneCredentialStore.ztcExited)? Nothing would join: its sender is told so at once, and
1001
+ * so is the sender of every later one, until the pane holds a credential of a ZTC that joins again, started again in
1002
+ * place by its owner or opened anew.
1003
+ */
1004
+ forExitedZtc(msg) {
1005
+ return this.isAgentMessageForPane(msg) && !this.isOnBus(msg.to) && this.auth.paneCredentials.ztcExited(msg.to);
1006
+ }
1007
+ /** Whether MSG is an agent's message (ztc_message) for one pane, not Main, and not the owner's control command. */
1008
+ isAgentMessageForPane(msg) {
1009
+ if (typeof msg.to !== 'number' || msg.to === OVERSEER_BUS_MEMBER_ID || msg.type !== 'ztc_message')
1010
+ return false;
1011
+ return !(msg.from.id === OVERSEER_BUS_MEMBER_ID && msg.text.startsWith('{"__ztc_cmd":'));
1012
+ }
1013
+ /**
1014
+ * Let go of what pane PANE_ID held once it can no longer join the bus, and tell its senders on the bus: it isn't on the
1015
+ * bus, and no credential that joins stands for it any more, since its program was started again in place without one
1016
+ * (the renderer's restart, or a replace a pane asked for through the pane relay). A message for it from then on is
1017
+ * answered as for any pane that holds no such credential, and never goes ahead of one that still waited.
1018
+ */
1019
+ dropUnjoinable(paneId) {
1020
+ if (this.isOnBus(paneId) || this.auth.paneCredentials.joinsBus(paneId))
1021
+ return;
1022
+ this.dropHeld(this.busHold.drop(paneId), 'unjoinable');
1023
+ }
1024
+ /** Drop each held message whose pane hasn't joined when it comes due (BusHold's HOLD_DEADLINE_MS). */
1025
+ armBusHoldExpiry() {
1026
+ if (this.busHoldTimer)
1027
+ clearTimeout(this.busHoldTimer);
1028
+ this.busHoldTimer = null;
1029
+ const next = this.busHold.nextDeadline();
1030
+ if (next === null)
1031
+ return;
1032
+ this.busHoldTimer = setTimeout(() => {
1033
+ this.busHoldTimer = null;
1034
+ this.dropHeld(this.busHold.expire(Date.now()), 'expired');
1035
+ this.armBusHoldExpiry();
1036
+ }, Math.max(0, next - Date.now()));
1037
+ this.busHoldTimer.unref?.();
1038
+ }
1039
+ /**
1040
+ * Tell each sender on the bus (a ZTC pane, Main) of its DROPPED messages and why, in one message from ZTC for each
1041
+ * pane they waited for. A sender off the bus (a Claude Code or Codex pane, the browser member) was told its message was
1042
+ * held and hears nothing more; nothing is typed into a pane.
1043
+ */
1044
+ dropHeld(dropped, reason) {
1045
+ const counts = new Map();
1046
+ for (const { paneId, message } of dropped) {
1047
+ const key = `${message.from.id}:${paneId}`;
1048
+ const entry = counts.get(key) ?? { sender: message.from.id, paneId, count: 0 };
1049
+ entry.count++;
1050
+ counts.set(key, entry);
1051
+ }
1052
+ for (const { sender, paneId, count } of counts.values()) {
1053
+ if (sender === paneId || !this.isOnBus(sender))
1054
+ continue;
1055
+ this.deliverBusMessage({ id: randomUUID(), from: HOLD_NOTICE_SENDER, to: sender, type: 'ztc_message',
1056
+ text: undeliveredNotice(paneId, count, reason) });
1057
+ }
894
1058
  }
895
1059
  queueBusMessage(targetId, msg, tag) {
896
1060
  if (!this.isSafeBusId(targetId, false)) {
@@ -954,6 +1118,7 @@ export class MirrorStreamServer {
954
1118
  for (const paneId of removedIds) {
955
1119
  this.childPublications.invalidate(paneId);
956
1120
  this.retireQuestion(paneId);
1121
+ this.dropHeld(this.busHold.drop(paneId), 'closed');
957
1122
  }
958
1123
  // Remove stale pane_info events and events referencing removed pane IDs
959
1124
  // so reconnecting browsers don't see ghost panes or stale messages. This drop
@@ -993,6 +1158,9 @@ export class MirrorStreamServer {
993
1158
  * Unregister a pane and notify browser.
994
1159
  */
995
1160
  unregisterPane(paneId) {
1161
+ // A closed pane takes what was held for it with it, and its senders on the bus hear so: a pane that opens later never
1162
+ // gets another's messages.
1163
+ this.dropHeld(this.busHold.drop(paneId), 'closed');
996
1164
  this.attention.markStale(paneId);
997
1165
  this.childPublications.invalidate(paneId);
998
1166
  this.retireQuestion(paneId);
@@ -1010,6 +1178,13 @@ export class MirrorStreamServer {
1010
1178
  }
1011
1179
  }
1012
1180
  this.panes.applyState(state);
1181
+ // A ZTC pane whose program the renderer reports exited won't join the bus: what waited for it goes now, and its
1182
+ // senders on the bus hear why, rather than two minutes later. (No credential stands for Main, pane 0.)
1183
+ for (const pane of state.panes) {
1184
+ if (pane.is_alive === false && this.auth.paneCredentials.programExited(pane.id)) {
1185
+ this.dropHeld(this.busHold.drop(pane.id), 'exited');
1186
+ }
1187
+ }
1013
1188
  this.publishPaneInfo();
1014
1189
  }
1015
1190
  /**
@@ -1089,6 +1264,12 @@ export class MirrorStreamServer {
1089
1264
  // Detach the module-global accounts listener so it doesn't outlive the server.
1090
1265
  this.accountsUnsub?.();
1091
1266
  this.accountsUnsub = null;
1267
+ // What waits for a pane is dropped, and a sender on the bus hears so before its stream ends: a mirror started again
1268
+ // holds nothing.
1269
+ if (this.busHoldTimer)
1270
+ clearTimeout(this.busHoldTimer);
1271
+ this.busHoldTimer = null;
1272
+ this.dropHeld(this.busHold.dropAll(), 'mirror_stopped');
1092
1273
  // End each pane's bus stream and each browser's event stream, and the connection each came on, so every client
1093
1274
  // connects again to whatever listens on the port next: a pane's mirror client rejoins the bus of the mirror ZTC
1094
1275
  // starts again there (/mirror stop, then /mirror start), and a browser reconnects. Left open, they stayed with this
@@ -2393,6 +2574,13 @@ export class MirrorStreamServer {
2393
2574
  const fallbackRoot = resolve(here, '..', '..', '..', '..');
2394
2575
  return resolve(fallbackRoot, 'zerg', 'zaai', 'domains', 'zcloud', 'modules', 'cv', 'cv_runner', 'state.json');
2395
2576
  }
2577
+ /** POST /mirror/publish (a CV publisher's events, behind its own secret) or GET /cv/snapshot (the public CV artifact). */
2578
+ async handleCvRoute(url, req, res) {
2579
+ if (url.pathname === '/mirror/publish')
2580
+ await this.handleMirrorPublish(req, res);
2581
+ else
2582
+ await this.handleCvSnapshot(req, res);
2583
+ }
2396
2584
  /**
2397
2585
  * GET /cv/snapshot — replaces the old Django /api/cv/snapshot endpoint.
2398
2586
  * Returns {schema_version, scenarios:[…]} sorted by (use_case, scenario, seed).
@@ -2638,17 +2826,28 @@ export class MirrorStreamServer {
2638
2826
  return auth.source === 'browser' && !this.mirrorAuthEnabled && auth.session?.canControl !== false && !auth.session?.shareId;
2639
2827
  }
2640
2828
  /**
2641
- * Refuse, answering RES, a caller with no credential that would open a pane or type into one (/input, /submit,
2642
- * /pane-input, /broadcast, /bus/send and PANE_OPENING_MUX_COMMANDS), on a mirror that keeps those for credentialed
2643
- * callers (setPaneControlCredentialRequired). True when it refused. Answers to what a pane already asks
2644
- * (/ask-user-answer, /widget-answer, /attention/action, /hook-approval) are not refused here yet: they wait for the
2645
- * approval model outside access gets.
2829
+ * Is AUTH a request with no credential to a mirror that answers only credentialed callers
2830
+ * (setPaneControlCredentialRequired)? Sign-in refuses a request with no credential itself.
2831
+ */
2832
+ holdsNoCredentialHere(auth) {
2833
+ return auth.source === 'open' && this.paneControlCredentialRequired;
2834
+ }
2835
+ /**
2836
+ * Refuse, answering RES with 401, a request with no credential on a mirror that answers only credentialed callers
2837
+ * (setPaneControlCredentialRequired), unless it asks for the page's scripts and icons, or /health
2838
+ * (servedWithoutCredential). The page itself is refused with a page saying how to open the mirror, anything else with
2839
+ * the same words in JSON. True when it refused. Sign-in refuses a request with no credential itself.
2646
2840
  */
2647
- refusesUncredentialedPaneControl(auth, res) {
2648
- if (!this.paneControlCredentialRequired || this.mirrorAuthEnabled || auth.source !== 'open')
2841
+ refusesUncredentialedRequest(auth, method, pathname, res) {
2842
+ if (!this.holdsNoCredentialHere(auth) || servedWithoutCredential(method, pathname))
2649
2843
  return false;
2650
- res.writeHead(403, { 'Content-Type': 'application/json' });
2651
- res.end(JSON.stringify({ ok: false, error: MIRROR_PANE_CONTROL_NEEDS_LINK }));
2844
+ if (asksForThePage(method, pathname)) {
2845
+ res.writeHead(401, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
2846
+ res.end(MIRROR_NEEDS_LINK_PAGE);
2847
+ return true;
2848
+ }
2849
+ res.writeHead(401, { 'Content-Type': 'application/json' });
2850
+ res.end(JSON.stringify({ ok: false, error: MIRROR_NEEDS_LINK }));
2652
2851
  return true;
2653
2852
  }
2654
2853
  /**
@@ -2669,28 +2868,39 @@ export class MirrorStreamServer {
2669
2868
  return false;
2670
2869
  }
2671
2870
  }
2871
+ /**
2872
+ * May PANE's own credential send COMMAND to /supervision/command? Only for its own pane's sessions: it lists them as
2873
+ * their supervisor, starts one as the supervisor of a pane its own pane opened through the pane relay (as the pane's
2874
+ * credential records: PaneCredentialStore.openerOf), never of a pane ZTC, the person or another pane opened, and stops
2875
+ * one it supervises (asking the owner which those are, since a stop names only its target). A session is kept by the
2876
+ * pane it supervises, so a start for another pane's would take that session over.
2877
+ */
2878
+ async supervisesOwnSessions(pane, command) {
2879
+ const scope = supervisionCommandScope(command);
2880
+ if (scope === null)
2881
+ return false;
2882
+ if (scope !== 'target') {
2883
+ return scope.supervisor === pane.paneId
2884
+ && (scope.target === undefined || this.auth.paneCredentials.openerOf(scope.target) === pane.paneId);
2885
+ }
2886
+ const own = await this.supervisionCommandCallback({ type: 'list_sessions', supervisor_pane_id: pane.paneId });
2887
+ const target = command.target_pane_id;
2888
+ return own.ok && (own.sessions ?? []).some(session => session.target_pane_id === target);
2889
+ }
2672
2890
  /** Where input this caller posts to /input, /submit or /pane-input came from (see MirrorInputVia). */
2673
2891
  inputVia(auth) {
2674
2892
  return this.speaksForPerson(auth) ? 'browser' : 'relayed';
2675
2893
  }
2676
- /** The bus member that input this caller posts for another pane speaks as: the person only for the person. */
2894
+ /**
2895
+ * The bus member that input this caller posts for another pane speaks as: the person only for the person, member 0
2896
+ * for ZTC's own process, by the name it joined the bus with ("Main" or its /rename name), "Main" until it has. A
2897
+ * pane's own credential posts no input (paneCredentialReaches).
2898
+ */
2677
2899
  inputSender(auth) {
2678
- if (auth.source === 'pane' && auth.pane) {
2679
- const id = auth.pane.paneId;
2680
- return { id, name: this.busMembers.get(id) ?? this.panes.get(id)?.title ?? `ZTC ${id}` };
2681
- }
2682
2900
  if (!this.speaksForPerson(auth))
2683
- return { id: OVERSEER_BUS_MEMBER_ID, name: 'Overseer' };
2901
+ return { id: OVERSEER_BUS_MEMBER_ID, name: this.busMembers.get(OVERSEER_BUS_MEMBER_ID) ?? 'Main' };
2684
2902
  return { id: BROWSER_BUS_MEMBER_ID, name: 'User' };
2685
2903
  }
2686
- /** May a pane's own credential use this route? (See PANE_CREDENTIAL_PATHS.) */
2687
- paneCredentialReaches(pane, pathname) {
2688
- if (PANE_CREDENTIAL_EXACT_PATHS.has(pathname))
2689
- return true;
2690
- if (PANE_CREDENTIAL_PATHS.some(path => pathname === path || pathname.startsWith(`${path}/`)))
2691
- return true;
2692
- return pane.scope === 'workspace-monitor' && WORKSPACE_MONITOR_PATHS.has(pathname);
2693
- }
2694
2904
  /**
2695
2905
  * May this principal mutate the account pool (POST /mirror/account)? Those ops
2696
2906
  * have real host side effects — `login` spawns an OAuth flow on the ztc host;
@@ -2838,6 +3048,12 @@ export class MirrorStreamServer {
2838
3048
  this.rejectUpgrade(socket, 403, 'Forbidden', { error: MIRROR_REMOTE_PEER_REFUSAL });
2839
3049
  return;
2840
3050
  }
3051
+ // A mirror that answers only credentialed callers takes no voice stream from a caller with none.
3052
+ if (this.paneControlCredentialRequired
3053
+ && this.auth.authenticate({ headers: req.headers, url, cookies: this.parseCookies(req) }).source === 'open') {
3054
+ this.rejectUpgrade(socket, 401, 'Unauthorized', { ok: false, error: MIRROR_NEEDS_LINK });
3055
+ return;
3056
+ }
2841
3057
  if (!this.authenticateUpgrade(req, url)) {
2842
3058
  this.rejectUpgrade(socket, 401, 'Unauthorized');
2843
3059
  return;
@@ -3116,14 +3332,12 @@ export class MirrorStreamServer {
3116
3332
  return;
3117
3333
  }
3118
3334
  // Server-to-server CV publishers use their own shared-secret header and
3119
- // should not require a browser mirror session cookie.
3120
- if (url.pathname === '/mirror/publish' && req.method === 'POST') {
3121
- await this.handleMirrorPublish(req, res);
3122
- return;
3123
- }
3124
- // The public CV artifact is separate from session access.
3125
- if (url.pathname === '/cv/snapshot' && req.method === 'GET') {
3126
- await this.handleCvSnapshot(req, res);
3335
+ // should not require a browser mirror session cookie. A mirror that answers
3336
+ // only credentialed callers takes them only past its credential check, below.
3337
+ const cvRoute = (url.pathname === '/mirror/publish' && req.method === 'POST')
3338
+ || (url.pathname === '/cv/snapshot' && req.method === 'GET');
3339
+ if (cvRoute && !this.paneControlCredentialRequired) {
3340
+ await this.handleCvRoute(url, req, res);
3127
3341
  return;
3128
3342
  }
3129
3343
  // A pane's program can start before its owner hears the renderer created the pane: wait (briefly) for the
@@ -3135,7 +3349,9 @@ export class MirrorStreamServer {
3135
3349
  const auth = this.authenticateRequest(req, url, res);
3136
3350
  if (!auth.ok)
3137
3351
  return;
3138
- if (auth.source === 'pane' && !this.paneCredentialReaches(auth.pane, url.pathname)) {
3352
+ if (this.refusesUncredentialedRequest(auth, req.method, url.pathname, res))
3353
+ return;
3354
+ if (auth.source === 'pane' && !paneCredentialReaches(auth.pane, url.pathname)) {
3139
3355
  res.writeHead(403, { 'Content-Type': 'application/json' });
3140
3356
  res.end(JSON.stringify({ error: 'A pane credential cannot use this endpoint.' }));
3141
3357
  return;
@@ -3146,6 +3362,10 @@ export class MirrorStreamServer {
3146
3362
  res.end(JSON.stringify({ error: 'Read-only observation does not permit this operation.' }));
3147
3363
  return;
3148
3364
  }
3365
+ if (cvRoute) {
3366
+ await this.handleCvRoute(url, req, res);
3367
+ return;
3368
+ }
3149
3369
  // Notification (sfx) on/off from a mirror client's bell. Applies the change
3150
3370
  // to the CLI config silently (no transcript echo); the CLI handler re-pushes
3151
3371
  // via setSfxConfig() which broadcasts 'sfx_config' back to all clients.
@@ -3736,8 +3956,6 @@ export class MirrorStreamServer {
3736
3956
  }
3737
3957
  // Handle input for the overseer (single-pane or parent pane): the browser's, or relayed by a ZTC process or pane
3738
3958
  if ((url.pathname === '/input' || url.pathname === '/submit') && req.method === 'POST') {
3739
- if (this.refusesUncredentialedPaneControl(auth, res))
3740
- return;
3741
3959
  try {
3742
3960
  const input = await this.readMessageInput(req);
3743
3961
  if (input.correlation_id !== undefined) {
@@ -3764,8 +3982,6 @@ export class MirrorStreamServer {
3764
3982
  // /broadcast's, never as the person's in the browser mirror (see MirrorInputVia). A ZTC pane gets it on its stdin,
3765
3983
  // all of which it treats as relayed already.
3766
3984
  if (url.pathname === '/broadcast' && req.method === 'POST') {
3767
- if (this.refusesUncredentialedPaneControl(auth, res))
3768
- return;
3769
3985
  try {
3770
3986
  const parsed = await this.readJsonBody(req, MAX_MIRROR_TEXT_INPUT_BYTES);
3771
3987
  const cleanText = this.sanitizeMirrorText(parsed.text).replace(/\n$/, '');
@@ -4422,27 +4638,41 @@ export class MirrorStreamServer {
4422
4638
  }
4423
4639
  this.busQueues.delete(memberId);
4424
4640
  }
4641
+ // And what was held for it until it joined, in the order it was sent; a stream that ends first leaves the rest held.
4642
+ this.busHold.release(memberId, (message) => {
4643
+ if (res.destroyed)
4644
+ return false;
4645
+ res.write(`data: ${JSON.stringify(message)}\n\n`);
4646
+ return true;
4647
+ });
4425
4648
  req.on('close', () => {
4426
4649
  this.busConnections.delete(memberId);
4427
4650
  this.busMembers.delete(memberId);
4428
4651
  });
4429
4652
  return;
4430
4653
  }
4431
- // Post a message to the bus. Every message types into its target (Main takes the person's as their own browser
4432
- // input), so a mirror that takes typing only from credentialed callers refuses one with none, as /input does.
4654
+ // Post a message to the bus (Main takes the person's as their own browser input): delivered (200), held for a ZTC
4655
+ // agent's pane until it joins (202), or refused; a mirror that answers only credentialed callers has already refused
4656
+ // one with no credential.
4433
4657
  if (url.pathname.startsWith('/bus/send') && req.method === 'POST') {
4434
- if (this.refusesUncredentialedPaneControl(auth, res))
4435
- return;
4436
4658
  try {
4437
4659
  const parsed = await this.readJsonBody(req, MAX_MIRROR_TEXT_INPUT_BYTES);
4438
4660
  const from = this.parseBusMember(parsed.from);
4439
4661
  const to = this.parseBusTarget(parsed.to);
4440
- const type = this.parseBusMessageType(parsed.type);
4662
+ // A pane's own credential sends messages, and nothing else: one with no type is a message, never input.
4663
+ const fromPane = auth.source === 'pane';
4664
+ const type = fromPane && (parsed.type === undefined || parsed.type === null || parsed.type === '')
4665
+ ? 'ztc_message' : this.parseBusMessageType(parsed.type);
4441
4666
  if (!from || to === null || type === null || !this.isKnownBusSender(from.id)) {
4442
4667
  res.writeHead(400, { 'Content-Type': 'application/json' });
4443
4668
  res.end(JSON.stringify({ error: 'Invalid bus message' }));
4444
4669
  return;
4445
4670
  }
4671
+ if (fromPane && type !== 'ztc_message') {
4672
+ res.writeHead(403, { 'Content-Type': 'application/json' });
4673
+ res.end(JSON.stringify({ ok: false, error: 'A pane\'s credential sends messages (ztc_message) only, never input or context.' }));
4674
+ return;
4675
+ }
4446
4676
  // The sender is who the caller authenticated as, not who the body says: refused, nothing is delivered.
4447
4677
  if (!this.mayClaimBusMember(auth, from.id)) {
4448
4678
  res.writeHead(403, { 'Content-Type': 'application/json' });
@@ -4450,16 +4680,47 @@ export class MirrorStreamServer {
4450
4680
  ? 'Internal mirror token required' : 'This credential cannot send as that bus member.' }));
4451
4681
  return;
4452
4682
  }
4683
+ // A reply mode travels with a message; one that isn't a mode is refused, and nothing is delivered.
4684
+ let replyMode;
4685
+ if (parsed.replyMode !== undefined && parsed.replyMode !== null) {
4686
+ try {
4687
+ replyMode = parseReplyMode(parsed.replyMode);
4688
+ }
4689
+ catch (error) {
4690
+ if (!(error instanceof ReplyModeError))
4691
+ throw error;
4692
+ res.writeHead(400, { 'Content-Type': 'application/json' });
4693
+ res.end(JSON.stringify({ ok: false, code: 'reply_mode', error: error.message }));
4694
+ return;
4695
+ }
4696
+ }
4453
4697
  const msg = {
4454
4698
  id: randomUUID(),
4455
4699
  from,
4456
4700
  to,
4457
4701
  type,
4458
4702
  text: this.sanitizeMirrorText(parsed.text),
4703
+ ...(replyMode === undefined ? {} : { replyMode }),
4459
4704
  };
4460
- this.deliverBusMessage(msg);
4461
- res.writeHead(200, { 'Content-Type': 'application/json' });
4462
- res.end(JSON.stringify({ ok: true, messageId: msg.id }));
4705
+ // What Main says of it first: a refusal delivers nothing.
4706
+ const checked = this.busMessageCheck?.(msg) ?? {};
4707
+ if ('refuse' in checked) {
4708
+ res.writeHead(400, { 'Content-Type': 'application/json' });
4709
+ res.end(JSON.stringify({ ok: false, code: 'reply_mode', error: checked.refuse }));
4710
+ return;
4711
+ }
4712
+ const sent = this.busSendResult(this.deliverBusMessage(msg, { agentsOnly: fromPane }), to);
4713
+ if (!sent.ok) {
4714
+ res.writeHead(sent.status, { 'Content-Type': 'application/json' });
4715
+ res.end(JSON.stringify({ ok: false, code: sent.code, error: sent.error }));
4716
+ return;
4717
+ }
4718
+ // Held: taken, not yet delivered, which the sender's tool says in the mirror's words. A notice of Main's about the
4719
+ // message (what became of its reply mode) goes with either answer.
4720
+ const notice = checked.notice ? { replyNotice: checked.notice } : {};
4721
+ res.writeHead(sent.held ? 202 : 200, { 'Content-Type': 'application/json' });
4722
+ res.end(JSON.stringify(sent.held ? { ok: true, held: true, messageId: msg.id, notice: sent.notice, ...notice }
4723
+ : { ok: true, messageId: msg.id, ...notice }));
4463
4724
  }
4464
4725
  catch (error) {
4465
4726
  this.writeJsonError(res, error);
@@ -4470,8 +4731,6 @@ export class MirrorStreamServer {
4470
4731
  // overseer as relayed and another pane as a message from the caller's own bus member (see inputVia, inputSender).
4471
4732
  // Legacy endpoint — now routes through the bus for child panes
4472
4733
  if (url.pathname === '/pane-input' && req.method === 'POST') {
4473
- if (this.refusesUncredentialedPaneControl(auth, res))
4474
- return;
4475
4734
  try {
4476
4735
  // Parse text + image attachments + pane_id from JSON or multipart upload.
4477
4736
  const input = await this.readMessageInput(req);
@@ -4570,9 +4829,6 @@ export class MirrorStreamServer {
4570
4829
  }
4571
4830
  try {
4572
4831
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
4573
- if (PANE_OPENING_MUX_COMMANDS.has(String(parsed?.type))
4574
- && this.refusesUncredentialedPaneControl(auth, res))
4575
- return;
4576
4832
  const result = await this.muxCommandCallback(parsed);
4577
4833
  res.writeHead(200, { 'Content-Type': 'application/json' });
4578
4834
  res.end(JSON.stringify(result));
@@ -4590,6 +4846,11 @@ export class MirrorStreamServer {
4590
4846
  }
4591
4847
  try {
4592
4848
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
4849
+ if (auth.source === 'pane' && !(await this.supervisesOwnSessions(auth.pane, parsed))) {
4850
+ res.writeHead(403, { 'Content-Type': 'application/json' });
4851
+ res.end(JSON.stringify({ ok: false, error: 'A pane\'s credential reaches only its own pane\'s supervision sessions.' }));
4852
+ return;
4853
+ }
4593
4854
  const result = await this.supervisionCommandCallback(parsed);
4594
4855
  res.writeHead(result.ok ? 200 : 400, { 'Content-Type': 'application/json' });
4595
4856
  res.end(JSON.stringify(result));
@@ -4646,8 +4907,14 @@ export class MirrorStreamServer {
4646
4907
  return;
4647
4908
  }
4648
4909
  if (url.pathname === '/health' && req.method === 'GET') {
4649
- const runtime = this.runtimeStatsProvider ? this.runtimeStatsProvider() : {};
4650
4910
  res.writeHead(200, { 'Content-Type': 'application/json' });
4911
+ // A mirror that answers only credentialed callers tells one with none that it is up, and nothing of the session:
4912
+ // the runtime names the accounts in use, the route and what the session cost.
4913
+ if (this.holdsNoCredentialHere(auth)) {
4914
+ res.end(JSON.stringify({ ok: true }));
4915
+ return;
4916
+ }
4917
+ const runtime = this.runtimeStatsProvider ? this.runtimeStatsProvider() : {};
4651
4918
  res.end(JSON.stringify({ clients: this.getViewerCount(), hosted: this.hostedMode, ok: true, runtime }));
4652
4919
  return;
4653
4920
  }