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