@phren/cli 0.3.55 → 0.3.57

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 (36) hide show
  1. package/dist/bridge/agent-hook-callback.js +1 -0
  2. package/dist/bridge/agent-hooks.js +1 -0
  3. package/dist/bridge/claude-suggestion.d.ts +9 -0
  4. package/dist/bridge/claude-suggestion.js +30 -4
  5. package/dist/bridge/dispatch-command.js +3 -3
  6. package/dist/bridge/dispatch-returns.d.ts +4 -0
  7. package/dist/bridge/dispatch-returns.js +10 -3
  8. package/dist/bridge/hand-off-queue.d.ts +21 -0
  9. package/dist/bridge/hand-off-queue.js +31 -2
  10. package/dist/bridge/hand-off.d.ts +1 -0
  11. package/dist/bridge/hand-off.js +5 -1
  12. package/dist/bridge/pair.d.ts +22 -0
  13. package/dist/bridge/pair.js +74 -1
  14. package/dist/bridge/prompt-deliveries.d.ts +21 -0
  15. package/dist/bridge/prompt-deliveries.js +140 -24
  16. package/dist/bridge/server-launch.d.ts +4 -0
  17. package/dist/bridge/server-launch.js +4 -1
  18. package/dist/bridge/server-pane-routes.d.ts +16 -0
  19. package/dist/bridge/server-pane-routes.js +132 -4
  20. package/dist/bridge/server-routes.d.ts +1 -0
  21. package/dist/bridge/server-routes.js +1 -1
  22. package/dist/bridge/server.js +9 -2
  23. package/dist/bridge/session-activity.d.ts +28 -0
  24. package/dist/bridge/session-activity.js +30 -0
  25. package/dist/bridge/session-move.d.ts +25 -0
  26. package/dist/bridge/session-move.js +128 -9
  27. package/dist/bridge/speech-transcribe.js +28 -3
  28. package/dist/bridge/terminal-herdr.js +28 -8
  29. package/dist/bridge/turn-records.d.ts +2 -0
  30. package/dist/bridge/turn-records.js +6 -1
  31. package/dist/bridge-hook.mjs +1900 -1524
  32. package/dist/cli-registry.js +2 -2
  33. package/dist/modules/registry.js +1 -1
  34. package/dist/tools/dispatch.js +3 -2
  35. package/package.json +1 -1
  36. package/starter/global/skills/conductor/SKILL.md +7 -0
@@ -94,6 +94,7 @@ async function forwardHook(source, target, event, value, left) {
94
94
  ...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
95
95
  tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
96
96
  ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
97
+ ...(event === "SessionStart" && typeof value.source === "string" ? { startSource: value.source.slice(0, 32) } : {}),
97
98
  ...(event === "Stop" ? stopFacts(value) : {}) });
