@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
@@ -23,6 +23,8 @@ import { streamCloseReason } from "./server-stream.js";
23
23
  * `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
24
24
  * gets `{ type: "resources", resources }` after the first overview, then at
25
25
  * `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
26
+ * One that asks with `sudo=1` gets `{ type: "sudo", requests }` after the first
27
+ * overview and whenever the pending sudo requests change.
26
28
  */
27
29
  export const OVERVIEW_TICK_MS = intervalFromEnv("PHREN_OVERVIEW_TICK_MS", 5_000, 250, 60_000);
28
30
  export const OVERVIEW_REFRESH_MS = intervalFromEnv("PHREN_OVERVIEW_REFRESH_MS", 10_000, 1_000, 120_000);
@@ -48,8 +50,12 @@ export function overviewStream(options) {
48
50
  }
49
51
  /** Streams one server's overview until the client closes. Returns the
50
52
  * tick function, for tests that drive time themselves. */
51
- return function stream(client, server, watchApprovals, withResources = false, typedMux = false) {
52
- let closed = false, busy = false, resourcesPending = false, first = true;
53
+ return function stream(client, server, watchApprovals, withResources = false, typedMux = false, withSudo = false) {
54
+ let closed = false, busy = false, resourcesPending = false, first = true, overviewSent = false;
55
+ // Subscribed at once, so the phone counts as able to answer while the first overview builds.
56
+ const unsubscribe = withSudo && options.sudo
57
+ ? options.sudo.subscribe(requests => { if (!closed && overviewSent)
58
+ send(client, { type: "sudo", requests }); }) : undefined;
53
59
  let snapshotKey = "", builtAt = 0, sentKey = "", sentAt = 0, resourcesAt = -Infinity;
54
60
  const collectResources = () => {
55
61
  const at = now();
@@ -88,6 +94,9 @@ export function overviewStream(options) {
88
94
  if (send(client, { type: "overview", ...overview })) {
89
95
  sentKey = rowsKey;
90
96
  sentAt = at;
97
+ if (!overviewSent && unsubscribe)
98
+ send(client, { type: "sudo", requests: options.sudo.list() });
99
+ overviewSent = true;
91
100
  }
92
101
  first = false;
93
102
  return;
@@ -114,7 +123,7 @@ export function overviewStream(options) {
114
123
  }
115
124
  };
116
125
  const timer = setInterval(() => { void tick(); }, tickMs);
117
- const stop = () => { closed = true; clearInterval(timer); };
126
+ const stop = () => { closed = true; clearInterval(timer); unsubscribe?.(); };
118
127
  client.once("close", stop);
119
128
  client.once("error", stop);
120
129
  void tick();
@@ -36,3 +36,4 @@ export declare function herdrWorktreeWorkers(s: Json): WorktreeWorker[];
36
36
  * took, or ten minutes end the watch; a pane asking for input is never answered. */
37
37
  export declare function followQueuedDelivery(agentHooks: AgentHooks, target: Target, terminal: unknown, text: string, intervalMs?: number): void;
38
38
  export declare function paneRoute(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse): Promise<unknown>;
39
+ export declare function paneRouteOnce(ctx: PaneRouteContext, url: URL, data: Json, response: ServerResponse, typing: () => void | Promise<void>): Promise<unknown>;
@@ -240,7 +240,7 @@ async function servedPrompt(target, session, text, typing) {
240
240
  const entry = servedPane(target.server, target.pane);
241
241
  if (!entry)
242
242
  return undefined;
243
- typing();
243
+ await typing();
244
244
  const sent = await sendServedPrompt(entry, session, text);
245
245
  if (!sent.sent)
246
246
  return undefined;
@@ -254,7 +254,7 @@ export async function paneRoute(ctx, url, data, response) {
254
254
  const id = deliveryIdSchema.parse(data.deliveryId);
255
255
  return promptOnce.run(id, promptScope(object(data.target), String(data.text ?? "")), async (typing) => object(await paneRouteOnce(ctx, url, data, response, typing)));
256
256
  }
257
- async function paneRouteOnce(ctx, url, data, response, typing) {
257
+ export async function paneRouteOnce(ctx, url, data, response, typing) {
258
258
  const { agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions } = ctx;
259
259
  let result;
260
260
  if (url.pathname === "/v1/keys" && object(data.target).starting === true) {
@@ -293,7 +293,7 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
293
293
  const served = await servedPrompt(target, undefined, text, typing);
294
294
  if (served)
295
295
  return served;
296
- typing();
296
+ await typing();
297
297
  await promptWithStartupRetry(() => terminalProvider().prompt(target.server, target.pane, text), async () => {
298
298
  const current = await validateStartingTarget(target);
299
299
  if (current.terminal_id !== pane.terminal_id)
@@ -348,6 +348,8 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
348
348
  // is pending there: an approval the Hook holds or saw, or a
349
349
  // status Herdr cannot read. Otherwise the answer keys are the way.
350
350
  const status = String(pane.agent_status);
351
+ if (data.hookQueued === true && !["idle", "done"].includes(status))
352
+ throw new BridgeError(409, "The worker is busy; the hand-off remains queued.", { code: "hand-off-busy" });
351
353
  if (status === "unknown" || (["blocked", "waiting"].includes(status) && (agentHooks.approval(target) || agentHooks.terminalPrompt(target) || agentHooks.servedQuestion(target)))) {
352
354
  throw new BridgeError(409, "This agent needs input in the terminal first.");
353
355
  }
@@ -371,7 +373,7 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
371
373
  if (sideQuestionText(target.source, text) !== undefined) {
372
374
  // Claude's `/btw` runs beside the turn and never reaches the transcript:
373
375
  // the Hook reads its panel and the answer arrives as a side-answer frame.
374
- typing();
376
+ await typing();
375
377
  return { ok: true, delivered: true, sideQuestion: await sideQuestions.ask(target, pane, text) };
376
378
  }
377
379
  if (target.source === "codex" && /^\s*\/model\s+\S/i.test(text))
@@ -383,7 +385,7 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
383
385
  // have reached it is reported uncertain and never retried.
384
386
  const owned = text.trim().startsWith("/") ? undefined : codexServers.forTarget(target);
385
387
  if (owned) {
386
- typing();
388
+ await typing();
387
389
  try {
388
390
  const { turnId } = await codexServers.prompt(owned, text);
389
391
  return { ok: true, delivered: true, turnId };
@@ -399,7 +401,7 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
399
401
  let outcome = await promptWithStartupRetry(async () => {
400
402
  const refused = new AbortController();
401
403
  const expected = agentHooks.expectDelivery(target, text, busy && target.source !== "claude" ? 300 : 1_500, refused.signal);
402
- typing();
404
+ await typing();
403
405
  try {
404
406
  await terminalProvider().prompt(target.server, target.pane, text);
405
407
  }
@@ -420,7 +422,7 @@ async function paneRouteOnce(ctx, url, data, response, typing) {
420
422
  sideQuestions.assertAvailable(target);
421
423
  refuseWorkingSlash(current, text, target.source);
422
424
  busy = String(current.agent_status) === "working";
423
- });
425
+ }, data.hookQueued === true ? 0 : 20_000);
424
426
  // Only Claude confirms plain prompts through its hook, and a slash
425
427
  // command opens a menu that a second Enter would answer.
426
428
  if (outcome === "pending" && target.source === "claude" && !text.trim().startsWith("/")) {
@@ -1,3 +1,4 @@
1
+ import type { HandOffQueue } from "./hand-off-queue.js";
1
2
  import type { IncomingMessage, ServerResponse } from "node:http";
2
3
  import type { FanoutMessages } from "./fanout-messages.js";
3
4
  import type { ModuleSnapshot } from "../modules/runtime.js";
@@ -50,6 +51,7 @@ export interface RouteContext {
50
51
  scheduler?: Scheduler;
51
52
  dispatches?: DispatchService;
52
53
  returns?: DispatchReturns;
54
+ handOffs?: HandOffQueue;
53
55
  agentHooks: AgentHooks;
54
56
  journal: ActivityJournal;
55
57
  tabActivity: TabActivityStore;
@@ -106,6 +108,8 @@ export declare const capabilities: {
106
108
  promptOnce: boolean;
107
109
  promptStatus: boolean;
108
110
  resources: boolean;
111
+ sudo: boolean;
112
+ sudoOutcome: boolean;
109
113
  };
110
114
  export declare function capabilitiesForModules(snapshot: ModuleSnapshot): Record<string, unknown>;
111
115
  export declare function requireRoute(snapshot: ModuleSnapshot, method: string, route: string): void;
@@ -1,6 +1,8 @@
1
+ import { sessionStalls } from "./stalls.js";
1
2
  import { harnessInventoryWithin, launchCheckOff } from "./harnesses.js";
2
3
  import path from "node:path";
3
4
  import { z } from "zod";
5
+ import { sudoAnswer } from "./sudo.js";
4
6
  import { saveCodeNote } from "./code-note.js";
5
7
  import { handOff } from "./hand-off.js";
6
8
  import { BUILTIN_MODULES, disabledHint } from "../modules/registry.js";
@@ -27,7 +29,7 @@ import { bootedSimulators, simulatorAct, simulatorApps, simulatorScreenshot } fr
27
29
  import { childAgentTree, historicalImage, publicChildAgents, refreshTranscript, targetTranscriptPath } from "./transcripts.js";
28
30
  import { listUploads, saveUpload, uploadImage } from "./uploads.js";
29
31
  import { currentModel, currentStep } from "./steps.js";
30
- import { usageForCaller } from "./usage.js";
32
+ import { capacityRoom, usageForCaller } from "./usage.js";
31
33
  import { readFinalTurn } from "./schedule-watch.js";
32
34
  import { healthDetails, listsCaller } from "./health.js";
33
35
  import { defaultPhrenPath } from "../shared.js";
@@ -65,7 +67,7 @@ async function childActivity(source, session) {
65
67
  export const capabilities = { transcript: true, progress: true, images: true, prompt: true, stop: true,
66
68
  terminal: "ssh-pty", shell: "ssh-pty", herdr: true, sessionRename: true, diff: true, webServers: true, webPreview: "ssh-exec", activity: true,
67
69
  approvals: true, questions: false, accountUsage: true, providers: ["codex", "claude", "copilot", "opencode"],
68
- files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true };
70
+ files: true, repositoryFiles: true, subagents: true, sideQuestions: true, dispatch: true, conductorSets: true, approvalPush: "direct-apns", simulators: process.platform === "darwin", code: true, overviewStream: true, speech: true, speechTimestamps: true, speechVoices: true, speechFormats: [...SPEECH_FORMATS], transcribe: true, memoryStore: true, promptOnce: true, promptStatus: true, resources: true, sudo: true, sudoOutcome: true };
69
71
  export function capabilitiesForModules(snapshot) {
70
72
  const allowed = new Set(snapshot.modules.flatMap(module => module.capabilities));
71
73
  const result = Object.fromEntries(Object.entries(capabilities).filter(([name]) => allowed.has(name)));
@@ -164,6 +166,7 @@ export function workspacesReader(ctx) {
164
166
  // turn still has background work, and which dispatch it is. It runs ahead
165
167
  // of the slower reads so the status does not flicker between answers, but
166
168
  // inside the budget, so a stuck disk cannot hold the overview either.
169
+ const awaited = new Map();
167
170
  const records = Promise.all(tabs.map(async ({ group, tab }) => {
168
171
  const agents = agentsByTab.get(JSON.stringify([group.id, tab.id])) ?? [];
169
172
  const session = agents.length === 1 && object(tab.target).session;
@@ -174,7 +177,12 @@ export function workspacesReader(ctx) {
174
177
  ]);
175
178
  if (expired)
176
179
  return;
180
+ if (background)
181
+ awaited.set(tab, background);
177
182
  markBackground(tab, background);
183
+ const target = targetSchema.safeParse(tab.target);
184
+ if (target.success && agents.length === 1)
185
+ Object.assign(tab, await sessionStalls.observe(target.data, { ...agents[0], agent_status: tab.agentStatus }));
178
186
  tab.title = title;
179
187
  }));
180
188
  let nextTab = 0;
@@ -208,8 +216,9 @@ export function workspacesReader(ctx) {
208
216
  // A row finished after the answer left belongs to the next read.
209
217
  if (!expired) {
210
218
  Object.assign(tab, Object.fromEntries(Object.entries(found).filter(([, value]) => value !== undefined)));
211
- // Codex subagents and fanout jobs keep an idle-looking session working too.
212
- markBackground(tab, typeof found.runningChildren === "number" ? found.runningChildren : undefined);
219
+ // Running sub-agents and fan-out jobs keep an idle-looking session
220
+ // working too, on top of the shells its last turn is waiting on.
221
+ markBackground(tab, (awaited.get(tab) ?? 0) + (typeof found.runningChildren === "number" ? found.runningChildren : 0));
213
222
  }
214
223
  }
215
224
  })));
@@ -221,6 +230,17 @@ export function workspacesReader(ctx) {
221
230
  };
222
231
  }
223
232
  /** One read-only GET to every linked peer, each answer or its error by computer name. */
233
+ /** The value, or undefined once `ms` passes or it fails: a probe never waits on a slow reader. */
234
+ async function within(ms, value) {
235
+ let timer;
236
+ const late = new Promise(resolve => { timer = setTimeout(() => resolve(undefined), ms); timer.unref(); });
237
+ try {
238
+ return await Promise.race([value.catch(() => undefined), late]);
239
+ }
240
+ finally {
241
+ clearTimeout(timer);
242
+ }
243
+ }
224
244
  async function fromPeers(route) {
225
245
  const { peers, peerError } = await optionalHookPeers();
226
246
  const answers = await Promise.all(peers.map(async (peer) => {
@@ -315,11 +335,13 @@ export function createRouteHandler(ctx) {
315
335
  const caller = z.object({ name: z.string().max(253).optional(), hostKey: z.string().max(512).optional() })
316
336
  .parse({ name: url.searchParams.get("name") ?? undefined, hostKey: url.searchParams.get("hostKey") ?? undefined });
317
337
  const linksBack = caller.name || caller.hostKey ? { knowsCaller: (await listsCaller(caller)).knowsCaller } : {};
338
+ // Both bounded so a peer's capacity probe never waits on a cold `claude auth status` or usage read; missing means unknown.
339
+ // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
340
+ // `usage` is the room left per Codex and Claude account, so `anywhere` can break a tie by it.
341
+ const [inventory, limits] = await Promise.all([launchCheckOff() ? undefined : harnessInventoryWithin(2_500), within(2_500, accountUsage.limits(true))]);
318
342
  result = { product: "phren-hook", protocol: PROTOCOL, computer: info.computer, servers: live.map(server => server.session), ...linksBack,
319
343
  working: snapshots.reduce((sum, value) => sum + objects(value.panes).filter(pane => pane.agent && pane.agent_status === "working").length, 0),
320
- // Bounded so a peer's capacity probe never waits on a cold `claude auth status`; missing means unknown.
321
- // PHREN_LAUNCH_CHECK=off turns this Hook's availability checks off, including what it advertises to dispatch.
322
- ...(launchCheckOff() ? {} : await harnessInventoryWithin(2_500).then(inventory => inventory ? { harnesses: inventory.harnesses } : {})) };
344
+ ...(inventory ? { harnesses: inventory.harnesses } : {}), ...(limits ? { usage: capacityRoom(limits, Date.now()) } : {}) };
323
345
  break;
324
346
  }
325
347
  case "/v1/speech/voices": {
@@ -428,6 +450,9 @@ export function createRouteHandler(ctx) {
428
450
  case "/v1/push/status":
429
451
  result = agentHooks.push.status;
430
452
  break;
453
+ case "/v1/sudo":
454
+ result = { requests: agentHooks.sudo.list() };
455
+ break;
431
456
  case "/v1/projects/locate": {
432
457
  const candidates = await locateProject(String(url.searchParams.get("project") ?? ""), await journal.recent());
433
458
  for (const candidate of candidates) {
@@ -601,6 +626,13 @@ export function createRouteHandler(ctx) {
601
626
  await streamSpeech(data, response);
602
627
  return;
603
628
  }
629
+ else if (url.pathname === "/v1/hand-off") {
630
+ result = await ctx.handOffs.enqueue(data);
631
+ }
632
+ else if (url.pathname === "/v1/hand-off/status") {
633
+ const body = z.object({ deliveryId: z.string().min(8).max(64), target: targetSchema }).strict().parse(data);
634
+ result = await ctx.handOffs.status(body.deliveryId, body.target);
635
+ }
604
636
  else if (url.pathname === "/v1/dispatch") {
605
637
  // `origin` is the caller's own pane, added by the MCP tool or CLI from Herdr's variables.
606
638
  const { origin, ...brief } = data;
@@ -642,6 +674,24 @@ export function createRouteHandler(ctx) {
642
674
  await agentHooks.push.register(data);
643
675
  result = { ok: true, configured: agentHooks.push.status.configured };
644
676
  }
677
+ else if (url.pathname === "/v1/sudo/answer") {
678
+ // The owner answers from the phone; an agent's call names its pane.
679
+ if (data && typeof data === "object" && "origin" in data)
680
+ throw new BridgeError(403, "Only the owner answers a sudo request, from the phone.");
681
+ let parsed;
682
+ try {
683
+ parsed = sudoAnswer(data);
684
+ }
685
+ catch {
686
+ throw new BridgeError(400, "Send an id and a password, or deny.");
687
+ }
688
+ const answered = agentHooks.sudo.answer(parsed.id, parsed.answer);
689
+ if (!answered)
690
+ throw new BridgeError(404, "This sudo request is no longer pending.");
691
+ // Asked for: whether sudo took the password, so the phone knows to save or forget it.
692
+ const outcome = parsed.outcome ? await answered.outcome : undefined;
693
+ result = { ok: true, ...(outcome ? { outcome } : {}) };
694
+ }
645
695
  else if (url.pathname === "/v1/push/answer") {
646
696
  await agentHooks.answerPush(z.string().uuid().parse(data.binding), data.decision);
647
697
  result = { ok: true };
@@ -1,3 +1,7 @@
1
+ import { handOff } from "./hand-off.js";
2
+ import { sessionStalls } from "./stalls.js";
3
+ import { HandOffQueue } from "./hand-off-queue.js";
4
+ import { paneRouteOnce } from "./server-pane-routes.js";
1
5
  import { FanoutMessages } from "./fanout-messages.js";
2
6
  import { activateModules as moduleSnapshot } from "../modules/runtime.js";
3
7
  import { disabledHint } from "../modules/registry.js";
@@ -96,6 +100,11 @@ export async function serve(version, options = {}) {
96
100
  const modelSwitcher = new ModelSwitcher(agentHooks, modelCatalog);
97
101
  const settingsSwitcher = new SettingsSwitcher(agentHooks);
98
102
  const sideQuestions = new SideQuestions();
103
+ const handOffs = dispatches ? new HandOffQueue({
104
+ validate: target => validateTarget(target, false, true),
105
+ notify: (target, text, deliveryId, computer) => handOff({ computer, target, text, deliveryId }, { notifySender: false }),
106
+ send: async (target, text, deliveryId, typing) => await paneRouteOnce({ agentHooks, modelSwitcher, settingsSwitcher, codexQuestions, sideQuestions }, new URL("http://phren.local/v1/prompt"), { target, text, deliveryId, hookQueued: true }, {}, typing),
107
+ }) : undefined;
99
108
  const contextUsage = new WorkspaceContextUsage();
100
109
  const accountUsage = options.accountUsage ?? new AccountUsageReader();
101
110
  const resources = new ResourceMonitor();
@@ -159,10 +168,11 @@ export async function serve(version, options = {}) {
159
168
  info: () => ({ ...info, capabilities: info.capabilities }),
160
169
  renew: server => agentHooks.overview.renew(server),
161
170
  resources: () => resources.read(),
171
+ sudo: agentHooks.sudo,
162
172
  });
163
173
  const http = createServer(createRouteHandler({ version, modules, info, computerID, scheduleStore, scheduler, dispatches, agentHooks,
164
174
  journal, tabActivity, contextUsage, modelCatalog, modelSwitcher, settingsSwitcher, sideQuestions, accountUsage, resources, codexQuestions, launches, locatedDirectories,
165
- fanoutMessages, canary, streams, returns }));
175
+ fanoutMessages, canary, streams, returns, handOffs }));
166
176
  http.requestTimeout = 20_000;
167
177
  http.headersTimeout = 10_000;
168
178
  http.maxHeadersCount = 32;
@@ -185,7 +195,7 @@ export async function serve(version, options = {}) {
185
195
  ws.clients.delete(oldest);
186
196
  }
187
197
  if (overviewServer !== undefined) {
188
- overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url));
198
+ overview(client, overviewServer, url.searchParams.get("watchApprovals") === "1", url.searchParams.get("resources") === "1", typedMuxRequest(url), url.searchParams.get("sudo") === "1");
189
199
  return;
190
200
  }
191
201
  if (url.pathname === "/v1/speech/transcribe") {
@@ -243,6 +253,8 @@ export async function serve(version, options = {}) {
243
253
  const state = await paneChatState(name, pane, { tokenWhenIdentified: false });
244
254
  const parsed = targetSchema.safeParse({ server: name, workspace: pane.workspace_id, tab: pane.tab_id, pane: pane.pane_id,
245
255
  source: pane.agent, session: state.sessionId });
256
+ if (parsed.success)
257
+ await sessionStalls.observe(parsed.data, pane);
246
258
  return parsed.success ? parsed.data : undefined;
247
259
  });
248
260
  }
@@ -251,6 +263,7 @@ export async function serve(version, options = {}) {
251
263
  await codexServers.sweep(live.map(server => String(server.session))).catch(() => { });
252
264
  // Dispatch returns ride this tick and its shared snapshots. The returns
253
265
  // loop throttles its own peer polls and never holds up activity.
266
+ void handOffs?.tick().catch(() => { });
254
267
  void returns?.tick();
255
268
  })().finally(() => { recording = false; }).catch(() => { });
256
269
  }, 5000);
@@ -6,11 +6,15 @@ import { type TurnRecord } from "./turn-records.js";
6
6
  * title, from the pane's turn record (turn-records.ts) and the dispatch label
7
7
  * (launch-brief.ts):
8
8
  *
9
- * - A Claude turn that ended while background shells or subagents still run
10
- * (its Stop's `background` count, less the tasks its transcript shows
11
- * finishing since, for at most BACKGROUND_STALE_MS), or a Codex session with
12
- * running subagents or fanout jobs, is still working. Herdr reports it idle, so the
13
- * phone listed it under IDLE with a moon badge. The tab keeps
9
+ * - A session whose turn ended while work it started still runs is still
10
+ * working: running sub-agents, teammates, workflow agents and fan-out jobs
11
+ * (its child tree, Claude and Codex alike), and for Claude the background
12
+ * shells and monitors started since the owner's last prompt that are not
13
+ * endless streams (`FinalTurn.awaited`, bounded by its Stop's count less the
14
+ * tasks finished since, for at most BACKGROUND_STALE_MS). A log tail, a
15
+ * watcher or a shell left over from an earlier exchange runs on without
16
+ * anyone waiting for it, so it does not count. Herdr reports such a session
17
+ * idle, so the phone listed it under IDLE with a moon badge. The tab keeps
14
18
  * `agentStatus: "working"` and gains `backgroundTasks`, the count.
15
19
  * - A dispatched worker is named by its dispatch label. Claude and Codex title
16
20
  * a session after its first prompt, which for a brief launch is
@@ -32,21 +36,29 @@ export declare const BACKGROUND_STALE_MS: number;
32
36
  * the Stop's count less those `finishedTasks` (FinalTurn's) says finished
33
37
  * after it. Undefined once none are left or the Stop is BACKGROUND_STALE_MS old. */
34
38
  export declare function recordedBackground(record: TurnRecord | undefined, finishedTasks?: readonly string[], now?: number): number | undefined;
35
- /** `recordedBackground` for a pane, reading the transcript (`readFinalTurn`,
36
- * passed in: schedule-watch imports herdr, which imports this) only when the
37
- * Stop left background work. Only Claude's Stop reports a count. */
39
+ /** The background shells and monitors a pane's ended Claude turn is waiting
40
+ * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
41
+ * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
42
+ * this) only when the Stop left background work; only Claude's Stop reports
43
+ * a count. Sub-agents are not in it: the overview adds its running children.
44
+ * An unreadable transcript counts nothing, since the Stop's count alone
45
+ * cannot tell a build from a log tail. */
38
46
  export declare function liveBackground(record: TurnRecord | undefined, readFinal: (source: "claude", session: string) => Promise<FinalTurn | undefined>, now?: number): Promise<number | undefined>;
39
47
  /**
40
48
  * Marks a tab whose main turn ended but whose background work continues:
41
49
  * an idle or done tab becomes `working` with `backgroundTasks: count`. Called
42
- * again with a second source (the transcript's running children), it keeps the
43
- * larger count, never the sum: Claude's own Stop count already includes its
44
- * subagents. A tab that is working, blocked or waiting on its own is left
45
- * alone, so `backgroundTasks` never sits on a tab with a live turn.
50
+ * again with a fuller count (the awaited shells plus the running children,
51
+ * once the child tree is read), it keeps the larger. A tab that is working,
52
+ * blocked or waiting on its own is left alone, so `backgroundTasks` never
53
+ * sits on a tab with a live turn.
46
54
  */
47
55
  export declare function markBackground(tab: Json, count: number | undefined): void;
48
56
  /** A tab or workspace label worth showing as a name: not empty, not Herdr's bare numbering, not an id. */
49
57
  export declare function meaningfulLabel(value: unknown): string | undefined;
58
+ /** A terminal title without the spinner or status glyphs around it, nor the
59
+ * separator they leave dangling (Codex's "⠸ | phren" before its thread has a
60
+ * title); undefined when nothing else is left. */
61
+ export declare function plainTitle(value: unknown): string | undefined;
50
62
  /** A harness title made from the brief launch's first prompt rather than the work: the prompt itself, the brief path, or "Brief <id>". */
51
63
  export declare function isBriefTitle(title: string): boolean;
52
64
  /**
@@ -6,11 +6,15 @@ import { backgroundLeft, readTurn, turnPhase } from "./turn-records.js";
6
6
  * title, from the pane's turn record (turn-records.ts) and the dispatch label
7
7
  * (launch-brief.ts):
8
8
  *
9
- * - A Claude turn that ended while background shells or subagents still run
10
- * (its Stop's `background` count, less the tasks its transcript shows
11
- * finishing since, for at most BACKGROUND_STALE_MS), or a Codex session with
12
- * running subagents or fanout jobs, is still working. Herdr reports it idle, so the
13
- * phone listed it under IDLE with a moon badge. The tab keeps
9
+ * - A session whose turn ended while work it started still runs is still
10
+ * working: running sub-agents, teammates, workflow agents and fan-out jobs
11
+ * (its child tree, Claude and Codex alike), and for Claude the background
12
+ * shells and monitors started since the owner's last prompt that are not
13
+ * endless streams (`FinalTurn.awaited`, bounded by its Stop's count less the
14
+ * tasks finished since, for at most BACKGROUND_STALE_MS). A log tail, a
15
+ * watcher or a shell left over from an earlier exchange runs on without
16
+ * anyone waiting for it, so it does not count. Herdr reports such a session
17
+ * idle, so the phone listed it under IDLE with a moon badge. The tab keeps
14
18
  * `agentStatus: "working"` and gains `backgroundTasks`, the count.
15
19
  * - A dispatched worker is named by its dispatch label. Claude and Codex title
16
20
  * a session after its first prompt, which for a brief launch is
@@ -45,22 +49,27 @@ export function recordedBackground(record, finishedTasks, now = Date.now()) {
45
49
  return undefined;
46
50
  return backgroundLeft(phase.background, phase.at, finishedTasks) || undefined;
47
51
  }
48
- /** `recordedBackground` for a pane, reading the transcript (`readFinalTurn`,
49
- * passed in: schedule-watch imports herdr, which imports this) only when the
50
- * Stop left background work. Only Claude's Stop reports a count. */
52
+ /** The background shells and monitors a pane's ended Claude turn is waiting
53
+ * on (`FinalTurn.awaited`), at most `recordedBackground`. Reads the transcript
54
+ * (`readFinalTurn`, passed in: schedule-watch imports herdr, which imports
55
+ * this) only when the Stop left background work; only Claude's Stop reports
56
+ * a count. Sub-agents are not in it: the overview adds its running children.
57
+ * An unreadable transcript counts nothing, since the Stop's count alone
58
+ * cannot tell a build from a log tail. */
51
59
  export async function liveBackground(record, readFinal, now = Date.now()) {
52
60
  if (!record || record.source !== "claude" || !recordedBackground(record, [], now))
53
61
  return undefined;
54
62
  const final = await readFinal("claude", record.session).catch(() => undefined);
55
- return recordedBackground(record, final?.finishedTasks, now);
63
+ const left = recordedBackground(record, final?.finishedTasks, now);
64
+ return left && final?.awaited ? Math.min(left, final.awaited) : undefined;
56
65
  }
57
66
  /**
58
67
  * Marks a tab whose main turn ended but whose background work continues:
59
68
  * an idle or done tab becomes `working` with `backgroundTasks: count`. Called
60
- * again with a second source (the transcript's running children), it keeps the
61
- * larger count, never the sum: Claude's own Stop count already includes its
62
- * subagents. A tab that is working, blocked or waiting on its own is left
63
- * alone, so `backgroundTasks` never sits on a tab with a live turn.
69
+ * again with a fuller count (the awaited shells plus the running children,
70
+ * once the child tree is read), it keeps the larger. A tab that is working,
71
+ * blocked or waiting on its own is left alone, so `backgroundTasks` never
72
+ * sits on a tab with a live turn.
64
73
  */
65
74
  export function markBackground(tab, count) {
66
75
  if (!count || count < 1)
@@ -79,6 +88,19 @@ export function meaningfulLabel(value) {
79
88
  const text = value.trim();
80
89
  return text && !/^\d+$/.test(text) && !/^\S*:\S*$/.test(text) && !/^[A-Za-z]{1,2}[_-]?\d+[A-Za-z]?$/.test(text) ? text : undefined;
81
90
  }
91
+ /** Spinner and status glyphs a harness puts around its terminal title while it
92
+ * works: Braille spinner frames (Codex), dingbat stars and checks (Claude's
93
+ * ✳), bullets, circles and hourglasses. */
94
+ const GLYPHS_AROUND = /^[\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606\s]+|[\s\u2800-\u28ff\u2700-\u27bf\u25a0-\u25ff\u23f0-\u23ff\u2022\u00b7\u2219\u22c5\u2605\u2606]+$/gu;
95
+ /** A terminal title without the spinner or status glyphs around it, nor the
96
+ * separator they leave dangling (Codex's "⠸ | phren" before its thread has a
97
+ * title); undefined when nothing else is left. */
98
+ export function plainTitle(value) {
99
+ if (typeof value !== "string")
100
+ return undefined;
101
+ const text = value.replace(GLYPHS_AROUND, "").replace(/^\|\s+|\s+\|$/g, "").replace(GLYPHS_AROUND, "").trim();
102
+ return text || undefined;
103
+ }
82
104
  /** A harness title made from the brief launch's first prompt rather than the work: the prompt itself, the brief path, or "Brief <id>". */
83
105
  export function isBriefTitle(title) {
84
106
  return /^\s*read and follow the brief/i.test(title) || title.includes("/briefs/")
@@ -104,7 +126,7 @@ export function sessionTitle(input) {
104
126
  if (input.dispatchLabel)
105
127
  return input.dispatchLabel;
106
128
  const named = meaningfulLabel(input.tabLabel) ?? meaningfulLabel(input.workspaceLabel);
107
- const title = typeof input.harnessTitle === "string" && input.harnessTitle.trim() ? input.harnessTitle : undefined;
129
+ const title = plainTitle(input.harnessTitle);
108
130
  const chosen = input.dispatched ? named : !title ? undefined : isBriefTitle(title) ? named : title;
109
131
  const label = input.fallbackLabel;
110
132
  const blank = "fallbackLabel" in input && (typeof label !== "string" || !label.trim());
@@ -0,0 +1,22 @@
1
+ import type { Json, Target } from "./protocol.js";
2
+ export interface Stall {
3
+ stalled: true;
4
+ stalledSince: string;
5
+ stallFor: number;
6
+ }
7
+ export interface StallReaders {
8
+ screen: (target: Target) => Promise<string>;
9
+ transcript: (target: Target) => Promise<string>;
10
+ now: () => number;
11
+ threshold: () => number;
12
+ }
13
+ export declare function stallThreshold(): number;
14
+ /** Requires successful observations of both sources. Identity, terminal, work
15
+ * status and either source changing all reset the clock. Missing data is unknown. */
16
+ export declare class StallDetector {
17
+ private readers;
18
+ private entries;
19
+ constructor(readers?: StallReaders);
20
+ observe(target: Target, pane: Json): Promise<Stall | undefined>;
21
+ }
22
+ export declare const sessionStalls: StallDetector;
@@ -0,0 +1,57 @@
1
+ import { createHash } from "node:crypto";
2
+ import { open } from "node:fs/promises";
3
+ import { targetTranscriptPath } from "./transcripts.js";
4
+ import { terminalProvider } from "./terminal.js";
5
+ export function stallThreshold() {
6
+ const value = Number(process.env.PHREN_STALL_MS ?? 300_000);
7
+ return Number.isFinite(value) && value >= 0 ? value : 300_000;
8
+ }
9
+ async function transcriptStamp(target) {
10
+ const file = await open(await targetTranscriptPath(target), "r");
11
+ try {
12
+ const info = await file.stat(), start = Math.max(0, info.size - 8192), buffer = Buffer.alloc(info.size - start);
13
+ await file.read(buffer, 0, buffer.length, start);
14
+ return `${info.size}:${createHash("sha256").update(buffer).digest("hex")}`;
15
+ }
16
+ finally {
17
+ await file.close();
18
+ }
19
+ }
20
+ /** Requires successful observations of both sources. Identity, terminal, work
21
+ * status and either source changing all reset the clock. Missing data is unknown. */
22
+ export class StallDetector {
23
+ readers;
24
+ entries = new Map();
25
+ constructor(readers = {
26
+ screen: target => terminalProvider().readScreen(target.server, target.pane, { scope: "pane", source: "visible", lines: 120, stripAnsi: true, timeoutMs: 1000 }),
27
+ transcript: transcriptStamp, now: Date.now, threshold: stallThreshold,
28
+ }) {
29
+ this.readers = readers;
30
+ }
31
+ async observe(target, pane) {
32
+ const key = JSON.stringify([target.server, target.pane]);
33
+ if (pane.agent_status !== "working" || this.readers.threshold() === 0) {
34
+ this.entries.delete(key);
35
+ return undefined;
36
+ }
37
+ let screen, transcript;
38
+ try {
39
+ [screen, transcript] = await Promise.all([this.readers.screen(target), this.readers.transcript(target)]);
40
+ }
41
+ catch {
42
+ this.entries.delete(key);
43
+ return undefined;
44
+ }
45
+ const signature = createHash("sha256").update(JSON.stringify([target, pane.terminal_id, screen, transcript])).digest("hex");
46
+ const now = this.readers.now(), prior = this.entries.get(key);
47
+ if (!prior || prior.signature !== signature) {
48
+ this.entries.delete(key);
49
+ this.entries.set(key, { signature, since: now });
50
+ }
51
+ while (this.entries.size > 1024)
52
+ this.entries.delete(this.entries.keys().next().value);
53
+ const since = this.entries.get(key).since;
54
+ return now - since >= this.readers.threshold() ? { stalled: true, stalledSince: new Date(since).toISOString(), stallFor: Math.floor((now - since) / 1000) } : undefined;
55
+ }
56
+ }
57
+ export const sessionStalls = new StallDetector();