@dogpile/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/LICENSE +16 -0
  3. package/README.md +842 -0
  4. package/dist/browser/index.d.ts +8 -0
  5. package/dist/browser/index.d.ts.map +1 -0
  6. package/dist/browser/index.js +4493 -0
  7. package/dist/browser/index.js.map +1 -0
  8. package/dist/index.d.ts +17 -0
  9. package/dist/index.d.ts.map +1 -0
  10. package/dist/index.js +14 -0
  11. package/dist/index.js.map +1 -0
  12. package/dist/providers/openai-compatible.d.ts +44 -0
  13. package/dist/providers/openai-compatible.d.ts.map +1 -0
  14. package/dist/providers/openai-compatible.js +305 -0
  15. package/dist/providers/openai-compatible.js.map +1 -0
  16. package/dist/runtime/broadcast.d.ts +18 -0
  17. package/dist/runtime/broadcast.d.ts.map +1 -0
  18. package/dist/runtime/broadcast.js +335 -0
  19. package/dist/runtime/broadcast.js.map +1 -0
  20. package/dist/runtime/cancellation.d.ts +6 -0
  21. package/dist/runtime/cancellation.d.ts.map +1 -0
  22. package/dist/runtime/cancellation.js +35 -0
  23. package/dist/runtime/cancellation.js.map +1 -0
  24. package/dist/runtime/coordinator.d.ts +18 -0
  25. package/dist/runtime/coordinator.d.ts.map +1 -0
  26. package/dist/runtime/coordinator.js +434 -0
  27. package/dist/runtime/coordinator.js.map +1 -0
  28. package/dist/runtime/decisions.d.ts +5 -0
  29. package/dist/runtime/decisions.d.ts.map +1 -0
  30. package/dist/runtime/decisions.js +31 -0
  31. package/dist/runtime/decisions.js.map +1 -0
  32. package/dist/runtime/defaults.d.ts +63 -0
  33. package/dist/runtime/defaults.d.ts.map +1 -0
  34. package/dist/runtime/defaults.js +426 -0
  35. package/dist/runtime/defaults.js.map +1 -0
  36. package/dist/runtime/engine.d.ts +79 -0
  37. package/dist/runtime/engine.d.ts.map +1 -0
  38. package/dist/runtime/engine.js +723 -0
  39. package/dist/runtime/engine.js.map +1 -0
  40. package/dist/runtime/model.d.ts +14 -0
  41. package/dist/runtime/model.d.ts.map +1 -0
  42. package/dist/runtime/model.js +82 -0
  43. package/dist/runtime/model.js.map +1 -0
  44. package/dist/runtime/sequential.d.ts +18 -0
  45. package/dist/runtime/sequential.d.ts.map +1 -0
  46. package/dist/runtime/sequential.js +277 -0
  47. package/dist/runtime/sequential.js.map +1 -0
  48. package/dist/runtime/shared.d.ts +18 -0
  49. package/dist/runtime/shared.d.ts.map +1 -0
  50. package/dist/runtime/shared.js +288 -0
  51. package/dist/runtime/shared.js.map +1 -0
  52. package/dist/runtime/termination.d.ts +77 -0
  53. package/dist/runtime/termination.d.ts.map +1 -0
  54. package/dist/runtime/termination.js +355 -0
  55. package/dist/runtime/termination.js.map +1 -0
  56. package/dist/runtime/tools.d.ts +314 -0
  57. package/dist/runtime/tools.d.ts.map +1 -0
  58. package/dist/runtime/tools.js +969 -0
  59. package/dist/runtime/tools.js.map +1 -0
  60. package/dist/runtime/validation.d.ts +23 -0
  61. package/dist/runtime/validation.d.ts.map +1 -0
  62. package/dist/runtime/validation.js +656 -0
  63. package/dist/runtime/validation.js.map +1 -0
  64. package/dist/types.d.ts +2434 -0
  65. package/dist/types.d.ts.map +1 -0
  66. package/dist/types.js +81 -0
  67. package/dist/types.js.map +1 -0
  68. package/package.json +157 -0
  69. package/src/browser/index.ts +7 -0
  70. package/src/index.ts +195 -0
  71. package/src/providers/openai-compatible.ts +406 -0
  72. package/src/runtime/broadcast.test.ts +355 -0
  73. package/src/runtime/broadcast.ts +428 -0
  74. package/src/runtime/cancellation.ts +40 -0
  75. package/src/runtime/coordinator.test.ts +468 -0
  76. package/src/runtime/coordinator.ts +581 -0
  77. package/src/runtime/decisions.ts +38 -0
  78. package/src/runtime/defaults.ts +547 -0
  79. package/src/runtime/engine.ts +880 -0
  80. package/src/runtime/model.ts +117 -0
  81. package/src/runtime/sequential.test.ts +262 -0
  82. package/src/runtime/sequential.ts +357 -0
  83. package/src/runtime/shared.test.ts +265 -0
  84. package/src/runtime/shared.ts +367 -0
  85. package/src/runtime/termination.ts +463 -0
  86. package/src/runtime/tools.ts +1518 -0
  87. package/src/runtime/validation.ts +771 -0
  88. package/src/types.ts +2729 -0
