@tormentalabs/claude-code-wire-compat 0.7.0 → 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 (97) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +31 -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 +208 -24
  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/limits.d.ts +29 -2
  33. package/dist/limits.d.ts.map +1 -1
  34. package/dist/limits.js +29 -2
  35. package/dist/limits.js.map +1 -1
  36. package/dist/model-capabilities.d.ts +8 -4
  37. package/dist/model-capabilities.d.ts.map +1 -1
  38. package/dist/model-capabilities.js +14 -7
  39. package/dist/model-capabilities.js.map +1 -1
  40. package/dist/model-identity.d.ts +15 -2
  41. package/dist/model-identity.d.ts.map +1 -1
  42. package/dist/model-identity.js +44 -1
  43. package/dist/model-identity.js.map +1 -1
  44. package/dist/model-queries.d.ts +11 -1
  45. package/dist/model-queries.d.ts.map +1 -1
  46. package/dist/model-queries.js +51 -7
  47. package/dist/model-queries.js.map +1 -1
  48. package/dist/models.d.ts.map +1 -1
  49. package/dist/models.js +2 -2
  50. package/dist/models.js.map +1 -1
  51. package/dist/profile-behaviors.d.ts +72 -0
  52. package/dist/profile-behaviors.d.ts.map +1 -1
  53. package/dist/profile-behaviors.js +66 -15
  54. package/dist/profile-behaviors.js.map +1 -1
  55. package/dist/profiles/beta-registry-2.1.329.d.ts +229 -0
  56. package/dist/profiles/beta-registry-2.1.329.d.ts.map +1 -0
  57. package/dist/profiles/beta-registry-2.1.329.js +281 -0
  58. package/dist/profiles/beta-registry-2.1.329.js.map +1 -0
  59. package/dist/profiles/claude-code-2.1.329.d.ts +3 -0
  60. package/dist/profiles/claude-code-2.1.329.d.ts.map +1 -0
  61. package/dist/profiles/claude-code-2.1.329.js +466 -0
  62. package/dist/profiles/claude-code-2.1.329.js.map +1 -0
  63. package/dist/redaction.d.ts.map +1 -1
  64. package/dist/redaction.js +7 -3
  65. package/dist/redaction.js.map +1 -1
  66. package/dist/request-body.d.ts +27 -1
  67. package/dist/request-body.d.ts.map +1 -1
  68. package/dist/request-body.js +192 -23
  69. package/dist/request-body.js.map +1 -1
  70. package/dist/system-prompt.d.ts.map +1 -1
  71. package/dist/system-prompt.js +6 -4
  72. package/dist/system-prompt.js.map +1 -1
  73. package/dist/tools-used.d.ts +52 -0
  74. package/dist/tools-used.d.ts.map +1 -0
  75. package/dist/tools-used.js +116 -0
  76. package/dist/tools-used.js.map +1 -0
  77. package/package.json +5 -1
  78. package/src/account-features.ts +114 -0
  79. package/src/anti-verbosity.ts +8 -3
  80. package/src/betas.ts +252 -22
  81. package/src/build-request.ts +251 -26
  82. package/src/contracts.ts +185 -3
  83. package/src/fingerprint.ts +84 -7
  84. package/src/headers.ts +221 -21
  85. package/src/index.ts +10 -0
  86. package/src/limits.ts +31 -2
  87. package/src/model-capabilities.ts +16 -7
  88. package/src/model-identity.ts +62 -2
  89. package/src/model-queries.ts +71 -8
  90. package/src/models.ts +2 -1
  91. package/src/profile-behaviors.ts +150 -16
  92. package/src/profiles/beta-registry-2.1.329.ts +298 -0
  93. package/src/profiles/claude-code-2.1.329.ts +471 -0
  94. package/src/redaction.ts +7 -3
  95. package/src/request-body.ts +253 -22
  96. package/src/system-prompt.ts +6 -2
  97. package/src/tools-used.ts +134 -0
