@nathanstephenson/flow 0.1.10-beta.4 → 0.1.10-beta.6

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 (101) hide show
  1. package/README.md +2 -2
  2. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  3. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  4. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  5. package/build/backend-worker.mjs +7 -3
  6. package/build/workflow-runtime.cjs +12 -12
  7. package/dist/backend/claude/index.js +6 -0
  8. package/dist/backend/claude/workflow-parent.js +1 -1
  9. package/dist/backend/fake/index.js +6 -0
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/model-auth.js +2 -2
  12. package/dist/backend/pi/plan-limits.js +41 -0
  13. package/dist/backend/pi/workflow-parent.js +1 -1
  14. package/dist/backend/plan-limits.js +17 -0
  15. package/dist/backend/worker/entry.js +4 -1
  16. package/dist/backend/worker/index.js +9 -3
  17. package/dist/backend/worker/launcher.js +11 -4
  18. package/dist/backend/worker/protocol.js +2 -1
  19. package/dist/build-id +1 -1
  20. package/dist/cli/application.js +5 -5
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/cli/host-control.js +1 -1
  23. package/dist/cli/install-guard.js +1 -1
  24. package/dist/cli/main.js +4 -4
  25. package/dist/cli/systemd-update.js +3 -3
  26. package/dist/cli/update.js +6 -6
  27. package/dist/cli/web-update.js +6 -6
  28. package/dist/client/context-usage.js +1 -1
  29. package/dist/client/markdown.js +3 -2
  30. package/dist/daemon/changes.js +116 -0
  31. package/dist/daemon/commit.js +84 -0
  32. package/dist/daemon/config-store.js +4 -3
  33. package/dist/daemon/config.js +31 -2
  34. package/dist/daemon/git-state.js +197 -0
  35. package/dist/daemon/github-image.js +18 -0
  36. package/dist/daemon/github.js +54 -0
  37. package/dist/daemon/host-control-routes.js +1 -1
  38. package/dist/daemon/host.js +280 -81
  39. package/dist/daemon/log.js +3 -0
  40. package/dist/daemon/mcp-auth.js +1 -1
  41. package/dist/daemon/pi-model-cache.js +1 -1
  42. package/dist/daemon/pull-request.js +156 -129
  43. package/dist/daemon/push.js +43 -0
  44. package/dist/daemon/repository.js +106 -0
  45. package/dist/daemon/runtime.js +28 -21
  46. package/dist/daemon/secret-store.js +1 -1
  47. package/dist/daemon/server.js +37 -10
  48. package/dist/daemon/skills.js +24 -0
  49. package/dist/daemon/spend-ledger.js +118 -0
  50. package/dist/daemon/stack-metadata.js +12 -5
  51. package/dist/daemon/stack.js +127 -656
  52. package/dist/daemon/summariser.js +30 -12
  53. package/dist/daemon/tour.js +42 -0
  54. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  55. package/dist/daemon/workflow-authoring-scope.js +1 -1
  56. package/dist/daemon/workflow-builder-files.js +2 -2
  57. package/dist/daemon/workflow-builder-routes.js +2 -2
  58. package/dist/daemon/workflow-builder.js +8 -6
  59. package/dist/daemon/workflow-environment.js +5 -5
  60. package/dist/daemon/workflow-execution-launch.js +5 -5
  61. package/dist/daemon/workflow-execution-resources.js +4 -4
  62. package/dist/daemon/workflow-execution-routes.js +3 -3
  63. package/dist/daemon/workflow-execution-values.js +5 -5
  64. package/dist/daemon/workflow-executions.js +19 -19
  65. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  66. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  67. package/dist/daemon/workflow-mcp.js +1 -1
  68. package/dist/daemon/workflow-routes.js +22 -3
  69. package/dist/daemon/workflow-schedule-driver.js +8 -8
  70. package/dist/daemon/workflow-schedule-routes.js +5 -5
  71. package/dist/daemon/workflow-schedules.js +9 -8
  72. package/dist/isolation/toolchain-assets.js +1 -1
  73. package/dist/protocol/spend.js +2 -0
  74. package/dist/protocol/stack.js +1 -41
  75. package/dist/workflows/calls.js +2 -2
  76. package/dist/workflows/executors.js +3 -3
  77. package/dist/workflows/graph.js +6 -6
  78. package/dist/workflows/invocations.js +1 -1
  79. package/dist/workflows/mcp.js +1 -1
  80. package/dist/workflows/records.js +6 -6
  81. package/dist/workflows/recovery.js +2 -2
  82. package/dist/workflows/runtime-settings.js +1 -1
  83. package/dist/workflows/runtime.js +2 -2
  84. package/dist/workflows/schedule-store.js +2 -2
  85. package/dist/workflows/scheduler.js +35 -23
  86. package/dist/workflows/schema.js +1 -1
  87. package/dist/workflows/store.js +19 -5
  88. package/package.json +3 -2
  89. package/web/dist/assets/index-BhfJhrVJ.js +51 -0
  90. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  91. package/web/dist/assets/{settings-mcp-bcNKV147.js → settings-mcp-3cgqQB28.js} +1 -1
  92. package/web/dist/assets/settings-workflows-Cutm8isB.js +23 -0
  93. package/web/dist/assets/{switch-DIogWclb.js → switch-B00FEUA7.js} +1 -1
  94. package/web/dist/assets/{workflows-DHG-CIo3.js → workflows-D6oEUUhj.js} +31 -31
  95. package/web/dist/assets/{workflows-pane-9u_hJvgQ.js → workflows-pane-KIdSDKJB.js} +1 -1
  96. package/web/dist/index.html +4 -4
  97. package/dist/daemon/publish.js +0 -289
  98. package/web/dist/assets/index-BWKZK5HD.css +0 -2
  99. package/web/dist/assets/index-nIc09tKZ.js +0 -40
  100. package/web/dist/assets/settings-workflows-C_TKOhVa.js +0 -23
  101. /package/dist/protocol/{publish.js → plan-limits.js} +0 -0
