@claudexor/harness-raw-api 4.8.2 → 5.0.2

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.
@@ -0,0 +1,52 @@
1
+ import type { CredentialProfile } from "@claudexor/schema";
2
+ import type { HarnessModelSpec, ModelCatalogObservation } from "@claudexor/core";
3
+ type Env = Record<string, string | null | undefined>;
4
+ /** The parts of one configured instance that decide which key it may send where. */
5
+ export interface RawApiInstance {
6
+ id: string;
7
+ baseUrl: string;
8
+ keyEnv: string;
9
+ }
10
+ /** The instance's default credential: its key variable, then its own secret slot. */
11
+ export declare function instanceApiKey(instance: RawApiInstance, env?: Env): string | undefined;
12
+ /**
13
+ * The key one request sends for a credential identity: ONE resolution for
14
+ * `run()` and the catalog read, so a catalog is never read under another
15
+ * account's key. INV-135 strict profile routing: a raw-api profile is exactly
16
+ * its secret-ref API key, inside the instance fence — the default instance may
17
+ * reference raw/openai slots, a NAMED instance only its own, and the ref must be
18
+ * NAMESPACED (a bare ref would alias the engine-default slot).
19
+ */
20
+ export declare function requestApiKey(instance: RawApiInstance, profile: CredentialProfile | null | undefined, env: Env | undefined): {
21
+ key: string;
22
+ } | {
23
+ refusal: string;
24
+ };
25
+ /** Non-secret identity of one key at one endpoint: a domain-separated,
26
+ * truncated SHA-256. It binds an observation to its key without storing it. */
27
+ export declare function apiKeyFingerprint(baseUrl: string, key: string): string;
28
+ /**
29
+ * The key `run()` sends: the one its spawn's dispatch read checked, when the
30
+ * gate made that read for this instance and profile, so the catalog, the packet
31
+ * sized from it and the request share one key resolution. A key replaced after
32
+ * that check is read by the next spawn (#393 x #147). Without such a read the
33
+ * key resolves now, exactly as the catalog read would.
34
+ */
35
+ export declare function requestKeyFor(instance: RawApiInstance, profile: CredentialProfile | null | undefined, env: Env | undefined, dispatched: ModelCatalogObservation | undefined): {
36
+ key: string;
37
+ } | {
38
+ refusal: string;
39
+ };
40
+ /**
41
+ * The REAL enumeration producer (ADP4): an OpenAI-compatible endpoint exposes
42
+ * `GET <baseURL>/models`. The read is bound to the credential identity `run()`
43
+ * would use and answers a complete catalog or a typed failure — never a
44
+ * smaller list standing in for a failed or partial read (#393). Every answer
45
+ * made with a key names it by fingerprint: a stored secret or key variable can
46
+ * be replaced under the same profile id, so the id alone is no identity.
47
+ */
48
+ export declare function readRawApiCatalog(instance: RawApiInstance, spec?: HarnessModelSpec): Promise<ModelCatalogObservation>;
49
+ /** One GET of the catalog with an already resolved `key`. */
50
+ export declare function readCatalogWithKey(instance: RawApiInstance, key: string, abortSignal?: AbortSignal): Promise<ModelCatalogObservation>;
51
+ export {};
52
+ //# sourceMappingURL=catalog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAgB,MAAM,mBAAmB,CAAC;AACzE,OAAO,KAAK,EACV,gBAAgB,EAGhB,uBAAuB,EACxB,MAAM,iBAAiB,CAAC;AASzB,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC,CAAC;AAErD,oFAAoF;AACpF,MAAM,WAAW,cAAc;IAC7B,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,qFAAqF;AACrF,wBAAgB,cAAc,CAC5B,QAAQ,EAAE,cAAc,EACxB,GAAG,GAAE,GAAiB,GACrB,MAAM,GAAG,SAAS,CAcpB;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,cAAc,EACxB,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,SAAS,EAC7C,GAAG,EAAE,GAAG,GAAG,SAAS,GACnB;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAuBvC;AAED;+EAC+E;AAC/E,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,MAAM,CAKtE;AAmCD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,cAAc,EACxB,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAAG,SAAS,EAC7C,GAAG,EAAE,GAAG,GAAG,SAAS,EACpB,UAAU,EAAE,uBAAuB,GAAG,SAAS,GAC9C;IAAE,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAGvC;AAgDD;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CACrC,QAAQ,EAAE,cAAc,EACxB,IAAI,CAAC,EAAE,gBAAgB,GACtB,OAAO,CAAC,uBAAuB,CAAC,CAMlC;AAED,6DAA6D;AAC7D,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,cAAc,EACxB,GAAG,EAAE,MAAM,EACX,WAAW,CAAC,EAAE,WAAW,GACxB,OAAO,CAAC,uBAAuB,CAAC,CAmClC"}
@@ -0,0 +1,180 @@
1
+ import { createHash } from "node:crypto";
2
+ import { namespacedSecretRefBase, resolveSecret } from "@claudexor/secrets";
3
+ import { redactSecrets } from "@claudexor/util";
4
+ import { parseModelsList } from "./parse.js";
5
+ /** Model enumeration is interactive (a picker waits on it): keep it snappy. */
6
+ const RAW_API_MODELS_TIMEOUT_MS = 15_000;
7
+ const FAILURE_DETAIL_MAX_CHARS = 200;
8
+ /** The instance's default credential: its key variable, then its own secret slot. */
9
+ export function instanceApiKey(instance, env = process.env) {
10
+ const value = env[instance.keyEnv];
11
+ if (value)
12
+ return value;
13
+ // Secret fallback is INSTANCE-SCOPED so a key for one provider is never sent
14
+ // to another (e.g. an OpenAI "raw" key must not reach openrouter.ai). The
15
+ // default OpenAI-compatible instance owns the managed "raw" (and "openai")
16
+ // secret; every named instance (openrouter, …) resolves ONLY its own slot.
17
+ if (instance.id === "raw-api") {
18
+ return (resolveSecret("raw") ??
19
+ (instance.keyEnv === "OPENAI_API_KEY" ? (resolveSecret("openai") ?? undefined) : undefined));
20
+ }
21
+ return resolveSecret(instance.id) ?? undefined;
22
+ }
23
+ /**
24
+ * The key one request sends for a credential identity: ONE resolution for
25
+ * `run()` and the catalog read, so a catalog is never read under another
26
+ * account's key. INV-135 strict profile routing: a raw-api profile is exactly
27
+ * its secret-ref API key, inside the instance fence — the default instance may
28
+ * reference raw/openai slots, a NAMED instance only its own, and the ref must be
29
+ * NAMESPACED (a bare ref would alias the engine-default slot).
30
+ */
31
+ export function requestApiKey(instance, profile, env) {
32
+ const { id } = instance;
33
+ if (!profile) {
34
+ const key = instanceApiKey(instance, { ...process.env, ...env });
35
+ return key ? { key } : { refusal: `${id}: ${instance.keyEnv} not set` };
36
+ }
37
+ if (profile.credential_kind !== "api_key")
38
+ return {
39
+ refusal: `credential profile "${profile.profile_id}": ${id} supports only the api_key transport`,
40
+ };
41
+ const ref = profile.secret_ref ?? "";
42
+ const base = namespacedSecretRefBase(ref);
43
+ const allowed = id === "raw-api" ? ["raw", "openai"] : [id];
44
+ if (!base || !allowed.includes(base))
45
+ return {
46
+ refusal: `credential profile "${profile.profile_id}": secret "${ref || "(missing ref)"}" is outside ${id}'s instance fence (namespaced base:profile refs only; allowed bases: ${allowed.join(", ")})`,
47
+ };
48
+ const key = (profile.secret_ref ? resolveSecret(profile.secret_ref) : null) ?? undefined;
49
+ return key
50
+ ? { key }
51
+ : {
52
+ refusal: `credential profile "${profile.profile_id}": secret "${profile.secret_ref ?? "(missing ref)"}" is not stored`,
53
+ };
54
+ }
55
+ /** Non-secret identity of one key at one endpoint: a domain-separated,
56
+ * truncated SHA-256. It binds an observation to its key without storing it. */
57
+ export function apiKeyFingerprint(baseUrl, key) {
58
+ return createHash("sha256")
59
+ .update(`claudexor.api-key-fingerprint.v1\0${baseUrl.replace(/\/$/, "")}\0${key}`)
60
+ .digest("hex")
61
+ .slice(0, 16);
62
+ }
63
+ /** The key one catalog read resolved, for one instance and profile. Only the
64
+ * fingerprint is public: the key is a private field, so no event, record, log
65
+ * or copy of the observation carries it, and it lives as long as the read. */
66
+ class CheckedApiKey {
67
+ fingerprint;
68
+ #key;
69
+ #instanceId;
70
+ #profileId;
71
+ constructor(instance, profile, key) {
72
+ this.fingerprint = apiKeyFingerprint(instance.baseUrl, key);
73
+ this.#key = key;
74
+ this.#instanceId = instance.id;
75
+ this.#profileId = profile?.profile_id ?? null;
76
+ }
77
+ static keyFor(credential, instance, profile) {
78
+ return credential instanceof CheckedApiKey &&
79
+ credential.#instanceId === instance.id &&
80
+ credential.#profileId === (profile?.profile_id ?? null)
81
+ ? credential.#key
82
+ : undefined;
83
+ }
84
+ }
85
+ /**
86
+ * The key `run()` sends: the one its spawn's dispatch read checked, when the
87
+ * gate made that read for this instance and profile, so the catalog, the packet
88
+ * sized from it and the request share one key resolution. A key replaced after
89
+ * that check is read by the next spawn (#393 x #147). Without such a read the
90
+ * key resolves now, exactly as the catalog read would.
91
+ */
92
+ export function requestKeyFor(instance, profile, env, dispatched) {
93
+ const checked = CheckedApiKey.keyFor(dispatched?.credential, instance, profile);
94
+ return checked ? { key: checked } : requestApiKey(instance, profile, env);
95
+ }
96
+ function unavailable(cause, httpStatus, detail) {
97
+ const bounded = redactSecrets(detail.replace(/\s+/g, " ").trim()).slice(0, FAILURE_DETAIL_MAX_CHARS);
98
+ return { status: "unavailable", failure: { cause, httpStatus, detail: bounded || "no detail" } };
99
+ }
100
+ function isTimeout(err) {
101
+ return err instanceof DOMException && err.name === "TimeoutError";
102
+ }
103
+ /** undici reports every transport failure as "fetch failed" and keeps the
104
+ * reason in `cause`: a socket code (ECONNREFUSED, ENOTFOUND, ...) or, for a
105
+ * refusal before any socket such as a blocked port, only a message. */
106
+ function networkDetail(err) {
107
+ const message = err instanceof Error ? err.message : String(err);
108
+ const cause = err instanceof Error ? err.cause : undefined;
109
+ const reason = typeof cause?.["code"] === "string" && cause["code"]
110
+ ? cause["code"]
111
+ : typeof cause?.["message"] === "string"
112
+ ? cause["message"]
113
+ : "";
114
+ return reason && reason !== message ? `${message} (${reason})` : message;
115
+ }
116
+ /** Catalog metadata is copied only when known: absent means unknown, never "none". */
117
+ function harnessModel(row) {
118
+ return {
119
+ id: row.id,
120
+ label: row.label,
121
+ context_window: row.context_window,
122
+ // A live enumeration reflects the credentials it ran under; route
123
+ // scoping is a manifest-annotation concept (W11), not an API fact.
124
+ routes: null,
125
+ ...(row.input_modalities ? { input_modalities: row.input_modalities } : {}),
126
+ ...(row.max_output_tokens ? { max_output_tokens: row.max_output_tokens } : {}),
127
+ };
128
+ }
129
+ /**
130
+ * The REAL enumeration producer (ADP4): an OpenAI-compatible endpoint exposes
131
+ * `GET <baseURL>/models`. The read is bound to the credential identity `run()`
132
+ * would use and answers a complete catalog or a typed failure — never a
133
+ * smaller list standing in for a failed or partial read (#393). Every answer
134
+ * made with a key names it by fingerprint: a stored secret or key variable can
135
+ * be replaced under the same profile id, so the id alone is no identity.
136
+ */
137
+ export async function readRawApiCatalog(instance, spec) {
138
+ const profile = spec?.credentialProfile;
139
+ const credential = requestApiKey(instance, profile, spec?.env);
140
+ if ("refusal" in credential)
141
+ return unavailable("no_credential", null, credential.refusal);
142
+ const read = await readCatalogWithKey(instance, credential.key, spec?.abortSignal);
143
+ return { ...read, credential: new CheckedApiKey(instance, profile, credential.key) };
144
+ }
145
+ /** One GET of the catalog with an already resolved `key`. */
146
+ export async function readCatalogWithKey(instance, key, abortSignal) {
147
+ const timeout = AbortSignal.timeout(RAW_API_MODELS_TIMEOUT_MS);
148
+ const signal = abortSignal ? AbortSignal.any([abortSignal, timeout]) : timeout;
149
+ let res;
150
+ try {
151
+ res = await fetch(`${instance.baseUrl.replace(/\/$/, "")}/models`, {
152
+ method: "GET",
153
+ headers: { accept: "application/json", authorization: `Bearer ${key}` },
154
+ signal,
155
+ });
156
+ }
157
+ catch (err) {
158
+ return isTimeout(err)
159
+ ? unavailable("timeout", null, `no answer within ${RAW_API_MODELS_TIMEOUT_MS / 1000}s`)
160
+ : unavailable("network", null, networkDetail(err));
161
+ }
162
+ if (!res.ok) {
163
+ const body = await res.text().catch(() => "");
164
+ return unavailable(res.status === 401 || res.status === 403 ? "auth_rejected" : "http_status", res.status, body);
165
+ }
166
+ let json;
167
+ try {
168
+ json = await res.json();
169
+ }
170
+ catch (err) {
171
+ return isTimeout(err)
172
+ ? unavailable("timeout", res.status, "the catalog body did not finish arriving")
173
+ : unavailable("malformed", res.status, "the answer is not JSON");
174
+ }
175
+ const parsed = parseModelsList(json);
176
+ return parsed.ok
177
+ ? { status: "listed", models: parsed.models.map(harnessModel) }
178
+ : unavailable(parsed.cause, res.status, parsed.detail);
179
+ }
180
+ //# sourceMappingURL=catalog.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"catalog.js","sourceRoot":"","sources":["../src/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAQzC,OAAO,EAAE,uBAAuB,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAC5E,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAoB,MAAM,YAAY,CAAC;AAE/D,+EAA+E;AAC/E,MAAM,yBAAyB,GAAG,MAAM,CAAC;AACzC,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAWrC,qFAAqF;AACrF,MAAM,UAAU,cAAc,CAC5B,QAAwB,EACxB,GAAG,GAAQ,OAAO,CAAC,GAAG;IAEtB,MAAM,KAAK,GAAG,GAAG,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACnC,IAAI,KAAK;QAAE,OAAO,KAAK,CAAC;IACxB,6EAA6E;IAC7E,0EAA0E;IAC1E,2EAA2E;IAC3E,2EAA2E;IAC3E,IAAI,QAAQ,CAAC,EAAE,KAAK,SAAS,EAAE,CAAC;QAC9B,OAAO,CACL,aAAa,CAAC,KAAK,CAAC;YAC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C;QACZ,MAAM,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;QAC9C,OAAO,WAAW,CAChB,GAAG,CAAC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,GAAG,CAAC,CAAC,CAAC,eAAe,CAAC,CAAC,CAAC,aAAa,EAC1E,GAAG,CAAC,MAAM,EACV,IAAI,CACL,CAAC;IACJ,CAAC;IACD,IAAI,IAAa,CAAC;IAClB,IAAI,CAAC;QACH,IAAI,GAAG,MAAM,GAAG,CAAC,IAAI,EAAE,CAAC;IAC1B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,OAAO,SAAS,CAAC,GAAG,CAAC;YACnB,CAAC,CAAC,WAAW,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,EAAE,0CAA0C,CAAC;YAChF,CAAC,CAAC,WAAW,CAAC,WAAW,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,CAAC;IACrE,CAAC;IACD,MAAM,MAAM,GAAG,eAAe,CAAC,IAAI,CAAC,CAAC;IACrC,OAAO,MAAM,CAAC,EAAE;QACd,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,YAAY,CAAC,EAAE;QAC/D,CAAC,CAAC,WAAW,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;AAC3D,CAAC"}
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
- import type { ProviderFamily } from "@claudexor/schema";
1
+ import type { ModelRoutingVariant, ProviderFamily, RefusedModelVariant } from "@claudexor/schema";
2
2
  import type { HarnessAdapter } from "@claudexor/core";
