@zergai/ztc 0.4.0-beta.1 → 0.5.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 (718) hide show
  1. package/README.md +398 -45
  2. package/RUST_THIRD_PARTY_LICENSES.txt +1080 -822
  3. package/THIRD_PARTY_NOTICES.md +273 -12
  4. package/bin/zmux-darwin-arm64 +0 -0
  5. package/bin/ztc-audio-darwin-arm64 +0 -0
  6. package/bin/ztc-capture-darwin-arm64 +0 -0
  7. package/bin/ztc-computer-darwin-arm64 +0 -0
  8. package/bin/ztc-llm-darwin-arm64 +0 -0
  9. package/bin/ztc-tts-darwin-arm64 +0 -0
  10. package/bin/ztc-tui-darwin-arm64 +0 -0
  11. package/bin/ztc-zlicky-overlay-darwin-arm64 +0 -0
  12. package/bin/zterm-darwin-arm64 +0 -0
  13. package/dist/App.js +1206 -209
  14. package/dist/agent/agent.d.ts +74 -8
  15. package/dist/agent/agent.js +1073 -184
  16. package/dist/agent/backends/account_rotation.d.ts +4 -0
  17. package/dist/agent/backends/account_rotation.js +8 -2
  18. package/dist/agent/backends/anthropic.d.ts +13 -0
  19. package/dist/agent/backends/anthropic.js +169 -28
  20. package/dist/agent/backends/claude_cli.js +18 -8
  21. package/dist/agent/backends/codex_app_server.d.ts +1 -0
  22. package/dist/agent/backends/codex_app_server.js +55 -3
  23. package/dist/agent/backends/codex_auth.d.ts +1 -0
  24. package/dist/agent/backends/codex_auth.js +67 -13
  25. package/dist/agent/backends/codex_buffered_recovery.d.ts +27 -0
  26. package/dist/agent/backends/codex_buffered_recovery.js +293 -0
  27. package/dist/agent/backends/gemini.js +3 -1
  28. package/dist/agent/backends/http_error.d.ts +26 -0
  29. package/dist/agent/backends/http_error.js +221 -0
  30. package/dist/agent/backends/index.d.ts +9 -2
  31. package/dist/agent/backends/index.js +22 -2
  32. package/dist/agent/backends/openai.d.ts +0 -6
  33. package/dist/agent/backends/openai.js +5 -2
  34. package/dist/agent/backends/openai_compatible.d.ts +5 -4
  35. package/dist/agent/backends/openai_compatible.js +26 -19
  36. package/dist/agent/backends/openai_responses.d.ts +8 -3
  37. package/dist/agent/backends/openai_responses.js +77 -33
  38. package/dist/agent/backends/provider_ids.d.ts +1 -0
  39. package/dist/agent/backends/provider_ids.js +4 -0
  40. package/dist/agent/backends/request_metrics.js +12 -2
  41. package/dist/agent/backends/types.d.ts +109 -6
  42. package/dist/agent/backends/types.js +5 -1
  43. package/dist/agent/backends/zrouter_stream.d.ts +6 -1
  44. package/dist/agent/backends/zrouter_stream.js +160 -42
  45. package/dist/agent/background_registry.d.ts +2 -0
  46. package/dist/agent/background_registry.js +1 -0
  47. package/dist/agent/claim_observation.d.ts +6 -0
  48. package/dist/agent/claim_observation.js +54 -0
  49. package/dist/agent/commands/accounts.js +46 -177
  50. package/dist/agent/commands/attention.d.ts +2 -0
  51. package/dist/agent/commands/attention.js +67 -0
  52. package/dist/agent/commands/auth.js +18 -2
  53. package/dist/agent/commands/board.d.ts +2 -0
  54. package/dist/agent/commands/board.js +169 -0
  55. package/dist/agent/commands/clipboard.js +50 -1
  56. package/dist/agent/commands/compact.js +21 -13
  57. package/dist/agent/commands/config.js +4 -1
  58. package/dist/agent/commands/context.js +6 -1
  59. package/dist/agent/commands/desktop.d.ts +2 -0
  60. package/dist/agent/commands/desktop.js +29 -0
  61. package/dist/agent/commands/effort.js +14 -6
  62. package/dist/agent/commands/environment.d.ts +3 -0
  63. package/dist/agent/commands/environment.js +109 -0
  64. package/dist/agent/commands/evidence.d.ts +2 -0
  65. package/dist/agent/commands/evidence.js +9 -0
  66. package/dist/agent/commands/fork.js +4 -3
  67. package/dist/agent/commands/goal.d.ts +33 -1
  68. package/dist/agent/commands/goal.js +174 -14
  69. package/dist/agent/commands/goal_exit.d.ts +36 -0
  70. package/dist/agent/commands/goal_exit.js +120 -0
  71. package/dist/agent/commands/help.js +3 -1
  72. package/dist/agent/commands/history.js +3 -1
  73. package/dist/agent/commands/inbox.d.ts +2 -0
  74. package/dist/agent/commands/inbox.js +148 -0
  75. package/dist/agent/commands/index.js +16 -1
  76. package/dist/agent/commands/input_mode.js +8 -6
  77. package/dist/agent/commands/job.d.ts +2 -0
  78. package/dist/agent/commands/job.js +93 -0
  79. package/dist/agent/commands/keybindings.js +4 -1
  80. package/dist/agent/commands/label.d.ts +2 -0
  81. package/dist/agent/commands/label.js +77 -0
  82. package/dist/agent/commands/layout.d.ts +2 -0
  83. package/dist/agent/commands/layout.js +20 -0
  84. package/dist/agent/commands/mirror.js +16 -1
  85. package/dist/agent/commands/model.js +12 -2
  86. package/dist/agent/commands/permissions.d.ts +3 -1
  87. package/dist/agent/commands/permissions.js +79 -89
  88. package/dist/agent/commands/plan.js +5 -15
  89. package/dist/agent/commands/profile.js +21 -2
  90. package/dist/agent/commands/provider_selection.js +20 -1
  91. package/dist/agent/commands/rename.js +1 -1
  92. package/dist/agent/commands/resources.d.ts +2 -0
  93. package/dist/agent/commands/resources.js +67 -0
  94. package/dist/agent/commands/rewind.d.ts +3 -0
  95. package/dist/agent/commands/rewind.js +16 -0
  96. package/dist/agent/commands/runbooks.d.ts +2 -0
  97. package/dist/agent/commands/runbooks.js +73 -0
  98. package/dist/agent/commands/runbooks_lazy.d.ts +2 -0
  99. package/dist/agent/commands/runbooks_lazy.js +8 -0
  100. package/dist/agent/commands/sessions.d.ts +1 -1
  101. package/dist/agent/commands/sessions.js +33 -5
  102. package/dist/agent/commands/settings.js +185 -39
  103. package/dist/agent/commands/setup.d.ts +2 -0
  104. package/dist/agent/commands/setup.js +78 -0
  105. package/dist/agent/commands/share.d.ts +2 -0
  106. package/dist/agent/commands/share.js +64 -0
  107. package/dist/agent/commands/status.js +14 -2
  108. package/dist/agent/commands/types.d.ts +99 -6
  109. package/dist/agent/commands/update.js +8 -0
  110. package/dist/agent/commands/usage.d.ts +2 -0
  111. package/dist/agent/commands/usage.js +8 -0
  112. package/dist/agent/factory.d.ts +11 -0
  113. package/dist/agent/factory.js +113 -88
  114. package/dist/agent/loop_policy.d.ts +6 -3
  115. package/dist/agent/loop_policy.js +12 -3
  116. package/dist/agent/measurement_guidance.d.ts +2 -0
  117. package/dist/agent/measurement_guidance.js +5 -0
  118. package/dist/agent/request_encoder.d.ts +8 -1
  119. package/dist/agent/request_encoder.js +95 -23
  120. package/dist/agent/runtime/benchmark_comparison.d.ts +30 -0
  121. package/dist/agent/runtime/benchmark_comparison.js +94 -0
  122. package/dist/agent/runtime/benchmark_contract.d.ts +48 -0
  123. package/dist/agent/runtime/benchmark_contract.js +90 -0
  124. package/dist/agent/runtime/checked_commands.d.ts +32 -0
  125. package/dist/agent/runtime/checked_commands.js +119 -0
  126. package/dist/agent/runtime/command_execution_policy.d.ts +26 -0
  127. package/dist/agent/runtime/command_execution_policy.js +91 -0
  128. package/dist/agent/runtime/command_jobs.d.ts +36 -18
  129. package/dist/agent/runtime/command_jobs.js +151 -13
  130. package/dist/agent/runtime/command_panes.d.ts +59 -0
  131. package/dist/agent/runtime/command_panes.js +398 -0
  132. package/dist/agent/runtime/command_wait.d.ts +19 -0
  133. package/dist/agent/runtime/command_wait.js +167 -0
  134. package/dist/agent/runtime/cpu_benchmark.d.ts +30 -0
  135. package/dist/agent/runtime/cpu_benchmark.js +126 -0
  136. package/dist/agent/runtime/delegated_evidence.d.ts +26 -0
  137. package/dist/agent/runtime/delegated_evidence.js +80 -0
  138. package/dist/agent/runtime/evidence.d.ts +127 -0
  139. package/dist/agent/runtime/evidence.js +468 -0
  140. package/dist/agent/runtime/execution_context.d.ts +7 -0
  141. package/dist/agent/runtime/execution_context.js +39 -3
  142. package/dist/agent/runtime/json_verifier_recipe.d.ts +8 -0
  143. package/dist/agent/runtime/json_verifier_recipe.js +66 -0
  144. package/dist/agent/runtime/measurements.d.ts +110 -0
  145. package/dist/agent/runtime/measurements.js +317 -0
  146. package/dist/agent/runtime/policy.d.ts +4 -0
  147. package/dist/agent/runtime/policy.js +31 -20
  148. package/dist/agent/runtime/provider_native_evidence.d.ts +20 -0
  149. package/dist/agent/runtime/provider_native_evidence.js +86 -0
  150. package/dist/agent/runtime/recovery.d.ts +2 -0
  151. package/dist/agent/runtime/recovery.js +45 -2
  152. package/dist/agent/runtime/remote_broker_transport.d.ts +10 -0
  153. package/dist/agent/runtime/remote_broker_transport.js +84 -0
  154. package/dist/agent/runtime/remote_deletion_receipts.d.ts +3 -0
  155. package/dist/agent/runtime/remote_deletion_receipts.js +43 -0
  156. package/dist/agent/runtime/remote_journal_replay.d.ts +13 -0
  157. package/dist/agent/runtime/remote_journal_replay.js +233 -0
  158. package/dist/agent/runtime/remote_mutation_journal.d.ts +25 -0
  159. package/dist/agent/runtime/remote_mutation_journal.js +208 -0
  160. package/dist/agent/runtime/remote_resource_endpoint.d.ts +7 -0
  161. package/dist/agent/runtime/remote_resource_endpoint.js +6 -0
  162. package/dist/agent/runtime/remote_resource_errors.d.ts +5 -0
  163. package/dist/agent/runtime/remote_resource_errors.js +9 -0
  164. package/dist/agent/runtime/remote_resource_script.d.ts +2 -0
  165. package/dist/agent/runtime/remote_resource_script.js +1009 -0
  166. package/dist/agent/runtime/remote_resources.d.ts +29 -0
  167. package/dist/agent/runtime/remote_resources.js +160 -0
  168. package/dist/agent/runtime/source_verification.d.ts +12 -0
  169. package/dist/agent/runtime/source_verification.js +210 -0
  170. package/dist/agent/runtime/source_verification_contract.d.ts +75 -0
  171. package/dist/agent/runtime/source_verification_contract.js +203 -0
  172. package/dist/agent/runtime/tool_checkpoints.d.ts +11 -0
  173. package/dist/agent/runtime/tool_checkpoints.js +26 -0
  174. package/dist/agent/runtime/tool_effects.d.ts +5 -0
  175. package/dist/agent/runtime/tool_progress.d.ts +12 -0
  176. package/dist/agent/runtime/tool_progress.js +76 -0
  177. package/dist/agent/runtime/tool_runtime.d.ts +16 -1
  178. package/dist/agent/runtime/tool_runtime.js +204 -10
  179. package/dist/agent/runtime/tracing.d.ts +1 -1
  180. package/dist/agent/runtime/verifier_capture.d.ts +9 -0
  181. package/dist/agent/runtime/verifier_capture.js +100 -0
  182. package/dist/agent/runtime/verifier_contract.d.ts +24 -0
  183. package/dist/agent/runtime/verifier_contract.js +41 -0
  184. package/dist/agent/subagent.d.ts +20 -10
  185. package/dist/agent/subagent.js +266 -29
  186. package/dist/agent/tool_response_directory.d.ts +24 -0
  187. package/dist/agent/tool_response_directory.js +61 -0
  188. package/dist/agent/tool_response_source.d.ts +8 -0
  189. package/dist/agent/tool_response_source.js +49 -0
  190. package/dist/agent/tool_response_store.d.ts +75 -4
  191. package/dist/agent/tool_response_store.js +583 -64
  192. package/dist/agent/tools/ask_user.d.ts +3 -1
  193. package/dist/agent/tools/ask_user.js +30 -11
  194. package/dist/agent/tools/background.js +1 -0
  195. package/dist/agent/tools/benchmark_cpu.d.ts +2 -0
  196. package/dist/agent/tools/benchmark_cpu.js +102 -0
  197. package/dist/agent/tools/compare_benchmarks.d.ts +2 -0
  198. package/dist/agent/tools/compare_benchmarks.js +53 -0
  199. package/dist/agent/tools/deferred.js +1 -0
  200. package/dist/agent/tools/delegate.js +18 -2
  201. package/dist/agent/tools/helper_requirements.d.ts +7 -0
  202. package/dist/agent/tools/helper_requirements.js +19 -0
  203. package/dist/agent/tools/index.d.ts +1 -0
  204. package/dist/agent/tools/index.js +3 -0
  205. package/dist/agent/tools/measurement_report.d.ts +22 -0
  206. package/dist/agent/tools/measurement_report.js +190 -0
  207. package/dist/agent/tools/pane.d.ts +0 -7
  208. package/dist/agent/tools/pane.js +5 -4
  209. package/dist/agent/tools/project_context.d.ts +3 -0
  210. package/dist/agent/tools/project_context.js +45 -0
  211. package/dist/agent/tools/recall_tool_response.d.ts +3 -5
  212. package/dist/agent/tools/recall_tool_response.js +19 -29
  213. package/dist/agent/tools/registry.d.ts +1 -0
  214. package/dist/agent/tools/registry.js +23 -0
  215. package/dist/agent/tools/related_sessions.d.ts +2 -0
  216. package/dist/agent/tools/related_sessions.js +156 -0
  217. package/dist/agent/tools/routine.js +13 -3
  218. package/dist/agent/tools/session_evidence.d.ts +3 -0
  219. package/dist/agent/tools/session_evidence.js +72 -0
  220. package/dist/agent/tools/shell.d.ts +4 -3
  221. package/dist/agent/tools/shell.js +174 -47
  222. package/dist/agent/tools/tool_search.js +3 -2
  223. package/dist/agent/tools/types.d.ts +28 -0
  224. package/dist/agent/tools/verify_artifact.d.ts +2 -0
  225. package/dist/agent/tools/verify_artifact.js +60 -0
  226. package/dist/agent/tools/workflow.js +1 -0
  227. package/dist/app/activity.d.ts +6 -1
  228. package/dist/app/activity.js +81 -12
  229. package/dist/app/agent_runner.d.ts +6 -1
  230. package/dist/app/agent_runner.js +34 -19
  231. package/dist/app/command_context.js +106 -10
  232. package/dist/app/controller.d.ts +15 -4
  233. package/dist/app/controller.js +29 -3
  234. package/dist/app/escape_stop.d.ts +11 -0
  235. package/dist/app/escape_stop.js +15 -0
  236. package/dist/app/liveness.d.ts +6 -4
  237. package/dist/app/liveness.js +13 -3
  238. package/dist/app/model_catalog_cache.d.ts +5 -0
  239. package/dist/app/model_catalog_cache.js +138 -0
  240. package/dist/app/ordered_transcript.js +43 -4
  241. package/dist/app/prompt_turn.d.ts +14 -0
  242. package/dist/app/prompt_turn.js +53 -0
  243. package/dist/app/recap.d.ts +3 -0
  244. package/dist/app/recap.js +9 -3
  245. package/dist/app/restart.d.ts +3 -2
  246. package/dist/app/restart.js +22 -7
  247. package/dist/app/rewind.d.ts +3 -3
  248. package/dist/app/rewind.js +3 -3
  249. package/dist/app/selection_completion.d.ts +17 -2
  250. package/dist/app/selection_completion.js +84 -9
  251. package/dist/app/session_manager.d.ts +38 -6
  252. package/dist/app/session_manager.js +263 -60
  253. package/dist/app/session_messages.d.ts +3 -0
  254. package/dist/app/session_messages.js +60 -0
  255. package/dist/app/task_scope_router.d.ts +20 -0
  256. package/dist/app/task_scope_router.js +173 -0
  257. package/dist/app/transcript_window.d.ts +2 -0
  258. package/dist/app/transcript_window.js +4 -0
  259. package/dist/app/workspace_admission_details.d.ts +3 -0
  260. package/dist/app/workspace_admission_details.js +26 -0
  261. package/dist/app/workspace_layout_controller.d.ts +11 -0
  262. package/dist/app/workspace_layout_controller.js +88 -0
  263. package/dist/app/workspace_monitor.d.ts +1 -0
  264. package/dist/app/workspace_monitor.js +216 -0
  265. package/dist/app/workspace_presets.d.ts +29 -0
  266. package/dist/app/workspace_presets.js +192 -0
  267. package/dist/attention/queue.d.ts +37 -0
  268. package/dist/attention/queue.js +183 -0
  269. package/dist/bench/rf_shared.d.ts +2 -0
  270. package/dist/board/binding.d.ts +42 -0
  271. package/dist/board/binding.js +38 -0
  272. package/dist/board/client.d.ts +42 -0
  273. package/dist/board/client.js +60 -0
  274. package/dist/cli.js +1 -1
  275. package/dist/cli_args.js +19 -17
  276. package/dist/cli_main.js +110 -13
  277. package/dist/cli_ratatui.d.ts +183 -16
  278. package/dist/cli_ratatui.js +3989 -1255
  279. package/dist/components/ActivityLine.d.ts +3 -2
  280. package/dist/components/ActivityLine.js +2 -2
  281. package/dist/components/InputArea.d.ts +19 -1
  282. package/dist/components/InputArea.js +264 -190
  283. package/dist/components/MessageList.d.ts +2 -0
  284. package/dist/components/MessageList.js +3 -1
  285. package/dist/components/SingleMessage.d.ts +2 -0
  286. package/dist/components/SingleMessage.js +4 -2
  287. package/dist/components/StatusBar.d.ts +4 -2
  288. package/dist/components/StatusBar.js +3 -1
  289. package/dist/conductor_branch.js +3 -0
  290. package/dist/config/api_retry.d.ts +6 -1
  291. package/dist/config/api_retry.js +19 -1
  292. package/dist/config/defaults.d.ts +2 -1
  293. package/dist/config/defaults.js +9 -2
  294. package/dist/config/message_display.d.ts +1 -0
  295. package/dist/config/message_display.js +17 -2
  296. package/dist/config/permissions.d.ts +21 -0
  297. package/dist/config/permissions.js +89 -0
  298. package/dist/config/resolved.d.ts +2 -2
  299. package/dist/config/types.d.ts +32 -5
  300. package/dist/config.d.ts +38 -4
  301. package/dist/config.js +290 -42
  302. package/dist/context/project_intelligence.d.ts +44 -0
  303. package/dist/context/project_intelligence.js +246 -0
  304. package/dist/desktop/cli_launch.d.ts +8 -0
  305. package/dist/desktop/cli_launch.js +6 -0
  306. package/dist/desktop/cli_shim.d.ts +8 -0
  307. package/dist/desktop/cli_shim.js +120 -0
  308. package/dist/desktop/runtime.d.ts +16 -0
  309. package/dist/desktop/runtime.js +161 -0
  310. package/dist/desktop/worker_launch.d.ts +7 -0
  311. package/dist/desktop/worker_launch.js +7 -0
  312. package/dist/diagnostics/cargo_mutants_selection.d.ts +27 -0
  313. package/dist/diagnostics/cargo_mutants_selection.js +48 -0
  314. package/dist/diagnostics/native_terminal_benchmark.d.ts +58 -0
  315. package/dist/diagnostics/native_terminal_benchmark.js +1247 -0
  316. package/dist/diagnostics/session_evidence_package.d.ts +40 -0
  317. package/dist/diagnostics/session_evidence_package.js +234 -0
  318. package/dist/diagnostics/session_export.d.ts +93 -0
  319. package/dist/diagnostics/session_export.js +634 -0
  320. package/dist/emulation/tool_adapters.js +48 -18
  321. package/dist/emulation/ztc_addendum.d.ts +1 -0
  322. package/dist/emulation/ztc_addendum.js +13 -12
  323. package/dist/environment/service_runner.d.ts +1 -0
  324. package/dist/environment/service_runner.js +68 -0
  325. package/dist/environment/store.d.ts +120 -0
  326. package/dist/environment/store.js +387 -0
  327. package/dist/events.d.ts +40 -1
  328. package/dist/events.js +10 -17
  329. package/dist/goal_contract.d.ts +25 -0
  330. package/dist/goal_contract.js +44 -0
  331. package/dist/headless.d.ts +31 -0
  332. package/dist/headless.js +578 -70
  333. package/dist/headless_cli.js +8 -0
  334. package/dist/headless_cli_args.d.ts +1 -0
  335. package/dist/headless_cli_args.js +1 -0
  336. package/dist/intake/cli.d.ts +1 -0
  337. package/dist/intake/cli.js +33 -0
  338. package/dist/intake/format.d.ts +2 -0
  339. package/dist/intake/format.js +14 -0
  340. package/dist/intake/notifications.d.ts +16 -0
  341. package/dist/intake/notifications.js +132 -0
  342. package/dist/intake/store.d.ts +56 -0
  343. package/dist/intake/store.js +238 -0
  344. package/dist/library.d.ts +8 -0
  345. package/dist/library.js +19 -10
  346. package/dist/mcp/client.d.ts +1 -0
  347. package/dist/mcp/client.js +20 -0
  348. package/dist/modes/builtin/plan.yaml +2 -2
  349. package/dist/modes/handlers.js +1 -1
  350. package/dist/onboarding/first_run.d.ts +3 -0
  351. package/dist/onboarding/first_run.js +33 -25
  352. package/dist/onboarding/setup.d.ts +32 -0
  353. package/dist/onboarding/setup.js +133 -0
  354. package/dist/onboarding/setup_agent_health.d.ts +17 -0
  355. package/dist/onboarding/setup_agent_health.js +79 -0
  356. package/dist/onboarding/setup_environment.d.ts +66 -0
  357. package/dist/onboarding/setup_environment.js +219 -0
  358. package/dist/onboarding/setup_workspace.d.ts +17 -0
  359. package/dist/onboarding/setup_workspace.js +129 -0
  360. package/dist/optimize/adapters/index.d.ts +4 -1
  361. package/dist/optimize/adapters/index.js +7 -0
  362. package/dist/optimize/adapters/kernelbench.js +14 -5
  363. package/dist/optimize/adapters/popcorn.js +3 -2
  364. package/dist/optimize/adapters/profile_benchmark.js +13 -7
  365. package/dist/optimize/adapters/rfbench.js +25 -14
  366. package/dist/optimize/adapters/types.d.ts +3 -0
  367. package/dist/optimize/adapters/zergpod.js +5 -2
  368. package/dist/optimize/baseline.js +10 -21
  369. package/dist/optimize/branch.js +9 -12
  370. package/dist/optimize/combine.js +2 -3
  371. package/dist/optimize/executor.js +34 -48
  372. package/dist/optimize/measurements.d.ts +55 -0
  373. package/dist/optimize/measurements.js +173 -0
  374. package/dist/optimize/results.d.ts +1 -0
  375. package/dist/optimize/results.js +11 -33
  376. package/dist/optimize/tge.js +2 -1
  377. package/dist/panes/initial_input.d.ts +19 -0
  378. package/dist/panes/initial_input.js +206 -0
  379. package/dist/panes/labels.d.ts +16 -0
  380. package/dist/panes/labels.js +42 -0
  381. package/dist/panes/model_catalog.d.ts +3 -3
  382. package/dist/panes/model_catalog.js +28 -4
  383. package/dist/panes/pane_registry.js +6 -2
  384. package/dist/panes/types.d.ts +3 -0
  385. package/dist/panes/ztc_launch.js +19 -0
  386. package/dist/plugin/optimization.d.ts +2 -0
  387. package/dist/plugin/optimization.js +1 -0
  388. package/dist/plugin/runtime.d.ts +2 -0
  389. package/dist/plugin/simulation.d.ts +6 -1
  390. package/dist/plugin/simulation_contract.d.ts +836 -1
  391. package/dist/plugin/simulation_documents.d.ts +22 -0
  392. package/dist/plugin/simulation_documents.js +1 -0
  393. package/dist/plugin/simulation_interventions.d.ts +103 -0
  394. package/dist/plugin/simulation_interventions.js +1 -0
  395. package/dist/plugin/simulation_living.d.ts +1 -0
  396. package/dist/plugin/simulation_living.js +3 -0
  397. package/dist/plugin/simulation_meetings.d.ts +121 -0
  398. package/dist/plugin/simulation_meetings.js +1 -0
  399. package/dist/plugin/simulation_story_review.d.ts +111 -0
  400. package/dist/plugin/simulation_story_review.js +1 -0
  401. package/dist/plugin/simulation_storyteller.d.ts +91 -0
  402. package/dist/plugin/simulation_storyteller.js +1 -0
  403. package/dist/plugin/simulation_structured.d.ts +2 -0
  404. package/dist/plugin/simulation_structured.js +2 -0
  405. package/dist/plugin/simulation_toolkit.d.ts +21 -0
  406. package/dist/plugin/simulation_toolkit.js +24 -0
  407. package/dist/prompts/tool_delegate_task.j2 +1 -1
  408. package/dist/remote-broker/Dockerfile +10 -0
  409. package/dist/remote-broker/archive.py +1227 -0
  410. package/dist/remote-broker/cutover.py +761 -0
  411. package/dist/remote-broker/requirements.txt +5 -0
  412. package/dist/remote-broker/resources.json +6 -0
  413. package/dist/remote-broker/resources.write-staging.example.json +18 -0
  414. package/dist/remote-broker/retained.py +686 -0
  415. package/dist/remote-broker/retained_cleanup.py +550 -0
  416. package/dist/remote-broker/server.py +648 -0
  417. package/dist/remote-broker/worker.py +1007 -0
  418. package/dist/router_auth.d.ts +31 -0
  419. package/dist/router_auth.js +155 -9
  420. package/dist/runbooks/catalog.d.ts +3 -0
  421. package/dist/runbooks/catalog.js +26 -0
  422. package/dist/runbooks/library.d.ts +11 -0
  423. package/dist/runbooks/library.js +95 -0
  424. package/dist/runbooks/package.d.ts +43 -0
  425. package/dist/runbooks/package.js +102 -0
  426. package/dist/session.d.ts +65 -13
  427. package/dist/session.js +548 -43
  428. package/dist/session_handoff.d.ts +25 -0
  429. package/dist/session_handoff.js +322 -0
  430. package/dist/session_handoff_contract.d.ts +89 -0
  431. package/dist/session_handoff_contract.js +179 -0
  432. package/dist/session_media.d.ts +41 -0
  433. package/dist/session_media.js +357 -0
  434. package/dist/session_ownership.d.ts +16 -0
  435. package/dist/session_ownership.js +221 -0
  436. package/dist/session_public.d.ts +10 -2
  437. package/dist/session_public.js +6 -1
  438. package/dist/simulation/dynamic_history.d.ts +42 -0
  439. package/dist/simulation/dynamic_history.js +173 -0
  440. package/dist/simulation/engines/swarm/pane_manager.js +7 -6
  441. package/dist/simulation/inference.d.ts +3 -1
  442. package/dist/simulation/inference.js +19 -1
  443. package/dist/simulation/intervention_generation.d.ts +27 -0
  444. package/dist/simulation/intervention_generation.js +246 -0
  445. package/dist/simulation/intervention_material.d.ts +4 -0
  446. package/dist/simulation/intervention_material.js +81 -0
  447. package/dist/simulation/living/context.d.ts +3130 -0
  448. package/dist/simulation/living/context.js +944 -0
  449. package/dist/simulation/living/definer.d.ts +12 -0
  450. package/dist/simulation/living/definer.js +223 -0
  451. package/dist/simulation/living/definition.d.ts +257 -0
  452. package/dist/simulation/living/definition.js +341 -0
  453. package/dist/simulation/living/frame.d.ts +259 -0
  454. package/dist/simulation/living/frame.js +223 -0
  455. package/dist/simulation/living/identifiers.d.ts +2 -0
  456. package/dist/simulation/living/identifiers.js +12 -0
  457. package/dist/simulation/living/index.d.ts +15 -0
  458. package/dist/simulation/living/index.js +15 -0
  459. package/dist/simulation/living/inference.d.ts +219 -0
  460. package/dist/simulation/living/inference.js +576 -0
  461. package/dist/simulation/living/mechanics.d.ts +54 -0
  462. package/dist/simulation/living/mechanics.js +588 -0
  463. package/dist/simulation/living/model-input.d.ts +25 -0
  464. package/dist/simulation/living/model-input.js +215 -0
  465. package/dist/simulation/living/open-world.d.ts +257 -0
  466. package/dist/simulation/living/open-world.js +102 -0
  467. package/dist/simulation/living/projection.d.ts +7 -0
  468. package/dist/simulation/living/projection.js +31 -0
  469. package/dist/simulation/living/recall.d.ts +17 -0
  470. package/dist/simulation/living/recall.js +25 -0
  471. package/dist/simulation/living/reduce.d.ts +15 -0
  472. package/dist/simulation/living/reduce.js +1853 -0
  473. package/dist/simulation/living/replay.d.ts +6 -0
  474. package/dist/simulation/living/replay.js +22 -0
  475. package/dist/simulation/living/runtime.d.ts +140 -0
  476. package/dist/simulation/living/runtime.js +3020 -0
  477. package/dist/simulation/living/shared-kinds.d.ts +24 -0
  478. package/dist/simulation/living/shared-kinds.js +96 -0
  479. package/dist/simulation/living/types.d.ts +2785 -0
  480. package/dist/simulation/living/types.js +669 -0
  481. package/dist/simulation/llm.d.ts +3 -1
  482. package/dist/simulation/llm.js +90 -30
  483. package/dist/simulation/memory/embedding.d.ts +1 -1
  484. package/dist/simulation/memory/embedding.js +9 -3
  485. package/dist/simulation/memory/filesystem.d.ts +2 -0
  486. package/dist/simulation/memory/filesystem.js +5 -1
  487. package/dist/simulation/memory/filesystem_file_tree.d.ts +4 -1
  488. package/dist/simulation/memory/filesystem_file_tree.js +41 -10
  489. package/dist/simulation/memory/filesystem_invariants.js +1 -2
  490. package/dist/simulation/memory/filesystem_types.d.ts +1 -0
  491. package/dist/simulation/memory/memory.d.ts +2 -0
  492. package/dist/simulation/memory/memory.js +5 -1
  493. package/dist/simulation/orchestration/intent.js +0 -2
  494. package/dist/simulation/orchestration/lifecycle.js +0 -2
  495. package/dist/simulation/plugin_host.d.ts +25 -1
  496. package/dist/simulation/plugin_host.js +334 -17
  497. package/dist/simulation/session_documents.d.ts +20 -0
  498. package/dist/simulation/session_documents.js +62 -0
  499. package/dist/simulation/session_input_validation.d.ts +43 -0
  500. package/dist/simulation/session_input_validation.js +364 -0
  501. package/dist/simulation/session_inputs.d.ts +32 -0
  502. package/dist/simulation/session_inputs.js +154 -0
  503. package/dist/simulation/telemetry.d.ts +11 -14
  504. package/dist/simulation/telemetry.js +177 -54
  505. package/dist/simulation/toolkit/bounded_turns.d.ts +13 -0
  506. package/dist/simulation/toolkit/bounded_turns.js +80 -0
  507. package/dist/simulation/toolkit/dynamic_agents.d.ts +25 -0
  508. package/dist/simulation/toolkit/dynamic_agents.js +218 -0
  509. package/dist/simulation/toolkit/dynamic_digest.d.ts +1 -0
  510. package/dist/simulation/toolkit/dynamic_digest.js +8 -0
  511. package/dist/simulation/toolkit/dynamic_documents.d.ts +7 -0
  512. package/dist/simulation/toolkit/dynamic_documents.js +71 -0
  513. package/dist/simulation/toolkit/dynamic_driver.d.ts +8 -0
  514. package/dist/simulation/toolkit/dynamic_driver.js +269 -0
  515. package/dist/simulation/toolkit/dynamic_game.d.ts +53 -0
  516. package/dist/simulation/toolkit/dynamic_game.js +805 -0
  517. package/dist/simulation/toolkit/dynamic_knowledge.d.ts +15 -0
  518. package/dist/simulation/toolkit/dynamic_knowledge.js +91 -0
  519. package/dist/simulation/toolkit/dynamic_mechanics.d.ts +22 -0
  520. package/dist/simulation/toolkit/dynamic_mechanics.js +910 -0
  521. package/dist/simulation/toolkit/dynamic_meetings.d.ts +239 -0
  522. package/dist/simulation/toolkit/dynamic_meetings.js +350 -0
  523. package/dist/simulation/toolkit/dynamic_progress.d.ts +131 -0
  524. package/dist/simulation/toolkit/dynamic_progress.js +214 -0
  525. package/dist/simulation/toolkit/dynamic_projection.d.ts +9 -0
  526. package/dist/simulation/toolkit/dynamic_projection.js +219 -0
  527. package/dist/simulation/toolkit/dynamic_runtime.d.ts +412 -0
  528. package/dist/simulation/toolkit/dynamic_runtime.js +6536 -0
  529. package/dist/simulation/toolkit/dynamic_state.d.ts +111 -0
  530. package/dist/simulation/toolkit/dynamic_state.js +1967 -0
  531. package/dist/simulation/toolkit/dynamic_story_review.d.ts +508 -0
  532. package/dist/simulation/toolkit/dynamic_story_review.js +333 -0
  533. package/dist/simulation/toolkit/dynamic_storyteller.d.ts +77 -0
  534. package/dist/simulation/toolkit/dynamic_storyteller.js +114 -0
  535. package/dist/simulation/toolkit/dynamic_storyteller_runtime.d.ts +26 -0
  536. package/dist/simulation/toolkit/dynamic_storyteller_runtime.js +126 -0
  537. package/dist/simulation/toolkit/dynamic_world.d.ts +22 -0
  538. package/dist/simulation/toolkit/dynamic_world.js +377 -0
  539. package/dist/simulation/toolkit/structured_output.d.ts +5 -0
  540. package/dist/simulation/toolkit/structured_output.js +321 -0
  541. package/dist/simulation/types/world.d.ts +2 -0
  542. package/dist/simulation/world/artifact_store.js +1 -1
  543. package/dist/simulation/world/memory_manager.d.ts +5 -0
  544. package/dist/simulation/world/memory_manager.js +17 -2
  545. package/dist/simulation/world/state.d.ts +3 -2
  546. package/dist/simulation/world/state.js +15 -5
  547. package/dist/skills/bundled/measurement-validation/SKILL.md +144 -0
  548. package/dist/terminal_attach.d.ts +1 -0
  549. package/dist/terminal_attach.js +113 -0
  550. package/dist/tool_progress.d.ts +3 -0
  551. package/dist/tool_progress.js +27 -0
  552. package/dist/types.d.ts +145 -10
  553. package/dist/types.js +3 -0
  554. package/dist/ui/core/input.d.ts +3 -0
  555. package/dist/ui/core/input_segments.d.ts +18 -1
  556. package/dist/ui/core/input_segments.js +131 -47
  557. package/dist/ui/core/input_state.d.ts +12 -0
  558. package/dist/ui/core/layout_yoga.d.ts +1 -1
  559. package/dist/ui/core/turn_metadata.d.ts +5 -0
  560. package/dist/ui/core/turn_metadata.js +22 -0
  561. package/dist/ui/ink/render.d.ts +2 -1
  562. package/dist/ui/ink/render.js +6 -5
  563. package/dist/ui/ratatui/headless_pane_manager.d.ts +14 -1
  564. package/dist/ui/ratatui/headless_pane_manager.js +293 -104
  565. package/dist/ui/ratatui/index.d.ts +1 -0
  566. package/dist/ui/ratatui/input.d.ts +4 -0
  567. package/dist/ui/ratatui/input.js +15 -0
  568. package/dist/ui/ratatui/ipc_path.d.ts +2 -0
  569. package/dist/ui/ratatui/ipc_path.js +29 -1
  570. package/dist/ui/ratatui/mux_persistence.d.ts +3 -1
  571. package/dist/ui/ratatui/mux_persistence.js +139 -1
  572. package/dist/ui/ratatui/pane_relay.d.ts +1 -1
  573. package/dist/ui/ratatui/pane_relay.js +55 -27
  574. package/dist/ui/ratatui/process.d.ts +17 -1
  575. package/dist/ui/ratatui/process.js +80 -7
  576. package/dist/ui/ratatui/protocol.d.ts +236 -1
  577. package/dist/ui/ratatui/protocol.js +90 -0
  578. package/dist/ui/scrollback.d.ts +2 -1
  579. package/dist/ui/scrollback.js +9 -4
  580. package/dist/ui/stream_typewriter.d.ts +8 -3
  581. package/dist/ui/stream_typewriter.js +30 -1
  582. package/dist/ui/streaming_scrollback.d.ts +1 -0
  583. package/dist/ui/streaming_scrollback.js +1 -1
  584. package/dist/ui/transcript_render_cache.js +10 -0
  585. package/dist/ui/views/activity_line.d.ts +5 -3
  586. package/dist/ui/views/activity_line.js +65 -7
  587. package/dist/ui/views/app.d.ts +6 -3
  588. package/dist/ui/views/app.js +17 -6
  589. package/dist/ui/views/completion_menu.js +10 -5
  590. package/dist/ui/views/input_area.d.ts +7 -3
  591. package/dist/ui/views/input_area.js +15 -9
  592. package/dist/ui/views/message_list.d.ts +4 -1
  593. package/dist/ui/views/message_list.js +89 -19
  594. package/dist/ui/views/queue_panel.d.ts +3 -1
  595. package/dist/ui/views/queue_panel.js +9 -2
  596. package/dist/ui/views/status_bar.d.ts +4 -2
  597. package/dist/ui/views/status_bar.js +28 -13
  598. package/dist/ui/views/theme.d.ts +2 -0
  599. package/dist/ui/views/theme.js +2 -0
  600. package/dist/ui/widgets/color_panel.js +18 -0
  601. package/dist/ui/widgets/form.js +8 -0
  602. package/dist/ui/widgets/log_view.js +7 -0
  603. package/dist/ui/widgets/navigator_panel.js +8 -0
  604. package/dist/ui/widgets/prompt_viewer.js +2 -0
  605. package/dist/ui/widgets/questionnaire.d.ts +2 -0
  606. package/dist/ui/widgets/questionnaire.js +79 -16
  607. package/dist/ui/widgets/resume_panel.d.ts +2 -0
  608. package/dist/ui/widgets/resume_panel.js +26 -15
  609. package/dist/ui/widgets/rewind_panel.d.ts +2 -2
  610. package/dist/ui/widgets/rewind_panel.js +4 -2
  611. package/dist/ui/widgets/select.js +16 -27
  612. package/dist/ui/widgets/settings_panel.js +16 -0
  613. package/dist/ui/widgets/status_line_panel.d.ts +1 -0
  614. package/dist/ui/widgets/status_line_panel.js +30 -4
  615. package/dist/ui/widgets/text_input.d.ts +2 -0
  616. package/dist/ui/widgets/text_input.js +15 -1
  617. package/dist/ui/widgets/types.d.ts +2 -0
  618. package/dist/usage_projection.d.ts +24 -0
  619. package/dist/usage_projection.js +130 -0
  620. package/dist/usage_snapshot.d.ts +36 -0
  621. package/dist/usage_snapshot.js +131 -0
  622. package/dist/utils/assistant_message.d.ts +2 -0
  623. package/dist/utils/assistant_message.js +5 -0
  624. package/dist/utils/atomic_write.d.ts +6 -2
  625. package/dist/utils/atomic_write.js +29 -4
  626. package/dist/utils/checked_shell.d.ts +25 -0
  627. package/dist/utils/checked_shell.js +107 -0
  628. package/dist/utils/compaction.d.ts +4 -1
  629. package/dist/utils/compaction.js +31 -7
  630. package/dist/utils/context.d.ts +4 -4
  631. package/dist/utils/context.js +14 -12
  632. package/dist/utils/deepseek.d.ts +2 -2
  633. package/dist/utils/deepseek.js +13 -5
  634. package/dist/utils/ephemeral.js +4 -0
  635. package/dist/utils/ephemeral_tools.d.ts +18 -0
  636. package/dist/utils/ephemeral_tools.js +97 -0
  637. package/dist/utils/jev_client.d.ts +4 -0
  638. package/dist/utils/jev_client.js +15 -0
  639. package/dist/utils/model_cache.d.ts +15 -0
  640. package/dist/utils/model_cache.js +143 -0
  641. package/dist/utils/models.d.ts +4 -2
  642. package/dist/utils/models.js +12 -16
  643. package/dist/utils/reasoning.d.ts +8 -1
  644. package/dist/utils/reasoning.js +31 -11
  645. package/dist/utils/router_catalog.d.ts +49 -0
  646. package/dist/utils/router_catalog.js +271 -0
  647. package/dist/utils/sandbox.d.ts +9 -0
  648. package/dist/utils/sandbox.js +118 -15
  649. package/dist/utils/shell.d.ts +7 -0
  650. package/dist/utils/shell.js +98 -34
  651. package/dist/utils/subprocess_env.d.ts +3 -0
  652. package/dist/utils/subprocess_env.js +27 -1
  653. package/dist/web/accounts_mirror.d.ts +3 -1
  654. package/dist/web/accounts_mirror.js +13 -9
  655. package/dist/web/child_publication.d.ts +17 -0
  656. package/dist/web/child_publication.js +45 -0
  657. package/dist/web/mirror_authenticator.d.ts +31 -11
  658. package/dist/web/mirror_authenticator.js +67 -17
  659. package/dist/web/mirror_client.d.ts +31 -4
  660. package/dist/web/mirror_client.js +189 -23
  661. package/dist/web/mirror_stream.d.ts +84 -22
  662. package/dist/web/mirror_stream.js +676 -95
  663. package/dist/web/observer_query_redaction.d.ts +6 -0
  664. package/dist/web/observer_query_redaction.js +58 -0
  665. package/dist/web/pane_registry.d.ts +2 -0
  666. package/dist/web/pane_registry.js +86 -22
  667. package/dist/web/tool_image.d.ts +6 -0
  668. package/dist/web/tool_image.js +17 -0
  669. package/dist/web/view_plugin.d.ts +14 -0
  670. package/dist/web/view_plugin.js +23 -1
  671. package/dist/worker/executor.js +31 -12
  672. package/dist/worker/index.d.ts +1 -0
  673. package/dist/worker/toolsets.js +3 -1
  674. package/dist/worker/types.d.ts +12 -1
  675. package/dist/workflows/registry.js +1 -0
  676. package/dist/workflows/registry_handle.d.ts +2 -0
  677. package/dist/workflows/runtime.d.ts +2 -0
  678. package/dist/workflows/runtime.js +1 -0
  679. package/dist/workspace_agent.d.ts +7 -0
  680. package/dist/workspace_agent.js +36 -0
  681. package/dist/workspace_collision.d.ts +76 -0
  682. package/dist/workspace_collision.js +688 -0
  683. package/dist/workspace_layout.d.ts +18 -0
  684. package/dist/workspace_layout.js +121 -0
  685. package/dist/workspace_runtime.d.ts +44 -0
  686. package/dist/workspace_runtime.js +82 -0
  687. package/dist/workspace_session_context.d.ts +62 -0
  688. package/dist/workspace_session_context.js +160 -0
  689. package/dist/zlm-embed.mjs +32518 -9615
  690. package/dist/zlm.js +1 -0
  691. package/node_modules/@zerg/model-contracts/LICENSE.md +375 -0
  692. package/node_modules/@zerg/model-contracts/README.md +90 -0
  693. package/node_modules/@zerg/model-contracts/index.d.ts +20 -0
  694. package/node_modules/@zerg/model-contracts/index.js +223 -0
  695. package/node_modules/@zerg/model-contracts/package.json +8 -0
  696. package/node_modules/glob/node_modules/brace-expansion/index.js +78 -22
  697. package/node_modules/glob/node_modules/brace-expansion/package.json +1 -1
  698. package/node_modules/readdir-glob/node_modules/brace-expansion/index.js +78 -22
  699. package/node_modules/readdir-glob/node_modules/brace-expansion/package.json +1 -1
  700. package/package.json +45 -24
  701. package/packages/model-contracts/LICENSE.md +375 -0
  702. package/packages/model-contracts/README.md +90 -0
  703. package/packages/model-contracts/index.d.ts +20 -0
  704. package/packages/model-contracts/index.js +223 -0
  705. package/packages/model-contracts/package.json +8 -0
  706. package/remote-broker/Dockerfile +10 -0
  707. package/remote-broker/README.md +308 -0
  708. package/remote-broker/archive.py +1227 -0
  709. package/remote-broker/cutover.py +761 -0
  710. package/remote-broker/requirements.txt +5 -0
  711. package/remote-broker/resources.example.json +6 -0
  712. package/remote-broker/resources.write-staging.example.json +18 -0
  713. package/remote-broker/retained.py +686 -0
  714. package/remote-broker/retained_cleanup.py +550 -0
  715. package/remote-broker/server.py +648 -0
  716. package/scripts/build-remote-broker.mjs +13 -0
  717. package/scripts/ensure-local-packages.mjs +6 -0
  718. package/scripts/node-pty-helpers.mjs +103 -0
