@nones/agentflow-opencode 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +114 -2
- package/package.json +36 -4
- package/src/adapter.ts +996 -0
- package/src/config.ts +268 -0
- package/src/errors.ts +95 -0
- package/src/http.ts +169 -0
- package/src/index.ts +31 -0
- package/src/normalize.ts +908 -0
- package/src/sse.ts +105 -0
- package/src/types.ts +204 -0
package/src/normalize.ts
ADDED
|
@@ -0,0 +1,908 @@
|
|
|
1
|
+
import { OpenCodeConfigError } from "./errors";
|
|
2
|
+
import type { ModelRef, RateLimitInfo } from "./types";
|
|
3
|
+
|
|
4
|
+
export type JsonRecord = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
export function isRecord(value: unknown): value is JsonRecord {
|
|
7
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function asString(value: unknown): string | undefined {
|
|
11
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function asNumber(value: unknown): number | undefined {
|
|
15
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
16
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
17
|
+
const parsed = Number(value);
|
|
18
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
19
|
+
}
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The native API sometimes returns bare data and sometimes wraps it in
|
|
25
|
+
* `{ data: ... }` (or a nested `result`). Unwrap only object/array payloads so
|
|
26
|
+
* a legitimate `data` field on an object is not destroyed accidentally.
|
|
27
|
+
*/
|
|
28
|
+
export function unwrapData(value: unknown, depth = 0): unknown {
|
|
29
|
+
if (depth > 5 || !isRecord(value)) return value;
|
|
30
|
+
const wrapped = value.data;
|
|
31
|
+
if (isRecord(wrapped) || Array.isArray(wrapped)) {
|
|
32
|
+
return unwrapData(wrapped, depth + 1);
|
|
33
|
+
}
|
|
34
|
+
const result = value.result;
|
|
35
|
+
if (isRecord(result) || Array.isArray(result)) {
|
|
36
|
+
return unwrapData(result, depth + 1);
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Extract a session id from direct or wrapped session creation responses. */
|
|
42
|
+
export function extractSessionId(
|
|
43
|
+
value: unknown,
|
|
44
|
+
depth = 0,
|
|
45
|
+
): string | undefined {
|
|
46
|
+
if (depth > 5) return undefined;
|
|
47
|
+
if (Array.isArray(value)) return undefined;
|
|
48
|
+
if (!isRecord(value)) return undefined;
|
|
49
|
+
|
|
50
|
+
const direct =
|
|
51
|
+
asString(value.id) ??
|
|
52
|
+
asString(value.sessionID) ??
|
|
53
|
+
asString(value.sessionId);
|
|
54
|
+
if (direct) return direct;
|
|
55
|
+
|
|
56
|
+
for (const key of ["session", "data", "result", "value"]) {
|
|
57
|
+
const nested = value[key];
|
|
58
|
+
const found = extractSessionId(nested, depth + 1);
|
|
59
|
+
if (found) return found;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function extractSession(
|
|
65
|
+
value: unknown,
|
|
66
|
+
depth = 0,
|
|
67
|
+
): JsonRecord | undefined {
|
|
68
|
+
if (depth > 5 || !isRecord(value)) return undefined;
|
|
69
|
+
const candidate = unwrapData(value);
|
|
70
|
+
if (!isRecord(candidate)) return undefined;
|
|
71
|
+
if (asString(candidate.id) || asString(candidate.sessionID)) {
|
|
72
|
+
return candidate;
|
|
73
|
+
}
|
|
74
|
+
for (const key of ["session", "data", "result", "value"]) {
|
|
75
|
+
const found = extractSession(candidate[key], depth + 1);
|
|
76
|
+
if (found) return found;
|
|
77
|
+
}
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function parseModelRef(value: unknown, source = "model"): ModelRef {
|
|
82
|
+
if (isRecord(value)) {
|
|
83
|
+
const providerID =
|
|
84
|
+
asString(value.providerID) ??
|
|
85
|
+
asString(value.providerId) ??
|
|
86
|
+
asString(value.provider);
|
|
87
|
+
const id =
|
|
88
|
+
asString(value.id) ??
|
|
89
|
+
asString(value.modelID) ??
|
|
90
|
+
asString(value.modelId) ??
|
|
91
|
+
asString(value.model);
|
|
92
|
+
if (providerID && id) return { providerID, id };
|
|
93
|
+
throw new OpenCodeConfigError(
|
|
94
|
+
`${source} must contain providerID and model id, received ${JSON.stringify(value)}`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
if (typeof value === "string") {
|
|
98
|
+
const trimmed = value.trim();
|
|
99
|
+
const slash = trimmed.indexOf("/");
|
|
100
|
+
const colon = trimmed.indexOf(":");
|
|
101
|
+
const separator = slash >= 0 ? slash : colon;
|
|
102
|
+
if (separator > 0 && separator < trimmed.length - 1) {
|
|
103
|
+
return {
|
|
104
|
+
providerID: trimmed.slice(0, separator),
|
|
105
|
+
id: trimmed.slice(separator + 1),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
throw new OpenCodeConfigError(
|
|
110
|
+
`${source} must be a concrete model such as "provider/model", received ${String(value)}`,
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export function tryParseModelRef(
|
|
115
|
+
value: unknown,
|
|
116
|
+
source = "model",
|
|
117
|
+
): ModelRef | undefined {
|
|
118
|
+
try {
|
|
119
|
+
return parseModelRef(value, source);
|
|
120
|
+
} catch {
|
|
121
|
+
return undefined;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function modelToString(model: ModelRef): string {
|
|
126
|
+
return `${model.providerID}/${model.id}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function modelsEqual(left: ModelRef, right: ModelRef): boolean {
|
|
130
|
+
return left.providerID === right.providerID && left.id === right.id;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Read a model reference from a native session object. */
|
|
134
|
+
export function extractSessionModel(
|
|
135
|
+
session: unknown,
|
|
136
|
+
): ModelRef | string | undefined {
|
|
137
|
+
if (!isRecord(session)) return undefined;
|
|
138
|
+
const candidates: unknown[] = [
|
|
139
|
+
session.model,
|
|
140
|
+
session.modelRef,
|
|
141
|
+
session.defaultModel,
|
|
142
|
+
isRecord(session.config) ? session.config.model : undefined,
|
|
143
|
+
isRecord(session.metadata) ? session.metadata.model : undefined,
|
|
144
|
+
session.modelID,
|
|
145
|
+
];
|
|
146
|
+
for (const candidate of candidates) {
|
|
147
|
+
if (candidate === undefined || candidate === null) continue;
|
|
148
|
+
if (typeof candidate === "string") return candidate;
|
|
149
|
+
if (isRecord(candidate)) {
|
|
150
|
+
const parsed = tryParseModelRef(candidate, "session.model");
|
|
151
|
+
if (parsed) return parsed;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return undefined;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export function sessionModelMatches(
|
|
158
|
+
observed: ModelRef | string | undefined,
|
|
159
|
+
expected: ModelRef,
|
|
160
|
+
): boolean | undefined {
|
|
161
|
+
if (observed === undefined) return undefined;
|
|
162
|
+
if (typeof observed === "string") {
|
|
163
|
+
const parsed = tryParseModelRef(observed, "session.model");
|
|
164
|
+
return parsed
|
|
165
|
+
? modelsEqual(parsed, expected)
|
|
166
|
+
: observed === modelToString(expected);
|
|
167
|
+
}
|
|
168
|
+
return modelsEqual(observed, expected);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Flatten the message-list response shapes into native message records. */
|
|
172
|
+
export function extractMessages(value: unknown, depth = 0): JsonRecord[] {
|
|
173
|
+
if (depth > 5) return [];
|
|
174
|
+
if (Array.isArray(value)) {
|
|
175
|
+
return value.filter(isRecord);
|
|
176
|
+
}
|
|
177
|
+
if (!isRecord(value)) return [];
|
|
178
|
+
const unwrapped = unwrapData(value);
|
|
179
|
+
if (unwrapped !== value) {
|
|
180
|
+
const nested = extractMessages(unwrapped, depth + 1);
|
|
181
|
+
if (nested.length > 0) return nested;
|
|
182
|
+
}
|
|
183
|
+
for (const key of ["messages", "items", "list", "data", "value"]) {
|
|
184
|
+
if (!(key in value)) continue;
|
|
185
|
+
const nested = extractMessages(value[key], depth + 1);
|
|
186
|
+
if (nested.length > 0) return nested;
|
|
187
|
+
}
|
|
188
|
+
return [];
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function messageId(message: unknown): string | undefined {
|
|
192
|
+
if (!isRecord(message)) return undefined;
|
|
193
|
+
return (
|
|
194
|
+
asString(message.id) ??
|
|
195
|
+
asString(message.messageID) ??
|
|
196
|
+
asString(message.messageId)
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function messageRole(message: unknown): string | undefined {
|
|
201
|
+
if (!isRecord(message)) return undefined;
|
|
202
|
+
return asString(message.type) ?? asString(message.role);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
export function isAssistantMessage(message: unknown): boolean {
|
|
206
|
+
return messageRole(message)?.toLowerCase() === "assistant";
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function isUserMessage(message: unknown): boolean {
|
|
210
|
+
return messageRole(message)?.toLowerCase() === "user";
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export function messageCreatedAt(message: unknown): number | undefined {
|
|
214
|
+
if (!isRecord(message)) return undefined;
|
|
215
|
+
const time = message.time;
|
|
216
|
+
if (isRecord(time)) {
|
|
217
|
+
const created =
|
|
218
|
+
asNumber(time.created) ??
|
|
219
|
+
asNumber(time.createdAt) ??
|
|
220
|
+
asNumber(time.start);
|
|
221
|
+
if (created !== undefined) return created;
|
|
222
|
+
}
|
|
223
|
+
return (
|
|
224
|
+
asNumber(message.createdAt) ??
|
|
225
|
+
asNumber(message.created) ??
|
|
226
|
+
asNumber(message.timestamp) ??
|
|
227
|
+
asNumber(message.time)
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
export function messageTerminal(message: unknown): boolean {
|
|
232
|
+
if (!isRecord(message)) return false;
|
|
233
|
+
if (isIntermediateToolStep(message)) return false;
|
|
234
|
+
const time = message.time;
|
|
235
|
+
if (
|
|
236
|
+
isRecord(time) &&
|
|
237
|
+
(asNumber(time.completed) !== undefined || time.completed === true)
|
|
238
|
+
) {
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
if (message.completed === true) return true;
|
|
242
|
+
if (asNumber(message.completedAt) !== undefined) return true;
|
|
243
|
+
const status = asString(message.status) ?? asString(message.state);
|
|
244
|
+
if (status && statusFromToken(status) !== undefined) return true;
|
|
245
|
+
if (
|
|
246
|
+
asString(message.finishReason) ||
|
|
247
|
+
asString(message.stopReason) ||
|
|
248
|
+
asString(message.finish)
|
|
249
|
+
) {
|
|
250
|
+
return true;
|
|
251
|
+
}
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* A native assistant step that ended because it requested tools is not the
|
|
257
|
+
* terminal assistant answer, even when it carries a completed timestamp.
|
|
258
|
+
*/
|
|
259
|
+
export function isIntermediateToolStep(message: unknown): boolean {
|
|
260
|
+
if (!isRecord(message)) return false;
|
|
261
|
+
for (const key of [
|
|
262
|
+
"finish",
|
|
263
|
+
"finishReason",
|
|
264
|
+
"finish_reason",
|
|
265
|
+
"stopReason",
|
|
266
|
+
"stop_reason",
|
|
267
|
+
"status",
|
|
268
|
+
"state",
|
|
269
|
+
]) {
|
|
270
|
+
const value = message[key];
|
|
271
|
+
if (typeof value !== "string") continue;
|
|
272
|
+
if (isToolStepToken(value)) return true;
|
|
273
|
+
}
|
|
274
|
+
const nested = message.message;
|
|
275
|
+
if (
|
|
276
|
+
nested !== undefined &&
|
|
277
|
+
nested !== message &&
|
|
278
|
+
isIntermediateToolStep(nested)
|
|
279
|
+
) {
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function isToolStepToken(value: string): boolean {
|
|
286
|
+
const normalized = value.toLowerCase().replace(/[\s_-]+/g, "-");
|
|
287
|
+
return (
|
|
288
|
+
normalized === "tool-calls" ||
|
|
289
|
+
normalized === "tool-use" ||
|
|
290
|
+
normalized === "tool" ||
|
|
291
|
+
normalized === "tools"
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
export function messageErrorText(message: unknown): string | undefined {
|
|
296
|
+
if (!isRecord(message)) return undefined;
|
|
297
|
+
const error = message.error;
|
|
298
|
+
if (typeof error === "string") return error;
|
|
299
|
+
if (isRecord(error)) {
|
|
300
|
+
return (
|
|
301
|
+
asString(error.message) ??
|
|
302
|
+
asString(error.type) ??
|
|
303
|
+
asString(error.name) ??
|
|
304
|
+
JSON.stringify(error)
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
return asString(message.errorMessage) ?? asString(message.failure);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export interface TerminalInfo {
|
|
311
|
+
status: "succeeded" | "failed" | "interrupted";
|
|
312
|
+
error?: string;
|
|
313
|
+
source: "event" | "wait" | "message";
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Derive a terminal status from a completed assistant message. */
|
|
317
|
+
export function terminalFromMessage(
|
|
318
|
+
message: unknown,
|
|
319
|
+
): TerminalInfo | undefined {
|
|
320
|
+
if (!messageTerminal(message)) return undefined;
|
|
321
|
+
const error = messageErrorText(message);
|
|
322
|
+
if (error) return { status: "failed", error, source: "message" };
|
|
323
|
+
const token = isRecord(message)
|
|
324
|
+
? (asString(message.status) ?? asString(message.state))
|
|
325
|
+
: undefined;
|
|
326
|
+
const status = statusFromToken(token);
|
|
327
|
+
if (status === "failed" || status === "interrupted") {
|
|
328
|
+
return { status, source: "message" };
|
|
329
|
+
}
|
|
330
|
+
return { status: "succeeded", source: "message" };
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** Extract text from native message parts, content, or a plain field. */
|
|
334
|
+
export function messageText(message: unknown): string {
|
|
335
|
+
if (!isRecord(message)) return "";
|
|
336
|
+
const pieces: string[] = [];
|
|
337
|
+
|
|
338
|
+
const appendText = (value: unknown) => {
|
|
339
|
+
if (typeof value === "string") pieces.push(value);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
appendText(message.text);
|
|
343
|
+
appendText(message.content);
|
|
344
|
+
const appendParts = (parts: unknown) => {
|
|
345
|
+
if (!Array.isArray(parts)) return;
|
|
346
|
+
for (const part of parts) {
|
|
347
|
+
if (typeof part === "string") {
|
|
348
|
+
pieces.push(part);
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
if (!isRecord(part)) continue;
|
|
352
|
+
if (asString(part.type)?.toLowerCase() === "text") {
|
|
353
|
+
appendText(part.text);
|
|
354
|
+
appendText(part.content);
|
|
355
|
+
appendText(part.value);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
appendParts(message.parts);
|
|
360
|
+
appendParts(message.content);
|
|
361
|
+
if (isRecord(message.message)) {
|
|
362
|
+
const nested = messageText(message.message);
|
|
363
|
+
if (nested) pieces.push(nested);
|
|
364
|
+
}
|
|
365
|
+
return pieces.filter((piece) => piece.length > 0).join("");
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
export function messageTurnKeys(message: unknown): string[] {
|
|
369
|
+
if (!isRecord(message)) return [];
|
|
370
|
+
const keys: string[] = [];
|
|
371
|
+
for (const key of [
|
|
372
|
+
"parentID",
|
|
373
|
+
"parentId",
|
|
374
|
+
"turnID",
|
|
375
|
+
"turnId",
|
|
376
|
+
"userMessageID",
|
|
377
|
+
"userMessageId",
|
|
378
|
+
"receiptID",
|
|
379
|
+
"receiptId",
|
|
380
|
+
"inReplyTo",
|
|
381
|
+
]) {
|
|
382
|
+
const value = asString(message[key]);
|
|
383
|
+
if (value) keys.push(value);
|
|
384
|
+
}
|
|
385
|
+
return keys;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
export interface MessageScope {
|
|
389
|
+
sessionId: string;
|
|
390
|
+
turnId: string;
|
|
391
|
+
receiptId?: string;
|
|
392
|
+
baselineIds: ReadonlySet<string>;
|
|
393
|
+
baselineAt: number;
|
|
394
|
+
acceptedAt: number;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Select only assistant messages that can be attributed to this turn. Native
|
|
399
|
+
* sessions are per agent, but a goal session can host several turns, so the
|
|
400
|
+
* baseline ids, receipt association, and creation time matter.
|
|
401
|
+
*/
|
|
402
|
+
export function assistantMessagesForScope(
|
|
403
|
+
messages: readonly JsonRecord[],
|
|
404
|
+
scope: MessageScope,
|
|
405
|
+
): JsonRecord[] {
|
|
406
|
+
const selected: JsonRecord[] = [];
|
|
407
|
+
for (const message of messages) {
|
|
408
|
+
if (!isAssistantMessage(message)) continue;
|
|
409
|
+
const id = messageId(message);
|
|
410
|
+
if (id && scope.baselineIds.has(id)) continue;
|
|
411
|
+
|
|
412
|
+
const sessionID =
|
|
413
|
+
asString(message.sessionID) ?? asString(message.sessionId);
|
|
414
|
+
if (sessionID && sessionID !== scope.sessionId) continue;
|
|
415
|
+
|
|
416
|
+
const turnKeys = messageTurnKeys(message);
|
|
417
|
+
if (turnKeys.length > 0) {
|
|
418
|
+
const matches =
|
|
419
|
+
(scope.receiptId !== undefined && turnKeys.includes(scope.receiptId)) ||
|
|
420
|
+
turnKeys.includes(scope.turnId);
|
|
421
|
+
if (!matches) continue;
|
|
422
|
+
} else {
|
|
423
|
+
const created = messageCreatedAt(message);
|
|
424
|
+
if (created === undefined) {
|
|
425
|
+
// Without a turn link or creation time the message cannot be
|
|
426
|
+
// attributed safely, especially during crash reconciliation.
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
if (scope.acceptedAt <= 0) continue;
|
|
430
|
+
if (created < scope.acceptedAt - 1) continue;
|
|
431
|
+
}
|
|
432
|
+
selected.push(message);
|
|
433
|
+
}
|
|
434
|
+
return selected;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
export function combineAssistantText(messages: readonly JsonRecord[]): string {
|
|
438
|
+
const ordered = [...messages].sort((a, b) => {
|
|
439
|
+
const left = messageCreatedAt(a) ?? 0;
|
|
440
|
+
const right = messageCreatedAt(b) ?? 0;
|
|
441
|
+
return left - right;
|
|
442
|
+
});
|
|
443
|
+
return ordered.map((message) => messageText(message)).join("");
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
export interface NormalizedEvent {
|
|
447
|
+
type: string;
|
|
448
|
+
sessionID?: string;
|
|
449
|
+
receiptID?: string;
|
|
450
|
+
turnID?: string;
|
|
451
|
+
messageID?: string;
|
|
452
|
+
status?: string;
|
|
453
|
+
httpStatus?: number;
|
|
454
|
+
reason?: string;
|
|
455
|
+
retryAfterMs?: number;
|
|
456
|
+
text?: string;
|
|
457
|
+
error?: string;
|
|
458
|
+
time?: number;
|
|
459
|
+
data: unknown;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
export function normalizeEvent(
|
|
463
|
+
parsed: unknown,
|
|
464
|
+
eventName?: string,
|
|
465
|
+
): NormalizedEvent | undefined {
|
|
466
|
+
if (!isRecord(parsed)) {
|
|
467
|
+
const type = asString(eventName);
|
|
468
|
+
if (!type) return undefined;
|
|
469
|
+
return { type, data: parsed };
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
const properties = isRecord(parsed.properties)
|
|
473
|
+
? parsed.properties
|
|
474
|
+
: undefined;
|
|
475
|
+
const data = isRecord(parsed.data) ? parsed.data : undefined;
|
|
476
|
+
const payload = properties ?? data ?? parsed;
|
|
477
|
+
|
|
478
|
+
const type =
|
|
479
|
+
asString(eventName) ??
|
|
480
|
+
asString(parsed.type) ??
|
|
481
|
+
asString(parsed.event) ??
|
|
482
|
+
asString(parsed.name) ??
|
|
483
|
+
asString(payload.type);
|
|
484
|
+
if (!type) return undefined;
|
|
485
|
+
|
|
486
|
+
const sessionID =
|
|
487
|
+
asString(payload.sessionID) ??
|
|
488
|
+
asString(payload.sessionId) ??
|
|
489
|
+
(isRecord(payload.session)
|
|
490
|
+
? asString(payload.session.sessionID)
|
|
491
|
+
: undefined) ??
|
|
492
|
+
(isRecord(payload.session) ? asString(payload.session.id) : undefined) ??
|
|
493
|
+
asString(parsed.sessionID) ??
|
|
494
|
+
asString(parsed.sessionId);
|
|
495
|
+
|
|
496
|
+
const receiptObject = isRecord(payload.receipt) ? payload.receipt : undefined;
|
|
497
|
+
const receiptID =
|
|
498
|
+
asString(receiptObject?.id) ??
|
|
499
|
+
asString(payload.receiptID) ??
|
|
500
|
+
asString(payload.receiptId) ??
|
|
501
|
+
(typeof payload.receipt === "string" ? payload.receipt : undefined) ??
|
|
502
|
+
asString(payload.userMessageID) ??
|
|
503
|
+
asString(payload.userMessageId) ??
|
|
504
|
+
asString(
|
|
505
|
+
isRecord(payload.userMessage) ? payload.userMessage.id : undefined,
|
|
506
|
+
);
|
|
507
|
+
|
|
508
|
+
const turnID =
|
|
509
|
+
asString(payload.turnID) ??
|
|
510
|
+
asString(payload.turnId) ??
|
|
511
|
+
asString(payload.turn);
|
|
512
|
+
const messageID =
|
|
513
|
+
asString(payload.messageID) ??
|
|
514
|
+
asString(payload.messageId) ??
|
|
515
|
+
asString(payload.assistantMessageID) ??
|
|
516
|
+
asString(payload.assistantMessageId);
|
|
517
|
+
|
|
518
|
+
const execution = isRecord(payload.execution) ? payload.execution : undefined;
|
|
519
|
+
const errorObject = isRecord(payload.error) ? payload.error : undefined;
|
|
520
|
+
const statusSource =
|
|
521
|
+
payload.status ?? payload.state ?? execution?.status ?? execution?.state;
|
|
522
|
+
const status = asString(statusSource);
|
|
523
|
+
const httpStatus =
|
|
524
|
+
asNumber(statusSource) ??
|
|
525
|
+
asNumber(payload.statusCode) ??
|
|
526
|
+
asNumber(payload.code) ??
|
|
527
|
+
asNumber(errorObject?.status) ??
|
|
528
|
+
asNumber(errorObject?.code);
|
|
529
|
+
|
|
530
|
+
const reason =
|
|
531
|
+
asString(payload.reason) ??
|
|
532
|
+
asString(payload.rateLimitReason) ??
|
|
533
|
+
asString(errorObject?.type);
|
|
534
|
+
|
|
535
|
+
const retryAfterSeconds =
|
|
536
|
+
asNumber(payload.retryAfterSeconds) ??
|
|
537
|
+
asNumber(payload.retry_after_seconds);
|
|
538
|
+
const retryAfterMs =
|
|
539
|
+
asNumber(payload.retryAfterMs) ??
|
|
540
|
+
asNumber(payload.retry_after_ms) ??
|
|
541
|
+
(retryAfterSeconds !== undefined ? retryAfterSeconds * 1_000 : undefined) ??
|
|
542
|
+
asNumber(payload.retryAfter) ??
|
|
543
|
+
asNumber(payload.retry_after);
|
|
544
|
+
|
|
545
|
+
const text =
|
|
546
|
+
asString(payload.text) ??
|
|
547
|
+
asString(isRecord(payload.message) ? payload.message.text : undefined) ??
|
|
548
|
+
asString(
|
|
549
|
+
isRecord(payload.assistantMessage)
|
|
550
|
+
? payload.assistantMessage.text
|
|
551
|
+
: undefined,
|
|
552
|
+
);
|
|
553
|
+
|
|
554
|
+
const error =
|
|
555
|
+
typeof payload.error === "string"
|
|
556
|
+
? payload.error
|
|
557
|
+
: isRecord(payload.error)
|
|
558
|
+
? (asString(payload.error.message) ?? asString(payload.error.type))
|
|
559
|
+
: asString(payload.errorMessage);
|
|
560
|
+
|
|
561
|
+
let time: number | undefined;
|
|
562
|
+
for (const candidate of [
|
|
563
|
+
parsed.time,
|
|
564
|
+
payload.time,
|
|
565
|
+
parsed.timestamp,
|
|
566
|
+
payload.timestamp,
|
|
567
|
+
]) {
|
|
568
|
+
if (isRecord(candidate)) {
|
|
569
|
+
time =
|
|
570
|
+
asNumber(candidate.completed) ??
|
|
571
|
+
asNumber(candidate.created) ??
|
|
572
|
+
asNumber(candidate.start) ??
|
|
573
|
+
asNumber(candidate.at);
|
|
574
|
+
} else {
|
|
575
|
+
time = asNumber(candidate);
|
|
576
|
+
}
|
|
577
|
+
if (time !== undefined) break;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
return {
|
|
581
|
+
type,
|
|
582
|
+
sessionID,
|
|
583
|
+
receiptID,
|
|
584
|
+
turnID,
|
|
585
|
+
messageID,
|
|
586
|
+
status,
|
|
587
|
+
httpStatus,
|
|
588
|
+
reason,
|
|
589
|
+
retryAfterMs,
|
|
590
|
+
text,
|
|
591
|
+
error,
|
|
592
|
+
time,
|
|
593
|
+
data: parsed,
|
|
594
|
+
};
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
export type TerminalStatus = "succeeded" | "failed" | "interrupted";
|
|
598
|
+
|
|
599
|
+
export function statusFromToken(
|
|
600
|
+
token: string | undefined,
|
|
601
|
+
): TerminalStatus | undefined {
|
|
602
|
+
if (!token) return undefined;
|
|
603
|
+
const value = token.toLowerCase();
|
|
604
|
+
if (value.includes("fail") || value.includes("error")) return "failed";
|
|
605
|
+
if (
|
|
606
|
+
value.includes("interrupt") ||
|
|
607
|
+
value.includes("cancel") ||
|
|
608
|
+
value.includes("abort") ||
|
|
609
|
+
value.includes("paused") ||
|
|
610
|
+
value.includes("incomplete") ||
|
|
611
|
+
value.includes("not complete") ||
|
|
612
|
+
value.includes("not_complete")
|
|
613
|
+
) {
|
|
614
|
+
return "interrupted";
|
|
615
|
+
}
|
|
616
|
+
if (
|
|
617
|
+
value.includes("complete") ||
|
|
618
|
+
value.includes("finish") ||
|
|
619
|
+
value === "done" ||
|
|
620
|
+
value === "idle" ||
|
|
621
|
+
value.includes("succeed") ||
|
|
622
|
+
value === "success" ||
|
|
623
|
+
value.includes("ended")
|
|
624
|
+
) {
|
|
625
|
+
return "succeeded";
|
|
626
|
+
}
|
|
627
|
+
return undefined;
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** Derive a terminal status from an SSE event, scoped to the current turn. */
|
|
631
|
+
export function terminalFromEvent(
|
|
632
|
+
event: NormalizedEvent,
|
|
633
|
+
scope: MessageScope,
|
|
634
|
+
): TerminalInfo | undefined {
|
|
635
|
+
if (event.sessionID && event.sessionID !== scope.sessionId) return undefined;
|
|
636
|
+
if (event.time !== undefined && event.time < scope.baselineAt - 1_000)
|
|
637
|
+
return undefined;
|
|
638
|
+
|
|
639
|
+
const explicitKeys = [event.receiptID, event.turnID].filter(
|
|
640
|
+
(value): value is string => value !== undefined,
|
|
641
|
+
);
|
|
642
|
+
if (explicitKeys.length > 0) {
|
|
643
|
+
const scoped =
|
|
644
|
+
(scope.receiptId !== undefined &&
|
|
645
|
+
explicitKeys.includes(scope.receiptId)) ||
|
|
646
|
+
explicitKeys.includes(scope.turnId);
|
|
647
|
+
if (!scoped) return undefined;
|
|
648
|
+
} else if (event.messageID && scope.baselineIds.has(event.messageID)) {
|
|
649
|
+
// An unscoped terminal event that names a message we already saw before
|
|
650
|
+
// submission belongs to an older turn.
|
|
651
|
+
return undefined;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
if (event.type.startsWith("session.inbox.")) return undefined;
|
|
655
|
+
|
|
656
|
+
const lower = event.type.toLowerCase();
|
|
657
|
+
const lastSegment = lower.slice(lower.lastIndexOf(".") + 1);
|
|
658
|
+
|
|
659
|
+
// Only an explicit session idle/error or a session.execution.* event may end
|
|
660
|
+
// a turn. Arbitrary step/tool success events are intermediate progress.
|
|
661
|
+
if (lower === "session.idle") {
|
|
662
|
+
return {
|
|
663
|
+
status: event.error ? "failed" : "succeeded",
|
|
664
|
+
...(event.error === undefined ? {} : { error: event.error }),
|
|
665
|
+
source: "event",
|
|
666
|
+
};
|
|
667
|
+
}
|
|
668
|
+
if (lower === "session.error") {
|
|
669
|
+
return { status: "failed", error: event.error, source: "event" };
|
|
670
|
+
}
|
|
671
|
+
if (!lower.startsWith("session.execution.")) return undefined;
|
|
672
|
+
if (
|
|
673
|
+
lower.includes(".step.") ||
|
|
674
|
+
lower.includes(".tool.") ||
|
|
675
|
+
lastSegment === "step" ||
|
|
676
|
+
lastSegment === "tool" ||
|
|
677
|
+
isToolStepToken(lastSegment) ||
|
|
678
|
+
(event.status !== undefined && isToolStepToken(event.status))
|
|
679
|
+
) {
|
|
680
|
+
return undefined;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
const status = statusFromToken(event.status) ?? statusFromToken(lastSegment);
|
|
684
|
+
if (!status) return undefined;
|
|
685
|
+
|
|
686
|
+
if (status === "succeeded" && event.error) {
|
|
687
|
+
return { status: "failed", error: event.error, source: "event" };
|
|
688
|
+
}
|
|
689
|
+
return { status, error: event.error, source: "event" };
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
export function terminalFromWaitBody(value: unknown): TerminalInfo | undefined {
|
|
693
|
+
const body = unwrapData(value);
|
|
694
|
+
if (!isRecord(body)) return undefined;
|
|
695
|
+
const error = body.error;
|
|
696
|
+
if (error) {
|
|
697
|
+
const message =
|
|
698
|
+
typeof error === "string"
|
|
699
|
+
? error
|
|
700
|
+
: isRecord(error)
|
|
701
|
+
? (asString(error.message) ?? asString(error.type))
|
|
702
|
+
: undefined;
|
|
703
|
+
return { status: "failed", error: message, source: "wait" };
|
|
704
|
+
}
|
|
705
|
+
const status =
|
|
706
|
+
statusFromToken(asString(body.status)) ??
|
|
707
|
+
statusFromToken(asString(body.state)) ??
|
|
708
|
+
statusFromToken(
|
|
709
|
+
asString(isRecord(body.execution) ? body.execution.status : undefined),
|
|
710
|
+
) ??
|
|
711
|
+
(body.completed === true ? "succeeded" : undefined);
|
|
712
|
+
if (!status) return undefined;
|
|
713
|
+
return { status, error: asString(body.message), source: "wait" };
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
export interface RetryScheduledSignal {
|
|
717
|
+
reason: RateLimitInfo["reason"];
|
|
718
|
+
retryAfterMs?: number;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function isRateLimitReason(
|
|
722
|
+
value: string | undefined,
|
|
723
|
+
): value is RateLimitInfo["reason"] {
|
|
724
|
+
return (
|
|
725
|
+
value === "concurrency" ||
|
|
726
|
+
value === "rate" ||
|
|
727
|
+
value === "quota" ||
|
|
728
|
+
value === "unknown"
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
/**
|
|
733
|
+
* A native `retry.scheduled` event is an observation, not a new turn. Only
|
|
734
|
+
* confirmed 429 signals are surfaced, and only as a provider event.
|
|
735
|
+
*/
|
|
736
|
+
export function retryScheduledFromEvent(
|
|
737
|
+
event: NormalizedEvent,
|
|
738
|
+
): RetryScheduledSignal | undefined {
|
|
739
|
+
if (!event.type.toLowerCase().includes("retry.scheduled")) return undefined;
|
|
740
|
+
const status = (event.status ?? "").toLowerCase();
|
|
741
|
+
const confirmed =
|
|
742
|
+
event.httpStatus === 429 ||
|
|
743
|
+
status.includes("429") ||
|
|
744
|
+
status === "rate_limited" ||
|
|
745
|
+
status === "too_many_requests";
|
|
746
|
+
if (!confirmed) return undefined;
|
|
747
|
+
|
|
748
|
+
const reason = isRateLimitReason(event.reason)
|
|
749
|
+
? event.reason
|
|
750
|
+
: classifyRateLimit(
|
|
751
|
+
event.data,
|
|
752
|
+
`${event.error ?? ""} ${event.reason ?? ""} ${event.status ?? ""}`,
|
|
753
|
+
).reason;
|
|
754
|
+
return {
|
|
755
|
+
reason,
|
|
756
|
+
...(event.retryAfterMs !== undefined
|
|
757
|
+
? { retryAfterMs: event.retryAfterMs }
|
|
758
|
+
: {}),
|
|
759
|
+
};
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
export interface ModelListing {
|
|
763
|
+
shape: "known" | "unknown";
|
|
764
|
+
models: ModelRef[];
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Best-effort parser for the official model catalogue endpoint. */
|
|
768
|
+
export function extractModelListing(value: unknown): ModelListing {
|
|
769
|
+
const body = unwrapData(value);
|
|
770
|
+
const models: ModelRef[] = [];
|
|
771
|
+
let sawShape = false;
|
|
772
|
+
|
|
773
|
+
const add = (model: ModelRef) => {
|
|
774
|
+
if (!models.some((existing) => modelsEqual(existing, model)))
|
|
775
|
+
models.push(model);
|
|
776
|
+
};
|
|
777
|
+
|
|
778
|
+
const visitEntry = (entry: unknown, providerHint?: string): boolean => {
|
|
779
|
+
if (typeof entry === "string") {
|
|
780
|
+
const parsed = tryParseModelRef(entry, "model listing");
|
|
781
|
+
if (parsed) {
|
|
782
|
+
add(parsed);
|
|
783
|
+
return true;
|
|
784
|
+
}
|
|
785
|
+
if (providerHint) {
|
|
786
|
+
add({ providerID: providerHint, id: entry });
|
|
787
|
+
return true;
|
|
788
|
+
}
|
|
789
|
+
return false;
|
|
790
|
+
}
|
|
791
|
+
if (!isRecord(entry)) return false;
|
|
792
|
+
const providerID =
|
|
793
|
+
asString(entry.providerID) ??
|
|
794
|
+
asString(entry.providerId) ??
|
|
795
|
+
asString(entry.provider) ??
|
|
796
|
+
providerHint;
|
|
797
|
+
const id =
|
|
798
|
+
asString(entry.id) ??
|
|
799
|
+
asString(entry.modelID) ??
|
|
800
|
+
asString(entry.modelId) ??
|
|
801
|
+
asString(entry.name) ??
|
|
802
|
+
asString(entry.model);
|
|
803
|
+
if (providerID && id) {
|
|
804
|
+
add({ providerID, id });
|
|
805
|
+
return true;
|
|
806
|
+
}
|
|
807
|
+
return false;
|
|
808
|
+
};
|
|
809
|
+
|
|
810
|
+
if (Array.isArray(body)) {
|
|
811
|
+
let known = 0;
|
|
812
|
+
for (const entry of body) {
|
|
813
|
+
if (visitEntry(entry)) known += 1;
|
|
814
|
+
}
|
|
815
|
+
return {
|
|
816
|
+
shape: body.length === 0 || known === body.length ? "known" : "unknown",
|
|
817
|
+
models,
|
|
818
|
+
};
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
if (!isRecord(body)) return { shape: "unknown", models };
|
|
822
|
+
|
|
823
|
+
const listCandidates: unknown[] = [
|
|
824
|
+
body.models,
|
|
825
|
+
body.items,
|
|
826
|
+
body.data,
|
|
827
|
+
body.list,
|
|
828
|
+
];
|
|
829
|
+
for (const candidate of listCandidates) {
|
|
830
|
+
if (!Array.isArray(candidate)) continue;
|
|
831
|
+
sawShape = true;
|
|
832
|
+
let known = 0;
|
|
833
|
+
for (const entry of candidate) {
|
|
834
|
+
if (visitEntry(entry)) known += 1;
|
|
835
|
+
}
|
|
836
|
+
if (known !== candidate.length) sawShape = false;
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
if (Array.isArray(body.providers)) {
|
|
840
|
+
sawShape = true;
|
|
841
|
+
for (const provider of body.providers) {
|
|
842
|
+
if (!isRecord(provider)) {
|
|
843
|
+
sawShape = false;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
const providerID =
|
|
847
|
+
asString(provider.id) ??
|
|
848
|
+
asString(provider.providerID) ??
|
|
849
|
+
asString(provider.name);
|
|
850
|
+
const providerModels = provider.models;
|
|
851
|
+
if (!providerID || !Array.isArray(providerModels)) {
|
|
852
|
+
sawShape = false;
|
|
853
|
+
continue;
|
|
854
|
+
}
|
|
855
|
+
for (const entry of providerModels) {
|
|
856
|
+
if (!visitEntry(entry, providerID)) sawShape = false;
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
return { shape: sawShape ? "known" : "unknown", models };
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
export function classifyRateLimit(
|
|
865
|
+
body: unknown,
|
|
866
|
+
rawText: string,
|
|
867
|
+
): { reason: RateLimitInfo["reason"]; message?: string } {
|
|
868
|
+
const text = `${rawText} ${JSON.stringify(body ?? "")}`.toLowerCase();
|
|
869
|
+
let message: string | undefined;
|
|
870
|
+
if (isRecord(body)) {
|
|
871
|
+
const error = body.error;
|
|
872
|
+
if (typeof error === "string") message = error;
|
|
873
|
+
else if (isRecord(error))
|
|
874
|
+
message = asString(error.message) ?? asString(error.type);
|
|
875
|
+
message ??= asString(body.message);
|
|
876
|
+
}
|
|
877
|
+
const reason: RateLimitInfo["reason"] = text.includes("concurren")
|
|
878
|
+
? "concurrency"
|
|
879
|
+
: text.includes("quota")
|
|
880
|
+
? "quota"
|
|
881
|
+
: text.includes("rate limit") ||
|
|
882
|
+
text.includes("too many requests") ||
|
|
883
|
+
text.includes("rate_limit")
|
|
884
|
+
? "rate"
|
|
885
|
+
: "unknown";
|
|
886
|
+
return { reason, message };
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
export function parseRetryAfter(
|
|
890
|
+
headers: Headers,
|
|
891
|
+
now: number,
|
|
892
|
+
): number | undefined {
|
|
893
|
+
const raw = headers.get("retry-after");
|
|
894
|
+
if (!raw) return undefined;
|
|
895
|
+
const trimmed = raw.trim();
|
|
896
|
+
const seconds = Number(trimmed);
|
|
897
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
898
|
+
return Math.round(seconds * 1_000);
|
|
899
|
+
const date = Date.parse(trimmed);
|
|
900
|
+
if (Number.isFinite(date)) return Math.max(0, date - now);
|
|
901
|
+
return undefined;
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
export function errorMessage(error: unknown): string {
|
|
905
|
+
if (error instanceof Error) return error.message;
|
|
906
|
+
if (typeof error === "string") return error;
|
|
907
|
+
return String(error);
|
|
908
|
+
}
|