@phren/cli 0.3.12 → 0.3.13

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 (52) 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-hook-trust.d.ts +27 -0
  6. package/dist/bridge/codex-hook-trust.js +237 -0
  7. package/dist/bridge/command.js +3 -0
  8. package/dist/bridge/dispatch-command.js +9 -3
  9. package/dist/bridge/dispatch-returns.d.ts +5 -0
  10. package/dist/bridge/dispatch-returns.js +16 -6
  11. package/dist/bridge/dispatch.d.ts +25 -1
  12. package/dist/bridge/dispatch.js +35 -6
  13. package/dist/bridge/hand-off-queue.d.ts +74 -0
  14. package/dist/bridge/hand-off-queue.js +235 -0
  15. package/dist/bridge/hand-off.d.ts +12 -4
  16. package/dist/bridge/hand-off.js +27 -7
  17. package/dist/bridge/install.js +16 -2
  18. package/dist/bridge/pane-status.d.ts +12 -0
  19. package/dist/bridge/pane-status.js +50 -1
  20. package/dist/bridge/push.d.ts +6 -0
  21. package/dist/bridge/push.js +21 -0
  22. package/dist/bridge/schedule-launch.d.ts +1 -1
  23. package/dist/bridge/schedule-launch.js +5 -1
  24. package/dist/bridge/schedule-watch.d.ts +15 -1
  25. package/dist/bridge/schedule-watch.js +45 -10
  26. package/dist/bridge/server-launch.js +14 -4
  27. package/dist/bridge/server-overview.d.ts +8 -1
  28. package/dist/bridge/server-overview.js +12 -3
  29. package/dist/bridge/server-pane-routes.d.ts +1 -0
  30. package/dist/bridge/server-pane-routes.js +9 -7
  31. package/dist/bridge/server-routes.d.ts +4 -0
  32. package/dist/bridge/server-routes.js +57 -7
  33. package/dist/bridge/server.js +15 -2
  34. package/dist/bridge/session-activity.d.ts +24 -12
  35. package/dist/bridge/session-activity.js +36 -14
  36. package/dist/bridge/stalls.d.ts +22 -0
  37. package/dist/bridge/stalls.js +57 -0
  38. package/dist/bridge/sudo.d.ts +209 -0
  39. package/dist/bridge/sudo.js +501 -0
  40. package/dist/bridge/terminal-tmux.d.ts +12 -0
  41. package/dist/bridge/terminal-tmux.js +79 -4
  42. package/dist/bridge/transcript-claude.d.ts +4 -0
  43. package/dist/bridge/transcript-claude.js +131 -6
  44. package/dist/bridge/usage.d.ts +17 -0
  45. package/dist/bridge/usage.js +37 -3
  46. package/dist/bridge-hook.mjs +19448 -18102
  47. package/dist/cli-registry.js +7 -1
  48. package/dist/modules/registry.js +8 -8
  49. package/dist/tools/dispatch.js +17 -2
  50. package/package.json +1 -1
  51. package/starter/global/AGENTS.md +4 -0
  52. package/starter/global/skills/conductor/SKILL.md +34 -2
@@ -100,15 +100,35 @@ function turnInterrupted(raw, source) {
100
100
  * `finished` keeps when each task's first final notification was written.
101
101
  * A notification reaching an idle session is written as a queue-operation
102
102
  * row, and may stay there with no new turn to deliver it. */
103
- function backgroundTasks(raw, running, finished) {
104
- const result = object(raw.toolUseResult);
105
- const started = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId
106
- : result.isAsync === true && typeof result.agentId === "string" ? result.agentId
107
- : typeof result.taskId === "string" && result.persistent !== true && typeof result.timeoutMs === "number" ? result.taskId : undefined;
103
+ /** A backgrounded command that runs until killed rather than finishing:
104
+ * following a log, watching files, serving a dev build. Nobody waits on it. */
105
+ export const ENDLESS_COMMAND = /\btail\s+(?:-[a-zA-Z]*[fF][a-zA-Z]*\b|--follow\b)|\bjournalctl\b[^|;&]*\s(?:-[a-zA-Z]*f[a-zA-Z]*\b|--follow\b)|\blog\s+stream\b|\blogcat\b|\bwatch\s|--watch\b|\binotifywait\b[^|;&]*\s-m\b|\bfswatch\b|\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:dev|serve|preview)\b|\bhttp\.server\b|\bsleep\s+infinity\b/;
106
+ function backgroundTasks(raw, running, finished, tail) {
107
+ const result = object(raw.toolUseResult), blocks = objects(object(raw.message).content);
108
+ if (raw.type === "assistant") {
109
+ for (const block of blocks) {
110
+ const input = object(block.input);
111
+ if (block.type === "tool_use" && typeof block.id === "string" && input.run_in_background === true && typeof input.command === "string")
112
+ tail.commands.set(block.id, input.command.slice(0, 2_000));
113
+ }
114
+ }
115
+ const shell = typeof result.backgroundTaskId === "string" ? result.backgroundTaskId : undefined;
116
+ const monitor = typeof result.taskId === "string" && result.persistent !== true && typeof result.timeoutMs === "number" ? result.taskId : undefined;
117
+ const started = shell ?? (result.isAsync === true && typeof result.agentId === "string" ? result.agentId : monitor);
108
118
  if (started)
109
119
  running.add(started);
110
- if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message))
120
+ if (shell) {
121
+ const call = blocks.find(block => block.type === "tool_result")?.tool_use_id;
122
+ const command = typeof call === "string" ? tail.commands.get(call) : undefined;
123
+ if (!command || !ENDLESS_COMMAND.test(command))
124
+ tail.awaited.add(shell);
125
+ }
126
+ else if (monitor)
127
+ tail.awaited.add(monitor);
128
+ if (typeof result.task_id === "string" && typeof result.message === "string" && /\bstopped\b/i.test(result.message)) {
111
129
  running.delete(result.task_id);
130
+ tail.awaited.delete(result.task_id);
131
+ }
112
132
  const content = object(raw.message).content, attachment = object(raw.attachment);
