@runtypelabs/sdk 4.20.0 → 5.0.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/dist/index.mjs CHANGED
@@ -1,3 +1,503 @@
1
+ // src/unified-stream-adapter.ts
2
+ var UNIFIED_EVENTS_QUERY = "events=unified";
3
+ function withUnifiedEvents(path) {
4
+ return path.includes("?") ? `${path}&${UNIFIED_EVENTS_QUERY}` : `${path}?${UNIFIED_EVENTS_QUERY}`;
5
+ }
6
+ var UNIFIED_ONLY_EVENT_TYPES = /* @__PURE__ */ new Set([
7
+ "execution_start",
8
+ "execution_complete",
9
+ "execution_error",
10
+ "turn_start",
11
+ "turn_complete",
12
+ "text_start",
13
+ "text_delta",
14
+ "text_complete",
15
+ "reasoning_start",
16
+ "reasoning_delta",
17
+ "reasoning_complete",
18
+ "media_start",
19
+ "media_delta",
20
+ "media_complete",
21
+ "tool_output_delta",
22
+ "await"
23
+ ]);
24
+ function isUnifiedEventType(type) {
25
+ return typeof type === "string" && UNIFIED_ONLY_EVENT_TYPES.has(type);
26
+ }
27
+ function str(value) {
28
+ return typeof value === "string" ? value : void 0;
29
+ }
30
+ function num(value) {
31
+ return typeof value === "number" ? value : void 0;
32
+ }
33
+ function compact(event) {
34
+ const out = { type: event.type };
35
+ for (const [k, v] of Object.entries(event)) {
36
+ if (k !== "type" && v !== void 0) out[k] = v;
37
+ }
38
+ return out;
39
+ }
40
+ var LEGACY_FLOW_PASSTHROUGH = /* @__PURE__ */ new Set([
41
+ "flow_start",
42
+ "flow_complete",
43
+ "flow_error",
44
+ "flow_await",
45
+ "step_await",
46
+ "step_delta"
47
+ ]);
48
+ function createFlowEventTranslator() {
49
+ let currentStepId;
50
+ let currentStepName;
51
+ return (raw) => {
52
+ if (!raw || typeof raw !== "object") return [];
53
+ const data = raw;
54
+ const type = str(data.type);
55
+ if (!type) return [];
56
+ const executionId = str(data.executionId);
57
+ const seq = num(data.seq);
58
+ if (LEGACY_FLOW_PASSTHROUGH.has(type)) return [data];
59
+ switch (type) {
60
+ case "execution_start":
61
+ if (data.kind !== "flow") return [];
62
+ return [
63
+ compact({
64
+ type: "flow_start",
65
+ executionId,
66
+ seq,
67
+ flowId: data.flowId,
68
+ flowName: data.flowName,
69
+ totalSteps: data.totalSteps,
70
+ startedAt: data.startedAt,
71
+ source: data.source
72
+ })
73
+ ];
74
+ case "step_start": {
75
+ const id = str(data.id) ?? str(data.stepId);
76
+ const name = str(data.name) ?? str(data.stepName);
77
+ currentStepId = id;
78
+ currentStepName = name;
79
+ return [
80
+ compact({
81
+ type: "step_start",
82
+ executionId,
83
+ seq,
84
+ stepId: id,
85
+ name,
86
+ stepName: name,
87
+ stepType: data.stepType,
88
+ index: data.index,
89
+ totalSteps: data.totalSteps,
90
+ startedAt: data.startedAt,
91
+ outputVariable: data.outputVariable
92
+ })
93
+ ];
94
+ }
95
+ case "text_delta":
96
+ return [
97
+ compact({
98
+ type: "step_delta",
99
+ executionId,
100
+ seq,
101
+ delta: str(data.delta) ?? "",
102
+ text: str(data.delta) ?? "",
103
+ stepId: currentStepId,
104
+ name: currentStepName,
105
+ stepName: currentStepName
106
+ })
107
+ ];
108
+ case "step_complete": {
109
+ const id = str(data.id) ?? str(data.stepId);
110
+ const name = str(data.name) ?? str(data.stepName);
111
+ const out = compact({
112
+ type: "step_complete",
113
+ executionId,
114
+ seq,
115
+ stepId: id,
116
+ name,
117
+ stepName: name,
118
+ stepType: data.stepType,
119
+ result: data.result,
120
+ success: data.success,
121
+ executionTime: num(data.durationMs) ?? num(data.executionTime),
122
+ stopReason: data.stopReason,
123
+ completedAt: data.completedAt,
124
+ unresolvedVariables: data.unresolvedVariables,
125
+ error: data.error
126
+ });
127
+ currentStepId = void 0;
128
+ currentStepName = void 0;
129
+ return [out];
130
+ }
131
+ case "execution_complete":
132
+ if (data.kind !== "flow") return [];
133
+ return [
134
+ compact({
135
+ type: "flow_complete",
136
+ executionId,
137
+ seq,
138
+ success: data.success,
139
+ totalSteps: data.totalSteps,
140
+ successfulSteps: data.successfulSteps,
141
+ failedSteps: data.failedSteps,
142
+ executionTime: data.durationMs,
143
+ finalOutput: data.finalOutput,
144
+ completedAt: data.completedAt
145
+ })
146
+ ];
147
+ case "execution_error":
148
+ return [
149
+ compact({
150
+ type: "flow_error",
151
+ executionId,
152
+ seq,
153
+ error: data.error,
154
+ code: data.code,
155
+ upgradeUrl: data.upgradeUrl
156
+ })
157
+ ];
158
+ case "await":
159
+ return [
160
+ compact({
161
+ type: "flow_await",
162
+ executionId,
163
+ seq,
164
+ toolId: data.toolId ?? data.toolCallId,
165
+ toolName: data.toolName,
166
+ parameters: data.parameters,
167
+ awaitedAt: data.awaitedAt,
168
+ origin: data.origin,
169
+ pageOrigin: data.pageOrigin
170
+ })
171
+ ];
172
+ // Channels/markers/tool-family/approval/skip/source/custom/ping the flow
173
+ // consumer never read → no legacy event. (A non-terminal `error` is only
174
+ // produced on agent streams; dropping it here avoids a false flow_error.)
175
+ default:
176
+ return [];
177
+ }
178
+ };
179
+ }
180
+ function createAgentEventTranslator() {
181
+ let agentId;
182
+ let iteration;
183
+ let turnId;
184
+ let reasoningScope;
185
+ let media = null;
186
+ return (raw) => {
187
+ if (!raw || typeof raw !== "object") return [];
188
+ const data = raw;
189
+ const type = str(data.type);
190
+ if (!type) return [];
191
+ const executionId = str(data.executionId);
192
+ const seq = num(data.seq);
193
+ const iter = num(data.iteration) ?? iteration;
194
+ if (type.startsWith("agent_")) return [data];
195
+ switch (type) {
196
+ case "execution_start":
197
+ if (data.kind !== "agent") return [];
198
+ agentId = str(data.agentId);
199
+ return [
200
+ compact({
201
+ type: "agent_start",
202
+ executionId,
203
+ seq,
204
+ agentId: data.agentId,
205
+ agentName: data.agentName,
206
+ maxTurns: data.maxTurns,
207
+ startedAt: data.startedAt,
208
+ config: data.config
209
+ })
210
+ ];
211
+ case "turn_start":
212
+ turnId = str(data.id);
213
+ iteration = num(data.iteration) ?? iteration;
214
+ return [
215
+ compact({
216
+ type: "agent_turn_start",
217
+ executionId,
218
+ seq,
219
+ iteration: data.iteration ?? iteration,
220
+ turnId: data.id,
221
+ turnIndex: data.turnIndex,
222
+ role: data.role
223
+ })
224
+ ];
225
+ case "text_delta":
226
+ return [
227
+ compact({
228
+ type: "agent_turn_delta",
229
+ executionId,
230
+ seq,
231
+ iteration: iter,
232
+ turnId,
233
+ delta: str(data.delta) ?? "",
234
+ contentType: "text"
235
+ })
236
+ ];
237
+ case "reasoning_start":
238
+ reasoningScope = data.scope === "loop" ? "loop" : "turn";
239
+ return [];
240
+ case "reasoning_delta":
241
+ return [
242
+ compact({
243
+ type: "agent_turn_delta",
244
+ executionId,
245
+ seq,
246
+ iteration: iter,
247
+ turnId,
248
+ delta: str(data.delta) ?? "",
249
+ contentType: "thinking"
250
+ })
251
+ ];
252
+ case "reasoning_complete": {
253
+ const scope = data.scope === "loop" ? "loop" : reasoningScope;
254
+ reasoningScope = void 0;
255
+ if (scope === "loop") {
256
+ return [
257
+ compact({
258
+ type: "agent_reflection",
259
+ executionId,
260
+ seq,
261
+ iteration: iter,
262
+ reflection: data.text
263
+ })
264
+ ];
265
+ }
266
+ return [];
267
+ }
268
+ case "turn_complete":
269
+ return [
270
+ compact({
271
+ type: "agent_turn_complete",
272
+ executionId,
273
+ seq,
274
+ iteration: data.iteration ?? iter,
275
+ turnId: data.id,
276
+ role: data.role,
277
+ completedAt: data.completedAt,
278
+ content: data.content,
279
+ tokens: data.tokens,
280
+ cost: data.cost,
281
+ stopReason: data.stopReason
282
+ })
283
+ ];
284
+ case "tool_start":
285
+ return [
286
+ compact({
287
+ type: "agent_tool_start",
288
+ executionId,
289
+ seq,
290
+ iteration: iter,
291
+ toolCallId: data.toolCallId,
292
+ toolName: data.toolName,
293
+ toolType: data.toolType,
294
+ parameters: data.parameters,
295
+ origin: data.origin,
296
+ pageOrigin: data.pageOrigin
297
+ })
298
+ ];
299
+ case "tool_output_delta":
300
+ return [
301
+ compact({
302
+ type: "agent_tool_delta",
303
+ executionId,
304
+ seq,
305
+ iteration: iter,
306
+ toolCallId: data.toolCallId,
307
+ delta: str(data.delta) ?? ""
308
+ })
309
+ ];
310
+ case "tool_input_delta":
311
+ return [
312
+ compact({
313
+ type: "agent_tool_input_delta",
314
+ executionId,
315
+ seq,
316
+ iteration: iter,
317
+ toolCallId: data.toolCallId,
318
+ delta: str(data.delta) ?? ""
319
+ })
320
+ ];
321
+ case "tool_input_complete":
322
+ return [
323
+ compact({
324
+ type: "agent_tool_input_complete",
325
+ executionId,
326
+ seq,
327
+ iteration: iter,
328
+ toolCallId: data.toolCallId,
329
+ toolName: data.toolName,
330
+ parameters: data.parameters ?? {},
331
+ hiddenParameterNames: data.hiddenParameterNames
332
+ })
333
+ ];
334
+ case "tool_complete":
335
+ return [
336
+ compact({
337
+ type: "agent_tool_complete",
338
+ executionId,
339
+ seq,
340
+ iteration: num(data.iteration) ?? iter,
341
+ toolCallId: data.toolCallId,
342
+ toolName: data.toolName,
343
+ success: data.success,
344
+ result: data.result,
345
+ executionTime: data.executionTime
346
+ })
347
+ ];
348
+ case "media_start":
349
+ media = {
350
+ mediaType: str(data.mediaType),
351
+ role: str(data.role),
352
+ toolCallId: str(data.toolCallId),
353
+ chunks: []
354
+ };
355
+ return [];
356
+ case "media_delta": {
357
+ const delta = str(data.delta);
358
+ if (media && delta) media.chunks.push(delta);
359
+ return [];
360
+ }
361
+ case "media_complete": {
362
+ const acc = media;
363
+ media = null;
364
+ const mediaType = str(data.mediaType) ?? acc?.mediaType;
365
+ const toolCallId = str(data.toolCallId) ?? acc?.toolCallId;
366
+ const url = str(data.url);
367
+ const inlineData = str(data.data) ?? (acc && acc.chunks.length ? acc.chunks.join("") : void 0);
368
+ let item;
369
+ if (url) {
370
+ const kind = mediaType && mediaType.startsWith("image/") ? "image-url" : "file-url";
371
+ item = compact({ type: kind, url, mediaType });
372
+ } else {
373
+ item = compact({ type: "media", data: inlineData ?? "", mediaType });
374
+ }
375
+ return [
376
+ compact({
377
+ type: "agent_media",
378
+ executionId,
379
+ seq,
380
+ iteration: iter,
381
+ toolCallId,
382
+ media: [item]
383
+ })
384
+ ];
385
+ }
386
+ case "approval_start":
387
+ return [
388
+ compact({
389
+ type: "agent_approval_start",
390
+ executionId,
391
+ seq,
392
+ iteration: iter,
393
+ approvalId: data.approvalId,
394
+ toolCallId: data.toolCallId,
395
+ toolName: data.toolName,
396
+ toolType: data.toolType,
397
+ description: data.description,
398
+ reason: data.reason,
399
+ parameters: data.parameters,
400
+ timeout: data.timeout,
401
+ startedAt: data.startedAt
402
+ })
403
+ ];
404
+ case "approval_complete":
405
+ return [
406
+ compact({
407
+ type: "agent_approval_complete",
408
+ executionId,
409
+ seq,
410
+ approvalId: data.approvalId,
411
+ decision: data.decision,
412
+ completedAt: data.completedAt,
413
+ resolvedBy: data.resolvedBy
414
+ })
415
+ ];
416
+ case "await":
417
+ return [
418
+ compact({
419
+ type: "agent_await",
420
+ executionId,
421
+ seq,
422
+ toolId: data.toolId ?? data.toolCallId,
423
+ toolName: data.toolName,
424
+ parameters: data.parameters,
425
+ awaitedAt: data.awaitedAt,
426
+ origin: data.origin,
427
+ pageOrigin: data.pageOrigin
428
+ })
429
+ ];
430
+ case "execution_complete":
431
+ if (data.kind !== "agent") return [];
432
+ return [
433
+ compact({
434
+ type: "agent_complete",
435
+ executionId,
436
+ seq,
437
+ agentId: data.agentId ?? agentId,
438
+ success: data.success,
439
+ iterations: data.iterations,
440
+ stopReason: data.stopReason,
441
+ completedAt: data.completedAt,
442
+ totalCost: data.totalCost,
443
+ totalTokens: data.totalTokens,
444
+ finalOutput: data.finalOutput,
445
+ duration: data.durationMs
446
+ })
447
+ ];
448
+ case "execution_error":
449
+ return [
450
+ compact({
451
+ type: "agent_complete",
452
+ executionId,
453
+ seq,
454
+ agentId,
455
+ success: false,
456
+ stopReason: "error",
457
+ error: errorMessage(data.error),
458
+ completedAt: data.completedAt
459
+ })
460
+ ];
461
+ case "error":
462
+ return [
463
+ compact({
464
+ type: "agent_error",
465
+ executionId,
466
+ seq,
467
+ iteration: iter,
468
+ error: errorObject(data.error),
469
+ recoverable: true
470
+ })
471
+ ];
472
+ case "ping":
473
+ return [compact({ type: "agent_ping", executionId, seq, timestamp: data.timestamp })];
474
+ // turn/text/reasoning open+close markers, step_*, artifact_*, source,
475
+ // custom (fallback beat / routing), and the skill-fold result envelope
476
+ // the SDK never consumed → no legacy event.
477
+ default:
478
+ return [];
479
+ }
480
+ };
481
+ }
482
+ function errorMessage(error) {
483
+ if (typeof error === "string") return error;
484
+ if (error && typeof error === "object" && "message" in error) {
485
+ const message = error.message;
486
+ if (typeof message === "string") return message;
487
+ }
488
+ return error === void 0 ? "Agent execution failed" : JSON.stringify(error);
489
+ }
490
+ function errorObject(error) {
491
+ if (typeof error === "string") return { code: "error", message: error };
492
+ if (error && typeof error === "object") {
493
+ const e = error;
494
+ const obj = { code: e.code ?? "error", message: e.message ?? "" };
495
+ if (e.details !== void 0) obj.details = e.details;
496
+ return obj;
497
+ }
498
+ return { code: "error", message: String(error) };
499
+ }
500
+
1
501
  // src/stream-utils.ts