3
+ export { KEY_ALLOWANCE_SOURCE, instanceKeyCredentials, parseKeyAllowance, readKeyAllowance, type KeyCredential, } from "./key-allowance.js";
3
4
  export interface RawApiConfig {
4
5
  id?: string;
5
6
  providerFamily?: ProviderFamily;
@@ -11,6 +12,11 @@ export interface RawApiConfig {
11
12
  baseUrl?: string;
12
13
  keyEnv?: string;
13
14
  defaultModel?: string;
15
+ /** Request-time routing suffixes this provider accepts on a listed id (#145);
16
+ * declared by the registry instance, surfaced as `model_routing_variants`. */
17
+ routingVariants?: readonly ModelRoutingVariant[];
18
+ /** Suffixes this instance refuses on any id (#393): `model_refused_variants`. */
19
+ refusedVariants?: readonly RefusedModelVariant[];
14
20
  }
15
21
  /**
16
22
  * A raw-API harness backed by an OpenAI-compatible chat-completions endpoint.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAMV,cAAc,EAEf,MAAM,mBAAmB,CAAC;AAM3B,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAwGlE,MAAM,WAAW,YAAY;IAC3B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;;OAGG;IACH,qBAAqB,CAAC,EAAE,KAAK,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,GAAE,YAAiB,GAAG,cAAc,CAgc7E"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAKV,mBAAmB,EACnB,cAAc,EAEd,mBAAmB,EACpB,MAAM,mBAAmB,CAAC;AAM3B,OAAO,KAAK,EAAc,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAgBlE,OAAO,EACL,oBAAoB,EACpB,sBAAsB,EACtB,iBAAiB,EACjB,gBAAgB,EAChB,KAAK,aAAa,GACnB,MAAM,oBAAoB,CAAC;AA4D5B,MAAM,WAAW,YAAY;IAC3B,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,cAAc,CAAC,EAAE,cAAc,CAAC;IAChC;;;OAGG;IACH,qBAAqB,CAAC,EAAE,KAAK,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;kFAC8E;IAC9E,eAAe,CAAC,EAAE,SAAS,mBAAmB,EAAE,CAAC;IACjD,iFAAiF;IACjF,eAAe,CAAC,EAAE,SAAS,mBAAmB,EAAE,CAAC;CAClD;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,MAAM,GAAE,YAAiB,GAAG,cAAc,CA+Z7E"}
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { ConformanceReport as ConformanceReportSchema, HarnessManifest as HarnessManifestSchema, RawGitPatchEnvelope as RawGitPatchEnvelopeSchema, } from "@claudexor/schema";
2
- import { HarnessUnavailableError, abortSignalFromSpec, parseUnifiedDiff, readVerifiedAttachmentBytes, } from "@claudexor/core";
3
- import { namespacedSecretRefBase, resolveSecret } from "@claudexor/secrets";
2
+ import { HarnessUnavailableError, abortSignalFromSpec, catalogRowFor, dispatchModelCatalog, parseUnifiedDiff, } from "@claudexor/core";
4
3
  import { CLAUDEXOR_VERSION, normalizeRetryDelayMs, nowIso, redactSecrets, sha256, } from "@claudexor/util";
5
- import { parseChatCompletion, parseModelsList } from "./parse.js";
4
+ import { instanceApiKey, readCatalogWithKey, readRawApiCatalog, requestKeyFor } from "./catalog.js";
5
+ export { KEY_ALLOWANCE_SOURCE, instanceKeyCredentials, parseKeyAllowance, readKeyAllowance, } from "./key-allowance.js";
6
+ import { parseChatCompletion } from "./parse.js";
6
7
  import { isTerminalProviderCompletion, providerCompletionErrorEvent } from "./providerError.js";
8
+ import { estimateMessageTokens, finalWindowRefusal, imageInputDisclosure, rawApiMessages, rawApiRequestCapacity, rawContextDisclosure, } from "./request.js";
7
9
  /** A stalled remote endpoint must not hang a run forever. */
8
10
  const RAW_API_TIMEOUT_MS = 180_000;
9
- /** Model enumeration is interactive (a picker waits on it): keep it snappy. */
10
- const RAW_API_MODELS_TIMEOUT_MS = 15_000;
11
11
  const RAW_API_TRANSIENT_STATUS = new Set([408, 502, 503, 504]);
12
12
  const RAW_API_ENABLED_INTENTS = [
13
13
  "implement",
@@ -19,43 +19,6 @@ const RAW_API_ENABLED_INTENTS = [
19
19
  ];
20
20
  const RAW_API_DISABLED_INTENTS = ["create_from_scratch", "repair", "verify", "audit"];
21
21
  const ALL_RAW_API_INTENTS = [...RAW_API_ENABLED_INTENTS, ...RAW_API_DISABLED_INTENTS];
22
- /**
23
- * Build the chat-completions content from digest-bound immutable resources.
24
- */
25
- function rawApiUserContent(spec) {
26
- let prompt = spec.prompt;
27
- if ((spec.intent === "implement" || spec.intent === "synthesize") && spec.raw_context_packet) {
28
- prompt = [
29
- prompt,
30
- "",
31
- 'Produce the requested change only by returning one JSON object: {"patch":"<complete textual git unified diff>"}.',
32
- "Touch existing files only from editable_paths. New paths are allowed only below creatable_roots.",
33
- "Do not calculate hashes or preimage evidence; the trusted local adapter derives them. Do not use Markdown fences or add prose. Binary patches are unsupported.",
34
- "RAW_CONTEXT_PACKET:",
35
- JSON.stringify(spec.raw_context_packet),
36
- ].join("\n");
37
- }
38
- const attachments = spec.attachments ?? [];
39
- if (attachments.length === 0)
40
- return prompt;
41
- const parts = [{ type: "text", text: prompt }];
42
- for (const a of attachments) {
43
- const bytes = readVerifiedAttachmentBytes(a);
44
- if (a.kind === "image") {
45
- parts.push({
46
- type: "image_url",
47
- image_url: { url: `data:${a.mime};base64,${bytes.toString("base64")}` },
48
- });
49
- }
50
- else {
51
- parts.push({
52
- type: "text",
53
- text: `Attached file ${a.name || a.resource_id} (${a.mime}, ${a.sha256}):\n${bytes.toString("utf8")}`,
54
- });
55
- }
56
- }
57
- return parts.length > 1 ? parts : prompt;
58
- }
59
22
  function buildPatchEnvelope(text, context) {
60
23
  const proposal = JSON.parse(text);
61
24
  if (!proposal ||
@@ -99,20 +62,10 @@ export function createRawApiAdapter(config = {}) {
99
62
  const baseUrl = config.baseUrl ?? process.env.CLAUDEXOR_RAWAPI_BASE_URL ?? "https://api.openai.com/v1";
100
63
  const keyEnv = config.keyEnv ?? (process.env.CLAUDEXOR_RAWAPI_KEY ? "CLAUDEXOR_RAWAPI_KEY" : "OPENAI_API_KEY");
101
64
  const defaultModel = config.defaultModel ?? process.env.CLAUDEXOR_RAWAPI_MODEL ?? "gpt-4o-mini";
102
- function apiKey(env = process.env) {
103
- const value = env[keyEnv];
104
- if (value)
105
- return value;
106
- // Secret fallback is INSTANCE-SCOPED so a key for one provider is never sent
107
- // to another (e.g. an OpenAI "raw" key must not reach openrouter.ai). The
108
- // default OpenAI-compatible instance owns the managed "raw" (and "openai")
109
- // secret; every named instance (openrouter, …) resolves ONLY its own slot.
110
- if (id === "raw-api") {
111
- return (resolveSecret("raw") ??
112
- (keyEnv === "OPENAI_API_KEY" ? (resolveSecret("openai") ?? undefined) : undefined));
113
- }
114
- return resolveSecret(id) ?? undefined;
115
- }
65
+ const routingVariants = config.routingVariants ?? [];
66
+ const refusedVariants = config.refusedVariants ?? [];
67
+ const instance = { id, baseUrl, keyEnv };
68
+ const apiKey = (env) => instanceApiKey(instance, env);
116
69
  const adapter = {
117
70
  id,
118
71
  async discover() {
@@ -149,6 +102,8 @@ export function createRawApiAdapter(config = {}) {
149
102
  // The chat-completions request sends no `reasoning_effort` field
150
103
  // (body is {model, messages} only) -> effort is not a tunable surface.
151
104
  effort_levels: [],
105
+ ...(routingVariants.length > 0 ? { model_routing_variants: [...routingVariants] } : {}),
106
+ ...(refusedVariants.length > 0 ? { model_refused_variants: [...refusedVariants] } : {}),
152
107
  },
153
108
  capability_profile: {
154
109
  auth: {
@@ -251,95 +206,33 @@ export function createRawApiAdapter(config = {}) {
251
206
  auth_sources: [readiness],
252
207
  });
253
208
  },
254
- // The REAL enumeration producer (ADP4): an OpenAI-compatible endpoint
255
- // exposes `GET <baseURL>/models`. Fails SOFT — a picker must never see a
256
- // throw, so network/auth/parse errors collapse to an empty list.
257
- async models() {
258
- const key = apiKey();
259
- if (!key)
260
- return [];
261
- try {
262
- const res = await fetch(`${baseUrl.replace(/\/$/, "")}/models`, {
263
- method: "GET",
264
- headers: { accept: "application/json", authorization: `Bearer ${key}` },
265
- signal: AbortSignal.timeout(RAW_API_MODELS_TIMEOUT_MS),
266
- });
267
- if (!res.ok)
268
- return [];
269
- const json = await res.json();
270
- return parseModelsList(json).map((m) => ({
271
- id: m.id,
272
- label: m.label,
273
- context_window: m.context_window,
274
- // A live enumeration reflects the credentials it ran under; route
275
- // scoping is a manifest-annotation concept (W11), not an API fact.
276
- routes: null,
277
- }));
278
- }
279
- catch {
280
- return [];
281
- }
209
+ // The typed catalog read (#393): the credential identity run() would use,
210
+ // and a failed or partial read is never an (apparently complete) list.
211
+ modelCatalog: (spec) => readRawApiCatalog(instance, spec),
212
+ // Fail-soft display projection of the same read; consumers that decide
213
+ // anything read `modelCatalog` through core's `readModelCatalog`.
214
+ async models(spec) {
215
+ const read = await readRawApiCatalog(instance, spec);
216
+ return read.status === "listed" ? read.models : [];
282
217
  },
218
+ rawRequestCapacity: (spec, catalog) => rawApiRequestCapacity(spec, spec.model_hint ?? defaultModel, routingVariants, catalog),
283
219
  async *run(spec) {
284
- // INV-135 strict profile routing: a raw-api profile is exactly its
285
- // secret-ref API key; other kinds and missing secrets refuse typed.
220
+ // INV-135 strict profile routing: one resolution with the catalog read
221
+ // (catalog.ts); other kinds, fenced refs and missing secrets refuse typed.
222
+ // The key this spawn's dispatch read checked is the one sent.
286
223
  const profile = spec.credential_profile;
287
- let key;
288
- if (profile) {
289
- if (profile.credential_kind !== "api_key") {
290
- yield {
291
- type: "error",
292
- session_id: spec.session_id,
293
- ts: nowIso(),
294
- error: `credential profile "${profile.profile_id}": ${id} supports only the api_key transport`,
295
- };
296
- yield { type: "completed", session_id: spec.session_id, ts: nowIso() };
297
- return;
298
- }
299
- // The instance secret fence holds for profiles too (release wave
300
- // round-11 BLOCK): the default instance may reference raw/openai
301
- // slots; a NAMED instance only its own — a profile must never route
302
- // one provider's key to another provider's base URL. The ref must be
303
- // NAMESPACED (round-15 #5): a bare ref would alias the engine-default
304
- // slot, and profiles are additive identities.
305
- const ref = profile.secret_ref ?? "";
306
- const base = namespacedSecretRefBase(ref);
307
- const allowed = id === "raw-api" ? ["raw", "openai"] : [id];
308
- if (!base || !allowed.includes(base)) {
309
- yield {
310
- type: "error",
311
- session_id: spec.session_id,
312
- ts: nowIso(),
313
- error: `credential profile "${profile.profile_id}": secret "${ref || "(missing ref)"}" is outside ${id}'s instance fence (namespaced base:profile refs only; allowed bases: ${allowed.join(", ")})`,
314
- };
315
- yield { type: "completed", session_id: spec.session_id, ts: nowIso() };
316
- return;
317
- }
318
- key = (profile.secret_ref ? resolveSecret(profile.secret_ref) : null) ?? undefined;
319
- if (!key) {
320
- yield {
321
- type: "error",
322
- session_id: spec.session_id,
323
- ts: nowIso(),
324
- error: `credential profile "${profile.profile_id}": secret "${profile.secret_ref ?? "(missing ref)"}" is not stored`,
325
- };
326
- yield { type: "completed", session_id: spec.session_id, ts: nowIso() };
327
- return;
328
- }
329
- }
330
- else {
331
- key = apiKey({ ...process.env, ...spec.env });
332
- }
333
- if (!key) {
224
+ const credential = requestKeyFor(instance, profile, spec.env, dispatchModelCatalog(spec));
225
+ if ("refusal" in credential) {
334
226
  yield {
335
227
  type: "error",
336
228
  session_id: spec.session_id,
337
229
  ts: nowIso(),
338
- error: `${id}: ${keyEnv} not set`,
230
+ error: credential.refusal,
339
231
  };
340
232
  yield { type: "completed", session_id: spec.session_id, ts: nowIso() };
341
233
  return;
342
234
  }
235
+ const { key } = credential;
343
236
  const model = spec.model_hint ?? defaultModel;
344
237
  // The model is only REQUESTED here; the observed model comes from the response.
345
238
  yield {
@@ -355,20 +248,42 @@ export function createRawApiAdapter(config = {}) {
355
248
  const specSignal = abortSignalFromSpec(spec);
356
249
  const timeoutSignal = AbortSignal.timeout(RAW_API_TIMEOUT_MS);
357
250
  const signal = specSignal ? AbortSignal.any([specSignal, timeoutSignal]) : timeoutSignal;
251
+ const messages = rawApiMessages(spec);
252
+ const budget = spec.raw_context_packet?.budget;
253
+ if (budget && (spec.intent === "implement" || spec.intent === "synthesize")) {
254
+ // #147 backstop: the packet was sized for this request; a request that
255
+ // grew past that KNOWN window afterwards is refused before sending.
256
+ const estimated = estimateMessageTokens(messages);
257
+ const refusal = finalWindowRefusal(budget, model, estimated);
258
+ if (refusal) {
259
+ yield {
260
+ type: "error",
261
+ session_id: spec.session_id,
262
+ ts: nowIso(),
263
+ error: refusal,
264
+ refusal_code: "raw_context_exceeds_window",
265
+ };
266
+ yield { type: "completed", session_id: spec.session_id, ts: nowIso() };
267
+ return;
268
+ }
269
+ const text = rawContextDisclosure(budget, model, estimated);
270
+ // The same facts typed, so no consumer reads them from the sentence.
271
+ const raw_context = { model, estimated_request_tokens: estimated, budget };
272
+ yield { type: "status", session_id: spec.session_id, ts: nowIso(), text, raw_context };
273
+ }
274
+ if (spec.attachments.some((a) => a.kind === "image")) {
275
+ // The dispatch gate's read of this key's catalog when it made one,
276
+ // else one read with the key this request sends.
277
+ const read = dispatchModelCatalog(spec) ?? (await readCatalogWithKey(instance, key));
278
+ const row = read.status === "listed" ? catalogRowFor(model, read.models, routingVariants) : null;
279
+ const text = imageInputDisclosure(model, row);
280
+ if (text)
281
+ yield { type: "status", session_id: spec.session_id, ts: nowIso(), text };
282
+ }
358
283
  const res = await fetch(`${baseUrl.replace(/\/$/, "")}/chat/completions`, {
359
284
  method: "POST",
360
285
  headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
361
- body: JSON.stringify({
362
- model,
363
- messages: [
364
- // Per-run instructions ride the OpenAI-style `system` role (the
365
- // engine already withheld them from synthesis/reviewers).
366
- ...(spec.instructions && spec.instructions.trim()
367
- ? [{ role: "system", content: spec.instructions }]
368
- : []),
369
- { role: "user", content: rawApiUserContent(spec) },
370
- ],
371
- }),
286
+ body: JSON.stringify({ model, messages }),
372
287
  signal,
373
288
  });
374
289
  if (!res.ok) {
@@ -453,17 +368,20 @@ export function createRawApiAdapter(config = {}) {
453
368
  patchEnvelope = buildPatchEnvelope(parsed.text, spec.raw_context_packet);
454
369
  }
455
370
  catch {
371
+ // A provider stop at its output limit is the typed truncation cause.
372
+ const cut = parsed.finish_reason === "length";
456
373
  yield {
457
374
  type: "error",
458
375
  session_id: spec.session_id,
459
376
  ts: nowIso(),
460
- error: `${id} ${spec.intent} response was not a complete Git patch proposal JSON object`,
377
+ error: `${id} ${spec.intent} response was not a complete Git patch proposal JSON object${cut ? " (the provider stopped at its output limit: finish_reason length)" : ""}`,
461
378
  refusal_code: "raw_patch_truncated",
379
+ ...(cut ? { payload: { finish_reason: "length" } } : {}),
462
380
  };
463
381
  }
464
382
  if (patchEnvelope) {
465
- // INV-062: secret-like content in the proposal is not a refusal;
466
- // the engine keeps the bytes and masks only its saved copies.
383
+ // INV-146: secret-like content in the proposal is not a refusal;
384
+ // the engine keeps and saves the exact bytes.
467
385
  yield {
468
386
  type: "patch_produced",
469
387
  session_id: spec.session_id,
@@ -475,6 +393,16 @@ export function createRawApiAdapter(config = {}) {
475
393
  }
476
394
  else if (parsed.text) {
477
395
  yield { type: "message", session_id: spec.session_id, ts: nowIso(), text: parsed.text };
396
+ // An answer cut at the provider's output limit stays an answer (#144)
397
+ // and says so, typed in the payload, instead of reading as complete.
398
+ if (parsed.finish_reason === "length")
399
+ yield {
400
+ type: "status",
401
+ session_id: spec.session_id,
402
+ ts: nowIso(),
403
+ text: "the provider stopped this answer at its output limit (finish_reason length); it may be incomplete",
404
+ payload: { finish_reason: "length" },
405
+ };
478
406
  }
479
407
  yield {
480
408
  type: "usage",