leakshield 0.3.0 → 0.4.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 (110) hide show
  1. package/LICENSE +202 -21
  2. package/NOTICE +2 -0
  3. package/README.md +39 -9
  4. package/README.zh-TW.md +38 -9
  5. package/dist/adapters/claude-code/capabilities.d.ts +14 -0
  6. package/dist/adapters/claude-code/capabilities.js +47 -0
  7. package/dist/adapters/claude-code/cli.d.ts +10 -0
  8. package/dist/adapters/claude-code/cli.js +51 -0
  9. package/dist/adapters/claude-code/doctor.d.ts +19 -0
  10. package/dist/adapters/claude-code/doctor.js +177 -0
  11. package/dist/adapters/claude-code/proxy.d.ts +47 -0
  12. package/dist/adapters/claude-code/proxy.js +348 -0
  13. package/dist/adapters/opencode/capabilities.d.ts +10 -0
  14. package/dist/adapters/opencode/capabilities.js +48 -0
  15. package/dist/adapters/opencode/doctor.d.ts +67 -0
  16. package/dist/{doctor.js → adapters/opencode/doctor.js} +16 -42
  17. package/dist/adapters/opencode/env-queries.d.ts +133 -0
  18. package/dist/adapters/opencode/env-tools.d.ts +20 -0
  19. package/dist/adapters/opencode/hooks.d.ts +4 -0
  20. package/dist/adapters/opencode/plugin.d.ts +12 -0
  21. package/dist/{opencode.js → adapters/opencode/plugin.js} +7 -7
  22. package/dist/adapters/opencode/tool-policy.d.ts +2 -0
  23. package/dist/adapters/opencode/tool-policy.js +23 -0
  24. package/dist/adapters/opencode/transparent-aisdk.d.ts +6 -0
  25. package/dist/{opencode-transparent-aisdk.js → adapters/opencode/transparent-aisdk.js} +1 -1
  26. package/dist/adapters/opencode/transparent.d.ts +66 -0
  27. package/dist/adapters/opencode/transparent.js +237 -0
  28. package/dist/adapters/opencode/v2.d.ts +20 -0
  29. package/dist/{opencode-v2.js → adapters/opencode/v2.js} +3 -3
  30. package/dist/adapters/pi/capabilities.d.ts +10 -0
  31. package/dist/adapters/pi/capabilities.js +50 -0
  32. package/dist/adapters/pi/doctor.d.ts +26 -0
  33. package/dist/adapters/pi/doctor.js +276 -0
  34. package/dist/adapters/pi/extension.d.ts +28 -0
  35. package/dist/adapters/pi/extension.js +109 -0
  36. package/dist/adapters/pi/guard.d.ts +33 -0
  37. package/dist/adapters/pi/guard.js +154 -0
  38. package/dist/adapters/pi/persistence.d.ts +9 -0
  39. package/dist/adapters/pi/persistence.js +69 -0
  40. package/dist/adapters/pi/settings.d.ts +51 -0
  41. package/dist/adapters/pi/settings.js +136 -0
  42. package/dist/adapters/pi/tool-policy.d.ts +11 -0
  43. package/dist/adapters/pi/tool-policy.js +114 -0
  44. package/dist/cli.d.ts +18 -0
  45. package/dist/cli.js +17 -6
  46. package/dist/config/loader.d.ts +70 -0
  47. package/dist/config/plain-object.d.ts +2 -0
  48. package/dist/core/index.d.ts +9 -0
  49. package/dist/core/index.js +9 -0
  50. package/dist/core/session-guard.d.ts +61 -0
  51. package/dist/{opencode-transparent.js → core/session-guard.js} +55 -713
  52. package/dist/core/sse-recovery.d.ts +6 -0
  53. package/dist/core/tool-restore-policy.d.ts +153 -0
  54. package/dist/core/tool-restore-policy.js +453 -0
  55. package/dist/core/wire.d.ts +213 -0
  56. package/dist/{opencode-transparent-http.js → core/wire.js} +170 -50
  57. package/dist/core/ws.d.ts +26 -0
  58. package/dist/{opencode-transparent-ws.js → core/ws.js} +1 -1
  59. package/dist/decision/deidentify.d.ts +63 -0
  60. package/dist/decision/ingress.d.ts +40 -0
  61. package/dist/decision/mapping-key.d.ts +91 -0
  62. package/dist/decision/mapping-store.d.ts +166 -0
  63. package/dist/decision/model.d.ts +41 -0
  64. package/dist/decision/pseudonymization.d.ts +176 -0
  65. package/dist/decision/redaction.d.ts +56 -0
  66. package/dist/decision/schema-strings.d.ts +23 -0
  67. package/dist/decision/schema-strings.js +2 -2
  68. package/dist/decision/value-search.d.ts +39 -0
  69. package/dist/doctor-capabilities.d.ts +21 -0
  70. package/dist/doctor-capabilities.js +58 -0
  71. package/dist/doctor-hosts.d.ts +18 -0
  72. package/dist/doctor-hosts.js +144 -0
  73. package/dist/doctor-report.d.ts +45 -0
  74. package/dist/doctor-report.js +111 -0
  75. package/dist/forget.d.ts +18 -0
  76. package/dist/guard-options.d.ts +45 -0
  77. package/dist/{plugin-options.js → guard-options.js} +4 -1
  78. package/dist/help.d.ts +2 -0
  79. package/dist/help.js +15 -1
  80. package/dist/i18n/en.d.ts +65 -0
  81. package/dist/i18n/index.d.ts +15 -0
  82. package/dist/i18n/zh-TW.d.ts +65 -0
  83. package/dist/index.d.ts +13 -0
  84. package/dist/index.js +1 -1
  85. package/dist/rules/builtin.d.ts +4 -0
  86. package/dist/rules/dynamic.d.ts +33 -0
  87. package/dist/scanner/allowlist.d.ts +22 -0
  88. package/dist/scanner/cidr.d.ts +39 -0
  89. package/dist/scanner/encoding.d.ts +87 -0
  90. package/dist/scanner/engine.d.ts +43 -0
  91. package/dist/scanner/exact-values.d.ts +11 -0
  92. package/dist/scanner/redaction-verifier.d.ts +24 -0
  93. package/dist/scanner/remotes.d.ts +29 -0
  94. package/dist/scanner/unicode.d.ts +57 -0
  95. package/dist/scanner/utils.d.ts +22 -0
  96. package/dist/transports/cli.d.ts +27 -0
  97. package/dist/transports/web-ui.d.ts +1 -0
  98. package/dist/transports/web-ui.js +1 -1
  99. package/dist/transports/web.d.ts +4 -0
  100. package/dist/types/capabilities.d.ts +67 -0
  101. package/dist/types/capabilities.js +133 -0
  102. package/dist/types.d.ts +149 -0
  103. package/dist/utils/files.d.ts +3 -0
  104. package/dist/utils/path-security.d.ts +18 -0
  105. package/dist/utils/win-encoding.d.ts +16 -0
  106. package/package.json +15 -5
  107. /package/dist/{env-queries.js → adapters/opencode/env-queries.js} +0 -0
  108. /package/dist/{opencode-env-tools.js → adapters/opencode/env-tools.js} +0 -0
  109. /package/dist/{opencode-hooks.js → adapters/opencode/hooks.js} +0 -0
  110. /package/dist/{opencode-transparent-stream.js → core/sse-recovery.js} +0 -0
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Transport-boundary helpers for OpenCode v2 transparent pseudonymization
3
+ * (issue #22; protocol selection is not provider-brand selection).
4
+ *
5
+ * Source-verified against the installed @opencode/plugin 2.0.19 declarations:
6
+ * `session:http.request` / `session:http.response` expose native `Request` /
7
+ * `Response` objects whose bodies are one-shot streams (clone before reading).
8
+ * Supported wire protocols are the three custom-provider dialects — OpenAI
9
+ * Chat Completions, Anthropic Messages and OpenAI Responses — selected by URL
10
+ * path shape; each has JSON / event-stream response restore.
11
+ *
12
+ * Outbound enforcement and ingress restoration:
13
+ * - Final-wire masking refuses unsupported routes, mixed dialects and
14
+ * bodyless requests. Explicit false admission may accept an unknown route
15
+ * with scoped host preparation proof; its opaque body is not inspected.
16
+ * A placeholder in transport metadata or the URL is judged
17
+ * session-aware instead: clean markers are preserved verbatim with a
18
+ * content-free WARN; sensitive content still refuses (unmaskable
19
+ * position).
20
+ * - Transport metadata is inspected: decoded non-auth headers and query
21
+ * parameters, and numeric body values, must not scan as sensitive;
22
+ * legitimate authentication headers are preserved.
23
+ * - The whole body is validated BEFORE any token is issued, then protected in
24
+ * ONE atomic transaction, so a rejected request commits no mapping or
25
+ * session capacity.
26
+ * - Protocol metadata (model ids, tools, usage, numeric fields, envelopes) is
27
+ * never rewritten: structural identifiers (message ids, roles, part types,
28
+ * tool names and schema keys/enum constraints) are preserved and a
29
+ * sensitive one refuses the request rather than being silently renamed.
30
+ * - Response restore touches assistant display text only: owned tokens are
31
+ * restored and unknown/malformed marker strings remain literal there. A
32
+ * placeholder in an unplaceable response field is degradation — kept
33
+ * literal with a WARN — never a refusal; actual tool arguments remain
34
+ * tokenized for the typed tool gate.
35
+ * - Streaming is pull-based with bounded original-event transactions and
36
+ * channel state. SG parser/restore failures replay undelivered originals,
37
+ * then bypass rewriting; source errors and cancellation remain failures.
38
+ * Non-stream restoration failures are recovered by the session hook.
39
+ */
40
+ import { type PseudonymJsonResult, type PseudonymTextResult } from "../decision/pseudonymization.js";
41
+ /** The masking/detection subset of the pseudonymization core this module needs. */
42
+ export interface TransportMaskingService {
43
+ protectJsonForModel(sessionID: string, value: unknown): PseudonymJsonResult;
44
+ restoreText(sessionID: string, text: string): PseudonymTextResult;
45
+ restoreTextForDisplay(sessionID: string, text: string): PseudonymTextResult;
46
+ /** Non-committing sensitivity detection: no mapping, no mutation. */
47
+ detectSensitive(text: string): boolean;
48
+ /**
49
+ * Session-aware judgement for structural positions (identifiers, transport
50
+ * metadata): marker-shaped content is safe when clean (registered-marker
51
+ * interiors exempt, unregistered payloads scanned); unsafe on a finding,
52
+ * because the position cannot be masked without breaking the protocol.
53
+ */
54
+ isStructuralIdentifierSafe(sessionID: string, text: string): boolean;
55
+ /**
56
+ * Field-aware transport variants: identical to the strict checks except
57
+ * that PII_URL findings are exempt. The request URL, query values, and
58
+ * header values are infrastructure positions — masking or refusing an
59
+ * endpoint URL would break every request once the opt-in URL rule is
60
+ * enabled, so URL findings are ignored there. User-content URLs inside
61
+ * the request body are unaffected (still masked).
62
+ */
63
+ transportDetectSensitive(text: string): boolean;
64
+ /** Transport variant of {@link isStructuralIdentifierSafe} (PII_URL exempt). */
65
+ isTransportIdentifierSafe(sessionID: string, text: string): boolean;
66
+ /**
67
+ * Attachment policy: "block" (default) refuses media/file parts at the
68
+ * wire; "allow" tolerates them as opaque leaves that are substituted with a
69
+ * sentinel around the masking transaction and restored verbatim after it,
70
+ * so binary payloads are neither scanned nor altered.
71
+ */
72
+ readonly attachmentsPolicy?: "block" | "allow";
73
+ /**
74
+ * Anthropic extended-thinking history blocks. "refuse" (default) keeps the
75
+ * original contract: any `thinking` / `redacted_thinking` block refuses the
76
+ * request. "mask" accepts them: thinking text is masked like other text,
77
+ * while `signature` and `redacted_thinking.data` cross verbatim as opaque
78
+ * provider state (never scanned, never altered).
79
+ */
80
+ readonly anthropicThinking?: "refuse" | "mask";
81
+ }
82
+ /** Wire routes this module can protect, detected by URL PATH SHAPE — never by
83
+ * provider or model name, so any endpoint speaking a supported dialect
84
+ * (OpenAI-compatible gateways, Anthropic-native, …) is covered uniformly. */
85
+ export type ModelWireRoute = "chat-completions" | "anthropic-messages" | "openai-responses";
86
+ export declare function classifyModelRoute(url: string): ModelWireRoute | null;
87
+ /**
88
+ * In "allow" mode, temporarily substitutes every media/file record with a
89
+ * unique sentinel string around the masking transaction, then restores the
90
+ * originals into the protected result: binary payloads are neither scanned
91
+ * nor altered, and the structural checks outside this wrapper see identical
92
+ * attachment records before and after. Shared by the wire remaskers and the
93
+ * session-layer request guard so "allow means unscanned" holds at both
94
+ * boundaries.
95
+ */
96
+ export declare function withOpaqueAttachments<T extends Record<string, unknown>>(policy: "block" | "allow", body: T, fn: (input: T) => T): T;
97
+ /**
98
+ * Remasks an OpenAI-compatible Chat Completions JSON request body.
99
+ *
100
+ * Every check that can reject runs FIRST (route, transport metadata, dialect,
101
+ * message shapes, structural identifiers, numeric values); only then is the
102
+ * whole body protected in a SINGLE transaction, so a rejected request commits
103
+ * no mapping or session capacity. The original request is consumed only through
104
+ * `clone()`; the ORIGINAL request object is returned only when its body already
105
+ * is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
106
+ * mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
107
+ * authentication headers) and recomputes body headers.
108
+ */
109
+ export declare function remaskChatCompletionsRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
110
+ /**
111
+ * Remasks an Anthropic Messages JSON request body. Same contract as the
112
+ * chat-completions path: every check that can reject runs FIRST, then the
113
+ * whole body is protected in ONE transaction; a rejected request commits no
114
+ * mapping or session capacity. tool_use.input is already a JSON object (no
115
+ * string re-encoding needed) and stays tokenized on the wire; the typed tool
116
+ * gate restores before execution.
117
+ */
118
+ export declare function remaskAnthropicMessagesRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
119
+ /**
120
+ * Remasks an OpenAI Responses JSON request body. Same contract as the other
121
+ * dialects: reject-first validation, ONE atomic transaction, structural
122
+ * identifiers preserved. function_call.arguments is a JSON-encoded string and
123
+ * is parsed before masking and re-encoded after (same rule as chat
124
+ * completions tool arguments).
125
+ */
126
+ export declare function remaskResponsesRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
127
+ /** Hook-first admission: check the supported response route and transport
128
+ * metadata without reading, validating, or changing the final request body.
129
+ * Returning the same Request preserves identity for response attribution. */
130
+ export declare function admitModelRequest(service: TransportMaskingService, sessionID: string, request: Request, allowHookOnly?: boolean): Request;
131
+ /** Protocol dispatcher: masks any supported wire route by URL shape. */
132
+ export declare function remaskModelRequest(service: TransportMaskingService, sessionID: string, request: Request): Promise<Request>;
133
+ /**
134
+ * Restores assistant display text in a model response. Error bodies and
135
+ * unsupported content types are passed through only when a bounded clone-read
136
+ * proves they carry no reserved token this module cannot restore; otherwise
137
+ * the response fails closed.
138
+ */
139
+ export declare function restoreChatCompletionsResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
140
+ export declare function restoreDisplayText(service: TransportMaskingService, sessionID: string, text: string): string;
141
+ /**
142
+ * Splits `buffered` into the portion safe to restore now and any incomplete
143
+ * token candidate that must be held back until more stream data arrives. A
144
+ * held tail is either a partial token from its LAST full prefix (either
145
+ * version), or the longest suffix that is a proper prefix of a reserved
146
+ * namespace prefix (e.g. `[SG`, `[SGP2`): emitting that suffix literally
147
+ * would make the token unrestorable. Complete tokens in the emit portion are
148
+ * restored by the caller through the core; a tail that never completes
149
+ * degrades to a literal emit with a WARN at the terminal boundary
150
+ * (P1, 2026-10-06b).
151
+ */
152
+ export declare function splitRestorable(buffered: string): {
153
+ emit: string;
154
+ hold: string;
155
+ };
156
+ /**
157
+ * Incremental SSE restore. UTF-8 is decoded streaming (code points may split
158
+ * across chunks), complete events are assembled from their `data:` lines as
159
+ * they terminate (a blank line), and each choice's `delta.content` channel
160
+ * keeps a token-prefix hold buffer so tokens split across chunks AND events
161
+ * are restored exactly once, in order.
162
+ *
163
+ * Bounds are explicit, measured in UTF-8 bytes and fail closed: the pending
164
+ * line buffer, the accumulated (unterminated) event, each choice channel, the
165
+ * aggregate channel state and the channel count are all capped, each charged
166
+ * before the value is accumulated. A choice whose token is still unresolved
167
+ * at a terminal `finish_reason` degrades — the held tail is emitted literally
168
+ * with a WARN — and a choice that keeps producing output after it is terminal
169
+ * refuses. Reading is pull-based: one
170
+ * bounded batch of upstream data is consumed per downstream pull, so an unread
171
+ * consumer never builds an unbounded downstream queue. Errors from the
172
+ * underlying stream propagate and downstream cancellation cancels its reader.
173
+ * SG parse/restore failures instead replay undelivered originals and bypass
174
+ * further rewriting; they never cancel a healthy upstream response.
175
+ */
176
+ export declare function createSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
177
+ /**
178
+ * Restores an Anthropic Messages SSE stream. Channel hold buffers are keyed by
179
+ * content-block index (tokens may split across content_block_delta events);
180
+ * content_block_stop requires an empty channel and marks the index terminal;
181
+ * message_stop requires every channel drained. input_json_delta is
182
+ * deliberately untouched (tool arguments restore at the typed tool gate). All
183
+ * framing/byte caps mirror the chat-completions stream.
184
+ */
185
+ export declare function createAnthropicSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
186
+ /**
187
+ * Restores assistant display text in an Anthropic Messages response. Error
188
+ * bodies and unsupported content types pass through only when provably free
189
+ * of reserved tokens; otherwise the response fails closed.
190
+ */
191
+ export declare function restoreAnthropicMessagesResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
192
+ /** Protocol dispatcher: restores a response using the SAME wire route the
193
+ * masked request used (classified by request URL shape). */
194
+ export declare function restoreModelResponse(service: TransportMaskingService, sessionID: string, request: Request, response: Response): Promise<Response>;
195
+ export declare const RESPONSES_TEXT_DELTA_TYPES: ReadonlySet<string>;
196
+ export declare const RESPONSES_TEXT_DONE_TYPES: ReadonlySet<string>;
197
+ /** Restore complete display fields of one Responses event (HTTP/WS share
198
+ * the same part/item semantics). Delta buffering belongs to the transport;
199
+ * function-call arguments and provider state are never restored here. */
200
+ export declare function restoreResponsesEventDisplay(service: TransportMaskingService, sessionID: string, chunk: Record<string, unknown>): void;
201
+ /**
202
+ * Restores an OpenAI Responses SSE stream. Channels are keyed by item id (or
203
+ * output index) for response.output_text.delta events; function_call_arguments
204
+ * deltas are untouched (tool gate); the terminal response.completed/failed/
205
+ * incomplete event requires drained channels, and no event may follow it.
206
+ */
207
+ export declare function createResponsesSseRestoreStream(service: TransportMaskingService, sessionID: string, body: ReadableStream<Uint8Array>): ReadableStream<Uint8Array>;
208
+ /**
209
+ * Restores assistant display text in an OpenAI Responses response; error
210
+ * bodies and unsupported content types pass through only when provably free
211
+ * of reserved tokens.
212
+ */
213
+ export declare function restoreResponsesResponse(service: TransportMaskingService, sessionID: string, response: Response): Promise<Response>;
@@ -37,9 +37,9 @@
37
37
  * then bypass rewriting; source errors and cancellation remain failures.
38
38
  * Non-stream restoration failures are recovered by the session hook.
39
39
  */
40
- import { containsTokenPrefix, PSEUDONYM_TOKEN_PREFIXES, } from "./decision/pseudonymization.js";
41
- import { walkSchemaStrings } from "./decision/schema-strings.js";
42
- import { createRecoveringSseStream } from "./opencode-transparent-stream.js";
40
+ import { containsTokenPrefix, PSEUDONYM_TOKEN_PREFIXES, } from "../decision/pseudonymization.js";
41
+ import { walkSchemaStrings } from "../decision/schema-strings.js";
42
+ import { createRecoveringSseStream } from "./sse-recovery.js";
43
43
  // ─── Static failure messages (no content ever included) ─────────────────────
44
44
  /**
45
45
  * Content-free degradation notice for the host log (P1, 2026-10-06b): one
@@ -419,7 +419,9 @@ function withOpaqueReasoningContent(body, fn) {
419
419
  return fn(body);
420
420
  const originals = [];
421
421
  for (const item of input) {
422
- if (isRecord(item) && item.type === "reasoning" && typeof item.encrypted_content === "string") {
422
+ if (isRecord(item) &&
423
+ (item.type === "reasoning" || item.type === "compaction") &&
424
+ typeof item.encrypted_content === "string") {
423
425
  originals.push(item.encrypted_content);
424
426
  item.encrypted_content = `${OPAQUE_REASONING_SENTINEL}_${originals.length - 1}`;
425
427
  }
@@ -603,6 +605,21 @@ function collectWireStructuralStrings(body) {
603
605
  walkSchemaStrings(out, body.response_format);
604
606
  return out;
605
607
  }
608
+ /** Forwards exactly the value that was scanned. The original bytes are kept
609
+ * only when they already are that serialization: a body that parses to
610
+ * something else (a duplicate key keeps only its last occurrence, invalid
611
+ * UTF-8 decodes to U+FFFD) would otherwise carry content the scanner never
612
+ * saw. Keeping the original Request otherwise preserves its identity. */
613
+ function forwardSerialized(request, raw, serialized) {
614
+ if (serialized === raw && !raw.includes("\uFFFD"))
615
+ return request;
616
+ const headers = new Headers(request.headers);
617
+ headers.delete("content-encoding");
618
+ // Let fetch frame the replacement body. An explicit length can also be
619
+ // rejected when Node's fetch uses a newer host-installed dispatcher.
620
+ headers.delete("content-length");
621
+ return new Request(request, { body: serialized, headers });
622
+ }
606
623
  /**
607
624
  * Remasks an OpenAI-compatible Chat Completions JSON request body.
608
625
  *
@@ -610,8 +627,8 @@ function collectWireStructuralStrings(body) {
610
627
  * message shapes, structural identifiers, numeric values); only then is the
611
628
  * whole body protected in a SINGLE transaction, so a rejected request commits
612
629
  * no mapping or session capacity. The original request is consumed only through
613
- * `clone()` and, when nothing changed, the ORIGINAL request object is returned
614
- * untouched. A rebuilt request inherits every transport control (method, url,
630
+ * `clone()`; the ORIGINAL request object is returned only when its body already
631
+ * is the canonical serialization of what was scanned. A rebuilt request inherits every transport control (method, url,
615
632
  * mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
616
633
  * authentication headers) and recomputes body headers.
617
634
  */
@@ -645,9 +662,6 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
645
662
  throw new Error(refusal("body-shape"));
646
663
  validateDialect(body);
647
664
  validateMessages(body, attachmentsAllowed(service));
648
- // Capture the original wire shape BEFORE transforming tool arguments, so a
649
- // no-op protection still returns the ORIGINAL request untouched.
650
- const originalSerialized = JSON.stringify(body);
651
665
  // Tool arguments are JSON-encoded strings. Protecting them as PARSED values
652
666
  // (a) keeps masking from invalidating the JSON — a numeric pin matched by the
653
667
  // phone detector would otherwise be masked mid-token, producing invalid JSON
@@ -741,19 +755,15 @@ export async function remaskChatCompletionsRequest(service, sessionID, request)
741
755
  }
