@phren/cli 0.3.57 → 0.3.59
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.
- package/README.md +1 -1
- package/dist/bridge/account-add.d.ts +30 -0
- package/dist/bridge/account-add.js +125 -19
- package/dist/bridge/account-failover.d.ts +9 -2
- package/dist/bridge/account-failover.js +1 -1
- package/dist/bridge/account-policy.d.ts +44 -0
- package/dist/bridge/account-policy.js +103 -0
- package/dist/bridge/account-pools.d.ts +35 -0
- package/dist/bridge/account-pools.js +171 -0
- package/dist/bridge/account-usage.d.ts +18 -0
- package/dist/bridge/account-usage.js +57 -1
- package/dist/bridge/agent-hook-callback.d.ts +6 -0
- package/dist/bridge/agent-hook-callback.js +10 -2
- package/dist/bridge/agent-hook-stores.d.ts +3 -0
- package/dist/bridge/agent-hook-stores.js +13 -0
- package/dist/bridge/agent-hooks.d.ts +12 -2
- package/dist/bridge/agent-hooks.js +41 -4
- package/dist/bridge/claude-account-setup.d.ts +16 -0
- package/dist/bridge/claude-account-setup.js +46 -2
- package/dist/bridge/claude-accounts.d.ts +9 -0
- package/dist/bridge/claude-accounts.js +53 -15
- package/dist/bridge/claude-credits.d.ts +5 -1
- package/dist/bridge/claude-credits.js +37 -29
- package/dist/bridge/command.js +12 -3
- package/dist/bridge/computer-identity.d.ts +4 -2
- package/dist/bridge/computer-identity.js +7 -3
- package/dist/bridge/conductor-group.d.ts +1 -1
- package/dist/bridge/conductor-group.js +2 -2
- package/dist/bridge/conductor-sets.d.ts +6 -0
- package/dist/bridge/conductor-sets.js +8 -2
- package/dist/bridge/dispatch-command.js +22 -0
- package/dist/bridge/dispatch-returns.d.ts +23 -0
- package/dist/bridge/dispatch-returns.js +57 -0
- package/dist/bridge/dispatch.d.ts +26 -4
- package/dist/bridge/dispatch.js +100 -11
- package/dist/bridge/git-host-gitlab.js +2 -1
- package/dist/bridge/hand-off-queue.d.ts +71 -0
- package/dist/bridge/hand-off-queue.js +38 -0
- package/dist/bridge/harnesses.d.ts +12 -0
- package/dist/bridge/harnesses.js +20 -4
- package/dist/bridge/helper.d.ts +54 -0
- package/dist/bridge/helper.js +186 -0
- package/dist/bridge/herdr.js +6 -2
- package/dist/bridge/hook-fast.d.ts +3 -0
- package/dist/bridge/hook-fast.js +10 -2
- package/dist/bridge/move-computers.d.ts +15 -1
- package/dist/bridge/move-computers.js +123 -26
- package/dist/bridge/prompt-deliveries.d.ts +29 -1
- package/dist/bridge/prompt-deliveries.js +146 -10
- package/dist/bridge/schedule-watch.js +17 -3
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +66 -6
- package/dist/bridge/server.js +8 -2
- package/dist/bridge/session-move.d.ts +59 -1
- package/dist/bridge/session-move.js +266 -18
- package/dist/bridge/simulator-stream.d.ts +118 -0
- package/dist/bridge/simulator-stream.js +284 -0
- package/dist/bridge/simulators.d.ts +31 -0
- package/dist/bridge/simulators.js +126 -40
- package/dist/bridge/speech-live.js +132 -22
- package/dist/bridge/task-routes.d.ts +16 -16
- package/dist/bridge/terminal-herdr.js +6 -1
- package/dist/bridge/terminal-tmux.js +9 -5
- package/dist/bridge/terminal.d.ts +9 -2
- package/dist/bridge/transcript-claude.d.ts +3 -0
- package/dist/bridge/transcript-claude.js +175 -29
- package/dist/bridge/transcript-preview.d.ts +11 -2
- package/dist/bridge/transcript-preview.js +90 -8
- package/dist/bridge/turn-records.d.ts +19 -0
- package/dist/bridge/turn-records.js +78 -3
- package/dist/bridge-hook.mjs +12129 -10324
- package/dist/cli-registry.js +2 -2
- package/dist/content/citation.d.ts +4 -0
- package/dist/content/citation.js +21 -21
- package/dist/data/task-contract.d.ts +4 -4
- package/dist/governance/policy.js +5 -2
- package/dist/index.js +1 -1
- package/dist/modules/registry.js +4 -4
- package/dist/project-config.d.ts +14 -0
- package/dist/project-config.js +40 -1
- package/dist/tools/helper.d.ts +3 -0
- package/dist/tools/helper.js +44 -0
- package/package.json +1 -1
|
@@ -20,6 +20,12 @@ export { NEAR_LIMIT_LEFT };
|
|
|
20
20
|
* one account. A window whose reset time has passed says `reset` and has no
|
|
21
21
|
* percent, and a report older than STALE_AFTER_MS is flagged stale.
|
|
22
22
|
*
|
|
23
|
+
* A Claude home with no readable login and nothing to show is a placeholder
|
|
24
|
+
* named only by its label ("work Team"). When that label names an account
|
|
25
|
+
* some computer reports (its own label, its email, or the email's name with
|
|
26
|
+
* its plan), the placeholder's computer joins that account's row instead of
|
|
27
|
+
* standing as a row of its own (`placeholderTarget`).
|
|
28
|
+
*
|
|
23
29
|
* `nearLimit` is information: the owner often wants quota used before it
|
|
24
30
|
* resets. Only `exhausted` (a window at 100% or refusing requests) rules an
|
|
25
31
|
* account out.
|
|
@@ -83,14 +89,64 @@ function accountName(usage) {
|
|
|
83
89
|
return usage.account?.email ?? (typeof named === "string" && named ? named : undefined)
|
|
84
90
|
?? (label && label.toLowerCase() !== (HARNESS_NAMES[usage.source] ?? usage.source).toLowerCase() ? label : undefined);
|
|
85
91
|
}
|
|
92
|
+
const words = (text) => text.trim().toLowerCase().replace(/\s+/g, " ");
|
|
93
|
+
/** A Claude home with no login Phren can read and no numbers: only its label names it. */
|
|
94
|
+
const isPlaceholder = (usage) => usage.source === "claude" && Boolean(usage.account?.key?.startsWith("claude:home:")) && !hasData(usage);
|
|
95
|
+
/**
|
|
96
|
+
* Which identified account a placeholder's label names, by index: one whose
|
|
97
|
+
* home carries the same label, else one whose email, email name, or email
|
|
98
|
+
* name and plan ("sam Team") the label spells. Two equally good matches name
|
|
99
|
+
* neither, and the provider's bare name ("Claude") names nothing.
|
|
100
|
+
*/
|
|
101
|
+
export function placeholderTarget(label, accounts, provider = "Claude") {
|
|
102
|
+
const wanted = words(label ?? "");
|
|
103
|
+
if (!wanted || wanted === words(provider))
|
|
104
|
+
return undefined;
|
|
105
|
+
const unique = (found) => found.length === 1 ? found[0] : undefined;
|
|
106
|
+
const same = accounts.flatMap((account, index) => account.labels.some(item => words(item) === wanted) ? [index] : []);
|
|
107
|
+
if (same.length)
|
|
108
|
+
return unique(same);
|
|
109
|
+
const spelled = accounts.flatMap((account, index) => {
|
|
110
|
+
const email = words(account.email ?? ""), name = email.split("@")[0], plan = words(account.plan ?? "");
|
|
111
|
+
if (!email)
|
|
112
|
+
return [];
|
|
113
|
+
if (wanted === email || wanted === name)
|
|
114
|
+
return [{ index, plan: false }];
|
|
115
|
+
if (!wanted.startsWith(`${name} `))
|
|
116
|
+
return [];
|
|
117
|
+
const rest = wanted.slice(name.length + 1);
|
|
118
|
+
// A login whose plan is unknown still answers to "name <plan>".
|
|
119
|
+
return !plan || rest === plan ? [{ index, plan: rest === plan }] : [];
|
|
120
|
+
});
|
|
121
|
+
const exact = spelled.filter(item => item.plan);
|
|
122
|
+
return unique((exact.length ? exact : spelled).map(item => item.index));
|
|
123
|
+
}
|
|
86
124
|
/** One row per account across every computer's report. */
|
|
87
125
|
export function mergeAccountUsage(reports, now = Date.now()) {
|
|
88
126
|
const groups = new Map();
|
|
127
|
+
const placeholders = [];
|
|
89
128
|
for (const report of reports)
|
|
90
129
|
for (const usage of report.accounts) {
|
|
130
|
+
if (isPlaceholder(usage)) {
|
|
131
|
+
placeholders.push({ computer: report.computer, usage });
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
91
134
|
const id = accountIdentity(usage, report.computer);
|
|
92
135
|
groups.set(id, [...groups.get(id) ?? [], { computer: report.computer, usage }]);
|
|
93
136
|
}
|
|
137
|
+
// A placeholder joins the account its label names; one naming none keeps its own group.
|
|
138
|
+
const identified = [...groups].filter(([, group]) => group[0].usage.source === "claude" && group.some(item => hasData(item.usage)) && !group[0].usage.account?.key?.startsWith("claude:home:"));
|
|
139
|
+
const named = identified.map(([, group]) => ({ labels: group.map(item => item.usage.account?.label ?? "").filter(Boolean),
|
|
140
|
+
email: group.find(item => item.usage.account?.email)?.usage.account?.email, plan: group.find(item => item.usage.subscription)?.usage.subscription?.plan }));
|
|
141
|
+
const joined = new Map();
|
|
142
|
+
for (const item of placeholders) {
|
|
143
|
+
const target = placeholderTarget(item.usage.account?.label, named);
|
|
144
|
+
const id = target === undefined ? accountIdentity(item.usage, item.computer) : identified[target][0];
|
|
145
|
+
if (target === undefined)
|
|
146
|
+
groups.set(id, [...groups.get(id) ?? [], item]);
|
|
147
|
+
else
|
|
148
|
+
joined.set(id, [...joined.get(id) ?? [], item]);
|
|
149
|
+
}
|
|
94
150
|
const accounts = [];
|
|
95
151
|
const empty = new Map();
|
|
96
152
|
for (const [id, group] of groups) {
|
|
@@ -122,7 +178,7 @@ export function mergeAccountUsage(reports, now = Date.now()) {
|
|
|
122
178
|
const availableAt = exhausted.filter(w => !w.id.startsWith("credit:")).map(w => w.resetsAt).filter((value) => Boolean(value)).sort().at(-1);
|
|
123
179
|
const availableIn = availableAt ? resetsIn(availableAt, now) : undefined;
|
|
124
180
|
const name = accountName(standing.usage);
|
|
125
|
-
const computers = reporting.map(item => ({ name: item.computer, ...(source === "claude" && item.usage.account?.id ? { account: item.usage.account.id } : {}) }))
|
|
181
|
+
const computers = [...reporting, ...joined.get(id) ?? []].map(item => ({ name: item.computer, ...(source === "claude" && item.usage.account?.id ? { account: item.usage.account.id } : {}) }))
|
|
126
182
|
.filter((item, index, list) => list.findIndex(other => other.name === item.name && other.account === item.account) === index);
|
|
127
183
|
accounts.push({
|
|
128
184
|
id, harness: source, name: HARNESS_NAMES[source] ?? source, ...(name ? { account: name } : {}), windows,
|
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
import { type Json, type Provider } from "./protocol.js";
|
|
2
2
|
/** The agent side of the Hook's callbacks: `hook <source>` reads the agent's
|
|
3
3
|
* payload and posts it to the daemon's local socket (agent-hooks.ts). */
|
|
4
|
+
/** A background task id as Claude Code writes them (an agent id, a shell id). */
|
|
5
|
+
export declare const BACKGROUND_TASK_ID: RegExp;
|
|
4
6
|
/** What a Stop payload says about the turn it ends: the harness's last
|
|
5
7
|
* assistant message (Claude, Codex) and, from Claude Code, the background
|
|
6
8
|
* tasks still in flight, which will wake the conversation again when they
|
|
7
9
|
* finish. Absent fields are left out, so the Hook falls back to the transcript. */
|
|
8
10
|
export declare function stopFacts(value: Json): {
|
|
9
11
|
background?: number;
|
|
12
|
+
backgroundTasks?: {
|
|
13
|
+
id: string;
|
|
14
|
+
running: boolean;
|
|
15
|
+
}[];
|
|
10
16
|
reply?: string;
|
|
11
17
|
};
|
|
12
18
|
/** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
|
|
@@ -2,7 +2,7 @@ import { request } from "node:http";
|
|
|
2
2
|
import { defaultPhrenPath } from "../shared.js";
|
|
3
3
|
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
4
4
|
import { object, provider, targetSchema } from "./protocol.js";
|
|
5
|
-
import { hookOutput, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
|
|
5
|
+
import { hookOutput, STOP_TASKS_SENT, TOOL_HOOK_BUDGET_MS } from "./hook-fast.js";
|
|
6
6
|
import { underCodexDaemon } from "./codex-daemon.js";
|
|
7
7
|
import { codexAutoReview } from "./codex-review-mode.js";
|
|
8
8
|
import { claudeHeadlessThread, codexForeignThread } from "./thread-origin.js";
|
|
@@ -12,6 +12,8 @@ import { CODEX_SERVER_ENV, codexServerId } from "./codex-servers.js";
|
|
|
12
12
|
import { localSocket } from "./agent-hook-stores.js";
|
|
13
13
|
/** The agent side of the Hook's callbacks: `hook <source>` reads the agent's
|
|
14
14
|
* payload and posts it to the daemon's local socket (agent-hooks.ts). */
|
|
15
|
+
/** A background task id as Claude Code writes them (an agent id, a shell id). */
|
|
16
|
+
export const BACKGROUND_TASK_ID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
15
17
|
/** What a Stop payload says about the turn it ends: the harness's last
|
|
16
18
|
* assistant message (Claude, Codex) and, from Claude Code, the background
|
|
17
19
|
* tasks still in flight, which will wake the conversation again when they
|
|
@@ -19,7 +21,13 @@ import { localSocket } from "./agent-hook-stores.js";
|
|
|
19
21
|
export function stopFacts(value) {
|
|
20
22
|
const tasks = Array.isArray(value.background_tasks)
|
|
21
23
|
? value.background_tasks.filter(task => !["completed", "failed", "killed", "stopped"].includes(String(object(task).status))) : undefined;
|
|
22
|
-
|
|
24
|
+
// Each task by id, running or not: a sub-agent's task id is its agent id, which the Hook's child tree keys on.
|
|
25
|
+
// Running ones first, so a cut list loses finished tasks before running ones.
|
|
26
|
+
const listed = Array.isArray(value.background_tasks) ? value.background_tasks.map(object)
|
|
27
|
+
.filter(task => typeof task.id === "string" && BACKGROUND_TASK_ID.test(task.id))
|
|
28
|
+
.map(task => ({ id: String(task.id), running: !["completed", "failed", "killed", "stopped"].includes(String(task.status)) }))
|
|
29
|
+
.sort((a, b) => Number(b.running) - Number(a.running)).slice(0, STOP_TASKS_SENT) : undefined;
|
|
30
|
+
return { ...(tasks ? { background: tasks.length } : {}), ...(listed ? { backgroundTasks: listed } : {}),
|
|
23
31
|
...(typeof value.last_assistant_message === "string" && value.last_assistant_message.trim() ? { reply: value.last_assistant_message.slice(0, 16_384) } : {}) };
|
|
24
32
|
}
|
|
25
33
|
/** One agent callback, run as `hook <source>`. Resolves "abandoned" when a
|
|
@@ -4,6 +4,9 @@ import { type Json } from "./protocol.js";
|
|
|
4
4
|
export declare const localSocket: () => string;
|
|
5
5
|
export declare const bindingPath: (server: string, pane: string) => string;
|
|
6
6
|
export declare function recordedSession(server: string, pane: Json, pids: number[]): Promise<string | undefined>;
|
|
7
|
+
/** The conversation the last callback recorded for this pane's terminal and
|
|
8
|
+
* agent, without the process check: a cheap cross-check of Herdr's report. */
|
|
9
|
+
export declare function boundSession(server: string, pane: Json): Promise<string | undefined>;
|
|
7
10
|
export interface PushBinding {
|
|
8
11
|
action: string;
|
|
9
12
|
expiresAt: number;
|
|
@@ -16,6 +16,19 @@ export async function recordedSession(server, pane, pids) {
|
|
|
16
16
|
return undefined;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
+
/** The conversation the last callback recorded for this pane's terminal and
|
|
20
|
+
* agent, without the process check: a cheap cross-check of Herdr's report. */
|
|
21
|
+
export async function boundSession(server, pane) {
|
|
22
|
+
try {
|
|
23
|
+
const value = object(JSON.parse(await readFile(bindingPath(server, String(pane.pane_id)), "utf8")));
|
|
24
|
+
if (value.terminal !== pane.terminal_id || value.source !== pane.agent)
|
|
25
|
+
return undefined;
|
|
26
|
+
return sessionId.parse(value.session);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
19
32
|
export class PushBindingStore {
|
|
20
33
|
now;
|
|
21
34
|
limit;
|
|
@@ -143,8 +143,12 @@ export declare class AgentHooks {
|
|
|
143
143
|
/** Keys the phone sends to a served OpenCode pane that its API answers
|
|
144
144
|
* better than the terminal: Esc declines a pending question or stops a
|
|
145
145
|
* working turn (`session.abort`), and a digit answers a pending
|
|
146
|
-
* single-question, single-choice set. False leaves the keys to the pane.
|
|
147
|
-
|
|
146
|
+
* single-question, single-choice set. False leaves the keys to the pane.
|
|
147
|
+
* With `abortTurn` (a move's "stop and hand off now"), Esc on a pending question declines it and then
|
|
148
|
+
* stops the turn too: a declined question alone lets the turn carry on. True only once the abort went. */
|
|
149
|
+
servedKeys(target: Target, keys: readonly string[], status: string, options?: {
|
|
150
|
+
abortTurn?: boolean;
|
|
151
|
+
}): Promise<boolean>;
|
|
148
152
|
/** A session's exact pane. A recorded binding carries the full target; when
|
|
149
153
|
* there is none, Herdr's explicit session identity names the pane. */
|
|
150
154
|
private resolveTarget;
|
|
@@ -293,6 +297,12 @@ export declare class AgentHooks {
|
|
|
293
297
|
/** Approve picks the dialog's yes/allow row (else its first), Deny its
|
|
294
298
|
* no/deny row (else Escape), typed as the pane's own keys. */
|
|
295
299
|
private answerDialog;
|
|
300
|
+
/** A held request the owner answered in the pane's own terminal: Claude
|
|
301
|
+
* moves on without closing the hook, so the hold would show its card until
|
|
302
|
+
* it times out. A later callback from the same conversation proves the
|
|
303
|
+
* dialog is gone: the call it held ran (its PostToolUse), the turn ended or
|
|
304
|
+
* took a new prompt, or the agent asked something else. */
|
|
305
|
+
private settleTerminalAnswered;
|
|
296
306
|
private dropPushBindings;
|
|
297
307
|
/** A server request from one of the Hook's own Codex app-servers: an
|
|
298
308
|
* approval card like a held PermissionRequest, pushed the same way, but
|
|
@@ -427,8 +427,10 @@ export class AgentHooks {
|
|
|
427
427
|
/** Keys the phone sends to a served OpenCode pane that its API answers
|
|
428
428
|
* better than the terminal: Esc declines a pending question or stops a
|
|
429
429
|
* working turn (`session.abort`), and a digit answers a pending
|
|
430
|
-
* single-question, single-choice set. False leaves the keys to the pane.
|
|
431
|
-
|
|
430
|
+
* single-question, single-choice set. False leaves the keys to the pane.
|
|
431
|
+
* With `abortTurn` (a move's "stop and hand off now"), Esc on a pending question declines it and then
|
|
432
|
+
* stops the turn too: a declined question alone lets the turn carry on. True only once the abort went. */
|
|
433
|
+
async servedKeys(target, keys, status, options = {}) {
|
|
432
434
|
if (target.source !== "opencode")
|
|
433
435
|
return false;
|
|
434
436
|
const entry = servedPane(target.server, target.pane);
|
|
@@ -440,7 +442,10 @@ export class AgentHooks {
|
|
|
440
442
|
if (question && escape) {
|
|
441
443
|
await client.rejectQuestion(question[0]).catch(() => { throw new BridgeError(409, "This question is no longer pending."); });
|
|
442
444
|
this.servedQuestions.delete(question[0]);
|
|
443
|
-
|
|
445
|
+
if (!options.abortTurn)
|
|
446
|
+
return true;
|
|
447
|
+
// A failed abort leaves Esc to the terminal, as below.
|
|
448
|
+
return client.abort(target.session).then(done => done === true, () => false);
|
|
444
449
|
}
|
|
445
450
|
if (question && keys.length === 1 && /^[1-9]$/.test(keys[0]) && question[1].questions.length === 1 && !question[1].questions[0].multiSelect) {
|
|
446
451
|
const option = question[1].questions[0].options[Number(keys[0]) - 1];
|
|
@@ -561,6 +566,7 @@ export class AgentHooks {
|
|
|
561
566
|
...(dispatch ? { dispatch } : {}),
|
|
562
567
|
...(body.event === "SessionStart" && typeof body.startSource === "string" ? { start: body.startSource } : {}),
|
|
563
568
|
...(typeof body.background === "number" ? { background: body.background } : {}),
|
|
569
|
+
...(body.event === "Stop" && Array.isArray(body.backgroundTasks) ? { backgroundTasks: body.backgroundTasks } : {}),
|
|
564
570
|
...(typeof body.reply === "string" ? { reply: body.reply } : {}),
|
|
565
571
|
...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
|
|
566
572
|
}
|
|
@@ -569,7 +575,7 @@ export class AgentHooks {
|
|
|
569
575
|
const questions = tool === "AskUserQuestion" ? terminalQuestions(body.input) : undefined;
|
|
570
576
|
const choice = questions ? questionChoice(questions, 0) : terminalChoice(body.input);
|
|
571
577
|
const summary = approvalSummary({ tool, input: body.input, question: tool === "AskUserQuestion" });
|
|
572
|
-
this.terminalPrompts.set(JSON.stringify(target), { tool,
|
|
578
|
+
this.terminalPrompts.set(JSON.stringify(target), { tool, input: body.input,
|
|
573
579
|
message: JSON.stringify(body.input || {}, null, 2).slice(0, 32_768), ...(choice ? { choice } : {}),
|
|
574
580
|
...summary,
|
|
575
581
|
...(questions ? { questions, questionIndex: 0 } : {}), at: Date.now() });
|
|
@@ -1423,6 +1429,36 @@ export class AgentHooks {
|
|
|
1423
1429
|
this.clearTerminalPrompt(dialog.target);
|
|
1424
1430
|
this.dropDialogPush(key);
|
|
1425
1431
|
}
|
|
1432
|
+
/** A held request the owner answered in the pane's own terminal: Claude
|
|
1433
|
+
* moves on without closing the hook, so the hold would show its card until
|
|
1434
|
+
* it times out. A later callback from the same conversation proves the
|
|
1435
|
+
* dialog is gone: the call it held ran (its PostToolUse), the turn ended or
|
|
1436
|
+
* took a new prompt, or the agent asked something else. */
|
|
1437
|
+
settleTerminalAnswered(target, body) {
|
|
1438
|
+
const event = String(body.event), key = JSON.stringify(target);
|
|
1439
|
+
const asked = event === "PermissionRequest" ? JSON.stringify([body.tool, body.input]) : undefined;
|
|
1440
|
+
const settled = (held) => ["Stop", "UserPromptSubmit"].includes(event)
|
|
1441
|
+
|| (event === "PermissionRequest" && JSON.stringify([held.tool, held.input]) !== asked)
|
|
1442
|
+
|| (event === "PostToolUse" && held.tool === body.tool && JSON.stringify(held.input) === JSON.stringify(body.input));
|
|
1443
|
+
for (const [action, held] of this.pending) {
|
|
1444
|
+
if (held.appServer || JSON.stringify(held.target) !== key || !settled(held))
|
|
1445
|
+
continue;
|
|
1446
|
+
clearTimeout(held.timer);
|
|
1447
|
+
this.pending.delete(action);
|
|
1448
|
+
this.pushedHolds.delete(action);
|
|
1449
|
+
this.dropPushBindings(action);
|
|
1450
|
+
if (!held.response.destroyed)
|
|
1451
|
+
held.response.end("{}");
|
|
1452
|
+
}
|
|
1453
|
+
const hold = this.releasedHolds.get(key), remembered = this.terminalPrompts.get(key);
|
|
1454
|
+
if (remembered && !remembered.questions?.length && settled({ tool: remembered.tool, input: remembered.input })) {
|
|
1455
|
+
this.terminalPrompts.delete(key);
|
|
1456
|
+
if (hold) {
|
|
1457
|
+
this.dropPushBindings(hold.action);
|
|
1458
|
+
this.releasedHolds.delete(key);
|
|
1459
|
+
}
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1426
1462
|
dropPushBindings(action) {
|
|
1427
1463
|
this.pushBindings.dropAction(action);
|
|
1428
1464
|
}
|
|
@@ -1610,6 +1646,7 @@ export class AgentHooks {
|
|
|
1610
1646
|
// had taken (before thread-origin.ts) back to the TUI's thread.
|
|
1611
1647
|
if (["SessionStart", "UserPromptSubmit", "Stop"].includes(String(body.event)) && target.source === "codex" && !daemon)
|
|
1612
1648
|
codexServers.follow(target.server, target.pane, target.session);
|
|
1649
|
+
this.settleTerminalAnswered(target, body);
|
|
1613
1650
|
if (body.event === "PreCompact") {
|
|
1614
1651
|
this.startCompacting(target);
|
|
1615
1652
|
res.end("{}");
|
|
@@ -7,8 +7,24 @@ export interface AddedAccount {
|
|
|
7
7
|
dir: string;
|
|
8
8
|
linked: string[];
|
|
9
9
|
created: boolean;
|
|
10
|
+
warning?: string;
|
|
10
11
|
}
|
|
12
|
+
/** A valid account name for `name`, or for the account's email when one is known: its user and the
|
|
13
|
+
* first part of its domain (`sam@example.com` is `sam-example`), lowercase, runs of anything else as one dash. */
|
|
14
|
+
export declare function suggestAccountSlug(name: string, email?: string): string;
|
|
15
|
+
/** Why `slug` is not an account name, with one that is. */
|
|
16
|
+
export declare function badAccountSlug(slug: string, email?: string): string;
|
|
17
|
+
/** `locked`: an ssh session on a Mac whose login keychain it cannot use (Claude keeps a Mac's login there,
|
|
18
|
+
* so a /login made in it is never saved). `unknown`: the check itself failed. A local session is never checked. */
|
|
19
|
+
export type KeychainState = "usable" | "locked" | "unknown";
|
|
20
|
+
export declare function sshKeychainState(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, exec?: (file: string, args: string[], options: {
|
|
21
|
+
timeout: number;
|
|
22
|
+
}) => Promise<unknown>): Promise<KeychainState>;
|
|
23
|
+
export declare const KEYCHAIN_UNKNOWN_WARNING = "Couldn't check this Mac's login keychain from this ssh session; if /login doesn't stick, run this on the Mac itself.";
|
|
24
|
+
export declare function keychainLockedMessage(slug: string, label?: string): string;
|
|
11
25
|
export declare function addClaudeAccount(slug: string, opts?: {
|
|
12
26
|
label?: string;
|
|
27
|
+
email?: string;
|
|
13
28
|
env?: NodeJS.ProcessEnv;
|
|
29
|
+
keychainState?: () => Promise<KeychainState>;
|
|
14
30
|
}): Promise<AddedAccount>;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
// `phren bridge accounts add`: a new Claude home that shares the default home's setup.
|
|
2
|
+
import { execFile } from "node:child_process";
|
|
2
3
|
import { chmod, lstat, mkdir, readFile, symlink } from "node:fs/promises";
|
|
3
4
|
import path from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
4
6
|
import { homeDir } from "../home-paths.js";
|
|
5
7
|
import { claudeHome, claudeHomes, DEFAULT_ACCOUNT, isAccountSlug, setAccountLabel } from "./claude-accounts.js";
|
|
6
8
|
import { atomic } from "./protocol.js";
|
|
@@ -43,15 +45,57 @@ export async function syncAccountMcpServers(env = process.env) {
|
|
|
43
45
|
changed.push(home.id);
|
|
44
46
|
return changed;
|
|
45
47
|
}
|
|
48
|
+
/** A valid account name for `name`, or for the account's email when one is known: its user and the
|
|
49
|
+
* first part of its domain (`sam@example.com` is `sam-example`), lowercase, runs of anything else as one dash. */
|
|
50
|
+
export function suggestAccountSlug(name, email) {
|
|
51
|
+
const [user, domain = ""] = email?.includes("@") ? email.trim().split("@") : [name];
|
|
52
|
+
const from = domain ? `${user}-${domain.split(".")[0]}` : user;
|
|
53
|
+
const slug = from.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+/, "").slice(0, 32).replace(/-+$/, "");
|
|
54
|
+
return !slug ? "account" : slug === DEFAULT_ACCOUNT ? "default-2" : slug;
|
|
55
|
+
}
|
|
56
|
+
/** Why `slug` is not an account name, with one that is. */
|
|
57
|
+
export function badAccountSlug(slug, email) {
|
|
58
|
+
return `"${slug}" is not an account name: use 1 to 32 lowercase letters, digits and dashes, and not "default". Try "${suggestAccountSlug(slug, email)}".`;
|
|
59
|
+
}
|
|
60
|
+
const run = promisify(execFile);
|
|
61
|
+
/** errSecInteractionNotAllowed (-25308): what the keychain answers a session it is locked to. */
|
|
62
|
+
const INTERACTION_NOT_ALLOWED = /User interaction is not allowed|-25308/;
|
|
63
|
+
export async function sshKeychainState(env = process.env, platform = process.platform, exec = run) {
|
|
64
|
+
if (platform !== "darwin" || !(env.SSH_CONNECTION || env.SSH_CLIENT))
|
|
65
|
+
return "usable";
|
|
66
|
+
try {
|
|
67
|
+
await exec("security", ["show-keychain-info"], { timeout: 5_000 });
|
|
68
|
+
return "usable";
|
|
69
|
+
}
|
|
70
|
+
catch (error) {
|
|
71
|
+
// Only the keychain's own refusal says it is locked; a timeout, a missing `security` or any other failure says nothing.
|
|
72
|
+
const { stderr, message } = (error ?? {});
|
|
73
|
+
return INTERACTION_NOT_ALLOWED.test(`${String(stderr ?? "")}\n${String(message ?? "")}`) ? "locked" : "unknown";
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
export const KEYCHAIN_UNKNOWN_WARNING = "Couldn't check this Mac's login keychain from this ssh session; if /login doesn't stick, run this on the Mac itself.";
|
|
77
|
+
export function keychainLockedMessage(slug, label) {
|
|
78
|
+
const labelArg = label ? ` --label '${label.replace(/'/g, "'\\''")}'` : "";
|
|
79
|
+
return "This Mac's login keychain is locked to this ssh session, so Claude can't save a login made here. "
|
|
80
|
+
+ `On the Mac itself, run: phren bridge accounts add ${slug}${labelArg}. `
|
|
81
|
+
+ "Or unlock the keychain for this session first (security unlock-keychain ~/Library/Keychains/login.keychain-db) and run it again.";
|
|
82
|
+
}
|
|
46
83
|
export async function addClaudeAccount(slug, opts = {}) {
|
|
47
84
|
const env = opts.env ?? process.env;
|
|
85
|
+
// A label given as the account's email names the account well.
|
|
86
|
+
const email = opts.email ?? (opts.label?.includes("@") ? opts.label : undefined);
|
|
48
87
|
if (slug === DEFAULT_ACCOUNT || !isAccountSlug(slug))
|
|
49
|
-
throw new Error(
|
|
88
|
+
throw new Error(badAccountSlug(slug, email));
|
|
50
89
|
const source = claudeHome(DEFAULT_ACCOUNT, env);
|
|
51
90
|
const dir = path.join(homeDir(env), `.claude-${slug}`);
|
|
52
91
|
if (dir === source.dir)
|
|
53
92
|
throw new Error(`~/.claude-${slug} is the default Claude home.`);
|
|
54
93
|
const created = !(await exists(dir));
|
|
94
|
+
// Checked before a new home is made: it would wait on a login this session can't save. Refreshing an
|
|
95
|
+
// existing home's links and label needs no keychain. A check that failed goes ahead, with a warning.
|
|
96
|
+
const keychain = created ? await (opts.keychainState ?? (() => sshKeychainState(env)))() : "usable";
|
|
97
|
+
if (keychain === "locked")
|
|
98
|
+
throw new Error(keychainLockedMessage(slug, opts.label));
|
|
55
99
|
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
56
100
|
await chmod(dir, 0o700); // An existing home keeps its login: tighten it too.
|
|
57
101
|
const linked = [];
|
|
@@ -65,5 +109,5 @@ export async function addClaudeAccount(slug, opts = {}) {
|
|
|
65
109
|
await mergeMcpServers(path.join(dir, ".claude.json"), await mcpServersOf(source.configFile));
|
|
66
110
|
if (opts.label)
|
|
67
111
|
await setAccountLabel(slug, opts.label);
|
|
68
|
-
return { id: slug, dir, linked, created };
|
|
112
|
+
return { id: slug, dir, linked, created, ...(keychain === "unknown" ? { warning: KEYCHAIN_UNKNOWN_WARNING } : {}) };
|
|
69
113
|
}
|
|
@@ -27,6 +27,15 @@ export declare function claudeLaunchEnv(home: ClaudeHome): Record<string, string
|
|
|
27
27
|
/** The config home a running Claude process uses, from its CLAUDE_CONFIG_DIR. */
|
|
28
28
|
export declare function claudeHomeOfEnv(value: string | undefined, env?: NodeJS.ProcessEnv): ClaudeHome | undefined;
|
|
29
29
|
export declare const accountsFile: () => string;
|
|
30
|
+
/** `accounts.yaml` as an object: empty when there is none (or it is blank), an error when it is there but is
|
|
31
|
+
* not a mapping, so a write never replaces what it couldn't read. */
|
|
32
|
+
export declare function parseAccountsYaml(text: string | undefined): Record<string, unknown>;
|
|
33
|
+
/**
|
|
34
|
+
* The one way `accounts.yaml` is changed (labels, credits, pools): reads it, applies `change`, and writes it back
|
|
35
|
+
* atomically. Writes in this process run one at a time, and each holds the file's lock against other processes
|
|
36
|
+
* (the CLI beside the Hook), so no write drops another's change. A file that can't be read is never replaced.
|
|
37
|
+
*/
|
|
38
|
+
export declare function updateAccountsFile(change: (parsed: Record<string, unknown>) => void): Promise<void>;
|
|
30
39
|
export declare function accountLabel(id: string, labels?: Record<string, string>): string;
|
|
31
40
|
export declare function setAccountLabel(id: string, label: string): Promise<void>;
|
|
32
41
|
/**
|
|
@@ -2,14 +2,15 @@
|
|
|
2
2
|
// ~/.claude is the "default" account and is launched without CLAUDE_CONFIG_DIR,
|
|
3
3
|
// so its keychain item and ~/.claude.json stay where Claude Code put them.
|
|
4
4
|
// Every ~/.claude-<slug> holding a .claude.json is another account. See docs/accounts.md.
|
|
5
|
-
import { createHash } from "node:crypto";
|
|
6
|
-
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
7
|
-
import { mkdir
|
|
5
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { mkdir } from "node:fs/promises";
|
|
8
8
|
import { spawn } from "node:child_process";
|
|
9
9
|
import path from "node:path";
|
|
10
10
|
import { dump, load } from "js-yaml";
|
|
11
|
+
import { withFileLock } from "../governance/locks.js";
|
|
11
12
|
import { claudeConfigDir, homeDir } from "../home-paths.js";
|
|
12
|
-
import {
|
|
13
|
+
import { bridgeRoot } from "./protocol.js";
|
|
13
14
|
import { claudePlan, monthlyAnniversary, subscriptionDate } from "./subscription.js";
|
|
14
15
|
export const DEFAULT_ACCOUNT = "default";
|
|
15
16
|
const SLUG = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
@@ -75,6 +76,50 @@ export function claudeHomeOfEnv(value, env = process.env) {
|
|
|
75
76
|
}
|
|
76
77
|
// ── labels (<bridge>/accounts.yaml) ─────────────────────────────────────────
|
|
77
78
|
export const accountsFile = () => path.join(bridgeRoot(), "accounts.yaml");
|
|
79
|
+
/** `accounts.yaml` as an object: empty when there is none (or it is blank), an error when it is there but is
|
|
80
|
+
* not a mapping, so a write never replaces what it couldn't read. */
|
|
81
|
+
export function parseAccountsYaml(text) {
|
|
82
|
+
if (text === undefined || !text.trim())
|
|
83
|
+
return {};
|
|
84
|
+
const parsed = load(text);
|
|
85
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
86
|
+
return parsed;
|
|
87
|
+
throw new Error(`${accountsFile()} is not a mapping; fix or remove it first.`);
|
|
88
|
+
}
|
|
89
|
+
let accountsWrites = Promise.resolve();
|
|
90
|
+
/**
|
|
91
|
+
* The one way `accounts.yaml` is changed (labels, credits, pools): reads it, applies `change`, and writes it back
|
|
92
|
+
* atomically. Writes in this process run one at a time, and each holds the file's lock against other processes
|
|
93
|
+
* (the CLI beside the Hook), so no write drops another's change. A file that can't be read is never replaced.
|
|
94
|
+
*/
|
|
95
|
+
export function updateAccountsFile(change) {
|
|
96
|
+
const run = accountsWrites.then(async () => {
|
|
97
|
+
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
98
|
+
const file = accountsFile();
|
|
99
|
+
withFileLock(file, () => {
|
|
100
|
+
let text;
|
|
101
|
+
try {
|
|
102
|
+
text = readFileSync(file, "utf8");
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (error.code !== "ENOENT")
|
|
106
|
+
throw error;
|
|
107
|
+
}
|
|
108
|
+
const parsed = parseAccountsYaml(text);
|
|
109
|
+
change(parsed);
|
|
110
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
111
|
+
try {
|
|
112
|
+
writeFileSync(temporary, dump(parsed), { mode: 0o600, flag: "wx" });
|
|
113
|
+
renameSync(temporary, file);
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
rmSync(temporary, { force: true });
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
accountsWrites = run.catch(() => undefined);
|
|
121
|
+
return run;
|
|
122
|
+
}
|
|
78
123
|
function readLabels() {
|
|
79
124
|
try {
|
|
80
125
|
const parsed = load(readFileSync(accountsFile(), "utf8"));
|
|
@@ -102,17 +147,10 @@ export async function setAccountLabel(id, label) {
|
|
|
102
147
|
const clean = label.trim();
|
|
103
148
|
if (!clean || clean.length > 40 || /[\u0000-\u001f]/.test(clean))
|
|
104
149
|
throw new Error("A label is 1 to 40 printable characters.");
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
parsed = raw;
|
|
110
|
-
}
|
|
111
|
-
catch { /* First label. */ }
|
|
112
|
-
const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {};
|
|
113
|
-
parsed.claude = { ...claude, [id]: clean };
|
|
114
|
-
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
115
|
-
await atomic(accountsFile(), dump(parsed), 0o600);
|
|
150
|
+
await updateAccountsFile(parsed => {
|
|
151
|
+
const claude = parsed.claude && typeof parsed.claude === "object" ? parsed.claude : {};
|
|
152
|
+
parsed.claude = { ...claude, [id]: clean };
|
|
153
|
+
});
|
|
116
154
|
}
|
|
117
155
|
const identityCache = new Map();
|
|
118
156
|
function oauthIdentity(configFile) {
|
|
@@ -26,7 +26,11 @@ export declare function addClaudeCredit(home: string, entry: {
|
|
|
26
26
|
export declare function removeClaudeCredit(home: string, id: string): Promise<boolean>;
|
|
27
27
|
/** Per-session costs from the status line, kept only for homes with a credit. */
|
|
28
28
|
export declare const costLedgerFile: (home: ClaudeHome) => string;
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Record one status-line render or helper run: the session's running total only grows, so the largest seen
|
|
31
|
+
* stands. Writes run one at a time in this process and under the ledger's lock across processes (the status
|
|
32
|
+
* line and the helper tool both write it), so none drops another's session.
|
|
33
|
+
*/
|
|
30
34
|
export declare function recordSessionCost(home: ClaudeHome, payload: unknown, now?: Date): Promise<void>;
|
|
31
35
|
/**
|
|
32
36
|
* Every session cost known for a home: the status-line ledger, plus the
|
|
@@ -5,11 +5,12 @@
|
|
|
5
5
|
// The estimate never reads billing; it can drift from the Console's balance.
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
8
|
-
import { mkdir
|
|
8
|
+
import { mkdir } from "node:fs/promises";
|
|
9
9
|
import path from "node:path";
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
10
|
+
import { load } from "js-yaml";
|
|
11
|
+
import { withFileLock } from "../governance/locks.js";
|
|
12
|
+
import { atomicInPrivateDir, bridgeRoot, object } from "./protocol.js";
|
|
13
|
+
import { accountsFile, isAccountSlug, updateAccountsFile } from "./claude-accounts.js";
|
|
13
14
|
const MAX_CREDITS = 16;
|
|
14
15
|
const MAX_SESSIONS = 4000;
|
|
15
16
|
const DAY = /^\d{4}-\d{2}-\d{2}$/;
|
|
@@ -56,23 +57,18 @@ export function claudeCredits(home) {
|
|
|
56
57
|
async function updateCredits(home, change) {
|
|
57
58
|
if (!isAccountSlug(home))
|
|
58
59
|
throw new Error(`"${home}" is not an account name: use lowercase letters, digits and dashes.`);
|
|
59
|
-
let
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
credits
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
parsed.credits = credits;
|
|
72
|
-
if (!Object.keys(credits).length)
|
|
73
|
-
delete parsed.credits;
|
|
74
|
-
await mkdir(bridgeRoot(), { recursive: true, mode: 0o700 });
|
|
75
|
-
await atomic(accountsFile(), dump(parsed), 0o600);
|
|
60
|
+
let next = [];
|
|
61
|
+
await updateAccountsFile(parsed => {
|
|
62
|
+
next = change(creditsOf(parsed, home));
|
|
63
|
+
const credits = { ...object(parsed.credits) };
|
|
64
|
+
if (next.length)
|
|
65
|
+
credits[home] = next;
|
|
66
|
+
else
|
|
67
|
+
delete credits[home];
|
|
68
|
+
parsed.credits = credits;
|
|
69
|
+
if (!Object.keys(credits).length)
|
|
70
|
+
delete parsed.credits;
|
|
71
|
+
});
|
|
76
72
|
return next;
|
|
77
73
|
}
|
|
78
74
|
/** `phren bridge accounts credit <id> --amount <usd> [--expires <date>] [--since <date>] [--label <name>]`. */
|
|
@@ -123,7 +119,12 @@ function readLedger(file) {
|
|
|
123
119
|
return {};
|
|
124
120
|
}
|
|
125
121
|
}
|
|
126
|
-
|
|
122
|
+
let ledgerWrites = Promise.resolve();
|
|
123
|
+
/**
|
|
124
|
+
* Record one status-line render or helper run: the session's running total only grows, so the largest seen
|
|
125
|
+
* stands. Writes run one at a time in this process and under the ledger's lock across processes (the status
|
|
126
|
+
* line and the helper tool both write it), so none drops another's session.
|
|
127
|
+
*/
|
|
127
128
|
export async function recordSessionCost(home, payload, now = new Date()) {
|
|
128
129
|
if (!claudeCredits(home.id).length)
|
|
129
130
|
return;
|
|
@@ -133,13 +134,20 @@ export async function recordSessionCost(home, payload, now = new Date()) {
|
|
|
133
134
|
if (!session || typeof cost !== "number" || !Number.isFinite(cost) || cost < 0 || cost > 100_000)
|
|
134
135
|
return;
|
|
135
136
|
const file = costLedgerFile(home);
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
137
|
+
const run = ledgerWrites.then(async () => {
|
|
138
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
139
|
+
await withFileLock(file, async () => {
|
|
140
|
+
const sessions = readLedger(file);
|
|
141
|
+
const seen = sessions[session];
|
|
142
|
+
if (seen && seen.costUSD >= cost)
|
|
143
|
+
return;
|
|
144
|
+
sessions[session] = { costUSD: cost, startedAt: seen?.startedAt ?? now.toISOString() };
|
|
145
|
+
const kept = Object.entries(sessions).sort(([, a], [, b]) => b.startedAt.localeCompare(a.startedAt)).slice(0, MAX_SESSIONS);
|
|
146
|
+
await atomicInPrivateDir(file, JSON.stringify({ sessions: Object.fromEntries(kept) }));
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
ledgerWrites = run.catch(() => undefined);
|
|
150
|
+
return run;
|
|
143
151
|
}
|
|
144
152
|
/**
|
|
145
153
|
* Every session cost known for a home: the status-line ledger, plus the
|