@zergai/ztc 0.26.2-dev.202611210149 → 0.26.4-dev.202611231953

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 (275) hide show
  1. package/README.md +590 -28
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/zmux-linux-x64 +0 -0
  4. package/bin/ztc-audio-darwin-arm64 +0 -0
  5. package/bin/ztc-capture-darwin-arm64 +0 -0
  6. package/bin/ztc-tui-darwin-arm64 +0 -0
  7. package/bin/ztc-tui-linux-x64 +0 -0
  8. package/bin/zterm-darwin-arm64 +2 -2
  9. package/dist/App.js +18 -1
  10. package/dist/agent/agent.d.ts +25 -1
  11. package/dist/agent/agent.js +26 -1
  12. package/dist/agent/attached_images.d.ts +58 -0
  13. package/dist/agent/attached_images.js +145 -0
  14. package/dist/agent/backends/anthropic.d.ts +14 -0
  15. package/dist/agent/backends/anthropic.js +49 -2
  16. package/dist/agent/backends/codex_app_server.d.ts +3 -1
  17. package/dist/agent/backends/codex_app_server.js +9 -6
  18. package/dist/agent/backends/codex_auth.js +3 -0
  19. package/dist/agent/backends/gemini.js +3 -0
  20. package/dist/agent/backends/host_effort_policy.js +14 -2
  21. package/dist/agent/backends/http_error.d.ts +17 -0
  22. package/dist/agent/backends/http_error.js +50 -1
  23. package/dist/agent/backends/index.js +2 -1
  24. package/dist/agent/backends/model_redirect.d.ts +47 -0
  25. package/dist/agent/backends/model_redirect.js +97 -0
  26. package/dist/agent/backends/openai_compatible.js +5 -0
  27. package/dist/agent/backends/openai_responses.d.ts +9 -1
  28. package/dist/agent/backends/openai_responses.js +21 -12
  29. package/dist/agent/backends/prompt_cache.d.ts +8 -0
  30. package/dist/agent/backends/prompt_cache.js +10 -0
  31. package/dist/agent/backends/provider_ids.d.ts +1 -1
  32. package/dist/agent/backends/provider_ids.js +1 -1
  33. package/dist/agent/backends/types.d.ts +8 -0
  34. package/dist/agent/backends/zerg-api.js +5 -1
  35. package/dist/agent/backends/zrouter_stream.d.ts +75 -9
  36. package/dist/agent/backends/zrouter_stream.js +250 -49
  37. package/dist/agent/commands/config.js +51 -4
  38. package/dist/agent/commands/connect.js +20 -0
  39. package/dist/agent/commands/credential_status.js +5 -3
  40. package/dist/agent/commands/debug.js +3 -0
  41. package/dist/agent/commands/diff.js +9 -5
  42. package/dist/agent/commands/emulation.js +7 -1
  43. package/dist/agent/commands/inbox.js +4 -3
  44. package/dist/agent/commands/mcp.js +3 -0
  45. package/dist/agent/commands/models.js +20 -3
  46. package/dist/agent/commands/permissions.js +16 -2
  47. package/dist/agent/commands/provider_selection.js +13 -6
  48. package/dist/agent/commands/settings.js +15 -4
  49. package/dist/agent/commands/status.js +23 -1
  50. package/dist/agent/commands/types.d.ts +34 -3
  51. package/dist/agent/commands/update.d.ts +2 -1
  52. package/dist/agent/commands/update.js +8 -3
  53. package/dist/agent/commands/zerg.d.ts +6 -0
  54. package/dist/agent/commands/zerg.js +152 -28
  55. package/dist/agent/commands/ztc_pane.js +8 -5
  56. package/dist/agent/factory.js +22 -4
  57. package/dist/agent/request_encoder.js +11 -2
  58. package/dist/agent/runtime/command_jobs.js +16 -1
  59. package/dist/agent/runtime/command_panes.js +4 -1
  60. package/dist/agent/runtime/execution_context.d.ts +8 -1
  61. package/dist/agent/runtime/execution_context.js +8 -2
  62. package/dist/agent/runtime/policy.d.ts +66 -5
  63. package/dist/agent/runtime/policy.js +161 -33
  64. package/dist/agent/runtime/remote_broker_transport.d.ts +7 -0
  65. package/dist/agent/runtime/remote_broker_transport.js +33 -3
  66. package/dist/agent/runtime/remote_resource_errors.d.ts +7 -0
  67. package/dist/agent/runtime/remote_resource_errors.js +10 -0
  68. package/dist/agent/runtime/remote_resources.d.ts +1 -1
  69. package/dist/agent/runtime/remote_resources.js +7 -3
  70. package/dist/agent/runtime/source_verification.js +15 -12
  71. package/dist/agent/runtime/tool_runtime.js +165 -58
  72. package/dist/agent/runtime/verifier_capture.d.ts +1 -1
  73. package/dist/agent/runtime/verifier_capture.js +6 -0
  74. package/dist/agent/runtime/work_base.js +46 -14
  75. package/dist/agent/tools/adaptation.js +29 -12
  76. package/dist/agent/tools/apply_patch.js +62 -5
  77. package/dist/agent/tools/background.js +2 -0
  78. package/dist/agent/tools/benchmark_cpu.js +2 -0
  79. package/dist/agent/tools/bus_message.d.ts +4 -2
  80. package/dist/agent/tools/bus_message.js +21 -3
  81. package/dist/agent/tools/delegate.js +2 -0
  82. package/dist/agent/tools/file.d.ts +12 -1
  83. package/dist/agent/tools/file.js +92 -11
  84. package/dist/agent/tools/lsp.d.ts +12 -0
  85. package/dist/agent/tools/lsp.js +61 -5
  86. package/dist/agent/tools/pane.js +20 -45
  87. package/dist/agent/tools/project_context.js +5 -2
  88. package/dist/agent/tools/routine.js +20 -4
  89. package/dist/agent/tools/screenshot.d.ts +8 -0
  90. package/dist/agent/tools/screenshot.js +39 -25
  91. package/dist/agent/tools/search.js +31 -3
  92. package/dist/agent/tools/shell.js +7 -1
  93. package/dist/agent/tools/supervision.js +6 -0
  94. package/dist/agent/tools/types.d.ts +18 -0
  95. package/dist/agent/tools/zerg.js +15 -19
  96. package/dist/agent/tools/ztc_command.d.ts +15 -4
  97. package/dist/agent/tools/ztc_command.js +48 -34
  98. package/dist/app/agent_runner.js +8 -6
  99. package/dist/app/conversation_compaction.d.ts +6 -3
  100. package/dist/app/conversation_compaction.js +6 -3
  101. package/dist/app/tool_callbacks.js +1 -0
  102. package/dist/audio/sfx.js +6 -0
  103. package/dist/batch/worktree.js +22 -10
  104. package/dist/board/client.js +2 -1
  105. package/dist/cli_main.d.ts +1 -0
  106. package/dist/cli_main.js +141 -45
  107. package/dist/cli_ratatui.d.ts +49 -4
  108. package/dist/cli_ratatui.js +355 -79
  109. package/dist/conductor_branch.js +4 -1
  110. package/dist/config/host_credentials.d.ts +157 -0
  111. package/dist/config/host_credentials.js +589 -0
  112. package/dist/config/model_pin.d.ts +111 -0
  113. package/dist/config/model_pin.js +182 -0
  114. package/dist/config/own_state_files.d.ts +35 -0
  115. package/dist/config/own_state_files.js +161 -0
  116. package/dist/config/permission_pin.d.ts +148 -0
  117. package/dist/config/permission_pin.js +203 -0
  118. package/dist/config/permissions.d.ts +9 -2
  119. package/dist/config/permissions.js +14 -3
  120. package/dist/config/platform_login.d.ts +72 -0
  121. package/dist/config/platform_login.js +111 -0
  122. package/dist/config/profile_limits.d.ts +34 -0
  123. package/dist/config/profile_limits.js +66 -0
  124. package/dist/config/provider_api_key_env.js +3 -2
  125. package/dist/config/provider_models.d.ts +6 -1
  126. package/dist/config/provider_models.js +38 -11
  127. package/dist/config/repo_config.d.ts +22 -0
  128. package/dist/config/repo_config.js +77 -3
  129. package/dist/config/router_runtime_grant.d.ts +53 -0
  130. package/dist/config/router_runtime_grant.js +131 -0
  131. package/dist/config/settings_merge.d.ts +22 -0
  132. package/dist/config/settings_merge.js +75 -0
  133. package/dist/config/types.d.ts +8 -0
  134. package/dist/config.d.ts +334 -4
  135. package/dist/config.js +1024 -41
  136. package/dist/context/project_intelligence.d.ts +11 -2
  137. package/dist/context/project_intelligence.js +38 -15
  138. package/dist/desktop/daily/desktop_wiring.js +8 -6
  139. package/dist/desktop/daily/native_pane_launcher.js +2 -1
  140. package/dist/desktop/daily/native_tool.d.ts +1 -1
  141. package/dist/desktop/daily/native_tool.js +4 -3
  142. package/dist/desktop/daily/process_identity.js +10 -2
  143. package/dist/desktop/daily/source_baseline.js +4 -3
  144. package/dist/diagnostics/native_terminal_benchmark.js +3 -2
  145. package/dist/diagnostics/session_export.js +27 -14
  146. package/dist/embedded/anempa_runtime.js +3 -3
  147. package/dist/embedded/gameboy_runtime.js +5 -4
  148. package/dist/embedded/zergpod_runtime.js +5 -4
  149. package/dist/emulation/catalog.js +6 -1
  150. package/dist/emulation/tool_adapters.js +13 -3
  151. package/dist/environment/store.js +5 -4
  152. package/dist/extension_discovery.d.ts +12 -2
  153. package/dist/extension_discovery.js +52 -7
  154. package/dist/headless.d.ts +8 -0
  155. package/dist/headless.js +52 -13
  156. package/dist/headless_cli.js +16 -1
  157. package/dist/headless_workflow_trigger.js +1 -1
  158. package/dist/hooks/dispatcher.d.ts +8 -0
  159. package/dist/hooks/dispatcher.js +22 -2
  160. package/dist/hooks/lifecycle.d.ts +6 -0
  161. package/dist/hooks/lifecycle.js +1 -0
  162. package/dist/hooks/program_files.d.ts +10 -0
  163. package/dist/hooks/program_files.js +175 -0
  164. package/dist/hooks/runner.d.ts +11 -1
  165. package/dist/hooks/runner.js +112 -11
  166. package/dist/hooks/types.d.ts +2 -0
  167. package/dist/host_credentials_startup.d.ts +6 -0
  168. package/dist/host_credentials_startup.js +17 -0
  169. package/dist/instance_registry.d.ts +6 -2
  170. package/dist/instance_registry.js +9 -15
  171. package/dist/intake/format.d.ts +6 -0
  172. package/dist/intake/format.js +9 -0
  173. package/dist/intake/notifications.js +2 -1
  174. package/dist/lsp/manager.d.ts +1 -1
  175. package/dist/lsp/manager.js +4 -5
  176. package/dist/mcp/client.d.ts +2 -0
  177. package/dist/mcp/client.js +116 -18
  178. package/dist/mcp/registry.d.ts +12 -0
  179. package/dist/mcp/registry.js +15 -1
  180. package/dist/modes/handlers.js +14 -5
  181. package/dist/panes/agent_cli.d.ts +23 -1
  182. package/dist/panes/agent_cli.js +96 -1
  183. package/dist/panes/agent_panes.d.ts +27 -4
  184. package/dist/panes/agent_panes.js +73 -11
  185. package/dist/panes/editor_program.d.ts +8 -0
  186. package/dist/panes/editor_program.js +25 -0
  187. package/dist/panes/motsi.d.ts +11 -1
  188. package/dist/panes/motsi.js +14 -1
  189. package/dist/panes/pane_registry.d.ts +28 -1
  190. package/dist/panes/pane_registry.js +25 -0
  191. package/dist/panes/worker_route.js +5 -3
  192. package/dist/panes/ztc_launch.d.ts +8 -0
  193. package/dist/panes/ztc_launch.js +26 -1
  194. package/dist/profile_baseline.js +2 -0
  195. package/dist/router_auth.d.ts +8 -3
  196. package/dist/router_auth.js +34 -2
  197. package/dist/runtime_info.js +56 -38
  198. package/dist/session.js +12 -2
  199. package/dist/shannon/runtime.js +13 -1
  200. package/dist/simulation/domains/loader.d.ts +2 -1
  201. package/dist/simulation/domains/loader.js +19 -2
  202. package/dist/simulation/living/context.d.ts +8 -8
  203. package/dist/simulation/living/types.d.ts +2 -2
  204. package/dist/simulation/memory/embedding.d.ts +2 -1
  205. package/dist/simulation/memory/embedding.js +25 -6
  206. package/dist/terminal_attach.js +2 -1
  207. package/dist/types.d.ts +21 -0
  208. package/dist/ui/ratatui/headless_pane_manager.d.ts +12 -6
  209. package/dist/ui/ratatui/headless_pane_manager.js +65 -21
  210. package/dist/ui/ratatui/ipc_path.d.ts +41 -2
  211. package/dist/ui/ratatui/ipc_path.js +164 -5
  212. package/dist/ui/ratatui/pane_credential_broker.d.ts +17 -4
  213. package/dist/ui/ratatui/pane_credential_broker.js +23 -5
  214. package/dist/ui/ratatui/pane_relay.d.ts +74 -0
  215. package/dist/ui/ratatui/pane_relay.js +188 -13
  216. package/dist/ui/ratatui/process.d.ts +15 -1
  217. package/dist/ui/ratatui/process.js +129 -163
  218. package/dist/ui/ratatui/protocol.d.ts +11 -1
  219. package/dist/ui/ratatui/protocol.js +6 -0
  220. package/dist/ui/ratatui/ztc_launch_trust.d.ts +87 -0
  221. package/dist/ui/ratatui/ztc_launch_trust.js +249 -0
  222. package/dist/utils/admitted_open.d.ts +40 -0
  223. package/dist/utils/admitted_open.js +111 -0
  224. package/dist/utils/clipboard.js +2 -1
  225. package/dist/utils/computer_native.js +12 -56
  226. package/dist/utils/dictation.js +15 -12
  227. package/dist/utils/dictation_native.js +17 -60
  228. package/dist/utils/git_probe_options.d.ts +28 -0
  229. package/dist/utils/git_probe_options.js +30 -0
  230. package/dist/utils/git_program_files.d.ts +145 -0
  231. package/dist/utils/git_program_files.js +1282 -0
  232. package/dist/utils/git_repository_programs.d.ts +13 -0
  233. package/dist/utils/git_repository_programs.js +38 -0
  234. package/dist/utils/host_shell.js +2 -1
  235. package/dist/utils/idle_compaction.js +8 -1
  236. package/dist/utils/image_fit.d.ts +4 -1
  237. package/dist/utils/image_fit.js +6 -2
  238. package/dist/utils/image_preview.js +3 -2
  239. package/dist/utils/mirror_media.d.ts +22 -4
  240. package/dist/utils/mirror_media.js +87 -86
  241. package/dist/utils/ml_native.js +11 -56
  242. package/dist/utils/native_install.d.ts +55 -0
  243. package/dist/utils/native_install.js +107 -0
  244. package/dist/utils/open_url.js +2 -0
  245. package/dist/utils/process_end.d.ts +16 -0
  246. package/dist/utils/process_end.js +73 -0
  247. package/dist/utils/router_catalog.js +9 -2
  248. package/dist/utils/sandbox.d.ts +64 -1
  249. package/dist/utils/sandbox.js +397 -89
  250. package/dist/utils/shell.js +31 -12
  251. package/dist/utils/subprocess_env.d.ts +218 -2
  252. package/dist/utils/subprocess_env.js +429 -11
  253. package/dist/utils/system_ps.d.ts +5 -0
  254. package/dist/utils/system_ps.js +30 -0
  255. package/dist/utils/tts.js +5 -0
  256. package/dist/utils/tts_native.js +13 -60
  257. package/dist/utils/zlicky_overlay.js +17 -50
  258. package/dist/utils/ztc_own_state.d.ts +58 -0
  259. package/dist/utils/ztc_own_state.js +236 -0
  260. package/dist/web/mirror_authenticator.d.ts +67 -6
  261. package/dist/web/mirror_authenticator.js +131 -22
  262. package/dist/web/mirror_stream.d.ts +54 -10
  263. package/dist/web/mirror_stream.js +379 -92
  264. package/dist/web/observer_query_redaction.js +53 -13
  265. package/dist/web/observer_secret_redaction.d.ts +59 -0
  266. package/dist/web/observer_secret_redaction.js +714 -0
  267. package/dist/web/pane_credentials.d.ts +20 -2
  268. package/dist/web/pane_credentials.js +58 -5
  269. package/dist/worker/executor.js +3 -1
  270. package/dist/workspace_collision.js +19 -15
  271. package/dist/zerg/local_zerg_launches.d.ts +27 -0
  272. package/dist/zerg/local_zerg_launches.js +198 -0
  273. package/dist/zlm-embed.mjs +6257 -2791
  274. package/npm-shrinkwrap.json +1 -1
  275. package/package.json +42 -15