@@ -1,3 +1,4 @@
1
+ import { parseGoalView, retainGoalView } from '../goal_contract.js';
1
2
  /**
2
3
  * Mirror Stream Server - Stream semantic events to browser mirrors
3
4
  *
@@ -18,17 +19,27 @@ import { createHash, randomUUID, timingSafeEqual } from 'crypto';
18
19
  import { homedir, tmpdir } from 'os';
19
20
  import { fileURLToPath } from 'url';
20
21
  import { configStore, DEFAULT_CONTEXT_PROGRESS_BAR } from '../config.js';
22
+ import { parseEvidenceSnapshot } from '../agent/runtime/evidence.js';
23
+ import { parseToolProgress } from '../tool_progress.js';
21
24
  import { readRepoConfig } from '../config/repo_config.js';
22
25
  import { runtimeDiag } from '../utils/debug_log.js';
23
26
  import { getModelCatalogPayload } from '../panes/model_catalog.js';
24
27
  import { isMeaningfulUserInput } from '../app/input_validation.js';
28
+ import { receiveIntakeRequest, listIntakeReceipts } from '../intake/store.js';
29
+ import { AttentionQueue } from '../attention/queue.js';
30
+ import { ObserverQueryRedaction } from './observer_query_redaction.js';
25
31
  import { completeAtMention } from '../utils/at_mention.js';
26
32
  import { isTerminalPaneType } from './terminal_replay.js';
33
+ import { MAX_TOOL_IMAGE_BODY_BYTES, mirrorToolImage } from './tool_image.js';
34
+ import { parseTaskHandoffView, retainTaskHandoffView } from './view_plugin.js';
27
35
  import { normalizeMirrorBasePath } from './mirror_base_path.js';
28
36
  import { runtimePluginRegistry } from '../plugin/runtime_registry.js';
29
37
  import { MIRROR_MEDIA_ROOT, stripForeignMediaTokens } from '../utils/mirror_media.js';
38
+ import { readDurableSessionImageSync, SessionMediaError } from '../session_media.js';
30
39
  import { MemoryHistoryStore, JsonlHistoryStore } from './event_history_store.js';
31
40
  import { PaneRegistry } from './pane_registry.js';
41
+ import { buildWorkspaceRuntimeSnapshot } from '../workspace_runtime.js';
42
+ import { ChildPublicationLedger } from './child_publication.js';
32
43
  import { createMirrorAuthenticatorFromEnv, } from './mirror_authenticator.js';
33
44
  import { areMirrorCorsRequestHeadersAllowed, getMirrorOriginPolicy, MIRROR_CORS_ALLOW_HEADERS, rejectReasonForUnsafeMirrorWrite, } from './mirror_origin_policy.js';
34
45
  import { getAccountsPayload, getAccountsPayloadWithCodexStatus, applyAccountOp, getActiveAccountsSummary } from './accounts_mirror.js';
@@ -67,6 +78,18 @@ function loadNativeDictation() {
67
78
  }
68
79
  return nativeDictationPromise;
69
80
  }
81
+ // Observation exposes terminal activity, never operator settings or plugin-specific state.
82
+ const OBSERVER_EVENT_TYPES = new Set([
83
+ 'message', 'stream_start', 'stream_delta', 'stream_end', 'reasoning_delta', 'reasoning',
84
+ 'tool_call', 'tool_result', 'status', 'token_usage', 'error', 'cancel', 'mode_change',
85
+ 'pane_info', 'pane_output', 'session_end', 'reload', 'clear', 'todo_list', 'ask_user',
86
+ 'queue_state', 'command_jobs', 'command_pane', 'hook_approval_request', 'widget_prompt', 'widget_select',
87
+ 'widget_questionnaire', 'widget_dismiss', 'context_progress_bar_config',
88
+ ]);
89
+ const OBSERVER_GET_PATHS = new Set([
90
+ '/', '/events', '/debug/config', '/mirror/pane-registry', '/mirror/layout',
91
+ '/status', '/stats', '/output', '/health', '/favicon.svg', '/favicon.ico', '/mirror-favicon.svg',
92
+ ]);
70
93
  const VOICE_MAX_AUDIO_BYTES = 12 * 1024 * 1024;
71
94
  // EPO-638/637 — a captured iframe frame is usually <2MB for a normal
72
95
  // desktop viewport at PNG. 8MB covers 4K screens with wide margin.
@@ -121,18 +144,16 @@ export class MirrorStreamServer {
121
144
  runtimeStatsProvider = null;
122
145
  inputCallback = null;
123
146
  mediaDir;
147
+ toolImageJobs = new Set();
124
148
  mediaById = new Map();
125
149
  cancelCallback = null;
126
150
  askUserAnswerCallback = null;
127
- pendingQuestionId = null;
151
+ attention = new AttentionQueue();
152
+ /** Active requests belong to a pane; retained transcript capacity is not their lifecycle. */
153
+ pendingQuestions = new Map();
154
+ workspaceOwnerId = randomUUID();
128
155
  widgetAnswerCallback = null;
