@phren/cli 0.3.12 → 0.3.14

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.
Files changed (58) hide show
  1. package/dist/bridge/account-usage.d.ts +124 -0
  2. package/dist/bridge/account-usage.js +258 -0
  3. package/dist/bridge/agent-hooks.d.ts +3 -0
  4. package/dist/bridge/agent-hooks.js +20 -1
  5. package/dist/bridge/codex-app-server.d.ts +6 -0
  6. package/dist/bridge/codex-app-server.js +3 -1
  7. package/dist/bridge/codex-hook-trust.d.ts +27 -0
  8. package/dist/bridge/codex-hook-trust.js +237 -0
  9. package/dist/bridge/codex-servers.d.ts +25 -1
  10. package/dist/bridge/codex-servers.js +78 -14
  11. package/dist/bridge/command.js +4 -1
  12. package/dist/bridge/dispatch-command.js +9 -3
  13. package/dist/bridge/dispatch-returns.d.ts +8 -0
  14. package/dist/bridge/dispatch-returns.js +21 -6
  15. package/dist/bridge/dispatch.d.ts +25 -1
  16. package/dist/bridge/dispatch.js +35 -6
  17. package/dist/bridge/hand-off-queue.d.ts +74 -0
  18. package/dist/bridge/hand-off-queue.js +235 -0
  19. package/dist/bridge/hand-off.d.ts +12 -4
  20. package/dist/bridge/hand-off.js +27 -7
  21. package/dist/bridge/install.d.ts +8 -1
  22. package/dist/bridge/install.js +60 -7
  23. package/dist/bridge/pane-status.d.ts +12 -0
  24. package/dist/bridge/pane-status.js +50 -1
  25. package/dist/bridge/push.d.ts +6 -0
  26. package/dist/bridge/push.js +21 -0
  27. package/dist/bridge/schedule-launch.d.ts +1 -1
  28. package/dist/bridge/schedule-launch.js +5 -1
  29. package/dist/bridge/schedule-watch.d.ts +15 -1
  30. package/dist/bridge/schedule-watch.js +45 -10
  31. package/dist/bridge/server-launch.js +14 -4
  32. package/dist/bridge/server-overview.d.ts +8 -1
  33. package/dist/bridge/server-overview.js +12 -3
  34. package/dist/bridge/server-pane-routes.d.ts +1 -0
  35. package/dist/bridge/server-pane-routes.js +9 -7
  36. package/dist/bridge/server-routes.d.ts +4 -0
  37. package/dist/bridge/server-routes.js +57 -7
  38. package/dist/bridge/server.js +15 -2
  39. package/dist/bridge/session-activity.d.ts +24 -12
  40. package/dist/bridge/session-activity.js +36 -14
  41. package/dist/bridge/stalls.d.ts +22 -0
  42. package/dist/bridge/stalls.js +57 -0
  43. package/dist/bridge/sudo.d.ts +209 -0
  44. package/dist/bridge/sudo.js +501 -0
  45. package/dist/bridge/terminal-tmux.d.ts +12 -0
  46. package/dist/bridge/terminal-tmux.js +79 -4
  47. package/dist/bridge/transcript-claude.d.ts +4 -0
  48. package/dist/bridge/transcript-claude.js +131 -6
  49. package/dist/bridge/usage.d.ts +17 -0
  50. package/dist/bridge/usage.js +37 -3
  51. package/dist/bridge-hook.mjs +24911 -23487
  52. package/dist/cli-registry.js +7 -1
  53. package/dist/modules/registry.js +8 -8
  54. package/dist/test-global-setup.js +7 -0
  55. package/dist/tools/dispatch.js +17 -2
  56. package/package.json +1 -1
  57. package/starter/global/AGENTS.md +4 -0
  58. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -1,8 +1,10 @@
1
+ import { sessionStalls } from "./stalls.js";
1
2
  import { createHash } from "node:crypto";
2
3
  import { z } from "zod";
3
4
  import { logger } from "../logger.js";
4
5
  import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
5
6
  import { briefArrival, briefId } from "./launch-brief.js";
7
+ import { codexServers, LOST_TURN } from "./codex-servers.js";
6
8
  import { findGrant } from "./grants.js";
7
9
  import { findPane, paneIdentity, sharedSnapshot } from "./herdr.js";
8
10
  import { handOff } from "./hand-off.js";
@@ -55,6 +57,8 @@ const defaultReaders = {
55
57
  identity: (server, pane) => paneIdentity(server, pane),
56
58
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
57
59
  turn: paneTurn,
60
+ stall: (target, pane) => sessionStalls.observe(target, pane),
61
+ lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
58
62
  };
59
63
  /** The default readers with the approval reader of the Hook that runs the workers. */