2
502
  function parseSSEChunk(chunk, buffer) {
3
503
  buffer += chunk;
@@ -35,7 +535,7 @@ function parseFinalBuffer(buffer) {
35
535
  }
36
536
  return null;
37
537
  }
38
- async function processStream(response, callbacks = {}) {
538
+ async function processStream(response, callbacks = {}, options = {}) {
39
539
  if (!response.ok) {
40
540
  const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
41
541
  callbacks.onError?.(error);
@@ -59,6 +559,20 @@ async function processStream(response, callbacks = {}) {
59
559
  executionTime: 0,
60
560
  success: true
61
561
  };
562
+ let translate = options.unified === true ? createFlowEventTranslator() : null;
563
+ const autoDetect = options.unified === void 0;
564
+ const dispatch = (parsed) => {
565
+ if (autoDetect && !translate && isUnifiedEventType(parsed?.type)) {
566
+ translate = createFlowEventTranslator();
567
+ }
568
+ if (translate) {
569
+ for (const ev of translate(parsed)) {
570
+ handleEvent(ev, callbacks, results, flowSummary);
571
+ }
572
+ } else {
573
+ handleEvent(parsed, callbacks, results, flowSummary);
574
+ }
575
+ };
62
576
  const contentType = response.headers.get("content-type");
63
577
  if (contentType?.includes("application/json")) {
64
578
  try {
@@ -115,8 +629,7 @@ async function processStream(response, callbacks = {}) {
115
629
  buffer = remainingBuffer;
116
630
  for (const eventStr of events) {
117
631
  try {
118
- const event = JSON.parse(eventStr);
119
- handleEvent(event, callbacks, results, flowSummary);
632
+ dispatch(JSON.parse(eventStr));
120
633
  } catch {
121
634
  console.warn("Failed to parse SSE event:", eventStr);
122
635
  }
@@ -125,8 +638,7 @@ async function processStream(response, callbacks = {}) {
125
638
  const finalEvent = parseFinalBuffer(buffer);
126
639
  if (finalEvent) {
127
640
  try {
128
- const event = JSON.parse(finalEvent);
129
- handleEvent(event, callbacks, results, flowSummary);
641
+ dispatch(JSON.parse(finalEvent));
130
642
  } catch {
131
643
  }
132
644
  }
@@ -196,10 +708,17 @@ function handleEvent(event, callbacks, results, summary) {
196
708
  break;
197
709
  }
198
710
  }
199
- async function* streamEvents(response) {
711
+ async function* streamEvents(response, options = {}) {
200
712
  if (!response.ok) {
201
713
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
202
714
  }
715
+ let translate = options.unified === true ? createFlowEventTranslator() : null;
716
+ const autoDetect = options.unified === void 0;
717
+ const maybeDetect = (parsed) => {
718
+ if (autoDetect && !translate && isUnifiedEventType(parsed?.type)) {
719
+ translate = createFlowEventTranslator();
720
+ }
721
+ };
203
722
  const contentType = response.headers.get("content-type");
204
723
  if (contentType?.includes("application/json")) {
205
724
  try {
@@ -229,19 +748,35 @@ async function* streamEvents(response) {
229
748
  const { events, remainingBuffer } = parseSSEChunk(chunk, buffer);
230
749
  buffer = remainingBuffer;
231
750
  for (const eventStr of events) {
751
+ let parsed;
232
752
  try {
233
- const event = JSON.parse(eventStr);
234
- yield event;
753
+ parsed = JSON.parse(eventStr);
235
754
  } catch {
755
+ continue;
756
+ }
757
+ maybeDetect(parsed);
758
+ if (translate) {
759
+ for (const ev of translate(parsed)) yield ev;
760
+ } else {
761
+ yield parsed;
236
762
  }
237
763
  }
238
764
  }
239
765
  const finalEvent = parseFinalBuffer(buffer);
240
766
  if (finalEvent) {
767
+ let parsed;
241
768
  try {
242
- const event = JSON.parse(finalEvent);
243
- yield event;
769
+ parsed = JSON.parse(finalEvent);
244
770
  } catch {
771
+ parsed = void 0;
772
+ }
773
+ if (parsed !== void 0) {
774
+ maybeDetect(parsed);
775
+ if (translate) {
776
+ for (const ev of translate(parsed)) yield ev;
777
+ } else {
778
+ yield parsed;
779
+ }
245
780
  }
246
781
  }
247
782
  } finally {
@@ -251,10 +786,16 @@ async function* streamEvents(response) {
251
786
 
252
787
  // src/flow-result.ts
253
788
  var FlowResult = class {
254
- constructor(response, summary) {
789
+ /**
790
+ * @param options.unified - The response is a unified-vocabulary SSE stream
791
+ * (`/dispatch` since the unified-SSE cutover). Set by dispatch call sites;
792
+ * left unset by the still-legacy eval stream producer.
793
+ */
794
+ constructor(response, summary, options = {}) {
255
795
  this.consumed = false;
256
796
  this.cachedSummary = null;
257
797
  this.response = response;
798
+ this.streamOptions = options;
258
799
  if (summary) {
259
800
  this.cachedSummary = summary;
260
801
  this.consumed = true;
@@ -307,7 +848,7 @@ var FlowResult = class {
307
848
  }
308
849
  this.ensureNotConsumed();
309
850
  this.consumed = true;
310
- this.cachedSummary = await processStream(this.response, callbacks);
851
+ this.cachedSummary = await processStream(this.response, callbacks, this.streamOptions);
311
852
  return this.cachedSummary;
312
853
  }
313
854
  /**
@@ -331,6 +872,7 @@ var FlowResult = class {
331
872
  * const analysis = await result.getResult('analyze screenshot') // ✗ undefined
332
873
  * ```
333
874
  */
875
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK step results are intentionally untyped (FlowSummary.results is Map<string, any>); consumers narrow at the use site
334
876
  async getResult(stepName) {
335
877
  const summary = await this.ensureSummary();
336
878
  if (summary.results.has(stepName)) {
@@ -351,6 +893,7 @@ var FlowResult = class {
351
893
  * }
352
894
  * ```
353
895
  */
896
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any -- SDK step results are intentionally untyped (FlowSummary.results is Map<string, any>); consumers narrow at the use site
354
897
  async getAllResults() {
355
898
  const summary = await this.ensureSummary();
356
899
  return summary.results;
@@ -1153,9 +1696,9 @@ var FlowBuilder = class {
1153
1696
  }
1154
1697
  const response = await client.dispatch(config);
1155
1698
  if (callbacks) {
1156
- return processStream(response, callbacks);
1699
+ return processStream(response, callbacks, { unified: true });
1157
1700
  }
1158
- return new FlowResult(response);
1701
+ return new FlowResult(response, void 0, { unified: true });
1159
1702
  }
1160
1703
  /**
1161
1704
  * Set a run condition (when predicate) on the last added step.
@@ -1287,9 +1830,9 @@ var ClientFlowBuilder = class extends FlowBuilder {
1287
1830
  }
1288
1831
  const response = await dispatchClient.dispatch(config);
1289
1832
  if (runCallbacks) {
1290
- return processStream(response, runCallbacks);
1833
+ return processStream(response, runCallbacks, { unified: true });
1291
1834
  }
1292
- return new FlowResult(response);
1835
+ return new FlowResult(response, void 0, { unified: true });
1293
1836
  }
1294
1837
  };
1295
1838
  function isStreamCallbacks(obj) {
@@ -2307,7 +2850,7 @@ var RuntypeFlowBuilder = class {
2307
2850
  config.options = { ...config.options, streamResponse: true };
2308
2851
  const client = this.getClient();
2309
2852
  const response = await this.dispatchWithPersistedFlow(client, config);
2310
- const result = new FlowResult(response);
2853
+ const result = new FlowResult(response, void 0, { unified: true });
2311
2854
  if (callbacks) {
2312
2855
  await result.stream(callbacks);
2313
2856
  }
@@ -2336,7 +2879,7 @@ var RuntypeFlowBuilder = class {
2336
2879
  config.options = { ...config.options, streamResponse: true };
2337
2880
  const client = this.getClient();
2338
2881
  const response = await this.dispatchWithPersistedFlow(client, config);
2339
- const result = new FlowResult(response);
2882
+ const result = new FlowResult(response, void 0, { unified: true });
2340
2883
  await result.getSummary();
2341
2884
  return result;
2342
2885
  }
@@ -2371,7 +2914,7 @@ var RuntypeFlowBuilder = class {
2371
2914
  onError: (error) => callbacks?.onError?.(error)
2372
2915
  };
2373
2916
  try {
2374
- for await (const event of streamEvents(response)) {
2917
+ for await (const event of streamEvents(response, { unified: true })) {
2375
2918
  collectLocalToolAwait(pausedTools, event);
2376
2919
  switch (event.type) {
2377
2920
  case "flow_start":
@@ -2479,7 +3022,7 @@ var RuntypeFlowBuilder = class {
2479
3022
  streamResponse: isStreaming
2480
3023
  };
2481
3024
  if (isStreaming) {
2482
- currentResponse = await client.requestStream("/dispatch/resume", {
3025
+ currentResponse = await client.requestStream(withUnifiedEvents("/dispatch/resume"), {
2483
3026
  method: "POST",
2484
3027
  body: JSON.stringify(resumeData)
2485
3028
  });
@@ -2912,138 +3455,10 @@ var EvalsNamespace = class {
2912
3455
  };
2913
3456
 
2914
3457
  // src/prompts-namespace.ts
2915
- var PromptRunner = class {
2916
- constructor(getClient, promptId, options) {
2917
- this.getClient = getClient;
2918
- this.promptId = promptId;
2919
- this.options = options;
2920
- }
2921
- /**
2922
- * Execute the prompt with streaming response
2923
- *
2924
- * Streams the prompt response as it's generated.
2925
- *
2926
- * @example
2927
- * ```typescript
2928
- * const result = await Runtype.prompts.run('prompt_123', {
2929
- * recordId: 'rec_456'
2930
- * }).stream()
2931
- *
2932
- * // Process with callbacks
2933
- * await result.stream({
2934
- * onStepDelta: (text) => process.stdout.write(text),
2935
- * onFlowComplete: () => console.log('Done!'),
2936
- * })
2937
- * ```
2938
- */
2939
- async stream(callbacks) {
2940
- const client = this.getClient();
2941
- const payload = this.buildPayload();
2942
- payload.stream = true;
2943
- const response = await client.requestStream(`/prompts/${this.promptId}/run`, {
2944
- method: "POST",
2945
- body: JSON.stringify(payload)
2946
- });
2947
- const result = new FlowResult(response);
2948
- if (callbacks) {
2949
- await result.stream(callbacks);
2950
- }
2951
- return result;
2952
- }
2953
- /**
2954
- * Execute the prompt and wait for complete result
2955
- *
2956
- * Waits for the entire response before returning.
2957
- *
2958
- * @example
2959
- * ```typescript
2960
- * const result = await Runtype.prompts.run('prompt_123', {
2961
- * recordId: 'rec_456'
2962
- * }).result()
2963
- *
2964
- * const output = await result.getResult('prompt')
2965
- * console.log(output)
2966
- * ```
2967
- */
2968
- async result() {
2969
- const client = this.getClient();
2970
- const payload = this.buildPayload();
2971
- payload.stream = true;
2972
- const response = await client.requestStream(`/prompts/${this.promptId}/run`, {
2973
- method: "POST",
2974
- body: JSON.stringify(payload)
2975
- });
2976
- const result = new FlowResult(response);
2977
- await result.getSummary();
2978
- return result;
2979
- }
2980
- /**
2981
- * Build the run payload
2982
- */
2983
- buildPayload() {
2984
- const payload = {};
2985
- if (this.options.recordId) {
2986
- payload.recordId = this.options.recordId;
2987
- } else if (this.options.record) {
2988
- payload.record = this.options.record;
2989
- }
2990
- if (this.options.modelOverride) {
2991
- payload.modelOverride = this.options.modelOverride;
2992
- }
2993
- if (this.options.temperature !== void 0) {
2994
- payload.temperature = this.options.temperature;
2995
- }
2996
- if (this.options.topP !== void 0) {
2997
- payload.topP = this.options.topP;
2998
- }
2999
- if (this.options.topK !== void 0) {
3000
- payload.topK = this.options.topK;
3001
- }
3002
- if (this.options.frequencyPenalty !== void 0) {
3003
- payload.frequencyPenalty = this.options.frequencyPenalty;
3004
- }
3005
- if (this.options.presencePenalty !== void 0) {
3006
- payload.presencePenalty = this.options.presencePenalty;
3007
- }
3008
- if (this.options.seed !== void 0) {
3009
- payload.seed = this.options.seed;
3010
- }
3011
- if (this.options.maxTokens !== void 0) {
3012
- payload.maxTokens = this.options.maxTokens;
3013
- }
3014
- if (this.options.storeResult !== void 0) {
3015
- payload.storeResult = this.options.storeResult;
3016
- }
3017
- return payload;
3018
- }
3019
- };
3020
3458
  var PromptsNamespace = class {
3021
3459
  constructor(getClient) {
3022
3460
  this.getClient = getClient;
3023
3461
  }
3024
- /**
3025
- * Run a prompt
3026
- *
3027
- * Returns a PromptRunner with terminal methods:
3028
- * - .stream() - Execute and stream results
3029
- * - .result() - Execute and wait for complete result
3030
- *
3031
- * @example
3032
- * ```typescript
3033
- * // Stream the response
3034
- * const result = await Runtype.prompts.run('prompt_123', {
3035
- * recordId: 'rec_456'
3036
- * }).stream()
3037
- *
3038
- * // Get complete result
3039
- * const result = await Runtype.prompts.run('prompt_123', {
3040
- * record: { name: 'Test', metadata: { input: 'Hello' } }
3041
- * }).result()
3042
- * ```
3043
- */
3044
- run(promptId, options = {}) {
3045
- return new PromptRunner(this.getClient, promptId, options);
3046
- }
3047
3462
  /**
3048
3463
  * Create a new prompt
3049
3464
  *
@@ -4723,7 +5138,7 @@ var RuntypeClient = class {
4723
5138
  * Dispatch flow execution (streaming)
4724
5139
  */
4725
5140
  async dispatch(config) {
4726
- return this.requestStream("/dispatch", {
5141
+ return this.requestStream(withUnifiedEvents("/dispatch"), {
4727
5142
  method: "POST",
4728
5143
  body: JSON.stringify(transformRequest(config))
4729
5144
  });
@@ -5094,7 +5509,7 @@ var Runtype = class {
5094
5509
 
5095
5510
  // src/version.ts
5096
5511
  var FALLBACK_VERSION = "0.0.0";
5097
- var SDK_VERSION = "4.20.0".length > 0 ? "4.20.0" : FALLBACK_VERSION;
5512
+ var SDK_VERSION = "5.0.0".length > 0 ? "5.0.0" : FALLBACK_VERSION;
5098
5513
  var RUNTYPE_CLIENT_KIND = "sdk";
5099
5514
  var SDK_USER_AGENT = `runtype-sdk/${SDK_VERSION} (typescript)`;
5100
5515
 
@@ -7217,12 +7632,6 @@ var PromptsEndpoint = class {
7217
7632
  async delete(id) {
7218
7633
  return this.client.delete(`/prompts/${id}`);
7219
7634
  }
7220
- /**
7221
- * Run a prompt on a specific record
7222
- */
7223
- async runOnRecord(id, recordId) {
7224
- return this.client.post(`/prompts/${id}/run-on-record`, { recordId });
7225
- }
7226
7635
  /**
7227
7636
  * Get flows using this prompt
7228
7637
  */
@@ -7588,7 +7997,7 @@ var DispatchEndpoint = class {
7588
7997
  * Dispatch with streaming response
7589
7998
  */
7590
7999
  async executeStream(data) {
7591
- return this.client.requestStream("/dispatch", {
8000
+ return this.client.requestStream(withUnifiedEvents("/dispatch"), {
7592
8001
  method: "POST",
7593
8002
  body: JSON.stringify(data)
7594
8003
  });
@@ -7604,7 +8013,7 @@ var DispatchEndpoint = class {
7604
8013
  */
7605
8014
  async resume(data) {
7606
8015
  if (data.streamResponse) {
7607
- return this.client.requestStream("/dispatch/resume", {
8016
+ return this.client.requestStream(withUnifiedEvents("/dispatch/resume"), {
7608
8017
  method: "POST",
7609
8018
  body: JSON.stringify(data)
7610
8019
  });
@@ -8119,6 +8528,19 @@ async function processAgentStream(body, callbacks) {
8119
8528
  const reader = body.getReader();
8120
8529
  const decoder = new TextDecoder();
8121
8530
  let buffer = "";
8531
+ let translate = null;
8532
+ const dispatch = (event) => {
8533
+ if (!translate && isUnifiedEventType(event.data?.type ?? event.eventType)) {
8534
+ translate = createAgentEventTranslator();
8535
+ }
8536
+ if (translate) {
8537
+ for (const legacy of translate(event.data)) {
8538
+ dispatchAgentEvent({ eventType: legacy.type, data: legacy }, callbacks);
8539
+ }
8540
+ } else {
8541
+ dispatchAgentEvent(event, callbacks);
8542
+ }
8543
+ };
8122
8544
  try {
8123
8545
  while (true) {
8124
8546
  const { done, value } = await reader.read();
@@ -8126,7 +8548,7 @@ async function processAgentStream(body, callbacks) {
8126
8548
  if (buffer.trim()) {
8127
8549
  const { events: events2 } = parseSSEChunkWithEventType(buffer + "\n\n", "");
8128
8550
  for (const event of events2) {
8129
- dispatchAgentEvent(event, callbacks);
8551
+ dispatch(event);
8130
8552
  }
8131
8553
  }
8132
8554
  break;
@@ -8135,7 +8557,7 @@ async function processAgentStream(body, callbacks) {
8135
8557
  const { events, remainingBuffer } = parseSSEChunkWithEventType(chunk, buffer);
8136
8558
  buffer = remainingBuffer;
8137
8559
  for (const event of events) {
8138
- dispatchAgentEvent(event, callbacks);
8560
+ dispatch(event);
8139
8561
  }
8140
8562
  }
8141
8563
  } finally {
@@ -8323,7 +8745,7 @@ var _AgentsEndpoint = class _AgentsEndpoint {
8323
8745
  * ```
8324
8746
  */
8325
8747
  async executeStream(id, data, init) {
8326
- return this.client.requestStream(`/agents/${id}/execute`, {
8748
+ return this.client.requestStream(withUnifiedEvents(`/agents/${id}/execute`), {
8327
8749
  method: "POST",
8328
8750
  body: JSON.stringify({
8329
8751
  ...data,
@@ -8675,16 +9097,19 @@ var _AgentsEndpoint = class _AgentsEndpoint {
8675
9097
  }
8676
9098
  let resumeResponse;
8677
9099
  try {
8678
- resumeResponse = await this.client.requestStream(`/agents/${id}/resume`, {
8679
- method: "POST",
8680
- body: JSON.stringify({
8681
- executionId,
8682
- toolOutputs: { [toolName]: toolResult },
8683
- streamResponse: true,
8684
- debugMode: data.debugMode
8685
- }),
8686
- ...abortSignal ? { signal: abortSignal } : {}
8687
- });
9100
+ resumeResponse = await this.client.requestStream(
9101
+ withUnifiedEvents(`/agents/${id}/resume`),
9102
+ {
9103
+ method: "POST",
9104
+ body: JSON.stringify({
9105
+ executionId,
9106
+ toolOutputs: { [toolName]: toolResult },
9107
+ streamResponse: true,
9108
+ debugMode: data.debugMode
9109
+ }),
9110
+ ...abortSignal ? { signal: abortSignal } : {}
9111
+ }
9112
+ );
8688
9113
  } catch (error) {
8689
9114
  if (abortSignal?.aborted) return finishAborted(executionId);
8690
9115
  throw error;
@@ -10149,9 +10574,9 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10149
10574
  }
10150
10575
  /** Returns true if a server-side session error message indicates a transient
10151
10576
  * network failure that is safe to retry. */
10152
- static isRetryableSessionError(errorMessage) {
10153
- if (!errorMessage) return false;
10154
- const lower = errorMessage.toLowerCase();
10577
+ static isRetryableSessionError(errorMessage2) {
10578
+ if (!errorMessage2) return false;
10579
+ const lower = errorMessage2.toLowerCase();
10155
10580
  return _AgentsEndpoint.RETRYABLE_SESSION_ERROR_PATTERNS.some(
10156
10581
  (pattern) => lower.includes(pattern)
10157
10582
  );
@@ -11603,7 +12028,7 @@ var RuntypeClient2 = class {
11603
12028
  success: true
11604
12029
  };
11605
12030
  try {
11606
- for await (const event of streamEvents(response)) {
12031
+ for await (const event of streamEvents(response, { unified: true })) {
11607
12032
  collectLocalToolAwait(pausedTools, event);
11608
12033
  switch (event.type) {
11609
12034
  case "flow_start":
@@ -12757,7 +13182,6 @@ export {
12757
13182
  ProductDriftError,
12758
13183
  ProductEnsureConflictError,
12759
13184
  ProductsNamespace,
12760
- PromptRunner,
12761
13185
  PromptsEndpoint,
12762
13186
  PromptsNamespace,
12763
13187
  ProviderKeysEndpoint,
@@ -12786,6 +13210,7 @@ export {
12786
13210
  ToolEnsureConflictError,
12787
13211
  ToolsEndpoint,
12788
13212
  ToolsNamespace,
13213
+ UNIFIED_EVENTS_QUERY,
12789
13214
  UsersEndpoint,
12790
13215
  applyGeneratedRuntimeToolProposalToDispatchRequest,
12791
13216
  attachRuntimeToolsToDispatchRequest,
@@ -12802,8 +13227,10 @@ export {
12802
13227
  computeSkillContentHash,
12803
13228
  computeSurfaceContentHash,
12804
13229
  computeToolContentHash,
13230
+ createAgentEventTranslator,
12805
13231
  createClient,
12806
13232
  createExternalTool,
13233
+ createFlowEventTranslator,
12807
13234
  defaultWorkflow,
12808
13235
  defaultWorkflowConfig,
12809
13236
  defineAgent,
@@ -12826,6 +13253,7 @@ export {
12826
13253
  isDiscoveryToolName,
12827
13254
  isMarathonArtifactPath,
12828
13255
  isPreservationSensitiveTask,
13256
+ isUnifiedEventType,
12829
13257
  isWorkflowHookRef,
12830
13258
  listWorkflowHooks,
12831
13259
  normalizeAgentDefinition,
@@ -12848,5 +13276,6 @@ export {
12848
13276
  shouldInjectEmptySessionNudge,
12849
13277
  shouldRequestModelEscalation,
12850
13278
  streamEvents,
12851
- unregisterWorkflowHook
13279
+ unregisterWorkflowHook,
13280
+ withUnifiedEvents
12852
13281
  };