@cortexkit/anthropic-auth-core 2.11.4 → 2.13.0
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/dist/cachekeep.d.ts +5 -0
- package/dist/custom-headers.d.ts +9 -0
- package/dist/gateway.d.ts +188 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +16419 -15061
- package/dist/internal-types/fs/canonical-file-path.d.ts +17 -0
- package/dist/internal-types/fs/index.d.ts +1 -0
- package/dist/internal-types/settings/edit.d.ts +1 -0
- package/dist/internal-types/settings/handle.d.ts +2 -1
- package/dist/internal-types/settings/index.d.ts +1 -0
- package/dist/internal-types/settings/update.d.ts +14 -0
- package/dist/native-account-runtime.d.ts +21 -0
- package/dist/native-runtime-settings.d.ts +25 -6
- package/dist/native-runtime.d.ts +2 -2
- package/dist/native-settings-write.d.ts +4 -16
- package/dist/oauth-origin.d.ts +47 -4
- package/dist/pool-store.d.ts +7 -0
- package/dist/relay-location.d.ts +109 -0
- package/dist/relay.d.ts +18 -2
- package/dist/settings-definition.d.ts +38 -0
- package/dist/settings-host-import.d.ts +18 -4
- package/dist/settings-mode.d.ts +22 -0
- package/dist/settings-move-run.d.ts +60 -1
- package/dist/settings-move-source.d.ts +4 -1
- package/dist/settings-move-sources.d.ts +15 -6
- package/dist/settings-protection-copy.d.ts +7 -1
- package/dist/settings-service.d.ts +81 -37
- package/dist/settings-start.d.ts +46 -6
- package/package.json +2 -2
- package/schema/anthropic-auth.schema.json +9 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type * as syncFs from 'node:fs';
|
|
2
|
+
import type * as fs from 'node:fs/promises';
|
|
3
|
+
type FilePathFs = Pick<typeof fs, 'lstat' | 'readlink' | 'realpath'>;
|
|
4
|
+
type FilePathSyncFs = Pick<typeof syncFs, 'lstatSync' | 'readlinkSync' | 'realpathSync'>;
|
|
5
|
+
/**
|
|
6
|
+
* Canonical path of a file that other processes may replace by write-and-rename.
|
|
7
|
+
*
|
|
8
|
+
* On Linux, Bun's realpath on such a file can answer "<file> (deleted)" (Bun
|
|
9
|
+
* 1.3) or ENOENT (Bun 1.4) during the rename. So this resolves the folder with
|
|
10
|
+
* realpath and appends the name, then follows a file symlink one readlink hop at
|
|
11
|
+
* a time, at most 40 hops. A missing file resolves to its would-be path; a
|
|
12
|
+
* dangling link or a loop throws. Pass `node:fs/promises` (or a test double).
|
|
13
|
+
*/
|
|
14
|
+
export declare function canonicalFilePath(file: string, fs: FilePathFs): Promise<string>;
|
|
15
|
+
/** Synchronous counterpart of canonicalFilePath; pass `node:fs`. */
|
|
16
|
+
export declare function canonicalFilePathSync(file: string, fs: FilePathSyncFs): string;
|
|
17
|
+
export {};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export type { AtomicWriteOptions } from './atomic-write.js';
|
|
2
2
|
export { writeJsonAtomic } from './atomic-write.js';
|
|
3
|
+
export { canonicalFilePath, canonicalFilePathSync, } from './canonical-file-path.js';
|
|
3
4
|
export { WRITER_LOCK_CONSTANTS } from './lock-constants.js';
|
|
4
5
|
export type { PrivateWriteOutcome } from './private-files.js';
|
|
5
6
|
export { PrivateFileError } from './private-files.js';
|
|
@@ -4,6 +4,7 @@ import { type ValueOf } from './descriptors.js';
|
|
|
4
4
|
import type { SettingsEdit, UpdateResult } from './edit.js';
|
|
5
5
|
import { type GetOptions } from './resolve.js';
|
|
6
6
|
import { type ReportEntry } from './snapshot.js';
|
|
7
|
+
import { type SettingsUpdatePlan } from './update.js';
|
|
7
8
|
export interface LegacyProjectSource {
|
|
8
9
|
readonly path: string;
|
|
9
10
|
read(text: string): unknown;
|
|
@@ -22,7 +23,7 @@ export interface SettingsHandle<S extends Readonly<Record<string, SettingDeclara
|
|
|
22
23
|
}): Promise<void>;
|
|
23
24
|
get<K extends keyof S & string>(name: K, options: GetOptions): Promise<ValueOf<S[K]['value']>>;
|
|
24
25
|
report(): ReportEntry[];
|
|
25
|
-
update(edits: readonly SettingsEdit[], options: Pick<GetOptions, 'host' | 'model'>): Promise<UpdateResult>;
|
|
26
|
+
update(edits: readonly SettingsEdit[] | SettingsUpdatePlan, options: Pick<GetOptions, 'host' | 'model'>): Promise<UpdateResult>;
|
|
26
27
|
watch(onChange: () => void): () => void;
|
|
27
28
|
}
|
|
28
29
|
/** Internal test hook; not part of the settings package exports. */
|
|
@@ -8,3 +8,4 @@ export { SETTINGS_REFUSAL_CODES, SettingsRefusal, type SettingsRefusalCode, } fr
|
|
|
8
8
|
export type { GetOptions } from './resolve.js';
|
|
9
9
|
export { settingsJsonSchema } from './schema.js';
|
|
10
10
|
export type { ReportEntry, ReportReason } from './snapshot.js';
|
|
11
|
+
export type { SettingsCurrent, SettingsUpdatePlan } from './update.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { SettingsDefinition } from './define.js';
|
|
2
|
+
import { type SettingsEdit, type UpdateResult } from './edit.js';
|
|
3
|
+
import type { OpenSettingsOptions } from './handle.js';
|
|
4
|
+
import type { GetOptions } from './resolve.js';
|
|
5
|
+
export type SettingsCurrent = {
|
|
6
|
+
readonly status: 'missing';
|
|
7
|
+
} | {
|
|
8
|
+
readonly status: 'ready';
|
|
9
|
+
readonly document: Readonly<Record<string, unknown>>;
|
|
10
|
+
};
|
|
11
|
+
/** Compute edits synchronously from an immutable copy read under the write lock. */
|
|
12
|
+
export type SettingsUpdatePlan = (current: SettingsCurrent) => readonly SettingsEdit[];
|
|
13
|
+
/** Lock the canonical user file so symlink aliases serialize the same edits. */
|
|
14
|
+
export declare function updateSettings(definition: SettingsDefinition, options: OpenSettingsOptions, edits: readonly SettingsEdit[] | SettingsUpdatePlan, context: Pick<GetOptions, 'host' | 'model'>): Promise<UpdateResult>;
|
|
@@ -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,10 +1,10 @@
|
|
|
1
|
-
import type { SettingsEdit } from "./internal-types/settings/index.js";
|
|
2
1
|
import type { AccountStorage } from './accounts.ts';
|
|
2
|
+
import { type ClaudeGateway, type ClaudeGatewayStatus } from './gateway.ts';
|
|
3
3
|
import { type SettingsKey } from './settings-definition.ts';
|
|
4
4
|
import { type SettingsMode, type SettingsModeOptions } from './settings-mode.ts';
|
|
5
5
|
import type { SettingsHost } from './settings-paths.ts';
|
|
6
|
-
import type
|
|
7
|
-
import type { SettingsProtectionFallback } from './settings-start.ts';
|
|
6
|
+
import { type SettingsFileStatus, type SettingsService, type SettingsUpdate, type SettingsValues } from './settings-service.ts';
|
|
7
|
+
import type { SettingsProtectionFallback, SettingsReopen } from './settings-start.ts';
|
|
8
8
|
export interface NativeRuntimeSettingsOptions {
|
|
9
9
|
settingsService?: SettingsService;
|
|
10
10
|
/** Return the cached settings mode; this callback must not read the filesystem. */
|
|
@@ -26,11 +26,17 @@ export interface NativeRuntimeSettingsOptions {
|
|
|
26
26
|
* authority timer and menu actions open it again off the request path, so a
|
|
27
27
|
* move another host publishes later is still noticed.
|
|
28
28
|
*/
|
|
29
|
-
settingsReopen?:
|
|
29
|
+
settingsReopen?: SettingsReopen;
|
|
30
30
|
}
|
|
31
31
|
export interface NativeRuntimeSettingsStatus {
|
|
32
32
|
file: SettingsFileStatus;
|
|
33
|
-
|
|
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
|
+
};
|
|
34
40
|
modelOverrides: Partial<Record<SettingsKey, {
|
|
35
41
|
model: string;
|
|
36
42
|
value: SettingsValues[SettingsKey];
|
|
@@ -50,11 +56,24 @@ export declare function createNativeRuntimeSettings(options: NativeRuntimeSettin
|
|
|
50
56
|
(stored: Record<string, unknown>, model?: string): Record<string, unknown>;
|
|
51
57
|
};
|
|
52
58
|
status: () => NativeRuntimeSettingsStatus | undefined;
|
|
59
|
+
gateway: () => ClaudeGateway | undefined;
|
|
53
60
|
applyEffects: () => void;
|
|
54
61
|
file: () => string | undefined;
|
|
55
62
|
prepareAction(): Promise<void>;
|
|
56
63
|
/** The settings file while the protection fallback is in use, else undefined. */
|
|
57
64
|
fallbackFile: () => string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* The settings file while it is open but this host does not use it yet
|
|
67
|
+
* (its import check has not passed), else undefined.
|
|
68
|
+
*/
|
|
69
|
+
checkingFile: () => string | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Why a menu write is refused while `checkingFile` is set. A file that
|
|
72
|
+
* can't be used stays held until the user fixes it, so the text names its
|
|
73
|
+
* problem; any other hold (the check running, a busy lock, an unreadable
|
|
74
|
+
* legacy store) clears by itself.
|
|
75
|
+
*/
|
|
76
|
+
checkingRefusal(): string;
|
|
58
77
|
/**
|
|
59
78
|
* Called under the legacy store's locks by a write that chose the legacy
|
|
60
79
|
* store: true when the user file became authoritative meanwhile (a move
|
|
@@ -67,6 +86,6 @@ export declare function createNativeRuntimeSettings(options: NativeRuntimeSettin
|
|
|
67
86
|
/** Recheck authority on the menu path before choosing a write target. */
|
|
68
87
|
prepareWrite(): Promise<SettingsService | undefined>;
|
|
69
88
|
legacyWriteCommitted(source: string, stored: Record<string, unknown>): Promise<void>;
|
|
70
|
-
update(edits:
|
|
89
|
+
update(edits: SettingsUpdate, before: Record<string, unknown>): Promise<void>;
|
|
71
90
|
close: () => Promise<void>;
|
|
72
91
|
};
|
package/dist/native-runtime.d.ts
CHANGED
|
@@ -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,6 +1,6 @@
|
|
|
1
1
|
import type { SettingsEdit } from "./internal-types/settings/index.js";
|
|
2
2
|
import type { SettingsHost } from './settings-paths.ts';
|
|
3
|
-
import { type SettingsGeneration, type SettingsValues } from './settings-service.ts';
|
|
3
|
+
import { type SettingsGeneration, type SettingsUpdatePlan, type SettingsValues } from './settings-service.ts';
|
|
4
4
|
type Settings = Record<string, unknown>;
|
|
5
5
|
interface StoreChange {
|
|
6
6
|
path: string[];
|
|
@@ -11,16 +11,7 @@ export declare function planNativeSettingsWrite(before: Settings, after: Setting
|
|
|
11
11
|
edits: SettingsEdit[];
|
|
12
12
|
storeChanges: StoreChange[];
|
|
13
13
|
refusal: string | undefined;
|
|
14
|
-
|
|
15
|
-
* What a floor-list edit was planned from: the file text, or a missing
|
|
16
|
-
* file. The write is refused as busy if the file is no longer that.
|
|
17
|
-
*/
|
|
18
|
-
floorsFrom: {
|
|
19
|
-
status: 'missing';
|
|
20
|
-
} | {
|
|
21
|
-
status: 'ready';
|
|
22
|
-
source: string;
|
|
23
|
-
} | undefined;
|
|
14
|
+
update: SettingsUpdatePlan | undefined;
|
|
24
15
|
};
|
|
25
16
|
/**
|
|
26
17
|
* The acting host's floor-list edit, as a pure function of the file it
|
|
@@ -29,11 +20,8 @@ export declare function planNativeSettingsWrite(before: Settings, after: Setting
|
|
|
29
20
|
* accounts change; a `both` entry for such an account is split first so the
|
|
30
21
|
* other host keeps its floor. Returns undefined when the list is unchanged.
|
|
31
22
|
*
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* since (see `SettingsUpdateOptions.expectedSource`); that leaves a small
|
|
35
|
-
* window before the lock. common-auth 0.49's planned update will pass this
|
|
36
|
-
* function the document read under the lock, closing it.
|
|
23
|
+
* The caller passes the document read under the settings writer lock, so
|
|
24
|
+
* concurrent writers retain each other's entries.
|
|
37
25
|
*/
|
|
38
26
|
export declare function planSettingsAccountFloors(current: {
|
|
39
27
|
status: 'missing';
|
package/dist/oauth-origin.d.ts
CHANGED
|
@@ -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
|
|
40
|
-
* user name or password in the URL. Throws
|
|
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
|
|
68
|
+
* requireAnthropicOAuthOrigin before dispatch, always sets
|
|
46
69
|
* `redirect: 'error'`, so an approved destination cannot forward the token
|
|
47
|
-
* elsewhere with a redirect
|
|
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;
|
package/dist/pool-store.d.ts
CHANGED
|
@@ -38,3 +38,10 @@ export declare function drainNativePoolStores(statePaths: readonly string[]): Pr
|
|
|
38
38
|
* authority or vault enrollment authority before using these files.
|
|
39
39
|
*/
|
|
40
40
|
export declare function createNativePoolStore(options: NativePoolStoreOptions): import("./internal-types/store/index.js").PoolStore;
|
|
41
|
+
/**
|
|
42
|
+
* Reads the plugin settings from exactly the config file at `configPath`, for
|
|
43
|
+
* a caller that resolved that file itself and must not read through another
|
|
44
|
+
* path's text. Nothing is ever written or locked through the store opened for
|
|
45
|
+
* it, so its state path is never used and is set to the config path.
|
|
46
|
+
*/
|
|
47
|
+
export declare function readNativePoolSettingsAt(configPath: string, quota: NativeQuotaCodec): Promise<import("./internal-types/store/index.js").SettingsRead>;
|
|
@@ -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
|
-
|
|
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 {};
|
|
@@ -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"];
|
|
@@ -596,6 +623,17 @@ export declare function malformedSettingsText(file: string): string;
|
|
|
596
623
|
export declare function refusedSettingsWriteText(key: SettingsKey, file: string): string;
|
|
597
624
|
export declare function refusedSettingsRecreationText(file: string): string;
|
|
598
625
|
export declare function invalidSettingsWriteText(key: SettingsKey, file: string): string;
|
|
626
|
+
/**
|
|
627
|
+
* A menu write while this host still checks the settings file against its
|
|
628
|
+
* legacy settings before using it: neither source can take the write yet.
|
|
629
|
+
*/
|
|
630
|
+
export declare function settingsCheckPendingText(file?: string): string;
|
|
631
|
+
/**
|
|
632
|
+
* A menu write while this host can't use the settings file until the user
|
|
633
|
+
* fixes it. `problem` says what is wrong in plain words, such as "is empty";
|
|
634
|
+
* it never quotes a value from the file.
|
|
635
|
+
*/
|
|
636
|
+
export declare function settingsFileUnusableText(problem: string, file?: string): string;
|
|
599
637
|
/** Only fixed, local text is shown; dependency errors can contain file contents. */
|
|
600
638
|
export declare const SETTINGS_WRITE_FAILURES: {
|
|
601
639
|
readonly 'settings-unparseable': {
|
|
@@ -1,17 +1,31 @@
|
|
|
1
1
|
import type { SettingsHost } from './settings-paths.ts';
|
|
2
2
|
import { SETTINGS_PROTECTION_KEYS, type SettingsFileLevels, type SettingsLevelEdit, type SettingsProtectionValues } from './settings-service.ts';
|
|
3
3
|
type ProtectionKey = (typeof SETTINGS_PROTECTION_KEYS)[number];
|
|
4
|
+
/**
|
|
5
|
+
* The killswitch's default floors. They hold accounts back only while the
|
|
6
|
+
* killswitch is on, so a host whose legacy killswitch was off contributes
|
|
7
|
+
* none of them.
|
|
8
|
+
*/
|
|
9
|
+
export declare const KILLSWITCH_FLOOR_KEYS: ReadonlySet<string>;
|
|
10
|
+
/**
|
|
11
|
+
* True when `legacy` protects more than `file` for one scalar protection key.
|
|
12
|
+
* Both sides are effective values: an unset legacy key counts as the value
|
|
13
|
+
* its legacy reader returns (the killswitch floors 5/10/0, `default` for the
|
|
14
|
+
* unknown-quota policy, `15m` for the same-account wait), never as absent.
|
|
15
|
+
*/
|
|
16
|
+
export declare function settingsProtectionStricter(key: ProtectionKey, legacy: unknown, file: unknown): boolean;
|
|
4
17
|
/**
|
|
5
18
|
* The import a host owes the settings file when its legacy store was never
|
|
6
19
|
* imported: for each protection key the file sets for this host no value of
|
|
7
20
|
* its own (fill-only), the host's legacy value where it protects more than
|
|
8
|
-
* what the host now resolves from the file.
|
|
21
|
+
* what the host now resolves from the file. Killswitch floors count only
|
|
22
|
+
* when the host's legacy killswitch was on. A pure function of the host's
|
|
9
23
|
* legacy set, its resolved set and the file's explicit levels.
|
|
10
24
|
*
|
|
11
25
|
* `edits` writes those values at the host's own level; account floors need
|
|
12
|
-
* no level, since each list entry names its host.
|
|
13
|
-
*
|
|
14
|
-
*
|
|
26
|
+
* no level, since each list entry names its host. The caller verifies that
|
|
27
|
+
* the validated protection fields still match the document under the lock
|
|
28
|
+
* before returning these edits from its writer plan.
|
|
15
29
|
*/
|
|
16
30
|
export declare function planSettingsHostImport(input: {
|
|
17
31
|
host: SettingsHost;
|