@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
@@ -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
+ }
@@ -0,0 +1,120 @@
1
+ export function registerPiNativeProvider(runtime, provider) {
2
+ const refresh = runtime.refresh;
3
+ runtime.refresh = async () => ({ aborted: false, errors: new Map() });
4
+ try {
5
+ runtime.registerNativeProvider(provider);
6
+ }
7
+ finally {
8
+ runtime.refresh = refresh;
9
+ }
10
+ }
11
+ export function unregisterPiNativeProvider(runtime, providerId) {
12
+ const refresh = runtime.refresh;
13
+ runtime.refresh = async () => ({ aborted: false, errors: new Map() });
14
+ try {
15
+ runtime.unregisterProvider(providerId);
16
+ }
17
+ finally {
18
+ runtime.refresh = refresh;
19
+ }
20
+ }
21
+ function object(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+ function finite(value) {
25
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
26
+ }
27
+ function rates(value) {
28
+ if (!object(value) || !finite(value.input) || !finite(value.output) || !finite(value.cacheRead) || !finite(value.cacheWrite))
29
+ return undefined;
30
+ return { input: value.input, output: value.output, cacheRead: value.cacheRead, cacheWrite: value.cacheWrite };
31
+ }
32
+ export function projectPi099RadiusCatalog(providerId, value) {
33
+ if (!object(value) || typeof value.baseUrl !== 'string' || !Array.isArray(value.models))
34
+ return undefined;
35
+ try {
36
+ const url = new URL(value.baseUrl);
37
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
38
+ return undefined;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ const baseUrl = value.baseUrl;
44
+ return value.models.flatMap(model => {
45
+ if (!object(model) || typeof model.id !== 'string' || typeof model.name !== 'string' || typeof model.reasoning !== 'boolean'
46
+ || !Array.isArray(model.input) || !model.input.every(input => input === 'text' || input === 'image')
47
+ || !finite(model.contextWindow) || !finite(model.maxTokens))
48
+ return [];
49
+ const cost = rates(model.cost);
50
+ if (!cost)
51
+ return [];
52
+ if (object(model.cost) && Array.isArray(model.cost.tiers)) {
53
+ cost.tiers = model.cost.tiers.flatMap(tier => {
54
+ const tierRates = rates(tier);
55
+ return object(tier) && finite(tier.inputTokensAbove) && tierRates ? [{ ...tierRates, inputTokensAbove: tier.inputTokensAbove }] : [];
56
+ });
57
+ }
58
+ const projected = { id: model.id, name: model.name, api: 'pi-messages', provider: providerId, baseUrl,
59
+ reasoning: model.reasoning, input: [...model.input], cost, contextWindow: model.contextWindow, maxTokens: model.maxTokens };
60
+ if (object(model.thinkingLevelMap)) {
61
+ projected.thinkingLevelMap = {};
62
+ for (const level of ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']) {
63
+ const value = model.thinkingLevelMap[level];
64
+ if (value === null || typeof value === 'string')
65
+ projected.thinkingLevelMap[level] = value;
66
+ }
67
+ }
68
+ if (object(model.promptCache)) {
69
+ projected.promptCache = {};
70
+ for (const tier of ['short', 'long'])
71
+ if (finite(model.promptCache[tier]))
72
+ projected.promptCache[tier] = model.promptCache[tier];
73
+ }
74
+ if (object(model.inputLimits)) {
75
+ const limits = model.inputLimits;
76
+ projected.inputLimits = {};
77
+ if (finite(limits.maxRequestBytes))
78
+ projected.inputLimits.maxRequestBytes = limits.maxRequestBytes;
79
+ if (object(limits.images)) {
80
+ projected.inputLimits.images = {};
81
+ for (const key of ['maxPerMessage', 'maxPerRequest']) {
82
+ if (finite(limits.images[key]))
83
+ projected.inputLimits.images[key] = limits.images[key];
84
+ }
85
+ if (object(limits.images.resize)) {
86
+ projected.inputLimits.images.resize = {};
87
+ for (const key of ['maxWidth', 'maxHeight', 'maxBytes', 'jpegQuality']) {
88
+ if (finite(limits.images.resize[key]))
89
+ projected.inputLimits.images.resize[key] = limits.images.resize[key];
90
+ }
91
+ }
92
+ }
93
+ }
94
+ return [projected];
95
+ });
96
+ }
97
+ export function projectPiStoredRadiusCatalog(providerId, value) {
98
+ if (!object(value) || !Array.isArray(value.models))
99
+ return undefined;
100
+ return value.models.flatMap(model => {
101
+ if (!object(model) || model.provider !== providerId || model.api !== 'pi-messages')
102
+ return [];
103
+ return projectPi099RadiusCatalog(providerId, { baseUrl: model.baseUrl, models: [model] }) ?? [];
104
+ });
105
+ }
106
+ export function withPi099RadiusCatalog(provider, cached) {
107
+ return {
108
+ ...provider,
109
+ async refreshModels(context) {
110
+ const legacy = context.stored ? undefined : cached();
111
+ if (legacy) {
112
+ const stored = { models: [...legacy], checkedAt: Date.now() };
113
+ if (!await context.publish({ persist: stored }))
114
+ return;
115
+ context = { ...context, stored };
116
+ }
117
+ await provider.refreshModels?.(context);
118
+ },
119
+ };
120
+ }
@@ -0,0 +1,5 @@
1
+ export function parsePiModelConfig(content) {
2
+ return JSON.parse(content.replace(/^\uFEFF/, "")
3
+ .replace(/"(?:\\.|[^"\\])*"|\/\/[^\n]*/g, (match) => match.startsWith('"') ? match : "")
4
+ .replace(/"(?:\\.|[^"\\])*"|,(\s*[}\]])/g, (match, closing) => closing ?? match));
5
+ }
@@ -0,0 +1,32 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
4
+ import { parsePiModelConfig } from "./model-config.js";
5
+ const legacyAzure = "azure-openai-responses";
6
+ export function findPiModel(available, modelId, allowBareId = false, agentDir = getAgentDir()) {
7
+ const canonicalId = modelId.startsWith(`${legacyAzure}/`) ? `azure/${modelId.slice(legacyAzure.length + 1)}` : modelId;
8
+ if (canonicalId.startsWith("azure/")) {
9
+ for (const name of ["auth.json", "models.json"]) {
10
+ const path = join(agentDir, name);
11
+ if (!existsSync(path))
12
+ continue;
13
+ const content = readFileSync(path, "utf8");
14
+ const data = name === "models.json" ? parsePiModelConfig(content) : JSON.parse(content.replace(/^\uFEFF/, ""));
15
+ const providers = name === "models.json" ? data.providers : data;
16
+ if (providers && Object.hasOwn(providers, legacyAzure) && !Object.hasOwn(providers, "azure")) {
17
+ throw new Error(`Pi 1.6 renamed Provider ${legacyAzure} to azure. Rename its Provider key in ${path} to azure; keep the API name azure-openai-responses unchanged. Flow did not change this file or select another model.`);
18
+ }
19
+ }
20
+ }
21
+ const qualified = available.find((model) => (model.provider ? `${model.provider}/${model.id}` : model.id) === canonicalId);
22
+ if (qualified || !allowBareId || canonicalId.startsWith("azure/"))
23
+ return qualified;
24
+ const bare = available.filter((model) => model.id === modelId);
25
+ return bare.length === 1 ? bare[0] : undefined;
26
+ }
27
+ export function piModelUnavailable(modelId, label = "Unknown model") {
28
+ const azure = modelId.startsWith(`${legacyAzure}/`) || modelId.startsWith("azure/");
29
+ return `${label}: ${modelId}. Select an available model explicitly; no replacement was used.${azure
30
+ ? " Pi 1.6 uses Provider azure. Check the azure Provider keys in Pi auth.json and models.json, and confirm the exact model ID is still available. The API name remains azure-openai-responses."
31
+ : ""}`;
32
+ }
@@ -1,6 +1,7 @@
1
1
  import { defineTool } from "@earendil-works/pi-coding-agent";
2
2
  import { Type } from "typebox";
3
3
  import { EFFORT_ORDER } from "../effort.js";
4
+ import { callIdFor } from "./work.js";
4
5
  export const SUBAGENT_TOOL = "subagent";
5
6
  const parameters = Type.Object({
6
7
  description: Type.String({ minLength: 1, description: "Short description of the delegated work" }),
@@ -10,14 +11,17 @@ const parameters = Type.Object({
10
11
  effort: Type.Optional(Type.String({ enum: EFFORT_ORDER, description: "Defaults to the parent's Effort at launch" })),
11
12
  run_in_background: Type.Optional(Type.Boolean({ description: "Defaults to true. Set false only when your next action requires the result." })),
12
13
  });
13
- export function subagentTool(work, run) {
14
+ export function subagentTool(work, run, producer) {
14
15
  return defineTool({
15
16
  name: SUBAGENT_TOOL,
16
17
  label: "Subagent",
17
18
  description: "Delegate work to a Subagent with its own Conversation Context. Subagents run in the background by default and report back automatically. Multiple Subagents may run concurrently. They cannot ask the human or create further Subagents.",
18
19
  promptSnippet: "Delegate independent work to Subagents",
19
20
  parameters,
20
- execute: async (id, input, signal) => work.run({ type: "subagent", subagentId: id,
21
- name: input.name ?? "Subagent", description: input.description }, (childSignal) => run(id, input, childSignal), input.run_in_background !== false, signal),
21
+ execute: async (id, input, signal) => {
22
+ const subagentId = callIdFor(id, producer);
23
+ return work.run({ type: "subagent", subagentId, name: input.name ?? "Subagent", description: input.description,
24
+ ...(producer ? { producer } : {}) }, (childSignal) => run(subagentId, input, childSignal), input.run_in_background !== false, signal);
25
+ },
22
26
  });
23
27
  }
@@ -38,7 +38,7 @@ export class PiWork {
38
38
  work.result = completion.result;
39
39
  if (brief.type === "subagent")
40
40
  this.jobs.delete(id);
41
- this.emit({ ...brief, state: completion.state });
41
+ this.emit({ ...work.brief, state: completion.state });
42
42
  if (background && !this.disposed)
43
43
  this.completed(completion);
44
44
  return completion;
@@ -53,6 +53,14 @@ export class PiWork {
53
53
  throw new Error(resultText(completion.result));
54
54
  return completion.result;
55
55
  }
56
+ /** Record the model and Effort a running Subagent resolved to. */
57
+ refine(id, patch) {
58
+ const work = this.jobs.get(id);
59
+ if (!work || work.brief.type !== "subagent")
60
+ return;
61
+ work.brief = { ...work.brief, ...patch };
62
+ this.emit({ ...work.brief, state: "running" });
63
+ }
56
64
  waiting(id, waiting) {
57
65
  const work = this.jobs.get(id);
58
66
  if (!work || work.brief.type !== "subagent" || !["running", "waiting"].includes(work.state))
@@ -2,6 +2,7 @@ import { piMcpTools } from "./mcp.js";
2
2
  import { createAgentSession, DefaultPackageManager, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, createReadToolDefinition, createEditToolDefinition, createWriteToolDefinition, createGrepToolDefinition, createFindToolDefinition, createLsToolDefinition, createPowerShellToolDefinition, } from "@earendil-works/pi-coding-agent";
3
3
  import { PiSession } from "./index.js";
4
4
  import { piAcceptsWorkflowEffort, piEffortLevels } from "./effort-capabilities.js";
5
+ import { findPiModel, piModelUnavailable } from "./model-selection.js";
5
6
  import { piAutoCompaction } from "./auto-compaction.js";
6
7
  import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
7
8
  import { PiEnquiries } from "./enquiries.js";
@@ -83,13 +84,13 @@ export class PiWorkflowSubagent {
83
84
  let compacting = false;
84
85
  try {
85
86
  controller.signal.throwIfAborted();
86
- const model = parent.modelRuntime.getAvailableSnapshot().find((model) => `${model.provider}/${model.id}` === options.modelId);
87
+ const model = findPiModel(parent.modelRuntime.getAvailableSnapshot(), options.modelId);
87
88
  if (!model)
88
- throw new Error(`Unknown workflow model: ${options.modelId}`);
89
+ throw new Error(piModelUnavailable(options.modelId, "Unknown workflow model"));
89
90
  if (!["ask", "auto-accept"].includes(options.permissionMode))
90
91
  throw new Error("Unsupported workflow permission mode");
91
92
  const scope = parent.sessionManager.getCwd();
92
- const settingsManager = SettingsManager.inMemory({ retry: { enabled: false } });
93
+ const settingsManager = SettingsManager.inMemory({ retry: { enabled: false }, cacheWarming: "streaming" });
93
94
  const skillContext = options.skill
94
95
  ? `The leading Skill invocation is expanded as the user prompt. Follow it together with the mapped workflow input below.\n\nMapped workflow input (JSON):\n${JSON.stringify(options.input)}\n\nWorkflow constraints:${options.instructions.slice(options.skill.invocation.length)}`
95
96
  : options.instructions;
@@ -7,7 +7,7 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  return path;
8
8
  };
9
9
  import { McpSession } from "../mcp.js";
10
- import { WorkerRpc, errorText } from "./rpc.js";
10
+ import { WorkerRpc, errorText, waitForAbort } from "./rpc.js";
11
11
  import { snapshot } from "./protocol.js";
12
12
  import { killWorkerTree } from "./launcher.js";
13
13
  import { encodeFrame, frameDecoder } from "./frames.js";
@@ -43,12 +43,22 @@ export function runWorker() {
43
43
  void stop(); });
44
44
  };
45
45
  const rpc = new WorkerRpc(send, async (method, args, signal) => {
46
+ if (method === "mcp.initialize") {
47
+ signal.throwIfAborted();
48
+ if (creating || closing)
49
+ throw new Error('Worker already initialized');
50
+ creating = true;
51
+ const options = args[0];
52
+ localMcp = new McpSession(options.connections, options.scope, undefined, true, undefined, undefined, undefined, 'none', undefined, (connectionId, refresh) => rpc.call('mcp.token', [connectionId, refresh]));
53
+ localMcp.connectTimeoutMs = 120_000;
54
+ return;
55
+ }
46
56
  if (method === "create") {
47
57
  const ready = performance.now();
48
58
  if (creating || closing)
49
59
  throw new Error("Backend worker already initialized");
50
60
  creating = true;
51
- const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, sessionToolsEnabled, workflowBuilderInstructions, backendModule, backend: backendName = "pi", ...options } = args[0];
61
+ const { mcpTools, mcpConnectionIds, mcpSandbox, workflowEnabled, sessionToolsEnabled, workflowBuilderInstructions, piAuth, backendModule, backend: backendName = "pi", ...options } = args[0];
52
62
  const workflowBuilder = workflowBuilderInstructions === undefined ? undefined : {
53
63
  instructions: workflowBuilderInstructions,
54
64
  read: (path) => rpc.call("workflowBuilder.read", [path]),
@@ -89,8 +99,20 @@ export function runWorker() {
89
99
  throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
90
100
  }
91
101
  const imported = performance.now();
102
+ let initialAuth = piAuth;
92
103
  session = await backend.create({
93
104
  ...options,
105
+ ...(piAuth ? { piAuth: {
106
+ snapshot: async (signal) => {
107
+ signal?.throwIfAborted();
108
+ if (!initialAuth)
109
+ return rpc.call('pi.auth.snapshot', [], signal);
110
+ const metadata = initialAuth;
111
+ initialAuth = undefined;
112
+ return metadata;
113
+ },
114
+ resolve: (providerId, signal) => rpc.call('pi.auth.resolve', [providerId], signal),
115
+ } } : {}),
94
116
  ...(workflowBuilder ? { workflowBuilder } : {
95
117
  ...(localMcp ? { mcp: localMcp }
96
118
  : mcpTools ? { mcp: { connections: (mcpConnectionIds ?? []).map((id) => ({ id })), tools: () => tools } } : {}),
@@ -116,8 +138,8 @@ export function runWorker() {
116
138
  setImmediate(() => process.stdout.end(() => process.exit(0)));
117
139
  return;
118
140
  }
119
- if (!session || closing)
120
- throw new Error("Backend worker is not running");
141
+ if (closing || (!session && (!localMcp || !method.startsWith('mcp.'))))
142
+ throw new Error("Worker is not running");
121
143
  let result;
122
144
  switch (method) {
123
145
  case "prompt":
@@ -181,14 +203,17 @@ export function runWorker() {
181
203
  case "mcp.direct": {
182
204
  if (!localMcp)
183
205
  throw new Error("No sandbox MCP clients");
206
+ signal.throwIfAborted();
184
207
  const id = args[0];
185
208
  if (localMcp.status().find((state) => state.id === id)?.state !== "connected")
186
- await localMcp.retry(id).catch(() => { });
209
+ await waitForAbort(localMcp.retry(id).catch(() => { }), signal);
210
+ signal.throwIfAborted();
187
211
  result = { status: localMcp.status().find((state) => state.id === id) ?? { id, state: "failed", tools: 0 },
188
212
  tools: localMcp.tools().filter((tool) => tool.connectionId === id).map(({ call: _, ...tool }) => tool) };
189
213
  break;
190
214
  }
191
215
  case "mcp.callTool": {
216
+ signal.throwIfAborted();
192
217
  const tool = localMcp?.tools().find((entry) => entry.name === args[0]);
193
218
  if (!tool)
194
219
  throw new Error("Unknown MCP tool");
@@ -217,7 +242,8 @@ export function runWorker() {
217
242
  break;
218
243
  default: throw new Error(`Unknown worker method: ${method}`);
219
244
  }
220
- rpc.notify("snapshot", publishSnapshot());
245
+ if (session)
246
+ rpc.notify("snapshot", publishSnapshot());
221
247
  return result;
222
248
  }, () => { });
223
249
  function updateTools(metadata) {