@@ -1,21 +1,28 @@
1
1
  // SPDX-License-Identifier: GPL-3.0-or-later
2
2
 
3
- import { MAX_INPUT_SIZE as MAX_SIZE } from "./limits.js";
3
+ import {
4
+ MAX_INPUT_ITEMS as MAX_ITEMS,
5
+ MAX_INPUT_SIZE as MAX_SIZE,
6
+ } from "./limits.js";
4
7
 
5
8
  import { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
6
9
  import { clampMaxTokens, resolveThinking } from "./thinking.js";
7
10
  import type { ThinkingDisplay, ThinkingRequest } from "./thinking.js";
8
11
 
12
+ import type { ClaudeCodeThreadBody } from "./betas.js";
9
13
  import { ClaudeCodeWireError } from "./contracts.js";
10
14
  import type {
11
15
  CacheControlEphemeral,
12
16
  ClaudeCodeCacheControlInput,
17
+ ClaudeCodeControlMessage,
18
+ ClaudeCodeControlMessageOutputConfig,
13
19
  ClaudeCodeProtocolProfile,
14
20
  CitationsConfigParam,
15
21
  DocumentBlock,
16
22
  ImageBlock,
17
23
  JsonValue,
18
24
  Message,
25
+ MessageContent,
19
26
  MessageContentBlock,
20
27
  RedactedThinkingBlock,
21
28
  SearchResultBlock,
@@ -30,6 +37,7 @@ import type {
30
37
  } from "./contracts.js";
31
38
  import { deriveCapabilities } from "./model-capabilities.js";
32
39
  import { stripModelMarkers } from "./model-identity.js";
40
+ import { profileBehaviors } from "./profile-behaviors.js";
33
41
  import { IDENTITY_TEXT } from "./system-prompt.js";
34
42
  import {
35
43
  inspectText,
@@ -39,9 +47,14 @@ import {
39
47
  import { violationDetails, type ViolationPathSegment } from "./violation.js";
40
48
 
41
49
  const MAX_DEPTH = 100;
42
- const MAX_ITEMS = 100_000;
43
50
  const FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);
44
51
  const MESSAGE_KEYS = new Set(["role", "content"]);
52
+ const CONTROL_MESSAGE_KEYS = new Set(["role", "content", "output_config"]);
53
+ const CONTROL_OUTPUT_CONFIG_KEYS = new Set(["effort", "timing"]);
54
+ const CONTROL_TIMING_KEYS = new Set(["type", "now"]);
55
+
56
+ /** A validated `messages` entry: a conversation turn or a control message. */
57
+ type WireMessage = Message | ClaudeCodeControlMessage;
45
58
  const CACHE_CONTROL_KEYS = new Set(["type", "ttl"]);
46
59
  const LEGACY_TEXT_CACHE_CONTROL_KEYS = new Set(["type", "ttl", "scope"]);
47
60
  const CITATIONS_CONFIG_KEYS = new Set(["enabled"]);
@@ -391,7 +404,7 @@ function inspectString(
391
404
  inKey = false,
392
405
  ): void {
393
406
  state.size += value.length;
394
- if (state.size > MAX_SIZE) fail("INPUT_TOO_LARGE");
407
+ if (state.size > MAX_SIZE) fail("INPUT_TOO_LARGE", { maximumSize: MAX_SIZE });
395
408
  validateString?.(value);
396
409
 
397
410
  // Body prose policy (P1.T1): only a lone surrogate can fail here now, so
@@ -427,11 +440,15 @@ function inspect(
427
440
  if (state.active.has(value)) fail("CYCLIC_INPUT");
428
441
  state.active.add(value);
429
442
  state.items += 1;
430
- if (state.items > MAX_ITEMS) fail("INPUT_TOO_LARGE");
443
+ if (state.items > MAX_ITEMS) {
444
+ fail("INPUT_TOO_LARGE", { maximumItems: MAX_ITEMS });
445
+ }
431
446
 
432
447
  if (Array.isArray(value)) {
433
448
  state.size += value.length;
434
- if (state.size > MAX_SIZE) fail("INPUT_TOO_LARGE");
449
+ if (state.size > MAX_SIZE) {
450
+ fail("INPUT_TOO_LARGE", { maximumSize: MAX_SIZE });
451
+ }
435
452
  for (let index = 0; index < value.length; index += 1) {
436
453
  if (!hasOwn(value, String(index))) fail("INVALID_INPUT");
437
454
  path.push(index);
@@ -696,12 +713,12 @@ function applyToolCacheControl(
696
713
  * had placed on its own message blocks.
697
714
  */
698
715
  function applyMessageCacheControl(
699
- value: readonly Message[],
716
+ value: readonly WireMessage[],
700
717
  input: ClaudeCodeCacheControlInput,
701
- ): readonly Message[] {
718
+ ): readonly WireMessage[] {
702
719
  if (input.enabled !== true) return value;
703
- const result = value.map((message): Message => ({
704
- role: message.role,
720
+ const result = value.map((message): WireMessage => ({
721
+ ...message,
705
722
  content:
706
723
  typeof message.content === "string"
707
724
  ? message.content
@@ -1110,22 +1127,73 @@ function messageContentBlock(
1110
1127
  return fail("INVALID_INPUT");
1111
1128
  }
1112
1129
 
1130
+ /**
1131
+ * Validates a per-turn control message's `output_config`: an effort level, a
1132
+ * timing statement, or both. Anything else is refused, because the shape is
1133
+ * transcribed from the genuine client and a package-invented member would be a
1134
+ * wire divergence.
1135
+ */
1136
+ function controlOutputConfig(
1137
+ value: unknown,
1138
+ ): ClaudeCodeControlMessageOutputConfig {
1139
+ const record = requireRecord(value);
1140
+ assertExactKeys(record, CONTROL_OUTPUT_CONFIG_KEYS);
1141
+ const effort = record["effort"];
1142
+ const timing = record["timing"];
1143
+ if (effort === undefined && timing === undefined) fail("INVALID_INPUT");
1144
+ if (
1145
+ effort !== undefined &&
1146
+ effort !== "low" &&
1147
+ effort !== "medium" &&
1148
+ effort !== "high" &&
1149
+ effort !== "xhigh" &&
1150
+ effort !== "max"
1151
+ ) {
1152
+ fail("INVALID_INPUT");
1153
+ }
1154
+ let validTiming: ClaudeCodeControlMessageOutputConfig["timing"];
1155
+ if (timing !== undefined) {
1156
+ const timingRecord = requireRecord(timing);
1157
+ assertExactKeys(timingRecord, CONTROL_TIMING_KEYS);
1158
+ if (timingRecord["type"] !== "now") fail("INVALID_INPUT");
1159
+ const now = timingRecord["now"];
1160
+ if (typeof now === "number") {
1161
+ if (!Number.isFinite(now)) fail("INVALID_INPUT");
1162
+ validTiming = { type: "now", now };
1163
+ } else {
1164
+ const text = requireIdentifier(now);
1165
+ if (text.length === 0 || text.length > 64) fail("INVALID_INPUT");
1166
+ validTiming = { type: "now", now: text };
1167
+ }
1168
+ }
1169
+ return {
1170
+ ...(effort === undefined ? {} : { effort }),
1171
+ ...(validTiming === undefined ? {} : { timing: validTiming }),
1172
+ };
1173
+ }
1174
+
1175
+ function messages(
1176
+ value: unknown,
1177
+ preserveThinkingCacheControl: boolean,
1178
+ acceptControlMessages: false,
1179
+ ): readonly Message[];
1180
+ function messages(
1181
+ value: unknown,
1182
+ preserveThinkingCacheControl: boolean,
1183
+ acceptControlMessages: boolean,
1184
+ ): readonly WireMessage[];
1113
1185
  function messages(
1114
1186
  value: unknown,
1115
1187
  preserveThinkingCacheControl: boolean,
1116
- ): readonly Message[] {
1188
+ acceptControlMessages: boolean,
1189
+ ): readonly WireMessage[] {
1117
1190
  if (!Array.isArray(value)) fail("INVALID_INPUT");
1118
1191
  const useIds = new Set<string>();
1119
1192
  const resultIds: string[] = [];
1120
- const result = value.map((item): Message => {
1121
- const record = requireRecord(item);
1122
- assertExactKeys(record, MESSAGE_KEYS);
1123
- const role = record["role"];
1124
- if (role !== "user" && role !== "assistant") fail("INVALID_INPUT");
1125
- const rawContent = record["content"];
1126
- if (typeof rawContent === "string") return { role, content: rawContent };
1193
+ const messageContent = (rawContent: unknown): MessageContent => {
1194
+ if (typeof rawContent === "string") return rawContent;
1127
1195
  if (!Array.isArray(rawContent)) fail("INVALID_INPUT");
1128
- const content = rawContent.map((block) => {
1196
+ return rawContent.map((block) => {
1129
1197
  const blockRecord = requireRecord(block);
1130
1198
  if (blockRecord["type"] === "text") return textBlock(blockRecord);
1131
1199
  if (blockRecord["type"] === "tool_use") {
@@ -1141,7 +1209,27 @@ function messages(
1141
1209
  }
1142
1210
  return messageContentBlock(blockRecord, preserveThinkingCacheControl);
1143
1211
  });
1144
- return { role, content };
1212
+ };
1213
+ const result = value.map((item): WireMessage => {
1214
+ const record = requireRecord(item);
1215
+ assertExactKeys(
1216
+ record,
1217
+ acceptControlMessages ? CONTROL_MESSAGE_KEYS : MESSAGE_KEYS,
1218
+ );
1219
+ const role = record["role"];
1220
+ if (acceptControlMessages && role === "system") {
1221
+ // A control message always carries its statement; the genuine client
1222
+ // never emits one without `output_config`.
1223
+ if (!hasOwn(record, "output_config")) fail("INVALID_INPUT");
1224
+ return {
1225
+ role,
1226
+ content: messageContent(record["content"]),
1227
+ output_config: controlOutputConfig(record["output_config"]),
1228
+ };
1229
+ }
1230
+ if (role !== "user" && role !== "assistant") fail("INVALID_INPUT");
1231
+ if (hasOwn(record, "output_config")) fail("INVALID_INPUT");
1232
+ return { role, content: messageContent(record["content"]) };
1145
1233
  });
1146
1234
  for (const id of resultIds) {
1147
1235
  if (!useIds.has(id)) fail("INVALID_INPUT");
@@ -1766,11 +1854,100 @@ export function canonicalCountTokensLists(
1766
1854
  return {
1767
1855
  // The count-tokens endpoint has no seam of its own, so thinking blocks stay
1768
1856
  // on the strict allowlist here.
1769
- messages: messages(rawMessages, false),
1857
+ messages: messages(rawMessages, false, false),
1770
1858
  tools: rawTools === undefined ? Object.freeze([]) : tools(rawTools),
1771
1859
  };
1772
1860
  }
1773
1861
 
1862
+ /**
1863
+ * The shape of an Anthropic message id as the genuine client's chaining guard
1864
+ * accepts it (`msg_` plus 1-64 identifier characters).
1865
+ */
1866
+ const MESSAGE_ID_PATTERN = /^msg_[A-Za-z0-9_]{1,64}$/u;
1867
+
1868
+ /**
1869
+ * Validates the `previousMessageId` input: a message id, or `null` (the
1870
+ * genuine client's value on the first request of a thread). Anything else is
1871
+ * `INVALID_INPUT`; unlike the billing chain ids, this one is not silently
1872
+ * dropped, because it is echoed verbatim into the body.
1873
+ */
1874
+ export function validatePreviousMessageId(value: unknown): string | null {
1875
+ if (value === null) return null;
1876
+ if (typeof value !== "string" || !MESSAGE_ID_PATTERN.test(value)) {
1877
+ fail("INVALID_INPUT");
1878
+ }
1879
+ return value;
1880
+ }
1881
+
1882
+ /**
1883
+ * Body fields the request builder derives from the beta composition and the
1884
+ * caller's chaining state rather than from a named body input. Each member is
1885
+ * honoured only under its profile behaviour flag.
1886
+ */
1887
+ export interface GeneratedBodyInputs {
1888
+ /** The context-management beta site fired (`ComposedBetas`). */
1889
+ readonly contextManagementComposed?: boolean;
1890
+ /** The cache-diagnosis beta site fired (`ComposedBetas`). */
1891
+ readonly cacheDiagnosisComposed?: boolean;
1892
+ /** The caller's `previousMessageId`; absent is the same as `null`. */
1893
+ readonly previousMessageId?: string | null;
1894
+ /**
1895
+ * The `thread` object the message-threads site decided on (`ComposedBetas`);
1896
+ * absent when the site did not fire or the caller suppressed its beta.
1897
+ */
1898
+ readonly thread?: ClaudeCodeThreadBody;
1899
+ }
1900
+
1901
+ /**
1902
+ * Body keys in the genuine client's emission order, split around the slot that
1903
+ * collects every key the genuine client's object literal does not name
1904
+ * (`service_tier`, `output_format`, `top_p`, `top_k`, `stop_sequences` and the
1905
+ * caller's experimental fields). View :158392-158394 @20154922-20155417; the
1906
+ * live capture `inter329-205` shows the same sequence, with the host-served
1907
+ * `safeguards` key sitting between `context_management` and `output_config`.
1908
+ */
1909
+ const GENUINE_BODY_KEYS_BEFORE_EXTRAS = [
1910
+ "model",
1911
+ "messages",
1912
+ "system",
1913
+ "tools",
1914
+ "tool_choice",
1915
+ "metadata",
1916
+ "max_tokens",
1917
+ "thinking",
1918
+ "temperature",
1919
+ "context_management",
1920
+ "context_hint",
1921
+ ] as const;
1922
+ const GENUINE_BODY_KEYS_AFTER_EXTRAS = [
1923
+ "output_config",
1924
+ "speed",
1925
+ "thread",
1926
+ "diagnostics",
1927
+ "stream",
1928
+ ] as const;
1929
+ const GENUINE_BODY_NAMED_KEYS: ReadonlySet<string> = new Set([
1930
+ ...GENUINE_BODY_KEYS_BEFORE_EXTRAS,
1931
+ ...GENUINE_BODY_KEYS_AFTER_EXTRAS,
1932
+ ]);
1933
+
1934
+ /** Re-emits `result` with its keys in the genuine client's order. */
1935
+ function orderGenuineBody(
1936
+ result: Readonly<Record<string, unknown>>,
1937
+ ): Record<string, unknown> {
1938
+ const ordered: Record<string, unknown> = {};
1939
+ const take = (key: string): void => {
1940
+ if (hasOwn(result, key)) ordered[key] = result[key];
1941
+ };
1942
+ for (const key of GENUINE_BODY_KEYS_BEFORE_EXTRAS) take(key);
1943
+ // Insertion order of `result` is preserved for the extras.
1944
+ for (const key of Object.keys(result)) {
1945
+ if (!GENUINE_BODY_NAMED_KEYS.has(key)) ordered[key] = result[key];
1946
+ }
1947
+ for (const key of GENUINE_BODY_KEYS_AFTER_EXTRAS) take(key);
1948
+ return ordered;
1949
+ }
1950
+
1774
1951
  export function buildCanonicalBody(
1775
1952
  rawInput: unknown,
1776
1953
  rawResolvedModel: unknown,
@@ -1778,6 +1955,7 @@ export function buildCanonicalBody(
1778
1955
  rawMetadata: unknown,
1779
1956
  profile?: ClaudeCodeProtocolProfile,
1780
1957
  thinkingDisplayOverride?: "updates",
1958
+ generated?: GeneratedBodyInputs,
1781
1959
  ): Readonly<Record<string, unknown>> {
1782
1960
  inspectJsonInputs(
1783
1961
  [
@@ -1814,7 +1992,11 @@ export function buildCanonicalBody(
1814
1992
  hasOwn(input, "preserveThinkingBlockCacheControl") &&
1815
1993
  requireBoolean(input["preserveThinkingBlockCacheControl"]);
1816
1994
  let systemBlocks = system(rawSystemBlocks);
1817
- let messageList = messages(input["messages"], preserveThinkingCacheControl);
1995
+ let messageList = messages(
1996
+ input["messages"],
1997
+ preserveThinkingCacheControl,
1998
+ profileBehaviors(effectiveProfile).perTurnControlMessages,
1999
+ );
1818
2000
  let toolList = hasOwn(input, "tools") ? tools(input["tools"]) : undefined;
1819
2001
  if (cacheOverride !== undefined && cacheOverride !== null) {
1820
2002
  systemBlocks = applySystemCacheControl(systemBlocks, cacheOverride);
@@ -1972,6 +2154,53 @@ export function buildCanonicalBody(
1972
2154
  else if (key === "stream") result["stream"] = requireBoolean(item);
1973
2155
  }
1974
2156
 
2157
+ const behaviors = profileBehaviors(effectiveProfile);
2158
+
2159
+ // Body half of the context-management pair. The genuine client attaches the
2160
+ // clear-thinking edit whenever the beta fired and thinking is on, unless the
2161
+ // caller supplied its own value (an explicit `null` is the caller's too).
2162
+ // Keyed on the composed state, not on the header list, so suppressing the
2163
+ // beta identifier leaves the field in place. A value carried by
2164
+ // `experimentalBodyFields` is the caller's as well.
2165
+ const emittedThinkingType = isRecord(result["thinking"])
2166
+ ? result["thinking"]["type"]
2167
+ : undefined;
2168
+ const experimentalInput = input["experimentalBodyFields"];
2169
+ const callerContextManagement =
2170
+ hasOwn(input, "contextManagement") ||
2171
+ (isRecord(experimentalInput) &&
2172
+ hasOwn(experimentalInput, "context_management"));
2173
+ if (
2174
+ behaviors.generatedContextManagement &&
2175
+ generated?.contextManagementComposed === true &&
2176
+ (emittedThinkingType === "adaptive" || emittedThinkingType === "enabled") &&
2177
+ !callerContextManagement
2178
+ ) {
2179
+ result["context_management"] = {
2180
+ edits: [{ type: "clear_thinking_20251015", keep: "all" }],
2181
+ };
2182
+ }
2183
+
2184
+ // Body half of the cache-diagnosis pair: the previous message id of the
2185
+ // thread, `null` on the first request.
2186
+ if (
2187
+ behaviors.cacheDiagnosisBody &&
2188
+ generated?.cacheDiagnosisComposed === true
2189
+ ) {
2190
+ result["diagnostics"] = {
2191
+ previous_message_id: validatePreviousMessageId(
2192
+ generated.previousMessageId ?? null,
2193
+ ),
2194
+ };
2195
+ }
2196
+
2197
+ // Body half of the message-threads pair. Present only when the site fired and
2198
+ // the beta was not suppressed; `orderGenuineBody` places it before
2199
+ // `diagnostics`.
2200
+ if (behaviors.accountServedInputs && generated?.thread !== undefined) {
2201
+ result["thread"] = generated.thread;
2202
+ }
2203
+
1975
2204
  if (contextHintEnabled(profile)) {
1976
2205
  result["context_hint"] = { enabled: true };
1977
2206
  }
@@ -1985,5 +2214,7 @@ export function buildCanonicalBody(
1985
2214
  result[key] = experimentalBodyFields[key];
1986
2215
  }
1987
2216
  }
1988
- return deepFreeze(result);
2217
+ return deepFreeze(
2218
+ behaviors.genuineBodyKeyOrder ? orderGenuineBody(result) : result,
2219
+ );
1989
2220
  }
@@ -72,7 +72,9 @@ function validateStructure(value: unknown): void {
72
72
 
73
73
  if (typeof current === "string") {
74
74
  size += current.length;
75
- if (size > MAX_INPUT_SIZE) fail("INPUT_TOO_LARGE");
75
+ if (size > MAX_INPUT_SIZE) {
76
+ fail("INPUT_TOO_LARGE", { maximumSize: MAX_INPUT_SIZE });
77
+ }
76
78
  validateText(current, path, false);
77
79
  return;
78
80
  }
@@ -93,7 +95,9 @@ function validateStructure(value: unknown): void {
93
95
  path.push(segment);
94
96
  if (typeof key === "string") {
95
97
  size += key.length;
96
- if (size > MAX_INPUT_SIZE) fail("INPUT_TOO_LARGE");
98
+ if (size > MAX_INPUT_SIZE) {
99
+ fail("INPUT_TOO_LARGE", { maximumSize: MAX_INPUT_SIZE });
100
+ }
97
101
  validateText(key, path, true);
98
102
  }
99
103
  visit(current[key], depth + 1);
@@ -0,0 +1,134 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { ClaudeCodeWireError } from "./contracts.js";
4
+
5
+ /**
6
+ * The `x-claude-code-sandy-plover` header: the tools the conversation has used.
7
+ *
8
+ * Transcribed from the 2.1.329 bundle (view lines 132137-132147, offsets
9
+ * 13706379-13708766): `ka` maps each entry to `{name, ...(mcp === true &&
10
+ * {mcp}), ...bao(url, directory_entry, unresolved)}`, so the keys are emitted
11
+ * in the order `name`, `mcp` (only when true), `url`; `_p` serialises each with
12
+ * `JSON.stringify`, stops at 64 entries or 7168 bytes, and the value is
13
+ * `[` + entries joined with `,` + `]`.
14
+ *
15
+ * Deliberately NOT ported: `directory_entry` and `unresolved` (host-state
16
+ * concepts of the connector-download tracker) and the truncation sentinel
17
+ * (`pFt`, unresolved). Where the genuine client truncates, this package
18
+ * refuses: a value over the caps is `INVALID_INPUT`. Listing the built-in tool
19
+ * names after the others (the genuine `va` ordering) is the host's job; entry
20
+ * order here is the caller's.
21
+ */
22
+
23
+ /** Entries above this count make the genuine client truncate (`our`). */
24
+ export const TOOLS_USED_MAX_ENTRIES = 64;
25
+ /** Serialized byte ceiling of the header value (`Rd`). */
26
+ export const TOOLS_USED_MAX_BYTES = 7168;
27
+ /** Longest accepted tool name in bytes (`jS`); longer names are dropped. */
28
+ export const TOOLS_USED_MAX_NAME_BYTES = 256;
29
+
30
+ const ALLOWED_KEYS: ReadonlySet<string> = new Set(["name", "mcp", "url"]);
31
+ const PRINTABLE_ASCII = /^[\u0020-\u007e]*$/u;
32
+
33
+ /** One validated, normalised entry. `mcp` is present only when true. */
34
+ export interface ToolsUsedEntry {
35
+ readonly name: string;
36
+ readonly mcp?: true;
37
+ readonly url?: string;
38
+ }
39
+
40
+ function invalid(
41
+ details: Readonly<Record<string, string | number | boolean>> = {},
42
+ ): never {
43
+ throw new ClaudeCodeWireError("INVALID_INPUT", details);
44
+ }
45
+
46
+ function isPlainRecord(
47
+ value: unknown,
48
+ ): value is Readonly<Record<string, unknown>> {
49
+ return typeof value === "object" && value !== null && !Array.isArray(value);
50
+ }
51
+
52
+ function validateEntry(value: unknown): ToolsUsedEntry | undefined {
53
+ if (!isPlainRecord(value)) return invalid();
54
+ for (const key of Reflect.ownKeys(value)) {
55
+ if (typeof key !== "string" || !ALLOWED_KEYS.has(key)) return invalid();
56
+ }
57
+ const name = Object.hasOwn(value, "name") ? value["name"] : undefined;
58
+ if (typeof name !== "string" || !PRINTABLE_ASCII.test(name)) return invalid();
59
+ const mcp = Object.hasOwn(value, "mcp") ? value["mcp"] : undefined;
60
+ if (mcp !== undefined && typeof mcp !== "boolean") return invalid();
61
+ const url = Object.hasOwn(value, "url") ? value["url"] : undefined;
62
+ if (
63
+ url !== undefined &&
64
+ (typeof url !== "string" || !PRINTABLE_ASCII.test(url))
65
+ ) {
66
+ return invalid();
67
+ }
68
+ // Printable ASCII: one byte per character, so length is the byte length.
69
+ if (name === "" || name.length > TOOLS_USED_MAX_NAME_BYTES) return undefined;
70
+ return Object.freeze({
71
+ name,
72
+ ...(mcp === true ? { mcp: true as const } : {}),
73
+ ...(url === undefined ? {} : { url }),
74
+ });
75
+ }
76
+
77
+ /**
78
+ * Serializes entries exactly as the genuine client does. Total over any
79
+ * `ToolsUsedEntry` list; the caps are enforced by `validateToolsUsed`.
80
+ */
81
+ export function serializeToolsUsed(entries: readonly ToolsUsedEntry[]): string {
82
+ const serialized = entries.map((entry) =>
83
+ JSON.stringify({
84
+ name: entry.name,
85
+ ...(entry.mcp === true ? { mcp: true } : {}),
86
+ ...(entry.url === undefined ? {} : { url: entry.url }),
87
+ }),
88
+ );
89
+ return `[${serialized.join(",")}]`;
90
+ }
91
+
92
+ /**
93
+ * Validates caller input and returns the normalised entries.
94
+ *
95
+ * Throws `INVALID_INPUT` for a non-array, more than 64 entries
96
+ * (`{maximumItems: 64}`), an entry that is not a record with only the keys
97
+ * `name`, `mcp` and `url`, a mistyped member, a non-printable-ASCII `name` or
98
+ * `url`, or a serialized value over 7168 bytes (`{maximumSize: 7168}`). Entries
99
+ * with an empty name or a name over 256 bytes are dropped silently, as upstream
100
+ * does.
101
+ */
102
+ export function validateToolsUsed(value: unknown): readonly ToolsUsedEntry[] {
103
+ if (!Array.isArray(value)) return invalid();
104
+ if (value.length > TOOLS_USED_MAX_ENTRIES) {
105
+ return invalid({ maximumItems: TOOLS_USED_MAX_ENTRIES });
106
+ }
107
+ const entries: ToolsUsedEntry[] = [];
108
+ for (const candidate of value as readonly unknown[]) {
109
+ const entry = validateEntry(candidate);
110
+ if (entry !== undefined) entries.push(entry);
111
+ }
112
+ // Printable ASCII only, so the serialized length is its byte length.
113
+ if (serializeToolsUsed(entries).length > TOOLS_USED_MAX_BYTES) {
114
+ return invalid({ maximumSize: TOOLS_USED_MAX_BYTES });
115
+ }
116
+ return Object.freeze(entries);
117
+ }
118
+
119
+ /**
120
+ * Reads a header value back into entries, for the request parser. The parser
121
+ * rebuilds the header from the result and compares bytes, so any value this
122
+ * accepts but would not serialize identically is still refused there.
123
+ */
124
+ export function parseToolsUsedHeaderValue(
125
+ value: string,
126
+ ): readonly ToolsUsedEntry[] {
127
+ let parsed: unknown;
128
+ try {
129
+ parsed = JSON.parse(value);
130
+ } catch {
131
+ return invalid();
132
+ }
133
+ return validateToolsUsed(parsed);
134
+ }