742
756
  }
743
757
  const serialized = JSON.stringify(next);
744
- if (serialized === originalSerialized)
745
- return request;
746
- const headers = new Headers(request.headers);
747
- headers.delete("content-encoding");
748
- headers.set("content-length", String(byteLength(serialized)));
749
- return new Request(request, { body: serialized, headers });
758
+ return forwardSerialized(request, raw, serialized);
750
759
  }
751
760
  // ─── Anthropic Messages request (wire dialect) ──────────────────────────────
752
761
  /**
753
762
  * Validates an Anthropic Messages request body: top-level `system` (string or
754
763
  * text blocks), `messages` with content blocks (text | tool_use |
755
- * tool_result), flat `tools` ({name, description?, input_schema}). Images,
756
- * documents, thinking blocks, and any unknown block type refuse — never pass
764
+ * tool_result, whose parts are text or a bare tool_reference), flat `tools` ({name, description?, input_schema}). Images,
765
+ * documents, thinking blocks (unless the service sets anthropicThinking
766
+ * "mask"), and any unknown block type refuse — never pass
757
767
  * tokenized or unscanned content through the wire boundary.
758
768
  */
759
769
  function validateAnthropicSystem(system) {
@@ -767,7 +777,17 @@ function validateAnthropicSystem(system) {
767
777
  }
768
778
  }
