@phren/cli 0.3.2 → 0.3.4

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.
@@ -472,9 +472,10 @@ export class AgentHooks {
472
472
  this.terminalPrompts.delete(key);
473
473
  return;
474
474
  }
475
- // Codex draws "> 1. Yes, proceed (y)" rows; the other fallbacks number
476
- // rows without a key in the label.
477
- const dialog = target.source === "codex" ? visibleTerminalChoice(text) : numberedDialog(text);
475
+ // Codex draws "> 1. Yes, proceed (y)" rows and Copilot a boxed select
476
+ // with a cursor row, both answered by moving to a row; the other
477
+ // fallbacks number rows without a key in the label.
478
+ const dialog = ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text) : numberedDialog(text);
478
479
  if (entry && !entry.dialog) {
479
480
  // The permission the pane still shows after its hook let go: keep the
480
481
  // request's own details and answer it with the dialog's rows, so the
@@ -2,8 +2,11 @@ import { AgentHooks } from "./agent-hooks.js";
2
2
  import { ModelCatalog, type AgentModel } from "./models.js";
3
3
  import { type Json, type Target } from "./protocol.js";
4
4
  export declare const MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
5
+ export declare const SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
5
6
  /** Busy slash commands must never enter the harness's text queue. Claude's
6
- * `/btw` side question is the one made to run beside a working turn. */
7
+ * `/btw` side question is the one made to run beside a working turn. Only
8
+ * `/model` is told about the model switch; any other command (`/yolo`,
9
+ * `/compact`) is told it runs between turns. */
7
10
  export declare function refuseWorkingSlash(pane: Json, text: string, source?: string): void;
8
11
  /** The levels Claude Code's `/effort` takes (2.1.280) when the catalogue
9
12
  * lists none for a model; Claude still refuses one the model lacks. */
@@ -6,13 +6,17 @@ import { BridgeError } from "./protocol.js";
6
6
  import { sideQuestionText } from "./side-questions.js";
7
7
  import { stripTerminal } from "../terminal-text.js";
8
8
  export const MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
9
+ export const SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
9
10
  /** Busy slash commands must never enter the harness's text queue. Claude's
10
- * `/btw` side question is the one made to run beside a working turn. */
11
+ * `/btw` side question is the one made to run beside a working turn. Only
12
+ * `/model` is told about the model switch; any other command (`/yolo`,
13
+ * `/compact`) is told it runs between turns. */
11
14
  export function refuseWorkingSlash(pane, text, source) {
12
15
  if (source && sideQuestionText(source, text) !== undefined)
13
16
  return;
14
- if (pane.agent_status === "working" && /^\s*\//.test(text))
15
- throw new BridgeError(409, MODEL_BUSY);
17
+ if (pane.agent_status !== "working" || !/^\s*\//.test(text))
18
+ return;
19
+ throw new BridgeError(409, /^\s*\/model(?:\s|$)/.test(text) ? MODEL_BUSY : SLASH_BUSY);
16
20
  }
17
21
  const request = z.object({ model: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._\[\]:/-]{0,99}$/),
18
22
  effort: z.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]).optional() });
@@ -92,6 +92,7 @@ export declare const capabilities: {
92
92
  code: boolean;
93
93
  overviewStream: boolean;
94
94
  speech: boolean;
95
+ speechTimestamps: boolean;
95
96
  transcribe: boolean;
96
97
  memoryStore: boolean;
97
98
  };
