leakshield 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +546 -2
- package/README.zh-TW.md +565 -0
- package/dist/cli.js +61 -0
- package/dist/config/loader.js +94 -0
- package/dist/decision/deidentify.js +195 -0
- package/dist/decision/ingress.js +136 -0
- package/dist/decision/mapping-key.js +318 -0
- package/dist/decision/mapping-store.js +555 -0
- package/dist/decision/model.js +76 -0
- package/dist/decision/pseudonymization.js +1230 -0
- package/dist/decision/redaction.js +185 -0
- package/dist/decision/schema-strings.js +42 -0
- package/dist/doctor.js +438 -0
- package/dist/env-queries.js +584 -0
- package/dist/forget.js +56 -0
- package/dist/help.js +37 -0
- package/dist/i18n/en.js +71 -0
- package/dist/i18n/index.js +28 -0
- package/dist/i18n/zh-TW.js +71 -0
- package/dist/index.js +12 -0
- package/dist/opencode-env-tools.js +243 -0
- package/dist/opencode-hooks.js +84 -0
- package/dist/opencode-transparent-aisdk.js +100 -0
- package/dist/opencode-transparent-http.js +2315 -0
- package/dist/opencode-transparent-stream.js +192 -0
- package/dist/opencode-transparent-ws.js +298 -0
- package/dist/opencode-transparent.js +1492 -0
- package/dist/opencode-v2.js +216 -0
- package/dist/opencode.js +175 -0
- package/dist/plugin-options.js +100 -0
- package/dist/rules/builtin.js +283 -0
- package/dist/rules/dynamic.js +68 -0
- package/dist/scanner/encoding.js +274 -0
- package/dist/scanner/engine.js +321 -0
- package/dist/scanner/exact-values.js +99 -0
- package/dist/scanner/redaction-verifier.js +82 -0
- package/dist/scanner/unicode.js +157 -0
- package/dist/scanner/utils.js +60 -0
- package/dist/transports/cli.js +447 -0
- package/dist/transports/web-ui.js +540 -0
- package/dist/transports/web.js +200 -0
- package/dist/types.js +23 -0
- package/dist/utils/files.js +36 -0
- package/dist/utils/path-security.js +30 -0
- package/dist/utils/win-encoding.js +45 -0
- package/package.json +71 -4
|
@@ -0,0 +1,2315 @@
|
|
|
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 { containsTokenPrefix, PSEUDONYM_TOKEN_PREFIXES, } from "./decision/pseudonymization.js";
|
|
41
|
+
import { walkSchemaStrings } from "./decision/schema-strings.js";
|
|
42
|
+
import { createRecoveringSseStream } from "./opencode-transparent-stream.js";
|
|
43
|
+
// ─── Static failure messages (no content ever included) ─────────────────────
|
|
44
|
+
/**
|
|
45
|
+
* Content-free degradation notice for the host log (P1, 2026-10-06b): one
|
|
46
|
+
* WARN line with a fixed context word, never response/request content.
|
|
47
|
+
*/
|
|
48
|
+
const warnDegradation = (context) => {
|
|
49
|
+
console.warn(`[leakshield] degraded: ${context}`);
|
|
50
|
+
};
|
|
51
|
+
const UNSUPPORTED_REQUEST_BODY = "LeakShield transparent mode blocked a model request with an unsupported or unidentifiable body.";
|
|
52
|
+
const UNSUPPORTED_TRANSPORT = "LeakShield transparent mode blocked a request on an unsupported model transport route.";
|
|
53
|
+
const MASK_FAILURE = "LeakShield transparent mode failed to mask a model request.";
|
|
54
|
+
const UNSUPPORTED_RESPONSE = "LeakShield transparent mode blocked a response it cannot restore safely.";
|
|
55
|
+
const RESTORE_FAILURE = "LeakShield transparent mode failed to restore a model response.";
|
|
56
|
+
const MALFORMED_STREAM = "LeakShield transparent mode blocked a malformed or incomplete streaming response.";
|
|
57
|
+
const STREAM_BUFFER_LIMIT = "LeakShield transparent mode blocked an oversized streaming buffer.";
|
|
58
|
+
/**
|
|
59
|
+
* Content-free refusal classification (2026-10-08): every request refusal
|
|
60
|
+
* appends a fixed code naming WHICH check failed — the refusal-policy spec
|
|
61
|
+
* requires refusals to name the cause. Codes are static labels, never
|
|
62
|
+
* request/response content, so the full message stays safe for host logs
|
|
63
|
+
* and user-facing errors. Existing substring assertions keep passing: the
|
|
64
|
+
* base sentence is unchanged and the code is appended in brackets.
|
|
65
|
+
*/
|
|
66
|
+
function refusal(code) {
|
|
67
|
+
return `${UNSUPPORTED_REQUEST_BODY} [${code}]`;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* All byte caps are UTF-8 bytes (not UTF-16 code units): the bound is a memory
|
|
71
|
+
* bound, and a code-unit cap would allow up to ~4× the stated bytes for
|
|
72
|
+
* multi-byte text. Each cap is charged BEFORE the value is accumulated.
|
|
73
|
+
*/
|
|
74
|
+
const MAX_BODY_BYTES = 4 * 1024 * 1024;
|
|
75
|
+
// SSE framing and original-event retention caps live in the shared recovery
|
|
76
|
+
// stream; protocol adapters only own their bounded text/channel state.
|
|
77
|
+
/** A single choice's held-back content channel. */
|
|
78
|
+
const MAX_CHANNEL_BYTES = 65_536;
|
|
79
|
+
/** The aggregate held-back content across all channels. */
|
|
80
|
+
const MAX_TOTAL_CHANNEL_BYTES = 1_048_576;
|
|
81
|
+
/** Bound on the number of concurrently-held choice channels. */
|
|
82
|
+
const MAX_CHANNELS = 256;
|
|
83
|
+
/** Headers that legitimately carry credentials; never scanned as content. */
|
|
84
|
+
const AUTH_HEADER_NAMES = new Set([
|
|
85
|
+
"authorization",
|
|
86
|
+
"proxy-authorization",
|
|
87
|
+
"cookie",
|
|
88
|
+
"set-cookie",
|
|
89
|
+
"x-api-key",
|
|
90
|
+
"api-key",
|
|
91
|
+
"x-auth-token",
|
|
92
|
+
"x-goog-api-key",
|
|
93
|
+
]);
|
|
94
|
+
// ─── Shared helpers ──────────────────────────────────────────────────────────
|
|
95
|
+
function isRecord(value) {
|
|
96
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
97
|
+
}
|
|
98
|
+
function byteLength(text) {
|
|
99
|
+
return new TextEncoder().encode(text).length;
|
|
100
|
+
}
|
|
101
|
+
/** The OpenAI-compatible chat-completions endpoint for this request, if any. */
|
|
102
|
+
function isChatCompletionsUrl(url) {
|
|
103
|
+
try {
|
|
104
|
+
return /\/chat\/completions\/?$/.test(new URL(url).pathname);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** The Anthropic Messages endpoint for this request, if any. */
|
|
111
|
+
function isAnthropicMessagesUrl(url) {
|
|
112
|
+
try {
|
|
113
|
+
return /\/messages\/?$/.test(new URL(url).pathname);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
/** The OpenAI Responses endpoint for this request, if any. */
|
|
120
|
+
function isResponsesUrl(url) {
|
|
121
|
+
try {
|
|
122
|
+
return /\/responses\/?$/.test(new URL(url).pathname);
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export function classifyModelRoute(url) {
|
|
129
|
+
try {
|
|
130
|
+
const pathname = new URL(url).pathname;
|
|
131
|
+
if (/\/chat\/completions\/?$/.test(pathname))
|
|
132
|
+
return "chat-completions";
|
|
133
|
+
if (/\/messages\/?$/.test(pathname))
|
|
134
|
+
return "anthropic-messages";
|
|
135
|
+
if (/\/responses\/?$/.test(pathname))
|
|
136
|
+
return "openai-responses";
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** Whether a URL carries a reserved token, raw or percent-encoded. */
|
|
144
|
+
function urlCarriesToken(url) {
|
|
145
|
+
if (containsTokenPrefix(url))
|
|
146
|
+
return true;
|
|
147
|
+
try {
|
|
148
|
+
return containsTokenPrefix(decodeURIComponent(url));
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return false; // malformed escapes: the raw check already covered them
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Reads a clone of `source` into a string, refusing (with `failure`) once the
|
|
156
|
+
* decoded content exceeds `limit` UTF-8 bytes or on any read error. The limit
|
|
157
|
+
* is charged before each decoded chunk is accumulated. The original
|
|
158
|
+
* request/response body is never consumed.
|
|
159
|
+
*/
|
|
160
|
+
async function readCappedText(source, limit, failure) {
|
|
161
|
+
const clone = source.clone();
|
|
162
|
+
if (clone.body === null)
|
|
163
|
+
return "";
|
|
164
|
+
const reader = clone.body.getReader();
|
|
165
|
+
const decoder = new TextDecoder();
|
|
166
|
+
let out = "";
|
|
167
|
+
let outBytes = 0;
|
|
168
|
+
for (;;) {
|
|
169
|
+
let step;
|
|
170
|
+
try {
|
|
171
|
+
step = await reader.read();
|
|
172
|
+
}
|
|
173
|
+
catch {
|
|
174
|
+
throw new Error(failure);
|
|
175
|
+
}
|
|
176
|
+
if (step.done)
|
|
177
|
+
break;
|
|
178
|
+
const decoded = decoder.decode(step.value, { stream: true });
|
|
179
|
+
outBytes += byteLength(decoded);
|
|
180
|
+
if (outBytes > limit) {
|
|
181
|
+
// Do not await cancellation here: cancelling a cloned body reader can
|
|
182
|
+
// block, and the static failure is the outcome either way.
|
|
183
|
+
void reader.cancel().catch(() => { });
|
|
184
|
+
throw new Error(failure);
|
|
185
|
+
}
|
|
186
|
+
out += decoded;
|
|
187
|
+
}
|
|
188
|
+
const tail = decoder.decode();
|
|
189
|
+
outBytes += byteLength(tail);
|
|
190
|
+
if (outBytes > limit)
|
|
191
|
+
throw new Error(failure);
|
|
192
|
+
return out + tail;
|
|
193
|
+
}
|
|
194
|
+
/** Visits every numeric value in a strict-JSON tree. */
|
|
195
|
+
function walkNumbers(value, visit) {
|
|
196
|
+
if (typeof value === "number") {
|
|
197
|
+
visit(value);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
if (value === null || typeof value !== "object")
|
|
201
|
+
return;
|
|
202
|
+
if (Array.isArray(value)) {
|
|
203
|
+
for (const item of value)
|
|
204
|
+
walkNumbers(item, visit);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
for (const item of Object.values(value))
|
|
208
|
+
walkNumbers(item, visit);
|
|
209
|
+
}
|
|
210
|
+
function isIntentionalToolArgumentsPath(path) {
|
|
211
|
+
if (path[path.length - 1] !== "arguments")
|
|
212
|
+
return false;
|
|
213
|
+
const modern = path.length === 7 &&
|
|
214
|
+
path[0] === "choices" &&
|
|
215
|
+
typeof path[1] === "number" &&
|
|
216
|
+
(path[2] === "message" || path[2] === "delta") &&
|
|
217
|
+
path[3] === "tool_calls" &&
|
|
218
|
+
typeof path[4] === "number" &&
|
|
219
|
+
path[5] === "function";
|
|
220
|
+
const legacy = path.length === 5 &&
|
|
221
|
+
path[0] === "choices" &&
|
|
222
|
+
typeof path[1] === "number" &&
|
|
223
|
+
(path[2] === "message" || path[2] === "delta") &&
|
|
224
|
+
path[3] === "function_call";
|
|
225
|
+
return modern || legacy;
|
|
226
|
+
}
|
|
227
|
+
function isAssistantDisplayPath(path) {
|
|
228
|
+
const messageContent = path.length === 4 &&
|
|
229
|
+
path[0] === "choices" &&
|
|
230
|
+
typeof path[1] === "number" &&
|
|
231
|
+
path[2] === "message" &&
|
|
232
|
+
path[3] === "content";
|
|
233
|
+
const messageTextPart = path.length === 6 &&
|
|
234
|
+
path[0] === "choices" &&
|
|
235
|
+
typeof path[1] === "number" &&
|
|
236
|
+
path[2] === "message" &&
|
|
237
|
+
path[3] === "content" &&
|
|
238
|
+
typeof path[4] === "number" &&
|
|
239
|
+
path[5] === "text";
|
|
240
|
+
const deltaContent = path.length === 4 &&
|
|
241
|
+
path[0] === "choices" &&
|
|
242
|
+
typeof path[1] === "number" &&
|
|
243
|
+
path[2] === "delta" &&
|
|
244
|
+
path[3] === "content";
|
|
245
|
+
return messageContent || messageTextPart || deltaContent;
|
|
246
|
+
}
|
|
247
|
+
function strayTokenIn(value, path = []) {
|
|
248
|
+
if (typeof value === "string") {
|
|
249
|
+
return (containsTokenPrefix(value) &&
|
|
250
|
+
!isIntentionalToolArgumentsPath(path) &&
|
|
251
|
+
!isAssistantDisplayPath(path));
|
|
252
|
+
}
|
|
253
|
+
if (value === null || typeof value !== "object")
|
|
254
|
+
return false;
|
|
255
|
+
if (Array.isArray(value)) {
|
|
256
|
+
return value.some((item, index) => strayTokenIn(item, [...path, index]));
|
|
257
|
+
}
|
|
258
|
+
const record = value;
|
|
259
|
+
for (const key of Object.keys(record)) {
|
|
260
|
+
if (containsTokenPrefix(key) || strayTokenIn(record[key], [...path, key]))
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
return false;
|
|
264
|
+
}
|
|
265
|
+
// ─── Transport metadata inspection ──────────────────────────────────────────
|
|
266
|
+
/**
|
|
267
|
+
* Inspects decoded transport metadata. P1 (2026-10-06b): a placeholder in a
|
|
268
|
+
* header or query parameter is no longer refused per se — it is judged
|
|
269
|
+
* session-aware (registered-marker interiors exempt, unregistered payloads
|
|
270
|
+
* scanned); clean markers are preserved verbatim with a content-free WARN.
|
|
271
|
+
* A sensitive hit still refuses: transport metadata cannot be masked or
|
|
272
|
+
* renamed without breaking the protocol. Legitimate authentication headers
|
|
273
|
+
* are excluded from content scanning.
|
|
274
|
+
*/
|
|
275
|
+
function inspectTransportMetadata(service, sessionID, request) {
|
|
276
|
+
const url = new URL(request.url);
|
|
277
|
+
for (const [name, value] of url.searchParams) {
|
|
278
|
+
if (containsTokenPrefix(name) || containsTokenPrefix(value)) {
|
|
279
|
+
if (!service.isStructuralIdentifierSafe(sessionID, name) ||
|
|
280
|
+
!service.isTransportIdentifierSafe(sessionID, value)) {
|
|
281
|
+
throw new Error(refusal("metadata-query-token"));
|
|
282
|
+
}
|
|
283
|
+
warnDegradation("transport metadata preserved with a literal placeholder");
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
if (service.detectSensitive(name) || service.transportDetectSensitive(value)) {
|
|
287
|
+
throw new Error(refusal("metadata-query-sensitive"));
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
for (const [name, value] of request.headers) {
|
|
291
|
+
if (containsTokenPrefix(value)) {
|
|
292
|
+
if (!service.isTransportIdentifierSafe(sessionID, value)) {
|
|
293
|
+
throw new Error(refusal("metadata-header-token"));
|
|
294
|
+
}
|
|
295
|
+
warnDegradation("transport metadata preserved with a literal placeholder");
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
if (AUTH_HEADER_NAMES.has(name.toLowerCase()))
|
|
299
|
+
continue;
|
|
300
|
+
if (service.detectSensitive(name) || service.transportDetectSensitive(value)) {
|
|
301
|
+
throw new Error(refusal("metadata-header-sensitive"));
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
// ─── Attachment pass-through (allow policy) ─────────────────────────────────
|
|
306
|
+
const OPAQUE_ATTACHMENT_SENTINEL = "__sg_opaque_attachment";
|
|
307
|
+
/**
|
|
308
|
+
* Internal + wire-serialized attachment part types. Beyond the host's own
|
|
309
|
+
* media/file records this includes what the provider serializers actually
|
|
310
|
+
* emit on the wire: image_url (Chat Completions), image (Anthropic
|
|
311
|
+
* Messages), input_image/input_file (Responses). Under the "allow" policy
|
|
312
|
+
* every one of these passes as an opaque, unscanned leaf in all dialects.
|
|
313
|
+
*/
|
|
314
|
+
const ATTACHMENT_PART_TYPES = new Set([
|
|
315
|
+
"media",
|
|
316
|
+
"file",
|
|
317
|
+
"image_url",
|
|
318
|
+
"image",
|
|
319
|
+
"input_image",
|
|
320
|
+
"input_file",
|
|
321
|
+
]);
|
|
322
|
+
function isAttachmentRecord(item) {
|
|
323
|
+
return isRecord(item) && typeof item.type === "string" && ATTACHMENT_PART_TYPES.has(item.type);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* In "allow" mode, temporarily substitutes every media/file record with a
|
|
327
|
+
* unique sentinel string around the masking transaction, then restores the
|
|
328
|
+
* originals into the protected result: binary payloads are neither scanned
|
|
329
|
+
* nor altered, and the structural checks outside this wrapper see identical
|
|
330
|
+
* attachment records before and after. Shared by the wire remaskers and the
|
|
331
|
+
* session-layer request guard so "allow means unscanned" holds at both
|
|
332
|
+
* boundaries.
|
|
333
|
+
*/
|
|
334
|
+
export function withOpaqueAttachments(policy, body, fn) {
|
|
335
|
+
if (policy !== "allow")
|
|
336
|
+
return fn(body);
|
|
337
|
+
const originals = [];
|
|
338
|
+
let counter = 0;
|
|
339
|
+
const substitute = (value) => {
|
|
340
|
+
if (value === null || typeof value !== "object")
|
|
341
|
+
return;
|
|
342
|
+
if (Array.isArray(value)) {
|
|
343
|
+
for (let index = 0; index < value.length; index++) {
|
|
344
|
+
const item = value[index];
|
|
345
|
+
if (isAttachmentRecord(item)) {
|
|
346
|
+
originals.push(item);
|
|
347
|
+
value[index] = `${OPAQUE_ATTACHMENT_SENTINEL}_${counter++}`;
|
|
348
|
+
}
|
|
349
|
+
else
|
|
350
|
+
substitute(item);
|
|
351
|
+
}
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const record = value;
|
|
355
|
+
for (const key of Object.keys(record)) {
|
|
356
|
+
const item = record[key];
|
|
357
|
+
if (isAttachmentRecord(item)) {
|
|
358
|
+
originals.push(item);
|
|
359
|
+
record[key] = `${OPAQUE_ATTACHMENT_SENTINEL}_${counter++}`;
|
|
360
|
+
}
|
|
361
|
+
else
|
|
362
|
+
substitute(item);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
substitute(body);
|
|
366
|
+
const result = fn(body);
|
|
367
|
+
const sentinelRe = new RegExp(`^${OPAQUE_ATTACHMENT_SENTINEL}_\\d+$`);
|
|
368
|
+
let restoreIndex = 0;
|
|
369
|
+
const restore = (value) => {
|
|
370
|
+
if (value === null || typeof value !== "object")
|
|
371
|
+
return;
|
|
372
|
+
if (Array.isArray(value)) {
|
|
373
|
+
for (let index = 0; index < value.length; index++) {
|
|
374
|
+
const item = value[index];
|
|
375
|
+
if (typeof item === "string" && sentinelRe.test(item)) {
|
|
376
|
+
if (restoreIndex >= originals.length)
|
|
377
|
+
throw new Error(MASK_FAILURE);
|
|
378
|
+
value[index] = originals[restoreIndex++];
|
|
379
|
+
}
|
|
380
|
+
else
|
|
381
|
+
restore(item);
|
|
382
|
+
}
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const record = value;
|
|
386
|
+
for (const key of Object.keys(record)) {
|
|
387
|
+
const item = record[key];
|
|
388
|
+
if (typeof item === "string" && sentinelRe.test(item)) {
|
|
389
|
+
if (restoreIndex >= originals.length)
|
|
390
|
+
throw new Error(MASK_FAILURE);
|
|
391
|
+
record[key] = originals[restoreIndex++];
|
|
392
|
+
}
|
|
393
|
+
else
|
|
394
|
+
restore(item);
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
restore(result);
|
|
398
|
+
if (restoreIndex !== originals.length)
|
|
399
|
+
throw new Error(MASK_FAILURE);
|
|
400
|
+
return result;
|
|
401
|
+
}
|
|
402
|
+
/** True when the policy tolerates media/file parts as opaque leaves. */
|
|
403
|
+
function attachmentsAllowed(service) {
|
|
404
|
+
return service.attachmentsPolicy === "allow";
|
|
405
|
+
}
|
|
406
|
+
const OPAQUE_REASONING_SENTINEL = "__sg_opaque_reasoning";
|
|
407
|
+
/**
|
|
408
|
+
* Stashes every reasoning item's `encrypted_content` string around the
|
|
409
|
+
* masking transaction: the payload is provider-opaque, so it is neither
|
|
410
|
+
* scanned nor masked — a false-positive detector hit (an `sk-` substring
|
|
411
|
+
* inside base64, say) would corrupt the blob and break the protocol — and
|
|
412
|
+
* it crosses the boundary verbatim while the same item's plaintext
|
|
413
|
+
* summary/content parts are masked normally. Same sentinel contract as
|
|
414
|
+
* withOpaqueAttachments: substitute, protect, restore, verify counts.
|
|
415
|
+
*/
|
|
416
|
+
function withOpaqueReasoningContent(body, fn) {
|
|
417
|
+
const input = body.input;
|
|
418
|
+
if (!Array.isArray(input))
|
|
419
|
+
return fn(body);
|
|
420
|
+
const originals = [];
|
|
421
|
+
for (const item of input) {
|
|
422
|
+
if (isRecord(item) && item.type === "reasoning" && typeof item.encrypted_content === "string") {
|
|
423
|
+
originals.push(item.encrypted_content);
|
|
424
|
+
item.encrypted_content = `${OPAQUE_REASONING_SENTINEL}_${originals.length - 1}`;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
if (originals.length === 0)
|
|
428
|
+
return fn(body);
|
|
429
|
+
const result = fn(body);
|
|
430
|
+
const sentinelRe = new RegExp(`^${OPAQUE_REASONING_SENTINEL}_\\d+$`);
|
|
431
|
+
const resultInput = result.input;
|
|
432
|
+
if (!Array.isArray(resultInput))
|
|
433
|
+
throw new Error(MASK_FAILURE);
|
|
434
|
+
let index = 0;
|
|
435
|
+
for (const item of resultInput) {
|
|
436
|
+
if (isRecord(item) &&
|
|
437
|
+
typeof item.encrypted_content === "string" &&
|
|
438
|
+
sentinelRe.test(item.encrypted_content)) {
|
|
439
|
+
if (index >= originals.length)
|
|
440
|
+
throw new Error(MASK_FAILURE);
|
|
441
|
+
item.encrypted_content = originals[index++];
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (index !== originals.length)
|
|
445
|
+
throw new Error(MASK_FAILURE);
|
|
446
|
+
return result;
|
|
447
|
+
}
|
|
448
|
+
// ─── Request validation (runs before any issuance) ──────────────────────────
|
|
449
|
+
function validateDialect(body) {
|
|
450
|
+
// An Anthropic-shaped /v1/messages body carries a top-level system prompt
|
|
451
|
+
// and input_schema tools this OpenAI-specific masker cannot place.
|
|
452
|
+
if (body.system !== undefined)
|
|
453
|
+
throw new Error(refusal("chatcompletions-system-field"));
|
|
454
|
+
if (body.tools !== undefined) {
|
|
455
|
+
if (!Array.isArray(body.tools))
|
|
456
|
+
throw new Error(refusal("chatcompletions-tools-shape"));
|
|
457
|
+
for (const tool of body.tools) {
|
|
458
|
+
if (!isRecord(tool) || !isRecord(tool.function) || typeof tool.function.name !== "string") {
|
|
459
|
+
throw new Error(refusal("chatcompletions-tool-shape"));
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
function validateMessages(body, allowAttachments) {
|
|
465
|
+
if (!Array.isArray(body.messages))
|
|
466
|
+
throw new Error(refusal("chatcompletions-messages-shape"));
|
|
467
|
+
for (const message of body.messages) {
|
|
468
|
+
if (!isRecord(message) || typeof message.role !== "string") {
|
|
469
|
+
throw new Error(refusal("chatcompletions-message-shape"));
|
|
470
|
+
}
|
|
471
|
+
const content = message.content;
|
|
472
|
+
if (content !== undefined && content !== null && typeof content !== "string") {
|
|
473
|
+
if (!Array.isArray(content))
|
|
474
|
+
throw new Error(refusal("chatcompletions-content-shape"));
|
|
475
|
+
for (const part of content) {
|
|
476
|
+
// Attachments and foreign part types must refuse, never pass tokenized
|
|
477
|
+
// or unscanned content through the wire boundary — unless the user
|
|
478
|
+
// explicitly chose the "allow" policy (visible, unscanned pass-through).
|
|
479
|
+
if (allowAttachments && isAttachmentRecord(part)) {
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
|
|
483
|
+
throw new Error(refusal("chatcompletions-content-part"));
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
const toolCalls = message.tool_calls;
|
|
488
|
+
if (toolCalls !== undefined && toolCalls !== null) {
|
|
489
|
+
if (!Array.isArray(toolCalls))
|
|
490
|
+
throw new Error(refusal("chatcompletions-tool-calls-shape"));
|
|
491
|
+
for (const call of toolCalls) {
|
|
492
|
+
if (!isRecord(call) ||
|
|
493
|
+
!isRecord(call.function) ||
|
|
494
|
+
typeof call.function.name !== "string" ||
|
|
495
|
+
typeof call.function.arguments !== "string") {
|
|
496
|
+
throw new Error(refusal("chatcompletions-tool-call-shape"));
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
JSON.parse(call.function.arguments);
|
|
500
|
+
}
|
|
501
|
+
catch {
|
|
502
|
+
throw new Error(refusal("chatcompletions-tool-call-arguments"));
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
const functionCall = message.function_call;
|
|
507
|
+
if (functionCall !== undefined && functionCall !== null) {
|
|
508
|
+
if (!isRecord(functionCall) || typeof functionCall.name !== "string" || typeof functionCall.arguments !== "string") {
|
|
509
|
+
throw new Error(refusal("chatcompletions-function-call-shape"));
|
|
510
|
+
}
|
|
511
|
+
try {
|
|
512
|
+
JSON.parse(functionCall.arguments);
|
|
513
|
+
}
|
|
514
|
+
catch {
|
|
515
|
+
throw new Error(refusal("chatcompletions-function-call-arguments"));
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
// ─── Structural identifiers ─────────────────────────────────────────────────
|
|
521
|
+
/** True for any string value positioned as a structural (never-renamed) id. */
|
|
522
|
+
function pushString(out, value) {
|
|
523
|
+
if (typeof value === "string")
|
|
524
|
+
out.push(value);
|
|
525
|
+
}
|
|
526
|
+
/** Keys and values of a schema/metadata subtree, in stable walk order. */
|
|
527
|
+
function walkStrings(out, value) {
|
|
528
|
+
if (typeof value === "string") {
|
|
529
|
+
out.push(value);
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
if (value === null || typeof value !== "object")
|
|
533
|
+
return;
|
|
534
|
+
if (Array.isArray(value)) {
|
|
535
|
+
for (const item of value)
|
|
536
|
+
walkStrings(out, item);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const record = value;
|
|
540
|
+
for (const key of Object.keys(record)) {
|
|
541
|
+
out.push(key);
|
|
542
|
+
walkStrings(out, record[key]);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Protocol/structural identifiers of a Chat Completions body: model id,
|
|
547
|
+
* message roles/ids, content part types, tool-call ids/names and the tool
|
|
548
|
+
* input schema identifiers (property names, types, required entries, enum
|
|
549
|
+
* values). These must survive masking verbatim; a sensitive or token-bearing
|
|
550
|
+
* one refuses the request rather than being silently renamed. Schema
|
|
551
|
+
* annotation prose (description/title values) is intentionally absent: it is
|
|
552
|
+
* masked as ordinary content instead of refusing.
|
|
553
|
+
*/
|
|
554
|
+
function collectWireStructuralStrings(body) {
|
|
555
|
+
const out = [];
|
|
556
|
+
pushString(out, body.model);
|
|
557
|
+
if (Array.isArray(body.messages)) {
|
|
558
|
+
for (const message of body.messages) {
|
|
559
|
+
if (!isRecord(message))
|
|
560
|
+
continue;
|
|
561
|
+
pushString(out, message.role);
|
|
562
|
+
pushString(out, message.id);
|
|
563
|
+
pushString(out, message.tool_call_id);
|
|
564
|
+
if (Array.isArray(message.content)) {
|
|
565
|
+
for (const part of message.content) {
|
|
566
|
+
if (isRecord(part))
|
|
567
|
+
pushString(out, part.type);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
if (Array.isArray(message.tool_calls)) {
|
|
571
|
+
for (const call of message.tool_calls) {
|
|
572
|
+
if (!isRecord(call))
|
|
573
|
+
continue;
|
|
574
|
+
pushString(out, call.id);
|
|
575
|
+
pushString(out, call.type);
|
|
576
|
+
if (isRecord(call.function))
|
|
577
|
+
pushString(out, call.function.name);
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
if (isRecord(message.function_call))
|
|
581
|
+
pushString(out, message.function_call.name);
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
for (const tools of [body.tools, body.functions]) {
|
|
585
|
+
if (!Array.isArray(tools))
|
|
586
|
+
continue;
|
|
587
|
+
for (const tool of tools) {
|
|
588
|
+
if (!isRecord(tool))
|
|
589
|
+
continue;
|
|
590
|
+
pushString(out, tool.type);
|
|
591
|
+
pushString(out, tool.name);
|
|
592
|
+
const fn = isRecord(tool.function) ? tool.function : tool;
|
|
593
|
+
pushString(out, fn.name);
|
|
594
|
+
// Annotation prose (description/title values) masks as content; only
|
|
595
|
+
// identifiers stay structural and can refuse the request.
|
|
596
|
+
if (fn.parameters !== undefined)
|
|
597
|
+
walkSchemaStrings(out, fn.parameters);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
if (body.tool_choice !== undefined)
|
|
601
|
+
walkStrings(out, body.tool_choice);
|
|
602
|
+
if (body.response_format !== undefined)
|
|
603
|
+
walkSchemaStrings(out, body.response_format);
|
|
604
|
+
return out;
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Remasks an OpenAI-compatible Chat Completions JSON request body.
|
|
608
|
+
*
|
|
609
|
+
* Every check that can reject runs FIRST (route, transport metadata, dialect,
|
|
610
|
+
* message shapes, structural identifiers, numeric values); only then is the
|
|
611
|
+
* whole body protected in a SINGLE transaction, so a rejected request commits
|
|
612
|
+
* 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,
|
|
615
|
+
* mode, credentials, cache, redirect, referrer, integrity, keepalive, signal,
|
|
616
|
+
* authentication headers) and recomputes body headers.
|
|
617
|
+
*/
|
|
618
|
+
export async function remaskChatCompletionsRequest(service, sessionID, request) {
|
|
619
|
+
if (!isChatCompletionsUrl(request.url))
|
|
620
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
621
|
+
if (urlCarriesToken(request.url)) {
|
|
622
|
+
// P1 (2026-10-06b): a placeholder in the URL is judged, not auto-refused;
|
|
623
|
+
// sensitive content in a URL cannot be masked without changing the target.
|
|
624
|
+
if (!service.isTransportIdentifierSafe(sessionID, request.url)) {
|
|
625
|
+
throw new Error(refusal("url-token"));
|
|
626
|
+
}
|
|
627
|
+
warnDegradation("request url preserved with a literal placeholder");
|
|
628
|
+
}
|
|
629
|
+
inspectTransportMetadata(service, sessionID, request);
|
|
630
|
+
// A body is required: transport metadata (query, headers) cannot be scanned
|
|
631
|
+
// for arbitrary content, so a bodyless request has no verifiable boundary.
|
|
632
|
+
if (request.body === null)
|
|
633
|
+
throw new Error(refusal("body-missing"));
|
|
634
|
+
const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
|
|
635
|
+
if (raw.length === 0)
|
|
636
|
+
throw new Error(refusal("body-empty"));
|
|
637
|
+
let body;
|
|
638
|
+
try {
|
|
639
|
+
body = JSON.parse(raw);
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
throw new Error(refusal("body-json"));
|
|
643
|
+
}
|
|
644
|
+
if (!isRecord(body))
|
|
645
|
+
throw new Error(refusal("body-shape"));
|
|
646
|
+
validateDialect(body);
|
|
647
|
+
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
|
+
// Tool arguments are JSON-encoded strings. Protecting them as PARSED values
|
|
652
|
+
// (a) keeps masking from invalidating the JSON — a numeric pin matched by the
|
|
653
|
+
// phone detector would otherwise be masked mid-token, producing invalid JSON
|
|
654
|
+
// and a post-commit rejection that still consumes capacity — and (b) lets
|
|
655
|
+
// structural/numeric policy see inside them, all BEFORE the one atomic
|
|
656
|
+
// commit. Every transformed argument is re-encoded afterwards; a parsed JSON
|
|
657
|
+
// *string* must also be re-encoded (it would otherwise be written as a bare
|
|
658
|
+
// string and become invalid JSON on the wire).
|
|
659
|
+
const transformedArguments = [];
|
|
660
|
+
const messages = body.messages;
|
|
661
|
+
for (let messageIndex = 0; messageIndex < messages.length; messageIndex++) {
|
|
662
|
+
const message = messages[messageIndex];
|
|
663
|
+
if (!isRecord(message))
|
|
664
|
+
continue;
|
|
665
|
+
if (Array.isArray(message.tool_calls)) {
|
|
666
|
+
for (let callIndex = 0; callIndex < message.tool_calls.length; callIndex++) {
|
|
667
|
+
const call = message.tool_calls[callIndex];
|
|
668
|
+
if (!isRecord(call) || !isRecord(call.function))
|
|
669
|
+
continue;
|
|
670
|
+
try {
|
|
671
|
+
call.function.arguments = JSON.parse(call.function.arguments);
|
|
672
|
+
}
|
|
673
|
+
catch {
|
|
674
|
+
throw new Error(refusal("chatcompletions-tool-call-arguments"));
|
|
675
|
+
}
|
|
676
|
+
transformedArguments.push({ message: messageIndex, call: callIndex });
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
if (isRecord(message.function_call)) {
|
|
680
|
+
try {
|
|
681
|
+
message.function_call.arguments = JSON.parse(message.function_call.arguments);
|
|
682
|
+
}
|
|
683
|
+
catch {
|
|
684
|
+
throw new Error(refusal("chatcompletions-function-call-arguments"));
|
|
685
|
+
}
|
|
686
|
+
transformedArguments.push({ message: messageIndex });
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
// Structural identifiers and numeric values (now including values inside
|
|
690
|
+
// tool arguments) must be safe BEFORE masking, so no mapping is committed for
|
|
691
|
+
// content we are about to refuse.
|
|
692
|
+
const structuralBefore = collectWireStructuralStrings(body);
|
|
693
|
+
for (const identifier of structuralBefore) {
|
|
694
|
+
if (containsTokenPrefix(identifier) || service.detectSensitive(identifier)) {
|
|
695
|
+
throw new Error(refusal("structural-identifier"));
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
let unsafeNumber = false;
|
|
699
|
+
walkNumbers(body, (value) => {
|
|
700
|
+
if (service.detectSensitive(String(value)))
|
|
701
|
+
unsafeNumber = true;
|
|
702
|
+
});
|
|
703
|
+
if (unsafeNumber)
|
|
704
|
+
throw new Error(refusal("number-sensitive"));
|
|
705
|
+
// Atomic protection: one transaction over the whole body.
|
|
706
|
+
const next = withOpaqueAttachments(service.attachmentsPolicy ?? "block", body, (input) => {
|
|
707
|
+
const masked = service.protectJsonForModel(sessionID, input);
|
|
708
|
+
if (!masked.ok)
|
|
709
|
+
throw new Error(MASK_FAILURE);
|
|
710
|
+
const value = masked.value;
|
|
711
|
+
if (!isRecord(value))
|
|
712
|
+
throw new Error(MASK_FAILURE);
|
|
713
|
+
return value;
|
|
714
|
+
});
|
|
715
|
+
// Defense in depth: no structural identifier may have changed.
|
|
716
|
+
const structuralAfter = collectWireStructuralStrings(next);
|
|
717
|
+
if (structuralAfter.length !== structuralBefore.length ||
|
|
718
|
+
structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
|
|
719
|
+
throw new Error(refusal("structural-drift"));
|
|
720
|
+
}
|
|
721
|
+
// Re-serialize every transformed argument: a parsed value re-encodes as
|
|
722
|
+
// valid JSON by construction, so masking can no longer break them.
|
|
723
|
+
if (Array.isArray(next.messages)) {
|
|
724
|
+
for (const { message: messageIndex, call: callIndex } of transformedArguments) {
|
|
725
|
+
const message = next.messages[messageIndex];
|
|
726
|
+
if (!isRecord(message))
|
|
727
|
+
throw new Error(MASK_FAILURE);
|
|
728
|
+
if (callIndex === undefined) {
|
|
729
|
+
if (!isRecord(message.function_call))
|
|
730
|
+
throw new Error(MASK_FAILURE);
|
|
731
|
+
message.function_call.arguments = JSON.stringify(message.function_call.arguments);
|
|
732
|
+
}
|
|
733
|
+
else {
|
|
734
|
+
if (!Array.isArray(message.tool_calls))
|
|
735
|
+
throw new Error(MASK_FAILURE);
|
|
736
|
+
const call = message.tool_calls[callIndex];
|
|
737
|
+
if (!isRecord(call) || !isRecord(call.function))
|
|
738
|
+
throw new Error(MASK_FAILURE);
|
|
739
|
+
call.function.arguments = JSON.stringify(call.function.arguments);
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
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 });
|
|
750
|
+
}
|
|
751
|
+
// ─── Anthropic Messages request (wire dialect) ──────────────────────────────
|
|
752
|
+
/**
|
|
753
|
+
* Validates an Anthropic Messages request body: top-level `system` (string or
|
|
754
|
+
* 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
|
|
757
|
+
* tokenized or unscanned content through the wire boundary.
|
|
758
|
+
*/
|
|
759
|
+
function validateAnthropicSystem(system) {
|
|
760
|
+
if (system === undefined || system === null || typeof system === "string")
|
|
761
|
+
return;
|
|
762
|
+
if (!Array.isArray(system))
|
|
763
|
+
throw new Error(refusal("anthropic-system-shape"));
|
|
764
|
+
for (const block of system) {
|
|
765
|
+
if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string") {
|
|
766
|
+
throw new Error(refusal("anthropic-system-block"));
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
function validateAnthropicContent(content, allowAttachments) {
|
|
771
|
+
if (content === undefined || content === null || typeof content === "string")
|
|
772
|
+
return;
|
|
773
|
+
if (!Array.isArray(content))
|
|
774
|
+
throw new Error(refusal("anthropic-content-shape"));
|
|
775
|
+
for (const block of content) {
|
|
776
|
+
if (!isRecord(block))
|
|
777
|
+
throw new Error(refusal("anthropic-content-block"));
|
|
778
|
+
if (allowAttachments && isAttachmentRecord(block))
|
|
779
|
+
continue;
|
|
780
|
+
switch (block.type) {
|
|
781
|
+
case "text":
|
|
782
|
+
if (typeof block.text !== "string")
|
|
783
|
+
throw new Error(refusal("anthropic-text-block"));
|
|
784
|
+
break;
|
|
785
|
+
case "tool_use":
|
|
786
|
+
if (typeof block.id !== "string" ||
|
|
787
|
+
typeof block.name !== "string" ||
|
|
788
|
+
!isRecord(block.input)) {
|
|
789
|
+
throw new Error(refusal("anthropic-tool-use-block"));
|
|
790
|
+
}
|
|
791
|
+
break;
|
|
792
|
+
case "tool_result": {
|
|
793
|
+
if (typeof block.tool_use_id !== "string")
|
|
794
|
+
throw new Error(refusal("anthropic-tool-result-block"));
|
|
795
|
+
const inner = block.content;
|
|
796
|
+
if (inner === undefined || inner === null || typeof inner === "string")
|
|
797
|
+
break;
|
|
798
|
+
if (!Array.isArray(inner))
|
|
799
|
+
throw new Error(refusal("anthropic-tool-result-content"));
|
|
800
|
+
for (const part of inner) {
|
|
801
|
+
// Images/documents inside tool results refuse like top-level ones,
|
|
802
|
+
// unless the user explicitly chose the "allow" policy.
|
|
803
|
+
if (allowAttachments && isAttachmentRecord(part)) {
|
|
804
|
+
continue;
|
|
805
|
+
}
|
|
806
|
+
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
|
|
807
|
+
throw new Error(refusal("anthropic-tool-result-part"));
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
default:
|
|
813
|
+
throw new Error(refusal("anthropic-content-block-type"));
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
function validateAnthropicDialect(body, allowAttachments) {
|
|
818
|
+
validateAnthropicSystem(body.system);
|
|
819
|
+
if (body.tools !== undefined) {
|
|
820
|
+
if (!Array.isArray(body.tools))
|
|
821
|
+
throw new Error(refusal("anthropic-tools-shape"));
|
|
822
|
+
for (const tool of body.tools) {
|
|
823
|
+
if (!isRecord(tool) || typeof tool.name !== "string")
|
|
824
|
+
throw new Error(refusal("anthropic-tool-shape"));
|
|
825
|
+
if (tool.input_schema !== undefined && !isRecord(tool.input_schema)) {
|
|
826
|
+
throw new Error(refusal("anthropic-tool-schema"));
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
if (!Array.isArray(body.messages))
|
|
831
|
+
throw new Error(refusal("anthropic-messages-shape"));
|
|
832
|
+
for (const message of body.messages) {
|
|
833
|
+
if (!isRecord(message) || typeof message.role !== "string") {
|
|
834
|
+
throw new Error(refusal("anthropic-message-shape"));
|
|
835
|
+
}
|
|
836
|
+
validateAnthropicContent(message.content, allowAttachments);
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
/** Structural identifiers that must survive masking verbatim (Anthropic shape). */
|
|
840
|
+
function collectAnthropicStructuralStrings(body) {
|
|
841
|
+
const out = [];
|
|
842
|
+
pushString(out, body.model);
|
|
843
|
+
if (Array.isArray(body.messages)) {
|
|
844
|
+
for (const message of body.messages) {
|
|
845
|
+
if (!isRecord(message))
|
|
846
|
+
continue;
|
|
847
|
+
pushString(out, message.role);
|
|
848
|
+
if (Array.isArray(message.content)) {
|
|
849
|
+
for (const block of message.content) {
|
|
850
|
+
if (!isRecord(block))
|
|
851
|
+
continue;
|
|
852
|
+
pushString(out, block.type);
|
|
853
|
+
if (block.type === "tool_use") {
|
|
854
|
+
pushString(out, block.id);
|
|
855
|
+
pushString(out, block.name);
|
|
856
|
+
}
|
|
857
|
+
if (block.type === "tool_result")
|
|
858
|
+
pushString(out, block.tool_use_id);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
if (Array.isArray(body.tools)) {
|
|
864
|
+
for (const tool of body.tools) {
|
|
865
|
+
if (isRecord(tool))
|
|
866
|
+
pushString(out, tool.name);
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
if (Array.isArray(body.stop_sequences)) {
|
|
870
|
+
for (const stop of body.stop_sequences)
|
|
871
|
+
pushString(out, stop);
|
|
872
|
+
}
|
|
873
|
+
return out;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Remasks an Anthropic Messages JSON request body. Same contract as the
|
|
877
|
+
* chat-completions path: every check that can reject runs FIRST, then the
|
|
878
|
+
* whole body is protected in ONE transaction; a rejected request commits no
|
|
879
|
+
* mapping or session capacity. tool_use.input is already a JSON object (no
|
|
880
|
+
* string re-encoding needed) and stays tokenized on the wire; the typed tool
|
|
881
|
+
* gate restores before execution.
|
|
882
|
+
*/
|
|
883
|
+
export async function remaskAnthropicMessagesRequest(service, sessionID, request) {
|
|
884
|
+
if (!isAnthropicMessagesUrl(request.url))
|
|
885
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
886
|
+
if (urlCarriesToken(request.url)) {
|
|
887
|
+
// P1 (2026-10-06b): a placeholder in the URL is judged, not auto-refused;
|
|
888
|
+
// sensitive content in a URL cannot be masked without changing the target.
|
|
889
|
+
if (!service.isTransportIdentifierSafe(sessionID, request.url)) {
|
|
890
|
+
throw new Error(refusal("url-token"));
|
|
891
|
+
}
|
|
892
|
+
warnDegradation("request url preserved with a literal placeholder");
|
|
893
|
+
}
|
|
894
|
+
inspectTransportMetadata(service, sessionID, request);
|
|
895
|
+
if (request.body === null)
|
|
896
|
+
throw new Error(refusal("body-missing"));
|
|
897
|
+
const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
|
|
898
|
+
if (raw.length === 0)
|
|
899
|
+
throw new Error(refusal("body-empty"));
|
|
900
|
+
let body;
|
|
901
|
+
try {
|
|
902
|
+
body = JSON.parse(raw);
|
|
903
|
+
}
|
|
904
|
+
catch {
|
|
905
|
+
throw new Error(refusal("body-json"));
|
|
906
|
+
}
|
|
907
|
+
if (!isRecord(body))
|
|
908
|
+
throw new Error(refusal("body-shape"));
|
|
909
|
+
validateAnthropicDialect(body, attachmentsAllowed(service));
|
|
910
|
+
const originalSerialized = JSON.stringify(body);
|
|
911
|
+
const structuralBefore = collectAnthropicStructuralStrings(body);
|
|
912
|
+
for (const identifier of structuralBefore) {
|
|
913
|
+
if (containsTokenPrefix(identifier) || service.detectSensitive(identifier)) {
|
|
914
|
+
throw new Error(refusal("structural-identifier"));
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
let unsafeNumber = false;
|
|
918
|
+
walkNumbers(body, (value) => {
|
|
919
|
+
if (service.detectSensitive(String(value)))
|
|
920
|
+
unsafeNumber = true;
|
|
921
|
+
});
|
|
922
|
+
if (unsafeNumber)
|
|
923
|
+
throw new Error(refusal("number-sensitive"));
|
|
924
|
+
const next = withOpaqueAttachments(service.attachmentsPolicy ?? "block", body, (input) => {
|
|
925
|
+
const masked = service.protectJsonForModel(sessionID, input);
|
|
926
|
+
if (!masked.ok)
|
|
927
|
+
throw new Error(MASK_FAILURE);
|
|
928
|
+
const value = masked.value;
|
|
929
|
+
if (!isRecord(value))
|
|
930
|
+
throw new Error(MASK_FAILURE);
|
|
931
|
+
return value;
|
|
932
|
+
});
|
|
933
|
+
const structuralAfter = collectAnthropicStructuralStrings(next);
|
|
934
|
+
if (structuralAfter.length !== structuralBefore.length ||
|
|
935
|
+
structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
|
|
936
|
+
throw new Error(refusal("structural-drift"));
|
|
937
|
+
}
|
|
938
|
+
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 });
|
|
945
|
+
}
|
|
946
|
+
// ─── OpenAI Responses request (wire dialect) ────────────────────────────────
|
|
947
|
+
/**
|
|
948
|
+
* Validates an OpenAI Responses request body: `instructions` string, `input`
|
|
949
|
+
* (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.
|
|
954
|
+
*/
|
|
955
|
+
function validateResponsesContentParts(content, allowAttachments) {
|
|
956
|
+
if (content === undefined || content === null || typeof content === "string")
|
|
957
|
+
return;
|
|
958
|
+
if (!Array.isArray(content))
|
|
959
|
+
throw new Error(refusal("responses-content-shape"));
|
|
960
|
+
for (const part of content) {
|
|
961
|
+
if (allowAttachments && isAttachmentRecord(part)) {
|
|
962
|
+
continue;
|
|
963
|
+
}
|
|
964
|
+
if (!isRecord(part) ||
|
|
965
|
+
(part.type !== "input_text" && part.type !== "output_text") ||
|
|
966
|
+
typeof part.text !== "string") {
|
|
967
|
+
throw new Error(refusal("responses-content-part"));
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|
|
971
|
+
/** Text-part kinds the restore side recognizes on reasoning items. */
|
|
972
|
+
const REASONING_TEXT_PART_TYPES = new Set(["summary_text", "reasoning_text"]);
|
|
973
|
+
function validateResponsesReasoningParts(parts) {
|
|
974
|
+
if (parts === undefined || parts === null)
|
|
975
|
+
return;
|
|
976
|
+
if (!Array.isArray(parts))
|
|
977
|
+
throw new Error(refusal("responses-reasoning-shape"));
|
|
978
|
+
for (const part of parts) {
|
|
979
|
+
if (!isRecord(part) ||
|
|
980
|
+
typeof part.type !== "string" ||
|
|
981
|
+
!REASONING_TEXT_PART_TYPES.has(part.type) ||
|
|
982
|
+
typeof part.text !== "string") {
|
|
983
|
+
throw new Error(refusal("responses-reasoning-shape"));
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
function validateResponsesInputItem(item, allowAttachments) {
|
|
988
|
+
if (typeof item === "string")
|
|
989
|
+
return;
|
|
990
|
+
if (!isRecord(item))
|
|
991
|
+
throw new Error(refusal("responses-input-item"));
|
|
992
|
+
// Responses EasyInputMessage permits omitted type. AI SDK's Responses
|
|
993
|
+
// lowering emits this form for system/developer/user/assistant messages.
|
|
994
|
+
// Do not normalize the wire body or infer arbitrary type-less records:
|
|
995
|
+
// require a recognized role plus actual supported content before masking.
|
|
996
|
+
if (item.type === undefined && typeof item.role === "string" && ["system", "developer", "user", "assistant"].includes(item.role)) {
|
|
997
|
+
if (item.content === undefined || item.content === null)
|
|
998
|
+
throw new Error(refusal("responses-content-shape"));
|
|
999
|
+
validateResponsesContentParts(item.content, allowAttachments);
|
|
1000
|
+
return;
|
|
1001
|
+
}
|
|
1002
|
+
switch (item.type) {
|
|
1003
|
+
case "message":
|
|
1004
|
+
if (typeof item.role !== "string")
|
|
1005
|
+
throw new Error(refusal("responses-message-role"));
|
|
1006
|
+
validateResponsesContentParts(item.content, allowAttachments);
|
|
1007
|
+
return;
|
|
1008
|
+
case "function_call":
|
|
1009
|
+
if (typeof item.name !== "string" || typeof item.arguments !== "string") {
|
|
1010
|
+
throw new Error(refusal("responses-function-call-shape"));
|
|
1011
|
+
}
|
|
1012
|
+
return;
|
|
1013
|
+
case "function_call_output":
|
|
1014
|
+
if (typeof item.output !== "string") {
|
|
1015
|
+
if (!Array.isArray(item.output))
|
|
1016
|
+
throw new Error(refusal("responses-function-output"));
|
|
1017
|
+
validateResponsesContentParts(item.output, allowAttachments);
|
|
1018
|
+
}
|
|
1019
|
+
return;
|
|
1020
|
+
case "reasoning": {
|
|
1021
|
+
// Encrypted reasoning payloads are provider-opaque: they cannot be
|
|
1022
|
+
// scanned, and masking them is impossible without corrupting the blob
|
|
1023
|
+
// (a false-positive finding — e.g. an `sk-` substring inside base64 —
|
|
1024
|
+
// would break the protocol). They are derived from earlier masked
|
|
1025
|
+
// traffic and return to the same provider, disclosing nothing new.
|
|
1026
|
+
// The plaintext channels (summary / content parts) are masked like
|
|
1027
|
+
// ordinary text; the id survives verbatim as a structural identifier.
|
|
1028
|
+
if (item.encrypted_content !== undefined && typeof item.encrypted_content !== "string") {
|
|
1029
|
+
throw new Error(refusal("responses-reasoning-shape"));
|
|
1030
|
+
}
|
|
1031
|
+
validateResponsesReasoningParts(item.summary);
|
|
1032
|
+
validateResponsesReasoningParts(item.content);
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
default:
|
|
1036
|
+
// item_reference / unknown: cannot verify or place.
|
|
1037
|
+
throw new Error(refusal("responses-item-type"));
|
|
1038
|
+
}
|
|
1039
|
+
}
|
|
1040
|
+
function validateResponsesDialect(body, allowAttachments) {
|
|
1041
|
+
// A chat-completions/anthropic-shaped body on a /responses route is a
|
|
1042
|
+
// mixed dialect this masker cannot place; refuse it explicitly.
|
|
1043
|
+
if (body.messages !== undefined || body.system !== undefined) {
|
|
1044
|
+
throw new Error(refusal("responses-mixed-dialect"));
|
|
1045
|
+
}
|
|
1046
|
+
if (body.instructions !== undefined && typeof body.instructions !== "string") {
|
|
1047
|
+
throw new Error(refusal("responses-instructions"));
|
|
1048
|
+
}
|
|
1049
|
+
if (body.tools !== undefined) {
|
|
1050
|
+
if (!Array.isArray(body.tools))
|
|
1051
|
+
throw new Error(refusal("responses-tools-shape"));
|
|
1052
|
+
for (const tool of body.tools) {
|
|
1053
|
+
if (!isRecord(tool) || typeof tool.name !== "string")
|
|
1054
|
+
throw new Error(refusal("responses-tool-shape"));
|
|
1055
|
+
if (tool.parameters !== undefined && !isRecord(tool.parameters)) {
|
|
1056
|
+
throw new Error(refusal("responses-tool-schema"));
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
1059
|
+
}
|
|
1060
|
+
if (body.input !== undefined) {
|
|
1061
|
+
if (typeof body.input !== "string") {
|
|
1062
|
+
if (!Array.isArray(body.input))
|
|
1063
|
+
throw new Error(refusal("responses-input-shape"));
|
|
1064
|
+
for (const item of body.input)
|
|
1065
|
+
validateResponsesInputItem(item, allowAttachments);
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
/** Structural identifiers that must survive masking verbatim (Responses shape). */
|
|
1070
|
+
function collectResponsesStructuralStrings(body) {
|
|
1071
|
+
const out = [];
|
|
1072
|
+
pushString(out, body.model);
|
|
1073
|
+
if (Array.isArray(body.input)) {
|
|
1074
|
+
for (const item of body.input) {
|
|
1075
|
+
if (!isRecord(item))
|
|
1076
|
+
continue;
|
|
1077
|
+
pushString(out, item.type);
|
|
1078
|
+
pushString(out, item.role);
|
|
1079
|
+
pushString(out, item.call_id);
|
|
1080
|
+
if (item.type === "function_call")
|
|
1081
|
+
pushString(out, item.name);
|
|
1082
|
+
if (item.type === "reasoning")
|
|
1083
|
+
pushString(out, item.id);
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
if (Array.isArray(body.tools)) {
|
|
1087
|
+
for (const tool of body.tools) {
|
|
1088
|
+
if (isRecord(tool))
|
|
1089
|
+
pushString(out, tool.name);
|
|
1090
|
+
}
|
|
1091
|
+
}
|
|
1092
|
+
return out;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Remasks an OpenAI Responses JSON request body. Same contract as the other
|
|
1096
|
+
* dialects: reject-first validation, ONE atomic transaction, structural
|
|
1097
|
+
* identifiers preserved. function_call.arguments is a JSON-encoded string and
|
|
1098
|
+
* is parsed before masking and re-encoded after (same rule as chat
|
|
1099
|
+
* completions tool arguments).
|
|
1100
|
+
*/
|
|
1101
|
+
export async function remaskResponsesRequest(service, sessionID, request) {
|
|
1102
|
+
if (!isResponsesUrl(request.url))
|
|
1103
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
1104
|
+
if (urlCarriesToken(request.url)) {
|
|
1105
|
+
// P1 (2026-10-06b): a placeholder in the URL is judged, not auto-refused;
|
|
1106
|
+
// sensitive content in a URL cannot be masked without changing the target.
|
|
1107
|
+
if (!service.isTransportIdentifierSafe(sessionID, request.url)) {
|
|
1108
|
+
throw new Error(refusal("url-token"));
|
|
1109
|
+
}
|
|
1110
|
+
warnDegradation("request url preserved with a literal placeholder");
|
|
1111
|
+
}
|
|
1112
|
+
inspectTransportMetadata(service, sessionID, request);
|
|
1113
|
+
if (request.body === null)
|
|
1114
|
+
throw new Error(refusal("body-missing"));
|
|
1115
|
+
const raw = await readCappedText(request, MAX_BODY_BYTES, refusal("body-cap"));
|
|
1116
|
+
if (raw.length === 0)
|
|
1117
|
+
throw new Error(refusal("body-empty"));
|
|
1118
|
+
let body;
|
|
1119
|
+
try {
|
|
1120
|
+
body = JSON.parse(raw);
|
|
1121
|
+
}
|
|
1122
|
+
catch {
|
|
1123
|
+
throw new Error(refusal("body-json"));
|
|
1124
|
+
}
|
|
1125
|
+
if (!isRecord(body))
|
|
1126
|
+
throw new Error(refusal("body-shape"));
|
|
1127
|
+
validateResponsesDialect(body, attachmentsAllowed(service));
|
|
1128
|
+
const originalSerialized = JSON.stringify(body);
|
|
1129
|
+
// function_call.arguments strings are parsed so masking cannot invalidate
|
|
1130
|
+
// the JSON; re-encoded after the atomic protect (chat-completions rule).
|
|
1131
|
+
const transformedArguments = [];
|
|
1132
|
+
if (Array.isArray(body.input)) {
|
|
1133
|
+
for (let index = 0; index < body.input.length; index++) {
|
|
1134
|
+
const item = body.input[index];
|
|
1135
|
+
if (isRecord(item) && item.type === "function_call" && isRecordArgumentsString(item)) {
|
|
1136
|
+
try {
|
|
1137
|
+
item.arguments = JSON.parse(item.arguments);
|
|
1138
|
+
}
|
|
1139
|
+
catch {
|
|
1140
|
+
throw new Error(refusal("responses-function-call-arguments"));
|
|
1141
|
+
}
|
|
1142
|
+
transformedArguments.push(index);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
const structuralBefore = collectResponsesStructuralStrings(body);
|
|
1147
|
+
for (const identifier of structuralBefore) {
|
|
1148
|
+
if (containsTokenPrefix(identifier) || service.detectSensitive(identifier)) {
|
|
1149
|
+
throw new Error(refusal("structural-identifier"));
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
let unsafeNumber = false;
|
|
1153
|
+
walkNumbers(body, (value) => {
|
|
1154
|
+
if (service.detectSensitive(String(value)))
|
|
1155
|
+
unsafeNumber = true;
|
|
1156
|
+
});
|
|
1157
|
+
if (unsafeNumber)
|
|
1158
|
+
throw new Error(refusal("number-sensitive"));
|
|
1159
|
+
const next = withOpaqueReasoningContent(body, (stage) => withOpaqueAttachments(service.attachmentsPolicy ?? "block", stage, (input) => {
|
|
1160
|
+
const masked = service.protectJsonForModel(sessionID, input);
|
|
1161
|
+
if (!masked.ok)
|
|
1162
|
+
throw new Error(MASK_FAILURE);
|
|
1163
|
+
const value = masked.value;
|
|
1164
|
+
if (!isRecord(value))
|
|
1165
|
+
throw new Error(MASK_FAILURE);
|
|
1166
|
+
return value;
|
|
1167
|
+
}));
|
|
1168
|
+
const structuralAfter = collectResponsesStructuralStrings(next);
|
|
1169
|
+
if (structuralAfter.length !== structuralBefore.length ||
|
|
1170
|
+
structuralAfter.some((identifier, index) => identifier !== structuralBefore[index])) {
|
|
1171
|
+
throw new Error(refusal("structural-drift"));
|
|
1172
|
+
}
|
|
1173
|
+
if (Array.isArray(next.input)) {
|
|
1174
|
+
for (const index of transformedArguments) {
|
|
1175
|
+
const item = next.input[index];
|
|
1176
|
+
if (!isRecord(item) || typeof item.name !== "string")
|
|
1177
|
+
throw new Error(MASK_FAILURE);
|
|
1178
|
+
item.arguments = JSON.stringify(item.arguments);
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
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 });
|
|
1188
|
+
}
|
|
1189
|
+
function isRecordArgumentsString(item) {
|
|
1190
|
+
return typeof item.arguments === "string";
|
|
1191
|
+
}
|
|
1192
|
+
/** Hook-first admission: check the supported response route and transport
|
|
1193
|
+
* metadata without reading, validating, or changing the final request body.
|
|
1194
|
+
* Returning the same Request preserves identity for response attribution. */
|
|
1195
|
+
export function admitModelRequest(service, sessionID, request, allowHookOnly = false) {
|
|
1196
|
+
const url = new URL(request.url);
|
|
1197
|
+
if ((url.protocol !== "http:" && url.protocol !== "https:") || (!allowHookOnly && classifyModelRoute(request.url) === null)) {
|
|
1198
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
1199
|
+
}
|
|
1200
|
+
if (urlCarriesToken(request.url)) {
|
|
1201
|
+
if (!service.isTransportIdentifierSafe(sessionID, request.url))
|
|
1202
|
+
throw new Error(refusal("url-token"));
|
|
1203
|
+
warnDegradation("request url preserved with a literal placeholder");
|
|
1204
|
+
}
|
|
1205
|
+
inspectTransportMetadata(service, sessionID, request);
|
|
1206
|
+
return request;
|
|
1207
|
+
}
|
|
1208
|
+
/** Protocol dispatcher: masks any supported wire route by URL shape. */
|
|
1209
|
+
export async function remaskModelRequest(service, sessionID, request) {
|
|
1210
|
+
const route = classifyModelRoute(request.url);
|
|
1211
|
+
if (route === null)
|
|
1212
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
1213
|
+
if (route === "anthropic-messages") {
|
|
1214
|
+
return remaskAnthropicMessagesRequest(service, sessionID, request);
|
|
1215
|
+
}
|
|
1216
|
+
if (route === "openai-responses") {
|
|
1217
|
+
return remaskResponsesRequest(service, sessionID, request);
|
|
1218
|
+
}
|
|
1219
|
+
return remaskChatCompletionsRequest(service, sessionID, request);
|
|
1220
|
+
}
|
|
1221
|
+
// ─── Response restore (assistant display text only) ─────────────────────────
|
|
1222
|
+
/**
|
|
1223
|
+
* Restores assistant display text in a model response. Error bodies and
|
|
1224
|
+
* unsupported content types are passed through only when a bounded clone-read
|
|
1225
|
+
* proves they carry no reserved token this module cannot restore; otherwise
|
|
1226
|
+
* the response fails closed.
|
|
1227
|
+
*/
|
|
1228
|
+
export async function restoreChatCompletionsResponse(service, sessionID, response) {
|
|
1229
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
1230
|
+
const restorable = response.status >= 200 && response.status < 300;
|
|
1231
|
+
if (restorable && contentType.includes("application/json")) {
|
|
1232
|
+
return restoreJsonResponse(service, sessionID, response);
|
|
1233
|
+
}
|
|
1234
|
+
if (restorable && contentType.includes("text/event-stream")) {
|
|
1235
|
+
return restoreSseResponse(service, sessionID, response);
|
|
1236
|
+
}
|
|
1237
|
+
// P1 (2026-10-06b): an unplaceable placeholder in an unrestorable body is
|
|
1238
|
+
// degradation — pass through with a WARN, never a refusal; token-free
|
|
1239
|
+
// error/metadata bodies pass untouched.
|
|
1240
|
+
return passThroughIfTokenBearing(response);
|
|
1241
|
+
}
|
|
1242
|
+
/** Passes an unrestorable response through, degrading (WARN) when it carries a placeholder. */
|
|
1243
|
+
async function passThroughIfTokenBearing(response) {
|
|
1244
|
+
if (response.body === null)
|
|
1245
|
+
return response;
|
|
1246
|
+
const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
|
|
1247
|
+
if (containsTokenPrefix(raw))
|
|
1248
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1249
|
+
return response;
|
|
1250
|
+
}
|
|
1251
|
+
async function restoreJsonResponse(service, sessionID, response) {
|
|
1252
|
+
const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
|
|
1253
|
+
if (raw.length === 0)
|
|
1254
|
+
return response;
|
|
1255
|
+
let body;
|
|
1256
|
+
try {
|
|
1257
|
+
body = JSON.parse(raw);
|
|
1258
|
+
}
|
|
1259
|
+
catch {
|
|
1260
|
+
if (containsTokenPrefix(raw))
|
|
1261
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1262
|
+
return response;
|
|
1263
|
+
}
|
|
1264
|
+
if (!isRecord(body)) {
|
|
1265
|
+
if (containsTokenPrefix(raw))
|
|
1266
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1267
|
+
return response;
|
|
1268
|
+
}
|
|
1269
|
+
if (body.choices === undefined) {
|
|
1270
|
+
// Not a chat-completions payload; an unplaceable placeholder degrades to
|
|
1271
|
+
// a literal emit with a WARN (P1, 2026-10-06b).
|
|
1272
|
+
if (containsTokenPrefix(raw))
|
|
1273
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1274
|
+
return response;
|
|
1275
|
+
}
|
|
1276
|
+
if (!Array.isArray(body.choices))
|
|
1277
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1278
|
+
let changed = false;
|
|
1279
|
+
for (const choice of body.choices) {
|
|
1280
|
+
if (!isRecord(choice))
|
|
1281
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1282
|
+
const message = choice.message;
|
|
1283
|
+
if (message === undefined || message === null)
|
|
1284
|
+
continue;
|
|
1285
|
+
if (!isRecord(message))
|
|
1286
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1287
|
+
changed = restoreAssistantContent(service, sessionID, message) || changed;
|
|
1288
|
+
// message.tool_calls is deliberately untouched: tool arguments stay
|
|
1289
|
+
// tokenized until the typed tool gate decides execution.
|
|
1290
|
+
}
|
|
1291
|
+
// P1 (2026-10-06b): a reserved token outside intentional tool arguments is
|
|
1292
|
+
// degradation, not failure — the placeholder stays literal with a WARN;
|
|
1293
|
+
// mapping loss never refuses response delivery.
|
|
1294
|
+
if (strayTokenIn(body))
|
|
1295
|
+
warnDegradation("response carries an unplaceable placeholder; kept literal");
|
|
1296
|
+
if (!changed)
|
|
1297
|
+
return response;
|
|
1298
|
+
const next = JSON.stringify(body);
|
|
1299
|
+
const headers = new Headers(response.headers);
|
|
1300
|
+
headers.delete("content-encoding");
|
|
1301
|
+
headers.set("content-length", String(byteLength(next)));
|
|
1302
|
+
return new Response(next, {
|
|
1303
|
+
status: response.status,
|
|
1304
|
+
statusText: response.statusText,
|
|
1305
|
+
headers,
|
|
1306
|
+
});
|
|
1307
|
+
}
|
|
1308
|
+
function restoreAssistantContent(service, sessionID, message) {
|
|
1309
|
+
const content = message.content;
|
|
1310
|
+
if (content === undefined || content === null)
|
|
1311
|
+
return false;
|
|
1312
|
+
if (typeof content === "string") {
|
|
1313
|
+
if (content.length === 0)
|
|
1314
|
+
return false;
|
|
1315
|
+
const restored = restoreDisplayText(service, sessionID, content);
|
|
1316
|
+
if (restored !== content) {
|
|
1317
|
+
message.content = restored;
|
|
1318
|
+
return true;
|
|
1319
|
+
}
|
|
1320
|
+
return false;
|
|
1321
|
+
}
|
|
1322
|
+
if (!Array.isArray(content))
|
|
1323
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1324
|
+
let changed = false;
|
|
1325
|
+
for (const part of content) {
|
|
1326
|
+
if (!isRecord(part) || part.type !== "text" || typeof part.text !== "string") {
|
|
1327
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1328
|
+
}
|
|
1329
|
+
if (part.text.length === 0)
|
|
1330
|
+
continue;
|
|
1331
|
+
const restored = restoreDisplayText(service, sessionID, part.text);
|
|
1332
|
+
if (restored !== part.text) {
|
|
1333
|
+
part.text = restored;
|
|
1334
|
+
changed = true;
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
return changed;
|
|
1338
|
+
}
|
|
1339
|
+
export function restoreDisplayText(service, sessionID, text) {
|
|
1340
|
+
const result = service.restoreTextForDisplay(sessionID, text);
|
|
1341
|
+
if (!result.ok)
|
|
1342
|
+
throw new Error(RESTORE_FAILURE);
|
|
1343
|
+
return result.text;
|
|
1344
|
+
}
|
|
1345
|
+
// ─── SSE streaming restore ───────────────────────────────────────────────────
|
|
1346
|
+
function restoreSseResponse(service, sessionID, response) {
|
|
1347
|
+
if (response.body === null)
|
|
1348
|
+
return response;
|
|
1349
|
+
const headers = new Headers(response.headers);
|
|
1350
|
+
headers.delete("content-encoding");
|
|
1351
|
+
headers.delete("content-length");
|
|
1352
|
+
const stream = createSseRestoreStream(service, sessionID, response.body);
|
|
1353
|
+
return new Response(stream, {
|
|
1354
|
+
status: response.status,
|
|
1355
|
+
statusText: response.statusText,
|
|
1356
|
+
headers,
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
/**
|
|
1360
|
+
* Splits `buffered` into the portion safe to restore now and any incomplete
|
|
1361
|
+
* token candidate that must be held back until more stream data arrives. A
|
|
1362
|
+
* held tail is either a partial token from its LAST full prefix (either
|
|
1363
|
+
* version), or the longest suffix that is a proper prefix of a reserved
|
|
1364
|
+
* namespace prefix (e.g. `[SG`, `[SGP2`): emitting that suffix literally
|
|
1365
|
+
* would make the token unrestorable. Complete tokens in the emit portion are
|
|
1366
|
+
* restored by the caller through the core; a tail that never completes
|
|
1367
|
+
* degrades to a literal emit with a WARN at the terminal boundary
|
|
1368
|
+
* (P1, 2026-10-06b).
|
|
1369
|
+
*/
|
|
1370
|
+
export function splitRestorable(buffered) {
|
|
1371
|
+
let at = -1;
|
|
1372
|
+
for (const prefix of PSEUDONYM_TOKEN_PREFIXES) {
|
|
1373
|
+
const candidate = buffered.lastIndexOf(prefix);
|
|
1374
|
+
if (candidate > at)
|
|
1375
|
+
at = candidate;
|
|
1376
|
+
}
|
|
1377
|
+
if (at !== -1) {
|
|
1378
|
+
const tail = buffered.slice(at);
|
|
1379
|
+
if (!tail.includes("]"))
|
|
1380
|
+
return { emit: buffered.slice(0, at), hold: tail };
|
|
1381
|
+
}
|
|
1382
|
+
// Longest suffix matching a proper prefix of either reserved prefix. Both
|
|
1383
|
+
// versions share "[SGP" and differ only in the version character, so the
|
|
1384
|
+
// distinct candidates (length 5 down to 1) are checked longest-first.
|
|
1385
|
+
for (let length = PSEUDONYM_TOKEN_PREFIXES[0].length - 1; length >= 1; length--) {
|
|
1386
|
+
for (const prefix of PSEUDONYM_TOKEN_PREFIXES) {
|
|
1387
|
+
const partial = prefix.slice(0, length);
|
|
1388
|
+
if (buffered.endsWith(partial)) {
|
|
1389
|
+
return { emit: buffered.slice(0, buffered.length - length), hold: partial };
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
return { emit: buffered, hold: "" };
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Incremental SSE restore. UTF-8 is decoded streaming (code points may split
|
|
1397
|
+
* across chunks), complete events are assembled from their `data:` lines as
|
|
1398
|
+
* they terminate (a blank line), and each choice's `delta.content` channel
|
|
1399
|
+
* keeps a token-prefix hold buffer so tokens split across chunks AND events
|
|
1400
|
+
* are restored exactly once, in order.
|
|
1401
|
+
*
|
|
1402
|
+
* Bounds are explicit, measured in UTF-8 bytes and fail closed: the pending
|
|
1403
|
+
* line buffer, the accumulated (unterminated) event, each choice channel, the
|
|
1404
|
+
* aggregate channel state and the channel count are all capped, each charged
|
|
1405
|
+
* before the value is accumulated. A choice whose token is still unresolved
|
|
1406
|
+
* at a terminal `finish_reason` degrades — the held tail is emitted literally
|
|
1407
|
+
* with a WARN — and a choice that keeps producing output after it is terminal
|
|
1408
|
+
* refuses. Reading is pull-based: one
|
|
1409
|
+
* bounded batch of upstream data is consumed per downstream pull, so an unread
|
|
1410
|
+
* consumer never builds an unbounded downstream queue. Errors from the
|
|
1411
|
+
* underlying stream propagate and downstream cancellation cancels its reader.
|
|
1412
|
+
* SG parse/restore failures instead replay undelivered originals and bypass
|
|
1413
|
+
* further rewriting; they never cancel a healthy upstream response.
|
|
1414
|
+
*/
|
|
1415
|
+
export function createSseRestoreStream(service, sessionID, body) {
|
|
1416
|
+
const reader = body.getReader();
|
|
1417
|
+
/** Held-back content tails per choice index (tokens split across events). */
|
|
1418
|
+
const channels = new Map();
|
|
1419
|
+
/** Choice indexes that have already seen a terminal `finish_reason`. */
|
|
1420
|
+
const terminalChannels = new Set();
|
|
1421
|
+
let totalChannelBytes = 0;
|
|
1422
|
+
let eventLines = [];
|
|
1423
|
+
/** An unresolved boundary stops rewriting; the shared loop retains and
|
|
1424
|
+
* releases the original frames rather than losing the literal prefix. */
|
|
1425
|
+
const requireEmptyChannels = () => {
|
|
1426
|
+
if (channels.size !== 0)
|
|
1427
|
+
throw new Error(MALFORMED_STREAM);
|
|
1428
|
+
};
|
|
1429
|
+
const setChannel = (channel, hold) => {
|
|
1430
|
+
const previous = channels.get(channel) ?? "";
|
|
1431
|
+
totalChannelBytes += byteLength(hold) - byteLength(previous);
|
|
1432
|
+
if (totalChannelBytes > MAX_TOTAL_CHANNEL_BYTES)
|
|
1433
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1434
|
+
channels.set(channel, hold);
|
|
1435
|
+
};
|
|
1436
|
+
const deleteChannel = (channel) => {
|
|
1437
|
+
const previous = channels.get(channel);
|
|
1438
|
+
if (previous !== undefined)
|
|
1439
|
+
totalChannelBytes -= byteLength(previous);
|
|
1440
|
+
channels.delete(channel);
|
|
1441
|
+
};
|
|
1442
|
+
/** Assembles and restores one SSE event; `terminated` adds the blank line. */
|
|
1443
|
+
const processEvent = (terminated) => {
|
|
1444
|
+
const lines = eventLines;
|
|
1445
|
+
eventLines = [];
|
|
1446
|
+
const framing = [];
|
|
1447
|
+
const dataPayloads = [];
|
|
1448
|
+
for (const rawLine of lines) {
|
|
1449
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
1450
|
+
if (line.startsWith("data:")) {
|
|
1451
|
+
let payload = line.slice("data:".length);
|
|
1452
|
+
if (payload.startsWith(" "))
|
|
1453
|
+
payload = payload.slice(1);
|
|
1454
|
+
dataPayloads.push(payload);
|
|
1455
|
+
}
|
|
1456
|
+
else {
|
|
1457
|
+
framing.push(line);
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
const emitPayload = (payload) => framing.concat(payload.split("\n").map((line) => `data: ${line}`));
|
|
1461
|
+
let outputLines;
|
|
1462
|
+
if (dataPayloads.length === 0) {
|
|
1463
|
+
outputLines = framing;
|
|
1464
|
+
}
|
|
1465
|
+
else {
|
|
1466
|
+
const joined = dataPayloads.join("\n");
|
|
1467
|
+
if (joined === "[DONE]") {
|
|
1468
|
+
requireEmptyChannels();
|
|
1469
|
+
outputLines = emitPayload(joined);
|
|
1470
|
+
}
|
|
1471
|
+
else {
|
|
1472
|
+
let chunk;
|
|
1473
|
+
try {
|
|
1474
|
+
chunk = JSON.parse(joined);
|
|
1475
|
+
}
|
|
1476
|
+
catch {
|
|
1477
|
+
throw new Error(MALFORMED_STREAM);
|
|
1478
|
+
}
|
|
1479
|
+
if (!isRecord(chunk))
|
|
1480
|
+
throw new Error(MALFORMED_STREAM);
|
|
1481
|
+
// A provider error must reach the host immediately, even while an
|
|
1482
|
+
// incomplete text token is holding earlier events transactionally.
|
|
1483
|
+
// Recovery releases the original error envelope, never a fake finish.
|
|
1484
|
+
if (chunk.error !== undefined || chunk.type === "error")
|
|
1485
|
+
throw new Error(MALFORMED_STREAM);
|
|
1486
|
+
if (chunk.choices !== undefined) {
|
|
1487
|
+
if (!Array.isArray(chunk.choices))
|
|
1488
|
+
throw new Error(MALFORMED_STREAM);
|
|
1489
|
+
for (let position = 0; position < chunk.choices.length; position++) {
|
|
1490
|
+
const choice = chunk.choices[position];
|
|
1491
|
+
if (!isRecord(choice))
|
|
1492
|
+
throw new Error(MALFORMED_STREAM);
|
|
1493
|
+
// Channel key is the provider's choice index when present, so
|
|
1494
|
+
// interleaved multi-choice streams keep independent hold buffers.
|
|
1495
|
+
const channel = typeof choice.index === "number" && Number.isInteger(choice.index)
|
|
1496
|
+
? choice.index
|
|
1497
|
+
: position;
|
|
1498
|
+
const terminal = typeof choice.finish_reason === "string";
|
|
1499
|
+
// Terminal state is per choice: no further event may follow it.
|
|
1500
|
+
if (terminalChannels.has(channel))
|
|
1501
|
+
throw new Error(MALFORMED_STREAM);
|
|
1502
|
+
const delta = choice.delta;
|
|
1503
|
+
if (delta !== undefined && delta !== null) {
|
|
1504
|
+
if (!isRecord(delta))
|
|
1505
|
+
throw new Error(MALFORMED_STREAM);
|
|
1506
|
+
// delta.tool_calls is deliberately not restored: tool arguments
|
|
1507
|
+
// remain tokenized until the typed tool gate.
|
|
1508
|
+
const content = delta.content;
|
|
1509
|
+
if (content !== undefined && content !== null) {
|
|
1510
|
+
if (typeof content !== "string")
|
|
1511
|
+
throw new Error(MALFORMED_STREAM);
|
|
1512
|
+
if (!channels.has(channel) && channels.size >= MAX_CHANNELS) {
|
|
1513
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1514
|
+
}
|
|
1515
|
+
const held = channels.get(channel) ?? "";
|
|
1516
|
+
if (byteLength(held) + byteLength(content) > MAX_CHANNEL_BYTES) {
|
|
1517
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1518
|
+
}
|
|
1519
|
+
const buffered = held + content;
|
|
1520
|
+
const { emit, hold } = splitRestorable(buffered);
|
|
1521
|
+
delta.content = emit.length === 0 ? "" : restoreDisplayText(service, sessionID, emit);
|
|
1522
|
+
if (hold === "")
|
|
1523
|
+
deleteChannel(channel);
|
|
1524
|
+
else
|
|
1525
|
+
setChannel(channel, hold);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
// P1 (2026-10-06b): a terminal choice holding an unresolved tail
|
|
1529
|
+
// (split or never-completed placeholder) is degradation, not a
|
|
1530
|
+
// stream failure — emit the held tail literally, WARN, and clear
|
|
1531
|
+
// the channel so per-choice state stays bounded.
|
|
1532
|
+
if (terminal) {
|
|
1533
|
+
const held = channels.get(channel);
|
|
1534
|
+
if (held !== undefined) {
|
|
1535
|
+
if (isRecord(delta) && typeof delta.content === "string") {
|
|
1536
|
+
delta.content += held;
|
|
1537
|
+
}
|
|
1538
|
+
else if (isRecord(delta)) {
|
|
1539
|
+
delta.content = held;
|
|
1540
|
+
}
|
|
1541
|
+
else {
|
|
1542
|
+
choice.delta = { content: held };
|
|
1543
|
+
}
|
|
1544
|
+
warnDegradation("terminal stream event emitted an incomplete placeholder tail literally");
|
|
1545
|
+
deleteChannel(channel);
|
|
1546
|
+
}
|
|
1547
|
+
if (!terminalChannels.has(channel) && terminalChannels.size >= MAX_CHANNELS) {
|
|
1548
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1549
|
+
}
|
|
1550
|
+
terminalChannels.add(channel);
|
|
1551
|
+
}
|
|
1552
|
+
}
|
|
1553
|
+
// A reserved token outside intentional tool arguments is degradation
|
|
1554
|
+
// (P1, 2026-10-06b): re-emit literally with a WARN.
|
|
1555
|
+
if (strayTokenIn(chunk)) {
|
|
1556
|
+
warnDegradation("stream event carries an unplaceable placeholder; kept literal");
|
|
1557
|
+
}
|
|
1558
|
+
outputLines = emitPayload(JSON.stringify(chunk));
|
|
1559
|
+
}
|
|
1560
|
+
else {
|
|
1561
|
+
// Usage-only etc.: re-emit the original payload verbatim; an
|
|
1562
|
+
// unplaceable placeholder stays literal with a WARN (P1).
|
|
1563
|
+
if (strayTokenIn(chunk)) {
|
|
1564
|
+
warnDegradation("stream event carries an unplaceable placeholder; kept literal");
|
|
1565
|
+
}
|
|
1566
|
+
outputLines = emitPayload(joined);
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
const text = outputLines.join("\n");
|
|
1571
|
+
if (text.length === 0)
|
|
1572
|
+
return terminated ? "\n" : "";
|
|
1573
|
+
return terminated ? `${text}\n\n` : text;
|
|
1574
|
+
};
|
|
1575
|
+
return createRecoveringSseStream(reader, (lines, terminated) => {
|
|
1576
|
+
eventLines = lines;
|
|
1577
|
+
return { output: processEvent(terminated), holding: channels.size > 0 };
|
|
1578
|
+
}, () => { channels.clear(); terminalChannels.clear(); });
|
|
1579
|
+
}
|
|
1580
|
+
/**
|
|
1581
|
+
* Marks a field as display-restored assistant text. Per the literal-content
|
|
1582
|
+
* policy (spec §Mapping and restoration), an unknown or malformed marker
|
|
1583
|
+
* string that survives display restoration there is literal content — not a
|
|
1584
|
+
* stray — while identifiers, transport metadata, and tool arguments stay
|
|
1585
|
+
* strict everywhere else.
|
|
1586
|
+
*/
|
|
1587
|
+
function allowAnthropicField(fields, record, field) {
|
|
1588
|
+
const allowed = fields.get(record) ?? new Set();
|
|
1589
|
+
allowed.add(field);
|
|
1590
|
+
fields.set(record, allowed);
|
|
1591
|
+
}
|
|
1592
|
+
function anthropicStrayTokenIn(value, fields) {
|
|
1593
|
+
if (typeof value === "string") {
|
|
1594
|
+
return containsTokenPrefix(value);
|
|
1595
|
+
}
|
|
1596
|
+
if (value === null || typeof value !== "object")
|
|
1597
|
+
return false;
|
|
1598
|
+
if (Array.isArray(value)) {
|
|
1599
|
+
return value.some((item) => anthropicStrayTokenIn(item, fields));
|
|
1600
|
+
}
|
|
1601
|
+
const record = value;
|
|
1602
|
+
for (const key of Object.keys(record)) {
|
|
1603
|
+
if (containsTokenPrefix(key))
|
|
1604
|
+
return true;
|
|
1605
|
+
const value = record[key];
|
|
1606
|
+
// content[].text is restored in place before this check runs; a surviving
|
|
1607
|
+
// token there was intentionally left by restore failure handling.
|
|
1608
|
+
if (key === "content" && Array.isArray(value)) {
|
|
1609
|
+
for (const block of value) {
|
|
1610
|
+
if (!isRecord(block))
|
|
1611
|
+
return true;
|
|
1612
|
+
if (block.type === "tool_use") {
|
|
1613
|
+
if (typeof block.id === "string" && containsTokenPrefix(block.id))
|
|
1614
|
+
return true;
|
|
1615
|
+
continue; // input stays tokenized by design
|
|
1616
|
+
}
|
|
1617
|
+
if (anthropicStrayTokenIn(block, fields))
|
|
1618
|
+
return true;
|
|
1619
|
+
}
|
|
1620
|
+
continue;
|
|
1621
|
+
}
|
|
1622
|
+
if (fields?.get(record)?.has(key))
|
|
1623
|
+
continue;
|
|
1624
|
+
if (anthropicStrayTokenIn(value, fields))
|
|
1625
|
+
return true;
|
|
1626
|
+
}
|
|
1627
|
+
return false;
|
|
1628
|
+
}
|
|
1629
|
+
async function restoreAnthropicJsonResponse(service, sessionID, response) {
|
|
1630
|
+
const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
|
|
1631
|
+
if (raw.length === 0)
|
|
1632
|
+
return response;
|
|
1633
|
+
let body;
|
|
1634
|
+
try {
|
|
1635
|
+
body = JSON.parse(raw);
|
|
1636
|
+
}
|
|
1637
|
+
catch {
|
|
1638
|
+
if (containsTokenPrefix(raw))
|
|
1639
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1640
|
+
return response;
|
|
1641
|
+
}
|
|
1642
|
+
if (!isRecord(body)) {
|
|
1643
|
+
if (containsTokenPrefix(raw))
|
|
1644
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1645
|
+
return response;
|
|
1646
|
+
}
|
|
1647
|
+
if (body.content === undefined) {
|
|
1648
|
+
if (containsTokenPrefix(raw))
|
|
1649
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
1650
|
+
return response;
|
|
1651
|
+
}
|
|
1652
|
+
if (!Array.isArray(body.content))
|
|
1653
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1654
|
+
let changed = false;
|
|
1655
|
+
const fields = new WeakMap();
|
|
1656
|
+
for (const block of body.content) {
|
|
1657
|
+
if (!isRecord(block))
|
|
1658
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1659
|
+
if (block.type === "text") {
|
|
1660
|
+
if (typeof block.text !== "string")
|
|
1661
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1662
|
+
if (block.text.length > 0) {
|
|
1663
|
+
block.text = restoreDisplayText(service, sessionID, block.text);
|
|
1664
|
+
allowAnthropicField(fields, block, "text");
|
|
1665
|
+
changed = true;
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
// tool_use / other blocks: input stays tokenized until the typed tool gate.
|
|
1669
|
+
}
|
|
1670
|
+
if (anthropicStrayTokenIn(body, fields))
|
|
1671
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
1672
|
+
if (!changed)
|
|
1673
|
+
return response;
|
|
1674
|
+
const next = JSON.stringify(body);
|
|
1675
|
+
const headers = new Headers(response.headers);
|
|
1676
|
+
headers.delete("content-encoding");
|
|
1677
|
+
headers.set("content-length", String(byteLength(next)));
|
|
1678
|
+
return new Response(next, {
|
|
1679
|
+
status: response.status,
|
|
1680
|
+
statusText: response.statusText,
|
|
1681
|
+
headers,
|
|
1682
|
+
});
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* Restores an Anthropic Messages SSE stream. Channel hold buffers are keyed by
|
|
1686
|
+
* content-block index (tokens may split across content_block_delta events);
|
|
1687
|
+
* content_block_stop requires an empty channel and marks the index terminal;
|
|
1688
|
+
* message_stop requires every channel drained. input_json_delta is
|
|
1689
|
+
* deliberately untouched (tool arguments restore at the typed tool gate). All
|
|
1690
|
+
* framing/byte caps mirror the chat-completions stream.
|
|
1691
|
+
*/
|
|
1692
|
+
export function createAnthropicSseRestoreStream(service, sessionID, body) {
|
|
1693
|
+
const reader = body.getReader();
|
|
1694
|
+
const channels = new Map();
|
|
1695
|
+
const terminalBlocks = new Set();
|
|
1696
|
+
const allowedFields = new WeakMap();
|
|
1697
|
+
let totalChannelBytes = 0;
|
|
1698
|
+
let eventLines = [];
|
|
1699
|
+
const messageStopped = { value: false };
|
|
1700
|
+
const setChannel = (channel, hold) => {
|
|
1701
|
+
const previous = channels.get(channel) ?? "";
|
|
1702
|
+
totalChannelBytes += byteLength(hold) - byteLength(previous);
|
|
1703
|
+
if (totalChannelBytes > MAX_TOTAL_CHANNEL_BYTES)
|
|
1704
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1705
|
+
channels.set(channel, hold);
|
|
1706
|
+
};
|
|
1707
|
+
const deleteChannel = (channel) => {
|
|
1708
|
+
const previous = channels.get(channel);
|
|
1709
|
+
if (previous !== undefined)
|
|
1710
|
+
totalChannelBytes -= byteLength(previous);
|
|
1711
|
+
channels.delete(channel);
|
|
1712
|
+
};
|
|
1713
|
+
const processEvent = (terminated) => {
|
|
1714
|
+
const lines = eventLines;
|
|
1715
|
+
eventLines = [];
|
|
1716
|
+
const framing = [];
|
|
1717
|
+
const dataPayloads = [];
|
|
1718
|
+
for (const rawLine of lines) {
|
|
1719
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
1720
|
+
if (line.startsWith("data:")) {
|
|
1721
|
+
let payload = line.slice("data:".length);
|
|
1722
|
+
if (payload.startsWith(" "))
|
|
1723
|
+
payload = payload.slice(1);
|
|
1724
|
+
dataPayloads.push(payload);
|
|
1725
|
+
}
|
|
1726
|
+
else {
|
|
1727
|
+
framing.push(line);
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
const emitPayload = (payload) => framing.concat(payload.split("\n").map((line) => `data: ${line}`));
|
|
1731
|
+
let outputLines;
|
|
1732
|
+
if (dataPayloads.length === 0) {
|
|
1733
|
+
outputLines = framing;
|
|
1734
|
+
}
|
|
1735
|
+
else {
|
|
1736
|
+
const joined = dataPayloads.join("\n");
|
|
1737
|
+
let chunk;
|
|
1738
|
+
try {
|
|
1739
|
+
chunk = JSON.parse(joined);
|
|
1740
|
+
}
|
|
1741
|
+
catch {
|
|
1742
|
+
throw new Error(MALFORMED_STREAM);
|
|
1743
|
+
}
|
|
1744
|
+
if (!isRecord(chunk) || typeof chunk.type !== "string")
|
|
1745
|
+
throw new Error(MALFORMED_STREAM);
|
|
1746
|
+
if (chunk.type === "error")
|
|
1747
|
+
throw new Error(MALFORMED_STREAM);
|
|
1748
|
+
if (messageStopped.value)
|
|
1749
|
+
throw new Error(MALFORMED_STREAM);
|
|
1750
|
+
switch (chunk.type) {
|
|
1751
|
+
case "message_start": {
|
|
1752
|
+
const message = chunk.message;
|
|
1753
|
+
if (isRecord(message) && Array.isArray(message.content)) {
|
|
1754
|
+
for (const block of message.content) {
|
|
1755
|
+
if (!isRecord(block))
|
|
1756
|
+
throw new Error(MALFORMED_STREAM);
|
|
1757
|
+
if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
|
|
1758
|
+
block.text = restoreDisplayText(service, sessionID, block.text);
|
|
1759
|
+
allowAnthropicField(allowedFields, block, "text");
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
break;
|
|
1764
|
+
}
|
|
1765
|
+
case "content_block_start": {
|
|
1766
|
+
const index = chunk.index;
|
|
1767
|
+
if (typeof index !== "number" || !Number.isInteger(index))
|
|
1768
|
+
throw new Error(MALFORMED_STREAM);
|
|
1769
|
+
if (terminalBlocks.has(index))
|
|
1770
|
+
throw new Error(MALFORMED_STREAM);
|
|
1771
|
+
const block = chunk.content_block;
|
|
1772
|
+
if (!isRecord(block))
|
|
1773
|
+
throw new Error(MALFORMED_STREAM);
|
|
1774
|
+
if (block.type === "text" && typeof block.text === "string" && block.text.length > 0) {
|
|
1775
|
+
const held = channels.get(index) ?? "";
|
|
1776
|
+
const buffered = held + block.text;
|
|
1777
|
+
const { emit, hold } = splitRestorable(buffered);
|
|
1778
|
+
if (emit.length > 0)
|
|
1779
|
+
block.text = restoreDisplayText(service, sessionID, emit);
|
|
1780
|
+
else
|
|
1781
|
+
block.text = "";
|
|
1782
|
+
allowAnthropicField(allowedFields, block, "text");
|
|
1783
|
+
if (hold === "")
|
|
1784
|
+
deleteChannel(index);
|
|
1785
|
+
else
|
|
1786
|
+
setChannel(index, hold);
|
|
1787
|
+
}
|
|
1788
|
+
break;
|
|
1789
|
+
}
|
|
1790
|
+
case "content_block_delta": {
|
|
1791
|
+
const index = chunk.index;
|
|
1792
|
+
if (typeof index !== "number" || !Number.isInteger(index))
|
|
1793
|
+
throw new Error(MALFORMED_STREAM);
|
|
1794
|
+
if (terminalBlocks.has(index))
|
|
1795
|
+
throw new Error(MALFORMED_STREAM);
|
|
1796
|
+
const delta = chunk.delta;
|
|
1797
|
+
if (!isRecord(delta))
|
|
1798
|
+
throw new Error(MALFORMED_STREAM);
|
|
1799
|
+
if (delta.type === "text_delta") {
|
|
1800
|
+
if (typeof delta.text !== "string")
|
|
1801
|
+
throw new Error(MALFORMED_STREAM);
|
|
1802
|
+
const held = channels.get(index) ?? "";
|
|
1803
|
+
const buffered = held + delta.text;
|
|
1804
|
+
const { emit, hold } = splitRestorable(buffered);
|
|
1805
|
+
delta.text = emit.length === 0 ? "" : restoreDisplayText(service, sessionID, emit);
|
|
1806
|
+
allowAnthropicField(allowedFields, delta, "text");
|
|
1807
|
+
if (hold === "")
|
|
1808
|
+
deleteChannel(index);
|
|
1809
|
+
else
|
|
1810
|
+
setChannel(index, hold);
|
|
1811
|
+
}
|
|
1812
|
+
// input_json_delta / thinking_delta / signature_delta: untouched.
|
|
1813
|
+
break;
|
|
1814
|
+
}
|
|
1815
|
+
case "content_block_stop": {
|
|
1816
|
+
const index = chunk.index;
|
|
1817
|
+
if (typeof index !== "number" || !Number.isInteger(index))
|
|
1818
|
+
throw new Error(MALFORMED_STREAM);
|
|
1819
|
+
// The shared recovery loop replays undelivered originals on a
|
|
1820
|
+
// boundary with unresolved text; no literal prefix is discarded.
|
|
1821
|
+
if (channels.has(index))
|
|
1822
|
+
throw new Error(MALFORMED_STREAM);
|
|
1823
|
+
if (!terminalBlocks.has(index) && terminalBlocks.size >= MAX_CHANNELS) {
|
|
1824
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
1825
|
+
}
|
|
1826
|
+
terminalBlocks.add(index);
|
|
1827
|
+
break;
|
|
1828
|
+
}
|
|
1829
|
+
case "message_stop": {
|
|
1830
|
+
if (channels.size !== 0)
|
|
1831
|
+
throw new Error(MALFORMED_STREAM);
|
|
1832
|
+
messageStopped.value = true;
|
|
1833
|
+
break;
|
|
1834
|
+
}
|
|
1835
|
+
default:
|
|
1836
|
+
// ping / message_delta / unknown events carry no display text.
|
|
1837
|
+
break;
|
|
1838
|
+
}
|
|
1839
|
+
// P1 (2026-10-06b): an unplaceable placeholder is degradation — WARN,
|
|
1840
|
+
// emit literally; mapping loss never refuses response delivery.
|
|
1841
|
+
if (anthropicChunkStrayTokenIn(chunk, allowedFields)) {
|
|
1842
|
+
warnDegradation("anthropic stream event carries an unplaceable placeholder; kept literal");
|
|
1843
|
+
}
|
|
1844
|
+
outputLines = emitPayload(JSON.stringify(chunk));
|
|
1845
|
+
}
|
|
1846
|
+
const text = outputLines.join("\n");
|
|
1847
|
+
if (text.length === 0)
|
|
1848
|
+
return terminated ? "\n" : "";
|
|
1849
|
+
return terminated ? `${text}\n\n` : text;
|
|
1850
|
+
};
|
|
1851
|
+
return createRecoveringSseStream(reader, (lines, terminated) => {
|
|
1852
|
+
eventLines = lines;
|
|
1853
|
+
return { output: processEvent(terminated), holding: channels.size > 0 };
|
|
1854
|
+
}, () => { channels.clear(); terminalBlocks.clear(); });
|
|
1855
|
+
}
|
|
1856
|
+
/** Stray-token policy for one Anthropic SSE chunk: tokens may live only in
|
|
1857
|
+
* text channels (already restored above) and tool_use/input_json payloads. */
|
|
1858
|
+
function anthropicChunkStrayTokenIn(chunk, fields) {
|
|
1859
|
+
const check = (value, inToolPayload) => {
|
|
1860
|
+
if (typeof value === "string") {
|
|
1861
|
+
return !inToolPayload && containsTokenPrefix(value);
|
|
1862
|
+
}
|
|
1863
|
+
if (value === null || typeof value !== "object")
|
|
1864
|
+
return false;
|
|
1865
|
+
if (Array.isArray(value)) {
|
|
1866
|
+
return value.some((item) => check(item, inToolPayload));
|
|
1867
|
+
}
|
|
1868
|
+
const record = value;
|
|
1869
|
+
for (const key of Object.keys(record)) {
|
|
1870
|
+
if (containsTokenPrefix(key))
|
|
1871
|
+
return true;
|
|
1872
|
+
if (key === "partial_json" || key === "input") {
|
|
1873
|
+
continue; // tool-argument payloads stay tokenized by design
|
|
1874
|
+
}
|
|
1875
|
+
if (fields?.get(record)?.has(key))
|
|
1876
|
+
continue;
|
|
1877
|
+
if (check(record[key], inToolPayload))
|
|
1878
|
+
return true;
|
|
1879
|
+
}
|
|
1880
|
+
return false;
|
|
1881
|
+
};
|
|
1882
|
+
return check(chunk, false);
|
|
1883
|
+
}
|
|
1884
|
+
function restoreAnthropicSseResponse(service, sessionID, response) {
|
|
1885
|
+
if (response.body === null)
|
|
1886
|
+
return response;
|
|
1887
|
+
const headers = new Headers(response.headers);
|
|
1888
|
+
headers.delete("content-encoding");
|
|
1889
|
+
headers.delete("content-length");
|
|
1890
|
+
const stream = createAnthropicSseRestoreStream(service, sessionID, response.body);
|
|
1891
|
+
return new Response(stream, {
|
|
1892
|
+
status: response.status,
|
|
1893
|
+
statusText: response.statusText,
|
|
1894
|
+
headers,
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
/**
|
|
1898
|
+
* Restores assistant display text in an Anthropic Messages response. Error
|
|
1899
|
+
* bodies and unsupported content types pass through only when provably free
|
|
1900
|
+
* of reserved tokens; otherwise the response fails closed.
|
|
1901
|
+
*/
|
|
1902
|
+
export async function restoreAnthropicMessagesResponse(service, sessionID, response) {
|
|
1903
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
1904
|
+
const restorable = response.status >= 200 && response.status < 300;
|
|
1905
|
+
if (restorable && contentType.includes("application/json")) {
|
|
1906
|
+
return restoreAnthropicJsonResponse(service, sessionID, response);
|
|
1907
|
+
}
|
|
1908
|
+
if (restorable && contentType.includes("text/event-stream")) {
|
|
1909
|
+
return restoreAnthropicSseResponse(service, sessionID, response);
|
|
1910
|
+
}
|
|
1911
|
+
return passThroughIfTokenBearing(response);
|
|
1912
|
+
}
|
|
1913
|
+
/** Protocol dispatcher: restores a response using the SAME wire route the
|
|
1914
|
+
* masked request used (classified by request URL shape). */
|
|
1915
|
+
export async function restoreModelResponse(service, sessionID, request, response) {
|
|
1916
|
+
const route = classifyModelRoute(request.url);
|
|
1917
|
+
if (route === null)
|
|
1918
|
+
throw new Error(UNSUPPORTED_TRANSPORT);
|
|
1919
|
+
if (route === "anthropic-messages") {
|
|
1920
|
+
return restoreAnthropicMessagesResponse(service, sessionID, response);
|
|
1921
|
+
}
|
|
1922
|
+
if (route === "openai-responses") {
|
|
1923
|
+
return restoreResponsesResponse(service, sessionID, response);
|
|
1924
|
+
}
|
|
1925
|
+
return restoreChatCompletionsResponse(service, sessionID, response);
|
|
1926
|
+
}
|
|
1927
|
+
// ─── OpenAI Responses response restore ──────────────────────────────────────
|
|
1928
|
+
const RESPONSES_TEXT_PART_TYPES = new Set(["output_text", "input_text", "summary_text", "reasoning_text"]);
|
|
1929
|
+
export const RESPONSES_TEXT_DELTA_TYPES = new Set([
|
|
1930
|
+
"response.output_text.delta",
|
|
1931
|
+
"response.refusal.delta",
|
|
1932
|
+
"response.reasoning.delta",
|
|
1933
|
+
"response.reasoning_text.delta",
|
|
1934
|
+
"response.reasoning_summary_text.delta",
|
|
1935
|
+
]);
|
|
1936
|
+
export const RESPONSES_TEXT_DONE_TYPES = new Set([
|
|
1937
|
+
"response.output_text.done",
|
|
1938
|
+
"response.refusal.done",
|
|
1939
|
+
"response.reasoning.done",
|
|
1940
|
+
"response.reasoning_text.done",
|
|
1941
|
+
"response.reasoning_summary_text.done",
|
|
1942
|
+
]);
|
|
1943
|
+
function allowResponsesField(fields, record, field) {
|
|
1944
|
+
const allowed = fields.get(record) ?? new Set();
|
|
1945
|
+
allowed.add(field);
|
|
1946
|
+
fields.set(record, allowed);
|
|
1947
|
+
}
|
|
1948
|
+
function restoreResponsesPartText(service, sessionID, part, fields) {
|
|
1949
|
+
if (typeof part.type === "string" && RESPONSES_TEXT_PART_TYPES.has(part.type) && typeof part.text === "string") {
|
|
1950
|
+
part.text = restoreDisplayText(service, sessionID, part.text);
|
|
1951
|
+
allowResponsesField(fields, part, "text");
|
|
1952
|
+
return true;
|
|
1953
|
+
}
|
|
1954
|
+
if (part.type === "refusal" && typeof part.refusal === "string") {
|
|
1955
|
+
part.refusal = restoreDisplayText(service, sessionID, part.refusal);
|
|
1956
|
+
allowResponsesField(fields, part, "refusal");
|
|
1957
|
+
return true;
|
|
1958
|
+
}
|
|
1959
|
+
return false;
|
|
1960
|
+
}
|
|
1961
|
+
function restoreResponsesItemText(service, sessionID, item, fields) {
|
|
1962
|
+
if (item.type === "function_call" && typeof item.arguments === "string") {
|
|
1963
|
+
allowResponsesField(fields, item, "arguments");
|
|
1964
|
+
}
|
|
1965
|
+
if (item.type === "function_call_output" && typeof item.output === "string") {
|
|
1966
|
+
allowResponsesField(fields, item, "output");
|
|
1967
|
+
}
|
|
1968
|
+
let changed = false;
|
|
1969
|
+
const partFields = item.type === "message" ? ["content"] : item.type === "reasoning" ? ["content", "summary"] : [];
|
|
1970
|
+
for (const field of partFields) {
|
|
1971
|
+
const parts = item[field];
|
|
1972
|
+
if (!Array.isArray(parts))
|
|
1973
|
+
continue;
|
|
1974
|
+
for (const part of parts) {
|
|
1975
|
+
if (isRecord(part))
|
|
1976
|
+
changed = restoreResponsesPartText(service, sessionID, part, fields) || changed;
|
|
1977
|
+
}
|
|
1978
|
+
}
|
|
1979
|
+
return restoreResponsesPartText(service, sessionID, item, fields) || changed;
|
|
1980
|
+
}
|
|
1981
|
+
function responsesStrayTokenIn(value, fields) {
|
|
1982
|
+
if (typeof value === "string") {
|
|
1983
|
+
return containsTokenPrefix(value);
|
|
1984
|
+
}
|
|
1985
|
+
if (value === null || typeof value !== "object")
|
|
1986
|
+
return false;
|
|
1987
|
+
if (Array.isArray(value)) {
|
|
1988
|
+
return value.some((item) => responsesStrayTokenIn(item, fields));
|
|
1989
|
+
}
|
|
1990
|
+
const record = value;
|
|
1991
|
+
for (const key of Object.keys(record)) {
|
|
1992
|
+
if (containsTokenPrefix(key))
|
|
1993
|
+
return true;
|
|
1994
|
+
if (fields.get(record)?.has(key))
|
|
1995
|
+
continue;
|
|
1996
|
+
if (responsesStrayTokenIn(record[key], fields))
|
|
1997
|
+
return true;
|
|
1998
|
+
}
|
|
1999
|
+
return false;
|
|
2000
|
+
}
|
|
2001
|
+
/** Restore complete display fields of one Responses event (HTTP/WS share
|
|
2002
|
+
* the same part/item semantics). Delta buffering belongs to the transport;
|
|
2003
|
+
* function-call arguments and provider state are never restored here. */
|
|
2004
|
+
export function restoreResponsesEventDisplay(service, sessionID, chunk) {
|
|
2005
|
+
const fields = new WeakMap();
|
|
2006
|
+
const type = String(chunk.type);
|
|
2007
|
+
if (RESPONSES_TEXT_DELTA_TYPES.has(type)) {
|
|
2008
|
+
allowResponsesField(fields, chunk, "delta");
|
|
2009
|
+
}
|
|
2010
|
+
else if (RESPONSES_TEXT_DONE_TYPES.has(type)) {
|
|
2011
|
+
const field = type === "response.refusal.done" ? "refusal" : "text";
|
|
2012
|
+
if (typeof chunk[field] === "string") {
|
|
2013
|
+
chunk[field] = restoreDisplayText(service, sessionID, chunk[field]);
|
|
2014
|
+
allowResponsesField(fields, chunk, field);
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
else if (type === "response.function_call_arguments.delta" || type === "response.function_call_arguments.done") {
|
|
2018
|
+
allowResponsesField(fields, chunk, type.endsWith(".delta") ? "delta" : "arguments");
|
|
2019
|
+
}
|
|
2020
|
+
else if (type === "response.output_item.added" || type === "response.output_item.done") {
|
|
2021
|
+
if (isRecord(chunk.item))
|
|
2022
|
+
restoreResponsesItemText(service, sessionID, chunk.item, fields);
|
|
2023
|
+
}
|
|
2024
|
+
else if (type === "response.content_part.added" || type === "response.content_part.done" ||
|
|
2025
|
+
type === "response.reasoning_summary_part.added" || type === "response.reasoning_summary_part.done") {
|
|
2026
|
+
if (isRecord(chunk.part))
|
|
2027
|
+
restoreResponsesPartText(service, sessionID, chunk.part, fields);
|
|
2028
|
+
}
|
|
2029
|
+
else if (type === "response.created" || type === "response.in_progress" ||
|
|
2030
|
+
type === "response.completed" || type === "response.failed" || type === "response.incomplete") {
|
|
2031
|
+
const response = chunk.response;
|
|
2032
|
+
if (isRecord(response)) {
|
|
2033
|
+
if (typeof response.output_text === "string") {
|
|
2034
|
+
response.output_text = restoreDisplayText(service, sessionID, response.output_text);
|
|
2035
|
+
allowResponsesField(fields, response, "output_text");
|
|
2036
|
+
}
|
|
2037
|
+
if (Array.isArray(response.output)) {
|
|
2038
|
+
for (const item of response.output) {
|
|
2039
|
+
if (isRecord(item))
|
|
2040
|
+
restoreResponsesItemText(service, sessionID, item, fields);
|
|
2041
|
+
}
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
}
|
|
2045
|
+
if (responsesStrayTokenIn(chunk, fields))
|
|
2046
|
+
warnDegradation("responses frame carries an unplaceable placeholder; kept literal");
|
|
2047
|
+
}
|
|
2048
|
+
async function restoreResponsesJsonResponse(service, sessionID, response) {
|
|
2049
|
+
const raw = await readCappedText(response, MAX_BODY_BYTES, UNSUPPORTED_RESPONSE);
|
|
2050
|
+
if (raw.length === 0)
|
|
2051
|
+
return response;
|
|
2052
|
+
let body;
|
|
2053
|
+
try {
|
|
2054
|
+
body = JSON.parse(raw);
|
|
2055
|
+
}
|
|
2056
|
+
catch {
|
|
2057
|
+
if (containsTokenPrefix(raw))
|
|
2058
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
2059
|
+
return response;
|
|
2060
|
+
}
|
|
2061
|
+
if (!isRecord(body)) {
|
|
2062
|
+
if (containsTokenPrefix(raw))
|
|
2063
|
+
warnDegradation("response body carries an unplaceable placeholder; kept literal");
|
|
2064
|
+
return response;
|
|
2065
|
+
}
|
|
2066
|
+
const fields = new WeakMap();
|
|
2067
|
+
if (body.output_text !== undefined && typeof body.output_text === "string") {
|
|
2068
|
+
body.output_text = restoreDisplayText(service, sessionID, body.output_text);
|
|
2069
|
+
allowResponsesField(fields, body, "output_text");
|
|
2070
|
+
}
|
|
2071
|
+
if (Array.isArray(body.output)) {
|
|
2072
|
+
for (const item of body.output) {
|
|
2073
|
+
if (!isRecord(item))
|
|
2074
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
2075
|
+
restoreResponsesItemText(service, sessionID, item, fields);
|
|
2076
|
+
}
|
|
2077
|
+
}
|
|
2078
|
+
if (responsesStrayTokenIn(body, fields))
|
|
2079
|
+
throw new Error(UNSUPPORTED_RESPONSE);
|
|
2080
|
+
const next = JSON.stringify(body);
|
|
2081
|
+
const headers = new Headers(response.headers);
|
|
2082
|
+
headers.delete("content-encoding");
|
|
2083
|
+
headers.set("content-length", String(byteLength(next)));
|
|
2084
|
+
return new Response(next, { status: response.status, statusText: response.statusText, headers });
|
|
2085
|
+
}
|
|
2086
|
+
/**
|
|
2087
|
+
* Restores an OpenAI Responses SSE stream. Channels are keyed by item id (or
|
|
2088
|
+
* output index) for response.output_text.delta events; function_call_arguments
|
|
2089
|
+
* deltas are untouched (tool gate); the terminal response.completed/failed/
|
|
2090
|
+
* incomplete event requires drained channels, and no event may follow it.
|
|
2091
|
+
*/
|
|
2092
|
+
export function createResponsesSseRestoreStream(service, sessionID, body) {
|
|
2093
|
+
const reader = body.getReader();
|
|
2094
|
+
const channels = new Map();
|
|
2095
|
+
const emittedRawCounts = new Map();
|
|
2096
|
+
let totalChannelBytes = 0;
|
|
2097
|
+
let eventLines = [];
|
|
2098
|
+
const terminal = { value: false };
|
|
2099
|
+
const setChannel = (channel, hold) => {
|
|
2100
|
+
const previous = channels.get(channel) ?? "";
|
|
2101
|
+
totalChannelBytes += byteLength(hold) - byteLength(previous);
|
|
2102
|
+
if (totalChannelBytes > MAX_TOTAL_CHANNEL_BYTES)
|
|
2103
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
2104
|
+
channels.set(channel, hold);
|
|
2105
|
+
};
|
|
2106
|
+
const deleteChannel = (channel) => {
|
|
2107
|
+
const previous = channels.get(channel);
|
|
2108
|
+
if (previous !== undefined)
|
|
2109
|
+
totalChannelBytes -= byteLength(previous);
|
|
2110
|
+
channels.delete(channel);
|
|
2111
|
+
};
|
|
2112
|
+
const finishChannel = (key, fullText, chunk, kind) => {
|
|
2113
|
+
const held = channels.get(key);
|
|
2114
|
+
const offset = emittedRawCounts.get(key) ?? 0;
|
|
2115
|
+
emittedRawCounts.delete(key);
|
|
2116
|
+
if (held === undefined)
|
|
2117
|
+
return "";
|
|
2118
|
+
const remainder = fullText.slice(offset);
|
|
2119
|
+
if (offset > fullText.length || !remainder.startsWith(held))
|
|
2120
|
+
throw new Error(MALFORMED_STREAM);
|
|
2121
|
+
const delta = restoreDisplayText(service, sessionID, remainder);
|
|
2122
|
+
deleteChannel(key);
|
|
2123
|
+
if (delta.length === 0)
|
|
2124
|
+
return "";
|
|
2125
|
+
const event = {
|
|
2126
|
+
type: `${kind}.delta`,
|
|
2127
|
+
item_id: chunk.item_id,
|
|
2128
|
+
output_index: chunk.output_index,
|
|
2129
|
+
content_index: chunk.content_index,
|
|
2130
|
+
summary_index: chunk.summary_index,
|
|
2131
|
+
delta,
|
|
2132
|
+
};
|
|
2133
|
+
return `event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`;
|
|
2134
|
+
};
|
|
2135
|
+
const processEvent = (terminated) => {
|
|
2136
|
+
const lines = eventLines;
|
|
2137
|
+
eventLines = [];
|
|
2138
|
+
const framing = [];
|
|
2139
|
+
const dataPayloads = [];
|
|
2140
|
+
for (const rawLine of lines) {
|
|
2141
|
+
const line = rawLine.endsWith("\r") ? rawLine.slice(0, -1) : rawLine;
|
|
2142
|
+
if (line.startsWith("data:")) {
|
|
2143
|
+
let payload = line.slice("data:".length);
|
|
2144
|
+
if (payload.startsWith(" "))
|
|
2145
|
+
payload = payload.slice(1);
|
|
2146
|
+
dataPayloads.push(payload);
|
|
2147
|
+
}
|
|
2148
|
+
else {
|
|
2149
|
+
framing.push(line);
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
const emitPayload = (payload) => framing.concat(payload.split("\n").map((line) => `data: ${line}`));
|
|
2153
|
+
let outputLines;
|
|
2154
|
+
let additionalEvents = "";
|
|
2155
|
+
if (dataPayloads.length === 0) {
|
|
2156
|
+
outputLines = framing;
|
|
2157
|
+
}
|
|
2158
|
+
else {
|
|
2159
|
+
const joined = dataPayloads.join("\n");
|
|
2160
|
+
if (joined.trim() === "[DONE]") {
|
|
2161
|
+
if (channels.size !== 0)
|
|
2162
|
+
throw new Error(MALFORMED_STREAM);
|
|
2163
|
+
emittedRawCounts.clear();
|
|
2164
|
+
terminal.value = true;
|
|
2165
|
+
outputLines = emitPayload("[DONE]");
|
|
2166
|
+
}
|
|
2167
|
+
else {
|
|
2168
|
+
let chunk;
|
|
2169
|
+
try {
|
|
2170
|
+
chunk = JSON.parse(joined);
|
|
2171
|
+
}
|
|
2172
|
+
catch {
|
|
2173
|
+
throw new Error(MALFORMED_STREAM);
|
|
2174
|
+
}
|
|
2175
|
+
if (!isRecord(chunk) || typeof chunk.type !== "string")
|
|
2176
|
+
throw new Error(MALFORMED_STREAM);
|
|
2177
|
+
if (chunk.type === "error")
|
|
2178
|
+
throw new Error(MALFORMED_STREAM);
|
|
2179
|
+
if (terminal.value)
|
|
2180
|
+
throw new Error(MALFORMED_STREAM);
|
|
2181
|
+
const eventType = chunk.type;
|
|
2182
|
+
const fields = new WeakMap();
|
|
2183
|
+
const channelKey = (kind = eventType.replace(/\.(?:delta|done)$/, "")) => {
|
|
2184
|
+
const item = chunk.item_id ?? chunk.id ?? chunk.output_index;
|
|
2185
|
+
const identity = typeof item === "string" || typeof item === "number" ? item : "0";
|
|
2186
|
+
return JSON.stringify([kind, identity, chunk.content_index ?? chunk.summary_index ?? 0]);
|
|
2187
|
+
};
|
|
2188
|
+
if (RESPONSES_TEXT_DELTA_TYPES.has(eventType)) {
|
|
2189
|
+
if (typeof chunk.delta !== "string")
|
|
2190
|
+
throw new Error(MALFORMED_STREAM);
|
|
2191
|
+
const key = channelKey();
|
|
2192
|
+
if ((!emittedRawCounts.has(key) && emittedRawCounts.size >= MAX_CHANNELS) || byteLength(key) > MAX_CHANNEL_BYTES) {
|
|
2193
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
2194
|
+
}
|
|
2195
|
+
const held = channels.get(key) ?? "";
|
|
2196
|
+
if (byteLength(held) + byteLength(chunk.delta) > MAX_CHANNEL_BYTES) {
|
|
2197
|
+
throw new Error(STREAM_BUFFER_LIMIT);
|
|
2198
|
+
}
|
|
2199
|
+
const buffered = held + chunk.delta;
|
|
2200
|
+
const { emit, hold } = splitRestorable(buffered);
|
|
2201
|
+
emittedRawCounts.set(key, (emittedRawCounts.get(key) ?? 0) + emit.length);
|
|
2202
|
+
chunk.delta = emit.length === 0 ? "" : restoreDisplayText(service, sessionID, emit);
|
|
2203
|
+
allowResponsesField(fields, chunk, "delta");
|
|
2204
|
+
if (hold === "")
|
|
2205
|
+
deleteChannel(key);
|
|
2206
|
+
else
|
|
2207
|
+
setChannel(key, hold);
|
|
2208
|
+
}
|
|
2209
|
+
else if (RESPONSES_TEXT_DONE_TYPES.has(eventType)) {
|
|
2210
|
+
const field = eventType === "response.refusal.done" ? "refusal" : "text";
|
|
2211
|
+
if (chunk[field] !== undefined) {
|
|
2212
|
+
if (typeof chunk[field] !== "string")
|
|
2213
|
+
throw new Error(MALFORMED_STREAM);
|
|
2214
|
+
additionalEvents += finishChannel(channelKey(), chunk[field], chunk, eventType.replace(/\.done$/, ""));
|
|
2215
|
+
chunk[field] = restoreDisplayText(service, sessionID, chunk[field]);
|
|
2216
|
+
allowResponsesField(fields, chunk, field);
|
|
2217
|
+
}
|
|
2218
|
+
else if (channels.has(channelKey())) {
|
|
2219
|
+
throw new Error(MALFORMED_STREAM);
|
|
2220
|
+
}
|
|
2221
|
+
else {
|
|
2222
|
+
emittedRawCounts.delete(channelKey());
|
|
2223
|
+
}
|
|
2224
|
+
}
|
|
2225
|
+
else if (eventType === "response.content_part.added" ||
|
|
2226
|
+
eventType === "response.content_part.done" ||
|
|
2227
|
+
eventType === "response.reasoning_summary_part.added" ||
|
|
2228
|
+
eventType === "response.reasoning_summary_part.done") {
|
|
2229
|
+
const part = chunk.part;
|
|
2230
|
+
if (isRecord(part)) {
|
|
2231
|
+
const completeText = part.type === "refusal" ? part.refusal : part.text;
|
|
2232
|
+
if (restoreResponsesPartText(service, sessionID, part, fields) && eventType.endsWith(".done") && typeof completeText === "string") {
|
|
2233
|
+
const kind = part.type === "summary_text" ? "reasoning_summary_text" : String(part.type);
|
|
2234
|
+
additionalEvents += finishChannel(channelKey(`response.${kind}`), completeText, chunk, `response.${kind}`);
|
|
2235
|
+
}
|
|
2236
|
+
}
|
|
2237
|
+
}
|
|
2238
|
+
else if (eventType === "response.output_item.added" || eventType === "response.output_item.done") {
|
|
2239
|
+
const item = chunk.item;
|
|
2240
|
+
if (isRecord(item)) {
|
|
2241
|
+
restoreResponsesItemText(service, sessionID, item, fields);
|
|
2242
|
+
if (eventType === "response.output_item.done") {
|
|
2243
|
+
for (const key of emittedRawCounts.keys()) {
|
|
2244
|
+
if (JSON.parse(key)[1] === item.id && !channels.has(key))
|
|
2245
|
+
emittedRawCounts.delete(key);
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
}
|
|
2250
|
+
else if (eventType === "response.completed" ||
|
|
2251
|
+
eventType === "response.failed" ||
|
|
2252
|
+
eventType === "response.incomplete") {
|
|
2253
|
+
if (channels.size !== 0)
|
|
2254
|
+
throw new Error(MALFORMED_STREAM);
|
|
2255
|
+
emittedRawCounts.clear();
|
|
2256
|
+
terminal.value = true;
|
|
2257
|
+
const response = chunk.response;
|
|
2258
|
+
if (isRecord(response)) {
|
|
2259
|
+
if (typeof response.output_text === "string") {
|
|
2260
|
+
response.output_text = restoreDisplayText(service, sessionID, response.output_text);
|
|
2261
|
+
allowResponsesField(fields, response, "output_text");
|
|
2262
|
+
}
|
|
2263
|
+
if (Array.isArray(response.output)) {
|
|
2264
|
+
for (const item of response.output) {
|
|
2265
|
+
if (isRecord(item))
|
|
2266
|
+
restoreResponsesItemText(service, sessionID, item, fields);
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
else if (eventType === "response.function_call_arguments.delta" || eventType === "response.function_call_arguments.done") {
|
|
2272
|
+
const field = eventType.endsWith(".delta") ? "delta" : "arguments";
|
|
2273
|
+
if (typeof chunk[field] === "string")
|
|
2274
|
+
allowResponsesField(fields, chunk, field);
|
|
2275
|
+
}
|
|
2276
|
+
// P1 (2026-10-06b): an unplaceable placeholder is degradation — WARN
|
|
2277
|
+
// and emit literally; mapping loss never refuses response delivery.
|
|
2278
|
+
if (responsesStrayTokenIn(chunk, fields)) {
|
|
2279
|
+
warnDegradation("responses stream event carries an unplaceable placeholder; kept literal");
|
|
2280
|
+
}
|
|
2281
|
+
outputLines = emitPayload(JSON.stringify(chunk));
|
|
2282
|
+
}
|
|
2283
|
+
}
|
|
2284
|
+
const text = outputLines.join("\n");
|
|
2285
|
+
if (text.length === 0)
|
|
2286
|
+
return terminated ? "\n" : "";
|
|
2287
|
+
return additionalEvents + (terminated ? `${text}\n\n` : text);
|
|
2288
|
+
};
|
|
2289
|
+
return createRecoveringSseStream(reader, (lines, terminated) => {
|
|
2290
|
+
eventLines = lines;
|
|
2291
|
+
return { output: processEvent(terminated), holding: channels.size > 0 };
|
|
2292
|
+
}, () => { channels.clear(); emittedRawCounts.clear(); });
|
|
2293
|
+
}
|
|
2294
|
+
/**
|
|
2295
|
+
* Restores assistant display text in an OpenAI Responses response; error
|
|
2296
|
+
* bodies and unsupported content types pass through only when provably free
|
|
2297
|
+
* of reserved tokens.
|
|
2298
|
+
*/
|
|
2299
|
+
export async function restoreResponsesResponse(service, sessionID, response) {
|
|
2300
|
+
const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
|
|
2301
|
+
const restorable = response.status >= 200 && response.status < 300;
|
|
2302
|
+
if (restorable && contentType.includes("application/json")) {
|
|
2303
|
+
return restoreResponsesJsonResponse(service, sessionID, response);
|
|
2304
|
+
}
|
|
2305
|
+
if (restorable && contentType.includes("text/event-stream")) {
|
|
2306
|
+
if (response.body === null)
|
|
2307
|
+
return response;
|
|
2308
|
+
const headers = new Headers(response.headers);
|
|
2309
|
+
headers.delete("content-encoding");
|
|
2310
|
+
headers.delete("content-length");
|
|
2311
|
+
const stream = createResponsesSseRestoreStream(service, sessionID, response.body);
|
|
2312
|
+
return new Response(stream, { status: response.status, statusText: response.statusText, headers });
|
|
2313
|
+
}
|
|
2314
|
+
return passThroughIfTokenBearing(response);
|
|
2315
|
+
}
|