@phren/cli 0.3.35 → 0.3.37

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 (89) hide show
  1. package/dist/bridge/account-choice.d.ts +82 -0
  2. package/dist/bridge/account-choice.js +173 -0
  3. package/dist/bridge/account-failover.d.ts +57 -0
  4. package/dist/bridge/account-failover.js +181 -0
  5. package/dist/bridge/account-usage.d.ts +2 -0
  6. package/dist/bridge/account-usage.js +17 -2
  7. package/dist/bridge/agent-hooks.d.ts +11 -1
  8. package/dist/bridge/agent-hooks.js +56 -19
  9. package/dist/bridge/changes.js +18 -9
  10. package/dist/bridge/dispatch-command.js +3 -1
  11. package/dist/bridge/dispatch-returns.d.ts +12 -0
  12. package/dist/bridge/dispatch-returns.js +37 -6
  13. package/dist/bridge/dispatch.d.ts +31 -3
  14. package/dist/bridge/dispatch.js +68 -10
  15. package/dist/bridge/hand-off.d.ts +23 -1
  16. package/dist/bridge/hand-off.js +36 -3
  17. package/dist/bridge/health.js +3 -1
  18. package/dist/bridge/host-key.d.ts +16 -0
  19. package/dist/bridge/host-key.js +35 -0
  20. package/dist/bridge/launch-brief.d.ts +5 -0
  21. package/dist/bridge/launch-brief.js +21 -0
  22. package/dist/bridge/link.js +11 -4
  23. package/dist/bridge/owner-inbox-sources.d.ts +5 -0
  24. package/dist/bridge/owner-inbox-sources.js +94 -0
  25. package/dist/bridge/owner-inbox-view.js +20 -1
  26. package/dist/bridge/owner-inbox.d.ts +7 -3
  27. package/dist/bridge/owner-inbox.js +113 -69
  28. package/dist/bridge/pair.js +3 -2
  29. package/dist/bridge/peers.js +4 -2
  30. package/dist/bridge/schedule-launch.js +5 -1
  31. package/dist/bridge/schedule-watch.d.ts +3 -0
  32. package/dist/bridge/schedule-watch.js +27 -1
  33. package/dist/bridge/server-launch.js +6 -2
  34. package/dist/bridge/server-routes.js +5 -1
  35. package/dist/bridge/server.js +9 -23
  36. package/dist/bridge/sudo.d.ts +36 -6
  37. package/dist/bridge/sudo.js +180 -37
  38. package/dist/bridge/usage.d.ts +4 -2
  39. package/dist/bridge/usage.js +4 -2
  40. package/dist/bridge/worker-reports.d.ts +8 -1
  41. package/dist/bridge/worker-reports.js +28 -7
  42. package/dist/bridge-hook.mjs +7120 -6298
  43. package/dist/clanker.d.ts +54 -0
  44. package/dist/clanker.js +188 -0
  45. package/dist/cli/config.js +56 -0
  46. package/dist/cli/hooks-output.d.ts +1 -1
  47. package/dist/cli/hooks-output.js +28 -21
  48. package/dist/cli/hooks.js +1 -1
  49. package/dist/cli/namespaces-skills.js +2 -2
  50. package/dist/cli/namespaces-tasks.js +46 -7
  51. package/dist/cli/session-start.js +12 -3
  52. package/dist/cli/session-stop.js +9 -0
  53. package/dist/cli/team.js +3 -0
  54. package/dist/cli-handlers.js +7 -0
  55. package/dist/cli-registry.js +1 -0
  56. package/dist/data/task-format.d.ts +5 -1
  57. package/dist/data/task-format.js +13 -5
  58. package/dist/index.js +82 -50
  59. package/dist/init/init-configure.d.ts +2 -0
  60. package/dist/init/init-configure.js +12 -0
  61. package/dist/init/init-uninstall.js +21 -2
  62. package/dist/init/init.d.ts +2 -0
  63. package/dist/init/init.js +11 -3
  64. package/dist/init/preferences.d.ts +12 -0
  65. package/dist/init/teardown.js +18 -4
  66. package/dist/link/doctor.js +2 -2
  67. package/dist/link/link.js +9 -0
  68. package/dist/link/refresh.d.ts +10 -0
  69. package/dist/link/refresh.js +34 -0
  70. package/dist/mcp/local-index.d.ts +20 -0
  71. package/dist/mcp/local-index.js +39 -1
  72. package/dist/modules/registry.js +1 -1
  73. package/dist/shared/index.d.ts +14 -0
  74. package/dist/shared/index.js +88 -74
  75. package/dist/shared/retrieval.js +1 -1
  76. package/dist/skill/files.js +40 -11
  77. package/dist/skill/registry.d.ts +6 -0
  78. package/dist/skill/registry.js +21 -5
  79. package/dist/task/lifecycle.js +3 -1
  80. package/dist/tools/dispatch.js +7 -4
  81. package/dist/tools/finding.js +20 -11
  82. package/dist/tools/graph.d.ts +2 -0
  83. package/dist/tools/graph.js +2 -0
  84. package/dist/tools/search.d.ts +2 -0
  85. package/dist/tools/search.js +88 -6
  86. package/dist/tools/tasks.js +45 -0
  87. package/dist/tools/types.d.ts +3 -1
  88. package/dist/tools/types.js +3 -2
  89. package/package.json +1 -1
