@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +60 -21
- package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
- package/build/backend-worker.mjs +77 -123
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +201 -21
- package/dist/backend/claude/session-tools.js +14 -0
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +125 -21
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/session-tools.js +21 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +27 -0
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +49 -8
- package/dist/backend/worker/index.js +155 -17
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -6
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +1010 -116
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/session-tool-views.js +22 -0
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +17 -8
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +434 -305
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +150 -10
- package/dist/workflows/recovery.js +87 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +389 -98
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
- package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-api-BfExddae.js +0 -6
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
- /package/dist/protocol/{publish.js → imports.js} +0 -0
package/dist/backend/pi/index.js
CHANGED
|
@@ -1,20 +1,32 @@
|
|
|
1
1
|
import { workflowParentTools } from "./workflow-parent.js";
|
|
2
|
+
import { piSessionTools } from "./session-tools.js";
|
|
2
3
|
import { piWorkflowBuilderTools } from "./workflow-builder.js";
|
|
3
4
|
import { piMcpTools } from "./mcp.js";
|
|
4
5
|
import { randomUUID } from "node:crypto";
|
|
6
|
+
import { existsSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { join } from "node:path";
|
|
8
|
+
import { USER_MESSAGE_MAP } from "./state.js";
|
|
5
9
|
import { createAgentSession, DefaultResourceLoader, getAgentDir, SessionManager, SettingsManager, } from "@earendil-works/pi-coding-agent";
|
|
6
10
|
import { PiWorkflowSubagent } from "./workflow-subagent.js";
|
|
7
11
|
import { piEffortLevels } from "./effort-capabilities.js";
|
|
12
|
+
import { findPiModel, piModelUnavailable } from "./model-selection.js";
|
|
8
13
|
import { clampEffort } from "../effort.js";
|
|
9
14
|
import { piAutoCompaction } from "./auto-compaction.js";
|
|
15
|
+
import { createWorkerPiModelRuntime } from "./model-auth.js";
|
|
16
|
+
import { streamingCacheWarming } from "./cache-warming.js";
|
|
10
17
|
import { compactionExtensionError, compactionModelExtension } from "./compaction-model.js";
|
|
11
18
|
import { ASK_TOOL, PiEnquiries } from "./enquiries.js";
|
|
19
|
+
import { TODO_TOOL, piTodoTool } from "./todo-list.js";
|
|
12
20
|
import { backgroundTools } from "./background-calls.js";
|
|
13
21
|
import { SUBAGENT_TOOL, subagentTool } from "./subagents.js";
|
|
14
22
|
import { PiAgentPermissions } from "./agent-permissions.js";
|
|
23
|
+
import { fetchAnthropicPlanLimits, fetchCodexPlanLimits } from "./plan-limits.js";
|
|
15
24
|
import { PiWork, callIdFor, resultText, textResult } from "./work.js";
|
|
25
|
+
import { DIFF_EXCERPT_INSTRUCTIONS } from "../diff-excerpt-instructions.js";
|
|
16
26
|
export class PiSession {
|
|
17
27
|
capabilities;
|
|
28
|
+
spend;
|
|
29
|
+
counted;
|
|
18
30
|
answerEnquiry;
|
|
19
31
|
enquiries;
|
|
20
32
|
work;
|
|
@@ -30,7 +42,7 @@ export class PiSession {
|
|
|
30
42
|
this.unsubscribe();
|
|
31
43
|
current.dispose();
|
|
32
44
|
this.session = await this.recreate(current);
|
|
33
|
-
this.unsubscribe = this.
|
|
45
|
+
this.unsubscribe = this.bindSession();
|
|
34
46
|
}
|
|
35
47
|
standingAuthorisations;
|
|
36
48
|
agentPermissions;
|
|
@@ -59,6 +71,8 @@ export class PiSession {
|
|
|
59
71
|
effort;
|
|
60
72
|
messageSeq = 0;
|
|
61
73
|
currentMessageId;
|
|
74
|
+
/** Host user message ids sent but not yet seen as pi user messages, oldest first. */
|
|
75
|
+
unmappedMessageIds = [];
|
|
62
76
|
constructor(session, emit, sessionDir, support = {}) {
|
|
63
77
|
this.workflowBuilder = support.workflowBuilder ?? false;
|
|
64
78
|
this.mcp = support.mcp;
|
|
@@ -68,6 +82,8 @@ export class PiSession {
|
|
|
68
82
|
if (support.permissionProducer)
|
|
69
83
|
this.permissionProducer = support.permissionProducer;
|
|
70
84
|
this.session = session;
|
|
85
|
+
this.spend = support.priorSpend;
|
|
86
|
+
this.counted = statsOf(session);
|
|
71
87
|
this.applyAutoCompaction = support.autoCompaction;
|
|
72
88
|
this.workflowAutoCompaction = support.workflowAutoCompaction;
|
|
73
89
|
this.workflowCompactionModelId = support.workflowCompactionModelId;
|
|
@@ -82,7 +98,17 @@ export class PiSession {
|
|
|
82
98
|
if (enquiries)
|
|
83
99
|
this.answerEnquiry = async (askId, answers) => enquiries.answer(askId, answers);
|
|
84
100
|
this.capabilities = capabilitiesOf(session, support.enquiries !== undefined, support.subagents ?? false, !this.workflowBuilder);
|
|
85
|
-
this.unsubscribe =
|
|
101
|
+
this.unsubscribe = this.bindSession();
|
|
102
|
+
}
|
|
103
|
+
bindSession() {
|
|
104
|
+
const stream = this.session.agent?.streamFunction;
|
|
105
|
+
if (stream)
|
|
106
|
+
this.session.agent.streamFunction = (...args) => {
|
|
107
|
+
if (this.disposed)
|
|
108
|
+
throw new Error("Backend Session stopped");
|
|
109
|
+
return stream(...args);
|
|
110
|
+
};
|
|
111
|
+
return this.session.subscribe((event) => this.translate(event));
|
|
86
112
|
}
|
|
87
113
|
startWorkflowSubagent(options) {
|
|
88
114
|
if (this.disposed)
|
|
@@ -100,7 +126,11 @@ export class PiSession {
|
|
|
100
126
|
// pi persists through its own SessionManager; the directory we gave it is the resume handle.
|
|
101
127
|
return this.sessionDir;
|
|
102
128
|
}
|
|
103
|
-
async prompt(text, attachments) {
|
|
129
|
+
async prompt(text, attachments, messageId) {
|
|
130
|
+
if (this.disposed)
|
|
131
|
+
return;
|
|
132
|
+
if (messageId && this.sessionDir)
|
|
133
|
+
this.unmappedMessageIds.push(messageId);
|
|
104
134
|
this.turnId = `turn-${++this.messageSeq}`;
|
|
105
135
|
this.emit({ type: "turn_started", turnId: this.turnId });
|
|
106
136
|
await this.session.prompt(text, {
|
|
@@ -120,11 +150,9 @@ export class PiSession {
|
|
|
120
150
|
async setPermissionMode(mode) { this.agentPermissions?.setMode(mode); }
|
|
121
151
|
async setModel(modelId) {
|
|
122
152
|
const available = await this.session.modelRuntime.getAvailable();
|
|
123
|
-
const
|
|
124
|
-
const legacy = available.filter((candidate) => candidate.id === modelId);
|
|
125
|
-
const model = qualified ?? (legacy.length === 1 ? legacy[0] : undefined);
|
|
153
|
+
const model = findPiModel(available, modelId, true);
|
|
126
154
|
if (!model)
|
|
127
|
-
throw new Error(
|
|
155
|
+
throw new Error(piModelUnavailable(modelId));
|
|
128
156
|
await this.session.setModel(model);
|
|
129
157
|
this.applyAutoCompaction?.(this.session.model);
|
|
130
158
|
// Which levels are on offer follows the model, and pi may have clamped its own thinking level
|
|
@@ -191,6 +219,9 @@ export class PiSession {
|
|
|
191
219
|
*/
|
|
192
220
|
async skills() {
|
|
193
221
|
await this.session.resourceLoader.reload();
|
|
222
|
+
// Reloading the loader alone leaves Pi's cached model context stale. Reapply the
|
|
223
|
+
// existing tool selection to rebuild the prompt for the next turn without changing access.
|
|
224
|
+
this.session.setActiveToolsByName(this.session.getActiveToolNames());
|
|
194
225
|
const { skills } = this.session.resourceLoader.getSkills();
|
|
195
226
|
const { prompts } = this.session.resourceLoader.getPrompts();
|
|
196
227
|
return [
|
|
@@ -202,6 +233,14 @@ export class PiSession {
|
|
|
202
233
|
})),
|
|
203
234
|
];
|
|
204
235
|
}
|
|
236
|
+
async planLimits() {
|
|
237
|
+
const read = async (provider, fetchLimits) => {
|
|
238
|
+
const token = (await this.session.modelRuntime.getAuth(provider).catch(() => undefined))?.auth.apiKey;
|
|
239
|
+
return token ? await fetchLimits(token).catch(() => undefined) : undefined;
|
|
240
|
+
};
|
|
241
|
+
const limits = await Promise.all([read("anthropic", fetchAnthropicPlanLimits), read("openai-codex", fetchCodexPlanLimits)]);
|
|
242
|
+
return limits.filter((limit) => limit !== undefined);
|
|
243
|
+
}
|
|
205
244
|
applyEffort(wanted) {
|
|
206
245
|
const level = clampEffort(wanted, availableEffort(this.session));
|
|
207
246
|
// Nothing to set on a model with no effort control. The request stays on file, so switching
|
|
@@ -289,6 +328,15 @@ export class PiSession {
|
|
|
289
328
|
this.emit({ type: "turn_ended", turnId, reason });
|
|
290
329
|
this.scheduleCompletions();
|
|
291
330
|
}
|
|
331
|
+
/** pi appends the entry just after `message_end` reaches listeners, so look it up after that. */
|
|
332
|
+
mapUserMessage(messageId, message) {
|
|
333
|
+
queueMicrotask(() => {
|
|
334
|
+
const entry = this.session.sessionManager.getBranch().findLast((candidate) => candidate.type === "message" && candidate.message === message);
|
|
335
|
+
if (!entry || !this.sessionDir)
|
|
336
|
+
return;
|
|
337
|
+
writeFileSync(join(this.sessionDir, USER_MESSAGE_MAP), JSON.stringify({ ...readUserMessageMap(this.sessionDir), [messageId]: entry.id }), { mode: 0o600 });
|
|
338
|
+
});
|
|
339
|
+
}
|
|
292
340
|
translate(event) {
|
|
293
341
|
switch (event.type) {
|
|
294
342
|
case "agent_start":
|
|
@@ -304,6 +352,8 @@ export class PiSession {
|
|
|
304
352
|
case "message_end":
|
|
305
353
|
this.emitMessage(event.message, true);
|
|
306
354
|
this.currentMessageId = undefined;
|
|
355
|
+
if (event.message.role === "user" && this.unmappedMessageIds.length)
|
|
356
|
+
this.mapUserMessage(this.unmappedMessageIds.shift(), event.message);
|
|
307
357
|
return;
|
|
308
358
|
case "tool_execution_start":
|
|
309
359
|
this.emit({ type: "tool_started", callId: event.toolCallId, name: event.toolName, input: event.args });
|
|
@@ -331,7 +381,7 @@ export class PiSession {
|
|
|
331
381
|
return;
|
|
332
382
|
}
|
|
333
383
|
case "agent_settled":
|
|
334
|
-
this.finishTurn(this.aborting ? "aborted" : this.turnReason);
|
|
384
|
+
this.finishTurn(event.aborted || this.aborting ? "aborted" : this.turnReason);
|
|
335
385
|
return;
|
|
336
386
|
case "auto_retry_start":
|
|
337
387
|
this.emit({
|
|
@@ -400,11 +450,26 @@ export class PiSession {
|
|
|
400
450
|
this.emit({ type: "thinking", id: `${id}-thinking`, text: thinking, final });
|
|
401
451
|
}
|
|
402
452
|
reportContextUsage() {
|
|
453
|
+
this.countSpend();
|
|
403
454
|
const usage = this.session.getContextUsage();
|
|
404
455
|
if (usage && typeof usage.tokens === "number") {
|
|
405
|
-
this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow });
|
|
456
|
+
this.emit({ type: "context_usage", used: usage.tokens, window: usage.contextWindow, ...(this.spend ? { spend: this.spend } : {}) });
|
|
406
457
|
}
|
|
407
458
|
}
|
|
459
|
+
countSpend() {
|
|
460
|
+
const now = statsOf(this.session);
|
|
461
|
+
const added = { tokens: now.tokens - this.counted.tokens, cached: now.cached - this.counted.cached, costUSD: now.costUSD - this.counted.costUSD };
|
|
462
|
+
this.counted = now;
|
|
463
|
+
if (added.tokens <= 0 && added.costUSD <= 0)
|
|
464
|
+
return;
|
|
465
|
+
const id = this.session.model ? describeModel(this.session.model).id : "unknown";
|
|
466
|
+
const spend = this.spend ?? { tokens: 0, cached: 0, costUSD: 0, models: [] };
|
|
467
|
+
const model = spend.models.find((item) => item.id === id) ?? { id, tokens: 0, cached: 0, costUSD: 0 };
|
|
468
|
+
this.spend = {
|
|
469
|
+
tokens: spend.tokens + added.tokens, cached: spend.cached + added.cached, costUSD: spend.costUSD + added.costUSD,
|
|
470
|
+
models: [...spend.models.filter((item) => item.id !== id), { id, tokens: model.tokens + added.tokens, cached: model.cached + added.cached, costUSD: model.costUSD + added.costUSD }],
|
|
471
|
+
};
|
|
472
|
+
}
|
|
408
473
|
}
|
|
409
474
|
export class PiBackend {
|
|
410
475
|
name = "pi";
|
|
@@ -414,10 +479,16 @@ export class PiBackend {
|
|
|
414
479
|
}
|
|
415
480
|
async create(options) {
|
|
416
481
|
const agentDir = getAgentDir();
|
|
482
|
+
const modelRuntime = options.piAuth
|
|
483
|
+
? await createWorkerPiModelRuntime(options.piAuth, join(agentDir, "models.json"), options.signal, {
|
|
484
|
+
...(options.stateDir ? { modelsStorePath: join(options.stateDir, 'models-store.json') } : {}),
|
|
485
|
+
discovery: options.refreshModels ? 'refresh' : 'automatic',
|
|
486
|
+
})
|
|
487
|
+
: undefined;
|
|
417
488
|
// Extensions are not loaded: they expect pi's own UI surface, and a background session that
|
|
418
489
|
// registers UI hooks has nowhere to render them.
|
|
419
490
|
const builder = options.workflowBuilder;
|
|
420
|
-
const settingsManager = builder ? SettingsManager.inMemory() : SettingsManager.create(options.scope, agentDir);
|
|
491
|
+
const settingsManager = builder ? SettingsManager.inMemory({ cacheWarming: "streaming" }) : SettingsManager.create(options.scope, agentDir);
|
|
421
492
|
const agentPermissions = builder || options.tools === "none" ? undefined : new PiAgentPermissions(options.permissionMode ?? "always", options.standingAuthorisations ?? [], options.emit);
|
|
422
493
|
const resourceLoader = new DefaultResourceLoader({
|
|
423
494
|
cwd: options.scope,
|
|
@@ -430,7 +501,9 @@ export class PiBackend {
|
|
|
430
501
|
appendSystemPromptOverride: () => [],
|
|
431
502
|
systemPromptOverride: () => builder.instructions,
|
|
432
503
|
} : {
|
|
504
|
+
appendSystemPromptOverride: (base) => [...base, DIFF_EXCERPT_INSTRUCTIONS],
|
|
433
505
|
extensionFactories: [
|
|
506
|
+
streamingCacheWarming(settingsManager),
|
|
434
507
|
...(agentPermissions ? [agentPermissions.extension()] : []),
|
|
435
508
|
...(options.compactionModelId ? [compactionModelExtension(options.compactionModelId, (text) => options.emit({ type: "notice", level: "error", text }))] : []),
|
|
436
509
|
],
|
|
@@ -448,19 +521,22 @@ export class PiBackend {
|
|
|
448
521
|
const defaults = settingsManager.getDefaultTools() ?? ["read", "bash", "edit", "write"];
|
|
449
522
|
const builderTools = builder ? piWorkflowBuilderTools(builder) : [];
|
|
450
523
|
const tools = builder ? builderTools.map(tool => tool.name) : options.tools === "none" ? [] : [...(this.options.tools ?? [
|
|
451
|
-
...defaults, ASK_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
|
|
452
|
-
])];
|
|
524
|
+
...defaults, ASK_TOOL, TODO_TOOL, SUBAGENT_TOOL, ...(defaults.includes("bash") ? ["bash_output", "kill_shell"] : []),
|
|
525
|
+
])].filter((name) => !readOnlyDeniedTools(options.readOnly).includes(name));
|
|
453
526
|
const mcp = builder || options.tools === "none" ? undefined : options.mcp;
|
|
454
527
|
const workflowTools = workflowParentTools(builder || options.tools === "none" ? undefined : options.workflow);
|
|
455
|
-
|
|
528
|
+
const sessionTools = piSessionTools(builder || options.tools === "none" ? undefined : options.sessionTools);
|
|
529
|
+
tools.push(...workflowTools.map(tool => tool.name), ...sessionTools.map(tool => tool.name));
|
|
456
530
|
const enabled = (name) => tools.includes(name);
|
|
457
531
|
const enquiries = enabled(ASK_TOOL) ? new PiEnquiries(options.emit) : undefined;
|
|
458
532
|
const work = new PiWork(options.emit, (completion) => piSession.completed(completion));
|
|
459
533
|
const subagents = enabled(SUBAGENT_TOOL);
|
|
460
534
|
const customTools = builder ? builderTools : [
|
|
461
535
|
...workflowTools,
|
|
536
|
+
...sessionTools,
|
|
462
537
|
...backgroundTools(options.scope, settingsManager, work).filter((tool) => enabled(tool.name)),
|
|
463
538
|
...(enquiries ? [enquiries.tool] : []),
|
|
539
|
+
...(enabled(TODO_TOOL) ? [piTodoTool(options.emit)] : []),
|
|
464
540
|
...(subagents ? [subagentTool(work, (id, input, signal) => runSubagent(session, options.scope, agentDir, work, id, input, signal, options.emit, mcp, options.compactionModelId, agentPermissions))] : []),
|
|
465
541
|
];
|
|
466
542
|
const start = (current) => {
|
|
@@ -470,6 +546,7 @@ export class PiBackend {
|
|
|
470
546
|
agentDir,
|
|
471
547
|
resourceLoader,
|
|
472
548
|
settingsManager,
|
|
549
|
+
...(modelRuntime ? { modelRuntime } : {}),
|
|
473
550
|
customTools: [...customTools, ...mcpTools],
|
|
474
551
|
tools: [...tools, ...mcpTools.map((tool) => tool.name)],
|
|
475
552
|
...(current ? { sessionManager: current.sessionManager, modelRuntime: current.modelRuntime, thinkingLevel: current.thinkingLevel, ...(current.model ? { model: current.model } : {}) }
|
|
@@ -478,16 +555,26 @@ export class PiBackend {
|
|
|
478
555
|
});
|
|
479
556
|
};
|
|
480
557
|
let { session, extensionsResult } = await start();
|
|
558
|
+
if (options.resumeBefore && sessionDir) {
|
|
559
|
+
const entryId = readUserMessageMap(sessionDir)[options.resumeBefore];
|
|
560
|
+
if (!entryId) {
|
|
561
|
+
session.dispose();
|
|
562
|
+
throw new Error("This message cannot be rewound: pi has no record of it");
|
|
563
|
+
}
|
|
564
|
+
await session.navigateTree(entryId);
|
|
565
|
+
}
|
|
481
566
|
const extensionError = options.compactionModelId && compactionExtensionError(extensionsResult.errors);
|
|
482
567
|
if (extensionError) {
|
|
483
568
|
session.dispose();
|
|
484
569
|
throw new Error(`Could not load the Pi compaction model hook: ${extensionError}`);
|
|
485
570
|
}
|
|
486
571
|
const autoCompaction = structuredClone(options.autoCompaction);
|
|
487
|
-
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) } : {}) });
|
|
488
|
-
|
|
572
|
+
const piSession = new PiSession(session, options.emit, sessionDir, { workflowBuilder: !!builder, ...(mcp ? { mcp } : {}), work, subagents, standingAuthorisations: options.standingAuthorisations ?? [], ...(agentPermissions ? { agentPermissions } : {}), ...(options.priorSpend ? { priorSpend: options.priorSpend } : {}), autoCompaction: piAutoCompaction(settingsManager, autoCompaction), ...(autoCompaction ? { workflowAutoCompaction: autoCompaction } : {}), ...(options.compactionModelId ? { workflowCompactionModelId: options.compactionModelId } : {}), ...(enquiries ? { enquiries } : {}), ...(mcp ? { recreate: async (current) => (session = (await start(current)).session) } : {}) });
|
|
573
|
+
const modelId = options.modelId ?? (settingsManager.getDefaultProvider() === "azure-openai-responses" && settingsManager.getDefaultModel()
|
|
574
|
+
? `azure-openai-responses/${settingsManager.getDefaultModel()}` : undefined);
|
|
575
|
+
if (modelId) {
|
|
489
576
|
try {
|
|
490
|
-
await piSession.setModel(
|
|
577
|
+
await piSession.setModel(modelId);
|
|
491
578
|
}
|
|
492
579
|
catch (error) {
|
|
493
580
|
await piSession.dispose();
|
|
@@ -522,21 +609,27 @@ export class PiBackend {
|
|
|
522
609
|
return piSession;
|
|
523
610
|
}
|
|
524
611
|
}
|
|
612
|
+
function readOnlyDeniedTools(readOnly) {
|
|
613
|
+
if (!readOnly)
|
|
614
|
+
return [];
|
|
615
|
+
return ["edit", "write", ...(readOnly === "tools" ? ["bash", "bash_output", "kill_shell", "powershell"] : [])];
|
|
616
|
+
}
|
|
525
617
|
async function runSubagent(parent, scope, agentDir, work, id, input, signal, emit, mcp, compactionModelId, agentPermissions) {
|
|
526
618
|
const available = parent.modelRuntime.getAvailableSnapshot();
|
|
527
|
-
const model = input.model ? available
|
|
619
|
+
const model = input.model ? findPiModel(available, input.model) : parent.model;
|
|
528
620
|
if (!model)
|
|
529
|
-
throw new Error(
|
|
621
|
+
throw new Error(`${piModelUnavailable(input.model ?? "(inherited)")} Available: ${available.map((model) => describeModel(model).id).join(", ")}`);
|
|
530
622
|
const effort = (input.effort ?? parent.thinkingLevel);
|
|
531
|
-
const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_"));
|
|
623
|
+
const tools = [...new Set([...parent.getActiveToolNames(), ...piMcpTools(mcp).map((tool) => tool.name)])].filter((name) => name !== ASK_TOOL && name !== TODO_TOOL && name !== SUBAGENT_TOOL && !name.startsWith("workflow_") && !name.startsWith("session_"));
|
|
532
624
|
const settingsManager = SettingsManager.create(scope, agentDir);
|
|
533
625
|
const producer = { subagentId: id };
|
|
534
626
|
const resourceLoader = new DefaultResourceLoader({ cwd: scope, agentDir, settingsManager, noExtensions: true,
|
|
535
627
|
extensionFactories: [
|
|
628
|
+
streamingCacheWarming(settingsManager),
|
|
536
629
|
...(agentPermissions ? [agentPermissions.extension(producer)] : []),
|
|
537
630
|
...(compactionModelId ? [compactionModelExtension(compactionModelId, (text) => emit({ type: "notice", level: "error", text }))] : []),
|
|
538
631
|
],
|
|
539
|
-
appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents."] });
|
|
632
|
+
appendSystemPrompt: ["You are a Subagent. Complete the delegated work and return the result. If human input is needed, return that request to the parent. You cannot ask the human or create further Subagents.", DIFF_EXCERPT_INSTRUCTIONS] });
|
|
540
633
|
await resourceLoader.reload();
|
|
541
634
|
signal.throwIfAborted();
|
|
542
635
|
const { session: child, extensionsResult } = await createAgentSession({ cwd: scope, agentDir, model, modelRuntime: parent.modelRuntime,
|
|
@@ -584,7 +677,9 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
584
677
|
try {
|
|
585
678
|
signal.throwIfAborted();
|
|
586
679
|
await adapter.setEffort(effort);
|
|
680
|
+
work.refine(id, { model: describeModel(model).id, effort: child.thinkingLevel });
|
|
587
681
|
signal.throwIfAborted();
|
|
682
|
+
emit({ type: "subagent_instruction", id: `${id}:brief`, text: input.prompt, producer });
|
|
588
683
|
await adapter.prompt(input.prompt);
|
|
589
684
|
if (reason !== "complete")
|
|
590
685
|
throw new Error(failure ?? `Subagent ${reason}`);
|
|
@@ -598,6 +693,10 @@ async function runSubagent(parent, scope, agentDir, work, id, input, signal, emi
|
|
|
598
693
|
await work.stopOwnedCalls(id);
|
|
599
694
|
}
|
|
600
695
|
}
|
|
696
|
+
function readUserMessageMap(sessionDir) {
|
|
697
|
+
const path = join(sessionDir, USER_MESSAGE_MAP);
|
|
698
|
+
return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : {};
|
|
699
|
+
}
|
|
601
700
|
function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
602
701
|
// The SDK populates this auth-filtered snapshot before createAgentSession resolves. Every model is
|
|
603
702
|
// described directly: effort discovery is observational and must never switch the active model.
|
|
@@ -608,7 +707,8 @@ function capabilitiesOf(session, enquiries, subagents, permissions = true) {
|
|
|
608
707
|
models,
|
|
609
708
|
compaction: true,
|
|
610
709
|
autoCompaction: "model-change",
|
|
611
|
-
fork:
|
|
710
|
+
fork: true,
|
|
711
|
+
rewind: true,
|
|
612
712
|
subagents,
|
|
613
713
|
enquiries,
|
|
614
714
|
permissions,
|
|
@@ -645,3 +745,7 @@ function joinBlocks(content, kind) {
|
|
|
645
745
|
function isString(value) {
|
|
646
746
|
return typeof value === "string";
|
|
647
747
|
}
|
|
748
|
+
function statsOf(session) {
|
|
749
|
+
const stats = session.getSessionStats();
|
|
750
|
+
return { tokens: stats.tokens.total, cached: stats.tokens.cacheRead, costUSD: stats.cost };
|
|
751
|
+
}
|
|
@@ -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
|
+
}
|