@phren/cli 0.3.16 → 0.3.18

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 (46) hide show
  1. package/dist/bridge/agent-hooks.d.ts +10 -0
  2. package/dist/bridge/agent-hooks.js +49 -10
  3. package/dist/bridge/claude-suggestion.d.ts +8 -0
  4. package/dist/bridge/claude-suggestion.js +71 -0
  5. package/dist/bridge/dispatch-returns.d.ts +6 -3
  6. package/dist/bridge/dispatch-returns.js +29 -17
  7. package/dist/bridge/job-registry.d.ts +144 -0
  8. package/dist/bridge/job-registry.js +247 -0
  9. package/dist/bridge/opencode-permissions.d.ts +17 -0
  10. package/dist/bridge/opencode-permissions.js +96 -0
  11. package/dist/bridge/permission-mode.d.ts +48 -0
  12. package/dist/bridge/permission-mode.js +144 -0
  13. package/dist/bridge/protocol.d.ts +4 -0
  14. package/dist/bridge/protocol.js +3 -0
  15. package/dist/bridge/resources.d.ts +38 -5
  16. package/dist/bridge/resources.js +110 -19
  17. package/dist/bridge/server-launch.js +8 -0
  18. package/dist/bridge/server-pane-routes.d.ts +2 -0
  19. package/dist/bridge/server-pane-routes.js +12 -2
  20. package/dist/bridge/server-routes.d.ts +3 -1
  21. package/dist/bridge/server-routes.js +8 -6
  22. package/dist/bridge/server-stream.js +14 -2
  23. package/dist/bridge/server.js +4 -2
  24. package/dist/bridge/session-activity.d.ts +13 -0
  25. package/dist/bridge/session-activity.js +27 -2
  26. package/dist/bridge/settings-switch.d.ts +19 -7
  27. package/dist/bridge/settings-switch.js +21 -29
  28. package/dist/bridge/speech.d.ts +6 -4
  29. package/dist/bridge/speech.js +6 -4
  30. package/dist/bridge/terminal-tmux.d.ts +4 -2
  31. package/dist/bridge/terminal-tmux.js +13 -7
  32. package/dist/bridge/transcript-claude.d.ts +9 -1
  33. package/dist/bridge/transcript-claude.js +50 -1
  34. package/dist/bridge/transcript-codex.js +23 -3
  35. package/dist/bridge/transcripts.d.ts +5 -1
  36. package/dist/bridge/transcripts.js +13 -3
  37. package/dist/bridge-hook.mjs +1169 -546
  38. package/dist/computers/command.js +2 -1
  39. package/dist/fanout/opencode-serve.js +3 -2
  40. package/dist/hooks.d.ts +3 -0
  41. package/dist/hooks.js +41 -6
  42. package/dist/init/setup.js +6 -3
  43. package/dist/modules/registry.js +2 -2
  44. package/dist/tools/dispatch.js +3 -2
  45. package/package.json +1 -1
  46. package/plugins/opencode/phren-transcript.js +4 -4
