@compose-market/core 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1300 +0,0 @@
1
- const EOL = /\r\n|\r|\n/;
2
- function lines(buffer) {
3
- const parts = buffer.split(EOL);
4
- const rest = parts.pop() ?? "";
5
- return { lines: parts, rest };
6
- }
7
- export async function* parseSSEStream(stream, options = {}) {
8
- const reader = stream.getReader();
9
- const decoder = new TextDecoder("utf-8");
10
- let buffer = "";
11
- let event = "message";
12
- let data = [];
13
- let id;
14
- const abort = () => {
15
- try {
16
- reader.cancel();
17
- }
18
- catch { /* best effort */ }
19
- };
20
- options.signal?.addEventListener("abort", abort);
21
- try {
22
- while (true) {
23
- const { value, done } = await reader.read();
24
- if (done)
25
- break;
26
- buffer += decoder.decode(value, { stream: true });
27
- const split = lines(buffer);
28
- buffer = split.rest;
29
- for (const line of split.lines) {
30
- if (line === "") {
31
- if (data.length > 0) {
32
- yield { event, data: data.join("\n"), ...(id ? { id } : {}) };
33
- }
34
- event = "message";
35
- data = [];
36
- id = undefined;
37
- continue;
38
- }
39
- if (line.startsWith(":"))
40
- continue;
41
- const colon = line.indexOf(":");
42
- const field = colon === -1 ? line : line.slice(0, colon);
43
- let value = colon === -1 ? "" : line.slice(colon + 1);
44
- if (value.startsWith(" "))
45
- value = value.slice(1);
46
- if (field === "event")
47
- event = value || "message";
48
- else if (field === "data")
49
- data.push(value);
50
- else if (field === "id")
51
- id = value;
52
- }
53
- }
54
- buffer += decoder.decode();
55
- if (buffer.length > 0) {
56
- const split = lines(`${buffer}\n`);
57
- for (const line of split.lines) {
58
- if (line === "")
59
- break;
60
- if (line.startsWith(":"))
61
- continue;
62
- const colon = line.indexOf(":");
63
- const field = colon === -1 ? line : line.slice(0, colon);
64
- let value = colon === -1 ? "" : line.slice(colon + 1);
65
- if (value.startsWith(" "))
66
- value = value.slice(1);
67
- if (field === "event")
68
- event = value || "message";
69
- else if (field === "data")
70
- data.push(value);
71
- else if (field === "id")
72
- id = value;
73
- }
74
- }
75
- if (data.length > 0) {
76
- yield { event, data: data.join("\n"), ...(id ? { id } : {}) };
77
- }
78
- }
79
- finally {
80
- options.signal?.removeEventListener("abort", abort);
81
- try {
82
- reader.releaseLock();
83
- }
84
- catch { /* best effort */ }
85
- }
86
- }
87
- export function encode(event) {
88
- return `data: ${JSON.stringify(event)}\n\n`;
89
- }
90
- export function createStreamTree() {
91
- return {
92
- roots: [],
93
- nodes: {},
94
- seen: {},
95
- text: "",
96
- reasoning: "",
97
- artifacts: [],
98
- receipts: [],
99
- errors: [],
100
- };
101
- }
102
- export function reduce(tree, event) {
103
- const next = {
104
- roots: tree.roots.slice(),
105
- nodes: { ...tree.nodes },
106
- seen: { ...tree.seen },
107
- text: tree.text,
108
- reasoning: tree.reasoning,
109
- artifacts: tree.artifacts.slice(),
110
- receipts: tree.receipts.slice(),
111
- errors: tree.errors.slice(),
112
- };
113
- if (!event.delta) {
114
- const serial = stable(event);
115
- if (next.seen[event.id] !== undefined && next.seen[event.id] === serial) {
116
- return next;
117
- }
118
- next.seen[event.id] = serial;
119
- }
120
- const current = next.nodes[event.id];
121
- const previousParentId = current?.parentId;
122
- const node = {
123
- id: event.id,
124
- kind: event.kind,
125
- source: event.source,
126
- ...(event.parentId ? { parentId: event.parentId } : current?.parentId ? { parentId: current.parentId } : {}),
127
- ...(event.rootId ? { rootId: event.rootId } : current?.rootId ? { rootId: current.rootId } : {}),
128
- ...(event.runId ? { runId: event.runId } : current?.runId ? { runId: current.runId } : {}),
129
- status: event.status ?? current?.status ?? "running",
130
- path: event.path ?? current?.path ?? [],
131
- display: { ...(current?.display ?? {}), ...(event.display ?? {}) },
132
- payload: merge(current?.payload, event.payload),
133
- ...(event.raw !== undefined ? { raw: event.raw } : current?.raw !== undefined ? { raw: current.raw } : {}),
134
- text: current?.text ?? "",
135
- children: current?.children.slice() ?? [],
136
- updatedAt: event.ts ?? Date.now(),
137
- events: (current?.events ?? 0) + 1,
138
- };
139
- if (event.delta) {
140
- node.text += event.delta;
141
- if (event.kind === "text")
142
- next.text += event.delta;
143
- if (event.kind === "reasoning")
144
- next.reasoning += event.delta;
145
- }
146
- next.nodes[event.id] = node;
147
- if (previousParentId && previousParentId !== node.parentId) {
148
- const previousParent = next.nodes[previousParentId];
149
- if (previousParent) {
150
- next.nodes[previousParentId] = {
151
- ...previousParent,
152
- children: previousParent.children.filter((idValue) => idValue !== node.id),
153
- };
154
- }
155
- }
156
- if (node.parentId) {
157
- const parent = next.nodes[node.parentId] ?? placeholder(node.parentId, event);
158
- if (!parent.children.includes(node.id))
159
- parent.children.push(node.id);
160
- next.nodes[parent.id] = parent;
161
- next.roots = next.roots.filter((idValue) => idValue !== node.id);
162
- if (!parent.parentId && !next.roots.includes(parent.id)) {
163
- next.roots.push(parent.id);
164
- }
165
- }
166
- else if (!next.roots.includes(node.id)) {
167
- next.roots.push(node.id);
168
- }
169
- if (event.kind === "artifact") {
170
- const artifact = stored(event, node);
171
- const index = next.artifacts.findIndex((item) => item.id === event.id);
172
- if (index >= 0)
173
- next.artifacts[index] = artifact;
174
- else
175
- next.artifacts.push(artifact);
176
- }
177
- if ((event.kind === "receipt" || event.kind === "payment") && !next.receipts.some((item) => item.id === event.id)) {
178
- next.receipts.push(event);
179
- }
180
- if (event.kind === "error" && !next.errors.some((item) => item.id === event.id)) {
181
- next.errors.push(event);
182
- }
183
- return next;
184
- }
185
- export function decode(input, options = {}) {
186
- const raw = framePayload(input);
187
- if (raw === "[DONE]") {
188
- const source = options.source ?? "stream";
189
- const targetId = terminalId(options, source);
190
- return event({
191
- id: targetId,
192
- kind: terminalKind(targetId),
193
- source,
194
- status: "completed",
195
- display: { summary: "Done" },
196
- raw,
197
- }, options);
198
- }
199
- if (!raw)
200
- return null;
201
- if (isRecord(raw) && raw.type === "stream") {
202
- const decoded = raw;
203
- if (!decoded.id || !decoded.kind || !decoded.source)
204
- return null;
205
- return decoded;
206
- }
207
- if (typeof raw === "string") {
208
- return event({
209
- id: id("text", options.runId),
210
- kind: "text",
211
- source: options.source ?? "stream",
212
- status: "running",
213
- delta: raw,
214
- raw,
215
- }, options);
216
- }
217
- if (!isRecord(raw))
218
- return null;
219
- return decodeRecord(raw, options);
220
- }
221
- function decodeRecord(raw, options) {
222
- const type = string(raw.type) ?? string(raw.eventName) ?? string(raw.event) ?? "";
223
- const runId = string(raw.composeRunId) ?? string(raw.runId) ?? options.runId;
224
- const rootId = string(raw.rootComposeRunId) ?? options.rootId ?? runId;
225
- const source = options.source ?? sourceOf(type, raw);
226
- const base = { ...options, runId, rootId, source };
227
- if (type === "text-delta") {
228
- const delta = string(raw.delta) ?? string(raw.text) ?? string(raw.content) ?? "";
229
- return delta ? event({
230
- id: id("text", runId),
231
- kind: "text",
232
- source,
233
- status: "running",
234
- delta,
235
- display: { title: "Response" },
236
- raw,
237
- }, base) : null;
238
- }
239
- if (type === "reasoning-delta" || type === "reasoning_delta" || type === "thinking" || type === "thinking-delta" || type === "thinking_delta") {
240
- const delta = string(raw.delta) ?? string(raw.text) ?? string(raw.thinking) ?? string(raw.content) ?? "";
241
- return delta ? event({
242
- id: id("reasoning", runId),
243
- kind: "reasoning",
244
- source,
245
- status: "running",
246
- delta,
247
- display: { title: "Reasoning" },
248
- raw,
249
- }, base) : null;
250
- }
251
- if (type === "warning" || type === "response.warning") {
252
- const warning = isRecord(raw.warning) ? raw.warning : raw;
253
- return event({
254
- id: id("warning", string(warning.code), string(warning.message), runId),
255
- kind: "debug",
256
- source,
257
- status: "info",
258
- display: { title: "Warning", summary: string(warning.message) ?? string(raw.message) },
259
- payload: { warning },
260
- raw,
261
- }, base);
262
- }
263
- if (type === "citation" || type === "response.citation") {
264
- const citation = isRecord(raw.citation) ? raw.citation : raw;
265
- return event({
266
- id: id("citation", string(citation.url), string(citation.title), string(citation.marker), runId),
267
- kind: "catalog",
268
- source,
269
- parentId: modelParent(base, string(raw.response_id)),
270
- status: "completed",
271
- display: {
272
- title: string(citation.title) ?? "Citation",
273
- summary: string(citation.snippet),
274
- target: string(citation.url) ?? string(citation.marker),
275
- },
276
- payload: { citation },
277
- raw,
278
- }, base);
279
- }
280
- if (type === "thinking-start" || type === "thinking_start" || type === "thinking-end" || type === "thinking_end") {
281
- return event({
282
- id: id("debug", type, runId),
283
- kind: "debug",
284
- source,
285
- status: type.endsWith("end") ? "completed" : "running",
286
- display: { title: "Runtime status", summary: string(raw.message) ?? type },
287
- payload: raw,
288
- raw,
289
- }, base);
290
- }
291
- if (type === "stopped") {
292
- return event({
293
- id: id("stopped", runId),
294
- kind: "run",
295
- source,
296
- status: "cancelled",
297
- display: { title: "Stopped", summary: string(raw.reason) },
298
- payload: raw,
299
- raw,
300
- }, base);
301
- }
302
- if (type === "tool-args-delta") {
303
- return event({
304
- id: id("tool", string(raw.id) ?? string(raw.toolName), runId),
305
- kind: "tool",
306
- source,
307
- status: "running",
308
- display: { title: string(raw.toolName) ?? "Tool" },
309
- payload: { arguments: string(raw.argsDelta) },
310
- raw,
311
- }, base);
312
- }
313
- if (type === "tool-start")
314
- raw.type = "tool_start";
315
- if (type === "tool-end")
316
- raw.type = "tool_end";
317
- if (Array.isArray(raw.choices)) {
318
- const choice = raw.choices[0];
319
- const delta = isRecord(choice) && isRecord(choice.delta) ? choice.delta : null;
320
- const reasoning = string(delta?.reasoning_content);
321
- if (reasoning) {
322
- return event({
323
- id: id("reasoning", runId),
324
- kind: "reasoning",
325
- source,
326
- parentId: modelParent(base, string(raw.id)),
327
- status: "running",
328
- delta: reasoning,
329
- display: { title: "Reasoning" },
330
- raw,
331
- }, base);
332
- }
333
- const text = string(delta?.content);
334
- if (text) {
335
- return event({
336
- id: id("text", runId),
337
- kind: "text",
338
- source,
339
- parentId: modelParent(base, string(raw.id)),
340
- status: "running",
341
- delta: text,
342
- display: { title: "Response" },
343
- raw,
344
- }, base);
345
- }
346
- if (raw.usage) {
347
- return event({
348
- id: id("model", string(raw.id) ?? runId),
349
- kind: "model",
350
- source,
351
- status: "completed",
352
- display: { title: string(raw.model) ?? "Model", summary: "Usage", target: string(raw.id) },
353
- payload: { usage: raw.usage },
354
- raw,
355
- }, base);
356
- }
357
- const finish = isRecord(choice) ? string(choice.finish_reason) : undefined;
358
- if (finish) {
359
- return event({
360
- id: id("model", string(raw.id) ?? runId),
361
- kind: "model",
362
- source,
363
- status: "completed",
364
- display: { title: string(raw.model) ?? "Model", summary: finish, target: string(raw.id) },
365
- payload: { finishReason: finish, usage: raw.usage },
366
- raw,
367
- }, base);
368
- }
369
- return null;
370
- }
371
- if (Array.isArray(raw.candidates)) {
372
- const candidate = isRecord(raw.candidates[0]) ? raw.candidates[0] : null;
373
- const content = isRecord(candidate?.content) ? candidate.content : {};
374
- const parts = Array.isArray(content.parts) ? content.parts : [];
375
- const part = parts.find(isRecord);
376
- if (part) {
377
- const text = string(part.text);
378
- if (text) {
379
- const reasoning = part.thought === true;
380
- return event({
381
- id: id(reasoning ? "reasoning" : "text", runId),
382
- kind: reasoning ? "reasoning" : "text",
383
- source,
384
- parentId: modelParent(base, string(raw.response_id)),
385
- status: "running",
386
- delta: text,
387
- display: { title: reasoning ? "Reasoning" : "Response" },
388
- raw,
389
- }, base);
390
- }
391
- const inline = isRecord(part.inlineData) ? part.inlineData : isRecord(part.inline_data) ? part.inline_data : null;
392
- const data = string(inline?.data);
393
- if (data) {
394
- return event({
395
- id: id("artifact", string(raw.response_id) ?? runId, number(raw.index), data),
396
- kind: "artifact",
397
- source,
398
- parentId: modelParent(base, string(raw.response_id)),
399
- status: "running",
400
- display: { title: "Media", target: string(raw.model) },
401
- payload: {
402
- artifactType: mediaKind(string(inline?.mimeType) ?? string(inline?.mime_type)),
403
- responseId: string(raw.response_id),
404
- mimeType: string(inline?.mimeType) ?? string(inline?.mime_type),
405
- inline: true,
406
- base64: data,
407
- },
408
- raw,
409
- }, base);
410
- }
411
- const call = isRecord(part.functionCall) ? part.functionCall : isRecord(part.function_call) ? part.function_call : null;
412
- if (call) {
413
- return event({
414
- id: id("tool", string(call.id) ?? string(call.name), runId),
415
- kind: "tool",
416
- source,
417
- parentId: modelParent(base, string(raw.response_id)),
418
- status: "completed",
419
- display: { title: string(call.name) ?? "Tool" },
420
- payload: {
421
- name: string(call.name),
422
- arguments: JSON.stringify(call.args ?? {}),
423
- },
424
- raw,
425
- }, base);
426
- }
427
- }
428
- if (raw.usageMetadata) {
429
- return event({
430
- id: id("model", string(raw.response_id) ?? runId),
431
- kind: "model",
432
- source,
433
- parentId: modelParent(base, string(raw.response_id)),
434
- status: "info",
435
- display: { title: string(raw.model) ?? "Model", summary: "Usage" },
436
- payload: { usage: raw.usageMetadata },
437
- raw,
438
- }, base);
439
- }
440
- }
441
- if (type === "response.created") {
442
- const response = isRecord(raw.response) ? raw.response : {};
443
- const responseId = string(response.id) ?? string(raw.response_id) ?? runId;
444
- return event({
445
- id: id("model", responseId),
446
- kind: "model",
447
- source,
448
- status: "running",
449
- display: { title: string(response.model) ?? string(raw.model) ?? "Model", target: responseId },
450
- payload: { response },
451
- raw,
452
- }, base);
453
- }
454
- if (type === "response.output_text.delta") {
455
- const delta = string(raw.delta) ?? "";
456
- return delta ? event({
457
- id: id("text", string(raw.response_id) ?? runId),
458
- kind: "text",
459
- source,
460
- parentId: modelParent(base, string(raw.response_id)),
461
- status: "running",
462
- delta,
463
- display: { title: "Response", target: string(raw.model) },
464
- raw,
465
- }, base) : null;
466
- }
467
- if (type === "response.reasoning.delta" || type === "response.reasoning_text.delta" || type === "response.reasoning_summary_text.delta") {
468
- const delta = string(raw.delta) ?? "";
469
- return delta ? event({
470
- id: id("reasoning", string(raw.response_id) ?? runId),
471
- kind: "reasoning",
472
- source,
473
- parentId: modelParent(base, string(raw.response_id)),
474
- status: "running",
475
- delta,
476
- display: { title: "Reasoning", target: string(raw.model) },
477
- raw,
478
- }, base) : null;
479
- }
480
- if (type === "content_block_start") {
481
- const block = isRecord(raw.content_block) ? raw.content_block : {};
482
- if (string(block.type) === "tool_use") {
483
- return event({
484
- id: id("tool", string(block.id), string(block.name), runId),
485
- kind: "tool",
486
- source,
487
- parentId: modelParent(base, string(raw.message_id)),
488
- status: "running",
489
- display: { title: string(block.name) ?? "Tool" },
490
- payload: { name: string(block.name), input: block.input, index: number(raw.index) },
491
- raw,
492
- }, base);
493
- }
494
- }
495
- if (type === "message_delta") {
496
- const delta = isRecord(raw.delta) ? raw.delta : {};
497
- return event({
498
- id: id("model", string(raw.message_id) ?? runId),
499
- kind: "model",
500
- source,
501
- status: "info",
502
- display: { title: string(raw.model) ?? "Model", summary: string(delta.stop_reason) },
503
- payload: { usage: raw.usage, stopReason: string(delta.stop_reason) },
504
- raw,
505
- }, base);
506
- }
507
- if (type === "content_block_delta") {
508
- const delta = isRecord(raw.delta) ? raw.delta : {};
509
- const deltaType = string(delta.type);
510
- const text = string(delta.text) ?? string(delta.thinking);
511
- if (!text)
512
- return null;
513
- const reasoning = deltaType === "thinking_delta" || string(delta.thinking) !== undefined;
514
- return event({
515
- id: id(reasoning ? "reasoning" : "text", string(raw.message_id) ?? runId),
516
- kind: reasoning ? "reasoning" : "text",
517
- source,
518
- parentId: modelParent(base, string(raw.message_id)),
519
- status: "running",
520
- delta: text,
521
- display: { title: reasoning ? "Reasoning" : "Response" },
522
- raw,
523
- }, base);
524
- }
525
- if (type === "response.audio.delta" || type === "response.output_audio.delta") {
526
- const delta = string(raw.delta) ?? "";
527
- return event({
528
- id: id("audio", string(raw.response_id) ?? runId, number(raw.output_index) ?? number(raw.index) ?? 0),
529
- kind: "artifact",
530
- source,
531
- parentId: modelParent(base, string(raw.response_id)),
532
- status: "running",
533
- display: { title: "Audio", target: string(raw.model) },
534
- payload: {
535
- artifactType: "audio",
536
- responseId: string(raw.response_id),
537
- outputIndex: number(raw.output_index) ?? number(raw.index) ?? 0,
538
- mimeType: string(raw.mime_type),
539
- inline: true,
540
- base64: delta,
541
- },
542
- raw,
543
- }, base);
544
- }
545
- if (type === "audio-chunk") {
546
- const audio = isRecord(raw.audio) ? raw.audio : {};
547
- const chunk = raw.chunk ?? audio.chunk ?? audio.base64;
548
- const base64 = typeof chunk === "string"
549
- ? chunk
550
- : isRecord(chunk) && typeof chunk.base64 === "string"
551
- ? chunk.base64
552
- : undefined;
553
- return event({
554
- id: id("audio", string(raw.response_id) ?? runId, number(raw.outputIndex) ?? number(raw.output_index) ?? 0),
555
- kind: "artifact",
556
- source,
557
- parentId: modelParent(base, string(raw.response_id)),
558
- status: "running",
559
- display: { title: "Audio", target: string(raw.model) },
560
- payload: {
561
- artifactType: "audio",
562
- responseId: string(raw.response_id),
563
- outputIndex: number(raw.outputIndex) ?? number(raw.output_index) ?? number(audio.outputIndex) ?? number(audio.output_index) ?? 0,
564
- sequenceIndex: number(raw.sequenceIndex) ?? number(raw.sequence_index) ?? number(audio.sequenceIndex) ?? number(audio.sequence_index),
565
- mimeType: string(raw.mime_type) ?? string(raw.mimeType) ?? string(audio.mimeType) ?? string(audio.mime_type),
566
- inline: true,
567
- base64,
568
- },
569
- raw,
570
- }, base);
571
- }
572
- if (type === "subtitle" || type === "response.output_audio.subtitle") {
573
- const subtitle = isRecord(raw.subtitle) ? raw.subtitle : raw;
574
- return event({
575
- id: id("subtitle", string(raw.response_id), number(subtitle.start), number(subtitle.end), runId),
576
- kind: "artifact",
577
- source,
578
- parentId: modelParent(base, string(raw.response_id)),
579
- status: "running",
580
- display: { title: "Subtitle", summary: string(subtitle.text), target: string(raw.model) },
581
- payload: {
582
- artifactType: "text",
583
- responseId: string(raw.response_id),
584
- subtitle,
585
- },
586
- raw,
587
- }, base);
588
- }
589
- if (type === "response.text.delta") {
590
- const delta = string(raw.delta) ?? "";
591
- return delta ? event({
592
- id: id("text", string(raw.response_id) ?? runId),
593
- kind: "text",
594
- source,
595
- parentId: modelParent(base, string(raw.response_id)),
596
- status: "running",
597
- delta,
598
- display: { title: "Response", target: string(raw.model) },
599
- raw,
600
- }, base) : null;
601
- }
602
- if (type === "response.image_generation_call.partial_image" || type === "response.image_generation_call.completed") {
603
- const complete = type.endsWith(".completed");
604
- const imageIndex = number(raw.partial_image_index) ?? number(raw.output_index) ?? number(raw.index) ?? 0;
605
- return event({
606
- id: id("artifact", string(raw.response_id) ?? runId, imageIndex),
607
- kind: "artifact",
608
- source,
609
- parentId: modelParent(base, string(raw.response_id)),
610
- status: complete ? "completed" : "running",
611
- display: {
612
- title: complete ? "Image complete" : "Image partial",
613
- target: string(raw.model),
614
- summary: string(raw.revised_prompt),
615
- },
616
- payload: {
617
- artifactType: "image",
618
- responseId: string(raw.response_id),
619
- outputIndex: imageIndex,
620
- mimeType: string(raw.mime_type) ?? "image/png",
621
- inline: true,
622
- partial: !complete,
623
- base64: string(raw.partial_image_b64) ?? string(raw.image_b64),
624
- usage: raw.usage,
625
- },
626
- raw,
627
- }, base);
628
- }
629
- if (type === "image-partial" || type === "image-complete") {
630
- const image = isRecord(raw.image) ? raw.image : raw;
631
- const complete = type === "image-complete";
632
- return event({
633
- id: id("artifact", string(raw.response_id) ?? runId, number(image.index)),
634
- kind: "artifact",
635
- source,
636
- parentId: modelParent(base, string(raw.response_id)),
637
- status: complete ? "completed" : "running",
638
- display: {
639
- title: complete ? "Image complete" : "Image partial",
640
- target: string(raw.model),
641
- summary: string(image.revisedPrompt),
642
- },
643
- payload: {
644
- artifactType: "image",
645
- responseId: string(raw.response_id),
646
- outputIndex: number(image.index) ?? 0,
647
- mimeType: string(image.mediaType) ?? string(image.mimeType) ?? "image/png",
648
- url: string(image.url),
649
- inline: string(image.base64) !== undefined,
650
- partial: !complete,
651
- base64: string(image.base64),
652
- usage: raw.usage,
653
- },
654
- raw,
655
- }, base);
656
- }
657
- if (type === "response.output_item.completed") {
658
- const item = isRecord(raw.item) ? raw.item : {};
659
- const itemType = string(item.type);
660
- if (itemType === "output_text") {
661
- const text = string(item.text) ?? "";
662
- return text ? event({
663
- id: id("text", string(raw.response_id) ?? runId),
664
- kind: "text",
665
- source,
666
- parentId: modelParent(base, string(raw.response_id)),
667
- status: "completed",
668
- delta: text,
669
- display: { title: "Response", target: string(raw.model) },
670
- raw,
671
- }, base) : null;
672
- }
673
- const asset = media(item);
674
- if (asset) {
675
- return event({
676
- id: mediaId(asset.kind, raw, item, runId),
677
- kind: "artifact",
678
- source,
679
- parentId: modelParent(base, string(raw.response_id)),
680
- status: "completed",
681
- display: {
682
- title: asset.kind,
683
- target: string(raw.model),
684
- summary: string(item.text) ?? string(item.status),
685
- },
686
- payload: {
687
- artifactType: asset.kind,
688
- responseId: string(raw.response_id),
689
- outputIndex: number(raw.output_index) ?? number(raw.index) ?? 0,
690
- mimeType: string(item.mime_type),
691
- url: asset.url,
692
- inline: asset.base64 !== undefined,
693
- base64: asset.base64,
694
- embedding: asset.embedding,
695
- status: string(item.status),
696
- jobId: string(item.job_id),
697
- },
698
- raw,
699
- }, base);
700
- }
701
- }
702
- if (type === "response.output_video.status" || type === "compose.video.status" || type === "status") {
703
- const video = isRecord(raw.videoStatus) ? raw.videoStatus : isRecord(raw.video) ? raw.video : raw;
704
- const videoStatus = string(raw.status) ?? string(video.status);
705
- return event({
706
- id: id("video", string(raw.response_id) ?? string(video.job_id) ?? string(video.jobId) ?? string(raw.job_id) ?? string(raw.jobId) ?? runId),
707
- kind: "artifact",
708
- source,
709
- parentId: modelParent(base, string(raw.response_id)),
710
- status: videoStatus === "failed" ? "failed" : videoStatus === "completed" ? "completed" : "running",
711
- display: {
712
- title: "Video",
713
- target: string(raw.model),
714
- summary: videoStatus,
715
- },
716
- payload: {
717
- artifactType: "video",
718
- responseId: string(raw.response_id),
719
- outputIndex: number(raw.output_index) ?? number(raw.index),
720
- jobId: string(video.job_id) ?? string(video.jobId) ?? string(raw.job_id) ?? string(raw.jobId),
721
- status: videoStatus,
722
- progress: number(raw.progress) ?? number(video.progress),
723
- url: string(raw.url) ?? string(video.url),
724
- error: string(raw.error) ?? string(video.error),
725
- },
726
- raw,
727
- }, base);
728
- }
729
- if (type === "video-complete") {
730
- const video = isRecord(raw.video) ? raw.video : raw;
731
- return event({
732
- id: id("video", string(raw.response_id) ?? string(video.jobId) ?? runId),
733
- kind: "artifact",
734
- source,
735
- parentId: modelParent(base, string(raw.response_id)),
736
- status: "completed",
737
- display: { title: "Video", target: string(raw.model), summary: string(video.status) },
738
- payload: {
739
- artifactType: "video",
740
- responseId: string(raw.response_id),
741
- outputIndex: number(raw.outputIndex) ?? number(raw.output_index),
742
- jobId: string(video.jobId),
743
- status: string(video.status) ?? "completed",
744
- progress: number(video.progress),
745
- url: string(video.url),
746
- mimeType: string(video.mediaType) ?? string(video.mimeType),
747
- inline: string(video.base64) !== undefined,
748
- base64: string(video.base64),
749
- },
750
- raw,
751
- }, base);
752
- }
753
- if (type === "start" || type === "step" || type === "agent" || type === "progress" || type === "complete") {
754
- const kind = type === "agent" ? "agent" : type === "progress" || type === "step" ? "action" : "run";
755
- return event({
756
- id: id(kind, string(raw.stepName) ?? string(raw.agentName) ?? type, runId),
757
- kind,
758
- source,
759
- status: type === "complete" ? "completed" : "running",
760
- display: {
761
- title: string(raw.agentName) ?? string(raw.stepName) ?? type,
762
- summary: string(raw.message),
763
- },
764
- payload: raw,
765
- raw,
766
- }, base);
767
- }
768
- if (type === "result") {
769
- const output = raw.output;
770
- const outputRecord = isRecord(output) ? output : {};
771
- const mediaOutput = media(outputRecord);
772
- if (mediaOutput) {
773
- return event({
774
- id: id("artifact", mediaOutput.url ?? mediaOutput.base64, runId),
775
- kind: "artifact",
776
- source,
777
- status: "completed",
778
- display: { title: mediaOutput.kind, summary: string(outputRecord.status) },
779
- payload: {
780
- artifactType: mediaOutput.kind,
781
- url: mediaOutput.url,
782
- inline: mediaOutput.base64 !== undefined,
783
- base64: mediaOutput.base64,
784
- mimeType: string(outputRecord.mimeType) ?? string(outputRecord.mime_type),
785
- },
786
- raw,
787
- }, base);
788
- }
789
- const text = string(output) ?? (isRecord(output) ? JSON.stringify(output) : undefined);
790
- return text ? event({
791
- id: id("text", runId),
792
- kind: "text",
793
- source,
794
- status: "completed",
795
- delta: text,
796
- display: { title: "Result" },
797
- payload: raw,
798
- raw,
799
- }, base) : null;
800
- }
801
- if (type === "tool-call-start" || type === "tool-call" || type === "tool-call-delta" || type === "response.tool_call" || type === "response.tool_call.delta" || type === "tool_args_delta") {
802
- const call = isRecord(raw.tool_call) ? raw.tool_call : raw;
803
- const delta = isRecord(raw.delta) ? raw.delta : raw;
804
- return event({
805
- id: id("tool", string(call.id) ?? string(delta.id) ?? string(call.name) ?? string(raw.toolName), runId),
806
- kind: "tool",
807
- source,
808
- parentId: modelParent(base, string(raw.response_id)),
809
- status: type.endsWith(".delta") || type === "tool_args_delta" || type === "tool-call-delta" || type === "tool-call-start" ? "running" : "completed",
810
- display: { title: string(call.name) ?? string(delta.name) ?? string(raw.toolName) ?? "Tool" },
811
- payload: {
812
- name: string(call.name) ?? string(delta.name) ?? string(raw.toolName),
813
- arguments: string(call.arguments) ?? string(delta.arguments) ?? string(raw.argumentsDelta) ?? string(raw.argsDelta),
814
- index: number(raw.index),
815
- },
816
- raw,
817
- }, base);
818
- }
819
- if (type === "tool_start" || type === "tool-start") {
820
- const display = displayOf(raw);
821
- return event({
822
- id: id("tool", string(raw.toolName) ?? display.target, runId),
823
- kind: displayKind(display, "tool"),
824
- source,
825
- parentId: agentParent(base),
826
- status: "running",
827
- display: { title: display.title ?? string(raw.toolName) ?? "Tool", summary: string(raw.content) ?? display.summary, target: display.target, kind: display.kind, metadata: display.metadata },
828
- raw,
829
- }, base);
830
- }
831
- if (type === "tool_end" || type === "tool-end") {
832
- const display = displayOf(raw);
833
- const failed = Boolean(raw.failed) || Boolean(string(raw.error));
834
- return event({
835
- id: id("tool", string(raw.toolName) ?? display.target, runId),
836
- kind: displayKind(display, "tool"),
837
- source,
838
- parentId: agentParent(base),
839
- status: failed ? "failed" : "completed",
840
- display: { title: display.title ?? string(raw.toolName) ?? "Tool", summary: string(raw.message) ?? display.summary, target: display.target, kind: display.kind, metadata: display.metadata },
841
- payload: { output: raw.output, error: string(raw.error) },
842
- raw,
843
- }, base);
844
- }
845
- if (type === "harness_plan_proposed" || type === "harness_plan_decided") {
846
- const decided = type === "harness_plan_decided";
847
- return event({
848
- id: id("approval", string(raw.proposalId), string(raw.version)),
849
- kind: "approval",
850
- source,
851
- parentId: agentParent(base),
852
- status: decided ? "completed" : "pending",
853
- display: {
854
- title: decided ? "Plan decision" : "Plan review",
855
- summary: string(raw.state),
856
- target: string(raw.composeRunId),
857
- },
858
- payload: {
859
- proposalId: string(raw.proposalId),
860
- version: number(raw.version),
861
- state: string(raw.state),
862
- decision: string(raw.decision),
863
- proposal: raw.proposal,
864
- markdown: string(raw.markdown),
865
- approver: string(raw.approver),
866
- reason: string(raw.reason),
867
- feedback: string(raw.feedback),
868
- },
869
- raw,
870
- }, base);
871
- }
872
- if (type.startsWith("swarm_child_") || type === "child") {
873
- return childEvent(raw, type, base);
874
- }
875
- if (type === "artifact") {
876
- const runKey = string(raw.runKey);
877
- const parentRunId = string(raw.parentRunId) ?? runId;
878
- return event({
879
- id: id("artifact", string(raw.responseId), string(raw.jobId), string(raw.runKey)),
880
- kind: "artifact",
881
- source,
882
- parentId: runKey ? id("agent", runKey, parentRunId) : agentParent(base),
883
- status: raw.status === "failed" ? "failed" : raw.status === "completed" ? "completed" : "running",
884
- display: { title: string(raw.artifactType) ?? "Artifact", summary: string(raw.status) },
885
- payload: raw,
886
- raw,
887
- }, base);
888
- }
889
- if (type === "trace") {
890
- const display = displayOf(raw);
891
- return event({
892
- id: id("debug", string(raw.source), string(raw.stage), string(raw.action), display.target ?? display.summary ?? display.title),
893
- kind: "debug",
894
- source,
895
- parentId: agentParent(base),
896
- status: "info",
897
- display,
898
- payload: { stage: string(raw.stage), action: string(raw.action), message: string(raw.message), details: raw.details },
899
- raw,
900
- }, base);
901
- }
902
- if (type === "conclave") {
903
- const key = string(raw.key);
904
- return event({
905
- id: id("conclave", string(raw.action), key, runId),
906
- kind: "conclave",
907
- source,
908
- parentId: agentParent(base),
909
- status: raw.success === false ? "failed" : "completed",
910
- display: { title: "Conclave", summary: string(raw.action), target: key },
911
- payload: raw,
912
- raw,
913
- }, base);
914
- }
915
- if (type === "compose.receipt") {
916
- return receipt(raw, base);
917
- }
918
- if (type === "session-active" || type === "session-expired" || type === "session-lease") {
919
- return event({
920
- id: id("session", type, string(raw.userAddress), string(raw.chainId)),
921
- kind: "session",
922
- source,
923
- status: type === "session-active" ? "running" : "info",
924
- display: { title: "Session", summary: type },
925
- payload: raw,
926
- raw,
927
- }, base);
928
- }
929
- if (type === "error" || type === "compose.error" || type === "response.error") {
930
- const err = isRecord(raw.error) ? raw.error : raw;
931
- return event({
932
- id: id("error", string(err.code), string(err.message) ?? string(raw.message), runId),
933
- kind: "error",
934
- source,
935
- status: "failed",
936
- display: { title: "Error", summary: string(err.message) ?? string(raw.message) ?? string(raw.content) },
937
- payload: { ...raw, error: err },
938
- raw,
939
- }, base);
940
- }
941
- if (type === "done" || type === "finish" || type === "message-stop" || type === "message_stop" || type === "response.completed") {
942
- if (type === "response.completed") {
943
- const responseId = string(raw.response_id) ?? runId;
944
- return event({
945
- id: id("model", responseId),
946
- kind: "model",
947
- source,
948
- status: "completed",
949
- display: { title: string(raw.model) ?? "Model", summary: string(raw.finish_reason), target: responseId },
950
- payload: raw,
951
- raw,
952
- }, base);
953
- }
954
- const targetId = terminalId(base, source, string(raw.response_id));
955
- return event({
956
- id: targetId,
957
- kind: terminalKind(targetId),
958
- source,
959
- status: "completed",
960
- display: { summary: string(raw.finish_reason) ?? string(raw.finishReason) ?? "Done" },
961
- payload: raw,
962
- raw,
963
- }, base);
964
- }
965
- const content = string(raw.content) ?? string(raw.text);
966
- if (content) {
967
- return event({
968
- id: id("text", runId),
969
- kind: "text",
970
- source,
971
- status: "running",
972
- delta: content,
973
- display: { title: "Response" },
974
- raw,
975
- }, base);
976
- }
977
- return null;
978
- }
979
- function childEvent(raw, type, options) {
980
- const eventType = type === "child" ? string(raw.event) ?? "" : type.replace(/^swarm_child_/, "");
981
- const runKey = string(raw.runKey);
982
- const parentRunId = string(raw.parentRunId) ?? options.runId;
983
- const agentId = id("agent", runKey ?? string(raw.agentWallet), parentRunId);
984
- const parentRun = parentRunId ? id("agent", parentRunId) : options.parentId;
985
- if (eventType === "start") {
986
- return event({
987
- id: agentId,
988
- kind: "agent",
989
- source: options.source ?? "agent",
990
- parentId: parentRun,
991
- status: "running",
992
- path: array(raw.runKeyChain),
993
- display: { title: string(raw.agentWallet) ?? "Agent", target: runKey },
994
- payload: raw,
995
- raw,
996
- }, options);
997
- }
998
- if (eventType === "delta") {
999
- const delta = string(raw.delta) ?? "";
1000
- return delta ? event({
1001
- id: id("text", runKey),
1002
- kind: "text",
1003
- source: options.source ?? "agent",
1004
- parentId: agentId,
1005
- status: "running",
1006
- path: array(raw.runKeyChain),
1007
- delta,
1008
- display: { title: "Agent response" },
1009
- raw,
1010
- }, options) : null;
1011
- }
1012
- if (eventType === "tool-start" || eventType === "tool_start") {
1013
- return event({
1014
- id: id("tool", runKey, string(raw.toolName)),
1015
- kind: "tool",
1016
- source: options.source ?? "agent",
1017
- parentId: agentId,
1018
- status: "running",
1019
- path: array(raw.runKeyChain),
1020
- display: { title: string(raw.toolName) ?? "Tool" },
1021
- payload: { input: raw.input },
1022
- raw,
1023
- }, options);
1024
- }
1025
- if (eventType === "tool-end" || eventType === "tool_end") {
1026
- return event({
1027
- id: id("tool", runKey, string(raw.toolName)),
1028
- kind: "tool",
1029
- source: options.source ?? "agent",
1030
- parentId: agentId,
1031
- status: raw.failed === true ? "failed" : "completed",
1032
- path: array(raw.runKeyChain),
1033
- display: { title: string(raw.toolName) ?? "Tool" },
1034
- payload: { output: raw.output, error: string(raw.error) },
1035
- raw,
1036
- }, options);
1037
- }
1038
- if (eventType === "done" || eventType === "error") {
1039
- return event({
1040
- id: agentId,
1041
- kind: "agent",
1042
- source: options.source ?? "agent",
1043
- parentId: parentRun,
1044
- status: eventType === "error" ? "failed" : "completed",
1045
- path: array(raw.runKeyChain),
1046
- display: { title: string(raw.agentWallet) ?? "Agent", summary: string(raw.stopReason) ?? string(raw.error), target: runKey },
1047
- payload: raw,
1048
- raw,
1049
- }, options);
1050
- }
1051
- return null;
1052
- }
1053
- function receipt(raw, options) {
1054
- return event({
1055
- id: id("receipt", string(raw.id), string(raw.runId), string(raw.txHash), string(raw.settleTxHash)),
1056
- kind: "receipt",
1057
- source: options.source ?? "payment",
1058
- status: "completed",
1059
- display: { title: "Receipt", summary: string(raw.settlementStatus), target: string(raw.txHash) ?? string(raw.settleTxHash) },
1060
- payload: raw,
1061
- raw,
1062
- }, options);
1063
- }
1064
- function event(input, options) {
1065
- return {
1066
- type: "stream",
1067
- ...input,
1068
- ...(input.rootId || options.rootId ? { rootId: input.rootId ?? options.rootId } : {}),
1069
- ...(input.runId || options.runId ? { runId: input.runId ?? options.runId } : {}),
1070
- ...(input.parentId || options.parentId ? { parentId: input.parentId ?? options.parentId } : {}),
1071
- ts: input.ts ?? Date.now(),
1072
- };
1073
- }
1074
- function stored(value, node) {
1075
- return {
1076
- ...value,
1077
- ...(node.parentId ? { parentId: node.parentId } : {}),
1078
- ...(node.rootId ? { rootId: node.rootId } : {}),
1079
- ...(node.runId ? { runId: node.runId } : {}),
1080
- status: node.status,
1081
- path: node.path,
1082
- display: node.display,
1083
- ...(node.payload ? { payload: node.payload } : {}),
1084
- ...(node.raw !== undefined ? { raw: node.raw } : {}),
1085
- ts: node.updatedAt,
1086
- };
1087
- }
1088
- function framePayload(input) {
1089
- if (isRecord(input) && typeof input.data === "string" && typeof input.event === "string") {
1090
- if (input.data === "[DONE]")
1091
- return "[DONE]";
1092
- if (input.event !== "message") {
1093
- try {
1094
- const parsed = JSON.parse(input.data);
1095
- return isRecord(parsed) ? { ...parsed, type: input.event } : parsed;
1096
- }
1097
- catch {
1098
- return { type: input.event, message: input.data };
1099
- }
1100
- }
1101
- try {
1102
- return JSON.parse(input.data);
1103
- }
1104
- catch {
1105
- return input.data;
1106
- }
1107
- }
1108
- return input;
1109
- }
1110
- function displayOf(raw) {
1111
- const display = isRecord(raw.display) ? raw.display : {};
1112
- const kind = streamKind(string(display.kind));
1113
- const details = isRecord(display.details) ? display.details : isRecord(raw.details) ? raw.details : undefined;
1114
- const metadata = kind || details ? { ...(details ?? {}), ...(kind ? { kind } : {}) } : undefined;
1115
- return {
1116
- title: string(display.name) ?? string(raw.source) ?? string(raw.toolName),
1117
- label: string(display.label),
1118
- summary: string(display.summary) ?? string(raw.message),
1119
- target: string(display.target) ?? string(display.id),
1120
- ...(kind ? { kind } : {}),
1121
- ...(metadata ? { metadata } : {}),
1122
- };
1123
- }
1124
- function displayKind(display, fallback) {
1125
- const kind = display.kind ?? (display.metadata && typeof display.metadata.kind === "string" ? streamKind(display.metadata.kind) : undefined);
1126
- if (kind === "model" || kind === "connector" || kind === "agent" || kind === "harness" || kind === "conclave" || kind === "catalog")
1127
- return kind;
1128
- return fallback;
1129
- }
1130
- function streamKind(value) {
1131
- switch (value) {
1132
- case "run":
1133
- case "agent":
1134
- case "text":
1135
- case "reasoning":
1136
- case "action":
1137
- case "tool":
1138
- case "catalog":
1139
- case "model":
1140
- case "connector":
1141
- case "harness":
1142
- case "conclave":
1143
- case "approval":
1144
- case "artifact":
1145
- case "receipt":
1146
- case "payment":
1147
- case "session":
1148
- case "error":
1149
- case "debug":
1150
- return value;
1151
- case "search":
1152
- return "catalog";
1153
- default:
1154
- return undefined;
1155
- }
1156
- }
1157
- function agentParent(options) {
1158
- return options.runId ? id("agent", options.runId) : options.parentId;
1159
- }
1160
- function modelParent(options, responseId) {
1161
- const value = responseId ?? options.runId;
1162
- return value ? id("model", value) : options.parentId;
1163
- }
1164
- function terminalId(options, source, responseId) {
1165
- const value = responseId ?? options.runId;
1166
- if ((source === "inference" || responseId) && value)
1167
- return id("model", value);
1168
- if (value)
1169
- return id("agent", value);
1170
- return options.parentId ?? "done";
1171
- }
1172
- function terminalKind(idValue) {
1173
- if (idValue.startsWith("agent:"))
1174
- return "agent";
1175
- if (idValue.startsWith("model:"))
1176
- return "model";
1177
- return "run";
1178
- }
1179
- function sourceOf(type, raw) {
1180
- const source = string(raw.source);
1181
- if (source)
1182
- return source;
1183
- if (type.startsWith("response."))
1184
- return "inference";
1185
- if (type.startsWith("swarm_child_"))
1186
- return "agent";
1187
- if (type.startsWith("harness_"))
1188
- return "harness";
1189
- if (type.startsWith("session-"))
1190
- return "session";
1191
- return "stream";
1192
- }
1193
- function id(...parts) {
1194
- const clean = parts
1195
- .filter((part) => part !== undefined && part !== null && String(part).trim().length > 0)
1196
- .map((part) => String(part).trim().replace(/\s+/g, "_"));
1197
- return clean.length > 0 ? clean.join(":") : "stream";
1198
- }
1199
- function mediaId(kind, raw, item, runId) {
1200
- const responseId = string(raw.response_id) ?? runId;
1201
- const indexValue = number(raw.output_index) ?? number(raw.index) ?? 0;
1202
- if (kind === "image")
1203
- return id("artifact", responseId, indexValue);
1204
- if (kind === "audio")
1205
- return id("audio", responseId, indexValue);
1206
- if (kind === "video")
1207
- return id("video", responseId ?? string(item.job_id) ?? string(item.jobId) ?? runId);
1208
- return id("artifact", responseId, indexValue, kind);
1209
- }
1210
- function placeholder(idValue, eventValue) {
1211
- const kind = idValue.startsWith("agent:")
1212
- ? "agent"
1213
- : idValue.startsWith("model:")
1214
- ? "model"
1215
- : "run";
1216
- return {
1217
- id: idValue,
1218
- kind,
1219
- source: eventValue.source,
1220
- status: "running",
1221
- path: [],
1222
- display: { title: kind === "agent" ? "Agent" : kind === "model" ? "Model" : idValue, target: idValue },
1223
- text: "",
1224
- children: [],
1225
- updatedAt: eventValue.ts ?? Date.now(),
1226
- events: 0,
1227
- };
1228
- }
1229
- function stable(eventValue) {
1230
- let hash = 5381;
1231
- const text = JSON.stringify({
1232
- id: eventValue.id,
1233
- kind: eventValue.kind,
1234
- status: eventValue.status,
1235
- delta: eventValue.delta,
1236
- display: eventValue.display,
1237
- payload: eventValue.payload,
1238
- });
1239
- for (let i = 0; i < text.length; i += 1) {
1240
- hash = ((hash << 5) + hash) ^ text.charCodeAt(i);
1241
- }
1242
- return hash >>> 0;
1243
- }
1244
- function merge(a, b) {
1245
- if (!a && !b)
1246
- return undefined;
1247
- return { ...(a ?? {}), ...(b ?? {}) };
1248
- }
1249
- function isRecord(value) {
1250
- return value !== null && typeof value === "object" && !Array.isArray(value);
1251
- }
1252
- function string(value) {
1253
- return typeof value === "string" && value.length > 0 ? value : undefined;
1254
- }
1255
- function number(value) {
1256
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
1257
- }
1258
- function array(value) {
1259
- return Array.isArray(value) && value.every((item) => typeof item === "string") ? value : undefined;
1260
- }
1261
- function media(value) {
1262
- const type = string(value.type) ?? string(value.kind);
1263
- const normalized = type === "output_image" || type === "image"
1264
- ? "image"
1265
- : type === "output_audio" || type === "audio"
1266
- ? "audio"
1267
- : type === "output_video" || type === "video"
1268
- ? "video"
1269
- : type === "output_embedding" || type === "embedding"
1270
- ? "embedding"
1271
- : type === "file" || type === "artifact"
1272
- ? "file"
1273
- : undefined;
1274
- if (!normalized)
1275
- return null;
1276
- const url = string(value.url)
1277
- ?? string(value.image_url)
1278
- ?? string(value.imageUrl)
1279
- ?? string(value.audio_url)
1280
- ?? string(value.audioUrl)
1281
- ?? string(value.video_url)
1282
- ?? string(value.videoUrl);
1283
- const base64 = string(value.base64)
1284
- ?? string(value.b64_json)
1285
- ?? string(value.data);
1286
- const embedding = normalized === "embedding" ? value.embedding ?? value.embeddings : undefined;
1287
- return { kind: normalized, ...(url ? { url } : {}), ...(base64 ? { base64 } : {}), ...(embedding !== undefined ? { embedding } : {}) };
1288
- }
1289
- function mediaKind(mimeType) {
1290
- if (!mimeType)
1291
- return "file";
1292
- if (mimeType.startsWith("image/"))
1293
- return "image";
1294
- if (mimeType.startsWith("audio/"))
1295
- return "audio";
1296
- if (mimeType.startsWith("video/"))
1297
- return "video";
1298
- return "file";
1299
- }
1300
- //# sourceMappingURL=index.js.map