@nathanstephenson/flow 0.1.10-beta.3 → 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 (44) hide show
  1. package/README.md +9 -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-QNU2YE4G.mjs → pi-JV6MWPW7.mjs} +1891 -35
  8. package/build/backend-worker.mjs +25 -126
  9. package/dist/backend/claude/index.js +69 -11
  10. package/dist/backend/claude/subagents.js +11 -0
  11. package/dist/backend/fake/index.js +8 -2
  12. package/dist/backend/pi/cache-warming.js +8 -0
  13. package/dist/backend/pi/canonical-json.js +120 -0
  14. package/dist/backend/pi/compaction-model.js +3 -2
  15. package/dist/backend/pi/host-auth.js +258 -0
  16. package/dist/backend/pi/index.js +37 -12
  17. package/dist/backend/pi/model-auth.js +159 -0
  18. package/dist/backend/pi/model-catalog.js +120 -0
  19. package/dist/backend/pi/model-config.js +5 -0
  20. package/dist/backend/pi/model-selection.js +32 -0
  21. package/dist/backend/pi/work.js +9 -1
  22. package/dist/backend/pi/workflow-subagent.js +4 -3
  23. package/dist/backend/worker/entry.js +13 -1
  24. package/dist/backend/worker/index.js +66 -5
  25. package/dist/build-id +1 -1
  26. package/dist/cli/bootstrap.js +1 -1
  27. package/dist/client/reduce.js +2 -0
  28. package/dist/client/tool-summary.js +26 -15
  29. package/dist/daemon/host.js +13 -2
  30. package/dist/daemon/models.js +2 -2
  31. package/dist/daemon/pi-model-cache.js +44 -0
  32. package/dist/isolation/filesystem.js +5 -1
  33. package/dist/isolation/sandbox.js +31 -4
  34. package/package.json +7 -5
  35. package/web/dist/assets/index-BWKZK5HD.css +2 -0
  36. package/web/dist/assets/index-nIc09tKZ.js +40 -0
  37. package/web/dist/assets/{settings-mcp-Vf_fCXyE.js → settings-mcp-bcNKV147.js} +1 -1
  38. package/web/dist/assets/{settings-workflows-DVKxJWQm.js → settings-workflows-C_TKOhVa.js} +2 -2
  39. package/web/dist/assets/{workflows-Dobqzjg-.js → workflows-DHG-CIo3.js} +36 -36
  40. package/web/dist/assets/{workflows-pane-KB-Q76KZ.js → workflows-pane-9u_hJvgQ.js} +1 -1
  41. package/web/dist/index.html +3 -3
  42. package/build/backend-worker-chunks/claude-6L5KCQWJ.mjs +0 -30894
  43. package/web/dist/assets/index-BGu3YSP7.css +0 -2
  44. package/web/dist/assets/index-Miy2nveb.js +0 -40
@@ -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,6 +640,7 @@ 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();
620
645
  emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
621
646
  await adapter.prompt(input.prompt);
