@dogpile/sdk 0.3.0 → 0.4.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.
Files changed (105) hide show
  1. package/CHANGELOG.md +145 -0
  2. package/README.md +1 -0
  3. package/dist/browser/index.js +2270 -507
  4. package/dist/browser/index.js.map +1 -1
  5. package/dist/index.d.ts +5 -1
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +2 -0
  8. package/dist/index.js.map +1 -1
  9. package/dist/providers/openai-compatible.d.ts +11 -0
  10. package/dist/providers/openai-compatible.d.ts.map +1 -1
  11. package/dist/providers/openai-compatible.js +87 -2
  12. package/dist/providers/openai-compatible.js.map +1 -1
  13. package/dist/runtime/broadcast.d.ts.map +1 -1
  14. package/dist/runtime/broadcast.js +1 -13
  15. package/dist/runtime/broadcast.js.map +1 -1
  16. package/dist/runtime/cancellation.d.ts +26 -0
  17. package/dist/runtime/cancellation.d.ts.map +1 -1
  18. package/dist/runtime/cancellation.js +38 -1
  19. package/dist/runtime/cancellation.js.map +1 -1
  20. package/dist/runtime/coordinator.d.ts +74 -1
  21. package/dist/runtime/coordinator.d.ts.map +1 -1
  22. package/dist/runtime/coordinator.js +929 -34
  23. package/dist/runtime/coordinator.js.map +1 -1
  24. package/dist/runtime/decisions.d.ts +25 -3
  25. package/dist/runtime/decisions.d.ts.map +1 -1
  26. package/dist/runtime/decisions.js +241 -3
  27. package/dist/runtime/decisions.js.map +1 -1
  28. package/dist/runtime/defaults.d.ts +37 -1
  29. package/dist/runtime/defaults.d.ts.map +1 -1
  30. package/dist/runtime/defaults.js +347 -0
  31. package/dist/runtime/defaults.js.map +1 -1
  32. package/dist/runtime/engine.d.ts.map +1 -1
  33. package/dist/runtime/engine.js +254 -24
  34. package/dist/runtime/engine.js.map +1 -1
  35. package/dist/runtime/ids.d.ts +19 -0
  36. package/dist/runtime/ids.d.ts.map +1 -0
  37. package/dist/runtime/ids.js +36 -0
  38. package/dist/runtime/ids.js.map +1 -0
  39. package/dist/runtime/logger.d.ts +61 -0
  40. package/dist/runtime/logger.d.ts.map +1 -0
  41. package/dist/runtime/logger.js +114 -0
  42. package/dist/runtime/logger.js.map +1 -0
  43. package/dist/runtime/retry.d.ts +99 -0
  44. package/dist/runtime/retry.d.ts.map +1 -0
  45. package/dist/runtime/retry.js +181 -0
  46. package/dist/runtime/retry.js.map +1 -0
  47. package/dist/runtime/sequential.d.ts.map +1 -1
  48. package/dist/runtime/sequential.js +9 -11
  49. package/dist/runtime/sequential.js.map +1 -1
  50. package/dist/runtime/shared.d.ts.map +1 -1
  51. package/dist/runtime/shared.js +1 -13
  52. package/dist/runtime/shared.js.map +1 -1
  53. package/dist/runtime/tools/built-in.d.ts +99 -0
  54. package/dist/runtime/tools/built-in.d.ts.map +1 -0
  55. package/dist/runtime/tools/built-in.js +577 -0
  56. package/dist/runtime/tools/built-in.js.map +1 -0
  57. package/dist/runtime/tools/vercel-ai.d.ts +67 -0
  58. package/dist/runtime/tools/vercel-ai.d.ts.map +1 -0
  59. package/dist/runtime/tools/vercel-ai.js +148 -0
  60. package/dist/runtime/tools/vercel-ai.js.map +1 -0
  61. package/dist/runtime/tools.d.ts +5 -268
  62. package/dist/runtime/tools.d.ts.map +1 -1
  63. package/dist/runtime/tools.js +7 -770
  64. package/dist/runtime/tools.js.map +1 -1
  65. package/dist/runtime/validation.d.ts +10 -0
  66. package/dist/runtime/validation.d.ts.map +1 -1
  67. package/dist/runtime/validation.js +73 -0
  68. package/dist/runtime/validation.js.map +1 -1
  69. package/dist/types/benchmark.d.ts +276 -0
  70. package/dist/types/benchmark.d.ts.map +1 -0
  71. package/dist/types/benchmark.js +2 -0
  72. package/dist/types/benchmark.js.map +1 -0
  73. package/dist/types/events.d.ts +816 -0
  74. package/dist/types/events.d.ts.map +1 -0
  75. package/dist/types/events.js +2 -0
  76. package/dist/types/events.js.map +1 -0
  77. package/dist/types/replay.d.ts +173 -0
  78. package/dist/types/replay.d.ts.map +1 -0
  79. package/dist/types/replay.js +2 -0
  80. package/dist/types/replay.js.map +1 -0
  81. package/dist/types.d.ts +135 -938
  82. package/dist/types.d.ts.map +1 -1
  83. package/dist/types.js.map +1 -1
  84. package/package.json +27 -1
  85. package/src/index.ts +14 -0
  86. package/src/providers/openai-compatible.ts +82 -3
  87. package/src/runtime/broadcast.ts +1 -16
  88. package/src/runtime/cancellation.ts +59 -1
  89. package/src/runtime/coordinator.ts +1164 -34
  90. package/src/runtime/decisions.ts +307 -4
  91. package/src/runtime/defaults.ts +376 -0
  92. package/src/runtime/engine.ts +363 -24
  93. package/src/runtime/ids.ts +41 -0
  94. package/src/runtime/logger.ts +152 -0
  95. package/src/runtime/retry.ts +270 -0
  96. package/src/runtime/sequential.ts +10 -13
  97. package/src/runtime/shared.ts +1 -16
  98. package/src/runtime/tools/built-in.ts +875 -0
  99. package/src/runtime/tools/vercel-ai.ts +269 -0
  100. package/src/runtime/tools.ts +60 -1255
  101. package/src/runtime/validation.ts +81 -0
  102. package/src/types/benchmark.ts +300 -0
  103. package/src/types/events.ts +895 -0
  104. package/src/types/replay.ts +212 -0
  105. package/src/types.ts +251 -997
