@phren/cli 0.2.16 → 0.3.1

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 (102) hide show
  1. package/dist/bridge/agent-hooks.d.ts +17 -6
  2. package/dist/bridge/agent-hooks.js +59 -24
  3. package/dist/bridge/claude-question-dialog.d.ts +65 -0
  4. package/dist/bridge/claude-question-dialog.js +210 -0
  5. package/dist/bridge/code-note.d.ts +2 -1
  6. package/dist/bridge/code-note.js +13 -4
  7. package/dist/bridge/code-routes.d.ts +32 -14
  8. package/dist/bridge/code-routes.js +131 -8
  9. package/dist/bridge/command.js +92 -2
  10. package/dist/bridge/computers.d.ts +5 -0
  11. package/dist/bridge/computers.js +10 -4
  12. package/dist/bridge/conductor-group.d.ts +23 -0
  13. package/dist/bridge/conductor-group.js +25 -0
  14. package/dist/bridge/dispatch-returns.d.ts +2 -0
  15. package/dist/bridge/dispatch-returns.js +12 -8
  16. package/dist/bridge/dispatch.d.ts +4 -1
  17. package/dist/bridge/dispatch.js +30 -5
  18. package/dist/bridge/hand-off.js +5 -1
  19. package/dist/bridge/herdr.d.ts +7 -0
  20. package/dist/bridge/herdr.js +53 -2
  21. package/dist/bridge/install.d.ts +0 -4
  22. package/dist/bridge/install.js +3 -3
  23. package/dist/bridge/link.d.ts +48 -0
  24. package/dist/bridge/link.js +136 -0
  25. package/dist/bridge/memory-store.d.ts +23 -0
  26. package/dist/bridge/memory-store.js +152 -0
  27. package/dist/bridge/pair.d.ts +46 -0
  28. package/dist/bridge/pair.js +240 -0
  29. package/dist/bridge/peers.d.ts +9 -0
  30. package/dist/bridge/peers.js +25 -2
  31. package/dist/bridge/protocol.js +20 -1
  32. package/dist/bridge/schedule-watch.d.ts +2 -0
  33. package/dist/bridge/schedule-watch.js +16 -3
  34. package/dist/bridge/server-launch.d.ts +9 -0
  35. package/dist/bridge/server-launch.js +34 -11
  36. package/dist/bridge/server-pane-routes.d.ts +7 -0
  37. package/dist/bridge/server-pane-routes.js +128 -18
  38. package/dist/bridge/server-routes.d.ts +3 -0
  39. package/dist/bridge/server-routes.js +55 -29
  40. package/dist/bridge/server-stream.js +4 -1
  41. package/dist/bridge/speech-key.d.ts +33 -0
  42. package/dist/bridge/speech-key.js +106 -0
  43. package/dist/bridge/speech-transcribe.js +1 -1
  44. package/dist/bridge/speech.d.ts +1 -3
  45. package/dist/bridge/speech.js +2 -16
  46. package/dist/bridge/transcript-preview.d.ts +2 -0
  47. package/dist/bridge/transcript-preview.js +15 -0
  48. package/dist/bridge-hook.mjs +9940 -3601
  49. package/dist/cli/config-policy.js +25 -0
  50. package/dist/cli/extract.d.ts +0 -8
  51. package/dist/cli/extract.js +1 -1
  52. package/dist/cli-handlers.js +6 -0
  53. package/dist/cli-registry.js +21 -9
  54. package/dist/content/learning.js +1 -1
  55. package/dist/content/validate.d.ts +14 -3
  56. package/dist/content/validate.js +174 -114
  57. package/dist/data/access.d.ts +9 -0
  58. package/dist/data/access.js +18 -0
  59. package/dist/data/tasks.d.ts +26 -0
  60. package/dist/data/tasks.js +72 -1
  61. package/dist/entrypoint.js +7 -0
  62. package/dist/generated/memory-ui-graph.browser.js +520 -410
  63. package/dist/governance/policy.js +4 -3
  64. package/dist/governance/rbac.d.ts +1 -1
  65. package/dist/governance/rbac.js +1 -0
  66. package/dist/hooks.d.ts +0 -15
  67. package/dist/hooks.js +1 -1
  68. package/dist/init/init-uninstall.js +13 -3
  69. package/dist/init/init-walkthrough.d.ts +10 -0
  70. package/dist/init/init-walkthrough.js +24 -1
  71. package/dist/init/init.d.ts +5 -0
  72. package/dist/init/init.js +54 -32
  73. package/dist/init/setup.js +19 -5
  74. package/dist/init/store-gitignore.d.ts +0 -5
  75. package/dist/init/store-gitignore.js +0 -8
  76. package/dist/link/context-imports.d.ts +15 -0
  77. package/dist/link/context-imports.js +101 -0
  78. package/dist/link/doctor.js +38 -4
  79. package/dist/mcp/profile.d.ts +0 -4
  80. package/dist/mcp/profile.js +2 -14
  81. package/dist/memory-ui-graph.runtime.js +520 -410
  82. package/dist/modules/code-package.js +10 -2
  83. package/dist/modules/config.d.ts +7 -0
  84. package/dist/modules/config.js +17 -0
  85. package/dist/modules/registry.js +6 -5
  86. package/dist/profile-store.js +39 -3
  87. package/dist/project-topics.d.ts +1 -0
  88. package/dist/project-topics.js +9 -6
  89. package/dist/shared/retrieval.d.ts +0 -2
  90. package/dist/shared/retrieval.js +1 -1
  91. package/dist/sync/task-claim.d.ts +22 -0
  92. package/dist/sync/task-claim.js +45 -0
  93. package/dist/tools/code.js +29 -21
  94. package/dist/tools/config.js +3 -0
  95. package/dist/tools/dispatch.js +3 -3
  96. package/dist/tools/finding.d.ts +11 -0
  97. package/dist/tools/finding.js +154 -99
  98. package/dist/tools/tasks.js +40 -1
  99. package/dist/ui/server.js +18 -1
  100. package/dist/update.js +21 -10
  101. package/package.json +8 -7
  102. package/starter/global/skills/conductor/SKILL.md +42 -10
