@phren/cli 0.3.11 → 0.3.12

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 (168) hide show
  1. package/dist/bridge/agent-hook-stores.d.ts +3 -0
  2. package/dist/bridge/agent-hook-stores.js +5 -0
  3. package/dist/bridge/agent-hooks.d.ts +159 -5
  4. package/dist/bridge/agent-hooks.js +663 -49
  5. package/dist/bridge/approval-summary.d.ts +16 -0
  6. package/dist/bridge/approval-summary.js +133 -0
  7. package/dist/bridge/authority-command.d.ts +20 -0
  8. package/dist/bridge/authority-command.js +120 -0
  9. package/dist/bridge/authority.d.ts +223 -0
  10. package/dist/bridge/authority.js +231 -0
  11. package/dist/bridge/claude-account-setup.d.ts +14 -0
  12. package/dist/bridge/claude-account-setup.js +69 -0
  13. package/dist/bridge/claude-accounts.d.ts +49 -0
  14. package/dist/bridge/claude-accounts.js +195 -0
  15. package/dist/bridge/code-routes.js +2 -2
  16. package/dist/bridge/codex-app-server.d.ts +144 -0
  17. package/dist/bridge/codex-app-server.js +319 -0
  18. package/dist/bridge/codex-auth-refresh.d.ts +33 -0
  19. package/dist/bridge/codex-auth-refresh.js +71 -0
  20. package/dist/bridge/codex-question-reply.d.ts +16 -0
  21. package/dist/bridge/codex-question-reply.js +57 -0
  22. package/dist/bridge/codex-review-mode.d.ts +10 -0
  23. package/dist/bridge/codex-review-mode.js +74 -0
  24. package/dist/bridge/codex-servers.d.ts +217 -0
  25. package/dist/bridge/codex-servers.js +636 -0
  26. package/dist/bridge/command.js +94 -4
  27. package/dist/bridge/computer-identity.d.ts +75 -0
  28. package/dist/bridge/computer-identity.js +166 -0
  29. package/dist/bridge/conductor-group.d.ts +91 -8
  30. package/dist/bridge/conductor-group.js +105 -9
  31. package/dist/bridge/conductor-role.d.ts +94 -0
  32. package/dist/bridge/conductor-role.js +176 -0
  33. package/dist/bridge/conductor-sets.d.ts +20 -0
  34. package/dist/bridge/conductor-sets.js +59 -0
  35. package/dist/bridge/dispatch-command.d.ts +3 -0
  36. package/dist/bridge/dispatch-command.js +75 -11
  37. package/dist/bridge/dispatch-returns.d.ts +123 -19
  38. package/dist/bridge/dispatch-returns.js +357 -50
  39. package/dist/bridge/dispatch.d.ts +103 -2
  40. package/dist/bridge/dispatch.js +272 -40
  41. package/dist/bridge/fanouts.d.ts +7 -1
  42. package/dist/bridge/fanouts.js +39 -4
  43. package/dist/bridge/folder-trust.d.ts +56 -0
  44. package/dist/bridge/folder-trust.js +195 -0
  45. package/dist/bridge/grants.d.ts +22 -1
  46. package/dist/bridge/grants.js +57 -9
  47. package/dist/bridge/hand-off.d.ts +21 -9
  48. package/dist/bridge/hand-off.js +58 -45
  49. package/dist/bridge/harness-status.d.ts +11 -0
  50. package/dist/bridge/harness-status.js +32 -0
  51. package/dist/bridge/harnesses.d.ts +39 -0
  52. package/dist/bridge/harnesses.js +65 -0
  53. package/dist/bridge/health.d.ts +2 -0
  54. package/dist/bridge/health.js +1 -1
  55. package/dist/bridge/herdr.d.ts +11 -2
  56. package/dist/bridge/herdr.js +98 -23
  57. package/dist/bridge/hook-fast.d.ts +4 -0
  58. package/dist/bridge/hook-fast.js +68 -0
  59. package/dist/bridge/install.d.ts +16 -1
  60. package/dist/bridge/install.js +88 -21
  61. package/dist/bridge/launch-brief.d.ts +96 -0
  62. package/dist/bridge/launch-brief.js +164 -0
  63. package/dist/bridge/model-switch.d.ts +3 -0
  64. package/dist/bridge/model-switch.js +17 -1
  65. package/dist/bridge/models.d.ts +8 -4
  66. package/dist/bridge/models.js +24 -8
  67. package/dist/bridge/mux-wire.d.ts +9 -0
  68. package/dist/bridge/mux-wire.js +19 -0
  69. package/dist/bridge/opencode-pane-server.d.ts +113 -0
  70. package/dist/bridge/opencode-pane-server.js +332 -0
  71. package/dist/bridge/opencode-panes.d.ts +111 -0
  72. package/dist/bridge/opencode-panes.js +295 -0
  73. package/dist/bridge/pane-accounts.d.ts +8 -0
  74. package/dist/bridge/pane-accounts.js +46 -0
  75. package/dist/bridge/prompt-startup.d.ts +5 -0
  76. package/dist/bridge/prompt-startup.js +24 -0
  77. package/dist/bridge/protocol.d.ts +5 -0
  78. package/dist/bridge/protocol.js +4 -0
  79. package/dist/bridge/push.d.ts +5 -4
  80. package/dist/bridge/push.js +6 -4
  81. package/dist/bridge/questions.d.ts +37 -2
  82. package/dist/bridge/questions.js +158 -15
  83. package/dist/bridge/resources.d.ts +9 -3
  84. package/dist/bridge/resources.js +24 -8
  85. package/dist/bridge/schedule-format.d.ts +2 -0
  86. package/dist/bridge/schedule-format.js +3 -0
  87. package/dist/bridge/schedule-launch.d.ts +2 -1
  88. package/dist/bridge/schedule-launch.js +23 -53
  89. package/dist/bridge/schedule-watch.d.ts +10 -1
  90. package/dist/bridge/schedule-watch.js +54 -2
  91. package/dist/bridge/server-launch.d.ts +22 -5
  92. package/dist/bridge/server-launch.js +225 -29
  93. package/dist/bridge/server-overview.d.ts +3 -3
  94. package/dist/bridge/server-overview.js +22 -14
  95. package/dist/bridge/server-pane-routes.d.ts +2 -0
  96. package/dist/bridge/server-pane-routes.js +145 -15
  97. package/dist/bridge/server-routes.d.ts +7 -0
  98. package/dist/bridge/server-routes.js +163 -35
  99. package/dist/bridge/server-stream.d.ts +2 -0
  100. package/dist/bridge/server-stream.js +22 -8
  101. package/dist/bridge/server.d.ts +6 -1
  102. package/dist/bridge/server.js +44 -12
  103. package/dist/bridge/session-activity.d.ts +81 -0
  104. package/dist/bridge/session-activity.js +117 -0
  105. package/dist/bridge/session-rename.d.ts +48 -0
  106. package/dist/bridge/session-rename.js +190 -0
  107. package/dist/bridge/session-servers.js +2 -2
  108. package/dist/bridge/settings-switch.d.ts +60 -0
  109. package/dist/bridge/settings-switch.js +287 -0
  110. package/dist/bridge/speech-voice.d.ts +55 -0
  111. package/dist/bridge/speech-voice.js +132 -0
  112. package/dist/bridge/speech.d.ts +70 -11
  113. package/dist/bridge/speech.js +169 -41
  114. package/dist/bridge/terminal-herdr.js +9 -3
  115. package/dist/bridge/terminal-tmux.d.ts +3 -3
  116. package/dist/bridge/terminal-tmux.js +24 -9
  117. package/dist/bridge/terminal.d.ts +27 -4
  118. package/dist/bridge/terminal.js +8 -1
  119. package/dist/bridge/transcript-claude.js +57 -12
  120. package/dist/bridge/transcript-codex.d.ts +0 -2
  121. package/dist/bridge/transcript-codex.js +29 -4
  122. package/dist/bridge/transcript-preview.d.ts +1 -0
  123. package/dist/bridge/transcript-preview.js +24 -4
  124. package/dist/bridge/transcripts.d.ts +15 -2
  125. package/dist/bridge/transcripts.js +47 -16
  126. package/dist/bridge/turn-records.d.ts +85 -0
  127. package/dist/bridge/turn-records.js +143 -0
  128. package/dist/bridge/uploads.d.ts +3 -0
  129. package/dist/bridge/uploads.js +14 -0
  130. package/dist/bridge/usage.d.ts +39 -10
  131. package/dist/bridge/usage.js +155 -44
  132. package/dist/bridge-hook.mjs +19169 -13176
  133. package/dist/cli/claude-unmanaged.d.ts +12 -0
  134. package/dist/cli/claude-unmanaged.js +105 -0
  135. package/dist/cli/schedules.js +2 -1
  136. package/dist/cli/session-start.js +10 -1
  137. package/dist/cli/session-stop.js +9 -1
  138. package/dist/cli-registry.js +24 -5
  139. package/dist/data/task-receipts.d.ts +19 -0
  140. package/dist/data/task-receipts.js +68 -0
  141. package/dist/data/tasks.js +4 -1
  142. package/dist/generated/memory-ui-graph.browser.js +63 -63
  143. package/dist/graph-core/model.js +24 -3
  144. package/dist/graph-core/types.d.ts +4 -1
  145. package/dist/graph-core/types.js +1 -0
  146. package/dist/init/init-preset.js +7 -3
  147. package/dist/init/init-uninstall.js +2 -11
  148. package/dist/init/teardown.d.ts +3 -0
  149. package/dist/init/teardown.js +47 -0
  150. package/dist/link/context.js +21 -9
  151. package/dist/mcp/plugin-mode.js +1 -1
  152. package/dist/memory-ui-graph.runtime.js +63 -63
  153. package/dist/modules/code-package.d.ts +1 -0
  154. package/dist/modules/code-package.js +36 -7
  155. package/dist/modules/registry.js +14 -13
  156. package/dist/profile-store.d.ts +6 -0
  157. package/dist/profile-store.js +25 -1
  158. package/dist/shell/graph/glyphs.js +4 -0
  159. package/dist/shell/graph/graph-view.js +2 -0
  160. package/dist/status.js +7 -1
  161. package/dist/sync/task-claim.js +3 -2
  162. package/dist/task/lifecycle.js +25 -4
  163. package/dist/test-global-setup.js +5 -0
  164. package/dist/tools/dispatch.js +35 -2
  165. package/dist/tools/tasks.js +10 -1
  166. package/package.json +1 -1
  167. package/plugins/opencode/phren-transcript.js +87 -4
  168. package/starter/global/skills/conductor/SKILL.md +17 -2
