@nathanstephenson/flow 0.1.10-beta.5 → 0.1.10-beta.7

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 (67) hide show
  1. package/README.md +5 -19
  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/dist/backend/claude/index.js +6 -0
  7. package/dist/backend/fake/index.js +6 -0
  8. package/dist/backend/pi/index.js +34 -2
  9. package/dist/backend/pi/plan-limits.js +41 -0
  10. package/dist/backend/plan-limits.js +17 -0
  11. package/dist/backend/worker/entry.js +4 -1
  12. package/dist/backend/worker/index.js +5 -0
  13. package/dist/backend/worker/protocol.js +2 -1
  14. package/dist/build-id +1 -1
  15. package/dist/cli/application.js +4 -37
  16. package/dist/cli/bootstrap.js +2 -2
  17. package/dist/cli/install-guard.js +1 -1
  18. package/dist/client/context-usage.js +3 -4
  19. package/dist/client/enquiry.js +0 -6
  20. package/dist/client/markdown.js +3 -2
  21. package/dist/client/model-choices.js +1 -1
  22. package/dist/client/permission.js +1 -2
  23. package/dist/client/relative-time.js +1 -1
  24. package/dist/client/scope-kind.js +2 -3
  25. package/dist/client/search.js +1 -1
  26. package/dist/client/status.js +1 -1
  27. package/dist/client/subagent-tree.js +1 -1
  28. package/dist/client/tool-chains.js +1 -1
  29. package/dist/client/tool-summary.js +2 -3
  30. package/dist/daemon/config-store.js +3 -0
  31. package/dist/daemon/config.js +63 -3
  32. package/dist/daemon/git.js +33 -2
  33. package/dist/daemon/github-image.js +18 -0
  34. package/dist/daemon/host.js +159 -9
  35. package/dist/daemon/runtime.js +2 -2
  36. package/dist/daemon/server.js +28 -2
  37. package/dist/daemon/skills.js +24 -0
  38. package/dist/daemon/spend-ledger.js +118 -0
  39. package/dist/daemon/summariser.js +11 -4
  40. package/dist/daemon/tour.js +42 -0
  41. package/dist/daemon/workflow-builder.js +3 -1
  42. package/dist/daemon/workflow-execution-resources.js +1 -1
  43. package/dist/daemon/workflow-routes.js +19 -0
  44. package/dist/daemon/workflow-schedule-driver.js +5 -1
  45. package/dist/daemon/workflow-schedules.js +6 -5
  46. package/dist/protocol/plan-limits.js +1 -0
  47. package/dist/protocol/spend.js +2 -0
  48. package/dist/workflows/scheduler.js +26 -14
  49. package/dist/workflows/schedules.js +1 -0
  50. package/dist/workflows/store.js +16 -2
  51. package/package.json +1 -1
  52. package/web/dist/assets/index-5E7qbtVD.js +51 -0
  53. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  54. package/web/dist/assets/{switch-B00FEUA7.js → select-C-BND5Jn.js} +1 -1
  55. package/web/dist/assets/{settings-mcp-BwOPXAfH.js → settings-mcp-CBXZt_cf.js} +1 -1
  56. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-29ZG3w6p.js} +1 -1
  57. package/web/dist/assets/{settings-workflows-DocTa31_.js → settings-workflows-CE11fxNj.js} +2 -2
  58. package/web/dist/assets/workflow-api-DkUjAZ4w.js +6 -0
  59. package/web/dist/assets/{workflows-DJqUuGyg.js → workflows-DdogjBu3.js} +6 -6
  60. package/web/dist/assets/{workflows-pane-oM1fO_BC.js → workflows-pane-B0dyuSuz.js} +1 -1
  61. package/web/dist/index.html +5 -5
  62. package/dist/tui/app.js +0 -612
  63. package/dist/tui/keys.js +0 -90
  64. package/dist/tui/render.js +0 -417
  65. package/web/dist/assets/index-BqZ_iUmY.css +0 -2
  66. package/web/dist/assets/index-CxdSb7k0.js +0 -51
  67. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
@@ -12,20 +12,22 @@ import { changes, changesText, commitContext, diff } from "./changes.js";
12
12
  import { commit } from "./commit.js";
13
13
  import { push, pushState } from "./push.js";
14
14
  import { GitStates, readStatus } from "./git-state.js";
15
+ import { TOUR_INSTRUCTIONS, TOUR_READ_TOOLS, tourInput, tourText } from "./tour.js";
15
16
  import { resolveDefaultBackend } from "../protocol/settings.js";