@@ -1,3 +1,5 @@
1
+ import path from "node:path";
2
+ import { setTimeout as sleep } from "node:timers/promises";
1
3
  import { z } from "zod";
2
4
  import { gitBranches, gitDiscard, gitLog, gitPulls, gitStage, gitStatus, gitTree, gitUnstage } from "./git.js";
3
5
  import { fanoutWorktrees } from "./fanouts.js";
@@ -63,7 +65,7 @@ export function herdrWorktreeWorkers(s) {
63
65
  const workers = [];
64
66
  for (const pane of objects(s.panes)) {
65
67
  const cwd = pane.foreground_cwd || pane.cwd;
66
- if (typeof pane.agent !== "string" || typeof cwd !== "string" || !cwd.startsWith("/"))
68
+ if (typeof pane.agent !== "string" || typeof cwd !== "string" || !path.isAbsolute(cwd))
67
69
  continue;
68
70
  const name = paneAgentName(s, pane);
69
71
  workers.push({ cwd, label: name || pane.agent, provider: pane.agent,
@@ -76,6 +78,31 @@ export function herdrWorktreeWorkers(s) {
76
78
  * queue, after which the option key (or typed text) is the answer. */
77
79
  const ANSWER_KEYS = ["Escape", "Enter", "Up", "Down", "Tab", "AltUp", "y", "n", "p", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
78
80
  const HERDR_KEYS = { Escape: "esc", Enter: "enter", Up: "up", Down: "down", Tab: "tab", AltUp: "alt+Up" };
81
+ // A question or label may wrap onto several lines; the pane shows them joined.
82
+ const questionText = z.string().trim().min(1).max(4000).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t));
83
+ const claudeQuestionBody = z.object({
84
+ questions: z.array(z.object({ question: questionText, multiSelect: z.boolean().optional(), options: z.array(questionText).min(1).max(8) })).min(1).max(8),
85
+ answers: z.array(z.object({ optionIndexes: z.array(z.number().int().nonnegative()).max(8),
86
+ text: z.string().max(1000).refine(t => !/[\x00-\x1f\x7f]/.test(t)).optional() })).min(1).max(8),
87
+ });
88
+ /** The phone's answer to Claude's AskUserQuestion: one answer per question,
89
+ * a single option or a typed answer for a single-select question, any
90
+ * options plus an optional typed answer for a multi-select one. */
91
+ function claudeQuestionAnswer(data) {
92
+ const body = claudeQuestionBody.parse(data);
93
+ if (body.answers.length !== body.questions.length)
94
+ throw new BridgeError(400, "Answer every question.");
95
+ const answers = body.answers.map((answer, index) => {
96
+ const question = body.questions[index], options = [...new Set(answer.optionIndexes)], text = answer.text?.trim() ?? "";
97
+ if (options.some(option => option >= question.options.length))
98
+ throw new BridgeError(400, "Choose an available answer.");
99
+ if (question.multiSelect ? !options.length && !text : options.length + (text ? 1 : 0) !== 1) {
100
+ throw new BridgeError(400, question.multiSelect ? "Choose at least one answer." : "Choose one answer for each question.");
101
+ }
102
+ return { options, ...(text ? { text } : {}) };
103
+ });
104
+ return { questions: body.questions.map(q => ({ question: q.question, multiSelect: q.multiSelect, options: q.options.map(label => ({ label })) })), answers };
105
+ }
79
106
  /** A secret typed into a terminal prompt: printable, bounded, never logged. */
80
107
  const secretText = z.string().min(1).max(256).refine(t => !/[\x00-\x1f\x7f]/.test(t));
81
108
  /** An idle agent that has not taken typed text within the first wait
@@ -99,6 +126,72 @@ async function resubmitIfIdle(agentHooks, target, text) {
99
126
  return outcome;
100
127
  return await status() === "working" ? "pending" : "unsubmitted";
101
128
  }
129
+ /** A busy Claude Code queues typed text on Enter, but after a long paste
130
+ * ("paste again to expand") it can swallow that Enter and leave the text in
131
+ * its input line, where it stays after the turn ends. Follow the pane: once
132
+ * it has stayed finished for two looks while the prompt is still unsubmitted,
133
+ * press Enter once. A closed or replaced pane, a delivery the conversation
134
+ * took, or ten minutes end the watch; a pane asking for input is never answered. */
135
+ export function followQueuedDelivery(agentHooks, target, terminal, text, intervalMs = 2_000) {
136
+ const started = Date.now();
137
+ let finishedLooks = 0;
138
+ const look = async () => {
139
+ if (!agentHooks.deliveryPending(target, text) || Date.now() - started > 600_000)
140
+ return;
141
+ let pane;
142
+ try {
143
+ pane = findPane(await snapshot(target.server), target);
144
+ }
145
+ catch {
146
+ pane = undefined;
147
+ }
148
+ if (!pane) {
149
+ schedule();
150
+ return;
151
+ }
152
+ if (pane.terminal_id !== terminal)
153
+ return;
154
+ const status = String(pane.agent_status);
155
+ finishedLooks = status === "idle" || status === "done" ? finishedLooks + 1 : 0;
156
+ if (finishedLooks >= 2) {
157
+ await resubmitIfIdle(agentHooks, target, text).catch(() => undefined);
158
+ return;
159
+ }
160
+ schedule();
161
+ };
162
+ const schedule = () => { const timer = setTimeout(() => void look(), intervalMs); timer.unref?.(); };
163
+ schedule();
164
+ }
165
+ /** A fresh Claude Code that took its first prompt starts working. One that
166
+ * stays idle kept the brief in its input line (a long paste can swallow the
167
+ * Enter): press Enter once, only while it is idle, so a dialog is never
168
+ * answered. False when it still has not started. */
169
+ async function submitStartingPrompt(server, target, terminal, looks = 4, intervalMs = 500) {
170
+ const status = async () => {
171
+ try {
172
+ const pane = findPane(await snapshot(server), target);
173
+ return pane && pane.terminal_id === terminal ? String(pane.agent_status) : "gone";
174
+ }
175
+ catch {
176
+ return "unknown";
177
+ }
178
+ };
179
+ const settled = async () => {
180
+ for (let look = 0; look < looks; look++) {
181
+ await sleep(intervalMs);
182
+ const current = await status();
183
+ if (current !== "idle" && current !== "done")
184
+ return current;
185
+ }
186
+ return "idle";
187
+ };
188
+ const first = await settled();
189
+ if (first !== "idle")
190
+ return first !== "gone";
191
+ await rpc(server, "agent.send_keys", { target: target.pane, keys: ["enter"] });
192
+ const second = await settled();
193
+ return second !== "idle" && second !== "gone";
194
+ }
102
195
  /** One key per character; Herdr's send_keys takes single characters and named
103
196
  * keys only, and a tty password read is corrupted by a bracketed paste. */
104
197
  function secretKeys(text) {
@@ -160,15 +253,23 @@ export async function paneRoute(ctx, url, data, response) {
160
253
  const text = z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)).parse(data.text);
161
254
  refuseWorkingSlash(pane, text);
162
255
  await rpc(target.server, "agent.prompt", { target: target.pane, text });
163
- // A first prompt may create its transcript immediately. Recheck the
164
- // terminal/process binding, not the absence of a session. Never retry.
165
- let confirmed = false;
166
- try {
167
- const current = findPane(await snapshot(target.server), target);
168
- confirmed = !!current && current.terminal_id === pane.terminal_id && (await paneChatState(target.server, current)).startingToken === target.startingToken;
256
+ // A dispatched worker's brief is often long enough for Claude Code to
257
+ // swallow the Enter; a slash command opens a menu an Enter would answer.
258
+ const submitted = target.source !== "claude" || text.trim().startsWith("/")
259
+ || await submitStartingPrompt(target.server, target, pane.terminal_id);
260
+ if (!submitted)
261
+ result = { ok: true, deliveryUncertain: true, unsubmitted: true };
262
+ else {
263
+ // A first prompt may create its transcript immediately. Recheck the
264
+ // terminal/process binding, not the absence of a session. Never retry.
265
+ let confirmed = false;
266
+ try {
267
+ const current = findPane(await snapshot(target.server), target);
268
+ confirmed = !!current && current.terminal_id === pane.terminal_id && (await paneChatState(target.server, current)).startingToken === target.startingToken;
269
+ }
270
+ catch { /* Already delivered; an uncertain reply must not resend. */ }
271
+ result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : {}) };
169
272
  }
170
- catch { /* Already delivered; an uncertain reply must not resend. */ }
171
- result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : {}) };
172
273
  }
