@phren/cli 0.3.58 → 0.3.61

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 (91) hide show
  1. package/README.md +1 -1
  2. package/dist/bridge/account-add.d.ts +30 -0
  3. package/dist/bridge/account-add.js +125 -19
  4. package/dist/bridge/account-failover.d.ts +9 -2
  5. package/dist/bridge/account-failover.js +1 -1
  6. package/dist/bridge/account-policy.d.ts +44 -0
  7. package/dist/bridge/account-policy.js +103 -0
  8. package/dist/bridge/account-pools.d.ts +35 -0
  9. package/dist/bridge/account-pools.js +171 -0
  10. package/dist/bridge/account-usage.d.ts +29 -4
  11. package/dist/bridge/account-usage.js +117 -8
  12. package/dist/bridge/agent-hook-callback.d.ts +6 -0
  13. package/dist/bridge/agent-hook-callback.js +10 -2
  14. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  15. package/dist/bridge/agent-hook-stores.js +13 -0
  16. package/dist/bridge/agent-hooks.d.ts +12 -2
  17. package/dist/bridge/agent-hooks.js +41 -4
  18. package/dist/bridge/claude-account-setup.d.ts +16 -0
  19. package/dist/bridge/claude-account-setup.js +46 -2
  20. package/dist/bridge/claude-accounts.d.ts +9 -0
  21. package/dist/bridge/claude-accounts.js +53 -15
  22. package/dist/bridge/claude-credits.d.ts +8 -2
  23. package/dist/bridge/claude-credits.js +52 -31
  24. package/dist/bridge/codex-threads.js +50 -2
  25. package/dist/bridge/command.js +12 -3
  26. package/dist/bridge/continuation-launch.d.ts +32 -0
  27. package/dist/bridge/continuation-launch.js +112 -1
  28. package/dist/bridge/dispatch-command.js +22 -0
  29. package/dist/bridge/dispatch-returns.d.ts +23 -0
  30. package/dist/bridge/dispatch-returns.js +57 -0
  31. package/dist/bridge/dispatch.d.ts +26 -4
  32. package/dist/bridge/dispatch.js +100 -11
  33. package/dist/bridge/git-host-gitlab.js +2 -1
  34. package/dist/bridge/git-hosts.d.ts +8 -0
  35. package/dist/bridge/git-hosts.js +16 -2
  36. package/dist/bridge/git-publish.js +18 -2
  37. package/dist/bridge/git.d.ts +8 -0
  38. package/dist/bridge/git.js +24 -1
  39. package/dist/bridge/hand-off-queue.d.ts +71 -0
  40. package/dist/bridge/hand-off-queue.js +38 -0
  41. package/dist/bridge/harnesses.d.ts +12 -0
  42. package/dist/bridge/harnesses.js +20 -4
  43. package/dist/bridge/helper.d.ts +54 -0
  44. package/dist/bridge/helper.js +186 -0
  45. package/dist/bridge/herdr.js +6 -2
  46. package/dist/bridge/hook-fast.d.ts +3 -0
  47. package/dist/bridge/hook-fast.js +10 -2
  48. package/dist/bridge/move-computers.d.ts +15 -1
  49. package/dist/bridge/move-computers.js +123 -26
  50. package/dist/bridge/owner-inbox-sources.d.ts +12 -1
  51. package/dist/bridge/owner-inbox-sources.js +127 -49
  52. package/dist/bridge/peers.d.ts +2 -0
  53. package/dist/bridge/peers.js +35 -4
  54. package/dist/bridge/prompt-deliveries.d.ts +69 -2
  55. package/dist/bridge/prompt-deliveries.js +342 -28
  56. package/dist/bridge/schedule-watch.js +17 -3
  57. package/dist/bridge/server-routes.d.ts +6 -0
  58. package/dist/bridge/server-routes.js +98 -14
  59. package/dist/bridge/server-stream.js +6 -4
  60. package/dist/bridge/server.js +2 -1
  61. package/dist/bridge/session-move.d.ts +70 -1
  62. package/dist/bridge/session-move.js +311 -19
  63. package/dist/bridge/simulators.d.ts +19 -0
  64. package/dist/bridge/simulators.js +93 -13
  65. package/dist/bridge/speech-live.js +132 -22
  66. package/dist/bridge/task-routes.d.ts +16 -16
  67. package/dist/bridge/terminal-herdr.js +6 -1
  68. package/dist/bridge/terminal-tmux.js +9 -5
  69. package/dist/bridge/terminal.d.ts +9 -2
  70. package/dist/bridge/transcript-claude.d.ts +3 -0
  71. package/dist/bridge/transcript-claude.js +175 -29
  72. package/dist/bridge/transcript-preview.d.ts +11 -2
  73. package/dist/bridge/transcript-preview.js +90 -8
  74. package/dist/bridge/turn-records.d.ts +19 -0
  75. package/dist/bridge/turn-records.js +78 -3
  76. package/dist/bridge/usage.d.ts +17 -0
  77. package/dist/bridge/usage.js +3 -2
  78. package/dist/bridge-hook.mjs +11964 -10084
  79. package/dist/cli-registry.js +2 -2
  80. package/dist/content/citation.d.ts +4 -0
  81. package/dist/content/citation.js +21 -21
  82. package/dist/data/task-contract.d.ts +4 -4
  83. package/dist/governance/policy.js +5 -2
  84. package/dist/index.js +1 -1
  85. package/dist/modules/registry.js +5 -5
  86. package/dist/project-config.d.ts +14 -0
  87. package/dist/project-config.js +40 -1
  88. package/dist/tools/dispatch.js +1 -1
  89. package/dist/tools/helper.d.ts +3 -0
  90. package/dist/tools/helper.js +44 -0
  91. package/package.json +1 -1
