@phren/cli 0.2.15 → 0.2.16

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 (386) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-instructions.d.ts +12 -0
  3. package/dist/agent-instructions.js +52 -0
  4. package/dist/bridge/agent-hook-stores.d.ts +32 -0
  5. package/dist/bridge/agent-hook-stores.js +67 -0
  6. package/dist/bridge/agent-hooks.d.ts +193 -2
  7. package/dist/bridge/agent-hooks.js +1045 -38
  8. package/dist/bridge/canary.d.ts +27 -0
  9. package/dist/bridge/canary.js +189 -0
  10. package/dist/bridge/changes.d.ts +57 -0
  11. package/dist/bridge/changes.js +403 -0
  12. package/dist/bridge/client.d.ts +3 -0
  13. package/dist/bridge/client.js +36 -0
  14. package/dist/bridge/code-note.d.ts +22 -0
  15. package/dist/bridge/code-note.js +42 -0
  16. package/dist/bridge/code-routes.d.ts +133 -0
  17. package/dist/bridge/code-routes.js +319 -0
  18. package/dist/bridge/codex-threads.d.ts +27 -0
  19. package/dist/bridge/codex-threads.js +442 -0
  20. package/dist/bridge/command.d.ts +7 -0
  21. package/dist/bridge/command.js +50 -5
  22. package/dist/bridge/computer-names.d.ts +4 -0
  23. package/dist/bridge/computer-names.js +16 -0
  24. package/dist/bridge/computers.d.ts +9 -0
  25. package/dist/bridge/computers.js +111 -0
  26. package/dist/bridge/context.d.ts +14 -0
  27. package/dist/bridge/context.js +149 -0
  28. package/dist/bridge/dispatch-command.d.ts +3 -0
  29. package/dist/bridge/dispatch-command.js +93 -0
  30. package/dist/bridge/dispatch-hosts.d.ts +23 -0
  31. package/dist/bridge/dispatch-hosts.js +25 -0
  32. package/dist/bridge/dispatch-returns.d.ts +123 -0
  33. package/dist/bridge/dispatch-returns.js +279 -0
  34. package/dist/bridge/dispatch-tree.d.ts +54 -0
  35. package/dist/bridge/dispatch-tree.js +198 -0
  36. package/dist/bridge/dispatch.d.ts +207 -0
  37. package/dist/bridge/dispatch.js +261 -0
  38. package/dist/bridge/enroll.d.ts +31 -0
  39. package/dist/bridge/enroll.js +236 -0
  40. package/dist/bridge/fanout-messages.d.ts +74 -0
  41. package/dist/bridge/fanout-messages.js +230 -0
  42. package/dist/bridge/fanouts.d.ts +160 -0
  43. package/dist/bridge/fanouts.js +702 -0
  44. package/dist/bridge/file-range.d.ts +16 -0
  45. package/dist/bridge/file-range.js +90 -0
  46. package/dist/bridge/files.d.ts +20 -0
  47. package/dist/bridge/files.js +54 -0
  48. package/dist/bridge/git-publish.d.ts +23 -0
  49. package/dist/bridge/git-publish.js +145 -0
  50. package/dist/bridge/git-worktrees.d.ts +21 -0
  51. package/dist/bridge/git-worktrees.js +150 -0
  52. package/dist/bridge/git.d.ts +54 -0
  53. package/dist/bridge/git.js +552 -0
  54. package/dist/bridge/grants.d.ts +31 -0
  55. package/dist/bridge/grants.js +181 -0
  56. package/dist/bridge/hand-off.d.ts +79 -0
  57. package/dist/bridge/hand-off.js +151 -0
  58. package/dist/bridge/health.d.ts +128 -0
  59. package/dist/bridge/health.js +260 -0
  60. package/dist/bridge/herdr.d.ts +79 -6
  61. package/dist/bridge/herdr.js +292 -27
  62. package/dist/bridge/hook-main.js +2 -0
  63. package/dist/bridge/install.d.ts +32 -1
  64. package/dist/bridge/install.js +225 -38
  65. package/dist/bridge/launch-worktree.d.ts +21 -0
  66. package/dist/bridge/launch-worktree.js +70 -0
  67. package/dist/bridge/limits.d.ts +20 -0
  68. package/dist/bridge/limits.js +65 -0
  69. package/dist/bridge/locate.d.ts +16 -0
  70. package/dist/bridge/locate.js +75 -0
  71. package/dist/bridge/metrics.d.ts +29 -0
  72. package/dist/bridge/metrics.js +71 -0
  73. package/dist/bridge/model-switch.d.ts +35 -0
  74. package/dist/bridge/model-switch.js +250 -0
  75. package/dist/bridge/models.d.ts +46 -0
  76. package/dist/bridge/models.js +257 -0
  77. package/dist/bridge/opencode-approvals.d.ts +6 -0
  78. package/dist/bridge/opencode-approvals.js +60 -0
  79. package/dist/bridge/pane-text.d.ts +15 -0
  80. package/dist/bridge/pane-text.js +23 -0
  81. package/dist/bridge/peers.d.ts +27 -0
  82. package/dist/bridge/peers.js +130 -0
  83. package/dist/bridge/projects.d.ts +12 -1
  84. package/dist/bridge/projects.js +268 -20
  85. package/dist/bridge/protocol.d.ts +35 -2
  86. package/dist/bridge/protocol.js +42 -7
  87. package/dist/bridge/push.d.ts +83 -0
  88. package/dist/bridge/push.js +199 -0
  89. package/dist/bridge/questions.d.ts +38 -0
  90. package/dist/bridge/questions.js +205 -0
  91. package/dist/bridge/schedule-format.d.ts +103 -0
  92. package/dist/bridge/schedule-format.js +266 -0
  93. package/dist/bridge/schedule-launch.d.ts +11 -0
  94. package/dist/bridge/schedule-launch.js +169 -0
  95. package/dist/bridge/schedule-watch.d.ts +52 -0
  96. package/dist/bridge/schedule-watch.js +242 -0
  97. package/dist/bridge/schedules.d.ts +48 -0
  98. package/dist/bridge/schedules.js +205 -0
  99. package/dist/bridge/server-launch.d.ts +14 -0
  100. package/dist/bridge/server-launch.js +218 -0
  101. package/dist/bridge/server-overview.d.ts +45 -0
  102. package/dist/bridge/server-overview.js +102 -0
  103. package/dist/bridge/server-pane-routes.d.ts +29 -0
  104. package/dist/bridge/server-pane-routes.js +400 -0
  105. package/dist/bridge/server-routes.d.ts +106 -0
  106. package/dist/bridge/server-routes.js +538 -0
  107. package/dist/bridge/server-stream.d.ts +46 -0
  108. package/dist/bridge/server-stream.js +253 -0
  109. package/dist/bridge/server.d.ts +3 -15
  110. package/dist/bridge/server.js +162 -264
  111. package/dist/bridge/session-servers.d.ts +24 -0
  112. package/dist/bridge/session-servers.js +136 -0
  113. package/dist/bridge/side-questions.d.ts +74 -0
  114. package/dist/bridge/side-questions.js +252 -0
  115. package/dist/bridge/simulators.d.ts +28 -0
  116. package/dist/bridge/simulators.js +198 -0
  117. package/dist/bridge/speech-transcribe.d.ts +24 -0
  118. package/dist/bridge/speech-transcribe.js +124 -0
  119. package/dist/bridge/speech.d.ts +35 -0
  120. package/dist/bridge/speech.js +98 -0
  121. package/dist/bridge/steps.d.ts +13 -0
  122. package/dist/bridge/steps.js +222 -0
  123. package/dist/bridge/tab-activity.d.ts +18 -0
  124. package/dist/bridge/tab-activity.js +99 -0
  125. package/dist/bridge/terminal-choice.d.ts +64 -0
  126. package/dist/bridge/terminal-choice.js +281 -0
  127. package/dist/bridge/transcript-claude.d.ts +22 -0
  128. package/dist/bridge/transcript-claude.js +353 -0
  129. package/dist/bridge/transcript-codex.d.ts +30 -0
  130. package/dist/bridge/transcript-codex.js +282 -0
  131. package/dist/bridge/transcript-copilot.d.ts +4 -0
  132. package/dist/bridge/transcript-copilot.js +14 -0
  133. package/dist/bridge/transcript-opencode.d.ts +5 -0
  134. package/dist/bridge/transcript-opencode.js +26 -0
  135. package/dist/bridge/transcript-preview.d.ts +94 -0
  136. package/dist/bridge/transcript-preview.js +476 -0
  137. package/dist/bridge/transcripts.d.ts +81 -4
  138. package/dist/bridge/transcripts.js +332 -67
  139. package/dist/bridge/transport.d.ts +3 -0
  140. package/dist/bridge/transport.js +96 -15
  141. package/dist/bridge/uploads.d.ts +15 -0
  142. package/dist/bridge/uploads.js +44 -2
  143. package/dist/bridge/usage.d.ts +124 -0
  144. package/dist/bridge/usage.js +859 -0
  145. package/dist/bridge-hook.mjs +41246 -21385
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-proactivity.d.ts +3 -1
  148. package/dist/cli/config-proactivity.js +35 -3
  149. package/dist/cli/config.js +4 -1
  150. package/dist/cli/extract.js +3 -6
  151. package/dist/cli/govern.js +5 -2
  152. package/dist/cli/hooks-globs.js +1 -1
  153. package/dist/cli/hooks.d.ts +1 -1
  154. package/dist/cli/hooks.js +9 -7
  155. package/dist/cli/namespaces-projects.js +12 -6
  156. package/dist/cli/namespaces-store.js +37 -6
  157. package/dist/cli/namespaces-tasks.js +1 -1
  158. package/dist/cli/schedules.d.ts +1 -0
  159. package/dist/cli/schedules.js +164 -0
  160. package/dist/cli/session-background.js +1 -1
  161. package/dist/cli/session-git.d.ts +8 -5
  162. package/dist/cli/session-git.js +45 -120
  163. package/dist/cli/session-start.js +3 -1
  164. package/dist/cli/session-stop.js +19 -8
  165. package/dist/cli/team.js +13 -10
  166. package/dist/cli-handlers.d.ts +1 -1
  167. package/dist/cli-handlers.js +8 -4
  168. package/dist/cli-help.d.ts +5 -4
  169. package/dist/cli-help.js +15 -15
  170. package/dist/cli-registry.d.ts +4 -1
  171. package/dist/cli-registry.js +119 -6
  172. package/dist/content/archive.js +2 -2
  173. package/dist/content/citation.d.ts +11 -0
  174. package/dist/content/citation.js +18 -0
  175. package/dist/content/learning.js +2 -0
  176. package/dist/content/summarize.d.ts +14 -15
  177. package/dist/content/summarize.js +60 -5
  178. package/dist/content/validate.d.ts +3 -1
  179. package/dist/content/validate.js +26 -8
  180. package/dist/core/project-registry.d.ts +26 -0
  181. package/dist/core/project-registry.js +573 -0
  182. package/dist/core/project.js +2 -3
  183. package/dist/data/access.d.ts +7 -1
  184. package/dist/data/access.js +13 -3
  185. package/dist/data/tasks.d.ts +18 -3
  186. package/dist/data/tasks.js +8 -7
  187. package/dist/entrypoint.js +44 -10
  188. package/dist/fanout/adapters/claude.d.ts +2 -0
  189. package/dist/fanout/adapters/claude.js +7 -0
  190. package/dist/fanout/adapters/codex.d.ts +2 -0
  191. package/dist/fanout/adapters/codex.js +9 -0
  192. package/dist/fanout/adapters/opencode.d.ts +4 -0
  193. package/dist/fanout/adapters/opencode.js +9 -0
  194. package/dist/fanout/adapters/types.d.ts +21 -0
  195. package/dist/fanout/adapters/types.js +3 -0
  196. package/dist/fanout/command.d.ts +2 -0
  197. package/dist/fanout/command.js +78 -0
  198. package/dist/fanout/launcher.d.ts +27 -0
  199. package/dist/fanout/launcher.js +156 -0
  200. package/dist/fanout/opencode-serve.d.ts +24 -0
  201. package/dist/fanout/opencode-serve.js +191 -0
  202. package/dist/fanout/picker.d.ts +91 -0
  203. package/dist/fanout/picker.js +51 -0
  204. package/dist/fanout/usage.d.ts +5 -0
  205. package/dist/fanout/usage.js +51 -0
  206. package/dist/fanout/watchdog.d.ts +10 -0
  207. package/dist/fanout/watchdog.js +27 -0
  208. package/dist/filenames.d.ts +9 -0
  209. package/dist/filenames.js +11 -0
  210. package/dist/finding/context.js +4 -22
  211. package/dist/generated/memory-ui-graph.browser.js +279 -283
  212. package/dist/governance/policy-constants.d.ts +11 -0
  213. package/dist/governance/policy-constants.js +9 -0
  214. package/dist/governance/policy.d.ts +5 -8
  215. package/dist/governance/policy.js +7 -5
  216. package/dist/graph-core/camera.d.ts +24 -0
  217. package/dist/graph-core/camera.js +18 -0
  218. package/dist/graph-core/index.d.ts +2 -0
  219. package/dist/graph-core/index.js +2 -0
  220. package/dist/graph-core/labels.d.ts +77 -0
  221. package/dist/graph-core/labels.js +124 -0
  222. package/dist/graph-core/model.d.ts +13 -0
  223. package/dist/graph-core/model.js +33 -0
  224. package/dist/graph-core/types.d.ts +2 -0
  225. package/dist/home-paths.d.ts +7 -0
  226. package/dist/home-paths.js +21 -0
  227. package/dist/hooks.d.ts +3 -0
  228. package/dist/hooks.js +13 -0
  229. package/dist/index.js +24 -2
  230. package/dist/init/guard-globals.d.ts +1 -1
  231. package/dist/init/guard-globals.js +4 -4
  232. package/dist/init/init-configure.js +3 -3
  233. package/dist/init/init-uninstall.js +2 -2
  234. package/dist/init/init-walkthrough.js +1 -1
  235. package/dist/init/init.js +26 -6
  236. package/dist/init/management-preset.d.ts +1 -1
  237. package/dist/init/management-preset.js +2 -2
  238. package/dist/init/preferences.js +1 -1
  239. package/dist/init/self-wiring.js +1 -1
  240. package/dist/init/setup.d.ts +3 -26
  241. package/dist/init/setup.js +49 -588
  242. package/dist/init/shared.js +2 -0
  243. package/dist/init/store-gitignore.d.ts +1 -1
  244. package/dist/init/store-gitignore.js +2 -0
  245. package/dist/init/teardown.d.ts +1 -1
  246. package/dist/init/teardown.js +2 -2
  247. package/dist/link/context.js +1 -1
  248. package/dist/link/doctor.d.ts +22 -1
  249. package/dist/link/doctor.js +100 -54
  250. package/dist/link/link.js +29 -61
  251. package/dist/link/refresh.js +2 -2
  252. package/dist/link/skills.js +26 -5
  253. package/dist/machine-identity.d.ts +3 -0
  254. package/dist/machine-identity.js +6 -0
  255. package/dist/mcp/profile.d.ts +2 -15
  256. package/dist/mcp/profile.js +64 -9
  257. package/dist/memory-ui-graph.runtime.js +279 -283
  258. package/dist/modules/code-package.d.ts +16 -0
  259. package/dist/modules/code-package.js +152 -0
  260. package/dist/modules/command.d.ts +2 -0
  261. package/dist/modules/command.js +67 -0
  262. package/dist/modules/config.d.ts +4 -0
  263. package/dist/modules/config.js +70 -0
  264. package/dist/modules/manifest.d.ts +41 -0
  265. package/dist/modules/manifest.js +1 -0
  266. package/dist/modules/provision.d.ts +3 -0
  267. package/dist/modules/provision.js +84 -0
  268. package/dist/modules/registry.d.ts +16 -0
  269. package/dist/modules/registry.js +250 -0
  270. package/dist/modules/runtime.d.ts +15 -0
  271. package/dist/modules/runtime.js +59 -0
  272. package/dist/package-metadata.js +10 -2
  273. package/dist/phren-dotenv.js +4 -2
  274. package/dist/phren-paths.d.ts +3 -2
  275. package/dist/phren-paths.js +4 -5
  276. package/dist/profile-store.js +4 -5
  277. package/dist/project-config.d.ts +19 -1
  278. package/dist/project-config.js +29 -3
  279. package/dist/project-topics.js +4 -4
  280. package/dist/provider-adapters.js +1 -4
  281. package/dist/query-correlation.js +6 -6
  282. package/dist/session/artifacts.js +5 -5
  283. package/dist/session/checkpoints.js +5 -0
  284. package/dist/session/utils.d.ts +2 -2
  285. package/dist/session/utils.js +6 -6
  286. package/dist/shared/content.d.ts +1 -1
  287. package/dist/shared/content.js +1 -1
  288. package/dist/shared/data-utils.js +1 -1
  289. package/dist/shared/fragment-graph.d.ts +1 -1
  290. package/dist/shared/fragment-graph.js +5 -5
  291. package/dist/shared/index.js +48 -7
  292. package/dist/shared/retrieval.d.ts +18 -1
  293. package/dist/shared/retrieval.js +100 -11
  294. package/dist/shared/search-fallback.js +4 -6
  295. package/dist/shared/sqljs.d.ts +2 -0
  296. package/dist/shared/sqljs.js +4 -2
  297. package/dist/shared.d.ts +0 -1
  298. package/dist/shared.js +0 -1
  299. package/dist/shell/input.d.ts +1 -5
  300. package/dist/shell/input.js +16 -10
  301. package/dist/shell/palette.d.ts +2 -2
  302. package/dist/shell/palette.js +3 -7
  303. package/dist/shell/render.d.ts +3 -1
  304. package/dist/shell/render.js +4 -4
  305. package/dist/shell/shell.js +4 -1
  306. package/dist/shell/types.d.ts +1 -0
  307. package/dist/shell/types.js +4 -0
  308. package/dist/shell/view.d.ts +0 -4
  309. package/dist/shell/view.js +19 -27
  310. package/dist/skill/registry.js +25 -17
  311. package/dist/skill/state.d.ts +3 -0
  312. package/dist/skill/state.js +13 -7
  313. package/dist/status.js +38 -17
  314. package/dist/store-registry.d.ts +44 -18
  315. package/dist/store-registry.js +169 -60
  316. package/dist/store-weight.d.ts +1 -6
  317. package/dist/store-weight.js +4 -2
  318. package/dist/sync/auth-doctor.d.ts +8 -0
  319. package/dist/sync/auth-doctor.js +27 -0
  320. package/dist/sync/auth.d.ts +27 -0
  321. package/dist/sync/auth.js +114 -0
  322. package/dist/sync/conflict-resolve.d.ts +9 -0
  323. package/dist/sync/conflict-resolve.js +146 -0
  324. package/dist/sync/git-state.d.ts +4 -0
  325. package/dist/sync/git-state.js +49 -0
  326. package/dist/sync/outcome.d.ts +34 -0
  327. package/dist/sync/outcome.js +57 -0
  328. package/dist/sync/pull.d.ts +15 -7
  329. package/dist/sync/pull.js +84 -35
  330. package/dist/sync/store-merge.d.ts +29 -0
  331. package/dist/sync/store-merge.js +137 -0
  332. package/dist/sync/task-merge.d.ts +22 -0
  333. package/dist/sync/task-merge.js +158 -0
  334. package/dist/task/github.js +1 -1
  335. package/dist/task/lifecycle.d.ts +5 -0
  336. package/dist/task/lifecycle.js +67 -23
  337. package/dist/terminal-text.d.ts +5 -0
  338. package/dist/terminal-text.js +11 -0
  339. package/dist/test-global-setup.js +7 -0
  340. package/dist/tool-registry.d.ts +1 -1
  341. package/dist/tool-registry.js +3 -1
  342. package/dist/tools/code.d.ts +3 -0
  343. package/dist/tools/code.js +178 -0
  344. package/dist/tools/config.js +5 -0
  345. package/dist/tools/data.js +14 -7
  346. package/dist/tools/dispatch.d.ts +2 -0
  347. package/dist/tools/dispatch.js +66 -0
  348. package/dist/tools/finding.js +43 -41
  349. package/dist/tools/ops.js +5 -2
  350. package/dist/tools/search.js +21 -8
  351. package/dist/tools/session.js +21 -22
  352. package/dist/tools/tasks.js +8 -2
  353. package/dist/tools/types.d.ts +2 -2
  354. package/dist/tools/types.js +2 -2
  355. package/dist/ui/assets.js +1 -1
  356. package/dist/ui/data.js +14 -15
  357. package/dist/ui/deep-void.d.ts +1 -1
  358. package/dist/ui/deep-void.js +0 -1
  359. package/dist/ui/graph-chrome.d.ts +1 -1
  360. package/dist/ui/graph-chrome.js +51 -0
  361. package/dist/ui/page.js +5 -5
  362. package/dist/ui/scripts.js +67 -30
  363. package/dist/ui/server.js +34 -6
  364. package/dist/update.js +1 -1
  365. package/dist/utils-fts.js +1 -0
  366. package/dist/utils-helpers.d.ts +7 -0
  367. package/dist/utils-helpers.js +17 -0
  368. package/dist/utils.d.ts +1 -1
  369. package/dist/utils.js +1 -1
  370. package/package.json +45 -3
  371. package/plugins/opencode/phren-transcript.js +340 -0
  372. package/starter/README.md +4 -4
  373. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  374. package/starter/global/skills/conductor/SKILL.md +106 -0
  375. package/starter/global/skills/fanout/SKILL.md +20 -0
  376. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  377. package/starter/global/skills/phren-init/SKILL.md +4 -4
  378. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  379. package/starter/templates/frontend/reference/README.md +1 -1
  380. package/starter/templates/library/reference/README.md +1 -1
  381. package/starter/templates/monorepo/reference/README.md +1 -1
  382. package/starter/templates/python-project/reference/README.md +1 -1
  383. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  384. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  385. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  386. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,279 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { dispatchStatus, updateReceipt } from "./dispatch.js";
