@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,18 +1,22 @@
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";
4
- import { workflowRoutes } from "./workflow-routes.js";
5
- import { workflowScheduleRoutes } from "./workflow-schedule-routes.js";
6
- import { workflowBuilderRoutes } from "./workflow-builder-routes.js";
7
- import { workflowMcpAuthoringRoutes } from "./workflow-mcp-authoring-routes.js";
8
- import { hostControlRoute } from "./host-control-routes.js";
9
- import { readBody, send } from "./http.js";
10
- import { workflowExecutionRoutes } from "./workflow-execution-routes.js";
6
+ import { gh } from "./github.js";
7
+ import { githubImage } from "./github-image.js";
8
+ import { workflowRoutes } from './workflow-routes.js';
9
+ import { workflowScheduleRoutes } from './workflow-schedule-routes.js';
10
+ import { workflowBuilderRoutes } from './workflow-builder-routes.js';
11
+ import { workflowMcpAuthoringRoutes } from './workflow-mcp-authoring-routes.js';
12
+ import { hostControlRoute } from './host-control-routes.js';
13
+ import { readBody, send } from './http.js';
14
+ import { workflowExecutionRoutes } from './workflow-execution-routes.js';
11
15
  import { discoverProjects, includedProjects, searchDirectories } from "./projects.js";
12
16
  import { gitAvailable, head, isRepository, localBranches, MAX_BRANCHES } from "./git.js";
13
17
  import { tokenMatches } from "./auth.js";
14
18
  import { CommandRefused } from "./host.js";
15
- import { UpdateRefusal } from "./update-api.js";
19
+ import { UpdateRefusal } from './update-api.js';
16
20
  const PUBLIC_ICON_PATHS = new Set([
17
21
  "/favicon.svg",
18
22
  "/favicon-16x16.png",
@@ -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
@@ -435,9 +447,10 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
435
447
  *
436
448
  * Its own endpoint rather than more of `/api/config`, and a query rather than state, for the
437
449
  * reason `/api/directories` is (ADR 0011): the answer changes outside Flow — a `git
438
- * branch` in a terminal, a `git fetch` — so there is nothing worth folding into the document
450
+ * branch` in a terminal, a `git fetch` — so the list of branches is not folded into the document
439
451
  * every client polls, and a cache would need a filesystem watcher in order to be more often
440
- * wrong.
452
+ * wrong. The Git State of an Agent Session's Scope is different: the Session Host holds it and
453
+ * reads it again at known points, and `SessionSummary.git` carries it (ADR 0043).
441
454
  *
442
455
  * Answers for a *Scope* rather than for an Agent Session, because the New Agent Session view
443
456
  * has to ask before there is a session to ask about: picking the branch to cut a worktree from
@@ -558,6 +571,20 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
558
571
  sendAttachment(response, options.store, attachmentMatch[1] ?? "", attachmentMatch[2] ?? "");
559
572
  return;
560
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
+ }
561
588
  if (request.method === "POST" && url.pathname === "/api/command") {
562
589
  const command = JSON.parse(await readBody(request));
563
590
  try {
@@ -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
+ }
@@ -1,13 +1,16 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import { resolve } from "node:path";
3
3
  import { run, GIT_READ_TIMEOUT_MS } from "./git.js";
4
+ export async function commonGitPath(scope, name) {
5
+ const common = await run(scope, ["rev-parse", "--git-common-dir"], GIT_READ_TIMEOUT_MS);
6
+ if (!common.ok)
7
+ throw new Error(common.failure.message);
8
+ return resolve(scope, common.value.trim(), name);
9
+ }
4
10
  export async function localStacks(scope) {
5
- const path = await run(scope, ["rev-parse", "--git-path", "gh-stack"], GIT_READ_TIMEOUT_MS);
6
- if (!path.ok)
7
- throw new Error(path.failure.message);
8
11
  let raw;
9
12
  try {
10
- raw = await readFile(resolve(scope, path.value.trim()), "utf8");
13
+ raw = await readFile(await commonGitPath(scope, "gh-stack"), "utf8");
11
14
  }
12
15
  catch (error) {
13
16
  if (error.code === "ENOENT")
@@ -16,9 +19,13 @@ export async function localStacks(scope) {
16
19
  }
17
20
  const data = JSON.parse(raw);
18
21
  if (data.schemaVersion !== 1 || !Array.isArray(data.stacks) || data.stacks.some(s => !s.trunk || typeof s.trunk.branch !== "string" || !Array.isArray(s.branches) || s.branches.some(b => typeof b.branch !== "string")))
19
- throw new Error("Invalid or unsupported gh stack metadata. Repair it with gh stack before publishing or syncing.");
22
+ throw new Error("Invalid or unsupported gh stack metadata. Repair it with gh stack before you continue.");
20
23
  return data.stacks;
21
24
  }
22
25
  export async function localStack(scope, branch) {
23
26
  return (await localStacks(scope)).find(s => s.branches.some(b => b.branch === branch));
24
27
  }
28
+ export function stackParent(stack, branch) {
29
+ const index = stack.branches.findIndex(b => b.branch === branch);
30
+ return stack.branches.slice(0, index).filter(b => !b.pullRequest?.merged).at(-1)?.branch ?? stack.trunk.branch;
31
+ }