@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,355 @@
|
|
|
1
|
+
import type { ModelCapabilities, ModelInfo, ModelListing } from "./capabilities";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Model capabilities from models.dev. The catalog is a convenience, never a
|
|
5
|
+
* gate: starting up must not touch the network, storage keeps a projection of
|
|
6
|
+
* the fields we use, and anything unknown answers "I don't know" and the
|
|
7
|
+
* provider decides.
|
|
8
|
+
*
|
|
9
|
+
* It knows tables, not providers: which table a provider reads, and what its
|
|
10
|
+
* backend serves differently, is in `catalog-view.ts`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const MODELS_DEV_ENDPOINT = "https://models.dev/api.json";
|
|
14
|
+
|
|
15
|
+
/** One day. The catalog changes weekly; nobody needs it fresher than this. */
|
|
16
|
+
export const DEFAULT_TTL_MS = 24 * 60 * 60 * 1_000;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Bumped whenever `toModelInfo` learns a new field. The cache holds our
|
|
20
|
+
* projection, so an old cache lacks the new field, and an ETag keeps it that
|
|
21
|
+
* way: a 304 keeps the old index. Exported so host fixtures follow the bump.
|
|
22
|
+
*/
|
|
23
|
+
export const CAPABILITY_CACHE_VERSION = 4;
|
|
24
|
+
|
|
25
|
+
/** Where a host keeps the catalog between runs: a file, a key in Redis, a variable. */
|
|
26
|
+
export interface CapabilityStorage {
|
|
27
|
+
read(): Promise<string | null>;
|
|
28
|
+
write(text: string): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface CapabilityIndex {
|
|
32
|
+
/** provider id → model id → what we use. */
|
|
33
|
+
byProvider: Record<string, Record<string, ModelInfo>>;
|
|
34
|
+
/**
|
|
35
|
+
* Model id alone, for endpoints models.dev does not know as providers —
|
|
36
|
+
* a local Ollama or a gateway named whatever its owner felt like.
|
|
37
|
+
*/
|
|
38
|
+
byModel: Record<string, ModelInfo>;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
interface CachedIndex extends CapabilityIndex {
|
|
42
|
+
cacheVersion: number;
|
|
43
|
+
fetchedAt: number;
|
|
44
|
+
etag?: string;
|
|
45
|
+
/**
|
|
46
|
+
* The tables this index was cut for, sorted; absent means all of them. A 304
|
|
47
|
+
* says the catalog is unchanged, not the cut: it keeps an old cut for good.
|
|
48
|
+
* Keeps its old name so files already written still match.
|
|
49
|
+
*/
|
|
50
|
+
providers?: string[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export type RefreshOutcome = "updated" | "unchanged" | "unavailable";
|
|
54
|
+
|
|
55
|
+
export interface ModelsDevOptions {
|
|
56
|
+
/** Absent: the catalog lives in memory only, and `load()` has nothing to read. */
|
|
57
|
+
storage?: CapabilityStorage;
|
|
58
|
+
fetchImpl?: typeof globalThis.fetch;
|
|
59
|
+
endpoint?: string;
|
|
60
|
+
/**
|
|
61
|
+
* Keep only these tables; everything still lands in `byModel`. A config's
|
|
62
|
+
* providers give theirs through `catalogTables`.
|
|
63
|
+
*/
|
|
64
|
+
tables?: readonly string[];
|
|
65
|
+
ttlMs?: number;
|
|
66
|
+
now?: () => number;
|
|
67
|
+
/**
|
|
68
|
+
* A catalog baked in at build time, or one the host fetched itself. In use
|
|
69
|
+
* from the start; what `load()` finds in storage replaces it. The core
|
|
70
|
+
* neither fetches it nor knows where it came from.
|
|
71
|
+
*/
|
|
72
|
+
snapshot?: CapabilityIndex;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export interface ModelsDevCapabilities extends ModelCapabilities {
|
|
76
|
+
/** Reads the cache. Never goes near the network. */
|
|
77
|
+
load(): Promise<void>;
|
|
78
|
+
/** Conditional request; returns what happened instead of throwing. */
|
|
79
|
+
refresh(): Promise<RefreshOutcome>;
|
|
80
|
+
isStale(): boolean;
|
|
81
|
+
readonly index: CapabilityIndex;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function asRecord(value: unknown): Record<string, unknown> | null {
|
|
85
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
86
|
+
? (value as Record<string, unknown>)
|
|
87
|
+
: null;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function asNumber(value: unknown): number | undefined {
|
|
91
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Reads `reasoning_options: [{ type: "effort", values: [...] }]`. A JSON `null`
|
|
96
|
+
* means reasoning off, which is `none`. `default` names no level and is left
|
|
97
|
+
* out. A `toggle` option means thinking can be switched off: `none` too,
|
|
98
|
+
* or the classifier's quickest first stage falls to the lowest listed level.
|
|
99
|
+
*/
|
|
100
|
+
function readEfforts(value: unknown): string[] | undefined {
|
|
101
|
+
if (!Array.isArray(value)) return undefined;
|
|
102
|
+
const efforts: string[] = [];
|
|
103
|
+
let toggle = false;
|
|
104
|
+
for (const entry of value) {
|
|
105
|
+
const option = asRecord(entry);
|
|
106
|
+
if (option?.type === "toggle") toggle = true;
|
|
107
|
+
if (option?.type !== "effort" || !Array.isArray(option.values)) continue;
|
|
108
|
+
for (const level of option.values) {
|
|
109
|
+
const name = level === null ? "none" : level;
|
|
110
|
+
if (typeof name === "string" && name !== "default" && !efforts.includes(name)) efforts.push(name);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
if (toggle && efforts.length > 0 && !efforts.includes("none")) efforts.unshift("none");
|
|
114
|
+
return efforts.length === 0 ? undefined : efforts;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const STATUSES: ReadonlySet<string> = new Set(["alpha", "beta", "deprecated"]);
|
|
118
|
+
|
|
119
|
+
function toModelInfo(raw: unknown): ModelInfo | null {
|
|
120
|
+
const model = asRecord(raw);
|
|
121
|
+
if (model === null) return null;
|
|
122
|
+
|
|
123
|
+
const limit = asRecord(model.limit);
|
|
124
|
+
const cost = asRecord(model.cost);
|
|
125
|
+
const info: ModelInfo = {};
|
|
126
|
+
|
|
127
|
+
if (typeof model.name === "string" && model.name !== "") info.name = model.name;
|
|
128
|
+
if (typeof model.reasoning === "boolean") info.reasoning = model.reasoning;
|
|
129
|
+
if (typeof model.release_date === "string" && model.release_date !== "") {
|
|
130
|
+
info.releaseDate = model.release_date;
|
|
131
|
+
}
|
|
132
|
+
if (typeof model.status === "string" && STATUSES.has(model.status)) {
|
|
133
|
+
info.status = model.status as NonNullable<ModelInfo["status"]>;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const context = asNumber(limit?.context);
|
|
137
|
+
if (context !== undefined) info.contextLimit = context;
|
|
138
|
+
|
|
139
|
+
const output = asNumber(limit?.output);
|
|
140
|
+
if (output !== undefined) info.outputLimit = output;
|
|
141
|
+
|
|
142
|
+
const efforts = readEfforts(model.reasoning_options);
|
|
143
|
+
if (efforts !== undefined) info.reasoningEfforts = efforts;
|
|
144
|
+
|
|
145
|
+
if (typeof model.temperature === "boolean") info.supportsTemperature = model.temperature;
|
|
146
|
+
if (typeof model.tool_call === "boolean") info.supportsToolCall = model.tool_call;
|
|
147
|
+
|
|
148
|
+
const modalities = asRecord(model.modalities);
|
|
149
|
+
if (Array.isArray(modalities?.input)) {
|
|
150
|
+
info.input = modalities.input.filter((kind): kind is string => typeof kind === "string");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const input = asNumber(cost?.input);
|
|
154
|
+
if (input !== undefined) info.inputPricePerMillion = input;
|
|
155
|
+
|
|
156
|
+
const outputPrice = asNumber(cost?.output);
|
|
157
|
+
if (outputPrice !== undefined) info.outputPricePerMillion = outputPrice;
|
|
158
|
+
|
|
159
|
+
// Without these, a cached turn is priced with a multiplier even though the
|
|
160
|
+
// catalog has the real rate.
|
|
161
|
+
const cacheRead = asNumber(cost?.cache_read);
|
|
162
|
+
if (cacheRead !== undefined) info.cacheReadPricePerMillion = cacheRead;
|
|
163
|
+
|
|
164
|
+
const cacheWrite = asNumber(cost?.cache_write);
|
|
165
|
+
if (cacheWrite !== undefined) info.cacheWritePricePerMillion = cacheWrite;
|
|
166
|
+
|
|
167
|
+
return Object.keys(info).length === 0 ? null : info;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The payload is keyed by provider, each holding its own `models` map. We keep
|
|
172
|
+
* the handful of fields we act on; the rest — benchmarks, weights, release
|
|
173
|
+
* dates — is somebody else's product.
|
|
174
|
+
*/
|
|
175
|
+
export function parseCapabilityIndex(
|
|
176
|
+
payload: unknown,
|
|
177
|
+
providers?: readonly string[],
|
|
178
|
+
): CapabilityIndex {
|
|
179
|
+
const root = asRecord(payload);
|
|
180
|
+
const wanted = providers === undefined ? null : new Set(providers);
|
|
181
|
+
const byProvider: Record<string, Record<string, ModelInfo>> = {};
|
|
182
|
+
const byModel: Record<string, ModelInfo> = {};
|
|
183
|
+
|
|
184
|
+
for (const [providerName, rawProvider] of Object.entries(root ?? {})) {
|
|
185
|
+
const models = asRecord(asRecord(rawProvider)?.models);
|
|
186
|
+
if (models === null) continue;
|
|
187
|
+
|
|
188
|
+
const table: Record<string, ModelInfo> = {};
|
|
189
|
+
for (const [modelId, rawModel] of Object.entries(models)) {
|
|
190
|
+
const info = toModelInfo(rawModel);
|
|
191
|
+
if (info === null) continue;
|
|
192
|
+
table[modelId] = info;
|
|
193
|
+
|
|
194
|
+
// Same model under several providers: keep the largest window, since a
|
|
195
|
+
// too-small one compacts conversations that did not need it.
|
|
196
|
+
const known = byModel[modelId];
|
|
197
|
+
if (known === undefined || (info.contextLimit ?? 0) > (known.contextLimit ?? 0)) {
|
|
198
|
+
byModel[modelId] = info;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (wanted === null || wanted.has(providerName)) byProvider[providerName] = table;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
return { byProvider, byModel };
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function emptyIndex(): CapabilityIndex {
|
|
209
|
+
return { byProvider: {}, byModel: {} };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** Null for every kind of miss: absent, unparsable, or written by an old build. */
|
|
213
|
+
async function readStored(storage: CapabilityStorage | undefined): Promise<CachedIndex | null> {
|
|
214
|
+
const text = (await storage?.read()) ?? null;
|
|
215
|
+
if (text === null) return null;
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
const cached = JSON.parse(text) as CachedIndex;
|
|
219
|
+
return cached.cacheVersion === CAPABILITY_CACHE_VERSION ? cached : null;
|
|
220
|
+
} catch {
|
|
221
|
+
// A damaged cache is a cache miss, never a failed start.
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The other shape models.dev publishes: one entry per model, keyed by id or in
|
|
228
|
+
* a flat list, without the provider tables. Fields are parsed by the shared
|
|
229
|
+
* `toModelInfo`: a second copy would drift invisibly, because a snapshot only
|
|
230
|
+
* runs when there is nothing to compare it against.
|
|
231
|
+
*/
|
|
232
|
+
export function parseModelIndex(payload: unknown): CapabilityIndex {
|
|
233
|
+
const byModel: Record<string, ModelInfo> = {};
|
|
234
|
+
|
|
235
|
+
const entries: [string, unknown][] = Array.isArray(payload)
|
|
236
|
+
? payload.map((model) => [String(asRecord(model)?.id ?? ""), model])
|
|
237
|
+
: Object.entries(asRecord(payload) ?? {});
|
|
238
|
+
|
|
239
|
+
for (const [key, raw] of entries) {
|
|
240
|
+
const model = asRecord(raw);
|
|
241
|
+
const id = typeof model?.id === "string" && model.id !== "" ? model.id : key;
|
|
242
|
+
if (id === "") continue;
|
|
243
|
+
|
|
244
|
+
const info = toModelInfo(raw);
|
|
245
|
+
if (info === null) continue;
|
|
246
|
+
|
|
247
|
+
// Same rule as the provider-keyed shape: the roomiest window wins, because
|
|
248
|
+
// a window that is too small compacts conversations that did not need it.
|
|
249
|
+
const known = byModel[id];
|
|
250
|
+
if (known === undefined || (info.contextLimit ?? 0) > (known.contextLimit ?? 0)) {
|
|
251
|
+
byModel[id] = info;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return { byProvider: {}, byModel };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export function createModelsDevCapabilities(
|
|
259
|
+
options: ModelsDevOptions = {},
|
|
260
|
+
): ModelsDevCapabilities {
|
|
261
|
+
const now = options.now ?? Date.now;
|
|
262
|
+
const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
|
|
263
|
+
const endpoint = options.endpoint ?? MODELS_DEV_ENDPOINT;
|
|
264
|
+
|
|
265
|
+
// `fetchedAt` stays 0 under a snapshot: it is old by construction, and
|
|
266
|
+
// pretending it is not would stop the first refresh that replaces it.
|
|
267
|
+
let index: CapabilityIndex =
|
|
268
|
+
options.snapshot === undefined
|
|
269
|
+
? emptyIndex()
|
|
270
|
+
: { byProvider: options.snapshot.byProvider, byModel: options.snapshot.byModel };
|
|
271
|
+
let fetchedAt = 0;
|
|
272
|
+
let etag: string | undefined;
|
|
273
|
+
|
|
274
|
+
const wanted: string[] | undefined =
|
|
275
|
+
options.tables === undefined ? undefined : [...new Set(options.tables)].sort();
|
|
276
|
+
|
|
277
|
+
const persist = async (): Promise<void> => {
|
|
278
|
+
const cached: CachedIndex = {
|
|
279
|
+
cacheVersion: CAPABILITY_CACHE_VERSION,
|
|
280
|
+
fetchedAt,
|
|
281
|
+
...(etag === undefined ? {} : { etag }),
|
|
282
|
+
...(wanted === undefined ? {} : { providers: wanted }),
|
|
283
|
+
byProvider: index.byProvider,
|
|
284
|
+
byModel: index.byModel,
|
|
285
|
+
};
|
|
286
|
+
await options.storage?.write(JSON.stringify(cached));
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
return {
|
|
290
|
+
get index() {
|
|
291
|
+
return index;
|
|
292
|
+
},
|
|
293
|
+
|
|
294
|
+
lookup(table: string, modelId: string): ModelInfo | null {
|
|
295
|
+
return index.byProvider[table]?.[modelId] ?? index.byModel[modelId] ?? null;
|
|
296
|
+
},
|
|
297
|
+
|
|
298
|
+
list(table: string): readonly ModelListing[] {
|
|
299
|
+
return Object.entries(index.byProvider[table] ?? {}).map(([id, info]) => ({ id, info }));
|
|
300
|
+
},
|
|
301
|
+
|
|
302
|
+
isStale(): boolean {
|
|
303
|
+
return now() - fetchedAt > ttlMs;
|
|
304
|
+
},
|
|
305
|
+
|
|
306
|
+
async load(): Promise<void> {
|
|
307
|
+
// Every miss (no storage, no file, a damaged one, an old format) keeps
|
|
308
|
+
// what is already in memory: the snapshot, or nothing.
|
|
309
|
+
const cached = await readStored(options.storage);
|
|
310
|
+
if (cached === null) return;
|
|
311
|
+
|
|
312
|
+
index = { byProvider: cached.byProvider ?? {}, byModel: cached.byModel ?? {} };
|
|
313
|
+
// Cut for other tables: still good for everything it has, but stale, and
|
|
314
|
+
// fetched without the ETag — a 304 would keep the old cut for good.
|
|
315
|
+
if (JSON.stringify(cached.providers) !== JSON.stringify(wanted)) return;
|
|
316
|
+
fetchedAt = cached.fetchedAt ?? 0;
|
|
317
|
+
etag = cached.etag;
|
|
318
|
+
},
|
|
319
|
+
|
|
320
|
+
async refresh(): Promise<RefreshOutcome> {
|
|
321
|
+
const fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
322
|
+
|
|
323
|
+
let response: Response;
|
|
324
|
+
try {
|
|
325
|
+
response = await fetchImpl(endpoint, {
|
|
326
|
+
headers: etag === undefined ? {} : { "if-none-match": etag },
|
|
327
|
+
});
|
|
328
|
+
} catch {
|
|
329
|
+
// Offline, blocked, or behind a proxy that hates us: keep what we have.
|
|
330
|
+
return "unavailable";
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// 304 comes back without a body.
|
|
334
|
+
if (response.status === 304) {
|
|
335
|
+
fetchedAt = now();
|
|
336
|
+
await persist();
|
|
337
|
+
return "unchanged";
|
|
338
|
+
}
|
|
339
|
+
if (!response.ok) return "unavailable";
|
|
340
|
+
|
|
341
|
+
let payload: unknown;
|
|
342
|
+
try {
|
|
343
|
+
payload = await response.json();
|
|
344
|
+
} catch {
|
|
345
|
+
return "unavailable";
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
index = parseCapabilityIndex(payload, wanted);
|
|
349
|
+
fetchedAt = now();
|
|
350
|
+
etag = response.headers.get("etag") ?? undefined;
|
|
351
|
+
await persist();
|
|
352
|
+
return "updated";
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { OAuthMethodLoader } from "../oauth";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Provider types that sign in rather than take a key, keyed like
|
|
5
|
+
* `builtinProviderFactories` and loaded as lazily.
|
|
6
|
+
*/
|
|
7
|
+
export const builtinOAuthMethods: Record<string, OAuthMethodLoader> = {
|
|
8
|
+
"openai-codex": (app) =>
|
|
9
|
+
import("./openai-codex").then((module) => module.codexOAuth({ originator: app.name })),
|
|
10
|
+
};
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { AgentError } from "../../errors";
|
|
2
|
+
import type { LoginAttempt, OAuthCredential, OAuthMethod } from "../oauth";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Signing in to Codex with a ChatGPT subscription.
|
|
6
|
+
*
|
|
7
|
+
* The client, endpoints and flow are the ones OpenAI points third-party users
|
|
8
|
+
* at; there is no way to register a client of our own. `originator` is the
|
|
9
|
+
* name this app sends in place of Codex's.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
const CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
13
|
+
const ISSUER = "https://auth.openai.com";
|
|
14
|
+
const REDIRECT_PORT = 1455;
|
|
15
|
+
const REDIRECT_PATH = "/auth/callback";
|
|
16
|
+
const REDIRECT_URI = `http://localhost:${String(REDIRECT_PORT)}${REDIRECT_PATH}`;
|
|
17
|
+
const SCOPE = "openid profile email offline_access";
|
|
18
|
+
const AUTH_CLAIM = "https://api.openai.com/auth";
|
|
19
|
+
|
|
20
|
+
/** A token endpoint that leaves out `expires_in` is taken to mean an hour. */
|
|
21
|
+
const DEFAULT_EXPIRES_IN_SECONDS = 3600;
|
|
22
|
+
|
|
23
|
+
export interface CodexOAuthOptions {
|
|
24
|
+
/** Shown to the user on the authorize page and sent with every request. */
|
|
25
|
+
originator: string;
|
|
26
|
+
fetch?: typeof globalThis.fetch;
|
|
27
|
+
now?: () => number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function base64Url(bytes: Uint8Array): string {
|
|
31
|
+
let binary = "";
|
|
32
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
33
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function randomToken(length: number): string {
|
|
37
|
+
return base64Url(crypto.getRandomValues(new Uint8Array(length)));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function challengeFor(verifier: string): Promise<string> {
|
|
41
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
42
|
+
return base64Url(new Uint8Array(digest));
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function jwtClaims(token: string): Record<string, unknown> | undefined {
|
|
46
|
+
const payload = token.split(".")[1];
|
|
47
|
+
if (payload === undefined) return undefined;
|
|
48
|
+
try {
|
|
49
|
+
const base64 = payload.replace(/-/g, "+").replace(/_/g, "/");
|
|
50
|
+
const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
|
|
51
|
+
const claims: unknown = JSON.parse(atob(padded));
|
|
52
|
+
return typeof claims === "object" && claims !== null ? (claims as Record<string, unknown>) : undefined;
|
|
53
|
+
} catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function stringField(value: unknown, key: string): string | undefined {
|
|
59
|
+
if (typeof value !== "object" || value === null) return undefined;
|
|
60
|
+
const field = (value as Record<string, unknown>)[key];
|
|
61
|
+
return typeof field === "string" && field !== "" ? field : undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The ChatGPT account the backend bills, read from the access token itself.
|
|
66
|
+
*
|
|
67
|
+
* Derived on every request rather than stored, so a credential is the same
|
|
68
|
+
* three fields for every provider.
|
|
69
|
+
*/
|
|
70
|
+
export function codexAccountId(accessToken: string): string | undefined {
|
|
71
|
+
const claims = jwtClaims(accessToken);
|
|
72
|
+
if (claims === undefined) return undefined;
|
|
73
|
+
const organisations = claims["organizations"];
|
|
74
|
+
return (
|
|
75
|
+
stringField(claims[AUTH_CLAIM], "chatgpt_account_id") ??
|
|
76
|
+
stringField(claims, "chatgpt_account_id") ??
|
|
77
|
+
(Array.isArray(organisations) ? stringField(organisations[0], "id") : undefined)
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** What someone pastes: the whole redirect URL, its query string, or the bare code. */
|
|
82
|
+
export function parseRedirect(input: string): { code?: string; state?: string; error?: string } {
|
|
83
|
+
const value = input.trim();
|
|
84
|
+
const fromParams = (params: URLSearchParams) => {
|
|
85
|
+
const result: { code?: string; state?: string; error?: string } = {};
|
|
86
|
+
const code = params.get("code");
|
|
87
|
+
const state = params.get("state");
|
|
88
|
+
const error = params.get("error");
|
|
89
|
+
if (code !== null && code !== "") result.code = code;
|
|
90
|
+
if (state !== null && state !== "") result.state = state;
|
|
91
|
+
if (error !== null && error !== "") result.error = error;
|
|
92
|
+
return result;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
return fromParams(new URL(value).searchParams);
|
|
97
|
+
} catch {
|
|
98
|
+
// Not a URL.
|
|
99
|
+
}
|
|
100
|
+
if (value.includes("=")) return fromParams(new URLSearchParams(value.replace(/^\?/, "")));
|
|
101
|
+
return value === "" ? {} : { code: value };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function codexOAuth(options: CodexOAuthOptions): OAuthMethod {
|
|
105
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
106
|
+
const now = options.now ?? Date.now;
|
|
107
|
+
|
|
108
|
+
async function requestTokens(
|
|
109
|
+
body: Record<string, string>,
|
|
110
|
+
operation: "sign-in" | "refresh",
|
|
111
|
+
previous?: OAuthCredential,
|
|
112
|
+
signal?: AbortSignal,
|
|
113
|
+
): Promise<OAuthCredential> {
|
|
114
|
+
let response: Response;
|
|
115
|
+
try {
|
|
116
|
+
response = await fetchImpl(`${ISSUER}/oauth/token`, {
|
|
117
|
+
method: "POST",
|
|
118
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
119
|
+
body: new URLSearchParams(body),
|
|
120
|
+
...(signal === undefined ? {} : { signal }),
|
|
121
|
+
});
|
|
122
|
+
} catch (cause) {
|
|
123
|
+
throw new AgentError(
|
|
124
|
+
"provider/request-failed",
|
|
125
|
+
`Could not reach ${ISSUER} to ${operation === "refresh" ? "refresh the ChatGPT sign-in" : "finish signing in"}.`,
|
|
126
|
+
{ cause },
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
if (!response.ok) {
|
|
131
|
+
// The error field only — the body of a token endpoint is not something to echo.
|
|
132
|
+
const reason = stringField(await response.json().catch(() => undefined), "error");
|
|
133
|
+
const details = { status: response.status, ...(reason === undefined ? {} : { reason }) };
|
|
134
|
+
// A refresh the server refuses means the grant is gone: revoked, expired, or
|
|
135
|
+
// spent by somebody else. Only a new sign-in brings it back.
|
|
136
|
+
if (operation === "refresh" && (response.status === 400 || response.status === 401)) {
|
|
137
|
+
throw new AgentError(
|
|
138
|
+
"config/not-signed-in",
|
|
139
|
+
`The ChatGPT sign-in has expired or was revoked (${reason ?? String(response.status)}). Sign in again.`,
|
|
140
|
+
{ details },
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
throw new AgentError(
|
|
144
|
+
"provider/request-failed",
|
|
145
|
+
`${ISSUER} refused to ${operation === "refresh" ? "refresh the sign-in" : "finish signing in"} (${reason ?? String(response.status)}).`,
|
|
146
|
+
{ details },
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const json: unknown = await response.json();
|
|
151
|
+
const access = stringField(json, "access_token");
|
|
152
|
+
// Refresh tokens rotate, but a server that keeps the old one must not sign us out.
|
|
153
|
+
const refresh = stringField(json, "refresh_token") ?? previous?.refresh;
|
|
154
|
+
if (access === undefined || refresh === undefined) {
|
|
155
|
+
throw new AgentError("provider/request-failed", `${ISSUER} answered without the tokens it was asked for.`);
|
|
156
|
+
}
|
|
157
|
+
if (codexAccountId(access) === undefined) {
|
|
158
|
+
throw new AgentError(
|
|
159
|
+
"provider/request-failed",
|
|
160
|
+
"The ChatGPT token carries no account id, so Codex would not know whom to bill.",
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const expiresIn = (json as { expires_in?: unknown }).expires_in;
|
|
165
|
+
const seconds = typeof expiresIn === "number" && expiresIn > 0 ? expiresIn : DEFAULT_EXPIRES_IN_SECONDS;
|
|
166
|
+
return { access, refresh, expires: now() + seconds * 1000 };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
return {
|
|
170
|
+
async begin(): Promise<LoginAttempt> {
|
|
171
|
+
const verifier = randomToken(48);
|
|
172
|
+
const state = randomToken(24);
|
|
173
|
+
const url = new URL(`${ISSUER}/oauth/authorize`);
|
|
174
|
+
url.search = new URLSearchParams({
|
|
175
|
+
response_type: "code",
|
|
176
|
+
client_id: CLIENT_ID,
|
|
177
|
+
redirect_uri: REDIRECT_URI,
|
|
178
|
+
scope: SCOPE,
|
|
179
|
+
code_challenge: await challengeFor(verifier),
|
|
180
|
+
code_challenge_method: "S256",
|
|
181
|
+
id_token_add_organizations: "true",
|
|
182
|
+
codex_cli_simplified_flow: "true",
|
|
183
|
+
state,
|
|
184
|
+
originator: options.originator,
|
|
185
|
+
}).toString();
|
|
186
|
+
|
|
187
|
+
return {
|
|
188
|
+
url: url.toString(),
|
|
189
|
+
redirect: { port: REDIRECT_PORT, path: REDIRECT_PATH },
|
|
190
|
+
async complete(redirected) {
|
|
191
|
+
const answer = parseRedirect(redirected);
|
|
192
|
+
if (answer.error !== undefined) {
|
|
193
|
+
throw new AgentError("config/not-signed-in", `Signing in was not completed: ${answer.error}.`);
|
|
194
|
+
}
|
|
195
|
+
// A pasted bare code carries no state and is accepted; a wrong state
|
|
196
|
+
// is rejected.
|
|
197
|
+
if (answer.state !== undefined && answer.state !== state) {
|
|
198
|
+
throw new AgentError(
|
|
199
|
+
"config/not-signed-in",
|
|
200
|
+
"That answer belongs to a different sign-in attempt. Start again.",
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
if (answer.code === undefined) {
|
|
204
|
+
throw new AgentError("config/not-signed-in", "There is no authorization code in that answer.");
|
|
205
|
+
}
|
|
206
|
+
return requestTokens(
|
|
207
|
+
{
|
|
208
|
+
grant_type: "authorization_code",
|
|
209
|
+
client_id: CLIENT_ID,
|
|
210
|
+
code: answer.code,
|
|
211
|
+
code_verifier: verifier,
|
|
212
|
+
redirect_uri: REDIRECT_URI,
|
|
213
|
+
},
|
|
214
|
+
"sign-in",
|
|
215
|
+
);
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
refresh: (current, signal) =>
|
|
221
|
+
requestTokens(
|
|
222
|
+
{ grant_type: "refresh_token", client_id: CLIENT_ID, refresh_token: current.refresh },
|
|
223
|
+
"refresh",
|
|
224
|
+
current,
|
|
225
|
+
signal,
|
|
226
|
+
),
|
|
227
|
+
};
|
|
228
|
+
}
|