@fractaal/pi-ai 0.86.9 → 1.4.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 +105 -45
- package/dist/api/anthropic-messages.d.ts.map +1 -1
- package/dist/api/anthropic-messages.js +180 -141
- package/dist/api/anthropic-messages.js.map +1 -1
- package/dist/api/azure-openai-responses.d.ts.map +1 -1
- package/dist/api/azure-openai-responses.js +8 -10
- package/dist/api/azure-openai-responses.js.map +1 -1
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
- package/dist/api/bedrock-converse-stream.js +130 -96
- package/dist/api/bedrock-converse-stream.js.map +1 -1
- package/dist/api/classifier-shared.d.ts +21 -0
- package/dist/api/classifier-shared.d.ts.map +1 -0
- package/dist/api/classifier-shared.js +99 -0
- package/dist/api/classifier-shared.js.map +1 -0
- package/dist/api/cloudflare-workers-ai-system-one.d.ts.map +1 -1
- package/dist/api/cloudflare-workers-ai-system-one.js +10 -1
- package/dist/api/cloudflare-workers-ai-system-one.js.map +1 -1
- package/dist/api/constrained-sampling.d.ts +11 -1
- package/dist/api/constrained-sampling.d.ts.map +1 -1
- package/dist/api/constrained-sampling.js +33 -18
- package/dist/api/constrained-sampling.js.map +1 -1
- package/dist/api/google-generative-ai.d.ts.map +1 -1
- package/dist/api/google-generative-ai.js +4 -10
- package/dist/api/google-generative-ai.js.map +1 -1
- package/dist/api/google-shared.d.ts +2 -1
- package/dist/api/google-shared.d.ts.map +1 -1
- package/dist/api/google-shared.js +60 -3
- package/dist/api/google-shared.js.map +1 -1
- package/dist/api/google-vertex.d.ts.map +1 -1
- package/dist/api/google-vertex.js +9 -15
- package/dist/api/google-vertex.js.map +1 -1
- package/dist/api/lazy.d.ts +7 -2
- package/dist/api/lazy.d.ts.map +1 -1
- package/dist/api/lazy.js +28 -8
- package/dist/api/lazy.js.map +1 -1
- package/dist/api/llama-cpp-classify.d.ts.map +1 -1
- package/dist/api/llama-cpp-classify.js +4 -1
- package/dist/api/llama-cpp-classify.js.map +1 -1
- package/dist/api/mistral-conversations.d.ts.map +1 -1
- package/dist/api/mistral-conversations.js +50 -60
- package/dist/api/mistral-conversations.js.map +1 -1
- package/dist/api/openai-codex-responses.d.ts.map +1 -1
- package/dist/api/openai-codex-responses.js +23 -14
- package/dist/api/openai-codex-responses.js.map +1 -1
- package/dist/api/openai-completions.d.ts.map +1 -1
- package/dist/api/openai-completions.js +83 -87
- package/dist/api/openai-completions.js.map +1 -1
- package/dist/api/openai-decisions.d.ts +4 -0
- package/dist/api/openai-decisions.d.ts.map +1 -0
- package/dist/api/openai-decisions.js +162 -0
- package/dist/api/openai-decisions.js.map +1 -0
- package/dist/api/openai-decisions.lazy.d.ts +3 -0
- package/dist/api/openai-decisions.lazy.d.ts.map +1 -0
- package/dist/api/openai-decisions.lazy.js +4 -0
- package/dist/api/openai-decisions.lazy.js.map +1 -0
- package/dist/api/openai-responses-shared.d.ts +26 -0
- package/dist/api/openai-responses-shared.d.ts.map +1 -1
- package/dist/api/openai-responses-shared.js +132 -66
- package/dist/api/openai-responses-shared.js.map +1 -1
- package/dist/api/openai-responses.d.ts.map +1 -1
- package/dist/api/openai-responses.js +38 -19
- package/dist/api/openai-responses.js.map +1 -1
- package/dist/api/openrouter-images.d.ts.map +1 -1
- package/dist/api/openrouter-images.js +5 -3
- package/dist/api/openrouter-images.js.map +1 -1
- package/dist/api/pi-messages.d.ts +2 -0
- package/dist/api/pi-messages.d.ts.map +1 -1
- package/dist/api/pi-messages.js +18 -12
- package/dist/api/pi-messages.js.map +1 -1
- package/dist/api/simple-options.d.ts.map +1 -1
- package/dist/api/simple-options.js +2 -1
- package/dist/api/simple-options.js.map +1 -1
- package/dist/api/system-one-shared.d.ts +29 -3
- package/dist/api/system-one-shared.d.ts.map +1 -1
- package/dist/api/system-one-shared.js +54 -86
- package/dist/api/system-one-shared.js.map +1 -1
- package/dist/api/transform-messages.d.ts +16 -1
- package/dist/api/transform-messages.d.ts.map +1 -1
- package/dist/api/transform-messages.js +28 -15
- package/dist/api/transform-messages.js.map +1 -1
- package/dist/api/typesafe-system-one.d.ts.map +1 -1
- package/dist/api/typesafe-system-one.js +12 -1
- package/dist/api/typesafe-system-one.js.map +1 -1
- package/dist/auth/oauth/anthropic.d.ts.map +1 -1
- package/dist/auth/oauth/anthropic.js +14 -6
- package/dist/auth/oauth/anthropic.js.map +1 -1
- package/dist/auth/oauth/openai-chatgpt.js +1 -1
- package/dist/auth/oauth/openai-chatgpt.js.map +1 -1
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -1
- package/dist/auth/oauth/openai-codex.js +4 -4
- package/dist/auth/oauth/openai-codex.js.map +1 -1
- package/dist/auth/types.d.ts +9 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/auth/types.js.map +1 -1
- package/dist/compat/extension-oauth-types.d.ts +4 -0
- package/dist/compat/extension-oauth-types.d.ts.map +1 -1
- package/dist/compat/extension-oauth-types.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/models.d.ts +9 -0
- package/dist/models.d.ts.map +1 -1
- package/dist/models.js +23 -7
- package/dist/models.js.map +1 -1
- package/dist/providers/compat-schema.d.ts +509 -0
- package/dist/providers/compat-schema.d.ts.map +1 -0
- package/dist/providers/compat-schema.js +396 -0
- package/dist/providers/compat-schema.js.map +1 -0
- package/dist/providers/data/.manifest.json +1 -1
- package/dist/providers/data/amazon-bedrock.json +1 -1
- package/dist/providers/data/anthropic.json +1 -1
- package/dist/providers/data/azure.json +1 -1
- package/dist/providers/data/baseten.json +1 -1
- package/dist/providers/data/cerebras.json +1 -1
- package/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/providers/data/fireworks.json +1 -1
- package/dist/providers/data/github-copilot.json +1 -1
- package/dist/providers/data/google-vertex.json +1 -1
- package/dist/providers/data/google.json +1 -1
- package/dist/providers/data/groq.json +1 -1
- package/dist/providers/data/huggingface.json +1 -1
- package/dist/providers/data/kimi-coding.json +1 -1
- package/dist/providers/data/meta.json +1 -1
- package/dist/providers/data/minimax-cn.json +1 -1
- package/dist/providers/data/minimax.json +1 -1
- package/dist/providers/data/mistral.json +1 -1
- package/dist/providers/data/moonshotai-cn.json +1 -1
- package/dist/providers/data/moonshotai.json +1 -1
- package/dist/providers/data/nvidia.json +1 -1
- package/dist/providers/data/openai-codex.json +1 -1
- package/dist/providers/data/openai.json +1 -1
- package/dist/providers/data/opencode-go.json +1 -1
- package/dist/providers/data/opencode.json +1 -1
- package/dist/providers/data/openrouter.json +1 -1
- package/dist/providers/data/qwen-token-plan-cn.json +1 -1
- package/dist/providers/data/qwen-token-plan.json +1 -1
- package/dist/providers/data/radius.json +1 -1
- package/dist/providers/data/together.json +1 -1
- package/dist/providers/data/typesafe.json +1 -1
- package/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/providers/data/xai.json +1 -1
- package/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
- package/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
- package/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
- package/dist/providers/data/xiaomi.json +1 -1
- package/dist/providers/data/zai-coding-cn.json +1 -1
- package/dist/providers/faux.d.ts.map +1 -1
- package/dist/providers/faux.js +31 -9
- package/dist/providers/faux.js.map +1 -1
- package/dist/providers/kimi-coding.d.ts +1 -1
- package/dist/providers/kimi-coding.js +3 -3
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/model-schema.d.ts +91 -0
- package/dist/providers/model-schema.d.ts.map +1 -0
- package/dist/providers/model-schema.js +57 -0
- package/dist/providers/model-schema.js.map +1 -0
- package/dist/providers/openai.d.ts.map +1 -1
- package/dist/providers/openai.js +12 -3
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/opencode-go.d.ts +3 -1
- package/dist/providers/opencode-go.d.ts.map +1 -1
- package/dist/providers/opencode-go.js +2 -0
- package/dist/providers/opencode-go.js.map +1 -1
- package/dist/providers/openrouter-api.d.ts +40 -0
- package/dist/providers/openrouter-api.d.ts.map +1 -0
- package/dist/providers/openrouter-api.js +41 -0
- package/dist/providers/openrouter-api.js.map +1 -0
- package/dist/providers/openrouter.d.ts +11 -1
- package/dist/providers/openrouter.d.ts.map +1 -1
- package/dist/providers/openrouter.js +52 -1
- package/dist/providers/openrouter.js.map +1 -1
- package/dist/providers/radius-config.d.ts.map +1 -1
- package/dist/providers/radius-config.js +2 -1
- package/dist/providers/radius-config.js.map +1 -1
- package/dist/providers/radius.d.ts.map +1 -1
- package/dist/providers/radius.js +4 -12
- package/dist/providers/radius.js.map +1 -1
- package/dist/telemetry.d.ts +288 -0
- package/dist/telemetry.d.ts.map +1 -0
- package/dist/telemetry.js +192 -0
- package/dist/telemetry.js.map +1 -0
- package/dist/types.d.ts +44 -307
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/error-body.d.ts.map +1 -1
- package/dist/utils/error-body.js +2 -1
- package/dist/utils/error-body.js.map +1 -1
- package/dist/utils/estimate.js +1 -1
- package/dist/utils/estimate.js.map +1 -1
- package/dist/utils/event-stream.d.ts +10 -1
- package/dist/utils/event-stream.d.ts.map +1 -1
- package/dist/utils/event-stream.js +25 -0
- package/dist/utils/event-stream.js.map +1 -1
- package/dist/utils/identity.d.ts +65 -0
- package/dist/utils/identity.d.ts.map +1 -0
- package/dist/utils/identity.js +141 -0
- package/dist/utils/identity.js.map +1 -0
- package/dist/utils/json-parse.d.ts +10 -0
- package/dist/utils/json-parse.d.ts.map +1 -1
- package/dist/utils/json-parse.js +26 -1
- package/dist/utils/json-parse.js.map +1 -1
- package/dist/utils/model-operations.d.ts +3 -1
- package/dist/utils/model-operations.d.ts.map +1 -1
- package/dist/utils/model-operations.js +6 -0
- package/dist/utils/model-operations.js.map +1 -1
- package/dist/utils/openrouter-cost.d.ts +24 -0
- package/dist/utils/openrouter-cost.d.ts.map +1 -0
- package/dist/utils/openrouter-cost.js +34 -0
- package/dist/utils/openrouter-cost.js.map +1 -0
- package/dist/utils/overflow.d.ts +1 -0
- package/dist/utils/overflow.d.ts.map +1 -1
- package/dist/utils/overflow.js +6 -1
- package/dist/utils/overflow.js.map +1 -1
- package/dist/utils/provider-retry.d.ts +2 -0
- package/dist/utils/provider-retry.d.ts.map +1 -1
- package/dist/utils/provider-retry.js +2 -0
- package/dist/utils/provider-retry.js.map +1 -1
- package/dist/utils/retry.d.ts.map +1 -1
- package/dist/utils/retry.js +26 -10
- package/dist/utils/retry.js.map +1 -1
- package/dist/utils/streaming-json.d.ts +84 -0
- package/dist/utils/streaming-json.d.ts.map +1 -0
- package/dist/utils/streaming-json.js +513 -0
- package/dist/utils/streaming-json.js.map +1 -0
- package/dist/utils/text.d.ts +7 -0
- package/dist/utils/text.d.ts.map +1 -1
- package/dist/utils/text.js +9 -0
- package/dist/utils/text.js.map +1 -1
- package/dist/utils/transcript.d.ts +22 -8
- package/dist/utils/transcript.d.ts.map +1 -1
- package/dist/utils/transcript.js +29 -18
- package/dist/utils/transcript.js.map +1 -1
- package/dist/utils/validation.d.ts.map +1 -1
- package/dist/utils/validation.js +3 -0
- package/dist/utils/validation.js.map +1 -1
- package/dist/utils/version.d.ts +2 -0
- package/dist/utils/version.d.ts.map +1 -0
- package/dist/utils/version.js +3 -0
- package/dist/utils/version.js.map +1 -0
- package/package.json +3 -3
- package/dist/utils/assistant-message-frame.d.ts +0 -77
- package/dist/utils/assistant-message-frame.d.ts.map +0 -1
- package/dist/utils/assistant-message-frame.js +0 -425
- package/dist/utils/assistant-message-frame.js.map +0 -1
- package/dist/utils/pi-user-agent.d.ts +0 -2
- package/dist/utils/pi-user-agent.d.ts.map +0 -1
- package/dist/utils/pi-user-agent.js +0 -12
- package/dist/utils/pi-user-agent.js.map +0 -1
|
@@ -1,15 +1,41 @@
|
|
|
1
|
-
import type { ClassifierApi, ClassifierContext, ClassifierModel, ClassifierOptions, ClassifierResult } from "../types.ts";
|
|
1
|
+
import type { ClassifierApi, ClassifierContext, ClassifierModel, ClassifierOptions, ClassifierResult, SystemOneCompat } from "../types.ts";
|
|
2
|
+
/** A System One image asset: base64 file bytes, referenced by its name from the state. */
|
|
3
|
+
interface SystemOneImageAsset {
|
|
4
|
+
type: "image";
|
|
5
|
+
format: "png" | "jpeg";
|
|
6
|
+
data_base64: string;
|
|
7
|
+
}
|
|
2
8
|
/** TypeSafe System One request body without the transport-specific envelope. */
|
|
3
9
|
export interface SystemOneWireRequest {
|
|
4
|
-
state
|
|
10
|
+
/** The context state, or with images a list of the images or their asset names followed by the state. */
|
|
11
|
+
state: unknown;
|
|
5
12
|
questions: Record<string, unknown>;
|
|
13
|
+
/** Images as System One assets, keyed by the names the state references. */
|
|
14
|
+
assets?: Record<string, SystemOneImageAsset>;
|
|
15
|
+
/** Images as data URLs, Clef's extension to System One. */
|
|
16
|
+
images?: string[];
|
|
6
17
|
}
|
|
18
|
+
/**
|
|
19
|
+
* How a service takes images (`SystemOneCompat.imageInput`):
|
|
20
|
+
* - `assets`: TypeSafe's `assets` map, `{ "<image-1>": { type: "image", format, data_base64 } }`,
|
|
21
|
+
* with the names placed before the state: `state: ["<image-1>", state]`. PNG and JPEG only.
|
|
22
|
+
* - `images`: Clef's `images` list of data URLs, which the model reads before the state.
|
|
23
|
+
* PNG, JPEG, and WebP, at most four.
|
|
24
|
+
* - `state-image-urls`: OpenRouter's form, data URL parts placed before the state:
|
|
25
|
+
* `state: [{ type: "image_url", image_url: { url } }, state]`. OpenRouter accepts this for every
|
|
26
|
+
* model, and drops `assets` silently.
|
|
27
|
+
*/
|
|
28
|
+
export type SystemOneImageInput = NonNullable<SystemOneCompat["imageInput"]>;
|
|
29
|
+
/** System One compatibility settings with every field resolved. */
|
|
30
|
+
export type ResolvedSystemOneCompat = Required<SystemOneCompat>;
|
|
7
31
|
/** Differences between services that serve System One models. */
|
|
8
32
|
export interface SystemOneTransport {
|
|
9
33
|
/** Classifier API implemented by this transport. */
|
|
10
34
|
api: ClassifierApi;
|
|
11
35
|
/** Service name used in error messages. */
|
|
12
36
|
label: string;
|
|
37
|
+
/** Compatibility settings for models that do not set them in `compat`. */
|
|
38
|
+
detectCompat(model: ClassifierModel<ClassifierApi>): ResolvedSystemOneCompat;
|
|
13
39
|
/** Absolute request URL. */
|
|
14
40
|
url(model: ClassifierModel<ClassifierApi>): URL;
|
|
15
41
|
/** Wraps the System One request in the service's request envelope. */
|
|
@@ -17,7 +43,7 @@ export interface SystemOneTransport {
|
|
|
17
43
|
/** Extracts the System One output (`{ answers, usage }`) from the service's response envelope. */
|
|
18
44
|
output(body: unknown): Record<string, unknown>;
|
|
19
45
|
}
|
|
20
|
-
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
21
46
|
/** Runs one System One classification over the given transport. */
|
|
22
47
|
export declare function classifySystemOne(transport: SystemOneTransport, model: ClassifierModel<ClassifierApi>, context: ClassifierContext, options: ClassifierOptions | undefined): Promise<ClassifierResult>;
|
|
48
|
+
export {};
|
|
23
49
|
//# sourceMappingURL=system-one-shared.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-one-shared.d.ts","sourceRoot":"","sources":["../../src/api/system-one-shared.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"system-one-shared.d.ts","sourceRoot":"","sources":["../../src/api/system-one-shared.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEX,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAEhB,eAAe,EACf,MAAM,aAAa,CAAC;AAIrB,0FAA0F;AAC1F,UAAU,mBAAmB;IAC5B,IAAI,EAAE,OAAO,CAAC;IACd,MAAM,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,WAAW,EAAE,MAAM,CAAC;CACpB;AAQD,gFAAgF;AAChF,MAAM,WAAW,oBAAoB;IACpC,yGAAyG;IACzG,KAAK,EAAE,OAAO,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"../utils/error-body.js";
|
|
3
|
-
import {
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
const error = new Error(`${label} returned ${response.status}`);
|
|
7
|
-
error.status = response.status;
|
|
8
|
-
error.headers = response.headers;
|
|
9
|
-
error.body = body;
|
|
10
|
-
return error;
|
|
11
|
-
}
|
|
12
|
-
function timeoutError(timeoutMs) {
|
|
13
|
-
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
14
|
-
error.name = "TimeoutError";
|
|
15
|
-
error.status = undefined;
|
|
16
|
-
error.headers = undefined;
|
|
17
|
-
error.body = "";
|
|
18
|
-
return error;
|
|
19
|
-
}
|
|
20
|
-
export function isRecord(value) {
|
|
21
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
-
}
|
|
23
|
-
function requiredNumber(label, value, field) {
|
|
24
|
-
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
25
|
-
throw new Error(`${label} returned an invalid ${field}`);
|
|
26
|
-
}
|
|
27
|
-
return value;
|
|
28
|
-
}
|
|
2
|
+
import { isRecord, parseClassifierUsage, postClassifierRequest, requiredNumber } from "./classifier-shared.js";
|
|
3
|
+
/** TypeSafe's opt-in header for its experimental image input. */
|
|
4
|
+
const IMAGE_OPT_IN_HEADERS = { "TypeSafe-Danger-Zone-Images": "true" };
|
|
29
5
|
function probabilities(label, value, id) {
|
|
30
6
|
if (!isRecord(value))
|
|
31
7
|
throw new Error(`${label} returned invalid probabilities for ${id}`);
|
|
@@ -82,28 +58,44 @@ function parseAnswers(label, value, context) {
|
|
|
82
58
|
}
|
|
83
59
|
return Object.fromEntries(answers);
|
|
84
60
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
61
|
+
const ASSET_FORMATS = { "image/png": "png", "image/jpeg": "jpeg" };
|
|
62
|
+
const DATA_URL_TYPES = new Set(["image/png", "image/jpeg", "image/webp"]);
|
|
63
|
+
/** Clef accepts at most this many images per request. */
|
|
64
|
+
const MAX_DATA_URL_IMAGES = 4;
|
|
65
|
+
/** Adds the context images to `request` in the service's form. */
|
|
66
|
+
function addImages(label, model, input, images, request) {
|
|
67
|
+
if (input === "images") {
|
|
68
|
+
if (images.length > MAX_DATA_URL_IMAGES) {
|
|
69
|
+
throw new Error(`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`);
|
|
70
|
+
}
|
|
71
|
+
request.images = images.map((image) => {
|
|
72
|
+
if (!DATA_URL_TYPES.has(image.mimeType)) {
|
|
73
|
+
throw new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);
|
|
74
|
+
}
|
|
75
|
+
return `data:${image.mimeType};base64,${image.data}`;
|
|
76
|
+
});
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (input === "state-image-urls") {
|
|
80
|
+
// OpenRouter validates the images against the model that serves the request.
|
|
81
|
+
const parts = images.map((image) => ({
|
|
82
|
+
type: "image_url",
|
|
83
|
+
image_url: { url: `data:${image.mimeType};base64,${image.data}` },
|
|
84
|
+
}));
|
|
85
|
+
request.state = [...parts, request.state];
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const assets = {};
|
|
89
|
+
images.forEach((image, index) => {
|
|
90
|
+
const format = ASSET_FORMATS[image.mimeType];
|
|
91
|
+
if (!format)
|
|
92
|
+
throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);
|
|
93
|
+
assets[`<image-${index + 1}>`] = { type: "image", format, data_base64: image.data };
|
|
94
|
+
});
|
|
95
|
+
request.assets = assets;
|
|
96
|
+
// Every asset must be referenced from the request. The names go before the state, where Clef
|
|
97
|
+
// also places its images.
|
|
98
|
+
request.state = [...Object.keys(assets), request.state];
|
|
107
99
|
}
|
|
108
100
|
/** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */
|
|
109
101
|
function wireRequest(context) {
|
|
@@ -115,9 +107,6 @@ function wireRequest(context) {
|
|
|
115
107
|
])),
|
|
116
108
|
};
|
|
117
109
|
}
|
|
118
|
-
function requestHeaders(model, apiKey, optionsHeaders) {
|
|
119
|
-
return (providerHeadersToRecord({ authorization: `Bearer ${apiKey}`, "content-type": "application/json" }, model.headers, optionsHeaders) ?? {});
|
|
120
|
-
}
|
|
121
110
|
/** Runs one System One classification over the given transport. */
|
|
122
111
|
export async function classifySystemOne(transport, model, context, options) {
|
|
123
112
|
const output = {
|
|
@@ -131,44 +120,23 @@ export async function classifySystemOne(transport, model, context, options) {
|
|
|
131
120
|
try {
|
|
132
121
|
if (model.api !== transport.api)
|
|
133
122
|
throw new Error(`Unsupported classifier API: ${model.api}`);
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
if (transformed !== undefined)
|
|
140
|
-
payload = transformed;
|
|
141
|
-
const requestFetch = options.fetch ?? globalThis.fetch;
|
|
142
|
-
const { response, body } = await retryProviderRequest(async () => {
|
|
143
|
-
const timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;
|
|
144
|
-
const signal = options.signal && timeoutSignal
|
|
145
|
-
? AbortSignal.any([options.signal, timeoutSignal])
|
|
146
|
-
: (options.signal ?? timeoutSignal);
|
|
147
|
-
try {
|
|
148
|
-
const next = await requestFetch(transport.url(model), {
|
|
149
|
-
method: "POST",
|
|
150
|
-
headers: requestHeaders(model, apiKey, options.headers),
|
|
151
|
-
body: JSON.stringify(payload),
|
|
152
|
-
signal,
|
|
153
|
-
});
|
|
154
|
-
if (!next.ok)
|
|
155
|
-
throw httpError(transport.label, next, await next.text());
|
|
156
|
-
return { response: next, body: (await next.json()) };
|
|
123
|
+
const request = wireRequest(context);
|
|
124
|
+
let requestOptions = options;
|
|
125
|
+
if (context.images?.length) {
|
|
126
|
+
if (!model.input.includes("image")) {
|
|
127
|
+
throw new Error(`${transport.label} does not support image input for ${model.id}`);
|
|
157
128
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
129
|
+
const detected = transport.detectCompat(model);
|
|
130
|
+
const imageInput = model.compat?.imageInput ?? detected.imageInput;
|
|
131
|
+
addImages(transport.label, model, imageInput, context.images, request);
|
|
132
|
+
if (model.compat?.sendImageOptInHeader ?? detected.sendImageOptInHeader) {
|
|
133
|
+
requestOptions = { ...options, headers: { ...IMAGE_OPT_IN_HEADERS, ...options?.headers } };
|
|
162
134
|
}
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
maxRetryDelayMs: options.maxRetryDelayMs,
|
|
166
|
-
signal: options.signal,
|
|
167
|
-
});
|
|
168
|
-
await options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);
|
|
135
|
+
}
|
|
136
|
+
const body = await postClassifierRequest(transport.label, transport.url(model), model, transport.payload(model, request), requestOptions);
|
|
169
137
|
const result = transport.output(body);
|
|
170
138
|
// Set before parsing answers: a request with malformed answers was still billed.
|
|
171
|
-
const usage =
|
|
139
|
+
const usage = parseClassifierUsage(result.usage, model);
|
|
172
140
|
if (usage)
|
|
173
141
|
output.usage = usage;
|
|
174
142
|
output.answers = parseAnswers(transport.label, result.answers, context);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-one-shared.js","sourceRoot":"","sources":["../../src/api/system-one-shared.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAW7C,OAAO,EAAE,mBAAmB,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACrF,OAAO,EAAE,eAAe,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAC/E,OAAO,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AAM;SACtB,CACD,CAAC;QACF,MAAM,OAAO,CAAC,UAAU,EAAE,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,MAAM,EAAE,OAAO,EAAE,eAAe,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;QAC3G,MAAM,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QACtC,iFAAiF;QACjF,MAAM,KAAK,GAAG,UAAU,CAAC,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAC9C,IAAI,KAAK;YAAE,MAAM,CAAC,KAAK,GAAG,KAAK,CAAC;QAChC,MAAM,CAAC,OAAO,GAAG,YAAY,CAAC,SAAS,CAAC,KAAK,EAAE,MAAM,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxE,OAAO,MAAM,CAAC;IACf,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,MAAM,CAAC,UAAU,GAAG,OAAO,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC;QACnE,MAAM,CAAC,YAAY,GAAG,mBAAmB,CAAC,sBAAsB,CAAC,KAAK,CAAC,EAAE,GAAG,SAAS,CAAC,KAAK,QAAQ,CAAC,CAAC;QACrG,OAAO,MAAM,CAAC;IACf,CAAC;AACF,CAAC","sourcesContent":["import { calculateCost } from \"../models.ts\";\nimport type {\n\tClassifierAnswer,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tProviderHeaders,\n\tUsage,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { headersToRecord, providerHeadersToRecord } from \"../utils/headers.ts\";\nimport { retryProviderRequest } from \"../utils/provider-retry.ts\";\n\n/** TypeSafe System One request body without the transport-specific envelope. */\nexport interface SystemOneWireRequest {\n\tstate: ClassifierContext[\"state\"];\n\tquestions: Record<string, unknown>;\n}\n\n/** Differences between services that serve System One models. */\nexport interface SystemOneTransport {\n\t/** Classifier API implemented by this transport. */\n\tapi: ClassifierApi;\n\t/** Service name used in error messages. */\n\tlabel: string;\n\t/** Absolute request URL. */\n\turl(model: ClassifierModel<ClassifierApi>): URL;\n\t/** Wraps the System One request in the service's request envelope. */\n\tpayload(model: ClassifierModel<ClassifierApi>, request: SystemOneWireRequest): unknown;\n\t/** Extracts the System One output (`{ answers, usage }`) from the service's response envelope. */\n\toutput(body: unknown): Record<string, unknown>;\n}\n\ninterface SystemOneHttpError extends Error {\n\tstatus: number | undefined;\n\theaders: Headers | undefined;\n\tbody: string;\n}\n\nfunction httpError(label: string, response: Response, body: string): SystemOneHttpError {\n\tconst error = new Error(`${label} returned ${response.status}`) as SystemOneHttpError;\n\terror.status = response.status;\n\terror.headers = response.headers;\n\terror.body = body;\n\treturn error;\n}\n\nfunction timeoutError(timeoutMs: number): SystemOneHttpError {\n\tconst error = new Error(`Request timed out after ${timeoutMs}ms`) as SystemOneHttpError;\n\terror.name = \"TimeoutError\";\n\terror.status = undefined;\n\terror.headers = undefined;\n\terror.body = \"\";\n\treturn error;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction requiredNumber(label: string, value: unknown, field: string): number {\n\tif (typeof value !== \"number\" || !Number.isFinite(value)) {\n\t\tthrow new Error(`${label} returned an invalid ${field}`);\n\t}\n\treturn value;\n}\n\nfunction probabilities(label: string, value: unknown, id: string): Record<string, number> {\n\tif (!isRecord(value)) throw new Error(`${label} returned invalid probabilities for ${id}`);\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, probability]) => [\n\t\t\tkey,\n\t\t\trequiredNumber(label, probability, `probability for ${id}.${key}`),\n\t\t]),\n\t);\n}\n\nfunction parseAnswers(label: string, value: unknown, context: ClassifierContext): Record<string, ClassifierAnswer> {\n\tif (!isRecord(value)) throw new Error(`${label} returned an unexpected response`);\n\tconst answers: Array<[string, ClassifierAnswer]> = [];\n\tfor (const [id, question] of Object.entries(context.questions)) {\n\t\tconst answer = value[id];\n\t\tif (!isRecord(answer)) throw new Error(`${label} did not return an answer for ${id}`);\n\t\tif (question.type === \"choice\") {\n\t\t\tif (answer.type !== \"choice\" || typeof answer.choice !== \"string\") {\n\t\t\t\tthrow new Error(`${label} did not return a choice answer for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"choice\",\n\t\t\t\t\tchoice: answer.choice,\n\t\t\t\t\tprobabilities: probabilities(label, answer.probabilities, id),\n\t\t\t\t\tconfidence: requiredNumber(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (answer.type !== \"score\") throw new Error(`${label} did not return a score answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"score\",\n\t\t\t\t\tscore: requiredNumber(label, answer.score, `score for ${id}`),\n\t\t\t\t\tconfidence: requiredNumber(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else {\n\t\t\tif (answer.type !== \"noul\") throw new Error(`${label} did not return a bool answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"bool\",\n\t\t\t\t\tprobability: requiredNumber(label, answer.noul, `probability for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\treturn Object.fromEntries(answers);\n}\n\nfunction tokenCount(value: unknown): number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : 0;\n}\n\n/**\n * Usage from System One's `{ input_tokens, output_tokens }`, priced from the model catalog like chat\n * usage. A missing or malformed usage object leaves the result without usage instead of failing it.\n */\nfunction parseUsage(value: unknown, model: ClassifierModel<ClassifierApi>): Usage | undefined {\n\tif (!isRecord(value) || (value.input_tokens === undefined && value.output_tokens === undefined)) return undefined;\n\tconst input = tokenCount(value.input_tokens);\n\tconst output = tokenCount(value.output_tokens);\n\tconst usage: Usage = {\n\t\tinput,\n\t\toutput,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\ttotalTokens: input + output,\n\t\tcost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },\n\t};\n\tcalculateCost(model, usage);\n\treturn usage;\n}\n\n/** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */\nfunction wireRequest(context: ClassifierContext): SystemOneWireRequest {\n\treturn {\n\t\tstate: context.state,\n\t\tquestions: Object.fromEntries(\n\t\t\tObject.entries(context.questions).map(([id, question]) => [\n\t\t\t\tid,\n\t\t\t\tquestion.type === \"bool\" ? { ...question, type: \"noul\" } : question,\n\t\t\t]),\n\t\t),\n\t};\n}\n\nfunction requestHeaders(\n\tmodel: ClassifierModel<ClassifierApi>,\n\tapiKey: string,\n\toptionsHeaders?: ProviderHeaders,\n): Record<string, string> {\n\treturn (\n\t\tproviderHeadersToRecord(\n\t\t\t{ authorization: `Bearer ${apiKey}`, \"content-type\": \"application/json\" },\n\t\t\tmodel.headers,\n\t\t\toptionsHeaders,\n\t\t) ?? {}\n\t);\n}\n\n/** Runs one System One classification over the given transport. */\nexport async function classifySystemOne(\n\ttransport: SystemOneTransport,\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions: ClassifierOptions | undefined,\n): Promise<ClassifierResult> {\n\tconst output: ClassifierResult = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tanswers: {},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\n\ttry {\n\t\tif (model.api !== transport.api) throw new Error(`Unsupported classifier API: ${model.api}`);\n\t\tif (!options?.apiKey) throw new Error(`No API key for provider: ${model.provider}`);\n\t\tconst apiKey = options.apiKey;\n\t\tlet payload = transport.payload(model, wireRequest(context));\n\t\tconst transformed = await options.onPayload?.(payload, model);\n\t\tif (transformed !== undefined) payload = transformed;\n\t\tconst requestFetch = options.fetch ?? globalThis.fetch;\n\t\tconst { response, body } = await retryProviderRequest(\n\t\t\tasync () => {\n\t\t\t\tconst timeoutSignal = options.timeoutMs !== undefined ? AbortSignal.timeout(options.timeoutMs) : undefined;\n\t\t\t\tconst signal =\n\t\t\t\t\toptions.signal && timeoutSignal\n\t\t\t\t\t\t? AbortSignal.any([options.signal, timeoutSignal])\n\t\t\t\t\t\t: (options.signal ?? timeoutSignal);\n\t\t\t\ttry {\n\t\t\t\t\tconst next = await requestFetch(transport.url(model), {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: requestHeaders(model, apiKey, options.headers),\n\t\t\t\t\t\tbody: JSON.stringify(payload),\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t});\n\t\t\t\t\tif (!next.ok) throw httpError(transport.label, next, await next.text());\n\t\t\t\t\treturn { response: next, body: (await next.json()) as unknown };\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (timeoutSignal?.aborted && !options.signal?.aborted) throw timeoutError(options.timeoutMs!);\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\tmaxRetries: options.maxRetries ?? 2,\n\t\t\t\tmaxRetryDelayMs: options.maxRetryDelayMs,\n\t\t\t\tsignal: options.signal,\n\t\t\t},\n\t\t);\n\t\tawait options.onResponse?.({ status: response.status, headers: headersToRecord(response.headers) }, model);\n\t\tconst result = transport.output(body);\n\t\t// Set before parsing answers: a request with malformed answers was still billed.\n\t\tconst usage = parseUsage(result.usage, model);\n\t\tif (usage) output.usage = usage;\n\t\toutput.answers = parseAnswers(transport.label, result.answers, context);\n\t\treturn output;\n\t} catch (error) {\n\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error), `${transport.label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ACF,CAAC","sourcesContent":["import type {\n\tClassifierAnswer,\n\tClassifierApi,\n\tClassifierContext,\n\tClassifierModel,\n\tClassifierOptions,\n\tClassifierResult,\n\tImageContent,\n\tSystemOneCompat,\n} from \"../types.ts\";\nimport { formatProviderError, normalizeProviderError } from \"../utils/error-body.ts\";\nimport { isRecord, parseClassifierUsage, postClassifierRequest, requiredNumber } from \"./classifier-shared.ts\";\n\n/** A System One image asset: base64 file bytes, referenced by its name from the state. */\ninterface SystemOneImageAsset {\n\ttype: \"image\";\n\tformat: \"png\" | \"jpeg\";\n\tdata_base64: string;\n}\n\n/** An image in the state, OpenRouter's form. */\ninterface SystemOneImageUrlPart {\n\ttype: \"image_url\";\n\timage_url: { url: string };\n}\n\n/** TypeSafe System One request body without the transport-specific envelope. */\nexport interface SystemOneWireRequest {\n\t/** The context state, or with images a list of the images or their asset names followed by the state. */\n\tstate: unknown;\n\tquestions: Record<string, unknown>;\n\t/** Images as System One assets, keyed by the names the state references. */\n\tassets?: Record<string, SystemOneImageAsset>;\n\t/** Images as data URLs, Clef's extension to System One. */\n\timages?: string[];\n}\n\n/**\n * How a service takes images (`SystemOneCompat.imageInput`):\n * - `assets`: TypeSafe's `assets` map, `{ \"<image-1>\": { type: \"image\", format, data_base64 } }`,\n * with the names placed before the state: `state: [\"<image-1>\", state]`. PNG and JPEG only.\n * - `images`: Clef's `images` list of data URLs, which the model reads before the state.\n * PNG, JPEG, and WebP, at most four.\n * - `state-image-urls`: OpenRouter's form, data URL parts placed before the state:\n * `state: [{ type: \"image_url\", image_url: { url } }, state]`. OpenRouter accepts this for every\n * model, and drops `assets` silently.\n */\nexport type SystemOneImageInput = NonNullable<SystemOneCompat[\"imageInput\"]>;\n\n/** System One compatibility settings with every field resolved. */\nexport type ResolvedSystemOneCompat = Required<SystemOneCompat>;\n\n/** TypeSafe's opt-in header for its experimental image input. */\nconst IMAGE_OPT_IN_HEADERS = { \"TypeSafe-Danger-Zone-Images\": \"true\" };\n\n/** Differences between services that serve System One models. */\nexport interface SystemOneTransport {\n\t/** Classifier API implemented by this transport. */\n\tapi: ClassifierApi;\n\t/** Service name used in error messages. */\n\tlabel: string;\n\t/** Compatibility settings for models that do not set them in `compat`. */\n\tdetectCompat(model: ClassifierModel<ClassifierApi>): ResolvedSystemOneCompat;\n\t/** Absolute request URL. */\n\turl(model: ClassifierModel<ClassifierApi>): URL;\n\t/** Wraps the System One request in the service's request envelope. */\n\tpayload(model: ClassifierModel<ClassifierApi>, request: SystemOneWireRequest): unknown;\n\t/** Extracts the System One output (`{ answers, usage }`) from the service's response envelope. */\n\toutput(body: unknown): Record<string, unknown>;\n}\n\nfunction probabilities(label: string, value: unknown, id: string): Record<string, number> {\n\tif (!isRecord(value)) throw new Error(`${label} returned invalid probabilities for ${id}`);\n\treturn Object.fromEntries(\n\t\tObject.entries(value).map(([key, probability]) => [\n\t\t\tkey,\n\t\t\trequiredNumber(label, probability, `probability for ${id}.${key}`),\n\t\t]),\n\t);\n}\n\nfunction parseAnswers(label: string, value: unknown, context: ClassifierContext): Record<string, ClassifierAnswer> {\n\tif (!isRecord(value)) throw new Error(`${label} returned an unexpected response`);\n\tconst answers: Array<[string, ClassifierAnswer]> = [];\n\tfor (const [id, question] of Object.entries(context.questions)) {\n\t\tconst answer = value[id];\n\t\tif (!isRecord(answer)) throw new Error(`${label} did not return an answer for ${id}`);\n\t\tif (question.type === \"choice\") {\n\t\t\tif (answer.type !== \"choice\" || typeof answer.choice !== \"string\") {\n\t\t\t\tthrow new Error(`${label} did not return a choice answer for ${id}`);\n\t\t\t}\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"choice\",\n\t\t\t\t\tchoice: answer.choice,\n\t\t\t\t\tprobabilities: probabilities(label, answer.probabilities, id),\n\t\t\t\t\tconfidence: requiredNumber(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else if (question.type === \"score\") {\n\t\t\tif (answer.type !== \"score\") throw new Error(`${label} did not return a score answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"score\",\n\t\t\t\t\tscore: requiredNumber(label, answer.score, `score for ${id}`),\n\t\t\t\t\tconfidence: requiredNumber(label, answer.confidence, `confidence for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t} else {\n\t\t\tif (answer.type !== \"noul\") throw new Error(`${label} did not return a bool answer for ${id}`);\n\t\t\tanswers.push([\n\t\t\t\tid,\n\t\t\t\t{\n\t\t\t\t\ttype: \"bool\",\n\t\t\t\t\tprobability: requiredNumber(label, answer.noul, `probability for ${id}`),\n\t\t\t\t},\n\t\t\t]);\n\t\t}\n\t}\n\treturn Object.fromEntries(answers);\n}\n\nconst ASSET_FORMATS: Record<string, SystemOneImageAsset[\"format\"]> = { \"image/png\": \"png\", \"image/jpeg\": \"jpeg\" };\nconst DATA_URL_TYPES = new Set([\"image/png\", \"image/jpeg\", \"image/webp\"]);\n/** Clef accepts at most this many images per request. */\nconst MAX_DATA_URL_IMAGES = 4;\n\n/** Adds the context images to `request` in the service's form. */\nfunction addImages(\n\tlabel: string,\n\tmodel: ClassifierModel<ClassifierApi>,\n\tinput: SystemOneImageInput,\n\timages: ImageContent[],\n\trequest: SystemOneWireRequest,\n): void {\n\tif (input === \"images\") {\n\t\tif (images.length > MAX_DATA_URL_IMAGES) {\n\t\t\tthrow new Error(\n\t\t\t\t`${label} accepts at most ${MAX_DATA_URL_IMAGES} images for ${model.id}, got ${images.length}`,\n\t\t\t);\n\t\t}\n\t\trequest.images = images.map((image) => {\n\t\t\tif (!DATA_URL_TYPES.has(image.mimeType)) {\n\t\t\t\tthrow new Error(`${label} accepts PNG, JPEG, and WebP images for ${model.id}, got ${image.mimeType}`);\n\t\t\t}\n\t\t\treturn `data:${image.mimeType};base64,${image.data}`;\n\t\t});\n\t\treturn;\n\t}\n\tif (input === \"state-image-urls\") {\n\t\t// OpenRouter validates the images against the model that serves the request.\n\t\tconst parts = images.map(\n\t\t\t(image): SystemOneImageUrlPart => ({\n\t\t\t\ttype: \"image_url\",\n\t\t\t\timage_url: { url: `data:${image.mimeType};base64,${image.data}` },\n\t\t\t}),\n\t\t);\n\t\trequest.state = [...parts, request.state];\n\t\treturn;\n\t}\n\tconst assets: Record<string, SystemOneImageAsset> = {};\n\timages.forEach((image, index) => {\n\t\tconst format = ASSET_FORMATS[image.mimeType];\n\t\tif (!format) throw new Error(`${label} accepts PNG and JPEG images for ${model.id}, got ${image.mimeType}`);\n\t\tassets[`<image-${index + 1}>`] = { type: \"image\", format, data_base64: image.data };\n\t});\n\trequest.assets = assets;\n\t// Every asset must be referenced from the request. The names go before the state, where Clef\n\t// also places its images.\n\trequest.state = [...Object.keys(assets), request.state];\n}\n\n/** Maps public `bool` questions to TypeSafe's wire-level `noul` type. */\nfunction wireRequest(context: ClassifierContext): SystemOneWireRequest {\n\treturn {\n\t\tstate: context.state,\n\t\tquestions: Object.fromEntries(\n\t\t\tObject.entries(context.questions).map(([id, question]) => [\n\t\t\t\tid,\n\t\t\t\tquestion.type === \"bool\" ? { ...question, type: \"noul\" } : question,\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/** Runs one System One classification over the given transport. */\nexport async function classifySystemOne(\n\ttransport: SystemOneTransport,\n\tmodel: ClassifierModel<ClassifierApi>,\n\tcontext: ClassifierContext,\n\toptions: ClassifierOptions | undefined,\n): Promise<ClassifierResult> {\n\tconst output: ClassifierResult = {\n\t\tapi: model.api,\n\t\tprovider: model.provider,\n\t\tmodel: model.id,\n\t\tanswers: {},\n\t\tstopReason: \"stop\",\n\t\ttimestamp: Date.now(),\n\t};\n\n\ttry {\n\t\tif (model.api !== transport.api) throw new Error(`Unsupported classifier API: ${model.api}`);\n\t\tconst request = wireRequest(context);\n\t\tlet requestOptions = options;\n\t\tif (context.images?.length) {\n\t\t\tif (!model.input.includes(\"image\")) {\n\t\t\t\tthrow new Error(`${transport.label} does not support image input for ${model.id}`);\n\t\t\t}\n\t\t\tconst detected = transport.detectCompat(model);\n\t\t\tconst imageInput = model.compat?.imageInput ?? detected.imageInput;\n\t\t\taddImages(transport.label, model, imageInput, context.images, request);\n\t\t\tif (model.compat?.sendImageOptInHeader ?? detected.sendImageOptInHeader) {\n\t\t\t\trequestOptions = { ...options, headers: { ...IMAGE_OPT_IN_HEADERS, ...options?.headers } };\n\t\t\t}\n\t\t}\n\t\tconst body = await postClassifierRequest(\n\t\t\ttransport.label,\n\t\t\ttransport.url(model),\n\t\t\tmodel,\n\t\t\ttransport.payload(model, request),\n\t\t\trequestOptions,\n\t\t);\n\t\tconst result = transport.output(body);\n\t\t// Set before parsing answers: a request with malformed answers was still billed.\n\t\tconst usage = parseClassifierUsage(result.usage, model);\n\t\tif (usage) output.usage = usage;\n\t\toutput.answers = parseAnswers(transport.label, result.answers, context);\n\t\treturn output;\n\t} catch (error) {\n\t\toutput.stopReason = options?.signal?.aborted ? \"aborted\" : \"error\";\n\t\toutput.errorMessage = formatProviderError(normalizeProviderError(error), `${transport.label} error`);\n\t\treturn output;\n\t}\n}\n"]}
|
|
@@ -1,4 +1,19 @@
|
|
|
1
|
-
import type { Api, AssistantMessage, Message, Model } from "../types.ts";
|
|
1
|
+
import type { Api, AssistantMessage, ImageContent, Message, Model, TextContent, ToolResultMessage } from "../types.ts";
|
|
2
|
+
/** An error tool result split into a text-only result and the images to send after the tool results. */
|
|
3
|
+
export interface SplitErrorToolResult {
|
|
4
|
+
/** The result content with each run of images replaced by a note. */
|
|
5
|
+
content: TextContent[];
|
|
6
|
+
/** Text naming the tool call, to send before `images`. */
|
|
7
|
+
caption: string;
|
|
8
|
+
images: ImageContent[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Split the images out of an error tool result, for APIs that reject images in error results
|
|
12
|
+
* (Anthropic, and Claude on Bedrock). Send the returned content as the tool result and the caption and
|
|
13
|
+
* images after all tool results of the turn, in the same user message. Returns undefined for results
|
|
14
|
+
* that need no split (#10794).
|
|
15
|
+
*/
|
|
16
|
+
export declare function splitErrorToolResultImages(msg: ToolResultMessage): SplitErrorToolResult | undefined;
|
|
2
17
|
/**
|
|
3
18
|
* Normalize tool call ID for cross-provider compatibility.
|
|
4
19
|
* OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform-messages.d.ts","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,
|
|
1
|
+
{"version":3,"file":"transform-messages.d.ts","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,GAAG,EACH,gBAAgB,EAChB,YAAY,EACZ,OAAO,EACP,KAAK,EACL,WAAW,EAEX,iBAAiB,EACjB,MAAM,aAAa,CAAC;AAMrB,wGAAwG;AACxG,MAAM,WAAW,oBAAoB;IACpC,qEAAqE;IACrE,OAAO,EAAE,WAAW,EAAE,CAAC;IACvB,0DAA0D;IAC1D,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,YAAY,EAAE,CAAC;CACvB;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,iBAAiB,GAAG,oBAAoB,GAAG,SAAS,CASnG;AA8CD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,SAAS,GAAG,EACjD,QAAQ,EAAE,OAAO,EAAE,EACnB,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAClB,mBAAmB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,gBAAgB,KAAK,MAAM,GACxF,OAAO,EAAE,CAiKX"}
|
|
@@ -1,5 +1,24 @@
|
|
|
1
1
|
const NON_VISION_USER_IMAGE_PLACEHOLDER = "(image omitted: model does not support images)";
|
|
2
2
|
const NON_VISION_TOOL_IMAGE_PLACEHOLDER = "(tool image omitted: model does not support images)";
|
|
3
|
+
const ERROR_TOOL_IMAGE_PLACEHOLDER = "(image attached after the tool results)";
|
|
4
|
+
/**
|
|
5
|
+
* Split the images out of an error tool result, for APIs that reject images in error results
|
|
6
|
+
* (Anthropic, and Claude on Bedrock). Send the returned content as the tool result and the caption and
|
|
7
|
+
* images after all tool results of the turn, in the same user message. Returns undefined for results
|
|
8
|
+
* that need no split (#10794).
|
|
9
|
+
*/
|
|
10
|
+
export function splitErrorToolResultImages(msg) {
|
|
11
|
+
if (!msg.isError)
|
|
12
|
+
return undefined;
|
|
13
|
+
const images = msg.content.filter((block) => block.type === "image");
|
|
14
|
+
if (images.length === 0)
|
|
15
|
+
return undefined;
|
|
16
|
+
return {
|
|
17
|
+
content: replaceImagesWithPlaceholder(msg.content, ERROR_TOOL_IMAGE_PLACEHOLDER),
|
|
18
|
+
caption: `Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,
|
|
19
|
+
images,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
3
22
|
function replaceImagesWithPlaceholder(content, placeholder) {
|
|
4
23
|
const result = [];
|
|
5
24
|
let previousWasPlaceholder = false;
|
|
@@ -70,24 +89,18 @@ export function transformMessages(messages, model, normalizeToolCallId) {
|
|
|
70
89
|
assistantMsg.model === model.id;
|
|
71
90
|
const transformedContent = assistantMsg.content.flatMap((block) => {
|
|
72
91
|
if (block.type === "thinking") {
|
|
73
|
-
//
|
|
74
|
-
//
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
if (
|
|
92
|
+
// Thinking from another model is dropped. Signatures and encrypted reasoning are
|
|
93
|
+
// only valid for the model that produced them, and sending readable thinking as
|
|
94
|
+
// plain text makes the new model treat it as part of the visible reply.
|
|
95
|
+
if (!isSameModel)
|
|
96
|
+
return [];
|
|
97
|
+
// Keep redacted and signed blocks even if the thinking text is empty
|
|
98
|
+
// (OpenAI encrypted reasoning); they are needed for replay.
|
|
99
|
+
if (block.redacted || block.thinkingSignature)
|
|
81
100
|
return block;
|
|
82
|
-
// Skip empty thinking blocks, convert others to plain text
|
|
83
101
|
if (!block.thinking || block.thinking.trim() === "")
|
|
84
102
|
return [];
|
|
85
|
-
|
|
86
|
-
return block;
|
|
87
|
-
return {
|
|
88
|
-
type: "text",
|
|
89
|
-
text: block.thinking,
|
|
90
|
-
};
|
|
103
|
+
return block;
|
|
91
104
|
}
|
|
92
105
|
if (block.type === "text") {
|
|
93
106
|
if (isSameModel)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAWA,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAEhG,SAAS,4BAA4B,CAAC,OAAuC,EAAE,WAAmB;IACjG,MAAM,MAAM,GAAkB,EAAE,CAAC;IACjC,IAAI,sBAAsB,GAAG,KAAK,CAAC;IAEnC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,sBAAsB,EAAE,CAAC;gBAC7B,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,CAAC,CAAC;YAClD,CAAC;YACD,sBAAsB,GAAG,IAAI,CAAC;YAC9B,SAAS;QACV,CAAC;QAED,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACnB,sBAAsB,GAAG,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC;IACrD,CAAC;IAED,OAAO,MAAM,CAAC;AACf,CAAC;AAED,SAAS,0BAA0B,CAAmB,QAAmB,EAAE,KAAkB;IAC5F,IAAI,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,C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,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+EAA+E;IAC/E,qBAAqB,EAAE,CAAC;IAExB,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\n\nfunction replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"image\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// System and user messages pass through unchanged\n\t\tif (msg.role === \"system\" || msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Redacted thinking is opaque encrypted content, only valid for the same model.\n\t\t\t\t\t// Drop it for cross-model to avoid API errors.\n\t\t\t\t\tif (block.redacted) {\n\t\t\t\t\t\treturn isSameModel ? block : [];\n\t\t\t\t\t}\n\t\t\t\t\t// For same model: keep thinking blocks with signatures (needed for replay)\n\t\t\t\t\t// even if the thinking text is empty (OpenAI encrypted reasoning)\n\t\t\t\t\tif (isSameModel && block.thinkingSignature) return block;\n\t\t\t\t\t// Skip empty thinking blocks, convert others to plain text\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.thinking,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\t// System messages are transparent to tool-call accounting: one that lands between a tool\n\t// call and its results is held back and emitted after the results (synthetic ones\n\t// included), so it never causes a duplicate result for a call that is answered later.\n\tconst heldSystemMessages: Message[] = [];\n\tconst closePendingToolCalls = () => {\n\t\tif (pendingToolCalls.length > 0) {\n\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\tresult.push({\n\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingToolCalls = [];\n\t\t\texistingToolResultIds = new Set();\n\t\t}\n\t\tresult.push(...heldSystemMessages);\n\t\theldSystemMessages.length = 0;\n\t};\n\n\tfor (let i = 0; i < transformed.length; i++) {\n\t\tconst msg = transformed[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tclosePendingToolCalls();\n\n\t\t\t// Skip errored/aborted assistant messages entirely.\n\t\t\t// These are incomplete turns that shouldn't be replayed:\n\t\t\t// - May have partial content (reasoning without message, incomplete tool calls)\n\t\t\t// - Replaying them can cause API errors (e.g., OpenAI \"reasoning without following item\")\n\t\t\t// - The model should retry from the last valid state\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"system\") {\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\theldSystemMessages.push(msg);\n\t\t\t} else {\n\t\t\t\tresult.push(msg);\n\t\t\t}\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// A new user turn interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tclosePendingToolCalls();\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\t// If the conversation ends with unresolved tool calls, synthesize results now.\n\tclosePendingToolCalls();\n\n\treturn result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transform-messages.js","sourceRoot":"","sources":["../../src/api/transform-messages.ts"],"names":[],"mappings":"AAWA,MAAM,iCAAiC,GAAG,gDAAgD,CAAC;AAC3F,MAAM,iCAAiC,GAAG,qDAAqD,CAAC;AAChG,MAAM,4BAA4B,GAAG,yCAAyC,CAAC;AAW/E;;;;;GAKG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAsB;IAChE,IAAI,CAAC,GAAG,CAAC,OAAO;QAAE,OAAO,SAAS,CAAC;IACnC,MAAM,MAAM,GAAG,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,KAAK,EAAyB,EAAE,CAAC,KAAK,CAAC,IAAI,KAAK,OAAO,CAAC,CAAC;IAC5F,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC1C,OAAO;QACN,OAAO,EAAE,4BAA4B,CAAC,GAAG,CAAC,OAAO,EAAE,4BAA4B,CAAC;QAChF,OAAO,EAAE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AAI,GAAG,CAAC,IAAI,KAAK,YAAY,EAAE,CAAC;YACtC,qBAAqB,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC1C,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;YAClC,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACjC,kBAAkB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAC9B,CAAC;iBAAM,CAAC;gBACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YAClB,CAAC;QACF,CAAC;aAAM,IAAI,GAAG,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;YAChC,qFAAqF;YACrF,qBAAqB,EAAE,CAAC;YACxB,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;aAAM,CAAC;YACP,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAClB,CAAC;IACF,CAAC;IAED,+EAA+E;IAC/E,qBAAqB,EAAE,CAAC;IAExB,OAAO,MAAM,CAAC;AACf,CAAC","sourcesContent":["import type {\n\tApi,\n\tAssistantMessage,\n\tImageContent,\n\tMessage,\n\tModel,\n\tTextContent,\n\tToolCall,\n\tToolResultMessage,\n} from \"../types.ts\";\n\nconst NON_VISION_USER_IMAGE_PLACEHOLDER = \"(image omitted: model does not support images)\";\nconst NON_VISION_TOOL_IMAGE_PLACEHOLDER = \"(tool image omitted: model does not support images)\";\nconst ERROR_TOOL_IMAGE_PLACEHOLDER = \"(image attached after the tool results)\";\n\n/** An error tool result split into a text-only result and the images to send after the tool results. */\nexport interface SplitErrorToolResult {\n\t/** The result content with each run of images replaced by a note. */\n\tcontent: TextContent[];\n\t/** Text naming the tool call, to send before `images`. */\n\tcaption: string;\n\timages: ImageContent[];\n}\n\n/**\n * Split the images out of an error tool result, for APIs that reject images in error results\n * (Anthropic, and Claude on Bedrock). Send the returned content as the tool result and the caption and\n * images after all tool results of the turn, in the same user message. Returns undefined for results\n * that need no split (#10794).\n */\nexport function splitErrorToolResultImages(msg: ToolResultMessage): SplitErrorToolResult | undefined {\n\tif (!msg.isError) return undefined;\n\tconst images = msg.content.filter((block): block is ImageContent => block.type === \"image\");\n\tif (images.length === 0) return undefined;\n\treturn {\n\t\tcontent: replaceImagesWithPlaceholder(msg.content, ERROR_TOOL_IMAGE_PLACEHOLDER),\n\t\tcaption: `Images from the error result of tool call ${msg.toolCallId} (${msg.toolName}):`,\n\t\timages,\n\t};\n}\n\nfunction replaceImagesWithPlaceholder(content: (TextContent | ImageContent)[], placeholder: string): TextContent[] {\n\tconst result: TextContent[] = [];\n\tlet previousWasPlaceholder = false;\n\n\tfor (const block of content) {\n\t\tif (block.type === \"image\") {\n\t\t\tif (!previousWasPlaceholder) {\n\t\t\t\tresult.push({ type: \"text\", text: placeholder });\n\t\t\t}\n\t\t\tpreviousWasPlaceholder = true;\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult.push(block);\n\t\tpreviousWasPlaceholder = block.text === placeholder;\n\t}\n\n\treturn result;\n}\n\nfunction downgradeUnsupportedImages<TApi extends Api>(messages: Message[], model: Model<TApi>): Message[] {\n\tif (model.input.includes(\"image\")) {\n\t\treturn messages;\n\t}\n\n\treturn messages.map((msg) => {\n\t\tif (msg.role === \"user\" && Array.isArray(msg.content)) {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_USER_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\tif (msg.role === \"toolResult\") {\n\t\t\treturn {\n\t\t\t\t...msg,\n\t\t\t\tcontent: replaceImagesWithPlaceholder(msg.content, NON_VISION_TOOL_IMAGE_PLACEHOLDER),\n\t\t\t};\n\t\t}\n\n\t\treturn msg;\n\t});\n}\n\n/**\n * Normalize tool call ID for cross-provider compatibility.\n * OpenAI Responses API generates IDs that are 450+ chars with special characters like `|`.\n * Anthropic APIs require IDs matching ^[a-zA-Z0-9_-]+$ (max 64 chars).\n */\nexport function transformMessages<TApi extends Api>(\n\tmessages: Message[],\n\tmodel: Model<TApi>,\n\tnormalizeToolCallId?: (id: string, model: Model<TApi>, source: AssistantMessage) => string,\n): Message[] {\n\t// Build a map of original tool call IDs to normalized IDs\n\tconst toolCallIdMap = new Map<string, string>();\n\t// Normalize null/undefined content from untyped callers (custom tools, hand-built\n\t// histories, old session files) so downstream code can rely on the type contract.\n\tconst normalizedMessages = messages.map((msg) => (msg.content == null ? { ...msg, content: [] } : msg));\n\tconst imageAwareMessages = downgradeUnsupportedImages(normalizedMessages, model);\n\n\t// First pass: transform messages (unsupported image downgrade, thinking blocks, tool call ID normalization)\n\tconst transformed = imageAwareMessages.map((msg) => {\n\t\t// System and user messages pass through unchanged\n\t\tif (msg.role === \"system\" || msg.role === \"user\") {\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Handle toolResult messages - normalize toolCallId if we have a mapping\n\t\tif (msg.role === \"toolResult\") {\n\t\t\tconst normalizedId = toolCallIdMap.get(msg.toolCallId);\n\t\t\tif (normalizedId && normalizedId !== msg.toolCallId) {\n\t\t\t\treturn { ...msg, toolCallId: normalizedId };\n\t\t\t}\n\t\t\treturn msg;\n\t\t}\n\n\t\t// Assistant messages need transformation check\n\t\tif (msg.role === \"assistant\") {\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tconst isSameModel =\n\t\t\t\tassistantMsg.provider === model.provider &&\n\t\t\t\tassistantMsg.api === model.api &&\n\t\t\t\tassistantMsg.model === model.id;\n\n\t\t\tconst transformedContent = assistantMsg.content.flatMap((block) => {\n\t\t\t\tif (block.type === \"thinking\") {\n\t\t\t\t\t// Thinking from another model is dropped. Signatures and encrypted reasoning are\n\t\t\t\t\t// only valid for the model that produced them, and sending readable thinking as\n\t\t\t\t\t// plain text makes the new model treat it as part of the visible reply.\n\t\t\t\t\tif (!isSameModel) return [];\n\t\t\t\t\t// Keep redacted and signed blocks even if the thinking text is empty\n\t\t\t\t\t// (OpenAI encrypted reasoning); they are needed for replay.\n\t\t\t\t\tif (block.redacted || block.thinkingSignature) return block;\n\t\t\t\t\tif (!block.thinking || block.thinking.trim() === \"\") return [];\n\t\t\t\t\treturn block;\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"text\") {\n\t\t\t\t\tif (isSameModel) return block;\n\t\t\t\t\treturn {\n\t\t\t\t\t\ttype: \"text\" as const,\n\t\t\t\t\t\ttext: block.text,\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (block.type === \"toolCall\") {\n\t\t\t\t\tconst toolCall = block as ToolCall;\n\t\t\t\t\tlet normalizedToolCall: ToolCall = toolCall;\n\n\t\t\t\t\tif (!isSameModel && toolCall.thoughtSignature) {\n\t\t\t\t\t\tnormalizedToolCall = { ...toolCall };\n\t\t\t\t\t\tdelete (normalizedToolCall as { thoughtSignature?: string }).thoughtSignature;\n\t\t\t\t\t}\n\n\t\t\t\t\tif (!isSameModel && normalizeToolCallId) {\n\t\t\t\t\t\tconst normalizedId = normalizeToolCallId(toolCall.id, model, assistantMsg);\n\t\t\t\t\t\tif (normalizedId !== toolCall.id) {\n\t\t\t\t\t\t\ttoolCallIdMap.set(toolCall.id, normalizedId);\n\t\t\t\t\t\t\tnormalizedToolCall = { ...normalizedToolCall, id: normalizedId };\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\treturn normalizedToolCall;\n\t\t\t\t}\n\n\t\t\t\treturn block;\n\t\t\t});\n\n\t\t\treturn {\n\t\t\t\t...assistantMsg,\n\t\t\t\tcontent: transformedContent,\n\t\t\t};\n\t\t}\n\t\treturn msg;\n\t});\n\n\t// Second pass: insert synthetic empty tool results for orphaned tool calls\n\t// This preserves thinking signatures and satisfies API requirements\n\tconst result: Message[] = [];\n\tlet pendingToolCalls: ToolCall[] = [];\n\tlet existingToolResultIds = new Set<string>();\n\t// System messages are transparent to tool-call accounting: one that lands between a tool\n\t// call and its results is held back and emitted after the results (synthetic ones\n\t// included), so it never causes a duplicate result for a call that is answered later.\n\tconst heldSystemMessages: Message[] = [];\n\tconst closePendingToolCalls = () => {\n\t\tif (pendingToolCalls.length > 0) {\n\t\t\tfor (const tc of pendingToolCalls) {\n\t\t\t\tif (!existingToolResultIds.has(tc.id)) {\n\t\t\t\t\tresult.push({\n\t\t\t\t\t\trole: \"toolResult\",\n\t\t\t\t\t\ttoolCallId: tc.id,\n\t\t\t\t\t\ttoolName: tc.name,\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: \"No result provided\" }],\n\t\t\t\t\t\tisError: true,\n\t\t\t\t\t\ttimestamp: Date.now(),\n\t\t\t\t\t} as ToolResultMessage);\n\t\t\t\t}\n\t\t\t}\n\t\t\tpendingToolCalls = [];\n\t\t\texistingToolResultIds = new Set();\n\t\t}\n\t\tresult.push(...heldSystemMessages);\n\t\theldSystemMessages.length = 0;\n\t};\n\n\tfor (let i = 0; i < transformed.length; i++) {\n\t\tconst msg = transformed[i];\n\n\t\tif (msg.role === \"assistant\") {\n\t\t\t// If we have pending orphaned tool calls from a previous assistant, insert synthetic results now\n\t\t\tclosePendingToolCalls();\n\n\t\t\t// Skip errored/aborted assistant messages entirely.\n\t\t\t// These are incomplete turns that shouldn't be replayed:\n\t\t\t// - May have partial content (reasoning without message, incomplete tool calls)\n\t\t\t// - Replaying them can cause API errors (e.g., OpenAI \"reasoning without following item\")\n\t\t\t// - The model should retry from the last valid state\n\t\t\tconst assistantMsg = msg as AssistantMessage;\n\t\t\tif (assistantMsg.stopReason === \"error\" || assistantMsg.stopReason === \"aborted\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Track tool calls from this assistant message\n\t\t\tconst toolCalls = assistantMsg.content.filter((b) => b.type === \"toolCall\") as ToolCall[];\n\t\t\tif (toolCalls.length > 0) {\n\t\t\t\tpendingToolCalls = toolCalls;\n\t\t\t\texistingToolResultIds = new Set();\n\t\t\t}\n\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"toolResult\") {\n\t\t\texistingToolResultIds.add(msg.toolCallId);\n\t\t\tresult.push(msg);\n\t\t} else if (msg.role === \"system\") {\n\t\t\tif (pendingToolCalls.length > 0) {\n\t\t\t\theldSystemMessages.push(msg);\n\t\t\t} else {\n\t\t\t\tresult.push(msg);\n\t\t\t}\n\t\t} else if (msg.role === \"user\") {\n\t\t\t// A new user turn interrupts tool flow - insert synthetic results for orphaned calls\n\t\t\tclosePendingToolCalls();\n\t\t\tresult.push(msg);\n\t\t} else {\n\t\t\tresult.push(msg);\n\t\t}\n\t}\n\n\t// If the conversation ends with unresolved tool calls, synthesize results now.\n\tclosePendingToolCalls();\n\n\treturn result;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typesafe-system-one.d.ts","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"typesafe-system-one.d.ts","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AA8BzE,gGAAgG;AAChG,eAAO,MAAM,QAAQ,EAAE,kBAAkB,CAAC,iBAAiB,CACL,CAAC"}
|
|
@@ -1,11 +1,22 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { isRecord } from "./classifier-shared.js";
|
|
2
|
+
import { classifySystemOne } from "./system-one-shared.js";
|
|
2
3
|
/**
|
|
3
4
|
* TypeSafe's native System One protocol. OpenRouter serves the same protocol,
|
|
4
5
|
* so both providers use this API with different base URLs.
|
|
6
|
+
*
|
|
7
|
+
* TypeSafe takes images as `assets`. They are experimental and need the
|
|
8
|
+
* `TypeSafe-Danger-Zone-Images` opt-in header; without it the API answers 400.
|
|
9
|
+
* OpenRouter drops `assets` silently and takes images as `image_url` parts in the state instead.
|
|
10
|
+
* Models behind a proxy that hides both the provider ID and the OpenRouter host must set
|
|
11
|
+
* `compat.imageInput`.
|
|
5
12
|
*/
|
|
6
13
|
const transport = {
|
|
7
14
|
api: "typesafe-system-one",
|
|
8
15
|
label: "System One API",
|
|
16
|
+
// OpenRouter by provider ID, which survives baseUrl overrides, or by host, which covers regional endpoints.
|
|
17
|
+
detectCompat: (model) => model.provider === "openrouter" || model.baseUrl.includes("openrouter.ai")
|
|
18
|
+
? { imageInput: "state-image-urls", sendImageOptInHeader: false }
|
|
19
|
+
: { imageInput: "assets", sendImageOptInHeader: true },
|
|
9
20
|
url: (model) => new URL("systemone", `${model.baseUrl.replace(/\/+$/u, "")}/`),
|
|
10
21
|
payload: (model, request) => ({ model: model.id, ...request }),
|
|
11
22
|
output: (body) => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"typesafe-system-one.js","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"typesafe-system-one.js","sourceRoot":"","sources":["../../src/api/typesafe-system-one.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAA2B,MAAM,wBAAwB,CAAC;AAEpF;;;;;;;;;GASG;AACH,MAAM,SAAS,GAAuB;IACrC,GAAG,EAAE,qBAAqB;IAC1B,KAAK,EAAE,gBAAgB;IACvB,4GAA4G;IAC5G,YAAY,EAAE,CAAC,KAAK,EAAE,EAAE,CACvB,KAAK,CAAC,QAAQ,KAAK,YAAY,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC;QACzE,CAAC,CAAC,EAAE,UAAU,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,KAAK,EAAE;QACjE,CAAC,CAAC,EAAE,UAAU,EAAE,QAAQ,EAAE,oBAAoB,EAAE,IAAI,EAAE;IACxD,GAAG,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,IAAI,GAAG,CAAC,WAAW,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,GAAG,CAAC;IAC9E,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,EAAE,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,EAAE,EAAE,GAAG,OAAO,EAAE,CAAC;IAC9D,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;QAChB,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACvF,OAAO,IAAI,CAAC;IACb,CAAC;CACD,CAAC;AAEF,gGAAgG;AAChG,MAAM,CAAC,MAAM,QAAQ,GAA0C,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,EAAE,CAC1F,iBAAiB,CAAC,SAAS,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC","sourcesContent":["import type { ClassifierFunction, ClassifierOptions } from \"../types.ts\";\nimport { isRecord } from \"./classifier-shared.ts\";\nimport { classifySystemOne, type SystemOneTransport } from \"./system-one-shared.ts\";\n\n/**\n * TypeSafe's native System One protocol. OpenRouter serves the same protocol,\n * so both providers use this API with different base URLs.\n *\n * TypeSafe takes images as `assets`. They are experimental and need the\n * `TypeSafe-Danger-Zone-Images` opt-in header; without it the API answers 400.\n * OpenRouter drops `assets` silently and takes images as `image_url` parts in the state instead.\n * Models behind a proxy that hides both the provider ID and the OpenRouter host must set\n * `compat.imageInput`.\n */\nconst transport: SystemOneTransport = {\n\tapi: \"typesafe-system-one\",\n\tlabel: \"System One API\",\n\t// OpenRouter by provider ID, which survives baseUrl overrides, or by host, which covers regional endpoints.\n\tdetectCompat: (model) =>\n\t\tmodel.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")\n\t\t\t? { imageInput: \"state-image-urls\", sendImageOptInHeader: false }\n\t\t\t: { imageInput: \"assets\", sendImageOptInHeader: true },\n\turl: (model) => new URL(\"systemone\", `${model.baseUrl.replace(/\\/+$/u, \"\")}/`),\n\tpayload: (model, request) => ({ model: model.id, ...request }),\n\toutput: (body) => {\n\t\tif (!isRecord(body)) throw new Error(\"System One API returned an unexpected response\");\n\t\treturn body;\n\t},\n};\n\n/** TypeSafe System One classification with public `bool` values mapped to wire-level `noul`. */\nexport const classify: ClassifierFunction<ClassifierOptions> = (model, context, options) =>\n\tclassifySystemOne(transport, model, context, options);\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA6QvF,eAAO,MAAM,cAAc,EAAE,SA6B5B,CAAC"}
|
|
@@ -12,6 +12,8 @@ const CLIENT_ID = decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
|
|
|
12
12
|
const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
|
|
13
13
|
const TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
|
|
14
14
|
const CALLBACK_HOST = getProviderEnvValue("PI_OAUTH_CALLBACK_HOST") || "127.0.0.1";
|
|
15
|
+
// Preferred so the port can be forwarded into containers or over SSH. Anthropic accepts any loopback port,
|
|
16
|
+
// so login falls back to a free port when this one cannot be bound (#10571).
|
|
15
17
|
const CALLBACK_PORT = 53692;
|
|
16
18
|
const CALLBACK_PATH = "/callback";
|
|
17
19
|
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
|
|
@@ -111,21 +113,27 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig
|
|
|
111
113
|
}
|
|
112
114
|
async function loginAnthropic(interaction) {
|
|
113
115
|
const { verifier, challenge } = await generatePKCE();
|
|
114
|
-
const
|
|
116
|
+
const startCallbackServer = (port) => startOAuthCallbackServer({
|
|
115
117
|
providerName: "Anthropic",
|
|
116
118
|
host: CALLBACK_HOST,
|
|
117
|
-
port
|
|
119
|
+
port,
|
|
118
120
|
path: CALLBACK_PATH,
|
|
121
|
+
redirectHost: "localhost",
|
|
119
122
|
state: verifier,
|
|
120
123
|
complete: async (code) => code,
|
|
121
124
|
signal: interaction.signal,
|
|
122
|
-
})
|
|
125
|
+
});
|
|
126
|
+
// Without a callback server, login continues with the pasted redirect URL.
|
|
127
|
+
const callback = await startCallbackServer(CALLBACK_PORT)
|
|
128
|
+
.catch(() => startCallbackServer(0))
|
|
129
|
+
.catch(() => undefined);
|
|
130
|
+
const redirectUri = callback?.redirectUri ?? REDIRECT_URI;
|
|
123
131
|
try {
|
|
124
132
|
const authParams = new URLSearchParams({
|
|
125
133
|
code: "true",
|
|
126
134
|
client_id: CLIENT_ID,
|
|
127
135
|
response_type: "code",
|
|
128
|
-
redirect_uri:
|
|
136
|
+
redirect_uri: redirectUri,
|
|
129
137
|
scope: SCOPES,
|
|
130
138
|
code_challenge: challenge,
|
|
131
139
|
code_challenge_method: "S256",
|
|
@@ -138,7 +146,7 @@ async function loginAnthropic(interaction) {
|
|
|
138
146
|
});
|
|
139
147
|
const result = await waitForCallbackOrManualInput(interaction, callback, {
|
|
140
148
|
message: "Complete login in your browser, or paste the authorization code / redirect URL here:",
|
|
141
|
-
placeholder:
|
|
149
|
+
placeholder: redirectUri,
|
|
142
150
|
});
|
|
143
151
|
let code;
|
|
144
152
|
let state = verifier;
|
|
@@ -155,7 +163,7 @@ async function loginAnthropic(interaction) {
|
|
|
155
163
|
if (!code)
|
|
156
164
|
throw new Error("Missing authorization code");
|
|
157
165
|
interaction.notify({ type: "progress", message: "Exchanging authorization code for tokens..." });
|
|
158
|
-
return await exchangeAuthorizationCode(code, state, verifier,
|
|
166
|
+
return await exchangeAuthorizationCode(code, state, verifier, redirectUri, interaction.signal);
|
|
159
167
|
}
|
|
160
168
|
finally {
|
|
161
169
|
callback?.close();
|