@nathanstephenson/flow 0.1.0

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 (141) hide show
  1. package/README.md +641 -0
  2. package/build/workflow-runtime.cjs +213964 -0
  3. package/dist/backend/claude/async-queue.js +44 -0
  4. package/dist/backend/claude/auto-compaction.js +10 -0
  5. package/dist/backend/claude/background-calls.js +116 -0
  6. package/dist/backend/claude/enquiries.js +162 -0
  7. package/dist/backend/claude/index.js +1138 -0
  8. package/dist/backend/claude/mcp.js +55 -0
  9. package/dist/backend/claude/permissions.js +106 -0
  10. package/dist/backend/claude/streamed-message.js +120 -0
  11. package/dist/backend/claude/subagents.js +128 -0
  12. package/dist/backend/claude/workflow-parent.js +12 -0
  13. package/dist/backend/claude/workflow-processes.js +95 -0
  14. package/dist/backend/claude/workflow-subagent.js +234 -0
  15. package/dist/backend/effort.js +30 -0
  16. package/dist/backend/fake/index.js +570 -0
  17. package/dist/backend/mcp.js +190 -0
  18. package/dist/backend/pi/auto-compaction.js +16 -0
  19. package/dist/backend/pi/background-calls.js +56 -0
  20. package/dist/backend/pi/enquiries.js +63 -0
  21. package/dist/backend/pi/index.js +597 -0
  22. package/dist/backend/pi/mcp.js +35 -0
  23. package/dist/backend/pi/subagents.js +23 -0
  24. package/dist/backend/pi/work.js +104 -0
  25. package/dist/backend/pi/workflow-parent.js +21 -0
  26. package/dist/backend/pi/workflow-subagent.js +199 -0
  27. package/dist/backend/registry.js +34 -0
  28. package/dist/backend/types.js +1 -0
  29. package/dist/backend/workflow-tools.js +25 -0
  30. package/dist/build-id +1 -0
  31. package/dist/cli/application.js +397 -0
  32. package/dist/cli/bootstrap.js +535 -0
  33. package/dist/cli/host-control.js +100 -0
  34. package/dist/cli/install-guard.js +270 -0
  35. package/dist/cli/install-process.js +52 -0
  36. package/dist/cli/main.js +12 -0
  37. package/dist/cli/update.js +128 -0
  38. package/dist/client/connection.js +183 -0
  39. package/dist/client/context-usage.js +66 -0
  40. package/dist/client/diff.js +36 -0
  41. package/dist/client/enquiry.js +105 -0
  42. package/dist/client/markdown.js +192 -0
  43. package/dist/client/model-choices.js +32 -0
  44. package/dist/client/permission.js +60 -0
  45. package/dist/client/project-name.js +19 -0
  46. package/dist/client/reduce.js +463 -0
  47. package/dist/client/relative-time.js +30 -0
  48. package/dist/client/scope-kind.js +28 -0
  49. package/dist/client/search.js +136 -0
  50. package/dist/client/session-label.js +9 -0
  51. package/dist/client/status.js +84 -0
  52. package/dist/client/tool-chains.js +52 -0
  53. package/dist/client/tool-summary.js +98 -0
  54. package/dist/daemon/auth.js +590 -0
  55. package/dist/daemon/config-store.js +183 -0
  56. package/dist/daemon/config.js +687 -0
  57. package/dist/daemon/credential-redaction.js +9 -0
  58. package/dist/daemon/git.js +312 -0
  59. package/dist/daemon/host-control-routes.js +29 -0
  60. package/dist/daemon/host.js +2343 -0
  61. package/dist/daemon/http.js +19 -0
  62. package/dist/daemon/log.js +44 -0
  63. package/dist/daemon/mcp-auth.js +164 -0
  64. package/dist/daemon/models.js +85 -0
  65. package/dist/daemon/ownership.js +104 -0
  66. package/dist/daemon/projects.js +317 -0
  67. package/dist/daemon/publish.js +289 -0
  68. package/dist/daemon/pull-request.js +198 -0
  69. package/dist/daemon/runtime.js +100 -0
  70. package/dist/daemon/secret-store.js +65 -0
  71. package/dist/daemon/server.js +827 -0
  72. package/dist/daemon/shell.js +220 -0
  73. package/dist/daemon/skills.js +104 -0
  74. package/dist/daemon/stack-metadata.js +24 -0
  75. package/dist/daemon/stack.js +743 -0
  76. package/dist/daemon/store.js +130 -0
  77. package/dist/daemon/summariser.js +476 -0
  78. package/dist/daemon/workflow-execution-routes.js +105 -0
  79. package/dist/daemon/workflow-executions.js +1018 -0
  80. package/dist/daemon/workflow-mcp.js +20 -0
  81. package/dist/daemon/workflow-routes.js +102 -0
  82. package/dist/protocol/attachments.js +59 -0
  83. package/dist/protocol/commands.js +1 -0
  84. package/dist/protocol/events.js +20 -0
  85. package/dist/protocol/fonts.js +26 -0
  86. package/dist/protocol/git.js +12 -0
  87. package/dist/protocol/mcp.js +51 -0
  88. package/dist/protocol/projects.js +21 -0
  89. package/dist/protocol/publish.js +1 -0
  90. package/dist/protocol/pull-request.js +1 -0
  91. package/dist/protocol/secrets.js +4 -0
  92. package/dist/protocol/settings.js +63 -0
  93. package/dist/protocol/shells.js +8 -0
  94. package/dist/protocol/skills.js +16 -0
  95. package/dist/protocol/stack.js +41 -0
  96. package/dist/protocol/workflow-executions.js +1 -0
  97. package/dist/protocol/workflows.js +1 -0
  98. package/dist/tui/app.js +518 -0
  99. package/dist/tui/keys.js +54 -0
  100. package/dist/tui/render.js +366 -0
  101. package/dist/web/assets.js +10 -0
  102. package/dist/web/embedded.js +12 -0
  103. package/dist/web/manifest.js +70 -0
  104. package/dist/workflows/decisions.js +65 -0
  105. package/dist/workflows/executors.js +132 -0
  106. package/dist/workflows/graph.js +276 -0
  107. package/dist/workflows/json-schema.js +49 -0
  108. package/dist/workflows/loops.js +102 -0
  109. package/dist/workflows/mcp.js +18 -0
  110. package/dist/workflows/records.js +111 -0
  111. package/dist/workflows/recovery.js +25 -0
  112. package/dist/workflows/runtime-asset.js +17 -0
  113. package/dist/workflows/runtime-libs.js +1 -0
  114. package/dist/workflows/runtime-settings.js +23 -0
  115. package/dist/workflows/runtime.js +343 -0
  116. package/dist/workflows/scheduler.js +573 -0
  117. package/dist/workflows/schema.js +161 -0
  118. package/dist/workflows/store.js +93 -0
  119. package/package.json +87 -0
  120. package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
  121. package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
  122. package/web/dist/assets/index-BC0gLS53.js +106 -0
  123. package/web/dist/assets/index-CCeZYKES.css +2 -0
  124. package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  125. package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  126. package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  127. package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  128. package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  129. package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  130. package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  131. package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
  132. package/web/dist/assets/select-6i3wxovH.js +1 -0
  133. package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
  134. package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
  135. package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
  136. package/web/dist/assets/switch-ftZleVB8.js +6 -0
  137. package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
  138. package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
  139. package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
  140. package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
  141. package/web/dist/index.html +31 -0
