@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +60 -21
  2. package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
  8. package/build/backend-worker.mjs +77 -123
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +201 -21
  13. package/dist/backend/claude/session-tools.js +14 -0
  14. package/dist/backend/claude/subagents.js +41 -9
  15. package/dist/backend/claude/todo-list.js +114 -0
  16. package/dist/backend/claude/workflow-parent.js +1 -1
  17. package/dist/backend/diff-excerpt-instructions.js +8 -0
  18. package/dist/backend/fake/index.js +54 -6
  19. package/dist/backend/mcp.js +4 -1
  20. package/dist/backend/pi/agent-permissions.js +1 -1
  21. package/dist/backend/pi/cache-warming.js +8 -0
  22. package/dist/backend/pi/canonical-json.js +120 -0
  23. package/dist/backend/pi/compaction-model.js +3 -2
  24. package/dist/backend/pi/host-auth.js +258 -0
  25. package/dist/backend/pi/import.js +269 -0
  26. package/dist/backend/pi/index.js +125 -21
  27. package/dist/backend/pi/model-auth.js +159 -0
  28. package/dist/backend/pi/model-catalog.js +120 -0
  29. package/dist/backend/pi/model-config.js +5 -0
  30. package/dist/backend/pi/model-selection.js +32 -0
  31. package/dist/backend/pi/plan-limits.js +41 -0
  32. package/dist/backend/pi/session-tools.js +21 -0
  33. package/dist/backend/pi/state.js +19 -1
  34. package/dist/backend/pi/subagents.js +7 -3
  35. package/dist/backend/pi/todo-list.js +23 -0
  36. package/dist/backend/pi/work.js +9 -1
  37. package/dist/backend/pi/workflow-parent.js +1 -1
  38. package/dist/backend/pi/workflow-subagent.js +4 -3
  39. package/dist/backend/plan-limits.js +17 -0
  40. package/dist/backend/session-tools.js +27 -0
  41. package/dist/backend/worker/claude-state.js +48 -0
  42. package/dist/backend/worker/entry.js +49 -8
  43. package/dist/backend/worker/index.js +155 -17
  44. package/dist/backend/worker/launcher.js +11 -4
  45. package/dist/backend/worker/protocol.js +2 -1
  46. package/dist/backend/worker/rpc.js +13 -0
  47. package/dist/backend/worker/sandbox-mcp.js +18 -7
  48. package/dist/backend/workflow-tools.js +9 -6
  49. package/dist/build-id +1 -1
  50. package/dist/cli/application.js +48 -42
  51. package/dist/cli/bootstrap.js +2 -2
  52. package/dist/cli/host-control.js +1 -1
  53. package/dist/cli/install-guard.js +2 -2
  54. package/dist/cli/main.js +4 -4
  55. package/dist/cli/systemd-update.js +3 -3
  56. package/dist/cli/update.js +6 -6
  57. package/dist/cli/web-update.js +6 -6
  58. package/dist/client/connection.js +46 -0
  59. package/dist/client/context-usage.js +3 -4
  60. package/dist/client/diff.js +40 -0
  61. package/dist/client/enquiry.js +0 -6
  62. package/dist/client/markdown.js +3 -2
  63. package/dist/client/model-choices.js +1 -1
  64. package/dist/client/permission.js +1 -2
  65. package/dist/client/project-name.js +3 -1
  66. package/dist/client/reduce.js +77 -3
  67. package/dist/client/relative-time.js +1 -1
  68. package/dist/client/scope-kind.js +6 -3
  69. package/dist/client/search.js +1 -1
  70. package/dist/client/status.js +1 -1
  71. package/dist/client/subagent-tree.js +49 -0
  72. package/dist/client/tool-chains.js +1 -1
  73. package/dist/client/tool-summary.js +28 -18
  74. package/dist/daemon/changes.js +128 -0
  75. package/dist/daemon/commit.js +84 -0
  76. package/dist/daemon/config-store.js +8 -3
  77. package/dist/daemon/config.js +105 -4
  78. package/dist/daemon/diff-excerpts.js +52 -0
  79. package/dist/daemon/git-state.js +197 -0
  80. package/dist/daemon/git.js +53 -10
  81. package/dist/daemon/github-image.js +18 -0
  82. package/dist/daemon/github.js +54 -0
  83. package/dist/daemon/host-control-routes.js +1 -1
  84. package/dist/daemon/host.js +1010 -116
  85. package/dist/daemon/http.js +4 -1
  86. package/dist/daemon/log.js +3 -0
  87. package/dist/daemon/mcp-auth.js +1 -1
  88. package/dist/daemon/models.js +2 -2
  89. package/dist/daemon/pi-model-cache.js +44 -0
  90. package/dist/daemon/pull-request.js +223 -138
  91. package/dist/daemon/push.js +43 -0
  92. package/dist/daemon/repository.js +123 -0
  93. package/dist/daemon/runtime.js +103 -22
  94. package/dist/daemon/secret-store.js +1 -1
  95. package/dist/daemon/server.js +111 -14
  96. package/dist/daemon/session-tool-views.js +22 -0
  97. package/dist/daemon/skills.js +24 -0
  98. package/dist/daemon/spend-ledger.js +118 -0
  99. package/dist/daemon/stack-metadata.js +12 -5
  100. package/dist/daemon/stack.js +162 -657
  101. package/dist/daemon/store.js +2 -0
  102. package/dist/daemon/summariser.js +30 -12
  103. package/dist/daemon/tour.js +56 -0
  104. package/dist/daemon/whisper.js +144 -0
  105. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  106. package/dist/daemon/workflow-authoring-scope.js +1 -1
  107. package/dist/daemon/workflow-builder-files.js +2 -2
  108. package/dist/daemon/workflow-builder-guidance.js +1 -1
  109. package/dist/daemon/workflow-builder-routes.js +2 -2
  110. package/dist/daemon/workflow-builder.js +44 -17
  111. package/dist/daemon/workflow-environment.js +193 -0
  112. package/dist/daemon/workflow-execution-launch.js +77 -0
  113. package/dist/daemon/workflow-execution-resources.js +76 -0
  114. package/dist/daemon/workflow-execution-routes.js +17 -8
  115. package/dist/daemon/workflow-execution-values.js +128 -0
  116. package/dist/daemon/workflow-executions.js +434 -305
  117. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  118. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  119. package/dist/daemon/workflow-mcp.js +1 -1
  120. package/dist/daemon/workflow-routes.js +60 -2
  121. package/dist/daemon/workflow-schedule-driver.js +251 -0
  122. package/dist/daemon/workflow-schedule-routes.js +137 -0
  123. package/dist/daemon/workflow-schedules.js +342 -0
  124. package/dist/isolation/filesystem.js +6 -2
  125. package/dist/isolation/sandbox.js +61 -18
  126. package/dist/isolation/shared-sandbox.js +3 -3
  127. package/dist/isolation/toolchain-assets.js +1 -1
  128. package/dist/protocol/events.js +3 -0
  129. package/dist/protocol/plan-limits.js +1 -0
  130. package/dist/protocol/settings.js +1 -0
  131. package/dist/protocol/spend.js +2 -0
  132. package/dist/protocol/stack.js +12 -39
  133. package/dist/protocol/workflow-schedules.js +1 -0
  134. package/dist/workflows/calls.js +53 -0
  135. package/dist/workflows/errors.js +2 -0
  136. package/dist/workflows/executors.js +6 -5
  137. package/dist/workflows/graph.js +83 -9
  138. package/dist/workflows/invocations.js +23 -0
  139. package/dist/workflows/mcp.js +1 -1
  140. package/dist/workflows/owner.js +45 -0
  141. package/dist/workflows/records.js +150 -10
  142. package/dist/workflows/recovery.js +87 -2
  143. package/dist/workflows/runtime-settings.js +16 -16
  144. package/dist/workflows/runtime.js +2 -2
  145. package/dist/workflows/schedule-errors.js +2 -0
  146. package/dist/workflows/schedule-store.js +385 -0
  147. package/dist/workflows/scheduler.js +389 -98
  148. package/dist/workflows/schedules.js +130 -0
  149. package/dist/workflows/schema.js +3 -1
  150. package/dist/workflows/store.js +126 -13
  151. package/package.json +10 -6
  152. package/web/dist/assets/index-C76t-z4w.css +2 -0
  153. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  154. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  155. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  156. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  157. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  158. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  159. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  160. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  161. package/web/dist/index.html +6 -5
  162. package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
  163. package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
  164. package/dist/daemon/publish.js +0 -289
  165. package/dist/tui/app.js +0 -612
  166. package/dist/tui/keys.js +0 -90
  167. package/dist/tui/render.js +0 -411
  168. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  169. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  170. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  171. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  172. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  173. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  174. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The Agent Session's Todo List, as Claude's todo tools build it.
