@khorsheed/dsh-local-agent-claude-code 0.2.0-rc.1 → 0.2.0-rc.3

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.
@@ -8,18 +8,24 @@ export declare const zh: {
8
8
  'card.expand': string;
9
9
  'card.collapse': string;
10
10
  'auth.title': string;
11
- 'model.title': string;
12
- 'model.info.aria': string;
13
- 'model.info': string;
14
- 'model.placeholder': string;
15
- 'model.menu': string;
16
- 'model.menuDefault': string;
17
- 'model.menuDefaultCliConfig': string;
18
- 'model.menuDefaultCliBuiltin': string;
19
- 'model.menuDefaultLastObserved': string;
20
- 'model.save': string;
21
- 'model.applied': string;
22
- 'model.error': string;
11
+ 'endpoint.info.aria': string;
12
+ 'endpoint.info': string;
13
+ 'endpoint.baseUrl': string;
14
+ 'endpoint.baseUrl.placeholder': string;
15
+ 'endpoint.apiKey': string;
16
+ 'endpoint.authToken': string;
17
+ 'endpoint.secret.configured': string;
18
+ 'endpoint.secret.placeholder': string;
19
+ 'endpoint.configured': string;
20
+ 'endpoint.save': string;
21
+ 'endpoint.applied': string;
22
+ 'endpoint.error': string;
23
+ 'endpoint.check': string;
24
+ 'endpoint.checking': string;
25
+ 'endpoint.checkDirtyHint': string;
26
+ 'endpoint.checkUnavailable': string;
27
+ 'endpoint.unavailable': string;
28
+ 'endpoint.checkFailed': string;
23
29
  'live.title': string;
24
30
  'live.info.aria': string;
25
31
  'live.info': string;
@@ -42,18 +48,24 @@ export declare const en: {
42
48
  'card.expand': string;
43
49
  'card.collapse': string;
44
50
  'auth.title': string;
45
- 'model.title': string;
46
- 'model.info.aria': string;
47
- 'model.info': string;
48
- 'model.placeholder': string;
49
- 'model.menu': string;
50
- 'model.menuDefault': string;
51
- 'model.menuDefaultCliConfig': string;
52
- 'model.menuDefaultCliBuiltin': string;
53
- 'model.menuDefaultLastObserved': string;
54
- 'model.save': string;
55
- 'model.applied': string;
56
- 'model.error': string;
51
+ 'endpoint.info.aria': string;
52
+ 'endpoint.info': string;
53
+ 'endpoint.baseUrl': string;
54
+ 'endpoint.baseUrl.placeholder': string;
55
+ 'endpoint.apiKey': string;
56
+ 'endpoint.authToken': string;
57
+ 'endpoint.secret.configured': string;
58
+ 'endpoint.secret.placeholder': string;
59
+ 'endpoint.configured': string;
60
+ 'endpoint.save': string;
61
+ 'endpoint.applied': string;
62
+ 'endpoint.error': string;
63
+ 'endpoint.check': string;
64
+ 'endpoint.checking': string;
65
+ 'endpoint.checkDirtyHint': string;
66
+ 'endpoint.checkUnavailable': string;
67
+ 'endpoint.unavailable': string;
68
+ 'endpoint.checkFailed': string;
57
69
  'live.title': string;
58
70
  'live.info.aria': string;
59
71
  'live.info': string;
@@ -3,23 +3,29 @@
3
3
  export const NS = 'local-agent-claude-code';
4
4
  /** Simplified Chinese dictionary (the key-set source of truth). */
5
5
  export const zh = {
6
- 'card.title': 'Local Agent · Claude Code',
7
- 'card.description': 'Claude Code 委派:登录授权与常驻模式(live)',
6
+ 'card.title': '本机 Claude Code 委派',
7
+ 'card.description': '使用本机安装的 Claude Code CLI 委派:端点凭据与常驻模式(live)',
8
8
  'card.expand': '展开',
9
9
  'card.collapse': '收起',
10
10
  'auth.title': '认证',
11
- 'model.title': '默认模型',
12
- 'model.info.aria': '默认模型说明',
13
- 'model.info': '留空 = 跟随默认(输入框里显示的就是当前跟随的模型)。从列表选择或手动输入一个模型名后保存,之后的每轮委派都以它起 CLI(`claude -p --model <模型>`,常驻模式同一个旗标)。成员会话里还可用作曲器按会话切换,不影响这里的默认。改动在下一轮委派生效,进行中的轮次不受影响;评测 run 的条件在建立时冻结,中途换模型会被下一轮的模型回读判为 misattributed 而拦下。',
14
- 'model.placeholder': '留空 = 不传模型,用 CLI 自己的默认',
15
- 'model.menu': '选择模型',
16
- 'model.menuDefault': '默认(跟随 CLI 内置默认)',
17
- 'model.menuDefaultCliConfig': '默认(跟随 CLI 配置:{model})',
18
- 'model.menuDefaultCliBuiltin': '默认(跟随 CLI 默认:{model})',
19
- 'model.menuDefaultLastObserved': '默认(跟随 CLI 内置默认(最近:{model}))',
20
- 'model.save': '保存',
21
- 'model.applied': '已保存,下一轮委派生效;进行中的轮次不受影响',
22
- 'model.error': '保存失败,请重试',
11
+ 'endpoint.info.aria': '端点凭据说明',
12
+ 'endpoint.info': '这里保存的就是默认 scope 的 endpoint-auth.json(0600,只存本机),它优先于 profile 的 YAML 配置行;宿主 shell 的环境变量从不被读取。端点留空 = Anthropic 官方端点;API Key 与 Auth Token 至少填一个(分别对应 x-api-key 与 Bearer 头,看你的中转认哪种)。密钥绝不写进 profile 文件,也不进入评测条件指纹。保存对下一轮委派生效,进行中的轮次不受影响。',
13
+ 'endpoint.baseUrl': '端点地址(baseUrl)',
14
+ 'endpoint.baseUrl.placeholder': '留空 = Anthropic 官方端点',
15
+ 'endpoint.apiKey': 'API Key',
16
+ 'endpoint.authToken': 'Auth Token',
17
+ 'endpoint.secret.configured': '已配置 · 输入新值更换,留空保存 = 清除',
18
+ 'endpoint.secret.placeholder': '未配置',
19
+ 'endpoint.configured': '已配置',
20
+ 'endpoint.save': '保存凭据',
21
+ 'endpoint.applied': '已保存,下一轮委派生效;进行中的轮次不受影响',
22
+ 'endpoint.error': '保存失败,请重试',
23
+ 'endpoint.check': '验证端点并获取模型',
24
+ 'endpoint.checking': '验证中…',
25
+ 'endpoint.checkDirtyHint': '有未保存的修改,先保存凭据再验证',
26
+ 'endpoint.checkUnavailable': '当前核心不支持端点验证(请升级 local-agent 核心包)',
27
+ 'endpoint.unavailable': '当前核心不支持凭据配置(请升级 local-agent 核心包)',
28
+ 'endpoint.checkFailed': '验证失败,请重试',
23
29
  'live.title': '常驻模式(live)',
24
30
  'live.info.aria': '常驻模式说明',
25
31
  'live.info': '常驻模式 = 成员进程常驻:输出实时流入成员会话、取消不杀进程、崩溃后自动续上原会话;关闭则每轮独立进程,跑完一次性出结果。设置为全局偏好,对所有后续委派生效。',
@@ -29,23 +35,29 @@ export const zh = {
29
35
  };
30
36
  /** English dictionary, checked complete against the zh key set. */
31
37
  export const en = {
32
- 'card.title': 'Local Agent · Claude Code',
33
- 'card.description': 'Claude Code delegation: sign-in and resident (live) mode',
38
+ 'card.title': 'Local Claude Code Delegation',
39
+ 'card.description': "Delegate through this machine's Claude Code CLI: endpoint credential and resident (live) mode",
34
40
  'card.expand': 'Expand',
35
41
  'card.collapse': 'Collapse',
36
42
  'auth.title': 'Authentication',
37
- 'model.title': 'Default model',
38
- 'model.info.aria': 'About the default model',
39
- 'model.info': "Blank = follow the default (the input shows the model it currently follows). Pick from the list or type a model name by hand and save, and every later delegation round starts the CLI with it (`claude -p --model <model>`, the same flag in resident mode). Inside a member session the composer can also switch the model per session, without touching this default. A change applies to the next round and never disturbs a round in flight; an evaluation run freezes its condition at setup, so switching mid-run is caught by the model read-back on the next round and fails the run as misattributed.",
40
- 'model.placeholder': "Blank = pass no model, keep the CLI's own default",
41
- 'model.menu': 'Pick a model',
42
- 'model.menuDefault': "Default (follow the CLI's built-in default)",
43
- 'model.menuDefaultCliConfig': 'Default (follow the CLI config: {model})',
44
- 'model.menuDefaultCliBuiltin': 'Default (follow the CLI default: {model})',
45
- 'model.menuDefaultLastObserved': "Default (follow the CLI's built-in default (last: {model}))",
46
- 'model.save': 'Save',
47
- 'model.applied': 'Saved — takes effect on the next delegation round; rounds in flight are unaffected',
48
- 'model.error': 'Save failed, please retry',
43
+ 'endpoint.info.aria': 'About the endpoint credential',
44
+ 'endpoint.info': "What you save here is the default scope's endpoint-auth.json (mode 0600, local only), which outranks the profile's YAML row; the host shell's environment is never read. A blank endpoint means Anthropic's own; fill at least one of API Key and Auth Token (x-api-key and Bearer respectively — whichever your relay accepts). Keys never enter the profile document or an evaluation's condition fingerprint. Saving applies to the next delegation round; rounds in flight are unaffected.",
45
+ 'endpoint.baseUrl': 'Endpoint (baseUrl)',
46
+ 'endpoint.baseUrl.placeholder': "Blank = Anthropic's own endpoint",
47
+ 'endpoint.apiKey': 'API Key',
48
+ 'endpoint.authToken': 'Auth Token',
49
+ 'endpoint.secret.configured': 'Configured · type to replace, save blank to clear',
50
+ 'endpoint.secret.placeholder': 'Not configured',
51
+ 'endpoint.configured': 'Configured',
52
+ 'endpoint.save': 'Save credential',
53
+ 'endpoint.applied': 'Saved — takes effect on the next delegation round; rounds in flight are unaffected',
54
+ 'endpoint.error': 'Save failed, please retry',
55
+ 'endpoint.check': 'Verify endpoint & fetch models',
56
+ 'endpoint.checking': 'Checking…',
57
+ 'endpoint.checkDirtyHint': 'Unsaved changes — save the credential first',
58
+ 'endpoint.checkUnavailable': 'Endpoint verification is not supported by this core (upgrade the local-agent core)',
59
+ 'endpoint.unavailable': 'Credential configuration is not supported by this core (upgrade the local-agent core)',
60
+ 'endpoint.checkFailed': 'Check failed, please retry',
49
61
  'live.title': 'Resident mode (live)',
50
62
  'live.info.aria': 'About resident mode',
51
63
  'live.info': 'Resident mode keeps the member process alive: output streams into the member session in real time, cancelling does not kill the process, and a crash resumes the same session. Off means every round runs as an independent one-shot process. The setting is global and applies to every later delegation.',
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Endpoint-key authentication — the claude-code harness's ONLY auth mode.
3
+ * There is no OAuth anywhere in this package: a delegation round reaches its
4
+ * endpoint with `ANTHROPIC_BASE_URL` plus `ANTHROPIC_API_KEY` (x-api-key) or
5
+ * `ANTHROPIC_AUTH_TOKEN` (Authorization: Bearer), exactly the environment a
6
+ * shell would export for a proxy relay, and `claude -p` needs nothing else
7
+ * (verified against claude 2.1.296: a fresh scoped home with only these
8
+ * variables runs a round and scaffolds `.claude.json` itself — no onboarding
9
+ * or key-approval gate in headless mode).
10
+ *
11
+ * Two layers, merged per field, file over config:
12
+ *
13
+ * - `<scopedHome>/endpoint-auth.json` (mode 0600) — the per-scope credential.
14
+ * Its name deliberately matches the eval contract hash's credential denylist
15
+ * (`auth`), so the key material never enters an evaluation's condition
16
+ * fingerprint; the file's mtime serves as the credential stamp, which makes
17
+ * "edit the file" the recovery gesture for a `rejected` grade.
18
+ * - The plugin config's `baseUrl` / `apiKey` / `authToken` — the deployment
19
+ * default every scope without a file shares. Read PER ROUND from the
20
+ * apply-time snapshot, so a profile edit applies to the next round (and a
21
+ * host restart clears the in-memory `rejected` mark).
22
+ *
23
+ * The env layer this module emits rides the family's existing plumbing:
24
+ * `delegationEnv` on the host, and `containerExecSpawn`'s name-only `-e`
25
+ * forwarding into a container (the value travels in the docker client's
26
+ * environment, never on an argv). A containerized round therefore
27
+ * authenticates with the same credential as the host — nothing is authorized
28
+ * inside the unit, which is the point.
29
+ * @module @khorsheed/dsh-local-agent-claude-code/endpoint-auth
30
+ */
31
+ /**
32
+ * The scoped-home credential file's name. Chosen to match the eval contract
33
+ * hash's credential-shaped denylist (`/token|key|credential|secret|password|auth|\.env/i`),
34
+ * so the file is excluded from condition fingerprints by name.
35
+ */
36
+ export declare const ENDPOINT_AUTH_FILE = "endpoint-auth.json";
37
+ /**
38
+ * One scope's endpoint credential. `baseUrl` is optional (absent means the
39
+ * CLI's own default endpoint — an official console key needs no relay); at
40
+ * least one of `apiKey` / `authToken` must be non-empty for the scope to
41
+ * count as authenticated. When both are set the CLI's own precedence rules
42
+ * apply — the package passes both through untouched.
43
+ */
44
+ export interface ClaudeEndpointAuth {
45
+ readonly baseUrl?: string;
46
+ /** Sent as `ANTHROPIC_API_KEY` (the `x-api-key` header). */
47
+ readonly apiKey?: string;
48
+ /** Sent as `ANTHROPIC_AUTH_TOKEN` (the `Authorization: Bearer` header). */
49
+ readonly authToken?: string;
50
+ }
51
+ /** Whether a resolved endpoint carries a usable credential. */
52
+ export declare function hasEndpointCredential(auth: ClaudeEndpointAuth | undefined): auth is (ClaudeEndpointAuth & {
53
+ apiKey: string;
54
+ }) | (ClaudeEndpointAuth & {
55
+ authToken: string;
56
+ });
57
+ /**
58
+ * Read the scope's endpoint-auth.json. Absent or unreadable yields undefined
59
+ * (the caller falls back to the plugin config); malformed JSON or a non-object
60
+ * payload also yields undefined — a torn file must not fail a status read.
61
+ * Non-string fields are dropped, never carried through.
62
+ * @param homeDir - the `claude-code` harness's scoped home.
63
+ * @returns the file's endpoint credential, or undefined.
64
+ */
65
+ export declare function readEndpointAuthFile(homeDir: string): Promise<ClaudeEndpointAuth | undefined>;
66
+ /**
67
+ * Resolve one scope's effective endpoint credential: the scope's
68
+ * endpoint-auth.json merged FIELD BY FIELD over the plugin config's
69
+ * `baseUrl` / `apiKey` / `authToken` (a file that names only a key rotates
70
+ * the key while keeping the deployment's relay URL). The result may carry no
71
+ * credential at all — {@link hasEndpointCredential} is the judgment, kept
72
+ * separate so the caller can still route/log the resolved baseUrl.
73
+ * @param homeDir - the scope's scoped home.
74
+ * @param config - the plugin config's deployment-level endpoint triple.
75
+ * @returns the merged endpoint auth.
76
+ */
77
+ export declare function resolveEndpointAuth(homeDir: string, config: ClaudeEndpointAuth): Promise<ClaudeEndpointAuth>;
78
+ /**
79
+ * The spawn-env layer for a resolved endpoint: one entry per defined field,
80
+ * nothing else. Undefined yields an empty layer — the spread then adds no
81
+ * keys at all, byte-identical to the pre-endpoint env.
82
+ * @param auth - the resolved endpoint auth, or undefined.
83
+ * @returns the explicit env entries for the delegation spawn.
84
+ */
85
+ export declare function endpointAuthEnv(auth: ClaudeEndpointAuth | undefined): NodeJS.ProcessEnv;
86
+ /**
87
+ * The credential marker's modification stamp (epoch ms): the endpoint file's
88
+ * mtime, or undefined when the scope has no file (a config-sourced credential
89
+ * has no marker — rotating it pairs with the profile edit and instance
90
+ * restart that clear the in-memory grade marks). A fresh file write is a
91
+ * fresh stamp, which is how an edited-in key recovers a `rejected` grade.
92
+ * @param homeDir - the scope's scoped home.
93
+ * @returns the stamp, or undefined.
94
+ */
95
+ export declare function endpointAuthStamp(homeDir: string): Promise<number | undefined>;
96
+ /** Whether the scope carries its own endpoint file at all. */
97
+ export declare function endpointAuthFileExists(homeDir: string): Promise<boolean>;
98
+ /**
99
+ * Write the scope's endpoint-auth.json (mode 0600, mkdir -p first), the
100
+ * per-scope provisioning path an evaluation's `conditions provision` (or a
101
+ * person) uses to give one scope its own credential. Whole-file write: the
102
+ * payload is exactly what {@link readEndpointAuthFile} parses back.
103
+ * @param homeDir - the scope's scoped home.
104
+ * @param auth - the endpoint credential to persist.
105
+ */
106
+ export declare function writeEndpointAuth(homeDir: string, auth: ClaudeEndpointAuth): Promise<void>;
107
+ /**
108
+ * Clear the scope's OWN endpoint credential (the endpoint-auth.json file).
109
+ * A deployment-level credential from the plugin config is untouched — the
110
+ * core's logout reply then names the profile row as the place to edit.
111
+ * @param homeDir - the scope's scoped home.
112
+ */
113
+ export declare function clearEndpointAuth(homeDir: string): Promise<void>;
114
+ /** The official endpoint used when no baseUrl is configured anywhere. */
115
+ export declare const OFFICIAL_BASE_URL = "https://api.anthropic.com";
116
+ /** The subcommand's fetch shape (injected in tests). */
117
+ export type EndpointCheckFetch = (url: string, init: {
118
+ headers: Record<string, string>;
119
+ signal: AbortSignal;
120
+ }) => Promise<{
121
+ ok: boolean;
122
+ status: number;
123
+ text(): Promise<string>;
124
+ }>;
125
+ /** One model the endpoint serves, from `GET <baseUrl>/v1/models`. */
126
+ export interface EndpointServedModel {
127
+ readonly id: string;
128
+ readonly displayName?: string;
129
+ /** Reasoning effort levels the endpoint advertises for this model, in ascending order. */
130
+ readonly efforts?: readonly string[];
131
+ }
132
+ /**
133
+ * The outcome of one `GET <baseUrl>/v1/models`: the parsed model list, the
134
+ * HTTP status when the endpoint answered, or the transport error's message.
135
+ * Callers fold it their own way (the check's verdict text, the catalog's
136
+ * directory); no case throws.
137
+ */
138
+ export type EndpointModelsResult = {
139
+ readonly kind: 'models';
140
+ readonly models: readonly EndpointServedModel[];
141
+ } | {
142
+ readonly kind: 'http';
143
+ readonly status: number;
144
+ readonly body: string;
145
+ } | {
146
+ readonly kind: 'unreachable';
147
+ readonly message: string;
148
+ } | {
149
+ readonly kind: 'malformed';
150
+ };
151
+ /**
152
+ * `GET <baseUrl>/v1/models` with the resolved credential's auth header(s) —
153
+ * the token-free endpoint probe shared by the `/claude-code check` verdict
154
+ * and the model catalog. Anthropic's own API serves this route with
155
+ * `x-api-key`; relays (openproxy verified) proxy it and answer the same
156
+ * shape. Never throws: every failure mode folds into the result.
157
+ * @param endpoint - the resolved endpoint auth (caller checks the credential).
158
+ * @param fetchImpl - the HTTP fetch; default the host's global fetch.
159
+ * @param signal - abort for the whole probe (timeout bundled by the caller).
160
+ * @returns the folded result.
161
+ */
162
+ export declare function fetchEndpointModels(endpoint: ClaudeEndpointAuth & {
163
+ readonly baseUrl: string;
164
+ }, fetchImpl?: EndpointCheckFetch, signal?: AbortSignal): Promise<EndpointModelsResult>;
165
+ /**
166
+ * Probe the resolved endpoint with a cheap, token-free round-trip: `GET
167
+ * <baseUrl>/v1/models` with the resolved credential's auth header(s). A 200
168
+ * proves both reachability and credential validity — the exact evidence a
169
+ * "verify" button needs — and the served model list rides the reply so the
170
+ * user sees what the endpoint offers (any id can be typed into the model
171
+ * field by hand). One transport-level retry rides along: a local proxy
172
+ * restart (a Surge/clash reload) stalls the first attempt into the timeout
173
+ * and answers the retry immediately. Never throws: every failure mode folds
174
+ * into the reply text, since the reply IS the diagnostic.
175
+ * @param endpoint - the resolved endpoint auth (scope file over settings).
176
+ * @param fetchImpl - the HTTP fetch; default the host's global fetch.
177
+ * @param timeoutMs - one attempt's deadline (two attempts at most).
178
+ * @returns the human-readable verdict for the `/claude-code check` reply.
179
+ */
180
+ export declare function checkClaudeEndpoint(endpoint: ClaudeEndpointAuth, fetchImpl?: EndpointCheckFetch, timeoutMs?: number): Promise<string>;
181
+ //# sourceMappingURL=endpoint-auth.d.ts.map
@@ -0,0 +1,281 @@
1
+ /**
2
+ * Endpoint-key authentication — the claude-code harness's ONLY auth mode.
3
+ * There is no OAuth anywhere in this package: a delegation round reaches its
4
+ * endpoint with `ANTHROPIC_BASE_URL` plus `ANTHROPIC_API_KEY` (x-api-key) or
5
+ * `ANTHROPIC_AUTH_TOKEN` (Authorization: Bearer), exactly the environment a
6
+ * shell would export for a proxy relay, and `claude -p` needs nothing else
7
+ * (verified against claude 2.1.296: a fresh scoped home with only these
8
+ * variables runs a round and scaffolds `.claude.json` itself — no onboarding
9
+ * or key-approval gate in headless mode).
10
+ *
11
+ * Two layers, merged per field, file over config:
12
+ *
13
+ * - `<scopedHome>/endpoint-auth.json` (mode 0600) — the per-scope credential.
14
+ * Its name deliberately matches the eval contract hash's credential denylist
15
+ * (`auth`), so the key material never enters an evaluation's condition
16
+ * fingerprint; the file's mtime serves as the credential stamp, which makes
17
+ * "edit the file" the recovery gesture for a `rejected` grade.
18
+ * - The plugin config's `baseUrl` / `apiKey` / `authToken` — the deployment
19
+ * default every scope without a file shares. Read PER ROUND from the
20
+ * apply-time snapshot, so a profile edit applies to the next round (and a
21
+ * host restart clears the in-memory `rejected` mark).
22
+ *
23
+ * The env layer this module emits rides the family's existing plumbing:
24
+ * `delegationEnv` on the host, and `containerExecSpawn`'s name-only `-e`
25
+ * forwarding into a container (the value travels in the docker client's
26
+ * environment, never on an argv). A containerized round therefore
27
+ * authenticates with the same credential as the host — nothing is authorized
28
+ * inside the unit, which is the point.
29
+ * @module @khorsheed/dsh-local-agent-claude-code/endpoint-auth
30
+ */
31
+ import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
32
+ import { join } from 'node:path';
33
+ /**
34
+ * The scoped-home credential file's name. Chosen to match the eval contract
35
+ * hash's credential-shaped denylist (`/token|key|credential|secret|password|auth|\.env/i`),
36
+ * so the file is excluded from condition fingerprints by name.
37
+ */
38
+ export const ENDPOINT_AUTH_FILE = 'endpoint-auth.json';
39
+ /** Trim and normalize one credential field; blank reads as absent. */
40
+ function field(value) {
41
+ if (typeof value !== 'string')
42
+ return undefined;
43
+ const trimmed = value.trim();
44
+ return trimmed === '' ? undefined : trimmed;
45
+ }
46
+ /** Whether a resolved endpoint carries a usable credential. */
47
+ export function hasEndpointCredential(auth) {
48
+ return auth !== undefined && (field(auth.apiKey) !== undefined || field(auth.authToken) !== undefined);
49
+ }
50
+ /**
51
+ * Read the scope's endpoint-auth.json. Absent or unreadable yields undefined
52
+ * (the caller falls back to the plugin config); malformed JSON or a non-object
53
+ * payload also yields undefined — a torn file must not fail a status read.
54
+ * Non-string fields are dropped, never carried through.
55
+ * @param homeDir - the `claude-code` harness's scoped home.
56
+ * @returns the file's endpoint credential, or undefined.
57
+ */
58
+ export async function readEndpointAuthFile(homeDir) {
59
+ let text;
60
+ try {
61
+ text = await readFile(join(homeDir, ENDPOINT_AUTH_FILE), 'utf8');
62
+ }
63
+ catch {
64
+ return undefined;
65
+ }
66
+ try {
67
+ const parsed = JSON.parse(text);
68
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
69
+ return undefined;
70
+ const baseUrl = field(parsed['baseUrl']);
71
+ const apiKey = field(parsed['apiKey']);
72
+ const authToken = field(parsed['authToken']);
73
+ return {
74
+ ...baseUrl === undefined ? {} : { baseUrl },
75
+ ...apiKey === undefined ? {} : { apiKey },
76
+ ...authToken === undefined ? {} : { authToken },
77
+ };
78
+ }
79
+ catch {
80
+ return undefined;
81
+ }
82
+ }
83
+ /**
84
+ * Resolve one scope's effective endpoint credential: the scope's
85
+ * endpoint-auth.json merged FIELD BY FIELD over the plugin config's
86
+ * `baseUrl` / `apiKey` / `authToken` (a file that names only a key rotates
87
+ * the key while keeping the deployment's relay URL). The result may carry no
88
+ * credential at all — {@link hasEndpointCredential} is the judgment, kept
89
+ * separate so the caller can still route/log the resolved baseUrl.
90
+ * @param homeDir - the scope's scoped home.
91
+ * @param config - the plugin config's deployment-level endpoint triple.
92
+ * @returns the merged endpoint auth.
93
+ */
94
+ export async function resolveEndpointAuth(homeDir, config) {
95
+ const file = await readEndpointAuthFile(homeDir);
96
+ const configBaseUrl = field(config.baseUrl);
97
+ const configApiKey = field(config.apiKey);
98
+ const configAuthToken = field(config.authToken);
99
+ return {
100
+ ...configBaseUrl === undefined ? {} : { baseUrl: configBaseUrl },
101
+ ...configApiKey === undefined ? {} : { apiKey: configApiKey },
102
+ ...configAuthToken === undefined ? {} : { authToken: configAuthToken },
103
+ ...file,
104
+ };
105
+ }
106
+ /**
107
+ * The spawn-env layer for a resolved endpoint: one entry per defined field,
108
+ * nothing else. Undefined yields an empty layer — the spread then adds no
109
+ * keys at all, byte-identical to the pre-endpoint env.
110
+ * @param auth - the resolved endpoint auth, or undefined.
111
+ * @returns the explicit env entries for the delegation spawn.
112
+ */
113
+ export function endpointAuthEnv(auth) {
114
+ if (auth === undefined)
115
+ return {};
116
+ const baseUrl = field(auth.baseUrl);
117
+ const apiKey = field(auth.apiKey);
118
+ const authToken = field(auth.authToken);
119
+ return {
120
+ ...baseUrl === undefined ? {} : { ANTHROPIC_BASE_URL: baseUrl },
121
+ ...apiKey === undefined ? {} : { ANTHROPIC_API_KEY: apiKey },
122
+ ...authToken === undefined ? {} : { ANTHROPIC_AUTH_TOKEN: authToken },
123
+ };
124
+ }
125
+ /**
126
+ * The credential marker's modification stamp (epoch ms): the endpoint file's
127
+ * mtime, or undefined when the scope has no file (a config-sourced credential
128
+ * has no marker — rotating it pairs with the profile edit and instance
129
+ * restart that clear the in-memory grade marks). A fresh file write is a
130
+ * fresh stamp, which is how an edited-in key recovers a `rejected` grade.
131
+ * @param homeDir - the scope's scoped home.
132
+ * @returns the stamp, or undefined.
133
+ */
134
+ export async function endpointAuthStamp(homeDir) {
135
+ try {
136
+ return (await stat(join(homeDir, ENDPOINT_AUTH_FILE))).mtimeMs;
137
+ }
138
+ catch {
139
+ return undefined;
140
+ }
141
+ }
142
+ /** Whether the scope carries its own endpoint file at all. */
143
+ export async function endpointAuthFileExists(homeDir) {
144
+ return (await endpointAuthStamp(homeDir)) !== undefined;
145
+ }
146
+ /**
147
+ * Write the scope's endpoint-auth.json (mode 0600, mkdir -p first), the
148
+ * per-scope provisioning path an evaluation's `conditions provision` (or a
149
+ * person) uses to give one scope its own credential. Whole-file write: the
150
+ * payload is exactly what {@link readEndpointAuthFile} parses back.
151
+ * @param homeDir - the scope's scoped home.
152
+ * @param auth - the endpoint credential to persist.
153
+ */
154
+ export async function writeEndpointAuth(homeDir, auth) {
155
+ await mkdir(homeDir, { recursive: true });
156
+ const baseUrl = field(auth.baseUrl);
157
+ const apiKey = field(auth.apiKey);
158
+ const authToken = field(auth.authToken);
159
+ const payload = {
160
+ ...baseUrl === undefined ? {} : { baseUrl },
161
+ ...apiKey === undefined ? {} : { apiKey },
162
+ ...authToken === undefined ? {} : { authToken },
163
+ };
164
+ await writeFile(join(homeDir, ENDPOINT_AUTH_FILE), JSON.stringify(payload, undefined, 2) + '\n', { mode: 0o600 });
165
+ }
166
+ /**
167
+ * Clear the scope's OWN endpoint credential (the endpoint-auth.json file).
168
+ * A deployment-level credential from the plugin config is untouched — the
169
+ * core's logout reply then names the profile row as the place to edit.
170
+ * @param homeDir - the scope's scoped home.
171
+ */
172
+ export async function clearEndpointAuth(homeDir) {
173
+ await rm(join(homeDir, ENDPOINT_AUTH_FILE), { force: true });
174
+ }
175
+ /** The official endpoint used when no baseUrl is configured anywhere. */
176
+ export const OFFICIAL_BASE_URL = 'https://api.anthropic.com';
177
+ /** How many served model ids the check reply lists before truncating. */
178
+ const CHECK_MODEL_LIST_LIMIT = 8;
179
+ /** Bound on the error-body excerpt a failed check reports. */
180
+ const CHECK_ERROR_BODY_LIMIT = 200;
181
+ /** The effort levels one served-model entry advertises, oldest-first. */
182
+ function servedEfforts(effort) {
183
+ if (typeof effort !== 'object' || effort === null)
184
+ return undefined;
185
+ const levels = ['low', 'medium', 'high', 'xhigh', 'max']
186
+ .filter(level => effort[level]?.supported === true);
187
+ return levels.length === 0 ? undefined : levels;
188
+ }
189
+ /**
190
+ * `GET <baseUrl>/v1/models` with the resolved credential's auth header(s) —
191
+ * the token-free endpoint probe shared by the `/claude-code check` verdict
192
+ * and the model catalog. Anthropic's own API serves this route with
193
+ * `x-api-key`; relays (openproxy verified) proxy it and answer the same
194
+ * shape. Never throws: every failure mode folds into the result.
195
+ * @param endpoint - the resolved endpoint auth (caller checks the credential).
196
+ * @param fetchImpl - the HTTP fetch; default the host's global fetch.
197
+ * @param signal - abort for the whole probe (timeout bundled by the caller).
198
+ * @returns the folded result.
199
+ */
200
+ export async function fetchEndpointModels(endpoint, fetchImpl, signal) {
201
+ const headers = { 'anthropic-version': '2023-06-01' };
202
+ if (endpoint.apiKey !== undefined)
203
+ headers['x-api-key'] = endpoint.apiKey;
204
+ if (endpoint.authToken !== undefined)
205
+ headers['authorization'] = `Bearer ${endpoint.authToken}`;
206
+ const fetcher = fetchImpl ?? globalThis.fetch;
207
+ const url = `${endpoint.baseUrl.replace(/\/+$/, '')}/v1/models`;
208
+ let response;
209
+ try {
210
+ response = await fetcher(url, { headers, signal: signal ?? AbortSignal.timeout(8_000) });
211
+ }
212
+ catch (error) {
213
+ return { kind: 'unreachable', message: error instanceof Error ? error.message : String(error) };
214
+ }
215
+ if (!response.ok) {
216
+ return { kind: 'http', status: response.status, body: (await response.text().catch(() => '')).slice(0, CHECK_ERROR_BODY_LIMIT) };
217
+ }
218
+ let data;
219
+ try {
220
+ data = JSON.parse(await response.text()).data;
221
+ }
222
+ catch {
223
+ return { kind: 'malformed' };
224
+ }
225
+ if (!Array.isArray(data))
226
+ return { kind: 'malformed' };
227
+ const models = [];
228
+ for (const entry of data) {
229
+ if (typeof entry !== 'object' || entry === null)
230
+ continue;
231
+ const record = entry;
232
+ if (typeof record.id !== 'string' || record.id === '')
233
+ continue;
234
+ const efforts = servedEfforts(record.effort);
235
+ models.push({
236
+ id: record.id,
237
+ ...typeof record.display_name === 'string' && record.display_name !== '' ? { displayName: record.display_name } : {},
238
+ ...efforts === undefined ? {} : { efforts },
239
+ });
240
+ }
241
+ return { kind: 'models', models };
242
+ }
243
+ /**
244
+ * Probe the resolved endpoint with a cheap, token-free round-trip: `GET
245
+ * <baseUrl>/v1/models` with the resolved credential's auth header(s). A 200
246
+ * proves both reachability and credential validity — the exact evidence a
247
+ * "verify" button needs — and the served model list rides the reply so the
248
+ * user sees what the endpoint offers (any id can be typed into the model
249
+ * field by hand). One transport-level retry rides along: a local proxy
250
+ * restart (a Surge/clash reload) stalls the first attempt into the timeout
251
+ * and answers the retry immediately. Never throws: every failure mode folds
252
+ * into the reply text, since the reply IS the diagnostic.
253
+ * @param endpoint - the resolved endpoint auth (scope file over settings).
254
+ * @param fetchImpl - the HTTP fetch; default the host's global fetch.
255
+ * @param timeoutMs - one attempt's deadline (two attempts at most).
256
+ * @returns the human-readable verdict for the `/claude-code check` reply.
257
+ */
258
+ export async function checkClaudeEndpoint(endpoint, fetchImpl, timeoutMs = 20_000) {
259
+ if (!hasEndpointCredential(endpoint)) {
260
+ return 'No endpoint credential configured — fill API Key or Auth Token on the settings card (or the profile row) first.';
261
+ }
262
+ const baseUrl = (endpoint.baseUrl ?? OFFICIAL_BASE_URL).replace(/\/+$/, '');
263
+ let result = await fetchEndpointModels({ ...endpoint, baseUrl }, fetchImpl, AbortSignal.timeout(timeoutMs));
264
+ if (result.kind === 'unreachable') {
265
+ result = await fetchEndpointModels({ ...endpoint, baseUrl }, fetchImpl, AbortSignal.timeout(timeoutMs));
266
+ }
267
+ if (result.kind === 'unreachable')
268
+ return `Endpoint unreachable (${baseUrl}): ${result.message}`;
269
+ if (result.kind === 'http') {
270
+ return `Endpoint answered HTTP ${String(result.status)} (${baseUrl})${result.body === '' ? '' : `: ${result.body}`}`;
271
+ }
272
+ if (result.kind === 'malformed') {
273
+ return `Endpoint reachable (${baseUrl}) but the model list did not parse — the credential worked, the reply was not /v1/models-shaped.`;
274
+ }
275
+ if (result.models.length === 0)
276
+ return `Endpoint reachable (${baseUrl}); it serves no models.`;
277
+ const ids = result.models.map(model => model.id);
278
+ const listed = ids.slice(0, CHECK_MODEL_LIST_LIMIT).join(', ');
279
+ const more = ids.length > CHECK_MODEL_LIST_LIMIT ? `, … +${String(ids.length - CHECK_MODEL_LIST_LIMIT)} more` : '';
280
+ return `Endpoint reachable (${baseUrl}): ${String(ids.length)} model(s) served — ${listed}${more}`;
281
+ }