@phren/cli 0.2.14 → 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 (387) 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.d.ts +2 -0
  235. package/dist/init/init-walkthrough.js +17 -6
  236. package/dist/init/init.js +26 -6
  237. package/dist/init/management-preset.d.ts +1 -1
  238. package/dist/init/management-preset.js +2 -2
  239. package/dist/init/preferences.js +1 -1
  240. package/dist/init/self-wiring.js +1 -1
  241. package/dist/init/setup.d.ts +3 -26
  242. package/dist/init/setup.js +49 -588
  243. package/dist/init/shared.js +2 -0
  244. package/dist/init/store-gitignore.d.ts +1 -1
  245. package/dist/init/store-gitignore.js +2 -0
  246. package/dist/init/teardown.d.ts +1 -1
  247. package/dist/init/teardown.js +2 -2
  248. package/dist/link/context.js +1 -1
  249. package/dist/link/doctor.d.ts +22 -1
  250. package/dist/link/doctor.js +100 -54
  251. package/dist/link/link.js +29 -61
  252. package/dist/link/refresh.js +2 -2
  253. package/dist/link/skills.js +26 -5
  254. package/dist/machine-identity.d.ts +3 -0
  255. package/dist/machine-identity.js +6 -0
  256. package/dist/mcp/profile.d.ts +2 -15
  257. package/dist/mcp/profile.js +64 -9
  258. package/dist/memory-ui-graph.runtime.js +279 -283
  259. package/dist/modules/code-package.d.ts +16 -0
  260. package/dist/modules/code-package.js +152 -0
  261. package/dist/modules/command.d.ts +2 -0
  262. package/dist/modules/command.js +67 -0
  263. package/dist/modules/config.d.ts +4 -0
  264. package/dist/modules/config.js +70 -0
  265. package/dist/modules/manifest.d.ts +41 -0
  266. package/dist/modules/manifest.js +1 -0
  267. package/dist/modules/provision.d.ts +3 -0
  268. package/dist/modules/provision.js +84 -0
  269. package/dist/modules/registry.d.ts +16 -0
  270. package/dist/modules/registry.js +250 -0
  271. package/dist/modules/runtime.d.ts +15 -0
  272. package/dist/modules/runtime.js +59 -0
  273. package/dist/package-metadata.js +10 -2
  274. package/dist/phren-dotenv.js +4 -2
  275. package/dist/phren-paths.d.ts +3 -2
  276. package/dist/phren-paths.js +4 -5
  277. package/dist/profile-store.js +4 -5
  278. package/dist/project-config.d.ts +19 -1
  279. package/dist/project-config.js +29 -3
  280. package/dist/project-topics.js +4 -4
  281. package/dist/provider-adapters.js +1 -4
  282. package/dist/query-correlation.js +6 -6
  283. package/dist/session/artifacts.js +5 -5
  284. package/dist/session/checkpoints.js +5 -0
  285. package/dist/session/utils.d.ts +2 -2
  286. package/dist/session/utils.js +6 -6
  287. package/dist/shared/content.d.ts +1 -1
  288. package/dist/shared/content.js +1 -1
  289. package/dist/shared/data-utils.js +1 -1
  290. package/dist/shared/fragment-graph.d.ts +1 -1
  291. package/dist/shared/fragment-graph.js +5 -5
  292. package/dist/shared/index.js +48 -7
  293. package/dist/shared/retrieval.d.ts +18 -1
  294. package/dist/shared/retrieval.js +100 -11
  295. package/dist/shared/search-fallback.js +4 -6
  296. package/dist/shared/sqljs.d.ts +2 -0
  297. package/dist/shared/sqljs.js +4 -2
  298. package/dist/shared.d.ts +0 -1
  299. package/dist/shared.js +0 -1
  300. package/dist/shell/input.d.ts +1 -5
  301. package/dist/shell/input.js +16 -10
  302. package/dist/shell/palette.d.ts +2 -2
  303. package/dist/shell/palette.js +3 -7
  304. package/dist/shell/render.d.ts +3 -1
  305. package/dist/shell/render.js +4 -4
  306. package/dist/shell/shell.js +4 -1
  307. package/dist/shell/types.d.ts +1 -0
  308. package/dist/shell/types.js +4 -0
  309. package/dist/shell/view.d.ts +0 -4
  310. package/dist/shell/view.js +19 -27
  311. package/dist/skill/registry.js +25 -17
  312. package/dist/skill/state.d.ts +3 -0
  313. package/dist/skill/state.js +13 -7
  314. package/dist/status.js +38 -17
  315. package/dist/store-registry.d.ts +44 -18
  316. package/dist/store-registry.js +169 -60
  317. package/dist/store-weight.d.ts +1 -6
  318. package/dist/store-weight.js +4 -2
  319. package/dist/sync/auth-doctor.d.ts +8 -0
  320. package/dist/sync/auth-doctor.js +27 -0
  321. package/dist/sync/auth.d.ts +27 -0
  322. package/dist/sync/auth.js +114 -0
  323. package/dist/sync/conflict-resolve.d.ts +9 -0
  324. package/dist/sync/conflict-resolve.js +146 -0
  325. package/dist/sync/git-state.d.ts +4 -0
  326. package/dist/sync/git-state.js +49 -0
  327. package/dist/sync/outcome.d.ts +34 -0
  328. package/dist/sync/outcome.js +57 -0
  329. package/dist/sync/pull.d.ts +15 -7
  330. package/dist/sync/pull.js +84 -35
  331. package/dist/sync/store-merge.d.ts +29 -0
  332. package/dist/sync/store-merge.js +137 -0
  333. package/dist/sync/task-merge.d.ts +22 -0
  334. package/dist/sync/task-merge.js +158 -0
  335. package/dist/task/github.js +1 -1
  336. package/dist/task/lifecycle.d.ts +5 -0
  337. package/dist/task/lifecycle.js +67 -23
  338. package/dist/terminal-text.d.ts +5 -0
  339. package/dist/terminal-text.js +11 -0
  340. package/dist/test-global-setup.js +7 -0
  341. package/dist/tool-registry.d.ts +1 -1
  342. package/dist/tool-registry.js +3 -1
  343. package/dist/tools/code.d.ts +3 -0
  344. package/dist/tools/code.js +178 -0
  345. package/dist/tools/config.js +5 -0
  346. package/dist/tools/data.js +14 -7
  347. package/dist/tools/dispatch.d.ts +2 -0
  348. package/dist/tools/dispatch.js +66 -0
  349. package/dist/tools/finding.js +43 -41
  350. package/dist/tools/ops.js +5 -2
  351. package/dist/tools/search.js +21 -8
  352. package/dist/tools/session.js +21 -22
  353. package/dist/tools/tasks.js +8 -2
  354. package/dist/tools/types.d.ts +2 -2
  355. package/dist/tools/types.js +2 -2
  356. package/dist/ui/assets.js +1 -1
  357. package/dist/ui/data.js +14 -15
  358. package/dist/ui/deep-void.d.ts +1 -1
  359. package/dist/ui/deep-void.js +0 -1
  360. package/dist/ui/graph-chrome.d.ts +1 -1
  361. package/dist/ui/graph-chrome.js +51 -0
  362. package/dist/ui/page.js +5 -5
  363. package/dist/ui/scripts.js +67 -30
  364. package/dist/ui/server.js +34 -6
  365. package/dist/update.js +1 -1
  366. package/dist/utils-fts.js +1 -0
  367. package/dist/utils-helpers.d.ts +7 -0
  368. package/dist/utils-helpers.js +17 -0
  369. package/dist/utils.d.ts +1 -1
  370. package/dist/utils.js +1 -1
  371. package/package.json +45 -3
  372. package/plugins/opencode/phren-transcript.js +340 -0
  373. package/starter/README.md +4 -4
  374. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  375. package/starter/global/skills/conductor/SKILL.md +106 -0
  376. package/starter/global/skills/fanout/SKILL.md +20 -0
  377. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  378. package/starter/global/skills/phren-init/SKILL.md +4 -4
  379. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  380. package/starter/templates/frontend/reference/README.md +1 -1
  381. package/starter/templates/library/reference/README.md +1 -1
  382. package/starter/templates/monorepo/reference/README.md +1 -1
  383. package/starter/templates/python-project/reference/README.md +1 -1
  384. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  385. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  386. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  387. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,538 @@