@@ -0,0 +1,54 @@
1
+ import { type ClaudeHome } from "./claude-accounts.js";
2
+ export declare const DEFAULT_HELPER_MODEL = "haiku";
3
+ export declare const HELPER_TIMEOUT_DEFAULT_S = 120;
4
+ export declare const HELPER_TIMEOUT_MAX_S = 600;
5
+ export interface HelperChoice {
6
+ project: string;
7
+ account: string;
8
+ model: string;
9
+ home: ClaudeHome;
10
+ pool?: string;
11
+ }
12
+ /**
13
+ * The project's helper account and model, checked: configured, an account on this computer, not `off`, and in
14
+ * the project's and this computer's allowed pools. Throws with what to change otherwise.
15
+ */
16
+ export declare function helperFor(phrenPath: string, project: string, env?: NodeJS.ProcessEnv): HelperChoice;
17
+ /** The helper's environment: the lead's, without anything naming another login, plus the account's home. */
18
+ export declare function helperEnv(home: ClaudeHome, env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
19
+ export interface HelperTokens {
20
+ input?: number;
21
+ output?: number;
22
+ cacheRead?: number;
23
+ cacheWrite?: number;
24
+ }
25
+ export interface HelperResult {
26
+ ok: boolean;
27
+ /** Claude's final reply, or what went wrong; capped at 64 KB. */
28
+ output: string;
29
+ project: string;
30
+ account: string;
31
+ model: string;
32
+ durationMs: number;
33
+ costUSD?: number;
34
+ /** Token counts, when Claude printed them (`usage` in its JSON answer). */
35
+ tokens?: HelperTokens;
36
+ sessionId?: string;
37
+ timedOut?: true;
38
+ truncated?: true;
39
+ }
40
+ export interface HelperRunOptions {
41
+ prompt: string;
42
+ cwd: string;
43
+ timeoutSeconds?: number;
44
+ /** Let the helper edit files (`--permission-mode acceptEdits`); otherwise tools that need a grant are refused. */
45
+ allowEdits?: boolean;
46
+ env?: NodeJS.ProcessEnv;
47
+ /** The MCP call's cancel: stops the run. */
48
+ signal?: AbortSignal;
49
+ now?: () => number;
50
+ }
51
+ /** Run one helper task and record it. Never throws for the run itself: a failed run is `ok: false`. */
52
+ export declare function runHelper(choice: HelperChoice, options: HelperRunOptions): Promise<HelperResult>;
53
+ /** `<bridge>/usage/helper-runs.jsonl`: one line per run (when, project, account, model, outcome, cost), never the prompt. */
54
+ export declare const helperRunsFile: () => string;
@@ -0,0 +1,186 @@
1
+ // Helper runs: one short headless Claude Code run (`claude -p`) for a lead agent, under the project's helper
2
+ // account and model, in the lead's folder. Lets a lead on a subscription hand small tasks to a cheaper model
3
+ // billed to another login (an API credit), which Claude Code's own subagents can't do: they always run under the
4
+ // lead's login. Opt-in per project; see docs/accounts.md.
5
+ //
6
+ // phren.project.yaml: helper: { account: <Claude account id>, model: haiku }
7
+ import { spawn } from "node:child_process";
8
+ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
9
+ import path from "node:path";
10
+ import { readProjectConfig } from "../project-config.js";
11
+ import { accountPolicy, poolAllowed, projectAllowedPools } from "./account-pools.js";
12
+ import { claudeHome, claudeLaunchEnv, isAccountSlug } from "./claude-accounts.js";
13
+ import { recordSessionCost } from "./claude-credits.js";
14
+ import { DISPATCH_ID_ENV } from "./launch-brief.js";
15
+ import { bridgeRoot, object } from "./protocol.js";
16
+ export const DEFAULT_HELPER_MODEL = "haiku";
17
+ export const HELPER_TIMEOUT_DEFAULT_S = 120;
18
+ export const HELPER_TIMEOUT_MAX_S = 600;
19
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9.:_[\]-]{0,63}$/;
20
+ const OUTPUT_MAX = 64 * 1024;
21
+ /** Claude's JSON answer is kept whole up to this, so a long reply is cut after parsing, not mid-JSON. */
22
+ const STDOUT_MAX = 4 * 1024 * 1024;
23
+ const LOG_MAX_BYTES = 512 * 1024;
24
+ const LOG_KEEP_LINES = 1000;
25
+ /** Variables that would make the helper sign in, bill or route as something other than its account's own login. */
26
+ const ACCOUNT_ENV = ["CLAUDE_CONFIG_DIR", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "ANTHROPIC_BASE_URL",
27
+ "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY"];
28
+ /** Variables that tie a process to the lead's pane or dispatch, so the helper's own hooks would report as the lead. */
29
+ const PANE_ENV = (name) => name.startsWith("HERDR_") || name === "TMUX" || name === "TMUX_PANE" || name === DISPATCH_ID_ENV;
30
+ /** Without allowEdits: tools that change files or run commands, refused even if a settings file allows them. */
31
+ const WRITE_TOOLS = "Bash,Edit,MultiEdit,Write,NotebookEdit";
32
+ /**
33
+ * The project's helper account and model, checked: configured, an account on this computer, not `off`, and in
34
+ * the project's and this computer's allowed pools. Throws with what to change otherwise.
35
+ */
36
+ export function helperFor(phrenPath, project, env = process.env) {
37
+ const raw = readProjectConfig(phrenPath, project).helper;
38
+ const setting = object(raw);
39
+ if (raw === undefined || setting.account === undefined) {
40
+ throw new Error(`Project ${project} has no helper account: set helper: { account: <account>, model: ${DEFAULT_HELPER_MODEL} } in its phren.project.yaml.`);
41
+ }
42
+ const account = setting.account;
43
+ if (typeof account !== "string" || !isAccountSlug(account))
44
+ throw new Error(`Project ${project}'s helper.account is not an account name.`);
45
+ if (setting.model !== undefined && (typeof setting.model !== "string" || !MODEL.test(setting.model)))
46
+ throw new Error(`Project ${project}'s helper.model is not a model name.`);
47
+ const model = typeof setting.model === "string" ? setting.model : DEFAULT_HELPER_MODEL;
48
+ // Homes as this computer has them, not as the lead's own CLAUDE_CONFIG_DIR would make "default".
49
+ const home = claudeHome(account, { ...env, CLAUDE_CONFIG_DIR: "" });
50
+ if (!home)
51
+ throw new Error(`There is no Claude account "${account}" on this computer (phren bridge accounts lists them).`);
52
+ // Read strictly: an accounts.yaml that can't be read must not turn the refusals off.
53
+ const policy = accountPolicy();
54
+ const { pool, role } = policy.settings[account] ?? {};
55
+ if (role === "off")
56
+ throw new Error(`Claude account ${account}'s role is off: it is never used automatically.`);
57
+ const where = pool ? `pool ${pool}` : "no pool";
58
+ const forProject = projectAllowedPools(phrenPath, project);
59
+ if (!poolAllowed(forProject, pool))
60
+ throw new Error(`Claude account ${account} (${where}) is not in project ${project}'s allowed pools: ${forProject.join(", ")}.`);
61
+ const forComputer = policy.allowedPools;
62
+ if (!poolAllowed(forComputer, pool))
63
+ throw new Error(`Claude account ${account} (${where}) is not in this computer's allowed pools: ${forComputer.join(", ")}.`);
64
+ return { project, account, model, home, ...(pool ? { pool } : {}) };
65
+ }
66
+ /** The helper's environment: the lead's, without anything naming another login, plus the account's home. */
67
+ export function helperEnv(home, env = process.env) {
68
+ const next = Object.fromEntries(Object.entries(env).filter(([name]) => !ACCOUNT_ENV.includes(name) && !PANE_ENV(name)));
69
+ return { ...next, ...claudeLaunchEnv(home), NO_COLOR: "1" };
70
+ }
71
+ /** `usage` from Claude's JSON answer as counts, or undefined when it printed none. */
72
+ function tokensOf(raw) {
73
+ const usage = object(raw);
74
+ const count = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
75
+ const tokens = {};
76
+ const set = (key, value) => { const n = count(value); if (n !== undefined)
77
+ tokens[key] = n; };
78
+ set("input", usage.input_tokens);
79
+ set("output", usage.output_tokens);
80
+ set("cacheRead", usage.cache_read_input_tokens);
81
+ set("cacheWrite", usage.cache_creation_input_tokens);
82
+ return Object.keys(tokens).length ? tokens : undefined;
83
+ }
84
+ function runClaude(args, input, cwd, env, timeoutMs, signal) {
85
+ return new Promise(resolve => {
86
+ let stdout = "", stderr = "", timedOut = false, settled = false;
87
+ const windows = process.platform === "win32";
88
+ // Its own process group, so a timeout or cancel also stops what it started.
89
+ const detached = !windows;
90
+ // An npm install on Windows is claude.cmd, which only a shell starts; the arguments are fixed flags and a checked model name.
91
+ const child = spawn("claude", args, { cwd, env, stdio: ["pipe", "pipe", "pipe"], detached, shell: windows });
92
+ const kill = () => {
93
+ try {
94
+ if (detached && child.pid)
95
+ process.kill(-child.pid, "SIGKILL");
96
+ else
97
+ child.kill("SIGKILL");
98
+ }
99
+ catch { /* Already gone. */ }
100
+ };
101
+ const onAbort = () => kill();
102
+ const finish = (exit) => {
103
+ if (settled)
104
+ return;
105
+ settled = true;
106
+ clearTimeout(timer);
107
+ signal?.removeEventListener("abort", onAbort);
108
+ resolve({ stdout, stderr, timedOut, ...exit });
109
+ };
110
+ const timer = setTimeout(() => { timedOut = true; kill(); }, timeoutMs);
111
+ if (signal?.aborted)
112
+ kill();
113
+ else
114
+ signal?.addEventListener("abort", onAbort, { once: true });
115
+ child.stdout.setEncoding("utf8");
116
+ child.stderr.setEncoding("utf8");
117
+ child.stdout.on("data", (chunk) => { if (stdout.length < STDOUT_MAX)
118
+ stdout += chunk; });
119
+ child.stderr.on("data", (chunk) => { if (stderr.length < OUTPUT_MAX)
120
+ stderr += chunk; });
121
+ child.on("error", error => finish({ code: null, spawnError: error.code === "ENOENT" ? "claude is not on this computer's PATH." : error.message }));
122
+ child.on("close", code => finish({ code }));
123
+ child.stdin.on("error", () => { });
124
+ child.stdin.end(input);
125
+ });
126
+ }
127
+ const cap = (text) => text.length > OUTPUT_MAX ? { text: `${text.slice(0, OUTPUT_MAX)}\n[output cut at 64 KB]`, truncated: true } : { text };
128
+ /** Run one helper task and record it. Never throws for the run itself: a failed run is `ok: false`. */
129
+ export async function runHelper(choice, options) {
130
+ const now = options.now ?? Date.now;
131
+ const seconds = Math.min(HELPER_TIMEOUT_MAX_S, Math.max(1, Math.round(options.timeoutSeconds ?? HELPER_TIMEOUT_DEFAULT_S)));
132
+ // No MCP servers from the account or the folder; read-only means the write tools are refused outright, whatever
133
+ // a settings file allows.
134
+ const args = ["-p", "--model", choice.model, "--output-format", "json", "--strict-mcp-config",
135
+ ...(options.allowEdits ? ["--permission-mode", "acceptEdits"] : ["--permission-mode", "default", "--disallowedTools", WRITE_TOOLS])];
136
+ const started = now();
137
+ const exit = await runClaude(args, options.prompt, options.cwd, helperEnv(choice.home, options.env), seconds * 1000, options.signal);
138
+ const durationMs = Math.max(0, now() - started);
139
+ const base = { project: choice.project, account: choice.account, model: choice.model, durationMs };
140
+ let result;
141
+ if (exit.spawnError) {
142
+ result = { ...base, ok: false, output: exit.spawnError };
143
+ }
144
+ else {
145
+ let parsed;
146
+ try {
147
+ const value = JSON.parse(exit.stdout);
148
+ if (value && typeof value === "object" && !Array.isArray(value))
149
+ parsed = value;
150
+ }
151
+ catch { /* Not Claude's JSON. */ }
152
+ const reply = typeof parsed?.result === "string" ? parsed.result : undefined;
153
+ const cost = typeof parsed?.total_cost_usd === "number" && Number.isFinite(parsed.total_cost_usd) && parsed.total_cost_usd >= 0 ? parsed.total_cost_usd : undefined;
154
+ const sessionId = typeof parsed?.session_id === "string" && /^[A-Za-z0-9-]{1,64}$/.test(parsed.session_id) ? parsed.session_id : undefined;
155
+ const cancelled = options.signal?.aborted === true;
156
+ const failed = cancelled || exit.timedOut || exit.code !== 0 || parsed?.is_error === true || reply === undefined;
157
+ const text = cancelled ? "The helper was cancelled." : exit.timedOut ? `The helper ran past ${seconds}s and was stopped.${reply ? `\n${reply}` : ""}`
158
+ : reply ?? (exit.stderr.trim() || exit.stdout.trim() || `claude exited with ${exit.code ?? "a signal"} and no reply.`);
159
+ const output = cap(text);
160
+ result = { ...base, ok: !failed, output: output.text, ...(output.truncated ? { truncated: true } : {}),
161
+ ...(cost !== undefined ? { costUSD: cost } : {}), ...(tokensOf(parsed?.usage) ? { tokens: tokensOf(parsed?.usage) } : {}),
162
+ ...(sessionId ? { sessionId } : {}), ...(exit.timedOut ? { timedOut: true } : {}) };
163
+ // The spend counts against the account's entered API credits, like its interactive sessions.
164
+ if (sessionId && cost !== undefined)
165
+ await recordSessionCost(choice.home, { session_id: sessionId, cost: { total_cost_usd: cost } }, new Date(now())).catch(() => undefined);
166
+ }
167
+ recordHelperRun(result, new Date(now()));
168
+ return result;
169
+ }
170
+ /** `<bridge>/usage/helper-runs.jsonl`: one line per run (when, project, account, model, outcome, cost), never the prompt. */
171
+ export const helperRunsFile = () => path.join(bridgeRoot(), "usage", "helper-runs.jsonl");
172
+ function recordHelperRun(result, at) {
173
+ const file = helperRunsFile();
174
+ const line = JSON.stringify({ at: at.toISOString(), project: result.project, account: result.account, model: result.model, ok: result.ok,
175
+ durationMs: result.durationMs, ...(result.costUSD !== undefined ? { costUSD: result.costUSD } : {}), ...(result.tokens ? { tokens: result.tokens } : {}),
176
+ ...(result.timedOut ? { timedOut: true } : {}) });
177
+ try {
178
+ mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
179
+ appendFileSync(file, `${line}\n`, { mode: 0o600 });
180
+ if (statSync(file).size > LOG_MAX_BYTES) {
181
+ const kept = readFileSync(file, "utf8").split("\n").filter(Boolean).slice(-LOG_KEEP_LINES);
182
+ writeFileSync(file, `${kept.join("\n")}\n`, { mode: 0o600 });
183
+ }
184
+ }
185
+ catch { /* The run's answer matters more than its log line. */ }
186
+ }
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  import { promisify } from "node:util";
9
9
  import { BridgeError, id, object, objects, requestID, serverName, provider, sessionId } from "./protocol.js";
