@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
@@ -1,69 +1,229 @@
1
- import { realpath } from "node:fs/promises";
1
+ import { readdir, realpath, lstat } from "node:fs/promises";
2
+ import { createHash } from "node:crypto";
2
3
  import { homedir } from "node:os";
4
+ import { codexHome, claudeConfigDir } from "../home-paths.js";
3
5
  import path from "node:path";
4
- import { glob } from "glob";
5
6
  import { withTranscriptIndex } from "./transcript-index.js";
6
- import { BridgeError, object, objects } from "./protocol.js";
7
- /** Preserve image block indexes without putting base64 payloads on the chat socket. */
7
+ import { BridgeError, object, objects, sessionId } from "./protocol.js";
8
+ import { materializeCodexThread, materializedRoot } from "./codex-threads.js";
9
+ import { namedPaths, SHELL_TOOLS, outputCallIds } from "./changes.js";
10
+ import { fanoutChildren } from "./fanouts.js";
11
+ import { claudeChildAgents, visibleClaudeEvent } from "./transcript-claude.js";
12
+ import { childTranscriptBelongsTo, directChildAgents, projectCodexRow, rewriteProjectedOutput, visibleCodexEvent } from "./transcript-codex.js";
13
+ import { visibleCopilotEvent } from "./transcript-copilot.js";
14
+ import { visibleOpencodeEvent } from "./transcript-opencode.js";
15
+ export { isNarration, unwrapPastedContent } from "./transcript-claude.js";
16
+ export { codeToolCalls, projectCodexRow } from "./transcript-codex.js";
17
+ /** Provider-neutral child-agent discovery. Codex currently supplies explicit
18
+ * SubAgentActivity links; other providers return no children until their
19
+ * public transcript format exposes an equivalent relationship. */
20
+ export async function childAgentTree(source, session, depth = 0, seen = new Set(), computer = "local") {
21
+ const identity = `${computer}\0${source}\0${session}`;
22
+ if (depth >= 4 || seen.size >= 128 || seen.has(identity))
23
+ return [];
24
+ seen.add(identity);
25
+ const fanouts = (await fanoutChildren(source, session, process.env, computer === "local" ? undefined : computer)).map(child => ({
26
+ ...child, session: child.session ?? child.id, cwd: child.cwd, children: [],
27
+ }));
28
+ if (!["codex", "claude"].includes(source))
29
+ return fanouts;
30
+ const file = await transcriptPath(source, session);
31
+ if (source === "claude")
32
+ return [...await claudeChildAgents(file, session), ...fanouts];
33
+ const relations = await directChildAgents(file), verified = [];
34
+ for (const relation of relations) {
35
+ const childFile = await transcriptPath(source, relation.session).catch(() => undefined);
36
+ if (!childFile || !await childTranscriptBelongsTo(childFile, session))
37
+ continue;
38
+ verified.push({ ...relation, transcript: childFile, provider: source,
39
+ id: createHash("sha256").update(`${source}\0${session}\0${relation.session}`).digest("hex").slice(0, 32),
40
+ children: await childAgentTree(source, relation.session, depth + 1, seen, computer).catch(() => []) });
41
+ }
42
+ return [...verified, ...fanouts];
43
+ }
44
+ /** Explicit wire projection prevents a provider's private transcript identity
45
+ * from being returned if relation internals grow later. */
46
+ export function publicChildAgents(tree) {
47
+ return tree.map(({ id, provider, path: agentPath, callId, state, reason, finishedAt, model, worktreeName, branch, computer, remote, fanout, children }) =>
48
+ // A blocked worker is finished; the phone's relation contract has no failed
49
+ // state, so the reason carries what happened without breaking old clients.
50
+ ({ id, provider, path: agentPath, callId, state: state === "failed" ? "completed" : state,
51
+ ...(state === "failed" ? { failed: true } : {}), ...(finishedAt ? { finishedAt } : {}),
52
+ ...(reason !== undefined ? { reason } : {}), ...(model !== undefined ? { model } : {}),
53
+ ...(worktreeName !== undefined ? { worktreeName } : {}), ...(branch !== undefined ? { branch } : {}),
54
+ ...(computer !== undefined ? { computer: { id: computer.id, name: computer.name } } : {}),
55
+ ...(remote !== undefined ? { remote: { target: remote.target, ...(remote.child !== undefined ? { child: remote.child } : {}) } } : {}),
56
+ ...(fanout ? { fanout } : {}),
57
+ children: publicChildAgents(children) }));
58
+ }
59
+ export function childAgent(tree, id) {
60
+ for (const node of tree) {
61
+ if (node.remote !== undefined)
62
+ continue;
63
+ if (node.id === id && node.session !== undefined && node.transcript !== undefined)
64
+ return node;
65
+ const nested = childAgent(node.children, id);
66
+ if (nested)
67
+ return nested;
68
+ }
69
+ }
70
+ /** Preserve content positions and image types; original bytes stay in the
71
+ * transcript for the separate image route. Only provider content blocks are
72
+ * interpreted, never text strings or arbitrary tool arguments. */
73
+ function imageReferences(content, toolResults = false) {
74
+ if (!Array.isArray(content))
75
+ return content;
76
+ return content.map(value => {
77
+ const block = object(value);
78
+ if (["image", "input_image"].includes(String(block.type)))
79
+ return { type: block.type };
80
+ if (toolResults && block.type === "tool_result")
81
+ return { ...block, content: toolOutputReferences(block.content) };
82
+ return value;
83
+ });
84
+ }
85
+ function toolOutputReferences(output) {
86
+ if (Array.isArray(output))
87
+ return imageReferences(output);
88
+ const result = object(output);
89
+ return Array.isArray(result.content) ? { ...result, content: imageReferences(result.content) } : output;
90
+ }
91
+ /**
92
+ * The phren store whose `.runtime/sessions` holds phren-agent event logs.
93
+ * `PHREN_PATH` or the shared `~/.phren` root — the two resolutions the CLI's
94
+ * `findPhrenPath` makes without a working directory, which a service has none
95
+ * of. Kept inline rather than importing phren-paths: that module drags in
96
+ * yaml and the data layer, and this bundle is budgeted for cold start.
97
+ */
98
+ export function phrenStoreRoot(env = process.env) {
99
+ const configured = env.PHREN_PATH?.trim();
100
+ if (!configured)
101
+ return path.join(homedir(), ".phren");
102
+ const expanded = configured === "~" ? homedir() : configured.startsWith("~/") ? path.join(homedir(), configured.slice(2)) : configured;
103
+ return path.resolve(expanded);
104
+ }
8
105
  function chatFrame(raw, source) {
106
+ if (source === "phren" || source === "opencode") {
107
+ const data = object(raw.data), message = object(data.message);
108
+ return Array.isArray(message.content)
109
+ ? { ...raw, data: { ...data, message: { ...message, content: imageReferences(message.content, true) } } } : raw;
110
+ }
111
+ if (source === "copilot") {
112
+ const data = object(raw.data);
113
+ return { ...raw, data: { ...data,
114
+ ...(Array.isArray(data.content) ? { content: imageReferences(data.content) } : {}),
115
+ ...(data.result !== undefined ? { result: toolOutputReferences(data.result) } : {}),
116
+ } };
117
+ }
9
118
  const key = source === "codex" ? "payload" : "message";
10
119
  const message = object(raw[key]);
11
- if (!Array.isArray(message.content))
12
- return raw;
13
- return { ...raw, [key]: { ...message, content: message.content.map(value => {
14
- const block = object(value);
15
- return ["image", "input_image"].includes(String(block.type)) ? { type: block.type } : block;
16
- }) } };
120
+ if (source === "codex" && ["function_call_output", "custom_tool_call_output"].includes(String(message.type))) {
121
+ return { ...raw, [key]: { ...message, output: toolOutputReferences(message.output) } };
122
+ }
123
+ return Array.isArray(message.content)
124
+ ? { ...raw, [key]: { ...message, content: imageReferences(message.content, source === "claude") } } : raw;
125
+ }
126
+ /** Compile one path segment to a regexp: `*` and `?` are the only wildcards,
127
+ * neither crosses `/`. */
128
+ function segmentRegExp(segment) {
129
+ const source = segment.split(/([*?])/).map(part => {
130
+ if (part === "*")
131
+ return "[^/]*";
132
+ if (part === "?")
133
+ return "[^/]";
134
+ return part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
135
+ }).join("");
136
+ return new RegExp(`^${source}$`);
137
+ }
138
+ /** The fixed transcript layouts globbed for: `*` within a single segment, no
139
+ * `**`, dotfiles skipped, symlinked directories not followed. Kept native so
140
+ * the Hook bundle does not carry the `glob` package. */
141
+ async function findPatternMatches(root, pattern) {
142
+ const segments = pattern.split("/");
143
+ const expressions = segments.map(segmentRegExp);
144
+ const matches = [];
145
+ const walk = async (dir, index) => {
146
+ const segment = segments[index];
147
+ const last = index === segments.length - 1;
148
+ if (!segment.includes("*") && !segment.includes("?")) {
149
+ const next = path.join(dir, segment);
150
+ try {
151
+ const info = await lstat(next);
152
+ if (last) {
153
+ // glob returns a symlink to a file here too; the caller's realpath
154
+ // check is what rejects one pointing outside the provider folder.
155
+ if (info.isFile() || info.isSymbolicLink())
156
+ matches.push(next);
157
+ }
158
+ else if (info.isDirectory()) {
159
+ await walk(next, index + 1);
160
+ }
161
+ }
162
+ catch { /* no match */ }
163
+ return;
164
+ }
165
+ let entries;
166
+ try {
167
+ entries = await readdir(dir, { withFileTypes: true });
168
+ }
169
+ catch {
170
+ return;
171
+ }
172
+ for (const entry of entries) {
173
+ if (entry.name.startsWith(".") || !expressions[index].test(entry.name))
174
+ continue;
175
+ const next = path.join(dir, entry.name);
176
+ if (last) {
177
+ if (entry.isFile() || entry.isSymbolicLink())
178
+ matches.push(next);
179
+ }
180
+ else if (entry.isDirectory()) {
181
+ await walk(next, index + 1);
182
+ }
183
+ }
184
+ };
185
+ await walk(root, 0);
186
+ return matches;
17
187
  }