60
64
  export const workerReaders = (approval) => ({ ...defaultReaders, approval });
@@ -129,6 +133,9 @@ export async function workerStates(input, readers = defaultReaders) {
129
133
  // Another conversation in the same pane means the worker is gone.
130
134
  if (expected && current && current !== expected)
131
135
  return { state: "gone" };
136
+ const lost = target.source === "codex" ? readers.lost?.(target.server, String(pane.pane_id), expected ?? current) : undefined;
137
+ if (lost)
138
+ return { state: "done", session: lost.threadId, completed: true, endedAt: lost.at, error: LOST_TURN };
132
139
  const status = String(pane.agent_status);
133
140
  // The record counts only for the conversation this dispatch started, in
134
141
  // the terminal still there, and never for another dispatch's worker.
@@ -136,12 +143,17 @@ export async function workerStates(input, readers = defaultReaders) {
136
143
  const own = record && record.terminal === pane.terminal_id && record.source === target.source
137
144
  && record.session === (expected ?? current ?? record.session)
138
145
  && !(target.dispatch && record.dispatch && target.dispatch !== record.dispatch) ? record : undefined;
139
- if (own)
140
- return fromTurn(own, own.session, status, target.source, readers);
146
+ if (own) {
147
+ const seen = await fromTurn(own, own.session, status, target.source, readers);
148
+ const full = targetSchema.safeParse({ ...target, session: seen.session });
149
+ return { ...seen, ...(full.success && seen.state === "working" ? await readers.stall?.(full.data, { ...pane, agent_status: "working" }) : {}) };
150
+ }
141
151
  const session = expected ?? current;
142
152
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
143
- if ((state !== "idle" && state !== "done") || !session)
144
- return { state, ...(session ? { session } : {}) };
153
+ if ((state !== "idle" && state !== "done") || !session) {
154
+ const full = targetSchema.safeParse({ ...target, session });
155
+ return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane) : {}) };
156
+ }
145
157
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
146
158
  // A finished turn that left background work is still the worker's turn. There is no Stop to time the wait
147
159
  // from, so it carries what a finished turn would and the dispatching Hook bounds the wait (see observe).
@@ -164,6 +176,7 @@ const observationSchema = z.object({
164
176
  session: z.string().max(200).optional(), completed: z.boolean().optional(),
165
177
  reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(), error: z.string().max(500).optional(),
166
178
  hook: z.boolean().optional(), endedAt: z.string().max(40).optional(), background: z.number().int().min(0).max(999).optional(),
179
+ stalled: z.boolean().optional(), stalledSince: z.string().datetime().optional(), stallFor: z.number().nonnegative().optional(),
167
180
  interrupted: z.boolean().optional(), approval: z.unknown().optional(),
168
181
  }).passthrough();
169
182
  /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