@@ -19,23 +19,27 @@ import { createHash, randomUUID, timingSafeEqual } from 'crypto';
19
19
  import { homedir, tmpdir } from 'os';
20
20
  import { fileURLToPath } from 'url';
21
21
  import { configStore, DEFAULT_CONTEXT_PROGRESS_BAR } from '../config.js';
22
+ import { routingEnvOverride } from '../config/model_pin.js';
22
23
  import { parseEvidenceSnapshot } from '../agent/runtime/evidence.js';
23
24
  import { parseToolProgress } from '../tool_progress.js';
24
25
  import { readRepoConfig } from '../config/repo_config.js';
26
+ import { hostEnvironmentValue } from '../config/host_credentials.js';
25
27
  import { runtimeDiag } from '../utils/debug_log.js';
26
28
  import { getModelCatalogPayload } from '../panes/model_catalog.js';
29
+ import { formatTypedPaneMessage } from '../panes/agent_panes.js';
27
30
  import { isMeaningfulUserInput } from '../app/input_validation.js';
28
31
  import { validTurnCorrelation } from '../app/correlated_turn.js';
29
32
  import { receiveIntakeRequest, listIntakeReceipts } from '../intake/store.js';
30
33
  import { AttentionQueue } from '../attention/queue.js';
31
34
  import { ObserverQueryRedaction } from './observer_query_redaction.js';
