zidane 6.5.5 → 6.5.6

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.
Files changed (91) hide show
  1. package/dist/{acp-BPJbXS2J.js → acp-Dm95NwNM.js} +4 -4
  2. package/dist/{acp-BPJbXS2J.js.map → acp-Dm95NwNM.js.map} +1 -1
  3. package/dist/acp-cli.js +5 -5
  4. package/dist/acp.d.ts +1 -1
  5. package/dist/acp.js +1 -1
  6. package/dist/{agent-gZjHsUft.js → agent-CcTWL-Z6.js} +59 -5
  7. package/dist/agent-CcTWL-Z6.js.map +1 -0
  8. package/dist/agent.d.ts +1 -1
  9. package/dist/agent.js +1 -1
  10. package/dist/{anthropic-D3le2d-s.js → anthropic-DLc_Kw-1.js} +362 -28
  11. package/dist/anthropic-DLc_Kw-1.js.map +1 -0
  12. package/dist/{auth-DCiXCwGa.js → auth-BAclQnl3.js} +126 -34
  13. package/dist/{auth-DCiXCwGa.js.map → auth-BAclQnl3.js.map} +1 -1
  14. package/dist/chat/pure.d.ts +3 -3
  15. package/dist/chat.d.ts +91 -6
  16. package/dist/chat.d.ts.map +1 -1
  17. package/dist/chat.js +4 -4
  18. package/dist/contexts/daytona.d.ts +1 -1
  19. package/dist/contexts/e2b.d.ts +1 -1
  20. package/dist/eval.d.ts +1 -1
  21. package/dist/eval.js +1 -1
  22. package/dist/extensions.d.ts +1 -1
  23. package/dist/extensions.js +1 -1
  24. package/dist/headless.d.ts +1 -1
  25. package/dist/headless.js +3 -3
  26. package/dist/{index-BYKzzYzi.d.ts → index-ZWibV230.d.ts} +33 -7
  27. package/dist/index-ZWibV230.d.ts.map +1 -0
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +6 -6
  30. package/dist/mcp.d.ts +1 -1
  31. package/dist/{messages-CVVg5jUL.js → messages-CZMUuKzo.js} +2 -2
  32. package/dist/{messages-CVVg5jUL.js.map → messages-CZMUuKzo.js.map} +1 -1
  33. package/dist/{openai-compat-hmZzpDrB.js → openai-compat-BoTi-9fd.js} +8 -3
  34. package/dist/openai-compat-BoTi-9fd.js.map +1 -0
  35. package/dist/output/stream-json.d.ts +1 -1
  36. package/dist/output/terminal.d.ts +1 -1
  37. package/dist/plugins.d.ts +1 -1
  38. package/dist/presets.d.ts +1 -1
  39. package/dist/presets.js +1 -1
  40. package/dist/providers/anthropic.d.ts +1 -1
  41. package/dist/providers/anthropic.js +1 -1
  42. package/dist/providers/arcee.d.ts +1 -1
  43. package/dist/providers/arcee.js +1 -1
  44. package/dist/providers/baseten.d.ts +1 -1
  45. package/dist/providers/baseten.js +1 -1
  46. package/dist/providers/cerebras.d.ts +1 -1
  47. package/dist/providers/cerebras.js +1 -1
  48. package/dist/providers/local.d.ts +1 -1
  49. package/dist/providers/local.js +1 -1
  50. package/dist/providers/openai-compat.d.ts +1 -1
  51. package/dist/providers/openai-compat.js +1 -1
  52. package/dist/providers/openai.d.ts +1 -1
  53. package/dist/providers/openai.js +2 -2
  54. package/dist/providers/openrouter.d.ts +1 -1
  55. package/dist/providers/openrouter.js +1 -1
  56. package/dist/providers/xai.d.ts +1 -1
  57. package/dist/providers/xai.js +1 -1
  58. package/dist/{providers-Cf0AXIIZ.js → providers-CmhdtD7w.js} +2 -2
  59. package/dist/{providers-Cf0AXIIZ.js.map → providers-CmhdtD7w.js.map} +1 -1
  60. package/dist/providers.d.ts +1 -1
  61. package/dist/providers.js +3 -3
  62. package/dist/restate.d.ts +1 -1
  63. package/dist/restate.js +2 -2
  64. package/dist/session/sqlite.d.ts +1 -1
  65. package/dist/{session-cqN5NbO-.js → session-CyRLSsVa.js} +2 -2
  66. package/dist/{session-cqN5NbO-.js.map → session-CyRLSsVa.js.map} +1 -1
  67. package/dist/session.d.ts +1 -1
  68. package/dist/session.js +2 -2
  69. package/dist/skills.d.ts +1 -1
  70. package/dist/{tool-formatters-B5WSHMCU.d.ts → tool-formatters-D3wSS2zz.d.ts} +2 -2
  71. package/dist/{tool-formatters-B5WSHMCU.d.ts.map → tool-formatters-D3wSS2zz.d.ts.map} +1 -1
  72. package/dist/tools/fetch-url.d.ts +1 -1
  73. package/dist/tools/web-search.d.ts +1 -1
  74. package/dist/tools.d.ts +1 -1
  75. package/dist/tools.js +1 -1
  76. package/dist/{transcript-anchors-BvC8t7dt.js → transcript-anchors-D-Yuimif.js} +3 -3
  77. package/dist/{transcript-anchors-BvC8t7dt.js.map → transcript-anchors-D-Yuimif.js.map} +1 -1
  78. package/dist/{transcript-anchors-BPnWHLyr.d.ts → transcript-anchors-llwMrLRG.d.ts} +2 -2
  79. package/dist/{transcript-anchors-BPnWHLyr.d.ts.map → transcript-anchors-llwMrLRG.d.ts.map} +1 -1
  80. package/dist/tui.d.ts +9 -3
  81. package/dist/tui.d.ts.map +1 -1
  82. package/dist/tui.js +232 -13
  83. package/dist/tui.js.map +1 -1
  84. package/dist/{turn-operations-BvP3_HsU.d.ts → turn-operations-C_XvfBU3.d.ts} +3 -3
  85. package/dist/{turn-operations-BvP3_HsU.d.ts.map → turn-operations-C_XvfBU3.d.ts.map} +1 -1
  86. package/dist/types.d.ts +1 -1
  87. package/package.json +1 -1
  88. package/dist/agent-gZjHsUft.js.map +0 -1
  89. package/dist/anthropic-D3le2d-s.js.map +0 -1
  90. package/dist/index-BYKzzYzi.d.ts.map +0 -1
  91. package/dist/openai-compat-hmZzpDrB.js.map +0 -1
