@nathanstephenson/flow 0.1.10-beta.5 → 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 (44) hide show
  1. package/build/backend-worker-chunks/{chunk-JOI2POLP.mjs → chunk-U73G6KK4.mjs} +18 -0
  2. package/build/backend-worker-chunks/{claude-GY27HBAY.mjs → claude-THGSOTC2.mjs} +7 -1
  3. package/build/backend-worker-chunks/{pi-JV6MWPW7.mjs → pi-5LAWIJNE.mjs} +82 -3
  4. package/build/backend-worker.mjs +7 -3
  5. package/dist/backend/claude/index.js +6 -0
  6. package/dist/backend/fake/index.js +6 -0
  7. package/dist/backend/pi/index.js +34 -2
  8. package/dist/backend/pi/plan-limits.js +41 -0
  9. package/dist/backend/plan-limits.js +17 -0
  10. package/dist/backend/worker/entry.js +4 -1
  11. package/dist/backend/worker/index.js +5 -0
  12. package/dist/backend/worker/protocol.js +2 -1
  13. package/dist/build-id +1 -1
  14. package/dist/cli/bootstrap.js +1 -1
  15. package/dist/client/context-usage.js +1 -1
  16. package/dist/client/markdown.js +3 -2
  17. package/dist/daemon/config-store.js +1 -0
  18. package/dist/daemon/config.js +31 -2
  19. package/dist/daemon/github-image.js +18 -0
  20. package/dist/daemon/host.js +147 -6
  21. package/dist/daemon/runtime.js +1 -1
  22. package/dist/daemon/server.js +26 -0
  23. package/dist/daemon/skills.js +24 -0
  24. package/dist/daemon/spend-ledger.js +118 -0
  25. package/dist/daemon/summariser.js +11 -4
  26. package/dist/daemon/tour.js +42 -0
  27. package/dist/daemon/workflow-builder.js +3 -1
  28. package/dist/daemon/workflow-execution-resources.js +1 -1
  29. package/dist/daemon/workflow-routes.js +19 -0
  30. package/dist/daemon/workflow-schedules.js +6 -5
  31. package/dist/protocol/plan-limits.js +1 -0
  32. package/dist/protocol/spend.js +2 -0
  33. package/dist/workflows/scheduler.js +26 -14
  34. package/dist/workflows/store.js +16 -2
  35. package/package.json +1 -1
  36. package/web/dist/assets/index-BhfJhrVJ.js +51 -0
  37. package/web/dist/assets/index-BvkM2cWL.css +2 -0
  38. package/web/dist/assets/{settings-mcp-BwOPXAfH.js → settings-mcp-3cgqQB28.js} +1 -1
  39. package/web/dist/assets/{settings-workflows-DocTa31_.js → settings-workflows-Cutm8isB.js} +1 -1
  40. package/web/dist/assets/{workflows-DJqUuGyg.js → workflows-D6oEUUhj.js} +3 -3
  41. package/web/dist/assets/{workflows-pane-oM1fO_BC.js → workflows-pane-KIdSDKJB.js} +1 -1
  42. package/web/dist/index.html +3 -3
  43. package/web/dist/assets/index-BqZ_iUmY.css +0 -2
  44. package/web/dist/assets/index-CxdSb7k0.js +0 -51
@@ -3,6 +3,23 @@ import {
3
3
  external_exports
4
4
  } from "./chunk-NZZME2I3.mjs";
5
5
 
6
+ // src/backend/plan-limits.ts
7
+ function anthropicPlanLimits(usage) {
8
+ const short = anthropicWindow("5-hour", usage?.five_hour);
9
+ const long = anthropicWindow("7-day", usage?.seven_day);
10
+ if (!short || !long) return void 0;
11
+ const others = [
12
+ anthropicWindow("Opus", usage?.seven_day_opus),
13
+ anthropicWindow("Sonnet", usage?.seven_day_sonnet),
14
+ ...(usage?.model_scoped ?? []).map((scoped) => anthropicWindow(scoped.display_name, scoped))
15
+ ].filter((window) => window !== void 0);
16
+ return { short, long, others };
17
+ }
18
+ function anthropicWindow(label, window) {
19
+ if (window?.utilization == null) return void 0;
20
+ return { label, utilization: window.utilization, ...window.resets_at ? { resetsAt: window.resets_at } : {} };
21
+ }
22
+
6
23
  // src/backend/effort.ts
7
24
  var EFFORT_ORDER = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
