@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,108 @@
|
|
|
1
|
+
import { APICallError } from "ai";
|
|
2
|
+
import { AgentError } from "../errors";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Turns a vendor failure into an AgentError a person can act on.
|
|
6
|
+
*
|
|
7
|
+
* This is what makes a capability catalogue optional: when a provider rejects
|
|
8
|
+
* a parameter, the user should see its name, not a raw 400 with a JSON body.
|
|
9
|
+
* It works for every provider, including ones no catalogue has heard of.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** Parameters worth naming back to the user when one is rejected. */
|
|
13
|
+
const KNOWN_PARAMETERS = [
|
|
14
|
+
"reasoning_effort",
|
|
15
|
+
"reasoning",
|
|
16
|
+
"max_completion_tokens",
|
|
17
|
+
"max_output_tokens",
|
|
18
|
+
"max_tokens",
|
|
19
|
+
"temperature",
|
|
20
|
+
"top_p",
|
|
21
|
+
"top_k",
|
|
22
|
+
"seed",
|
|
23
|
+
"stop",
|
|
24
|
+
"tool_choice",
|
|
25
|
+
"tools",
|
|
26
|
+
"response_format",
|
|
27
|
+
"verbosity",
|
|
28
|
+
] as const;
|
|
29
|
+
|
|
30
|
+
export interface ProviderErrorContext {
|
|
31
|
+
providerName: string;
|
|
32
|
+
modelId: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Finds the first known parameter named anywhere in the provider's reply. */
|
|
36
|
+
export function findRejectedParameter(body: string): string | undefined {
|
|
37
|
+
const haystack = body.toLowerCase();
|
|
38
|
+
return KNOWN_PARAMETERS.find((parameter) => haystack.includes(parameter));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function bodyOf(error: APICallError): string {
|
|
42
|
+
if (typeof error.responseBody === "string") return error.responseBody;
|
|
43
|
+
return error.message;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function mapProviderError(error: unknown, context: ProviderErrorContext): unknown {
|
|
47
|
+
if (!APICallError.isInstance(error)) {
|
|
48
|
+
// Some providers emit stream errors as plain objects.
|
|
49
|
+
if (
|
|
50
|
+
typeof error === "object" &&
|
|
51
|
+
error !== null &&
|
|
52
|
+
"code" in error &&
|
|
53
|
+
error.code === 429 &&
|
|
54
|
+
"message" in error &&
|
|
55
|
+
typeof error.message === "string"
|
|
56
|
+
) {
|
|
57
|
+
return new AgentError("provider/rate-limited", error.message, {
|
|
58
|
+
cause: error,
|
|
59
|
+
details: {
|
|
60
|
+
provider: context.providerName,
|
|
61
|
+
model: context.modelId,
|
|
62
|
+
status: 429,
|
|
63
|
+
},
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return error;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const details: Record<string, unknown> = {
|
|
71
|
+
provider: context.providerName,
|
|
72
|
+
model: context.modelId,
|
|
73
|
+
status: error.statusCode,
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
if (error.statusCode === 401 || error.statusCode === 403) {
|
|
77
|
+
return new AgentError(
|
|
78
|
+
"provider/unauthorized",
|
|
79
|
+
`Provider "${context.providerName}" rejected the API key (${error.statusCode}).`,
|
|
80
|
+
{ cause: error, details },
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (error.statusCode === 429) {
|
|
85
|
+
return new AgentError(
|
|
86
|
+
"provider/rate-limited",
|
|
87
|
+
`Provider "${context.providerName}" is rate limiting requests for ${context.modelId}.`,
|
|
88
|
+
{ cause: error, details },
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (error.statusCode === 400) {
|
|
93
|
+
const parameter = findRejectedParameter(bodyOf(error));
|
|
94
|
+
if (parameter !== undefined) {
|
|
95
|
+
return new AgentError(
|
|
96
|
+
"provider/unsupported-parameter",
|
|
97
|
+
`Model ${context.modelId} on "${context.providerName}" rejected the "${parameter}" setting. Remove it from the model profile, or move it under providerOptions if the vendor spells it differently.`,
|
|
98
|
+
{ cause: error, details: { ...details, parameter } },
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return new AgentError(
|
|
104
|
+
"provider/request-failed",
|
|
105
|
+
`Provider "${context.providerName}" failed for ${context.modelId}: ${error.message}`,
|
|
106
|
+
{ cause: error, details },
|
|
107
|
+
);
|
|
108
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { ProviderFactoryLoader } from "../types";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The single registration point for built-in providers.
|
|
5
|
+
*
|
|
6
|
+
* Loaders are lazy: a static import would pull every vendor SDK into the
|
|
7
|
+
* compiled binary and into startup. Adding a provider takes one file and one
|
|
8
|
+
* line here. Import specifiers must stay literal so the bundler can still find
|
|
9
|
+
* them.
|
|
10
|
+
*/
|
|
11
|
+
export const builtinProviderFactories: Record<string, ProviderFactoryLoader> = {
|
|
12
|
+
openrouter: () => import("./openrouter").then((module) => module.factory),
|
|
13
|
+
"openai-compatible": () => import("./openai-compatible").then((module) => module.factory),
|
|
14
|
+
"openai-codex": () => import("./openai-codex").then((module) => module.factory),
|
|
15
|
+
};
|
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
2
|
+
import { type LanguageModelMiddleware, wrapLanguageModel } from "ai";
|
|
3
|
+
import { WRAITH, type AppIdentity } from "../../app";
|
|
4
|
+
import { AgentError } from "../../errors";
|
|
5
|
+
import type { CacheOptions, RequestFields } from "../cache";
|
|
6
|
+
import { type Provider, type ProviderOptions, providerFromFactory } from "../model";
|
|
7
|
+
import {
|
|
8
|
+
type CredentialStore,
|
|
9
|
+
credentialSource,
|
|
10
|
+
type OAuthCredential,
|
|
11
|
+
type OAuthMethod,
|
|
12
|
+
type OAuthMethodLoader,
|
|
13
|
+
startProviderSignIn,
|
|
14
|
+
} from "../oauth";
|
|
15
|
+
import type { SignIn } from "../../sign-in/attempt";
|
|
16
|
+
import { builtinOAuthMethods } from "../oauth/methods";
|
|
17
|
+
import { codexAccountId } from "../oauth/openai-codex";
|
|
18
|
+
import { type ExplicitEffort, explicitEffort, planTurnEfforts, TURN_EFFORT_MODELS } from "../turn-effort";
|
|
19
|
+
import type { ProviderFactory, ProviderInstance } from "../types";
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Codex on a ChatGPT subscription.
|
|
23
|
+
*
|
|
24
|
+
* Everything the backend wants differently lives in one middleware, so the
|
|
25
|
+
* loop, the classifier, compaction and titles never learn which provider they
|
|
26
|
+
* are talking to.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
const DEFAULT_BASE_URL = "https://chatgpt.com/backend-api/codex";
|
|
30
|
+
|
|
31
|
+
/** A placeholder: without one the SDK reads OPENAI_API_KEY itself. */
|
|
32
|
+
const PLACEHOLDER_KEY = "chatgpt-sign-in";
|
|
33
|
+
|
|
34
|
+
/** The backend wants instructions even when a caller has none. */
|
|
35
|
+
const FALLBACK_INSTRUCTIONS = "You are a helpful assistant.";
|
|
36
|
+
|
|
37
|
+
type CallParams = Parameters<NonNullable<LanguageModelMiddleware["transformParams"]>>[0]["params"];
|
|
38
|
+
type WrapGenerate = NonNullable<LanguageModelMiddleware["wrapGenerate"]>;
|
|
39
|
+
type GenerateResult = Awaited<ReturnType<WrapGenerate>>;
|
|
40
|
+
type StreamResult = Awaited<ReturnType<Parameters<WrapGenerate>[0]["doStream"]>>;
|
|
41
|
+
type StreamPart = StreamResult["stream"] extends ReadableStream<infer Part> ? Part : never;
|
|
42
|
+
type Content = GenerateResult["content"][number];
|
|
43
|
+
type ProviderMetadata = NonNullable<GenerateResult["providerMetadata"]>;
|
|
44
|
+
type PromptMessage = CallParams["prompt"][number];
|
|
45
|
+
|
|
46
|
+
export function codexRequestFields(cache: CacheOptions): RequestFields {
|
|
47
|
+
if (cache.key === undefined) return {};
|
|
48
|
+
return {
|
|
49
|
+
// The backend groups a conversation by this header, caching or not.
|
|
50
|
+
headers: { "session-id": cache.key },
|
|
51
|
+
...(cache.enabled ? { providerOptions: { openai: { promptCacheKey: cache.key } } } : {}),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Item ids point at server-side copies, and with `store: false` there are
|
|
57
|
+
* none. Without the id, the SDK sends reasoning as its encrypted content, which
|
|
58
|
+
* a stateless turn needs.
|
|
59
|
+
*
|
|
60
|
+
* Reasoning with no encrypted content is dropped too. One item arrives as a
|
|
61
|
+
* part per summary, and only the last carries the content. The SDK joins parts
|
|
62
|
+
* by id, so without the id it skips the rest, warning on every request.
|
|
63
|
+
*/
|
|
64
|
+
function withoutItemIds(message: PromptMessage): PromptMessage {
|
|
65
|
+
if (message.role === "system") return message;
|
|
66
|
+
const parts = message.content as Array<{ type?: string; providerOptions?: ProviderMetadata }>;
|
|
67
|
+
const content = parts.flatMap((part) => {
|
|
68
|
+
const openai = part.providerOptions?.["openai"];
|
|
69
|
+
if (part.type === "reasoning" && openai?.["reasoningEncryptedContent"] == null) return [];
|
|
70
|
+
if (openai === undefined || !("itemId" in openai)) return [part];
|
|
71
|
+
const { itemId: _, ...rest } = openai;
|
|
72
|
+
return [{ ...part, providerOptions: { ...part.providerOptions, openai: rest } }];
|
|
73
|
+
});
|
|
74
|
+
return { ...message, content } as PromptMessage;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function mergeMetadata(left: ProviderMetadata | undefined, right: ProviderMetadata | undefined) {
|
|
78
|
+
if (left === undefined) return right;
|
|
79
|
+
if (right === undefined) return left;
|
|
80
|
+
const merged: ProviderMetadata = { ...left };
|
|
81
|
+
for (const [provider, fields] of Object.entries(right)) merged[provider] = { ...left[provider], ...fields };
|
|
82
|
+
return merged;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* A generate result assembled from a stream, because the backend only streams
|
|
87
|
+
* and the classifier, compaction and titles call `generateText`.
|
|
88
|
+
*/
|
|
89
|
+
export async function collectStream(result: StreamResult): Promise<GenerateResult> {
|
|
90
|
+
type Open = { type: "text" | "reasoning"; text: string; providerMetadata?: ProviderMetadata };
|
|
91
|
+
const content: Content[] = [];
|
|
92
|
+
const open = new Map<string, Open>();
|
|
93
|
+
let warnings: GenerateResult["warnings"] = [];
|
|
94
|
+
let metadata: Omit<Extract<StreamPart, { type: "response-metadata" }>, "type"> = {};
|
|
95
|
+
let finish: Extract<StreamPart, { type: "finish" }> | undefined;
|
|
96
|
+
|
|
97
|
+
const start = (type: Open["type"], id: string, providerMetadata?: ProviderMetadata) => {
|
|
98
|
+
const part: Open = { type, text: "", ...(providerMetadata === undefined ? {} : { providerMetadata }) };
|
|
99
|
+
content.push(part);
|
|
100
|
+
open.set(`${type}:${id}`, part);
|
|
101
|
+
};
|
|
102
|
+
const end = (key: string, providerMetadata?: ProviderMetadata) => {
|
|
103
|
+
const part = open.get(key);
|
|
104
|
+
open.delete(key);
|
|
105
|
+
const merged = mergeMetadata(part?.providerMetadata, providerMetadata);
|
|
106
|
+
if (part !== undefined && merged !== undefined) part.providerMetadata = merged;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
const reader = result.stream.getReader();
|
|
110
|
+
for (;;) {
|
|
111
|
+
const { done, value } = await reader.read();
|
|
112
|
+
if (done) break;
|
|
113
|
+
switch (value.type) {
|
|
114
|
+
case "stream-start":
|
|
115
|
+
warnings = value.warnings;
|
|
116
|
+
break;
|
|
117
|
+
case "response-metadata": {
|
|
118
|
+
const { type: _, ...rest } = value;
|
|
119
|
+
metadata = rest;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
case "text-start":
|
|
123
|
+
start("text", value.id, value.providerMetadata);
|
|
124
|
+
break;
|
|
125
|
+
case "reasoning-start":
|
|
126
|
+
start("reasoning", value.id, value.providerMetadata);
|
|
127
|
+
break;
|
|
128
|
+
case "text-delta":
|
|
129
|
+
case "reasoning-delta": {
|
|
130
|
+
const part = open.get(`${value.type === "text-delta" ? "text" : "reasoning"}:${value.id}`);
|
|
131
|
+
if (part !== undefined) part.text += value.delta;
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
case "text-end":
|
|
135
|
+
end(`text:${value.id}`, value.providerMetadata);
|
|
136
|
+
break;
|
|
137
|
+
case "reasoning-end":
|
|
138
|
+
end(`reasoning:${value.id}`, value.providerMetadata);
|
|
139
|
+
break;
|
|
140
|
+
case "tool-input-start":
|
|
141
|
+
case "tool-input-delta":
|
|
142
|
+
case "tool-input-end":
|
|
143
|
+
case "raw":
|
|
144
|
+
case "ping":
|
|
145
|
+
// The finished tool call arrives as its own part.
|
|
146
|
+
break;
|
|
147
|
+
case "finish":
|
|
148
|
+
finish = value;
|
|
149
|
+
break;
|
|
150
|
+
case "error":
|
|
151
|
+
throw value.error;
|
|
152
|
+
default:
|
|
153
|
+
content.push(value);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
if (finish === undefined) {
|
|
158
|
+
throw new AgentError("provider/request-failed", "The Codex stream ended before it said it was finished.");
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const headers = result.response?.headers;
|
|
162
|
+
return {
|
|
163
|
+
content,
|
|
164
|
+
finishReason: finish.finishReason,
|
|
165
|
+
usage: finish.usage,
|
|
166
|
+
...(finish.providerMetadata === undefined ? {} : { providerMetadata: finish.providerMetadata }),
|
|
167
|
+
...(result.request === undefined ? {} : { request: result.request }),
|
|
168
|
+
response: { ...metadata, ...(headers === undefined ? {} : { headers }) },
|
|
169
|
+
warnings,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** An empty system message the SDK sends as a `configuration_update` item. */
|
|
174
|
+
const updateFor = (level: ExplicitEffort): PromptMessage => ({
|
|
175
|
+
role: "system",
|
|
176
|
+
content: "",
|
|
177
|
+
providerOptions: { openai: { reasoningEffortUpdate: level } },
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
const isUpdate = (message: PromptMessage): boolean =>
|
|
181
|
+
message.role === "system" && message.providerOptions?.["openai"]?.["reasoningEffortUpdate"] !== undefined;
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* The level goes as `reasoningEffort`, which the SDK sends as it is; the
|
|
185
|
+
* portable `reasoning` it would first fit to its own model table. On a model
|
|
186
|
+
* that takes an update mid-conversation, a change goes as one, as on OpenRouter.
|
|
187
|
+
*/
|
|
188
|
+
export function codexMiddleware(perTurn = false): LanguageModelMiddleware {
|
|
189
|
+
return {
|
|
190
|
+
specificationVersion: "v4",
|
|
191
|
+
|
|
192
|
+
async transformParams({ params }) {
|
|
193
|
+
const { maxOutputTokens: _, providerOptions, reasoning, ...rest } = params;
|
|
194
|
+
const openai = providerOptions?.["openai"];
|
|
195
|
+
const current = explicitEffort(reasoning);
|
|
196
|
+
const plan = perTurn ? planTurnEfforts(params.prompt, current, updateFor) : undefined;
|
|
197
|
+
const prompt = plan?.prompt ?? params.prompt;
|
|
198
|
+
const effort = plan === undefined ? current : plan.base;
|
|
199
|
+
|
|
200
|
+
const instructions = prompt
|
|
201
|
+
.flatMap((message) => (message.role === "system" && !isUpdate(message) ? [message.content] : []))
|
|
202
|
+
.join("\n\n");
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
...rest,
|
|
206
|
+
prompt: prompt.filter((message) => message.role !== "system" || isUpdate(message)).map(withoutItemIds),
|
|
207
|
+
// Schemas from anywhere must register, strict or not.
|
|
208
|
+
...(params.tools === undefined
|
|
209
|
+
? {}
|
|
210
|
+
: { tools: params.tools.map((tool) => (tool.type === "function" ? { ...tool, strict: false } : tool)) }),
|
|
211
|
+
providerOptions: {
|
|
212
|
+
...providerOptions,
|
|
213
|
+
openai: {
|
|
214
|
+
reasoningSummary: "auto",
|
|
215
|
+
...(effort === undefined ? {} : { reasoningEffort: effort }),
|
|
216
|
+
...openai,
|
|
217
|
+
// The backend refuses anything else, whatever a profile says.
|
|
218
|
+
instructions: instructions === "" ? FALLBACK_INSTRUCTIONS : instructions,
|
|
219
|
+
store: false,
|
|
220
|
+
include: ["reasoning.encrypted_content"],
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
},
|
|
225
|
+
|
|
226
|
+
wrapGenerate: async ({ doStream }) => collectStream(await doStream()),
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function minutesUntil(resetsAt: unknown): number | undefined {
|
|
231
|
+
if (typeof resetsAt !== "number") return undefined;
|
|
232
|
+
return Math.max(0, Math.round((resetsAt * 1000 - Date.now()) / 60_000));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Two answers turned into errors before the SDK sees them: a spent plan,
|
|
237
|
+
* which it would retry as an ordinary 429, and a refused token, which it would
|
|
238
|
+
* report as a rejected API key there never was.
|
|
239
|
+
*/
|
|
240
|
+
async function refusal(response: Response, provider: string): Promise<AgentError | undefined> {
|
|
241
|
+
if (response.status === 401) {
|
|
242
|
+
return new AgentError("config/not-signed-in", `ChatGPT rejected the sign-in for "${provider}".`, {
|
|
243
|
+
details: { provider, status: 401 },
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
if (response.status !== 429) return undefined;
|
|
247
|
+
|
|
248
|
+
const body: unknown = await response
|
|
249
|
+
.clone()
|
|
250
|
+
.json()
|
|
251
|
+
.catch(() => undefined);
|
|
252
|
+
const error = (body as { error?: Record<string, unknown> } | undefined)?.error;
|
|
253
|
+
const code = typeof error?.["code"] === "string" ? error["code"] : typeof error?.["type"] === "string" ? error["type"] : "";
|
|
254
|
+
const details = { provider, status: 429, code };
|
|
255
|
+
|
|
256
|
+
if (code === "usage_not_included") {
|
|
257
|
+
return new AgentError(
|
|
258
|
+
"provider/rate-limited",
|
|
259
|
+
`This ChatGPT plan does not include Codex, so "${provider}" cannot be used with it.`,
|
|
260
|
+
{ details },
|
|
261
|
+
);
|
|
262
|
+
}
|
|
263
|
+
if (code !== "usage_limit_reached") return undefined;
|
|
264
|
+
|
|
265
|
+
const plan = typeof error?.["plan_type"] === "string" ? ` (${error["plan_type"].toLowerCase()} plan)` : "";
|
|
266
|
+
const minutes = minutesUntil(error?.["resets_at"]);
|
|
267
|
+
const when = minutes === undefined ? "" : ` Try again in about ${String(minutes)} min.`;
|
|
268
|
+
return new AgentError("provider/rate-limited", `You have hit your ChatGPT usage limit${plan}.${when}`, {
|
|
269
|
+
details: { ...details, ...(minutes === undefined ? {} : { resetsInMinutes: minutes }) },
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function signedInFetch(
|
|
274
|
+
provider: string,
|
|
275
|
+
credential: () => Promise<OAuthCredential>,
|
|
276
|
+
app: AppIdentity,
|
|
277
|
+
): typeof globalThis.fetch {
|
|
278
|
+
return Object.assign(
|
|
279
|
+
async (input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {
|
|
280
|
+
const { access } = await credential();
|
|
281
|
+
const headers = new Headers(init?.headers);
|
|
282
|
+
headers.set("authorization", `Bearer ${access}`);
|
|
283
|
+
const accountId = codexAccountId(access);
|
|
284
|
+
if (accountId !== undefined) headers.set("chatgpt-account-id", accountId);
|
|
285
|
+
headers.set("originator", app.name);
|
|
286
|
+
|
|
287
|
+
const response = await globalThis.fetch(input, { ...init, headers });
|
|
288
|
+
const refused = await refusal(response, provider);
|
|
289
|
+
if (refused !== undefined) throw refused;
|
|
290
|
+
return response;
|
|
291
|
+
},
|
|
292
|
+
{ preconnect: globalThis.fetch.preconnect },
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
export const factory: ProviderFactory = (context): ProviderInstance => {
|
|
297
|
+
const app = context.app ?? WRAITH;
|
|
298
|
+
let client: ReturnType<typeof createOpenAI> | null = null;
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
languageModel(modelId) {
|
|
302
|
+
const credential = context.credential;
|
|
303
|
+
if (credential === undefined) {
|
|
304
|
+
throw new AgentError(
|
|
305
|
+
"config/not-signed-in",
|
|
306
|
+
`Provider "${context.name}" signs in with a ChatGPT subscription, and this host keeps no sign-ins. Pass a credential store to createProviderRegistry.`,
|
|
307
|
+
{ details: { provider: context.name } },
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
// One client per provider: it knows how to reach the backend, not who is asking.
|
|
311
|
+
client ??= createOpenAI({
|
|
312
|
+
...context.config.options,
|
|
313
|
+
baseURL: context.config.baseURL ?? DEFAULT_BASE_URL,
|
|
314
|
+
apiKey: PLACEHOLDER_KEY,
|
|
315
|
+
headers: context.config.headers,
|
|
316
|
+
fetch: signedInFetch(context.name, credential, app),
|
|
317
|
+
});
|
|
318
|
+
return wrapLanguageModel({
|
|
319
|
+
model: client.responses(modelId),
|
|
320
|
+
middleware: codexMiddleware(TURN_EFFORT_MODELS.has(`openai/${modelId}`)),
|
|
321
|
+
});
|
|
322
|
+
},
|
|
323
|
+
cacheSupport: "automatic",
|
|
324
|
+
requestFields: codexRequestFields,
|
|
325
|
+
};
|
|
326
|
+
};
|
|
327
|
+
|
|
328
|
+
export interface OpenAICodexOptions extends ProviderOptions {
|
|
329
|
+
/**
|
|
330
|
+
* The name of the sign-in too: the token is kept under it. Defaults to
|
|
331
|
+
* "codex", the name `login codex` gives, so both read the same sign-in.
|
|
332
|
+
*/
|
|
333
|
+
name?: string;
|
|
334
|
+
/** Where the ChatGPT sign-in is kept and refreshed; the CLI's `login` writes one. */
|
|
335
|
+
credentials: CredentialStore;
|
|
336
|
+
/** Replaces the built-in ChatGPT sign-in, for tests. */
|
|
337
|
+
oauthMethod?: OAuthMethodLoader;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export interface CodexProvider extends Provider {
|
|
341
|
+
/** Whether a sign-in is kept under this provider's name. An expired one still counts: it is refreshed. */
|
|
342
|
+
signedIn(): Promise<boolean>;
|
|
343
|
+
/**
|
|
344
|
+
* The registry's browser sign-in, into `credentials` under this name. Opening
|
|
345
|
+
* `url` is the host's; `done` settles once the token is stored.
|
|
346
|
+
*/
|
|
347
|
+
signIn(): Promise<SignIn<void>>;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** What `login codex` names the provider, and so the file its token is in. */
|
|
351
|
+
export const CODEX_PROVIDER_NAME = "codex";
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Codex on a ChatGPT subscription, from code. One person, their own account:
|
|
355
|
+
* never back a server for many users with one subscription.
|
|
356
|
+
*/
|
|
357
|
+
export function openaiCodex(options: OpenAICodexOptions): CodexProvider {
|
|
358
|
+
const name = options.name ?? CODEX_PROVIDER_NAME;
|
|
359
|
+
const app = options.app ?? WRAITH;
|
|
360
|
+
// Loaded on first use, so building the provider stays synchronous.
|
|
361
|
+
let method: Promise<OAuthMethod> | undefined;
|
|
362
|
+
const loadMethod = (): Promise<OAuthMethod> => {
|
|
363
|
+
const loader = options.oauthMethod ?? builtinOAuthMethods["openai-codex"];
|
|
364
|
+
if (loader === undefined) {
|
|
365
|
+
return Promise.reject(new AgentError("provider/load-failed", "No ChatGPT sign-in method is built in."));
|
|
366
|
+
}
|
|
367
|
+
method ??= loader(app);
|
|
368
|
+
return method;
|
|
369
|
+
};
|
|
370
|
+
|
|
371
|
+
let source: (() => Promise<OAuthCredential>) | undefined;
|
|
372
|
+
const credential = async (): Promise<OAuthCredential> => {
|
|
373
|
+
source ??= credentialSource(options.credentials, name, await loadMethod());
|
|
374
|
+
return source();
|
|
375
|
+
};
|
|
376
|
+
|
|
377
|
+
return {
|
|
378
|
+
...providerFromFactory(factory, "openai-codex", { ...options, name, credential }),
|
|
379
|
+
signedIn: async () => (await options.credentials.read(name)) !== undefined,
|
|
380
|
+
signIn: async () => startProviderSignIn(name, await loadMethod(), options.credentials, app.name),
|
|
381
|
+
};
|
|
382
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
2
|
+
import { AgentError } from "../../errors";
|
|
3
|
+
import type { CacheOptions, ProviderOptionsMap } from "../cache";
|
|
4
|
+
import { type Provider, type ProviderOptions, providerFromFactory } from "../model";
|
|
5
|
+
import type { ProviderFactory, ProviderInstance } from "../types";
|
|
6
|
+
import { modelsEndpointFor } from "./shared";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Ollama, LM Studio, vLLM, Together and in-house gateways all speak this
|
|
10
|
+
* protocol, so a second vendor rarely needs a second factory.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Cache fields for endpoints that really are OpenAI-shaped.
|
|
15
|
+
*
|
|
16
|
+
* Opt-in: `dialect` exists for this. Caching here is automatic, so these fields
|
|
17
|
+
* buy a routing hint and a retention window, while vLLM answers an unrecognised
|
|
18
|
+
* body field with a 400. Sent by default, they would turn a working local setup
|
|
19
|
+
* into an error for no gain.
|
|
20
|
+
*
|
|
21
|
+
* They travel per request rather than per model because this provider takes no
|
|
22
|
+
* per-model settings, and the SDK forwards `providerOptions` keys it does not
|
|
23
|
+
* know straight into the request body (verified against 3.0.35).
|
|
24
|
+
*/
|
|
25
|
+
export function openaiCacheCallOptions(
|
|
26
|
+
providerName: string,
|
|
27
|
+
cache?: CacheOptions,
|
|
28
|
+
): ProviderOptionsMap | undefined {
|
|
29
|
+
if (cache?.enabled !== true || cache.dialect !== "openai") return undefined;
|
|
30
|
+
|
|
31
|
+
const fields: Record<string, unknown> = {};
|
|
32
|
+
if (cache.key !== undefined) fields.prompt_cache_key = cache.key;
|
|
33
|
+
// The only retention this dialect has is "in_memory" or "24h"; 5m and 1h are
|
|
34
|
+
// Anthropic's notion and have nothing to map onto here.
|
|
35
|
+
if (cache.ttl === "24h") fields.prompt_cache_retention = "24h";
|
|
36
|
+
|
|
37
|
+
return Object.keys(fields).length === 0 ? undefined : { [providerName]: fields };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const factory: ProviderFactory = (context): ProviderInstance => {
|
|
41
|
+
const baseURL = context.config.baseURL;
|
|
42
|
+
if (baseURL === undefined) {
|
|
43
|
+
throw new AgentError(
|
|
44
|
+
"config/invalid",
|
|
45
|
+
`Provider "${context.name}" is openai-compatible and needs providers.${context.name}.baseURL.`,
|
|
46
|
+
{ details: { provider: context.name } },
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const client = createOpenAICompatible({
|
|
51
|
+
name: context.name,
|
|
52
|
+
baseURL,
|
|
53
|
+
// Local runtimes such as Ollama accept any key, so this one is optional.
|
|
54
|
+
...(context.apiKey === "" ? {} : { apiKey: context.apiKey }),
|
|
55
|
+
headers: context.config.headers,
|
|
56
|
+
...context.config.options,
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
return {
|
|
60
|
+
languageModel: (modelId) => client.chatModel(modelId),
|
|
61
|
+
cacheSupport: context.config.cache?.dialect === "openai" ? "signal" : "unknown",
|
|
62
|
+
requestFields: (cache) => {
|
|
63
|
+
const providerOptions = openaiCacheCallOptions(context.name, cache);
|
|
64
|
+
return providerOptions === undefined ? {} : { providerOptions };
|
|
65
|
+
},
|
|
66
|
+
modelsEndpoint: modelsEndpointFor(baseURL),
|
|
67
|
+
// The adapter sends a `content` tool result through `JSON.stringify` (3.0.35).
|
|
68
|
+
imagesInToolResults: false,
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export interface OpenAICompatibleOptions extends ProviderOptions {
|
|
73
|
+
baseURL: string;
|
|
74
|
+
/** Optional: a local runtime takes any key or none. */
|
|
75
|
+
apiKey?: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** An OpenAI-shaped endpoint from code: `openaiCompatible({ name: "ollama", baseURL }).model("qwen3")`. */
|
|
79
|
+
export function openaiCompatible(options: OpenAICompatibleOptions): Provider {
|
|
80
|
+
return providerFromFactory(factory, "openai-compatible", options);
|
|
81
|
+
}
|