package/dist/agent.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { $h as hydrateReadStateFromSessionAsync, $r as createRunSummaryCollector, Bf as installCacheBreakLogger, Ff as CacheDimensionSnapshot, Gi as AgentHookMap, Gr as RunSummaryBudget, If as CacheDriftInfo, Jh as ReadStateEntry, Ji as McpConnector, Jr as RunSummaryCollectorOptions, Ki as AgentHooks, Kr as RunSummaryByModel, Lf as diffCacheDimensions, Mf as CacheBreakLoggerOptions, Nf as CacheDimensionDiff, Pf as CacheDimensionName, Qh as hydrateReadStateFromSession, Qr as RunSummaryValidation, Rf as fnv1a32, Ur as RunSummary, Vf as snapshotCacheDimensions, Wi as Agent, Wr as RunSummaryBlock, Xh as getReadState, Xi as McpToolWrap, Xr as RunSummaryRepeatGuard, Yh as ReadStateMap, Yi as McpToolMeta, Yr as RunSummaryError, Zi as createAgent, Zr as RunSummaryTokens, eg as readStateKey, jf as CacheBreakInfo, qh as HydrateReadStateOptions, qi as AgentOptions, qr as RunSummaryCollector, tg as resolveReadStateMap, zf as hashMessages } from "./index-BYKzzYzi.js";
1
+ import { $h as hydrateReadStateFromSessionAsync, $r as createRunSummaryCollector, Bf as installCacheBreakLogger, Ff as CacheDimensionSnapshot, Gi as AgentHookMap, Gr as RunSummaryBudget, If as CacheDriftInfo, Jh as ReadStateEntry, Ji as McpConnector, Jr as RunSummaryCollectorOptions, Ki as AgentHooks, Kr as RunSummaryByModel, Lf as diffCacheDimensions, Mf as CacheBreakLoggerOptions, Nf as CacheDimensionDiff, Pf as CacheDimensionName, Qh as hydrateReadStateFromSession, Qr as RunSummaryValidation, Rf as fnv1a32, Ur as RunSummary, Vf as snapshotCacheDimensions, Wi as Agent, Wr as RunSummaryBlock, Xh as getReadState, Xi as McpToolWrap, Xr as RunSummaryRepeatGuard, Yh as ReadStateMap, Yi as McpToolMeta, Yr as RunSummaryError, Zi as createAgent, Zr as RunSummaryTokens, eg as readStateKey, jf as CacheBreakInfo, qh as HydrateReadStateOptions, qi as AgentOptions, qr as RunSummaryCollector, tg as resolveReadStateMap, zf as hashMessages } from "./index-ZWibV230.js";
2
2
  export { type Agent, type AgentHookMap, type AgentHooks, type AgentOptions, type CacheBreakInfo, type CacheBreakLoggerOptions, type CacheDimensionDiff, type CacheDimensionName, type CacheDimensionSnapshot, type CacheDriftInfo, type HydrateReadStateOptions, type McpConnector, type McpToolMeta, type McpToolWrap, type ReadStateEntry, type ReadStateMap, type RunSummary, type RunSummaryBlock, type RunSummaryBudget, type RunSummaryByModel, type RunSummaryCollector, type RunSummaryCollectorOptions, type RunSummaryError, type RunSummaryRepeatGuard, type RunSummaryTokens, type RunSummaryValidation, createAgent, createRunSummaryCollector, diffCacheDimensions, fnv1a32, getReadState, hashMessages, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, installCacheBreakLogger, readStateKey, resolveReadStateMap, snapshotCacheDimensions };