@@ -246,7 +259,7 @@ function observeState(receipt, parsed, now) {
246
259
  if (seen.state === "gone")
247
260
  next = "gone";
248
261
  else if (seen.state === "working")
249
- next = "working";
262
+ next = seen.stalled ? "stalled" : "working";
250
263
  else if (seen.state === "blocked")
251
264
  next = "blocked";
252
265
  else if (failed)
@@ -287,6 +300,7 @@ function observeState(receipt, parsed, now) {
287
300
  if (next !== "working") {
288
301
  receipt.returned = { state: next, at, read: false,
289
302
  ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
303
+ ...(next === "stalled" ? { stalledSince: seen.stalledSince, stallFor: seen.stallFor } : {}),
290
304
  ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}),
291
305
  ...((next === "done" || next === "needs-you") && seen.background ? { background: seen.background } : {}),
292
306
  // Nothing still running: say what it waited on.
@@ -297,7 +311,7 @@ function observeState(receipt, parsed, now) {
297
311
  /** One line for the dispatching agent: who returned, how, and where to read it. */
298
312
  export function noticeLine(receipts) {
299
313
  const clean = (value, max) => value.replace(/[\x00-\x1f\x7f]+/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
300
- const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
314
+ const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone", "stalled": "stalled" };
301
315
  const describe = (receipt, room) => {
302
316
  const returned = receipt.returned;
303
317
  const asking = returned.state === "blocked" ? receipt.approval : undefined;
@@ -319,6 +333,7 @@ export function noticeLine(receipts) {
319
333
  export function returnRow(receipt) {
320
334
  const returned = receipt.returned;
321
335
  return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
336
+ ...(returned.state === "stalled" ? { stalled: true, stalledSince: returned.stalledSince, stallFor: returned.stallFor } : {}),
322
337
  state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
323
338
  ...(returned.truncated ? { truncated: true } : {}), ...(returned.error ? { error: returned.error } : {}), ...(returned.question ? { question: returned.question } : {}),
324
339
  ...(returned.background ? { background: returned.background } : {}),
@@ -71,7 +71,7 @@ export declare const originPaneSchema: z.ZodObject<{
71
71
  pane: z.ZodString;
72
72
  }, z.core.$strict>;
73
73
  export type OriginPane = z.infer<typeof originPaneSchema>;
74
- export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "gone"];
74
+ export declare const workerStates: readonly ["working", "done", "needs-you", "failed", "blocked", "stalled", "gone"];
75
75
  export type WorkerState = typeof workerStates[number];
76
76
  declare const receiptSchema: z.ZodObject<{
77
77
  computer: z.ZodUnion<readonly [z.ZodLiteral<"anywhere">, z.ZodString]>;
@@ -202,6 +202,7 @@ declare const receiptSchema: z.ZodObject<{
202
202
  failed: "failed";
203
203
  gone: "gone";
204
204
  "needs-you": "needs-you";
205
+ stalled: "stalled";
205
206
  working: "working";
206
207
  }>;
207
208
  since: z.ZodString;
@@ -217,12 +218,15 @@ declare const receiptSchema: z.ZodObject<{
217
218
  failed: "failed";
218
219
  gone: "gone";
219
220
  "needs-you": "needs-you";
221
+ stalled: "stalled";
220
222
  }>;
221
223
  at: z.ZodString;
222
224
  reply: z.ZodOptional<z.ZodString>;
223
225
  error: z.ZodOptional<z.ZodString>;
224
226
  truncated: z.ZodOptional<z.ZodBoolean>;
225
227
  question: z.ZodOptional<z.ZodString>;
228
+ stalledSince: z.ZodOptional<z.ZodString>;
229
+ stallFor: z.ZodOptional<z.ZodNumber>;
226
230
  turn: z.ZodOptional<z.ZodString>;
227
231
  read: z.ZodBoolean;
228
232
  notifiedAt: z.ZodOptional<z.ZodString>;
@@ -273,6 +277,26 @@ export declare function updateReceipt(receiptID: string, change: (receipt: Recei
273
277
  /** One bounded line for a log or a receipt: a Bridge message, an errno code, or the error's first line. */
274
278
  export declare function failureReason(error: unknown): string;
275
279
  export declare function dispatchStatus(): Promise<Receipt[]>;
280
+ /** `caller` (a conductor's name and host key) asks a peer whether it links this computer back:
281
+ * `outside` is a peer in another set, which a conductor does not dispatch to. */
282
+ type Room = {
283
+ source: string;
284
+ account?: string;
285
+ leftPercent?: number;
286
+ exhausted?: boolean;
287
+ until?: string;
288
+ };
289
+ /** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
290
+ export declare function roomFor(data: {
291
+ harness: string;
292
+ account?: string;
293
+ }, usage: readonly Room[] | undefined): Room | undefined;
294
+ /** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
295
+ * Low quota is not a reason; the owner often wants it used before it resets. */
296
+ export declare function outOfQuota(data: {
297
+ harness: string;
298
+ account?: string;
299
+ }, usage: readonly Room[] | undefined, now?: number): string | undefined;
276
300
  /** What the worker's own hooks reported for a brief that went with its
277
301
  * launch, or undefined when the receiving Hook has no such brief. */
278
302
  export declare function arrivalOf(peer: Pick<DispatchHost, "request">, id: string): Promise<BriefArrival | undefined>;
@@ -41,7 +41,7 @@ export const dispatchSchema = z.object({
41
41
  const remoteTarget = z.union([targetSchema, startingTargetSchema]);
42
42
  /** The local pane that asked for the dispatch, where return notices go. */
43
43
  export const originPaneSchema = z.object({ server: serverName, workspace: id, tab: id, pane: id }).strict();
44
- export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "gone"];
44
+ export const workerStates = ["working", "done", "needs-you", "failed", "blocked", "stalled", "gone"];
45
45
  const timestamp = z.string().datetime();
46
46
  const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
47
47
  id: z.string().uuid(), createdAt: z.string().datetime(), updatedAt: z.string().datetime(),
@@ -62,8 +62,9 @@ const receiptSchema = dispatchSchema.omit({ prompt: true }).extend({
62
62
  waitingSince: timestamp.optional().describe("When the dispatching Hook first saw the worker's finished turn waiting on background tasks; bounds that wait.") }).strict().optional()
63
63
  .describe("The worker pane's last observed state."),
64
64
  returned: z.object({
65
- state: z.enum(["done", "needs-you", "failed", "blocked", "gone"]), at: timestamp,
65
+ state: z.enum(["done", "needs-you", "failed", "blocked", "stalled", "gone"]), at: timestamp,
66
66
  reply: z.string().max(4000).optional(), error: z.string().max(500).optional(), truncated: z.boolean().optional(), question: z.string().max(200).optional(),
67
+ stalledSince: timestamp.optional(), stallFor: z.number().nonnegative().optional(),
67
68
  turn: z.string().regex(/^[a-f0-9]{16}$/).optional(), read: z.boolean(), notifiedAt: timestamp.optional(),
68
69
  background: z.number().int().min(1).max(999).optional().describe("Background tasks the worker left running when it was counted done."),
69
70
  waited: z.number().int().min(1).max(999).optional().describe("The most background tasks the worker waited on before it finished."),
@@ -172,8 +173,6 @@ export async function dispatchStatus() {
172
173
  }
173
174
  return receipts.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
174
175
  }
175
- /** `caller` (a conductor's name and host key) asks a peer whether it links this computer back:
176
- * `outside` is a peer in another set, which a conductor does not dispatch to. */
177
176
  async function capacity(host, caller) {
178
177
  const value = await host.request(caller && !host.local ? `/v1/dispatch/capacity?${caller}` : "/v1/dispatch/capacity");
179
178
  const result = z.object({ product: z.literal("phren-hook"), protocol: z.literal(PROTOCOL), working: z.number().int().nonnegative(),
@@ -181,6 +180,9 @@ async function capacity(host, caller) {
181
180
  // Missing from an older Hook, or when its inventory was not ready in time: unknown, not unavailable.
182
181
  harnesses: z.array(z.object({ source: z.string(), installed: z.boolean(), usable: z.boolean(), reason: z.string().optional(),
183
182
  accounts: z.array(z.object({ id: z.string(), usable: z.boolean(), reason: z.string().optional() }).passthrough()).optional() }).passthrough()).optional(),
183
+ // Missing from an older Hook or a slow read: that computer's quota is unknown, so it is never ruled out by it.
184
+ usage: z.array(z.object({ source: z.string(), account: z.string().optional(), leftPercent: z.number().min(0).max(100).optional(),
185
+ exhausted: z.boolean().optional(), until: z.string().max(40).optional() }).passthrough()).max(64).optional(),
184
186
  knowsCaller: z.boolean().optional() }).parse(value);
185
187
  // This computer places on whichever Herdr server its own Hook runs.
186
188
  if (host.local && !result.servers.includes(host.server) && result.servers[0])
@@ -188,8 +190,25 @@ async function capacity(host, caller) {
188
190
  if (!result.servers.includes(host.server))
189
191
  throw new BridgeError(503, "Herdr is not running on the selected computer. Headless dispatch is not installed yet.");
190
192
  return { working: result.working, computerId: result.computer.id, ...(result.harnesses ? { harnesses: result.harnesses } : {}),
193
+ ...(result.usage ? { usage: result.usage } : {}),
191
194
  ...(caller && result.knowsCaller === false ? { outside: true } : {}) };
192
195
  }
196
+ /** The account this dispatch would run under there, as its capacity probe reports it: Codex's one, or the named Claude home. */
197
+ export function roomFor(data, usage) {
198
+ const account = data.account ?? "default";
199
+ return usage?.find(item => item.source === data.harness && (data.harness !== "claude" || (item.account ?? "default") === account));
200
+ }
201
+ /** Why `anywhere` must not pick a computer for quota: only an account with none left (at 100% or refusing requests).
202
+ * Low quota is not a reason; the owner often wants it used before it resets. */
203
+ export function outOfQuota(data, usage, now = Date.now()) {
204
+ const room = roomFor(data, usage);
205
+ if (!room?.exhausted)
206
+ return undefined;
207
+ const until = room.until ? Date.parse(room.until) : NaN;
208
+ const minutes = Number.isFinite(until) ? Math.max(1, Math.round((until - now) / 60_000)) : undefined;
209
+ const back = minutes === undefined ? "" : minutes >= 1440 ? ` for about ${Math.round(minutes / 1440)} more days` : minutes >= 60 ? ` for about ${Math.round(minutes / 60)} more hours` : ` for about ${minutes} more minutes`;
210
+ return `Its ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} has no quota left${back}.`;
211
+ }
193
212
  /** Why a computer cannot run this dispatch's harness and account, or undefined when it can or cannot yet be told.
194
213
  * `unknown` (no `harnesses`) only counts against a computer when a non-default account was asked for. */
195
214
  function unusable(data, harnesses, strictUnknown) {
@@ -339,7 +358,7 @@ export class DispatchService {
339
358
  let peer;
340
359
  let remoteComputerID;
341
360
  const skipped = [];
342
- let incapable = false;
361
+ let incapable = false, spentSeen = false;
343
362
  if (data.computer === "anywhere") {
344
363
  const available = await Promise.all(peers.map(async (candidate) => {
345
364
  try {
@@ -362,13 +381,23 @@ export class DispatchService {
362
381
  incapable = true;
363
382
  if (reason)
364
383
  skipped.push({ computer: item.peer.name, reason: reason.slice(0, 200) });
365
- return !reason;
384
+ if (reason)
385
+ return false;
386
+ // The one quota rule: never place a worker on an account with none left. Low quota still counts as room.
387
+ const spent = outOfQuota(data, item.usage);
388
+ if (spent) {
389
+ spentSeen = true;
390
+ skipped.push({ computer: item.peer.name, reason: spent });
391
+ }
392
+ return !spent;
366
393
  });
367
394
  skipped.sort((a, b) => a.computer.localeCompare(b.computer));
368
395
  const selected = capable
369
396
  .sort((a, b) => a.working - b.working || a.peer.name.localeCompare(b.peer.name))[0];
370
397
  peer = selected?.peer;
371
398
  remoteComputerID = selected?.computerId;
399
+ if (!peer && spentSeen)
400
+ throw new BridgeError(503, `No connected computer has ${data.harness}${data.harness === "claude" ? ` account ${data.account ?? "default"}` : ""} quota left right now.`, { code: "out_of_quota", skipped });
372
401
  if (!peer)
373
402
  throw new BridgeError(503, incapable ? `No enrolled computer with a running Herdr can run ${data.harness}${data.account ? ` account ${data.account}` : ""}.` : "No enrolled computer with a running Herdr is connected.", skipped.length ? { skipped } : undefined);
374
403
  }
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { type Json, type Target } from "./protocol.js";
3
+ export declare const queuedHandOffSchema: z.ZodObject<{
4
+ target: z.ZodObject<{
5
+ server: z.ZodString;
6
+ workspace: z.ZodString;
7
+ tab: z.ZodString;
8
+ pane: z.ZodString;
9
+ source: z.ZodEnum<{
10
+ claude: "claude";
11
+ codex: "codex";
12
+ copilot: "copilot";
13
+ opencode: "opencode";
14
+ phren: "phren";
15
+ }>;
16
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
17
+ }, z.core.$strip>;
18
+ text: z.ZodString;
19
+ deliveryId: z.ZodOptional<z.ZodString>;
20
+ origin: z.ZodOptional<z.ZodObject<{
21
+ server: z.ZodString;
22
+ workspace: z.ZodString;
23
+ tab: z.ZodString;
24
+ pane: z.ZodString;
25
+ source: z.ZodEnum<{
26
+ claude: "claude";
27
+ codex: "codex";
28
+ copilot: "copilot";
29
+ opencode: "opencode";
30
+ phren: "phren";
31
+ }>;
32
+ session: z.ZodUnion<readonly [z.ZodString, z.ZodString]>;
33
+ }, z.core.$strip>>;
34
+ originComputer: z.ZodOptional<z.ZodString>;
35
+ }, z.core.$strict>;
36
+ export interface QueueOptions {
37
+ validate: (target: Target) => Promise<Json>;
38
+ send: (target: Target, text: string, deliveryId: string, typing: () => Promise<void>) => Promise<Json>;
39
+ notify?: (target: Target, text: string, deliveryId: string, computer: string) => Promise<Json>;
40
+ now?: () => number;
41
+ root?: string;
42
+ }
43
+ /** Settled rows (and notice tombstones) are kept this long, so a late retry of
44
+ * an old delivery id still replays instead of typing again. */
45
+ export declare const HAND_OFF_RETENTION_MS: number;
46
+ /** At most this many rows stay on disk; the oldest settled rows go first. */
47
+ export declare const HAND_OFF_MAX_ROWS = 512;
48
+ /** A durable outbox on the receiving Hook. Persist 'attempting' before input,
49
+ * so a crash in the input/ack gap recovers as uncertain, never as a retry.
50
+ * Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
51
+ * replays instead of typing a second time; a queued or attempting row is never
52
+ * pruned. The sweep runs on enqueue and at most daily from tick(). */
53
+ export declare class HandOffQueue {
54
+ private options;
55
+ private pending;
56
+ private root;
57
+ private now;
58
+ private lastPrune;
59
+ constructor(options: QueueOptions);
60
+ private serial;
61
+ private file;
62
+ private save;
63
+ private read;
64
+ private rows;
65
+ /** Drops settled rows past retention, then the oldest settled rows over the
66
+ * cap (those still owing their sender a notice last). Returns what is kept. */
67
+ private prune;
68
+ private reply;
69
+ enqueue(input: unknown): Promise<Json>;
70
+ status(id: string, target: Target): Promise<Json>;
71
+ private attempt;
72
+ tick(): Promise<void>;
73
+ hasPending(target: Target): Promise<boolean>;
74
+ }
@@ -0,0 +1,235 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { lstat, open, readFile, readdir, unlink } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { z } from "zod";
5
+ import { atomicInPrivateDir, BridgeError, bridgeRoot, targetSchema, computerName } from "./protocol.js";
6
+ import { deliveryIdSchema } from "./prompt-once.js";
7
+ import { agentNotReady } from "./terminal.js";
8
+ export const queuedHandOffSchema = z.object({
9
+ target: targetSchema, text: z.string().min(1).max(32768).refine(t => !/[\x00-\x08\x0b-\x1f\x7f]/.test(t)),
10
+ deliveryId: deliveryIdSchema, origin: targetSchema.optional(), originComputer: computerName.optional(),
11
+ }).strict();
12
+ const rowSchema = queuedHandOffSchema.extend({
13
+ deliveryId: deliveryIdSchema.unwrap(), terminal: z.string().min(1).max(200),
14
+ state: z.enum(["queued", "attempting", "delivered", "uncertain", "failed"]),
15
+ createdAt: z.string().datetime(), updatedAt: z.string().datetime(), error: z.string().max(500).optional(),
16
+ notified: z.boolean().optional(),
17
+ });
18
+ const DAY = 86_400_000;
19
+ /** Settled rows (and notice tombstones) are kept this long, so a late retry of
20
+ * an old delivery id still replays instead of typing again. */
21
+ export const HAND_OFF_RETENTION_MS = 7 * DAY;
22
+ /** At most this many rows stay on disk; the oldest settled rows go first. */
23
+ export const HAND_OFF_MAX_ROWS = 512;
24
+ const settled = (row) => row.state !== "queued" && row.state !== "attempting";
25
+ const sameTarget = (a, b) => ["server", "workspace", "tab", "pane", "source", "session"].every(key => a[key] === b[key]);
26
+ /** A durable outbox on the receiving Hook. Persist 'attempting' before input,
27
+ * so a crash in the input/ack gap recovers as uncertain, never as a retry.
28
+ * Tombstones are retained for HAND_OFF_RETENTION_MS, so a retried delivery id
29
+ * replays instead of typing a second time; a queued or attempting row is never
30
+ * pruned. The sweep runs on enqueue and at most daily from tick(). */
31
+ export class HandOffQueue {
32
+ options;
33
+ pending = Promise.resolve();
34
+ root;
35
+ now;
36
+ lastPrune = -Infinity;
37
+ constructor(options) {
38
+ this.options = options;
39
+ this.root = options.root ?? path.join(bridgeRoot(), "hand-offs");
40
+ this.now = options.now ?? Date.now;
41
+ }
42
+ serial(run) {
43
+ const result = this.pending.then(run);
44
+ this.pending = result.catch(() => { });
45
+ return result;
46
+ }
47
+ file(id) { return path.join(this.root, `${deliveryIdSchema.unwrap().parse(id)}.json`); }
48
+ async save(row) {
49
+ row.updatedAt = new Date(this.now()).toISOString();
50
+ const file = this.file(row.deliveryId);
51
+ await atomicInPrivateDir(file, rowSchema.parse(row));
52
+ // Ensure the renamed entry survives a host crash as well as a service restart.
53
+ // Windows refuses fsync on a read-only handle (EPERM) and on directories.
54
+ if (process.platform !== "win32")
55
+ for (const target of [file, this.root]) {
56
+ const handle = await open(target, "r");
57
+ try {
58
+ await handle.sync();
59
+ }
60
+ finally {
61
+ await handle.close();
62
+ }
63
+ }
64
+ }
65
+ async read(id) {
66
+ const file = this.file(id), info = await lstat(file).catch(error => {
67
+ if (error.code === "ENOENT")
68
+ return undefined;
69
+ throw error;
70
+ });
71
+ if (!info)
72
+ return undefined;
73
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 100_000)
74
+ throw new BridgeError(409, "The hand-off record cannot be read safely.");
75
+ const row = rowSchema.parse(JSON.parse(await readFile(file, "utf8")));
76
+ if (row.state === "attempting") {
77
+ row.state = "uncertain";
78
+ row.error = "The Hook restarted before delivery was confirmed.";
79
+ await this.save(row);
80
+ }
81
+ return row;
82
+ }
83
+ async rows() {
84
+ const names = await readdir(this.root).catch(error => { if (error.code === "ENOENT")
85
+ return []; throw error; });
86
+ const rows = [];
87
+ for (const name of names.sort())
88
+ if (/^[A-Za-z0-9_-]{8,64}\.json$/.test(name)) {
89
+ const row = await this.read(name.slice(0, -5));
90
+ if (row)
91
+ rows.push(row);
92
+ }
93
+ return rows.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.deliveryId.localeCompare(b.deliveryId));
94
+ }
95
+ /** Drops settled rows past retention, then the oldest settled rows over the
96
+ * cap (those still owing their sender a notice last). Returns what is kept. */
97
+ async prune(rows) {
98
+ this.lastPrune = this.now();
99
+ const now = this.now(), drop = new Set();
100
+ for (const row of rows)
101
+ if (settled(row) && now - Date.parse(row.updatedAt) > HAND_OFF_RETENTION_MS)
102
+ drop.add(row.deliveryId);
103
+ let excess = rows.length - drop.size - HAND_OFF_MAX_ROWS;
104
+ if (excess > 0) {
105
+ const owesNotice = (row) => (row.origin && !row.notified ? 1 : 0);
106
+ const candidates = rows.filter(row => settled(row) && !drop.has(row.deliveryId))
107
+ .sort((a, b) => owesNotice(a) - owesNotice(b) || a.updatedAt.localeCompare(b.updatedAt) || a.deliveryId.localeCompare(b.deliveryId));
108
+ for (const row of candidates) {
109
+ if (excess-- <= 0)
110
+ break;
111
+ drop.add(row.deliveryId);
112
+ }
113
+ }
114
+ for (const id of drop)
115
+ await unlink(this.file(id)).catch(error => { if (error.code !== "ENOENT")
116
+ throw error; });
117
+ return drop.size ? rows.filter(row => !drop.has(row.deliveryId)) : rows;
118
+ }
119
+ reply(row) {
120
+ return { ok: row.state === "delivered" || row.state === "queued", delivered: row.state === "delivered", queued: row.state === "queued",
121
+ deliveryId: row.deliveryId, state: row.state, target: row.target,
122
+ ...(row.state === "uncertain" ? { deliveryUncertain: true } : {}), ...(row.error ? { error: row.error } : {}) };
123
+ }
124
+ enqueue(input) {
125
+ return this.serial(async () => {
126
+ const data = queuedHandOffSchema.parse(input), id = data.deliveryId ?? randomUUID().replaceAll("-", "");
127
+ const prior = await this.read(id);
128
+ if (prior) {
129
+ if (!sameTarget(prior.target, data.target) || prior.text !== data.text)
130
+ throw new BridgeError(409, "This message id was already used for a different message.");
131
+ return { ...this.reply(prior), replayed: true };
132
+ }
133
+ const pane = await this.options.validate(data.target);
134
+ if (typeof pane.terminal_id !== "string")
135
+ throw new BridgeError(409, "This agent has no terminal binding.");
136
+ const at = new Date(this.now()).toISOString();
137
+ const row = { ...data, deliveryId: id, terminal: pane.terminal_id, state: "queued", createdAt: at, updatedAt: at };
138
+ await this.save(row);
139
+ // Older queued messages take precedence even if this one arrives at idle.
140
+ const ahead = (await this.prune(await this.rows())).some(other => other.deliveryId !== id && sameTarget(other.target, row.target) && other.state === "queued");
141
+ if (!ahead)
142
+ await this.attempt(row, pane);
143
+ return this.reply(row);
144
+ });
145
+ }
146
+ status(id, target) {
147
+ return this.serial(async () => { const row = await this.read(id); if (!row || !sameTarget(row.target, target))
148
+ throw new BridgeError(404, "No hand-off with this id and target."); return this.reply(row); });
149
+ }
150
+ async attempt(row, pane) {
151
+ try {
152
+ pane ??= await this.options.validate(row.target);
153
+ }
154
+ catch (error) {
155
+ if (error instanceof BridgeError && [404, 409].includes(error.status)) {
156
+ row.state = "failed";
157
+ row.error = error.message.slice(0, 500);
158
+ await this.save(row);
159
+ }
160
+ return; // Offline is not gone and does not discard a queued message.
161
+ }
162
+ if (pane.terminal_id !== row.terminal) {
163
+ row.state = "failed";
164
+ row.error = "The worker's terminal changed before delivery.";
165
+ await this.save(row);
166
+ return;
167
+ }
168
+ if (!["idle", "done"].includes(String(pane.agent_status)))
169
+ return;
170
+ let typed = false;
171
+ try {
172
+ const result = await this.options.send(row.target, row.text, row.deliveryId, async () => {
173
+ row.state = "attempting";
174
+ await this.save(row);
175
+ typed = true;
176
+ });
177
+ row.state = result.delivered === true && result.deliveryUncertain !== true && result.unsubmitted !== true ? "delivered" : "uncertain";
178
+ }
179
+ catch (error) {
180
+ if (agentNotReady(error) || (error instanceof BridgeError && error.details?.code === "hand-off-busy"))
181
+ row.state = "queued"; // Herdr guarantees no input was written.
182
+ else if (!typed) {
183
+ if (!(error instanceof BridgeError) || ![404, 409, 422].includes(error.status))
184
+ return;
185
+ row.state = "failed";
186
+ }
187
+ else
188
+ row.state = "uncertain";
189
+ row.error = (error instanceof Error ? error.message : "Delivery failed.").slice(0, 500);
190
+ }
191
+ if (row.state === "delivered")
192
+ delete row.error;
193
+ await this.save(row);
194
+ }
195
+ tick() {
196
+ return this.serial(async () => {
197
+ let rows = await this.rows();
198
+ if (this.now() - this.lastPrune >= DAY)
199
+ rows = await this.prune(rows);
200
+ const attempted = new Set();
201
+ for (const row of rows)
202
+ if (row.state === "queued") {
203
+ const key = JSON.stringify(row.target);
204
+ if (attempted.has(key))
205
+ continue;
206
+ attempted.add(key);
207
+ await this.attempt(row);
208
+ }
209
+ for (const row of rows)
210
+ if (row.origin && !row.notified && ["delivered", "failed", "uncertain"].includes(row.state)) {
211
+ // A notice is itself an idempotent queued hand-off, without an origin.
212
+ const id = `handoff-notice-${createHash("sha256").update(row.deliveryId).digest("hex").slice(0, 40)}`;
213
+ if (row.originComputer) {
214
+ const result = await this.options.notify?.(row.origin, `Hand-off ${row.deliveryId}: ${row.state}.`, id, row.originComputer).catch(() => undefined);
215
+ if (!result || (!result.queued && !result.delivered && !result.deliveryUncertain))
216
+ continue;
217
+ row.notified = true;
218
+ await this.save(row);
219
+ continue;
220
+ }
221
+ if (!await this.read(id)) {
222
+ const pane = await this.options.validate(row.origin).catch(() => undefined);
223
+ if (!pane || typeof pane.terminal_id !== "string")
224
+ continue;
225
+ const at = new Date(this.now()).toISOString();
226
+ await this.save({ deliveryId: id, target: row.origin, text: `Hand-off ${row.deliveryId}: ${row.state}.`, terminal: pane.terminal_id,
227
+ state: "queued", createdAt: at, updatedAt: at });
228
+ }
229
+ row.notified = true;
230
+ await this.save(row);
231
+ }
232
+ });
233
+ }
234
+ hasPending(target) { return this.serial(async () => (await this.rows()).some(row => sameTarget(row.target, target) && ["queued", "attempting", "uncertain"].includes(row.state))); }
235
+ }
@@ -21,18 +21,23 @@ export declare const handOffSchema: z.ZodObject<{
21
21
  session: z.ZodOptional<z.ZodUnion<readonly [z.ZodString, z.ZodString]>>;
22
22
  project: z.ZodOptional<z.ZodString>;
23
23
  account: z.ZodOptional<z.ZodString>;
24
- text: z.ZodString;
24
+ deliveryId: z.ZodOptional<z.ZodString>;
25
+ status: z.ZodOptional<z.ZodBoolean>;
26
+ text: z.ZodOptional<z.ZodString>;
25
27
  }, z.core.$strict>;
26
28
  export type HandOffInput = z.infer<typeof handOffSchema>;
27
- /** `deliveryId` names this one message on the receiving Hook, which then types
28
- * it at most once however often it is sent (the Hook's own callers retry;
29
- * the MCP tool does not take one). */
29
+ /** A stable delivery id names a message on the receiving Hook. The Hook
30
+ * queues busy targets and retains outcomes across restarts. */
30
31
  export declare function handOff(input: unknown, options?: {
31
32
  deliveryId?: string;
33
+ notifySender?: boolean;
32
34
  }): Promise<{
33
35
  ok: boolean;
34
36
  delivered: boolean;
35
37
  target: Target;
38
+ queued?: boolean;
39
+ deliveryId?: string;
40
+ state?: string;
36
41
  deliveryUncertain?: boolean;
37
42
  unsubmitted?: boolean;
38
43
  label?: string;
@@ -57,6 +62,9 @@ export interface LiveSession {
57
62
  idleFor?: number;
58
63
  /** Set when the main turn ended and this many background tasks keep the session `working`. */
59
64
  backgroundTasks?: number;
65
+ stalled?: boolean;
66
+ stallFor?: number;
67
+ stalledSince?: string;
60
68
  }
61
69
  /** A registered computer this Hook cannot see, with the other names the store
62
70
  * registers it under. */