@nathanstephenson/flow 0.1.10-beta.2 → 0.1.10-beta.4

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 (79) hide show
  1. package/README.md +27 -1
  2. package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
  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-GY27HBAY.mjs +35739 -0
  7. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-JV6MWPW7.mjs} +1901 -45
  8. package/build/backend-worker.mjs +52 -116
  9. package/dist/backend/claude/background-calls.js +7 -3
  10. package/dist/backend/claude/index.js +106 -16
  11. package/dist/backend/claude/subagents.js +41 -9
  12. package/dist/backend/fake/index.js +26 -5
  13. package/dist/backend/pi/cache-warming.js +8 -0
  14. package/dist/backend/pi/canonical-json.js +120 -0
  15. package/dist/backend/pi/compaction-model.js +3 -2
  16. package/dist/backend/pi/host-auth.js +258 -0
  17. package/dist/backend/pi/index.js +38 -12
  18. package/dist/backend/pi/model-auth.js +159 -0
  19. package/dist/backend/pi/model-catalog.js +120 -0
  20. package/dist/backend/pi/model-config.js +5 -0
  21. package/dist/backend/pi/model-selection.js +32 -0
  22. package/dist/backend/pi/subagents.js +7 -3
  23. package/dist/backend/pi/work.js +9 -1
  24. package/dist/backend/pi/workflow-subagent.js +4 -3
  25. package/dist/backend/worker/entry.js +32 -6
  26. package/dist/backend/worker/index.js +87 -7
  27. package/dist/backend/worker/rpc.js +13 -0
  28. package/dist/backend/worker/sandbox-mcp.js +18 -7
  29. package/dist/build-id +1 -1
  30. package/dist/cli/bootstrap.js +1 -1
  31. package/dist/client/reduce.js +11 -3
  32. package/dist/client/subagent-tree.js +49 -0
  33. package/dist/client/tool-summary.js +26 -15
  34. package/dist/daemon/git.js +10 -7
  35. package/dist/daemon/host.js +100 -22
  36. package/dist/daemon/models.js +2 -2
  37. package/dist/daemon/pi-model-cache.js +44 -0
  38. package/dist/daemon/runtime.js +63 -3
  39. package/dist/daemon/server.js +3 -0
  40. package/dist/daemon/store.js +2 -0
  41. package/dist/daemon/workflow-environment.js +191 -0
  42. package/dist/daemon/workflow-execution-launch.js +77 -0
  43. package/dist/daemon/workflow-execution-resources.js +76 -0
  44. package/dist/daemon/workflow-execution-values.js +128 -0
  45. package/dist/daemon/workflow-executions.js +272 -285
  46. package/dist/daemon/workflow-schedule-driver.js +247 -0
  47. package/dist/daemon/workflow-schedule-routes.js +137 -0
  48. package/dist/daemon/workflow-schedules.js +341 -0
  49. package/dist/isolation/filesystem.js +5 -1
  50. package/dist/isolation/sandbox.js +61 -18
  51. package/dist/isolation/shared-sandbox.js +3 -3
  52. package/dist/protocol/workflow-schedules.js +1 -0
  53. package/dist/tui/render.js +7 -1
  54. package/dist/workflows/calls.js +10 -7
  55. package/dist/workflows/errors.js +2 -0
  56. package/dist/workflows/executors.js +1 -1
  57. package/dist/workflows/invocations.js +8 -5
  58. package/dist/workflows/owner.js +45 -0
  59. package/dist/workflows/records.js +8 -2
  60. package/dist/workflows/schedule-errors.js +2 -0
  61. package/dist/workflows/schedule-store.js +385 -0
  62. package/dist/workflows/scheduler.js +29 -18
  63. package/dist/workflows/schedules.js +129 -0
  64. package/dist/workflows/store.js +110 -11
  65. package/package.json +8 -5
  66. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  67. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  68. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-bcNKV147.js} +1 -1
  69. package/web/dist/assets/settings-workflows-C_TKOhVa.js +23 -0
  70. package/web/dist/assets/workflows-DHG-CIo3.js +146 -0
  71. package/web/dist/assets/workflows-pane-9u_hJvgQ.js +1 -0
  72. package/web/dist/index.html +4 -3
  73. package/build/backend-worker-chunks/claude-COCNALN2.mjs +0 -30846
  74. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  75. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  76. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  77. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  78. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  79. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -323,12 +323,14 @@ export class FakeSession {
323
323
  *
324
324
  * `completeTurn` deliberately does not close an open Subagent: leaving one running is the
325
325
  * torn-Subagent fixture, and the Session Host is what has to cope with it.
326
+ *
327
+ * `producer` names the Subagent spawning this one, for a nested Subagent.
326
328
  */
327
- beginSubagent(name, description) {
329
+ beginSubagent(name, description, producer) {
328
330
  const subagentId = randomUUID();
329
- const subagent = new FakeSubagent(subagentId, name, description, this.emit);
331
+ const subagent = new FakeSubagent(subagentId, name, description, this.emit, this.modelId, this.effort, producer);
330
332
  this.subagents.push(subagent);
331
- this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description } });
333
+ this.emit({ type: "tool_started", callId: subagentId, name: "Agent", input: { name, description }, ...(producer ? { producer } : {}) });
332
334
  subagent.snapshot({ state: "running" });