35
+ import { liveObserverSecrets, ObserverSecretRedaction, redactCutObserverSecrets, redactObserverSecrets } from './observer_secret_redaction.js';
32
36
  import { completeAtMention } from '../utils/at_mention.js';
33
- import { isTerminalPaneType } from './terminal_replay.js';
37
+ import { isTerminalPaneType, TERMINAL_OUTPUT_CAP } from './terminal_replay.js';
34
38
  import { MAX_TOOL_IMAGE_BODY_BYTES, mirrorToolImage } from './tool_image.js';
35
39
  import { parseTaskHandoffView, retainTaskHandoffView } from './view_plugin.js';
36
40
  import { normalizeMirrorBasePath } from './mirror_base_path.js';
37
41
  import { runtimePluginRegistry } from '../plugin/runtime_registry.js';
38
- import { MIRROR_MEDIA_ROOT, stripForeignMediaTokens } from '../utils/mirror_media.js';
42
+ import { MIRROR_MEDIA_ROOT, stripForeignMediaTokens, stripForeignMediaTokensIn } from '../utils/mirror_media.js';
39
43
  import { readDurableSessionImageSync, SessionMediaError } from '../session_media.js';
40
44
  import { MemoryHistoryStore, JsonlHistoryStore } from './event_history_store.js';
41
45
  import { PaneRegistry } from './pane_registry.js';
@@ -86,6 +90,39 @@ function loadNativeDictation() {
86
90
  }
87
91
  return nativeDictationPromise;
88
92
  }
93
+ /**
94
+ * The refusal of a message for pane TO, which runs no agent (a shell, a command, another program), or, when MISSING, is
95
+ * no pane at all (not_an_agent): the mirror's answer, and ZTC's own when it runs no mirror (typeOverseerMessage). Said
96
+ * to an agent, workspace-mcp's in a Claude Code or Codex pane or a ZTC's own: each types into such a pane with its tool.
97
+ * When the pane is one of the desktop app's NATIVE panes that takes no agent's message (nativeNonAgentPane), the refusal
98
+ * says what the pane is and what works instead (nativePaneRefusal): a native Claude Code or Codex pane is no pane a
99
+ * message reaches, though Claude Code and Codex panes are.
100
+ */
101
+ export function notAnAgentResult(to, missing, native) {
102
+ return { ok: false, status: 409, code: 'not_an_agent', error: native ? nativePaneRefusal(to, native)
103
+ : missing ? `There's no pane ${String(to)}.`
104
+ : `Pane ${String(to)} isn't an agent: a pane's messages go to Main, ZTC panes, and Claude Code or Codex panes. `
105
+ + 'To type into a shell or a command pane, use type_into_pane (write_terminal_pane in a ZTC pane).' };
106
+ }
107
+ /**
108
+ * Why native pane TO takes no agent's message, and what works instead: a delegated pane shows a worker's feed and takes
109
+ * nothing; an interactive shell takes typing, which type_into_pane does (write_terminal_pane in a ZTC pane); an
110
+ * interactive Claude Code or Codex pane is for the person's typing (the desktop labels it "human input only"), though
111
+ * type_into_pane and write_terminal_pane type into it as into any pane, and started without workspace-mcp, it couldn't
112
+ * answer a message, so an agent to message is a Claude Code or Codex pane ZTC opens, with /claude or /codex.
113
+ */
114
+ function nativePaneRefusal(to, native) {
115
+ if (native.mode === 'delegated') {
116
+ return `Pane ${String(to)} is a native delegated pane, which shows a worker's feed and takes no messages.`;
117
+ }
118
+ if (native.tool === 'shell') {
119
+ return `Pane ${String(to)} is a native shell pane, which takes typing, not messages. `
120
+ + 'To type into it, use type_into_pane (write_terminal_pane in a ZTC pane).';
121
+ }
122
+ const name = native.tool === 'codex' ? 'Codex' : 'Claude Code';
123
+ return `Pane ${String(to)} is a native ${name} pane, which takes typing, not messages. `
124
+ + 'To message an agent, open a Claude Code or Codex pane with /claude or /codex.';
125
+ }
89
126
  /** 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
127
  const HOLD_NOTICE_SENDER = { id: OVERSEER_BUS_MEMBER_ID, name: 'ZTC' };
91
128
  // Observation exposes terminal activity, never operator settings or plugin-specific state.
@@ -98,6 +135,8 @@ const OBSERVER_EVENT_TYPES = new Set([
98
135
  ]);
99
136
  /** How long a request presenting a pane credential waits for its owner to hear the pane was created. */
100
137
  const PANE_CREDENTIAL_SETTLE_MS = 10_000;
138
+ /** The longest a timer can wait; a longer delay fires at once. */
139
+ const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
101
140
  const OBSERVER_GET_PATHS = new Set([
102
141
  '/', '/events', '/debug/config', '/mirror/pane-registry', '/mirror/layout',
103
142
  '/status', '/stats', '/output', '/health', '/favicon.svg', '/favicon.ico', '/mirror-favicon.svg',
@@ -109,6 +148,13 @@ const ZLICKY_CAPTURE_MAX_BYTES = 8 * 1024 * 1024;
109
148
  const ZLICKY_CAPTURE_TIMEOUT_MS = 20_000;
110
149
  const ZLICKY_CAPTURE_TTL_MS = 90_000; // tmpfiles live ~90s after delivery
111
150
  const ZLICKY_CAPTURE_ALLOWED_MIMES = new Set(['image/png', 'image/jpeg', 'image/webp']);
151
+ /** How each accepted capture type's bytes start; a body that claims a type it does not start as is refused. */
152
+ const ZLICKY_CAPTURE_SIGNATURES = {
153
+ 'image/png': body => body.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])),
154
+ 'image/jpeg': body => body.length >= 3 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff,
155
+ 'image/webp': body => body.length >= 12 && body.subarray(0, 4).toString('latin1') === 'RIFF'
156
+ && body.subarray(8, 12).toString('latin1') === 'WEBP',
157
+ };
112
158
  // Per-IP rate limit on the capture POST (moving 60-second window).
113
159
  // Legit agent + user flows sit well under 5/min. 60/min is a belt-and-
114
160
  // suspenders ceiling against a compromised browser context that tries to
@@ -149,6 +195,71 @@ function endStream(res) {
149
195
  const socket = res.socket;
150
196
  res.end(() => { socket?.end(); });
151
197
  }