18
188
  export async function transcriptPath(source, session) {
19
- if (!/^[a-f0-9-]{36}$/i.test(session))
189
+ if (!sessionId.safeParse(session).success)
20
190
  throw new BridgeError(400, "Invalid conversation identity.");
21
- const base = source === "codex" ? path.join(process.env.CODEX_HOME || path.join(homedir(), ".codex"), "sessions")
22
- : source === "claude" ? path.join(process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), ".claude"), "projects")
23
- : path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state");
24
- const root = await realpath(base);
25
- const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl` : `${session}/events.jsonl`;
26
- const matches = await glob(pattern, { cwd: root, absolute: true, follow: false });
27
- if (matches.length !== 1)
191
+ const base = source === "codex" ? path.join(codexHome(), "sessions")
192
+ : source === "claude" ? path.join(claudeConfigDir(), "projects")
193
+ : source === "phren" || source === "opencode" ? path.join(phrenStoreRoot(), ".runtime", "sessions")
194
+ : path.join(process.env.COPILOT_HOME || path.join(homedir(), ".copilot"), "session-state");
195
+ const root = await realpath(base).catch(() => base);
196
+ const pattern = source === "codex" ? `*/*/*/rollout-*-${session}.jsonl` : source === "claude" ? `*/${session}.jsonl`
197
+ : source === "phren" ? `session-${session}.events.jsonl` : source === "opencode" ? `opencode-${session}.events.jsonl` : `${session}/events.jsonl`;
198
+ const matches = await findPatternMatches(root, pattern).catch(() => []);
199
+ if (matches.length !== 1) {
200
+ // Codex 0.155 keeps new threads only in its sqlite store; the Hook
201
+ // materializes those into a rollout-shaped file of its own.
202
+ const materialized = source === "codex" ? await materializeCodexThread(session) : undefined;
203
+ if (materialized)
204
+ return materialized;
28
205
  throw new BridgeError(404, "The transcript is not available for this conversation.");
206
+ }
29
207
  const file = await realpath(matches[0]);
30
208
  if (!file.startsWith(root + path.sep))
31
209
  throw new BridgeError(403, "The transcript points outside its agent folder.");
32
210
  return file;
33
211
  }
212
+ /** Keeps a materialized Codex thread current before a read; a no-op for
213
+ * transcripts the agent writes itself. */
214
+ export async function refreshTranscript(file, source, session) {
215
+ if (source === "codex" && file.startsWith(materializedRoot() + path.sep))
216
+ await materializeCodexThread(session);
217
+ }
34
218
  /** Public conversation/tool events and real usage only. Never export private reasoning. */
35
- export function visibleEvent(raw, source) {
36
- if (source === "codex") {
37
- const p = object(raw.payload);
38
- if (raw.type === "event_msg" && ["token_count", "task_started", "task_complete", "task_completed", "turn_aborted", "task_aborted", "error"].includes(String(p.type)))
39
- return raw;
40
- if (raw.type !== "response_item")
41
- return undefined;
42
- if (p.type === "message" && ["user", "assistant"].includes(String(p.role)) && p.channel !== "analysis")
43
- return raw;
44
- if (["function_call", "custom_tool_call", "function_call_output", "custom_tool_call_output"].includes(String(p.type)))
45
- return raw;
46
- }
47
- else if (source === "claude") {
48
- if (raw.isMeta || raw.isSidechain || !["user", "assistant", "system"].includes(String(raw.type)))
49
- return undefined;
50
- const message = object(raw.message);
51
- // Keep indexes for historical images while removing thinking contents.
52
- if (typeof message.content === "string")
53
- return raw;
54
- if (Array.isArray(message.content))
55
- return { ...raw, message: { ...message, content: objects(message.content).map(b => ["text", "image", "tool_use", "tool_result"].includes(String(b.type)) ? b : { type: "redacted" }) } };
56
- }
57
- else {
58
- if (raw.agentId || raw.ephemeral || !["user.message", "assistant.message", "assistant.message_delta", "tool.execution_start", "tool.execution_complete", "assistant.turn_start", "assistant.turn_end", "session.idle", "abort", "session.error", "session.usage_info", "assistant.usage"].includes(String(raw.type)))
59
- return undefined;
60
- const data = object(raw.data);
61
- // Copilot includes optional reasoning beside the public message in some
62
- // versions. Export only the fields used by public text/tool/usage readers.
63
- const allowed = ["content", "source", "messageId", "deltaContent", "toolName", "toolCallId", "arguments", "result", "error", "aborted", "inputTokens", "outputTokens", "cacheReadTokens"];
64
- return { type: raw.type, timestamp: raw.timestamp, data: Object.fromEntries(Object.entries(data).filter(([key]) => allowed.includes(key))) };
65
- }
66
- return undefined;
219
+ export function visibleEvent(raw, source, includeSidechain = false, cwd) {
220
+ if (source === "phren" || source === "opencode")
221
+ return visibleOpencodeEvent(raw, source, cwd);
222
+ if (source === "codex")
223
+ return visibleCodexEvent(raw);
224
+ if (source === "claude")
225
+ return visibleClaudeEvent(raw, includeSidechain);
226
+ return visibleCopilotEvent(raw);
67
227
  }
68
228
  /** Parse only the requested page; shared byte indexes make reopening and
69
229
  * backward pagination independent of the amount of already-read history. */
@@ -71,61 +231,134 @@ export class TranscriptReader {
71
231
  file;
72
232
  source;
73
233
  imageLine;
234
+ changes;
235
+ includeSidechain;
236
+ cwd;
74
237
  revision;
75
238
  nextLine = 0;
76
- constructor(file, source, imageLine) {
239
+ constructor(file, source, imageLine, changes, includeSidechain = false, cwd) {
77
240
  this.file = file;
78
241
  this.source = source;
79
242
  this.imageLine = imageLine;
243
+ this.changes = changes;
244
+ this.includeSidechain = includeSidechain;
245
+ this.cwd = cwd;
80
246
  }
81
247
  async read(before, signal) {
248
+ return this.readPage(before, undefined, signal);
249
+ }
250
+ /** Resume a fresh live reader after the last raw line the client retained. */
251
+ async readAfter(afterLine, signal) {
252
+ if (!Number.isSafeInteger(afterLine) || afterLine < 0)
253
+ throw new BridgeError(400, "Invalid transcript cursor.");
254
+ return this.readPage(undefined, afterLine, signal);
255
+ }
256
+ async readPage(before, afterLine, signal) {
82
257
  return withTranscriptIndex(this.file, async (handle, index) => {
83
258
  const reset = this.revision !== index.revision;
84
259
  const end = Math.min(before ?? index.lines, index.lines);
85
- const lower = this.imageLine ?? (reset || before !== undefined ? 0 : this.nextLine);
260
+ const resuming = before === undefined && afterLine !== undefined && this.revision === undefined;
261
+ // The phone's cursor can sit past the end after the file was replaced
262
+ // (compaction, a rewritten thread). A resume into that gap is a full
263
+ // snapshot of the new file, flagged as the replacement it is; an
264
+ // in-range resume is only a delta and never claims a replacement.
265
+ const pastEnd = resuming && afterLine >= index.lines;
266
+ const lower = this.imageLine ?? (pastEnd ? 0
267
+ : resuming ? Math.min(afterLine + 1, index.lines)
268
+ : reset || before !== undefined ? 0 : this.nextLine);
86
269
  const entries = [];
87
- let bytes = 0, cursor = end;
270
+ // The first page of a conversation is what the phone parses and lays
271
+ // out before anything shows; keep it light and let scrolling fetch the
272
+ // rest in fuller pages. A live tail (nextLine known) stays small too.
273
+ const opening = before === undefined && (pastEnd || (!resuming && (reset || this.nextLine === 0)));
274
+ const entryBudget = opening ? 60 : 200;
275
+ const byteBudget = opening ? 1_048_576 : 4_194_304;
276
+ let bytes = 0, cursor = end, held;
88
277
  for await (const row of index.rows(handle, end, lower, signal)) {
89
278
  signal?.throwIfAborted();
90
- let entry;
279
+ let rows = [];
91
280
  try {
92
- const raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source);
93
- if (raw)
94
- entry = { line: row.line, raw: this.imageLine === row.line ? raw : chatFrame(raw, this.source) };
281
+ let raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), this.source, this.includeSidechain, this.cwd);
282
+ // A child agent's transcript is the sidechain. Its rows are that
283
+ // conversation's own turns, not something for the reader to skip.
284
+ if (raw && this.includeSidechain && raw.isSidechain === true) {
285
+ const { isSidechain: _sidechain, ...own } = raw;
286
+ raw = own;
287
+ }
288
+ if (raw) {
289
+ if (this.changes && this.imageLine === undefined) {
290
+ // A shell call's output carries what it changed on disk. While
291
+ // that diff is still being computed on the live tail, the row
292
+ // (and the newer rows already collected) waits for the next read.
293
+ const ids = outputCallIds(raw, this.source);
294
+ if (before === undefined && ids.some(id => this.changes.pending(id))) {
295
+ held = row.line;
296
+ entries.length = 0;
297
+ bytes = 0;
298
+ cursor = row.line;
299
+ continue;
300
+ }
301
+ const attached = {};
302
+ for (const id of ids) {
303
+ const files = await this.changes.changes(id);
304
+ if (files)
305
+ attached[id] = files;
306
+ }
307
+ // A row that already carries a worker's own diff (OpenCode edit,
308
+ // write or patch) keeps it; the shell lookup only fills in the rest.
309
+ if (Object.keys(attached).length)
310
+ raw = { ...raw, phren_changes: { ...attached, ...object(raw.phren_changes) } };
311
+ }
312
+ const projected = this.source === "codex" ? projectCodexRow(raw) : { rows: [raw] };
313
+ rows = this.imageLine === row.line ? projected.rows : projected.rows.map(r => chatFrame(r, this.source));
314
+ if (projected.base)
315
+ rewriteProjectedOutput(entries, projected.base);
316
+ }
95
317
  }
96
318
  catch { /* A malformed old row cannot block the next readable page. */ }
97
- if (entry) {
98
- const size = Buffer.byteLength(JSON.stringify(entry));
319
+ if (rows.length) {
320
+ const size = Buffer.byteLength(JSON.stringify(rows));
99
321
  if (this.imageLine !== undefined || size < 2_097_152) {
100
322
  // Leave an entry that doesn't fit for the following history page.
101
- if (this.imageLine === undefined && bytes + size > 4_194_304)
323
+ if (this.imageLine === undefined && bytes + size > byteBudget)
102
324
  break;
103
- entries.push(entry);
325
+ // Rows arrive newest first; reverse a row's blocks so the page
326
+ // lists several calls from one source in the order they were written.
327
+ entries.push(...rows.slice().reverse().map(raw => ({ line: row.line, raw })));
104
328
  bytes += size;
105
329
  }
106
330
  }
107
331
  cursor = row.line;
108
- if (entries.length >= 200)
332
+ if (entries.length >= entryBudget)
109
333
  break;
110
334
  }
111
335
  if (before === undefined) {
112
336
  this.revision = index.revision;
113
- this.nextLine = index.lines;
337
+ this.nextLine = held ?? index.lines;
114
338
  }
115
- return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0, reset };
339
+ return { entries: entries.reverse(), totalLines: index.lines, startLine: cursor, hasMore: cursor > 0,
340
+ reset: resuming && !pastEnd ? false : reset };
116
341
  }, signal);
117
342
  }
118
343
  }
119
- export async function historicalImage(file, line, block, source) {
344
+ /** One embedded image: block `block` of the row's content — or, with
345
+ * `inner`, image `inner` inside that block's tool_result content (what a
346
+ * Read of a PNG returns). For Codex, an output row's array is the content. */
347
+ export async function historicalImage(file, line, block, source, inner) {
120
348
  if (!Number.isSafeInteger(line) || line < 0 || !Number.isSafeInteger(block) || block < 0 || block > 2000)
121
349
  throw new BridgeError(400, "Invalid image reference.");
350
+ if (inner !== undefined && (!Number.isSafeInteger(inner) || inner < 0 || inner > 2000))
351
+ throw new BridgeError(400, "Invalid image reference.");
122
352
  const reader = new TranscriptReader(file, source, line);
123
353
  const page = await reader.read(line + 1);
124
354
  const row = page.entries.find(e => e.line === line)?.raw;
125
355
  if (!row)
126
356
  throw new BridgeError(404, "This image is no longer in the transcript.");
127
- const content = objects(source === "codex" ? object(row.payload).content : object(row.message).content);
128
- const image = content[block];
357
+ const payload = source === "codex" ? object(row.payload) : source === "phren" || source === "opencode" ? object(object(row.data).message) : object(row.message);
358
+ const content = objects(source === "codex" && Array.isArray(payload.output) ? payload.output : payload.content);
359
+ let image = content[block];
360
+ if (inner !== undefined)
361
+ image = objects(image?.content)[inner];
129
362
  const encoded = image?.image_url || object(image?.source).data;
130
363
  const base64 = typeof encoded === "string" ? encoded.replace(/^data:image\/[a-z0-9.+-]+;base64,/i, "") : "";
131
364
  if (!base64 || !/^[A-Za-z0-9+/=\s]+$/.test(base64) || base64.length > 11_184_812)
@@ -135,3 +368,35 @@ export async function historicalImage(file, line, block, source) {
135
368
  throw new BridgeError(413, "This image is too large.");
136
369
  return bytes;
137
370
  }
371
+ /** Derive optional diff scope from local tool-call rows, never phone commands. */
372
+ export async function conversationNamedPaths(file, source, cwd, signal) {
373
+ return withTranscriptIndex(file, async (handle, index) => {
374
+ const paths = new Set();
375
+ for await (const row of index.rows(handle, index.lines, 0, signal)) {
376
+ signal?.throwIfAborted();
377
+ try {
378
+ const raw = row.bytes && visibleEvent(object(JSON.parse(row.bytes.toString())), source);
379
+ if (!raw)
380
+ continue;
381
+ const payload = object(raw.payload), data = object(raw.data);
382
+ const calls = source === "codex" ? (["function_call", "custom_tool_call"].includes(String(payload.type)) ? [payload] : [])
383
+ : source === "copilot" ? (raw.type === "tool.execution_start" ? [data] : [])
384
+ : objects(object(source === "phren" || source === "opencode" ? data.message : raw.message).content).filter(b => b.type === "tool_use");
385
+ for (const call of calls) {
386
+ if (!SHELL_TOOLS.has(String(call.name ?? call.toolName)))
387
+ continue;
388
+ const args = call.arguments ?? call.input;
389
+ const input = typeof args === "string" ? object(JSON.parse(args)) : object(args);
390
+ const command = input.command ?? input.cmd;
391
+ if (typeof command !== "string")
392
+ continue;
393
+ const base = [input.workdir, input.cwd, raw.cwd, cwd].find(v => typeof v === "string" && path.isAbsolute(v));
394
+ for (const named of namedPaths(command))
395
+ paths.add(named.startsWith("~/") ? path.join(homedir(), named.slice(2)) : path.resolve(base, named));
396
+ }
397
+ }
398
+ catch { /* Malformed or private rows grant no additional scope. */ }
399
+ }
400
+ return [...paths];
401
+ }, signal);
402
+ }
@@ -1,4 +1,7 @@
1
1
  import { type Json } from "./protocol.js";
2
+ /** Decode the base64url project folder from a `phren-hook v1 shell` command; undefined when it is not a path. */
3
+ export declare function decodeShellDirectory(encoded: string): string | undefined;
4
+ export declare function shellEnvironment(base?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
2
5
  export declare function health(): Promise<Json>;
3
6
  /** The SSH key is forced to this allowlisted dispatcher. The supplied command is data, never a shell. */
4
7
  export declare function dispatch(command: string): Promise<void>;
@@ -1,10 +1,29 @@
1
+ import { activateModules as moduleSnapshot } from "../modules/runtime.js";
2
+ import { disabledHint } from "../modules/registry.js";
3
+ import { defaultPhrenPath } from "../shared.js";
1
4
  import { connect } from "node:net";
2
5
  import { request } from "node:http";
3
6
  import { spawn } from "node:child_process";
4
7
  import { homedir } from "node:os";
5
8
  import path from "node:path";
6
- import { BridgeError, object, PROTOCOL, serverName, socketPath } from "./protocol.js";
9
+ import { BridgeError, object, PROTOCOL, serverName, socketPath, bridgeRoot, atomic } from "./protocol.js";
7
10
  import { rpc } from "./herdr.js";
11
+ import { launchDirectory } from "./projects.js";
12
+ /** Decode the base64url project folder from a `phren-hook v1 shell` command; undefined when it is not a path. */
13
+ export function decodeShellDirectory(encoded) {
14
+ if (!/^[A-Za-z0-9_-]{1,8192}$/.test(encoded))
15
+ return undefined;
16
+ const decoded = Buffer.from(encoded, "base64url");
17
+ if (decoded.toString("base64url") !== encoded)
18
+ return undefined;
19
+ const dir = decoded.toString("utf8");
20
+ return path.isAbsolute(dir) && !/[\x00-\x1f\x7f]/.test(dir) && !dir.includes("\ufffd") ? dir : undefined;
21
+ }
22
+ export function shellEnvironment(base = process.env) {
23
+ const env = Object.fromEntries(Object.entries(base).filter(([key]) => !key.startsWith("HERDR_")));
24
+ env.PATH = [path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
25
+ return env;
26
+ }
8
27
  export async function health() {
9
28
  return new Promise((resolve, reject) => {
10
29
  const req = request({ socketPath: socketPath(), path: "/v1/health", timeout: 2000 }, response => {
@@ -29,33 +48,95 @@ export async function health() {
29
48
  req.end();
30
49
  });
31
50
  }
51
+ /** `keepWriteOpen` suppresses the client's EOF: the Hook answers one HTTP
52
+ * request and closes the socket itself, while a raw relay (the web preview)
53
+ * needs the EOF forwarded or the far end waits forever. */
54
+ async function pipe(destination, timing, keepWriteOpen = false) {
55
+ // The gateway's own cost, from process start to the first byte the Hook
56
+ // answers with. A loaded machine makes this large even while it is healthy.
57
+ const started = Date.now() - process.uptime() * 1000;
58
+ await new Promise((resolve, reject) => {
59
+ const socket = connect(destination);
60
+ const stop = () => socket.destroy();
61
+ if (timing)
62
+ socket.once("data", () => {
63
+ atomic(timing, { ms: Math.round(Date.now() - started), at: new Date().toISOString() }).catch(() => { });
64
+ });
65
+ // With keepWriteOpen the client's EOF is not forwarded as a FIN: node's
66
+ // HTTP server aborts a half-closed connection whose response has not
67
+ // started yet, which dropped the reply to a large upload whenever the SSH
68
+ // client closed its write side right after the body. The Hook closes the
69
+ // socket itself once it has answered (every request is Connection: close),
70
+ // and that close ends this process.
71
+ const end = () => socket.end();
72
+ socket.on("connect", () => { process.stdin.pipe(socket, { end: !keepWriteOpen }); socket.pipe(process.stdout); });
73
+ socket.on("error", reject);
74
+ socket.on("close", () => {
75
+ process.stdin.unpipe(socket);
76
+ process.stdin.pause();
77
+ process.stdin.removeListener("end", end);
78
+ process.stdout.removeListener("error", stop);
79
+ resolve();
80
+ });
81
+ if (keepWriteOpen)
82
+ process.stdin.once("end", () => { });
83
+ else
84
+ process.stdin.once("end", end);
85
+ process.stdout.once("error", stop);
86
+ });
87
+ }
32
88
  /** The SSH key is forced to this allowlisted dispatcher. The supplied command is data, never a shell. */
33
89
  export async function dispatch(command) {
90
+ const requireHook = () => {
91
+ if (!moduleSnapshot(defaultPhrenPath(), undefined, true).has("hook"))
92
+ throw new BridgeError(404, disabledHint("hook"));
93
+ };
34
94
  if (command === "phren-hook v1 pipe") {
35
- await new Promise((resolve, reject) => {
36
- const socket = connect(socketPath());
37
- socket.on("connect", () => { process.stdin.pipe(socket); socket.pipe(process.stdout); });
38
- socket.on("error", reject);
39
- socket.on("close", () => { process.stdin.unpipe(socket); process.stdin.pause(); resolve(); });
40
- process.stdin.once("end", () => socket.end());
41
- process.stdout.once("error", () => socket.destroy());
42
- });
95
+ requireHook();
96
+ await pipe({ path: socketPath() }, path.join(bridgeRoot(), "gateway.json"), true);
97
+ return;
98
+ }
99
+ // SSH port-forwarding also permits Unix sockets, bypassing the callback and
100
+ // Herdr boundaries. Preview bytes instead use this exact loopback command.
101
+ const preview = /^phren-hook v1 web (127\.0\.0\.1|::1) ([1-9][0-9]{0,4})$/.exec(command);
102
+ if (preview && preview[0] === command && Number(preview[2]) <= 65535) {
103
+ requireHook();
104
+ await pipe({ host: preview[1], port: Number(preview[2]) });
105
+ return;
106
+ }
107
+ // Without Herdr: a login shell, or one agent, in a validated project folder
108
+ // on the SSH PTY itself. Nothing persists after the phone disconnects.
109
+ const shell = /^phren-hook v1 shell ([A-Za-z0-9_-]{1,8192})(?: (codex|claude|copilot|opencode))?$/.exec(command);
110
+ if (shell && shell[0] === command) {
111
+ requireHook();
112
+ const raw = decodeShellDirectory(shell[1]);
113
+ if (!raw)
114
+ throw new BridgeError(403, "The shell folder is not a valid absolute path.");
115
+ const cwd = await launchDirectory(raw);
116
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
117
+ throw new Error("Request an SSH terminal first.");
118
+ const login = process.env.SHELL && path.isAbsolute(process.env.SHELL) ? process.env.SHELL : "/bin/sh";
119
+ const [file, args] = shell[2] ? [shell[2], []] : [login, ["-l"]];
120
+ await attach(file, args, { cwd, env: shellEnvironment() }, shell[2] ? `${shell[2]} exited.` : "The shell exited.");
43
121
  return;
44
122
  }
45
123
  const terminal = /^phren-hook v1 terminal ([A-Za-z0-9_.-]{1,100})$/.exec(command);
46
- if (!terminal)
47
- throw new BridgeError(403, "This SSH key only permits Phren Hook and existing Herdr terminals.");
124
+ if (!terminal || terminal[0] !== command)
125
+ throw new BridgeError(403, "This SSH key only permits Phren Hook, loopback web previews, project shells, and existing Herdr terminals.");
126
+ requireHook();
48
127
  const server = serverName.parse(terminal[1]);
49
128
  if (!process.stdin.isTTY || !process.stdout.isTTY)
50
129
  throw new Error("Request an SSH terminal first.");
51
130
  // Verify the named server exists; never create a workspace or an agent implicitly.
52
131
  await rpc(server, "ping");
53
- const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("HERDR_")));
54
- env.PATH = [path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin"].join(":");
132
+ await attach("herdr", ["session", "attach", server], { env: shellEnvironment() }, "The Herdr terminal disconnected.");
133
+ }
134
+ /** Run one program on the inherited SSH PTY until it exits or the session hangs up. */
135
+ async function attach(file, args, options, failure) {
55
136
  await new Promise((resolve, reject) => {
56
- const child = spawn("herdr", ["session", "attach", server], { env, stdio: "inherit" });
137
+ const child = spawn(file, args, { ...options, stdio: "inherit" });
57
138
  child.once("error", reject);
58
- child.once("exit", code => code === 0 ? resolve() : reject(new Error("The Herdr terminal disconnected.")));
139
+ child.once("exit", code => code === 0 ? resolve() : reject(new Error(failure)));
59
140
  const stop = () => child.kill("SIGHUP");
60
141
  process.once("SIGHUP", stop);
61
142
  process.once("SIGTERM", stop);
@@ -1,2 +1,17 @@
1
1
  export declare function imageBytes(bytes: Buffer): boolean;
2
+ export declare const IMAGE_NAME: RegExp;
3
+ /** Stores a file the phone sent under uploads/<session>/. A name with an
4
+ * image extension must hold image bytes; anything else is kept as-is. */
2
5
  export declare function saveUpload(session: string, name: string, bytes: Buffer): Promise<string>;
6
+ /** What the phone has put in one folder, newest first. */
7
+ export declare function listUploads(session: string): Promise<{
8
+ name: string;
9
+ path: string;
10
+ size: number;
11
+ modified: string;
12
+ }[]>;
13
+ /** The bytes of one image the phone put under uploads/, by the absolute
14
+ * path the transcript names. Served only when the path resolves (through
15
+ * any link) to a regular file inside the uploads folder whose bytes are
16
+ * an image; anything else — outside, traversal, a note — is 404. */
17
+ export declare function uploadImage(requested: string): Promise<Buffer>;