@byokkit/cmd-provider-anthropic 0.1.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/index.js ADDED
@@ -0,0 +1,464 @@
1
+ import {
2
+ ANTHROPIC_MODEL_SPECS,
3
+ matchesAnthropicModel
4
+ } from "./chunk-V3B4JGF6.js";
5
+
6
+ // src/index.ts
7
+ import { randomBytes as randomBytes2 } from "crypto";
8
+ import { createAnthropic } from "@ai-sdk/anthropic";
9
+
10
+ // ../harness/dist/chunk-T4KJUC4B.js
11
+ import { createHash, randomBytes } from "crypto";
12
+ function generatePkce(params = {}) {
13
+ const verifier = (params.randomBytesImpl ?? randomBytes)(32).toString(
14
+ "base64url"
15
+ );
16
+ const challenge = createHash("sha256").update(verifier).digest("base64url");
17
+ return { verifier, challenge };
18
+ }
19
+
20
+ // src/anthropic-oauth-fetch.ts
21
+ var OAUTH_BETAS = "oauth-2025-04-20,interleaved-thinking-2025-05-14,web-search-2025-03-05,web-fetch-2025-09-10";
22
+ var TOOL_PREFIX = "cc_";
23
+ var CLAUDE_CODE_VERSION = "2.1.76";
24
+ var CLAUDE_CODE_USER_AGENT = `claude-code/${CLAUDE_CODE_VERSION}`;
25
+ var BILLING_SALT = "59cf53e54c78";
26
+ async function sha256Hex(input) {
27
+ const data = new TextEncoder().encode(input);
28
+ const hashBuffer = await crypto.subtle.digest("SHA-256", data);
29
+ return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
30
+ }
31
+ function sampleJsCodeUnit(text, idx) {
32
+ let pos = 0;
33
+ for (let i = 0; i < text.length; i++) {
34
+ const code = text.charCodeAt(i);
35
+ if (pos === idx) return String.fromCharCode(code);
36
+ pos++;
37
+ if (code >= 55296 && code <= 56319) {
38
+ if (pos === idx) return String.fromCharCode(text.charCodeAt(i + 1));
39
+ pos++;
40
+ i++;
41
+ }
42
+ }
43
+ return "0";
44
+ }
45
+ function extractFirstUserMessage(messages) {
46
+ for (const msg of messages) {
47
+ if (msg.role !== "user") continue;
48
+ if (typeof msg.content === "string") return msg.content;
49
+ if (Array.isArray(msg.content)) {
50
+ for (const block of msg.content) {
51
+ const b = block;
52
+ if (b.type === "text" && typeof b.text === "string")
53
+ return b.text;
54
+ }
55
+ }
56
+ }
57
+ return "";
58
+ }
59
+ async function buildBillingBlock(messages) {
60
+ const firstMsg = extractFirstUserMessage(messages);
61
+ const sampled = [4, 7, 20].map((idx) => sampleJsCodeUnit(firstMsg, idx)).join("");
62
+ const versionHash = await sha256Hex(
63
+ `${BILLING_SALT}${sampled}${CLAUDE_CODE_VERSION}`
64
+ );
65
+ return `x-anthropic-billing-header: cc_version=${CLAUDE_CODE_VERSION}.${versionHash.slice(0, 3)}; cc_entrypoint=cli; cch=00000;`;
66
+ }
67
+ var BRAND_SPOOF_RULES = [
68
+ {
69
+ pattern: /(?<![\w./\\~-])Command Code(?![\w-])/g,
70
+ replacement: "Claude Code"
71
+ },
72
+ {
73
+ pattern: /(?<![\w./\\~-])commandcode(?![\w-])/gi,
74
+ replacement: "claude"
75
+ }
76
+ ];
77
+ function spoofBrandText(text) {
78
+ let result = text;
79
+ for (const rule of BRAND_SPOOF_RULES) {
80
+ result = result.replace(rule.pattern, rule.replacement);
81
+ }
82
+ return result;
83
+ }
84
+ function prefixOAuthToolName(tool) {
85
+ const name = tool.name;
86
+ const type = tool.type;
87
+ if (!name || type?.includes("web_")) {
88
+ return tool;
89
+ }
90
+ return {
91
+ ...tool,
92
+ name: `${TOOL_PREFIX}${name}`
93
+ };
94
+ }
95
+ function cleanOAuthMessageBlock(block) {
96
+ const cleaned = { ...block };
97
+ if (cleaned.type === "tool_use") {
98
+ return prefixOAuthToolName(cleaned);
99
+ }
100
+ return cleaned;
101
+ }
102
+ function cleanOAuthMessage(message) {
103
+ if (!message.content || !Array.isArray(message.content)) {
104
+ return message;
105
+ }
106
+ return {
107
+ ...message,
108
+ content: message.content.map(
109
+ (block) => cleanOAuthMessageBlock(block)
110
+ )
111
+ };
112
+ }
113
+ function createAnthropicOAuthFetch(oauthToken, upstreamFetch = globalThis.fetch) {
114
+ return async (input, init) => {
115
+ const requestHeaders = new Headers(
116
+ init?.headers
117
+ );
118
+ requestHeaders.set("authorization", `Bearer ${oauthToken}`);
119
+ requestHeaders.delete("x-api-key");
120
+ requestHeaders.set("anthropic-beta", OAUTH_BETAS);
121
+ requestHeaders.set("user-agent", CLAUDE_CODE_USER_AGENT);
122
+ let body = init?.body;
123
+ if (body && typeof body === "string") {
124
+ try {
125
+ const parsed = JSON.parse(body);
126
+ delete parsed.tool_choice;
127
+ delete parsed.top_k;
128
+ delete parsed.top_p;
129
+ delete parsed.stop_sequences;
130
+ for (const key of Object.keys(parsed)) {
131
+ if (parsed[key] === void 0 || parsed[key] === null)
132
+ delete parsed[key];
133
+ }
134
+ const billingText = await buildBillingBlock(
135
+ parsed.messages || []
136
+ );
137
+ const billingBlock = { type: "text", text: billingText };
138
+ if (parsed.system && Array.isArray(parsed.system)) {
139
+ parsed.system = [
140
+ billingBlock,
141
+ ...parsed.system.map(
142
+ (item) => {
143
+ const cleaned = { ...item };
144
+ if (cleaned.type === "text" && typeof cleaned.text === "string") {
145
+ cleaned.text = spoofBrandText(
146
+ cleaned.text
147
+ );
148
+ }
149
+ return cleaned;
150
+ }
151
+ )
152
+ ];
153
+ } else if (typeof parsed.system === "string") {
154
+ parsed.system = [
155
+ billingBlock,
156
+ {
157
+ type: "text",
158
+ text: spoofBrandText(parsed.system)
159
+ }
160
+ ];
161
+ } else {
162
+ parsed.system = [billingBlock];
163
+ }
164
+ if (parsed.tools && Array.isArray(parsed.tools)) {
165
+ parsed.tools = parsed.tools.map(prefixOAuthToolName);
166
+ }
167
+ if (parsed.messages && Array.isArray(parsed.messages)) {
168
+ parsed.messages = parsed.messages.map(cleanOAuthMessage);
169
+ }
170
+ body = JSON.stringify(parsed);
171
+ } catch {
172
+ }
173
+ }
174
+ let requestInput = input;
175
+ try {
176
+ const url = new URL(
177
+ typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url
178
+ );
179
+ if (url.pathname === "/v1/messages" && !url.searchParams.has("beta")) {
180
+ url.searchParams.set("beta", "true");
181
+ requestInput = input instanceof Request ? new Request(url.toString(), input) : url;
182
+ }
183
+ } catch {
184
+ }
185
+ const response = await upstreamFetch(requestInput, {
186
+ ...init,
187
+ body,
188
+ headers: requestHeaders
189
+ });
190
+ if (response.body) {
191
+ const reader = response.body.getReader();
192
+ const decoder = new TextDecoder();
193
+ const encoder = new TextEncoder();
194
+ const stripToolPrefix = (text) => text.replace(/"name"\s*:\s*"cc_([^"]+)"/g, '"name": "$1"');
195
+ let carry = "";
196
+ const stream = new ReadableStream({
197
+ async pull(controller) {
198
+ const { done, value } = await reader.read();
199
+ if (done) {
200
+ carry += decoder.decode();
201
+ if (carry) {
202
+ controller.enqueue(
203
+ encoder.encode(stripToolPrefix(carry))
204
+ );
205
+ carry = "";
206
+ }
207
+ controller.close();
208
+ return;
209
+ }
210
+ carry += decoder.decode(value, { stream: true });
211
+ const boundary = carry.lastIndexOf("\n");
212
+ if (boundary === -1) return;
213
+ const complete = carry.slice(0, boundary + 1);
214
+ carry = carry.slice(boundary + 1);
215
+ controller.enqueue(
216
+ encoder.encode(stripToolPrefix(complete))
217
+ );
218
+ }
219
+ });
220
+ return new Response(stream, {
221
+ status: response.status,
222
+ statusText: response.statusText,
223
+ headers: response.headers
224
+ });
225
+ }
226
+ return response;
227
+ };
228
+ }
229
+
230
+ // src/index.ts
231
+ var CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
232
+ var AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
233
+ var TOKEN_URL = "https://console.anthropic.com/v1/oauth/token";
234
+ var REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback";
235
+ var SCOPE = "org:create_api_key user:profile user:inference";
236
+ var ANTHROPIC_PROVIDER_ID = "anthropic";
237
+ var OAUTH_TOKEN_HEADER = "x-oauth-token";
238
+ var OAUTH_PROVIDER_HEADER = "x-oauth-provider";
239
+ var OAUTH_PROVIDER_VALUE = "anthropic";
240
+ var ANTHROPIC_BASE_URL = "https://api.anthropic.com";
241
+ var EXPIRY_SKEW_MS = 5 * 60 * 1e3;
242
+ function defaultFetch() {
243
+ return globalThis.fetch;
244
+ }
245
+ function buildAuthorizeUrl(params) {
246
+ const query = encodeQuery({
247
+ code: "true",
248
+ client_id: CLIENT_ID,
249
+ response_type: "code",
250
+ redirect_uri: REDIRECT_URI,
251
+ scope: SCOPE,
252
+ code_challenge: params.challenge,
253
+ code_challenge_method: "S256",
254
+ state: params.state
255
+ });
256
+ return `${AUTHORIZE_URL}?${query}`;
257
+ }
258
+ function encodeQuery(params) {
259
+ return Object.entries(params).map(
260
+ ([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
261
+ ).join("&");
262
+ }
263
+ function generateState() {
264
+ return randomBytes2(32).toString("base64url");
265
+ }
266
+ function toCredential(token) {
267
+ return {
268
+ kind: "oauth",
269
+ token: token.accessToken,
270
+ refreshToken: token.refreshToken,
271
+ expiresAt: token.expiresAt
272
+ };
273
+ }
274
+ function isStale(credential, nowMs) {
275
+ return typeof credential.expiresAt === "number" && credential.expiresAt - EXPIRY_SKEW_MS <= nowMs;
276
+ }
277
+ function toTokenResult(raw, params) {
278
+ if (!raw.access_token) {
279
+ throw new Error("OAuth token response had no access_token");
280
+ }
281
+ return {
282
+ accessToken: raw.access_token,
283
+ refreshToken: raw.refresh_token ?? params.fallbackRefreshToken,
284
+ expiresAt: typeof raw.expires_in === "number" ? params.now() + raw.expires_in * 1e3 : void 0,
285
+ tokenType: raw.token_type,
286
+ scope: raw.scope
287
+ };
288
+ }
289
+ async function postAnthropicToken(params) {
290
+ const fetchImpl = params.fetchImpl ?? defaultFetch();
291
+ const response = await fetchImpl(TOKEN_URL, {
292
+ method: "POST",
293
+ headers: {
294
+ "Content-Type": "application/json",
295
+ Accept: "application/json"
296
+ },
297
+ body: JSON.stringify(params.body)
298
+ });
299
+ if (response.ok === false) {
300
+ const error = response.text ? await response.text() : "";
301
+ throw new Error(`Token exchange failed: ${error}`);
302
+ }
303
+ return toTokenResult(await response.json(), {
304
+ now: params.now,
305
+ fallbackRefreshToken: params.fallbackRefreshToken
306
+ });
307
+ }
308
+ function createAnthropicProvider(options = {}) {
309
+ const { fetchImpl, now } = options;
310
+ const clock = now ?? (() => Date.now());
311
+ const refreshCredential = async (credential) => {
312
+ if (!credential.refreshToken) {
313
+ throw new Error(
314
+ "Cannot refresh Anthropic OAuth: no refresh token stored"
315
+ );
316
+ }
317
+ const token = await postAnthropicToken({
318
+ body: {
319
+ grant_type: "refresh_token",
320
+ client_id: CLIENT_ID,
321
+ refresh_token: credential.refreshToken
322
+ },
323
+ fetchImpl,
324
+ now: clock,
325
+ fallbackRefreshToken: credential.refreshToken
326
+ });
327
+ return toCredential(token);
328
+ };
329
+ const inFlight = /* @__PURE__ */ new Map();
330
+ const refreshOnce = async (params) => {
331
+ const existing = inFlight.get(ANTHROPIC_PROVIDER_ID);
332
+ if (existing) return existing;
333
+ const pending = (async () => {
334
+ try {
335
+ const next = await refreshCredential(params.credential);
336
+ await params.store.set({
337
+ provider: ANTHROPIC_PROVIDER_ID,
338
+ credential: next
339
+ });
340
+ return next;
341
+ } catch {
342
+ return params.credential;
343
+ } finally {
344
+ inFlight.delete(ANTHROPIC_PROVIDER_ID);
345
+ }
346
+ })();
347
+ inFlight.set(ANTHROPIC_PROVIDER_ID, pending);
348
+ return pending;
349
+ };
350
+ return {
351
+ id: ANTHROPIC_PROVIDER_ID,
352
+ displayName: "Anthropic",
353
+ // The full Anthropic catalog (windows/efforts/interleaved-thinking) — overlays the
354
+ // harness's fallback mirror so this package is the runtime source of truth.
355
+ models: ANTHROPIC_MODEL_SPECS,
356
+ // Claims BYO/dated claude-* ids the catalog doesn't enumerate, so interleaved-thinking
357
+ // finalization still applies to them (the heuristic that used to live in core).
358
+ matchesModelId: matchesAnthropicModel,
359
+ // Requests go straight to api.anthropic.com, run locally through @ai-sdk/anthropic. ALL
360
+ // OAuth wire behavior (Authorization bearer, the oauth beta set, brand rewrite, billing
361
+ // block, cc_ tool prefixing) lives in the custom fetch the auth.loader returns — the SDK
362
+ // model itself stays stock. The dummy apiKey only satisfies the SDK's key check; the
363
+ // OAuth fetch strips x-api-key off every request. Neither the OAuth token nor prompts
364
+ // pass through Command Code's API.
365
+ transport: {
366
+ kind: "aisdk",
367
+ buildModel: ({ model, auth }) => createAnthropic({
368
+ baseURL: `${ANTHROPIC_BASE_URL}/v1`,
369
+ apiKey: "commandcode-oauth",
370
+ ...auth.fetch ? { fetch: auth.fetch } : fetchImpl ? { fetch: fetchImpl } : {}
371
+ })(model)
372
+ },
373
+ auth: {
374
+ methods: [
375
+ {
376
+ kind: "oauth",
377
+ label: "OAuth (paste code)",
378
+ // Manual code-paste: open the `code=true` authorize URL, then resolve once the user
379
+ // pastes the `code#state` Anthropic shows them. `prompt` present ⇒ the harness collects
380
+ // the pasted value and forwards it to callback() (no localhost redirect server).
381
+ authorize: async () => {
382
+ const pkce = generatePkce();
383
+ const state = generateState();
384
+ const url = buildAuthorizeUrl({
385
+ challenge: pkce.challenge,
386
+ state
387
+ });
388
+ return {
389
+ type: "pending",
390
+ url,
391
+ instructions: "Open the URL and approve access, then copy the authorization code Anthropic shows you (it looks like `code#state`) and paste it back here.",
392
+ prompt: { label: "Paste the authorization code" },
393
+ callback: async (input) => {
394
+ const pasted = (input?.code ?? "").trim();
395
+ if (!pasted) {
396
+ throw new Error(
397
+ "No authorization code provided"
398
+ );
399
+ }
400
+ const hashIndex = pasted.indexOf("#");
401
+ const code = (hashIndex === -1 ? pasted : pasted.slice(0, hashIndex)).trim();
402
+ const pastedState = hashIndex === -1 ? "" : pasted.slice(hashIndex + 1).trim();
403
+ if (!code) {
404
+ throw new Error(
405
+ "No authorization code provided"
406
+ );
407
+ }
408
+ if (pastedState && pastedState !== state) {
409
+ throw new Error(
410
+ "OAuth state parameter mismatch"
411
+ );
412
+ }
413
+ const token = await postAnthropicToken({
414
+ body: {
415
+ grant_type: "authorization_code",
416
+ client_id: CLIENT_ID,
417
+ code,
418
+ redirect_uri: REDIRECT_URI,
419
+ code_verifier: pkce.verifier,
420
+ state
421
+ },
422
+ fetchImpl,
423
+ now: clock
424
+ });
425
+ return toCredential(token);
426
+ }
427
+ };
428
+ },
429
+ refresh: async (params) => refreshCredential(params.credential)
430
+ }
431
+ ],
432
+ // Turn a stored credential into request headers, refreshing first if it is within the skew
433
+ // window. Returns the exact header set command-auth-headers.ts emits for Anthropic.
434
+ loader: async (params) => {
435
+ const { credential, store } = params;
436
+ if (!credential || credential.kind !== "oauth" || !credential.token) {
437
+ return {};
438
+ }
439
+ const active = credential.refreshToken && isStale(credential, clock()) ? await refreshOnce({ credential, store }) : credential;
440
+ if (!active.token) return {};
441
+ return {
442
+ headers: {
443
+ Authorization: `Bearer ${active.token}`
444
+ },
445
+ fetch: createAnthropicOAuthFetch(
446
+ active.token,
447
+ fetchImpl
448
+ )
449
+ };
450
+ }
451
+ }
452
+ };
453
+ }
454
+ var anthropicProvider = createAnthropicProvider();
455
+ var index_default = anthropicProvider;
456
+ export {
457
+ ANTHROPIC_PROVIDER_ID,
458
+ OAUTH_PROVIDER_HEADER,
459
+ OAUTH_PROVIDER_VALUE,
460
+ OAUTH_TOKEN_HEADER,
461
+ createAnthropicProvider,
462
+ index_default as default
463
+ };
464
+ //# sourceMappingURL=index.js.map