operon-agents-core 0.1.0-alpha.29 → 0.1.0-alpha.30
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/dist/agent/profiles.d.ts +3 -0
- package/dist/agent/profiles.js +1 -0
- package/dist/agent/run-support.d.ts +2 -2
- package/dist/agent/run-support.js +3 -1
- package/dist/agent/runner.d.ts +8 -0
- package/dist/agent/runner.js +11 -4
- package/dist/agent/toolset.js +1 -1
- package/dist/agent/workflow/index.d.ts +1 -1
- package/dist/agent/workflow/index.js +1 -1
- package/dist/agent/workflow/structured.d.ts +2 -0
- package/dist/agent/workflow/structured.js +4 -0
- package/dist/agent/workflow/tool.js +5 -4
- package/dist/capabilities/skills/index.d.ts +1 -1
- package/dist/llm/decision-model.d.ts +5 -3
- package/dist/llm/decision-model.js +8 -3
- package/dist/llm/define-model.d.ts +9 -17
- package/dist/llm/define-model.js +9 -20
- package/dist/llm/index.d.ts +3 -3
- package/dist/llm/index.js +2 -2
- package/dist/llm/model-manager.d.ts +95 -0
- package/dist/llm/model-manager.js +233 -0
- package/dist/llm/model.d.ts +0 -1
- package/dist/llm/provider.d.ts +3 -0
- package/dist/llm/provider.js +3 -0
- package/dist/mcp/manager.d.ts +2 -2
- package/dist/mcp/manager.js +2 -2
- package/package.json +1 -1
- package/dist/llm/runtime.d.ts +0 -25
- package/dist/llm/runtime.js +0 -38
package/dist/agent/profiles.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
2
|
import type { ChatModel } from "../llm/define-model.ts";
|
|
3
|
+
import type { ModelSettings } from "../llm/model.ts";
|
|
3
4
|
import type { Tool } from "../tool/types.ts";
|
|
4
5
|
import { Agent } from "./agent.ts";
|
|
5
6
|
import type { SystemPromptContext } from "./instruction-context.ts";
|
|
@@ -61,6 +62,8 @@ export interface BuildAgentOptions {
|
|
|
61
62
|
* `Agent.maxStepsPerTurn`. Lets a host vary the cap per agent (and so per session) without
|
|
62
63
|
* standing up a second Runner. */
|
|
63
64
|
readonly maxStepsPerTurn?: number;
|
|
65
|
+
/** How the built agent's model should behave. See `Agent.modelSettings`. */
|
|
66
|
+
readonly modelSettings?: ModelSettings;
|
|
64
67
|
}
|
|
65
68
|
/** Turn a resolved profile into a runnable Agent whose system prompt renders from live context. */
|
|
66
69
|
export declare function buildAgentFromProfile<TContext = unknown>(profile: ResolvedAgentProfile, options?: BuildAgentOptions): Promise<Agent<TContext>>;
|
package/dist/agent/profiles.js
CHANGED
|
@@ -166,6 +166,7 @@ export async function buildAgentFromProfile(profile, options = {}) {
|
|
|
166
166
|
model,
|
|
167
167
|
tools: toolset,
|
|
168
168
|
...(options.maxStepsPerTurn !== undefined ? { maxStepsPerTurn: options.maxStepsPerTurn } : {}),
|
|
169
|
+
...(options.modelSettings !== undefined ? { modelSettings: options.modelSettings } : {}),
|
|
169
170
|
handoffDescription: profile.whenToUse ?? profile.description,
|
|
170
171
|
});
|
|
171
172
|
}
|
|
@@ -9,7 +9,7 @@ import type { AssistantMessage, Message } from "../protocol/index.ts";
|
|
|
9
9
|
import type { ModelSettings, ThinkingLevel } from "../llm/model.ts";
|
|
10
10
|
import type { AgentEventBody, EventSink } from "../events/index.ts";
|
|
11
11
|
import type { ConversationContext, HistoryChangeListener } from "../loop/context.ts";
|
|
12
|
-
import type { AgentRunContext } from "./agent.ts";
|
|
12
|
+
import type { Agent, AgentRunContext } from "./agent.ts";
|
|
13
13
|
import type { DeriveOptions, RunState, RunStatus } from "./runner.ts";
|
|
14
14
|
import type { TurnStopReason } from "../loop/types.ts";
|
|
15
15
|
/**
|
|
@@ -59,7 +59,7 @@ export declare function runCtxFor<TContext>(state: RunState<TContext>): AgentRun
|
|
|
59
59
|
* unless an override is given. This is the single place child frames are minted — the
|
|
60
60
|
* subagent, Agent, and Workflow tools all go through it.
|
|
61
61
|
*/
|
|
62
|
-
export declare function deriveChild<TContext>(parent: RunState<TContext>, opts: DeriveOptions): RunState<TContext>;
|
|
62
|
+
export declare function deriveChild<TContext>(parent: RunState<TContext>, opts: DeriveOptions, spawner: Pick<Agent<TContext>, "model">): RunState<TContext>;
|
|
63
63
|
/** Runs the turn-boundary injectors, appending their reminders to `context`, and returns each
|
|
64
64
|
* injector's token estimate so the context breakdown can break the framing out of `messages`. */
|
|
65
65
|
export declare function injectAtTurnBoundary<TContext>(state: RunState<TContext>, context: ConversationContext): Map<string, number>;
|
|
@@ -104,10 +104,12 @@ export function runCtxFor(state) {
|
|
|
104
104
|
* unless an override is given. This is the single place child frames are minted — the
|
|
105
105
|
* subagent, Agent, and Workflow tools all go through it.
|
|
106
106
|
*/
|
|
107
|
-
export function deriveChild(parent, opts) {
|
|
107
|
+
export function deriveChild(parent, opts, spawner) {
|
|
108
108
|
const frame = opts.resumeFrame;
|
|
109
|
+
const inheritedModel = spawner.model ?? parent.inheritedModel;
|
|
109
110
|
return {
|
|
110
111
|
...parent,
|
|
112
|
+
...(inheritedModel !== undefined ? { inheritedModel } : {}),
|
|
111
113
|
frameId: frame?.frameId ?? newInterruptionId("frame"),
|
|
112
114
|
agentInstanceId: frame?.agentInstanceId ?? opts.agentInstanceId ?? addressTail(opts.address),
|
|
113
115
|
parentFrameId: parent.frameId,
|
package/dist/agent/runner.d.ts
CHANGED
|
@@ -122,6 +122,12 @@ export interface RunOptions<TContext = unknown> {
|
|
|
122
122
|
readonly session?: Session;
|
|
123
123
|
/** Structured provenance for fresh input. Omit for an ordinary user prompt. */
|
|
124
124
|
readonly inputOrigin?: PromptOrigin;
|
|
125
|
+
/** Replaces `RunnerConfig.subagentProvider` for this run. `null` means no runtime subagents. */
|
|
126
|
+
readonly subagentProvider?: SubagentProvider<TContext> | null;
|
|
127
|
+
/** Replaces `RunnerConfig.maxConcurrentSubagents` for this run. */
|
|
128
|
+
readonly maxConcurrentSubagents?: number;
|
|
129
|
+
/** Replaces `RunnerConfig.workflowTool` for this run. */
|
|
130
|
+
readonly workflowTool?: boolean;
|
|
125
131
|
}
|
|
126
132
|
/**
|
|
127
133
|
* A run's runtime: the shared environment (session/store/environment/permission/…, one per
|
|
@@ -164,6 +170,8 @@ export interface RunState<TContext> {
|
|
|
164
170
|
currentTurnId?: string;
|
|
165
171
|
/** Tool call that spawned this (sub-)agent; surfaced on `agent_start`. Unset for root. */
|
|
166
172
|
readonly parentToolCallId?: string;
|
|
173
|
+
/** The model of the agent that spawned this frame, for a child that declares none. Unset for root. */
|
|
174
|
+
readonly inheritedModel?: string | ChatModel;
|
|
167
175
|
}
|
|
168
176
|
/** Overrides applied when forking a child runtime frame from a parent (see `deriveChild`). */
|
|
169
177
|
export interface DeriveOptions {
|
package/dist/agent/runner.js
CHANGED
|
@@ -502,6 +502,7 @@ export class Runner {
|
|
|
502
502
|
throw error;
|
|
503
503
|
}
|
|
504
504
|
const permission = session.permission;
|
|
505
|
+
const maxConcurrentSubagents = opts?.maxConcurrentSubagents ?? this.config.maxConcurrentSubagents;
|
|
505
506
|
const state = {
|
|
506
507
|
runId: interruption?.runId ?? newInterruptionId("run"),
|
|
507
508
|
frameId: frame?.frameId ?? newInterruptionId("frame"),
|
|
@@ -519,9 +520,9 @@ export class Runner {
|
|
|
519
520
|
store: session.store,
|
|
520
521
|
responder: session.responder,
|
|
521
522
|
background: session.background,
|
|
522
|
-
subagentProvider: this.config.subagentProvider,
|
|
523
|
-
...(
|
|
524
|
-
workflowTool: this.config.workflowTool,
|
|
523
|
+
subagentProvider: opts?.subagentProvider === null ? undefined : opts?.subagentProvider ?? this.config.subagentProvider,
|
|
524
|
+
...(maxConcurrentSubagents !== undefined ? { maxConcurrentSubagents } : {}),
|
|
525
|
+
workflowTool: opts?.workflowTool ?? this.config.workflowTool,
|
|
525
526
|
permission,
|
|
526
527
|
capabilities,
|
|
527
528
|
steer: session.steer,
|
|
@@ -828,8 +829,14 @@ class Engine {
|
|
|
828
829
|
}
|
|
829
830
|
return false;
|
|
830
831
|
}
|
|
832
|
+
/**
|
|
833
|
+
* The root frame runs on what the session was told to run on, else its agent's model. A child
|
|
834
|
+
* frame runs on the model it declares, else the session's, else its spawner's.
|
|
835
|
+
*/
|
|
831
836
|
async resolveModelFor(agent, state) {
|
|
832
|
-
const model = state.
|
|
837
|
+
const model = state.parentFrameId === undefined
|
|
838
|
+
? state.session.modelSetting ?? agent.model
|
|
839
|
+
: agent.model ?? state.session.modelSetting ?? state.inheritedModel;
|
|
833
840
|
if (!model)
|
|
834
841
|
throw new Error(`Agent "${agent.name}" has no model.`);
|
|
835
842
|
if (typeof model !== "string")
|
package/dist/agent/toolset.js
CHANGED
|
@@ -110,7 +110,7 @@ function makeSpawner(active, parent, providerAgents, runAgent) {
|
|
|
110
110
|
// Resolve a type to an Agent: prefer the static graph, then the runtime provider.
|
|
111
111
|
resolve: async (type) => subagents.find((sub) => sub.name === type) ?? (await parent.subagentProvider?.get(type)),
|
|
112
112
|
resolveInGraph: (root, key) => findAgentByName(root, key),
|
|
113
|
-
derive: (opts) => deriveChild(parent, opts),
|
|
113
|
+
derive: (opts) => deriveChild(parent, opts, active),
|
|
114
114
|
run: runAgent,
|
|
115
115
|
ctxFor: (childState) => runCtxFor(childState),
|
|
116
116
|
};
|
|
@@ -5,5 +5,5 @@ export type { WorkflowSnapshot, WorkflowSnapshotStatus, WorkflowRunDetails } fro
|
|
|
5
5
|
export { WorkflowManager } from "./manager.ts";
|
|
6
6
|
export { runWorkflow, type RunWorkflowResult, WorkflowAgentCapError, WorkflowBudgetExceededError, WorkflowAbortedError, } from "./runtime.ts";
|
|
7
7
|
export { workflowPrompt } from "./prompt.ts";
|
|
8
|
-
export { makeStructuredOutputTool, cloneAgentWithTool, validateValue, structuredInstruction, getValidator, type StructuredCapture, } from "./structured.ts";
|
|
8
|
+
export { makeStructuredOutputTool, cloneAgentWithModel, cloneAgentWithTool, validateValue, structuredInstruction, getValidator, type StructuredCapture, } from "./structured.ts";
|
|
9
9
|
//# sourceMappingURL=index.d.ts.map
|
|
@@ -4,5 +4,5 @@ export { WorkflowJournal, journalAddress } from "./journal.js";
|
|
|
4
4
|
export { WorkflowManager } from "./manager.js";
|
|
5
5
|
export { runWorkflow, WorkflowAgentCapError, WorkflowBudgetExceededError, WorkflowAbortedError, } from "./runtime.js";
|
|
6
6
|
export { workflowPrompt } from "./prompt.js";
|
|
7
|
-
export { makeStructuredOutputTool, cloneAgentWithTool, validateValue, structuredInstruction, getValidator, } from "./structured.js";
|
|
7
|
+
export { makeStructuredOutputTool, cloneAgentWithModel, cloneAgentWithTool, validateValue, structuredInstruction, getValidator, } from "./structured.js";
|
|
8
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -30,6 +30,8 @@ export declare function makeStructuredOutputTool(schema: Record<string, unknown>
|
|
|
30
30
|
};
|
|
31
31
|
/** Clone an agent, appending one extra tool (the StructuredOutput injector). */
|
|
32
32
|
export declare function cloneAgentWithTool<TContext>(sub: Agent<TContext>, extra: Tool): Agent<TContext>;
|
|
33
|
+
/** Clone an agent onto another model: the script's `agent(prompt, { model })`. */
|
|
34
|
+
export declare function cloneAgentWithModel<TContext>(sub: Agent<TContext>, model: string): Agent<TContext>;
|
|
33
35
|
/** Instruction appended to the prompt so the subagent knows to call the tool. */
|
|
34
36
|
export declare function structuredInstruction(schema: Record<string, unknown>): string;
|
|
35
37
|
//# sourceMappingURL=structured.d.ts.map
|
|
@@ -69,6 +69,10 @@ export function cloneAgentWithTool(sub, extra) {
|
|
|
69
69
|
maxStepsPerTurn: sub.maxStepsPerTurn,
|
|
70
70
|
});
|
|
71
71
|
}
|
|
72
|
+
/** Clone an agent onto another model: the script's `agent(prompt, { model })`. */
|
|
73
|
+
export function cloneAgentWithModel(sub, model) {
|
|
74
|
+
return new Agent({ ...sub, model });
|
|
75
|
+
}
|
|
72
76
|
/** Instruction appended to the prompt so the subagent knows to call the tool. */
|
|
73
77
|
export function structuredInstruction(schema) {
|
|
74
78
|
return ("\n\nIMPORTANT: When you have your answer, call the StructuredOutput tool exactly once " +
|
|
@@ -15,7 +15,7 @@ import { asTaskRegistrar } from "../../capabilities/background/registrar.js";
|
|
|
15
15
|
import { newAgentId } from "../subagent.js";
|
|
16
16
|
import { guardSubagentInput } from "../subagent-tools.js";
|
|
17
17
|
import { createWorktree } from "../worktree.js";
|
|
18
|
-
import { runWorkflow, parseWorkflow, WorkflowJournal, journalAddress, workflowPrompt, makeStructuredOutputTool, cloneAgentWithTool, validateValue, structuredInstruction, WORKFLOW_AGENT_TIMEOUT_MS, } from "./index.js";
|
|
18
|
+
import { runWorkflow, parseWorkflow, WorkflowJournal, journalAddress, workflowPrompt, makeStructuredOutputTool, cloneAgentWithTool, validateValue, cloneAgentWithModel, structuredInstruction, WORKFLOW_AGENT_TIMEOUT_MS, } from "./index.js";
|
|
19
19
|
/**
|
|
20
20
|
* The Workflow tool — a deterministic JS orchestration runtime over subagents.
|
|
21
21
|
* The script runs in a hardened VM (see workflow/sandbox.ts); its agent() hook spawns
|
|
@@ -38,11 +38,12 @@ export function buildWorkflowTool(spawner, parent) {
|
|
|
38
38
|
budget: { total: tokenBudget, getTurnSpent: () => baseline },
|
|
39
39
|
resolveWorkflowScript: (name) => readNamedWorkflow(parent.environment, name),
|
|
40
40
|
emitProgress,
|
|
41
|
-
runAgent: async ({ prompt, agentType, schema, isolation, signal, onStart }) => {
|
|
42
|
-
const
|
|
43
|
-
if (
|
|
41
|
+
runAgent: async ({ prompt, agentType, model, schema, isolation, signal, onStart }) => {
|
|
42
|
+
const found = await spawner.resolve(agentType ?? spawner.defaultType);
|
|
43
|
+
if (found === undefined) {
|
|
44
44
|
throw new Error(`unknown agentType "${agentType ?? spawner.defaultType}". Available: ${spawner.available.map((a) => a.name).join(", ")}`);
|
|
45
45
|
}
|
|
46
|
+
const sub = model === undefined ? found : cloneAgentWithModel(found, model);
|
|
46
47
|
const agentId = newAgentId(sub.name);
|
|
47
48
|
const address = joinAddress(parent.address, agentId);
|
|
48
49
|
// Publish + journal the stable identity before any work runs, so the orchestration
|
|
@@ -15,7 +15,7 @@ export type { ActivateSkillRequest, SkillActivationResult, SkillActivationTrigge
|
|
|
15
15
|
export { normalizeSkillName, isInlineSkillType, isFlowSkillType, isUserActivatableSkillType, isSupportedSkillType, summarizeSkill, } from "./types.ts";
|
|
16
16
|
export type { SkillCatalog, SkillDefinition, SkillMetadata, SkillSource, SkillSummary, SkillRoot, SkillPluginContext, SkippedSkill, FlowSkillExecutor, FlowSkillRequest, } from "./types.ts";
|
|
17
17
|
export interface SkillsOptions {
|
|
18
|
-
/** A pre-built registry — e.g. the harness's shared one (`
|
|
18
|
+
/** A pre-built registry — e.g. the harness's shared one (`HarnessInfrastructure.skillRegistry`). */
|
|
19
19
|
readonly registry?: SkillRegistry;
|
|
20
20
|
/** `false` = the registry is already loaded (the harness scanned it once); skip the per-session
|
|
21
21
|
* scan and only bind this session to it. Default `true`. */
|
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import type { ClassifierApi, ClassifierContext, ClassifierModel, ClassifierResult } from "@earendil-works/pi-ai";
|
|
2
|
-
import type {
|
|
2
|
+
import type { ModelManager } from "./model-manager.ts";
|
|
3
3
|
/**
|
|
4
4
|
* A structured decision model (Jev, Clef, OpenAI Decisions…): it answers fixed questions about a
|
|
5
5
|
* JSON state with probabilities and writes no text, so it has no place in a turn loop. It is a
|
|
6
6
|
* sibling of `ChatModel`, not a kind of it.
|
|
7
7
|
*/
|
|
8
8
|
export declare class DecisionModel {
|
|
9
|
-
private readonly
|
|
9
|
+
private readonly manager;
|
|
10
10
|
private readonly descriptor;
|
|
11
|
+
private readonly apiKey;
|
|
11
12
|
constructor(spec: {
|
|
12
|
-
readonly
|
|
13
|
+
readonly manager: ModelManager;
|
|
13
14
|
readonly descriptor: ClassifierModel<ClassifierApi>;
|
|
15
|
+
readonly apiKey?: string;
|
|
14
16
|
});
|
|
15
17
|
get id(): string;
|
|
16
18
|
/** Never rejects: a failed request comes back with `stopReason: "error"`. */
|
|
@@ -4,18 +4,23 @@
|
|
|
4
4
|
* sibling of `ChatModel`, not a kind of it.
|
|
5
5
|
*/
|
|
6
6
|
export class DecisionModel {
|
|
7
|
-
|
|
7
|
+
manager;
|
|
8
8
|
descriptor;
|
|
9
|
+
apiKey;
|
|
9
10
|
constructor(spec) {
|
|
10
|
-
this.
|
|
11
|
+
this.manager = spec.manager;
|
|
11
12
|
this.descriptor = spec.descriptor;
|
|
13
|
+
this.apiKey = spec.apiKey;
|
|
12
14
|
}
|
|
13
15
|
get id() {
|
|
14
16
|
return this.descriptor.id;
|
|
15
17
|
}
|
|
16
18
|
/** Never rejects: a failed request comes back with `stopReason: "error"`. */
|
|
17
19
|
classify(context, call) {
|
|
18
|
-
return this.
|
|
20
|
+
return this.manager.models.classify(this.descriptor, context, {
|
|
21
|
+
...call,
|
|
22
|
+
...(this.apiKey !== undefined ? { apiKey: this.apiKey } : {}),
|
|
23
|
+
});
|
|
19
24
|
}
|
|
20
25
|
}
|
|
21
26
|
//# sourceMappingURL=decision-model.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Api, AssistantMessage, AssistantMessageEventStream, Model, Provider, ProviderHeaders, Transport } from "../protocol/index.ts";
|
|
2
|
-
import { type
|
|
2
|
+
import { type ModelManager } from "./model-manager.ts";
|
|
3
3
|
import type { CallOptions, LlmRequest } from "./model.ts";
|
|
4
4
|
import { type RequestRetryPolicy } from "./request-retry.ts";
|
|
5
5
|
/**
|
|
@@ -15,7 +15,8 @@ import { type RequestRetryPolicy } from "./request-retry.ts";
|
|
|
15
15
|
* silent precedence rule between them. Anything absent from this interface is deliberate — add
|
|
16
16
|
* a field when a knob earns one, instead of reopening the bag.
|
|
17
17
|
*
|
|
18
|
-
*
|
|
18
|
+
* Set it for a whole provider with `ModelManager.register`, for one model with
|
|
19
|
+
* `ModelManager.resolve`, or on a `ChatModel` built directly.
|
|
19
20
|
*/
|
|
20
21
|
export interface ModelConnection {
|
|
21
22
|
/** Merged over provider and model defaults. A `null` value deletes a header pi would send. */
|
|
@@ -52,15 +53,17 @@ export interface ModelConnection {
|
|
|
52
53
|
/** WebSocket connect/open handshake budget; stream idleness still uses `timeoutMs`. */
|
|
53
54
|
readonly websocketConnectTimeoutMs?: number;
|
|
54
55
|
}
|
|
55
|
-
interface
|
|
56
|
-
|
|
56
|
+
export interface ModelSpec {
|
|
57
|
+
/** Owns the provider `descriptor` belongs to; every request goes through it. */
|
|
58
|
+
readonly manager: ModelManager;
|
|
59
|
+
readonly descriptor: Model<Api>;
|
|
57
60
|
/** Transport-tier settings applied to every request this model makes. */
|
|
58
61
|
readonly connection?: ModelConnection;
|
|
59
62
|
/**
|
|
60
63
|
* Credential for this model, for the common case of holding a key in code or config rather
|
|
61
64
|
* than in a `CredentialStore`.
|
|
62
65
|
*
|
|
63
|
-
* This OVERRIDES whatever the
|
|
66
|
+
* This OVERRIDES whatever the manager's credential store resolves for the provider,
|
|
64
67
|
* including a freshly refreshed OAuth token — passing it opts out of `forceRefreshOAuth`
|
|
65
68
|
* recovery for this model. Leave it unset to use ambient credentials (`ANTHROPIC_API_KEY`
|
|
66
69
|
* and friends) or a stored credential, which is what OAuth-based providers want.
|
|
@@ -71,15 +74,6 @@ interface ModelSpecBase {
|
|
|
71
74
|
*/
|
|
72
75
|
readonly apiKey?: string;
|
|
73
76
|
}
|
|
74
|
-
export type ModelSpec = (ModelSpecBase & {
|
|
75
|
-
readonly provider: string;
|
|
76
|
-
readonly model: string;
|
|
77
|
-
readonly baseUrl?: string;
|
|
78
|
-
}) | (ModelSpecBase & {
|
|
79
|
-
readonly descriptor: Model<Api>;
|
|
80
|
-
/** A descriptor needs the Models collection that owns its provider. */
|
|
81
|
-
readonly runtime: ModelRuntime;
|
|
82
|
-
});
|
|
83
77
|
export declare class ChatModel {
|
|
84
78
|
readonly id: string;
|
|
85
79
|
readonly provider: Provider;
|
|
@@ -92,7 +86,7 @@ export declare class ChatModel {
|
|
|
92
86
|
/** Loading a deferred tool mid-conversation keeps the request prefix: SearchTool mode. */
|
|
93
87
|
readonly supportsDeferredTools: boolean;
|
|
94
88
|
private readonly piModel;
|
|
95
|
-
private readonly
|
|
89
|
+
private readonly manager;
|
|
96
90
|
/** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
|
|
97
91
|
* Every request starts from these; `params` and `providerOptions` layer on top. */
|
|
98
92
|
private readonly requestDefaults;
|
|
@@ -110,11 +104,9 @@ export declare class ChatModel {
|
|
|
110
104
|
private errorMessage;
|
|
111
105
|
}
|
|
112
106
|
export declare function defineModel(spec: ModelSpec): ChatModel;
|
|
113
|
-
export declare function tryGetPiModel(provider: string, model: string, runtime?: ModelRuntime): Model<Api> | undefined;
|
|
114
107
|
/**
|
|
115
108
|
* Whether pi's direct Anthropic catalog flags this model, however the id is spelled:
|
|
116
109
|
* `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ...
|
|
117
110
|
*/
|
|
118
111
|
export declare function acceptsMidConvoToolChanges(modelId: string): boolean;
|
|
119
|
-
export {};
|
|
120
112
|
//# sourceMappingURL=define-model.d.ts.map
|
package/dist/llm/define-model.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
2
2
|
import { ANTHROPIC_MODELS } from "@earendil-works/pi-ai/providers/anthropic.models";
|
|
3
3
|
import { emptyUsage } from "../loop/usage.js";
|
|
4
|
-
import {
|
|
4
|
+
import { forceRefreshOAuth, } from "./model-manager.js";
|
|
5
5
|
import { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.js";
|
|
6
6
|
/** Node's longest timer, which is what "no cap" on a retry wait amounts to. */
|
|
7
7
|
const MAX_TIMER_MS = 2 ** 31 - 1;
|
|
@@ -27,15 +27,15 @@ export class ChatModel {
|
|
|
27
27
|
/** Loading a deferred tool mid-conversation keeps the request prefix: SearchTool mode. */
|
|
28
28
|
supportsDeferredTools;
|
|
29
29
|
piModel;
|
|
30
|
-
|
|
30
|
+
manager;
|
|
31
31
|
/** Build-time settings (`apiKey` + `connection`) flattened once into pi's option shape.
|
|
32
32
|
* Every request starts from these; `params` and `providerOptions` layer on top. */
|
|
33
33
|
requestDefaults;
|
|
34
34
|
/** Read by `streamWithRetry` and `completeWithRetry`, which own every retry. */
|
|
35
35
|
requestRetry;
|
|
36
36
|
constructor(spec) {
|
|
37
|
-
this.
|
|
38
|
-
this.piModel = withAnthropicToolChanges(
|
|
37
|
+
this.manager = spec.manager;
|
|
38
|
+
this.piModel = withAnthropicToolChanges(spec.descriptor);
|
|
39
39
|
const { maxRetries, maxRetryDelayMs, ...transport } = spec.connection ?? {};
|
|
40
40
|
this.requestRetry = {
|
|
41
41
|
...DEFAULT_REQUEST_RETRY_POLICY,
|
|
@@ -66,7 +66,7 @@ export class ChatModel {
|
|
|
66
66
|
const ctx = toContext(req);
|
|
67
67
|
let first;
|
|
68
68
|
try {
|
|
69
|
-
first = await this.
|
|
69
|
+
first = await this.manager.models.completeSimple(this.piModel, ctx, this.options(req, call));
|
|
70
70
|
}
|
|
71
71
|
catch (error) {
|
|
72
72
|
first = this.errorMessage(messageOf(error));
|
|
@@ -75,9 +75,9 @@ export class ChatModel {
|
|
|
75
75
|
return first;
|
|
76
76
|
}
|
|
77
77
|
try {
|
|
78
|
-
if (!(await forceRefreshOAuth(this.
|
|
78
|
+
if (!(await forceRefreshOAuth(this.manager, this.provider, call?.signal)))
|
|
79
79
|
return first;
|
|
80
|
-
return await this.
|
|
80
|
+
return await this.manager.models.completeSimple(this.piModel, ctx, this.options(req, call));
|
|
81
81
|
}
|
|
82
82
|
catch (error) {
|
|
83
83
|
return this.errorMessage(messageOf(error));
|
|
@@ -97,7 +97,7 @@ export class ChatModel {
|
|
|
97
97
|
// revoked-token recovery: one forced refresh after a clean pre-content 401.
|
|
98
98
|
if (isAuthError(first.errorMessage)) {
|
|
99
99
|
try {
|
|
100
|
-
if (!(await forceRefreshOAuth(this.
|
|
100
|
+
if (!(await forceRefreshOAuth(this.manager, this.provider, call?.signal))) {
|
|
101
101
|
out.push(first.terminal);
|
|
102
102
|
return;
|
|
103
103
|
}
|
|
@@ -119,7 +119,7 @@ export class ChatModel {
|
|
|
119
119
|
let streamedContent = false;
|
|
120
120
|
let terminal;
|
|
121
121
|
try {
|
|
122
|
-
for await (const event of this.
|
|
122
|
+
for await (const event of this.manager.models.streamSimple(this.piModel, ctx, this.options(req, call))) {
|
|
123
123
|
if (event.type === "done" || event.type === "error") {
|
|
124
124
|
terminal = event;
|
|
125
125
|
break;
|
|
@@ -207,17 +207,6 @@ function isAuthError(message) {
|
|
|
207
207
|
export function defineModel(spec) {
|
|
208
208
|
return new ChatModel(spec);
|
|
209
209
|
}
|
|
210
|
-
function resolvePiModel(spec, runtime) {
|
|
211
|
-
if ("descriptor" in spec)
|
|
212
|
-
return spec.descriptor;
|
|
213
|
-
const model = tryGetPiModel(spec.provider, spec.model, runtime);
|
|
214
|
-
if (!model)
|
|
215
|
-
throw new Error(`unknown model: ${spec.provider}/${spec.model}`);
|
|
216
|
-
return spec.baseUrl ? { ...model, baseUrl: spec.baseUrl } : model;
|
|
217
|
-
}
|
|
218
|
-
export function tryGetPiModel(provider, model, runtime = createModelRuntime()) {
|
|
219
|
-
return runtime.models.getModel(provider, model);
|
|
220
|
-
}
|
|
221
210
|
/**
|
|
222
211
|
* Mirror pi's gates for anchoring a `toolsAdded` system message in place, so Operon only
|
|
223
212
|
* hides capability tools when loading one will not rewrite the request prefix. Everywhere
|
package/dist/llm/index.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
export { streamResult } from "./model.ts";
|
|
2
2
|
export type { LlmRequest, CallOptions, HttpExchange, ModelSettings, ThinkingBudgets, ThinkingLevel, StreamResultOptions, } from "./model.ts";
|
|
3
|
-
export { ChatModel, defineModel
|
|
3
|
+
export { ChatModel, defineModel } from "./define-model.ts";
|
|
4
4
|
export { DecisionModel } from "./decision-model.ts";
|
|
5
5
|
export * from "./provider.ts";
|
|
6
6
|
export type { ModelConnection, ModelSpec } from "./define-model.ts";
|
|
7
|
-
export {
|
|
8
|
-
export type {
|
|
7
|
+
export { ModelManager, NO_KEY_PLACEHOLDER, PROVIDER_APIS, createModelManager, dialectStreams, endpointModel, forceRefreshOAuth } from "./model-manager.ts";
|
|
8
|
+
export type { CreateModelManagerOptions, EndpointModelFields, ModelProviderRegistration, ModelResolveOptions, ProviderApi } from "./model-manager.ts";
|
|
9
9
|
export { completeWithRetry, streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.ts";
|
|
10
10
|
export { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.ts";
|
|
11
11
|
export type { RequestRetryPolicy } from "./request-retry.ts";
|
package/dist/llm/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { streamResult } from "./model.js";
|
|
2
|
-
export { ChatModel, defineModel
|
|
2
|
+
export { ChatModel, defineModel } from "./define-model.js";
|
|
3
3
|
export { DecisionModel } from "./decision-model.js";
|
|
4
4
|
export * from "./provider.js";
|
|
5
|
-
export {
|
|
5
|
+
export { ModelManager, NO_KEY_PLACEHOLDER, PROVIDER_APIS, createModelManager, dialectStreams, endpointModel, forceRefreshOAuth } from "./model-manager.js";
|
|
6
6
|
export { completeWithRetry, streamWithRetry, DEFAULT_MAX_RETRIES_PER_STEP } from "./retry.js";
|
|
7
7
|
export { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.js";
|
|
8
8
|
export { InMemoryCredentialStore, MemoryCredentialStore, FileCredentialStore, } from "./auth.js";
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { type Api, type AuthContext, type CredentialStore, type Model, type ModelsStore, type MutableModels } from "@earendil-works/pi-ai";
|
|
2
|
+
import { DecisionModel } from "./decision-model.ts";
|
|
3
|
+
import { type ChatModel, type ModelConnection, type ModelSpec } from "./define-model.ts";
|
|
4
|
+
/** Settings for one resolved model, on top of what its provider registration says. */
|
|
5
|
+
export type ModelResolveOptions = Pick<ModelSpec, "apiKey" | "connection">;
|
|
6
|
+
/** The wire dialects a custom endpoint can speak. Almost everything speaks the first. */
|
|
7
|
+
export declare const PROVIDER_APIS: readonly ["openai-completions", "openai-responses", "anthropic-messages"];
|
|
8
|
+
export type ProviderApi = (typeof PROVIDER_APIS)[number];
|
|
9
|
+
/** pi's API implementations load on first use, so an unused dialect is never imported. */
|
|
10
|
+
export declare function dialectStreams(api: ProviderApi): import("@earendil-works/pi-ai").ProviderStreams;
|
|
11
|
+
/**
|
|
12
|
+
* A provider a host adds to its {@link ModelManager}. With `api` it is a custom endpoint; without
|
|
13
|
+
* it, it reuses a catalog provider (`extends`, or the one named `id`) under the host's key and
|
|
14
|
+
* address. The limit fields describe models the provider does not list.
|
|
15
|
+
*
|
|
16
|
+
* This is configuration, for what a host learns from its user: an address, a key, any model id. To
|
|
17
|
+
* state each model's facts yourself, build a pi provider with `createProvider` and add it through
|
|
18
|
+
* `manager.models.setProvider`; string ids resolve against it the same way.
|
|
19
|
+
*/
|
|
20
|
+
export interface ModelProviderRegistration extends Readonly<Partial<Pick<Model<Api>, "contextWindow" | "maxTokens" | "input" | "reasoning">>> {
|
|
21
|
+
/** The name before the `/` in a model id. Registering it again replaces the previous entry. */
|
|
22
|
+
readonly id: string;
|
|
23
|
+
readonly name?: string;
|
|
24
|
+
/** The catalog provider whose models and dialects this one uses. Defaults to `id`. */
|
|
25
|
+
readonly extends?: string;
|
|
26
|
+
/** Marks a custom endpoint and names its dialect. Requires `baseUrl`. */
|
|
27
|
+
readonly api?: ProviderApi;
|
|
28
|
+
/** Used exactly as given. Without it, the catalog says where each model lives. */
|
|
29
|
+
readonly baseUrl?: string;
|
|
30
|
+
/** Wins over a credential in the manager's store, which is used when this is unset. A key passed to `resolve` beats both. */
|
|
31
|
+
readonly apiKey?: string;
|
|
32
|
+
/** How every chat model of this provider reaches it. A field passed to `resolve` replaces the same field here. */
|
|
33
|
+
readonly connection?: ModelConnection;
|
|
34
|
+
/** The models a custom endpoint serves. */
|
|
35
|
+
readonly models?: readonly string[];
|
|
36
|
+
/** Accept model ids the provider does not list. Off by default, so a misspelled id is an error. */
|
|
37
|
+
readonly allowUnlisted?: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** What a keyless endpoint sends as its bearer token; the OpenAI dialect refuses to send none. */
|
|
40
|
+
export declare const NO_KEY_PLACEHOLDER = "unused";
|
|
41
|
+
/** The facts about a model no catalog describes. Anything left out takes a conservative default. */
|
|
42
|
+
export interface EndpointModelFields extends Pick<Model<Api>, "id" | "provider" | "api" | "baseUrl">, Partial<Pick<Model<Api>, "name" | "reasoning" | "input" | "contextWindow" | "maxTokens" | "headers">> {
|
|
43
|
+
}
|
|
44
|
+
/** A complete pi model descriptor from what is known about a model on a custom endpoint. */
|
|
45
|
+
export declare function endpointModel(fields: Readonly<EndpointModelFields>): Model<Api>;
|
|
46
|
+
/**
|
|
47
|
+
* The models one harness can run: provider catalog, credentials, request dispatch, and what a
|
|
48
|
+
* `provider/model` id resolves to. Customize it in place with {@link register}.
|
|
49
|
+
*
|
|
50
|
+
* pi keeps one credential per provider, so a registered key is per provider too. A host that needs
|
|
51
|
+
* a different key per user passes it to {@link resolve} and hands the session that `ChatModel`.
|
|
52
|
+
*/
|
|
53
|
+
export declare class ModelManager {
|
|
54
|
+
readonly models: MutableModels;
|
|
55
|
+
readonly credentials: CredentialStore;
|
|
56
|
+
private readonly registrations;
|
|
57
|
+
constructor(options?: CreateModelManagerOptions);
|
|
58
|
+
/** Add or replace a provider. Sessions running on string ids pick it up on their next turn. */
|
|
59
|
+
register(registration: ModelProviderRegistration): void;
|
|
60
|
+
/** Remove a registration. A catalog provider it overrode goes back to its defaults. */
|
|
61
|
+
unregister(id: string): void;
|
|
62
|
+
/**
|
|
63
|
+
* The `ChatModel` a `provider/model` id names. Throws when the id names nothing. `options` apply
|
|
64
|
+
* to this one model, which is how a host gives each of its users their own key.
|
|
65
|
+
*/
|
|
66
|
+
resolve(id: string, options?: ModelResolveOptions): ChatModel;
|
|
67
|
+
/**
|
|
68
|
+
* The decision model a `provider/model` id names, or undefined when it names anything else. An
|
|
69
|
+
* id catalogued as both a decision model and an LLM counts as an LLM. Decision models exist only
|
|
70
|
+
* at the catalog's endpoints, so a provider registered at another address has none: its key must
|
|
71
|
+
* not be sent there.
|
|
72
|
+
*/
|
|
73
|
+
resolveDecision(id: string, options?: Pick<ModelResolveOptions, "apiKey">): DecisionModel | undefined;
|
|
74
|
+
private registerEndpoint;
|
|
75
|
+
}
|
|
76
|
+
export interface CreateModelManagerOptions {
|
|
77
|
+
readonly credentials?: CredentialStore;
|
|
78
|
+
readonly modelsStore?: ModelsStore;
|
|
79
|
+
readonly authContext?: AuthContext;
|
|
80
|
+
/** Register pi's full built-in provider catalog. Defaults to true. */
|
|
81
|
+
readonly builtins?: boolean;
|
|
82
|
+
}
|
|
83
|
+
/** Create one provider/auth/catalog manager to be shared by related ChatModels. */
|
|
84
|
+
export declare function createModelManager(options?: CreateModelManagerOptions): ModelManager;
|
|
85
|
+
/**
|
|
86
|
+
* Force one OAuth refresh after a clean 401 for a non-expired but revoked
|
|
87
|
+
* token. pi automatically refreshes expired credentials; this preserves
|
|
88
|
+
* Operon's additional revoked-token recovery policy.
|
|
89
|
+
*
|
|
90
|
+
* `signal` should be the in-flight request's: this runs inside the credential store's
|
|
91
|
+
* per-provider lock, so a refresh that hangs blocks every other request for that provider
|
|
92
|
+
* until it settles. Omitting it leaves the refresh unbounded.
|
|
93
|
+
*/
|
|
94
|
+
export declare function forceRefreshOAuth(runtime: ModelManager, providerId: string, signal?: AbortSignal): Promise<boolean>;
|
|
95
|
+
//# sourceMappingURL=model-manager.d.ts.map
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { InMemoryCredentialStore, InMemoryModelsStore, createModels, createProvider, } from "@earendil-works/pi-ai";
|
|
2
|
+
import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
|
|
3
|
+
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
|
|
4
|
+
import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
|
|
5
|
+
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
6
|
+
import { DecisionModel } from "./decision-model.js";
|
|
7
|
+
import { defineModel } from "./define-model.js";
|
|
8
|
+
/** The wire dialects a custom endpoint can speak. Almost everything speaks the first. */
|
|
9
|
+
export const PROVIDER_APIS = ["openai-completions", "openai-responses", "anthropic-messages"];
|
|
10
|
+
/** pi's API implementations load on first use, so an unused dialect is never imported. */
|
|
11
|
+
export function dialectStreams(api) {
|
|
12
|
+
switch (api) {
|
|
13
|
+
case "anthropic-messages":
|
|
14
|
+
return anthropicMessagesApi();
|
|
15
|
+
case "openai-responses":
|
|
16
|
+
return openAIResponsesApi();
|
|
17
|
+
case "openai-completions":
|
|
18
|
+
return openAICompletionsApi();
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** A `provider/model` id's two halves. A model id may itself contain slashes. */
|
|
22
|
+
function splitModelId(id) {
|
|
23
|
+
const slash = id.indexOf("/");
|
|
24
|
+
if (slash <= 0 || slash === id.length - 1)
|
|
25
|
+
return undefined;
|
|
26
|
+
return { providerId: id.slice(0, slash), modelId: id.slice(slash + 1) };
|
|
27
|
+
}
|
|
28
|
+
function sameAddress(a, b) {
|
|
29
|
+
return a.replace(/\/+$/, "") === b.replace(/\/+$/, "");
|
|
30
|
+
}
|
|
31
|
+
/** Zero cost: an unlisted or self-hosted model has no known price, and a wrong number is worse. */
|
|
32
|
+
const NO_COST = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
|
33
|
+
/** What a keyless endpoint sends as its bearer token; the OpenAI dialect refuses to send none. */
|
|
34
|
+
export const NO_KEY_PLACEHOLDER = "unused";
|
|
35
|
+
/** A complete pi model descriptor from what is known about a model on a custom endpoint. */
|
|
36
|
+
export function endpointModel(fields) {
|
|
37
|
+
const { id, name, provider, api, baseUrl, reasoning, input, contextWindow, maxTokens, headers } = fields;
|
|
38
|
+
return {
|
|
39
|
+
id,
|
|
40
|
+
name: name ?? id,
|
|
41
|
+
api,
|
|
42
|
+
provider,
|
|
43
|
+
baseUrl,
|
|
44
|
+
reasoning: reasoning ?? false,
|
|
45
|
+
input: [...(input ?? ["text"])],
|
|
46
|
+
cost: NO_COST,
|
|
47
|
+
contextWindow: contextWindow ?? 128_000,
|
|
48
|
+
maxTokens: maxTokens ?? 8_192,
|
|
49
|
+
...(headers !== undefined ? { headers } : {}),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function limitsOf({ reasoning, input, contextWindow, maxTokens }) {
|
|
53
|
+
return { reasoning, input, contextWindow, maxTokens };
|
|
54
|
+
}
|
|
55
|
+
function customModel(registration, api, modelId) {
|
|
56
|
+
return endpointModel({
|
|
57
|
+
...limitsOf(registration),
|
|
58
|
+
id: modelId,
|
|
59
|
+
provider: registration.id,
|
|
60
|
+
api: api,
|
|
61
|
+
baseUrl: registration.baseUrl ?? "",
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function withRegisteredConnection(registration, options) {
|
|
65
|
+
if (registration?.connection === undefined)
|
|
66
|
+
return options;
|
|
67
|
+
return { ...options, connection: { ...registration.connection, ...options.connection } };
|
|
68
|
+
}
|
|
69
|
+
/** An id newer than a catalog provider's list runs on the API of that provider's default endpoint. */
|
|
70
|
+
function unlistedCatalogModel(provider, registration, modelId) {
|
|
71
|
+
const models = provider.getModels();
|
|
72
|
+
const template = models.find((model) => model.baseUrl === provider.baseUrl) ?? models[0];
|
|
73
|
+
if (template === undefined)
|
|
74
|
+
throw new Error(`Provider "${provider.id}" lists no models to run "${modelId}" like.`);
|
|
75
|
+
return endpointModel({
|
|
76
|
+
...limitsOf(registration),
|
|
77
|
+
id: modelId,
|
|
78
|
+
provider: provider.id,
|
|
79
|
+
api: template.api,
|
|
80
|
+
baseUrl: template.baseUrl,
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The models one harness can run: provider catalog, credentials, request dispatch, and what a
|
|
85
|
+
* `provider/model` id resolves to. Customize it in place with {@link register}.
|
|
86
|
+
*
|
|
87
|
+
* pi keeps one credential per provider, so a registered key is per provider too. A host that needs
|
|
88
|
+
* a different key per user passes it to {@link resolve} and hands the session that `ChatModel`.
|
|
89
|
+
*/
|
|
90
|
+
export class ModelManager {
|
|
91
|
+
models;
|
|
92
|
+
credentials;
|
|
93
|
+
registrations = new Map();
|
|
94
|
+
constructor(options = {}) {
|
|
95
|
+
this.credentials = options.credentials ?? new InMemoryCredentialStore();
|
|
96
|
+
const modelOptions = {
|
|
97
|
+
credentials: this.credentials,
|
|
98
|
+
modelsStore: options.modelsStore ?? new InMemoryModelsStore(),
|
|
99
|
+
...(options.authContext !== undefined ? { authContext: options.authContext } : {}),
|
|
100
|
+
};
|
|
101
|
+
this.models = options.builtins === false
|
|
102
|
+
? createModels(modelOptions)
|
|
103
|
+
: builtinModels(modelOptions);
|
|
104
|
+
}
|
|
105
|
+
/** Add or replace a provider. Sessions running on string ids pick it up on their next turn. */
|
|
106
|
+
register(registration) {
|
|
107
|
+
if (registration.api !== undefined) {
|
|
108
|
+
this.registerEndpoint(registration, registration.api);
|
|
109
|
+
}
|
|
110
|
+
else if (this.models.getProvider(registration.extends ?? registration.id) === undefined) {
|
|
111
|
+
throw new Error(`Provider "${registration.extends ?? registration.id}" is not in the catalog. Set \`api\` and \`baseUrl\` for a custom endpoint.`);
|
|
112
|
+
}
|
|
113
|
+
this.registrations.set(registration.id, registration);
|
|
114
|
+
}
|
|
115
|
+
/** Remove a registration. A catalog provider it overrode goes back to its defaults. */
|
|
116
|
+
unregister(id) {
|
|
117
|
+
const registration = this.registrations.get(id);
|
|
118
|
+
if (registration === undefined)
|
|
119
|
+
return;
|
|
120
|
+
if (registration.api !== undefined)
|
|
121
|
+
this.models.deleteProvider(id);
|
|
122
|
+
this.registrations.delete(id);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The `ChatModel` a `provider/model` id names. Throws when the id names nothing. `options` apply
|
|
126
|
+
* to this one model, which is how a host gives each of its users their own key.
|
|
127
|
+
*/
|
|
128
|
+
resolve(id, options = {}) {
|
|
129
|
+
const parts = splitModelId(id);
|
|
130
|
+
if (parts === undefined)
|
|
131
|
+
throw new Error(`Model id "${id}" must be "provider/model".`);
|
|
132
|
+
const { providerId, modelId } = parts;
|
|
133
|
+
const registration = this.registrations.get(providerId);
|
|
134
|
+
if (registration?.api !== undefined) {
|
|
135
|
+
const listed = this.models.getModel(providerId, modelId);
|
|
136
|
+
if (listed === undefined && registration.allowUnlisted !== true)
|
|
137
|
+
throw new Error(`unknown model: ${id}`);
|
|
138
|
+
return defineModel({ ...withRegisteredConnection(registration, options), manager: this, descriptor: listed ?? customModel(registration, registration.api, modelId) });
|
|
139
|
+
}
|
|
140
|
+
// Stays under the catalog provider's own id: pi's dialects adjust requests by provider.
|
|
141
|
+
const catalogId = registration?.extends ?? providerId;
|
|
142
|
+
const provider = this.models.getProvider(catalogId);
|
|
143
|
+
if (provider === undefined)
|
|
144
|
+
throw new Error(`unknown model: ${id}`);
|
|
145
|
+
const listed = this.models.getModel(catalogId, modelId);
|
|
146
|
+
if (listed === undefined && registration?.allowUnlisted !== true)
|
|
147
|
+
throw new Error(`unknown model: ${id}`);
|
|
148
|
+
const descriptor = listed ?? unlistedCatalogModel(provider, registration, modelId);
|
|
149
|
+
return defineModel({
|
|
150
|
+
...(registration?.apiKey !== undefined ? { apiKey: registration.apiKey } : {}),
|
|
151
|
+
...withRegisteredConnection(registration, options),
|
|
152
|
+
manager: this,
|
|
153
|
+
descriptor: registration?.baseUrl === undefined ? descriptor : { ...descriptor, baseUrl: registration.baseUrl },
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* The decision model a `provider/model` id names, or undefined when it names anything else. An
|
|
158
|
+
* id catalogued as both a decision model and an LLM counts as an LLM. Decision models exist only
|
|
159
|
+
* at the catalog's endpoints, so a provider registered at another address has none: its key must
|
|
160
|
+
* not be sent there.
|
|
161
|
+
*/
|
|
162
|
+
resolveDecision(id, options = {}) {
|
|
163
|
+
const parts = splitModelId(id);
|
|
164
|
+
if (parts === undefined)
|
|
165
|
+
return undefined;
|
|
166
|
+
const registration = this.registrations.get(parts.providerId);
|
|
167
|
+
if (registration?.api !== undefined)
|
|
168
|
+
return undefined;
|
|
169
|
+
const catalogId = registration?.extends ?? parts.providerId;
|
|
170
|
+
if (this.models.getModel(catalogId, parts.modelId) !== undefined)
|
|
171
|
+
return undefined;
|
|
172
|
+
const descriptor = this.models.getModelOfType("classifier", catalogId, parts.modelId);
|
|
173
|
+
if (descriptor === undefined)
|
|
174
|
+
return undefined;
|
|
175
|
+
if (registration?.baseUrl !== undefined && !sameAddress(registration.baseUrl, descriptor.baseUrl))
|
|
176
|
+
return undefined;
|
|
177
|
+
const apiKey = options.apiKey ?? registration?.apiKey;
|
|
178
|
+
return new DecisionModel({ manager: this, descriptor, ...(apiKey !== undefined ? { apiKey } : {}) });
|
|
179
|
+
}
|
|
180
|
+
registerEndpoint(registration, api) {
|
|
181
|
+
const { id, baseUrl, apiKey } = registration;
|
|
182
|
+
if (baseUrl === undefined)
|
|
183
|
+
throw new Error(`Custom provider "${id}" needs a \`baseUrl\`.`);
|
|
184
|
+
const name = registration.name ?? id;
|
|
185
|
+
this.models.setProvider(createProvider({
|
|
186
|
+
id,
|
|
187
|
+
name,
|
|
188
|
+
baseUrl,
|
|
189
|
+
auth: {
|
|
190
|
+
apiKey: {
|
|
191
|
+
name: `${name} API key`,
|
|
192
|
+
resolve: async ({ credential, signal }) => {
|
|
193
|
+
signal.throwIfAborted();
|
|
194
|
+
if (apiKey !== undefined)
|
|
195
|
+
return { auth: { apiKey }, source: "registered" };
|
|
196
|
+
if (credential?.key)
|
|
197
|
+
return { auth: { apiKey: credential.key }, source: "stored credential" };
|
|
198
|
+
return { auth: { apiKey: NO_KEY_PLACEHOLDER }, source: baseUrl };
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
models: (registration.models ?? []).map((modelId) => customModel(registration, api, modelId)),
|
|
203
|
+
api: dialectStreams(api),
|
|
204
|
+
}));
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
/** Create one provider/auth/catalog manager to be shared by related ChatModels. */
|
|
208
|
+
export function createModelManager(options = {}) {
|
|
209
|
+
return new ModelManager(options);
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Force one OAuth refresh after a clean 401 for a non-expired but revoked
|
|
213
|
+
* token. pi automatically refreshes expired credentials; this preserves
|
|
214
|
+
* Operon's additional revoked-token recovery policy.
|
|
215
|
+
*
|
|
216
|
+
* `signal` should be the in-flight request's: this runs inside the credential store's
|
|
217
|
+
* per-provider lock, so a refresh that hangs blocks every other request for that provider
|
|
218
|
+
* until it settles. Omitting it leaves the refresh unbounded.
|
|
219
|
+
*/
|
|
220
|
+
export async function forceRefreshOAuth(runtime, providerId, signal) {
|
|
221
|
+
const oauth = runtime.models.getProvider(providerId)?.auth.oauth;
|
|
222
|
+
if (oauth === undefined)
|
|
223
|
+
return false;
|
|
224
|
+
let refreshed = false;
|
|
225
|
+
await runtime.credentials.modify(providerId, async (current) => {
|
|
226
|
+
if (current?.type !== "oauth")
|
|
227
|
+
return undefined;
|
|
228
|
+
refreshed = true;
|
|
229
|
+
return oauth.refresh(current, signal ?? new AbortController().signal);
|
|
230
|
+
});
|
|
231
|
+
return refreshed;
|
|
232
|
+
}
|
|
233
|
+
//# sourceMappingURL=model-manager.js.map
|
package/dist/llm/model.d.ts
CHANGED
|
@@ -31,7 +31,6 @@ export interface HttpExchange {
|
|
|
31
31
|
}
|
|
32
32
|
export interface CallOptions {
|
|
33
33
|
readonly signal?: AbortSignal;
|
|
34
|
-
readonly timeoutMs?: number;
|
|
35
34
|
/**
|
|
36
35
|
* Called after every HTTP request, failed ones included, unlike pi's `onResponse`. Not called
|
|
37
36
|
* for APIs that accept no custom `fetch`: Google, Vertex and Bedrock.
|
package/dist/llm/provider.d.ts
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
* fetched, or both) and the wire dialect it speaks; `MutableModels.setProvider` registers it on a
|
|
8
8
|
* runtime, and everything downstream — `defineModel`, `Models.getAvailable`, the harness's
|
|
9
9
|
* `registerProvider` — treats it exactly like a built-in one.
|
|
10
|
+
*
|
|
11
|
+
* Use this to state each model's facts yourself. `ModelManager.register` is the shorter path for
|
|
12
|
+
* plain configuration: an address, a key, and model ids that may not be known in advance.
|
|
10
13
|
*/
|
|
11
14
|
export { createProvider, createModels } from "@earendil-works/pi-ai";
|
|
12
15
|
export { envApiKeyAuth } from "@earendil-works/pi-ai";
|
package/dist/llm/provider.js
CHANGED
|
@@ -7,6 +7,9 @@
|
|
|
7
7
|
* fetched, or both) and the wire dialect it speaks; `MutableModels.setProvider` registers it on a
|
|
8
8
|
* runtime, and everything downstream — `defineModel`, `Models.getAvailable`, the harness's
|
|
9
9
|
* `registerProvider` — treats it exactly like a built-in one.
|
|
10
|
+
*
|
|
11
|
+
* Use this to state each model's facts yourself. `ModelManager.register` is the shorter path for
|
|
12
|
+
* plain configuration: an address, a key, and model ids that may not be known in advance.
|
|
10
13
|
*/
|
|
11
14
|
export { createProvider, createModels } from "@earendil-works/pi-ai";
|
|
12
15
|
export { envApiKeyAuth } from "@earendil-works/pi-ai";
|
package/dist/mcp/manager.d.ts
CHANGED
|
@@ -17,7 +17,7 @@ export type McpTransportKind = "stdio" | "http";
|
|
|
17
17
|
* pushed out to a sandbox. On a single-tenant local host that is exactly right. On a server it
|
|
18
18
|
* is four problems at once:
|
|
19
19
|
*
|
|
20
|
-
* - LIFECYCLE. `
|
|
20
|
+
* - LIFECYCLE. `HarnessInfrastructure.mcpServers` is "one set of connections per process", which holds
|
|
21
21
|
* inside one process and stops holding the moment the server runs as more than one replica:
|
|
22
22
|
* each replica spawns its own children, and a rolling restart takes them with it.
|
|
23
23
|
* - FAULT DOMAIN. A leaking or crashing `npx`-launched server takes down a process that is
|
|
@@ -127,7 +127,7 @@ export interface McpServersHandle {
|
|
|
127
127
|
export declare function assertMcpTransportsPermitted(configs: Record<string, McpServerConfig>, allowed: readonly McpTransportKind[] | undefined): void;
|
|
128
128
|
/**
|
|
129
129
|
* The controller set behind a group of configured servers — buildable on its own so a HARNESS
|
|
130
|
-
* can hold one set of connections for every session it serves (`
|
|
130
|
+
* can hold one set of connections for every session it serves (`HarnessInfrastructure.mcpServers`), or a session can
|
|
131
131
|
* own a private set (`mcpServersCapability`). Nothing connects until `handle.connect()`.
|
|
132
132
|
*
|
|
133
133
|
* Transport admission is checked HERE, while the set is being built, and not where the
|
package/dist/mcp/manager.js
CHANGED
|
@@ -13,7 +13,7 @@ import { McpServerConfigSchema } from "../config/schema.js";
|
|
|
13
13
|
* pushed out to a sandbox. On a single-tenant local host that is exactly right. On a server it
|
|
14
14
|
* is four problems at once:
|
|
15
15
|
*
|
|
16
|
-
* - LIFECYCLE. `
|
|
16
|
+
* - LIFECYCLE. `HarnessInfrastructure.mcpServers` is "one set of connections per process", which holds
|
|
17
17
|
* inside one process and stops holding the moment the server runs as more than one replica:
|
|
18
18
|
* each replica spawns its own children, and a rolling restart takes them with it.
|
|
19
19
|
* - FAULT DOMAIN. A leaking or crashing `npx`-launched server takes down a process that is
|
|
@@ -507,7 +507,7 @@ export function assertMcpTransportsPermitted(configs, allowed) {
|
|
|
507
507
|
}
|
|
508
508
|
/**
|
|
509
509
|
* The controller set behind a group of configured servers — buildable on its own so a HARNESS
|
|
510
|
-
* can hold one set of connections for every session it serves (`
|
|
510
|
+
* can hold one set of connections for every session it serves (`HarnessInfrastructure.mcpServers`), or a session can
|
|
511
511
|
* own a private set (`mcpServersCapability`). Nothing connects until `handle.connect()`.
|
|
512
512
|
*
|
|
513
513
|
* Transport admission is checked HERE, while the set is being built, and not where the
|
package/package.json
CHANGED
package/dist/llm/runtime.d.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { type AuthContext, type CredentialStore, type ModelsStore, type MutableModels } from "@earendil-works/pi-ai";
|
|
2
|
-
export interface ModelRuntime {
|
|
3
|
-
readonly models: MutableModels;
|
|
4
|
-
readonly credentials: CredentialStore;
|
|
5
|
-
}
|
|
6
|
-
export interface CreateModelRuntimeOptions {
|
|
7
|
-
readonly credentials?: CredentialStore;
|
|
8
|
-
readonly modelsStore?: ModelsStore;
|
|
9
|
-
readonly authContext?: AuthContext;
|
|
10
|
-
/** Register pi's full built-in provider catalog. Defaults to true. */
|
|
11
|
-
readonly builtins?: boolean;
|
|
12
|
-
}
|
|
13
|
-
/** Create one provider/auth/catalog runtime to be shared by related ChatModels. */
|
|
14
|
-
export declare function createModelRuntime(options?: CreateModelRuntimeOptions): ModelRuntime;
|
|
15
|
-
/**
|
|
16
|
-
* Force one OAuth refresh after a clean 401 for a non-expired but revoked
|
|
17
|
-
* token. pi automatically refreshes expired credentials; this preserves
|
|
18
|
-
* Operon's additional revoked-token recovery policy.
|
|
19
|
-
*
|
|
20
|
-
* `signal` should be the in-flight request's: this runs inside the credential store's
|
|
21
|
-
* per-provider lock, so a refresh that hangs blocks every other request for that provider
|
|
22
|
-
* until it settles. Omitting it leaves the refresh unbounded.
|
|
23
|
-
*/
|
|
24
|
-
export declare function forceRefreshOAuth(runtime: ModelRuntime, providerId: string, signal?: AbortSignal): Promise<boolean>;
|
|
25
|
-
//# sourceMappingURL=runtime.d.ts.map
|
package/dist/llm/runtime.js
DELETED
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
import { InMemoryCredentialStore, InMemoryModelsStore, createModels, } from "@earendil-works/pi-ai";
|
|
2
|
-
import { builtinModels } from "@earendil-works/pi-ai/providers/all";
|
|
3
|
-
/** Create one provider/auth/catalog runtime to be shared by related ChatModels. */
|
|
4
|
-
export function createModelRuntime(options = {}) {
|
|
5
|
-
const credentials = options.credentials ?? new InMemoryCredentialStore();
|
|
6
|
-
const modelOptions = {
|
|
7
|
-
credentials,
|
|
8
|
-
modelsStore: options.modelsStore ?? new InMemoryModelsStore(),
|
|
9
|
-
...(options.authContext !== undefined ? { authContext: options.authContext } : {}),
|
|
10
|
-
};
|
|
11
|
-
const models = options.builtins === false
|
|
12
|
-
? createModels(modelOptions)
|
|
13
|
-
: builtinModels(modelOptions);
|
|
14
|
-
return { models, credentials };
|
|
15
|
-
}
|
|
16
|
-
/**
|
|
17
|
-
* Force one OAuth refresh after a clean 401 for a non-expired but revoked
|
|
18
|
-
* token. pi automatically refreshes expired credentials; this preserves
|
|
19
|
-
* Operon's additional revoked-token recovery policy.
|
|
20
|
-
*
|
|
21
|
-
* `signal` should be the in-flight request's: this runs inside the credential store's
|
|
22
|
-
* per-provider lock, so a refresh that hangs blocks every other request for that provider
|
|
23
|
-
* until it settles. Omitting it leaves the refresh unbounded.
|
|
24
|
-
*/
|
|
25
|
-
export async function forceRefreshOAuth(runtime, providerId, signal) {
|
|
26
|
-
const oauth = runtime.models.getProvider(providerId)?.auth.oauth;
|
|
27
|
-
if (oauth === undefined)
|
|
28
|
-
return false;
|
|
29
|
-
let refreshed = false;
|
|
30
|
-
await runtime.credentials.modify(providerId, async (current) => {
|
|
31
|
-
if (current?.type !== "oauth")
|
|
32
|
-
return undefined;
|
|
33
|
-
refreshed = true;
|
|
34
|
-
return oauth.refresh(current, signal ?? new AbortController().signal);
|
|
35
|
-
});
|
|
36
|
-
return refreshed;
|
|
37
|
-
}
|
|
38
|
-
//# sourceMappingURL=runtime.js.map
|