173
274
  else {
174
275
  const target = targetSchema.parse(data.target);
@@ -218,8 +319,11 @@ export async function paneRoute(ctx, url, data, response) {
218
319
  let outcome = await expected;
219
320
  // Only Claude confirms plain prompts through its hook, and a slash
220
321
  // command opens a menu that a second Enter would answer.
221
- if (outcome === "pending" && !busy && target.source === "claude" && !text.trim().startsWith("/")) {
222
- outcome = await resubmitIfIdle(agentHooks, target, text);
322
+ if (outcome === "pending" && target.source === "claude" && !text.trim().startsWith("/")) {
323
+ if (!busy)
324
+ outcome = await resubmitIfIdle(agentHooks, target, text);
325
+ else
326
+ followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
223
327
  }
224
328
  if (outcome === "blocked")
225
329
  throw new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
@@ -265,12 +369,10 @@ export async function paneRoute(ctx, url, data, response) {
265
369
  if (!holding && (keys.every(key => key === "Escape") ? !["working", "blocked", "waiting", "unknown"].includes(status)
266
370
  : !["blocked", "waiting", "unknown"].includes(status)))
267
371
  throw new BridgeError(409, keys.every(key => key === "Escape") ? "This agent is no longer working." : "This agent is not waiting for an answer.");
268
- // A released AskUserQuestion is answered one question at a time:
269
- // the Hook sends the chosen digit, then Tab to advance or Enter
270
- // after the last, and clears the prompt when the set is done.
271
- const question = agentHooks.questionAnswerKeys(target, keys);
272
- if (question) {
273
- await rpc(target.server, "agent.send_keys", { target: target.pane, keys: question.map(key => HERDR_KEYS[key] ?? key) });
372
+ // An older phone answers a released AskUserQuestion one question at
373
+ // a time with its digits; the Hook walks that question in the pane
374
+ // and submits the set after the last.
375
+ if (await agentHooks.answerReleasedQuestion(target, keys)) {
274
376
  result = { ok: true };
275
377
  }
276
378
  else {
@@ -390,7 +492,15 @@ export async function paneRoute(ctx, url, data, response) {
390
492
  result = { ok: true };
391
493
  }
392
494
  else if (url.pathname === "/v1/questions/answer") {
393
- await codexQuestions.answer(target, data);
495
+ if (target.source === "claude") {
496
+ // Claude's AskUserQuestion, answered in its terminal dialog: the
497
+ // phone names the questions it shows, and the Hook answers only a
498
+ // pane that is drawing exactly those.
499
+ const { questions, answers } = claudeQuestionAnswer(data);
500
+ await agentHooks.answerClaudeQuestions(target, questions, answers);
501
+ }
502
+ else
503
+ await codexQuestions.answer(target, data);
394
504
  result = { ok: true };
395
505
  }
396
506
  else
@@ -63,6 +63,8 @@ export interface RouteContext {
63
63
  canary: (trigger: "manual" | "daily") => Promise<unknown>;
64
64
  streams: TranscriptStreams;
65
65
  }
66
+ /** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
67
+ export declare const OVERVIEW_ENRICH_BUDGET_MS = 5000;
66
68
  export declare const capabilities: {
67
69
  transcript: boolean;
68
70
  progress: boolean;
@@ -91,6 +93,7 @@ export declare const capabilities: {
91
93
  overviewStream: boolean;
92
94
  speech: boolean;
93
95
  transcribe: boolean;
96
+ memoryStore: boolean;
94
97
  };
95
98
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
96
99
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -13,6 +13,7 @@ import { optionalHookPeers, peerRequest } from "./peers.js";
13
13
  import { candidateRepos, enrollProject } from "./enroll.js";
14
14
  import { browseFiles } from "./files.js";
15
15
  import { MAX_FILE_RANGE, rangeInteger, readFileRange } from "./file-range.js";
16
+ import { storeRoute } from "./memory-store.js";
16
17
  import { paneChatState, panes, servers, snapshot, validateTarget, workspaceSnapshot } from "./herdr.js";
17
18
  import { locateProject } from "./locate.js";
18
19
  import { gitRoot, launchDirectory, repositoryBranch, webServers } from "./projects.js";
@@ -25,10 +26,12 @@ import { healthDetails, listsCaller } from "./health.js";
25
26
  import { defaultPhrenPath } from "../shared.js";
26
27
  import { loadCodePackage, loadedFrom } from "../modules/code-package.js";
27
28
  import { gitRepository, paneRoute, uploadBody } from "./server-pane-routes.js";
28
- import { launchSession, workspaceAction } from "./server-launch.js";
29
+ import { launchSession, localConductor, workspaceAction } from "./server-launch.js";
29
30
  import { hookMetrics } from "./metrics.js";
30
31
  import { streamSpeech } from "./speech.js";
31
32
  const CHILD_ACTIVITY_CACHE_MS = 5_000;
33
+ /** How long the overview waits for per-tab git and transcript reads; the phone gives up at 20 s. */
34
+ export const OVERVIEW_ENRICH_BUDGET_MS = 5_000;
32
35
  const childActivityCache = new Map();
33
36
  async function childActivity(source, session) {
34
37
  const key = `${source}\0${session}`, now = Date.now(), cached = childActivityCache.get(key);
@@ -48,7 +51,7 @@ async function childActivity(source, session) {
48
51
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
49
52
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
50
53
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
51
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, transcribe: true };
54
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, transcribe: true, memoryStore: true };
52
55
  export function capabilitiesForModules(snapshot) {
53
56
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
54
57
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -109,48 +112,61 @@ export function workspacesReader(ctx) {
109
112
  agentsByTab.set(key, agents);
110
113
  }
111
114
  const tabs = objects(workspaces.groups).flatMap(group => objects(group.children).map(tab => ({ group, tab })));
115
+ // What a chat needs to open (the exact conversation) comes straight from the
116
+ // chat states; everything below it is decoration.
117
+ for (const { group, tab } of tabs) {
118
+ const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
119
+ if (agents.length !== 1)
120
+ continue;
121
+ const chat = chatStates.get(agents[0]);
122
+ if (chat?.starting === true)
123
+ tab.starting = true;
124
+ if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
125
+ tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id, source: agents[0].agent, session: chat.sessionId };
126
+ }
127
+ }
128
+ // Branch, model, children and current step read git and transcripts. On a
129
+ // starved machine (load 230 on 10 cores, 2026-09-24) that took longer than
130
+ // the phone waits, so the computer read as offline. The overview answers
131
+ // within its budget with whatever decoration is ready; a later read fills in.
132
+ let expired = false;
112
133
  let nextTab = 0;
113
- // Bound transcript and git work across tabs. Each worker owns one
114
- // response row; snapshot order and target validation are unchanged.
115
- await Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
116
- while (nextTab < tabs.length) {
134
+ const enrich = Promise.all(Array.from({ length: Math.min(4, tabs.length) }, async () => {
135
+ while (!expired && nextTab < tabs.length) {
117
136
  const { group, tab } = tabs[nextTab++];
118
137
  const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
119
- if (agents.length === 1) {
120
- const chat = chatStates.get(agents[0]);
121
- if (chat?.starting === true)
122
- tab.starting = true;
123
- if (typeof chat?.sessionId === "string" && provider.safeParse(agents[0].agent).success) {
124
- tab.target = { server, workspace: group.id, tab: tab.id, pane: agents[0].pane_id,
125
- source: agents[0].agent, session: chat.sessionId };
126
- }
127
- }
138
+ const found = {};
128
139
  if (modules.has("git") && typeof tab.cwd === "string" && tab.agent)
129
- tab.branch = await repositoryBranch(tab.cwd);
130
- // The model the pane's agent is running, and what it is doing
131
- // right now, for cards and the lock screen.
140
+ found.branch = await repositoryBranch(tab.cwd);
132
141
  if (agents.length === 1 && provider.safeParse(agents[0].agent).success) {
133
142
  const session = chatStates.get(agents[0])?.sessionId;
134
- tab.runningChildren = 0;
135
- tab.childProviders = [];
143
+ found.runningChildren = 0;
144
+ found.childProviders = [];
136
145
  if (typeof session === "string") {
137
146
  const source = agents[0].agent;
138
147
  const [model, children] = await Promise.all([
139
148
  currentModel(source, session).catch(() => undefined), childActivity(source, session),
140
149
  ]);
141
150
  if (model)
142
- tab.model = model;
143
- tab.runningChildren = children.runningChildren;
144
- tab.childProviders = children.childProviders;
151
+ found.model = model;
152
+ found.runningChildren = children.runningChildren;
153
+ found.childProviders = children.childProviders;
145
154
  if (agents[0].agent_status === "working") {
146
155
  const step = await currentStep(source, session).catch(() => undefined);
147
156
  if (step)
148
- tab.currentStep = step;
157
+ found.currentStep = step;
149
158
  }
150
159
  }
151
160
  }
161
+ // A row finished after the answer left belongs to the next read.
162
+ if (!expired)
163
+ Object.assign(tab, Object.fromEntries(Object.entries(found).filter(([, value]) => value !== undefined)));
152
164
  }
153
165
  }));
166
+ let timer;
167
+ await Promise.race([enrich, new Promise(resolve => { timer = setTimeout(resolve, OVERVIEW_ENRICH_BUDGET_MS); })]);
168
+ expired = true;
169
+ clearTimeout(timer);
154
170
  return { ...workspaces, phren: info };
155
171
  };
156
172
  }
@@ -167,7 +183,10 @@ export function createRouteHandler(ctx) {
167
183
  throw new BridgeError(400, "Invalid request origin.");
168
184
  requireRoute(modules, request.method ?? "", url.pathname);
169
185
  let result;
170
- if (request.method === "GET") {
186
+ if (url.pathname.startsWith("/v1/store/")) {
187
+ result = await storeRoute(modules.store, request.method ?? "", url, request.method === "POST" ? await body(request) : undefined);
188
+ }
189
+ else if (request.method === "GET") {
171
190
  switch (url.pathname) {
172
191
  case "/v1/health":
173
192
  result = { ...info, codePackage: await codePackageStatus(scheduleStore, modules.has("code")) };
@@ -192,6 +211,10 @@ export function createRouteHandler(ctx) {
192
211
  case "/v1/conductor/grants":
193
212
  result = { grants: await listGrants() };
194
213
  break;
214
+ // Asked by linked peers before they start a conductor: one per connected group.
215
+ case "/v1/conductor":
216
+ result = { computer: info.computer, conductor: await localConductor() ?? null };
217
+ break;
195
218
  case "/v1/dispatch/capacity": {
196
219
  const live = await servers();
197
220
  const snapshots = await Promise.all(live.map(server => snapshot(String(server.session))));
@@ -365,8 +388,11 @@ export function createRouteHandler(ctx) {
365
388
  case "/v1/code/tree":
366
389
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).tree(url.searchParams.get("project"), url.searchParams.get("directory"));
367
390
  break;
368
- case "/v1/code/recent":
369
- result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).recent(url.searchParams.get("project"), url.searchParams.get("directory"));
391
+ case "/v1/code/changed":
392
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).whatChanged(url.searchParams.get("project"));
393
+ break;
394
+ case "/v1/code/change-counts":
395
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).changeCounts(url.searchParams.get("project"), url.searchParams.get("paths"));
370
396
  break;
371
397
  case "/v1/code/usage-page":
372
398
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usagePage(url.searchParams.get("project"), {
@@ -390,10 +416,10 @@ export function createRouteHandler(ctx) {
390
416
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).outline(url.searchParams.get("project"), url.searchParams.get("path"));
391
417
  break;
392
418
  case "/v1/code/definition":
393
- result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).definition(url.searchParams.get("project"), url.searchParams.get("symbol"));
419
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).definition(url.searchParams.get("project"), (url.searchParams.get("name") ?? url.searchParams.get("symbol")));
394
420
  break;
395
421
  case "/v1/code/references":
396
- result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).references(url.searchParams.get("project"), url.searchParams.get("symbol"), url.searchParams.get("limit"));
422
+ result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).references(url.searchParams.get("project"), (url.searchParams.get("name") ?? url.searchParams.get("symbol")), url.searchParams.get("limit"));
397
423
  break;
398
424
  case "/v1/code/usage":
399
425
  result = await (new CodeRoutes(await resolveCodeStore(scheduleStore, url.searchParams.get("store")))).usage(url.searchParams.get("project"), url.searchParams.get("top"));
@@ -175,7 +175,10 @@ export function transcriptStreams(ctx) {
175
175
  compacting: agentHooks.compacting(target),
176
176
  ...(historyHealth.stalled ? { historyStalled: true, historyStalledSince: historyHealth.since } : {}),
177
177
  modules: info.modules, store: info.store, profile: info.profile, generation: info.generation,
178
- capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available }, branch } });
178
+ capabilities: { ...activeCapabilities, asyncQuestions: target.source === "codex" && codexQuestions.available,
179
+ // Claude's AskUserQuestion is answered in its terminal dialog
180
+ // through /v1/questions/answer, whether or not a hold caught it.
181
+ ...(target.source === "claude" ? { questions: true } : {}) }, branch } });
179
182
  }