package/dist/agent.js CHANGED
@@ -1,4 +1,4 @@
1
- import { In as hydrateReadStateFromSession, Ln as hydrateReadStateFromSessionAsync, Pn as getReadState, Rn as readStateKey, t as createAgent, zn as resolveReadStateMap } from "./agent-gZjHsUft.js";
1
+ import { Bn as hydrateReadStateFromSessionAsync, Hn as resolveReadStateMap, Ln as getReadState, Vn as readStateKey, t as createAgent, zn as hydrateReadStateFromSession } from "./agent-CcTWL-Z6.js";
2
2
  import { a as snapshotCacheDimensions, i as installCacheBreakLogger, n as fnv1a32, r as hashMessages, t as diffCacheDimensions } from "./cache-telemetry-ehVdWsg2.js";
3
3
  import { t as createRunSummaryCollector } from "./run-summary-BU_NgwUT.js";
4
4
  export { createAgent, createRunSummaryCollector, diffCacheDimensions, fnv1a32, getReadState, hashMessages, hydrateReadStateFromSession, hydrateReadStateFromSessionAsync, installCacheBreakLogger, readStateKey, resolveReadStateMap, snapshotCacheDimensions };
@@ -1,9 +1,12 @@
1
- import { F as unsupportedMediaError, S as resolvePromptCacheKey, b as sanitizeToolSpecs, k as lookupModel, v as createToolNameBoundary, w as fillEstimatedCost } from "./openai-compat-hmZzpDrB.js";
1
+ import { F as unsupportedMediaError, S as resolvePromptCacheKey, b as sanitizeToolSpecs, k as lookupModel, v as createToolNameBoundary, w as fillEstimatedCost } from "./openai-compat-BoTi-9fd.js";
2
2
  import { t as lazyAsync } from "./lazy-DLOurOC_.js";
3
3
  import { f as isRetryableHttpStatus, h as matchesToolPairingError, l as classifyErrorPrelude, m as matchesContextExceeded, u as errorMessage } from "./errors-DKiMrOKq.js";
4
4
  import { renderSystemForWire, splitSystemPrompt } from "./prompt.js";
5
- import { g as toAnthropic, u as fromAnthropic } from "./messages-CVVg5jUL.js";
5
+ import { g as toAnthropic, u as fromAnthropic } from "./messages-CZMUuKzo.js";
6
6
  import { a as readOAuthCredentials, r as extractRuntimeCredentials, s as resolveOAuthApiKey } from "./oauth-C4GvY_p1.js";
7
+ import { Buffer } from "node:buffer";
8
+ import { arch, homedir, hostname, platform, userInfo } from "node:os";
9
+ import { createHash, randomUUID } from "node:crypto";
7
10
  //#region src/chat/anthropic-models.ts
