operon-agents-core 0.1.0-alpha.28 → 0.1.0-alpha.29
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/recovery.js +2 -2
- package/dist/agent/run-support.js +2 -7
- package/dist/agent/runner.js +1 -1
- package/dist/capabilities/compaction/full.js +2 -2
- package/dist/config/index.d.ts +2 -6
- package/dist/config/index.js +1 -3
- package/dist/config/merge.js +0 -6
- package/dist/config/resolver.d.ts +0 -3
- package/dist/config/resolver.js +0 -3
- package/dist/config/schema.d.ts +0 -98
- package/dist/config/schema.js +0 -44
- package/dist/llm/define-model.d.ts +5 -4
- package/dist/llm/define-model.js +14 -34
- package/dist/llm/model.d.ts +7 -14
- package/dist/llm/retry.js +1 -1
- package/dist/loop/tool-call.js +15 -0
- package/dist/loop/turn-step.js +2 -2
- package/dist/permission/auto-approver/llm-auto-approver.js +1 -1
- package/dist/tool/builtin/read.js +18 -7
- package/dist/tracing/otel.js +1 -1
- package/package.json +1 -1
- package/dist/config/model-catalog.d.ts +0 -17
- package/dist/config/model-catalog.js +0 -37
- package/dist/config/provider-manager.d.ts +0 -64
- package/dist/config/provider-manager.js +0 -345
package/dist/agent/recovery.js
CHANGED
|
@@ -46,9 +46,9 @@ export async function withToolCallRecoveryContext(state, request) {
|
|
|
46
46
|
const reminder = lines.join("\n");
|
|
47
47
|
return {
|
|
48
48
|
...request,
|
|
49
|
-
|
|
49
|
+
systemPrompt: request.systemPrompt === undefined || request.systemPrompt.length === 0
|
|
50
50
|
? reminder
|
|
51
|
-
: `${request.
|
|
51
|
+
: `${request.systemPrompt}\n\n${reminder}`,
|
|
52
52
|
};
|
|
53
53
|
}
|
|
54
54
|
function findBackgroundByOrigin(value, parentAddress, toolCallId) {
|
|
@@ -83,13 +83,8 @@ export function historyChangeEmitter(events, sessionId) {
|
|
|
83
83
|
* stay exactly as they were.
|
|
84
84
|
*/
|
|
85
85
|
export function resolveModelParams(settings, sessionThinking) {
|
|
86
|
-
const
|
|
87
|
-
const params = {
|
|
88
|
-
...(settings?.temperature !== undefined ? { temperature: settings.temperature } : {}),
|
|
89
|
-
...(settings?.maxTokens !== undefined ? { maxTokens: settings.maxTokens } : {}),
|
|
90
|
-
...(thinking !== undefined ? { thinking } : {}),
|
|
91
|
-
...(settings?.thinkingBudgets !== undefined ? { thinkingBudgets: settings.thinkingBudgets } : {}),
|
|
92
|
-
};
|
|
86
|
+
const reasoning = sessionThinking ?? settings?.reasoning;
|
|
87
|
+
const params = { ...settings, ...(reasoning !== undefined ? { reasoning } : {}) };
|
|
93
88
|
return Object.keys(params).length > 0 ? params : undefined;
|
|
94
89
|
}
|
|
95
90
|
/** The run context handed to agent-facing callbacks (instructions/guardrails/onHandoff). */
|
package/dist/agent/runner.js
CHANGED
|
@@ -656,7 +656,7 @@ class Engine {
|
|
|
656
656
|
deferEnabled: toolset.deferEnabled,
|
|
657
657
|
onToolsPrepared: (tools) => { permissionTools = tools; },
|
|
658
658
|
onRequestPrepared: (request) => stampBreakdown({
|
|
659
|
-
system: request.
|
|
659
|
+
system: request.systemPrompt,
|
|
660
660
|
tools: (request.tools ?? []).map((schema) => ({ schema })),
|
|
661
661
|
messages: request.messages,
|
|
662
662
|
}),
|
|
@@ -104,13 +104,13 @@ async function summarize(deps, initialCount) {
|
|
|
104
104
|
deps.signal.throwIfAborted();
|
|
105
105
|
const prefix = deps.messages.slice(0, count);
|
|
106
106
|
const request = {
|
|
107
|
-
|
|
107
|
+
systemPrompt: deps.system,
|
|
108
108
|
messages: [...prefix, instructionUserMessage(instruction)],
|
|
109
109
|
tools: undefined,
|
|
110
110
|
};
|
|
111
111
|
logger.log("debug", "compaction llm request", logDataPolicy.dontLogModelData
|
|
112
112
|
? { model: deps.model.id, attempt, count, messages: request.messages.length }
|
|
113
|
-
: { model: deps.model.id, attempt, count, system: request.
|
|
113
|
+
: { model: deps.model.id, attempt, count, system: request.systemPrompt, messages: request.messages });
|
|
114
114
|
let summaryText = "";
|
|
115
115
|
let truncatedOrError = false;
|
|
116
116
|
try {
|
package/dist/config/index.d.ts
CHANGED
|
@@ -1,10 +1,6 @@
|
|
|
1
|
-
export { AgentFrameworkConfigSchema,
|
|
2
|
-
export type { AgentFrameworkConfig, HookDefConfig, LoopControl, McpServerConfig, McpOAuthClientConfig,
|
|
1
|
+
export { AgentFrameworkConfigSchema, McpServerConfigSchema, PermissionRuleConfigSchema, parseConfig, } from "./schema.ts";
|
|
2
|
+
export type { AgentFrameworkConfig, HookDefConfig, LoopControl, McpServerConfig, McpOAuthClientConfig, PermissionConfig, PermissionRuleConfig, PluginRef, ThinkingConfig, } from "./schema.ts";
|
|
3
3
|
export { mergeConfigs } from "./merge.ts";
|
|
4
|
-
export { ModelCatalog } from "./model-catalog.ts";
|
|
5
|
-
export type { ModelCapabilityInfo } from "./model-catalog.ts";
|
|
6
|
-
export { ProviderManager } from "./provider-manager.ts";
|
|
7
|
-
export type { ResolvedModel, ResolvableAlias, ApiKeyResolver, ProviderManagerConfig, ProviderManagerOptions, } from "./provider-manager.ts";
|
|
8
4
|
export { Flags, FLAG_DEFINITIONS } from "./flags.ts";
|
|
9
5
|
export type { FlagDefinition } from "./flags.ts";
|
|
10
6
|
export { objectResolver, layeredResolver, toCoreOptions, resolveCoreOptions, } from "./resolver.ts";
|
package/dist/config/index.js
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
export { AgentFrameworkConfigSchema,
|
|
1
|
+
export { AgentFrameworkConfigSchema, McpServerConfigSchema, PermissionRuleConfigSchema, parseConfig, } from "./schema.js";
|
|
2
2
|
export { mergeConfigs } from "./merge.js";
|
|
3
|
-
export { ModelCatalog } from "./model-catalog.js";
|
|
4
|
-
export { ProviderManager } from "./provider-manager.js";
|
|
5
3
|
export { Flags, FLAG_DEFINITIONS } from "./flags.js";
|
|
6
4
|
export { objectResolver, layeredResolver, toCoreOptions, resolveCoreOptions, } from "./resolver.js";
|
|
7
5
|
export { resolveConfigLayers } from "./paths.js";
|
package/dist/config/merge.js
CHANGED
|
@@ -17,10 +17,6 @@ function mergeRecord(base, over) {
|
|
|
17
17
|
}
|
|
18
18
|
function mergeOne(base, layer) {
|
|
19
19
|
return {
|
|
20
|
-
providers: mergeRecord(base.providers, layer.providers),
|
|
21
|
-
models: mergeRecord(base.models, layer.models),
|
|
22
|
-
defaultModel: layer.defaultModel ?? base.defaultModel,
|
|
23
|
-
modelCredentials: layer.modelCredentials ?? base.modelCredentials,
|
|
24
20
|
permission: {
|
|
25
21
|
mode: layer.permission?.mode ?? base.permission.mode,
|
|
26
22
|
// Concatenate rules across layers — scope encodes the originating tier.
|
|
@@ -41,8 +37,6 @@ function dedupe(values) {
|
|
|
41
37
|
return [...new Set(values)];
|
|
42
38
|
}
|
|
43
39
|
const EMPTY = {
|
|
44
|
-
providers: {},
|
|
45
|
-
models: {},
|
|
46
40
|
permission: { rules: [] },
|
|
47
41
|
loopControl: {},
|
|
48
42
|
mcpServers: {},
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import type { HookDef } from "../capabilities/user-hooks/types.ts";
|
|
2
2
|
import type { PermissionMode, PermissionRule } from "../permission/types.ts";
|
|
3
|
-
import { ModelCatalog } from "./model-catalog.ts";
|
|
4
3
|
import { Flags } from "./flags.ts";
|
|
5
4
|
import { type AgentFrameworkConfig, type ThinkingConfig } from "./schema.ts";
|
|
6
5
|
export interface ConfigResolver {
|
|
@@ -25,9 +24,7 @@ export interface CoreOptions {
|
|
|
25
24
|
readonly maxRetriesPerStep?: number;
|
|
26
25
|
readonly maxTurns?: number;
|
|
27
26
|
};
|
|
28
|
-
readonly catalog: ModelCatalog;
|
|
29
27
|
readonly flags: Flags;
|
|
30
|
-
readonly defaultModel?: string;
|
|
31
28
|
readonly thinking?: ThinkingConfig;
|
|
32
29
|
/** Plugin marketplace registry locations (URLs / paths) the product may browse. */
|
|
33
30
|
readonly pluginMarketplaces: readonly string[];
|
package/dist/config/resolver.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { hookDefsFromConfig } from "../plugins/hooks.js";
|
|
2
2
|
import { mergeConfigs } from "./merge.js";
|
|
3
|
-
import { ModelCatalog } from "./model-catalog.js";
|
|
4
3
|
import { Flags } from "./flags.js";
|
|
5
4
|
import { parseConfig } from "./schema.js";
|
|
6
5
|
export function objectResolver(config) {
|
|
@@ -37,9 +36,7 @@ export function toCoreOptions(config) {
|
|
|
37
36
|
maxRetriesPerStep: config.loopControl.maxRetriesPerStep,
|
|
38
37
|
maxTurns: config.loopControl.maxTurns,
|
|
39
38
|
},
|
|
40
|
-
catalog: new ModelCatalog(config.models),
|
|
41
39
|
flags: new Flags(config.flags),
|
|
42
|
-
defaultModel: config.defaultModel,
|
|
43
40
|
thinking: config.thinking,
|
|
44
41
|
pluginMarketplaces: config.pluginMarketplaces,
|
|
45
42
|
hooks: hookDefsFromConfig(config.hooks),
|
package/dist/config/schema.d.ts
CHANGED
|
@@ -1,61 +1,4 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
export declare const ProviderTypeSchema: z.ZodEnum<{
|
|
3
|
-
openai: "openai";
|
|
4
|
-
anthropic: "anthropic";
|
|
5
|
-
kimi: "kimi";
|
|
6
|
-
"google-genai": "google-genai";
|
|
7
|
-
openai_responses: "openai_responses";
|
|
8
|
-
vertexai: "vertexai";
|
|
9
|
-
}>;
|
|
10
|
-
export declare const ProviderOAuthSchema: z.ZodObject<{
|
|
11
|
-
storage: z.ZodEnum<{
|
|
12
|
-
file: "file";
|
|
13
|
-
keyring: "keyring";
|
|
14
|
-
}>;
|
|
15
|
-
key: z.ZodString;
|
|
16
|
-
oauthHost: z.ZodOptional<z.ZodString>;
|
|
17
|
-
}, z.core.$strip>;
|
|
18
|
-
export declare const ProviderConfigSchema: z.ZodObject<{
|
|
19
|
-
type: z.ZodEnum<{
|
|
20
|
-
openai: "openai";
|
|
21
|
-
anthropic: "anthropic";
|
|
22
|
-
kimi: "kimi";
|
|
23
|
-
"google-genai": "google-genai";
|
|
24
|
-
openai_responses: "openai_responses";
|
|
25
|
-
vertexai: "vertexai";
|
|
26
|
-
}>;
|
|
27
|
-
apiKey: z.ZodOptional<z.ZodString>;
|
|
28
|
-
baseUrl: z.ZodOptional<z.ZodString>;
|
|
29
|
-
defaultModel: z.ZodOptional<z.ZodString>;
|
|
30
|
-
oauth: z.ZodOptional<z.ZodObject<{
|
|
31
|
-
storage: z.ZodEnum<{
|
|
32
|
-
file: "file";
|
|
33
|
-
keyring: "keyring";
|
|
34
|
-
}>;
|
|
35
|
-
key: z.ZodString;
|
|
36
|
-
oauthHost: z.ZodOptional<z.ZodString>;
|
|
37
|
-
}, z.core.$strip>>;
|
|
38
|
-
env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
39
|
-
customHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
40
|
-
}, z.core.$strip>;
|
|
41
|
-
export declare const ModelAliasSchema: z.ZodObject<{
|
|
42
|
-
provider: z.ZodString;
|
|
43
|
-
model: z.ZodString;
|
|
44
|
-
maxContextSize: z.ZodNumber;
|
|
45
|
-
maxOutputSize: z.ZodOptional<z.ZodNumber>;
|
|
46
|
-
capabilities: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
47
|
-
displayName: z.ZodOptional<z.ZodString>;
|
|
48
|
-
reasoningKey: z.ZodOptional<z.ZodString>;
|
|
49
|
-
adaptiveThinking: z.ZodOptional<z.ZodBoolean>;
|
|
50
|
-
}, z.core.$strip>;
|
|
51
|
-
/**
|
|
52
|
-
* Persistent model-provider credentials. A configured path selects Operon's
|
|
53
|
-
* FileCredentialStore; deployments may still inject a different store
|
|
54
|
-
* directly into ProviderManager.
|
|
55
|
-
*/
|
|
56
|
-
export declare const ModelCredentialsSchema: z.ZodObject<{
|
|
57
|
-
path: z.ZodString;
|
|
58
|
-
}, z.core.$strip>;
|
|
59
2
|
export declare const PermissionRuleScopeSchema: z.ZodEnum<{
|
|
60
3
|
user: "user";
|
|
61
4
|
"turn-override": "turn-override";
|
|
@@ -237,43 +180,6 @@ export declare const PluginRefSchema: z.ZodObject<{
|
|
|
237
180
|
enabled: z.ZodDefault<z.ZodBoolean>;
|
|
238
181
|
}, z.core.$strip>;
|
|
239
182
|
export declare const AgentFrameworkConfigSchema: z.ZodObject<{
|
|
240
|
-
providers: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
241
|
-
type: z.ZodEnum<{
|
|
242
|
-
openai: "openai";
|
|
243
|
-
anthropic: "anthropic";
|
|
244
|
-
kimi: "kimi";
|
|
245
|
-
"google-genai": "google-genai";
|
|
246
|
-
openai_responses: "openai_responses";
|
|
247
|
-
vertexai: "vertexai";
|
|
248
|
-
}>;
|
|
249
|
-
apiKey: z.ZodOptional<z.ZodString>;
|
|
250
|
-
baseUrl: z.ZodOptional<z.ZodString>;
|
|
251
|
-
defaultModel: z.ZodOptional<z.ZodString>;
|
|
252
|
-
oauth: z.ZodOptional<z.ZodObject<{
|
|
253
|
-
storage: z.ZodEnum<{
|
|
254
|
-
file: "file";
|
|
255
|
-
keyring: "keyring";
|
|
256
|
-
}>;
|
|
257
|
-
key: z.ZodString;
|
|
258
|
-
oauthHost: z.ZodOptional<z.ZodString>;
|
|
259
|
-
}, z.core.$strip>>;
|
|
260
|
-
env: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
261
|
-
customHeaders: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
262
|
-
}, z.core.$strip>>>;
|
|
263
|
-
models: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
|
|
264
|
-
provider: z.ZodString;
|
|
265
|
-
model: z.ZodString;
|
|
266
|
-
maxContextSize: z.ZodNumber;
|
|
267
|
-
maxOutputSize: z.ZodOptional<z.ZodNumber>;
|
|
268
|
-
capabilities: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
269
|
-
displayName: z.ZodOptional<z.ZodString>;
|
|
270
|
-
reasoningKey: z.ZodOptional<z.ZodString>;
|
|
271
|
-
adaptiveThinking: z.ZodOptional<z.ZodBoolean>;
|
|
272
|
-
}, z.core.$strip>>>;
|
|
273
|
-
defaultModel: z.ZodOptional<z.ZodString>;
|
|
274
|
-
modelCredentials: z.ZodOptional<z.ZodObject<{
|
|
275
|
-
path: z.ZodString;
|
|
276
|
-
}, z.core.$strip>>;
|
|
277
183
|
permission: z.ZodDefault<z.ZodObject<{
|
|
278
184
|
mode: z.ZodOptional<z.ZodEnum<{
|
|
279
185
|
auto: "auto";
|
|
@@ -420,10 +326,6 @@ export declare const AgentFrameworkConfigSchema: z.ZodObject<{
|
|
|
420
326
|
pluginMarketplaces: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
421
327
|
flags: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
|
|
422
328
|
}, z.core.$strip>;
|
|
423
|
-
export type ProviderType = z.infer<typeof ProviderTypeSchema>;
|
|
424
|
-
export type ProviderConfig = z.infer<typeof ProviderConfigSchema>;
|
|
425
|
-
export type ModelAlias = z.infer<typeof ModelAliasSchema>;
|
|
426
|
-
export type ModelCredentialsConfig = z.infer<typeof ModelCredentialsSchema>;
|
|
427
329
|
export type PermissionRuleScope = z.infer<typeof PermissionRuleScopeSchema>;
|
|
428
330
|
export type PermissionRuleConfig = z.infer<typeof PermissionRuleConfigSchema>;
|
|
429
331
|
export type PermissionConfig = z.infer<typeof PermissionConfigSchema>;
|
package/dist/config/schema.js
CHANGED
|
@@ -1,44 +1,4 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
export const ProviderTypeSchema = z.enum([
|
|
3
|
-
"anthropic",
|
|
4
|
-
"openai",
|
|
5
|
-
"kimi",
|
|
6
|
-
"google-genai",
|
|
7
|
-
"openai_responses",
|
|
8
|
-
"vertexai",
|
|
9
|
-
]);
|
|
10
|
-
export const ProviderOAuthSchema = z.object({
|
|
11
|
-
storage: z.enum(["file", "keyring"]),
|
|
12
|
-
key: z.string(),
|
|
13
|
-
oauthHost: z.string().optional(),
|
|
14
|
-
});
|
|
15
|
-
export const ProviderConfigSchema = z.object({
|
|
16
|
-
type: ProviderTypeSchema,
|
|
17
|
-
apiKey: z.string().optional(),
|
|
18
|
-
baseUrl: z.string().optional(),
|
|
19
|
-
defaultModel: z.string().optional(),
|
|
20
|
-
oauth: ProviderOAuthSchema.optional(),
|
|
21
|
-
env: z.record(z.string(), z.string()).optional(),
|
|
22
|
-
customHeaders: z.record(z.string(), z.string()).optional(),
|
|
23
|
-
});
|
|
24
|
-
export const ModelAliasSchema = z.object({
|
|
25
|
-
provider: z.string(),
|
|
26
|
-
model: z.string(),
|
|
27
|
-
maxContextSize: z.number().int().positive(),
|
|
28
|
-
maxOutputSize: z.number().int().positive().optional(),
|
|
29
|
-
capabilities: z.array(z.string()).optional(),
|
|
30
|
-
displayName: z.string().optional(),
|
|
31
|
-
reasoningKey: z.string().optional(),
|
|
32
|
-
adaptiveThinking: z.boolean().optional(),
|
|
33
|
-
});
|
|
34
|
-
/**
|
|
35
|
-
* Persistent model-provider credentials. A configured path selects Operon's
|
|
36
|
-
* FileCredentialStore; deployments may still inject a different store
|
|
37
|
-
* directly into ProviderManager.
|
|
38
|
-
*/
|
|
39
|
-
export const ModelCredentialsSchema = z.object({
|
|
40
|
-
path: z.string().trim().min(1),
|
|
41
|
-
});
|
|
42
2
|
export const PermissionRuleScopeSchema = z.enum(["turn-override", "session-runtime", "project", "user"]);
|
|
43
3
|
export const PermissionRuleConfigSchema = z.object({
|
|
44
4
|
decision: z.enum(["allow", "deny", "ask"]),
|
|
@@ -170,10 +130,6 @@ export const PluginRefSchema = z.object({
|
|
|
170
130
|
enabled: z.boolean().default(true),
|
|
171
131
|
});
|
|
172
132
|
export const AgentFrameworkConfigSchema = z.object({
|
|
173
|
-
providers: z.record(z.string(), ProviderConfigSchema).default({}),
|
|
174
|
-
models: z.record(z.string(), ModelAliasSchema).default({}),
|
|
175
|
-
defaultModel: z.string().optional(),
|
|
176
|
-
modelCredentials: ModelCredentialsSchema.optional(),
|
|
177
133
|
permission: PermissionConfigSchema.default({ rules: [] }),
|
|
178
134
|
loopControl: LoopControlSchema.default({}),
|
|
179
135
|
thinking: ThinkingConfigSchema.optional(),
|
|
@@ -15,9 +15,7 @@ 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
|
-
*
|
|
19
|
-
* settings through provider and model descriptor headers; this is the programmatic equivalent
|
|
20
|
-
* for callers building a `ChatModel` directly.
|
|
18
|
+
* This is for callers building a `ChatModel` directly.
|
|
21
19
|
*/
|
|
22
20
|
export interface ModelConnection {
|
|
23
21
|
/** Merged over provider and model defaults. A `null` value deletes a header pi would send. */
|
|
@@ -113,7 +111,10 @@ export declare class ChatModel {
|
|
|
113
111
|
}
|
|
114
112
|
export declare function defineModel(spec: ModelSpec): ChatModel;
|
|
115
113
|
export declare function tryGetPiModel(provider: string, model: string, runtime?: ModelRuntime): Model<Api> | undefined;
|
|
116
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Whether pi's direct Anthropic catalog flags this model, however the id is spelled:
|
|
116
|
+
* `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ...
|
|
117
|
+
*/
|
|
117
118
|
export declare function acceptsMidConvoToolChanges(modelId: string): boolean;
|
|
118
119
|
export {};
|
|
119
120
|
//# sourceMappingURL=define-model.d.ts.map
|
package/dist/llm/define-model.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
|
|
2
|
+
import { ANTHROPIC_MODELS } from "@earendil-works/pi-ai/providers/anthropic.models";
|
|
2
3
|
import { emptyUsage } from "../loop/usage.js";
|
|
3
4
|
import { createModelRuntime, forceRefreshOAuth, } from "./runtime.js";
|
|
4
5
|
import { DEFAULT_REQUEST_RETRY_POLICY } from "./request-retry.js";
|
|
@@ -241,10 +242,10 @@ function supportsNativeDeferredTools(model) {
|
|
|
241
242
|
}
|
|
242
243
|
}
|
|
243
244
|
/**
|
|
244
|
-
*
|
|
245
|
-
*
|
|
246
|
-
*
|
|
247
|
-
*
|
|
245
|
+
* pi's catalog flags mid-conversation `tool_addition` support only on direct Anthropic models,
|
|
246
|
+
* though the same model takes them through a gateway or proxy on the Anthropic wire (Sonnet 5.5
|
|
247
|
+
* verified through OpenRouter). Carry that flag over to the models it leaves unset. An explicit
|
|
248
|
+
* flag always wins.
|
|
248
249
|
*/
|
|
249
250
|
function withAnthropicToolChanges(model) {
|
|
250
251
|
if (model.api !== "anthropic-messages")
|
|
@@ -261,26 +262,18 @@ function withAnthropicToolChanges(model) {
|
|
|
261
262
|
},
|
|
262
263
|
};
|
|
263
264
|
}
|
|
264
|
-
/**
|
|
265
|
+
/**
|
|
266
|
+
* Whether pi's direct Anthropic catalog flags this model, however the id is spelled:
|
|
267
|
+
* `claude-opus-4-8`, `anthropic/claude-sonnet-5.5`, `claude-fable-5-20260101`, ...
|
|
268
|
+
*/
|
|
265
269
|
export function acceptsMidConvoToolChanges(modelId) {
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
.match(/^claude-(opus|sonnet|fable)-(\d+)(?:-(\d{1,2}))?(?:-|$)/);
|
|
270
|
-
if (match === null)
|
|
271
|
-
return false;
|
|
272
|
-
const family = match[1];
|
|
273
|
-
const major = Number(match[2]);
|
|
274
|
-
const minor = match[3] === undefined ? 0 : Number(match[3]);
|
|
275
|
-
if (family === "fable")
|
|
276
|
-
return true;
|
|
277
|
-
if (family === "sonnet" && major === 5 && minor === 0)
|
|
278
|
-
return false;
|
|
279
|
-
return major > 4 || (major === 4 && minor >= 8);
|
|
270
|
+
const directId = modelId.replace(/^.*\//, "").replace(/\./g, "-").replace(/-\d{8}$/, "");
|
|
271
|
+
const direct = ANTHROPIC_MODELS[directId];
|
|
272
|
+
return direct?.compat?.supportsMidConvoToolChanges === true;
|
|
280
273
|
}
|
|
281
274
|
function toContext(req) {
|
|
282
275
|
return {
|
|
283
|
-
systemPrompt: req.
|
|
276
|
+
systemPrompt: req.systemPrompt,
|
|
284
277
|
messages: [...req.messages],
|
|
285
278
|
tools: req.tools?.map(toPiTool),
|
|
286
279
|
};
|
|
@@ -305,20 +298,7 @@ function toPiTool(tool) {
|
|
|
305
298
|
function toOptions(req, call, defaults) {
|
|
306
299
|
return {
|
|
307
300
|
...defaults,
|
|
308
|
-
...
|
|
309
|
-
? { reasoning: req.params.thinking }
|
|
310
|
-
: {}),
|
|
311
|
-
// Only meaningful alongside `reasoning`: pi reads it from `adjustMaxTokensForThinking`,
|
|
312
|
-
// which `streamSimple` skips entirely when no reasoning level was requested.
|
|
313
|
-
...(req.params?.thinkingBudgets !== undefined
|
|
314
|
-
? { thinkingBudgets: req.params.thinkingBudgets }
|
|
315
|
-
: {}),
|
|
316
|
-
...(req.params?.temperature !== undefined
|
|
317
|
-
? { temperature: req.params.temperature }
|
|
318
|
-
: {}),
|
|
319
|
-
...(req.params?.maxTokens !== undefined
|
|
320
|
-
? { maxTokens: req.params.maxTokens }
|
|
321
|
-
: {}),
|
|
301
|
+
...req.params,
|
|
322
302
|
...(call?.signal !== undefined ? { signal: call.signal } : {}),
|
|
323
303
|
...req.providerOptions,
|
|
324
304
|
};
|
package/dist/llm/model.d.ts
CHANGED
|
@@ -1,28 +1,21 @@
|
|
|
1
1
|
import type { AssistantMessage, AssistantMessageEvent, AssistantMessageEventStream, Message, ThinkingBudgets, ThinkingLevel, ToolSchema } from "../protocol/index.ts";
|
|
2
|
+
import type { SimpleStreamOptions } from "@earendil-works/pi-ai";
|
|
2
3
|
export type { ThinkingBudgets, ThinkingLevel };
|
|
3
4
|
/**
|
|
4
5
|
* How the model should behave for one request — the knobs that legitimately vary per agent
|
|
5
|
-
* and per turn.
|
|
6
|
-
* (transport/timeouts/retries/headers) are not part of an agent's configuration
|
|
7
|
-
*
|
|
6
|
+
* and per turn. A subset of pi's `SimpleStreamOptions`, under pi's names: connection-tier
|
|
7
|
+
* settings (transport/timeouts/retries/headers) are not part of an agent's configuration
|
|
8
|
+
* surface, and `deferred` returns a handle the turn loop can't stream. Anything else reaches the
|
|
9
|
+
* wire through `providerOptions` if something genuinely needs it.
|
|
8
10
|
*
|
|
9
11
|
* One type serves both `AgentConfig.modelSettings` and `LlmRequest.params` on purpose. They
|
|
10
12
|
* used to be separate look-alike shapes, and the loop forwarded only `thinking` — so a
|
|
11
13
|
* `temperature` set on an agent was silently dropped. Sharing the type makes that class of
|
|
12
14
|
* drift a compile error instead of a silent no-op.
|
|
13
15
|
*/
|
|
14
|
-
export
|
|
15
|
-
readonly temperature?: number;
|
|
16
|
-
readonly maxTokens?: number;
|
|
17
|
-
readonly thinking?: ThinkingLevel;
|
|
18
|
-
/**
|
|
19
|
-
* Per-level thinking budgets, for models that take a token budget rather than an effort
|
|
20
|
-
* level. Adaptive-thinking models ignore it. Only consulted when `thinking` is set.
|
|
21
|
-
*/
|
|
22
|
-
readonly thinkingBudgets?: ThinkingBudgets;
|
|
23
|
-
}
|
|
16
|
+
export type ModelSettings = Readonly<Pick<SimpleStreamOptions, "temperature" | "maxTokens" | "reasoning" | "thinkingBudgets" | "toolChoice" | "samplingParams" | "cacheRetention" | "metadata">>;
|
|
24
17
|
export interface LlmRequest {
|
|
25
|
-
readonly
|
|
18
|
+
readonly systemPrompt?: string;
|
|
26
19
|
readonly messages: readonly Message[];
|
|
27
20
|
/** Top-level tools. Tools that become available later in the conversation are declared
|
|
28
21
|
* by `system` messages in `messages` (pi's `toolsAdded`). */
|
package/dist/llm/retry.js
CHANGED
|
@@ -27,7 +27,7 @@ export async function streamWithRetry(input) {
|
|
|
27
27
|
const mode = useCompleteFallback ? "complete" : "stream";
|
|
28
28
|
logger.log("debug", "llm request", logDataPolicy.dontLogModelData
|
|
29
29
|
? { model: model.id, attempt, mode, messages: request.messages.length, tools: request.tools?.length ?? 0 }
|
|
30
|
-
: { model: model.id, attempt, mode, system: request.
|
|
30
|
+
: { model: model.id, attempt, mode, system: request.systemPrompt, messages: request.messages, tools: request.tools?.map((t) => t.name), params: request.params });
|
|
31
31
|
let exchange;
|
|
32
32
|
const observe = (seen) => {
|
|
33
33
|
exchange = seen;
|
package/dist/loop/tool-call.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
1
2
|
import { ToolAccesses } from "../tool/access.js";
|
|
2
3
|
import { logDataPolicy, noopLogger } from "../logging/index.js";
|
|
3
4
|
import { ToolScheduler } from "./scheduler.js";
|
|
@@ -153,6 +154,9 @@ async function prepareCall(step, call) {
|
|
|
153
154
|
if (isToolSuspendSignal(error)) {
|
|
154
155
|
return { kind: "result", call, result: errorResult("suspend() is only available during tool execution (plan.run), not resolve().") };
|
|
155
156
|
}
|
|
157
|
+
if (error instanceof z.ZodError) {
|
|
158
|
+
return { kind: "result", call, result: errorResult(`Invalid arguments for ${call.name}: ${describeIssues(error.issues).join("; ")}`) };
|
|
159
|
+
}
|
|
156
160
|
return { kind: "result", call, result: errorResult(messageOf(error)) };
|
|
157
161
|
}
|
|
158
162
|
if (step.hooks?.authorizeToolExecution) {
|
|
@@ -450,6 +454,17 @@ function toResultMessage(call, result) {
|
|
|
450
454
|
timestamp: Date.now(),
|
|
451
455
|
};
|
|
452
456
|
}
|
|
457
|
+
/** One `field: problem` line per issue; a union reports what its branches wanted, not "Invalid input". */
|
|
458
|
+
function describeIssues(issues, parentPath = []) {
|
|
459
|
+
return issues.flatMap((issue) => {
|
|
460
|
+
const path = [...parentPath, ...issue.path];
|
|
461
|
+
if (issue.code === "invalid_union" && issue.errors.length > 0) {
|
|
462
|
+
const branches = issue.errors.map((branch) => describeIssues(branch, path).join(", "));
|
|
463
|
+
return [[...new Set(branches)].join(" OR ")];
|
|
464
|
+
}
|
|
465
|
+
return [`${path.map(String).join(".") || "arguments"}: ${issue.message}`];
|
|
466
|
+
});
|
|
467
|
+
}
|
|
453
468
|
function messageOf(error) {
|
|
454
469
|
return error instanceof Error ? error.message : String(error);
|
|
455
470
|
}
|
package/dist/loop/turn-step.js
CHANGED
|
@@ -40,7 +40,7 @@ export async function executeStep(deps) {
|
|
|
40
40
|
const toolSchemas = prepared.requestTools;
|
|
41
41
|
const toolMap = new Map(activeTools.map((tool) => [tool.schema.name, tool]));
|
|
42
42
|
let request = {
|
|
43
|
-
system,
|
|
43
|
+
systemPrompt: system,
|
|
44
44
|
messages: prepared.deferEnabled
|
|
45
45
|
? withToolLoads(deps.context, new Set(toolSchemas.map((schema) => schema.name)))
|
|
46
46
|
: messages,
|
|
@@ -88,7 +88,7 @@ export async function executeStep(deps) {
|
|
|
88
88
|
turnId,
|
|
89
89
|
step: currentStep,
|
|
90
90
|
stepId,
|
|
91
|
-
...(request.
|
|
91
|
+
...(request.systemPrompt !== undefined ? { system: request.systemPrompt } : {}),
|
|
92
92
|
messages: [...request.messages],
|
|
93
93
|
toolNames: (request.tools ?? []).map((tool) => tool.name),
|
|
94
94
|
...(request.params !== undefined ? { params: request.params } : {}),
|
|
@@ -135,7 +135,7 @@ export class LlmAutoApprover {
|
|
|
135
135
|
/** Run one classifier stage and return its text content. Throws on a stream error. */
|
|
136
136
|
async runStage(model, userText, maxTokens, signal) {
|
|
137
137
|
const request = {
|
|
138
|
-
|
|
138
|
+
systemPrompt: this.system(),
|
|
139
139
|
messages: [{ role: "user", content: [{ type: "text", text: userText }], timestamp: Date.now() }],
|
|
140
140
|
// No thinking, so tokens aren't spent reasoning. No temperature either: providers disagree
|
|
141
141
|
// on what they accept (Mistral rejects 0 without top_p 1), and a request refused here
|
|
@@ -35,21 +35,32 @@ export const MAX_BYTES = 100 * 1024;
|
|
|
35
35
|
export const MAX_UNPAGED_FILE_BYTES = 256 * 1024;
|
|
36
36
|
const MAX_IMAGE_MEGABYTES = 100;
|
|
37
37
|
const MAX_IMAGE_BYTES = MAX_IMAGE_MEGABYTES * 1024 * 1024;
|
|
38
|
-
|
|
39
|
-
|
|
38
|
+
/** Some models stringify integer arguments (`"line_offset": "80"`); the intent is unambiguous, so honor it. */
|
|
39
|
+
function numberFromIntegerString(value) {
|
|
40
|
+
if (typeof value !== "string")
|
|
41
|
+
return value;
|
|
42
|
+
const trimmed = value.trim();
|
|
43
|
+
return /^[+-]?\d+$/.test(trimmed) ? Number(trimmed) : value;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* One `integer` rather than a union of the positive and tail ranges: the union renders as `anyOf`,
|
|
47
|
+
* and weaker models answered that shape with a string while filling the plain integer beside it correctly.
|
|
48
|
+
*/
|
|
49
|
+
const LineOffset = z
|
|
50
|
+
.number()
|
|
51
|
+
.int()
|
|
52
|
+
.min(-MAX_LINES)
|
|
53
|
+
.refine((offset) => offset !== 0, { error: "line_offset must not be 0: line numbers start at 1" });
|
|
40
54
|
const ReadInput = z.object({
|
|
41
55
|
path: z
|
|
42
56
|
.string()
|
|
43
57
|
.describe("Path to a text or image file. Relative paths resolve against the working directory; a path outside the working directory must be absolute. Directories are not supported; use `ls` via Bash for a known directory, or Glob for pattern search."),
|
|
44
58
|
line_offset: z
|
|
45
|
-
.
|
|
59
|
+
.preprocess(numberFromIntegerString, LineOffset)
|
|
46
60
|
.optional()
|
|
47
61
|
.describe(`The line number to start reading from. Omit to start at line 1. Negative values read from the end of the file; the absolute value cannot exceed ${String(MAX_LINES)}.`),
|
|
48
62
|
n_lines: z
|
|
49
|
-
.number()
|
|
50
|
-
.int()
|
|
51
|
-
.positive()
|
|
52
|
-
.max(MAX_LINES)
|
|
63
|
+
.preprocess(numberFromIntegerString, z.number().int().positive().max(MAX_LINES))
|
|
53
64
|
.optional()
|
|
54
65
|
.describe(`The number of lines to read, at most ${String(MAX_LINES)}. Omit to read to the end of the file.`),
|
|
55
66
|
});
|
package/dist/tracing/otel.js
CHANGED
|
@@ -160,7 +160,7 @@ export class OTelTracingProcessor {
|
|
|
160
160
|
...(data.toolNames === undefined ? {} : { "operon_agents.generation.tools": [...data.toolNames] }),
|
|
161
161
|
...(data.params?.temperature === undefined ? {} : { "gen_ai.request.temperature": data.params.temperature }),
|
|
162
162
|
...(data.params?.maxTokens === undefined ? {} : { "gen_ai.request.max_tokens": data.params.maxTokens }),
|
|
163
|
-
...(data.params?.
|
|
163
|
+
...(data.params?.reasoning === undefined ? {} : { "operon_agents.generation.thinking": String(data.params.reasoning) }),
|
|
164
164
|
};
|
|
165
165
|
case "tool":
|
|
166
166
|
return {
|
package/package.json
CHANGED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { type ModelCapability } from "../llm/index.ts";
|
|
2
|
-
import type { ModelAlias } from "./schema.ts";
|
|
3
|
-
export interface ModelCapabilityInfo {
|
|
4
|
-
readonly maxContextSize: number | undefined;
|
|
5
|
-
readonly maxOutputSize: number | undefined;
|
|
6
|
-
readonly capability: ModelCapability;
|
|
7
|
-
readonly known: boolean;
|
|
8
|
-
}
|
|
9
|
-
export declare class ModelCatalog {
|
|
10
|
-
private readonly aliases;
|
|
11
|
-
constructor(models?: Record<string, ModelAlias>);
|
|
12
|
-
private find;
|
|
13
|
-
info(modelRef: string): ModelCapabilityInfo;
|
|
14
|
-
maxContextSize(modelRef: string): number | undefined;
|
|
15
|
-
has(modelRef: string, capability: string): boolean;
|
|
16
|
-
}
|
|
17
|
-
//# sourceMappingURL=model-catalog.d.ts.map
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { UNKNOWN_CAPABILITY, applyDeclaredCapability } from "../llm/index.js";
|
|
2
|
-
export class ModelCatalog {
|
|
3
|
-
aliases;
|
|
4
|
-
constructor(models = {}) {
|
|
5
|
-
this.aliases = new Map(Object.entries(models));
|
|
6
|
-
}
|
|
7
|
-
find(modelRef) {
|
|
8
|
-
const direct = this.aliases.get(modelRef);
|
|
9
|
-
if (direct)
|
|
10
|
-
return direct;
|
|
11
|
-
for (const alias of this.aliases.values()) {
|
|
12
|
-
if (`${alias.provider}/${alias.model}` === modelRef || alias.model === modelRef)
|
|
13
|
-
return alias;
|
|
14
|
-
}
|
|
15
|
-
return undefined;
|
|
16
|
-
}
|
|
17
|
-
info(modelRef) {
|
|
18
|
-
const alias = this.find(modelRef);
|
|
19
|
-
if (!alias) {
|
|
20
|
-
return { maxContextSize: undefined, maxOutputSize: undefined, capability: UNKNOWN_CAPABILITY, known: false };
|
|
21
|
-
}
|
|
22
|
-
return {
|
|
23
|
-
maxContextSize: alias.maxContextSize,
|
|
24
|
-
maxOutputSize: alias.maxOutputSize,
|
|
25
|
-
capability: applyDeclaredCapability(UNKNOWN_CAPABILITY, alias.capabilities, alias.maxContextSize),
|
|
26
|
-
known: true,
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
maxContextSize(modelRef) {
|
|
30
|
-
return this.find(modelRef)?.maxContextSize;
|
|
31
|
-
}
|
|
32
|
-
has(modelRef, capability) {
|
|
33
|
-
const alias = this.find(modelRef);
|
|
34
|
-
return alias?.capabilities?.includes(capability) ?? false;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
//# sourceMappingURL=model-catalog.js.map
|
|
@@ -1,64 +0,0 @@
|
|
|
1
|
-
import { type AuthContext, type CredentialStore, type ModelsStore } from "@earendil-works/pi-ai";
|
|
2
|
-
import { ChatModel, DecisionModel, UNKNOWN_CAPABILITY, type ModelCapability, type ModelRuntime } from "../llm/index.ts";
|
|
3
|
-
import type { ModelCredentialsConfig, ProviderConfig } from "./schema.ts";
|
|
4
|
-
export interface ResolvedModel {
|
|
5
|
-
readonly model: ChatModel;
|
|
6
|
-
readonly capability: ModelCapability;
|
|
7
|
-
readonly maxOutputSize?: number;
|
|
8
|
-
readonly providerName: string;
|
|
9
|
-
}
|
|
10
|
-
export type ApiKeyResolver = (providerName: string, providerConfig: ProviderConfig) => string | undefined | Promise<string | undefined>;
|
|
11
|
-
export interface ProviderManagerConfig {
|
|
12
|
-
readonly providers: Readonly<Record<string, ProviderConfig>>;
|
|
13
|
-
readonly models: Readonly<Record<string, ResolvableAlias>>;
|
|
14
|
-
readonly defaultModel?: string;
|
|
15
|
-
readonly modelCredentials?: ModelCredentialsConfig;
|
|
16
|
-
}
|
|
17
|
-
export interface ResolvableAlias {
|
|
18
|
-
readonly provider: string;
|
|
19
|
-
readonly model: string;
|
|
20
|
-
readonly maxContextSize?: number;
|
|
21
|
-
readonly maxOutputSize?: number;
|
|
22
|
-
readonly capabilities?: readonly string[];
|
|
23
|
-
readonly displayName?: string;
|
|
24
|
-
}
|
|
25
|
-
export interface ProviderManagerOptions {
|
|
26
|
-
readonly config: ProviderManagerConfig | (() => ProviderManagerConfig);
|
|
27
|
-
/** Reuse a caller-owned pi provider/auth/catalog collection. */
|
|
28
|
-
readonly runtime?: ModelRuntime;
|
|
29
|
-
readonly credentials?: CredentialStore;
|
|
30
|
-
readonly modelsStore?: ModelsStore;
|
|
31
|
-
readonly authContext?: AuthContext;
|
|
32
|
-
/** Legacy convenience overlay; `authContext` is the canonical injection. */
|
|
33
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
34
|
-
/**
|
|
35
|
-
* Optional product secret resolver. It is compiled into provider-owned
|
|
36
|
-
* ApiKeyAuth (not called while resolving an alias).
|
|
37
|
-
*/
|
|
38
|
-
readonly resolveApiKey?: ApiKeyResolver;
|
|
39
|
-
}
|
|
40
|
-
export declare class ProviderManager {
|
|
41
|
-
private readonly options;
|
|
42
|
-
readonly runtime: ModelRuntime;
|
|
43
|
-
private readonly baseProviders;
|
|
44
|
-
private readonly overlayFingerprints;
|
|
45
|
-
constructor(options: ProviderManagerOptions);
|
|
46
|
-
private get config();
|
|
47
|
-
get defaultModel(): string | undefined;
|
|
48
|
-
resolveModel(modelRef?: string): Promise<ResolvedModel>;
|
|
49
|
-
/**
|
|
50
|
-
* The decision model `modelRef` names, or undefined when it is an LLM. An id catalogued as both
|
|
51
|
-
* (OpenAI's `gpt-6-luna`) counts as an LLM, and an id the catalog doesn't know can only be one.
|
|
52
|
-
*/
|
|
53
|
-
resolveDecisionModel(modelRef: string): DecisionModel | undefined;
|
|
54
|
-
/** One model reference, whichever kind it is — what `createAutoApprover` takes. */
|
|
55
|
-
resolveReviewModel(modelRef: string): Promise<ChatModel | DecisionModel>;
|
|
56
|
-
modelResolver(): (modelId: string) => Promise<ChatModel>;
|
|
57
|
-
private resolveAlias;
|
|
58
|
-
private syncConfiguredProviders;
|
|
59
|
-
private restoreBaseProvider;
|
|
60
|
-
private buildConfiguredProvider;
|
|
61
|
-
private baseProviderFor;
|
|
62
|
-
}
|
|
63
|
-
export { UNKNOWN_CAPABILITY };
|
|
64
|
-
//# sourceMappingURL=provider-manager.d.ts.map
|
|
@@ -1,345 +0,0 @@
|
|
|
1
|
-
import { homedir } from "node:os";
|
|
2
|
-
import { join, resolve as resolvePath } from "node:path";
|
|
3
|
-
import { createProvider, defaultProviderAuthContext, } from "@earendil-works/pi-ai";
|
|
4
|
-
import { anthropicMessagesApi } from "@earendil-works/pi-ai/api/anthropic-messages.lazy";
|
|
5
|
-
import { googleGenerativeAIApi } from "@earendil-works/pi-ai/api/google-generative-ai.lazy";
|
|
6
|
-
import { googleVertexApi } from "@earendil-works/pi-ai/api/google-vertex.lazy";
|
|
7
|
-
import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
|
|
8
|
-
import { openAIResponsesApi } from "@earendil-works/pi-ai/api/openai-responses.lazy";
|
|
9
|
-
import { ChatModel, DecisionModel, FileCredentialStore, UNKNOWN_CAPABILITY, applyDeclaredCapability, capabilityFromPiModel, createModelRuntime, } from "../llm/index.js";
|
|
10
|
-
export class ProviderManager {
|
|
11
|
-
options;
|
|
12
|
-
runtime;
|
|
13
|
-
baseProviders = new Map();
|
|
14
|
-
overlayFingerprints = new Map();
|
|
15
|
-
constructor(options) {
|
|
16
|
-
this.options = options;
|
|
17
|
-
const initialConfig = this.config;
|
|
18
|
-
const authContext = overlayOptionalAuthContext(options.authContext ?? defaultProviderAuthContext(), options.env);
|
|
19
|
-
const credentials = options.credentials ??
|
|
20
|
-
credentialStoreFromConfig(initialConfig.modelCredentials);
|
|
21
|
-
this.runtime = options.runtime ?? createModelRuntime({
|
|
22
|
-
...(credentials !== undefined ? { credentials } : {}),
|
|
23
|
-
...(options.modelsStore !== undefined ? { modelsStore: options.modelsStore } : {}),
|
|
24
|
-
authContext,
|
|
25
|
-
});
|
|
26
|
-
for (const provider of this.runtime.models.getProviders()) {
|
|
27
|
-
this.baseProviders.set(provider.id, provider);
|
|
28
|
-
}
|
|
29
|
-
this.syncConfiguredProviders(initialConfig);
|
|
30
|
-
}
|
|
31
|
-
get config() {
|
|
32
|
-
const c = this.options.config;
|
|
33
|
-
return typeof c === "function" ? c() : c;
|
|
34
|
-
}
|
|
35
|
-
get defaultModel() {
|
|
36
|
-
return this.config.defaultModel;
|
|
37
|
-
}
|
|
38
|
-
async resolveModel(modelRef) {
|
|
39
|
-
const config = this.config;
|
|
40
|
-
this.syncConfiguredProviders(config);
|
|
41
|
-
const ref = modelRef ?? config.defaultModel;
|
|
42
|
-
if (ref === undefined || ref.length === 0) {
|
|
43
|
-
throw new Error("provider manager: no model specified and config has no defaultModel");
|
|
44
|
-
}
|
|
45
|
-
const alias = this.resolveAlias(ref, config);
|
|
46
|
-
const piModel = this.runtime.models.getModel(alias.provider, alias.model);
|
|
47
|
-
if (piModel === undefined) {
|
|
48
|
-
const providerConfig = config.providers[alias.provider];
|
|
49
|
-
if (providerConfig?.baseUrl === undefined || providerConfig.baseUrl.length === 0) {
|
|
50
|
-
throw new Error(`provider manager: model "${alias.provider}/${alias.model}" is unknown to pi and ` +
|
|
51
|
-
`provider "${alias.provider}" has no baseUrl to build a custom endpoint`);
|
|
52
|
-
}
|
|
53
|
-
throw new Error(`provider manager: configured provider "${alias.provider}" did not expose model "${alias.model}"`);
|
|
54
|
-
}
|
|
55
|
-
return {
|
|
56
|
-
model: new ChatModel({
|
|
57
|
-
runtime: this.runtime,
|
|
58
|
-
descriptor: piModel,
|
|
59
|
-
}),
|
|
60
|
-
capability: applyDeclaredCapability(capabilityFromPiModel(piModel), alias.capabilities, alias.maxContextSize),
|
|
61
|
-
maxOutputSize: alias.maxOutputSize,
|
|
62
|
-
providerName: alias.provider,
|
|
63
|
-
};
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* The decision model `modelRef` names, or undefined when it is an LLM. An id catalogued as both
|
|
67
|
-
* (OpenAI's `gpt-6-luna`) counts as an LLM, and an id the catalog doesn't know can only be one.
|
|
68
|
-
*/
|
|
69
|
-
resolveDecisionModel(modelRef) {
|
|
70
|
-
const config = this.config;
|
|
71
|
-
this.syncConfiguredProviders(config);
|
|
72
|
-
const alias = this.resolveAlias(modelRef, config);
|
|
73
|
-
if (this.runtime.models.getModel(alias.provider, alias.model) !== undefined)
|
|
74
|
-
return undefined;
|
|
75
|
-
const descriptor = this.runtime.models.getModelOfType("classifier", alias.provider, alias.model);
|
|
76
|
-
return descriptor === undefined ? undefined : new DecisionModel({ runtime: this.runtime, descriptor });
|
|
77
|
-
}
|
|
78
|
-
/** One model reference, whichever kind it is — what `createAutoApprover` takes. */
|
|
79
|
-
async resolveReviewModel(modelRef) {
|
|
80
|
-
return this.resolveDecisionModel(modelRef) ?? (await this.resolveModel(modelRef)).model;
|
|
81
|
-
}
|
|
82
|
-
modelResolver() {
|
|
83
|
-
return async (id) => (await this.resolveModel(id)).model;
|
|
84
|
-
}
|
|
85
|
-
resolveAlias(ref, config) {
|
|
86
|
-
const declared = config.models[ref];
|
|
87
|
-
if (declared !== undefined)
|
|
88
|
-
return declared;
|
|
89
|
-
const slash = ref.indexOf("/");
|
|
90
|
-
if (slash > 0 && slash < ref.length - 1) {
|
|
91
|
-
return { provider: ref.slice(0, slash), model: ref.slice(slash + 1) };
|
|
92
|
-
}
|
|
93
|
-
throw new Error(`provider manager: model "${ref}" is not in config.models and is not a "provider/model" ref`);
|
|
94
|
-
}
|
|
95
|
-
syncConfiguredProviders(config) {
|
|
96
|
-
const configured = new Set(Object.keys(config.providers));
|
|
97
|
-
for (const providerId of this.overlayFingerprints.keys()) {
|
|
98
|
-
if (configured.has(providerId))
|
|
99
|
-
continue;
|
|
100
|
-
this.restoreBaseProvider(providerId);
|
|
101
|
-
this.overlayFingerprints.delete(providerId);
|
|
102
|
-
}
|
|
103
|
-
for (const [providerId, providerConfig] of Object.entries(config.providers)) {
|
|
104
|
-
const aliases = Object.values(config.models).filter((alias) => alias.provider === providerId);
|
|
105
|
-
const fingerprint = JSON.stringify({ providerConfig, aliases });
|
|
106
|
-
if (this.overlayFingerprints.get(providerId) === fingerprint)
|
|
107
|
-
continue;
|
|
108
|
-
const provider = this.buildConfiguredProvider(providerId, providerConfig, aliases);
|
|
109
|
-
this.runtime.models.setProvider(provider);
|
|
110
|
-
this.overlayFingerprints.set(providerId, fingerprint);
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
restoreBaseProvider(providerId) {
|
|
114
|
-
const base = this.baseProviders.get(providerId);
|
|
115
|
-
if (base !== undefined)
|
|
116
|
-
this.runtime.models.setProvider(base);
|
|
117
|
-
else
|
|
118
|
-
this.runtime.models.deleteProvider(providerId);
|
|
119
|
-
}
|
|
120
|
-
buildConfiguredProvider(providerId, config, aliases) {
|
|
121
|
-
const base = this.baseProviderFor(providerId, config.type);
|
|
122
|
-
const models = configuredModels(providerId, config, aliases, base);
|
|
123
|
-
// A custom baseUrl is a different service: the catalog's decision endpoints don't apply to it,
|
|
124
|
-
// and its key must not be sent to them.
|
|
125
|
-
const decision = config.baseUrl ? undefined : catalogDecisionModels(this.baseProviders.get(providerId));
|
|
126
|
-
return createProvider({
|
|
127
|
-
id: providerId,
|
|
128
|
-
name: base?.name ?? providerId,
|
|
129
|
-
baseUrl: config.baseUrl ?? base?.baseUrl,
|
|
130
|
-
headers: mergeHeaders(base?.headers, config.customHeaders),
|
|
131
|
-
auth: configuredAuth(providerId, config, base?.auth, this.options.resolveApiKey),
|
|
132
|
-
models: decision ? [...models, ...decision.models] : models,
|
|
133
|
-
api: API_IMPLEMENTATIONS,
|
|
134
|
-
...(decision ? { classifiers: decision.classifiers } : {}),
|
|
135
|
-
});
|
|
136
|
-
}
|
|
137
|
-
baseProviderFor(providerId, type) {
|
|
138
|
-
return (this.baseProviders.get(providerId) ??
|
|
139
|
-
this.baseProviders.get(builtinProviderIdForType(type)));
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
function credentialStoreFromConfig(config) {
|
|
143
|
-
return config === undefined
|
|
144
|
-
? undefined
|
|
145
|
-
: new FileCredentialStore(resolveCredentialPath(config.path));
|
|
146
|
-
}
|
|
147
|
-
/**
|
|
148
|
-
* `~` is the user's home. Relative paths are workspace/process-cwd relative;
|
|
149
|
-
* layered TOML has no single source file whose directory could own them.
|
|
150
|
-
*/
|
|
151
|
-
function resolveCredentialPath(configuredPath) {
|
|
152
|
-
const expanded = configuredPath === "~"
|
|
153
|
-
? homedir()
|
|
154
|
-
: configuredPath.startsWith("~/")
|
|
155
|
-
? join(homedir(), configuredPath.slice(2))
|
|
156
|
-
: configuredPath;
|
|
157
|
-
return resolvePath(expanded);
|
|
158
|
-
}
|
|
159
|
-
/** A catalog provider's decision models and the code that calls them, to carry onto its overlay. */
|
|
160
|
-
function catalogDecisionModels(base) {
|
|
161
|
-
const models = (base?.getAllModels?.() ?? []).filter((model) => model.type === "classifier");
|
|
162
|
-
if (base?.classify === undefined || models.length === 0)
|
|
163
|
-
return undefined;
|
|
164
|
-
const classifier = { classify: base.classify.bind(base) };
|
|
165
|
-
return { models, classifiers: Object.fromEntries(models.map((model) => [model.api, classifier])) };
|
|
166
|
-
}
|
|
167
|
-
function configuredModels(providerId, config, aliases, base) {
|
|
168
|
-
const byId = new Map();
|
|
169
|
-
for (const model of base?.getModels() ?? []) {
|
|
170
|
-
byId.set(model.id, configureKnownModel(model, providerId, config));
|
|
171
|
-
}
|
|
172
|
-
for (const alias of aliases) {
|
|
173
|
-
if (byId.has(alias.model))
|
|
174
|
-
continue;
|
|
175
|
-
// Unknown catalog entries need an explicit endpoint. Without one, leave
|
|
176
|
-
// them absent so resolveModel reports the same actionable error as before.
|
|
177
|
-
if (config.baseUrl === undefined || config.baseUrl.length === 0)
|
|
178
|
-
continue;
|
|
179
|
-
byId.set(alias.model, buildCustomPiModel(alias, providerId, config));
|
|
180
|
-
}
|
|
181
|
-
return [...byId.values()];
|
|
182
|
-
}
|
|
183
|
-
function configureKnownModel(model, providerId, config) {
|
|
184
|
-
return {
|
|
185
|
-
...model,
|
|
186
|
-
provider: providerId,
|
|
187
|
-
...(config.baseUrl !== undefined ? { baseUrl: config.baseUrl } : {}),
|
|
188
|
-
...(config.customHeaders !== undefined
|
|
189
|
-
? { headers: { ...(model.headers ?? {}), ...config.customHeaders } }
|
|
190
|
-
: {}),
|
|
191
|
-
};
|
|
192
|
-
}
|
|
193
|
-
function buildCustomPiModel(alias, providerId, providerConfig) {
|
|
194
|
-
const tags = new Set((alias.capabilities ?? []).map((c) => c.trim().toLowerCase()));
|
|
195
|
-
const input = tags.has("image") || tags.has("image_in") || tags.has("vision")
|
|
196
|
-
? ["text", "image"]
|
|
197
|
-
: ["text"];
|
|
198
|
-
const api = apiForProviderType(providerConfig.type);
|
|
199
|
-
return {
|
|
200
|
-
id: alias.model,
|
|
201
|
-
name: alias.displayName ?? alias.model,
|
|
202
|
-
api,
|
|
203
|
-
provider: providerId,
|
|
204
|
-
baseUrl: providerConfig.baseUrl,
|
|
205
|
-
reasoning: tags.has("thinking") ||
|
|
206
|
-
tags.has("reasoning") ||
|
|
207
|
-
tags.has("always_thinking"),
|
|
208
|
-
input,
|
|
209
|
-
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
210
|
-
contextWindow: alias.maxContextSize ?? 0,
|
|
211
|
-
maxTokens: alias.maxOutputSize ?? 4096,
|
|
212
|
-
...(providerConfig.customHeaders !== undefined
|
|
213
|
-
? { headers: providerConfig.customHeaders }
|
|
214
|
-
: {}),
|
|
215
|
-
};
|
|
216
|
-
}
|
|
217
|
-
function configuredAuth(providerId, config, base, resolveApiKey) {
|
|
218
|
-
return {
|
|
219
|
-
apiKey: configuredApiKeyAuth(providerId, config, base?.apiKey, resolveApiKey),
|
|
220
|
-
...(base?.oauth !== undefined ? { oauth: base.oauth } : {}),
|
|
221
|
-
};
|
|
222
|
-
}
|
|
223
|
-
function configuredApiKeyAuth(providerId, config, fallback, resolveApiKey) {
|
|
224
|
-
return {
|
|
225
|
-
name: fallback?.name ?? `${providerId} API key`,
|
|
226
|
-
...(fallback?.login !== undefined ? { login: fallback.login } : {}),
|
|
227
|
-
async resolve({ ctx, credential, signal }) {
|
|
228
|
-
const scopedContext = overlayAuthContext(ctx, config.env);
|
|
229
|
-
if (credential !== undefined && fallback !== undefined) {
|
|
230
|
-
const stored = await fallback.resolve({
|
|
231
|
-
ctx: scopedContext,
|
|
232
|
-
credential,
|
|
233
|
-
signal,
|
|
234
|
-
});
|
|
235
|
-
if (stored !== undefined)
|
|
236
|
-
return mergeAuthEnv(stored, config.env);
|
|
237
|
-
}
|
|
238
|
-
const external = config.oauth === undefined
|
|
239
|
-
? undefined
|
|
240
|
-
: await resolveApiKey?.(providerId, config);
|
|
241
|
-
if (external !== undefined && external.length > 0) {
|
|
242
|
-
return {
|
|
243
|
-
auth: { apiKey: external },
|
|
244
|
-
env: config.env,
|
|
245
|
-
source: "Resolver",
|
|
246
|
-
};
|
|
247
|
-
}
|
|
248
|
-
if (config.apiKey !== undefined && config.apiKey.length > 0) {
|
|
249
|
-
return {
|
|
250
|
-
auth: { apiKey: config.apiKey },
|
|
251
|
-
env: config.env,
|
|
252
|
-
source: "Config",
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
const providerEnvName = `${providerId.toUpperCase().replace(/[^A-Z0-9]+/g, "_")}_API_KEY`;
|
|
256
|
-
const providerKey = await scopedContext.env(providerEnvName);
|
|
257
|
-
if (providerKey !== undefined && providerKey.trim().length > 0) {
|
|
258
|
-
return {
|
|
259
|
-
auth: { apiKey: providerKey },
|
|
260
|
-
env: config.env,
|
|
261
|
-
source: providerEnvName,
|
|
262
|
-
};
|
|
263
|
-
}
|
|
264
|
-
if (fallback !== undefined) {
|
|
265
|
-
const ambient = await fallback.resolve({
|
|
266
|
-
ctx: scopedContext,
|
|
267
|
-
credential: undefined,
|
|
268
|
-
signal,
|
|
269
|
-
});
|
|
270
|
-
if (ambient !== undefined)
|
|
271
|
-
return mergeAuthEnv(ambient, config.env);
|
|
272
|
-
}
|
|
273
|
-
// Explicit custom endpoints may be keyless (e.g. local OpenAI-compatible servers).
|
|
274
|
-
if (config.baseUrl !== undefined && config.baseUrl.length > 0) {
|
|
275
|
-
return { auth: {}, env: config.env, source: "Keyless endpoint" };
|
|
276
|
-
}
|
|
277
|
-
return undefined;
|
|
278
|
-
},
|
|
279
|
-
};
|
|
280
|
-
}
|
|
281
|
-
function mergeAuthEnv(result, env) {
|
|
282
|
-
if (env === undefined)
|
|
283
|
-
return result;
|
|
284
|
-
return { ...result, env: { ...(result.env ?? {}), ...env } };
|
|
285
|
-
}
|
|
286
|
-
function overlayAuthContext(base, env) {
|
|
287
|
-
if (env === undefined)
|
|
288
|
-
return base;
|
|
289
|
-
return {
|
|
290
|
-
env: async (name) => env[name] ?? (await base.env(name)),
|
|
291
|
-
fileExists: (path) => base.fileExists(path),
|
|
292
|
-
};
|
|
293
|
-
}
|
|
294
|
-
function overlayOptionalAuthContext(base, env) {
|
|
295
|
-
if (env === undefined)
|
|
296
|
-
return base;
|
|
297
|
-
return {
|
|
298
|
-
env: async (name) => env[name] ?? (await base.env(name)),
|
|
299
|
-
fileExists: (path) => base.fileExists(path),
|
|
300
|
-
};
|
|
301
|
-
}
|
|
302
|
-
const API_IMPLEMENTATIONS = {
|
|
303
|
-
"anthropic-messages": anthropicMessagesApi(),
|
|
304
|
-
"openai-completions": openAICompletionsApi(),
|
|
305
|
-
"openai-responses": openAIResponsesApi(),
|
|
306
|
-
"google-generative-ai": googleGenerativeAIApi(),
|
|
307
|
-
"google-vertex": googleVertexApi(),
|
|
308
|
-
};
|
|
309
|
-
function mergeHeaders(base, override) {
|
|
310
|
-
if (base === undefined && override === undefined)
|
|
311
|
-
return undefined;
|
|
312
|
-
return { ...(base ?? {}), ...(override ?? {}) };
|
|
313
|
-
}
|
|
314
|
-
function builtinProviderIdForType(type) {
|
|
315
|
-
switch (type) {
|
|
316
|
-
case "anthropic":
|
|
317
|
-
return "anthropic";
|
|
318
|
-
case "openai":
|
|
319
|
-
case "openai_responses":
|
|
320
|
-
return "openai";
|
|
321
|
-
case "kimi":
|
|
322
|
-
return "moonshotai";
|
|
323
|
-
case "google-genai":
|
|
324
|
-
return "google";
|
|
325
|
-
case "vertexai":
|
|
326
|
-
return "google-vertex";
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
function apiForProviderType(type) {
|
|
330
|
-
switch (type) {
|
|
331
|
-
case "anthropic":
|
|
332
|
-
return "anthropic-messages";
|
|
333
|
-
case "openai":
|
|
334
|
-
case "kimi":
|
|
335
|
-
return "openai-completions";
|
|
336
|
-
case "openai_responses":
|
|
337
|
-
return "openai-responses";
|
|
338
|
-
case "google-genai":
|
|
339
|
-
return "google-generative-ai";
|
|
340
|
-
case "vertexai":
|
|
341
|
-
return "google-vertex";
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
export { UNKNOWN_CAPABILITY };
|
|
345
|
-
//# sourceMappingURL=provider-manager.js.map
|