@@ -51,7 +51,7 @@ async function childActivity(source, session) {
51
51
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
52
52
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
53
53
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
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 };
54
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, transcribe: true, memoryStore: true };
55
55
  export function capabilitiesForModules(snapshot) {
56
56
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
57
57
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -14,7 +14,15 @@ export declare const SPEECH_MODEL = "eleven_flash_v2_5";
14
14
  export declare const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
15
15
  export declare const speechRequest: z.ZodObject<{
16
16
  text: z.ZodString;
17
+ timestamps: z.ZodOptional<z.ZodBoolean>;
17
18
  }, z.core.$strip>;
19
+ /** When each character of the voiced text starts and ends, in seconds from
20
+ * the start of the audio. */
21
+ export interface SpeechAlignment {
22
+ characters: string[];
23
+ starts: number[];
24
+ ends: number[];
25
+ }
18
26
  export interface SpeechOptions {
19
27
  fetch?: typeof fetch;
20
28
  /** Resolves the ElevenLabs key; defaults to ELEVENLABS_API_KEY, then the stored key (speech-key.ts). */
@@ -32,7 +40,21 @@ export declare function speechError(upstream: Response): Promise<BridgeError>;
32
40
  export declare function speakableText(text: string): string;
33
41
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
34
42
  export declare function synthesizeSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<ReadableStream<Uint8Array>>;
43
+ /** Voices the text in one piece with ElevenLabs' character alignment. */
44
+ export declare function synthesizeTimedSpeech(text: string, signal: AbortSignal, options?: SpeechOptions): Promise<{
45
+ audio: string;
46
+ alignment: SpeechAlignment | null;
47
+ }>;
48
+ /** ElevenLabs' alignment, kept only when its three lists line up. */
49
+ export declare function alignmentOf(raw: {
50
+ characters?: unknown;
51
+ character_start_times_seconds?: unknown;
52
+ character_end_times_seconds?: unknown;
53
+ } | null | undefined): SpeechAlignment | null;
35
54
  /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
55
+ * With `timestamps`, answers JSON instead: `{ audio, audioFormat, alignment }`,
56
+ * the audio base64 in the same PCM format and the alignment null when
57
+ * ElevenLabs sent none.
36
58
  * Failures before the first byte are thrown for the route's JSON error; a
37
59
  * failure mid-stream cuts the response off, which the phone treats as an
38
60
  * error. The phone hanging up cancels the ElevenLabs request. */
@@ -15,7 +15,12 @@ export const SPEECH_MODEL = "eleven_flash_v2_5";
15
15
  /** River: relaxed, neutral and informative. PHREN_SPEECH_VOICE overrides it. */
16
16
  export const DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
17
17
  const MAX_TEXT = 2_000;
18
- export const speechRequest = z.object({ text: z.string().trim().min(1).max(MAX_TEXT) });
18
+ export const speechRequest = z.object({
19
+ text: z.string().trim().min(1).max(MAX_TEXT),
20
+ /** Answer JSON with the audio and when each character is spoken, so the
21
+ * phone can highlight the word being read (talk mode's karaoke). */
22
+ timestamps: z.boolean().optional(),
23
+ });
19
24
  /** A fixed message per ElevenLabs failure: its own response text is never
20
25
  * passed on. */
21
26
  export async function speechError(upstream) {
@@ -69,11 +74,42 @@ export function speakableText(text) {
69
74
  }
70
75
  /** Starts ElevenLabs' streaming synthesis and returns its audio body. */
71
76
  export async function synthesizeSpeech(text, signal, options = {}) {
77
+ const upstream = await elevenLabs("stream", text, signal, options);
78
+ if (!upstream.body)
79
+ throw await speechError(upstream);
80
+ return upstream.body;
81
+ }
82
+ /** Voices the text in one piece with ElevenLabs' character alignment. */
83
+ export async function synthesizeTimedSpeech(text, signal, options = {}) {
84
+ const upstream = await elevenLabs("with-timestamps", text, signal, options);
85
+ let body;
86
+ try {
87
+ body = (await upstream.json());
88
+ }
89
+ catch {
90
+ throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
91
+ }
92
+ if (typeof body.audio_base64 !== "string")
93
+ throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
94
+ return { audio: body.audio_base64, alignment: alignmentOf(body.alignment) };
95
+ }
96
+ /** ElevenLabs' alignment, kept only when its three lists line up. */
97
+ export function alignmentOf(raw) {
98
+ const characters = raw?.characters, starts = raw?.character_start_times_seconds, ends = raw?.character_end_times_seconds;
99
+ if (!Array.isArray(characters) || !Array.isArray(starts) || !Array.isArray(ends))
100
+ return null;
101
+ if (characters.length !== starts.length || characters.length !== ends.length)
102
+ return null;
103
+ if (!characters.every(c => typeof c === "string") || ![...starts, ...ends].every(t => typeof t === "number" && Number.isFinite(t)))
104
+ return null;
105
+ return { characters: characters, starts: starts, ends: ends };
106
+ }
107
+ async function elevenLabs(endpoint, text, signal, options) {
72
108
  const key = await (options.key ?? readSpeechKey)();
73
109
  if (!key)
74
110
  throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
75
111
  const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
76
- const url = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
112
+ const url = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/${endpoint}?output_format=${OUTPUT_FORMAT}`;
77
113
  let upstream;
78
114
  try {
79
115
  upstream = await (options.fetch ?? fetch)(url, {
@@ -85,21 +121,34 @@ export async function synthesizeSpeech(text, signal, options = {}) {
85
121
  catch {
86
122
  throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
87
123
  }
88
- if (!upstream.ok || !upstream.body)
124
+ if (!upstream.ok)
89
125
  throw await speechError(upstream);
90
- return upstream.body;
126
+ return upstream;
91
127
  }
92
128
  /** POST /v1/speech: writes the audio to the phone as ElevenLabs produces it.
129
+ * With `timestamps`, answers JSON instead: `{ audio, audioFormat, alignment }`,
130
+ * the audio base64 in the same PCM format and the alignment null when
131
+ * ElevenLabs sent none.
93
132
  * Failures before the first byte are thrown for the route's JSON error; a
94
133
  * failure mid-stream cuts the response off, which the phone treats as an
95
134
  * error. The phone hanging up cancels the ElevenLabs request. */
96
135
  export async function streamSpeech(data, response, options = {}) {
97
- const text = speakableText(speechRequest.parse(data).text);
136
+ const request = speechRequest.parse(data);
137
+ const text = speakableText(request.text);
98
138
  if (!text)
99
139
  throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
140
+ // With timestamps, the alignment covers these spoken words, not the markdown.
141
+ const { timestamps } = request;
100
142
  const abort = new AbortController();
101
143
  response.once("close", () => { if (!response.writableEnded)
102
144
  abort.abort(); });
145
+ if (timestamps) {
146
+ const { audio, alignment } = await synthesizeTimedSpeech(text, abort.signal, options);
147
+ response.statusCode = 200;
148
+ response.setHeader("Content-Type", "application/json");
149
+ response.end(JSON.stringify({ audio, audioFormat: SPEECH_AUDIO, alignment }));
150
+ return;
151
+ }
103
152
  const audio = await synthesizeSpeech(text, abort.signal, options);
104
153
  response.statusCode = 200;
105
154
  response.setHeader("Content-Type", "application/octet-stream");
@@ -15,11 +15,7 @@ export interface TerminalChoice {
15
15
  options: TerminalChoiceOption[];
16
16
  highlightedIndex?: number;
17
17
  }
18
- /** The question a pane's terminal lines are asking, in the same shape a held
19
- * permission request carries: every non-empty line above the first numbered
20
- * row (the "$ command" line included, the "Press enter" hint dropped), joined
21
- * with newlines, then one option per row. Keyless rows require exactly one
22
- * readable cursor so the Hook can navigate without confirming another row. */
18
+ export declare function unframed(text: string): string;
23
19
  export declare function visibleTerminalChoice(text: string): TerminalChoice | undefined;
24
20
  /** The pane's last non-empty line is a password read: sudo's "[sudo] password
25
21
  * for user", or any "… Password:" prompt. */
@@ -92,7 +92,35 @@ function numberedOptions(text) {
92
92
  * row (the "$ command" line included, the "Press enter" hint dropped), joined
93
93
  * with newlines, then one option per row. Keyless rows require exactly one
94
94
  * readable cursor so the Hook can navigate without confirming another row. */
95
+ /** Copilot CLI draws each select inside a box, so its rows read
96
+ * "│ ❯ 1. Yes │". Strip the frame (nested boxes too) so rows and the
97
+ * question read as bare lines. Inside a box the blank and border lines go,
98
+ * so the box's whole body (title, command, question) is one block above its
99
+ * options; the box's own edges become the blank lines around it. Text with
100
+ * no framed line passes through unchanged. */
101
+ const BAR = "│┃║";
102
+ const framed = new RegExp(`^\\s*[${BAR}] ?(.*?)\\s*[${BAR}]\\s*$`);
103
+ const border = /^[\s╭╮╰╯┌┐└┘├┤─━═│┃║]*$/;
104
+ export function unframed(text) {
105
+ let lines = text.split(/\r?\n/);
106
+ // Copilot's scrollbar: a "┃" closing most lines once the chat overflows.
107
+ const filled = lines.filter(line => line.trim());
108
+ if (filled.length && filled.filter(line => /┃\s*$/.test(line)).length * 2 > filled.length) {
109
+ lines = lines.map(line => line.replace(/\s*┃\s*$/, ""));
110
+ }
111
+ if (!lines.some(line => framed.test(line)))
112
+ return lines.join("\n");
113
+ return lines.flatMap(line => {
114
+ if (!framed.test(line))
115
+ return [border.test(line) ? "" : line];
116
+ let inner = line, match;
117
+ while ((match = framed.exec(inner)))
118
+ inner = match[1];
119
+ return border.test(inner) ? [] : [inner];
120
+ }).join("\n");
121
+ }
95
122
  export function visibleTerminalChoice(text) {
123
+ text = unframed(text);
96
124
  const parsed = numberedOptions(text);
97
125
  const highlights = parsed.flatMap((option, index) => option.highlighted ? [index] : []);
98
126
  const highlightedIndex = highlights.length === 1 ? highlights[0] : undefined;
@@ -136,6 +164,7 @@ export function passwordLine(text) {
136
164
  * " · ", and a footer offering "Esc to cancel" gains the Escape option.
137
165
  * Undefined without two numbered rows and a question. */
138
166
  export function numberedDialog(text) {
167
+ text = unframed(text);
139
168
  const row = /^\s*[>❯›▸▶»•*]?\s*(\d+)\.\s+(.+?)\s*$/;
140
169
  const lines = text.split(/\r?\n/);
141
170
  const first = lines.findIndex(line => row.test(line));
@@ -47,6 +47,11 @@ export declare function parseClaudeSpinnerLine(line: string): ClaudeSpinner | un
47
47
  export declare function claudeSpinner(rendered: string): ClaudeSpinner | undefined;
48
48
  /** The word Claude's own spinner shows ("✻ Pondering… (12s · esc to interrupt)"). */
49
49
  export declare function claudeSpinnerVerb(rendered: string): string | undefined;
50
+ /** Copilot's reasoning state for the running turn, from the headers it draws
51
+ * above each reasoning block ("⌄ Thought for 16s", "Thinking" while it
52
+ * streams), newest below the turn's prompt line. Only the header is read:
53
+ * the reasoning under it ("│ …") never leaves the Hook. */
54
+ export declare function copilotThinking(rendered: string): ClaudeSpinner | undefined;
50
55
  export declare function readPreviewPane(target: Target): Promise<string>;
51
56
  /**
52
57
  * One pane line as Markdown bold. Claude draws a reply's **bold** with SGR 1
@@ -223,6 +223,28 @@ export function claudeSpinner(rendered) {
223
223
  export function claudeSpinnerVerb(rendered) {
224
224
  return claudeSpinner(rendered)?.verb;
225
225
  }
226
+ /** Copilot's reasoning state for the running turn, from the headers it draws
227
+ * above each reasoning block ("⌄ Thought for 16s", "Thinking" while it
228
+ * streams), newest below the turn's prompt line. Only the header is read:
229
+ * the reasoning under it ("│ …") never leaves the Hook. */
230
+ export function copilotThinking(rendered) {
231
+ // Copilot draws a scrollbar down the right edge once the chat overflows.
232
+ const lines = stripTerminal(rendered).split("\n").map(line => line.replace(/\s*┃\s*$/, ""));
233
+ let from = 0;
234
+ lines.forEach((line, index) => { if (/^\s*❯\s+(?!\d+[.)]\s)\S/.test(line))
235
+ from = index + 1; });
236
+ for (let i = lines.length - 1; i >= from; i--) {
237
+ const header = /^\s*[⌄⌃▾▸›>]?\s*(?:(Thinking)\b.*|Thought for (\S+))\s*$/.exec(lines[i]);
238
+ if (!header)
239
+ continue;
240
+ if (header[1])
241
+ return { verb: "Working", thinking: true };
242
+ const seconds = spinnerSeconds(header[2]);
243
+ if (seconds !== undefined)
244
+ return { verb: "Working", thinking: false, thoughtFor: seconds };
245
+ }
246
+ return undefined;
247
+ }
226
248
  export function readPreviewPane(target) {
227
249
  // With its styles: Claude's bold becomes Markdown; everything else strips.
228
250
  return readPaneText(target.server, target.pane, { method: "agent.read", source: "visible", lines: 80, stripAnsi: false, format: "ansi", timeoutMs: 2_000, what: "Preview pane read" });
@@ -410,6 +432,23 @@ export class TranscriptPreviewStream {
410
432
  this.ended = true;
411
433
  continue;
412
434
  }
435
+ if (this.target.source === "copilot") {
436
+ // A prompt starts the turn; idle or abort ends it (Copilot writes a
437
+ // turn_start/turn_end pair per model call, not per prompt).
438
+ if (raw.type === "user.message" && typeof raw.timestamp === "string") {
439
+ this.startedAt = raw.timestamp;
440
+ this.ended = false;
441
+ this.wasWorking = false;
442
+ this.verb = undefined;
443
+ this.activity = undefined;
444
+ }
445
+ else if (["session.idle", "abort"].includes(String(raw.type))) {
446
+ this.ended = true;
447
+ this.verb = undefined;
448
+ this.activity = undefined;
449
+ }
450
+ continue;
451
+ }
413
452
  if (this.target.source !== "claude")
414
453
  continue;
415
454
  const message = object(raw.message), blocks = objects(message.content);
@@ -465,8 +504,19 @@ export class TranscriptPreviewStream {
465
504
  if (text)
466
505
  next = { turnStartedAt: this.startedAt, text };
467
506
  }
507
+ else if (this.target.source === "copilot" && this.startedAt && !this.ended) {
508
+ // No reply text from the pane: only whether Copilot is thinking.
509
+ if (readAt - this.lastRead < PREVIEW_INTERVAL_MS)
510
+ return undefined;
511
+ this.lastRead = readAt;
512
+ const thinking = copilotThinking(await this.pane());
513
+ if (thinking) {
514
+ this.activity = thinking;
515
+ this.verb = thinking.verb;
516
+ }
517
+ }
468
518
  }
469
- else if (this.target.source === "claude" && this.wasWorking) {
519
+ else if (["claude", "copilot"].includes(this.target.source) && this.wasWorking) {
470
520
  this.landed = true;
471
521
  this.ended = true;
472
522
  this.verb = undefined;
@@ -28275,7 +28275,7 @@ var init_package_metadata = __esm({
28275
28275
  __dirname = path24.dirname(fileURLToPath2(import.meta.url));
28276
28276
  ROOT = path24.join(__dirname, "..");
28277
28277
  PACKAGE_JSON_PATH = path24.join(ROOT, "package.json");
28278
- BUNDLED_VERSION = true ? "0.3.2" : "0.0.0";
28278
+ BUNDLED_VERSION = true ? "0.3.4" : "0.0.0";
28279
28279
  PACKAGE_JSON = readPackageJson();
28280
28280
  PACKAGE_NAME = PACKAGE_JSON.name || "phren";
28281
28281
  VERSION = PACKAGE_JSON.version || BUNDLED_VERSION;
@@ -33310,6 +33310,7 @@ var BUILTIN_MODULES = [
33310
33310
  "simulators",
33311
33311
  "overviewStream",
33312
33312
  "speech",
33313
+ "speechTimestamps",
33313
33314
  "transcribe"
33314
33315
  ],
33315
33316
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
@@ -35026,7 +35027,25 @@ function numberedOptions(text3) {
35026
35027
  }] : [];
35027
35028
  });
35028
35029
  }
35030
+ var BAR = "\u2502\u2503\u2551";
35031
+ var framed = new RegExp(`^\\s*[${BAR}] ?(.*?)\\s*[${BAR}]\\s*$`);
35032
+ var border = /^[\s╭╮╰╯┌┐└┘├┤─━═│┃║]*$/;
35033
+ function unframed(text3) {
35034
+ let lines = text3.split(/\r?\n/);
35035
+ const filled = lines.filter((line) => line.trim());
35036
+ if (filled.length && filled.filter((line) => /┃\s*$/.test(line)).length * 2 > filled.length) {
35037
+ lines = lines.map((line) => line.replace(/\s*┃\s*$/, ""));
35038
+ }
35039
+ if (!lines.some((line) => framed.test(line))) return lines.join("\n");
35040
+ return lines.flatMap((line) => {
35041
+ if (!framed.test(line)) return [border.test(line) ? "" : line];
35042
+ let inner = line, match;
35043
+ while (match = framed.exec(inner)) inner = match[1];
35044
+ return border.test(inner) ? [] : [inner];
35045
+ }).join("\n");
35046
+ }
35029
35047
  function visibleTerminalChoice(text3) {
35048
+ text3 = unframed(text3);
35030
35049
  const parsed = numberedOptions(text3);
35031
35050
  const highlights = parsed.flatMap((option, index2) => option.highlighted ? [index2] : []);
35032
35051
  const highlightedIndex = highlights.length === 1 ? highlights[0] : void 0;
@@ -35055,6 +35074,7 @@ function passwordLine(text3) {
35055
35074
  return /password[^\n]*:\s*$/i.test(last);
35056
35075
  }
35057
35076
  function numberedDialog(text3) {
35077
+ text3 = unframed(text3);
35058
35078
  const row = /^\s*[>❯›▸▶»•*]?\s*(\d+)\.\s+(.+?)\s*$/;
35059
35079
  const lines = text3.split(/\r?\n/);
35060
35080
  const first = lines.findIndex((line) => row.test(line));
@@ -35583,7 +35603,7 @@ var AgentHooks = class {
35583
35603
  this.terminalPrompts.delete(key);
35584
35604
  return;
35585
35605
  }
35586
- const dialog = target.source === "codex" ? visibleTerminalChoice(text3) : numberedDialog(text3);
35606
+ const dialog = ["codex", "copilot"].includes(target.source) ? visibleTerminalChoice(text3) : numberedDialog(text3);
35587
35607
  if (entry && !entry.dialog) {
35588
35608
  if (dialog?.title) {
35589
35609
  entry.choice = dialog;
@@ -40469,9 +40489,11 @@ var SideQuestions = class {
40469
40489
 
40470
40490
  // src/bridge/model-switch.ts
40471
40491
  var MODEL_BUSY = "This agent is working. The model switch can happen when the turn ends. Choose Switch after this turn.";
40492
+ var SLASH_BUSY = "This agent is working. Slash commands run between turns; send it again when this turn ends.";
40472
40493
  function refuseWorkingSlash(pane, text3, source) {
40473
40494
  if (source && sideQuestionText(source, text3) !== void 0) return;
40474
- if (pane.agent_status === "working" && /^\s*\//.test(text3)) throw new BridgeError(409, MODEL_BUSY);
40495
+ if (pane.agent_status !== "working" || !/^\s*\//.test(text3)) return;
40496
+ throw new BridgeError(409, /^\s*\/model(?:\s|$)/.test(text3) ? MODEL_BUSY : SLASH_BUSY);
40475
40497
  }
40476
40498
  var request5 = external_exports.object({
40477
40499
  model: external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._\[\]:/-]{0,99}$/),
@@ -47253,7 +47275,12 @@ var OUTPUT_FORMAT = "pcm_24000";
47253
47275
  var SPEECH_MODEL = "eleven_flash_v2_5";
47254
47276
  var DEFAULT_SPEECH_VOICE = "SAz9YHcvj6GT2YYXdXww";
47255
47277
  var MAX_TEXT = 2e3;
47256
- var speechRequest = external_exports.object({ text: external_exports.string().trim().min(1).max(MAX_TEXT) });
47278
+ var speechRequest = external_exports.object({
47279
+ text: external_exports.string().trim().min(1).max(MAX_TEXT),
47280
+ /** Answer JSON with the audio and when each character is spoken, so the
47281
+ * phone can highlight the word being read (talk mode's karaoke). */
47282
+ timestamps: external_exports.boolean().optional()
47283
+ });
47257
47284
  async function speechError(upstream) {
47258
47285
  let detail = "";
47259
47286
  try {
@@ -47284,10 +47311,33 @@ function speakableText(text3) {
47284
47311
  }).filter(Boolean).join(" ").replace(/\s+/g, " ").trim();
47285
47312
  }
47286
47313
  async function synthesizeSpeech(text3, signal, options = {}) {
47314
+ const upstream = await elevenLabs("stream", text3, signal, options);
47315
+ if (!upstream.body) throw await speechError(upstream);
47316
+ return upstream.body;
47317
+ }
47318
+ async function synthesizeTimedSpeech(text3, signal, options = {}) {
47319
+ const upstream = await elevenLabs("with-timestamps", text3, signal, options);
47320
+ let body2;
47321
+ try {
47322
+ body2 = await upstream.json();
47323
+ } catch {
47324
+ throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
47325
+ }
47326
+ if (typeof body2.audio_base64 !== "string") throw new BridgeError(502, "ElevenLabs sent an unreadable reply.", { code: "speech-failed" });
47327
+ return { audio: body2.audio_base64, alignment: alignmentOf(body2.alignment) };
47328
+ }
47329
+ function alignmentOf(raw) {
47330
+ const characters = raw?.characters, starts = raw?.character_start_times_seconds, ends = raw?.character_end_times_seconds;
47331
+ if (!Array.isArray(characters) || !Array.isArray(starts) || !Array.isArray(ends)) return null;
47332
+ if (characters.length !== starts.length || characters.length !== ends.length) return null;
47333
+ if (!characters.every((c) => typeof c === "string") || ![...starts, ...ends].every((t) => typeof t === "number" && Number.isFinite(t))) return null;
47334
+ return { characters, starts, ends };
47335
+ }
47336
+ async function elevenLabs(endpoint, text3, signal, options) {
47287
47337
  const key = await (options.key ?? readSpeechKey)();
47288
47338
  if (!key) throw new BridgeError(503, "Spoken replies aren't set up on this computer: it has no ElevenLabs key.", { code: "speech-unconfigured" });
47289
47339
  const voice = options.voice ?? process.env.PHREN_SPEECH_VOICE ?? DEFAULT_SPEECH_VOICE;
47290
- const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/stream?output_format=${OUTPUT_FORMAT}`;
47340
+ const url2 = `https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice)}/${endpoint}?output_format=${OUTPUT_FORMAT}`;
47291
47341
  let upstream;
47292
47342
  try {
47293
47343
  upstream = await (options.fetch ?? fetch)(url2, {
@@ -47299,16 +47349,25 @@ async function synthesizeSpeech(text3, signal, options = {}) {
47299
47349
  } catch {
47300
47350
  throw new BridgeError(502, "Couldn't reach ElevenLabs from this computer.", { code: "speech-unreachable" });
47301
47351
  }
47302
- if (!upstream.ok || !upstream.body) throw await speechError(upstream);
47303
- return upstream.body;
47352
+ if (!upstream.ok) throw await speechError(upstream);
47353
+ return upstream;
47304
47354
  }
47305
47355
  async function streamSpeech(data, response, options = {}) {
47306
- const text3 = speakableText(speechRequest.parse(data).text);
47356
+ const request6 = speechRequest.parse(data);
47357
+ const text3 = speakableText(request6.text);
47307
47358
  if (!text3) throw new BridgeError(400, "There is nothing to say in this reply.", { code: "speech-invalid" });
47359
+ const { timestamps } = request6;
47308
47360
  const abort = new AbortController();
47309
47361
  response.once("close", () => {
47310
47362
  if (!response.writableEnded) abort.abort();
47311
47363
  });
47364
+ if (timestamps) {
47365
+ const { audio: audio2, alignment } = await synthesizeTimedSpeech(text3, abort.signal, options);
47366
+ response.statusCode = 200;
47367
+ response.setHeader("Content-Type", "application/json");
47368
+ response.end(JSON.stringify({ audio: audio2, audioFormat: SPEECH_AUDIO, alignment }));
47369
+ return;
47370
+ }
47312
47371
  const audio = await synthesizeSpeech(text3, abort.signal, options);
47313
47372
  response.statusCode = 200;
47314
47373
  response.setHeader("Content-Type", "application/octet-stream");
@@ -47367,6 +47426,7 @@ var capabilities = {
47367
47426
  code: true,
47368
47427
  overviewStream: true,
47369
47428
  speech: true,
47429
+ speechTimestamps: true,
47370
47430
  transcribe: true,
47371
47431
  memoryStore: true
47372
47432
  };
@@ -47999,6 +48059,21 @@ function claudeSpinner(rendered) {
47999
48059
  }
48000
48060
  return void 0;
48001
48061
  }
48062
+ function copilotThinking(rendered) {
48063
+ const lines = stripTerminal(rendered).split("\n").map((line) => line.replace(/\s*┃\s*$/, ""));
48064
+ let from = 0;
48065
+ lines.forEach((line, index2) => {
48066
+ if (/^\s*❯\s+(?!\d+[.)]\s)\S/.test(line)) from = index2 + 1;
48067
+ });
48068
+ for (let i = lines.length - 1; i >= from; i--) {
48069
+ const header2 = /^\s*[⌄⌃▾▸›>]?\s*(?:(Thinking)\b.*|Thought for (\S+))\s*$/.exec(lines[i]);
48070
+ if (!header2) continue;
48071
+ if (header2[1]) return { verb: "Working", thinking: true };
48072
+ const seconds = spinnerSeconds(header2[2]);
48073
+ if (seconds !== void 0) return { verb: "Working", thinking: false, thoughtFor: seconds };
48074
+ }
48075
+ return void 0;
48076
+ }
48002
48077
  function readPreviewPane(target) {
48003
48078
  return readPaneText(
48004
48079
  target.server,
@@ -48147,6 +48222,20 @@ var TranscriptPreviewStream = class {
48147
48222
  else if (raw.type === "event_msg" && ["task_complete", "task_completed", "turn_aborted", "task_aborted"].includes(String(payload.type))) this.ended = true;
48148
48223
  continue;
48149
48224
  }
48225
+ if (this.target.source === "copilot") {
48226
+ if (raw.type === "user.message" && typeof raw.timestamp === "string") {
48227
+ this.startedAt = raw.timestamp;
48228
+ this.ended = false;
48229
+ this.wasWorking = false;
48230
+ this.verb = void 0;
48231
+ this.activity = void 0;
48232
+ } else if (["session.idle", "abort"].includes(String(raw.type))) {
48233
+ this.ended = true;
48234
+ this.verb = void 0;
48235
+ this.activity = void 0;
48236
+ }
48237
+ continue;
48238
+ }
48150
48239
  if (this.target.source !== "claude") continue;
48151
48240
  const message = object2(raw.message), blocks = objects(message.content);
48152
48241
  if (raw.type === "user" && !raw.phrenQueued && !raw.isMeta && !blocks.some((b) => b.type === "tool_result")) {
@@ -48190,8 +48279,16 @@ var TranscriptPreviewStream = class {
48190
48279
  this.verb = spinner.verb;
48191
48280
  }
48192
48281
  if (text3) next = { turnStartedAt: this.startedAt, text: text3 };
48282
+ } else if (this.target.source === "copilot" && this.startedAt && !this.ended) {
48283
+ if (readAt - this.lastRead < PREVIEW_INTERVAL_MS) return void 0;
48284
+ this.lastRead = readAt;
48285
+ const thinking = copilotThinking(await this.pane());
48286
+ if (thinking) {
48287
+ this.activity = thinking;
48288
+ this.verb = thinking.verb;
48289
+ }
48193
48290
  }
48194
- } else if (this.target.source === "claude" && this.wasWorking) {
48291
+ } else if (["claude", "copilot"].includes(this.target.source) && this.wasWorking) {
48195
48292
  this.landed = true;
48196
48293
  this.ended = true;
48197
48294
  this.verb = void 0;
@@ -49015,7 +49112,7 @@ async function readSecret(prompt) {
49015
49112
  // src/bridge/hook-main.ts
49016
49113
  init_utils_helpers();
49017
49114
  Object.assign(process.env, nonInteractiveGitEnv());
49018
- runBridge(process.argv.slice(2), "0.3.2").then((code) => {
49115
+ runBridge(process.argv.slice(2), "0.3.4").then((code) => {
49019
49116
  process.exitCode = code;
49020
49117
  }).catch((error62) => {
49021
49118
  console.error(error62 instanceof Error ? error62.message : "Phren Hook failed.");
@@ -6,16 +6,67 @@ import { getPhrenPath } from "../shared.js";
6
6
  import { isValidProjectName, errorMessage, getOptionValue } from "../utils.js";
7
7
  import { resolveAllStores, addStoreToRegistry, removeStoreFromRegistry, generateStoreId, getStoreProjectDirs, readTeamBootstrap, } from "../store-registry.js";
8
8
  import { mergeStoreUpstream } from "../sync/store-merge.js";
9
+ import { aheadBehind, logSyncOutcome } from "../sync/outcome.js";
10
+ import { getRuntimeHealth, updateRuntimeHealth } from "../shared/governance.js";
9
11
  function printStoreUsage() {
10
12
  console.log("Usage:");
11
13
  console.log(" phren store list List registered stores");
12
14
  console.log(" phren store add <name> --remote <url> Add a team store");
13
15
  console.log(" phren store remove <name> Remove a store (local only)");
14
- console.log(" phren store sync Pull all stores");
16
+ console.log(" phren store sync Pull and push all stores");
15
17
  console.log(" phren store activity [--limit N] Recent team findings");
16
18
  console.log(" phren store subscribe <name> <project...> Subscribe store to projects");
17
19
  console.log(" phren store unsubscribe <name> <project...> Unsubscribe store from projects");
18
20
  }
21
+ /**
22
+ * Push what a sync left ahead of the upstream: the merge commit and any local
23
+ * commits. Without this a merge that resolved conflicts stayed local, and the
24
+ * store sat N commits ahead until someone ran `git push` by hand.
25
+ */
26
+ async function pushStoreUpstream(store, git) {
27
+ if (store.sync === "pull-only" || store.role === "readonly")
28
+ return { status: "skipped", detail: "pull-only store" };
29
+ const counts = await aheadBehind(store.path, git);
30
+ if (!counts)
31
+ return { status: "skipped", detail: "no tracking remote" };
32
+ if (counts.ahead === 0)
33
+ return { status: "in-sync", detail: "nothing to push" };
34
+ const branch = await git(store.path, ["symbolic-ref", "--quiet", "HEAD"]);
35
+ const refs = branch.ok
36
+ ? await git(store.path, ["for-each-ref", "--format=%(upstream:remotename)%09%(upstream:remoteref)", branch.output])
37
+ : branch;
38
+ const [remote, remoteRef] = refs.ok ? refs.output.split("\t") : [];
39
+ if (!remote || !remoteRef)
40
+ return { status: "failed", detail: "cannot read the upstream branch" };
41
+ const pushed = await git(store.path, ["push", "--quiet", "--", remote, `HEAD:${remoteRef}`]);
42
+ if (!pushed.ok)
43
+ return { status: "failed", detail: `push failed: ${(pushed.error || "unknown Git error").split("\n")[0]}` };
44
+ return { status: "pushed", detail: `pushed ${counts.ahead} commit${counts.ahead === 1 ? "" : "s"}` };
45
+ }
46
+ /** Record a sync's push on the primary store, so doctor's runtime-auto-save check reflects it. */
47
+ async function recordPrimaryPush(phrenPath, push, git) {
48
+ if (push.status === "skipped")
49
+ return;
50
+ const now = new Date().toISOString();
51
+ const previous = getRuntimeHealth(phrenPath).lastSync;
52
+ const counts = await aheadBehind(phrenPath, git);
53
+ const detail = `store sync: ${push.detail}`;
54
+ const failed = push.status === "failed";
55
+ updateRuntimeHealth(phrenPath, {
56
+ lastAutoSave: { at: now, status: failed ? "sync-failed" : "saved-pushed", detail },
57
+ lastSync: {
58
+ ...previous,
59
+ lastPushAt: now,
60
+ lastPushStatus: failed ? "push-failed" : "saved-pushed",
61
+ lastPushDetail: detail,
62
+ unsyncedCommits: counts?.ahead ?? previous?.unsyncedCommits,
63
+ consecutiveFailures: failed ? (previous?.consecutiveFailures ?? 0) + 1 : 0,
64
+ ...(failed ? {} : { lastSuccessfulPushAt: now }),
65
+ ...(counts ?? {}),
66
+ },
67
+ });
68
+ logSyncOutcome(phrenPath, "store-sync", { ok: !failed, detail: push.detail, counts });
69
+ }
19
70
  function countStoreProjects(store) {
20
71
  if (!fs.existsSync(store.path))
21
72
  return 0;
@@ -279,7 +330,16 @@ export async function handleStoreNamespace(args) {
279
330
  // sparse-checkout not configured — nothing to reapply
280
331
  }
281
332
  }
282
- console.log(` ${store.name}: ok (${result.detail})`);
333
+ const push = await pushStoreUpstream(store, git);
334
+ if (store.role === "primary")
335
+ await recordPrimaryPush(store.path, push, git);
336
+ if (push.status === "failed") {
337
+ console.log(` ${store.name}: PUSH FAILED (${result.detail} ${push.detail}; the store is still ahead of the remote)`);
338
+ hasErrors = true;
339
+ }
340
+ else {
341
+ console.log(` ${store.name}: ok (${result.detail}${push.status === "pushed" ? ` Then ${push.detail}.` : ""})`);
342
+ }
283
343
  if (store.role === "primary")
284
344
  primarySynced = true;
285
345
  }
@@ -121,7 +121,7 @@ const STORE_SUBCOMMANDS = [
121
121
  { name: "list", usage: "phren store list", summary: "List registered stores" },
122
122
  { name: "add", usage: "phren store add <name> --remote <url>", summary: "Add a team store" },
123
123
  { name: "remove", usage: "phren store remove <name>", summary: "Remove a store (local only)" },
124
- { name: "sync", usage: "phren store sync", summary: "Pull all stores" },
124
+ { name: "sync", usage: "phren store sync", summary: "Pull and push all stores" },
125
125
  ];
126
126
  const TEAM_SUBCOMMANDS = [
127
127
  { name: "init", usage: "phren team init <name> [--remote <url>]", summary: "Create a new team store" },
@@ -96,7 +96,7 @@ export const BUILTIN_MODULES = [
96
96
  capabilities: [
97
97
  "hook", "transcript", "progress", "images", "prompt", "stop", "terminal", "shell", "herdr",
98
98
  "webServers", "webPreview", "activity", "approvals", "questions", "accountUsage", "providers",
99
- "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "transcribe",
99
+ "files", "repositoryFiles", "subagents", "sideQuestions", "approvalPush", "simulators", "overviewStream", "speech", "speechTimestamps", "transcribe",
100
100
  ],
101
101
  storeFiles: [".runtime/sessions/opencode-*.events.jsonl", ".runtime/approvals/opencode-*.json"],
102
102
  localFiles: ["<bridge>/installed.json", "<bridge>/versions/**", "<bridge>/current", "<bridge>/dispatch", "<bridge>/computer-id", "<bridge>/canary.json", "<bridge>/canary-daily"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@phren/cli",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "Knowledge layer for AI agents - CLI, MCP server, and data layer",
5
5
  "type": "module",
6
6
  "bin": {