@phren/cli 0.3.54 → 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/git.js +82 -8
- package/dist/bridge/hand-off-queue.d.ts +21 -0
- package/dist/bridge/hand-off-queue.js +31 -2
- package/dist/bridge/projects.js +13 -8
- 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 +14 -13
- package/dist/bridge/session-activity.d.ts +28 -0
- package/dist/bridge/session-activity.js +30 -0
- package/dist/bridge/socket-budget.d.ts +29 -0
- package/dist/bridge/socket-budget.js +62 -0
- package/dist/bridge/turn-records.d.ts +2 -0
- package/dist/bridge/turn-records.js +6 -1
- package/dist/bridge-hook.mjs +2363 -2150
- 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)
|
package/dist/bridge/git.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { readFileSync, realpathSync } from "node:fs";
|
|
2
|
+
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
3
4
|
import { lstat, open, readdir, realpath } from "node:fs/promises";
|
|
4
5
|
import path from "node:path";
|
|
5
6
|
import { BridgeError } from "./protocol.js";
|
|
@@ -325,19 +326,92 @@ export function invalidatePullsForDomain(domain) {
|
|
|
325
326
|
if (JSON.parse(key)[1] === normalized)
|
|
326
327
|
credentialReads.delete(key);
|
|
327
328
|
pullsCache.invalidate(key => key.split("\0")[1] === normalized);
|
|
329
|
+
pullsTargets.clear();
|
|
330
|
+
}
|
|
331
|
+
// Finding a checkout's root, branch and host costs about eight git subprocesses. The answer
|
|
332
|
+
// only changes when HEAD or a git config file does, so it is reused per cwd while those are
|
|
333
|
+
// unchanged, for at most PULLS_TARGET_TTL_MS (which also bounds what a config `include` or a
|
|
334
|
+
// nested repository could hide). Concurrent polls share one lookup.
|
|
335
|
+
const PULLS_TARGET_TTL_MS = 10_000;
|
|
336
|
+
const pullsTargets = new Map();
|
|
337
|
+
function fileStamp(file) {
|
|
338
|
+
try {
|
|
339
|
+
const info = statSync(file);
|
|
340
|
+
return `${info.mtimeMs}:${info.size}:${info.ino}`;
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
return "-";
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
/** A cheap freshness signal: HEAD's text and the stamps of the repository's and the user's git config files. */
|
|
347
|
+
function pullsSignature(root) {
|
|
348
|
+
const parts = [];
|
|
349
|
+
const dotGit = path.join(root, ".git");
|
|
350
|
+
let gitDir = dotGit;
|
|
351
|
+
try {
|
|
352
|
+
const link = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, "utf8"));
|
|
353
|
+
if (link)
|
|
354
|
+
gitDir = path.resolve(root, link[1].trim());
|
|
355
|
+
}
|
|
356
|
+
catch { /* a directory: the main checkout */ }
|
|
357
|
+
let common = gitDir;
|
|
358
|
+
try {
|
|
359
|
+
common = path.resolve(gitDir, readFileSync(path.join(gitDir, "commondir"), "utf8").trim());
|
|
360
|
+
}
|
|
361
|
+
catch { /* gitDir is the common one */ }
|
|
362
|
+
let head;
|
|
363
|
+
try {
|
|
364
|
+
head = readFileSync(path.join(gitDir, "HEAD"), "utf8");
|
|
365
|
+
}
|
|
366
|
+
catch {
|
|
367
|
+
head = "?";
|
|
368
|
+
}
|
|
369
|
+
const home = homedir();
|
|
370
|
+
parts.push(head, fileStamp(path.join(common, "config")), fileStamp(path.join(gitDir, "config.worktree")), fileStamp(process.env.GIT_CONFIG_GLOBAL || path.join(home, ".gitconfig")), fileStamp(path.join(process.env.XDG_CONFIG_HOME || path.join(home, ".config"), "git", "config")));
|
|
371
|
+
return parts.join("\0");
|
|
372
|
+
}
|
|
373
|
+
async function pullsTarget(cwd) {
|
|
374
|
+
const hit = pullsTargets.get(cwd);
|
|
375
|
+
if (hit && Date.now() - hit.at < PULLS_TARGET_TTL_MS) {
|
|
376
|
+
try {
|
|
377
|
+
const { target, signature } = await hit.value;
|
|
378
|
+
if (pullsSignature(target.root) === signature)
|
|
379
|
+
return target;
|
|
380
|
+
}
|
|
381
|
+
catch (error) {
|
|
382
|
+
// A shared lookup that failed fails its own callers; the next call looks again.
|
|
383
|
+
if (pullsTargets.get(cwd) === hit)
|
|
384
|
+
pullsTargets.delete(cwd);
|
|
385
|
+
throw error;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
const entry = { at: Date.now(), value: withIndependentGitReadDeadline(async () => {
|
|
389
|
+
const root = await repository(cwd);
|
|
390
|
+
// Signed before the reads below, so a change made while they run is seen by the next call.
|
|
391
|
+
const signature = pullsSignature(root);
|
|
392
|
+
const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
|
|
393
|
+
const host = await detectHost(root, branch);
|
|
394
|
+
const { apiHost } = await tokenDestination(root, host);
|
|
395
|
+
return { target: { root, branch, host: { ...host, apiHost } }, signature };
|
|
396
|
+
}) };
|
|
397
|
+
pullsTargets.set(cwd, entry);
|
|
398
|
+
if (pullsTargets.size > 64)
|
|
399
|
+
pullsTargets.delete(pullsTargets.keys().next().value);
|
|
400
|
+
try {
|
|
401
|
+
return (await entry.value).target;
|
|
402
|
+
}
|
|
403
|
+
catch (error) {
|
|
404
|
+
if (pullsTargets.get(cwd) === entry)
|
|
405
|
+
pullsTargets.delete(cwd);
|
|
406
|
+
throw error;
|
|
407
|
+
}
|
|
328
408
|
}
|
|
329
409
|
/** Open pull or merge requests and the checked-out branch's own (any state)
|
|
330
410
|
* with its checks, from whichever host the remote is on (git-hosts.ts). A
|
|
331
411
|
* host that cannot answer (a missing CLI, a stubbed provider, an unknown
|
|
332
412
|
* domain) is `{ available: false, reason, message }`, never an error. */
|
|
333
413
|
export async function gitPulls(cwd, retried = false) {
|
|
334
|
-
const { root, branch, host } = await
|
|
335
|
-
const root = await repository(cwd);
|
|
336
|
-
const branch = (await git(root, "branch", "--show-current").catch(() => "")).trim();
|
|
337
|
-
const host = await detectHost(root, branch);
|
|
338
|
-
const { apiHost } = await tokenDestination(root, host);
|
|
339
|
-
return { root, branch, host: { ...host, apiHost } };
|
|
340
|
-
});
|
|
414
|
+
const { root, branch, host } = await pullsTarget(cwd);
|
|
341
415
|
const provider = providerFor(host);
|
|
342
416
|
const credential = await credentialIdentity(host);
|
|
343
417
|
const key = repositoryId(root) + "\0" + (host.domain ?? "").toLowerCase().replace(/\.$/, "") + "\0" + JSON.stringify([branch, host, credential]);
|
|
@@ -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;
|
package/dist/bridge/projects.js
CHANGED
|
@@ -417,7 +417,7 @@ export async function webServers() {
|
|
|
417
417
|
const servers = await serversCache.get("listeners", scanWebServers);
|
|
418
418
|
if (!servers.some(server => server.pid !== undefined) || Date.now() - (scanStarted.get(servers) ?? 0) < LISTENER_TRUST_MS)
|
|
419
419
|
return servers;
|
|
420
|
-
const live = await
|
|
420
|
+
const live = await sharedListeners();
|
|
421
421
|
// The table could not be read (ss timed out, no lsof): ownership cannot be verified, so none is claimed.
|
|
422
422
|
if (!live)
|
|
423
423
|
return servers.map(({ pid: _pid, ...server }) => ({ ...server, unverified: true }));
|
|
@@ -426,6 +426,11 @@ export async function webServers() {
|
|
|
426
426
|
serversCache.invalidate(() => true);
|
|
427
427
|
return kept;
|
|
428
428
|
}
|
|
429
|
+
/** Concurrent ownership checks share one socket-table read; a read is never reused once it has settled. */
|
|
430
|
+
let listenersInFlight;
|
|
431
|
+
function sharedListeners() {
|
|
432
|
+
return listenersInFlight ??= readListeners().catch(() => undefined).finally(() => { listenersInFlight = undefined; });
|
|
433
|
+
}
|
|
429
434
|
/** The key `addListener` files a server under: its host with the port always spelled out (a URL's host drops the default one). */
|
|
430
435
|
export function listenerKey(server) {
|
|
431
436
|
return `${server.origin.includes("[::1]") ? "[::1]" : "127.0.0.1"}:${server.port}`;
|
|
@@ -459,13 +464,13 @@ async function scanWebServers() {
|
|
|
459
464
|
.sort((a, b) => Number(a.port >= EPHEMERAL_PORT) - Number(b.port >= EPHEMERAL_PORT) || a.port - b.port)
|
|
460
465
|
.slice(0, 64);
|
|
461
466
|
const found = [];
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
}
|
|
467
|
+
// Every probe is bounded (1.2 s) and loopback-only, so they all run at once: in groups of eight
|
|
468
|
+
// a handful of listeners that accept and never answer cost 1.2 s per group.
|
|
469
|
+
await Promise.all(candidates.map(async (server) => {
|
|
470
|
+
const name = await probe(server.port, server.origin.includes("[::1]") ? "::1" : "127.0.0.1");
|
|
471
|
+
if (name !== null)
|
|
472
|
+
found.push({ ...server, name });
|
|
473
|
+
}));
|
|
469
474
|
const listing = found.sort((a, b) => a.port - b.port);
|
|
470
475
|
scanStarted.set(listing, started);
|
|
471
476
|
return listing;
|
|
@@ -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
|