@phren/cli 0.3.73 → 0.3.75

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.
@@ -1,5 +1,5 @@
1
1
  import { execFile } from "node:child_process";
2
- import { createHash, createHmac, randomInt, timingSafeEqual } from "node:crypto";
2
+ import { createHash, createHmac, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
3
3
  import { lstat, readFile } from "node:fs/promises";
4
4
  import { createServer } from "node:http";
5
5
  import { connect } from "node:net";
@@ -13,10 +13,11 @@ import { forcedCommand, install, scopedForcedCommand, scopedGatewayPath } from "
13
13
  import { isGatewayScope, SCOPE_KEY_COMMENT } from "./scoped-gateway.js";
14
14
  import { BridgeError, bridgeRoot } from "./protocol.js";
15
15
  // `phren pair` connects a phone in one scan. The QR code carries where to
16
- // reach this computer, its SSH host key fingerprint and a one-time code. The
17
- // phone makes its own key and posts the public half here with an HMAC keyed
18
- // by the code, so the code itself never crosses the network; this computer
19
- // answers with an HMAC over its fingerprint, which lets a phone that typed
16
+ // reach this computer, its SSH host key fingerprint, a one-time code and a
17
+ // scan secret. The phone makes its own key and posts the public half here
18
+ // with an HMAC keyed by the code and the secret (a phone that typed the code
19
+ // has only the code, and waits to be allowed at the computer), so neither
20
+ // crosses the network; this computer answers with an HMAC over its fingerprint, which lets a phone that typed
20
21
  // the code by hand trust the host key too. One success, five bad proofs or
21
22
  // the time limit closes the listener.
22
23
  const exec = promisify(execFile);
@@ -33,6 +34,20 @@ export function normalizeCode(code) {
33
34
  export function pairingProof(code, label, ...parts) {
34
35
  return createHmac("sha256", `phren-pair-v1:${normalizeCode(code)}`).update([label, ...parts].join("\n")).digest("base64url");
35
36
  }
37
+ /**
38
+ * The secret only the QR code and the phren://pair link carry: 128 random
39
+ * bits, never typed and never sent. The six-character code can be recovered
40
+ * from one captured request (about 30 bits, checked offline against its
41
+ * proof), so a proof made with the code alone always needs the person at the
42
+ * computer; a proof made with this secret shows the phone read the screen.
43
+ */
44
+ export function newScanSecret() {
45
+ return randomBytes(16).toString("base64url");
46
+ }
47
+ /** The proof of a phone that scanned: keyed by the code and the scan secret together. */
48
+ export function scanProof(code, secret, label, ...parts) {
49
+ return createHmac("sha256", `phren-pair-v2:${normalizeCode(code)}:${secret}`).update([label, ...parts].join("\n")).digest("base64url");
50
+ }
36
51
  function sameProof(expected, received) {
37
52
  const a = Buffer.from(expected), b = Buffer.from(received);
38
53
  return a.length === b.length && timingSafeEqual(a, b);
@@ -98,6 +113,8 @@ export function pairingURL(offer) {
98
113
  s: String(offer.sshPort), c: offer.code, n: offer.name });
99
114
  if (offer.fingerprint)
100
115
  query.set("fp", offer.fingerprint);
116
+ if (offer.secret)
117
+ query.set("k", offer.secret);
101
118
  return `phren://pair?${query.toString()}`;
102
119
  }
103
120
  const request = z.object({
@@ -143,13 +160,21 @@ export async function startPairing(options) {
143
160
  }
144
161
  const input = request.parse(JSON.parse(Buffer.concat(chunks).toString() || "{}"));
145
162
  const publicKey = publicComputerKey(input.publicKey);
146
- if (!sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
163
+ const scanned = options.scanSecret !== undefined
164
+ && sameProof(scanProof(options.code, options.scanSecret, "phone", publicKey), input.proof);
165
+ if (!scanned && !sameProof(pairingProof(options.code, "phone", publicKey), input.proof)) {
147
166
  failures++;
148
167
  if (failures >= MAX_FAILURES)
149
168
  setImmediate(() => finish(new Error("Too many wrong pairing codes; pairing closed. Run phren pair again.")));
150
169
  throw new BridgeError(403, "That pairing code doesn't match this computer.");
151
170
  }
152
- if (input.typed) {
171
+ if (!scanned) {
172
+ // The code alone never authorizes a key, whatever the request says
173
+ // about itself: `typed` only tells a phone that will wait for the
174
+ // answer from an app that scanned before the scan secret existed and
175
+ // gives up in seconds.
176
+ if (!input.typed)
177
+ throw new BridgeError(403, "This version of the Phren app can't pair by scanning with this computer. Update the app, or choose Enter code and type the code.");
153
178
  // One question at a time, each bound to its own phone: a single answer
154
179
  // never allows two keys.
155
180
  const ask = approvals.then(() => finished || claimed || incoming.socket.destroyed ? false
@@ -180,7 +205,8 @@ export async function startPairing(options) {
180
205
  }
181
206
  reply(response, 200, {
182
207
  v: 1, name: options.name, user: options.user, sshPort: options.sshPort, fingerprint: options.fingerprint ?? null,
183
- proof: pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
208
+ proof: scanned ? scanProof(options.code, options.scanSecret, "computer", options.fingerprint ?? "", publicKey)
209
+ : pairingProof(options.code, "computer", options.fingerprint ?? "", publicKey),
184
210
  });
185
211
  setImmediate(() => finish(undefined, { device: input.device, name: input.name, publicKey }));
186
212
  }
@@ -357,7 +383,7 @@ export async function runPair(args, version) {
357
383
  const sshPort = 22;
358
384
  if (!await sshListening(sshPort))
359
385
  console.log(`\n⚠ SSH isn't answering on this computer. ${sshHint()}\n Pairing can finish now; the phone connects once SSH is on.`);
360
- const code = newPairingCode();
386
+ const code = newPairingCode(), scanSecret = newScanSecret();
361
387
  const name = await computerDisplayName(), user = userInfo().username, fingerprint = await hostFingerprint();
362
388
  const hosts = await pairingHosts();
363
389
  if (!hosts.length) {
@@ -365,10 +391,10 @@ export async function runPair(args, version) {
365
391
  return 1;
366
392
  }
367
393
  let cancelPairing = () => { };
368
- const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000,
394
+ const session = await startPairing({ code, user, sshPort, fingerprint, name, port, timeoutMs: minutes * 60_000, scanSecret,
369
395
  approve: phone => askToAllow(phone, () => cancelPairing()) });
370
396
  cancelPairing = () => session.close();
371
- const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name });
397
+ const url = pairingURL({ hosts, port: session.port, user, sshPort, fingerprint, code, name, secret: scanSecret });
372
398
  const { renderUnicodeCompact } = await import("uqr");
373
399
  console.log(`\nConnect your phone to ${name}`);
374
400
  console.log(" In the Phren app: Agents → Add computer → Scan pairing code\n");
@@ -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;
@@ -711,6 +711,36 @@ export function skillBody(raw) {
711
711
  const QUEUED_IMAGE_LABEL = /\[Image #\d+\]/;
712
712
  const QUEUED_IMAGE_LABELS = /\[Image #\d+\]/g;
713
713
  const ATTACHED_FILES_FOOTER = /Attached files on this computer:\s*$/;
714
+ /** How much of one agent's message crosses: the terminal folds it too. */
715
+ const PEER_MESSAGE_LIMIT = 32_768;
716
+ const HANDBACK_FRAME = /^\[Subagent hand-back\][\s\S]*?The report follows:\n/;
717
+ /** A message another agent sent this session (a teammate, a subagent's
718
+ * hand-back or another Claude session), which Claude Code delivers as a hidden
719
+ * user row when the agent is idle, or a queued_command attachment mid-turn,
720
+ * both naming it with `origin.kind: "peer"`. The terminal shows it as
721
+ * "Message from @name"; only the sender's name and the words cross, never the
722
+ * envelope, socket path or ids. */
723
+ export function peerMessage(raw, includeSidechain = false) {
724
+ if (raw.isSidechain && !includeSidechain)
725
+ return undefined;
726
+ const attachment = object(raw.attachment);
727
+ const origin = raw.type === "user" ? object(raw.origin)
728
+ : raw.type === "attachment" && attachment.type === "queued_command" ? object(attachment.origin) : {};
729
+ if (origin.kind !== "peer" || typeof origin.body !== "string")
730
+ return undefined;
731
+ const handback = origin.handback === true;
732
+ // A hand-back's body opens with the harness's framing and indents the
733
+ // report two spaces; the report itself is carried alongside when it fits.
734
+ const text = handback && typeof origin.handbackReportText === "string" ? origin.handbackReportText
735
+ : handback && HANDBACK_FRAME.test(origin.body) ? origin.body.replace(HANDBACK_FRAME, "").replace(/^ {2}/gm, "")
736
+ : origin.body;
737
+ if (!text.trim())
738
+ return undefined;
739
+ const name = typeof origin.name === "string" ? origin.name.replace(/[\p{Cc}\p{Cf}]+/gu, " ").trim().slice(0, 80) : "";
740
+ return { type: "phren_peer_message", timestamp: raw.timestamp, ...(typeof raw.uuid === "string" ? { uuid: raw.uuid } : {}),
741
+ name: name || "agent", ...(handback ? { handback: true } : {}),
742
+ text: text.length > PEER_MESSAGE_LIMIT ? text.slice(0, PEER_MESSAGE_LIMIT) + "\n…" : text };
743
+ }
714
744
  /** A phren UserPromptSubmit injection, as `{ type: "phren_hook_context",
715
745
  * parentUuid, content }`, or undefined for any other row. */
716
746
  export function phrenHookContext(raw, includeSidechain = false) {
@@ -721,6 +751,9 @@ export function phrenHookContext(raw, includeSidechain = false) {
721
751
  // its hook output. Only whether it was a background notification crosses,
722
752
  // so the phone can leave a notification's injection out.
723
753
  if (attachment.type === "queued_command") {
754
+ const peer = peerMessage(raw, includeSidechain);
755
+ if (peer)
756
+ return peer;
724
757
  return { type: "phren_turn_input", timestamp: raw.timestamp, notification: attachment.commandMode === "task-notification" };
725
758
  }
726
759
  if (attachment.type !== "hook_success" || attachment.hookEvent !== "UserPromptSubmit")
@@ -877,6 +910,8 @@ export function visibleClaudeEvent(raw, includeSidechain = false, queue) {
877
910
  // origin says "task-notification" (sometimes wrapped in a system reminder).
878
911
  // It is a notice, not a prompt: normalize only its public envelope and never
879
912
  // let established notification provenance fall through as ordinary user text.
913
+ if (raw.type === "user" && object(raw.origin).kind === "peer")
914
+ return peerMessage(raw, includeSidechain);
880
915
  if (raw.type === "user") {
881
916
  const content = object(raw.message).content;
882
917
  const text = typeof content === "string" ? content