@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

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 (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,23 +1,36 @@
1
- import { credentialKey } from "./credential-redaction.js";
1
+ import { waitForAbort } from "../backend/worker/rpc.js";
2
+ import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from '../backend/session-tools.js';
3
+ import { sessionToolSummary, sessionToolPage } from './session-tool-views.js';
4
+ import { credentialKey } from './credential-redaction.js';
2
5
  import { randomUUID } from "node:crypto";
3
- import { existsSync, realpathSync } from "node:fs";
4
- import { join, resolve } from "node:path";
6
+ import { copyFileSync, existsSync, mkdirSync, realpathSync, rmSync } from "node:fs";
7
+ import { isAbsolute, join, resolve } from "node:path";
5
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
6
- import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
7
- import { stackStatus, actionStackStatus, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
8
- import { gitStatus, snapshot, target, branchChanges, canNameBranch, publish } from "./publish.js";
9
+ import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog, dropUnchangedBranch, fetchBranch, listPullRequests, projectPullRequest, projectTarget, pullRequestRange, remoteUrl, submitReview } from "./pull-request.js";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage, mergeableStack, stackMergeMethods } from "./stack.js";
11
+ import { changes, changesText, commitContext, diff, fileDiff, rangeChanges } from "./changes.js";
12
+ import { gh } from "./github.js";
13
+ import { resolveRepository } from "./repository.js";
14
+ import { commit } from "./commit.js";
15
+ import { push, pushState } from "./push.js";
16
+ import { GitStates, readStatus } from "./git-state.js";
17
+ import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, pullRequestTourInput, tourInput, tourText } from "./tour.js";
18
+ import { diffExcerpts, hasDiffReference, messageExcerpts } from "./diff-excerpts.js";
9
19
  import { resolveDefaultBackend } from "../protocol/settings.js";
10
20
  import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
11
21
  import { deriveStatus, railGroupRank } from "../client/status.js";
12
22
  // `switchBranch` is aliased because this class has a method of that name: the method is the
13
23
  // Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
