@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
@@ -1,29 +1,301 @@
1
+ import { defaultPhrenPath } from "../shared.js";
2
+ import { disabledHint } from "../modules/registry.js";
3
+ import { activateModules as moduleSnapshot } from "../modules/runtime.js";
4
+ import { logger } from "../logger.js";
1
5
  import { request, createServer } from "node:http";
2
- import { mkdir, writeFile, readFile, rename, chmod, unlink, lstat } from "node:fs/promises";
6
+ import { mkdir, readFile, chmod, unlink, lstat } from "node:fs/promises";
7
+ import { watch } from "node:fs";
3
8
  import path from "node:path";
4
9
  import { randomUUID } from "node:crypto";
5
- import { z } from "zod";
6
- import { BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
7
- import { herdrRoot, rpc, snapshot, validateTarget } from "./herdr.js";
8
- const localSocket = () => path.join(bridgeRoot(), "agent.sock");
9
- const bindingPath = (server, pane) => path.join(bridgeRoot(), "bindings", server, encodeURIComponent(pane) + ".json");
10
- export async function recordedSession(server, pane, pids) {
11
- try {
12
- const value = object(JSON.parse(await readFile(bindingPath(server, String(pane.pane_id)), "utf8")));
13
- if (value.terminal !== pane.terminal_id || value.source !== pane.agent || !Array.isArray(value.pids) || !value.pids.some(p => pids.includes(Number(p))))
14
- return undefined;
15
- return z.string().uuid().parse(value.session);
16
- }
17
- catch {
10
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, object, objects, provider, targetSchema } from "./protocol.js";
11
+ import { findPane, herdrPaneFromEnv, knownPanes, rpc, servers, snapshot, trustedDirectory, validateTarget } from "./herdr.js";
12
+ import { readPaneText } from "./pane-text.js";
13
+ import { capturesChanges, ToolChanges } from "./changes.js";
14
+ import { phrenStoreRoot, unwrapPastedContent } from "./transcripts.js";
15
+ import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.js";
16
+ import { ensureGrant, listGrants, matchGrant } from "./grants.js";
17
+ import { ApprovalPushService } from "./push.js";
18
+ import { intervalFromEnv } from "./limits.js";
19
+ import { answeredQuestionInput, numberedDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
20
+ import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
21
+ import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
22
+ import { countTick } from "./metrics.js";
23
+ export { permissionPrompt, terminalChoice, visibleTerminalChoice } from "./terminal-choice.js";
24
+ export { ApprovalWatchLeases, PushBindingStore, recordedSession } from "./agent-hook-stores.js";
25
+ const APPROVAL_SWEEP_MS = 2_000;
26
+ /** How recent the Herdr snapshots must be for the poll to trust "no opencode pane". */
27
+ const OPENCODE_PANES_FRESH_MS = 15_000;
28
+ const APPROVAL_DEBOUNCE_MS = 100;
29
+ /** How long a permission ask is held for the phone before it falls back to
30
+ * the terminal. Claude's own hook window is 60 s; a test shortens it. */
31
+ const APPROVAL_HOLD_MS = (() => {
32
+ const value = Number(process.env.PHREN_APPROVAL_HOLD_MS);
33
+ return Number.isFinite(value) && value >= 50 && value <= 60_000 ? Math.floor(value) : 55_000;
34
+ })();
35
+ /** A pane's terminal dialog is read at most once per this window. */
36
+ const DIALOG_READ_MS = intervalFromEnv("PHREN_DIALOG_THROTTLE_MS", 3_000);
37
+ const AGENT_NAMES = { claude: "Claude", codex: "Codex", opencode: "OpenCode", copilot: "Copilot", phren: "phren" };
38
+ /** How long a pushed terminal dialog can be answered from its notification. */
39
+ const DIALOG_PUSH_MS = 10 * 60_000;
40
+ const FANOUT_SWEEP_MS = 5_000;
41
+ const FANOUT_ARCHIVE_MS = 60 * 60 * 1000;
42
+ /** A conductor `dispatch` or `hand_off` permission ask the Hook can answer
43
+ * itself under a standing grant, or offer the phone two grant-writing answers. */
44
+ export function conductorCall(tool, input) {
45
+ // MCP tool names vary by harness: `dispatch`, `phren.dispatch`,
46
+ // `mcp__phren__dispatch`; phren_admin carries the action in its fields.
47
+ const tail = /(?:^|[.:/]|__)(dispatch|hand_off|phren_admin)$/.exec(tool)?.[1];
48
+ const fields = object(input);
49
+ let action;
50
+ if (tail === "dispatch")
51
+ action = "dispatch";
52
+ else if (tail === "hand_off")
53
+ action = "hand_off";
54
+ else if (tail === "phren_admin" && (fields.action === "dispatch" || fields.action === "hand_off"))
55
+ action = fields.action;
56
+ if (!action)
18
57
  return undefined;
19
- }
58
+ const project = typeof fields.project === "string" ? fields.project : undefined;
59
+ const computer = typeof fields.computer === "string" ? fields.computer : undefined;
60
+ return { action, ...(project ? { project } : {}), ...(computer ? { computer } : {}) };
61
+ }
62
+ /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
63
+ * form of what Phren typed; compare the words, not the wrapping. */
64
+ function promptKey(text) {
65
+ return unwrapPastedContent(text).replace(/\s+/g, " ").trim();
20
66
  }
21
67
  /** This socket is deliberately separate from the phone's HTTP pipe. Only local
22
68
  * agent callbacks can register identities or create an approval request. */
23
69
  export class AgentHooks {
70
+ push;
71
+ modules;
72
+ changes = new ToolChanges();
24
73
  pending = new Map();
74
+ /** Prompts Phren has typed into a pane, by their text, until the agent that
75
+ * actually receives one reports in through UserPromptSubmit. Herdr writes
76
+ * to a pane, not a conversation; the receiving agent's hook is the only
77
+ * party that knows which conversation consumed the text, so it is the one
78
+ * that can refuse it when that is not the conversation the phone meant. */
79
+ deliveries = new Map();
80
+ /** The permission request a conversation is drawing in its own terminal
81
+ * because nobody was there to hold it: what the phone shows above its
82
+ * answer keys until the pane stops waiting. `dialog` marks a choice parsed
83
+ * from the pane's own numbered lines, whose answers gain an Enter, and
84
+ * `questions` carries a released AskUserQuestion's normalized question set
85
+ * with the index currently being answered. */
86
+ terminalPrompts = new Map();
87
+ /** The last time each pane's terminal lines were read for a dialog, so a
88
+ * status tick reads them at most once per three seconds per pane. */
89
+ dialogReads = new Map();
90
+ /** Panes whose last read terminal line is a password prompt, so the status
91
+ * frame can offer the phone's secret sheet only when one is really asking. */
92
+ passwords = new Map();
93
+ /** Conversations Claude Code is compacting, by target, until the new context
94
+ * starts. The phone shows the state instead of the summary row's text. */
95
+ compactingSince = new Map();
96
+ /** Panes where Phren just typed a bare slash command: the agent is drawing
97
+ * that command's menu, which Herdr reports as an idle agent, so keys are
98
+ * allowed there for a short while to walk and confirm it. The command text
99
+ * and a one-shot confirmation attempt ride with the window. */
100
+ menus = new Map();
25
101
  watching = new Map();
102
+ overview = new ApprovalWatchLeases();
26
103
  server;
104
+ pushBindings = new PushBindingStore();
105
+ /** Held asks that were pushed: action -> when the notification expires. */
106
+ pushedHolds = new Map();
107
+ /** Pushed asks whose hold ended with the request left in the terminal. */
108
+ releasedHolds = new Map();
109
+ /** Terminal dialogs pushed to phones: by pane, the dialog last pushed; by
110
+ * action, what an answer from the notification types. */
111
+ dialogPushes = new Map();
112
+ dialogActions = new Map();
113
+ /** opencode permission asks seen on disk, by request id. */
114
+ opencode = new Map();
115
+ closed = false;
116
+ opencodeSweep;
117
+ opencodeLive = new Set();
118
+ fanoutLive = new Set();
119
+ fanoutSweeping = false;
120
+ opencodeWatcher;
121
+ opencodePoll;
122
+ opencodeDebounce;
123
+ /** Fan-out jobs already pushed as blocked, by job id and blocked timestamp. */
124
+ fanoutSeen = new Map();
125
+ fanoutTimer;
126
+ fanoutArchiveTimer;
127
+ constructor(push = new ApprovalPushService(), modules) {
128
+ this.push = push;
129
+ this.modules = modules;
130
+ }
131
+ approvalsDirectory() { return path.join(phrenStoreRoot(), ".runtime", "approvals"); }
132
+ scheduleOpencodeSweep() {
133
+ if (this.closed || this.opencodeDebounce)
134
+ return;
135
+ this.opencodeDebounce = setTimeout(() => { this.opencodeDebounce = undefined; void this.sweepOpencodeApprovals().catch(() => { }); }, APPROVAL_DEBOUNCE_MS);
136
+ this.opencodeDebounce.unref?.();
137
+ }
138
+ /** Read every live opencode request file, map it to a target through the
139
+ * recorded bindings or Herdr's explicit opencode session id, and register it
140
+ * for a push and a push-binding answer. A file that vanished or expired is
141
+ * forgotten. */
142
+ async sweepOpencodeApprovals() {
143
+ if (this.closed)
144
+ return;
145
+ if (this.opencodeSweep)
146
+ return this.opencodeSweep;
147
+ countTick("opencode-sweep");
148
+ const sweep = this.readOpencodeApprovals();
149
+ this.opencodeSweep = sweep;
150
+ try {
151
+ await sweep;
152
+ }
153
+ finally {
154
+ this.opencodeSweep = undefined;
155
+ }
156
+ }
157
+ async readOpencodeApprovals() {
158
+ const directory = this.approvalsDirectory();
159
+ const live = this.opencodeLive;
160
+ live.clear();
161
+ for await (const name of directoryNames(directory, 1024)) {
162
+ if (this.closed)
163
+ return;
164
+ const match = /^opencode-(ses_[0-9A-Za-z]{1,64})\.request\.json$/.exec(name);
165
+ if (!match)
166
+ continue;
167
+ const request = await readOpencodeRequest(match[1]);
168
+ if (!request)
169
+ continue;
170
+ const id = String(request.id);
171
+ live.add(id);
172
+ if (this.opencode.has(id))
173
+ continue;
174
+ // The launcher names the fan-out job; its manifest, not the request,
175
+ // says which worker session and parent conversation it belongs to.
176
+ const asking = request.fanout === undefined ? undefined : await fanoutAsking(request.fanout, match[1]);
177
+ if (request.fanout !== undefined && !asking)
178
+ continue;
179
+ const target = asking ? await this.resolveTarget(asking.parent.provider, asking.parent.session) : await this.resolveTarget("opencode", match[1]);
180
+ if (this.closed)
181
+ return;
182
+ if (!target && !asking)
183
+ continue;
184
+ const expiresAt = typeof request.expiresAt === "string" ? Date.parse(request.expiresAt) : NaN;
185
+ if (!Number.isFinite(expiresAt) || expiresAt <= Date.now())
186
+ continue;
187
+ // The answer route checks an action id by the parent's source: a UUID
188
+ // for Claude and Codex, a plain token for opencode.
189
+ const fanout = asking ? { session: match[1], actionId: asking.parent.provider === "opencode" ? randomUUID().replaceAll("-", "") : randomUUID() } : undefined;
190
+ this.opencode.set(id, { ...(target ? { target } : {}), request, expiresAt, ...(fanout ? { fanout } : {}) });
191
+ if (!this.push.available)
192
+ continue;
193
+ const binding = randomUUID();
194
+ this.pushBindings.add(binding, { action: id, expiresAt });
195
+ const title = typeof request.title === "string" ? request.title : `Allow ${String(request.type ?? "action")}?`;
196
+ const message = typeof request.message === "string" ? request.message : "";
197
+ // The held request is what stops a later sweep from pushing again; a
198
+ // failed delivery only drops the binding and leaves the card in place.
199
+ void this.push.notify({ binding, provider: "opencode", question: false, expiresAt: String(request.expiresAt), title, message })
200
+ .then(delivered => { if (!delivered)
201
+ this.pushBindings.dropAction(id); })
202
+ .catch(() => { });
203
+ }
204
+ for (const [id, held] of this.opencode) {
205
+ if (!live.has(id) || held.expiresAt <= Date.now()) {
206
+ this.opencode.delete(id);
207
+ this.pushBindings.dropAction(id);
208
+ }
209
+ }
210
+ }
211
+ /** A session's exact pane. A recorded binding carries the full target; when
212
+ * there is none, Herdr's explicit session identity names the pane. */
213
+ async resolveTarget(source, session) {
214
+ const root = path.join(bridgeRoot(), "bindings");
215
+ for await (const folder of directoryNames(root, 64)) {
216
+ for await (const name of directoryNames(path.join(root, folder), 1024)) {
217
+ if (!name.endsWith(".json"))
218
+ continue;
219
+ let value;
220
+ try {
221
+ const file = path.join(root, folder, name), info = await lstat(file);
222
+ if (!info.isFile() || info.size > 65_536)
223
+ continue;
224
+ value = object(JSON.parse(await readFile(file, "utf8")));
225
+ }
226
+ catch {
227
+ continue;
228
+ }
229
+ if (value.source !== source || value.session !== session)
230
+ continue;
231
+ if (typeof value.workspace !== "string" || typeof value.tab !== "string")
232
+ continue;
233
+ const parsed = targetSchema.safeParse({ server: decodeURIComponent(folder), workspace: value.workspace, tab: value.tab,
234
+ pane: decodeURIComponent(name.slice(0, -".json".length)), source, session });
235
+ if (parsed.success)
236
+ return parsed.data;
237
+ }
238
+ }
239
+ const live = await servers().catch(() => []);
240
+ for (const entry of live) {
241
+ const server = String(entry.session);
242
+ const state = await snapshot(server).catch(() => undefined);
243
+ if (!state)
244
+ continue;
245
+ for (const pane of objects(state.panes)) {
246
+ if (pane.agent !== source)
247
+ continue;
248
+ const reported = object(pane.agent_session);
249
+ if (reported.kind !== "id" || reported.agent !== source || reported.value !== session)
250
+ continue;
251
+ const parsed = targetSchema.safeParse({ server, workspace: pane.workspace_id, tab: pane.tab_id,
252
+ pane: pane.pane_id, source, session });
253
+ if (parsed.success)
254
+ return parsed.data;
255
+ }
256
+ }
257
+ return undefined;
258
+ }
259
+ /** Push once for each fan-out job whose blocked.json the plugin wrote. */
260
+ async sweepBlockedFanouts() {
261
+ if (this.closed || this.fanoutSweeping)
262
+ return;
263
+ this.fanoutSweeping = true;
264
+ try {
265
+ const jobs = await blockedFanouts().catch(() => []);
266
+ if (this.closed)
267
+ return;
268
+ const live = this.fanoutLive;
269
+ live.clear();
270
+ for (const job of jobs) {
271
+ live.add(job.id);
272
+ const parsed = job.at ? Date.parse(job.at) : 0;
273
+ const stamp = Number.isFinite(parsed) ? parsed : 0;
274
+ if (this.fanoutSeen.get(job.id) === stamp)
275
+ continue;
276
+ this.fanoutSeen.set(job.id, stamp);
277
+ void this.push.notifyFanoutBlocked({ job: job.id, label: job.label, provider: job.provider, reason: job.reason }).catch(() => { });
278
+ }
279
+ for (const id of this.fanoutSeen.keys())
280
+ if (!live.has(id))
281
+ this.fanoutSeen.delete(id);
282
+ }
283
+ finally {
284
+ this.fanoutSweeping = false;
285
+ }
286
+ }
287
+ /** Move finished fan-out folders older than a day into the archive; one log
288
+ * line records a sweep that moved or deleted anything, and a sweep that
289
+ * fails never takes the Hook down. */
290
+ async sweepFanoutArchive() {
291
+ try {
292
+ const { moved, deleted } = await archiveFinishedFanouts();
293
+ if (!moved.length && !deleted)
294
+ return;
295
+ logger.info("fanouts", `Archived ${moved.length} finished fan-out job(s); deleted ${deleted} past the archive cap.`);
296
+ }
297
+ catch { /* The archive sweep must never break the Hook. */ }
298
+ }
27
299
  watch(target) {
28
300
  const key = JSON.stringify(target);
29
301
  this.watching.set(key, (this.watching.get(key) || 0) + 1);
@@ -32,24 +304,632 @@ export class AgentHooks {
32
304
  else
33
305
  this.watching.delete(key); };
34
306
  }
307
+ /** Register a prompt about to be typed into `target`'s pane. The returned
308
+ * promise settles "delivered" once that conversation's own hook submits the
309
+ * text, "blocked" if another conversation in the pane tried to, or "pending"
310
+ * after `waitMs`: a busy agent queues typed input and submits it only when
311
+ * its turn ends, so the record outlives the wait (up to ten minutes) and a
312
+ * late submission to the wrong conversation is still refused. */
313
+ expectDelivery(target, text, waitMs = 1_500) {
314
+ const key = promptKey(text);
315
+ if (!key)
316
+ return Promise.resolve("pending");
317
+ return new Promise(resolve => {
318
+ let settled = false;
319
+ const list = this.deliveries.get(key) ?? [];
320
+ const remove = () => { const current = this.deliveries.get(key) ?? []; const index = current.indexOf(delivery); if (index >= 0)
321
+ current.splice(index, 1); if (!current.length)
322
+ this.deliveries.delete(key); };
323
+ const settle = (outcome) => {
324
+ if (!settled) {
325
+ settled = true;
326
+ resolve(outcome);
327
+ }
328
+ else if (outcome !== "pending")
329
+ delivery.late?.(outcome);
330
+ if (outcome !== "pending") {
331
+ clearTimeout(delivery.timer);
332
+ remove();
333
+ }
334
+ };
335
+ const delivery = { source: target.source, session: target.session, settle, timer: setTimeout(() => settle("pending"), waitMs) };
336
+ delivery.timer.unref?.();
337
+ const expiry = setTimeout(remove, 600_000);
338
+ expiry.unref?.();
339
+ list.push(delivery);
340
+ this.deliveries.set(key, list);
341
+ while (this.deliveries.size > 256)
342
+ this.deliveries.delete(this.deliveries.keys().next().value);
343
+ });
344
+ }
345
+ /** A prompt Phren typed into `target` that its conversation has not submitted yet. */
346
+ deliveryPending(target, text) {
347
+ return !!this.deliveries.get(promptKey(text))?.some(entry => entry.source === target.source && entry.session === target.session);
348
+ }
349
+ /** Wait again for a delivery `expectDelivery` already reported pending,
350
+ * after the Hook pressed Enter a second time. */
351
+ awaitLateDelivery(target, text, waitMs = 2_500) {
352
+ const delivery = this.deliveries.get(promptKey(text))?.find(entry => entry.source === target.source && entry.session === target.session);
353
+ if (!delivery)
354
+ return Promise.resolve("pending");
355
+ return new Promise(resolve => {
356
+ const timer = setTimeout(() => { delivery.late = undefined; resolve("pending"); }, waitMs);
357
+ timer.unref?.();
358
+ delivery.late = outcome => { clearTimeout(timer); delivery.late = undefined; resolve(outcome); };
359
+ });
360
+ }
361
+ /** The conversation `target` just submitted `prompt`. Nothing Phren typed
362
+ * matches: a locally typed prompt, always allowed. Otherwise the oldest
363
+ * matching delivery decides: its own conversation consumes it; any other
364
+ * conversation is told to drop it, so the text is never spoken to the
365
+ * wrong agent and the phone can safely send it again. */
366
+ submitted(target, prompt) {
367
+ const list = this.deliveries.get(promptKey(prompt));
368
+ const delivery = list?.[0];
369
+ if (!delivery)
370
+ return {};
371
+ if (delivery.source === target.source && delivery.session === target.session) {
372
+ delivery.settle("delivered");
373
+ return {};
374
+ }
375
+ delivery.settle("blocked");
376
+ return { decision: "block", reason: "Phren sent this message to a different conversation in this pane; it was not delivered here. Send it again from the phone." };
377
+ }
378
+ rememberTerminalPrompt(target, body) {
379
+ const tool = String(body.tool || "action").slice(0, 200);
380
+ const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
381
+ const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
382
+ this.terminalPrompts.set(JSON.stringify(target), { tool,
383
+ message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
384
+ ...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
385
+ while (this.terminalPrompts.size > 64)
386
+ this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
387
+ }
388
+ /** The request the agent is showing in its terminal, if one fell through
389
+ * in the last fifteen minutes; the caller only asks while the pane waits. */
390
+ terminalPrompt(target) {
391
+ const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
392
+ if (!entry)
393
+ return undefined;
394
+ if (Date.now() - entry.at > 900_000) {
395
+ this.terminalPrompts.delete(key);
396
+ return undefined;
397
+ }
398
+ return { toolName: entry.tool, message: entry.message, ...(entry.choice ? { choice: entry.choice } : {}),
399
+ ...(entry.questions?.length ? { questions: entry.questions, questionIndex: entry.questionIndex ?? 0 } : {}), at: new Date(entry.at).toISOString() };
400
+ }
401
+ clearTerminalPrompt(target) { this.terminalPrompts.delete(JSON.stringify(target)); }
402
+ /** True while the pane's own terminal is reading a password. */
403
+ passwordPrompt(target) { return this.passwords.get(JSON.stringify(target)) === true; }
404
+ /** Claude Code's auto-mode fallback, opencode and Codex draw a numbered
405
+ * dialog in the pane with no PermissionRequest hook behind it. While the pane
406
+ * waits with nothing else to ask, read its last lines (at most once per
407
+ * three seconds per pane) and publish the dialog as a terminal choice; drop
408
+ * it when the pane leaves waiting or the dialog lines vanish. A remembered
409
+ * permission request that is not a dialog keeps the slot untouched. The same
410
+ * read notes whether the terminal is reading a password. */
411
+ async syncTerminalDialog(target, active) {
412
+ const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
413
+ const held = [...this.pending.values()].find(p => JSON.stringify(p.target) === key);
414
+ // A held Codex permission can already have real choices in its pane.
415
+ // Refresh those before publishing the approval, even while it is held.
416
+ if (held && target.source === "codex") {
417
+ const now = Date.now();
418
+ if (now - (this.dialogReads.get(key) ?? 0) < DIALOG_READ_MS)
419
+ return;
420
+ this.dialogReads.set(key, now);
421
+ const prompt = permissionPrompt(held.tool, held.input, await this.paneLines(target));
422
+ if ([...this.pending.values()].includes(held)) {
423
+ held.choice = prompt.choice;
424
+ held.title = prompt.title;
425
+ if (held.choice)
426
+ this.terminalPrompts.set(key, { tool: held.tool, message: held.message, choice: held.choice, dialog: true, at: now });
427
+ else
428
+ this.terminalPrompts.delete(key);
429
+ }
430
+ return;
431
+ }
432
+ // A released AskUserQuestion is answered by its own question card, never
433
+ // by the pane's numbered lines; it is cleared only when the pane stops
434
+ // waiting for it.
435
+ if (entry?.questions?.length) {
436
+ if (!active) {
437
+ this.terminalPrompts.delete(key);
438
+ this.passwords.delete(key);
439
+ }
440
+ return;
441
+ }
442
+ // A released permission request that carried its own choices keeps them;
443
+ // one without (a Bash or MCP call) reads the pane's rows below.
444
+ if (entry && !entry.dialog && entry.choice && !entry.released)
445
+ return;
446
+ if (!active) {
447
+ if (entry)
448
+ this.terminalPrompts.delete(key);
449
+ this.passwords.delete(key);
450
+ return;
451
+ }
452
+ const now = Date.now();
453
+ if (now - (this.dialogReads.get(key) ?? 0) < DIALOG_READ_MS)
454
+ return;
455
+ this.dialogReads.set(key, now);
456
+ while (this.dialogReads.size > 128)
457
+ this.dialogReads.delete(this.dialogReads.keys().next().value);
458
+ const text = await this.paneLines(target);
459
+ this.passwords.set(key, passwordLine(text));
460
+ while (this.passwords.size > 128)
461
+ this.passwords.delete(this.passwords.keys().next().value);
462
+ // Codex draws "> 1. Yes, proceed (y)" rows; the other fallbacks number
463
+ // rows without a key in the label.
464
+ const dialog = target.source === "codex" ? visibleTerminalChoice(text) : numberedDialog(text);
465
+ if (entry && !entry.dialog) {
466
+ // The permission the pane still shows after its hook let go: keep the
467
+ // request's own details and answer it with the dialog's rows, so the
468
+ // phone can approve it long after the hold ended, as Moshi does. Not a
469
+ // `dialog`: Claude takes a row's digit at once, and an Enter after it
470
+ // could land on the next permission.
471
+ if (dialog?.title) {
472
+ entry.choice = dialog;
473
+ entry.released = true;
474
+ }
475
+ else if (entry.released) {
476
+ delete entry.choice;
477
+ delete entry.released;
478
+ }
479
+ return;
480
+ }
481
+ if (!dialog?.title) {
482
+ if (entry)
483
+ this.terminalPrompts.delete(key);
484
+ return;
485
+ }
486
+ this.terminalPrompts.set(key, { tool: "Question", message: dialog.title, choice: dialog, dialog: true, at: now });
487
+ while (this.terminalPrompts.size > 64)
488
+ this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
489
+ }
490
+ /** Resolve a phone option identifier. Real shortcuts retain their key path;
491
+ * keyless rows are reached and verified before returning Enter to the route. */
492
+ async dialogAnswerKeys(target, keys) {
493
+ const entry = this.terminalPrompts.get(JSON.stringify(target));
494
+ const choice = entry?.choice;
495
+ const option = choice?.options.find(option => keys.includes(option.key));
496
+ if (choice && option?.hasKey === false) {
497
+ if (keys.length !== 1)
498
+ throw new BridgeError(409, "Choose one terminal option at a time.");
499
+ await this.moveDialogHighlight(target, choice, option.key);
500
+ return ["Enter"];
501
+ }
502
+ const digit = keys.some(key => key.length === 1 && key >= "1" && key <= "9");
503
+ if (digit && !option && choice?.options.some(option => option.hasKey === false)) {
504
+ throw new BridgeError(409, "That terminal option is no longer available. Open terminal to choose an option.");
505
+ }
506
+ return entry?.dialog && digit ? [...keys, "Enter"] : [...keys];
507
+ }
508
+ async moveDialogHighlight(target, expected, key, beforeKeys) {
509
+ const intended = expected.options.findIndex(option => option.key === key);
510
+ let current = visibleTerminalChoice(await this.paneLines(target));
511
+ // A held permission can expose just the asking sentence from the title.
512
+ // Anchor subsequent reads to the entire live title, including its command.
513
+ const title = current?.title;
514
+ const matches = (choice) => !!choice
515
+ && choice.highlightedIndex !== undefined && choice.title === title
516
+ && (title === expected.title || !!expected.title && !!title?.split("\n").includes(expected.title))
517
+ && JSON.stringify(choice.options) === JSON.stringify(expected.options);
518
+ for (let attempt = 0; attempt < 2; attempt++) {
519
+ if (!matches(current))
520
+ break;
521
+ await validateTarget(target, false, true);
522
+ const difference = intended - current.highlightedIndex;
523
+ if (!difference)
524
+ return;
525
+ await beforeKeys?.();
526
+ await rpc(target.server, "agent.send_keys", { target: target.pane,
527
+ keys: Array(Math.abs(difference)).fill(difference > 0 ? "down" : "up") });
528
+ await new Promise(resolve => setTimeout(resolve, 150));
529
+ current = visibleTerminalChoice(await this.paneLines(target));
530
+ if (matches(current) && current.highlightedIndex === intended) {
531
+ // Pane reads and cursor movement can outlive the session the phone
532
+ // selected. Check its fresh identity before permitting confirmation.
533
+ await validateTarget(target, false, true);
534
+ return;
535
+ }
536
+ }
537
+ throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
538
+ }
539
+ /** Answer one question of a released AskUserQuestion with the option's own
540
+ * digit: send the chosen digit(s), then Tab to advance to the next
541
+ * question or Enter after the last. The stored question index moves with
542
+ * them and a finished set is cleared. Undefined when the prompt is not a
543
+ * question, so an ordinary key falls through to the usual handling. */
544
+ questionAnswerKeys(target, keys) {
545
+ const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
546
+ if (!entry?.questions?.length)
547
+ return undefined;
548
+ const digits = keys.filter(value => /^[1-9]$/.test(value));
549
+ if (!digits.length)
550
+ return undefined;
551
+ const index = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), next = index + 1;
552
+ if (next >= entry.questions.length) {
553
+ this.terminalPrompts.delete(key);
554
+ return [...digits, "Enter"];
555
+ }
556
+ entry.questionIndex = next;
557
+ entry.choice = questionChoice(entry.questions, next);
558
+ return [...digits, "Tab"];
559
+ }
560
+ startCompacting(target) {
561
+ this.compactingSince.set(JSON.stringify(target), Date.now());
562
+ while (this.compactingSince.size > 64)
563
+ this.compactingSince.delete(this.compactingSince.keys().next().value);
564
+ }
565
+ stopCompacting(target) { this.compactingSince.delete(JSON.stringify(target)); }
566
+ /** True while Claude Code is compacting `target`; a boundary older than ten
567
+ * minutes is stale, so a missed SessionStart cannot pin the state forever. */
568
+ compacting(target) {
569
+ const key = JSON.stringify(target), at = this.compactingSince.get(key);
570
+ if (at === undefined)
571
+ return false;
572
+ if (Date.now() - at > 600_000) {
573
+ this.compactingSince.delete(key);
574
+ return false;
575
+ }
576
+ return true;
577
+ }
578
+ menuOpened(target, command) {
579
+ this.menus.set(JSON.stringify(target), { at: Date.now(), ...(command ? { command } : {}) });
580
+ while (this.menus.size > 64)
581
+ this.menus.delete(this.menus.keys().next().value);
582
+ }
583
+ menuOpen(target) {
584
+ const entry = this.menus.get(JSON.stringify(target));
585
+ return entry !== undefined && Date.now() - entry.at < 30_000;
586
+ }
587
+ /** The bare slash command that opened this pane's current menu window. */
588
+ menuCommand(target) {
589
+ const entry = this.menus.get(JSON.stringify(target));
590
+ return entry && Date.now() - entry.at < 30_000 ? entry.command : undefined;
591
+ }
592
+ menuClosed(target) { this.menus.delete(JSON.stringify(target)); }
593
+ /** Read what the pane draws, stripping ANSI unless placeholder styling is needed. */
594
+ paneLines(target, stripAnsi = true) {
595
+ return readPaneText(target.server, target.pane, { method: "agent.read", source: "visible", lines: 40, stripAnsi, timeoutMs: 2_000 });
596
+ }
597
+ /** After the phone walks Codex's /permissions menu onto Full Access, the
598
+ * agent draws a second "Enable full access?" confirmation. Watch the pane's
599
+ * terminal lines for it, answer with its own numbered choice, and only then
600
+ * close the menu window. A confirmation that never arrives within three
601
+ * seconds is left open as the visible prompt, published as the terminal
602
+ * choice the phone draws as a question card. Runs at most once per window. */
603
+ async walkMenuConfirmation(target) {
604
+ const key = JSON.stringify(target), entry = this.menus.get(key);
605
+ if (!entry || entry.confirmationAttempted)
606
+ return entry ? { menuClosed: false } : { menuClosed: true };
607
+ entry.confirmationAttempted = true;
608
+ const deadline = Date.now() + 3_000;
609
+ for (;;) {
610
+ const lines = await this.paneLines(target);
611
+ const choice = visibleTerminalChoice(lines);
612
+ if (choice && /\benable full access\b/i.test(choice.title ?? "")) {
613
+ const option = choice.options[0];
614
+ if (option.hasKey === false)
615
+ await this.moveDialogHighlight(target, choice, option.key);
616
+ await validateTarget(target, false, true);
617
+ await rpc(target.server, "agent.send_keys", { target: target.pane,
618
+ keys: option.hasKey === false ? ["enter"] : [option.key.toLowerCase(), "enter"] });
619
+ this.clearTerminalPrompt(target);
620
+ this.menuClosed(target);
621
+ return { menuClosed: true };
622
+ }
623
+ if (Date.now() >= deadline) {
624
+ const message = lines.trim().slice(0, 32_768) || "The terminal is still waiting for an answer.";
625
+ this.terminalPrompts.set(key, { tool: "Permissions", message, ...(choice ? { choice } : {}), at: Date.now() });
626
+ while (this.terminalPrompts.size > 64)
627
+ this.terminalPrompts.delete(this.terminalPrompts.keys().next().value);
628
+ return { menuClosed: false, waiting: { message, ...(choice ? { choice } : {}) } };
629
+ }
630
+ await new Promise(resolve => setTimeout(resolve, 150));
631
+ }
632
+ }
35
633
  approval(target) {
36
634
  const pending = [...this.pending.entries()].find(([, p]) => JSON.stringify(p.target) === JSON.stringify(target));
37
- return pending ? { actionId: pending[0], toolName: pending[1].tool, title: `Allow ${pending[1].tool}?`, message: pending[1].message } : undefined;
635
+ if (pending)
636
+ return { actionId: pending[0], toolName: pending[1].tool, title: pending[1].choice?.title ?? pending[1].title, message: pending[1].message,
637
+ details: pending[1].message, terminalOnly: target.source === "codex" && !pending[1].choice,
638
+ ...(pending[1].choice ? { choice: pending[1].choice } : {}), expiresAt: pending[1].expiresAt,
639
+ ...(pending[1].conductor ? { conductor: pending[1].conductor } : {}) };
640
+ const own = target.source === "opencode" ? this.opencodeApproval(target) : undefined;
641
+ if (own)
642
+ return own;
643
+ // A fan-out worker this conversation started is waiting on the owner.
644
+ const worker = this.fanoutHeld(target)[0];
645
+ return worker?.fanout ? { actionId: worker.fanout.actionId, toolName: worker.request.type, title: worker.request.title,
646
+ message: worker.request.message, expiresAt: worker.request.expiresAt } : undefined;
647
+ }
648
+ opencodeApproval(target) {
649
+ const held = [...this.opencode.values()].find(value => !value.fanout && JSON.stringify(value.target) === JSON.stringify(target));
650
+ if (held)
651
+ return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, expiresAt: held.request.expiresAt };
652
+ const request = opencodeRequest(target.session);
653
+ return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message, expiresAt: request.expiresAt } : undefined;
654
+ }
655
+ /** Live fan-out worker asks shown on this parent conversation, oldest first. */
656
+ fanoutHeld(target) {
657
+ const key = JSON.stringify(target);
658
+ return [...this.opencode.values()].filter(value => value.fanout && value.target && JSON.stringify(value.target) === key
659
+ && value.expiresAt > Date.now() && opencodeRequest(value.fanout.session)?.id === value.request.id);
660
+ }
661
+ pendingPanes(server, state) {
662
+ const panes = objects(state.panes);
663
+ const pending = new Set([...this.pending.values()].filter(p => p.target.server === server && panes.some(pane => {
664
+ if (pane.pane_id !== p.target.pane || pane.workspace_id !== p.target.workspace || pane.tab_id !== p.target.tab || pane.agent !== p.target.source)
665
+ return false;
666
+ const reported = object(pane.agent_session);
667
+ return reported.kind !== "id" || (reported.agent === p.target.source && reported.value === p.target.session);
668
+ })).map(p => p.target.pane));
669
+ // A permission or dialog the pane still draws after its hook let go.
670
+ for (const [key, entry] of this.terminalPrompts) {
671
+ if (!entry.choice || entry.questions?.length || Date.now() - entry.at > 900_000)
672
+ continue;
673
+ const target = JSON.parse(key);
674
+ if (target.server !== server)
675
+ continue;
676
+ if (panes.some(pane => pane.pane_id === target.pane && pane.workspace_id === target.workspace && pane.tab_id === target.tab
677
+ && pane.agent === target.source && ["waiting", "blocked"].includes(String(pane.agent_status))))
678
+ pending.add(target.pane);
679
+ }
680
+ for (const pane of panes) {
681
+ if (pane.agent !== "opencode")
682
+ continue;
683
+ const reported = object(pane.agent_session);
684
+ if (reported.kind === "id" && reported.agent === "opencode" && typeof reported.value === "string" && opencodeRequest(reported.value)) {
685
+ pending.add(String(pane.pane_id));
686
+ }
687
+ }
688
+ for (const held of this.opencode.values()) {
689
+ const parent = held.target;
690
+ if (!held.fanout || !parent || parent.server !== server)
691
+ continue;
692
+ if (panes.some(pane => pane.pane_id === parent.pane && pane.workspace_id === parent.workspace && pane.tab_id === parent.tab)
693
+ && this.fanoutHeld(parent).length)
694
+ pending.add(parent.pane);
695
+ }
696
+ return pending;
697
+ }
698
+ /** Hands the owner's answer to the fan-out launcher waiting on the worker's session. */
699
+ async answerFanout(id, held, decision) {
700
+ if (!["approve", "deny"].includes(String(decision)))
701
+ throw new BridgeError(400, "The approval answer is not valid.");
702
+ const file = held.fanout && opencodeApprovalFile(held.fanout.session, "answer");
703
+ if (!held.fanout || !file || opencodeRequest(held.fanout.session)?.id !== id)
704
+ throw new BridgeError(409, "This approval is no longer pending.");
705
+ await atomicInPrivateDir(file, JSON.stringify({ id, decision }));
706
+ this.opencode.delete(id);
707
+ this.pushBindings.dropAction(id);
38
708
  }
39
- async answer(target, id, decision) {
709
+ async answer(target, id, decision, updatedInput) {
710
+ const worker = [...this.opencode.entries()].find(([, held]) => held.fanout?.actionId === id && JSON.stringify(held.target) === JSON.stringify(target));
711
+ if (worker) {
712
+ if (updatedInput !== undefined)
713
+ throw new BridgeError(400, "Answers go with an approval.");
714
+ await validateTarget(target);
715
+ await this.answerFanout(worker[0], worker[1], decision);
716
+ return;
717
+ }
718
+ if (target.source === "opencode") {
719
+ if (!["approve", "deny"].includes(String(decision)))
720
+ throw new BridgeError(400, "The approval answer is not valid.");
721
+ const file = opencodeApprovalFile(target.session, "answer");
722
+ if (!file)
723
+ throw new BridgeError(400, "Invalid conversation identity.");
724
+ await validateTarget(target);
725
+ if (opencodeRequest(target.session)?.id !== id)
726
+ throw new BridgeError(409, "This approval is no longer pending.");
727
+ await atomicInPrivateDir(file, JSON.stringify({ id, decision }));
728
+ this.opencode.delete(id);
729
+ this.pushBindings.dropAction(id);
730
+ return;
731
+ }
40
732
  const entry = this.pending.get(id);
41
- if (!entry || JSON.stringify(entry.target) !== JSON.stringify(target) || !["approve", "deny"].includes(String(decision)))
733
+ if (!entry || JSON.stringify(entry.target) !== JSON.stringify(target))
42
734
  throw new BridgeError(409, "This approval is no longer pending.");
735
+ const grantAnswer = entry.conductor && (decision === "allow-project" || decision === "allow-everywhere") ? decision : undefined;
736
+ if (grantAnswer && !entry.conductor)
737
+ throw new BridgeError(400, "Only a conductor dispatch or hand-off can write a grant.");
738
+ const effective = grantAnswer ? "approve" : decision;
739
+ if (!["approve", "deny"].includes(String(effective)))
740
+ throw new BridgeError(409, "This approval is no longer pending.");
741
+ if (updatedInput !== undefined && effective !== "approve")
742
+ throw new BridgeError(400, "Answers go with an approval.");
743
+ const answered = updatedInput === undefined ? undefined : answeredQuestionInput(entry.tool, entry.input, updatedInput);
43
744
  await validateTarget(target);
745
+ if (this.pending.get(id) !== entry || entry.response.destroyed)
746
+ throw new BridgeError(409, "This approval is no longer pending.");
747
+ if (grantAnswer) {
748
+ const conductor = entry.conductor;
749
+ if (grantAnswer === "allow-project" && !conductor.project)
750
+ throw new BridgeError(400, "This call has no project to scope a grant to.");
751
+ await ensureGrant({
752
+ scope: grantAnswer === "allow-everywhere" ? "global" : `project:${conductor.project}`,
753
+ actions: [conductor.action],
754
+ ...(conductor.computer && conductor.computer !== "anywhere" ? { computers: [conductor.computer] } : {}),
755
+ });
756
+ }
44
757
  if (this.pending.get(id) !== entry || entry.response.destroyed)
45
758
  throw new BridgeError(409, "This approval is no longer pending.");
46
759
  this.pending.delete(id);
760
+ this.dropPushBindings(id);
47
761
  clearTimeout(entry.timer);
48
762
  entry.response.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: {
49
- behavior: decision === "approve" ? "allow" : "deny", ...(decision === "deny" ? { message: "Declined in Phren." } : {}),
763
+ behavior: effective === "approve" ? "allow" : "deny", ...(effective === "deny" ? { message: "Declined in Phren." } : {}),
764
+ ...(answered ? { updatedInput: answered } : {}),
50
765
  } } }));
