dsh-lcx-codex 0.6.0-pre.1 → 0.6.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.
@@ -1,9 +1,8 @@
1
+ import { isRecord, codedError } from "./util.js";
1
2
  export const PORTABLE_BUDGET_ERROR_CODE = "LCX_PORTABLE_BUDGET_EXCEEDED";
2
3
  export const PORTABLE_UNSUPPORTED_CONTENT_CODE = "LCX_CHECKPOINT_PORTABLE_UNSUPPORTED_CONTENT";
3
4
  function unsupportedContent(kind) {
4
- return Object.assign(new Error(`LCX cannot budget unsupported message content: ${String(kind)}`), {
5
- code: PORTABLE_UNSUPPORTED_CONTENT_CODE,
6
- });
5
+ return codedError(`LCX cannot budget unsupported message content: ${String(kind)}`, PORTABLE_UNSUPPORTED_CONTENT_CODE);
7
6
  }
8
7
  const MAX_BUDGET_INPUT_CHARS = 2_000_000;
9
8
  const CONSERVATIVE_IMAGE_TOKEN_COST = 2_048;
@@ -12,15 +11,12 @@ const ASCII_WORD = /[A-Za-z0-9]/u;
12
11
  const STRUCTURAL = /[\p{P}\p{S}]/u;
13
12
  const DATA_URI = /^data:[^;,\s]+(?:;[^,\s]*)?;base64,[A-Za-z0-9+/\s]+={0,2}$/u;
14
13
  const ENCODED_TEXT = /^[A-Za-z0-9+/_-]{512,}={0,2}$/u;
15
- /** @param {string} value */
16
14
  function looksEncodedText(value) {
17
15
  return DATA_URI.test(value) || ENCODED_TEXT.test(value);
18
16
  }
19
17
  /**
20
18
  * A small conservative fallback, deliberately not a tokenizer. The baseline
21
19
  * preserves legacy /4 while CJK and structural characters cost more.
22
- * @param {unknown} value
23
- * @returns {number | undefined}
24
20
  */