198
+ /** The host path a zlicky frame is stored at, as zlicky_look's result names it (png_path), a JSON string. */
199
+ const FRAME_PATH_FIELD = /("png_path"\s*:\s*)"(?:[^"\\]|\\.)*"/g;
200
+ /**
201
+ * zlicky_look's RESULT as the mirror publishes it: the frame's id, target, size and dimensions, and in place of the
202
+ * host path it is stored at, "(host path withheld)". The agent reads the PNG from the path in its own result; no
203
+ * browser session, a controller's or an observer's, is told where on this computer the frame lies, as the capture
204
+ * routes tell none (GET /zlicky/capture/:id).
205
+ */
206
+ function withoutFramePath(result) {
207
+ return result.replace(FRAME_PATH_FIELD, '$1"(host path withheld)"');
208
+ }
209
+ /** VALUE when it is a plain object, else null. */
210
+ function recordOf(value) {
211
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
212
+ }
213
+ /**
214
+ * Events that describe the whole mirror rather than the pane that posts them: the panes' layout, the connection, the
215
+ * repository's and the colony's config, a reload, and what only the mirror itself says of the session: a share revoked
216
+ * or expired (the browser closes its stream for good), a cut-short history (it resets every pane's transcript, and a
217
+ * stored one is replayed to every viewer that connects later), the operator's sign-in, the active accounts and the
218
+ * notification setting. A pane's own credential publishes none of them (/pane-events, /pane-store-event): a Claude
219
+ * Code or Codex pane's credential sits in its environment, where the agent's shell reads it, and a forged layout retyped
220
+ * or removed pane 0 in every viewer's. No child publishes them (MirrorClient); ZTC's own internal token, which the
221
+ * hosted owner's proxy uses too, still may.
222
+ */
223
+ const WHOLE_MIRROR_EVENT_TYPES = new Set(['pane_info', 'connected', 'repo_config', 'colony_config',
224
+ 'connection_state', 'auth_mode', 'reload', 'share_revoked', 'share_expired', 'history_truncated', 'auth_update',
225
+ 'accounts', 'open_accounts', 'sfx_config']);
226
+ /** Why a pane's own credential may not publish EVENT, or null when it may (WHOLE_MIRROR_EVENT_TYPES). */
227
+ function paneEventRefusal(event) {
228
+ const type = recordOf(event)?.type;
229
+ return typeof type === 'string' && WHOLE_MIRROR_EVENT_TYPES.has(type)
230
+ ? `A pane credential publishes only its own pane's events: ${type} describes the whole mirror.` : null;
231
+ }
232
+ /** A /job word: /job at a line's start or after a blank, and a blank after it. */
233
+ const JOB_WORD = /(?:^|\s)\/job\s/m;
234
+ /** An --env option: at a line's start or after a blank, and a blank or = after it. */
235
+ const ENV_OPTION = /(?:^|\s)--env(?:\s|=)/gm;
236
+ /**
237
+ * Does TEXT give a /job command environment options: an --env option anywhere after a /job word? Each is searched for
238
+ * once: an --env after any /job word is after the first one too, so TEXT is read once, however many /job words it holds.
239
+ */
240
+ function namesJobEnvironment(text) {
241
+ const job = JOB_WORD.exec(text);
242
+ if (!job)
243
+ return false;
244
+ ENV_OPTION.lastIndex = job.index + job[0].length;
245
+ return ENV_OPTION.test(text);
246
+ }
247
+ /**
248
+ * Why a colony log route (/api/colony/log-pane, /log-output) refuses the pane ID, or null for one it manages. The colony
249
+ * view registers its log panes at ids of its own, below zero (colony-view.js SCRIPT_VIRTUAL_PANE_IDS: -100, -101, -102),
250
+ * the only ids any caller uses. The pane manager's panes are at zero and above: pane 0, the overseer, whose entry holds
251
+ * the primary session /status reports, and each ZTC, shell or command pane. No colony route removes, registers again or
252
+ * writes as one of them, which hid it from close_pane and from the cap on ZTC panes, or put output in its terminal.
253
+ */
254
+ function colonyLogPaneRefusal(id) {
255
+ if (typeof id !== 'number' || !Number.isSafeInteger(id))
256
+ return { status: 400, error: 'a colony log pane needs an integer id' };
257
+ if (id < 0)
258
+ return null;
259
+ return { status: 403, error: id === 0
260
+ ? 'pane 0 is the overseer: a colony log route manages only its own panes, at ids below zero'
261
+ : `pane ${id} is not a colony log pane: a colony log route manages only its own panes, at ids below zero` };
262
+ }
152
263
  /**
153
264
  * What an open mirror (sign-in off) answers a caller on another machine: it serves this computer alone, whatever Host
154
265
  * or X-Forwarded-For a request claims, and sign-in is how other machines get in.
@@ -237,6 +348,7 @@ export class MirrorStreamServer {
237
348
  // user-prompt channel) so the two can never be confused by content.
238
349
  paneControlCallback = null;
239
350
  agentPaneMessageCallback = null;
351
+ nativeNonAgentPaneLookup = null;
240
352
  busMessageCheck = null;
241
353
  muxCommandCallback = null;
242
354
  supervisionCommandCallback = null;
@@ -415,6 +527,19 @@ export class MirrorStreamServer {
415
527
  this.clients.delete(clientId);
416
528
  }
417
529
  });
530
+ // A stream lasts as long as the session it was opened with: signed out, pushed out by a cap or no longer valid,
531
+ // the session takes its streams with it (an observer whose share expired is told so first, as at its expiry).
532
+ this.auth.onSessionDropped(session => {
533
+ for (const [clientId, client] of this.clients) {
534
+ if (client.session !== session)
535
+ continue;
536
+ if (client.readOnly && Date.now() >= session.expiresAtMs) {
537
+ client.res.write(`data: ${JSON.stringify({ type: 'share_expired', data: { share_id: client.shareId } })}\n\n`);
538
+ }
539
+ client.res.end();
540
+ this.clients.delete(clientId);
541
+ }
542
+ });
418
543
  const devBarFlag = (process.env.ZTC_MIRROR_DEV_BAR || '').trim();
419
544
  if (devBarFlag === '1') {
420
545
  this.devSystemBarEnabled = true;
@@ -709,6 +834,14 @@ export class MirrorStreamServer {
709
834
  onAgentPaneMessage(cb) {
710
835
  this.agentPaneMessageCallback = cb;
711
836
  }
837
+ /**
838
+ * Name the desktop app's native panes that take no agent's message (nativeNonAgentPane), from the owner's record of
839
+ * each, so the refusal of a message for one (not_an_agent), Main's or a pane's own, says what the pane is and what
840
+ * works instead (notAnAgentResult). Nothing is delivered either way.
841
+ */
842
+ onNativeNonAgentPane(cb) {
843
+ this.nativeNonAgentPaneLookup = cb;
844
+ }
712
845
  /**
713
846
  * What Main says of a message a pane posts to /bus/send before it is delivered (BusMessageCheck): it refuses a reply
714
847
  * mode that names an arbitrator the person didn't set up, and tells the sender what became of its mode.
@@ -740,10 +873,20 @@ export class MirrorStreamServer {
740
873
  this.publish({ type: 'attention_resolved', data: { id, request_id: item.requestId, kind: item.kind, pane_id: item.paneId } });
741
874
  return item;
742
875
  }
743
- respondAttention(id, answer) {
876
+ /**
877
+ * Answer attention item ID with ANSWER: a question's text, an approval's decision and reason, a prompt widget's fields.
878
+ * FROM is who sent it: the browser mirror ('mirror': this server's routes, and a command the browser sent or that is
879
+ * relayed here), or the person at this ZTC's own terminal ('terminal': the /attention command they type). Every string
880
+ * the mirror sends is mirror text (stripForeignMediaTokensIn), wherever it goes next: a question's answer becomes the
881
+ * agent's next message, a plan's feedback becomes one, and a ZTC pane that is relayed an answer runs it as its prompt,
882
+ * so a forged `[image PATH]` in it would read PATH. What the person types at the terminal keeps their own paths, as
883
+ * their messages do.
884
+ */
885
+ respondAttention(id, answer, from = 'mirror') {
744
886
  const item = this.attention.find(id);
745
887
  if (!item || item.primaryAction === 'inspect')
746
888
  throw new Error('Stale attention request; inspect the current queue.');
889
+ answer = from === 'terminal' ? answer : stripForeignMediaTokensIn(answer);
747
890
  if (item.kind === 'question') {
748
891
  if (typeof answer !== 'string' || !answer.trim())
749
892
  throw new Error('A non-empty question answer is required.');
@@ -824,14 +967,16 @@ export class MirrorStreamServer {
824
967
  return () => { this.busObservers = this.busObservers.filter(o => o !== callback); };
825
968
  }
826
969
  /**
827
- * Deliver a bus message to the appropriate target(s). With `agentsOnly` (what a pane's own credential sends), a message
828
- * goes only to an agent: Main, every bus member ('all'), a pane on the bus or running ZTC, or a Claude Code or Codex
829
- * pane, which the owner types it into with its sender. For any other pane (a shell, a command) nothing is delivered,
830
- * queued or typed, and the answer is 'not_an_agent'. Whoever sends it, an agent's message for a ZTC agent's pane that
831
- * hasn't joined the bus is held until it joins, never typed into the pane, and the answer is 'held' (waitsForJoin);
832
- * once the renderer has reported that pane's program exited, nothing is held or typed and the answer is 'pane_exited'
833
- * (forExitedZtc), until a ZTC that joins stands for the pane again. What a pane that can no longer join held is dropped
834
- * first (dropUnjoinable), so no message for it goes ahead of one that waits.
970
+ * Deliver a bus message to the appropriate target(s). With `agentsOnly` (what a pane's own credential sends, and what
971
+ * Main sends: overseerBusTransport), a message goes only to an agent: Main, every bus member ('all'), a pane on the bus
972
+ * or running ZTC, or a Claude Code or Codex pane, which the owner types it into with its sender. For any other pane (a
973
+ * shell, a command) nothing is delivered, queued or typed, and the answer is 'not_an_agent'. Whoever sends it, an
974
+ * agent's message for a ZTC agent's pane that hasn't joined the bus is held until it joins, never typed into the pane,
975
+ * and the answer is 'held' (waitsForJoin); once the renderer has reported that pane's program exited, nothing is held
976
+ * or typed and the answer is 'pane_exited' (forExitedZtc), until a ZTC that joins stands for the pane again. What a
977
+ * pane that can no longer join held is dropped first (dropUnjoinable), so no message for it goes ahead of one that
978
+ * waits. With `agentsOnly`, a message for a ZTC pane that reads stdin and joins no bus is typed in as one line that
979
+ * says who sent it, never on the pane's control channel and never as its raw text.
835
980
  */
836
981
  deliverBusMessage(msg, options = {}) {
837
982
  if (typeof msg.to === 'number' && msg.to !== OVERSEER_BUS_MEMBER_ID)
@@ -928,14 +1073,28 @@ export class MirrorStreamServer {
928
1073
  }
929
1074
  // What a pane with no bus connection still reads from its terminal (an agent's
930
1075
  // message for a ZTC agent's pane waits for it to join instead: waitsForJoin).
931
- // A ztc_message from the overseer (bus member 0, the ZTC that opened the pane)
932
- // is an internal control command ({"__ztc_cmd":...}), NOT user text: deliver
933
- // it BARE via the control channel so the child classifies it as a control
934
- // command instead of replaying it to the LLM as a prompt. From any other member
935
- // it is no control command, as a pane on the bus ignores one (cli_ratatui
936
- // handleBusMessage): it falls through to the input channel below, as ordinary
937
- // input, so it can't change the pane's model or answer its question.
938
- if (typeof targetId === 'number' && targetId !== 0 && msg.type === 'ztc_message'
1076
+ // An agent's message (agentsOnly: Main's agent, or a pane's own credential) for
1077
+ // a ZTC pane that reads its input from stdin and joins no bus (the browser
1078
+ // mirror's own ZTC chat panes) is typed in as one inert line that says who sent
1079
+ // it (formatTypedPaneMessage), as Main types one into a ZTC pane while it runs no
1080
+ // mirror: never on the pane's control channel, where Main's agent would speak as
1081
+ // the pane's owner, and never as its raw text, a line of which (a slash command,
1082
+ // a shell line) the pane would run as its own command.
1083
+ if (options.agentsOnly && typeof targetId === 'number' && targetId !== 0 && msg.type === 'ztc_message'
1084
+ && this.paneInputCallback) {
1085
+ if (process.env.ZTC_DEBUG)
1086
+ process.stderr.write(`${tag} delivered as a typed message via pane-input callback (stdin)\n`);
1087
+ this.paneInputCallback(targetId, { text: formatTypedPaneMessage(msg), attachments: [] });
1088
+ return 'delivered';
1089
+ }
1090
+ // A ztc_message from the overseer itself (bus member 0, the ZTC that opened the
1091
+ // pane, not its agent) is an internal control command ({"__ztc_cmd":...}), NOT
1092
+ // user text: deliver it BARE via the control channel so the child classifies it
1093
+ // as a control command instead of replaying it to the LLM as a prompt. From any
1094
+ // other member it is no control command, as a pane on the bus ignores one
1095
+ // (cli_ratatui handleBusMessage): it falls through to the input channel below,
1096
+ // as ordinary input, so it can't change the pane's model or answer its question.
1097
+ if (typeof targetId === 'number' && targetId !== 0 && msg.type === 'ztc_message' && !options.agentsOnly
939
1098
  && msg.from.id === OVERSEER_BUS_MEMBER_ID && this.paneControlCallback) {
940
1099
  if (process.env.ZTC_DEBUG)
941
1100
  process.stderr.write(`${tag} delivered via pane-control callback (stdin, bare)\n`);
@@ -965,11 +1124,7 @@ export class MirrorStreamServer {
965
1124
  case 'hold_full':
966
1125
  return { ok: false, status: 429, code: 'hold_full', error: holdFullRefusal(to) };
967
1126
  case 'not_an_agent':
968
- // 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.
969
- return { ok: false, status: 409, code: 'not_an_agent', error: typeof to === 'number' && !this.panes.has(to)
970
- ? `There's no pane ${to}.`
971
- : `Pane ${String(to)} isn't an agent: a pane's messages go to Main, ZTC panes, and Claude Code or Codex panes. `
972
- + 'To type into a shell or a command pane, use type_into_pane (write_terminal_pane in a ZTC pane).' };
1127
+ return notAnAgentResult(to, typeof to === 'number' && !this.panes.has(to), this.nativeNonAgentPaneLookup?.(to));
973
1128
  case 'pane_exited':
974
1129
  return { ok: false, status: 409, code: 'pane_exited', error: paneExitedRefusal(to) };
975
1130
  }
@@ -1432,31 +1587,81 @@ export class MirrorStreamServer {
1432
1587
  observerProjections = new WeakMap();
1433
1588
  observerQueryRedaction = new ObserverQueryRedaction();
1434
1589
  observerTextRedaction = new ObserverQueryRedaction();
1435
- observerEvent(event) {
1590
+ /** Each live stream's credential context, keyed as observerQueryRedaction is (see observer_secret_redaction.ts). */
1591
+ observerSecretRedaction = new ObserverSecretRedaction();
1592
+ /**
1593
+ * EVENT as a read-only observer gets it, or null for a type it never gets. Every string it carries has the URL
1594
+ * tokens and the credentials an observer is never shown withheld; streamed text keeps each stream's context, so a
1595
+ * credential split across its pieces is withheld too. A STANDALONE event is a connect snapshot of a stream's
1596
+ * retained text, which neither reads nor moves its live stream's context.
1597
+ */
1598
+ observerEvent(event, standalone = false) {
1436
1599
  if (!OBSERVER_EVENT_TYPES.has(event.type))
1437
1600
  return null;
1438
1601
  const cached = this.observerProjections.get(event);
1439
1602
  if (cached)
1440
1603
  return cached;
1604
+ const secrets = liveObserverSecrets();
1441
1605
  const scope = JSON.stringify([event.data.origin_session_id ?? this.originSessionId, event.data.pane_id ?? 0]);
1442
1606
  if (event.type === 'stream_start') {
1443
- for (const type of ['stream_delta', 'reasoning_delta'])
1607
+ for (const type of ['stream_delta', 'reasoning_delta']) {
1444
1608
  this.observerQueryRedaction.reset(`${scope}:${type}`);
1609
+ this.observerSecretRedaction.reset(`${scope}:${type}`);
1610
+ }
1445
1611
  }
1446
1612
  let source = event;
1447
- if (['stream_delta', 'reasoning_delta', 'pane_output'].includes(event.type) && typeof event.data.content === 'string') {
1448
- source = { ...event, data: { ...event.data, content: this.observerQueryRedaction.redact(`${scope}:${event.type}`, event.data.content, event.type === 'pane_output' && event.data.reset === true) } };
1613
+ // The panes' layout carries each pane's goal, task handoff and evidence too: an observer gets the layout without
1614
+ // them, as it gets none of their own events.
1615
+ if (event.type === 'pane_info' && Array.isArray(event.data.panes)) {
1616
+ source = { ...event, data: { ...event.data, panes: event.data.panes.map(pane => {
1617
+ if (pane === null || typeof pane !== 'object' || Array.isArray(pane))
1618
+ return pane;
1619
+ const visible = { ...pane };
1620
+ delete visible.evidence;
1621
+ delete visible.goal;
1622
+ delete visible.taskHandoff;
1623
+ return visible;
1624
+ }) } };
1449
1625
  }
1450
- const projected = JSON.parse(JSON.stringify(source, (_key, value) => typeof value === 'string'
1451
- ? /(?:^|\s)\/job\s[\s\S]*?(?:^|\s)--env(?:\s|=)/m.test(value)
1452
- ? '/job [environment options withheld]'
1453
- : this.observerTextRedaction.redact('text', value, true)
1454
- : value));
1626
+ if (['stream_delta', 'reasoning_delta', 'pane_output'].includes(event.type) && typeof event.data.content === 'string') {
1627
+ const stream = `${scope}:${event.type}`;
1628
+ const reset = event.type === 'pane_output' && event.data.reset === true;
1629
+ const queries = standalone ? new ObserverQueryRedaction() : this.observerQueryRedaction;
1630
+ const credentials = standalone ? new ObserverSecretRedaction() : this.observerSecretRedaction;
1631
+ // A pane's output may be a terminal's, whose colour codes can split a credential: it is also read as a terminal
1632
+ // shows it. (Only process, command and colony_script panes render it as a terminal; reading any pane's output
1633
+ // that way can only withhold more.)
1634
+ const terminal = event.type === 'pane_output';
1635
+ const content = queries.redact(stream, event.data.content, reset);
1636
+ source = { ...event, data: { ...event.data, content: credentials.redact(stream, content, secrets, reset, terminal) } };
1637
+ }
1638
+ // A tool's result is cut at its cap, and a running command's latest line where its limit or the output so far
1639
+ // ends, without a mark saying so: each may end partway through a credential, so what may start one at its end is
1640
+ // withheld, as at the end of a stream's piece. (A tool call's argument says where it was cut; observerStrings
1641
+ // reads that mark.)
1642
+ if (event.type === 'tool_result' && typeof event.data.result === 'string') {
1643
+ source = { ...source, data: { ...source.data, result: redactCutObserverSecrets(event.data.result, secrets) } };
1644
+ }
1645
+ const toolProgress = event.type === 'status' ? recordOf(event.data.toolProgress) : null;
1646
+ const progress = recordOf(toolProgress?.progress);
1647
+ if (toolProgress && progress && typeof progress.latestLine === 'string') {
1648
+ source = { ...source, data: { ...source.data, toolProgress: { ...toolProgress,
1649
+ progress: { ...progress, latestLine: redactCutObserverSecrets(progress.latestLine, secrets) } } } };
1650
+ }
1651
+ const projected = this.observerStrings(source, secrets);
1455
1652
  // Weak keys share the canonical history lifetime and do not create another
1456
1653
  // unbounded event store. Replays reuse the same safe projection.
1457
1654
  this.observerProjections.set(event, projected);
1458
1655
  return projected;
1459
1656
  }
1657
+ /** A copy of VALUE with each string in it as an observer reads it: no /job environment options, URL tokens or SECRETS. */
1658
+ observerStrings(value, secrets = liveObserverSecrets()) {
1659
+ return JSON.parse(JSON.stringify(value, (_key, item) => typeof item === 'string'
1660
+ ? namesJobEnvironment(item)
1661
+ ? '/job [environment options withheld]'
1662
+ : redactObserverSecrets(this.observerTextRedaction.redact('text', item, true), secrets)
1663
+ : item));
1664
+ }
1460
1665
  observerConnectionData(clientId) {
1461
1666
  return {
1462
1667
  clientId, port: this.port, origin_session_id: this.originSessionId, read_only: true,
@@ -1472,7 +1677,8 @@ export class MirrorStreamServer {
1472
1677
  * nulled out client-side, so overlapping fields must be kept in sync.
1473
1678
  */
1474
1679
  buildDebugConfigData(canInspectPrompts = false) {
1475
- const authEnvOverride = process.env.ZTC_LLM_AUTH_MODE || process.env.ZERG_LLM_AUTH_MODE || undefined;
1680
+ // The variable only while it outranks the saved routing: the routing it pins leaves it nothing to override.
1681
+ const authEnvOverride = routingEnvOverride(configStore.get().authMode);
1476
1682
  return {
1477
1683
  auth_required: this.auth.enabled,
1478
1684
  dev_bar_enabled: this.devSystemBarEnabled,
@@ -1501,7 +1707,8 @@ export class MirrorStreamServer {
1501
1707
  * socket.
1502
1708
  */
1503
1709
  buildConnectedEventData(clientId, canInspectPrompts = false) {
1504
- const authEnvOverride = process.env.ZTC_LLM_AUTH_MODE || process.env.ZERG_LLM_AUTH_MODE || undefined;
1710
+ // The variable only while it outranks the saved routing: the routing it pins leaves it nothing to override.
1711
+ const authEnvOverride = routingEnvOverride(configStore.get().authMode);
1505
1712
  return {
1506
1713
  clientId,
1507
1714
  origin_session_id: this.originSessionId,
@@ -1804,7 +2011,7 @@ export class MirrorStreamServer {
1804
2011
  this.publish({ type: 'task_handoff', data: { sessionId, projection } });
1805
2012
  }
1806
2013
  publishToolResult(tool, result, success, toolCallId) {
1807
- const data = this.retainToolImage({ tool, result, success, toolCallId });
2014
+ const data = this.retainToolImage({ tool, result: tool === 'zlicky_look' ? withoutFramePath(result) : result, success, toolCallId });
1808
2015
  // Larger limits for tools with structured/visual output in the mirror
1809
2016
  const largeLimitTools = ['delegate_task', 'read_file', 'search', 'run_command'];
1810
2017
  const maxLen = largeLimitTools.includes(tool) ? 15000 : 4000;
@@ -1983,11 +2190,12 @@ export class MirrorStreamServer {
1983
2190
  throw new Error('capture_id is required');
1984
2191
  const timeoutMs = Math.max(Math.min(request.timeout_ms ?? ZLICKY_CAPTURE_TIMEOUT_MS, ZLICKY_CAPTURE_TIMEOUT_MS), 1_000);
1985
2192
  // Create a pending pledge the POST handler will resolve.
1986
- let pending = this.zlickyCaptures.get(id);
1987
- if (!pending) {
1988
- pending = { resolvers: [], arrived: null };
1989
- this.zlickyCaptures.set(id, pending);
2193
+ let entry = this.zlickyCaptures.get(id);
2194
+ if (!entry) {
2195
+ entry = { resolvers: [], arrived: null };
2196
+ this.zlickyCaptures.set(id, entry);
1990
2197
  }
2198
+ const pending = entry;
1991
2199
  // Fire the event so the overlay starts capturing.
1992
2200
  this.publishZlicky('zlicky_capture_request', {
1993
2201
  capture_id: id,
@@ -1995,23 +2203,38 @@ export class MirrorStreamServer {
1995
2203
  reason: request.reason || '',
1996
2204
  });
1997
2205
  const result = await new Promise((resolve, reject) => {
2206
+ // The waiter this request adds, kept so that its timeout removes this one and no other: a frame posted later
2207
+ // then reaches only the requests still waiting.
2208
+ const waiter = {
2209
+ resolve: (v) => { clearTimeout(timer); resolve(v); },
2210
+ reject: (e) => { clearTimeout(timer); reject(e); },
2211
+ };
1998
2212
  const timer = setTimeout(() => {
1999
- // Remove this resolver; if others are waiting, they can still fire.
2000
- if (pending) {
2001
- pending.resolvers = pending.resolvers.filter((r) => r.resolve !== resolve);
2213
+ pending.resolvers = pending.resolvers.filter((r) => r !== waiter);
2214
+ // With nothing else waiting and no frame come, the id is forgotten, as one nobody asked for is. A frame that
2215
+ // came stays until its own cleanup (the POST handler's), and another request's wait keeps the id.
2216
+ if (pending.resolvers.length === 0 && !pending.arrived && this.zlickyCaptures.get(id) === pending) {
2217
+ this.zlickyCaptures.delete(id);
2002
2218
  }
2003
2219
  reject(new Error(`capture ${id} timed out after ${timeoutMs}ms`));
2004
2220
  }, timeoutMs);
2005
- pending.resolvers.push({
2006
- resolve: (v) => { clearTimeout(timer); resolve(v); },
2007
- reject: (e) => { clearTimeout(timer); reject(e); },
2008
- });
2221
+ pending.resolvers.push(waiter);
2009
2222
  });
2010
2223
  return result;
2011
2224
  }
2012
- rateLimitKey(req) {
2013
- const forwarded = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim();
2014
- return forwarded || req.socket.remoteAddress || 'unknown';
2225
+ /**
2226
+ * The bucket a capture POST counts against: the token that sent it (one name for every session it starts), the pane
2227
+ * or ZTC process, else the socket's address. Never a header the client writes, such as X-Forwarded-For.
2228
+ */
2229
+ rateLimitKey(req, auth) {
2230
+ const credential = this.auth.credentialKeyOf(auth.session);
2231
+ if (credential)
2232
+ return `token:${credential}`;
2233
+ if (auth.source === 'pane' && auth.pane)
2234
+ return `pane:${auth.pane.paneId}`;
2235
+ if (auth.source === 'internal')
2236
+ return 'internal';
2237
+ return `peer:${req.socket.remoteAddress || 'unknown'}`;
2015
2238
  }
2016
2239
  // Whether the request came from this computer, which is all an open mirror answers (see isLoopbackPeer).
2017
2240
  // Trusts the socket address only (x-forwarded-for is client-controlled).
@@ -2499,7 +2722,7 @@ export class MirrorStreamServer {
2499
2722
  }
2500
2723
  }
2501
2724
  async handleMirrorPublish(req, res) {
2502
- const secret = process.env.ZERG_CV_PUBLISH_SECRET;
2725
+ const secret = hostEnvironmentValue('ZERG_CV_PUBLISH_SECRET');
2503
2726
  if (!secret) {
2504
2727
  res.writeHead(404, { 'Content-Type': 'application/json' });
2505
2728
  res.end(JSON.stringify({ error: 'publish endpoint disabled' }));
@@ -2750,11 +2973,12 @@ export class MirrorStreamServer {
2750
2973
  }
2751
2974
  return out;
2752
2975
  }
2753
- /** Persist the authenticator-minted session and write the Set-Cookie header. */
2976
+ /** Persist the authenticator-minted session and write the Set-Cookie header. Returns the session as the store keeps it. */
2754
2977
  issueMirrorSession(res, session) {
2755
2978
  const sessionId = this.auth.persistSession(session);
2756
2979
  const maxAgeSeconds = Math.max(1, Math.floor((session.expiresAtMs - Date.now()) / 1000));
2757
2980
  res.setHeader('Set-Cookie', `${this.auth.cookieName}=${encodeURIComponent(sessionId)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAgeSeconds}`);
2981
+ return this.auth.getSession(sessionId) ?? session;
2758
2982
  }
2759
2983
  async persistLayoutToDisk(layout) {
2760
2984
  try {
@@ -2784,14 +3008,13 @@ export class MirrorStreamServer {
2784
3008
  url,
2785
3009
  cookies: this.parseCookies(req),
2786
3010
  });
2787
- if (decision.issueCookie) {
2788
- this.issueMirrorSession(res, decision.issueCookie);
2789
- }
3011
+ // A session the request started is the one the store keeps from now on: what the request opens follows that one.
3012
+ const session = decision.issueCookie ? this.issueMirrorSession(res, decision.issueCookie) : decision.session;
2790
3013
  if (!decision.ok) {
2791
3014
  res.writeHead(401, { 'Content-Type': 'application/json' });
2792
3015
  res.end(JSON.stringify({ error: 'Mirror authentication required' }));
2793
3016
  }
2794
- return { ok: decision.ok, session: decision.session, source: decision.source, ...(decision.pane ? { pane: decision.pane } : {}) };
3017
+ return { ok: decision.ok, session, source: decision.source, ...(decision.pane ? { pane: decision.pane } : {}) };
2795
3018
  }
2796
3019
  requireInternalAuth(auth, res) {
2797
3020
  if (auth.source === 'internal')
@@ -3192,6 +3415,15 @@ export class MirrorStreamServer {
3192
3415
  }
3193
3416
  socket.resume();
3194
3417
  }
3418
+ /** Refuse with 403, and say so, an event a pane's own credential may not publish (paneEventRefusal). */
3419
+ refusePaneEvent(parsed, res) {
3420
+ const refusal = paneEventRefusal(parsed?.event);
3421
+ if (!refusal)
3422
+ return false;
3423
+ res.writeHead(403, { 'Content-Type': 'application/json' });
3424
+ res.end(JSON.stringify({ error: refusal }));
3425
+ return true;
3426
+ }
3195
3427
  admitChildPublication(parsed, res, scope) {
3196
3428
  if (!parsed || !Number.isSafeInteger(parsed.pane_id) || parsed.pane_id < -1 || scope.length > 256) {
3197
3429
  res.writeHead(400, { 'Content-Type': 'application/json' });
@@ -3322,19 +3554,15 @@ export class MirrorStreamServer {
3322
3554
  if (url.pathname === '/debug/signin-token' && req.method === 'POST') {
3323
3555
  try {
3324
3556
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
3325
- const token = String(parsed.token || '');
3326
- const result = this.auth.isValidToken(token);
3327
- if (!result.ok) {
3557
+ // A session of its own, counted against the token it came from: however often a link's token signs in, it
3558
+ // pushes out only that token's sessions, never the owner's.
3559
+ const session = this.auth.startSession(String(parsed.token || ''));
3560
+ if (!session) {
3328
3561
  res.writeHead(401, { 'Content-Type': 'application/json' });
3329
3562
  res.end(JSON.stringify({ ok: false, error: 'Invalid or expired token' }));
3330
3563
  return;
3331
3564
  }
3332
- this.issueMirrorSession(res, {
3333
- expiresAtMs: result.expiresAtMs,
3334
- canInspectPrompts: result.canInspectPrompts,
3335
- canControl: result.canControl,
3336
- shareId: result.shareId,
3337
- });
3565
+ this.issueMirrorSession(res, session);
3338
3566
  res.writeHead(200, { 'Content-Type': 'application/json' });
3339
3567
  res.end(JSON.stringify({ ok: true }));
3340
3568
  }
@@ -3346,9 +3574,11 @@ export class MirrorStreamServer {
3346
3574
  // Server-to-server CV publishers use their own shared-secret header and
3347
3575
  // should not require a browser mirror session cookie. A mirror that answers
3348
3576
  // only credentialed callers takes them only past its credential check, below.
3349
- const cvRoute = (url.pathname === '/mirror/publish' && req.method === 'POST')
3350
- || (url.pathname === '/cv/snapshot' && req.method === 'GET');
3351
- if (cvRoute && !this.paneControlCredentialRequired) {
3577
+ // The CV snapshot is a read like any other: a mirror that requires sign-in
3578
+ // answers it only past authentication too.
3579
+ const cvPublish = url.pathname === '/mirror/publish' && req.method === 'POST';
3580
+ const cvRoute = cvPublish || (url.pathname === '/cv/snapshot' && req.method === 'GET');
3581
+ if (cvRoute && !this.paneControlCredentialRequired && (cvPublish || !this.mirrorAuthEnabled)) {
3352
3582
  await this.handleCvRoute(url, req, res);
3353
3583
  return;
3354
3584
  }
@@ -3620,7 +3850,8 @@ export class MirrorStreamServer {
3620
3850
  paneCount: entries.length,
3621
3851
  panes: entries.map(([id, info]) => ({
3622
3852
  id,
3623
- title: info.title,
3853
+ // A title can be a command line: an observer reads it as it reads the panes' layout.
3854
+ title: readOnly && typeof info.title === 'string' ? this.observerStrings(info.title) : info.title,
3624
3855
  paneType: info.paneType,
3625
3856
  model: info.model,
3626
3857
  status: info.status,
@@ -3690,9 +3921,12 @@ export class MirrorStreamServer {
3690
3921
  return;
3691
3922
  }
3692
3923
  if (url.pathname === '/mirror/layout' && req.method === 'GET') {
3924
+ // Each panel's title is its pane's, which can be a command line: a read-only client reads the layout as it reads
3925
+ // the pane registry, with every string through the observer projection.
3926
+ const visibleLayout = (layout) => readOnly ? this.observerStrings(layout) : layout;
3693
3927
  if (this.savedLayout) {
3694
3928
  res.writeHead(200, { 'Content-Type': 'application/json' });
3695
- res.end(JSON.stringify(this.savedLayout));
3929
+ res.end(JSON.stringify(visibleLayout(this.savedLayout)));
3696
3930
  }
3697
3931
  else {
3698
3932
  // Try loading from disk
@@ -3700,7 +3934,7 @@ export class MirrorStreamServer {
3700
3934
  const data = await readFile(this.layoutFilePath, 'utf-8');
3701
3935
  this.savedLayout = JSON.parse(data);
3702
3936
  res.writeHead(200, { 'Content-Type': 'application/json' });
3703
- res.end(JSON.stringify(this.savedLayout));
3937
+ res.end(JSON.stringify(visibleLayout(this.savedLayout)));
3704
3938
  }
3705
3939
  catch {
3706
3940
  res.writeHead(404, { 'Content-Type': 'application/json' });
@@ -3819,11 +4053,11 @@ export class MirrorStreamServer {
3819
4053
  Connection: 'keep-alive',
3820
4054
  });
3821
4055
  res.write('\n');
3822
- const client = { id, res, canInspectPrompts, readOnly, shareId: auth.session?.shareId };
4056
+ const client = { id, res, canInspectPrompts, readOnly, shareId: auth.session?.shareId, session: auth.session };
3823
4057
  this.clients.set(id, client);
3824
4058
  const sendSnapshot = (type, data) => {
3825
4059
  const event = { type, data, timestamp: new Date().toISOString() };
3826
- const visible = readOnly ? this.observerEvent(event) : event;
4060
+ const visible = readOnly ? this.observerEvent(event, true) : event;
3827
4061
  if (visible)
3828
4062
  res.write(`data: ${JSON.stringify(visible)}\n\n`);
3829
4063
  };
@@ -3892,28 +4126,35 @@ export class MirrorStreamServer {
3892
4126
  data: getActiveAccountsSummary(),
3893
4127
  })}\n\n`);
3894
4128
  }
4129
+ // A pane's goal, task handoff and evidence are replayed as they are published: a read-only client gets them
4130
+ // through the observer projection, which leaves all three out, so the prompts and tool output its evidence keeps
4131
+ // never reach an observation link.
4132
+ const sendReplay = (event) => {
4133
+ const visible = readOnly ? this.observerEvent(event) : event;
4134
+ if (visible)
4135
+ res.write(`data: ${JSON.stringify(visible)}\n\n`);
4136
+ };
3895
4137
  // Replay cached pane content that may have been evicted from event history,
3896
4138
  // so new clients always see it regardless of history depth.
3897
4139
  for (const [pid, info] of this.panes.entries()) {
3898
4140
  if (info.commandPane)
3899
4141
  sendSnapshot('command_pane', { pane_id: pid, command: info.commandPane });
3900
4142
  if (info.goal) {
3901
- res.write(`data: ${JSON.stringify({ type: 'goal', timestamp: new Date().toISOString(),
3902
- data: { pane_id: pid, ...info.goal } })}\n\n`);
4143
+ sendReplay({ type: 'goal', timestamp: new Date().toISOString(), data: { pane_id: pid, ...info.goal } });
3903
4144
  }
3904
4145
  if (info.taskHandoff) {
3905
- res.write(`data: ${JSON.stringify({
4146
+ sendReplay({
3906
4147
  type: 'task_handoff',
3907
4148
  timestamp: new Date().toISOString(),
3908
4149
  data: { pane_id: pid, ...info.taskHandoff },
3909
- })}\n\n`);
4150
+ });
3910
4151
  }
3911
4152
  if (info.evidence) {
3912
- res.write(`data: ${JSON.stringify({
4153
+ sendReplay({
3913
4154
  type: 'evidence',
3914
4155
  timestamp: new Date().toISOString(),
3915
4156
  data: { pane_id: pid, session_id: info.evidence.sessionId, snapshot: info.evidence.snapshot },
3916
- })}\n\n`);
4157
+ });
3917
4158
  }
3918
4159
  if (info.commandJobs) {
3919
4160
  sendSnapshot('command_jobs', { pane_id: pid, jobs: info.commandJobs });
@@ -3924,7 +4165,12 @@ export class MirrorStreamServer {
3924
4165
  else if (isTerminalPaneType(info.paneType) && info.terminalOutput) {
3925
4166
  // reset:true clears any partial paint, then the buffered tail repaints
3926
4167
  // the terminal — so an idle shell shows its prompt instead of blank.
3927
- sendSnapshot('pane_output', { pane_id: pid, content: info.terminalOutput, reset: true });
4168
+ // A full tail was cut wherever its cap fell, perhaps through a credential: an observer's starts at the
4169
+ // first whitespace after the cut, where no credential begins midway.
4170
+ const cut = readOnly && info.terminalOutput.length >= TERMINAL_OUTPUT_CAP ? info.terminalOutput.search(/\s/) : 0;
4171
+ const content = cut < 0 ? '' : info.terminalOutput.slice(cut);
4172
+ if (content)
4173
+ sendSnapshot('pane_output', { pane_id: pid, content, reset: true });
3928
4174
  }
3929
4175
  }
3930
4176
  // SSE keepalive: write a comment line every 25s so intermediaries
@@ -3940,13 +4186,25 @@ export class MirrorStreamServer {
3940
4186
  // ignore — connection cleanup handled by 'close' below
3941
4187
  }
3942
4188
  }, 25000);
3943
- const expiryTimer = readOnly && auth.session
3944
- ? setTimeout(() => {
3945
- res.write(`data: ${JSON.stringify({ type: 'share_expired', data: { share_id: client.shareId } })}\n\n`);
4189
+ // A stream opened with a session ends when the session does, at its token's expiry, which no use of the session
4190
+ // moves; an observer is told its share expired first. The timer checks the time when it fires and waits again
4191
+ // for what is left, so it neither ends a live session early nor overflows on a far expiry.
4192
+ let expiryTimer = null;
4193
+ const session = auth.session;
4194
+ if (session) {
4195
+ const endAtExpiry = () => {
4196
+ const remaining = session.expiresAtMs - Date.now();
4197
+ if (remaining > 0) {
4198
+ expiryTimer = setTimeout(endAtExpiry, Math.min(remaining, MAX_TIMER_DELAY_MS));
4199
+ return;
4200
+ }
4201
+ if (readOnly)
4202
+ res.write(`data: ${JSON.stringify({ type: 'share_expired', data: { share_id: client.shareId } })}\n\n`);
3946
4203
  res.end();
3947
4204
  this.clients.delete(id);
3948
- }, Math.max(1, auth.session.expiresAtMs - Date.now()))
3949
- : null;
4205
+ };
4206
+ endAtExpiry();
4207
+ }
3950
4208
  req.on('close', () => {
3951
4209
  clearInterval(keepAliveTimer);
3952
4210
  if (expiryTimer)
@@ -4074,6 +4332,12 @@ export class MirrorStreamServer {
4074
4332
  if (url.pathname === '/api/colony/log-pane' && req.method === 'POST') {
4075
4333
  try {
4076
4334
  const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
4335
+ const refusal = colonyLogPaneRefusal(parsed.id);
4336
+ if (refusal) {
4337
+ res.writeHead(refusal.status, { 'Content-Type': 'application/json' });
4338
+ res.end(JSON.stringify({ ok: false, error: refusal.error }));
4339
+ return;
4340
+ }
4077
4341
  const paneId = parsed.id;
4078
4342
  const action = parsed.action || 'create';
4079
4343
  if (action === 'remove') {
@@ -4107,6 +4371,12 @@ export class MirrorStreamServer {
4107
4371
  if (url.pathname === '/api/colony/log-output' && req.method === 'POST') {
4108
4372
  try {
4109
4373
  const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
4374
+ const refusal = colonyLogPaneRefusal(parsed.id);
4375
+ if (refusal) {
4376
+ res.writeHead(refusal.status, { 'Content-Type': 'application/json' });
4377
+ res.end(JSON.stringify({ ok: false, error: refusal.error }));
4378
+ return;
4379
+ }
4110
4380
  const paneId = parsed.id;
4111
4381
  const pane = this.panes.get(paneId);
4112
4382
  if (pane) {
@@ -4231,9 +4501,9 @@ export class MirrorStreamServer {
4231
4501
  res.end(JSON.stringify({ ok: false, error: 'capture_id is required' }));
4232
4502
  return;
4233
4503
  }
4234
- // Per-IP moving-window rate limit — complements the 8MB body cap and
4504
+ // Per-source moving-window rate limit — complements the 8MB body cap and
4235
4505
  // 90s tmpfile TTL so a burst from one source can't fill the disk.
4236
- const rateKey = this.rateLimitKey(req);
4506
+ const rateKey = this.rateLimitKey(req, auth);
4237
4507
  if (!this.allowZlickyCapture(rateKey)) {
4238
4508
  res.writeHead(429, { 'Content-Type': 'application/json' });
4239
4509
  res.end(JSON.stringify({
@@ -4263,6 +4533,11 @@ export class MirrorStreamServer {
4263
4533
  res.end(JSON.stringify({ ok: false, error: 'capture payload too large' }));
4264
4534
  return;
4265
4535
  }
4536
+ if (!ZLICKY_CAPTURE_SIGNATURES[mime](buf)) {
4537
+ res.writeHead(415, { 'Content-Type': 'application/json' });
4538
+ res.end(JSON.stringify({ ok: false, error: `capture is not a ${mime} image` }));
4539
+ return;
4540
+ }
4266
4541
  const width = Math.max(Number(req.headers['x-zlicky-width'] || 0) | 0, 0);
4267
4542
  const height = Math.max(Number(req.headers['x-zlicky-height'] || 0) | 0, 0);
4268
4543
  const ext = mime === 'image/jpeg' ? 'jpg' : mime === 'image/webp' ? 'webp' : 'png';
@@ -4295,12 +4570,19 @@ export class MirrorStreamServer {
4295
4570
  for (const r of pending.resolvers.splice(0, pending.resolvers.length)) {
4296
4571
  r.resolve(payload);
4297
4572
  }
4298
- // Schedule tmpfile cleanup so the disk doesn't fill up if nothing reads it.
4573
+ // Schedule tmpfile cleanup so the disk doesn't fill up if nothing reads it. Each frame's timer removes its own
4574
+ // file, a later one posted under the same capture id included. The id is forgotten with its latest frame unless a
4575
+ // request still waits on it: that request keeps the id (with no frame held) for the next frame, and its own
4576
+ // timeout forgets the id when nothing has come.
4299
4577
  const cleanupTimer = setTimeout(() => {
4300
- if (this.zlickyCaptures.get(captureId) === pending) {
4301
- void unlink(tmpPath).catch(() => { });
4578
+ void unlink(tmpPath).catch(() => { });
4579
+ const held = this.zlickyCaptures.get(captureId);
4580
+ if (held?.arrived?.tmpPath !== tmpPath)
4581
+ return;
4582
+ if (held.resolvers.length > 0)
4583
+ held.arrived = null;
4584
+ else
4302
4585
  this.zlickyCaptures.delete(captureId);
4303
- }
4304
4586
  }, ZLICKY_CAPTURE_TTL_MS);
4305
4587
  cleanupTimer.unref?.();
4306
4588
  res.writeHead(200, { 'Content-Type': 'application/json' });
@@ -4318,10 +4600,11 @@ export class MirrorStreamServer {
4318
4600
  res.end(JSON.stringify({ ok: false, error: 'no capture ready for this id' }));
4319
4601
  return;
4320
4602
  }
4603
+ // What is held, never where: no caller of this route reads the frame's path, and a browser session is never told
4604
+ // one of this computer's. The agent's zlicky_look tool reads it from requestZlickyCapture's in-process answer.
4321
4605
  res.writeHead(200, { 'Content-Type': 'application/json' });
4322
4606
  res.end(JSON.stringify({
4323
4607
  ok: true,
4324
- tmp_path: pending.arrived.tmpPath,
4325
4608
  mime: pending.arrived.mime,
4326
4609
  byte_length: pending.arrived.byteLength,
4327
4610
  width: pending.arrived.width,
@@ -4530,6 +4813,8 @@ export class MirrorStreamServer {
4530
4813
  const parsed = await this.readJsonBody(req, req.headers['x-ztc-tool-image'] === '1' ? MAX_TOOL_IMAGE_BODY_BYTES : MAX_MIRROR_EVENT_BODY_BYTES);
4531
4814
  if (auth.source === 'pane' && !this.requirePaneIdentity(auth, Number(parsed?.pane_id), res))
4532
4815
  return;
4816
+ if (auth.source === 'pane' && this.refusePaneEvent(parsed, res))
4817
+ return;
4533
4818
  if (!this.admitChildPublication(parsed, res, url.pathname.slice('/pane-events'.length)))
4534
4819
  return;
4535
4820
  // Inject pane_id into event data and broadcast to SSE clients
@@ -4610,6 +4895,8 @@ export class MirrorStreamServer {
4610
4895
  const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
4611
4896
  if (auth.source === 'pane' && !this.requirePaneIdentity(auth, Number(parsed?.pane_id), res))
4612
4897
  return;
4898
+ if (auth.source === 'pane' && this.refusePaneEvent(parsed, res))
4899
+ return;
4613
4900
  if (!this.admitChildPublication(parsed, res, ''))
4614
4901
  return;
4615
4902
  const event = parsed.event;