@phren/cli 0.3.12 → 0.3.13
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-usage.d.ts +124 -0
- package/dist/bridge/account-usage.js +258 -0
- package/dist/bridge/agent-hooks.d.ts +3 -0
- package/dist/bridge/agent-hooks.js +20 -1
- package/dist/bridge/codex-hook-trust.d.ts +27 -0
- package/dist/bridge/codex-hook-trust.js +237 -0
- package/dist/bridge/command.js +3 -0
- package/dist/bridge/dispatch-command.js +9 -3
- package/dist/bridge/dispatch-returns.d.ts +5 -0
- package/dist/bridge/dispatch-returns.js +16 -6
- package/dist/bridge/dispatch.d.ts +25 -1
- package/dist/bridge/dispatch.js +35 -6
- package/dist/bridge/hand-off-queue.d.ts +74 -0
- package/dist/bridge/hand-off-queue.js +235 -0
- package/dist/bridge/hand-off.d.ts +12 -4
- package/dist/bridge/hand-off.js +27 -7
- package/dist/bridge/install.js +16 -2
- package/dist/bridge/pane-status.d.ts +12 -0
- package/dist/bridge/pane-status.js +50 -1
- package/dist/bridge/push.d.ts +6 -0
- package/dist/bridge/push.js +21 -0
- package/dist/bridge/schedule-launch.d.ts +1 -1
- package/dist/bridge/schedule-launch.js +5 -1
- package/dist/bridge/schedule-watch.d.ts +15 -1
- package/dist/bridge/schedule-watch.js +45 -10
- package/dist/bridge/server-launch.js +14 -4
- package/dist/bridge/server-overview.d.ts +8 -1
- package/dist/bridge/server-overview.js +12 -3
- package/dist/bridge/server-pane-routes.d.ts +1 -0
- package/dist/bridge/server-pane-routes.js +9 -7
- package/dist/bridge/server-routes.d.ts +4 -0
- package/dist/bridge/server-routes.js +57 -7
- package/dist/bridge/server.js +15 -2
- package/dist/bridge/session-activity.d.ts +24 -12
- package/dist/bridge/session-activity.js +36 -14
- package/dist/bridge/stalls.d.ts +22 -0
- package/dist/bridge/stalls.js +57 -0
- package/dist/bridge/sudo.d.ts +209 -0
- package/dist/bridge/sudo.js +501 -0
- package/dist/bridge/terminal-tmux.d.ts +12 -0
- package/dist/bridge/terminal-tmux.js +79 -4
- package/dist/bridge/transcript-claude.d.ts +4 -0
- package/dist/bridge/transcript-claude.js +131 -6
- package/dist/bridge/usage.d.ts +17 -0
- package/dist/bridge/usage.js +37 -3
- package/dist/bridge-hook.mjs +19448 -18102
- package/dist/cli-registry.js +7 -1
- package/dist/modules/registry.js +8 -8
- package/dist/tools/dispatch.js +17 -2
- package/package.json +1 -1
- package/starter/global/AGENTS.md +4 -0
- package/starter/global/skills/conductor/SKILL.md +34 -2
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { lstat, readFile, realpath } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { codexHome } from "../home-paths.js";
|
|
5
|
+
import { logger } from "../logger.js";
|
|
6
|
+
import { pretrustEnabled } from "./folder-trust.js";
|
|
7
|
+
import { atomic, object, objects } from "./protocol.js";
|
|
8
|
+
/**
|
|
9
|
+
* Keeping the owner's trust in Phren's own Codex hooks when an install
|
|
10
|
+
* rewrites them.
|
|
11
|
+
*
|
|
12
|
+
* Codex 0.158+ runs a `hooks.json` handler only when `config.toml` holds a
|
|
13
|
+
* matching `trusted_hash` for it, under
|
|
14
|
+
* `[hooks.state."<hooks.json path>:<event_snake>:<group>:<handler>"]`. The
|
|
15
|
+
* hash covers the handler's command, timeout and matcher, so an install that
|
|
16
|
+
* changes Phren's timeout (3 s to 15 s) or moves its group turns a handler the
|
|
17
|
+
* owner trusted into a "modified" one: Codex skips it and every new TUI opens
|
|
18
|
+
* on "Hooks need review".
|
|
19
|
+
*
|
|
20
|
+
* The rule never grants trust the owner did not give. A Phren handler whose
|
|
21
|
+
* key has no matching hash is trusted only when a hash stored for the same
|
|
22
|
+
* event in the same hooks.json is one of:
|
|
23
|
+
*
|
|
24
|
+
* - the same command with a timeout Phren has shipped (3, 10, 15, 60 or none);
|
|
25
|
+
* - a Phren handler for that event in hooks.json as it was before this
|
|
26
|
+
* install rewrote it (a changed node path, a moved group).
|
|
27
|
+
*
|
|
28
|
+
* A hash cannot come from anything but that event and that command, so a
|
|
29
|
+
* match means the owner trusted Phren's handler there. Other handlers are
|
|
30
|
+
* never touched. `PHREN_PRETRUST=off` turns this off with folder trust.
|
|
31
|
+
*/
|
|
32
|
+
/** Timeouts Phren's Codex callbacks have carried in any release; undefined is "no timeout key". */
|
|
33
|
+
const SHIPPED_TIMEOUTS = [3, 10, 15, 60, undefined];
|
|
34
|
+
const quote = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
35
|
+
/** `SessionStart` to `session_start`, the event name in Codex's trust keys. */
|
|
36
|
+
export function codexEventName(event) {
|
|
37
|
+
return event.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
|
|
38
|
+
}
|
|
39
|
+
/** JSON with every object's keys sorted and no whitespace: serde_json's output for Codex's identity value. */
|
|
40
|
+
function canonicalJson(value) {
|
|
41
|
+
if (Array.isArray(value))
|
|
42
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
43
|
+
if (value && typeof value === "object") {
|
|
44
|
+
const record = value;
|
|
45
|
+
return `{${Object.keys(record).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(record[key])}`).join(",")}}`;
|
|
46
|
+
}
|
|
47
|
+
// JSON.stringify escapes strings as serde_json does: `"`, `\` and control
|
|
48
|
+
// characters only, lowercase \u00xx, non-ASCII left as UTF-8.
|
|
49
|
+
return JSON.stringify(value);
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Codex's `hook_hash` for one handler in one group (codex-rs hooks
|
|
53
|
+
* discovery + config fingerprint): sha256 of the canonical JSON of
|
|
54
|
+
* `{ event_name, matcher?, hooks: [handler] }`, where the handler always
|
|
55
|
+
* carries `timeout` (default 600, at least 1) and `async` (default false).
|
|
56
|
+
*/
|
|
57
|
+
export function codexHookHash(event, group, handler) {
|
|
58
|
+
const name = codexEventName(event);
|
|
59
|
+
const shortLived = name === "session_end" || name === "interrupt";
|
|
60
|
+
const given = typeof handler.timeout === "number" ? handler.timeout : undefined;
|
|
61
|
+
const timeout = shortLived ? Math.min(3, Math.max(1, given ?? 1)) : Math.max(1, given ?? 600);
|
|
62
|
+
const hook = { type: handler.type ?? "command", command: handler.command, timeout, async: handler.async ?? false };
|
|
63
|
+
for (const key of ["statusMessage", "commandWindows", "additionalContextLimit"]) {
|
|
64
|
+
if (handler[key] !== undefined && handler[key] !== null)
|
|
65
|
+
hook[key] = handler[key];
|
|
66
|
+
}
|
|
67
|
+
const identity = { event_name: name, hooks: [hook] };
|
|
68
|
+
if (typeof group.matcher === "string")
|
|
69
|
+
identity.matcher = group.matcher;
|
|
70
|
+
return `sha256:${createHash("sha256").update(canonicalJson(identity), "utf8").digest("hex")}`;
|
|
71
|
+
}
|
|
72
|
+
/** Phren's own handlers in a Codex hooks.json text; none when it does not parse. */
|
|
73
|
+
function ownHandlers(text, program) {
|
|
74
|
+
if (text === undefined)
|
|
75
|
+
return [];
|
|
76
|
+
let parsed;
|
|
77
|
+
try {
|
|
78
|
+
parsed = JSON.parse(text);
|
|
79
|
+
}
|
|
80
|
+
catch {
|
|
81
|
+
return [];
|
|
82
|
+
}
|
|
83
|
+
const suffix = ` ${quote(program)} hook codex`;
|
|
84
|
+
const found = [];
|
|
85
|
+
for (const [event, groups] of Object.entries(object(object(parsed).hooks))) {
|
|
86
|
+
objects(groups).forEach((group, groupIndex) => objects(group.hooks).forEach((handler, handlerIndex) => {
|
|
87
|
+
if (typeof handler.command === "string" && handler.command.endsWith(suffix))
|
|
88
|
+
found.push({ event, group, handler, groupIndex, handlerIndex });
|
|
89
|
+
}));
|
|
90
|
+
}
|
|
91
|
+
return found;
|
|
92
|
+
}
|
|
93
|
+
const TABLE = /^[ \t]*\[[ \t]*hooks[ \t]*\.[ \t]*state[ \t]*\.[ \t]*("(?:[^"\\\r\n]|\\.)*"|'[^'\r\n]*')[ \t]*\][ \t]*(?:#.*)?$/;
|
|
94
|
+
const HASH_LINE = /^[ \t]*trusted_hash[ \t]*=[ \t]*"([^"\r\n]*)"/;
|
|
95
|
+
/** The `[hooks.state."<key>"]` tables of a config.toml, by line. */
|
|
96
|
+
function stateTables(lines) {
|
|
97
|
+
const tables = [];
|
|
98
|
+
let current;
|
|
99
|
+
lines.forEach((line, index) => {
|
|
100
|
+
if (/^[ \t]*\[/.test(line)) {
|
|
101
|
+
if (current)
|
|
102
|
+
current.end = index;
|
|
103
|
+
current = undefined;
|
|
104
|
+
const match = TABLE.exec(line);
|
|
105
|
+
if (!match)
|
|
106
|
+
return;
|
|
107
|
+
let key;
|
|
108
|
+
try {
|
|
109
|
+
key = match[1].startsWith("'") ? match[1].slice(1, -1) : JSON.parse(match[1]);
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
current = { key, header: index, end: lines.length };
|
|
115
|
+
tables.push(current);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
const hash = current && current.hash === undefined ? HASH_LINE.exec(line) : null;
|
|
119
|
+
if (current && hash) {
|
|
120
|
+
current.hash = hash[1];
|
|
121
|
+
current.hashLine = index;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
return tables;
|
|
125
|
+
}
|
|
126
|
+
function tomlKey(value) {
|
|
127
|
+
return `"${value.replace(/[\\"\u0000-\u001f\u007f]/g, c => c === "\\" ? "\\\\" : c === "\"" ? "\\\"" : `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`)}"`;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The config text with trust carried forward to Phren's handlers in
|
|
131
|
+
* `hooks` (the hooks.json text as it is now), or undefined when nothing
|
|
132
|
+
* changes. `before` is hooks.json as it stood before this install rewrote
|
|
133
|
+
* it, when there was a rewrite. `hooksPaths` are the names Codex may key
|
|
134
|
+
* this hooks.json by; the first is used for a new key.
|
|
135
|
+
*/
|
|
136
|
+
export function codexHookTrustText(config, hooks, program, hooksPaths, before) {
|
|
137
|
+
const own = ownHandlers(hooks, program);
|
|
138
|
+
if (!own.length)
|
|
139
|
+
return undefined;
|
|
140
|
+
const newline = config.includes("\r\n") ? "\r\n" : "\n";
|
|
141
|
+
const lines = config.split(/\r?\n/);
|
|
142
|
+
const tables = stateTables(lines);
|
|
143
|
+
const split = (key) => {
|
|
144
|
+
const match = /^(.*):([a-z_]+):(\d+):(\d+)$/.exec(key);
|
|
145
|
+
return match && hooksPaths.includes(match[1]) ? { file: match[1], event: match[2] } : undefined;
|
|
146
|
+
};
|
|
147
|
+
const stored = tables.flatMap(table => { const parts = split(table.key); return parts && table.hash ? [{ ...parts, hash: table.hash }] : []; });
|
|
148
|
+
if (!stored.length)
|
|
149
|
+
return undefined;
|
|
150
|
+
const keyPath = stored[0].file;
|
|
151
|
+
const previous = ownHandlers(before, program);
|
|
152
|
+
const edits = new Map(), appended = [], carried = [];
|
|
153
|
+
for (const entry of own) {
|
|
154
|
+
const name = codexEventName(entry.event);
|
|
155
|
+
const key = `${keyPath}:${name}:${entry.groupIndex}:${entry.handlerIndex}`;
|
|
156
|
+
const want = codexHookHash(entry.event, entry.group, entry.handler);
|
|
157
|
+
const table = tables.find(t => t.key === key);
|
|
158
|
+
if (table?.hash === want)
|
|
159
|
+
continue;
|
|
160
|
+
const accepted = new Set([
|
|
161
|
+
...SHIPPED_TIMEOUTS.map(timeout => codexHookHash(entry.event, entry.group, { ...entry.handler, timeout })),
|
|
162
|
+
...previous.filter(p => p.event === entry.event).map(p => codexHookHash(p.event, p.group, p.handler)),
|
|
163
|
+
]);
|
|
164
|
+
if (!stored.some(s => s.event === name && accepted.has(s.hash)))
|
|
165
|
+
continue;
|
|
166
|
+
const line = `trusted_hash = "${want}"`;
|
|
167
|
+
if (table?.hashLine !== undefined)
|
|
168
|
+
edits.set(table.hashLine, lines[table.hashLine].replace(/"[^"]*"/, `"${want}"`));
|
|
169
|
+
else if (table)
|
|
170
|
+
edits.set(table.header, `${lines[table.header]}${newline}${line}`);
|
|
171
|
+
else
|
|
172
|
+
appended.push(`[hooks.state.${tomlKey(key)}]${newline}${line}${newline}`);
|
|
173
|
+
carried.push(key);
|
|
174
|
+
}
|
|
175
|
+
if (!carried.length)
|
|
176
|
+
return undefined;
|
|
177
|
+
const next = lines.map((line, index) => edits.get(index) ?? line);
|
|
178
|
+
if (appended.length) {
|
|
179
|
+
// New tables go right after the last hooks.state table, next to their siblings.
|
|
180
|
+
const last = tables[tables.length - 1];
|
|
181
|
+
const insertAt = last.end;
|
|
182
|
+
const block = appended.join(newline);
|
|
183
|
+
if (insertAt < next.length)
|
|
184
|
+
next.splice(insertAt, 0, ...block.split(newline).slice(0, -1), "");
|
|
185
|
+
else {
|
|
186
|
+
const text = next.join(newline);
|
|
187
|
+
const separator = text.endsWith(newline + newline) || text === "" ? "" : text.endsWith(newline) ? newline : newline + newline;
|
|
188
|
+
return { text: text + separator + block, carried };
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
return { text: next.join(newline), carried };
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Carries the owner's Codex trust forward to Phren's handlers in
|
|
195
|
+
* `$CODEX_HOME/hooks.json`. Runs after every install, update, rollback and
|
|
196
|
+
* module reconcile, whether or not hooks.json changed, so a computer an
|
|
197
|
+
* earlier install left untrusted is repaired too. Never throws.
|
|
198
|
+
*/
|
|
199
|
+
export async function carryCodexHookTrust(program, before, env = process.env) {
|
|
200
|
+
if (!pretrustEnabled(env))
|
|
201
|
+
return [];
|
|
202
|
+
try {
|
|
203
|
+
const directory = codexHome(env);
|
|
204
|
+
const hooksFile = path.join(directory, "hooks.json");
|
|
205
|
+
const hooks = await readFile(hooksFile, "utf8").catch(() => undefined);
|
|
206
|
+
if (hooks === undefined)
|
|
207
|
+
return [];
|
|
208
|
+
const hooksPaths = [...new Set([hooksFile, await realpath(hooksFile).catch(() => hooksFile)])];
|
|
209
|
+
const configured = path.join(directory, "config.toml");
|
|
210
|
+
const file = await realpath(configured).catch(() => configured);
|
|
211
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
212
|
+
const text = await readFile(file, "utf8").catch(error => {
|
|
213
|
+
if (error.code === "ENOENT")
|
|
214
|
+
return undefined;
|
|
215
|
+
throw error;
|
|
216
|
+
});
|
|
217
|
+
// No config means the owner never trusted anything.
|
|
218
|
+
if (text === undefined)
|
|
219
|
+
return [];
|
|
220
|
+
const result = codexHookTrustText(text, hooks, program, hooksPaths, before);
|
|
221
|
+
if (!result)
|
|
222
|
+
return [];
|
|
223
|
+
const metadata = await lstat(file);
|
|
224
|
+
// Codex may have rewritten the file meanwhile; start over from its text.
|
|
225
|
+
if (await readFile(file, "utf8").catch(() => "") !== text)
|
|
226
|
+
continue;
|
|
227
|
+
await atomic(file, result.text, metadata.mode & 0o777);
|
|
228
|
+
logger.info("install", `Kept Codex trust for Phren's rewritten hooks: ${result.carried.join(", ")}.`);
|
|
229
|
+
return result.carried;
|
|
230
|
+
}
|
|
231
|
+
throw new Error("config.toml kept changing while it was being updated");
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
logger.warn("install", `Could not carry Codex hook trust forward: ${error instanceof Error ? error.message.split("\n")[0] : String(error)}`);
|
|
235
|
+
return [];
|
|
236
|
+
}
|
|
237
|
+
}
|
package/dist/bridge/command.js
CHANGED
|
@@ -5,6 +5,7 @@ import { install, rollback, uninstall } from "./install.js";
|
|
|
5
5
|
import { servers } from "./herdr.js";
|
|
6
6
|
import { describeTerminal, terminalHealth } from "./health.js";
|
|
7
7
|
import { agentHook } from "./agent-hooks.js";
|
|
8
|
+
import { askpass } from "./sudo.js";
|
|
8
9
|
import { object, provider } from "./protocol.js";
|
|
9
10
|
import { apnsSetupSteps } from "./push.js";
|
|
10
11
|
import { speechKeyFile, speechKeyStatus, writeSpeechKey } from "./speech-key.js";
|
|
@@ -166,6 +167,8 @@ export async function runBridge(args, version) {
|
|
|
166
167
|
case "hook":
|
|
167
168
|
await agentHook(provider.parse(args[1])).catch(() => { });
|
|
168
169
|
break;
|
|
170
|
+
// sudo -A runs <bridge>/askpass, which runs this: the password on stdout, or exit 1.
|
|
171
|
+
case "askpass": return askpass(args[1]);
|
|
169
172
|
case "serve": {
|
|
170
173
|
// The subprocess bridge suite supplies this fixture; no agent binaries or
|
|
171
174
|
// machine-specific catalogue caches should affect its HTTP assertions.
|
|
@@ -14,6 +14,12 @@ export async function runDispatch(args) {
|
|
|
14
14
|
console.log(JSON.stringify(await hookRequest("/v1/dispatch/returns", {}), null, 2));
|
|
15
15
|
return 0;
|
|
16
16
|
}
|
|
17
|
+
if (args[0] === "usage" && args.slice(1).every(arg => arg === "--json")) {
|
|
18
|
+
const { readAccountUsage, formatAccountUsage } = await import("./account-usage.js");
|
|
19
|
+
const view = await readAccountUsage();
|
|
20
|
+
console.log(args.includes("--json") ? JSON.stringify(view, null, 2) : formatAccountUsage(view));
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
17
23
|
if (args.length === 1 && args[0] === "sessions") {
|
|
18
24
|
const { listLiveSessions } = await import("./hand-off.js");
|
|
19
25
|
console.log(JSON.stringify(await listLiveSessions(), null, 2));
|
|
@@ -47,12 +53,12 @@ export async function runDispatch(args) {
|
|
|
47
53
|
}
|
|
48
54
|
export async function runHandOff(args) {
|
|
49
55
|
const { values, positionals } = parseArgs({ args, allowPositionals: true, options: {
|
|
50
|
-
session: { type: "string" }, text: { type: "string" }, project: { type: "string" }, account: { type: "string" },
|
|
56
|
+
"delivery-id": { type: "string" }, status: { type: "boolean" }, session: { type: "string" }, text: { type: "string" }, project: { type: "string" }, account: { type: "string" },
|
|
51
57
|
} });
|
|
52
|
-
if (positionals.length !== 1 || !values.session || !values.text)
|
|
58
|
+
if (positionals.length !== 1 || !values.session || (!values.status && !values.text) || (values.status && !values["delivery-id"]))
|
|
53
59
|
throw new Error("Usage: phren hand-off <computer|local> --session <id> --text <prompt> [--project <slug>] [--account <id>]");
|
|
54
60
|
const computer = positionals[0] === "local" ? undefined : positionals[0];
|
|
55
|
-
const result = await handOff({ ...(computer ? { computer } : {}), project: values.project, ...(values.account ? { account: values.account } : {}), session: sessionId.parse(values.session), text: values.text });
|
|
61
|
+
const result = await handOff({ ...(computer ? { computer } : {}), project: values.project, ...(values.account ? { account: values.account } : {}), session: sessionId.parse(values.session), ...(values.status ? { status: true } : { text: values.text }), ...(values["delivery-id"] ? { deliveryId: values["delivery-id"] } : {}) });
|
|
56
62
|
console.log(JSON.stringify(result, null, 2));
|
|
57
63
|
return result.ok ? 0 : 1;
|
|
58
64
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sessionStalls } from "./stalls.js";
|
|
1
2
|
import { z } from "zod";
|
|
2
3
|
import { type OriginPane, type Receipt } from "./dispatch.js";
|
|
3
4
|
import { type BriefArrival } from "./launch-brief.js";
|
|
@@ -84,6 +85,9 @@ export interface WorkerObservation {
|
|
|
84
85
|
interrupted?: true;
|
|
85
86
|
/** A permission request the pane's worker is waiting on, forwarded by its Hook (`AgentHooks.workerApproval`). */
|
|
86
87
|
approval?: Json;
|
|
88
|
+
stalled?: boolean;
|
|
89
|
+
stalledSince?: string;
|
|
90
|
+
stallFor?: number;
|
|
87
91
|
}
|
|
88
92
|
export interface WorkerReaders {
|
|
89
93
|
snapshot: (server: string) => Promise<Json>;
|
|
@@ -94,6 +98,7 @@ export interface WorkerReaders {
|
|
|
94
98
|
/** What the worker in this conversation is waiting on, from the Hook that runs it. */
|
|
95
99
|
approval?: (target: Target) => Json | undefined;
|
|
96
100
|
now?: () => number;
|
|
101
|
+
stall?: typeof sessionStalls.observe;
|
|
97
102
|
}
|
|
98
103
|
/** The default readers with the approval reader of the Hook that runs the workers. */
|
|
99
104
|
export declare const workerReaders: (approval: NonNullable<WorkerReaders["approval"]>) => WorkerReaders;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { sessionStalls } from "./stalls.js";
|
|
1
2
|
import { createHash } from "node:crypto";
|
|
2
3
|
import { z } from "zod";
|
|
3
4
|
import { logger } from "../logger.js";
|
|
@@ -55,6 +56,7 @@ const defaultReaders = {
|
|
|
55
56
|
identity: (server, pane) => paneIdentity(server, pane),
|
|
56
57
|
finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
|
|
57
58
|
turn: paneTurn,
|
|
59
|
+
stall: (target, pane) => sessionStalls.observe(target, pane),
|
|
58
60
|
};
|
|
59
61
|
/** The default readers with the approval reader of the Hook that runs the workers. */
|
|
60
62
|
export const workerReaders = (approval) => ({ ...defaultReaders, approval });
|
|
@@ -136,12 +138,17 @@ export async function workerStates(input, readers = defaultReaders) {
|
|
|
136
138
|
const own = record && record.terminal === pane.terminal_id && record.source === target.source
|
|
137
139
|
&& record.session === (expected ?? current ?? record.session)
|
|
138
140
|
&& !(target.dispatch && record.dispatch && target.dispatch !== record.dispatch) ? record : undefined;
|
|
139
|
-
if (own)
|
|
140
|
-
|
|
141
|
+
if (own) {
|
|
142
|
+
const seen = await fromTurn(own, own.session, status, target.source, readers);
|
|
143
|
+
const full = targetSchema.safeParse({ ...target, session: seen.session });
|
|
144
|
+
return { ...seen, ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }) : {}) };
|
|
145
|
+
}
|
|
141
146
|
const session = expected ?? current;
|
|
142
147
|
const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
|
|
143
|
-
if ((state !== "idle" && state !== "done") || !session)
|
|
144
|
-
|
|
148
|
+
if ((state !== "idle" && state !== "done") || !session) {
|
|
149
|
+
const full = targetSchema.safeParse({ ...target, session });
|
|
150
|
+
return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane) : {}) };
|
|
151
|
+
}
|
|
145
152
|
const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
|
|
146
153
|
// A finished turn that left background work is still the worker's turn. There is no Stop to time the wait
|
|
147
154
|
// from, so it carries what a finished turn would and the dispatching Hook bounds the wait (see observe).
|
|
@@ -164,6 +171,7 @@ const observationSchema = z.object({
|
|
|
164
171
|
session: z.string().max(200).optional(), completed: z.boolean().optional(),
|
|
165
172
|
reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(), error: z.string().max(500).optional(),
|
|
166
173
|
hook: z.boolean().optional(), endedAt: z.string().max(40).optional(), background: z.number().int().min(0).max(999).optional(),
|
|
174
|
+
stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
|
|
167
175
|
interrupted: z.boolean().optional(), approval: z.unknown().optional(),
|
|
168
176
|
}).passthrough();
|
|
169
177
|
/** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
|
|
@@ -246,7 +254,7 @@ function observeState(receipt, parsed, now) {
|
|
|
246
254
|
if (seen.state === "gone")
|
|
247
255
|
next = "gone";
|
|
248
256
|
else if (seen.state === "working")
|
|
249
|
-
next = "working";
|
|
257
|
+
next = seen.stalled ? "stalled" : "working";
|
|
250
258
|
else if (seen.state === "blocked")
|
|
251
259
|
next = "blocked";
|
|
252
260
|
else if (failed)
|
|
@@ -287,6 +295,7 @@ function observeState(receipt, parsed, now) {
|
|
|
287
295
|
if (next !== "working") {
|
|
288
296
|
receipt.returned = { state: next, at, read: false,
|
|
289
297
|
...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
|
|
298
|
+
...(next === "stalled" ? { stalledSince: seen.stalledSince, stallFor: seen.stallFor } : {}),
|
|
290
299
|
...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}),
|
|
291
300
|
...((next === "done" || next === "needs-you") && seen.background ? { background: seen.background } : {}),
|
|
292
301
|
// Nothing still running: say what it waited on.
|
|
@@ -297,7 +306,7 @@ function observeState(receipt, parsed, now) {
|
|
|
297
306
|
/** One line for the dispatching agent: who returned, how, and where to read it. */
|
|
298
307
|
export function noticeLine(receipts) {
|
|
299
308
|
const clean = (value, max) => value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
|
|
300
|
-
const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
|
|
309
|
+
const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone", "stalled": "stalled" };
|
|
301
310
|
const describe = (receipt, room) => {
|
|
302
311
|
const returned = receipt.returned;
|
|
303
312
|
const asking = returned.state === "blocked" ? receipt.approval : undefined;
|
|
@@ -319,6 +328,7 @@ export function noticeLine(receipts) {
|
|
|
319
328
|
export function returnRow(receipt) {
|
|
320
329
|
const returned = receipt.returned;
|
|
321
330
|
return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
|
|
331
|
+
...(returned.state === "stalled" ? { stalled: true, stalledSince: returned.stalledSince, stallFor: returned.stallFor } : {}),
|
|
322
332
|
state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
|
|
323
333
|
...(returned.truncated ? { truncated: true } : {}), ...(returned.error ? { error: returned.error } : {}), ...(returned.question ? { question: returned.question } : {}),
|
|
324
334
|
...(returned.background ? { background: returned.background } : {}),
|
|
@@ -71,7 +71,7 @@ export declare const originPaneSchema: z.ZodObject<{
|
|
|
71
71
|
pane: z.ZodString;
|
|
72
72
|
}, z.core.$strict>;
|
|
73
73
|
export type OriginPane = z.infer<typeof originPaneSchema>;
|
|
74
|
-
export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "gone"];
|
|
74
|
+
export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "stalled", "gone"];
|
|
75
75
|
export type WorkerState = typeof workerStates[number];
|
|
76
76
|
declare const receiptSchema: z.ZodObject<{
|
|
77
77
|
computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
|
|
@@ -202,6 +202,7 @@ declare const receiptSchema: z.ZodObject<{
|
|
|
202
202
|
failed: "failed";
|
|
203
203
|
gone: "gone";
|
|
204
204
|
"needs-you": "needs-you";
|
|
205
|
+
stalled: "stalled";
|
|
205
206
|
working: "working";
|
|
206
207
|
}>;
|
|
207
208
|
since: z.ZodString;
|
|
@@ -217,12 +218,15 @@ declare const receiptSchema: z.ZodObject<{
|
|
|
217
218
|
failed: "failed";
|
|
218
219
|
gone: "gone";
|
|
219
220
|
"needs-you": "needs-you";
|
|
221
|
+
stalled: "stalled";
|
|
220
222
|
}>;
|
|
221
223
|
at: z.ZodString;
|
|
222
224
|
reply: z.ZodOptional<z.ZodString>;
|
|
223
225
|
error: z.ZodOptional<z.ZodString>;
|
|
224
226
|
truncated: z.ZodOptional<z.ZodBoolean>;
|
|
225
227
|
question: z.ZodOptional<z.ZodString>;
|
|
228
|
+
stalledSince: z.ZodOptional<z.ZodString>;
|
|
229
|
+
stallFor: z.ZodOptional<z.ZodNumber>;
|
|
226
230
|
turn: z.ZodOptional<z.ZodString>;
|
|
227
231
|
read: z.ZodBoolean;
|
|
228
232
|
notifiedAt: z.ZodOptional<z.ZodString>;
|
|
@@ -273,6 +277,26 @@ export declare function updateReceipt(receiptID: string, change: (receipt: Recei
|
|
|
273
277
|
/** One bounded line for a log or a receipt: a Bridge message, an errno code, or the error's first line. */
|
|
274
278
|
export declare function failureReason(error: unknown): string;
|
|
275
279
|
export declare function dispatchStatus(): Promise<Receipt[]>;
|
|
280
|
+
/** `caller` (a conductor's name and host key) asks a peer whether it links this computer back:
|
|
281
|
+
* `outside` is a peer in another set, which a conductor does not dispatch to. */
|
|
282
|
+
type Room = {
|
|
283
|
+
source: string;
|
|
284
|
+
account?: string;
|
|
285
|
+
leftPercent?: number;
|
|
286
|
+
exhausted?: boolean;
|
|
287
|
+
until?: string;
|
|
288
|
+
};
|
|
289
|
+
/** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
|
|
290
|
+
export declare function roomFor(data: {
|
|
291
|
+
harness: string;
|
|
292
|
+
account?: string;
|
|
293
|
+
}, usage: readonly Room[] | undefined): Room | undefined;
|
|
294
|
+
/** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
|
|
295
|
+
* Low quota is not a reason; the owner often wants it used before it resets. */
|
|
296
|
+
export declare function outOfQuota(data: {
|
|
297
|
+
harness: string;
|
|
298
|
+
account?: string;
|
|
299
|
+
}, usage: readonly Room[] | undefined, now?: number): string | undefined;
|
|
276
300
|
/** What the worker's own hooks reported for a brief that went with its
|
|
277
301
|
* launch, or undefined when the receiving Hook has no such brief. */
|
|
278
302
|
export declare function arrivalOf(peer: Pick<DispatchHost, "request">, id: string): Promise<BriefArrival | undefined>;
|
package/dist/bridge/dispatch.js
CHANGED
|
@@ -41,7 +41,7 @@ export const dispatchSchema = z.object({
|
|
|
41
41
|
const remoteTarget = z.union([targetSchema, startingTargetSchema]);
|
|
42
42
|
/** The local pane that asked for the dispatch, where return notices go. */
|
|
43
43
|
export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
|
|
44
|
-
export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "gone"];
|
|
44
|
+
export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "stalled", "gone"];
|
|
45
45
|
const timestamp = z.string().datetime();
|
|
46
46
|
const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
|
|
47
47
|
id: z.string().uuid(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
|
|
@@ -62,8 +62,9 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
|
|
|
62
62
|
waitingSince: timestamp.optional().describe("When the dispatching Hook first saw the worker's finished turn waiting on background tasks; bounds that wait.") }).strict().optional()
|
|
63
63
|
.describe("The worker pane's last observed state."),
|
|
64
64
|
returned: z.object({
|
|
65
|
-
state: z.enum(["done", "needs-you", "failed", "blocked", "gone"]), at: timestamp,
|
|
65
|
+
state: z.enum(["done", "needs-you", "failed", "blocked", "stalled", "gone"]), at: timestamp,
|
|
66
66
|
reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
|
|
67
|
+
stalledSince: timestamp.optional(), stallFor: z.number().nonnegative().optional(),
|
|
67
68
|
turn: z.string().regex(/^[a-f0-9]{16}$/).optional(), read: z.boolean(), notifiedAt: timestamp.optional(),
|
|
68
69
|
background: z.number().int().min(1).max(999).optional().describe("Background tasks the worker left running when it was counted done."),
|
|
69
70
|
waited: z.number().int().min(1).max(999).optional().describe("The most background tasks the worker waited on before it finished."),
|
|
@@ -172,8 +173,6 @@ export async function dispatchStatus() {
|
|
|
172
173
|
}
|
|
173
174
|
return receipts.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
174
175
|
}
|
|
175
|
-
/** `caller` (a conductor's name and host key) asks a peer whether it links this computer back:
|
|
176
|
-
* `outside` is a peer in another set, which a conductor does not dispatch to. */
|
|
177
176
|
async function capacity(host, caller) {
|
|
178
177
|
const value = await host.request(caller && !host.local ? `/v1/dispatch/capacity?${caller}` : "/v1/dispatch/capacity");
|
|
179
178
|
const result = z.object({ product: z.literal("phren-hook"), protocol: z.literal(PROTOCOL), working: z.number().int().nonnegative(),
|
|
@@ -181,6 +180,9 @@ async function capacity(host, caller) {
|
|
|
181
180
|
// Missing from an older Hook, or when its inventory was not ready in time: unknown, not unavailable.
|
|
182
181
|
harnesses: z.array(z.object({ source: z.string(), installed: z.boolean(), usable: z.boolean(), reason: z.string().optional(),
|
|
183
182
|
accounts: z.array(z.object({ id: z.string(), usable: z.boolean(), reason: z.string().optional() }).passthrough()).optional() }).passthrough()).optional(),
|
|
183
|
+
// Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
|
|
184
|
+
usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
|
|
185
|
+
exhausted: z.boolean().optional(), until: z.string().max(40).optional() }).passthrough()).max(64).optional(),
|
|
184
186
|
knowsCaller: z.boolean().optional() }).parse(value);
|
|
185
187
|
// This computer places on whichever Herdr server its own Hook runs.
|
|
186
188
|
if (host.local && !result.servers.includes(host.server) && result.servers[0])
|
|
@@ -188,8 +190,25 @@ async function capacity(host, caller) {
|
|
|
188
190
|
if (!result.servers.includes(host.server))
|
|
189
191
|
throw new BridgeError(503, "Herdr is not running on the selected computer. Headless dispatch is not installed yet.");
|
|
190
192
|
return { working: result.working, computerId: result.computer.id, ...(result.harnesses ? { harnesses: result.harnesses } : {}),
|
|
193
|
+
...(result.usage ? { usage: result.usage } : {}),
|
|
191
194
|
...(caller && result.knowsCaller === false ? { outside: true } : {}) };
|
|
192
195
|
}
|
|
196
|
+
/** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
|
|
197
|
+
export function roomFor(data, usage) {
|
|
198
|
+
const account = data.account ?? "default";
|
|
199
|
+
return usage?.find(item => item.source === data.harness && (data.harness !== "claude" || (item.account ?? "default") === account));
|
|
200
|
+
}
|
|
201
|
+
/** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
|
|
202
|
+
* Low quota is not a reason; the owner often wants it used before it resets. */
|
|
203
|
+
export function outOfQuota(data, usage, now = Date.now()) {
|
|
204
|
+
const room = roomFor(data, usage);
|
|
205
|
+
if (!room?.exhausted)
|
|
206
|
+
return undefined;
|
|
207
|
+
const until = room.until ? Date.parse(room.until) : NaN;
|
|
208
|
+
const minutes = Number.isFinite(until) ? Math.max(1, Math.round((until - now) / 60_000)) : undefined;
|
|
209
|
+
const back = minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
|
|
210
|
+
return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${back}.`;
|
|
211
|
+
}
|
|
193
212
|
/** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
|
|
194
213
|
* `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
|
|
195
214
|
function unusable(data, harnesses, strictUnknown) {
|
|
@@ -339,7 +358,7 @@ export class DispatchService {
|
|
|
339
358
|
let peer;
|
|
340
359
|
let remoteComputerID;
|
|
341
360
|
const skipped = [];
|
|
342
|
-
let incapable = false;
|
|
361
|
+
let incapable = false, spentSeen = false;
|
|
343
362
|
if (data.computer === "anywhere") {
|
|
344
363
|
const available = await Promise.all(peers.map(async (candidate) => {
|
|
345
364
|
try {
|
|
@@ -362,13 +381,23 @@ export class DispatchService {
|
|
|
362
381
|
incapable = true;
|
|
363
382
|
if (reason)
|
|
364
383
|
skipped.push({ computer: item.peer.name, reason: reason.slice(0, 200) });
|
|
365
|
-
|
|
384
|
+
if (reason)
|
|
385
|
+
return false;
|
|
386
|
+
// The one quota rule: never place a worker on an account with none left. Low quota still counts as room.
|
|
387
|
+
const spent = outOfQuota(data, item.usage);
|
|
388
|
+
if (spent) {
|
|
389
|
+
spentSeen = true;
|
|
390
|
+
skipped.push({ computer: item.peer.name, reason: spent });
|
|
391
|
+
}
|
|
392
|
+
return !spent;
|
|
366
393
|
});
|
|
367
394
|
skipped.sort((a, b) => a.computer.localeCompare(b.computer));
|
|
368
395
|
const selected = capable
|
|
369
396
|
.sort((a, b) => a.working - b.working || a.peer.name.localeCompare(b.peer.name))[0];
|
|
370
397
|
peer = selected?.peer;
|
|
371
398
|
remoteComputerID = selected?.computerId;
|
|
399
|
+
if (!peer && spentSeen)
|
|
400
|
+
throw new BridgeError(503, `No connected computer has ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} quota left right now.`, { code: "out_of_quota", skipped });
|
|
372
401
|
if (!peer)
|
|
373
402
|
throw new BridgeError(503, incapable ? `No enrolled computer with a running Herdr can run ${data.harness}${data.account ? ` account ${data.account}` : ""}.` : "No enrolled computer with a running Herdr is connected.", skipped.length ? { skipped } : undefined);
|
|
374
403
|
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { type Json, type Target } from "./protocol.js";
|
|
3
|
+
export declare const queuedHandOffSchema: z.ZodObject<{
|
|
4
|
+
target: z.ZodObject<{
|
|
5
|
+
server: z.ZodString;
|
|
6
|
+
workspace: z.ZodString;
|
|
7
|
+
tab: z.ZodString;
|
|
8
|
+
pane: z.ZodString;
|
|
9
|
+
source: z.ZodEnum<{
|
|
10
|
+
claude: "claude";
|
|
11
|
+
codex: "codex";
|
|
12
|
+
copilot: "copilot";
|
|
13
|
+
opencode: "opencode";
|
|
14
|
+
phren: "phren";
|
|
15
|
+
}>;
|
|
16
|
+
session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
17
|
+
}, z.core.$strip>;
|
|
18
|
+
text: z.ZodString;
|
|
19
|
+
deliveryId: z.ZodOptional<z.ZodString>;
|
|
20
|
+
origin: z.ZodOptional<z.ZodObject<{
|
|
21
|
+
server: z.ZodString;
|
|
22
|
+
workspace: z.ZodString;
|
|
23
|
+
tab: z.ZodString;
|
|
24
|
+
pane: z.ZodString;
|
|
25
|
+
source: z.ZodEnum<{
|
|
26
|
+
claude: "claude";
|
|
27
|
+
codex: "codex";
|
|
28
|
+
copilot: "copilot";
|
|
29
|
+
opencode: "opencode";
|
|
30
|
+
phren: "phren";
|
|
31
|
+
}>;
|
|
32
|
+
session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
|
|
33
|
+
}, z.core.$strip>>;
|
|
34
|
+
originComputer: z.ZodOptional<z.ZodString>;
|
|
35
|
+
}, z.core.$strict>;
|
|
36
|
+
export interface QueueOptions {
|
|
37
|
+
validate: (target: Target) => Promise<Json>;
|
|
38
|
+
send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
|
|
39
|
+
notify?: (target: Target, text: string, deliveryId: string, computer: string) => Promise<Json>;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
root?: string;
|
|
42
|
+
}
|
|
43
|
+
/** Settled rows (and notice tombstones) are kept this long, so a late retry of
|
|
44
|
+
* an old delivery id still replays instead of typing again. */
|
|
45
|
+
export declare const HAND_OFF_RETENTION_MS: number;
|
|
46
|
+
/** At most this many rows stay on disk; the oldest settled rows go first. */
|
|
47
|
+
export declare const HAND_OFF_MAX_ROWS = 512;
|
|
48
|
+
/** A durable outbox on the receiving Hook. Persist 'attempting' before input,
|
|
49
|
+
* so a crash in the input/ack gap recovers as uncertain, never as a retry.
|
|
50
|
+
* Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
|
|
51
|
+
* replays instead of typing a second time; a queued or attempting row is never
|
|
52
|
+
* pruned. The sweep runs on enqueue and at most daily from tick(). */
|
|
53
|
+
export declare class HandOffQueue {
|
|
54
|
+
private options;
|
|
55
|
+
private pending;
|
|
56
|
+
private root;
|
|
57
|
+
private now;
|
|
58
|
+
private lastPrune;
|
|
59
|
+
constructor(options: QueueOptions);
|
|
60
|
+
private serial;
|
|
61
|
+
private file;
|
|
62
|
+
private save;
|
|
63
|
+
private read;
|
|
64
|
+
private rows;
|
|
65
|
+
/** Drops settled rows past retention, then the oldest settled rows over the
|
|
66
|
+
* cap (those still owing their sender a notice last). Returns what is kept. */
|
|
67
|
+
private prune;
|
|
68
|
+
private reply;
|
|
69
|
+
enqueue(input: unknown): Promise<Json>;
|
|
70
|
+
status(id: string, target: Target): Promise<Json>;
|
|
71
|
+
private attempt;
|
|
72
|
+
tick(): Promise<void>;
|
|
73
|
+
hasPending(target: Target): Promise<boolean>;
|
|
74
|
+
}
|