129
156
  hookApprovalCallback = null;
130
- // All approval IDs currently awaiting a decision. A turn may issue two
131
- // tool_use blocks in parallel, each producing its own approval card.
132
- // Resolution is per-id: the /hook-approval POST supplies the id; the HTTP
133
- // handler deletes that id and drops the matching hook_approval_request
134
- // event from history so a reload after decision doesn't resurrect it.
135
- pendingHookApprovalIds = new Set();
136
157
  // EPO-638/637 — pending captures keyed by capture_id. Resolvers wait for
137
158
  // the matching POST /zlicky/capture/:id to land.
138
159
  zlickyCaptures = new Map();
@@ -151,9 +172,11 @@ export class MirrorStreamServer {
151
172
  paneViewportCallback = null;
152
173
  /** Single owner of pane runtime state + status derivation + pane_info payload (Seam B). */
153
174
  panes = new PaneRegistry();
175
+ childPublications = new ChildPublicationLedger();
154
176
  hiddenPaneIds = new Set();
155
177
  suppressPaneInfo = false;
156
178
  persistenceKey = null;
179
+ originSessionId;
157
180
  colonyChild = false;
158
181
  hostedMode = false;
159
182
  modelCatalogProvider = getModelCatalogPayload;
@@ -185,6 +208,7 @@ export class MirrorStreamServer {
185
208
  // Recreates the live agent so a web `use` (switch account) picks up the new
186
209
  // credentials without a restart (see setAccountReloadHook / the CLI use path).
187
210
  accountReloadHook = null;
211
+ accountOperationHook = null;
188
212
  setLogBuffer(fn) {
189
213
  this._logBufferGetter = fn;
190
214
  }
@@ -242,7 +266,13 @@ export class MirrorStreamServer {
242
266
  return (type === 'widget_select'
243
267
  || type === 'widget_questionnaire'
244
268
  || type === 'widget_prompt'
245
- || type === 'widget_dismiss');
269
+ || type === 'widget_dismiss'
270
+ || type === 'widget_settings'
271
+ || type === 'ask_user'
272
+ || type === 'question_dismiss'
273
+ || type === 'hook_approval_request'
274
+ || type === 'hook_approval_resolved'
275
+ || type === 'attention_resolved');
246
276
  }
247
277
  // --- View Plugins ---
248
278
  plugins = [];
@@ -275,6 +305,15 @@ export class MirrorStreamServer {
275
305
  // the session store, and the secret/internal-token self-mint (writing process.env
276
306
  // so child panes inherit them).
277
307
  this.auth = createMirrorAuthenticatorFromEnv();
308
+ this.auth.onShareRevoked(id => {
309
+ for (const [clientId, client] of this.clients) {
310
+ if (client.shareId !== id)
311
+ continue;
312
+ client.res.write(`data: ${JSON.stringify({ type: 'share_revoked', data: { share_id: id } })}\n\n`);
313
+ client.res.end();
314
+ this.clients.delete(clientId);
315
+ }
316
+ });
278
317
  const devBarFlag = (process.env.ZTC_MIRROR_DEV_BAR || '').trim();
279
318
  if (devBarFlag === '1') {
280
319
  this.devSystemBarEnabled = true;
@@ -289,9 +328,13 @@ export class MirrorStreamServer {
289
328
  // Disabled for ephemeral parent sessions (no --resume flag). The EventHistoryStore
290
329
  // (Seam A) owns the bounded ring, the seq counter, and JSONL replay.
291
330
  this.persistenceKey = (persistenceKey || process.env.ZTC_MIRROR_PERSISTENCE_KEY || process.env.COLONY_SESSION_ID || '').trim() || null;
331
+ this.originSessionId = this.persistenceKey ?? randomUUID();
292
332
  this.history = persistEvents
293
333
  ? new JsonlHistoryStore(JsonlHistoryStore.sessionFilePath(this.persistenceKey), undefined, undefined, (event) => this.isEphemeralWidgetEvent(event.type))
294
334
  : new MemoryHistoryStore();
335
+ // Restore safe projections in chronological order before live publication.
336
+ for (const event of this.history.snapshot())
337
+ this.observerEvent(event);
295
338
  // Live active-account badge: re-publish whenever a switch or auto-rotation
296
339
  // moves the active pointer (both go through ConfigStore.setActiveAccount).
297
340
  // Keep the unsubscribe so stop() detaches — the listener set is module-global.
@@ -311,12 +354,18 @@ export class MirrorStreamServer {
311
354
  setAccountReloadHook(fn) {
312
355
  this.accountReloadHook = fn;
313
356
  }
357
+ /** Admission belongs to the session owner, before any account settings are written. */
358
+ setAccountOperationHook(fn) {
359
+ this.accountOperationHook = fn;
360
+ }
314
361
  /**
315
362
  * Register a view plugin that extends the server with domain-specific routes and behavior.
316
363
  * Plugins are called in registration order for route handling and event hooks.
317
364
  */
318
365
  registerViewPlugin(plugin) {
319
366
  const ctx = {
367
+ getOrigin: () => new URL(this.getLaunchUrl()).origin,
368
+ getEvents: () => this.getEventHistory(),
320
369
  readBody: (req) => this.readBody(req, MAX_MIRROR_PLUGIN_BODY_BYTES),
321
370
  isAuthEnabled: () => this.mirrorAuthEnabled,
322
371
  isLocalRequest: (req) => this.isLocalRequest(req),
@@ -369,6 +418,9 @@ export class MirrorStreamServer {
369
418
  getEventHistory() {
370
419
  return this.history.snapshot();
371
420
  }
421
+ getWorkspaceRuntimeSnapshot() {
422
+ return buildWorkspaceRuntimeSnapshot(this.workspaceOwnerId, this.panes.entries(), [...this.pendingQuestions.values()]);
423
+ }
372
424
  setSuperuser(value) {
373
425
  this.operatorIsSuperuser = value;
374
426
  }
@@ -398,6 +450,16 @@ export class MirrorStreamServer {
398
450
  }
399
451
  return url.toString();
400
452
  }
453
+ /** Operator-issued observation capability. Never contains a controller token. */
454
+ createObservationShare(label, ttlSeconds = 3600) {
455
+ const token = this.auth.issueToken({ readOnly: true, label, ttlMs: ttlSeconds * 1000 });
456
+ const state = this.auth.isValidToken(token);
457
+ const url = new URL(`http://localhost:${this.port}${this.browserBasePath || '/'}`);
458
+ url.searchParams.set(this.auth.queryTokenName, token);
459
+ return { id: state.shareId, label, expiresAtMs: state.expiresAtMs, url: url.toString() };
460
+ }
461
+ getObservationShares() { return this.auth.listShares(); }
462
+ revokeObservationShare(id) { return this.auth.revokeShare(id); }
401
463
  /**
402
464
  * Set callback for handling input from browser
403
465
  */
@@ -509,6 +571,57 @@ export class MirrorStreamServer {
509
571
  this.eventObservers = this.eventObservers.filter((observer) => observer !== callback);
510
572
  };
511
573
  }
574
+ getAttentionSnapshot(limit = 100, offset = 0) {
575
+ return this.attention.snapshot(limit, offset);
576
+ }
577
+ resolveAttention(id) {
578
+ const item = this.attention.resolve(id);
579
+ if (item)
580
+ this.publish({ type: 'attention_resolved', data: { id, request_id: item.requestId, kind: item.kind, pane_id: item.paneId } });
581
+ return item;
582
+ }
583
+ respondAttention(id, answer) {
584
+ const item = this.attention.find(id);
585
+ if (!item || item.primaryAction === 'inspect')
586
+ throw new Error('Stale attention request; inspect the current queue.');
587
+ if (item.kind === 'question') {
588
+ if (typeof answer !== 'string' || !answer.trim())
589
+ throw new Error('A non-empty question answer is required.');
590
+ if (!this.askUserAnswerCallback)
591
+ throw new Error('Question owner is unavailable.');
592
+ this.resolveAttention(id);
593
+ this.retireQuestion(item.paneId);
594
+ this.askUserAnswerCallback(answer, item.paneId, item.requestId);
595
+ return;
596
+ }
597
+ if (item.kind === 'approval') {
598
+ const decision = answer;
599
+ if (!decision || (decision.decision !== 'approve' && decision.decision !== 'deny'))
600
+ throw new Error('Choose approve or deny.');
601
+ if (!this.hookApprovalCallback)
602
+ throw new Error('Approval owner is unavailable.');
603
+ this.resolveAttention(id);
604
+ this.history.removeByPredicate(e => e.type === 'hook_approval_request' && e.data.id === item.requestId && (e.data.pane_id ?? 0) === item.paneId, true);
605
+ this.hookApprovalCallback(item.requestId, decision.decision, typeof decision.reason === 'string' ? decision.reason : undefined, item.paneId);
606
+ return;
607
+ }
608
+ if (!answer || typeof answer !== 'object' || Array.isArray(answer))
609
+ throw new Error('A prompt answer object is required.');
610
+ if (!this.widgetAnswerCallback)
611
+ throw new Error('Prompt owner is unavailable.');
612
+ this.resolveAttention(id);
613
+ this.history.removeByPredicate(e => ['widget_prompt', 'widget_select', 'widget_questionnaire'].includes(e.type)
614
+ && e.data.widget_id === item.requestId && (e.data.pane_id ?? 0) === item.paneId, true);
615
+ this.widgetAnswerCallback(item.requestId, answer, item.paneId);
616
+ }
617
+ dismissAttention(id) {
618
+ const item = this.attention.find(id);
619
+ if (!item)
620
+ throw new Error('Attention item is no longer pending.');
621
+ if (item.primaryAction !== 'inspect')
622
+ throw new Error('Answer or deny this request; an open approval cannot be dismissed.');
623
+ this.resolveAttention(id);
624
+ }
512
625
  // --- Bus Methods ---
513
626
  /**
514
627
  * Register an in-process bus member (parent ZTC). No HTTP round-trip needed.
@@ -691,6 +804,10 @@ export class MirrorStreamServer {
691
804
  */
692
805
  clearChildPanes() {
693
806
  const removedIds = this.panes.clearNonOverseer();
807
+ for (const paneId of removedIds) {
808
+ this.childPublications.invalidate(paneId);
809
+ this.retireQuestion(paneId);
810
+ }
694
811
  // Remove stale pane_info events and events referencing removed pane IDs
695
812
  // so reconnecting browsers don't see ghost panes or stale messages. This drop
696
813
  // also compacts the persisted log (rewritePersisted=true).
@@ -729,12 +846,22 @@ export class MirrorStreamServer {
729
846
  * Unregister a pane and notify browser.
730
847
  */
731
848
  unregisterPane(paneId) {
849
+ this.attention.markStale(paneId);
850
+ this.childPublications.invalidate(paneId);
851
+ this.retireQuestion(paneId);
732
852
  this.panes.delete(paneId);
733
853
  this.history.purgePane(paneId);
734
854
  this.publishPaneInfo();
735
855
  }
736
856
  updatePaneState(state) {
737
857
  this.multiPaneMode = true;
858
+ const nextIds = new Set(state.panes.map(pane => pane.id));
859
+ for (const paneId of this.panes.ids()) {
860
+ if (paneId !== 0 && !nextIds.has(paneId)) {
861
+ this.childPublications.invalidate(paneId);
862
+ this.retireQuestion(paneId);
863
+ }
864
+ }
738
865
  this.panes.applyState(state);
739
866
  this.publishPaneInfo();
740
867
  }
@@ -817,14 +944,16 @@ export class MirrorStreamServer {
817
944
  this.server.close(() => resolve());
818
945
  setTimeout(resolve, 2000);
819
946
  });
947
+ await Promise.allSettled([...this.toolImageJobs]);
820
948
  await this.cleanupMediaDir();
821
949
  }
822
950
  /**
823
951
  * Publish an event to all connected SSE clients.
824
952
  */
825
- publish(event) {
953
+ stampEvent(event) {
826
954
  const fullEvent = {
827
955
  ...event,
956
+ data: { ...event.data, origin_session_id: event.data.origin_session_id ?? this.originSessionId },
828
957
  timestamp: new Date().toISOString(),
829
958
  seq: this.history.nextSeq(),
830
959
  };
@@ -834,7 +963,36 @@ export class MirrorStreamServer {
834
963
  if (this.multiPaneMode && fullEvent.data.pane_id === undefined && fullEvent.type !== 'pane_info') {
835
964
  fullEvent.data = { ...fullEvent.data, pane_id: 0 };
836
965
  }
966
+ return fullEvent;
967
+ }
968
+ publish(event) {
969
+ event = this.registerDurableMessageMedia(event);
970
+ if (event.type === 'goal') {
971
+ const data = this.admitGoalEvent(event.data);
972
+ if (!data)
973
+ return;
974
+ event = { ...event, data };
975
+ }
976
+ if (event.type === 'task_handoff') {
977
+ const data = this.admitTaskHandoffEvent(event.data);
978
+ if (!data)
979
+ return;
980
+ event = { ...event, data };
981
+ }
982
+ if (event.type === 'evidence') {
983
+ const snapshot = parseEvidenceSnapshot(event.data.snapshot);
984
+ const sessionId = event.data.session_id;
985
+ if (!snapshot || typeof sessionId !== 'string' || !sessionId || Buffer.byteLength(sessionId) > 1024)
986
+ return;
987
+ event = { ...event, data: { ...event.data, snapshot, session_id: sessionId } };
988
+ }
989
+ const fullEvent = this.stampEvent(event);
990
+ // Project once before broadcasting, even with no observers connected yet.
991
+ // A later observer must not see the continuation of a split token.
992
+ this.observerEvent(fullEvent);
993
+ this.admitQuestionLifecycle(fullEvent);
837
994
  this.panes.applyEvent(fullEvent);
995
+ this.attention.observe(fullEvent, this.panes.get(typeof fullEvent.data.pane_id === 'number' ? fullEvent.data.pane_id : 0));
838
996
  // Consolidate live-only reasoning deltas into ONE retained reasoning event
839
997
  // per thought (see consolidateReasoningForBackfill) BEFORE the retention
840
998
  // decision below, so the consolidated event lands in history ahead of the
@@ -890,9 +1048,48 @@ export class MirrorStreamServer {
890
1048
  this.clients.delete(id);
891
1049
  continue;
892
1050
  }
893
- client.res.write(payload);
1051
+ const visible = client.readOnly ? this.observerEvent(fullEvent) : fullEvent;
1052
+ if (visible)
1053
+ client.res.write(client.readOnly ? `id: ${fullEvent.seq}\ndata: ${JSON.stringify(visible)}\n\n` : payload);
894
1054
  }
895
1055
  }
1056
+ /** Project a transcript event without changing its retained, operator-owned copy. */
1057
+ observerProjections = new WeakMap();
1058
+ observerQueryRedaction = new ObserverQueryRedaction();
1059
+ observerTextRedaction = new ObserverQueryRedaction();
1060
+ observerEvent(event) {
1061
+ if (!OBSERVER_EVENT_TYPES.has(event.type))
1062
+ return null;
1063
+ const cached = this.observerProjections.get(event);
1064
+ if (cached)
1065
+ return cached;
1066
+ const scope = JSON.stringify([event.data.origin_session_id ?? this.originSessionId, event.data.pane_id ?? 0]);
1067
+ if (event.type === 'stream_start') {
1068
+ for (const type of ['stream_delta', 'reasoning_delta'])
1069
+ this.observerQueryRedaction.reset(`${scope}:${type}`);
1070
+ }
1071
+ let source = event;
1072
+ if (['stream_delta', 'reasoning_delta', 'pane_output'].includes(event.type) && typeof event.data.content === 'string') {
1073
+ source = { ...event, data: { ...event.data, content: this.observerQueryRedaction.redact(`${scope}:${event.type}`, event.data.content, event.type === 'pane_output' && event.data.reset === true) } };
1074
+ }
1075
+ const projected = JSON.parse(JSON.stringify(source, (_key, value) => typeof value === 'string'
1076
+ ? /(?:^|\s)\/job\s[\s\S]*?(?:^|\s)--env(?:\s|=)/m.test(value)
1077
+ ? '/job [environment options withheld]'
1078
+ : this.observerTextRedaction.redact('text', value, true)
1079
+ : value));
1080
+ // Weak keys share the canonical history lifetime and do not create another
1081
+ // unbounded event store. Replays reuse the same safe projection.
1082
+ this.observerProjections.set(event, projected);
1083
+ return projected;
1084
+ }
1085
+ observerConnectionData(clientId) {
1086
+ return {
1087
+ clientId, port: this.port, origin_session_id: this.originSessionId, read_only: true,
1088
+ auth_required: true, dev_bar_enabled: false, runtime_env: this.runtimeEnv,
1089
+ is_superuser: false, colony_child: this.colonyChild, hosted_mode: this.hostedMode,
1090
+ colony_enabled: false, sfx: this.sfxConfig,
1091
+ };
1092
+ }
896
1093
  /**
897
1094
  * The /debug/config payload. The web client fetches this right after
898
1095
  * connect (for zerg_id) and maps it through the SAME mapConfig as the
@@ -931,6 +1128,9 @@ export class MirrorStreamServer {
931
1128
  const authEnvOverride = process.env.ZTC_LLM_AUTH_MODE || process.env.ZERG_LLM_AUTH_MODE || undefined;
932
1129
  return {
933
1130
  clientId,
1131
+ origin_session_id: this.originSessionId,
1132
+ read_only: false,
1133
+ workspace_owner_id: this.workspaceOwnerId,
934
1134
  port: this.port,
935
1135
  auth_required: this.auth.enabled,
936
1136
  dev_bar_enabled: this.devSystemBarEnabled,
@@ -1057,15 +1257,58 @@ export class MirrorStreamServer {
1057
1257
  this.lastBroadcastTokenUsageKey = key;
1058
1258
  this.publish({ type: 'token_usage', data: { ...this.lastTokenUsage } });
1059
1259
  }
1260
+ retireQuestion(paneId) {
1261
+ const current = this.pendingQuestions.get(paneId);
1262
+ const request = typeof current?.data.question_id === 'string' ? this.attention.findRequest('question', current.data.question_id, paneId) : undefined;
1263
+ if (request)
1264
+ this.attention.resolve(request.id);
1265
+ this.pendingQuestions.delete(paneId);
1266
+ this.history.removeByPredicate(event => event.type === 'ask_user' && (event.data.pane_id ?? 0) === paneId, true);
1267
+ }
1268
+ admitQuestionLifecycle(event) {
1269
+ const paneId = (event.data.pane_id ?? 0);
1270
+ if (event.type === 'ask_user') {
1271
+ if (!this.pendingQuestions.has(paneId) && this.pendingQuestions.size >= 256) {
1272
+ throw new Error('Workspace has 256 pending child decisions; answer or cancel a request before asking another.');
1273
+ }
1274
+ const questionId = event.data.question_id;
1275
+ event.data = { ...event.data, pane_id: paneId,
1276
+ question_id: typeof questionId === 'string' && questionId.length > 0 ? questionId : randomUUID() };
1277
+ this.retireQuestion(paneId);
1278
+ this.pendingQuestions.set(paneId, structuredClone(event));
1279
+ }
1280
+ else if (event.type === 'cancel' || event.type === 'clear' || event.type === 'session_end') {
1281
+ this.retireQuestion(paneId);
1282
+ }
1283
+ }
1060
1284
  storeEvent(event) {
1061
- const fullEvent = {
1062
- ...event,
1063
- timestamp: new Date().toISOString(),
1064
- seq: this.history.nextSeq(),
1065
- };
1066
- if (this.multiPaneMode && fullEvent.data.pane_id === undefined && fullEvent.type !== 'pane_info') {
1067
- fullEvent.data = { ...fullEvent.data, pane_id: 0 };
1285
+ event = this.registerDurableMessageMedia(event);
1286
+ if (event.type === 'goal') {
1287
+ const data = this.admitGoalEvent(event.data);
1288
+ if (!data)
1289
+ return;
1290
+ event = { ...event, data };
1291
+ }
1292
+ if (event.type === 'task_handoff') {
1293
+ const data = this.admitTaskHandoffEvent(event.data);
1294
+ if (!data)
1295
+ return;
1296
+ event = { ...event, data };
1068
1297
  }
1298
+ if (event.type === 'evidence') {
1299
+ const snapshot = parseEvidenceSnapshot(event.data.snapshot);
1300
+ const sessionId = event.data.session_id;
1301
+ if (!snapshot || typeof sessionId !== 'string' || !sessionId || Buffer.byteLength(sessionId) > 1024)
1302
+ return;
1303
+ event = { ...event, data: { ...event.data, snapshot, session_id: sessionId } };
1304
+ }
1305
+ const fullEvent = this.stampEvent(event);
1306
+ this.observerEvent(fullEvent);
1307
+ this.admitQuestionLifecycle(fullEvent);
1308
+ if (fullEvent.type === 'ask_user')
1309
+ this.attention.observe(fullEvent);
1310
+ if (['task_handoff', 'goal', 'todo_list', 'request_usage'].includes(fullEvent.type))
1311
+ this.panes.applyEvent(fullEvent);
1069
1312
  if (event.type !== 'pane_info') {
1070
1313
  this.history.append(fullEvent);
1071
1314
  }
@@ -1123,15 +1366,58 @@ export class MirrorStreamServer {
1123
1366
  data: { tool, args: safeArgs, toolCallId },
1124
1367
  });
1125
1368
  }
1369
+ publishEvidenceSnapshot(snapshot, sessionId) {
1370
+ this.publish({ type: 'evidence', data: { snapshot, session_id: sessionId } });
1371
+ }
1372
+ admitGoalEvent(data) {
1373
+ const paneId = data.pane_id ?? 0;
1374
+ if (typeof paneId !== 'number' || !Number.isSafeInteger(paneId) || paneId < 0)
1375
+ return null;
1376
+ const next = parseGoalView({ sessionId: data.sessionId, goal: data.goal });
1377
+ if (!next)
1378
+ return null;
1379
+ const previous = this.panes.get(paneId)?.goal;
1380
+ if (retainGoalView(previous, next) === previous)
1381
+ return null;
1382
+ return { ...(data.pane_id === undefined ? {} : { pane_id: paneId }), ...next };
1383
+ }
1384
+ admitTaskHandoffEvent(data) {
1385
+ const paneId = data.pane_id ?? 0;
1386
+ if (typeof paneId !== 'number' || !Number.isSafeInteger(paneId) || paneId < 0)
1387
+ return null;
1388
+ const next = parseTaskHandoffView({ sessionId: data.sessionId, projection: data.projection });
1389
+ if (!next)
1390
+ return null;
1391
+ const previous = this.panes.get(paneId)?.taskHandoff;
1392
+ if (retainTaskHandoffView(previous, next) === previous)
1393
+ return null;
1394
+ return { ...(data.pane_id === undefined ? {} : { pane_id: paneId }), ...next };
1395
+ }
1396
+ publishTaskHandoff(projection, sessionId) {
1397
+ this.publish({ type: 'task_handoff', data: { sessionId, projection } });
1398
+ }
1126
1399
  publishToolResult(tool, result, success, toolCallId) {
1400
+ const data = this.retainToolImage({ tool, result, success, toolCallId });
1127
1401
  // Larger limits for tools with structured/visual output in the mirror
1128
1402
  const largeLimitTools = ['delegate_task', 'read_file', 'search', 'run_command'];
1129
1403
  const maxLen = largeLimitTools.includes(tool) ? 15000 : 4000;
1130
1404
  this.publish({
1131
1405
  type: 'tool_result',
1132
- data: { tool, result: result.slice(0, maxLen), success, toolCallId },
1406
+ data: { ...data, result: String(data.result).slice(0, maxLen) },
1133
1407
  });
1134
1408
  }
1409
+ retainToolImage(data) {
1410
+ const image = mirrorToolImage(data.result);
1411
+ if (!image)
1412
+ return data;
1413
+ const source = { origin_session_id: data.origin_session_id ?? this.originSessionId, pane_id: data.pane_id ?? 0, toolCallId: data.toolCallId };
1414
+ const job = this.storeMirrorImage(Buffer.from(image.data, 'base64'), 'capture.png')
1415
+ .then(attachment => { this.publish({ type: 'tool_artifact', data: { ...source, kind: 'image', title: image.description, media_url: attachment.url } }); })
1416
+ .catch(() => { this.publish({ type: 'tool_artifact', data: { ...source, kind: 'image', title: image.description, error: 'Captured image preview could not be stored. Capture it again.' } }); })
1417
+ .finally(() => { this.toolImageJobs.delete(job); });
1418
+ this.toolImageJobs.add(job);
1419
+ return { ...data, result: image.description };
1420
+ }
1135
1421
  publishTodoList(todos) {
1136
1422
  this.publish({
1137
1423
  type: 'todo_list',
@@ -1139,7 +1425,6 @@ export class MirrorStreamServer {
1139
1425
  });
1140
1426
  }
1141
1427
  publishHookApprovalRequest(request) {
1142
- this.pendingHookApprovalIds.add(request.id);
1143
1428
  this.publish({
1144
1429
  type: 'hook_approval_request',
1145
1430
  data: {
@@ -1153,9 +1438,16 @@ export class MirrorStreamServer {
1153
1438
  },
1154
1439
  });
1155
1440
  }
1441
+ publishHookApprovalResolved(id) {
1442
+ this.history.removeByPredicate(e => e.type === 'hook_approval_request' && e.data.id === id && (e.data.pane_id ?? 0) === 0, true);
1443
+ this.publish({ type: 'hook_approval_resolved', data: { id } });
1444
+ }
1445
+ publishQuestionDismiss(questionId) {
1446
+ this.history.removeByPredicate(e => e.type === 'ask_user' && e.data.question_id === questionId && (e.data.pane_id ?? 0) === 0, true);
1447
+ this.publish({ type: 'question_dismiss', data: { question_id: questionId } });
1448
+ }
1156
1449
  publishAskUser(questions, paneId, allowOther) {
1157
1450
  const questionId = randomUUID();
1158
- this.pendingQuestionId = questionId;
1159
1451
  const baseData = { pane_id: paneId ?? 0, question_id: questionId, allow_other: allowOther ?? true };
1160
1452
  if (questions.length === 1) {
1161
1453
  this.publish({
@@ -1169,11 +1461,14 @@ export class MirrorStreamServer {
1169
1461
  data: { ...baseData, questions },
1170
1462
  });
1171
1463
  }
1464
+ return questionId;
1172
1465
  }
1173
- publishStatus(status, verb) {
1466
+ publishStatus(status, verb, waiting, toolProgress) {
1467
+ const observed = status === 'tool_executing' ? parseToolProgress(toolProgress) : null;
1174
1468
  this.publish({
1175
1469
  type: 'status',
1176
- data: { status, verb },
1470
+ data: { status, verb, ...(waiting ? { waiting } : {}),
1471
+ ...(observed ? { toolProgress: observed } : {}) },
1177
1472
  });
1178
1473
  }
1179
1474
  publishQueueState(total, entries) {
@@ -1218,8 +1513,7 @@ export class MirrorStreamServer {
1218
1513
  // resurrect the spinner or question widget from the aborted turn.
1219
1514
  // Partial tool_call/tool_result/message events from the aborted turn are
1220
1515
  // kept intentionally so replay preserves forensic visibility into what ran.
1221
- this.history.removeByPredicate((e) => e.type === 'todo_list' || e.type === 'ask_user' || e.type === 'hook_approval_request', true);
1222
- this.pendingHookApprovalIds.clear();
1516
+ this.history.removeByPredicate((e) => (e.data.pane_id ?? 0) === 0 && (e.type === 'todo_list' || e.type === 'hook_approval_request'), true);
1223
1517
  this.publishTodoList([]);
1224
1518
  this.publish({
1225
1519
  type: 'cancel',
@@ -1231,10 +1525,10 @@ export class MirrorStreamServer {
1231
1525
  // persisted JSONL) so a reconnecting or restarted client doesn't backfill the
1232
1526
  // pre-clear transcript, then broadcast a live-only `clear` so connected clients
1233
1527
  // wipe what they are currently showing. seq numbering stays monotonic.
1234
- this.history.clear(); // empties the ring + truncates the persisted file
1528
+ this.history.removeByPredicate(event => !this.multiPaneMode || (event.data.pane_id ?? 0) === 0, true);
1235
1529
  this.publish({
1236
1530
  type: 'clear',
1237
- data: {},
1531
+ data: { pane_id: 0 },
1238
1532
  });
1239
1533
  }
1240
1534
  publishSessionEnd(options = {}) {
@@ -1355,6 +1649,8 @@ export class MirrorStreamServer {
1355
1649
  }
1356
1650
  const payload = JSON.stringify(fullEvent);
1357
1651
  for (const client of this.clients.values()) {
1652
+ if (client.readOnly)
1653
+ continue;
1358
1654
  client.res.write(`data: ${payload}\n\n`);
1359
1655
  }
1360
1656
  }
@@ -1662,6 +1958,39 @@ export class MirrorStreamServer {
1662
1958
  this.mediaById.set(id, attachment);
1663
1959
  return attachment;
1664
1960
  }
1961
+ /** Rebuild media delivery only from attachments verified against a saved checkpoint. */
1962
+ registerDurableMessageMedia(event) {
1963
+ if (event.type !== 'message')
1964
+ return event;
1965
+ const metadata = event.data.metadata;
1966
+ if (!metadata || typeof metadata !== 'object' || Array.isArray(metadata))
1967
+ return event;
1968
+ const source = metadata;
1969
+ if (!Array.isArray(source.attachments))
1970
+ return event;
1971
+ const attachments = source.attachments.map(value => {
1972
+ if (!value || typeof value !== 'object' || Array.isArray(value))
1973
+ return value;
1974
+ const attachment = value;
1975
+ if (attachment.kind !== 'image')
1976
+ return value;
1977
+ try {
1978
+ const image = readDurableSessionImageSync(attachment);
1979
+ if (!image)
1980
+ return value;
1981
+ const canonical = { ...attachment, localPath: image.localPath,
1982
+ mediaType: image.mediaType, url: `/media/${encodeURIComponent(attachment.id)}`, stale: false };
1983
+ this.mediaById.set(canonical.id, canonical);
1984
+ return canonical;
1985
+ }
1986
+ catch (error) {
1987
+ if (!(error instanceof SessionMediaError))
1988
+ throw error;
1989
+ return { ...attachment, stale: true };
1990
+ }
1991
+ });
1992
+ return { ...event, data: { ...event.data, metadata: { ...source, attachments } } };
1993
+ }
1665
1994
  // Re-hydrate a client-supplied attachment reference from server state by id, so a
1666
1995
  // caller cannot forge url/localPath (which a child agent would later read as a local
1667
1996
  // file, or other mirrors would load as an arbitrary thumbnail URL).
@@ -1746,8 +2075,9 @@ export class MirrorStreamServer {
1746
2075
  return;
1747
2076
  }
1748
2077
  try {
1749
- const data = await readFile(attachment.localPath);
1750
- res.writeHead(200, { 'Content-Type': attachment.mediaType, 'Cache-Control': 'no-cache, no-store, must-revalidate' });
2078
+ const durable = readDurableSessionImageSync(attachment);
2079
+ const data = durable ? durable.data : await readFile(attachment.localPath);
2080
+ res.writeHead(200, { 'Content-Type': durable ? durable.mediaType : attachment.mediaType, 'Cache-Control': 'no-cache, no-store, must-revalidate' });
1751
2081
  res.end(data);
1752
2082
  }
1753
2083
  catch {
@@ -1988,8 +2318,15 @@ export class MirrorStreamServer {
1988
2318
  continue;
1989
2319
  const k = part.slice(0, idx).trim();
1990
2320
  const v = part.slice(idx + 1).trim();
1991
- if (k)
1992
- out[k] = decodeURIComponent(v);
2321
+ if (k) {
2322
+ try {
2323
+ out[k] = decodeURIComponent(v);
2324
+ }
2325
+ catch (error) {
2326
+ if (!(error instanceof URIError))
2327
+ throw error;
2328
+ }
2329
+ }
1993
2330
  }
1994
2331
  return out;
1995
2332
  }
@@ -2315,8 +2652,43 @@ export class MirrorStreamServer {
2315
2652
  }
2316
2653
  socket.resume();
2317
2654
  }
2655
+ admitChildPublication(parsed, res, scope) {
2656
+ if (!parsed || !Number.isSafeInteger(parsed.pane_id) || parsed.pane_id < -1 || scope.length > 256) {
2657
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2658
+ res.end(JSON.stringify({ error: 'invalid_publication_pane' }));
2659
+ return false;
2660
+ }
2661
+ const event = parsed.event;
2662
+ if (!event || typeof event.type !== 'string' || !event.type || event.type.length > 100
2663
+ || (event.data !== undefined && (!event.data || typeof event.data !== 'object' || Array.isArray(event.data)))) {
2664
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2665
+ res.end(JSON.stringify({ error: 'invalid_publication_event' }));
2666
+ return false;
2667
+ }
2668
+ const admission = this.childPublications.admit(parsed.pane_id, parsed.publication_id, parsed.sequence, scope);
2669
+ if (!admission.accepted) {
2670
+ res.writeHead(admission.status, { 'Content-Type': 'application/json' });
2671
+ res.end(JSON.stringify({ error: admission.error }));
2672
+ return false;
2673
+ }
2674
+ if (admission.duplicate) {
2675
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2676
+ res.end(JSON.stringify({ ok: true, duplicate: true }));
2677
+ return false;
2678
+ }
2679
+ return true;
2680
+ }
2318
2681
  async handleRequest(req, res) {
2319
- const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
2682
+ res.setHeader('Referrer-Policy', 'no-referrer');
2683
+ let url;
2684
+ try {
2685
+ url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
2686
+ }
2687
+ catch {
2688
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2689
+ res.end(JSON.stringify({ error: 'Invalid mirror request URL' }));
2690
+ return;
2691
+ }
2320
2692
  const originPolicy = getMirrorOriginPolicy(req);
2321
2693
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
2322
2694
  res.setHeader('Access-Control-Allow-Headers', MIRROR_CORS_ALLOW_HEADERS);
@@ -2324,7 +2696,6 @@ export class MirrorStreamServer {
2324
2696
  // ?ztc_mirror_token=... query param can't leak via Referer headers
2325
2697
  // when the loaded scripts fetch sub-resources. Set at handler entry so
2326
2698
  // every response (including 401/403/400 paths) carries the policy.
2327
- res.setHeader('Referrer-Policy', 'no-referrer');
2328
2699
  // Allow trusted loopback browser origins to read authenticated mirror responses.
2329
2700
  if (originPolicy.isTrustedOrigin && originPolicy.requestOrigin) {
2330
2701
  res.setHeader('Access-Control-Allow-Origin', originPolicy.requestOrigin);
@@ -2359,15 +2730,15 @@ export class MirrorStreamServer {
2359
2730
  res.end(JSON.stringify({ error: unsafeWriteReason }));
2360
2731
  return;
2361
2732
  }
2362
- // Defense-in-depth for the AUTH-DISABLED mirror (a colony cell on a predictable
2363
- // loopback port), beyond the Origin / Sec-Fetch-Site checks above:
2733
+ // Protect reads and writes for the AUTH-DISABLED mirror (a colony cell on
2734
+ // a predictable loopback port), beyond the write-only CSRF checks above:
2364
2735
  // - DNS rebinding: the Host the request arrived on must itself be loopback, so
2365
- // an Origin-less form POST to attacker.com (rebound to 127.0.0.1) is refused.
2736
+ // requests to attacker.com (rebound to 127.0.0.1) are refused.
2366
2737
  // - sibling local apps: a browser Origin must be loopback AND match THIS mirror's
2367
2738
  // actual listening port (this.port — NOT the attacker-controlled Host port), so
2368
- // a page on another localhost:* port cannot write into the cell.
2369
- const writeMethod = String(req.method || 'GET').toUpperCase();
2370
- if (!this.mirrorAuthEnabled && writeMethod !== 'GET' && writeMethod !== 'HEAD' && writeMethod !== 'OPTIONS') {
2739
+ // a page on another localhost:* port cannot read or control the cell.
2740
+ const requestMethod = String(req.method || 'GET').toUpperCase();
2741
+ if ((!this.mirrorAuthEnabled || originPolicy.requestOrigin && ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)) && requestMethod !== 'OPTIONS') {
2371
2742
  const isLoopbackHostname = (h) => h === '127.0.0.1' || h === 'localhost' || h === '::1' || h === '[::1]' || h.startsWith('127.');
2372
2743
  const explicitHostPortOk = !url.port || url.port === String(this.port);
2373
2744
  let originOk = true;
@@ -2387,6 +2758,25 @@ export class MirrorStreamServer {
2387
2758
  return;
2388
2759
  }
2389
2760
  }
2761
+ // Authenticated reverse proxies retain their public same-origin browser
2762
+ // contract, while a sibling origin cannot reuse a session cookie.
2763
+ if (this.mirrorAuthEnabled && originPolicy.requestOrigin && requestMethod !== 'OPTIONS') {
2764
+ let requestOrigin;
2765
+ try {
2766
+ requestOrigin = new URL(originPolicy.requestOrigin);
2767
+ }
2768
+ catch {
2769
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2770
+ res.end(JSON.stringify({ error: 'Invalid mirror browser origin' }));
2771
+ return;
2772
+ }
2773
+ const loopbackAliases = ['127.0.0.1', 'localhost', '[::1]'];
2774
+ if (!(loopbackAliases.includes(url.hostname) && loopbackAliases.includes(requestOrigin.hostname)) && requestOrigin.host !== url.host) {
2775
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2776
+ res.end(JSON.stringify({ error: 'Cross-origin mirror access denied' }));
2777
+ return;
2778
+ }
2779
+ }
2390
2780
  if (url.pathname === '/debug/signin-token' && req.method === 'POST') {
2391
2781
  try {
2392
2782
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
@@ -2400,6 +2790,8 @@ export class MirrorStreamServer {
2400
2790
  this.issueMirrorSession(res, {
2401
2791
  expiresAtMs: result.expiresAtMs,
2402
2792
  canInspectPrompts: result.canInspectPrompts,
2793
+ canControl: result.canControl,
2794
+ shareId: result.shareId,
2403
2795
  });
2404
2796
  res.writeHead(200, { 'Content-Type': 'application/json' });
2405
2797
  res.end(JSON.stringify({ ok: true }));
@@ -2415,6 +2807,20 @@ export class MirrorStreamServer {
2415
2807
  await this.handleMirrorPublish(req, res);
2416
2808
  return;
2417
2809
  }
2810
+ // The public CV artifact is separate from session access.
2811
+ if (url.pathname === '/cv/snapshot' && req.method === 'GET') {
2812
+ await this.handleCvSnapshot(req, res);
2813
+ return;
2814
+ }
2815
+ const auth = this.authenticateRequest(req, url, res);
2816
+ if (!auth.ok)
2817
+ return;
2818
+ const readOnly = auth.session?.canControl === false;
2819
+ if (readOnly && (req.method !== 'GET' || !(OBSERVER_GET_PATHS.has(url.pathname) || url.pathname.startsWith('/js/') || url.pathname.startsWith('/media/')))) {
2820
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2821
+ res.end(JSON.stringify({ error: 'Read-only observation does not permit this operation.' }));
2822
+ return;
2823
+ }
2418
2824
  // Notification (sfx) on/off from a mirror client's bell. Applies the change
2419
2825
  // to the CLI config silently (no transcript echo); the CLI handler re-pushes
2420
2826
  // via setSfxConfig() which broadcasts 'sfx_config' back to all clients.
@@ -2438,17 +2844,85 @@ export class MirrorStreamServer {
2438
2844
  }
2439
2845
  return;
2440
2846
  }
2441
- // CV snapshot — replaces the old Django /api/cv/snapshot endpoint.
2442
- // Reads zaai/.../cv_runner/state.json from the local repo checkout and
2443
- // returns the same shape Andre's Diff pane consumed: {schema_version, scenarios:[…]}.
2444
- // No auth: the mirror server is local/internal, and state.json is a
2445
- // committed artifact in the public repo.
2446
- if (url.pathname === '/cv/snapshot' && req.method === 'GET') {
2447
- await this.handleCvSnapshot(req, res);
2847
+ // Intake is deliberately separate from /input: delivery creates a receipt,
2848
+ // never an agent turn. Existing mirror authentication applies to both routes.
2849
+ if (url.pathname === '/attention' && req.method === 'GET') {
2850
+ try {
2851
+ const snapshot = this.getAttentionSnapshot(Number(url.searchParams.get('limit') ?? 100), Number(url.searchParams.get('offset') ?? 0));
2852
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2853
+ res.end(JSON.stringify(snapshot));
2854
+ }
2855
+ catch (error) {
2856
+ this.writeJsonError(res, error, 'Invalid attention page');
2857
+ }
2448
2858
  return;
2449
2859
  }
2450
- const auth = this.authenticateRequest(req, url, res);
2451
- if (!auth.ok) {
2860
+ if (url.pathname === '/attention/action' && req.method === 'POST') {
2861
+ let body;
2862
+ try {
2863
+ body = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
2864
+ }
2865
+ catch (error) {
2866
+ this.writeJsonError(res, error);
2867
+ return;
2868
+ }
2869
+ try {
2870
+ if (!body || typeof body.id !== 'string' || !body.id || !['respond', 'dismiss'].includes(String(body.action))) {
2871
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2872
+ res.end(JSON.stringify({ error: 'An attention ID and respond or dismiss action are required.' }));
2873
+ return;
2874
+ }
2875
+ if (body.action === 'dismiss')
2876
+ this.dismissAttention(body.id);
2877
+ else
2878
+ this.respondAttention(body.id, body.answer);
2879
+ res.writeHead(200, { 'Content-Type': 'application/json' });
2880
+ res.end(JSON.stringify({ ok: true }));
2881
+ }
2882
+ catch (error) {
2883
+ res.writeHead(409, { 'Content-Type': 'application/json' });
2884
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'Attention request could not be resolved.' }));
2885
+ }
2886
+ return;
2887
+ }
2888
+ if (url.pathname === '/intake' && (req.method === 'POST' || req.method === 'GET')) {
2889
+ // This is the local operator's profile-wide inbox. Shared/hosted viewers
2890
+ // must not read or inject work into it; hosted adapters need tenant scoping.
2891
+ if (this.hostedMode || (auth.source === 'browser' && auth.session?.canInspectPrompts !== true)) {
2892
+ res.writeHead(403, { 'Content-Type': 'application/json' });
2893
+ res.end(JSON.stringify({ error: 'Local operator inbox access required' }));
2894
+ return;
2895
+ }
2896
+ try {
2897
+ const result = req.method === 'POST'
2898
+ ? await receiveIntakeRequest(await this.readJsonBody(req, 64 * 1024))
2899
+ : await listIntakeReceipts();
2900
+ if ('receipt' in result && !result.duplicate)
2901
+ this.publish({ type: 'intake_receipt', data: { receipt: result.receipt } });
2902
+ res.writeHead(req.method === 'POST' && 'duplicate' in result && !result.duplicate ? 201 : 200, { 'Content-Type': 'application/json' });
2903
+ res.end(JSON.stringify(result));
2904
+ }
2905
+ catch (error) {
2906
+ res.writeHead(400, { 'Content-Type': 'application/json' });
2907
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'Invalid intake envelope' }));
2908
+ }
2909
+ return;
2910
+ }
2911
+ if (url.pathname === '/workspace/runtime') {
2912
+ if (!this.requireInternalAuth(auth, res))
2913
+ return;
2914
+ if (req.headers['x-ztc-workspace-owner'] !== this.workspaceOwnerId) {
2915
+ res.writeHead(409, { 'Content-Type': 'application/json' });
2916
+ res.end(JSON.stringify({ error: 'Workspace owner changed; open a fresh layout.' }));
2917
+ return;
2918
+ }
2919
+ if (req.method !== 'GET') {
2920
+ res.writeHead(405, { 'Content-Type': 'application/json', Allow: 'GET' });
2921
+ res.end(JSON.stringify({ error: 'Workspace runtime requires GET' }));
2922
+ return;
2923
+ }
2924
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
2925
+ res.end(JSON.stringify(this.getWorkspaceRuntimeSnapshot()));
2452
2926
  return;
2453
2927
  }
2454
2928
  if (this.hostedMode && url.pathname === '/internal/tool/call' && req.method === 'POST') {
@@ -2495,7 +2969,7 @@ export class MirrorStreamServer {
2495
2969
  }
2496
2970
  if (url.pathname === '/debug/config' && req.method === 'GET') {
2497
2971
  res.writeHead(200, { 'Content-Type': 'application/json' });
2498
- res.end(JSON.stringify(this.buildDebugConfigData(auth.session?.canInspectPrompts ?? false)));
2972
+ res.end(JSON.stringify(readOnly ? this.observerConnectionData('') : this.buildDebugConfigData(auth.session?.canInspectPrompts ?? false)));
2499
2973
  return;
2500
2974
  }
2501
2975
  // Dev log viewer endpoint — streams in-memory ring buffer (dev builds only).
@@ -2721,9 +3195,15 @@ export class MirrorStreamServer {
2721
3195
  }
2722
3196
  // Pass the reload hook so a `use` on the live provider hot-swaps the
2723
3197
  // running agent's credentials (parity with the CLI /accounts use path).
2724
- const result = await applyAccountOp(parsed, configStore, this.accountReloadHook ?? undefined);
2725
- res.writeHead(result.ok ? 200 : 400, { 'Content-Type': 'application/json' });
2726
- res.end(JSON.stringify(result));
3198
+ try {
3199
+ const result = this.accountOperationHook ? await this.accountOperationHook(parsed)
3200
+ : await applyAccountOp(parsed, configStore, this.accountReloadHook ?? undefined);
3201
+ res.writeHead(result.ok ? 200 : result.blocked === true ? 409 : 400, { 'Content-Type': 'application/json' });
3202
+ res.end(JSON.stringify(result));
3203
+ }
3204
+ catch (error) {
3205
+ this.writeCommandJsonError(res, error);
3206
+ }
2727
3207
  })();
2728
3208
  });
2729
3209
  return;
@@ -2754,8 +3234,14 @@ export class MirrorStreamServer {
2754
3234
  Connection: 'keep-alive',
2755
3235
  });
2756
3236
  res.write('\n');
2757
- const client = { id, res, canInspectPrompts };
3237
+ const client = { id, res, canInspectPrompts, readOnly, shareId: auth.session?.shareId };
2758
3238
  this.clients.set(id, client);
3239
+ const sendSnapshot = (type, data) => {
3240
+ const event = { type, data, timestamp: new Date().toISOString() };
3241
+ const visible = readOnly ? this.observerEvent(event) : event;
3242
+ if (visible)
3243
+ res.write(`data: ${JSON.stringify(visible)}\n\n`);
3244
+ };
2759
3245
  // Clean up stale client on stream error — prevents uncaught exception
2760
3246
  // when write() hits a destroyed socket before the req 'close' event fires.
2761
3247
  res.on('error', () => { this.clients.delete(id); });
@@ -2763,22 +3249,18 @@ export class MirrorStreamServer {
2763
3249
  res.write(`data: ${JSON.stringify({
2764
3250
  type: 'connected',
2765
3251
  timestamp: new Date().toISOString(),
2766
- data: this.buildConnectedEventData(id, canInspectPrompts),
3252
+ data: readOnly ? this.observerConnectionData(id) : this.buildConnectedEventData(id, canInspectPrompts),
2767
3253
  })}\n\n`);
2768
3254
  // Send pane layout on connect (multi-pane mode). Same payload the live
2769
3255
  // publishPaneInfo broadcast uses — built once by the registry.
2770
3256
  if (this.multiPaneMode) {
2771
- res.write(`data: ${JSON.stringify({
2772
- type: 'pane_info',
2773
- timestamp: new Date().toISOString(),
2774
- data: this.panes.toPaneInfoData(this.hiddenPaneIds),
2775
- })}\n\n`);
3257
+ sendSnapshot('pane_info', this.panes.toPaneInfoData(this.hiddenPaneIds));
2776
3258
  }
2777
3259
  // Send event history to catch up new clients.
2778
3260
  // Plugins may intercept (e.g. colony sends per-worktree persisted events).
2779
3261
  let pluginHandledHistory = false;
2780
3262
  for (const plugin of this.plugins) {
2781
- if (plugin.onSSEConnect && plugin.onSSEConnect(res, url)) {
3263
+ if (!readOnly && plugin.onSSEConnect && plugin.onSSEConnect(res, url)) {
2782
3264
  pluginHandledHistory = true;
2783
3265
  break;
2784
3266
  }
@@ -2810,13 +3292,15 @@ export class MirrorStreamServer {
2810
3292
  for (const event of backfill) {
2811
3293
  if (res.destroyed)
2812
3294
  break;
2813
- res.write(`id: ${event.seq ?? 0}\ndata: ${JSON.stringify(event)}\n\n`);
3295
+ const visible = readOnly ? this.observerEvent(event) : event;
3296
+ if (visible)
3297
+ res.write(`id: ${event.seq ?? 0}\ndata: ${JSON.stringify(visible)}\n\n`);
2814
3298
  }
2815
3299
  }
2816
3300
  // The accounts badge is kept out of retained history (above), so replay it
2817
3301
  // per-client on connect — otherwise a fresh client shows a blank/stale badge
2818
3302
  // until the next switch. Live-only: no seq/id line, like `connected`.
2819
- if (!res.destroyed) {
3303
+ if (!res.destroyed && !readOnly) {
2820
3304
  res.write(`data: ${JSON.stringify({
2821
3305
  type: 'accounts',
2822
3306
  timestamp: new Date().toISOString(),
@@ -2826,28 +3310,36 @@ export class MirrorStreamServer {
2826
3310
  // Replay cached pane content that may have been evicted from event history,
2827
3311
  // so new clients always see it regardless of history depth.
2828
3312
  for (const [pid, info] of this.panes.entries()) {
2829
- if (info.commandJobs) {
3313
+ if (info.commandPane)
3314
+ sendSnapshot('command_pane', { pane_id: pid, command: info.commandPane });
3315
+ if (info.goal) {
3316
+ res.write(`data: ${JSON.stringify({ type: 'goal', timestamp: new Date().toISOString(),
3317
+ data: { pane_id: pid, ...info.goal } })}\n\n`);
3318
+ }
3319
+ if (info.taskHandoff) {
2830
3320
  res.write(`data: ${JSON.stringify({
2831
- type: 'command_jobs',
3321
+ type: 'task_handoff',
2832
3322
  timestamp: new Date().toISOString(),
2833
- data: { pane_id: pid, jobs: info.commandJobs },
3323
+ data: { pane_id: pid, ...info.taskHandoff },
2834
3324
  })}\n\n`);
2835
3325
  }
2836
- if ((info.paneType === 'doc' || info.paneType === 'feed') && info.docContent) {
3326
+ if (info.evidence) {
2837
3327
  res.write(`data: ${JSON.stringify({
2838
- type: 'pane_output',
3328
+ type: 'evidence',
2839
3329
  timestamp: new Date().toISOString(),
2840
- data: { pane_id: pid, content: info.docContent },
3330
+ data: { pane_id: pid, session_id: info.evidence.sessionId, snapshot: info.evidence.snapshot },
2841
3331
  })}\n\n`);
2842
3332
  }
3333
+ if (info.commandJobs) {
3334
+ sendSnapshot('command_jobs', { pane_id: pid, jobs: info.commandJobs });
3335
+ }
3336
+ if ((info.paneType === 'doc' || info.paneType === 'feed') && info.docContent) {
3337
+ sendSnapshot('pane_output', { pane_id: pid, content: info.docContent });
3338
+ }
2843
3339
  else if (isTerminalPaneType(info.paneType) && info.terminalOutput) {
2844
3340
  // reset:true clears any partial paint, then the buffered tail repaints
2845
3341
  // the terminal — so an idle shell shows its prompt instead of blank.
2846
- res.write(`data: ${JSON.stringify({
2847
- type: 'pane_output',
2848
- timestamp: new Date().toISOString(),
2849
- data: { pane_id: pid, content: info.terminalOutput, reset: true },
2850
- })}\n\n`);
3342
+ sendSnapshot('pane_output', { pane_id: pid, content: info.terminalOutput, reset: true });
2851
3343
  }
2852
3344
  }
2853
3345
  // SSE keepalive: write a comment line every 25s so intermediaries
@@ -2863,8 +3355,17 @@ export class MirrorStreamServer {
2863
3355
  // ignore — connection cleanup handled by 'close' below
2864
3356
  }
2865
3357
  }, 25000);
3358
+ const expiryTimer = readOnly && auth.session
3359
+ ? setTimeout(() => {
3360
+ res.write(`data: ${JSON.stringify({ type: 'share_expired', data: { share_id: client.shareId } })}\n\n`);
3361
+ res.end();
3362
+ this.clients.delete(id);
3363
+ }, Math.max(1, auth.session.expiresAtMs - Date.now()))
3364
+ : null;
2866
3365
  req.on('close', () => {
2867
3366
  clearInterval(keepAliveTimer);
3367
+ if (expiryTimer)
3368
+ clearTimeout(expiryTimer);
2868
3369
  this.clients.delete(id);
2869
3370
  });
2870
3371
  return;
@@ -3262,7 +3763,14 @@ export class MirrorStreamServer {
3262
3763
  res.end(JSON.stringify({ error: "decision must be 'approve' or 'deny'" }));
3263
3764
  return;
3264
3765
  }
3265
- if (!this.pendingHookApprovalIds.has(parsed.id)) {
3766
+ const paneId = parsed.pane_id ?? 0;
3767
+ if (!Number.isSafeInteger(paneId) || paneId < 0) {
3768
+ res.writeHead(400, { 'Content-Type': 'application/json' });
3769
+ res.end(JSON.stringify({ error: 'pane_id must be a non-negative integer' }));
3770
+ return;
3771
+ }
3772
+ const pending = this.attention.findRequest('approval', parsed.id, paneId);
3773
+ if (!pending) {
3266
3774
  // 409 only when the id isn't in the live map — any other id is stale.
3267
3775
  // With parallel approvals, multiple ids may be in flight concurrently;
3268
3776
  // a valid in-flight id always matches.
@@ -3270,13 +3778,8 @@ export class MirrorStreamServer {
3270
3778
  res.end(JSON.stringify({ error: 'Stale approval — request no longer pending' }));
3271
3779
  return;
3272
3780
  }
3273
- this.pendingHookApprovalIds.delete(parsed.id);
3274
- // Drop only the event for this id so other in-flight approvals survive.
3275
- this.history.removeByPredicate((e) => e.type === 'hook_approval_request' && e.data.id === parsed.id, true);
3276
3781
  const reason = typeof parsed.reason === 'string' ? parsed.reason : undefined;
3277
- if (this.hookApprovalCallback) {
3278
- this.hookApprovalCallback(parsed.id, parsed.decision, reason);
3279
- }
3782
+ this.respondAttention(pending.id, { decision: parsed.decision, reason });
3280
3783
  res.writeHead(200, { 'Content-Type': 'application/json' });
3281
3784
  res.end(JSON.stringify({ ok: true }));
3282
3785
  }
@@ -3287,6 +3790,18 @@ export class MirrorStreamServer {
3287
3790
  }
3288
3791
  // Handle ask_user answers from the browser
3289
3792
  if (url.pathname === '/ask-user-answer' && req.method === 'POST') {
3793
+ // Managed terminal monitors are tied to this owner incarnation. Existing
3794
+ // browser callers retain their pane/question identity contract.
3795
+ const workspaceOwner = req.headers['x-ztc-workspace-owner'];
3796
+ if (workspaceOwner !== undefined) {
3797
+ if (!this.requireInternalAuth(auth, res))
3798
+ return;
3799
+ if (workspaceOwner !== this.workspaceOwnerId) {
3800
+ res.writeHead(409, { 'Content-Type': 'application/json' });
3801
+ res.end(JSON.stringify({ error: 'Workspace owner changed; open a fresh layout.' }));
3802
+ return;
3803
+ }
3804
+ }
3290
3805
  try {
3291
3806
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
3292
3807
  if (!parsed.answer || typeof parsed.answer !== 'string') {
@@ -3299,20 +3814,24 @@ export class MirrorStreamServer {
3299
3814
  res.end(JSON.stringify({ error: 'pane_id must be a number' }));
3300
3815
  return;
3301
3816
  }
3302
- if (parsed.question_id && this.pendingQuestionId && parsed.question_id !== this.pendingQuestionId) {
3303
- res.writeHead(409, { 'Content-Type': 'application/json' });
3304
- res.end(JSON.stringify({ error: 'Stale question — a newer question has been asked' }));
3817
+ if (parsed.question_id !== undefined && (typeof parsed.question_id !== 'string' || !parsed.question_id)) {
3818
+ res.writeHead(400, { 'Content-Type': 'application/json' });
3819
+ res.end(JSON.stringify({ error: 'question_id must be a non-empty string' }));
3305
3820
  return;
3306
3821
  }
3307
- this.pendingQuestionId = null;
3308
- // Purge the answered question from replay history: a reconnecting SSE
3309
- // consumer (browser reload, colony bridge) must not re-receive a stale
3310
- // ask_user and treat the cell as still waiting. Single-slot pending
3311
- // question, so a blanket type filter is safe.
3312
- this.history.removeByPredicate((e) => e.type === 'ask_user', true);
3313
- if (this.askUserAnswerCallback) {
3314
- this.askUserAnswerCallback(parsed.answer, parsed.pane_id ?? 0);
3822
+ const paneId = parsed.pane_id ?? 0;
3823
+ // Legacy clients answer the current pane question without an ID. Modern
3824
+ // clients keep the stronger stale-ID check; neither path crosses panes.
3825
+ const currentId = this.pendingQuestions.get(paneId)?.data.question_id;
3826
+ const questionId = parsed.question_id ?? currentId;
3827
+ const pending = typeof questionId === 'string' && questionId === currentId
3828
+ ? this.attention.findRequest('question', questionId, paneId) : undefined;
3829
+ if (!pending) {
3830
+ res.writeHead(409, { 'Content-Type': 'application/json' });
3831
+ res.end(JSON.stringify({ error: 'Stale question — request no longer pending in this pane. Refresh the mirror if the question ID is missing.' }));
3832
+ return;
3315
3833
  }
3834
+ this.respondAttention(pending.id, parsed.answer);
3316
3835
  res.writeHead(200, { 'Content-Type': 'application/json' });
3317
3836
  res.end(JSON.stringify({ ok: true }));
3318
3837
  }
@@ -3325,12 +3844,35 @@ export class MirrorStreamServer {
3325
3844
  if (url.pathname === '/widget-answer' && req.method === 'POST') {
3326
3845
  try {
3327
3846
  const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
3328
- if (!parsed.widget_id) {
3847
+ if (typeof parsed.widget_id !== 'string' || !parsed.widget_id || !parsed.answer || typeof parsed.answer !== 'object' || Array.isArray(parsed.answer)
3848
+ || (parsed.pane_id !== undefined && (!Number.isSafeInteger(parsed.pane_id) || parsed.pane_id < 0))) {
3329
3849
  res.writeHead(400, { 'Content-Type': 'application/json' });
3330
- res.end(JSON.stringify({ error: 'widget_id is required' }));
3850
+ res.end(JSON.stringify({ error: 'widget_id, an answer object and a valid pane_id are required' }));
3851
+ return;
3852
+ }
3853
+ const paneId = parsed.pane_id ?? 0;
3854
+ const pending = this.attention.findRequest('prompt', parsed.widget_id, paneId);
3855
+ const settings = this.attention.hasSettings(parsed.widget_id, paneId);
3856
+ if (!pending && !settings) {
3857
+ res.writeHead(409, { 'Content-Type': 'application/json' });
3858
+ res.end(JSON.stringify({ error: 'Stale widget — request no longer pending in this pane' }));
3859
+ return;
3860
+ }
3861
+ if (pending) {
3862
+ try {
3863
+ this.respondAttention(pending.id, parsed.answer);
3864
+ }
3865
+ catch (error) {
3866
+ res.writeHead(409, { 'Content-Type': 'application/json' });
3867
+ res.end(JSON.stringify({ error: error instanceof Error ? error.message : 'Prompt owner is unavailable.' }));
3868
+ return;
3869
+ }
3870
+ res.writeHead(200, { 'Content-Type': 'application/json' });
3871
+ res.end(JSON.stringify({ ok: true }));
3331
3872
  return;
3332
3873
  }
3333
3874
  if (parsed.answer && parsed.answer._closed === true) {
3875
+ this.attention.closeSettings(parsed.widget_id, paneId);
3334
3876
  // Closed settings panel: drop its widget_settings event so a reload
3335
3877
  // doesn't reopen the modal.
3336
3878
  this.history.removeByPredicate((e) => e.type === 'widget_settings' && e.data.widget_id === parsed.widget_id, true);
@@ -3346,21 +3888,54 @@ export class MirrorStreamServer {
3346
3888
  }
3347
3889
  return;
3348
3890
  }
3891
+ // Open a fresh parent-issued publication identity. Reopening supersedes old packets;
3892
+ // clients never retry uncertain effects and do not carry an identity across reconnects.
3893
+ if (url.pathname.startsWith('/pane-publication') && req.method === 'POST') {
3894
+ if (!this.requireInternalAuth(auth, res))
3895
+ return;
3896
+ try {
3897
+ const parsed = await this.readJsonBody(req, MAX_MIRROR_CONTROL_BODY_BYTES);
3898
+ const paneId = parsed?.pane_id;
3899
+ const scope = url.pathname.slice('/pane-publication'.length);
3900
+ if (!Number.isSafeInteger(paneId) || paneId < -1 || scope.length > 256) {
3901
+ res.writeHead(400, { 'Content-Type': 'application/json' });
3902
+ res.end(JSON.stringify({ error: 'invalid_publication_pane' }));
3903
+ return;
3904
+ }
3905
+ const publicationId = this.childPublications.open(paneId, scope);
3906
+ res.writeHead(publicationId ? 200 : 503, { 'Content-Type': 'application/json' });
3907
+ res.end(JSON.stringify(publicationId ? { ok: true, publication_id: publicationId }
3908
+ : { error: 'publication_capacity_exhausted', message: 'Restart the parent mirror before registering more pane identities.' }));
3909
+ }
3910
+ catch (error) {
3911
+ this.writeJsonError(res, error);
3912
+ }
3913
+ return;
3914
+ }
3349
3915
  // Handle events from child panes (multi-pane mode)
3350
3916
  if (url.pathname.startsWith('/pane-events') && req.method === 'POST') {
3351
3917
  if (!this.requireInternalAuth(auth, res))
3352
3918
  return;
3353
3919
  try {
3354
- const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
3920
+ const parsed = await this.readJsonBody(req, req.headers['x-ztc-tool-image'] === '1' ? MAX_TOOL_IMAGE_BODY_BYTES : MAX_MIRROR_EVENT_BODY_BYTES);
3921
+ if (!this.admitChildPublication(parsed, res, url.pathname.slice('/pane-events'.length)))
3922
+ return;
3355
3923
  // Inject pane_id into event data and broadcast to SSE clients
3356
3924
  const event = parsed.event;
3925
+ if (req.headers['x-ztc-tool-image'] === '1' && (event.type !== 'tool_result' || !mirrorToolImage(event.data?.result))) {
3926
+ res.writeHead(400, { 'Content-Type': 'application/json' });
3927
+ res.end(JSON.stringify({ error: 'A tool-image upload must contain a valid image result.' }));
3928
+ return;
3929
+ }
3357
3930
  const rawData = event.data && typeof event.data === 'object' ? event.data : {};
3358
3931
  const { final_message: finalMessageRaw, final_message_metadata: finalMessageMetadataRaw, ...eventData } = rawData;
3359
3932
  const finalMessage = typeof finalMessageRaw === 'string' ? finalMessageRaw : null;
3360
3933
  const finalMessageMetadata = finalMessageMetadataRaw && typeof finalMessageMetadataRaw === 'object'
3361
3934
  ? finalMessageMetadataRaw
3362
3935
  : undefined;
3363
- const taggedEventData = { ...eventData, pane_id: parsed.pane_id };
3936
+ const taggedEventData = event.type === 'tool_result'
3937
+ ? this.retainToolImage({ ...eventData, pane_id: parsed.pane_id })
3938
+ : { ...eventData, pane_id: parsed.pane_id };
3364
3939
  // Drop session_end from child panes — a child exiting must not
3365
3940
  // trigger the parent's browser "reconnect" overlay.
3366
3941
  if (event.type === 'session_end') {
@@ -3399,6 +3974,7 @@ export class MirrorStreamServer {
3399
3974
  type: 'message',
3400
3975
  data: {
3401
3976
  pane_id: parsed.pane_id,
3977
+ origin_session_id: taggedEventData.origin_session_id,
3402
3978
  role: 'assistant',
3403
3979
  content: finalMessage,
3404
3980
  ...(finalMessageMetadata ? { metadata: finalMessageMetadata } : {}),
@@ -3420,6 +3996,8 @@ export class MirrorStreamServer {
3420
3996
  return;
3421
3997
  try {
3422
3998
  const parsed = await this.readJsonBody(req, MAX_MIRROR_EVENT_BODY_BYTES);
3999
+ if (!this.admitChildPublication(parsed, res, ''))
4000
+ return;
3423
4001
  const event = parsed.event;
3424
4002
  event.data = { ...event.data, pane_id: parsed.pane_id };
3425
4003
  this.storeEvent({
@@ -3683,7 +4261,10 @@ export class MirrorStreamServer {
3683
4261
  const lineCount = parseInt(url.searchParams.get('lines') || '50', 10) || 50;
3684
4262
  const outputTypes = new Set(['message', 'tool_call', 'tool_result', 'status', 'error']);
3685
4263
  const filtered = this.history.snapshot().filter((e) => outputTypes.has(e.type));
3686
- const recent = filtered.slice(-lineCount);
4264
+ const recent = filtered.slice(-lineCount).flatMap(event => {
4265
+ const visible = readOnly ? this.observerEvent(event) : event;
4266
+ return visible ? [visible] : [];
4267
+ });
3687
4268
  const text = recent.map((e) => {
3688
4269
  const content = e.data.content || e.data.message || JSON.stringify(e.data);
3689
4270
  return `[${e.type}] ${content}`;