@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
@@ -9,16 +9,20 @@ import { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
9
9
  import { clampMaxTokens, resolveThinking } from "./thinking.js";
10
10
  import type { ThinkingDisplay, ThinkingRequest } from "./thinking.js";
11
11
 
12
+ import type { ClaudeCodeThreadBody } from "./betas.js";
12
13
  import { ClaudeCodeWireError } from "./contracts.js";
13
14
  import type {
14
15
  CacheControlEphemeral,
15
16
  ClaudeCodeCacheControlInput,
17
+ ClaudeCodeControlMessage,
18
+ ClaudeCodeControlMessageOutputConfig,
16
19
  ClaudeCodeProtocolProfile,
17
20
  CitationsConfigParam,
18
21
  DocumentBlock,
19
22
  ImageBlock,
20
23
  JsonValue,
21
24
  Message,
25
+ MessageContent,
22
26
  MessageContentBlock,
23
27
  RedactedThinkingBlock,
24
28
  SearchResultBlock,
@@ -33,6 +37,7 @@ import type {
33
37
  } from "./contracts.js";
34
38
  import { deriveCapabilities } from "./model-capabilities.js";
35
39
  import { stripModelMarkers } from "./model-identity.js";
40
+ import { profileBehaviors } from "./profile-behaviors.js";
36
41
  import { IDENTITY_TEXT } from "./system-prompt.js";
37
42
  import {
38
43
  inspectText,
@@ -44,6 +49,12 @@ import { violationDetails, type ViolationPathSegment } from "./violation.js";
44
49
  const MAX_DEPTH = 100;
45
50
  const FORBIDDEN_KEYS = new Set(["__proto__", "prototype", "constructor"]);
46
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;
47
58
  const CACHE_CONTROL_KEYS = new Set(["type", "ttl"]);
48
59
  const LEGACY_TEXT_CACHE_CONTROL_KEYS = new Set(["type", "ttl", "scope"]);
49
60
  const CITATIONS_CONFIG_KEYS = new Set(["enabled"]);
@@ -702,12 +713,12 @@ function applyToolCacheControl(
702
713
  * had placed on its own message blocks.
703
714
  */
704
715
  function applyMessageCacheControl(
705
- value: readonly Message[],
716
+ value: readonly WireMessage[],
706
717
  input: ClaudeCodeCacheControlInput,
707
- ): readonly Message[] {
718
+ ): readonly WireMessage[] {
708
719
  if (input.enabled !== true) return value;
709
- const result = value.map((message): Message => ({
710
- role: message.role,
720
+ const result = value.map((message): WireMessage => ({
721
+ ...message,
711
722
  content:
712
723
  typeof message.content === "string"
713
724
  ? message.content
@@ -1116,22 +1127,73 @@ function messageContentBlock(
1116
1127
  return fail("INVALID_INPUT");
1117
1128
  }
1118
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
+
1119
1175
  function messages(
1120
1176
  value: unknown,
1121
1177
  preserveThinkingCacheControl: boolean,
1122
- ): readonly Message[] {
1178
+ acceptControlMessages: false,
1179
+ ): readonly Message[];
1180
+ function messages(
1181
+ value: unknown,
1182
+ preserveThinkingCacheControl: boolean,
1183
+ acceptControlMessages: boolean,
1184
+ ): readonly WireMessage[];
1185
+ function messages(
1186
+ value: unknown,
1187
+ preserveThinkingCacheControl: boolean,
1188
+ acceptControlMessages: boolean,
1189
+ ): readonly WireMessage[] {
1123
1190
  if (!Array.isArray(value)) fail("INVALID_INPUT");
1124
1191
  const useIds = new Set<string>();
1125
1192
  const resultIds: string[] = [];
1126
- const result = value.map((item): Message => {
1127
- const record = requireRecord(item);
1128
- assertExactKeys(record, MESSAGE_KEYS);
1129
- const role = record["role"];
1130
- if (role !== "user" && role !== "assistant") fail("INVALID_INPUT");
1131
- const rawContent = record["content"];
1132
- if (typeof rawContent === "string") return { role, content: rawContent };
1193
+ const messageContent = (rawContent: unknown): MessageContent => {
1194
+ if (typeof rawContent === "string") return rawContent;
1133
1195
  if (!Array.isArray(rawContent)) fail("INVALID_INPUT");
1134
- const content = rawContent.map((block) => {
1196
+ return rawContent.map((block) => {
1135
1197
  const blockRecord = requireRecord(block);
1136
1198
  if (blockRecord["type"] === "text") return textBlock(blockRecord);
1137
1199
  if (blockRecord["type"] === "tool_use") {
@@ -1147,7 +1209,27 @@ function messages(
1147
1209
  }
1148
1210
  return messageContentBlock(blockRecord, preserveThinkingCacheControl);
1149
1211
  });
1150
- 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"]) };
1151
1233
  });
1152
1234
  for (const id of resultIds) {
1153
1235
  if (!useIds.has(id)) fail("INVALID_INPUT");
@@ -1772,11 +1854,100 @@ export function canonicalCountTokensLists(
1772
1854
  return {
1773
1855
  // The count-tokens endpoint has no seam of its own, so thinking blocks stay
1774
1856
  // on the strict allowlist here.
1775
- messages: messages(rawMessages, false),
1857
+ messages: messages(rawMessages, false, false),
1776
1858
  tools: rawTools === undefined ? Object.freeze([]) : tools(rawTools),
1777
1859
  };
1778
1860
  }
1779
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
+
1780
1951
  export function buildCanonicalBody(
1781
1952
  rawInput: unknown,
1782
1953
  rawResolvedModel: unknown,
@@ -1784,6 +1955,7 @@ export function buildCanonicalBody(
1784
1955
  rawMetadata: unknown,
1785
1956
  profile?: ClaudeCodeProtocolProfile,
1786
1957
  thinkingDisplayOverride?: "updates",
1958
+ generated?: GeneratedBodyInputs,
1787
1959
  ): Readonly<Record<string, unknown>> {
1788
1960
  inspectJsonInputs(
1789
1961
  [
@@ -1820,7 +1992,11 @@ export function buildCanonicalBody(
1820
1992
  hasOwn(input, "preserveThinkingBlockCacheControl") &&
1821
1993
  requireBoolean(input["preserveThinkingBlockCacheControl"]);
1822
1994
  let systemBlocks = system(rawSystemBlocks);
1823
- let messageList = messages(input["messages"], preserveThinkingCacheControl);
1995
+ let messageList = messages(
1996
+ input["messages"],
1997
+ preserveThinkingCacheControl,
1998
+ profileBehaviors(effectiveProfile).perTurnControlMessages,
1999
+ );
1824
2000
  let toolList = hasOwn(input, "tools") ? tools(input["tools"]) : undefined;
1825
2001
  if (cacheOverride !== undefined && cacheOverride !== null) {
1826
2002
  systemBlocks = applySystemCacheControl(systemBlocks, cacheOverride);
@@ -1978,6 +2154,53 @@ export function buildCanonicalBody(
1978
2154
  else if (key === "stream") result["stream"] = requireBoolean(item);
1979
2155
  }
1980
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
+
1981
2204
  if (contextHintEnabled(profile)) {
1982
2205
  result["context_hint"] = { enabled: true };
1983
2206
  }
@@ -1991,5 +2214,7 @@ export function buildCanonicalBody(
1991
2214
  result[key] = experimentalBodyFields[key];
1992
2215
  }
1993
2216
  }
1994
- return deepFreeze(result);
2217
+ return deepFreeze(
2218
+ behaviors.genuineBodyKeyOrder ? orderGenuineBody(result) : result,
2219
+ );
1995
2220
  }
@@ -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
+ }