@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.
- package/README.md +9 -1
- package/build/backend-worker-chunks/{chunk-LO7O6NAM.mjs → chunk-JOI2POLP.mjs} +1 -1
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-GY27HBAY.mjs +35739 -0
- package/build/backend-worker-chunks/{pi-QNU2YE4G.mjs → pi-JV6MWPW7.mjs} +1891 -35
- package/build/backend-worker.mjs +25 -126
- package/dist/backend/claude/index.js +69 -11
- package/dist/backend/claude/subagents.js +11 -0
- package/dist/backend/fake/index.js +8 -2
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/index.js +37 -12
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/worker/entry.js +13 -1
- package/dist/backend/worker/index.js +66 -5
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +2 -0
- package/dist/client/tool-summary.js +26 -15
- package/dist/daemon/host.js +13 -2
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/isolation/filesystem.js +5 -1
- package/dist/isolation/sandbox.js +31 -4
- package/package.json +7 -5
- package/web/dist/assets/index-BWKZK5HD.css +2 -0
- package/web/dist/assets/index-nIc09tKZ.js +40 -0
- package/web/dist/assets/{settings-mcp-Vf_fCXyE.js → settings-mcp-bcNKV147.js} +1 -1
- package/web/dist/assets/{settings-workflows-DVKxJWQm.js → settings-workflows-C_TKOhVa.js} +2 -2
- package/web/dist/assets/{workflows-Dobqzjg-.js → workflows-DHG-CIo3.js} +36 -36
- package/web/dist/assets/{workflows-pane-KB-Q76KZ.js → workflows-pane-9u_hJvgQ.js} +1 -1
- package/web/dist/index.html +3 -3
- package/build/backend-worker-chunks/claude-6L5KCQWJ.mjs +0 -30894
- package/web/dist/assets/index-BGu3YSP7.css +0 -2
- package/web/dist/assets/index-Miy2nveb.js +0 -40
|
@@ -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
|
+
}
|
package/dist/backend/pi/work.js
CHANGED
|
@@ -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()
|
|
87
|
+
const model = findPiModel(parent.modelRuntime.getAvailableSnapshot(), options.modelId);
|
|
87
88
|
if (!model)
|
|
88
|
-
throw new Error(
|
|
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;
|
|
@@ -58,7 +58,7 @@ export function runWorker() {
|
|
|
58
58
|
if (creating || closing)
|
|
59
59
|
throw new Error("Backend worker already initialized");
|
|
60
60
|
creating = true;
|
|
61
|
-
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];
|
|
62
62
|
const workflowBuilder = workflowBuilderInstructions === undefined ? undefined : {
|
|
63
63
|
instructions: workflowBuilderInstructions,
|
|
64
64
|
read: (path) => rpc.call("workflowBuilder.read", [path]),
|
|
@@ -99,8 +99,20 @@ export function runWorker() {
|
|
|
99
99
|
throw new Error(`Backend "${backendName}" is not available in this build: ${errorText(error)}`);
|
|
100
100
|
}
|
|
101
101
|
const imported = performance.now();
|
|
102
|
+
let initialAuth = piAuth;
|
|
102
103
|
session = await backend.create({
|
|
103
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
|
+
} } : {}),
|
|
104
116
|
...(workflowBuilder ? { workflowBuilder } : {
|
|
105
117
|
...(localMcp ? { mcp: localMcp }
|
|
106
118
|
: mcpTools ? { mcp: { connections: (mcpConnectionIds ?? []).map((id) => ({ id })), tools: () => tools } } : {}),
|
|
@@ -5,7 +5,7 @@ import { dirname, join, resolve, sep } from "node:path";
|
|
|
5
5
|
import { isSea } from "node:sea";
|
|
6
6
|
import { fileURLToPath } from "node:url";
|
|
7
7
|
import { prepareFilesystemIsolation } from "../../isolation/filesystem.js";
|
|
8
|
-
import { createSandbox, sandboxMounts, sandboxUnavailable } from "../../isolation/sandbox.js";
|
|
8
|
+
import { createSandbox, hostClaude, sandboxMounts, sandboxUnavailable } from "../../isolation/sandbox.js";
|
|
9
9
|
import { validateFilesystemScope } from "../../isolation/filesystem.js";
|
|
10
10
|
import { workflowBuilderFolder } from "../../isolation/shared-sandbox.js";
|
|
11
11
|
import { nodeExecutionAssets } from "../../isolation/node-assets.js";
|
|
@@ -18,12 +18,23 @@ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "
|
|
|
18
18
|
import { sessionListInput, sessionInspectInput, sessionCreateInput, sessionSendInput } from "../session-tools.js";
|
|
19
19
|
import { migrateLegacyClaudeState, prepareClaudeState, relocateClaudeState, forkClaudeState } from "./claude-state.js";
|
|
20
20
|
import { relocatePiState, forkPiState } from "../pi/state.js";
|
|
21
|
+
import { createPiModelAuth } from "../pi/model-auth.js";
|
|
21
22
|
import { recordTiming } from "../../daemon/timings.js";
|
|
22
23
|
/** One owned worker per Backend Session, optionally enforcing a filesystem boundary. */
|
|
23
24
|
export class WorkerBackend {
|
|
24
25
|
name;
|
|
25
26
|
options;
|
|
27
|
+
piAuth;
|
|
28
|
+
stopped = false;
|
|
26
29
|
constructor(options = {}) { this.options = options; this.name = options.backend ?? "pi"; }
|
|
30
|
+
async shutdown() {
|
|
31
|
+
this.stopped = true;
|
|
32
|
+
await this.piAuth?.close?.();
|
|
33
|
+
}
|
|
34
|
+
assertRunning() {
|
|
35
|
+
if (this.stopped)
|
|
36
|
+
throw new Error("Backend Adapter stopped");
|
|
37
|
+
}
|
|
27
38
|
scheduledSandboxMounts(scope) {
|
|
28
39
|
const packageRoot = fileURLToPath(new URL("../../..", import.meta.url));
|
|
29
40
|
const readable = [packageRoot, ...(this.options.readablePaths ?? [])];
|
|
@@ -77,6 +88,18 @@ export class WorkerBackend {
|
|
|
77
88
|
if (this.options.backendModule)
|
|
78
89
|
assets.push(fileURLToPath(this.options.backendModule));
|
|
79
90
|
assets.push(...nodeExecutionAssets(assets));
|
|
91
|
+
let claudePath = support.provider.claudePath;
|
|
92
|
+
if (support.provider.hostClaudePath && (shared || this.name === "claude")) {
|
|
93
|
+
let host;
|
|
94
|
+
try {
|
|
95
|
+
host = hostClaude(support.provider.hostClaudePath);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
throw new Error(`${sandboxUnavailable().message}: ${error.message}`);
|
|
99
|
+
}
|
|
100
|
+
claudePath = host.executable;
|
|
101
|
+
assets.push(host.directory);
|
|
102
|
+
}
|
|
80
103
|
const env = { FLOW_BACKEND_WORKER: "1",
|
|
81
104
|
...Object.fromEntries(Object.entries(this.options.env ?? {}).filter((entry) => entry[1] !== undefined)) };
|
|
82
105
|
const cleanups = [];
|
|
@@ -87,7 +110,10 @@ export class WorkerBackend {
|
|
|
87
110
|
env.CLAUDE_CONFIG_DIR = claude.env.CLAUDE_CONFIG_DIR;
|
|
88
111
|
if (claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR)
|
|
89
112
|
env.CLAUDE_SECURESTORAGE_CONFIG_DIR = claude.env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
|
|
90
|
-
|
|
113
|
+
if (claudePath)
|
|
114
|
+
env.FLOW_CLAUDE_PATH = claudePath;
|
|
115
|
+
if (support.provider.hostClaudePath)
|
|
116
|
+
env.DISABLE_AUTOUPDATER = "1";
|
|
91
117
|
for (const entry of readdirSync(env.CLAUDE_CONFIG_DIR)) {
|
|
92
118
|
const link = join(env.CLAUDE_CONFIG_DIR, entry);
|
|
93
119
|
if (!options.workflowBuilder && lstatSync(link).isSymbolicLink() && !["projects", "file-history"].includes(entry))
|
|
@@ -100,7 +126,7 @@ export class WorkerBackend {
|
|
|
100
126
|
rmSync(agent, { recursive: true, force: true });
|
|
101
127
|
mkdirSync(agent, { recursive: true, mode: 0o700 });
|
|
102
128
|
cleanups.push(() => rmSync(agent, { recursive: true, force: true }));
|
|
103
|
-
for (const name of ["
|
|
129
|
+
for (const name of ["models.json", "settings.json"]) {
|
|
104
130
|
if (existsSync(join(source, name)))
|
|
105
131
|
copyFileSync(join(source, name), join(agent, name));
|
|
106
132
|
}
|
|
@@ -140,6 +166,7 @@ export class WorkerBackend {
|
|
|
140
166
|
({ startup } = sandbox);
|
|
141
167
|
cleanups.push(() => { removed = sandbox.close().catch((error) => console.error(`Sandbox ${sandbox.name} removal failed: ${error.message}`)); });
|
|
142
168
|
}
|
|
169
|
+
this.assertRunning();
|
|
143
170
|
const launch = sandbox.command(scope, [support.provider.nodePath, ...plan.args], env);
|
|
144
171
|
proxy = new WorkerSession({ ...options, scope, stateDir }, { ...this.options, sandboxed: sandbox, startupTimeoutMs: this.options.startupTimeoutMs ?? 300_000, command: launch.command, args: launch.args, env: {} }, cleanup);
|
|
145
172
|
await this.opened(proxy, options.signal, "sandbox", begin, { sharing: shared ? "shared" : "own", remove: Math.round(startup.remove), create: Math.round(startup.create) });
|
|
@@ -163,8 +190,14 @@ export class WorkerBackend {
|
|
|
163
190
|
return this.name === "claude" ? forkClaudeState(from, to) : forkPiState(from.stateDir, to.stateDir, to.scope);
|
|
164
191
|
}
|
|
165
192
|
async create(options) {
|
|
193
|
+
this.assertRunning();
|
|
166
194
|
const begin = performance.now();
|
|
167
195
|
options.signal?.throwIfAborted();
|
|
196
|
+
if (this.name === 'pi' && !this.options.backendModule && !options.piAuth) {
|
|
197
|
+
const directory = this.options.env?.PI_CODING_AGENT_DIR;
|
|
198
|
+
this.piAuth ??= createPiModelAuth(directory ? { authPath: join(directory, 'auth.json') } : {});
|
|
199
|
+
options = { ...options, piAuth: this.piAuth };
|
|
200
|
+
}
|
|
168
201
|
const isolationMode = options.isolationMode ?? this.options.isolationMode?.() ?? "bubblewrap";
|
|
169
202
|
if (isolationMode === "sandbox")
|
|
170
203
|
return this.createSandboxed(options);
|
|
@@ -210,6 +243,7 @@ export class WorkerBackend {
|
|
|
210
243
|
env: this.options.env ?? {}, credentials: this.name, workflowBuilder: !!options.workflowBuilder, worker: true, readablePaths: assets });
|
|
211
244
|
let proxy;
|
|
212
245
|
try {
|
|
246
|
+
this.assertRunning();
|
|
213
247
|
options.signal?.throwIfAborted();
|
|
214
248
|
if (this.name === "claude")
|
|
215
249
|
migrateLegacyClaudeState(options.stateDir, { ...process.env, ...this.options.env }, isolation.scope, options.resume);
|
|
@@ -233,6 +267,7 @@ class WorkerSession {
|
|
|
233
267
|
worker;
|
|
234
268
|
rpc;
|
|
235
269
|
failed;
|
|
270
|
+
piAuthProviders = new Set();
|
|
236
271
|
disposing = false;
|
|
237
272
|
disposal;
|
|
238
273
|
workflows = new Map();
|
|
@@ -260,11 +295,25 @@ class WorkerSession {
|
|
|
260
295
|
if (this.disposing || this.failed)
|
|
261
296
|
throw new Error("Backend Session stopped");
|
|
262
297
|
// Builders never inherit other host capabilities, even if the worker asks directly.
|
|
263
|
-
if (this.options.workflowBuilder && !["workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
|
|
298
|
+
if (this.options.workflowBuilder && !["pi.auth.snapshot", "pi.auth.resolve", "workflowBuilder.read", "workflowBuilder.list", "workflowBuilder.write"].includes(method)) {
|
|
264
299
|
throw new Error("Host capability is not enabled for workflow builder");
|
|
265
300
|
}
|
|
266
301
|
// Never look up host functions by a worker-supplied property name.
|
|
267
302
|
switch (method) {
|
|
303
|
+
case 'pi.auth.snapshot': return this.snapshotPiAuth(signal);
|
|
304
|
+
case 'pi.auth.resolve': {
|
|
305
|
+
const auth = this.requirePiAuth();
|
|
306
|
+
const provider = args[0];
|
|
307
|
+
if (typeof provider !== 'string' || !this.piAuthProviders.has(provider))
|
|
308
|
+
throw new Error('Unknown Pi provider');
|
|
309
|
+
try {
|
|
310
|
+
return await auth.resolve(provider, signal);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
signal.throwIfAborted();
|
|
314
|
+
throw new Error(`Pi authentication failed for ${provider}. Check sign-in and auth.json access. Move any !command credentials to models.json.`);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
268
317
|
case "mcp.token": {
|
|
269
318
|
if (!(this.options.mcp instanceof SandboxMcpSession) || typeof args[0] !== "string")
|
|
270
319
|
throw new Error("Host capability is not enabled");
|
|
@@ -301,6 +350,16 @@ class WorkerSession {
|
|
|
301
350
|
child.stdout?.once("close", () => this.fail(new Error("Backend worker disconnected")));
|
|
302
351
|
child.once("exit", (code, signal) => this.fail(new Error(`Backend worker exited (${signal ?? code ?? "unknown"})${this.worker.diagnostics() ? `: ${this.worker.diagnostics()}` : ""}`)));
|
|
303
352
|
}
|
|
353
|
+
requirePiAuth() {
|
|
354
|
+
if ((this.launchOptions.backend ?? 'pi') !== 'pi' || !this.options.piAuth)
|
|
355
|
+
throw new Error('Pi auth is not enabled');
|
|
356
|
+
return this.options.piAuth;
|
|
357
|
+
}
|
|
358
|
+
async snapshotPiAuth(signal) {
|
|
359
|
+
const metadata = await this.requirePiAuth().snapshot(signal);
|
|
360
|
+
this.piAuthProviders = new Set(metadata.map(({ providerId }) => providerId));
|
|
361
|
+
return metadata;
|
|
362
|
+
}
|
|
304
363
|
requireWorkflowBuilder(input) {
|
|
305
364
|
if (!this.options.workflowBuilder)
|
|
306
365
|
throw new Error("Workflow builder tools are not enabled");
|
|
@@ -319,7 +378,7 @@ class WorkerSession {
|
|
|
319
378
|
return this.options.sessionTools;
|
|
320
379
|
}
|
|
321
380
|
async open(signal) {
|
|
322
|
-
const { emit: _emit, onFailure: _onFailure, signal: _signal, evict: _evict, mcp, workflow, workflowBuilder, sessionTools, ...options } = this.options;
|
|
381
|
+
const { emit: _emit, onFailure: _onFailure, signal: _signal, evict: _evict, mcp, workflow, workflowBuilder, sessionTools, piAuth, ...options } = this.options;
|
|
323
382
|
const controller = new AbortController();
|
|
324
383
|
const cancel = () => controller.abort(signal?.reason);
|
|
325
384
|
if (signal?.aborted)
|
|
@@ -328,7 +387,9 @@ class WorkerSession {
|
|
|
328
387
|
signal?.addEventListener('abort', cancel, { once: true });
|
|
329
388
|
const timer = setTimeout(() => controller.abort(), this.launchOptions.startupTimeoutMs ?? 60_000);
|
|
330
389
|
try {
|
|
390
|
+
const auth = piAuth ? await this.snapshotPiAuth(controller.signal) : undefined;
|
|
331
391
|
const state = await this.rpc.call("create", [{ ...options, backend: this.launchOptions.backend ?? "pi",
|
|
392
|
+
...(auth ? { piAuth: auth } : {}),
|
|
332
393
|
workflowEnabled: !workflowBuilder && !!workflow,
|
|
333
394
|
sessionToolsEnabled: !workflowBuilder && options.tools !== "none" && !!sessionTools,
|
|
334
395
|
...(workflowBuilder ? { workflowBuilderInstructions: workflowBuilder.instructions }
|
package/dist/build-id
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
f94da56f-258e-42d7-900e-3933fca5ee5e
|
package/dist/cli/bootstrap.js
CHANGED
|
@@ -889,7 +889,7 @@ async function bootstrap() {
|
|
|
889
889
|
if (!managed) throw new Error("Missing systemd update configuration");
|
|
890
890
|
await assertSystemdOwner(managed, managed.updater, process.pid);
|
|
891
891
|
}
|
|
892
|
-
const lease = await install.register("
|
|
892
|
+
const lease = await install.register("f94da56f-258e-42d7-900e-3933fca5ee5e", root, args, process.env.FLOW_UPDATE_CAPABILITY ?? systemdCapability(root));
|
|
893
893
|
delete process.env.FLOW_UPDATE_CAPABILITY;
|
|
894
894
|
process.on("exit", lease.release);
|
|
895
895
|
if (args[0] === "update") {
|
package/dist/client/reduce.js
CHANGED
|
@@ -188,6 +188,8 @@ function applyEvent(state, event, at) {
|
|
|
188
188
|
id: event.subagentId,
|
|
189
189
|
name: event.name,
|
|
190
190
|
...(event.description === undefined ? {} : { description: event.description }),
|
|
191
|
+
...(event.model === undefined ? {} : { model: event.model }),
|
|
192
|
+
...(event.effort === undefined ? {} : { effort: event.effort }),
|
|
191
193
|
...(event.producer === undefined ? {} : { producer: event.producer }),
|
|
192
194
|
status: event.state,
|
|
193
195
|
// Only ever set alongside "waiting", so a Subagent that resumes drops it rather than
|
|
@@ -13,17 +13,18 @@
|
|
|
13
13
|
const MAX = 60;
|
|
14
14
|
/**
|
|
15
15
|
* Ordered, because a tool's input usually carries several of these and the first is the one the
|
|
16
|
-
* question is about: a
|
|
17
|
-
* directory it searched.
|
|
16
|
+
* question is about: the `description` a model wrote for a call before the `command` or `prompt` it
|
|
17
|
+
* describes, a Grep's `pattern` before the directory it searched.
|
|
18
18
|
*
|
|
19
19
|
* Keyed on the shape of the arguments rather than on the tool's name, because the name is the part
|
|
20
20
|
* that varies: Claude's `Edit` and a pi tool that edits a file are not called the same thing, while
|
|
21
21
|
* `file_path` means the same in both. An unrecognised tool with a recognisable argument still reads.
|
|
22
22
|
*/
|
|
23
23
|
const ARGUMENTS = [
|
|
24
|
+
{ key: "description", shape: "text" },
|
|
24
25
|
{ key: "command", shape: "text" },
|
|
25
|
-
// Ahead of `
|
|
26
|
-
//
|
|
26
|
+
// Ahead of `prompt`, which an AskUserQuestion call does not carry but a future asking tool might.
|
|
27
|
+
// Keyed on the argument rather than the tool's name, which is this list's rule.
|
|
27
28
|
{ key: "questions", shape: "questions" },
|
|
28
29
|
{ key: "file_path", shape: "path" },
|
|
29
30
|
{ key: "notebook_path", shape: "path" },
|
|
@@ -31,36 +32,46 @@ const ARGUMENTS = [
|
|
|
31
32
|
{ key: "url", shape: "text" },
|
|
32
33
|
{ key: "query", shape: "text" },
|
|
33
34
|
{ key: "path", shape: "path" },
|
|
34
|
-
{ key: "description", shape: "text" },
|
|
35
35
|
{ key: "prompt", shape: "text" },
|
|
36
36
|
];
|
|
37
|
+
const MAIN_ARGUMENTS = ARGUMENTS.filter(({ key }) => key !== "description");
|
|
37
38
|
/**
|
|
38
39
|
* Returns undefined when there is nothing worth saying, so a caller renders the tool's name alone
|
|
39
40
|
* rather than a padded blank. `input` is `unknown` on the wire (`events.ts` — a Backend Adapter
|
|
40
41
|
* passes its backend's arguments through), so every access is narrowed rather than trusted.
|
|
41
42
|
*/
|
|
42
43
|
export function toolSummary(input) {
|
|
44
|
+
return summarise(input, MAX);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The first argument after `description`, unclipped — the command or prompt the description
|
|
48
|
+
* stands for — for a card that has room to wrap it.
|
|
49
|
+
*/
|
|
50
|
+
export function fullToolSummary(input) {
|
|
51
|
+
return summarise(input, Infinity, MAIN_ARGUMENTS);
|
|
52
|
+
}
|
|
53
|
+
function summarise(input, max, args = ARGUMENTS) {
|
|
43
54
|
if (!input || typeof input !== "object")
|
|
44
55
|
return undefined;
|
|
45
56
|
const record = input;
|
|
46
|
-
for (const argument of
|
|
57
|
+
for (const argument of args) {
|
|
47
58
|
const value = record[argument.key];
|
|
48
59
|
if (argument.shape === "questions") {
|
|
49
|
-
const asked = clipQuestions(value);
|
|
60
|
+
const asked = clipQuestions(value, max);
|
|
50
61
|
if (asked !== undefined)
|
|
51
62
|
return asked;
|
|
52
63
|
continue;
|
|
53
64
|
}
|
|
54
65
|
if (typeof value !== "string" || value.trim() === "")
|
|
55
66
|
continue;
|
|
56
|
-
return argument.shape === "path" ? clipPath(value.trim()) : clipText(value);
|
|
67
|
+
return argument.shape === "path" ? clipPath(value.trim(), max) : clipText(value, max);
|
|
57
68
|
}
|
|
58
69
|
// The fallback: a tool nobody here has heard of, whose input is a single string, is describing
|
|
59
70
|
// itself with that string. Two or more and there is no way to know which one matters, so say
|
|
60
71
|
// nothing rather than pick.
|
|
61
72
|
const strings = Object.values(record).filter((value) => typeof value === "string");
|
|
62
73
|
const only = strings.length === 1 ? strings[0] : undefined;
|
|
63
|
-
return only && only.trim() !== "" ? clipText(only) : undefined;
|
|
74
|
+
return only && only.trim() !== "" ? clipText(only, max) : undefined;
|
|
64
75
|
}
|
|
65
76
|
/**
|
|
66
77
|
* The first question asked, and how many others came with it.
|
|
@@ -72,7 +83,7 @@ export function toolSummary(input) {
|
|
|
72
83
|
* The front-ends suppress this row where an Enquiry Entry stands beside it, so what this actually
|
|
73
84
|
* serves is the case where one does not: a Subagent's Enquiry, seen from the Agents tab.
|
|
74
85
|
*/
|
|
75
|
-
function clipQuestions(value) {
|
|
86
|
+
function clipQuestions(value, max) {
|
|
76
87
|
if (!Array.isArray(value) || value.length === 0)
|
|
77
88
|
return undefined;
|
|
78
89
|
const first = value[0];
|
|
@@ -84,15 +95,15 @@ function clipQuestions(value) {
|
|
|
84
95
|
const rest = value.length - 1;
|
|
85
96
|
// Clipped after the count is appended, not before, so the whole précis obeys MAX rather than
|
|
86
97
|
// MAX-plus-however-long-the-suffix-turned-out-to-be.
|
|
87
|
-
return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked);
|
|
98
|
+
return clipText(rest > 0 ? `${asked} (+${rest} more)` : asked, max);
|
|
88
99
|
}
|
|
89
100
|
/** Whitespace collapsed so a heredoc or a multi-line prompt still occupies one line. */
|
|
90
|
-
function clipText(value) {
|
|
101
|
+
function clipText(value, max) {
|
|
91
102
|
const text = value.replace(/\s+/g, " ").trim();
|
|
92
|
-
return text.length <=
|
|
103
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
|
|
93
104
|
}
|
|
94
|
-
function clipPath(path) {
|
|
105
|
+
function clipPath(path, max) {
|
|
95
106
|
// The tail of a path is what identifies the file; the leading directories are what a reader can
|
|
96
107
|
// afford to lose, which is the opposite of how everything else here truncates.
|
|
97
|
-
return path.length <=
|
|
108
|
+
return path.length <= max ? path : `…${path.slice(-(max - 1))}`;
|
|
98
109
|
}
|
package/dist/daemon/host.js
CHANGED
|
@@ -17,6 +17,7 @@ import { deriveStatus, railGroupRank } from "../client/status.js";
|
|
|
17
17
|
import { createWorktree, head, isClean, isRepository, removeMergedBranch, removeWorktree, repairWorktree, switchBranch as gitSwitchBranch, } from "./git.js";
|
|
18
18
|
import { SessionLog } from "./log.js";
|
|
19
19
|
import { probeModels } from "./models.js";
|
|
20
|
+
import { PiModelProbeCache } from "./pi-model-cache.js";
|
|
20
21
|
import { ScheduleValidationError } from "../workflows/schedule-errors.js";
|
|
21
22
|
import { probeSkills } from "./skills.js";
|
|
22
23
|
import { recordTiming } from "./timings.js";
|
|
@@ -44,6 +45,7 @@ export class SessionHost {
|
|
|
44
45
|
backends = new Map();
|
|
45
46
|
/** Model probes by backend name, held in flight rather than resolved — see `models`. */
|
|
46
47
|
modelProbes = new Map();
|
|
48
|
+
piModelProbeCache = new PiModelProbeCache();
|
|
47
49
|
/** One warm Skills session per Backend Adapter, for the last Scope asked — see `skillsFor` (ADR 0035). */
|
|
48
50
|
skillSessions = new Map();
|
|
49
51
|
/**
|
|
@@ -308,7 +310,7 @@ export class SessionHost {
|
|
|
308
310
|
const held = this.modelProbes.get(backend.name);
|
|
309
311
|
if (held)
|
|
310
312
|
return held;
|
|
311
|
-
const probe = this.timed("models", backend, false, (timed) => probeModels(timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false)));
|
|
313
|
+
const probe = this.timed("models", backend, false, (timed) => probeModels(backend.name === 'pi' ? this.piModelProbeCache.wrap(timed) : timed, scope, false, (held) => this.holdSkillSession(backend.name, held, false), refresh));
|
|
312
314
|
this.modelProbes.set(backend.name, probe);
|
|
313
315
|
return probe;
|
|
314
316
|
});
|
|
@@ -2145,6 +2147,10 @@ export class SessionHost {
|
|
|
2145
2147
|
this.persist(record);
|
|
2146
2148
|
}
|
|
2147
2149
|
await this.shared?.close().catch((error) => console.error(`Shared sandbox removal failed: ${error.message}`));
|
|
2150
|
+
const stopped = await Promise.allSettled([...this.backends.values()].map(async (backend) => backend.shutdown?.()));
|
|
2151
|
+
const failures = stopped.filter(result => result.status === "rejected").map(result => result.reason);
|
|
2152
|
+
if (failures.length)
|
|
2153
|
+
throw new AggregateError(failures, "Backend Adapter shutdown failed");
|
|
2148
2154
|
}
|
|
2149
2155
|
async execute(command) {
|
|
2150
2156
|
switch (command.type) {
|
|
@@ -3295,7 +3301,12 @@ function openSubagents(entries) {
|
|
|
3295
3301
|
if (event.type !== "subagent")
|
|
3296
3302
|
continue;
|
|
3297
3303
|
if (event.state === "running" || event.state === "waiting") {
|
|
3298
|
-
open.set(event.subagentId, {
|
|
3304
|
+
open.set(event.subagentId, {
|
|
3305
|
+
name: event.name,
|
|
3306
|
+
...(event.model === undefined ? {} : { model: event.model }),
|
|
3307
|
+
...(event.effort === undefined ? {} : { effort: event.effort }),
|
|
3308
|
+
...(event.producer === undefined ? {} : { producer: event.producer }),
|
|
3309
|
+
});
|
|
3299
3310
|
}
|
|
3300
3311
|
else
|
|
3301
3312
|
open.delete(event.subagentId);
|
package/dist/daemon/models.js
CHANGED
|
@@ -29,7 +29,7 @@ const PROBE_TIMEOUT_MS = 45_000;
|
|
|
29
29
|
* Never throws: a backend that cannot answer reports a `problem`, and its section of the Settings
|
|
30
30
|
* offers a text field instead of a list. A refusal here must not make the whole page unreachable.
|
|
31
31
|
*/
|
|
32
|
-
export async function probeModels(backend, scope, workflowBuilder = false, keep) {
|
|
32
|
+
export async function probeModels(backend, scope, workflowBuilder = false, keep, refresh = false) {
|
|
33
33
|
let models = [];
|
|
34
34
|
let settle;
|
|
35
35
|
// Claude reports a provisional Capabilities at create and the real list moments later, over
|
|
@@ -47,7 +47,7 @@ export async function probeModels(backend, scope, workflowBuilder = false, keep)
|
|
|
47
47
|
let session;
|
|
48
48
|
try {
|
|
49
49
|
const refuseTool = async () => { throw new Error("Model discovery cannot use workflow builder tools"); };
|
|
50
|
-
session = await backend.create({ ...options, ...(workflowBuilder ? { workflowBuilder: {
|
|
50
|
+
session = await backend.create({ ...options, ...(refresh ? { refreshModels: true } : {}), ...(workflowBuilder ? { workflowBuilder: {
|
|
51
51
|
instructions: "List available models only.", read: refuseTool, list: refuseTool, write: refuseTool,
|
|
52
52
|
} } : {}) });
|
|
53
53
|
}
|