@@ -0,0 +1,159 @@
1
+ import { registerPiNativeProvider, unregisterPiNativeProvider, withPi099RadiusCatalog } from "./model-catalog.js";
2
+ export { createPiModelAuth } from "./host-auth.js";
3
+ const emptyCredentials = {
4
+ async read(_providerId, options) { options?.signal?.throwIfAborted(); return undefined; },
5
+ async list(options) { options?.signal?.throwIfAborted(); return []; },
6
+ async modify() { throw new Error('Worker Pi credentials are read-only'); },
7
+ async delete() { throw new Error('Worker Pi credentials are read-only'); },
8
+ };
9
+ export async function createWorkerPiModelRuntime(auth, modelsPath, signal, options = {}) {
10
+ let metadata = new Map((await auth.snapshot(signal)).map(entry => [entry.providerId, entry]));
11
+ const storedKey = Symbol('host credential metadata');
12
+ const credentials = {
13
+ ...emptyCredentials,
14
+ async read(id, options) {
15
+ options?.signal?.throwIfAborted();
16
+ const entry = metadata.get(id);
17
+ if (entry?.check?.type === 'api_key')
18
+ return { type: 'api_key', [storedKey]: true };
19
+ if (entry?.check?.type === 'oauth')
20
+ return {
21
+ type: 'oauth', access: '', refresh: '', expires: Number.MAX_SAFE_INTEGER,
22
+ ...(entry.availableModelIds ? { availableModelIds: [...entry.availableModelIds] } : {}),
23
+ };
24
+ return undefined;
25
+ },
26
+ };
27
+ const { ModelRuntime } = await import('@earendil-works/pi-coding-agent');
28
+ const { radiusProvider } = await import('@earendil-works/pi-ai/providers/all');
29
+ const catalog = await ModelRuntime.create({ credentials: emptyCredentials, modelsPath: null, refreshOnCreate: false });
30
+ const runtime = await ModelRuntime.create({ credentials, modelsPath,
31
+ ...(options.modelsStorePath ? { modelsStorePath: options.modelsStorePath } : {}),
32
+ refreshOnCreate: false, ...(signal ? { signal } : {}) });
33
+ const refresh = runtime.refresh.bind(runtime);
34
+ const builtins = new Map(catalog.getProviders().map(provider => [provider.id, provider]));
35
+ const registered = new Set();
36
+ const registeredGateways = new Map();
37
+ const expandKey = async (key, env, signal) => {
38
+ if (!key?.includes('$'))
39
+ return key;
40
+ const resolver = await ModelRuntime.create({ credentials: emptyCredentials, modelsPath: null, refreshOnCreate: false, signal });
41
+ const refresh = resolver.refresh;
42
+ resolver.refresh = async () => ({ aborted: false, errors: new Map() });
43
+ try {
44
+ resolver.registerProvider('worker-key-template', { apiKey: key });
45
+ }
46
+ finally {
47
+ resolver.refresh = refresh;
48
+ }
49
+ return (await resolver.getAuth('worker-key-template', { ...(env ? { env } : {}), signal }))?.auth.apiKey;
50
+ };
51
+ const genericApiKey = {
52
+ name: 'API key',
53
+ async resolve({ credential }) {
54
+ return credential?.key ? { auth: { apiKey: credential.key }, ...(credential.env ? { env: credential.env } : {}) } : undefined;
55
+ },
56
+ };
57
+ const brokered = (provider, catalogAuth = provider.id === 'radius') => {
58
+ const id = provider.id;
59
+ const apiKey = provider.auth.apiKey ?? genericApiKey;
60
+ const oauth = provider.auth.oauth;
61
+ return {
62
+ ...provider,
63
+ auth: {
64
+ ...(apiKey ? { apiKey: {
65
+ ...apiKey,
66
+ async check(input) {
67
+ input.signal.throwIfAborted();
68
+ if (input.credential?.[storedKey])
69
+ return metadata.get(id)?.check;
70
+ if (apiKey.check)
71
+ return apiKey.check(input);
72
+ const result = await apiKey.resolve(input);
73
+ return result ? { type: 'api_key', ...(result.source !== undefined ? { source: result.source } : {}) } : undefined;
74
+ },
75
+ async resolve(input) {
76
+ if (!input.credential?.[storedKey])
77
+ return apiKey.resolve(input);
78
+ const result = await auth.resolve(id, input.signal);
79
+ if (!result)
80
+ return undefined;
81
+ const env = { ...result.env, ...input.credential?.env };
82
+ const key = await expandKey(result.auth.apiKey, env, input.signal);
83
+ return apiKey.resolve({ ...input, credential: { type: 'api_key', ...(key !== undefined ? { key } : {}), env },
84
+ ctx: { ...input.ctx, env: async (name) => env[name] ?? input.ctx.env(name) } });
85
+ },
86
+ } } : {}),
87
+ ...(oauth ? { oauth: {
88
+ ...oauth,
89
+ async toAuth() {
90
+ const result = await auth.resolve(id);
91
+ if (!result)
92
+ throw new Error('Session Host auth is unavailable');
93
+ return result.auth;
94
+ },
95
+ } } : {}),
96
+ },
97
+ ...(provider.refreshModels ? { async refreshModels(context) {
98
+ if (catalogAuth && context.allowNetwork && context.credential?.type === 'oauth') {
99
+ const result = await auth.resolve(id, context.signal);
100
+ if (!result)
101
+ return;
102
+ return provider.refreshModels({ ...context, credential: {
103
+ ...context.credential, access: result.auth.apiKey ?? '', refresh: '',
104
+ } });
105
+ }
106
+ return provider.refreshModels(context);
107
+ } } : {}),
108
+ };
109
+ };
110
+ const registerProviders = () => {
111
+ if (!metadata.has('radius') && registered.delete('radius')) {
112
+ unregisterPiNativeProvider(runtime, 'radius');
113
+ registeredGateways.delete('radius');
114
+ }
115
+ const gateways = new Map([...metadata.values()].flatMap(entry => entry.radiusGateway !== undefined
116
+ ? [[entry.providerId, entry.radiusGateway]] : []));
117
+ const baseUrl = runtime.getProvider('radius')?.baseUrl;
118
+ if (metadata.has('radius') && !gateways.has('radius') && (!baseUrl || /^https:\/\/radius\.pi\.dev(?:\/v1)?\/?$/u.test(baseUrl)
119
+ || registeredGateways.has('radius')))
120
+ gateways.set('radius', '');
121
+ for (const [id, gateway] of gateways) {
122
+ if (registeredGateways.get(id) === gateway)
123
+ continue;
124
+ const provider = radiusProvider({ id, ...(gateway ? { gateway } : {}) });
125
+ registerPiNativeProvider(runtime, brokered(withPi099RadiusCatalog(provider, () => metadata.get(id)?.cachedModels), true));
126
+ registeredGateways.set(id, gateway);
127
+ registered.add(id);
128
+ }
129
+ for (const entry of metadata.values()) {
130
+ const id = entry.providerId;
131
+ if (registered.has(id))
132
+ continue;
133
+ const provider = builtins.get(id) ?? {
134
+ id, name: id, getModels: () => [],
135
+ auth: { apiKey: genericApiKey },
136
+ stream() { throw new Error('Provider requires configured models and API'); },
137
+ streamSimple() { throw new Error('Provider requires configured models and API'); },
138
+ };
139
+ registerPiNativeProvider(runtime, brokered(provider));
140
+ registered.add(id);
141
+ }
142
+ };
143
+ registerProviders();
144
+ runtime.refresh = async (options = {}) => {
145
+ metadata = new Map((await auth.snapshot(options.signal)).map(entry => [entry.providerId, entry]));
146
+ registerProviders();
147
+ return refresh(options);
148
+ };
149
+ await refresh({ allowNetwork: false, ...(signal ? { signal } : {}) });
150
+ if (options.discovery && process.env['PI_OFFLINE'] === undefined) {
151
+ const force = options.discovery === 'refresh';
152
+ const providers = runtime.getProviders().filter(provider => runtime.hasConfiguredAuth(provider.id)
153
+ && (force || (builtins.has(provider.id) && provider.id !== 'radius' && !registeredGateways.has(provider.id))))
154
+ .map(provider => provider.id);
155
+ const timeout = AbortSignal.timeout(5_000);
156
+ await runtime.refresh({ allowNetwork: true, force, providers, signal: signal ? AbortSignal.any([signal, timeout]) : timeout });
157
+ }
158
+ return runtime;
159
+ }