8
25
  function clampEffort(wanted, available) {
@@ -128,6 +145,7 @@ export {
128
145
  sessionCreateDescription,
129
146
  sessionSendDescription,
130
147
  workflowBuilderTools,
148
+ anthropicPlanLimits,
131
149
  EFFORT_ORDER,
132
150
  clampEffort
133
151
  };
@@ -43,6 +43,7 @@ import {
43
43
  } from "./chunk-K774KOGL.mjs";
44
44
  import {
45
45
  EFFORT_ORDER,
46
+ anthropicPlanLimits,
46
47
  clampEffort,
47
48
  inspectDescription,
48
49
  recoverDescription,
@@ -60,7 +61,7 @@ import {
60
61
  workflowInspectInput,
61
62
  workflowRecoverInput,
62
63
  workflowRelayInput
63
- } from "./chunk-JOI2POLP.mjs";
64
+ } from "./chunk-U73G6KK4.mjs";
64
65
  import {
65
66
  AutoPermissionUnavailable,
66
67
  ZodOptional,
@@ -35058,6 +35059,11 @@ var ClaudeSession = class {
35058
35059
  * That it also rescans the disk is the behaviour worth having: a human who has just written a
35059
35060
  * Skill opens the menu expecting to find it.
35060
35061
  */
35062
+ async planLimits() {
35063
+ const { rate_limits } = await this.stream.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
35064
+ const limits = anthropicPlanLimits(rate_limits);
35065
+ return limits ? [limits] : [];
35066
+ }
35061
35067
  async skills() {
35062
35068
  if (this.options.workflowBuilder) return [];
35063
35069
  const { skills } = await this.stream.reloadSkills();
@@ -2,6 +2,7 @@ import { createRequire as __flowCreateRequire } from 'node:module'; const requir
2
2
  import "./chunk-LAEUXDNH.mjs";
3
3
  import {
4
4
  EFFORT_ORDER,
5
+ anthropicPlanLimits,
5
6
  clampEffort,
6
7
  inspectDescription,
7
8
  recoverDescription,
@@ -19,7 +20,7 @@ import {
19
20
  workflowInspectInput,
20
21
  workflowRecoverInput,
21
22
  workflowRelayInput
22
- } from "./chunk-JOI2POLP.mjs";
23
+ } from "./chunk-U73G6KK4.mjs";
23
24
  import {
24
25
  __commonJS,
25
26
  __export,
@@ -7018,9 +7019,57 @@ var PiAgentPermissions = class {
7018
7019
  }
7019
7020
  };
7020
7021
 
7022
+ // src/backend/pi/plan-limits.ts
7023
+ async function fetchAnthropicPlanLimits(token, signal) {
7024
+ const usage = await getJson(
7025
+ "https://api.anthropic.com/api/oauth/usage",
7026
+ { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" },
7027
+ signal
7028
+ );
7029
+ const limits = anthropicPlanLimits(usage);
7030
+ return limits && { provider: "Anthropic", ...limits };
7031
+ }
7032
+ async function fetchCodexPlanLimits(token, signal) {
7033
+ const usage = await getJson(
7034
+ "https://chatgpt.com/backend-api/wham/usage",
7035
+ { authorization: `Bearer ${token}`, "chatgpt-account-id": codexAccountId(token), "user-agent": "codex-cli" },
7036
+ signal
7037
+ );
7038
+ return codexPlanLimits(usage);
7039
+ }
7040
+ function codexPlanLimits(usage) {
7041
+ const short = codexWindow("", usage.rate_limit?.primary_window);
7042
+ const long = codexWindow("", usage.rate_limit?.secondary_window);
7043
+ if (!short || !long) return void 0;
7044
+ const others = (usage.additional_rate_limits ?? []).flatMap((limit) => [
7045
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.primary_window),
7046
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.secondary_window)
7047
+ ]).filter((window) => window !== void 0);
7048
+ return { provider: "Codex", short, long, others };
7049
+ }
7050
+ function codexWindow(prefix, window) {
7051
+ if (!window) return void 0;
7052
+ const hours = window.limit_window_seconds / 3600;
7053
+ const span = hours < 24 ? `${Math.round(hours)}-hour` : `${Math.round(hours / 24)}-day`;
7054
+ return { label: `${prefix}${span}`, utilization: window.used_percent, resetsAt: new Date(window.reset_at * 1e3).toISOString() };
7055
+ }
7056
+ function codexAccountId(token) {
7057
+ const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
7058
+ const id = payload["https://api.openai.com/auth"]?.chatgpt_account_id;
7059
+ if (!id) throw new Error("No ChatGPT account ID in the Codex token");
7060
+ return id;
7061
+ }
7062
+ async function getJson(url, headers, signal) {
7063
+ const response = await fetch(url, { headers, ...signal ? { signal } : {} });
7064
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
7065
+ return await response.json();
7066
+ }
7067
+
7021
7068
  // src/backend/pi/index.ts
7022
7069
  var PiSession = class {
7023
7070
  capabilities;
7071
+ spend;
7072
+ counted;
7024
7073
  answerEnquiry;
7025
7074
  enquiries;
7026
7075
  work;
@@ -7074,6 +7123,8 @@ var PiSession = class {
7074
7123
  this.agentPermissions = support.agentPermissions;
7075
7124
  if (support.permissionProducer) this.permissionProducer = support.permissionProducer;
7076
7125
  this.session = session;
7126
+ this.spend = support.priorSpend;
7127
+ this.counted = statsOf(session);
7077
7128
  this.applyAutoCompaction = support.autoCompaction;
7078
7129
  this.workflowAutoCompaction = support.workflowAutoCompaction;
7079
7130
  this.workflowCompactionModelId = support.workflowCompactionModelId;
@@ -7210,6 +7261,14 @@ var PiSession = class {
7210
7261
  }))
7211
7262
  ];
7212
7263
  }
7264
+ async planLimits() {
7265
+ const read = async (provider, fetchLimits) => {
7266
+ const token = (await this.session.modelRuntime.getAuth(provider).catch(() => void 0))?.auth.apiKey;
7267
+ return token ? await fetchLimits(token).catch(() => void 0) : void 0;
7268
+ };
7269
+ const limits = await Promise.all([read("anthropic", fetchAnthropicPlanLimits), read("openai-codex", fetchCodexPlanLimits)]);
7270
+ return limits.filter((limit) => limit !== void 0);
7271
+ }
7213
7272
  applyEffort(wanted) {
7214
7273
  const level = clampEffort(wanted, availableEffort(this.session));
7215
7274
  if (!level) {
@@ -7397,11 +7456,27 @@ var PiSession = class {
7397
7456
  if (thinking) this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
7398
7457
  }
7399
7458
  reportContextUsage() {
7459
+ this.countSpend();
7400
7460
  const usage = this.session.getContextUsage();
7401
7461
  if (usage && typeof usage.tokens === "number") {
7402
- this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
7462
+ this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow, ...this.spend ? { spend: this.spend } : {} });
7403
7463
  }
7404
7464
  }
7465
+ countSpend() {
7466
+ const now = statsOf(this.session);
7467
+ const added = { tokens: now.tokens - this.counted.tokens, cached: now.cached - this.counted.cached, costUSD: now.costUSD - this.counted.costUSD };
7468
+ this.counted = now;
7469
+ if (added.tokens <= 0 && added.costUSD <= 0) return;
7470
+ const id = this.session.model ? describeModel(this.session.model).id : "unknown";
7471
+ const spend = this.spend ?? { tokens: 0, cached: 0, costUSD: 0, models: [] };
7472
+ const model = spend.models.find((item) => item.id === id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
7473
+ this.spend = {
7474
+ tokens: spend.tokens + added.tokens,
7475
+ cached: spend.cached + added.cached,
7476
+ costUSD: spend.costUSD + added.costUSD,
7477
+ models: [...spend.models.filter((item) => item.id !== id), { id, tokens: model.tokens + added.tokens, cached: model.cached + added.cached, costUSD: model.costUSD + added.costUSD }]
7478
+ };
7479
+ }
7405
7480
  };
7406
7481
  var PiBackend = class {
7407
7482
  name = "pi";
@@ -7496,7 +7571,7 @@ var PiBackend = class {
7496
7571
  throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
7497
7572
  }
7498
7573
  const autoCompaction = structuredClone(options.autoCompaction);
7499
- const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...mcp ? { mcp } : {}, work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...agentPermissions ? { agentPermissions } : {}, autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}, ...options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}, ...enquiries ? { enquiries } : {}, ...mcp ? { recreate: async (current) => session = (await start(current)).session } : {} });
7574
+ const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...mcp ? { mcp } : {}, work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...agentPermissions ? { agentPermissions } : {}, ...options.priorSpend ? { priorSpend: options.priorSpend } : {}, autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}, ...options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}, ...enquiries ? { enquiries } : {}, ...mcp ? { recreate: async (current) => session = (await start(current)).session } : {} });
7500
7575
  const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel() ? `azure-openai-responses/${settingsManager.getDefaultModel()}` : void 0);