@@ -1,51 +1,113 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { z } from "zod";
3
- import { dispatchStatus, updateReceipt } from "./dispatch.js";
3
+ import { logger } from "../logger.js";
4
+ import { arrivalOf, dispatchStatus, updateReceipt } from "./dispatch.js";
5
+ import { briefArrival, briefId } from "./launch-brief.js";
6
+ import { findGrant } from "./grants.js";
4
7
  import { findPane, paneIdentity, sharedSnapshot } from "./herdr.js";
5
8
  import { handOff } from "./hand-off.js";
6
9
  import { hookPeers, peerRequest } from "./peers.js";
7
10
  import { isLocalComputer } from "./dispatch-hosts.js";
8
- import { objects, startingTargetSchema, targetSchema } from "./protocol.js";
11
+ import { BridgeError, objects, startingTargetSchema, targetSchema } from "./protocol.js";
9
12
  import { ownerQuestion, readFinalTurn } from "./schedule-watch.js";
13
+ import { terminalProvider } from "./terminal.js";
14
+ import { backgroundLeft, opencodeTurn, readTurn, TURN_REPLY_LIMIT, truncateUtf8, turnPhase } from "./turn-records.js";
15
+ export { truncateUtf8 } from "./turn-records.js";
10
16
  /**
11
17
  * The conductor's returns loop. The worker's computer answers what its
12
- * dispatched panes are doing from the Herdr snapshot its Hook already shares
13
- * (`workerStates`); the dispatching Hook asks each peer once per poll for all
14
- * of its open dispatches, records transitions in the receipts, and tells an
15
- * idle dispatching agent that returns are waiting (`DispatchReturns`).
18
+ * dispatched panes are doing (`workerStates`): from the turn record its
19
+ * agent's own hooks wrote (turn-records.ts) when there is one, else from the
20
+ * Herdr snapshot its Hook already shares and the transcript. The dispatching
21
+ * Hook asks each peer once per poll for all of its open dispatches, records
22
+ * transitions in the receipts, and tells an idle dispatching agent that
23
+ * returns are waiting (`DispatchReturns`).
16
24
  */
