@phren/cli 0.2.15 → 0.3.0

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 (392) 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 +195 -2
  7. package/dist/bridge/agent-hooks.js +1049 -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 +23 -0
  15. package/dist/bridge/code-note.js +51 -0
  16. package/dist/bridge/code-routes.d.ts +151 -0
  17. package/dist/bridge/code-routes.js +442 -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 +125 -0
  33. package/dist/bridge/dispatch-returns.js +283 -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 +210 -0
  37. package/dist/bridge/dispatch.js +286 -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 +28 -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 +61 -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 +54 -0
  96. package/dist/bridge/schedule-watch.js +255 -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 +36 -0
  104. package/dist/bridge/server-pane-routes.js +479 -0
  105. package/dist/bridge/server-routes.d.ts +108 -0
  106. package/dist/bridge/server-routes.js +556 -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 +96 -0
  136. package/dist/bridge/transcript-preview.js +491 -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 +46545 -21051
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-policy.js +25 -0
  148. package/dist/cli/config-proactivity.d.ts +3 -1
  149. package/dist/cli/config-proactivity.js +35 -3
  150. package/dist/cli/config.js +4 -1
  151. package/dist/cli/extract.d.ts +0 -8
  152. package/dist/cli/extract.js +4 -7
  153. package/dist/cli/govern.js +5 -2
  154. package/dist/cli/hooks-globs.js +1 -1
  155. package/dist/cli/hooks.d.ts +1 -1
  156. package/dist/cli/hooks.js +9 -7
  157. package/dist/cli/namespaces-projects.js +12 -6
  158. package/dist/cli/namespaces-store.js +37 -6
  159. package/dist/cli/namespaces-tasks.js +1 -1
  160. package/dist/cli/schedules.d.ts +1 -0
  161. package/dist/cli/schedules.js +164 -0
  162. package/dist/cli/session-background.js +1 -1
  163. package/dist/cli/session-git.d.ts +8 -5
  164. package/dist/cli/session-git.js +45 -120
  165. package/dist/cli/session-start.js +3 -1
  166. package/dist/cli/session-stop.js +19 -8
  167. package/dist/cli/team.js +13 -10
  168. package/dist/cli-handlers.d.ts +1 -1
  169. package/dist/cli-handlers.js +8 -4
  170. package/dist/cli-help.d.ts +5 -4
  171. package/dist/cli-help.js +15 -15
  172. package/dist/cli-registry.d.ts +4 -1
  173. package/dist/cli-registry.js +119 -6
  174. package/dist/content/archive.js +2 -2
  175. package/dist/content/citation.d.ts +11 -0
  176. package/dist/content/citation.js +18 -0
  177. package/dist/content/learning.js +2 -0
  178. package/dist/content/summarize.d.ts +14 -15
  179. package/dist/content/summarize.js +60 -5
  180. package/dist/content/validate.d.ts +17 -4
  181. package/dist/content/validate.js +200 -122
  182. package/dist/core/project-registry.d.ts +26 -0
  183. package/dist/core/project-registry.js +573 -0
  184. package/dist/core/project.js +2 -3
  185. package/dist/data/access.d.ts +16 -1
  186. package/dist/data/access.js +31 -3
  187. package/dist/data/tasks.d.ts +18 -3
  188. package/dist/data/tasks.js +8 -7
  189. package/dist/entrypoint.js +44 -10
  190. package/dist/fanout/adapters/claude.d.ts +2 -0
  191. package/dist/fanout/adapters/claude.js +7 -0
  192. package/dist/fanout/adapters/codex.d.ts +2 -0
  193. package/dist/fanout/adapters/codex.js +9 -0
  194. package/dist/fanout/adapters/opencode.d.ts +4 -0
  195. package/dist/fanout/adapters/opencode.js +9 -0
  196. package/dist/fanout/adapters/types.d.ts +21 -0
  197. package/dist/fanout/adapters/types.js +3 -0
  198. package/dist/fanout/command.d.ts +2 -0
  199. package/dist/fanout/command.js +78 -0
  200. package/dist/fanout/launcher.d.ts +27 -0
  201. package/dist/fanout/launcher.js +156 -0
  202. package/dist/fanout/opencode-serve.d.ts +24 -0
  203. package/dist/fanout/opencode-serve.js +191 -0
  204. package/dist/fanout/picker.d.ts +91 -0
  205. package/dist/fanout/picker.js +51 -0
  206. package/dist/fanout/usage.d.ts +5 -0
  207. package/dist/fanout/usage.js +51 -0
  208. package/dist/fanout/watchdog.d.ts +10 -0
  209. package/dist/fanout/watchdog.js +27 -0
  210. package/dist/filenames.d.ts +9 -0
  211. package/dist/filenames.js +11 -0
  212. package/dist/finding/context.js +4 -22
  213. package/dist/generated/memory-ui-graph.browser.js +525 -419
  214. package/dist/governance/policy-constants.d.ts +11 -0
  215. package/dist/governance/policy-constants.js +9 -0
  216. package/dist/governance/policy.d.ts +5 -8
  217. package/dist/governance/policy.js +11 -8
  218. package/dist/graph-core/camera.d.ts +24 -0
  219. package/dist/graph-core/camera.js +18 -0
  220. package/dist/graph-core/index.d.ts +2 -0
  221. package/dist/graph-core/index.js +2 -0
  222. package/dist/graph-core/labels.d.ts +77 -0
  223. package/dist/graph-core/labels.js +124 -0
  224. package/dist/graph-core/model.d.ts +13 -0
  225. package/dist/graph-core/model.js +33 -0
  226. package/dist/graph-core/types.d.ts +2 -0
  227. package/dist/home-paths.d.ts +7 -0
  228. package/dist/home-paths.js +21 -0
  229. package/dist/hooks.d.ts +3 -15
  230. package/dist/hooks.js +14 -1
  231. package/dist/index.js +24 -2
  232. package/dist/init/guard-globals.d.ts +1 -1
  233. package/dist/init/guard-globals.js +4 -4
  234. package/dist/init/init-configure.js +3 -3
  235. package/dist/init/init-uninstall.js +15 -5
  236. package/dist/init/init-walkthrough.js +1 -1
  237. package/dist/init/init.js +26 -6
  238. package/dist/init/management-preset.d.ts +1 -1
  239. package/dist/init/management-preset.js +2 -2
  240. package/dist/init/preferences.js +1 -1
  241. package/dist/init/self-wiring.js +1 -1
  242. package/dist/init/setup.d.ts +3 -26
  243. package/dist/init/setup.js +68 -593
  244. package/dist/init/shared.js +2 -0
  245. package/dist/init/store-gitignore.d.ts +1 -6
  246. package/dist/init/store-gitignore.js +2 -8
  247. package/dist/init/teardown.d.ts +1 -1
  248. package/dist/init/teardown.js +2 -2
  249. package/dist/link/context-imports.d.ts +15 -0
  250. package/dist/link/context-imports.js +101 -0
  251. package/dist/link/context.js +1 -1
  252. package/dist/link/doctor.d.ts +22 -1
  253. package/dist/link/doctor.js +128 -58
  254. package/dist/link/link.js +29 -61
  255. package/dist/link/refresh.js +2 -2
  256. package/dist/link/skills.js +26 -5
  257. package/dist/machine-identity.d.ts +3 -0
  258. package/dist/machine-identity.js +6 -0
  259. package/dist/mcp/profile.d.ts +2 -19
  260. package/dist/mcp/profile.js +64 -22
  261. package/dist/memory-ui-graph.runtime.js +525 -419
  262. package/dist/modules/code-package.d.ts +16 -0
  263. package/dist/modules/code-package.js +160 -0
  264. package/dist/modules/command.d.ts +2 -0
  265. package/dist/modules/command.js +67 -0
  266. package/dist/modules/config.d.ts +4 -0
  267. package/dist/modules/config.js +70 -0
  268. package/dist/modules/manifest.d.ts +41 -0
  269. package/dist/modules/manifest.js +1 -0
  270. package/dist/modules/provision.d.ts +3 -0
  271. package/dist/modules/provision.js +84 -0
  272. package/dist/modules/registry.d.ts +16 -0
  273. package/dist/modules/registry.js +250 -0
  274. package/dist/modules/runtime.d.ts +15 -0
  275. package/dist/modules/runtime.js +59 -0
  276. package/dist/package-metadata.js +10 -2
  277. package/dist/phren-dotenv.js +4 -2
  278. package/dist/phren-paths.d.ts +3 -2
  279. package/dist/phren-paths.js +4 -5
  280. package/dist/profile-store.js +43 -8
  281. package/dist/project-config.d.ts +19 -1
  282. package/dist/project-config.js +29 -3
  283. package/dist/project-topics.d.ts +1 -0
  284. package/dist/project-topics.js +13 -10
  285. package/dist/provider-adapters.js +1 -4
  286. package/dist/query-correlation.js +6 -6
  287. package/dist/session/artifacts.js +5 -5
  288. package/dist/session/checkpoints.js +5 -0
  289. package/dist/session/utils.d.ts +2 -2
  290. package/dist/session/utils.js +6 -6
  291. package/dist/shared/content.d.ts +1 -1
  292. package/dist/shared/content.js +1 -1
  293. package/dist/shared/data-utils.js +1 -1
  294. package/dist/shared/fragment-graph.d.ts +1 -1
  295. package/dist/shared/fragment-graph.js +5 -5
  296. package/dist/shared/index.js +48 -7
  297. package/dist/shared/retrieval.d.ts +18 -3
  298. package/dist/shared/retrieval.js +101 -12
  299. package/dist/shared/search-fallback.js +4 -6
  300. package/dist/shared/sqljs.d.ts +2 -0
  301. package/dist/shared/sqljs.js +4 -2
  302. package/dist/shared.d.ts +0 -1
  303. package/dist/shared.js +0 -1
  304. package/dist/shell/input.d.ts +1 -5
  305. package/dist/shell/input.js +16 -10
  306. package/dist/shell/palette.d.ts +2 -2
  307. package/dist/shell/palette.js +3 -7
  308. package/dist/shell/render.d.ts +3 -1
  309. package/dist/shell/render.js +4 -4
  310. package/dist/shell/shell.js +4 -1
  311. package/dist/shell/types.d.ts +1 -0
  312. package/dist/shell/types.js +4 -0
  313. package/dist/shell/view.d.ts +0 -4
  314. package/dist/shell/view.js +19 -27
  315. package/dist/skill/registry.js +25 -17
  316. package/dist/skill/state.d.ts +3 -0
  317. package/dist/skill/state.js +13 -7
  318. package/dist/status.js +38 -17
  319. package/dist/store-registry.d.ts +44 -18
  320. package/dist/store-registry.js +169 -60
  321. package/dist/store-weight.d.ts +1 -6
  322. package/dist/store-weight.js +4 -2
  323. package/dist/sync/auth-doctor.d.ts +8 -0
  324. package/dist/sync/auth-doctor.js +27 -0
  325. package/dist/sync/auth.d.ts +27 -0
  326. package/dist/sync/auth.js +114 -0
  327. package/dist/sync/conflict-resolve.d.ts +9 -0
  328. package/dist/sync/conflict-resolve.js +146 -0
  329. package/dist/sync/git-state.d.ts +4 -0
  330. package/dist/sync/git-state.js +49 -0
  331. package/dist/sync/outcome.d.ts +34 -0
  332. package/dist/sync/outcome.js +57 -0
  333. package/dist/sync/pull.d.ts +15 -7
  334. package/dist/sync/pull.js +84 -35
  335. package/dist/sync/store-merge.d.ts +29 -0
  336. package/dist/sync/store-merge.js +137 -0
  337. package/dist/sync/task-merge.d.ts +22 -0
  338. package/dist/sync/task-merge.js +158 -0
  339. package/dist/task/github.js +1 -1
  340. package/dist/task/lifecycle.d.ts +5 -0
  341. package/dist/task/lifecycle.js +67 -23
  342. package/dist/terminal-text.d.ts +5 -0
  343. package/dist/terminal-text.js +11 -0
  344. package/dist/test-global-setup.js +7 -0
  345. package/dist/tool-registry.d.ts +1 -1
  346. package/dist/tool-registry.js +3 -1
  347. package/dist/tools/code.d.ts +3 -0
  348. package/dist/tools/code.js +186 -0
  349. package/dist/tools/config.js +8 -0
  350. package/dist/tools/data.js +14 -7
  351. package/dist/tools/dispatch.d.ts +2 -0
  352. package/dist/tools/dispatch.js +66 -0
  353. package/dist/tools/finding.d.ts +11 -0
  354. package/dist/tools/finding.js +180 -123
  355. package/dist/tools/ops.js +5 -2
  356. package/dist/tools/search.js +21 -8
  357. package/dist/tools/session.js +21 -22
  358. package/dist/tools/tasks.js +8 -2
  359. package/dist/tools/types.d.ts +2 -2
  360. package/dist/tools/types.js +2 -2
  361. package/dist/ui/assets.js +1 -1
  362. package/dist/ui/data.js +14 -15
  363. package/dist/ui/deep-void.d.ts +1 -1
  364. package/dist/ui/deep-void.js +0 -1
  365. package/dist/ui/graph-chrome.d.ts +1 -1
  366. package/dist/ui/graph-chrome.js +51 -0
  367. package/dist/ui/page.js +5 -5
  368. package/dist/ui/scripts.js +67 -30
  369. package/dist/ui/server.js +52 -7
  370. package/dist/update.js +22 -11
  371. package/dist/utils-fts.js +1 -0
  372. package/dist/utils-helpers.d.ts +7 -0
  373. package/dist/utils-helpers.js +17 -0
  374. package/dist/utils.d.ts +1 -1
  375. package/dist/utils.js +1 -1
  376. package/package.json +49 -7
  377. package/plugins/opencode/phren-transcript.js +340 -0
  378. package/starter/README.md +4 -4
  379. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  380. package/starter/global/skills/conductor/SKILL.md +106 -0
  381. package/starter/global/skills/fanout/SKILL.md +20 -0
  382. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  383. package/starter/global/skills/phren-init/SKILL.md +4 -4
  384. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  385. package/starter/templates/frontend/reference/README.md +1 -1
  386. package/starter/templates/library/reference/README.md +1 -1
  387. package/starter/templates/monorepo/reference/README.md +1 -1
  388. package/starter/templates/python-project/reference/README.md +1 -1
  389. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  390. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  391. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  392. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,702 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash } from "node:crypto";