98
99
  await new Promise(resolve => {
99
100
  const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? Math.max(1, left()) : 12_000,
@@ -559,6 +559,7 @@ export class AgentHooks {
559
559
  return;
560
560
  await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
561
561
  ...(dispatch ? { dispatch } : {}),
562
+ ...(body.event === "SessionStart" && typeof body.startSource === "string" ? { start: body.startSource } : {}),
562
563
  ...(typeof body.background === "number" ? { background: body.background } : {}),
563
564
  ...(typeof body.reply === "string" ? { reply: body.reply } : {}),
564
565
  ...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
@@ -6,3 +6,12 @@
6
6
  * offered, since sending half a sentence would be worse than nothing.
7
7
  */
8
8
  export declare function claudeSuggestion(screen: string): string | undefined;
9
+ /** The suggestion as drawn, a narrow pane's cut one ("…" at the end) included, for refusing a relay of what
10
+ * a screen read shows; undefined when there is none. */
11
+ export declare function claudeSuggestionShown(screen: string): string | undefined;
12
+ /** Claude Code showing a subagent's (or teammate's) view: its empty input box
13
+ * reads "Message @<agent>…". Text typed there goes to that agent, not the
14
+ * conversation, so a phone message typed into it never reaches the turn;
15
+ * Escape returns to the main view. */
16
+ export declare const SUBAGENT_VIEW: RegExp;
17
+ export declare function claudeSubagentView(screen: string): boolean;
@@ -20,6 +20,35 @@ const PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$
20
20
  * offered, since sending half a sentence would be worse than nothing.
21
21
  */
22
22
  export function claudeSuggestion(screen) {
23
+ const text = liveInputDimText(screen);
24
+ if (!text || text.endsWith("…") || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)))
25
+ return undefined;
26
+ return text;
27
+ }
28
+ /** The suggestion as drawn, a narrow pane's cut one ("…" at the end) included, for refusing a relay of what
29
+ * a screen read shows; undefined when there is none. */
30
+ export function claudeSuggestionShown(screen) {
31
+ const text = liveInputDimText(screen);
32
+ if (!text || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)) || SUBAGENT_VIEW.test(text))
33
+ return undefined;
34
+ return text;
35
+ }
36
+ /** Claude Code showing a subagent's (or teammate's) view: its empty input box
37
+ * reads "Message @<agent>…". Text typed there goes to that agent, not the
38
+ * conversation, so a phone message typed into it never reaches the turn;
39
+ * Escape returns to the main view. */
40
+ // Only the bare placeholder, one agent name and nothing else: a suggestion
41
+ // that a narrow pane cut short ("Message @researcher to check…") is not one.
42
+ // Claude Code (2.1.303) cuts a name past 20 columns with its own "…" before the
43
+ // placeholder's: "Message @researcher-performa……".
44
+ export const SUBAGENT_VIEW = /^Message @[\w.-]{1,20}…?…$/;
45
+ export function claudeSubagentView(screen) {
46
+ const text = liveInputDimText(screen);
47
+ return !!text && SUBAGENT_VIEW.test(text);
48
+ }
49
+ /** The dim text in the live input box (between its two rules), "" when the
50
+ * box holds typed text, undefined when there is no live box on screen. */
51
+ function liveInputDimText(screen) {
23
52
  const lines = screen.split("\n").map(line => line.replace(/\r$/, ""));
24
53
  for (let index = lines.length - 2; index > 0; index--) {
25
54
  const plain = stripTerminal(lines[index]);
@@ -28,10 +57,7 @@ export function claudeSuggestion(screen) {
28
57
  // Only the live input box: a sent prompt in the history has no rules around it.
29
58
  if (!rule(stripTerminal(lines[index - 1])) || !rule(stripTerminal(lines[index + 1])))
30
59
  return undefined;
31
- const text = dimText(lines[index]);
32
- if (!text || text.endsWith("…") || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)))
33
- return undefined;
34
- return text;
60
+ return dimText(lines[index]);
35
61
  }
36
62
  return undefined;
37
63
  }
@@ -89,12 +89,12 @@ export async function runHandOff(args) {
89
89
  console.log(JSON.stringify(result, null, 2));
90
90
  return result.ok ? 0 : 1;
91
91
  }
92
- const MOVE_USAGE = "Usage: phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id>] [--computer <name>] [--no-wait] | phren move --status <move-id> [--computer <name>]";
92
+ const MOVE_USAGE = "Usage: phren move <session-or-pane> --to <claude|codex|opencode|copilot> [--model <model>] [--effort <effort>] [--account <id> [--resume]] [--computer <name>] [--no-wait] | phren move --status <move-id> [--computer <name>]";
93
93
  /** `phren move`: a live session, named by its session id or its pane id (`wC9:p1`), to another agent, through its computer's Hook (session-move.ts). */
94
94
  export async function runMove(args) {
95
95
  const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
96
96
  to: { type: "string" }, account: { type: "string" }, model: { type: "string" }, effort: { type: "string" }, computer: { type: "string" },
97
- status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" },
97
+ status: { type: "string" }, id: { type: "string" }, "no-wait": { type: "boolean" }, resume: { type: "boolean" },
98
98
  } });
99
99
  const computer = values.computer ? { computer: values.computer } : {};
100
100
  if (values.status) {
@@ -109,7 +109,7 @@ export async function runMove(args) {
109
109
  const named = sessionId.safeParse(positionals[0]).success ? { session: positionals[0] } : { pane: positionals[0] };
110
110
  const result = await moveSession({ ...computer, ...named, harness: values.to, ...(values.account ? { account: values.account } : {}),
111
111
  ...(values.model ? { model: values.model } : {}), ...(values.effort ? { effort: values.effort } : {}), ...(values.id ? { id: values.id } : {}),
112
- ...(values["no-wait"] ? { wait: false } : {}) });
112
+ ...(values["no-wait"] ? { wait: false } : {}), ...(values.resume ? { resume: true } : {}) });
113
113
  console.log(JSON.stringify(result, null, 2));