@@ -1,14 +1,18 @@
1
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
+ 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';
5
5
  import { randomUUID } from "node:crypto";
6
6
  import { copyFileSync, existsSync, mkdirSync, realpathSync } from "node:fs";
7
7
  import { isAbsolute, join, resolve } from "node:path";
8
8
  import { validateFilesystemScope } from "../isolation/filesystem.js";
9
- import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest } from "./pull-request.js";
10
- import { stackStatus, actionStackStatus, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
11
- import { gitStatus, snapshot, target, branchChanges, canNameBranch, publish } from "./publish.js";
9
+ import { pullRequest, commentPullRequest, resolvePullRequestThread, pullBranch, changePullRequest, createPullRequest, editPullRequest, setPullRequestDraft, rerunPullRequestChecks, checkLog } from "./pull-request.js";
10
+ import { otherWorktreeRebase, stackStatus, stackTitles, cleanStack, stackFingerprint, changeStack, stackConflictMessage } from "./stack.js";
11
+ import { changes, changesText, commitContext, diff } from "./changes.js";
12
+ import { commit } from "./commit.js";
13
+ import { push, pushState } from "./push.js";
14
+ import { GitStates, readStatus } from "./git-state.js";
15
+ import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, tourInput, tourText } from "./tour.js";
12
16
  import { resolveDefaultBackend } from "../protocol/settings.js";
13
17
  import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
14
18
  import { deriveStatus, railGroupRank } from "../client/status.js";
@@ -19,10 +23,11 @@ import { SessionLog } from "./log.js";
19
23
  import { probeModels } from "./models.js";
20
24
  import { PiModelProbeCache } from "./pi-model-cache.js";
21
25
  import { ScheduleValidationError } from "../workflows/schedule-errors.js";
22
- import { probeSkills } from "./skills.js";
26
+ import { probePlanLimits, probeSkills } from "./skills.js";
23
27
  import { recordTiming } from "./timings.js";
24
28
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
25
- import { nameInput, summarisePublish, suggestedBranch, SummaryModelSpare } from "./summariser.js";
29
+ import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
30
+ import { SpendLedger } from "./spend-ledger.js";
26
31
  /**
27
32
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
28
33
  * Scope that is not a repository, a checkout git itself refused.
@@ -56,6 +61,7 @@ export class SessionHost {
56
61
  * one dimension.
57
62
  */
58
63
  skillProbes = new Map();
64
+ planLimitProbe;
59
65
  /**
60
66
  * One Summary Model session, booted before a naming needs it (ADR 0020).
61
67
  *
@@ -63,10 +69,12 @@ export class SessionHost {
63
69
  * `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
64
70
  */
65
71
  summarySpare = new SummaryModelSpare();
72
+ spendLedger;
66
73
  stackReviews = new Map();
67
74
  gitOperations = new Set();
75
+ gitStates = new GitStates();
68
76
  closingScopes = new Set();
69
- publishReviews = new Map();
77
+ tours = new Map();
70
78
  refuseGitOperation(scope) {
71
79
  if (this.gitOperations.has(scopeKey(scope)))
72
80
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -103,6 +111,7 @@ export class SessionHost {
103
111
  }
104
112
  finally {
105
113
  this.gitOperations.delete(key);
114
+ void this.gitStates.refresh(scope);
106
115
  }
107
116
  }