17
25
  /** Longest final reply kept in a receipt, in UTF-8 bytes. */
18
- export const REPLY_LIMIT = 4000;
26
+ export const REPLY_LIMIT = TURN_REPLY_LIMIT;
19
27
  /** How often the dispatching Hook asks peers about open dispatches. */
20
28
  export const POLL_MS = 15_000;
21
29
  /** Shortest gap between two notices typed into the same dispatching pane. */
22
30
  export const NOTICE_MS = 120_000;
23
31
  /** Receipts older than this are no longer watched. */
24
32
  export const WATCH_MS = 24 * 60 * 60 * 1000;
25
- /** An idle worker that was never seen working and has no finished turn is
26
- * counted as done after this long: the prompt may never have been taken. */
27
- export const IDLE_GRACE_MS = 5 * 60 * 1000;
33
+ /** How long a stopped worker whose harness still runs background tasks is
34
+ * waited on before it counts as done anyway. Measured from the latest Stop,
35
+ * and every task that finishes wakes the worker (a new prompt, a new Stop), so
36
+ * it only elapses when no background task has finished for two hours: a dev
37
+ * server the worker left running. It is then reported done with the count
38
+ * still running. */
39
+ export const BACKGROUND_WAIT_MS = 2 * 60 * 60 * 1000;
28
40
  /** How old a shared Herdr snapshot may be when answering a peer. */
29
41
  const SNAPSHOT_AGE_MS = 5_000;
30
- const workerTarget = z.union([targetSchema, startingTargetSchema]);
42
+ // `dispatch` names the receipt, which is the worker's PHREN_DISPATCH_ID. An
43
+ // older Hook's target schema strips it, so it is safe to send to any peer.
44
+ const workerTarget = z.union([targetSchema.extend({ dispatch: briefId.optional() }), startingTargetSchema.extend({ dispatch: briefId.optional() })]);
31
45
  export const workerRequestSchema = z.object({ targets: z.array(workerTarget).min(1).max(64) }).strict();
46
+ async function paneTurn(server, pane, source) {
47
+ if (source !== "opencode")
48
+ return readTurn(server, String(pane.pane_id));
49
+ if (typeof pane.terminal_id !== "string")
50
+ return undefined;
51
+ return opencodeTurn((await terminalProvider().processes(server, String(pane.pane_id))).foregroundPids, pane.terminal_id);
52
+ }
32
53
  const defaultReaders = {
33
54
  snapshot: server => sharedSnapshot(server, SNAPSHOT_AGE_MS),
34
55
  identity: (server, pane) => paneIdentity(server, pane),
35
56
  finalTurn: (source, session) => source === "codex" || source === "claude" || source === "opencode" ? readFinalTurn(source, session) : Promise.resolve(undefined),
57
+ turn: paneTurn,
36
58
  };
