@phren/cli 0.2.14 → 0.2.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (387) hide show
  1. package/README.md +2 -2
  2. package/dist/agent-instructions.d.ts +12 -0
  3. package/dist/agent-instructions.js +52 -0
  4. package/dist/bridge/agent-hook-stores.d.ts +32 -0
  5. package/dist/bridge/agent-hook-stores.js +67 -0
  6. package/dist/bridge/agent-hooks.d.ts +193 -2
  7. package/dist/bridge/agent-hooks.js +1045 -38
  8. package/dist/bridge/canary.d.ts +27 -0
  9. package/dist/bridge/canary.js +189 -0
  10. package/dist/bridge/changes.d.ts +57 -0
  11. package/dist/bridge/changes.js +403 -0
  12. package/dist/bridge/client.d.ts +3 -0
  13. package/dist/bridge/client.js +36 -0
  14. package/dist/bridge/code-note.d.ts +22 -0
  15. package/dist/bridge/code-note.js +42 -0
  16. package/dist/bridge/code-routes.d.ts +133 -0
  17. package/dist/bridge/code-routes.js +319 -0
  18. package/dist/bridge/codex-threads.d.ts +27 -0
  19. package/dist/bridge/codex-threads.js +442 -0
  20. package/dist/bridge/command.d.ts +7 -0
  21. package/dist/bridge/command.js +50 -5
  22. package/dist/bridge/computer-names.d.ts +4 -0
  23. package/dist/bridge/computer-names.js +16 -0
  24. package/dist/bridge/computers.d.ts +9 -0
  25. package/dist/bridge/computers.js +111 -0
  26. package/dist/bridge/context.d.ts +14 -0
  27. package/dist/bridge/context.js +149 -0
  28. package/dist/bridge/dispatch-command.d.ts +3 -0
  29. package/dist/bridge/dispatch-command.js +93 -0
  30. package/dist/bridge/dispatch-hosts.d.ts +23 -0
  31. package/dist/bridge/dispatch-hosts.js +25 -0
  32. package/dist/bridge/dispatch-returns.d.ts +123 -0
  33. package/dist/bridge/dispatch-returns.js +279 -0
  34. package/dist/bridge/dispatch-tree.d.ts +54 -0
  35. package/dist/bridge/dispatch-tree.js +198 -0
  36. package/dist/bridge/dispatch.d.ts +207 -0
  37. package/dist/bridge/dispatch.js +261 -0
  38. package/dist/bridge/enroll.d.ts +31 -0
  39. package/dist/bridge/enroll.js +236 -0
  40. package/dist/bridge/fanout-messages.d.ts +74 -0
  41. package/dist/bridge/fanout-messages.js +230 -0
  42. package/dist/bridge/fanouts.d.ts +160 -0
  43. package/dist/bridge/fanouts.js +702 -0
  44. package/dist/bridge/file-range.d.ts +16 -0
  45. package/dist/bridge/file-range.js +90 -0
  46. package/dist/bridge/files.d.ts +20 -0
  47. package/dist/bridge/files.js +54 -0
  48. package/dist/bridge/git-publish.d.ts +23 -0
  49. package/dist/bridge/git-publish.js +145 -0
  50. package/dist/bridge/git-worktrees.d.ts +21 -0
  51. package/dist/bridge/git-worktrees.js +150 -0
  52. package/dist/bridge/git.d.ts +54 -0
  53. package/dist/bridge/git.js +552 -0
  54. package/dist/bridge/grants.d.ts +31 -0
  55. package/dist/bridge/grants.js +181 -0
  56. package/dist/bridge/hand-off.d.ts +79 -0
  57. package/dist/bridge/hand-off.js +151 -0
  58. package/dist/bridge/health.d.ts +128 -0
  59. package/dist/bridge/health.js +260 -0
  60. package/dist/bridge/herdr.d.ts +79 -6
  61. package/dist/bridge/herdr.js +292 -27
  62. package/dist/bridge/hook-main.js +2 -0
  63. package/dist/bridge/install.d.ts +32 -1
  64. package/dist/bridge/install.js +225 -38
  65. package/dist/bridge/launch-worktree.d.ts +21 -0
  66. package/dist/bridge/launch-worktree.js +70 -0
  67. package/dist/bridge/limits.d.ts +20 -0
  68. package/dist/bridge/limits.js +65 -0
  69. package/dist/bridge/locate.d.ts +16 -0
  70. package/dist/bridge/locate.js +75 -0
  71. package/dist/bridge/metrics.d.ts +29 -0
  72. package/dist/bridge/metrics.js +71 -0
  73. package/dist/bridge/model-switch.d.ts +35 -0
  74. package/dist/bridge/model-switch.js +250 -0
  75. package/dist/bridge/models.d.ts +46 -0
  76. package/dist/bridge/models.js +257 -0
  77. package/dist/bridge/opencode-approvals.d.ts +6 -0
  78. package/dist/bridge/opencode-approvals.js +60 -0
  79. package/dist/bridge/pane-text.d.ts +15 -0
  80. package/dist/bridge/pane-text.js +23 -0
  81. package/dist/bridge/peers.d.ts +27 -0
  82. package/dist/bridge/peers.js +130 -0
  83. package/dist/bridge/projects.d.ts +12 -1
  84. package/dist/bridge/projects.js +268 -20
  85. package/dist/bridge/protocol.d.ts +35 -2
  86. package/dist/bridge/protocol.js +42 -7
  87. package/dist/bridge/push.d.ts +83 -0
  88. package/dist/bridge/push.js +199 -0
  89. package/dist/bridge/questions.d.ts +38 -0
  90. package/dist/bridge/questions.js +205 -0
  91. package/dist/bridge/schedule-format.d.ts +103 -0
  92. package/dist/bridge/schedule-format.js +266 -0
  93. package/dist/bridge/schedule-launch.d.ts +11 -0
  94. package/dist/bridge/schedule-launch.js +169 -0
  95. package/dist/bridge/schedule-watch.d.ts +52 -0
  96. package/dist/bridge/schedule-watch.js +242 -0
  97. package/dist/bridge/schedules.d.ts +48 -0
  98. package/dist/bridge/schedules.js +205 -0
  99. package/dist/bridge/server-launch.d.ts +14 -0
  100. package/dist/bridge/server-launch.js +218 -0
  101. package/dist/bridge/server-overview.d.ts +45 -0
  102. package/dist/bridge/server-overview.js +102 -0
  103. package/dist/bridge/server-pane-routes.d.ts +29 -0
  104. package/dist/bridge/server-pane-routes.js +400 -0
  105. package/dist/bridge/server-routes.d.ts +106 -0
  106. package/dist/bridge/server-routes.js +538 -0
  107. package/dist/bridge/server-stream.d.ts +46 -0
  108. package/dist/bridge/server-stream.js +253 -0
  109. package/dist/bridge/server.d.ts +3 -15
  110. package/dist/bridge/server.js +162 -264
  111. package/dist/bridge/session-servers.d.ts +24 -0
  112. package/dist/bridge/session-servers.js +136 -0
  113. package/dist/bridge/side-questions.d.ts +74 -0
  114. package/dist/bridge/side-questions.js +252 -0
  115. package/dist/bridge/simulators.d.ts +28 -0
  116. package/dist/bridge/simulators.js +198 -0
  117. package/dist/bridge/speech-transcribe.d.ts +24 -0
  118. package/dist/bridge/speech-transcribe.js +124 -0
  119. package/dist/bridge/speech.d.ts +35 -0
  120. package/dist/bridge/speech.js +98 -0
  121. package/dist/bridge/steps.d.ts +13 -0
  122. package/dist/bridge/steps.js +222 -0
  123. package/dist/bridge/tab-activity.d.ts +18 -0
  124. package/dist/bridge/tab-activity.js +99 -0
  125. package/dist/bridge/terminal-choice.d.ts +64 -0
  126. package/dist/bridge/terminal-choice.js +281 -0
  127. package/dist/bridge/transcript-claude.d.ts +22 -0
  128. package/dist/bridge/transcript-claude.js +353 -0
  129. package/dist/bridge/transcript-codex.d.ts +30 -0
  130. package/dist/bridge/transcript-codex.js +282 -0
  131. package/dist/bridge/transcript-copilot.d.ts +4 -0
  132. package/dist/bridge/transcript-copilot.js +14 -0
  133. package/dist/bridge/transcript-opencode.d.ts +5 -0
  134. package/dist/bridge/transcript-opencode.js +26 -0
  135. package/dist/bridge/transcript-preview.d.ts +94 -0
  136. package/dist/bridge/transcript-preview.js +476 -0
  137. package/dist/bridge/transcripts.d.ts +81 -4
  138. package/dist/bridge/transcripts.js +332 -67
  139. package/dist/bridge/transport.d.ts +3 -0
  140. package/dist/bridge/transport.js +96 -15
  141. package/dist/bridge/uploads.d.ts +15 -0
  142. package/dist/bridge/uploads.js +44 -2
  143. package/dist/bridge/usage.d.ts +124 -0
  144. package/dist/bridge/usage.js +859 -0
  145. package/dist/bridge-hook.mjs +41246 -21385
  146. package/dist/cli/actions.js +14 -1
  147. package/dist/cli/config-proactivity.d.ts +3 -1
  148. package/dist/cli/config-proactivity.js +35 -3
  149. package/dist/cli/config.js +4 -1
  150. package/dist/cli/extract.js +3 -6
  151. package/dist/cli/govern.js +5 -2
  152. package/dist/cli/hooks-globs.js +1 -1
  153. package/dist/cli/hooks.d.ts +1 -1
  154. package/dist/cli/hooks.js +9 -7
  155. package/dist/cli/namespaces-projects.js +12 -6
  156. package/dist/cli/namespaces-store.js +37 -6
  157. package/dist/cli/namespaces-tasks.js +1 -1
  158. package/dist/cli/schedules.d.ts +1 -0
  159. package/dist/cli/schedules.js +164 -0
  160. package/dist/cli/session-background.js +1 -1
  161. package/dist/cli/session-git.d.ts +8 -5
  162. package/dist/cli/session-git.js +45 -120
  163. package/dist/cli/session-start.js +3 -1
  164. package/dist/cli/session-stop.js +19 -8
  165. package/dist/cli/team.js +13 -10
  166. package/dist/cli-handlers.d.ts +1 -1
  167. package/dist/cli-handlers.js +8 -4
  168. package/dist/cli-help.d.ts +5 -4
  169. package/dist/cli-help.js +15 -15
  170. package/dist/cli-registry.d.ts +4 -1
  171. package/dist/cli-registry.js +119 -6
  172. package/dist/content/archive.js +2 -2
  173. package/dist/content/citation.d.ts +11 -0
  174. package/dist/content/citation.js +18 -0
  175. package/dist/content/learning.js +2 -0
  176. package/dist/content/summarize.d.ts +14 -15
  177. package/dist/content/summarize.js +60 -5
  178. package/dist/content/validate.d.ts +3 -1
  179. package/dist/content/validate.js +26 -8
  180. package/dist/core/project-registry.d.ts +26 -0
  181. package/dist/core/project-registry.js +573 -0
  182. package/dist/core/project.js +2 -3
  183. package/dist/data/access.d.ts +7 -1
  184. package/dist/data/access.js +13 -3
  185. package/dist/data/tasks.d.ts +18 -3
  186. package/dist/data/tasks.js +8 -7
  187. package/dist/entrypoint.js +44 -10
  188. package/dist/fanout/adapters/claude.d.ts +2 -0
  189. package/dist/fanout/adapters/claude.js +7 -0
  190. package/dist/fanout/adapters/codex.d.ts +2 -0
  191. package/dist/fanout/adapters/codex.js +9 -0
  192. package/dist/fanout/adapters/opencode.d.ts +4 -0
  193. package/dist/fanout/adapters/opencode.js +9 -0
  194. package/dist/fanout/adapters/types.d.ts +21 -0
  195. package/dist/fanout/adapters/types.js +3 -0
  196. package/dist/fanout/command.d.ts +2 -0
  197. package/dist/fanout/command.js +78 -0
  198. package/dist/fanout/launcher.d.ts +27 -0
  199. package/dist/fanout/launcher.js +156 -0
  200. package/dist/fanout/opencode-serve.d.ts +24 -0
  201. package/dist/fanout/opencode-serve.js +191 -0
  202. package/dist/fanout/picker.d.ts +91 -0
  203. package/dist/fanout/picker.js +51 -0
  204. package/dist/fanout/usage.d.ts +5 -0
  205. package/dist/fanout/usage.js +51 -0
  206. package/dist/fanout/watchdog.d.ts +10 -0
  207. package/dist/fanout/watchdog.js +27 -0
  208. package/dist/filenames.d.ts +9 -0
  209. package/dist/filenames.js +11 -0
  210. package/dist/finding/context.js +4 -22
  211. package/dist/generated/memory-ui-graph.browser.js +279 -283
  212. package/dist/governance/policy-constants.d.ts +11 -0
  213. package/dist/governance/policy-constants.js +9 -0
  214. package/dist/governance/policy.d.ts +5 -8
  215. package/dist/governance/policy.js +7 -5
  216. package/dist/graph-core/camera.d.ts +24 -0
  217. package/dist/graph-core/camera.js +18 -0
  218. package/dist/graph-core/index.d.ts +2 -0
  219. package/dist/graph-core/index.js +2 -0
  220. package/dist/graph-core/labels.d.ts +77 -0
  221. package/dist/graph-core/labels.js +124 -0
  222. package/dist/graph-core/model.d.ts +13 -0
  223. package/dist/graph-core/model.js +33 -0
  224. package/dist/graph-core/types.d.ts +2 -0
  225. package/dist/home-paths.d.ts +7 -0
  226. package/dist/home-paths.js +21 -0
  227. package/dist/hooks.d.ts +3 -0
  228. package/dist/hooks.js +13 -0
  229. package/dist/index.js +24 -2
  230. package/dist/init/guard-globals.d.ts +1 -1
  231. package/dist/init/guard-globals.js +4 -4
  232. package/dist/init/init-configure.js +3 -3
  233. package/dist/init/init-uninstall.js +2 -2
  234. package/dist/init/init-walkthrough.d.ts +2 -0
  235. package/dist/init/init-walkthrough.js +17 -6
  236. package/dist/init/init.js +26 -6
  237. package/dist/init/management-preset.d.ts +1 -1
  238. package/dist/init/management-preset.js +2 -2
  239. package/dist/init/preferences.js +1 -1
  240. package/dist/init/self-wiring.js +1 -1
  241. package/dist/init/setup.d.ts +3 -26
  242. package/dist/init/setup.js +49 -588
  243. package/dist/init/shared.js +2 -0
  244. package/dist/init/store-gitignore.d.ts +1 -1
  245. package/dist/init/store-gitignore.js +2 -0
  246. package/dist/init/teardown.d.ts +1 -1
  247. package/dist/init/teardown.js +2 -2
  248. package/dist/link/context.js +1 -1
  249. package/dist/link/doctor.d.ts +22 -1
  250. package/dist/link/doctor.js +100 -54
  251. package/dist/link/link.js +29 -61
  252. package/dist/link/refresh.js +2 -2
  253. package/dist/link/skills.js +26 -5
  254. package/dist/machine-identity.d.ts +3 -0
  255. package/dist/machine-identity.js +6 -0
  256. package/dist/mcp/profile.d.ts +2 -15
  257. package/dist/mcp/profile.js +64 -9
  258. package/dist/memory-ui-graph.runtime.js +279 -283
  259. package/dist/modules/code-package.d.ts +16 -0
  260. package/dist/modules/code-package.js +152 -0
  261. package/dist/modules/command.d.ts +2 -0
  262. package/dist/modules/command.js +67 -0
  263. package/dist/modules/config.d.ts +4 -0
  264. package/dist/modules/config.js +70 -0
  265. package/dist/modules/manifest.d.ts +41 -0
  266. package/dist/modules/manifest.js +1 -0
  267. package/dist/modules/provision.d.ts +3 -0
  268. package/dist/modules/provision.js +84 -0
  269. package/dist/modules/registry.d.ts +16 -0
  270. package/dist/modules/registry.js +250 -0
  271. package/dist/modules/runtime.d.ts +15 -0
  272. package/dist/modules/runtime.js +59 -0
  273. package/dist/package-metadata.js +10 -2
  274. package/dist/phren-dotenv.js +4 -2
  275. package/dist/phren-paths.d.ts +3 -2
  276. package/dist/phren-paths.js +4 -5
  277. package/dist/profile-store.js +4 -5
  278. package/dist/project-config.d.ts +19 -1
  279. package/dist/project-config.js +29 -3
  280. package/dist/project-topics.js +4 -4
  281. package/dist/provider-adapters.js +1 -4
  282. package/dist/query-correlation.js +6 -6
  283. package/dist/session/artifacts.js +5 -5
  284. package/dist/session/checkpoints.js +5 -0
  285. package/dist/session/utils.d.ts +2 -2
  286. package/dist/session/utils.js +6 -6
  287. package/dist/shared/content.d.ts +1 -1
  288. package/dist/shared/content.js +1 -1
  289. package/dist/shared/data-utils.js +1 -1
  290. package/dist/shared/fragment-graph.d.ts +1 -1
  291. package/dist/shared/fragment-graph.js +5 -5
  292. package/dist/shared/index.js +48 -7
  293. package/dist/shared/retrieval.d.ts +18 -1
  294. package/dist/shared/retrieval.js +100 -11
  295. package/dist/shared/search-fallback.js +4 -6
  296. package/dist/shared/sqljs.d.ts +2 -0
  297. package/dist/shared/sqljs.js +4 -2
  298. package/dist/shared.d.ts +0 -1
  299. package/dist/shared.js +0 -1
  300. package/dist/shell/input.d.ts +1 -5
  301. package/dist/shell/input.js +16 -10
  302. package/dist/shell/palette.d.ts +2 -2
  303. package/dist/shell/palette.js +3 -7
  304. package/dist/shell/render.d.ts +3 -1
  305. package/dist/shell/render.js +4 -4
  306. package/dist/shell/shell.js +4 -1
  307. package/dist/shell/types.d.ts +1 -0
  308. package/dist/shell/types.js +4 -0
  309. package/dist/shell/view.d.ts +0 -4
  310. package/dist/shell/view.js +19 -27
  311. package/dist/skill/registry.js +25 -17
  312. package/dist/skill/state.d.ts +3 -0
  313. package/dist/skill/state.js +13 -7
  314. package/dist/status.js +38 -17
  315. package/dist/store-registry.d.ts +44 -18
  316. package/dist/store-registry.js +169 -60
  317. package/dist/store-weight.d.ts +1 -6
  318. package/dist/store-weight.js +4 -2
  319. package/dist/sync/auth-doctor.d.ts +8 -0
  320. package/dist/sync/auth-doctor.js +27 -0
  321. package/dist/sync/auth.d.ts +27 -0
  322. package/dist/sync/auth.js +114 -0
  323. package/dist/sync/conflict-resolve.d.ts +9 -0
  324. package/dist/sync/conflict-resolve.js +146 -0
  325. package/dist/sync/git-state.d.ts +4 -0
  326. package/dist/sync/git-state.js +49 -0
  327. package/dist/sync/outcome.d.ts +34 -0
  328. package/dist/sync/outcome.js +57 -0
  329. package/dist/sync/pull.d.ts +15 -7
  330. package/dist/sync/pull.js +84 -35
  331. package/dist/sync/store-merge.d.ts +29 -0
  332. package/dist/sync/store-merge.js +137 -0
  333. package/dist/sync/task-merge.d.ts +22 -0
  334. package/dist/sync/task-merge.js +158 -0
  335. package/dist/task/github.js +1 -1
  336. package/dist/task/lifecycle.d.ts +5 -0
  337. package/dist/task/lifecycle.js +67 -23
  338. package/dist/terminal-text.d.ts +5 -0
  339. package/dist/terminal-text.js +11 -0
  340. package/dist/test-global-setup.js +7 -0
  341. package/dist/tool-registry.d.ts +1 -1
  342. package/dist/tool-registry.js +3 -1
  343. package/dist/tools/code.d.ts +3 -0
  344. package/dist/tools/code.js +178 -0
  345. package/dist/tools/config.js +5 -0
  346. package/dist/tools/data.js +14 -7
  347. package/dist/tools/dispatch.d.ts +2 -0
  348. package/dist/tools/dispatch.js +66 -0
  349. package/dist/tools/finding.js +43 -41
  350. package/dist/tools/ops.js +5 -2
  351. package/dist/tools/search.js +21 -8
  352. package/dist/tools/session.js +21 -22
  353. package/dist/tools/tasks.js +8 -2
  354. package/dist/tools/types.d.ts +2 -2
  355. package/dist/tools/types.js +2 -2
  356. package/dist/ui/assets.js +1 -1
  357. package/dist/ui/data.js +14 -15
  358. package/dist/ui/deep-void.d.ts +1 -1
  359. package/dist/ui/deep-void.js +0 -1
  360. package/dist/ui/graph-chrome.d.ts +1 -1
  361. package/dist/ui/graph-chrome.js +51 -0
  362. package/dist/ui/page.js +5 -5
  363. package/dist/ui/scripts.js +67 -30
  364. package/dist/ui/server.js +34 -6
  365. package/dist/update.js +1 -1
  366. package/dist/utils-fts.js +1 -0
  367. package/dist/utils-helpers.d.ts +7 -0
  368. package/dist/utils-helpers.js +17 -0
  369. package/dist/utils.d.ts +1 -1
  370. package/dist/utils.js +1 -1
  371. package/package.json +45 -3
  372. package/plugins/opencode/phren-transcript.js +340 -0
  373. package/starter/README.md +4 -4
  374. package/starter/global/{CLAUDE.md → AGENTS.md} +2 -2
  375. package/starter/global/skills/conductor/SKILL.md +106 -0
  376. package/starter/global/skills/fanout/SKILL.md +20 -0
  377. package/starter/global/skills/phren-discover/SKILL.md +6 -6
  378. package/starter/global/skills/phren-init/SKILL.md +4 -4
  379. package/starter/global/skills/phren-sync/SKILL.md +3 -3
  380. package/starter/templates/frontend/reference/README.md +1 -1
  381. package/starter/templates/library/reference/README.md +1 -1
  382. package/starter/templates/monorepo/reference/README.md +1 -1
  383. package/starter/templates/python-project/reference/README.md +1 -1
  384. /package/starter/templates/frontend/{CLAUDE.md → AGENTS.md} +0 -0
  385. /package/starter/templates/library/{CLAUDE.md → AGENTS.md} +0 -0
  386. /package/starter/templates/monorepo/{CLAUDE.md → AGENTS.md} +0 -0
  387. /package/starter/templates/python-project/{CLAUDE.md → AGENTS.md} +0 -0