@@ -72,6 +72,16 @@ export interface ForwardedApproval {
72
72
  /** A conductor `dispatch` or `hand_off` permission ask the Hook can answer
73
73
  * itself under a standing grant, or offer the phone two grant-writing answers. */
74
74
  export declare function conductorCall(tool: string, input: unknown): Pending["conductor"] | undefined;
75
+ /** The decisions an OpenCode permission ask offers the phone. OpenCode's
76
+ * `always` covers the current session, so both grant answers reply `always`;
77
+ * `allow-everywhere` additionally writes an allow rule into the user's
78
+ * OpenCode config. Advertised as the approval card's `options`, the same
79
+ * shape the phone already renders for a provider-supplied option list. */
80
+ export declare const OPENCODE_APPROVAL_OPTIONS: Json[];
81
+ /** The OpenCode permission reply a card decision maps to: both grant scopes
82
+ * are `always`, a plain approve is `once`, a deny is `reject`. Undefined for
83
+ * anything else. */
84
+ export declare function opencodePermissionReply(decision: unknown): "once" | "always" | "reject" | undefined;
75
85
  export type DeliveryOutcome = "delivered" | "blocked" | "pending";
76
86
  /** A phone message the Hook answered as delivered or queued, kept under the
77
87
  * phone's delivery id so the phone can ask what became of it by that id.
@@ -25,6 +25,7 @@ import { intervalFromEnv } from "./limits.js";
25
25
  import { answerClaudeQuestionDialog, claudeQuestionDialog } from "./claude-question-dialog.js";
26
26
  import { answeredQuestionInput, numberedDialog, opencodePermissionDialog, passwordLine, permissionPrompt, questionChoice, terminalChoice, terminalQuestions, visibleTerminalChoice } from "./terminal-choice.js";
27
27
  import { directoryNames, opencodeApprovalFile, opencodeRequest, readOpencodeRequest } from "./opencode-approvals.js";
28
+ import { allowOpencodeToolEverywhere } from "./opencode-permissions.js";
28
29
  import { ApprovalWatchLeases, bindingPath, localSocket, PushBindingStore } from "./agent-hook-stores.js";
29
30
  import { notePaneTranscript, paneAccountKey } from "./pane-accounts.js";
30
31
  import { eventStatus, notePaneStatus, settleBlockedPane } from "./pane-status.js";
@@ -107,6 +108,29 @@ export function conductorCall(tool, input) {
107
108
  const computer = typeof fields.computer === "string" ? fields.computer : undefined;
108
109
  return { action, ...(project ? { project } : {}), ...(computer ? { computer } : {}) };
109
110
  }
111
+ /** The decisions an OpenCode permission ask offers the phone. OpenCode's
112
+ * `always` covers the current session, so both grant answers reply `always`;
113
+ * `allow-everywhere` additionally writes an allow rule into the user's
114
+ * OpenCode config. Advertised as the approval card's `options`, the same
115
+ * shape the phone already renders for a provider-supplied option list. */
116
+ export const OPENCODE_APPROVAL_OPTIONS = [
117
+ { label: "Allow once", decision: "approve" },
118
+ { label: "Allow for this project", decision: "allow-project" },
119
+ { label: "Allow everywhere", decision: "allow-everywhere" },
120
+ { label: "Deny", decision: "deny" },
121
+ ];
122
+ /** The OpenCode permission reply a card decision maps to: both grant scopes
123
+ * are `always`, a plain approve is `once`, a deny is `reject`. Undefined for
124
+ * anything else. */
125
+ export function opencodePermissionReply(decision) {
126
+ if (decision === "approve")
127
+ return "once";
128
+ if (decision === "deny")
129
+ return "reject";
130
+ if (decision === "allow-project" || decision === "allow-everywhere")
131
+ return "always";
132
+ return undefined;
133
+ }
110
134
  /** As long as a typed prompt's own record guards it (`expectDelivery`). */
111
135
  const TRACK_MS = 600_000;
112
136
  /** What the agent hands its UserPromptSubmit hook is the terminal's pasted
@@ -419,12 +443,17 @@ export class AgentHooks {
419
443
  }
420
444
  /** Answers a served pane's permission ask over its own API. */
421
445
  async answerServed(id, held, decision) {
422
- if (!["approve", "deny"].includes(String(decision)))
446
+ const reply = opencodePermissionReply(decision);
447
+ if (!reply)
423
448
  throw new BridgeError(400, "The approval answer is not valid.");
424
449
  const served = held.served;
425
450
  const client = this.servedClient(served.server, served.pane);
451
+ // Everywhere writes the user's config before the pane is unblocked, so a
452
+ // failed write leaves the ask answerable rather than half-answered.
453
+ if (decision === "allow-everywhere")
454
+ await allowOpencodeToolEverywhere(held.request.type);
426
455
  try {
427
- await client.replyPermission(id, decision === "approve" ? "once" : "reject");
456
+ await client.replyPermission(id, reply);
428
457
  }
429
458
  catch {
430
459
  throw new BridgeError(409, "This approval is no longer pending.");
@@ -1052,16 +1081,16 @@ export class AgentHooks {
1052
1081
  // A fan-out worker this conversation started is waiting on the owner.
1053
1082
  const worker = this.fanoutHeld(target)[0];
1054
1083
  return worker?.fanout ? { actionId: worker.fanout.actionId, toolName: worker.request.type, title: worker.request.title,
1055
- message: worker.request.message, request: worker.requestLine, expiresAt: worker.request.expiresAt } : undefined;
1084
+ message: worker.request.message, request: worker.requestLine, expiresAt: worker.request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS } : undefined;
1056
1085
  }
1057
1086
  opencodeApproval(target) {
1058
1087
  const held = [...this.opencode.values()].find(value => !value.fanout && JSON.stringify(value.target) === JSON.stringify(target));
1059
1088
  if (held)
1060
- return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt };
1089
+ return { actionId: held.request.id, toolName: held.request.type, title: held.request.title, message: held.request.message, request: held.requestLine, expiresAt: held.request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS };
1061
1090
  const request = opencodeRequest(target.session);
1062
1091
  return request ? { actionId: request.id, toolName: request.type, title: request.title, message: request.message,
1063
1092
  request: approvalSummary({ tool: String(request.type ?? ""), input: request, message: typeof request.message === "string" ? request.message : undefined }).request,
1064
- expiresAt: request.expiresAt } : undefined;
1093
+ expiresAt: request.expiresAt, options: OPENCODE_APPROVAL_OPTIONS } : undefined;
1065
1094
  }