16
17
  import { isAttachmentMediaType, mediaTypeOf, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BASE64_BYTES, } from "../protocol/attachments.js";
17
18
  import { deriveStatus, railGroupRank } from "../client/status.js";
18
19
  // `switchBranch` is aliased because this class has a method of that name: the method is the
19
20
  // Session Host's refusal-and-record wrapper, and the import is the git invocation it wraps.
20
- import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
21
+ import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, updateSourceBranch, switchBranch as gitSwitchBranch, } from "./git.js";
21
22
  import { SessionLog } from "./log.js";
22
23
  import { probeModels } from "./models.js";
23
24
  import { PiModelProbeCache } from "./pi-model-cache.js";
24
25
  import { ScheduleValidationError } from "../workflows/schedule-errors.js";
25
- import { probeSkills } from "./skills.js";
26
+ import { probePlanLimits, probeSkills } from "./skills.js";
26
27
  import { recordTiming } from "./timings.js";
27
28
  import { SharedSandbox } from "../isolation/shared-sandbox.js";
28
29
  import { nameInput, suggestGitText, SummaryModelSpare } from "./summariser.js";
30
+ import { SpendLedger } from "./spend-ledger.js";
29
31
  /**
30
32
  * A command the Session Host will not carry out in the state the thing is in — a turn in flight, a
31
33
  * Scope that is not a repository, a checkout git itself refused.
@@ -59,6 +61,7 @@ export class SessionHost {
59
61
  * one dimension.
60
62
  */
61
63
  skillProbes = new Map();
64
+ planLimitProbe;
62
65
  /**
63
66
  * One Summary Model session, booted before a naming needs it (ADR 0020).
64
67
  *
@@ -66,10 +69,12 @@ export class SessionHost {
66
69
  * `settle` — it is a throwaway that outlives any one of them, in the same way `modelProbes` is.
67
70
  */
68
71
  summarySpare = new SummaryModelSpare();
72
+ spendLedger;
69
73
  stackReviews = new Map();
70
74
  gitOperations = new Set();
71
75
  gitStates = new GitStates();
72
76
  closingScopes = new Set();
77
+ tours = new Map();
73
78
  refuseGitOperation(scope) {
74
79
  if (this.gitOperations.has(scopeKey(scope)))
75
80
  throw new CommandRefused("A Git operation is in progress in this Scope. Wait for it to finish.");
@@ -236,9 +241,79 @@ export class SessionHost {
236
241
  throw new CommandRefused("No Summary Model is configured. Choose one in Settings, or enter the text.");
237
242
  return this.readGit(async () => {
238
243
  const text = await changesText(record.scope, kind === "pull_request" ? "branch" : "uncommitted", paths, branch => this.gitStates.pullRequestBase(record.scope, branch));
239
- return await suggestGitText({ backend: this.backendFor(model.backend), modelId: model.modelId, text, kind });
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) });
240
246
  });
241
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
+ }
242
317
  store;
243
318
  retention;
244
319
  standingAuthorisations;