@@ -0,0 +1,124 @@
1
+ import { WebSocket } from "ws";
2
+ import { readSpeechKey } from "./speech.js";
3
+ /** Dictation through ElevenLabs Scribe v2 Realtime, for the phone's opt-in
4
+ * Scribe input. The phone streams 16 kHz mono PCM as binary frames; this
5
+ * computer forwards it to ElevenLabs with its own key, which never leaves
6
+ * here, and sends back `{type: "partial"|"committed", text}` frames. Errors
7
+ * are fixed messages by code: ElevenLabs' own text is never passed on. */
8
+ export const TRANSCRIBE_MODEL = "scribe_v2_realtime";
9
+ export const TRANSCRIBE_RATE = 16_000;
10
+ const ENDPOINT = "wss://api.elevenlabs.io/v1/speech-to-text/realtime";
11
+ /** Ten minutes of dictation per socket; the phone opens a fresh one after. */
12
+ const MAX_SESSION_MS = 10 * 60_000;
13
+ /** Audio held while the upstream socket opens: about eight seconds. */
14
+ const MAX_PENDING_BYTES = TRANSCRIBE_RATE * 2 * 8;
15
+ const MAX_KEYTERMS = 50;
16
+ const OPEN = 1;
17
+ /** The upstream URL: VAD commits, the phone's language and its vocabulary as keyterms. */
18
+ export function transcribeURL(query) {
19
+ const url = new URL(ENDPOINT);
20
+ url.searchParams.set("model_id", TRANSCRIBE_MODEL);
21
+ url.searchParams.set("audio_format", "pcm_16000");
22
+ url.searchParams.set("commit_strategy", "vad");
23
+ const language = query.get("language") ?? "";
24
+ if (/^[a-z]{2,3}$/.test(language))
25
+ url.searchParams.set("language_code", language);
26
+ const terms = query.getAll("keyterm").map(term => term.trim()).filter(term => term.length > 0 && term.length <= 50);
27
+ for (const term of [...new Set(terms)].slice(0, MAX_KEYTERMS))
28
+ url.searchParams.append("keyterms", term);
29
+ return url.toString();
30
+ }
31
+ const ERRORS = {
32
+ auth_error: { code: "transcribe-rejected", message: "ElevenLabs refused this computer's key." },
33
+ quota_exceeded: { code: "transcribe-quota", message: "The ElevenLabs quota on this computer's account is used up." },
34
+ rate_limited: { code: "transcribe-busy", message: "ElevenLabs is busy. Try again shortly." },
35
+ resource_exhausted: { code: "transcribe-busy", message: "ElevenLabs is busy. Try again shortly." },
36
+ queue_overflow: { code: "transcribe-busy", message: "ElevenLabs is busy. Try again shortly." },
37
+ session_time_limit_exceeded: { code: "transcribe-limit", message: "This dictation reached ElevenLabs' time limit." },
38
+ };
39
+ export function relayTranscription(client, query, options = {}) {
40
+ const connect = options.connect ?? ((url, key) => new WebSocket(url, { headers: { "xi-api-key": key } }));
41
+ return (async () => {
42
+ const key = await (options.key ?? readSpeechKey)();
43
+ const tell = (frame) => { if (client.readyState === OPEN)
44
+ client.send(JSON.stringify(frame)); };
45
+ if (!key) {
46
+ tell({ type: "error", code: "transcribe-unconfigured", error: "This computer has no ElevenLabs key." });
47
+ client.close(1008, "No ElevenLabs key");
48
+ return;
49
+ }
50
+ const upstream = connect(transcribeURL(query), key);
51
+ let pending = [], pendingBytes = 0, closed = false;
52
+ const finish = (code = 1000, reason = "") => {
53
+ if (closed)
54
+ return;
55
+ closed = true;
56
+ clearTimeout(limit);
57
+ try {
58
+ upstream.close();
59
+ }
60
+ catch { /* already closed */ }
61
+ if (client.readyState === OPEN)
62
+ client.close(code, reason);
63
+ };
64
+ const limit = setTimeout(() => finish(1000, "Session limit"), options.maxSessionMs ?? MAX_SESSION_MS);
65
+ limit.unref?.();
66
+ const chunk = (audio, commit = false) => JSON.stringify({
67
+ message_type: "input_audio_chunk", audio_base_64: audio.toString("base64"), commit, sample_rate: TRANSCRIBE_RATE
68
+ });
69
+ client.on("message", (data, isBinary) => {
70
+ if (closed)
71
+ return;
72
+ if (!isBinary) {
73
+ // The phone's only text frame: the person stopped, commit what's left.
74
+ if (upstream.readyState === OPEN)
75
+ upstream.send(chunk(Buffer.alloc(0), true));
76
+ return;
77
+ }
78
+ if (upstream.readyState === OPEN) {
79
+ upstream.send(chunk(data));
80
+ return;
81
+ }
82
+ pendingBytes += data.length;
83
+ if (pendingBytes > MAX_PENDING_BYTES) {
84
+ tell({ type: "error", code: "transcribe-failed", error: "ElevenLabs didn't answer." });
85
+ finish(1011);
86
+ return;
87
+ }
88
+ pending.push(data);
89
+ });
90
+ client.on("close", () => finish());
91
+ client.on("error", () => finish());
92
+ upstream.on("open", () => {
93
+ for (const audio of pending)
94
+ upstream.send(chunk(audio));
95
+ pending = [];
96
+ pendingBytes = 0;
97
+ });
98
+ upstream.on("message", data => {
99
+ let message;
100
+ try {
101
+ message = JSON.parse(data.toString("utf8"));
102
+ }
103
+ catch {
104
+ return;
105
+ }
106
+ const type = String(message.message_type ?? "");
107
+ const text = typeof message.text === "string" ? message.text : "";
108
+ if (type === "partial_transcript")
109
+ tell({ type: "partial", text });
110
+ else if (type === "committed_transcript")
111
+ tell({ type: "committed", text });
112
+ else if (type in ERRORS || /error|exceeded|invalid|throttled/.test(type)) {
113
+ const known = ERRORS[type] ?? { code: "transcribe-failed", message: "ElevenLabs couldn't transcribe this audio." };
114
+ // Too little speech is not a failure worth stopping for.
115
+ if (type === "insufficient_audio_activity" || type === "commit_throttled")
116
+ return;
117
+ tell({ type: "error", code: known.code, error: known.message });
118
+ finish(1011);
119
+ }
120
+ });
121
+ upstream.on("error", () => { tell({ type: "error", code: "transcribe-failed", error: "Couldn't reach ElevenLabs." }); finish(1011); });
122
+ upstream.on("close", () => finish());
123
+ })();
124
+ }
@@ -0,0 +1,35 @@
1
+ import type { ServerResponse } from "node:http";
2
+ import { z } from "zod";
3
+ import { BridgeError, type Json } from "./protocol.js";
4
+ /** Spoken replies for the phone's talk mode. The phone sends a sentence; the
5
+ * Hook voices it with ElevenLabs and streams the audio back. The API key is
6
+ * read on this computer, used only in the request to ElevenLabs, and never
7
+ * appears in a response, including errors. */
8
+ /** Raw signed 16-bit little-endian mono PCM, so the phone can queue it
9
+ * straight into its audio engine without decoding. */
10
+ export declare const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
11
+ /** ElevenLabs' lowest-latency model. */
12
+ export declare const SPEECH_MODEL = "eleven_flash_v2_5";
13
+ /** River: relaxed, neutral and informative. PHREN_SPEECH_VOICE overrides it. */
14
+ export declare const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
15
+ export declare const speechRequest: z.ZodObject<{
16
+ text: z.ZodString;
17
+ }, z.core.$strip>;
18
+ export interface SpeechOptions {
19
+ fetch?: typeof fetch;
20
+ /** Resolves the ElevenLabs key; defaults to ~/.config/mina-trailer.json. */
21
+ key?: () => Promise<string | undefined>;
22
+ voice?: string;
23
+ }
24
+ export declare function speechKeyFile(env?: NodeJS.ProcessEnv): string;
25
+ export declare function readSpeechKey(file?: string): Promise<string | undefined>;
26
+ /** A fixed message per ElevenLabs failure: its own response text is never
27
+ * passed on. */
28
+ export declare function speechError(upstream: Response): Promise<BridgeError>;
29
+ /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
30
+ export declare function synthesizeSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<ReadableStream<Uint8Array>>;
31
+ /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
32
+ * Failures before the first byte are thrown for the route's JSON error; a
33
+ * failure mid-stream cuts the response off, which the phone treats as an
34
+ * error. The phone hanging up cancels the ElevenLabs request. */
35
+ export declare function streamSpeech(data: Json, response: ServerResponse, options?: SpeechOptions): Promise<void>;
@@ -0,0 +1,98 @@
1
+ import { once } from "node:events";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { homeDir } from "../home-paths.js";
6
+ import { BridgeError } from "./protocol.js";
7
+ /** Spoken replies for the phone's talk mode. The phone sends a sentence; the
8
+ * Hook voices it with ElevenLabs and streams the audio back. The API key is
9
+ * read on this computer, used only in the request to ElevenLabs, and never
10
+ * appears in a response, including errors. */
11
+ /** Raw signed 16-bit little-endian mono PCM, so the phone can queue it
12
+ * straight into its audio engine without decoding. */
13
+ export const SPEECH_AUDIO = "pcm_s16le;rate=24000;channels=1";
14
+ const OUTPUT_FORMAT = "pcm_24000";
15
+ /** ElevenLabs' lowest-latency model. */
16
+ export const SPEECH_MODEL = "eleven_flash_v2_5";
17
+ /** River: relaxed, neutral and informative. PHREN_SPEECH_VOICE overrides it. */
18
+ export const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
19
+ const MAX_TEXT = 2_000;
20
+ export const speechRequest = z.object({ text: z.string().trim().min(1).max(MAX_TEXT) });
21
+ export function speechKeyFile(env = process.env) {
22
+ return path.join(homeDir(env), ".config", "mina-trailer.json");
23
+ }
24
+ export async function readSpeechKey(file = speechKeyFile()) {
25
+ try {
26
+ const key = JSON.parse(await readFile(file, "utf8")).elevenlabs_api_key;
27
+ return typeof key === "string" && key.trim() ? key.trim() : undefined;
28
+ }
29
+ catch {
30
+ return undefined;
31
+ }
32
+ }
33
+ /** A fixed message per ElevenLabs failure: its own response text is never
34
+ * passed on. */
35
+ export async function speechError(upstream) {
36
+ let detail = "";
37
+ try {
38
+ detail = String((await upstream.json()).detail?.status ?? "");
39
+ }
40
+ catch { /* not JSON */ }
41
+ if (detail === "quota_exceeded")
42
+ return new BridgeError(402, "The ElevenLabs quota on this computer's account is used up.", { code: "speech-quota" });
43
+ switch (upstream.status) {
44
+ case 401:
45
+ case 403: return new BridgeError(502, "ElevenLabs refused this computer's key.", { code: "speech-rejected" });
46
+ case 404: return new BridgeError(502, "ElevenLabs doesn't know the configured voice.", { code: "speech-voice" });
47
+ case 400:
48
+ case 422: return new BridgeError(400, "ElevenLabs couldn't voice this text.", { code: "speech-invalid" });
49
+ case 429: return new BridgeError(429, "ElevenLabs is busy. Try again shortly.", { code: "speech-busy" });
50
+ default: return new BridgeError(502, `ElevenLabs failed (HTTP ${upstream.status}).`, { code: "speech-failed" });
51
+ }
52
+ }
53
+ /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
54
+ export async function synthesizeSpeech(text, signal, options = {}) {
55
+ const key = await (options.key ?? (() => readSpeechKey()))();
56
+ if (!key)
57
+ throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
58
+ const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
59
+ const url = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
60
+ let upstream;
61
+ try {
62
+ upstream = await (options.fetch ?? fetch)(url, {
63
+ method: "POST", signal,
64
+ headers: { "xi-api-key": key, "Content-Type": "application/json" },
65
+ body: JSON.stringify({ text, model_id: SPEECH_MODEL, voice_settings: { stability: 0.6, similarity_boost: 0.75 } }),
66
+ });
67
+ }
68
+ catch {
69
+ throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
70
+ }
71
+ if (!upstream.ok || !upstream.body)
72
+ throw await speechError(upstream);
73
+ return upstream.body;
74
+ }
75
+ /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
76
+ * Failures before the first byte are thrown for the route's JSON error; a
77
+ * failure mid-stream cuts the response off, which the phone treats as an
78
+ * error. The phone hanging up cancels the ElevenLabs request. */
79
+ export async function streamSpeech(data, response, options = {}) {
80
+ const { text } = speechRequest.parse(data);
81
+ const abort = new AbortController();
82
+ response.once("close", () => { if (!response.writableEnded)
83
+ abort.abort(); });
84
+ const audio = await synthesizeSpeech(text, abort.signal, options);
85
+ response.statusCode = 200;
86
+ response.setHeader("Content-Type", "application/octet-stream");
87
+ response.setHeader("X-Phren-Audio", SPEECH_AUDIO);
88
+ try {
89
+ for await (const chunk of audio) {
90
+ if (!response.write(chunk))
91
+ await once(response, "drain", { signal: abort.signal });
92
+ }
93
+ response.end();
94
+ }
95
+ catch {
96
+ response.destroy();
97
+ }
98
+ }
@@ -0,0 +1,13 @@
1
+ import { type Json, type Provider } from "./protocol.js";
2
+ export declare function currentStep(source: Provider, session: string): Promise<string | undefined>;
3
+ /** The model the agent's newest answer ran on, for the lock screen's row
4
+ * label. Codex names it once per turn; Claude stamps it on every assistant
5
+ * row, and its raw id reads as the family and version the phone shows. */
6
+ export declare function currentModel(source: Provider, session: string): Promise<string | undefined>;
7
+ /** The model a visible row names, in the shape the chat header reads. */
8
+ export declare function modelOf(raw: Json, source: Provider): string | undefined;
9
+ /** One row's verdict, newest first: a tool call names the step; an
10
+ * assistant text means a reply is being written; a person's turn means the
11
+ * agent is reading it. Tool results and bookkeeping say nothing. */
12
+ export declare function stepOf(raw: Json, source: Provider): string | undefined;
13
+ export declare function describe(tool: string, args: unknown): string;
@@ -0,0 +1,222 @@
1
+ import { homedir, tmpdir } from "node:os";
2
+ import path from "node:path";
3
+ import { withTranscriptIndex } from "./transcript-index.js";
4
+ import { refreshTranscript, transcriptPath, visibleEvent } from "./transcripts.js";
5
+ import { claudeName } from "./models.js";
6
+ import { BridgeError, object, objects } from "./protocol.js";
7
+ /** What a working agent is doing right now, in the words the lock screen
8
+ * uses: the newest tool call in its transcript, or that it is writing or
9
+ * reading. Bounded to the tail; cached until the file changes. */
10
+ const cache = new Map();
11
+ const modelCache = new Map();
12
+ const TAIL_ROWS = 24, MODEL_TAIL_ROWS = 200, LIMIT = 40;
13
+ // A command often opens with `export FOO=1`-style assignments; they name the
14
+ // computer's setup, not the work, and can carry an absolute path.
15
+ const SHELL_ASSIGNMENTS = /^(?:(?:export\s+)?[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s;]*)[;\s]+)+/;
16
+ // The scratchpad a wrapper like Claude Code runs in is a temp path the account
17
+ // name hides inside; only its last component tells the person anything.
18
+ const TEMP_ROOTS = [tmpdir(), "/private/tmp", "/tmp"].map(root => root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
19
+ const TEMP_PATH = new RegExp(`(?:${TEMP_ROOTS.join("|")})(?:/[A-Za-z0-9._@+-]+)+`, "g");
20
+ const collapseTemp = (value) => value.replace(TEMP_PATH, m => "…/" + (m.split("/").filter(Boolean).pop() ?? ""));
21
+ export async function currentStep(source, session) {
22
+ let file;
23
+ try {
24
+ file = await transcriptPath(source, session);
25
+ await refreshTranscript(file, source, session);
26
+ }
27
+ catch (error) {
28
+ if (error instanceof BridgeError)
29
+ return undefined;
30
+ throw error;
31
+ }
32
+ return withTranscriptIndex(file, async (handle, index) => {
33
+ const key = `${index.revision}:${index.lines}`;
34
+ const cached = cache.get(file);
35
+ if (cached?.key === key)
36
+ return cached.step;
37
+ let step;
38
+ for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - TAIL_ROWS))) {
39
+ if (!row.bytes)
40
+ continue;
41
+ let raw;
42
+ try {
43
+ raw = visibleEvent(object(JSON.parse(row.bytes.toString())), source);
44
+ }
45
+ catch {
46
+ continue;
47
+ }
48
+ if (!raw)
49
+ continue;
50
+ const decided = stepOf(raw, source);
51
+ if (decided) {
52
+ step = decided;
53
+ break;
54
+ }
55
+ }
56
+ cache.delete(file);
57
+ cache.set(file, { key, step });
58
+ while (cache.size > 128)
59
+ cache.delete(cache.keys().next().value);
60
+ return step;
61
+ });
62
+ }
63
+ /** The model the agent's newest answer ran on, for the lock screen's row
64
+ * label. Codex names it once per turn; Claude stamps it on every assistant
65
+ * row, and its raw id reads as the family and version the phone shows. */
66
+ export async function currentModel(source, session) {
67
+ let file;
68
+ try {
69
+ file = await transcriptPath(source, session);
70
+ await refreshTranscript(file, source, session);
71
+ }
72
+ catch (error) {
73
+ if (error instanceof BridgeError)
74
+ return undefined;
75
+ throw error;
76
+ }
77
+ return withTranscriptIndex(file, async (handle, index) => {
78
+ const key = `${index.revision}:${index.lines}`;
79
+ const cached = modelCache.get(file);
80
+ if (cached?.key === key)
81
+ return cached.model;
82
+ let model;
83
+ for await (const row of index.rows(handle, index.lines, Math.max(0, index.lines - MODEL_TAIL_ROWS))) {
84
+ if (!row.bytes)
85
+ continue;
86
+ let raw;
87
+ // Model metadata need not be a visible transcript row (OpenCode strips it).
88
+ try {
89
+ raw = object(JSON.parse(row.bytes.toString()));
90
+ }
91
+ catch {
92
+ continue;
93
+ }
94
+ if (!raw)
95
+ continue;
96
+ const decided = modelOf(raw, source);
97
+ if (decided) {
98
+ model = decided;
99
+ break;
100
+ }
101
+ }
102
+ modelCache.delete(file);
103
+ modelCache.set(file, { key, model });
104
+ while (modelCache.size > 128)
105
+ modelCache.delete(modelCache.keys().next().value);
106
+ return model;
107
+ });
108
+ }
109
+ /** The model a visible row names, in the shape the chat header reads. */
110
+ export function modelOf(raw, source) {
111
+ if (source === "claude" && (raw.type !== "assistant" || raw.isSidechain === true || raw.isMeta === true))
112
+ return undefined;
113
+ if (source === "codex" && raw.type !== "turn_context")
114
+ return undefined;
115
+ if ((source === "phren" || source === "opencode") && raw.type !== "assistant/message")
116
+ return undefined;
117
+ const message = source === "phren" || source === "opencode" ? object(object(raw.data).message) : object(raw.message);
118
+ const value = source === "codex" ? object(raw.payload).model : message.model;
119
+ if (typeof value !== "string" || !value.trim())
120
+ return undefined;
121
+ const name = source === "claude" ? claudeName(value.trim()) : value.trim();
122
+ return name.slice(0, 100);
123
+ }
124
+ /** One row's verdict, newest first: a tool call names the step; an
125
+ * assistant text means a reply is being written; a person's turn means the
126
+ * agent is reading it. Tool results and bookkeeping say nothing. */
127
+ export function stepOf(raw, source) {
128
+ if (source === "codex") {
129
+ const payload = object(raw.payload);
130
+ if (raw.type !== "response_item")
131
+ return undefined;
132
+ if (["function_call", "custom_tool_call"].includes(String(payload.type)))
133
+ return describe(String(payload.name ?? ""), payload.arguments ?? payload.input);
134
+ if (payload.type === "message")
135
+ return payload.role === "assistant" ? "Writing a reply" : payload.role === "user" ? "Reading your message" : undefined;
136
+ return undefined;
137
+ }
138
+ if (source === "copilot") {
139
+ const data = object(raw.data);
140
+ if (raw.type === "tool.execution_start")
141
+ return describe(String(data.toolName ?? ""), data.arguments);
142
+ if (raw.type === "assistant.message")
143
+ return "Writing a reply";
144
+ if (raw.type === "user.message")
145
+ return "Reading your message";
146
+ return undefined;
147
+ }
148
+ const message = source === "phren" || source === "opencode" ? object(object(raw.data).message) : object(raw.message);
149
+ const role = source === "phren" || source === "opencode" ? (raw.type === "assistant/message" ? "assistant" : raw.type === "user/message" ? "user" : "tool") : String(raw.type);
150
+ const blocks = objects(message.content);
151
+ if (role === "assistant") {
152
+ const call = [...blocks].reverse().find(b => b.type === "tool_use");
153
+ if (call)
154
+ return describe(String(call.name ?? ""), call.input);
155
+ return blocks.some(b => b.type === "text") || typeof message.content === "string" ? "Writing a reply" : undefined;
156
+ }
157
+ if (role === "user") {
158
+ if (blocks.some(b => b.type === "tool_result"))
159
+ return undefined;
160
+ return blocks.some(b => b.type === "text") || typeof message.content === "string" ? "Reading your message" : undefined;
161
+ }
162
+ return undefined;
163
+ }
164
+ export function describe(tool, args) {
165
+ let input = {};
166
+ if (typeof args === "string") {
167
+ try {
168
+ input = object(JSON.parse(args));
169
+ }
170
+ catch {
171
+ input = {};
172
+ }
173
+ }
174
+ else
175
+ input = object(args);
176
+ const text = (...keys) => { for (const key of keys) {
177
+ const v = input[key];
178
+ if (typeof v === "string" && v.trim())
179
+ return v;
180
+ if (Array.isArray(v) && v.every(p => typeof p === "string"))
181
+ return v.join(" ");
182
+ } return ""; };
183
+ const firstLine = (v) => v.split(/\r?\n/).map(l => l.trim()).find(l => l) ?? "";
184
+ const base = (v) => path.basename(v.split(" · ")[0].trim()) || "file";
185
+ const name = tool.toLowerCase();
186
+ let value;
187
+ if (["bash", "shell", "exec_command", "exec", "parallel", "tools", "write_stdin", "container.exec"].includes(name)) {
188
+ // Drop the shell wrapper, a leading run of variable assignments, and a
189
+ // `cd <dir> &&`, and keep the home directory (and the account name in it)
190
+ // and any scratchpad path off the lock screen.
191
+ const command = collapseTemp(firstLine(text("command", "cmd")).replace(/^(?:\/\S*\/)?(?:bash|sh|zsh)\s+-l?c\s+/, "")
192
+ .replace(/^(['"])(.*)\1$/, "$2").replace(SHELL_ASSIGNMENTS, "").replace(/^cd\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/, "").replace(SHELL_ASSIGNMENTS, "").split(homedir()).join("~"));
193
+ value = command ? `${tool}: ${command}` : tool;
194
+ }
195
+ else if (["edit", "multiedit", "write", "notebookedit", "patch", "apply_patch", "str_replace_editor", "str_replace"].includes(name)) {
196
+ const patchTarget = /\*\*\* (?:Update|Add|Delete) File: (.+)/.exec(text("input", "patch"))?.[1];
197
+ value = `Editing ${base(text("file_path", "filePath", "path") || patchTarget || "")}`;
198
+ }
199
+ else if (["read", "ls", "list"].includes(name))
200
+ value = `Reading ${base(text("file_path", "filePath", "path"))}`;
201
+ else if (["grep", "glob", "search", "websearch", "browse"].includes(name)) {
202
+ const q = firstLine(text("pattern", "query"));
203
+ value = q ? `Searching ${q}` : tool;
204
+ }
205
+ else if (["fetch", "webfetch"].includes(name)) {
206
+ let host = "";
207
+ try {
208
+ host = new URL(text("url")).host;
209
+ }
210
+ catch { /* not a URL */ }
211
+ value = host ? `Fetching ${host}` : tool;
212
+ }
213
+ else if (["task", "agent"].includes(name)) {
214
+ const d = firstLine(text("description", "name"));
215
+ value = d ? `Delegating ${d}` : tool;
216
+ }
217
+ else {
218
+ const d = firstLine(text("command", "cmd", "query", "description"));
219
+ value = d ? `${tool}: ${d}` : tool || "Working";
220
+ }
221
+ return value.length > LIMIT ? value.slice(0, LIMIT - 1) + "…" : value;
222
+ }
@@ -0,0 +1,18 @@
1
+ import { type Json } from "./protocol.js";
2
+ export declare const tabActivityKey: (workspace: unknown, tab: unknown) => string;
3
+ /** A clock for Herdr's clockless state counters. Only successful snapshots
4
+ * prune tabs; each activity pass also prunes missing servers. Writes are ordered
5
+ * and atomic, and an unchanged poll never rewrites the file. */
6
+ export declare class TabActivityStore {
7
+ private readonly file;
8
+ private readonly now;
9
+ private entries;
10
+ private loaded;
11
+ private dirty;
12
+ private pending;
13
+ constructor(file?: string, now?: () => Date);
14
+ observe(server: string, snapshot: Json): Promise<ReadonlyMap<string, string>>;
15
+ private load;
16
+ private persist;
17
+ pruneServers(servers: string[]): Promise<void>;
18
+ }
@@ -0,0 +1,99 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { createHash } from "node:crypto";
4
+ import { atomicInPrivateDir, bridgeRoot, object, objects } from "./protocol.js";
5
+ const digest = (text) => createHash("sha256").update(text).digest("hex");
6
+ export const tabActivityKey = (workspace, tab) => JSON.stringify([workspace, tab]);
7
+ /** A clock for Herdr's clockless state counters. Only successful snapshots
8
+ * prune tabs; each activity pass also prunes missing servers. Writes are ordered
9
+ * and atomic, and an unchanged poll never rewrites the file. */
10
+ export class TabActivityStore {
11
+ file;
12
+ now;
13
+ entries = new Map();
14
+ loaded = false;
15
+ dirty = false;
16
+ pending = Promise.resolve();
17
+ constructor(file = path.join(bridgeRoot(), "tab-activity.json"), now = () => new Date()) {
18
+ this.file = file;
19
+ this.now = now;
20
+ }
21
+ observe(server, snapshot) {
22
+ const at = this.now().toISOString();
23
+ const operation = this.pending.catch(() => { }).then(async () => {
24
+ await this.load();
25
+ const prefix = JSON.stringify(server) + ":";
26
+ const seen = new Set(), times = new Map();
27
+ let changed = false;
28
+ for (const tab of objects(snapshot.tabs)) {
29
+ const tabKey = tabActivityKey(tab.workspace_id, tab.tab_id), key = prefix + tabKey;
30
+ seen.add(key);
31
+ // Include every pane: a lower counter changing must count even when
32
+ // another pane still has the tab's maximum state_change_seq.
33
+ const panes = objects(snapshot.panes).filter(p => p.workspace_id === tab.workspace_id && p.tab_id === tab.tab_id)
34
+ .map(p => [p.pane_id, p.agent, p.agent_status, p.state_change_seq, p.title || p.terminal_title_stripped])
35
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])));
36
+ const signature = digest(JSON.stringify([tab.agent_status, tab.state_change_seq, tab.label, tab.title, panes]));
37
+ let stamp = this.entries.get(key);
38
+ if (stamp?.signature !== signature) {
39
+ stamp = { signature, lastChangedAt: at };
40
+ this.entries.set(key, stamp);
41
+ changed = true;
42
+ }
43
+ times.set(tabKey, stamp.lastChangedAt);
44
+ }
45
+ for (const key of this.entries.keys()) {
46
+ if (key.startsWith(prefix) && !seen.has(key)) {
47
+ this.entries.delete(key);
48
+ changed = true;
49
+ }
50
+ }
51
+ this.dirty ||= changed;
52
+ await this.persist();
53
+ return times;
54
+ });
55
+ this.pending = operation;
56
+ return operation;
57
+ }
58
+ async load() {
59
+ if (!this.loaded) {
60
+ const saved = await readFile(this.file, "utf8").then(JSON.parse).catch(() => ({}));
61
+ for (const [key, value] of Object.entries(object(object(saved).entries))) {
62
+ const stamp = object(value);
63
+ if (typeof stamp.signature === "string" && typeof stamp.lastChangedAt === "string"
64
+ && Number.isFinite(Date.parse(stamp.lastChangedAt))) {
65
+ const hashed = /^[a-f0-9]{64}$/.test(stamp.signature);
66
+ this.entries.set(key, { signature: hashed ? stamp.signature : digest(stamp.signature), lastChangedAt: stamp.lastChangedAt });
67
+ this.dirty ||= !hashed;
68
+ }
69
+ }
70
+ this.loaded = true;
71
+ }
72
+ }
73
+ async persist() {
74
+ if (this.dirty) {
75
+ try {
76
+ await atomicInPrivateDir(this.file, JSON.stringify({ version: 1, entries: Object.fromEntries(this.entries) }));
77
+ this.dirty = false;
78
+ }
79
+ catch {
80
+ // A full/unwritable disk must not hide live sessions. Keep the clock
81
+ // in memory and retry saving on the next successful snapshot.
82
+ }
83
+ }
84
+ }
85
+ pruneServers(servers) {
86
+ const operation = this.pending.catch(() => { }).then(async () => {
87
+ await this.load();
88
+ const prefixes = servers.map(server => JSON.stringify(server) + ":");
89
+ for (const key of this.entries.keys())
90
+ if (!prefixes.some(prefix => key.startsWith(prefix))) {
91
+ this.entries.delete(key);
92
+ this.dirty = true;
93
+ }
94
+ await this.persist();
95
+ });
96
+ this.pending = operation;
97
+ return operation;
98
+ }
99
+ }