1
+ import path from "node:path";
2
+ import { z } from "zod";
3
+ import { saveCodeNote } from "./code-note.js";
4
+ import { handOff } from "./hand-off.js";
5
+ import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
6
+ import { homeDir } from "../home-paths.js";
7
+ import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
8
+ import { dispatchProjectDirectory, dispatchStatus } from "./dispatch.js";
9
+ import { workerStates } from "./dispatch-returns.js";
10
+ import { remoteChildren } from "./dispatch-tree.js";
11
+ import { addGrant, listGrants, removeGrant } from "./grants.js";
12
+ import { optionalHookPeers, peerRequest } from "./peers.js";
13
+ import { candidateRepos, enrollProject } from "./enroll.js";
14
+ import { browseFiles } from "./files.js";
15
+ import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
16
+ import { paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
17
+ import { locateProject } from "./locate.js";
18
+ import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
19
+ import { BridgeError, bridgeRoot, MAX_FRAME, object, objects, PROTOCOL, provider, serverName, targetFromURL, targetSchema } from "./protocol.js";
20
+ import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } from "./simulators.js";
21
+ import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, transcriptPath } from "./transcripts.js";
22
+ import { listUploads, saveUpload, uploadImage } from "./uploads.js";
23
+ import { currentModel, currentStep } from "./steps.js";
24
+ import { healthDetails, listsCaller } from "./health.js";
25
+ import { defaultPhrenPath } from "../shared.js";
26
+ import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
27
+ import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
28
+ import { launchSession, workspaceAction } from "./server-launch.js";
29
+ import { hookMetrics } from "./metrics.js";
30
+ import { streamSpeech } from "./speech.js";
31
+ const CHILD_ACTIVITY_CACHE_MS = 5_000;
32
+ const childActivityCache = new Map();
33
+ async function childActivity(source, session) {
34
+ const key = `${source}\0${session}`, now = Date.now(), cached = childActivityCache.get(key);
35
+ if (cached && now - cached.at < CHILD_ACTIVITY_CACHE_MS)
36
+ return cached.result;
37
+ const result = childAgentTree(source, session).then(tree => {
38
+ const running = tree.flatMap(function visit(child) {
39
+ return [child, ...child.children.flatMap(visit)];
40
+ }).filter(child => child.state === "running");
41
+ return { runningChildren: running.length, childProviders: [...new Set(running.map(child => child.provider))].sort() };
42
+ }).catch(() => ({ runningChildren: 0, childProviders: [] }));
43
+ childActivityCache.set(key, { at: now, result });
44
+ while (childActivityCache.size > 128)
45
+ childActivityCache.delete(childActivityCache.keys().next().value);
46
+ return result;
47
+ }
48
+ export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
49
+ terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
50
+ approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
51
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, transcribe: true };
52
+ export function capabilitiesForModules(snapshot) {
53
+ const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
54
+ const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
55
+ for (const name of ["memory", "tasks", "hook", "git", "schedules"])
56
+ if (snapshot.has(name))
57
+ result[name] = true;
58
+ return result;
59
+ }
60
+ export function requireRoute(snapshot, method, route) {
61
+ const owner = BUILTIN_MODULES.find(module => module.hookRoutes.some(entry => entry.method === method && entry.path === route));
62
+ if (owner && !snapshot.has(owner.name))
63
+ throw new BridgeError(404, disabledHint(owner.name));
64
+ }
65
+ /** Whether the Hook can load @phren/code and, if so, from where. Reported by
66
+ * /v1/health so a phone can explain a missing code package. */
67
+ async function codePackageStatus(store, enabled) {
68
+ if (!enabled)
69
+ return { missing: true };
70
+ const code = await loadCodePackage(store);
71
+ const from = loadedFrom();
72
+ return code && from ? { loadedFrom: from } : { missing: true };
73
+ }
74
+ async function body(request) {
75
+ let size = 0;
76
+ const chunks = [];
77
+ for await (const chunk of request) {
78
+ size += chunk.length;
79
+ if (size > 11_500_000)
80
+ throw new BridgeError(413, "Request is too large.");
81
+ chunks.push(chunk);
82
+ }
83
+ return object(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
84
+ }
85
+ export function selectedServer(url) {
86
+ const mux = url.searchParams.get("mux");
87
+ if (mux && !mux.startsWith("herdr:"))
88
+ throw new BridgeError(400, "Select a Herdr server.");
89
+ return serverName.parse(url.searchParams.get("server") || mux?.slice(6) || "default");
90
+ }
91
+ export function workspacesReader(ctx) {
92
+ const { modules, info, agentHooks, journal, tabActivity, contextUsage } = ctx;
93
+ return async (server, s, watchApprovals) => {
94
+ const lastChanged = await tabActivity.observe(server, s);
95
+ if (watchApprovals)
96
+ agentHooks.overview.renew(server);
97
+ const context = await contextUsage.read(server, s);
98
+ await journal.record(server, objects(s.panes));
99
+ const chatStates = new Map(await Promise.all(objects(s.panes).filter(p => p.agent).map(async (p) => [p, await paneChatState(server, p, { tokenWhenIdentified: false }).catch(() => ({}))])));
100
+ const workspaces = workspaceSnapshot(s, context, agentHooks.pendingPanes(server, s), lastChanged);
101
+ // The branch each tab's agent is on, for the session cards.
102
+ const agentsByTab = new Map();
103
+ for (const pane of objects(s.panes)) {
104
+ if (!pane.agent)
105
+ continue;
106
+ const key = JSON.stringify([pane.workspace_id, pane.tab_id]);
107
+ const agents = agentsByTab.get(key) ?? [];
108
+ agents.push(pane);
109
+ agentsByTab.set(key, agents);
110
+ }
111
+ const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
112
+ let nextTab = 0;
113
+ // Bound transcript and git work across tabs. Each worker owns one
114
+ // response row; snapshot order and target validation are unchanged.
115
+ await Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
116
+ while (nextTab < tabs.length) {
117
+ const { group, tab } = tabs[nextTab++];
118
+ const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
119
+ if (agents.length === 1) {
120
+ const chat = chatStates.get(agents[0]);
121
+ if (chat?.starting === true)
122
+ tab.starting = true;
123
+ if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
124
+ tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id,
125
+ source: agents[0].agent, session: chat.sessionId };
126
+ }
127
+ }
128
+ if (modules.has("git") && typeof tab.cwd === "string" && tab.agent)
129
+ tab.branch = await repositoryBranch(tab.cwd);
130
+ // The model the pane's agent is running, and what it is doing
131
+ // right now, for cards and the lock screen.
132
+ if (agents.length === 1 && provider.safeParse(agents[0].agent).success) {
133
+ const session = chatStates.get(agents[0])?.sessionId;
134
+ tab.runningChildren = 0;
135
+ tab.childProviders = [];
136
+ if (typeof session === "string") {
137
+ const source = agents[0].agent;
138
+ const [model, children] = await Promise.all([
139
+ currentModel(source, session).catch(() => undefined), childActivity(source, session),
140
+ ]);
141
+ if (model)
142
+ tab.model = model;
143
+ tab.runningChildren = children.runningChildren;
144
+ tab.childProviders = children.childProviders;
145
+ if (agents[0].agent_status === "working") {
146
+ const step = await currentStep(source, session).catch(() => undefined);
147
+ if (step)
148
+ tab.currentStep = step;
149
+ }
150
+ }
151
+ }
152
+ }
153
+ }));
154
+ return { ...workspaces, phren: info };
155
+ };
156
+ }
157
+ export function createRouteHandler(ctx) {
158
+ const { version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks, journal, modelCatalog, accountUsage, launches, locatedDirectories, fanoutMessages, canary } = ctx;
159
+ const { conversationReader, childConversationReader, emptyPage } = ctx.streams;
160
+ const readWorkspaces = workspacesReader(ctx);
161
+ return async (request, response) => {
162
+ response.setHeader("X-Phren-Protocol", String(PROTOCOL));
163
+ response.setHeader("Cache-Control", "no-store");
164
+ try {
165
+ const url = new URL(request.url || "/", "http://phren.local");
166
+ if (url.origin !== "http://phren.local")
167
+ throw new BridgeError(400, "Invalid request origin.");
168
+ requireRoute(modules, request.method ?? "", url.pathname);
169
+ let result;
170
+ if (request.method === "GET") {
171
+ switch (url.pathname) {
172
+ case "/v1/health":
173
+ result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
174
+ break;
175
+ case "/v1/metrics":
176
+ result = hookMetrics.snapshot();
177
+ break;
178
+ case "/v1/health/details":
179
+ result = await healthDetails({ hookVersion: version, computerId: computerID, store: scheduleStore,
180
+ scheduler: scheduler ? { running: true, lastTickAt: scheduler.lastTickAt } : undefined, push: agentHooks.push.status });
181
+ break;
182
+ case "/v1/health/peers": {
183
+ // A peer's health probe asks whether this computer lists it back.
184
+ const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
185
+ .parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
186
+ result = { computer: info.computer, version, ...await listsCaller(caller) };
187
+ break;
188
+ }
189
+ case "/v1/dispatch":
190
+ result = { dispatches: await dispatchStatus() };
191
+ break;
192
+ case "/v1/conductor/grants":
193
+ result = { grants: await listGrants() };
194
+ break;
195
+ case "/v1/dispatch/capacity": {
196
+ const live = await servers();
197
+ const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
198
+ result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session),
199
+ working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0) };
200
+ break;
201
+ }
202
+ case "/v1/muxes":
203
+ result = { muxes: await servers() };
204
+ break;
205
+ case "/v1/activity":
206
+ result = { events: await journal.recent() };
207
+ break;
208
+ case "/v1/web-servers":
209
+ result = { servers: await webServers() };
210
+ break;
211
+ case "/v1/simulators":
212
+ result = { simulators: await bootedSimulators() };
213
+ break;
214
+ case "/v1/simulators/screenshot": {
215
+ const bytes = await simulatorScreenshot(String(url.searchParams.get("udid") ?? ""));
216
+ response.setHeader("Content-Type", "image/png");
217
+ response.end(bytes);
218
+ return;
219
+ }
220
+ case "/v1/files":
221
+ result = { files: await listUploads("files") };
222
+ break;
223
+ case "/v1/files/range": {
224
+ let root;
225
+ if (url.searchParams.get("scope") === "uploads") {
226
+ root = path.join(bridgeRoot(), "uploads");
227
+ }
228
+ else if (url.searchParams.has("session")) {
229
+ const target = targetFromURL(url), pane = await validateTarget(target);
230
+ const cwd = await gitRepository(pane, target, url.searchParams.get("child") ?? undefined, url.searchParams.get("worktree") ?? undefined);
231
+ const repository = await gitRoot(cwd);
232
+ if (!repository)
233
+ throw new BridgeError(409, "This pane is not in a project repository.");
234
+ root = repository;
235
+ }
236
+ else {
237
+ const candidates = await locateProject(url.searchParams.get("project") ?? "", await journal.recent());
238
+ const directory = url.searchParams.get("directory");
239
+ const candidate = directory ? candidates.find(item => item.directory === directory) : candidates[0];
240
+ if (!candidate)
241
+ throw new BridgeError(404, "This project folder is not available on this computer.");
242
+ root = candidate.directory;
243
+ }
244
+ result = await readFileRange(root, url.searchParams.get("path") ?? "", rangeInteger(url.searchParams.get("offset"), 0), rangeInteger(url.searchParams.get("length"), MAX_FILE_RANGE), url.searchParams.get("version") ?? undefined);
245
+ break;
246
+ }
247
+ case "/v1/models":
248
+ result = { models: await modelCatalog.list(String(url.searchParams.get("source") ?? "")) };
249
+ break;
250
+ case "/v1/projects/files": {
251
+ const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
252
+ const directory = url.searchParams.get("directory");
253
+ const candidate = directory ? candidates.find(item => item.directory === directory) : candidates[0];
254
+ if (!candidate)
255
+ throw new BridgeError(404, "This project folder is not available on this computer.");
256
+ result = await browseFiles(candidate.directory, url.searchParams.get("path") ?? "");
257
+ break;
258
+ }
259
+ case "/v1/uploads/image": {
260
+ // A picture the phone sent, as the transcript names it by path.
261
+ const bytes = await uploadImage(String(url.searchParams.get("path") ?? ""));
262
+ response.setHeader("Content-Type", "application/octet-stream");
263
+ response.end(bytes);
264
+ return;
265
+ }
266
+ case "/v1/simulators/apps":
267
+ result = { apps: await simulatorApps(String(url.searchParams.get("udid") ?? "")) };
268
+ break;
269
+ case "/v1/usage": {
270
+ // A phone built before OpenCode Go rejects the whole response when it
271
+ // meets a source it does not know, so a client names the sources it
272
+ // understands and an older one gets the original four.
273
+ const known = new Set((url.searchParams.get("sources") ?? "codex,claude,opencode,openrouter").split(",").map(s => s.trim()).filter(Boolean));
274
+ const usage = await accountUsage.read();
275
+ result = { ...usage, accounts: usage.accounts.filter(account => known.has(account.source)) };
276
+ break;
277
+ }
278
+ case "/v1/push/status":
279
+ result = agentHooks.push.status;
280
+ break;
281
+ case "/v1/projects/locate": {
282
+ const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
283
+ for (const candidate of candidates) {
284
+ locatedDirectories.delete(candidate.directory);
285
+ locatedDirectories.add(candidate.directory);
286
+ if (locatedDirectories.size > 128)
287
+ locatedDirectories.delete(locatedDirectories.values().next().value);
288
+ }
289
+ result = { candidates };
290
+ break;
291
+ }
292
+ case "/v1/projects/repos":
293
+ result = { repos: await candidateRepos(await journal.recent()) };
294
+ break;
295
+ case "/v1/workspaces": {
296
+ const server = selectedServer(url);
297
+ result = await readWorkspaces(server, await snapshot(server), url.searchParams.get("watchApprovals") === "1");
298
+ break;
299
+ }
300
+ case "/v1/workspaces/panes":
301
+ result = await panes(selectedServer(url), url.searchParams.get("groupId") || "", url.searchParams.get("childId") || "");
302
+ break;
303
+ case "/v1/transcripts/blob": {
304
+ const target = targetFromURL(url);
305
+ await validateTarget(target);
306
+ const inner = url.searchParams.get("inner");
307
+ const bytes = await historicalImage(await transcriptPath(target.source, target.session), Number(url.searchParams.get("line")), Number(url.searchParams.get("block")), target.source, inner === null ? undefined : Number(inner));
308
+ response.setHeader("Content-Type", "application/octet-stream");
309
+ response.end(bytes);
310
+ return;
311
+ }
312
+ case "/v1/transcripts/history": {
313
+ const target = targetFromURL(url);
314
+ const before = z.coerce.number().int().positive().parse(url.searchParams.get("beforeLine"));
315
+ const abort = new AbortController();
316
+ response.once("close", () => { if (!response.writableEnded)
317
+ abort.abort(); });
318
+ await validateTarget(target);
319
+ const child = url.searchParams.get("child");
320
+ const { reader, source, session } = child === null ? await conversationReader(target) : await childConversationReader(target, child);
321
+ if (reader)
322
+ await refreshTranscript(reader.file, source, session);
323
+ const page = reader ? await reader.read(before, abort.signal) : emptyPage;
324
+ result = { ...page, type: "older", source, session };
325
+ break;
326
+ }
327
+ case "/v1/subagents": {
328
+ const target = targetFromURL(url);
329
+ await validateTarget(target);
330
+ const local = await childAgentTree(target.source, target.session, 0, new Set(), computerID);
331
+ let remote = [];
332
+ let peerError;
333
+ if (url.searchParams.get("remote") !== "0") {
334
+ const { peers, peerError: reason } = await optionalHookPeers();
335
+ peerError = reason;
336
+ remote = await remoteChildren({ provider: target.source, session: target.session, computer: computerID },
337
+ // A worker whose turn finished shows as a completed lead.
338
+ (await dispatchStatus()).map(receipt => receipt.worker?.state === "done" ? { ...receipt, status: "completed" } : receipt), async (receipt) => {
339
+ const peer = peers.find(candidate => candidate.name === receipt.computer);
340
+ const remoteTarget = targetSchema.safeParse(receipt.target);
341
+ if (!peer || !remoteTarget.success)
342
+ return;
343
+ const query = new URLSearchParams(Object.entries(remoteTarget.data).map(([key, value]) => [key, String(value)]));
344
+ query.set("remote", "0");
345
+ const snapshot = await peerRequest(peer, `/v1/subagents?${query}`);
346
+ return { target: remoteTarget.data, computer: snapshot.computer,
347
+ agents: Array.isArray(snapshot.agents) ? snapshot.agents : [] };
348
+ });
349
+ }
350
+ result = { computer: info.computer, agents: publicChildAgents([...local, ...remote]), ...(peerError ? { peerError } : {}) };
351
+ break;
352
+ }
353
+ case "/v1/subagents/messages": {
354
+ result = await fanoutMessages.list(targetFromURL(url), url.searchParams.get("child"));
355
+ break;
356
+ }
357
+ case "/v1/subagents/transcript": {
358
+ const target = targetFromURL(url);
359
+ await validateTarget(target);
360
+ const { reader, source, session } = await childConversationReader(target, z.string().parse(url.searchParams.get("child")));
361
+ const page = await reader.read();
362
+ result = { ...page, type: "backlog", source, session };
363
+ break;
364
+ }
365
+ case "/v1/code/tree":
366
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).tree(url.searchParams.get("project"), url.searchParams.get("directory"));
367
+ break;
368
+ case "/v1/code/recent":
369
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).recent(url.searchParams.get("project"), url.searchParams.get("directory"));
370
+ break;
371
+ case "/v1/code/usage-page":
372
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usagePage(url.searchParams.get("project"), {
373
+ kind: url.searchParams.get("kind"), file: url.searchParams.get("file"), directory: url.searchParams.get("directory"),
374
+ offset: url.searchParams.get("offset"), limit: url.searchParams.get("limit"), end: url.searchParams.get("end"),
375
+ });
376
+ break;
377
+ case "/v1/code/status":
378
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).status(url.searchParams.get("project"));
379
+ break;
380
+ case "/v1/code/search":
381
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).search(url.searchParams.get("project"), url.searchParams.get("q"), url.searchParams.get("kind"), url.searchParams.get("limit"), url.searchParams.get("directory"));
382
+ break;
383
+ case "/v1/code/outline-summary":
384
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outlineSummary(url.searchParams.get("project"), url.searchParams.get("paths"));
385
+ break;
386
+ case "/v1/code/file-references":
387
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).fileReferences(url.searchParams.get("project"), url.searchParams.get("path"));
388
+ break;
389
+ case "/v1/code/outline":
390
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outline(url.searchParams.get("project"), url.searchParams.get("path"));
391
+ break;
392
+ case "/v1/code/definition":
393
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).definition(url.searchParams.get("project"), url.searchParams.get("symbol"));
394
+ break;
395
+ case "/v1/code/references":
396
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).references(url.searchParams.get("project"), url.searchParams.get("symbol"), url.searchParams.get("limit"));
397
+ break;
398
+ case "/v1/code/usage":
399
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usage(url.searchParams.get("project"), url.searchParams.get("top"));
400
+ break;
401
+ default: throw new BridgeError(404, "Unknown Phren Hook route.");
402
+ }
403
+ }
404
+ else if (request.method === "POST") {
405
+ const data = await body(request);
406
+ if (url.pathname === "/v1/subagents/resume") {
407
+ result = await fanoutMessages.send(data);
408
+ }
409
+ else if (url.pathname === "/v1/subagents/archive-finished") {
410
+ result = await fanoutMessages.archiveFinished(data);
411
+ }
412
+ else if (url.pathname === "/v1/code/disable") {
413
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true)))
414
+ .disable(z.string().parse(data.project));
415
+ }
416
+ else if (url.pathname === "/v1/code/reindex") {
417
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true)))
418
+ .reindex(z.string().parse(data.project));
419
+ }
420
+ else if (url.pathname === "/v1/code/note") {
421
+ result = await saveCodeNote(await resolveCodeStore(scheduleStore, typeof data.store === "string" ? data.store : undefined, true), data, dispatches ? async (note, prompt) => {
422
+ if (note.target && "session" in note.target)
423
+ return handOff({ session: note.target.session, project: note.project, text: prompt });
424
+ return dispatches.dispatch({ computer: "anywhere", project: note.project,
425
+ harness: note.target && "harness" in note.target ? note.target.harness : "codex", prompt, label: `Code note: ${note.symbol}`.slice(0, 200) });
426
+ } : undefined);
427
+ }
428
+ else if (url.pathname === "/v1/schedules") {
429
+ result = await scheduler.statuses();
430
+ }
431
+ else if (url.pathname === "/v1/schedules/run") {
432
+ const input = z.object({ project: z.string().min(1).max(200), id: z.string().regex(/^[a-f0-9]{8}$/) }).parse(data);
433
+ result = { ok: true, run: await scheduler.launchNow(input.project, input.id) };
434
+ }
435
+ else if (url.pathname === "/v1/schedules/history") {
436
+ const input = z.object({ project: z.string().min(1).max(200).optional(), id: z.string().regex(/^[a-f0-9]{8}$/).optional(),
437
+ limit: z.number().int().min(1).max(500).optional() }).parse(data);
438
+ result = { runs: await scheduler.history(input) };
439
+ }
440
+ else if (url.pathname === "/v1/canary") {
441
+ result = await canary("manual");
442
+ }
443
+ else if (url.pathname === "/v1/speech") {
444
+ // Audio, not JSON: the route writes its own response.
445
+ await streamSpeech(data, response);
446
+ return;
447
+ }
448
+ else if (url.pathname === "/v1/dispatch") {
449
+ // `origin` is the caller's own pane, added by the MCP tool or CLI from Herdr's variables.
450
+ const { origin, ...brief } = data;
451
+ result = await dispatches.dispatch(brief, origin);
452
+ }
453
+ else if (url.pathname === "/v1/dispatch/workers") {
454
+ result = await workerStates(data);
455
+ }
456
+ else if (url.pathname === "/v1/dispatch/returns") {
457
+ result = { returns: await ctx.returns.take() };
458
+ }
459
+ else if (url.pathname === "/v1/conductor/grants") {
460
+ result = { ok: true, grant: await addGrant(data) };
461
+ }
462
+ else if (url.pathname === "/v1/push/register") {
463
+ // Registration is kept for when a key is added; the reply says whether push works now.
464
+ await agentHooks.push.register(data);
465
+ result = { ok: true, configured: agentHooks.push.status.configured };
466
+ }
467
+ else if (url.pathname === "/v1/push/answer") {
468
+ await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
469
+ result = { ok: true };
470
+ }
471
+ else if (url.pathname === "/v1/push/target") {
472
+ // A tapped notification opens its session; the binding stays unspent.
473
+ const target = agentHooks.pushTarget(z.string().uuid().parse(data.binding));
474
+ if (!target)
475
+ throw new BridgeError(409, "This approval is no longer pending.");
476
+ result = { target: { server: target.server, workspace: target.workspace, tab: target.tab, pane: target.pane, source: target.source } };
477
+ }
478
+ else if (url.pathname === "/v1/files") {
479
+ // Files the phone keeps on this computer, outside any session.
480
+ const { name, bytes } = uploadBody(data);
481
+ result = { ok: true, path: await saveUpload("files", name, bytes) };
482
+ }
483
+ else if (url.pathname === "/v1/projects/add") {
484
+ // Enrolling a repository with phren from the phone: an existing
485
+ // checkout, or a clone. Serialized like launches — one at a time.
486
+ result = await launches.run(async () => enrollProject(z.object({ directory: z.string().max(4096).optional(), cloneUrl: z.string().max(512).optional() }).parse(data)));
487
+ }
488
+ else if (url.pathname === "/v1/simulators/action") {
489
+ result = await simulatorAct(z.string().parse(data.udid), z.object({ action: z.string(), bundleId: z.string().optional(), url: z.string().optional(), x: z.number().optional(), y: z.number().optional(), text: z.string().optional(), submit: z.boolean().optional() }).parse(data));
490
+ }
491
+ else {
492
+ if (url.pathname === "/v1/workspaces/launch") {
493
+ result = await launches.run(async () => {
494
+ if (data.role === "conductor" && !modules.has("conductor"))
495
+ throw new BridgeError(404, disabledHint("conductor"));
496
+ if (data.project !== undefined && data.cwd !== undefined)
497
+ throw new BridgeError(400, "Choose project or cwd, not both.");
498
+ // A conductor belongs to no one project: without a folder it starts in
499
+ // this computer's phren store and dispatches into any project from there.
500
+ const storeRooted = data.role === "conductor" && data.project === undefined && (data.cwd === undefined || data.cwd === "");
501
+ const cwd = storeRooted ? await launchDirectory(defaultPhrenPath(), [], [defaultPhrenPath()])
502
+ : data.project !== undefined ? await dispatchProjectDirectory(data.project)
503
+ : await launchDirectory(data.cwd, await journal.recent(), locatedDirectories);
504
+ return launchSession(selectedServer(url), { ...data, cwd });
505
+ });
506
+ }
507
+ else if (url.pathname.startsWith("/v1/workspaces/")) {
508
+ const operation = url.pathname.split("/").at(-1);
509
+ result = operation === "create" ? await launches.run(async () => workspaceAction(selectedServer(url), operation, { ...data, cwd: await launchDirectory(data.cwd ?? homeDir(), await journal.recent(), locatedDirectories) }))
510
+ : await workspaceAction(selectedServer(url), operation, data);
511
+ }
512
+ else {
513
+ result = await paneRoute(ctx, url, data, response);
514
+ }
515
+ }
516
+ }
517
+ else if (request.method === "DELETE") {
518
+ if (url.pathname !== "/v1/conductor/grants")
519
+ throw new BridgeError(404, "Unknown Phren Hook route.");
520
+ const data = await body(request);
521
+ result = { ok: true, grant: await removeGrant(data) };
522
+ }
523
+ else
524
+ throw new BridgeError(405, "Unsupported request method.");
525
+ const payload = JSON.stringify(result);
526
+ if (Buffer.byteLength(payload) > MAX_FRAME)
527
+ throw new BridgeError(413, "The response is too large.");
528
+ response.setHeader("Content-Type", "application/json");
529
+ response.end(payload);
530
+ }
531
+ catch (error) {
532
+ response.statusCode = error instanceof BridgeError ? error.status : error instanceof z.ZodError || error instanceof SyntaxError ? 400 : 503;
533
+ response.setHeader("Content-Type", "application/json");
534
+ response.end(JSON.stringify({ error: error instanceof BridgeError ? error.message : "Phren Hook could not complete this request. Run phren bridge doctor on the computer.",
535
+ ...(error instanceof BridgeError ? error.details : {}) }));
536
+ }
537
+ };
538
+ }
@@ -0,0 +1,46 @@
1
+ import { WebSocket } from "ws";
2
+ import type { AgentHooks } from "./agent-hooks.js";
3
+ import { type Provider, type Target } from "./protocol.js";
4
+ import type { CodexQuestions } from "./questions.js";
5
+ import type { HookInfo } from "./server-routes.js";
6
+ import type { SideQuestions } from "./side-questions.js";
7
+ import { TranscriptReader } from "./transcripts.js";
8
+ import type { ModuleSnapshot } from "../modules/runtime.js";
9
+ /** The WebSocket transcript and status streams: the backlog, appended rows and
10
+ * previews on a tick loop, older pages on request, and the pane's status. */
11
+ export interface StreamContext {
12
+ modules: ModuleSnapshot;
13
+ agentHooks: AgentHooks;
14
+ codexQuestions: CodexQuestions;
15
+ sideQuestions?: SideQuestions;
16
+ info: HookInfo;
17
+ activeCapabilities: Record<string, unknown>;
18
+ }
19
+ export type TranscriptStreams = ReturnType<typeof transcriptStreams>;
20
+ /**
21
+ * Why a transcript or status stream closed. Only a real target change (the
22
+ * 409 validation) says the conversation changed; I/O, parse and git failures
23
+ * keep their own words, with absolute paths cut to their last component and
24
+ * the reason bounded to WebSocket's 123-byte close limit.
25
+ */
26
+ export declare function streamCloseReason(error: unknown): string;
27
+ export declare function transcriptStreams(ctx: StreamContext): {
28
+ conversationReader: (target: Target) => Promise<{
29
+ reader?: TranscriptReader;
30
+ source: Provider;
31
+ session: string;
32
+ }>;
33
+ childConversationReader: (target: Target, child: string) => Promise<{
34
+ reader: TranscriptReader;
35
+ source: "claude" | "codex" | "copilot" | "opencode" | "phren";
36
+ session: string;
37
+ }>;
38
+ emptyPage: {
39
+ entries: never[];
40
+ totalLines: number;
41
+ startLine: number;
42
+ hasMore: boolean;
43
+ reset: boolean;
44
+ };
45
+ stream: (client: WebSocket, url: URL) => Promise<void>;
46
+ };