25
21
  export function estimateTextTokens(value) {
26
22
  if (typeof value !== "string")
@@ -50,18 +46,6 @@ export function estimateTextTokens(value) {
50
46
  flushAscii();
51
47
  return Math.max(1, Math.ceil(value.length / 4), weighted);
52
48
  }
53
- /**
54
- * @param {unknown} value
55
- * @returns {value is UnknownRecord}
56
- */
57
- function isObject(value) {
58
- return value !== null && typeof value === "object" && !Array.isArray(value);
59
- }
60
- /**
61
- * @param {unknown} value
62
- * @param {Set<object>} [seen]
63
- * @returns {boolean}
64
- */
65
49
  function containsOpaqueValue(value, seen = new Set()) {
66
50
  if (value === null || typeof value !== "object")
67
51
  return false;
@@ -72,7 +56,6 @@ function containsOpaqueValue(value, seen = new Set()) {
72
56
  seen.add(value);
73
57
  return Object.values(value).some((entry) => containsOpaqueValue(entry, seen));
74
58
  }
75
- /** @param {unknown} value */
76
59
  function safeJson(value) {
77
60
  try {
78
61
  if (containsOpaqueValue(value))
@@ -84,7 +67,6 @@ function safeJson(value) {
84
67
  return undefined;
85
68
  }
86
69
  }
87
- /** @param {unknown} value */
88
70
  function safeScalar(value) {
89
71
  return typeof value === "string" ||
90
72
  typeof value === "number" ||
@@ -92,10 +74,6 @@ function safeScalar(value) {
92
74
  ? String(value)
93
75
  : undefined;
94
76
  }
95
- /**
96
- * @param {unknown} content
97
- * @returns {unknown[] | undefined}
98
- */
99
77
  function visibleContent(content) {
100
78
  if (typeof content === "string")
101
79
  return [{ type: "text", text: content }];
@@ -103,7 +81,7 @@ function visibleContent(content) {
103
81
  return undefined;
104
82
  const parts = [];
105
83
  for (const part of content) {
106
- if (!isObject(part) || typeof part.type !== "string")
84
+ if (!isRecord(part) || typeof part.type !== "string")
107
85
  throw unsupportedContent("missing block type");
108
86
  if (["text", "input_text", "output_text"].includes(part.type)) {
109
87
  if (typeof part.text !== "string")
@@ -137,11 +115,9 @@ function visibleContent(content) {
137
115
  /**
138
116
  * Project an item to model-visible fields only. Opaque provider state, raw
139
117
  * binary, and replay/session metadata are intentionally excluded.
140
- * @param {unknown} item
141
- * @returns {unknown | undefined}
142
118
  */
143
119
  export function modelVisibleBudgetView(item) {
144
- if (!isObject(item))
120
+ if (!isRecord(item))
145
121
  return undefined;
146
122
  if (item.type === "function_call") {
147
123
  const callId = safeScalar(item.call_id);
@@ -181,8 +157,6 @@ export function modelVisibleBudgetView(item) {
181
157
  /**
182
158
  * Images have provider/model-dependent costs. Count each known image block with
183
159
  * a fixed conservative surcharge without inspecting base64 or attachment data.
184
- * @param {unknown} value
185
- * @returns {number}
186
160
  */
187
161
  function imageTokenCost(value) {
188
162
  if (Array.isArray(value)) {
@@ -191,17 +165,13 @@ function imageTokenCost(value) {
191
165
  total += imageTokenCost(entry);
192
166
  return total;
193
167
  }
194
- if (!isObject(value))
168
+ if (!isRecord(value))
195
169
  return 0;
196
170
  let total = value.image === true ? CONSERVATIVE_IMAGE_TOKEN_COST : 0;
197
171
  for (const entry of Object.values(value))
198
172
  total += imageTokenCost(entry);
199
173
  return total;
200
174
  }
201
- /**
202
- * @param {unknown} item
203
- * @returns {number | undefined}
204
- */
205
175
  export function estimateBudgetItem(item) {
206
176
  const view = modelVisibleBudgetView(item);
207
177
  if (view === undefined)
@@ -210,7 +180,6 @@ export function estimateBudgetItem(item) {
210
180
  const textCost = estimateTextTokens(encoded);
211
181
  return textCost === undefined ? undefined : textCost + imageTokenCost(view);
212
182
  }
213
- /** @param {unknown} maxChars */
214
183
  export function portableTokenCeiling(maxChars) {
215
184
  return typeof maxChars === "number" &&
216
185
  Number.isSafeInteger(maxChars) &&
@@ -218,10 +187,6 @@ export function portableTokenCeiling(maxChars) {
218
187
  ? Math.ceil(maxChars / 4)
219
188
  : undefined;
220
189
  }
221
- /** @param {string} message */
222
190
  export function portableBudgetError(message) {
223
- /** @type {Error & { code?: string }} */
224
- const error = new Error(message);
225
- error.code = PORTABLE_BUDGET_ERROR_CODE;
226
- return error;
191
+ return codedError(message, PORTABLE_BUDGET_ERROR_CODE);
227
192
  }
@@ -1,23 +1,20 @@
1
+ import { getResponsesToolSupport } from "./pi-responses-runtime.js";
1
2
  import { projectToolUpdates } from "@deepseek-ai/dsh-llm";
2
3
  export const DEFAULT_TOOL_UPDATES = "addition-only";
3
4
  /** Reason used when the route compat explicitly declines both declaration kinds; a deliberate configuration. */
4
5
  export const COMPAT_OPT_OUT = "route compat opts out of additional_tools and tool_search";
6
+ /** Reason used when the route compat names no supported declaration shape at all; LCX does not guess one. */
7
+ export const COMPAT_SILENT = "route compat does not say whether the model supports additional_tools or tool_search";
5
8
  /**
6
- * Which declaration item carries a mid-session addition. DSH declares `toolUpdate: "addition-only"` only for
7
- * models whose host catalog supports `additional_tools` or `tool_search`, so a route compat that says nothing
8
- * (LCX's frozen Pi 0.86 catalog does not know newer models such as gpt-6-sol) is not evidence against it. Only
9
- * an explicit `false` on a declaration kind that is not backed by an explicit `true` opts the route out.
9
+ * Which declaration item carries a mid-session addition, from what the route compat states: `additional_tools`
10
+ * wins over `tool_search` when both are supported, as in Pi. A shape is never guessed: a compat that is silent
11
+ * about both (a model neither the bundled Pi catalog nor the profile describes) or that declines both yields
12
+ * no shape, and the request carries the complete tool list instead. DSH declares addition-only for models whose
13
+ * own catalog supports one of the two, but only the compat says which.
10
14
  */
11
15
  export function declarationKind(compat) {
12
- const additional = compat?.supportsAdditionalTools;
13
- const search = compat?.supportsToolSearch;
14
- if (additional === true)
15
- return "additional_tools";
16
- if (search === true)
17
- return "tool_search";
18
- if (additional === false || search === false)
19
- return undefined;
20
- return "additional_tools";
16
+ const support = getResponsesToolSupport({ ...compat, supportsMidConvoSystemMessages: true });
17
+ return support === "changes" ? "additional_tools" : support === "additions" ? "tool_search" : undefined;
21
18
  }
22
19
  /** Remove the activation marker; the wire never carries it. */
23
20
  export function withoutDeferLoading(tool) {
@@ -40,10 +37,10 @@ function full(messages, tools, toolHistory, fallbackReason, fallbackUnexpected)
40
37
  /**
41
38
  * Decide the tool surface of one GPT Responses request.
42
39
  *
43
- * Addition-only is used only when every condition holds, otherwise the full current list is sent:
40
+ * DSH history projection is used only when every condition holds; Pi owns the wire tool state:
44
41
  * the policy is on, DSH reports `toolUpdate: "addition-only"` with an in-history system prompt, the route
45
- * compat does not explicitly opt out of `additional_tools`/`tool_search` (silence is accepted: the host
46
- * declares addition-only only for models that support them), and DSH supplied its tool history. The host
42
+ * compat names a supported declaration shape (`additional_tools` or `tool_search`; silence is not guessed
43
+ * at, see `declarationKind`), and DSH supplied its tool history. The host
47
44
  * projection is then re-verified (LCX-owned self check); any inconsistency falls back to the full list.
48
45
  * Removals and same-name redefinitions need no extra handling: the host history fold already yields a
49
46
  * shrunken or fully redeclared baseline for them (one-time cache loss), which this function passes through.
@@ -63,7 +60,7 @@ export function planToolSurface(input) {
63
60
  return fallback("route is not in-history");
64
61
  const kind = declarationKind(compat);
65
62
  if (kind === undefined)
66
- return fallback(COMPAT_OPT_OUT);
63
+ return fallback(compat?.supportsAdditionalTools === false || compat?.supportsToolSearch === false ? COMPAT_OPT_OUT : COMPAT_SILENT);
67
64
  if (toolHistory === undefined)
68
65
  return fallback("no DSH tool history");
69
66
  const projected = projectToolUpdates(messages, tools, "addition-only", toolHistory);
@@ -102,6 +99,5 @@ export function planToolSurface(input) {
102
99
  messages: projected.messages,
103
100
  tools: projectedTools,
104
101
  anchored: true,
105
- compat: kind === "additional_tools" ? { supportsAdditionalTools: true } : { supportsAdditionalTools: false, supportsToolSearch: true },
106
102
  };
107
103
  }
package/lib/transport.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { abortError } from "./abort-error.js";
2
- const DEFAULT_TIMEOUT_MS = 300_000;
3
- const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
2
+ import { DEFAULTS } from "./defaults.js";
3
+ const DEFAULT_TIMEOUT_MS = DEFAULTS.requestTimeoutMs;
4
+ const DEFAULT_MAX_BYTES = DEFAULTS.maxResponseBytes;
4
5
  const MAX_ERROR_BYTES = 512 * 1024;
5
6
  function errorFacts(value) {
6
7
  return value instanceof Error ? value : new Error(String(value));
@@ -110,27 +111,31 @@ async function readLimited(response, maxBytes = DEFAULT_MAX_BYTES) {
110
111
  reader.releaseLock();
111
112
  }
112
113
  }
113
- export async function fetchJsonWithRetry(url, body, headers = {}, signal, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
114
- const maxAttempts = Math.max(1, Math.min(6, Number(options.maxAttempts ?? 3)));
115
- const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_BYTES;
114
+ /**
115
+ * The shared request core: POST with bounded retries. A non-2xx answer becomes a classified error (quota,
116
+ * retryable status, other) with its retry-after delay, a transport failure is retried with backoff, and a
117
+ * 2xx answer is handed to `onOk`, whose failures are classified like any other.
118
+ */
119
+ async function postWithRetry(url, body, headers, accept, signal, requestTimeoutMs, maxAttemptsOption, maxErrorBytes, onOk) {
120
+ const maxAttempts = Math.max(1, Math.min(DEFAULTS.maxAttemptsCap, Number(maxAttemptsOption ?? DEFAULTS.maxAttempts)));
116
121
  let last;
117
122
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
118
123
  abortIfNeeded(signal);
119
124
  try {
120
- const requestSignal = combinedSignal(signal, timeoutMs);
125
+ const requestSignal = combinedSignal(signal, requestTimeoutMs);
121
126
  const response = await fetch(url, {
122
127
  method: "POST",
123
128
  headers: {
124
129
  "content-type": "application/json",
125
- accept: "application/json",
130
+ accept,
126
131
  ...headers,
127
132
  },
128
133
  body: JSON.stringify(body),
129
134
  signal: requestSignal,
130
135
  redirect: "error",
131
136
  });
132
- const text = await readLimited(response, response.ok ? maxResponseBytes : Math.min(maxResponseBytes, MAX_ERROR_BYTES));
133
137
  if (!response.ok) {
138
+ const text = await readLimited(response, maxErrorBytes);
134
139
  const quota = isQuotaError(text);
135
140
  const retryable = !quota && retryableStatus(response.status);
136
141
  const providerRetryAfterMs = retryAfterFromHeaders(response.headers);
@@ -144,20 +149,13 @@ export async function fetchJsonWithRetry(url, body, headers = {}, signal, timeou
144
149
  ? {}
145
150
  : { providerRetryAfterMs }),
146
151
  });
147
- if (!error.retryable || attempt >= maxAttempts)
152
+ if (!retryable || attempt >= maxAttempts)
148
153
  throw error;
149
154
  last = error;
150
155
  await sleep(delayFromHeaders(response.headers, attempt), signal);
151
156
  continue;
152
157
  }
153
- let parsed;
154
- try {
155
- parsed = text ? JSON.parse(text) : {};
156
- }
157
- catch (cause) {
158
- throw makeError(`invalid JSON response from ${url}`, "LCX_INVALID_JSON", { status: response.status, cause });
159
- }
160
- return parsed;
158
+ return await onOk(response, requestSignal);
161
159
  }
162
160
  catch (error) {
163
161
  if (signal?.aborted)
@@ -184,135 +182,107 @@ export async function fetchJsonWithRetry(url, body, headers = {}, signal, timeou
184
182
  }
185
183
  throw last ?? makeError("request failed", "LCX_REQUEST_FAILED");
186
184
  }
187
- export async function fetchSseWithRetry(url, body, headers = {}, signal, timeoutMs, options = {}) {
188
- const requestTimeoutMs = timeoutMs ??
189
- (options.applyDefaultTimeout === false ? undefined : DEFAULT_TIMEOUT_MS);
190
- const maxAttempts = Math.max(1, Math.min(6, Number(options.maxAttempts ?? 3)));
191
- let last;
192
- for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
193
- abortIfNeeded(signal);
185
+ export async function fetchJsonWithRetry(url, body, headers = {}, signal, timeoutMs = DEFAULT_TIMEOUT_MS, options = {}) {
186
+ const maxResponseBytes = options.maxResponseBytes ?? DEFAULT_MAX_BYTES;
187
+ return postWithRetry(url, body, headers, "application/json", signal, timeoutMs, options.maxAttempts, Math.min(maxResponseBytes, MAX_ERROR_BYTES), async (response) => {
188
+ const text = await readLimited(response, maxResponseBytes);
194
189
  try {
195
- const requestSignal = combinedSignal(signal, requestTimeoutMs);
196
- const response = await fetch(url, {
197
- method: "POST",
198
- headers: {
199
- "content-type": "application/json",
200
- accept: "text/event-stream",
201
- ...headers,
202
- },
203
- body: JSON.stringify(body),
204
- signal: requestSignal,
205
- redirect: "error",
206
- });
207
- if (!response.ok) {
208
- const text = await readLimited(response, Math.min(options.maxResponseBytes ?? DEFAULT_MAX_BYTES, MAX_ERROR_BYTES));
209
- const quota = isQuotaError(text);
210
- const retryable = !quota && retryableStatus(response.status);
211
- const providerRetryAfterMs = retryAfterFromHeaders(response.headers);
212
- const error = makeError(`HTTP ${response.status}`, quota ? "LCX_INSUFFICIENT_QUOTA" : retryable ? "LCX_HTTP_RETRYABLE" : "LCX_HTTP_ERROR", {
213
- status: response.status,
214
- retryable,
215
- requestId: response.headers.get("x-request-id") ??
216
- response.headers.get("request-id") ??
217
- undefined,
218
- ...(providerRetryAfterMs === undefined
219
- ? {}
220
- : { providerRetryAfterMs }),
221
- });
222
- if (!retryable || attempt >= maxAttempts)
223
- throw error;
224
- last = error;
225
- await sleep(delayFromHeaders(response.headers, attempt), signal);
226
- continue;
227
- }
228
- if (typeof options.consume === "function")
229
- return await options.consume(response, { requestSignal });
230
- return response;
190
+ return text ? JSON.parse(text) : {};
231
191
  }
232
- catch (error) {
233
- if (signal?.aborted)
234
- throw abortError(signal, error);
235
- const details = errorFacts(error);
236
- const retryable = details.retryable === true ||
237
- details.code === "LCX_HTTP_RETRYABLE" ||
238
- error instanceof TypeError ||
239
- [
240
- "ECONNRESET",
241
- "ECONNREFUSED",
242
- "ETIMEDOUT",
243
- "EAI_AGAIN",
244
- "UND_ERR_CONNECT_TIMEOUT",
245
- ].includes(details.code ?? "");
246
- if (!retryable || attempt >= maxAttempts) {
247
- if (attempt >= maxAttempts && retryable)
248
- throw makeError(`request failed after ${maxAttempts} attempts`, "LCX_RETRY_EXHAUSTED", { cause: error, retryable: true });
249
- throw error;
250
- }
251
- last = error;
252
- await sleep(Math.min(10_000, 500 * 2 ** (attempt - 1)), signal);
192
+ catch (cause) {
193
+ throw makeError(`invalid JSON response from ${url}`, "LCX_INVALID_JSON", { status: response.status, cause });
253
194
  }
254
- }
255
- throw last ?? makeError("request failed", "LCX_REQUEST_FAILED");
195
+ });
256
196
  }
257
- export async function consumeSse(response, onEvent, options = {}) {
258
- if (!response.body)
259
- throw makeError("SSE response has no body", "LCX_INVALID_SSE");
260
- const maxBytes = options.maxResponseBytes ?? DEFAULT_MAX_BYTES;
197
+ export async function fetchSseWithRetry(url, body, headers = {}, signal, timeoutMs, options = {}) {
198
+ const requestTimeoutMs = timeoutMs ??
199
+ (options.applyDefaultTimeout === false ? undefined : DEFAULT_TIMEOUT_MS);
200
+ return postWithRetry(url, body, headers, "text/event-stream", signal, requestTimeoutMs, options.maxAttempts, Math.min(options.maxResponseBytes ?? DEFAULT_MAX_BYTES, MAX_ERROR_BYTES), async (response, requestSignal) => typeof options.consume === "function"
201
+ ? options.consume(response, { requestSignal })
202
+ : response);
203
+ }
204
+ /** `reader.read()` that settles with the abort as soon as `signal` aborts, whatever the stream does. */
205
+ async function readWithSignal(reader, signal) {
206
+ if (!signal)
207
+ return reader.read();
208
+ if (signal.aborted)
209
+ throw abortError(signal);
210
+ return new Promise((resolve, reject) => {
211
+ const onAbort = () => reject(abortError(signal));
212
+ signal.addEventListener("abort", onAbort, { once: true });
213
+ reader.read().then(resolve, reject).finally(() => {
214
+ signal.removeEventListener("abort", onAbort);
215
+ });
216
+ });
217
+ }
218
+ /**
219
+ * The one SSE event reader: yields each parsed JSON `data:` event (`[DONE]` yields nothing) with a byte limit.
220
+ * An abort interrupts a read that never settles in two ways: the pending read is rejected with the abort, and
221
+ * the underlying reader is cancelled so the connection is released; the abort is also re-checked around every
222
+ * read. The reader is always cancelled and released when the generator ends, however it ends.
223
+ */
224
+ export async function* readSseEvents(response, options) {
225
+ const { signal, errors } = options;
226
+ if (!response?.body)
227
+ throw errors.noBody(response);
228
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
261
229
  const reader = response.body.getReader();
262
230
  const decoder = new TextDecoder();
263
231
  let pending = "";
264
232
  let dataLines = [];
265
233
  let bytes = 0;
266
- const dispatch = () => {
234
+ const decode = () => {
267
235
  if (dataLines.length === 0)
268
- return;
236
+ return undefined;
269
237
  const data = dataLines.join("\n");
270
238
  dataLines = [];
271
239
  if (data === "[DONE]")
272
- return;
273
- let event;
240
+ return undefined;
274
241
  try {
275
- event = JSON.parse(data);
242
+ return JSON.parse(data);
276
243
  }
277
244
  catch (cause) {
278
- throw makeError("malformed SSE JSON", "LCX_INVALID_SSE", { cause });
245
+ throw errors.malformed(cause);
279
246
  }
280
- onEvent(event);
281
247
  };
282
- // An abort must interrupt a read that never settles, not only be noticed between reads. Cancelling
283
- // the reader settles the pending read as done, so the abort is re-checked right after every read.
284
248
  const onAbort = () => {
285
- reader.cancel(options.signal?.reason).catch(() => { });
249
+ reader.cancel(signal?.reason).catch(() => { });
286
250
  };
287
- options.signal?.addEventListener("abort", onAbort, { once: true });
251
+ signal?.addEventListener("abort", onAbort, { once: true });
288
252
  try {
289
253
  while (true) {
290
- abortIfNeeded(options.signal);
291
- const { done, value } = await reader.read();
292
- abortIfNeeded(options.signal);
254
+ abortIfNeeded(signal);
255
+ const { done, value } = await readWithSignal(reader, signal);
256
+ abortIfNeeded(signal);
293
257
  if (done)
294
258
  break;
295
259
  bytes += value.byteLength;
296
260
  if (bytes > maxBytes)
297
- throw makeError(`SSE response exceeds ${maxBytes} bytes`, "LCX_RESPONSE_TOO_LARGE");
261
+ throw errors.tooLarge(maxBytes);
298
262
  pending += decoder.decode(value, { stream: true });
299
263
  let newline;
300
264
  while ((newline = pending.indexOf("\n")) >= 0) {
301
265
  const line = pending.slice(0, newline).replace(/\r$/u, "");
302
266
  pending = pending.slice(newline + 1);
303
- if (line === "")
304
- dispatch();
305
- else if (!line.startsWith(":") && line.startsWith("data:"))
267
+ if (line === "") {
268
+ const event = decode();
269
+ if (event !== undefined)
270
+ yield event;
271
+ }
272
+ else if (!line.startsWith(":") && line.startsWith("data:")) {
306
273
  dataLines.push(line.slice(5).replace(/^ /u, ""));
274
+ }
307
275
  }
308
276
  }
309
277
  pending += decoder.decode();
310
278
  if (pending.startsWith("data:"))
311
279
  dataLines.push(pending.slice(5).replace(/^ /u, ""));
312
- dispatch();
280
+ const event = decode();
281
+ if (event !== undefined)
282
+ yield event;
313
283
  }
314
284
  finally {
315
- options.signal?.removeEventListener("abort", onAbort);
285
+ signal?.removeEventListener("abort", onAbort);
316
286
  try {
317
287
  await reader.cancel();
318
288
  }
@@ -327,3 +297,15 @@ export async function consumeSse(response, onEvent, options = {}) {
327
297
  }
328
298
  }
329
299
  }
300
+ export async function consumeSse(response, onEvent, options = {}) {
301
+ for await (const event of readSseEvents(response, {
302
+ signal: options.signal,
303
+ maxBytes: options.maxResponseBytes,
304
+ errors: {
305
+ noBody: () => makeError("SSE response has no body", "LCX_INVALID_SSE"),
306
+ malformed: (cause) => makeError("malformed SSE JSON", "LCX_INVALID_SSE", { cause }),
307
+ tooLarge: (maxBytes) => makeError(`SSE response exceeds ${maxBytes} bytes`, "LCX_RESPONSE_TOO_LARGE"),
308
+ },
309
+ }))
310
+ onEvent(event);
311
+ }
@@ -21,5 +21,3 @@ export declare function mergeSearchMedia(structured: readonly SearchMediaItem[],
21
21
  * files are LCX's; everything else (pages, video sites) stays an ordinary link.
22
22
  */
23
23
  export declare function extractDirectMediaLinks(text: string): readonly SearchMediaItem[];
24
- /** Direct video files only (see `extractDirectMediaLinks`). */
25
- export declare function extractDirectVideoLinks(text: string): readonly SearchMediaItem[];
package/lib/util.js ADDED
@@ -0,0 +1,21 @@
1
+ /** Small value guards and error constructors shared by the host-side modules. */
2
+ /** A plain JSON-like object: not null and not an array. */
3
+ export function isRecord(value) {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+ /** A number that is a positive safe integer. */
7
+ export function isPositiveSafeInteger(value) {
8
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
9
+ }
10
+ /** The value when it is a positive safe integer, otherwise the fallback. */
11
+ export function positiveSafeInteger(value, fallback) {
12
+ return isPositiveSafeInteger(value) ? value : fallback;
13
+ }
14
+ /** A finite number greater than zero. */
15
+ export function isPositiveFinite(value) {
16
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
17
+ }
18
+ /** An Error carrying a stable machine-readable `code`. */
19
+ export function codedError(message, code) {
20
+ return Object.assign(new Error(message), { code });
21
+ }
@@ -184,6 +184,3 @@ export function outputPdfRefs(blocks) {
184
184
  }
185
185
  return refs;
186
186
  }
187
- export function blockPlainText(block) {
188
- return block.lines.map((line) => line.text).filter(Boolean).join(" ");
189
- }