@phren/cli 0.2.15 → 0.2.16

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