@phren/cli 0.3.28 → 0.3.31
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/agent-hooks.d.ts +5 -55
- package/dist/bridge/agent-hooks.js +22 -155
- package/dist/bridge/codex-servers.d.ts +12 -0
- package/dist/bridge/codex-servers.js +35 -3
- package/dist/bridge/codex-thread-origin.d.ts +12 -0
- package/dist/bridge/codex-thread-origin.js +31 -0
- package/dist/bridge/hand-off-queue.d.ts +16 -0
- package/dist/bridge/hand-off-queue.js +62 -19
- package/dist/bridge/hook-main.js +12 -2
- package/dist/bridge/prompt-deliveries.d.ts +99 -0
- package/dist/bridge/prompt-deliveries.js +327 -0
- package/dist/bridge/prompt-once.d.ts +2 -0
- package/dist/bridge/prompt-once.js +2 -0
- package/dist/bridge/resources.d.ts +21 -0
- package/dist/bridge/resources.js +58 -2
- package/dist/bridge/server-launch.js +2 -1
- package/dist/bridge/server-pane-routes.js +72 -34
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +34 -3
- package/dist/bridge/server-stream.js +4 -2
- package/dist/bridge/server.js +12 -3
- package/dist/bridge/simulators.d.ts +3 -1
- package/dist/bridge/simulators.js +40 -5
- package/dist/bridge/sudo.d.ts +1 -1
- package/dist/bridge/sudo.js +51 -17
- package/dist/bridge/task-routes.d.ts +282 -0
- package/dist/bridge/task-routes.js +162 -0
- package/dist/bridge/uploads.d.ts +4 -0
- package/dist/bridge/uploads.js +15 -0
- package/dist/bridge-hook.mjs +18218 -15566
- package/dist/cli/namespaces-store.js +32 -1
- package/dist/cli/namespaces-tasks.d.ts +1 -0
- package/dist/cli/namespaces-tasks.js +55 -4
- package/dist/cli/ops.d.ts +2 -1
- package/dist/cli/ops.js +20 -4
- package/dist/cli-registry.js +5 -4
- package/dist/data/task-contract.d.ts +75 -0
- package/dist/data/task-contract.js +161 -0
- package/dist/data/task-format.d.ts +20 -0
- package/dist/data/task-format.js +55 -0
- package/dist/data/task-metadata.d.ts +10 -0
- package/dist/data/task-metadata.js +24 -0
- package/dist/data/task-store-directory.d.ts +21 -0
- package/dist/data/task-store-directory.js +37 -0
- package/dist/data/tasks.d.ts +38 -2
- package/dist/data/tasks.js +221 -28
- package/dist/generated/memory-ui-graph.browser.js +328 -333
- package/dist/init/setup.js +2 -2
- package/dist/memory-ui-graph.runtime.js +328 -333
- package/dist/modules/registry.js +3 -3
- package/dist/shell/input.js +49 -4
- package/dist/shell/state-store.d.ts +1 -0
- package/dist/shell/state-store.js +2 -0
- package/dist/shell/view.js +19 -3
- package/dist/store-registry.d.ts +12 -1
- package/dist/store-registry.js +52 -4
- package/dist/sync/task-claim.d.ts +1 -0
- package/dist/sync/task-claim.js +8 -1
- package/dist/sync/task-merge.d.ts +0 -9
- package/dist/sync/task-merge.js +48 -1
- package/dist/tools/tasks.js +31 -18
- package/dist/ui/page.js +1 -0
- package/dist/ui/scripts.js +64 -5
- package/dist/ui/server.js +18 -0
- package/package.json +8 -8
|
@@ -22,7 +22,8 @@ export const HAND_OFF_RETENTION_MS = 7 * DAY;
|
|
|
22
22
|
/** At most this many rows stay on disk; the oldest settled rows go first. */
|
|
23
23
|
export const HAND_OFF_MAX_ROWS = 512;
|
|
24
24
|
const settled = (row) => row.state !== "queued" && row.state !== "attempting";
|
|
25
|
-
|
|
25
|
+
/** A row follows its pane's conversation, so it is found by pane. */
|
|
26
|
+
const samePane = (a, b) => ["server", "workspace", "tab", "pane", "source"].every(key => a[key] === b[key]);
|
|
26
27
|
/** A durable outbox on the receiving Hook. Persist 'attempting' before input,
|
|
27
28
|
* so a crash in the input/ack gap recovers as uncertain, never as a retry.
|
|
28
29
|
* Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
|
|
@@ -34,6 +35,7 @@ export class HandOffQueue {
|
|
|
34
35
|
root;
|
|
35
36
|
now;
|
|
36
37
|
lastPrune = -Infinity;
|
|
38
|
+
ticking;
|
|
37
39
|
constructor(options) {
|
|
38
40
|
this.options = options;
|
|
39
41
|
this.root = options.root ?? path.join(bridgeRoot(), "hand-offs");
|
|
@@ -126,30 +128,52 @@ export class HandOffQueue {
|
|
|
126
128
|
const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
|
|
127
129
|
const prior = await this.read(id);
|
|
128
130
|
if (prior) {
|
|
129
|
-
if (!
|
|
131
|
+
if (!samePane(prior.target, data.target) || prior.text !== data.text)
|
|
130
132
|
throw new BridgeError(409, "This message id was already used for a different message.");
|
|
131
133
|
return { ...this.reply(prior), replayed: true };
|
|
132
134
|
}
|
|
133
|
-
const
|
|
135
|
+
const row = { ...data, deliveryId: id };
|
|
136
|
+
const pane = await this.validate(row);
|
|
134
137
|
if (typeof pane.terminal_id !== "string")
|
|
135
138
|
throw new BridgeError(409, "This agent has no terminal binding.");
|
|
136
139
|
const at = new Date(this.now()).toISOString();
|
|
137
|
-
|
|
140
|
+
Object.assign(row, { terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at });
|
|
138
141
|
await this.save(row);
|
|
139
142
|
// 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 &&
|
|
143
|
+
const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && samePane(other.target, row.target) && other.state === "queued");
|
|
141
144
|
if (!ahead)
|
|
142
145
|
await this.attempt(row, pane);
|
|
143
146
|
return this.reply(row);
|
|
144
147
|
});
|
|
145
148
|
}
|
|
146
149
|
status(id, target) {
|
|
147
|
-
return this.serial(async () => { const row = await this.read(id); if (!row || !
|
|
150
|
+
return this.serial(async () => { const row = await this.read(id); if (!row || !samePane(row.target, target))
|
|
148
151
|
throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
|
|
149
152
|
}
|
|
153
|
+
/** Validates the row's target. When the pane's conversation was replaced
|
|
154
|
+
* in the same terminal (a Codex thread change, a Claude /clear), the row
|
|
155
|
+
* follows it: a queued message is for the pane, not for a conversation
|
|
156
|
+
* that is no longer there. Saved by the caller's next state change. */
|
|
157
|
+
async validate(row) {
|
|
158
|
+
try {
|
|
159
|
+
return await this.options.validate(row.target);
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
if (!(error instanceof BridgeError) || error.status !== 409 || !this.options.current)
|
|
163
|
+
throw error;
|
|
164
|
+
const now = await this.options.current(row.target).catch(() => undefined);
|
|
165
|
+
if (!now || now.session === row.target.session || (row.terminal && now.terminal !== row.terminal))
|
|
166
|
+
throw error;
|
|
167
|
+
row.target = { ...row.target, session: now.session };
|
|
168
|
+
return await this.options.validate(row.target);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
150
171
|
async attempt(row, pane) {
|
|
172
|
+
const session = row.target.session;
|
|
151
173
|
try {
|
|
152
|
-
pane ??= await this.
|
|
174
|
+
pane ??= await this.validate(row);
|
|
175
|
+
if (row.target.session !== session)
|
|
176
|
+
await this.save(row);
|
|
153
177
|
}
|
|
154
178
|
catch (error) {
|
|
155
179
|
if (error instanceof BridgeError && [404, 409].includes(error.status)) {
|
|
@@ -192,15 +216,21 @@ export class HandOffQueue {
|
|
|
192
216
|
delete row.error;
|
|
193
217
|
await this.save(row);
|
|
194
218
|
}
|
|
219
|
+
/** Coalesced: the Hook calls this every 5 s whether or not the last tick
|
|
220
|
+
* finished, and queuing each behind the lock would hold every enqueue and
|
|
221
|
+
* status behind a backlog that grows faster than a slow tick drains it. */
|
|
195
222
|
tick() {
|
|
196
|
-
return this.
|
|
223
|
+
return this.ticking ??= this.sweep().finally(() => { this.ticking = undefined; });
|
|
224
|
+
}
|
|
225
|
+
async sweep() {
|
|
226
|
+
const remote = await this.serial(async () => {
|
|
197
227
|
let rows = await this.rows();
|
|
198
228
|
if (this.now() - this.lastPrune >= DAY)
|
|
199
229
|
rows = await this.prune(rows);
|
|
200
|
-
const attempted = new Set();
|
|
230
|
+
const attempted = new Set(), remote = [];
|
|
201
231
|
for (const row of rows)
|
|
202
232
|
if (row.state === "queued") {
|
|
203
|
-
const key = JSON.stringify(row.target);
|
|
233
|
+
const key = JSON.stringify({ ...row.target, session: undefined });
|
|
204
234
|
if (attempted.has(key))
|
|
205
235
|
continue;
|
|
206
236
|
attempted.add(key);
|
|
@@ -208,16 +238,12 @@ export class HandOffQueue {
|
|
|
208
238
|
}
|
|
209
239
|
for (const row of rows)
|
|
210
240
|
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
241
|
if (row.originComputer) {
|
|
214
|
-
|
|
215
|
-
if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
|
|
216
|
-
continue;
|
|
217
|
-
row.notified = true;
|
|
218
|
-
await this.save(row);
|
|
242
|
+
remote.push(row);
|
|
219
243
|
continue;
|
|
220
244
|
}
|
|
245
|
+
// A notice is itself an idempotent queued hand-off, without an origin.
|
|
246
|
+
const id = this.noticeId(row);
|
|
221
247
|
if (!await this.read(id)) {
|
|
222
248
|
const pane = await this.options.validate(row.origin).catch(() => undefined);
|
|
223
249
|
if (!pane || typeof pane.terminal_id !== "string")
|
|
@@ -229,16 +255,33 @@ export class HandOffQueue {
|
|
|
229
255
|
row.notified = true;
|
|
230
256
|
await this.save(row);
|
|
231
257
|
}
|
|
258
|
+
return remote;
|
|
232
259
|
});
|
|
260
|
+
// Sent outside the lock: the sender's Hook may be holding its own lock
|
|
261
|
+
// while it waits on this one, and two Hooks each waiting on the other
|
|
262
|
+
// left both refusing every hand-off until a peer request timed out.
|
|
263
|
+
await Promise.all(remote.map(async (row) => {
|
|
264
|
+
const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, this.noticeId(row), row.originComputer).catch(() => undefined);
|
|
265
|
+
if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
|
|
266
|
+
return;
|
|
267
|
+
await this.serial(async () => {
|
|
268
|
+
const current = await this.read(row.deliveryId);
|
|
269
|
+
if (current && !current.notified) {
|
|
270
|
+
current.notified = true;
|
|
271
|
+
await this.save(current);
|
|
272
|
+
}
|
|
273
|
+
});
|
|
274
|
+
}));
|
|
233
275
|
}
|
|
276
|
+
noticeId(row) { return `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`; }
|
|
234
277
|
/** Hold enqueues and delivery while the Hook validates and closes a worker.
|
|
235
278
|
* A new hand-off cannot be accepted between the pending check and closure. */
|
|
236
279
|
whenNoPending(target, close) {
|
|
237
280
|
return this.serial(async () => {
|
|
238
|
-
if ((await this.rows()).some(row =>
|
|
281
|
+
if ((await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state)))
|
|
239
282
|
return { ok: true, closed: false };
|
|
240
283
|
return close();
|
|
241
284
|
});
|
|
242
285
|
}
|
|
243
|
-
hasPending(target) { return this.serial(async () => (await this.rows()).some(row =>
|
|
286
|
+
hasPending(target) { return this.serial(async () => (await this.rows()).some(row => samePane(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
|
|
244
287
|
}
|
package/dist/bridge/hook-main.js
CHANGED
|
@@ -1,7 +1,17 @@
|
|
|
1
|
-
import { runBridge } from "./command.js";
|
|
2
1
|
import { nonInteractiveGitEnv } from "../utils-helpers.js";
|
|
3
2
|
Object.assign(process.env, nonInteractiveGitEnv());
|
|
4
|
-
|
|
3
|
+
async function main() {
|
|
4
|
+
const args = process.argv.slice(2);
|
|
5
|
+
// sudo starts a fresh process for every password attempt. It needs only
|
|
6
|
+
// the askpass client, rather than initializing the Hook server and tools.
|
|
7
|
+
if (args[0] === "askpass") {
|
|
8
|
+
const { askpass } = await import("./sudo.js");
|
|
9
|
+
return askpass(args[1]);
|
|
10
|
+
}
|
|
11
|
+
const { runBridge } = await import("./command.js");
|
|
12
|
+
return runBridge(args, PHREN_HOOK_VERSION);
|
|
13
|
+
}
|
|
14
|
+
main().then(code => {
|
|
5
15
|
process.exitCode = code;
|
|
6
16
|
}).catch(error => {
|
|
7
17
|
console.error(error instanceof Error ? error.message : "Phren Hook failed.");
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type Json, type Provider, type Target } from "./protocol.js";
|
|
2
|
+
export type DeliveryOutcome = "delivered" | "pending";
|
|
3
|
+
/** What a phone message is known to have become. `queued`: typed into the
|
|
4
|
+
* pane and held by the agent until its turn ends. `failed` carries a reason
|
|
5
|
+
* and may still turn `delivered` if the agent takes it late. */
|
|
6
|
+
export type DeliveryState = "queued" | "delivered" | "failed";
|
|
7
|
+
export type TrackedState = DeliveryState | "unknown";
|
|
8
|
+
export interface DeliveryStatus {
|
|
9
|
+
state: TrackedState;
|
|
10
|
+
reason?: string;
|
|
11
|
+
session?: string;
|
|
12
|
+
}
|
|
13
|
+
/** A message is kept this long, by its id, so a late status or a retry still
|
|
14
|
+
* finds it: a busy Codex turn can run far past the old ten minutes. */
|
|
15
|
+
export declare const DELIVERY_RETENTION_MS: number;
|
|
16
|
+
/** An agent that ended its turn after the message was typed and then stayed
|
|
17
|
+
* idle this long without taking it has dropped it. */
|
|
18
|
+
export declare const DELIVERY_GIVE_UP_MS = 30000;
|
|
19
|
+
/** What the agent hands its UserPromptSubmit hook is the terminal's pasted
|
|
20
|
+
* form of what Phren typed; compare the words, not the wrapping. Claude Code
|
|
21
|
+
* also takes each attached picture's path line out of the text and puts an
|
|
22
|
+
* "[Image #N]" label at the front, so neither side keeps picture paths or
|
|
23
|
+
* labels. */
|
|
24
|
+
export declare function promptKey(text: string): string;
|
|
25
|
+
export declare const promptHash: (text: string) => string;
|
|
26
|
+
/** One message per record, bound to the pane it was typed into (server, pane,
|
|
27
|
+
* agent kind), not to the conversation: a Codex thread or a Claude /clear can
|
|
28
|
+
* replace the conversation while the agent still holds the typed text, and
|
|
29
|
+
* the conversation that submits it is the one it reached. Records hold a hash
|
|
30
|
+
* of the words, never the text, and those with a phone id are written to
|
|
31
|
+
* `file` so a Hook restart keeps their state. */
|
|
32
|
+
export declare class PromptDeliveries {
|
|
33
|
+
private file?;
|
|
34
|
+
private now;
|
|
35
|
+
private landed;
|
|
36
|
+
private records;
|
|
37
|
+
private waiters;
|
|
38
|
+
private writing;
|
|
39
|
+
constructor(file?: string | undefined, now?: () => number, landed?: (record: {
|
|
40
|
+
source: Provider;
|
|
41
|
+
session: string;
|
|
42
|
+
hash: string;
|
|
43
|
+
at: number;
|
|
44
|
+
}) => Promise<boolean>);
|
|
45
|
+
private samePane;
|
|
46
|
+
private byId;
|
|
47
|
+
private prune;
|
|
48
|
+
private save;
|
|
49
|
+
/** Settled writes, for tests and an orderly shutdown. */
|
|
50
|
+
flush(): Promise<void>;
|
|
51
|
+
/** Register a message about to be typed into `target`'s pane. Settles
|
|
52
|
+
* "delivered" once a conversation in that pane submits the words, or
|
|
53
|
+
* "pending" after `waitMs`; the record outlives the wait. A retry of a
|
|
54
|
+
* failed id replaces its record. Aborting (the terminal refused before
|
|
55
|
+
* writing) drops it. */
|
|
56
|
+
expect(target: Target, text: string, waitMs: number, signal?: AbortSignal, id?: string, terminal?: string): Promise<DeliveryOutcome>;
|
|
57
|
+
private release;
|
|
58
|
+
private open;
|
|
59
|
+
/** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
|
|
60
|
+
pending(target: Target, text: string): boolean;
|
|
61
|
+
/** Wait again for a message `expect` reported pending, after a second Enter. */
|
|
62
|
+
awaitLate(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
|
|
63
|
+
private find;
|
|
64
|
+
/** The Hook answered `id` as typed and held by the agent. */
|
|
65
|
+
queue(id: string, target: Target): void;
|
|
66
|
+
/** Delivered without a hook: an app-server turn or a served OpenCode prompt. */
|
|
67
|
+
delivered(id: string | undefined, target: Target, text: string): void;
|
|
68
|
+
/** The message did not reach the agent, and why. It stays matchable, so a
|
|
69
|
+
* late submission still turns it delivered. */
|
|
70
|
+
fail(id: string | undefined, target: Target, reason: string): void;
|
|
71
|
+
/** The pane's Codex server moved to another thread (/new, /resume):
|
|
72
|
+
* input still pending on the old one stays there, out of the pane's view.
|
|
73
|
+
* Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
|
|
74
|
+
threadChanged(previous: Target): void;
|
|
75
|
+
/** False when `id` names another message: other words or another pane. */
|
|
76
|
+
sameMessage(id: string, target: Pick<Target, "server" | "pane" | "source">, text: string): boolean;
|
|
77
|
+
/** What became of phone message `id` in `target`'s pane. `unknown` while the
|
|
78
|
+
* Hook has not answered it, for another pane, or past retention. */
|
|
79
|
+
status(id: string, target: Pick<Target, "server" | "pane" | "source">): DeliveryStatus;
|
|
80
|
+
/** Every known phone message in `target`'s pane, for its conversation's stream. */
|
|
81
|
+
forPane(target: Pick<Target, "server" | "pane" | "source">): ({
|
|
82
|
+
deliveryId: string;
|
|
83
|
+
} & DeliveryStatus)[];
|
|
84
|
+
/** Conversation `target` just submitted `prompt`. Its own record wins, then
|
|
85
|
+
* the oldest open one in the same pane: the agent kept the text across a
|
|
86
|
+
* conversation change, and the conversation now in the pane is where it
|
|
87
|
+
* went. A prompt nothing matches was typed locally. Never refused. */
|
|
88
|
+
submitted(target: Target, prompt: string): void;
|
|
89
|
+
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
90
|
+
stopped(target: Target): void;
|
|
91
|
+
/** Called on the Hook's activity tick with a server's panes. A message
|
|
92
|
+
* still held fails loudly when its pane closed, its agent restarted, or the
|
|
93
|
+
* agent ended a turn and stayed idle without taking it (unless its
|
|
94
|
+
* transcript shows it after all). */
|
|
95
|
+
observe(server: string, panes: Json[]): Promise<void>;
|
|
96
|
+
}
|
|
97
|
+
/** A transcript row's user-typed text: Claude's user rows, Codex's
|
|
98
|
+
* user_message events and user response items. */
|
|
99
|
+
export declare function userTexts(row: Json): string[];
|
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { open } from "node:fs/promises";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { atomicInPrivateDir, object, objects, provider } from "./protocol.js";
|
|
6
|
+
import { transcriptPath, unwrapPastedContent } from "./transcripts.js";
|
|
7
|
+
/** A message is kept this long, by its id, so a late status or a retry still
|
|
8
|
+
* finds it: a busy Codex turn can run far past the old ten minutes. */
|
|
9
|
+
export const DELIVERY_RETENTION_MS = 24 * 3_600_000;
|
|
10
|
+
/** An agent that ended its turn after the message was typed and then stayed
|
|
11
|
+
* idle this long without taking it has dropped it. */
|
|
12
|
+
export const DELIVERY_GIVE_UP_MS = 30_000;
|
|
13
|
+
const MAX_RECORDS = 512;
|
|
14
|
+
/** What the agent hands its UserPromptSubmit hook is the terminal's pasted
|
|
15
|
+
* form of what Phren typed; compare the words, not the wrapping. Claude Code
|
|
16
|
+
* also takes each attached picture's path line out of the text and puts an
|
|
17
|
+
* "[Image #N]" label at the front, so neither side keeps picture paths or
|
|
18
|
+
* labels. */
|
|
19
|
+
export function promptKey(text) {
|
|
20
|
+
return unwrapPastedContent(text).split("\n").filter(line => !PICTURE_PATH_LINE.test(line)).join("\n")
|
|
21
|
+
.replace(/\[Image #\d+\]/g, " ").replace(/\s+/g, " ").trim();
|
|
22
|
+
}
|
|
23
|
+
const PICTURE_PATH_LINE = /^\s*\/.*\.(?:png|jpe?g|gif|webp)\s*$/i;
|
|
24
|
+
export const promptHash = (text) => createHash("sha256").update(promptKey(text)).digest("hex");
|
|
25
|
+
const recordSchema = z.object({
|
|
26
|
+
id: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional(), hash: z.string().regex(/^[0-9a-f]{64}$/),
|
|
27
|
+
server: z.string().min(1).max(200), pane: z.string().min(1).max(200), source: provider, session: z.string().min(1).max(200),
|
|
28
|
+
terminal: z.string().max(200).optional(), state: z.enum(["typed", "queued", "delivered", "failed"]),
|
|
29
|
+
reason: z.string().max(500).optional(), at: z.number(), settledAt: z.number().optional(), stoppedAt: z.number().optional(),
|
|
30
|
+
}).strict();
|
|
31
|
+
/** One message per record, bound to the pane it was typed into (server, pane,
|
|
32
|
+
* agent kind), not to the conversation: a Codex thread or a Claude /clear can
|
|
33
|
+
* replace the conversation while the agent still holds the typed text, and
|
|
34
|
+
* the conversation that submits it is the one it reached. Records hold a hash
|
|
35
|
+
* of the words, never the text, and those with a phone id are written to
|
|
36
|
+
* `file` so a Hook restart keeps their state. */
|
|
37
|
+
export class PromptDeliveries {
|
|
38
|
+
file;
|
|
39
|
+
now;
|
|
40
|
+
landed;
|
|
41
|
+
records = [];
|
|
42
|
+
waiters = new Map();
|
|
43
|
+
writing = Promise.resolve();
|
|
44
|
+
constructor(file, now = Date.now, landed = transcriptHas) {
|
|
45
|
+
this.file = file;
|
|
46
|
+
this.now = now;
|
|
47
|
+
this.landed = landed;
|
|
48
|
+
if (!file)
|
|
49
|
+
return;
|
|
50
|
+
try {
|
|
51
|
+
for (const row of objects(object(JSON.parse(readFileSync(file, "utf8"))).records)) {
|
|
52
|
+
const parsed = recordSchema.safeParse(row);
|
|
53
|
+
// A message the Hook was typing when it stopped is in the pane or
|
|
54
|
+
// nowhere: wait for the agent, and give up as for any other.
|
|
55
|
+
if (parsed.success)
|
|
56
|
+
this.records.push({ ...parsed.data, state: parsed.data.state === "typed" ? "queued" : parsed.data.state });
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch { /* No file yet, or an unreadable one: start empty. */ }
|
|
60
|
+
this.prune();
|
|
61
|
+
}
|
|
62
|
+
samePane(record, target) {
|
|
63
|
+
return record.server === target.server && record.pane === target.pane && record.source === target.source;
|
|
64
|
+
}
|
|
65
|
+
byId(id) { return this.records.find(record => record.id === id); }
|
|
66
|
+
prune() {
|
|
67
|
+
const cutoff = this.now() - DELIVERY_RETENTION_MS;
|
|
68
|
+
this.records = this.records.filter(record => record.at >= cutoff || this.waiters.has(record));
|
|
69
|
+
while (this.records.length > MAX_RECORDS)
|
|
70
|
+
this.records.shift();
|
|
71
|
+
}
|
|
72
|
+
save() {
|
|
73
|
+
if (!this.file)
|
|
74
|
+
return;
|
|
75
|
+
const rows = this.records.filter(record => record.id).map(({ idleSince: _, ...row }) => row);
|
|
76
|
+
const file = this.file;
|
|
77
|
+
this.writing = this.writing.then(() => atomicInPrivateDir(file, { records: rows })).catch(() => undefined);
|
|
78
|
+
}
|
|
79
|
+
/** Settled writes, for tests and an orderly shutdown. */
|
|
80
|
+
flush() { return this.writing; }
|
|
81
|
+
/** Register a message about to be typed into `target`'s pane. Settles
|
|
82
|
+
* "delivered" once a conversation in that pane submits the words, or
|
|
83
|
+
* "pending" after `waitMs`; the record outlives the wait. A retry of a
|
|
84
|
+
* failed id replaces its record. Aborting (the terminal refused before
|
|
85
|
+
* writing) drops it. */
|
|
86
|
+
expect(target, text, waitMs, signal, id, terminal) {
|
|
87
|
+
if (!promptKey(text) || signal?.aborted)
|
|
88
|
+
return Promise.resolve("pending");
|
|
89
|
+
this.prune();
|
|
90
|
+
if (id)
|
|
91
|
+
this.records = this.records.filter(record => record.id !== id);
|
|
92
|
+
const record = { ...(id ? { id } : {}), hash: promptHash(text), server: target.server, pane: target.pane, source: target.source,
|
|
93
|
+
session: target.session, ...(typeof terminal === "string" ? { terminal } : {}), state: "typed", at: this.now() };
|
|
94
|
+
this.records.push(record);
|
|
95
|
+
this.save();
|
|
96
|
+
return new Promise(resolve => {
|
|
97
|
+
const timer = setTimeout(() => this.release(record, "pending"), waitMs);
|
|
98
|
+
timer.unref?.();
|
|
99
|
+
this.waiters.set(record, { resolve, timer });
|
|
100
|
+
signal?.addEventListener("abort", () => {
|
|
101
|
+
this.release(record, "pending");
|
|
102
|
+
if (record.state === "typed") {
|
|
103
|
+
this.records = this.records.filter(entry => entry !== record);
|
|
104
|
+
this.save();
|
|
105
|
+
}
|
|
106
|
+
}, { once: true });
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
release(record, outcome) {
|
|
110
|
+
const waiter = this.waiters.get(record);
|
|
111
|
+
if (!waiter)
|
|
112
|
+
return;
|
|
113
|
+
clearTimeout(waiter.timer);
|
|
114
|
+
waiter.resolve?.(outcome);
|
|
115
|
+
waiter.resolve = undefined;
|
|
116
|
+
if (outcome !== "pending")
|
|
117
|
+
waiter.late?.(outcome);
|
|
118
|
+
if (outcome !== "pending" || !waiter.late)
|
|
119
|
+
this.waiters.delete(record);
|
|
120
|
+
}
|
|
121
|
+
open(target, text) {
|
|
122
|
+
const hash = promptHash(text);
|
|
123
|
+
return this.records.find(record => record.hash === hash && this.samePane(record, target) && (record.state === "typed" || record.state === "queued"));
|
|
124
|
+
}
|
|
125
|
+
/** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
|
|
126
|
+
pending(target, text) { return !!this.open(target, text); }
|
|
127
|
+
/** Wait again for a message `expect` reported pending, after a second Enter. */
|
|
128
|
+
awaitLate(target, text, waitMs = 2_500) {
|
|
129
|
+
const record = this.open(target, text);
|
|
130
|
+
if (!record)
|
|
131
|
+
return Promise.resolve("pending");
|
|
132
|
+
return new Promise(resolve => {
|
|
133
|
+
const waiter = this.waiters.get(record) ?? {};
|
|
134
|
+
const timer = setTimeout(() => { waiter.late = undefined; if (!waiter.resolve)
|
|
135
|
+
this.waiters.delete(record); resolve("pending"); }, waitMs);
|
|
136
|
+
timer.unref?.();
|
|
137
|
+
waiter.late = outcome => { clearTimeout(timer); waiter.late = undefined; resolve(outcome); };
|
|
138
|
+
this.waiters.set(record, waiter);
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
find(id, target) {
|
|
142
|
+
const record = this.byId(id);
|
|
143
|
+
return record && this.samePane(record, target) && this.now() - record.at <= DELIVERY_RETENTION_MS ? record : undefined;
|
|
144
|
+
}
|
|
145
|
+
/** The Hook answered `id` as typed and held by the agent. */
|
|
146
|
+
queue(id, target) {
|
|
147
|
+
const record = this.find(id, target);
|
|
148
|
+
if (record?.state === "typed") {
|
|
149
|
+
record.state = "queued";
|
|
150
|
+
this.save();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** Delivered without a hook: an app-server turn or a served OpenCode prompt. */
|
|
154
|
+
delivered(id, target, text) {
|
|
155
|
+
if (!id)
|
|
156
|
+
return;
|
|
157
|
+
this.records = this.records.filter(record => record.id !== id);
|
|
158
|
+
this.records.push({ id, hash: promptHash(text), server: target.server, pane: target.pane, source: target.source, session: target.session,
|
|
159
|
+
state: "delivered", at: this.now(), settledAt: this.now() });
|
|
160
|
+
this.save();
|
|
161
|
+
}
|
|
162
|
+
/** The message did not reach the agent, and why. It stays matchable, so a
|
|
163
|
+
* late submission still turns it delivered. */
|
|
164
|
+
fail(id, target, reason) {
|
|
165
|
+
const record = id ? this.find(id, target) : undefined;
|
|
166
|
+
if (!record || record.state === "delivered")
|
|
167
|
+
return;
|
|
168
|
+
record.state = "failed";
|
|
169
|
+
record.reason = reason.slice(0, 500);
|
|
170
|
+
record.settledAt = this.now();
|
|
171
|
+
this.save();
|
|
172
|
+
}
|
|
173
|
+
/** The pane's Codex server moved to another thread (/new, /resume):
|
|
174
|
+
* input still pending on the old one stays there, out of the pane's view.
|
|
175
|
+
* Fails loudly; a late UserPromptSubmit from the old thread still settles it. */
|
|
176
|
+
threadChanged(previous) {
|
|
177
|
+
let changed = false;
|
|
178
|
+
for (const record of this.records)
|
|
179
|
+
if ((record.state === "typed" || record.state === "queued") && this.samePane(record, previous) && record.session === previous.session) {
|
|
180
|
+
record.state = "failed";
|
|
181
|
+
record.settledAt = this.now();
|
|
182
|
+
changed = true;
|
|
183
|
+
record.reason = "The pane moved to another Codex conversation before the agent took the message.";
|
|
184
|
+
}
|
|
185
|
+
if (changed)
|
|
186
|
+
this.save();
|
|
187
|
+
}
|
|
188
|
+
/** False when `id` names another message: other words or another pane. */
|
|
189
|
+
sameMessage(id, target, text) {
|
|
190
|
+
const record = this.byId(id);
|
|
191
|
+
return !record || (this.samePane(record, target) && record.hash === promptHash(text));
|
|
192
|
+
}
|
|
193
|
+
/** What became of phone message `id` in `target`'s pane. `unknown` while the
|
|
194
|
+
* Hook has not answered it, for another pane, or past retention. */
|
|
195
|
+
status(id, target) {
|
|
196
|
+
const record = this.find(id, target);
|
|
197
|
+
if (!record || record.state === "typed")
|
|
198
|
+
return { state: "unknown" };
|
|
199
|
+
return { state: record.state, ...(record.reason && record.state === "failed" ? { reason: record.reason } : {}), session: record.session };
|
|
200
|
+
}
|
|
201
|
+
/** Every known phone message in `target`'s pane, for its conversation's stream. */
|
|
202
|
+
forPane(target) {
|
|
203
|
+
return this.records.filter(record => record.id && this.samePane(record, target)).map(record => ({ deliveryId: record.id, ...this.status(record.id, target) }))
|
|
204
|
+
.filter(item => item.state !== "unknown");
|
|
205
|
+
}
|
|
206
|
+
/** Conversation `target` just submitted `prompt`. Its own record wins, then
|
|
207
|
+
* the oldest open one in the same pane: the agent kept the text across a
|
|
208
|
+
* conversation change, and the conversation now in the pane is where it
|
|
209
|
+
* went. A prompt nothing matches was typed locally. Never refused. */
|
|
210
|
+
submitted(target, prompt) {
|
|
211
|
+
const hash = promptHash(prompt);
|
|
212
|
+
const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered");
|
|
213
|
+
const record = open.find(entry => entry.session === target.session) ?? open[0];
|
|
214
|
+
if (!record)
|
|
215
|
+
return;
|
|
216
|
+
record.state = "delivered";
|
|
217
|
+
record.session = target.session;
|
|
218
|
+
record.settledAt = this.now();
|
|
219
|
+
delete record.reason;
|
|
220
|
+
this.save();
|
|
221
|
+
this.release(record, "delivered");
|
|
222
|
+
}
|
|
223
|
+
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
224
|
+
stopped(target) {
|
|
225
|
+
const at = this.now();
|
|
226
|
+
for (const record of this.records)
|
|
227
|
+
if (this.samePane(record, target) && (record.state === "typed" || record.state === "queued") && record.at < at)
|
|
228
|
+
record.stoppedAt = at;
|
|
229
|
+
}
|
|
230
|
+
/** Called on the Hook's activity tick with a server's panes. A message
|
|
231
|
+
* still held fails loudly when its pane closed, its agent restarted, or the
|
|
232
|
+
* agent ended a turn and stayed idle without taking it (unless its
|
|
233
|
+
* transcript shows it after all). */
|
|
234
|
+
async observe(server, panes) {
|
|
235
|
+
const now = this.now();
|
|
236
|
+
let changed = false;
|
|
237
|
+
for (const record of this.records) {
|
|
238
|
+
if (record.server !== server || (record.state !== "typed" && record.state !== "queued"))
|
|
239
|
+
continue;
|
|
240
|
+
const pane = panes.find(entry => entry.pane_id === record.pane);
|
|
241
|
+
if (!pane || (record.terminal && pane.terminal_id !== record.terminal) || (pane.agent && pane.agent !== record.source)) {
|
|
242
|
+
if (await this.landed(record).catch(() => false)) {
|
|
243
|
+
record.state = "delivered";
|
|
244
|
+
record.settledAt = now;
|
|
245
|
+
changed = true;
|
|
246
|
+
this.release(record, "delivered");
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
record.state = "failed";
|
|
250
|
+
record.settledAt = now;
|
|
251
|
+
changed = true;
|
|
252
|
+
record.reason = pane ? "The agent in this pane restarted before it took the message." : "The agent's pane closed before it took the message.";
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
if (!["idle", "done"].includes(String(pane.agent_status))) {
|
|
256
|
+
record.idleSince = undefined;
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
record.idleSince ??= now;
|
|
260
|
+
if (record.stoppedAt === undefined || now - Math.max(record.idleSince, record.stoppedAt) < DELIVERY_GIVE_UP_MS)
|
|
261
|
+
continue;
|
|
262
|
+
if (await this.landed(record).catch(() => false)) {
|
|
263
|
+
record.state = "delivered";
|
|
264
|
+
record.settledAt = now;
|
|
265
|
+
changed = true;
|
|
266
|
+
this.release(record, "delivered");
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
record.state = "failed";
|
|
270
|
+
record.settledAt = now;
|
|
271
|
+
changed = true;
|
|
272
|
+
record.reason = "The agent finished its turn without taking the message.";
|
|
273
|
+
}
|
|
274
|
+
if (changed)
|
|
275
|
+
this.save();
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
/** Whether a user row with these words reached the conversation's transcript
|
|
279
|
+
* after the message was typed: the agent took it without its hook saying so
|
|
280
|
+
* (a mid-turn steer). Reads at most the last 512 KiB. */
|
|
281
|
+
async function transcriptHas(record) {
|
|
282
|
+
const file = await open(await transcriptPath(record.source, record.session), "r");
|
|
283
|
+
try {
|
|
284
|
+
const size = (await file.stat()).size, start = Math.max(0, size - 524_288), buffer = Buffer.alloc(size - start);
|
|
285
|
+
await file.read(buffer, 0, buffer.length, start);
|
|
286
|
+
for (const line of buffer.toString("utf8").split("\n").reverse()) {
|
|
287
|
+
let row;
|
|
288
|
+
try {
|
|
289
|
+
row = object(JSON.parse(line));
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
const stamp = Date.parse(String(row.timestamp ?? ""));
|
|
295
|
+
if (Number.isFinite(stamp) && stamp < record.at - 5_000)
|
|
296
|
+
break;
|
|
297
|
+
for (const text of userTexts(row))
|
|
298
|
+
if (promptHash(text) === record.hash)
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
return false;
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
await file.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
/** A transcript row's user-typed text: Claude's user rows, Codex's
|
|
308
|
+
* user_message events and user response items. */
|
|
309
|
+
export function userTexts(row) {
|
|
310
|
+
const texts = [];
|
|
311
|
+
const blocks = (content) => {
|
|
312
|
+
if (typeof content === "string")
|
|
313
|
+
texts.push(content);
|
|
314
|
+
else
|
|
315
|
+
for (const block of objects(content))
|
|
316
|
+
if (typeof block.text === "string")
|
|
317
|
+
texts.push(block.text);
|
|
318
|
+
};
|
|
319
|
+
if (row.type === "user" && !row.isMeta)
|
|
320
|
+
blocks(object(row.message).content);
|
|
321
|
+
const payload = object(row.payload);
|
|
322
|
+
if (payload.type === "user_message" && typeof payload.message === "string")
|
|
323
|
+
texts.push(payload.message);
|
|
324
|
+
if (payload.type === "message" && payload.role === "user")
|
|
325
|
+
blocks(payload.content);
|
|
326
|
+
return texts;
|
|
327
|
+
}
|
|
@@ -17,6 +17,8 @@ export declare class PromptOnce {
|
|
|
17
17
|
private attempts;
|
|
18
18
|
constructor(now?: () => number);
|
|
19
19
|
run(id: string | undefined, scope: string, send: (typing: () => void) => Promise<Json>): Promise<Json>;
|
|
20
|
+
/** Lets a message the Hook found failed be typed again under its id. */
|
|
21
|
+
forget(id: string): void;
|
|
20
22
|
private prune;
|
|
21
23
|
}
|
|
22
24
|
/** What a delivery id is bound to: the pane, its agent and the exact text.
|
|
@@ -50,6 +50,8 @@ export class PromptOnce {
|
|
|
50
50
|
throw error;
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
|
+
/** Lets a message the Hook found failed be typed again under its id. */
|
|
54
|
+
forget(id) { this.attempts.delete(id); }
|
|
53
55
|
prune() {
|
|
54
56
|
const cutoff = this.now() - REMEMBER_MS;
|
|
55
57
|
for (const [id, attempt] of this.attempts)
|
|
@@ -63,6 +63,7 @@ export interface ComputerResources {
|
|
|
63
63
|
charging: boolean;
|
|
64
64
|
onAC: boolean;
|
|
65
65
|
};
|
|
66
|
+
hardware?: ComputerHardware;
|
|
66
67
|
heavy: HeavyProcess[];
|
|
67
68
|
/** 0 idle to 1 saturated, per resource and overall (the highest), so every client fills its gauge the same way. */
|
|
68
69
|
pressure: {
|
|
@@ -74,6 +75,25 @@ export interface ComputerResources {
|
|
|
74
75
|
level: "ok" | "busy" | "stressed";
|
|
75
76
|
warnings: Array<"load-high" | "memory-low" | "disk-low" | "battery-low">;
|
|
76
77
|
}
|
|
78
|
+
/** What the computer is, read once per Hook run: "MacBook Pro", "Apple M1 Max",
|
|
79
|
+
* 32 GB; on Linux the DMI vendor and product ("Dell XPS 13 9310") and the CPU's
|
|
80
|
+
* model name. Never a serial number or any other identifier. */
|
|
81
|
+
export interface ComputerHardware {
|
|
82
|
+
model?: string;
|
|
83
|
+
chip?: string;
|
|
84
|
+
memoryBytes: number;
|
|
85
|
+
cores: number;
|
|
86
|
+
}
|
|
87
|
+
/** `system_profiler SPHardwareDataType -json` → model and chip. Intel Macs name
|
|
88
|
+
* the processor in `cpu_type` instead of `chip_type`. */
|
|
89
|
+
export declare function parseMacHardware(json: string): Pick<ComputerHardware, "model" | "chip">;
|
|
90
|
+
/** DMI vendor and product → "Dell XPS 13 9310", "Lenovo ThinkPad X1 Carbon";
|
|
91
|
+
* placeholder strings firmware leaves in are dropped. */
|
|
92
|
+
export declare function linuxModel(vendor: string | undefined, product: string | undefined, version?: string): string | undefined;
|
|
93
|
+
/** /proc/cpuinfo's first `model name`, without the (R)/(TM) marks, "CPU" and clock. */
|
|
94
|
+
export declare function linuxChip(cpuinfo: string): string | undefined;
|
|
95
|
+
/** Read once; the answer can't change while the Hook runs. */
|
|
96
|
+
export declare function computerHardware(platform?: NodeJS.Platform): Promise<ComputerHardware>;
|
|
77
97
|
/** A `ps` row; `pgid` is the process group the job registry attributes work by. */
|
|
78
98
|
export interface ProcessRow extends ProcessLike {
|
|
79
99
|
cpu: number;
|
|
@@ -136,6 +156,7 @@ export interface ResourceDeps {
|
|
|
136
156
|
panes: Set<string>;
|
|
137
157
|
servers: Set<string>;
|
|
138
158
|
} | undefined>;
|
|
159
|
+
hardware?: () => Promise<ComputerHardware | undefined>;
|
|
139
160
|
jobs?: JobSource;
|
|
140
161
|
}
|
|
141
162
|
export declare function collectResources(deps: ResourceDeps): Promise<ComputerResources>;
|