@@ -0,0 +1,895 @@
1
+ import type {
2
+ BudgetCaps,
3
+ BudgetStopReason,
4
+ CostSummary,
5
+ JsonObject,
6
+ JsonValue,
7
+ ModelFinishReason,
8
+ ModelOutputChunk,
9
+ ModelRequest,
10
+ ModelResponse,
11
+ NormalizedQualityScore,
12
+ Protocol,
13
+ ProtocolName,
14
+ RunEvaluation,
15
+ RunResult,
16
+ RuntimeToolIdentity,
17
+ RuntimeToolPermission,
18
+ RuntimeToolResult,
19
+ TerminationStopRecord,
20
+ Trace
21
+ } from "../types.js";
22
+
23
+
24
+ /**
25
+ * Event emitted when a protocol assigns or records an agent role.
26
+ *
27
+ * @remarks
28
+ * This event normally appears near the beginning of a run and establishes the
29
+ * `agentId`/`role` pair that later turn and transcript records refer to. A
30
+ * renderer can use it to build the participant roster before model output
31
+ * starts streaming.
32
+ *
33
+ * Payload shape:
34
+ *
35
+ * - `type`: always `role-assignment`.
36
+ * - `runId`: stable id shared by every event and trace object for the run.
37
+ * - `at`: ISO-8601 timestamp for when the assignment was emitted.
38
+ * - `agentId`: stable agent id used in events, trace, and transcript entries.
39
+ * - `role`: model-visible role or perspective assigned to that agent.
40
+ */
41
+ export interface RoleAssignmentEvent {
42
+ /** Discriminant for event rendering and exhaustive switches. */
43
+ readonly type: "role-assignment";
44
+ /** Stable run id shared by all events in one workflow. */
45
+ readonly runId: string;
46
+ /** Root-first ancestry chain when bubbled through a parent stream. */
47
+ readonly parentRunIds?: readonly string[];
48
+ /** ISO-8601 event timestamp. */
49
+ readonly at: string;
50
+ /** Agent receiving the role assignment. */
51
+ readonly agentId: string;
52
+ /** Role assigned to the agent. */
53
+ readonly role: string;
54
+ }
55
+
56
+ /**
57
+ * Event emitted when Dogpile is about to ask the configured model provider for
58
+ * one protocol-managed response.
59
+ *
60
+ * @remarks
61
+ * This event is the request-side model activity counterpart to
62
+ * {@link ModelResponseEvent}. Protocol implementations may omit it when they
63
+ * only expose completed turns, but adapters and researcher harnesses can emit
64
+ * it to make provider calls visible in the same streaming event log as agent
65
+ * turns and final output.
66
+ */
67
+ export interface ModelRequestEvent {
68
+ /** Discriminant for event rendering and exhaustive switches. */
69
+ readonly type: "model-request";
70
+ /** Stable run id shared by all events in one workflow. */
71
+ readonly runId: string;
72
+ /** Root-first ancestry chain when bubbled through a parent stream. */
73
+ readonly parentRunIds?: readonly string[];
74
+ /** ISO-8601 event timestamp. */
75
+ readonly at: string;
76
+ /** Stable provider call id within the run. */
77
+ readonly callId: string;
78
+ /** Configured model provider id receiving the request. */
79
+ readonly providerId: string;
80
+ /** Agent requesting the model call. */
81
+ readonly agentId: string;
82
+ /** Agent role for the active model call. */
83
+ readonly role: string;
84
+ /** Provider-neutral request handed to the model adapter. */
85
+ readonly request: ModelRequest;
86
+ }
87
+
88
+ /**
89
+ * Event emitted after the configured model provider returns one response.
90
+ *
91
+ * @remarks
92
+ * This event records provider-level model activity without forcing callers to
93
+ * infer it from the higher-level {@link TurnEvent}. The response is the same
94
+ * provider-neutral shape captured in replay traces, so it remains portable and
95
+ * JSON-serializable across Node LTS, Bun, and browser ESM runtimes.
96
+ */
97
+ export interface ModelResponseEvent {
98
+ /** Discriminant for event rendering and exhaustive switches. */
99
+ readonly type: "model-response";
100
+ /** Stable run id shared by all events in one workflow. */
101
+ readonly runId: string;
102
+ /** Root-first ancestry chain when bubbled through a parent stream. */
103
+ readonly parentRunIds?: readonly string[];
104
+ /** ISO-8601 event timestamp. */
105
+ readonly at: string;
106
+ /** Stable provider call id within the run. */
107
+ readonly callId: string;
108
+ /** Configured model provider id that produced the response. */
109
+ readonly providerId: string;
110
+ /** Agent that requested the model call. */
111
+ readonly agentId: string;
112
+ /** Agent role for the completed model call. */
113
+ readonly role: string;
114
+ /** Provider-neutral response returned by the model adapter. */
115
+ readonly response: ModelResponse;
116
+ }
117
+
118
+ /**
119
+ * Event emitted while a model turn is still generating text.
120
+ *
121
+ * @remarks
122
+ * `model-output-chunk` lets streaming callers render provider output before
123
+ * the protocol has enough information to commit the completed `agent-turn`
124
+ * transcript entry. It is emitted only when the configured model provider
125
+ * implements {@link ConfiguredModelProvider.stream}; non-streaming providers
126
+ * continue to produce the existing role/turn/final event sequence.
127
+ *
128
+ * Payload shape:
129
+ *
130
+ * - `type`: always `model-output-chunk`.
131
+ * - `runId`: stable id shared by every event and trace object for the run.
132
+ * - `at`: ISO-8601 timestamp for when the chunk was observed.
133
+ * - `agentId` and `role`: identify the active generating agent.
134
+ * - `input`: prompt text visible to that agent for this turn.
135
+ * - `chunkIndex`: zero-based chunk index within this model turn.
136
+ * - `text`: text delta from the provider.
137
+ * - `output`: accumulated output for this turn after applying the chunk.
138
+ */
139
+ export interface ModelOutputChunkEvent {
140
+ /** Discriminant for event rendering and exhaustive switches. */
141
+ readonly type: "model-output-chunk";
142
+ /** Stable run id shared by all events in one workflow. */
143
+ readonly runId: string;
144
+ /** Root-first ancestry chain when bubbled through a parent stream. */
145
+ readonly parentRunIds?: readonly string[];
146
+ /** ISO-8601 event timestamp. */
147
+ readonly at: string;
148
+ /** Agent currently producing output. */
149
+ readonly agentId: string;
150
+ /** Agent role for the active turn. */
151
+ readonly role: string;
152
+ /** Prompt/input visible to the agent for this turn. */
153
+ readonly input: string;
154
+ /** Zero-based chunk index within the active model turn. */
155
+ readonly chunkIndex: number;
156
+ /** Text delta produced by the model provider. */
157
+ readonly text: string;
158
+ /** Accumulated output for this turn after applying this chunk. */
159
+ readonly output: string;
160
+ }
161
+
162
+ /**
163
+ * Event emitted when a runtime tool is invoked by protocol or model policy.
164
+ *
165
+ * @remarks
166
+ * Tools are caller-owned escape hatches. This request-side event keeps tool
167
+ * invocation observable without making Dogpile core depend on Node-only
168
+ * capabilities, a storage layer, or a provider-specific function-call shape.
169
+ */
170
+ export interface ToolCallEvent {
171
+ /** Discriminant for event rendering and exhaustive switches. */
172
+ readonly type: "tool-call";
173
+ /** Stable run id shared by all events in one workflow. */
174
+ readonly runId: string;
175
+ /** Root-first ancestry chain when bubbled through a parent stream. */
176
+ readonly parentRunIds?: readonly string[];
177
+ /** ISO-8601 event timestamp. */
178
+ readonly at: string;
179
+ /** Stable tool call id within the run. */
180
+ readonly toolCallId: string;
181
+ /** Tool identity selected for execution. */
182
+ readonly tool: RuntimeToolIdentity;
183
+ /** JSON-serializable tool input. */
184
+ readonly input: JsonObject;
185
+ /** Agent that requested the tool, when agent-scoped. */
186
+ readonly agentId?: string;
187
+ /** Agent role that requested the tool, when available. */
188
+ readonly role?: string;
189
+ }
190
+
191
+ /**
192
+ * Event emitted after a runtime tool returns a normalized result.
193
+ *
194
+ * @remarks
195
+ * Tool failures are data at the public boundary. The result payload uses the
196
+ * same discriminated union as runtime tool adapters, allowing log consumers to
197
+ * render successful outputs and normalized errors exhaustively.
198
+ */
199
+ export interface ToolResultEvent {
200
+ /** Discriminant for event rendering and exhaustive switches. */
201
+ readonly type: "tool-result";
202
+ /** Stable run id shared by all events in one workflow. */
203
+ readonly runId: string;
204
+ /** Root-first ancestry chain when bubbled through a parent stream. */
205
+ readonly parentRunIds?: readonly string[];
206
+ /** ISO-8601 event timestamp. */
207
+ readonly at: string;
208
+ /** Stable tool call id within the run. */
209
+ readonly toolCallId: string;
210
+ /** Tool identity that produced the result. */
211
+ readonly tool: RuntimeToolIdentity;
212
+ /** Normalized JSON-serializable tool result. */
213
+ readonly result: RuntimeToolResult;
214
+ /** Agent that requested the tool, when agent-scoped. */
215
+ readonly agentId?: string;
216
+ /** Agent role that requested the tool, when available. */
217
+ readonly role?: string;
218
+ }
219
+
220
+ /**
221
+ * Provider-normalized participation decision parsed from paper-style agent output.
222
+ *
223
+ * @remarks
224
+ * Dogpile preserves the raw model text on transcript entries and events. When
225
+ * a model emits the labeled fields `role_selected`, `participation`,
226
+ * `rationale`, and `contribution`, protocols also attach this structured
227
+ * metadata so reproduction harnesses can distinguish contribution from
228
+ * voluntary abstention without reparsing raw text.
229
+ */
230
+ export interface ParticipateAgentDecision {
231
+ /** Discriminant marking this as a participate-style decision. */
232
+ readonly type: "participate";
233
+ /** Task-specific role selected by the agent for this turn. */
234
+ readonly selectedRole: string;
235
+ /** Whether the agent contributed or voluntarily abstained. */
236
+ readonly participation: AgentParticipation;
237
+ /** Agent-provided rationale for the selected role and participation choice. */
238
+ readonly rationale: string;
239
+ /** Agent-provided contribution text, or abstention explanation. */
240
+ readonly contribution: string;
241
+ }
242
+
243
+ /**
244
+ * Decision emitted by a coordinator agent that delegates a sub-mission to a
245
+ * coordination protocol rather than contributing directly. The runtime
246
+ * dispatches a child run when this decision is returned.
247
+ */
248
+ export interface DelegateAgentDecision {
249
+ /** Discriminant marking this as a delegate-style decision. */
250
+ readonly type: "delegate";
251
+ /** Coordination protocol the child sub-run will execute. */
252
+ readonly protocol: ProtocolName;
253
+ /** Mission text passed to the child sub-run. */
254
+ readonly intent: string;
255
+ /**
256
+ * Optional model provider id assertion. When set, the runtime requires the
257
+ * value to match the parent's `ConfiguredModelProvider.id` (D-11) — child
258
+ * runs always inherit the parent provider instance verbatim.
259
+ */
260
+ readonly model?: string;
261
+ /** Optional per-decision budget caps applied to the child run. */
262
+ readonly budget?: BudgetCaps;
263
+ /**
264
+ * Optional per-decision child concurrency ceiling. This can only lower the
265
+ * engine/run effective max for the current coordinator fan-out turn (D-05).
266
+ */
267
+ readonly maxConcurrentChildren?: number;
268
+ }
269
+
270
+ /**
271
+ * Discriminated union of structured agent decisions parsed from model output.
272
+ *
273
+ * - `participate`: paper-style turn contribution; carries the four labeled
274
+ * fields (`selectedRole`, `participation`, `rationale`, `contribution`).
275
+ * - `delegate`: coordinator-only delegation to a child sub-run. The runtime
276
+ * dispatches a sub-mission when this branch is returned.
277
+ *
278
+ * Consumers MUST narrow on `decision.type === "participate"` before reading
279
+ * paper-style fields.
280
+ */
281
+ export type AgentDecision = ParticipateAgentDecision | DelegateAgentDecision;
282
+
283
+ /**
284
+ * Agent participation state for a paper-style turn decision.
285
+ */
286
+ export type AgentParticipation = "contribute" | "abstain";
287
+
288
+ /**
289
+ * Event emitted after one agent contributes a model turn.
290
+ *
291
+ * @remarks
292
+ * `agent-turn` is the primary streaming payload for sequential, coordinator,
293
+ * shared-state, and broadcast executions. It captures the exact prompt/input
294
+ * Dogpile supplied to the agent, the text returned by the model provider, and
295
+ * the cumulative cost after applying that response.
296
+ *
297
+ * The corresponding durable transcript record contains the same
298
+ * `agentId`/`role`/`input`/`output` contribution without event timing or cost
299
+ * fields. Use this event for live progress UIs and the transcript for replay
300
+ * or downstream application logic.
301
+ *
302
+ * Payload shape:
303
+ *
304
+ * - `type`: always `agent-turn`.
305
+ * - `runId`: stable id shared by every event and trace object for the run.
306
+ * - `at`: ISO-8601 timestamp for when the turn completed.
307
+ * - `agentId` and `role`: identify the contributing agent.
308
+ * - `input`: prompt text visible to that agent for this turn.
309
+ * - `output`: generated model text produced by the agent.
310
+ * - `cost`: cumulative token and spend accounting after this turn.
311
+ */
312
+ export interface TurnEvent {
313
+ /** Discriminant for event rendering and exhaustive switches. */
314
+ readonly type: "agent-turn";
315
+ /** Stable run id shared by all events in one workflow. */
316
+ readonly runId: string;
317
+ /** Root-first ancestry chain when bubbled through a parent stream. */
318
+ readonly parentRunIds?: readonly string[];
319
+ /** ISO-8601 event timestamp. */
320
+ readonly at: string;
321
+ /** Agent that produced this turn. */
322
+ readonly agentId: string;
323
+ /** Agent role for this turn. */
324
+ readonly role: string;
325
+ /** Prompt/input visible to the agent for this turn. */
326
+ readonly input: string;
327
+ /** Model output produced by the agent. */
328
+ readonly output: string;
329
+ /** Optional structured role/participation decision parsed from model output. */
330
+ readonly decision?: AgentDecision | readonly DelegateAgentDecision[];
331
+ /** Cumulative cost after this turn. */
332
+ readonly cost: CostSummary;
333
+ }
334
+
335
+ /**
336
+ * One independent contribution captured by a broadcast round event.
337
+ *
338
+ * @remarks
339
+ * Broadcast protocols collect one contribution per participating agent before
340
+ * synthesis. The contribution payload is intentionally smaller than
341
+ * {@link TurnEvent}: it is a round-level summary of model outputs, while the
342
+ * complete prompt/output pair for each agent is still available as individual
343
+ * `agent-turn` events and {@link TranscriptEntry} records.
344
+ *
345
+ * Payload shape:
346
+ *
347
+ * - `agentId`: stable id of the contributing agent.
348
+ * - `role`: model-visible role or perspective used for that contribution.
349
+ * - `output`: generated text contributed independently for the round.
350
+ */
351
+ export interface BroadcastContribution {
352
+ /** Agent that produced the broadcast contribution. */
353
+ readonly agentId: string;
354
+ /** Agent role for the contribution. */
355
+ readonly role: string;
356
+ /** Independent model output produced for the shared mission. */
357
+ readonly output: string;
358
+ /** Optional structured role/participation decision parsed from model output. */
359
+ readonly decision?: AgentDecision | readonly DelegateAgentDecision[];
360
+ }
361
+
362
+ /**
363
+ * Event emitted after agents broadcast independent contributions for a round.
364
+ *
365
+ * @remarks
366
+ * A `broadcast` event marks the coordination moment where independently
367
+ * generated agent outputs are gathered for a shared round. It does not replace
368
+ * per-agent `agent-turn` events; instead, it groups their outputs by round so
369
+ * observers can render the broadcast barrier and replay the paper protocol's
370
+ * independent-contribution step.
371
+ *
372
+ * Payload shape:
373
+ *
374
+ * - `type`: always `broadcast`.
375
+ * - `runId`: stable id shared by every event and trace object for the run.
376
+ * - `at`: ISO-8601 timestamp for when the round finished.
377
+ * - `round`: one-based broadcast round number.
378
+ * - `contributions`: independent outputs collected for this round.
379
+ * - `cost`: cumulative token and spend accounting after the round.
380
+ */
381
+ export interface BroadcastEvent {
382
+ /** Discriminant for event rendering and exhaustive switches. */
383
+ readonly type: "broadcast";
384
+ /** Stable run id shared by all events in one workflow. */
385
+ readonly runId: string;
386
+ /** Root-first ancestry chain when bubbled through a parent stream. */
387
+ readonly parentRunIds?: readonly string[];
388
+ /** ISO-8601 event timestamp. */
389
+ readonly at: string;
390
+ /** One-based broadcast round number. */
391
+ readonly round: number;
392
+ /** Independent contributions collected in this broadcast round. */
393
+ readonly contributions: readonly BroadcastContribution[];
394
+ /** Cumulative cost after this broadcast round. */
395
+ readonly cost: CostSummary;
396
+ }
397
+
398
+ /**
399
+ * Event emitted when a workflow halts because a configured budget cap fired.
400
+ *
401
+ * @remarks
402
+ * `budget-stop` records the normalized cap class that stopped execution before
403
+ * the final event closes the run. The detail object is JSON-serializable so
404
+ * callers can persist or replay the exact cap, observed value, and limit.
405
+ */
406
+ export interface BudgetStopEvent {
407
+ /** Discriminant for event rendering and exhaustive switches. */
408
+ readonly type: "budget-stop";
409
+ /** Stable run id shared by all events in one workflow. */
410
+ readonly runId: string;
411
+ /** Root-first ancestry chain when bubbled through a parent stream. */
412
+ readonly parentRunIds?: readonly string[];
413
+ /** ISO-8601 event timestamp. */
414
+ readonly at: string;
415
+ /** Normalized machine-readable budget stop reason. */
416
+ readonly reason: BudgetStopReason;
417
+ /** Total cost at the stop point. */
418
+ readonly cost: CostSummary;
419
+ /** Completed model-turn iterations at the stop point. */
420
+ readonly iteration: number;
421
+ /** Elapsed runtime in milliseconds at the stop point. */
422
+ readonly elapsedMs: number;
423
+ /** Serializable cap diagnostics. */
424
+ readonly detail: JsonObject;
425
+ }
426
+
427
+ /**
428
+ * Link from a terminal event to the completed trace transcript.
429
+ *
430
+ * @remarks
431
+ * Final events are emitted before callers await {@link StreamHandle.result},
432
+ * so this compact link tells streaming UIs exactly which transcript artifact
433
+ * the terminal output closes over without duplicating every transcript entry
434
+ * inside the event log.
435
+ */
436
+ export interface TranscriptLink {
437
+ /** Discriminant for future transcript link variants. */
438
+ readonly kind: "trace-transcript";
439
+ /** Number of transcript entries included in the completed trace. */
440
+ readonly entryCount: number;
441
+ /** Zero-based index of the last transcript entry, or `null` for empty runs. */
442
+ readonly lastEntryIndex: number | null;
443
+ }
444
+
445
+ /**
446
+ * Event emitted when a workflow produces its final output.
447
+ *
448
+ * @remarks
449
+ * `final` is the terminal streaming event for a successful run. Its `output`
450
+ * value matches {@link RunResult.output}, and its `cost` value matches the
451
+ * final aggregate cost returned on the result. Its `transcript` link points to
452
+ * the completed {@link Trace.transcript} entries that produced the terminal
453
+ * output.
454
+ *
455
+ * Payload shape:
456
+ *
457
+ * - `type`: always `final`.
458
+ * - `runId`: stable id shared by every event and trace object for the run.
459
+ * - `at`: ISO-8601 timestamp for when final synthesis completed.
460
+ * - `output`: final synthesized answer returned to the caller.
461
+ * - `cost`: total token and spend accounting for the run.
462
+ * - `transcript`: compact link to the completed trace transcript.
463
+ */
464
+ export interface FinalEvent {
465
+ /** Discriminant for event rendering and exhaustive switches. */
466
+ readonly type: "final";
467
+ /** Stable run id shared by all events in one workflow. */
468
+ readonly runId: string;
469
+ /** ISO-8601 event timestamp. */
470
+ readonly at: string;
471
+ /** Final synthesized answer returned as `RunResult.output`. */
472
+ readonly output: string;
473
+ /** Total cost at completion. */
474
+ readonly cost: CostSummary;
475
+ /** Link to the completed trace transcript. */
476
+ readonly transcript: TranscriptLink;
477
+ /** Optional normalized quality score supplied by a caller-owned evaluator. */
478
+ readonly quality?: NormalizedQualityScore;
479
+ /** Optional serializable evaluation payload supplied by a caller-owned evaluator. */
480
+ readonly evaluation?: RunEvaluation;
481
+ /** Termination condition that stopped the run, when the run ended by policy. */
482
+ readonly termination?: TerminationStopRecord;
483
+ }
484
+
485
+ /**
486
+ * Event emitted when the coordinator dispatches a delegated sub-run.
487
+ *
488
+ * @remarks
489
+ * Recorded immediately before the child run starts executing. Carries the
490
+ * child's run id, the parent decision id that triggered the dispatch, and the
491
+ * resolved protocol/intent/depth. The `recursive` flag marks the diagnostic
492
+ * case where a coordinator delegates to another coordinator (D-16).
493
+ *
494
+ * The event's `runId` is the PARENT run id, matching the existing trace
495
+ * convention; `parentRunId` duplicates it for explicit cross-reference.
496
+ */
497
+ export interface SubRunStartedEvent {
498
+ /** Discriminant for event rendering and exhaustive switches. */
499
+ readonly type: "sub-run-started";
500
+ /** Parent run id; matches the surrounding trace runId. */
501
+ readonly runId: string;
502
+ /** Root-first ancestry chain when bubbled through a parent stream. */
503
+ readonly parentRunIds?: readonly string[];
504
+ /** ISO-8601 event timestamp. */
505
+ readonly at: string;
506
+ /** Child run id assigned to the dispatched sub-run. */
507
+ readonly childRunId: string;
508
+ /** Parent run id (duplicates `runId` for explicit cross-reference). */
509
+ readonly parentRunId: string;
510
+ /** Replay decision id of the parent decision that triggered this sub-run. */
511
+ readonly parentDecisionId: string;
512
+ /**
513
+ * 0-indexed position of this delegate within the fan-out array of its
514
+ * originating coordinator plan-turn (Phase 3 D-10). Single-delegate turns
515
+ * use `0` for backward compatibility. Together with `parentDecisionId`, this
516
+ * uniquely identifies the delegate within a fan-out.
517
+ */
518
+ readonly parentDecisionArrayIndex: number;
519
+ /** Coordination protocol the child run will execute. */
520
+ readonly protocol: ProtocolName;
521
+ /** Mission intent passed to the child run. */
522
+ readonly intent: string;
523
+ /** Recursion depth of the child run (1 for first-level sub-run). */
524
+ readonly depth: number;
525
+ /**
526
+ * Diagnostic flag set when a coordinator delegates to another coordinator
527
+ * (parent protocol === "coordinator" and child protocol === "coordinator").
528
+ */
529
+ readonly recursive?: boolean;
530
+ }
531
+
532
+ /**
533
+ * Event emitted when a delegated sub-run completes successfully.
534
+ *
535
+ * @remarks
536
+ * Carries the full {@link RunResult} as `subResult`, including the embedded
537
+ * child {@link Trace}. Replay walks the parent event sequence and recurses on
538
+ * `subResult.trace` to rehydrate sub-run accounting without re-invoking the
539
+ * provider (D-08).
540
+ */
541
+ export interface SubRunCompletedEvent {
542
+ /** Discriminant for event rendering and exhaustive switches. */
543
+ readonly type: "sub-run-completed";
544
+ /** Parent run id; matches the surrounding trace runId. */
545
+ readonly runId: string;
546
+ /** Root-first ancestry chain when bubbled through a parent stream. */
547
+ readonly parentRunIds?: readonly string[];
548
+ /** ISO-8601 event timestamp. */
549
+ readonly at: string;
550
+ /** Child run id that produced this result. */
551
+ readonly childRunId: string;
552
+ /** Parent run id (duplicates `runId` for explicit cross-reference). */
553
+ readonly parentRunId: string;
554
+ /** Replay decision id of the parent decision that triggered the sub-run. */
555
+ readonly parentDecisionId: string;
556
+ /**
557
+ * 0-indexed position of this delegate within the fan-out array of its
558
+ * originating coordinator plan-turn (Phase 3 D-10). Single-delegate turns
559
+ * use `0` for backward compatibility. Together with `parentDecisionId`, this
560
+ * uniquely identifies the delegate within a fan-out.
561
+ */
562
+ readonly parentDecisionArrayIndex: number;
563
+ /** Full child {@link RunResult}, including the embedded child {@link Trace}. */
564
+ readonly subResult: RunResult;
565
+ }
566
+
567
+ /**
568
+ * Event emitted when a delegated sub-run fails before completion.
569
+ *
570
+ * @remarks
571
+ * Captures a structured `error` plus the partial {@link Trace} accumulated
572
+ * before failure. The same `Trace` shape used by completed runs is preserved
573
+ * — consumers can replay or inspect the partial child events without bespoke
574
+ * deserialization logic.
575
+ */
576
+ export interface SubRunFailedEvent {
577
+ /** Discriminant for event rendering and exhaustive switches. */
578
+ readonly type: "sub-run-failed";
579
+ /** Parent run id; matches the surrounding trace runId. */
580
+ readonly runId: string;
581
+ /** Root-first ancestry chain when bubbled through a parent stream. */
582
+ readonly parentRunIds?: readonly string[];
583
+ /** ISO-8601 event timestamp. */
584
+ readonly at: string;
585
+ /** Child run id that failed. */
586
+ readonly childRunId: string;
587
+ /** Parent run id (duplicates `runId` for explicit cross-reference). */
588
+ readonly parentRunId: string;
589
+ /** Replay decision id of the parent decision that triggered the sub-run. */
590
+ readonly parentDecisionId: string;
591
+ /**
592
+ * 0-indexed position of this delegate within the fan-out array of its
593
+ * originating coordinator plan-turn (Phase 3 D-10). Single-delegate turns
594
+ * use `0` for backward compatibility. Together with `parentDecisionId`, this
595
+ * uniquely identifies the delegate within a fan-out.
596
+ */
597
+ readonly parentDecisionArrayIndex: number;
598
+ /** Structured failure description. */
599
+ readonly error: {
600
+ /** Stable error code (matches DogpileError code shape). */
601
+ readonly code: string;
602
+ /** Human-readable failure description. */
603
+ readonly message: string;
604
+ /** Provider id when the failure originated in a model call. */
605
+ readonly providerId?: string;
606
+ /** Optional structured detail (e.g., the failed delegate decision payload). */
607
+ readonly detail?: JsonObject;
608
+ };
609
+ /** Partial child {@link Trace} accumulated up to the failure point. */
610
+ readonly partialTrace: Trace;
611
+ /**
612
+ * Cost from provider calls completed before the child threw (BUDGET-03 / D-02).
613
+ *
614
+ * Equals `lastCostBearingEventCost(partialTrace.events) ?? emptyCost()`. The
615
+ * parent rolls this into its own `accounting.cost` so failed children
616
+ * contribute their real wallet spend.
617
+ */
618
+ readonly partialCost: CostSummary;
619
+ }
620
+
621
+ /**
622
+ * Event emitted when the parent's `signal` aborts AFTER a sub-run has already
623
+ * completed successfully but BEFORE the parent advances to its next coordinator
624
+ * turn (BUDGET-01 / D-10).
625
+ *
626
+ * @remarks
627
+ * Provides replay/streaming provenance for "parent gave up after a successful
628
+ * child finished." The marker is observable on `Dogpile.stream()` subscribers
629
+ * before the run errors with `code: "aborted"`. Non-streaming `run()` rejects
630
+ * with the abort error and does NOT expose the marker — `engine.ts` does not
631
+ * attach the parent events array to the rejected error (verified at
632
+ * `engine.ts:230-239`). Streaming-subscriber observability is the contract.
633
+ */
634
+ export interface SubRunParentAbortedEvent {
635
+ /** Discriminant for event rendering and exhaustive switches. */
636
+ readonly type: "sub-run-parent-aborted";
637
+ /** Parent run id; matches the surrounding trace runId. */
638
+ readonly runId: string;
639
+ /** Root-first ancestry chain when bubbled through a parent stream. */
640
+ readonly parentRunIds?: readonly string[];
641
+ /** ISO-8601 event timestamp. */
642
+ readonly at: string;
643
+ /** Most-recent completed child run id whose completion preceded the abort. */
644
+ readonly childRunId: string;
645
+ /** Parent run id (duplicates `runId` for explicit cross-reference). */
646
+ readonly parentRunId: string;
647
+ /** Discriminator (currently always "parent-aborted"; reserved for future variants). */
648
+ readonly reason: "parent-aborted";
649
+ }
650
+
651
+ /**
652
+ * Event emitted when a delegated sub-run's requested `budget.timeoutMs`
653
+ * exceeds the parent's remaining deadline and is therefore clamped to the
654
+ * parent's remaining time (BUDGET-02 / D-12).
655
+ *
656
+ * @remarks
657
+ * Emitted on the parent trace BEFORE `sub-run-started`. When the requested
658
+ * decision-level timeout fits within the parent's remaining deadline, the
659
+ * event is NOT emitted (zero-overhead happy path). The parent's deadline is
660
+ * a hard ceiling for the whole tree, so any decision-level override that
661
+ * exceeds it is silently clamped rather than throwing — recording the
662
+ * requested-vs-clamped pair on the trace preserves provenance for replay.
663
+ */
664
+ export interface SubRunBudgetClampedEvent {
665
+ /** Discriminant for event rendering and exhaustive switches. */
666
+ readonly type: "sub-run-budget-clamped";
667
+ /** Parent run id; matches the surrounding trace runId. */
668
+ readonly runId: string;
669
+ /** Root-first ancestry chain when bubbled through a parent stream. */
670
+ readonly parentRunIds?: readonly string[];
671
+ /** ISO-8601 event timestamp. */
672
+ readonly at: string;
673
+ /** Child run id whose budget was clamped. */
674
+ readonly childRunId: string;
675
+ /** Parent run id (duplicates `runId` for explicit cross-reference). */
676
+ readonly parentRunId: string;
677
+ /** Replay decision id of the parent decision that triggered the sub-run. */
678
+ readonly parentDecisionId: string;
679
+ /** The decision's originally requested `budget.timeoutMs` value (milliseconds). */
680
+ readonly requestedTimeoutMs: number;
681
+ /** The clamped child timeout actually applied (parent's remaining deadline, in milliseconds). */
682
+ readonly clampedTimeoutMs: number;
683
+ /** Discriminator for the clamp cause (currently always "exceeded-parent-remaining"). */
684
+ readonly reason: "exceeded-parent-remaining";
685
+ }
686
+
687
+ /**
688
+ * Event emitted when a delegated sub-run is enqueued because the
689
+ * coordinator's effective `maxConcurrentChildren` budget is fully in flight
690
+ * (Phase 3 D-07). Emitted ONLY when the slot is not immediately free —
691
+ * no-pressure runs do NOT emit this event.
692
+ *
693
+ * Three-event timeline under pressure: sub-run-queued → sub-run-started →
694
+ * sub-run-completed (or sub-run-failed). Without pressure: sub-run-started
695
+ * → completion (no queued event).
696
+ */
697
+ export interface SubRunQueuedEvent {
698
+ readonly type: "sub-run-queued";
699
+ readonly runId: string;
700
+ readonly parentRunIds?: readonly string[];
701
+ readonly at: string;
702
+ readonly childRunId: string;
703
+ readonly parentRunId: string;
704
+ readonly parentDecisionId: string;
705
+ readonly parentDecisionArrayIndex: number;
706
+ readonly protocol: ProtocolName;
707
+ readonly intent: string;
708
+ readonly depth: number;
709
+ readonly queuePosition: number;
710
+ }
711
+
712
+ /**
713
+ * Event emitted ONCE per run when the runtime detects a `"local"` provider
714
+ * in the coordinator's active tree and clamps `maxConcurrentChildren` to 1
715
+ * (Phase 3 CONCURRENCY-02 / D-12). Emitted at the FIRST delegate dispatch
716
+ * where the local-provider check trips. Subsequent dispatches in the same
717
+ * run do NOT re-emit. Runs with no delegates, or runs with delegates but
718
+ * no local provider, never emit this event.
719
+ *
720
+ * The clamp is silent (no throw, no console output) per D-13 — this event
721
+ * IS the warning surface; subscribers can react via the engine's `emit`
722
+ * callback.
723
+ */
724
+ export interface SubRunConcurrencyClampedEvent {
725
+ readonly type: "sub-run-concurrency-clamped";
726
+ readonly runId: string;
727
+ readonly parentRunIds?: readonly string[];
728
+ readonly at: string;
729
+ /** The pre-clamp effective max that would have applied (engine/run/decision min). */
730
+ readonly requestedMax: number;
731
+ /** Always 1 — locality-clamp is a fixed cap. */
732
+ readonly effectiveMax: 1;
733
+ readonly reason: "local-provider-detected";
734
+ /** Stable id of the FIRST local provider found during the active-tree walk. */
735
+ readonly providerId: string;
736
+ }
737
+
738
+ /**
739
+ * Successful coordination event emitted by Dogpile and persisted in traces.
740
+ *
741
+ * @remarks
742
+ * `RunEvent` is the discriminated union stored in {@link Trace.events} and
743
+ * used by low-level protocol emit callbacks. Switch on `type` to handle each
744
+ * coordination moment exhaustively:
745
+ *
746
+ * - `role-assignment`: participant/role roster was established.
747
+ * - `model-request`: one provider-neutral model request was started.
748
+ * - `model-response`: one provider-neutral model response completed.
749
+ * - `model-output-chunk`: one streaming model text delta arrived.
750
+ * - `tool-call`: one runtime tool invocation was started.
751
+ * - `tool-result`: one runtime tool invocation completed.
752
+ * - `agent-turn`: one agent completed a prompt/response turn.
753
+ * - `broadcast`: a broadcast round gathered independent contributions.
754
+ * - `sub-run-started`: a delegated sub-run was dispatched.
755
+ * - `sub-run-completed`: a delegated sub-run completed and embedded its full result.
756
+ * - `sub-run-failed`: a delegated sub-run failed before completion.
757
+ * - `sub-run-queued`: a delegated sub-run waited for a concurrency slot.
758
+ * - `sub-run-concurrency-clamped`: a local provider forced child concurrency to 1.
759
+ * - `budget-stop`: a configured budget cap halted further model turns.
760
+ * - `final`: the run completed and produced the final output.
761
+ *
762
+ * Every variant is JSON-serializable and includes `runId` plus an ISO-8601
763
+ * `at` timestamp so callers can persist, render, or replay the event log
764
+ * without SDK-owned storage.
765
+ *
766
+ * @example
767
+ * ```ts
768
+ * for await (const event of Dogpile.stream(options)) {
769
+ * switch (event.type) {
770
+ * case "agent-turn":
771
+ * console.log(event.agentId, event.output);
772
+ * break;
773
+ * case "final":
774
+ * console.log(event.output);
775
+ * break;
776
+ * }
777
+ * }
778
+ * ```
779
+ */
780
+ export type RunEvent =
781
+ | RoleAssignmentEvent
782
+ | ModelRequestEvent
783
+ | ModelResponseEvent
784
+ | ModelOutputChunkEvent
785
+ | ToolCallEvent
786
+ | ToolResultEvent
787
+ | TurnEvent
788
+ | BroadcastEvent
789
+ | SubRunStartedEvent
790
+ | SubRunCompletedEvent
791
+ | SubRunFailedEvent
792
+ | SubRunParentAbortedEvent
793
+ | SubRunBudgetClampedEvent
794
+ | SubRunQueuedEvent
795
+ | SubRunConcurrencyClampedEvent
796
+ | BudgetStopEvent
797
+ | FinalEvent;
798
+
799
+ /**
800
+ * Model activity events yielded by `stream()` and persisted in traces when a
801
+ * protocol exposes provider-call boundaries.
802
+ */
803
+ export type ModelActivityEvent = ModelRequestEvent | ModelResponseEvent | ModelOutputChunkEvent;
804
+
805
+ /**
806
+ * Tool activity events yielded by `stream()` and persisted in traces when a
807
+ * protocol or caller-owned adapter invokes runtime tools.
808
+ */
809
+ export type ToolActivityEvent = ToolCallEvent | ToolResultEvent;
810
+
811
+ /**
812
+ * Lifecycle event yielded by `stream()`.
813
+ *
814
+ * These events describe workflow coordination state rather than model text.
815
+ * Role assignment establishes the participant roster, `budget-stop` records a
816
+ * lifecycle halt before the terminal completion event, and the `sub-run-*`
817
+ * variants surface delegated child-run dispatch boundaries.
818
+ */
819
+ export type StreamLifecycleEvent =
820
+ | RoleAssignmentEvent
821
+ | BudgetStopEvent
822
+ | SubRunStartedEvent
823
+ | SubRunCompletedEvent
824
+ | SubRunFailedEvent
825
+ | SubRunParentAbortedEvent
826
+ | SubRunBudgetClampedEvent
827
+ | SubRunQueuedEvent
828
+ | SubRunConcurrencyClampedEvent
829
+ | AbortedEvent;
830
+
831
+ /**
832
+ * Lifecycle event yielded by `stream()` when a run is aborted.
833
+ */
834
+ export interface AbortedEvent {
835
+ readonly type: "aborted";
836
+ readonly runId: string;
837
+ readonly at: string;
838
+ readonly reason: "parent-aborted" | "timeout";
839
+ readonly detail?: JsonObject;
840
+ readonly parentRunIds?: readonly string[];
841
+ }
842
+
843
+ /**
844
+ * Output event yielded by `stream()`.
845
+ *
846
+ * These events carry generated agent output or grouped round output while a
847
+ * workflow is still running.
848
+ */
849
+ export type StreamOutputEvent = ModelActivityEvent | ToolActivityEvent | TurnEvent | BroadcastEvent;
850
+
851
+ /**
852
+ * Error event yielded by `stream()` when execution rejects.
853
+ *
854
+ * @remarks
855
+ * Stream errors are emitted before {@link StreamHandle.result} rejects so UIs
856
+ * and log collectors can record a terminal failure without wrapping the result
857
+ * promise. The error payload is JSON-serializable and intentionally omits
858
+ * runtime-specific values such as `Error.stack`.
859
+ */
860
+ export interface StreamErrorEvent {
861
+ /** Discriminant for stream event handling. */
862
+ readonly type: "error";
863
+ /** Stable run id when known; empty when failure happened before protocol startup. */
864
+ readonly runId: string;
865
+ /** ISO-8601 event timestamp. */
866
+ readonly at: string;
867
+ /** Error name when available. */
868
+ readonly name: string;
869
+ /** Human-readable error message. */
870
+ readonly message: string;
871
+ /** Optional serializable diagnostics supplied by the SDK. */
872
+ readonly detail?: JsonObject;
873
+ }
874
+
875
+ /**
876
+ * Completion event yielded by `stream()` after successful execution.
877
+ */
878
+ export type StreamCompletionEvent = FinalEvent;
879
+
880
+ /**
881
+ * Public streaming event union returned by `stream()`.
882
+ *
883
+ * @remarks
884
+ * The union is grouped into lifecycle, output, error, and completion families:
885
+ *
886
+ * - lifecycle: {@link StreamLifecycleEvent}
887
+ * - output: {@link StreamOutputEvent}
888
+ * - error: {@link StreamErrorEvent}
889
+ * - completion: {@link StreamCompletionEvent}
890
+ *
891
+ * Successful stream events are also persisted as {@link RunEvent} values in the
892
+ * completed trace. `error` is stream-only because a failed run has no completed
893
+ * {@link RunResult} trace to return.
894
+ */
895
+ export type StreamEvent = StreamLifecycleEvent | StreamOutputEvent | StreamErrorEvent | StreamCompletionEvent;