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