7501
7576
  if (modelId) {
7502
7577
  try {
@@ -7657,6 +7732,10 @@ function joinBlocks(content, kind) {
7657
7732
  function isString(value) {
7658
7733
  return typeof value === "string";
7659
7734
  }
7735
+ function statsOf(session) {
7736
+ const stats = session.getSessionStats();
7737
+ return { tokens: stats.tokens.total, cached: stats.tokens.cacheRead, costUSD: stats.cost };
7738
+ }
7660
7739
  export {
7661
7740
  PiBackend,
7662
7741
  PiSession,
@@ -3955,7 +3955,8 @@ function snapshot(session) {
3955
3955
  return {
3956
3956
  capabilities: session.capabilities,
3957
3957
  resume: session.resumeToken(),
3958
- methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "answerEnquiry", "answerPermission", "setPermissionMode"].filter((method) => typeof session[method] === "function")
3958
+ spend: session.spend,
3959
+ methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "planLimits", "answerEnquiry", "answerPermission", "setPermissionMode"].filter((method) => typeof session[method] === "function")
3959
3960
  };
3960
3961
  }
3961
3962
 
@@ -4146,7 +4147,7 @@ function runWorker() {
4146
4147
  let backend;
4147
4148
  const importing = performance.now();
4148
4149
  try {
4149
- backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-GY27HBAY.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-JV6MWPW7.mjs")).PiBackend();
4150
+ backend = backendModule ? isSea3() ? createRequire(pathToFileURL(process.execPath))(fileURLToPath(backendModule)).default : (await import(backendModule)).default : backendName === "claude" ? new (await import("./backend-worker-chunks/claude-THGSOTC2.mjs")).ClaudeBackend() : new (await import("./backend-worker-chunks/pi-5LAWIJNE.mjs")).PiBackend();
4150
4151
  } catch (error) {
4151
4152
  throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
4152
4153
  }
@@ -4170,7 +4171,7 @@ function runWorker() {
4170
4171
  ...sessionToolsEnabled && options.tools !== "none" ? { sessionTools } : {}
4171
4172
  },
4172
4173
  emit: (event) => {
4173
- const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume);
4174
+ const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume || session.spend !== published?.spend);
4174
4175
  rpc.notify("event", { event, ...changed ? { snapshot: publishSnapshot() } : {} });
4175
4176
  }
4176
4177
  });
