@phren/cli 0.3.73 → 0.3.74

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.
@@ -13,6 +13,7 @@ interface Row {
13
13
  checked?: boolean;
14
14
  answered: boolean;
15
15
  cursor: boolean;
16
+ wrapped?: boolean;
16
17
  }
17
18
  export interface ClaudeQuestionScreen {
18
19
  kind: "question";
@@ -32,15 +33,13 @@ export interface ClaudeReviewScreen {
32
33
  answers: {
33
34
  question: string;
34
35
  answer: string;
36
+ wrapped?: boolean;
35
37
  }[];
36
38
  }
37
39
  export type ClaudeDialogScreen = ClaudeQuestionScreen | ClaudeReviewScreen;
38
40
  /** Claude cuts a question at 2000 characters with "…" while the phone may send
39
41
  * more, so the pane's title matches when it is the question's own head. */
40
42
  export declare const sameTitle: (shown: string, asked: string) => boolean;
41
- /** Claude collapses runs of whitespace in a label, and the Hook reads only the
42
- * first line of one it wraps, so a long label matches by its head. */
43
- export declare const sameLabel: (shown: string, asked: string) => boolean;
44
43
  /** The question dialog the pane is drawing now, or undefined when the last
45
44
  * lines are not one: the last tab bar anchors it, and an active dialog ends
46
45
  * with its "Esc to cancel" footer or the review's Submit/Cancel rows. */
@@ -1,3 +1,5 @@
1
+ import { claudeFooterMode } from "./claude-footer-mode.js";
2
+ import { dialogHasClosed } from "./dialog-observation.js";
1
3
  import { joinDialogFooters } from "./terminal-dialog-text.js";
2
4
  import { BridgeError } from "./protocol.js";
3
5
  const TAB_BAR = /^\s*(?:←\s+)?((?:[☐☒]\s+\S[^☐☒✔→]*?\s*)+)(?:✔\s+Submit\s*)?(?:→\s*)?$/;
@@ -12,12 +14,6 @@ export const sameTitle = (shown, asked) => {
12
14
  return true;
13
15
  return shown.endsWith("…") && shown.length > 200 && want.startsWith(shown.slice(0, -1).trimEnd());
14
16
  };
15
- /** Claude collapses runs of whitespace in a label, and the Hook reads only the
16
- * first line of one it wraps, so a long label matches by its head. */
17
- export const sameLabel = (shown, asked) => {
18
- const want = normalize(asked);
19
- return shown === want || (shown.length >= 30 && want.startsWith(shown));
20
- };
21
17
  /** Claude Code (2.1.284) draws a question that has a line break or is wider
22
18
  * than 80 columns inside a dimmed left border, "│ " before each line, on its
23
19
  * tab and in the review. The border is not part of the question. */
@@ -84,8 +80,10 @@ export function claudeQuestionDialog(text) {
84
80
  last.answer = answer[1];
85
81
  // A long question or answer wraps onto the next line.
86
82
  else if (last) {
87
- if (last.answer)
83
+ if (last.answer) {
88
84
  last.answer += " " + line;
85
+ last.wrapped = true;
86
+ }
89
87
  else
90
88
  last.question += " " + line;
91
89
  }
@@ -118,7 +116,7 @@ export function claudeQuestionDialog(text) {
118
116
  continue;
119
117
  }
120
118
  const answered = !match[3] && / ✔$/.test(match[4]);
121
- rows.push({ number, label: answered ? match[4].slice(0, -2).trim() : match[4], answered, cursor: !!match[1],
119
+ rows.push({ number, label: match[4], answered, cursor: !!match[1],
122
120
  ...(match[3] ? { checked: match[3] === "✔" } : {}) });
123
121
  }
124
122
  if (!title || !chat || cursor === undefined || rows.length < 2)
@@ -126,6 +124,18 @@ export function claudeQuestionDialog(text) {
126
124
  // The last row above "Chat about this" is the typed answer ("Type
127
125
  // something." until something is typed there).
128
126
  const other = rows.pop();
127
+ // Only option labels have a removable selection marker. Other is user
128
+ // input: preserving its raw value prevents "Teal ✔" reconciling as "Teal".
129
+ for (const row of rows)
130
+ if (row.answered)
131
+ row.label = row.label.slice(0, -2).trim();
132
+ const otherLine = body.findIndex(line => Number(ROW.exec(line)?.[2]) === other.number);
133
+ for (const line of body.slice(otherLine + 1)) {
134
+ if (NEXT.test(line) || ROW.test(line) || /^─+$/.test(line.trim()))
135
+ break;
136
+ if (line.trim())
137
+ other.wrapped = true;
138
+ }
129
139
  return { kind: "question", tabs, title, multiSelect: rows.some(row => row.checked !== undefined), options: rows, other, ...(cursor !== undefined ? { cursor } : {}) };
130
140
  }
131
141
  /** A 409 that says whether any key reached the terminal: `question-not-shown`
@@ -142,6 +152,9 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
142
152
  const from = options.from ?? 0, submit = options.submit ?? true;
143
153
  let sent = false;
144
154
  const changed = (message) => refusal(message, sent);
155
+ if (submit && (from !== 0 || answers.length !== questions.length)) {
156
+ throw changed("Cannot verify the full review from a partial answer set; send all answers together or finish in the terminal.");
157
+ }
145
158
  const realKeys = io.keys.bind(io);
146
159
  io = { ...io, keys: async (keys) => { sent = true; await realKeys(keys); } };
147
160
  const sleep = io.sleep ?? ((ms) => new Promise(resolve => setTimeout(resolve, ms)));
@@ -149,7 +162,12 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
149
162
  // Claude redraws a moment after a key; poll until the expected screen shows.
150
163
  const settle = async (check, ms = 2_000) => {
151
164
  for (let waited = 0;; waited += 120) {
152
- const value = check(claudeQuestionDialog(await io.read()));
165
+ const text = await io.read(), screen = claudeQuestionDialog(text);
166
+ // A bare cursor can itself be a partial question redraw. Closure must
167
+ // also have Claude's live footer or working hint, after the dialog cues.
168
+ const closed = !screen && dialogHasClosed(text)
169
+ && (claudeFooterMode(text) !== undefined || /\besc to interrupt\b/i.test(text));
170
+ const value = check(screen, closed);
153
171
  if (value !== undefined || waited >= ms)
154
172
  return value;
155
173
  await sleep(120);
@@ -166,6 +184,70 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
166
184
  // draws its own header. The tabs must be this set's, in this order.
167
185
  if (initial.tabs.length !== questions.length)
168
186
  throw changed("The terminal is asking a different set of questions.");
187
+ const moveCursor = async (index, screen, to) => {
188
+ const position = (value) => value === "next" ? screen.other.number + 1 : value;
189
+ while (screen.cursor !== to) {
190
+ const at = position(screen.cursor), target = position(to);
191
+ if (at === undefined || target === undefined)
192
+ throw changed("Could not locate the terminal cursor.");
193
+ const next = at + (target > at ? 1 : -1);
194
+ const expected = next === screen.other.number + 1 ? "next" : next;
195
+ await io.keys([target > at ? "down" : "up"]);
196
+ const moved = await settle(value => matches(value, index) && value.cursor === expected ? value : undefined);
197
+ if (!moved)
198
+ throw changed("Could not move and verify the terminal cursor.");
199
+ screen = moved;
200
+ }
201
+ return screen;
202
+ };
203
+ const commandCursor = async (index, screen) => {
204
+ if (screen.other && screen.cursor === screen.other.number)
205
+ screen = await moveCursor(index, screen, screen.other.number - 1);
206
+ if (!screen.options.some(row => row.number === screen.cursor) && !(screen.multiSelect && screen.cursor === "next")) {
207
+ throw changed("The terminal cursor is not on an option or Next row.");
208
+ }
209
+ return screen;
210
+ };
211
+ const enterText = async (index, screen, text) => {
212
+ screen = await moveCursor(index, screen, screen.other.number);
213
+ const existing = screen.other.label;
214
+ if (screen.other.answered)
215
+ throw changed("The existing typed answer ends with an ambiguous selection marker; edit it in the terminal.");
216
+ if (screen.other.wrapped)
217
+ throw changed("The existing typed answer is wrapped and cannot be verified; edit it in the terminal.");
218
+ const placeholder = existing === (screen.multiSelect ? "Type something" : "Type something.");
219
+ // The terminal capture cannot prove an editor shortcut cleared a field,
220
+ // or distinguish a literal placeholder answer from an empty field. Refuse
221
+ // those cases rather than append to a draft or submit an empty answer.
222
+ if ((placeholder && text === existing) || (!placeholder && existing !== text)) {
223
+ throw changed("The existing typed answer differs from the phone's answer or cannot be verified; clear it in the terminal first.");
224
+ }
225
+ const verifyText = async (expected) => {
226
+ const shown = await settle(value => matches(value, index) && value.cursor === screen.other.number
227
+ && !value.other?.wrapped && value.other?.label === expected && (!screen.multiSelect || value.other.checked) ? value : undefined);
228
+ if (!shown)
229
+ throw changed("The full typed answer did not appear exactly in the terminal.");
230
+ return shown;
231
+ };
232
+ if (placeholder) {
233
+ if (/^[0-9]/.test(text)) {
234
+ // Current Claude versions type digits into Other. Older versions may
235
+ // select (and immediately submit) an option if the field is empty,
236
+ // so establish text ownership without ever probing it with a digit.
237
+ await io.keys(["."]);
238
+ await verifyText(".");
239
+ await io.keys(typedKeys(text));
240
+ await verifyText("." + text);
241
+ // These editor keys cannot submit. If movement/deletion is unsupported
242
+ // or dropped, exact readback refuses before Enter can send the prefix.
243
+ await io.keys(["home", "right", "backspace"]);
244
+ }
245
+ else
246
+ await io.keys(typedKeys(text));
247
+ }
248
+ const shown = await verifyText(text);
249
+ return shown;
250
+ };
169
251
  const reach = async (index) => {
170
252
  const screen = await settle(value => value);
171
253
  if (screen?.kind === "question" && sameTitle(screen.title, questions[index].question))
@@ -175,15 +257,23 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
175
257
  if (at < 0)
176
258
  throw changed("The terminal is showing a different question.");
177
259
  // Arrow keys would edit a typed answer; step off that row first.
178
- if (screen?.kind === "question" && screen.other && screen.cursor === screen.other.number)
179
- await io.keys(["up"]);
260
+ if (screen?.kind === "question")
261
+ await commandCursor(at, screen);
180
262
  await io.keys(Array(Math.abs(index - at)).fill(index > at ? "right" : "left"));
181
263
  const moved = await settle(value => matches(value, index) ? value : undefined);
182
264
  if (!moved)
183
265
  throw changed("Could not move the terminal to the question being answered.");
184
266
  return moved;
185
267
  };
186
- const leaves = (index) => (value) => value === undefined ? "gone" : !matches(value, index) ? "moved" : undefined;
268
+ const leaves = (index, mayClose) => (value, closed) => {
269
+ if (mayClose && closed)
270
+ return "gone";
271
+ if (index + 1 < questions.length && matches(value, index + 1))
272
+ return "moved";
273
+ if (index + 1 === questions.length && value?.kind === "review")
274
+ return "moved";
275
+ return undefined;
276
+ };
187
277
  for (const [offset, answer] of answers.entries()) {
188
278
  const index = from + offset, question = questions[index];
189
279
  if (!question)
@@ -191,58 +281,42 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
191
281
  const typed = answer.text?.trim() ?? "";
192
282
  let screen = await reach(index);
193
283
  if (screen.multiSelect !== !!question.multiSelect || screen.options.length !== question.options.length
194
- || screen.options.some((row, position) => !sameLabel(row.label, question.options[position].label))) {
284
+ || screen.options.some((row, position) => row.label !== normalize(question.options[position].label))) {
195
285
  throw changed("The terminal's options differ from the question being answered.");
196
286
  }
197
287
  if (!screen.multiSelect) {
198
288
  if (typed) {
199
- const other = screen.other;
200
- await io.keys([String(other.number)]);
201
- const focused = await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined);
202
- if (!focused)
203
- throw changed("Could not open the typed answer.");
204
- await io.keys(typedKeys(typed));
205
- const shown = await settle(value => matches(value, index) && value.other && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
206
- if (!shown)
207
- throw changed("The typed answer did not appear in the terminal.");
289
+ await enterText(index, screen, typed);
208
290
  await io.keys(["enter"]);
209
291
  }
210
292
  else {
293
+ screen = await commandCursor(index, screen);
211
294
  await io.keys([String(screen.options[answer.options[0]].number)]);
212
295
  }
213
- if (!await settle(leaves(index), ANSWERED_MS))
214
- throw changed("The terminal did not take the answer.");
296
+ if (!await settle(leaves(index, questions.length === 1), ANSWERED_MS))
297
+ throw changed("The terminal did not confirm taking the answer.");
215
298
  continue;
216
299
  }
300
+ screen = await commandCursor(index, screen);
217
301
  // Multi-select: toggle only the boxes that differ, one key per write
218
302
  // (Ink reads "13" in one write as a single input and toggles nothing),
219
303
  // and check each box before the next.
220
304
  const rows = [...screen.options, ...(screen.other ? [screen.other] : [])];
221
305
  for (const [position, row] of rows.entries()) {
222
- const wanted = position < screen.options.length ? answer.options.includes(position) : !!row.checked && !!typed;
306
+ const wanted = position < screen.options.length ? answer.options.includes(position) : !!typed && row.label === typed;
223
307
  if (wanted === !!row.checked)
224
308
  continue;
225
309
  const box = (value) => matches(value, index)
226
310
  ? !!(position < value.options.length ? value.options[position] : value.other)?.checked : undefined;
227
- // A key that lands while the tab is still drawing can be dropped; the
228
- // box itself says whether one more press is needed.
229
- for (let attempt = 0; attempt < 2 && box(screen) !== wanted; attempt++) {
230
- await io.keys([String(row.number)]);
231
- screen = await settle(value => box(value) === wanted ? value : undefined, 1_000) ?? screen;
232
- }
233
- if (box(screen) !== wanted)
311
+ screen = await commandCursor(index, screen);
312
+ await io.keys([String(row.number)]);
313
+ const toggled = await settle(value => box(value) === wanted ? value : undefined);
314
+ if (!toggled)
234
315
  throw changed("The terminal's checkboxes did not match the answer.");
316
+ screen = toggled;
235
317
  }
236
318
  if (typed) {
237
- const other = screen.other, cursor = typeof screen.cursor === "number" ? screen.cursor : 1;
238
- if (cursor !== other.number)
239
- await io.keys(Array(Math.abs(other.number - cursor)).fill(other.number > cursor ? "down" : "up"));
240
- if (!await settle(value => matches(value, index) && value.cursor === other.number ? value : undefined))
241
- throw changed("Could not reach the typed answer row.");
242
- await io.keys(typedKeys(typed));
243
- const shown = await settle(value => matches(value, index) && value.other?.checked && normalize(value.other.label).startsWith(normalize(typed).slice(0, 20)) ? value : undefined);
244
- if (!shown)
245
- throw changed("The typed answer did not appear in the terminal.");
319
+ screen = await enterText(index, screen, typed);
246
320
  // Tab moves from the typed row to Next; Enter there leaves the question.
247
321
  await io.keys(["tab"]);
248
322
  if (!await settle(value => matches(value, index) && value.cursor === "next" ? value : undefined))
@@ -251,23 +325,32 @@ export async function answerClaudeQuestionDialog(io, questions, answers, options
251
325
  }
252
326
  else {
253
327
  // Tab from the typed row would stop on Next instead of leaving.
254
- await io.keys(screen.other && screen.cursor === screen.other.number ? ["up", "tab"] : ["tab"]);
328
+ screen = await commandCursor(index, screen);
329
+ await io.keys(["tab"]);
255
330
  }
256
- if (!await settle(leaves(index), ANSWERED_MS))
331
+ if (!await settle(leaves(index, false), ANSWERED_MS))
257
332
  throw changed("The terminal did not move past the question.");
258
333
  }
259
334
  if (!submit)
260
335
  return;
261
- const review = await settle(value => value?.kind === "review" ? value : value === undefined ? "gone" : undefined, ANSWERED_MS);
336
+ const review = await settle((value, closed) => value?.kind === "review" ? value
337
+ : questions.length === 1 && !questions[0].multiSelect && closed ? "gone" : undefined, ANSWERED_MS);
262
338
  // A lone single-select question submits on its digit.
263
339
  if (review === "gone")
264
340
  return;
265
341
  if (!review)
266
342
  throw changed("The terminal did not reach the review of the answers.");
267
343
  if (review.answers.length !== questions.length || review.answers.some((row, position) => !sameTitle(normalize(row.question), questions[position].question) || !row.answer)) {
268
- throw changed("Not every question has an answer in the terminal.");
344
+ throw changed("The terminal's review does not contain every expected question and answer.");
345
+ }
346
+ for (const [offset, answer] of answers.entries()) {
347
+ const index = from + offset, question = questions[index], text = answer.text?.trim() ?? "";
348
+ const labels = question.options.filter((_, position) => answer.options.includes(position)).map(option => normalize(option.label));
349
+ const expected = question.multiSelect ? [...labels, ...(text ? [text] : [])].join(", ") : text || labels[0];
350
+ if (review.answers[index]?.wrapped || review.answers[index]?.answer !== expected)
351
+ throw changed("The terminal's review does not exactly match the phone's answers.");
269
352
  }
270
353
  await io.keys(["1"]);
271
- if (await settle(value => value === undefined ? "gone" : undefined, ANSWERED_MS) !== "gone")
354
+ if (await settle((_value, closed) => closed ? "gone" : undefined, ANSWERED_MS) !== "gone")
272
355
  throw changed("The terminal did not submit the answers.");
273
356
  }
@@ -1,3 +1,4 @@
1
+ import type { IncomingMessage } from "node:http";
1
2
  import { type LinkResult, linkComputer } from "./link.js";
2
3
  import { type Json } from "./protocol.js";
3
4
  /** The Hook routes for linked computer sets (docs/conductor-sets.md). */
@@ -27,5 +28,5 @@ export declare function nameSet(data: Json): Promise<Json>;
27
28
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
28
29
  * on the computer whose set lists `name` as indirect or one-way, over this
29
30
  * computer's own ssh login, one link at a time. */
30
- export declare function linkSetMember(data: Json, link?: typeof linkComputer): Promise<LinkResult>;
31
+ export declare function linkSetMember(data: Json, request: Pick<IncomingMessage, "headers">, link?: typeof linkComputer): Promise<LinkResult>;
31
32
  export {};
@@ -7,6 +7,7 @@ import { listsCaller } from "./health.js";
7
7
  import { linkComputer } from "./link.js";
8
8
  import { optionalHookPeers, peerRequest } from "./peers.js";
9
9
  import { BridgeError, object } from "./protocol.js";
10
+ import { ownerRequest } from "./request-origin.js";
10
11
  import { localConductor } from "./server-launch.js";
11
12
  const callerSchema = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() });
12
13
  /** `GET /v1/conductor`: this computer's live conductor and what a peer needs
@@ -89,8 +90,8 @@ let linking;
89
90
  /** `POST /v1/sets/link`: the phone's one-tap `phren bridge link <name>`. Runs
90
91
  * on the computer whose set lists `name` as indirect or one-way, over this
91
92
  * computer's own ssh login, one link at a time. */
92
- export async function linkSetMember(data, link = linkComputer) {
93
- if (data && typeof data === "object" && "origin" in data)
93
+ export async function linkSetMember(data, request, link = linkComputer) {
94
+ if (!ownerRequest(request, data))
94
95
  throw new BridgeError(403, "Only the owner links computers, from the phone or `phren bridge link` in their own terminal.");
95
96
  const { name } = linkInput.parse(data);
96
97
  if (linking)
@@ -3,3 +3,7 @@
3
3
  export declare const DIALOG_READ_MS: number;
4
4
  export declare const DIALOG_CONFIRM_MS = 300;
5
5
  export declare function confirmDialogRead<T>(read: () => Promise<T>, current: () => boolean): Promise<T | undefined>;
6
+ /** A live composer or working hint after all dialog cues proves closure.
7
+ * Call only after ruling out a currently readable dialog. A failed parse alone
8
+ * says nothing: clipped and half-drawn screens remain unknown. */
9
+ export declare function dialogHasClosed(screen: string): boolean;
@@ -1,3 +1,5 @@
1
+ import { stripTerminal } from "../terminal-text.js";
2
+ import { claudeFooterMode } from "./claude-footer-mode.js";
1
3
  import { intervalFromEnv } from "./limits.js";
2
4
  /** Discovery is frequent by default; an owner can still cap polling explicitly.
3
5
  * Confirmation has its own small, fixed budget, independent of that cap. */
@@ -18,3 +20,25 @@ export async function confirmDialogRead(read, current) {
18
20
  clearTimeout(timer);
19
21
  }
20
22
  }
23
+ /** A live composer or working hint after all dialog cues proves closure.
24
+ * Call only after ruling out a currently readable dialog. A failed parse alone
25
+ * says nothing: clipped and half-drawn screens remain unknown. */
26
+ export function dialogHasClosed(screen) {
27
+ const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
28
+ const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
29
+ const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
30
+ || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
31
+ const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
32
+ let cue = -1;
33
+ for (let index = 0; index < lines.length; index++) {
34
+ if (/^(?:[>❯›]?\s*\d+[.)]|Do you want|Would you like|Ready to code|Allow\b|Trust\b|Teach auto|△\s*Permission|[☐☒]|.*Esc to cancel)/i.test(lines[index]))
35
+ cue = index;
36
+ }
37
+ for (let index = lines.length - 1; index > cue; index--) {
38
+ if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
39
+ return true;
40
+ if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
41
+ return true;
42
+ }
43
+ return false;
44
+ }
@@ -23,9 +23,8 @@ import { readFile } from "node:fs/promises";
23
23
  import { stripTerminal } from "../terminal-text.js";
24
24
  import { bindingPath } from "./agent-hook-stores.js";
25
25
  import { claudeQuestionDialog } from "./claude-question-dialog.js";
26
- import { confirmDialogRead, DIALOG_READ_MS } from "./dialog-observation.js";
26
+ import { confirmDialogRead, dialogHasClosed, DIALOG_READ_MS } from "./dialog-observation.js";
27
27
  import { object } from "./protocol.js";
28
- import { claudeFooterMode } from "./claude-footer-mode.js";
29
28
  import { claudePermissionDialog, opencodePermissionDialog, visibleTerminalChoice } from "./terminal-choice.js";
30
29
  const EVENT_STATUS = {
31
30
  SessionStart: "idle", UserPromptSubmit: "working", PreToolUse: "working", PostToolUse: "working",
@@ -120,23 +119,7 @@ export function screenDialog(agent, screen) {
120
119
  export function screenDialogState(agent, screen) {
121
120
  if (screenDialog(agent, screen))
122
121
  return "shown";
123
- const lines = stripTerminal(screen).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
124
- const composer = (line) => /^[❯›](?!\s*\d+[.)])(?:\s|$)/.test(line);
125
- const chrome = (line) => /^[─━═]+$/.test(line) || claudeFooterMode(line) !== undefined
126
- || /^(?:[←→?].*(?:agents|shortcuts)|(?:gpt-|GPT-|claude-|Claude ).*)/i.test(line);
127
- const liveTail = (index) => lines.slice(index + 1).every(line => composer(line) || chrome(line));
128
- let cue = -1;
129
- for (let index = 0; index < lines.length; index++) {
130
- if (/^(?:[>❯›]?\s*\d+[.)]|Do you want|Would you like|Ready to code|Allow\b|Trust\b|Teach auto|△\s*Permission|[☐☒]|.*Esc to cancel)/i.test(lines[index]))
131
- cue = index;
132
- }
133
- for (let index = lines.length - 1; index > cue; index--) {
134
- if (/\besc to interrupt\b/i.test(lines[index]) && liveTail(index))
135
- return "gone";
136
- if (index >= lines.length - 3 && composer(lines[index]) && liveTail(index))
137
- return "gone";
138
- }
139
- return "unknown";
122
+ return dialogHasClosed(screen) ? "gone" : "unknown";
140
123
  }
141
124
  const dialogs = new Map();
142
125
  /** The status of a pane after a look at its screen: blocked while its agent
@@ -55,4 +55,4 @@ export declare function retryAfterSubagentView(agentHooks: AgentHooks, target: T
55
55
  * resets that window. No observation sends input to the terminal. */
56
56
  export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, id?: string, intervalMs?: number): void;
