@phren/cli 0.2.15 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-instructions.d.ts +12 -0
  3. package/dist/agent-instructions.js +52 -0
  4. package/dist/bridge/agent-hook-stores.d.ts +32 -0
  5. package/dist/bridge/agent-hook-stores.js +67 -0
  6. package/dist/bridge/agent-hooks.d.ts +195 -2
  7. package/dist/bridge/agent-hooks.js +1049 -38
  8. package/dist/bridge/canary.d.ts +27 -0
  9. package/dist/bridge/canary.js +189 -0
  10. package/dist/bridge/changes.d.ts +57 -0
  11. package/dist/bridge/changes.js +403 -0
  12. package/dist/bridge/client.d.ts +3 -0
  13. package/dist/bridge/client.js +36 -0
  14. package/dist/bridge/code-note.d.ts +23 -0
  15. package/dist/bridge/code-note.js +51 -0
  16. package/dist/bridge/code-routes.d.ts +151 -0
  17. package/dist/bridge/code-routes.js +442 -0
  18. package/dist/bridge/codex-threads.d.ts +27 -0
  19. package/dist/bridge/codex-threads.js +442 -0
  20. package/dist/bridge/command.d.ts +7 -0
  21. package/dist/bridge/command.js +50 -5
  22. package/dist/bridge/computer-names.d.ts +4 -0
  23. package/dist/bridge/computer-names.js +16 -0
  24. package/dist/bridge/computers.d.ts +9 -0
  25. package/dist/bridge/computers.js +111 -0
  26. package/dist/bridge/context.d.ts +14 -0
  27. package/dist/bridge/context.js +149 -0
  28. package/dist/bridge/dispatch-command.d.ts +3 -0
  29. package/dist/bridge/dispatch-command.js +93 -0
  30. package/dist/bridge/dispatch-hosts.d.ts +23 -0
  31. package/dist/bridge/dispatch-hosts.js +25 -0
  32. package/dist/bridge/dispatch-returns.d.ts +125 -0
  33. package/dist/bridge/dispatch-returns.js +283 -0
  34. package/dist/bridge/dispatch-tree.d.ts +54 -0
  35. package/dist/bridge/dispatch-tree.js +198 -0
  36. package/dist/bridge/dispatch.d.ts +210 -0
  37. package/dist/bridge/dispatch.js +286 -0
  38. package/dist/bridge/enroll.d.ts +31 -0
  39. package/dist/bridge/enroll.js +236 -0
  40. package/dist/bridge/fanout-messages.d.ts +74 -0
  41. package/dist/bridge/fanout-messages.js +230 -0
  42. package/dist/bridge/fanouts.d.ts +160 -0
  43. package/dist/bridge/fanouts.js +702 -0
  44. package/dist/bridge/file-range.d.ts +16 -0
  45. package/dist/bridge/file-range.js +90 -0
  46. package/dist/bridge/files.d.ts +20 -0
  47. package/dist/bridge/files.js +54 -0
  48. package/dist/bridge/git-publish.d.ts +23 -0
  49. package/dist/bridge/git-publish.js +145 -0
  50. package/dist/bridge/git-worktrees.d.ts +21 -0
  51. package/dist/bridge/git-worktrees.js +150 -0
  52. package/dist/bridge/git.d.ts +54 -0
  53. package/dist/bridge/git.js +552 -0
  54. package/dist/bridge/grants.d.ts +31 -0
  55. package/dist/bridge/grants.js +181 -0
  56. package/dist/bridge/hand-off.d.ts +79 -0
  57. package/dist/bridge/hand-off.js +151 -0
  58. package/dist/bridge/health.d.ts +128 -0
  59. package/dist/bridge/health.js +260 -0
  60. package/dist/bridge/herdr.d.ts +79 -6
  61. package/dist/bridge/herdr.js +292 -27
  62. package/dist/bridge/hook-main.js +2 -0
  63. package/dist/bridge/install.d.ts +28 -1
  64. package/dist/bridge/install.js +225 -38
  65. package/dist/bridge/launch-worktree.d.ts +21 -0
  66. package/dist/bridge/launch-worktree.js +70 -0
  67. package/dist/bridge/limits.d.ts +20 -0
  68. package/dist/bridge/limits.js +65 -0
  69. package/dist/bridge/locate.d.ts +16 -0
  70. package/dist/bridge/locate.js +75 -0
  71. package/dist/bridge/metrics.d.ts +29 -0
  72. package/dist/bridge/metrics.js +71 -0
  73. package/dist/bridge/model-switch.d.ts +35 -0
  74. package/dist/bridge/model-switch.js +250 -0
  75. package/dist/bridge/models.d.ts +46 -0
  76. package/dist/bridge/models.js +257 -0
  77. package/dist/bridge/opencode-approvals.d.ts +6 -0
  78. package/dist/bridge/opencode-approvals.js +60 -0
  79. package/dist/bridge/pane-text.d.ts +15 -0
  80. package/dist/bridge/pane-text.js +23 -0
  81. package/dist/bridge/peers.d.ts +27 -0
  82. package/dist/bridge/peers.js +130 -0
  83. package/dist/bridge/projects.d.ts +12 -1
  84. package/dist/bridge/projects.js +268 -20
  85. package/dist/bridge/protocol.d.ts +35 -2
  86. package/dist/bridge/protocol.js +61 -7
  87. package/dist/bridge/push.d.ts +83 -0
  88. package/dist/bridge/push.js +199 -0
  89. package/dist/bridge/questions.d.ts +38 -0
  90. package/dist/bridge/questions.js +205 -0
  91. package/dist/bridge/schedule-format.d.ts +103 -0
  92. package/dist/bridge/schedule-format.js +266 -0
  93. package/dist/bridge/schedule-launch.d.ts +11 -0
  94. package/dist/bridge/schedule-launch.js +169 -0
  95. package/dist/bridge/schedule-watch.d.ts +54 -0
  96. package/dist/bridge/schedule-watch.js +255 -0
  97. package/dist/bridge/schedules.d.ts +48 -0
  98. package/dist/bridge/schedules.js +205 -0
  99. package/dist/bridge/server-launch.d.ts +14 -0
  100. package/dist/bridge/server-launch.js +218 -0
  101. package/dist/bridge/server-overview.d.ts +45 -0
  102. package/dist/bridge/server-overview.js +102 -0
  103. package/dist/bridge/server-pane-routes.d.ts +36 -0
  104. package/dist/bridge/server-pane-routes.js +479 -0
  105. package/dist/bridge/server-routes.d.ts +108 -0
  106. package/dist/bridge/server-routes.js +556 -0
  107. package/dist/bridge/server-stream.d.ts +46 -0
  108. package/dist/bridge/server-stream.js +253 -0
  109. package/dist/bridge/server.d.ts +3 -15
  110. package/dist/bridge/server.js +162 -264
  111. package/dist/bridge/session-servers.d.ts +24 -0
  112. package/dist/bridge/session-servers.js +136 -0
  113. package/dist/bridge/side-questions.d.ts +74 -0
  114. package/dist/bridge/side-questions.js +252 -0
  115. package/dist/bridge/simulators.d.ts +28 -0
  116. package/dist/bridge/simulators.js +198 -0
  117. package/dist/bridge/speech-transcribe.d.ts +24 -0
  118. package/dist/bridge/speech-transcribe.js +124 -0
  119. package/dist/bridge/speech.d.ts +35 -0
  120. package/dist/bridge/speech.js +98 -0
  121. package/dist/bridge/steps.d.ts +13 -0
  122. package/dist/bridge/steps.js +222 -0
  123. package/dist/bridge/tab-activity.d.ts +18 -0
  124. package/dist/bridge/tab-activity.js +99 -0
  125. package/dist/bridge/terminal-choice.d.ts +64 -0
  126. package/dist/bridge/terminal-choice.js +281 -0
  127. package/dist/bridge/transcript-claude.d.ts +22 -0
  128. package/dist/bridge/transcript-claude.js +353 -0
  129. package/dist/bridge/transcript-codex.d.ts +30 -0
  130. package/dist/bridge/transcript-codex.js +282 -0
  131. package/dist/bridge/transcript-copilot.d.ts +4 -0
  132. package/dist/bridge/transcript-copilot.js +14 -0
  133. package/dist/bridge/transcript-opencode.d.ts +5 -0
  134. package/dist/bridge/transcript-opencode.js +26 -0
  135. package/dist/bridge/transcript-preview.d.ts +96 -0
  136. package/dist/bridge/transcript-preview.js +491 -0
  137. package/dist/bridge/transcripts.d.ts +81 -4
  138. package/dist/bridge/transcripts.js +332 -67
  139. package/dist/bridge/transport.d.ts +3 -0
  140. package/dist/bridge/transport.js +96 -15
  141. package/dist/bridge/uploads.d.ts +15 -0
  142. package/dist/bridge/uploads.js +44 -2
  143. package/dist/bridge/usage.d.ts +124 -0
  144. package/dist/bridge/usage.js +859 -0
  145. package/dist/bridge-hook.mjs +46545 -21051
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-policy.js +25 -0
  148. package/dist/cli/config-proactivity.d.ts +3 -1
  149. package/dist/cli/config-proactivity.js +35 -3
  150. package/dist/cli/config.js +4 -1
  151. package/dist/cli/extract.d.ts +0 -8
  152. package/dist/cli/extract.js +4 -7
  153. package/dist/cli/govern.js +5 -2
  154. package/dist/cli/hooks-globs.js +1 -1
  155. package/dist/cli/hooks.d.ts +1 -1
  156. package/dist/cli/hooks.js +9 -7
  157. package/dist/cli/namespaces-projects.js +12 -6
  158. package/dist/cli/namespaces-store.js +37 -6
  159. package/dist/cli/namespaces-tasks.js +1 -1
  160. package/dist/cli/schedules.d.ts +1 -0
  161. package/dist/cli/schedules.js +164 -0
  162. package/dist/cli/session-background.js +1 -1
  163. package/dist/cli/session-git.d.ts +8 -5
  164. package/dist/cli/session-git.js +45 -120
  165. package/dist/cli/session-start.js +3 -1
  166. package/dist/cli/session-stop.js +19 -8
  167. package/dist/cli/team.js +13 -10
  168. package/dist/cli-handlers.d.ts +1 -1
  169. package/dist/cli-handlers.js +8 -4
  170. package/dist/cli-help.d.ts +5 -4
  171. package/dist/cli-help.js +15 -15
  172. package/dist/cli-registry.d.ts +4 -1
  173. package/dist/cli-registry.js +119 -6
  174. package/dist/content/archive.js +2 -2
  175. package/dist/content/citation.d.ts +11 -0
  176. package/dist/content/citation.js +18 -0
  177. package/dist/content/learning.js +2 -0
  178. package/dist/content/summarize.d.ts +14 -15
  179. package/dist/content/summarize.js +60 -5
  180. package/dist/content/validate.d.ts +17 -4
  181. package/dist/content/validate.js +200 -122
  182. package/dist/core/project-registry.d.ts +26 -0
  183. package/dist/core/project-registry.js +573 -0
  184. package/dist/core/project.js +2 -3
  185. package/dist/data/access.d.ts +16 -1
  186. package/dist/data/access.js +31 -3
  187. package/dist/data/tasks.d.ts +18 -3
  188. package/dist/data/tasks.js +8 -7
  189. package/dist/entrypoint.js +44 -10
  190. package/dist/fanout/adapters/claude.d.ts +2 -0
  191. package/dist/fanout/adapters/claude.js +7 -0
  192. package/dist/fanout/adapters/codex.d.ts +2 -0
  193. package/dist/fanout/adapters/codex.js +9 -0
  194. package/dist/fanout/adapters/opencode.d.ts +4 -0
  195. package/dist/fanout/adapters/opencode.js +9 -0
  196. package/dist/fanout/adapters/types.d.ts +21 -0
  197. package/dist/fanout/adapters/types.js +3 -0
  198. package/dist/fanout/command.d.ts +2 -0
  199. package/dist/fanout/command.js +78 -0
  200. package/dist/fanout/launcher.d.ts +27 -0
  201. package/dist/fanout/launcher.js +156 -0
  202. package/dist/fanout/opencode-serve.d.ts +24 -0
  203. package/dist/fanout/opencode-serve.js +191 -0
  204. package/dist/fanout/picker.d.ts +91 -0
  205. package/dist/fanout/picker.js +51 -0
  206. package/dist/fanout/usage.d.ts +5 -0
  207. package/dist/fanout/usage.js +51 -0
  208. package/dist/fanout/watchdog.d.ts +10 -0
  209. package/dist/fanout/watchdog.js +27 -0
  210. package/dist/filenames.d.ts +9 -0
  211. package/dist/filenames.js +11 -0
  212. package/dist/finding/context.js +4 -22
  213. package/dist/generated/memory-ui-graph.browser.js +525 -419
  214. package/dist/governance/policy-constants.d.ts +11 -0
  215. package/dist/governance/policy-constants.js +9 -0
  216. package/dist/governance/policy.d.ts +5 -8
  217. package/dist/governance/policy.js +11 -8
  218. package/dist/graph-core/camera.d.ts +24 -0
  219. package/dist/graph-core/camera.js +18 -0
  220. package/dist/graph-core/index.d.ts +2 -0
  221. package/dist/graph-core/index.js +2 -0
  222. package/dist/graph-core/labels.d.ts +77 -0
  223. package/dist/graph-core/labels.js +124 -0
  224. package/dist/graph-core/model.d.ts +13 -0
  225. package/dist/graph-core/model.js +33 -0
  226. package/dist/graph-core/types.d.ts +2 -0
  227. package/dist/home-paths.d.ts +7 -0
  228. package/dist/home-paths.js +21 -0
  229. package/dist/hooks.d.ts +3 -15
  230. package/dist/hooks.js +14 -1
  231. package/dist/index.js +24 -2
  232. package/dist/init/guard-globals.d.ts +1 -1
  233. package/dist/init/guard-globals.js +4 -4
  234. package/dist/init/init-configure.js +3 -3
  235. package/dist/init/init-uninstall.js +15 -5
  236. package/dist/init/init-walkthrough.js +1 -1
  237. package/dist/init/init.js +26 -6
  238. package/dist/init/management-preset.d.ts +1 -1
  239. package/dist/init/management-preset.js +2 -2
  240. package/dist/init/preferences.js +1 -1
  241. package/dist/init/self-wiring.js +1 -1
  242. package/dist/init/setup.d.ts +3 -26
  243. package/dist/init/setup.js +68 -593
  244. package/dist/init/shared.js +2 -0
  245. package/dist/init/store-gitignore.d.ts +1 -6
  246. package/dist/init/store-gitignore.js +2 -8
  247. package/dist/init/teardown.d.ts +1 -1
  248. package/dist/init/teardown.js +2 -2
  249. package/dist/link/context-imports.d.ts +15 -0
  250. package/dist/link/context-imports.js +101 -0
  251. package/dist/link/context.js +1 -1
  252. package/dist/link/doctor.d.ts +22 -1
  253. package/dist/link/doctor.js +128 -58
  254. package/dist/link/link.js +29 -61
  255. package/dist/link/refresh.js +2 -2
  256. package/dist/link/skills.js +26 -5
  257. package/dist/machine-identity.d.ts +3 -0
  258. package/dist/machine-identity.js +6 -0
  259. package/dist/mcp/profile.d.ts +2 -19
  260. package/dist/mcp/profile.js +64 -22
  261. package/dist/memory-ui-graph.runtime.js +525 -419
  262. package/dist/modules/code-package.d.ts +16 -0
  263. package/dist/modules/code-package.js +160 -0
  264. package/dist/modules/command.d.ts +2 -0
  265. package/dist/modules/command.js +67 -0
  266. package/dist/modules/config.d.ts +4 -0
  267. package/dist/modules/config.js +70 -0
  268. package/dist/modules/manifest.d.ts +41 -0
  269. package/dist/modules/manifest.js +1 -0
  270. package/dist/modules/provision.d.ts +3 -0
  271. package/dist/modules/provision.js +84 -0
  272. package/dist/modules/registry.d.ts +16 -0
  273. package/dist/modules/registry.js +250 -0
  274. package/dist/modules/runtime.d.ts +15 -0
  275. package/dist/modules/runtime.js +59 -0
  276. package/dist/package-metadata.js +10 -2
  277. package/dist/phren-dotenv.js +4 -2
  278. package/dist/phren-paths.d.ts +3 -2
  279. package/dist/phren-paths.js +4 -5
  280. package/dist/profile-store.js +43 -8
  281. package/dist/project-config.d.ts +19 -1
  282. package/dist/project-config.js +29 -3
  283. package/dist/project-topics.d.ts +1 -0
  284. package/dist/project-topics.js +13 -10
  285. package/dist/provider-adapters.js +1 -4
  286. package/dist/query-correlation.js +6 -6
  287. package/dist/session/artifacts.js +5 -5
  288. package/dist/session/checkpoints.js +5 -0
  289. package/dist/session/utils.d.ts +2 -2
  290. package/dist/session/utils.js +6 -6
  291. package/dist/shared/content.d.ts +1 -1
  292. package/dist/shared/content.js +1 -1
  293. package/dist/shared/data-utils.js +1 -1
  294. package/dist/shared/fragment-graph.d.ts +1 -1
  295. package/dist/shared/fragment-graph.js +5 -5
  296. package/dist/shared/index.js +48 -7
  297. package/dist/shared/retrieval.d.ts +18 -3
  298. package/dist/shared/retrieval.js +101 -12
  299. package/dist/shared/search-fallback.js +4 -6
  300. package/dist/shared/sqljs.d.ts +2 -0
  301. package/dist/shared/sqljs.js +4 -2
  302. package/dist/shared.d.ts +0 -1
  303. package/dist/shared.js +0 -1
  304. package/dist/shell/input.d.ts +1 -5
  305. package/dist/shell/input.js +16 -10
  306. package/dist/shell/palette.d.ts +2 -2
  307. package/dist/shell/palette.js +3 -7
  308. package/dist/shell/render.d.ts +3 -1
  309. package/dist/shell/render.js +4 -4
  310. package/dist/shell/shell.js +4 -1
  311. package/dist/shell/types.d.ts +1 -0
  312. package/dist/shell/types.js +4 -0
  313. package/dist/shell/view.d.ts +0 -4
  314. package/dist/shell/view.js +19 -27
  315. package/dist/skill/registry.js +25 -17
  316. package/dist/skill/state.d.ts +3 -0
  317. package/dist/skill/state.js +13 -7
  318. package/dist/status.js +38 -17
  319. package/dist/store-registry.d.ts +44 -18
  320. package/dist/store-registry.js +169 -60
  321. package/dist/store-weight.d.ts +1 -6
  322. package/dist/store-weight.js +4 -2
  323. package/dist/sync/auth-doctor.d.ts +8 -0
  324. package/dist/sync/auth-doctor.js +27 -0
  325. package/dist/sync/auth.d.ts +27 -0
  326. package/dist/sync/auth.js +114 -0
  327. package/dist/sync/conflict-resolve.d.ts +9 -0
  328. package/dist/sync/conflict-resolve.js +146 -0
  329. package/dist/sync/git-state.d.ts +4 -0
  330. package/dist/sync/git-state.js +49 -0
  331. package/dist/sync/outcome.d.ts +34 -0
  332. package/dist/sync/outcome.js +57 -0
  333. package/dist/sync/pull.d.ts +15 -7
  334. package/dist/sync/pull.js +84 -35
  335. package/dist/sync/store-merge.d.ts +29 -0
  336. package/dist/sync/store-merge.js +137 -0
  337. package/dist/sync/task-merge.d.ts +22 -0
  338. package/dist/sync/task-merge.js +158 -0
  339. package/dist/task/github.js +1 -1
  340. package/dist/task/lifecycle.d.ts +5 -0
  341. package/dist/task/lifecycle.js +67 -23
  342. package/dist/terminal-text.d.ts +5 -0
  343. package/dist/terminal-text.js +11 -0
  344. package/dist/test-global-setup.js +7 -0
  345. package/dist/tool-registry.d.ts +1 -1
  346. package/dist/tool-registry.js +3 -1
  347. package/dist/tools/code.d.ts +3 -0
  348. package/dist/tools/code.js +186 -0
  349. package/dist/tools/config.js +8 -0
  350. package/dist/tools/data.js +14 -7
  351. package/dist/tools/dispatch.d.ts +2 -0
  352. package/dist/tools/dispatch.js +66 -0
  353. package/dist/tools/finding.d.ts +11 -0
  354. package/dist/tools/finding.js +180 -123
  355. package/dist/tools/ops.js +5 -2
  356. package/dist/tools/search.js +21 -8
  357. package/dist/tools/session.js +21 -22
  358. package/dist/tools/tasks.js +8 -2
  359. package/dist/tools/types.d.ts +2 -2
  360. package/dist/tools/types.js +2 -2
  361. package/dist/ui/assets.js +1 -1
  362. package/dist/ui/data.js +14 -15
  363. package/dist/ui/deep-void.d.ts +1 -1
  364. package/dist/ui/deep-void.js +0 -1
  365. package/dist/ui/graph-chrome.d.ts +1 -1
  366. package/dist/ui/graph-chrome.js +51 -0
  367. package/dist/ui/page.js +5 -5
  368. package/dist/ui/scripts.js +67 -30
  369. package/dist/ui/server.js +52 -7
  370. package/dist/update.js +22 -11
  371. package/dist/utils-fts.js +1 -0
  372. package/dist/utils-helpers.d.ts +7 -0
  373. package/dist/utils-helpers.js +17 -0
  374. package/dist/utils.d.ts +1 -1
  375. package/dist/utils.js +1 -1
  376. package/package.json +49 -7
  377. package/plugins/opencode/phren-transcript.js +340 -0
  378. package/starter/README.md +4 -4
  379. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  380. package/starter/global/skills/conductor/SKILL.md +106 -0
  381. package/starter/global/skills/fanout/SKILL.md +20 -0
  382. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  383. package/starter/global/skills/phren-init/SKILL.md +4 -4
  384. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  385. package/starter/templates/frontend/reference/README.md +1 -1
  386. package/starter/templates/library/reference/README.md +1 -1
  387. package/starter/templates/monorepo/reference/README.md +1 -1
  388. package/starter/templates/python-project/reference/README.md +1 -1
  389. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  390. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  391. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  392. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,218 @@