10
10
  import { logger } from "../logger.js";
11
- import { recordedSession } from "./agent-hook-stores.js";
11
+ import { boundSession, recordedSession } from "./agent-hook-stores.js";
12
12
  import { paneRecord, recordTitle } from "./session-activity.js";
13
13
  import { tabActivityKey } from "./tab-activity.js";
14
14
  import { intervalFromEnv } from "./limits.js";
@@ -302,7 +302,11 @@ async function resolveIdentity(server, pane, fresh) {
302
302
  // A Codex pane on the Hook's own app-server: the registry follows `/new`
303
303
  // and `/resume` as they happen, while Herdr's report waits for a hook.
304
304
  const owned = pane.agent === "codex" && !!codexServers.forPane(server, String(pane.pane_id))?.threadId;
305
- if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success) {
305
+ // A `claude -p` run from the pane's shell inherits HERDR_*, and Herdr then
306
+ // reports that run's session for the pane long after it exits. When the
307
+ // Hook's own binding names another conversation, the processes decide.
308
+ if (pane.agent !== "copilot" && !owned && reported.kind === "id" && reported.agent === pane.agent && typeof reported.value === "string" && sessionId.safeParse(reported.value).success
309
+ && (pane.agent !== "claude" || [undefined, reported.value].includes(await boundSession(server, pane)))) {
306
310
  countIdentity("reported");
307
311
  return { sessionId: reported.value, noTranscriptLogs: false };
308
312
  }
@@ -11,6 +11,9 @@ export declare const fastHookPath: (versionDir: string) => string;
11
11
  * them, so once the budget is spent they give up and the tool runs.
12
12
  */
13
13
  export declare const TOOL_HOOK_BUDGET_MS = 5000;
14
+ /** Most background tasks a Stop's callback forwards, running ones first. Above the turn record's own
15
+ * limit (`STOP_TASKS_LIMIT`, turn-records.ts), so a list cut here is also marked cut there. */
16
+ export declare const STOP_TASKS_SENT = 1024;
14
17
  /** Keep permission replies and turn context, without turning tool callbacks into approvals. */
15
18
  export declare function hookOutput(event: string, result: string): string;
16
19
  /** The forwarder's source, with the ToolUse budget written in. */
@@ -25,6 +25,9 @@ export const fastHookPath = (versionDir) => path.join(versionDir, FAST_HOOK_FILE
25
25
  * them, so once the budget is spent they give up and the tool runs.
26
26
  */
27
27
  export const TOOL_HOOK_BUDGET_MS = 5_000;
28
+ /** Most background tasks a Stop's callback forwards, running ones first. Above the turn record's own
29
+ * limit (`STOP_TASKS_LIMIT`, turn-records.ts), so a list cut here is also marked cut there. */
30
+ export const STOP_TASKS_SENT = 1024;
28
31
  /** Keep permission replies and turn context, without turning tool callbacks into approvals. */
29
32
  export function hookOutput(event, result) {
30
33
  if (event === "PermissionRequest")
@@ -75,11 +78,16 @@ async function forward(place) {
75
78
  const dispatchId = (event === "SessionStart" || event === "UserPromptSubmit") && /^[A-Za-z0-9_-]{8,64}$/.test(env.PHREN_DISPATCH_ID ?? "") ? env.PHREN_DISPATCH_ID : undefined;
76
79
  const tasks = Array.isArray(value.background_tasks)
77
80
  ? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(plain(task).status))) : undefined;
78
- const stop = event !== "Stop" ? {} : { ...(tasks ? { background: tasks.length } : {}),
81
+ const listed = Array.isArray(value.background_tasks) ? value.background_tasks.map(plain)
82
+ .filter(task => typeof task.id === "string" && /^[A-Za-z0-9._-]{1,128}$/.test(task.id))
83
+ .map(task => ({ id: task.id, running: !["completed", "failed", "killed", "stopped"].includes(String(task.status)) }))
84
+ .sort((a, b) => Number(b.running) - Number(a.running)).slice(0, ${STOP_TASKS_SENT}) : undefined;
85
+ const stop = event !== "Stop" ? {} : { ...(tasks ? { background: tasks.length } : {}), ...(listed ? { backgroundTasks: listed } : {}),
79
86
  ...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
80
87
  const data = JSON.stringify({ target, event, ...(dispatchId ? { dispatchId } : {}),
81
88
  tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
82
- ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}), ...stop });
89
+ ...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
90
+ ...(event === "SessionStart" && typeof value.source === "string" ? { startSource: value.source.slice(0, 32) } : {}), ...stop });
83
91
  const socketPath = path.join(env.PHREN_BRIDGE_HOME || path.join(homedir(), ".local/share/phren/bridge"), "agent.sock");