4
+ import { findPane, paneIdentity, sharedSnapshot } from "./herdr.js";
5
+ import { handOff } from "./hand-off.js";
6
+ import { hookPeers, peerRequest } from "./peers.js";
7
+ import { isLocalComputer } from "./dispatch-hosts.js";
8
+ import { objects, startingTargetSchema, targetSchema } from "./protocol.js";
9
+ import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
10
+ /**
11
+ * The conductor's returns loop. The worker's computer answers what its
12
+ * dispatched panes are doing from the Herdr snapshot its Hook already shares
13
+ * (`workerStates`); the dispatching Hook asks each peer once per poll for all
14
+ * of its open dispatches, records transitions in the receipts, and tells an
15
+ * idle dispatching agent that returns are waiting (`DispatchReturns`).
16
+ */
17
+ /** Longest final reply kept in a receipt, in UTF-8 bytes. */
18
+ export const REPLY_LIMIT = 4000;
19
+ /** How often the dispatching Hook asks peers about open dispatches. */
20
+ export const POLL_MS = 15_000;
21
+ /** Shortest gap between two notices typed into the same dispatching pane. */
22
+ export const NOTICE_MS = 120_000;
23
+ /** Receipts older than this are no longer watched. */
24
+ export const WATCH_MS = 24 * 60 * 60 * 1000;
25
+ /** An idle worker that was never seen working and has no finished turn is
26
+ * counted as done after this long: the prompt may never have been taken. */
27
+ export const IDLE_GRACE_MS = 5 * 60 * 1000;
28
+ /** How old a shared Herdr snapshot may be when answering a peer. */
29
+ const SNAPSHOT_AGE_MS = 5_000;
30
+ const workerTarget = z.union([targetSchema, startingTargetSchema]);
31
+ export const workerRequestSchema = z.object({ targets: z.array(workerTarget).min(1).max(64) }).strict();
32
+ const defaultReaders = {
33
+ snapshot: server => sharedSnapshot(server, SNAPSHOT_AGE_MS),
34
+ identity: (server, pane) => paneIdentity(server, pane),
35
+ finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
36
+ };
37
+ /** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
38
+ export function truncateUtf8(value, limit = REPLY_LIMIT) {
39
+ const bytes = Buffer.from(value);
40
+ if (bytes.length <= limit)
41
+ return { text: value, truncated: false };
42
+ let end = limit;
43
+ while (end > 0 && (bytes[end] & 0xc0) === 0x80)
44
+ end--;
45
+ return { text: bytes.subarray(0, end).toString("utf8"), truncated: true };
46
+ }
47
+ /** Receiving side: the state of each dispatched pane, from the shared snapshot
48
+ * and, once the agent has stopped, the final reply in its transcript. */
49
+ export async function workerStates(input, readers = defaultReaders) {
50
+ const { targets } = workerRequestSchema.parse(input);
51
+ const snapshots = new Map();
52
+ const workers = await Promise.all(targets.map(async (target) => {
53
+ let s;
54
+ try {
55
+ if (!snapshots.has(target.server))
56
+ snapshots.set(target.server, readers.snapshot(target.server));
57
+ s = await snapshots.get(target.server);
58
+ }
59
+ catch {
60
+ return { state: "unavailable" };
61
+ }
62
+ const pane = findPane(s, target);
63
+ if (!pane)
64
+ return { state: "gone" };
65
+ const current = await readers.identity(target.server, pane).catch(() => undefined);
66
+ const expected = "session" in target ? target.session : undefined;
67
+ // Another conversation in the same pane means the worker is gone.
68
+ if (expected && current && current !== expected)
69
+ return { state: "gone" };
70
+ const session = expected ?? current;
71
+ const status = String(pane.agent_status);
72
+ const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
73
+ if ((state !== "idle" && state !== "done") || !session)
74
+ return { state, ...(session ? { session } : {}) };
75
+ const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
76
+ const reply = turn?.lastAssistant ? truncateUtf8(turn.lastAssistant) : undefined;
77
+ return { state, session, completed: turn?.completed === true,
78
+ ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
79
+ }));
80
+ return { workers };
81
+ }
82
+ const observationSchema = z.object({
83
+ state: z.enum(["working", "idle", "done", "blocked", "unknown", "gone", "unavailable"]),
84
+ session: z.string().max(200).optional(), completed: z.boolean().optional(),
85
+ reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(),
86
+ }).passthrough();
87
+ function turnKey(reply) {
88
+ return reply ? createHash("sha256").update(reply).digest("hex").slice(0, 16) : undefined;
89
+ }
90
+ /** Apply one observation to a receipt. Returns true when the receipt changed. */
91
+ export function observe(receipt, value, now) {
92
+ const parsed = observationSchema.safeParse(value);
93
+ if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown")
94
+ return false;
95
+ const seen = parsed.data, at = new Date(now).toISOString();
96
+ let changed = false;
97
+ // A worker that started without a conversation id gets its full target once one exists.
98
+ if (seen.session && receipt.target && !("session" in receipt.target)) {
99
+ const full = targetSchema.safeParse({ server: receipt.target.server, workspace: receipt.target.workspace, tab: receipt.target.tab,
100
+ pane: receipt.target.pane, source: receipt.target.source, session: seen.session });
101
+ if (full.success) {
102
+ receipt.target = full.data;
103
+ changed = true;
104
+ }
105
+ }
106
+ const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
107
+ const question = seen.completed && seen.reply ? ownerQuestion(seen.reply) : undefined;
108
+ let next;
109
+ if (seen.state === "gone")
110
+ next = "gone";
111
+ else if (seen.state === "working")
112
+ next = "working";
113
+ else if (seen.state === "blocked")
114
+ next = "blocked";
115
+ else if (seen.completed)
116
+ next = question ? "needs-you" : "done";
117
+ else
118
+ next = sawWorking || now - Date.parse(receipt.createdAt) > IDLE_GRACE_MS ? "done" : "working";
119
+ const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : undefined;
120
+ const previous = receipt.worker?.state;
121
+ // The same finished state with a different final reply is a new turn: the
122
+ // worker took more work (a hand_off) and finished again between two polls.
123
+ const repeated = previous === next && !(turn && receipt.returned?.turn && turn !== receipt.returned.turn);
124
+ if (repeated) {
125
+ if (receipt.worker && receipt.worker.sawWorking !== sawWorking) {
126
+ receipt.worker.sawWorking = sawWorking;
127
+ changed = true;
128
+ }
129
+ return changed;
130
+ }
131
+ receipt.worker = { state: next, since: at, checkedAt: at, sawWorking };
132
+ if (next !== "working") {
133
+ receipt.returned = { state: next, at, read: false,
134
+ ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
135
+ ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
136
+ }
137
+ return true;
138
+ }
139
+ /** One line for the dispatching agent: who returned, how, and where to read it. */
140
+ export function noticeLine(receipts) {
141
+ const clean = (value, max) => value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
142
+ const word = { "done": "done", "needs-you": "needs you", "blocked": "blocked", "gone": "gone" };
143
+ const describe = (receipt, room) => {
144
+ const returned = receipt.returned;
145
+ const detail = returned.state === "needs-you" ? returned.question
146
+ : returned.state === "done" ? returned.reply?.split("\n").find(line => line.trim()) : undefined;
147
+ const excerpt = detail ? clean(detail.replace(/[*_`#>]+/g, ""), room) : "";
148
+ return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
149
+ };
150
+ if (receipts.length === 1)
151
+ return `Return: ${describe(receipts[0], 100)} (dispatch ${receipts[0].id}). Call dispatch_returns.`;
152
+ const items = receipts.slice(0, 4).map(receipt => describe(receipt, 40)).join("; ");
153
+ return `Returns: ${receipts.length} dispatches (${items}${receipts.length > 4 ? "; more" : ""}). Call dispatch_returns.`;
154
+ }
155
+ /** What `dispatch_returns` lists for one unread return. */
156
+ export function returnRow(receipt) {
157
+ const returned = receipt.returned;
158
+ return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
159
+ state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
160
+ ...(returned.truncated ? { truncated: true } : {}), ...(returned.question ? { question: returned.question } : {}),
161
+ ...(receipt.target ? { target: receipt.target } : {}) };
162
+ }
163
+ const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
164
+ /** Dispatching side: follows open dispatches and delivers their returns. */
165
+ export class DispatchReturns {
166
+ peers;
167
+ request;
168
+ localWorkers;
169
+ isLocal;
170
+ snapshot;
171
+ identity;
172
+ deliver;
173
+ now;
174
+ lastPoll = -Infinity;
175
+ lastNotice = new Map();
176
+ running;
177
+ constructor(options = {}) {
178
+ this.peers = options.peers ?? hookPeers;
179
+ this.request = options.request ?? peerRequest;
180
+ this.localWorkers = options.localWorkers ?? (input => workerStates(input));
181
+ this.isLocal = options.isLocal ?? (computer => isLocalComputer(computer));
182
+ this.snapshot = options.snapshot ?? (server => sharedSnapshot(server, SNAPSHOT_AGE_MS));
183
+ this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
184
+ this.deliver = options.deliver ?? ((target, text) => handOff({ target, text }));
185
+ this.now = options.now ?? Date.now;
186
+ }
187
+ /** Called from the Hook's activity tick; polls and notifies at most every POLL_MS. */
188
+ tick() {
189
+ if (this.running || this.now() - this.lastPoll < POLL_MS)
190
+ return this.running ?? Promise.resolve();
191
+ this.lastPoll = this.now();
192
+ this.running = (async () => { await this.poll(); await this.notify(); })().catch(() => { }).finally(() => { this.running = undefined; });
193
+ return this.running;
194
+ }
195
+ /** Ask each peer, once, about every open dispatch placed on it. */
196
+ async poll() {
197
+ const now = this.now();
198
+ const open = (await dispatchStatus()).filter(receipt => (receipt.state === "accepted" || receipt.state === "uncertain")
199
+ && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
200
+ if (!open.length)
201
+ return;
202
+ const peers = await this.peers().catch(() => []);
203
+ const byComputer = new Map();
204
+ for (const receipt of open)
205
+ byComputer.set(receipt.computer, [...byComputer.get(receipt.computer) ?? [], receipt]);
206
+ await Promise.all([...byComputer].map(async ([computer, receipts]) => {
207
+ // A dispatch placed on this computer is read here, without SSH.
208
+ const peer = peers.find(candidate => candidate.name === computer);
209
+ const local = !peer && this.isLocal(computer);
210
+ if (!peer && !local)
211
+ return;
212
+ for (let start = 0; start < receipts.length; start += 64) {
213
+ const batch = receipts.slice(start, start + 64);
214
+ const input = { targets: batch.map(receipt => receipt.target) };
215
+ // An unreachable peer records nothing: silence is not a transition.
216
+ const answer = await (peer ? this.request(peer, "/v1/dispatch/workers", input) : this.localWorkers(input)).catch(() => undefined);
217
+ const workers = objects(answer?.workers);
218
+ if (workers.length !== batch.length)
219
+ continue;
220
+ for (const [index, receipt] of batch.entries()) {
221
+ await updateReceipt(receipt.id, current => observe(current, workers[index], this.now())).catch(() => undefined);
222
+ }
223
+ }
224
+ }));
225
+ }
226
+ /** Type one line into each idle dispatching agent that has returns it was not told about. */
227
+ async notify() {
228
+ const waiting = (await dispatchStatus()).filter(receipt => receipt.origin && receipt.returned && !receipt.returned.read && !receipt.returned.notifiedAt);
229
+ const byOrigin = new Map();
230
+ for (const receipt of waiting)
231
+ byOrigin.set(originKey(receipt.origin), [...byOrigin.get(originKey(receipt.origin)) ?? [], receipt]);
232
+ for (const [key, receipts] of byOrigin) {
233
+ if (this.now() - (this.lastNotice.get(key) ?? -Infinity) < NOTICE_MS)
234
+ continue;
235
+ const origin = receipts[0].origin;
236
+ const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
237
+ // Never interrupt: only an agent that has stopped, in the same terminal, gets a notice.
238
+ if (!pane || pane.terminal_id !== origin.terminal || !["idle", "done"].includes(String(pane.agent_status)))
239
+ continue;
240
+ const session = await this.identity(origin.server, pane).catch(() => undefined);
241
+ const target = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
242
+ if (!target.success)
243
+ continue;
244
+ this.lastNotice.set(key, this.now());
245
+ const sent = await this.deliver(target.data, noticeLine(receipts)).catch(() => ({ delivered: false }));
246
+ if (!sent.delivered)
247
+ continue;
248
+ const at = new Date(this.now()).toISOString();
249
+ for (const receipt of receipts) {
250
+ await updateReceipt(receipt.id, current => {
251
+ if (!current.returned || current.returned.read || current.returned.at !== receipt.returned.at)
252
+ return false;
253
+ current.returned.notifiedAt = at;
254
+ return true;
255
+ }).catch(() => undefined);
256
+ }
257
+ }
258
+ }
259
+ /** Every unread return, oldest first, marked read as it is handed over. */
260
+ async take() {
261
+ const unread = (await dispatchStatus()).filter(receipt => receipt.returned && !receipt.returned.read)
262
+ .sort((a, b) => a.returned.at.localeCompare(b.returned.at));
263
+ const rows = [];
264
+ for (const receipt of unread) {
265
+ let marked = false;
266
+ const current = await updateReceipt(receipt.id, value => {
267
+ if (!value.returned || value.returned.read)
268
+ return false;
269
+ value.returned.read = true;
270
+ marked = true;
271
+ return true;
272
+ }).catch(() => undefined);
273
+ // A concurrent take already handed this one over.
274
+ if (marked && current?.returned)
275
+ rows.push(returnRow(current));
276
+ }
277
+ return rows;
278
+ }
279
+ }
@@ -0,0 +1,54 @@
1
+ import { z } from "zod";
2
+ import { type Target } from "./protocol.js";
3
+ import type { ChildAgentRelation } from "./transcripts.js";
4
+ export declare const dispatchParentSchema: z.ZodObject<{
5
+ provider: z.ZodEnum<{
6
+ claude: "claude";
7
+ codex: "codex";
8
+ copilot: "copilot";
9
+ opencode: "opencode";
10
+ phren: "phren";
11
+ }>;
12
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
13
+ computer: z.ZodString;
14
+ }, z.core.$strict>;
15
+ export type DispatchParent = z.infer<typeof dispatchParentSchema>;
16
+ export interface DispatchParentInput {
17
+ parent?: unknown;
18
+ parentTarget?: unknown;
19
+ }
20
+ /** Parent metadata is optional as a pair. When present it must name this Hook
21
+ * and the exact live conversation target the caller supplied. */
22
+ export declare function validateDispatchParent(input: DispatchParentInput, localComputer: string, validateTarget: (target: Target) => Promise<unknown>): Promise<{
23
+ parent?: DispatchParent;
24
+ parentTarget?: Target;
25
+ }>;
26
+ export interface DispatchTreeReceipt {
27
+ readonly id: string;
28
+ readonly computer: string;
29
+ readonly computerId?: string;
30
+ readonly remoteComputer?: unknown;
31
+ readonly label: string;
32
+ readonly model?: string;
33
+ readonly state: string;
34
+ readonly target?: unknown;
35
+ readonly parent?: unknown;
36
+ readonly parentTarget?: unknown;
37
+ readonly status?: string;
38
+ readonly completedAt?: string;
39
+ }
40
+ export interface RemoteDispatchSnapshot {
41
+ readonly dispatchId?: string;
42
+ readonly available?: boolean;
43
+ readonly state?: "running" | "completed" | "unavailable";
44
+ readonly target?: unknown;
45
+ readonly computer?: unknown;
46
+ readonly agents?: readonly unknown[];
47
+ readonly children?: readonly unknown[];
48
+ }
49
+ export type RemoteSnapshotReader = (receipt: DispatchTreeReceipt) => RemoteDispatchSnapshot | undefined | Promise<RemoteDispatchSnapshot | undefined>;
50
+ export type RemoteSnapshotSource = RemoteSnapshotReader | ReadonlyMap<string, RemoteDispatchSnapshot | undefined> | Readonly<Record<string, RemoteDispatchSnapshot | undefined>> | readonly RemoteDispatchSnapshot[] | RemoteDispatchSnapshot | undefined;
51
+ /** Project this conductor's durable outbound receipts into remote work-tree
52
+ * rows. Snapshot readers are GET-only adapters; missing or rejected snapshots
53
+ * keep the lead visible as unavailable. */
54
+ export declare function remoteChildren(parentValue: DispatchParent, receipts: readonly DispatchTreeReceipt[], remoteSnapshot: RemoteSnapshotSource): Promise<ChildAgentRelation[]>;
@@ -0,0 +1,198 @@
1
+ import { createHash } from "node:crypto";
2
+ import { z } from "zod";
3
+ import { computerName } from "./computers.js";
4
+ import { BridgeError, object, provider, sessionId, targetSchema } from "./protocol.js";
5
+ const computerID = z.string().uuid();
6
+ const dispatchID = z.string().uuid();
7
+ const childID = z.string().regex(/^[a-f0-9]{32}$/);
8
+ export const dispatchParentSchema = z.object({
9
+ provider,
10
+ session: sessionId,
11
+ computer: computerID,
12
+ }).strict();
13
+ /** Parent metadata is optional as a pair. When present it must name this Hook
14
+ * and the exact live conversation target the caller supplied. */
15
+ export async function validateDispatchParent(input, localComputer, validateTarget) {
16
+ const hasParent = input.parent !== undefined, hasTarget = input.parentTarget !== undefined;
17
+ if (hasParent !== hasTarget)
18
+ throw new BridgeError(400, "Supply both parent and parentTarget, or omit both.");
19
+ if (!hasParent)
20
+ return {};
21
+ const parent = dispatchParentSchema.parse(input.parent);
22
+ const parentTarget = targetSchema.parse(input.parentTarget);
23
+ if (parent.computer !== computerID.parse(localComputer))
24
+ throw new BridgeError(403, "The dispatch parent belongs to a different computer.");
25
+ if (parent.provider !== parentTarget.source || parent.session !== parentTarget.session) {
26
+ throw new BridgeError(400, "The dispatch parent does not match parentTarget.");
27
+ }
28
+ await validateTarget(parentTarget);
29
+ return { parent, parentTarget };
30
+ }
31
+ const sameTarget = (left, right) => left.server === right.server && left.workspace === right.workspace && left.tab === right.tab
32
+ && left.pane === right.pane && left.source === right.source && left.session === right.session;
33
+ function publicID(parent, computer, dispatch, descendant) {
34
+ return createHash("sha256").update(`${parent.provider}\0${parent.session}\0${computer}\0${dispatch}\0${descendant}`)
35
+ .digest("hex").slice(0, 32);
36
+ }
37
+ function publicLabel(value) {
38
+ if (typeof value !== "string" || value.length === 0 || value.length > 512)
39
+ return;
40
+ return /^(?:[/\\]|[A-Za-z]:[/\\]|~[/\\])/.test(value) ? "Agent" : value;
41
+ }
42
+ function sameParent(value, parent) {
43
+ const parsed = dispatchParentSchema.safeParse(value);
44
+ return parsed.success && parsed.data.provider === parent.provider && parsed.data.session === parent.session
45
+ && parsed.data.computer === parent.computer;
46
+ }
47
+ function parentTargetMatches(value, parent) {
48
+ const parsed = targetSchema.safeParse(value);
49
+ return parsed.success && parsed.data.source === parent.provider && parsed.data.session === parent.session;
50
+ }
51
+ function directSnapshot(source) {
52
+ if (!source || typeof source !== "object" || Array.isArray(source) || source instanceof Map)
53
+ return;
54
+ const value = source;
55
+ return value.available !== undefined || value.state !== undefined || value.target !== undefined
56
+ || value.computer !== undefined || value.agents !== undefined || value.children !== undefined ? value : undefined;
57
+ }
58
+ async function snapshotFor(source, receipt) {
59
+ try {
60
+ if (source === undefined)
61
+ return;
62
+ if (typeof source === "function")
63
+ return await source(receipt);
64
+ if (source instanceof Map)
65
+ return source.get(receipt.id);
66
+ if (Array.isArray(source))
67
+ return source.find(item => item.dispatchId === receipt.id);
68
+ const direct = directSnapshot(source);
69
+ if (direct)
70
+ return direct;
71
+ return Object.prototype.hasOwnProperty.call(source, receipt.id)
72
+ ? source[receipt.id] : undefined;
73
+ }
74
+ catch {
75
+ return;
76
+ }
77
+ }
78
+ function snapshotMatches(snapshot, target, computer) {
79
+ if (snapshot.target !== undefined) {
80
+ const parsed = targetSchema.safeParse(snapshot.target);
81
+ if (!parsed.success || !sameTarget(parsed.data, target))
82
+ return false;
83
+ }
84
+ if (snapshot.computer !== undefined) {
85
+ const parsed = z.object({ id: computerID, name: computerName }).strict().safeParse(snapshot.computer);
86
+ if (!parsed.success || parsed.data.id !== computer.id)
87
+ return false;
88
+ }
89
+ return true;
90
+ }
91
+ function destination(raw, fallbackComputer, fallbackTarget) {
92
+ const suppliedComputer = raw.computer !== undefined, suppliedRemote = raw.remote !== undefined;
93
+ if (!suppliedComputer && !suppliedRemote) {
94
+ const id = childID.safeParse(raw.id);
95
+ return id.success ? { computer: fallbackComputer, remote: { target: fallbackTarget, child: id.data } } : undefined;
96
+ }
97
+ if (!suppliedComputer || !suppliedRemote)
98
+ return;
99
+ const computer = z.object({ id: computerID, name: computerName }).strict().safeParse(raw.computer);
100
+ const remoteRaw = object(raw.remote), target = targetSchema.safeParse(remoteRaw.target);
101
+ const child = remoteRaw.child === undefined ? undefined : childID.safeParse(remoteRaw.child);
102
+ if (!computer.success || !target.success || (child !== undefined && !child.success))
103
+ return;
104
+ return { computer: computer.data, remote: { target: target.data, ...(child?.success ? { child: child.data } : {}) } };
105
+ }
106
+ function projectAgents(values, parent, receipt, fallbackComputer, fallbackTarget, depth, state, lineage = "") {
107
+ if (depth > 4 || state.count >= 128)
108
+ return [];
109
+ const projected = [];
110
+ for (const value of values.slice(0, 128)) {
111
+ if (state.count >= 128)
112
+ break;
113
+ const raw = object(value), id = childID.safeParse(raw.id), source = provider.safeParse(raw.provider);
114
+ const path = publicLabel(raw.path);
115
+ const callId = typeof raw.callId === "string" && raw.callId.length > 0 && raw.callId.length <= 200 ? raw.callId : undefined;
116
+ const routed = destination(raw, fallbackComputer, fallbackTarget);
117
+ if (!id.success || !source.success || !path || !callId || !routed)
118
+ continue;
119
+ const descendant = lineage ? `${lineage}/${id.data}` : id.data;
120
+ const nestedSession = sessionId.safeParse(raw.session);
121
+ const cycleIdentity = nestedSession.success ? nestedSession.data
122
+ : routed.remote.child ?? routed.remote.target.session;
123
+ const cycleKey = `${routed.computer.id}\0${source.data}\0${cycleIdentity}`;
124
+ if (state.seen.has(cycleKey))
125
+ continue;
126
+ state.seen.add(cycleKey);
127
+ state.count++;
128
+ const childState = ["running", "completed", "failed", "unavailable"].includes(String(raw.state))
129
+ ? raw.state : "unavailable";
130
+ const children = Array.isArray(raw.children)
131
+ ? projectAgents(raw.children, parent, receipt, fallbackComputer, fallbackTarget, depth + 1, state, descendant) : [];
132
+ projected.push({
133
+ id: publicID(parent, routed.computer.id, receipt.id, descendant),
134
+ provider: source.data,
135
+ path,
136
+ callId,
137
+ state: raw.failed === true ? "failed" : childState,
138
+ ...(typeof raw.finishedAt === "string" && Number.isFinite(Date.parse(raw.finishedAt)) ? { finishedAt: raw.finishedAt } : {}),
139
+ ...(typeof raw.reason === "string" && raw.reason.length > 0 && raw.reason.length <= 500 ? { reason: raw.reason } : {}),
140
+ ...(typeof raw.model === "string" && raw.model.length > 0 && raw.model.length <= 200 ? { model: raw.model } : {}),
141
+ ...(typeof raw.worktreeName === "string" && raw.worktreeName.length > 0 && raw.worktreeName.length <= 200
142
+ && !/[/\\]/.test(raw.worktreeName) ? { worktreeName: raw.worktreeName } : {}),
143
+ ...(typeof raw.branch === "string" && raw.branch.length > 0 && raw.branch.length <= 200 ? { branch: raw.branch } : {}),
144
+ ...(typeof object(raw.fanout).resumable === "boolean" ? { fanout: { resumable: object(raw.fanout).resumable } } : {}),
145
+ computer: routed.computer,
146
+ remote: routed.remote,
147
+ children,
148
+ });
149
+ }
150
+ return projected;
151
+ }
152
+ /** Project this conductor's durable outbound receipts into remote work-tree
153
+ * rows. Snapshot readers are GET-only adapters; missing or rejected snapshots
154
+ * keep the lead visible as unavailable. */
155
+ export async function remoteChildren(parentValue, receipts, remoteSnapshot) {
156
+ const parent = dispatchParentSchema.parse(parentValue);
157
+ const state = {
158
+ count: 0,
159
+ seen: new Set([`${parent.computer}\0${parent.provider}\0${parent.session}`]),
160
+ };
161
+ const children = [];
162
+ for (const receipt of receipts) {
163
+ if (state.count >= 128 || receipt.state === "failed" || !dispatchID.safeParse(receipt.id).success
164
+ || !sameParent(receipt.parent, parent) || !parentTargetMatches(receipt.parentTarget, parent))
165
+ continue;
166
+ const storedComputer = z.object({ id: computerID, name: computerName }).strict().safeParse(receipt.remoteComputer);
167
+ const target = targetSchema.safeParse(receipt.target);
168
+ const id = computerID.safeParse(receipt.computerId ?? (storedComputer.success ? storedComputer.data.id : undefined));
169
+ const name = computerName.safeParse(storedComputer.success ? storedComputer.data.name : receipt.computer);
170
+ if (!target.success || !id.success || !name.success)
171
+ continue;
172
+ const cycleKey = `${id.data}\0${target.data.source}\0${target.data.session}`;
173
+ if (state.seen.has(cycleKey))
174
+ continue;
175
+ state.seen.add(cycleKey);
176
+ state.count++;
177
+ const computer = { id: id.data, name: name.data };
178
+ const snapshot = await snapshotFor(remoteSnapshot, receipt);
179
+ const available = snapshot !== undefined && snapshot.available !== false && snapshotMatches(snapshot, target.data, computer);
180
+ const completed = receipt.state === "completed" || receipt.status === "completed" || receipt.completedAt !== undefined
181
+ || snapshot?.state === "completed";
182
+ const snapshotAgents = snapshot?.agents ?? snapshot?.children;
183
+ const projected = available && Array.isArray(snapshotAgents)
184
+ ? projectAgents(snapshotAgents, parent, receipt, computer, target.data, 2, state) : [];
185
+ children.push({
186
+ id: publicID(parent, computer.id, receipt.id, "lead"),
187
+ provider: target.data.source,
188
+ path: receipt.label.slice(0, 200),
189
+ callId: `dispatch:${receipt.id}`,
190
+ state: completed ? "completed" : available ? "running" : "unavailable",
191
+ ...(receipt.model !== undefined ? { model: receipt.model.slice(0, 200) } : {}),
192
+ computer,
193
+ remote: { target: target.data },
194
+ children: projected,
195
+ });
196
+ }
197
+ return children;
198
+ }