@phren/cli 0.3.30 → 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 +10 -0
- package/dist/bridge/hand-off-queue.js +33 -10
- 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/server-pane-routes.js +72 -34
- package/dist/bridge/server-routes.d.ts +1 -0
- package/dist/bridge/server-routes.js +1 -1
- package/dist/bridge/server-stream.js +4 -2
- package/dist/bridge/server.js +12 -3
- package/dist/bridge/sudo.d.ts +1 -1
- package/dist/bridge/sudo.js +51 -17
- package/dist/bridge-hook.mjs +17318 -15965
- 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/package.json +8 -8
|
@@ -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)
|
|
@@ -126,7 +126,7 @@ async function resubmitIfIdle(agentHooks, target, text) {
|
|
|
126
126
|
} };
|
|
127
127
|
if (await status() === "working")
|
|
128
128
|
return "pending";
|
|
129
|
-
const late = agentHooks.
|
|
129
|
+
const late = agentHooks.deliveries.awaitLate(target, text);
|
|
130
130
|
await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
|
|
131
131
|
const outcome = await late;
|
|
132
132
|
if (outcome !== "pending")
|
|
@@ -143,7 +143,7 @@ export function followQueuedDelivery(agentHooks, target, terminal, text, interva
|
|
|
143
143
|
const started = Date.now();
|
|
144
144
|
let finishedLooks = 0;
|
|
145
145
|
const look = async () => {
|
|
146
|
-
if (!agentHooks.
|
|
146
|
+
if (!agentHooks.deliveries.pending(target, text) || Date.now() - started > 600_000)
|
|
147
147
|
return;
|
|
148
148
|
let pane;
|
|
149
149
|
try {
|
|
@@ -247,13 +247,35 @@ async function servedPrompt(target, session, text, typing) {
|
|
|
247
247
|
return undefined;
|
|
248
248
|
return sent.delivered ? { ok: true, delivered: true } : { ok: true, deliveryUncertain: true };
|
|
249
249
|
}
|
|
250
|
+
/** A known message's reply by its id: `state` plus the legacy flags. */
|
|
251
|
+
function deliveryReply(agentHooks, id, target, text) {
|
|
252
|
+
const parsed = targetSchema.safeParse(target);
|
|
253
|
+
if (!parsed.success)
|
|
254
|
+
return undefined;
|
|
255
|
+
if (!agentHooks.deliveries.sameMessage(id, parsed.data, text))
|
|
256
|
+
throw new BridgeError(409, "This message id was already used for a different message.");
|
|
257
|
+
const status = agentHooks.deliveries.status(id, parsed.data);
|
|
258
|
+
if (status.state === "unknown")
|
|
259
|
+
return undefined;
|
|
260
|
+
return { ok: status.state !== "failed", state: status.state, ...(status.state === "delivered" ? { delivered: true } : {}),
|
|
261
|
+
...(status.state === "queued" ? { queued: true } : {}), ...(status.reason ? { reason: status.reason } : {}) };
|
|
262
|
+
}
|
|
250
263
|
export async function paneRoute(ctx, url, data, response) {
|
|
251
264
|
if (url.pathname !== "/v1/prompt")
|
|
252
265
|
return paneRouteOnce(ctx, url, data, response, () => { });
|
|
253
266
|
// A retried send carries its first attempt's id; the Hook answers it with
|
|
254
267
|
// that attempt's reply instead of typing the message a second time.
|
|
255
268
|
const id = deliveryIdSchema.parse(data.deliveryId);
|
|
256
|
-
|
|
269
|
+
const scope = promptScope(object(data.target), String(data.text ?? ""));
|
|
270
|
+
// The Hook keeps each message's state by its id (prompt-deliveries.ts), so
|
|
271
|
+
// a retry, even after a Hook restart, answers with where the message is
|
|
272
|
+
// now. Only a failed one is typed again, under the same id.
|
|
273
|
+
const known = id ? deliveryReply(ctx.agentHooks, id, object(data.target), String(data.text ?? "")) : undefined;
|
|
274
|
+
if (known && known.state !== "failed")
|
|
275
|
+
return { ...known, replayed: true };
|
|
276
|
+
if (known)
|
|
277
|
+
promptOnce.forget(id);
|
|
278
|
+
return promptOnce.run(id, scope, async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
|
|
257
279
|
}
|
|
258
280
|
export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
259
281
|
const { agentHooks, modelSwitcher, settingsSwitcher, permissionModeSwitcher, codexQuestions, sideQuestions } = ctx;
|
|
@@ -358,6 +380,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
358
380
|
}
|
|
359
381
|
const text = typeof data.text === "string" && data.text && data.text.length <= 32768 && !/[\x00-\x08\x0b-\x1f\x7f]/.test(data.text) ? data.text : undefined;
|
|
360
382
|
const served = text === undefined ? undefined : await servedPrompt(target, target.session, text, typing);
|
|
383
|
+
if (served?.delivered && text)
|
|
384
|
+
agentHooks.deliveries.delivered(deliveryIdSchema.parse(data.deliveryId), target, text);
|
|
361
385
|
if (served)
|
|
362
386
|
return served;
|
|
363
387
|
}
|
|
@@ -381,30 +405,48 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
381
405
|
}
|
|
382
406
|
if (target.source === "codex" && /^\s*\/model\s+\S/i.test(text))
|
|
383
407
|
throw new BridgeError(422, "Use the model picker to switch Codex models.");
|
|
384
|
-
// A Codex pane on the Hook's own app-server takes the prompt
|
|
385
|
-
//
|
|
408
|
+
// A Codex pane on the Hook's own app-server takes the prompt on its
|
|
409
|
+
// thread, as the TUI takes Enter: steered into a running turn, else a new
|
|
410
|
+
// turn; nothing is typed. The turn id only says Codex has it: the model
|
|
411
|
+
// reads it at its next step, possibly after a long tool call, and Codex's
|
|
412
|
+
// UserPromptSubmit says when. Until then it is queued, like typed text. A slash
|
|
386
413
|
// command is the TUI's own and is still typed. An unreachable server
|
|
387
414
|
// sent nothing, so the pane is typed into instead; a request that may
|
|
388
415
|
// have reached it is reported uncertain and never retried.
|
|
389
416
|
const owned = text.trim().startsWith("/") ? undefined : codexServers.forTarget(target);
|
|
390
417
|
if (owned) {
|
|
391
418
|
await typing();
|
|
419
|
+
const id = deliveryIdSchema.parse(data.deliveryId), refused = new AbortController();
|
|
420
|
+
// An idle thread starts the turn and confirms in about two seconds; a
|
|
421
|
+
// running one takes the text only after its current step.
|
|
422
|
+
const taken = agentHooks.deliveries.expect(target, text, owned.activeTurn ? 300 : 4_000, refused.signal, id, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
|
|
392
423
|
try {
|
|
393
|
-
const { turnId } = await codexServers.
|
|
394
|
-
|
|
424
|
+
const { turnId } = await codexServers.send(owned, text);
|
|
425
|
+
if (await taken === "delivered")
|
|
426
|
+
return { ok: true, delivered: true, state: "delivered", turnId };
|
|
427
|
+
if (id)
|
|
428
|
+
agentHooks.deliveries.queue(id, target);
|
|
429
|
+
return { ok: true, queued: true, ...(id ? { state: "queued" } : {}), turnId };
|
|
395
430
|
}
|
|
396
431
|
catch (error) {
|
|
397
|
-
if (error instanceof AppServerRpcError)
|
|
432
|
+
if (error instanceof AppServerRpcError) {
|
|
433
|
+
refused.abort();
|
|
398
434
|
throw new BridgeError(409, `Codex refused the message: ${error.message}`);
|
|
399
|
-
|
|
400
|
-
|
|
435
|
+
}
|
|
436
|
+
if (error instanceof CodexServerUnavailable)
|
|
437
|
+
refused.abort();
|
|
438
|
+
else {
|
|
439
|
+
if (id)
|
|
440
|
+
agentHooks.deliveries.queue(id, target);
|
|
441
|
+
return { ok: true, deliveryUncertain: true, ...(id ? { state: "queued" } : {}) };
|
|
442
|
+
}
|
|
401
443
|
}
|
|
402
444
|
}
|
|
403
445
|
const deliveryId = deliveryIdSchema.parse(data.deliveryId);
|
|
404
446
|
let busy = String(pane.agent_status) === "working";
|
|
405
447
|
let outcome = await promptWithStartupRetry(async () => {
|
|
406
448
|
const refused = new AbortController();
|
|
407
|
-
const expected = agentHooks.
|
|
449
|
+
const expected = agentHooks.deliveries.expect(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal, deliveryId, typeof pane.terminal_id === "string" ? pane.terminal_id : undefined);
|
|
408
450
|
await typing();
|
|
409
451
|
try {
|
|
410
452
|
await terminalProvider().prompt(target.server, target.pane, text);
|
|
@@ -435,45 +477,40 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
435
477
|
else
|
|
436
478
|
followQueuedDelivery(agentHooks, target, pane.terminal_id, text);
|
|
437
479
|
}
|
|
438
|
-
const refusedHere = () => new BridgeError(409, "The conversation in this pane changed; the message was not delivered. Reopen the chat and send it again.");
|
|
439
|
-
if (outcome === "blocked")
|
|
440
|
-
throw refusedHere();
|
|
441
480
|
// A bare slash command opens the agent's own menu; the phone may
|
|
442
481
|
// walk it with keys for the next half minute. The command rides
|
|
443
482
|
// along so a Codex /permissions walk can find its confirmation.
|
|
444
483
|
if (/^\/[a-z][a-z0-9_-]*$/i.test(text.trim()))
|
|
445
484
|
agentHooks.menuOpened(target, text.trim());
|
|
446
485
|
if (outcome === "delivered")
|
|
447
|
-
result = { ok: true, delivered: true };
|
|
486
|
+
result = { ok: true, delivered: true, state: "delivered" };
|
|
448
487
|
else if (outcome === "unsubmitted") {
|
|
449
|
-
|
|
488
|
+
const reason = "The agent did not take the message; it may still be in its input line.";
|
|
489
|
+
if (deliveryId)
|
|
490
|
+
agentHooks.deliveries.fail(deliveryId, target, reason);
|
|
491
|
+
result = { ok: true, deliveryUncertain: true, unsubmitted: true, ...(deliveryId ? { state: "failed", reason } : {}) };
|
|
450
492
|
}
|
|
451
493
|
else {
|
|
452
|
-
// The agent has not submitted it yet
|
|
453
|
-
//
|
|
454
|
-
//
|
|
455
|
-
//
|
|
456
|
-
//
|
|
494
|
+
// The agent has not submitted it yet: a busy agent holds typed input
|
|
495
|
+
// until its turn ends. The record is bound to the pane, so whichever
|
|
496
|
+
// conversation is there then takes it, and the Hook fails it loudly if
|
|
497
|
+
// the agent closes, restarts or ends its turn without it. A failed
|
|
498
|
+
// identity probe still says deliveryUncertain to phones without
|
|
499
|
+
// `paneDeliveries`. Never retried here.
|
|
457
500
|
let confirmed = false;
|
|
458
501
|
try {
|
|
459
502
|
const current = findPane(await snapshot(target.server), target);
|
|
460
503
|
confirmed = !!current && current.terminal_id === pane.terminal_id && await paneIdentity(target.server, current, true) === target.session;
|
|
461
504
|
}
|
|
462
505
|
catch { /* No reliable post-delivery identity. */ }
|
|
463
|
-
// The hook can take it while the identity probe runs
|
|
464
|
-
|
|
465
|
-
const late = deliveryId ? agentHooks.deliveryState(deliveryId, target) : "unknown";
|
|
466
|
-
if (late === "blocked")
|
|
467
|
-
throw refusedHere();
|
|
506
|
+
// The hook can take it while the identity probe runs.
|
|
507
|
+
const late = deliveryId ? agentHooks.deliveries.status(deliveryId, target).state : "unknown";
|
|
468
508
|
if (late === "delivered")
|
|
469
|
-
result = { ok: true, delivered: true };
|
|
509
|
+
result = { ok: true, delivered: true, state: "delivered" };
|
|
470
510
|
else {
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
if (confirmed && deliveryId)
|
|
475
|
-
agentHooks.queueDelivery(deliveryId, target);
|
|
476
|
-
result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }) };
|
|
511
|
+
if (deliveryId)
|
|
512
|
+
agentHooks.deliveries.queue(deliveryId, target);
|
|
513
|
+
result = { ok: true, ...(!confirmed ? { deliveryUncertain: true } : { queued: true }), ...(deliveryId ? { state: "queued" } : {}) };
|
|
477
514
|
}
|
|
478
515
|
}
|
|
479
516
|
}
|
|
@@ -482,7 +519,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
482
519
|
const id = deliveryIdSchema.parse(data.deliveryId);
|
|
483
520
|
if (!id)
|
|
484
521
|
throw new BridgeError(400, "Name the message by its deliveryId.");
|
|
485
|
-
|
|
522
|
+
// Bound to the pane: the conversation that took it may be a newer one.
|
|
523
|
+
result = { ok: true, ...agentHooks.deliveries.status(id, target) };
|
|
486
524
|
}
|
|
487
525
|
else if (url.pathname === "/v1/side-question/dismiss") {
|
|
488
526
|
result = sideQuestions.dismiss(target, z.string().uuid().parse(data.id));
|