114
114
  return result.ok ? 0 : 1;
115
115
  }
@@ -223,6 +223,9 @@ export interface DispatchReturnsOptions {
223
223
  /** A recent Herdr snapshot of a local server, to see whether the dispatching agent is idle. */
224
224
  snapshot?: (server: string) => Promise<Json>;
225
225
  identity?: (server: string, pane: Json) => Promise<string | undefined>;
226
+ /** Whether the dispatching agent takes a typed notice now (session-activity.ts `takesPrompt`, with
227
+ * the Hook's `promptGuards`, so a dialog in a lead Herdr reads working is never answered). */
228
+ takesPrompt?: (target: Target, pane: Json) => Promise<boolean>;
226
229
  /** Types the notice into the dispatching agent, through the ordinary hand-off
227
230
  * path; the same notice keeps one delivery id, so a retry is never typed twice. */
228
231
  deliver?: (target: Target, text: string, deliveryId: string) => Promise<{
@@ -256,6 +259,7 @@ export declare class DispatchReturns {
256
259
  private readonly isLocal;
257
260
  private readonly snapshot;
258
261
  private readonly identity;
262
+ private readonly takesPrompt;
259
263
  private readonly deliver;
260
264
  private readonly localArrival;
261
265
  private readonly now;
@@ -17,7 +17,7 @@ import { hookPeers, peerRequest } from "./peers.js";
17
17
  import { isLocalComputer, peerFingerprint } from "./dispatch-hosts.js";
18
18
  import { BridgeError, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
19
19
  import { isClaudeUsageLimit, ownerQuestion, readFinalTurn } from "./schedule-watch.js";
20
- import { liveWork, runningTasks } from "./session-activity.js";
20
+ import { liveWork, runningTasks, takesPrompt } from "./session-activity.js";
21
21
  import { terminalProvider } from "./terminal.js";
22
22
  import { childAgentTree, runningChildAgents } from "./transcripts.js";
23
23
  import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
@@ -562,6 +562,7 @@ export class DispatchReturns {
562
562
  isLocal;
563
563
  snapshot;
564
564
  identity;
565
+ takesPrompt;
565
566
  deliver;
566
567
  localArrival;
567
568
  now;
@@ -587,6 +588,7 @@ export class DispatchReturns {
587
588
  this.isLocal = options.isLocal ?? (computer => isLocalComputer(computer));
588
589
  this.snapshot = options.snapshot ?? (server => sharedSnapshot(server, SNAPSHOT_AGE_MS));
589
590
  this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
591
+ this.takesPrompt = options.takesPrompt ?? ((target, pane) => takesPrompt(target.server, pane, target.session));
590
592
  this.deliver = options.deliver ?? ((target, text, deliveryId) => handOff({ target, text }, { deliveryId, bypassConductor: true }));
591
593
  this.localArrival = options.localArrival ?? briefArrival;
592
594
  this.now = options.now ?? Date.now;
@@ -855,10 +857,11 @@ export class DispatchReturns {
855
857
  }
856
858
  else {
857
859
  const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
858
- // Never interrupt: only an agent that has stopped, in the same terminal, gets a notice.
860
+ // Never interrupt: only an agent that has stopped, in the same terminal, gets a notice. A Claude
861
+ // lead whose turn ended while its background agents run on has stopped, though Herdr reads it working.
859
862
  if (!pane || pane.terminal_id !== origin.terminal)
860
863
  continue;
861
- if (!["idle", "done"].includes(String(pane.agent_status))) {
864
+ if (!["idle", "done", "working"].includes(String(pane.agent_status))) {
862
865
  busy = true;
863
866
  continue;
864
867
  }
@@ -866,6 +869,10 @@ export class DispatchReturns {
866
869
  const target = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
867
870
  if (!target.success)
868
871
  continue;
872
+ if (!await this.takesPrompt(target.data, pane).catch(() => false)) {
873
+ busy = true;
874
+ continue;
875
+ }
869
876
  this.lastNotice.set(key, this.now());
870
877
  const sent = await this.deliver(target.data, noticeLine(receipts), noticeDeliveryId(receipts)).catch(() => ({ delivered: false }));
871
878
  if (!sent.delivered)
@@ -1,5 +1,6 @@
1
1
  import { z } from "zod";
2
2
  import { type Json, type Target } from "./protocol.js";
3
+ import type { DeliveryStatus } from "./prompt-deliveries.js";
3
4
  export declare const queuedHandOffSchema: z.ZodObject<{
4
5
  target: z.ZodObject<{
5
6
  server: z.ZodString;
@@ -45,6 +46,19 @@ export interface QueueOptions {
45
46
  session: string;
46
47
  terminal: unknown;
47
48
  } | undefined>;
49
+ /** What became of the message typed under `deliveryId` (prompt-deliveries.ts): an agent whose
50
+ * UserPromptSubmit comes after the send returned settles it there, later. */
51
+ delivery?: (target: Target, deliveryId: string) => DeliveryStatus;
52
+ /** Whether text typed into the target's pane is still waiting to be taken. Nothing more is typed
53
+ * there until it is: a second paste would land in the same input line, after the first. */
54
+ inFlight?: (target: Target) => boolean;
55
+ /** Whether the message typed under `deliveryId` may still be taken: held, and not past the time a pane
56
+ * that sends no hooks is given (prompt-deliveries.ts `held`). */
57
+ held?: (target: Target, deliveryId: string) => boolean;
58
+ /** Whether the target's agent takes a typed prompt now (session-activity.ts `takesPrompt`): idle or
59
+ * done, or a Claude turn that ended while its background agents run on, which Herdr reads working.
60
+ * Without it, only an idle or done pane is typed into. */
61
+ ready?: (target: Target, pane: Json) => Promise<boolean>;
48
62
  now?: () => number;
49
63
  root?: string;
50
64
  }
@@ -70,6 +84,13 @@ export declare class HandOffQueue {
70
84
  private file;
71
85
  private save;
72
86
  private read;
87
+ /** An uncertain row takes the outcome its typed message came to: delivered once the agent's
88
+ * UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
89
+ * failed row still turns delivered when the agent takes the message late. */
90
+ private follow;
91
+ /** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
92
+ * in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
93
+ private stillHeld;
73
94
  private rows;
74
95
  /** Drops settled rows past retention, then the oldest settled rows over the
75
96
  * cap (those still owing their sender a notice last). Returns what is kept. */
@@ -80,8 +80,32 @@ export class HandOffQueue {
80
80
  row.error = "The Hook restarted before delivery was confirmed.";
81
81
  await this.save(row);
82
82
  }
83
+ await this.follow(row);
83
84
  return row;
84
85
  }
86
+ /** An uncertain row takes the outcome its typed message came to: delivered once the agent's
87
+ * UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
88
+ * failed row still turns delivered when the agent takes the message late. */
89
+ async follow(row) {
90
+ if ((row.state !== "uncertain" && row.state !== "failed") || !this.options.delivery)
91
+ return;
92
+ const known = this.options.delivery(row.target, row.deliveryId);
93
+ if (known.state === "delivered") {
94
+ row.state = "delivered";
95
+ delete row.error;
96
+ await this.save(row);
97
+ }
98
+ else if (known.state === "failed" && row.state === "uncertain") {
99
+ row.state = "failed";
100
+ row.error = (known.reason ?? "The agent did not take the message.").slice(0, 500);
101
+ await this.save(row);
102
+ }
103
+ }
104
+ /** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
105
+ * in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
106
+ stillHeld(row) {
107
+ return row.state === "uncertain" && !!this.options.held?.(row.target, row.deliveryId);
108
+ }
85
109
  async rows() {
86
110
  const names = await readdir(this.root).catch(error => { if (error.code === "ENOENT")
87
111
  return []; throw error; });
@@ -189,7 +213,11 @@ export class HandOffQueue {
189
213
  await this.save(row);
190
214
  return;
191
215
  }
192
- if (!["idle", "done"].includes(String(pane.agent_status)))
216
+ if (!(this.options.ready ? await this.options.ready(row.target, pane).catch(() => false) : ["idle", "done"].includes(String(pane.agent_status))))
217
+ return;
218
+ // Herdr reads a pane idle for a few seconds after a prompt was submitted, while the agent runs its
219
+ // hooks; typing the next message then left both in the input line (2026-10-17, five 5 s apart).
220
+ if (this.options.inFlight?.(row.target))
193
221
  return;
194
222
  let typed = false;
195
223
  try {
@@ -236,8 +264,9 @@ export class HandOffQueue {
236
264
  attempted.add(key);
237
265
  await this.attempt(row);
238
266
  }
267
+ // A sender hears the outcome once there is one: not "uncertain" for a message the agent still holds.
239
268
  for (const row of rows)
240
- if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
269
+ if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state) && !this.stillHeld(row)) {
241
270
  if (row.originComputer) {
242
271
  remote.push(row);
243
272
  continue;
@@ -77,6 +77,7 @@ export declare const moveSessionSchema: z.ZodObject<{
77
77
  minimal: "minimal";
78
78
  xhigh: "xhigh";
79
79
  }>>;
80
+ resume: z.ZodOptional<z.ZodBoolean>;
80
81
  id: z.ZodOptional<z.ZodString>;
81
82
  status: z.ZodOptional<z.ZodBoolean>;
82
83
  wait: z.ZodOptional<z.ZodBoolean>;
@@ -131,6 +131,7 @@ export const moveSessionSchema = z.object({
131
131
  account: moveToSchema.shape.account,
132
132
  model: moveToSchema.shape.model,
133
133
  effort: moveToSchema.shape.effort,
134
+ resume: z.boolean().optional().describe("Switch a Claude conversation to another Claude account on this computer without a hand-off: the old agent exits, its transcript is copied into that account's home and the same conversation resumes there, so an account at its usage limit can still switch. Needs harness claude and account."),
134
135
  id: z.string().uuid().optional().describe("Move id: keep it on a retry, or pass it with status:true to read where the move is."),
135
136
  status: z.boolean().optional().describe("Read the move's state without starting one; requires id."),
136
137
  wait: z.boolean().optional().describe("Wait (up to five minutes) until the move finished or failed. Defaults to true."),
@@ -139,6 +140,8 @@ export const moveSessionSchema = z.object({
139
140
  context.addIssue({ code: "custom", message: "Provide exactly one of target, session or pane." });
140
141
  if (value.status && !value.id)
141
142
  context.addIssue({ code: "custom", message: "A status query requires id." });
143
+ if (value.resume && (value.harness !== "claude" || !value.account || value.computer))
144
+ context.addIssue({ code: "custom", message: "resume switches a Claude conversation on its own computer to another account: harness claude, an account, and no computer." });
142
145
  });
143
146
  const MOVE_WAIT_MS = 5 * 60_000;
144
147
  /** The live session in a pane, by the pane id the terminal shows. */
@@ -167,7 +170,8 @@ export async function moveSession(input, options = {}) {
167
170
  if (peer && target.server !== peer.server)
168
171
  throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
169
172
  const to = { harness: data.harness, ...(data.account ? { account: data.account } : {}), ...(data.model ? { model: data.model } : {}), ...(data.effort ? { effort: data.effort } : {}) };
170
- move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}) })).move);
173
+ move = object((await request("/v1/sessions/move", { target, to: moveToSchema.parse(to), ...(options.agent ? { origin: "agent" } : {}), ...(data.id ? { id: data.id } : {}),
174
+ ...(data.resume ? { continuation: "resume" } : {}) })).move);
171
175
  if (data.wait !== false && typeof move.id === "string") {
172
176
  const until = Date.now() + (options.waitMs ?? MOVE_WAIT_MS);
173
177
  while (!settled(move) && Date.now() < until) {
@@ -4,6 +4,13 @@ export declare function newPairingCode(): string;
4
4
  /** Codes are typed as ABC-234 or abc234; both mean the same code. */
5
5
  export declare function normalizeCode(code: string): string;
6
6
  export declare function pairingProof(code: string, label: "phone" | "computer", ...parts: string[]): string;
7
+ /**
8
+ * The short check a phone that typed the code shows to confirm: the first
9
+ * eight characters of the host key fingerprint, as "abcd efgh". A typed code
10
+ * alone could be guessed by someone on the network during pairing; matching
11
+ * this shows the phone reached this computer. Same as the app's `checkCode`.
12
+ */
13
+ export declare function pairingCheckCode(fingerprint: string | undefined | null): string | null;
7
14
  /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
8
15
  export declare function keyFingerprint(publicKeyLine: string): string | undefined;
9
16
  export declare function hostFingerprint(file?: string): Promise<string | undefined>;
@@ -32,6 +39,12 @@ export interface PairingSession {
32
39
  done: Promise<Paired>;
33
40
  close(): void;
34
41
  }
42
+ /** A phone that typed the code, waiting for the person at the computer to allow it. */
43
+ export interface PairingApproval {
44
+ device: "ios" | "android";
45
+ name?: string;
46
+ check: string | null;
47
+ }
35
48
  /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
36
49
  export declare function startPairing(options: {
37
50
  code: string;
@@ -42,10 +55,19 @@ export declare function startPairing(options: {
42
55
  port?: number;
43
56
  timeoutMs?: number;
44
57
  sshDirectory?: string;
58
+ /**
59
+ * Asked before a phone that typed the code is authorized: a typed code can
60
+ * be cracked from a captured request, so the person at the computer allows
61
+ * the phone whose key check matches the one it shows. Without it, typed
62
+ * pairing is refused.
63
+ */
64
+ approve?: (phone: PairingApproval) => Promise<boolean>;
45
65
  }): Promise<PairingSession>;
46
66
  export declare const PAIR_USAGE = "phren pair [--minutes <1-30>] [--port <n>] [--no-install] | phren pair --scope gitboy-read|gitboy-write --key <public-key-file|-> [--no-install]";
47
67
  /** The authorized_keys line for a scoped key: no PTY, no forwarding, its own forced command. */
48
68
  export declare function scopedKeyLine(scope: GatewayScope, publicKey: string): string;
49
69
  /** Authorize a server's key for one scope. Options on the supplied line are discarded and rebuilt. */
50
70
  export declare function acceptScopedKey(scope: GatewayScope, input: string, sshDirectory?: string): Promise<string>;
71
+ /** A name safe to print in a terminal: control and format characters dropped, at most 80 characters. */
72
+ export declare function printableName(name: string): string;
51
73
  export declare function runPair(args: string[], version: string): Promise<number>;
@@ -37,6 +37,18 @@ function sameProof(expected, received) {
37
37
  const a = Buffer.from(expected), b = Buffer.from(received);
38
38
  return a.length === b.length && timingSafeEqual(a, b);
39
39
  }
40
+ /**
41
+ * The short check a phone that typed the code shows to confirm: the first
42
+ * eight characters of the host key fingerprint, as "abcd efgh". A typed code
43
+ * alone could be guessed by someone on the network during pairing; matching
44
+ * this shows the phone reached this computer. Same as the app's `checkCode`.
45
+ */
46
+ export function pairingCheckCode(fingerprint) {
47
+ if (!fingerprint?.startsWith("SHA256:"))
48
+ return null;
49
+ const body = fingerprint.slice("SHA256:".length);
50
+ return body.length >= 8 ? `${body.slice(0, 4)} ${body.slice(4, 8)}` : null;
51
+ }
40
52
  /** OpenSSH's SHA256 fingerprint of a public key line, as the phone computes it. */
41
53
  export function keyFingerprint(publicKeyLine) {
42
54
  const blob = publicKeyLine.trim().split(/\s+/)[1];
@@ -91,10 +103,12 @@ export function pairingURL(offer) {
91
103
  const request = z.object({
92
104
  v: z.literal(1), publicKey: z.string().max(512), proof: z.string().max(128),
93
105
  device: z.enum(["ios", "android"]).default("ios"), name: z.string().max(80).optional(),
106
+ typed: z.boolean().optional(),
94
107
  });
95
108
  /** Listen for one phone. Resolves once its key is authorized; rejects on timeout or too many bad proofs. */
96
109
  export async function startPairing(options) {
97
110
  let failures = 0, finished = false, timer;
111
+ let approvals = Promise.resolve();
98
112
  let resolve, reject;
99
113
  const done = new Promise((yes, no) => { resolve = yes; reject = no; });
100
114
  const server = createServer((incoming, response) => { void handle(incoming, response); });
@@ -135,6 +149,21 @@ export async function startPairing(options) {
135
149
  setImmediate(() => finish(new Error("Too many wrong pairing codes; pairing closed. Run phren pair again.")));
136
150
  throw new BridgeError(403, "That pairing code doesn't match this computer.");
137
151
  }
152
+ if (input.typed) {
153
+ // One question at a time, each bound to its own phone: a single answer
154
+ // never allows two keys.
155
+ const ask = approvals.then(() => finished || incoming.socket.destroyed ? false
156
+ : options.approve ? options.approve({ device: input.device, name: input.name, check: pairingCheckCode(keyFingerprint(publicKey)) }) : false);
157
+ approvals = ask.catch(() => false);
158
+ const allowed = await ask;
159
+ if (finished)
160
+ throw new BridgeError(410, "Pairing is closed. Run phren pair again.");
161
+ // A phone that gave up while the question waited gets nothing written.
162
+ if (incoming.socket.destroyed)
163
+ return;
164
+ if (!allowed)
165
+ throw new BridgeError(403, "The computer didn't allow this phone. Run phren pair again and allow it there.");
166
+ }
138
167
  const comment = input.device === "android" ? "phren-android" : "phren-iphone";
139
168
  const encoded = publicKey.split(" ")[1];
140
169
  await appendAuthorizedKey(`restrict,pty,${forcedCommand} ${publicKey} ${comment}`, existing => existing.split(/\s+/).includes(encoded), "This phone key is already authorized with different options.", options.sshDirectory);
@@ -248,6 +277,44 @@ async function runScopedPair(args, version) {
248
277
  console.log(` Revoke: remove the ${SCOPE_KEY_COMMENT[scope]} line from ${path.join(homedir(), ".ssh/authorized_keys")}.`);
249
278
  return 0;
250
279
  }
280
+ /** A name safe to print in a terminal: control and format characters dropped, at most 80 characters. */
281
+ export function printableName(name) {
282
+ return name.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu, "").slice(0, 80);
283
+ }
284
+ /** How long the terminal waits for an answer: less than the phone waits, so a late yes never authorizes a phone that gave up. */
285
+ const APPROVAL_WAIT_MS = 100_000;
286
+ /**
287
+ * The terminal's say on a phone that typed the code; no terminal, no typed
288
+ * pairing. No answer in time is no, and Ctrl-C at the question cancels pairing.
289
+ */
290
+ async function askToAllow(phone, cancel) {
291
+ if (!process.stdin.isTTY) {
292
+ console.log("\n A phone typed the code, but there's no terminal here to allow it. Scan the QR code instead.");
293
+ return false;
294
+ }
295
+ const { createInterface } = await import("node:readline/promises");
296
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
297
+ const abort = new AbortController();
298
+ const timer = setTimeout(() => abort.abort(), APPROVAL_WAIT_MS);
299
+ prompt.on("SIGINT", () => { abort.abort(); cancel(); });
300
+ try {
301
+ // The name comes from the request: printed without control characters, so
302
+ // it can't hide or forge the check line with terminal escapes.
303
+ const name = phone.name ? printableName(phone.name) : "";
304
+ const who = name ? `"${name}"` : "A phone";
305
+ console.log(`\n ${who} typed the code. Its screen shows a key check${phone.check ? `; it should be: ${phone.check}` : "."}`);
306
+ const answer = await prompt.question(" Allow this phone? [y/N] ", { signal: abort.signal });
307
+ return /^y(es)?$/i.test(answer.trim());
308
+ }
309
+ catch {
310
+ console.log("\n Not allowed.");
311
+ return false;
312
+ }
313
+ finally {
314
+ clearTimeout(timer);
315
+ prompt.close();
316
+ }
317
+ }
251
318
  export async function runPair(args, version) {
252
319
  if (args.includes("--scope"))
253
320
  return runScopedPair(args, version);
@@ -286,7 +353,10 @@ export async function runPair(args, version) {
286
353
  console.error("No network address found. Connect to Wi-Fi or Tailscale and try again.");
287
354
  return 1;
288
355
  }
289
- const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000 });
356
+ let cancelPairing = () => { };
357
+ const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000,
358
+ approve: phone => askToAllow(phone, () => cancelPairing()) });
359
+ cancelPairing = () => session.close();
290
360
  const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
291
361
  const { renderUnicodeCompact } = await import("uqr");
292
362
  console.log(`\nConnect your phone to ${name}`);
@@ -294,6 +364,9 @@ export async function runPair(args, version) {
294
364
  console.log(renderUnicodeCompact(url, { border: 2 }));
295
365
  const typed = `${code.slice(0, 3)}-${code.slice(3)}`;
296
366
  console.log(`\n Can't scan? Choose "Enter code" and type: ${hosts[0]}${session.port === PAIR_PORT ? "" : `:${session.port}`} ${typed}`);
367
+ const check = pairingCheckCode(fingerprint);
368
+ if (check)
369
+ console.log(` The phone then asks you to match: Check: ${check}`);
297
370
  if (process.env.WSL_DISTRO_NAME) {
298
371
  console.log(`\n This is WSL: Windows may block inbound port ${session.port} (and SSH) from the phone. If it cannot connect, run once in an admin PowerShell:`);
299
372
  console.log(` New-NetFirewallHyperVRule -Name phren-pair -DisplayName "Phren pairing" -Direction Inbound -VMCreatorId '{40E0AC32-46A5-438A-A0B2-2B479E8F2E90}' -Protocol TCP -LocalPorts ${session.port},22`);
@@ -1,4 +1,6 @@
1
1
  import { type Json, type Provider, type Target } from "./protocol.js";
2
+ /** A delivery the agent's turn ended without: the reason the phone shows. */
3
+ export declare const TURN_ENDED_WITHOUT_IT = "The agent finished its turn without taking the message.";
2
4
  export type DeliveryOutcome = "delivered" | "pending";
3
5
  /** What a phone message is known to have become. `queued`: typed into the
4
6
  * pane and held by the agent until its turn ends. `failed` carries a reason
@@ -8,6 +10,7 @@ export type DeliveryState = "queued" | "delivered" | "failed";
8
10
  export interface TranscriptEntry {
9
11
  offset: number;
10
12
  hook: boolean;
13
+ at?: number;
11
14
  }
12
15
  export type TrackedState = DeliveryState | "unknown";
13
16
  export interface DeliveryStatus {
@@ -21,6 +24,9 @@ export declare const DELIVERY_RETENTION_MS: number;
21
24
  /** An agent that ended its turn after the message was typed and then stayed
22
25
  * idle this long without taking it has dropped it. */
23
26
  export declare const DELIVERY_GIVE_UP_MS = 30000;
27
+ /** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
28
+ * UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */
29
+ export declare const IN_FLIGHT_MS = 45000;
24
30
  /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
25
31
  * form of what Phren typed; compare the words, not the wrapping. Claude Code
26
32
  * also takes each attached picture's path line out of the text and puts an
@@ -43,6 +49,8 @@ export declare class PromptDeliveries {
43
49
  private writing;
44
50
  /** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
45
51
  private hookPanes;
52
+ /** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
53
+ private lastStop;
46
54
  private paneKey;
47
55
  private static open;
48
56
  /** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
@@ -69,6 +77,12 @@ export declare class PromptDeliveries {
69
77
  private open;
70
78
  /** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
71
79
  pending(target: Target, text: string): boolean;
80
+ /** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
81
+ private inFlight;
82
+ /** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
83
+ holding(target: Pick<Target, "server" | "pane" | "source">): boolean;
84
+ /** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
85
+ held(id: string, target: Pick<Target, "server" | "pane" | "source">): boolean;
72
86
  /** Wait again for a message `expect` reported pending, after a second Enter. */
73
87
  awaitLate(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
74
88
  private find;
@@ -102,6 +116,13 @@ export declare class PromptDeliveries {
102
116
  * callback for a row already claimed (the idle check settled it, the hook
103
117
  * came late) settles nothing more. */
104
118
  submitted(target: Target, prompt: string): Promise<void>;
119
+ /** Claude submits the messages it held while busy as one turn, joined by newlines, so no single message's
120
+ * hash matches the prompt. Each open message in the pane whose words are a run of whole lines of it settles,
121
+ * the longest run first at each line and the oldest of identical messages first, so "yes" never settles
122
+ * inside "yes, but later". Only hashes of the line runs are compared, never stored. Only messages still held
123
+ * (typed or queued) are matched: a failed one could take the lines of messages that are held, and a late
124
+ * take of a failed message stays its own hook's to report. */
125
+ private settleJoined;
105
126
  /** Marks `record` delivered, with the transcript entry that settled it when known. */
106
127
  private settle;
107
128
  /** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.