@@ -0,0 +1,2434 @@
1
+ /**
2
+ * Primitive JSON value accepted in serializable trace metadata.
3
+ */
4
+ export type JsonPrimitive = string | number | boolean | null;
5
+ /**
6
+ * JSON-compatible value used for trace metadata, model request metadata, and
7
+ * caller-managed replay artifacts.
8
+ *
9
+ * Dogpile core is stateless, so everything needed to inspect or persist a run
10
+ * is represented with serializable data instead of SDK-owned storage.
11
+ */
12
+ export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
13
+ /**
14
+ * JSON-compatible object with immutable properties.
15
+ */
16
+ export interface JsonObject {
17
+ readonly [key: string]: JsonValue;
18
+ }
19
+ declare const dogpileErrorCodes: readonly ["invalid-configuration", "aborted", "timeout", "provider-authentication", "provider-invalid-request", "provider-invalid-response", "provider-not-found", "provider-rate-limited", "provider-timeout", "provider-unavailable", "provider-unsupported", "provider-error", "unknown"];
20
+ /**
21
+ * Stable machine-readable error codes thrown by Dogpile public adapters.
22
+ *
23
+ * @remarks
24
+ * The string values are part of the v1 API contract so JavaScript callers can
25
+ * branch on provider failures without depending on provider SDK classes.
26
+ */
27
+ export type DogpileErrorCode = (typeof dogpileErrorCodes)[number];
28
+ /**
29
+ * Options used to construct a stable Dogpile public error.
30
+ */
31
+ export interface DogpileErrorOptions<Code extends DogpileErrorCode = DogpileErrorCode> {
32
+ /** Stable machine-readable error code. */
33
+ readonly code: Code;
34
+ /** Human-readable error message. */
35
+ readonly message: string;
36
+ /** Original thrown value, kept off JSON serialization by default. */
37
+ readonly cause?: unknown;
38
+ /** Whether caller retry policy may safely retry the same operation. */
39
+ readonly retryable?: boolean;
40
+ /** Configured provider id associated with the failure, when available. */
41
+ readonly providerId?: string;
42
+ /** Optional serializable diagnostic detail. */
43
+ readonly detail?: JsonObject;
44
+ }
45
+ interface DogpileErrorBase<Code extends DogpileErrorCode> extends Error {
46
+ /** Public error class name. */
47
+ readonly name: "DogpileError";
48
+ /** Stable machine-readable error code. */
49
+ readonly code: Code;
50
+ /** Whether caller retry policy may safely retry the same operation. */
51
+ readonly retryable?: boolean;
52
+ /** Configured provider id associated with the failure, when available. */
53
+ readonly providerId?: string;
54
+ /** Optional serializable diagnostic detail. */
55
+ readonly detail?: JsonObject;
56
+ /** Original thrown value, if Dogpile wrapped a lower-level failure. */
57
+ readonly cause?: unknown;
58
+ /** JSON-safe representation for logs, traces, and observability tools. */
59
+ toJSON(): JsonObject;
60
+ }
61
+ export type DogpileInvalidConfigurationError = DogpileErrorBase<"invalid-configuration">;
62
+ export type DogpileAbortedError = DogpileErrorBase<"aborted">;
63
+ export type DogpileTimeoutError = DogpileErrorBase<"timeout">;
64
+ export type DogpileProviderAuthenticationError = DogpileErrorBase<"provider-authentication">;
65
+ export type DogpileProviderInvalidRequestError = DogpileErrorBase<"provider-invalid-request">;
66
+ export type DogpileProviderInvalidResponseError = DogpileErrorBase<"provider-invalid-response">;
67
+ export type DogpileProviderNotFoundError = DogpileErrorBase<"provider-not-found">;
68
+ export type DogpileProviderRateLimitedError = DogpileErrorBase<"provider-rate-limited">;
69
+ export type DogpileProviderTimeoutError = DogpileErrorBase<"provider-timeout">;
70
+ export type DogpileProviderUnavailableError = DogpileErrorBase<"provider-unavailable">;
71
+ export type DogpileProviderUnsupportedError = DogpileErrorBase<"provider-unsupported">;
72
+ export type DogpileProviderError = DogpileErrorBase<"provider-error">;
73
+ export type DogpileUnknownError = DogpileErrorBase<"unknown">;
74
+ /**
75
+ * Public Dogpile error union with stable string code discriminants.
76
+ *
77
+ * @remarks
78
+ * `code` is the discriminant for exhaustive caller handling. The exported
79
+ * `DogpileError` value is still the constructor used to create these errors.
80
+ */
81
+ export type DogpileError = DogpileInvalidConfigurationError | DogpileAbortedError | DogpileTimeoutError | DogpileProviderAuthenticationError | DogpileProviderInvalidRequestError | DogpileProviderInvalidResponseError | DogpileProviderNotFoundError | DogpileProviderRateLimitedError | DogpileProviderTimeoutError | DogpileProviderUnavailableError | DogpileProviderUnsupportedError | DogpileProviderError | DogpileUnknownError;
82
+ export type DogpileErrorByCode<Code extends DogpileErrorCode> = Extract<DogpileError, {
83
+ readonly code: Code;
84
+ }>;
85
+ export interface DogpileErrorConstructor {
86
+ new <Code extends DogpileErrorCode>(options: DogpileErrorOptions<Code>): DogpileErrorByCode<Code>;
87
+ readonly prototype: DogpileError;
88
+ /**
89
+ * Cross-realm guard for Dogpile public errors.
90
+ */
91
+ isInstance(error: unknown): error is DogpileError;
92
+ }
93
+ /**
94
+ * Public Dogpile error constructor.
95
+ */
96
+ export declare const DogpileError: DogpileErrorConstructor;
97
+ /**
98
+ * Coordination protocols supported by the public SDK surface.
99
+ *
100
+ * Supported values:
101
+ *
102
+ * - `coordinator`: a coordinator assigns work and synthesizes a final answer.
103
+ * - `sequential`: agents refine the answer one after another.
104
+ * - `broadcast`: agents answer the same mission independently before merge.
105
+ * - `shared`: agents collaborate through shared state.
106
+ *
107
+ * Passing a string protocol uses the SDK defaults from {@link ProtocolConfig}:
108
+ * `maxTurns: 3` for `coordinator`, `sequential`, and `shared`, and
109
+ * `maxRounds: 2` for `broadcast`.
110
+ */
111
+ export type Protocol = "coordinator" | "sequential" | "broadcast" | "shared";
112
+ /**
113
+ * Public coordination protocol selector name.
114
+ *
115
+ * @remarks
116
+ * This alias is the caller-facing literal union shared by high-level calls,
117
+ * low-level engine configuration, traces, events, and benchmark artifacts.
118
+ * `Protocol` remains the short compatibility name for the same public union.
119
+ */
120
+ export type ProtocolName = Protocol;
121
+ /**
122
+ * Named cost and quality presets.
123
+ *
124
+ * Supported values:
125
+ *
126
+ * - `fast`: minimizes latency and spend; default temperature is `0`.
127
+ * - `balanced`: general-purpose tradeoff; default temperature is `0.2`.
128
+ * - `quality`: spends more work on answer quality; default temperature is `0.4`.
129
+ *
130
+ * High-level workflow calls default to `balanced` when callers omit a tier.
131
+ * Low-level engine configuration keeps the tier explicit for repeatable
132
+ * research runs.
133
+ */
134
+ export type BudgetTier = "fast" | "balanced" | "quality";
135
+ /**
136
+ * Short compatibility name for the public budget tier union.
137
+ */
138
+ export type Tier = BudgetTier;
139
+ /**
140
+ * Sequential protocol configuration.
141
+ *
142
+ * Agents contribute in order, with each turn seeing the prior transcript.
143
+ * Default when `protocol: "sequential"` is supplied: `{ kind: "sequential",
144
+ * maxTurns: 3 }`.
145
+ */
146
+ export interface SequentialProtocolConfig {
147
+ /** Discriminant for exhaustive protocol handling. */
148
+ readonly kind: "sequential";
149
+ /** Maximum number of agent turns to execute; defaults to `3` for named protocols. */
150
+ readonly maxTurns?: number;
151
+ }
152
+ /**
153
+ * Coordinator protocol configuration.
154
+ *
155
+ * A coordinator manages worker turns and synthesizes the final output.
156
+ * Default when `protocol: "coordinator"` is supplied: `{ kind: "coordinator",
157
+ * maxTurns: 3 }`.
158
+ */
159
+ export interface CoordinatorProtocolConfig {
160
+ /** Discriminant for exhaustive protocol handling. */
161
+ readonly kind: "coordinator";
162
+ /** Maximum number of coordinator-managed turns to execute; defaults to `3` for named protocols. */
163
+ readonly maxTurns?: number;
164
+ }
165
+ /**
166
+ * Broadcast protocol configuration.
167
+ *
168
+ * Agents independently answer the same mission before a merge/synthesis step.
169
+ * Default when `protocol: "broadcast"` is supplied: `{ kind: "broadcast",
170
+ * maxRounds: 2 }`.
171
+ */
172
+ export interface BroadcastProtocolConfig {
173
+ /** Discriminant for exhaustive protocol handling. */
174
+ readonly kind: "broadcast";
175
+ /** Maximum number of broadcast/merge rounds to execute; defaults to `2` for named protocols. */
176
+ readonly maxRounds?: number;
177
+ }
178
+ /**
179
+ * Shared-state protocol configuration.
180
+ *
181
+ * Agents coordinate by reading and updating a shared working state.
182
+ * Default when `protocol: "shared"` is supplied: `{ kind: "shared",
183
+ * maxTurns: 3 }`.
184
+ */
185
+ export interface SharedProtocolConfig {
186
+ /** Discriminant for exhaustive protocol handling. */
187
+ readonly kind: "shared";
188
+ /** Maximum number of shared-state turns to execute; defaults to `3` for named protocols. */
189
+ readonly maxTurns?: number;
190
+ /** Optional organizational memory snapshot visible to every shared agent. */
191
+ readonly organizationalMemory?: string;
192
+ }
193
+ /**
194
+ * Discriminated protocol configuration union for low-level runs.
195
+ *
196
+ * Use this union when the named {@link Protocol} defaults are too coarse. The
197
+ * `kind` property is the discriminant and supported values are `coordinator`,
198
+ * `sequential`, `broadcast`, and `shared`.
199
+ */
200
+ export type ProtocolConfig = SequentialProtocolConfig | CoordinatorProtocolConfig | BroadcastProtocolConfig | SharedProtocolConfig;
201
+ /**
202
+ * Budget policy composed from a named tier plus optional hard caps.
203
+ *
204
+ * Supported `tier` values are `fast`, `balanced`, and `quality`. The tier
205
+ * selects default execution behavior such as temperature, while `maxUsd`,
206
+ * `maxTokens`, and `qualityWeight` layer caller-owned cost policy over that
207
+ * preset.
208
+ *
209
+ * The SDK should halt before cap breach and report accumulated usage in
210
+ * {@link CostSummary}. `qualityWeight` expresses how strongly the caller values
211
+ * spending additional budget for higher answer quality.
212
+ */
213
+ export interface Budget {
214
+ /** Named preset used to choose default execution behavior; recommended default is `balanced`. */
215
+ readonly tier: BudgetTier;
216
+ /** Optional maximum spend in US dollars; omit for no SDK-enforced dollar cap. */
217
+ readonly maxUsd?: number;
218
+ /** Optional maximum total token count; omit for no SDK-enforced token cap. */
219
+ readonly maxTokens?: number;
220
+ /** Optional maximum completed model-turn iterations; omit for no SDK-enforced iteration cap. */
221
+ readonly maxIterations?: number;
222
+ /** Optional maximum elapsed runtime in milliseconds; omit for no SDK-enforced timeout cap. */
223
+ readonly timeoutMs?: number;
224
+ /** Optional quality preference in the inclusive range `0..1`; omit to use the tier default. */
225
+ readonly qualityWeight?: number;
226
+ }
227
+ /**
228
+ * Serializable termination condition for cost-controlled and quality-aware runs.
229
+ *
230
+ * @remarks
231
+ * Conditions are discriminated by `kind` so callers can compose and inspect
232
+ * stop policies without relying on functions, closures, storage, or
233
+ * runtime-specific state. Use {@link FirstOfTerminationCondition} when multiple
234
+ * conditions should race and the first terminating condition should win.
235
+ */
236
+ export type TerminationCondition = BudgetTerminationCondition | ConvergenceTerminationCondition | JudgeTerminationCondition | FirstOfTerminationCondition;
237
+ /**
238
+ * Primitive, non-composite termination conditions accepted by `firstOf`.
239
+ */
240
+ export type PrimitiveTerminationCondition = BudgetTerminationCondition | ConvergenceTerminationCondition | JudgeTerminationCondition;
241
+ /**
242
+ * Halt when observed usage reaches or would exceed a configured cap.
243
+ */
244
+ export interface BudgetTerminationCondition {
245
+ /** Discriminant for exhaustive termination handling. */
246
+ readonly kind: "budget";
247
+ /** Optional maximum spend in US dollars. */
248
+ readonly maxUsd?: number;
249
+ /** Optional maximum total token count. */
250
+ readonly maxTokens?: number;
251
+ /** Optional maximum completed model-turn iterations. */
252
+ readonly maxIterations?: number;
253
+ /** Optional maximum elapsed runtime in milliseconds. */
254
+ readonly timeoutMs?: number;
255
+ }
256
+ /**
257
+ * Normalized machine-readable reason for a budget stop.
258
+ */
259
+ export type BudgetStopReason = "cost" | "tokens" | "iterations" | "timeout";
260
+ /**
261
+ * Halt when recent outputs are stable enough to treat the run as converged.
262
+ */
263
+ export interface ConvergenceTerminationCondition {
264
+ /** Discriminant for exhaustive termination handling. */
265
+ readonly kind: "convergence";
266
+ /** Number of consecutive stable turns required before terminating. */
267
+ readonly stableTurns: number;
268
+ /** Similarity threshold in the inclusive range `0..1`. */
269
+ readonly minSimilarity: number;
270
+ }
271
+ /**
272
+ * Halt when a judge accepts, rejects, or scores the current run state.
273
+ */
274
+ export interface JudgeTerminationCondition {
275
+ /** Discriminant for exhaustive termination handling. */
276
+ readonly kind: "judge";
277
+ /** Model-visible rubric or serialized judge configuration. */
278
+ readonly rubric: string | JsonObject;
279
+ /** Optional score threshold in the inclusive range `0..1`. */
280
+ readonly minScore?: number;
281
+ }
282
+ /**
283
+ * Normalized machine-readable reason for a judge stop.
284
+ */
285
+ export type JudgeStopReason = "accepted" | "rejected" | "score-threshold";
286
+ /**
287
+ * Normalized machine-readable stop reason across all termination evaluators.
288
+ */
289
+ export type NormalizedStopReason = "budget:cost" | "budget:tokens" | "budget:iterations" | "budget:timeout" | "convergence" | "judge:accepted" | "judge:rejected" | "judge:score-threshold";
290
+ /**
291
+ * Serializable judge decision visible to judge termination evaluators.
292
+ *
293
+ * @remarks
294
+ * Judge decisions are deliberately separate from budget and convergence state:
295
+ * a caller-owned evaluator can record an explicit accept/reject verdict or a
296
+ * normalized score without coupling termination checks to cost caps or protocol
297
+ * transcript similarity.
298
+ */
299
+ export type JudgeEvaluationDecision = JudgeAcceptDecision | JudgeRejectDecision | JudgeScoreDecision;
300
+ /**
301
+ * Judge verdict that accepts the current run state.
302
+ */
303
+ export interface JudgeAcceptDecision {
304
+ /** Decision discriminant for exhaustive judge handling. */
305
+ readonly type: "accept";
306
+ /** Optional normalized quality score in the inclusive range `0..1`. */
307
+ readonly score?: NormalizedQualityScore;
308
+ /** Optional serializable rationale for trace diagnostics. */
309
+ readonly rationale?: string;
310
+ /** Optional serializable judge metadata. */
311
+ readonly metadata?: JsonObject;
312
+ }
313
+ /**
314
+ * Judge verdict that rejects the current run state.
315
+ */
316
+ export interface JudgeRejectDecision {
317
+ /** Decision discriminant for exhaustive judge handling. */
318
+ readonly type: "reject";
319
+ /** Optional normalized quality score in the inclusive range `0..1`. */
320
+ readonly score?: NormalizedQualityScore;
321
+ /** Optional serializable rationale for trace diagnostics. */
322
+ readonly rationale?: string;
323
+ /** Optional serializable judge metadata. */
324
+ readonly metadata?: JsonObject;
325
+ }
326
+ /**
327
+ * Judge score without a hard accept/reject verdict.
328
+ */
329
+ export interface JudgeScoreDecision {
330
+ /** Decision discriminant for exhaustive judge handling. */
331
+ readonly type: "score";
332
+ /** Normalized quality score in the inclusive range `0..1`. */
333
+ readonly score: NormalizedQualityScore;
334
+ /** Optional serializable rationale for trace diagnostics. */
335
+ readonly rationale?: string;
336
+ /** Optional serializable judge metadata. */
337
+ readonly metadata?: JsonObject;
338
+ }
339
+ /**
340
+ * Input tuple accepted by a `firstOf(...conditions)` helper.
341
+ */
342
+ export type FirstOfTerminationConditions = readonly [
343
+ PrimitiveTerminationCondition | FirstOfTerminationCondition,
344
+ ...(PrimitiveTerminationCondition | FirstOfTerminationCondition)[]
345
+ ];
346
+ /**
347
+ * Composite termination condition where the earliest terminating child wins.
348
+ */
349
+ export interface FirstOfTerminationCondition {
350
+ /** Discriminant for exhaustive termination handling. */
351
+ readonly kind: "firstOf";
352
+ /** Ordered child conditions evaluated by the composite. */
353
+ readonly conditions: FirstOfTerminationConditions;
354
+ }
355
+ /**
356
+ * Serializable input passed to a firstOf composition evaluator.
357
+ */
358
+ export interface FirstOfTerminationInput {
359
+ /** Composition input discriminant for logs and tests. */
360
+ readonly kind: "firstOf-input";
361
+ /** Conditions to evaluate in order. */
362
+ readonly conditions: FirstOfTerminationConditions;
363
+ /** Current run state visible to termination evaluators. */
364
+ readonly context: TerminationEvaluationContext;
365
+ }
366
+ /**
367
+ * Current run state visible to termination evaluators.
368
+ */
369
+ export interface TerminationEvaluationContext {
370
+ /** Stable id for the workflow run being evaluated. */
371
+ readonly runId: string;
372
+ /** Protocol currently executing. */
373
+ readonly protocol: Protocol;
374
+ /** Cost/quality tier selected for the run. */
375
+ readonly tier: BudgetTier;
376
+ /** Current accumulated cost and token usage. */
377
+ readonly cost: CostSummary;
378
+ /** Completed coordination events available at the evaluation point. */
379
+ readonly events: readonly RunEvent[];
380
+ /** Completed transcript entries available at the evaluation point. */
381
+ readonly transcript: readonly TranscriptEntry[];
382
+ /** Completed model-turn iterations at the evaluation point. */
383
+ readonly iteration?: number;
384
+ /** Elapsed runtime in milliseconds at the evaluation point. */
385
+ readonly elapsedMs?: number;
386
+ /** Optional normalized judge or quality score in the inclusive range `0..1`. */
387
+ readonly quality?: NormalizedQualityScore;
388
+ /** Optional caller-owned judge decision for judge termination checks. */
389
+ readonly judgeDecision?: JudgeEvaluationDecision;
390
+ /** Additional serializable evaluator metadata. */
391
+ readonly metadata?: JsonObject;
392
+ }
393
+ /**
394
+ * Decision returned by a termination condition evaluator.
395
+ */
396
+ export type TerminationDecision = ContinueTerminationDecision | StopTerminationDecision;
397
+ /**
398
+ * Continue running because a condition has not fired.
399
+ */
400
+ export interface ContinueTerminationDecision {
401
+ /** Decision discriminant for exhaustive termination handling. */
402
+ readonly type: "continue";
403
+ /** Condition that was evaluated. */
404
+ readonly condition: TerminationCondition;
405
+ }
406
+ /**
407
+ * Stop running because a condition fired.
408
+ */
409
+ export interface StopTerminationDecision {
410
+ /** Decision discriminant for exhaustive termination handling. */
411
+ readonly type: "stop";
412
+ /** Condition that fired. */
413
+ readonly condition: TerminationCondition;
414
+ /** Machine-readable stop reason. */
415
+ readonly reason: "budget" | "convergence" | "judge";
416
+ /** Normalized machine-readable stop reason across all stop classes. */
417
+ readonly normalizedReason: NormalizedStopReason;
418
+ /** Normalized budget stop reason when `reason` is `budget`. */
419
+ readonly budgetReason?: BudgetStopReason;
420
+ /** Normalized judge stop reason when `reason` is `judge`. */
421
+ readonly judgeReason?: JudgeStopReason;
422
+ /** Optional serializable detail for traces and diagnostics. */
423
+ readonly detail?: JsonObject;
424
+ }
425
+ /**
426
+ * Output returned after evaluating a `firstOf` composition.
427
+ */
428
+ export interface FirstOfTerminationOutput {
429
+ /** Composition output discriminant for logs and tests. */
430
+ readonly kind: "firstOf-output";
431
+ /** Final decision for the composite condition. */
432
+ readonly decision: TerminationDecision;
433
+ /** Zero-based index of the child condition that fired, or `null` if none fired. */
434
+ readonly winningConditionIndex: number | null;
435
+ /** Per-child decisions in evaluation order. */
436
+ readonly evaluated: readonly TerminationDecision[];
437
+ }
438
+ /**
439
+ * Serializable diagnostics for a firstOf composition that stopped a run.
440
+ */
441
+ export interface FirstOfTerminationStopRecord {
442
+ /** Composition stop discriminant for trace consumers. */
443
+ readonly kind: "firstOf-stop";
444
+ /** Zero-based index of the top-level child condition that fired. */
445
+ readonly winningConditionIndex: number;
446
+ /** Top-level child condition that fired. */
447
+ readonly winningCondition: TerminationCondition;
448
+ /** Concrete condition that produced the stop decision. */
449
+ readonly firedCondition: TerminationCondition;
450
+ /** Per-child decisions in evaluation order. */
451
+ readonly evaluated: readonly TerminationDecision[];
452
+ }
453
+ /**
454
+ * Serializable record of the termination condition that stopped a run.
455
+ */
456
+ export interface TerminationStopRecord {
457
+ /** Stop record discriminant for trace consumers. */
458
+ readonly kind: "termination-stop";
459
+ /** Condition supplied to the protocol runner. */
460
+ readonly rootCondition: TerminationCondition;
461
+ /** Concrete condition that fired. */
462
+ readonly firedCondition: TerminationCondition;
463
+ /** Machine-readable stop reason. */
464
+ readonly reason: StopTerminationDecision["reason"];
465
+ /** Normalized machine-readable stop reason across all stop classes. */
466
+ readonly normalizedReason: NormalizedStopReason;
467
+ /** Normalized budget stop reason when the fired condition is budget-based. */
468
+ readonly budgetReason?: BudgetStopReason;
469
+ /** Normalized judge stop reason when the fired condition is judge-based. */
470
+ readonly judgeReason?: JudgeStopReason;
471
+ /** Optional serializable detail from the fired condition. */
472
+ readonly detail?: JsonObject;
473
+ /** firstOf winner diagnostics when the root condition is a composition. */
474
+ readonly firstOf?: FirstOfTerminationStopRecord;
475
+ }
476
+ /**
477
+ * Agent participating in a coordinated workflow.
478
+ */
479
+ export interface AgentSpec {
480
+ /** Stable id written into events, traces, and transcripts. */
481
+ readonly id: string;
482
+ /** Model-visible role or perspective for this agent. */
483
+ readonly role: string;
484
+ /** Optional per-agent instruction appended to the protocol prompt. */
485
+ readonly instructions?: string;
486
+ }
487
+ /**
488
+ * Provider-facing model message.
489
+ *
490
+ * @remarks
491
+ * This is the smallest prompt unit handed to a model adapter. Dogpile keeps it
492
+ * provider-neutral so researchers can bridge the same protocol run into Vercel
493
+ * AI SDK models, deterministic fixtures, or custom lab harnesses without
494
+ * changing protocol code.
495
+ */
496
+ export interface ModelMessage {
497
+ /** Chat role supplied to the configured model provider. */
498
+ readonly role: "system" | "user" | "assistant";
499
+ /** Message text supplied to the configured model provider. */
500
+ readonly content: string;
501
+ }
502
+ /**
503
+ * Provider-neutral reason why a model call stopped generating.
504
+ *
505
+ * @remarks
506
+ * This mirrors the Vercel AI SDK's unified finish reasons while keeping
507
+ * Dogpile's core provider contract independent from the `ai` package.
508
+ */
509
+ export type ModelFinishReason = "stop" | "length" | "content-filter" | "tool-calls" | "error" | "other";
510
+ /**
511
+ * Request passed to a configured model provider.
512
+ *
513
+ * @remarks
514
+ * This is the low-level researcher escape hatch for provider adapters. It is
515
+ * intentionally fetch/runtime neutral and does not depend on Node-only APIs,
516
+ * mutable SDK state, or a specific provider package. Adapters can translate
517
+ * `messages` and `temperature` directly into a Vercel AI SDK call while
518
+ * preserving `metadata` for experiment labels, protocol state, replay ids, or
519
+ * provider-specific request annotations.
520
+ *
521
+ * The metadata object must remain JSON-compatible because it is eligible for
522
+ * inclusion in caller-managed traces and benchmark artifacts.
523
+ *
524
+ * @example
525
+ * ```ts
526
+ * const response = await generateText({
527
+ * model,
528
+ * messages: request.messages,
529
+ * temperature: request.temperature
530
+ * });
531
+ * ```
532
+ */
533
+ export interface ModelRequest {
534
+ /** Ordered chat messages for the next model call. */
535
+ readonly messages: readonly ModelMessage[];
536
+ /** Sampling temperature selected from the tier or caller override. */
537
+ readonly temperature: number;
538
+ /** Optional cancellation signal passed through to fetch-based model adapters. */
539
+ readonly signal?: AbortSignal;
540
+ /** Serializable protocol metadata for tracing and provider adapters. */
541
+ readonly metadata: JsonObject;
542
+ }
543
+ /**
544
+ * Response returned by a configured model provider.
545
+ *
546
+ * @remarks
547
+ * Provider adapters return only the text Dogpile should feed back into the
548
+ * active protocol plus optional usage/cost telemetry. Keeping the response
549
+ * small makes deterministic fixtures and cross-runtime adapters easy to write.
550
+ * When the upstream provider cannot report usage or price, omit those fields
551
+ * rather than inventing non-replayable side data.
552
+ */
553
+ export interface ModelResponse {
554
+ /** Generated text used by the active coordination protocol. */
555
+ readonly text: string;
556
+ /** Optional provider-normalized finish reason for the model call. */
557
+ readonly finishReason?: ModelFinishReason;
558
+ /**
559
+ * Optional provider-neutral runtime tool requests produced by the model adapter.
560
+ *
561
+ * @remarks
562
+ * Adapters that translate Vercel AI SDK tool calls can return normalized
563
+ * requests here. First-party protocols execute them through the shared
564
+ * runtime tool executor and emit matched `tool-call` / `tool-result` events
565
+ * without coupling core to a provider-specific tool-call shape.
566
+ */
567
+ readonly toolRequests?: readonly RuntimeToolExecutionRequest[];
568
+ /** Optional provider-reported token usage. */
569
+ readonly usage?: {
570
+ /** Input tokens consumed by the model call. */
571
+ readonly inputTokens: number;
572
+ /** Output tokens generated by the model call. */
573
+ readonly outputTokens: number;
574
+ /** Combined input and output token count. */
575
+ readonly totalTokens: number;
576
+ };
577
+ /** Optional provider-reported or adapter-estimated cost in US dollars. */
578
+ readonly costUsd?: number;
579
+ /** Optional provider-adapter metadata normalized to JSON-compatible data. */
580
+ readonly metadata?: JsonObject;
581
+ }
582
+ /**
583
+ * Version tag for the replay trace artifact schema.
584
+ */
585
+ export type ReplayTraceSchemaVersion = "1.0";
586
+ /**
587
+ * Serializable seed metadata recorded with replay traces.
588
+ *
589
+ * @remarks
590
+ * Most providers do not expose deterministic seed control. Dogpile still
591
+ * records an explicit empty seed artifact so replay consumers can distinguish
592
+ * "no seed supplied" from a missing trace field.
593
+ */
594
+ export interface ReplayTraceSeed {
595
+ /** Seed artifact discriminant. */
596
+ readonly kind: "replay-trace-seed";
597
+ /** Seed source visible to replay tooling. */
598
+ readonly source: "caller" | "none";
599
+ /** Caller-supplied seed value, or `null` when no seed was supplied. */
600
+ readonly value: string | number | null;
601
+ }
602
+ /**
603
+ * Normalized run inputs persisted inside the replay trace artifact.
604
+ */
605
+ export interface ReplayTraceRunInputs {
606
+ /** Run input artifact discriminant. */
607
+ readonly kind: "replay-trace-run-inputs";
608
+ /** Mission or intent supplied by the caller. */
609
+ readonly intent: string;
610
+ /** Exact normalized protocol config used for execution. */
611
+ readonly protocol: ProtocolConfig;
612
+ /** Selected cost/quality tier. */
613
+ readonly tier: Tier;
614
+ /** Configured model provider id. */
615
+ readonly modelProviderId: string;
616
+ /** Concrete agent roster visible to the protocol. */
617
+ readonly agents: readonly AgentSpec[];
618
+ /** Temperature supplied to provider requests. */
619
+ readonly temperature: number;
620
+ }
621
+ /**
622
+ * Budget and stop-policy artifact persisted inside replay traces.
623
+ */
624
+ export interface ReplayTraceBudget {
625
+ /** Budget artifact discriminant. */
626
+ readonly kind: "replay-trace-budget";
627
+ /** Selected cost/quality tier. */
628
+ readonly tier: Tier;
629
+ /** Optional hard caps supplied by the caller. */
630
+ readonly caps?: Omit<Budget, "tier">;
631
+ /** Optional composable termination policy used by the protocol. */
632
+ readonly termination?: TerminationCondition;
633
+ }
634
+ /**
635
+ * Budget state snapshot derived from a cost-bearing trace event.
636
+ *
637
+ * @remarks
638
+ * Replay consumers can inspect this artifact without walking the full event
639
+ * log. Entries are emitted for model-turn accounting changes, coordination
640
+ * barriers that expose cumulative cost, budget stops, and final completion.
641
+ */
642
+ export interface ReplayTraceBudgetStateChange {
643
+ /** Budget state artifact discriminant. */
644
+ readonly kind: "replay-trace-budget-state-change";
645
+ /** Zero-based event index that exposed this budget state. */
646
+ readonly eventIndex: number;
647
+ /** Source event type for the budget state. */
648
+ readonly eventType: "agent-turn" | "broadcast" | "budget-stop" | "final";
649
+ /** ISO-8601 timestamp from the source event. */
650
+ readonly at: string;
651
+ /** Cumulative cost visible at this point in the run. */
652
+ readonly cost: CostSummary;
653
+ /** Completed model-turn iteration count when known. */
654
+ readonly iteration?: number;
655
+ /** Elapsed runtime in milliseconds when known. */
656
+ readonly elapsedMs?: number;
657
+ /** Budget stop reason when this state records a halt. */
658
+ readonly budgetReason?: BudgetStopReason;
659
+ }
660
+ /**
661
+ * Provider-neutral protocol decision kinds recorded for replay.
662
+ */
663
+ export type ReplayTraceProtocolDecisionType = "assign-role" | "select-agent-turn" | "start-model-call" | "complete-model-call" | "observe-model-output" | "start-tool-call" | "complete-tool-call" | "collect-broadcast-round" | "stop-for-budget" | "finalize-output";
664
+ /**
665
+ * Protocol-level decision appended during execution.
666
+ */
667
+ export interface ReplayTraceProtocolDecision {
668
+ /** Decision artifact discriminant. */
669
+ readonly kind: "replay-trace-protocol-decision";
670
+ /** Zero-based event index that produced this decision. */
671
+ readonly eventIndex: number;
672
+ /** Event type that records the decision. */
673
+ readonly eventType: RunEvent["type"];
674
+ /** Coordination protocol that made the decision. */
675
+ readonly protocol: Protocol;
676
+ /** Provider-neutral decision kind for replay tooling. */
677
+ readonly decision: ReplayTraceProtocolDecisionType;
678
+ /** ISO-8601 timestamp from the source event. */
679
+ readonly at: string;
680
+ /** Agent involved in the decision, when agent-scoped. */
681
+ readonly agentId?: string;
682
+ /** Role involved in the decision, when agent-scoped. */
683
+ readonly role?: string;
684
+ /** Provider call involved in the decision, when model-scoped. */
685
+ readonly callId?: string;
686
+ /** Provider involved in the decision, when model-scoped. */
687
+ readonly providerId?: string;
688
+ /** Tool call involved in the decision, when tool-scoped. */
689
+ readonly toolCallId?: string;
690
+ /** Tool identity involved in the decision, when tool-scoped. */
691
+ readonly tool?: RuntimeToolIdentity;
692
+ /** One-based protocol turn for turn-scoped decisions. */
693
+ readonly turn?: number;
694
+ /** Coordinator phase for coordinator protocol turn decisions. */
695
+ readonly phase?: "plan" | "worker" | "final-synthesis";
696
+ /** One-based broadcast round for grouped broadcast decisions. */
697
+ readonly round?: number;
698
+ /** Number of transcript entries visible after this decision. */
699
+ readonly transcriptEntryCount?: number;
700
+ /** Number of contributions collected at a broadcast barrier. */
701
+ readonly contributionCount?: number;
702
+ /** Prompt/input associated with turn decisions. */
703
+ readonly input?: string;
704
+ /** Output associated with turn or final decisions. */
705
+ readonly output?: string;
706
+ /** Cumulative cost visible at this decision point. */
707
+ readonly cost?: CostSummary;
708
+ /** Normalized budget stop reason for budget-stop decisions. */
709
+ readonly budgetReason?: BudgetStopReason;
710
+ }
711
+ /**
712
+ * Provider call metadata and response captured for replay inspection.
713
+ */
714
+ export interface ReplayTraceProviderCall {
715
+ /** Provider call artifact discriminant. */
716
+ readonly kind: "replay-trace-provider-call";
717
+ /** Stable call id within the run. */
718
+ readonly callId: string;
719
+ /** Configured model provider id. */
720
+ readonly providerId: string;
721
+ /** ISO-8601 timestamp before the provider call started. */
722
+ readonly startedAt: string;
723
+ /** ISO-8601 timestamp after the provider call completed. */
724
+ readonly completedAt: string;
725
+ /** Agent that requested this provider call. */
726
+ readonly agentId: string;
727
+ /** Role that requested this provider call. */
728
+ readonly role: string;
729
+ /** Request handed to the configured model provider. */
730
+ readonly request: ModelRequest;
731
+ /** Response returned by the configured model provider. */
732
+ readonly response: ModelResponse;
733
+ }
734
+ /**
735
+ * Final output artifact persisted inside replay traces.
736
+ */
737
+ export interface ReplayTraceFinalOutput {
738
+ /** Final output artifact discriminant. */
739
+ readonly kind: "replay-trace-final-output";
740
+ /** Final synthesized output returned by the run. */
741
+ readonly output: string;
742
+ /** Total cost at completion. */
743
+ readonly cost: CostSummary;
744
+ /** ISO-8601 completion timestamp from the terminal event. */
745
+ readonly completedAt: string;
746
+ /** Link to the completed transcript artifact. */
747
+ readonly transcript: TranscriptLink;
748
+ }
749
+ /**
750
+ * Incremental text produced by a streaming model provider.
751
+ *
752
+ * @remarks
753
+ * Providers that can surface partial model output should implement
754
+ * {@link ConfiguredModelProvider.stream}. Dogpile concatenates `text` chunks
755
+ * into the completed {@link ModelResponse.text} for transcript and final
756
+ * result compatibility while emitting each chunk as a typed stream/trace event.
757
+ *
758
+ * Usage and cost are optional on chunks because many provider SDKs only expose
759
+ * them at stream completion. When supplied, the last observed usage/cost values
760
+ * are used for the completed model turn.
761
+ */
762
+ export interface ModelOutputChunk {
763
+ /** Text delta produced by the provider. */
764
+ readonly text: string;
765
+ /** Optional provider-normalized finish reason surfaced on a final chunk. */
766
+ readonly finishReason?: ModelResponse["finishReason"];
767
+ /** Optional provider-neutral runtime tool requests surfaced on a final chunk. */
768
+ readonly toolRequests?: ModelResponse["toolRequests"];
769
+ /** Optional provider-reported token usage for the stream so far or final chunk. */
770
+ readonly usage?: ModelResponse["usage"];
771
+ /** Optional provider-reported or adapter-estimated cost in US dollars. */
772
+ readonly costUsd?: number;
773
+ /** Optional provider-adapter metadata normalized to JSON-compatible data. */
774
+ readonly metadata?: ModelResponse["metadata"];
775
+ }
776
+ /**
777
+ * Runtime-neutral model provider configured by the caller.
778
+ *
779
+ * @remarks
780
+ * This is the primary model-extension point. Production adapters can wrap
781
+ * Vercel AI SDK models behind this interface while tests can provide
782
+ * deterministic providers for replayable protocol checks.
783
+ *
784
+ * Implementations should be pure TypeScript and fetch-compatible for Node LTS,
785
+ * Bun, and browser ESM runtimes. Do not assume filesystem access,
786
+ * process globals, or SDK-managed session storage.
787
+ *
788
+ * @example
789
+ * ```ts
790
+ * const provider: ConfiguredModelProvider = {
791
+ * id: "vercel-ai:model-name",
792
+ * async generate(request) {
793
+ * const result = await generateText({
794
+ * model,
795
+ * messages: request.messages,
796
+ * temperature: request.temperature
797
+ * });
798
+ *
799
+ * return { text: result.text };
800
+ * }
801
+ * };
802
+ * ```
803
+ */
804
+ export interface ConfiguredModelProvider {
805
+ /** Stable provider id recorded in traces. */
806
+ readonly id: string;
807
+ /** Generate a response for one protocol-managed model request. */
808
+ generate(request: ModelRequest): Promise<ModelResponse>;
809
+ /**
810
+ * Optionally stream response text for one protocol-managed model request.
811
+ *
812
+ * When present, protocol execution consumes this stream directly and emits
813
+ * `model-output-chunk` events before the completed `agent-turn` event. The
814
+ * fallback `generate()` method remains required for adapters that do not
815
+ * support incremental output and for callers that prefer batch execution.
816
+ */
817
+ stream?(request: ModelRequest): AsyncIterable<ModelOutputChunk>;
818
+ }
819
+ /**
820
+ * Stable identity for a runtime tool available to protocol execution.
821
+ *
822
+ * @remarks
823
+ * Tool identity is protocol-agnostic: the same tool can be made visible to
824
+ * coordinator, sequential, broadcast, or shared runs. `id` is the canonical
825
+ * trace key and should remain stable across releases when replay fixtures
826
+ * depend on it. `namespace` and `version` let applications distinguish
827
+ * similarly named tools without baking provider or runtime details into core.
828
+ */
829
+ export interface RuntimeToolIdentity {
830
+ /** Stable tool id written into tool calls, results, and trace artifacts. */
831
+ readonly id: string;
832
+ /** Human-readable tool name suitable for model-visible descriptions. */
833
+ readonly name: string;
834
+ /** Optional package, product, or caller-owned namespace. */
835
+ readonly namespace?: string;
836
+ /** Optional semantic version or caller-managed revision label. */
837
+ readonly version?: string;
838
+ /** Optional model-visible description of what the tool does. */
839
+ readonly description?: string;
840
+ }
841
+ /**
842
+ * Protocol-agnostic input schema for a runtime tool.
843
+ *
844
+ * @remarks
845
+ * Dogpile keeps the schema as JSON-compatible data so callers can translate it
846
+ * into Vercel AI SDK tool definitions, provider-specific function calling, or
847
+ * custom researcher harnesses without importing Node-only validators. The
848
+ * schema should describe a JSON object input; tool execution receives that
849
+ * object as the typed `input` argument.
850
+ */
851
+ export interface RuntimeToolInputSchema {
852
+ /** Schema discriminant for future schema families. */
853
+ readonly kind: "json-schema";
854
+ /** JSON Schema-compatible object describing the tool input. */
855
+ readonly schema: JsonObject;
856
+ /** Optional human-readable input description. */
857
+ readonly description?: string;
858
+ }
859
+ /**
860
+ * Immutable trace snapshot visible to a runtime tool during execution.
861
+ *
862
+ * @remarks
863
+ * The snapshot is intentionally read-only and serializable. Tools can inspect
864
+ * coordination history without mutating SDK state or depending on storage.
865
+ */
866
+ export interface RuntimeToolTraceContext {
867
+ /** Ordered coordination events emitted before this tool execution. */
868
+ readonly events: readonly RunEvent[];
869
+ /** Ordered transcript entries completed before this tool execution. */
870
+ readonly transcript: readonly TranscriptEntry[];
871
+ }
872
+ /**
873
+ * Protocol-agnostic execution context passed to runtime tools.
874
+ *
875
+ * @remarks
876
+ * The context gives a tool the active run identity, protocol, tier, optional
877
+ * agent/turn labels, and a read-only trace snapshot. The optional
878
+ * `abortSignal` is runtime-neutral across modern JS runtimes and lets budget
879
+ * or timeout policy cancel long-running fetch-based tools without requiring
880
+ * Node-only APIs.
881
+ */
882
+ export interface RuntimeToolExecutionContext {
883
+ /** Stable id for the workflow run that requested the tool. */
884
+ readonly runId: string;
885
+ /** Stable id for this individual tool call. */
886
+ readonly toolCallId: string;
887
+ /** Coordination protocol currently executing. */
888
+ readonly protocol: Protocol;
889
+ /** Cost/quality tier selected for the run. */
890
+ readonly tier: Tier;
891
+ /** Agent that requested the tool, when execution is agent-scoped. */
892
+ readonly agentId?: string;
893
+ /** Model-visible role of the requesting agent, when available. */
894
+ readonly role?: string;
895
+ /** One-based protocol turn index, when execution is turn-scoped. */
896
+ readonly turn?: number;
897
+ /** Read-only serializable trace state visible at the call boundary. */
898
+ readonly trace?: RuntimeToolTraceContext;
899
+ /** Optional cancellation signal for fetch-based tool implementations. */
900
+ readonly abortSignal?: AbortSignal;
901
+ /** Additional caller-owned serializable execution metadata. */
902
+ readonly metadata?: JsonObject;
903
+ }
904
+ /**
905
+ * Protocol-neutral request to execute one runtime tool.
906
+ *
907
+ * @remarks
908
+ * First-party protocols use this shape instead of protocol-specific tool call
909
+ * objects. The input and metadata are JSON-compatible so the request-side
910
+ * event can be persisted for caller-managed replay, while `abortSignal`
911
+ * remains an execution-only control for portable fetch-based adapters.
912
+ */
913
+ export interface RuntimeToolExecutionRequest {
914
+ /** Stable tool id from {@link RuntimeToolIdentity.id}. */
915
+ readonly toolId: string;
916
+ /** Optional caller-supplied call id; generated by the executor when omitted. */
917
+ readonly toolCallId?: string;
918
+ /** JSON-serializable tool input. */
919
+ readonly input: JsonObject;
920
+ /** Agent that requested the tool, when agent-scoped. */
921
+ readonly agentId?: string;
922
+ /** Model-visible role of the requesting agent, when available. */
923
+ readonly role?: string;
924
+ /** One-based protocol turn index, when execution is turn-scoped. */
925
+ readonly turn?: number;
926
+ /** Optional cancellation signal for this call. */
927
+ readonly abortSignal?: AbortSignal;
928
+ /** Additional caller-owned serializable request metadata. */
929
+ readonly metadata?: JsonObject;
930
+ }
931
+ /**
932
+ * Shared protocol-agnostic tool executor used by first-party protocol runners.
933
+ */
934
+ export interface RuntimeToolExecutor {
935
+ /** Runtime tools available to the active protocol run. */
936
+ readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];
937
+ /** Execute one normalized tool request and emit matching tool events. */
938
+ execute(request: RuntimeToolExecutionRequest): Promise<RuntimeToolResult>;
939
+ }
940
+ /**
941
+ * JSON-serializable runtime tool error shape.
942
+ *
943
+ * @remarks
944
+ * Tool errors are data, not thrown values, at the public boundary. Adapters may
945
+ * still throw internally, but protocol code should normalize failures into
946
+ * this shape before writing traces so failed tool calls remain replayable.
947
+ */
948
+ export interface RuntimeToolError {
949
+ /** Machine-readable error code, for example `timeout` or `invalid-input`. */
950
+ readonly code: string;
951
+ /** Human-readable error message. */
952
+ readonly message: string;
953
+ /** Whether the same call may be retried safely by caller policy. */
954
+ readonly retryable?: boolean;
955
+ /** Optional serializable diagnostic detail. */
956
+ readonly detail?: JsonObject;
957
+ }
958
+ /**
959
+ * Successful runtime tool execution result.
960
+ */
961
+ export interface RuntimeToolSuccessResult<Output = JsonValue> {
962
+ /** Result discriminant for exhaustive tool-result handling. */
963
+ readonly type: "success";
964
+ /** Stable id matching the execution context call id. */
965
+ readonly toolCallId: string;
966
+ /** Tool identity that produced the result. */
967
+ readonly tool: RuntimeToolIdentity;
968
+ /** JSON-serializable tool output. */
969
+ readonly output: Output;
970
+ /** Optional serializable result metadata. */
971
+ readonly metadata?: JsonObject;
972
+ }
973
+ /**
974
+ * Failed runtime tool execution result.
975
+ */
976
+ export interface RuntimeToolErrorResult {
977
+ /** Result discriminant for exhaustive tool-result handling. */
978
+ readonly type: "error";
979
+ /** Stable id matching the execution context call id. */
980
+ readonly toolCallId: string;
981
+ /** Tool identity that produced the error. */
982
+ readonly tool: RuntimeToolIdentity;
983
+ /** JSON-serializable normalized error. */
984
+ readonly error: RuntimeToolError;
985
+ /** Optional serializable result metadata. */
986
+ readonly metadata?: JsonObject;
987
+ }
988
+ /**
989
+ * Runtime tool result union shared by every coordination protocol.
990
+ */
991
+ export type RuntimeToolResult<Output = JsonValue> = RuntimeToolSuccessResult<Output> | RuntimeToolErrorResult;
992
+ /**
993
+ * Tool call/result pair preserved on the transcript entry for the model turn
994
+ * that requested it.
995
+ */
996
+ export interface TranscriptToolCall {
997
+ /** Stable id shared by the request event and result payload. */
998
+ readonly toolCallId: string;
999
+ /** Tool identity selected for execution. */
1000
+ readonly tool: RuntimeToolIdentity;
1001
+ /** JSON-serializable tool input requested by the model/provider adapter. */
1002
+ readonly input: JsonObject;
1003
+ /** Normalized JSON-serializable tool result returned by the runtime tool. */
1004
+ readonly result: RuntimeToolResult;
1005
+ }
1006
+ /**
1007
+ * Protocol-agnostic runtime tool definition.
1008
+ *
1009
+ * @remarks
1010
+ * This is the low-level tool escape hatch used by applications and research
1011
+ * harnesses. Core owns the orchestration context and serializable result
1012
+ * contract; callers own the actual implementation and any fetch-based I/O the
1013
+ * tool performs. `inputSchema` is the model-visible JSON contract; optional
1014
+ * `validateInput` is the adapter-owned runtime check applied immediately before
1015
+ * `execute`.
1016
+ */
1017
+ export interface RuntimeTool<Input extends object = JsonObject, Output = JsonValue> {
1018
+ /** Stable identity and model-visible description. */
1019
+ readonly identity: RuntimeToolIdentity;
1020
+ /** JSON-compatible schema for the object input expected by `execute`. */
1021
+ readonly inputSchema: RuntimeToolInputSchema;
1022
+ /** Optional permissions the adapter needs from caller policy before execution. */
1023
+ readonly permissions?: readonly RuntimeToolPermission[];
1024
+ /**
1025
+ * Optional adapter-owned input validation hook evaluated before execution.
1026
+ *
1027
+ * @remarks
1028
+ * Dogpile validates that this property is callable at registration time.
1029
+ * During a tool call, Dogpile invokes it after the `tool-call` event and
1030
+ * before `execute`. Returning `{ type: "invalid", issues }` prevents
1031
+ * `execute` from running and produces a `RuntimeToolErrorResult` with
1032
+ * `error.code: "invalid-input"` and serializable issue details. Use this
1033
+ * hook for deterministic, side-effect-free runtime checks that narrow the
1034
+ * JSON input before the tool performs I/O.
1035
+ */
1036
+ validateInput?(input: Readonly<Input>): RuntimeToolValidationResult;
1037
+ /** Execute the tool for one protocol-managed call. */
1038
+ execute(input: Readonly<Input>, context: RuntimeToolExecutionContext): RuntimeToolResult<Output> | Promise<RuntimeToolResult<Output>>;
1039
+ }
1040
+ /**
1041
+ * Permission declaration for tool adapters.
1042
+ *
1043
+ * @remarks
1044
+ * Permissions are declarative and serializable. Dogpile core does not grant
1045
+ * capabilities itself; applications and protocol harnesses can inspect this
1046
+ * data before exposing tools to model-driven execution.
1047
+ */
1048
+ export type RuntimeToolPermission = RuntimeToolNetworkPermission | RuntimeToolCodeExecutionPermission | RuntimeToolCustomPermission;
1049
+ /**
1050
+ * Permission declaration for fetch-compatible network access.
1051
+ */
1052
+ export interface RuntimeToolNetworkPermission {
1053
+ /** Permission discriminant. */
1054
+ readonly kind: "network";
1055
+ /** Optional host allowlist expected by the adapter. */
1056
+ readonly allowHosts?: readonly string[];
1057
+ /** Whether private-network destinations may be reached. */
1058
+ readonly allowPrivateNetwork?: boolean;
1059
+ }
1060
+ /**
1061
+ * Permission declaration for caller-owned code execution sandboxes.
1062
+ */
1063
+ export interface RuntimeToolCodeExecutionPermission {
1064
+ /** Permission discriminant. */
1065
+ readonly kind: "code-execution";
1066
+ /** Sandbox boundary supplied by the caller or host application. */
1067
+ readonly sandbox: "caller-provided" | "none";
1068
+ /** Optional language allowlist exposed by the adapter. */
1069
+ readonly languages?: readonly string[];
1070
+ /** Whether executed code may perform network I/O inside the sandbox. */
1071
+ readonly allowNetwork?: boolean;
1072
+ }
1073
+ /**
1074
+ * Permission declaration for adapter-specific capabilities.
1075
+ */
1076
+ export interface RuntimeToolCustomPermission {
1077
+ /** Permission discriminant. */
1078
+ readonly kind: "custom";
1079
+ /** Stable custom permission name. */
1080
+ readonly name: string;
1081
+ /** Optional human-readable policy note for caller-owned authorization checks. */
1082
+ readonly description?: string;
1083
+ /** Optional serializable policy metadata. */
1084
+ readonly metadata?: JsonObject;
1085
+ }
1086
+ /**
1087
+ * Shared validation issue emitted before a tool adapter executes.
1088
+ */
1089
+ export interface RuntimeToolValidationIssue {
1090
+ /** Machine-readable validation code. */
1091
+ readonly code: "invalid-type" | "missing-field" | "invalid-value" | "out-of-range";
1092
+ /** Dot-path or field name that failed validation. */
1093
+ readonly path: string;
1094
+ /** Human-readable validation message. */
1095
+ readonly message: string;
1096
+ /** Optional serializable diagnostic detail. */
1097
+ readonly detail?: JsonObject;
1098
+ }
1099
+ /**
1100
+ * Shared validation result for adapter input checks.
1101
+ */
1102
+ export type RuntimeToolValidationResult = RuntimeToolValidationValidResult | RuntimeToolValidationInvalidResult;
1103
+ /**
1104
+ * Valid adapter input.
1105
+ */
1106
+ export interface RuntimeToolValidationValidResult {
1107
+ /** Validation discriminant. */
1108
+ readonly type: "valid";
1109
+ }
1110
+ /**
1111
+ * Invalid adapter input.
1112
+ */
1113
+ export interface RuntimeToolValidationInvalidResult {
1114
+ /** Validation discriminant. */
1115
+ readonly type: "invalid";
1116
+ /** One or more serializable validation issues. */
1117
+ readonly issues: readonly RuntimeToolValidationIssue[];
1118
+ }
1119
+ /**
1120
+ * Common adapter error codes used by built-in and third-party tools.
1121
+ */
1122
+ export type RuntimeToolAdapterErrorCode = "invalid-input" | "permission-denied" | "timeout" | "aborted" | "unavailable" | "backend-error" | "unknown";
1123
+ /**
1124
+ * Normalized adapter error data.
1125
+ */
1126
+ export interface RuntimeToolAdapterError extends RuntimeToolError {
1127
+ /** Common machine-readable adapter error code. */
1128
+ readonly code: RuntimeToolAdapterErrorCode;
1129
+ }
1130
+ /**
1131
+ * Shared adapter contract implemented by built-in adapters and low-level tools.
1132
+ */
1133
+ export interface RuntimeToolAdapterContract<Input extends object = JsonObject, Output = JsonValue> extends RuntimeTool<Input, Output> {
1134
+ /** Permissions required before this adapter should be exposed or executed. */
1135
+ readonly permissions: readonly RuntimeToolPermission[];
1136
+ /** Adapter-owned input validation hook. */
1137
+ validateInput(input: Readonly<Input>): RuntimeToolValidationResult;
1138
+ }
1139
+ /**
1140
+ * Required output artifact for a benchmark task.
1141
+ */
1142
+ export interface BenchmarkRequiredArtifact {
1143
+ /** Stable artifact name used by scorers and reports. */
1144
+ readonly name: string;
1145
+ /** Fixture-defined artifact shape, for example `enum` or `markdown_table`. */
1146
+ readonly type: string;
1147
+ /** Optional human-readable artifact requirement. */
1148
+ readonly description?: string;
1149
+ /** Optional allowed values for constrained artifacts. */
1150
+ readonly allowedValues?: readonly string[];
1151
+ }
1152
+ /**
1153
+ * Serializable task input shared by benchmark protocol runners.
1154
+ */
1155
+ export interface BenchmarkTaskInput {
1156
+ /** Stable benchmark task id. */
1157
+ readonly id: string;
1158
+ /** Mission text supplied to protocol runners. */
1159
+ readonly intent: string;
1160
+ /** Optional task title for reports. */
1161
+ readonly title?: string;
1162
+ /** Optional benchmark difficulty or paper task level, such as `L3`. */
1163
+ readonly level?: string;
1164
+ /** Required artifacts the run output must contain. */
1165
+ readonly requiredArtifacts?: readonly BenchmarkRequiredArtifact[];
1166
+ /** Serializable scoring rubric or fixture-specific judging metadata. */
1167
+ readonly rubric?: JsonObject;
1168
+ /** Additional serializable fixture metadata. */
1169
+ readonly metadata?: JsonObject;
1170
+ }
1171
+ /**
1172
+ * Benchmark budget controls shared by all protocol runners in one comparison.
1173
+ */
1174
+ export interface BenchmarkBudget {
1175
+ /** Named cost/quality tier selected for the benchmark run. */
1176
+ readonly tier: Tier;
1177
+ /** Optional maximum spend in US dollars. */
1178
+ readonly maxUsd?: number;
1179
+ /** Optional maximum input token count. */
1180
+ readonly maxInputTokens?: number;
1181
+ /** Optional maximum output token count. */
1182
+ readonly maxOutputTokens?: number;
1183
+ /** Optional maximum total token count. */
1184
+ readonly maxTotalTokens?: number;
1185
+ /** Optional quality preference in the inclusive range `0..1`. */
1186
+ readonly qualityWeight?: number;
1187
+ }
1188
+ /**
1189
+ * Benchmark model settings shared across protocol runners.
1190
+ *
1191
+ * @remarks
1192
+ * Research and reproduction workflows use this object to hold provider
1193
+ * settings constant while changing only the coordination protocol. The
1194
+ * `metadata` field is for serializable experiment labels such as corpus id,
1195
+ * prompt template version, model family, or paper reproduction condition.
1196
+ */
1197
+ export interface BenchmarkModelSettings {
1198
+ /** Caller-configured model provider, typically backed by the Vercel AI SDK. */
1199
+ readonly provider: ConfiguredModelProvider;
1200
+ /** Optional fixed temperature for controlled reproduction runs. */
1201
+ readonly temperature?: number;
1202
+ /** Optional deterministic seed recorded for provider adapters that support it. */
1203
+ readonly seed?: number;
1204
+ /** Additional serializable provider or run metadata. */
1205
+ readonly metadata?: JsonObject;
1206
+ }
1207
+ /**
1208
+ * Shared benchmark runner configuration before selecting a protocol.
1209
+ *
1210
+ * @remarks
1211
+ * This contract carries the task input, budget policy, and model settings that
1212
+ * must stay constant when comparing multiple coordination protocols. It is the
1213
+ * researcher-facing escape hatch for paper-faithfulness checks: callers can
1214
+ * project one task into Sequential, Broadcast, Shared, and Coordinator runs
1215
+ * while preserving the same agents, tier, caps, model, and fixture metadata.
1216
+ *
1217
+ * The object is intentionally JSON-adjacent and storage-free. Persist benchmark
1218
+ * inputs, run manifests, and traces in caller-owned systems.
1219
+ */
1220
+ export interface BenchmarkRunnerConfig {
1221
+ /** Serializable benchmark task input. */
1222
+ readonly task: BenchmarkTaskInput;
1223
+ /** Shared budget and cap policy. */
1224
+ readonly budget: BenchmarkBudget;
1225
+ /** Shared model provider and generation settings. */
1226
+ readonly model: BenchmarkModelSettings;
1227
+ /** Optional explicit agents; defaults are used when omitted. */
1228
+ readonly agents?: readonly AgentSpec[];
1229
+ /** Additional serializable benchmark metadata. */
1230
+ readonly metadata?: JsonObject;
1231
+ }
1232
+ /**
1233
+ * Benchmark configuration for one concrete protocol runner invocation.
1234
+ *
1235
+ * @remarks
1236
+ * Use this derived shape after selecting the protocol under test. It preserves
1237
+ * the shared benchmark controls from {@link BenchmarkRunnerConfig} and adds a
1238
+ * named or explicit {@link ProtocolConfig}, which lets reproduction code tune
1239
+ * protocol-native parameters without widening the high-level API.
1240
+ */
1241
+ export interface ProtocolBenchmarkRunConfig extends BenchmarkRunnerConfig {
1242
+ /** Protocol being evaluated under the shared benchmark settings. */
1243
+ readonly protocol: Protocol | ProtocolConfig;
1244
+ }
1245
+ /**
1246
+ * Serializable benchmark protocol descriptor persisted with run artifacts.
1247
+ *
1248
+ * @remarks
1249
+ * Benchmark artifacts record both the normalized protocol name and the exact
1250
+ * caller-supplied protocol config so a reproduction harness can distinguish
1251
+ * `"sequential"` defaults from `{ kind: "sequential", maxTurns: 4 }`.
1252
+ */
1253
+ export interface BenchmarkProtocolArtifact {
1254
+ /** Normalized protocol name used for comparison grouping. */
1255
+ readonly kind: Protocol;
1256
+ /** Exact protocol value supplied to the runner. */
1257
+ readonly config: Protocol | ProtocolConfig;
1258
+ }
1259
+ /**
1260
+ * Reproducibility metadata persisted with every benchmark run artifact.
1261
+ *
1262
+ * @remarks
1263
+ * This shape intentionally stores provider identity and serializable model
1264
+ * settings, but not the provider implementation itself. Callers own provider
1265
+ * construction and external storage; Dogpile owns the portable artifact shape.
1266
+ */
1267
+ export interface BenchmarkReproducibilityArtifact {
1268
+ /** Benchmark task input used for this run. */
1269
+ readonly task: BenchmarkTaskInput;
1270
+ /** Shared budget and cap policy used for this run. */
1271
+ readonly budget: BenchmarkBudget;
1272
+ /** Protocol selected for this run. */
1273
+ readonly protocol: BenchmarkProtocolArtifact;
1274
+ /** Provider id recorded from the configured model. */
1275
+ readonly modelProviderId: string;
1276
+ /** Optional fixed temperature used for the run. */
1277
+ readonly temperature?: number;
1278
+ /** Optional deterministic seed recorded for provider adapters that support it. */
1279
+ readonly seed?: number;
1280
+ /** Additional serializable provider or run metadata. */
1281
+ readonly modelMetadata?: JsonObject;
1282
+ /** Concrete agent roster used for the run. */
1283
+ readonly agents: readonly AgentSpec[];
1284
+ /** Additional serializable benchmark metadata. */
1285
+ readonly benchmarkMetadata?: JsonObject;
1286
+ }
1287
+ /**
1288
+ * Cost and budget metadata recorded for one benchmark run.
1289
+ *
1290
+ * @remarks
1291
+ * This accounting block is intentionally duplicated from the run result and
1292
+ * benchmark controls so benchmark reports can group, filter, and audit spend
1293
+ * without unpacking the full trace or reproduction object. Utilization fields
1294
+ * are only present when the corresponding cap was configured.
1295
+ */
1296
+ export interface BenchmarkCostAccounting {
1297
+ /** Accounting artifact discriminant for future benchmark metadata unions. */
1298
+ readonly kind: "benchmark-cost-accounting";
1299
+ /** Named budget/cost tier selected for this benchmark run. */
1300
+ readonly tier: Tier;
1301
+ /** Shared benchmark budget and cap policy used for this run. */
1302
+ readonly budget: BenchmarkBudget;
1303
+ /** Total token and spend accounting observed for this run. */
1304
+ readonly cost: CostSummary;
1305
+ /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */
1306
+ readonly usdCapUtilization?: number;
1307
+ /** Fraction of the configured total-token cap consumed, when `maxTotalTokens` is present. */
1308
+ readonly totalTokenCapUtilization?: number;
1309
+ }
1310
+ /**
1311
+ * Structured streaming event log captured for one benchmark run.
1312
+ *
1313
+ * @remarks
1314
+ * Benchmark artifacts keep this log beside the full trace so reproduction
1315
+ * harnesses can inspect exactly what the streaming API yielded during the run
1316
+ * without unpacking unrelated trace metadata. The `events` array must match
1317
+ * `trace.events` for completed runs.
1318
+ */
1319
+ export interface BenchmarkStreamingEventLog {
1320
+ /** Event-log discriminant for future benchmark observability artifacts. */
1321
+ readonly kind: "benchmark-streaming-event-log";
1322
+ /** Stable run id shared by the benchmark artifact and trace. */
1323
+ readonly runId: string;
1324
+ /** Protocol whose streaming events were captured. */
1325
+ readonly protocol: Protocol;
1326
+ /** Ordered event kinds for compact coverage checks. */
1327
+ readonly eventTypes: readonly RunEvent["type"][];
1328
+ /** Number of streaming events captured. */
1329
+ readonly eventCount: number;
1330
+ /** Complete ordered streaming events yielded by the run. */
1331
+ readonly events: readonly RunEvent[];
1332
+ }
1333
+ /**
1334
+ * Serializable score persisted for one protocol benchmark artifact.
1335
+ *
1336
+ * @remarks
1337
+ * The score is protocol-scoped because paper reproduction reports compare the
1338
+ * same task across protocol variants. When a judge supplies
1339
+ * {@link RunResult.quality}, the benchmark score records that value on a
1340
+ * 0..100 scale. Otherwise Dogpile computes a conservative artifact-completeness
1341
+ * score from the captured output, transcript, streaming event log, and budget
1342
+ * accounting so unjudged benchmark artifacts still carry an auditable score
1343
+ * derived from stored data.
1344
+ */
1345
+ export interface BenchmarkProtocolScore {
1346
+ /** Score artifact discriminant for future benchmark scoring variants. */
1347
+ readonly kind: "benchmark-protocol-score";
1348
+ /** Protocol this score belongs to. */
1349
+ readonly protocol: Protocol;
1350
+ /** Score in the inclusive range `0..100`. */
1351
+ readonly score: number;
1352
+ /** Normalized score in the inclusive range `0..1`. */
1353
+ readonly normalizedScore: number;
1354
+ /** Maximum score for the current scoring scale. */
1355
+ readonly maxScore: 100;
1356
+ /** How the score was derived. */
1357
+ readonly source: "run-quality" | "artifact-completeness";
1358
+ /** Compact scoring dimensions used to compute the stored score. */
1359
+ readonly dimensions: readonly BenchmarkScoreDimension[];
1360
+ }
1361
+ /**
1362
+ * One serializable dimension contributing to a benchmark protocol score.
1363
+ */
1364
+ export interface BenchmarkScoreDimension {
1365
+ /** Stable dimension name for reports. */
1366
+ readonly name: string;
1367
+ /** Earned points for this dimension. */
1368
+ readonly score: number;
1369
+ /** Maximum points available for this dimension. */
1370
+ readonly maxScore: number;
1371
+ }
1372
+ /**
1373
+ * Reproducible benchmark output artifact for one protocol run.
1374
+ *
1375
+ * @remarks
1376
+ * This is the storage-free persistence contract for reproduction workflows:
1377
+ * callers can write the object to JSON, NDJSON, object storage, or a database
1378
+ * without Dogpile depending on Node-only filesystem APIs. It contains the final
1379
+ * output, full transcript, a structured streaming event log, full trace, cost
1380
+ * summary, and all serializable controls needed to replay the run in
1381
+ * caller-managed infrastructure.
1382
+ */
1383
+ export interface BenchmarkRunArtifact {
1384
+ /** Artifact discriminant for future benchmark artifact unions. */
1385
+ readonly kind: "benchmark-run";
1386
+ /** Schema version for reproducible artifact consumers. */
1387
+ readonly schemaVersion: "1.0";
1388
+ /** Stable run id from the trace. */
1389
+ readonly runId: string;
1390
+ /** ISO-8601 timestamp derived from the first trace event when available. */
1391
+ readonly startedAt: string;
1392
+ /** ISO-8601 timestamp derived from the final trace event when available. */
1393
+ readonly completedAt: string;
1394
+ /** Reproduction controls and serializable fixture inputs. */
1395
+ readonly reproducibility: BenchmarkReproducibilityArtifact;
1396
+ /** Final output produced by the protocol. */
1397
+ readonly output: string;
1398
+ /** Complete normalized transcript for this run. */
1399
+ readonly transcript: readonly TranscriptEntry[];
1400
+ /** Structured streaming event log captured for this benchmark run. */
1401
+ readonly eventLog: BenchmarkStreamingEventLog;
1402
+ /** Full serializable event log and trace for this run. */
1403
+ readonly trace: Trace;
1404
+ /** Cost, tier, and benchmark budget metadata for this run. */
1405
+ readonly accounting: BenchmarkCostAccounting;
1406
+ /** Per-protocol benchmark score computed from the captured artifact data. */
1407
+ readonly score: BenchmarkProtocolScore;
1408
+ /** Total token and spend accounting for this run. */
1409
+ readonly cost: CostSummary;
1410
+ /** Optional normalized quality score in the inclusive range `0..1`. */
1411
+ readonly quality?: number;
1412
+ }
1413
+ /**
1414
+ * Event emitted when a protocol assigns or records an agent role.
1415
+ *
1416
+ * @remarks
1417
+ * This event normally appears near the beginning of a run and establishes the
1418
+ * `agentId`/`role` pair that later turn and transcript records refer to. A
1419
+ * renderer can use it to build the participant roster before model output
1420
+ * starts streaming.
1421
+ *
1422
+ * Payload shape:
1423
+ *
1424
+ * - `type`: always `role-assignment`.
1425
+ * - `runId`: stable id shared by every event and trace object for the run.
1426
+ * - `at`: ISO-8601 timestamp for when the assignment was emitted.
1427
+ * - `agentId`: stable agent id used in events, trace, and transcript entries.
1428
+ * - `role`: model-visible role or perspective assigned to that agent.
1429
+ */
1430
+ export interface RoleAssignmentEvent {
1431
+ /** Discriminant for event rendering and exhaustive switches. */
1432
+ readonly type: "role-assignment";
1433
+ /** Stable run id shared by all events in one workflow. */
1434
+ readonly runId: string;
1435
+ /** ISO-8601 event timestamp. */
1436
+ readonly at: string;
1437
+ /** Agent receiving the role assignment. */
1438
+ readonly agentId: string;
1439
+ /** Role assigned to the agent. */
1440
+ readonly role: string;
1441
+ }
1442
+ /**
1443
+ * Event emitted when Dogpile is about to ask the configured model provider for
1444
+ * one protocol-managed response.
1445
+ *
1446
+ * @remarks
1447
+ * This event is the request-side model activity counterpart to
1448
+ * {@link ModelResponseEvent}. Protocol implementations may omit it when they
1449
+ * only expose completed turns, but adapters and researcher harnesses can emit
1450
+ * it to make provider calls visible in the same streaming event log as agent
1451
+ * turns and final output.
1452
+ */
1453
+ export interface ModelRequestEvent {
1454
+ /** Discriminant for event rendering and exhaustive switches. */
1455
+ readonly type: "model-request";
1456
+ /** Stable run id shared by all events in one workflow. */
1457
+ readonly runId: string;
1458
+ /** ISO-8601 event timestamp. */
1459
+ readonly at: string;
1460
+ /** Stable provider call id within the run. */
1461
+ readonly callId: string;
1462
+ /** Configured model provider id receiving the request. */
1463
+ readonly providerId: string;
1464
+ /** Agent requesting the model call. */
1465
+ readonly agentId: string;
1466
+ /** Agent role for the active model call. */
1467
+ readonly role: string;
1468
+ /** Provider-neutral request handed to the model adapter. */
1469
+ readonly request: ModelRequest;
1470
+ }
1471
+ /**
1472
+ * Event emitted after the configured model provider returns one response.
1473
+ *
1474
+ * @remarks
1475
+ * This event records provider-level model activity without forcing callers to
1476
+ * infer it from the higher-level {@link TurnEvent}. The response is the same
1477
+ * provider-neutral shape captured in replay traces, so it remains portable and
1478
+ * JSON-serializable across Node LTS, Bun, and browser ESM runtimes.
1479
+ */
1480
+ export interface ModelResponseEvent {
1481
+ /** Discriminant for event rendering and exhaustive switches. */
1482
+ readonly type: "model-response";
1483
+ /** Stable run id shared by all events in one workflow. */
1484
+ readonly runId: string;
1485
+ /** ISO-8601 event timestamp. */
1486
+ readonly at: string;
1487
+ /** Stable provider call id within the run. */
1488
+ readonly callId: string;
1489
+ /** Configured model provider id that produced the response. */
1490
+ readonly providerId: string;
1491
+ /** Agent that requested the model call. */
1492
+ readonly agentId: string;
1493
+ /** Agent role for the completed model call. */
1494
+ readonly role: string;
1495
+ /** Provider-neutral response returned by the model adapter. */
1496
+ readonly response: ModelResponse;
1497
+ }
1498
+ /**
1499
+ * Event emitted while a model turn is still generating text.
1500
+ *
1501
+ * @remarks
1502
+ * `model-output-chunk` lets streaming callers render provider output before
1503
+ * the protocol has enough information to commit the completed `agent-turn`
1504
+ * transcript entry. It is emitted only when the configured model provider
1505
+ * implements {@link ConfiguredModelProvider.stream}; non-streaming providers
1506
+ * continue to produce the existing role/turn/final event sequence.
1507
+ *
1508
+ * Payload shape:
1509
+ *
1510
+ * - `type`: always `model-output-chunk`.
1511
+ * - `runId`: stable id shared by every event and trace object for the run.
1512
+ * - `at`: ISO-8601 timestamp for when the chunk was observed.
1513
+ * - `agentId` and `role`: identify the active generating agent.
1514
+ * - `input`: prompt text visible to that agent for this turn.
1515
+ * - `chunkIndex`: zero-based chunk index within this model turn.
1516
+ * - `text`: text delta from the provider.
1517
+ * - `output`: accumulated output for this turn after applying the chunk.
1518
+ */
1519
+ export interface ModelOutputChunkEvent {
1520
+ /** Discriminant for event rendering and exhaustive switches. */
1521
+ readonly type: "model-output-chunk";
1522
+ /** Stable run id shared by all events in one workflow. */
1523
+ readonly runId: string;
1524
+ /** ISO-8601 event timestamp. */
1525
+ readonly at: string;
1526
+ /** Agent currently producing output. */
1527
+ readonly agentId: string;
1528
+ /** Agent role for the active turn. */
1529
+ readonly role: string;
1530
+ /** Prompt/input visible to the agent for this turn. */
1531
+ readonly input: string;
1532
+ /** Zero-based chunk index within the active model turn. */
1533
+ readonly chunkIndex: number;
1534
+ /** Text delta produced by the model provider. */
1535
+ readonly text: string;
1536
+ /** Accumulated output for this turn after applying this chunk. */
1537
+ readonly output: string;
1538
+ }
1539
+ /**
1540
+ * Event emitted when a runtime tool is invoked by protocol or model policy.
1541
+ *
1542
+ * @remarks
1543
+ * Tools are caller-owned escape hatches. This request-side event keeps tool
1544
+ * invocation observable without making Dogpile core depend on Node-only
1545
+ * capabilities, a storage layer, or a provider-specific function-call shape.
1546
+ */
1547
+ export interface ToolCallEvent {
1548
+ /** Discriminant for event rendering and exhaustive switches. */
1549
+ readonly type: "tool-call";
1550
+ /** Stable run id shared by all events in one workflow. */
1551
+ readonly runId: string;
1552
+ /** ISO-8601 event timestamp. */
1553
+ readonly at: string;
1554
+ /** Stable tool call id within the run. */
1555
+ readonly toolCallId: string;
1556
+ /** Tool identity selected for execution. */
1557
+ readonly tool: RuntimeToolIdentity;
1558
+ /** JSON-serializable tool input. */
1559
+ readonly input: JsonObject;
1560
+ /** Agent that requested the tool, when agent-scoped. */
1561
+ readonly agentId?: string;
1562
+ /** Agent role that requested the tool, when available. */
1563
+ readonly role?: string;
1564
+ }
1565
+ /**
1566
+ * Event emitted after a runtime tool returns a normalized result.
1567
+ *
1568
+ * @remarks
1569
+ * Tool failures are data at the public boundary. The result payload uses the
1570
+ * same discriminated union as runtime tool adapters, allowing log consumers to
1571
+ * render successful outputs and normalized errors exhaustively.
1572
+ */
1573
+ export interface ToolResultEvent {
1574
+ /** Discriminant for event rendering and exhaustive switches. */
1575
+ readonly type: "tool-result";
1576
+ /** Stable run id shared by all events in one workflow. */
1577
+ readonly runId: string;
1578
+ /** ISO-8601 event timestamp. */
1579
+ readonly at: string;
1580
+ /** Stable tool call id within the run. */
1581
+ readonly toolCallId: string;
1582
+ /** Tool identity that produced the result. */
1583
+ readonly tool: RuntimeToolIdentity;
1584
+ /** Normalized JSON-serializable tool result. */
1585
+ readonly result: RuntimeToolResult;
1586
+ /** Agent that requested the tool, when agent-scoped. */
1587
+ readonly agentId?: string;
1588
+ /** Agent role that requested the tool, when available. */
1589
+ readonly role?: string;
1590
+ }
1591
+ /**
1592
+ * Provider-normalized participation decision parsed from paper-style agent output.
1593
+ *
1594
+ * @remarks
1595
+ * Dogpile preserves the raw model text on transcript entries and events. When
1596
+ * a model emits the labeled fields `role_selected`, `participation`,
1597
+ * `rationale`, and `contribution`, protocols also attach this structured
1598
+ * metadata so reproduction harnesses can distinguish contribution from
1599
+ * voluntary abstention without reparsing raw text.
1600
+ */
1601
+ export interface AgentDecision {
1602
+ /** Task-specific role selected by the agent for this turn. */
1603
+ readonly selectedRole: string;
1604
+ /** Whether the agent contributed or voluntarily abstained. */
1605
+ readonly participation: AgentParticipation;
1606
+ /** Agent-provided rationale for the selected role and participation choice. */
1607
+ readonly rationale: string;
1608
+ /** Agent-provided contribution text, or abstention explanation. */
1609
+ readonly contribution: string;
1610
+ }
1611
+ /**
1612
+ * Agent participation state for a paper-style turn decision.
1613
+ */
1614
+ export type AgentParticipation = "contribute" | "abstain";
1615
+ /**
1616
+ * Event emitted after one agent contributes a model turn.
1617
+ *
1618
+ * @remarks
1619
+ * `agent-turn` is the primary streaming payload for sequential, coordinator,
1620
+ * shared-state, and broadcast executions. It captures the exact prompt/input
1621
+ * Dogpile supplied to the agent, the text returned by the model provider, and
1622
+ * the cumulative cost after applying that response.
1623
+ *
1624
+ * The corresponding durable transcript record contains the same
1625
+ * `agentId`/`role`/`input`/`output` contribution without event timing or cost
1626
+ * fields. Use this event for live progress UIs and the transcript for replay
1627
+ * or downstream application logic.
1628
+ *
1629
+ * Payload shape:
1630
+ *
1631
+ * - `type`: always `agent-turn`.
1632
+ * - `runId`: stable id shared by every event and trace object for the run.
1633
+ * - `at`: ISO-8601 timestamp for when the turn completed.
1634
+ * - `agentId` and `role`: identify the contributing agent.
1635
+ * - `input`: prompt text visible to that agent for this turn.
1636
+ * - `output`: generated model text produced by the agent.
1637
+ * - `cost`: cumulative token and spend accounting after this turn.
1638
+ */
1639
+ export interface TurnEvent {
1640
+ /** Discriminant for event rendering and exhaustive switches. */
1641
+ readonly type: "agent-turn";
1642
+ /** Stable run id shared by all events in one workflow. */
1643
+ readonly runId: string;
1644
+ /** ISO-8601 event timestamp. */
1645
+ readonly at: string;
1646
+ /** Agent that produced this turn. */
1647
+ readonly agentId: string;
1648
+ /** Agent role for this turn. */
1649
+ readonly role: string;
1650
+ /** Prompt/input visible to the agent for this turn. */
1651
+ readonly input: string;
1652
+ /** Model output produced by the agent. */
1653
+ readonly output: string;
1654
+ /** Optional structured role/participation decision parsed from model output. */
1655
+ readonly decision?: AgentDecision;
1656
+ /** Cumulative cost after this turn. */
1657
+ readonly cost: CostSummary;
1658
+ }
1659
+ /**
1660
+ * One independent contribution captured by a broadcast round event.
1661
+ *
1662
+ * @remarks
1663
+ * Broadcast protocols collect one contribution per participating agent before
1664
+ * synthesis. The contribution payload is intentionally smaller than
1665
+ * {@link TurnEvent}: it is a round-level summary of model outputs, while the
1666
+ * complete prompt/output pair for each agent is still available as individual
1667
+ * `agent-turn` events and {@link TranscriptEntry} records.
1668
+ *
1669
+ * Payload shape:
1670
+ *
1671
+ * - `agentId`: stable id of the contributing agent.
1672
+ * - `role`: model-visible role or perspective used for that contribution.
1673
+ * - `output`: generated text contributed independently for the round.
1674
+ */
1675
+ export interface BroadcastContribution {
1676
+ /** Agent that produced the broadcast contribution. */
1677
+ readonly agentId: string;
1678
+ /** Agent role for the contribution. */
1679
+ readonly role: string;
1680
+ /** Independent model output produced for the shared mission. */
1681
+ readonly output: string;
1682
+ /** Optional structured role/participation decision parsed from model output. */
1683
+ readonly decision?: AgentDecision;
1684
+ }
1685
+ /**
1686
+ * Event emitted after agents broadcast independent contributions for a round.
1687
+ *
1688
+ * @remarks
1689
+ * A `broadcast` event marks the coordination moment where independently
1690
+ * generated agent outputs are gathered for a shared round. It does not replace
1691
+ * per-agent `agent-turn` events; instead, it groups their outputs by round so
1692
+ * observers can render the broadcast barrier and replay the paper protocol's
1693
+ * independent-contribution step.
1694
+ *
1695
+ * Payload shape:
1696
+ *
1697
+ * - `type`: always `broadcast`.
1698
+ * - `runId`: stable id shared by every event and trace object for the run.
1699
+ * - `at`: ISO-8601 timestamp for when the round finished.
1700
+ * - `round`: one-based broadcast round number.
1701
+ * - `contributions`: independent outputs collected for this round.
1702
+ * - `cost`: cumulative token and spend accounting after the round.
1703
+ */
1704
+ export interface BroadcastEvent {
1705
+ /** Discriminant for event rendering and exhaustive switches. */
1706
+ readonly type: "broadcast";
1707
+ /** Stable run id shared by all events in one workflow. */
1708
+ readonly runId: string;
1709
+ /** ISO-8601 event timestamp. */
1710
+ readonly at: string;
1711
+ /** One-based broadcast round number. */
1712
+ readonly round: number;
1713
+ /** Independent contributions collected in this broadcast round. */
1714
+ readonly contributions: readonly BroadcastContribution[];
1715
+ /** Cumulative cost after this broadcast round. */
1716
+ readonly cost: CostSummary;
1717
+ }
1718
+ /**
1719
+ * Event emitted when a workflow halts because a configured budget cap fired.
1720
+ *
1721
+ * @remarks
1722
+ * `budget-stop` records the normalized cap class that stopped execution before
1723
+ * the final event closes the run. The detail object is JSON-serializable so
1724
+ * callers can persist or replay the exact cap, observed value, and limit.
1725
+ */
1726
+ export interface BudgetStopEvent {
1727
+ /** Discriminant for event rendering and exhaustive switches. */
1728
+ readonly type: "budget-stop";
1729
+ /** Stable run id shared by all events in one workflow. */
1730
+ readonly runId: string;
1731
+ /** ISO-8601 event timestamp. */
1732
+ readonly at: string;
1733
+ /** Normalized machine-readable budget stop reason. */
1734
+ readonly reason: BudgetStopReason;
1735
+ /** Total cost at the stop point. */
1736
+ readonly cost: CostSummary;
1737
+ /** Completed model-turn iterations at the stop point. */
1738
+ readonly iteration: number;
1739
+ /** Elapsed runtime in milliseconds at the stop point. */
1740
+ readonly elapsedMs: number;
1741
+ /** Serializable cap diagnostics. */
1742
+ readonly detail: JsonObject;
1743
+ }
1744
+ /**
1745
+ * Link from a terminal event to the completed trace transcript.
1746
+ *
1747
+ * @remarks
1748
+ * Final events are emitted before callers await {@link StreamHandle.result},
1749
+ * so this compact link tells streaming UIs exactly which transcript artifact
1750
+ * the terminal output closes over without duplicating every transcript entry
1751
+ * inside the event log.
1752
+ */
1753
+ export interface TranscriptLink {
1754
+ /** Discriminant for future transcript link variants. */
1755
+ readonly kind: "trace-transcript";
1756
+ /** Number of transcript entries included in the completed trace. */
1757
+ readonly entryCount: number;
1758
+ /** Zero-based index of the last transcript entry, or `null` for empty runs. */
1759
+ readonly lastEntryIndex: number | null;
1760
+ }
1761
+ /**
1762
+ * Event emitted when a workflow produces its final output.
1763
+ *
1764
+ * @remarks
1765
+ * `final` is the terminal streaming event for a successful run. Its `output`
1766
+ * value matches {@link RunResult.output}, and its `cost` value matches the
1767
+ * final aggregate cost returned on the result. Its `transcript` link points to
1768
+ * the completed {@link Trace.transcript} entries that produced the terminal
1769
+ * output.
1770
+ *
1771
+ * Payload shape:
1772
+ *
1773
+ * - `type`: always `final`.
1774
+ * - `runId`: stable id shared by every event and trace object for the run.
1775
+ * - `at`: ISO-8601 timestamp for when final synthesis completed.
1776
+ * - `output`: final synthesized answer returned to the caller.
1777
+ * - `cost`: total token and spend accounting for the run.
1778
+ * - `transcript`: compact link to the completed trace transcript.
1779
+ */
1780
+ export interface FinalEvent {
1781
+ /** Discriminant for event rendering and exhaustive switches. */
1782
+ readonly type: "final";
1783
+ /** Stable run id shared by all events in one workflow. */
1784
+ readonly runId: string;
1785
+ /** ISO-8601 event timestamp. */
1786
+ readonly at: string;
1787
+ /** Final synthesized answer returned as `RunResult.output`. */
1788
+ readonly output: string;
1789
+ /** Total cost at completion. */
1790
+ readonly cost: CostSummary;
1791
+ /** Link to the completed trace transcript. */
1792
+ readonly transcript: TranscriptLink;
1793
+ /** Optional normalized quality score supplied by a caller-owned evaluator. */
1794
+ readonly quality?: NormalizedQualityScore;
1795
+ /** Optional serializable evaluation payload supplied by a caller-owned evaluator. */
1796
+ readonly evaluation?: RunEvaluation;
1797
+ /** Termination condition that stopped the run, when the run ended by policy. */
1798
+ readonly termination?: TerminationStopRecord;
1799
+ }
1800
+ /**
1801
+ * Successful coordination event emitted by Dogpile and persisted in traces.
1802
+ *
1803
+ * @remarks
1804
+ * `RunEvent` is the discriminated union stored in {@link Trace.events} and
1805
+ * used by low-level protocol emit callbacks. Switch on `type` to handle each
1806
+ * coordination moment exhaustively:
1807
+ *
1808
+ * - `role-assignment`: participant/role roster was established.
1809
+ * - `model-request`: one provider-neutral model request was started.
1810
+ * - `model-response`: one provider-neutral model response completed.
1811
+ * - `model-output-chunk`: one streaming model text delta arrived.
1812
+ * - `tool-call`: one runtime tool invocation was started.
1813
+ * - `tool-result`: one runtime tool invocation completed.
1814
+ * - `agent-turn`: one agent completed a prompt/response turn.
1815
+ * - `broadcast`: a broadcast round gathered independent contributions.
1816
+ * - `budget-stop`: a configured budget cap halted further model turns.
1817
+ * - `final`: the run completed and produced the final output.
1818
+ *
1819
+ * Every variant is JSON-serializable and includes `runId` plus an ISO-8601
1820
+ * `at` timestamp so callers can persist, render, or replay the event log
1821
+ * without SDK-owned storage.
1822
+ *
1823
+ * @example
1824
+ * ```ts
1825
+ * for await (const event of Dogpile.stream(options)) {
1826
+ * switch (event.type) {
1827
+ * case "agent-turn":
1828
+ * console.log(event.agentId, event.output);
1829
+ * break;
1830
+ * case "final":
1831
+ * console.log(event.output);
1832
+ * break;
1833
+ * }
1834
+ * }
1835
+ * ```
1836
+ */
1837
+ export type RunEvent = RoleAssignmentEvent | ModelRequestEvent | ModelResponseEvent | ModelOutputChunkEvent | ToolCallEvent | ToolResultEvent | TurnEvent | BroadcastEvent | BudgetStopEvent | FinalEvent;
1838
+ /**
1839
+ * Model activity events yielded by `stream()` and persisted in traces when a
1840
+ * protocol exposes provider-call boundaries.
1841
+ */
1842
+ export type ModelActivityEvent = ModelRequestEvent | ModelResponseEvent | ModelOutputChunkEvent;
1843
+ /**
1844
+ * Tool activity events yielded by `stream()` and persisted in traces when a
1845
+ * protocol or caller-owned adapter invokes runtime tools.
1846
+ */
1847
+ export type ToolActivityEvent = ToolCallEvent | ToolResultEvent;
1848
+ /**
1849
+ * Lifecycle event yielded by `stream()`.
1850
+ *
1851
+ * These events describe workflow coordination state rather than model text.
1852
+ * Role assignment establishes the participant roster, while `budget-stop`
1853
+ * records a lifecycle halt before the terminal completion event.
1854
+ */
1855
+ export type StreamLifecycleEvent = RoleAssignmentEvent | BudgetStopEvent;
1856
+ /**
1857
+ * Output event yielded by `stream()`.
1858
+ *
1859
+ * These events carry generated agent output or grouped round output while a
1860
+ * workflow is still running.
1861
+ */
1862
+ export type StreamOutputEvent = ModelActivityEvent | ToolActivityEvent | TurnEvent | BroadcastEvent;
1863
+ /**
1864
+ * Error event yielded by `stream()` when execution rejects.
1865
+ *
1866
+ * @remarks
1867
+ * Stream errors are emitted before {@link StreamHandle.result} rejects so UIs
1868
+ * and log collectors can record a terminal failure without wrapping the result
1869
+ * promise. The error payload is JSON-serializable and intentionally omits
1870
+ * runtime-specific values such as `Error.stack`.
1871
+ */
1872
+ export interface StreamErrorEvent {
1873
+ /** Discriminant for stream event handling. */
1874
+ readonly type: "error";
1875
+ /** Stable run id when known; empty when failure happened before protocol startup. */
1876
+ readonly runId: string;
1877
+ /** ISO-8601 event timestamp. */
1878
+ readonly at: string;
1879
+ /** Error name when available. */
1880
+ readonly name: string;
1881
+ /** Human-readable error message. */
1882
+ readonly message: string;
1883
+ /** Optional serializable diagnostics supplied by the SDK. */
1884
+ readonly detail?: JsonObject;
1885
+ }
1886
+ /**
1887
+ * Completion event yielded by `stream()` after successful execution.
1888
+ */
1889
+ export type StreamCompletionEvent = FinalEvent;
1890
+ /**
1891
+ * Public streaming event union returned by `stream()`.
1892
+ *
1893
+ * @remarks
1894
+ * The union is grouped into lifecycle, output, error, and completion families:
1895
+ *
1896
+ * - lifecycle: {@link StreamLifecycleEvent}
1897
+ * - output: {@link StreamOutputEvent}
1898
+ * - error: {@link StreamErrorEvent}
1899
+ * - completion: {@link StreamCompletionEvent}
1900
+ *
1901
+ * Successful stream events are also persisted as {@link RunEvent} values in the
1902
+ * completed trace. `error` is stream-only because a failed run has no completed
1903
+ * {@link RunResult} trace to return.
1904
+ */
1905
+ export type StreamEvent = StreamLifecycleEvent | StreamOutputEvent | StreamErrorEvent | StreamCompletionEvent;
1906
+ /**
1907
+ * Lifecycle status for a live {@link StreamHandle}.
1908
+ */
1909
+ export type StreamHandleStatus = "running" | "completed" | "failed" | "cancelled";
1910
+ /**
1911
+ * Normalized transcript entry captured during a run.
1912
+ *
1913
+ * @remarks
1914
+ * The transcript is an ordered list of model-visible contributions. Each entry
1915
+ * represents exactly one agent prompt/response pair in the order Dogpile
1916
+ * executed it. Unlike {@link RunEvent}, transcript entries omit lifecycle
1917
+ * timing, broadcast grouping, and cumulative cost so the structure stays small
1918
+ * and stable for application display, caller-managed persistence, and replay
1919
+ * fixtures.
1920
+ *
1921
+ * Transcript structure:
1922
+ *
1923
+ * - `agentId`: stable id of the agent that produced the contribution.
1924
+ * - `role`: model-visible role or perspective for that contribution.
1925
+ * - `input`: prompt text visible to the agent for that turn.
1926
+ * - `output`: generated text returned by the model provider.
1927
+ * - `toolCalls`: optional ordered tool call/result pairs requested during
1928
+ * that turn.
1929
+ *
1930
+ * `RunResult.transcript` and `Trace.transcript` contain the same ordered
1931
+ * entries; the result-level copy exists for ergonomic access while the trace
1932
+ * keeps the complete serializable replay artifact together.
1933
+ */
1934
+ export interface TranscriptEntry {
1935
+ /** Agent that produced the transcript contribution. */
1936
+ readonly agentId: string;
1937
+ /** Agent role for the contribution. */
1938
+ readonly role: string;
1939
+ /** Prompt/input visible to the agent. */
1940
+ readonly input: string;
1941
+ /** Text produced by the agent. */
1942
+ readonly output: string;
1943
+ /** Optional structured role/participation decision parsed from model output. */
1944
+ readonly decision?: AgentDecision;
1945
+ /** Ordered runtime tool calls and results requested during this turn. */
1946
+ readonly toolCalls?: readonly TranscriptToolCall[];
1947
+ }
1948
+ /**
1949
+ * Complete transcript artifact for a finished run.
1950
+ *
1951
+ * @remarks
1952
+ * High-level APIs expose `readonly TranscriptEntry[]` directly for ergonomic
1953
+ * application use. This named structure is the durable artifact shape for
1954
+ * callers that want a self-describing transcript object with the run id, entry
1955
+ * count, and final output bundled together for persistence or replay.
1956
+ */
1957
+ export interface Transcript {
1958
+ /** Transcript artifact discriminant. */
1959
+ readonly kind: "run-transcript";
1960
+ /** Stable run id shared by the source trace and event log. */
1961
+ readonly runId: string;
1962
+ /** Number of entries in the completed transcript. */
1963
+ readonly entryCount: number;
1964
+ /** Ordered agent prompt/response entries. */
1965
+ readonly entries: readonly TranscriptEntry[];
1966
+ /** Final synthesized output produced from these entries. */
1967
+ readonly finalOutput: string;
1968
+ }
1969
+ /**
1970
+ * Token and spend accounting for a run or turn.
1971
+ */
1972
+ export interface CostSummary {
1973
+ /** Estimated spend in US dollars. */
1974
+ readonly usd: number;
1975
+ /** Input tokens consumed. */
1976
+ readonly inputTokens: number;
1977
+ /** Output tokens generated. */
1978
+ readonly outputTokens: number;
1979
+ /** Combined input and output token count. */
1980
+ readonly totalTokens: number;
1981
+ }
1982
+ /**
1983
+ * Aggregate provider usage reported for a completed run.
1984
+ *
1985
+ * This mirrors {@link CostSummary} at the non-streaming result boundary so
1986
+ * callers can read model usage without treating spend accounting as the only
1987
+ * usage artifact. It remains JSON-serializable and runtime-neutral.
1988
+ */
1989
+ export interface RunUsage {
1990
+ /** Estimated spend in US dollars. */
1991
+ readonly usd: number;
1992
+ /** Input tokens consumed across all model calls. */
1993
+ readonly inputTokens: number;
1994
+ /** Output tokens generated across all model calls. */
1995
+ readonly outputTokens: number;
1996
+ /** Combined input and output token count. */
1997
+ readonly totalTokens: number;
1998
+ }
1999
+ /**
2000
+ * Result-level cost and budget accounting for a completed run.
2001
+ *
2002
+ * @remarks
2003
+ * This block makes budget state first-class on {@link RunResult} without
2004
+ * forcing application code to unpack the full replay trace. It records the
2005
+ * selected tier, caller-supplied caps, optional termination policy, final
2006
+ * usage/cost totals, and compact cap-utilization metadata.
2007
+ */
2008
+ export interface RunAccounting {
2009
+ /** Accounting artifact discriminant. */
2010
+ readonly kind: "run-accounting";
2011
+ /** Named budget/cost tier selected for the run. */
2012
+ readonly tier: Tier;
2013
+ /** Optional hard caps supplied by the caller. */
2014
+ readonly budget?: BudgetCaps;
2015
+ /** Optional termination policy used by the protocol. */
2016
+ readonly termination?: TerminationCondition;
2017
+ /** Total token and spend usage for the run. */
2018
+ readonly usage: RunUsage;
2019
+ /** Total token and spend cost for the run. */
2020
+ readonly cost: CostSummary;
2021
+ /** Ordered budget state snapshots derived from cost-bearing events. */
2022
+ readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];
2023
+ /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */
2024
+ readonly usdCapUtilization?: number;
2025
+ /** Fraction of the configured total-token cap consumed, when `maxTokens` is present. */
2026
+ readonly totalTokenCapUtilization?: number;
2027
+ }
2028
+ /**
2029
+ * Normalized quality score for a completed run.
2030
+ *
2031
+ * Values use the inclusive `0..1` range. The field is optional on
2032
+ * {@link RunResult} because production model runs may not have a judge, while
2033
+ * benchmark and researcher harnesses can attach a score without changing the
2034
+ * single-call result shape.
2035
+ */
2036
+ export type NormalizedQualityScore = number;
2037
+ /**
2038
+ * Serializable evaluation payload for a completed run.
2039
+ *
2040
+ * @remarks
2041
+ * Applications and benchmark harnesses can attach caller-owned judge output
2042
+ * without making Dogpile core depend on a storage layer, model-specific judge,
2043
+ * or Node-only runtime. The `quality` value is mirrored to
2044
+ * {@link RunResult.quality} and the terminal {@link FinalEvent} so streaming
2045
+ * and non-streaming execution expose the same judged result.
2046
+ */
2047
+ export interface RunEvaluation {
2048
+ /** Normalized quality score in the inclusive range `0..1`. */
2049
+ readonly quality: NormalizedQualityScore;
2050
+ /** Optional human-readable judge rationale. */
2051
+ readonly rationale?: string;
2052
+ /** Optional serializable judge or benchmark metadata. */
2053
+ readonly metadata?: JsonObject;
2054
+ }
2055
+ /**
2056
+ * JSON-serializable trace returned with every completed workflow.
2057
+ *
2058
+ * @remarks
2059
+ * This is the canonical caller-managed replay artifact. Dogpile core remains
2060
+ * stateless, so every SDK-owned fact needed to inspect a completed run is
2061
+ * represented as JSON-compatible data here: normalized inputs, budget policy,
2062
+ * seed metadata, ordered events, protocol decisions, provider requests and
2063
+ * responses, budget snapshots, transcript entries, and the final output.
2064
+ *
2065
+ * Event order is authoritative. `events[n]` is the source coordination moment
2066
+ * for `protocolDecisions[n]`, and `RunEventLog.events` uses the same order as
2067
+ * this trace for completed runs. Provider calls are ordered by execution and
2068
+ * capture the exact {@link ModelRequest} handed to the configured adapter plus
2069
+ * the exact {@link ModelResponse} returned by that adapter, including optional
2070
+ * usage and cost telemetry. Current protocol runners keep provider calls
2071
+ * one-to-one with transcript entries and completed `agent-turn` events.
2072
+ */
2073
+ export interface Trace {
2074
+ /** Replay trace schema version. */
2075
+ readonly schemaVersion: ReplayTraceSchemaVersion;
2076
+ /** Stable id for this workflow run. */
2077
+ readonly runId: string;
2078
+ /** Protocol that produced this trace. */
2079
+ readonly protocol: Protocol;
2080
+ /** Cost/quality tier selected for the run. */
2081
+ readonly tier: Tier;
2082
+ /** Configured model provider id used by the run. */
2083
+ readonly modelProviderId: string;
2084
+ /** Concrete agents that participated in the run. */
2085
+ readonly agentsUsed: readonly AgentSpec[];
2086
+ /** Normalized caller inputs needed to replay this run. */
2087
+ readonly inputs: ReplayTraceRunInputs;
2088
+ /** Budget caps and termination policy used by this run. */
2089
+ readonly budget: ReplayTraceBudget;
2090
+ /** Ordered budget state snapshots derived from cost-bearing events. */
2091
+ readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];
2092
+ /** Deterministic seed metadata for replay tooling. */
2093
+ readonly seed: ReplayTraceSeed;
2094
+ /** Ordered protocol decisions derived from the event log. */
2095
+ readonly protocolDecisions: readonly ReplayTraceProtocolDecision[];
2096
+ /** Provider requests and responses captured during execution. */
2097
+ readonly providerCalls: readonly ReplayTraceProviderCall[];
2098
+ /** Final output artifact for replay consumers. */
2099
+ readonly finalOutput: ReplayTraceFinalOutput;
2100
+ /**
2101
+ * Ordered coordination and lifecycle events.
2102
+ *
2103
+ * This is the complete streaming event log captured during execution. It has
2104
+ * the same event shapes yielded by {@link StreamHandle} and remains
2105
+ * JSON-serializable for caller-managed replay.
2106
+ */
2107
+ readonly events: readonly RunEvent[];
2108
+ /**
2109
+ * Complete normalized model-turn transcript.
2110
+ *
2111
+ * Entries are ordered by execution and contain only agent id, role, input,
2112
+ * and output. Use this when the application needs the conversation artifact
2113
+ * without streaming lifecycle metadata.
2114
+ */
2115
+ readonly transcript: readonly TranscriptEntry[];
2116
+ }
2117
+ /**
2118
+ * Complete event log returned by non-streaming APIs.
2119
+ *
2120
+ * This is the result-level counterpart to the live {@link StreamHandle}
2121
+ * iterator. It contains the exact ordered events also stored in
2122
+ * {@link Trace.events}, plus compact metadata useful for dashboards and tests
2123
+ * that do not need to unpack the full trace.
2124
+ */
2125
+ export interface RunEventLog {
2126
+ /** Event-log artifact discriminant. */
2127
+ readonly kind: "run-event-log";
2128
+ /** Stable id shared by every event in this log. */
2129
+ readonly runId: string;
2130
+ /** Protocol that produced the event log. */
2131
+ readonly protocol: Protocol;
2132
+ /** Ordered event kinds for compact coverage checks. */
2133
+ readonly eventTypes: readonly RunEvent["type"][];
2134
+ /** Number of events captured. */
2135
+ readonly eventCount: number;
2136
+ /** Complete ordered event log for the run. */
2137
+ readonly events: readonly RunEvent[];
2138
+ }
2139
+ /**
2140
+ * Run metadata returned by non-streaming APIs.
2141
+ *
2142
+ * The metadata block gathers stable identifiers and timing boundaries that are
2143
+ * otherwise derivable from {@link Trace}. Keeping it explicit makes the
2144
+ * single-call result easier to persist, index, and inspect without adding SDK
2145
+ * storage.
2146
+ */
2147
+ export interface RunMetadata {
2148
+ /** Stable id for this workflow run. */
2149
+ readonly runId: string;
2150
+ /** Protocol that produced this run. */
2151
+ readonly protocol: Protocol;
2152
+ /** Cost/quality tier selected for the run. */
2153
+ readonly tier: Tier;
2154
+ /** Configured model provider id used by the run. */
2155
+ readonly modelProviderId: string;
2156
+ /** Concrete agents that participated in the run. */
2157
+ readonly agentsUsed: readonly AgentSpec[];
2158
+ /** ISO-8601 timestamp of the first event, or an empty string for eventless runs. */
2159
+ readonly startedAt: string;
2160
+ /** ISO-8601 timestamp of the final event, or an empty string for eventless runs. */
2161
+ readonly completedAt: string;
2162
+ }
2163
+ /**
2164
+ * Result returned by high-level single-call APIs.
2165
+ *
2166
+ * The returned shape is
2167
+ * `{ output, eventLog, transcript, usage, metadata, accounting, trace, cost, quality, evaluation }`.
2168
+ * `output` is the final synthesized answer, `eventLog` is the complete ordered
2169
+ * coordination log, `transcript` is the complete agent-turn transcript,
2170
+ * `usage` reports token and dollar accounting, and `metadata` exposes stable
2171
+ * run identifiers and timing. `accounting` bundles the selected tier, budget
2172
+ * caps, final usage/cost, and cap utilization. `trace` remains the complete
2173
+ * serializable replay artifact, `cost` is retained as a compatibility alias
2174
+ * for `usage`, and `quality` and `evaluation` are present when a judge or
2175
+ * benchmark supplies a normalized score and serializable evaluation payload.
2176
+ */
2177
+ export interface RunResult {
2178
+ /** Final synthesized answer for the supplied intent. */
2179
+ readonly output: string;
2180
+ /** Complete non-streaming event log captured during the run. */
2181
+ readonly eventLog: RunEventLog;
2182
+ /** Full serializable trace and event log. */
2183
+ readonly trace: Trace;
2184
+ /**
2185
+ * Complete normalized transcript for direct application use.
2186
+ *
2187
+ * This duplicates `trace.transcript` so high-level callers can read the
2188
+ * ordered agent contributions without unpacking the full trace object.
2189
+ */
2190
+ readonly transcript: readonly TranscriptEntry[];
2191
+ /** Total usage and spend accounting for the run. */
2192
+ readonly usage: RunUsage;
2193
+ /** Stable ids, selected controls, provider id, participating agents, and timing boundaries. */
2194
+ readonly metadata: RunMetadata;
2195
+ /** Result-level budget, usage, cost, and cap-utilization accounting. */
2196
+ readonly accounting: RunAccounting;
2197
+ /** Total cost and token accounting for the run; compatibility alias for `usage`. */
2198
+ readonly cost: CostSummary;
2199
+ /** Optional normalized quality score in the inclusive range `0..1`. */
2200
+ readonly quality?: NormalizedQualityScore;
2201
+ /** Optional serializable evaluation data supplied by a caller-owned evaluator. */
2202
+ readonly evaluation?: RunEvaluation;
2203
+ }
2204
+ /**
2205
+ * Caller-owned evaluator invoked after protocol execution and before the final
2206
+ * result is exposed to `run()` or `stream()` callers.
2207
+ */
2208
+ export type RunEvaluator = (result: Omit<RunResult, "quality" | "evaluation">) => RunEvaluation | Promise<RunEvaluation>;
2209
+ /**
2210
+ * Mission supplied to a high-level Dogpile workflow call.
2211
+ *
2212
+ * @remarks
2213
+ * `intent` is the caller-facing mission statement for the agent collective. It
2214
+ * is kept as a named type so applications can expose the same concept without
2215
+ * depending on the full {@link DogpileOptions} object.
2216
+ */
2217
+ export type MissionIntent = string;
2218
+ /**
2219
+ * Coordination protocol selection accepted by high-level SDK calls.
2220
+ *
2221
+ * @remarks
2222
+ * Pass a named protocol for ergonomic defaults, or a protocol config object
2223
+ * when a run needs explicit turn/round limits. The union remains
2224
+ * discriminated once normalized through {@link ProtocolConfig}.
2225
+ */
2226
+ export type ProtocolSelection = ProtocolName | ProtocolConfig;
2227
+ /**
2228
+ * Compatibility alias for high-level coordination protocol selection.
2229
+ */
2230
+ export type CoordinationProtocolSelection = ProtocolSelection;
2231
+ /**
2232
+ * Hard budget caps layered over a selected cost/quality tier.
2233
+ *
2234
+ * @remarks
2235
+ * High-level calls keep `tier` next to `budget`, so the budget object only
2236
+ * carries caps and quality weighting. This shape is JSON-serializable and can
2237
+ * be copied directly into replay traces.
2238
+ */
2239
+ export type BudgetCaps = Omit<Budget, "tier">;
2240
+ /**
2241
+ * Cost and budget controls accepted by high-level SDK calls.
2242
+ *
2243
+ * @remarks
2244
+ * Omit `tier` to use the high-level default `balanced` preset. Omit `budget`
2245
+ * for an uncapped run beyond the tier preset.
2246
+ */
2247
+ export interface BudgetCostTierOptions {
2248
+ /**
2249
+ * Named budget/cost tier.
2250
+ *
2251
+ * Supported values are `fast`, `balanced`, and `quality`. Defaults to
2252
+ * `balanced` when omitted.
2253
+ */
2254
+ readonly tier?: BudgetTier;
2255
+ /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */
2256
+ readonly budget?: BudgetCaps;
2257
+ }
2258
+ /**
2259
+ * Options accepted by the high-level single-call workflow APIs.
2260
+ *
2261
+ * Provide an `intent` and configure a model provider. The high-level surface
2262
+ * defaults to the Sequential protocol and `balanced` tier; callers can pass a
2263
+ * protocol, tier, agents, temperature, or budget caps to refine execution
2264
+ * without constructing an engine.
2265
+ */
2266
+ export interface DogpileOptions extends BudgetCostTierOptions {
2267
+ /** Mission or intent for the agent collective. */
2268
+ readonly intent: MissionIntent;
2269
+ /**
2270
+ * Coordination protocol, either by name or explicit configuration.
2271
+ *
2272
+ * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.
2273
+ * Named protocols use default configs: `maxTurns: 3` for coordinator,
2274
+ * sequential, and shared; `maxRounds: 2` for broadcast.
2275
+ */
2276
+ readonly protocol?: ProtocolSelection;
2277
+ /** Caller-configured model provider, typically backed by the Vercel AI SDK. */
2278
+ readonly model: ConfiguredModelProvider;
2279
+ /** Optional explicit agents; defaults are used when omitted. */
2280
+ readonly agents?: readonly AgentSpec[];
2281
+ /** Optional protocol-agnostic runtime tools available to first-party protocols. */
2282
+ readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];
2283
+ /** Optional temperature override. */
2284
+ readonly temperature?: number;
2285
+ /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */
2286
+ readonly terminate?: TerminationCondition;
2287
+ /** Optional caller-owned evaluator that supplies quality and evaluation data. */
2288
+ readonly evaluate?: RunEvaluator;
2289
+ /** Optional deterministic seed recorded in the replay trace. */
2290
+ readonly seed?: string | number;
2291
+ /** Optional caller cancellation signal passed to provider-facing model requests. */
2292
+ readonly signal?: AbortSignal;
2293
+ }
2294
+ /**
2295
+ * Low-level engine configuration for reusable protocol execution.
2296
+ *
2297
+ * @remarks
2298
+ * Researchers can create one engine with fixed protocol/model/agent settings
2299
+ * and run multiple missions through it for controlled comparisons. Application
2300
+ * code usually starts with {@link DogpileOptions}; use this escape hatch when
2301
+ * you need stable experiment controls, repeated runs against the same model
2302
+ * adapter, custom agent rosters, or explicit protocol configs.
2303
+ *
2304
+ * `budget` is layered over `tier` for caps and quality weighting. The core
2305
+ * remains stateless: every run still returns its own serializable trace and
2306
+ * transcript, and the caller owns persistence or replay.
2307
+ *
2308
+ * @example
2309
+ * ```ts
2310
+ * const engine = createEngine({
2311
+ * protocol: { kind: "sequential", maxTurns: 4 },
2312
+ * tier: "balanced",
2313
+ * model: provider,
2314
+ * agents
2315
+ * });
2316
+ *
2317
+ * const result = await engine.run("Compare the protocol variants.");
2318
+ * ```
2319
+ */
2320
+ export interface EngineOptions {
2321
+ /**
2322
+ * Coordination protocol, either by name or explicit configuration.
2323
+ *
2324
+ * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.
2325
+ * Named protocols use default configs: `maxTurns: 3` for coordinator,
2326
+ * sequential, and shared; `maxRounds: 2` for broadcast.
2327
+ */
2328
+ readonly protocol: ProtocolSelection;
2329
+ /**
2330
+ * Named budget/cost tier.
2331
+ *
2332
+ * Supported values are `fast`, `balanced`, and `quality`. Use `balanced` as
2333
+ * the recommended default when callers do not expose a user preference.
2334
+ */
2335
+ readonly tier: BudgetTier;
2336
+ /** Caller-configured model provider, typically backed by the Vercel AI SDK. */
2337
+ readonly model: ConfiguredModelProvider;
2338
+ /** Optional explicit agents; defaults are used when omitted. */
2339
+ readonly agents?: readonly AgentSpec[];
2340
+ /** Optional protocol-agnostic runtime tools available to first-party protocols. */
2341
+ readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];
2342
+ /** Optional temperature override. */
2343
+ readonly temperature?: number;
2344
+ /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */
2345
+ readonly budget?: Omit<Budget, "tier">;
2346
+ /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */
2347
+ readonly terminate?: TerminationCondition;
2348
+ /** Optional caller-owned evaluator that supplies quality and evaluation data. */
2349
+ readonly evaluate?: RunEvaluator;
2350
+ /** Optional deterministic seed recorded in the replay trace. */
2351
+ readonly seed?: string | number;
2352
+ /** Optional caller cancellation signal passed to provider-facing model requests. */
2353
+ readonly signal?: AbortSignal;
2354
+ }
2355
+ /**
2356
+ * Async event stream returned by `stream()`.
2357
+ *
2358
+ * @remarks
2359
+ * Iterate the handle to receive live {@link StreamEvent} values. Successful
2360
+ * lifecycle, output, and completion events are stored in `result.trace.events`
2361
+ * in the same order. If execution fails, the stream yields one `error` event
2362
+ * and {@link StreamHandle.result} rejects with the original error.
2363
+ *
2364
+ * @example
2365
+ * ```ts
2366
+ * const handle = Dogpile.stream(options);
2367
+ *
2368
+ * for await (const event of handle) {
2369
+ * if (event.type === "agent-turn") {
2370
+ * renderTurn(event.agentId, event.output);
2371
+ * }
2372
+ * }
2373
+ *
2374
+ * const result = await handle.result;
2375
+ * ```
2376
+ */
2377
+ export interface StreamHandle extends AsyncIterable<StreamEvent> {
2378
+ /** Current lifecycle state for this handle. */
2379
+ readonly status: StreamHandleStatus;
2380
+ /** Final result resolved after the stream completes. */
2381
+ readonly result: Promise<RunResult>;
2382
+ /**
2383
+ * Cancel this live stream.
2384
+ *
2385
+ * Cancellation aborts the active provider-facing request signal, emits a
2386
+ * terminal `error` stream event with `code: "aborted"` and
2387
+ * `status: "cancelled"` diagnostics, rejects {@link result}, and closes the
2388
+ * consumer-facing iterator. Calling `cancel()` after the handle has already
2389
+ * completed is a no-op.
2390
+ */
2391
+ cancel(): void;
2392
+ /**
2393
+ * Attach to live events emitted by this run.
2394
+ *
2395
+ * Subscribers first receive the events already emitted by the handle, then
2396
+ * receive live events until they unsubscribe or the run completes. The
2397
+ * returned subscription detaches the listener without cancelling the
2398
+ * underlying run, so demos and UIs can mount/unmount against a live SDK
2399
+ * workflow while the caller still awaits {@link result}.
2400
+ */
2401
+ subscribe(subscriber: StreamEventSubscriber): StreamSubscription;
2402
+ }
2403
+ /**
2404
+ * Callback invoked for each live streaming event.
2405
+ */
2406
+ export type StreamEventSubscriber = (event: StreamEvent) => void;
2407
+ /**
2408
+ * Subscription returned by {@link StreamHandle.subscribe}.
2409
+ */
2410
+ export interface StreamSubscription {
2411
+ /** Stop delivering future events to the subscriber. */
2412
+ unsubscribe(): void;
2413
+ }
2414
+ /**
2415
+ * Reusable low-level protocol engine.
2416
+ *
2417
+ * @remarks
2418
+ * `Engine` is the extension point behind the high-level `run()`,
2419
+ * `stream()`, and `Dogpile.pile()` helpers. It lets research harnesses reuse
2420
+ * one normalized protocol configuration across many missions while choosing
2421
+ * between batch results and live event streams.
2422
+ *
2423
+ * The engine does not retain run history. Store each returned
2424
+ * {@link RunResult.trace} in caller-managed infrastructure if you need replay,
2425
+ * audit, or benchmark aggregation.
2426
+ */
2427
+ export interface Engine {
2428
+ /** Execute a mission to completion and return the final result. */
2429
+ run(intent: string): Promise<RunResult>;
2430
+ /** Stream a mission's events while preserving access to the final result. */
2431
+ stream(intent: string): StreamHandle;
2432
+ }
2433
+ export {};
2434
+ //# sourceMappingURL=types.d.ts.map