3
+ *
4
+ * Claude has two ways to keep one. `TodoWrite` hands over the whole list every time, so its input is
5
+ * already the snapshot. The `Task*` tools edit one task at a time, so their effect is folded into a
6
+ * list here and the whole list reported — the protocol's `plan` event is a snapshot, never a delta.
7
+ *
8
+ * Fed only the Agent Session's own model's calls, and only settled ones: a denied or failed call
9
+ * changed nothing, so it reports nothing. The live adapter and Import both drive this, so an imported
10
+ * conversation reconstructs the same list a live one showed.
11
+ *
12
+ * Deliberately free of the SDK: Import reads Claude Code's records without opening a session.
13
+ */
14
+ /** The todo tools this reads. `TaskGet` is one too, but reading a task changes nothing. */
15
+ export const TODO_TOOLS = new Set(["TodoWrite", "TaskCreate", "TaskUpdate", "TaskList"]);
16
+ const STATUSES = new Set(["pending", "in_progress", "completed"]);
17
+ function statusOf(value) {
18
+ return typeof value === "string" && STATUSES.has(value) ? value : undefined;
19
+ }
20
+ function recordOf(value) {
21
+ return value !== null && typeof value === "object" ? value : {};
22
+ }
23
+ function idOf(value) {
24
+ if (typeof value === "string" && value !== "")
25
+ return value;
26
+ if (typeof value === "number")
27
+ return String(value);
28
+ return undefined;
29
+ }
30
+ export class TodoList {
31
+ items = [];
32
+ /**
33
+ * Fold one settled todo call into the list.
34
+ *
35
+ * `input` is the call's own input and `result` the SDK's structured `tool_use_result`. Returns
36
+ * the whole new list when the call changed it, and undefined when it did not — including for a
37
+ * call that is not a todo call at all, so a caller can hand over every result it sees.
38
+ */
39
+ settle(name, input, result, isError) {
40
+ if (isError || !TODO_TOOLS.has(name))
41
+ return undefined;
42
+ const next = this.apply(name, recordOf(input), recordOf(result));
43
+ if (next === undefined)
44
+ return undefined;
45
+ const changed = !sameItems(this.items, next);
46
+ // Kept even when the list reads the same: a `TaskList` can bring back the ids a `TodoWrite` list
47
+ // never had, and the next `TaskUpdate` needs them.
48
+ this.items = next;
49
+ return changed ? this.snapshot() : undefined;
50
+ }
51
+ snapshot() {
52
+ return this.items.map(({ item }) => ({ ...item }));
53
+ }
54
+ apply(name, input, result) {
55
+ switch (name) {
56
+ case "TodoWrite": {
57
+ if (!Array.isArray(input["todos"]))
58
+ return undefined;
59
+ return input["todos"].flatMap((raw) => {
60
+ const todo = recordOf(raw);
61
+ const status = statusOf(todo["status"]);
62
+ // `activeForm` is the spinner's wording, not the item's; the list shows what the item is.
63
+ return typeof todo["content"] === "string" && status ? [{ item: { content: todo["content"], status } }] : [];
64
+ });
65
+ }
66
+ case "TaskCreate": {
67
+ const task = recordOf(result["task"]);
68
+ const id = idOf(task["id"]);
69
+ const subject = typeof task["subject"] === "string" ? task["subject"] : input["subject"];
70
+ if (id === undefined || typeof subject !== "string")
71
+ return undefined;
72
+ const created = { id, item: { content: subject, status: "pending" } };
73
+ const at = this.items.findIndex((item) => item.id === id);
74
+ return at < 0 ? [...this.items, created] : this.items.map((item, index) => index === at ? created : item);
75
+ }
76
+ case "TaskUpdate": {
77
+ if (result["success"] === false)
78
+ return undefined;
79
+ const id = idOf(input["taskId"]) ?? idOf(result["taskId"]);
80
+ const at = this.items.findIndex((item) => item.id !== undefined && item.id === id);
81
+ // A task this list never saw created — most often one from before a Revive, which a
82
+ // `TaskList` will bring back. Guessing where it belongs would be worse than leaving it out.
83
+ if (at < 0)
84
+ return undefined;
85
+ if (input["status"] === "deleted")
86
+ return this.items.filter((_, index) => index !== at);
87
+ const existing = this.items[at];
88
+ const status = statusOf(input["status"]) ?? existing.item.status;
89
+ const content = typeof input["subject"] === "string" ? input["subject"] : existing.item.content;
90
+ return this.items.map((item, index) => index === at ? { ...item, item: { ...item.item, content, status } } : item);
91
+ }
92
+ case "TaskList": {
93
+ if (!Array.isArray(result["tasks"]))
94
+ return undefined;
95
+ return result["tasks"].flatMap((raw) => {
96
+ const task = recordOf(raw);
97
+ const id = idOf(task["id"]);
98
+ const status = statusOf(task["status"]);
99
+ return id !== undefined && typeof task["subject"] === "string" && status
100
+ ? [{ id, item: { content: task["subject"], status } }] : [];
101
+ });
102
+ }
103
+ default:
104
+ return undefined;
105
+ }
106
+ }
107
+ }
108
+ /** Whether two lists read the same to a human. Ids are bookkeeping, not part of the snapshot. */
109
+ function sameItems(left, right) {
110
+ return left.length === right.length && left.every(({ item }, index) => {
111
+ const other = right[index].item;
112
+ return item.content === other.content && item.status === other.status && item.priority === other.priority;
113
+ });
114
+ }
@@ -1,5 +1,5 @@
1
1
  import { createSdkMcpServer, tool } from '@anthropic-ai/claude-agent-sdk';
