@tormentalabs/claude-code-wire-compat 0.7.1 → 0.8.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.
Files changed (88) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +27 -4
  3. package/dist/account-features.d.ts +11 -0
  4. package/dist/account-features.d.ts.map +1 -0
  5. package/dist/account-features.js +98 -0
  6. package/dist/account-features.js.map +1 -0
  7. package/dist/anti-verbosity.d.ts.map +1 -1
  8. package/dist/anti-verbosity.js +3 -3
  9. package/dist/anti-verbosity.js.map +1 -1
  10. package/dist/betas.d.ts +74 -2
  11. package/dist/betas.d.ts.map +1 -1
  12. package/dist/betas.js +158 -18
  13. package/dist/betas.js.map +1 -1
  14. package/dist/build-request.d.ts.map +1 -1
  15. package/dist/build-request.js +201 -19
  16. package/dist/build-request.js.map +1 -1
  17. package/dist/contracts.d.ts +181 -2
  18. package/dist/contracts.d.ts.map +1 -1
  19. package/dist/contracts.js.map +1 -1
  20. package/dist/fingerprint.d.ts +28 -5
  21. package/dist/fingerprint.d.ts.map +1 -1
  22. package/dist/fingerprint.js +63 -5
  23. package/dist/fingerprint.js.map +1 -1
  24. package/dist/headers.d.ts +60 -1
  25. package/dist/headers.d.ts.map +1 -1
  26. package/dist/headers.js +176 -23
  27. package/dist/headers.js.map +1 -1
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +3 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/model-capabilities.d.ts +8 -4
  33. package/dist/model-capabilities.d.ts.map +1 -1
  34. package/dist/model-capabilities.js +14 -7
  35. package/dist/model-capabilities.js.map +1 -1
  36. package/dist/model-identity.d.ts +15 -2
  37. package/dist/model-identity.d.ts.map +1 -1
  38. package/dist/model-identity.js +44 -1
  39. package/dist/model-identity.js.map +1 -1
  40. package/dist/model-queries.d.ts +11 -1
  41. package/dist/model-queries.d.ts.map +1 -1
  42. package/dist/model-queries.js +51 -7
  43. package/dist/model-queries.js.map +1 -1
  44. package/dist/models.d.ts.map +1 -1
  45. package/dist/models.js +2 -2
  46. package/dist/models.js.map +1 -1
  47. package/dist/profile-behaviors.d.ts +72 -0
  48. package/dist/profile-behaviors.d.ts.map +1 -1
  49. package/dist/profile-behaviors.js +66 -15
  50. package/dist/profile-behaviors.js.map +1 -1
  51. package/dist/profiles/beta-registry-2.1.329.d.ts +229 -0
  52. package/dist/profiles/beta-registry-2.1.329.d.ts.map +1 -0
  53. package/dist/profiles/beta-registry-2.1.329.js +281 -0
  54. package/dist/profiles/beta-registry-2.1.329.js.map +1 -0
  55. package/dist/profiles/claude-code-2.1.329.d.ts +3 -0
  56. package/dist/profiles/claude-code-2.1.329.d.ts.map +1 -0
  57. package/dist/profiles/claude-code-2.1.329.js +466 -0
  58. package/dist/profiles/claude-code-2.1.329.js.map +1 -0
  59. package/dist/redaction.d.ts.map +1 -1
  60. package/dist/redaction.js +1 -0
  61. package/dist/redaction.js.map +1 -1
  62. package/dist/request-body.d.ts +27 -1
  63. package/dist/request-body.d.ts.map +1 -1
  64. package/dist/request-body.js +184 -16
  65. package/dist/request-body.js.map +1 -1
  66. package/dist/tools-used.d.ts +52 -0
  67. package/dist/tools-used.d.ts.map +1 -0
  68. package/dist/tools-used.js +116 -0
  69. package/dist/tools-used.js.map +1 -0
  70. package/package.json +5 -1
  71. package/src/account-features.ts +114 -0
  72. package/src/anti-verbosity.ts +8 -3
  73. package/src/betas.ts +252 -22
  74. package/src/build-request.ts +245 -22
  75. package/src/contracts.ts +185 -3
  76. package/src/fingerprint.ts +84 -7
  77. package/src/headers.ts +221 -21
  78. package/src/index.ts +10 -0
  79. package/src/model-capabilities.ts +16 -7
  80. package/src/model-identity.ts +62 -2
  81. package/src/model-queries.ts +71 -8
  82. package/src/models.ts +2 -1
  83. package/src/profile-behaviors.ts +150 -16
  84. package/src/profiles/beta-registry-2.1.329.ts +298 -0
  85. package/src/profiles/claude-code-2.1.329.ts +471 -0
  86. package/src/redaction.ts +1 -0
  87. package/src/request-body.ts +242 -17
  88. package/src/tools-used.ts +134 -0