37
- /** `value` cut to at most `limit` UTF-8 bytes on a character boundary. */
38
- export function truncateUtf8(value, limit = REPLY_LIMIT) {
39
- const bytes = Buffer.from(value);
40
- if (bytes.length <= limit)
41
- return { text: value, truncated: false };
42
- let end = limit;
43
- while (end > 0 && (bytes[end] & 0xc0) === 0x80)
44
- end--;
45
- return { text: bytes.subarray(0, end).toString("utf8"), truncated: true };
59
+ /** The default readers with the approval reader of the Hook that runs the workers. */
60
+ export const workerReaders = (approval) => ({ ...defaultReaders, approval });
61
+ /** The receiving side of `/v1/dispatch/workers` on a Hook: leases the panes'
62
+ * permission asks for the dispatching Hook's next polls and reads what each
63
+ * worker is waiting on. */
64
+ export function hookWorkers(hooks) {
65
+ return input => {
66
+ hooks.leaseDispatch(workerRequestSchema.parse(input).targets);
67
+ return workerStates(input, workerReaders(target => hooks.workerApproval(target)));
68
+ };
69
+ }
70
+ function replyFields(text, truncated) {
71
+ if (!text)
72
+ return {};
73
+ const reply = truncateUtf8(text);
74
+ return { reply: reply.text, ...(reply.truncated || truncated ? { truncated: true } : {}) };
46
75
  }
47
- /** Receiving side: the state of each dispatched pane, from the shared snapshot
48
- * and, once the agent has stopped, the final reply in its transcript. */
76
+ /** A worker's state from its own turn events. Done means a Stop arrived after
77
+ * the last submitted prompt with no background work left (or it has waited
78
+ * BACKGROUND_WAIT_MS); a prompt with no Stop is still working, unless the
79
+ * pane is idle and the transcript shows the owner interrupted it (no Stop
80
+ * comes then) or a finished turn whose Stop the Hook never received. */
81
+ async function fromTurn(record, session, status, source, readers) {
82
+ const base = { session, hook: true };
83
+ if (status === "blocked")
84
+ return { state: "blocked", ...base };
85
+ const phase = turnPhase(record);
86
+ if (phase.phase === "unprompted")
87
+ return { state: "idle", ...base, completed: false };
88
+ const idle = status === "idle" || status === "done";
89
+ if (phase.phase === "working" && !idle)
90
+ return { state: "working", ...base };
91
+ const final = await readers.finalTurn(source, session).catch(() => undefined);
92
+ if (phase.phase === "working") {
93
+ if (final?.interrupted)
94
+ return { state: "done", ...base, completed: true, interrupted: true };
95
+ if (!final?.completed || final.background)
96
+ return { state: "working", ...base };
97
+ return { state: "done", ...base, completed: true, ...(final.error ? { error: final.error } : {}), ...replyFields(final.lastAssistant) };
98
+ }
99
+ const background = phase.background !== undefined ? backgroundLeft(phase.background, phase.at, final?.finishedTasks) || undefined
100
+ : final?.completed ? final.background : undefined;
101
+ const now = (readers.now ?? Date.now)();
102
+ if (background && now - Date.parse(phase.at) < BACKGROUND_WAIT_MS)
103
+ return { state: "working", ...base, background };
104
+ return { state: "done", ...base, completed: true, endedAt: phase.at, ...(background ? { background } : {}),
105
+ ...(final?.completed && final.error ? { error: final.error } : {}),
106
+ ...(phase.reply ? replyFields(phase.reply, phase.truncated) : replyFields(final?.lastAssistant)) };
107
+ }
108
+ /** Receiving side: the state of each dispatched pane, from its agent's turn
109
+ * record when its hooks wrote one, else from the shared snapshot and, once
110
+ * the agent has stopped, the final reply in its transcript. */
49
111
  export async function workerStates(input, readers = defaultReaders) {
50
112
  const { targets } = workerRequestSchema.parse(input);
51
113
  const snapshots = new Map();
@@ -67,32 +129,88 @@ export async function workerStates(input, readers = defaultReaders) {
67
129
  // Another conversation in the same pane means the worker is gone.
68
130
  if (expected && current && current !== expected)
69
131
  return { state: "gone" };
70
- const session = expected ?? current;
71
132
  const status = String(pane.agent_status);
133
+ // The record counts only for the conversation this dispatch started, in
134
+ // the terminal still there, and never for another dispatch's worker.
135
+ const record = await readers.turn?.(target.server, pane, target.source).catch(() => undefined);
136
+ const own = record && record.terminal === pane.terminal_id && record.source === target.source
137
+ && record.session === (expected ?? current ?? record.session)
138
+ && !(target.dispatch && record.dispatch && target.dispatch !== record.dispatch) ? record : undefined;
139
+ if (own)
140
+ return fromTurn(own, own.session, status, target.source, readers);
141
+ const session = expected ?? current;
72
142
  const state = ["working", "idle", "done", "blocked"].find(value => value === status) ?? "unknown";
73
143
  if ((state !== "idle" && state !== "done") || !session)
74
144
  return { state, ...(session ? { session } : {}) };
75
145
  const turn = await readers.finalTurn(target.source, session).catch(() => undefined);
76
- const reply = turn?.lastAssistant ? truncateUtf8(turn.lastAssistant) : undefined;
146
+ // A finished turn that left background work is still the worker's turn. There is no Stop to time the wait
147
+ // from, so it carries what a finished turn would and the dispatching Hook bounds the wait (see observe).
148
+ if (turn?.completed && turn.background) {
149
+ return { state: "working", session, completed: true, background: turn.background, ...(turn.error ? { error: turn.error } : {}), ...replyFields(turn.lastAssistant) };
150
+ }
77
151
  return { state, session, completed: turn?.completed === true, ...(turn?.error ? { error: turn.error } : {}),
78
- ...(reply ? { reply: reply.text, ...(reply.truncated ? { truncated: true } : {}) } : {}) };
152
+ ...(turn?.interrupted ? { interrupted: true } : {}), ...replyFields(turn?.lastAssistant) };
79
153
  }));
80
- return { workers };
154
+ // Only a conversation this dispatch named can be answered; a starting target has no session yet.
155
+ return { workers: workers.map((seen, index) => {
156
+ const { dispatch: _dispatch, ...target } = targets[index];
157
+ const full = "session" in target ? targetSchema.safeParse(target) : undefined;
158
+ const approval = full?.success && seen.state !== "gone" && seen.state !== "unavailable" ? readers.approval?.(full.data) : undefined;
159
+ return approval ? { ...seen, approval } : seen;
160
+ }) };
81
161
  }
82
162
  const observationSchema = z.object({
83
163
  state: z.enum(["working", "idle", "done", "blocked", "unknown", "gone", "unavailable"]),
84
164
  session: z.string().max(200).optional(), completed: z.boolean().optional(),
85
165
  reply: z.string().max(REPLY_LIMIT).optional(), truncated: z.boolean().optional(), error: z.string().max(500).optional(),
166
+ hook: z.boolean().optional(), endedAt: z.string().max(40).optional(), background: z.number().int().min(0).max(999).optional(),
167
+ interrupted: z.boolean().optional(), approval: z.unknown().optional(),
86
168
  }).passthrough();