57
57
  export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, headers?: IncomingHttpHeaders): Promise<unknown>;
58
- export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>): Promise<unknown>;
58
+ export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>, headers?: IncomingHttpHeaders): Promise<unknown>;
@@ -20,6 +20,7 @@ import { AppServerRpcError } from "./codex-app-server.js";
20
20
  import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
21
21
  import { refuseWorkingSlash } from "./model-switch.js";
22
22
  import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
23
+ import { ownerRequest } from "./request-origin.js";
23
24
  import { sessionWebServers } from "./session-servers.js";
24
25
  import { takesPrompt } from "./session-activity.js";
25
26
  import { gitRoot, repositoryDiff, withGitReadDeadline } from "./projects.js";
@@ -473,10 +474,10 @@ export async function paneRoute(ctx, url, data, response, headers = {}) {
473
474
  throw new BridgeError(400, "This app is too old to change Git safely. Update it.", { code: "expected-repository-required" });
474
475
  }
475
476
  if (["/v1/diff", "/v1/git/status", "/v1/git/worktrees"].includes(url.pathname)) {
476
- return withGitReadDeadline(() => paneRouteOnce(ctx, url, data, response, () => { }));
477
+ return withGitReadDeadline(() => paneRouteOnce(ctx, url, data, response, () => { }, headers));
477
478
  }