@@ -0,0 +1,2343 @@
1
+ import { credentialKey } from "./credential-redaction.js";
2
+ import { randomUUID } from "node:crypto";
3
+ import { realpathSync } from "node:fs";
4
+ import { resolve } from "node:path";
5
+ import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
6
+ import { stackStatus, actionStackStatus, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
7
+ import { gitStatus, snapshot, target, branchChanges, canNameBranch, publish } from "./publish.js";
8
+ import { resolveDefaultBackend } from "../protocol/settings.js";
9
+ import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
10
+ import { deriveStatus, railBand } from "../client/status.js";
11
+ // `switchBranch` is aliased because this class has a method of that name: the method is the
12
+ // Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
13
+ import { createWorktree, head, isClean, isRepository, removeWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
14
+ import { SessionLog } from "./log.js";
15
+ import { probeModels } from "./models.js";
16
+ import { probeSkills } from "./skills.js";
17
+ import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare, workflowNameInput } from "./summariser.js";
18
+ /**
19
+ * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
20
+ * Scope that is not a repository, a checkout git itself refused.
21
+ *
22
+ * Named for its subject the way `ConfigError` is, and its message written to be read by whoever
23
+ * sent the command. That is the whole distinction it exists to draw: a refusal is the caller's to
24
+ * fix and is safe to pass back, while anything else is ours and becomes a 500.
25
+ */
26
+ export class CommandRefused extends Error {
27
+ }
28
+ /** Owns every Agent Session, and the Steering Queue that sits above all backends (ADR 0002). */
29
+ export class SessionHost {
30
+ sessions = new Map();
31
+ backends = new Map();
32
+ /** Model probes by backend name, held in flight rather than resolved — see `models`. */
33
+ modelProbes = new Map();
34
+ /**
35
+ * Skill probes by Backend Adapter and Scope, held *only* while in flight — see `skillsFor`.
36
+ *
37
+ * Keyed on both because a Skill list is a fact about a Scope read through an adapter, and the two
38
+ * adapters disagree about what a Skill is. `modelProbes` gets away with a bare name because it has
39
+ * one dimension.
40
+ */
41
+ skillProbes = new Map();
42
+ /**
43
+ * One Summary Model session, booted before a naming needs it (ADR 0020).
44
+ *
45
+ * Belongs to no Agent Session, and is deliberately not wired to `announceClosed`, the reaper or
46
+ * `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
47
+ */
48
+ summarySpare = new SummaryModelSpare();
49
+ stackReviews = new Map();
50
+ gitOperations = new Set();
51
+ closingScopes = new Set();
52
+ publishReviews = new Map();
53
+ refuseGitOperation(scope) {
54
+ if (this.gitOperations.has(scopeKey(scope)))
55
+ throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
56
+ if (this.closingScopes.has(scopeKey(scope)))
57
+ throw new CommandRefused("A Backend Session in this Scope is stopping. Wait for it to finish.");
58
+ }
59
+ async stopBackendSession(scope, session, sessionId) {
60
+ const key = scopeKey(scope);
61
+ this.closingScopes.add(key);
62
+ try {
63
+ if (this.workflowOwner)
64
+ await this.workflowOwner.stop(sessionId);
65
+ await session?.dispose();
66
+ }
67
+ finally {
68
+ this.closingScopes.delete(key);
69
+ }
70
+ }
71
+ async withGitOperation(scope, work) {
72
+ this.refuseGitOperation(scope);
73
+ const key = scopeKey(scope);
74
+ if ([...this.sessions.values()].some((record) => scopeKey(record.scope) === key && (record.turnInFlight || record.reviving || record.buffered !== undefined))) {
75
+ throw new CommandRefused("An Agent Session in this Scope is running or otherwise occupied; abort the turn or wait for it to finish before changing Git state.");
76
+ }
77
+ if ([...this.sessions.values()].some((record) => scopeKey(record.scope) === key && (record.openSubagentIds.size > 0 || record.openBackgroundCallIds.size > 0))) {
78
+ throw new CommandRefused("A Subagent or Background Call is still working in this Scope. Wait for it to finish before changing Git state.");
79
+ }
80
+ this.gitOperations.add(key);
81
+ try {
82
+ return await work();
83
+ }
84
+ catch (error) {
85
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
86
+ }
87
+ finally {
88
+ this.gitOperations.delete(key);
89
+ }
90
+ }
91
+ async prepareStack(sessionId, action) {
92
+ if (action !== "submit" && action !== "sync")
93
+ throw new CommandRefused("Invalid Stack review action.");
94
+ const record = this.record(sessionId);
95
+ return this.withGitOperation(record.scope, async () => {
96
+ this.stackReviews.delete(sessionId);
97
+ await cleanStack(record.scope);
98
+ const status = await actionStackStatus(record.scope);
99
+ if (!status.view)
100
+ throw new Error(status.problem ?? "No stack found.");
101
+ const review = { token: randomUUID(), action, view: status.view };
102
+ this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
103
+ return review;
104
+ });
105
+ }
106
+ async changeStack(sessionId, input) {
107
+ const record = this.record(sessionId);
108
+ return this.withGitOperation(record.scope, async () => {
109
+ if (input.action === "submit" || input.action === "sync") {
110
+ const saved = this.stackReviews.get(sessionId);
111
+ this.stackReviews.delete(sessionId);
112
+ if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
113
+ throw new Error("This Stack review expired. Review again.");
114
+ await cleanStack(record.scope);
115
+ const status = await actionStackStatus(record.scope);
116
+ if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
117
+ throw new Error("The reviewed stack changed. Review again.");
118
+ }
119
+ try {
120
+ return await changeStack(record.scope, input);
121
+ }
122
+ finally {
123
+ for (const other of this.sessions.values()) {
124
+ if (scopeKey(other.scope) !== scopeKey(record.scope))
125
+ continue;
126
+ this.stackReviews.delete(other.id);
127
+ this.publishReviews.delete(other.id);
128
+ await this.refreshBranch(other);
129
+ other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
130
+ }
131
+ }
132
+ });
133
+ }
134
+ async assistStack(sessionId) {
135
+ const record = this.record(sessionId);
136
+ await this.withGitOperation(record.scope, async () => {
137
+ const status = await actionStackStatus(record.scope);
138
+ if (!status.rebasing)
139
+ throw new Error("No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
140
+ });
141
+ await this.send(sessionId, stackConflictMessage, "now");
142
+ }
143
+ async gitStatus(sessionId) {
144
+ return gitStatus(this.record(sessionId).scope);
145
+ }
146
+ async preparePublish(sessionId) {
147
+ const record = this.record(sessionId);
148
+ return this.withGitOperation(record.scope, async () => {
149
+ this.publishReviews.delete(sessionId);
150
+ for (const [id, review] of this.publishReviews)
151
+ if (review.expires < Date.now())
152
+ this.publishReviews.delete(id);
153
+ const { input: changes, ...reviewed } = await snapshot(record.scope);
154
+ const destination = await target(record.scope, reviewed.branch);
155
+ const committed = await branchChanges(record.scope, destination);
156
+ if (reviewed.files.length === 0 && committed.commits.length === 0 && !destination.pr)
157
+ throw new CommandRefused("There are no changes to publish.");
158
+ let text = { commitMessage: "", title: destination.pr?.title ?? "", body: "" };
159
+ let warning;
160
+ const model = this.summaryModel?.(record.backendName);
161
+ try {
162
+ if (!model)
163
+ throw new Error("No Summary Model is configured. Choose one in Settings, or enter publish text below.");
164
+ text = await summarisePublish({ backend: this.backendFor(model.backend), modelId: model.modelId, text: `${changes}\nCommitted branch changes:\n${committed.input}` });
165
+ }
166
+ catch (error) {
167
+ warning = `Enter publish text manually. ${error instanceof Error ? error.message : String(error)}`;
168
+ }
169
+ const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
170
+ ? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
171
+ : undefined;
172
+ delete text.suggestedBranch;
173
+ const token = randomUUID();
174
+ this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
175
+ return { ...text, ...(suggestion ? { suggestedBranch: suggestion } : {}), token, files: reviewed.files, committedFiles: committed.files, commits: committed.commits, branch: reviewed.branch, defaultBranch: destination.defaultBranch, ...(destination.baseBranch ? { baseBranch: destination.baseBranch } : {}), ...(destination.pr ? { pr: destination.pr } : {}), ...(warning ? { warning } : {}) };
176
+ });
177
+ }
178
+ async publish(sessionId, input) {
179
+ const record = this.record(sessionId);
180
+ return this.withGitOperation(record.scope, async () => {
181
+ const review = this.publishReviews.get(sessionId);
182
+ if (!review || review.token !== input.token || review.expires < Date.now())
183
+ throw new CommandRefused("This Publish review expired. Open Publish again.");
184
+ this.publishReviews.delete(sessionId);
185
+ try {
186
+ return await publish(record.scope, review.snapshot, review.target, input);
187
+ }
188
+ finally {
189
+ for (const other of this.sessions.values()) {
190
+ if (scopeKey(other.scope) !== scopeKey(record.scope))
191
+ continue;
192
+ await this.refreshBranch(other);
193
+ other.pendingBranchNote = "[Flow] Git publishing was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
194
+ }
195
+ }
196
+ });
197
+ }
198
+ store;
199
+ retention;
200
+ standingAuthorisations;
201
+ allowTool;
202
+ defaultBackend;
203
+ defaultModel;
204
+ autoCompaction;
205
+ defaultEffort;
206
+ summaryModel;
207
+ closedListeners = new Set();
208
+ keptListeners = new Set();
209
+ mcpConnections;
210
+ mcpAuth;
211
+ resolveSecret;
212
+ constructor(options = {}) {
213
+ this.mcpConnections = options.mcpConnections;
214
+ this.mcpAuth = options.mcpAuth;
215
+ this.resolveSecret = options.resolveSecret;
216
+ this.store = options.store;
217
+ this.retention = options.retention ?? "never";
218
+ this.standingAuthorisations = options.standingAuthorisations;
219
+ this.allowTool = options.allowTool;
220
+ this.defaultBackend = options.defaultBackend;
221
+ this.defaultModel = options.defaultModel;
222
+ this.autoCompaction = options.autoCompaction;
223
+ this.defaultEffort = options.defaultEffort;
224
+ this.summaryModel = options.summaryModel;
225
+ }
226
+ /**
227
+ * Notified when an Agent Session stops being something its owner is working in — Settled, Ended
228
+ * or Reaped. Dormant is deliberately not one of these: it says the Backend Session went away, not
229
+ * that the reader did.
230
+ *
231
+ * An observer rather than a direct call into the Shells, so the host stays ignorant that Shells
232
+ * exist. It owns Agent Sessions; what else hangs off one is not its business.
233
+ */
234
+ onSessionClosed(listener) {
235
+ this.closedListeners.add(listener);
236
+ return () => this.closedListeners.delete(listener);
237
+ }
238
+ announceClosed(sessionId) {
239
+ for (const listener of this.closedListeners)
240
+ listener(sessionId);
241
+ }
242
+ /**
243
+ * Notified when a reap left a worktree on disk rather than removing it.
244
+ *
245
+ * Only a clean worktree is removed: a branch ref always survives a reap, so no commit is ever
246
+ * lost, but uncommitted and untracked work would be — and deleting that on a retention timer,
247
+ * from a sweep nobody is watching, is a second destructive act ADR 0006 does not license.
248
+ *
249
+ * An observer rather than a log call, for the reason `onSessionClosed` is one: the host owns
250
+ * Agent Sessions, not the daemon's stderr.
251
+ */
252
+ onWorktreeKept(listener) {
253
+ this.keptListeners.add(listener);
254
+ return () => this.keptListeners.delete(listener);
255
+ }
256
+ registerBackend(backend) {
257
+ this.backends.set(backend.name, backend);
258
+ }
259
+ backendNames() {
260
+ return [...this.backends.keys()];
261
+ }
262
+ /**
263
+ * What models each Backend Adapter can reach — what the Providers section offers to choose from.
264
+ *
265
+ * **Memoised for the life of the daemon**, which is a deliberate departure from `/api/branches`
266
+ * and `/api/directories`, the two other queries beside the Settings. Those are asked fresh
267
+ * because their answers change outside Flow between one keystroke and the next. This one changes
268
+ * when an account's entitlements do — rarely — and answering it spawns a process per backend, so
269
+ * asking on every render of a settings page would be a real cost for a list that had not moved.
270
+ * `refresh` is the Check again button, for the day it has.
271
+ *
272
+ * In flight rather than resolved is what is remembered, so two clients opening the page at once
273
+ * spawn one probe between them rather than one each.
274
+ */
275
+ async models(scope, refresh = false) {
276
+ if (refresh)
277
+ this.modelProbes.clear();
278
+ const probes = [...this.backends.values()].map((backend) => {
279
+ const held = this.modelProbes.get(backend.name);
280
+ if (held)
281
+ return held;
282
+ const probe = probeModels(backend, scope);
283
+ this.modelProbes.set(backend.name, probe);
284
+ return probe;
285
+ });
286
+ return await Promise.all(probes);
287
+ }
288
+ /**
289
+ * Which Skills a Scope offers through one Backend Adapter, with no Agent Session in it.
290
+ *
291
+ * The counterpart to `listSkills` above, which answers the same question for an Agent Session that
292
+ * already exists and so costs nothing. This one has to open a Backend Session to ask, which is why
293
+ * it is here and not folded into that: they share a word and nothing else, and a shared helper
294
+ * would be one `try` bought by dragging one of two return shapes onto the other.
295
+ *
296
+ * **Held in flight and never after.** The entry is deleted as the probe settles, so two clients
297
+ * asking at once spawn one backend between them, and the next ask after that spawns another. That
298
+ * is deliberately unlike `models` directly above: a model list changes when an account's
299
+ * entitlements do, while a Skill directory changes when somebody saves a file, and ADR 0020
300
+ * already drew that line between `/api/models` and `/api/branches`. Skills are on the
301
+ * `/api/branches` side. What makes the spawn affordable is the client asking early — when its
302
+ * Scope field settles rather than when the menu opens — not the host holding a stale answer.
303
+ *
304
+ * Never throws, so the route never falls through to `serve`'s blanket 500: an unknown Backend
305
+ * Adapter is reported as a `problem` like any other reason a list might be empty.
306
+ */
307
+ async skillsFor(scope, backendName) {
308
+ const backend = this.backends.get(backendName);
309
+ if (!backend) {
310
+ return { backend: backendName, scope, skills: [], problem: `No backend named ${backendName}` };
311
+ }
312
+ const key = `${backendName}\n${scope}`;
313
+ const held = this.skillProbes.get(key);
314
+ if (held)
315
+ return await held;
316
+ const probe = probeSkills(backend, scope).finally(() => {
317
+ this.skillProbes.delete(key);
318
+ });
319
+ this.skillProbes.set(key, probe);
320
+ return await probe;
321
+ }
322
+ logFor(sessionId) {
323
+ return this.record(sessionId).log;
324
+ }
325
+ statusOf(sessionId) {
326
+ return this.activityOf(this.record(sessionId));
327
+ }
328
+ /**
329
+ * Three `Set.size` reads and a comparison, because this runs for every Agent Session on every
330
+ * `GET /api/sessions` — the same budget `branch` is held on the record to stay inside. Independent
331
+ * workflow activity is a separate scheduler-map lookup when summaries are assembled below.
332
+ */
333
+ activityOf(record) {
334
+ return deriveStatus({
335
+ lifecycle: record.lifecycle,
336
+ turnInFlight: record.turnInFlight,
337
+ awaiting: record.openPermissionIds.size > 0 || record.openEnquiryIds.size > 0,
338
+ });
339
+ }
340
+ list() {
341
+ return [...this.sessions.values()]
342
+ .map((record) => ({
343
+ id: record.id,
344
+ scope: record.scope,
345
+ backend: record.backendName,
346
+ status: this.activityOf(record),
347
+ title: record.title,
348
+ restingAt: record.restingAt,
349
+ activeSubagents: record.openSubagentIds.size,
350
+ activeBackgroundCalls: record.openBackgroundCallIds.size,
351
+ activeWorkflows: this.workflowOwner?.active(record.id) ?? 0,
352
+ ...(record.settledAt === undefined ? {} : { settledAt: record.settledAt }),
353
+ lastSeq: record.log.lastSeq,
354
+ ...(record.capabilities ? { capabilities: record.capabilities } : {}),
355
+ ...(record.branch ? { branch: record.branch } : {}),
356
+ ...(record.worktree ? { worktree: true } : {}),
357
+ }))
358
+ /*
359
+ * Banded by how alive an Agent Session is, then by recency inside each band.
360
+ *
361
+ * One recency key alone put an Agent Session that finished ten minutes ago above one still
362
+ * working, which is backwards: the top of a list is where a reader looks for what is
363
+ * happening. Bands fix the order without giving back the stability they were introduced for —
364
+ * a row moves when its band changes and at no other time, so a turn streams for an hour
365
+ * without touching the list.
366
+ *
367
+ * Settled and Ended sort by when they were filed away rather than by `restingAt`, which for
368
+ * them is whenever they happened to go idle beforehand — ordering them by something their
369
+ * owner never did.
370
+ */
371
+ .sort((left, right) => {
372
+ const band = railBand(left) - railBand(right);
373
+ if (band !== 0)
374
+ return band;
375
+ // `?? restingAt` on both sides rather than a branch on whether each has been Settled: the
376
+ // bottom band holds Settled and Ended together and only one of them carries `settledAt`, so
377
+ // comparing different fields per row would make this comparator non-transitive.
378
+ const by = (summary) => summary.settledAt ?? summary.restingAt;
379
+ return by(right).localeCompare(by(left));
380
+ });
381
+ }
382
+ /**
383
+ * Load previously persisted Agent Sessions as Dormant (ADR 0003): transcripts readable, nothing
384
+ * running, no money spent until someone asks.
385
+ */
386
+ async load() {
387
+ if (!this.store)
388
+ return;
389
+ for (const id of await this.store.listSessionIds()) {
390
+ const meta = this.store.readMeta(id);
391
+ if (!meta || this.sessions.has(id))
392
+ continue;
393
+ const entries = this.store.readEntries(id);
394
+ const record = {
395
+ id: meta.id,
396
+ scope: meta.scope,
397
+ backendName: meta.backend,
398
+ log: this.newLog(meta.id, entries),
399
+ session: undefined,
400
+ reviving: undefined,
401
+ lifecycle: lifecycleFrom(meta),
402
+ turnInFlight: false,
403
+ openPermissionIds: new Set(openPermissions(entries).map((open) => open.callId)),
404
+ openEnquiryIds: new Set(openEnquiries(entries).map((open) => open.askId)),
405
+ openSubagentIds: new Set(openSubagents(entries).map((open) => open.subagentId)),
406
+ openBackgroundCallIds: new Set(openBackgroundCalls(entries).map((open) => open.callId)),
407
+ // A meta written before the split has neither, and `updatedAt` is what both used to be.
408
+ restingAt: meta.restingAt ?? meta.updatedAt,
409
+ settledAt: meta.settledAt ?? (lifecycleFrom(meta) === "settled" ? meta.updatedAt : undefined),
410
+ buffered: undefined,
411
+ queue: [],
412
+ title: meta.title,
413
+ // Read leniently, in config.json's manner: a meta.json written before Agent Sessions were
414
+ // named by a model has no `titleSource`, and the sentinel that used to stand in for one
415
+ // still answers correctly for it. So nothing has to be migrated, and an old session whose
416
+ // title is still its Scope is titled by its next message exactly as it always was.
417
+ titleSource: meta.titleSource ?? (meta.title === meta.scope ? "scope" : "first-line"),
418
+ titleGeneration: 0,
419
+ // Recovered from the transcript rather than by asking git, for the reason capabilities are:
420
+ // a daemon holding fifty Agent Sessions would otherwise spawn fifty processes on the way up,
421
+ // to answer a question the next Revive or turn re-asks anyway.
422
+ branch: branchFrom(entries),
423
+ branchGeneration: 0,
424
+ worktree: meta.worktree,
425
+ pendingBranchNote: undefined,
426
+ capabilities: capabilitiesFrom(entries),
427
+ spend: spendFrom(entries),
428
+ mcpConnectionIds: meta.mcpConnectionIds ?? [],
429
+ resumeToken: meta.resumeToken,
430
+ modelId: meta.modelId,
431
+ effort: meta.effort,
432
+ createdAt: meta.createdAt,
433
+ updatedAt: meta.updatedAt,
434
+ };
435
+ this.sessions.set(id, record);
436
+ // Empties all three sets seeded above: a torn turn's prompts and Subagents are closed here,
437
+ // and nothing can be open on an Agent Session with no Backend Session attached.
438
+ this.closeTornTurn(record, entries);
439
+ // Dormancy has to be visible to a client reducing the transcript, or a session with nothing
440
+ // running still looks ready to type at. A clean shutdown already recorded it.
441
+ if (record.lifecycle === "dormant" && lastEventType(record.log.since(0)) !== "session_dormant") {
442
+ record.log.append({ type: "session_dormant", reason: "host restarted" });
443
+ }
444
+ this.persist(record);
445
+ }
446
+ await this.reap();
447
+ }
448
+ async create(options) {
449
+ const connections = this.mcpConnections?.() ?? [];
450
+ if (options.mcpConnectionIds !== undefined && (!Array.isArray(options.mcpConnectionIds) || options.mcpConnectionIds.some((id) => typeof id !== "string")))
451
+ throw new Error("Invalid MCP selection");
452
+ const mcpConnectionIds = connections.filter((connection) => options.mcpConnectionIds ? options.mcpConnectionIds.includes(connection.id) : connection.enabledByDefault).map((connection) => connection.id);
453
+ const backendName = options.backend ?? resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
454
+ if (backendName === undefined)
455
+ throw new Error("No backends available");
456
+ const backend = this.backendFor(backendName);
457
+ const worktree = options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined;
458
+ // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
459
+ // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
460
+ // that is not there.
461
+ const scope = worktree?.path ?? options.scope;
462
+ const id = randomUUID();
463
+ const now = new Date().toISOString();
464
+ const record = {
465
+ id,
466
+ scope,
467
+ backendName: backend.name,
468
+ log: this.newLog(id),
469
+ session: undefined,
470
+ reviving: undefined,
471
+ lifecycle: "live",
472
+ turnInFlight: false,
473
+ openPermissionIds: new Set(),
474
+ openEnquiryIds: new Set(),
475
+ openSubagentIds: new Set(),
476
+ openBackgroundCallIds: new Set(),
477
+ // A brand new Agent Session is its owner's turn from the moment it exists, which is what puts
478
+ // it at the top of the rail.
479
+ restingAt: now,
480
+ settledAt: undefined,
481
+ buffered: undefined,
482
+ queue: [],
483
+ title: scope,
484
+ titleSource: "scope",
485
+ titleGeneration: 0,
486
+ branch: undefined,
487
+ branchGeneration: 0,
488
+ worktree,
489
+ pendingBranchNote: undefined,
490
+ capabilities: undefined,
491
+ spend: undefined,
492
+ mcpConnectionIds,
493
+ resumeToken: undefined,
494
+ /*
495
+ * Resolved here and never again.
496
+ *
497
+ * Not in `startBackendSession`, which is the tempting place: that path also runs on a Revive,
498
+ * so reading the Default Model there would move a week-old Dormant Agent Session onto whatever
499
+ * the default is *today*, silently, on the turn its owner came back to write. Resolving once
500
+ * and persisting to `SessionMeta.modelId` is what makes the choice stick for this session's
501
+ * life — the same shape as the Standing Authorisations snapshot in BackendCreateOptions.
502
+ */
503
+ modelId: options.modelId ?? this.defaultModel?.(backend.name),
504
+ effort: options.effort ?? this.defaultEffort?.(backend.name),
505
+ createdAt: now,
506
+ updatedAt: now,
507
+ };
508
+ this.sessions.set(id, record);
509
+ this.persist(record);
510
+ record.buffered = [];
511
+ const session = await this.startBackendSession(record);
512
+ record.log.append({
513
+ type: "session_started",
514
+ backend: backend.name,
515
+ scope,
516
+ capabilities: session.capabilities,
517
+ ...(worktree === undefined ? {} : { worktree: true }),
518
+ });
519
+ this.flushBuffered(record);
520
+ // After session_started, never before: the transcript has to open with it (see `buffered`).
521
+ await this.refreshBranch(record);
522
+ /*
523
+ * Somebody who has just made an Agent Session is about to type into it, and naming what they
524
+ * type means booting a Summary Model session that takes the better part of a minute. Started
525
+ * here so that most of that is paid while they are still writing.
526
+ *
527
+ * Called unconditionally, including when no Summary Model is configured, because that is also
528
+ * how a spare gets dropped when somebody clears the Setting: nothing will ever *tell* us it
529
+ * changed (ADR 0009), so a read-through is the only moment it can be noticed.
530
+ */
531
+ this.warmSummaryModel(backend.name);
532
+ return id;
533
+ }
534
+ /**
535
+ * Boot a Summary Model session ahead of needing one, or drop the one held if the Setting is gone.
536
+ *
537
+ * The backend is resolved here rather than inside the spare because `backendFor` throws for a
538
+ * name it does not know: a typo in `providers.summary.backend` must cost a worse Agent Session
539
+ * *name*, never the Agent Session itself.
540
+ */
541
+ warmSummaryModel(backendName) {
542
+ const model = this.summaryModel?.(backendName);
543
+ /*
544
+ * Three cases, and the middle one is the reason this is not a one-liner.
545
+ *
546
+ * No Summary Model at all: drop whatever is held. This is the only moment a Setting somebody
547
+ * cleared is ever noticed, because nothing pushes a change (ADR 0009).
548
+ *
549
+ * A Summary Model with automatic naming *off*: leave the spare exactly as it is. Not warmed,
550
+ * because nothing will need one until somebody clicks Rename — and that path warms its own
551
+ * replacement afterwards, so a second rename is fast without a daemon nobody is renaming in
552
+ * holding an idle process. And not dropped either: a spare a rename just warmed must survive
553
+ * the next Agent Session being created, or the two would fight over it.
554
+ */
555
+ if (!model) {
556
+ this.summarySpare.warm(undefined, undefined);
557
+ return;
558
+ }
559
+ if (!model.automatic)
560
+ return;
561
+ let backend;
562
+ try {
563
+ backend = this.backendFor(model.backend);
564
+ }
565
+ catch {
566
+ backend = undefined;
567
+ }
568
+ this.summarySpare.warm(backend, model);
569
+ }
570
+ /**
571
+ * Create the worktree a `create` asked for.
572
+ *
573
+ * Throws rather than returning a failure, because its caller has someone waiting on a session id
574
+ * and there is nothing partial to hand back: no Agent Session is created at all.
575
+ */
576
+ async cutWorktree(repo, options) {
577
+ // A host with no state root has nowhere to put a worktree. Said plainly rather than left to
578
+ // fail as an undefined path, the way an unavailable pty is reported.
579
+ if (!this.store)
580
+ throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
581
+ if (!isRepository(repo))
582
+ throw new CommandRefused(`${repo} is not a git repository`);
583
+ const created = await createWorktree({
584
+ repo,
585
+ from: options.from,
586
+ under: this.store.worktreesRoot(),
587
+ ...(options.branch === undefined ? {} : { branch: options.branch }),
588
+ });
589
+ if (!created.ok)
590
+ throw new CommandRefused(created.failure.message);
591
+ return { path: created.value.path, repo, branch: created.value.branch };
592
+ }
593
+ /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
594
+ async revive(sessionId) {
595
+ const record = this.record(sessionId);
596
+ this.refuseGitOperation(record.scope);
597
+ if (record.session)
598
+ return;
599
+ if (record.lifecycle === "ended")
600
+ throw new Error(`Session ${sessionId} has ended`);
601
+ if (record.reviving)
602
+ return await record.reviving;
603
+ const reviving = this.reviveOnce(record);
604
+ record.reviving = reviving;
605
+ try {
606
+ await reviving;
607
+ }
608
+ finally {
609
+ // Cleared even on failure, so a backend that would not start is retried by the next send.
610
+ record.reviving = undefined;
611
+ }
612
+ }
613
+ async reviveOnce(record) {
614
+ const fromSeq = record.log.lastSeq;
615
+ record.buffered = [];
616
+ // A backend that died without saying so can have left a prompt open with no path having run.
617
+ // Self-deduplicating, so on every ordinary Revive this appends nothing.
618
+ this.closeOpenEnquiries(record, record.log.since(0));
619
+ this.closeOpenPermissions(record, record.log.since(0));
620
+ this.closeOpenSubagents(record, record.log.since(0));
621
+ this.closeOpenBackgroundCalls(record, record.log.since(0));
622
+ await this.startBackendSession(record);
623
+ record.lifecycle = "live";
624
+ // Un-settled, so the retention window starts again from the next Settle rather than from the
625
+ // one this Revive just undid.
626
+ record.settledAt = undefined;
627
+ record.restingAt = new Date().toISOString();
628
+ record.log.append({ type: "revived", fromSeq });
629
+ this.flushBuffered(record);
630
+ // A Dormant Agent Session may have sat for a week while its Scope was moved by hand.
631
+ await this.refreshBranch(record);
632
+ // Workflow input never Revives a Dormant parent by itself. Once a human explicitly Revives it,
633
+ // resume the retained relay queue without requiring another Workflow event.
634
+ if (this.workflowInputs.has(record.id))
635
+ this.queueWorkflowDrain(record.id);
636
+ }
637
+ /**
638
+ * `when` is required rather than defaulted. A default of "now" would hand the next caller the one
639
+ * value that can bypass the Steering Queue, and "after_turn" already means "queue if busy, else
640
+ * dispatch now" — so there is no sensible default to pick. It matches `Command` either way.
641
+ */
642
+ async send(sessionId, text, when, attachments) {
643
+ const record = this.record(sessionId);
644
+ this.refuseGitOperation(record.scope);
645
+ // ADR 0003: the first message revives a Dormant session, so resuming work is one action.
646
+ if (!record.session)
647
+ await this.revive(sessionId);
648
+ // Checked before anything is written, so a refused send leaves no bytes behind.
649
+ this.refuseUnservableAttachments(record, attachments);
650
+ const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
651
+ if (when === "after_turn" && record.turnInFlight) {
652
+ record.queue.push({ id: randomUUID(), text, attachments: ids });
653
+ record.log.append(queueChanged(record.queue));
654
+ this.touch(record);
655
+ return;
656
+ }
657
+ await this.dispatch(record, { text, attachments: ids });
658
+ }
659
+ /**
660
+ * Whether this send's Attachments can be carried at all, refused before any are written down.
661
+ *
662
+ * Strict about what it *knows* is wrong and lenient about what it cannot know. The count, the
663
+ * media type and the size are facts about the request, so a client offering one this cannot use is
664
+ * refused — the rule the Settings already follow. Whether the model accepts an image is a fact
665
+ * about the backend, and the host cannot always name the model in force: `record.modelId` is
666
+ * absent whenever nobody overrode the default, which is the common case. So an unidentifiable
667
+ * model is allowed through rather than blocking every default-model session. The positive check
668
+ * belongs to the client, which reduces `model_changed` and therefore always knows.
669
+ */
670
+ refuseUnservableAttachments(record, attachments) {
671
+ if (!attachments?.length)
672
+ return;
673
+ if (attachments.length > MAX_ATTACHMENTS_PER_MESSAGE) {
674
+ throw new CommandRefused(`At most ${MAX_ATTACHMENTS_PER_MESSAGE} attachments may be sent with one message`);
675
+ }
676
+ for (const attachment of attachments) {
677
+ if (!isAttachmentMediaType(attachment.mediaType)) {
678
+ throw new CommandRefused(`${attachment.mediaType} is not an attachable media type`);
679
+ }
680
+ if (attachment.data.length > MAX_ATTACHMENT_BASE64_BYTES) {
681
+ throw new CommandRefused(`An attachment may not exceed ${MAX_ATTACHMENT_BASE64_BYTES} base64 bytes`);
682
+ }
683
+ }
684
+ const model = record.session?.capabilities.models.find((candidate) => candidate.id === record.modelId);
685
+ if (model && !model.acceptsImages) {
686
+ throw new CommandRefused(`${model.label ?? model.id} cannot be shown an attachment`);
687
+ }
688
+ }
689
+ storeOrThrow() {
690
+ if (!this.store)
691
+ throw new CommandRefused("This Session Host keeps no state, so it cannot hold an attachment");
692
+ return this.store;
693
+ }
694
+ async steerQueued(sessionId, messageId) {
695
+ const record = this.record(sessionId);
696
+ this.refuseGitOperation(record.scope);
697
+ const index = record.queue.findIndex((message) => message.id === messageId);
698
+ if (index < 0)
699
+ throw new CommandRefused("This message is no longer queued");
700
+ const [message] = record.queue.splice(index, 1);
701
+ record.log.append(queueChanged(record.queue));
702
+ await this.dispatch(record, message);
703
+ this.touch(record);
704
+ }
705
+ cancelQueued(sessionId, messageId) {
706
+ const record = this.record(sessionId);
707
+ const index = record.queue.findIndex((message) => message.id === messageId);
708
+ if (index < 0)
709
+ throw new CommandRefused("This message is no longer queued");
710
+ record.queue.splice(index, 1);
711
+ record.log.append(queueChanged(record.queue));
712
+ this.touch(record);
713
+ }
714
+ async abort(sessionId) {
715
+ const record = this.record(sessionId);
716
+ this.cancelWorkflowConfirmation(sessionId);
717
+ this.workflowNotifications.delete(sessionId);
718
+ // A parent abort only stops its current turn. Workflow completions are independent work and
719
+ // must remain queued for the now-idle parent to report.
720
+ // Aborting means stop, not stop-then-continue: queued follow-ups go too.
721
+ if (record.queue.length > 0) {
722
+ record.queue.length = 0;
723
+ record.log.append({ type: "queue_changed", pending: [] });
724
+ }
725
+ await record.session?.abort();
726
+ this.touch(record);
727
+ }
728
+ async setModel(sessionId, modelId) {
729
+ const record = this.record(sessionId);
730
+ await record.session?.setModel(modelId);
731
+ record.modelId = modelId;
732
+ this.touch(record);
733
+ }
734
+ async setEffort(sessionId, effort) {
735
+ const record = this.record(sessionId);
736
+ await record.session?.setEffort(effort);
737
+ // Remembered as asked for, not as clamped: a Revive onto a model that can serve it should.
738
+ record.effort = effort;
739
+ this.touch(record);
740
+ }
741
+ /**
742
+ * Compact this Agent Session's Conversation Context now.
743
+ *
744
+ * **A Dormant or Settled session Revives first**, the way `send` does (ADR 0003: resuming work is
745
+ * one action). This used to refuse, on the reasoning that a Revive rebuilds a Conversation Context
746
+ * only to summarise what it just rebuilt. That was simply wrong — a Revive *restores* the
747
+ * conversation from its resume token, it does not summarise it — and the case for allowing it is
748
+ * a good one: a session parked at 90% occupancy is exactly the one worth compacting, and before
749
+ * resuming is the best moment, because nothing is waiting on the turn it makes room for.
750
+ *
751
+ * Two refusals are left, and each is a state where compacting would be a lie rather than a
752
+ * failure.
753
+ *
754
+ * **A turn in flight.** The backend is mid-conversation and would be summarising a context it is
755
+ * still writing to. Queueing it instead was rejected: `abort` discards the queue wholesale, so a
756
+ * compaction would vanish with a cancelled turn and nobody would be told which of the two they
757
+ * had lost. This now also refuses a *second* compaction, because a compaction is a turn.
758
+ *
759
+ * **A backend that cannot.** Checked on `capabilities.compaction` rather than on whether the
760
+ * method exists, so an adapter cannot half-declare itself — the flag is what clients hide the
761
+ * control on, and the two must agree.
762
+ *
763
+ * **The session is occupied for the duration**, exactly as `dispatch` occupies it. A compaction
764
+ * spends money and holds the backend for minutes, and while it did not say so the Steering Queue
765
+ * believed the session idle — so a message typed during one was pushed into the backend's inbox
766
+ * ahead of the compaction instead of queueing behind it, and a second `/compact` sailed past the
767
+ * refusal above. `turn_ended` from the adapter releases it and drains the queue, the same path
768
+ * every other turn takes.
769
+ *
770
+ * No `user_message` is written. Compaction is not something anyone said, and the turn it opens is
771
+ * the backend's own work; what a reader sees is the `compacted` the adapter emits when it lands.
772
+ */
773
+ /**
774
+ * Answer an Enquiry this Agent Session is holding open.
775
+ *
776
+ * **Never Revives**, which is the one place this parts company with `send` and `compact`. Those
777
+ * carry something still meaningful after a Revive; this resolves a promise held by a Backend
778
+ * Session that no longer exists, so reviving here would start a process and spend money to answer
779
+ * nothing. Dormant, Settled and Ended are all refused, and the transcript already carries the
780
+ * `aborted` snapshot that says why.
781
+ *
782
+ * **Writes no `user_message`.** An answer is not something anyone said to the model — it is the
783
+ * input to a tool call the model itself made — and a turn is already in flight, so there is nothing
784
+ * to occupy and nothing to queue. What a reader sees is the `answered` snapshot the adapter emits.
785
+ *
786
+ * Arity is checked here rather than left to the adapter, because getting it wrong is not an error
787
+ * the model should be asked to cope with: a client sending two answers for three Questions would
788
+ * otherwise produce an `answers` map the model reads as consent nobody gave.
789
+ */
790
+ async answerEnquiry(sessionId, askId, answers) {
791
+ const relay = this.workflowEnquiryRelays.get(askId);
792
+ if (relay?.sessionId === sessionId) {
793
+ if (answers.length !== relay.questions || answers.some(answer => !answer.length || answer.some(value => typeof value !== 'string' || !value.trim())))
794
+ throw new CommandRefused('Every Workflow question needs an explicit answer');
795
+ await relay.submit(answers);
796
+ return;
797
+ }
798
+ const workflow = this.workflowConfirmations.get(askId);
799
+ if (workflow?.sessionId === sessionId) {
800
+ if (answers.length !== 1 || answers[0]?.length !== 1 || !['Recover', 'Cancel'].includes(answers[0][0]))
801
+ throw new CommandRefused('Choose Recover or Cancel');
802
+ workflow.finish(answers[0][0] === 'Recover');
803
+ return;
804
+ }
805
+ const record = this.record(sessionId);
806
+ const session = record.session;
807
+ if (!session) {
808
+ throw new CommandRefused(`Agent Session ${sessionId} is ${this.activityOf(record)}; the question it was asked can no longer be answered`);
809
+ }
810
+ // The flag, never the method — the rule `compact` sets, so an adapter cannot be half-capable.
811
+ if (!session.capabilities.enquiries || !session.answerEnquiry) {
812
+ throw new CommandRefused(`${record.backendName} cannot carry an answer to a question`);
813
+ }
814
+ const open = openEnquiries(record.log.since(0)).find((enquiry) => enquiry.askId === askId);
815
+ if (!open)
816
+ throw new CommandRefused(`That question is no longer open`);
817
+ if (answers.length !== open.questions.length) {
818
+ throw new CommandRefused(`That question has ${open.questions.length} parts and must be answered in one act`);
819
+ }
820
+ // False is a race, not a fault: the transcript said it was open and the backend says otherwise,
821
+ // which is what an abort landing between the two looks like.
822
+ if (!(await session.answerEnquiry(askId, answers))) {
823
+ throw new CommandRefused(`That question is no longer open`);
824
+ }
825
+ this.touch(record);
826
+ }
827
+ /**
828
+ * Authorise, or refuse, one tool call this Agent Session is holding open.
829
+ *
830
+ * Refused when there is no Backend Session, and **never Revives**, for the reason `answerEnquiry`
831
+ * never does: the promise this settles died with the process that held it.
832
+ *
833
+ * Unlike `answerEnquiry` it does **not** read the transcript first. That scan buys arity checking
834
+ * there, and a prompt has no arity — one decision settles one call. What is left would be an
835
+ * O(transcript) walk per decision, on a record that grows all session, to produce a nicer message
836
+ * for a race the adapter already reports by answering `false`. So this delegates, and turns the
837
+ * `false` into the refusal.
838
+ *
839
+ * An `always` is persisted **after** the callback is settled, never before. Crashing between the
840
+ * two then loses a Standing Authorisation and the next session asks once more — a cost already
841
+ * accepted for a grant made in another session. The other order would leave a tool permanently
842
+ * authorised that the human never saw run, in a turn that then died: a record of consent to
843
+ * something that did not happen.
844
+ */
845
+ async answerPermission(sessionId, callId, decision) {
846
+ const relay = this.workflowPermissionRelays.get(callId);
847
+ if (relay?.sessionId === sessionId) {
848
+ if (decision === 'always' && !relay.allowAlways)
849
+ throw new CommandRefused('This Workflow tool can only be allowed once or denied');
850
+ await relay.submit(decision);
851
+ return;
852
+ }
853
+ const record = this.record(sessionId);
854
+ const session = record.session;
855
+ if (!session) {
856
+ throw new CommandRefused(`Agent Session ${sessionId} is ${this.activityOf(record)}; what it was waiting to be allowed can no longer be authorised`);
857
+ }
858
+ // The flag, never the method — the rule `compact` sets, so an adapter cannot be half-capable.
859
+ if (!session.capabilities.permissions || !session.answerPermission) {
860
+ throw new CommandRefused(`${record.backendName} cannot be asked before it acts`);
861
+ }
862
+ /*
863
+ * Read before the decision, because deciding is what forgets it — but only for an `always`,
864
+ * which is the one decision that needs the name.
865
+ *
866
+ * `answerEnquiry` scans unconditionally because it has an arity to check. There is nothing to
867
+ * check here, so on the common path this would be an O(transcript) walk, per decision, on a
868
+ * record that grows all session — to fetch a string two of the three decisions throw away.
869
+ */
870
+ const tool = decision === "always"
871
+ ? openPermissions(record.log.since(0)).find((open) => open.callId === callId)?.tool
872
+ : undefined;
873
+ // False is a race, not a fault, and it is also what says to persist nothing: an abort landing
874
+ // between a client's click and this call must not leave a Standing Authorisation behind.
875
+ if (!(await session.answerPermission(callId, decision))) {
876
+ throw new CommandRefused(`That tool call is no longer waiting to be authorised`);
877
+ }
878
+ this.touch(record);
879
+ if (decision !== "always" || tool === undefined)
880
+ return;
881
+ try {
882
+ this.allowTool?.(tool);
883
+ }
884
+ catch (error) {
885
+ // Partial success, and the register `applyEffort` uses for exactly this shape: the tool ran, and
886
+ // only the remembering failed. Reporting it as a refusal would be a lie about what happened.
887
+ record.log.append({
888
+ type: "notice",
889
+ level: "warn",
890
+ text: `Allowed ${tool} once, but could not remember it: ${error instanceof Error ? error.message : String(error)}`,
891
+ });
892
+ this.touch(record);
893
+ }
894
+ }
895
+ async compact(sessionId, instructions) {
896
+ const record = this.record(sessionId);
897
+ this.refuseGitOperation(record.scope);
898
+ // Refused rather than left to `revive`'s own throw, which would reach the client as a 500 for
899
+ // something it should be told plainly.
900
+ if (record.lifecycle === "ended") {
901
+ throw new CommandRefused(`Agent Session ${sessionId} has Ended; it has no Conversation Context`);
902
+ }
903
+ if (!record.session)
904
+ await this.revive(sessionId);
905
+ this.refuseGitOperation(record.scope);
906
+ const session = record.session;
907
+ if (!session) {
908
+ throw new CommandRefused(`Agent Session ${sessionId} has no Backend Session to compact`);
909
+ }
910
+ if (record.turnInFlight) {
911
+ throw new CommandRefused(`Agent Session ${sessionId} is running; abort the turn or wait for it to end before compacting`);
912
+ }
913
+ if (!session.capabilities.compaction || !session.compact) {
914
+ throw new CommandRefused(`${record.backendName} cannot compact a Conversation Context`);
915
+ }
916
+ // Set here rather than left to the adapter's `turn_started`, because that is how `dispatch`
917
+ // occupies a session too: the host's own flag is what `send` consults, and it must be true
918
+ // before this returns or the very next request races it.
919
+ record.turnInFlight = true;
920
+ await session.compact(instructions);
921
+ this.touch(record);
922
+ }
923
+ /**
924
+ * The Skills this Agent Session can be sent.
925
+ *
926
+ * Answers with an empty list in every case it cannot answer properly — no Backend Session, an
927
+ * adapter with no notion of Skills, a backend that threw while reading its own disk. This is the
928
+ * opposite of `compact`'s three refusals, and deliberately: a refusal is right for an act with
929
+ * consequences and wrong for a menu. Opening one on a Dormant session must not Revive it, and must
930
+ * not put a red toast in front of someone who pressed `/` — an empty menu says "nothing to offer
931
+ * here" perfectly well.
932
+ *
933
+ * Nothing is written down, and `touch` is not called: reading a menu is not activity on an Agent
934
+ * Session, and letting it postpone a Reap would mean an idle browser tab kept sessions alive.
935
+ */
936
+ async listSkills(sessionId) {
937
+ const session = this.record(sessionId).session;
938
+ if (!session?.skills)
939
+ return [];
940
+ try {
941
+ return await session.skills();
942
+ }
943
+ catch {
944
+ return [];
945
+ }
946
+ }
947
+ /**
948
+ * Move this Agent Session's Scope to another branch.
949
+ *
950
+ * Refused while running, and running is the only status where it has to be: git would change
951
+ * files underneath a turn that is reading them, and the model has no way to be told mid-turn.
952
+ * Idle, Dormant and Settled all have nothing in flight to disturb, so git is asked and whatever
953
+ * it says is what the caller hears — git already refuses a checkout that would clobber a modified
954
+ * file, and reimplementing that judgement here would block switches engineers make by hand.
955
+ *
956
+ * The refusal lives here rather than in the request handler because `execute` is not the only
957
+ * door — the one-shot CLI and the tests call this directly — and because only the host holds
958
+ * `turnInFlight` without a gap between reading it and acting on it.
959
+ *
960
+ * Reads `turnInFlight` rather than the derived status, and the difference is a working tree. An
961
+ * Agent Session blocked on a Permission Prompt derives `awaiting`, not `running`, while its turn
962
+ * is still open around a tool call — so a status comparison here would quietly stop refusing and
963
+ * move the branch under it.
964
+ */
965
+ async switchBranch(sessionId, branch) {
966
+ const record = this.record(sessionId);
967
+ return this.withGitOperation(record.scope, () => this.switchBranchOnce(sessionId, branch));
968
+ }
969
+ async switchBranchOnce(sessionId, branch) {
970
+ const record = this.record(sessionId);
971
+ if (record.turnInFlight) {
972
+ throw new CommandRefused(`Agent Session ${sessionId} is running; abort the turn or wait for it to end before switching branch`);
973
+ }
974
+ if (!isRepository(record.scope)) {
975
+ throw new CommandRefused(`${record.scope} is not a git repository`);
976
+ }
977
+ const switched = await gitSwitchBranch(record.scope, branch);
978
+ if (!switched.ok)
979
+ throw new CommandRefused(switched.failure.message);
980
+ this.announceBranch(record, switched.value);
981
+ /*
982
+ * Held for the next message rather than sent now, and this is not a stylistic choice — the
983
+ * Steering Queue cannot carry it.
984
+ *
985
+ * `send(…, "after_turn")` only queues while a turn is in flight, and a switch is permitted only
986
+ * when one is *not*, so routing this through `send` would dispatch it immediately as its own
987
+ * turn: an agent reply nobody asked for, spending tokens. Pushing it onto `queue` instead
988
+ * strands it, because `drain` runs only when a turn ends and an idle session has no turn to
989
+ * end — so it would arrive *after* the reader's next message, which is the one order that
990
+ * defeats the purpose.
991
+ *
992
+ * Riding along with the next message costs nothing, arrives before the model acts, and is not
993
+ * a `user_message` the human never sent — it is part of one they did.
994
+ */
995
+ record.pendingBranchNote = `[Flow] This working tree is now on branch ${switched.value.name}. Any files you read earlier may have changed, so re-read before relying on them.`;
996
+ this.touch(record);
997
+ return switched.value;
998
+ }
999
+ async switchScopeBranch(scope, branch) {
1000
+ return this.withGitOperation(scope, () => this.switchScopeBranchOnce(scope, branch));
1001
+ }
1002
+ async switchScopeBranchOnce(scope, branch) {
1003
+ if (!isRepository(scope))
1004
+ throw new CommandRefused(`${scope} is not a git repository`);
1005
+ const switched = await gitSwitchBranch(scope, branch);
1006
+ if (!switched.ok)
1007
+ throw new CommandRefused(switched.failure.message);
1008
+ // Whoever is bound to this directory is now somewhere else. Awaited so the answer a client
1009
+ // polls for straight afterwards is the new one rather than the one it just replaced.
1010
+ await Promise.all([...this.sessions.values()]
1011
+ .filter((record) => record.scope === scope)
1012
+ .map((record) => this.refreshBranch(record)));
1013
+ return switched.value;
1014
+ }
1015
+ /**
1016
+ * Ask git where the Scope is now, and record it if that is news.
1017
+ *
1018
+ * Called where there is reason to believe the answer changed — at create, on Revive, after a
1019
+ * switch, and at the end of a turn. That last one is not optional: tools are pre-approved
1020
+ * (ADR 0004), so the *model* can run `git checkout`, and without it the reported branch would be
1021
+ * a stale claim a reader trusts. Never polled, which is why `SessionSummary.branch` is documented
1022
+ * as the last branch observed rather than a live one.
1023
+ */
1024
+ async refreshBranch(record) {
1025
+ if (!isRepository(record.scope))
1026
+ return;
1027
+ const generation = (record.branchGeneration += 1);
1028
+ const found = await head(record.scope);
1029
+ // A repository git cannot answer about is left as it was: this runs off the critical path, and
1030
+ // there is no reader to tell.
1031
+ if (!found.ok)
1032
+ return;
1033
+ // Something newer has been learned or done while this was in flight, so this answer is already
1034
+ // history. Dropping it is the whole point of the generation.
1035
+ if (record.branchGeneration !== generation)
1036
+ return;
1037
+ this.announceBranch(record, found.value);
1038
+ }
1039
+ /**
1040
+ * Record where the Scope is, if that is news.
1041
+ *
1042
+ * Bumps the generation, so an older refresh still in flight cannot land on top of what this says.
1043
+ * A switch is the case that matters: it *knows* the answer, and must outrank any reading taken
1044
+ * before it happened.
1045
+ */
1046
+ announceBranch(record, branch) {
1047
+ record.branchGeneration += 1;
1048
+ if (record.branch?.name === branch.name && record.branch?.detached === branch.detached)
1049
+ return;
1050
+ record.branch = branch;
1051
+ record.log.append({ type: "branch_changed", branch });
1052
+ }
1053
+ workflowOwner;
1054
+ workflowNotifications = new Map();
1055
+ /** Sessions with an unannounced Workflow request. A Set is only a wake signal; ordering is owned
1056
+ * by WorkflowExecutionService, where execution/step/attempt identity can be validated. */
1057
+ workflowInputs = new Set();
1058
+ /** Ordered, per-execution completion queue. A session may finish another workflow while its
1059
+ * parent is still reporting the previous one. */
1060
+ workflowCompletions = new Map();
1061
+ workflowConfirmations = new Map();
1062
+ workflowEnquiryRelays = new Map();
1063
+ workflowPermissionRelays = new Map();
1064
+ cancelWorkflowConfirmation(sessionId) {
1065
+ for (const pending of this.workflowConfirmations.values())
1066
+ if (pending.sessionId === sessionId)
1067
+ pending.finish();
1068
+ }
1069
+ workflowInput(sessionId) {
1070
+ if (this.workflowShutdown || this.workflowStopping.has(sessionId))
1071
+ return;
1072
+ this.workflowInputs.add(sessionId);
1073
+ this.queueWorkflowDrain(sessionId);
1074
+ }
1075
+ workflowWake(sessionId, executionId, revision) {
1076
+ if (this.workflowShutdown || this.workflowStopping.has(sessionId))
1077
+ return;
1078
+ this.workflowNotifications.set(sessionId, { executionId, revision });
1079
+ this.queueWorkflowDrain(sessionId);
1080
+ }
1081
+ workflowComplete(sessionId, executionId) {
1082
+ if (this.workflowShutdown || this.workflowStopping.has(sessionId))
1083
+ return;
1084
+ const pending = this.workflowCompletions.get(sessionId) ?? [];
1085
+ if (!pending.includes(executionId))
1086
+ pending.push(executionId);
1087
+ this.workflowCompletions.set(sessionId, pending);
1088
+ this.queueWorkflowDrain(sessionId);
1089
+ }
1090
+ queueWorkflowDrain(sessionId) {
1091
+ queueMicrotask(() => {
1092
+ const record = this.sessions.get(sessionId);
1093
+ if (record)
1094
+ void this.drainWorkflowNotification(record).catch(() => { });
1095
+ });
1096
+ }
1097
+ /**
1098
+ * Start one host-driven parent turn for workflow monitoring, but never interrupt a turn already in
1099
+ * flight. Completion is delivered before later Steering Queue entries: "after the current turn"
1100
+ * must not become "after every message that happened to be queued while it ran".
1101
+ */
1102
+ async drainWorkflowNotification(record) {
1103
+ if (record.turnInFlight || !record.session || record.lifecycle !== 'live' || this.workflowShutdown || this.workflowStopping.has(record.id))
1104
+ return false;
1105
+ let kind;
1106
+ let text;
1107
+ if (this.workflowInputs.delete(record.id)) {
1108
+ text = this.workflowOwner?.takeInput?.(record.id);
1109
+ if (text)
1110
+ kind = 'input';
1111
+ }
1112
+ const recovery = kind ? undefined : this.workflowNotifications.get(record.id);
1113
+ const completions = recovery || kind ? undefined : this.workflowCompletions.get(record.id);
1114
+ const completion = completions?.shift();
1115
+ if (recovery) {
1116
+ this.workflowNotifications.delete(record.id);
1117
+ text = this.workflowOwner?.takeNotification(record.id, recovery.executionId, recovery.revision);
1118
+ kind = text ? 'recovery' : undefined;
1119
+ }
1120
+ else if (completion) {
1121
+ if (!completions.length)
1122
+ this.workflowCompletions.delete(record.id);
1123
+ text = this.workflowOwner?.takeCompletion(record.id, completion);
1124
+ kind = text ? 'completion' : undefined;
1125
+ }
1126
+ if (!kind || !text) {
1127
+ // A request can be canceled, or a recovery can become stale, before the parent becomes free.
1128
+ // Continue to the next host-driven item rather than waiting for an unrelated future wake.
1129
+ if (this.workflowInputs.has(record.id) || this.workflowNotifications.has(record.id) || this.workflowCompletions.has(record.id))
1130
+ return this.drainWorkflowNotification(record);
1131
+ return false;
1132
+ }
1133
+ record.turnInFlight = true;
1134
+ record.log.append({
1135
+ type: 'notice',
1136
+ level: 'info',
1137
+ text: kind === 'input'
1138
+ ? 'Workflow input requested. The parent is relaying it.'
1139
+ : kind === 'recovery'
1140
+ ? 'Workflow requires recovery. The parent is inspecting it.'
1141
+ : 'Workflow completed. The parent is preparing the result.',
1142
+ });
1143
+ try {
1144
+ await record.session.prompt(text);
1145
+ return true;
1146
+ }
1147
+ catch (error) {
1148
+ record.turnInFlight = false;
1149
+ if (kind === 'input')
1150
+ this.workflowOwner?.rearmInput?.(record.id);
1151
+ record.log.append({ type: 'notice', level: 'warn', text: `Could not notify parent: ${errorMessage(error)}` });
1152
+ // The notification was consumed but no turn began. Keep draining in case another workflow
1153
+ // event is ready; returning false when there is not one lets drain() release the Steering Queue.
1154
+ return this.drainWorkflowNotification(record);
1155
+ }
1156
+ }
1157
+ /** Confirmation belongs to this exact action, never a standing grant or model assertion. */
1158
+ confirmWorkflow(sessionId, description, signal) {
1159
+ const record = this.record(sessionId);
1160
+ if (!record.session || record.lifecycle !== 'live' || !record.turnInFlight || signal?.aborted)
1161
+ return Promise.resolve(false);
1162
+ const askId = `workflow-${randomUUID()}`;
1163
+ const questions = [{ header: 'Workflow recovery', question: description, multiSelect: false,
1164
+ options: [{ label: 'Recover', description: 'Authorize this action once. Earlier operations may already have made changes.' }, { label: 'Cancel', description: 'Do not perform this recovery.' }] }];
1165
+ return new Promise(resolve => {
1166
+ const abort = () => finish();
1167
+ const finish = (allowed) => {
1168
+ if (!this.workflowConfirmations.delete(askId))
1169
+ return;
1170
+ signal?.removeEventListener('abort', abort);
1171
+ this.onBackendEvent(sessionId, allowed === undefined ? { type: 'enquiry', askId, questions, state: 'aborted' } : { type: 'enquiry', askId, questions, state: 'answered', answers: [[allowed ? 'Recover' : 'Cancel']] });
1172
+ resolve(allowed === true);
1173
+ };
1174
+ this.workflowConfirmations.set(askId, { sessionId, finish });
1175
+ signal?.addEventListener('abort', abort, { once: true });
1176
+ this.onBackendEvent(sessionId, { type: 'enquiry', askId, questions, state: 'asked' });
1177
+ });
1178
+ }
1179
+ async relayWorkflowEnquiry(sessionId, context, questions, forward, signal) {
1180
+ const record = this.record(sessionId);
1181
+ if (!record.session || record.lifecycle !== 'live' || !record.turnInFlight || signal?.aborted)
1182
+ throw new CommandRefused('The parent relay is no longer active');
1183
+ const askId = `workflow-input-${randomUUID()}`;
1184
+ await new Promise((resolve, reject) => {
1185
+ let state = 'open';
1186
+ let canceled = false;
1187
+ const clear = () => { state = 'settled'; signal?.removeEventListener('abort', cancel); this.workflowEnquiryRelays.delete(askId); };
1188
+ const abort = () => {
1189
+ if (state === 'settled')
1190
+ return;
1191
+ clear();
1192
+ this.onBackendEvent(sessionId, { type: 'enquiry', askId, questions, context, state: 'aborted' });
1193
+ reject(new CommandRefused('The Workflow Enquiry was canceled before it was answered'));
1194
+ };
1195
+ const cancel = () => {
1196
+ if (!this.workflowEnquiryRelays.has(askId))
1197
+ return;
1198
+ if (state === 'submitting') {
1199
+ canceled = true;
1200
+ return;
1201
+ }
1202
+ abort();
1203
+ };
1204
+ const submit = async (answers) => {
1205
+ if (state !== 'open' || !this.workflowEnquiryRelays.has(askId))
1206
+ throw new CommandRefused('That Workflow Enquiry is no longer open');
1207
+ state = 'submitting';
1208
+ try {
1209
+ await forward(answers);
1210
+ if (canceled) {
1211
+ abort();
1212
+ return;
1213
+ }
1214
+ clear();
1215
+ this.onBackendEvent(sessionId, { type: 'enquiry', askId, questions, context, state: 'answered', answers });
1216
+ resolve();
1217
+ }
1218
+ catch (error) {
1219
+ if (canceled)
1220
+ abort();
1221
+ else
1222
+ state = 'open';
1223
+ throw error;
1224
+ }
1225
+ };
1226
+ this.workflowEnquiryRelays.set(askId, { sessionId, questions: questions.length, submit, cancel });
1227
+ signal?.addEventListener('abort', cancel, { once: true });
1228
+ this.onBackendEvent(sessionId, { type: 'enquiry', askId, questions, context, state: 'asked' });
1229
+ });
1230
+ }
1231
+ async relayWorkflowPermission(sessionId, prompt, forward, signal) {
1232
+ const record = this.record(sessionId);
1233
+ if (!record.session || record.lifecycle !== 'live' || !record.turnInFlight || signal?.aborted)
1234
+ throw new CommandRefused('The parent relay is no longer active');
1235
+ const callId = `workflow-input-${randomUUID()}`;
1236
+ await new Promise((resolve, reject) => {
1237
+ let state = 'open';
1238
+ let canceled = false;
1239
+ const clear = () => { state = 'settled'; signal?.removeEventListener('abort', cancel); this.workflowPermissionRelays.delete(callId); };
1240
+ const finish = (decision, error) => {
1241
+ if (state === 'settled')
1242
+ return;
1243
+ clear();
1244
+ this.onBackendEvent(sessionId, decision === undefined
1245
+ ? { type: 'permission', callId, tool: prompt.tool, context: prompt.context, allowAlways: prompt.allowAlways, authorizationScope: prompt.authorizationScope, state: 'aborted' }
1246
+ : { type: 'permission', callId, tool: prompt.tool, context: prompt.context, allowAlways: prompt.allowAlways, authorizationScope: prompt.authorizationScope, state: 'decided', decision });
1247
+ this.onBackendEvent(sessionId, { type: 'tool_ended', callId, result: decision === undefined ? 'Workflow request canceled' : `Human decision: ${decision}`, isError: decision === undefined || decision === 'deny' });
1248
+ if (error !== undefined)
1249
+ reject(error);
1250
+ else
1251
+ resolve();
1252
+ };
1253
+ const cancel = () => {
1254
+ if (!this.workflowPermissionRelays.has(callId))
1255
+ return;
1256
+ if (state === 'submitting') {
1257
+ canceled = true;
1258
+ return;
1259
+ }
1260
+ finish(undefined, new CommandRefused('The Workflow Permission Prompt was canceled before it was decided'));
1261
+ };
1262
+ const submit = async (decision) => {
1263
+ if (state !== 'open' || !this.workflowPermissionRelays.has(callId))
1264
+ throw new CommandRefused('That Workflow Permission Prompt is no longer open');
1265
+ state = 'submitting';
1266
+ try {
1267
+ await forward(decision);
1268
+ if (canceled)
1269
+ finish(undefined, new CommandRefused('The Workflow Permission Prompt was canceled before it was decided'));
1270
+ else
1271
+ finish(decision);
1272
+ }
1273
+ catch (error) {
1274
+ if (canceled)
1275
+ finish(undefined, new CommandRefused('The Workflow Permission Prompt was canceled before it was decided'));
1276
+ else
1277
+ state = 'open';
1278
+ throw error;
1279
+ }
1280
+ };
1281
+ this.workflowPermissionRelays.set(callId, { sessionId, allowAlways: prompt.allowAlways, submit, cancel });
1282
+ signal?.addEventListener('abort', cancel, { once: true });
1283
+ // The tool row keeps the original arguments so the shared composer derives the same précis it
1284
+ // would for a parent call. Origin and scope stay on the prompt: they are decision metadata,
1285
+ // not invented tool arguments.
1286
+ this.onBackendEvent(sessionId, { type: 'tool_started', callId, name: prompt.tool, input: prompt.details ?? {} });
1287
+ this.onBackendEvent(sessionId, { type: 'permission', callId, tool: prompt.tool, context: prompt.context, allowAlways: prompt.allowAlways, authorizationScope: prompt.authorizationScope, state: 'asked' });
1288
+ });
1289
+ }
1290
+ workflowShutdown = false;
1291
+ workflowStopping = new Set();
1292
+ workflowSession(sessionId) {
1293
+ const record = this.record(sessionId);
1294
+ if (record.lifecycle === 'ended')
1295
+ throw new CommandRefused('Agent Session has ended');
1296
+ return { sessionId, backend: record.backendName, scope: scopeKey(record.scope), projectId: scopeKey(record.worktree?.repo ?? record.scope), session: record.session };
1297
+ }
1298
+ assertWorkflowSession(sessionId, session) {
1299
+ const record = this.record(sessionId);
1300
+ if (this.workflowShutdown || this.workflowStopping.has(sessionId) || record.lifecycle !== 'live' || !session || record.session !== session)
1301
+ throw new CommandRefused('Backend Session is stopping or no longer owned');
1302
+ }
1303
+ async openWorkflowSession(sessionId) {
1304
+ if (this.workflowShutdown || this.workflowStopping.has(sessionId))
1305
+ throw new CommandRefused('Backend Session is stopping');
1306
+ this.workflowSession(sessionId);
1307
+ if (!this.record(sessionId).session)
1308
+ await this.revive(sessionId);
1309
+ return this.workflowSession(sessionId);
1310
+ }
1311
+ workflowSpend(sessionId, executionId, spend) {
1312
+ const record = this.record(sessionId);
1313
+ const previous = record.log.since(0).findLast(({ event }) => event.type === 'workflow_spend' && event.executionId === executionId);
1314
+ if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
1315
+ return;
1316
+ record.log.append({ type: 'workflow_spend', executionId, spend });
1317
+ }
1318
+ authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
1319
+ async dispose(sessionId, reason = "disposed") {
1320
+ const record = this.sessions.get(sessionId);
1321
+ if (!record)
1322
+ return;
1323
+ this.refuseGitOperation(record.scope);
1324
+ const session = record.session;
1325
+ record.session = undefined;
1326
+ record.lifecycle = "ended";
1327
+ record.turnInFlight = false;
1328
+ record.queue.length = 0;
1329
+ await this.stopBackendSession(record.scope, session, sessionId);
1330
+ record.log.append({ type: "session_ended", reason });
1331
+ this.touch(record);
1332
+ this.announceClosed(sessionId);
1333
+ }
1334
+ /**
1335
+ * Settle an Agent Session: the engineer declaring they are done with it.
1336
+ *
1337
+ * The Backend Session stops and the retention clock starts, but unlike `dispose` this is not
1338
+ * terminal — the transcript stays readable and a Revive (or the next message) un-settles it.
1339
+ * That reversibility is the point: a Settle you regret in the morning is recoverable, while one
1340
+ * you forget about is reaped (ADR 0006).
1341
+ */
1342
+ async settle(sessionId) {
1343
+ const record = this.record(sessionId);
1344
+ this.refuseGitOperation(record.scope);
1345
+ if (record.lifecycle === "ended")
1346
+ throw new Error(`Session ${sessionId} has ended`);
1347
+ if (record.lifecycle === "settled")
1348
+ return;
1349
+ const session = record.session;
1350
+ record.session = undefined;
1351
+ record.lifecycle = "settled";
1352
+ this.workflowStopping.add(sessionId);
1353
+ this.workflowNotifications.delete(sessionId);
1354
+ this.workflowCompletions.delete(sessionId);
1355
+ for (const pending of this.workflowConfirmations.values())
1356
+ if (pending.sessionId === sessionId)
1357
+ pending.finish();
1358
+ // The retention window runs from here, not from the last thing that happened: settling
1359
+ // something untouched for a week still grants it a full window (ADR 0006).
1360
+ record.settledAt = new Date().toISOString();
1361
+ record.queue.length = 0;
1362
+ record.turnInFlight = false;
1363
+ await this.stopBackendSession(record.scope, session, sessionId);
1364
+ // Close a turn we are interrupting before recording the Settle. Leaving it open would let the
1365
+ // restart path close it *after* session_settled, and a trailing turn_ended reduces to idle —
1366
+ // the rail would say settled while the pane said idle.
1367
+ this.closeOpenSubagents(record, record.log.since(0));
1368
+ this.closeOpenBackgroundCalls(record, record.log.since(0));
1369
+ this.closeOpenEnquiries(record, record.log.since(0));
1370
+ this.closeOpenPermissions(record, record.log.since(0));
1371
+ const openTurn = openTurnId(record.log.since(0));
1372
+ if (openTurn)
1373
+ record.log.append({ type: "turn_ended", turnId: openTurn, reason: "aborted" });
1374
+ record.log.append({ type: "session_settled" });
1375
+ // Stamps updatedAt, which is what starts the retention clock: a Settled Agent Session runs
1376
+ // nothing and so records no further activity, and it always gets a full window.
1377
+ this.touch(record);
1378
+ this.workflowStopping.delete(sessionId);
1379
+ this.announceClosed(sessionId);
1380
+ }
1381
+ /**
1382
+ * Delete Settled Agent Sessions whose retention window has passed. Only Settled ones: no other
1383
+ * state is deleted on a rule its owner did not opt into.
1384
+ *
1385
+ * Takes `now` so it can be tested without waiting, and returns what it removed.
1386
+ */
1387
+ async reap(now = Date.now()) {
1388
+ // Asked, not remembered: the Settings own this value and it may have changed since startup.
1389
+ const retention = typeof this.retention === "function" ? this.retention() : this.retention;
1390
+ if (retention === "never")
1391
+ return [];
1392
+ const reaped = [];
1393
+ for (const record of [...this.sessions.values()]) {
1394
+ if (record.lifecycle !== "settled")
1395
+ continue;
1396
+ const settledAt = record.settledAt === undefined ? NaN : Date.parse(record.settledAt);
1397
+ // An unreadable timestamp means we cannot know the age; leaving it is the safe failure.
1398
+ if (Number.isNaN(settledAt) || now - settledAt < retention)
1399
+ continue;
1400
+ // Before deleting the session, so a worktree that cannot be removed leaves its Agent Session
1401
+ // in place to be retried on the next sweep rather than stranding a directory whose owner is
1402
+ // gone. `deleteSession` removes only `<root>/sessions/<id>`, so it can never take a worktree
1403
+ // with it by accident.
1404
+ const key = scopeKey(record.scope);
1405
+ if (this.gitOperations.has(key) || this.closingScopes.has(key))
1406
+ continue;
1407
+ this.gitOperations.add(key);
1408
+ try {
1409
+ await this.workflowOwner?.forget(record.id);
1410
+ await this.releaseWorktree(record);
1411
+ record.log.closeSubscribers();
1412
+ this.sessions.delete(record.id);
1413
+ this.publishReviews.delete(record.id);
1414
+ this.store?.deleteSession(record.id);
1415
+ reaped.push(record.id);
1416
+ }
1417
+ finally {
1418
+ this.gitOperations.delete(key);
1419
+ }
1420
+ }
1421
+ for (const sessionId of reaped)
1422
+ this.announceClosed(sessionId);
1423
+ return reaped;
1424
+ }
1425
+ /**
1426
+ * Remove a reaped session's worktree, but only while it is clean.
1427
+ *
1428
+ * `git worktree remove` never deletes the branch ref or the commits on it, so committed work
1429
+ * survives a reap and is reachable by name afterwards. The only thing at risk is what was never
1430
+ * committed, which is why one `status --porcelain` is the whole safety rule — and why a dirty
1431
+ * worktree is left where it is and announced instead.
1432
+ */
1433
+ async releaseWorktree(record) {
1434
+ const worktree = record.worktree;
1435
+ if (!worktree)
1436
+ return;
1437
+ const kept = (reason) => {
1438
+ for (const listener of this.keptListeners) {
1439
+ listener({ path: worktree.path, branch: worktree.branch, reason });
1440
+ }
1441
+ };
1442
+ const clean = await isClean(worktree.path);
1443
+ if (!clean.ok) {
1444
+ kept(clean.failure.message);
1445
+ return;
1446
+ }
1447
+ if (!clean.value) {
1448
+ kept("it has uncommitted changes");
1449
+ return;
1450
+ }
1451
+ const removed = await removeWorktree({ repo: worktree.repo, path: worktree.path });
1452
+ if (!removed.ok)
1453
+ kept(removed.failure.message);
1454
+ }
1455
+ /**
1456
+ * Name this Agent Session again, from its Presentation Transcript, with the Summary Model.
1457
+ *
1458
+ * **Never Revives** (ADR 0003). It reads the transcript, not the Conversation Context — two
1459
+ * different records (ADR 0001), and only the first can be read with nothing running. So a Dormant
1460
+ * Agent Session stays Dormant, no Backend Session is started on it, and no turn is opened on it:
1461
+ * the work happens in a throwaway session somewhere else entirely.
1462
+ *
1463
+ * **Awaited**, unlike the naming at dispatch, because a human clicked this and is watching for the
1464
+ * result. Every way it can fail is a refusal they can read rather than a silence.
1465
+ */
1466
+ async rename(sessionId) {
1467
+ const record = this.record(sessionId);
1468
+ const summary = this.summaryModel?.(record.backendName);
1469
+ if (!summary)
1470
+ throw new CommandRefused("No Summary Model is configured — choose one in Settings");
1471
+ const entries = record.log.since(0);
1472
+ if (!entries.some((entry) => entry.event.type === "user_message")) {
1473
+ throw new CommandRefused("This Agent Session has nothing to name yet");
1474
+ }
1475
+ // Refused readably rather than thrown as a 500: nothing validates a model id or a backend name
1476
+ // when the Settings are saved (ADR 0020), so naming a backend this build lacks is an ordinary
1477
+ // typo and the person who made it is the one reading this message.
1478
+ let backend;
1479
+ try {
1480
+ backend = this.backendFor(summary.backend);
1481
+ }
1482
+ catch {
1483
+ throw new CommandRefused(`No backend named ${summary.backend} — check the Summary Model in Settings`);
1484
+ }
1485
+ const generation = (record.titleGeneration += 1);
1486
+ const name = await this.summarySpare.name(backend, summary, nameInput(entries));
1487
+ if (name === undefined)
1488
+ throw new CommandRefused("Could not name this Agent Session");
1489
+ // Refused rather than applied when something newer has already been asked for. A human who
1490
+ // clicked twice wants the second answer, and the first arriving afterwards must not undo it.
1491
+ if (record.titleGeneration !== generation)
1492
+ throw new CommandRefused("This Agent Session was renamed again");
1493
+ record.title = name;
1494
+ record.titleSource = "summary";
1495
+ this.touch(record);
1496
+ return name;
1497
+ }
1498
+ /**
1499
+ * Automatically name a newly-created Agent Session from a validated workflow launch.
1500
+ *
1501
+ * Like first-message naming, this never blocks or fails the launch. Only the untouched Scope
1502
+ * placeholder may yield: a manual/summary title, or even a first chat message that raced the
1503
+ * workflow start, always wins.
1504
+ */
1505
+ async nameWorkflow(sessionId, workflowName, input) {
1506
+ const record = this.sessions.get(sessionId);
1507
+ if (record)
1508
+ await this.nameAutomatically(record, workflowNameInput(workflowName, input), "scope");
1509
+ }
1510
+ /** Generate and apply a convenience title only while the placeholder which requested it remains. */
1511
+ async nameAutomatically(record, input, expectedSource) {
1512
+ if (record.titleSource !== expectedSource)
1513
+ return;
1514
+ const summary = this.summaryModel?.(record.backendName);
1515
+ if (!summary?.automatic)
1516
+ return;
1517
+ const generation = (record.titleGeneration += 1);
1518
+ let name;
1519
+ try {
1520
+ name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
1521
+ }
1522
+ catch {
1523
+ return;
1524
+ }
1525
+ if (name === undefined)
1526
+ return;
1527
+ const current = this.sessions.get(record.id);
1528
+ if (!current || current !== record || current.lifecycle === "ended" || current.lifecycle === "settled")
1529
+ return;
1530
+ if (current.titleSource !== expectedSource || current.titleGeneration !== generation)
1531
+ return;
1532
+ current.title = name;
1533
+ current.titleSource = "summary";
1534
+ this.touch(current);
1535
+ }
1536
+ hasActiveWork() {
1537
+ return [...this.sessions.values()].some(record => record.turnInFlight || record.queue.length > 0 || record.openSubagentIds.size > 0 || record.openBackgroundCallIds.size > 0);
1538
+ }
1539
+ /** Stop running work without ending the Agent Sessions: they become Dormant and can be revived. */
1540
+ async shutdown() {
1541
+ this.workflowShutdown = true;
1542
+ // First, so that a naming still in flight cannot warm a replacement on the way out — the
1543
+ // one-shot CLI runner shuts down microseconds before `process.exit`, and a spare booted in
1544
+ // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
1545
+ // `SummaryModelSpare.dispose`.
1546
+ this.summarySpare.dispose();
1547
+ for (const record of this.sessions.values()) {
1548
+ if (!record.session)
1549
+ continue;
1550
+ const session = record.session;
1551
+ record.session = undefined;
1552
+ record.lifecycle = "dormant";
1553
+ record.turnInFlight = false;
1554
+ record.queue.length = 0;
1555
+ record.turnInFlight = false;
1556
+ await this.stopBackendSession(record.scope, session, record.id);
1557
+ this.closeOpenSubagents(record, record.log.since(0));
1558
+ this.closeOpenBackgroundCalls(record, record.log.since(0));
1559
+ this.closeOpenEnquiries(record, record.log.since(0));
1560
+ this.closeOpenPermissions(record, record.log.since(0));
1561
+ record.log.append({ type: "session_dormant", reason: "host shutdown" });
1562
+ this.persist(record);
1563
+ }
1564
+ }
1565
+ async execute(command) {
1566
+ switch (command.type) {
1567
+ case "create":
1568
+ return await this.create({
1569
+ scope: command.scope,
1570
+ ...(command.backend === undefined ? {} : { backend: command.backend }),
1571
+ ...(command.modelId === undefined ? {} : { modelId: command.modelId }),
1572
+ ...(command.effort === undefined ? {} : { effort: command.effort }),
1573
+ ...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
1574
+ ...(command.worktree === undefined ? {} : { worktree: command.worktree }),
1575
+ });
1576
+ case "send":
1577
+ return await this.send(command.sessionId, command.text, command.when, command.attachments);
1578
+ case "cancel_queued":
1579
+ return this.cancelQueued(command.sessionId, command.messageId);
1580
+ case "steer_queued":
1581
+ return await this.steerQueued(command.sessionId, command.messageId);
1582
+ case "abort":
1583
+ return await this.abort(command.sessionId);
1584
+ case "revive":
1585
+ return await this.revive(command.sessionId);
1586
+ case "dispose":
1587
+ return await this.dispose(command.sessionId);
1588
+ case "settle":
1589
+ return await this.settle(command.sessionId);
1590
+ case "set_model":
1591
+ return await this.setModel(command.sessionId, command.modelId);
1592
+ case "set_effort":
1593
+ return await this.setEffort(command.sessionId, command.effort);
1594
+ case "pull_branch":
1595
+ return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
1596
+ case "change_pull_request":
1597
+ return await this.withGitOperation(this.record(command.sessionId).scope, () => changePullRequest(this.record(command.sessionId).scope, command.action, command.input));
1598
+ case "pull_request":
1599
+ return await pullRequest(this.record(command.sessionId).scope);
1600
+ case "comment_pull_request":
1601
+ return await commentPullRequest(this.record(command.sessionId).scope, command.input);
1602
+ case "resolve_pull_request_thread":
1603
+ return await resolvePullRequestThread(this.record(command.sessionId).scope, command.input);
1604
+ case "stack_status":
1605
+ return await this.withGitOperation(this.record(command.sessionId).scope, () => stackStatus(this.record(command.sessionId).scope));
1606
+ case "prepare_stack":
1607
+ return await this.prepareStack(command.sessionId, command.action);
1608
+ case "change_stack":
1609
+ return await this.changeStack(command.sessionId, command.input);
1610
+ case "assist_stack":
1611
+ return await this.assistStack(command.sessionId);
1612
+ case "git_status":
1613
+ return await this.gitStatus(command.sessionId);
1614
+ case "prepare_publish":
1615
+ return await this.preparePublish(command.sessionId);
1616
+ case "publish":
1617
+ return await this.publish(command.sessionId, command.input);
1618
+ case "switch_branch":
1619
+ return await this.switchBranch(command.sessionId, command.branch);
1620
+ case "switch_scope_branch":
1621
+ return await this.switchScopeBranch(command.scope, command.branch);
1622
+ case "rename":
1623
+ return await this.rename(command.sessionId);
1624
+ case "compact":
1625
+ return await this.compact(command.sessionId, command.instructions);
1626
+ case "answer_enquiry":
1627
+ return await this.answerEnquiry(command.sessionId, command.askId, command.answers);
1628
+ case "answer_permission":
1629
+ return await this.answerPermission(command.sessionId, command.callId, command.decision);
1630
+ case "list_skills":
1631
+ return await this.listSkills(command.sessionId);
1632
+ case "list":
1633
+ return this.list();
1634
+ }
1635
+ }
1636
+ workflowMcpCredentials() {
1637
+ const values = [...(this.mcpAuth?.credentialValues() ?? [])];
1638
+ for (const connection of this.mcpConnections?.() ?? []) {
1639
+ if (connection.transport === 'http') {
1640
+ for (const [key, value] of new URL(connection.url).searchParams)
1641
+ if (credentialKey.test(key) && value)
1642
+ values.push(value);
1643
+ // A literal header is only redacted when its name reads as a credential: redaction is
1644
+ // substring replacement, so feeding it an innocuous `X-Tenant-Id: 1` would corrupt every
1645
+ // transcript. A secret-backed header is always redacted — that is what naming a Secret means.
1646
+ for (const [name, source] of Object.entries(connection.headers)) {
1647
+ if (!('secret' in source)) {
1648
+ if (credentialKey.test(name))
1649
+ values.push(source.value);
1650
+ }
1651
+ else if (this.resolveSecret)
1652
+ try {
1653
+ values.push(this.resolveSecret(source.secret));
1654
+ }
1655
+ catch { }
1656
+ }
1657
+ }
1658
+ else {
1659
+ connection.args.forEach((arg, index) => {
1660
+ if (credentialKey.test(arg.split('=')[0])) {
1661
+ const value = arg.includes('=') ? arg.slice(arg.indexOf('=') + 1) : connection.args[index + 1];
1662
+ if (value)
1663
+ values.push(value);
1664
+ }
1665
+ });
1666
+ }
1667
+ }
1668
+ return values;
1669
+ }
1670
+ workflowMcpConnections(id) {
1671
+ const record = this.sessions.get(id);
1672
+ if (!record)
1673
+ throw new Error('Unknown Agent Session');
1674
+ return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
1675
+ }
1676
+ async openWorkflowMcp(id, connectionId) {
1677
+ const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
1678
+ if (!connection)
1679
+ throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
1680
+ const { McpSession } = await import("../backend/mcp.js");
1681
+ const scope = this.workflowSession(id).scope;
1682
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret);
1683
+ }
1684
+ mcpStatus(id) {
1685
+ const record = this.sessions.get(id);
1686
+ if (!record)
1687
+ throw new Error("Unknown Agent Session");
1688
+ return record.session ? record.mcp?.status() ?? [] : [];
1689
+ }
1690
+ async retryMcp(id, connectionId) {
1691
+ const record = this.sessions.get(id);
1692
+ if (!record?.session || !record.mcp || record.turnInFlight || record.openSubagentIds.size || record.openBackgroundCallIds.size || record.mcpWorkflows)
1693
+ throw new Error("Retry requires an Idle Agent Session without background work");
1694
+ const session = record.session;
1695
+ const mcp = record.mcp;
1696
+ const retry = (record.mcpReady ?? Promise.resolve()).then(async () => {
1697
+ if (record.session !== session)
1698
+ return;
1699
+ await mcp.retry(connectionId);
1700
+ if (record.session === session)
1701
+ await session.refreshMcp?.();
1702
+ });
1703
+ this.trackMcpReadiness(record, retry.catch(() => { mcp.registrationFailed(); }));
1704
+ await retry;
1705
+ }
1706
+ trackMcpReadiness(record, ready) {
1707
+ if (ready)
1708
+ record.mcpReady = ready;
1709
+ else
1710
+ delete record.mcpReady;
1711
+ void ready?.then(() => {
1712
+ if (record.mcpReady === ready)
1713
+ delete record.mcpReady;
1714
+ });
1715
+ }
1716
+ async startBackendSession(record) {
1717
+ const backend = this.backendFor(record.backendName);
1718
+ const { McpSession } = await import("../backend/mcp.js");
1719
+ const mcp = new McpSession((this.mcpConnections?.() ?? []).filter((connection) => record.mcpConnectionIds?.includes(connection.id)), record.scope, this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined, false, this.resolveSecret);
1720
+ record.mcp = mcp;
1721
+ const openingMcp = mcp.open();
1722
+ const session = await backend.create({
1723
+ mcp,
1724
+ workflow: {
1725
+ inspect: input => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
1726
+ throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).inspect(input); },
1727
+ recover: (input, signal) => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
1728
+ throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).recover(input, signal); },
1729
+ relayEnquiry: (input, signal) => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
1730
+ throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayEnquiry(input, signal); },
1731
+ relayPermission: (input, signal) => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
1732
+ throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
1733
+ },
1734
+ scope: record.scope,
1735
+ emit: (event) => this.onBackendEvent(record.id, event),
1736
+ ...(this.autoCompaction ? { autoCompaction: this.autoCompaction(backend.name) } : {}),
1737
+ ...(record.modelId === undefined ? {} : { modelId: record.modelId }),
1738
+ ...(record.effort === undefined ? {} : { effort: record.effort }),
1739
+ ...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
1740
+ ...(record.spend === undefined ? {} : { priorSpend: record.spend }),
1741
+ ...(this.store ? { stateDir: this.store.backendDir(record.id) } : {}),
1742
+ // Read here rather than held, so a Revive picks up every grant made since this Agent Session
1743
+ // last had a Backend Session — which is the whole of how a grant reaches an older session.
1744
+ ...(this.standingAuthorisations
1745
+ ? { standingAuthorisations: this.standingAuthorisations() }
1746
+ : {}),
1747
+ }).catch(async (error) => { await mcp.dispose(); throw error; });
1748
+ const dispose = session.dispose.bind(session);
1749
+ let disposed = false;
1750
+ session.dispose = async () => { disposed = true; try {
1751
+ await dispose();
1752
+ }
1753
+ finally {
1754
+ await mcp.dispose();
1755
+ } };
1756
+ record.session = session;
1757
+ record.capabilities = session.capabilities;
1758
+ const ready = openingMcp.then(async () => {
1759
+ if (!disposed && mcp.connections.length && record.session === session)
1760
+ await session.refreshMcp?.();
1761
+ }).catch(() => {
1762
+ mcp.registrationFailed();
1763
+ if (!disposed)
1764
+ this.onBackendEvent(record.id, { type: "notice", level: "warn", text: "MCP tools could not be updated. Retry the connection." });
1765
+ });
1766
+ this.trackMcpReadiness(record, mcp.connections.length ? ready : undefined);
1767
+ let cancelPendingTurn;
1768
+ let pendingTurn;
1769
+ const waitForMcp = async (run) => {
1770
+ if (disposed)
1771
+ return;
1772
+ if (!record.mcpReady)
1773
+ return run();
1774
+ let cancel;
1775
+ let stopped = false;
1776
+ const cancelled = new Promise((resolve) => { cancel = () => { stopped = true; resolve(false); }; });
1777
+ cancelPendingTurn = cancel;
1778
+ const ready = await Promise.race([record.mcpReady.then(() => true), cancelled]);
1779
+ if (cancelPendingTurn === cancel)
1780
+ cancelPendingTurn = undefined;
1781
+ if ((!ready || stopped) && !disposed) {
1782
+ const turnId = randomUUID();
1783
+ this.onBackendEvent(record.id, { type: "turn_started", turnId });
1784
+ this.onBackendEvent(record.id, { type: "turn_ended", turnId, reason: "aborted" });
1785
+ }
1786
+ if (ready && !stopped && !disposed)
1787
+ await run();
1788
+ };
1789
+ const abort = session.abort.bind(session);
1790
+ session.abort = async () => {
1791
+ if (cancelPendingTurn) {
1792
+ cancelPendingTurn();
1793
+ await pendingTurn;
1794
+ }
1795
+ else
1796
+ await abort();
1797
+ };
1798
+ const prompt = session.prompt.bind(session);
1799
+ session.prompt = (text, attachments) => {
1800
+ pendingTurn = waitForMcp(() => prompt(text, attachments));
1801
+ return pendingTurn;
1802
+ };
1803
+ if (session.compact) {
1804
+ const compact = session.compact.bind(session);
1805
+ session.compact = (instructions) => {
1806
+ pendingTurn = waitForMcp(() => compact(instructions));
1807
+ return pendingTurn;
1808
+ };
1809
+ }
1810
+ if (session.startWorkflowSubagent) {
1811
+ const start = session.startWorkflowSubagent.bind(session);
1812
+ session.startWorkflowSubagent = (options) => {
1813
+ record.mcpWorkflows = (record.mcpWorkflows ?? 0) + 1;
1814
+ let cancel;
1815
+ let stopped = false;
1816
+ const cancelled = new Promise((resolve) => { cancel = () => { stopped = true; resolve(false); }; });
1817
+ const handle = (async () => {
1818
+ const ready = record.mcpReady ? await Promise.race([record.mcpReady.then(() => true), cancelled]) : true;
1819
+ if (disposed || stopped || !ready)
1820
+ throw new Error("Workflow Step stopped");
1821
+ return start(options);
1822
+ })();
1823
+ const done = handle.then((handle) => handle.done).finally(() => {
1824
+ record.mcpWorkflows = record.mcpWorkflows - 1;
1825
+ });
1826
+ return {
1827
+ done,
1828
+ answerEnquiry: async (...args) => (await handle).answerEnquiry(...args),
1829
+ answerPermission: async (...args) => (await handle).answerPermission(...args),
1830
+ cancel: async () => { cancel(); await handle.then((handle) => handle.cancel(), () => { }); },
1831
+ };
1832
+ };
1833
+ }
1834
+ this.captureResumeToken(record);
1835
+ return session;
1836
+ }
1837
+ /**
1838
+ * A turn left open by an unclean shutdown is closed on load rather than left hanging. The
1839
+ * transcript is append-only (ADR 0001), so we record that we now know it ended instead of
1840
+ * rewriting the turn that never finished.
1841
+ */
1842
+ closeTornTurn(record, entries) {
1843
+ this.closeOpenSubagents(record, entries);
1844
+ this.closeOpenBackgroundCalls(record, entries);
1845
+ // The daemon-restart case for an Enquiry: nothing was in memory to abandon its callback, and the
1846
+ // process holding it is gone. All that is left is to record that nobody will ever answer it.
1847
+ this.closeOpenEnquiries(record, entries);
1848
+ this.closeOpenPermissions(record, entries);
1849
+ const openTurn = openTurnId(entries);
1850
+ if (!openTurn)
1851
+ return;
1852
+ record.log.append({ type: "turn_ended", turnId: openTurn, reason: "aborted" });
1853
+ }
1854
+ /**
1855
+ * Close every Subagent the transcript still has running.
1856
+ *
1857
+ * A backgrounded Subagent outlives the turn that spawned it (ADR 0016), but none outlives its
1858
+ * Backend Session — they are children of the CLI process. So one still running when that session
1859
+ * is gone is a record of something that will never finish: on a Revive it renders as a subagent
1860
+ * working forever, with a spinner nothing will ever stop. Aborted for the same reason a torn turn
1861
+ * is: the work stopped, and nobody can say whether it had succeeded.
1862
+ */
1863
+ closeOpenSubagents(record, entries) {
1864
+ for (const open of openSubagents(entries)) {
1865
+ record.log.append({ type: "subagent", ...open, state: "aborted" });
1866
+ }
1867
+ record.openSubagentIds.clear();
1868
+ }
1869
+ /**
1870
+ * Close every Background Call the transcript still has running.
1871
+ *
1872
+ * The same argument `closeOpenSubagents` makes, and it reaches the same place: a Background Call
1873
+ * outlives the turn that made it (ADR 0021) but not its Backend Session, being a child of the CLI
1874
+ * process. One still running when that session is gone would render on a Revive as a job working
1875
+ * forever with nothing that could ever stop it.
1876
+ *
1877
+ * A remotely-launched call is the honest exception — it may really still be running on another
1878
+ * machine — and is recorded aborted anyway, because Flow has no channel to hear about it again
1879
+ * and a card spinning on a promise nothing can keep is the worse of the two lies.
1880
+ */
1881
+ closeOpenBackgroundCalls(record, entries) {
1882
+ for (const open of openBackgroundCalls(entries)) {
1883
+ record.log.append({ type: "background_call", ...open, state: "aborted" });
1884
+ }
1885
+ record.openBackgroundCallIds.clear();
1886
+ }
1887
+ /**
1888
+ * Record that an Enquiry nobody answered is over.
1889
+ *
1890
+ * Called beside `closeOpenSubagents` from every path that takes a Backend Session away, and always
1891
+ * *before* the `session_dormant` / `session_settled` line, so a state arriving after the marker
1892
+ * cannot reduce a pane back out of it.
1893
+ *
1894
+ * Self-deduplicating rather than conditional: it runs after `session.dispose()`, which is where a
1895
+ * live adapter abandons its own pending callbacks and emits these snapshots itself — so by the time
1896
+ * this reads the transcript there is usually nothing open, and it appends nothing. What it is for
1897
+ * is the cases where there was no adapter to do it: a daemon that restarted, or one whose backend
1898
+ * died without saying so.
1899
+ */
1900
+ closeOpenEnquiries(record, entries) {
1901
+ for (const open of openEnquiries(entries)) {
1902
+ record.log.append({ type: "enquiry", ...open, state: "aborted" });
1903
+ }
1904
+ record.openEnquiryIds.clear();
1905
+ }
1906
+ /**
1907
+ * Record that a Permission Prompt nobody decided is over.
1908
+ *
1909
+ * Beside `closeOpenEnquiries`, called from the same three paths and self-deduplicating for the same
1910
+ * reason: a live adapter abandons its own callbacks in `dispose()` and emits these snapshots
1911
+ * itself, so this usually appends nothing. What it is for is a daemon that restarted, or a backend
1912
+ * that died without saying so — and the failure it prevents is worse here than there. A prompt left
1913
+ * open in a replayed transcript locks the composer on buttons whose promise died with the process,
1914
+ * so the human has a question they cannot answer and cannot dismiss.
1915
+ */
1916
+ closeOpenPermissions(record, entries) {
1917
+ for (const open of openPermissions(entries)) {
1918
+ record.log.append({ type: "permission", ...open, state: "aborted" });
1919
+ }
1920
+ record.openPermissionIds.clear();
1921
+ }
1922
+ async dispatch(record, message) {
1923
+ this.refuseGitOperation(record.scope);
1924
+ if (!record.session)
1925
+ throw new Error(`Session ${record.id} has no Backend Session`);
1926
+ const { text, attachments } = message;
1927
+ const note = record.pendingBranchNote;
1928
+ record.pendingBranchNote = undefined;
1929
+ /*
1930
+ * After the human's words, not before them.
1931
+ *
1932
+ * A backend expands a Skill the human picked — `/tdd`, `/code-review` — only when the name is at
1933
+ * the very start of the message, and a note prepended here moves it off that first character. It
1934
+ * worked until the turn after someone switched branch, and then quietly became an ordinary
1935
+ * message asking the model about the word "/tdd". Ordering within one message is not what makes
1936
+ * the note work: it arrives before the model acts either way.
1937
+ */
1938
+ const sent = note === undefined ? text : `${text}\n\n${note}`;
1939
+ record.turnInFlight = true;
1940
+ record.log.append({
1941
+ type: "user_message",
1942
+ id: randomUUID(),
1943
+ text: sent,
1944
+ ...(attachments.length > 0 ? { attachments } : {}),
1945
+ });
1946
+ // Titled from what its owner actually typed, never from `sent`. A switch made before the first
1947
+ // message would otherwise name the Agent Session after the note, and permanently: the rename
1948
+ // fires only while the title is still the placeholder. An Attachment never titles anything
1949
+ // either, so a wordless paste falls to firstLine's own "Untitled session" rather than a filename.
1950
+ if (record.titleSource === "scope") {
1951
+ record.title = firstLine(text);
1952
+ record.titleSource = "first-line";
1953
+ /*
1954
+ * And then, seconds later, something better.
1955
+ *
1956
+ * `void`ed rather than awaited: this is a model call that can take ten seconds, and the human
1957
+ * is waiting on their turn starting, not on its name. The first line is already in place, so
1958
+ * what arrives replaces a usable title rather than filling an empty one — no spinner, no
1959
+ * flicker into and out of blank. It can only happen on a first dispatch, so no *established*
1960
+ * name ever changes under its reader.
1961
+ */
1962
+ void this.nameAutomatically(record, text, "first-line");
1963
+ }
1964
+ this.touch(record);
1965
+ const workflowContext = this.workflowOwner?.context(record.id);
1966
+ await record.session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments));
1967
+ }
1968
+ /**
1969
+ * The bytes for a dispatch, base64 for whichever SDK is about to receive them.
1970
+ *
1971
+ * Read at dispatch rather than held from the send, because a queued message may wait out a long
1972
+ * turn and the disk is where it is already durable. An id whose file has gone is skipped rather
1973
+ * than fatal: it can only mean the session's directory was interfered with, and losing an image
1974
+ * from a turn is a smaller harm than losing the words that came with it.
1975
+ */
1976
+ loadAttachments(sessionId, ids) {
1977
+ if (ids.length === 0)
1978
+ return undefined;
1979
+ const loaded = [];
1980
+ for (const id of ids) {
1981
+ const mediaType = mediaTypeOf(id);
1982
+ const bytes = mediaType ? this.store?.readAttachment(sessionId, id) : undefined;
1983
+ if (mediaType && bytes)
1984
+ loaded.push({ mediaType, data: bytes.toString("base64") });
1985
+ }
1986
+ return loaded.length > 0 ? loaded : undefined;
1987
+ }
1988
+ flushBuffered(record) {
1989
+ const buffered = record.buffered ?? [];
1990
+ record.buffered = undefined;
1991
+ for (const event of buffered)
1992
+ this.onBackendEvent(record.id, event);
1993
+ }
1994
+ onBackendEvent(sessionId, event) {
1995
+ const record = this.sessions.get(sessionId);
1996
+ if (!record || record.lifecycle === "ended" || record.lifecycle === "settled")
1997
+ return;
1998
+ if (record.buffered) {
1999
+ record.buffered.push(event);
2000
+ return;
2001
+ }
2002
+ const before = this.activityOf(record);
2003
+ record.log.append(event);
2004
+ this.touch(record);
2005
+ this.indexOpen(record, event);
2006
+ if (event.type === 'notice' && event.level === 'error')
2007
+ void this.workflowOwner?.stop(sessionId).catch(() => { });
2008
+ // Kept current so a Revive can hand the running total back to the next Backend Session, which
2009
+ // counts only its own run.
2010
+ if (event.type === "context_usage" && event.spend)
2011
+ record.spend = event.spend;
2012
+ /*
2013
+ * Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
2014
+ * for the race the field's own comment describes. It matters for the turn nobody asked for: a
2015
+ * backgrounded Subagent settling wakes the model on its own (ADR 0016), and the adapter mints a
2016
+ * turn for what it says. Without this the Steering Queue would believe the session idle and
2017
+ * dispatch into it, which is the very thing holding the turn open used to prevent.
2018
+ */
2019
+ if (event.type === "turn_started") {
2020
+ record.turnInFlight = true;
2021
+ }
2022
+ if (event.type === "turn_ended") {
2023
+ this.workflowOwner?.rearmInput?.(sessionId);
2024
+ for (const pending of this.workflowConfirmations.values())
2025
+ if (pending.sessionId === sessionId)
2026
+ pending.finish();
2027
+ for (const pending of this.workflowEnquiryRelays.values())
2028
+ if (pending.sessionId === sessionId)
2029
+ pending.cancel();
2030
+ for (const pending of this.workflowPermissionRelays.values())
2031
+ if (pending.sessionId === sessionId)
2032
+ pending.cancel();
2033
+ record.turnInFlight = false;
2034
+ this.captureResumeToken(record);
2035
+ // Tools are pre-approved (ADR 0004), so the model can have run `git checkout` during the turn
2036
+ // it just finished. Off the critical path, and announces only on a difference.
2037
+ void this.refreshBranch(record);
2038
+ void this.drain(record);
2039
+ }
2040
+ this.noteResting(record, before);
2041
+ }
2042
+ /**
2043
+ * Keep the open-prompt and open-Subagent index in step with the transcript.
2044
+ *
2045
+ * Only ever called from `onBackendEvent`, which is the one path every adapter event takes. The
2046
+ * host's own terminal snapshots go through `closeOpen*`, which clear these sets themselves.
2047
+ */
2048
+ indexOpen(record, event) {
2049
+ if (event.type === "permission") {
2050
+ toggle(record.openPermissionIds, event.callId, event.state === "asked");
2051
+ }
2052
+ if (event.type === "enquiry") {
2053
+ toggle(record.openEnquiryIds, event.askId, event.state === "asked");
2054
+ }
2055
+ if (event.type === "subagent") {
2056
+ toggle(record.openSubagentIds, event.subagentId, event.state === "running" || event.state === "waiting");
2057
+ }
2058
+ if (event.type === "background_call") {
2059
+ toggle(record.openBackgroundCallIds, event.callId, event.state === "running");
2060
+ }
2061
+ /*
2062
+ * Mirrors the reducer's own `turn_ended` arm, and has to. Neither an Enquiry nor a Permission
2063
+ * Prompt can outlive the turn that raised it, so an adapter that tore one down without emitting
2064
+ * its terminal snapshot would otherwise pin this Agent Session at `awaiting` for good.
2065
+ *
2066
+ * Subagents and Background Calls are deliberately not cleared: one the model backgrounded
2067
+ * outlives the turn that started it and reports into a later one (ADR 0016, ADR 0021).
2068
+ */
2069
+ if (event.type === "turn_ended") {
2070
+ record.openEnquiryIds.clear();
2071
+ record.openPermissionIds.clear();
2072
+ }
2073
+ }
2074
+ /**
2075
+ * Stamp `restingAt` when the derived activity *enters* `idle` — the moment this Agent Session
2076
+ * came to rest and became something to type at.
2077
+ *
2078
+ * On the transition rather than on the state, because `onBackendEvent` runs for every streamed
2079
+ * token: stamping on the state would restamp continuously and reproduce the `updatedAt` churn
2080
+ * this field exists to escape.
2081
+ *
2082
+ * Awaiting deliberately does not stamp, though it is equally its owner's turn. The rail surfaces
2083
+ * it by band now, so a stamp would buy nothing — and it would cost: a turn that hits two
2084
+ * un-authorised tools would come back out of Awaiting with a fresh timestamp and jump the running
2085
+ * band, which is the churn all of this exists to stop.
2086
+ */
2087
+ noteResting(record, before) {
2088
+ const after = this.activityOf(record);
2089
+ if (after === before)
2090
+ return;
2091
+ if (after === "idle")
2092
+ record.restingAt = new Date().toISOString();
2093
+ }
2094
+ captureResumeToken(record) {
2095
+ const token = record.session?.resumeToken();
2096
+ if (token && token !== record.resumeToken) {
2097
+ record.resumeToken = token;
2098
+ this.persist(record);
2099
+ }
2100
+ }
2101
+ async drain(record) {
2102
+ // Avoid an `await` at all when there is no workflow notification. Yielding here lets a backend
2103
+ // mint a new turn between the check and the queue shift, which would dispatch into that turn.
2104
+ if ((this.workflowInputs.has(record.id) || this.workflowNotifications.has(record.id) || this.workflowCompletions.has(record.id)) &&
2105
+ await this.drainWorkflowNotification(record))
2106
+ return;
2107
+ const next = record.queue.shift();
2108
+ if (next === undefined)
2109
+ return;
2110
+ record.log.append(queueChanged(record.queue));
2111
+ try {
2112
+ await this.dispatch(record, next);
2113
+ }
2114
+ catch (error) {
2115
+ record.log.append({ type: "notice", level: "error", text: errorMessage(error) });
2116
+ }
2117
+ }
2118
+ newLog(sessionId, existing) {
2119
+ const store = this.store;
2120
+ return new SessionLog(sessionId, {
2121
+ ...(existing ? { existing } : {}),
2122
+ ...(store ? { sink: (entry) => store.append(entry) } : {}),
2123
+ });
2124
+ }
2125
+ backendFor(name) {
2126
+ const backend = this.backends.get(name);
2127
+ if (!backend)
2128
+ throw new Error(`Unknown backend: ${name}`);
2129
+ return backend;
2130
+ }
2131
+ record(sessionId) {
2132
+ const record = this.sessions.get(sessionId);
2133
+ if (!record)
2134
+ throw new Error(`Unknown session: ${sessionId}`);
2135
+ return record;
2136
+ }
2137
+ touch(record) {
2138
+ record.updatedAt = new Date().toISOString();
2139
+ this.persist(record);
2140
+ }
2141
+ persist(record) {
2142
+ if (!this.store)
2143
+ return;
2144
+ const meta = {
2145
+ id: record.id,
2146
+ scope: record.scope,
2147
+ backend: record.backendName,
2148
+ title: record.title,
2149
+ titleSource: record.titleSource,
2150
+ createdAt: record.createdAt,
2151
+ updatedAt: record.updatedAt,
2152
+ lifecycle: record.lifecycle,
2153
+ // Mirrored for a daemon rolled back to before the split, which reads only this. Without it
2154
+ // every Settled Agent Session would load as Dormant there and stop being reaped.
2155
+ status: record.lifecycle === "live" ? "idle" : record.lifecycle,
2156
+ restingAt: record.restingAt,
2157
+ ...(record.settledAt === undefined ? {} : { settledAt: record.settledAt }),
2158
+ mcpConnectionIds: record.mcpConnectionIds ?? [],
2159
+ ...(record.resumeToken === undefined ? {} : { resumeToken: record.resumeToken }),
2160
+ ...(record.modelId === undefined ? {} : { modelId: record.modelId }),
2161
+ ...(record.effort === undefined ? {} : { effort: record.effort }),
2162
+ ...(record.worktree === undefined ? {} : { worktree: record.worktree }),
2163
+ };
2164
+ this.store.writeMeta(meta);
2165
+ }
2166
+ }
2167
+ /** The turn still open at the end of these entries, if any. */
2168
+ function openTurnId(entries) {
2169
+ let openTurn;
2170
+ for (const entry of entries) {
2171
+ if (entry.event.type === "turn_started")
2172
+ openTurn = entry.event.turnId;
2173
+ if (entry.event.type === "turn_ended")
2174
+ openTurn = undefined;
2175
+ }
2176
+ return openTurn;
2177
+ }
2178
+ function lastEventType(entries) {
2179
+ return entries.at(-1)?.event.type;
2180
+ }
2181
+ /** The last branch the transcript recorded, so a restart does not have to ask git again. */
2182
+ function branchFrom(entries) {
2183
+ let branch;
2184
+ for (const entry of entries) {
2185
+ const event = entry.event;
2186
+ if (event.type === "branch_changed")
2187
+ branch = event.branch;
2188
+ }
2189
+ return branch;
2190
+ }
2191
+ /**
2192
+ * Subagents the transcript last saw running or waiting.
2193
+ *
2194
+ * Derived rather than held on the record, in the style of `branchFrom` and `capabilitiesFrom`: a
2195
+ * Subagent belongs to a turn of a Backend Session, and the host outlives both. Reading it back
2196
+ * from the transcript is also what makes the restart path work at all — nothing was in memory.
2197
+ */
2198
+ /**
2199
+ * The Enquiries the transcript last saw open.
2200
+ *
2201
+ * Derived rather than held on the record, for the reason `openSubagents` is derived: an Enquiry
2202
+ * belongs to a turn of a Backend Session and the host outlives both, and reading it back from the
2203
+ * transcript is what makes the restart path work at all — nothing was in memory.
2204
+ *
2205
+ * The whole `questions` array comes back with it, because a snapshot carries the whole state and the
2206
+ * terminal one the host is about to append needs it again.
2207
+ */
2208
+ function toggle(ids, id, open) {
2209
+ if (open)
2210
+ ids.add(id);
2211
+ else
2212
+ ids.delete(id);
2213
+ }
2214
+ /**
2215
+ * The Lifecycle a persisted Agent Session loads as.
2216
+ *
2217
+ * Anything that was live becomes Dormant: ADR 0003 drops the turn a restart tore, so there is
2218
+ * nothing running to report. `lifecycle` is absent on a meta written before the split, and the
2219
+ * deprecated `status` mirror is what stands in — including its own live values, which collapse the
2220
+ * same way.
2221
+ */
2222
+ function lifecycleFrom(meta) {
2223
+ const stored = meta.lifecycle ?? meta.status;
2224
+ return stored === "ended" || stored === "settled" || stored === "dormant" ? stored : "dormant";
2225
+ }
2226
+ function openEnquiries(entries) {
2227
+ const open = new Map();
2228
+ for (const entry of entries) {
2229
+ const event = entry.event;
2230
+ if (event.type !== "enquiry")
2231
+ continue;
2232
+ if (event.state === "asked")
2233
+ open.set(event.askId, { questions: event.questions, ...(event.context === undefined ? {} : { context: event.context }) });
2234
+ else
2235
+ open.delete(event.askId);
2236
+ }
2237
+ return [...open].map(([askId, value]) => ({ askId, ...value }));
2238
+ }
2239
+ /**
2240
+ * The Permission Prompts the transcript last saw open.
2241
+ *
2242
+ * Derived rather than held, for the reason `openEnquiries` is derived: a prompt belongs to a turn of
2243
+ * a Backend Session and the host outlives both, and reading it back from the transcript is the only
2244
+ * thing that works on the restart path — nothing was in memory to read.
2245
+ *
2246
+ * The tool name comes back with it, because a snapshot carries the whole state and the terminal one
2247
+ * the host is about to append needs it again.
2248
+ */
2249
+ function openPermissions(entries) {
2250
+ const open = new Map();
2251
+ for (const entry of entries) {
2252
+ const event = entry.event;
2253
+ if (event.type !== "permission")
2254
+ continue;
2255
+ if (event.state === "asked")
2256
+ open.set(event.callId, {
2257
+ tool: event.tool,
2258
+ ...(event.context === undefined ? {} : { context: event.context }),
2259
+ ...(event.allowAlways === undefined ? {} : { allowAlways: event.allowAlways }),
2260
+ ...(event.authorizationScope === undefined ? {} : { authorizationScope: event.authorizationScope }),
2261
+ });
2262
+ else
2263
+ open.delete(event.callId);
2264
+ }
2265
+ return [...open].map(([callId, value]) => ({ callId, ...value }));
2266
+ }
2267
+ /**
2268
+ * The same scan for Background Calls (ADR 0021).
2269
+ *
2270
+ * `producer` comes back with the tool name because the terminal snapshot must carry it too: the web
2271
+ * client decides from `producer` which surface a card belongs to, so one that dropped it would move
2272
+ * the card as it settled.
2273
+ */
2274
+ function openBackgroundCalls(entries) {
2275
+ const open = new Map();
2276
+ for (const entry of entries) {
2277
+ const event = entry.event;
2278
+ if (event.type !== "background_call")
2279
+ continue;
2280
+ if (event.state === "running") {
2281
+ open.set(event.callId, { tool: event.tool, ...(event.producer === undefined ? {} : { producer: event.producer }) });
2282
+ }
2283
+ else
2284
+ open.delete(event.callId);
2285
+ }
2286
+ return [...open].map(([callId, brief]) => ({ callId, ...brief }));
2287
+ }
2288
+ function openSubagents(entries) {
2289
+ const open = new Map();
2290
+ for (const entry of entries) {
2291
+ const event = entry.event;
2292
+ if (event.type !== "subagent")
2293
+ continue;
2294
+ if (event.state === "running" || event.state === "waiting")
2295
+ open.set(event.subagentId, event.name);
2296
+ else
2297
+ open.delete(event.subagentId);
2298
+ }
2299
+ return [...open].map(([subagentId, name]) => ({ subagentId, name }));
2300
+ }
2301
+ /** What the transcript last reported this Agent Session had spent, across every Backend Session. */
2302
+ function spendFrom(entries) {
2303
+ let spend;
2304
+ for (const entry of entries) {
2305
+ const event = entry.event;
2306
+ if (event.type === "context_usage" && event.spend)
2307
+ spend = event.spend;
2308
+ }
2309
+ return spend;
2310
+ }
2311
+ function capabilitiesFrom(entries) {
2312
+ let capabilities;
2313
+ for (const entry of entries) {
2314
+ const event = entry.event;
2315
+ if (event.type === "session_started" || event.type === "capabilities_changed") {
2316
+ capabilities = event.capabilities;
2317
+ }
2318
+ }
2319
+ return capabilities;
2320
+ }
2321
+ function queueChanged(queue) {
2322
+ return {
2323
+ type: "queue_changed",
2324
+ pending: queue.map((message) => message.text),
2325
+ ids: queue.map((message) => message.id),
2326
+ attachments: queue.map((message) => message.attachments),
2327
+ };
2328
+ }
2329
+ function firstLine(text) {
2330
+ const line = text.trim().split(/\r?\n/, 1)[0] ?? "";
2331
+ return line.length > 60 ? `${line.slice(0, 59)}…` : line || "Untitled session";
2332
+ }
2333
+ function errorMessage(error) {
2334
+ return error instanceof Error ? error.message : String(error);
2335
+ }
2336
+ function scopeKey(scope) {
2337
+ try {
2338
+ return realpathSync(scope);
2339
+ }
2340
+ catch {
2341
+ return resolve(scope);
2342
+ }
2343
+ }