1066
1095
  /** Live fan-out worker asks shown on this parent conversation, oldest first. */
1067
1096
  fanoutHeld(target) {
@@ -1116,12 +1145,16 @@ export class AgentHooks {
1116
1145
  }
1117
1146
  /** Hands the owner's answer to the fan-out launcher waiting on the worker's session. */
1118
1147
  async answerFanout(id, held, decision) {
1119
- if (!["approve", "deny"].includes(String(decision)))
1148
+ const reply = opencodePermissionReply(decision);
1149
+ if (!reply)
1120
1150
  throw new BridgeError(400, "The approval answer is not valid.");
1121
1151
  const file = held.fanout && opencodeApprovalFile(held.fanout.session, "answer");
1122
1152
  if (!held.fanout || !file || opencodeRequest(held.fanout.session)?.id !== id)
1123
1153
  throw new BridgeError(409, "This approval is no longer pending.");
1124
- await atomicInPrivateDir(file, JSON.stringify({ id, decision }));
1154
+ if (decision === "allow-everywhere")
1155
+ await allowOpencodeToolEverywhere(held.request.type);
1156
+ // The launcher reads the same approve/deny/always vocabulary the plugin does.
1157
+ await atomicInPrivateDir(file, JSON.stringify({ id, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
1125
1158
  this.opencode.delete(id);
1126
1159
  this.pushBindings.dropAction(id);
1127
1160
  }
@@ -1156,15 +1189,21 @@ export class AgentHooks {
1156
1189
  return;
1157
1190
  }
1158
1191
  if (target.source === "opencode") {
1159
- if (!["approve", "deny"].includes(String(decision)))
1192
+ const reply = opencodePermissionReply(decision);
1193
+ if (!reply)
1160
1194
  throw new BridgeError(400, "The approval answer is not valid.");
1161
1195
  const file = opencodeApprovalFile(target.session, "answer");
1162
1196
  if (!file)
1163
1197
  throw new BridgeError(400, "Invalid conversation identity.");
1164
1198
  await validateTarget(target);
1165
- if (opencodeRequest(target.session)?.id !== id)
1199
+ const request = opencodeRequest(target.session);
1200
+ if (request?.id !== id)
1166
1201
  throw new BridgeError(409, "This approval is no longer pending.");
1167
- await atomicInPrivateDir(file, JSON.stringify({ id, decision }));
1202
+ // Everywhere also writes the user's OpenCode config, before the plugin
1203
+ // is unblocked so a failed write leaves the ask answerable.
1204
+ if (decision === "allow-everywhere")
1205
+ await allowOpencodeToolEverywhere(request.type);
1206
+ await atomicInPrivateDir(file, JSON.stringify({ id, decision: decision === "approve" || decision === "deny" ? decision : "always" }));
1168
1207
  this.opencode.delete(id);
1169
1208
  this.pushBindings.dropAction(id);
1170
1209
  return;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The suggestion on a Claude screen read with its styles, or undefined when
3
+ * there is none. Only an input line whose every character after the prompt is
4
+ * dim counts: once the owner types, their text is drawn plain. A narrow pane
5
+ * cuts a long suggestion with "…" instead of wrapping it; a cut one is not
6
+ * offered, since sending half a sentence would be worse than nothing.
7
+ */
8
+ export declare function claudeSuggestion(screen: string): string | undefined;
@@ -0,0 +1,71 @@
1
+ // Claude Code's predicted next prompt: after a turn it draws a short guess at
2
+ // what the owner will type next as dim text in its empty input box. The screen
3
+ // is the only place a live pane shows it. Claude generates it in a side request
4
+ // that skips the transcript, keeps it in memory only (no config or state file),
5
+ // and no hook event carries it; `claude -p --prompt-suggestions` streams it as
6
+ // a `prompt_suggestion` message, but only in print mode, never in a pane.
7
+ import { stripTerminal } from "../terminal-text.js";
8
+ const MAX_SUGGESTION = 500;
9
+ // The input box sits between two rules; the upper one can carry the session
10
+ // title ("───── Claude sesh ─").
11
+ const rule = (line) => /^[─━═]{3,}/.test(line.trim());
12
+ // Dim text Claude also draws in the empty input that is not a prediction: the
13
+ // first-turn example, the queued-message hints and a teammate's name.
14
+ const PLACEHOLDERS = [/^Try ".*"$/, /^Press (?:up|Enter) to /, /^Message @.*…$/];
15
+ /**
16
+ * The suggestion on a Claude screen read with its styles, or undefined when
17
+ * there is none. Only an input line whose every character after the prompt is
18
+ * dim counts: once the owner types, their text is drawn plain. A narrow pane
19
+ * cuts a long suggestion with "…" instead of wrapping it; a cut one is not
20
+ * offered, since sending half a sentence would be worse than nothing.
21
+ */
22
+ export function claudeSuggestion(screen) {
23
+ const lines = screen.split("\n").map(line => line.replace(/\r$/, ""));
24
+ for (let index = lines.length - 2; index > 0; index--) {
25
+ const plain = stripTerminal(lines[index]);
26
+ if (!/^\s*❯/.test(plain))
27
+ continue;
28
+ // Only the live input box: a sent prompt in the history has no rules around it.
29
+ if (!rule(stripTerminal(lines[index - 1])) || !rule(stripTerminal(lines[index + 1])))
30
+ return undefined;
31
+ const text = dimText(lines[index]);
32
+ if (!text || text.endsWith("…") || text.length > MAX_SUGGESTION || PLACEHOLDERS.some(pattern => pattern.test(text)))
33
+ return undefined;
34
+ return text;
35
+ }
36
+ return undefined;
37
+ }
38
+ /** The text after the prompt glyph when all of it is dim (SGR 2), else "". */
39
+ function dimText(line) {
40
+ let dim = false, prompt = false, text = "";
41
+ for (const token of line.match(/\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|[^\x1b]/gu) ?? []) {
42
+ if (token.startsWith("\x1b")) {
43
+ if (!token.startsWith("\x1b[") || !token.endsWith("m"))
44
+ continue;
45
+ const codes = (token.slice(2, -1) || "0").split(/[;:]/).map(Number);
46
+ for (let i = 0; i < codes.length; i++) {
47
+ const code = codes[i];
48
+ // Extended colors carry their own numbers: 38;5;2 is not dim.
49
+ if (code === 38 || code === 48 || code === 58) {
50
+ i += codes[i + 1] === 5 ? 2 : codes[i + 1] === 2 ? 4 : 0;
51
+ continue;
52
+ }
53
+ if (code === 0 || code === 22)
54
+ dim = false;
55
+ else if (code === 2)
56
+ dim = true;
57
+ }
58
+ }
59
+ else if (!prompt) {
60
+ if (token === "❯")
61
+ prompt = true;
62
+ }
63
+ else if (!token.trim())
64
+ text += " ";
65
+ else if (!dim)
66
+ return "";
67
+ else
68
+ text += token;
69
+ }
70
+ return text.replace(/\s+/g, " ").trim();
71
+ }
@@ -6,7 +6,7 @@ import { type BriefArrival } from "./launch-brief.js";
6
6
  import { type LostTurn } from "./codex-servers.js";
7
7
  import { findGrant } from "./grants.js";
8
8
  import { peerRequest, type HookPeer } from "./peers.js";
9
- import { type Json, type Provider, type Target } from "./protocol.js";
9
+ import { type ApprovalDecision, type Json, type Provider, type Target } from "./protocol.js";
10
10
  import { type FinalTurn } from "./schedule-watch.js";
11
11
  import { type TurnRecord } from "./turn-records.js";
12
12
  export { truncateUtf8 } from "./turn-records.js";
@@ -105,6 +105,9 @@ export interface WorkerReaders {
105
105
  turn?: (server: string, pane: Json, source: Provider) => Promise<TurnRecord | undefined>;
106
106
  /** What the worker in this conversation is waiting on, from the Hook that runs it. */
107
107
  approval?: (target: Target) => Json | undefined;
108
+ /** Running child agents (sub-agents, teammates, workflows, fan-outs) of the
109
+ * worker's conversation, counted like the session rows count them. */
110
+ children?: (source: Provider, session: string) => Promise<number>;
108
111
  now?: () => number;
109
112
  stall?: typeof sessionStalls.observe;
110
113
  /** The turn a Codex pane lost with its app-server, which no Stop will end. */
@@ -192,7 +195,7 @@ export interface DispatchReturnsOptions {
192
195
  /** The standing grant for a conductor call, on this computer. */
193
196
  findGrant?: typeof findGrant;
194
197
  /** Answers a worker's approval placed on this computer, without SSH (the Hook's own `AgentHooks.answer`). */
195
- localAnswer?: (target: Target, actionId: string, decision: "approve" | "deny") => Promise<unknown>;
198
+ localAnswer?: (target: Target, actionId: string, decision: ApprovalDecision) => Promise<unknown>;
196
199
  /** A worker's new forwarded request was recorded. Returns true when this Hook pushed it to its phone. */
197
200
  onApproval?: (receipt: Receipt, approval: NonNullable<Receipt["approval"]>) => boolean | void;
198
201
  close?: (receipt: Receipt) => Promise<Json>;
@@ -227,7 +230,7 @@ export declare class DispatchReturns {
227
230
  /** Answer the permission request a dispatched worker is waiting on. It is
228
231
  * cleared from the receipt once answered, or once its Hook says it is no
229
232
  * longer pending (answered in the terminal, or timed out). */
230
- answerApproval(id: string, decision: "approve" | "deny", actionId: string, caller?: OriginPane): Promise<void>;
233
+ answerApproval(id: string, decision: ApprovalDecision, actionId: string, caller?: OriginPane): Promise<void>;
231
234
  /** Called from the Hook's activity tick. Polls peers at most every POLL_MS;
232
235
  * a return waiting for its notice is tried on every tick, so one recorded
233
236
  * while the dispatching agent was busy reaches it as soon as it stops. */
@@ -15,8 +15,10 @@ import { hookPeers, peerRequest } from "./peers.js";
15
15
  import { isLocalComputer } from "./dispatch-hosts.js";
16
16
  import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
17
17
  import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
18
+ import { liveWork } from "./session-activity.js";
18
19
  import { terminalProvider } from "./terminal.js";
19
- import { backgroundLeft, opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
20
+ import { childAgentTree, runningChildAgents } from "./transcripts.js";
21
+ import { opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
20
22
  export { truncateUtf8 } from "./turn-records.js";
21
23
  /**
22
24
  * The conductor's returns loop. The worker's computer answers what its
@@ -64,6 +66,7 @@ const defaultReaders = {
64
66
  identity: (server, pane) => paneIdentity(server, pane),
65
67
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
66
68
  turn: paneTurn,
69
+ children: (source, session) => childAgentTree(source, session).then(runningChildAgents).then(children => children.length),
67
70
  stall: (target, pane) => sessionStalls.observe(target, pane),
68
71
  lost: (server, pane, session) => codexServers.lostTurn(server, pane, session),
69
72
  };
@@ -85,10 +88,11 @@ function replyFields(text, truncated) {
85
88
  return { reply: reply.text, ...(reply.truncated || truncated ? { truncated: true } : {}) };
86
89
  }
87
90
  /** A worker's state from its own turn events. Done means a Stop arrived after
88
- * the last submitted prompt with no background work left (or it has waited
89
- * BACKGROUND_WAIT_MS); a prompt with no Stop is still working, unless the
90
- * pane is idle and the transcript shows the owner interrupted it (no Stop
91
- * comes then) or a finished turn whose Stop the Hook never received. */
91
+ * the last submitted prompt with no live work left (see `liveWork`: awaited
92
+ * shells plus running children, never a leftover idle shell); a prompt with no
93
+ * Stop is still working, unless the pane is idle and the transcript shows the
94
+ * owner interrupted it (no Stop comes then) or a finished turn whose Stop the
95
+ * Hook never received. */
92
96
  async function fromTurn(record, session, status, source, readers) {
93
97
  const base = { session, hook: true };
94
98
  if (status === "blocked")
@@ -99,20 +103,25 @@ async function fromTurn(record, session, status, source, readers) {
99
103
  const idle = status === "idle" || status === "done";
100
104
  if (phase.phase === "working" && !idle)
101
105
  return { state: "working", ...base };
102
- const final = await readers.finalTurn(source, session).catch(() => undefined);
106
+ const now = (readers.now ?? Date.now)();
107
+ const [final, children] = await Promise.all([
108
+ readers.finalTurn(source, session).catch(() => undefined),
109
+ readers.children ? readers.children(source, session).catch(() => 0) : Promise.resolve(0),
110
+ ]);
103
111
  if (phase.phase === "working") {
104
112
  if (final?.interrupted)
105
113
  return { state: "done", ...base, completed: true, interrupted: true };
106
- if (!final?.completed || final.background)
114
+ if (!final?.completed)
107
115
  return { state: "working", ...base };
116
+ const live = liveWork(record, final, children, now);
117
+ if (live)
118
+ return { state: "working", ...base, background: live };
108
119
  return { state: "done", ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
109
120
  }
110
- const background = phase.background !== undefined ? backgroundLeft(phase.background, phase.at, final?.finishedTasks) || undefined
111
- : final?.completed ? final.background : undefined;
112
- const now = (readers.now ?? Date.now)();
113
- if (background && now - Date.parse(phase.at) < BACKGROUND_WAIT_MS)
114
- return { state: "working", ...base, background };
115
- return { state: "done", ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq, ...(background ? { background } : {}),
121
+ const live = liveWork(record, final, children, now);
122
+ if (live)
123
+ return { state: "working", ...base, background: live };
124
+ return { state: "done", ...base, completed: true, endedAt: phase.at, stopSeq: record.stop?.seq,
116
125
  ...(final?.completed && final.error ? { error: final.error } : {}),
117
126
  ...(phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)) };
118
127
  }
@@ -176,10 +185,13 @@ export async function workerStates(input, readers = defaultReaders) {
176
185
  return { state, ...(session ? { session } : {}), ...(full.success && state === "working" ? await readers.stall?.(full.data, pane) : {}) };
177
186
  }
178
187
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
179
- // A finished turn that left background work is still the worker's turn. There is no Stop to time the wait
180
- // from, so it carries what a finished turn would and the dispatching Hook bounds the wait (see observe).
181
- if (turn?.completed && turn.background) {
182
- return { state: "working", session, completed: true, background: turn.background, ...(turn.error ? { error: turn.error } : {}), ...replyFields(turn.lastAssistant) };
188
+ const children = readers.children ? await readers.children(target.source, session).catch(() => 0) : 0;
189
+ // A finished turn that left live work is still the worker's turn. With no
190
+ // Stop record, the transcript's awaited shells and the running children are
191
+ // all there is: a leftover shell alone does not hold it.
192
+ const live = turn?.completed ? liveWork(undefined, turn, children, (readers.now ?? Date.now)()) : undefined;
193
+ if (live) {
194
+ return { state: "working", session, completed: true, background: live, ...(turn?.error ? { error: turn.error } : {}), ...replyFields(turn?.lastAssistant) };
183
195
  }
184
196
  return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
185
197
  ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
@@ -0,0 +1,144 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * A small registry of the process groups this computer started for or by a
4
+ * dispatched worker. It answers two questions the plain process table cannot:
5
+ *
6
+ * 1. Which agent owns a heavy process? A worker's helpers, a detached server
7
+ * (`nohup … &`, reparented to PID 1) and a build in a new process group are
8
+ * matched by the registered process group as well as by ancestry, so the
9
+ * resources report names the owning agent instead of guessing from a lone
10
+ * `node`.
11
+ * 2. May a leftover process group be ended? Only a group the Hook registered
12
+ * and whose owning pane is gone is ever signalled; the Hook's own service,
13
+ * the owner's sessions and anything unregistered are never touched.
14
+ *
15
+ * A job is recorded when the Hook launches a worker in a pane. The process
16
+ * group is filled in on the next read, because a pane's process does not exist
17
+ * until the multiplexer has started it; matching the pane's shell in the
18
+ * process table resolves it. Records are small and kept briefly.
19
+ */
20
+ /** The pane that owns a job, structurally the shape the terminal provider reports. */
21
+ export interface JobPane {
22
+ server: string;
23
+ workspace?: string;
24
+ pane: string;
25
+ agent?: string;
26
+ label?: string;
27
+ }
28
+ /** The fields of a process table row this registry reads; `ProcessRow` satisfies it. */
29
+ export interface ProcessLike {
30
+ pid: number;
31
+ ppid: number;
32
+ pgid: number;
33
+ command: string;
34
+ args: string; /** Epoch ms, to about a second. */
35
+ startedAt?: number;
36
+ }
37
+ declare const jobSchema: z.ZodObject<{
38
+ pgid: z.ZodOptional<z.ZodNumber>;
39
+ leaderStartedAt: z.ZodOptional<z.ZodNumber>;
40
+ pane: z.ZodOptional<z.ZodObject<{
41
+ server: z.ZodString;
42
+ workspace: z.ZodOptional<z.ZodString>;
43
+ pane: z.ZodString;
44
+ agent: z.ZodOptional<z.ZodString>;
45
+ label: z.ZodOptional<z.ZodString>;
46
+ }, z.core.$strict>>;
47
+ session: z.ZodOptional<z.ZodString>;
48
+ agent: z.ZodOptional<z.ZodString>;
49
+ label: z.ZodOptional<z.ZodString>;
50
+ command: z.ZodString;
51
+ startedAt: z.ZodNumber;
52
+ }, z.core.$strict>;
53
+ export type TrackedJob = z.infer<typeof jobSchema>;
54
+ /** The identity of a job: its pane while one exists, else its session, else its group. */
55
+ export declare const paneKey: (pane: JobPane) => string;
56
+ export declare function jobKey(job: TrackedJob): string;
57
+ /** The registered jobs by their process group, for attribution. */
58
+ export declare function jobPgids(jobs: readonly TrackedJob[]): Map<number, TrackedJob>;
59
+ /**
60
+ * Fill each job's process group from the pane it owns: a job registered before
61
+ * its terminal started has no pgid until the process table shows the pane's
62
+ * shell (or an already-detached process) in a group. Never invents a group.
63
+ */
64
+ export declare function resolveJobGroups(jobs: readonly TrackedJob[], rows: readonly ProcessLike[], owners: ReadonlyMap<number, JobPane>): TrackedJob[];
65
+ /** How long a job's process group is left alone after its pane was requested,
66
+ * so a launch that is still coming up is never signalled. */
67
+ export declare const CLEANUP_LEASE_MS: number;
68
+ /** `ps` reports elapsed time in whole seconds, read at slightly different moments. */
69
+ export declare const LEADER_START_TOLERANCE_MS = 3000;
70
+ /** How long a finished or reused record is kept before it is dropped. */
71
+ export declare const CLEANUP_RETAIN_MS: number;
72
+ export interface CleanupOptions {
73
+ now?: number;
74
+ leaseMs?: number;
75
+ retainMs?: number;
76
+ /** The Hook's own pid; its process group is never signalled. */
77
+ selfPid?: number;
78
+ /** False when the caller could not read the live panes: nothing is ended. */
79
+ panesKnown?: boolean;
80
+ /** When given, unresolved jobs are matched to their panes before planning. */
81
+ owners?: ReadonlyMap<number, JobPane>;
82
+ /** The terminal servers whose panes are all in `live`. A job on any other
83
+ * server (one that didn't answer, or isn't listed) is never ended: its pane
84
+ * is unknown, not gone. Omitted, nothing is ended. */
85
+ servers?: ReadonlySet<string>;
86
+ kill?: (pgid: number, signal: NodeJS.Signals) => void;
87
+ }
88
+ export interface CleanupPlan {
89
+ kill: TrackedJob[];
90
+ keep: Array<{
91
+ job: TrackedJob;
92
+ reason: string;
93
+ }>;
94
+ forget: TrackedJob[];
95
+ }
96
+ /**
97
+ * Decide which registered process groups may be ended. A job is ended only when
98
+ * every one of these holds: it has a resolved group above 1, its owning pane is
99
+ * not in `live`, its group still has processes, none of them is the Hook itself,
100
+ * the lease has passed, and a process still matches the command the Hook
101
+ * started. Anything else is kept (with a reason) or, when the group is gone or
102
+ * the record is old, forgotten. A caller that could not read the live panes
103
+ * passes `panesKnown: false`, so a failed snapshot never triggers a kill.
104
+ */
105
+ export declare function planCleanup(jobs: readonly TrackedJob[], rows: readonly ProcessLike[], live: ReadonlySet<string>, options?: CleanupOptions): CleanupPlan;
106
+ export interface CleanupReport {
107
+ killed: number[];
108
+ kept: Array<{
109
+ pgid?: number;
110
+ reason: string;
111
+ }>;
112
+ forgotten: number[];
113
+ }
114
+ /** What the resources report needs from a registry; `JobRegistry` implements it, tests can stub it. */
115
+ export interface JobSource {
116
+ list(): Promise<TrackedJob[]>;
117
+ reconcile(rows: readonly ProcessLike[], owners: ReadonlyMap<number, JobPane>): Promise<TrackedJob[]>;
118
+ cleanup(rows: readonly ProcessLike[], live: ReadonlySet<string>, options?: CleanupOptions): Promise<CleanupReport>;
119
+ }
120
+ /**
121
+ * The on-disk job registry. The Hook is the only writer, so the file is read
122
+ * whole; a damaged file reads as no jobs rather than failing a report.
123
+ */
124
+ export declare class JobRegistry {
125
+ private readonly file;
126
+ private readonly now;
127
+ constructor(file?: string, now?: () => number);
128
+ list(): Promise<TrackedJob[]>;
129
+ private replace;
130
+ /** Record (or refresh) one worker's job, keyed by its pane. */
131
+ register(job: Omit<TrackedJob, "startedAt"> & {
132
+ startedAt?: number;
133
+ }): Promise<TrackedJob>;
134
+ /** Resolve process groups against the current table and persist any change. */
135
+ reconcile(rows: readonly ProcessLike[], owners: ReadonlyMap<number, JobPane>): Promise<TrackedJob[]>;
136
+ /**
137
+ * End every registered process group that is safe to end (`planCleanup`) and
138
+ * drop the records that are gone. `live` is the set of pane keys the caller
139
+ * still sees; a caller whose snapshot failed passes `panesKnown: false`, and
140
+ * nothing is ended.
141
+ */
142
+ cleanup(rows: readonly ProcessLike[], live: ReadonlySet<string>, options?: CleanupOptions): Promise<CleanupReport>;
143
+ }
144
+ export {};