478
479
  if (url.pathname !== "/v1/prompt")
479
- return paneRouteOnce(ctx, url, data, response, () => { });
480
+ return paneRouteOnce(ctx, url, data, response, () => { }, headers);
480
481
  // A retried send carries its first attempt's id; the Hook answers it with
481
482
  // that attempt's reply instead of typing the message a second time.
482
483
  const id = deliveryIdSchema.parse(data.deliveryId);
@@ -489,9 +490,9 @@ export async function paneRoute(ctx, url, data, response, headers = {}) {
489
490
  return { ...known, replayed: true };
490
491
  if (known)
491
492
  promptOnce.forget(id);
492
- return promptOnce.run(id, scope, async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
493
+ return promptOnce.run(id, scope, async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing, headers)));
493
494
  }
494
- export async function paneRouteOnce(ctx, url, data, response, typing) {
495
+ export async function paneRouteOnce(ctx, url, data, response, typing, headers = {}) {
495
496
  const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
496
497
  let result;
497
498
  if (url.pathname === "/v1/git/worktrees/remove/preview" || url.pathname === "/v1/git/worktrees/remove") {
@@ -764,8 +765,9 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
764
765
  // The messages a busy agent holds in its own queue: sent to the running
765
766
  // turn now, or withdrawn unsent. Only Claude Code's queue can be reached;
766
767
  // a pane the Hook types into for any other harness has none it can act on.
767
- // The owner's words: an agent may not send or discard another pane's queue.
768
- if (data && typeof data === "object" && "origin" in data)
768
+ // The owner's words: neither an agent nor a peer computer may send or
769
+ // discard a pane's queue.
770
+ if (!ownerRequest({ headers }, data))
769
771
  throw new BridgeError(403, "Only the owner sends or cancels queued messages, from the phone.");
770
772
  const action = z.enum(["send-now", "withdraw"]).parse(data.action);
771
773
  if (target.source !== "claude")
@@ -786,9 +788,10 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
786
788
  }
787
789
  else if (url.pathname === "/v1/agents/permission-mode") {
788
790
  // The owner's own choice from the phone: no authority ceiling applies.
789
- // An agent's call carries its pane as `origin` and is refused, so no
790
- // agent can raise its own or another pane's mode past its ceiling.
791
- refuseAgentOrigin(data && typeof data === "object" && "origin" in data ? data.origin ?? null : undefined);
791
+ // An agent's call carries its pane as `origin`, a peer computer's
792
+ // arrives through its key's scope, and both are refused, so neither can
793
+ // raise a pane's mode past its ceiling.
794
+ refuseAgentOrigin(ownerRequest({ headers }, data) ? undefined : data.origin ?? "peer");
792
795
  result = await permissionModeSwitcher.set(target, z.enum(PERMISSION_MODE_VALUES).parse(data.mode));
793
796
  }
794
797
  else if (url.pathname === "/v1/keys" && await agentHooks.servedKeys(target, z.array(z.enum(ANSWER_KEYS)).min(1).max(4).parse(data.keys), String(pane.agent_status))) {
@@ -1294,8 +1294,9 @@ export function createRouteHandler(ctx) {
1294
1294
  result = await conductorCall("grants-add", grant, origin, async () => ({ ok: true, grant: await addGrant(grant) }));
1295
1295
  }
1296
1296
  else if (url.pathname === "/v1/authority" || url.pathname === "/v1/authority/confirm") {
1297
- // The owner writes the policy from the phone; an agent's call names its pane.
1298
- if (data.origin !== undefined)
1297
+ // The owner writes the policy from the phone; an agent's call names its
1298
+ // pane and a peer computer's arrives through its key's scope.
1299
+ if (!ownerRequest(request, data))
1299
1300
  throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
1300
1301
  result = url.pathname === "/v1/authority" ? { ok: true, authority: await setProjectAuthority(data, "phone") }
1301
1302
  : { ok: true, confirmation: await confirmAuthority(data, "phone") };
@@ -1315,7 +1316,7 @@ export function createRouteHandler(ctx) {
1315
1316
  result = await nameSet(data);
1316
1317
  }
1317
1318
  else if (url.pathname === "/v1/sets/link") {
1318
- result = await linkSetMember(data);
1319
+ result = await linkSetMember(data, request);
1319
1320
  }
1320
1321
  else if (url.pathname === "/v1/push/register") {
1321
1322
  // Registration is kept for when a key is added; the reply says whether push works now.
@@ -1323,8 +1324,9 @@ export function createRouteHandler(ctx) {
1323
1324
  result = { ok: true, configured: agentHooks.push.status.configured };
1324
1325
  }
1325
1326
  else if (url.pathname === "/v1/sudo/answer") {
1326
- // The owner answers from the phone; an agent's call names its pane.
1327
- if (data && typeof data === "object" && "origin" in data)
1327
+ // The owner answers from the phone; an agent's call names its pane and
1328
+ // a peer computer's arrives through its key's scope.
1329
+ if (!ownerRequest(request, data))
1328
1330
  throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
1329
1331
  let parsed;
1330
1332
  try {
@@ -1418,7 +1420,7 @@ export function createRouteHandler(ctx) {
1418
1420
  result = await changeApprovalRule(data, "DELETE");
1419
1421
  }
1420
1422
  else if (url.pathname === "/v1/authority") {
1421
- if (data.origin !== undefined)
1423
+ if (!ownerRequest(request, data))
1422
1424
  throw new BridgeError(403, "Only the owner changes the release authority policy, from the phone or `phren authority` in their own terminal.");
1423
1425
  result = { ok: true, authority: await clearProjectAuthority(data, "phone") };
1424
1426
  }
@@ -76,6 +76,10 @@ export declare function tmuxSnapshot(server: string): Promise<Json>;
76
76
  export declare function tmuxKey(key: string): string | undefined;
77
77
  /** send-keys calls for `keys`, in order: named keys together, literal characters with -l. */
78
78
  export declare function sendKeysCalls(pane: string, keys: string[]): string[][];
79
+ /** tmux reads the names and directories it is handed as formats, so `#(…)`
80
+ * would run a command and `#{…}` read a variable. A doubled `#` is a literal
81
+ * one. Option values (`set-option`) are not formats and take text as it is. */
82
+ export declare function tmuxLiteral(text: string): string;
79
83
  export declare const tmuxTerminal: TerminalProvider;
80
84
  /** The tmux servers the Hook drives, as `/v1/muxes` lists servers: the owner's
81
85
  * servers that answer, and (unless `hidden: false`) the hidden server whenever
@@ -406,6 +406,12 @@ function loginShell() {
406
406
  // Only a POSIX shell takes the launcher script below.
407
407
  return shell && /^(sh|bash|zsh|ksh|dash)$/.test(path.basename(shell)) && existsSync(shell) ? shell : "/bin/sh";
408
408
  }
409
+ /** tmux reads the names and directories it is handed as formats, so `#(…)`
410
+ * would run a command and `#{…}` read a variable. A doubled `#` is a literal
411
+ * one. Option values (`set-option`) are not formats and take text as it is. */
412
+ export function tmuxLiteral(text) {
413
+ return text.replace(/#/g, "##");
414
+ }
409
415
  /** A session name tmux accepts: no "." or ":" and nothing unprintable. */
410
416
  function sessionName(label, taken) {
411
417
  const base = (label ?? "phren").replace(/[.:\x00-\x1f\x7f]/g, "_").trim().slice(0, 60) || "phren";
@@ -460,8 +466,8 @@ export const tmuxTerminal = {
460
466
  await tmux(server, ["send-keys", "-t", target, "Enter"], { signal });
461
467
  },
462
468
  async create(server, { workspace, label, cwd }) {
463
- const directory = cwd && path.isAbsolute(cwd) ? ["-c", cwd] : [];
464
- const name = label ? ["-n", label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100)] : [];
469
+ const directory = cwd && path.isAbsolute(cwd) ? ["-c", tmuxLiteral(cwd)] : [];
470
+ const name = label ? ["-n", tmuxLiteral(label.replace(/[\x00-\x1f\x7f]/g, " ").slice(0, 100))] : [];
465
471
  // `-P -F` prints the new pane's ids, so the caller knows it without diffing the pane list.
466
472
  const printed = ["-P", "-F", "#{session_id} #{window_id} #{pane_id}"];
467
473
  const created = (output) => {
@@ -471,7 +477,7 @@ export const tmuxTerminal = {
471
477
  if (workspace)
472
478
  return created(await tmux(server, ["new-window", "-d", ...printed, "-t", `${toTmuxId(workspace, "s")}:`, ...directory, ...name]));
473
479
  const taken = new Set((await tmux(server, ["list-sessions", "-F", "#{session_name}"]).catch(() => "")).split("\n").filter(Boolean));
474
- return created(await tmux(server, ["new-session", "-d", ...printed, "-s", sessionName(label, taken), "-x", "200", "-y", "50", ...directory, ...name]));
480
+ return created(await tmux(server, ["new-session", "-d", ...printed, "-s", tmuxLiteral(sessionName(label, taken)), "-x", "200", "-y", "50", ...directory, ...name]));
475
481
  },
476
482
  async startAgent(server, pane, { name, kind, args, timeoutMs, env, envExact }) {
477
483
  if (!["claude", "codex", "copilot", "opencode", "phren"].includes(kind))
@@ -488,13 +494,13 @@ export const tmuxTerminal = {
488
494
  const shell = loginShell();
489
495
  if (envExact) {
490
496
  const command = explicitAgentCommand(kind, args, env ?? {});
491
- await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []),
497
+ await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", tmuxLiteral(row.pane_current_path)] : []),
492
498
  "--", shell, "-l", "-c", command]);
493
499
  }
494
500
  else {
495
501
  // Variables for the agent alone (a dispatch id) ride on the respawn.
496
502
  const variables = Object.entries(env ?? {}).flatMap(([key, value]) => ["-e", `${key}=${value}`]);
497
- await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", row.pane_current_path] : []), ...variables,
503
+ await tmux(server, ["respawn-pane", "-k", "-t", target, ...(row.pane_current_path ? ["-c", tmuxLiteral(row.pane_current_path)] : []), ...variables,
498
504
  "--", shell, "-l", "-c", 'shell="$1"; shift; "$@"; exec "$shell" -l', "phren", shell, kind, ...args]);
499
505
  }
500
506
  // Started once the harness is the pane's foreground program.
@@ -534,7 +540,7 @@ export const tmuxTerminal = {
534
540
  if (operation === "focus")
535
541
  await tmux(server, ["select-window", "-t", target]);
536
542
  else if (operation === "rename")
537
- await tmux(server, ["rename-window", "-t", target, (label ?? "").replace(/[\x00-\x1f\x7f]/g, " ")]);
543
+ await tmux(server, ["rename-window", "-t", target, tmuxLiteral((label ?? "").replace(/[\x00-\x1f\x7f]/g, " "))]);
538
544
  else
539
545
  await tmux(server, ["kill-window", "-t", target]);
540
546
  return;
@@ -546,7 +552,7 @@ export const tmuxTerminal = {
546
552
  if (operation === "focus")
547
553
  return;
548
554
  if (operation === "rename")
549
- await tmux(server, ["rename-session", "-t", target, sessionName(label, new Set())]);
555
+ await tmux(server, ["rename-session", "-t", target, tmuxLiteral(sessionName(label, new Set()))]);
550
556
  else
551
557
  await tmux(server, ["kill-session", "-t", target]);
552
558
  },
@@ -40,6 +40,13 @@ export declare function isNarration(block: Record<string, unknown>): boolean;
40
40
  * second result for the same call, so the phone can show what the skill said;
41
41
  * every other hidden row stays private. */
42
42
  export declare function skillBody(raw: Json): Json | undefined;
43
+ /** A message another agent sent this session (a teammate, a subagent's
44
+ * hand-back or another Claude session), which Claude Code delivers as a hidden
45
+ * user row when the agent is idle, or a queued_command attachment mid-turn,
46
+ * both naming it with `origin.kind: "peer"`. The terminal shows it as
47
+ * "Message from @name"; only the sender's name and the words cross, never the
48
+ * envelope, socket path or ids. */
49
+ export declare function peerMessage(raw: Json, includeSidechain?: boolean): Json | undefined;
43
50
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
44
51
  * parentUuid, content }`, or undefined for any other row. */
45
52
  export declare function phrenHookContext(raw: Json, includeSidechain?: boolean): Json | undefined;