@wraith-ai/core 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
- package/dist/attempt-HgararU3.d.mts.map +1 -0
- package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
- package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
- package/dist/index.d.mts +6 -5
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +11 -9
- package/dist/index.mjs.map +1 -0
- package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
- package/dist/methods-7Ryz6zbd.mjs.map +1 -0
- package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
- package/dist/model-C16NUwXW.mjs.map +1 -0
- package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
- package/dist/model-_wqePNTL.d.mts.map +1 -0
- package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
- package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
- package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
- package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
- package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
- package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
- package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
- package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
- package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
- package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
- package/dist/providers/openai-codex.d.mts +4 -3
- package/dist/providers/openai-codex.d.mts.map +1 -0
- package/dist/providers/openai-codex.mjs +1 -1
- package/dist/providers/openai-compatible.d.mts +3 -2
- package/dist/providers/openai-compatible.d.mts.map +1 -0
- package/dist/providers/openai-compatible.mjs +1 -1
- package/dist/providers/openrouter.d.mts +3 -2
- package/dist/providers/openrouter.d.mts.map +1 -0
- package/dist/providers/openrouter.mjs +1 -1
- package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
- package/dist/shared-BIJaPhMm.mjs.map +1 -0
- package/dist/snapshot.d.mts +3 -2
- package/dist/snapshot.d.mts.map +1 -0
- package/dist/snapshot.mjs +4999 -4977
- package/dist/snapshot.mjs.map +1 -0
- package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
- package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
- package/package.json +3 -2
- package/src/agent/agent.ts +90 -0
- package/src/agent/attachments.ts +195 -0
- package/src/agent/classifier.ts +525 -0
- package/src/agent/compact.ts +384 -0
- package/src/agent/conversation.ts +300 -0
- package/src/agent/cost.ts +164 -0
- package/src/agent/inbox.ts +80 -0
- package/src/agent/instructions.ts +62 -0
- package/src/agent/loop.ts +675 -0
- package/src/agent/messages.ts +252 -0
- package/src/agent/on-demand.ts +58 -0
- package/src/agent/prompts.ts +35 -0
- package/src/agent/request-images.ts +94 -0
- package/src/agent/stop.ts +37 -0
- package/src/agent/title.ts +122 -0
- package/src/agent/tool-groups.ts +186 -0
- package/src/agent/tools.ts +106 -0
- package/src/app.ts +67 -0
- package/src/config/credential-file-store.ts +66 -0
- package/src/config/environment.ts +105 -0
- package/src/config/instructions.ts +157 -0
- package/src/config/load.ts +667 -0
- package/src/config/locked-file.ts +85 -0
- package/src/config/paths.ts +368 -0
- package/src/config/schema.ts +363 -0
- package/src/config/subagents.ts +156 -0
- package/src/config/trust.ts +53 -0
- package/src/config/write.ts +241 -0
- package/src/errors.ts +85 -0
- package/src/events/types.ts +258 -0
- package/src/glob.ts +161 -0
- package/src/index.ts +681 -0
- package/src/logger.ts +47 -0
- package/src/paths.ts +143 -0
- package/src/permissions/chain.ts +42 -0
- package/src/permissions/command.ts +233 -0
- package/src/permissions/layered.ts +77 -0
- package/src/permissions/match.ts +80 -0
- package/src/permissions/modes.ts +48 -0
- package/src/permissions/policy.ts +160 -0
- package/src/permissions/types.ts +159 -0
- package/src/providers/cache.ts +107 -0
- package/src/providers/capabilities.ts +77 -0
- package/src/providers/catalog-view.ts +91 -0
- package/src/providers/catalog.ts +65 -0
- package/src/providers/errors.ts +108 -0
- package/src/providers/factories/index.ts +15 -0
- package/src/providers/factories/openai-codex.ts +382 -0
- package/src/providers/factories/openai-compatible.ts +81 -0
- package/src/providers/factories/openrouter.ts +165 -0
- package/src/providers/factories/shared.ts +22 -0
- package/src/providers/model.ts +197 -0
- package/src/providers/models-dev.ts +355 -0
- package/src/providers/oauth/methods.ts +10 -0
- package/src/providers/oauth/openai-codex.ts +228 -0
- package/src/providers/oauth.ts +177 -0
- package/src/providers/openai-codex.ts +7 -0
- package/src/providers/openai-compatible.ts +2 -0
- package/src/providers/openrouter.ts +2 -0
- package/src/providers/registry.ts +464 -0
- package/src/providers/turn-effort.ts +156 -0
- package/src/providers/types.ts +83 -0
- package/src/session/backend.ts +44 -0
- package/src/session/file-store.ts +278 -0
- package/src/session/format.ts +1037 -0
- package/src/session/memory-store.ts +73 -0
- package/src/session/session.ts +153 -0
- package/src/session/store.ts +219 -0
- package/src/sign-in/attempt.ts +166 -0
- package/src/sign-in/loopback.ts +74 -0
- package/src/snapshot/data.json +8936 -0
- package/src/snapshot/index.ts +37 -0
- package/src/tools/bin.ts +364 -0
- package/src/tools/builtin.ts +48 -0
- package/src/tools/change.ts +88 -0
- package/src/tools/define.ts +267 -0
- package/src/tools/describe.ts +96 -0
- package/src/tools/fs/edit-file.ts +129 -0
- package/src/tools/fs/glob.ts +75 -0
- package/src/tools/fs/grep.ts +212 -0
- package/src/tools/fs/line-endings.ts +17 -0
- package/src/tools/fs/list-dir.ts +85 -0
- package/src/tools/fs/read-file.ts +230 -0
- package/src/tools/fs/ripgrep.ts +211 -0
- package/src/tools/fs/write-file.ts +97 -0
- package/src/tools/job.ts +252 -0
- package/src/tools/mcp/auth-store.ts +127 -0
- package/src/tools/mcp/command.ts +151 -0
- package/src/tools/mcp/config.ts +168 -0
- package/src/tools/mcp/servers.ts +463 -0
- package/src/tools/mcp/sign-in.ts +226 -0
- package/src/tools/mcp/stdio.ts +204 -0
- package/src/tools/mcp/tools.ts +173 -0
- package/src/tools/on-demand.ts +184 -0
- package/src/tools/registry.ts +935 -0
- package/src/tools/shell/bash.ts +217 -0
- package/src/tools/shell/find-bash.ts +162 -0
- package/src/tools/source.ts +35 -0
- package/src/tools/spill.ts +127 -0
- package/src/tools/subagents.ts +597 -0
- package/src/tools/tasks.ts +603 -0
- package/src/tools/to-model.ts +33 -0
- package/src/tools/web/address.ts +95 -0
- package/src/tools/web/exa.ts +163 -0
- package/src/tools/web/fetch.ts +373 -0
- package/src/tools/web/html.ts +173 -0
- package/src/tools/web/search.ts +111 -0
- package/src/tools/web/source.ts +51 -0
- package/src/units.ts +18 -0
- package/src/version.ts +23 -0
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import type { AppIdentity } from "../app";
|
|
2
|
+
import { AgentError } from "../errors";
|
|
3
|
+
import { openSignIn, SIGN_IN_TIMEOUT_MS, type SignIn } from "../sign-in/attempt";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Signing in with a subscription instead of a key.
|
|
7
|
+
*
|
|
8
|
+
* The core knows the protocol: when a token is stale and how to refresh it.
|
|
9
|
+
* Where the tokens live is the store's, which the host picks; nothing here
|
|
10
|
+
* opens a file.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export interface OAuthCredential {
|
|
14
|
+
access: string;
|
|
15
|
+
refresh: string;
|
|
16
|
+
/** Epoch milliseconds. */
|
|
17
|
+
expires: number;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Where sign-ins live, supplied by the host and keyed by provider name.
|
|
22
|
+
*
|
|
23
|
+
* `modify` is the only write path, and it runs one at a time per provider —
|
|
24
|
+
* across processes too, where the store can manage it (a file lock). Refresh
|
|
25
|
+
* tokens are single-use, so two refreshes racing on the same token lose the
|
|
26
|
+
* sign-in; the lock plus a second look under it is what prevents that.
|
|
27
|
+
*/
|
|
28
|
+
export interface CredentialStore {
|
|
29
|
+
read(provider: string): Promise<OAuthCredential | undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* `fn` sees what is stored at the moment the lock is held. Returning
|
|
32
|
+
* undefined leaves the entry as it is; the result is what is stored after.
|
|
33
|
+
*/
|
|
34
|
+
modify(
|
|
35
|
+
provider: string,
|
|
36
|
+
fn: (current: OAuthCredential | undefined) => Promise<OAuthCredential | undefined>,
|
|
37
|
+
): Promise<OAuthCredential | undefined>;
|
|
38
|
+
delete(provider: string): Promise<void>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** One sign-in in progress: a page to open and a way to finish from where it lands. */
|
|
42
|
+
export interface LoginAttempt {
|
|
43
|
+
url: string;
|
|
44
|
+
/** Where the browser comes back to; the host listens there when it can. */
|
|
45
|
+
redirect: { port: number; path: string };
|
|
46
|
+
/** Takes the full redirect URL, or the bare code when that is all somebody has. */
|
|
47
|
+
complete(redirected: string): Promise<OAuthCredential>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** How one kind of provider signs in. Protocol only — no terminal, no browser, no disk. */
|
|
51
|
+
export interface OAuthMethod {
|
|
52
|
+
begin(): Promise<LoginAttempt>;
|
|
53
|
+
refresh(current: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Lazy, and told whose name to sign in under. */
|
|
57
|
+
export type OAuthMethodLoader = (app: AppIdentity) => Promise<OAuthMethod>;
|
|
58
|
+
|
|
59
|
+
/** Refresh ahead of expiry, so a token never dies between the check and the request. */
|
|
60
|
+
export const REFRESH_MARGIN_MS = 5 * 60_000;
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Well under the file store's stale-lock threshold: a refresh that outlived it
|
|
64
|
+
* would see its lock taken over while still holding a token, and the race the
|
|
65
|
+
* lock exists to prevent would be back.
|
|
66
|
+
*/
|
|
67
|
+
export const REFRESH_TIMEOUT_MS = 15_000;
|
|
68
|
+
|
|
69
|
+
export interface CredentialSourceOptions {
|
|
70
|
+
now?: () => number;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* A browser sign-in whose credential lands in `store`. Opening `url` is the
|
|
75
|
+
* host's; `done` settles once the credential is stored.
|
|
76
|
+
*/
|
|
77
|
+
export async function startProviderSignIn(
|
|
78
|
+
provider: string,
|
|
79
|
+
method: OAuthMethod,
|
|
80
|
+
store: CredentialStore,
|
|
81
|
+
appName: string,
|
|
82
|
+
): Promise<SignIn<void>> {
|
|
83
|
+
const attempt = await method.begin();
|
|
84
|
+
return openSignIn<void>({
|
|
85
|
+
// The method's client takes this one address only: a taken port leaves a pasted answer.
|
|
86
|
+
redirect: { ...attempt.redirect, anyPortIfTaken: false },
|
|
87
|
+
prepare: async () => ({ url: attempt.url, state: new URL(attempt.url).searchParams.get("state") ?? "" }),
|
|
88
|
+
finish: async (code) => {
|
|
89
|
+
const credential = await attempt.complete(code);
|
|
90
|
+
await store.modify(provider, async () => credential);
|
|
91
|
+
},
|
|
92
|
+
failure: (message, cause) => new AgentError("config/not-signed-in", message, { cause, details: { provider } }),
|
|
93
|
+
acceptsBareCode: true,
|
|
94
|
+
timeoutMs: SIGN_IN_TIMEOUT_MS,
|
|
95
|
+
appName,
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Names no command: how somebody signs in is the host's to say. */
|
|
100
|
+
export function notSignedIn(provider: string): AgentError {
|
|
101
|
+
return new AgentError("config/not-signed-in", `Provider "${provider}" is not signed in.`, {
|
|
102
|
+
details: { provider },
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* A valid credential on every call, refreshed under the store's lock when due.
|
|
108
|
+
*
|
|
109
|
+
* Holds no state of its own: several callers in one process queue on the same
|
|
110
|
+
* lock as callers in other processes, and whoever comes second finds a fresh
|
|
111
|
+
* token under it and refreshes nothing.
|
|
112
|
+
*/
|
|
113
|
+
export function credentialSource(
|
|
114
|
+
store: CredentialStore,
|
|
115
|
+
provider: string,
|
|
116
|
+
method: OAuthMethod,
|
|
117
|
+
options: CredentialSourceOptions = {},
|
|
118
|
+
): () => Promise<OAuthCredential> {
|
|
119
|
+
const now = options.now ?? Date.now;
|
|
120
|
+
const expiresSoon = (credential: OAuthCredential): boolean =>
|
|
121
|
+
now() + REFRESH_MARGIN_MS >= credential.expires;
|
|
122
|
+
|
|
123
|
+
return async () => {
|
|
124
|
+
const stored = await store.read(provider);
|
|
125
|
+
if (stored !== undefined && !expiresSoon(stored)) return stored;
|
|
126
|
+
|
|
127
|
+
const next = await store.modify(provider, async (current) => {
|
|
128
|
+
if (current === undefined) return undefined;
|
|
129
|
+
// Someone else refreshed while we waited for the lock.
|
|
130
|
+
if (!expiresSoon(current)) return undefined;
|
|
131
|
+
// What was read under the lock, not the copy from before it: a sign-in
|
|
132
|
+
// in between would otherwise be refreshed with a token already spent.
|
|
133
|
+
return method.refresh(current, AbortSignal.timeout(REFRESH_TIMEOUT_MS));
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
if (next === undefined) throw notSignedIn(provider);
|
|
137
|
+
return next;
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* For tests and for a library host with one user and nowhere to keep files.
|
|
143
|
+
* Serialises per provider in-process only.
|
|
144
|
+
*/
|
|
145
|
+
export function memoryCredentialStore(
|
|
146
|
+
initial: Record<string, OAuthCredential> = {},
|
|
147
|
+
): CredentialStore {
|
|
148
|
+
const entries = new Map(Object.entries(initial));
|
|
149
|
+
const queues = new Map<string, Promise<unknown>>();
|
|
150
|
+
|
|
151
|
+
function queued<T>(provider: string, task: () => Promise<T>): Promise<T> {
|
|
152
|
+
const run = (queues.get(provider) ?? Promise.resolve()).then(task);
|
|
153
|
+
queues.set(
|
|
154
|
+
provider,
|
|
155
|
+
run.catch(() => undefined),
|
|
156
|
+
);
|
|
157
|
+
return run;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
read: async (provider) => entries.get(provider),
|
|
162
|
+
|
|
163
|
+
modify: (provider, fn) =>
|
|
164
|
+
queued(provider, async () => {
|
|
165
|
+
const current = entries.get(provider);
|
|
166
|
+
const next = await fn(current);
|
|
167
|
+
if (next === undefined) return current;
|
|
168
|
+
entries.set(provider, next);
|
|
169
|
+
return next;
|
|
170
|
+
}),
|
|
171
|
+
|
|
172
|
+
delete: (provider) =>
|
|
173
|
+
queued(provider, async () => {
|
|
174
|
+
entries.delete(provider);
|
|
175
|
+
}),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import { WRAITH, type AppIdentity } from "../app";
|
|
2
|
+
import { type Config, defaultApiKeyEnv, INHERIT_MODEL, type ReasoningEffort } from "../config/schema";
|
|
3
|
+
import { AgentError } from "../errors";
|
|
4
|
+
import { cacheOptionsFor } from "./cache";
|
|
5
|
+
import type { ModelCapabilities } from "./capabilities";
|
|
6
|
+
import { type CatalogModel, parseModelCatalog } from "./catalog";
|
|
7
|
+
import { catalogView } from "./catalog-view";
|
|
8
|
+
import { builtinProviderFactories } from "./factories/index";
|
|
9
|
+
import { type Model, type Provider, providerFrom } from "./model";
|
|
10
|
+
import type { SignIn } from "../sign-in/attempt";
|
|
11
|
+
import {
|
|
12
|
+
type CredentialStore,
|
|
13
|
+
credentialSource,
|
|
14
|
+
type OAuthCredential,
|
|
15
|
+
type OAuthMethod,
|
|
16
|
+
type OAuthMethodLoader,
|
|
17
|
+
startProviderSignIn,
|
|
18
|
+
} from "./oauth";
|
|
19
|
+
import { builtinOAuthMethods } from "./oauth/methods";
|
|
20
|
+
import {
|
|
21
|
+
type ModelCallSettings,
|
|
22
|
+
type ProviderFactoryLoader,
|
|
23
|
+
type ProviderInstance,
|
|
24
|
+
settingsFromProfile,
|
|
25
|
+
} from "./types";
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Turns a model reference into a model.
|
|
29
|
+
*
|
|
30
|
+
* A reference is one of, in this order:
|
|
31
|
+
* 1. a profile name from config.models ("default", "cheap", "reviewer")
|
|
32
|
+
* 2. "provider:model" ("openrouter:anthropic/claude-opus-5")
|
|
33
|
+
* 3. a bare model id, when exactly one provider is registered
|
|
34
|
+
*
|
|
35
|
+
* Profiles exist only in a registry made from config. The separator is ":" to
|
|
36
|
+
* match AI SDK's own registry convention; model ids keep their slashes, so
|
|
37
|
+
* splitting on the first colon is unambiguous.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
export const PROVIDER_SEPARATOR = ":";
|
|
41
|
+
|
|
42
|
+
export interface ResolveOptions {
|
|
43
|
+
/**
|
|
44
|
+
* The effort for this model, over whatever the profile says.
|
|
45
|
+
* `provider-default` clears it.
|
|
46
|
+
*/
|
|
47
|
+
reasoning?: ReasoningEffort;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* A provider, or what makes one on first use. The second is how a registry
|
|
52
|
+
* made from config keeps a vendor's SDK unloaded until somebody asks for it.
|
|
53
|
+
*/
|
|
54
|
+
export type ProviderEntry = Provider | (() => Promise<Provider>);
|
|
55
|
+
|
|
56
|
+
/** A model a registry resolved, which always knows the reference it was asked by. */
|
|
57
|
+
export type RegistryModel = Model & { readonly ref: string };
|
|
58
|
+
|
|
59
|
+
export interface ProviderRegistry {
|
|
60
|
+
providerNames(): string[];
|
|
61
|
+
/** Throws `provider/unknown` for a name it does not hold. */
|
|
62
|
+
provider(name: string): Promise<Provider>;
|
|
63
|
+
resolve(ref: string, options?: ResolveOptions): Promise<RegistryModel>;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Providers by name, made in code: `createProviderRegistry({ openrouter: openrouter({ apiKey }) })`. */
|
|
67
|
+
export function createProviderRegistry(entries: Readonly<Record<string, ProviderEntry>>): ProviderRegistry {
|
|
68
|
+
const names = Object.keys(entries);
|
|
69
|
+
const made = new Map(
|
|
70
|
+
Object.entries(entries).map(([name, entry]) => [
|
|
71
|
+
name,
|
|
72
|
+
typeof entry === "function" ? once(entry) : async () => entry,
|
|
73
|
+
]),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
const provider = async (name: string): Promise<Provider> => {
|
|
77
|
+
const make = made.get(name);
|
|
78
|
+
if (make === undefined) throw unknownProvider(name, names);
|
|
79
|
+
return make();
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
providerNames: () => [...names],
|
|
84
|
+
provider,
|
|
85
|
+
async resolve(ref, options = {}) {
|
|
86
|
+
const { providerName, modelId } = splitRef(ref, names);
|
|
87
|
+
const model = (await provider(providerName)).model(modelId, {
|
|
88
|
+
ref,
|
|
89
|
+
settings: withReasoning({}, options.reasoning),
|
|
90
|
+
});
|
|
91
|
+
// What the session records is what a resume asks this registry for: the
|
|
92
|
+
// key, not the provider's own name, and the ref even if a provider drops it.
|
|
93
|
+
return { ...model, ref, providerName };
|
|
94
|
+
},
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export interface RegistryFromConfigOptions {
|
|
99
|
+
/**
|
|
100
|
+
* Looks up a key in the environment, where it wins over the config's key.
|
|
101
|
+
* Left out, the registry reads no environment at all.
|
|
102
|
+
*/
|
|
103
|
+
env?: (variable: string) => string | undefined;
|
|
104
|
+
/** Extra loaders, merged over the built-ins and keyed by provider type. Lets a host add vendors. */
|
|
105
|
+
factories?: Record<string, ProviderFactoryLoader>;
|
|
106
|
+
/** Where windows and prices come from; without it they are unknown. */
|
|
107
|
+
capabilities?: ModelCapabilities;
|
|
108
|
+
/** Whose command and directory error messages name. Only branding. */
|
|
109
|
+
app?: AppIdentity;
|
|
110
|
+
/**
|
|
111
|
+
* Where sign-ins live, for provider types that sign in instead of taking a
|
|
112
|
+
* key. A host running on API keys leaves this out and nothing changes.
|
|
113
|
+
*/
|
|
114
|
+
credentials?: CredentialStore;
|
|
115
|
+
/** Extra sign-in methods, merged over the built-ins, keyed by provider type. */
|
|
116
|
+
oauthMethods?: Record<string, OAuthMethodLoader>;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Which of the two sources supplied a provider's key — never the key.
|
|
121
|
+
*
|
|
122
|
+
* The order lives only in `registryFromConfig`; anything that reports it asks
|
|
123
|
+
* `keyOrigin`. A second copy of the order would let `key list` disagree with
|
|
124
|
+
* the run.
|
|
125
|
+
*/
|
|
126
|
+
export type ProviderKeyOrigin =
|
|
127
|
+
| { source: "env"; variable: string }
|
|
128
|
+
| { source: "config" }
|
|
129
|
+
| { source: "none"; variable: string }
|
|
130
|
+
/** Takes no key at all: the provider type signs in. */
|
|
131
|
+
| { source: "sign-in" };
|
|
132
|
+
|
|
133
|
+
export interface ConfiguredRegistry extends ProviderRegistry {
|
|
134
|
+
profileNames(): string[];
|
|
135
|
+
/** Absent `ref` means the configured default. */
|
|
136
|
+
resolve(ref?: string, options?: ResolveOptions): Promise<RegistryModel>;
|
|
137
|
+
/** Asks the provider which models it currently offers. Never cached here. */
|
|
138
|
+
listModels(name: string, fetchImpl?: typeof globalThis.fetch): Promise<CatalogModel[]>;
|
|
139
|
+
/** Where this provider's key came from, for `key list` and `doctor`. */
|
|
140
|
+
keyOrigin(name: string): ProviderKeyOrigin;
|
|
141
|
+
/** How this provider signs in, or undefined when it takes a key. */
|
|
142
|
+
oauthMethod(name: string): Promise<OAuthMethod | undefined>;
|
|
143
|
+
/**
|
|
144
|
+
* Starts a browser sign-in for a provider that signs in, into `credentials`.
|
|
145
|
+
* Opening `url` is the host's; `done` settles once the sign-in is stored.
|
|
146
|
+
*/
|
|
147
|
+
signIn(name: string): Promise<SignIn<void>>;
|
|
148
|
+
/**
|
|
149
|
+
* True when this provider signs in and nothing is kept under its name yet.
|
|
150
|
+
* False for one that takes a key, and for an expired sign-in, which is refreshed.
|
|
151
|
+
*/
|
|
152
|
+
needsSignIn(name: string): Promise<boolean>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export interface AuxiliaryModelOptions {
|
|
156
|
+
/** What config says: a profile, a "provider:model", or `INHERIT_MODEL`. */
|
|
157
|
+
ref: string;
|
|
158
|
+
/** What inheriting means here — the reference the run itself resolved. */
|
|
159
|
+
inheritFrom: string;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* The model for a mechanism that runs beside the conversation, such as
|
|
164
|
+
* compaction or the approval classifier. Each one resolves it through this
|
|
165
|
+
* function: resolving it by hand can leave the config knob with no effect.
|
|
166
|
+
*/
|
|
167
|
+
export async function resolveAuxiliaryModel(
|
|
168
|
+
registry: ProviderRegistry,
|
|
169
|
+
options: AuxiliaryModelOptions,
|
|
170
|
+
): Promise<RegistryModel> {
|
|
171
|
+
return registry.resolve(options.ref === INHERIT_MODEL ? options.inheritFrom : options.ref);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
interface Built {
|
|
175
|
+
provider: Provider;
|
|
176
|
+
instance: ProviderInstance;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* A registry over a config's providers. Making it loads nothing: a vendor's
|
|
181
|
+
* SDK is imported when that provider is first resolved, so one that nobody
|
|
182
|
+
* asks for this run never loads, and a misconfigured one cannot break another.
|
|
183
|
+
*/
|
|
184
|
+
export function registryFromConfig(
|
|
185
|
+
config: Config,
|
|
186
|
+
options: RegistryFromConfigOptions = {},
|
|
187
|
+
): ConfiguredRegistry {
|
|
188
|
+
const loaders = { ...builtinProviderFactories, ...options.factories };
|
|
189
|
+
const oauthLoaders = { ...builtinOAuthMethods, ...options.oauthMethods };
|
|
190
|
+
const app = options.app ?? WRAITH;
|
|
191
|
+
const providerNames = Object.keys(config.providers);
|
|
192
|
+
const keys = new Map<string, { apiKey: string; origin: ProviderKeyOrigin }>();
|
|
193
|
+
const built: Record<string, () => Promise<Built>> = {};
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Environment first, then the config's key. With the config first,
|
|
197
|
+
* `KEY=… wraith run` would be silently ignored whenever the config holds a
|
|
198
|
+
* key. A host that passes no `env` keeps the config key; that is the
|
|
199
|
+
* multi-tenant case.
|
|
200
|
+
*/
|
|
201
|
+
for (const [name, providerConfig] of Object.entries(config.providers)) {
|
|
202
|
+
if (oauthLoaders[providerConfig.type] !== undefined) {
|
|
203
|
+
keys.set(name, { apiKey: "", origin: { source: "sign-in" } });
|
|
204
|
+
} else {
|
|
205
|
+
const variable = providerConfig.apiKeyEnv ?? defaultApiKeyEnv(name);
|
|
206
|
+
const fromEnv = options.env?.(variable);
|
|
207
|
+
const fromConfig = providerConfig.apiKey;
|
|
208
|
+
keys.set(
|
|
209
|
+
name,
|
|
210
|
+
fromEnv !== undefined && fromEnv !== ""
|
|
211
|
+
? { apiKey: fromEnv, origin: { source: "env", variable } }
|
|
212
|
+
: fromConfig !== undefined && fromConfig !== ""
|
|
213
|
+
? { apiKey: fromConfig, origin: { source: "config" } }
|
|
214
|
+
: { apiKey: "", origin: { source: "none", variable } },
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
built[name] = once(() => build(name));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function build(name: string): Promise<Built> {
|
|
221
|
+
const providerConfig = config.providers[name];
|
|
222
|
+
if (providerConfig === undefined) throw unknownProvider(name, providerNames);
|
|
223
|
+
|
|
224
|
+
const loader = loaders[providerConfig.type];
|
|
225
|
+
if (loader === undefined) {
|
|
226
|
+
throw new AgentError(
|
|
227
|
+
"provider/unknown",
|
|
228
|
+
`Provider "${name}" has unknown type "${providerConfig.type}". Available types: ${Object.keys(loaders).join(", ")}.`,
|
|
229
|
+
{ details: { provider: name, type: providerConfig.type, available: Object.keys(loaders) } },
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
let factory: Awaited<ReturnType<ProviderFactoryLoader>>;
|
|
234
|
+
try {
|
|
235
|
+
factory = await loader();
|
|
236
|
+
} catch (cause) {
|
|
237
|
+
throw new AgentError(
|
|
238
|
+
"provider/load-failed",
|
|
239
|
+
`Could not load the "${providerConfig.type}" provider. Its SDK package may not be installed.`,
|
|
240
|
+
{ cause, details: { provider: name, type: providerConfig.type } },
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const credential = await signInFor(name, providerConfig.type);
|
|
245
|
+
const instance = factory({
|
|
246
|
+
name,
|
|
247
|
+
apiKey: keys.get(name)?.apiKey ?? "",
|
|
248
|
+
config: { ...providerConfig, apiKeyEnv: providerConfig.apiKeyEnv ?? defaultApiKeyEnv(name) },
|
|
249
|
+
app,
|
|
250
|
+
...(credential === undefined ? {} : { credential }),
|
|
251
|
+
});
|
|
252
|
+
const provider = providerFrom(instance, {
|
|
253
|
+
name,
|
|
254
|
+
view: catalogView(name, providerConfig.type),
|
|
255
|
+
capabilities: options.capabilities,
|
|
256
|
+
cache: cacheOptionsFor(config, name),
|
|
257
|
+
});
|
|
258
|
+
return { provider, instance };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
async function loadOAuthMethod(name: string, type: string): Promise<OAuthMethod | undefined> {
|
|
262
|
+
const loader = oauthLoaders[type];
|
|
263
|
+
if (loader === undefined) return undefined;
|
|
264
|
+
try {
|
|
265
|
+
return await loader(app);
|
|
266
|
+
} catch (cause) {
|
|
267
|
+
throw new AgentError(
|
|
268
|
+
"provider/load-failed",
|
|
269
|
+
`Could not load how the "${type}" provider signs in.`,
|
|
270
|
+
{ cause, details: { provider: name, type } },
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** The store and the method folded into one function, so a factory sees neither. */
|
|
276
|
+
async function signInFor(
|
|
277
|
+
name: string,
|
|
278
|
+
type: string,
|
|
279
|
+
): Promise<(() => Promise<OAuthCredential>) | undefined> {
|
|
280
|
+
if (options.credentials === undefined) return undefined;
|
|
281
|
+
const method = await loadOAuthMethod(name, type);
|
|
282
|
+
return method === undefined ? undefined : credentialSource(options.credentials, name, method);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const builtFor = (name: string): Promise<Built> => {
|
|
286
|
+
const entry = built[name];
|
|
287
|
+
return entry === undefined ? Promise.reject(unknownProvider(name, providerNames)) : entry();
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const registry = createProviderRegistry(
|
|
291
|
+
Object.fromEntries(providerNames.map((name) => [name, async () => (await builtFor(name)).provider])),
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
providerNames: () => [...providerNames],
|
|
296
|
+
profileNames: () => Object.keys(config.models),
|
|
297
|
+
provider: registry.provider,
|
|
298
|
+
|
|
299
|
+
keyOrigin(name: string): ProviderKeyOrigin {
|
|
300
|
+
return (
|
|
301
|
+
keys.get(name)?.origin ?? {
|
|
302
|
+
source: "none",
|
|
303
|
+
variable: config.providers[name]?.apiKeyEnv ?? defaultApiKeyEnv(name),
|
|
304
|
+
}
|
|
305
|
+
);
|
|
306
|
+
},
|
|
307
|
+
|
|
308
|
+
async oauthMethod(name: string): Promise<OAuthMethod | undefined> {
|
|
309
|
+
const providerConfig = config.providers[name];
|
|
310
|
+
if (providerConfig === undefined) throw unknownProvider(name, providerNames);
|
|
311
|
+
return loadOAuthMethod(name, providerConfig.type);
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
async signIn(name: string): Promise<SignIn<void>> {
|
|
315
|
+
const providerConfig = config.providers[name];
|
|
316
|
+
if (providerConfig === undefined) throw unknownProvider(name, providerNames);
|
|
317
|
+
const method = await loadOAuthMethod(name, providerConfig.type);
|
|
318
|
+
if (method === undefined) {
|
|
319
|
+
throw new AgentError("config/invalid", `Provider "${name}" takes an API key, not a sign-in.`, {
|
|
320
|
+
details: { provider: name },
|
|
321
|
+
});
|
|
322
|
+
}
|
|
323
|
+
if (options.credentials === undefined) {
|
|
324
|
+
throw new AgentError("config/not-signed-in", "There is nowhere to keep a sign-in: give the registry a credential store.", {
|
|
325
|
+
details: { provider: name },
|
|
326
|
+
});
|
|
327
|
+
}
|
|
328
|
+
return startProviderSignIn(name, method, options.credentials, app.name);
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
async needsSignIn(name: string): Promise<boolean> {
|
|
332
|
+
const providerConfig = config.providers[name];
|
|
333
|
+
if (providerConfig === undefined) throw unknownProvider(name, providerNames);
|
|
334
|
+
// The loader, not the method: knowing that it signs in needs nothing loaded.
|
|
335
|
+
if (oauthLoaders[providerConfig.type] === undefined) return false;
|
|
336
|
+
if (options.credentials === undefined) return true;
|
|
337
|
+
return (await options.credentials.read(name)) === undefined;
|
|
338
|
+
},
|
|
339
|
+
|
|
340
|
+
async listModels(name, fetchImpl = globalThis.fetch): Promise<CatalogModel[]> {
|
|
341
|
+
const endpoint = (await builtFor(name)).instance.modelsEndpoint;
|
|
342
|
+
if (endpoint === undefined) {
|
|
343
|
+
throw new AgentError(
|
|
344
|
+
"provider/request-failed",
|
|
345
|
+
`Provider "${name}" does not expose a model catalogue.`,
|
|
346
|
+
{ details: { provider: name } },
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const apiKey = keys.get(name)?.apiKey ?? "";
|
|
351
|
+
|
|
352
|
+
let response: Response;
|
|
353
|
+
try {
|
|
354
|
+
response = await fetchImpl(endpoint, {
|
|
355
|
+
headers: {
|
|
356
|
+
...config.providers[name]?.headers,
|
|
357
|
+
...(apiKey === "" ? {} : { Authorization: `Bearer ${apiKey}` }),
|
|
358
|
+
},
|
|
359
|
+
});
|
|
360
|
+
} catch (cause) {
|
|
361
|
+
// A local runtime that is not running is the common case here, so the
|
|
362
|
+
// message names the endpoint rather than surfacing a socket error.
|
|
363
|
+
throw new AgentError(
|
|
364
|
+
"provider/request-failed",
|
|
365
|
+
`Could not reach "${name}" at ${endpoint}. Is it running and reachable?`,
|
|
366
|
+
{ cause, details: { provider: name, endpoint } },
|
|
367
|
+
);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
if (!response.ok) {
|
|
371
|
+
throw new AgentError(
|
|
372
|
+
"provider/request-failed",
|
|
373
|
+
`Provider "${name}" returned ${response.status} for its model catalogue.`,
|
|
374
|
+
{ details: { provider: name, status: response.status, endpoint } },
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
return parseModelCatalog(await response.json());
|
|
379
|
+
},
|
|
380
|
+
|
|
381
|
+
async resolve(ref?: string, resolveOptions: ResolveOptions = {}): Promise<RegistryModel> {
|
|
382
|
+
const requested = ref ?? config.defaultModel;
|
|
383
|
+
if (requested === undefined || requested === "") {
|
|
384
|
+
// What is wrong, and nothing about how to fix it: the commands are the
|
|
385
|
+
// host's, and it adds them from `details`.
|
|
386
|
+
throw new AgentError(
|
|
387
|
+
"model/not-configured",
|
|
388
|
+
"No model selected, and the configuration names no default.",
|
|
389
|
+
{ details: { profiles: Object.keys(config.models), providers: providerNames } },
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const profile = config.models[requested];
|
|
394
|
+
const { providerName, modelId } = splitRef(profile?.model ?? requested, providerNames);
|
|
395
|
+
const settings = profile === undefined ? {} : settingsFromProfile(profile);
|
|
396
|
+
|
|
397
|
+
const model = (await registry.provider(providerName)).model(modelId, {
|
|
398
|
+
ref: requested,
|
|
399
|
+
settings: withReasoning(settings, resolveOptions.reasoning),
|
|
400
|
+
// A price written by hand states this user's bill; the catalog's is the public one.
|
|
401
|
+
...(profile?.pricing === undefined ? {} : { pricing: profile.pricing }),
|
|
402
|
+
});
|
|
403
|
+
return { ...model, ref: requested };
|
|
404
|
+
},
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Builds once and hands every later caller the same promise, so two resolves
|
|
410
|
+
* at once share one build. A failed build is forgotten and tried again.
|
|
411
|
+
*/
|
|
412
|
+
function once<T>(build: () => Promise<T>): () => Promise<T> {
|
|
413
|
+
let pending: Promise<T> | undefined;
|
|
414
|
+
return () => {
|
|
415
|
+
pending ??= build().catch((error: unknown) => {
|
|
416
|
+
pending = undefined;
|
|
417
|
+
throw error;
|
|
418
|
+
});
|
|
419
|
+
return pending;
|
|
420
|
+
};
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function withReasoning(settings: ModelCallSettings, reasoning: ReasoningEffort | undefined): ModelCallSettings {
|
|
424
|
+
const next = { ...settings };
|
|
425
|
+
if (reasoning === "provider-default") delete next.reasoning;
|
|
426
|
+
else if (reasoning !== undefined) next.reasoning = reasoning;
|
|
427
|
+
return next;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function unknownProvider(name: string, names: readonly string[]): AgentError {
|
|
431
|
+
return new AgentError(
|
|
432
|
+
"provider/unknown",
|
|
433
|
+
`Unknown provider "${name}". Configured: ${names.join(", ") || "(none)"}.`,
|
|
434
|
+
{ details: { requested: name, configured: [...names] } },
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function splitRef(ref: string, names: readonly string[]): { providerName: string; modelId: string } {
|
|
439
|
+
const separatorAt = ref.indexOf(PROVIDER_SEPARATOR);
|
|
440
|
+
const prefix = separatorAt > 0 ? ref.slice(0, separatorAt) : undefined;
|
|
441
|
+
|
|
442
|
+
let split: { providerName: string; modelId: string } | undefined;
|
|
443
|
+
// `vendor/model:free` is a model id with the separator in it. A prefix
|
|
444
|
+
// without a slash stays a provider, so one since removed is still an error.
|
|
445
|
+
if (prefix !== undefined && (!prefix.includes("/") || names.includes(prefix))) {
|
|
446
|
+
split = { providerName: prefix, modelId: ref.slice(separatorAt + PROVIDER_SEPARATOR.length) };
|
|
447
|
+
} else if (names.length === 1 && names[0] !== undefined) {
|
|
448
|
+
split = { providerName: names[0], modelId: ref };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
if (split === undefined) {
|
|
452
|
+
throw new AgentError(
|
|
453
|
+
"model/unknown-alias",
|
|
454
|
+
`Ambiguous model "${ref}". Several providers are configured (${names.join(", ")}) — write it as "provider${PROVIDER_SEPARATOR}model" or define a profile in config.models.`,
|
|
455
|
+
{ details: { requested: ref, providers: [...names] } },
|
|
456
|
+
);
|
|
457
|
+
}
|
|
458
|
+
if (split.modelId === "") {
|
|
459
|
+
throw new AgentError("model/unknown-alias", `Model reference "${ref}" has no model id.`, {
|
|
460
|
+
details: { requested: ref },
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
return split;
|
|
464
|
+
}
|