108
117
  async prepareStack(sessionId, action) {
@@ -112,9 +121,9 @@ export class SessionHost {
112
121
  return this.withGitOperation(record.scope, async () => {
113
122
  this.stackReviews.delete(sessionId);
114
123
  await cleanStack(record.scope);
115
- const status = await actionStackStatus(record.scope);
124
+ const status = await stackStatus(record.scope);
116
125
  if (!status.view)
117
- throw new Error(status.problem ?? "No stack found.");
126
+ throw new Error(status.notice ?? "This branch is not in a stack.");
118
127
  const review = { token: randomUUID(), action, view: status.view };
119
128
  this.stackReviews.set(sessionId, { review, fingerprint: await stackFingerprint(record.scope, status.view, action === "sync"), expires: Date.now() + 15 * 60_000 });
120
129
  return review;
@@ -129,19 +138,18 @@ export class SessionHost {
129
138
  if (!saved || saved.expires < Date.now() || saved.review.token !== input.token || saved.review.action !== input.action)
130
139
  throw new Error("This Stack review expired. Review again.");
131
140
  await cleanStack(record.scope);
132
- const status = await actionStackStatus(record.scope);
141
+ const status = await stackStatus(record.scope);
133
142
  if (!status.view || await stackFingerprint(record.scope, status.view, input.action === "sync") !== saved.fingerprint)
134
143
  throw new Error("The reviewed stack changed. Review again.");
135
144
  }
136
145
  try {
137
- return await changeStack(record.scope, input);
146
+ return await this.afterPullRequestWrite(record.scope, changeStack(record.scope, input));
138
147
  }
139
148
  finally {
140
149
  for (const other of this.sessions.values()) {
141
150
  if (scopeKey(other.scope) !== scopeKey(record.scope))
142
151
  continue;
143
152
  this.stackReviews.delete(other.id);
144
- this.publishReviews.delete(other.id);
145
153
  await this.refreshBranch(other);
146
154
  other.pendingBranchNote = "[Flow] A Stack operation was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
147
155
  }
@@ -151,67 +159,161 @@ export class SessionHost {
151
159
  async assistStack(sessionId) {
152
160
  const record = this.record(sessionId);
153
161
  await this.withGitOperation(record.scope, async () => {
154
- const status = await actionStackStatus(record.scope);
162
+ const status = await stackStatus(record.scope);
155
163
  if (!status.rebasing)
156
- throw new Error("No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
164
+ throw new Error(status.notice === otherWorktreeRebase ? otherWorktreeRebase : "No Stack rebase is in progress. Use Rebase first after a Sync conflict.");
157
165
  });
158
166
  await this.send(sessionId, stackConflictMessage, "now");
159
167
  }
160
- async gitStatus(sessionId) {
161
- return gitStatus(this.record(sessionId).scope);
168
+ pollGitState(forced) {
169
+ return this.gitStates.poll([...this.sessions.values()].map(record => ({ scope: record.scope, lifecycle: record.lifecycle, watched: record.log.watched })), forced);
162
170
  }
163
- async preparePublish(sessionId) {
164
- const record = this.record(sessionId);
165
- return this.withGitOperation(record.scope, async () => {
166
- this.publishReviews.delete(sessionId);
167
- for (const [id, review] of this.publishReviews)
168
- if (review.expires < Date.now())
169
- this.publishReviews.delete(id);
170
- const { input: changes, ...reviewed } = await snapshot(record.scope);
171
- const destination = await target(record.scope, reviewed.branch);
172
- const committed = await branchChanges(record.scope, destination);
173
- if (reviewed.files.length === 0 && committed.commits.length === 0 && !destination.pr)
174
- throw new CommandRefused("There are no changes to publish.");
175
- let text = { commitMessage: "", title: destination.pr?.title ?? "", body: "" };
176
- let warning;
177
- const model = this.summaryModel?.(record.backendName);
178
- try {
179
- if (!model)
180
- throw new Error("No Summary Model is configured. Choose one in Settings, or enter publish text below.");
181
- text = await summarisePublish({ backend: this.backendFor(model.backend), modelId: model.modelId, text: `${changes}\nCommitted branch changes:\n${committed.input}` });
182
- }
183
- catch (error) {
184
- warning = `Enter publish text manually. ${error instanceof Error ? error.message : String(error)}`;
185
- }
186
- const suggestion = await canNameBranch(record.scope, reviewed.branch, destination)
187
- ? text.suggestedBranch ?? suggestedBranch((record.titleSource !== "scope" ? record.title : "") || text.commitMessage || committed.commits[0]?.replace(/^[a-f0-9]+ /, "") || record.title)
188
- : undefined;
189
- delete text.suggestedBranch;
190
- const token = randomUUID();
191
- this.publishReviews.set(sessionId, { token, expires: Date.now() + 15 * 60_000, snapshot: reviewed, target: destination });
192
- 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 } : {}) };
171
+ async afterPullRequestWrite(scope, write) {
172
+ try {
173
+ return await write;
174
+ }
175
+ finally {
176
+ await this.pollGitState(scope);
177
+ }
178
+ }
179
+ async readGit(read) {
180
+ try {
181
+ return await read();
182
+ }
183
+ catch (error) {
184
+ throw new CommandRefused(error instanceof Error ? error.message : String(error));
185
+ }
186
+ }
187
+ readStack(sessionId) {
188
+ const scope = this.gitScope(sessionId);
189
+ return this.readGit(async () => {
190
+ const status = await stackStatus(scope);
191
+ if (status.view && !await stackTitles(scope, status.view))
192
+ status.notice = "Pull request titles could not be read. Copy uses the links.";
193
+ return status;
193
194
  });
194
195
  }
195
- async publish(sessionId, input) {
196
+ gitScope(sessionId) {
197
+ const scope = this.record(sessionId).scope;
198
+ if (!isRepository(scope))
199
+ throw new CommandRefused("This Scope is not a Git repository.");
200
+ return scope;
201
+ }
202
+ async readChanges(command) {
203
+ const scope = this.gitScope(command.sessionId);
204
+ const base = (branch) => this.gitStates.pullRequestBase(scope, branch);
205
+ return this.readGit(async () => {
206
+ if (command.type === "git_diff")
207
+ return await diff(scope, command.view, command.path, base);
208
+ if (command.view === "branch")
209
+ return await changes(scope, command.view, base);
210
+ const read = await readStatus(scope);
211
+ return { files: read.files, commits: [], fingerprint: read.fingerprint, ...await commitContext(scope, read.local.branch, branch => this.gitStates.hasPullRequest(scope, branch)) };
212
+ });
213
+ }
214
+ async commit(sessionId, input) {
215
+ this.gitScope(sessionId);
196
216
  const record = this.record(sessionId);
197
217
  return this.withGitOperation(record.scope, async () => {
198
- const review = this.publishReviews.get(sessionId);
199
- if (!review || review.token !== input.token || review.expires < Date.now())
200
- throw new CommandRefused("This Publish review expired. Open Publish again.");
201
- this.publishReviews.delete(sessionId);
218
+ const before = await head(record.scope);
202
219
  try {
203
- return await publish(record.scope, review.snapshot, review.target, input);
220
+ return await commit(record.scope, input);
204
221
  }
205
222
  finally {
206
- for (const other of this.sessions.values()) {
207
- if (scopeKey(other.scope) !== scopeKey(record.scope))
208
- continue;
209
- await this.refreshBranch(other);
210
- other.pendingBranchNote = "[Flow] Git publishing was attempted in this Scope. Re-read the branch and changed files before relying on earlier reads.";
223
+ const after = await head(record.scope);
224
+ if (after.ok && before.ok && after.value.name !== before.value.name) {
225
+ for (const other of this.sessions.values()) {
226
+ if (scopeKey(other.scope) !== scopeKey(record.scope))
227
+ continue;
228
+ await this.refreshBranch(other);
229
+ 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.`;
230
+ }
211
231
  }
212
232
  }
213
233
  });
214
234
  }
235
+ async suggestGitText(sessionId, kind, paths) {
236
+ const record = this.record(sessionId);
237
+ if (!["commit", "pull_request", "branch"].includes(kind) || (paths !== undefined && (!Array.isArray(paths) || paths.some(path => typeof path !== "string"))))
238
+ throw new CommandRefused("Invalid suggestion request.");
239
+ const model = this.summaryModel?.(record.backendName);
240
+ if (!model)
241
+ throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
242
+ return this.readGit(async () => {
243
+ const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
244
+ return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind,
245
+ spent: (spend) => this.recordSpend("publish", randomUUID(), this.spendScope(this.record(sessionId)), spend) });
246
+ });
247
+ }
248
+ tour(sessionId) {
249
+ this.record(sessionId);
250
+ return this.tours.get(sessionId)?.view ?? { state: "idle" };
251
+ }
252
+ startTour(sessionId) {
253
+ const record = this.record(sessionId);
254
+ this.dropTour(sessionId);
255
+ const tour = { id: randomUUID(), view: { state: "running" } };
256
+ this.tours.set(sessionId, tour);
257
+ void this.runTour(record, tour);
258
+ return tour.view;
259
+ }
260
+ cancelTour(sessionId) {
261
+ this.record(sessionId);
262
+ this.dropTour(sessionId);
263
+ return { state: "idle" };
264
+ }
265
+ dropTour(sessionId) {
266
+ const tour = this.tours.get(sessionId);
267
+ this.tours.delete(sessionId);
268
+ void tour?.handle?.cancel().catch(() => undefined);
269
+ }
270
+ async runTour(record, tour) {
271
+ const current = () => this.tours.get(record.id) === tour;
272
+ let made;
273
+ try {
274
+ const { input, ...found } = await tourInput(record.scope);
275
+ made = found;
276
+ if (!current())
277
+ return;
278
+ tour.view = { state: "running", branch: made.branch, head: made.head };
279
+ if (!record.session)
280
+ await this.revive(record.id);
281
+ const session = record.session;
282
+ if (!current())
283
+ return;
284
+ if (!session?.startWorkflowSubagent)
285
+ throw new Error("This Backend Adapter cannot run a tour.");
286
+ const log = record.log.since(0);
287
+ const model = log.findLast(({ event }) => event.type === "model_changed")?.event;
288
+ const effort = log.findLast(({ event }) => event.type === "effort_changed")?.event;
289
+ const chosen = this.tourModel?.(record.backendName);
290
+ const modelId = chosen?.modelId ?? (model?.type === "model_changed" ? model.model.id : record.modelId);
291
+ if (!modelId)
292
+ throw new Error("The Agent Session's model is unknown. Choose a Tour Model in Settings.");
293
+ tour.handle = session.startWorkflowSubagent({
294
+ id: tour.id, name: "Tour", instructions: TOUR_INSTRUCTIONS, input, modelId,
295
+ effort: chosen?.effort ?? (effort?.type === "effort_changed" ? effort.effort : record.effort) ?? "off",
296
+ permissionMode: "ask",
297
+ emit: ({ event }) => {
298
+ if (event.type === "permission" && event.state === "asked") {
299
+ queueMicrotask(() => void tour.handle?.answerPermission(event.callId, TOUR_READ_TOOLS.includes(event.tool) ? "allow" : "deny").catch(() => undefined));
300
+ }
301
+ if (event.type === "enquiry" && event.state === "asked") {
302
+ queueMicrotask(() => void tour.handle?.answerEnquiry(event.askId, event.questions.map(() => ["No human is available. Continue without an answer."])).catch(() => undefined));
303
+ }
304
+ if (event.type === "spend")
305
+ this.workflowSpend(record.id, `tour:${tour.id}`, event.spend);
306
+ },
307
+ });
308
+ const text = tourText(await tour.handle.done);
309
+ if (current())
310
+ tour.view = { state: "done", text, ...made };
311
+ }
312
+ catch (error) {
313
+ if (current())
314
+ tour.view = { state: "failed", problem: error instanceof Error ? error.message : String(error), ...(made ? { branch: made.branch, head: made.head } : {}) };
315
+ }
316
+ }
215
317
  store;
216
318
  retention;
217
319
  standingAuthorisations;
@@ -223,6 +325,7 @@ export class SessionHost {
223
325
  defaultEffort;
224
326
  defaultPermissionMode;
225
327
  summaryModel;
328
+ tourModel;
226
329
  closedListeners = new Set();
227
330
  backendFailures = new Set();
228
331
  keptListeners = new Set();
@@ -242,6 +345,7 @@ export class SessionHost {
242
345
  this.mcpAuth = options.mcpAuth;
243
346
  this.resolveSecret = options.resolveSecret;
244
347
  this.store = options.store;
348
+ this.spendLedger = options.store ? new SpendLedger(options.store.root) : undefined;
245
349
  this.retention = options.retention ?? "never";
246
350
  this.standingAuthorisations = options.standingAuthorisations;
247
351
  this.allowTool = options.allowTool;
@@ -252,6 +356,7 @@ export class SessionHost {
252
356
  this.defaultEffort = options.defaultEffort;
253
357
  this.defaultPermissionMode = options.defaultPermissionMode;
254
358
  this.summaryModel = options.summaryModel;
359
+ this.tourModel = options.tourModel;
255
360
  }
256
361
  /**
257
362
  * Notified when an Agent Session stops being something its owner is working in — Settled, Ended
@@ -371,6 +476,27 @@ export class SessionHost {
371
476
  }
372
477
  return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
373
478
  }
479
+ async planLimits(scope) {
480
+ this.planLimitProbe ??= Promise.all([...this.backends.values()].map(async (backend) => (await this.askPlanLimits(backend, scope)).map((windows) => ({ backend: backend.name, ...windows }))))
481
+ .then((answers) => answers.flat())
482
+ .finally(() => { this.planLimitProbe = undefined; });
483
+ return await this.planLimitProbe;
484
+ }
485
+ async askPlanLimits(backend, scope) {
486
+ const warm = this.skillSessions.get(backend.name);
487
+ if (warm && !warm.dead) {
488
+ if (!warm.session.planLimits)
489
+ return [];
490
+ try {
491
+ return await this.timed("planLimits", backend, true, () => warm.session.planLimits());
492
+ }
493
+ catch {
494
+ this.skillSessions.delete(backend.name);
495
+ void warm.session.dispose().catch(() => { });
496
+ }
497
+ }
498
+ return await this.timed("planLimits", backend, false, (timed) => probePlanLimits(timed, scope, (held) => this.holdSkillSession(backend.name, held, false)));
499
+ }
374
500
  /** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
375
501
  holdSkillSession(name, held, replace) {
376
502
  const old = this.skillSessions.get(name);
@@ -471,6 +597,7 @@ export class SessionHost {
471
597
  // lifting an Ended row back out of Filed away.
472
598
  const input = record.lifecycle === "live" ? newestAt(parentInput, workflowInput) : undefined;
473
599
  const outcome = record.latestOutcome;
600
+ const git = this.gitStates.summary(record.scope);
474
601
  const unread = outcome !== undefined && outcome.version > record.readAttentionVersion;
475
602
  const attention = input
476
603
  ? {
@@ -506,6 +633,7 @@ export class SessionHost {
506
633
  lastSeq: record.log.lastSeq,
507
634
  ...(record.capabilities ? { capabilities: record.capabilities } : {}),
508
635
  ...(record.branch ? { branch: record.branch } : {}),
636
+ ...(git ? { git } : {}),
509
637
  ...(record.worktree ? { worktree: true } : {}),
510
638
  ...(record.session || existsSync(record.scope) ? {} : {
511
639
  scopeMissing: true,
@@ -541,6 +669,8 @@ export class SessionHost {
541
669
  if (!meta || this.sessions.has(id))
542
670
  continue;
543
671
  const entries = this.store.readEntries(id);
672
+ if (this.spendLedger?.needsBackfill)
673
+ this.backfillSpend(id, scopeKey(meta.worktree?.repo ?? meta.scope), entries);
544
674
  const record = {
545
675
  id: meta.id,
546
676
  scope: meta.scope,
@@ -607,8 +737,29 @@ export class SessionHost {
607
737
  }
608
738
  this.persist(record);
609
739
  }
740
+ this.spendLedger?.finishBackfill();
610
741
  await this.reap();
611
742
  }
743
+ backfillSpend(sessionId, scope, entries) {
744
+ for (const { event, at } of entries.slice(entries.findLastIndex(({ event }) => event.type === "forked") + 1)) {
745
+ if (event.type === "context_usage" && event.spend)
746
+ this.spendLedger.record("session", sessionId, scope, event.spend, at);
747
+ if (event.type === "workflow_spend")
748
+ this.spendLedger.record("workflow", JSON.stringify([sessionId, event.executionId]), scope, event.spend, at);
749
+ }
750
+ }
751
+ recordSpend(source, key, scope, spend) {
752
+ this.spendLedger?.record(source, key, scope, spend);
753
+ }
754
+ spendSummary() {
755
+ return this.spendLedger?.summary();
756
+ }
757
+ namingSpent(record) {
758
+ return (spend) => this.recordSpend("naming", randomUUID(), this.spendScope(record), spend);
759
+ }
760
+ spendScope(record) {
761
+ return scopeKey(record.worktree?.repo ?? record.scope);
762
+ }
612
763
  scheduledAttachments = new Map();
613
764
  /** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
614
765
  * The caller has already journaled the intended identity before entering this operation. */
@@ -1428,8 +1579,13 @@ export class SessionHost {
1428
1579
  /** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
1429
1580
  appendForkPrefix(record, sourceId, userMessageId, prefix) {
1430
1581
  for (const { event, at } of prefix) {
1431
- if (event.type === "session_started" || event.type === "queue_changed")
1582
+ if (event.type === "session_started" || event.type === "queue_changed" || event.type === "workflow_spend")
1583
+ continue;
1584
+ if (event.type === "context_usage" && event.spend) {
1585
+ const { spend: _, ...rest } = event;
1586
+ record.log.append(rest, at);
1432
1587
  continue;
1588
+ }
1433
1589
  if (event.type === "revived") {
1434
1590
  record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
1435
1591
  continue;
@@ -1553,7 +1709,7 @@ export class SessionHost {
1553
1709
  if (!isRepository(record.scope))
1554
1710
  return;
1555
1711
  const generation = (record.branchGeneration += 1);
1556
- const found = await head(record.scope);
1712
+ const [found] = await Promise.all([head(record.scope), this.gitStates.refresh(record.scope)]);
1557
1713
  // A repository git cannot answer about is left as it was: this runs off the critical path, and
1558
1714
  // there is no reader to tell.
1559
1715
  if (!found.ok)
@@ -1877,6 +2033,7 @@ export class SessionHost {
1877
2033
  if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
1878
2034
  return;
1879
2035
  record.log.append({ type: 'workflow_spend', executionId, spend });
2036
+ this.recordSpend("workflow", JSON.stringify([sessionId, executionId]), this.spendScope(record), spend);
1880
2037
  }
1881
2038
  authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
1882
2039
  workflowNamingAllowed(sessionId) {
@@ -1888,6 +2045,7 @@ export class SessionHost {
1888
2045
  if (!record)
1889
2046
  return;
1890
2047
  this.refuseGitOperation(record.scope);
2048
+ this.dropTour(sessionId);
1891
2049
  const session = record.session;
1892
2050
  record.session = undefined;
1893
2051
  record.lifecycle = "ended";
@@ -1914,6 +2072,7 @@ export class SessionHost {
1914
2072
  throw new Error(`Session ${sessionId} has ended`);
1915
2073
  if (record.lifecycle === "settled")
1916
2074
  return;
2075
+ this.dropTour(sessionId);
1917
2076
  const session = record.session;
1918
2077
  record.session = undefined;
1919
2078
  record.lifecycle = "settled";
@@ -1981,7 +2140,7 @@ export class SessionHost {
1981
2140
  await this.releaseWorktree(record);
1982
2141
  record.log.closeSubscribers();
1983
2142
  this.sessions.delete(record.id);
1984
- this.publishReviews.delete(record.id);
2143
+ this.dropTour(record.id);
1985
2144
  this.store?.deleteSession(record.id);
1986
2145
  reaped.push(record.id);
1987
2146
  }
@@ -2061,7 +2220,7 @@ export class SessionHost {
2061
2220
  }
2062
2221
  const generation = (record.titleGeneration += 1);
2063
2222
  let reason;
2064
- const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
2223
+ const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; }, this.namingSpent(record));
2065
2224
  if (name === undefined)
2066
2225
  throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
2067
2226
  // Refused rather than applied when something newer has already been asked for. A human who
@@ -2095,7 +2254,7 @@ export class SessionHost {
2095
2254
  const generation = (record.titleGeneration += 1);
2096
2255
  let name;
2097
2256
  try {
2098
- name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
2257
+ name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input, undefined, undefined, this.namingSpent(record));
2099
2258
  }
2100
2259
  catch {
2101
2260
  return;
@@ -2191,27 +2350,61 @@ export class SessionHost {
2191
2350
  case "pull_branch":
2192
2351
  return await this.withGitOperation(this.record(command.sessionId).scope, () => pullBranch(this.record(command.sessionId).scope, command.branch));
2193
2352
  case "change_pull_request":
2194
- return await this.withGitOperation(this.record(command.sessionId).scope, () => changePullRequest(this.record(command.sessionId).scope, command.action, command.input));
2195
- case "pull_request":
2196
- return await pullRequest(this.record(command.sessionId).scope);
2353
+ return await this.withGitOperation(this.record(command.sessionId).scope, () => this.afterPullRequestWrite(this.record(command.sessionId).scope, changePullRequest(this.record(command.sessionId).scope, command.action, command.input)));
2354
+ case "pull_request": {
2355
+ const scope = this.record(command.sessionId).scope;
2356
+ return await this.readGit(() => pullRequest(scope, this.gitStates.pullRequestRef(scope)));
2357
+ }
2197
2358
  case "comment_pull_request":
2198
- return await commentPullRequest(this.record(command.sessionId).scope, command.input);
2359
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, commentPullRequest(this.record(command.sessionId).scope, command.input));
2199
2360
  case "resolve_pull_request_thread":
2200
- return await resolvePullRequestThread(this.record(command.sessionId).scope, command.input);
2361
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, resolvePullRequestThread(this.record(command.sessionId).scope, command.input));
2362
+ case "edit_pull_request":
2363
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, editPullRequest(this.record(command.sessionId).scope, command.input));
2364
+ case "set_pull_request_draft":
2365
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, setPullRequestDraft(this.record(command.sessionId).scope, command.input));
2366
+ case "rerun_pull_request_checks":
2367
+ return await this.afterPullRequestWrite(this.record(command.sessionId).scope, rerunPullRequestChecks(this.record(command.sessionId).scope, command.input));
2368
+ case "pull_request_check_log":
2369
+ return await checkLog(this.record(command.sessionId).scope, command.pr, command.jobId);
2201
2370
  case "stack_status":
2202
- return await this.withGitOperation(this.record(command.sessionId).scope, () => stackStatus(this.record(command.sessionId).scope));
2371
+ return await this.readStack(command.sessionId);
2203
2372
  case "prepare_stack":
2204
2373
  return await this.prepareStack(command.sessionId, command.action);
2205
2374
  case "change_stack":
2206
2375
  return await this.changeStack(command.sessionId, command.input);
2207
2376
  case "assist_stack":
2208
2377
  return await this.assistStack(command.sessionId);
2209
- case "git_status":
2210
- return await this.gitStatus(command.sessionId);
2211
- case "prepare_publish":
2212
- return await this.preparePublish(command.sessionId);
2213
- case "publish":
2214
- return await this.publish(command.sessionId, command.input);
2378
+ case "refresh_git": {
2379
+ const scope = this.record(command.sessionId).scope;
2380
+ if (!isRepository(scope)) {
2381
+ await this.gitStates.refresh(scope);
2382
+ return { repository: false };
2383
+ }
2384
+ await Promise.all([...this.sessions.values()].filter(other => scopeKey(other.scope) === scopeKey(scope)).map(other => this.refreshBranch(other)));
2385
+ if (command.pullRequest === true)
2386
+ await this.pollGitState(scope);
2387
+ return { repository: true };
2388
+ }
2389
+ case "git_changes":
2390
+ case "git_diff":
2391
+ return await this.readChanges(command);
2392
+ case "commit":
2393
+ return await this.commit(command.sessionId, { fingerprint: command.fingerprint, paths: command.paths, message: command.message, ...(command.branch === undefined ? {} : { branch: command.branch }) });
2394
+ case "push_state":
2395
+ return await this.readGit(() => pushState(this.gitScope(command.sessionId)));
2396
+ case "push":
2397
+ 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 }) })));
2398
+ case "create_pull_request":
2399
+ 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 })));
2400
+ case "suggest_git_text":
2401
+ return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2402
+ case "start_tour":
2403
+ return this.startTour(command.sessionId);
2404
+ case "tour":
2405
+ return this.tour(command.sessionId);
2406
+ case "cancel_tour":
2407
+ return this.cancelTour(command.sessionId);
2215
2408
  case "switch_branch":
2216
2409
  return await this.switchBranch(command.sessionId, command.branch);
2217
2410
  case "switch_scope_branch":
@@ -2290,10 +2483,10 @@ export class SessionHost {
2290
2483
  scheduledMcp(scope, ids, mode) {
2291
2484
  const connections = this.scheduledConnections(ids);
2292
2485
  const oauth = this.mcpAuth ? (connection) => this.mcpAuth.provider(connection) : undefined;
2293
- return import("../backend/mcp.js").then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2486
+ return import('../backend/mcp.js').then(({ McpSession }) => new McpSession(connections, scope, oauth, true, this.resolveSecret, undefined, this.filesystemStateRoot(), mode));
2294
2487
  }
2295
2488
  scheduledSandboxMcp(scope, ids) {
2296
- 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));
2489
+ 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));
2297
2490
  }
2298
2491
  /** Include an SDK-supplied owning root in every local execution's filesystem policy. */
2299
2492
  filesystemStateRoot() { return this.store?.root; }
@@ -2320,7 +2513,7 @@ export class SessionHost {
2320
2513
  const connection = this.workflowMcpConnections(id).find(connection => connection.id === connectionId);
2321
2514
  if (!connection)
2322
2515
  throw new Error('MCP connection is removed or disabled for this Agent Session. Enable it in the Agent Session settings and reconfigure the step.');
2323
- const { McpSession } = await import("../backend/mcp.js");
2516
+ const { McpSession } = await import('../backend/mcp.js');
2324
2517
  const scope = this.workflowSession(id).scope;
2325
2518
  signal?.throwIfAborted();
2326
2519
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode);
@@ -2330,7 +2523,7 @@ export class SessionHost {
2330
2523
  const connection = (this.mcpConnections?.() ?? []).find(connection => connection.id === connectionId);
2331
2524
  if (!connection)
2332
2525
  throw new Error('MCP connection removed. Refresh the workflow editor.');
2333
- const { McpSession } = await import("../backend/mcp.js");
2526
+ const { McpSession } = await import('../backend/mcp.js');
2334
2527
  return new McpSession([connection], scope, this.mcpAuth ? connection => this.mcpAuth.provider(connection) : undefined, true, this.resolveSecret, undefined, this.filesystemStateRoot(), isolationMode, expectedScopeIdentity);
2335
2528
  }
2336
2529
  mcpStatus(id) {
@@ -2869,8 +3062,10 @@ export class SessionHost {
2869
3062
  void this.workflowOwner?.stop(sessionId).catch(() => { });
2870
3063
  // Kept current so a Revive can hand the running total back to the next Backend Session, which
2871
3064
  // counts only its own run.
2872
- if (event.type === "context_usage" && event.spend)
3065
+ if (event.type === "context_usage" && event.spend) {
2873
3066
  record.spend = event.spend;
3067
+ this.recordSpend("session", sessionId, this.spendScope(record), event.spend);
3068
+ }
2874
3069
  /*
2875
3070
  * Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
2876
3071
  * for the race the field's own comment describes. It matters for the turn nobody asked for: a
@@ -2883,6 +3078,8 @@ export class SessionHost {
2883
3078
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2884
3079
  record.turnInFlight = true;
2885
3080
  }
3081
+ if (event.type === "tool_ended" && record.turnInFlight)
3082
+ this.gitStates.touch(record.scope);
2886
3083
  if (event.type === "turn_ended") {
2887
3084
  record.turnGeneration = (record.turnGeneration ?? 0) + 1;
2888
3085
  this.workflowOwner?.rearmInput?.(sessionId);
@@ -3320,6 +3517,8 @@ function spendFrom(entries) {
3320
3517
  const event = entry.event;
3321
3518
  if (event.type === "context_usage" && event.spend)
3322
3519
  spend = event.spend;
3520
+ if (event.type === "forked")
3521
+ spend = undefined;
3323
3522
  }
3324
3523
  return spend;
3325
3524
  }
@@ -92,6 +92,9 @@ export class SessionLog {
92
92
  const start = Math.max(0, end - limit);
93
93
  return { seq: this.lastSeq, entries: this.indexedRange(view.entries, start, end), start, total };
94
94
  }
95
+ get watched() {
96
+ return this.listeners.size > 0 || this.presentationListeners.size > 0;
97
+ }
95
98
  subscribePresentation(listener) {
96
99
  this.presentationView();
97
100
  this.presentationListeners.add(listener);
@@ -1,4 +1,4 @@
1
- import { credentialKey } from "./credential-redaction.js";
1
+ import { credentialKey } from './credential-redaction.js';
2
2
  import { randomBytes, createHash } from "node:crypto";
3
3
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
4
  import { join } from "node:path";
@@ -1,6 +1,6 @@
1
1
  import { closeSync, fstatSync, mkdirSync, mkdtempSync, openSync, readSync, rmSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { workflowBuilderFolder } from "../isolation/shared-sandbox.js";
3
+ import { workflowBuilderFolder } from '../isolation/shared-sandbox.js';
4
4
  export class PiModelProbeCache {
5
5
  catalog;
6
6
  generation = 0;