769
779
  }
770
- function validateAnthropicContent(content, allowAttachments) {
780
+ /**
781
+ * A `tool_reference` part (Claude Code's ToolSearch result) names a tool and
782
+ * nothing else. Only that exact shape is accepted; its `tool_name` is a
783
+ * structural identifier, so a finding there refuses instead of being renamed.
784
+ */
785
+ function isToolReferencePart(part) {
786
+ if (!isRecord(part) || part.type !== "tool_reference" || typeof part.tool_name !== "string")
787
+ return false;
788
+ return Object.keys(part).every((key) => key === "type" || key === "tool_name");
789
+ }
790
+ function validateAnthropicContent(content, allowAttachments, allowThinking = false) {
771
791
  if (content === undefined || content === null || typeof content === "string")
772
792
  return;
773
793
  if (!Array.isArray(content))
@@ -777,6 +797,17 @@ function validateAnthropicContent(content, allowAttachments) {
777
797
  throw new Error(refusal("anthropic-content-block"));
778
798
  if (allowAttachments && isAttachmentRecord(block))
779
799
  continue;
800
+ if (allowThinking && block.type === "thinking") {
801
+ if (typeof block.thinking !== "string" || (block.signature !== undefined && typeof block.signature !== "string")) {
802
+ throw new Error(refusal("anthropic-thinking-block"));
803
+ }
804
+ continue;
805
+ }
806
+ if (allowThinking && block.type === "redacted_thinking") {
807
+ if (typeof block.data !== "string")
808
+ throw new Error(refusal("anthropic-thinking-block"));
809
+ continue;
810
+ }
780
811
  switch (block.type) {
781
812
  case "text":
782
813
  if (typeof block.text !== "string")
@@ -803,6 +834,8 @@ function validateAnthropicContent(content, allowAttachments) {
803
834
  if (allowAttachments && isAttachmentRecord(part)) {
804
835
  continue;
805
836
  }
837
+ if (isToolReferencePart(part))
838
+ continue;
806
839
  if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
807
840
  throw new Error(refusal("anthropic-tool-result-part"));
808
841
  }
@@ -814,7 +847,7 @@ function validateAnthropicContent(content, allowAttachments) {
814
847
  }
815
848
  }
816
849
  }
817
- function validateAnthropicDialect(body, allowAttachments) {
850
+ function validateAnthropicDialect(body, allowAttachments, allowThinking = false) {
818
851
  validateAnthropicSystem(body.system);
819
852
  if (body.tools !== undefined) {
820
853
  if (!Array.isArray(body.tools))
@@ -833,8 +866,55 @@ function validateAnthropicDialect(body, allowAttachments) {
833
866
  if (!isRecord(message) || typeof message.role !== "string") {
834
867
  throw new Error(refusal("anthropic-message-shape"));
835
868
  }
836
- validateAnthropicContent(message.content, allowAttachments);
869
+ validateAnthropicContent(message.content, allowAttachments, allowThinking);
870
+ }
871
+ }
872
+ const OPAQUE_THINKING_SENTINEL = "__sg_opaque_thinking";
873
+ /**
874
+ * Stashes thinking `signature` and `redacted_thinking.data` strings around the
875
+ * masking transaction. Both are provider-verified blobs over earlier masked
876
+ * traffic: a false-positive detector hit inside the base64 would corrupt them
877
+ * and the provider would reject the whole history. Same sentinel contract as
878
+ * withOpaqueReasoningContent: substitute, protect, restore, verify counts.
879
+ */
880
+ function withOpaqueThinkingState(body, fn) {
881
+ const opaqueField = (block) => {
882
+ if (block.type === "thinking" && typeof block.signature === "string")
883
+ return "signature";
884
+ if (block.type === "redacted_thinking" && typeof block.data === "string")
885
+ return "data";
886
+ return null;
887
+ };
888
+ const blocksOf = (value) => {
889
+ if (!Array.isArray(value.messages))
890
+ return [];
891
+ return value.messages.flatMap((message) => isRecord(message) && Array.isArray(message.content) ? message.content.filter(isRecord) : []);
892
+ };
893
+ const originals = [];
894
+ for (const block of blocksOf(body)) {
895
+ const field = opaqueField(block);
896
+ if (field === null)
897
+ continue;
898
+ originals.push(block[field]);
899
+ block[field] = `${OPAQUE_THINKING_SENTINEL}_${originals.length - 1}`;
900
+ }
901
+ if (originals.length === 0)
902
+ return fn(body);
903
+ const result = fn(body);
904
+ const sentinelRe = new RegExp(`^${OPAQUE_THINKING_SENTINEL}_(\\d+)$`);
905
+ let restored = 0;
906
+ for (const block of blocksOf(result)) {
907
+ const field = opaqueField(block);
908
+ if (field === null)
909
+ continue;
910
+ const match = sentinelRe.exec(block[field]);
911
+ if (match === null || Number(match[1]) !== restored)
912
+ throw new Error(MASK_FAILURE);
913
+ block[field] = originals[restored++];
837
914
  }
915
+ if (restored !== originals.length)
916
+ throw new Error(MASK_FAILURE);
917
+ return result;
838
918
  }
839
919
  /** Structural identifiers that must survive masking verbatim (Anthropic shape). */
840
920
  function collectAnthropicStructuralStrings(body) {
@@ -854,8 +934,15 @@ function collectAnthropicStructuralStrings(body) {
854
934
  pushString(out, block.id);
855
935
  pushString(out, block.name);
856
936
  }
857
- if (block.type === "tool_result")
937
+ if (block.type === "tool_result") {
858
938
  pushString(out, block.tool_use_id);
939
+ if (Array.isArray(block.content)) {
940
+ for (const part of block.content) {
941
+ if (isToolReferencePart(part))
942
+ pushString(out, part.tool_name);
943
+ }
944
+ }
945
+ }
859
946
  }
860
947
  }
861
948
  }
@@ -906,8 +993,8 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
906
993
  }
907
994
  if (!isRecord(body))
908
995
  throw new Error(refusal("body-shape"));
909
- validateAnthropicDialect(body, attachmentsAllowed(service));
910
- const originalSerialized = JSON.stringify(body);
996
+ const allowThinking = service.anthropicThinking === "mask";
997
+ validateAnthropicDialect(body, attachmentsAllowed(service), allowThinking);
911
998
  const structuralBefore = collectAnthropicStructuralStrings(body);
912
999
  for (const identifier of structuralBefore) {
913
1000
  if (containsTokenPrefix(identifier) || service.detectSensitive(identifier)) {
@@ -921,7 +1008,7 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
921
1008
  });
922
1009
  if (unsafeNumber)
923
1010
  throw new Error(refusal("number-sensitive"));
924
- const next = withOpaqueAttachments(service.attachmentsPolicy ?? "block", body, (input) => {
1011
+ const protect = (input) => {
925
1012
  const masked = service.protectJsonForModel(sessionID, input);
926
1013
  if (!masked.ok)
927
1014
  throw new Error(MASK_FAILURE);
@@ -929,28 +1016,25 @@ export async function remaskAnthropicMessagesRequest(service, sessionID, request
929
1016
  if (!isRecord(value))
930
1017
  throw new Error(MASK_FAILURE);
931
1018
  return value;
932
- });
1019
+ };
1020
+ const next = withOpaqueAttachments(service.attachmentsPolicy ?? "block", body, (input) => allowThinking ? withOpaqueThinkingState(input, protect) : protect(input));
933
1021
  const structuralAfter = collectAnthropicStructuralStrings(next);
934
1022
  if (structuralAfter.length !== structuralBefore.length ||
935
1023
  structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
936
1024
  throw new Error(refusal("structural-drift"));
937
1025
  }
938
1026
  const serialized = JSON.stringify(next);
939
- if (serialized === originalSerialized)
940
- return request;
941
- const headers = new Headers(request.headers);
942
- headers.delete("content-encoding");
943
- headers.set("content-length", String(byteLength(serialized)));
944
- return new Request(request, { body: serialized, headers });
1027
+ return forwardSerialized(request, raw, serialized);
945
1028
  }
946
1029
  // ─── OpenAI Responses request (wire dialect) ────────────────────────────────
947
1030
  /**
948
1031
  * Validates an OpenAI Responses request body: `instructions` string, `input`
949
1032
  * (string or item array: message | function_call | function_call_output |
950
- * reasoning), flat `tools` ({type:"function", name, parameters}). Reasoning
951
- * items pass with their encrypted payload opaque (unscanned, verbatim) and
952
- * their summary/content text masked; item references and unknown types
953
- * refuse.
1033
+ * custom_tool_call | custom_tool_call_output | reasoning | compaction |
1034
+ * configuration_update), flat `tools` ({type:"function", name, parameters}).
1035
+ * Reasoning and compaction items pass with their encrypted payload opaque
1036
+ * (unscanned, verbatim); reasoning summary/content text is masked; item
1037
+ * references and unknown types refuse.
954
1038
  */
955
1039
  function validateResponsesContentParts(content, allowAttachments) {
956
1040
  if (content === undefined || content === null || typeof content === "string")
@@ -1010,7 +1094,13 @@ function validateResponsesInputItem(item, allowAttachments) {
1010
1094
  throw new Error(refusal("responses-function-call-shape"));
1011
1095
  }
1012
1096
  return;
1097
+ case "custom_tool_call":
1098
+ if (typeof item.name !== "string" || typeof item.input !== "string") {
1099
+ throw new Error(refusal("responses-custom-tool-call-shape"));
1100
+ }
1101
+ return;
1013
1102
  case "function_call_output":
1103
+ case "custom_tool_call_output":
1014
1104
  if (typeof item.output !== "string") {
1015
1105
  if (!Array.isArray(item.output))
1016
1106
  throw new Error(refusal("responses-function-output"));
@@ -1032,6 +1122,19 @@ function validateResponsesInputItem(item, allowAttachments) {
1032
1122
  validateResponsesReasoningParts(item.content);
1033
1123
  return;
1034
1124
  }
1125
+ case "compaction":
1126
+ // Same opacity argument as reasoning.encrypted_content: a provider
1127
+ // checkpoint of already-masked history, replayed to the same provider.
1128
+ if (typeof item.encrypted_content !== "string" ||
1129
+ (item.id !== undefined && item.id !== null && typeof item.id !== "string")) {
1130
+ throw new Error(refusal("responses-compaction-shape"));
1131
+ }
1132
+ return;
1133
+ case "configuration_update":
1134
+ if (!isRecord(item.reasoning) || typeof item.reasoning.effort !== "string") {
1135
+ throw new Error(refusal("responses-configuration-update-shape"));
1136
+ }
1137
+ return;
1035
1138
  default:
1036
1139
  // item_reference / unknown: cannot verify or place.
1037
1140
  throw new Error(refusal("responses-item-type"));
@@ -1077,10 +1180,14 @@ function collectResponsesStructuralStrings(body) {
1077
1180
  pushString(out, item.type);
1078
1181
  pushString(out, item.role);
1079
1182
  pushString(out, item.call_id);
1080
- if (item.type === "function_call")
1183
+ if (item.type === "function_call" || item.type === "custom_tool_call")
1081
1184
  pushString(out, item.name);
1082
- if (item.type === "reasoning")
1185
+ if (item.type === "function_call")
1186
+ pushString(out, item.namespace);
1187
+ if (item.type === "reasoning" || item.type === "compaction")
1083
1188
  pushString(out, item.id);
1189
+ if (item.type === "configuration_update" && isRecord(item.reasoning))
1190
+ pushString(out, item.reasoning.effort);
1084
1191
  }
1085
1192
  }
1086
1193
  if (Array.isArray(body.tools)) {
@@ -1125,7 +1232,6 @@ export async function remaskResponsesRequest(service, sessionID, request) {
1125
1232
  if (!isRecord(body))
1126
1233
  throw new Error(refusal("body-shape"));
1127
1234
  validateResponsesDialect(body, attachmentsAllowed(service));
1128
- const originalSerialized = JSON.stringify(body);
1129
1235
  // function_call.arguments strings are parsed so masking cannot invalidate
1130
1236
  // the JSON; re-encoded after the atomic protect (chat-completions rule).
1131
1237
  const transformedArguments = [];
@@ -1179,12 +1285,7 @@ export async function remaskResponsesRequest(service, sessionID, request) {
1179
1285
  }
1180
1286
  }
1181
1287
  const serialized = JSON.stringify(next);
1182
- if (serialized === originalSerialized)
1183
- return request;
1184
- const headers = new Headers(request.headers);
1185
- headers.delete("content-encoding");
1186
- headers.set("content-length", String(byteLength(serialized)));
1187
- return new Request(request, { body: serialized, headers });
1288
+ return forwardSerialized(request, raw, serialized);
1188
1289
  }
1189
1290
  function isRecordArgumentsString(item) {
1190
1291
  return typeof item.arguments === "string";
@@ -1589,14 +1690,14 @@ function allowAnthropicField(fields, record, field) {
1589
1690
  allowed.add(field);
1590
1691
  fields.set(record, allowed);
1591
1692
  }
1592
- function anthropicStrayTokenIn(value, fields) {
1693
+ function anthropicStrayTokenIn(value, fields, tokenizedThinking = false) {
1593
1694
  if (typeof value === "string") {
1594
1695
  return containsTokenPrefix(value);
1595
1696
  }
1596
1697
  if (value === null || typeof value !== "object")
1597
1698
  return false;
1598
1699
  if (Array.isArray(value)) {
1599
- return value.some((item) => anthropicStrayTokenIn(item, fields));
1700
+ return value.some((item) => anthropicStrayTokenIn(item, fields, tokenizedThinking));
1600
1701
  }
1601
1702
  const record = value;
1602
1703
  for (const key of Object.keys(record)) {
@@ -1614,14 +1715,22 @@ function anthropicStrayTokenIn(value, fields) {
1614
1715
  return true;
1615
1716
  continue; // input stays tokenized by design
1616
1717
  }
1617
- if (anthropicStrayTokenIn(block, fields))
1718
+ if (tokenizedThinking && block.type === "thinking") {
1719
+ // Thinking text is signed: restoring it would break the signature
1720
+ // when Claude Code resends it, so its placeholders stay as sent.
1721
+ const { thinking: _signed, ...rest } = block;
1722
+ if (anthropicStrayTokenIn(rest, fields, tokenizedThinking))
1723
+ return true;
1724
+ continue;
1725
+ }
1726
+ if (anthropicStrayTokenIn(block, fields, tokenizedThinking))
1618
1727
  return true;
1619
1728
  }
1620
1729
  continue;
1621
1730
  }
1622
1731
  if (fields?.get(record)?.has(key))
1623
1732
  continue;
1624
- if (anthropicStrayTokenIn(value, fields))
1733
+ if (anthropicStrayTokenIn(value, fields, tokenizedThinking))
1625
1734
  return true;
1626
1735
  }
1627
1736
  return false;
@@ -1667,7 +1776,7 @@ async function restoreAnthropicJsonResponse(service, sessionID, response) {
1667
1776
  }
1668
1777
  // tool_use / other blocks: input stays tokenized until the typed tool gate.
1669
1778
  }
1670
- if (anthropicStrayTokenIn(body, fields))
1779
+ if (anthropicStrayTokenIn(body, fields, service.anthropicThinking === "mask"))
1671
1780
  throw new Error(UNSUPPORTED_RESPONSE);
1672
1781
  if (!changed)
1673
1782
  return response;
@@ -1962,7 +2071,10 @@ function restoreResponsesItemText(service, sessionID, item, fields) {
1962
2071
  if (item.type === "function_call" && typeof item.arguments === "string") {
1963
2072
  allowResponsesField(fields, item, "arguments");
1964
2073
  }
1965
- if (item.type === "function_call_output" && typeof item.output === "string") {
2074
+ if (item.type === "custom_tool_call" && typeof item.input === "string") {
2075
+ allowResponsesField(fields, item, "input");
2076
+ }
2077
+ if ((item.type === "function_call_output" || item.type === "custom_tool_call_output") && typeof item.output === "string") {
1966
2078
  allowResponsesField(fields, item, "output");
1967
2079
  }
1968
2080
  let changed = false;
@@ -2017,6 +2129,9 @@ export function restoreResponsesEventDisplay(service, sessionID, chunk) {
2017
2129
  else if (type === "response.function_call_arguments.delta" || type === "response.function_call_arguments.done") {
2018
2130
  allowResponsesField(fields, chunk, type.endsWith(".delta") ? "delta" : "arguments");
2019
2131
  }
2132
+ else if (type === "response.custom_tool_call_input.delta" || type === "response.custom_tool_call_input.done") {
2133
+ allowResponsesField(fields, chunk, type.endsWith(".delta") ? "delta" : "input");
2134
+ }
2020
2135
  else if (type === "response.output_item.added" || type === "response.output_item.done") {
2021
2136
  if (isRecord(chunk.item))
2022
2137
  restoreResponsesItemText(service, sessionID, chunk.item, fields);
@@ -2273,6 +2388,11 @@ export function createResponsesSseRestoreStream(service, sessionID, body) {
2273
2388
  if (typeof chunk[field] === "string")
2274
2389
  allowResponsesField(fields, chunk, field);
2275
2390
  }
2391
+ else if (eventType === "response.custom_tool_call_input.delta" || eventType === "response.custom_tool_call_input.done") {
2392
+ const field = eventType.endsWith(".delta") ? "delta" : "input";
2393
+ if (typeof chunk[field] === "string")
2394
+ allowResponsesField(fields, chunk, field);
2395
+ }
2276
2396
  // P1 (2026-10-06b): an unplaceable placeholder is degradation — WARN
2277
2397
  // and emit literally; mapping loss never refuses response delivery.
2278
2398
  if (responsesStrayTokenIn(chunk, fields)) {