@tormentalabs/claude-code-wire-compat 0.1.0-rc.16 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,219 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import type {
4
+ AntiVerbosityPolicy,
5
+ AntiVerbositySection,
6
+ ClaudeCodeProtocolProfile,
7
+ } from "./contracts.js";
8
+ import { ClaudeCodeWireError } from "./contracts.js";
9
+ import { normalizeModelId } from "./model-identity.js";
10
+ import { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
11
+
12
+ /**
13
+ * The genuine client's anti-verbosity system-prompt section, and the three-way
14
+ * selector that chooses between its variants.
15
+ *
16
+ * Upstream this is `ytm(e)` at byte offset 238083640 of the
17
+ * pinned client build. The four strings below were not transcribed by hand: they
18
+ * were produced by executing the client's own template literals against stubbed
19
+ * predicates. The forensic dump tooling collapses non-printable runs and so
20
+ * cannot be trusted for whitespace inside a template literal; the branch-3
21
+ * heading in particular is followed by a newline, not a space, which a
22
+ * dump-based reading got wrong.
23
+ *
24
+ * The package EXPOSES this text and never injects it. `buildClaudeCodeRequest`
25
+ * does not consult this module. The genuine client assembles a large system
26
+ * prompt from many sections and this package models only the protocol envelope,
27
+ * so silently adding one section would produce a body matching neither the
28
+ * client nor the caller's intent. This is the same boundary already settled for
29
+ * `defaultEffort` and for cache-breakpoint placement: expose, let the caller
30
+ * decide.
31
+ */
32
+
33
+ /** Mirrors upstream defaults: a stock first-party install reports both false. */
34
+ export const DEFAULT_ANTI_VERBOSITY_POLICY: AntiVerbosityPolicy = Object.freeze(
35
+ {
36
+ briefModeEnabled: false,
37
+ pewterOwlToolEnabled: false,
38
+ },
39
+ );
40
+
41
+ /**
42
+ * Branch 1 with upstream `htm` true, which is the default because `htm` is
43
+ * `!(isBriefEnabled() || pewterOwlTool())`. Carries the extra paragraph about
44
+ * text written between tool calls.
45
+ */
46
+ export const COMMUNICATING_WITH_THE_USER_FULL =
47
+ "# Communicating with the user\n" +
48
+ "\n" +
49
+ "Your text output is what the user reads; they usually can't see your thinking or the raw tool results. Write it for a teammate who stepped away and is catching up, not for a log file: they don't know the codenames or shorthand you created along the way, and they didn't watch your process unfold. Before your first tool call, say in a sentence what you're about to do; while working, give brief updates when you find something load-bearing or change direction.\n" +
50
+ "\n" +
51
+ "Text you write between tool calls may not be shown to the user. Everything the user needs from this turn — answers, summaries, findings, conclusions, deliverables — must be in the final text message of your turn, with no tool calls after it. Keep text between tool calls to brief status notes. If something important appeared only mid-turn or in your thinking, restate it in that final message.\n" +
52
+ "\n" +
53
+ 'Lead with the outcome. Your first sentence after finishing should answer "what happened" or "what did you find" — the thing the user would ask for if they said "just give me the TLDR." Supporting detail and reasoning come after, for readers who want them.\n' +
54
+ "\n" +
55
+ "Being readable and being concise are different things, and readable matters more. If the user has to reread your summary or ask you to explain, any time saved by brevity is gone. The way to keep output short is to be selective about what you include (drop details that don't change what the reader would do next), not to compress the writing into fragments, abbreviations, arrow chains like `A → B → fails`, or jargon. What you do include, write in complete sentences with the technical terms spelled out. Don't make the reader cross-reference labels or numbering you invented earlier; say what you mean in place.\n" +
56
+ "\n" +
57
+ "Match the response to the question: a simple question gets a direct answer in prose, not headers and sections. Use tables only for short enumerable facts, with explanations in the surrounding prose rather than the cells. Calibrate to the user — a bit tighter for an expert, more explanatory for someone newer.\n" +
58
+ "\n" +
59
+ "Write code that reads like the surrounding code: match its comment density, naming, and idiom.\n" +
60
+ "Only write a code comment to state a constraint the code itself can't show — never to say where it came from, what the next line does, or why your change is correct; that's you talking to the reviewer, not the next reader, and it's noise the moment the PR merges.";
61
+
62
+ /** Branch 1 with upstream `htm` false: brief mode or the pewter-owl tool is on. */
63
+ export const COMMUNICATING_WITH_THE_USER_CONDENSED =
64
+ "# Communicating with the user\n" +
65
+ "\n" +
66
+ "Your text output is what the user reads between tool calls; they usually can't see your thinking or the raw tool results. Write it for a teammate who stepped away and is catching up, not for a log file: they don't know the codenames or shorthand you created along the way, and they didn't watch your process unfold. Before your first tool call, say in a sentence what you're about to do; while working, give brief updates when you find something load-bearing or change direction.\n" +
67
+ "\n" +
68
+ 'Lead with the outcome. Your first sentence after finishing should answer "what happened" or "what did you find" — the thing the user would ask for if they said "just give me the TLDR." Supporting detail and reasoning come after, for readers who want them.\n' +
69
+ "\n" +
70
+ "Being readable and being concise are different things, and readable matters more. If the user has to reread your summary or ask you to explain, any time saved by brevity is gone. The way to keep output short is to be selective about what you include (drop details that don't change what the reader would do next), not to compress the writing into fragments, abbreviations, arrow chains like `A → B → fails`, or jargon. What you do include, write in complete sentences with the technical terms spelled out. Don't make the reader cross-reference labels or numbering you invented earlier; say what you mean in place.\n" +
71
+ "\n" +
72
+ "Match the response to the question: a simple question gets a direct answer in prose, not headers and sections. Use tables only for short enumerable facts, with explanations in the surrounding prose rather than the cells. Calibrate to the user — a bit tighter for an expert, more explanatory for someone newer.\n" +
73
+ "\n" +
74
+ "Write code that reads like the surrounding code: match its comment density, naming, and idiom.\n" +
75
+ "Only write a code comment to state a constraint the code itself can't show — never to say where it came from, what the next line does, or why your change is correct; that's you talking to the reviewer, not the next reader, and it's noise the moment the PR merges.";
76
+
77
+ /** Branch 2, upstream `ph(e)` true. A single sentence. */
78
+ export const LEAN_SECTION =
79
+ "Write code that reads like the surrounding code: match its comment density, naming, and idiom.";
80
+
81
+ /** Branch 3, the fallthrough. */
82
+ export const TEXT_OUTPUT_SECTION =
83
+ "# Text output (does not apply to tool calls)\n" +
84
+ "Assume users can't see most tool calls or thinking — only your text output. Before your first tool call, state in one sentence what you're about to do. While working, give short updates at key moments: when you find something, when you change direction, or when you hit a blocker. Brief is good — silent is not. One sentence per update is almost always enough.\n" +
85
+ "\n" +
86
+ "Don't narrate your internal deliberation. User-facing text should be relevant communication to the user, not a running commentary on your thought process. State results and decisions directly, and focus user-facing text on relevant updates for the user.\n" +
87
+ "\n" +
88
+ "When you do write updates, write so the reader can pick up cold: complete sentences, no unexplained jargon or shorthand from earlier in the session. But keep it tight — a clear sentence is better than a clear paragraph.\n" +
89
+ "\n" +
90
+ "End-of-turn summary: one or two sentences. What changed and what's next. Nothing else.\n" +
91
+ "\n" +
92
+ "Match responses to the task: a simple question gets a direct answer, not headers and sections.\n" +
93
+ "\n" +
94
+ "In code: default to writing no comments. Never write multi-paragraph docstrings or multi-line comment blocks — one short line max. Don't create planning, decision, or analysis documents unless the user asks for them — work from conversation context, not intermediate files.";
95
+
96
+ /**
97
+ * SHA-256 of each constant as executed from the genuine client. A test pins
98
+ * these so any edit to the text above fails loudly rather than silently
99
+ * shipping a divergent prompt.
100
+ */
101
+ export const ANTI_VERBOSITY_DIGESTS = Object.freeze({
102
+ communicatingWithTheUserFull:
103
+ "41a8a87303e6f6f8224906daf9741fd6be495b79400854d92078991d15e9c56c",
104
+ communicatingWithTheUserCondensed:
105
+ "7028dc6d1492b7616b9b5f2f58416c09a0db5cd671f1032fbaeb9120ad51437b",
106
+ lean: "ee43af37398581e92bde06d341c98c7b7a9ff6c56023c2bc17b9feaf2d6e31ea",
107
+ textOutput:
108
+ "c184a5d4b4b6a0fc374a37c69f72937abf38bcccaa2d0cce0427968fcda3ccc7",
109
+ });
110
+
111
+ /** Upstream `i_e`, deliberately applied to the RAW caller string. */
112
+ const EAP_PATTERN = /-eap($|\[)/iu;
113
+
114
+ function catalogueCapability(
115
+ normalizedId: string,
116
+ capability: string,
117
+ profile: ClaudeCodeProtocolProfile,
118
+ ): boolean {
119
+ if (!Object.hasOwn(profile.supportedModels, normalizedId)) return false;
120
+ return (
121
+ profile.supportedModels[normalizedId]?.capabilities.includes(capability) ===
122
+ true
123
+ );
124
+ }
125
+
126
+ /**
127
+ * Upstream `Mte`. This is one of the few places where the catalogue capability
128
+ * array is genuinely load-bearing: unlike the nine model-capability predicates,
129
+ * `Mte` has no provider fallback, so the membership test decides the result.
130
+ */
131
+ function hasFableMitigations(
132
+ normalizedId: string,
133
+ profile: ClaudeCodeProtocolProfile,
134
+ ): boolean {
135
+ return (
136
+ catalogueCapability(normalizedId, "fable_5_mitigations", profile) ||
137
+ normalizedId === "claude-mythos-5"
138
+ );
139
+ }
140
+
141
+ /**
142
+ * Upstream `Kkd`. Its trailing `return !td()` is false on the first-party
143
+ * provider this profile pins, so an unrecognised identifier falls through to
144
+ * the lean branch rather than the text-output branch.
145
+ *
146
+ * Upstream also carries `|| t === "claude-mythos-5"` beside the
147
+ * `lean_prompt` test. It is omitted here because it is unreachable: the only
148
+ * caller tests `hasFableMitigations` first, which already claims mythos-5 for
149
+ * the communicating-with-the-user branch. Upstream shares `Kkd` with other
150
+ * call sites and so still needs it. Restore it if this helper ever gains a
151
+ * second caller.
152
+ */
153
+ function usesTextOutputSection(
154
+ rawModel: string,
155
+ profile: ClaudeCodeProtocolProfile,
156
+ ): boolean {
157
+ if (EAP_PATTERN.test(rawModel)) return false;
158
+ const id = normalizeModelId(rawModel);
159
+ if (catalogueCapability(id, "lean_prompt", profile)) return false;
160
+ return (
161
+ id.includes("claude-3-") ||
162
+ id.includes("haiku") ||
163
+ id.includes("sonnet") ||
164
+ id === "claude-opus-4-0" ||
165
+ id === "claude-opus-4-1" ||
166
+ id === "claude-opus-4-5" ||
167
+ id === "claude-opus-4-6" ||
168
+ id === "claude-opus-4-7"
169
+ );
170
+ }
171
+
172
+ /**
173
+ * Reports which branch of upstream `ytm` a model selects.
174
+ *
175
+ * Upstream `gtm` is `return !1`, so branch 1 is gated on `Mte` alone. Note
176
+ * that `ytm` passes the NORMALISED id to `Mte` but the RAW caller string to
177
+ * `ph`, because `ph` reaches `i_e`, which must see an unnormalised
178
+ * `-eap` suffix. That asymmetry is reproduced here.
179
+ */
180
+ export function selectAntiVerbositySection(
181
+ rawModel: string,
182
+ profile: ClaudeCodeProtocolProfile = CLAUDE_CODE_2_1_195_PROFILE,
183
+ ): AntiVerbositySection {
184
+ if (typeof rawModel !== "string" || rawModel.length === 0) {
185
+ throw new ClaudeCodeWireError("INVALID_INPUT");
186
+ }
187
+ if (hasFableMitigations(normalizeModelId(rawModel), profile)) {
188
+ return "communicating-with-the-user";
189
+ }
190
+ return usesTextOutputSection(rawModel, profile) ? "text-output" : "lean";
191
+ }
192
+
193
+ /** Returns the exact section text the genuine client would emit for a model. */
194
+ export function antiVerbosityText(
195
+ rawModel: string,
196
+ policy: AntiVerbosityPolicy = DEFAULT_ANTI_VERBOSITY_POLICY,
197
+ profile: ClaudeCodeProtocolProfile = CLAUDE_CODE_2_1_195_PROFILE,
198
+ ): string {
199
+ // Validated eagerly, and for every section rather than only the one that
200
+ // reads it, so a malformed policy fails the same way regardless of which
201
+ // model it is paired with. `selectAntiVerbositySection` validates its own
202
+ // argument the same way despite the declared types, because callers reach
203
+ // this module across an untyped boundary.
204
+ const candidate: unknown = policy;
205
+ if (candidate === null || typeof candidate !== "object") {
206
+ throw new ClaudeCodeWireError("INVALID_INPUT");
207
+ }
208
+ const brief: unknown = Reflect.get(candidate, "briefModeEnabled");
209
+ const pewterOwl: unknown = Reflect.get(candidate, "pewterOwlToolEnabled");
210
+ if (typeof brief !== "boolean" || typeof pewterOwl !== "boolean") {
211
+ throw new ClaudeCodeWireError("INVALID_INPUT");
212
+ }
213
+ const section = selectAntiVerbositySection(rawModel, profile);
214
+ if (section === "lean") return LEAN_SECTION;
215
+ if (section === "text-output") return TEXT_OUTPUT_SECTION;
216
+ return brief || pewterOwl
217
+ ? COMMUNICATING_WITH_THE_USER_CONDENSED
218
+ : COMMUNICATING_WITH_THE_USER_FULL;
219
+ }
@@ -0,0 +1,140 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ interface BetaRegistryEntry {
4
+ readonly featureKey: string;
5
+ readonly header: string;
6
+ }
7
+
8
+ function deepFreeze<T>(value: T): T {
9
+ if (value !== null && typeof value === "object") {
10
+ for (const key of Reflect.ownKeys(value)) {
11
+ deepFreeze(Reflect.get(value, key));
12
+ }
13
+ Object.freeze(value);
14
+ }
15
+ return value;
16
+ }
17
+
18
+ /** Genuine-client beta registry, upstream `Udd`. */
19
+ export const BETA_REGISTRY = deepFreeze({
20
+ CLAUDE_CODE: { featureKey: "claude_code", header: "claude-code-20250219" }, // Y2e
21
+ OAUTH_AUTH: { featureKey: "oauth_auth", header: "oauth-2025-04-20" }, // qIe
22
+ INTERLEAVED_THINKING: {
23
+ featureKey: "interleaved_thinking",
24
+ header: "interleaved-thinking-2025-05-14",
25
+ }, // Gnt
26
+ LONG_CONTEXT: { featureKey: "long_context", header: "context-1m-2025-08-07" }, // FY
27
+ CONTEXT_MANAGEMENT: {
28
+ featureKey: "context_management",
29
+ header: "context-management-2025-06-27",
30
+ }, // X2e
31
+ STRUCTURED_OUTPUTS: {
32
+ featureKey: "structured_outputs",
33
+ header: "structured-outputs-2025-12-15",
34
+ }, // lte
35
+ WEB_SEARCH: { featureKey: "web_search", header: "web-search-2025-03-05" }, // IPt
36
+ ADVANCED_TOOL_USE: {
37
+ featureKey: "tool_search",
38
+ header: "advanced-tool-use-2025-11-20",
39
+ }, // p2r
40
+ TOOL_SEARCH: {
41
+ featureKey: "tool_search",
42
+ header: "tool-search-tool-2025-10-19",
43
+ }, // xPt
44
+ EFFORT: { featureKey: "effort", header: "effort-2025-11-24" }, // Wnt
45
+ TASK_BUDGETS: {
46
+ featureKey: "task_budgets",
47
+ header: "task-budgets-2026-03-13",
48
+ }, // lAn
49
+ PROMPT_CACHING_SCOPE: {
50
+ featureKey: "prompt_caching_scope",
51
+ header: "prompt-caching-scope-2026-01-05",
52
+ }, // qnt
53
+ EXTENDED_CACHE_TTL: {
54
+ featureKey: "extended_cache_ttl",
55
+ header: "extended-cache-ttl-2025-04-11",
56
+ }, // J2e
57
+ SPEED: { featureKey: "speed", header: "fast-mode-2026-02-01" }, // Vnt
58
+ REDACT_THINKING: {
59
+ featureKey: "redact_thinking",
60
+ header: "redact-thinking-2026-02-12",
61
+ }, // kPt
62
+ THINKING_TOKEN_COUNT: {
63
+ featureKey: "thinking_token_count",
64
+ header: "thinking-token-count-2026-05-13",
65
+ }, // cAn
66
+ NARRATION_SUMMARIES: {
67
+ featureKey: "narration_summaries",
68
+ header: "summarize-connector-text-2026-03-13",
69
+ }, // RPt
70
+ AFK_MODE: { featureKey: "afk_mode", header: "afk-mode-2026-01-31" }, // T0
71
+ ADVISOR_TOOL: {
72
+ featureKey: "advisor_tool",
73
+ header: "advisor-tool-2026-03-01",
74
+ }, // f2r
75
+ CACHE_DIAGNOSIS: {
76
+ featureKey: "cache_diagnosis",
77
+ header: "cache-diagnosis-2026-04-07",
78
+ }, // fye
79
+ CONTEXT_HINT: {
80
+ featureKey: "context_hint",
81
+ header: "context-hint-2026-04-09",
82
+ }, // m2r
83
+ MCP_SERVERS: {
84
+ featureKey: "mcp_servers",
85
+ header: "mcp-servers-2025-12-04",
86
+ }, // g2r
87
+ FILES_API: { featureKey: "files_api", header: "files-api-2025-04-14" }, // h2r
88
+ ENVIRONMENTS: {
89
+ featureKey: "environments",
90
+ header: "environments-2025-11-01",
91
+ }, // y2r
92
+ CCR_BYOC: { featureKey: "ccr_byoc", header: "ccr-byoc-2025-07-29" }, // _2r
93
+ MID_CONVERSATION_SYSTEM: {
94
+ featureKey: "mid_conversation_system",
95
+ header: "mid-conversation-system-2026-04-07",
96
+ }, // jY
97
+ SERVER_SIDE_FALLBACK: {
98
+ featureKey: "server_side_fallback",
99
+ header: "server-side-fallback-2026-06-01",
100
+ }, // r1
101
+ FALLBACK_CREDIT: {
102
+ featureKey: "fallback_credit",
103
+ header: "fallback-credit-2026-06-01",
104
+ }, // o1
105
+ } satisfies Record<string, BetaRegistryEntry>);
106
+
107
+ // Reserved for later work packages; upstream `Pvi` third-party filtering.
108
+ export const THIRD_PARTY_ALLOWED_BETAS: ReadonlySet<string> = Object.freeze(
109
+ new Set([
110
+ BETA_REGISTRY.CLAUDE_CODE.header,
111
+ BETA_REGISTRY.INTERLEAVED_THINKING.header,
112
+ BETA_REGISTRY.LONG_CONTEXT.header,
113
+ BETA_REGISTRY.CONTEXT_MANAGEMENT.header,
114
+ BETA_REGISTRY.STRUCTURED_OUTPUTS.header,
115
+ BETA_REGISTRY.WEB_SEARCH.header,
116
+ BETA_REGISTRY.EFFORT.header,
117
+ BETA_REGISTRY.TOOL_SEARCH.header,
118
+ BETA_REGISTRY.AFK_MODE.header,
119
+ BETA_REGISTRY.FALLBACK_CREDIT.header,
120
+ ]),
121
+ );
122
+
123
+ // Reserved for later work packages; upstream `S2r` provider filtering.
124
+ export const BEDROCK_UNSUPPORTED_BETAS: ReadonlySet<string> = Object.freeze(
125
+ new Set([
126
+ BETA_REGISTRY.INTERLEAVED_THINKING.header,
127
+ BETA_REGISTRY.LONG_CONTEXT.header,
128
+ BETA_REGISTRY.TOOL_SEARCH.header,
129
+ ]),
130
+ );
131
+
132
+ // Reserved for later work packages; upstream `E2r` count-tokens selection.
133
+ export const COUNT_TOKENS_BETAS: ReadonlySet<string> = Object.freeze(
134
+ new Set([
135
+ BETA_REGISTRY.CLAUDE_CODE.header,
136
+ BETA_REGISTRY.INTERLEAVED_THINKING.header,
137
+ BETA_REGISTRY.CONTEXT_MANAGEMENT.header,
138
+ BETA_REGISTRY.OAUTH_AUTH.header,
139
+ ]),
140
+ );
package/src/betas.ts ADDED
@@ -0,0 +1,219 @@
1
+ // SPDX-License-Identifier: GPL-3.0-or-later
2
+
3
+ import { BETA_REGISTRY } from "./beta-registry.js";
4
+ import type {
5
+ ClaudeCodeCapabilities,
6
+ ClaudeCodeProtocolProfile,
7
+ } from "./contracts.js";
8
+ import { ClaudeCodeWireError } from "./contracts.js";
9
+ import {
10
+ supportsMidConversationSystem,
11
+ supportsStructuredOutputs,
12
+ } from "./model-capabilities.js";
13
+ import { CLAUDE_CODE_2_1_195_PROFILE } from "./profiles/claude-code-2.1.195.js";
14
+
15
+ /*
16
+ * Provenance. The emitted order is a port of the genuine client's base beta set
17
+ * `$9r` (byte offset 227387921), followed by the gated pushes the request
18
+ * builder performs afterwards (bytes 238153535-238155672). The identifiers
19
+ * themselves come from registry `Udd`, ported verbatim as `BETA_REGISTRY`.
20
+ *
21
+ * The order is EMERGENT, not declared: upstream neither sorts the array nor
22
+ * keeps a canonical list, so the sequence below is load-bearing and must not be
23
+ * reordered for tidiness. `docs/source-trace.md` records the same fact under
24
+ * "Beta registry and push order".
25
+ */
26
+ export interface ComposeBetasInput {
27
+ readonly rawModel: string;
28
+ readonly normalizedId: string;
29
+ readonly capabilities: ClaudeCodeCapabilities;
30
+ readonly thinkingDisplayActive: boolean;
31
+ readonly cacheTtl?: "5m" | "1h" | null;
32
+ readonly speed?: "standard" | "fast" | null;
33
+ /**
34
+ * Package extension, not observed upstream behaviour. Consumer-supplied beta
35
+ * identifiers appended AFTER the derived canonical set. See
36
+ * `docs/source-trace.md`, governance ledger L10.
37
+ */
38
+ readonly additionalBetas?: readonly string[];
39
+ /**
40
+ * Package extension, not observed upstream behaviour. Beta identifiers
41
+ * removed from the emitted set AFTER composition and AFTER the
42
+ * `additionalBetas` merge, so suppression beats addition. An identifier that
43
+ * is not in the composed set is a silent no-op. See `docs/source-trace.md`,
44
+ * governance ledger L14.
45
+ */
46
+ readonly suppressBetas?: readonly string[];
47
+ /**
48
+ * Package extension, not observed upstream behaviour. Forces (`true`) or
49
+ * suppresses (`false`) the 1M-context beta for this request, overriding the
50
+ * `[1m]` model marker. See `docs/source-trace.md`, governance ledger L10.
51
+ */
52
+ readonly use1MContextOverride?: boolean;
53
+ }
54
+
55
+ /**
56
+ * Reports the emitted beta set together with the identifiers `suppressBetas`
57
+ * actually removed. `suppressedBetaNames` is empty when the seam is unused or
58
+ * matched nothing, which is what keeps the evidence key absent for every
59
+ * request built before the seam existed.
60
+ */
61
+ export interface ComposedBetas {
62
+ readonly betas: readonly string[];
63
+ readonly suppressedBetaNames: readonly string[];
64
+ }
65
+
66
+ /**
67
+ * Bounds a caller-supplied beta list (`additionalBetas` and `suppressBetas`
68
+ * share these rules verbatim). The header is a comma-joined single
69
+ * field, so a comma, control character, or whitespace in an entry would let a
70
+ * caller synthesize extra beta values (or, with CR/LF, an entirely separate
71
+ * header). The allowlist below is deliberately narrower than the observed
72
+ * upstream identifiers require, because every genuine beta name in
73
+ * `BETA_REGISTRY` matches it.
74
+ */
75
+ const ADDITIONAL_BETA_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/u;
76
+ const MAX_ADDITIONAL_BETA_LENGTH = 128;
77
+ const MAX_ADDITIONAL_BETAS = 32;
78
+
79
+ function validateAdditionalBetas(value: unknown): readonly string[] {
80
+ if (!Array.isArray(value) || value.length > MAX_ADDITIONAL_BETAS) {
81
+ throw new ClaudeCodeWireError("INVALID_INPUT");
82
+ }
83
+ return value.map((entry: unknown): string => {
84
+ if (
85
+ typeof entry !== "string" ||
86
+ entry.length === 0 ||
87
+ entry.length > MAX_ADDITIONAL_BETA_LENGTH ||
88
+ !ADDITIONAL_BETA_PATTERN.test(entry)
89
+ ) {
90
+ throw new ClaudeCodeWireError("INVALID_INPUT");
91
+ }
92
+ return entry;
93
+ });
94
+ }
95
+
96
+ const NO_SUPPRESSED_BETAS: readonly string[] = Object.freeze([]);
97
+
98
+ export function composeBetas(
99
+ input: ComposeBetasInput,
100
+ profile: ClaudeCodeProtocolProfile = CLAUDE_CODE_2_1_195_PROFILE,
101
+ ): readonly string[] {
102
+ return composeBetasWithAudit(input, profile).betas;
103
+ }
104
+
105
+ export function composeBetasWithAudit(
106
+ input: ComposeBetasInput,
107
+ profile: ClaudeCodeProtocolProfile = CLAUDE_CODE_2_1_195_PROFILE,
108
+ ): ComposedBetas {
109
+ const out: string[] = [];
110
+ const policy = profile.betaPolicy;
111
+ const experimental = policy.experimentalBetasEnabled;
112
+
113
+ if (!input.normalizedId.includes("haiku"))
114
+ out.push(BETA_REGISTRY.CLAUDE_CODE.header);
115
+ if (policy.oauthAuthenticated) out.push(BETA_REGISTRY.OAUTH_AUTH.header);
116
+ // Package extension: `use1MContextOverride` replaces the model-marker gate
117
+ // for this request. The profile gate still applies, so an override cannot
118
+ // enable a beta the pinned profile declares unavailable.
119
+ const oneMillionRequested =
120
+ input.use1MContextOverride ?? /\[1m\]/iu.test(input.rawModel);
121
+ if (policy.oneMillionContextEnabled && oneMillionRequested) {
122
+ out.push(BETA_REGISTRY.LONG_CONTEXT.header);
123
+ }
124
+ if (
125
+ policy.interleavedThinkingEnabled &&
126
+ input.capabilities.interleavedThinking
127
+ ) {
128
+ out.push(BETA_REGISTRY.INTERLEAVED_THINKING.header);
129
+ }
130
+ if (
131
+ experimental &&
132
+ input.capabilities.interleavedThinking &&
133
+ policy.interactive &&
134
+ !policy.thinkingSummariesShown &&
135
+ !input.thinkingDisplayActive
136
+ ) {
137
+ out.push(BETA_REGISTRY.REDACT_THINKING.header);
138
+ }
139
+ if (
140
+ policy.thinkingTokenCountEnabled &&
141
+ experimental &&
142
+ input.capabilities.interleavedThinking
143
+ ) {
144
+ out.push(BETA_REGISTRY.THINKING_TOKEN_COUNT.header);
145
+ }
146
+ if (experimental && policy.narrationSummariesEnabled)
147
+ out.push(BETA_REGISTRY.NARRATION_SUMMARIES.header);
148
+ if (experimental && input.capabilities.contextManagement)
149
+ out.push(BETA_REGISTRY.CONTEXT_MANAGEMENT.header);
150
+ if (
151
+ experimental &&
152
+ supportsStructuredOutputs(input.normalizedId) &&
153
+ policy.structuredOutputsEnabled
154
+ ) {
155
+ out.push(BETA_REGISTRY.STRUCTURED_OUTPUTS.header);
156
+ }
157
+
158
+ // No web-search beta: upstream pushes it only for vertex and foundry.
159
+ if (experimental) out.push(BETA_REGISTRY.PROMPT_CACHING_SCOPE.header);
160
+ if (supportsMidConversationSystem(input.normalizedId))
161
+ out.push(BETA_REGISTRY.MID_CONVERSATION_SYSTEM.header);
162
+ if (input.capabilities.effort) out.push(BETA_REGISTRY.EFFORT.header);
163
+
164
+ if (input.speed === "fast" && !out.includes(BETA_REGISTRY.SPEED.header)) {
165
+ out.push(BETA_REGISTRY.SPEED.header);
166
+ }
167
+ if (policy.afkModeEnabled && !out.includes(BETA_REGISTRY.AFK_MODE.header)) {
168
+ out.push(BETA_REGISTRY.AFK_MODE.header);
169
+ }
170
+ if (
171
+ input.cacheTtl === "1h" &&
172
+ experimental &&
173
+ !out.includes(BETA_REGISTRY.EXTENDED_CACHE_TTL.header)
174
+ ) {
175
+ out.push(BETA_REGISTRY.EXTENDED_CACHE_TTL.header);
176
+ }
177
+ if (profile.contextHintEnabled) out.push(BETA_REGISTRY.CONTEXT_HINT.header);
178
+ if (
179
+ policy.cacheDiagnosisEnabled &&
180
+ !out.includes(BETA_REGISTRY.CACHE_DIAGNOSIS.header)
181
+ ) {
182
+ out.push(BETA_REGISTRY.CACHE_DIAGNOSIS.header);
183
+ }
184
+
185
+ // No advisor-tool beta: upstream has no observed unconditional push site.
186
+
187
+ // Package extension. Canonical, upstream-derived identifiers always precede
188
+ // caller-supplied ones, and a caller entry that duplicates an already-emitted
189
+ // identifier is dropped rather than reordering the canonical prefix.
190
+ if (input.additionalBetas !== undefined) {
191
+ for (const beta of validateAdditionalBetas(input.additionalBetas)) {
192
+ if (!out.includes(beta)) out.push(beta);
193
+ }
194
+ }
195
+
196
+ // Package extension. The suppression filter is deliberately LAST: it runs
197
+ // after the canonical composition and after the `additionalBetas` merge, so
198
+ // an identifier named by both seams does not reach the wire. Removal is
199
+ // reported in composed order, never in caller order, and an identifier that
200
+ // was never composed is a silent no-op because a consumer cannot know which
201
+ // betas this package derives for a given model.
202
+ if (input.suppressBetas === undefined) {
203
+ return Object.freeze({
204
+ betas: Object.freeze(out),
205
+ suppressedBetaNames: NO_SUPPRESSED_BETAS,
206
+ });
207
+ }
208
+ const suppressed = new Set(validateAdditionalBetas(input.suppressBetas));
209
+ const kept: string[] = [];
210
+ const removed: string[] = [];
211
+ for (const beta of out) {
212
+ if (suppressed.has(beta)) removed.push(beta);
213
+ else kept.push(beta);
214
+ }
215
+ return Object.freeze({
216
+ betas: Object.freeze(kept),
217
+ suppressedBetaNames: Object.freeze(removed),
218
+ });
219
+ }