84
92
  // A tool call's callback fits its budget from process start, or is skipped.
85
93
  const left = Math.floor(${toolBudgetMs} - performance.now());
@@ -28,11 +28,19 @@ declare const availability: z.ZodObject<{
28
28
  fiveHourLeft: z.ZodOptional<z.ZodNumber>;
29
29
  weekLeft: z.ZodOptional<z.ZodNumber>;
30
30
  resetsAt: z.ZodOptional<z.ZodString>;
31
+ pool: z.ZodOptional<z.ZodString>;
32
+ role: z.ZodOptional<z.ZodString>;
33
+ console: z.ZodOptional<z.ZodBoolean>;
34
+ poolRefused: z.ZodOptional<z.ZodString>;
31
35
  }, z.core.$strip>>>;
32
36
  }, z.core.$strip>>;
37
+ usagePending: z.ZodOptional<z.ZodLiteral<true>>;
38
+ usageError: z.ZodOptional<z.ZodString>;
33
39
  }, z.core.$strip>;
34
40
  export type MoveAvailability = z.infer<typeof availability>;
35
- export declare function localMoveAvailability(project: unknown, usage: () => Promise<Json>, conductor?: boolean): Promise<MoveAvailability>;
41
+ /** How long a computer's own Claude usage read may hold its continuation facts. */
42
+ export declare const MOVE_USAGE_TIMEOUT_MS = 5000;
43
+ export declare function localMoveAvailability(project: unknown, usage: () => Promise<Json>, conductor?: boolean, usageTimeoutMs?: number): Promise<MoveAvailability>;
36
44
  /** Exact verified names only; self also accepts the name health displays. */
