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.
- package/README.md +116 -202
- package/cordis.patch.yml +3 -20
- package/lib/client.js +273 -146
- package/lib/compact-v2.js +218 -199
- package/lib/dsh-compat.js +227 -100
- package/lib/dsh-responses.js +445 -277
- package/lib/index.js +851 -757
- package/lib/json-store.js +50 -31
- package/lib/native-checkpoint.js +520 -194
- package/lib/responses-request.js +106 -121
- package/lib/responses-stream.js +972 -443
- package/lib/route.js +229 -355
- package/lib/service-mutex.js +73 -64
- package/lib/token-budget.js +176 -108
- package/lib/transport.js +277 -67
- package/lib/types/client/index.d.ts +6 -0
- package/lib/types/compact-v2.d.ts +104 -0
- package/lib/types/dsh-compat.d.ts +78 -0
- package/lib/types/dsh-responses.d.ts +82 -0
- package/lib/types/index.d.ts +83 -0
- package/lib/types/json-store.d.ts +10 -0
- package/lib/types/native-checkpoint.d.ts +213 -0
- package/lib/types/responses-request.d.ts +58 -0
- package/lib/types/responses-stream.d.ts +51 -0
- package/lib/types/route.d.ts +132 -0
- package/lib/types/service-mutex.d.ts +14 -0
- package/lib/types/token-budget.d.ts +50 -0
- package/lib/types/transport.d.ts +20 -0
- package/lib/types/web-run-output.d.ts +29 -0
- package/lib/types/web-search-alpha.d.ts +286 -0
- package/lib/types/web-search-capability.d.ts +26 -0
- package/lib/types/web-search-hosted.d.ts +246 -0
- package/lib/types/web-search-ref-store.d.ts +22 -0
- package/lib/web-run-output.js +167 -18
- package/lib/web-search-alpha.js +865 -163
- package/lib/web-search-capability.js +55 -65
- package/lib/web-search-hosted.js +210 -32
- package/lib/web-search-ref-store.js +63 -59
- package/package.json +79 -27
- package/ARCHITECTURE.md +0 -117
- package/CHANGELOG.md +0 -224
- package/README_EN.md +0 -277
- package/assets/dsh-lcx-codex-banner.jpg +0 -0
- package/lib/legacy-v3.js +0 -20
- package/lib/responses-replay.js +0 -68
- package/scripts/probe-alpha.mjs +0 -43
- package/scripts/validate-dsh-schema.mjs +0 -31
package/lib/responses-stream.js
CHANGED
|
@@ -1,239 +1,496 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
|
|
3
|
-
import { processResponsesStream } from
|
|
4
|
-
import {
|
|
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
|
-
|
|
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) {
|
|
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) {
|
|
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
|
-
|
|
56
|
-
|
|
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
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
130
|
-
|
|
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
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
dataLines = []
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
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
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
-
|
|
195
|
-
|
|
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
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
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
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
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
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
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
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
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
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
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
|
-
|
|
382
|
-
|
|
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
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
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
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
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<
|
|
850
|
+
* @param {AsyncIterable<AssistantMessageEvent>} events
|
|
430
851
|
* @param {AbortSignal} [signal]
|
|
431
852
|
*/
|
|
432
853
|
async function* toDshChunks(events, signal) {
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
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
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
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
|
}
|