3
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
4
+ import { homedir } from "node:os";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+ import { z } from "zod";
8
+ import { object, sessionId } from "./protocol.js";
9
+ import { countGit } from "./metrics.js";
10
+ import { readOpencodeRequest } from "./opencode-approvals.js";
11
+ const MAX_MANIFEST_BYTES = 64 * 1024;
12
+ const MAX_EVENT_LOG_BYTES = 64 * 1024 * 1024;
13
+ const MAX_BLOCKED_BYTES = 16 * 1024;
14
+ const MAX_JOBS = 128;
15
+ /** A finished job is archived once its finish stamp is older than this. */
16
+ const ARCHIVE_AGE_MS = 24 * 60 * 60 * 1000;
17
+ /** How many folders the archive keeps; the oldest beyond that are deleted. */
18
+ export const ARCHIVE_MAX_FOLDERS = 500;
19
+ const ARCHIVED_STATUSES = new Set(["completed", "failed", "cancelled"]);
20
+ const WORKTREE_CACHE_MS = 15_000;
21
+ const exec = promisify(execFile);
22
+ const jobID = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/);
23
+ const timestamp = z.string().datetime({ offset: true });
24
+ const opencodeSession = z.string().regex(/^ses_[0-9A-Za-z]{1,64}$/);
25
+ export const manifestSchema = z.object({
26
+ schemaVersion: z.literal(1),
27
+ id: jobID,
28
+ parent: z.object({
29
+ provider: z.enum(["codex", "claude", "copilot", "phren", "opencode"]),
30
+ session: sessionId,
31
+ computer: z.string().uuid().optional(),
32
+ }).strict().optional(),
33
+ provider: z.enum(["opencode", "codex", "claude"]),
34
+ session: sessionId.optional(),
35
+ taskLabel: z.string().min(1).max(200),
36
+ cwd: z.string().min(1).max(4096).refine(path.isAbsolute),
37
+ worktree: z.string().min(1).max(4096).refine(path.isAbsolute),
38
+ model: z.string().min(1).max(200).optional(),
39
+ eventLog: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.jsonl$/),
40
+ createdAt: timestamp,
41
+ startedAt: timestamp,
42
+ updatedAt: timestamp,
43
+ finishedAt: timestamp.optional(),
44
+ status: z.enum(["queued", "running", "completed", "failed", "cancelled"]),
45
+ exitCode: z.number().int().min(0).max(255).optional(),
46
+ reason: z.string().max(4000).optional(),
47
+ resumes: sessionId.optional(),
48
+ schedule: z.object({ id: z.string().regex(/^[a-f0-9]{8}$/), project: z.string().min(1).max(200) }).optional(),
49
+ }).strict().superRefine((manifest, ctx) => {
50
+ // OpenCode sessions are `ses_…`; Codex and Claude sessions are UUIDs.
51
+ // A provider cannot claim another provider's identity shape.
52
+ if (manifest.session === undefined)
53
+ return;
54
+ const valid = manifest.provider === "opencode" ? opencodeSession.safeParse(manifest.session).success
55
+ : z.string().uuid().safeParse(manifest.session).success;
56
+ if (!valid)
57
+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["session"],
58
+ message: `A ${manifest.provider} manifest needs a matching session identity.` });
59
+ });
60
+ /** What the opencode plugin writes when it refuses a fan-out worker's
61
+ * permission: the ask that was denied, so the Hook can report a worker that
62
+ * exited 0 as blocked rather than finished. */
63
+ const blockedSchema = z.object({
64
+ type: z.string().min(1).max(200),
65
+ pattern: z.string().max(2000).optional(),
66
+ message: z.string().max(4000).optional(),
67
+ at: z.string().max(100).optional(),
68
+ }).passthrough();
69
+ const worktreeCache = new Map();
70
+ async function worktreeDetails(worktree) {
71
+ const now = Date.now(), cached = worktreeCache.get(worktree);
72
+ if (cached && cached.expiresAt > now)
73
+ return cached.details;
74
+ let details = {};
75
+ const metadata = await stat(worktree).catch(() => undefined);
76
+ if (metadata?.isDirectory()) {
77
+ const worktreeName = path.basename(worktree).slice(0, 200);
78
+ details = worktreeName ? { worktreeName } : {};
79
+ try {
80
+ countGit("fanouts");
81
+ const { stdout } = await exec("git", ["-C", worktree, "rev-parse", "--abbrev-ref", "HEAD"], { timeout: 2_000, maxBuffer: 4_096 });
82
+ const branch = stdout.trim();
83
+ if (branch && branch !== "HEAD")
84
+ details.branch = branch.slice(0, 200);
85
+ }
86
+ catch { /* Missing repositories, detached heads, and git errors have no public branch. */ }
87
+ }
88
+ worktreeCache.set(worktree, { expiresAt: Date.now() + WORKTREE_CACHE_MS, details });
89
+ while (worktreeCache.size > MAX_JOBS)
90
+ worktreeCache.delete(worktreeCache.keys().next().value);
91
+ return details;
92
+ }
93
+ export function storeRoot(env) {
94
+ const configured = env.PHREN_PATH?.trim();
95
+ return !configured ? path.join(homedir(), ".phren")
96
+ : configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : path.resolve(configured);
97
+ }
98
+ export function fanoutRoot(env = process.env) {
99
+ return path.join(storeRoot(env), ".runtime", "agent-fanouts");
100
+ }
101
+ /** Bind public worker identities to the canonical store as well as their parent. */
102
+ export function fanoutChildID(root, manifest) {
103
+ return createHash("sha256").update(`${root}\0${manifest.parent?.provider}\0${manifest.parent?.session}\0${manifest.id}`).digest("hex").slice(0, 32);
104
+ }
105
+ export async function containedFanoutRoot(env) {
106
+ try {
107
+ const store = await realpath(storeRoot(env));
108
+ const expected = path.join(store, ".runtime", "agent-fanouts");
109
+ return await realpath(expected) === expected ? expected : undefined;
110
+ }
111
+ catch {
112
+ return undefined;
113
+ }
114
+ }
115
+ async function regularContainedFile(root, candidate, maxBytes) {
116
+ try {
117
+ const link = await lstat(candidate);
118
+ if (!link.isFile() || link.isSymbolicLink() || link.size > maxBytes)
119
+ return;
120
+ const resolved = await realpath(candidate);
121
+ if (!resolved.startsWith(root + path.sep))
122
+ return;
123
+ const metadata = await stat(resolved);
124
+ return metadata.isFile() && metadata.size <= maxBytes ? resolved : undefined;
125
+ }
126
+ catch {
127
+ return;
128
+ }
129
+ }
130
+ async function readBlocked(jobRoot) {
131
+ const file = await regularContainedFile(jobRoot, path.join(jobRoot, "blocked.json"), MAX_BLOCKED_BYTES);
132
+ if (file) {
133
+ try {
134
+ return blockedSchema.parse(JSON.parse(await readFile(file, "utf8")));
135
+ }
136
+ catch { /* fall through to stderr */ }
137
+ }
138
+ return readRefusedFromStderr(jobRoot);
139
+ }
140
+ /** OpenCode refuses some permissions itself in headless runs, before any
141
+ * plugin sees them, and only says so on stderr: `permission requested:
142
+ * <type> (<pattern>); auto-rejecting`. The launcher captures stderr into the
143
+ * job directory, so that line is the evidence when blocked.json is absent. */
144
+ const REFUSED_LINE = /permission requested: ([a-z_]+) \(([^)]*)\); auto-rejecting/g;
145
+ async function readRefusedFromStderr(jobRoot) {
146
+ const file = await regularContainedFile(jobRoot, path.join(jobRoot, "stderr.log"), 4 * 1024 * 1024);
147
+ if (!file)
148
+ return undefined;
149
+ try {
150
+ const handle = await open(file, "r");
151
+ let tail;
152
+ let at;
153
+ try {
154
+ const info = await handle.stat();
155
+ const buffer = Buffer.alloc(Math.min(info.size, 16_384));
156
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, Math.max(0, info.size - buffer.length));
157
+ tail = buffer.toString("utf8", 0, bytesRead);
158
+ at = info.mtime.toISOString();
159
+ }
160
+ finally {
161
+ await handle.close();
162
+ }
163
+ let last;
164
+ for (const match of tail.matchAll(REFUSED_LINE))
165
+ last = match;
166
+ if (!last)
167
+ return undefined;
168
+ return { type: last[1], pattern: last[2].slice(0, 500), message: `${last[1]}: ${last[2]}`.slice(0, 600), at };
169
+ }
170
+ catch {
171
+ return undefined;
172
+ }
173
+ }
174
+ function blockedReason(value) {
175
+ const pattern = typeof value.pattern === "string" ? value.pattern.trim() : "";
176
+ return (pattern ? `blocked: ${value.type} ${pattern}` : `blocked: ${value.type}`).slice(0, 500);
177
+ }
178
+ /** Read only manifests explicitly bound to the already validated parent. */
179
+ export async function fanoutChildren(parentProvider, parentSession, env = process.env, parentComputer) {
180
+ if (!sessionId.safeParse(parentSession).success)
181
+ return [];
182
+ const root = await containedFanoutRoot(env);
183
+ if (!root)
184
+ return [];
185
+ // Newest first, so a directory that outgrew MAX_JOBS drops old finished
186
+ // jobs rather than the workers running right now.
187
+ const entries = (await readdir(root).catch(() => [])).filter(name => jobID.safeParse(name).success);
188
+ const stamped = await Promise.all(entries.map(async (name) => ({ name, at: (await stat(path.join(root, name)).catch(() => undefined))?.mtimeMs ?? 0 })));
189
+ const names = stamped.sort((a, b) => b.at - a.at).slice(0, MAX_JOBS).map(entry => entry.name);
190
+ const children = [];
191
+ for (const name of names) {
192
+ const directory = path.join(root, name);
193
+ const manifestFile = await regularContainedFile(root, path.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
194
+ if (!manifestFile)
195
+ continue;
196
+ try {
197
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestFile, "utf8")));
198
+ if (manifest.id !== name || manifest.parent?.provider !== parentProvider || manifest.parent.session !== parentSession
199
+ || (manifest.parent.computer !== undefined && parentComputer !== undefined && manifest.parent.computer !== parentComputer))
200
+ continue;
201
+ const jobRoot = await realpath(directory);
202
+ if (!jobRoot.startsWith(root + path.sep))
203
+ continue;
204
+ const transcript = await regularContainedFile(jobRoot, path.join(jobRoot, manifest.eventLog), MAX_EVENT_LOG_BYTES);
205
+ if (!transcript)
206
+ continue;
207
+ const worktree = await worktreeDetails(manifest.worktree);
208
+ const id = fanoutChildID(root, manifest);
209
+ // A denied permission aborts the turn while the launcher still records a
210
+ // zero exit; blocked.json is the only evidence the worker did not finish.
211
+ const blocked = await readBlocked(jobRoot);
212
+ // A running worker waiting on the phone's answer to a permission ask.
213
+ const asking = !blocked && manifest.status === "running" && manifest.provider === "opencode" && manifest.session
214
+ ? await readOpencodeRequest(manifest.session, storeRoot(env)) : undefined;
215
+ const finishedAt = manifest.finishedAt ?? blocked?.at
216
+ ?? (ARCHIVED_STATUSES.has(manifest.status)
217
+ ? (await stat(path.join(jobRoot, "exit.txt")).catch(() => undefined))?.mtime.toISOString() ?? manifest.updatedAt : undefined);
218
+ children.push({ id, provider: manifest.provider, session: manifest.session, model: manifest.model, ...worktree, cwd: manifest.worktree,
219
+ path: manifest.taskLabel, callId: `fanout:${id}`,
220
+ state: blocked || manifest.status === "failed" || manifest.status === "cancelled" ? "failed" : ["queued", "running"].includes(manifest.status) ? "running" : "completed",
221
+ ...(blocked ? { reason: blockedReason(blocked) } : asking ? { reason: `needs-you: ${String(asking.message ?? asking.type)}`.slice(0, 500) } : {}), ...(finishedAt ? { finishedAt } : {}), transcript,
222
+ fanout: { resumable: ["codex", "opencode"].includes(manifest.provider) && manifest.session !== undefined }, children: [] });
223
+ }
224
+ catch { /* Torn, old, or untrusted manifests do not become child agents. */ }
225
+ }
226
+ return children.sort((a, b) => a.path.localeCompare(b.path) || a.id.localeCompare(b.id));
227
+ }
228
+ /** Every fan-out job's worktree with its task label and harness, whatever
229
+ * conversation launched it, so the Changes screen can name the worker editing
230
+ * a checkout. Newest first, bounded like the child listing. */
231
+ export async function fanoutWorktrees(env = process.env) {
232
+ const root = await containedFanoutRoot(env);
233
+ if (!root)
234
+ return [];
235
+ const entries = (await readdir(root).catch(() => [])).filter(name => jobID.safeParse(name).success);
236
+ const stamped = await Promise.all(entries.map(async (name) => ({ name, at: (await stat(path.join(root, name)).catch(() => undefined))?.mtimeMs ?? 0 })));
237
+ const jobs = [];
238
+ for (const { name } of stamped.sort((a, b) => b.at - a.at).slice(0, MAX_JOBS)) {
239
+ const manifestFile = await regularContainedFile(root, path.join(root, name, "manifest.json"), MAX_MANIFEST_BYTES);
240
+ if (!manifestFile)
241
+ continue;
242
+ try {
243
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestFile, "utf8")));
244
+ if (manifest.id !== name)
245
+ continue;
246
+ jobs.push({ worktree: manifest.worktree, label: manifest.taskLabel, provider: manifest.provider, state: manifest.status });
247
+ }
248
+ catch { /* Torn or untrusted manifests name no worker. */ }
249
+ }
250
+ return jobs;
251
+ }
252
+ /** Every fan-out job that left a blocked.json, for the Hook's push watcher. */
253
+ export async function blockedFanouts(env = process.env) {
254
+ const root = await containedFanoutRoot(env);
255
+ if (!root)
256
+ return [];
257
+ const names = (await readdir(root).catch(() => [])).filter(name => jobID.safeParse(name).success).slice(0, MAX_JOBS);
258
+ const blocked = [];
259
+ for (const name of names) {
260
+ const jobRoot = await realpath(path.join(root, name)).catch(() => undefined);
261
+ if (!jobRoot || !jobRoot.startsWith(root + path.sep))
262
+ continue;
263
+ const manifestFile = await regularContainedFile(root, path.join(jobRoot, "manifest.json"), MAX_MANIFEST_BYTES);
264
+ if (!manifestFile)
265
+ continue;
266
+ try {
267
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(manifestFile, "utf8")));
268
+ if (manifest.id !== name)
269
+ continue;
270
+ const value = await readBlocked(jobRoot);
271
+ if (!value)
272
+ continue;
273
+ blocked.push({ id: manifest.id, provider: manifest.provider, label: manifest.taskLabel,
274
+ ...(manifest.parent ? { parent: manifest.parent } : {}), reason: blockedReason(value), ...(value.at ? { at: value.at } : {}) });
275
+ }
276
+ catch { /* Torn or untrusted jobs are not pushed. */ }
277
+ }
278
+ return blocked;
279
+ }
280
+ /** The running OpenCode fan-out job a permission request names, when its own
281
+ * manifest confirms the worker session and a parent conversation: the parent
282
+ * is where the phone answers the ask. */
283
+ export async function fanoutAsking(job, session, env = process.env) {
284
+ if (!jobID.safeParse(job).success)
285
+ return undefined;
286
+ const root = await containedFanoutRoot(env);
287
+ if (!root)
288
+ return undefined;
289
+ const jobRoot = await realpath(path.join(root, job)).catch(() => undefined);
290
+ if (!jobRoot || !jobRoot.startsWith(root + path.sep))
291
+ return undefined;
292
+ const file = await regularContainedFile(root, path.join(jobRoot, "manifest.json"), MAX_MANIFEST_BYTES);
293
+ if (!file)
294
+ return undefined;
295
+ try {
296
+ const manifest = manifestSchema.parse(JSON.parse(await readFile(file, "utf8")));
297
+ if (manifest.id !== job || manifest.provider !== "opencode" || manifest.session !== session || manifest.status !== "running" || !manifest.parent)
298
+ return undefined;
299
+ return { id: manifest.id, label: manifest.taskLabel, parent: manifest.parent };
300
+ }
301
+ catch {
302
+ return undefined;
303
+ }
304
+ }
305
+ /** The job's own manifest when it parses, absent when the folder has none. */
306
+ async function jobManifest(root, directory) {
307
+ const manifestFile = await regularContainedFile(root, path.join(directory, "manifest.json"), MAX_MANIFEST_BYTES);
308
+ if (!manifestFile)
309
+ return undefined;
310
+ try {
311
+ return manifestSchema.parse(JSON.parse(await readFile(manifestFile, "utf8")));
312
+ }
313
+ catch {
314
+ return undefined;
315
+ }
316
+ }
317
+ /** The launcher's exit stamp: its presence is what says the job is finished. */
318
+ async function exitStamp(directory) {
319
+ const exit = await lstat(path.join(directory, "exit.txt")).catch(() => undefined);
320
+ return exit?.isFile() && !exit.isSymbolicLink() ? exit.mtimeMs : undefined;
321
+ }
322
+ /** When an archived folder counts as finished for the cap: its manifest's
323
+ * finishedAt, else exit.txt's mtime, else the folder's own mtime. */
324
+ async function archivedFinishedAt(directory) {
325
+ const manifestFile = await lstat(path.join(directory, "manifest.json")).catch(() => undefined);
326
+ if (manifestFile?.isFile() && !manifestFile.isSymbolicLink() && manifestFile.size <= MAX_MANIFEST_BYTES) {
327
+ try {
328
+ const value = JSON.parse(await readFile(path.join(directory, "manifest.json"), "utf8"));
329
+ const finished = typeof value.finishedAt === "string" ? Date.parse(value.finishedAt) : NaN;
330
+ if (Number.isFinite(finished))
331
+ return finished;
332
+ }
333
+ catch { /* Missing, torn, or synthesized manifests fall back to the exit stamp. */ }
334
+ }
335
+ const exit = await exitStamp(directory);
336
+ if (exit !== undefined)
337
+ return exit;
338
+ return (await stat(directory).catch(() => undefined))?.mtimeMs ?? 0;
339
+ }
340
+ /** Move finished fan-out job folders into the archive.
341
+ *
342
+ * A folder moves when it has exit.txt (without it the job is still running and
343
+ * is never touched), its manifest status is completed, failed or cancelled,
344
+ * and its finishedAt (or exit.txt's mtime when there is none) is over
345
+ * ARCHIVE_AGE_MS old. A folder with no manifest goes too once its exit.txt is
346
+ * that old, gaining a synthesized {status: failed, reason: "no manifest"}
347
+ * manifest in the archive. The archive keeps ARCHIVE_MAX_FOLDERS folders,
348
+ * deleting the oldest beyond that. `dryRun` reports the same work without
349
+ * touching anything. `olderThanMs` replaces the 24 hour age (0 archives every
350
+ * finished job), and `parent` limits the sweep to one parent session's jobs;
351
+ * a folder without a manifest has no parent and is left alone then. */
352
+ export async function archiveFinishedFanouts(env = process.env, options = {}) {
353
+ const now = options.now ?? Date.now(), dryRun = options.dryRun ?? false;
354
+ const age = options.olderThanMs ?? ARCHIVE_AGE_MS, parent = options.parent;
355
+ const moves = [];
356
+ const configured = fanoutRoot(env);
357
+ const root = await realpath(configured).catch(() => undefined);
358
+ const archive = path.join(path.dirname(root ?? configured), "agent-fanouts-archive");
359
+ if (root) {
360
+ const names = (await readdir(root).catch(() => [])).filter(name => jobID.safeParse(name).success).sort();
361
+ for (const name of names) {
362
+ const directory = path.join(root, name);
363
+ const metadata = await lstat(directory).catch(() => undefined);
364
+ if (!metadata?.isDirectory() || metadata.isSymbolicLink())
365
+ continue;
366
+ if (await lstat(path.join(directory, "message-lock")).catch(() => undefined))
367
+ continue;
368
+ const messages = await readdir(path.join(directory, "messages")).catch(() => []);
369
+ if (messages.some(name => name.endsWith(".queued.json")))
370
+ continue;
371
+ const exit = await exitStamp(directory);
372
+ if (exit === undefined)
373
+ continue;
374
+ const manifest = await jobManifest(root, directory);
375
+ if (parent && (manifest?.parent?.session !== parent.session
376
+ || (parent.provider !== undefined && manifest.parent.provider !== parent.provider)))
377
+ continue;
378
+ let basis;
379
+ if (manifest && ARCHIVED_STATUSES.has(manifest.status)) {
380
+ const finished = manifest.finishedAt ? Date.parse(manifest.finishedAt) : NaN;
381
+ basis = Number.isFinite(finished) ? finished : exit;
382
+ }
383
+ else if (!manifest) {
384
+ basis = exit;
385
+ }
386
+ else
387
+ continue;
388
+ // An explicit "now" (age 0) archives every finished job; comparing against
389
+ // the exit stamp raced file times a millisecond ahead of the clock.
390
+ if (age > 0 && now - basis <= age)
391
+ continue;
392
+ moves.push({ name, basis });
393
+ if (dryRun)
394
+ continue;
395
+ await mkdir(archive, { recursive: true, mode: 0o700 });
396
+ const destination = path.join(archive, name);
397
+ await rm(destination, { recursive: true, force: true });
398
+ await rename(directory, destination);
399
+ if (!manifest)
400
+ await writeFile(path.join(destination, "manifest.json"), JSON.stringify({ status: "failed", reason: "no manifest" }), { mode: 0o600 });
401
+ }
402
+ }
403
+ // Cap the archive: after the moves it may hold ARCHIVE_MAX_FOLDERS + n folders.
404
+ const archived = (await readdir(archive).catch(() => [])).filter(name => jobID.safeParse(name).success);
405
+ const entries = [];
406
+ for (const name of archived)
407
+ entries.push({ name, age: await archivedFinishedAt(path.join(archive, name)) });
408
+ // On a dry run the moves never landed, so weigh them at their finish stamp.
409
+ if (dryRun)
410
+ for (const move of moves)
411
+ entries.push({ name: move.name, age: move.basis });
412
+ let deleted = 0;
413
+ if (entries.length > ARCHIVE_MAX_FOLDERS) {
414
+ const excess = entries.sort((a, b) => a.age - b.age || a.name.localeCompare(b.name)).slice(0, entries.length - ARCHIVE_MAX_FOLDERS);
415
+ for (const entry of excess)
416
+ if (!dryRun)
417
+ await rm(path.join(archive, entry.name), { recursive: true, force: true });
418
+ deleted = excess.length;
419
+ }
420
+ return { moved: moves.map(move => move.name), deleted };
421
+ }
422
+ export const FANOUTS_ARCHIVE_USAGE = "Usage: phren bridge fanouts archive [--dry-run] [--parent <session-id>] [--older-than <minutes>]";
423
+ /** `--parent` limits the sweep to one parent chat's workers; `--older-than`
424
+ * replaces the 24 hour age, and 0 archives every finished one. */
425
+ export function parseFanoutArchiveFlags(flags) {
426
+ const options = {};
427
+ for (let index = 0; index < flags.length; index++) {
428
+ const flag = flags[index];
429
+ if (flag === "--dry-run") {
430
+ options.dryRun = true;
431
+ continue;
432
+ }
433
+ const value = flags[index + 1];
434
+ if (flag === "--parent" && value !== undefined && sessionId.safeParse(value).success) {
435
+ options.parent = { session: value };
436
+ index++;
437
+ continue;
438
+ }
439
+ if (flag === "--older-than" && value !== undefined && /^\d{1,7}$/.test(value)) {
440
+ options.olderThanMs = Number(value) * 60_000;
441
+ index++;
442
+ continue;
443
+ }
444
+ throw new Error(FANOUTS_ARCHIVE_USAGE);
445
+ }
446
+ return options;
447
+ }
448
+ /** Project raw `opencode run --format json` rows into the small public chat
449
+ * contract. Reasoning, snapshots, costs, and metadata are omitted. Like the
450
+ * Codex mapping, the command, URL or path a tool was given and a bounded
451
+ * output tail cross the wire so the owner can see what a worker is doing.
452
+ * An MCP tool keeps its own arguments and an edit, write or patch carries the
453
+ * changed-file diff the phone draws under the card; both are bounded. */
454
+ export function visibleOpenCodeRunEvent(raw, cwd) {
455
+ if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
456
+ return { type: "user/message", time: raw.timestamp, data: { message: {
457
+ role: "user", content: [{ type: "text", text: raw.text }],
458
+ } } };
459
+ }
460
+ const part = object(raw.part), time = typeof raw.timestamp === "number" && Number.isFinite(raw.timestamp)
461
+ ? new Date(raw.timestamp).toISOString() : undefined;
462
+ if (raw.type === "text" && part.type === "text" && typeof part.text === "string") {
463
+ return { type: "assistant/message", ...(time ? { time } : {}), data: { message: {
464
+ role: "assistant", content: [{ type: "text", text: part.text.slice(0, 262_144) }],
465
+ } } };
466
+ }
467
+ if (raw.type === "tool_use" && part.type === "tool" && typeof part.tool === "string") {
468
+ const state = object(part.state), status = ["pending", "running", "completed", "error"].includes(String(state.status))
469
+ ? String(state.status) : "completed";
470
+ const id = String(part.callID ?? "").slice(0, 200);
471
+ const content = [{ type: "tool_use", id, name: part.tool.slice(0, 200), input: opencodeToolInput(part.tool, object(state.input)), phrenStatus: status }];
472
+ if (status === "completed" || status === "error") {
473
+ content.push({ type: "tool_result", tool_use_id: id, content: opencodeToolOutput(part.tool, state), ...(status === "error" ? { is_error: true } : {}) });
474
+ }
475
+ const files = status === "completed" ? opencodeChanges(part.tool, state, cwd) : undefined;
476
+ return { type: "assistant/message", ...(time ? { time } : {}),
477
+ ...(files?.length ? { phren_changes: { [id]: files } } : {}), data: { message: { role: "assistant", content } } };
478
+ }
479
+ if (raw.type === "step_finish") {
480
+ return { type: "system", ...(time ? { time } : {}), data: { message: {
481
+ role: "assistant", content: [{ type: "text", text: `Step finished${typeof part.reason === "string" ? `: ${part.reason.slice(0, 200)}` : "."}` }],
482
+ } } };
483
+ }
484
+ }
485
+ /** Project raw `codex exec --json` rows into the shape Codex's own rollout
486
+ * files use, so the existing Codex transcript reader renders them unchanged.
487
+ * Command text, a bounded output tail, and changed paths cross the wire so the
488
+ * owner can see what a worker is doing; diffs, usage, and costs do not. */
489
+ export function visibleCodexExecEvent(raw) {
490
+ if (raw.type === "phren/fanout-message" && typeof raw.text === "string") {
491
+ return { type: "response_item", timestamp: raw.timestamp, payload: { type: "message", role: "user",
492
+ content: [{ type: "input_text", text: raw.text }] } };
493
+ }
494
+ const item = object(raw.item), callId = () => String(item.id ?? "").slice(0, 200);
495
+ if (raw.type === "item.completed" && item.type === "agent_message") {
496
+ if (typeof item.text !== "string")
497
+ return undefined;
498
+ return { type: "response_item", payload: { type: "message", role: "assistant",
499
+ content: [{ type: "output_text", text: item.text.slice(0, 262_144) }] } };
500
+ }
501
+ if (raw.type === "item.started" && item.type === "command_execution") {
502
+ return { type: "response_item", payload: { type: "function_call", name: "shell",
503
+ call_id: callId(), arguments: JSON.stringify({ command: codexCommand(item) }) } };
504
+ }
505
+ if (raw.type === "item.completed" && item.type === "command_execution") {
506
+ return { type: "response_item", payload: { type: "function_call_output", call_id: callId(),
507
+ output: codexCommandOutput(item) } };
508
+ }
509
+ if (raw.type === "item.started" && item.type === "file_change") {
510
+ return { type: "response_item", payload: { type: "function_call", name: "apply_patch",
511
+ call_id: callId(), arguments: JSON.stringify({ files: codexFiles(item) }) } };
512
+ }
513
+ if (raw.type === "item.completed" && item.type === "file_change") {
514
+ const files = codexFiles(item), header = `${files.length} file(s) changed`;
515
+ return { type: "response_item", payload: { type: "function_call_output", call_id: callId(),
516
+ output: files.length ? `${header}\n${files.map(file => file.path).join("\n")}` : header } };
517
+ }
518
+ if (raw.type === "turn.completed")
519
+ return { type: "event_msg", payload: { type: "task_complete" } };
520
+ if (raw.type === "error" && typeof raw.message === "string") {
521
+ return { type: "event_msg", payload: { type: "error", message: raw.message.slice(0, 2000) } };
522
+ }
523
+ return undefined;
524
+ }
525
+ const OPENCODE_BUILTINS = new Set(["bash", "read", "edit", "write", "patch", "grep", "glob", "list", "webfetch", "todowrite", "todoread", "task", "skill"]);
526
+ /** The one argument that says what a tool did: a command, a URL, a path or a
527
+ * pattern. MCP tools (anything outside OpenCode's own set) keep their whole
528
+ * argument object, and an edit, write or patch keeps the text it touched. */
529
+ function opencodeToolInput(tool, input) {
530
+ const text = (key, max = 2000) => typeof input[key] === "string" ? collapseHomeText(String(input[key])).slice(0, max) : undefined;
531
+ switch (tool) {
532
+ case "bash": return { command: text("command") ?? "" };
533
+ case "webfetch": return { url: text("url") ?? "" };
534
+ case "read": return { path: text("filePath") ?? text("path") ?? "" };
535
+ case "edit": return { path: text("filePath") ?? text("path") ?? "", oldString: text("oldString", 4000) ?? "", newString: text("newString", 4000) ?? "" };
536
+ case "write": return { path: text("filePath") ?? text("path") ?? "", content: text("content", 4000) ?? "" };
537
+ case "patch": return { path: text("filePath") ?? text("path") ?? "", patch: text("patch", 4000) ?? text("content", 4000) ?? "" };
538
+ case "grep":
539
+ case "glob":
540
+ case "list": return { pattern: text("pattern", 500) ?? "", path: text("path") ?? "" };
541
+ default: return OPENCODE_BUILTINS.has(tool) ? {} : mcpToolInput(input);
542
+ }
543
+ }
544
+ const MCP_INPUT_BYTES = 8 * 1024;
545
+ const MCP_STRING_CHARS = 4000;
546
+ const MCP_INPUT_DEPTH = 4;
547
+ /** An MCP tool's arguments as the phone shows them: home paths collapsed,
548
+ * long strings cut, nesting bounded, and the whole object kept under 8 KB by
549
+ * shortening the strings further rather than dropping the call. */
550
+ function mcpToolInput(input) {
551
+ for (const cap of [MCP_STRING_CHARS, 2000, 1000, 500, 250, 120, 60, 0]) {
552
+ const value = boundedValue(input, 0, cap);
553
+ if (Buffer.byteLength(JSON.stringify(value)) <= MCP_INPUT_BYTES)
554
+ return object(value);
555
+ }
556
+ return {};
557
+ }
558
+ function boundedValue(value, depth, cap) {
559
+ if (depth > MCP_INPUT_DEPTH)
560
+ return undefined;
561
+ if (typeof value === "string") {
562
+ const text = collapseHomeText(value);
563
+ return text.length > cap ? `${text.slice(0, cap)}…` : text;
564
+ }
565
+ if (typeof value === "number" || typeof value === "boolean" || value === null)
566
+ return value;
567
+ if (Array.isArray(value))
568
+ return value.slice(0, 64).map(item => boundedValue(item, depth + 1, cap)).filter(item => item !== undefined);
569
+ if (value && typeof value === "object") {
570
+ const out = Object.create(null);
571
+ for (const [key, item] of Object.entries(value).slice(0, 64)) {
572
+ const bounded = boundedValue(item, depth + 1, cap);
573
+ if (bounded !== undefined)
574
+ out[key] = bounded;
575
+ }
576
+ return out;
577
+ }
578
+ return undefined;
579
+ }
580
+ const MAX_CHANGE_PATCH = 64 * 1024;
581
+ /** The files an OpenCode edit, write or patch touched, in the ChangedFile
582
+ * shape `phren_changes` already carries. `cwd` is the worker's checkout when
583
+ * the caller knows it, so the path is shown relative to it. */
584
+ function opencodeChanges(tool, state, cwd) {
585
+ if (!["edit", "write", "patch"].includes(tool))
586
+ return undefined;
587
+ const input = object(state.input), metadata = object(state.metadata), filediff = object(metadata.filediff);
588
+ let patch = [metadata.diff, filediff.patch, input.patch, input.diff].find(value => typeof value === "string" && value);
589
+ let status = patch ? changeStatus(patch) : "M";
590
+ if (tool === "write" && !patch && metadata.exists === false) {
591
+ patch = addedFilePatch(typeof input.content === "string" ? input.content : "");
592
+ status = "A";
593
+ }
594
+ if (!patch)
595
+ return undefined;
596
+ patch = collapseHomeText(patch);
597
+ const chunks = patch.split(/(?=^diff --git )/m).filter(Boolean);
598
+ const patches = chunks.length > 1 ? chunks : patch.split(/(?=^--- [^\n]+\n\+\+\+ )/m).filter(Boolean);
599
+ const multiple = patches.length > 1;
600
+ return patches.slice(0, 50).flatMap(patch => {
601
+ const given = multiple ? patchPath(patch) :
602
+ [filediff.file, metadata.filepath, input.filePath, input.path].find(value => typeof value === "string" && value)
603
+ ?? patchPath(patch);
604
+ if (!given)
605
+ return [];
606
+ const counted = diffCounts(patch);
607
+ const validCount = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
608
+ const added = !multiple && validCount(filediff.additions) ? filediff.additions : counted.added;
609
+ const removed = !multiple && validCount(filediff.deletions) ? filediff.deletions : counted.removed;
610
+ // The phone draws worker patches without needing their private checkout root.
611
+ return [{ root: "", path: relativeChangePath(given, cwd), status: multiple ? changeStatus(patch) : status,
612
+ patch: patch.slice(0, MAX_CHANGE_PATCH), added, removed }];
613
+ });
614
+ }
615
+ /** A patch tool may carry only the diff; its `+++` (or `Index:`) header names
616
+ * the file. */
617
+ function patchPath(patch) {
618
+ const next = /^\+\+\+ (?:b\/)?(.+)$/m.exec(patch)?.[1]?.trim();
619
+ if (next && next !== "/dev/null")
620
+ return next;
621
+ return (/^--- (?:a\/)?(.+)$/m.exec(patch) ?? /^Index: (.+)$/m.exec(patch))?.[1]?.trim() || undefined;
622
+ }
623
+ function relativeChangePath(value, cwd) {
624
+ if (cwd && path.isAbsolute(value)) {
625
+ const relative = path.relative(cwd, value);
626
+ if (relative && relative !== ".." && !relative.startsWith(`..${path.sep}`))
627
+ return relative;
628
+ }
629
+ return collapseHome(value);
630
+ }
631
+ /** Does a unified diff add, delete or change the file? */
632
+ function changeStatus(patch) {
633
+ if (/^new file mode\b/m.test(patch) || /^--- \/dev\/null$/m.test(patch) || /^@@ -0,0 /m.test(patch))
634
+ return "A";
635
+ if (/^deleted file mode\b/m.test(patch) || /^\+\+\+ \/dev\/null$/m.test(patch))
636
+ return "D";
637
+ return "M";
638
+ }
639
+ function diffCounts(patch) {
640
+ let added = 0, removed = 0;
641
+ for (const line of patch.split("\n")) {
642
+ if (line.startsWith("+++") || line.startsWith("---"))
643
+ continue;
644
+ if (line.startsWith("+"))
645
+ added++;
646
+ else if (line.startsWith("-"))
647
+ removed++;
648
+ }
649
+ return { added, removed };
650
+ }
651
+ /** The `@@` hunk the phone's diff card expects from a new file's content. */
652
+ function addedFilePatch(content) {
653
+ const text = content.endsWith("\n") ? content.slice(0, -1) : content;
654
+ const lines = content ? text.split("\n") : [];
655
+ return [`@@ -0,0 +1,${lines.length} @@`, ...lines.map(line => `+${line}`)].join("\n");
656
+ }
657
+ function opencodeToolOutput(tool, state) {
658
+ const metadata = object(state.metadata);
659
+ const raw = typeof state.output === "string" ? state.output : typeof state.error === "string" ? state.error : "";
660
+ const text = collapseHomeText(raw).slice(-4000);
661
+ if (tool === "bash")
662
+ return `${text}${text && !text.endsWith("\n") ? "\n" : ""}${typeof metadata.exit === "number" ? `[exit ${metadata.exit}]` : "[finished]"}`;
663
+ return text;
664
+ }
665
+ /** Replace the real home directory wherever it appears in free text (a
666
+ * command line, an output tail) with `~`, so the account name stays home. */
667
+ function collapseHomeText(value) {
668
+ const home = homedir();
669
+ const base = home.endsWith(path.sep) ? home.slice(0, -path.sep.length) : home;
670
+ return base.length > 1 ? value.split(base).join("~") : value;
671
+ }
672
+ /** Replace a leading real home directory with `~` for display. */
673
+ function collapseHome(value) {
674
+ const home = homedir();
675
+ const trimmed = home.endsWith(path.sep) ? home.slice(0, -path.sep.length) : home;
676
+ for (const base of [home, trimmed]) {
677
+ if (value === base)
678
+ return "~";
679
+ const prefix = `${base}${path.sep}`;
680
+ if (value.startsWith(prefix))
681
+ return `~${path.sep}${value.slice(prefix.length)}`;
682
+ }
683
+ return value;
684
+ }
685
+ function codexCommand(item) {
686
+ const value = item.command;
687
+ const text = Array.isArray(value) ? value.filter(part => typeof part === "string").join(" ")
688
+ : typeof value === "string" ? value : "";
689
+ return text.slice(0, 2000);
690
+ }
691
+ function codexCommandOutput(item) {
692
+ const text = typeof item.aggregated_output === "string" ? item.aggregated_output.slice(-4000) : "";
693
+ const status = typeof item.exit_code === "number" ? `[exit ${item.exit_code}]` : "[finished]";
694
+ return `${text}\n${status}`;
695
+ }
696
+ function codexFiles(item) {
697
+ const changes = Array.isArray(item.changes) ? item.changes : [];
698
+ return changes.slice(0, 50).map(change => {
699
+ const entry = object(change);
700
+ return { path: collapseHome(String(entry.path ?? "")).slice(0, 512), kind: String(entry.kind ?? "").slice(0, 512) };
701
+ });
702
+ }