51
766
  }
767
+ /** A held approval that is really a terminal dialog, answered from the
768
+ * phone with its own keys: let the callback fall back to the terminal at
769
+ * once instead of leaving the card up until the 55-second timer. */
770
+ releaseChoice(target) {
771
+ for (const [id, entry] of this.pending) {
772
+ if (!entry.choice || JSON.stringify(entry.target) !== JSON.stringify(target))
773
+ continue;
774
+ this.pending.delete(id);
775
+ this.dropPushBindings(id);
776
+ clearTimeout(entry.timer);
777
+ if (!entry.response.destroyed)
778
+ entry.response.end("{}");
779
+ }
780
+ }
781
+ async answerPush(binding, decision) {
782
+ if (!["approve", "deny"].includes(String(decision)))
783
+ throw new BridgeError(400, "The approval answer is not valid.");
784
+ const linked = this.pushBindings.consume(binding);
785
+ if (!linked)
786
+ throw new BridgeError(409, "This approval is no longer pending.");
787
+ const pending = this.pending.get(linked.action);
788
+ if (pending) {
789
+ await this.answer(pending.target, linked.action, decision);
790
+ return;
791
+ }
792
+ const released = [...this.releasedHolds].find(([, hold]) => hold.action === linked.action);
793
+ if (released && !this.dialogActions.has(linked.action)) {
794
+ // The hold just ended: read the pane now rather than wait for the tick.
795
+ const target = JSON.parse(released[0]);
796
+ await this.syncTerminalDialog(target, true).catch(() => { });
797
+ const entry = this.terminalPrompts.get(released[0]);
798
+ if (entry?.choice?.title)
799
+ this.adoptReleasedHold(released[0], target, entry.choice, entry.choice.title);
800
+ }
801
+ if (this.dialogActions.has(linked.action)) {
802
+ await this.answerDialog(linked.action, decision);
803
+ return;
804
+ }
805
+ const held = this.opencode.get(linked.action);
806
+ // The binding is the single-use proof for a worker's ask, whose parent
807
+ // may not be in any pane the Hook can see.
808
+ if (held?.fanout) {
809
+ await this.answerFanout(linked.action, held, decision);
810
+ return;
811
+ }
812
+ if (held?.target) {
813
+ await this.answer(held.target, linked.action, decision);
814
+ return;
815
+ }
816
+ throw new BridgeError(409, "This approval is no longer pending.");
817
+ }
818
+ /** Where a pushed ask lives, without answering it: the phone opens that
819
+ * session's details when the notification itself is tapped. */
820
+ pushTarget(binding) {
821
+ const action = this.pushBindings.peek(binding)?.action;
822
+ if (!action)
823
+ return undefined;
824
+ const held = this.pending.get(action)?.target ?? this.dialogActions.get(action)?.target ?? this.opencode.get(action)?.target;
825
+ if (held)
826
+ return held;
827
+ const released = [...this.releasedHolds].find(([, hold]) => hold.action === action);
828
+ return released ? JSON.parse(released[0]) : undefined;
829
+ }
830
+ /** Every waiting pane on this computer, each Hook tick, whether or not a
831
+ * phone watches: an approval an agent draws as a numbered dialog in its
832
+ * terminal (Claude's fallback prompts, Codex, OpenCode, Copilot) has no
833
+ * hook behind it, so this is the only way it reaches a phone with phren
834
+ * closed. Each dialog is pushed once; a pane that stops waiting drops it. */
835
+ async observeWaitingPanes(server, panes, resolve) {
836
+ const waiting = new Set();
837
+ for (const pane of panes) {
838
+ if (!pane.agent || !["waiting", "blocked"].includes(String(pane.agent_status)))
839
+ continue;
840
+ const target = await resolve(pane).catch(() => undefined);
841
+ if (!target)
842
+ continue;
843
+ const key = JSON.stringify(target);
844
+ waiting.add(key);
845
+ // A request its own hook already holds was pushed on arrival.
846
+ if ([...this.pending.values()].some(held => JSON.stringify(held.target) === key))
847
+ continue;
848
+ // Read the dialog even with no push device: the overview marks the
849
+ // tab as needing permission from it, and the phone answers it there.
850
+ await this.syncTerminalDialog(target, true).catch(() => { });
851
+ if (!this.push.available)
852
+ continue;
853
+ const entry = this.terminalPrompts.get(key);
854
+ const title = entry?.dialog || entry?.released ? entry.choice?.title : undefined;
855
+ if (!entry?.choice || !title) {
856
+ this.dropDialogPush(key);
857
+ continue;
858
+ }
859
+ if (this.dialogPushes.get(key)?.title === title)
860
+ continue;
861
+ this.dropDialogPush(key);
862
+ // Its own notification is already on the phone: answer that one.
863
+ if (this.adoptReleasedHold(key, target, entry.choice, title))
864
+ continue;
865
+ const action = `dialog-${randomUUID()}`, binding = randomUUID(), expiresAt = Date.now() + DIALOG_PUSH_MS;
866
+ this.dialogPushes.set(key, { action, title });
867
+ this.dialogActions.set(action, { target, choice: entry.choice, expiresAt });
868
+ this.pushBindings.add(binding, { action, expiresAt });
869
+ void this.push.notify({ binding, provider: target.source, question: false, expiresAt: new Date(expiresAt).toISOString(),
870
+ title: `${AGENT_NAMES[target.source] ?? "An agent"} needs your approval`, message: title.slice(0, 1_000) })
871
+ .then(delivered => { if (!delivered)
872
+ this.dropDialogPush(key); }).catch(() => this.dropDialogPush(key));
873
+ }
874
+ for (const [key, hold] of this.releasedHolds) {
875
+ // Answered in the terminal, or expired: the notification can no longer act.
876
+ if ((!waiting.has(key) && JSON.parse(key).server === server) || hold.expiresAt <= Date.now()) {
877
+ this.dropPushBindings(hold.action);
878
+ this.releasedHolds.delete(key);
879
+ }
880
+ }
881
+ for (const [key, pushed] of this.dialogPushes) {
882
+ if (!waiting.has(key) && JSON.parse(key).server === server) {
883
+ this.dialogActions.delete(pushed.action);
884
+ this.dropPushBindings(pushed.action);
885
+ this.dialogPushes.delete(key);
886
+ }
887
+ }
888
+ }
889
+ adoptReleasedHold(key, target, choice, title) {
890
+ const hold = this.releasedHolds.get(key);
891
+ this.releasedHolds.delete(key);
892
+ if (!hold || hold.expiresAt <= Date.now())
893
+ return false;
894
+ this.dialogPushes.set(key, { action: hold.action, title });
895
+ this.dialogActions.set(hold.action, { target, choice, expiresAt: hold.expiresAt });
896
+ return true;
897
+ }
898
+ dropDialogPush(key) {
899
+ const pushed = this.dialogPushes.get(key);
900
+ if (!pushed)
901
+ return;
902
+ this.dialogActions.delete(pushed.action);
903
+ this.dropPushBindings(pushed.action);
904
+ this.dialogPushes.delete(key);
905
+ }
906
+ /** Approve picks the dialog's yes/allow row (else its first), Deny its
907
+ * no/deny row (else Escape), typed as the pane's own keys. */
908
+ async answerDialog(action, decision) {
909
+ const dialog = this.dialogActions.get(action);
910
+ if (!dialog || dialog.expiresAt <= Date.now())
911
+ throw new BridgeError(409, "This approval is no longer pending.");
912
+ const key = JSON.stringify(dialog.target);
913
+ await validateTarget(dialog.target, false, true);
914
+ const live = this.terminalPrompts.get(key)?.choice;
915
+ if (!live || live.title !== dialog.choice.title) {
916
+ this.dropDialogPush(key);
917
+ throw new BridgeError(409, "That question in the terminal has changed. Open phren to answer it.");
918
+ }
919
+ const option = decision === "approve"
920
+ ? live.options.find(row => /^(yes|allow|approve|proceed|continue|run)\b/i.test(row.label)) ?? live.options[0]
921
+ : live.options.find(row => /^(no|deny|reject|don'?t|cancel|skip)\b/i.test(row.label));
922
+ const keys = option ? await this.dialogAnswerKeys(dialog.target, [option.key]) : ["Escape"];
923
+ await rpc(dialog.target.server, "agent.send_keys", { target: dialog.target.pane,
924
+ keys: keys.map(key => key === "Enter" ? "enter" : key === "Escape" ? "esc" : key.toLowerCase()) });
925
+ this.clearTerminalPrompt(dialog.target);
926
+ this.dropDialogPush(key);
927
+ }
928
+ dropPushBindings(action) {
929
+ this.pushBindings.dropAction(action);
930
+ }
52
931
  async start() {
932
+ await this.push.start();
53
933
  // The public helper singleton was already checked before this is called.
54
934
  const previous = await lstat(localSocket()).catch(() => undefined);
55
935
  if (previous) {
@@ -71,34 +951,115 @@ export class AgentHooks {
71
951
  chunks.push(bytes);
72
952
  }
73
953
  const body = object(JSON.parse(Buffer.concat(chunks).toString())), target = targetSchema.parse(body.target);
954
+ if (this.modules?.has("git") === false && ["PreToolUse", "PostToolUse"].includes(String(body.event))) {
955
+ res.statusCode = 404;
956
+ res.end(JSON.stringify({ error: disabledHint("git") }));
957
+ return;
958
+ }
74
959
  const s = await snapshot(target.server);
75
- const pane = objects(s.panes).find(p => p.pane_id === target.pane && p.tab_id === target.tab && p.workspace_id === target.workspace);
960
+ const pane = findPane(s, { workspace: target.workspace, tab: target.tab, pane: target.pane });
76
961
  if (!pane || (pane.agent && pane.agent !== target.source))
77
962
  throw new Error("The pane changed");
78
963
  const info = object((await rpc(target.server, "pane.process_info", { pane_id: target.pane })).process_info);
79
964
  const pids = objects(info.foreground_processes).map(p => p.pid).filter(p => Number.isSafeInteger(p));
80
965
  if (!pids.length)
81
966
  throw new Error("No foreground process");
82
- const file = bindingPath(target.server, target.pane);
83
- await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
84
- const temporary = file + "." + randomUUID();
85
- await writeFile(temporary, JSON.stringify({ terminal: pane.terminal_id, source: target.source, session: target.session, pids }), { mode: 0o600, flag: "wx" });
86
- await rename(temporary, file);
87
- if (body.event !== "PermissionRequest" || target.source === "copilot" || !this.watching.has(JSON.stringify(target))) {
967
+ await atomicInPrivateDir(bindingPath(target.server, target.pane), JSON.stringify({ terminal: pane.terminal_id, source: target.source,
968
+ session: target.session, pids, workspace: target.workspace, tab: target.tab }));
969
+ // What a shell call changed on disk: snapshot before, diff after.
970
+ const input = typeof body.input === "string" ? { patch: body.input } : object(body.input), command = [input.command, input.cmd].find(v => typeof v === "string");
971
+ // A shell call by name, or any tool whose input is a command line —
972
+ // Codex has renamed its shell tool more than once.
973
+ if (body.event === "PreCompact") {
974
+ this.startCompacting(target);
975
+ res.end("{}");
976
+ return;
977
+ }
978
+ if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)))
979
+ this.stopCompacting(target);
980
+ if (body.event === "UserPromptSubmit") {
981
+ res.end(JSON.stringify(typeof body.prompt === "string" ? this.submitted(target, body.prompt.slice(0, 65_536)) : {}));
982
+ return;
983
+ }
984
+ if ((this.modules?.has("git") ?? true) && ["PreToolUse", "PostToolUse"].includes(String(body.event)) && capturesChanges(String(body.tool), input)) {
985
+ const conversation = `${target.source}:${target.session}`, id = String(body.toolUseId || "").slice(0, 200);
986
+ if (body.event === "PreToolUse")
987
+ await this.changes.before(conversation, id, typeof body.cwd === "string" && path.isAbsolute(body.cwd) ? body.cwd : await trustedDirectory(pane), command ?? "", input);
988
+ else
989
+ await this.changes.after(conversation, id);
88
990
  res.end("{}");
89
991
  return;
90
992
  }
91
- // Only wait while a phone is watching this exact session; otherwise the
92
- // agent's ordinary terminal permission prompt remains immediate.
993
+ if (body.event === "PermissionRequest")
994
+ this.terminalPrompts.delete(JSON.stringify(target));
995
+ if (body.event === "PermissionRequest") {
996
+ const conductor = conductorCall(String(body.tool || "action"), body.input);
997
+ if (conductor) {
998
+ // A standing grant answers the call before it becomes an approval card.
999
+ const grant = matchGrant(await listGrants().catch(() => []), {
1000
+ action: conductor.action, project: conductor.project, computer: conductor.computer,
1001
+ });
1002
+ if (grant) {
1003
+ res.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest", decision: { behavior: "allow" } } }));
1004
+ return;
1005
+ }
1006
+ }
1007
+ }
1008
+ if (body.event !== "PermissionRequest" || target.source === "copilot"
1009
+ || (!this.watching.has(JSON.stringify(target)) && !this.overview.has(target.server) && !this.push.available)) {
1010
+ if (body.event === "PermissionRequest")
1011
+ this.rememberTerminalPrompt(target, body);
1012
+ res.end("{}");
1013
+ return;
1014
+ }
1015
+ // A foreground watcher or configured push device can hold the callback.
1016
+ // Timeouts always return control to the ordinary terminal prompt.
93
1017
  if (this.pending.size >= 64) {
94
1018
  res.end("{}");
95
1019
  return;
96
1020
  }
97
1021
  const action = randomUUID();
98
- const timer = setTimeout(() => { this.pending.delete(action); res.end("{}"); }, 55_000);
99
- this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200),
100
- message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), timer });
101
- res.on("close", () => { clearTimeout(timer); this.pending.delete(action); });
1022
+ this.dialogReads.delete(JSON.stringify(target));
1023
+ const conductor = body.event === "PermissionRequest" ? conductorCall(String(body.tool || "action"), body.input) : undefined;
1024
+ const locallyWatched = this.watching.has(JSON.stringify(target)) || this.overview.has(target.server);
1025
+ // When the hold ends the request stays in the terminal. A pushed
1026
+ // notification keeps working: its binding waits for the pane's dialog
1027
+ // and then answers that, instead of going dead with the hold.
1028
+ let released = false;
1029
+ const timer = setTimeout(() => {
1030
+ released = true;
1031
+ this.pending.delete(action);
1032
+ this.rememberTerminalPrompt(target, body);
1033
+ if (this.pushedHolds.has(action))
1034
+ this.releasedHolds.set(JSON.stringify(target), { action, expiresAt: this.pushedHolds.get(action) });
1035
+ this.pushedHolds.delete(action);
1036
+ res.end("{}");
1037
+ }, APPROVAL_HOLD_MS);
1038
+ const expiresAt = new Date(Date.now() + APPROVAL_HOLD_MS).toISOString();
1039
+ const { choice, title } = permissionPrompt(String(body.tool || "action"), body.input);
1040
+ this.pending.set(action, { target, response: res, tool: String(body.tool || "action").slice(0, 200), input: body.input, title,
1041
+ message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}), expiresAt, timer,
1042
+ ...(conductor ? { conductor } : {}) });
1043
+ res.on("close", () => { clearTimeout(timer); this.pending.delete(action); this.pushedHolds.delete(action); if (!released)
1044
+ this.dropPushBindings(action); });
1045
+ if (this.push.available) {
1046
+ const binding = randomUUID(), pushExpiresAt = Date.now() + DIALOG_PUSH_MS;
1047
+ this.pushBindings.add(binding, { action, expiresAt: pushExpiresAt });
1048
+ this.pushedHolds.set(action, pushExpiresAt);
1049
+ void this.push.notify({ binding, provider: target.source, question: body.tool === "AskUserQuestion",
1050
+ expiresAt: new Date(pushExpiresAt).toISOString() }).catch(() => false).then(delivered => {
1051
+ if (!delivered) {
1052
+ this.pushBindings.consume(binding);
1053
+ this.pushedHolds.delete(action);
1054
+ const pending = this.pending.get(action);
1055
+ if (!locallyWatched && pending) {
1056
+ clearTimeout(pending.timer);
1057
+ this.pending.delete(action);
1058
+ res.end("{}");
1059
+ }
1060
+ }
1061
+ });
1062
+ }
102
1063
  }