333
335
  return subagent;
334
336
  }
@@ -390,16 +392,22 @@ export class FakeSubagent {
390
392
  subagentId;
391
393
  name;
392
394
  description;
395
+ model;
396
+ effort;
397
+ producer;
393
398
  finished = false;
394
399
  launched = false;
395
400
  emit;
396
401
  /** Bumped when a message finalises, so a partial and its finished half share one id. */
397
402
  messageIndex = 0;
398
- constructor(subagentId, name, description, emit) {
403
+ constructor(subagentId, name, description, emit, model, effort, producer) {
399
404
  this.subagentId = subagentId;
400
405
  this.name = name;
401
406
  this.description = description;
402
407
  this.emit = emit;
408
+ this.model = model;
409
+ this.effort = effort;
410
+ this.producer = producer;
403
411
  }
404
412
  /**
405
413
  * Attributed assistant text. The id is stable until the message finalises, because a partial and
@@ -417,6 +425,12 @@ export class FakeSubagent {
417
425
  if (final)
418
426
  this.messageIndex += 1;
419
427
  }
428
+ /** Instructions from the model that spawned it. */
429
+ instruct(text) {
430
+ const id = randomUUID();
431
+ this.emit({ type: "subagent_instruction", id, text, producer: { subagentId: this.subagentId } });
432
+ return id;
433
+ }
420
434
  /** An attributed tool call — the subagent's Read, not the parent's. */
421
435
  useTool(name, input, result, isError = false) {
422
436
  const callId = randomUUID();
@@ -449,6 +463,7 @@ export class FakeSubagent {
449
463
  callId: this.subagentId,
450
464
  result: `${this.name} launched in the background`,
451
465
  isError: false,
466
+ ...this.attribution(),
452
467
  });
453
468
  }
454
469
  finish(reason = "complete") {
@@ -461,7 +476,7 @@ export class FakeSubagent {
461
476
  // produces.
462
477
  if (this.launched)
463
478
  return;
464
- this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error" });
479
+ this.emit({ type: "tool_ended", callId: this.subagentId, result: `${this.name} finished`, isError: reason === "error", ...this.attribution() });
465
480
  }
466
481
  /** @internal — used by FakeSession to emit the opening snapshot. */
467
482
  snapshot(state) {
@@ -470,9 +485,15 @@ export class FakeSubagent {
470
485
  subagentId: this.subagentId,
471
486
  name: this.name,
472
487
  ...(this.description === undefined ? {} : { description: this.description }),
488
+ model: this.model,
489
+ ...(this.effort === undefined ? {} : { effort: this.effort }),
490
+ ...this.attribution(),
473
491
  ...state,
474
492
  });
475
493
  }
494
+ attribution() {
495
+ return this.producer ? { producer: this.producer } : {};
496
+ }
476
497
  }
