@phren/cli 0.3.55 → 0.3.56
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-hook-callback.js +1 -0
- package/dist/bridge/agent-hooks.js +1 -0
- package/dist/bridge/dispatch-returns.d.ts +4 -0
- package/dist/bridge/dispatch-returns.js +10 -3
- package/dist/bridge/hand-off-queue.d.ts +21 -0
- package/dist/bridge/hand-off-queue.js +31 -2
- package/dist/bridge/prompt-deliveries.d.ts +12 -0
- package/dist/bridge/prompt-deliveries.js +74 -21
- package/dist/bridge/server-pane-routes.d.ts +4 -0
- package/dist/bridge/server-pane-routes.js +20 -4
- package/dist/bridge/server.js +7 -1
- package/dist/bridge/session-activity.d.ts +28 -0
- package/dist/bridge/session-activity.js +30 -0
- package/dist/bridge/turn-records.d.ts +2 -0
- package/dist/bridge/turn-records.js +6 -1
- package/dist/bridge-hook.mjs +790 -694
- package/package.json +1 -1
|
@@ -94,6 +94,7 @@ async function forwardHook(source, target, event, value, left) {
|
|
|
94
94
|
...(source === "claude" && typeof value.transcript_path === "string" ? { transcript: value.transcript_path.slice(0, 4096) } : {}),
|
|
95
95
|
tool: value.tool_name, input: value.tool_input, toolUseId: value.tool_use_id, cwd: value.cwd,
|
|
96
96
|
...(event === "UserPromptSubmit" && typeof value.prompt === "string" ? { prompt: value.prompt.slice(0, 65_536) } : {}),
|
|
97
|
+
...(event === "SessionStart" && typeof value.source === "string" ? { startSource: value.source.slice(0, 32) } : {}),
|
|
97
98
|
...(event === "Stop" ? stopFacts(value) : {}) });
|
|
98
99
|
await new Promise(resolve => {
|
|
99
100
|
const req = request({ socketPath: localSocket(), path: "/hook", method: "POST", timeout: event === "PermissionRequest" ? 58_000 : event.endsWith("ToolUse") ? Math.max(1, left()) : 12_000,
|
|
@@ -559,6 +559,7 @@ export class AgentHooks {
|
|
|
559
559
|
return;
|
|
560
560
|
await recordTurn(target.server, target.pane, { event: String(body.event), terminal: pane.terminal_id, source: target.source, session: target.session,
|
|
561
561
|
...(dispatch ? { dispatch } : {}),
|
|
562
|
+
...(body.event === "SessionStart" && typeof body.startSource === "string" ? { start: body.startSource } : {}),
|
|
562
563
|
...(typeof body.background === "number" ? { background: body.background } : {}),
|
|
563
564
|
...(typeof body.reply === "string" ? { reply: body.reply } : {}),
|
|
564
565
|
...(body.event === "Stop" && typeof body.cwd === "string" ? { cwd: body.cwd } : {}) }).catch(() => undefined);
|
|
@@ -223,6 +223,9 @@ export interface DispatchReturnsOptions {
|
|
|
223
223
|
/** A recent Herdr snapshot of a local server, to see whether the dispatching agent is idle. */
|
|
224
224
|
snapshot?: (server: string) => Promise<Json>;
|
|
225
225
|
identity?: (server: string, pane: Json) => Promise<string | undefined>;
|
|
226
|
+
/** Whether the dispatching agent takes a typed notice now (session-activity.ts `takesPrompt`, with
|
|
227
|
+
* the Hook's `promptGuards`, so a dialog in a lead Herdr reads working is never answered). */
|
|
228
|
+
takesPrompt?: (target: Target, pane: Json) => Promise<boolean>;
|
|
226
229
|
/** Types the notice into the dispatching agent, through the ordinary hand-off
|
|
227
230
|
* path; the same notice keeps one delivery id, so a retry is never typed twice. */
|
|
228
231
|
deliver?: (target: Target, text: string, deliveryId: string) => Promise<{
|
|
@@ -256,6 +259,7 @@ export declare class DispatchReturns {
|
|
|
256
259
|
private readonly isLocal;
|
|
257
260
|
private readonly snapshot;
|
|
258
261
|
private readonly identity;
|
|
262
|
+
private readonly takesPrompt;
|
|
259
263
|
private readonly deliver;
|
|
260
264
|
private readonly localArrival;
|
|
261
265
|
private readonly now;
|
|
@@ -17,7 +17,7 @@ import { hookPeers, peerRequest } from "./peers.js";
|
|
|
17
17
|
import { isLocalComputer, peerFingerprint } from "./dispatch-hosts.js";
|
|
18
18
|
import { BridgeError, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
19
19
|
import { isClaudeUsageLimit, ownerQuestion, readFinalTurn } from "./schedule-watch.js";
|
|
20
|
-
import { liveWork, runningTasks } from "./session-activity.js";
|
|
20
|
+
import { liveWork, runningTasks, takesPrompt } from "./session-activity.js";
|
|
21
21
|
import { terminalProvider } from "./terminal.js";
|
|
22
22
|
import { childAgentTree, runningChildAgents } from "./transcripts.js";
|
|
23
23
|
import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
|
|
@@ -562,6 +562,7 @@ export class DispatchReturns {
|
|
|
562
562
|
isLocal;
|
|
563
563
|
snapshot;
|
|
564
564
|
identity;
|
|
565
|
+
takesPrompt;
|
|
565
566
|
deliver;
|
|
566
567
|
localArrival;
|
|
567
568
|
now;
|
|
@@ -587,6 +588,7 @@ export class DispatchReturns {
|
|
|
587
588
|
this.isLocal = options.isLocal ?? (computer => isLocalComputer(computer));
|
|
588
589
|
this.snapshot = options.snapshot ?? (server => sharedSnapshot(server, SNAPSHOT_AGE_MS));
|
|
589
590
|
this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
|
|
591
|
+
this.takesPrompt = options.takesPrompt ?? ((target, pane) => takesPrompt(target.server, pane, target.session));
|
|
590
592
|
this.deliver = options.deliver ?? ((target, text, deliveryId) => handOff({ target, text }, { deliveryId, bypassConductor: true }));
|
|
591
593
|
this.localArrival = options.localArrival ?? briefArrival;
|
|
592
594
|
this.now = options.now ?? Date.now;
|
|
@@ -855,10 +857,11 @@ export class DispatchReturns {
|
|
|
855
857
|
}
|
|
856
858
|
else {
|
|
857
859
|
const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
|
|
858
|
-
// Never interrupt: only an agent that has stopped, in the same terminal, gets a notice.
|
|
860
|
+
// Never interrupt: only an agent that has stopped, in the same terminal, gets a notice. A Claude
|
|
861
|
+
// lead whose turn ended while its background agents run on has stopped, though Herdr reads it working.
|
|
859
862
|
if (!pane || pane.terminal_id !== origin.terminal)
|
|
860
863
|
continue;
|
|
861
|
-
if (!["idle", "done"].includes(String(pane.agent_status))) {
|
|
864
|
+
if (!["idle", "done", "working"].includes(String(pane.agent_status))) {
|
|
862
865
|
busy = true;
|
|
863
866
|
continue;
|
|
864
867
|
}
|
|
@@ -866,6 +869,10 @@ export class DispatchReturns {
|
|
|
866
869
|
const target = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
|
|
867
870
|
if (!target.success)
|
|
868
871
|
continue;
|
|
872
|
+
if (!await this.takesPrompt(target.data, pane).catch(() => false)) {
|
|
873
|
+
busy = true;
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
869
876
|
this.lastNotice.set(key, this.now());
|
|
870
877
|
const sent = await this.deliver(target.data, noticeLine(receipts), noticeDeliveryId(receipts)).catch(() => ({ delivered: false }));
|
|
871
878
|
if (!sent.delivered)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import { type Json, type Target } from "./protocol.js";
|
|
3
|
+
import type { DeliveryStatus } from "./prompt-deliveries.js";
|
|
3
4
|
export declare const queuedHandOffSchema: z.ZodObject<{
|
|
4
5
|
target: z.ZodObject<{
|
|
5
6
|
server: z.ZodString;
|
|
@@ -45,6 +46,19 @@ export interface QueueOptions {
|
|
|
45
46
|
session: string;
|
|
46
47
|
terminal: unknown;
|
|
47
48
|
} | undefined>;
|
|
49
|
+
/** What became of the message typed under `deliveryId` (prompt-deliveries.ts): an agent whose
|
|
50
|
+
* UserPromptSubmit comes after the send returned settles it there, later. */
|
|
51
|
+
delivery?: (target: Target, deliveryId: string) => DeliveryStatus;
|
|
52
|
+
/** Whether text typed into the target's pane is still waiting to be taken. Nothing more is typed
|
|
53
|
+
* there until it is: a second paste would land in the same input line, after the first. */
|
|
54
|
+
inFlight?: (target: Target) => boolean;
|
|
55
|
+
/** Whether the message typed under `deliveryId` may still be taken: held, and not past the time a pane
|
|
56
|
+
* that sends no hooks is given (prompt-deliveries.ts `held`). */
|
|
57
|
+
held?: (target: Target, deliveryId: string) => boolean;
|
|
58
|
+
/** Whether the target's agent takes a typed prompt now (session-activity.ts `takesPrompt`): idle or
|
|
59
|
+
* done, or a Claude turn that ended while its background agents run on, which Herdr reads working.
|
|
60
|
+
* Without it, only an idle or done pane is typed into. */
|
|
61
|
+
ready?: (target: Target, pane: Json) => Promise<boolean>;
|
|
48
62
|
now?: () => number;
|
|
49
63
|
root?: string;
|
|
50
64
|
}
|
|
@@ -70,6 +84,13 @@ export declare class HandOffQueue {
|
|
|
70
84
|
private file;
|
|
71
85
|
private save;
|
|
72
86
|
private read;
|
|
87
|
+
/** An uncertain row takes the outcome its typed message came to: delivered once the agent's
|
|
88
|
+
* UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
|
|
89
|
+
* failed row still turns delivered when the agent takes the message late. */
|
|
90
|
+
private follow;
|
|
91
|
+
/** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
|
|
92
|
+
* in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
|
|
93
|
+
private stillHeld;
|
|
73
94
|
private rows;
|
|
74
95
|
/** Drops settled rows past retention, then the oldest settled rows over the
|
|
75
96
|
* cap (those still owing their sender a notice last). Returns what is kept. */
|
|
@@ -80,8 +80,32 @@ export class HandOffQueue {
|
|
|
80
80
|
row.error = "The Hook restarted before delivery was confirmed.";
|
|
81
81
|
await this.save(row);
|
|
82
82
|
}
|
|
83
|
+
await this.follow(row);
|
|
83
84
|
return row;
|
|
84
85
|
}
|
|
86
|
+
/** An uncertain row takes the outcome its typed message came to: delivered once the agent's
|
|
87
|
+
* UserPromptSubmit came, failed (with why) once the Hook knows the agent will not take it. A
|
|
88
|
+
* failed row still turns delivered when the agent takes the message late. */
|
|
89
|
+
async follow(row) {
|
|
90
|
+
if ((row.state !== "uncertain" && row.state !== "failed") || !this.options.delivery)
|
|
91
|
+
return;
|
|
92
|
+
const known = this.options.delivery(row.target, row.deliveryId);
|
|
93
|
+
if (known.state === "delivered") {
|
|
94
|
+
row.state = "delivered";
|
|
95
|
+
delete row.error;
|
|
96
|
+
await this.save(row);
|
|
97
|
+
}
|
|
98
|
+
else if (known.state === "failed" && row.state === "uncertain") {
|
|
99
|
+
row.state = "failed";
|
|
100
|
+
row.error = (known.reason ?? "The agent did not take the message.").slice(0, 500);
|
|
101
|
+
await this.save(row);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Uncertain only while the agent may still take it: its typed message is held, not yet settled, and
|
|
105
|
+
* in a pane whose hooks will settle it or typed only moments ago. Past that the sender hears "uncertain". */
|
|
106
|
+
stillHeld(row) {
|
|
107
|
+
return row.state === "uncertain" && !!this.options.held?.(row.target, row.deliveryId);
|
|
108
|
+
}
|
|
85
109
|
async rows() {
|
|
86
110
|
const names = await readdir(this.root).catch(error => { if (error.code === "ENOENT")
|
|
87
111
|
return []; throw error; });
|
|
@@ -189,7 +213,11 @@ export class HandOffQueue {
|
|
|
189
213
|
await this.save(row);
|
|
190
214
|
return;
|
|
191
215
|
}
|
|
192
|
-
if (!["idle", "done"].includes(String(pane.agent_status)))
|
|
216
|
+
if (!(this.options.ready ? await this.options.ready(row.target, pane).catch(() => false) : ["idle", "done"].includes(String(pane.agent_status))))
|
|
217
|
+
return;
|
|
218
|
+
// Herdr reads a pane idle for a few seconds after a prompt was submitted, while the agent runs its
|
|
219
|
+
// hooks; typing the next message then left both in the input line (2026-10-17, five 5 s apart).
|
|
220
|
+
if (this.options.inFlight?.(row.target))
|
|
193
221
|
return;
|
|
194
222
|
let typed = false;
|
|
195
223
|
try {
|
|
@@ -236,8 +264,9 @@ export class HandOffQueue {
|
|
|
236
264
|
attempted.add(key);
|
|
237
265
|
await this.attempt(row);
|
|
238
266
|
}
|
|
267
|
+
// A sender hears the outcome once there is one: not "uncertain" for a message the agent still holds.
|
|
239
268
|
for (const row of rows)
|
|
240
|
-
if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
|
|
269
|
+
if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state) && !this.stillHeld(row)) {
|
|
241
270
|
if (row.originComputer) {
|
|
242
271
|
remote.push(row);
|
|
243
272
|
continue;
|
|
@@ -8,6 +8,7 @@ export type DeliveryState = "queued" | "delivered" | "failed";
|
|
|
8
8
|
export interface TranscriptEntry {
|
|
9
9
|
offset: number;
|
|
10
10
|
hook: boolean;
|
|
11
|
+
at?: number;
|
|
11
12
|
}
|
|
12
13
|
export type TrackedState = DeliveryState | "unknown";
|
|
13
14
|
export interface DeliveryStatus {
|
|
@@ -21,6 +22,9 @@ export declare const DELIVERY_RETENTION_MS: number;
|
|
|
21
22
|
/** An agent that ended its turn after the message was typed and then stayed
|
|
22
23
|
* idle this long without taking it has dropped it. */
|
|
23
24
|
export declare const DELIVERY_GIVE_UP_MS = 30000;
|
|
25
|
+
/** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
|
|
26
|
+
* UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */
|
|
27
|
+
export declare const IN_FLIGHT_MS = 45000;
|
|
24
28
|
/** What the agent hands its UserPromptSubmit hook is the terminal's pasted
|
|
25
29
|
* form of what Phren typed; compare the words, not the wrapping. Claude Code
|
|
26
30
|
* also takes each attached picture's path line out of the text and puts an
|
|
@@ -43,6 +47,8 @@ export declare class PromptDeliveries {
|
|
|
43
47
|
private writing;
|
|
44
48
|
/** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
|
|
45
49
|
private hookPanes;
|
|
50
|
+
/** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
|
|
51
|
+
private lastStop;
|
|
46
52
|
private paneKey;
|
|
47
53
|
private static open;
|
|
48
54
|
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
@@ -69,6 +75,12 @@ export declare class PromptDeliveries {
|
|
|
69
75
|
private open;
|
|
70
76
|
/** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
|
|
71
77
|
pending(target: Target, text: string): boolean;
|
|
78
|
+
/** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
|
|
79
|
+
private inFlight;
|
|
80
|
+
/** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
|
|
81
|
+
holding(target: Pick<Target, "server" | "pane" | "source">): boolean;
|
|
82
|
+
/** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
|
|
83
|
+
held(id: string, target: Pick<Target, "server" | "pane" | "source">): boolean;
|
|
72
84
|
/** Wait again for a message `expect` reported pending, after a second Enter. */
|
|
73
85
|
awaitLate(target: Target, text: string, waitMs?: number): Promise<DeliveryOutcome>;
|
|
74
86
|
private find;
|
|
@@ -15,6 +15,11 @@ const MAX_RECORDS = 512;
|
|
|
15
15
|
const LANDED_CHECK_MS = 3_000;
|
|
16
16
|
/** The transcript scan starts this long before a message was typed (clock skew), so entries up to this far back may belong to an earlier message. */
|
|
17
17
|
const ENTRY_SLACK_MS = 5_000;
|
|
18
|
+
/** Claude writes a submitted row after its hooks return; a message its hook settled claims only a row stamped within this long of that. */
|
|
19
|
+
const HOOK_ROW_MS = 30_000;
|
|
20
|
+
/** Typed text holds its pane (nothing more is typed there) at most this long when the pane sends no
|
|
21
|
+
* UserPromptSubmit or Stop to settle it: a message such an agent took or dropped never settles. */
|
|
22
|
+
export const IN_FLIGHT_MS = 45_000;
|
|
18
23
|
/** What the agent hands its UserPromptSubmit hook is the terminal's pasted
|
|
19
24
|
* form of what Phren typed; compare the words, not the wrapping. Claude Code
|
|
20
25
|
* also takes each attached picture's path line out of the text and puts an
|
|
@@ -33,6 +38,8 @@ const recordSchema = z.object({
|
|
|
33
38
|
reason: z.string().max(500).optional(), at: z.number(), settledAt: z.number().optional(), stoppedAt: z.number().optional(),
|
|
34
39
|
/** The transcript entry (byte offset) that settled it, so no other message claims the same one. */
|
|
35
40
|
entry: z.number().optional(),
|
|
41
|
+
/** Whether that entry is a user row (one its agent's UserPromptSubmit fired for), not a mid-turn queue removal. */
|
|
42
|
+
entryHook: z.boolean().optional(),
|
|
36
43
|
}).strict();
|
|
37
44
|
/** One message per record, bound to the pane it was typed into (server, pane,
|
|
38
45
|
* agent kind), not to the conversation: a Codex thread or a Claude /clear can
|
|
@@ -49,6 +56,8 @@ export class PromptDeliveries {
|
|
|
49
56
|
writing = Promise.resolve();
|
|
50
57
|
/** Panes (server, pane, agent) that sent a UserPromptSubmit or Stop since the Hook started. */
|
|
51
58
|
hookPanes = new Set();
|
|
59
|
+
/** When each pane (server, pane, agent) last sent a Stop since the Hook started. */
|
|
60
|
+
lastStop = new Map();
|
|
52
61
|
paneKey(target) { return [target.server, target.pane, target.source].join("|"); }
|
|
53
62
|
static open(record) { return record.state === "typed" || record.state === "queued"; }
|
|
54
63
|
/** Open, or failed with its own hook's claim still waiting for its row (a late delivery). */
|
|
@@ -137,6 +146,14 @@ export class PromptDeliveries {
|
|
|
137
146
|
}
|
|
138
147
|
/** A message Phren typed into `target`'s pane that no conversation there has submitted yet. */
|
|
139
148
|
pending(target, text) { return !!this.open(target, text); }
|
|
149
|
+
/** Whether `record` still holds its pane: open, and either young or in a pane whose hooks will settle it. */
|
|
150
|
+
inFlight(record) {
|
|
151
|
+
return PromptDeliveries.open(record) && (this.now() - record.at < IN_FLIGHT_MS || this.hookPanes.has(this.paneKey(record)));
|
|
152
|
+
}
|
|
153
|
+
/** Whether any message typed into `target`'s pane is still waiting to be taken or refused. */
|
|
154
|
+
holding(target) { return this.records.some(record => this.samePane(record, target) && this.inFlight(record)); }
|
|
155
|
+
/** Whether phone message `id` may still be taken: held by the agent, and in flight as `holding` counts it. */
|
|
156
|
+
held(id, target) { const record = this.find(id, target); return !!record && this.inFlight(record); }
|
|
140
157
|
/** Wait again for a message `expect` reported pending, after a second Enter. */
|
|
141
158
|
awaitLate(target, text, waitMs = 2_500) {
|
|
142
159
|
const record = this.open(target, text);
|
|
@@ -228,8 +245,12 @@ export class PromptDeliveries {
|
|
|
228
245
|
async submitted(target, prompt) {
|
|
229
246
|
const hash = promptHash(prompt);
|
|
230
247
|
this.hookPanes.add(this.paneKey(target));
|
|
248
|
+
// A failed message stays matchable for a late take only until the pane's next Stop: a turn that ended
|
|
249
|
+
// without it means a later identical prompt is a new one.
|
|
250
|
+
const stop = this.lastStop.get(this.paneKey(target)) ?? -Infinity;
|
|
231
251
|
const pick = () => {
|
|
232
|
-
const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered"
|
|
252
|
+
const open = this.records.filter(record => record.hash === hash && this.samePane(record, target) && record.state !== "delivered"
|
|
253
|
+
&& (record.state !== "failed" || (record.settledAt ?? record.at) >= stop));
|
|
233
254
|
return open.find(entry => entry.session === target.session) ?? open[0];
|
|
234
255
|
};
|
|
235
256
|
let record = pick();
|
|
@@ -251,30 +272,34 @@ export class PromptDeliveries {
|
|
|
251
272
|
if (!record)
|
|
252
273
|
return;
|
|
253
274
|
// Claims are per conversation: another conversation's rows can sit at the same byte offset.
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
275
|
+
// Only user rows count: a mid-turn queue removal never had a hook, so it says nothing about this callback.
|
|
276
|
+
const claimed = new Set(this.records.filter(other => other.hash === hash && this.samePane(other, target) && other.session === target.session && other.entry !== undefined && other.entryHook !== false).map(other => other.entry));
|
|
277
|
+
const free = rows?.filter(row => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
|
|
278
|
+
// Claude writes the submitted row only after its UserPromptSubmit hooks return, and this callback is one
|
|
279
|
+
// of them: the row for this submission is never readable yet. So no free row (or a transcript that cannot
|
|
280
|
+
// be read) settles on the hook's word at once, as the agent took it and started its turn. The row it
|
|
281
|
+
// writes next stays this message's (`taken` counts hook-settled messages first). Only when a message
|
|
282
|
+
// with these words already claimed a row in this conversation may the callback be that message's, late:
|
|
283
|
+
// then it waits for a row of its own, looked for in the conversation that made the claim.
|
|
284
|
+
if (!free && !claimed.size) {
|
|
258
285
|
this.settle(record, undefined, target.session);
|
|
259
286
|
this.save();
|
|
260
287
|
return;
|
|
261
288
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
289
|
+
if (!free) {
|
|
290
|
+
if (!rows?.length) {
|
|
291
|
+
record.hookClaim = true;
|
|
292
|
+
record.session = target.session;
|
|
293
|
+
}
|
|
266
294
|
return;
|
|
267
295
|
}
|
|
268
|
-
const free = rows.filter(row => !claimed.has(row.offset)).sort((a, b) => a.offset - b.offset)[0];
|
|
269
|
-
if (!free)
|
|
270
|
-
return;
|
|
271
296
|
entry = free.offset;
|
|
272
297
|
}
|
|
273
|
-
this.settle(record, entry, target.session);
|
|
298
|
+
this.settle(record, entry, target.session, entry !== undefined ? true : undefined);
|
|
274
299
|
this.save();
|
|
275
300
|
}
|
|
276
301
|
/** Marks `record` delivered, with the transcript entry that settled it when known. */
|
|
277
|
-
settle(record, entry, session) {
|
|
302
|
+
settle(record, entry, session, hook) {
|
|
278
303
|
record.state = "delivered";
|
|
279
304
|
record.settledAt = this.now();
|
|
280
305
|
delete record.reason;
|
|
@@ -284,6 +309,8 @@ export class PromptDeliveries {
|
|
|
284
309
|
record.session = session;
|
|
285
310
|
if (entry !== undefined)
|
|
286
311
|
record.entry = entry;
|
|
312
|
+
if (hook !== undefined)
|
|
313
|
+
record.entryHook = hook;
|
|
287
314
|
this.release(record, "delivered");
|
|
288
315
|
}
|
|
289
316
|
/** Whether the transcript shows the agent took `record`'s message, claiming the entry it settled with.
|
|
@@ -304,12 +331,30 @@ export class PromptDeliveries {
|
|
|
304
331
|
const key = [record.hash, record.server, record.pane, record.session, working].join("|");
|
|
305
332
|
let free = pass.get(key);
|
|
306
333
|
if (!free) {
|
|
307
|
-
|
|
334
|
+
// A message the agent's hook settled before its row was written took that row without recording it: the
|
|
335
|
+
// scan reaches back to it, and it claims (and keeps) the earliest unclaimed user row stamped after it was
|
|
336
|
+
// typed and soon after its hook, oldest first, before any open message is offered a row.
|
|
337
|
+
const hooked = this.records.filter(other => same(other) && other.state === "delivered" && other.entry === undefined)
|
|
338
|
+
.sort((a, b) => (a.settledAt ?? a.at) - (b.settledAt ?? b.at));
|
|
339
|
+
const from = Math.min(record.at, ...hooked.map(other => other.at));
|
|
340
|
+
const found = (await this.landed({ ...record, at: from }).catch(() => [])).sort((a, b) => a.offset - b.offset);
|
|
308
341
|
const used = new Set(this.records.filter(other => same(other) && other.entry !== undefined).map(other => other.entry));
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
342
|
+
let claimedRows = false;
|
|
343
|
+
for (const other of hooked) {
|
|
344
|
+
if (other.entry !== undefined)
|
|
345
|
+
continue;
|
|
346
|
+
const row = found.find(entry => entry.hook && !used.has(entry.offset)
|
|
347
|
+
&& (entry.at === undefined || (entry.at >= other.at - ENTRY_SLACK_MS && entry.at <= (other.settledAt ?? other.at) + HOOK_ROW_MS)));
|
|
348
|
+
if (!row)
|
|
349
|
+
continue;
|
|
350
|
+
other.entry = row.offset;
|
|
351
|
+
other.entryHook = true;
|
|
352
|
+
used.add(row.offset);
|
|
353
|
+
claimedRows = true;
|
|
354
|
+
}
|
|
355
|
+
if (claimedRows)
|
|
356
|
+
this.save();
|
|
357
|
+
const unclaimed = found.filter(entry => !used.has(entry.offset) && (entry.at === undefined || entry.at >= record.at - ENTRY_SLACK_MS));
|
|
313
358
|
if (working) {
|
|
314
359
|
// A user row is its hook's to settle, unless that hook already came (before the row could be read), or
|
|
315
360
|
// the pane sends no callbacks at all: then a row two checks in a row saw unclaimed settles it.
|
|
@@ -331,12 +376,14 @@ export class PromptDeliveries {
|
|
|
331
376
|
if (entry === undefined)
|
|
332
377
|
return false;
|
|
333
378
|
record.entry = entry.offset;
|
|
379
|
+
record.entryHook = entry.hook;
|
|
334
380
|
return true;
|
|
335
381
|
}
|
|
336
382
|
/** A turn in `target`'s pane ended: the agent now takes held input or never will. */
|
|
337
383
|
stopped(target) {
|
|
338
384
|
const at = this.now();
|
|
339
385
|
this.hookPanes.add(this.paneKey(target));
|
|
386
|
+
this.lastStop.set(this.paneKey(target), at);
|
|
340
387
|
let marked = false;
|
|
341
388
|
for (const record of this.records)
|
|
342
389
|
if (this.samePane(record, target) && (record.state === "typed" || record.state === "queued") && record.at < at) {
|
|
@@ -431,6 +478,9 @@ export function matchingOffsets(buffer, start, record) {
|
|
|
431
478
|
for (let index = lines.length - 1; index >= 0; index--) {
|
|
432
479
|
const line = lines[index];
|
|
433
480
|
offset -= Buffer.byteLength(line) + (index < lines.length - 1 ? 1 : 0);
|
|
481
|
+
// Only a row that can carry user text is parsed: the scan reads the whole tail now, not just its newest rows.
|
|
482
|
+
if (!line.includes('"user') && !line.includes("queue-operation"))
|
|
483
|
+
continue;
|
|
434
484
|
let row;
|
|
435
485
|
try {
|
|
436
486
|
row = object(JSON.parse(line));
|
|
@@ -438,12 +488,15 @@ export function matchingOffsets(buffer, start, record) {
|
|
|
438
488
|
catch {
|
|
439
489
|
continue;
|
|
440
490
|
}
|
|
491
|
+
// Rows are not in time order: Claude writes a queued message's attachment rows, stamped when it was
|
|
492
|
+
// typed, after the queue removal that took it. An older row is skipped, never the end of the scan,
|
|
493
|
+
// or a message typed after an earlier queued one is never found (seen 2026-10-17: taken, reported failed).
|
|
441
494
|
const stamp = Date.parse(String(row.timestamp ?? ""));
|
|
442
495
|
if (Number.isFinite(stamp) && stamp < record.at - 5_000)
|
|
443
|
-
|
|
496
|
+
continue;
|
|
444
497
|
// One entry per row, even when its content repeats the words.
|
|
445
498
|
if (userTexts(row).some(text => promptHash(text) === record.hash))
|
|
446
|
-
entries.push({ offset, hook: row.type === "user" });
|
|
499
|
+
entries.push({ offset, hook: row.type === "user", ...(Number.isFinite(stamp) ? { at: stamp } : {}) });
|
|
447
500
|
}
|
|
448
501
|
return entries;
|
|
449
502
|
}
|
|
@@ -5,6 +5,7 @@ import { type WorktreeWorker } from "./git-worktrees.js";
|
|
|
5
5
|
import { type ModelSwitcher } from "./model-switch.js";
|
|
6
6
|
import { type PermissionModeSwitcher } from "./permission-mode.js";
|
|
7
7
|
import type { SettingsSwitcher } from "./settings-switch.js";
|
|
8
|
+
import { type PromptGuards } from "./session-activity.js";
|
|
8
9
|
import { type Json, type Target } from "./protocol.js";
|
|
9
10
|
import type { CodexQuestions } from "./questions.js";
|
|
10
11
|
import { type SideQuestions } from "./side-questions.js";
|
|
@@ -32,6 +33,9 @@ export declare function gitRepository(pane: Json, target: Target, child: unknown
|
|
|
32
33
|
* an agent launched into a new worktree from the phone is named here. Listed
|
|
33
34
|
* last, so a sub-agent or fan-out manifest for the same folder wins a tie. */
|
|
34
35
|
export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
|
|
36
|
+
/** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
|
|
37
|
+
* pending there and no dialog on its screen. */
|
|
38
|
+
export declare function promptGuards(agentHooks: Pick<AgentHooks, "approval" | "terminalPrompt" | "servedQuestion">, target: Target): PromptGuards;
|
|
35
39
|
/** A busy Claude Code queues typed text on Enter, but after a long paste
|
|
36
40
|
* ("paste again to expand") it can swallow that Enter and leave the text in
|
|
37
41
|
* its input line, where it stays after the turn ends. Follow the pane: once
|
|
@@ -15,6 +15,7 @@ import { CodexServerUnavailable, codexServers } from "./codex-servers.js";
|
|
|
15
15
|
import { refuseWorkingSlash } from "./model-switch.js";
|
|
16
16
|
import { PERMISSION_MODE_VALUES, refuseAgentOrigin } from "./permission-mode.js";
|
|
17
17
|
import { sessionWebServers } from "./session-servers.js";
|
|
18
|
+
import { takesPrompt } from "./session-activity.js";
|
|
18
19
|
import { gitRoot, repositoryDiff, withGitReadDeadline } from "./projects.js";
|
|
19
20
|
import { BridgeError, MAX_FRAME, object, objects, startingTargetSchema, targetSchema } from "./protocol.js";
|
|
20
21
|
import { childAgent, childAgentTree, conversationNamedPaths, targetTranscriptPath } from "./transcripts.js";
|
|
@@ -119,6 +120,14 @@ function claudeQuestionAnswer(data) {
|
|
|
119
120
|
}
|
|
120
121
|
/** A secret typed into a terminal prompt: printable, bounded, never logged. */
|
|
121
122
|
const secretText = z.string().min(1).max(256).refine(t => !/[\x00-\x1f\x7f]/.test(t));
|
|
123
|
+
/** What `takesPrompt` checks before typing into a Claude pane Herdr reads working: nothing structured
|
|
124
|
+
* pending there and no dialog on its screen. */
|
|
125
|
+
export function promptGuards(agentHooks, target) {
|
|
126
|
+
return { held: () => !!(agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)),
|
|
127
|
+
screen: () => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 40, format: "ansi", timeoutMs: 2_000 }) };
|
|
128
|
+
}
|
|
129
|
+
/** Herdr answered the request with a refusal (a 409 carrying its own error code): it performed nothing. */
|
|
130
|
+
const herdrRefused = (error) => error instanceof BridgeError && error.status === 409 && typeof error.details?.herdrCode === "string";
|
|
122
131
|
/** An idle agent that has not taken typed text within the first wait
|
|
123
132
|
* likely lost the Enter while it redrew (an update notice, a resize): the
|
|
124
133
|
* text sits in its input line. Press Enter once more and wait again. A
|
|
@@ -131,8 +140,10 @@ async function resubmitIfIdle(agentHooks, target, text) {
|
|
|
131
140
|
catch {
|
|
132
141
|
return "unknown";
|
|
133
142
|
} };
|
|
143
|
+
// A pane that turned working started a turn: its UserPromptSubmit is on its way (the agent runs its
|
|
144
|
+
// other hooks too). Wait for it rather than answering "queued" for a message the agent took.
|
|
134
145
|
if (await status() === "working")
|
|
135
|
-
return
|
|
146
|
+
return await agentHooks.deliveries.awaitLate(target, text);
|
|
136
147
|
const late = agentHooks.deliveries.awaitLate(target, text);
|
|
137
148
|
await terminalProvider().sendKeys(target.server, target.pane, ["enter"]);
|
|
138
149
|
const outcome = await late;
|
|
@@ -388,7 +399,8 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
388
399
|
// is pending there: an approval the Hook holds or saw, or a
|
|
389
400
|
// status Herdr cannot read. Otherwise the answer keys are the way.
|
|
390
401
|
const status = String(pane.agent_status);
|
|
391
|
-
|
|
402
|
+
// A Claude lead waiting on its background agents takes a prompt though Herdr reads it working (`takesPrompt`).
|
|
403
|
+
if (data.hookQueued === true && !await takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)))
|
|
392
404
|
throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
|
|
393
405
|
if (status === "unknown" || (["blocked", "waiting"].includes(status) && (agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)))) {
|
|
394
406
|
throw new BridgeError(409, "This agent needs input in the terminal first.");
|
|
@@ -462,12 +474,16 @@ export async function paneRouteOnce(ctx, url, data, response, typing) {
|
|
|
462
474
|
let outcome = await promptWithStartupRetry(async () => {
|
|
463
475
|
const refused = new AbortController();
|
|
464
476
|
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);
|
|
465
|
-
|
|
477
|
+
let typed = false;
|
|
466
478
|
try {
|
|
479
|
+
await typing();
|
|
480
|
+
typed = true;
|
|
467
481
|
await terminalProvider().prompt(target.server, target.pane, text);
|
|
468
482
|
}
|
|
469
483
|
catch (error) {
|
|
470
|
-
|
|
484
|
+
// Nothing reached the pane: the reservation failed first, the agent was not ready, or Herdr refused the
|
|
485
|
+
// request (its `agent.prompt` is one call). The record goes, or it would hold the pane's hand-offs.
|
|
486
|
+
if (!typed || agentNotReady(error) || herdrRefused(error))
|
|
471
487
|
refused.abort();
|
|
472
488
|
throw error;
|
|
473
489
|
}
|
package/dist/bridge/server.js
CHANGED
|
@@ -12,7 +12,7 @@ import { hookPeers, peerRequest } from "./peers.js";
|
|
|
12
12
|
import { handOff } from "./hand-off.js";
|
|
13
13
|
import { sessionStalls } from "./stalls.js";
|
|
14
14
|
import { HandOffQueue } from "./hand-off-queue.js";
|
|
15
|
-
import { paneRouteOnce } from "./server-pane-routes.js";
|
|
15
|
+
import { paneRouteOnce, promptGuards } from "./server-pane-routes.js";
|
|
16
16
|
import { FanoutMessages } from "./fanout-messages.js";
|
|
17
17
|
import { activateModules as moduleSnapshot } from "../modules/runtime.js";
|
|
18
18
|
import { disabledHint } from "../modules/registry.js";
|
|
@@ -60,6 +60,7 @@ import { SessionMover, transcriptTail } from "./session-move.js";
|
|
|
60
60
|
import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
|
|
61
61
|
import { paneAccount, paneAccountKey } from "./pane-accounts.js";
|
|
62
62
|
import { readTurn } from "./turn-records.js";
|
|
63
|
+
import { takesPrompt } from "./session-activity.js";
|
|
63
64
|
import { readLaunchBrief } from "./launch-brief.js";
|
|
64
65
|
import { conductorPane, readRoleState } from "./conductor-role.js";
|
|
65
66
|
import { terminalKind, terminalProvider } from "./terminal.js";
|
|
@@ -108,6 +109,7 @@ export async function serve(version, options = {}) {
|
|
|
108
109
|
// Follows what dispatched workers do and tells the dispatching agent.
|
|
109
110
|
let succession;
|
|
110
111
|
const returns = dispatches ? new DispatchReturns({
|
|
112
|
+
takesPrompt: (target, pane) => takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)),
|
|
111
113
|
localComputer: { id: computerID, name: hostname() },
|
|
112
114
|
forward: (origin, text, deliveryId) => succession?.forward(origin, text, deliveryId) ?? Promise.resolve(undefined),
|
|
113
115
|
// Continue on another signed-in account when a Claude worker stops at its usage limit: opt-in, `phren config account-failover on`.
|
|
@@ -155,6 +157,10 @@ export async function serve(version, options = {}) {
|
|
|
155
157
|
},
|
|
156
158
|
notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false, bypassConductor: true }),
|
|
157
159
|
send: sendPrompt,
|
|
160
|
+
delivery: (target, deliveryId) => agentHooks.deliveries.status(deliveryId, target),
|
|
161
|
+
inFlight: target => agentHooks.deliveries.holding(target),
|
|
162
|
+
held: (target, deliveryId) => agentHooks.deliveries.held(deliveryId, target),
|
|
163
|
+
ready: (target, pane) => takesPrompt(target.server, pane, target.session, promptGuards(agentHooks, target)),
|
|
158
164
|
}) : undefined;
|
|
159
165
|
// Moving a session to another agent (session-move.ts): its hand-off request
|
|
160
166
|
// takes the hand_off path, and the new agent starts through the launch path.
|
|
@@ -36,6 +36,34 @@ export declare const BACKGROUND_STALE_MS: number;
|
|
|
36
36
|
* the Stop's count less those `finishedTasks` (FinalTurn's) says finished
|
|
37
37
|
* after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
|
|
38
38
|
export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
|
|
39
|
+
/** What may still be open in a pane whose turn record says it ended: Claude
|
|
40
|
+
* starts a turn on its own when a background agent finishes (its task
|
|
41
|
+
* notification, with no UserPromptSubmit), and that turn can open a dialog
|
|
42
|
+
* Herdr still reads as working (plan approval, an MCP elicitation, a
|
|
43
|
+
* permission request the Hook holds). Pasted text plus Enter would answer it. */
|
|
44
|
+
export interface PromptGuards {
|
|
45
|
+
/** An approval the Hook holds, a terminal prompt or a question it serves for this pane. */
|
|
46
|
+
held?: () => boolean;
|
|
47
|
+
/** The pane's visible screen; a dialog there (pane-status.ts `screenDialog`) or a failed read refuses. */
|
|
48
|
+
screen?: () => Promise<string>;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Whether the agent in a pane takes a typed prompt now: Herdr reads it idle or
|
|
52
|
+
* done, or it is a Claude session Herdr reads `working` whose own turn record
|
|
53
|
+
* ended with background tasks still running (`recordedBackground`). That is
|
|
54
|
+
* Claude's "Waiting for N background agents to finish": its turn is over and
|
|
55
|
+
* pasted text plus Enter submits at once and starts a turn (seen live, Claude
|
|
56
|
+
* Code 2.1.302), but Herdr keeps it `working` until the last background agent
|
|
57
|
+
* ends. Waiting for idle there held a hand-off or a dispatch-return notice for
|
|
58
|
+
* as long as a lead kept sub-agents running, over an hour. Another working
|
|
59
|
+
* pane, or one blocked, waiting or unknown, does not take one, nor one with a
|
|
60
|
+
* dialog open (`guards`). The record is read only for a working Claude pane,
|
|
61
|
+
* through the same guard the session rows use (`paneRecord`), so a leftover
|
|
62
|
+
* record of an earlier conversation never speaks for this one; once the prompt
|
|
63
|
+
* is submitted its UserPromptSubmit makes the turn working again. Past
|
|
64
|
+
* BACKGROUND_STALE_MS after the Stop the pane waits for idle again.
|
|
65
|
+
*/
|
|
66
|
+
export declare function takesPrompt(server: string, pane: Json, session: string | undefined, guards?: PromptGuards, now?: number): Promise<boolean>;
|
|
39
67
|
/** The background shells and monitors a turn still awaits, from its transcript
|
|
40
68
|
* final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
|
|
41
69
|
* count less the tasks that finished since, and by the 2-hour cap; a Stop that
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { briefLabel } from "./launch-brief.js";
|
|
2
|
+
import { screenDialog } from "./pane-status.js";
|
|
2
3
|
import { provider } from "./protocol.js";
|
|
3
4
|
import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
|
|
4
5
|
/**
|
|
@@ -49,6 +50,35 @@ export function recordedBackground(record, finishedTasks, now = Date.now()) {
|
|
|
49
50
|
return undefined;
|
|
50
51
|
return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
|
|
51
52
|
}
|
|
53
|
+
/**
|
|
54
|
+
* Whether the agent in a pane takes a typed prompt now: Herdr reads it idle or
|
|
55
|
+
* done, or it is a Claude session Herdr reads `working` whose own turn record
|
|
56
|
+
* ended with background tasks still running (`recordedBackground`). That is
|
|
57
|
+
* Claude's "Waiting for N background agents to finish": its turn is over and
|
|
58
|
+
* pasted text plus Enter submits at once and starts a turn (seen live, Claude
|
|
59
|
+
* Code 2.1.302), but Herdr keeps it `working` until the last background agent
|
|
60
|
+
* ends. Waiting for idle there held a hand-off or a dispatch-return notice for
|
|
61
|
+
* as long as a lead kept sub-agents running, over an hour. Another working
|
|
62
|
+
* pane, or one blocked, waiting or unknown, does not take one, nor one with a
|
|
63
|
+
* dialog open (`guards`). The record is read only for a working Claude pane,
|
|
64
|
+
* through the same guard the session rows use (`paneRecord`), so a leftover
|
|
65
|
+
* record of an earlier conversation never speaks for this one; once the prompt
|
|
66
|
+
* is submitted its UserPromptSubmit makes the turn working again. Past
|
|
67
|
+
* BACKGROUND_STALE_MS after the Stop the pane waits for idle again.
|
|
68
|
+
*/
|
|
69
|
+
export async function takesPrompt(server, pane, session, guards = {}, now = Date.now()) {
|
|
70
|
+
const status = String(pane.agent_status);
|
|
71
|
+
if (status === "idle" || status === "done")
|
|
72
|
+
return true;
|
|
73
|
+
if (status !== "working" || pane.agent !== "claude")
|
|
74
|
+
return false;
|
|
75
|
+
if (!recordedBackground(await paneRecord(server, pane, session), [], now) || guards.held?.())
|
|
76
|
+
return false;
|
|
77
|
+
if (!guards.screen)
|
|
78
|
+
return true;
|
|
79
|
+
const screen = await guards.screen().catch(() => undefined);
|
|
80
|
+
return screen !== undefined && !screenDialog("claude", screen);
|
|
81
|
+
}
|
|
52
82
|
/** The background shells and monitors a turn still awaits, from its transcript
|
|
53
83
|
* final turn. A recorded ended turn bounds `FinalTurn.awaited` by the Stop's
|
|
54
84
|
* count less the tasks that finished since, and by the 2-hour cap; a Stop that
|
|
@@ -37,6 +37,8 @@ export interface TurnEvent {
|
|
|
37
37
|
session: string;
|
|
38
38
|
/** SessionStart / UserPromptSubmit: the dispatch id the worker's hook named. */
|
|
39
39
|
dispatch?: string;
|
|
40
|
+
/** SessionStart only: how the session started, as the harness names it (Claude: startup, resume, clear, compact). */
|
|
41
|
+
start?: string;
|
|
40
42
|
/** Stop only: the harness's count of in-flight background tasks, when it reports one. */
|
|
41
43
|
background?: number;
|
|
42
44
|
/** Stop only: the harness's last assistant message, when it reports one. */
|