@@ -16,17 +16,55 @@ const PREVIOUS_REQUEST_ID_PATTERN = /^req_[A-Za-z0-9_-]{1,36}$/;
16
16
  /**
17
17
  * Upstream guard on `cc_prompt_id`, transcribed verbatim from the same builder.
18
18
  * The `i` flag is upstream's, not a relaxation: an upper-case UUID IS emitted.
19
+ * Exported because the 2.1.329 header layout guards `x-claude-code-prompt-id`
20
+ * with the same pattern.
19
21
  */
20
- const PROMPT_ID_PATTERN =
22
+ export const PROMPT_ID_PATTERN =
21
23
  /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
22
24
 
23
25
  /**
24
- * The conversation-chaining inputs of the 2.1.233 billing block. Both are the
25
- * caller's to supply; see `ClaudeCodeRequestInput.previousRequestId`.
26
+ * Shape of the `cch` value: exactly five lowercase hexadecimal characters.
27
+ * Exported so the input validator and the block builder share one definition.
28
+ */
29
+ export const CCH_PATTERN = /^[0-9a-f]{5}$/u;
30
+
31
+ /**
32
+ * Upstream guard on `cc_turn_origin` (2.1.329 billing builder, view line
33
+ * 115131): a lowercase letter followed by up to 31 lowercase letters or
34
+ * underscores.
35
+ */
36
+ const TURN_ORIGIN_PATTERN = /^[a-z][a-z_]{0,31}$/;
37
+
38
+ /**
39
+ * Upstream integer guard `xu` (2.1.329 bundle, view line 115141): a finite
40
+ * integer number from `minimum` to ten million inclusive.
41
+ */
42
+ function isBoundedInteger(value: unknown, minimum: number): value is number {
43
+ return (
44
+ typeof value === "number" &&
45
+ Number.isInteger(value) &&
46
+ value >= minimum &&
47
+ value <= 1e7
48
+ );
49
+ }
50
+
51
+ /**
52
+ * The conversation-chaining inputs of the billing block. All are the caller's
53
+ * to supply; see `ClaudeCodeRequestInput.previousRequestId`.
54
+ *
55
+ * `cch` replaces the placeholder checksum value and is honoured by every
56
+ * profile. `turnOrigin` and `turnPosition` feed the turn segments that only the
57
+ * `billingTurnSegments` behaviour emits.
26
58
  */
27
59
  export interface BillingChain {
28
60
  readonly previousRequestId?: string;
29
61
  readonly promptId?: string;
62
+ readonly cch?: string;
63
+ readonly turnOrigin?: string;
64
+ readonly turnPosition?: {
65
+ readonly promptIndex: number;
66
+ readonly turnIndex: number;
67
+ };
30
68
  }
31
69
 