477
498
  export class FakeBackend {
478
499
  name = "fake";
@@ -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);
@@ -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
+ }
@@ -9,8 +9,11 @@ import { USER_MESSAGE_MAP } from "./state.js";
9
9
  import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
10
10
  import { PiWorkflowSubagent } from "./workflow-subagent.js";
11
11
  import { piEffortLevels } from "./effort-capabilities.js";
12
+ import { findPiModel, piModelUnavailable } from "./model-selection.js";
12
13
  import { clampEffort } from "../effort.js";
13
14
  import { piAutoCompaction } from "./auto-compaction.js";
15
+ import { createWorkerPiModelRuntime } from "./model-auth.js";
16
+ import { streamingCacheWarming } from "./cache-warming.js";
14
17
  import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
15
18
  import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
16
19
  import { backgroundTools } from "./background-calls.js";
@@ -34,7 +37,7 @@ export class PiSession {
34
37
  this.unsubscribe();
35
38
  current.dispose();
36
39
  this.session = await this.recreate(current);
37
- this.unsubscribe = this.session.subscribe((event) => this.translate(event));
40
+ this.unsubscribe = this.bindSession();
38
41
  }
39
42
  standingAuthorisations;
40
43
  agentPermissions;
@@ -88,7 +91,17 @@ export class PiSession {
88
91
  if (enquiries)
89
92
  this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
90
93
  this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false, !this.workflowBuilder);
91
- this.unsubscribe = session.subscribe((event) => this.translate(event));
94
+ this.unsubscribe = this.bindSession();
95
+ }
96
+ bindSession() {
97
+ const stream = this.session.agent?.streamFunction;
98
+ if (stream)
99
+ this.session.agent.streamFunction = (...args) => {
100
+ if (this.disposed)
101
+ throw new Error("Backend Session stopped");
102
+ return stream(...args);
103
+ };
104
+ return this.session.subscribe((event) => this.translate(event));
92
105
  }