2
- import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from "../workflow-tools.js";
2
+ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput, inspectDescription, recoverDescription, relayEnquiryDescription, relayPermissionDescription } from '../workflow-tools.js';
3
3
  export function workflowParentServer(parent) {
4
4
  if (!parent)
5
5
  return {};
@@ -0,0 +1,8 @@
1
+ export const DIFF_EXCERPT_INSTRUCTIONS = [
2
+ "To show a diff to the human, do not copy diff text. Write an empty fence that names the file and a range of line numbers in the new file (old file for a deleted file):",
3
+ "```flow-diff path=src/example.ts lines=40-72",
4
+ "```",
5
+ "Flow replaces each fence with the complete hunks that overlap the range. Without lines=, Flow shows all hunks of the file.",
6
+ "Flow reads the uncommitted changes when the file has them, and the committed branch changes when it does not. Add view=uncommitted or view=branch to choose.",
7
+ "When you give a Subagent a task that reports diffs, give it these instructions.",
8
+ ].join("\n");
@@ -37,8 +37,14 @@ export class FakeSession {
37
37
  /** Parallel to `prompts`, so a test can assert what reached the backend beside each text. */
38
38
  promptedAttachments = [];
39
39
  resumedFrom;
40
+ resumedBefore;
41
+ /** Parallel to `prompts`: the host's user message id for each. */
42
+ promptIds = [];
43
+ rewoundFiles = [];
44
+ rewindFiles;
40
45
  /** What this session was told the Agent Session had already spent, for asserting a Revive. */
41
46
  priorSpend;
47
+ spend;
42
48
  /** What this session was told the machine already authorises, for asserting the read-at-create. */
43
49
  standingAuthorisations;
44
50
  /** Parent Workflow tools, exposed so relay orchestration can be driven without a model in tests. */
@@ -150,6 +156,8 @@ export class FakeSession {
150
156
  return true;
151
157
  };
152
158
  }
159
+ if (this.capabilities.rewindFiles)
160
+ this.rewindFiles = async (messageId) => { this.rewoundFiles.push(messageId); };
153
161
  if (this.capabilities.compaction) {
154
162
  // Opens and closes a turn, because a compaction is one: it spends money and holds the backend
155
163
  // while it runs, and the Steering Queue only orders messages correctly if it is told so.
@@ -166,6 +174,7 @@ export class FakeSession {
166
174
  this.emit = options.emit;
167
175
  this.modelId = options.modelId ?? "fake-1";
168
176
  this.resumedFrom = options.resume;
177
+ this.resumedBefore = options.resumeBefore;
169
178
  this.priorSpend = options.priorSpend;
170
179
  this.emit({ type: "model_changed", model: { id: this.modelId, provider: "fake" } });
171
180
  if (options.effort)
@@ -174,8 +183,9 @@ export class FakeSession {
174
183
  resumeToken() {
175
184
  return "fake-resume";
176
185
  }
177
- async prompt(text, attachments) {
186
+ async prompt(text, attachments, messageId) {
178
187
  this.prompts.push(text);
188
+ this.promptIds.push(messageId);
179
189
  this.promptedAttachments.push(attachments ?? []);
180
190
  this.turnId = randomUUID();
181
191
  this.emit({ type: "turn_started", turnId: this.turnId });
@@ -206,6 +216,10 @@ export class FakeSession {
206
216
  async skills() {
207
217
  return this.skillList;
208
218
  }
219
+ planLimitWindows = [];
220
+ async planLimits() {
221
+ return this.planLimitWindows;
222
+ }
209
223
  async setEffort(effort) {
210
224
  this.wantedEffort = effort;
211
225
  const levels = FAKE_CAPABILITIES.models.find((model) => model.id === this.modelId)?.effortLevels;
@@ -238,6 +252,7 @@ export class FakeSession {
238
252
  }
239
253
  /** Test affordance: report Spend, which is how a Revive gets something to carry forward. */
240
254
  reportSpend(spend) {
255
+ this.spend = spend;
241
256
  this.emit({ type: "context_usage", used: 10, window: 100, spend });
242
257
  }
243
258
  /** Test affordance: emit a complete tool call. */
@@ -247,6 +262,12 @@ export class FakeSession {
247
262
  this.emit({ type: "tool_ended", callId, result, isError });
248
263
  return callId;
249
264
  }
265
+ /** Test affordance: a todo call and the Todo List snapshot it produced, as the Claude adapter reports one. */
266
+ writeTodos(entries) {
267
+ const callId = this.useTool("TodoWrite", { todos: entries }, "ok");
268
+ this.emit({ type: "plan", entries, callId });
269
+ return callId;
270
+ }
250
271
  /**
251
272
  * Test affordance: open a turn nobody prompted for.
252
273
  *
@@ -314,12 +335,14 @@ export class FakeSession {
314
335
  *
315
336
  * `completeTurn` deliberately does not close an open Subagent: leaving one running is the
316
337
  * torn-Subagent fixture, and the Session Host is what has to cope with it.
338
+ *
339
+ * `producer` names the Subagent spawning this one, for a nested Subagent.
317
340
  */
318
- beginSubagent(name, description) {
341
+ beginSubagent(name, description, producer) {
319
342
  const subagentId = randomUUID();
320
- const subagent = new FakeSubagent(subagentId, name, description, this.emit);
343
+ const subagent = new FakeSubagent(subagentId, name, description, this.emit, this.modelId, this.effort, producer);
321
344
  this.subagents.push(subagent);
322
- this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description } });
345
+ this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description }, ...(producer ? { producer } : {}) });
323
346
  subagent.snapshot({ state: "running" });
324
347
  return subagent;
325
348
  }
@@ -381,16 +404,22 @@ export class FakeSubagent {
381
404
  subagentId;
382
405
  name;
383
406
  description;
407
+ model;
408
+ effort;
409
+ producer;
384
410
  finished = false;
385
411
  launched = false;
386
412
  emit;
387
413
  /** Bumped when a message finalises, so a partial and its finished half share one id. */
388
414
  messageIndex = 0;
389
- constructor(subagentId, name, description, emit) {
415
+ constructor(subagentId, name, description, emit, model, effort, producer) {
390
416
  this.subagentId = subagentId;
391
417
  this.name = name;
392
418
  this.description = description;
393
419
  this.emit = emit;
420
+ this.model = model;
421
+ this.effort = effort;
422
+ this.producer = producer;
394
423
  }
395
424
  /**
396
425
  * Attributed assistant text. The id is stable until the message finalises, because a partial and
@@ -408,6 +437,12 @@ export class FakeSubagent {
408
437
  if (final)
409
438
  this.messageIndex += 1;
410
439
  }
440
+ /** Instructions from the model that spawned it. */
441
+ instruct(text) {
442
+ const id = randomUUID();
443
+ this.emit({ type: "subagent_instruction", id, text, producer: { subagentId: this.subagentId } });
444
+ return id;
445
+ }
411
446
  /** An attributed tool call — the subagent's Read, not the parent's. */
412
447
  useTool(name, input, result, isError = false) {
413
448
  const callId = randomUUID();
@@ -440,6 +475,7 @@ export class FakeSubagent {
440
475
  callId: this.subagentId,
441
476
  result: `${this.name} launched in the background`,
442
477
  isError: false,
478
+ ...this.attribution(),
443
479
  });
444
480
  }
445
481
  finish(reason = "complete") {
@@ -452,7 +488,7 @@ export class FakeSubagent {
452
488
  // produces.
453
489
  if (this.launched)
454
490
  return;
455
- this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error" });
491
+ this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error", ...this.attribution() });
456
492
  }
457
493
  /** @internal — used by FakeSession to emit the opening snapshot. */
458
494
  snapshot(state) {
@@ -461,9 +497,15 @@ export class FakeSubagent {
461
497
  subagentId: this.subagentId,
462
498
  name: this.name,
463
499
  ...(this.description === undefined ? {} : { description: this.description }),
500
+ model: this.model,
501
+ ...(this.effort === undefined ? {} : { effort: this.effort }),
502
+ ...this.attribution(),
464
503
  ...state,
465
504
  });
466
505
  }
506
+ attribution() {
507
+ return this.producer ? { producer: this.producer } : {};
508
+ }
467
509
  }
468
510
  export class FakeBackend {
469
511
  name = "fake";
@@ -500,6 +542,12 @@ export class FakeBackend {
500
542
  for (const resume of this.waiting.splice(0))
501
543
  resume();
502
544
  }
545
+ /** Every Fork copy asked of this backend. */
546
+ forks = [];
547
+ fork(from, to) {
548
+ this.forks.push({ from, to });
549
+ return from.resume;
550
+ }
503
551
  get latest() {
504
552
  const session = this.sessions.at(-1);
505
553
  if (!session)
@@ -60,12 +60,14 @@ export class McpSession {
60
60
  stateRoot;
61
61
  isolationMode;
62
62
  expectedScopeIdentity;
63
+ scopeReadOnly;
63
64
  /** Sandbox workers: the host owns OAuth, refreshes on request and returns only access tokens. */
64
65
  hostToken;
65
66
  /** Sandbox workers start local servers from host paths over the VM's shared file system. */
66
67
  connectTimeoutMs = 10_000;
67
- constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationMode = "bubblewrap", expectedScopeIdentity, hostToken) {
68
+ constructor(connections, scope, auth, direct = false, resolveSecret, protectedPaths, stateRoot, isolationMode = "bubblewrap", expectedScopeIdentity, hostToken, scopeReadOnly = false) {
68
69
  this.hostToken = hostToken;
70
+ this.scopeReadOnly = scopeReadOnly;
69
71
  this.connections = structuredClone(connections);
70
72
  this.scope = scope;
71
73
  this.auth = auth;
@@ -196,6 +198,7 @@ export class McpSession {
196
198
  ...(this.protectedPaths ? { protectedPaths: this.protectedPaths } : {}),
197
199
  ...(this.stateRoot ? { stateRoot: this.stateRoot } : {}),
198
200
  credentials: "none",
201
+ scopeReadOnly: this.scopeReadOnly,
199
202
  });
200
203
  // Disposal can arrive while the mount/namespace probe is in flight. No spawn may
201
204
  // follow it, even when preparation succeeds after dispose() has closed the client.
@@ -35,7 +35,7 @@ export class PiAgentPermissions {
35
35
  return { name: "flow-agent-permissions", hidden: true, factory: (pi) => {
36
36
  pi.on("tool_call", async (event, ctx) => {
37
37
  const tool = event.toolName;
38
- if (tool === "read" || tool === "ask_question" || tool === "subagent" || tool === "bash_output" || tool === "kill_shell" || tool.startsWith("workflow_") ||
38
+ if (tool === "read" || tool === "session_list" || tool === "session_inspect" || tool === "ask_question" || tool === "todo_write" || tool === "subagent" || tool === "bash_output" || tool === "kill_shell" || tool.startsWith("workflow_") ||
39
39
  this.grants.has(tool) || this.mode === "always")
40
40
  return;
41
41
  const refusedKey = `${producer?.subagentId ?? "parent"}/${tool}`;
@@ -0,0 +1,8 @@
1
+ export function streamingCacheWarming(settings) {
2
+ return { name: "flow-streaming-cache-warming", hidden: true, factory: (pi) => {
3
+ pi.on("cache_warming_decision", (_event, ctx) => {
4
+ if (settings.getGlobalSettings().cacheWarming !== "idle" && ctx.isIdle())
5
+ return { action: "stop" };
6
+ });
7
+ } };
8
+ }
@@ -0,0 +1,120 @@
1
+ import { constants, closeSync, fstatSync, ftruncateSync, lstatSync, openSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { setTimeout as sleep } from 'node:timers/promises';
3
+ import lockfile from 'proper-lockfile';
4
+ function object(value) {
5
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
6
+ }
7
+ export class PiCanonicalJson {
8
+ path;
9
+ name;
10
+ constructor(path, name) { this.path = path; this.name = name; }
11
+ check(stat) {
12
+ if (!stat.isFile() || (this.name === 'models-store.json' && stat.nlink !== 1)) {
13
+ throw new Error(this.name === 'auth.json' ? 'Pi auth.json must be a regular file, not a symbolic link'
14
+ : 'Pi models-store.json must be a regular file, not a symbolic or hard link');
15
+ }
16
+ if (this.name === 'models-store.json' && stat.size > 16 * 1024 * 1024) {
17
+ throw new Error('Pi models-store.json exceeds the catalog size limit');
18
+ }
19
+ }
20
+ exists() {
21
+ try {
22
+ this.check(lstatSync(this.path));
23
+ return true;
24
+ }
25
+ catch (error) {
26
+ if (error.code === 'ENOENT')
27
+ return false;
28
+ throw error;
29
+ }
30
+ }
31
+ open(flags) {
32
+ this.exists();
33
+ const fd = openSync(this.path, flags | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
34
+ try {
35
+ this.check(fstatSync(fd));
36
+ }
37
+ catch (error) {
38
+ closeSync(fd);
39
+ throw error;
40
+ }
41
+ return fd;
42
+ }
43
+ readRaw() {
44
+ if (!this.exists())
45
+ return {};
46
+ const fd = this.open(constants.O_RDONLY);
47
+ try {
48
+ let raw;
49
+ try {
50
+ const content = readFileSync(fd, 'utf8').replace(/^\uFEFF/, '');
51
+ raw = this.name === 'models-store.json' && !content ? {} : JSON.parse(content);
52
+ }
53
+ catch {
54
+ throw new Error(`Invalid Pi ${this.name}: expected valid JSON`);
55
+ }
56
+ if (!object(raw))
57
+ throw new Error(`Invalid Pi ${this.name}: expected an object`);
58
+ return raw;
59
+ }
60
+ finally {
61
+ closeSync(fd);
62
+ }
63
+ }
64
+ writeRaw(raw) {
65
+ const create = this.name === 'models-store.json' && !this.exists();
66
+ const content = JSON.stringify(raw, null, 2);
67
+ if (this.name === 'models-store.json' && Buffer.byteLength(content) > 16 * 1024 * 1024) {
68
+ throw new Error('Pi models-store.json exceeds the catalog size limit');
69
+ }
70
+ const fd = this.open(constants.O_WRONLY | (create ? constants.O_CREAT | constants.O_EXCL : 0));
71
+ try {
72
+ ftruncateSync(fd, 0);
73
+ writeFileSync(fd, content, { encoding: 'utf8', mode: 0o600 });
74
+ }
75
+ finally {
76
+ closeSync(fd);
77
+ }
78
+ }
79
+ async locked(fn, signal, create = false) {
80
+ signal?.throwIfAborted();
81
+ if (!this.exists() && !create)
82
+ return fn({}, () => { });
83
+ const deadline = Date.now() + 30_000;
84
+ let compromised;
85
+ let release;
86
+ const assertLock = () => { if (compromised)
87
+ throw compromised; };
88
+ for (let attempt = 0; !release; attempt++) {
89
+ signal?.throwIfAborted();
90
+ try {
91
+ release = await lockfile.lock(this.path, {
92
+ realpath: false, stale: 30_000, retries: 0,
93
+ onCompromised: error => { compromised = error; },
94
+ });
95
+ }
96
+ catch (error) {
97
+ if (error.code !== 'ELOCKED' || Date.now() >= deadline)
98
+ throw error;
99
+ await sleep(Math.min(10 * 2 ** Math.min(attempt, 7), 1000, deadline - Date.now()), undefined, signal ? { signal } : {});
100
+ }
101
+ }
102
+ try {
103
+ assertLock();
104
+ signal?.throwIfAborted();
105
+ return await fn(this.readRaw(), assertLock);
106
+ }
107
+ finally {
108
+ try {
109
+ await release();
110
+ }
111
+ catch (error) {
112
+ if (!compromised)
113
+ throw error;
114
+ }
115
+ }
116
+ }
117
+ raw(signal) {
118
+ return this.locked(raw => raw, signal);
119
+ }
120
+ }
@@ -1,4 +1,5 @@
1
1
  import { compact } from "@earendil-works/pi-coding-agent";
2
+ import { findPiModel, piModelUnavailable } from "./model-selection.js";
2
3
  /** Keep Pi's preparation, split-turn handling, file tracking and usage accounting, changing only
3
4
  * the model for its summary calls. External extensions remain disabled in Flow's Backend Sessions. */
4
5
  export function compactionExtensionError(errors) {
@@ -8,9 +9,9 @@ export function compactionModelExtension(modelId, notice) {
8
9
  return { name: "flow-compaction-model", hidden: true, factory: (pi) => {
9
10
  pi.on("session_before_compact", async (event, ctx) => {
10
11
  try {
11
- const model = ctx.modelRegistry.getAvailable().find((candidate) => `${candidate.provider}/${candidate.id}` === modelId);
12
+ const model = findPiModel(ctx.modelRegistry.getAvailable(), modelId);
12
13
  if (!model)
13
- throw new Error(`Configured compaction model “${modelId}” is unavailable`);
14
+ throw new Error(piModelUnavailable(modelId, "Configured compaction model is unavailable"));
14
15
  const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
15
16
  if (!auth.ok)
16
17
  throw new Error(auth.error);