@@ -250,12 +325,14 @@ export class SessionHost {
250
325
  defaultEffort;
251
326
  defaultPermissionMode;
252
327
  summaryModel;
328
+ tourModel;
253
329
  closedListeners = new Set();
254
330
  backendFailures = new Set();
255
331
  keptListeners = new Set();
256
332
  filesystemIsolation;
257
333
  sandbox;
258
334
  sandboxSharing;
335
+ updateSourceBranch;
259
336
  shared;
260
337
  mcpConnections;
261
338
  mcpAuth;
@@ -264,11 +341,13 @@ export class SessionHost {
264
341
  this.filesystemIsolation = options.filesystemIsolationMode;
265
342
  this.sandbox = options.sandboxSupport;
266
343
  this.sandboxSharing = options.sandboxSharing;
344
+ this.updateSourceBranch = options.updateSourceBranch;
267
345
  this.shared = options.store ? new SharedSandbox(options.store.root, options.projectRoot ?? (() => undefined)) : undefined;
268
346
  this.mcpConnections = options.mcpConnections;
269
347
  this.mcpAuth = options.mcpAuth;
270
348
  this.resolveSecret = options.resolveSecret;
271
349
  this.store = options.store;
350
+ this.spendLedger = options.store ? new SpendLedger(options.store.root) : undefined;
272
351
  this.retention = options.retention ?? "never";
273
352
  this.standingAuthorisations = options.standingAuthorisations;
274
353
  this.allowTool = options.allowTool;
@@ -279,6 +358,7 @@ export class SessionHost {
279
358
  this.defaultEffort = options.defaultEffort;
280
359
  this.defaultPermissionMode = options.defaultPermissionMode;
281
360
  this.summaryModel = options.summaryModel;
361
+ this.tourModel = options.tourModel;
282
362
  }
283
363
  /**
284
364
  * Notified when an Agent Session stops being something its owner is working in — Settled, Ended
@@ -398,6 +478,27 @@ export class SessionHost {
398
478
  }
399
479
  return await this.timed("skills", backend, false, (timed) => probeSkills(timed, scope, (held) => this.holdSkillSession(backend.name, held, true)));
400
480
  }
481
+ async planLimits(scope) {
482
+ this.planLimitProbe ??= Promise.all([...this.backends.values()].map(async (backend) => (await this.askPlanLimits(backend, scope)).map((windows) => ({ backend: backend.name, ...windows }))))
483
+ .then((answers) => answers.flat())
484
+ .finally(() => { this.planLimitProbe = undefined; });
485
+ return await this.planLimitProbe;
486
+ }
487
+ async askPlanLimits(backend, scope) {
488
+ const warm = this.skillSessions.get(backend.name);
489
+ if (warm && !warm.dead) {
490
+ if (!warm.session.planLimits)
491
+ return [];
492
+ try {
493
+ return await this.timed("planLimits", backend, true, () => warm.session.planLimits());
494
+ }
495
+ catch {
496
+ this.skillSessions.delete(backend.name);
497
+ void warm.session.dispose().catch(() => { });
498
+ }
499
+ }
500
+ return await this.timed("planLimits", backend, false, (timed) => probePlanLimits(timed, scope, (held) => this.holdSkillSession(backend.name, held, false)));
501
+ }
401
502
  /** `replace` is false for the model probe: it fills an empty or dead slot and never replaces a live one. */
402
503
  holdSkillSession(name, held, replace) {
403
504
  const old = this.skillSessions.get(name);
@@ -570,6 +671,8 @@ export class SessionHost {
570
671
  if (!meta || this.sessions.has(id))
571
672
  continue;
572
673
  const entries = this.store.readEntries(id);
674
+ if (this.spendLedger?.needsBackfill)
675
+ this.backfillSpend(id, scopeKey(meta.worktree?.repo ?? meta.scope), entries);
573
676
  const record = {
574
677
  id: meta.id,
575
678
  scope: meta.scope,
@@ -636,8 +739,29 @@ export class SessionHost {
636
739
  }
637
740
  this.persist(record);
638
741
  }
742
+ this.spendLedger?.finishBackfill();
639
743
  await this.reap();
640
744
  }
745
+ backfillSpend(sessionId, scope, entries) {
746
+ for (const { event, at } of entries.slice(entries.findLastIndex(({ event }) => event.type === "forked") + 1)) {
747
+ if (event.type === "context_usage" && event.spend)
748
+ this.spendLedger.record("session", sessionId, scope, event.spend, at);
749
+ if (event.type === "workflow_spend")
750
+ this.spendLedger.record("workflow", JSON.stringify([sessionId, event.executionId]), scope, event.spend, at);
751
+ }
752
+ }
753
+ recordSpend(source, key, scope, spend) {
754
+ this.spendLedger?.record(source, key, scope, spend);
755
+ }
756
+ spendSummary() {
757
+ return this.spendLedger?.summary();
758
+ }
759
+ namingSpent(record) {
760
+ return (spend) => this.recordSpend("naming", randomUUID(), this.spendScope(record), spend);
761
+ }
762
+ spendScope(record) {
763
+ return scopeKey(record.worktree?.repo ?? record.scope);
764
+ }
641
765
  scheduledAttachments = new Map();
642
766
  /** Internal attachment lane: concurrent agent/input/recovery callbacks share creation and Revive.
643
767
  * The caller has already journaled the intended identity before entering this operation. */
@@ -673,7 +797,8 @@ export class SessionHost {
673
797
  // Reject an unsupported policy before creating a worktree or any durable Agent Session state.
674
798
  const permissionMode = options.permissionMode ?? this.permissionDefault(backend.name);
675
799
  this.validatePermissionMode(backend.name, permissionMode);
676
- const worktree = options.scheduled?.worktree ?? (options.worktree ? await this.cutWorktree(options.scope, options.worktree) : undefined);
800
+ const cut = options.scheduled?.worktree || !options.worktree ? undefined : await this.cutWorktree(options.scope, options.worktree);
801
+ const worktree = options.scheduled?.worktree ?? cut?.worktree;
677
802
  // The Scope from here down, and for this Agent Session's whole life. Resolved before any record
678
803
  // exists so that a `worktree add` which failed leaves nothing persisted pointing at a directory
679
804
  // that is not there.
@@ -770,6 +895,8 @@ export class SessionHost {
770
895
  if (options.fork)
771
896
  this.appendForkPrefix(record, options.fork.source.id, options.fork.userMessageId, options.fork.prefix);
772
897
  this.flushBuffered(record);
898
+ if (cut?.warning)
899
+ record.log.append({ type: "notice", level: "warn", text: cut.warning });
773
900
  // After session_started, never before: the transcript has to open with it (see `buffered`).
774
901
  await this.refreshBranch(record);
775
902
  /*
@@ -834,6 +961,7 @@ export class SessionHost {
834
961
  throw new CommandRefused("This Session Host keeps no state, so it cannot make a worktree");
835
962
  if (!isRepository(repo))
836
963
  throw new CommandRefused(`${repo} is not a git repository`);
964
+ const updated = this.updateSourceBranch?.() ? await updateSourceBranch(repo, options.from) : undefined;
837
965
  const created = await createWorktree({
838
966
  repo,
839
967
  from: options.from,
@@ -842,7 +970,10 @@ export class SessionHost {
842
970
  });
843
971
  if (!created.ok)
844
972
  throw new CommandRefused(created.failure.message);
845
- return { path: created.value.path, repo, branch: created.value.branch };
973
+ return {
974
+ worktree: { path: created.value.path, repo, branch: created.value.branch },
975
+ ...(updated?.ok === false ? { warning: `Source Branch ${options.from} was not updated, so the Worktree was cut from the local branch: ${updated.failure.message}` } : {}),
976
+ };
846
977
  }
847
978
  /** Attach a fresh Backend Session to a Dormant Agent Session, continuing the same transcript. */
848
979
  async revive(sessionId) {
@@ -1457,8 +1588,13 @@ export class SessionHost {
1457
1588
  /** Copy what the human saw before the Fork point. The source's session start, scope and queue are not this session's. */
1458
1589
  appendForkPrefix(record, sourceId, userMessageId, prefix) {
1459
1590
  for (const { event, at } of prefix) {
1460
- if (event.type === "session_started" || event.type === "queue_changed")
1591
+ if (event.type === "session_started" || event.type === "queue_changed" || event.type === "workflow_spend")
1461
1592
  continue;
1593
+ if (event.type === "context_usage" && event.spend) {
1594
+ const { spend: _, ...rest } = event;
1595
+ record.log.append(rest, at);
1596
+ continue;
1597
+ }
1462
1598
  if (event.type === "revived") {
1463
1599
  record.log.append({ type: "revived", fromSeq: event.fromSeq }, at);
1464
1600
  continue;
@@ -1906,6 +2042,7 @@ export class SessionHost {
1906
2042
  if (previous?.event.type === 'workflow_spend' && JSON.stringify(previous.event.spend) === JSON.stringify(spend))
1907
2043
  return;
1908
2044
  record.log.append({ type: 'workflow_spend', executionId, spend });
2045
+ this.recordSpend("workflow", JSON.stringify([sessionId, executionId]), this.spendScope(record), spend);
1909
2046
  }
1910
2047
  authoriseWorkflowTool(tool) { this.allowTool?.(tool); }
1911
2048
  workflowNamingAllowed(sessionId) {
@@ -1917,6 +2054,7 @@ export class SessionHost {
1917
2054
  if (!record)
1918
2055
  return;
1919
2056
  this.refuseGitOperation(record.scope);
2057
+ this.dropTour(sessionId);
1920
2058
  const session = record.session;
1921
2059
  record.session = undefined;
1922
2060
  record.lifecycle = "ended";
@@ -1943,6 +2081,7 @@ export class SessionHost {
1943
2081
  throw new Error(`Session ${sessionId} has ended`);
1944
2082
  if (record.lifecycle === "settled")
1945
2083
  return;
2084
+ this.dropTour(sessionId);
1946
2085
  const session = record.session;
1947
2086
  record.session = undefined;
1948
2087
  record.lifecycle = "settled";
@@ -2010,6 +2149,7 @@ export class SessionHost {
2010
2149
  await this.releaseWorktree(record);
2011
2150
  record.log.closeSubscribers();
2012
2151
  this.sessions.delete(record.id);
2152
+ this.dropTour(record.id);
2013
2153
  this.store?.deleteSession(record.id);
2014
2154
  reaped.push(record.id);
2015
2155
  }
@@ -2089,7 +2229,7 @@ export class SessionHost {
2089
2229
  }
2090
2230
  const generation = (record.titleGeneration += 1);
2091
2231
  let reason;
2092
- const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; });
2232
+ const name = await this.summarySpare.name(backend, summary, nameInput(entries), undefined, (problem) => { reason = problem; }, this.namingSpent(record));
2093
2233
  if (name === undefined)
2094
2234
  throw new CommandRefused(`Could not name this Agent Session${reason ? `: ${reason}` : ""}`);
2095
2235
  // Refused rather than applied when something newer has already been asked for. A human who
@@ -2123,7 +2263,7 @@ export class SessionHost {
2123
2263
  const generation = (record.titleGeneration += 1);
2124
2264
  let name;
2125
2265
  try {
2126
- name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input);
2266
+ name = await this.summarySpare.name(this.backendFor(summary.backend), summary, input, undefined, undefined, this.namingSpent(record));
2127
2267
  }
2128
2268
  catch {
2129
2269
  return;
@@ -2268,6 +2408,12 @@ export class SessionHost {
2268
2408
  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 })));
2269
2409
  case "suggest_git_text":
2270
2410
  return await this.suggestGitText(command.sessionId, command.kind, command.paths);
2411
+ case "start_tour":
2412
+ return this.startTour(command.sessionId);
2413
+ case "tour":
2414
+ return this.tour(command.sessionId);
2415
+ case "cancel_tour":
2416
+ return this.cancelTour(command.sessionId);
2271
2417
  case "switch_branch":
2272
2418
  return await this.switchBranch(command.sessionId, command.branch);
2273
2419
  case "switch_scope_branch":
@@ -2925,8 +3071,10 @@ export class SessionHost {
2925
3071
  void this.workflowOwner?.stop(sessionId).catch(() => { });
2926
3072
  // Kept current so a Revive can hand the running total back to the next Backend Session, which
2927
3073
  // counts only its own run.
2928
- if (event.type === "context_usage" && event.spend)
3074
+ if (event.type === "context_usage" && event.spend) {
2929
3075
  record.spend = event.spend;
3076
+ this.recordSpend("session", sessionId, this.spendScope(record), event.spend);
3077
+ }
2930
3078
  /*
2931
3079
  * Ordinarily redundant — `dispatch` and `compact` both set this before the adapter acknowledges,
2932
3080
  * for the race the field's own comment describes. It matters for the turn nobody asked for: a
@@ -3378,6 +3526,8 @@ function spendFrom(entries) {
3378
3526
  const event = entry.event;
3379
3527
  if (event.type === "context_usage" && event.spend)
3380
3528
  spend = event.spend;
3529
+ if (event.type === "forked")
3530
+ spend = undefined;
3381
3531
  }
3382
3532
  return spend;
3383
3533
  }
@@ -49,10 +49,10 @@ export async function startRuntime(options) {
49
49
  store, resolveSecret: name => secrets.resolve(name), retention: config.retention,
50
50
  mcpConnections: config.mcpConnections, mcpAuth,
51
51
  filesystemIsolationMode: config.filesystemIsolationMode, sandboxSupport: config.sandboxSupport,
52
- sandboxSharing: config.sandboxSharing, projectRoot: config.projectRoot,
52
+ sandboxSharing: config.sandboxSharing, updateSourceBranch: config.updateSourceBranch, projectRoot: config.projectRoot,
53
53
  standingAuthorisations: config.standingAuthorisations, allowTool: config.allowTool,
54
54
  defaultBackend: config.defaultBackend, defaultModel: config.defaultModel,
55
- defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
55
+ defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel, tourModel: config.tourModel,
56
56
  });
57
57
  const shells = new ShellRegistry();
58
58
  let workflowSchedules;
@@ -1,6 +1,10 @@
1
1
  import { createServer } from "node:http";
2
+ import { Readable } from "node:stream";
3
+ import { homedir } from "node:os";
2
4
  import { mediaTypeOf } from "../protocol/attachments.js";
3
5
  import { ConfigError } from "./config.js";
6
+ import { gh } from "./github.js";
7
+ import { githubImage } from "./github-image.js";
4
8
  import { workflowRoutes } from './workflow-routes.js';
5
9
  import { workflowScheduleRoutes } from './workflow-schedule-routes.js';
6
10
  import { workflowBuilderRoutes } from './workflow-builder-routes.js';
@@ -367,6 +371,14 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
367
371
  send(response, 200, options.host.list());
368
372
  return;
369
373
  }
374
+ if (request.method === "GET" && url.pathname === "/api/spend") {
375
+ send(response, 200, options.host.spendSummary());
376
+ return;
377
+ }
378
+ if (request.method === "GET" && url.pathname === "/api/plan-limits") {
379
+ send(response, 200, await options.host.planLimits(options.config?.projectRoot() ?? options.scope ?? process.cwd()));
380
+ return;
381
+ }
370
382
  if (request.method === "GET" && url.pathname === "/api/config") {
371
383
  send(response, 200, {
372
384
  // The Project Root first: it is the directory this deployment is anchored to, and a client
@@ -559,6 +571,20 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
559
571
  sendAttachment(response, options.store, attachmentMatch[1] ?? "", attachmentMatch[2] ?? "");
560
572
  return;
561
573
  }
574
+ if (request.method === "GET" && url.pathname === "/api/github-image") {
575
+ const image = await githubImage(url.searchParams.get("url") ?? "", () => gh(homedir(), ["auth", "token"])).catch(() => null);
576
+ if (!image?.body) {
577
+ send(response, 404, { error: "Image not found." });
578
+ return;
579
+ }
580
+ response.writeHead(200, {
581
+ "content-type": image.headers.get("content-type") ?? "",
582
+ "x-content-type-options": "nosniff",
583
+ "cache-control": "private, max-age=300",
584
+ });
585
+ Readable.fromWeb(image.body).pipe(response);
586
+ return;
587
+ }
562
588
  if (request.method === "POST" && url.pathname === "/api/command") {
563
589
  const command = JSON.parse(await readBody(request));
564
590
  try {
@@ -933,7 +959,7 @@ function streamEvents(response, host, sessionId, since, oidc, browserSessionId)
933
959
  detachAuth?.();
934
960
  });
935
961
  }
936
- /** Bearer access is deliberately independent of OIDC so remote CLI/TUI clients keep working. */
962
+ /** Bearer access is deliberately independent of OIDC so remote CLI clients keep working. */
937
963
  async function authenticateRequest(request, options) {
938
964
  if (tokenMatches(options.token, presentedBearer(request)))
939
965
  return { kind: "bearer" };
@@ -995,7 +1021,7 @@ a{display:inline-flex;align-items:center;justify-content:center;width:100%;heigh
995
1021
  response.end(html);
996
1022
  }
997
1023
  /**
998
- * Same-origin only. A request with no Origin header is a non-browser client (the TUI, curl), which
1024
+ * Same-origin only. A request with no Origin header is a non-browser client (the CLI, curl), which
999
1025
  * a hostile page cannot forge on the user's behalf, so it is not what this check defends against.
1000
1026
  */
1001
1027
  function originAllowed(request, publicAppUrl) {
@@ -83,6 +83,30 @@ export async function probeSkills(backend, scope, keep) {
83
83
  await release(held, answered ? keep : undefined);
84
84
  }
85
85
  }
86
+ export async function probePlanLimits(backend, scope, keep) {
87
+ const { held, options } = probeSession(scope);
88
+ const started = backend.create(options);
89
+ const session = await within(started, PROBE_TIMEOUT_MS);
90
+ if (session === undefined) {
91
+ void started.then((late) => void late.dispose().catch(() => { }), () => { });
92
+ return [];
93
+ }
94
+ if (session instanceof Error)
95
+ return [];
96
+ held.session = session;
97
+ let answered = false;
98
+ try {
99
+ const limits = await session.planLimits?.() ?? [];
100
+ answered = true;
101
+ return limits;
102
+ }
103
+ catch {
104
+ return [];
105
+ }
106
+ finally {
107
+ await release(held, answered ? keep : undefined);
108
+ }
109
+ }
86
110
  function message(error) {
87
111
  return error instanceof Error ? error.message : String(error);
88
112
  }
@@ -0,0 +1,118 @@
1
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, truncateSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ const HOUR = 60 * 60 * 1000;
4
+ const DAY = 24 * HOUR;
5
+ const WINDOWS = {
6
+ day: { span: DAY, bucket: HOUR }, week: { span: 7 * DAY, bucket: 6 * HOUR }, month: { span: 30 * DAY, bucket: DAY }, lifetime: { span: Infinity, bucket: 0 },
7
+ };
8
+ const LIFETIME_BUCKETS = [DAY, 7 * DAY, 30 * DAY];
9
+ const MAX_BARS = 60;
10
+ export class SpendLedger {
11
+ path;
12
+ backfill;
13
+ last = new Map();
14
+ deltas = [];
15
+ constructor(root) {
16
+ this.path = join(root, "spend-ledger.jsonl");
17
+ if (!existsSync(this.path)) {
18
+ this.backfill = [];
19
+ return;
20
+ }
21
+ const raw = readFileSync(this.path, "utf8");
22
+ const complete = raw.slice(0, raw.lastIndexOf("\n") + 1);
23
+ if (complete.length < raw.length)
24
+ truncateSync(this.path, Buffer.byteLength(complete));
25
+ for (const line of complete.split("\n"))
26
+ if (line)
27
+ this.apply(JSON.parse(line));
28
+ }
29
+ get needsBackfill() {
30
+ return this.backfill !== undefined;
31
+ }
32
+ record(source, key, scope, spend, at = new Date().toISOString()) {
33
+ const readings = spend.models.flatMap(({ id, tokens, cached, costUSD }) => {
34
+ const previous = this.last.get(JSON.stringify([key, id]));
35
+ if (previous?.tokens === tokens && previous.cached === cached && previous.costUSD === costUSD)
36
+ return [];
37
+ return [{ at, source, key, ...(scope === undefined ? {} : { scope }), model: id, tokens, cached, costUSD }];
38
+ });
39
+ if (readings.length === 0)
40
+ return;
41
+ if (this.backfill)
42
+ this.backfill.push(...readings);
43
+ else
44
+ write(this.path, "a", readings);
45
+ for (const reading of readings)
46
+ this.apply(reading);
47
+ }
48
+ finishBackfill() {
49
+ if (!this.backfill)
50
+ return;
51
+ mkdirSync(dirname(this.path), { recursive: true });
52
+ write(`${this.path}.tmp`, "w", this.backfill);
53
+ renameSync(`${this.path}.tmp`, this.path);
54
+ this.backfill = undefined;
55
+ }
56
+ summary(now = Date.now()) {
57
+ const entries = Object.entries(WINDOWS).map(([name, { span, bucket }]) => [name, this.window(now, span, bucket)]);
58
+ return Object.fromEntries(entries);
59
+ }
60
+ apply(reading) {
61
+ const id = JSON.stringify([reading.key, reading.model]);
62
+ const previous = this.last.get(id);
63
+ const counted = previous && reading.tokens >= previous.tokens && reading.costUSD >= previous.costUSD ? previous : undefined;
64
+ this.last.set(id, { tokens: reading.tokens, cached: reading.cached, costUSD: reading.costUSD });
65
+ this.deltas.push({
66
+ at: Date.parse(reading.at), source: reading.source, model: reading.model,
67
+ tokens: reading.tokens - (counted?.tokens ?? 0),
68
+ cached: reading.cached - (counted?.cached ?? 0),
69
+ costUSD: reading.costUSD - (counted?.costUSD ?? 0),
70
+ });
71
+ }
72
+ window(now, span, bucket) {
73
+ const since = now - span;
74
+ const start = Number.isFinite(since) ? since : this.deltas.reduce((earliest, delta) => Math.min(earliest, delta.at), now);
75
+ const size = bucket || LIFETIME_BUCKETS.find(size => (now - start) / size <= MAX_BARS) || LIFETIME_BUCKETS.at(-1);
76
+ const count = Math.max(1, Math.ceil((now - start) / size));
77
+ const first = now - count * size;
78
+ const result = {
79
+ tokens: 0, cached: 0, costUSD: 0, models: [], sources: [],
80
+ buckets: Array.from({ length: count }, (_, index) => ({ start: new Date(first + index * size).toISOString(), models: [] })),
81
+ };
82
+ for (const delta of this.deltas) {
83
+ if (delta.at < since)
84
+ continue;
85
+ add(result, delta);
86
+ const { models } = result.buckets[Math.min(count - 1, Math.max(0, Math.floor((delta.at - first) / size)))];
87
+ add(find(models, model => model.id === delta.model, () => ({ id: delta.model, tokens: 0, cached: 0, costUSD: 0 })), delta);
88
+ add(find(result.models, model => model.id === delta.model, () => ({ id: delta.model, tokens: 0, cached: 0, costUSD: 0 })), delta);
89
+ add(find(result.sources, source => source.source === delta.source, () => ({ source: delta.source, tokens: 0, cached: 0, costUSD: 0 })), delta);
90
+ }
91
+ result.models.sort((a, b) => b.costUSD - a.costUSD || b.tokens - a.tokens);
92
+ result.sources.sort((a, b) => b.costUSD - a.costUSD || b.tokens - a.tokens);
93
+ return result;
94
+ }
95
+ }
96
+ function write(path, flags, readings) {
97
+ const fd = openSync(path, flags, 0o600);
98
+ try {
99
+ writeFileSync(fd, readings.map(reading => JSON.stringify(reading) + "\n").join(""));
100
+ fsyncSync(fd);
101
+ }
102
+ finally {
103
+ closeSync(fd);
104
+ }
105
+ }
106
+ function add(total, delta) {
107
+ total.tokens += delta.tokens;
108
+ total.cached += delta.cached;
109
+ total.costUSD += delta.costUSD;
110
+ }
111
+ function find(items, match, create) {
112
+ const found = items.find(match);
113
+ if (found)
114
+ return found;
115
+ const item = create();
116
+ items.push(item);
117
+ return item;
118
+ }
@@ -98,6 +98,8 @@ export async function suggestGitText(request) {
98
98
  finally {
99
99
  if (timer)
100
100
  clearTimeout(timer);
101
+ if (session?.spend)
102
+ request.spent?.(session.spend);
101
103
  if (session)
102
104
  await session.dispose().catch(() => { });
103
105
  }
@@ -242,13 +244,13 @@ export class SummaryModelSpare {
242
244
  * tick, before any await. Two namings that both saw the same spare would prompt one Backend
243
245
  * Session twice and take each other's answers.
244
246
  */
245
- async name(backend, model, text, timeoutMs, problem) {
247
+ async name(backend, model, text, timeoutMs, problem, spent) {
246
248
  const claimed = this.claim(model);
247
249
  try {
248
250
  const spare = claimed ? await claimed.session : undefined;
249
251
  if (claimed && spare && !claimed.sink.dead) {
250
252
  try {
251
- return await nameWith(spare, claimed.sink, text, timeoutMs ?? SUMMARY_TIMEOUT_MS, problem);
253
+ return await nameWith(spare, claimed.sink, text, timeoutMs ?? SUMMARY_TIMEOUT_MS, problem, spent);
252
254
  }
253
255
  finally {
254
256
  await spare.dispose().catch(() => { });
@@ -264,6 +266,7 @@ export class SummaryModelSpare {
264
266
  text,
265
267
  ...(timeoutMs === undefined ? {} : { timeoutMs }),
266
268
  ...(problem === undefined ? {} : { problem }),
269
+ ...(spent === undefined ? {} : { spent }),
267
270
  });
268
271
  }
269
272
  finally {
@@ -373,7 +376,7 @@ export async function summariseToName(request) {
373
376
  return undefined;
374
377
  }
375
378
  try {
376
- return await nameWith(session, sink, text, request.timeoutMs ?? SUMMARY_TIMEOUT_MS, request.problem);
379
+ return await nameWith(session, sink, text, request.timeoutMs ?? SUMMARY_TIMEOUT_MS, request.problem, request.spent);
377
380
  }
378
381
  finally {
379
382
  // Every path: answered, junk, timed out, or the prompt itself throwing. A leaked adapter is a
@@ -390,7 +393,7 @@ export async function summariseToName(request) {
390
393
  *
391
394
  * Never throws, like everything else here.
392
395
  */
393
- async function nameWith(session, sink, text, timeoutMs, problem) {
396
+ async function nameWith(session, sink, text, timeoutMs, problem, spent) {
394
397
  /*
395
398
  * Latest-wins per id, because `message` events are snapshots of one message as it streams rather
396
399
  * than pieces of it — appending them would give a name repeated once per token.
@@ -423,6 +426,10 @@ async function nameWith(session, sink, text, timeoutMs, problem) {
423
426
  problem?.(message(error));
424
427
  return undefined;
425
428
  }
429
+ finally {
430
+ if (session.spend)
431
+ spent?.(session.spend);
432
+ }
426
433
  const answer = [...said.values()].join("\n").trim();
427
434
  const name = nameFrom(answer);
428
435
  if (name === undefined) {