dsh-lcx-codex 0.4.2 → 0.4.3-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.
Files changed (47) hide show
  1. package/README.md +116 -202
  2. package/cordis.patch.yml +3 -20
  3. package/lib/client.js +273 -146
  4. package/lib/compact-v2.js +218 -199
  5. package/lib/dsh-compat.js +227 -100
  6. package/lib/dsh-responses.js +445 -277
  7. package/lib/index.js +851 -757
  8. package/lib/json-store.js +50 -31
  9. package/lib/native-checkpoint.js +520 -194
  10. package/lib/responses-request.js +106 -121
  11. package/lib/responses-stream.js +972 -443
  12. package/lib/route.js +229 -355
  13. package/lib/service-mutex.js +73 -64
  14. package/lib/token-budget.js +176 -108
  15. package/lib/transport.js +277 -67
  16. package/lib/types/client/index.d.ts +6 -0
  17. package/lib/types/compact-v2.d.ts +104 -0
  18. package/lib/types/dsh-compat.d.ts +78 -0
  19. package/lib/types/dsh-responses.d.ts +82 -0
  20. package/lib/types/index.d.ts +83 -0
  21. package/lib/types/json-store.d.ts +10 -0
  22. package/lib/types/native-checkpoint.d.ts +213 -0
  23. package/lib/types/responses-request.d.ts +58 -0
  24. package/lib/types/responses-stream.d.ts +51 -0
  25. package/lib/types/route.d.ts +132 -0
  26. package/lib/types/service-mutex.d.ts +14 -0
  27. package/lib/types/token-budget.d.ts +50 -0
  28. package/lib/types/transport.d.ts +20 -0
  29. package/lib/types/web-run-output.d.ts +29 -0
  30. package/lib/types/web-search-alpha.d.ts +286 -0
  31. package/lib/types/web-search-capability.d.ts +26 -0
  32. package/lib/types/web-search-hosted.d.ts +246 -0
  33. package/lib/types/web-search-ref-store.d.ts +22 -0
  34. package/lib/web-run-output.js +167 -18
  35. package/lib/web-search-alpha.js +865 -163
  36. package/lib/web-search-capability.js +55 -65
  37. package/lib/web-search-hosted.js +210 -32
  38. package/lib/web-search-ref-store.js +63 -59
  39. package/package.json +79 -27
  40. package/ARCHITECTURE.md +0 -117
  41. package/CHANGELOG.md +0 -224
  42. package/README_EN.md +0 -277
  43. package/assets/dsh-lcx-codex-banner.jpg +0 -0
  44. package/lib/legacy-v3.js +0 -20
  45. package/lib/responses-replay.js +0 -68
  46. package/scripts/probe-alpha.mjs +0 -43
  47. package/scripts/validate-dsh-schema.mjs +0 -31
@@ -1,239 +1,496 @@
1
1
  // @ts-check
2
-
3
- import { processResponsesStream } from '@earendil-works/pi-ai/api/openai-responses-shared'
4
- import { fetchSseWithRetry } from './transport.js'
5
-
6
- /** @typedef {Record<string, unknown>} UnknownRecord */
7
- /** @typedef {import('openai/resources/responses/responses.js').ResponseStreamEvent} ResponseStreamEvent */
8
- /** @typedef {{ message: string, code: string, status?: number, requestId?: string, providerRetryAfterMs?: number }} ManagedFailure */
9
- /** @typedef {Error & { code?: string, status?: number, requestId?: string, providerRetryAfterMs?: number, cause?: unknown }} LcxError */
10
-
2
+ import { createAssistantMessageEventStream, } from "@earendil-works/pi-ai";
3
+ import { processResponsesStream } from "@earendil-works/pi-ai/api/openai-responses-shared";
4
+ import { ToolCallId } from "@deepseek-ai/dsh-llm";
5
+ import { fetchSseWithRetry } from "./transport.js";
11
6
  function emptyUsage() {
12
- return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }
7
+ return {
8
+ input: 0,
9
+ output: 0,
10
+ cacheRead: 0,
11
+ cacheWrite: 0,
12
+ totalTokens: 0,
13
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
14
+ };
13
15
  }
14
-
15
16
  /** @param {unknown} value @returns {value is UnknownRecord} */
16
- function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value) }
17
-
18
- class PiEventQueue {
19
- constructor() {
20
- /** @type {unknown[]} */
21
- this.queue = []
22
- /** @type {Array<(value: IteratorResult<unknown>) => void>} */
23
- this.waiting = []
24
- this.done = false
25
- }
26
- /** @param {unknown} event */
27
- push(event) {
28
- if (this.done) return
29
- const waiter = this.waiting.shift()
30
- if (waiter) waiter({ value: event, done: false })
31
- else this.queue.push(event)
32
- }
33
- end() {
34
- this.done = true
35
- while (this.waiting.length > 0) this.waiting.shift()?.({ value: undefined, done: true })
36
- }
37
- async *[Symbol.asyncIterator]() {
38
- while (true) {
39
- if (this.queue.length > 0) yield this.queue.shift()
40
- else if (this.done) return
41
- else {
42
- const result = await new Promise((resolve) => this.waiting.push(resolve))
43
- if (result.done) return
44
- yield result.value
45
- }
46
- }
47
- }
17
+ function isObject(value) {
18
+ return value !== null && typeof value === "object" && !Array.isArray(value);
48
19
  }
49
-
50
20
  /** @param {unknown} raw */
51
- function safeStatus(raw) { return Number.isInteger(raw) && Number(raw) >= 100 && Number(raw) <= 599 ? Number(raw) : undefined }
52
-
21
+ function safeStatus(raw) {
22
+ return Number.isInteger(raw) && Number(raw) >= 100 && Number(raw) <= 599
23
+ ? Number(raw)
24
+ : undefined;
25
+ }
53
26
  /** @param {unknown} raw */
54
27
  function safeRequestId(raw) {
55
- if (typeof raw !== 'string' || raw.length === 0 || raw.length > 160) return undefined
56
- return /^[A-Za-z0-9._:\/-]+$/u.test(raw) ? raw : undefined
28
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 160)
29
+ return undefined;
30
+ return /^[A-Za-z0-9._:\/-]+$/u.test(raw) ? raw : undefined;
57
31
  }
58
-
59
32
  /** @param {unknown} error */
60
33
  function errorFacts(error) {
61
- const seen = new Set()
62
- const codes = []
63
- const texts = []
64
- let status
65
- let requestId
66
- let providerRetryAfterMs
67
- let current = error
68
- for (let depth = 0; depth < 8 && (current instanceof Error || isObject(current)) && !seen.has(current); depth += 1) {
69
- seen.add(current)
70
- const value = /** @type {LcxError} */ (current)
71
- if (status === undefined) status = safeStatus(value.status)
72
- if (requestId === undefined) requestId = safeRequestId(value.requestId)
73
- if (providerRetryAfterMs === undefined && Number.isFinite(value.providerRetryAfterMs) && Number(value.providerRetryAfterMs) > 0) providerRetryAfterMs = Number(value.providerRetryAfterMs)
74
- if (typeof value.code === 'string' && value.code) codes.push(value.code)
75
- if (typeof value.message === 'string' && value.message) texts.push(value.message)
76
- current = value.cause
77
- }
78
- return { status, requestId, providerRetryAfterMs, codes, text: texts.join(' | ') }
34
+ const seen = new Set();
35
+ const codes = [];
36
+ const texts = [];
37
+ let status;
38
+ let requestId;
39
+ let providerRetryAfterMs;
40
+ let current = error;
41
+ for (let depth = 0; depth < 8 &&
42
+ (current instanceof Error || isObject(current)) &&
43
+ !seen.has(current); depth += 1) {
44
+ seen.add(current);
45
+ const value = current;
46
+ if (status === undefined)
47
+ status = safeStatus(value.status);
48
+ if (requestId === undefined)
49
+ requestId = safeRequestId(value.requestId);
50
+ if (providerRetryAfterMs === undefined &&
51
+ Number.isFinite(value.providerRetryAfterMs) &&
52
+ Number(value.providerRetryAfterMs) > 0)
53
+ providerRetryAfterMs = Number(value.providerRetryAfterMs);
54
+ if (typeof value.code === "string" && value.code)
55
+ codes.push(value.code);
56
+ if (typeof value.message === "string" && value.message)
57
+ texts.push(value.message);
58
+ current = value.cause;
59
+ }
60
+ return {
61
+ status,
62
+ requestId,
63
+ providerRetryAfterMs,
64
+ codes,
65
+ text: texts.join(" | "),
66
+ };
79
67
  }
80
-
81
68
  /**
82
69
  * Provider bodies/messages are deliberately not surfaced. Only a stable class and safe facts leave the wire boundary.
83
70
  * @param {unknown} error
84
71
  * @param {AbortSignal} [signal]
85
72
  */