37
45
  export declare function movePeer(computer: string | undefined, self?: string): Promise<DispatchHost | undefined>;
38
46
  export declare function peerMoveAvailability(peer: DispatchHost, project: string, conductor?: boolean): Promise<MoveAvailability>;
@@ -42,6 +50,12 @@ export declare function checkMovePeer(peer: DispatchHost, project: string, to: M
42
50
  computerId?: string;
43
51
  }>;
44
52
  export declare function moveComputers(project: unknown, self: string, local: () => Promise<MoveAvailability>, currentAccount?: string, conductor?: boolean): Promise<Json>;
53
+ /**
54
+ * Why this computer's Claude account `account` may not take a session in `cwd` (a same-computer move or
55
+ * account switch), or undefined: the pools of the project whose checkout holds `cwd` and this computer's own.
56
+ * Roles don't apply: the account is named by hand.
57
+ */
58
+ export declare function localPoolRefusal(cwd: string, account: string): Promise<string | undefined>;
45
59
  /** Re-read enrollment before every request that may transmit a brief. */
46
60
  export declare function currentMovePeer(captured: DispatchHost): Promise<DispatchHost>;
47
61
  export {};
@@ -1,24 +1,51 @@
1
1
  // Continuation destinations expose login labels and quota, never auth material.
2
2
  import { z } from "zod";
3
3
  import { dispatchProjectDirectory, PEER_COPILOT_REASON, projectName } from "./dispatch.js";