87
- function turnKey(reply) {
88
- return reply ? createHash("sha256").update(reply).digest("hex").slice(0, 16) : undefined;
169
+ /** A worker's forwarded permission request as its Hook sent it; an invalid one is ignored, not a reason to drop the state. */
170
+ const approvalObservation = z.object({
171
+ actionId: z.string().min(1).max(200), tool: z.string().max(200).default("action"), title: z.string().max(200).optional(), request: z.string().max(500).optional(),
172
+ requestKind: z.enum(["command", "tool", "edit", "question", "other"]).optional(), terminal: z.boolean().optional(),
173
+ conductor: z.object({ action: z.enum(["dispatch", "hand_off"]), project: z.string().max(200).optional(), computer: z.string().max(200).optional() }).strict().optional(),
174
+ expiresAt: z.string().max(40).optional(), pushed: z.boolean().optional(),
175
+ });
176
+ /** What the owner is told when the worker's turn was interrupted in its terminal. */
177
+ export const INTERRUPTED = "The worker's turn was interrupted in its terminal before it finished.";
178
+ function turnKey(value) {
179
+ return value ? createHash("sha256").update(value).digest("hex").slice(0, 16) : undefined;
89
180
  }
90
181
  /** Apply one observation to a receipt. Returns true when the receipt changed. */
91
182
  export function observe(receipt, value, now) {
92
183
  const parsed = observationSchema.safeParse(value);
93
184
  if (!parsed.success || parsed.data.state === "unavailable" || parsed.data.state === "unknown")
94
185
  return false;
95
- const seen = parsed.data, at = new Date(now).toISOString();
186
+ const state = observeState(receipt, parsed.data, now);
187
+ return observeApproval(receipt, parsed.data.approval, now) || state;
188
+ }
189
+ /** Follow the request the worker is waiting on: a new one is a fresh unread
190
+ * blocked return that carries it, the same one is nothing new, and none means
191
+ * it was answered or gone. */
192
+ function observeApproval(receipt, value, now) {
193
+ const parsed = value === undefined ? undefined : approvalObservation.safeParse(value);
194
+ if (parsed && !parsed.success)
195
+ return false;
196
+ if (!parsed) {
197
+ if (!receipt.approval)
198
+ return false;
199
+ delete receipt.approval;
200
+ return true;
201
+ }
202
+ const seen = parsed.data;
203
+ if (receipt.approval?.actionId === seen.actionId)
204
+ return false;
205
+ const at = new Date(now).toISOString();
206
+ const { conductor, requestKind, terminal, pushed, ...rest } = seen;
207
+ receipt.approval = { ...rest, ...(requestKind ? { requestKind } : {}), ...(terminal ? { terminal } : {}), ...(conductor ? { conductor } : {}), ...(pushed ? { pushed } : {}), at };
208
+ receipt.returned = { state: "blocked", at, read: false, question: `Approval: ${seen.request ?? seen.title ?? seen.tool}`.slice(0, 200) };
209
+ return true;
210
+ }
211
+ function observeState(receipt, parsed, now) {
212
+ let seen = parsed;
213
+ const at = new Date(now).toISOString();
96
214
  let changed = false;
97
215
  // A worker that started without a conversation id gets its full target once one exists.
98
216
  if (seen.session && receipt.target && !("session" in receipt.target)) {
@@ -103,9 +221,26 @@ export function observe(receipt, value, now) {
103
221
  changed = true;
104
222
  }
105
223
  }
224
+ // The most background work seen while the worker was working: what the
225
+ // dispatcher is told it waited on when the worker finally returns.
226
+ // A worker that took new work after returning starts the count again.
227
+ const carried = seen.state === "working" && receipt.worker && receipt.worker.state !== "working" ? 0 : receipt.worker?.background ?? 0;
228
+ const background = seen.state === "working" && seen.background ? Math.max(carried, seen.background) : carried;
229
+ // A finished turn waiting on background work with no turn record (`hook` unset)
230
+ // has no Stop to time the wait from, and a crashed background shell or a lost
231
+ // task notification would keep it working until WATCH_MS: count the wait from
232
+ // when this Hook first saw it, and return the turn as done after BACKGROUND_WAIT_MS.
233
+ // Observations from the worker's own hooks bound themselves in `fromTurn`.
234
+ const waiting = seen.state === "working" && seen.completed === true && !!seen.background && !seen.hook;
235
+ const waitingSince = waiting ? receipt.worker?.waitingSince ?? at : undefined;
236
+ const expired = waitingSince !== undefined && now - Date.parse(waitingSince) >= BACKGROUND_WAIT_MS;
237
+ if (expired)
238
+ seen = { ...seen, state: "done" };
106
239
  const sawWorking = receipt.worker?.sawWorking === true || seen.state === "working" || seen.state === "blocked";
107
- // A turn the harness ended on an error (a usage limit) failed, reply or not.
108
- const failed = seen.completed && seen.error ? seen.error : undefined;
240
+ const stopped = seen.state === "idle" || seen.state === "done";
241
+ // A turn the harness ended on an error (a usage limit) failed, reply or not,
242
+ // and so did one the owner interrupted in the worker's terminal.
243
+ const failed = stopped && seen.completed && seen.error ? seen.error : stopped && seen.interrupted ? INTERRUPTED : undefined;
109
244
  const question = seen.completed && seen.reply && !failed ? ownerQuestion(seen.reply) : undefined;
110
245
  let next;
111
246
  if (seen.state === "gone")
@@ -118,9 +253,13 @@ export function observe(receipt, value, now) {
118
253
  next = "failed";
119
254
  else if (seen.completed)
120
255
  next = question ? "needs-you" : "done";
256
+ // The worker's own hooks say no turn has ended: it has not taken its
257
+ // brief yet. Without them, idle after being seen working is the only sign.
121
258
  else
122
- next = sawWorking || now - Date.parse(receipt.createdAt) > IDLE_GRACE_MS ? "done" : "working";
123
- const turn = next === "done" || next === "needs-you" ? turnKey(seen.reply) : next === "failed" ? turnKey(failed) : undefined;
259
+ next = !seen.hook && sawWorking ? "done" : "working";
260
+ // A Stop's time names its turn; without one, the final reply does.
261
+ const turn = next === "done" || next === "needs-you" || next === "failed"
262
+ ? turnKey(seen.endedAt ? `${seen.endedAt}\n${failed ?? ""}` : next === "failed" ? failed : seen.reply) : undefined;
124
263
  const previous = receipt.worker?.state;
125
264
  // The same finished state with a different final reply is a new turn: the
126
265
  // worker took more work (a hand_off) and finished again between two polls.
@@ -130,13 +269,28 @@ export function observe(receipt, value, now) {
130
269
  receipt.worker.sawWorking = sawWorking;
131
270
  changed = true;
132
271
  }
272
+ if (receipt.worker && background > (receipt.worker.background ?? 0)) {
273
+ receipt.worker.background = background;
274
+ changed = true;
275
+ }
276
+ if (receipt.worker && receipt.worker.waitingSince !== waitingSince) {
277
+ if (waitingSince)
278
+ receipt.worker.waitingSince = waitingSince;
279
+ else
280
+ delete receipt.worker.waitingSince;
281
+ changed = true;
282
+ }
133
283
  return changed;
134
284
  }
135
- receipt.worker = { state: next, since: at, checkedAt: at, sawWorking };
285
+ receipt.worker = { state: next, since: at, checkedAt: at, sawWorking, ...(background ? { background } : {}),
286
+ ...(next === "working" && waitingSince ? { waitingSince } : {}) };
136
287
  if (next !== "working") {
137
288
  receipt.returned = { state: next, at, read: false,
138
289
  ...(seen.reply && (next === "done" || next === "needs-you") ? { reply: seen.reply, ...(seen.truncated ? { truncated: true } : {}) } : {}),
139
- ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}) };
290
+ ...(failed ? { error: failed } : {}), ...(question ? { question } : {}), ...(turn ? { turn } : {}),
291
+ ...((next === "done" || next === "needs-you") && seen.background ? { background: seen.background } : {}),
292
+ // Nothing still running: say what it waited on.
293
+ ...((next === "done" || next === "needs-you") && !seen.background && background ? { waited: background } : {}) };
140
294
  }
