@cortexkit/anthropic-auth-core 2.12.0 → 2.13.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.
@@ -19,4 +19,4 @@ export type { PullReason } from './runtime.js';
19
19
  export type { ApiKeyCredential, CredentialStampStatus, OAuthCredential, PoolCredential, PoolRow, ProviderStateCodec, ProviderStateDrop, ProviderStateReplacement, QuotaCodec, RotateCredential, StoredCredential, } from './schema.js';
20
20
  export { fingerprintOf, LEGACY_STORE_VERSION, POOL_KEY, POOL_ROWS_KEY, POOL_SCHEMA_VERSION, PROVIDER_STATE_KEY, REFRESH_STAMP_TOLERANCE_MS, rowLockKey, } from './schema.js';
21
21
  export type { PoolSettings, SettingsMutator, SettingsRead, UpdateSettingsOptions, UpdateSettingsResult, } from './settings.js';
22
- export { POOL_OWNED_KEYS } from './settings.js';
22
+ export { POOL_OWNED_KEYS, readPoolSettingsAt } from './settings.js';
@@ -52,6 +52,14 @@ export type UpdateSettingsResult = {
52
52
  };
53
53
  /** Reads only the config's settings, without taking a lock or writing anything. */
54
54
  export declare function readPoolSettings(rt: StoreRuntime): Promise<SettingsRead>;
55
+ /**
56
+ * Reads the settings of the pool config at `configPath`, exactly as a store's
57
+ * `readSettings()` does, without opening a store. It reads only that file: no
58
+ * state file, lock, write or migration. A plugin that has already resolved
59
+ * which config file to trust (for example, after a location check) reads it
60
+ * here rather than opening a second store on it.
61
+ */
62
+ export declare function readPoolSettingsAt(configPath: string): Promise<SettingsRead>;
55
63
  /**
56
64
  * One locked read-modify-write of the plugin's settings in the config file
57
65
  * the pool lives in. The pool must be ready (a pending migration or a load
@@ -1,5 +1,6 @@
1
1
  import { type PoolCredential } from "./internal-types/store/index.js";
2
2
  import { type AccountStorage, type OAuthAccountProfile, type OAuthQuotaSnapshot, type PrimeUsageDelta } from './accounts.ts';
3
+ import type { ClaudeGateway } from './gateway.ts';
3
4
  import { type LogLevel } from './logger.ts';
4
5
  import { type NativeAccountMetadataPatch, type NativeAccountSnapshot, type NativeAccountView } from './native-account-view.ts';
5
6
  import { type NativeCustodyReceipt } from './native-custody.ts';
@@ -72,12 +73,32 @@ export interface NativeAccountRuntime {
72
73
  drainRoutingPublications(): Promise<void>;
73
74
  /** Fresh private relay authorization for transport only; never include it in a status snapshot. */
74
75
  getRelayConfig(): Promise<RelayConfig | null>;
76
+ /**
77
+ * Refuses (NativeRuntimeError `relay-not-default-location`, or
78
+ * `relay-account-home-unknown` when the account's home folder cannot be
79
+ * found) when a relay saved now would be ignored. updateRelay runs the same
80
+ * check before enabling a relay.
81
+ */
82
+ assertRelayLocation(): Promise<void>;
75
83
  updateRelay(patch: NativeRelayUpdate): Promise<void>;
84
+ /**
85
+ * Status lines about the relay from memory: why the last read ignored a
86
+ * configured relay (its account settings are not in their default
87
+ * location, or the account's home folder could not be found), or that the
88
+ * relay in use is refused because a proxy setting would carry it in plain
89
+ * text. Never names a value.
90
+ */
91
+ getRelayStatusNotes?(): string[];
76
92
  read(model?: string): Promise<NativeAccountSnapshot>;
77
93
  /** Memory-only policy settings for a tracked target; never persist the returned record. */
78
94
  resolveSettings?(stored: AccountStorage, model?: string): AccountStorage;
79
95
  /** No-model settings and every explicit model override, for /claude status. */
80
96
  getSettingsStatus?(): NativeRuntimeSettingsStatus | undefined;
97
+ /**
98
+ * The user's gateway for Claude OAuth model requests, from memory. Hosts
99
+ * use it only for model requests, never for sign-in, refresh or usage.
100
+ */
101
+ getClaudeGateway?(): ClaudeGateway | undefined;
81
102
  /** Hosts call after startup and committed menu writes; watches use the same deduplicated hook. */
82
103
  applySettingsEffects?(): void;
83
104
  /** Await at instance start and before every /claude action, never on requests. */
@@ -1,4 +1,5 @@
1
1
  import type { AccountStorage } from './accounts.ts';
2
+ import { type ClaudeGateway, type ClaudeGatewayStatus } from './gateway.ts';
2
3
  import { type SettingsKey } from './settings-definition.ts';
3
4
  import { type SettingsMode, type SettingsModeOptions } from './settings-mode.ts';
4
5
  import type { SettingsHost } from './settings-paths.ts';
@@ -29,7 +30,13 @@ export interface NativeRuntimeSettingsOptions {
29
30
  }
