@nathanstephenson/flow 0.1.10-beta.1 → 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.
- package/README.md +52 -22
- package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
- package/build/backend-worker.mjs +69 -122
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +188 -25
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +118 -20
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +1 -1
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +42 -8
- package/dist/backend/worker/index.js +131 -15
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -7
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +940 -119
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +12 -9
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +400 -311
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +127 -11
- package/dist/workflows/recovery.js +38 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +367 -96
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-api-BfExddae.js +0 -6
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
- /package/dist/protocol/{publish.js → imports.js} +0 -0
|
@@ -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
|
|
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)
|
package/dist/backend/mcp.js
CHANGED
|
@@ -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 === "session_list" || tool === "session_inspect" || 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()
|
|
12
|
+
const model = findPiModel(ctx.modelRegistry.getAvailable(), modelId);
|
|
12
13
|
if (!model)
|
|
13
|
-
throw new Error(
|
|
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);
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { constants, closeSync, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { waitForAbort } from "../worker/rpc.js";
|
|
5
|
+
import { projectPi099RadiusCatalog, projectPiStoredRadiusCatalog, registerPiNativeProvider } from "./model-catalog.js";
|
|
6
|
+
import { parsePiModelConfig } from "./model-config.js";
|
|
7
|
+
import { PiCanonicalJson } from "./canonical-json.js";
|
|
8
|
+
function object(value) {
|
|
9
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
10
|
+
}
|
|
11
|
+
function oauth(value) {
|
|
12
|
+
return object(value) && value.type === "oauth" && typeof value.access === "string"
|
|
13
|
+
&& typeof value.refresh === "string" && typeof value.expires === "number" && Number.isFinite(value.expires);
|
|
14
|
+
}
|
|
15
|
+
function stringMap(value) {
|
|
16
|
+
return object(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
17
|
+
}
|
|
18
|
+
function radiusGateways(modelsPath) {
|
|
19
|
+
let fd;
|
|
20
|
+
try {
|
|
21
|
+
if (!lstatSync(modelsPath).isFile())
|
|
22
|
+
throw new Error();
|
|
23
|
+
fd = openSync(modelsPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
if (error.code === "ENOENT")
|
|
27
|
+
return new Map();
|
|
28
|
+
throw new Error("Pi models.json must be a readable regular file, not a symbolic link");
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
if (!fstatSync(fd).isFile())
|
|
32
|
+
throw new Error("Pi models.json must be a regular file");
|
|
33
|
+
let raw;
|
|
34
|
+
try {
|
|
35
|
+
raw = parsePiModelConfig(readFileSync(fd, "utf8"));
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
throw new Error("Invalid Pi models.json: expected valid JSON");
|
|
39
|
+
}
|
|
40
|
+
if (!object(raw))
|
|
41
|
+
throw new Error("Invalid Pi models.json: expected an object");
|
|
42
|
+
const gateways = new Map();
|
|
43
|
+
if (!object(raw.providers))
|
|
44
|
+
return gateways;
|
|
45
|
+
for (const [id, config] of Object.entries(raw.providers)) {
|
|
46
|
+
if (!object(config) || config.oauth !== "radius")
|
|
47
|
+
continue;
|
|
48
|
+
if (!id.trim() || typeof config.baseUrl !== "string")
|
|
49
|
+
throw new Error("Invalid Pi models.json: native Radius requires a gateway URL");
|
|
50
|
+
const base = config.baseUrl.replace(/\/v1\/?$/u, "");
|
|
51
|
+
const gateway = (/^https?:\/\//iu.test(base) ? base : `https://${base}`).replace(/\/+$/u, "");
|
|
52
|
+
try {
|
|
53
|
+
const url = new URL(gateway);
|
|
54
|
+
if ((!/^https?:\/\//iu.test(base) && base.includes('://'))
|
|
55
|
+
|| !['https:', 'http:'].includes(url.protocol) || !url.hostname || url.username || url.password || url.search || url.hash
|
|
56
|
+
|| /[\s\\!${}\u0000-\u001f\u007f]/u.test(gateway))
|
|
57
|
+
throw new Error();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
throw new Error("Invalid Pi models.json: native Radius requires a safe gateway URL");
|
|
61
|
+
}
|
|
62
|
+
gateways.set(id, gateway);
|
|
63
|
+
}
|
|
64
|
+
return gateways;
|
|
65
|
+
}
|
|
66
|
+
finally {
|
|
67
|
+
closeSync(fd);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
function metadata(raw, gateways = new Map()) {
|
|
71
|
+
const entries = Object.entries(raw).flatMap(([providerId, credential]) => {
|
|
72
|
+
if (!object(credential))
|
|
73
|
+
return [];
|
|
74
|
+
if (oauth(credential)) {
|
|
75
|
+
const ids = credential.availableModelIds;
|
|
76
|
+
const cachedModels = projectPi099RadiusCatalog(providerId, credential.gatewayConfig);
|
|
77
|
+
return [{ providerId, check: { type: "oauth", source: "OAuth" },
|
|
78
|
+
...(Array.isArray(ids) && ids.every((id) => typeof id === "string") ? { availableModelIds: [...ids] } : {}),
|
|
79
|
+
...(cachedModels ? { cachedModels } : {}), }];
|
|
80
|
+
}
|
|
81
|
+
if (credential.type === "api_key" && (credential.key === undefined || typeof credential.key === "string")
|
|
82
|
+
&& (credential.env === undefined || stringMap(credential.env))) {
|
|
83
|
+
return [{ providerId, check: { type: "api_key", source: "stored credential" } }];
|
|
84
|
+
}
|
|
85
|
+
return [];
|
|
86
|
+
});
|
|
87
|
+
for (const [providerId, radiusGateway] of gateways) {
|
|
88
|
+
if (providerId === "radius" && radiusGateway === "https://radius.pi.dev")
|
|
89
|
+
continue;
|
|
90
|
+
const entry = entries.find(entry => entry.providerId === providerId);
|
|
91
|
+
if (entry)
|
|
92
|
+
entry.radiusGateway = radiusGateway;
|
|
93
|
+
else
|
|
94
|
+
entries.push({ providerId, radiusGateway });
|
|
95
|
+
}
|
|
96
|
+
return entries;
|
|
97
|
+
}
|
|
98
|
+
class CanonicalCatalogs extends PiCanonicalJson {
|
|
99
|
+
constructor(path) { super(path, "models-store.json"); }
|
|
100
|
+
async importLegacy(providerId, models, signal) {
|
|
101
|
+
await this.locked((raw, assertLock) => {
|
|
102
|
+
if (Object.hasOwn(raw, providerId)) {
|
|
103
|
+
if (!object(raw[providerId]) || !Array.isArray(raw[providerId].models))
|
|
104
|
+
throw new Error("Invalid Pi models-store.json: expected a catalog");
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
assertLock();
|
|
108
|
+
this.writeRaw({ ...raw, [providerId]: { models, checkedAt: Date.now() } });
|
|
109
|
+
assertLock();
|
|
110
|
+
}, signal, true);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
class CanonicalCredentials extends PiCanonicalJson {
|
|
114
|
+
catalogs;
|
|
115
|
+
constructor(authPath, catalogs) { super(authPath, "auth.json"); this.catalogs = catalogs; }
|
|
116
|
+
async read(providerId, options) {
|
|
117
|
+
const raw = await this.raw(options?.signal);
|
|
118
|
+
const credential = Object.hasOwn(raw, providerId) ? raw[providerId] : undefined;
|
|
119
|
+
return oauth(credential) ? structuredClone(credential) : undefined;
|
|
120
|
+
}
|
|
121
|
+
async list(options) {
|
|
122
|
+
return metadata(await this.raw(options?.signal)).map(({ providerId, check }) => ({ providerId, type: check.type }));
|
|
123
|
+
}
|
|
124
|
+
async modify(providerId, fn, options) {
|
|
125
|
+
return this.locked(async (raw, assertLock) => {
|
|
126
|
+
const current = Object.hasOwn(raw, providerId) ? raw[providerId] : undefined;
|
|
127
|
+
if (!oauth(current))
|
|
128
|
+
return undefined;
|
|
129
|
+
const legacy = projectPi099RadiusCatalog(providerId, current.gatewayConfig);
|
|
130
|
+
if (legacy)
|
|
131
|
+
await this.catalogs.importLegacy(providerId, legacy, options?.signal);
|
|
132
|
+
assertLock();
|
|
133
|
+
const next = await fn(structuredClone(current));
|
|
134
|
+
assertLock();
|
|
135
|
+
options?.signal?.throwIfAborted();
|
|
136
|
+
if (next !== undefined) {
|
|
137
|
+
if (!oauth(next))
|
|
138
|
+
throw new Error("Pi host can only persist OAuth credentials");
|
|
139
|
+
raw[providerId] = next;
|
|
140
|
+
this.writeRaw(raw);
|
|
141
|
+
assertLock();
|
|
142
|
+
}
|
|
143
|
+
return next ?? current;
|
|
144
|
+
}, options?.signal);
|
|
145
|
+
}
|
|
146
|
+
async delete() {
|
|
147
|
+
throw new Error("Pi host credential deletion is not supported");
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
export function createPiModelAuth(options = {}) {
|
|
151
|
+
const path = options.authPath ?? join(process.env.PI_CODING_AGENT_DIR || join(homedir(), '.pi/agent'), 'auth.json');
|
|
152
|
+
const authPath = resolve(/^~[\\/\\\\]/.test(path) ? join(homedir(), path.slice(2)) : path);
|
|
153
|
+
const catalogs = new CanonicalCatalogs(join(dirname(authPath), "models-store.json"));
|
|
154
|
+
const store = new CanonicalCredentials(authPath, catalogs);
|
|
155
|
+
const modelsPath = join(dirname(authPath), "models.json");
|
|
156
|
+
const registeredGateways = new Map();
|
|
157
|
+
let runtime;
|
|
158
|
+
const pending = new Map();
|
|
159
|
+
const admitted = new Set();
|
|
160
|
+
let closing;
|
|
161
|
+
let closed = false;
|
|
162
|
+
function admit(operation) {
|
|
163
|
+
if (closed)
|
|
164
|
+
return Promise.reject(new Error("Pi model auth is closed"));
|
|
165
|
+
const result = Promise.resolve().then(operation);
|
|
166
|
+
admitted.add(result);
|
|
167
|
+
void result.then(() => admitted.delete(result), () => admitted.delete(result));
|
|
168
|
+
return result;
|
|
169
|
+
}
|
|
170
|
+
return {
|
|
171
|
+
close() {
|
|
172
|
+
closed = true;
|
|
173
|
+
closing ??= (async () => {
|
|
174
|
+
await Promise.allSettled([...admitted]);
|
|
175
|
+
await Promise.allSettled([...pending.values()]);
|
|
176
|
+
})();
|
|
177
|
+
return closing;
|
|
178
|
+
},
|
|
179
|
+
snapshot(signal) {
|
|
180
|
+
return admit(async () => {
|
|
181
|
+
const raw = await store.raw(signal);
|
|
182
|
+
signal?.throwIfAborted();
|
|
183
|
+
const entries = metadata(raw, radiusGateways(modelsPath));
|
|
184
|
+
const radius = entries.filter(entry => entry.check && (entry.providerId === "radius" || entry.radiusGateway !== undefined || entry.cachedModels !== undefined));
|
|
185
|
+
if (radius.length) {
|
|
186
|
+
const stored = await catalogs.raw(signal);
|
|
187
|
+
signal?.throwIfAborted();
|
|
188
|
+
for (const entry of radius) {
|
|
189
|
+
const models = projectPiStoredRadiusCatalog(entry.providerId, stored[entry.providerId]);
|
|
190
|
+
if (models)
|
|
191
|
+
entry.cachedModels = models;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
return entries;
|
|
195
|
+
});
|
|
196
|
+
},
|
|
197
|
+
resolve(providerId, signal) {
|
|
198
|
+
return admit(async () => {
|
|
199
|
+
signal?.throwIfAborted();
|
|
200
|
+
if (typeof providerId !== "string" || !providerId)
|
|
201
|
+
throw new Error("Unknown Pi provider");
|
|
202
|
+
const raw = await store.raw(signal);
|
|
203
|
+
signal?.throwIfAborted();
|
|
204
|
+
if (!metadata(raw).some((entry) => entry.providerId === providerId))
|
|
205
|
+
throw new Error("Unknown Pi provider");
|
|
206
|
+
const gateways = radiusGateways(modelsPath);
|
|
207
|
+
const credential = raw[providerId];
|
|
208
|
+
if (object(credential) && credential.type === "api_key") {
|
|
209
|
+
if (typeof credential.key === "string" && credential.key.startsWith("!")) {
|
|
210
|
+
throw new Error("Pi host refuses !command credentials in auth.json. Move the command to models.json so it runs only in the worker.");
|
|
211
|
+
}
|
|
212
|
+
return { auth: { ...(typeof credential.key === "string" ? { apiKey: credential.key } : {}) },
|
|
213
|
+
...(stringMap(credential.env) ? { env: { ...credential.env } } : {}), source: "stored credential" };
|
|
214
|
+
}
|
|
215
|
+
runtime ??= import('@earendil-works/pi-coding-agent').then(({ ModelRuntime }) => ModelRuntime.create({ credentials: store, modelsPath: null, refreshOnCreate: false }));
|
|
216
|
+
const current = await waitForAbort(runtime, signal);
|
|
217
|
+
signal?.throwIfAborted();
|
|
218
|
+
const gateway = gateways.get(providerId);
|
|
219
|
+
if (gateway !== undefined || (providerId === "radius" && registeredGateways.has(providerId))) {
|
|
220
|
+
const signature = gateway ?? "https://radius.pi.dev";
|
|
221
|
+
if (registeredGateways.get(providerId) !== signature) {
|
|
222
|
+
const { radiusProvider } = await import('@earendil-works/pi-ai/providers/all');
|
|
223
|
+
signal?.throwIfAborted();
|
|
224
|
+
if (registeredGateways.get(providerId) !== signature) {
|
|
225
|
+
registerPiNativeProvider(current, radiusProvider({ id: providerId, gateway: signature }));
|
|
226
|
+
registeredGateways.set(providerId, signature);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
else if (registeredGateways.has(providerId)) {
|
|
231
|
+
throw new Error(`Pi provider ${providerId} does not support native OAuth`);
|
|
232
|
+
}
|
|
233
|
+
const provider = current.getProvider(providerId);
|
|
234
|
+
if (!provider?.auth.oauth)
|
|
235
|
+
throw new Error(`Pi provider ${providerId} does not support native OAuth`);
|
|
236
|
+
delete provider.auth.apiKey;
|
|
237
|
+
let operation = pending.get(providerId);
|
|
238
|
+
if (!operation) {
|
|
239
|
+
operation = current.getAuth(providerId).then((result) => result ? {
|
|
240
|
+
auth: {
|
|
241
|
+
...(result.auth.apiKey !== undefined ? { apiKey: result.auth.apiKey } : {}),
|
|
242
|
+
...(result.auth.headers ? { headers: result.auth.headers } : {}),
|
|
243
|
+
...(result.auth.baseUrl !== undefined ? { baseUrl: result.auth.baseUrl } : {}),
|
|
244
|
+
},
|
|
245
|
+
...(result.env ? { env: result.env } : {}),
|
|
246
|
+
...(result.source !== undefined ? { source: result.source } : {}),
|
|
247
|
+
} : undefined);
|
|
248
|
+
pending.set(providerId, operation);
|
|
249
|
+
const owned = operation;
|
|
250
|
+
void operation.then(() => { if (pending.get(providerId) === owned)
|
|
251
|
+
pending.delete(providerId); }, () => { if (pending.get(providerId) === owned)
|
|
252
|
+
pending.delete(providerId); });
|
|
253
|
+
}
|
|
254
|
+
return waitForAbort(operation, signal);
|
|
255
|
+
});
|
|
256
|
+
},
|
|
257
|
+
};
|
|
258
|
+
}
|