@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
|
@@ -170,6 +170,44 @@ export class HandOffQueue {
|
|
|
170
170
|
return this.reply(row);
|
|
171
171
|
});
|
|
172
172
|
}
|
|
173
|
+
/**
|
|
174
|
+
* Runs `action` only while the message `id` for `target` has not been typed: its row is still queued,
|
|
175
|
+
* or not made yet. Under the queue's lock, so a sweep cannot type it between the check and the action
|
|
176
|
+
* (a move's "stop and hand off now" sends Escape this way: before the request is typed, never into the
|
|
177
|
+
* hand-off it asked for). Otherwise answers the row's state. `action` gets the row (when made): the
|
|
178
|
+
* terminal it was queued for, and the conversation it is for now (it follows one that replaced the first
|
|
179
|
+
* in the same terminal).
|
|
180
|
+
*/
|
|
181
|
+
whileQueued(id, target, action) {
|
|
182
|
+
return this.serial(async () => {
|
|
183
|
+
const row = await this.read(id);
|
|
184
|
+
if (row && !samePane(row.target, target))
|
|
185
|
+
throw new BridgeError(404, "No hand-off with this id and target.");
|
|
186
|
+
if (row && row.state !== "queued")
|
|
187
|
+
return { ran: false, state: row.state };
|
|
188
|
+
await action(row ? { terminal: row.terminal, ...(row.target.session ? { session: row.target.session } : {}) } : undefined);
|
|
189
|
+
return { ran: true };
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Takes back the message `id` for `target` while it is still queued, never typed: its row fails with
|
|
194
|
+
* `reason`, and no sweep types it later (a move whose hand-off wait ended no longer wants its request in the
|
|
195
|
+
* old agent). Answers the row's state after: `failed` once withdrawn, else what it already came to
|
|
196
|
+
* (`delivered`: the agent took it), or undefined when there is no such row.
|
|
197
|
+
*/
|
|
198
|
+
withdraw(id, target, reason) {
|
|
199
|
+
return this.serial(async () => {
|
|
200
|
+
const row = await this.read(id);
|
|
201
|
+
if (!row || !samePane(row.target, target))
|
|
202
|
+
return undefined;
|
|
203
|
+
if (row.state === "queued") {
|
|
204
|
+
row.state = "failed";
|
|
205
|
+
row.error = reason.slice(0, 500);
|
|
206
|
+
await this.save(row);
|
|
207
|
+
}
|
|
208
|
+
return row.state;
|
|
209
|
+
});
|
|
210
|
+
}
|
|
173
211
|
status(id, target) {
|
|
174
212
|
return this.serial(async () => { const row = await this.read(id); if (!row || !samePane(row.target, target))
|
|
175
213
|
throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
import { type AccountRef, type AuthRunner } from "./claude-accounts.js";
|
|
2
2
|
import { type ToolVersion } from "./health.js";
|
|
3
|
+
import { type AccountRole } from "./account-pools.js";
|
|
3
4
|
export type HarnessSource = "claude" | "codex" | "opencode" | "copilot" | "phren";
|
|
4
5
|
export interface HarnessAccount extends AccountRef {
|
|
5
6
|
signedIn: boolean;
|
|
6
7
|
usable: boolean;
|
|
7
8
|
plan?: string;
|
|
8
9
|
reason?: string;
|
|
10
|
+
signInAvailable?: boolean;
|
|
11
|
+
/** The account's pool and role, when the owner set them (account-pools.ts). */
|
|
12
|
+
pool?: string;
|
|
13
|
+
role?: AccountRole;
|
|
14
|
+
/** Signed in with a Console (API billing) login: with no role it is never chosen automatically. */
|
|
15
|
+
console?: true;
|
|
9
16
|
}
|
|
10
17
|
export interface HarnessEntry {
|
|
11
18
|
source: HarnessSource;
|
|
@@ -14,9 +21,14 @@ export interface HarnessEntry {
|
|
|
14
21
|
usable: boolean;
|
|
15
22
|
reason?: string;
|
|
16
23
|
accounts?: HarnessAccount[];
|
|
24
|
+
/** Claude's entry: this computer's allowed pools, as on the inventory, or that accounts.yaml can't be read. */
|
|
25
|
+
allowedPools?: string[];
|
|
26
|
+
poolsUnreadable?: true;
|
|
17
27
|
}
|
|
28
|
+
/** `allowedPools`: the pools this computer's accounts may do work for, when the owner set them; none means any. */
|
|
18
29
|
export interface HarnessInventory {
|
|
19
30
|
harnesses: HarnessEntry[];
|
|
31
|
+
allowedPools?: string[];
|
|
20
32
|
}
|
|
21
33
|
export interface HarnessDeps {
|
|
22
34
|
toolVersion?: (tool: string) => Promise<ToolVersion>;
|
package/dist/bridge/harnesses.js
CHANGED
|
@@ -6,6 +6,7 @@ import path from "node:path";
|
|
|
6
6
|
import { codexHome } from "../home-paths.js";
|
|
7
7
|
import { claudeAccountRef, claudeAuthStatus, claudeHomes, CODEX_ACCOUNT } from "./claude-accounts.js";
|
|
8
8
|
import { toolVersion } from "./health.js";
|
|
9
|
+
import { accountPolicy, accountSettings, computerAllowedPools } from "./account-pools.js";
|
|
9
10
|
const SOURCES = ["claude", "codex", "opencode", "copilot", "phren"];
|
|
10
11
|
/** The binary is `phren`; the agent answers `phren agent --version` from the separate @phren/agent package. */
|
|
11
12
|
const probeSource = (source) => source === "phren" ? toolVersion("phren agent", "phren", ["agent"]) : toolVersion(source);
|
|
@@ -23,15 +24,29 @@ export async function harnessInventory(deps = {}) {
|
|
|
23
24
|
}
|
|
24
25
|
const base = { source, installed: true, ...(found.version ? { version: found.version } : {}) };
|
|
25
26
|
if (source === "claude") {
|
|
27
|
+
const settings = accountSettings();
|
|
26
28
|
const accounts = await Promise.all(claudeHomes(env).map(async (home) => {
|
|
27
29
|
const auth = await claudeAuthStatus(home, deps.authRunner);
|
|
28
30
|
// An unanswered sign-in check stays usable: only Claude saying "logged out" hides an account.
|
|
29
31
|
const usable = auth.signedIn || auth.unknown === true;
|
|
30
|
-
return { ...claudeAccountRef(home), signedIn: auth.signedIn, usable,
|
|
31
|
-
...(auth.plan ? { plan: auth.plan } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" })
|
|
32
|
+
return { ...claudeAccountRef(home), ...settings[home.id], signedIn: auth.signedIn, usable,
|
|
33
|
+
...(auth.plan ? { plan: auth.plan } : {}), ...(auth.console ? { console: true } : {}), ...(auth.signedIn ? {} : { reason: auth.reason ?? "Not signed in" }),
|
|
34
|
+
// Claude said it is signed out: the phone offers Sign in (POST /v1/accounts/claude/add {slug, mode: "sign-in"}).
|
|
35
|
+
...(!auth.signedIn && !auth.unknown ? { signInAvailable: true } : {}) };
|
|
32
36
|
}));
|
|
33
37
|
const usable = accounts.some(account => account.usable);
|
|
34
|
-
|
|
38
|
+
// On the entry too, so a dispatch's capacity probe (which carries only the entries) knows this computer's pools,
|
|
39
|
+
// and that they can't be known when accounts.yaml can't be read (an automatic choice then takes no account here).
|
|
40
|
+
const allowedPools = computerAllowedPools();
|
|
41
|
+
let poolsUnreadable = false;
|
|
42
|
+
try {
|
|
43
|
+
accountPolicy();
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
poolsUnreadable = true;
|
|
47
|
+
}
|
|
48
|
+
return { ...base, usable, ...(usable ? {} : { reason: "No signed-in Claude account" }), accounts, ...(allowedPools ? { allowedPools } : {}),
|
|
49
|
+
...(poolsUnreadable ? { poolsUnreadable: true } : {}) };
|
|
35
50
|
}
|
|
36
51
|
if (source === "codex") {
|
|
37
52
|
const signedIn = existsSync(path.join(codexHome(env), "auth.json"));
|
|
@@ -40,7 +55,8 @@ export async function harnessInventory(deps = {}) {
|
|
|
40
55
|
}
|
|
41
56
|
return { ...base, usable: true };
|
|
42
57
|
}));
|
|
43
|
-
|
|
58
|
+
const allowedPools = computerAllowedPools();
|
|
59
|
+
return { harnesses, ...(allowedPools ? { allowedPools } : {}) };
|
|
44
60
|
}
|
|
45
61
|
/** The inventory, or undefined when it is not ready within `ms` (a cold `claude auth status` can take seconds). */
|
|
46
62
|
export function harnessInventoryWithin(ms, deps = {}) {
|
|
@@ -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
|
+
}
|
package/dist/bridge/herdr.js
CHANGED
|
@@ -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
|
-
|
|
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. */
|
package/dist/bridge/hook-fast.js
CHANGED
|
@@ -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
|
|
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) } : {}),
|
|
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
|
-
|
|
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 {};
|