8
11
  /**
9
12
  * Anthropic "fast mode" — `speed: "fast"` on the Messages API. ~2.5× output
@@ -123,6 +126,324 @@ const ANTHROPIC_EXTRA_MODELS = [
123
126
  }
124
127
  ];
125
128
  //#endregion
129
+ //#region src/providers/anthropic-claude-code.ts
130
+ /**
131
+ * Claude Code client alignment for Anthropic subscription OAuth.
132
+ *
133
+ * Anthropic's subscription endpoint serves the Claude Code CLI. Requests that
134
+ * do not look like that client are, at best, treated as a different product; at
135
+ * worst they miss features the CLI relies on. This module holds every surface
136
+ * that has to match, in one file, so a client bump is one edit rather than a
137
+ * scavenger hunt through the provider.
138
+ *
139
+ * Modelled on `@pi-plugins/claude-oauth`, which maintains the same alignment
140
+ * for pi and verifies its pins against a live client trace. Everything here is
141
+ * scoped to the OAuth path — API-key, gateway-bearer and Bedrock requests never
142
+ * reach it.
143
+ */
144
+ /**
145
+ * Pinned Claude Code client versions.
146
+ *
147
+ * These travel together: the billing fingerprint below hashes
148
+ * {@link CLAUDE_CODE_VERSION}, so bumping one without the others produces a
149
+ * value that does not correspond to any real client. Re-check all five against
150
+ * the upstream plugin's `constants.ts` when bumping.
151
+ */
152
+ const CLAUDE_CODE_VERSION = "2.1.165";
153
+ const CLAUDE_AGENT_SDK_VERSION = "0.3.165";
154
+ const CLAUDE_CLIENT_VERSION = "1.11187.4";
155
+ const CLAUDE_CODE_STAINLESS_PACKAGE_VERSION = "0.94.0";
156
+ const CLAUDE_CODE_STAINLESS_RUNTIME_VERSION = "v24.3.0";
157
+ /**
158
+ * Claude Code caps requested output at 64k even where the model ceiling is
159
+ * higher (Opus allows 128k). Requests above the cap are clamped to match.
160
+ */
161
+ const CLAUDE_CODE_MAX_OUTPUT_TOKENS = 64e3;
162
+ /**
163
+ * Tool names the Claude subscription backend reserves.
164
+ *
165
+ * A tool named exactly `todowrite` is classified as a paid Claude product
166
+ * surface: the otherwise-valid OAuth request is refused with "You're out of
167
+ * extra usage" when the account has no purchased usage credits. The same body
168
+ * succeeds when only that wire name changes.
169
+ */
170
+ const CLAUDE_CODE_RESERVED_TOOL_NAMES = ["todowrite"];
171
+ const RESERVED_TOOL_ALIAS_PREFIX = "zidane_";
172
+ /**
173
+ * Request-local wire aliases that move reserved names out of the way, for
174
+ * Claude subscription OAuth only.
175
+ *
176
+ * Resolved against the request's FULL name set (history + current specs) rather
177
+ * than hardcoded, because the obvious alias is itself a legal tool name: an
178
+ * extension shipping `zidane_todowrite` alongside `todowrite` would otherwise
179
+ * make the boundary throw on a collision it can trivially avoid. Suffixing is
180
+ * deterministic, so the wire bytes — and the provider prompt cache — stay
181
+ * stable across turns with the same tool set.
182
+ *
183
+ * Canonical names are restored at the provider boundary, so dispatch, hooks,
184
+ * persistence, and other auth modes never see the alias.
185
+ */
186
+ function claudeCodeToolAliases(names) {
187
+ let aliases;
188
+ const taken = new Set(names);
189
+ for (const reserved of CLAUDE_CODE_RESERVED_TOOL_NAMES) {
190
+ if (!names.has(reserved)) continue;
191
+ let candidate = `${RESERVED_TOOL_ALIAS_PREFIX}${reserved}`;
192
+ for (let n = 2; taken.has(candidate); n++) candidate = `${RESERVED_TOOL_ALIAS_PREFIX}${reserved}_${n}`;
193
+ taken.add(candidate);
194
+ aliases ??= {};
195
+ aliases[reserved] = candidate;
196
+ }
197
+ return aliases;
198
+ }
199
+ /**
200
+ * Beta set the Claude Code agent sends, in client order.
201
+ *
202
+ * Sent as one unit: the endpoint is configured for this combination, and
203
+ * trimming it to "the ones we think we use" is how a client stops looking like
204
+ * the client. Betas without matching request fields are inert.
205
+ */
206
+ const CLAUDE_CODE_BETAS = [
207
+ "claude-code-20250219",
208
+ "oauth-2025-04-20",
209
+ "interleaved-thinking-2025-05-14",
210
+ "fine-grained-tool-streaming-2025-05-14",
211
+ "context-management-2025-06-27",
212
+ "prompt-caching-scope-2026-01-05",
213
+ "mid-conversation-system-2026-04-07",
214
+ "advanced-tool-use-2025-11-20",
215
+ "effort-2025-11-24",
216
+ "extended-cache-ttl-2025-04-11"
217
+ ];
218
+ /** Billing-header pins. See {@link claudeCodeBillingText}. */
219
+ const BILLING_FINGERPRINT_SALT = "59cf53e54c78";
220
+ const BILLING_FINGERPRINT_INDICES = [
221
+ 4,
222
+ 7,
223
+ 20
224
+ ];
225
+ const BILLING_HEADER_PREFIX = "x-anthropic-billing-header:";
226
+ const CCH_PLACEHOLDER = "cch=00000";
227
+ const CCH_SEED = 5577024349156291176n;
228
+ /** `os.arch()` values mapped to the labels Stainless emits. */
229
+ function stainlessArch(value) {
230
+ switch (value.toLowerCase()) {
231
+ case "amd64":
232
+ case "x64": return "x64";
233
+ case "arm64":
234
+ case "aarch64": return "arm64";
235
+ case "386":
236
+ case "x86":
237
+ case "ia32": return "x86";
238
+ default: return `other::${value.toLowerCase()}`;
239
+ }
240
+ }
241
+ /** `os.platform()` values mapped to the labels Stainless emits. */
242
+ function stainlessOs(value) {
243
+ switch (value.toLowerCase()) {
244
+ case "darwin": return "MacOS";
245
+ case "win32":
246
+ case "windows": return "Windows";
247
+ case "linux": return "Linux";
248
+ case "freebsd": return "FreeBSD";
249
+ default: return `Other::${value.toLowerCase()}`;
250
+ }
251
+ }
252
+ /**
253
+ * Headers a Claude Code OAuth request carries.
254
+ *
255
+ * The `x-stainless-*` entries deliberately OVERRIDE the ones the Anthropic SDK
256
+ * generates about itself: left alone they advertise `Anthropic/JS <sdk version>`
257
+ * on a request claiming to be the CLI, which is a contradiction no real client
258
+ * produces.
259
+ */
260
+ function buildClaudeCodeHeaders() {
261
+ return {
262
+ "user-agent": `claude-cli/${CLAUDE_CODE_VERSION} (external, local-agent, agent-sdk/${CLAUDE_AGENT_SDK_VERSION})`,
263
+ "x-app": "cli",
264
+ "anthropic-dangerous-direct-browser-access": "true",
265
+ "x-stainless-retry-count": "0",
266
+ "x-stainless-runtime-version": CLAUDE_CODE_STAINLESS_RUNTIME_VERSION,
267
+ "x-stainless-package-version": CLAUDE_CODE_STAINLESS_PACKAGE_VERSION,
268
+ "x-stainless-runtime": "node",
269
+ "x-stainless-lang": "js",
270
+ "x-stainless-arch": stainlessArch(arch()),
271
+ "x-stainless-os": stainlessOs(platform()),
272
+ "x-stainless-timeout": "900",
273
+ "anthropic-client-platform": "desktop_app",
274
+ "anthropic-client-version": CLAUDE_CLIENT_VERSION
275
+ };
276
+ }
277
+ /**
278
+ * Text of the `system[0]` billing block.
279
+ *
280
+ * The version suffix is `sha256(salt + msg[4] + msg[7] + msg[20] + version)`
281
+ * truncated to 3 hex chars, where the indices sample the first user message.
282
+ * Missing characters (a first message shorter than 21 chars) contribute `'0'`,
283
+ * matching the client rather than throwing.
284
+ *
285
+ * The `cch` field ships as {@link CCH_PLACEHOLDER} and is overwritten by
286
+ * {@link patchCch} once the body is serialized — it hashes those very bytes, so
287
+ * it cannot be computed here.
288
+ */
289
+ function claudeCodeBillingText(firstUserMessage) {
290
+ const seed = BILLING_FINGERPRINT_INDICES.map((i) => firstUserMessage[i] ?? "0").join("");
291
+ const suffix = createHash("sha256").update(`${BILLING_FINGERPRINT_SALT}${seed}${CLAUDE_CODE_VERSION}`).digest("hex").slice(0, 3);
292
+ return `${BILLING_HEADER_PREFIX} cc_version=${CLAUDE_CODE_VERSION}.${suffix}; cc_entrypoint=local-agent; ${CCH_PLACEHOLDER};`;
293
+ }
294
+ /** Concatenated text of the first user message — the fingerprint's sample source. */
295
+ function firstUserMessageText(messages) {
296
+ const content = messages.find((m) => m.role === "user")?.content;
297
+ if (typeof content === "string") return content;
298
+ if (!Array.isArray(content)) return "";
299
+ return content.filter((b) => !!b && typeof b === "object" && b.type === "text" && typeof b.text === "string").map((b) => b.text).join("");
300
+ }
301
+ /**
302
+ * Machine-stable device id + per-process session id, sent as
303
+ * `metadata.user_id`'s JSON envelope.
304
+ *
305
+ * `userInfo()` throws in locked-down sandboxes, so the seed degrades to the
306
+ * hostname rather than taking the process down.
307
+ */
308
+ function machineSeed() {
309
+ try {
310
+ return `${hostname()}:${userInfo().username}:${homedir()}`;
311
+ } catch {
312
+ return `${hostname()}:zidane-claude-code-fallback`;
313
+ }
314
+ }
315
+ const DEVICE_ID = createHash("sha256").update(`zidane-claude-code-device-v1:${machineSeed()}`).digest("hex");
316
+ const SESSION_ID = randomUUID();
317
+ /** The `metadata.user_id` envelope Claude Code sends. */
318
+ function claudeCodeUserId() {
319
+ return JSON.stringify({
320
+ device_id: DEVICE_ID,
321
+ session_id: SESSION_ID
322
+ });
323
+ }
324
+ const MASK = (1n << 64n) - 1n;
325
+ const PRIME64_1 = 11400714785074694791n;
326
+ const PRIME64_2 = 14029467366897019727n;
327
+ const PRIME64_3 = 1609587929392839161n;
328
+ const PRIME64_4 = 9650029242287828579n;
329
+ const PRIME64_5 = 2870177450012600261n;
330
+ const rotl = (x, r) => (x << r | x >> 64n - r) & MASK;
331
+ function round(acc, input) {
332
+ const next = acc + input * PRIME64_2 & MASK;
333
+ return rotl(next, 31n) * PRIME64_1 & MASK;
334
+ }
335
+ function mergeRound(acc, val) {
336
+ return ((acc ^ round(0n, val)) * PRIME64_1 & MASK) + PRIME64_4 & MASK;
337
+ }
338
+ /**
339
+ * XXH64, reproducing Claude Code's `cch` request-integrity value.
340
+ *
341
+ * Ported rather than delegated to `Bun.hash.xxHash64` so the result cannot
342
+ * drift with a runtime's hash implementation or seed handling, and so the
343
+ * provider still works off-Bun. Verified against published XXH64 vectors.
344
+ */
345
+ function xxHash64(input, seed) {
346
+ const len = input.length;
347
+ const dv = new DataView(input.buffer, input.byteOffset, input.byteLength);
348
+ let h64;
349
+ let p = 0;
350
+ if (len >= 32) {
351
+ let v1 = seed + PRIME64_1 + PRIME64_2 & MASK;
352
+ let v2 = seed + PRIME64_2 & MASK;
353
+ let v3 = seed & MASK;
354
+ let v4 = seed - PRIME64_1 & MASK;
355
+ const limit = len - 32;
356
+ while (p <= limit) {
357
+ v1 = round(v1, dv.getBigUint64(p, true));
358
+ p += 8;
359
+ v2 = round(v2, dv.getBigUint64(p, true));
360
+ p += 8;
361
+ v3 = round(v3, dv.getBigUint64(p, true));
362
+ p += 8;
363
+ v4 = round(v4, dv.getBigUint64(p, true));
364
+ p += 8;
365
+ }
366
+ h64 = rotl(v1, 1n) + rotl(v2, 7n) + rotl(v3, 12n) + rotl(v4, 18n) & MASK;
367
+ h64 = mergeRound(h64, v1);
368
+ h64 = mergeRound(h64, v2);
369
+ h64 = mergeRound(h64, v3);
370
+ h64 = mergeRound(h64, v4);
371
+ } else h64 = seed + PRIME64_5 & MASK;
372
+ h64 = h64 + BigInt(len) & MASK;
373
+ while (p + 8 <= len) {
374
+ h64 ^= round(0n, dv.getBigUint64(p, true));
375
+ h64 = rotl(h64, 27n) * PRIME64_1 & MASK;
376
+ h64 = h64 + PRIME64_4 & MASK;
377
+ p += 8;
378
+ }
379
+ if (p + 4 <= len) {
380
+ h64 ^= BigInt(dv.getUint32(p, true)) * PRIME64_1 & MASK;
381
+ h64 = rotl(h64, 23n) * PRIME64_2 & MASK;
382
+ h64 = h64 + PRIME64_3 & MASK;
383
+ p += 4;
384
+ }
385
+ while (p < len) {
386
+ h64 ^= BigInt(input[p] ?? 0) * PRIME64_5 & MASK;
387
+ h64 = rotl(h64, 11n) * PRIME64_1 & MASK;
388
+ p += 1;
389
+ }
390
+ h64 ^= h64 >> 33n;
391
+ h64 = h64 * PRIME64_2 & MASK;
392
+ h64 ^= h64 >> 29n;
393
+ h64 = h64 * PRIME64_3 & MASK;
394
+ h64 ^= h64 >> 32n;
395
+ return h64 & MASK;
396
+ }
397
+ const encoder = new TextEncoder();
398
+ /**
399
+ * Anchor for the placeholder search. The SDK serializes `messages` before
400
+ * `system`, so these bytes can only belong to the block we injected — user
401
+ * content that happens to contain `cch=00000` can never match.
402
+ */
403
+ const BILLING_SYSTEM_MARKER = encoder.encode(`"system":[{"type":"text","text":"${BILLING_HEADER_PREFIX}`);
404
+ const CCH_PLACEHOLDER_BYTES = encoder.encode(CCH_PLACEHOLDER);
405
+ /** The placeholder must sit this close to the marker, else system[0] was reshaped. */
406
+ const CCH_SEARCH_WINDOW = 150;
407
+ /**
408
+ * Overwrite the `cch` placeholder with `XXH64(body) & 0xfffff`, in place.
409
+ *
410
+ * Returns the original bytes untouched when the placeholder is absent or not
411
+ * anchored to `system[0]` — a request that goes out with the placeholder intact
412
+ * is far better than one whose user content was corrupted by a stray patch.
413
+ */
414
+ function patchCch(encoded) {
415
+ const view = Buffer.from(encoded.buffer, encoded.byteOffset, encoded.byteLength);
416
+ const markerIdx = view.indexOf(BILLING_SYSTEM_MARKER);
417
+ if (markerIdx === -1) return encoded;
418
+ const searchFrom = markerIdx + BILLING_SYSTEM_MARKER.length;
419
+ const placeholderIdx = view.indexOf(CCH_PLACEHOLDER_BYTES, searchFrom);
420
+ if (placeholderIdx === -1 || placeholderIdx - searchFrom > CCH_SEARCH_WINDOW) return encoded;
421
+ const cch = (xxHash64(encoded, CCH_SEED) & 1048575n).toString(16).padStart(5, "0");
422
+ for (let i = 0; i < 5; i++) encoded[placeholderIdx + 4 + i] = cch.charCodeAt(i);
423
+ return encoded;
424
+ }
425
+ /**
426
+ * Wrap a `fetch` so bodies carrying the placeholder get their attestation
427
+ * patched after serialization.
428
+ *
429
+ * Handed to the Anthropic SDK per client rather than installed on
430
+ * `globalThis` — every other request in the process stays untouched, and two
431
+ * providers cannot fight over the global.
432
+ */
433
+ function wrapFetchForCch(base) {
434
+ const wrapped = (input, init) => {
435
+ const body = init?.body;
436
+ let finalBody = body;
437
+ if (typeof body === "string" && body.includes("cch=00000")) finalBody = patchCch(encoder.encode(body));
438
+ return base(input, finalBody === body ? init : {
439
+ ...init,
440
+ body: finalBody
441
+ });
442
+ };
443
+ wrapped.preconnect = base.preconnect?.bind(base) ?? (() => {});
444
+ return wrapped;
445
+ }
446
+ //#endregion
126
447
  //#region src/providers/anthropic.ts
