dsh-lcx-codex 0.6.0-pre.1 → 0.6.0-pre.2
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/README.md +9 -9
- package/THIRD_PARTY_NOTICES.md +3 -2
- package/lib/abort-error.js +12 -1
- package/lib/client.js +73 -39
- package/lib/compact-v2.js +16 -56
- package/lib/defaults.js +15 -0
- package/lib/dsh-compat.js +15 -76
- package/lib/dsh-responses.js +70 -75
- package/lib/grok-native-search.js +1 -3
- package/lib/index.js +132 -55
- package/lib/model-catalog.js +46 -0
- package/lib/native-checkpoint.js +20 -183
- package/lib/pi-responses-runtime.js +142 -48
- package/lib/provider-headers.js +31 -0
- package/lib/responses-request.js +4 -12
- package/lib/responses-stream.js +115 -214
- package/lib/route.js +205 -87
- package/lib/search-accounting.js +1 -16
- package/lib/token-budget.js +6 -41
- package/lib/tool-surface.js +13 -14
- package/lib/transport.js +89 -107
- package/lib/types/client/search-media.d.ts +0 -2
- package/lib/util.js +21 -0
- package/lib/web-run-output.js +0 -3
- package/lib/web-search-alpha.js +22 -27
- package/lib/web-search-capability.js +1 -3
- package/lib/web-search-hosted.js +2 -2
- package/lib/web-search-ref-store.js +1 -3
- package/package.json +3 -3
- package/lib/pi086-responses-allowlist.js +0 -131
package/lib/dsh-responses.js
CHANGED
|
@@ -1,17 +1,15 @@
|
|
|
1
1
|
import { IMAGE_OFFLOAD_REQUIRED_CODE, LlmError, offloadedImageText, projectOffloadedImages, requiredImageOffload, requestImageHandleText, resolveImageAttachmentAccess, } from "@deepseek-ai/dsh-llm";
|
|
2
2
|
import { requestImageDimensions } from "@deepseek-ai/dsh-attachment";
|
|
3
|
-
import { convertResponsesMessages, convertResponsesTools, createGrammarToolInputProperties,
|
|
4
|
-
import {
|
|
3
|
+
import { convertResponsesMessages, convertResponsesTools, createGrammarToolInputProperties, normalizeContext, } from "./pi-responses-runtime.js";
|
|
4
|
+
import { resolveCatalogModel } from "./model-catalog.js";
|
|
5
5
|
import { withoutDeferLoading } from "./tool-surface.js";
|
|
6
|
+
import { isRecord, codedError, positiveSafeInteger } from "./util.js";
|
|
6
7
|
const DEFAULT_MAX_REQUEST_IMAGE_BYTES = 20 * 1024 * 1024;
|
|
7
8
|
const DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET = 2048 * 2048;
|
|
8
9
|
const DEFAULT_REQUEST_IMAGE_MAX_BYTES = 1024 * 1024;
|
|
9
10
|
export { DEFAULT_MAX_REQUEST_IMAGE_BYTES, DEFAULT_REQUEST_IMAGE_PIXEL_BUDGET, DEFAULT_REQUEST_IMAGE_MAX_BYTES, };
|
|
10
|
-
function isObject(value) {
|
|
11
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12
|
-
}
|
|
13
11
|
function isResponseInputItem(value) {
|
|
14
|
-
if (!
|
|
12
|
+
if (!isRecord(value))
|
|
15
13
|
return false;
|
|
16
14
|
if (value.type === "compaction")
|
|
17
15
|
return typeof value.encrypted_content === "string";
|
|
@@ -31,7 +29,7 @@ function isResponseInputItem(value) {
|
|
|
31
29
|
}
|
|
32
30
|
export function responseInputItems(value) {
|
|
33
31
|
if (!Array.isArray(value) || !value.every(isResponseInputItem))
|
|
34
|
-
throw
|
|
32
|
+
throw codedError("native checkpoint contains an unsupported Responses input item", "LCX_COMPACT_INVALID_RESPONSE");
|
|
35
33
|
return value;
|
|
36
34
|
}
|
|
37
35
|
function asArray(value) {
|
|
@@ -40,18 +38,8 @@ function asArray(value) {
|
|
|
40
38
|
function stringValue(value, fallback = "") {
|
|
41
39
|
return typeof value === "string" ? value : fallback;
|
|
42
40
|
}
|
|
43
|
-
function positiveSafeInteger(value, fallback) {
|
|
44
|
-
return Number.isSafeInteger(value) && value > 0
|
|
45
|
-
? value
|
|
46
|
-
: fallback;
|
|
47
|
-
}
|
|
48
|
-
function error(message, code) {
|
|
49
|
-
const value = new Error(message);
|
|
50
|
-
value.code = code;
|
|
51
|
-
return value;
|
|
52
|
-
}
|
|
53
41
|
function errorCode(value) {
|
|
54
|
-
return
|
|
42
|
+
return isRecord(value) && typeof value.code === "string" ? value.code : undefined;
|
|
55
43
|
}
|
|
56
44
|
function errorMessage(value) {
|
|
57
45
|
return value instanceof Error ? value.message : String(value);
|
|
@@ -65,7 +53,7 @@ function attachmentServices(store) {
|
|
|
65
53
|
};
|
|
66
54
|
}
|
|
67
55
|
function hasImageAttachment(value) {
|
|
68
|
-
return
|
|
56
|
+
return isRecord(value) && typeof value.attachmentId === "string" && typeof value.bytes === "number";
|
|
69
57
|
}
|
|
70
58
|
function imageAccess(ctx, attachments, ref) {
|
|
71
59
|
const mapper = ctx?.fs
|
|
@@ -81,7 +69,7 @@ function imageAccess(ctx, attachments, ref) {
|
|
|
81
69
|
export async function resolveRouteModelFacts(ctx, route, signal) {
|
|
82
70
|
const llm = ctx?.llm;
|
|
83
71
|
if (llm === undefined)
|
|
84
|
-
return { imageSupport: "unknown", systemPromptUpdate: undefined, toolUpdate: undefined, reasoning: undefined, resolved: false };
|
|
72
|
+
return { imageSupport: "unknown", systemPromptUpdate: undefined, toolUpdate: undefined, reasoning: undefined, contextWindow: undefined, resolved: false };
|
|
85
73
|
try {
|
|
86
74
|
const info = await llm.resolveModelInfo(stringValue(route.provider), stringValue(route.model), signal);
|
|
87
75
|
const modalities = info.inputModalities;
|
|
@@ -96,34 +84,48 @@ export async function resolveRouteModelFacts(ctx, route, signal) {
|
|
|
96
84
|
reasoning: info.reasoning === undefined
|
|
97
85
|
? undefined
|
|
98
86
|
: { efforts: info.reasoning.efforts.map((effort) => String(effort.id)) },
|
|
87
|
+
contextWindow: positiveSafeInteger(info.context?.contextWindow, 0) || undefined,
|
|
99
88
|
resolved: true,
|
|
100
89
|
};
|
|
101
90
|
}
|
|
102
91
|
catch {
|
|
103
92
|
// `resolved: false` tells callers the mode is unknown rather than known-absent, so they can refuse
|
|
104
93
|
// to downgrade history that only an in-history route may legitimately contain.
|
|
105
|
-
return { imageSupport: "unknown", systemPromptUpdate: undefined, toolUpdate: undefined, reasoning: undefined, resolved: false };
|
|
94
|
+
return { imageSupport: "unknown", systemPromptUpdate: undefined, toolUpdate: undefined, reasoning: undefined, contextWindow: undefined, resolved: false };
|
|
106
95
|
}
|
|
107
96
|
}
|
|
108
|
-
|
|
109
|
-
|
|
97
|
+
/**
|
|
98
|
+
* The model facts a route serializes and sends with, laid over the bundled catalog descriptor. What DSH
|
|
99
|
+
* reported for the exact routed model (context window; on a GPT route also the reasoning capability) wins
|
|
100
|
+
* over the catalog entry, and on a GPT route a profile's declared `reasoningEfforts` (wire mapping, or `false`
|
|
101
|
+
* for a non-reasoning model) wins over both. A GPT model with no catalog entry follows what DSH itself
|
|
102
|
+
* resolved for it instead of being assumed to reason. A Grok route carries its reasoning projection
|
|
103
|
+
* separately (`modelDefaults` / `modelControls`), so only the context window is applied there.
|
|
104
|
+
*/
|
|
105
|
+
export function routeModelOverride(routeConfig, facts, grok) {
|
|
106
|
+
const contextWindow = facts.resolved && facts.contextWindow !== undefined ? { contextWindow: facts.contextWindow } : {};
|
|
107
|
+
if (grok)
|
|
108
|
+
return Object.keys(contextWindow).length > 0 ? contextWindow : undefined;
|
|
109
|
+
if (!facts.resolved)
|
|
110
|
+
return routeConfig.modelControls === undefined ? undefined : { ...routeConfig.modelControls };
|
|
111
|
+
return { reasoning: facts.reasoning !== undefined, ...contextWindow, ...routeConfig.modelControls };
|
|
110
112
|
}
|
|
111
113
|
function attachmentResolver(ctx, options, requestImages) {
|
|
112
114
|
const attachments = attachmentServices(ctx?.attachments);
|
|
113
115
|
return async (block, signal) => {
|
|
114
116
|
if (attachments === undefined)
|
|
115
|
-
throw
|
|
117
|
+
throw codedError("LCX requires the DSH request-image attachment API", "LCX_COMPACT_IMAGE_API_UNAVAILABLE");
|
|
116
118
|
const request = requestImages === undefined
|
|
117
119
|
? await attachments.store.readImageRequest(block.attachment, { ...requestImageDimensions(block.attachment.width, block.attachment.height, options.requestImagePixelBudget), maxBytes: options.requestImageMaxBytes }, signal)
|
|
118
120
|
: requestImages.get(String(block.attachment.attachmentId));
|
|
119
121
|
if (request === undefined)
|
|
120
|
-
throw
|
|
122
|
+
throw codedError("DSH attachment returned no request-image bytes", "LCX_COMPACT_IMAGE_UNAVAILABLE");
|
|
121
123
|
const data = request.data;
|
|
122
124
|
const mediaType = request.mediaType ?? block.attachment.mediaType;
|
|
123
125
|
if (!(data instanceof Uint8Array) && !Buffer.isBuffer(data))
|
|
124
|
-
throw
|
|
126
|
+
throw codedError("DSH attachment returned no request-image bytes", "LCX_COMPACT_IMAGE_UNAVAILABLE");
|
|
125
127
|
if (typeof mediaType !== "string" || !mediaType.startsWith("image/"))
|
|
126
|
-
throw
|
|
128
|
+
throw codedError("DSH attachment returned an invalid request-image media type", "LCX_COMPACT_IMAGE_UNAVAILABLE");
|
|
127
129
|
return {
|
|
128
130
|
data: Buffer.from(data),
|
|
129
131
|
mediaType,
|
|
@@ -138,7 +140,7 @@ async function imagePart(block, ctx, options, imageMap, requestImages) {
|
|
|
138
140
|
return { type: "input_text", text: "[image omitted because the target model does not support image input]" };
|
|
139
141
|
const image = await attachmentResolver(ctx, options, requestImages)(block, options.signal);
|
|
140
142
|
if (Math.ceil(image.data.byteLength / 3) * 4 > options.maxRequestImageBytes)
|
|
141
|
-
throw
|
|
143
|
+
throw codedError("one image exceeds the configured LCX request image bound", "LCX_COMPACT_IMAGE_TOO_LARGE");
|
|
142
144
|
const imageUrl = `data:${image.mediaType};base64,${image.data.toString("base64")}`;
|
|
143
145
|
imageMap.set(imageUrl, structuredClone(image.ref));
|
|
144
146
|
return { type: "input_image", detail: "auto", image_url: imageUrl };
|
|
@@ -148,7 +150,7 @@ async function piImageParts(block, ctx, options, imageMap, requestImages) {
|
|
|
148
150
|
return [{ type: "text", text: "[image omitted because the target model does not support image input]" }];
|
|
149
151
|
const image = await attachmentResolver(ctx, options, requestImages)(block, options.signal);
|
|
150
152
|
if (Math.ceil(image.data.byteLength / 3) * 4 > options.maxRequestImageBytes)
|
|
151
|
-
throw
|
|
153
|
+
throw codedError("one image exceeds the configured LCX request image bound", "LCX_COMPACT_IMAGE_TOO_LARGE");
|
|
152
154
|
const data = image.data.toString("base64");
|
|
153
155
|
imageMap.set(`data:${image.mediaType};base64,${data}`, structuredClone(image.ref));
|
|
154
156
|
return [
|
|
@@ -157,13 +159,13 @@ async function piImageParts(block, ctx, options, imageMap, requestImages) {
|
|
|
157
159
|
];
|
|
158
160
|
}
|
|
159
161
|
function parseArguments(value) {
|
|
160
|
-
if (
|
|
162
|
+
if (isRecord(value))
|
|
161
163
|
return structuredClone(value);
|
|
162
164
|
if (typeof value !== "string")
|
|
163
165
|
return {};
|
|
164
166
|
try {
|
|
165
167
|
const parsed = JSON.parse(value);
|
|
166
|
-
return
|
|
168
|
+
return isRecord(parsed) ? parsed : {};
|
|
167
169
|
}
|
|
168
170
|
catch {
|
|
169
171
|
return {};
|
|
@@ -173,10 +175,10 @@ function emptyUsage() {
|
|
|
173
175
|
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
|
|
174
176
|
}
|
|
175
177
|
function invalidReplay(message) {
|
|
176
|
-
return
|
|
178
|
+
return codedError(`invalid pi-ai replay state: ${message}`, "LCX_COMPACT_INVALID_REPLAY_STATE");
|
|
177
179
|
}
|
|
178
180
|
function unsupportedContent(type) {
|
|
179
|
-
return
|
|
181
|
+
return codedError(`LCX Compact cannot safely serialize DSH message content type: ${String(type)}`, "LCX_CHECKPOINT_PORTABLE_UNSUPPORTED_CONTENT");
|
|
180
182
|
}
|
|
181
183
|
function replayBlockType(type) {
|
|
182
184
|
return type === "text" || type === "reasoning" || type === "tool-call" ? type : undefined;
|
|
@@ -186,7 +188,7 @@ function replayTextPhase(signature) {
|
|
|
186
188
|
return undefined;
|
|
187
189
|
try {
|
|
188
190
|
const parsed = JSON.parse(signature);
|
|
189
|
-
if (!
|
|
191
|
+
if (!isRecord(parsed) || parsed.v !== 1 || typeof parsed.id !== "string")
|
|
190
192
|
return undefined;
|
|
191
193
|
return parsed.phase === "commentary" || parsed.phase === "final_answer"
|
|
192
194
|
? parsed.phase
|
|
@@ -218,14 +220,14 @@ function restorePortableAssistantPhases(input, messages, target) {
|
|
|
218
220
|
const output = structuredClone(input);
|
|
219
221
|
let slotIndex = 0;
|
|
220
222
|
for (const [index, candidate] of output.entries()) {
|
|
221
|
-
if (!
|
|
223
|
+
if (!isRecord(candidate) || candidate.type !== "message" || candidate.role !== "assistant" ||
|
|
222
224
|
!Array.isArray(candidate.content))
|
|
223
225
|
continue;
|
|
224
226
|
const slot = slots[slotIndex++];
|
|
225
227
|
if (slot?.phase === undefined)
|
|
226
228
|
continue;
|
|
227
229
|
const text = candidate.content
|
|
228
|
-
.map((part) =>
|
|
230
|
+
.map((part) => isRecord(part) && part.type === "output_text" ? String(part.text ?? "") : "")
|
|
229
231
|
.join("");
|
|
230
232
|
if (text === slot.text)
|
|
231
233
|
output[index] = { ...candidate, phase: slot.phase };
|
|
@@ -233,10 +235,10 @@ function restorePortableAssistantPhases(input, messages, target) {
|
|
|
233
235
|
return output;
|
|
234
236
|
}
|
|
235
237
|
export function readDshPiReplayState(value) {
|
|
236
|
-
if (!
|
|
238
|
+
if (!isRecord(value))
|
|
237
239
|
throw invalidReplay("expected a replay envelope");
|
|
238
240
|
const responseValue = value.response;
|
|
239
|
-
if (!
|
|
241
|
+
if (!isRecord(responseValue) || responseValue.kind !== "pi-ai" || responseValue.version !== 2)
|
|
240
242
|
throw invalidReplay("expected a pi-ai version 2 response object");
|
|
241
243
|
const required = ["api", "provider", "model"];
|
|
242
244
|
for (const key of required)
|
|
@@ -251,7 +253,7 @@ export function readDshPiReplayState(value) {
|
|
|
251
253
|
if (!Array.isArray(value.blocks))
|
|
252
254
|
throw invalidReplay("blocks must be an array");
|
|
253
255
|
const blocks = value.blocks.map((block, index) => {
|
|
254
|
-
if (!
|
|
256
|
+
if (!isRecord(block) || replayBlockType(block.type) === undefined)
|
|
255
257
|
throw invalidReplay(`block ${index} has an unknown type`);
|
|
256
258
|
for (const signature of ["textSignature", "thinkingSignature", "thoughtSignature", "namespace"])
|
|
257
259
|
if (block[signature] !== undefined && typeof block[signature] !== "string")
|
|
@@ -424,7 +426,7 @@ async function dshToPiMessages(messages, ctx, options, imageMap, requestImages)
|
|
|
424
426
|
throw unsupportedContent(block.type);
|
|
425
427
|
const tool = options.anchoredTools.find((candidate) => candidate.name === block.toolName);
|
|
426
428
|
if (tool === undefined)
|
|
427
|
-
throw
|
|
429
|
+
throw codedError(`LCX tool update references undeclared tool "${block.toolName}"`, "LCX_RESPONSES_INVALID_INPUT");
|
|
428
430
|
toolsAdded.push(tool);
|
|
429
431
|
}
|
|
430
432
|
if (toolsAdded.length > 0)
|
|
@@ -468,24 +470,17 @@ async function dshToPiMessages(messages, ctx, options, imageMap, requestImages)
|
|
|
468
470
|
return result;
|
|
469
471
|
}
|
|
470
472
|
function builtinResponsesModel(provider, modelId) {
|
|
471
|
-
//
|
|
472
|
-
|
|
473
|
-
return undefined;
|
|
474
|
-
try {
|
|
475
|
-
return getBuiltinModels(provider).find((model) => model.id === modelId && model.api === "openai-responses");
|
|
476
|
-
}
|
|
477
|
-
catch {
|
|
478
|
-
return undefined;
|
|
479
|
-
}
|
|
473
|
+
// The exact bundled catalog entry (see `resolveCatalogModel`): the same descriptor the route resolution reads.
|
|
474
|
+
return resolveCatalogModel(provider, modelId).descriptor;
|
|
480
475
|
}
|
|
481
476
|
export function resolvePiResponsesModel(options) {
|
|
482
|
-
const route =
|
|
483
|
-
const explicit =
|
|
477
|
+
const route = isRecord(options.route) ? options.route : {};
|
|
478
|
+
const explicit = isRecord(options.model) ? options.model : {};
|
|
484
479
|
const provider = stringValue(explicit.provider, stringValue(route.provider, "dsh-lcx-codex"));
|
|
485
480
|
const id = stringValue(explicit.id, stringValue(route.model, "unknown"));
|
|
486
481
|
const builtin = builtinResponsesModel(provider, id);
|
|
487
|
-
const builtinRecord =
|
|
488
|
-
const compat = { ...(
|
|
482
|
+
const builtinRecord = isRecord(builtin) ? builtin : {};
|
|
483
|
+
const compat = { ...(isRecord(builtinRecord.compat) ? builtinRecord.compat : {}), ...(isRecord(options.responsesCompat) ? options.responsesCompat : {}), ...(isRecord(explicit.compat) ? explicit.compat : {}) };
|
|
489
484
|
const imageSupport = options.imageSupport === "supported" || options.imageSupport === "unsupported" ? options.imageSupport : "unknown";
|
|
490
485
|
const input = imageSupport === "supported" ? ["text", "image"] : imageSupport === "unsupported" ? ["text"] : Array.isArray(explicit.input) ? explicit.input : Array.isArray(builtinRecord.input) ? builtinRecord.input : ["text"];
|
|
491
486
|
return { ...builtinRecord, ...explicit, id, name: stringValue(explicit.name, stringValue(builtinRecord.name, id)), api: "openai-responses", provider, baseUrl: stringValue(explicit.baseUrl, stringValue(route.baseURL, stringValue(builtinRecord.baseUrl))), reasoning: typeof explicit.reasoning === "boolean" ? explicit.reasoning : typeof builtinRecord.reasoning === "boolean" ? builtinRecord.reasoning : true, input, cost: explicit.cost ?? builtinRecord.cost ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: positiveSafeInteger(explicit.contextWindow ?? builtinRecord.contextWindow, 262144), maxTokens: positiveSafeInteger(explicit.maxTokens ?? builtinRecord.maxTokens, 32768), ...(Object.keys(compat).length > 0 ? { compat } : {}) };
|
|
@@ -493,7 +488,7 @@ export function resolvePiResponsesModel(options) {
|
|
|
493
488
|
export async function serializeDshMessages(messages, ctx, options = {}) {
|
|
494
489
|
const anchored = options.toolUpdate === "addition-only";
|
|
495
490
|
if (anchored && options.systemPromptUpdate !== "in-history")
|
|
496
|
-
throw
|
|
491
|
+
throw codedError("LCX addition-only tool updates require an in-history route", "LCX_RESPONSES_INVALID_INPUT");
|
|
497
492
|
for (const message of messages) {
|
|
498
493
|
if (message.role === "developer" && !anchored)
|
|
499
494
|
throw unsupportedContent("developer message");
|
|
@@ -546,7 +541,7 @@ export async function serializeDshMessages(messages, ctx, options = {}) {
|
|
|
546
541
|
const projected = projectOffloadedImages(fileProjected, (ref) => offloadedImageText(ref, attachments === undefined ? undefined : imageAccess(ctx, attachments, ref)));
|
|
547
542
|
const model = resolvePiResponsesModel(normalized);
|
|
548
543
|
const dshContext = { systemPrompt: normalized.systemPrompt, messages: await dshToPiMessages(projected, ctx, normalized, imageMap, requestImages), tools: [...normalized.tools] };
|
|
549
|
-
const compat =
|
|
544
|
+
const compat = isRecord(model.compat) ? model.compat : {};
|
|
550
545
|
const supportsStrictMode = compat.supportsStrictMode === true;
|
|
551
546
|
const supportsOpenAIGrammarTools = compat.supportsOpenAIGrammarTools === true;
|
|
552
547
|
const supportsAdditionalTools = compat.supportsAdditionalTools === true;
|
|
@@ -579,8 +574,8 @@ export async function serializeDshMessages(messages, ctx, options = {}) {
|
|
|
579
574
|
if (normalized.snapshotMarker !== undefined && isMarkerItem(item, normalized.snapshotMarker)) {
|
|
580
575
|
markersFound += 1;
|
|
581
576
|
const rendered = convertedInput[position + 1];
|
|
582
|
-
if (!
|
|
583
|
-
throw
|
|
577
|
+
if (!isRecord(rendered) || (rendered.role !== "developer" && rendered.role !== "system"))
|
|
578
|
+
throw codedError("LCX could not trace a rendered system prompt snapshot", "LCX_RESPONSES_INVALID_INPUT");
|
|
584
579
|
supersededInstructionItems.push(unmarkedInput.length);
|
|
585
580
|
continue;
|
|
586
581
|
}
|
|
@@ -593,35 +588,35 @@ export async function serializeDshMessages(messages, ctx, options = {}) {
|
|
|
593
588
|
const inserted = dshContext.messages.filter((message) => message.role === "user" && message.content === normalized.snapshotMarker).length;
|
|
594
589
|
const nonce = normalized.snapshotMarker.slice(normalized.snapshotMarker.lastIndexOf(":") + 1);
|
|
595
590
|
if (markersFound !== inserted || JSON.stringify(unmarkedInput).includes(nonce))
|
|
596
|
-
throw
|
|
591
|
+
throw codedError("LCX could not remove a system prompt snapshot marker", "LCX_RESPONSES_INVALID_INPUT");
|
|
597
592
|
}
|
|
598
593
|
const input = restorePortableAssistantPhases(unmarkedInput, dshContext.messages, { provider: model.provider, id: model.id, api: model.api });
|
|
599
594
|
const tools = options.tools === undefined ? undefined : convertResponsesTools([...immediateTools.values()], toolOptions);
|
|
600
595
|
return { input, supersededInstructionItems, imageMap, tools, model: piModel, grammarToolInputProperties, deferredToolsMode };
|
|
601
596
|
}
|
|
602
597
|
function isMarkerItem(item, marker) {
|
|
603
|
-
if (!
|
|
598
|
+
if (!isRecord(item) || item.role !== "user" || !Array.isArray(item.content))
|
|
604
599
|
return false;
|
|
605
|
-
return item.content.length === 1 &&
|
|
600
|
+
return item.content.length === 1 && isRecord(item.content[0]) && item.content[0].text === marker;
|
|
606
601
|
}
|
|
607
602
|
export function responsesTools(tools) {
|
|
608
603
|
if (tools === undefined)
|
|
609
604
|
return undefined;
|
|
610
605
|
if (!Array.isArray(tools))
|
|
611
|
-
throw
|
|
612
|
-
if (tools.every((tool) =>
|
|
606
|
+
throw codedError("LCX Responses tools must be an array", "LCX_COMPACT_INVALID_TOOLS");
|
|
607
|
+
if (tools.every((tool) => isRecord(tool) && typeof tool.type === "string"))
|
|
613
608
|
return structuredClone(tools);
|
|
614
609
|
for (const tool of tools)
|
|
615
|
-
if (!
|
|
616
|
-
throw
|
|
610
|
+
if (!isRecord(tool) || typeof tool.name !== "string" || !tool.name)
|
|
611
|
+
throw codedError("LCX Responses tool has no name", "LCX_COMPACT_INVALID_TOOLS");
|
|
617
612
|
return convertResponsesTools(tools, { supportsStrictMode: false, supportsOpenAIGrammarTools: false });
|
|
618
613
|
}
|
|
619
614
|
function isResponsesMessageItem(item) {
|
|
620
|
-
return
|
|
615
|
+
return isRecord(item) && typeof item.role === "string" && (item.type === undefined || item.type === "message");
|
|
621
616
|
}
|
|
622
617
|
function mapImageParts(value, mapper) {
|
|
623
618
|
return value.map((part) => {
|
|
624
|
-
if (!
|
|
619
|
+
if (!isRecord(part))
|
|
625
620
|
return structuredClone(part);
|
|
626
621
|
if (part.type === "input_image" || part.type === "dsh_image_attachment")
|
|
627
622
|
return mapper(part);
|
|
@@ -632,17 +627,17 @@ function mapImageParts(value, mapper) {
|
|
|
632
627
|
}
|
|
633
628
|
export function persistNativeImageReferences(output, imageMap) {
|
|
634
629
|
const persist = (part) => {
|
|
635
|
-
if (part.type === "dsh_image_attachment" &&
|
|
630
|
+
if (part.type === "dsh_image_attachment" && isRecord(part.attachment))
|
|
636
631
|
return structuredClone(part);
|
|
637
632
|
if (part.type !== "input_image" || typeof part.image_url !== "string")
|
|
638
|
-
throw
|
|
633
|
+
throw codedError("native compact returned an invalid image item", "LCX_COMPACT_INVALID_RESPONSE");
|
|
639
634
|
const ref = imageMap.get(part.image_url);
|
|
640
635
|
if (ref === undefined)
|
|
641
|
-
throw
|
|
636
|
+
throw codedError("native compact returned an untracked image item", "LCX_COMPACT_INVALID_RESPONSE");
|
|
642
637
|
return { type: "dsh_image_attachment", attachment: structuredClone(ref) };
|
|
643
638
|
};
|
|
644
639
|
return output.map((item) => {
|
|
645
|
-
if (!
|
|
640
|
+
if (!isRecord(item))
|
|
646
641
|
return structuredClone(item);
|
|
647
642
|
if (isResponsesMessageItem(item) && Array.isArray(item.content))
|
|
648
643
|
return { ...structuredClone(item), content: mapImageParts(item.content, persist) };
|
|
@@ -652,11 +647,11 @@ export function persistNativeImageReferences(output, imageMap) {
|
|
|
652
647
|
});
|
|
653
648
|
}
|
|
654
649
|
async function hydratePart(part, ctx, options) {
|
|
655
|
-
if (!
|
|
650
|
+
if (!isRecord(part) || part.type !== "dsh_image_attachment")
|
|
656
651
|
return structuredClone(part);
|
|
657
652
|
const attachment = part.attachment;
|
|
658
653
|
if (!hasImageAttachment(attachment))
|
|
659
|
-
throw
|
|
654
|
+
throw codedError("native compact returned an invalid image attachment", "LCX_COMPACT_INVALID_RESPONSE");
|
|
660
655
|
if (options.imageSupport === "unsupported")
|
|
661
656
|
return { type: "input_text", text: "[image omitted because the target model does not support image input]" };
|
|
662
657
|
return imagePart({ attachment }, ctx, options, options.imageMap);
|
|
@@ -670,7 +665,7 @@ export function inputImageBase64Lengths(input) {
|
|
|
670
665
|
visit(child);
|
|
671
666
|
return;
|
|
672
667
|
}
|
|
673
|
-
if (!
|
|
668
|
+
if (!isRecord(value))
|
|
674
669
|
return;
|
|
675
670
|
if (value.type === "input_image" && typeof value.image_url === "string") {
|
|
676
671
|
const url = value.image_url;
|
|
@@ -710,7 +705,7 @@ export function assertAggregateImageBudget(options) {
|
|
|
710
705
|
if (removed >= excess) {
|
|
711
706
|
throw new LlmError(`LCX request images exceed the configured base64 bound once checkpoint images are counted; ${count} more oldest occurrence(s) must be offloaded.`, IMAGE_OFFLOAD_REQUIRED_CODE, { offloadImages: count });
|
|
712
707
|
}
|
|
713
|
-
throw
|
|
708
|
+
throw codedError(`Images retained in the compaction checkpoint (${options.fixedBytes} base64 bytes) leave no room within the ${options.maxBytes}-byte request image bound, and offloading new images cannot recover it; start a new session or raise maxRequestImageBytes`, "LCX_CHECKPOINT_IMAGE_BUDGET");
|
|
714
709
|
}
|
|
715
710
|
export async function hydrateNativeImageReferences(output, ctx, options = {}) {
|
|
716
711
|
const normalized = {
|
|
@@ -723,7 +718,7 @@ export async function hydrateNativeImageReferences(output, ctx, options = {}) {
|
|
|
723
718
|
};
|
|
724
719
|
const result = [];
|
|
725
720
|
for (const item of asArray(output)) {
|
|
726
|
-
if (!
|
|
721
|
+
if (!isRecord(item)) {
|
|
727
722
|
result.push(structuredClone(item));
|
|
728
723
|
continue;
|
|
729
724
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { isRecord } from "./util.js";
|
|
2
3
|
export const GROK_NATIVE_SERVER_TOOL_TYPES = new Set([
|
|
3
4
|
"web_search_call",
|
|
4
5
|
"x_search_call",
|
|
@@ -28,9 +29,6 @@ const GROK_CITATION_ID_MARKER = /([ \t]?)\{render_inline_citation:citation_id=(\
|
|
|
28
29
|
const GROK_UI_CITATION_MARKER = /render_inline_citation[^\r\n]*[ \t]*/giu;
|
|
29
30
|
const GROK_PRIVATE_RENDER_MARKER = /[\uE000-\uF8FF]render_inline_citation[^\uE000-\uF8FF\r\n]*[\uE000-\uF8FF][ \t]*/giu;
|
|
30
31
|
const GROK_EOS_MARKER = /<\|eos\|>/giu;
|
|
31
|
-
function isRecord(value) {
|
|
32
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
33
|
-
}
|
|
34
32
|
function citationId(annotation) {
|
|
35
33
|
const value = annotation.citation_id ?? annotation.citationId ?? annotation.id;
|
|
36
34
|
return typeof value === "string" || typeof value === "number"
|