141
295
  return true;
142
296
  }
@@ -146,13 +300,18 @@ export function noticeLine(receipts) {
146
300
  const word = { "done": "done", "needs-you": "needs you", "failed": "failed", "blocked": "blocked", "gone": "gone" };
147
301
  const describe = (receipt, room) => {
148
302
  const returned = receipt.returned;
149
- const detail = returned.state === "needs-you" ? returned.question : returned.state === "failed" ? returned.error
303
+ const asking = returned.state === "blocked" ? receipt.approval : undefined;
304
+ const detail = asking ? asking.request ?? asking.title ?? asking.tool : returned.state === "needs-you" ? returned.question : returned.state === "failed" ? returned.error
150
305
  : returned.state === "done" ? returned.reply?.split("\n").find(line => line.trim()) : undefined;
151
306
  const excerpt = detail ? clean(detail.replace(/[*_`#>]+/g, ""), room) : "";
152
- return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${word[returned.state]}${excerpt ? `, ${excerpt}` : ""}`;
307
+ const tasks = (count) => `${count} background task${count === 1 ? "" : "s"}`;
308
+ const left = returned.background ? ` (${tasks(returned.background)} still running)` : returned.waited ? ` (after ${tasks(returned.waited)} finished)` : "";
309
+ return `${clean(receipt.computer, 60)} ${clean(receipt.label, 80)} ${asking ? "needs approval" : word[returned.state]}${left}${excerpt ? `, ${excerpt}` : ""}`;
153
310
  };
154
- if (receipts.length === 1)
155
- return `Return: ${describe(receipts[0], 100)} (dispatch ${receipts[0].id}). Call dispatch_returns.`;
311
+ if (receipts.length === 1) {
312
+ const [only] = receipts;
313
+ return `Return: ${describe(only, 100)} (dispatch ${only.id}${only.approval && only.returned?.state === "blocked" ? "; answer with dispatch_approve" : ""}). Call dispatch_returns.`;
314
+ }
156
315
  const items = receipts.slice(0, 4).map(receipt => describe(receipt, 40)).join("; ");
157
316
  return `Returns: ${receipts.length} dispatches (${items}${receipts.length > 4 ? "; more" : ""}). Call dispatch_returns.`;
158
317
  }
@@ -162,9 +321,18 @@ export function returnRow(receipt) {
162
321
  return { id: receipt.id, computer: receipt.computer, project: receipt.project, label: receipt.label, harness: receipt.harness,
163
322
  state: returned.state, at: returned.at, ...(returned.reply !== undefined ? { reply: returned.reply } : {}),
164
323
  ...(returned.truncated ? { truncated: true } : {}), ...(returned.error ? { error: returned.error } : {}), ...(returned.question ? { question: returned.question } : {}),
324
+ ...(returned.background ? { background: returned.background } : {}),
325
+ ...(returned.waited && !returned.background ? { waited: returned.waited } : {}),
326
+ ...(receipt.approval && returned.state === "blocked" ? { approval: { actionId: receipt.approval.actionId, tool: receipt.approval.tool,
327
+ ...(receipt.approval.request ? { request: receipt.approval.request } : {}), ...(receipt.approval.title ? { title: receipt.approval.title } : {}),
328
+ ...(receipt.approval.terminal ? { terminal: true } : {}) } } : {}),
165
329
  ...(receipt.target ? { target: receipt.target } : {}) };
166
330
  }
167
331
  const originKey = (origin) => JSON.stringify([origin.server, origin.workspace, origin.tab, origin.pane, origin.terminal]);
332
+ /** One notice's delivery id, named by what it reports: the same returns keep the same id on a retry. */
333
+ export function noticeDeliveryId(receipts) {
334
+ return `notice-${createHash("sha256").update(receipts.map(receipt => `${receipt.id}@${receipt.returned.at}`).sort().join(",")).digest("hex").slice(0, 32)}`;
335
+ }
168
336
  /** Dispatching side: follows open dispatches and delivers their returns. */
169
337
  export class DispatchReturns {
170
338
  peers;
@@ -174,9 +342,16 @@ export class DispatchReturns {
174
342
  snapshot;
175
343
  identity;
176
344
  deliver;
345
+ localArrival;
177
346
  now;
347
+ grant;
348
+ localAnswer;
349
+ onApproval;
178
350
  lastPoll = -Infinity;
179
351
  lastNotice = new Map();
352
+ /** A return is waiting for a dispatching agent that was busy: try again on
353
+ * the next tick instead of the next poll. */
354
+ noticesDue = false;
180
355
  running;
181
356
  constructor(options = {}) {
182
357
  this.peers = options.peers ?? hookPeers;
@@ -185,19 +360,105 @@ export class DispatchReturns {
185
360
  this.isLocal = options.isLocal ?? (computer => isLocalComputer(computer));
186
361
  this.snapshot = options.snapshot ?? (server => sharedSnapshot(server, SNAPSHOT_AGE_MS));
187
362
  this.identity = options.identity ?? ((server, pane) => paneIdentity(server, pane));
188
- this.deliver = options.deliver ?? ((target, text) => handOff({ target, text }));
363
+ this.deliver = options.deliver ?? ((target, text, deliveryId) => handOff({ target, text }, { deliveryId }));
364
+ this.localArrival = options.localArrival ?? briefArrival;
189
365
  this.now = options.now ?? Date.now;
366
+ this.grant = options.findGrant ?? findGrant;
367
+ this.localAnswer = options.localAnswer;
368
+ this.onApproval = options.onApproval;
190
369
  }
191
- /** Called from the Hook's activity tick; polls and notifies at most every POLL_MS. */
370
+ /** Send a decision for a worker's request to the Hook that runs it. */
371
+ async sendAnswer(receipt, actionId, decision) {
372
+ const target = receipt.target;
373
+ if (!target || !("session" in target))
374
+ throw new BridgeError(409, "This worker is not waiting on an approval.");
375
+ const peer = (await this.peers().catch(() => [])).find(candidate => candidate.name === receipt.computer);
376
+ if (peer) {
377
+ await this.request(peer, "/v1/approvals/answer", { target, actionId, decision });
378
+ return;
379
+ }
380
+ if (!this.localAnswer || !this.isLocal(receipt.computer))
381
+ throw new BridgeError(503, `${receipt.computer} is not reachable from here.`);
382
+ await this.localAnswer(target, actionId, decision);
383
+ }
384
+ /** Answer the permission request a dispatched worker is waiting on. It is
385
+ * cleared from the receipt once answered, or once its Hook says it is no
386
+ * longer pending (answered in the terminal, or timed out). */
387
+ async answerApproval(id, decision, actionId, caller) {
388
+ const receipt = (await dispatchStatus()).find(candidate => candidate.id === id);
389
+ const approval = receipt?.approval;
390
+ if (!receipt || !approval || approval.actionId !== actionId)
391
+ throw new BridgeError(409, "This worker is not waiting on an approval.");
392
+ // A caller pane is an agent asking over MCP: only the one that dispatched the worker, never the worker itself. No pane (phone, CLI) answers as the owner.
393
+ if (caller) {
394
+ const same = (pane) => !!pane && pane.server === caller.server && pane.pane === caller.pane;
395
+ // A worker dispatched from the phone or CLI records no dispatching pane, so no agent may answer for it; the owner answers without a pane.
396
+ if (!receipt.origin || !same(receipt.origin) || (this.isLocal(receipt.computer) && same(receipt.target)))
397
+ throw new BridgeError(403, "Only the agent that dispatched this worker can answer its approvals.");
398
+ }
399
+ const clear = () => updateReceipt(id, current => {
400
+ if (current.approval?.actionId !== approval.actionId)
401
+ return false;
402
+ delete current.approval;
403
+ return true;
404
+ }).catch(() => undefined);
405
+ try {
406
+ await this.sendAnswer(receipt, approval.actionId, decision);
407
+ }
408
+ catch (error) {
409
+ if (error instanceof BridgeError && error.status === 409)
410
+ await clear();
411
+ throw error;
412
+ }
413
+ await clear();
414
+ }
415
+ /** Called from the Hook's activity tick. Polls peers at most every POLL_MS;
416
+ * a return waiting for its notice is tried on every tick, so one recorded
417
+ * while the dispatching agent was busy reaches it as soon as it stops. */
192
418
  tick() {
193
- if (this.running || this.now() - this.lastPoll < POLL_MS)
194
- return this.running ?? Promise.resolve();
195
- this.lastPoll = this.now();
196
- this.running = (async () => { await this.poll(); await this.notify(); })().catch(() => { }).finally(() => { this.running = undefined; });
419
+ if (this.running)
420
+ return this.running;
421
+ const poll = this.now() - this.lastPoll >= POLL_MS;
422
+ if (!poll && !this.noticesDue)
423
+ return Promise.resolve();
424
+ if (poll)
425
+ this.lastPoll = this.now();
426
+ this.running = (async () => { if (poll)
427
+ await this.poll(); await this.notify(); })()
428
+ .catch(() => { }).finally(() => { this.running = undefined; });
197
429
  return this.running;
198
430
  }
431
+ /**
432
+ * A brief that went with the launch but was not confirmed while the dispatch
433
+ * was placed (a startup screen held it, the agent was slow): ask the
434
+ * worker's computer whether its hook has confirmed it since.
435
+ */
436
+ async confirmArrivals(peers) {
437
+ const now = this.now();
438
+ const unconfirmed = (await dispatchStatus()).filter(receipt => receipt.state === "uncertain" && receipt.brief === "launch"
439
+ && now - Date.parse(receipt.createdAt) < WATCH_MS).slice(0, 64);
440
+ for (const receipt of unconfirmed) {
441
+ const peer = peers.find(candidate => candidate.name === receipt.computer);
442
+ if (!peer && !this.isLocal(receipt.computer))
443
+ continue;
444
+ const arrival = await (peer ? arrivalOf({ request: route => this.request(peer, route) }, receipt.id) : this.localArrival(receipt.id)).catch(() => undefined);
445
+ if (!arrival?.accepted)
446
+ continue;
447
+ const named = arrival.accepted.target;
448
+ await updateReceipt(receipt.id, current => {
449
+ if (current.state !== "uncertain")
450
+ return false;
451
+ current.state = "accepted";
452
+ delete current.error;
453
+ if (named.source === current.harness)
454
+ current.target = named;
455
+ return true;
456
+ }).catch(() => undefined);
457
+ }
458
+ }
199
459
  /** Ask each peer, once, about every open dispatch placed on it. */
200
460
  async poll() {
461
+ await this.confirmArrivals(await this.peers().catch(() => []));
201
462
  const now = this.now();
202
463
  const open = (await dispatchStatus()).filter(receipt => (receipt.state === "accepted" || receipt.state === "uncertain")
203
464
  && receipt.target && receipt.worker?.state !== "gone" && now - Date.parse(receipt.createdAt) < WATCH_MS);
@@ -215,21 +476,62 @@ export class DispatchReturns {
215
476
  return;
216
477
  for (let start = 0; start < receipts.length; start += 64) {
217
478
  const batch = receipts.slice(start, start + 64);
218
- const input = { targets: batch.map(receipt => receipt.target) };
479
+ const input = { targets: batch.map(receipt => ({ ...receipt.target, dispatch: receipt.id })) };
219
480
  // An unreachable peer records nothing: silence is not a transition.
220
481
  const answer = await (peer ? this.request(peer, "/v1/dispatch/workers", input) : this.localWorkers(input)).catch(() => undefined);
221
482
  const workers = objects(answer?.workers);
222
483
  if (workers.length !== batch.length)
223
484
  continue;
224
485
  for (const [index, receipt] of batch.entries()) {
225
- await updateReceipt(receipt.id, current => observe(current, workers[index], this.now())).catch(() => undefined);
486
+ const seen = await this.grantAnswered(receipt, workers[index]);
487
+ let fresh;
488
+ const current = await updateReceipt(receipt.id, value => {
489
+ const before = value.approval?.actionId, changed = observe(value, seen, this.now());
490
+ if (value.approval && value.approval.actionId !== before)
491
+ fresh = value.approval;
492
+ return changed;
493
+ }).catch(() => undefined);
494
+ if (!fresh || !current)
495
+ continue;
496
+ const pushed = await Promise.resolve(this.onApproval?.(current, fresh)).catch(() => undefined);
497
+ if (pushed === true) {
498
+ await updateReceipt(receipt.id, value => {
499
+ if (value.approval?.actionId !== fresh.actionId || value.approval.pushed)
500
+ return false;
501
+ value.approval.pushed = true;
502
+ return true;
503
+ }).catch(() => undefined);
504
+ }
226
505
  }
227
506
  }
228
507
  }));
229
508
  }
230
- /** Type one line into each idle dispatching agent that has returns it was not told about. */
509
+ /** A conductor call the owner's standing grant covers is answered here at
510
+ * once, and its request is left off the observation so it never becomes a
511
+ * return. Anything else, or an answer that failed, is left for the owner. */
512
+ async grantAnswered(receipt, worker) {
513
+ const parsed = approvalObservation.safeParse(worker.approval);
514
+ const conductor = parsed.success ? parsed.data.conductor : undefined;
515
+ if (!parsed.success || !conductor)
516
+ return worker;
517
+ const grant = await this.grant({ action: conductor.action, project: conductor.project, computer: conductor.computer }).catch(() => undefined);
518
+ if (!grant)
519
+ return worker;
520
+ try {
521
+ await this.sendAnswer(receipt, parsed.data.actionId, "approve");
522
+ }
523
+ catch {
524
+ return worker;
525
+ }
526
+ logger.info("dispatch", `Approved ${conductor.action} for ${receipt.computer} ${receipt.label} under grant ${grant.scope}.`);
527
+ const { approval: _answered, ...rest } = worker;
528
+ return rest;
529
+ }
530
+ /** Type one line into each idle dispatching agent that has returns it was
531
+ * not told about. A pane still working is tried again on the next tick. */
231
532
  async notify() {
232
533
  const waiting = (await dispatchStatus()).filter(receipt => receipt.origin && receipt.returned && !receipt.returned.read && !receipt.returned.notifiedAt);
534
+ let busy = false;
233
535
  const byOrigin = new Map();
234
536
  for (const receipt of waiting)
235
537
  byOrigin.set(originKey(receipt.origin), [...byOrigin.get(originKey(receipt.origin)) ?? [], receipt]);
@@ -239,14 +541,18 @@ export class DispatchReturns {
239
541
  const origin = receipts[0].origin;
240
542
  const pane = findPane(await this.snapshot(origin.server).catch(() => ({})), { ...origin, source: origin.agent });
241
543
  // Never interrupt: only an agent that has stopped, in the same terminal, gets a notice.
242
- if (!pane || pane.terminal_id !== origin.terminal || !["idle", "done"].includes(String(pane.agent_status)))
544
+ if (!pane || pane.terminal_id !== origin.terminal)
243
545
  continue;
546
+ if (!["idle", "done"].includes(String(pane.agent_status))) {
547
+ busy = true;
548
+ continue;
549
+ }
244
550
  const session = await this.identity(origin.server, pane).catch(() => undefined);
245
551
  const target = targetSchema.safeParse({ server: origin.server, workspace: origin.workspace, tab: origin.tab, pane: origin.pane, source: origin.agent, session });
246
552
  if (!target.success)
247
553
  continue;
248
554
  this.lastNotice.set(key, this.now());
249
- const sent = await this.deliver(target.data, noticeLine(receipts)).catch(() => ({ delivered: false }));
555
+ const sent = await this.deliver(target.data, noticeLine(receipts), noticeDeliveryId(receipts)).catch(() => ({ delivered: false }));
250
556
  if (!sent.delivered)
251
557
  continue;
252
558
  const at = new Date(this.now()).toISOString();
@@ -259,6 +565,7 @@ export class DispatchReturns {
259
565
  }).catch(() => undefined);
260
566
  }
261
567
  }
568
+ this.noticesDue = busy;
262
569
  }
263
570
  /** Every unread return, oldest first, marked read as it is handed over. */
264
571
  async take() {