@@ -4217,6 +4218,9 @@ function runWorker() {
4217
4218
  case "skills":
4218
4219
  result = await session.skills?.();
4219
4220
  break;
4221
+ case "planLimits":
4222
+ result = await session.planLimits?.();
4223
+ break;
4220
4224
  case "answerEnquiry":
4221
4225
  result = await session.answerEnquiry?.(args[0], args[1]) ?? false;
4222
4226
  break;
@@ -5,6 +5,7 @@ import { randomUUID } from "node:crypto";
5
5
  import { claudeAutoCompactionEnv } from "./auto-compaction.js";
6
6
  import { spawn, spawnSync } from "node:child_process";
7
7
  import { query, } from "@anthropic-ai/claude-agent-sdk";
8
+ import { anthropicPlanLimits } from "../plan-limits.js";
8
9
  import { ClaudeWorkflowSubagent, spawnWorkflowProcess } from "./workflow-subagent.js";
9
10
  import { clampEffort, EFFORT_ORDER } from "../effort.js";
10
11
  import { AsyncQueue } from "./async-queue.js";
@@ -524,6 +525,11 @@ class ClaudeSession {
524
525
  * That it also rescans the disk is the behaviour worth having: a human who has just written a
525
526
  * Skill opens the menu expecting to find it.
526
527
  */
528
+ async planLimits() {
529
+ const { rate_limits } = await this.stream.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
530
+ const limits = anthropicPlanLimits(rate_limits);
531
+ return limits ? [limits] : [];
532
+ }
527
533
  async skills() {
528
534
  if (this.options.workflowBuilder)
529
535
  return [];
@@ -44,6 +44,7 @@ export class FakeSession {
44
44
  rewindFiles;
45
45
  /** What this session was told the Agent Session had already spent, for asserting a Revive. */
46
46
  priorSpend;
47
+ spend;
47
48
  /** What this session was told the machine already authorises, for asserting the read-at-create. */
48
49
  standingAuthorisations;
49
50
  /** Parent Workflow tools, exposed so relay orchestration can be driven without a model in tests. */
@@ -215,6 +216,10 @@ export class FakeSession {
215
216
  async skills() {
216
217
  return this.skillList;
217
218
  }
219
+ planLimitWindows = [];
220
+ async planLimits() {
221
+ return this.planLimitWindows;
222
+ }
218
223
  async setEffort(effort) {
219
224
  this.wantedEffort = effort;
220
225
  const levels = FAKE_CAPABILITIES.models.find((model) => model.id === this.modelId)?.effortLevels;
@@ -247,6 +252,7 @@ export class FakeSession {
247
252
  }
248
253
  /** Test affordance: report Spend, which is how a Revive gets something to carry forward. */
249
254
  reportSpend(spend) {
255
+ this.spend = spend;
250
256
  this.emit({ type: "context_usage", used: 10, window: 100, spend });
251
257
  }
252
258
  /** Test affordance: emit a complete tool call. */
@@ -19,9 +19,12 @@ import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
19
19
  import { backgroundTools } from "./background-calls.js";
20
20
  import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
21
21
  import { PiAgentPermissions } from "./agent-permissions.js";
22
+ import { fetchAnthropicPlanLimits, fetchCodexPlanLimits } from "./plan-limits.js";
22
23
  import { PiWork, callIdFor, resultText, textResult } from "./work.js";
23
24
  export class PiSession {
24
25
  capabilities;
26
+ spend;
27
+ counted;
25
28
  answerEnquiry;
26
29
  enquiries;
27
30
  work;
@@ -77,6 +80,8 @@ export class PiSession {
77
80
  if (support.permissionProducer)
78
81
  this.permissionProducer = support.permissionProducer;
79
82
  this.session = session;
83
+ this.spend = support.priorSpend;
84
+ this.counted = statsOf(session);
80
85
  this.applyAutoCompaction = support.autoCompaction;
81
86
  this.workflowAutoCompaction = support.workflowAutoCompaction;
82
87
  this.workflowCompactionModelId = support.workflowCompactionModelId;
@@ -226,6 +231,14 @@ export class PiSession {
226
231
  })),
227
232
  ];
228
233
  }
234
+ async planLimits() {
235
+ const read = async (provider, fetchLimits) => {
236
+ const token = (await this.session.modelRuntime.getAuth(provider).catch(() => undefined))?.auth.apiKey;
237
+ return token ? await fetchLimits(token).catch(() => undefined) : undefined;
238
+ };
239
+ const limits = await Promise.all([read("anthropic", fetchAnthropicPlanLimits), read("openai-codex", fetchCodexPlanLimits)]);
240
+ return limits.filter((limit) => limit !== undefined);
241
+ }
229
242
  applyEffort(wanted) {
230
243
  const level = clampEffort(wanted, availableEffort(this.session));
231
244
  // Nothing to set on a model with no effort control. The request stays on file, so switching
@@ -435,11 +448,26 @@ export class PiSession {
435
448
  this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
436
449
  }
437
450
  reportContextUsage() {
451
+ this.countSpend();
438
452
  const usage = this.session.getContextUsage();
439
453
  if (usage && typeof usage.tokens === "number") {
440
- this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
454
+ this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow, ...(this.spend ? { spend: this.spend } : {}) });
441
455
  }
442
456
  }
457
+ countSpend() {
458
+ const now = statsOf(this.session);
459
+ const added = { tokens: now.tokens - this.counted.tokens, cached: now.cached - this.counted.cached, costUSD: now.costUSD - this.counted.costUSD };
460
+ this.counted = now;
461
+ if (added.tokens <= 0 && added.costUSD <= 0)
462
+ return;
463
+ const id = this.session.model ? describeModel(this.session.model).id : "unknown";
464
+ const spend = this.spend ?? { tokens: 0, cached: 0, costUSD: 0, models: [] };
465
+ const model = spend.models.find((item) => item.id === id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
466
+ this.spend = {
467
+ tokens: spend.tokens + added.tokens, cached: spend.cached + added.cached, costUSD: spend.costUSD + added.costUSD,
468
+ models: [...spend.models.filter((item) => item.id !== id), { id, tokens: model.tokens + added.tokens, cached: model.cached + added.cached, costUSD: model.costUSD + added.costUSD }],
469
+ };
470
+ }
443
471
  }
444
472
  export class PiBackend {
445
473
  name = "pi";
@@ -537,7 +565,7 @@ export class PiBackend {
537
565
  throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
538
566
  }
539
567
  const autoCompaction = structuredClone(options.autoCompaction);
540
- const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
568
+ const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), ...(options.priorSpend ? { priorSpend: options.priorSpend } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
541
569
  const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel()
542
570
  ? `azure-openai-responses/${settingsManager.getDefaultModel()}` : undefined);
543
571
  if (modelId) {
@@ -708,3 +736,7 @@ function joinBlocks(content, kind) {
708
736
  function isString(value) {
709
737
  return typeof value === "string";
710
738
  }
739
+ function statsOf(session) {
740
+ const stats = session.getSessionStats();
741
+ return { tokens: stats.tokens.total, cached: stats.tokens.cacheRead, costUSD: stats.cost };
742
+ }
@@ -0,0 +1,41 @@
1
+ import { anthropicPlanLimits } from "../plan-limits.js";
2
+ export async function fetchAnthropicPlanLimits(token, signal) {
3
+ const usage = await getJson("https://api.anthropic.com/api/oauth/usage", { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" }, signal);
4
+ const limits = anthropicPlanLimits(usage);
5
+ return limits && { provider: "Anthropic", ...limits };
6
+ }
7
+ export async function fetchCodexPlanLimits(token, signal) {
8
+ const usage = await getJson("https://chatgpt.com/backend-api/wham/usage", { authorization: `Bearer ${token}`, "chatgpt-account-id": codexAccountId(token), "user-agent": "codex-cli" }, signal);
9
+ return codexPlanLimits(usage);
10
+ }
11
+ export function codexPlanLimits(usage) {
12
+ const short = codexWindow("", usage.rate_limit?.primary_window);
13
+ const long = codexWindow("", usage.rate_limit?.secondary_window);
14
+ if (!short || !long)
15
+ return undefined;
16
+ const others = (usage.additional_rate_limits ?? []).flatMap((limit) => [
17
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.primary_window),
18
+ codexWindow(`${limit.limit_name} `, limit.rate_limit?.secondary_window),
19
+ ]).filter((window) => window !== undefined);
20
+ return { provider: "Codex", short, long, others };
21
+ }
22
+ function codexWindow(prefix, window) {
23
+ if (!window)
24
+ return undefined;
25
+ const hours = window.limit_window_seconds / 3600;
26
+ const span = hours < 24 ? `${Math.round(hours)}-hour` : `${Math.round(hours / 24)}-day`;
27
+ return { label: `${prefix}${span}`, utilization: window.used_percent, resetsAt: new Date(window.reset_at * 1000).toISOString() };
28
+ }
29
+ function codexAccountId(token) {
30
+ const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString());
31
+ const id = payload["https://api.openai.com/auth"]?.chatgpt_account_id;
32
+ if (!id)
33
+ throw new Error("No ChatGPT account ID in the Codex token");
34
+ return id;
35
+ }
36
+ async function getJson(url, headers, signal) {
37
+ const response = await fetch(url, { headers, ...(signal ? { signal } : {}) });
38
+ if (!response.ok)
39
+ throw new Error(`${url} answered ${response.status}`);
40
+ return await response.json();
41
+ }
@@ -0,0 +1,17 @@
1
+ export function anthropicPlanLimits(usage) {
2
+ const short = anthropicWindow("5-hour", usage?.five_hour);
3
+ const long = anthropicWindow("7-day", usage?.seven_day);
4
+ if (!short || !long)
5
+ return undefined;
6
+ const others = [
7
+ anthropicWindow("Opus", usage?.seven_day_opus),
8
+ anthropicWindow("Sonnet", usage?.seven_day_sonnet),
9
+ ...(usage?.model_scoped ?? []).map((scoped) => anthropicWindow(scoped.display_name, scoped)),
10
+ ].filter((window) => window !== undefined);
11
+ return { short, long, others };
12
+ }
13
+ function anthropicWindow(label, window) {
14
+ if (window?.utilization == null)
15
+ return undefined;
16
+ return { label, utilization: window.utilization, ...(window.resets_at ? { resetsAt: window.resets_at } : {}) };
17
+ }
@@ -122,7 +122,7 @@ export function runWorker() {
122
122
  emit: (event) => {
123
123
  // Models can be a large catalogue. Do not resend it for every text/tool delta, but do
124
124
  // mirror any changed state before the event that exposes it to the Session Host.
125
- const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume);
125
+ const changed = session && (session.capabilities !== published?.capabilities || session.resumeToken() !== published?.resume || session.spend !== published?.spend);
126
126
  rpc.notify("event", { event, ...(changed ? { snapshot: publishSnapshot() } : {}) });
127
127
  },
128
128
  });
@@ -174,6 +174,9 @@ export function runWorker() {
174
174
  case "skills":
175
175
  result = await session.skills?.();
176
176
  break;
177
+ case "planLimits":
178
+ result = await session.planLimits?.();
179
+ break;
177
180
  case "answerEnquiry":
178
181
  result = await session.answerEnquiry?.(args[0], args[1]) ?? false;
179
182
  break;
@@ -264,6 +264,7 @@ class WorkerSession {
264
264
  capabilities;
265
265
  get sandbox() { return this.launchOptions.sandboxed; }
266
266
  resume;
267
+ spend;
267
268
  worker;
268
269
  rpc;
269
270
  failed;
@@ -276,6 +277,7 @@ class WorkerSession {
276
277
  compact;
277
278
  rewindFiles;
278
279
  skills;
280
+ planLimits;
279
281
  answerEnquiry;
280
282
  answerPermission;
281
283
  setPermissionMode;
@@ -410,6 +412,8 @@ class WorkerSession {
410
412
  this.rewindFiles = (messageId) => this.rpc.call("rewindFiles", [messageId]);
411
413
  if (methods.has("skills"))
412
414
  this.skills = () => this.rpc.call("skills");
415
+ if (methods.has("planLimits"))
416
+ this.planLimits = () => this.rpc.call("planLimits");
413
417
  if (methods.has("answerEnquiry"))
414
418
  this.answerEnquiry = (id, answers) => this.rpc.call("answerEnquiry", [id, answers]);
415
419
  if (methods.has("answerPermission"))
@@ -428,6 +432,7 @@ class WorkerSession {
428
432
  updateSnapshot(state) {
429
433
  this.capabilities = state.capabilities;
430
434
  this.resume = state.resume;
435
+ this.spend = state.spend;
431
436
  }
432
437
  notify(name, value) {
433
438
  switch (name) {
@@ -2,7 +2,8 @@ export function snapshot(session) {
2
2
  return {
3
3
  capabilities: session.capabilities,
4
4
  resume: session.resumeToken(),
5
- methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "answerEnquiry", "answerPermission", "setPermissionMode"]
5
+ spend: session.spend,
6
+ methods: ["refreshMcp", "startWorkflowSubagent", "compact", "rewindFiles", "skills", "planLimits", "answerEnquiry", "answerPermission", "setPermissionMode"]
6
7
  .filter((method) => typeof session[method] === "function"),
7
8
  };
8
9
  }
package/dist/build-id CHANGED
@@ -1 +1 @@
1
- c0812b29-3bd1-4f02-be7b-5147006e3476
1
+ 607b7e81-c593-4a74-86cb-83029e6da64f
@@ -889,7 +889,7 @@ async function bootstrap() {
889
889
  if (!managed) throw new Error("Missing systemd update configuration");
890
890
  await assertSystemdOwner(managed, managed.updater, process.pid);
891
891
  }
892
- const lease = await install.register("c0812b29-3bd1-4f02-be7b-5147006e3476", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
892
+ const lease = await install.register("607b7e81-c593-4a74-86cb-83029e6da64f", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
893
893
  delete process.env.FLOW_UPDATE_CAPABILITY;
894
894
  process.on("exit", lease.release);
895
895
  if (args[0] === "update") {
@@ -43,7 +43,7 @@ export function contextUsageDetail(usage) {
43
43
  * cent, and rounding that to `$0.00` would report free work. Anything at or above a cent reads in
44
44
  * the two places money is normally written.
45
45
  */
46
- function money(usd) {
46
+ export function money(usd) {
47
47
  if (usd >= 0.01)
48
48
  return `$${usd.toFixed(2)}`;
49
49
  if (usd === 0)
@@ -156,12 +156,13 @@ function toImage(href, alt, raw, options) {
156
156
  if (!src || !/^https?:\/\//i.test(src))
157
157
  return { kind: "text", text: raw };
158
158
  const url = new URL(src);
159
- const blob = /^\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(url.pathname);
159
+ const blob = /^\/([^/]+)\/([^/]+)\/(?:blob|raw)\/(.+)$/.exec(url.pathname);
160
160
  if (url.hostname === "github.com" && blob) {
161
161
  url.hostname = "raw.githubusercontent.com";
162
162
  url.pathname = `/${blob[1]}/${blob[2]}/${blob[3]}`;
163
163
  }
164
- return { kind: "image", src: url.href, alt };
164
+ const github = url.hostname === "raw.githubusercontent.com" || (url.hostname === "github.com" && url.pathname.startsWith("/user-attachments/assets/"));
165
+ return { kind: "image", src: options.imageProxy && github ? `${options.imageProxy}${encodeURIComponent(url.href)}` : url.href, alt };
165
166
  }
166
167
  function htmlImages(text, options) {
167
168
  const tags = text.match(/<img\b(?:[^"'<>]|"[^"]*"|'[^']*')*\/?>/gi);
@@ -131,6 +131,7 @@ export class ConfigStore {
131
131
  return { backend, ...summary };
132
132
  return providers?.summary?.backend === backend ? providers.summary : undefined;
133
133
  };
134
+ tourModel = (backend) => this.config.providers?.tours?.[backend];
134
135
  defaultPermissionMode = (backend) => this.config.providers?.permissionModes?.[backend];
135
136
  defaultEffort = (backend) => this.config.providers?.efforts?.[backend];
136
137
  /**
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT, defaultFonts, } from "../protocol/fonts.js";
5
5
  import { DEFAULT_WORKFLOW_RUNTIME, formatDuration, parseDuration, } from "../protocol/settings.js";
6
+ import { EFFORT_ORDER } from "../backend/effort.js";
6
7
  export { DEFAULT_CHROME_FONT, DEFAULT_MONOSPACE_FONT };
7
8
  export { formatDuration, parseDuration };
8
9
  export const DEFAULT_SETTLED_RETENTION = 24 * 60 * 60 * 1000;
@@ -214,7 +215,7 @@ function parseProviders(parsed, warnings) {
214
215
  };
215
216
  }
216
217
  }
217
- for (const field of ["efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"]) {
218
+ for (const field of ["efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"]) {
218
219
  const entries = section[field];
219
220
  if (entries === undefined)
220
221
  continue;
@@ -477,7 +478,7 @@ export function applyPatch(current, patch) {
477
478
  function patchProviders(current, patch) {
478
479
  if (patch === undefined)
479
480
  return current;
480
- refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
+ refuseUnknownKeys(patch, ["defaultBackend", "defaults", "summary", "efforts", "summaries", "tours", "autoCompaction", "compactionModels", "permissionModes"], "providers");
481
482
  const next = {
482
483
  ...(current?.autoCompaction === undefined ? {} : { autoCompaction: { ...current.autoCompaction } }),
483
484
  ...(current?.compactionModels === undefined ? {} : { compactionModels: { ...current.compactionModels } }),
@@ -485,6 +486,7 @@ function patchProviders(current, patch) {
485
486
  ...(current?.efforts === undefined ? {} : { efforts: { ...current.efforts } }),
486
487
  ...(current?.permissionModes === undefined ? {} : { permissionModes: { ...current.permissionModes } }),
487
488
  ...(current?.summaries === undefined ? {} : { summaries: { ...current.summaries } }),
489
+ ...(current?.tours === undefined ? {} : { tours: { ...current.tours } }),
488
490
  ...(current?.defaults === undefined ? {} : { defaults: { ...current.defaults } }),
489
491
  ...(current?.summary === undefined ? {} : { summary: current.summary }),
490
492
  };
@@ -599,6 +601,33 @@ function patchProviders(current, patch) {
599
601
  };
600
602
  }
601
603
  }
604
+ if (patch.tours !== undefined) {
605
+ const entries = patch.tours;
606
+ if (typeof entries !== "object" || entries === null || Array.isArray(entries))
607
+ throw new ConfigError("providers.tours must be an object");
608
+ const tours = { ...next.tours };
609
+ for (const [backend, value] of Object.entries(entries)) {
610
+ const field = `providers.tours.${backend}`;
611
+ if (value === null) {
612
+ delete tours[backend];
613
+ continue;
614
+ }
615
+ if (typeof value !== "object" || Array.isArray(value))
616
+ throw new ConfigError(`${field} must name a model and an effort`);
617
+ refuseUnknownKeys(value, ["modelId", "effort"], field);
618
+ const named = value;
619
+ const problem = checkModelId(named.modelId, `${field}.modelId`);
620
+ if (problem)
621
+ throw new ConfigError(problem);
622
+ if (!EFFORT_ORDER.includes(named.effort))
623
+ throw new ConfigError(`${field}.effort must be a valid effort`);
624
+ tours[backend] = { modelId: named.modelId.trim(), effort: named.effort };
625
+ }
626
+ if (Object.keys(tours).length)
627
+ next.tours = tours;
628
+ else
629
+ delete next.tours;
630
+ }
602
631
  if (patch.permissionModes !== undefined) {
603
632
  if (typeof patch.permissionModes !== "object" || patch.permissionModes === null || Array.isArray(patch.permissionModes))
604
633
  throw new ConfigError("providers.permissionModes must be an object");
@@ -0,0 +1,18 @@
1
+ const TYPES = new Set(["image/png", "image/jpeg", "image/gif", "image/webp"]);
2
+ function isGithubImage(url) {
3
+ if (url.protocol !== "https:")
4
+ return false;
5
+ if (url.hostname === "raw.githubusercontent.com")
6
+ return /^\/[^/]+\/[^/]+\/.+/.test(url.pathname);
7
+ return url.hostname === "github.com" && /^\/user-attachments\/assets\/[0-9a-f-]+$/i.test(url.pathname);
8
+ }
9
+ export async function githubImage(href, token, fetcher = fetch) {
10
+ if (!URL.canParse(href) || !isGithubImage(new URL(href)))
11
+ return null;
12
+ const response = await fetcher(href, { headers: { authorization: `token ${(await token()).trim()}` } });
13
+ const type = response.headers.get("content-type")?.split(";")[0]?.trim() ?? "";
14
+ if (response.ok && TYPES.has(type))
15
+ return response;
16
+ await response.body?.cancel();
17
+ return null;
18
+ }