@phren/cli 0.3.0 → 0.3.2

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 (64) hide show
  1. package/dist/bridge/agent-hooks.d.ts +20 -6
  2. package/dist/bridge/agent-hooks.js +74 -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/command.d.ts +3 -2
  6. package/dist/bridge/command.js +97 -5
  7. package/dist/bridge/computers.d.ts +5 -0
  8. package/dist/bridge/computers.js +10 -4
  9. package/dist/bridge/conductor-group.d.ts +23 -0
  10. package/dist/bridge/conductor-group.js +25 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/herdr.d.ts +7 -0
  13. package/dist/bridge/herdr.js +53 -2
  14. package/dist/bridge/link.d.ts +48 -0
  15. package/dist/bridge/link.js +136 -0
  16. package/dist/bridge/memory-store.d.ts +23 -0
  17. package/dist/bridge/memory-store.js +152 -0
  18. package/dist/bridge/pair.d.ts +46 -0
  19. package/dist/bridge/pair.js +240 -0
  20. package/dist/bridge/peers.d.ts +9 -0
  21. package/dist/bridge/peers.js +25 -2
  22. package/dist/bridge/push.d.ts +42 -3
  23. package/dist/bridge/push.js +90 -20
  24. package/dist/bridge/server-launch.d.ts +9 -0
  25. package/dist/bridge/server-launch.js +34 -11
  26. package/dist/bridge/server-pane-routes.js +45 -8
  27. package/dist/bridge/server-routes.d.ts +1 -0
  28. package/dist/bridge/server-routes.js +11 -3
  29. package/dist/bridge/server-stream.js +4 -1
  30. package/dist/bridge/speech-key.d.ts +33 -0
  31. package/dist/bridge/speech-key.js +106 -0
  32. package/dist/bridge/speech-transcribe.js +1 -1
  33. package/dist/bridge/speech.d.ts +7 -3
  34. package/dist/bridge/speech.js +36 -17
  35. package/dist/bridge-hook.mjs +1356 -514
  36. package/dist/cli/namespaces-store.js +21 -0
  37. package/dist/cli-handlers.js +6 -0
  38. package/dist/cli-registry.js +14 -2
  39. package/dist/content/learning.js +1 -1
  40. package/dist/data/tasks.d.ts +26 -0
  41. package/dist/data/tasks.js +72 -1
  42. package/dist/entrypoint.js +7 -0
  43. package/dist/governance/rbac.d.ts +1 -1
  44. package/dist/governance/rbac.js +1 -0
  45. package/dist/init/init-walkthrough.d.ts +10 -0
  46. package/dist/init/init-walkthrough.js +25 -2
  47. package/dist/init/init.d.ts +5 -0
  48. package/dist/init/init.js +54 -32
  49. package/dist/link/doctor.js +10 -0
  50. package/dist/link/link.js +9 -3
  51. package/dist/link/refresh.js +11 -10
  52. package/dist/mcp/profile.js +2 -1
  53. package/dist/modules/config.d.ts +7 -0
  54. package/dist/modules/config.js +17 -0
  55. package/dist/modules/registry.js +5 -4
  56. package/dist/sync/conflict-resolve.d.ts +1 -1
  57. package/dist/sync/conflict-resolve.js +44 -7
  58. package/dist/sync/task-claim.d.ts +22 -0
  59. package/dist/sync/task-claim.js +45 -0
  60. package/dist/tools/dispatch.js +2 -2
  61. package/dist/tools/search.js +1 -1
  62. package/dist/tools/tasks.js +40 -1
  63. package/package.json +2 -1
  64. package/starter/global/skills/conductor/SKILL.md +41 -9
@@ -3,6 +3,7 @@ import { type ServerResponse } from "node:http";
3
3
  import { type Json, type Provider, type Target } from "./protocol.js";
4
4
  import { ToolChanges } from "./changes.js";
5
5
  import { ApprovalPushService } from "./push.js";
6
+ import { type DialogAnswer, type DialogQuestion } from "./claude-question-dialog.js";
6
7
  import { type TerminalChoice } from "./terminal-choice.js";
7
8
  import { ApprovalWatchLeases } from "./agent-hook-stores.js";
8
9
  export { permissionPrompt, terminalChoice, visibleTerminalChoice, type TerminalChoice, type TerminalQuestion } from "./terminal-choice.js";