1
+ import { mkdir, readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { z } from "zod";
5
+ import { homeDir } from "../home-paths.js";
6
+ import { agentNames, findPane, isConductorName, paneAgentName, paneChatState, paneIdentity, rpc, servers, snapshot } from "./herdr.js";
7
+ import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
8
+ import { atomic, BridgeError, bridgeRoot, id, objects, provider } from "./protocol.js";
9
+ /** Starting agents in Herdr from the phone: the launch route's harness
10
+ * arguments, the conductor brief, and workspace, tab and pane actions. */
11
+ const launchKinds = ["codex", "claude", "copilot", "opencode"];
12
+ const plainText = (max) => z.string().min(1).max(max).refine(t => !/[\x00-\x1f\x7f]/.test(t));
13
+ async function conductorBrief() {
14
+ let source;
15
+ if (typeof CONDUCTOR_SKILL_SOURCE === "string")
16
+ source = CONDUCTOR_SKILL_SOURCE;
17
+ else {
18
+ const here = path.dirname(fileURLToPath(import.meta.url));
19
+ for (const candidate of [
20
+ path.join(here, "..", "starter", "global", "skills", "conductor", "SKILL.md"),
21
+ path.join(here, "..", "..", "starter", "global", "skills", "conductor", "SKILL.md"),
22
+ ]) {
23
+ source = await readFile(candidate, "utf8").catch(() => undefined);
24
+ if (source !== undefined)
25
+ break;
26
+ }
27
+ }
28
+ if (source === undefined)
29
+ throw new BridgeError(503, "The shipped conductor brief is unavailable. Reinstall Phren Hook.");
30
+ const match = /^---\r?\n[\s\S]*?\r?\n---\r?\n([\s\S]*)$/.exec(source);
31
+ const brief = (match?.[1] ?? source).trim();
32
+ if (!brief)
33
+ throw new BridgeError(503, "The shipped conductor brief is empty. Reinstall Phren Hook.");
34
+ return brief;
35
+ }
36
+ const launchEfforts = ["minimal", "low", "medium", "high", "xhigh", "max"];
37
+ /** How each harness takes a reasoning effort at startup. */
38
+ function effortArgs(kind, effort) {
39
+ if (kind === "claude")
40
+ return ["--effort", effort];
41
+ if (kind === "codex")
42
+ return ["-c", `model_reasoning_effort=${effort}`];
43
+ if (kind === "opencode")
44
+ return ["--variant", effort];
45
+ return [];
46
+ }
47
+ async function prepareConductor(kind, effort, model) {
48
+ const brief = await conductorBrief();
49
+ const briefDirectory = path.join(bridgeRoot(), "conductor");
50
+ await mkdir(briefDirectory, { recursive: true, mode: 0o700 });
51
+ const briefFile = path.join(briefDirectory, "brief.md");
52
+ if (await readFile(briefFile, "utf8").catch(() => undefined) !== brief + "\n")
53
+ await atomic(briefFile, brief + "\n");
54
+ // A multi-line argument cannot be typed safely into every shell (Herdr
55
+ // refuses it for zsh); Claude reads the brief from its file instead.
56
+ if (kind === "claude")
57
+ return [...(model ? ["--model", model] : []), "--append-system-prompt-file", briefFile, "--effort", effort];
58
+ if (kind === "codex")
59
+ return [...(model ? ["--model", model] : []), "-c", `model_reasoning_effort=${effort}`, "-c", `developer_instructions=${JSON.stringify(brief)}`];
60
+ if (kind === "opencode") {
61
+ const directory = path.join(process.env.XDG_CONFIG_HOME || path.join(homeDir(), ".config"), "opencode", "agents");
62
+ const file = path.join(directory, "conductor.md");
63
+ const definition = `---\ndescription: Coordinate the owner's work across agent sessions.\nmode: primary\n---\n\n${brief}\n`;
64
+ await mkdir(directory, { recursive: true, mode: 0o700 });
65
+ if (await readFile(file, "utf8").catch(() => undefined) !== definition)
66
+ await atomic(file, definition, 0o644);
67
+ return [...(model ? ["--model", model] : []), "--agent", "conductor", "--variant", effort];
68
+ }
69
+ throw new BridgeError(400, "The selected harness cannot run as a conductor.");
70
+ }
71
+ async function targetForPane(server, pane) {
72
+ if (!provider.safeParse(pane.agent).success || !id.safeParse(pane.workspace_id).success || !id.safeParse(pane.tab_id).success || !id.safeParse(pane.pane_id).success)
73
+ return undefined;
74
+ const binding = { server, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent };
75
+ const session = await paneIdentity(server, pane);
76
+ if (session)
77
+ return { ...binding, session };
78
+ const chat = await paneChatState(server, pane).catch(() => ({}));
79
+ return chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
80
+ }
81
+ /** The Herdr agent-name slug for a human label: "Conductor smoke 4" becomes "conductor-smoke-4". */
82
+ export function herdrAgentName(label) {
83
+ const slug = label.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z]+/, "").replace(/-+$/, "").slice(0, 32).replace(/-+$/, "");
84
+ return slug || "agent";
85
+ }
86
+ /**
87
+ * "Open on a computer": a new Herdr workspace (or a tab in an existing one)
88
+ * in the project's directory, with the chosen agent started in its pane.
89
+ * Herdr's create calls do not return identifiers, so the new tab is found
90
+ * by diffing snapshots; `agent.start` returns once Herdr has detected the
91
+ * agent and it is ready for input, which can take most of `timeoutMs`.
92
+ */
93
+ export async function launchSession(server, data, options = {}) {
94
+ const role = z.enum(["agent", "conductor"]).default("agent").parse(data.role);
95
+ const projectDirectory = z.string().min(1).max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
96
+ const worktreeRequest = data.worktree === undefined || data.worktree === null ? undefined : launchWorktreeSchema.parse(data.worktree);
97
+ if (worktreeRequest && role === "conductor")
98
+ throw new BridgeError(400, "A conductor works across projects, so it cannot start in a worktree.");
99
+ const label = plainText(200).parse(data.label);
100
+ const kind = z.enum(launchKinds).parse(data.kind);
101
+ const effort = z.enum(launchEfforts).default("medium").parse(data.effort);
102
+ if (role === "conductor" && kind === "copilot")
103
+ throw new BridgeError(400, "Copilot cannot run as a conductor.");
104
+ // Herdr's agent name is a slug (lowercase, digits, - or _, 1 to 32 chars);
105
+ // the label a person typed is not, so derive one from it.
106
+ const baseName = herdrAgentName(data.name === undefined ? label : plainText(200).parse(data.name));
107
+ // "Conductor" stays "conductor", never "conductor-conductor".
108
+ // The canary's conductor is not the store's conductor: it keeps its own
109
+ // name, so the phone never pins it and a real conductor is never refused.
110
+ const wanted = options.canary ? "phren-canary" : role === "conductor" ? (baseName === "conductor" || baseName.startsWith("conductor-") ? baseName : herdrAgentName(`conductor-${baseName}`)) : baseName;
111
+ const model = typeof data.model === "string" && data.model.trim() ? plainText(200).parse(data.model.trim()) : undefined;
112
+ const modelFlag = { codex: "--model", claude: "--model", opencode: "--model" };
113
+ const workspace = data.workspaceId === undefined ? undefined : id.parse(data.workspaceId);
114
+ // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
115
+ const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
116
+ const before = await snapshot(server);
117
+ // Herdr agent names are unique per server; a scheduled run or a second
118
+ // launch with the same label would otherwise collide with the first.
119
+ const taken = agentNames(before);
120
+ let name = wanted;
121
+ for (let n = 2; taken.has(name) && n < 100; n++)
122
+ name = `${wanted.slice(0, 32 - String(n).length - 1)}-${n}`;
123
+ if (role === "conductor" && !options.canary) {
124
+ const otherServers = (await servers()).map(item => String(item.session)).filter(name => name !== server);
125
+ const overviews = [{ name: server, value: before }, ...await Promise.all(otherServers.map(async (name) => ({ name, value: await snapshot(name) })))];
126
+ for (const overview of overviews) {
127
+ const existing = objects(overview.value.panes).find(pane => isConductorName(paneAgentName(overview.value, pane))
128
+ && provider.safeParse(pane.agent).success && !["completed", "exited", "failed", "stopped"].includes(String(pane.agent_status)));
129
+ if (existing)
130
+ throw new BridgeError(409, "A conductor is already running for this store.", { target: await targetForPane(overview.name, existing) });
131
+ }
132
+ }
133
+ const args = role === "conductor" ? await prepareConductor(kind, effort, model)
134
+ : [...(model && modelFlag[kind] ? [modelFlag[kind], model] : []), ...(data.effort === undefined ? [] : effortArgs(kind, effort))];
135
+ if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
136
+ throw new BridgeError(409, "The workspace changed.");
137
+ const knownWorkspaces = new Set(objects(before.workspaces).map(w => w.workspace_id));
138
+ const knownTabs = new Set(objects(before.tabs).map(t => t.tab_id));
139
+ // Created last, once nothing else can refuse the launch, so a refusal
140
+ // never leaves a worktree or branch behind.
141
+ const worktree = worktreeRequest ? await createLaunchWorktree(projectDirectory, worktreeRequest) : undefined;
142
+ const cwd = worktree?.cwd ?? projectDirectory;
143
+ try {
144
+ await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
145
+ }
146
+ catch (error) {
147
+ await worktree?.discard();
148
+ throw error;
149
+ }
150
+ let created;
151
+ for (let attempt = 0; attempt < 25 && !created; attempt++) {
152
+ const s = await snapshot(server);
153
+ const fresh = objects(s.tabs).filter(t => !knownTabs.has(t.tab_id)
154
+ && (workspace ? t.workspace_id === workspace : !knownWorkspaces.has(t.workspace_id)));
155
+ const tab = fresh.find(t => t.label === label)
156
+ ?? fresh.find(t => objects(s.workspaces).some(w => w.workspace_id === t.workspace_id && w.label === label))
157
+ ?? fresh[0];
158
+ const pane = tab && objects(s.panes).find(p => p.tab_id === tab.tab_id && p.workspace_id === tab.workspace_id && !p.agent);
159
+ if (tab && pane && id.safeParse(tab.workspace_id).success && id.safeParse(tab.tab_id).success && id.safeParse(pane.pane_id).success) {
160
+ created = { workspaceId: String(tab.workspace_id), tabId: String(tab.tab_id), paneId: String(pane.pane_id) };
161
+ }
162
+ else
163
+ await new Promise(resolve => setTimeout(resolve, 200));
164
+ }
165
+ if (!created)
166
+ throw new BridgeError(409, `Herdr created "${label}" but its pane did not appear. Check Herdr on the computer.`);
167
+ try {
168
+ await rpc(server, "agent.start", { name, kind, pane_id: created.paneId, timeout_ms: timeout, ...(args.length ? { args } : {}) }, undefined, timeout + 5_000);
169
+ }
170
+ catch (error) {
171
+ // A first-run screen (Claude's folder trust, a login notice) holds the
172
+ // agent at startup. It did start: hand the pane back so the owner answers
173
+ // that screen from the chat instead of stranding the workspace.
174
+ const blocked = error instanceof BridgeError && error.details?.herdrCode === "agent_not_ready";
175
+ if (!blocked) {
176
+ const reason = error instanceof BridgeError && error.status === 504 ? "it did not become ready in time"
177
+ : error instanceof BridgeError && error.message.startsWith("Herdr: ") ? error.message.slice(7) : "Herdr reported an error";
178
+ throw new BridgeError(409, `Herdr couldn't start ${kind} in the new "${label}" pane (${reason}). The workspace was created and is still open on the computer — open it from Herdr workspaces.`);
179
+ }
180
+ }
181
+ const after = await snapshot(server);
182
+ const pane = findPane(after, { workspace: created.workspaceId, tab: created.tabId, pane: created.paneId });
183
+ const agentStatus = typeof pane?.agent_status === "string" ? pane.agent_status : undefined;
184
+ const sessionId = pane && pane.agent === kind ? await paneIdentity(server, pane) : undefined;
185
+ const chat = !sessionId && pane && pane.agent === kind ? await paneChatState(server, pane).catch(() => ({})) : {};
186
+ const binding = { server, workspace: created.workspaceId, tab: created.tabId, pane: created.paneId, source: kind };
187
+ const target = sessionId ? { ...binding, session: sessionId }
188
+ : chat.starting === true ? { ...binding, starting: true, startingToken: chat.startingToken } : undefined;
189
+ return { ok: true, ...created, agent: kind, agentStatus, role, sessionId, target,
190
+ ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
191
+ }
192
+ export async function workspaceAction(server, operation, data) {
193
+ if (!["focus", "rename", "create", "close"].includes(operation))
194
+ throw new BridgeError(400, "Unsupported Herdr action.");
195
+ const s = await snapshot(server);
196
+ const workspace = typeof data.workspaceId === "string" ? data.workspaceId : undefined;
197
+ const tab = typeof data.tabId === "string" ? data.tabId : undefined;
198
+ const pane = typeof data.paneId === "string" ? data.paneId : undefined;
199
+ if (workspace && !objects(s.workspaces).some(w => w.workspace_id === workspace))
200
+ throw new BridgeError(409, "The workspace changed.");
201
+ if (tab && !objects(s.tabs).some(t => t.tab_id === tab && (!workspace || t.workspace_id === workspace)))
202
+ throw new BridgeError(409, "The tab changed.");
203
+ if (pane && !objects(s.panes).some(p => p.pane_id === pane && (!tab || p.tab_id === tab) && (!workspace || p.workspace_id === workspace)))
204
+ throw new BridgeError(409, "The pane changed.");
205
+ const label = data.label === undefined ? undefined : z.string().min(1).max(200).refine(t => !/[\x00-\x1f\x7f]/.test(t)).parse(data.label);
206
+ const cwd = data.cwd === undefined ? undefined : z.string().max(4096).refine(t => path.isAbsolute(t) && !/[\x00-\x1f\x7f]/.test(t)).parse(data.cwd);
207
+ if (operation === "create")
208
+ await rpc(server, workspace ? "tab.create" : "workspace.create", { workspace_id: workspace, label, cwd, focus: false, env: {} });
209
+ else if (!workspace && !tab && !pane)
210
+ throw new BridgeError(400, "Choose a Herdr destination.");
211
+ else if (pane && operation === "focus")
212
+ await rpc(server, "pane.focus", { pane_id: pane });
213
+ else if (pane)
214
+ throw new BridgeError(400, "This pane action is not available.");
215
+ else
216
+ await rpc(server, `${tab ? "tab" : "workspace"}.${operation}`, { ...(tab ? { tab_id: tab } : { workspace_id: workspace }), ...(label ? { label } : {}) });
217
+ return { ok: true };
218
+ }
@@ -0,0 +1,45 @@
1
+ import { type Json } from "./protocol.js";
2
+ import type { WorkspacesReader } from "./server-routes.js";
3
+ /**
4
+ * The `/v1/overview` WebSocket: the same overview `GET /v1/workspaces`
5
+ * answers, pushed to the phone when it changes, so a phone keeps one socket
6
+ * per computer open instead of polling. Each tick reads the shared Herdr
7
+ * snapshot at most one tick old: the activity timer takes one every five
8
+ * seconds (and open chats every 2.5), so a connected phone adds no Herdr
9
+ * snapshots of its own, and a status change reaches it within one tick. The
10
+ * overview is rebuilt when that snapshot changed or `OVERVIEW_REFRESH_MS` has
11
+ * passed (branches, models and steps live outside the snapshot), and sent
12
+ * only when it differs from the last one sent. With nothing to send, a heartbeat every
13
+ * `OVERVIEW_HEARTBEAT_MS` carries the Hook's info and tells the phone the
14
+ * overview it holds is still current.
15
+ *
16
+ * Frames: `{ type: "overview", ...workspaces, phren }` and
17
+ * `{ type: "heartbeat", phren }`.
18
+ */
19
+ export declare const OVERVIEW_TICK_MS: number;
20
+ export declare const OVERVIEW_REFRESH_MS: number;
21
+ export declare const OVERVIEW_HEARTBEAT_MS: number;
22
+ export interface OverviewStreamOptions {
23
+ read: WorkspacesReader;
24
+ /** The Hook's info, as `/v1/health` reports it. */
25
+ info: () => Json;
26
+ /** Renews the approval watch lease `watchApprovals=1` asks for. */
27
+ renew: (server: string) => void;
28
+ snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
29
+ now?: () => number;
30
+ tickMs?: number;
31
+ refreshMs?: number;
32
+ heartbeatMs?: number;
33
+ }
34
+ /** A socket-like peer: the `ws` client, or a test double. */
35
+ export interface OverviewClient {
36
+ readonly readyState: number;
37
+ readonly bufferedAmount: number;
38
+ send(data: string): void;
39
+ close(code?: number, reason?: string): void;
40
+ once(event: "close" | "error", listener: () => void): unknown;
41
+ }
42
+ export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean) => {
43
+ tick: () => Promise<void>;
44
+ stop: () => void;
45
+ };
@@ -0,0 +1,102 @@
1
+ import { WebSocket } from "ws";
2
+ import { logger } from "../logger.js";
3
+ import { sharedSnapshot } from "./herdr.js";
4
+ import { intervalFromEnv } from "./limits.js";
5
+ import { countTick } from "./metrics.js";
6
+ import { MAX_FRAME } from "./protocol.js";
7
+ import { streamCloseReason } from "./server-stream.js";
8
+ /**
9
+ * The `/v1/overview` WebSocket: the same overview `GET /v1/workspaces`
10
+ * answers, pushed to the phone when it changes, so a phone keeps one socket
11
+ * per computer open instead of polling. Each tick reads the shared Herdr
12
+ * snapshot at most one tick old: the activity timer takes one every five
13
+ * seconds (and open chats every 2.5), so a connected phone adds no Herdr
14
+ * snapshots of its own, and a status change reaches it within one tick. The
15
+ * overview is rebuilt when that snapshot changed or `OVERVIEW_REFRESH_MS` has
16
+ * passed (branches, models and steps live outside the snapshot), and sent
17
+ * only when it differs from the last one sent. With nothing to send, a heartbeat every
18
+ * `OVERVIEW_HEARTBEAT_MS` carries the Hook's info and tells the phone the
19
+ * overview it holds is still current.
20
+ *
21
+ * Frames: `{ type: "overview", ...workspaces, phren }` and
22
+ * `{ type: "heartbeat", phren }`.
23
+ */
24
+ export const OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5_000, 250, 60_000);
25
+ export const OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 10_000, 1_000, 120_000);
26
+ export const OVERVIEW_HEARTBEAT_MS = intervalFromEnv("PHREN_OVERVIEW_HEARTBEAT_MS", 20_000, 1_000, 60_000);
27
+ export function overviewStream(options) {
28
+ const snapshot = options.snapshot ?? sharedSnapshot;
29
+ const now = options.now ?? Date.now;
30
+ const tickMs = options.tickMs ?? OVERVIEW_TICK_MS;
31
+ const refreshMs = options.refreshMs ?? OVERVIEW_REFRESH_MS;
32
+ const heartbeatMs = options.heartbeatMs ?? OVERVIEW_HEARTBEAT_MS;
33
+ function send(client, frame) {
34
+ if (client.readyState !== WebSocket.OPEN)
35
+ return false;
36
+ const data = JSON.stringify(frame);
37
+ if (Buffer.byteLength(data) > MAX_FRAME || client.bufferedAmount > MAX_FRAME) {
38
+ client.close(1009, "Overview too large; refresh");
39
+ return false;
40
+ }
41
+ client.send(data);
42
+ return true;
43
+ }
44
+ /** Streams one server's overview until the client closes. Returns the
45
+ * tick function, for tests that drive time themselves. */
46
+ return function stream(client, server, watchApprovals) {
47
+ let closed = false, busy = false, first = true;
48
+ let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0;
49
+ const tick = async () => {
50
+ if (busy || closed)
51
+ return;
52
+ busy = true;
53
+ try {
54
+ countTick("overview-stream");
55
+ const at = now();
56
+ // The first frame reads a fresh snapshot, as a poll would.
57
+ const held = await snapshot(server, first ? 0 : tickMs);
58
+ if (closed)
59
+ return;
60
+ const key = JSON.stringify(held);
61
+ if (first || key !== snapshotKey || at - builtAt >= refreshMs) {
62
+ snapshotKey = key;
63
+ builtAt = at;
64
+ const overview = await options.read(server, held, watchApprovals);
65
+ if (closed)
66
+ return;
67
+ const { phren: _phren, ...rows } = overview;
68
+ const rowsKey = JSON.stringify(rows);
69
+ if (first || rowsKey !== sentKey) {
70
+ if (send(client, { type: "overview", ...overview })) {
71
+ sentKey = rowsKey;
72
+ sentAt = at;
73
+ }
74
+ first = false;
75
+ return;
76
+ }
77
+ }
78
+ else if (watchApprovals) {
79
+ options.renew(server);
80
+ }
81
+ first = false;
82
+ if (at - sentAt >= heartbeatMs && send(client, { type: "heartbeat", phren: options.info() }))
83
+ sentAt = at;
84
+ }
85
+ catch (error) {
86
+ const reason = streamCloseReason(error);
87
+ logger.warn("stream", `/v1/overview closed: ${reason}`);
88
+ stop();
89
+ client.close(1011, reason);
90
+ }
91
+ finally {
92
+ busy = false;
93
+ }
94
+ };
95
+ const timer = setInterval(() => { void tick(); }, tickMs);
96
+ const stop = () => { closed = true; clearInterval(timer); };
97
+ client.once("close", stop);
98
+ client.once("error", stop);
99
+ void tick();
100
+ return { tick, stop };
101
+ };
102
+ }
@@ -0,0 +1,36 @@
1
+ import type { ServerResponse } from "node:http";
2
+ import type { AgentHooks } from "./agent-hooks.js";
3
+ import { type WorktreeWorker } from "./git-worktrees.js";
4
+ import { type ModelSwitcher } from "./model-switch.js";
5
+ import { type Json, type Target } from "./protocol.js";
6
+ import type { CodexQuestions } from "./questions.js";
7
+ import { type SideQuestions } from "./side-questions.js";
8
+ /** Routes that act on one pane's conversation: prompts, answer keys, typed
9
+ * secrets, uploads, diffs, git, approvals and questions. A starting pane (no
10
+ * conversation yet) takes keys, a secret or a first prompt. */
11
+ export interface PaneRouteContext {
12
+ agentHooks: AgentHooks;
13
+ modelSwitcher: ModelSwitcher;
14
+ codexQuestions: CodexQuestions;
15
+ sideQuestions: SideQuestions;
16
+ }
17
+ export declare function uploadBody(data: Json): {
18
+ name: string;
19
+ bytes: Buffer;
20
+ };
21
+ /** The repository a git route acts on: the pane's trusted directory, a
22
+ * spawned child's own worktree exactly as /v1/diff resolves it, or one of the
23
+ * pane repository's other worktrees as `/v1/git/worktrees` lists it. */
24
+ export declare function gitRepository(pane: Json, target: Target, child: unknown, worktree?: unknown): Promise<string>;
25
+ /** Agents running in this Herdr server's panes, by the folder each works in:
26
+ * an agent launched into a new worktree from the phone is named here. Listed
27
+ * last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
28
+ export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
29
+ /** A busy Claude Code queues typed text on Enter, but after a long paste
30
+ * ("paste again to expand") it can swallow that Enter and leave the text in
31
+ * its input line, where it stays after the turn ends. Follow the pane: once
32
+ * it has stayed finished for two looks while the prompt is still unsubmitted,
33
+ * press Enter once. A closed or replaced pane, a delivery the conversation
34
+ * took, or ten minutes end the watch; a pane asking for input is never answered. */
35
+ export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
36
+ export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse): Promise<unknown>;