32
70
  function isCryptoProvider(value: unknown): value is Pick<Crypto, "subtle"> {
@@ -103,9 +141,10 @@ export async function createBillingFingerprint(
103
141
  *
104
142
  * Three of those five are settled for every request this package emits:
105
143
  *
106
- * - `cch=00000;` is always present. Its gate is the first-party predicate,
107
- * which is true for the Anthropic provider this package targets, and its
108
- * value is static — the upstream hashed-cache path is dead code.
144
+ * - `cch=…;` is always present. Its gate is the first-party predicate,
145
+ * which is true for the Anthropic provider this package targets. Its value
146
+ * is the placeholder `00000` unless the caller supplies its own five
147
+ * lowercase hexadecimal characters through `BillingChain.cch`.
109
148
  * - `cc_workload` and `cc_is_subagent` are never emitted. They describe a
110
149
  * background workload and a sub-agent session respectively; this package
111
150
  * models the CLI's main session, which has neither. Same position as
@@ -126,7 +165,19 @@ export async function createBillingBlock(
126
165
  crypto,
127
166
  );
128
167
 
129
- let text = `x-anthropic-billing-header: cc_version=${cliVersion}.${fingerprint}; cc_entrypoint=${entrypoint}; cch=00000;`;
168
+ /*
169
+ * The checksum value is the caller's to supply when it has computed one;
170
+ * otherwise the placeholder every earlier release emitted, so a request
171
+ * built without it is byte-identical to before. It is the only caller bytes
172
+ * in this position, so a value that is not five lowercase hexadecimal
173
+ * characters is refused rather than interpolated.
174
+ */
175
+ const cch = chain?.cch ?? "00000";
176
+ if (!CCH_PATTERN.test(cch)) {
177
+ throw new ClaudeCodeWireError("INVALID_INPUT", { field: "cch" });
178
+ }
179
+
180
+ let text = `x-anthropic-billing-header: cc_version=${cliVersion}.${fingerprint}; cc_entrypoint=${entrypoint}; cch=${cch};`;
130
181
 
131
182
  /*
132
183
  * ---- Demarcated: conversation chaining, upstream 2.1.233. ----
@@ -156,5 +207,31 @@ export async function createBillingBlock(
156
207
  }
157
208
  }
158
209
 
210
+ /*
211
+ * ---- Demarcated: turn origin and turn position, upstream 2.1.329. ----
212
+ *
213
+ * Two segments follow `cc_prompt_id`, each guarded independently and each
214
+ * dropped silently when its value fails the guard (a malformed value must
215
+ * not reach the wire in any form). The origin names who started the turn;
216
+ * the position pair is emitted only when BOTH indexes hold: the prompt index
217
+ * from 0 and the turn index from 1, each an integer no greater than ten
218
+ * million. A profile without the behaviour has no parameter for either, so
219
+ * it never emits them, whatever the caller supplies.
220
+ */
221
+ if (profileBehaviors(profile).billingTurnSegments) {
222
+ const turnOrigin = chain?.turnOrigin;
223
+ if (
224
+ typeof turnOrigin === "string" &&
225
+ TURN_ORIGIN_PATTERN.test(turnOrigin)
226
+ ) {
227
+ text += ` cc_turn_origin=${turnOrigin};`;
228
+ }
229
+ const promptIndex = chain?.turnPosition?.promptIndex;
230
+ const turnIndex = chain?.turnPosition?.turnIndex;
231
+ if (isBoundedInteger(promptIndex, 0) && isBoundedInteger(turnIndex, 1)) {
232
+ text += ` cc_prompt_index=${String(promptIndex)}; cc_turn_index=${String(turnIndex)};`;
233
+ }
234
+ }
235
+
159
236
  return { type: "text", text };
160
237
  }
package/src/headers.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // SPDX-License-Identifier: GPL-3.0-or-later
2
2
 
3
3
  import type {
4
+ ClaudeCodeDispatchId,
4
5
  ClaudeCodeExtraHeaderPolicy,
5
6
  ClaudeCodeProtocolProfile,
6
7
  HeaderPair,
@@ -9,6 +10,11 @@ import { ClaudeCodeWireError } from "./contracts.js";
9
10
  import { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
10
11
  import { CLAUDE_CODE_2_1_233_PROFILE } from "./profiles/claude-code-2.1.233.js";
11
12
  import { CLAUDE_CODE_2_1_280_PROFILE } from "./profiles/claude-code-2.1.280.js";
13
+ import { CLAUDE_CODE_2_1_329_PROFILE } from "./profiles/claude-code-2.1.329.js";
14
+ import { PROMPT_ID_PATTERN } from "./fingerprint.js";
15
+ import { profileBehaviors } from "./profile-behaviors.js";
16
+ import type { ToolsUsedEntry } from "./tools-used.js";
17
+ import { serializeToolsUsed, validateToolsUsed } from "./tools-used.js";
12
18
 
13
19
  const HEADER_NAMES = Object.freeze({
14
20
  anthropicBeta: "anthropic-beta",
@@ -35,10 +41,86 @@ const HEADER_NAMES = Object.freeze({
35
41
  additionalProtection: "x-anthropic-additional-protection",
36
42
  } as const);
37
43
 
44
+ /** The names a header layout owns, keyed by role. */
45
+ export type HeaderNameTable = {
46
+ readonly [K in keyof typeof HEADER_NAMES]: string;
47
+ };
48
+
49
+ /** The genuine layout adds the names the legacy layout never emits. */
50
+ export type GenuineHeaderNameTable = HeaderNameTable & {
51
+ readonly accept: string;
52
+ readonly dispatchId: string;
53
+ readonly requestClass1p: string;
54
+ readonly requestClass: string;
55
+ readonly promptId: string;
56
+ readonly sandyPlover: string;
57
+ };
58
+
59
+ /**
60
+ * Header names as the genuine 2.1.329 client writes them (live capture): the
61
+ * HTTP-standard names and the `User-Agent`/`X-Claude-Code-Session-Id`/
62
+ * `X-Stainless-*` set are capitalised, everything the Anthropic SDK and the
63
+ * client add on top is lowercase. The dynamic headers keep their lowercase
64
+ * names.
65
+ *
66
+ * The casing only survives on a case-preserving transport (for example Bun);
67
+ * Node's undici lowercases every name before it reaches the wire. This table
68
+ * records what the genuine client hands its transport; it does not change what
69
+ * a lowercasing transport sends.
70
+ */
71
+ export const GENUINE_HEADER_NAMES: GenuineHeaderNameTable = Object.freeze({
72
+ ...HEADER_NAMES,
73
+ accept: "Accept",
74
+ authorization: "Authorization",
75
+ contentType: "Content-Type",
76
+ userAgent: "User-Agent",
77
+ sessionId: "X-Claude-Code-Session-Id",
78
+ arch: "X-Stainless-Arch",
79
+ lang: "X-Stainless-Lang",
80
+ os: "X-Stainless-OS",
81
+ packageVersion: "X-Stainless-Package-Version",
82
+ retryCount: "X-Stainless-Retry-Count",
83
+ runtime: "X-Stainless-Runtime",
84
+ runtimeVersion: "X-Stainless-Runtime-Version",
85
+ timeout: "X-Stainless-Timeout",
86
+ dispatchId: "anthropic-dispatch-id",
87
+ requestClass1p: "x-claude-1p-request-class",
88
+ requestClass: "x-claude-code-request-class",
89
+ promptId: "x-claude-code-prompt-id",
90
+ sandyPlover: "x-claude-code-sandy-plover",
91
+ });
92
+
93
+ /** Resolves the header name table of the layout a profile follows. */
94
+ export function headerNamesFor(
95
+ profile: ClaudeCodeProtocolProfile,
96
+ ): HeaderNameTable | GenuineHeaderNameTable {
97
+ return profileBehaviors(profile).genuineHeaderLayout
98
+ ? GENUINE_HEADER_NAMES
99
+ : HEADER_NAMES;
100
+ }
101
+
102
+ /** The names a caller may never supply under the legacy layout. */
38
103
  const CANONICAL_NAMES: ReadonlySet<string> = new Set(
39
104
  Object.values(HEADER_NAMES),
40
105
  );
41
106
 
107
+ /**
108
+ * The names a caller may never supply under the genuine layout, lowercased:
109
+ * the whole table (so every capitalisation variant is refused), which includes
110
+ * `anthropic-dispatch-id` whether or not the request carries it.
111
+ */
112
+ export const GENUINE_RESERVED_NAMES: ReadonlySet<string> = new Set(
113
+ Object.values(GENUINE_HEADER_NAMES).map((name) => name.toLowerCase()),
114
+ );
115
+
116
+ /** Compares two header names by UTF-16 code unit, as a plain `<` does. */
117
+ function compareNames(left: string, right: string): number {
118
+ if (left < right) return -1;
119
+ return left > right ? 1 : 0;
120
+ }
121
+
122
+ type RequestKind = "messages" | "count_tokens";
123
+
42
124
  interface HeaderRuntime {
43
125
  readonly sessionId: string;
44
126
  readonly runtime: string;
@@ -62,6 +144,10 @@ interface ValidatedInput {
62
144
  readonly extraHeaders: readonly HeaderPair[];
63
145
  readonly extraHeaderPolicy: ClaudeCodeExtraHeaderPolicy;
64
146
  readonly profile: ClaudeCodeProtocolProfile;
147
+ readonly requestKind: RequestKind;
148
+ readonly promptId?: string;
149
+ readonly toolsUsed: readonly ToolsUsedEntry[];
150
+ readonly dispatchId?: ClaudeCodeDispatchId;
65
151
  }
66
152
 
67
153
  /** Reports the headers placed on the wire plus what the policy discarded. */
@@ -172,6 +258,7 @@ function parseProfile(value: unknown): ClaudeCodeProtocolProfile {
172
258
  if (value === CLAUDE_CODE_2_1_195_PROFILE) return CLAUDE_CODE_2_1_195_PROFILE;
173
259
  if (value === CLAUDE_CODE_2_1_233_PROFILE) return CLAUDE_CODE_2_1_233_PROFILE;
174
260
  if (value === CLAUDE_CODE_2_1_280_PROFILE) return CLAUDE_CODE_2_1_280_PROFILE;
261
+ if (value === CLAUDE_CODE_2_1_329_PROFILE) return CLAUDE_CODE_2_1_329_PROFILE;
175
262
  throw new ClaudeCodeWireError("INVALID_INPUT");
176
263
  }
177
264
 
@@ -201,10 +288,48 @@ function optionalHeaderString(
201
288
  return value;
202
289
  }
203
290
 
291
+ function parseRequestKind(value: unknown): RequestKind {
292
+ if (value === undefined) return "messages";
293
+ if (value !== "messages" && value !== "count_tokens") {
294
+ throw new ClaudeCodeWireError("INVALID_INPUT");
295
+ }
296
+ return value;
297
+ }
298
+
299
+ /**
300
+ * The prompt id is only ever a string; its FORMAT is checked at emission
301
+ * (`PROMPT_ID_PATTERN`), where a value upstream cannot vouch for is dropped
302
+ * silently, so an empty or malformed string is not an error here.
303
+ */
304
+ function parseOptionalPromptId(value: unknown): string | undefined {
305
+ if (value === undefined) return undefined;
306
+ if (typeof value !== "string") {
307
+ throw new ClaudeCodeWireError("INVALID_INPUT");
308
+ }
309
+ return value;
310
+ }
311
+
312
+ /**
313
+ * The dispatch id is a closed domain; unlike the prompt id there is no
314
+ * upstream emission guard that silently drops a bad value, so a stray one is a
315
+ * caller bug.
316
+ */
317
+ function parseOptionalDispatchId(
318
+ value: unknown,
319
+ ): ClaudeCodeDispatchId | undefined {
320
+ if (value === undefined) return undefined;
321
+ if (value !== "v2d" && value !== "v2s" && value !== "v2p") {
322
+ throw new ClaudeCodeWireError("INVALID_INPUT");
323
+ }
324
+ return value;
325
+ }
326
+
204
327
  function parseInput(input: unknown): ValidatedInput {
205
328
  if (!isRecord(input)) {
206
329
  throw new ClaudeCodeWireError("INVALID_INPUT");
207
330
  }
331
+ const promptId = parseOptionalPromptId(input["promptId"]);
332
+ const dispatchId = parseOptionalDispatchId(input["dispatchId"]);
208
333
  const stainlessHelper = optionalHeaderString(input, "stainlessHelper");
209
334
  const claudeRemoteContainerId = optionalHeaderString(
210
335
  input,
@@ -235,6 +360,13 @@ function parseInput(input: unknown): ValidatedInput {
235
360
  input["extraHeaderPolicy"] ?? "strict",
236
361
  ),
237
362
  profile: parseProfile(input["profile"]),
363
+ requestKind: parseRequestKind(input["requestKind"]),
364
+ toolsUsed:
365
+ input["toolsUsed"] === undefined
366
+ ? []
367
+ : validateToolsUsed(input["toolsUsed"]),
368
+ ...(promptId === undefined ? {} : { promptId }),
369
+ ...(dispatchId === undefined ? {} : { dispatchId }),
238
370
  ...(stainlessHelper === undefined ? {} : { stainlessHelper }),
239
371
  ...(claudeRemoteContainerId === undefined
240
372
  ? {}
@@ -319,6 +451,7 @@ function resolveExtraHeaders(
319
451
  extraHeaders: readonly HeaderPair[],
320
452
  accessToken: string,
321
453
  policy: ClaudeCodeExtraHeaderPolicy,
454
+ canonicalNames: ReadonlySet<string>,
322
455
  ): ResolvedExtraHeaders {
323
456
  const seenExtras = new Set<string>();
324
457
  const kept: HeaderPair[] = [];
@@ -329,7 +462,7 @@ function resolveExtraHeaders(
329
462
  const safeName = safeDiagnosticName(normalizedName, accessToken);
330
463
  const ownershipConflict = isForbiddenHeader(normalizedName)
331
464
  ? "FORBIDDEN_HEADER"
332
- : CANONICAL_NAMES.has(normalizedName)
465
+ : canonicalNames.has(normalizedName)
333
466
  ? "DUPLICATE_HEADER"
334
467
  : undefined;
335
468
  if (ownershipConflict !== undefined) {
@@ -362,12 +495,70 @@ function assertTokenIsolation(
362
495
  accessToken: string,
363
496
  ): void {
364
497
  for (const [name, value] of pairs) {
365
- if (name !== HEADER_NAMES.authorization && value.includes(accessToken)) {
498
+ // Lowercased so the capitalised genuine `Authorization` is exempt too.
499
+ if (
500
+ name.toLowerCase() !== HEADER_NAMES.authorization &&
501
+ value.includes(accessToken)
502
+ ) {
366
503
  throw new ClaudeCodeWireError("INVALID_INPUT");
367
504
  }
368
505
  }
369
506
  }
370
507
 
508
+ /**
509
+ * The built-in pairs of the genuine layout, in no particular order (the caller
510
+ * sorts). `count_tokens` requests carry neither the request-class pair, the
511
+ * prompt id, the tools-used header nor the dispatch id.
512
+ */
513
+ function genuineHeaderValues(
514
+ validated: ValidatedInput,
515
+ beta: string,
516
+ ): (readonly [string, string])[] {
517
+ const names = GENUINE_HEADER_NAMES;
518
+ const values: (readonly [string, string])[] = [
519
+ [names.accept, "application/json"],
520
+ [names.authorization, `Bearer ${validated.accessToken}`],
521
+ [names.contentType, "application/json"],
522
+ [names.userAgent, validated.profile.userAgent],
523
+ [names.sessionId, validated.runtime.sessionId],
524
+ [names.arch, validated.runtime.arch],
525
+ [names.lang, "js"],
526
+ [names.os, validated.runtime.os],
527
+ [names.packageVersion, validated.profile.sdkVersion],
528
+ [names.retryCount, String(validated.stainlessRetryCount)],
529
+ [names.runtime, validated.runtime.runtime],
530
+ [names.runtimeVersion, validated.runtime.runtimeVersion],
531
+ [names.timeout, "600"],
532
+ [names.anthropicBeta, beta],
533
+ [names.browserAccess, "true"],
534
+ [names.anthropicVersion, validated.profile.anthropicVersion],
535
+ [names.app, validated.app],
536
+ [names.clientRequestId, validated.clientRequestId],
537
+ ];
538
+ if (validated.requestKind === "messages") {
539
+ // Account-served: only on a caller's explicit opt-in, and never on
540
+ // count-tokens. Sorts between the browser-access and version headers.
541
+ if (
542
+ validated.dispatchId !== undefined &&
543
+ profileBehaviors(validated.profile).accountServedInputs
544
+ ) {
545
+ values.push([names.dispatchId, validated.dispatchId]);
546
+ }
547
+ values.push(
548
+ [names.requestClass1p, "main"],
549
+ [names.requestClass, "main"],
550
+ [names.sandyPlover, serializeToolsUsed(validated.toolsUsed)],
551
+ );
552
+ if (
553
+ validated.promptId !== undefined &&
554
+ PROMPT_ID_PATTERN.test(validated.promptId)
555
+ ) {
556
+ values.push([names.promptId, validated.promptId]);
557
+ }
558
+ }
559
+ return values;
560
+ }
561
+
371
562
  /**
372
563
  * Builds the pinned canonical logical header list together with the audit of
373
564
  * whatever the extra-header policy discarded.
@@ -385,32 +576,36 @@ export function buildOrderedHeaderPlan(input: unknown): OrderedHeaderPlan {
385
576
  Object.hasOwn(input, "clientApp") ||
386
577
  Object.hasOwn(input, "anthropicAdditionalProtection"));
387
578
  const validated = parseInput(input);
579
+ const layout = profileBehaviors(validated.profile).genuineHeaderLayout;
388
580
  const resolvedExtras = resolveExtraHeaders(
389
581
  validated.extraHeaders,
390
582
  validated.accessToken,
391
583
  validated.extraHeaderPolicy,
584
+ layout ? GENUINE_RESERVED_NAMES : CANONICAL_NAMES,
392
585
  );
393
586
 
394
587
  const beta = validated.betaFeatures.join(",");
395
- const values = [
396
- [HEADER_NAMES.anthropicBeta, beta],
397
- [HEADER_NAMES.browserAccess, "true"],
398
- [HEADER_NAMES.anthropicVersion, validated.profile.anthropicVersion],
399
- [HEADER_NAMES.authorization, `Bearer ${validated.accessToken}`],
400
- [HEADER_NAMES.contentType, "application/json"],
401
- [HEADER_NAMES.userAgent, validated.profile.userAgent],
402
- [HEADER_NAMES.app, validated.app],
403
- [HEADER_NAMES.sessionId, validated.runtime.sessionId],
404
- [HEADER_NAMES.clientRequestId, validated.clientRequestId],
405
- [HEADER_NAMES.arch, validated.runtime.arch],
406
- [HEADER_NAMES.lang, "js"],
407
- [HEADER_NAMES.os, validated.runtime.os],
408
- [HEADER_NAMES.packageVersion, validated.profile.sdkVersion],
409
- [HEADER_NAMES.retryCount, String(validated.stainlessRetryCount)],
410
- [HEADER_NAMES.runtime, validated.runtime.runtime],
411
- [HEADER_NAMES.runtimeVersion, validated.runtime.runtimeVersion],
412
- [HEADER_NAMES.timeout, "600"],
413
- ] as const;
588
+ const values: (readonly [string, string])[] = layout
589
+ ? genuineHeaderValues(validated, beta)
590
+ : [
591
+ [HEADER_NAMES.anthropicBeta, beta],
592
+ [HEADER_NAMES.browserAccess, "true"],
593
+ [HEADER_NAMES.anthropicVersion, validated.profile.anthropicVersion],
594
+ [HEADER_NAMES.authorization, `Bearer ${validated.accessToken}`],
595
+ [HEADER_NAMES.contentType, "application/json"],
596
+ [HEADER_NAMES.userAgent, validated.profile.userAgent],
597
+ [HEADER_NAMES.app, validated.app],
598
+ [HEADER_NAMES.sessionId, validated.runtime.sessionId],
599
+ [HEADER_NAMES.clientRequestId, validated.clientRequestId],
600
+ [HEADER_NAMES.arch, validated.runtime.arch],
601
+ [HEADER_NAMES.lang, "js"],
602
+ [HEADER_NAMES.os, validated.runtime.os],
603
+ [HEADER_NAMES.packageVersion, validated.profile.sdkVersion],
604
+ [HEADER_NAMES.retryCount, String(validated.stainlessRetryCount)],
605
+ [HEADER_NAMES.runtime, validated.runtime.runtime],
606
+ [HEADER_NAMES.runtimeVersion, validated.runtime.runtimeVersion],
607
+ [HEADER_NAMES.timeout, "600"],
608
+ ];
414
609
 
415
610
  const pairs: HeaderPair[] = [];
416
611
  for (const [name, value] of values) {
@@ -437,6 +632,11 @@ export function buildOrderedHeaderPlan(input: unknown): OrderedHeaderPlan {
437
632
  pairs.push(freezePair(name, value));
438
633
  }
439
634
  }
635
+ // The genuine client sorts every pair, caller extras included, by UTF-16
636
+ // code unit. `Array.prototype.sort` is stable, so equal names keep their
637
+ // insertion order. Never `localeCompare`: it is locale-dependent and orders
638
+ // by collation, not by code unit.
639
+ if (layout) pairs.sort(([left], [right]) => compareNames(left, right));
440
640
  assertTokenIsolation(pairs, validated.accessToken);
441
641
  return Object.freeze({
442
642
  headers: Object.freeze(pairs),
package/src/index.ts CHANGED
@@ -18,11 +18,15 @@ export type {
18
18
  AntiVerbositySection,
19
19
  BuiltClaudeCodeCountTokensRequest,
20
20
  BuiltClaudeCodeRequest,
21
+ ClaudeCodeAccountFeatures,
21
22
  ClaudeCodeBetaOverrides,
22
23
  ClaudeCodeBetaPolicy,
23
24
  ClaudeCodeCapabilities,
24
25
  ClaudeCodeCapabilityDecisions,
25
26
  ClaudeCodeCatalogueEntry,
27
+ ClaudeCodeControlMessage,
28
+ ClaudeCodeControlMessageOutputConfig,
29
+ ClaudeCodeDispatchId,
26
30
  ClaudeCodeEffort,
27
31
  ClaudeCodeExtraHeaderPolicy,
28
32
  ClaudeCodeMetadataOverrides,
@@ -31,6 +35,9 @@ export type {
31
35
  ClaudeCodeCountTokensInput,
32
36
  ClaudeCodeRequestInput,
33
37
  ClaudeCodeRuntimeIdentity,
38
+ ClaudeCodeThreadInput,
39
+ ClaudeCodeToolUsed,
40
+ ClaudeCodeTurnPosition,
34
41
  ClaudeCodeWireErrorCode,
35
42
  HeaderPair,
36
43
  JsonPrimitive,
@@ -77,12 +84,15 @@ export {
77
84
  isOpus48Model,
78
85
  isSonnet46Model,
79
86
  modelCapability,
87
+ modelCatalogueEntry,
80
88
  supportsStructuredOutputs,
81
89
  supportsWebSearch,
82
90
  } from "./model-queries.js";
83
91
 
84
92
  export { BETA_REGISTRY_2_1_233 } from "./profiles/beta-registry-2.1.233.js";
85
93
  export { BETA_REGISTRY_2_1_280 } from "./profiles/beta-registry-2.1.280.js";
94
+ export { BETA_REGISTRY_2_1_329 } from "./profiles/beta-registry-2.1.329.js";
86
95
  export { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
87
96
  export { CLAUDE_CODE_2_1_233_PROFILE } from "./profiles/claude-code-2.1.233.js";
88
97
  export { CLAUDE_CODE_2_1_280_PROFILE } from "./profiles/claude-code-2.1.280.js";
98
+ export { CLAUDE_CODE_2_1_329_PROFILE } from "./profiles/claude-code-2.1.329.js";
@@ -253,24 +253,33 @@ export function supportsStructuredOutputs(normalizedId: string): boolean {
253
253
  * excludes `claude-opus-4-8`. Do not merge them.
254
254
  * This beta-only gate is intentionally absent from `ClaudeCodeCapabilities`.
255
255
  *
256
- * Catalogue-first WHEN a profile is supplied and that profile catalogues the
257
- * id: `mid_conv_system` exists as a catalogue string, and from 2.1.222+ the
256
+ * Catalogue-first WHEN a profile is supplied, that profile's behaviour set
257
+ * reads the catalogue for this question
258
+ * (`midConversationSystemFromCatalogue`), and the profile catalogues the id:
259
+ * `mid_conv_system` exists as a catalogue string, and from 2.1.222+ the
258
260
  * catalogue is what upstream reads. The switch is behaviour-preserving for
259
261
  * 2.1.195, which is the point of the equivalence pinning in
260
262
  * `test/validation/capability-equivalence.test.ts`: in the 2.1.195 catalogue
261
263
  * exactly `claude-opus-4-8` and `claude-fable-5` carry the string, and those
262
264
  * are exactly the two ids the exclusion list below admits.
263
265
  *
264
- * Without a profile -- or for an id the profile does not catalogue, such as
265
- * `claude-mythos-5` under 2.1.195 -- the predicate remains authoritative.
266
+ * Without a profile, for a profile whose behaviour set does not read the
267
+ * catalogue here (2.1.329 retired the string: no catalogue entry carries it),
268
+ * or for an id the profile does not catalogue, such as `claude-mythos-5` under
269
+ * 2.1.195 -- the predicate remains authoritative.
266
270
  */
267
271
  export function supportsMidConversationSystem(
268
272
  normalizedId: string,
269
273
  profile?: ClaudeCodeProtocolProfile,
270
274
  ): boolean {
271
- const entry = profile?.supportedModels[normalizedId];
272
- if (entry !== undefined) {
273
- return entry.capabilities.includes("mid_conv_system");
275
+ if (
276
+ profile !== undefined &&
277
+ profileBehaviors(profile).midConversationSystemFromCatalogue
278
+ ) {
279
+ const entry = profile.supportedModels[normalizedId];
280
+ if (entry !== undefined) {
281
+ return entry.capabilities.includes("mid_conv_system");
282
+ }
274
283
  }
275
284
  return !(
276
285
  normalizedId.includes("claude-3-") ||
@@ -1,6 +1,10 @@
1
1
  // SPDX-License-Identifier: GPL-3.0-or-later
2
2
 
3
- import type { ClaudeCodeModelFamily } from "./contracts.js";
3
+ import type {
4
+ ClaudeCodeModelFamily,
5
+ ClaudeCodeProtocolProfile,
6
+ } from "./contracts.js";
7
+ import { profileBehaviors } from "./profile-behaviors.js";
4
8
 
5
9
  /** Ports upstream `dp` (binary offset 226644497). */
6
10
  export function stripModelMarkers(model: string): string {
@@ -21,6 +25,40 @@ function dottedToDashedVersion(model: string): string {
21
25
  return model.replace(/(\d)\.(\d)/g, "$1-$2");
22
26
  }
23
27
 
28
+ /** Which normalizer rungs apply; see `normalizeModelId`. */
29
+ export type ModelIdLadder = "base" | "extended";
30
+
31
+ /**
32
+ * Resolves the ladder a profile's own normalizer follows, from the behaviour
33
+ * flag rather than from the profile id.
34
+ */
35
+ export function modelIdLadder(
36
+ profile: ClaudeCodeProtocolProfile,
37
+ ): ModelIdLadder {
38
+ return profileBehaviors(profile).extendedModelIdLadder ? "extended" : "base";
39
+ }
40
+
41
+ /**
42
+ * Ports upstream `V2e` (2.1.329 bundle, view line 101880, byte offset
43
+ * 5753662): whether `needle` occurs in `haystack` as an undated id. When the
44
+ * needle ends in a `-`/`_` plus a digit, an occurrence directly followed by
45
+ * three more digits is a date suffix on the shorter id (`claude-fable-5-` +
46
+ * `20260101`) and does not count.
47
+ */
48
+ function matchesUndated(haystack: string, needle: string): boolean {
49
+ const endsInDigit = /[-_]\d$/.test(needle);
50
+ for (
51
+ let at = haystack.indexOf(needle);
52
+ at !== -1;
53
+ at = haystack.indexOf(needle, at + 1)
54
+ ) {
55
+ if (!endsInDigit || !/^\d{3}/.test(haystack.slice(at + needle.length))) {
56
+ return true;
57
+ }
58
+ }
59
+ return false;
60
+ }
61
+
24
62
  /**
25
63
  * Ports upstream `$_` (binary offset 226639025); in the 2.1.280 bundle the
26
64
  * function is `GF` at byte offset 7413751. The two offsets are in different
@@ -29,11 +67,27 @@ function dottedToDashedVersion(model: string): string {
29
67
  *
30
68
  * Rung order is load-bearing: each test is a substring test, so a longer id
31
69
  * must precede the shorter id it contains or the shorter rung swallows it.
70
+ *
71
+ * Two ladders. `"base"` is the ladder every profile through 2.1.280 follows.
72
+ * `"extended"` adds four rungs transcribed from the 2.1.329 bundle (`NK`, view
73
+ * lines 113702-113708): `claude-fable-5-2`, `claude-mythos-5-2`,
74
+ * `claude-sonnet-5-5` and `claude-haiku-5-5`, each placed before the shorter id
75
+ * it contains. Which ladder a profile follows is decided by `modelIdLadder`.
32
76
  */
33
- export function normalizeModelId(model: string): string {
77
+ export function normalizeModelId(
78
+ model: string,
79
+ ladder: ModelIdLadder = "base",
80
+ ): string {
34
81
  model = dottedToDashedVersion(model.toLowerCase());
82
+ const extended = ladder === "extended";
83
+ if (extended && matchesUndated(model, "claude-fable-5-2")) {
84
+ return "claude-fable-5-2";
85
+ }
35
86
  if (model.includes("claude-fable-5-1")) return "claude-fable-5-1";
36
87
  if (model.includes("claude-fable-5")) return "claude-fable-5";
88
+ if (extended && matchesUndated(model, "claude-mythos-5-2")) {
89
+ return "claude-mythos-5-2";
90
+ }
37
91
  if (model.includes("claude-mythos-5-1")) return "claude-mythos-5-1";
38
92
  if (model.includes("claude-mythos-5")) return "claude-mythos-5";
39
93
  if (model.includes("claude-opus-5-5")) return "claude-opus-5-5";
@@ -44,10 +98,16 @@ export function normalizeModelId(model: string): string {
44
98
  if (model.includes("claude-opus-4-5")) return "claude-opus-4-5";
45
99
  if (model.includes("claude-opus-4-1")) return "claude-opus-4-1";
46
100
  if (/claude-opus-4(?!-\d(?!\d))/.test(model)) return "claude-opus-4-0";
101
+ if (extended && model.includes("claude-sonnet-5-5")) {
102
+ return "claude-sonnet-5-5";
103
+ }
47
104
  if (model.includes("claude-sonnet-5")) return "claude-sonnet-5";
48
105
  if (model.includes("claude-sonnet-4-6")) return "claude-sonnet-4-6";
49
106
  if (model.includes("claude-sonnet-4-5")) return "claude-sonnet-4-5";
50
107
  if (/claude-sonnet-4(?!-\d(?!\d))/.test(model)) return "claude-sonnet-4-0";
108
+ if (extended && model.includes("claude-haiku-5-5")) {
109
+ return "claude-haiku-5-5";
110
+ }
51
111
  if (model.includes("claude-haiku-4-5")) return "claude-haiku-4-5";
52
112
  if (model.includes("claude-3-7-sonnet")) return "claude-3-7-sonnet";
53
113
  if (model.includes("claude-3-5-sonnet")) return "claude-3-5-sonnet";