14
- import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
24
+ import { addDetachedCheckout, createWorktree, refExists, removeDetachedCheckout, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
15
25
  import { SessionLog } from "./log.js";
16
26
  import { probeModels } from "./models.js";
17
- import { probeSkills } from "./skills.js";
27
+ import { PiModelProbeCache } from "./pi-model-cache.js";
28
+ import { ScheduleValidationError } from "../workflows/schedule-errors.js";
29
+ import { probePlanLimits, probeSkills } from "./skills.js";
18
30
  import { recordTiming } from "./timings.js";
19
31
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
20
- import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from "./summariser.js";
32
+ import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
33
+ import { SpendLedger } from "./spend-ledger.js";
21
34
  /**
22
35
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
23
36
  * Scope that is not a repository, a checkout git itself refused.
@@ -40,6 +53,7 @@ export class SessionHost {
40
53
  backends = new Map();
41
54
  /** Model probes by backend name, held in flight rather than resolved — see `models`. */
42
55
  modelProbes = new Map();
56
+ piModelProbeCache = new PiModelProbeCache();
43
57
  /** One warm Skills session per Backend Adapter, for the last Scope asked — see `skillsFor` (ADR 0035). */
44
58
  skillSessions = new Map();
45
59
  /**
@@ -50,6 +64,7 @@ export class SessionHost {
50
64
  * one dimension.
51
65
  */
52
66
  skillProbes = new Map();
67
+ planLimitProbe;
53
68
  /**
54
69
  * One Summary Model session, booted before a naming needs it (ADR 0020).
55
70
  *
@@ -57,10 +72,13 @@ export class SessionHost {
57
72
  * `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
58
73
  */
59
74
  summarySpare = new SummaryModelSpare();
75
+ spendLedger;
60
76
  stackReviews = new Map();
61
77
  gitOperations = new Set();
78
+ gitStates = new GitStates();
62
79
  closingScopes = new Set();
63
- publishReviews = new Map();
80
+ tours = new Map();
81
+ pullRequestTours = new Map();
64
82
  refuseGitOperation(scope) {
65
83
  if (this.gitOperations.has(scopeKey(scope)))
66
84
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -97,45 +115,54 @@ export class SessionHost {
97
115
  }
98
116
  finally {
99
117
  this.gitOperations.delete(key);
118
+ void this.gitStates.refresh(scope);
100
119
  }
101
120
  }
102
121
  async prepareStack(sessionId, action) {
103
- if (action !== "submit" && action !== "sync")
122
+ if (action !== "submit" && action !== "sync" && action !== "merge")
104
123
  throw new CommandRefused("Invalid Stack review action.");
105
124
  const record = this.record(sessionId);
106
125
  return this.withGitOperation(record.scope, async () => {
107
126
  this.stackReviews.delete(sessionId);
108
127
  await cleanStack(record.scope);
109
- const status = await actionStackStatus(record.scope);
128
+ const status = await stackStatus(record.scope);
110
129
  if (!status.view)
111
- throw new Error(status.problem ?? "No stack found.");
130
+ throw new Error(status.notice ?? "This branch is not in a stack.");
131
+ const fingerprint = await stackFingerprint(record.scope, status.view, action === "sync");
112
132
  const review = { token: randomUUID(), action, view: status.view };
113
- this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
133
+ if (action === "merge") {
134
+ review.view = await mergeableStack(record.scope);
135
+ review.mergeMethods = await stackMergeMethods(record.scope, review.view);
136
+ if (!review.mergeMethods.length)
137
+ throw new Error("You cannot merge pull requests in this repository.");
138
+ }
139
+ this.stackReviews.set(sessionId, { review, fingerprint, expires: Date.now() + 15 * 60_000 });
114
140
  return review;
115
141
  });
116
142
  }
117
143
  async changeStack(sessionId, input) {
118
144
  const record = this.record(sessionId);
119
145
  return this.withGitOperation(record.scope, async () => {
120
- if (input.action === "submit" || input.action === "sync") {
146
+ if (input.action === "submit" || input.action === "sync" || input.action === "merge") {
121
147
  const saved = this.stackReviews.get(sessionId);
122
148
  this.stackReviews.delete(sessionId);
123
149
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
124
150
  throw new Error("This Stack review expired. Review again.");
151
+ if (input.action === "merge" && !saved.review.mergeMethods?.includes(input.method))
152
+ throw new Error("This repository does not permit that merge method.");
125
153
  await cleanStack(record.scope);
126
- const status = await actionStackStatus(record.scope);
154
+ const status = await stackStatus(record.scope);
127
155
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
128
156
  throw new Error("The reviewed stack changed. Review again.");
129
157
  }
130
158
  try {
131
- return await changeStack(record.scope, input);
159
+ return await this.afterPullRequestWrite(record.scope, changeStack(record.scope, input));
132
160
  }
133
161
  finally {
134
162
  for (const other of this.sessions.values()) {
135
163
  if (scopeKey(other.scope) !== scopeKey(record.scope))
136
164
  continue;
137
165
  this.stackReviews.delete(other.id);
138
- this.publishReviews.delete(other.id);
139
166
  await this.refreshBranch(other);
140
167
  other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
141
168
  }
@@ -145,67 +172,282 @@ export class SessionHost {
145
172
  async assistStack(sessionId) {
146
173
  const record = this.record(sessionId);
147
174
  await this.withGitOperation(record.scope, async () => {
148
- const status = await actionStackStatus(record.scope);
175
+ const status = await stackStatus(record.scope);
149
176
  if (!status.rebasing)
150
- throw new Error("No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
177
+ throw new Error(status.notice === otherWorktreeRebase ? otherWorktreeRebase : "No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
151
178
  });
152
179
  await this.send(sessionId, stackConflictMessage, "now");
153
180
  }
154
- async gitStatus(sessionId) {
155
- return gitStatus(this.record(sessionId).scope);
181
+ pollGitState(forced) {
182
+ return this.gitStates.poll([...this.sessions.values()].map(record => ({ scope: record.scope, lifecycle: record.lifecycle, watched: record.log.watched })), forced);
156
183
  }
157
- async preparePublish(sessionId) {
158
- const record = this.record(sessionId);
159
- return this.withGitOperation(record.scope, async () => {
160
- this.publishReviews.delete(sessionId);
161
- for (const [id, review] of this.publishReviews)
162
- if (review.expires < Date.now())
163
- this.publishReviews.delete(id);
164
- const { input: changes, ...reviewed } = await snapshot(record.scope);
165
- const destination = await target(record.scope, reviewed.branch);
166
- const committed = await branchChanges(record.scope, destination);
167
- if (reviewed.files.length === 0 && committed.commits.length === 0 && !destination.pr)
168
- throw new CommandRefused("There are no changes to publish.");
169
- let text = { commitMessage: "", title: destination.pr?.title ?? "", body: "" };
170
- let warning;
171
- const model = this.summaryModel?.(record.backendName);
172
- try {
173
- if (!model)
174
- throw new Error("No Summary Model is configured. Choose one in Settings, or enter publish text below.");
175
- text = await summarisePublish({ backend: this.backendFor(model.backend), modelId: model.modelId, text: `${changes}\nCommitted branch changes:\n${committed.input}` });
176
- }
177
- catch (error) {
178
- warning = `Enter publish text manually. ${error instanceof Error ? error.message : String(error)}`;
179
- }
180
- const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
181
- ? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
182
- : undefined;
183
- delete text.suggestedBranch;
184
- const token = randomUUID();
185
- this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
186
- 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 } : {}) };
184
+ async afterPullRequestWrite(scope, write) {
185
+ try {
186
+ return await write;
187
+ }
188
+ finally {
189
+ await this.pollGitState(scope);
190
+ }
191
+ }
192
+ async readGit(read) {
193
+ try {
194
+ return await read();
195
+ }
196
+ catch (error) {
197
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
198
+ }
199
+ }
200
+ readStack(sessionId) {
201
+ const scope = this.gitScope(sessionId);
202
+ return this.readGit(async () => {
203
+ const status = await stackStatus(scope);
204
+ if (status.view && !await stackTitles(scope, status.view))
205
+ status.notice = "Pull request titles could not be read. Copy uses the links.";
206
+ return status;
187
207
  });
188
208
  }
189
- async publish(sessionId, input) {
209
+ projectScope(project) {
210
+ if (typeof project !== "string" || !isRepository(project))
211
+ throw new CommandRefused(`${project} is not a git repository.`);
212
+ return project;
213
+ }
214
+ pullRequestPlace(target) {
215
+ if (target.project === undefined)
216
+ return { scope: this.record(target.sessionId).scope };
217
+ return { scope: this.projectScope(target.project), find: projectTarget };
218
+ }
219
+ /** Start an Agent Session in a Worktree on the head branch of a Pull Request, or focus the one already on it. */
220
+ async startPullRequestSession(project, ref) {
221
+ const scope = this.projectScope(project);
222
+ const pr = await this.readGit(() => projectTarget(scope, ref, gh));
223
+ const repository = await this.readGit(() => resolveRepository(scope, undefined, gh));
224
+ if (pr.state !== "OPEN")
225
+ throw new CommandRefused("This pull request is not open.");
226
+ if (pr.headRepository?.id !== repository.base.id)
227
+ throw new CommandRefused("This pull request comes from a fork. Flow can start an Agent Session only on a branch in the base repository.");
228
+ const existing = [...this.sessions.values()].find(record => record.lifecycle !== "ended" && scopeKey(record.worktree?.repo ?? record.scope) === scopeKey(scope) && !record.branch?.detached && record.branch?.name === pr.headRefName);
229
+ if (existing)
230
+ return existing.id;
231
+ if (await refExists(scope, pr.headRefName))
232
+ throw new CommandRefused(`The branch ${pr.headRefName} already exists in ${scope}. Start an Agent Session on it from the New Agent Session page.`);
233
+ const { remote } = await this.readGit(() => remoteUrl(scope, pr.repo));
234
+ if (!remote)
235
+ throw new CommandRefused(`No remote in ${scope} points to ${pr.repo}. Add one.`);
236
+ const fetched = await this.readGit(() => fetchBranch(scope, remote, pr.headRefName));
237
+ try {
238
+ return await this.create({ scope, worktree: { from: `${remote}/${pr.headRefName}`, branch: pr.headRefName } });
239
+ }
240
+ catch (error) {
241
+ await dropUnchangedBranch(scope, pr.headRefName, fetched);
242
+ throw error;
243
+ }
244
+ }
245
+ gitScope(sessionId) {
246
+ const scope = this.record(sessionId).scope;
247
+ if (!isRepository(scope))
248
+ throw new CommandRefused("This Scope is not a Git repository.");
249
+ return scope;
250
+ }
251
+ async readChanges(command) {
252
+ const scope = this.gitScope(command.sessionId);
253
+ const base = (branch) => this.gitStates.pullRequestBase(scope, branch);
254
+ return this.readGit(async () => {
255
+ if (command.type === "git_diff")
256
+ return await diff(scope, command.view, command.path, base);
257
+ if (command.view === "branch")
258
+ return await changes(scope, command.view, base);
259
+ const read = await readStatus(scope);
260
+ return { files: read.files, commits: [], fingerprint: read.fingerprint, ...await commitContext(scope, read.local.branch, branch => this.gitStates.hasPullRequest(scope, branch)) };
261
+ });
262
+ }
263
+ async commit(sessionId, input) {
264
+ this.gitScope(sessionId);
190
265
  const record = this.record(sessionId);
191
266
  return this.withGitOperation(record.scope, async () => {
192
- const review = this.publishReviews.get(sessionId);
193
- if (!review || review.token !== input.token || review.expires < Date.now())
194
- throw new CommandRefused("This Publish review expired. Open Publish again.");
195
- this.publishReviews.delete(sessionId);
267
+ const before = await head(record.scope);
196
268
  try {
197
- return await publish(record.scope, review.snapshot, review.target, input);
269
+ return await commit(record.scope, input);
198
270
  }
199
271
  finally {
200
- for (const other of this.sessions.values()) {
201
- if (scopeKey(other.scope) !== scopeKey(record.scope))
202
- continue;
203
- await this.refreshBranch(other);
204
- other.pendingBranchNote = "[Flow] Git publishing was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
272
+ const after = await head(record.scope);
273
+ if (after.ok && before.ok && after.value.name !== before.value.name) {
274
+ for (const other of this.sessions.values()) {
275
+ if (scopeKey(other.scope) !== scopeKey(record.scope))
276
+ continue;
277
+ await this.refreshBranch(other);
278
+ other.pendingBranchNote = `[Flow] A commit from the Git pane moved this Scope to branch ${after.value.name}. Re-read the branch and changed files before relying on earlier reads.`;
279
+ }
205
280
  }
206
281
  }
207
282
  });
208
283
  }
284
+ async suggestGitText(sessionId, kind, paths) {
285
+ const record = this.record(sessionId);
286
+ if (!["commit", "pull_request", "branch"].includes(kind) || (paths !== undefined && (!Array.isArray(paths) || paths.some(path => typeof path !== "string"))))
287
+ throw new CommandRefused("Invalid suggestion request.");
288
+ const model = this.summaryModel?.(record.backendName);
289
+ if (!model)
290
+ throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
291
+ return this.readGit(async () => {
292
+ const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
293
+ return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind,
294
+ spent: (spend) => this.recordSpend("publish", randomUUID(), this.spendScope(this.record(sessionId)), spend) });
295
+ });
296
+ }
297
+ tour(sessionId) {
298
+ this.record(sessionId);
299
+ return this.tours.get(sessionId)?.view ?? { state: "idle" };
300
+ }
301
+ startTour(sessionId) {
302
+ const record = this.record(sessionId);
303
+ this.dropTour(sessionId);
304
+ const tour = { id: randomUUID(), view: { state: "running" } };
305
+ this.tours.set(sessionId, tour);
306
+ void this.runTour(record, tour);
307
+ return tour.view;
308
+ }
309
+ cancelTour(sessionId) {
310
+ this.record(sessionId);
311
+ this.dropTour(sessionId);
312
+ return { state: "idle" };
313
+ }
314
+ dropTour(sessionId) {
315
+ const tour = this.tours.get(sessionId);
316
+ this.tours.delete(sessionId);
317
+ void tour?.handle?.cancel().catch(() => undefined);
318
+ }
319
+ async runTour(record, tour) {
320
+ const current = () => this.tours.get(record.id) === tour;
321
+ let made;
322
+ try {
323
+ const { input, base, ...found } = await tourInput(record.scope);
324
+ made = found;
325
+ if (!current())
326
+ return;
327
+ tour.view = { state: "running", branch: made.branch, head: made.head };
328
+ if (!record.session)
329
+ await this.revive(record.id);
330
+ const session = record.session;
331
+ if (!current())
332
+ return;
333
+ if (!session)
334
+ throw new Error("This Backend Adapter cannot run a tour.");
335
+ const log = record.log.since(0);
336
+ const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
337
+ const effort = log.findLast(({ event }) => event.type === "effort_changed")?.event;
338
+ const chosen = this.tourModel?.(record.backendName);
339
+ const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
340
+ if (!modelId)
341
+ throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
342
+ const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off", spend => this.workflowSpend(record.id, `tour:${tour.id}`, spend));
343
+ const excerpts = await diffExcerpts(text, found.head, async (path) => ({ view: "branch", diff: await fileDiff(record.scope, path, base, found.head) }));
344
+ if (current())
345
+ tour.view = { state: "done", text, excerpts, ...made };
346
+ }
347
+ catch (error) {
348
+ if (current())
349
+ tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
350
+ }
351
+ }
352
+ async writeTour(session, tour, input, modelId, effort, spent) {
353
+ if (!session.startWorkflowSubagent)
354
+ throw new Error("This Backend Adapter cannot run a tour.");
355
+ tour.handle = session.startWorkflowSubagent({
356
+ id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId, effort, permissionMode: "ask",
357
+ emit: ({ event }) => {
358
+ if (event.type === "permission" && event.state === "asked") {
359
+ queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
360
+ }
361
+ if (event.type === "enquiry" && event.state === "asked") {
362
+ queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
363
+ }
364
+ if (event.type === "spend")
365
+ spent(event.spend);
366
+ },
367
+ });
368
+ return tourText(await tour.handle.done);
369
+ }
370
+ pullRequestTourKey(project, ref) {
371
+ return `${scopeKey(this.projectScope(project))}\0${ref?.repo}#${ref?.number}`;
372
+ }
373
+ pullRequestTour(project, ref) {
374
+ return this.pullRequestTours.get(this.pullRequestTourKey(project, ref))?.view ?? { state: "idle" };
375
+ }
376
+ startPullRequestTour(project, ref) {
377
+ const key = this.pullRequestTourKey(project, ref);
378
+ if (!this.store)
379
+ throw new CommandRefused("This Session Host keeps no state, so it cannot make a tour.");
380
+ this.dropPullRequestTour(key);
381
+ const tour = { id: randomUUID(), view: { state: "running" } };
382
+ this.pullRequestTours.set(key, tour);
383
+ tour.running = this.runPullRequestTour(project, ref, key, tour);
384
+ return tour.view;
385
+ }
386
+ cancelPullRequestTour(project, ref) {
387
+ this.dropPullRequestTour(this.pullRequestTourKey(project, ref));
388
+ return { state: "idle" };
389
+ }
390
+ dropPullRequestTour(key) {
391
+ const tour = this.pullRequestTours.get(key);
392
+ this.pullRequestTours.delete(key);
393
+ void tour?.handle?.cancel().catch(() => undefined);
394
+ }
395
+ /** A Tour with no Agent Session: a host Backend Session over a read-only checkout of the Pull Request head. */
396
+ async runPullRequestTour(project, ref, key, tour) {
397
+ const current = () => this.pullRequestTours.get(key) === tour;
398
+ let made;
399
+ let checkout;
400
+ let session;
401
+ try {
402
+ const range = await pullRequestRange(project, ref);
403
+ made = { branch: range.pr.headRefName, head: range.head, repo: range.pr.repo };
404
+ if (current())
405
+ tour.view = { state: "running", branch: made.branch, head: made.head };
406
+ const input = await pullRequestTourInput(project, range, { headRefName: range.pr.headRefName, baseRefName: range.pr.baseBranch });
407
+ const backendName = resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
408
+ if (backendName === undefined)
409
+ throw new Error("No backends available");
410
+ const chosen = this.tourModel?.(backendName);
411
+ const configured = chosen?.modelId ?? this.defaultModel?.(backendName);
412
+ let reported;
413
+ if (!current())
414
+ return;
415
+ checkout = join(this.store.worktreesRoot(), ".tours", tour.id);
416
+ const added = await addDetachedCheckout(project, range.head, checkout);
417
+ if (!added.ok) {
418
+ checkout = undefined;
419
+ throw new Error(added.failure.message);
420
+ }
421
+ if (!current())
422
+ return;
423
+ session = await this.backendFor(backendName).create({
424
+ scope: checkout, permissionMode: "ask", readOnly: this.readOnlyEnforcement(), ...(configured ? { modelId: configured } : {}),
425
+ emit: (event) => { if (event.type === "model_changed")
426
+ reported = event.model.id; },
427
+ });
428
+ if (!current())
429
+ return;
430
+ const modelId = configured ?? reported;
431
+ if (!modelId)
432
+ throw new Error("The Default Backend reported no model. Choose a Tour Model in Settings.");
433
+ const text = await this.writeTour(session, tour, input, modelId, chosen?.effort ?? this.defaultEffort?.(backendName) ?? "off", spend => this.recordSpend("tour", tour.id, scopeKey(project), spend));
434
+ const excerpts = await diffExcerpts(text, range.head, async (path) => ({ view: "branch", diff: await fileDiff(project, path, range.base, range.head) }));
435
+ if (current())
436
+ tour.view = { state: "done", text, excerpts, ...made };
437
+ }
438
+ catch (error) {
439
+ if (current())
440
+ tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
441
+ }
442
+ finally {
443
+ await session?.dispose().catch(() => undefined);
444
+ if (checkout)
445
+ await removeDetachedCheckout(project, checkout);
446
+ }
447
+ }
448
+ readOnlyEnforcement(isolationMode = this.filesystemIsolationMode()) {
449
+ return isolationMode === "bubblewrap" || (isolationMode === "sandbox" && this.sandboxSharing?.() !== "shared") ? "mounted" : "tools";
450
+ }
209
451
  store;
210
452
  retention;
211
453
  standingAuthorisations;
@@ -217,12 +459,17 @@ export class SessionHost {
217
459
  defaultEffort;
218
460
  defaultPermissionMode;
219
461
  summaryModel;
462
+ tourModel;
220
463
  closedListeners = new Set();
464
+ attentionListeners = new Set();
221
465
  backendFailures = new Set();
222
466
  keptListeners = new Set();
223
467
  filesystemIsolation;
224
468
  sandbox;
225
469
  sandboxSharing;
470
+ updateSourceBranch;
471
+ projectRoot;
472
+ projectPaths;
226
473
  shared;
227
474
  mcpConnections;
228
475
  mcpAuth;
@@ -231,11 +478,15 @@ export class SessionHost {
231
478
  this.filesystemIsolation = options.filesystemIsolationMode;
232
479
  this.sandbox = options.sandboxSupport;
233
480
  this.sandboxSharing = options.sandboxSharing;
481
+ this.updateSourceBranch = options.updateSourceBranch;
482
+ this.projectRoot = options.projectRoot;
483
+ this.projectPaths = options.projectPaths;
234
484
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
235
485
  this.mcpConnections = options.mcpConnections;
236
486
  this.mcpAuth = options.mcpAuth;
237
487
  this.resolveSecret = options.resolveSecret;
238
488
  this.store = options.store;
489
+ this.spendLedger = options.store ? new SpendLedger(options.store.root) : undefined;
239
490
  this.retention = options.retention ?? "never";
240
491
  this.standingAuthorisations = options.standingAuthorisations;
241
492
  this.allowTool = options.allowTool;
@@ -246,6 +497,7 @@ export class SessionHost {
246
497
  this.defaultEffort = options.defaultEffort;
247
498
  this.defaultPermissionMode = options.defaultPermissionMode;
248
499
  this.summaryModel = options.summaryModel;
500
+ this.tourModel = options.tourModel;
249
501
  }
250
502
  /**
251
503
  * Notified when an Agent Session stops being something its owner is working in — Settled, Ended
@@ -259,6 +511,10 @@ export class SessionHost {
259
511
  this.closedListeners.add(listener);
260
512
  return () => this.closedListeners.delete(listener);
261
513
  }
514
+ onAttentionRaised(listener) {
515
+ this.attentionListeners.add(listener);
516
+ return () => this.attentionListeners.delete(listener);
517
+ }
262
518
  announceClosed(sessionId) {
263
519
  for (const listener of this.closedListeners)
264
520
  listener(sessionId);
@@ -296,19 +552,29 @@ export class SessionHost {
296
552
  * In flight rather than resolved is what is remembered, so two clients opening the page at once
297
553
  * spawn one probe between them rather than one each.
298
554
  */
299
- async models(scope, refresh = false) {
555
+ async models(scope, refresh = false, backendName) {
300
556
  if (refresh)
301
557
  this.modelProbes.clear();
302
- const probes = [...this.backends.values()].map((backend) => {
558
+ const backends = backendName === undefined ? [...this.backends.values()] : [this.backendFor(backendName)];
559
+ const probes = backends.map((backend) => {
303
560
  const held = this.modelProbes.get(backend.name);
304
561
  if (held)
305
562
  return held;
306
- const probe = this.timed("models", backend, false, (timed) => probeModels(timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false)));
563
+ const probe = this.timed("models", backend, false, (timed) => probeModels(backend.name === 'pi' ? this.piModelProbeCache.wrap(timed) : timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false), refresh));
307
564
  this.modelProbes.set(backend.name, probe);
308
565
  return probe;
309
566
  });
310
567
  return await Promise.all(probes);
311
568
  }
569
+ async workflowAgentModels(scope, backend) {
570
+ const [catalogue] = await this.models(scope, false, backend);
571
+ if (!catalogue || catalogue.problem)
572
+ throw new Error(catalogue?.problem ?? 'Workflow model capabilities are unavailable');
573
+ const probe = this.skillSessions.get(backend);
574
+ if (!probe || probe.dead || !probe.session.startWorkflowSubagent)
575
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
576
+ return catalogue.models;
577
+ }
312
578
  /**
313
579
  * Which Skills a Scope offers through one Backend Adapter, with no Agent Session in it.
314
580
  *
@@ -355,6 +621,27 @@ export class SessionHost {
355
621
  }
356
622
  return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
357
623
  }
624
+ async planLimits(scope) {
625
+ this.planLimitProbe ??= Promise.all([...this.backends.values()].map(async (backend) => (await this.askPlanLimits(backend, scope)).map((windows) => ({ backend: backend.name, ...windows }))))
626
+ .then((answers) => answers.flat())
627
+ .finally(() => { this.planLimitProbe = undefined; });
628
+ return await this.planLimitProbe;
629
+ }
630
+ async askPlanLimits(backend, scope) {
631
+ const warm = this.skillSessions.get(backend.name);
632
+ if (warm && !warm.dead) {
633
+ if (!warm.session.planLimits)
634
+ return [];
635
+ try {
636
+ return await this.timed("planLimits", backend, true, () => warm.session.planLimits());
637
+ }
638
+ catch {
639
+ this.skillSessions.delete(backend.name);
640
+ void warm.session.dispose().catch(() => { });
641
+ }
642
+ }
643
+ return await this.timed("planLimits", backend, false, (timed) => probePlanLimits(timed, scope, (held) => this.holdSkillSession(backend.name, held, false)));
644
+ }
358
645
  /** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
359
646
  holdSkillSession(name, held, replace) {
360
647
  const old = this.skillSessions.get(name);
@@ -423,6 +710,9 @@ export class SessionHost {
423
710
  };
424
711
  if (reason !== "Input needed")
425
712
  record.latestOutcome = record.latestAttention;
713
+ for (const listener of this.attentionListeners) {
714
+ listener({ sessionId: record.id, title: record.title, reason, version, at });
715
+ }
426
716
  return { at, version };
427
717
  }
428
718
  /**
@@ -455,6 +745,7 @@ export class SessionHost {
455
745
  // lifting an Ended row back out of Filed away.
456
746
  const input = record.lifecycle === "live" ? newestAt(parentInput, workflowInput) : undefined;
457
747
  const outcome = record.latestOutcome;
748
+ const git = this.gitStates.summary(record.scope);
458
749
  const unread = outcome !== undefined && outcome.version > record.readAttentionVersion;
459
750
  const attention = input
460
751
  ? {
@@ -490,7 +781,9 @@ export class SessionHost {
490
781
  lastSeq: record.log.lastSeq,
491
782
  ...(record.capabilities ? { capabilities: record.capabilities } : {}),
492
783
  ...(record.branch ? { branch: record.branch } : {}),
784
+ ...(git ? { git } : {}),
493
785
  ...(record.worktree ? { worktree: true } : {}),
786
+ ...(record.readOnly ? { readOnly: true } : {}),
494
787
  ...(record.session || existsSync(record.scope) ? {} : {
495
788
  scopeMissing: true,
496
789
  ...this.suggestion(record.scope),
@@ -520,11 +813,14 @@ export class SessionHost {
520
813
  async load() {
521
814
  if (!this.store)
522
815
  return;
816
+ rmSync(join(this.store.worktreesRoot(), ".tours"), { recursive: true, force: true });
523
817
  for (const id of await this.store.listSessionIds()) {
524
818
  const meta = this.store.readMeta(id);
525
819
  if (!meta || this.sessions.has(id))
526
820
  continue;
527
821
  const entries = this.store.readEntries(id);
822
+ if (this.spendLedger?.needsBackfill)
823
+ this.backfillSpend(id, scopeKey(meta.worktree?.repo ?? meta.scope), entries);
528
824
  const record = {
529
825
  id: meta.id,
530
826
  scope: meta.scope,
@@ -564,11 +860,15 @@ export class SessionHost {
564
860
  branch: branchFrom(entries),
565
861
  branchGeneration: 0,
566
862
  worktree: meta.worktree,
863
+ ...(meta.readOnly ? { readOnly: true } : {}),
864
+ ...(meta.scheduledOccurrenceId ? { scheduledOccurrenceId: meta.scheduledOccurrenceId } : {}),
567
865
  pendingBranchNote: undefined,
568
866
  capabilities: capabilitiesFrom(entries),
569
867
  spend: spendFrom(entries),
570
868
  mcpConnectionIds: meta.mcpConnectionIds ?? [],
571
869
  resumeToken: meta.resumeToken,
870
+ imported: meta.imported,
871
+ rewindTo: meta.rewindTo,
572
872
  modelId: meta.modelId,
573
873
  effort: meta.effort,
574
874
  permissionMode: meta.permissionMode ?? this.permissionDefault(meta.backend),
@@ -589,9 +889,53 @@ export class SessionHost {
589
889
  }
590
890
  this.persist(record);
591
891
  }
892
+ this.spendLedger?.finishBackfill();
592
893
  await this.reap();
593
894
  }
895
+ backfillSpend(sessionId, scope, entries) {
896
+ for (const { event, at } of entries.slice(entries.findLastIndex(({ event }) => event.type === "forked") + 1)) {
897
+ if (event.type === "context_usage" && event.spend)
898
+ this.spendLedger.record("session", sessionId, scope, event.spend, at);
899
+ if (event.type === "workflow_spend")
900
+ this.spendLedger.record("workflow", JSON.stringify([sessionId, event.executionId]), scope, event.spend, at);
901
+ }
902
+ }
903
+ recordSpend(source, key, scope, spend) {
904
+ this.spendLedger?.record(source, key, scope, spend);
905
+ }
906
+ spendSummary() {
907
+ return this.spendLedger?.summary();
908
+ }
909
+ namingSpent(record) {
910
+ return (spend) => this.recordSpend("naming", randomUUID(), this.spendScope(record), spend);
911
+ }
912
+ spendScope(record) {
913
+ return scopeKey(record.worktree?.repo ?? record.scope);
914
+ }
915
+ scheduledAttachments = new Map();
916
+ /** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
917
+ * The caller has already journaled the intended identity before entering this operation. */
918
+ attachScheduled(options) {
919
+ if (this.workflowShutdown)
920
+ return Promise.reject(new CommandRefused('Session Host is stopping'));
921
+ const id = options.scheduled.id;
922
+ const pending = this.scheduledAttachments.get(id);
923
+ if (pending)
924
+ return pending;
925
+ const attachment = this.create(options).finally(() => { this.scheduledAttachments.delete(id); });
926
+ this.scheduledAttachments.set(id, attachment);
927
+ return attachment;
928
+ }
594
929
  async create(options) {
930
+ if (options.scheduled) {
931
+ const existing = this.sessions.get(options.scheduled.id);
932
+ if (existing) {
933
+ if (existing.scheduledOccurrenceId !== options.scheduled.occurrenceId)
934
+ throw new Error('Scheduled association mismatch');
935
+ await this.openWorkflowSession(existing.id);
936
+ return existing.id;
937
+ }
938
+ }
595
939
  const connections = this.mcpConnections?.() ?? [];
596
940
  if (options.mcpConnectionIds !== undefined && (!Array.isArray(options.mcpConnectionIds) || options.mcpConnectionIds.some((id) => typeof id !== "string")))
597
941
  throw new Error("Invalid MCP selection");
@@ -603,17 +947,26 @@ export class SessionHost {
603
947
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
604
948
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
605
949
  this.validatePermissionMode(backend.name, permissionMode);
606
- const worktree = options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined;
950
+ if (options.readOnly) {
951
+ const root = this.projectRoot?.();
952
+ if (root === undefined || scopeKey(options.scope) !== scopeKey(root))
953
+ throw new CommandRefused("A Read-only Scope must be the Project Root.");
954
+ if (options.worktree)
955
+ throw new CommandRefused("A Read-only Scope cannot be a Worktree.");
956
+ }
957
+ const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
958
+ const worktree = options.scheduled?.worktree ?? cut?.worktree;
607
959
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
608
960
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
609
961
  // that is not there.
610
962
  const scope = scopeKey(worktree?.path ?? options.scope);
611
- const id = randomUUID();
963
+ const id = options.scheduled?.id ?? randomUUID();
612
964
  const now = new Date().toISOString();
613
965
  const modelId = options.modelId ?? this.defaultModel?.(backend.name);
614
966
  const effort = options.effort ?? this.defaultEffort?.(backend.name);
615
967
  const record = {
616
968
  id,
969
+ ...(options.scheduled ? { scheduledOccurrenceId: options.scheduled.occurrenceId } : {}),
617
970
  scope,
618
971
  backendName: backend.name,
619
972
  log: this.newLog(id),
@@ -643,11 +996,14 @@ export class SessionHost {
643
996
  branch: undefined,
644
997
  branchGeneration: 0,
645
998
  worktree,
999
+ ...(options.readOnly ? { readOnly: true } : {}),
646
1000
  pendingBranchNote: undefined,
647
1001
  capabilities: undefined,
648
1002
  spend: undefined,
649
1003
  mcpConnectionIds,
650
1004
  resumeToken: undefined,
1005
+ imported: undefined,
1006
+ rewindTo: undefined,
651
1007
  /*
652
1008
  * Resolved here and never again.
653
1009
  *
@@ -669,6 +1025,8 @@ export class SessionHost {
669
1025
  record.buffered = [];
670
1026
  let session;
671
1027
  try {
1028
+ if (options.fork)
1029
+ this.copyForkState(record, options.fork.source, options.fork.userMessageId, options.fork.prefix);
672
1030
  session = await this.startPermissionBackend(record);
673
1031
  if (session.capabilities.models.length === 0) {
674
1032
  throw new CommandRefused("Model capabilities are unavailable. Check the backend and try again.");
@@ -678,7 +1036,8 @@ export class SessionHost {
678
1036
  // Creation never returns an Agent Session without confirmed models. In particular, do not
679
1037
  // leave a persisted, empty Agent Session (or a newly cut worktree) after a failed probe.
680
1038
  await record.session?.dispose().catch(() => { });
681
- await this.releaseWorktree(record);
1039
+ if (!options.scheduled)
1040
+ await this.releaseWorktree(record);
682
1041
  record.log.closeSubscribers();
683
1042
  this.sessions.delete(id);
684
1043
  this.store?.deleteSession(id);
@@ -692,7 +1051,11 @@ export class SessionHost {
692
1051
  permissionMode: record.permissionMode,
693
1052
  ...(worktree === undefined ? {} : { worktree: true }),
694
1053
  });
1054
+ if (options.fork)
1055
+ this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
695
1056
  this.flushBuffered(record);
1057
+ if (cut?.warning)
1058
+ record.log.append({ type: "notice", level: "warn", text: cut.warning });
696
1059
  // After session_started, never before: the transcript has to open with it (see `buffered`).
697
1060
  await this.refreshBranch(record);
698
1061
  /*
@@ -704,9 +1067,150 @@ export class SessionHost {
704
1067
  * how a spare gets dropped when somebody clears the Setting: nothing will ever *tell* us it
705
1068
  * changed (ADR 0009), so a read-through is the only moment it can be noticed.
706
1069
  */
707
- this.warmSummaryModel(backend.name);
1070
+ if (!options.scheduled)
1071
+ this.warmSummaryModel(backend.name);
1072
+ return id;
1073
+ }
1074
+ /** The conversations a backend's own tool recorded in `scope` that could be imported here (ADR 0047). */
1075
+ async listImports(backendName, scope) {
1076
+ const name = this.importBackendName(backendName);
1077
+ const key = scopeKey(scope);
1078
+ const imported = new Map();
1079
+ for (const record of this.sessions.values()) {
1080
+ if (record.imported && record.backendName === name && record.scope === key)
1081
+ imported.set(record.imported.conversationId, record.id);
1082
+ }
1083
+ return (await this.importBackend(name).listImports(key)).map((conversation) => {
1084
+ const as = imported.get(conversation.id);
1085
+ return as === undefined ? conversation : { ...conversation, importedAs: as };
1086
+ });
1087
+ }
1088
+ /**
1089
+ * Make an Agent Session from one conversation a backend's own tool recorded (ADR 0047).
1090
+ *
1091
+ * Starts no Backend Session, which is what keeps an import cheap and safe to try: nothing is
1092
+ * spent and nothing runs until somebody writes to the result. A `continue` import is Dormant, so
1093
+ * that first message Revives it through the ordinary path (ADR 0003); a `view` import is Ended,
1094
+ * which is already the Lifecycle that means "readable, never Revived, never Reaped".
1095
+ *
1096
+ * Everything is read and copied before any record exists, and a failure removes what was written
1097
+ * so far: a half-made import must not load on the next boot as an Agent Session with no transcript.
1098
+ */
1099
+ importConversation(options) {
1100
+ if (options.mode !== "continue" && options.mode !== "view")
1101
+ throw new CommandRefused(`Unknown import mode: ${String(options.mode)}`);
1102
+ const backendName = this.importBackendName(options.backend);
1103
+ const backend = this.importBackend(backendName);
1104
+ const store = this.storeOrThrow();
1105
+ const scope = scopeKey(options.scope);
1106
+ if (!existsSync(scope))
1107
+ throw new CommandRefused(`${scope} does not exist`);
1108
+ const id = randomUUID();
1109
+ let conversation;
1110
+ let resumeToken;
1111
+ try {
1112
+ conversation = backend.readImport(scope, options.conversationId, (mediaType, base64) => isAttachmentMediaType(mediaType) ? store.writeAttachment(id, mediaType, base64) : undefined);
1113
+ if (options.mode === "continue")
1114
+ resumeToken = backend.copyImport(store.backendDir(id), scope, options.conversationId);
1115
+ }
1116
+ catch (error) {
1117
+ store.deleteSession(id);
1118
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
1119
+ }
1120
+ const now = new Date().toISOString();
1121
+ const effort = options.mode === "continue" ? this.defaultEffort?.(backendName) : undefined;
1122
+ const record = {
1123
+ id,
1124
+ scope,
1125
+ backendName,
1126
+ log: this.newLog(id),
1127
+ session: undefined,
1128
+ reviving: undefined,
1129
+ lifecycle: options.mode === "continue" ? "dormant" : "ended",
1130
+ turnInFlight: false,
1131
+ openSubagentIds: new Set(),
1132
+ openBackgroundCallIds: new Set(),
1133
+ // Now, not when the conversation last moved: somebody who has just imported something is
1134
+ // about to look for it, and a week-old resting time would bury it beneath the Bands above.
1135
+ restingAt: now,
1136
+ settledAt: undefined,
1137
+ // What `backendEpoch` reads back on load, since the transcript opens with `session_started`.
1138
+ backendEpoch: 1,
1139
+ latestAttention: undefined,
1140
+ latestOutcome: undefined,
1141
+ seenAttentionKeys: new Set(),
1142
+ readAttentionVersion: 0,
1143
+ outputPreview: undefined,
1144
+ openPermissionAttention: new Map(),
1145
+ openEnquiryAttention: new Map(),
1146
+ buffered: undefined,
1147
+ queue: [],
1148
+ title: conversation.title,
1149
+ // A name the source gave it is as considered as one ours would be, so it is not replaced by
1150
+ // the first line of whatever is typed next. A first prompt is still only a first line.
1151
+ titleSource: conversation.named ? "summary" : "first-line",
1152
+ titleGeneration: 0,
1153
+ branch: undefined,
1154
+ branchGeneration: 0,
1155
+ worktree: undefined,
1156
+ pendingBranchNote: undefined,
1157
+ capabilities: IMPORTED_CAPABILITIES,
1158
+ spend: undefined,
1159
+ mcpConnectionIds: (this.mcpConnections?.() ?? []).filter((connection) => connection.enabledByDefault).map((connection) => connection.id),
1160
+ resumeToken,
1161
+ imported: { conversationId: options.conversationId },
1162
+ rewindTo: undefined,
1163
+ // Resolved once, as `create` resolves them, so a Revive a month from now does not pick up
1164
+ // whatever the defaults are by then.
1165
+ modelId: options.mode === "continue" ? this.defaultModel?.(backendName) : undefined,
1166
+ effort,
1167
+ permissionMode: this.permissionDefault(backendName),
1168
+ initialEffortUnconfirmed: effort !== undefined,
1169
+ createdAt: conversation.startedAt,
1170
+ updatedAt: now,
1171
+ };
1172
+ try {
1173
+ /*
1174
+ * Opened with `session_started` like every other transcript, so a client reducing it learns
1175
+ * the backend and Scope the usual way. Its Capabilities are honest about having none: no
1176
+ * Backend Session has served this Agent Session yet, and the first Revive reports the real
1177
+ * ones (see `reviveOnce`).
1178
+ */
1179
+ record.log.append({
1180
+ type: "session_started",
1181
+ backend: backendName,
1182
+ scope,
1183
+ capabilities: IMPORTED_CAPABILITIES,
1184
+ permissionMode: record.permissionMode,
1185
+ }, conversation.startedAt);
1186
+ for (const { at, event } of conversation.events)
1187
+ record.log.append(event, at);
1188
+ record.log.append(options.mode === "continue"
1189
+ ? { type: "session_dormant", reason: "imported" }
1190
+ : { type: "session_ended", reason: "imported as read-only" });
1191
+ record.outputPreview = latestParentOutputPreview(record.log.since(0));
1192
+ this.sessions.set(id, record);
1193
+ this.persist(record);
1194
+ }
1195
+ catch (error) {
1196
+ this.sessions.delete(id);
1197
+ store.deleteSession(id);
1198
+ throw error;
1199
+ }
708
1200
  return id;
709
1201
  }
1202
+ importBackendName(name) {
1203
+ const resolved = name ?? resolveDefaultBackend([...this.backends.keys()], this.defaultBackend?.());
1204
+ if (resolved === undefined)
1205
+ throw new CommandRefused("This Session Host has no backend");
1206
+ return resolved;
1207
+ }
1208
+ importBackend(name) {
1209
+ const backend = this.backends.get(name);
1210
+ if (!backend?.listImports || !backend.readImport || !backend.copyImport)
1211
+ throw new CommandRefused(`Backend Adapter ${name} cannot import conversations`);
1212
+ return backend;
1213
+ }
710
1214
  /**
711
1215
  * Boot a Summary Model session ahead of needing one, or drop the one held if the Setting is gone.
712
1216
  *
@@ -756,6 +1260,7 @@ export class SessionHost {
756
1260
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
757
1261
  if (!isRepository(repo))
758
1262
  throw new CommandRefused(`${repo} is not a git repository`);
1263
+ const updated = this.updateSourceBranch?.() && await refExists(repo, options.from) ? await updateSourceBranch(repo, options.from) : undefined;
759
1264
  const created = await createWorktree({
760
1265
  repo,
761
1266
  from: options.from,
@@ -764,7 +1269,10 @@ export class SessionHost {
764
1269
  });
765
1270
  if (!created.ok)
766
1271
  throw new CommandRefused(created.failure.message);
767
- return { path: created.value.path, repo, branch: created.value.branch };
1272
+ return {
1273
+ worktree: { path: created.value.path, repo, branch: created.value.branch },
1274
+ ...(updated?.ok === false ? { warning: `Source Branch ${options.from} was not updated, so the Worktree was cut from the local branch: ${updated.failure.message}` } : {}),
1275
+ };
768
1276
  }
769
1277
  /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
770
1278
  async revive(sessionId) {
@@ -803,6 +1311,8 @@ export class SessionHost {
803
1311
  async relocate(sessionId, scope, repo) {
804
1312
  const record = this.record(sessionId);
805
1313
  const from = record.scope;
1314
+ if (record.readOnly)
1315
+ throw new CommandRefused("An Agent Session with a Read-only Scope cannot relocate.");
806
1316
  if (record.session || record.reviving)
807
1317
  throw new CommandRefused("This Agent Session is running. Only a stopped Agent Session can relocate.");
808
1318
  if (existsSync(from))
@@ -865,7 +1375,15 @@ export class SessionHost {
865
1375
  this.closeOpenSubagents(record, record.log.since(0));
866
1376
  this.closeOpenBackgroundCalls(record, record.log.since(0));
867
1377
  record.backendEpoch += 1;
868
- await this.startPermissionBackend(record);
1378
+ const session = await this.startPermissionBackend(record);
1379
+ // An imported Agent Session's transcript opened with no models, because nothing had served it
1380
+ // (ADR 0047). Its first Revive is the first moment its Capabilities are known, and a client
1381
+ // reads them off the transcript — so they are written there, after `revived` like the rest.
1382
+ // Only when the adapter did not already announce them on its way up, which Claude's does.
1383
+ if (record.imported && capabilitiesFrom(record.log.since(0))?.models.length === 0
1384
+ && !record.buffered?.some((event) => event.type === "capabilities_changed")) {
1385
+ record.buffered?.push({ type: "capabilities_changed", capabilities: session.capabilities });
1386
+ }
869
1387
  record.lifecycle = "live";
870
1388
  // Un-settled, so the retention window starts again from the next Settle rather than from the
871
1389
  // one this Revive just undid.
@@ -885,7 +1403,7 @@ export class SessionHost {
885
1403
  * value that can bypass the Steering Queue, and "after_turn" already means "queue if busy, else
886
1404
  * dispatch now" — so there is no sensible default to pick. It matches `Command` either way.
887
1405
  */
888
- async send(sessionId, text, when, attachments) {
1406
+ async send(sessionId, text, when, attachments, beforeAccept, titleText, fromSessionId) {
889
1407
  const record = this.record(sessionId);
890
1408
  this.refuseGitOperation(record.scope);
891
1409
  // ADR 0003: the first message revives a Dormant session, so resuming work is one action.
@@ -893,16 +1411,20 @@ export class SessionHost {
893
1411
  await this.revive(sessionId);
894
1412
  if (record.permissionChanging)
895
1413
  await this.waitForPermissionChange(record);
1414
+ // Agent sends revalidate ownership after asynchronous Revive and permission-policy changes.
1415
+ beforeAccept?.();
896
1416
  // Checked before anything is written, so a refused send leaves no bytes behind.
897
1417
  this.refuseUnservableAttachments(record, attachments);
898
1418
  const ids = (attachments ?? []).map((attachment) => this.storeOrThrow().writeAttachment(record.id, attachment.mediaType, attachment.data));
1419
+ const from = fromSessionId === undefined ? {} : { fromSessionId };
899
1420
  if (when === "after_turn" && record.turnInFlight) {
900
- record.queue.push({ id: randomUUID(), text, attachments: ids });
1421
+ record.queue.push({ id: randomUUID(), text, attachments: ids, ...from });
901
1422
  record.log.append(queueChanged(record.queue));
902
1423
  this.touch(record);
903
1424
  return;
904
1425
  }
905
- await this.dispatch(record, { text, attachments: ids });
1426
+ // A title override applies only to the initial dispatch; a queued turn already has a title.
1427
+ await this.dispatch(record, { text, attachments: ids, ...from }, titleText);
906
1428
  }
907
1429
  /**
908
1430
  * Whether this send's Attachments can be carried at all, refused before any are written down.
@@ -1282,6 +1804,127 @@ export class SessionHost {
1282
1804
  await session.compact(instructions);
1283
1805
  this.touch(record);
1284
1806
  }
1807
+ /** Rewind (CONTEXT.md). Answers with the user message, for the composer to offer again. */
1808
+ async rewind(sessionId, userMessageId, restore) {
1809
+ const record = this.record(sessionId);
1810
+ this.refuseGitOperation(record.scope);
1811
+ if (record.lifecycle === "ended")
1812
+ throw new CommandRefused(`Agent Session ${sessionId} has Ended`);
1813
+ const message = userMessage(record.log.since(0), userMessageId)?.event;
1814
+ if (message?.type !== "user_message")
1815
+ throw new CommandRefused("That user message is not in this Agent Session");
1816
+ if (!record.session)
1817
+ await this.revive(sessionId);
1818
+ if (record.permissionChanging)
1819
+ await this.waitForPermissionChange(record);
1820
+ const session = record.session;
1821
+ if (!session)
1822
+ throw new CommandRefused(`Agent Session ${sessionId} has no Backend Session`);
1823
+ if (record.turnInFlight || record.queue.length > 0 || record.openSubagentIds.size > 0 || record.openBackgroundCallIds.size > 0) {
1824
+ throw new CommandRefused("Wait for the turn, the queued messages and the background work to finish, or abort them, before rewinding");
1825
+ }
1826
+ const files = restore !== "conversation";
1827
+ if (files && record.readOnly)
1828
+ throw new CommandRefused("This Agent Session has a Read-only Scope. Rewind only its conversation.");
1829
+ const conversation = restore !== "files";
1830
+ if (conversation && !session.capabilities.rewind)
1831
+ throw new CommandRefused(`${record.backendName} cannot rewind a Conversation Context`);
1832
+ if (files && (!session.capabilities.rewindFiles || !session.rewindFiles))
1833
+ throw new CommandRefused(`${record.backendName} cannot rewind files`);
1834
+ if (files) {
1835
+ try {
1836
+ await session.rewindFiles(userMessageId);
1837
+ }
1838
+ catch (error) {
1839
+ throw new CommandRefused(`Files were not rewound: ${errorMessage(error)}`);
1840
+ }
1841
+ }
1842
+ if (conversation) {
1843
+ record.rewindTo = userMessageId;
1844
+ this.persist(record);
1845
+ record.session = undefined;
1846
+ await this.stopBackendSession(record.scope, session, record.id);
1847
+ record.buffered = [];
1848
+ record.backendEpoch += 1;
1849
+ try {
1850
+ await this.startPermissionBackend(record);
1851
+ }
1852
+ catch (error) {
1853
+ record.buffered = undefined;
1854
+ record.lifecycle = "dormant";
1855
+ record.log.append({ type: "session_dormant", reason: `rewind failed: ${errorMessage(error)}` });
1856
+ this.touch(record);
1857
+ throw error;
1858
+ }
1859
+ }
1860
+ record.log.append({ type: "rewound", userMessageId, restore });
1861
+ this.flushBuffered(record);
1862
+ this.touch(record);
1863
+ return { text: message.text, attachments: message.attachments ?? [] };
1864
+ }
1865
+ /** Fork (CONTEXT.md). Answers with the new Agent Session's id. */
1866
+ async fork(sessionId, userMessageId, worktree) {
1867
+ const source = this.record(sessionId);
1868
+ if (!source.capabilities?.fork)
1869
+ throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
1870
+ const events = source.log.since(0);
1871
+ const at = userMessage(events, userMessageId);
1872
+ if (!at)
1873
+ throw new CommandRefused("That user message is not in this Agent Session");
1874
+ return await this.create({
1875
+ scope: worktree ? source.worktree?.repo ?? source.scope : source.scope,
1876
+ backend: source.backendName,
1877
+ ...(source.modelId === undefined ? {} : { modelId: source.modelId }),
1878
+ ...(source.effort === undefined ? {} : { effort: source.effort }),
1879
+ permissionMode: source.permissionMode,
1880
+ mcpConnectionIds: source.mcpConnectionIds ?? [],
1881
+ ...(worktree === undefined ? {} : { worktree }),
1882
+ ...(source.readOnly ? { readOnly: true } : {}),
1883
+ fork: { source, userMessageId, prefix: events.filter((entry) => entry.seq < at.seq) },
1884
+ });
1885
+ }
1886
+ /** Give a Fork the source's Conversation Context, to be cut before the user message on start. */
1887
+ copyForkState(record, source, userMessageId, prefix) {
1888
+ record.title = `${source.title} (fork)`;
1889
+ record.titleSource = "summary";
1890
+ const backend = this.backendFor(source.backendName);
1891
+ const kept = prefix.some(({ event }) => event.type === "user_message");
1892
+ if (!kept || !this.store || !source.resumeToken)
1893
+ return;
1894
+ if (!backend.fork)
1895
+ throw new CommandRefused(`${source.backendName} cannot fork a Conversation Context`);
1896
+ record.resumeToken = backend.fork({ stateDir: this.store.backendDir(source.id), scope: source.scope, resume: source.resumeToken }, { stateDir: this.store.backendDir(record.id), scope: record.scope });
1897
+ record.rewindTo = userMessageId;
1898
+ this.persist(record);
1899
+ }
1900
+ /** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
1901
+ appendForkPrefix(record, sourceId, userMessageId, prefix) {
1902
+ for (const { event, at } of prefix) {
1903
+ if (event.type === "session_started" || event.type === "queue_changed" || event.type === "workflow_spend")
1904
+ continue;
1905
+ if (event.type === "context_usage" && event.spend) {
1906
+ const { spend: _, ...rest } = event;
1907
+ record.log.append(rest, at);
1908
+ continue;
1909
+ }
1910
+ if (event.type === "revived") {
1911
+ record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
1912
+ continue;
1913
+ }
1914
+ if (event.type === "user_message" && event.attachments && this.store) {
1915
+ const to = this.store.attachmentsDir(record.id);
1916
+ mkdirSync(to, { recursive: true });
1917
+ for (const id of event.attachments) {
1918
+ const from = join(this.store.attachmentsDir(sourceId), id);
1919
+ if (existsSync(from))
1920
+ copyFileSync(from, join(to, id));
1921
+ }
1922
+ }
1923
+ record.log.append(event, at);
1924
+ }
1925
+ this.closeTornTurn(record, record.log.since(0));
1926
+ record.log.append({ type: "forked", fromSessionId: sourceId, userMessageId });
1927
+ }
1285
1928
  /**
1286
1929
  * The Skills this Agent Session can be sent.
1287
1930
  *
@@ -1387,7 +2030,7 @@ export class SessionHost {
1387
2030
  if (!isRepository(record.scope))
1388
2031
  return;
1389
2032
  const generation = (record.branchGeneration += 1);
1390
- const found = await head(record.scope);
2033
+ const [found] = await Promise.all([head(record.scope), this.gitStates.refresh(record.scope)]);
1391
2034
  // A repository git cannot answer about is left as it was: this runs off the critical path, and
1392
2035
  // there is no reader to tell.
1393
2036
  if (!found.ok)
@@ -1711,6 +2354,7 @@ export class SessionHost {
1711
2354
  if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
1712
2355
  return;
1713
2356
  record.log.append({ type: 'workflow_spend', executionId, spend });
2357
+ this.recordSpend("workflow", JSON.stringify([sessionId, executionId]), this.spendScope(record), spend);
1714
2358
  }
1715
2359
  authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
1716
2360
  workflowNamingAllowed(sessionId) {
@@ -1722,6 +2366,7 @@ export class SessionHost {
1722
2366
  if (!record)
1723
2367
  return;
1724
2368
  this.refuseGitOperation(record.scope);
2369
+ this.dropTour(sessionId);
1725
2370
  const session = record.session;
1726
2371
  record.session = undefined;
1727
2372
  record.lifecycle = "ended";
@@ -1748,6 +2393,7 @@ export class SessionHost {
1748
2393
  throw new Error(`Session ${sessionId} has ended`);
1749
2394
  if (record.lifecycle === "settled")
1750
2395
  return;
2396
+ this.dropTour(sessionId);
1751
2397
  const session = record.session;
1752
2398
  record.session = undefined;
1753
2399
  record.lifecycle = "settled";
@@ -1796,6 +2442,8 @@ export class SessionHost {
1796
2442
  for (const record of [...this.sessions.values()]) {
1797
2443
  if (record.lifecycle !== "settled")
1798
2444
  continue;
2445
+ if (this.workflowOwner?.canForget?.(record.id, record.scheduledOccurrenceId) === false)
2446
+ continue;
1799
2447
  const settledAt = record.settledAt === undefined ? NaN : Date.parse(record.settledAt);
1800
2448
  // An unreadable timestamp means we cannot know the age; leaving it is the safe failure.
1801
2449
  if (Number.isNaN(settledAt) || now - settledAt < retention)
@@ -1813,7 +2461,7 @@ export class SessionHost {
1813
2461
  await this.releaseWorktree(record);
1814
2462
  record.log.closeSubscribers();
1815
2463
  this.sessions.delete(record.id);
1816
- this.publishReviews.delete(record.id);
2464
+ this.dropTour(record.id);
1817
2465
  this.store?.deleteSession(record.id);
1818
2466
  reaped.push(record.id);
1819
2467
  }
@@ -1893,7 +2541,7 @@ export class SessionHost {
1893
2541
  }
1894
2542
  const generation = (record.titleGeneration += 1);
1895
2543
  let reason;
1896
- const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
2544
+ const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; }, this.namingSpent(record));
1897
2545
  if (name === undefined)
1898
2546
  throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
1899
2547
  // Refused rather than applied when something newer has already been asked for. A human who
@@ -1927,7 +2575,7 @@ export class SessionHost {
1927
2575
  const generation = (record.titleGeneration += 1);
1928
2576
  let name;
1929
2577
  try {
1930
- name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
2578
+ name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input, undefined, undefined, this.namingSpent(record));
1931
2579
  }
1932
2580
  catch {
1933
2581
  return;
@@ -1949,11 +2597,16 @@ export class SessionHost {
1949
2597
  /** Stop running work without ending the Agent Sessions: they become Dormant and can be revived. */
1950
2598
  async shutdown() {
1951
2599
  this.workflowShutdown = true;
2600
+ // Creation can still be awaiting backend startup after its caller disconnects. Drain those
2601
+ // accepted operations before walking sessions, so late children cannot escape shutdown.
2602
+ await Promise.allSettled([...this.sessionToolOperations, ...this.scheduledAttachments.values()]);
1952
2603
  // First, so that a naming still in flight cannot warm a replacement on the way out — the
1953
2604
  // one-shot CLI runner shuts down microseconds before `process.exit`, and a spare booted in
1954
2605
  // that window is a child process nothing is left to dispose. Not awaited, and cannot be: see
1955
2606
  // `SummaryModelSpare.dispose`.
1956
2607
  this.summarySpare.dispose();
2608
+ const tours = [...this.pullRequestTours.keys()].map(key => { const running = this.pullRequestTours.get(key)?.running; this.dropPullRequestTour(key); return running; });
2609
+ await Promise.allSettled(tours);
1957
2610
  const warm = [...this.skillSessions.values()];
1958
2611
  this.skillSessions.clear();
1959
2612
  await Promise.all(warm.map((held) => held.session.dispose().catch(() => { })));
@@ -1976,8 +2629,15 @@ export class SessionHost {
1976
2629
  this.persist(record);
1977
2630
  }
1978
2631
  await this.shared?.close().catch((error) => console.error(`Shared sandbox removal failed: ${error.message}`));
2632
+ const stopped = await Promise.allSettled([...this.backends.values()].map(async (backend) => backend.shutdown?.()));
2633
+ const failures = stopped.filter(result => result.status === "rejected").map(result => result.reason);
2634
+ if (failures.length)
2635
+ throw new AggregateError(failures, "Backend Adapter shutdown failed");
1979
2636
  }
1980
2637
  async execute(command) {
2638
+ if (READ_ONLY_REFUSED.has(command.type) && "sessionId" in command && this.record(command.sessionId).readOnly) {
2639
+ throw new CommandRefused("This Agent Session has a Read-only Scope. It cannot change Git state or run a Tour.");
2640
+ }
1981
2641
  switch (command.type) {
1982
2642
  case "create":
1983
2643
  return await this.create({
@@ -1988,6 +2648,7 @@ export class SessionHost {
1988
2648
  ...(command.permissionMode === undefined ? {} : { permissionMode: command.permissionMode }),
1989
2649
  ...(command.mcpConnectionIds === undefined ? {} : { mcpConnectionIds: command.mcpConnectionIds }),
1990
2650
  ...(command.worktree === undefined ? {} : { worktree: command.worktree }),
2651
+ ...(command.readOnly ? { readOnly: true } : {}),
1991
2652
  });
1992
2653
  case "send":
1993
2654
  return await this.send(command.sessionId, command.text, command.when, command.attachments);
@@ -2015,28 +2676,100 @@ export class SessionHost {
2015
2676
  return await this.setEffort(command.sessionId, command.effort);
2016
2677
  case "pull_branch":
2017
2678
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2018
- case "change_pull_request":
2019
- return await this.withGitOperation(this.record(command.sessionId).scope, () => changePullRequest(this.record(command.sessionId).scope, command.action, command.input));
2020
- case "pull_request":
2021
- return await pullRequest(this.record(command.sessionId).scope);
2022
- case "comment_pull_request":
2023
- return await commentPullRequest(this.record(command.sessionId).scope, command.input);
2024
- case "resolve_pull_request_thread":
2025
- return await resolvePullRequestThread(this.record(command.sessionId).scope, command.input);
2679
+ case "change_pull_request": {
2680
+ const { scope, find } = this.pullRequestPlace(command);
2681
+ const change = () => this.afterPullRequestWrite(scope, changePullRequest(scope, command.action, command.input, gh, find));
2682
+ return await (find ? this.readGit(change) : this.withGitOperation(scope, change));
2683
+ }
2684
+ case "pull_request": {
2685
+ if ("project" in command) {
2686
+ const scope = this.projectScope(command.project);
2687
+ return await this.readGit(() => projectPullRequest(scope, command.number));
2688
+ }
2689
+ const scope = this.record(command.sessionId).scope;
2690
+ return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
2691
+ }
2692
+ case "comment_pull_request": {
2693
+ const { scope, find } = this.pullRequestPlace(command);
2694
+ return await this.afterPullRequestWrite(scope, commentPullRequest(scope, command.input, gh, find));
2695
+ }
2696
+ case "resolve_pull_request_thread": {
2697
+ const { scope, find } = this.pullRequestPlace(command);
2698
+ return await this.afterPullRequestWrite(scope, resolvePullRequestThread(scope, command.input, gh, find));
2699
+ }
2700
+ case "edit_pull_request": {
2701
+ const { scope, find } = this.pullRequestPlace(command);
2702
+ return await this.afterPullRequestWrite(scope, editPullRequest(scope, command.input, gh, find));
2703
+ }
2704
+ case "set_pull_request_draft": {
2705
+ const { scope, find } = this.pullRequestPlace(command);
2706
+ return await this.afterPullRequestWrite(scope, setPullRequestDraft(scope, command.input, gh, find));
2707
+ }
2708
+ case "rerun_pull_request_checks": {
2709
+ const { scope, find } = this.pullRequestPlace(command);
2710
+ return await this.afterPullRequestWrite(scope, rerunPullRequestChecks(scope, command.input, gh, find));
2711
+ }
2712
+ case "pull_request_check_log": {
2713
+ const { scope, find } = this.pullRequestPlace(command);
2714
+ return await checkLog(scope, command.pr, command.jobId, gh, find);
2715
+ }
2716
+ case "submit_pull_request_review": {
2717
+ const { scope, find } = this.pullRequestPlace(command);
2718
+ return await this.afterPullRequestWrite(scope, submitReview(scope, command.input, gh, find));
2719
+ }
2720
+ case "project_pull_requests": {
2721
+ const scope = this.projectScope(command.project);
2722
+ const query = typeof command.query === "string" ? command.query.trim() : "";
2723
+ return await this.readGit(() => listPullRequests(scope, gh, query || undefined));
2724
+ }
2725
+ case "pull_request_changes":
2726
+ case "pull_request_diff": {
2727
+ const scope = this.projectScope(command.project);
2728
+ return await this.readGit(async () => {
2729
+ const range = await pullRequestRange(scope, command.pr);
2730
+ return command.type === "pull_request_diff" ? await fileDiff(scope, command.path, range.base, range.head) : await rangeChanges(scope, range.base, range.head);
2731
+ });
2732
+ }
2733
+ case "start_pull_request_session":
2734
+ return await this.startPullRequestSession(command.project, command.pr);
2026
2735
  case "stack_status":
2027
- return await this.withGitOperation(this.record(command.sessionId).scope, () => stackStatus(this.record(command.sessionId).scope));
2736
+ return await this.readStack(command.sessionId);
2028
2737
  case "prepare_stack":
2029
2738
  return await this.prepareStack(command.sessionId, command.action);
2030
2739
  case "change_stack":
2031
2740
  return await this.changeStack(command.sessionId, command.input);
2032
2741
  case "assist_stack":
2033
2742
  return await this.assistStack(command.sessionId);
2034
- case "git_status":
2035
- return await this.gitStatus(command.sessionId);
2036
- case "prepare_publish":
2037
- return await this.preparePublish(command.sessionId);
2038
- case "publish":
2039
- return await this.publish(command.sessionId, command.input);
2743
+ case "refresh_git": {
2744
+ const scope = this.record(command.sessionId).scope;
2745
+ if (!isRepository(scope)) {
2746
+ await this.gitStates.refresh(scope);
2747
+ return { repository: false };
2748
+ }
2749
+ await Promise.all([...this.sessions.values()].filter(other => scopeKey(other.scope) === scopeKey(scope)).map(other => this.refreshBranch(other)));
2750
+ if (command.pullRequest === true)
2751
+ await this.pollGitState(scope);
2752
+ return { repository: true };
2753
+ }
2754
+ case "git_changes":
2755
+ case "git_diff":
2756
+ return await this.readChanges(command);
2757
+ case "commit":
2758
+ return await this.commit(command.sessionId, { fingerprint: command.fingerprint, paths: command.paths, message: command.message, ...(command.branch === undefined ? {} : { branch: command.branch }) });
2759
+ case "push_state":
2760
+ return await this.readGit(() => pushState(this.gitScope(command.sessionId)));
2761
+ case "push":
2762
+ return await this.withGitOperation(this.gitScope(command.sessionId), () => this.afterPullRequestWrite(this.record(command.sessionId).scope, push(this.record(command.sessionId).scope, { head: command.head, ...(command.replace === undefined ? {} : { replace: command.replace }) })));
2763
+ case "create_pull_request":
2764
+ return await this.withGitOperation(this.gitScope(command.sessionId), () => this.afterPullRequestWrite(this.record(command.sessionId).scope, createPullRequest(this.record(command.sessionId).scope, { head: command.head, title: command.title, body: command.body, draft: command.draft === true })));
2765
+ case "suggest_git_text":
2766
+ return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2767
+ case "start_tour":
2768
+ return "project" in command ? this.startPullRequestTour(command.project, command.pr) : this.startTour(command.sessionId);
2769
+ case "tour":
2770
+ return "project" in command ? this.pullRequestTour(command.project, command.pr) : this.tour(command.sessionId);
2771
+ case "cancel_tour":
2772
+ return "project" in command ? this.cancelPullRequestTour(command.project, command.pr) : this.cancelTour(command.sessionId);
2040
2773
  case "switch_branch":
2041
2774
  return await this.switchBranch(command.sessionId, command.branch);
2042
2775
  case "switch_scope_branch":
@@ -2045,12 +2778,20 @@ export class SessionHost {
2045
2778
  return await this.rename(command.sessionId);
2046
2779
  case "compact":
2047
2780
  return await this.compact(command.sessionId, command.instructions);
2781
+ case "rewind":
2782
+ return await this.rewind(command.sessionId, command.userMessageId, command.restore);
2783
+ case "fork":
2784
+ return await this.fork(command.sessionId, command.userMessageId, command.worktree);
2048
2785
  case "answer_enquiry":
2049
2786
  return await this.answerEnquiry(command.sessionId, command.askId, command.answers);
2050
2787
  case "answer_permission":
2051
2788
  return await this.answerPermission(command.sessionId, command.callId, command.decision);
2052
2789
  case "list_skills":
2053
2790
  return await this.listSkills(command.sessionId);
2791
+ case "list_imports":
2792
+ return await this.listImports(command.backend, command.scope);
2793
+ case "import":
2794
+ return this.importConversation(command);
2054
2795
  case "list":
2055
2796
  return this.list();
2056
2797
  }
@@ -2102,36 +2843,58 @@ export class SessionHost {
2102
2843
  throw new Error('Unknown Agent Session');
2103
2844
  return structuredClone((this.mcpConnections?.() ?? []).filter(connection => record.mcpConnectionIds?.includes(connection.id)));
2104
2845
  }
2846
+ scheduledConnections(ids) {
2847
+ const connections = this.mcpConnections?.() ?? [];
2848
+ if (ids.some(id => !connections.some(connection => connection.id === id)))
2849
+ throw new ScheduleValidationError('Selected MCP connection is unavailable');
2850
+ return structuredClone(connections.filter(connection => ids.includes(connection.id)));
2851
+ }
2852
+ scheduledMcp(scope, ids, mode) {
2853
+ const connections = this.scheduledConnections(ids);
2854
+ const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2855
+ return import('../backend/mcp.js').then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2856
+ }
2857
+ scheduledSandboxMcp(scope, ids) {
2858
+ return import('../backend/worker/sandbox-mcp.js').then(({ SandboxMcpSession }) => new SandboxMcpSession(this.scheduledConnections(ids), scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, this.resolveSecret));
2859
+ }
2105
2860
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2106
2861
  filesystemStateRoot() { return this.store?.root; }
2107
2862
  /** A host without configured Settings keeps the safe, restricted library default. */
2108
2863
  filesystemIsolationMode() { return this.filesystemIsolation?.() ?? "bubblewrap"; }
2109
2864
  sandboxSupport() { return this.sandbox?.(); }
2110
2865
  /** The Shared Sandbox, when the Settings choose one VM for all sandbox sessions. */
2866
+ scheduledSandboxMounts(scope) {
2867
+ const mounts = [...this.backends.values()].flatMap(backend => backend.scheduledSandboxMounts?.(scope) ?? []);
2868
+ return { writable: mounts.flatMap(item => item.writable), readable: mounts.flatMap(item => item.readable) };
2869
+ }
2870
+ isReadOnly(sessionId) { return this.record(sessionId).readOnly === true; }
2111
2871
  sharedSandbox() { return this.sandboxSharing?.() === "shared" ? this.shared : undefined; }
2112
- async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode()) {
2872
+ async openWorkflowMcp(id, connectionId, isolationMode = this.filesystemIsolationMode(), signal) {
2873
+ signal?.throwIfAborted();
2113
2874
  if (isolationMode === "sandbox") {
2114
- await this.openWorkflowSession(id);
2875
+ await waitForAbort(this.openWorkflowSession(id), signal);
2876
+ signal?.throwIfAborted();
2115
2877
  const { SandboxMcpSession } = await import("../backend/worker/sandbox-mcp.js");
2116
2878
  const mcp = this.record(id).mcp;
2117
2879
  if (!(mcp instanceof SandboxMcpSession))
2118
2880
  throw new Error("Sandbox isolation is unavailable; unrestricted launch refused: the Agent Session has no sandbox");
2119
- return mcp.directView(connectionId);
2881
+ return mcp.directView(connectionId, signal);
2120
2882
  }
2121
2883
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2122
2884
  if (!connection)
2123
2885
  throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
2124
- const { McpSession } = await import("../backend/mcp.js");
2886
+ const { McpSession } = await import('../backend/mcp.js');
2125
2887
  const scope = this.workflowSession(id).scope;
2126
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
2888
+ signal?.throwIfAborted();
2889
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, this.isReadOnly(id));
2127
2890
  }
2128
2891
  /** Metadata discovery owned by authoring, never by an Agent/Backend Session. */
2129
2892
  async openWorkflowMcpAuthoring(scope, connectionId, isolationMode = this.filesystemIsolationMode(), expectedScopeIdentity) {
2130
2893
  const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
2131
2894
  if (!connection)
2132
2895
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2133
- const { McpSession } = await import("../backend/mcp.js");
2134
- return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
2896
+ const { McpSession } = await import('../backend/mcp.js');
2897
+ return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity, undefined, true);
2135
2898
  }
2136
2899
  mcpStatus(id) {
2137
2900
  const record = this.sessions.get(id);
@@ -2206,6 +2969,74 @@ export class SessionHost {
2206
2969
  return await this.startBackendSession(record);
2207
2970
  }
2208
2971
  }
2972
+ sessionToolOperations = new Set();
2973
+ agentSessionTools(source, backend) {
2974
+ const check = (signal) => {
2975
+ signal?.throwIfAborted();
2976
+ this.assertWorkflowSession(source.id, backend());
2977
+ };
2978
+ const owned = (operation) => {
2979
+ const pending = operation();
2980
+ this.sessionToolOperations.add(pending);
2981
+ void pending.finally(() => this.sessionToolOperations.delete(pending)).catch(() => { });
2982
+ return pending;
2983
+ };
2984
+ const attributed = (text) => `[Agent message from ${source.id} — not human authorization]\n${text}`;
2985
+ return {
2986
+ list: async (input) => {
2987
+ check();
2988
+ const { offset, limit } = sessionListInput.parse(input);
2989
+ // Stable identity ordering makes offset pages independent of live activity changes.
2990
+ const all = this.list().sort((a, b) => a.id.localeCompare(b.id));
2991
+ return { callerSessionId: source.id, total: all.length,
2992
+ sessions: all.slice(offset, offset + limit).map(sessionToolSummary),
2993
+ nextOffset: offset + limit < all.length ? offset + limit : null };
2994
+ },
2995
+ inspect: async (input) => {
2996
+ check();
2997
+ const { sessionId, before, limit } = sessionInspectInput.parse(input);
2998
+ const record = this.record(sessionId);
2999
+ const summary = this.list().find(item => item.id === sessionId);
3000
+ return { session: sessionToolSummary(summary),
3001
+ transcript: sessionToolPage(record.log.presentationPage(before, limit)) };
3002
+ },
3003
+ create: (input, signal) => owned(async () => {
3004
+ check(signal);
3005
+ const { text, worktree, scope = worktree ? source.worktree?.repo ?? source.scope : source.scope, backend: name = source.backendName, modelId, effort } = sessionCreateInput.parse(input);
3006
+ if (!isAbsolute(scope))
3007
+ throw new CommandRefused('Scope must be an absolute directory');
3008
+ const readOnly = source.readOnly && !(this.projectPaths?.() ?? []).some(path => scopeKey(path) === scopeKey(scope));
3009
+ if (readOnly && scopeKey(scope) !== scopeKey(this.projectRoot?.() ?? scope))
3010
+ throw new CommandRefused('A read-only Agent Session can create Agent Sessions only in a Project or at the Project Root');
3011
+ const sessionId = await this.create({ scope, backend: name,
3012
+ ...(readOnly ? { readOnly: true } : {}),
3013
+ ...(modelId === undefined ? {} : { modelId }),
3014
+ ...(effort === undefined ? {} : { effort }),
3015
+ ...(worktree === undefined ? {} : { worktree: { from: worktree.from, ...(worktree.branch === undefined ? {} : { branch: worktree.branch }) } }),
3016
+ mcpConnectionIds: source.mcpConnectionIds ?? [],
3017
+ permissionMode: source.permissionMode === 'auto' && name !== 'claude' ? 'ask' : source.permissionMode });
3018
+ // Persist a receipt even if cancellation loses the RPC result; never blindly recreate.
3019
+ source.log.append({ type: 'notice', level: 'info', text: `Created Agent Session ${sessionId}`, sessionId });
3020
+ this.record(sessionId).log.append({ type: 'notice', level: 'info', text: `Created by Agent Session ${source.id}`, sessionId: source.id });
3021
+ try {
3022
+ check(signal);
3023
+ await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
3024
+ return { sessionId, delivery: 'accepted' };
3025
+ }
3026
+ catch (error) {
3027
+ return { sessionId, delivery: 'not-sent', error: error instanceof Error ? error.message : String(error) };
3028
+ }
3029
+ }),
3030
+ send: (input, signal) => owned(async () => {
3031
+ check(signal);
3032
+ const { sessionId, text } = sessionSendInput.parse(input);
3033
+ if (sessionId === source.id)
3034
+ throw new CommandRefused('Use the current conversation instead of messaging yourself');
3035
+ await this.send(sessionId, attributed(text), 'after_turn', undefined, () => check(signal), text, source.id);
3036
+ return { sessionId, delivery: 'accepted' };
3037
+ }),
3038
+ };
3039
+ }
2209
3040
  async startBackendSession(record) {
2210
3041
  record.endedTurnIds = new Set();
2211
3042
  const backend = this.backendFor(record.backendName);
@@ -2216,13 +3047,14 @@ export class SessionHost {
2216
3047
  const isolationMode = this.filesystemIsolationMode();
2217
3048
  const mcp = isolationMode === "sandbox"
2218
3049
  ? new SandboxMcpSession(selected, record.scope, oauth, this.resolveSecret)
2219
- : new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
3050
+ : new McpSession(selected, record.scope, oauth, false, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, undefined, undefined, record.readOnly === true);
2220
3051
  record.mcp = mcp;
2221
3052
  const openingMcp = mcp.open();
2222
3053
  const autoCompaction = this.autoCompaction?.(backend.name);
2223
3054
  const compactionModelId = this.compactionModel?.(backend.name);
2224
3055
  let attached;
2225
3056
  const session = await backend.create({
3057
+ isolationMode,
2226
3058
  mcp,
2227
3059
  onFailure: () => {
2228
3060
  if (!attached || record.session !== attached)
@@ -2231,6 +3063,7 @@ export class SessionHost {
2231
3063
  this.backendFailures.add(stopped);
2232
3064
  void stopped.finally(() => this.backendFailures.delete(stopped));
2233
3065
  },
3066
+ sessionTools: this.agentSessionTools(record, () => attached),
2234
3067
  workflow: {
2235
3068
  inspect: input => { this.assertWorkflowSession(record.id, session); if (!this.workflowOwner)
2236
3069
  throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).inspect(input); },
@@ -2242,6 +3075,7 @@ export class SessionHost {
2242
3075
  throw new Error('Workflow execution is unavailable'); return this.workflowOwner.parent(record.id).relayPermission(input, signal); },
2243
3076
  },
2244
3077
  scope: record.scope,
3078
+ ...(record.readOnly ? { readOnly: this.readOnlyEnforcement(isolationMode) } : {}),
2245
3079
  emit: (event) => {
2246
3080
  if (!attached || record.session === attached)
2247
3081
  this.onBackendEvent(record.id, event);
@@ -2252,6 +3086,7 @@ export class SessionHost {
2252
3086
  ...(record.effort === undefined ? {} : { effort: record.effort }),
2253
3087
  permissionMode: record.permissionMode,
2254
3088
  ...(record.resumeToken === undefined ? {} : { resume: record.resumeToken }),
3089
+ ...(record.resumeToken === undefined || record.rewindTo === undefined ? {} : { resumeBefore: record.rewindTo }),
2255
3090
  ...(record.spend === undefined ? {} : { priorSpend: record.spend }),
2256
3091
  ...(this.store ? { stateDir: this.store.backendDir(record.id) } : {}),
2257
3092
  // Read here rather than held, so a Revive picks up every grant made since this Agent Session
@@ -2312,8 +3147,8 @@ export class SessionHost {
2312
3147
  await abort();
2313
3148
  };
2314
3149
  const prompt = session.prompt.bind(session);
2315
- session.prompt = (text, attachments) => {
2316
- pendingTurn = waitForMcp(() => prompt(text, attachments));
3150
+ session.prompt = (text, attachments, messageId) => {
3151
+ pendingTurn = waitForMcp(() => prompt(text, attachments, messageId));
2317
3152
  return pendingTurn;
2318
3153
  };
2319
3154
  if (session.compact) {
@@ -2435,7 +3270,7 @@ export class SessionHost {
2435
3270
  }
2436
3271
  record.openPermissionAttention.clear();
2437
3272
  }
2438
- async dispatch(record, message) {
3273
+ async dispatch(record, message, titleText = message.text) {
2439
3274
  if (record.permissionChanging)
2440
3275
  await this.waitForPermissionChange(record);
2441
3276
  this.refuseGitOperation(record.scope);
@@ -2459,7 +3294,7 @@ export class SessionHost {
2459
3294
  }
2460
3295
  record.initialEffortUnconfirmed = false;
2461
3296
  }
2462
- const { text, attachments } = message;
3297
+ const { text, attachments, fromSessionId } = message;
2463
3298
  const note = record.pendingBranchNote;
2464
3299
  record.pendingBranchNote = undefined;
2465
3300
  /*
@@ -2476,18 +3311,21 @@ export class SessionHost {
2476
3311
  const startingTurn = !record.turnInFlight;
2477
3312
  const generation = record.turnGeneration = (record.turnGeneration ?? 0) + (startingTurn ? 1 : 0);
2478
3313
  record.turnInFlight = true;
3314
+ const messageId = randomUUID();
2479
3315
  record.log.append({
2480
3316
  type: "user_message",
2481
- id: randomUUID(),
2482
- text: sent,
3317
+ id: messageId,
3318
+ text,
3319
+ ...(note === undefined ? {} : { note }),
2483
3320
  ...(attachments.length > 0 ? { attachments } : {}),
3321
+ ...(fromSessionId === undefined ? {} : { fromSessionId }),
2484
3322
  });
2485
- // Titled from what its owner actually typed, never from `sent`. A switch made before the first
3323
+ // Titled from the original instructions, never attribution or `sent`. A switch made before the first
2486
3324
  // message would otherwise name the Agent Session after the note, and permanently: the rename
2487
3325
  // fires only while the title is still the placeholder. An Attachment never titles anything
2488
3326
  // either, so a wordless paste falls to firstLine's own "Untitled session" rather than a filename.
2489
3327
  if (record.titleSource === "scope") {
2490
- record.title = firstLine(text);
3328
+ record.title = firstLine(titleText);
2491
3329
  record.titleSource = "first-line";
2492
3330
  /*
2493
3331
  * And then, seconds later, something better.
@@ -2498,7 +3336,7 @@ export class SessionHost {
2498
3336
  * flicker into and out of blank. It can only happen on a first dispatch, so no *established*
2499
3337
  * name ever changes under its reader.
2500
3338
  */
2501
- void this.nameAutomatically(record, text, "first-line");
3339
+ void this.nameAutomatically(record, titleText, "first-line");
2502
3340
  }
2503
3341
  this.touch(record);
2504
3342
  const workflowContext = this.workflowOwner?.context(record.id);
@@ -2511,7 +3349,7 @@ export class SessionHost {
2511
3349
  this.recordDispatchFailure(record, error, startingTurn);
2512
3350
  };
2513
3351
  try {
2514
- void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments)).catch(failed);
3352
+ void session.prompt(workflowContext ? `${sent}\n\n${workflowContext}` : sent, this.loadAttachments(record.id, attachments), messageId).catch(failed);
2515
3353
  }
2516
3354
  catch (error) {
2517
3355
  failed(error);
@@ -2543,6 +3381,15 @@ export class SessionHost {
2543
3381
  for (const event of buffered)
2544
3382
  this.onBackendEvent(record.id, event);
2545
3383
  }
3384
+ async diffExcerpts(sessionId, text) {
3385
+ const scope = this.record(sessionId).scope;
3386
+ return await messageExcerpts(text, scope, branch => this.gitStates.pullRequestBase(scope, branch));
3387
+ }
3388
+ async appendExcerpts(record, messageId, text) {
3389
+ const excerpts = await this.diffExcerpts(record.id, text);
3390
+ if (this.sessions.get(record.id) === record)
3391
+ record.log.append({ type: "diff_excerpts", messageId, excerpts });
3392
+ }
2546
3393
  onBackendEvent(sessionId, event) {
2547
3394
  const record = this.sessions.get(sessionId);
2548
3395
  if (!record || record.lifecycle === "ended" || record.lifecycle === "settled")
@@ -2564,6 +3411,10 @@ export class SessionHost {
2564
3411
  if (event.type === "turn_started" || (event.type === "permission" && event.state === "asked")) {
2565
3412
  record.permissionActivityVersion = (record.permissionActivityVersion ?? 0) + 1;
2566
3413
  }
3414
+ if (event.type === "turn_started" && record.rewindTo !== undefined) {
3415
+ record.rewindTo = undefined;
3416
+ this.persist(record);
3417
+ }
2567
3418
  const before = this.activityOf(record);
2568
3419
  const permissionWasOpen = event.type === "permission" && record.openPermissionAttention.has(event.callId);
2569
3420
  const enquiryWasOpen = event.type === "enquiry" && record.openEnquiryAttention.has(event.askId);
@@ -2574,6 +3425,8 @@ export class SessionHost {
2574
3425
  const preview = event.text.replace(/\s+/g, " ").trim();
2575
3426
  record.outputPreview = preview ? preview.slice(0, 500) : undefined;
2576
3427
  }
3428
+ if (event.type === "message" && event.final && hasDiffReference(event.text))
3429
+ void this.appendExcerpts(record, event.id, event.text);
2577
3430
  let inputAttention;
2578
3431
  if (event.type === "permission" && event.state === "asked" && !permissionWasOpen) {
2579
3432
  inputAttention = this.markAttention(record, "Input needed", `backend:${record.backendEpoch}:permission:${event.callId}`, logged.at);
@@ -2596,8 +3449,10 @@ export class SessionHost {
2596
3449
  void this.workflowOwner?.stop(sessionId).catch(() => { });
2597
3450
  // Kept current so a Revive can hand the running total back to the next Backend Session, which
2598
3451
  // counts only its own run.
2599
- if (event.type === "context_usage" && event.spend)
3452
+ if (event.type === "context_usage" && event.spend) {
2600
3453
  record.spend = event.spend;
3454
+ this.recordSpend("session", sessionId, this.spendScope(record), event.spend);
3455
+ }
2601
3456
  /*
2602
3457
  * Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
2603
3458
  * for the race the field's own comment describes. It matters for the turn nobody asked for: a
@@ -2610,6 +3465,8 @@ export class SessionHost {
2610
3465
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2611
3466
  record.turnInFlight = true;
2612
3467
  }
3468
+ if (event.type === "tool_ended" && record.turnInFlight)
3469
+ this.gitStates.touch(record.scope);
2613
3470
  if (event.type === "turn_ended") {
2614
3471
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2615
3472
  this.workflowOwner?.rearmInput?.(sessionId);
@@ -2792,6 +3649,7 @@ export class SessionHost {
2792
3649
  return;
2793
3650
  const meta = {
2794
3651
  id: record.id,
3652
+ ...(record.scheduledOccurrenceId ? { scheduledOccurrenceId: record.scheduledOccurrenceId } : {}),
2795
3653
  scope: record.scope,
2796
3654
  backend: record.backendName,
2797
3655
  title: record.title,
@@ -2811,11 +3669,14 @@ export class SessionHost {
2811
3669
  readAttentionVersion: record.readAttentionVersion,
2812
3670
  mcpConnectionIds: record.mcpConnectionIds ?? [],
2813
3671
  ...(record.resumeToken === undefined ? {} : { resumeToken: record.resumeToken }),
3672
+ ...(record.imported === undefined ? {} : { imported: record.imported }),
3673
+ ...(record.rewindTo === undefined ? {} : { rewindTo: record.rewindTo }),
2814
3674
  ...(record.modelId === undefined ? {} : { modelId: record.modelId }),
2815
3675
  ...(record.effort === undefined ? {} : { effort: record.effort }),
2816
3676
  permissionMode: record.permissionMode,
2817
3677
  ...(record.initialEffortUnconfirmed ? { initialEffortUnconfirmed: true } : {}),
2818
3678
  ...(record.worktree === undefined ? {} : { worktree: record.worktree }),
3679
+ ...(record.readOnly ? { readOnly: true } : {}),
2819
3680
  };
2820
3681
  this.store.writeMeta(meta);
2821
3682
  }
@@ -2829,6 +3690,9 @@ export function suggestedScope(scope, worktreesRoot) {
2829
3690
  const candidate = join(worktreesRoot, scope.slice(at + marker.length));
2830
3691
  return candidate !== scope && existsSync(candidate) ? candidate : undefined;
2831
3692
  }
3693
+ function userMessage(entries, id) {
3694
+ return entries.find(({ event }) => event.type === "user_message" && event.id === id);
3695
+ }
2832
3696
  /** The turn still open at the end of these entries, if any. */
2833
3697
  function openTurnId(entries) {
2834
3698
  let openTurn;
@@ -3022,12 +3886,18 @@ function openSubagents(entries) {
3022
3886
  const event = entry.event;
3023
3887
  if (event.type !== "subagent")
3024
3888
  continue;
3025
- if (event.state === "running" || event.state === "waiting")
3026
- open.set(event.subagentId, event.name);
3889
+ if (event.state === "running" || event.state === "waiting") {
3890
+ open.set(event.subagentId, {
3891
+ name: event.name,
3892
+ ...(event.model === undefined ? {} : { model: event.model }),
3893
+ ...(event.effort === undefined ? {} : { effort: event.effort }),
3894
+ ...(event.producer === undefined ? {} : { producer: event.producer }),
3895
+ });
3896
+ }
3027
3897
  else
3028
3898
  open.delete(event.subagentId);
3029
3899
  }
3030
- return [...open].map(([subagentId, name]) => ({ subagentId, name }));
3900
+ return [...open].map(([subagentId, brief]) => ({ subagentId, ...brief }));
3031
3901
  }
3032
3902
  /** What the transcript last reported this Agent Session had spent, across every Backend Session. */
3033
3903
  function spendFrom(entries) {
@@ -3036,9 +3906,28 @@ function spendFrom(entries) {
3036
3906
  const event = entry.event;
3037
3907
  if (event.type === "context_usage" && event.spend)
3038
3908
  spend = event.spend;
3909
+ if (event.type === "forked")
3910
+ spend = undefined;
3039
3911
  }
3040
3912
  return spend;
3041
3913
  }
3914
+ /**
3915
+ * The Capabilities an imported Agent Session opens with: none (ADR 0047).
3916
+ *
3917
+ * `create` refuses to return an Agent Session without confirmed models, so an empty model list can
3918
+ * only mean that no Backend Session has served this one yet — which is exactly what `reviveOnce`
3919
+ * checks for. Claiming the Capabilities of whatever the adapter would report today instead would put
3920
+ * a guess into an append-only transcript.
3921
+ */
3922
+ const IMPORTED_CAPABILITIES = {
3923
+ providers: [],
3924
+ models: [],
3925
+ compaction: false,
3926
+ fork: false,
3927
+ subagents: false,
3928
+ enquiries: false,
3929
+ permissions: false,
3930
+ };
3042
3931
  function capabilitiesFrom(entries) {
3043
3932
  let capabilities;
3044
3933
  for (const entry of entries) {
@@ -3064,6 +3953,11 @@ function firstLine(text) {
3064
3953
  function errorMessage(error) {
3065
3954
  return error instanceof Error ? error.message : String(error);
3066
3955
  }
3956
+ const READ_ONLY_REFUSED = new Set([
3957
+ "switch_branch", "pull_branch", "change_pull_request", "comment_pull_request", "submit_pull_request_review", "resolve_pull_request_thread",
3958
+ "edit_pull_request", "set_pull_request_draft", "rerun_pull_request_checks", "prepare_stack", "change_stack",
3959
+ "assist_stack", "commit", "push", "create_pull_request", "start_tour",
3960
+ ]);
3067
3961
  function scopeKey(scope) {
3068
3962
  try {
3069
3963
  return realpathSync(scope);