@@ -1,9 +1,9 @@
1
- import { createHash, randomUUID } from "node:crypto";
2
- import { lstat, readFile } from "node:fs/promises";
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstat, mkdir, readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { z } from "zod";
5
5
  import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, startingTargetSchema, computerName } from "./protocol.js";
6
- import { dispatchStatus } from "./dispatch.js";
6
+ import { tryFileLock } from "../governance/locks.js";
7
7
  const title = z.string().trim().min(1).max(500).refine(s => !/[\x00-\x1f\x7f]/.test(s));
8
8
  export const inboxTargetSchema = z.union([targetSchema, startingTargetSchema]);
9
9
  const itemSchema = z.object({
@@ -20,9 +20,15 @@ export const ownerInboxSchema = z.object({
20
20
  id: z.string().uuid().optional(), resolution: z.string().max(2000).optional(),
21
21
  includeResolved: z.boolean().optional(), computer: computerName.optional(),
22
22
  }).strict();
23
- const uuidOf = (source) => { const h = createHash("sha256").update(source).digest("hex"); return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-8${h.slice(17, 20)}-${h.slice(20, 32)}`; };
24
- /** Hook-owned inbox. Return reads do not resolve owner work. Live sources
25
- * disappearing are retained as no-longer-live until explicitly resolved. */
23
+ // Prompt prose, counters and timestamps are observations, not identities.
24
+ function sourceKey(row) {
25
+ const t = row.target;
26
+ return t ? JSON.stringify([row.computer ?? "local", t.server, t.workspace, t.tab, t.pane, t.source,
27
+ "session" in t ? t.session : t.startingToken, row.actionId ?? "waiting"])
28
+ : row.dispatch ? `dispatch:${row.dispatch}:${row.actionId ?? "waiting"}` : row.source;
29
+ }
30
+ /** Reconcile automatic work against current sources; manual work is owner-owned.
31
+ * The first reconciliation also migrates old stale/duplicate automatic rows. */
26
32
  export class OwnerInbox {
27
33
  sources;
28
34
  file;
@@ -42,76 +48,114 @@ export class OwnerInbox {
42
48
  }
43
49
  run(input) {
44
50
  const run = this.pending.then(async () => {
45
- const data = ownerInboxSchema.parse(input), rows = await this.read(), at = new Date().toISOString();
46
- const sources = [];
47
- for (const receipt of await dispatchStatus()) {
48
- const returned = receipt.returned;
49
- if (receipt.closedAt || !returned || !["needs-you", "blocked"].includes(returned.state))
50
- continue;
51
- if (receipt.worker && receipt.worker.state !== returned.state && !receipt.approval)
52
- continue;
53
- const actionId = receipt.approval?.actionId;
54
- sources.push({ source: `dispatch:${receipt.id}:${actionId ?? returned.at}`, kind: returned.state,
55
- title: (receipt.approval?.request ?? returned.question ?? returned.reply ?? `${receipt.label} needs input`).replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500),
56
- project: receipt.project, computer: receipt.computer, ...("session" in (receipt.target ?? {}) ? { target: receipt.target } : {}), dispatch: receipt.id, ...(actionId ? { actionId } : {}) });
57
- }
58
- for (const source of await this.sources()) {
59
- if (source.actionId && sources.some(other => other.actionId === source.actionId && JSON.stringify(other.target) === JSON.stringify(source.target)))
60
- continue;
61
- sources.push(source);
51
+ const data = ownerInboxSchema.parse(input);
52
+ // Wait asynchronously: another instance in this process must be able to
53
+ // finish its write while we contend, just like another CLI process.
54
+ await mkdir(path.dirname(this.file), { recursive: true, mode: 0o700 });
55
+ const deadline = Date.now() + 30_000;
56
+ let release = tryFileLock(this.file);
57
+ while (!release) {
58
+ if (Date.now() >= deadline)
59
+ throw new BridgeError(503, "The owner inbox is busy; retry the operation.");
60
+ await new Promise(resolve => setTimeout(resolve, 20));
61
+ release = tryFileLock(this.file);
62
62
  }
63
- let changed = false;
64
- const live = new Set(sources.map(s => s.source));
65
- for (const row of rows)
66
- if (row.source && row.live !== live.has(row.source)) {
67
- row.live = live.has(row.source);
68
- row.updatedAt = at;
69
- changed = true;
63
+ try {
64
+ const rows = await this.read(), at = new Date().toISOString();
65
+ let changed = false;
66
+ // Manual adds/resolves must work even when source discovery is offline.
67
+ if (data.action === "list") {
68
+ const observed = await this.sources();
69
+ const { sources, unavailableDispatches = [] } = Array.isArray(observed) ? { sources: observed } : observed;
70
+ const active = new Map(sources.map(source => [sourceKey(source), source]));
71
+ const retained = new Set();
72
+ const resolve = (row, reason) => {
73
+ row.state = "resolved";
74
+ row.live = false;
75
+ row.resolvedAt = at;
76
+ row.updatedAt = at;
77
+ row.resolution = reason;
78
+ changed = true;
79
+ };
80
+ for (const row of rows) {
81
+ if (row.kind === "manual")
82
+ continue;
83
+ // Retired history cannot suppress a later wait on the same pane.
84
+ // An owner dismissal remains live until its current wait ends.
85
+ if (row.state === "resolved" && !row.live)
86
+ continue;
87
+ const key = sourceKey(row), source = key ? active.get(key) : undefined;
88
+ const unavailable = !!row.dispatch && unavailableDispatches.includes(row.dispatch);
89
+ const live = !!source && !retained.has(key);
90
+ if (row.live !== live) {
91
+ row.live = live;
92
+ row.updatedAt = at;
93
+ changed = true;
94
+ }
95
+ if (!source) {
96
+ if (row.state === "open" && !unavailable)
97
+ resolve(row, "stale: source gone");
98
+ continue;
99
+ }
100
+ if (retained.has(key)) {
101
+ if (row.state === "open")
102
+ resolve(row, "duplicate: source");
103
+ continue;
104
+ }
105
+ retained.add(key);
106
+ if (row.state === "open" && JSON.stringify({ ...row, ...source }) !== JSON.stringify(row)) {
107
+ Object.assign(row, source, { updatedAt: at });
108
+ changed = true;
109
+ }
110
+ }
111
+ for (const [key, source] of active) {
112
+ if (retained.has(key))
113
+ continue;
114
+ if (rows.length >= 10000)
115
+ throw new BridgeError(409, "The owner inbox is full.");
116
+ rows.push(itemSchema.parse({ ...source, id: randomUUID(), state: "open", live: true, createdAt: at, updatedAt: at }));
117
+ changed = true;
118
+ }
70
119
  }
71
- for (const source of sources) {
72
- const existing = rows.find(row => row.source === source.source);
73
- if (existing)
74
- continue; // Resolved sources do not resurrect on a poll.
75
- if (rows.length >= 10000)
76
- throw new BridgeError(409, "The owner inbox is full.");
77
- rows.push(itemSchema.parse({ ...source, id: uuidOf(source.source), state: "open", live: true, createdAt: at, updatedAt: at }));
78
- changed = true;
79
- }
80
- if (data.action === "add") {
81
- if (!data.title)
82
- throw new BridgeError(400, "Name the owner inbox item.");
83
- const item = itemSchema.parse({ id: data.id ?? randomUUID(), kind: "manual", title: data.title, state: "open", createdAt: at, updatedAt: at, ...(data.project ? { project: data.project } : {}) });
84
- const prior = rows.find(row => row.id === item.id);
85
- if (prior && (prior.title !== item.title || prior.project !== item.project || prior.kind !== "manual"))
86
- throw new BridgeError(409, "This inbox id names another item.");
87
- if (!prior) {
88
- if (rows.length >= 10000)
89
- throw new BridgeError(409, "The owner inbox is full.");
90
- rows.push(item);
91
- changed = true;
120
+ if (data.action === "add") {
121
+ if (!data.title)
122
+ throw new BridgeError(400, "Name the owner inbox item.");
123
+ const item = itemSchema.parse({ id: data.id ?? randomUUID(), kind: "manual", title: data.title, state: "open", createdAt: at, updatedAt: at, ...(data.project ? { project: data.project } : {}) });
124
+ const prior = rows.find(row => row.id === item.id);
125
+ if (prior && (prior.title !== item.title || prior.project !== item.project || prior.kind !== "manual"))
126
+ throw new BridgeError(409, "This inbox id names another item.");
127
+ if (!prior) {
128
+ if (rows.length >= 10000)
129
+ throw new BridgeError(409, "The owner inbox is full.");
130
+ rows.push(item);
131
+ changed = true;
132
+ }
133
+ if (changed)
134
+ await atomicInPrivateDir(this.file, rows);
135
+ return { ok: true, item: prior ?? item };
92
136
  }
93
- if (changed)
94
- await atomicInPrivateDir(this.file, rows);
95
- return { ok: true, item: prior ?? item };
96
- }
97
- if (data.action === "resolve") {
98
- const item = rows.find(row => row.id === data.id);
99
- if (!item)
100
- throw new BridgeError(404, "No owner inbox item with that id.");
101
- if (item.state !== "resolved") {
102
- item.state = "resolved";
103
- item.resolvedAt = at;
104
- item.updatedAt = at;
105
- item.resolution = data.resolution;
106
- changed = true;
137
+ if (data.action === "resolve") {
138
+ const item = rows.find(row => row.id === data.id);
139
+ if (!item)
140
+ throw new BridgeError(404, "No owner inbox item with that id.");
141
+ if (item.state !== "resolved") {
142
+ item.state = "resolved";
143
+ item.resolvedAt = at;
144
+ item.updatedAt = at;
145
+ item.resolution = data.resolution;
146
+ changed = true;
147
+ }
148
+ if (changed)
149
+ await atomicInPrivateDir(this.file, rows);
150
+ return { ok: true, item };
107
151
  }
108
152
  if (changed)
109
153
  await atomicInPrivateDir(this.file, rows);
110
- return { ok: true, item };
154
+ return { ok: true, items: rows.filter(row => data.includeResolved || (row.state === "open" && (row.kind === "manual" || row.live === true))).sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
155
+ }
156
+ finally {
157
+ release();
111
158
  }
112
- if (changed)
113
- await atomicInPrivateDir(this.file, rows);
114
- return { ok: true, items: rows.filter(row => data.includeResolved || row.state === "open").sort((a, b) => a.createdAt.localeCompare(b.createdAt)) };
115
159
  });
116
160
  this.pending = run.catch(() => { });
117
161
  return run;
@@ -8,6 +8,7 @@ import path from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { z } from "zod";
10
10
  import { appendAuthorizedKey, publicComputerKey } from "./computers.js";
11
+ import { localHostKeyLine } from "./host-key.js";
11
12
  import { forcedCommand, install } from "./install.js";
12
13
  import { BridgeError, bridgeRoot } from "./protocol.js";
13
14
  // `phren pair` connects a phone in one scan. The QR code carries where to
@@ -42,8 +43,8 @@ export function keyFingerprint(publicKeyLine) {
42
43
  return undefined;
43
44
  return "SHA256:" + createHash("sha256").update(Buffer.from(blob, "base64")).digest("base64").replace(/=+$/, "");
44
45
  }
45
- export async function hostFingerprint(file = "/etc/ssh/ssh_host_ed25519_key.pub") {
46
- return keyFingerprint(await readFile(file, "utf8").catch(() => ""));
46
+ export async function hostFingerprint(file) {
47
+ return keyFingerprint((file ? await readFile(file, "utf8").catch(() => "") : await localHostKeyLine()) ?? "");
47
48
  }
48
49
  /** Addresses the phone can try, best first: Tailscale name and address, then LAN IPv4. */
49
50
  export async function pairingHosts() {
@@ -6,8 +6,10 @@ import { dump, load } from "js-yaml";
6
6
  import { z } from "zod";
7
7
  import { logger } from "../logger.js";
8
8
  import { hookRequest } from "./client.js";
9
- import { computerName, dispatchKeyPath, publicComputerKey } from "./computers.js";
10
- import { atomic, BridgeError, bridgeRoot, serverName, withErrorCode } from "./protocol.js";
9
+ import { dispatchKeyPath, publicComputerKey } from "./computers.js";
10
+ // computerName comes from protocol.js, where it is defined: through computers.js it can still be
11
+ // undefined when an import cycle (usage -> account-choice -> health -> peers) loads this file first.
12
+ import { atomic, BridgeError, bridgeRoot, computerName, serverName, withErrorCode } from "./protocol.js";
11
13
  const peerSchema = z.object({
12
14
  name: computerName,
13
15
  address: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9.:-]{0,252}$/),
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { finished as streamFinished } from "node:stream/promises";
6
6
  import { askpassEnv } from "./sudo.js";
7
7
  import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
8
+ import { pickClaudeAccount } from "./account-choice.js";
8
9
  import { fanoutRoot } from "./fanouts.js";
9
10
  import { pretrustFolder } from "./folder-trust.js";
10
11
  import { findPane, paneIdentity, servers, snapshot } from "./herdr.js";
@@ -104,7 +105,10 @@ export function headlessEnv(schedule, env = process.env) {
104
105
  return { ...env, ...claudeLaunchEnv(home) };
105
106
  }
106
107
  async function launchHeadless(context, store, started) {
107
- const env = headlessEnv(context.schedule);
108
+ // A Claude schedule that names no account runs under the one with the most room, as a Herdr launch does.
109
+ const choice = context.schedule.harness === "claude" && !context.schedule.account
110
+ ? await pickClaudeAccount(`Schedule "${context.schedule.name}"`).catch(() => undefined) : undefined;
111
+ const env = headlessEnv(choice ? { ...context.schedule, account: choice.account } : context.schedule);
108
112
  const root = fanoutRoot({ ...process.env, PHREN_PATH: store }), jobDir = path.join(root, context.runId);
109
113
  await mkdir(jobDir, { recursive: true, mode: 0o700 });
110
114
  const eventLog = "events.jsonl", now = new Date().toISOString();
@@ -54,6 +54,9 @@ export interface FinalTurn {
54
54
  }
55
55
  /** The public text of one assistant row, without reasoning or tool output. */
56
56
  export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
57
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
58
+ export declare const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
59
+ export declare const isClaudeUsageLimit: (error: string | undefined) => boolean;
57
60
  /** Claude Code background work a transcript line starts or ends, by task id:
58
61
  * a backgrounded Bash call, an async subagent or a Monitor start one; a
59
62
  * task-notification with a final status, or a TaskStop, ends it. A
@@ -99,6 +99,22 @@ function turnError(raw, source) {
99
99
  const error = object(object(raw.payload).error), message = typeof error.message === "string" ? error.message.replace(/\s+/g, " ").trim() : "";
100
100
  return message ? message.slice(0, 500) : undefined;
101
101
  }
102
+ /** How a Claude usage-limit error starts, so dispatch can tell it from any other failure (account-failover.ts). */
103
+ export const CLAUDE_USAGE_LIMIT = "Claude usage limit:";
104
+ export const isClaudeUsageLimit = (error) => !!error?.startsWith(CLAUDE_USAGE_LIMIT);
105
+ /** Claude Code's own record of a subscription limit ending the turn: a synthetic assistant row
106
+ * (`isApiErrorMessage`, `error: "rate_limit"`) whose text says which limit and when it resets,
107
+ * as "You've hit your session limit · resets 3pm". A transient 429 Claude Code retries by itself never ends the turn. */
108
+ function claudeUsageLimit(raw) {
109
+ if (raw.type !== "assistant" || raw.isApiErrorMessage !== true || raw.error !== "rate_limit")
110
+ return undefined;
111
+ const content = object(raw.message).content;
112
+ const text = (typeof content === "string" ? content : objects(content).filter(block => block.type === "text").map(block => String(block.text ?? "")).join(" "))
113
+ .replace(/\s+/g, " ").trim();
114
+ if (!/\b(?:hit your|usage limit|limit reached|out of (?:extra )?usage)\b/i.test(text) && !raw.quotaLimits)
115
+ return undefined;
116
+ return `${CLAUDE_USAGE_LIMIT} ${text || "the subscription refused the request"}`.slice(0, 500);
117
+ }
102
118
  /** The owner stopping a turn: Claude's interruption marker, Codex's aborted turn, Copilot's abort. */
103
119
  function turnInterrupted(raw, source) {
104
120
  if (source === "codex")
@@ -216,18 +232,28 @@ export function finalTurnFromLines(lines, source) {
216
232
  copilotFinal = false;
217
233
  continue;
218
234
  }
235
+ // The limit ends the turn; its own text is the error, not the worker's last reply.
236
+ const limit = source === "claude" ? claudeUsageLimit(raw) : undefined;
237
+ if (limit) {
238
+ completed = true;
239
+ interrupted = false;
240
+ error = limit;
241
+ continue;
242
+ }
219
243
  const text = publicAssistant(raw, source);
220
244
  if (text) {
221
245
  lastAssistant = text;
222
246
  completed = false;
223
247
  interrupted = false;
248
+ error = undefined;
224
249
  }
225
250
  if (source === "copilot" && raw.type === "assistant.message" && !raw.agentId)
226
251
  copilotFinal = object(raw.data).phase === "final_answer";
252
+ // Claude's turn_duration after its limit row keeps that error.
227
253
  if (turnEnded(raw, source, copilotFinal)) {
228
254
  completed = true;
229
255
  interrupted = false;
230
- error = turnError(raw, source);
256
+ error = turnError(raw, source) ?? (source === "claude" ? error : undefined);
231
257
  copilotFinal = false;
232
258
  }
233
259
  }
@@ -19,6 +19,7 @@ import { clearConductor, conductorPane, noteConductorSession, readRoleState, rec
19
19
  import { localNames } from "./computer-names.js";
20
20
  import { pretrustFolder } from "./folder-trust.js";
21
21
  import { claudeHome, claudeLaunchEnv, isAccountSlug, DEFAULT_ACCOUNT } from "./claude-accounts.js";
22
+ import { pickClaudeAccount } from "./account-choice.js";
22
23
  import { harnessInventoryWithin, hasUsable, launchCheckOff } from "./harnesses.js";
23
24
  import { paneAccountKey, recordPaneAccount } from "./pane-accounts.js";
24
25
  import { optionalHookPeers } from "./peers.js";
@@ -328,7 +329,7 @@ async function startSession(server, data, options) {
328
329
  const label = plainText(200).parse(data.label);
329
330
  const kind = z.enum(launchKinds).parse(data.kind);
330
331
  const effort = z.enum(launchEfforts).default("medium").parse(data.effort);
331
- const account = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
332
+ const named = data.account === undefined || data.account === null ? undefined : z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").parse(data.account);
332
333
  const permissionMode = z.enum(PERMISSION_MODES).optional().parse(data.permissionMode ?? undefined);
333
334
  if (permissionMode && role === "conductor")
334
335
  throw new BridgeError(400, "A conductor starts with its own permissions; permissionMode is for workers.");
@@ -362,6 +363,9 @@ async function startSession(server, data, options) {
362
363
  // Herdr 0.9.1 refuses a start timeout of 3000 ms or less (invalid_agent_timeout).
363
364
  const timeout = Math.min(120_000, Math.max(3_001, data.timeoutMs === undefined ? 45_000 : z.number().int().parse(data.timeoutMs)));
364
365
  // Checked before anything is created, so a refusal leaves no pane, worktree or brief file behind.
366
+ // A Claude launch that names no account runs under the signed-in one with the most room left.
367
+ const choice = kind === "claude" && named === undefined ? await pickClaudeAccount(`Launch "${label}"`).catch(() => undefined) : undefined;
368
+ const account = named ?? choice?.account;
365
369
  await requireAvailable(kind, account);
366
370
  const home = kind === "claude" && account && account !== DEFAULT_ACCOUNT ? claudeHome(account) : undefined;
367
371
  if (kind === "claude" && account && account !== DEFAULT_ACCOUNT && !home)
@@ -536,7 +540,7 @@ async function startSession(server, data, options) {
536
540
  await new JobRegistry().register({ pane: { server, pane: created.paneId, ...(created.workspaceId ? { workspace: created.workspaceId } : {}), agent: kind, label },
537
541
  ...(sessionId ? { session: sessionId } : {}), agent: kind, label, command: kind }).catch(() => undefined);
538
542
  }
539
- return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
543
+ return { ok: true, ...created, cwd, agent: kind, agentStatus, role, sessionId, target, ...(account ? { account } : {}), ...(choice ? { accountChoice: choice.reason } : {}), ...(permissionMode ? { permissionMode } : {}), ...(unchecked.length ? { unchecked } : {}),
540
544
  // The caller types the brief itself unless it went with the launch.
541
545
  ...(brief ? { briefLaunched: appServer ? briefTurn !== undefined : !!briefLaunch || !!servedBrief,
542
546
  briefState: appServer ? briefTurn ?? "unconfirmed" : served ? (servedBrief?.delivered ? "sent" : "uncertain") : briefLaunch ? "sent" : "unconfirmed" } : {}),
@@ -15,7 +15,7 @@ import { resolveCodeStore, CodeRoutes } from "./code-routes.js";
15
15
  import { dispatchProjectDirectory, dispatchStatus, originPaneSchema } from "./dispatch.js";
16
16
  import { hookWorkers } from "./dispatch-returns.js";
17
17
  import { remoteChildren } from "./dispatch-tree.js";
18
- import { briefArrival, briefId } from "./launch-brief.js";
18
+ import { briefArrival, briefId, readLaunchBrief } from "./launch-brief.js";
19
19
  import { listApprovalRules, changeApprovalRule } from "./approval-rules.js";
20
20
  import { addGrant, listNamedGrants, removeGrant } from "./grants.js";
21
21
  import { clearProjectAuthority, confirmAuthority, listConfirmations, projectAuthority, readAuthority, setProjectAuthority } from "./authority.js";
@@ -347,6 +347,10 @@ export function createRouteHandler(ctx) {
347
347
  case "/v1/dispatch/arrival":
348
348
  result = { arrival: await briefArrival(briefId.parse(url.searchParams.get("id"))) ?? null };
349
349
  break;
350
+ // Asked by the dispatching Hook when this computer's worker hit its usage limit and continues on another account.
351
+ case "/v1/dispatch/brief":
352
+ result = { text: await readLaunchBrief(briefId.parse(url.searchParams.get("id"))) ?? null };
353
+ break;
350
354
  case "/v1/approval-rules":
351
355
  result = { rules: await listApprovalRules(undefined, z.string().regex(/^[A-Za-z0-9+/]{43}=$/).optional().parse(url.searchParams.get("pairedKey") ?? undefined)) };
352
356
  break;
@@ -1,4 +1,7 @@
1
- import { OwnerInbox, inboxTargetSchema } from "./owner-inbox.js";
1
+ import { setChoiceReaders } from "./account-choice.js";
2
+ import { AccountFailover } from "./account-failover.js";
3
+ import { ownerInboxSources } from "./owner-inbox-sources.js";
4
+ import { OwnerInbox } from "./owner-inbox.js";
2
5
  import { closeFinishedWorker } from "./worker-close.js";
3
6
  import { isLocalComputer } from "./dispatch-hosts.js";
4
7
  import { hookPeers, peerRequest } from "./peers.js";
@@ -87,6 +90,8 @@ export async function serve(version, options = {}) {
87
90
  const agentHooks = new AgentHooks(undefined, modules, path.join(bridgeRoot(), "deliveries.json"));
88
91
  // Follows what dispatched workers do and tells the dispatching agent.
89
92
  const returns = dispatches ? new DispatchReturns({
93
+ // Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
94
+ failover: new AccountFailover({ rooms: () => dispatches.claudeRooms(), dispatch: (input, origin, continues) => dispatches.dispatch(input, origin, continues) }),
90
95
  localWorkers: hookWorkers(agentHooks),
91
96
  close: async (receipt) => {
92
97
  const data = { target: receipt.target, dispatch: receipt.id, turn: receipt.closePending.turn };
@@ -111,28 +116,7 @@ export async function serve(version, options = {}) {
111
116
  if ("approvalPush" in activeCapabilities) {
112
117
  Object.defineProperty(activeCapabilities, "approvalPush", { enumerable: true, get: () => approvalPushCapability(agentHooks.push.status) });
113
118
  }
114
- const inbox = dispatches ? new OwnerInbox(async () => {
115
- const items = [];
116
- for (const server of await recentServers()) {
117
- const name = String(server.session), state = await sharedSnapshot(name, 4000);
118
- for (const pane of objects(state.panes)) {
119
- const chat = await paneChatState(name, pane, { tokenWhenIdentified: false }).catch(() => ({}));
120
- const parsed = inboxTargetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id, source: pane.agent,
121
- ...(chat.sessionId ? { session: chat.sessionId } : { starting: true, startingToken: chat.startingToken }) });
122
- if (!parsed.success)
123
- continue;
124
- const target = parsed.data, approval = "session" in target ? agentHooks.workerApproval(target) : undefined, question = "session" in target ? agentHooks.servedQuestion(target) : undefined, terminal = "session" in target ? agentHooks.terminalPrompt(target) : undefined;
125
- const request = approval?.request ?? (question ? "The worker has a question for the owner." : undefined) ?? terminal?.message
126
- ?? (["blocked", "waiting"].includes(String(pane.agent_status)) ? `${pane.agent} needs terminal input.` : undefined);
127
- if (!request)
128
- continue;
129
- const source = `prompt:${JSON.stringify(target)}:${approval?.actionId ?? JSON.stringify(question ?? terminal)}`;
130
- items.push({ source, kind: "blocked", title: String(request).replace(/[\x00-\x1f\x7f]+/g, " ").slice(0, 500), target,
131
- ...(approval?.actionId ? { actionId: approval.actionId } : {}) });
132
- }
133
- }
134
- return items;
135
- }) : undefined;
119
+ const inbox = dispatches ? new OwnerInbox(() => ownerInboxSources(agentHooks)) : undefined;
136
120
  const modelCatalog = options.modelCatalog ?? new ModelCatalog();
137
121
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
138
122
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
@@ -150,6 +134,8 @@ export async function serve(version, options = {}) {
150
134
  }) : undefined;
151
135
  const contextUsage = new WorkspaceContextUsage();
152
136
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
137
+ // A Claude launch that names no account runs under the one with the most room (account-choice.ts).
138
+ setChoiceReaders({ usage: () => accountUsage.limits(true) });
153
139
  const resources = new ResourceMonitor();
154
140
  const tabActivity = new TabActivityStore();
155
141
  const codexQuestions = new CodexQuestions(undefined, codexServers);
@@ -1,4 +1,5 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
+ import { type Socket } from "node:net";
2
3
  import { type Json } from "./protocol.js";
3
4
  /**
4
5
  * sudo with no terminal, answered from the phone.
@@ -13,9 +14,13 @@ import { type Json } from "./protocol.js";
13
14
  * running as root (euid 0, which no process of the owner's can fake), and the
14
15
  * asker's stdout is a pipe no other process of the owner's reads. The
15
16
  * connection is bound to that process too: on macOS its other end must be
16
- * held by the asker alone; on Linux the Hook writes the password straight into
17
- * the asker's stdout (`/proc/<pid>/fd/1`), so a connection that names another
18
- * process's pid gets nothing. It reads
17
+ * held by the asker alone. On Linux, where no unprivileged process can see a
18
+ * socket's peer, askpass listens on a fresh abstract socket and names it in
19
+ * its request; the listener must be held by the asker alone, and the Hook
20
+ * hands the password to that listener (with a one-time nonce askpass chose),
21
+ * which prints it to its own stdout. So a connection that names another
22
+ * process's pid gets nothing. (sudo creates askpass's stdout pipe as root,
23
+ * 0600, so the Hook cannot open `/proc/<pid>/fd/1` there.) It reads
19
24
  * that sudo's command line itself and pushes the request to the phone; `GET /v1/sudo` and the overview socket's `sudo` frame
20
25
  * list it. `POST /v1/sudo/answer` writes the password into the held
21
26
  * connection and forgets the request: the password is never logged, stored,
@@ -62,8 +67,8 @@ export interface SudoRequestView {
62
67
  askedAt: string;
63
68
  expiresAt: string;
64
69
  }
65
- /** What askpass gets: the password to print, word that the Hook wrote it into
66
- * askpass's stdout itself (Linux), or why not. */
70
+ /** What askpass gets: the password to print, word that the Hook handed it to
71
+ * askpass's delivery socket or wrote it into askpass's stdout (Linux), or why not. */
67
72
  export type SudoReply = {
68
73
  password: string;
69
74
  } | {
@@ -104,6 +109,31 @@ export declare function stdoutReaders(pid: number, allowed: number[]): Promise<"
104
109
  export declare function connectionHolders(pid: number, hookFd: number | undefined): Promise<"asker" | "other" | "unknown">;
105
110
  /** Linux: a process's start time, to tell it from a later one with its pid. */
106
111
  export declare function processStart(pid: number): Promise<string | undefined>;
112
+ /** Linux: the abstract socket askpass listens on for its password, and the
113
+ * nonce the Hook must send first. Both are random and chosen by askpass. */
114
+ export interface AskpassDelivery {
115
+ socket: string;
116
+ nonce: string;
117
+ }
118
+ export declare function deliveryFrom(value: unknown): AskpassDelivery | undefined;
119
+ export declare function newDelivery(): AskpassDelivery;
120
+ /** Linux: the inode of the listening abstract socket `name`, from
121
+ * `/proc/net/unix` (`Num RefCount Protocol Flags Type St Inode Path`; a
122
+ * listener has `__SO_ACCEPTCON`, 0x10000, in Flags). */
123
+ export declare function listeningInode(name: string, table?: () => Promise<string>): Promise<string | undefined>;
124
+ /** Linux: whether the listening socket `inode` is held by `pid` and no other
125
+ * process of the owner's. */
126
+ export declare function listenerHolders(pid: number, inode: string): Promise<"asker" | "other" | "unknown">;
127
+ /** Linux: the password handed to askpass's own listener, if askpass is still
128
+ * the process that was verified and its listener is still the one checked.
129
+ * The check runs after connecting: a name is bound to one listener at a time,
130
+ * so while the asker still holds that listener, this connection reached it. */
131
+ export declare function deliverToListener(pid: number, start: string, delivery: AskpassDelivery, inode: string, password: string, checks?: {
132
+ start?: typeof processStart;
133
+ inode?: typeof listeningInode;
134
+ holders?: typeof listenerHolders;
135
+ connect?: (path: string) => Socket;
136
+ }): Promise<SudoReply>;
107
137
  export interface AskerCheck {
108
138
  processes: (pid: number) => Promise<ProcessRecord | undefined>;
109
139
  stdout: (pid: number, allowed: number[]) => Promise<"sudo" | "other" | "unknown">;
@@ -139,7 +169,7 @@ export interface SudoBrokerOptions {
139
169
  /** Reads a process, to see whether sudo is still running; tests replace it. */
140
170
  processes?: (pid: number) => Promise<ProcessRecord | undefined>;
141
171
  /** The askpass chain check and how the password then reaches it; tests replace it. */
142
- verify?: (pid: number, hookFd: number | undefined) => Promise<Verified | {
172
+ verify?: (pid: number, hookFd: number | undefined, delivery?: AskpassDelivery) => Promise<Verified | {
143
173
  refused: string;
144
174
  }>;
145
175
  holdMs?: number;