127
448
  const loadAnthropicSdk = lazyAsync(async () => {
128
449
  try {
@@ -156,23 +477,15 @@ function normalizeBedrock(value) {
156
477
  if (!value) return void 0;
157
478
  return value === true ? {} : value;
158
479
  }
159
- /** Beta flags sent unconditionally on the OAuth path (Claude Code parity). */
160
- const OAUTH_DEFAULT_BETAS = ["claude-code-20250219", "oauth-2025-04-20"];
161
480
  /**
162
- * Claude Code identity advertised on subscription-OAuth requests. Anthropic's
163
- * subscription endpoint checks the Claude CLI identity; zidane's package
164
- * version is not a compatible user agent.
481
+ * Beta flags sent unconditionally on the OAuth path (Claude Code parity).
165
482
  *
166
- * Mirrors `claudeCodeVersion` in the pinned pi-ai
167
- * (`@earendil-works/pi-ai@0.84.2`, `dist/api/anthropic-messages.js`), which is
168
- * module-private there — there is no constant to import, so this has to be
169
- * re-checked by hand whenever pi-ai is bumped. The version is named here so
170
- * that check has an anchor instead of "the pinned release".
171
- *
172
- * Note this is parity-improving, not parity-complete: the SDK still stamps its
173
- * own `X-Stainless-*` platform headers, which the real CLI does not send.
483
+ * The full client set, sent as one unit — see `CLAUDE_CODE_BETAS`. Betas whose
484
+ * request fields we never populate are inert, so the cost of matching the
485
+ * client exactly is nil while the cost of guessing a subset is looking like a
486
+ * different client.
174
487
  */
175
- const CLAUDE_CODE_USER_AGENT = "claude-cli/2.1.75";
488
+ const OAUTH_DEFAULT_BETAS = CLAUDE_CODE_BETAS;
176
489
  /**
177
490
  * Beta flag that enables the `speed: "fast"` request field (fast mode — up to
178
491
  * 2.5× output tokens/sec at premium pricing; supported models are enumerated
@@ -187,6 +500,16 @@ const API_KEY_RESERVED_EXTRA_HEADER_NAMES = /* @__PURE__ */ new Set(["anthropic-
187
500
  const OAUTH_RESERVED_EXTRA_HEADER_NAMES = /* @__PURE__ */ new Set([
188
501
  "accept",
189
502
  "anthropic-beta",
503
+ "anthropic-client-platform",
504
+ "anthropic-client-version",
505
+ "x-stainless-arch",
506
+ "x-stainless-lang",
507
+ "x-stainless-os",
508
+ "x-stainless-package-version",
509
+ "x-stainless-retry-count",
510
+ "x-stainless-runtime",
511
+ "x-stainless-runtime-version",
512
+ "x-stainless-timeout",
190
513
  "anthropic-dangerous-direct-browser-access",
191
514
  "user-agent",
192
515
  "x-app"
@@ -296,10 +619,8 @@ function buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHea
296
619
  if (auth.claudeCode) {
297
620
  const defaultHeaders = {
298
621
  ...filterReservedExtraHeaders(extraHeaders, OAUTH_RESERVED_EXTRA_HEADER_NAMES),
299
- "accept": "application/json",
300
- "anthropic-dangerous-direct-browser-access": "true",
301
- "user-agent": CLAUDE_CODE_USER_AGENT,
302
- "x-app": "cli"
622
+ accept: "application/json",
623
+ ...buildClaudeCodeHeaders()
303
624
  };
304
625
  if (betaHeader) defaultHeaders["anthropic-beta"] = betaHeader;
305
626
  return {
@@ -307,6 +628,7 @@ function buildAnthropicClientOptions(apiKey, auth, baseURL, extraBetas, extraHea
307
628
  authToken: apiKey,
308
629
  dangerouslyAllowBrowser: true,
309
630
  defaultHeaders,
631
+ fetch: wrapFetchForCch(globalThis.fetch),
310
632
  ...base
311
633
  };
312
634
  }
@@ -1086,7 +1408,7 @@ function anthropic(anthropicParams) {
1086
1408
  ...payload.messages
1087
1409
  ] : [...payload.messages];
1088
1410
  const countTools = payload.tools;
1089
- const countBoundary = createToolNameBoundary(messages, countTools.map((t) => t.name));
1411
+ const countBoundary = createToolNameBoundary(messages, countTools.map((t) => t.name), callIsOAuth ? claudeCodeToolAliases : void 0);
1090
1412
  return (await client.messages.countTokens({
1091
1413
  model: payload.model,
1092
1414
  system,
@@ -1150,8 +1472,9 @@ function anthropic(anthropicParams) {
1150
1472
  * far — `callAuth.bearer` is false for both.
1151
1473
  */
1152
1474
  const callCanRotateAuth = callAuth.bearer;
1153
- const extendedTtl = options.cache !== false && options.cacheTtl === "1h" && !callIsOAuth && !bedrockConfig;
1154
- const conditionalBetas = [...options.modelOptions?.fast ? [FAST_MODE_BETA] : [], ...extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []];
1475
+ const effectiveCacheTtl = options.cacheTtl ?? (callIsOAuth ? "1h" : void 0);
1476
+ const extendedTtl = options.cache !== false && effectiveCacheTtl === "1h" && !bedrockConfig;
1477
+ const conditionalBetas = [...options.modelOptions?.fast && !callIsOAuth ? [FAST_MODE_BETA] : [], ...extendedTtl ? [EXTENDED_CACHE_TTL_BETA] : []];
1155
1478
  const requestBetas = conditionalBetas.length > 0 ? [...anthropicParams?.extraBetas ?? [], ...conditionalBetas] : anthropicParams?.extraBetas;
1156
1479
  const resolvedExtraHeaders = await resolveExtraHeaders(anthropicParams?.extraHeaders);
1157
1480
  let client = bedrockConfig ? await createBedrockClient(bedrockConfig, anthropicParams, resolvedExtraHeaders) : createClient(await loadAnthropicSdk(), apiKey, callAuth, anthropicParams?.baseURL, requestBetas, resolvedExtraHeaders);
@@ -1176,7 +1499,7 @@ function anthropic(anthropicParams) {
1176
1499
  ] : [...options.messages];
1177
1500
  const thinking = options.thinking ?? "off";
1178
1501
  const inputTools = options.tools ?? [];
1179
- const nameBoundary = createToolNameBoundary(messages, inputTools.map((t) => t.name));
1502
+ const nameBoundary = createToolNameBoundary(messages, inputTools.map((t) => t.name), callIsOAuth ? claudeCodeToolAliases : void 0);
1180
1503
  const wireTools = nameBoundary.changed ? inputTools.map((t) => t.name === nameBoundary.toWire(t.name) ? t : {
1181
1504
  ...t,
1182
1505
  name: nameBoundary.toWire(t.name)
@@ -1193,7 +1516,7 @@ function anthropic(anthropicParams) {
1193
1516
  stream: true
1194
1517
  };
1195
1518
  if (anthropicParams?.contextManagement && !bedrockConfig) params.context_management = anthropicParams.contextManagement;
1196
- if (options.cache !== false) applyAnthropicCacheBreakpoints(params, callIsOAuth ? void 0 : options.system, extendedTtl ? options.cacheTtl : void 0);
1519
+ if (options.cache !== false) applyAnthropicCacheBreakpoints(params, callIsOAuth ? void 0 : options.system, extendedTtl ? effectiveCacheTtl : void 0);
1197
1520
  const plan = planAnthropicThinking(thinking, options.thinkingBudget, options.taskBudget, options.effortHint !== false);
1198
1521
  if (plan && bedrockConfig) {
1199
1522
  const budget = plan.kind === "enabled" ? plan.budgetTokens : BEDROCK_THINKING_BUDGETS[plan.effort ?? "medium"];
@@ -1235,6 +1558,17 @@ function anthropic(anthropicParams) {
1235
1558
  params.temperature = 1;
1236
1559
  }
1237
1560
  params.max_tokens = Math.min(params.max_tokens, modelMaxOutput);
1561
+ if (callIsOAuth) {
1562
+ params.max_tokens = Math.min(params.max_tokens, CLAUDE_CODE_MAX_OUTPUT_TOKENS);
1563
+ if (Array.isArray(params.system)) params.system = [{
1564
+ type: "text",
1565
+ text: claudeCodeBillingText(firstUserMessageText(params.messages))
1566
+ }, ...params.system];
1567
+ if (typeof params.metadata?.user_id !== "string") params.metadata = {
1568
+ ...params.metadata,
1569
+ user_id: claudeCodeUserId()
1570
+ };
1571
+ }
1238
1572
  if (params.thinking?.type === "enabled" && params.thinking.budget_tokens >= params.max_tokens) {
1239
1573
  const fitted = params.max_tokens - THINKING_RESPONSE_RESERVE_TOKENS;
1240
1574
  if (fitted >= 1024) params.thinking.budget_tokens = fitted;
@@ -1243,7 +1577,7 @@ function anthropic(anthropicParams) {
1243
1577
  delete params.temperature;
1244
1578
  }
1245
1579
  }
1246
- if (options.modelOptions?.fast) params.speed = "fast";
1580
+ if (options.modelOptions?.fast && !callIsOAuth) params.speed = "fast";
1247
1581
  if (options.toolChoice) if (options.toolChoice.type === "tool" && options.toolChoice.name) params.tool_choice = {
1248
1582
  type: "tool",
1249
1583
  name: nameBoundary.toWire(options.toolChoice.name)
@@ -1373,11 +1707,11 @@ function anthropic(anthropicParams) {
1373
1707
  usage
1374
1708
  };
1375
1709
  };
1376
- return await runStream(params, options.modelOptions?.fast === true);
1710
+ return await runStream(params, options.modelOptions?.fast === true && !callIsOAuth);
1377
1711
  }
1378
1712
  };
1379
1713
  }
1380
1714
  //#endregion
1381
1715
  export { classifyAnthropicError as a, planAnthropicThinking as c, resolveAnthropicMaxOutput as d, ANTHROPIC_EXTRA_MODELS as f, buildAnthropicClientOptions as i, resolveAnthropicAuthShape as l, anthropic as n, credentialIdentity as o, FAST_MODE_OPTIONS as p, applyAnthropicCacheBreakpoints as r, defaultAnthropicMaxTokens as s, EXTENDED_CACHE_TTL_BETA as t, resolveAnthropicBetas as u };
1382
1716
 
1383
- //# sourceMappingURL=anthropic-D3le2d-s.js.map
1717
+ //# sourceMappingURL=anthropic-DLc_Kw-1.js.map