113
133
  const notices = [typeof content === "string" ? content : "", typeof attachment.prompt === "string" ? attachment.prompt : "",
114
134
  raw.type === "queue-operation" && typeof raw.content === "string" ? raw.content : ""];
@@ -118,6 +138,7 @@ function backgroundTasks(raw, running, finished) {
118
138
  if (!id || !/<status>(?:completed|failed|killed|stopped)<\/status>/.test(block))
119
139
  continue;
120
140
  running.delete(id);
141
+ tail.awaited.delete(id);
121
142
  if (!finished.has(id) && typeof raw.timestamp === "string" && !Number.isNaN(Date.parse(raw.timestamp)))
122
143
  finished.set(id, raw.timestamp);
123
144
  }
@@ -126,7 +147,7 @@ function backgroundTasks(raw, running, finished) {
126
147
  * A person's message after the reply opens a new turn, so it clears both. */
127
148
  export function finalTurnFromLines(lines, source) {
128
149
  let completed = false, lastAssistant, error, interrupted = false;
129
- const running = new Set(), finished = new Map();
150
+ const running = new Set(), finished = new Map(), tail = { commands: new Map(), awaited: new Set() };
130
151
  for (const line of lines) {
131
152
  if (!line.trim())
132
153
  continue;
@@ -138,8 +159,13 @@ export function finalTurnFromLines(lines, source) {
138
159
  continue;
139
160
  }
140
161
  const payload = object(raw.payload);
141
- if (source === "claude")
142
- backgroundTasks(raw, running, finished);
162
+ if (source === "claude") {
163
+ backgroundTasks(raw, running, finished, tail);
164
+ // The owner moving on leaves what earlier turns started behind: a
165
+ // shell still running from then is a leftover, not work in flight.
166
+ if (ownerPrompt(raw))
167
+ tail.awaited.clear();
168
+ }
143
169
  if (turnInterrupted(raw, source)) {
144
170
  interrupted = true;
145
171
  completed = false;
@@ -169,7 +195,16 @@ export function finalTurnFromLines(lines, source) {
169
195
  }
170
196
  return { completed, ...(lastAssistant ? { lastAssistant } : {}), ...(completed && error ? { error } : {}),
171
197
  ...(interrupted ? { interrupted: true } : {}), ...(completed && running.size ? { background: running.size } : {}),
172
- ...(finished.size ? { finishedTasks: [...finished.values()] } : {}) };
198
+ ...(finished.size ? { finishedTasks: [...finished.values()] } : {}), ...(tail.awaited.size ? { awaited: tail.awaited.size } : {}) };
199
+ }
200
+ /** A prompt the owner (or a dispatcher) typed, not a task's notification or
201
+ * a teammate's message waking the session. */
202
+ function ownerPrompt(raw) {
203
+ const content = object(raw.message).content;
204
+ if (raw.type !== "user" || raw.isMeta || typeof content !== "string")
205
+ return false;
206
+ const text = content.trimStart();
207
+ return !text.startsWith("<task-notification>") && !text.startsWith("<teammate-message");
173
208
  }
174
209
  /** The final turn of a conversation, read from the tail of its transcript. */
175
210
  export async function readFinalTurn(source, sessionId) {
@@ -4,9 +4,11 @@ import { fileURLToPath } from "node:url";
4
4
  import { z } from "zod";
5
5
  import { homeDir } from "../home-paths.js";
6
6
  import { agentNames, findPane, isConductorName, paneChatState, paneIdentity, servers, snapshot } from "./herdr.js";
7
- import { agentNotReady, terminalName, terminalProvider } from "./terminal.js";
7
+ import { agentNotReady, terminalKind, terminalName, terminalProvider } from "./terminal.js";
8
+ import { tmuxScroll } from "./terminal-tmux.js";
8
9
  import { intervalFromEnv } from "./limits.js";
9
10
  import { createLaunchWorktree, launchWorktreeSchema } from "./launch-worktree.js";
11
+ import { askpassEnv } from "./sudo.js";
10
12
  import { briefArgs, DISPATCH_ID_ENV, launchBriefSchema, launchesWithBrief, recordBriefArrival, writeLaunchBrief } from "./launch-brief.js";
11
13
  import { prepareServedLaunch, registerServedPane, sendServedBrief } from "./opencode-panes.js";
12
14
  import { groupConductor } from "./conductor-group.js";
@@ -292,7 +294,8 @@ export async function launchSession(server, data, options = {}) {
292
294
  args.push(...served.args);
293
295
  const briefFile = brief && (launchesWithBrief(kind) || structured || served) ? await writeLaunchBrief(brief, Date.now(), label) : undefined;
294
296
  const briefLaunch = brief && briefFile && launchesWithBrief(kind) ? briefArgs(kind, briefFile) : undefined;
295
- const variables = { ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
297
+ // sudo -A in the new agent asks the phone for the password (sudo.ts).
298
+ const variables = { ...askpassEnv(), ...(brief ? { [DISPATCH_ID_ENV]: brief.id } : {}), ...served?.env, ...(home ? claudeLaunchEnv(home) : {}) };
296
299
  const env = Object.keys(variables).length ? variables : undefined;
297
300
  if (workspace && !objects(before.workspaces).some(w => w.workspace_id === workspace))
298
301
  throw new BridgeError(409, "The workspace changed.");
@@ -411,12 +414,19 @@ export async function launchSession(server, data, options = {}) {
411
414
  ...(worktree ? { worktree: { path: worktree.path, branch: worktree.branch } } : {}) };
412
415
  }
413
416
  export async function workspaceAction(server, operation, data) {
414
- if (!["focus", "rename", "create", "close"].includes(operation))
417
+ if (!["focus", "rename", "create", "close", "scroll"].includes(operation))
415
418
  throw new BridgeError(400, "Unsupported Herdr action.");
416
- const s = await snapshot(server);
417
419
  const workspace = typeof data.workspaceId === "string" ? data.workspaceId : undefined;
418
420
  const tab = typeof data.tabId === "string" ? data.tabId : undefined;
419
421
  const pane = typeof data.paneId === "string" ? data.paneId : undefined;
422
+ if (operation === "scroll") {
423
+ // Every swipe step lands here, so it skips the snapshot: tmux itself
424
+ // refuses a pane that is gone.
425
+ if (terminalKind(server) !== "tmux")
426
+ throw new BridgeError(400, "Herdr scrolls in the terminal itself.");
427
+ return { ok: true, ...await tmuxScroll(server, pane, z.number().int().min(-200).max(200).parse(data.lines)) };
428
+ }
429
+ const s = await snapshot(server);
420
430
  if (workspace && !objects(s.workspaces).some(w => w.workspace_id === workspace))
421
431
  throw new BridgeError(409, "The workspace changed.");
422
432
  if (tab && !objects(s.tabs).some(t => t.tab_id === tab && (!workspace || t.workspace_id === workspace)))
@@ -17,6 +17,8 @@ import type { WorkspacesReader } from "./server-routes.js";
17
17
  * `{ type: "heartbeat", phren }`. A phone that asks with `resources=1` also
18
18
  * gets `{ type: "resources", resources }` after the first overview, then at
19
19
  * `OVERVIEW_RESOURCES_MS` intervals (an older phone never asks, so never meets it).
20
+ * One that asks with `sudo=1` gets `{ type: "sudo", requests }` after the first
21
+ * overview and whenever the pending sudo requests change.
20
22
  */
21
23
  export declare const OVERVIEW_TICK_MS: number;
22
24
  export declare const OVERVIEW_REFRESH_MS: number;
@@ -28,6 +30,11 @@ export interface OverviewStreamOptions {
28
30
  info: () => Json;
29
31
  /** Renews the approval watch lease `watchApprovals=1` asks for. */
30
32
  renew: (server: string) => void;
33
+ /** Pending sudo requests (`GET /v1/sudo`), for phones that ask with `sudo=1`. */
34
+ sudo?: {
35
+ list(): unknown[];
36
+ subscribe(listener: (requests: unknown[]) => void): () => void;
37
+ };
31
38
  /** This computer's resources (`GET /v1/resources`), for phones that ask. */
32
39
  resources?: () => Promise<unknown>;
33
40
  snapshot?: (server: string, maxAgeMs: number) => Promise<Json>;
@@ -45,7 +52,7 @@ export interface OverviewClient {
45
52
  close(code?: number, reason?: string): void;
46
53
  once(event: "close" | "error", listener: () => void): unknown;
47
54
  }
48
- export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean) => {
55
+ export declare function overviewStream(options: OverviewStreamOptions): (client: OverviewClient, server: string, watchApprovals: boolean, withResources?: boolean, typedMux?: boolean, withSudo?: boolean) => {
49
56
  tick: () => Promise<void>;
50
57
  stop: () => void;
51
58
  };
@@ -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
  /**