4
- import { chooseAccount } from "./account-choice.js";
4
+ import { choosePolicyAccount, computerRule, poolRefusal, projectRule, withPolicy } from "./account-policy.js";
5
+ import { accountPolicy } from "./account-pools.js";
5
6
  import { harnessInventoryWithin } from "./harnesses.js";
7
+ import { phrenStoreRoot } from "./transcripts.js";
6
8
  import { peerHost, isLocalComputer } from "./dispatch-hosts.js";
7
9
  import { hookPeers, optionalHookPeers } from "./peers.js";
8
10
  import { BridgeError } from "./protocol.js";
9
11
  const account = z.object({ id: z.string().max(64), label: z.string().max(200), usable: z.boolean(), signedIn: z.boolean(), email: z.string().optional(), plan: z.string().optional(), current: z.boolean().default(false),
10
12
  fiveHourResetsAt: z.string().optional(), weekResetsAt: z.string().optional(),
11
- fiveHourLeft: z.number().min(0).max(100).optional(), weekLeft: z.number().min(0).max(100).optional(), resetsAt: z.string().optional() });
13
+ fiveHourLeft: z.number().min(0).max(100).optional(), weekLeft: z.number().min(0).max(100).optional(), resetsAt: z.string().optional(),
14
+ // Pools and roles (account-policy.ts): `poolRefused` says why the project's or this computer's pools rule the login out.
15
+ pool: z.string().max(32).optional(), role: z.string().max(16).optional(), console: z.boolean().optional(), poolRefused: z.string().max(300).optional() });
12
16
  const availability = z.object({ computerId: z.string().uuid().optional(), hasCheckout: z.boolean(), harnesses: z.array(z.object({
13
17
  source: z.enum(["claude", "codex", "opencode", "copilot"]), usable: z.boolean(), reason: z.string().optional(), accounts: z.array(account).optional(),
14
- })) });
15
- export async function localMoveAvailability(project, usage, conductor = false) {
18
+ })),
19
+ /** The Claude usage read had not answered in time: accounts carry no room yet. */
20
+ usagePending: z.literal(true).optional(),
21
+ /** The Claude usage read failed: accounts carry no room. */
22
+ usageError: z.string().max(200).optional(),
23
+ });
24
+ /** How long a computer's own Claude usage read may hold its continuation facts. */
25
+ export const MOVE_USAGE_TIMEOUT_MS = 5_000;
26
+ /** The usage read, or why there is none: a read past `ms` is left running (it still warms the cache). */
27
+ async function usageWithin(usage, ms) {
28
+ let timer;
29
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve("late"), ms); timer.unref?.(); });
30
+ try {
31
+ const limits = await Promise.race([usage(), late]);
32
+ return limits === "late" ? { limits: {}, usagePending: true } : { limits };
33
+ }
34
+ catch {
35
+ return { limits: {}, usageError: "Claude usage could not be read on this computer." };
36
+ }
37
+ finally {
38
+ clearTimeout(timer);
39
+ }
40
+ }
41
+ export async function localMoveAvailability(project, usage, conductor = false, usageTimeoutMs = MOVE_USAGE_TIMEOUT_MS) {
16
42
  const name = project === null || project === undefined || project === "" ? undefined : projectName.parse(project);
17
- const [checkout, found, limits] = await Promise.all([
43
+ const [checkout, found, read] = await Promise.all([
18
44
  conductor ? Promise.resolve(true) : name ? dispatchProjectDirectory(name).then(() => true, () => false) : Promise.resolve(false),
19
45
  harnessInventoryWithin(2_500),
20
- usage().catch(() => ({})),
46
+ usageWithin(usage, usageTimeoutMs),
21
47
  ]);
48
+ const { limits } = read;
22
49
  const { claudeMoveAccounts } = await import("./hand-off.js");
23
50
  const rooms = claudeMoveAccounts(limits);
24
51
  const { claudeHomes, claudeAccountRef, claudeAccountEmail, claudeAccountSubscription } = await import("./claude-accounts.js");
@@ -30,11 +57,18 @@ export async function localMoveAvailability(project, usage, conductor = false) {
30
57
  const ref = claudeAccountRef(home), email = claudeAccountEmail(home), subscription = claudeAccountSubscription(home);
31
58
  accounts.push({ ...ref, usable: false, signedIn: false, ...(email ? { email } : {}), ...(subscription?.plan ? { plan: subscription.plan } : {}) });
32
59
  }
60
+ // The project's pools (a conductor move has none of its own) and this computer's.
61
+ const rules = [...(name && !conductor ? [projectRule(phrenStoreRoot(), name)] : []), computerRule("this computer", claude?.allowedPools, claude?.poolsUnreadable === true)];
62
+ const refusal = (login) => poolRefusal({ account: login.id, pool: login.pool }, rules);
33
63
  const inventory = claude ? discovered.map(row => row.source === "claude" ? { ...row, accounts } : row) : [...discovered, { source: "claude", installed: false, usable: false, accounts }];
34
- return availability.parse({ hasCheckout: checkout, harnesses: inventory.filter(row => row.source !== "phren").map(row => ({
64
+ return availability.parse({ hasCheckout: checkout, ...(read.usagePending ? { usagePending: true } : {}), ...(read.usageError ? { usageError: read.usageError } : {}),
65
+ harnesses: inventory.filter(row => row.source !== "phren").map(row => ({
35
66
  source: row.source, usable: row.usable, ...(row.accounts ? { accounts: row.accounts.map(login => {
36
67
  const room = row.source === "claude" ? rooms.find(item => item.id === login.id) : undefined;
37
- return { ...room, id: login.id, label: login.label ?? login.id, usable: login.usable && room?.fiveHourLeft !== 0 && room?.weekLeft !== 0, signedIn: login.signedIn, ...(login.email ? { email: login.email } : {}), ...(login.plan ? { plan: login.plan } : {}) };
68
+ const listed = login;
69
+ const refused = row.source === "claude" ? refusal({ id: login.id, pool: listed.pool }) : undefined;
70
+ return { ...room, id: login.id, label: login.label ?? login.id, usable: login.usable && room?.fiveHourLeft !== 0 && room?.weekLeft !== 0, signedIn: login.signedIn, ...(login.email ? { email: login.email } : {}), ...(login.plan ? { plan: login.plan } : {}),
71
+ ...(listed.pool ? { pool: listed.pool } : {}), ...(listed.role ? { role: listed.role } : {}), ...(listed.console ? { console: true } : {}), ...(refused ? { poolRefused: refused } : {}) };
38
72
  }) } : {}),
39
73
  })) });
40
74
  }
@@ -62,11 +96,26 @@ export async function peerMoveAvailability(peer, project, conductor = false) {
62
96
  throw new BridgeError(409, `Computer ${peer.name} is offline or cannot report continuation availability.`);
63
97
  }
64
98
  }
99
+ /** The login an unnamed Claude continuation takes there: most room, among those the pools allow and roles let
100
+ * be chosen automatically (`last-resort` only when no other fits). Without pools or roles, the most room as before. */
65
101
  function chosenLogin(accounts) {
66
- return chooseAccount(accounts.map(login => ({ account: login.id, usable: login.usable,
102
+ const refused = accounts.filter(login => login.poolRefused).map(login => `${login.id}: ${login.poolRefused}`);
103
+ const picked = choosePolicyAccount(accounts.filter(login => !login.poolRefused).map(login => withPolicy({ account: login.id, usable: login.usable,
67
104
  exhausted: login.fiveHourLeft === 0 || login.weekLeft === 0,
68
105
  fiveHour: { leftPercent: login.fiveHourLeft }, week: { leftPercent: login.weekLeft },
69
- }))).choice;
106
+ }, login)));
107
+ return { ...picked, skipped: [...refused, ...picked.skipped] };
108
+ }
109
+ /** The receiving computer's logins with the project's pools checked here too: a peer on an older Hook (no pools)
110
+ * or with a store that has not synced the project's list can't let a login through that this side refuses. */
111
+ function checkedHere(accounts, project, conductor) {
112
+ if (conductor)
113
+ return accounts;
114
+ const rule = projectRule(phrenStoreRoot(), project);
115
+ return accounts.map(login => {
116
+ const refused = login.poolRefused ?? poolRefusal({ account: login.id, pool: login.pool }, [rule]);
117
+ return refused ? { ...login, poolRefused: refused } : login;
118
+ });
70
119
  }
71
120
  export async function checkMovePeer(peer, project, to, conductor = false) {
72
121
  if (to.harness === "copilot")
@@ -74,8 +123,20 @@ export async function checkMovePeer(peer, project, to, conductor = false) {
74
123
  const facts = await peerMoveAvailability(peer, project, conductor);
75
124
  if (!facts.hasCheckout)
76
125
  throw new BridgeError(409, `Computer ${peer.name} has no checkout of ${project}.`);
77
- const harness = facts.harnesses.find(row => row.source === to.harness);
78
- const choice = to.harness === "claude" && !to.account && harness?.accounts ? chosenLogin(harness.accounts) : undefined;
126
+ // Without its room an exhausted login looks usable: wait for the read, which goes on and fills the peer's cache.
127
+ if (to.harness === "claude" && facts.usagePending)
128
+ throw new BridgeError(409, `Claude usage on ${peer.name} is still being read; try again in a moment.`);
129
+ const found = facts.harnesses.find(row => row.source === to.harness);
130
+ const harness = found?.source === "claude" && found.accounts ? { ...found, accounts: checkedHere(found.accounts, project, conductor) } : found;
131
+ const picked = to.harness === "claude" && !to.account && harness?.accounts ? chosenLogin(harness.accounts) : undefined;
132
+ const choice = picked?.choice;
133
+ // Pools rule a login out even when it is named; with pools or roles in play an unnamed move never falls back to default.
134
+ const named = to.account ? harness?.accounts?.find(row => row.id === to.account) : undefined;
135
+ if (named?.poolRefused)
136
+ throw new BridgeError(409, `Claude account ${to.account} on ${peer.name} may not do this work: ${named.poolRefused}.`, { code: "account_pool" });
137
+ if (picked && !choice && harness?.accounts?.some(login => login.poolRefused || login.role || login.console || login.pool)) {
138
+ throw new BridgeError(409, `No Claude account on ${peer.name} may continue this${picked.skipped.length ? `: ${picked.skipped.join("; ")}` : ""}.`.slice(0, 500), { code: "account_pool" });
139
+ }
79
140
  const login = harness?.accounts?.find(row => row.id === (to.account ?? choice?.account ?? "default"));
80
141
  if (!harness?.usable || (harness.accounts && !login?.usable) || login?.fiveHourLeft === 0 || login?.weekLeft === 0) {
81
142
  throw new BridgeError(409, `The harness or account is not usable on ${peer.name}.`);
@@ -86,24 +147,60 @@ export async function checkMovePeer(peer, project, to, conductor = false) {
86
147
  }
87
148
  export async function moveComputers(project, self, local, currentAccount, conductor = false) {
88
149
  const name = project === null || project === undefined || project === "" ? "" : projectName.parse(project);
150
+ // This computer's facts are read beside its peers', not before them: one slow read never holds the rest.
151
+ const localFacts = local();
152
+ localFacts.catch(() => undefined); // Still thrown below; not unhandled while the peers are listed.
89
153
  const { peers } = await optionalHookPeers();
90
- const here = await local();
91
- const publicFacts = (facts, remote = false) => ({ ...(facts.computerId ? { computerId: facts.computerId } : {}), hasCheckout: facts.hasCheckout, harnesses: facts.harnesses.map(row => ({
92
- source: row.source, usable: remote && row.source === "copilot" ? false : row.usable,
93
- ...(remote && row.source === "copilot" ? { reason: PEER_COPILOT_REASON } : {}),
94
- ...(row.source === "claude" && row.accounts ? { selectedAccount: chosenLogin(row.accounts)?.account } : {}), ...(row.accounts ? { accounts: row.accounts.map(({ signedIn: _signedIn, ...login }) => ({ ...login, current: !remote && row.source === "claude" && login.id === currentAccount })) } : {}),
95
- })) });
96
- const computers = await Promise.all(peers.map(async (peer) => {
97
- try {
98
- return { name: peer.name, self: false, online: true, ...publicFacts(await peerMoveAvailability(peerHost(peer), name, conductor), true) };
99
- }
100
- catch {
101
- return { name: peer.name, self: false, online: false, hasCheckout: false, harnesses: [] };
102
- }
103
- }));
154
+ const publicFacts = (facts, remote = false) => ({ ...(facts.computerId ? { computerId: facts.computerId } : {}), hasCheckout: facts.hasCheckout,
155
+ ...(facts.usagePending ? { usagePending: true } : {}), ...(facts.usageError ? { usageError: facts.usageError } : {}),
156
+ harnesses: facts.harnesses.map(listed => {
157
+ // A peer's logins as checkMovePeer judges them, so the phone's pick is the one the move makes.
158
+ const row = remote && name && listed.source === "claude" && listed.accounts ? { ...listed, accounts: checkedHere(listed.accounts, name, conductor) } : listed;
159
+ return {
160
+ source: row.source, usable: remote && row.source === "copilot" ? false : row.usable,
161
+ ...(remote && row.source === "copilot" ? { reason: PEER_COPILOT_REASON } : {}),
162
+ ...(row.source === "claude" && row.accounts ? { selectedAccount: chosenLogin(row.accounts).choice?.account } : {}), ...(row.accounts ? { accounts: row.accounts.map(({ signedIn: _signedIn, ...login }) => ({ ...login, current: !remote && row.source === "claude" && login.id === currentAccount })) } : {}),
163
+ };
164
+ }) });
165
+ const [here, computers] = await Promise.all([localFacts, Promise.all(peers.map(async (peer) => {
166
+ try {
167
+ return { name: peer.name, self: false, online: true, ...publicFacts(await peerMoveAvailability(peerHost(peer), name, conductor), true) };
168
+ }
169
+ catch {
170
+ return { name: peer.name, self: false, online: false, hasCheckout: false, harnesses: [] };
171
+ }
172
+ }))]);
104
173
  return { computers: [{ name: self, self: true, online: true, ...publicFacts(here) }, ...computers],
105
174
  localClaudeLogins: here.harnesses.find(row => row.source === "claude")?.accounts?.filter(login => login.signedIn).length ?? 0 };
106
175
  }
176
+ /**
177
+ * Why this computer's Claude account `account` may not take a session in `cwd` (a same-computer move or
178
+ * account switch), or undefined: the pools of the project whose checkout holds `cwd` and this computer's own.
179
+ * Roles don't apply: the account is named by hand.
180
+ */
181
+ export async function localPoolRefusal(cwd, account) {
182
+ const { getProjectDirs } = await import("../phren-paths.js");
183
+ const { realpath } = await import("node:fs/promises");
184
+ const path = await import("node:path");
185
+ const source = await realpath(cwd).catch(() => cwd);
186
+ let project, longest = 0;
187
+ for (const directoryName of getProjectDirs(phrenStoreRoot())) {
188
+ const name = path.basename(directoryName);
189
+ const directory = await dispatchProjectDirectory(name).catch(() => undefined);
190
+ if (directory && directory.length > longest && (source === directory || source.startsWith(directory + path.sep))) {
191
+ project = name;
192
+ longest = directory.length;
193
+ }
194
+ }
195
+ // An accounts.yaml that can't be read allows no pool here, as a dispatch to this computer would find.
196
+ let policy;
197
+ try {
198
+ policy = accountPolicy();
199
+ }
200
+ catch { /* Refused below. */ }
201
+ const rules = [...(project ? [projectRule(phrenStoreRoot(), project)] : []), computerRule("this computer", policy?.allowedPools, !policy)];
202
+ return poolRefusal({ account, pool: policy?.settings[account]?.pool }, rules);
203
+ }
107
204
  /** Re-read enrollment before every request that may transmit a brief. */
108
205
  export async function currentMovePeer(captured) {
109
206
  const current = await movePeer(captured.name).catch(() => undefined);
@@ -1,5 +1,16 @@
1
1
  import type { AgentHooks } from "./agent-hooks.js";
2
- import { type InboxSnapshot } from "./owner-inbox.js";
2
+ import { type Receipt } from "./dispatch.js";
3
+ import { type InboxSnapshot, type InboxSource } from "./owner-inbox.js";
3
4
  /** Read the actual panes and pending asks, never a stored inbox's live flag.
4
5
  * Called on reads and on the Hook's five-second activity tick. */
5
6
  export declare function ownerInboxSources(hooks: AgentHooks): Promise<InboxSnapshot>;
7
+ /** How often the inbox asks another computer about its receipts past the returns loop's watch, failed or not. */
8
+ export declare const AGED_CHECK_MS: number;
9
+ /** Forgets the hourly answers (tests). */
10
+ export declare function resetAgedChecks(): void;
11
+ /**
12
+ * A dispatch on another computer, within the returns loop's watch, as that loop last saw it, with no SSH of its
13
+ * own: waiting on an approval it forwarded (blocked, answerable by its `actionId`), blocked, or stopped with a
14
+ * question for the owner. A worker the loop saw back at work, or gone, has no row.
15
+ */
16
+ export declare function remoteSource(receipt: Receipt): InboxSource | undefined;