86
73
  export function managedFailure(error, signal) {
87
- const facts = errorFacts(error)
88
- const sourceCodes = new Set(facts.codes)
89
- const text = facts.text
90
- let code = 'RESPONSES_ERROR'
91
- if (signal?.aborted || sourceCodes.has('LCX_ABORTED') || /\babort(?:ed)?\b/iu.test(text)) code = 'ABORTED'
92
- else if (sourceCodes.has('LCX_RESPONSES_UNSUPPORTED_OPTION')) code = 'UNSUPPORTED_OPTION'
93
- else if (sourceCodes.has('LCX_RESPONSES_ROUTE_UNAVAILABLE') || sourceCodes.has('LCX_RESPONSES_MODEL_UNAVAILABLE')) code = 'NO_ADAPTER'
94
- else if (facts.status === 401 || facts.status === 403 || sourceCodes.has('AUTH') || sourceCodes.has('LCX_CREDENTIAL_UNAVAILABLE')) code = 'AUTH'
95
- else if (facts.status === 408) code = 'TIMEOUT'
96
- else if (facts.status === 409 || facts.status === 425) code = 'TRANSPORT'
97
- else if (facts.status === 429 || /rate.?limit|quota exceeded/iu.test(text)) code = 'RATE_LIMIT'
98
- else if (facts.status !== undefined && facts.status >= 500) code = 'SERVER'
99
- else if (/context (?:window|length)|maximum context|too many tokens/iu.test(text) || [...sourceCodes].some((value) => /context.*(?:window|length|exceed)/iu.test(value))) code = 'CONTEXT_WINDOW_EXCEEDED'
100
- else if (facts.status === 400 || facts.status === 404 || facts.status === 413 || facts.status === 422 || sourceCodes.has('LCX_RESPONSES_INVALID_INPUT') || /invalid.?request|payload too large|length limit exceeded/iu.test(text)) code = 'INVALID_REQUEST'
101
- else if (sourceCodes.has('LCX_RESPONSE_TOO_LARGE')) code = 'INVALID_REQUEST'
102
- else if (sourceCodes.has('LCX_INVALID_SSE') || /stream ended before|without a terminal|malformed.*sse/iu.test(text)) code = 'TRANSPORT'
103
- else if (/time(?:d)?\s*out|timeout/iu.test(text) || sourceCodes.has('TimeoutError')) code = 'TIMEOUT'
104
- else if (error instanceof TypeError || /\bnetwork|connection|socket|fetch|ECONN|EAI_AGAIN|terminated|premature close\b/iu.test(text)) code = 'TRANSPORT'
105
- const messages = /** @type {Record<string, string>} */ ({
106
- ABORTED: 'Responses request was aborted',
107
- AUTH: 'Responses request was rejected by authentication',
108
- UNSUPPORTED_OPTION: 'LCX Responses does not support this request option',
109
- NO_ADAPTER: 'LCX could not resolve the selected Responses route',
110
- RATE_LIMIT: 'Responses provider rate limit was reached',
111
- SERVER: 'Responses provider returned a server failure',
112
- INVALID_REQUEST: 'Responses provider rejected the request',
113
- CONTEXT_WINDOW_EXCEEDED: 'Responses request exceeded the model context window',
114
- TIMEOUT: 'Responses request timed out',
115
- TRANSPORT: 'Responses transport failed',
116
- RESPONSES_ERROR: 'Responses request failed',
117
- })
118
- return {
119
- message: messages[code] ?? messages.RESPONSES_ERROR,
120
- code,
121
- ...(facts.status === undefined ? {} : { status: facts.status }),
122
- ...(facts.requestId === undefined ? {} : { requestId: facts.requestId }),
123
- ...(facts.providerRetryAfterMs === undefined ? {} : { providerRetryAfterMs: facts.providerRetryAfterMs }),
124
- }
74
+ const facts = errorFacts(error);
75
+ const sourceCodes = new Set(facts.codes);
76
+ const text = facts.text;
77
+ const signalReason = signal?.reason;
78
+ const signalTimedOut = signal?.aborted &&
79
+ (signalReason?.name === "TimeoutError" ||
80
+ signalReason?.code === "TimeoutError" ||
81
+ /time(?:d)?\s*out|timeout/iu.test(String(signalReason?.message ?? "")));
82
+ let code = "RESPONSES_ERROR";
83
+ if (signalTimedOut ||
84
+ facts.status === 408 ||
85
+ sourceCodes.has("TimeoutError") ||
86
+ /time(?:d)?\s*out|timeout/iu.test(text))
87
+ code = "TIMEOUT";
88
+ else if (signal?.aborted ||
89
+ sourceCodes.has("LCX_ABORTED") ||
90
+ /\babort(?:ed)?\b/iu.test(text))
91
+ code = "ABORTED";
92
+ else if (sourceCodes.has("LCX_RESPONSES_UNSUPPORTED_OPTION"))
93
+ code = "UNSUPPORTED_OPTION";
94
+ else if (sourceCodes.has("LCX_RESPONSES_ROUTE_UNAVAILABLE") ||
95
+ sourceCodes.has("LCX_RESPONSES_MODEL_UNAVAILABLE"))
96
+ code = "NO_ADAPTER";
97
+ else if (facts.status === 401 ||
98
+ facts.status === 403 ||
99
+ sourceCodes.has("AUTH") ||
100
+ sourceCodes.has("LCX_CREDENTIAL_UNAVAILABLE"))
101
+ code = "AUTH";
102
+ else if (facts.status === 409 || facts.status === 425)
103
+ code = "TRANSPORT";
104
+ else if (facts.status === 429 || /rate.?limit|quota exceeded/iu.test(text))
105
+ code = "RATE_LIMIT";
106
+ else if (facts.status !== undefined && facts.status >= 500)
107
+ code = "SERVER";
108
+ else if (/context (?:window|length)|maximum context|too many tokens/iu.test(text) ||
109
+ [...sourceCodes].some((value) => /context.*(?:window|length|exceed)/iu.test(value)))
110
+ code = "CONTEXT_WINDOW_EXCEEDED";
111
+ else if (facts.status === 400 ||
112
+ facts.status === 404 ||
113
+ facts.status === 413 ||
114
+ facts.status === 422 ||
115
+ sourceCodes.has("LCX_RESPONSES_INVALID_INPUT") ||
116
+ sourceCodes.has("LCX_CHECKPOINT_UNSUPPORTED") ||
117
+ /invalid.?request|payload too large|length limit exceeded/iu.test(text))
118
+ code = "INVALID_REQUEST";
119
+ else if (sourceCodes.has("LCX_RESPONSE_TOO_LARGE"))
120
+ code = "INVALID_REQUEST";
121
+ else if (sourceCodes.has("LCX_INVALID_SSE") ||
122
+ /stream ended before|without a terminal|malformed.*sse/iu.test(text))
123
+ code = "TRANSPORT";
124
+ else if (error instanceof TypeError ||
125
+ /\bnetwork|connection|socket|fetch|ECONN|EAI_AGAIN|terminated|premature close\b/iu.test(text))
126
+ code = "TRANSPORT";
127
+ const messages = /** @type {Record<string, string>} */ {
128
+ ABORTED: "Responses request was aborted",
129
+ AUTH: "Responses request was rejected by authentication",
130
+ UNSUPPORTED_OPTION: "LCX Responses does not support this request option",
131
+ NO_ADAPTER: "LCX could not resolve the selected Responses route",
132
+ RATE_LIMIT: "Responses provider rate limit was reached",
133
+ SERVER: "Responses provider returned a server failure",
134
+ INVALID_REQUEST: sourceCodes.has("LCX_CHECKPOINT_UNSUPPORTED")
135
+ ? "Unsupported or invalid LCX checkpoint; start a new session"
136
+ : "Responses provider rejected the request",
137
+ CONTEXT_WINDOW_EXCEEDED: "Responses request exceeded the model context window",
138
+ TIMEOUT: "Responses request timed out",
139
+ TRANSPORT: "Responses transport failed",
140
+ RESPONSES_ERROR: "Responses request failed",
141
+ };
142
+ return {
143
+ message: messages[code] ?? messages.RESPONSES_ERROR,
144
+ code,
145
+ ...(facts.status === undefined ? {} : { status: facts.status }),
146
+ ...(facts.requestId === undefined ? {} : { requestId: facts.requestId }),
147
+ ...(facts.providerRetryAfterMs === undefined
148
+ ? {}
149
+ : { providerRetryAfterMs: facts.providerRetryAfterMs }),
150
+ };
125
151
  }
126
-
127
152
  /** @param {unknown} error @param {AbortSignal} [signal] */
128
153
  export function managedFailureChunk(error, signal) {
129
- const failure = managedFailure(error, signal)
130
- return { type: 'finish', reason: failure.code === 'ABORTED' ? { kind: 'aborted', failure } : { kind: 'error', failure } }
154
+ const managed = managedFailure(error, signal);
155
+ const failure = {
156
+ message: managed.message,
157
+ code: managed.code,
158
+ ...(managed.status === undefined ? {} : { status: managed.status }),
159
+ ...(managed.providerRetryAfterMs === undefined
160
+ ? {}
161
+ : { providerRetryAfterMs: managed.providerRetryAfterMs }),
162
+ };
163
+ return {
164
+ type: "finish",
165
+ reason: managed.code === "ABORTED"
166
+ ? { kind: "aborted", failure }
167
+ : { kind: "error", failure },
168
+ };
131
169
  }
132
-
133
170
  /**
134
171
  * Minimal JSON SSE reader. LCX owns the exact HTTP wire; Pi owns event semantics after this boundary.
135
172
  * @param {Response} response
136
173
  * @param {{ signal?: AbortSignal, maxResponseBytes?: number }} [options]
137
174
  */