@@ -143,12 +144,20 @@ export declare class AgentHooks {
143
144
  * keyless rows are reached and verified before returning Enter to the route. */
144
145
  dialogAnswerKeys<K extends string>(target: Target, keys: readonly K[]): Promise<(K | "Enter")[]>;
145
146
  moveDialogHighlight(target: Target, expected: TerminalChoice, key: string, beforeKeys?: () => Promise<void>): Promise<void>;
146
- /** Answer one question of a released AskUserQuestion with the option's own
147
- * digit: send the chosen digit(s), then Tab to advance to the next
148
- * question or Enter after the last. The stored question index moves with
149
- * them and a finished set is cleared. Undefined when the prompt is not a
150
- * question, so an ordinary key falls through to the usual handling. */
151
- questionAnswerKeys(target: Target, keys: readonly string[]): string[] | undefined;
147
+ /** Answer Claude's AskUserQuestion dialog in the pane: every question in
148
+ * `answers` from `from` on, then the set's submission when `submit`. The
149
+ * walk reads the pane before and after each key, so a dialog on another
150
+ * tab, a changed question or a missed key stops it with nothing stray
151
+ * typed. A finished set clears the remembered question. */
152
+ answerClaudeQuestions(target: Target, questions: DialogQuestion[], answers: DialogAnswer[], options?: {
153
+ from?: number;
154
+ submit?: boolean;
155
+ }): Promise<void>;
156
+ /** An older phone answers a released AskUserQuestion one question at a
157
+ * time with the chosen digits through `/v1/keys`. Walk that question with
158
+ * the same verified steps and submit after the last. False when the
159
+ * prompt is not a remembered question, so the keys take the usual path. */
160
+ answerReleasedQuestion(target: Target, keys: readonly string[]): Promise<boolean>;
152
161
  private startCompacting;
153
162
  private stopCompacting;
154
163
  /** True while Claude Code is compacting `target`; a boundary older than ten
@@ -186,6 +195,11 @@ export declare class AgentHooks {
186
195
  * phone with its own keys: let the callback fall back to the terminal at
187
196
  * once instead of leaving the card up until the 55-second timer. */
188
197
  releaseChoice(target: Target): void;
198
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
199
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
200
+ * go and the terminal stays frozen until the hold timer; decline it now so
201
+ * Claude moves on. True when a held question was cancelled. */
202
+ cancelHeldQuestion(target: Target): boolean;
189
203
  answerPush(binding: string, decision: unknown): Promise<void>;
190
204
  /** Where a pushed ask lives, without answering it: the phone opens that
191
205
  * session's details when the notification itself is tapped. */
@@ -16,6 +16,7 @@ import { archiveFinishedFanouts, blockedFanouts, fanoutAsking } from "./fanouts.
16
16
  import { ensureGrant, listGrants, matchGrant } from "./grants.js";
17
17
  import { ApprovalPushService } from "./push.js";
18
18
  import { intervalFromEnv } from "./limits.js";
19
+ import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
19
20
  import { answeredQuestionInput, numberedDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
20
21
  import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
21
22
  import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
@@ -430,18 +431,17 @@ export class AgentHooks {
430
431
  return;
431
432
  }
432
433
  // A released AskUserQuestion is answered by its own question card, never
433
- // by the pane's numbered lines; it is cleared only when the pane stops
434
- // waiting for it.
435
- if (entry?.questions?.length) {
436
- if (!active) {
437
- this.terminalPrompts.delete(key);
438
- this.passwords.delete(key);
439
- }
434
+ // by the pane's numbered lines. It is cleared when the pane stops waiting
435
+ // or no longer draws a question (answered or cancelled in the terminal).
436
+ const question = !!entry?.questions?.length;
437
+ if (question && !active) {
438
+ this.terminalPrompts.delete(key);
439
+ this.passwords.delete(key);
440
440
  return;
441
441
  }
442
442
  // A released permission request that carried its own choices keeps them;
443
443
  // one without (a Bash or MCP call) reads the pane's rows below.
444
- if (entry && !entry.dialog && entry.choice && !entry.released)
444
+ if (!question && entry && !entry.dialog && entry.choice && !entry.released)
445
445
  return;
446
446
  if (!active) {
447
447
  if (entry)
@@ -459,6 +459,19 @@ export class AgentHooks {
459
459
  this.passwords.set(key, passwordLine(text));
460
460
  while (this.passwords.size > 128)
461
461
  this.passwords.delete(this.passwords.keys().next().value);
462
+ // Claude's AskUserQuestion dialog is answered from the question itself
463
+ // (the held request, the remembered one, or the transcript's), never as
464
+ // a numbered dialog: its digits advance on their own and a trailing
465
+ // Enter would land on the next tab.
466
+ if (target.source === "claude" && claudeQuestionDialog(text)) {
467
+ if (entry && !question)
468
+ this.terminalPrompts.delete(key);
469
+ return;
470
+ }
471
+ if (question) {
472
+ this.terminalPrompts.delete(key);
473
+ return;
474
+ }
462
475
  // Codex draws "> 1. Yes, proceed (y)" rows; the other fallbacks number
463
476
  // rows without a key in the label.
464
477
  const dialog = target.source === "codex" ? visibleTerminalChoice(text) : numberedDialog(text);
@@ -536,26 +549,44 @@ export class AgentHooks {
536
549
  }
537
550
  throw new BridgeError(409, "Could not move and verify the terminal selection. Open terminal to choose this option.");
538
551
  }
539
- /** Answer one question of a released AskUserQuestion with the option's own
540
- * digit: send the chosen digit(s), then Tab to advance to the next
541
- * question or Enter after the last. The stored question index moves with
542
- * them and a finished set is cleared. Undefined when the prompt is not a
543
- * question, so an ordinary key falls through to the usual handling. */
544
- questionAnswerKeys(target, keys) {
552
+ /** Answer Claude's AskUserQuestion dialog in the pane: every question in
553
+ * `answers` from `from` on, then the set's submission when `submit`. The
554
+ * walk reads the pane before and after each key, so a dialog on another
555
+ * tab, a changed question or a missed key stops it with nothing stray
556
+ * typed. A finished set clears the remembered question. */
557
+ async answerClaudeQuestions(target, questions, answers, options = {}) {
558
+ const key = JSON.stringify(target);
559
+ await answerClaudeQuestionDialog({
560
+ read: () => this.paneLines(target),
561
+ keys: async (keys) => {
562
+ if (!keys.length)
563
+ return;
564
+ await validateTarget(target, false, true);
565
+ await rpc(target.server, "agent.send_keys", { target: target.pane, keys });
566
+ },
567
+ }, questions, answers, options);
568
+ this.dialogReads.delete(key);
569
+ if (options.submit ?? true)
570
+ this.terminalPrompts.delete(key);
571
+ }
572
+ /** An older phone answers a released AskUserQuestion one question at a
573
+ * time with the chosen digits through `/v1/keys`. Walk that question with
574
+ * the same verified steps and submit after the last. False when the
575
+ * prompt is not a remembered question, so the keys take the usual path. */
576
+ async answerReleasedQuestion(target, keys) {
545
577
  const key = JSON.stringify(target), entry = this.terminalPrompts.get(key);
546
- if (!entry?.questions?.length)
547
- return undefined;
578
+ if (target.source !== "claude" || !entry?.questions?.length)
579
+ return false;
548
580
  const digits = keys.filter(value => /^[1-9]$/.test(value));
549
581
  if (!digits.length)
550
- return undefined;
551
- const index = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), next = index + 1;
552
- if (next >= entry.questions.length) {
553
- this.terminalPrompts.delete(key);
554
- return [...digits, "Enter"];
582
+ return false;
583
+ const index = Math.min(entry.questionIndex ?? 0, entry.questions.length - 1), last = index + 1 >= entry.questions.length;
584
+ await this.answerClaudeQuestions(target, entry.questions, [{ options: digits.map(digit => Number(digit) - 1) }], { from: index, submit: last });
585
+ if (!last) {
586
+ entry.questionIndex = index + 1;
587
+ entry.choice = questionChoice(entry.questions, index + 1);
555
588
  }
556
- entry.questionIndex = next;
557
- entry.choice = questionChoice(entry.questions, next);
558
- return [...digits, "Tab"];
589
+ return true;
559
590
  }
560
591
  startCompacting(target) {
561
592
  this.compactingSince.set(JSON.stringify(target), Date.now());
@@ -778,6 +809,25 @@ export class AgentHooks {
778
809
  entry.response.end("{}");
779
810
  }
780
811
  }
812
+ /** The phone's Esc or Cancel on a question the Hook holds. A held
813
+ * AskUserQuestion has no terminal choice, so `releaseChoice` never lets it
814
+ * go and the terminal stays frozen until the hold timer; decline it now so
815
+ * Claude moves on. True when a held question was cancelled. */
816
+ cancelHeldQuestion(target) {
817
+ let cancelled = false;
818
+ for (const [id, entry] of this.pending) {
819
+ if (entry.tool !== "AskUserQuestion" || JSON.stringify(entry.target) !== JSON.stringify(target))
820
+ continue;
821
+ this.pending.delete(id);
822
+ this.dropPushBindings(id);
823
+ clearTimeout(entry.timer);
824
+ if (!entry.response.destroyed)
825
+ entry.response.end(JSON.stringify({ hookSpecificOutput: { hookEventName: "PermissionRequest",
826
+ decision: { behavior: "deny", message: "The user cancelled this question in Phren without answering." } } }));
827
+ cancelled = true;
828
+ }
829
+ return cancelled;
830
+ }
781
831
  async answerPush(binding, decision) {
782
832
  if (!["approve", "deny"].includes(String(decision)))
783
833
  throw new BridgeError(400, "The approval answer is not valid.");
@@ -0,0 +1,65 @@
1
+ /** Claude Code's AskUserQuestion dialog as the pane draws it, and a walk that
2
+ * answers it one verified key at a time. Claude's keys are not uniform: a
3
+ * digit on a single-select question picks the row and moves to the next
4
+ * question on its own, a digit on a multi-select question only toggles its
5
+ * box, Tab leaves a multi-select question (or, from the typed "Other" row,
6
+ * moves to its Next row), and a set of more than one question, or any
7
+ * multi-select question, ends on a "Review your answers" tab that "1"
8
+ * submits. Blind key sequences drift onto the wrong tab, so every step reads
9
+ * the pane first and checks the result before the next. */
10
+ interface Row {
11
+ number: number;
12
+ label: string;
13
+ checked?: boolean;
14
+ answered: boolean;
15
+ cursor: boolean;
16
+ }
17
+ export interface ClaudeQuestionScreen {
18
+ kind: "question";
19
+ /** Headers from the tab bar, without the trailing Submit tab. */
20
+ tabs: string[];
21
+ title: string;
22
+ multiSelect: boolean;
23
+ /** The asked options, in order; the typed "Other" row is `other`. */
24
+ options: Row[];
25
+ other?: Row;
26
+ /** The row number under the cursor, or "next" on a multi-select Next/Submit row. */
27
+ cursor?: number | "next";
28
+ }
29
+ export interface ClaudeReviewScreen {
30
+ kind: "review";
31
+ tabs: string[];
32
+ answers: {
33
+ question: string;
34
+ answer: string;
35
+ }[];
36
+ }
37
+ export type ClaudeDialogScreen = ClaudeQuestionScreen | ClaudeReviewScreen;
38
+ /** The question dialog the pane is drawing now, or undefined when the last
39
+ * lines are not one: the last tab bar anchors it, and an active dialog ends
40
+ * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
41
+ export declare function claudeQuestionDialog(text: string): ClaudeDialogScreen | undefined;
42
+ export interface DialogQuestion {
43
+ question: string;
44
+ multiSelect?: boolean;
45
+ options: {
46
+ label: string;
47
+ }[];
48
+ }
49
+ /** Option indexes into the question's options, plus a typed "Other" answer. */
50
+ export interface DialogAnswer {
51
+ options: number[];
52
+ text?: string;
53
+ }
54
+ export interface DialogIO {
55
+ read(): Promise<string>;
56
+ keys(keys: string[]): Promise<void>;
57
+ sleep?(ms: number): Promise<void>;
58
+ }
59
+ /** Answer `answers[i]` for question `from + i`, then submit the set when
60
+ * `submit` is true. Each step is checked against a fresh read of the pane. */
61
+ export declare function answerClaudeQuestionDialog(io: DialogIO, questions: DialogQuestion[], answers: DialogAnswer[], options?: {
62
+ from?: number;
63
+ submit?: boolean;
64
+ }): Promise<void>;
65
+ export {};
@@ -0,0 +1,210 @@
1
+ import { BridgeError } from "./protocol.js";
2
+ const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
3
+ const ROW = /^\s*(❯)?\s*(\d)\.\s+(?:\[([ ✔])\]\s+)?(.*?)\s*$/;
4
+ const NEXT = /^\s*(❯)?\s+(?:Next|Submit)\s*$/;
5
+ const normalize = (text) => text.replace(/\s+/g, " ").trim();
6
+ /** The question dialog the pane is drawing now, or undefined when the last
7
+ * lines are not one: the last tab bar anchors it, and an active dialog ends
8
+ * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
9
+ export function claudeQuestionDialog(text) {
10
+ const lines = text.split(/\r?\n/);
11
+ let bar = -1;
12
+ for (let index = lines.length - 1; index >= 0; index--)
13
+ if (TAB_BAR.test(lines[index]) && /[☐☒]/.test(lines[index])) {
14
+ bar = index;
15
+ break;
16
+ }
17
+ if (bar < 0)
18
+ return undefined;
19
+ const tabs = [...lines[bar].matchAll(/[☐☒]\s+([^☐☒✔→]+?)(?=\s{2,}|\s*[☐☒✔→]|\s*$)/g)].map(match => match[1].trim());
20
+ const body = lines.slice(bar + 1);
21
+ const content = body.map(line => line.trim()).filter(line => line && !/^─+$/.test(line));
22
+ if (content[0] === "Review your answers") {
23
+ if (!body.some(line => /^\s*❯?\s*1\.\s+Submit answers\s*$/.test(line)))
24
+ return undefined;
25
+ const answers = [];
26
+ for (const line of content.slice(1)) {
27
+ if (/^Ready to submit/.test(line))
28
+ break;
29
+ const question = /^●\s+(.+)$/.exec(line), answer = /^→\s+(.+)$/.exec(line), last = answers[answers.length - 1];
30
+ if (question)
31
+ answers.push({ question: question[1], answer: "" });
32
+ else if (answer && last)
33
+ last.answer = answer[1];
34
+ // A long question or answer wraps onto the next line.
35
+ else if (last) {
36
+ if (last.answer)
37
+ last.answer += " " + line;
38
+ else
39
+ last.question += " " + line;
40
+ }
41
+ }
42
+ return { kind: "review", tabs, answers };
43
+ }
44
+ if (!content.some(line => /Esc to cancel/.test(line)))
45
+ return undefined;
46
+ const first = body.findIndex(line => ROW.test(line));
47
+ if (first < 0)
48
+ return undefined;
49
+ const title = normalize(body.slice(0, first).filter(line => line.trim()).join(" "));
50
+ const rows = [];
51
+ let cursor, chat = false;
52
+ for (const line of body.slice(first)) {
53
+ const next = NEXT.exec(line);
54
+ if (next) {
55
+ if (next[1])
56
+ cursor = "next";
57
+ continue;
58
+ }
59
+ const match = ROW.exec(line);
60
+ if (!match)
61
+ continue;
62
+ const number = Number(match[2]);
63
+ if (match[1])
64
+ cursor = number;
65
+ if (/^Chat about this$/.test(match[4])) {
66
+ chat = true;
67
+ continue;
68
+ }
69
+ const answered = !match[3] && / ✔$/.test(match[4]);
70
+ rows.push({ number, label: answered ? match[4].slice(0, -2).trim() : match[4], answered, cursor: !!match[1],
71
+ ...(match[3] ? { checked: match[3] === "✔" } : {}) });
72
+ }
73
+ if (!title || !chat || rows.length < 2)
74
+ return undefined;
75
+ // The last row above "Chat about this" is the typed answer ("Type
76
+ // something." until something is typed there).
77
+ const other = rows.pop();
78
+ return { kind: "question", tabs, title, multiSelect: rows.some(row => row.checked !== undefined), options: rows, other, ...(cursor !== undefined ? { cursor } : {}) };
79
+ }
80
+ const changed = (message) => new BridgeError(409, `${message} Nothing else was sent; check the question and answer again, or cancel it.`);
81
+ /** A typed answer, one key per character; herdr names the space bar. */
82
+ const typedKeys = (text) => [...text].map(character => character === " " ? "space" : character);
83
+ /** Answer `answers[i]` for question `from + i`, then submit the set when
84
+ * `submit` is true. Each step is checked against a fresh read of the pane. */
85
+ export async function answerClaudeQuestionDialog(io, questions, answers, options = {}) {
86
+ const from = options.from ?? 0, submit = options.submit ?? true;
87
+ const sleep = io.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
88
+ const matches = (screen, index) => screen?.kind === "question" && screen.title === normalize(questions[index].question);
89
+ // Claude redraws a moment after a key; poll until the expected screen shows.
90
+ const settle = async (check, ms = 2_000) => {
91
+ for (let waited = 0;; waited += 120) {
92
+ const value = check(claudeQuestionDialog(await io.read()));
93
+ if (value !== undefined || waited >= ms)
94
+ return value;
95
+ await sleep(120);
96
+ }
97
+ };
98
+ const initial = await settle(screen => screen);
99
+ if (!initial)
100
+ throw changed("The terminal is not showing Claude's question.");
101
+ // A set of several questions draws one tab per question; a single question
102
+ // draws its own header. The tabs must be this set's, in this order.
103
+ if (initial.tabs.length !== questions.length)
104
+ throw changed("The terminal is asking a different set of questions.");
105
+ const reach = async (index) => {
106
+ const screen = await settle(value => value);
107
+ if (screen?.kind === "question" && screen.title === normalize(questions[index].question))
108
+ return screen;
109
+ const at = screen?.kind === "review" ? questions.length
110
+ : screen?.kind === "question" ? questions.findIndex(question => normalize(question.question) === screen.title) : -1;
111
+ if (at < 0)
112
+ throw changed("The terminal is showing a different question.");
113
+ // Arrow keys would edit a typed answer; step off that row first.
114
+ if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number)
115
+ await io.keys(["up"]);
116
+ await io.keys(Array(Math.abs(index - at)).fill(index > at ? "right" : "left"));
117
+ const moved = await settle(value => matches(value, index) ? value : undefined);
118
+ if (!moved)
119
+ throw changed("Could not move the terminal to the question being answered.");
120
+ return moved;
121
+ };
122
+ const leaves = (index) => (value) => value === undefined ? "gone" : !matches(value, index) ? "moved" : undefined;
123
+ for (const [offset, answer] of answers.entries()) {
124
+ const index = from + offset, question = questions[index];
125
+ if (!question)
126
+ throw new BridgeError(400, "The answer names a question that was not asked.");
127
+ const typed = answer.text?.trim() ?? "";
128
+ let screen = await reach(index);
129
+ if (screen.multiSelect !== !!question.multiSelect || screen.options.length !== question.options.length
130
+ || screen.options.some((row, position) => row.label !== question.options[position].label.trim())) {
131
+ throw changed("The terminal's options differ from the question being answered.");
132
+ }
133
+ if (!screen.multiSelect) {
134
+ if (typed) {
135
+ const other = screen.other;
136
+ await io.keys([String(other.number)]);
137
+ const focused = await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined);
138
+ if (!focused)
139
+ throw changed("Could not open the typed answer.");
140
+ await io.keys(typedKeys(typed));
141
+ const shown = await settle(value => matches(value, index) && value.other && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
142
+ if (!shown)
143
+ throw changed("The typed answer did not appear in the terminal.");
144
+ await io.keys(["enter"]);
145
+ }
146
+ else {
147
+ await io.keys([String(screen.options[answer.options[0]].number)]);
148
+ }
149
+ if (!await settle(leaves(index)))
150
+ throw changed("The terminal did not take the answer.");
151
+ continue;
152
+ }
153
+ // Multi-select: toggle only the boxes that differ, one key per write
154
+ // (Ink reads "13" in one write as a single input and toggles nothing),
155
+ // and check each box before the next.
156
+ const rows = [...screen.options, ...(screen.other ? [screen.other] : [])];
157
+ for (const [position, row] of rows.entries()) {
158
+ const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.checked && !!typed;
159
+ if (wanted === !!row.checked)
160
+ continue;
161
+ const box = (value) => matches(value, index)
162
+ ? !!(position < value.options.length ? value.options[position] : value.other)?.checked : undefined;
163
+ // A key that lands while the tab is still drawing can be dropped; the
164
+ // box itself says whether one more press is needed.
165
+ for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
166
+ await io.keys([String(row.number)]);
167
+ screen = await settle(value => box(value) === wanted ? value : undefined, 1_000) ?? screen;
168
+ }
169
+ if (box(screen) !== wanted)
170
+ throw changed("The terminal's checkboxes did not match the answer.");
171
+ }
172
+ if (typed) {
173
+ const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
174
+ if (cursor !== other.number)
175
+ await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
176
+ if (!await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined))
177
+ throw changed("Could not reach the typed answer row.");
178
+ await io.keys(typedKeys(typed));
179
+ const shown = await settle(value => matches(value, index) && value.other?.checked && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
180
+ if (!shown)
181
+ throw changed("The typed answer did not appear in the terminal.");
182
+ // Tab moves from the typed row to Next; Enter there leaves the question.
183
+ await io.keys(["tab"]);
184
+ if (!await settle(value => matches(value, index) && value.cursor === "next" ? value : undefined))
185
+ throw changed("Could not reach the question's Next row.");
186
+ await io.keys(["enter"]);
187
+ }
188
+ else {
189
+ // Tab from the typed row would stop on Next instead of leaving.
190
+ await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
191
+ }
192
+ if (!await settle(leaves(index)))
193
+ throw changed("The terminal did not move past the question.");
194
+ }
195
+ if (!submit)
196
+ return;
197
+ const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined);
198
+ // A lone single-select question submits on its digit.
199
+ if (review === "gone")
200
+ return;
201
+ if (!review)
202
+ throw changed("The terminal did not reach the review of the answers.");
203
+ const expected = questions.map(question => normalize(question.question));
204
+ if (review.answers.length !== questions.length || review.answers.some((row, position) => normalize(row.question) !== expected[position] || !row.answer)) {
205
+ throw changed("Not every question has an answer in the terminal.");
206
+ }
207
+ await io.keys(["1"]);
208
+ if (await settle(value => value === undefined ? "gone" : undefined) !== "gone")
209
+ throw changed("The terminal did not submit the answers.");
210
+ }
@@ -1,7 +1,8 @@
1
1
  import { type Json } from "./protocol.js";
2
2
  export declare function runBridge(args: string[], version: string): Promise<number>;
3
- /** Doctor's push check, from the running Hook's own capability: only a Hook
4
- * that loaded apns.json and its key offers `approvalPush`. */
3
+ /** Doctor's push check, from the running Hook's own capability: a Hook that
4
+ * loaded apns.json and its key, or one whose phones registered through the
5
+ * push relay, offers `approvalPush`. */
5
6
  export declare function approvalPushCheck(helper: Json): {
6
7
  configured: boolean;
7
8
  warning?: string;
@@ -6,9 +6,12 @@ import { servers } from "./herdr.js";
6
6
  import { agentHook } from "./agent-hooks.js";
7
7
  import { object, provider } from "./protocol.js";
8
8
  import { apnsSetupSteps } from "./push.js";
9
+ import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
9
10
  import { AccountUsageReader, captureClaudeUsage } from "./usage.js";
10
11
  import { acceptComputer, enrollComputer } from "./computers.js";
12
+ import { addPeerFromLink, discoverComputers, linkComputer } from "./link.js";
11
13
  import { ARCHIVE_MAX_FOLDERS, archiveFinishedFanouts, FANOUTS_ARCHIVE_USAGE, parseFanoutArchiveFlags } from "./fanouts.js";
14
+ const LINK_USAGE = "Usage: phren bridge link <ssh-host> [--name <its name here>] [--as <this computer's name there>] [--back-address <address it dials>] [--yes]";
12
15
  export async function runBridge(args, version) {
13
16
  switch (args[0]) {
14
17
  case "enroll-computer": {
@@ -22,6 +25,46 @@ export async function runBridge(args, version) {
22
25
  throw new Error("Usage: phren bridge enroll-computer <name> [--accept <public-key-file>]");
23
26
  break;
24
27
  }
28
+ case "discover": {
29
+ const { reachable, checked } = await discoverComputers();
30
+ if (!reachable.length)
31
+ console.log(`No unlinked computers running Phren Hook answered over ssh (checked ${checked.length}: ${checked.join(", ") || "none"}).`);
32
+ else {
33
+ console.log("Reachable over ssh, running Phren Hook, and not linked:");
34
+ for (const item of reachable)
35
+ console.log(` ${item.host} (${item.user}) link with: phren bridge link ${item.host}`);
36
+ }
37
+ break;
38
+ }
39
+ case "link": {
40
+ const host = args[1];
41
+ const flag = (name) => { const index = args.indexOf(name); return index > 1 ? args[index + 1] : undefined; };
42
+ if (!host || host.startsWith("-"))
43
+ throw new Error(LINK_USAGE);
44
+ if (!args.includes("--yes")) {
45
+ if (!process.stdin.isTTY)
46
+ throw new Error(`Linking ${host} lets each computer run agents on the other. Pass --yes to confirm.`);
47
+ const { createInterface } = await import("node:readline/promises");
48
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
49
+ const answer = await prompt.question(`Link this computer and ${host} both ways, so each can list and start agents on the other? [y/N] `);
50
+ prompt.close();
51
+ if (!/^y(es)?$/i.test(answer.trim())) {
52
+ console.log("Not linked.");
53
+ return 1;
54
+ }
55
+ }
56
+ const result = await linkComputer(host, { name: flag("--name"), as: flag("--as"), backAddress: flag("--back-address") });
57
+ console.log(JSON.stringify(result, null, 2));
58
+ return result.reachable && result.remote.reachable ? 0 : 1;
59
+ }
60
+ case "add-peer": {
61
+ // The receiving half of `phren bridge link`, run by the linking computer over ssh.
62
+ const chunks = [];
63
+ for await (const chunk of process.stdin)
64
+ chunks.push(chunk);
65
+ console.log(JSON.stringify(await addPeerFromLink(Buffer.concat(chunks).toString("utf8"))));
66
+ break;
67
+ }
25
68
  case "fanouts": {
26
69
  if (args[1] !== "archive")
27
70
  throw new Error(FANOUTS_ARCHIVE_USAGE);
@@ -33,6 +76,14 @@ export async function runBridge(args, version) {
33
76
  console.log(`${doing} ${moved.length} fan-out job(s); ${removal} ${deleted} past the ${ARCHIVE_MAX_FOLDERS}-folder cap.`);
34
77
  break;
35
78
  }
79
+ case "speech-key": {
80
+ // The key comes from stdin, never argv, so it stays out of ps and shell history.
81
+ if (args[1] !== "set" || args.length !== 2)
82
+ throw new Error(SPEECH_KEY_USAGE);
83
+ await writeSpeechKey(await readSecret("ElevenLabs API key: "));
84
+ console.log(`Stored the ElevenLabs key in ${speechKeyFile()} (mode 600).`);
85
+ break;
86
+ }
36
87
  case "usage-statusline":
37
88
  await captureClaudeUsage(args[1] || "");
38
89
  break;
@@ -63,25 +114,66 @@ export async function runBridge(args, version) {
63
114
  break;
64
115
  case "doctor": {
65
116
  const helper = await health(), muxes = await servers();
66
- const push = approvalPushCheck(helper);
117
+ const push = approvalPushCheck(helper), speech = await speechKeyStatus();
67
118
  // Chat needs Herdr; a plain project shell or agent over SSH does not.
68
119
  console.log(JSON.stringify({ ok: true, helper, herdr: muxes, checks: {
69
120
  privateSocket: true, protocol: true, independentHelper: true,
70
121
  herdrRunning: muxes.length > 0, terminal: "SSH PTY; authorize the Phren device key with pty",
71
122
  shell: muxes.length > 0 ? "available" : "Herdr is not running: chat is unavailable, project shells and agents still open over SSH",
72
123
  approvalPush: push.configured ? "configured" : "not configured",
124
+ speechKey: speech.configured ? "configured" : "not configured", speechKeyDetail: speech.detail,
73
125
  }, ...(push.warning ? { warnings: [push.warning] } : {}) }, null, 2));
74
126
  if (push.warning)
75
127
  console.error(`warning: ${push.warning}`);
76
128
  break;
77
129
  }
78
- default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|fanouts archive>");
130
+ default: throw new Error("Usage: phren bridge <install|status|doctor|usage|update|rollback|uninstall|enroll-computer|discover|link|fanouts archive|speech-key set>");
79
131
  }
80
132
  return 0;
81
133
  }
82
- /** Doctor's push check, from the running Hook's own capability: only a Hook
83
- * that loaded apns.json and its key offers `approvalPush`. */
134
+ /** Doctor's push check, from the running Hook's own capability: a Hook that
135
+ * loaded apns.json and its key, or one whose phones registered through the
136
+ * push relay, offers `approvalPush`. */
84
137
  export function approvalPushCheck(helper) {
85
- const configured = object(helper.capabilities).approvalPush === "direct-apns";
138
+ const capability = object(helper.capabilities).approvalPush;
139
+ const configured = capability === "direct-apns" || capability === "relay";
86
140
  return configured ? { configured } : { configured, warning: apnsSetupSteps() };
87
141
  }
142
+ const SPEECH_KEY_USAGE = "Usage: phren bridge speech-key set (paste the key when asked, or pipe it on stdin)";
143
+ /** One line from stdin: piped as is, or typed at a prompt without echo. */
144
+ async function readSecret(prompt) {
145
+ const stdin = process.stdin;
146
+ if (!stdin.isTTY) {
147
+ let text = "";
148
+ for await (const chunk of stdin)
149
+ text += chunk;
150
+ return text;
151
+ }
152
+ process.stderr.write(prompt);
153
+ stdin.setEncoding("utf8");
154
+ stdin.setRawMode(true);
155
+ stdin.resume();
156
+ return new Promise((resolve, reject) => {
157
+ let value = "";
158
+ const finish = () => { stdin.off("data", onData); stdin.setRawMode(false); stdin.pause(); process.stderr.write("\n"); };
159
+ const onData = (chunk) => {
160
+ for (const char of chunk) {
161
+ if (char === "\r" || char === "\n") {
162
+ finish();
163
+ resolve(value);
164
+ return;
165
+ }
166
+ if (char === "\u0003") {
167
+ finish();
168
+ reject(new Error("Cancelled."));
169
+ return;
170
+ }
171
+ if (char === "\u007f" || char === "\b")
172
+ value = value.slice(0, -1);
173
+ else
174
+ value += char;
175
+ }
176
+ };
177
+ stdin.on("data", onData);
178
+ });
179
+ }
@@ -7,3 +7,8 @@ export declare function computerKeyLine(name: string, publicKey: string): string
7
7
  export declare function enrollComputer(name: string, root?: string): Promise<string>;
8
8
  /** Accept a public key, rebuilding the restrictions rather than trusting supplied options. */
9
9
  export declare function acceptComputer(name: string, input: string, sshDirectory?: string): Promise<void>;
10
+ /**
11
+ * Append one authorized_keys line under a lock, refusing when `conflicts`
12
+ * matches an existing line and leaving an identical line in place.
13
+ */
14
+ export declare function appendAuthorizedKey(line: string, conflicts: (existing: string) => boolean, conflictMessage: string, sshDirectory?: string): Promise<void>;