103
1064
  catch {
104
1065
  if (!res.headersSent)
@@ -109,8 +1070,41 @@ export class AgentHooks {
109
1070
  this.server.requestTimeout = 65_000;
110
1071
  await new Promise((resolve, reject) => { this.server.once("error", reject); this.server.listen(localSocket(), () => resolve()); });
111
1072
  await chmod(localSocket(), 0o600);
1073
+ // A permission ask the opencode plugin writes must reach the phone even
1074
+ // when nobody is polling; fs.watch catches the atomic rename, and a slow
1075
+ // poll covers a watcher that a platform drops.
1076
+ await mkdir(this.approvalsDirectory(), { recursive: true, mode: 0o700 }).catch(() => { });
1077
+ try {
1078
+ this.opencodeWatcher = watch(this.approvalsDirectory(), { persistent: false }, () => this.scheduleOpencodeSweep());
1079
+ this.opencodeWatcher.on("error", () => { this.opencodeWatcher?.close(); this.opencodeWatcher = undefined; });
1080
+ }
1081
+ catch {
1082
+ this.opencodeWatcher = undefined;
1083
+ }
1084
+ // The poll backs up the watcher. It skips while nothing is held and every
1085
+ // running Herdr server's recent snapshot shows no opencode pane; a new
1086
+ // request file still reaches the sweep through the watcher.
1087
+ this.opencodePoll = setInterval(() => {
1088
+ countTick("opencode-approvals");
1089
+ const panes = this.opencodeWatcher && !this.opencode.size ? knownPanes(OPENCODE_PANES_FRESH_MS) : undefined;
1090
+ if (panes && !panes.some(pane => pane.agent === "opencode"))
1091
+ return;
1092
+ this.scheduleOpencodeSweep();
1093
+ }, APPROVAL_SWEEP_MS);
1094
+ this.opencodePoll.unref?.();
1095
+ this.fanoutTimer = setInterval(() => { countTick("fanout-blocked"); void this.sweepBlockedFanouts(); }, FANOUT_SWEEP_MS);
1096
+ this.fanoutTimer.unref?.();
1097
+ // The archive sweep runs once at start so a long-dormant store clears
1098
+ // immediately, then hourly.
1099
+ void this.sweepFanoutArchive();
1100
+ this.fanoutArchiveTimer = setInterval(() => { countTick("fanout-archive"); void this.sweepFanoutArchive(); }, FANOUT_ARCHIVE_MS);
1101
+ this.fanoutArchiveTimer.unref?.();
1102
+ this.scheduleOpencodeSweep();
1103
+ void this.sweepBlockedFanouts();
112
1104
  }
113
1105
  close() {
1106
+ this.closed = true;
1107
+ void this.changes.close().catch(() => { });
114
1108
  for (const pending of this.pending.values()) {
115
1109
  clearTimeout(pending.timer);
116
1110
  pending.response.end("{}");
@@ -118,6 +1112,19 @@ export class AgentHooks {
118
1112
  this.pending.clear();
119
1113
  this.server?.close();
120
1114
  this.server?.closeAllConnections();
1115
+ this.pushBindings.clear();
1116
+ this.opencode.clear();
1117
+ if (this.opencodeDebounce)
1118
+ clearTimeout(this.opencodeDebounce);
1119
+ if (this.opencodePoll)
1120
+ clearInterval(this.opencodePoll);
1121
+ this.opencodeWatcher?.close();
1122
+ this.opencodeWatcher = undefined;
1123
+ if (this.fanoutTimer)
1124
+ clearInterval(this.fanoutTimer);
1125
+ if (this.fanoutArchiveTimer)
1126
+ clearInterval(this.fanoutArchiveTimer);
1127
+ this.fanoutSeen.clear();
121
1128
  }
122
1129
  }
123
1130
  export async function agentHook(source) {
@@ -125,9 +1132,7 @@ export async function agentHook(source) {
125
1132
  // A missing helper must never prevent the coding agent from running.
126
1133
  if (process.env.HERDR_ENV !== "1" || !process.env.HERDR_SOCKET_PATH)
127
1134
  return;
128
- const socket = path.resolve(process.env.HERDR_SOCKET_PATH), root = path.resolve(herdrRoot());
129
- const server = socket === path.join(root, "herdr.sock") ? "default"
130
- : socket.startsWith(path.join(root, "sessions") + path.sep) ? path.basename(path.dirname(socket)) : undefined;
1135
+ const server = herdrPaneFromEnv()?.server;
131
1136
  if (!server)
132
1137
  return;
133
1138
  let input = "";
@@ -142,14 +1147,20 @@ export async function agentHook(source) {
142
1147
  const target = targetSchema.parse({ server, workspace: process.env.HERDR_WORKSPACE_ID, tab: process.env.HERDR_TAB_ID,
143
1148
  pane: process.env.HERDR_PANE_ID, source, session: value.session_id || value.sessionId });
144
1149
  const event = String(value.hook_event_name || "SessionStart");
145
- const data = JSON.stringify({ target, event, tool: value.tool_name, input: value.tool_input });
1150
+ const modules = moduleSnapshot(defaultPhrenPath(), undefined, true);
1151
+ if (!modules.has("hook") || (event.endsWith("ToolUse") && !modules.has("git")))
1152
+ return;
1153
+ const data = JSON.stringify({ target, event, tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
1154
+ ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}) });
146
1155
  await new Promise(resolve => {
147
- const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : 1500,
1156
+ const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? 8_000 : 1500,
148
1157
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(data) } }, res => {
149
1158
  let result = "";
150
1159
  res.on("data", chunk => { result += chunk.toString(); if (result.length > 16_384)
151
1160
  req.destroy(); });
152
- res.on("end", () => { if (res.statusCode === 200 && event === "PermissionRequest")
1161
+ // Only a decision reaches the agent: an approval answer, or a refusal of
1162
+ // a prompt Phren meant for another conversation. An empty reply says nothing.
1163
+ res.on("end", () => { if (res.statusCode === 200 && (event === "PermissionRequest" || (event === "UserPromptSubmit" && result.includes("\"decision\""))))
153
1164
  process.stdout.write(result); resolve(); });
154
1165
  res.on("error", () => resolve());
155
1166
  });