@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,235 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { lstat, open, readFile, readdir, unlink } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, computerName } from "./protocol.js";
|
|
6
|
+
import { deliveryIdSchema } from "./prompt-once.js";
|
|
7
|
+
import { agentNotReady } from "./terminal.js";
|
|
8
|
+
export const queuedHandOffSchema = z.object({
|
|
9
|
+
target: targetSchema, text: z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)),
|
|
10
|
+
deliveryId: deliveryIdSchema, origin: targetSchema.optional(), originComputer: computerName.optional(),
|
|
11
|
+
}).strict();
|
|
12
|
+
const rowSchema = queuedHandOffSchema.extend({
|
|
13
|
+
deliveryId: deliveryIdSchema.unwrap(), terminal: z.string().min(1).max(200),
|
|
14
|
+
state: z.enum(["queued", "attempting", "delivered", "uncertain", "failed"]),
|
|
15
|
+
createdAt: z.string().datetime(), updatedAt: z.string().datetime(), error: z.string().max(500).optional(),
|
|
16
|
+
notified: z.boolean().optional(),
|
|
17
|
+
});
|
|
18
|
+
const DAY = 86_400_000;
|
|
19
|
+
/** Settled rows (and notice tombstones) are kept this long, so a late retry of
|
|
20
|
+
* an old delivery id still replays instead of typing again. */
|
|
21
|
+
export const HAND_OFF_RETENTION_MS = 7 * DAY;
|
|
22
|
+
/** At most this many rows stay on disk; the oldest settled rows go first. */
|
|
23
|
+
export const HAND_OFF_MAX_ROWS = 512;
|
|
24
|
+
const settled = (row) => row.state !== "queued" && row.state !== "attempting";
|
|
25
|
+
const sameTarget = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every(key => a[key] === b[key]);
|
|
26
|
+
/** A durable outbox on the receiving Hook. Persist 'attempting' before input,
|
|
27
|
+
* so a crash in the input/ack gap recovers as uncertain, never as a retry.
|
|
28
|
+
* Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
|
|
29
|
+
* replays instead of typing a second time; a queued or attempting row is never
|
|
30
|
+
* pruned. The sweep runs on enqueue and at most daily from tick(). */
|
|
31
|
+
export class HandOffQueue {
|
|
32
|
+
options;
|
|
33
|
+
pending = Promise.resolve();
|
|
34
|
+
root;
|
|
35
|
+
now;
|
|
36
|
+
lastPrune = -Infinity;
|
|
37
|
+
constructor(options) {
|
|
38
|
+
this.options = options;
|
|
39
|
+
this.root = options.root ?? path.join(bridgeRoot(), "hand-offs");
|
|
40
|
+
this.now = options.now ?? Date.now;
|
|
41
|
+
}
|
|
42
|
+
serial(run) {
|
|
43
|
+
const result = this.pending.then(run);
|
|
44
|
+
this.pending = result.catch(() => { });
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
file(id) { return path.join(this.root, `${deliveryIdSchema.unwrap().parse(id)}.json`); }
|
|
48
|
+
async save(row) {
|
|
49
|
+
row.updatedAt = new Date(this.now()).toISOString();
|
|
50
|
+
const file = this.file(row.deliveryId);
|
|
51
|
+
await atomicInPrivateDir(file, rowSchema.parse(row));
|
|
52
|
+
// Ensure the renamed entry survives a host crash as well as a service restart.
|
|
53
|
+
// Windows refuses fsync on a read-only handle (EPERM) and on directories.
|
|
54
|
+
if (process.platform !== "win32")
|
|
55
|
+
for (const target of [file, this.root]) {
|
|
56
|
+
const handle = await open(target, "r");
|
|
57
|
+
try {
|
|
58
|
+
await handle.sync();
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
await handle.close();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
async read(id) {
|
|
66
|
+
const file = this.file(id), info = await lstat(file).catch(error => {
|
|
67
|
+
if (error.code === "ENOENT")
|
|
68
|
+
return undefined;
|
|
69
|
+
throw error;
|
|
70
|
+
});
|
|
71
|
+
if (!info)
|
|
72
|
+
return undefined;
|
|
73
|
+
if (!info.isFile() || info.isSymbolicLink() || info.size > 100_000)
|
|
74
|
+
throw new BridgeError(409, "The hand-off record cannot be read safely.");
|
|
75
|
+
const row = rowSchema.parse(JSON.parse(await readFile(file, "utf8")));
|
|
76
|
+
if (row.state === "attempting") {
|
|
77
|
+
row.state = "uncertain";
|
|
78
|
+
row.error = "The Hook restarted before delivery was confirmed.";
|
|
79
|
+
await this.save(row);
|
|
80
|
+
}
|
|
81
|
+
return row;
|
|
82
|
+
}
|
|
83
|
+
async rows() {
|
|
84
|
+
const names = await readdir(this.root).catch(error => { if (error.code === "ENOENT")
|
|
85
|
+
return []; throw error; });
|
|
86
|
+
const rows = [];
|
|
87
|
+
for (const name of names.sort())
|
|
88
|
+
if (/^[A-Za-z0-9_-]{8,64}\.json$/.test(name)) {
|
|
89
|
+
const row = await this.read(name.slice(0, -5));
|
|
90
|
+
if (row)
|
|
91
|
+
rows.push(row);
|
|
92
|
+
}
|
|
93
|
+
return rows.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.deliveryId.localeCompare(b.deliveryId));
|
|
94
|
+
}
|
|
95
|
+
/** Drops settled rows past retention, then the oldest settled rows over the
|
|
96
|
+
* cap (those still owing their sender a notice last). Returns what is kept. */
|
|
97
|
+
async prune(rows) {
|
|
98
|
+
this.lastPrune = this.now();
|
|
99
|
+
const now = this.now(), drop = new Set();
|
|
100
|
+
for (const row of rows)
|
|
101
|
+
if (settled(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS)
|
|
102
|
+
drop.add(row.deliveryId);
|
|
103
|
+
let excess = rows.length - drop.size - HAND_OFF_MAX_ROWS;
|
|
104
|
+
if (excess > 0) {
|
|
105
|
+
const owesNotice = (row) => (row.origin && !row.notified ? 1 : 0);
|
|
106
|
+
const candidates = rows.filter(row => settled(row) && !drop.has(row.deliveryId))
|
|
107
|
+
.sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
|
|
108
|
+
for (const row of candidates) {
|
|
109
|
+
if (excess-- <= 0)
|
|
110
|
+
break;
|
|
111
|
+
drop.add(row.deliveryId);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
for (const id of drop)
|
|
115
|
+
await unlink(this.file(id)).catch(error => { if (error.code !== "ENOENT")
|
|
116
|
+
throw error; });
|
|
117
|
+
return drop.size ? rows.filter(row => !drop.has(row.deliveryId)) : rows;
|
|
118
|
+
}
|
|
119
|
+
reply(row) {
|
|
120
|
+
return { ok: row.state === "delivered" || row.state === "queued", delivered: row.state === "delivered", queued: row.state === "queued",
|
|
121
|
+
deliveryId: row.deliveryId, state: row.state, target: row.target,
|
|
122
|
+
...(row.state === "uncertain" ? { deliveryUncertain: true } : {}), ...(row.error ? { error: row.error } : {}) };
|
|
123
|
+
}
|
|
124
|
+
enqueue(input) {
|
|
125
|
+
return this.serial(async () => {
|
|
126
|
+
const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
|
|
127
|
+
const prior = await this.read(id);
|
|
128
|
+
if (prior) {
|
|
129
|
+
if (!sameTarget(prior.target, data.target) || prior.text !== data.text)
|
|
130
|
+
throw new BridgeError(409, "This message id was already used for a different message.");
|
|
131
|
+
return { ...this.reply(prior), replayed: true };
|
|
132
|
+
}
|
|
133
|
+
const pane = await this.options.validate(data.target);
|
|
134
|
+
if (typeof pane.terminal_id !== "string")
|
|
135
|
+
throw new BridgeError(409, "This agent has no terminal binding.");
|
|
136
|
+
const at = new Date(this.now()).toISOString();
|
|
137
|
+
const row = { ...data, deliveryId: id, terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at };
|
|
138
|
+
await this.save(row);
|
|
139
|
+
// Older queued messages take precedence even if this one arrives at idle.
|
|
140
|
+
const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && sameTarget(other.target, row.target) && other.state === "queued");
|
|
141
|
+
if (!ahead)
|
|
142
|
+
await this.attempt(row, pane);
|
|
143
|
+
return this.reply(row);
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
status(id, target) {
|
|
147
|
+
return this.serial(async () => { const row = await this.read(id); if (!row || !sameTarget(row.target, target))
|
|
148
|
+
throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
|
|
149
|
+
}
|
|
150
|
+
async attempt(row, pane) {
|
|
151
|
+
try {
|
|
152
|
+
pane ??= await this.options.validate(row.target);
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
if (error instanceof BridgeError && [404, 409].includes(error.status)) {
|
|
156
|
+
row.state = "failed";
|
|
157
|
+
row.error = error.message.slice(0, 500);
|
|
158
|
+
await this.save(row);
|
|
159
|
+
}
|
|
160
|
+
return; // Offline is not gone and does not discard a queued message.
|
|
161
|
+
}
|
|
162
|
+
if (pane.terminal_id !== row.terminal) {
|
|
163
|
+
row.state = "failed";
|
|
164
|
+
row.error = "The worker's terminal changed before delivery.";
|
|
165
|
+
await this.save(row);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (!["idle", "done"].includes(String(pane.agent_status)))
|
|
169
|
+
return;
|
|
170
|
+
let typed = false;
|
|
171
|
+
try {
|
|
172
|
+
const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
|
|
173
|
+
row.state = "attempting";
|
|
174
|
+
await this.save(row);
|
|
175
|
+
typed = true;
|
|
176
|
+
});
|
|
177
|
+
row.state = result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true ? "delivered" : "uncertain";
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
if (agentNotReady(error) || (error instanceof BridgeError && error.details?.code === "hand-off-busy"))
|
|
181
|
+
row.state = "queued"; // Herdr guarantees no input was written.
|
|
182
|
+
else if (!typed) {
|
|
183
|
+
if (!(error instanceof BridgeError) || ![404, 409, 422].includes(error.status))
|
|
184
|
+
return;
|
|
185
|
+
row.state = "failed";
|
|
186
|
+
}
|
|
187
|
+
else
|
|
188
|
+
row.state = "uncertain";
|
|
189
|
+
row.error = (error instanceof Error ? error.message : "Delivery failed.").slice(0, 500);
|
|
190
|
+
}
|
|
191
|
+
if (row.state === "delivered")
|
|
192
|
+
delete row.error;
|
|
193
|
+
await this.save(row);
|
|
194
|
+
}
|
|
195
|
+
tick() {
|
|
196
|
+
return this.serial(async () => {
|
|
197
|
+
let rows = await this.rows();
|
|
198
|
+
if (this.now() - this.lastPrune >= DAY)
|
|
199
|
+
rows = await this.prune(rows);
|
|
200
|
+
const attempted = new Set();
|
|
201
|
+
for (const row of rows)
|
|
202
|
+
if (row.state === "queued") {
|
|
203
|
+
const key = JSON.stringify(row.target);
|
|
204
|
+
if (attempted.has(key))
|
|
205
|
+
continue;
|
|
206
|
+
attempted.add(key);
|
|
207
|
+
await this.attempt(row);
|
|
208
|
+
}
|
|
209
|
+
for (const row of rows)
|
|
210
|
+
if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
|
|
211
|
+
// A notice is itself an idempotent queued hand-off, without an origin.
|
|
212
|
+
const id = `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
|
|
213
|
+
if (row.originComputer) {
|
|
214
|
+
const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, id, row.originComputer).catch(() => undefined);
|
|
215
|
+
if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
|
|
216
|
+
continue;
|
|
217
|
+
row.notified = true;
|
|
218
|
+
await this.save(row);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!await this.read(id)) {
|
|
222
|
+
const pane = await this.options.validate(row.origin).catch(() => undefined);
|
|
223
|
+
if (!pane || typeof pane.terminal_id !== "string")
|
|
224
|
+
continue;
|
|
225
|
+
const at = new Date(this.now()).toISOString();
|
|
226
|
+
await this.save({ deliveryId: id, target: row.origin, text: `Hand-off ${row.deliveryId}: ${row.state}.`, terminal: pane.terminal_id,
|
|
227
|
+
state: "queued", createdAt: at, updatedAt: at });
|
|
228
|
+
}
|
|
229
|
+
row.notified = true;
|
|
230
|
+
await this.save(row);
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
hasPending(target) { return this.serial(async () => (await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
|
|
235
|
+
}
|
|
@@ -21,18 +21,23 @@ export declare const handOffSchema: z.ZodObject<{
|
|
|
21
21
|
session: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
|
|
22
22
|
project: z.ZodOptional<z.ZodString>;
|
|
23
23
|
account: z.ZodOptional<z.ZodString>;
|
|
24
|
-
|
|
24
|
+
deliveryId: z.ZodOptional<z.ZodString>;
|
|
25
|
+
status: z.ZodOptional<z.ZodBoolean>;
|
|
26
|
+
text: z.ZodOptional<z.ZodString>;
|
|
25
27
|
}, z.core.$strict>;
|
|
26
28
|
export type HandOffInput = z.infer<typeof handOffSchema>;
|
|
27
|
-
/**
|
|
28
|
-
*
|
|
29
|
-
* the MCP tool does not take one). */
|
|
29
|
+
/** A stable delivery id names a message on the receiving Hook. The Hook
|
|
30
|
+
* queues busy targets and retains outcomes across restarts. */
|
|
30
31
|
export declare function handOff(input: unknown, options?: {
|
|
31
32
|
deliveryId?: string;
|
|
33
|
+
notifySender?: boolean;
|
|
32
34
|
}): Promise<{
|
|
33
35
|
ok: boolean;
|
|
34
36
|
delivered: boolean;
|
|
35
37
|
target: Target;
|
|
38
|
+
queued?: boolean;
|
|
39
|
+
deliveryId?: string;
|
|
40
|
+
state?: string;
|
|
36
41
|
deliveryUncertain?: boolean;
|
|
37
42
|
unsubmitted?: boolean;
|
|
38
43
|
label?: string;
|
|
@@ -57,6 +62,9 @@ export interface LiveSession {
|
|
|
57
62
|
idleFor?: number;
|
|
58
63
|
/** Set when the main turn ended and this many background tasks keep the session `working`. */
|
|
59
64
|
backgroundTasks?: number;
|
|
65
|
+
stalled?: boolean;
|
|
66
|
+
stallFor?: number;
|
|
67
|
+
stalledSince?: string;
|
|
60
68
|
}
|
|
61
69
|
/** A registered computer this Hook cannot see, with the other names the store
|
|
62
70
|
* registers it under. */
|
package/dist/bridge/hand-off.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { deliveryIdSchema } from "./prompt-once.js";
|
|
3
|
+
import { terminalPaneFromEnv } from "./terminal.js";
|
|
1
4
|
import { z } from "zod";
|
|
2
5
|
import { computerName } from "./computers.js";
|
|
3
6
|
import { hookRequest } from "./client.js";
|
|
@@ -19,8 +22,12 @@ export const handOffSchema = z.object({
|
|
|
19
22
|
project: projectName.optional().describe("Project slug this hand-off belongs to, for conductor grant matching."),
|
|
20
23
|
account: z.string().refine(isAccountSlug, "Account must be default or a lowercase slug.").optional()
|
|
21
24
|
.describe("Claude account id the session must run under (default, or a slug). A session of another account is refused; a row without an account counts as default."),
|
|
22
|
-
|
|
25
|
+
deliveryId: deliveryIdSchema.describe("Stable message id to keep on retries or to check status."),
|
|
26
|
+
status: z.boolean().optional().describe("Read delivery status without sending; requires deliveryId."),
|
|
27
|
+
text: promptText.optional().describe("Prompt to deliver to the existing session, at most 32768 characters."),
|
|
23
28
|
}).strict().superRefine((value, context) => {
|
|
29
|
+
if (value.status ? !value.deliveryId || value.text !== undefined : !value.text)
|
|
30
|
+
context.addIssue({ code: "custom", message: "A send requires text; a status query requires deliveryId and no text." });
|
|
24
31
|
if ((value.target === undefined) === (value.session === undefined))
|
|
25
32
|
context.addIssue({ code: "custom", message: "Provide exactly one of target or session." });
|
|
26
33
|
});
|
|
@@ -51,9 +58,8 @@ async function targetFromOverview(request, session, server, account) {
|
|
|
51
58
|
throw new BridgeError(409, `That session runs under account ${found.account}, not ${account}.`, { code: "account_mismatch" });
|
|
52
59
|
return found;
|
|
53
60
|
}
|
|
54
|
-
/**
|
|
55
|
-
*
|
|
56
|
-
* the MCP tool does not take one). */
|
|
61
|
+
/** A stable delivery id names a message on the receiving Hook. The Hook
|
|
62
|
+
* queues busy targets and retains outcomes across restarts. */
|
|
57
63
|
export async function handOff(input, options = {}) {
|
|
58
64
|
const data = handOffSchema.parse(input);
|
|
59
65
|
let request;
|
|
@@ -83,7 +89,16 @@ export async function handOff(input, options = {}) {
|
|
|
83
89
|
if (peer && target.server !== peer.server)
|
|
84
90
|
throw new BridgeError(400, "The target belongs to a different Herdr server on that computer.");
|
|
85
91
|
const grant = await findGrant({ action: "hand_off", project: data.project, computer: data.computer });
|
|
86
|
-
|
|
92
|
+
let origin;
|
|
93
|
+
if (!data.status && options.notifySender !== false) {
|
|
94
|
+
const here = await terminalPaneFromEnv();
|
|
95
|
+
if (here)
|
|
96
|
+
origin = await findInOverview((route, body) => hookRequest(route, body), found => found.server === here.server && found.pane === here.pane, here.server).then(found => found?.target, () => undefined);
|
|
97
|
+
}
|
|
98
|
+
const originComputer = peer && origin ? await hookRequest("/v1/health").then(health => object(health.computer).name, () => undefined) : undefined;
|
|
99
|
+
const deliveryId = data.deliveryId ?? options.deliveryId ?? randomUUID().replaceAll("-", "");
|
|
100
|
+
const result = await request(data.status ? "/v1/hand-off/status" : "/v1/hand-off", { target, deliveryId,
|
|
101
|
+
...(!data.status ? { text: data.text, ...(origin ? { origin, ...(typeof originComputer === "string" ? { originComputer } : {}) } : {}) } : {}) });
|
|
87
102
|
// A bare ok only acknowledges typing. Even an unchanged, busy Codex pane
|
|
88
103
|
// may have kept the text in its composer instead of submitting a turn.
|
|
89
104
|
const delivered = result.ok === true && result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true;
|
|
@@ -92,8 +107,12 @@ export async function handOff(input, options = {}) {
|
|
|
92
107
|
const label = resolved ? resolved.label
|
|
93
108
|
: await findInOverview(request, found => found.pane === target.pane && found.session === target.session, peer?.server)
|
|
94
109
|
.then(found => found?.label, () => undefined);
|
|
95
|
-
|
|
96
|
-
|
|
110
|
+
const queued = result.queued === true && result.deliveryUncertain !== true;
|
|
111
|
+
return { ok: delivered || queued, delivered, target,
|
|
112
|
+
...(queued ? { queued: true } : {}),
|
|
113
|
+
...(typeof result.deliveryId === "string" ? { deliveryId: result.deliveryId } : {}),
|
|
114
|
+
...(typeof result.state === "string" ? { state: result.state } : {}),
|
|
115
|
+
...(!delivered && !queued && (result.ok === true || result.deliveryUncertain === true) ? { deliveryUncertain: true } : {}),
|
|
97
116
|
...(result.unsubmitted === true ? { unsubmitted: true } : {}),
|
|
98
117
|
...(label ? { label } : {}), ...(grant ? { granted: grantLabel(grant) } : {}) };
|
|
99
118
|
}
|
|
@@ -116,6 +135,7 @@ function sessionsFrom(overview, computer, local, now = Date.now()) {
|
|
|
116
135
|
title: text(tab.title), agent: tab.agent, status: text(tab.agentStatus), role: text(tab.role),
|
|
117
136
|
branch: text(tab.branch), model: text(tab.model), ...(typeof object(tab.account).id === "string" ? { account: String(object(tab.account).id) } : {}), ...(target.success ? { target: target.data } : {}),
|
|
118
137
|
...(typeof tab.backgroundTasks === "number" && tab.backgroundTasks > 0 ? { backgroundTasks: tab.backgroundTasks } : {}),
|
|
138
|
+
...(tab.stalled === true ? { stalled: true, stallFor: Number(tab.stallFor), stalledSince: String(tab.stalledSince) } : {}),
|
|
119
139
|
...(Number.isFinite(changedAt) ? { idleFor: Math.max(0, Math.floor((now - changedAt) / 1000)) } : {}) });
|
|
120
140
|
}
|
|
121
141
|
return sessions;
|
package/dist/bridge/install.js
CHANGED
|
@@ -15,7 +15,9 @@ import { bridgeRoot, object, objects, atomic, socketPath } from "./protocol.js";
|
|
|
15
15
|
import { herdrRoot } from "./herdr.js";
|
|
16
16
|
import { health } from "./transport.js";
|
|
17
17
|
import { FAST_HOOK_SOURCE, fastHookPath } from "./hook-fast.js";
|
|
18
|
+
import { installAskpass, removeAskpass } from "./sudo.js";
|
|
18
19
|
import { readStoredVoice, SPEECH_VOICE_ENV, writeSpeechVoice } from "./speech-voice.js";
|
|
20
|
+
import { carryCodexHookTrust } from "./codex-hook-trust.js";
|
|
19
21
|
const exec = promisify(execFile);
|
|
20
22
|
const label = "com.phren.hook";
|
|
21
23
|
const unit = "phren-hook.service";
|
|
@@ -245,6 +247,7 @@ export async function install(version, noService = false) {
|
|
|
245
247
|
root, herdr, store: modules.store, profile: modules.profile, node: process.execPath,
|
|
246
248
|
bundle: path.join(root, "current/bridge-hook.mjs"), socket: socketPath(), timing: path.join(root, "gateway.json"),
|
|
247
249
|
}), 0o700);
|
|
250
|
+
await installAskpass(process.execPath, path.join(root, "current/bridge-hook.mjs"));
|
|
248
251
|
const environmentPath = [path.dirname(process.execPath), path.join(homedir(), ".local/bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin"].join(":");
|
|
249
252
|
const program = path.join(root, "current/bridge-hook.mjs");
|
|
250
253
|
if (!noService) {
|
|
@@ -308,6 +311,8 @@ export async function install(version, noService = false) {
|
|
|
308
311
|
console.log(`Updated ${after.changed} Phren iPhone key(s); other keys were preserved.`);
|
|
309
312
|
}
|
|
310
313
|
await atomic(path.join(root, "installed.json"), JSON.stringify({ version, previous: previous?.version === version ? previous.previous : previous?.version, node: process.execPath, gateway }, null, 2) + "\n");
|
|
314
|
+
// Last, so a failed install restores hooks.json without leaving trust for entries it no longer has.
|
|
315
|
+
await carryCodexHookTrust(program, codexHooksBefore(hookEdits));
|
|
311
316
|
console.log("Agent hooks installed. In Codex, review the new Phren entries in /hooks. Existing agents may need to resume before new hooks load.");
|
|
312
317
|
console.log(`SSH gateway: ${gateway}${gateway === "node" ? " (no socat or nc -U found)" : ""}.`);
|
|
313
318
|
console.log(`Phren Hook ${version} installed${noService ? " (service not started)" : " and running"}. Run phren bridge doctor.`);
|
|
@@ -339,6 +344,7 @@ export async function uninstall() {
|
|
|
339
344
|
}
|
|
340
345
|
await applyAgentHooks(await planAgentHooks(path.join(bridgeRoot(), "current/bridge-hook.mjs"), true));
|
|
341
346
|
await applyOpencodePlugin(true);
|
|
347
|
+
await removeAskpass();
|
|
342
348
|
// Preserve journal, settings, uploaded images, rollback version and SSH backups.
|
|
343
349
|
console.log("Phren Hook stopped and its background service removed. Remove phren-iphone, phren-android and phren-computer keys from authorized_keys to revoke device access. Local data remains in " + bridgeRoot());
|
|
344
350
|
}
|
|
@@ -485,6 +491,8 @@ async function applyAgentHooks(edits) {
|
|
|
485
491
|
await atomic(file, after);
|
|
486
492
|
}
|
|
487
493
|
}
|
|
494
|
+
/** Codex's hooks.json as it stood before `edits` rewrote it, when they did. */
|
|
495
|
+
const codexHooksBefore = (edits) => edits.find(edit => edit.file === path.join(codexHome(), "hooks.json"))?.before;
|
|
488
496
|
async function restoreAgentHooks(edits) {
|
|
489
497
|
for (const { file, before, after } of edits) {
|
|
490
498
|
// A concurrent user edit always wins over rollback.
|
|
@@ -506,7 +514,10 @@ export async function rollback() {
|
|
|
506
514
|
// The version now in `current/` decides whether Claude's callbacks run its
|
|
507
515
|
// forwarder or, from before the forwarder, its bundle.
|
|
508
516
|
const root = bridgeRoot();
|
|
509
|
-
|
|
517
|
+
const program = path.join(root, "current/bridge-hook.mjs");
|
|
518
|
+
const edits = await planAgentHooks(program, false, moduleSnapshot(defaultPhrenPath(), undefined, true), await currentHasFastHook(root));
|
|
519
|
+
await applyAgentHooks(edits);
|
|
520
|
+
await carryCodexHookTrust(program, codexHooksBefore(edits));
|
|
510
521
|
await atomic(path.join(bridgeRoot(), "installed.json"), JSON.stringify({ version: config.previous, previous: config.version }) + "\n");
|
|
511
522
|
}
|
|
512
523
|
export async function reconcileModuleHooks(store, profile) {
|
|
@@ -515,7 +526,10 @@ export async function reconcileModuleHooks(store, profile) {
|
|
|
515
526
|
// Synced enablement alone never installs a host service or enrolls a key.
|
|
516
527
|
if (!await missingFile(readFile(path.join(root, "installed.json"))))
|
|
517
528
|
return;
|
|
518
|
-
|
|
529
|
+
const program = path.join(root, "current/bridge-hook.mjs");
|
|
530
|
+
const edits = await planAgentHooks(program, false, modules, await currentHasFastHook(root));
|
|
531
|
+
await applyAgentHooks(edits);
|
|
532
|
+
await carryCodexHookTrust(program, codexHooksBefore(edits));
|
|
519
533
|
await applyOpencodePlugin(!modules.has("hook"));
|
|
520
534
|
if (!modules.has("hook"))
|
|
521
535
|
await stopService();
|
|
@@ -33,5 +33,17 @@ export declare function dialogStatus(server: string, pane: string, terminal: str
|
|
|
33
33
|
status: string;
|
|
34
34
|
seq: number;
|
|
35
35
|
} | undefined>;
|
|
36
|
+
/** A Codex that has not sent its first lifecycle event, read from its
|
|
37
|
+
* screen: blocked on a startup menu (folder trust, hooks to review), working
|
|
38
|
+
* while it shows its interrupt hint (a turn whose hooks did not run), idle
|
|
39
|
+
* once its composer and footer are drawn, else undefined (still starting). */
|
|
40
|
+
export declare function codexStartupStatus(screen: string): "blocked" | "working" | "idle" | undefined;
|
|
41
|
+
/** The status of a hooked agent in `pane` that has sent no lifecycle event
|
|
42
|
+
* yet: Codex's screen read (`codexStartupStatus`) at most once per
|
|
43
|
+
* DIALOG_READ_MS, else undefined. Its first event takes over for good. */
|
|
44
|
+
export declare function startupStatus(server: string, pane: string, terminal: string, agent: string, read: () => Promise<string>): Promise<{
|
|
45
|
+
status: string;
|
|
46
|
+
seq: number;
|
|
47
|
+
} | undefined>;
|
|
36
48
|
/** For tests. */
|
|
37
49
|
export declare function resetPaneStatus(): void;
|
|
@@ -14,6 +14,11 @@
|
|
|
14
14
|
// looks "working" to all of that. While a pane is working its screen is read,
|
|
15
15
|
// at most once per DIALOG_READ_MS, and a dialog there makes the pane blocked
|
|
16
16
|
// until the dialog is gone.
|
|
17
|
+
//
|
|
18
|
+
// Codex holds its SessionStart hook until the first turn, so a Codex that has
|
|
19
|
+
// just opened has sent nothing yet and would stay "unknown", which refuses
|
|
20
|
+
// the phone's first message. Until its first event its screen says instead:
|
|
21
|
+
// a menu (folder trust, hooks to review) is blocked, its composer idle.
|
|
17
22
|
import { readFile } from "node:fs/promises";
|
|
18
23
|
import { stripTerminal } from "../terminal-text.js";
|
|
19
24
|
import { bindingPath } from "./agent-hook-stores.js";
|
|
@@ -135,5 +140,49 @@ export async function dialogStatus(server, pane, terminal, agent, base, read) {
|
|
|
135
140
|
return { status: "blocked", seq: entry.shown.seq };
|
|
136
141
|
return { status: base.status, seq: Math.max(base.seq, entry.cleared ?? 0) };
|
|
137
142
|
}
|
|
143
|
+
/** A Codex that has not sent its first lifecycle event, read from its
|
|
144
|
+
* screen: blocked on a startup menu (folder trust, hooks to review), working
|
|
145
|
+
* while it shows its interrupt hint (a turn whose hooks did not run), idle
|
|
146
|
+
* once its composer and footer are drawn, else undefined (still starting). */
|
|
147
|
+
export function codexStartupStatus(screen) {
|
|
148
|
+
const text = stripTerminal(screen);
|
|
149
|
+
if (visibleTerminalChoice(text))
|
|
150
|
+
return "blocked";
|
|
151
|
+
if (/\besc to interrupt\b/i.test(text))
|
|
152
|
+
return "working";
|
|
153
|
+
const lines = text.split(/\r?\n/).map(line => line.trimEnd()).filter(line => line.trim());
|
|
154
|
+
let composer = lines.length - 1;
|
|
155
|
+
while (composer >= 0 && !/^\u203a(?:\s|$)/.test(lines[composer]))
|
|
156
|
+
composer -= 1;
|
|
157
|
+
// The composer sits above a footer or two: "? for shortcuts" (0.158), or
|
|
158
|
+
// just the model line (0.155). A "\u203a" row higher up is an earlier prompt.
|
|
159
|
+
return composer >= 0 && composer >= lines.length - 3 && lines.length - composer > 1 ? "idle" : undefined;
|
|
160
|
+
}
|
|
161
|
+
const startups = new Map();
|
|
162
|
+
/** The status of a hooked agent in `pane` that has sent no lifecycle event
|
|
163
|
+
* yet: Codex's screen read (`codexStartupStatus`) at most once per
|
|
164
|
+
* DIALOG_READ_MS, else undefined. Its first event takes over for good. */
|
|
165
|
+
export async function startupStatus(server, pane, terminal, agent, read) {
|
|
166
|
+
if (agent !== "codex")
|
|
167
|
+
return undefined;
|
|
168
|
+
const id = key(server, pane);
|
|
169
|
+
let entry = startups.get(id);
|
|
170
|
+
if (!entry || entry.terminal !== terminal) {
|
|
171
|
+
entry = { terminal, readAt: 0 };
|
|
172
|
+
startups.delete(id);
|
|
173
|
+
while (startups.size >= 512)
|
|
174
|
+
startups.delete(startups.keys().next().value);
|
|
175
|
+
startups.set(id, entry);
|
|
176
|
+
}
|
|
177
|
+
const now = Date.now();
|
|
178
|
+
if (now - entry.readAt >= DIALOG_READ_MS) {
|
|
179
|
+
entry.readAt = now;
|
|
180
|
+
// A failed read says nothing: the pane keeps what it had.
|
|
181
|
+
const seen = await read().then(codexStartupStatus, () => entry.status?.status);
|
|
182
|
+
if (seen !== entry.status?.status)
|
|
183
|
+
entry.status = seen ? { status: seen, seq: ++sequence } : undefined;
|
|
184
|
+
}
|
|
185
|
+
return entry.status;
|
|
186
|
+
}
|
|
138
187
|
/** For tests. */
|
|
139
|
-
export function resetPaneStatus() { entries.clear(); dialogs.clear(); }
|
|
188
|
+
export function resetPaneStatus() { entries.clear(); dialogs.clear(); startups.clear(); }
|
package/dist/bridge/push.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type RequestKind } from "./approval-summary.js";
|
|
3
|
+
import type { SudoRequestView } from "./sudo.js";
|
|
3
4
|
/** A phone registered through the phren push relay: the relay knows where to
|
|
4
5
|
* deliver, and `key` (32 bytes, base64url) encrypts what the notification says
|
|
5
6
|
* so only the phone reads it. The phone made the key and sent it over SSH. */
|
|
@@ -66,6 +67,10 @@ export interface SchedulePushResult {
|
|
|
66
67
|
}
|
|
67
68
|
export declare function scheduleCollapseId(kind: SchedulePushKind, runId: string): string;
|
|
68
69
|
export declare function approvalPushPayload(value: ApprovalPush, host?: string): Record<string, unknown>;
|
|
70
|
+
/** A sudo request waiting for its password. The command is what the owner
|
|
71
|
+
* approves; the password itself is typed only in the app, never in a
|
|
72
|
+
* notification action. */
|
|
73
|
+
export declare function sudoPushPayload(value: SudoRequestView, host?: string): Record<string, unknown>;
|
|
69
74
|
export declare function fanoutBlockedPushPayload(value: FanoutBlockedPush): Record<string, unknown>;
|
|
70
75
|
export declare function schedulePushPayload(value: SchedulePush): Record<string, unknown>;
|
|
71
76
|
/** What `phren bridge doctor` prints when the Hook has no APNs sender. */
|
|
@@ -114,6 +119,7 @@ export declare class ApprovalPushService {
|
|
|
114
119
|
/** One phone: the relay when it registered through one, otherwise direct. */
|
|
115
120
|
private send;
|
|
116
121
|
notify(value: ApprovalPush): Promise<boolean>;
|
|
122
|
+
notifySudo(value: SudoRequestView): Promise<boolean>;
|
|
117
123
|
/** A headless worker whose permission the plugin refused. Approval-registered
|
|
118
124
|
* phones already accept agent alerts; the payload carries the reason so the
|
|
119
125
|
* notification is actionable on its own. */
|
package/dist/bridge/push.js
CHANGED
|
@@ -45,6 +45,19 @@ export function approvalPushPayload(value, host) {
|
|
|
45
45
|
request, requestKind: value.requestKind ?? (value.question ? "question" : "other") },
|
|
46
46
|
};
|
|
47
47
|
}
|
|
48
|
+
/** A sudo request waiting for its password. The command is what the owner
|
|
49
|
+
* approves; the password itself is typed only in the app, never in a
|
|
50
|
+
* notification action. */
|
|
51
|
+
export function sudoPushPayload(value, host) {
|
|
52
|
+
const command = shortApproval(value.command) || "sudo";
|
|
53
|
+
return {
|
|
54
|
+
aps: {
|
|
55
|
+
alert: { title: `sudo on ${value.computer}`, body: command },
|
|
56
|
+
sound: "default", category: "PHREN_SUDO", "interruption-level": "time-sensitive",
|
|
57
|
+
},
|
|
58
|
+
phren: { version: 1, kind: "sudo", id: value.id, ...(host ? { host } : {}), computer: value.computer, command, expiresAt: value.expiresAt },
|
|
59
|
+
};
|
|
60
|
+
}
|
|
48
61
|
export function fanoutBlockedPushPayload(value) {
|
|
49
62
|
return {
|
|
50
63
|
aps: { alert: { title: `${value.label} blocked`, body: value.reason }, sound: "default", category: "PHREN_FANOUT" },
|
|
@@ -238,6 +251,14 @@ export class ApprovalPushService {
|
|
|
238
251
|
expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: value.binding,
|
|
239
252
|
})))).some(Boolean);
|
|
240
253
|
}
|
|
254
|
+
async notifySudo(value) {
|
|
255
|
+
const devices = this.reachable.filter(device => device.kinds.includes("approval"));
|
|
256
|
+
if (!devices.length)
|
|
257
|
+
return false;
|
|
258
|
+
return (await Promise.all(devices.map(device => this.send(device, sudoPushPayload(value, device.hostID), {
|
|
259
|
+
expiration: String(Math.floor(Date.parse(value.expiresAt) / 1000)), collapseId: `sudo-${value.id}`,
|
|
260
|
+
})))).some(Boolean);
|
|
261
|
+
}
|
|
241
262
|
/** A headless worker whose permission the plugin refused. Approval-registered
|
|
242
263
|
* phones already accept agent alerts; the payload carries the reason so the
|
|
243
264
|
* notification is actionable on its own. */
|
|
@@ -11,7 +11,7 @@ export declare function createScheduleLauncher(launchHerdr: HerdrLauncher, store
|
|
|
11
11
|
* since an open run blocks its schedule for good.
|
|
12
12
|
*/
|
|
13
13
|
export declare function resumeScheduleRun(run: ScheduleRun, schedule: Schedule, signal: AbortSignal, watch?: typeof watchHerdrRun): Promise<ScheduleRunOutcome>;
|
|
14
|
-
/** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
|
|
14
|
+
/** The environment a headless run gets: this Hook's, SUDO_ASKPASS, plus the chosen Claude account's config directory. */
|
|
15
15
|
export declare function headlessEnv(schedule: Schedule, env?: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
|
|
16
16
|
export declare function headlessCommand(schedule: Schedule, cwd: string): {
|
|
17
17
|
file: string;
|
|
@@ -3,6 +3,7 @@ import { createWriteStream } from "node:fs";
|
|
|
3
3
|
import { mkdir, readFile } from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { finished as streamFinished } from "node:stream/promises";
|
|
6
|
+
import { askpassEnv } from "./sudo.js";
|
|
6
7
|
import { claudeHome, claudeLaunchEnv } from "./claude-accounts.js";
|
|
7
8
|
import { fanoutRoot } from "./fanouts.js";
|
|
8
9
|
import { pretrustFolder } from "./folder-trust.js";
|
|
@@ -90,8 +91,11 @@ async function promptWhenReady(server, paneId, text, signal, waitMs = 60_000) {
|
|
|
90
91
|
}
|
|
91
92
|
}
|
|
92
93
|
}
|
|
93
|
-
/** The environment a headless run gets: this Hook's, plus the chosen Claude account's config directory. */
|
|
94
|
+
/** The environment a headless run gets: this Hook's, SUDO_ASKPASS, plus the chosen Claude account's config directory. */
|
|
94
95
|
export function headlessEnv(schedule, env = process.env) {
|
|
96
|
+
const askpass = askpassEnv();
|
|
97
|
+
if (askpass.SUDO_ASKPASS)
|
|
98
|
+
env = { ...env, ...askpass };
|
|
95
99
|
if (!schedule.account || schedule.harness !== "claude")
|
|
96
100
|
return env;
|
|
97
101
|
const home = claudeHome(schedule.account, env);
|
|
@@ -36,7 +36,10 @@ export interface StartupWatchEnv {
|
|
|
36
36
|
* `background`: Claude Code background tasks (shells, subagents, monitors) started in
|
|
37
37
|
* the transcript's tail with no task-notification or TaskStop ending them yet.
|
|
38
38
|
* `finishedTasks`: when each Claude background task the tail shows finishing
|
|
39
|
-
* finished (its first final task-notification's timestamp), one per task.
|
|
39
|
+
* finished (its first final task-notification's timestamp), one per task.
|
|
40
|
+
* `awaited`: those of the running tasks that are shells or monitors started
|
|
41
|
+
* since the owner's last prompt, other than streams that never end (a log
|
|
42
|
+
* tail, a watcher, a dev server). Sub-agents are left to the child tree. */
|
|
40
43
|
export interface FinalTurn {
|
|
41
44
|
completed: boolean;
|
|
42
45
|
lastAssistant?: string;
|
|
@@ -44,9 +47,20 @@ export interface FinalTurn {
|
|
|
44
47
|
interrupted?: boolean;
|
|
45
48
|
background?: number;
|
|
46
49
|
finishedTasks?: string[];
|
|
50
|
+
awaited?: number;
|
|
47
51
|
}
|
|
48
52
|
/** The public text of one assistant row, without reasoning or tool output. */
|
|
49
53
|
export declare function publicAssistant(raw: Json, source: Provider): string | undefined;
|
|
54
|
+
/** Claude Code background work a transcript line starts or ends, by task id:
|
|
55
|
+
* a backgrounded Bash call, an async subagent or a Monitor start one; a
|
|
56
|
+
* task-notification with a final status, or a TaskStop, ends it. A
|
|
57
|
+
* persistent monitor runs for the whole session and is never waited on.
|
|
58
|
+
* `finished` keeps when each task's first final notification was written.
|
|
59
|
+
* A notification reaching an idle session is written as a queue-operation
|
|
60
|
+
* row, and may stay there with no new turn to deliver it. */
|
|
61
|
+
/** A backgrounded command that runs until killed rather than finishing:
|
|
62
|
+
* following a log, watching files, serving a dev build. Nobody waits on it. */
|
|
63
|
+
export declare const ENDLESS_COMMAND: RegExp;
|
|
50
64
|
/** The last assistant reply in a transcript and whether its turn finished.
|
|
51
65
|
* A person's message after the reply opens a new turn, so it clears both. */
|
|
52
66
|
export declare function finalTurnFromLines(lines: readonly string[], source: ScheduleHarness): FinalTurn;
|