180
183
  if (sideAnswers && sideQuestions) {
181
184
  for (const { revision, ...side } of sideQuestions.list(target)) {
@@ -0,0 +1,33 @@
1
+ /** The ElevenLabs key for spoken replies and Scribe dictation. It is machine
2
+ * config, like apns.json: it lives in the Hook's own directory, mode 600, and
3
+ * never in the synced store. ELEVENLABS_API_KEY, ElevenLabs' own convention
4
+ * that its SDKs and MCP server read, wins when set. The Hook runs as a service
5
+ * that doesn't see shell env, so the file is the durable source. */
6
+ export declare const SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
7
+ export type SpeechKeySource = "environment" | "file";
8
+ export declare function speechKeyFile(): string;
9
+ /** Where the key lived before phren kept its own: the mina trailer config. It
10
+ * is read once to migrate and never written or deleted. */
11
+ export declare function legacySpeechKeyFile(env?: NodeJS.ProcessEnv): string;
12
+ export declare function writeSpeechKey(key: string, file?: string): Promise<void>;
13
+ export interface SpeechKeyPaths {
14
+ env?: NodeJS.ProcessEnv;
15
+ file?: string;
16
+ legacy?: string;
17
+ }
18
+ /** ELEVENLABS_API_KEY, else the stored key. When nothing is stored yet and the
19
+ * mina trailer config has a key, it is copied here once and read from here
20
+ * after. */
21
+ export declare function resolveSpeechKey(paths?: SpeechKeyPaths): Promise<{
22
+ key: string;
23
+ source: SpeechKeySource;
24
+ } | undefined>;
25
+ export declare function readSpeechKey(): Promise<string | undefined>;
26
+ export interface SpeechKeyStatus {
27
+ configured: boolean;
28
+ detail: string;
29
+ problem?: boolean;
30
+ }
31
+ /** Whether this computer has a key, for doctor. Never the key itself, and it
32
+ * doesn't migrate: a read-only check. */
33
+ export declare function speechKeyStatus(paths?: SpeechKeyPaths): Promise<SpeechKeyStatus>;
@@ -0,0 +1,106 @@
1
+ import { mkdir, readFile, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { homeDir } from "../home-paths.js";
4
+ import { atomic, bridgeRoot } from "./protocol.js";
5
+ /** The ElevenLabs key for spoken replies and Scribe dictation. It is machine
6
+ * config, like apns.json: it lives in the Hook's own directory, mode 600, and
7
+ * never in the synced store. ELEVENLABS_API_KEY, ElevenLabs' own convention
8
+ * that its SDKs and MCP server read, wins when set. The Hook runs as a service
9
+ * that doesn't see shell env, so the file is the durable source. */
10
+ export const SPEECH_KEY_ENV = "ELEVENLABS_API_KEY";
11
+ export function speechKeyFile() {
12
+ return path.join(bridgeRoot(), "elevenlabs.json");
13
+ }
14
+ /** Where the key lived before phren kept its own: the mina trailer config. It
15
+ * is read once to migrate and never written or deleted. */
16
+ export function legacySpeechKeyFile(env = process.env) {
17
+ return path.join(homeDir(env), ".config", "mina-trailer.json");
18
+ }
19
+ function clean(value) {
20
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
21
+ }
22
+ /** The stored key. A file other users can read is refused, as apns.json is. */
23
+ async function readStored(file) {
24
+ let info;
25
+ try {
26
+ info = await stat(file);
27
+ }
28
+ catch {
29
+ return { state: "missing" };
30
+ }
31
+ if (!info.isFile())
32
+ return { state: "invalid" };
33
+ if (process.platform !== "win32" && ((info.mode & 0o077) !== 0 || (process.getuid && info.uid !== process.getuid())))
34
+ return { state: "unsafe" };
35
+ try {
36
+ const key = clean(JSON.parse(await readFile(file, "utf8")).apiKey);
37
+ return key ? { state: "ok", key } : { state: "invalid" };
38
+ }
39
+ catch {
40
+ return { state: "invalid" };
41
+ }
42
+ }
43
+ async function readLegacy(file) {
44
+ try {
45
+ return clean(JSON.parse(await readFile(file, "utf8")).elevenlabs_api_key);
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ export async function writeSpeechKey(key, file = speechKeyFile()) {
52
+ const value = clean(key);
53
+ if (!value)
54
+ throw new Error("The ElevenLabs key is empty.");
55
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
56
+ await atomic(file, JSON.stringify({ apiKey: value }) + "\n", 0o600);
57
+ }
58
+ /** ELEVENLABS_API_KEY, else the stored key. When nothing is stored yet and the
59
+ * mina trailer config has a key, it is copied here once and read from here
60
+ * after. */
61
+ export async function resolveSpeechKey(paths = {}) {
62
+ const env = paths.env ?? process.env;
63
+ const fromEnv = clean(env[SPEECH_KEY_ENV]);
64
+ if (fromEnv)
65
+ return { key: fromEnv, source: "environment" };
66
+ const file = paths.file ?? speechKeyFile();
67
+ const stored = await readStored(file);
68
+ if (stored.state === "ok")
69
+ return { key: stored.key, source: "file" };
70
+ if (stored.state !== "missing")
71
+ return undefined;
72
+ const legacy = await readLegacy(paths.legacy ?? legacySpeechKeyFile(env));
73
+ if (!legacy)
74
+ return undefined;
75
+ try {
76
+ await writeSpeechKey(legacy, file);
77
+ }
78
+ catch { /* use it this once; the next call tries again */ }
79
+ return { key: legacy, source: "file" };
80
+ }
81
+ export async function readSpeechKey() {
82
+ return (await resolveSpeechKey())?.key;
83
+ }
84
+ /** Whether this computer has a key, for doctor. Never the key itself, and it
85
+ * doesn't migrate: a read-only check. */
86
+ export async function speechKeyStatus(paths = {}) {
87
+ const env = paths.env ?? process.env;
88
+ const file = paths.file ?? speechKeyFile();
89
+ const stored = await readStored(file);
90
+ const setup = "run `phren bridge speech-key set` and paste the key";
91
+ if (clean(env[SPEECH_KEY_ENV])) {
92
+ return stored.state === "ok"
93
+ ? { configured: true, detail: `${SPEECH_KEY_ENV} is set and a key is stored in ${file}` }
94
+ : { configured: true, detail: `${SPEECH_KEY_ENV} is set in this shell; the Hook service doesn't see shell env, so ${setup} to store it` };
95
+ }
96
+ switch (stored.state) {
97
+ case "ok": return { configured: true, detail: `stored in ${file}` };
98
+ case "unsafe": return { configured: false, problem: true, detail: `${file} is readable by other users; run chmod 600 on it` };
99
+ case "invalid": return { configured: false, problem: true, detail: `${file} has no apiKey; ${setup}` };
100
+ }
101
+ const legacy = paths.legacy ?? legacySpeechKeyFile(env);
102
+ if (await readLegacy(legacy)) {
103
+ return { configured: true, detail: `not stored yet; the Hook copies it from ${legacy} on first use` };
104
+ }
105
+ return { configured: false, detail: `no ElevenLabs key, so spoken replies and Scribe dictation are off; ${setup}` };
106
+ }
@@ -1,5 +1,5 @@
1
1
  import { WebSocket } from "ws";
2
- import { readSpeechKey } from "./speech.js";
2
+ import { readSpeechKey } from "./speech-key.js";
3
3
  /** Dictation through ElevenLabs Scribe v2 Realtime, for the phone's opt-in
4
4
  * Scribe input. The phone streams 16 kHz mono PCM as binary frames; this
5
5
  * computer forwards it to ElevenLabs with its own key, which never leaves
@@ -17,12 +17,10 @@ export declare const speechRequest: z.ZodObject<{
17
17
  }, z.core.$strip>;
18
18
  export interface SpeechOptions {
19
19
  fetch?: typeof fetch;
20
- /** Resolves the ElevenLabs key; defaults to ~/.config/mina-trailer.json. */
20
+ /** Resolves the ElevenLabs key; defaults to ELEVENLABS_API_KEY, then the stored key (speech-key.ts). */
21
21
  key?: () => Promise<string | undefined>;
22
22
  voice?: string;
23
23
  }
24
- export declare function speechKeyFile(env?: NodeJS.ProcessEnv): string;
25
- export declare function readSpeechKey(file?: string): Promise<string | undefined>;
26
24
  /** A fixed message per ElevenLabs failure: its own response text is never
27
25
  * passed on. */
28
26
  export declare function speechError(upstream: Response): Promise<BridgeError>;
@@ -1,9 +1,7 @@
1
1
  import { once } from "node:events";
2
- import { readFile } from "node:fs/promises";
3
- import path from "node:path";
4
2
  import { z } from "zod";
5
- import { homeDir } from "../home-paths.js";
6
3
  import { BridgeError } from "./protocol.js";
4
+ import { readSpeechKey } from "./speech-key.js";
7
5
  /** Spoken replies for the phone's talk mode. The phone sends a sentence; the
8
6
  * Hook voices it with ElevenLabs and streams the audio back. The API key is
9
7
  * read on this computer, used only in the request to ElevenLabs, and never
@@ -18,18 +16,6 @@ export const SPEECH_MODEL = "eleven_flash_v2_5";
18
16
  export const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
19
17
  const MAX_TEXT = 2_000;
20
18
  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
19
  /** A fixed message per ElevenLabs failure: its own response text is never
34
20
  * passed on. */
35
21
  export async function speechError(upstream) {
@@ -52,7 +38,7 @@ export async function speechError(upstream) {
52
38
  }
53
39
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
54
40
  export async function synthesizeSpeech(text, signal, options = {}) {
55
- const key = await (options.key ?? (() => readSpeechKey()))();
41
+ const key = await (options.key ?? readSpeechKey)();
56
42
  if (!key)
57
43
  throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
58
44
  const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
@@ -8,6 +8,8 @@ export declare const PREVIEW_INTERVAL_MS = 500;
8
8
  /** Only the last Claude reply after the current prompt is eligible. A missing
9
9
  * prompt anchor is deliberately silent: scrollback could belong to an old turn. */
10
10
  export declare function claudePanePreview(rendered: string, prompt: string, previous?: string): string;
11
+ /** An unbulleted tool-group summary line, e.g. " Read 1 file, ran 1 shell command". */
12
+ export declare function claudeToolSummary(line: string): boolean;
11
13
  /**
12
14
  * Claude Code's own screen text, never part of a reply: the update and
13
15
  * restart notices, status lines it marks ✔ / ✗ / ⚠ / ※, tips, and the
@@ -69,6 +69,15 @@ export function claudePanePreview(rendered, prompt, previous = "") {
69
69
  break;
70
70
  if (/^\s*[✻✽✶✢✳✦·⠁-⣿]/u.test(line) || parseClaudeSpinnerLine(line))
71
71
  continue;
72
+ // Claude Code draws a finished or running tool group as an unbulleted,
73
+ // indented summary under the reply (" Ran 1 shell command", " Called
74
+ // phren, ran 1 shell command", " Running 1 shell command… grep -rn …").
75
+ // It starts a block after a blank line; it and its wrapped command lines
76
+ // are tool activity, which lands as its own entry.
77
+ if (!body[index - 1]?.trim() && claudeToolSummary(line)) {
78
+ writing = false;
79
+ continue;
80
+ }
72
81
  // A running tool group ("⏺ Running 2 agents…") and a tool call
73
82
  // ("⏺ Bash(ls)", "⏺ phren - search (MCP)(…)") are not reply
74
83
  // text; it lands as its own entry a moment later.
@@ -101,6 +110,12 @@ export function claudePanePreview(rendered, prompt, previous = "") {
101
110
  return overlap >= 0 && text.startsWith(previous.slice(overlap))
102
111
  ? (previous.slice(0, overlap) + text).slice(0, MAX_TEXT) : previous;
103
112
  }
113
+ const TOOL_SUMMARY_CLAUSE = String.raw `(?:(?:[Cc]alled|[Cc]alling) [\w.-]+(?: \d+ times?)?|(?:[Rr]an|[Rr]unning|[Rr]ead|[Rr]eading|[Ss]earched|[Ss]earching|[Ww]rote|[Ww]riting|[Ee]dited|[Ee]diting|[Uu]pdated|[Uu]pdating|[Ff]etched|[Ff]etching|[Ll]isted|[Ll]isting|[Cc]reated|[Cc]reating|[Ll]aunched|[Ll]aunching) \d+ [a-z]+(?: [a-z]+)?)`;
114
+ const TOOL_SUMMARY = new RegExp(`^ {1,4}${TOOL_SUMMARY_CLAUSE}(?:, ${TOOL_SUMMARY_CLAUSE})*(?:(?:…|\\.\\.\\.)(?:\\s.*)?)?(?: \\(ctrl\\+o to expand\\))?\\s*$`);
115
+ /** An unbulleted tool-group summary line, e.g. " Read 1 file, ran 1 shell command". */
116
+ export function claudeToolSummary(line) {
117
+ return TOOL_SUMMARY.test(line);
118
+ }
104
119
  /**
105
120
  * Claude Code's own screen text, never part of a reply: the update and
106
121
  * restart notices, status lines it marks ✔ / ✗ / ⚠ / ※, tips, and the