93
106
  startWorkflowSubagent(options) {
94
107
  if (this.disposed)
@@ -107,6 +120,8 @@ export class PiSession {
107
120
  return this.sessionDir;
108
121
  }
109
122
  async prompt(text, attachments, messageId) {
123
+ if (this.disposed)
124
+ return;
110
125
  if (messageId && this.sessionDir)
111
126
  this.unmappedMessageIds.push(messageId);
112
127
  this.turnId = `turn-${++this.messageSeq}`;
@@ -128,11 +143,9 @@ export class PiSession {
128
143
  async setPermissionMode(mode) { this.agentPermissions?.setMode(mode); }
129
144
  async setModel(modelId) {
130
145
  const available = await this.session.modelRuntime.getAvailable();
131
- const qualified = available.find((candidate) => describeModel(candidate).id === modelId);
132
- const legacy = available.filter((candidate) => candidate.id === modelId);
133
- const model = qualified ?? (legacy.length === 1 ? legacy[0] : undefined);
146
+ const model = findPiModel(available, modelId, true);
134
147
  if (!model)
135
- throw new Error(`Unknown model: ${modelId}`);
148
+ throw new Error(piModelUnavailable(modelId));
136
149
  await this.session.setModel(model);
137
150
  this.applyAutoCompaction?.(this.session.model);
138
151
  // Which levels are on offer follows the model, and pi may have clamped its own thinking level
@@ -353,7 +366,7 @@ export class PiSession {
353
366
  return;
354
367
  }
355
368
  case "agent_settled":
356
- this.finishTurn(this.aborting ? "aborted" : this.turnReason);
369
+ this.finishTurn(event.aborted || this.aborting ? "aborted" : this.turnReason);
357
370
  return;
358
371
  case "auto_retry_start":
359
372
  this.emit({
@@ -436,10 +449,16 @@ export class PiBackend {
436
449
  }
437
450
  async create(options) {
438
451
  const agentDir = getAgentDir();
452
+ const modelRuntime = options.piAuth
453
+ ? await createWorkerPiModelRuntime(options.piAuth, join(agentDir, "models.json"), options.signal, {
454
+ ...(options.stateDir ? { modelsStorePath: join(options.stateDir, 'models-store.json') } : {}),
455
+ discovery: options.refreshModels ? 'refresh' : 'automatic',
456
+ })
457
+ : undefined;
439
458
  // Extensions are not loaded: they expect pi's own UI surface, and a background session that
440
459
  // registers UI hooks has nowhere to render them.
441
460
  const builder = options.workflowBuilder;
442
- const settingsManager = builder ? SettingsManager.inMemory() : SettingsManager.create(options.scope, agentDir);
461
+ const settingsManager = builder ? SettingsManager.inMemory({ cacheWarming: "streaming" }) : SettingsManager.create(options.scope, agentDir);
443
462
  const agentPermissions = builder || options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
444
463
  const resourceLoader = new DefaultResourceLoader({
445
464
  cwd: options.scope,
@@ -453,6 +472,7 @@ export class PiBackend {
453
472
  systemPromptOverride: () => builder.instructions,
454
473
  } : {
455
474
  extensionFactories: [
475
+ streamingCacheWarming(settingsManager),
456
476
  ...(agentPermissions ? [agentPermissions.extension()] : []),
457
477
  ...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
458
478
  ],
@@ -494,6 +514,7 @@ export class PiBackend {
494
514
  agentDir,
495
515
  resourceLoader,
496
516
  settingsManager,
517
+ ...(modelRuntime ? { modelRuntime } : {}),
497
518
  customTools: [...customTools, ...mcpTools],
498
519
  tools: [...tools, ...mcpTools.map((tool) => tool.name)],
499
520
  ...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
@@ -517,9 +538,11 @@ export class PiBackend {
517
538
  }
518
539
  const autoCompaction = structuredClone(options.autoCompaction);
519
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) } : {}) });
520
- if (options.modelId) {
541
+ const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel()
542
+ ? `azure-openai-responses/${settingsManager.getDefaultModel()}` : undefined);
543
+ if (modelId) {
521
544
  try {
522
- await piSession.setModel(options.modelId);
545
+ await piSession.setModel(modelId);
523
546
  }
524
547
  catch (error) {
525
548
  await piSession.dispose();
@@ -556,15 +579,16 @@ export class PiBackend {
556
579
  }
557
580
  async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
558
581
  const available = parent.modelRuntime.getAvailableSnapshot();
559
- const model = input.model ? available.find((model) => describeModel(model).id === input.model) : parent.model;
582
+ const model = input.model ? findPiModel(available, input.model) : parent.model;
560
583
  if (!model)
561
- throw new Error(`Unknown model: ${input.model}. Available: ${available.map((model) => describeModel(model).id).join(", ")}`);
584
+ throw new Error(`${piModelUnavailable(input.model ?? "(inherited)")} Available: ${available.map((model) => describeModel(model).id).join(", ")}`);
562
585
  const effort = (input.effort ?? parent.thinkingLevel);
563
586
  const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_") && !name.startsWith("session_"));
564
587
  const settingsManager = SettingsManager.create(scope, agentDir);
565
588
  const producer = { subagentId: id };
566
589
  const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
567
590
  extensionFactories: [
591
+ streamingCacheWarming(settingsManager),
568
592
  ...(agentPermissions ? [agentPermissions.extension(producer)] : []),
569
593
  ...(compactionModelId ? [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] : []),
570
594
  ],
@@ -616,7 +640,9 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
616
640
  try {
617
641
  signal.throwIfAborted();
618
642
  await adapter.setEffort(effort);
643
+ work.refine(id, { model: describeModel(model).id, effort: child.thinkingLevel });
619
644
  signal.throwIfAborted();
645
+ emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
620
646
  await adapter.prompt(input.prompt);
621
647
  if (reason !== "complete")
622
648
  throw new Error(failure ?? `Subagent ${reason}`);