30
31
  export interface NativeRuntimeSettingsStatus {
31
32
  file: SettingsFileStatus;
32
- values: SettingsValues;
33
+ /**
34
+ * No-model values. Gateway header values are secrets, so `gateway_headers`
35
+ * is left out; `gateway` shows the gateway in use, with header names only.
36
+ */
37
+ values: Omit<SettingsValues, 'gateway_headers'> & {
38
+ gateway: ClaudeGatewayStatus | null;
39
+ };
33
40
  modelOverrides: Partial<Record<SettingsKey, {
34
41
  model: string;
35
42
  value: SettingsValues[SettingsKey];
@@ -49,6 +56,7 @@ export declare function createNativeRuntimeSettings(options: NativeRuntimeSettin
49
56
  (stored: Record<string, unknown>, model?: string): Record<string, unknown>;
50
57
  };
51
58
  status: () => NativeRuntimeSettingsStatus | undefined;
59
+ gateway: () => ClaudeGateway | undefined;
52
60
  applyEffects: () => void;
53
61
  file: () => string | undefined;
54
62
  prepareAction(): Promise<void>;
@@ -83,10 +83,10 @@ export type NativeRuntimeRead = {
83
83
  state: NativeRuntimeState;
84
84
  };
85
85
  export declare class NativeRuntimeError extends Error {
86
- readonly code: 'invalid-runtime' | 'unsafe-runtime' | 'runtime-io' | 'runtime-conflict' | 'publication-refused' | 'relay-inconsistent';
86
+ readonly code: 'invalid-runtime' | 'unsafe-runtime' | 'runtime-io' | 'runtime-conflict' | 'publication-refused' | 'relay-inconsistent' | 'relay-not-default-location' | 'relay-account-home-unknown';
87
87
  readonly status?: 400;
88
88
  readonly retryable?: false;
89
- constructor(code: 'invalid-runtime' | 'unsafe-runtime' | 'runtime-io' | 'runtime-conflict' | 'publication-refused' | 'relay-inconsistent');
89
+ constructor(code: 'invalid-runtime' | 'unsafe-runtime' | 'runtime-io' | 'runtime-conflict' | 'publication-refused' | 'relay-inconsistent' | 'relay-not-default-location' | 'relay-account-home-unknown');
90
90
  }
91
91
  /** Validate structure and internal identifier consistency. The publisher separately checks these identifiers against the current pool or vault roster. */
92
92
  export declare function decodeNativeRuntime(value: unknown, storageId: string): NativeRuntimeState;
@@ -1,3 +1,4 @@
1
+ import { type ClaudeGateway } from './gateway.ts';
1
2
  /**
2
3
  * Where a Claude OAuth access token may be sent.
3
4
  *
@@ -8,6 +9,11 @@
8
9
  * user opened, so the URL alone is not trusted: every OAuth send checks its
9
10
  * final URL here before the token leaves the process. API-key routes are not
10
11
  * checked here; they keep whatever base URL the user configured.
12
+ *
13
+ * Model requests may also go to the gateway the user named in their own
14
+ * settings file (see gateway.ts). Only the model-request send passes that
15
+ * gateway here; sign-in, refresh, usage and other sends never do, so they
16
+ * stay limited to api.anthropic.com.
11
17
  */
12
18
  export declare const ANTHROPIC_OAUTH_ORIGIN = "https://api.anthropic.com";
13
19
  /** Fixed refusal text. It never includes the refused URL or any credential. */
@@ -19,6 +25,15 @@ export declare const ANTHROPIC_OAUTH_ORIGIN_REFUSAL = "Claude OAuth requests can
19
25
  */
20
26
  export declare class AnthropicOAuthOriginError extends Error {
21
27
  readonly check = "oauth_destination";
28
+ constructor(message?: string);
29
+ }
30
+ /**
31
+ * A plain-http send to the user's gateway was refused locally because a
32
+ * proxy setting would carry it (see claudeGatewayProxyApplies). Nothing was
33
+ * sent, and nothing falls back to api.anthropic.com. Its message is fixed
34
+ * and names no value.
35
+ */
36
+ export declare class ClaudeGatewayProxyRefusal extends AnthropicOAuthOriginError {
22
37
  constructor();
23
38
  }
24
39
  export interface AnthropicOAuthOriginOptions {
@@ -28,6 +43,12 @@ export interface AnthropicOAuthOriginOptions {
28
43
  * never derived from provider configuration.
29
44
  */
30
45
  readonly extraOrigin?: string;
46
+ /**
47
+ * The user's gateway from their settings file, for model requests only.
48
+ * A URL with its exact origin and under its path prefix is accepted. Never
49
+ * derived from provider configuration or the environment.
50
+ */
51
+ readonly gateway?: ClaudeGateway;
31
52
  /**
32
53
  * Builds the error thrown for a refused URL. `unparseable` means the value
33
54
  * is not a URL at all. Defaults to AnthropicOAuthOriginError for both.
@@ -36,16 +57,38 @@ export interface AnthropicOAuthOriginOptions {
36
57
  }
37
58
  /**
38
59
  * Returns the parsed URL when an OAuth token may be sent to it: HTTPS on
39
- * api.anthropic.com's default port (or the caller's extra origin), with no
40
- * user name or password in the URL. Throws otherwise.
60
+ * api.anthropic.com's default port (or the caller's extra origin, or inside
61
+ * the caller's gateway), with no user name or password in the URL. Throws
62
+ * otherwise, and also for a plain-http gateway URL that a proxy setting
63
+ * would carry (ClaudeGatewayProxyRefusal).
41
64
  */
42
65
  export declare function requireAnthropicOAuthOrigin(value: string, options?: AnthropicOAuthOriginOptions): URL;
43
66
  /**
44
67
  * A fetch for OAuth sends. It checks each URL with
45
- * requireAnthropicOAuthOrigin before dispatch and always sets
68
+ * requireAnthropicOAuthOrigin before dispatch, always sets
46
69
  * `redirect: 'error'`, so an approved destination cannot forward the token
47
- * elsewhere with a redirect. It calls the global fetch at call time, so test
70
+ * elsewhere with a redirect, and drops any `tls` option, so certificate
71
+ * checks always apply. It calls the global fetch at call time, so test
48
72
  * stubs installed later still apply. Options are read on every call when
49
73
  * given as a function.
50
74
  */
51
75
  export declare function createAnthropicOAuthFetch(options?: AnthropicOAuthOriginOptions | (() => AnthropicOAuthOriginOptions)): typeof fetch;
76
+ export interface ClaudeModelFetchOptions {
77
+ /** Origin options for every send (test-only loopback, refusal wording). */
78
+ readonly origin?: AnthropicOAuthOriginOptions | (() => AnthropicOAuthOriginOptions);
79
+ /**
80
+ * The user's gateway, or undefined for none. A function is read on every
81
+ * call, so a keep-warm or Prime send follows the current settings; a live
82
+ * request passes the value it read once, so all its sends agree.
83
+ */
84
+ readonly gateway?: ClaudeGateway | undefined | (() => ClaudeGateway | undefined);
85
+ }
86
+ /**
87
+ * A fetch for Claude OAuth model requests (`POST /v1/messages`). Without a
88
+ * gateway it is createAnthropicOAuthFetch. With one, a model request to
89
+ * api.anthropic.com goes to the gateway instead, carrying the gateway
90
+ * headers; only the URL and those headers change. Other URLs are not moved
91
+ * and are checked without the gateway, so nothing but a model request can
92
+ * reach it. Redirects are refused either way.
93
+ */
94
+ export declare function createClaudeModelFetch(options?: ClaudeModelFetchOptions): typeof fetch;
@@ -0,0 +1,109 @@
1
+ import { type StateLayout } from './state-layout-paths.ts';
2
+ /**
3
+ * Where the relay may come from.
4
+ *
5
+ * A relay's URL is read from the selected account store's settings file and
6
+ * its token from that store's runtime file, and every model request is then
7
+ * posted to that URL with the account's bearer inside. Environment variables
8
+ * (OPENCODE_ANTHROPIC_AUTH_FILE, OPENCODE_CONFIG_DIR, XDG_CONFIG_HOME, HOME,
9
+ * PI_ANTHROPIC_AUTH_FILE, PI_CODING_AGENT_DIR and others) can move that store,
10
+ * and a repository's `.env` can set them. In vault and Thalamus-hosted mode
11
+ * the bearer does not live in the store, so a moved store could name a relay
12
+ * that receives the user's real bearer. The relay is therefore honoured only
13
+ * when both files are the ones of the host's default store for the operating
14
+ * system account, found from the account database and never from the
15
+ * environment:
16
+ *
17
+ * - OpenCode: `<home>/.config/opencode/anthropic-auth.json`, with its files
18
+ * wherever this process's state-layout decision put them.
19
+ * - Pi: `<home>/.pi/agent/anthropic-auth.json`.
20
+ *
21
+ * On Windows `<home>` is the user's profile folder (`%USERPROFILE%`).
22
+ *
23
+ * The store's own relay files must be regular files: a selected settings or
24
+ * runtime file whose last path component is a symbolic link is treated as
25
+ * not in the default place, because the link could be repointed after the
26
+ * check. The selected files are resolved again on every check; only the
27
+ * default store's resolved paths are cached.
28
+ */
29
+ /** The Status line, and the reason, when a configured relay is not used. */
30
+ export declare const RELAY_IGNORED_NOTE = "Relay ignored: account settings are not in their default location";
31
+ /** Why saving a relay is refused when the account store is elsewhere. */
32
+ export declare const RELAY_SAVE_REFUSAL = "Relay not saved: account settings are not in their default location";
33
+ /**
34
+ * The Status line, and the reason, when a configured relay is not used
35
+ * because the operating system account's home folder could not be found, so
36
+ * the default place is unknown.
37
+ */
38
+ export declare const RELAY_HOME_UNKNOWN_NOTE = "Relay ignored: the operating system account's home folder could not be found";
39
+ /** Why saving a relay is refused when the account's home is unknown. */
40
+ export declare const RELAY_SAVE_HOME_UNKNOWN_REFUSAL = "Relay not saved: the operating system account's home folder could not be found";
41
+ /**
42
+ * Where the selected store is: its default place, somewhere else, or unknown
43
+ * because the operating system account's home folder could not be found.
44
+ */
45
+ export type RelayLocation = 'default' | 'elsewhere' | 'home-unknown';
46
+ /**
47
+ * Test-only escape hatch for the relay location check.
48
+ *
49
+ * Test suites keep their account stores in temporary folders chosen with
50
+ * environment variables, so no test store is ever in the operating system
51
+ * account's default place. Test preloads set this symbol on `globalThis` to
52
+ * `'unchecked'`, which skips only the relay location check (never the
53
+ * gateway's), or to a function returning the home folder to use in place of
54
+ * the account lookup. It is deliberately not an environment variable: a
55
+ * repository's `.env` could set one. Only code already running in the process
56
+ * can set this symbol, and no shipped code does.
57
+ */
58
+ export declare const TEST_RELAY_ACCOUNT_HOME_KEY: unique symbol;
59
+ /** The two files a relay is read from: settings (URL) and runtime (token). */
60
+ export interface RelayStoreFiles {
61
+ readonly config: string;
62
+ readonly runtime: string;
63
+ }
64
+ export interface RelayStoreSelection {
65
+ readonly local: RelayStoreFiles;
66
+ readonly vault: RelayStoreFiles;
67
+ }
68
+ /**
69
+ * The default store's relay files for `host` under `home`, resolved exactly
70
+ * as the host resolves a store with no environment override: the same file
71
+ * names and, for OpenCode, `layout`, which defaults to the state layout this
72
+ * process decided for that folder. Pi's files never move, so Pi always uses
73
+ * the legacy layout.
74
+ */
75
+ export declare function defaultRelayStoreFiles(host: 'opencode' | 'pi', home: string, layout?: StateLayout): Promise<RelayStoreSelection>;
76
+ export interface RelayLocationCheck {
77
+ /**
78
+ * Where `mode`'s store is; its relay may be used only at 'default'. The
79
+ * account lookup and the default store's paths are cached; the selected
80
+ * store's two files are checked and resolved again on every call.
81
+ */
82
+ locate(mode: 'local' | 'claustrum'): Promise<RelayLocation>;
83
+ /**
84
+ * Like `locate`, and at 'default' also the default store's canonical files
85
+ * the selected ones matched. A relay is read through those files, not the
86
+ * selected path text, so a folder swapped after the check cannot redirect
87
+ * the read. `files` is absent only when tests skip the check.
88
+ */
89
+ resolve(mode: 'local' | 'claustrum'): Promise<{
90
+ location: RelayLocation;
91
+ files?: RelayStoreFiles;
92
+ }>;
93
+ /** Starts the lookups early, off the request path. */
94
+ prepare(): void;
95
+ /** Records that a configured relay was ignored; logs once per store. */
96
+ ignored(mode: 'local' | 'claustrum', location: Exclude<RelayLocation, 'default'>): void;
97
+ /**
98
+ * Records that the last read found no ignored relay, and the URL of the
99
+ * relay it found in use, if any.
100
+ */
101
+ clear(relayUrl?: string): void;
102
+ /**
103
+ * The Status lines: why a configured relay is ignored, or that the relay
104
+ * in use is refused because a proxy setting would carry it; or none.
105
+ */
106
+ statusNotes(env?: Readonly<Record<string, string | undefined>>): string[];
107
+ }
108
+ /** The relay location check for one runtime's local and vault stores. */
109
+ export declare function createRelayLocationCheck(host: 'opencode' | 'pi', selected: RelayStoreSelection): RelayLocationCheck;
package/dist/relay.d.ts CHANGED
@@ -47,7 +47,23 @@ export type RelayAttemptAuthorization = {
47
47
  errorSecrets?: readonly string[];
48
48
  };
49
49
  export type AuthorizeRelayAttempt = () => Promise<RelayAttemptAuthorization>;
50
- export declare function getRelayConfig(storage: AccountStorage | null): RelayConfig | null;
50
+ /**
51
+ * Fixed text for refusing a relay send that a proxy setting would carry in
52
+ * plain text. It names no value: the variables may hold credentials.
53
+ */
54
+ export declare const RELAY_PROXY_REFUSAL = "Relay refused: a proxy setting would carry plain-http requests";
55
+ /**
56
+ * True when a send to the relay at `url` would go in plain text through a
57
+ * proxy that a proxy setting names. The relay envelope carries the account's
58
+ * bearer and the relay token, so such a send is refused, by the same rule as
59
+ * a plain-http gateway (see claudeGatewayProxyApplies). A `ws:` relay counts
60
+ * as plain http: its HTTP rescue posts to `http:`, and a WebSocket handshake
61
+ * is plain text too. `https:` and `wss:` relays are never affected. A URL
62
+ * that cannot be parsed counts as affected, so the check fails closed.
63
+ */
64
+ export declare function relayProxyApplies(url: string, env?: Readonly<Record<string, string | undefined>>): boolean;
65
+ /** Logs once per process that plain-text relay sends are being refused. */
66
+ export declare function warnRelayProxyRefused(): void;
51
67
  export declare function generateRelayToken(): string;
52
68
  export declare function hashBody(body: string): string;
53
69
  export declare function createStringPatch(previous: string, next: string): RelayPatch;
@@ -87,5 +103,5 @@ export declare function sendViaRelay(options: {
87
103
  */
88
104
  requireUpstreamUrl?: (url: string) => unknown;
89
105
  }): Promise<Response>;
90
- export declare const WORKER_SCRIPT = "\nasync function hashBody(body) {\n const bytes = new TextEncoder().encode(body)\n const digest = await crypto.subtle.digest('SHA-256', bytes)\n const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')\n return 'sha256:' + hex\n}\n\nfunction applyPatch(base, patch) {\n return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)\n}\n\nfunction applyPatchSet(base, patch) {\n if (!Array.isArray(patch)) return applyPatch(base, patch)\n if (patch.length === 0) return base\n\n let result = ''\n let cursor = 0\n for (const item of patch) {\n if (item.start < cursor) return { error: 'overlapping patch', status: 400 }\n result += base.slice(cursor, item.start)\n result += item.insert\n cursor = item.start + item.deleteCount\n }\n return result + base.slice(cursor)\n}\n\nasync function readState(env, affinity) {\n const raw = await env.RELAY_STATE.get('session:' + affinity)\n return raw ? JSON.parse(raw) : null\n}\n\nasync function writeState(env, affinity, state) {\n await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })\n}\n\nasync function resolveBody(env, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n const state = await readState(env, payload.affinity)\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nasync function prepareUpstream(env, payload) {\n if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = await resolveBody(env, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n\n if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'relay',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, stateWrite }\n}\n\nfunction resolveBodyFromState(state, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nfunction deferWorkerTask(task) {\n return new Promise((resolve) => setTimeout(resolve, 0)).then(task)\n}\n\nconst WEBSOCKET_STREAM_FLUSH_BYTES = 1024\nconst WEBSOCKET_STREAM_FLUSH_MS = 20\n\nfunction createWebSocketStreamCoalescer(socket, options = {}) {\n const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES\n const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS\n let chunks = []\n let byteLength = 0\n let flushTimer = null\n const stats = {\n upstreamChunks: 0,\n upstreamBytes: 0,\n frames: 0,\n frameBytes: 0,\n }\n\n const clearFlushTimer = () => {\n if (flushTimer === null) return\n clearTimeout(flushTimer)\n flushTimer = null\n }\n\n const mergeChunks = () => {\n if (chunks.length === 1) return chunks[0]\n const frame = new Uint8Array(byteLength)\n let offset = 0\n for (const chunk of chunks) {\n frame.set(chunk, offset)\n offset += chunk.byteLength\n }\n return frame\n }\n\n const flush = () => {\n clearFlushTimer()\n if (byteLength === 0) return\n const frame = mergeChunks()\n chunks = []\n byteLength = 0\n socket.send(frame)\n stats.frames += 1\n stats.frameBytes += frame.byteLength\n }\n\n const scheduleFlush = () => {\n if (flushTimer !== null) return\n flushTimer = setTimeout(flush, flushMs)\n }\n\n return {\n push(value) {\n const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)\n if (chunk.byteLength === 0) return\n stats.upstreamChunks += 1\n stats.upstreamBytes += chunk.byteLength\n chunks.push(chunk)\n byteLength += chunk.byteLength\n if (byteLength >= flushBytes) flush()\n else scheduleFlush()\n },\n flush,\n stats() {\n return { ...stats, pendingBytes: byteLength }\n },\n }\n}\n\nfunction checkpointWebSocketState(env, payload, body, nextState) {\n return deferWorkerTask(async () => {\n try {\n if ((await hashBody(body)) !== payload.next_hash) {\n throw new Error('hash mismatch')\n }\n await writeState(env, payload.affinity, nextState)\n } catch {\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n event: 'checkpoint_write_failed',\n affinity: String(payload.affinity).slice(0, 12),\n code: 'checkpoint_write_error',\n }))\n }\n })\n}\n\nasync function prepareWebSocketUpstream(env, state, payload) {\n if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = resolveBodyFromState(state, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n if (typeof body !== 'string') return { error: 'invalid body', status: 400 }\n if ((await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const nextState = { body, hash: payload.next_hash, revision: payload.revision }\n const checkpoint = checkpointWebSocketState(env, payload, body, nextState)\n const logAccepted = () => console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, state: nextState, checkpoint, logAccepted }\n}\n\nfunction headersToObject(headers) {\n const result = {}\n for (const [key, value] of headers.entries()) result[key] = value\n return result\n}\n\nasync function handleRelayPayload(env, payload) {\n const prepared = await prepareUpstream(env, payload)\n if (prepared.error) return prepared\n const upstream = await fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: prepared.body,\n })\n return { upstream, stateWrite: prepared.stateWrite }\n}\n\nasync function handleWebSocket(socket, env, ctx, payload, getState, setState) {\n const heartbeat = setInterval(() => {\n try {\n socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))\n } catch {\n clearInterval(heartbeat)\n }\n }, 15000)\n let streamCoalescer = null\n try {\n const result = await prepareWebSocketUpstream(env, getState(), payload)\n if (result.error) {\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))\n return\n }\n\n setState(result.state)\n socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))\n ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))\n\n const upstreamPromise = fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: result.body,\n })\n ctx?.waitUntil?.(result.checkpoint)\n const upstream = await upstreamPromise\n socket.send(JSON.stringify({\n protocol: 2,\n type: 'response_start',\n id: payload.id,\n status: upstream.status,\n statusText: upstream.statusText,\n headers: headersToObject(upstream.headers),\n }))\n\n const reader = upstream.body?.getReader()\n if (reader) {\n streamCoalescer = createWebSocketStreamCoalescer(socket)\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n streamCoalescer.push(value)\n }\n streamCoalescer.flush()\n }\n const stats = streamCoalescer?.stats?.() || {}\n socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))\n } catch (error) {\n try {\n streamCoalescer?.flush?.()\n } catch {}\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))\n } finally {\n clearInterval(heartbeat)\n }\n}\n\nexport default {\n async fetch(request, env, ctx) {\n if (request.headers.get('Upgrade') === 'websocket') {\n const url = new URL(request.url)\n const token = url.searchParams.get('token')\n const affinity = url.searchParams.get('affinity')\n if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })\n if (!affinity) return new Response('missing affinity', { status: 400 })\n const pair = new WebSocketPair()\n const client = pair[0]\n const server = pair[1]\n server.binaryType = 'arraybuffer'\n let state = null\n let ready = false\n server.accept()\n const loadState = readState(env, affinity).then((loadedState) => {\n state = loadedState\n ready = true\n server.send(JSON.stringify({\n protocol: 2,\n type: 'ready',\n state: state ? { hash: state.hash, revision: state.revision } : null,\n }))\n }).catch((error) => {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))\n server.close(1011, 'state load failed')\n })\n ctx?.waitUntil?.(loadState)\n if (!ctx?.waitUntil) void loadState\n let busy = false\n server.addEventListener('message', (event) => {\n if (!ready) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))\n return\n }\n if (busy) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))\n return\n }\n let payload\n try {\n payload = JSON.parse(event.data)\n } catch {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))\n return\n }\n payload.affinity = affinity\n busy = true\n const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })\n ctx?.waitUntil?.(run)\n if (!ctx?.waitUntil) void run\n })\n return new Response(null, { status: 101, webSocket: client })\n }\n\n if (request.method === 'GET') {\n return Response.json({ status: 'ok', transports: ['http', 'websocket'] })\n }\n if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })\n if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {\n return new Response('unauthorized', { status: 401 })\n }\n\n try {\n const payload = await request.json()\n const result = await handleRelayPayload(env, payload)\n if (result.error) return Response.json({ error: result.error }, { status: result.status })\n\n if (result.stateWrite) ctx.waitUntil(result.stateWrite)\n\n const upstream = result.upstream\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers: upstream.headers,\n })\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : 'internal relay error' },\n { status: 502 },\n )\n }\n },\n}\n";
106
+ export declare const WORKER_SCRIPT = "\nasync function hashBody(body) {\n const bytes = new TextEncoder().encode(body)\n const digest = await crypto.subtle.digest('SHA-256', bytes)\n const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')\n return 'sha256:' + hex\n}\n\nfunction applyPatch(base, patch) {\n return base.slice(0, patch.start) + patch.insert + base.slice(patch.start + patch.deleteCount)\n}\n\nfunction applyPatchSet(base, patch) {\n if (!Array.isArray(patch)) return applyPatch(base, patch)\n if (patch.length === 0) return base\n\n let result = ''\n let cursor = 0\n for (const item of patch) {\n if (item.start < cursor) return { error: 'overlapping patch', status: 400 }\n result += base.slice(cursor, item.start)\n result += item.insert\n cursor = item.start + item.deleteCount\n }\n return result + base.slice(cursor)\n}\n\nasync function readState(env, affinity) {\n const raw = await env.RELAY_STATE.get('session:' + affinity)\n return raw ? JSON.parse(raw) : null\n}\n\nasync function writeState(env, affinity, state) {\n await env.RELAY_STATE.put('session:' + affinity, JSON.stringify(state), { expirationTtl: 86400 })\n}\n\nasync function resolveBody(env, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n const state = await readState(env, payload.affinity)\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nasync function prepareUpstream(env, payload) {\n if ((payload.protocol !== 1 && payload.protocol !== 2) || payload.type !== 'request' || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = await resolveBody(env, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n\n if (typeof body !== 'string' || (await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const stateWrite = writeState(env, payload.affinity, { body, hash: payload.next_hash, revision: payload.revision }).catch(() => {})\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'relay',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, stateWrite }\n}\n\nfunction resolveBodyFromState(state, payload) {\n if (payload.mode === 'full_sync') return payload.body\n if (payload.mode === 'patch') {\n if (!state || state.hash !== payload.base_hash) {\n return { error: 'state mismatch', status: 409 }\n }\n return applyPatchSet(state.body, payload.patch)\n }\n return { error: 'unknown mode', status: 400 }\n}\n\nfunction deferWorkerTask(task) {\n return new Promise((resolve) => setTimeout(resolve, 0)).then(task)\n}\n\nconst WEBSOCKET_STREAM_FLUSH_BYTES = 1024\nconst WEBSOCKET_STREAM_FLUSH_MS = 20\n\nfunction createWebSocketStreamCoalescer(socket, options = {}) {\n const flushBytes = options.flushBytes || WEBSOCKET_STREAM_FLUSH_BYTES\n const flushMs = options.flushMs ?? WEBSOCKET_STREAM_FLUSH_MS\n let chunks = []\n let byteLength = 0\n let flushTimer = null\n const stats = {\n upstreamChunks: 0,\n upstreamBytes: 0,\n frames: 0,\n frameBytes: 0,\n }\n\n const clearFlushTimer = () => {\n if (flushTimer === null) return\n clearTimeout(flushTimer)\n flushTimer = null\n }\n\n const mergeChunks = () => {\n if (chunks.length === 1) return chunks[0]\n const frame = new Uint8Array(byteLength)\n let offset = 0\n for (const chunk of chunks) {\n frame.set(chunk, offset)\n offset += chunk.byteLength\n }\n return frame\n }\n\n const flush = () => {\n clearFlushTimer()\n if (byteLength === 0) return\n const frame = mergeChunks()\n chunks = []\n byteLength = 0\n socket.send(frame)\n stats.frames += 1\n stats.frameBytes += frame.byteLength\n }\n\n const scheduleFlush = () => {\n if (flushTimer !== null) return\n flushTimer = setTimeout(flush, flushMs)\n }\n\n return {\n push(value) {\n const chunk = value instanceof Uint8Array ? value : new Uint8Array(value)\n if (chunk.byteLength === 0) return\n stats.upstreamChunks += 1\n stats.upstreamBytes += chunk.byteLength\n chunks.push(chunk)\n byteLength += chunk.byteLength\n if (byteLength >= flushBytes) flush()\n else scheduleFlush()\n },\n flush,\n stats() {\n return { ...stats, pendingBytes: byteLength }\n },\n }\n}\n\nfunction checkpointWebSocketState(env, payload, body, nextState) {\n return deferWorkerTask(async () => {\n try {\n if ((await hashBody(body)) !== payload.next_hash) {\n throw new Error('hash mismatch')\n }\n await writeState(env, payload.affinity, nextState)\n } catch {\n console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n event: 'checkpoint_write_failed',\n affinity: String(payload.affinity).slice(0, 12),\n code: 'checkpoint_write_error',\n }))\n }\n })\n}\n\nasync function prepareWebSocketUpstream(env, state, payload) {\n if (payload.protocol !== 2 || payload.type !== 'request' || !payload.id || !payload.affinity || !payload.upstream?.url || !payload.next_hash) {\n return { error: 'invalid payload', status: 400 }\n }\n\n const body = resolveBodyFromState(state, payload)\n if (body && typeof body === 'object' && 'error' in body) return body\n if (typeof body !== 'string') return { error: 'invalid body', status: 400 }\n if ((await hashBody(body)) !== payload.next_hash) {\n return { error: 'hash mismatch', status: 409 }\n }\n\n const nextState = { body, hash: payload.next_hash, revision: payload.revision }\n const checkpoint = checkpointWebSocketState(env, payload, body, nextState)\n const logAccepted = () => console.log(JSON.stringify({\n relay: 'opencode-anthropic-auth',\n transport: 'websocket',\n mode: payload.mode,\n revision: payload.revision,\n affinity: String(payload.affinity).slice(0, 12),\n bodyBytes: body.length,\n }))\n\n return { body, state: nextState, checkpoint, logAccepted }\n}\n\nfunction headersToObject(headers) {\n const result = {}\n for (const [key, value] of headers.entries()) result[key] = value\n return result\n}\n\nasync function handleRelayPayload(env, payload) {\n const prepared = await prepareUpstream(env, payload)\n if (prepared.error) return prepared\n // The upstream headers carry the caller's credential: a redirect is\n // returned to the caller as it is, never followed with them.\n const upstream = await fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: prepared.body,\n redirect: 'manual',\n })\n return { upstream, stateWrite: prepared.stateWrite }\n}\n\nasync function handleWebSocket(socket, env, ctx, payload, getState, setState) {\n const heartbeat = setInterval(() => {\n try {\n socket.send(JSON.stringify({ protocol: 2, type: 'keepalive' }))\n } catch {\n clearInterval(heartbeat)\n }\n }, 15000)\n let streamCoalescer = null\n try {\n const result = await prepareWebSocketUpstream(env, getState(), payload)\n if (result.error) {\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: result.status, message: result.error }))\n return\n }\n\n setState(result.state)\n socket.send(JSON.stringify({ protocol: 2, type: 'accepted', id: payload.id, hash: result.state.hash, revision: result.state.revision }))\n ctx?.waitUntil?.(deferWorkerTask(result.logAccepted))\n\n const upstreamPromise = fetch(payload.upstream.url, {\n method: payload.upstream.method || 'POST',\n headers: payload.upstream.headers,\n body: result.body,\n redirect: 'manual',\n })\n ctx?.waitUntil?.(result.checkpoint)\n const upstream = await upstreamPromise\n socket.send(JSON.stringify({\n protocol: 2,\n type: 'response_start',\n id: payload.id,\n status: upstream.status,\n statusText: upstream.statusText,\n headers: headersToObject(upstream.headers),\n }))\n\n const reader = upstream.body?.getReader()\n if (reader) {\n streamCoalescer = createWebSocketStreamCoalescer(socket)\n while (true) {\n const { done, value } = await reader.read()\n if (done) break\n streamCoalescer.push(value)\n }\n streamCoalescer.flush()\n }\n const stats = streamCoalescer?.stats?.() || {}\n socket.send(JSON.stringify({ protocol: 2, type: 'done', id: payload.id, ...stats }))\n } catch (error) {\n try {\n streamCoalescer?.flush?.()\n } catch {}\n socket.send(JSON.stringify({ protocol: 2, type: 'error', id: payload.id, status: 500, message: error instanceof Error ? error.message : String(error) }))\n } finally {\n clearInterval(heartbeat)\n }\n}\n\nexport default {\n async fetch(request, env, ctx) {\n if (request.headers.get('Upgrade') === 'websocket') {\n const url = new URL(request.url)\n const token = url.searchParams.get('token')\n const affinity = url.searchParams.get('affinity')\n if (token !== env.RELAY_TOKEN) return new Response('unauthorized', { status: 401 })\n if (!affinity) return new Response('missing affinity', { status: 400 })\n const pair = new WebSocketPair()\n const client = pair[0]\n const server = pair[1]\n server.binaryType = 'arraybuffer'\n let state = null\n let ready = false\n server.accept()\n const loadState = readState(env, affinity).then((loadedState) => {\n state = loadedState\n ready = true\n server.send(JSON.stringify({\n protocol: 2,\n type: 'ready',\n state: state ? { hash: state.hash, revision: state.revision } : null,\n }))\n }).catch((error) => {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 500, message: error instanceof Error ? error.message : String(error) }))\n server.close(1011, 'state load failed')\n })\n ctx?.waitUntil?.(loadState)\n if (!ctx?.waitUntil) void loadState\n let busy = false\n server.addEventListener('message', (event) => {\n if (!ready) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 425, message: 'relay state is not ready' }))\n return\n }\n if (busy) {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 429, message: 'request already in flight' }))\n return\n }\n let payload\n try {\n payload = JSON.parse(event.data)\n } catch {\n server.send(JSON.stringify({ protocol: 2, type: 'error', status: 400, message: 'invalid JSON payload' }))\n return\n }\n payload.affinity = affinity\n busy = true\n const run = handleWebSocket(server, env, ctx, payload, () => state, (nextState) => { state = nextState }).finally(() => { busy = false })\n ctx?.waitUntil?.(run)\n if (!ctx?.waitUntil) void run\n })\n return new Response(null, { status: 101, webSocket: client })\n }\n\n if (request.method === 'GET') {\n return Response.json({ status: 'ok', transports: ['http', 'websocket'] })\n }\n if (request.method !== 'POST') return new Response('method not allowed', { status: 405 })\n if (request.headers.get('x-relay-token') !== env.RELAY_TOKEN) {\n return new Response('unauthorized', { status: 401 })\n }\n\n try {\n const payload = await request.json()\n const result = await handleRelayPayload(env, payload)\n if (result.error) return Response.json({ error: result.error }, { status: result.status })\n\n if (result.stateWrite) ctx.waitUntil(result.stateWrite)\n\n const upstream = result.upstream\n return new Response(upstream.body, {\n status: upstream.status,\n statusText: upstream.statusText,\n headers: upstream.headers,\n })\n } catch (error) {\n return Response.json(\n { error: error instanceof Error ? error.message : 'internal relay error' },\n { status: 502 },\n )\n }\n },\n}\n";
91
107
  export {};
@@ -17,5 +17,11 @@ export declare function reportSessionCacheTouch(sessionId: string, input: CacheT
17
17
  export declare function reportSessionCacheWarmStopped(sessionId: string, input: CacheWarmStoppedInput): boolean;
18
18
  /** Apply only a lifetime override; the host still chooses breakpoint placement. */
19
19
  export declare function applySessionCacheTtl(body: Record<string, unknown>, ttl: SessionCacheTtl | undefined): void;
20
- /** The longest sent cache lifetime bounds when every cached prefix is gone. */
20
+ /**
21
+ * Cache-touch reports and our local activity, hold and keep-warm timing use the
22
+ * longest sent lifetime: the cache is fully cold only after every prefix expires.
23
+ * Billing reports use requestShortestCacheLifetimeMs instead.
24
+ */
21
25
  export declare function requestCacheLifetimeMs(input: Record<string, unknown> | string): number;
26
+ /** Billing reports use the shortest sent lifetime among the cache breakpoints. */
27
+ export declare function requestShortestCacheLifetimeMs(input: Record<string, unknown> | string): number;
@@ -443,8 +443,33 @@ export declare const settingsDefinition: import("./internal-types/settings/index
443
443
  };
444
444
  readonly default: readonly ["board", "ctx_reduce"];
445
445
  };
446
+ readonly gateway_url: {
447
+ readonly hosts: 'both';
448
+ readonly project: 'user-only';
449
+ readonly value: Readonly<{
450
+ readonly kind: 'string';
451
+ }>;
452
+ readonly default: "";
453
+ };
454
+ readonly gateway_headers: {
455
+ readonly hosts: 'both';
456
+ readonly project: 'user-only';
457
+ readonly value: {
458
+ readonly kind: 'record';
459
+ readonly value: Readonly<{
460
+ readonly kind: 'string';
461
+ }>;
462
+ };
463
+ readonly default: {};
464
+ };
446
465
  }>;
447
466
  export type SettingsKey = keyof typeof settingsDefinition.settings;
467
+ /**
468
+ * Settings that exist only in the user settings file: no legacy store holds
469
+ * them, so the one-time move never reads or writes them, and the `/claude`
470
+ * menu never writes them.
471
+ */
472
+ export declare const SETTINGS_FILE_ONLY_KEYS: readonly ["gateway_url", "gateway_headers"];
448
473
  /** Empty: no Pi-specific default is needed beyond per-reader default/on/off handling. */
449
474
  export declare const SETTINGS_PI_DIFFERING_FIELDS: readonly [];
450
475
  /** Names the current readers whose absence behavior determines each schema default. */
@@ -482,6 +507,8 @@ export declare const SETTINGS_DEFAULT_READERS: {
482
507
  readonly log_level: 'packages/core/src/accounts.ts:getPersistedLogLevel';
483
508
  readonly thinking_binding_prefix_mismatch_behavior: 'packages/core/src/thinking-binding.ts:getThinkingPrefixMismatchBehavior';
484
509
  readonly turn_end_note_tools: 'packages/core/src/turn-end-note.ts:applyTurnEndNotes';
510
+ readonly gateway_url: 'packages/core/src/native-runtime-settings.ts:gateway';
511
+ readonly gateway_headers: 'packages/core/src/native-runtime-settings.ts:gateway';
485
512
  };
486
513
  /** These enum members defer to the existing environment/account inference. */
487
514
  export declare const SETTINGS_INFERRED_FIELDS: readonly ["log_level", "thinking_binding_prefix_mismatch_behavior"];
@@ -1,7 +1,10 @@
1
1
  import type { MoveSource } from "./internal-types/settings/index.js";
2
2
  import type { SettingsHost } from './settings-paths.ts';
3
3
  import { type SettingsValues } from './settings-service.ts';
4
- /** Legacy paths by schema key; cache_keep_window combines the two named sibling hours. */
4
+ /**
5
+ * Legacy paths by schema key; cache_keep_window combines the two named
6
+ * sibling hours. File-only settings have no legacy path.
7
+ */
5
8
  export declare const SETTINGS_MOVE_PATHS: {
6
9
  readonly routing_mode: readonly ["routing", "mode"];
7
10
  readonly max_same_account_wait: readonly ["routing", "maxSameAccountWait"];
@@ -1,4 +1,5 @@
1
1
  import { type OpenSettingsOptions, type ReportEntry, type SettingsEdit, type SettingsHandle, type UpdateResult, type ValueOf } from "./internal-types/settings/index.js";
2
+ import { type ClaudeGatewayIgnored } from './gateway.ts';
2
3
  import { type SettingsKey, settingsDefinition } from './settings-definition.ts';
3
4
  import type { SettingsHost } from './settings-paths.ts';
4
5
  import { writeSettingsProtectionCopy } from './settings-protection-copy.ts';
@@ -6,6 +7,12 @@ export type SettingsValues = {
6
7
  [K in SettingsKey]: ValueOf<(typeof settingsDefinition.settings)[K]['value']>;
7
8
  };
8
9
  export declare const SETTINGS_PROTECTION_KEYS: readonly ["max_same_account_wait", "quota_minimum_remaining_five_hour", "quota_minimum_remaining_seven_day", "quota_minimum_remaining_scoped", "quota_fail_closed_on_unknown_quota", "killswitch_enabled", "killswitch_default_five_hour", "killswitch_default_seven_day", "killswitch_default_scoped", "killswitch_account_floors"];
10
+ /**
11
+ * The gateway settings are validated together. Any problem with either one
12
+ * means no gateway at all: model requests go directly to api.anthropic.com,
13
+ * never to a last-good or partly valid gateway.
14
+ */
15
+ export declare const SETTINGS_GATEWAY_KEYS: readonly ["gateway_url", "gateway_headers"];
9
16
  export type SettingsProtectionValues = Pick<SettingsValues, (typeof SETTINGS_PROTECTION_KEYS)[number]>;
10
17
  export type SettingsProtectionRung = 0 | 1 | 2 | 3;
11
18
  export declare class SettingsRecreationRefusal extends Error {
@@ -63,6 +70,12 @@ export interface SettingsFileStatus {
63
70
  model: string;
64
71
  }[];
65
72
  readonly duplicateKeys: readonly string[];
73
+ /**
74
+ * Set when the file names a gateway that is not used: the file is not the
75
+ * default settings file of the operating system account, or that
76
+ * account's home folder could not be found.
77
+ */
78
+ readonly gatewayIgnored?: ClaudeGatewayIgnored;
66
79
  }
67
80
  export interface SettingsGeneration {
68
81
  readonly id: number;
@@ -76,6 +89,8 @@ export interface SettingsGeneration {
76
89
  readonly contexts: Readonly<Record<SettingsHost, SettingsContextValues>>;
77
90
  readonly report: readonly ReportEntry[];
78
91
  readonly fileStatus: SettingsFileStatus;
92
+ /** See SettingsFileStatus.gatewayIgnored. */
93
+ readonly gatewayIgnored?: ClaudeGatewayIgnored;
79
94
  /** Recover an unusable set as a whole from last-good values or startup recovery, never per key. */
80
95
  readonly protection: Readonly<Record<SettingsHost, {
81
96
  readonly usable: boolean;
@@ -136,6 +151,8 @@ export interface SettingsServiceOptions {
136
151
  writeAppliedCopy?: typeof writeSettingsProtectionCopy;
137
152
  /** Schedule an off-request re-read; return a cancellation function. */
138
153
  schedule?: (callback: () => void, delayMs: number) => () => void;
154
+ /** Test seam: the file the gateway is honoured from (gatewaySettingsFile). */
155
+ gatewaySettingsFile?: () => string | undefined | Promise<string | undefined>;
139
156
  };
140
157
  }
141
158
  /** The levels at which a parsed settings document sets each key; values and their validity remain common-auth's responsibility. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/anthropic-auth-core",
3
- "version": "2.12.0",
3
+ "version": "2.13.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -31,7 +31,7 @@
31
31
  "prepublishOnly": "bun run build"
32
32
  },
33
33
  "devDependencies": {
34
- "@cortexkit/common-auth": "0.49.2"
34
+ "@cortexkit/common-auth": "0.50.0"
35
35
  },
36
36
  "dependencies": {
37
37
  "@cortexkit/claustrum-client": "0.18.0",
@@ -1075,6 +1075,15 @@
1075
1075
  "additionalProperties": false
1076
1076
  }
1077
1077
  ]
1078
+ },
1079
+ "gateway_url": {
1080
+ "type": "string"
1081
+ },
1082
+ "gateway_headers": {
1083
+ "type": "object",
1084
+ "additionalProperties": {
1085
+ "type": "string"
1086
+ }
1078
1087
  }
1079
1088
  },
1080
1089
  "additionalProperties": false