138
175
  async function* responseEvents(response, options = {}) {
139
- if (!response?.body) throw Object.assign(new Error('Responses stream returned no body'), { code: 'LCX_INVALID_SSE', status: response?.status })
140
- const reader = response.body.getReader()
141
- const decoder = new TextDecoder()
142
- const maxBytes = options.maxResponseBytes ?? 8 * 1024 * 1024
143
- let bytes = 0
144
- let pending = ''
145
- /** @type {string[]} */
146
- let dataLines = []
147
- const decode = () => {
148
- if (dataLines.length === 0) return undefined
149
- const data = dataLines.join('\n')
150
- dataLines = []
151
- if (data === '[DONE]') return undefined
152
- try { return JSON.parse(data) }
153
- catch (cause) { throw Object.assign(new Error('Responses stream contained malformed SSE JSON', { cause }), { code: 'LCX_INVALID_SSE' }) }
154
- }
155
- try {
156
- while (true) {
157
- if (options.signal?.aborted) throw options.signal.reason ?? Object.assign(new Error('request aborted'), { code: 'LCX_ABORTED' })
158
- const { done, value } = await reader.read()
159
- if (done) break
160
- bytes += value.byteLength
161
- if (bytes > maxBytes) throw Object.assign(new Error(`Responses SSE exceeds ${maxBytes} bytes`), { code: 'LCX_RESPONSE_TOO_LARGE' })
162
- pending += decoder.decode(value, { stream: true })
163
- let newline
164
- while ((newline = pending.indexOf('\n')) >= 0) {
165
- const line = pending.slice(0, newline).replace(/\r$/u, '')
166
- pending = pending.slice(newline + 1)
167
- if (line === '') {
168
- const event = decode()
169
- if (event !== undefined) yield event
170
- } else if (!line.startsWith(':') && line.startsWith('data:')) {
171
- dataLines.push(line.slice(5).replace(/^ /u, ''))
176
+ if (!response?.body)
177
+ throw Object.assign(new Error("Responses stream returned no body"), {
178
+ code: "LCX_INVALID_SSE",
179
+ status: response?.status,
180
+ });
181
+ const reader = response.body.getReader();
182
+ const decoder = new TextDecoder();
183
+ const maxBytes = options.maxResponseBytes ?? 8 * 1024 * 1024;
184
+ let bytes = 0;
185
+ let pending = "";
186
+ /** @type {string[]} */
187
+ let dataLines = [];
188
+ const decode = () => {
189
+ if (dataLines.length === 0)
190
+ return undefined;
191
+ const data = dataLines.join("\n");
192
+ dataLines = [];
193
+ if (data === "[DONE]")
194
+ return undefined;
195
+ try {
196
+ return JSON.parse(data);
197
+ }
198
+ catch (cause) {
199
+ throw Object.assign(new Error("Responses stream contained malformed SSE JSON", { cause }), { code: "LCX_INVALID_SSE" });
172
200
  }
173
- }
201
+ };
202
+ try {
203
+ while (true) {
204
+ if (options.signal?.aborted)
205
+ throw (options.signal.reason ??
206
+ Object.assign(new Error("request aborted"), { code: "LCX_ABORTED" }));
207
+ const { done, value } = await reader.read();
208
+ if (done)
209
+ break;
210
+ bytes += value.byteLength;
211
+ if (bytes > maxBytes)
212
+ throw Object.assign(new Error(`Responses SSE exceeds ${maxBytes} bytes`), { code: "LCX_RESPONSE_TOO_LARGE" });
213
+ pending += decoder.decode(value, { stream: true });
214
+ let newline;
215
+ while ((newline = pending.indexOf("\n")) >= 0) {
216
+ const line = pending.slice(0, newline).replace(/\r$/u, "");
217
+ pending = pending.slice(newline + 1);
218
+ if (line === "") {
219
+ const event = decode();
220
+ if (event !== undefined)
221
+ yield event;
222
+ }
223
+ else if (!line.startsWith(":") && line.startsWith("data:")) {
224
+ dataLines.push(line.slice(5).replace(/^ /u, ""));
225
+ }
226
+ }
227
+ }
228
+ pending += decoder.decode();
229
+ if (pending.startsWith("data:"))
230
+ dataLines.push(pending.slice(5).replace(/^ /u, ""));
231
+ const event = decode();
232
+ if (event !== undefined)
233
+ yield event;
234
+ }
235
+ finally {
236
+ await reader.cancel().catch(() => undefined);
237
+ }
238
+ }
239
+ function isSupportedOutputItem(value) {
240
+ if (!isObject(value))
241
+ return false;
242
+ if (value.type === "message")
243
+ return (typeof value.id === "string" &&
244
+ value.role === "assistant" &&
245
+ (value.status === "in_progress" ||
246
+ value.status === "completed" ||
247
+ value.status === "incomplete") &&
248
+ Array.isArray(value.content) &&
249
+ value.content.every((part) => isObject(part) &&
250
+ ((part.type === "output_text" &&
251
+ typeof part.text === "string" &&
252
+ Array.isArray(part.annotations)) ||
253
+ (part.type === "refusal" && typeof part.refusal === "string"))));
254
+ if (value.type === "reasoning")
255
+ return (typeof value.id === "string" &&
256
+ Array.isArray(value.summary) &&
257
+ value.summary.every((part) => isObject(part) && typeof part.text === "string"));
258
+ if (value.type === "function_call")
259
+ return (typeof value.id === "string" &&
260
+ typeof value.call_id === "string" &&
261
+ typeof value.name === "string" &&
262
+ typeof value.arguments === "string");
263
+ return (value.type === "custom_tool_call" &&
264
+ typeof value.id === "string" &&
265
+ typeof value.call_id === "string" &&
266
+ typeof value.name === "string" &&
267
+ typeof value.input === "string");
268
+ }
269
+ function isTerminalResponse(value) {
270
+ if (!isObject(value) || typeof value.id !== "string")
271
+ return false;
272
+ if (!Array.isArray(value.output))
273
+ return false;
274
+ return (value.status === "completed" ||
275
+ value.status === "incomplete" ||
276
+ value.status === "failed" ||
277
+ value.status === "cancelled" ||
278
+ value.status === "in_progress" ||
279
+ value.status === "queued");
280
+ }
281
+ const PI_RESPONSE_EVENT_TYPES = new Set([
282
+ "response.created",
283
+ "response.output_item.added",
284
+ "response.output_item.done",
285
+ "response.reasoning_summary_text.delta",
286
+ "response.reasoning_summary_part.done",
287
+ "response.reasoning_text.delta",
288
+ "response.output_text.delta",
289
+ "response.refusal.delta",
290
+ "response.function_call_arguments.delta",
291
+ "response.function_call_arguments.done",
292
+ "response.custom_tool_call_input.delta",
293
+ "response.custom_tool_call_input.done",
294
+ "response.completed",
295
+ "response.incomplete",
296
+ "response.failed",
297
+ "error",
298
+ ]);
299
+ /**
300
+ * Pi only consumes this public Responses subset. Validate all fields it reads before
301
+ * narrowing provider wire data, and silently preserve Pi's existing behavior of
302
+ * ignoring unrelated Responses events.
303
+ */
304
+ function isSupportedResponseStreamEvent(value) {
305
+ if (!isObject(value))
306
+ return false;
307
+ if (!Number.isSafeInteger(value.sequence_number) ||
308
+ typeof value.type !== "string" ||
309
+ !PI_RESPONSE_EVENT_TYPES.has(value.type))
310
+ return false;
311
+ if (value.type === "response.created")
312
+ return isObject(value.response) && typeof value.response.id === "string";
313
+ if (value.type === "response.output_item.added" ||
314
+ value.type === "response.output_item.done")
315
+ return Number.isSafeInteger(value.output_index) && isSupportedOutputItem(value.item);
316
+ if (value.type === "response.output_text.delta" ||
317
+ value.type === "response.refusal.delta" ||
318
+ value.type === "response.reasoning_text.delta")
319
+ return (Number.isSafeInteger(value.output_index) &&
320
+ Number.isSafeInteger(value.content_index) &&
321
+ typeof value.item_id === "string" &&
322
+ typeof value.delta === "string");
323
+ if (value.type === "response.reasoning_summary_text.delta")
324
+ return (Number.isSafeInteger(value.output_index) &&
325
+ Number.isSafeInteger(value.summary_index) &&
326
+ typeof value.item_id === "string" &&
327
+ typeof value.delta === "string");
328
+ if (value.type === "response.reasoning_summary_part.done")
329
+ return (Number.isSafeInteger(value.output_index) &&
330
+ Number.isSafeInteger(value.summary_index) &&
331
+ typeof value.item_id === "string");
332
+ if (value.type === "response.function_call_arguments.delta")
333
+ return (Number.isSafeInteger(value.output_index) &&
334
+ typeof value.item_id === "string" &&
335
+ typeof value.delta === "string");
336
+ if (value.type === "response.function_call_arguments.done")
337
+ return (Number.isSafeInteger(value.output_index) &&
338
+ typeof value.item_id === "string" &&
339
+ typeof value.arguments === "string");
340
+ if (value.type === "response.custom_tool_call_input.delta")
341
+ return (Number.isSafeInteger(value.output_index) &&
342
+ typeof value.item_id === "string" &&
343
+ typeof value.delta === "string");
344
+ if (value.type === "response.custom_tool_call_input.done")
345
+ return (Number.isSafeInteger(value.output_index) &&
346
+ typeof value.item_id === "string" &&
347
+ typeof value.input === "string");
348
+ if (value.type === "response.completed" ||
349
+ value.type === "response.incomplete")
350
+ return isTerminalResponse(value.response);
351
+ if (value.type === "response.failed")
352
+ return isObject(value.response);
353
+ return typeof value.code === "string" && typeof value.message === "string";
354
+ }
355
+ async function* validatedResponseEvents(source) {
356
+ let sequenceNumber = 0;
357
+ for await (const raw of source) {
358
+ if (!isObject(raw))
359
+ continue;
360
+ if (!PI_RESPONSE_EVENT_TYPES.has(String(raw.type ?? "")))
361
+ continue;
362
+ const event = { ...raw, sequence_number: sequenceNumber++ };
363
+ if (!isSupportedResponseStreamEvent(event))
364
+ throw Object.assign(new Error("Responses stream contained an unsupported Pi event"), { code: "LCX_INVALID_SSE" });
365
+ yield event;
174
366
  }
175
- pending += decoder.decode()
176
- if (pending.startsWith('data:')) dataLines.push(pending.slice(5).replace(/^ /u, ''))
177
- const event = decode()
178
- if (event !== undefined) yield event
179
- } finally {
180
- await reader.cancel().catch(() => undefined)
181
- }
182
367
  }
183
-
184
368
  /** @param {UnknownRecord} item */
185
369
  function itemKind(item) {
186
- if (item.type === 'message') return 'text'
187
- if (item.type === 'reasoning') return 'reasoning'
188
- if (item.type === 'function_call' || item.type === 'custom_tool_call') return 'tool-call'
189
- return undefined
370
+ if (item.type === "message")
371
+ return "text";
372
+ if (item.type === "reasoning")
373
+ return "reasoning";
374
+ if (item.type === "function_call" || item.type === "custom_tool_call")
375
+ return "tool-call";
376
+ return undefined;
190
377
  }
191
-
192
378
  /** @param {UnknownRecord} item */
193
379
  function itemIdentity(item) {
194
- const id = typeof item.id === 'string' && item.id ? item.id : typeof item.call_id === 'string' ? item.call_id : ''
195
- return id ? `${String(item.type)}:${id}` : undefined
380
+ const id = typeof item.id === "string" && item.id
381
+ ? item.id
382
+ : typeof item.call_id === "string"
383
+ ? item.call_id
384
+ : "";
385
+ return id ? `${String(item.type)}:${id}` : undefined;
196
386
  }
197
-
198
387
  /** @param {UnknownRecord} item */
199
388
  function itemText(item) {
200
- if (item.type === 'message') return (Array.isArray(item.content) ? item.content : []).map((part) => isObject(part) && (part.type === 'output_text' || part.type === 'refusal') ? String(part.text ?? part.refusal ?? '') : '').join('')
201
- if (item.type === 'reasoning') {
202
- const parts = Array.isArray(item.summary) && item.summary.length > 0 ? item.summary : Array.isArray(item.content) ? item.content : []
203
- return parts.map((part) => isObject(part) ? String(part.text ?? '') : '').join('\n\n')
204
- }
205
- if (item.type === 'function_call') return String(item.arguments ?? '')
206
- if (item.type === 'custom_tool_call') return String(item.input ?? '')
207
- return ''
389
+ if (item.type === "message")
390
+ return (Array.isArray(item.content) ? item.content : [])
391
+ .map((part) => isObject(part) &&
392
+ (part.type === "output_text" || part.type === "refusal")
393
+ ? String(part.text ?? part.refusal ?? "")
394
+ : "")
395
+ .join("");
396
+ if (item.type === "reasoning") {
397
+ const parts = Array.isArray(item.summary) && item.summary.length > 0
398
+ ? item.summary
399
+ : Array.isArray(item.content)
400
+ ? item.content
401
+ : [];
402
+ return parts
403
+ .map((part) => isObject(part) ? String(part.text ?? "") : "")
404
+ .join("\n\n");
405
+ }
406
+ if (item.type === "function_call")
407
+ return String(item.arguments ?? "");
408
+ if (item.type === "custom_tool_call")
409
+ return String(item.input ?? "");
410
+ return "";
208
411
  }
209
-
210
412
  /** @param {UnknownRecord} item @param {number} index */
211
413
  function normalizedTerminalItem(item, index) {
212
- if (item.type === 'message') return { ...structuredClone(item), id: typeof item.id === 'string' && item.id ? item.id : `msg_lcx_${index}`, role: 'assistant', status: item.status ?? 'completed', content: Array.isArray(item.content) ? structuredClone(item.content) : [] }
213
- if (item.type === 'reasoning') return { ...structuredClone(item), id: typeof item.id === 'string' && item.id ? item.id : `rs_lcx_${index}`, summary: Array.isArray(item.summary) ? structuredClone(item.summary) : [] }
214
- if (item.type === 'function_call') return { ...structuredClone(item), id: typeof item.id === 'string' && item.id ? item.id : `fc_lcx_${index}`, call_id: typeof item.call_id === 'string' && item.call_id ? item.call_id : `call_lcx_${index}`, name: String(item.name ?? ''), arguments: String(item.arguments ?? '') }
215
- if (item.type === 'custom_tool_call') return { ...structuredClone(item), id: typeof item.id === 'string' && item.id ? item.id : `ctc_lcx_${index}`, call_id: typeof item.call_id === 'string' && item.call_id ? item.call_id : `call_lcx_${index}`, name: String(item.name ?? ''), input: String(item.input ?? '') }
216
- return structuredClone(item)
414
+ if (item.type === "message")
415
+ return {
416
+ ...structuredClone(item),
417
+ id: typeof item.id === "string" && item.id ? item.id : `msg_lcx_${index}`,
418
+ role: "assistant",
419
+ status: item.status ?? "completed",
420
+ content: Array.isArray(item.content) ? structuredClone(item.content) : [],
421
+ };
422
+ if (item.type === "reasoning")
423
+ return {
424
+ ...structuredClone(item),
425
+ id: typeof item.id === "string" && item.id ? item.id : `rs_lcx_${index}`,
426
+ summary: Array.isArray(item.summary) ? structuredClone(item.summary) : [],
427
+ };
428
+ if (item.type === "function_call")
429
+ return {
430
+ ...structuredClone(item),
431
+ id: typeof item.id === "string" && item.id ? item.id : `fc_lcx_${index}`,
432
+ call_id: typeof item.call_id === "string" && item.call_id
433
+ ? item.call_id
434
+ : `call_lcx_${index}`,
435
+ name: String(item.name ?? ""),
436
+ arguments: String(item.arguments ?? ""),
437
+ };
438
+ if (item.type === "custom_tool_call")
439
+ return {
440
+ ...structuredClone(item),
441
+ id: typeof item.id === "string" && item.id ? item.id : `ctc_lcx_${index}`,
442
+ call_id: typeof item.call_id === "string" && item.call_id
443
+ ? item.call_id
444
+ : `call_lcx_${index}`,
445
+ name: String(item.name ?? ""),
446
+ input: String(item.input ?? ""),
447
+ };
448
+ return structuredClone(item);
217
449
  }
218
-
219
450
  /** @param {UnknownRecord} item @param {number} index */
220
451
  function addedShell(item, index) {
221
- if (item.type === 'message') return { type: 'message', id: item.id ?? `msg_lcx_${index}`, role: 'assistant', status: 'in_progress', content: [] }
222
- if (item.type === 'reasoning') return { type: 'reasoning', id: item.id ?? `rs_lcx_${index}`, summary: [] }
223
- if (item.type === 'function_call') return { type: 'function_call', id: item.id ?? `fc_lcx_${index}`, call_id: item.call_id ?? `call_lcx_${index}`, name: String(item.name ?? ''), arguments: '' }
224
- return { type: 'custom_tool_call', id: item.id ?? `ctc_lcx_${index}`, call_id: item.call_id ?? `call_lcx_${index}`, name: String(item.name ?? ''), input: '' }
452
+ if (item.type === "message")
453
+ return {
454
+ type: "message",
455
+ id: item.id ?? `msg_lcx_${index}`,
456
+ role: "assistant",
457
+ status: "in_progress",
458
+ content: [],
459
+ };
460
+ if (item.type === "reasoning")
461
+ return { type: "reasoning", id: item.id ?? `rs_lcx_${index}`, summary: [] };
462
+ if (item.type === "function_call")
463
+ return {
464
+ type: "function_call",
465
+ id: item.id ?? `fc_lcx_${index}`,
466
+ call_id: item.call_id ?? `call_lcx_${index}`,
467
+ name: String(item.name ?? ""),
468
+ arguments: "",
469
+ };
470
+ return {
471
+ type: "custom_tool_call",
472
+ id: item.id ?? `ctc_lcx_${index}`,
473
+ call_id: item.call_id ?? `call_lcx_${index}`,
474
+ name: String(item.name ?? ""),
475
+ input: "",
476
+ };
225
477
  }
226
-
227
478
  /** @param {UnknownRecord} record @param {UnknownRecord} item */
228
479
  function recordMatches(record, item) {
229
- if (record.kind !== itemKind(item)) return false
230
- const recordItem = /** @type {UnknownRecord} */ (record.item)
231
- if (itemIdentity(recordItem) && itemIdentity(recordItem) === itemIdentity(item)) return true
232
- const streamed = String(record.text ?? '')
233
- const terminal = itemText(item)
234
- return streamed.length > 0 && terminal.length > 0 && (streamed === terminal || streamed.startsWith(terminal) || terminal.startsWith(streamed))
480
+ if (record.kind !== itemKind(item))
481
+ return false;
482
+ const recordItem = /** @type {UnknownRecord} */ record.item;
483
+ if (itemIdentity(recordItem) &&
484
+ itemIdentity(recordItem) === itemIdentity(item))
485
+ return true;
486
+ const streamed = String(record.text ?? "");
487
+ const terminal = itemText(item);
488
+ return (streamed.length > 0 &&
489
+ terminal.length > 0 &&
490
+ (streamed === terminal ||
491
+ streamed.startsWith(terminal) ||
492
+ terminal.startsWith(streamed)));
235
493
  }
236
-
237
494
  /**
238
495
  * Some compatible gateways omit `response.output_item.added/done`, or terminal output indexes drift
239
496
  * when a reasoning item is inserted. Normalize only the missing framing; Pi remains authoritative for item semantics.
@@ -241,245 +498,502 @@ function recordMatches(record, item) {
241
498
  * @param {{ responseModel?: string }} [meta]
242
499
  */
243
500
  async function* normalizedResponseEvents(source, meta = {}) {
244
- const open = new Map()
245
- const completed = new Set()
246
- /** @param {number} index @param {UnknownRecord} item */
247
- const ensure = function* (index, item) {
248
- let record = open.get(index)
249
- if (record) return record
250
- const normalized = normalizedTerminalItem(item, index)
251
- record = { kind: itemKind(normalized), item: normalized, text: '' }
252
- open.set(index, record)
253
- yield { type: 'response.output_item.added', output_index: index, item: addedShell(normalized, index) }
254
- return record
255
- }
256
-
257
- for await (const raw of source) {
258
- if (!isObject(raw)) continue
259
- const event = /** @type {UnknownRecord} */ (raw)
260
- const index = Number.isInteger(event.output_index) ? Number(event.output_index) : 0
261
- if (event.type === 'response.output_item.added' && isObject(event.item)) {
262
- const item = normalizedTerminalItem(/** @type {UnknownRecord} */ (event.item), index)
263
- open.set(index, { kind: itemKind(item), item, text: itemText(item) })
264
- yield { ...event, item }
265
- continue
266
- }
267
- if (event.type === 'response.output_text.delta') {
268
- let record = open.get(index)
269
- if (!record) {
270
- const item = { type: 'message', id: typeof event.item_id === 'string' ? event.item_id : `msg_lcx_${index}` }
271
- const generated = ensure(index, item)
272
- let next = generated.next()
273
- while (!next.done) { yield next.value; next = generated.next() }
274
- record = next.value
275
- }
276
- record.text = String(record.text ?? '') + String(event.delta ?? '')
277
- yield event
278
- continue
279
- }
280
- if (event.type === 'response.reasoning_summary_text.delta' || event.type === 'response.reasoning_text.delta') {
281
- let record = open.get(index)
282
- if (!record) {
283
- const item = { type: 'reasoning', id: typeof event.item_id === 'string' ? event.item_id : `rs_lcx_${index}` }
284
- const generated = ensure(index, item)
285
- let next = generated.next()
286
- while (!next.done) { yield next.value; next = generated.next() }
287
- record = next.value
288
- }
289
- record.text = String(record.text ?? '') + String(event.delta ?? '')
290
- yield event
291
- continue
292
- }
293
- if (event.type === 'response.function_call_arguments.delta') {
294
- let record = open.get(index)
295
- if (!record) {
296
- const item = { type: 'function_call', id: typeof event.item_id === 'string' ? event.item_id : `fc_lcx_${index}`, call_id: typeof event.call_id === 'string' ? event.call_id : `call_lcx_${index}`, name: String(event.name ?? '') }
297
- const generated = ensure(index, item)
298
- let next = generated.next()
299
- while (!next.done) { yield next.value; next = generated.next() }
300
- record = next.value
301
- }
302
- record.text = String(record.text ?? '') + String(event.delta ?? '')
303
- yield event
304
- continue
305
- }
306
- if (event.type === 'response.custom_tool_call_input.delta') {
307
- let record = open.get(index)
308
- if (!record) {
309
- const item = { type: 'custom_tool_call', id: typeof event.item_id === 'string' ? event.item_id : `ctc_lcx_${index}`, call_id: typeof event.call_id === 'string' ? event.call_id : `call_lcx_${index}`, name: String(event.name ?? '') }
310
- const generated = ensure(index, item)
311
- let next = generated.next()
312
- while (!next.done) { yield next.value; next = generated.next() }
313
- record = next.value
314
- }
315
- record.text = String(record.text ?? '') + String(event.delta ?? '')
316
- yield event
317
- continue
318
- }
319
- if (event.type === 'response.output_item.done' && isObject(event.item)) {
320
- const item = normalizedTerminalItem(/** @type {UnknownRecord} */ (event.item), index)
321
- const identity = itemIdentity(item)
322
- if (identity) completed.add(identity)
323
- open.delete(index)
324
- yield { ...event, item }
325
- continue
326
- }
327
- if ((event.type === 'response.completed' || event.type === 'response.incomplete') && isObject(event.response)) {
328
- const response = /** @type {UnknownRecord} */ (event.response)
329
- if (typeof response.model === 'string' && response.model.length > 0) meta.responseModel = response.model
330
- const output = Array.isArray(response.output) ? response.output.map((item, terminalIndex) => isObject(item) ? normalizedTerminalItem(/** @type {UnknownRecord} */ (item), terminalIndex) : item) : []
331
- const used = new Set()
332
- for (const [streamIndex, record] of open) {
333
- let terminalIndex = output.findIndex((item, candidateIndex) => !used.has(candidateIndex) && isObject(item) && candidateIndex === streamIndex && recordMatches(record, /** @type {UnknownRecord} */ (item)))
334
- if (terminalIndex < 0) terminalIndex = output.findIndex((item, candidateIndex) => !used.has(candidateIndex) && isObject(item) && recordMatches(record, /** @type {UnknownRecord} */ (item)))
335
- const item = terminalIndex >= 0
336
- ? /** @type {UnknownRecord} */ (output[terminalIndex])
337
- : normalizedTerminalItem(/** @type {UnknownRecord} */ (record.item), streamIndex)
338
- if (terminalIndex >= 0) used.add(terminalIndex)
339
- yield { type: 'response.output_item.done', output_index: streamIndex, item }
340
- const identity = itemIdentity(item)
341
- if (identity) completed.add(identity)
342
- }
343
- open.clear()
344
- for (const [terminalIndex, candidate] of output.entries()) {
345
- if (!isObject(candidate) || !itemKind(/** @type {UnknownRecord} */ (candidate)) || used.has(terminalIndex)) continue
346
- const item = /** @type {UnknownRecord} */ (candidate)
347
- const identity = itemIdentity(item)
348
- if (identity && completed.has(identity)) continue
349
- yield { type: 'response.output_item.added', output_index: terminalIndex, item: addedShell(item, terminalIndex) }
350
- const text = itemText(item)
351
- if (text) {
352
- if (item.type === 'message') yield { type: 'response.output_text.delta', output_index: terminalIndex, content_index: 0, item_id: item.id, delta: text }
353
- else if (item.type === 'reasoning') yield { type: 'response.reasoning_summary_text.delta', output_index: terminalIndex, summary_index: 0, item_id: item.id, delta: text }
354
- else if (item.type === 'function_call') yield { type: 'response.function_call_arguments.delta', output_index: terminalIndex, item_id: item.id, call_id: item.call_id, name: item.name, delta: text }
355
- else yield { type: 'response.custom_tool_call_input.delta', output_index: terminalIndex, item_id: item.id, call_id: item.call_id, name: item.name, delta: text }
501
+ const open = new Map();
502
+ const completed = new Set();
503
+ /** @param {number} index @param {UnknownRecord} item */
504
+ const ensure = function* (index, item) {
505
+ let record = open.get(index);
506
+ if (record)
507
+ return record;
508
+ const normalized = normalizedTerminalItem(item, index);
509
+ record = { kind: itemKind(normalized), item: normalized, text: "" };
510
+ open.set(index, record);
511
+ yield {
512
+ type: "response.output_item.added",
513
+ output_index: index,
514
+ item: addedShell(normalized, index),
515
+ };
516
+ return record;
517
+ };
518
+ for await (const raw of source) {
519
+ if (!isObject(raw))
520
+ continue;
521
+ const event = /** @type {UnknownRecord} */ raw;
522
+ const index = Number.isInteger(event.output_index)
523
+ ? Number(event.output_index)
524
+ : 0;
525
+ if (event.type === "response.output_item.added" && isObject(event.item)) {
526
+ const item = normalizedTerminalItem(event.item, index);
527
+ open.set(index, { kind: itemKind(item), item, text: itemText(item) });
528
+ yield { ...event, item };
529
+ continue;
530
+ }
531
+ if (event.type === "response.output_text.delta") {
532
+ let record = open.get(index);
533
+ if (!record) {
534
+ const item = {
535
+ type: "message",
536
+ id: typeof event.item_id === "string"
537
+ ? event.item_id
538
+ : `msg_lcx_${index}`,
539
+ };
540
+ const generated = ensure(index, item);
541
+ let next = generated.next();
542
+ while (!next.done) {
543
+ yield next.value;
544
+ next = generated.next();
545
+ }
546
+ record = next.value;
547
+ }
548
+ record.text = String(record.text ?? "") + String(event.delta ?? "");
549
+ yield event;
550
+ continue;
551
+ }
552
+ if (event.type === "response.reasoning_summary_text.delta" ||
553
+ event.type === "response.reasoning_text.delta") {
554
+ let record = open.get(index);
555
+ if (!record) {
556
+ const item = {
557
+ type: "reasoning",
558
+ id: typeof event.item_id === "string"
559
+ ? event.item_id
560
+ : `rs_lcx_${index}`,
561
+ };
562
+ const generated = ensure(index, item);
563
+ let next = generated.next();
564
+ while (!next.done) {
565
+ yield next.value;
566
+ next = generated.next();
567
+ }
568
+ record = next.value;
569
+ }
570
+ record.text = String(record.text ?? "") + String(event.delta ?? "");
571
+ yield event;
572
+ continue;
573
+ }
574
+ if (event.type === "response.function_call_arguments.delta") {
575
+ let record = open.get(index);
576
+ if (!record) {
577
+ const item = {
578
+ type: "function_call",
579
+ id: typeof event.item_id === "string"
580
+ ? event.item_id
581
+ : `fc_lcx_${index}`,
582
+ call_id: typeof event.call_id === "string"
583
+ ? event.call_id
584
+ : `call_lcx_${index}`,
585
+ name: String(event.name ?? ""),
586
+ };
587
+ const generated = ensure(index, item);
588
+ let next = generated.next();
589
+ while (!next.done) {
590
+ yield next.value;
591
+ next = generated.next();
592
+ }
593
+ record = next.value;
594
+ }
595
+ record.text = String(record.text ?? "") + String(event.delta ?? "");
596
+ yield event;
597
+ continue;
598
+ }
599
+ if (event.type === "response.custom_tool_call_input.delta") {
600
+ let record = open.get(index);
601
+ if (!record) {
602
+ const item = {
603
+ type: "custom_tool_call",
604
+ id: typeof event.item_id === "string"
605
+ ? event.item_id
606
+ : `ctc_lcx_${index}`,
607
+ call_id: typeof event.call_id === "string"
608
+ ? event.call_id
609
+ : `call_lcx_${index}`,
610
+ name: String(event.name ?? ""),
611
+ };
612
+ const generated = ensure(index, item);
613
+ let next = generated.next();
614
+ while (!next.done) {
615
+ yield next.value;
616
+ next = generated.next();
617
+ }
618
+ record = next.value;
619
+ }
620
+ record.text = String(record.text ?? "") + String(event.delta ?? "");
621
+ yield event;
622
+ continue;
356
623
  }
357
- yield { type: 'response.output_item.done', output_index: terminalIndex, item }
358
- if (identity) completed.add(identity)
359
- }
360
- yield { ...event, response: { ...response, output } }
361
- continue
624
+ if (event.type === "response.output_item.done" && isObject(event.item)) {
625
+ const item = normalizedTerminalItem(event.item, index);
626
+ const identity = itemIdentity(item);
627
+ if (identity)
628
+ completed.add(identity);
629
+ open.delete(index);
630
+ yield { ...event, item };
631
+ continue;
632
+ }
633
+ if ((event.type === "response.completed" ||
634
+ event.type === "response.incomplete") &&
635
+ isObject(event.response)) {
636
+ const response = /** @type {UnknownRecord} */ event.response;
637
+ if (typeof response.model === "string" && response.model.length > 0)
638
+ meta.responseModel = response.model;
639
+ const output = Array.isArray(response.output)
640
+ ? response.output.map((item, terminalIndex) => isObject(item)
641
+ ? normalizedTerminalItem(item, terminalIndex)
642
+ : item)
643
+ : [];
644
+ const used = new Set();
645
+ for (const [streamIndex, record] of open) {
646
+ let terminalIndex = output.findIndex((item, candidateIndex) => !used.has(candidateIndex) &&
647
+ isObject(item) &&
648
+ candidateIndex === streamIndex &&
649
+ recordMatches(record, item));
650
+ if (terminalIndex < 0)
651
+ terminalIndex = output.findIndex((item, candidateIndex) => !used.has(candidateIndex) &&
652
+ isObject(item) &&
653
+ recordMatches(record, item));
654
+ const item = terminalIndex >= 0
655
+ ? output[terminalIndex]
656
+ : normalizedTerminalItem(record.item, streamIndex);
657
+ if (terminalIndex >= 0)
658
+ used.add(terminalIndex);
659
+ yield {
660
+ type: "response.output_item.done",
661
+ output_index: streamIndex,
662
+ item,
663
+ };
664
+ const identity = itemIdentity(item);
665
+ if (identity)
666
+ completed.add(identity);
667
+ }
668
+ open.clear();
669
+ for (const [terminalIndex, candidate] of output.entries()) {
670
+ if (!isObject(candidate) ||
671
+ !itemKind(candidate) ||
672
+ used.has(terminalIndex))
673
+ continue;
674
+ const item = candidate;
675
+ const identity = itemIdentity(item);
676
+ if (identity && completed.has(identity))
677
+ continue;
678
+ yield {
679
+ type: "response.output_item.added",
680
+ output_index: terminalIndex,
681
+ item: addedShell(item, terminalIndex),
682
+ };
683
+ const text = itemText(item);
684
+ if (text) {
685
+ if (item.type === "message")
686
+ yield {
687
+ type: "response.output_text.delta",
688
+ output_index: terminalIndex,
689
+ content_index: 0,
690
+ item_id: item.id,
691
+ delta: text,
692
+ };
693
+ else if (item.type === "reasoning")
694
+ yield {
695
+ type: "response.reasoning_summary_text.delta",
696
+ output_index: terminalIndex,
697
+ summary_index: 0,
698
+ item_id: item.id,
699
+ delta: text,
700
+ };
701
+ else if (item.type === "function_call")
702
+ yield {
703
+ type: "response.function_call_arguments.delta",
704
+ output_index: terminalIndex,
705
+ item_id: item.id,
706
+ call_id: item.call_id,
707
+ name: item.name,
708
+ delta: text,
709
+ };
710
+ else
711
+ yield {
712
+ type: "response.custom_tool_call_input.delta",
713
+ output_index: terminalIndex,
714
+ item_id: item.id,
715
+ call_id: item.call_id,
716
+ name: item.name,
717
+ delta: text,
718
+ };
719
+ }
720
+ yield {
721
+ type: "response.output_item.done",
722
+ output_index: terminalIndex,
723
+ item,
724
+ };
725
+ if (identity)
726
+ completed.add(identity);
727
+ }
728
+ yield { ...event, response: { ...response, output } };
729
+ continue;
730
+ }
731
+ yield event;
362
732
  }
363
- yield event
364
- }
365
733
  }
366
-
367
734
  /** @param {unknown} usage */
735
+ function isManagedFailure(value) {
736
+ return (isObject(value) &&
737
+ typeof value.message === "string" &&
738
+ typeof value.code === "string" &&
739
+ (value.status === undefined || typeof value.status === "number") &&
740
+ (value.requestId === undefined || typeof value.requestId === "string") &&
741
+ (value.providerRetryAfterMs === undefined ||
742
+ typeof value.providerRetryAfterMs === "number"));
743
+ }
368
744
  function dshUsage(usage) {
369
- const value = /** @type {UnknownRecord} */ (isObject(usage) ? usage : {})
370
- return {
371
- inputTokens: Number(value.input ?? 0),
372
- outputTokens: Number(value.output ?? 0),
373
- ...(Number(value.cacheRead ?? 0) > 0 ? { cacheReadTokens: Number(value.cacheRead) } : {}),
374
- ...(Number(value.cacheWrite ?? 0) > 0 ? { cacheWriteTokens: Number(value.cacheWrite) } : {}),
375
- ...(Number(value.reasoning ?? 0) > 0 ? { reasoningTokens: Number(value.reasoning) } : {}),
376
- }
745
+ const value = /** @type {UnknownRecord} */ isObject(usage) ? usage : {};
746
+ return {
747
+ inputTokens: Number(value.input ?? 0),
748
+ outputTokens: Number(value.output ?? 0),
749
+ ...(Number(value.cacheRead ?? 0) > 0
750
+ ? { cacheReadTokens: Number(value.cacheRead) }
751
+ : {}),
752
+ ...(Number(value.cacheWrite ?? 0) > 0
753
+ ? { cacheWriteTokens: Number(value.cacheWrite) }
754
+ : {}),
755
+ ...(Number(value.reasoning ?? 0) > 0
756
+ ? { reasoningTokens: Number(value.reasoning) }
757
+ : {}),
758
+ };
377
759
  }
378
-
379
760
  /** @param {unknown} value */
380
761
  function rawArguments(value) {
381
- try { return JSON.stringify(isObject(value) ? value : {}) }
382
- catch { return '{}' }
762
+ try {
763
+ return JSON.stringify(isObject(value) ? value : {});
764
+ }
765
+ catch {
766
+ return "{}";
767
+ }
383
768
  }
384
-
385
769
  /** @param {unknown} message */
386
770
  function replayState(message) {
387
- if (!isObject(message)) return undefined
388
- const content = /** @type {UnknownRecord[]} */ (Array.isArray(message.content) ? message.content.filter(isObject) : [])
389
- const provider = typeof message.provider === 'string' ? message.provider : undefined
390
- const model = typeof message.model === 'string' ? message.model : undefined
391
- const api = typeof message.api === 'string' ? message.api : undefined
392
- if (!provider || !model || !api) return undefined
393
- return {
394
- response: {
395
- kind: 'pi-ai',
396
- version: 2,
397
- api,
398
- provider,
399
- model,
400
- ...(typeof message.responseModel === 'string' ? { responseModel: message.responseModel } : {}),
401
- ...(typeof message.responseId === 'string' ? { responseId: message.responseId } : {}),
402
- stopReason: message.stopReason,
403
- },
404
- blocks: content.map((block) => {
405
- if (block?.type === 'text') return { type: 'text', ...(typeof block.textSignature === 'string' ? { textSignature: block.textSignature } : {}) }
406
- if (block?.type === 'thinking') return { type: 'reasoning', ...(typeof block.thinkingSignature === 'string' ? { thinkingSignature: block.thinkingSignature } : {}), ...(typeof block.redacted === 'boolean' ? { redacted: block.redacted } : {}) }
407
- return {
408
- type: 'tool-call',
409
- ...(typeof block?.thoughtSignature === 'string' ? { thoughtSignature: block.thoughtSignature } : {}),
410
- ...(typeof block?.namespace === 'string' && block.namespace.length > 0 ? { namespace: block.namespace } : {}),
411
- }
412
- }),
413
- }
771
+ if (!isObject(message))
772
+ return undefined;
773
+ const content = Array.isArray(message.content)
774
+ ? message.content.filter(isObject)
775
+ : [];
776
+ const provider = typeof message.provider === "string" ? message.provider : undefined;
777
+ const model = typeof message.model === "string" ? message.model : undefined;
778
+ const api = typeof message.api === "string" ? message.api : undefined;
779
+ if (!provider || !model || !api)
780
+ return undefined;
781
+ return {
782
+ response: {
783
+ kind: "pi-ai",
784
+ version: 2,
785
+ api,
786
+ provider,
787
+ model,
788
+ ...(typeof message.responseModel === "string"
789
+ ? { responseModel: message.responseModel }
790
+ : {}),
791
+ ...(typeof message.responseId === "string"
792
+ ? { responseId: message.responseId }
793
+ : {}),
794
+ stopReason: message.stopReason,
795
+ },
796
+ blocks: content.map((block) => {
797
+ if (block?.type === "text")
798
+ return {
799
+ type: "text",
800
+ ...(typeof block.textSignature === "string"
801
+ ? { textSignature: block.textSignature }
802
+ : {}),
803
+ };
804
+ if (block?.type === "thinking")
805
+ return {
806
+ type: "reasoning",
807
+ ...(typeof block.thinkingSignature === "string"
808
+ ? { thinkingSignature: block.thinkingSignature }
809
+ : {}),
810
+ ...(typeof block.redacted === "boolean"
811
+ ? { redacted: block.redacted }
812
+ : {}),
813
+ };
814
+ return {
815
+ type: "tool-call",
816
+ ...(typeof block?.thoughtSignature === "string"
817
+ ? { thoughtSignature: block.thoughtSignature }
818
+ : {}),
819
+ ...(typeof block?.namespace === "string" && block.namespace.length > 0
820
+ ? { namespace: block.namespace }
821
+ : {}),
822
+ };
823
+ }),
824
+ };
414
825
  }
415
-
416
826
  /** @param {unknown} message */
417
827
  function successfulFinish(message) {
418
- const value = /** @type {UnknownRecord} */ (isObject(message) ? message : {})
419
- const stopReason = String(value.stopReason ?? 'stop')
420
- const content = /** @type {UnknownRecord[]} */ (Array.isArray(value.content) ? value.content.filter(isObject) : [])
421
- if (stopReason === 'length') return { kind: 'max-tokens' }
422
- if (stopReason === 'toolUse' || content.some((block) => block?.type === 'toolCall')) return { kind: 'tool-calls' }
423
- if (stopReason === 'stop' && content.length === 0) return { kind: 'error', failure: { message: 'Responses provider completed without content', code: 'EMPTY_RESPONSE' } }
424
- return { kind: 'stop' }
828
+ const value = /** @type {UnknownRecord} */ isObject(message) ? message : {};
829
+ const stopReason = String(value.stopReason ?? "stop");
830
+ const content = /** @type {UnknownRecord[]} */ Array.isArray(value.content)
831
+ ? value.content.filter(isObject)
832
+ : [];
833
+ if (stopReason === "length")
834
+ return { kind: "max-tokens" };
835
+ if (stopReason === "toolUse" ||
836
+ content.some((block) => block.type === "toolCall"))
837
+ return { kind: "tool-calls" };
838
+ if (stopReason === "stop" && content.length === 0)
839
+ return {
840
+ kind: "error",
841
+ failure: {
842
+ message: "Responses provider completed without content",
843
+ code: "EMPTY_RESPONSE",
844
+ },
845
+ };
846
+ return { kind: "stop" };
425
847
  }
426
-
427
848
  /**
428
849
  * Pi event vocabulary -> DSH StreamChunk. This remains thin and provider-neutral.
429
- * @param {AsyncIterable<unknown>} events
850
+ * @param {AsyncIterable<AssistantMessageEvent>} events
430
851
  * @param {AbortSignal} [signal]
431
852
  */
432
853
  async function* toDshChunks(events, signal) {
433
- const toolIds = new Map()
434
- for await (const raw of events) {
435
- const event = /** @type {UnknownRecord} */ (raw)
436
- switch (event.type) {
437
- case 'start': break
438
- case 'text_start': yield { type: 'block-start', index: Number(event.contentIndex), blockType: 'text' }; break
439
- case 'text_delta': yield { type: 'text-delta', index: Number(event.contentIndex), text: String(event.delta ?? '') }; break
440
- case 'text_end': yield { type: 'block-end', index: Number(event.contentIndex), block: { type: 'text', text: String(event.content ?? '') } }; break
441
- case 'thinking_start': yield { type: 'block-start', index: Number(event.contentIndex), blockType: 'reasoning' }; break
442
- case 'thinking_delta': yield { type: 'reasoning-delta', index: Number(event.contentIndex), text: String(event.delta ?? '') }; break
443
- case 'thinking_end': yield { type: 'block-end', index: Number(event.contentIndex), block: { type: 'reasoning', text: String(event.content ?? '') } }; break
444
- case 'toolcall_start': {
445
- const partial = /** @type {UnknownRecord | undefined} */ (isObject(event.partial) ? event.partial : undefined)
446
- const content = Array.isArray(partial?.content) ? partial.content : []
447
- const block = /** @type {UnknownRecord | undefined} */ (content[Number(event.contentIndex)])
448
- toolIds.set(Number(event.contentIndex), { id: String(block?.id ?? ''), name: String(block?.name ?? '') })
449
- yield { type: 'block-start', index: Number(event.contentIndex), blockType: 'tool-call' }
450
- break
451
- }
452
- case 'toolcall_delta': {
453
- const known = toolIds.get(Number(event.contentIndex)) ?? { id: '', name: '' }
454
- yield { type: 'tool-call-delta', index: Number(event.contentIndex), id: known.id, ...(known.name ? { name: known.name } : {}), argumentsDelta: String(event.delta ?? '') }
455
- break
456
- }
457
- case 'toolcall_end': {
458
- const call = /** @type {UnknownRecord} */ (isObject(event.toolCall) ? event.toolCall : {})
459
- yield { type: 'block-end', index: Number(event.contentIndex), block: { type: 'tool-call', id: String(call.id ?? ''), name: String(call.name ?? ''), arguments: rawArguments(call.arguments) } }
460
- break
461
- }
462
- case 'done': {
463
- const message = /** @type {UnknownRecord} */ (isObject(event.message) ? event.message : {})
464
- yield { type: 'usage', usage: dshUsage(message.usage) }
465
- const reason = successfulFinish(message)
466
- const replay = reason.kind === 'error' ? undefined : replayState(message)
467
- yield { type: 'finish', reason, ...(replay === undefined ? {} : { replayState: replay }) }
468
- return
469
- }
470
- case 'error': {
471
- const message = /** @type {UnknownRecord} */ (isObject(event.error) ? event.error : {})
472
- yield { type: 'usage', usage: dshUsage(message.usage) }
473
- const failure = /** @type {ManagedFailure} */ (isObject(message.__lcxFailure) ? message.__lcxFailure : managedFailure(Object.assign(new Error(String(message.errorMessage ?? 'Responses stream failed')), { code: message.stopReason === 'aborted' ? 'LCX_ABORTED' : undefined }), signal))
474
- yield { type: 'finish', reason: failure.code === 'ABORTED' ? { kind: 'aborted', failure } : { kind: 'error', failure } }
475
- return
476
- }
477
- default: break
854
+ const toolIds = new Map();
855
+ for await (const event of events) {
856
+ switch (event.type) {
857
+ case "start":
858
+ break;
859
+ case "text_start":
860
+ yield {
861
+ type: "block-start",
862
+ index: Number(event.contentIndex),
863
+ blockType: "text",
864
+ };
865
+ break;
866
+ case "text_delta":
867
+ yield {
868
+ type: "text-delta",
869
+ index: Number(event.contentIndex),
870
+ text: String(event.delta ?? ""),
871
+ };
872
+ break;
873
+ case "text_end":
874
+ yield {
875
+ type: "block-end",
876
+ index: Number(event.contentIndex),
877
+ block: { type: "text", text: String(event.content ?? "") },
878
+ };
879
+ break;
880
+ case "thinking_start":
881
+ yield {
882
+ type: "block-start",
883
+ index: Number(event.contentIndex),
884
+ blockType: "reasoning",
885
+ };
886
+ break;
887
+ case "thinking_delta":
888
+ yield {
889
+ type: "reasoning-delta",
890
+ index: Number(event.contentIndex),
891
+ text: String(event.delta ?? ""),
892
+ };
893
+ break;
894
+ case "thinking_end":
895
+ yield {
896
+ type: "block-end",
897
+ index: Number(event.contentIndex),
898
+ block: { type: "reasoning", text: String(event.content ?? "") },
899
+ };
900
+ break;
901
+ case "toolcall_start": {
902
+ const partial = /** @type {UnknownRecord | undefined} */ isObject(event.partial)
903
+ ? event.partial
904
+ : undefined;
905
+ const content = Array.isArray(partial?.content) ? partial.content : [];
906
+ const item = content[Number(event.contentIndex)];
907
+ const block = isObject(item) ? item : undefined;
908
+ toolIds.set(Number(event.contentIndex), {
909
+ id: String(block?.id ?? ""),
910
+ name: String(block?.name ?? ""),
911
+ });
912
+ yield {
913
+ type: "block-start",
914
+ index: Number(event.contentIndex),
915
+ blockType: "tool-call",
916
+ };
917
+ break;
918
+ }
919
+ case "toolcall_delta": {
920
+ const known = toolIds.get(Number(event.contentIndex)) ?? {
921
+ id: "",
922
+ name: "",
923
+ };
924
+ yield {
925
+ type: "tool-call-delta",
926
+ index: Number(event.contentIndex),
927
+ id: ToolCallId(known.id),
928
+ ...(known.name ? { name: known.name } : {}),
929
+ argumentsDelta: String(event.delta ?? ""),
930
+ };
931
+ break;
932
+ }
933
+ case "toolcall_end": {
934
+ const call = isObject(event.toolCall)
935
+ ? event.toolCall
936
+ : {};
937
+ yield {
938
+ type: "block-end",
939
+ index: Number(event.contentIndex),
940
+ block: {
941
+ type: "tool-call",
942
+ id: ToolCallId(String(call.id ?? "")),
943
+ name: String(call.name ?? ""),
944
+ arguments: rawArguments(call.arguments),
945
+ },
946
+ };
947
+ break;
948
+ }
949
+ case "done": {
950
+ const message = isObject(event.message)
951
+ ? event.message
952
+ : {};
953
+ yield { type: "usage", usage: dshUsage(message.usage) };
954
+ const reason = successfulFinish(message);
955
+ const replay = reason.kind === "error" ? undefined : replayState(message);
956
+ yield {
957
+ type: "finish",
958
+ reason,
959
+ ...(replay === undefined ? {} : { replayState: replay }),
960
+ };
961
+ return;
962
+ }
963
+ case "error": {
964
+ const message = isObject(event.error)
965
+ ? event.error
966
+ : {};
967
+ yield { type: "usage", usage: dshUsage(message.usage) };
968
+ const failure = isManagedFailure(message.__lcxFailure)
969
+ ? message.__lcxFailure
970
+ : managedFailure(Object.assign(new Error(String(message.errorMessage ?? "Responses stream failed")), {
971
+ code: message.stopReason === "aborted"
972
+ ? "LCX_ABORTED"
973
+ : undefined,
974
+ }), signal);
975
+ const normalizedFailure = {
976
+ message: String(failure.message ?? "Responses stream failed"),
977
+ code: String(failure.code ?? "RESPONSES_ERROR"),
978
+ ...(typeof failure.status === "number" ? { status: failure.status } : {}),
979
+ ...(typeof failure.providerRetryAfterMs === "number"
980
+ ? { providerRetryAfterMs: failure.providerRetryAfterMs }
981
+ : {}),
982
+ };
983
+ yield {
984
+ type: "finish",
985
+ reason: normalizedFailure.code === "ABORTED"
986
+ ? { kind: "aborted", failure: normalizedFailure }
987
+ : { kind: "error", failure: normalizedFailure },
988
+ };
989
+ return;
990
+ }
991
+ default:
992
+ break;
993
+ }
478
994
  }
479
- }
480
- yield managedFailureChunk(Object.assign(new Error('Responses event stream ended without done/error'), { code: 'LCX_INVALID_SSE' }), signal)
995
+ yield managedFailureChunk(Object.assign(new Error("Responses event stream ended without done/error"), { code: "LCX_INVALID_SSE" }), signal);
481
996
  }
482
-
483
997
  /**
484
998
  * Send one LCX-owned OpenAI Responses request. Ordinary and replay use one provider attempt;
485
999
  * the DSH agent recovery layer remains the visible retry owner.
@@ -496,44 +1010,59 @@ async function* toDshChunks(events, signal) {
496
1010
  * @param {number} [options.maxAttempts]
497
1011
  * @param {number} [options.maxResponseBytes]
498
1012
  */
499
- export async function* streamResponsesRequest({ baseURL, provider, model, piModel, body, grammarToolInputProperties, headers, signal, timeoutMs, maxAttempts = 1, maxResponseBytes }) {
500
- try {
501
- const response = await fetchSseWithRetry(`${String(baseURL).replace(/\/+$/u, '')}/responses`, body, headers, signal, timeoutMs, { maxAttempts, maxResponseBytes })
502
- /** @type {import('@earendil-works/pi-ai').AssistantMessage & { __lcxFailure?: ManagedFailure }} */
503
- const output = {
504
- role: 'assistant', content: [], api: 'openai-responses', provider, model,
505
- usage: emptyUsage(), stopReason: 'pending', timestamp: Date.now(),
1013
+ export async function* streamResponsesRequest({ baseURL, provider, model, piModel, body, grammarToolInputProperties, headers, signal, timeoutMs, maxAttempts = 1, maxResponseBytes, }) {
1014
+ try {
1015
+ const response = await fetchSseWithRetry(`${String(baseURL).replace(/\/+$/u, "")}/responses`, body, headers, signal, timeoutMs, { maxAttempts, maxResponseBytes });
1016
+ const output = {
1017
+ role: "assistant",
1018
+ content: [],
1019
+ api: "openai-responses",
1020
+ provider,
1021
+ model,
1022
+ usage: emptyUsage(),
1023
+ stopReason: "pending",
1024
+ timestamp: Date.now(),
1025
+ };
1026
+ const piEvents = createAssistantMessageEventStream();
1027
+ const wireMeta = {};
1028
+ const parser = (async () => {
1029
+ try {
1030
+ piEvents.push({ type: "start", partial: output });
1031
+ await processResponsesStream(validatedResponseEvents(normalizedResponseEvents(responseEvents(response, { signal, maxResponseBytes }), wireMeta)), output, piEvents, piModel, { grammarToolInputProperties });
1032
+ if (typeof wireMeta.responseModel === "string" &&
1033
+ wireMeta.responseModel.length > 0)
1034
+ output.responseModel = wireMeta.responseModel;
1035
+ if (signal?.aborted)
1036
+ throw (signal.reason ??
1037
+ Object.assign(new Error("request aborted"), { code: "LCX_ABORTED" }));
1038
+ if (output.stopReason === "pending")
1039
+ throw Object.assign(new Error("Responses stream ended without a stop reason"), { code: "LCX_INVALID_SSE" });
1040
+ if (output.stopReason === "aborted" || output.stopReason === "error")
1041
+ throw new Error("Responses stream ended in failure");
1042
+ piEvents.push({
1043
+ type: "done",
1044
+ reason: output.stopReason,
1045
+ message: output,
1046
+ });
1047
+ piEvents.end();
1048
+ }
1049
+ catch (error) {
1050
+ output.stopReason = signal?.aborted ? "aborted" : "error";
1051
+ output.errorMessage =
1052
+ error instanceof Error ? error.message : "Responses stream failed";
1053
+ output.__lcxFailure = managedFailure(error, signal);
1054
+ piEvents.push({
1055
+ type: "error",
1056
+ reason: /** @type {'aborted' | 'error'} */ output.stopReason,
1057
+ error: output,
1058
+ });
1059
+ piEvents.end();
1060
+ }
1061
+ })();
1062
+ yield* toDshChunks(piEvents, signal);
1063
+ await parser;
1064
+ }
1065
+ catch (error) {
1066
+ yield managedFailureChunk(error, signal);
506
1067
  }
507
- const piEvents = new PiEventQueue()
508
- /** @type {{ responseModel?: string }} */
509
- const wireMeta = {}
510
- const parser = (async () => {
511
- try {
512
- piEvents.push({ type: 'start', partial: output })
513
- await processResponsesStream(
514
- /** @type {AsyncIterable<ResponseStreamEvent>} */ (/** @type {unknown} */ (normalizedResponseEvents(responseEvents(response, { signal, maxResponseBytes }), wireMeta))),
515
- output,
516
- /** @type {any} */ (piEvents),
517
- /** @type {any} */ (piModel),
518
- { grammarToolInputProperties },
519
- )
520
- if (typeof wireMeta.responseModel === 'string' && wireMeta.responseModel.length > 0) output.responseModel = wireMeta.responseModel
521
- if (signal?.aborted) throw signal.reason ?? Object.assign(new Error('request aborted'), { code: 'LCX_ABORTED' })
522
- if (output.stopReason === 'pending') throw Object.assign(new Error('Responses stream ended without a stop reason'), { code: 'LCX_INVALID_SSE' })
523
- if (output.stopReason === 'aborted' || output.stopReason === 'error') throw new Error('Responses stream ended in failure')
524
- piEvents.push({ type: 'done', reason: /** @type {'stop' | 'length' | 'toolUse' | 'deferred'} */ (output.stopReason), message: output })
525
- piEvents.end()
526
- } catch (error) {
527
- output.stopReason = signal?.aborted ? 'aborted' : 'error'
528
- output.errorMessage = error instanceof Error ? error.message : 'Responses stream failed'
529
- output.__lcxFailure = managedFailure(error, signal)
530
- piEvents.push({ type: 'error', reason: /** @type {'aborted' | 'error'} */ (output.stopReason), error: output })
531
- piEvents.end()
532
- }
533
- })()
534
- yield* toDshChunks(piEvents, signal)
535
- await parser
536
- } catch (error) {
537
- yield managedFailureChunk(error, signal)
538
- }
539
1068
  }