@dogpile/sdk 0.2.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +86 -655
- package/dist/browser/index.js +337 -22
- package/dist/browser/index.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/runtime/broadcast.d.ts +1 -0
- package/dist/runtime/broadcast.d.ts.map +1 -1
- package/dist/runtime/broadcast.js +27 -6
- package/dist/runtime/broadcast.js.map +1 -1
- package/dist/runtime/coordinator.d.ts +1 -0
- package/dist/runtime/coordinator.d.ts.map +1 -1
- package/dist/runtime/coordinator.js +45 -8
- package/dist/runtime/coordinator.js.map +1 -1
- package/dist/runtime/engine.d.ts.map +1 -1
- package/dist/runtime/engine.js +5 -0
- package/dist/runtime/engine.js.map +1 -1
- package/dist/runtime/sequential.d.ts +1 -0
- package/dist/runtime/sequential.d.ts.map +1 -1
- package/dist/runtime/sequential.js +24 -6
- package/dist/runtime/sequential.js.map +1 -1
- package/dist/runtime/shared.d.ts +1 -0
- package/dist/runtime/shared.d.ts.map +1 -1
- package/dist/runtime/shared.js +24 -6
- package/dist/runtime/shared.js.map +1 -1
- package/dist/runtime/termination.d.ts +6 -1
- package/dist/runtime/termination.d.ts.map +1 -1
- package/dist/runtime/termination.js +75 -0
- package/dist/runtime/termination.js.map +1 -1
- package/dist/runtime/validation.d.ts.map +1 -1
- package/dist/runtime/validation.js +22 -0
- package/dist/runtime/validation.js.map +1 -1
- package/dist/runtime/wrap-up.d.ts +26 -0
- package/dist/runtime/wrap-up.d.ts.map +1 -0
- package/dist/runtime/wrap-up.js +178 -0
- package/dist/runtime/wrap-up.js.map +1 -0
- package/dist/types.d.ts +68 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +3 -1
- package/src/runtime/broadcast.ts +49 -19
- package/src/runtime/coordinator.ts +83 -27
- package/src/runtime/engine.ts +6 -0
- package/src/runtime/sequential.ts +45 -19
- package/src/runtime/shared.ts +45 -19
- package/src/runtime/termination.ts +100 -0
- package/src/runtime/validation.ts +25 -0
- package/src/runtime/wrap-up.ts +257 -0
- package/src/types.ts +70 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/types.ts","../../src/runtime/defaults.ts","../../src/runtime/cancellation.ts","../../src/runtime/decisions.ts","../../src/runtime/model.ts","../../src/runtime/termination.ts","../../src/runtime/validation.ts","../../src/runtime/tools.ts","../../src/runtime/broadcast.ts","../../src/runtime/coordinator.ts","../../src/runtime/sequential.ts","../../src/runtime/shared.ts","../../src/runtime/engine.ts","../../src/providers/openai-compatible.ts"],"sourcesContent":["/**\n * Primitive JSON value accepted in serializable trace metadata.\n */\nexport type JsonPrimitive = string | number | boolean | null;\n\n/**\n * JSON-compatible value used for trace metadata, model request metadata, and\n * caller-managed replay artifacts.\n *\n * Dogpile core is stateless, so everything needed to inspect or persist a run\n * is represented with serializable data instead of SDK-owned storage.\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n\n/**\n * JSON-compatible object with immutable properties.\n */\nexport interface JsonObject {\n readonly [key: string]: JsonValue;\n}\n\nconst dogpileErrorCodes = [\n \"invalid-configuration\",\n \"aborted\",\n \"timeout\",\n \"provider-authentication\",\n \"provider-invalid-request\",\n \"provider-invalid-response\",\n \"provider-not-found\",\n \"provider-rate-limited\",\n \"provider-timeout\",\n \"provider-unavailable\",\n \"provider-unsupported\",\n \"provider-error\",\n \"unknown\"\n] as const;\n\n/**\n * Stable machine-readable error codes thrown by Dogpile public adapters.\n *\n * @remarks\n * The string values are part of the v1 API contract so JavaScript callers can\n * branch on provider failures without depending on provider SDK classes.\n */\nexport type DogpileErrorCode = (typeof dogpileErrorCodes)[number];\n\n/**\n * Options used to construct a stable Dogpile public error.\n */\nexport interface DogpileErrorOptions<Code extends DogpileErrorCode = DogpileErrorCode> {\n /** Stable machine-readable error code. */\n readonly code: Code;\n /** Human-readable error message. */\n readonly message: string;\n /** Original thrown value, kept off JSON serialization by default. */\n readonly cause?: unknown;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\ninterface DogpileErrorBase<Code extends DogpileErrorCode> extends Error {\n /** Public error class name. */\n readonly name: \"DogpileError\";\n /** Stable machine-readable error code. */\n readonly code: Code;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n /** Original thrown value, if Dogpile wrapped a lower-level failure. */\n readonly cause?: unknown;\n /** JSON-safe representation for logs, traces, and observability tools. */\n toJSON(): JsonObject;\n}\n\nexport type DogpileInvalidConfigurationError = DogpileErrorBase<\"invalid-configuration\">;\nexport type DogpileAbortedError = DogpileErrorBase<\"aborted\">;\nexport type DogpileTimeoutError = DogpileErrorBase<\"timeout\">;\nexport type DogpileProviderAuthenticationError = DogpileErrorBase<\"provider-authentication\">;\nexport type DogpileProviderInvalidRequestError = DogpileErrorBase<\"provider-invalid-request\">;\nexport type DogpileProviderInvalidResponseError = DogpileErrorBase<\"provider-invalid-response\">;\nexport type DogpileProviderNotFoundError = DogpileErrorBase<\"provider-not-found\">;\nexport type DogpileProviderRateLimitedError = DogpileErrorBase<\"provider-rate-limited\">;\nexport type DogpileProviderTimeoutError = DogpileErrorBase<\"provider-timeout\">;\nexport type DogpileProviderUnavailableError = DogpileErrorBase<\"provider-unavailable\">;\nexport type DogpileProviderUnsupportedError = DogpileErrorBase<\"provider-unsupported\">;\nexport type DogpileProviderError = DogpileErrorBase<\"provider-error\">;\nexport type DogpileUnknownError = DogpileErrorBase<\"unknown\">;\n\n/**\n * Public Dogpile error union with stable string code discriminants.\n *\n * @remarks\n * `code` is the discriminant for exhaustive caller handling. The exported\n * `DogpileError` value is still the constructor used to create these errors.\n */\nexport type DogpileError =\n | DogpileInvalidConfigurationError\n | DogpileAbortedError\n | DogpileTimeoutError\n | DogpileProviderAuthenticationError\n | DogpileProviderInvalidRequestError\n | DogpileProviderInvalidResponseError\n | DogpileProviderNotFoundError\n | DogpileProviderRateLimitedError\n | DogpileProviderTimeoutError\n | DogpileProviderUnavailableError\n | DogpileProviderUnsupportedError\n | DogpileProviderError\n | DogpileUnknownError;\n\nexport type DogpileErrorByCode<Code extends DogpileErrorCode> = Extract<DogpileError, { readonly code: Code }>;\n\nexport interface DogpileErrorConstructor {\n new <Code extends DogpileErrorCode>(options: DogpileErrorOptions<Code>): DogpileErrorByCode<Code>;\n readonly prototype: DogpileError;\n /**\n * Cross-realm guard for Dogpile public errors.\n */\n isInstance(error: unknown): error is DogpileError;\n}\n\nclass DogpileErrorImpl extends Error implements DogpileErrorBase<DogpileErrorCode> {\n override name = \"DogpileError\" as const;\n /** Stable machine-readable error code. */\n readonly code: DogpileErrorCode;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n /** Original thrown value, if Dogpile wrapped a lower-level failure. */\n readonly cause?: unknown;\n\n constructor(options: DogpileErrorOptions) {\n super(options.message);\n this.code = options.code;\n\n if (options.retryable !== undefined) {\n this.retryable = options.retryable;\n }\n if (options.providerId !== undefined) {\n this.providerId = options.providerId;\n }\n if (options.detail !== undefined) {\n this.detail = options.detail;\n }\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Cross-realm guard for Dogpile public errors.\n */\n static isInstance(error: unknown): error is DogpileError {\n if (error instanceof DogpileErrorImpl) {\n return true;\n }\n\n if (!isRecord(error)) {\n return false;\n }\n\n return error.name === \"DogpileError\" && isDogpileErrorCode(error.code) && typeof error.message === \"string\";\n }\n\n /**\n * JSON-safe representation for logs, traces, and observability tools.\n */\n toJSON(): JsonObject {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.retryable !== undefined ? { retryable: this.retryable } : {}),\n ...(this.providerId !== undefined ? { providerId: this.providerId } : {}),\n ...(this.detail !== undefined ? { detail: this.detail } : {})\n };\n }\n}\n\n/**\n * Public Dogpile error constructor.\n */\nexport const DogpileError = DogpileErrorImpl as DogpileErrorConstructor;\n\nfunction isDogpileErrorCode(value: unknown): value is DogpileErrorCode {\n return typeof value === \"string\" && dogpileErrorCodes.includes(value as DogpileErrorCode);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Coordination protocols supported by the public SDK surface.\n *\n * Supported values:\n *\n * - `coordinator`: a coordinator assigns work and synthesizes a final answer.\n * - `sequential`: agents refine the answer one after another.\n * - `broadcast`: agents answer the same mission independently before merge.\n * - `shared`: agents collaborate through shared state.\n *\n * Passing a string protocol uses the SDK defaults from {@link ProtocolConfig}:\n * `maxTurns: 3` for `coordinator`, `sequential`, and `shared`, and\n * `maxRounds: 2` for `broadcast`.\n */\nexport type Protocol = \"coordinator\" | \"sequential\" | \"broadcast\" | \"shared\";\n\n/**\n * Public coordination protocol selector name.\n *\n * @remarks\n * This alias is the caller-facing literal union shared by high-level calls,\n * low-level engine configuration, traces, events, and benchmark artifacts.\n * `Protocol` remains the short compatibility name for the same public union.\n */\nexport type ProtocolName = Protocol;\n\n/**\n * Named cost and quality presets.\n *\n * Supported values:\n *\n * - `fast`: minimizes latency and spend; default temperature is `0`.\n * - `balanced`: general-purpose tradeoff; default temperature is `0.2`.\n * - `quality`: spends more work on answer quality; default temperature is `0.4`.\n *\n * High-level workflow calls default to `balanced` when callers omit a tier.\n * Low-level engine configuration keeps the tier explicit for repeatable\n * research runs.\n */\nexport type BudgetTier = \"fast\" | \"balanced\" | \"quality\";\n\n/**\n * Short compatibility name for the public budget tier union.\n */\nexport type Tier = BudgetTier;\n\n/**\n * Sequential protocol configuration.\n *\n * Agents contribute in order, with each turn seeing the prior transcript.\n * Default when `protocol: \"sequential\"` is supplied: `{ kind: \"sequential\",\n * maxTurns: 3 }`.\n */\nexport interface SequentialProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"sequential\";\n /** Maximum number of agent turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n}\n\n/**\n * Coordinator protocol configuration.\n *\n * A coordinator manages worker turns and synthesizes the final output.\n * Default when `protocol: \"coordinator\"` is supplied: `{ kind: \"coordinator\",\n * maxTurns: 3 }`.\n */\nexport interface CoordinatorProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"coordinator\";\n /** Maximum number of coordinator-managed turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n}\n\n/**\n * Broadcast protocol configuration.\n *\n * Agents independently answer the same mission before a merge/synthesis step.\n * Default when `protocol: \"broadcast\"` is supplied: `{ kind: \"broadcast\",\n * maxRounds: 2 }`.\n */\nexport interface BroadcastProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"broadcast\";\n /** Maximum number of broadcast/merge rounds to execute; defaults to `2` for named protocols. */\n readonly maxRounds?: number;\n}\n\n/**\n * Shared-state protocol configuration.\n *\n * Agents coordinate by reading and updating a shared working state.\n * Default when `protocol: \"shared\"` is supplied: `{ kind: \"shared\",\n * maxTurns: 3 }`.\n */\nexport interface SharedProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"shared\";\n /** Maximum number of shared-state turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n /** Optional organizational memory snapshot visible to every shared agent. */\n readonly organizationalMemory?: string;\n}\n\n/**\n * Discriminated protocol configuration union for low-level runs.\n *\n * Use this union when the named {@link Protocol} defaults are too coarse. The\n * `kind` property is the discriminant and supported values are `coordinator`,\n * `sequential`, `broadcast`, and `shared`.\n */\nexport type ProtocolConfig =\n | SequentialProtocolConfig\n | CoordinatorProtocolConfig\n | BroadcastProtocolConfig\n | SharedProtocolConfig;\n\n/**\n * Budget policy composed from a named tier plus optional hard caps.\n *\n * Supported `tier` values are `fast`, `balanced`, and `quality`. The tier\n * selects default execution behavior such as temperature, while `maxUsd`,\n * `maxTokens`, and `qualityWeight` layer caller-owned cost policy over that\n * preset.\n *\n * The SDK should halt before cap breach and report accumulated usage in\n * {@link CostSummary}. `qualityWeight` expresses how strongly the caller values\n * spending additional budget for higher answer quality.\n */\nexport interface Budget {\n /** Named preset used to choose default execution behavior; recommended default is `balanced`. */\n readonly tier: BudgetTier;\n /** Optional maximum spend in US dollars; omit for no SDK-enforced dollar cap. */\n readonly maxUsd?: number;\n /** Optional maximum total token count; omit for no SDK-enforced token cap. */\n readonly maxTokens?: number;\n /** Optional maximum completed model-turn iterations; omit for no SDK-enforced iteration cap. */\n readonly maxIterations?: number;\n /** Optional maximum elapsed runtime in milliseconds; omit for no SDK-enforced timeout cap. */\n readonly timeoutMs?: number;\n /** Optional quality preference in the inclusive range `0..1`; omit to use the tier default. */\n readonly qualityWeight?: number;\n}\n\n/**\n * Serializable termination condition for cost-controlled and quality-aware runs.\n *\n * @remarks\n * Conditions are discriminated by `kind` so callers can compose and inspect\n * stop policies without relying on functions, closures, storage, or\n * runtime-specific state. Use {@link FirstOfTerminationCondition} when multiple\n * conditions should race and the first terminating condition should win.\n */\nexport type TerminationCondition =\n | BudgetTerminationCondition\n | ConvergenceTerminationCondition\n | JudgeTerminationCondition\n | FirstOfTerminationCondition;\n\n/**\n * Primitive, non-composite termination conditions accepted by `firstOf`.\n */\nexport type PrimitiveTerminationCondition =\n | BudgetTerminationCondition\n | ConvergenceTerminationCondition\n | JudgeTerminationCondition;\n\n/**\n * Halt when observed usage reaches or would exceed a configured cap.\n */\nexport interface BudgetTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"budget\";\n /** Optional maximum spend in US dollars. */\n readonly maxUsd?: number;\n /** Optional maximum total token count. */\n readonly maxTokens?: number;\n /** Optional maximum completed model-turn iterations. */\n readonly maxIterations?: number;\n /** Optional maximum elapsed runtime in milliseconds. */\n readonly timeoutMs?: number;\n}\n\n/**\n * Normalized machine-readable reason for a budget stop.\n */\nexport type BudgetStopReason = \"cost\" | \"tokens\" | \"iterations\" | \"timeout\";\n\n/**\n * Halt when recent outputs are stable enough to treat the run as converged.\n */\nexport interface ConvergenceTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"convergence\";\n /** Number of consecutive stable turns required before terminating. */\n readonly stableTurns: number;\n /** Similarity threshold in the inclusive range `0..1`. */\n readonly minSimilarity: number;\n}\n\n/**\n * Halt when a judge accepts, rejects, or scores the current run state.\n */\nexport interface JudgeTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"judge\";\n /** Model-visible rubric or serialized judge configuration. */\n readonly rubric: string | JsonObject;\n /** Optional score threshold in the inclusive range `0..1`. */\n readonly minScore?: number;\n}\n\n/**\n * Normalized machine-readable reason for a judge stop.\n */\nexport type JudgeStopReason = \"accepted\" | \"rejected\" | \"score-threshold\";\n\n/**\n * Normalized machine-readable stop reason across all termination evaluators.\n */\nexport type NormalizedStopReason =\n | \"budget:cost\"\n | \"budget:tokens\"\n | \"budget:iterations\"\n | \"budget:timeout\"\n | \"convergence\"\n | \"judge:accepted\"\n | \"judge:rejected\"\n | \"judge:score-threshold\";\n\n/**\n * Serializable judge decision visible to judge termination evaluators.\n *\n * @remarks\n * Judge decisions are deliberately separate from budget and convergence state:\n * a caller-owned evaluator can record an explicit accept/reject verdict or a\n * normalized score without coupling termination checks to cost caps or protocol\n * transcript similarity.\n */\nexport type JudgeEvaluationDecision =\n | JudgeAcceptDecision\n | JudgeRejectDecision\n | JudgeScoreDecision;\n\n/**\n * Judge verdict that accepts the current run state.\n */\nexport interface JudgeAcceptDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"accept\";\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly score?: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Judge verdict that rejects the current run state.\n */\nexport interface JudgeRejectDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"reject\";\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly score?: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Judge score without a hard accept/reject verdict.\n */\nexport interface JudgeScoreDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"score\";\n /** Normalized quality score in the inclusive range `0..1`. */\n readonly score: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Input tuple accepted by a `firstOf(...conditions)` helper.\n */\nexport type FirstOfTerminationConditions = readonly [\n PrimitiveTerminationCondition | FirstOfTerminationCondition,\n ...(PrimitiveTerminationCondition | FirstOfTerminationCondition)[]\n];\n\n/**\n * Composite termination condition where the earliest terminating child wins.\n */\nexport interface FirstOfTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"firstOf\";\n /** Ordered child conditions evaluated by the composite. */\n readonly conditions: FirstOfTerminationConditions;\n}\n\n/**\n * Serializable input passed to a firstOf composition evaluator.\n */\nexport interface FirstOfTerminationInput {\n /** Composition input discriminant for logs and tests. */\n readonly kind: \"firstOf-input\";\n /** Conditions to evaluate in order. */\n readonly conditions: FirstOfTerminationConditions;\n /** Current run state visible to termination evaluators. */\n readonly context: TerminationEvaluationContext;\n}\n\n/**\n * Current run state visible to termination evaluators.\n */\nexport interface TerminationEvaluationContext {\n /** Stable id for the workflow run being evaluated. */\n readonly runId: string;\n /** Protocol currently executing. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: BudgetTier;\n /** Current accumulated cost and token usage. */\n readonly cost: CostSummary;\n /** Completed coordination events available at the evaluation point. */\n readonly events: readonly RunEvent[];\n /** Completed transcript entries available at the evaluation point. */\n readonly transcript: readonly TranscriptEntry[];\n /** Completed model-turn iterations at the evaluation point. */\n readonly iteration?: number;\n /** Elapsed runtime in milliseconds at the evaluation point. */\n readonly elapsedMs?: number;\n /** Optional normalized judge or quality score in the inclusive range `0..1`. */\n readonly quality?: NormalizedQualityScore;\n /** Optional caller-owned judge decision for judge termination checks. */\n readonly judgeDecision?: JudgeEvaluationDecision;\n /** Additional serializable evaluator metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Decision returned by a termination condition evaluator.\n */\nexport type TerminationDecision = ContinueTerminationDecision | StopTerminationDecision;\n\n/**\n * Continue running because a condition has not fired.\n */\nexport interface ContinueTerminationDecision {\n /** Decision discriminant for exhaustive termination handling. */\n readonly type: \"continue\";\n /** Condition that was evaluated. */\n readonly condition: TerminationCondition;\n}\n\n/**\n * Stop running because a condition fired.\n */\nexport interface StopTerminationDecision {\n /** Decision discriminant for exhaustive termination handling. */\n readonly type: \"stop\";\n /** Condition that fired. */\n readonly condition: TerminationCondition;\n /** Machine-readable stop reason. */\n readonly reason: \"budget\" | \"convergence\" | \"judge\";\n /** Normalized machine-readable stop reason across all stop classes. */\n readonly normalizedReason: NormalizedStopReason;\n /** Normalized budget stop reason when `reason` is `budget`. */\n readonly budgetReason?: BudgetStopReason;\n /** Normalized judge stop reason when `reason` is `judge`. */\n readonly judgeReason?: JudgeStopReason;\n /** Optional serializable detail for traces and diagnostics. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Output returned after evaluating a `firstOf` composition.\n */\nexport interface FirstOfTerminationOutput {\n /** Composition output discriminant for logs and tests. */\n readonly kind: \"firstOf-output\";\n /** Final decision for the composite condition. */\n readonly decision: TerminationDecision;\n /** Zero-based index of the child condition that fired, or `null` if none fired. */\n readonly winningConditionIndex: number | null;\n /** Per-child decisions in evaluation order. */\n readonly evaluated: readonly TerminationDecision[];\n}\n\n/**\n * Serializable diagnostics for a firstOf composition that stopped a run.\n */\nexport interface FirstOfTerminationStopRecord {\n /** Composition stop discriminant for trace consumers. */\n readonly kind: \"firstOf-stop\";\n /** Zero-based index of the top-level child condition that fired. */\n readonly winningConditionIndex: number;\n /** Top-level child condition that fired. */\n readonly winningCondition: TerminationCondition;\n /** Concrete condition that produced the stop decision. */\n readonly firedCondition: TerminationCondition;\n /** Per-child decisions in evaluation order. */\n readonly evaluated: readonly TerminationDecision[];\n}\n\n/**\n * Serializable record of the termination condition that stopped a run.\n */\nexport interface TerminationStopRecord {\n /** Stop record discriminant for trace consumers. */\n readonly kind: \"termination-stop\";\n /** Condition supplied to the protocol runner. */\n readonly rootCondition: TerminationCondition;\n /** Concrete condition that fired. */\n readonly firedCondition: TerminationCondition;\n /** Machine-readable stop reason. */\n readonly reason: StopTerminationDecision[\"reason\"];\n /** Normalized machine-readable stop reason across all stop classes. */\n readonly normalizedReason: NormalizedStopReason;\n /** Normalized budget stop reason when the fired condition is budget-based. */\n readonly budgetReason?: BudgetStopReason;\n /** Normalized judge stop reason when the fired condition is judge-based. */\n readonly judgeReason?: JudgeStopReason;\n /** Optional serializable detail from the fired condition. */\n readonly detail?: JsonObject;\n /** firstOf winner diagnostics when the root condition is a composition. */\n readonly firstOf?: FirstOfTerminationStopRecord;\n}\n\n/**\n * Agent participating in a coordinated workflow.\n */\nexport interface AgentSpec {\n /** Stable id written into events, traces, and transcripts. */\n readonly id: string;\n /** Model-visible role or perspective for this agent. */\n readonly role: string;\n /** Optional per-agent instruction appended to the protocol prompt. */\n readonly instructions?: string;\n}\n\n/**\n * Provider-facing model message.\n *\n * @remarks\n * This is the smallest prompt unit handed to a model adapter. Dogpile keeps it\n * provider-neutral so researchers can bridge the same protocol run into Vercel\n * AI SDK models, deterministic fixtures, or custom lab harnesses without\n * changing protocol code.\n */\nexport interface ModelMessage {\n /** Chat role supplied to the configured model provider. */\n readonly role: \"system\" | \"user\" | \"assistant\";\n /** Message text supplied to the configured model provider. */\n readonly content: string;\n}\n\n/**\n * Provider-neutral reason why a model call stopped generating.\n *\n * @remarks\n * This mirrors the Vercel AI SDK's unified finish reasons while keeping\n * Dogpile's core provider contract independent from the `ai` package.\n */\nexport type ModelFinishReason = \"stop\" | \"length\" | \"content-filter\" | \"tool-calls\" | \"error\" | \"other\";\n\n/**\n * Request passed to a configured model provider.\n *\n * @remarks\n * This is the low-level researcher escape hatch for provider adapters. It is\n * intentionally fetch/runtime neutral and does not depend on Node-only APIs,\n * mutable SDK state, or a specific provider package. Adapters can translate\n * `messages` and `temperature` directly into a Vercel AI SDK call while\n * preserving `metadata` for experiment labels, protocol state, replay ids, or\n * provider-specific request annotations.\n *\n * The metadata object must remain JSON-compatible because it is eligible for\n * inclusion in caller-managed traces and benchmark artifacts.\n *\n * @example\n * ```ts\n * const response = await generateText({\n * model,\n * messages: request.messages,\n * temperature: request.temperature\n * });\n * ```\n */\nexport interface ModelRequest {\n /** Ordered chat messages for the next model call. */\n readonly messages: readonly ModelMessage[];\n /** Sampling temperature selected from the tier or caller override. */\n readonly temperature: number;\n /** Optional cancellation signal passed through to fetch-based model adapters. */\n readonly signal?: AbortSignal;\n /** Serializable protocol metadata for tracing and provider adapters. */\n readonly metadata: JsonObject;\n}\n\n/**\n * Response returned by a configured model provider.\n *\n * @remarks\n * Provider adapters return only the text Dogpile should feed back into the\n * active protocol plus optional usage/cost telemetry. Keeping the response\n * small makes deterministic fixtures and cross-runtime adapters easy to write.\n * When the upstream provider cannot report usage or price, omit those fields\n * rather than inventing non-replayable side data.\n */\nexport interface ModelResponse {\n /** Generated text used by the active coordination protocol. */\n readonly text: string;\n /** Optional provider-normalized finish reason for the model call. */\n readonly finishReason?: ModelFinishReason;\n /**\n * Optional provider-neutral runtime tool requests produced by the model adapter.\n *\n * @remarks\n * Adapters that translate Vercel AI SDK tool calls can return normalized\n * requests here. First-party protocols execute them through the shared\n * runtime tool executor and emit matched `tool-call` / `tool-result` events\n * without coupling core to a provider-specific tool-call shape.\n */\n readonly toolRequests?: readonly RuntimeToolExecutionRequest[];\n /** Optional provider-reported token usage. */\n readonly usage?: {\n /** Input tokens consumed by the model call. */\n readonly inputTokens: number;\n /** Output tokens generated by the model call. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n };\n /** Optional provider-reported or adapter-estimated cost in US dollars. */\n readonly costUsd?: number;\n /** Optional provider-adapter metadata normalized to JSON-compatible data. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Version tag for the replay trace artifact schema.\n */\nexport type ReplayTraceSchemaVersion = \"1.0\";\n\n/**\n * Serializable seed metadata recorded with replay traces.\n *\n * @remarks\n * Most providers do not expose deterministic seed control. Dogpile still\n * records an explicit empty seed artifact so replay consumers can distinguish\n * \"no seed supplied\" from a missing trace field.\n */\nexport interface ReplayTraceSeed {\n /** Seed artifact discriminant. */\n readonly kind: \"replay-trace-seed\";\n /** Seed source visible to replay tooling. */\n readonly source: \"caller\" | \"none\";\n /** Caller-supplied seed value, or `null` when no seed was supplied. */\n readonly value: string | number | null;\n}\n\n/**\n * Normalized run inputs persisted inside the replay trace artifact.\n */\nexport interface ReplayTraceRunInputs {\n /** Run input artifact discriminant. */\n readonly kind: \"replay-trace-run-inputs\";\n /** Mission or intent supplied by the caller. */\n readonly intent: string;\n /** Exact normalized protocol config used for execution. */\n readonly protocol: ProtocolConfig;\n /** Selected cost/quality tier. */\n readonly tier: Tier;\n /** Configured model provider id. */\n readonly modelProviderId: string;\n /** Concrete agent roster visible to the protocol. */\n readonly agents: readonly AgentSpec[];\n /** Temperature supplied to provider requests. */\n readonly temperature: number;\n}\n\n/**\n * Budget and stop-policy artifact persisted inside replay traces.\n */\nexport interface ReplayTraceBudget {\n /** Budget artifact discriminant. */\n readonly kind: \"replay-trace-budget\";\n /** Selected cost/quality tier. */\n readonly tier: Tier;\n /** Optional hard caps supplied by the caller. */\n readonly caps?: Omit<Budget, \"tier\">;\n /** Optional composable termination policy used by the protocol. */\n readonly termination?: TerminationCondition;\n}\n\n/**\n * Budget state snapshot derived from a cost-bearing trace event.\n *\n * @remarks\n * Replay consumers can inspect this artifact without walking the full event\n * log. Entries are emitted for model-turn accounting changes, coordination\n * barriers that expose cumulative cost, budget stops, and final completion.\n */\nexport interface ReplayTraceBudgetStateChange {\n /** Budget state artifact discriminant. */\n readonly kind: \"replay-trace-budget-state-change\";\n /** Zero-based event index that exposed this budget state. */\n readonly eventIndex: number;\n /** Source event type for the budget state. */\n readonly eventType: \"agent-turn\" | \"broadcast\" | \"budget-stop\" | \"final\";\n /** ISO-8601 timestamp from the source event. */\n readonly at: string;\n /** Cumulative cost visible at this point in the run. */\n readonly cost: CostSummary;\n /** Completed model-turn iteration count when known. */\n readonly iteration?: number;\n /** Elapsed runtime in milliseconds when known. */\n readonly elapsedMs?: number;\n /** Budget stop reason when this state records a halt. */\n readonly budgetReason?: BudgetStopReason;\n}\n\n/**\n * Provider-neutral protocol decision kinds recorded for replay.\n */\nexport type ReplayTraceProtocolDecisionType =\n | \"assign-role\"\n | \"select-agent-turn\"\n | \"start-model-call\"\n | \"complete-model-call\"\n | \"observe-model-output\"\n | \"start-tool-call\"\n | \"complete-tool-call\"\n | \"collect-broadcast-round\"\n | \"stop-for-budget\"\n | \"finalize-output\";\n\n/**\n * Protocol-level decision appended during execution.\n */\nexport interface ReplayTraceProtocolDecision {\n /** Decision artifact discriminant. */\n readonly kind: \"replay-trace-protocol-decision\";\n /** Zero-based event index that produced this decision. */\n readonly eventIndex: number;\n /** Event type that records the decision. */\n readonly eventType: RunEvent[\"type\"];\n /** Coordination protocol that made the decision. */\n readonly protocol: Protocol;\n /** Provider-neutral decision kind for replay tooling. */\n readonly decision: ReplayTraceProtocolDecisionType;\n /** ISO-8601 timestamp from the source event. */\n readonly at: string;\n /** Agent involved in the decision, when agent-scoped. */\n readonly agentId?: string;\n /** Role involved in the decision, when agent-scoped. */\n readonly role?: string;\n /** Provider call involved in the decision, when model-scoped. */\n readonly callId?: string;\n /** Provider involved in the decision, when model-scoped. */\n readonly providerId?: string;\n /** Tool call involved in the decision, when tool-scoped. */\n readonly toolCallId?: string;\n /** Tool identity involved in the decision, when tool-scoped. */\n readonly tool?: RuntimeToolIdentity;\n /** One-based protocol turn for turn-scoped decisions. */\n readonly turn?: number;\n /** Coordinator phase for coordinator protocol turn decisions. */\n readonly phase?: \"plan\" | \"worker\" | \"final-synthesis\";\n /** One-based broadcast round for grouped broadcast decisions. */\n readonly round?: number;\n /** Number of transcript entries visible after this decision. */\n readonly transcriptEntryCount?: number;\n /** Number of contributions collected at a broadcast barrier. */\n readonly contributionCount?: number;\n /** Prompt/input associated with turn decisions. */\n readonly input?: string;\n /** Output associated with turn or final decisions. */\n readonly output?: string;\n /** Cumulative cost visible at this decision point. */\n readonly cost?: CostSummary;\n /** Normalized budget stop reason for budget-stop decisions. */\n readonly budgetReason?: BudgetStopReason;\n}\n\n/**\n * Provider call metadata and response captured for replay inspection.\n */\nexport interface ReplayTraceProviderCall {\n /** Provider call artifact discriminant. */\n readonly kind: \"replay-trace-provider-call\";\n /** Stable call id within the run. */\n readonly callId: string;\n /** Configured model provider id. */\n readonly providerId: string;\n /** ISO-8601 timestamp before the provider call started. */\n readonly startedAt: string;\n /** ISO-8601 timestamp after the provider call completed. */\n readonly completedAt: string;\n /** Agent that requested this provider call. */\n readonly agentId: string;\n /** Role that requested this provider call. */\n readonly role: string;\n /** Request handed to the configured model provider. */\n readonly request: ModelRequest;\n /** Response returned by the configured model provider. */\n readonly response: ModelResponse;\n}\n\n/**\n * Final output artifact persisted inside replay traces.\n */\nexport interface ReplayTraceFinalOutput {\n /** Final output artifact discriminant. */\n readonly kind: \"replay-trace-final-output\";\n /** Final synthesized output returned by the run. */\n readonly output: string;\n /** Total cost at completion. */\n readonly cost: CostSummary;\n /** ISO-8601 completion timestamp from the terminal event. */\n readonly completedAt: string;\n /** Link to the completed transcript artifact. */\n readonly transcript: TranscriptLink;\n}\n\n/**\n * Incremental text produced by a streaming model provider.\n *\n * @remarks\n * Providers that can surface partial model output should implement\n * {@link ConfiguredModelProvider.stream}. Dogpile concatenates `text` chunks\n * into the completed {@link ModelResponse.text} for transcript and final\n * result compatibility while emitting each chunk as a typed stream/trace event.\n *\n * Usage and cost are optional on chunks because many provider SDKs only expose\n * them at stream completion. When supplied, the last observed usage/cost values\n * are used for the completed model turn.\n */\nexport interface ModelOutputChunk {\n /** Text delta produced by the provider. */\n readonly text: string;\n /** Optional provider-normalized finish reason surfaced on a final chunk. */\n readonly finishReason?: ModelResponse[\"finishReason\"];\n /** Optional provider-neutral runtime tool requests surfaced on a final chunk. */\n readonly toolRequests?: ModelResponse[\"toolRequests\"];\n /** Optional provider-reported token usage for the stream so far or final chunk. */\n readonly usage?: ModelResponse[\"usage\"];\n /** Optional provider-reported or adapter-estimated cost in US dollars. */\n readonly costUsd?: number;\n /** Optional provider-adapter metadata normalized to JSON-compatible data. */\n readonly metadata?: ModelResponse[\"metadata\"];\n}\n\n/**\n * Runtime-neutral model provider configured by the caller.\n *\n * @remarks\n * This is the primary model-extension point. Production adapters can wrap\n * Vercel AI SDK models behind this interface while tests can provide\n * deterministic providers for replayable protocol checks.\n *\n * Implementations should be pure TypeScript and fetch-compatible for Node LTS,\n * Bun, and browser ESM runtimes. Do not assume filesystem access,\n * process globals, or SDK-managed session storage.\n *\n * @example\n * ```ts\n * const provider: ConfiguredModelProvider = {\n * id: \"vercel-ai:model-name\",\n * async generate(request) {\n * const result = await generateText({\n * model,\n * messages: request.messages,\n * temperature: request.temperature\n * });\n *\n * return { text: result.text };\n * }\n * };\n * ```\n */\nexport interface ConfiguredModelProvider {\n /** Stable provider id recorded in traces. */\n readonly id: string;\n /** Generate a response for one protocol-managed model request. */\n generate(request: ModelRequest): Promise<ModelResponse>;\n /**\n * Optionally stream response text for one protocol-managed model request.\n *\n * When present, protocol execution consumes this stream directly and emits\n * `model-output-chunk` events before the completed `agent-turn` event. The\n * fallback `generate()` method remains required for adapters that do not\n * support incremental output and for callers that prefer batch execution.\n */\n stream?(request: ModelRequest): AsyncIterable<ModelOutputChunk>;\n}\n\n/**\n * Stable identity for a runtime tool available to protocol execution.\n *\n * @remarks\n * Tool identity is protocol-agnostic: the same tool can be made visible to\n * coordinator, sequential, broadcast, or shared runs. `id` is the canonical\n * trace key and should remain stable across releases when replay fixtures\n * depend on it. `namespace` and `version` let applications distinguish\n * similarly named tools without baking provider or runtime details into core.\n */\nexport interface RuntimeToolIdentity {\n /** Stable tool id written into tool calls, results, and trace artifacts. */\n readonly id: string;\n /** Human-readable tool name suitable for model-visible descriptions. */\n readonly name: string;\n /** Optional package, product, or caller-owned namespace. */\n readonly namespace?: string;\n /** Optional semantic version or caller-managed revision label. */\n readonly version?: string;\n /** Optional model-visible description of what the tool does. */\n readonly description?: string;\n}\n\n/**\n * Protocol-agnostic input schema for a runtime tool.\n *\n * @remarks\n * Dogpile keeps the schema as JSON-compatible data so callers can translate it\n * into Vercel AI SDK tool definitions, provider-specific function calling, or\n * custom researcher harnesses without importing Node-only validators. The\n * schema should describe a JSON object input; tool execution receives that\n * object as the typed `input` argument.\n */\nexport interface RuntimeToolInputSchema {\n /** Schema discriminant for future schema families. */\n readonly kind: \"json-schema\";\n /** JSON Schema-compatible object describing the tool input. */\n readonly schema: JsonObject;\n /** Optional human-readable input description. */\n readonly description?: string;\n}\n\n/**\n * Immutable trace snapshot visible to a runtime tool during execution.\n *\n * @remarks\n * The snapshot is intentionally read-only and serializable. Tools can inspect\n * coordination history without mutating SDK state or depending on storage.\n */\nexport interface RuntimeToolTraceContext {\n /** Ordered coordination events emitted before this tool execution. */\n readonly events: readonly RunEvent[];\n /** Ordered transcript entries completed before this tool execution. */\n readonly transcript: readonly TranscriptEntry[];\n}\n\n/**\n * Protocol-agnostic execution context passed to runtime tools.\n *\n * @remarks\n * The context gives a tool the active run identity, protocol, tier, optional\n * agent/turn labels, and a read-only trace snapshot. The optional\n * `abortSignal` is runtime-neutral across modern JS runtimes and lets budget\n * or timeout policy cancel long-running fetch-based tools without requiring\n * Node-only APIs.\n */\nexport interface RuntimeToolExecutionContext {\n /** Stable id for the workflow run that requested the tool. */\n readonly runId: string;\n /** Stable id for this individual tool call. */\n readonly toolCallId: string;\n /** Coordination protocol currently executing. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Agent that requested the tool, when execution is agent-scoped. */\n readonly agentId?: string;\n /** Model-visible role of the requesting agent, when available. */\n readonly role?: string;\n /** One-based protocol turn index, when execution is turn-scoped. */\n readonly turn?: number;\n /** Read-only serializable trace state visible at the call boundary. */\n readonly trace?: RuntimeToolTraceContext;\n /** Optional cancellation signal for fetch-based tool implementations. */\n readonly abortSignal?: AbortSignal;\n /** Additional caller-owned serializable execution metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Protocol-neutral request to execute one runtime tool.\n *\n * @remarks\n * First-party protocols use this shape instead of protocol-specific tool call\n * objects. The input and metadata are JSON-compatible so the request-side\n * event can be persisted for caller-managed replay, while `abortSignal`\n * remains an execution-only control for portable fetch-based adapters.\n */\nexport interface RuntimeToolExecutionRequest {\n /** Stable tool id from {@link RuntimeToolIdentity.id}. */\n readonly toolId: string;\n /** Optional caller-supplied call id; generated by the executor when omitted. */\n readonly toolCallId?: string;\n /** JSON-serializable tool input. */\n readonly input: JsonObject;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Model-visible role of the requesting agent, when available. */\n readonly role?: string;\n /** One-based protocol turn index, when execution is turn-scoped. */\n readonly turn?: number;\n /** Optional cancellation signal for this call. */\n readonly abortSignal?: AbortSignal;\n /** Additional caller-owned serializable request metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared protocol-agnostic tool executor used by first-party protocol runners.\n */\nexport interface RuntimeToolExecutor {\n /** Runtime tools available to the active protocol run. */\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Execute one normalized tool request and emit matching tool events. */\n execute(request: RuntimeToolExecutionRequest): Promise<RuntimeToolResult>;\n}\n\n/**\n * JSON-serializable runtime tool error shape.\n *\n * @remarks\n * Tool errors are data, not thrown values, at the public boundary. Adapters may\n * still throw internally, but protocol code should normalize failures into\n * this shape before writing traces so failed tool calls remain replayable.\n */\nexport interface RuntimeToolError {\n /** Machine-readable error code, for example `timeout` or `invalid-input`. */\n readonly code: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Whether the same call may be retried safely by caller policy. */\n readonly retryable?: boolean;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Successful runtime tool execution result.\n */\nexport interface RuntimeToolSuccessResult<Output = JsonValue> {\n /** Result discriminant for exhaustive tool-result handling. */\n readonly type: \"success\";\n /** Stable id matching the execution context call id. */\n readonly toolCallId: string;\n /** Tool identity that produced the result. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool output. */\n readonly output: Output;\n /** Optional serializable result metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Failed runtime tool execution result.\n */\nexport interface RuntimeToolErrorResult {\n /** Result discriminant for exhaustive tool-result handling. */\n readonly type: \"error\";\n /** Stable id matching the execution context call id. */\n readonly toolCallId: string;\n /** Tool identity that produced the error. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable normalized error. */\n readonly error: RuntimeToolError;\n /** Optional serializable result metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Runtime tool result union shared by every coordination protocol.\n */\nexport type RuntimeToolResult<Output = JsonValue> =\n | RuntimeToolSuccessResult<Output>\n | RuntimeToolErrorResult;\n\n/**\n * Tool call/result pair preserved on the transcript entry for the model turn\n * that requested it.\n */\nexport interface TranscriptToolCall {\n /** Stable id shared by the request event and result payload. */\n readonly toolCallId: string;\n /** Tool identity selected for execution. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool input requested by the model/provider adapter. */\n readonly input: JsonObject;\n /** Normalized JSON-serializable tool result returned by the runtime tool. */\n readonly result: RuntimeToolResult;\n}\n\n/**\n * Protocol-agnostic runtime tool definition.\n *\n * @remarks\n * This is the low-level tool escape hatch used by applications and research\n * harnesses. Core owns the orchestration context and serializable result\n * contract; callers own the actual implementation and any fetch-based I/O the\n * tool performs. `inputSchema` is the model-visible JSON contract; optional\n * `validateInput` is the adapter-owned runtime check applied immediately before\n * `execute`.\n */\nexport interface RuntimeTool<Input extends object = JsonObject, Output = JsonValue> {\n /** Stable identity and model-visible description. */\n readonly identity: RuntimeToolIdentity;\n /** JSON-compatible schema for the object input expected by `execute`. */\n readonly inputSchema: RuntimeToolInputSchema;\n /** Optional permissions the adapter needs from caller policy before execution. */\n readonly permissions?: readonly RuntimeToolPermission[];\n /**\n * Optional adapter-owned input validation hook evaluated before execution.\n *\n * @remarks\n * Dogpile validates that this property is callable at registration time.\n * During a tool call, Dogpile invokes it after the `tool-call` event and\n * before `execute`. Returning `{ type: \"invalid\", issues }` prevents\n * `execute` from running and produces a `RuntimeToolErrorResult` with\n * `error.code: \"invalid-input\"` and serializable issue details. Use this\n * hook for deterministic, side-effect-free runtime checks that narrow the\n * JSON input before the tool performs I/O.\n */\n validateInput?(input: Readonly<Input>): RuntimeToolValidationResult;\n /** Execute the tool for one protocol-managed call. */\n execute(\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext\n ): RuntimeToolResult<Output> | Promise<RuntimeToolResult<Output>>;\n}\n\n/**\n * Permission declaration for tool adapters.\n *\n * @remarks\n * Permissions are declarative and serializable. Dogpile core does not grant\n * capabilities itself; applications and protocol harnesses can inspect this\n * data before exposing tools to model-driven execution.\n */\nexport type RuntimeToolPermission =\n | RuntimeToolNetworkPermission\n | RuntimeToolCodeExecutionPermission\n | RuntimeToolCustomPermission;\n\n/**\n * Permission declaration for fetch-compatible network access.\n */\nexport interface RuntimeToolNetworkPermission {\n /** Permission discriminant. */\n readonly kind: \"network\";\n /** Optional host allowlist expected by the adapter. */\n readonly allowHosts?: readonly string[];\n /** Whether private-network destinations may be reached. */\n readonly allowPrivateNetwork?: boolean;\n}\n\n/**\n * Permission declaration for caller-owned code execution sandboxes.\n */\nexport interface RuntimeToolCodeExecutionPermission {\n /** Permission discriminant. */\n readonly kind: \"code-execution\";\n /** Sandbox boundary supplied by the caller or host application. */\n readonly sandbox: \"caller-provided\" | \"none\";\n /** Optional language allowlist exposed by the adapter. */\n readonly languages?: readonly string[];\n /** Whether executed code may perform network I/O inside the sandbox. */\n readonly allowNetwork?: boolean;\n}\n\n/**\n * Permission declaration for adapter-specific capabilities.\n */\nexport interface RuntimeToolCustomPermission {\n /** Permission discriminant. */\n readonly kind: \"custom\";\n /** Stable custom permission name. */\n readonly name: string;\n /** Optional human-readable policy note for caller-owned authorization checks. */\n readonly description?: string;\n /** Optional serializable policy metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared validation issue emitted before a tool adapter executes.\n */\nexport interface RuntimeToolValidationIssue {\n /** Machine-readable validation code. */\n readonly code: \"invalid-type\" | \"missing-field\" | \"invalid-value\" | \"out-of-range\";\n /** Dot-path or field name that failed validation. */\n readonly path: string;\n /** Human-readable validation message. */\n readonly message: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Shared validation result for adapter input checks.\n */\nexport type RuntimeToolValidationResult =\n | RuntimeToolValidationValidResult\n | RuntimeToolValidationInvalidResult;\n\n/**\n * Valid adapter input.\n */\nexport interface RuntimeToolValidationValidResult {\n /** Validation discriminant. */\n readonly type: \"valid\";\n}\n\n/**\n * Invalid adapter input.\n */\nexport interface RuntimeToolValidationInvalidResult {\n /** Validation discriminant. */\n readonly type: \"invalid\";\n /** One or more serializable validation issues. */\n readonly issues: readonly RuntimeToolValidationIssue[];\n}\n\n/**\n * Common adapter error codes used by built-in and third-party tools.\n */\nexport type RuntimeToolAdapterErrorCode =\n | \"invalid-input\"\n | \"permission-denied\"\n | \"timeout\"\n | \"aborted\"\n | \"unavailable\"\n | \"backend-error\"\n | \"unknown\";\n\n/**\n * Normalized adapter error data.\n */\nexport interface RuntimeToolAdapterError extends RuntimeToolError {\n /** Common machine-readable adapter error code. */\n readonly code: RuntimeToolAdapterErrorCode;\n}\n\n/**\n * Shared adapter contract implemented by built-in adapters and low-level tools.\n */\nexport interface RuntimeToolAdapterContract<Input extends object = JsonObject, Output = JsonValue>\n extends RuntimeTool<Input, Output> {\n /** Permissions required before this adapter should be exposed or executed. */\n readonly permissions: readonly RuntimeToolPermission[];\n /** Adapter-owned input validation hook. */\n validateInput(input: Readonly<Input>): RuntimeToolValidationResult;\n}\n\n/**\n * Required output artifact for a benchmark task.\n */\nexport interface BenchmarkRequiredArtifact {\n /** Stable artifact name used by scorers and reports. */\n readonly name: string;\n /** Fixture-defined artifact shape, for example `enum` or `markdown_table`. */\n readonly type: string;\n /** Optional human-readable artifact requirement. */\n readonly description?: string;\n /** Optional allowed values for constrained artifacts. */\n readonly allowedValues?: readonly string[];\n}\n\n/**\n * Serializable task input shared by benchmark protocol runners.\n */\nexport interface BenchmarkTaskInput {\n /** Stable benchmark task id. */\n readonly id: string;\n /** Mission text supplied to protocol runners. */\n readonly intent: string;\n /** Optional task title for reports. */\n readonly title?: string;\n /** Optional benchmark difficulty or paper task level, such as `L3`. */\n readonly level?: string;\n /** Required artifacts the run output must contain. */\n readonly requiredArtifacts?: readonly BenchmarkRequiredArtifact[];\n /** Serializable scoring rubric or fixture-specific judging metadata. */\n readonly rubric?: JsonObject;\n /** Additional serializable fixture metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Benchmark budget controls shared by all protocol runners in one comparison.\n */\nexport interface BenchmarkBudget {\n /** Named cost/quality tier selected for the benchmark run. */\n readonly tier: Tier;\n /** Optional maximum spend in US dollars. */\n readonly maxUsd?: number;\n /** Optional maximum input token count. */\n readonly maxInputTokens?: number;\n /** Optional maximum output token count. */\n readonly maxOutputTokens?: number;\n /** Optional maximum total token count. */\n readonly maxTotalTokens?: number;\n /** Optional quality preference in the inclusive range `0..1`. */\n readonly qualityWeight?: number;\n}\n\n/**\n * Benchmark model settings shared across protocol runners.\n *\n * @remarks\n * Research and reproduction workflows use this object to hold provider\n * settings constant while changing only the coordination protocol. The\n * `metadata` field is for serializable experiment labels such as corpus id,\n * prompt template version, model family, or paper reproduction condition.\n */\nexport interface BenchmarkModelSettings {\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly provider: ConfiguredModelProvider;\n /** Optional fixed temperature for controlled reproduction runs. */\n readonly temperature?: number;\n /** Optional deterministic seed recorded for provider adapters that support it. */\n readonly seed?: number;\n /** Additional serializable provider or run metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared benchmark runner configuration before selecting a protocol.\n *\n * @remarks\n * This contract carries the task input, budget policy, and model settings that\n * must stay constant when comparing multiple coordination protocols. It is the\n * researcher-facing escape hatch for paper-faithfulness checks: callers can\n * project one task into Sequential, Broadcast, Shared, and Coordinator runs\n * while preserving the same agents, tier, caps, model, and fixture metadata.\n *\n * The object is intentionally JSON-adjacent and storage-free. Persist benchmark\n * inputs, run manifests, and traces in caller-owned systems.\n */\nexport interface BenchmarkRunnerConfig {\n /** Serializable benchmark task input. */\n readonly task: BenchmarkTaskInput;\n /** Shared budget and cap policy. */\n readonly budget: BenchmarkBudget;\n /** Shared model provider and generation settings. */\n readonly model: BenchmarkModelSettings;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Additional serializable benchmark metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Benchmark configuration for one concrete protocol runner invocation.\n *\n * @remarks\n * Use this derived shape after selecting the protocol under test. It preserves\n * the shared benchmark controls from {@link BenchmarkRunnerConfig} and adds a\n * named or explicit {@link ProtocolConfig}, which lets reproduction code tune\n * protocol-native parameters without widening the high-level API.\n */\nexport interface ProtocolBenchmarkRunConfig extends BenchmarkRunnerConfig {\n /** Protocol being evaluated under the shared benchmark settings. */\n readonly protocol: Protocol | ProtocolConfig;\n}\n\n/**\n * Serializable benchmark protocol descriptor persisted with run artifacts.\n *\n * @remarks\n * Benchmark artifacts record both the normalized protocol name and the exact\n * caller-supplied protocol config so a reproduction harness can distinguish\n * `\"sequential\"` defaults from `{ kind: \"sequential\", maxTurns: 4 }`.\n */\nexport interface BenchmarkProtocolArtifact {\n /** Normalized protocol name used for comparison grouping. */\n readonly kind: Protocol;\n /** Exact protocol value supplied to the runner. */\n readonly config: Protocol | ProtocolConfig;\n}\n\n/**\n * Reproducibility metadata persisted with every benchmark run artifact.\n *\n * @remarks\n * This shape intentionally stores provider identity and serializable model\n * settings, but not the provider implementation itself. Callers own provider\n * construction and external storage; Dogpile owns the portable artifact shape.\n */\nexport interface BenchmarkReproducibilityArtifact {\n /** Benchmark task input used for this run. */\n readonly task: BenchmarkTaskInput;\n /** Shared budget and cap policy used for this run. */\n readonly budget: BenchmarkBudget;\n /** Protocol selected for this run. */\n readonly protocol: BenchmarkProtocolArtifact;\n /** Provider id recorded from the configured model. */\n readonly modelProviderId: string;\n /** Optional fixed temperature used for the run. */\n readonly temperature?: number;\n /** Optional deterministic seed recorded for provider adapters that support it. */\n readonly seed?: number;\n /** Additional serializable provider or run metadata. */\n readonly modelMetadata?: JsonObject;\n /** Concrete agent roster used for the run. */\n readonly agents: readonly AgentSpec[];\n /** Additional serializable benchmark metadata. */\n readonly benchmarkMetadata?: JsonObject;\n}\n\n/**\n * Cost and budget metadata recorded for one benchmark run.\n *\n * @remarks\n * This accounting block is intentionally duplicated from the run result and\n * benchmark controls so benchmark reports can group, filter, and audit spend\n * without unpacking the full trace or reproduction object. Utilization fields\n * are only present when the corresponding cap was configured.\n */\nexport interface BenchmarkCostAccounting {\n /** Accounting artifact discriminant for future benchmark metadata unions. */\n readonly kind: \"benchmark-cost-accounting\";\n /** Named budget/cost tier selected for this benchmark run. */\n readonly tier: Tier;\n /** Shared benchmark budget and cap policy used for this run. */\n readonly budget: BenchmarkBudget;\n /** Total token and spend accounting observed for this run. */\n readonly cost: CostSummary;\n /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */\n readonly usdCapUtilization?: number;\n /** Fraction of the configured total-token cap consumed, when `maxTotalTokens` is present. */\n readonly totalTokenCapUtilization?: number;\n}\n\n/**\n * Structured streaming event log captured for one benchmark run.\n *\n * @remarks\n * Benchmark artifacts keep this log beside the full trace so reproduction\n * harnesses can inspect exactly what the streaming API yielded during the run\n * without unpacking unrelated trace metadata. The `events` array must match\n * `trace.events` for completed runs.\n */\nexport interface BenchmarkStreamingEventLog {\n /** Event-log discriminant for future benchmark observability artifacts. */\n readonly kind: \"benchmark-streaming-event-log\";\n /** Stable run id shared by the benchmark artifact and trace. */\n readonly runId: string;\n /** Protocol whose streaming events were captured. */\n readonly protocol: Protocol;\n /** Ordered event kinds for compact coverage checks. */\n readonly eventTypes: readonly RunEvent[\"type\"][];\n /** Number of streaming events captured. */\n readonly eventCount: number;\n /** Complete ordered streaming events yielded by the run. */\n readonly events: readonly RunEvent[];\n}\n\n/**\n * Serializable score persisted for one protocol benchmark artifact.\n *\n * @remarks\n * The score is protocol-scoped because paper reproduction reports compare the\n * same task across protocol variants. When a judge supplies\n * {@link RunResult.quality}, the benchmark score records that value on a\n * 0..100 scale. Otherwise Dogpile computes a conservative artifact-completeness\n * score from the captured output, transcript, streaming event log, and budget\n * accounting so unjudged benchmark artifacts still carry an auditable score\n * derived from stored data.\n */\nexport interface BenchmarkProtocolScore {\n /** Score artifact discriminant for future benchmark scoring variants. */\n readonly kind: \"benchmark-protocol-score\";\n /** Protocol this score belongs to. */\n readonly protocol: Protocol;\n /** Score in the inclusive range `0..100`. */\n readonly score: number;\n /** Normalized score in the inclusive range `0..1`. */\n readonly normalizedScore: number;\n /** Maximum score for the current scoring scale. */\n readonly maxScore: 100;\n /** How the score was derived. */\n readonly source: \"run-quality\" | \"artifact-completeness\";\n /** Compact scoring dimensions used to compute the stored score. */\n readonly dimensions: readonly BenchmarkScoreDimension[];\n}\n\n/**\n * One serializable dimension contributing to a benchmark protocol score.\n */\nexport interface BenchmarkScoreDimension {\n /** Stable dimension name for reports. */\n readonly name: string;\n /** Earned points for this dimension. */\n readonly score: number;\n /** Maximum points available for this dimension. */\n readonly maxScore: number;\n}\n\n/**\n * Reproducible benchmark output artifact for one protocol run.\n *\n * @remarks\n * This is the storage-free persistence contract for reproduction workflows:\n * callers can write the object to JSON, NDJSON, object storage, or a database\n * without Dogpile depending on Node-only filesystem APIs. It contains the final\n * output, full transcript, a structured streaming event log, full trace, cost\n * summary, and all serializable controls needed to replay the run in\n * caller-managed infrastructure.\n */\nexport interface BenchmarkRunArtifact {\n /** Artifact discriminant for future benchmark artifact unions. */\n readonly kind: \"benchmark-run\";\n /** Schema version for reproducible artifact consumers. */\n readonly schemaVersion: \"1.0\";\n /** Stable run id from the trace. */\n readonly runId: string;\n /** ISO-8601 timestamp derived from the first trace event when available. */\n readonly startedAt: string;\n /** ISO-8601 timestamp derived from the final trace event when available. */\n readonly completedAt: string;\n /** Reproduction controls and serializable fixture inputs. */\n readonly reproducibility: BenchmarkReproducibilityArtifact;\n /** Final output produced by the protocol. */\n readonly output: string;\n /** Complete normalized transcript for this run. */\n readonly transcript: readonly TranscriptEntry[];\n /** Structured streaming event log captured for this benchmark run. */\n readonly eventLog: BenchmarkStreamingEventLog;\n /** Full serializable event log and trace for this run. */\n readonly trace: Trace;\n /** Cost, tier, and benchmark budget metadata for this run. */\n readonly accounting: BenchmarkCostAccounting;\n /** Per-protocol benchmark score computed from the captured artifact data. */\n readonly score: BenchmarkProtocolScore;\n /** Total token and spend accounting for this run. */\n readonly cost: CostSummary;\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly quality?: number;\n}\n\n/**\n * Event emitted when a protocol assigns or records an agent role.\n *\n * @remarks\n * This event normally appears near the beginning of a run and establishes the\n * `agentId`/`role` pair that later turn and transcript records refer to. A\n * renderer can use it to build the participant roster before model output\n * starts streaming.\n *\n * Payload shape:\n *\n * - `type`: always `role-assignment`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the assignment was emitted.\n * - `agentId`: stable agent id used in events, trace, and transcript entries.\n * - `role`: model-visible role or perspective assigned to that agent.\n */\nexport interface RoleAssignmentEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"role-assignment\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent receiving the role assignment. */\n readonly agentId: string;\n /** Role assigned to the agent. */\n readonly role: string;\n}\n\n/**\n * Event emitted when Dogpile is about to ask the configured model provider for\n * one protocol-managed response.\n *\n * @remarks\n * This event is the request-side model activity counterpart to\n * {@link ModelResponseEvent}. Protocol implementations may omit it when they\n * only expose completed turns, but adapters and researcher harnesses can emit\n * it to make provider calls visible in the same streaming event log as agent\n * turns and final output.\n */\nexport interface ModelRequestEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-request\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable provider call id within the run. */\n readonly callId: string;\n /** Configured model provider id receiving the request. */\n readonly providerId: string;\n /** Agent requesting the model call. */\n readonly agentId: string;\n /** Agent role for the active model call. */\n readonly role: string;\n /** Provider-neutral request handed to the model adapter. */\n readonly request: ModelRequest;\n}\n\n/**\n * Event emitted after the configured model provider returns one response.\n *\n * @remarks\n * This event records provider-level model activity without forcing callers to\n * infer it from the higher-level {@link TurnEvent}. The response is the same\n * provider-neutral shape captured in replay traces, so it remains portable and\n * JSON-serializable across Node LTS, Bun, and browser ESM runtimes.\n */\nexport interface ModelResponseEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-response\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable provider call id within the run. */\n readonly callId: string;\n /** Configured model provider id that produced the response. */\n readonly providerId: string;\n /** Agent that requested the model call. */\n readonly agentId: string;\n /** Agent role for the completed model call. */\n readonly role: string;\n /** Provider-neutral response returned by the model adapter. */\n readonly response: ModelResponse;\n}\n\n/**\n * Event emitted while a model turn is still generating text.\n *\n * @remarks\n * `model-output-chunk` lets streaming callers render provider output before\n * the protocol has enough information to commit the completed `agent-turn`\n * transcript entry. It is emitted only when the configured model provider\n * implements {@link ConfiguredModelProvider.stream}; non-streaming providers\n * continue to produce the existing role/turn/final event sequence.\n *\n * Payload shape:\n *\n * - `type`: always `model-output-chunk`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the chunk was observed.\n * - `agentId` and `role`: identify the active generating agent.\n * - `input`: prompt text visible to that agent for this turn.\n * - `chunkIndex`: zero-based chunk index within this model turn.\n * - `text`: text delta from the provider.\n * - `output`: accumulated output for this turn after applying the chunk.\n */\nexport interface ModelOutputChunkEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-output-chunk\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent currently producing output. */\n readonly agentId: string;\n /** Agent role for the active turn. */\n readonly role: string;\n /** Prompt/input visible to the agent for this turn. */\n readonly input: string;\n /** Zero-based chunk index within the active model turn. */\n readonly chunkIndex: number;\n /** Text delta produced by the model provider. */\n readonly text: string;\n /** Accumulated output for this turn after applying this chunk. */\n readonly output: string;\n}\n\n/**\n * Event emitted when a runtime tool is invoked by protocol or model policy.\n *\n * @remarks\n * Tools are caller-owned escape hatches. This request-side event keeps tool\n * invocation observable without making Dogpile core depend on Node-only\n * capabilities, a storage layer, or a provider-specific function-call shape.\n */\nexport interface ToolCallEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"tool-call\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable tool call id within the run. */\n readonly toolCallId: string;\n /** Tool identity selected for execution. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool input. */\n readonly input: JsonObject;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Agent role that requested the tool, when available. */\n readonly role?: string;\n}\n\n/**\n * Event emitted after a runtime tool returns a normalized result.\n *\n * @remarks\n * Tool failures are data at the public boundary. The result payload uses the\n * same discriminated union as runtime tool adapters, allowing log consumers to\n * render successful outputs and normalized errors exhaustively.\n */\nexport interface ToolResultEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"tool-result\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable tool call id within the run. */\n readonly toolCallId: string;\n /** Tool identity that produced the result. */\n readonly tool: RuntimeToolIdentity;\n /** Normalized JSON-serializable tool result. */\n readonly result: RuntimeToolResult;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Agent role that requested the tool, when available. */\n readonly role?: string;\n}\n\n/**\n * Provider-normalized participation decision parsed from paper-style agent output.\n *\n * @remarks\n * Dogpile preserves the raw model text on transcript entries and events. When\n * a model emits the labeled fields `role_selected`, `participation`,\n * `rationale`, and `contribution`, protocols also attach this structured\n * metadata so reproduction harnesses can distinguish contribution from\n * voluntary abstention without reparsing raw text.\n */\nexport interface AgentDecision {\n /** Task-specific role selected by the agent for this turn. */\n readonly selectedRole: string;\n /** Whether the agent contributed or voluntarily abstained. */\n readonly participation: AgentParticipation;\n /** Agent-provided rationale for the selected role and participation choice. */\n readonly rationale: string;\n /** Agent-provided contribution text, or abstention explanation. */\n readonly contribution: string;\n}\n\n/**\n * Agent participation state for a paper-style turn decision.\n */\nexport type AgentParticipation = \"contribute\" | \"abstain\";\n\n/**\n * Event emitted after one agent contributes a model turn.\n *\n * @remarks\n * `agent-turn` is the primary streaming payload for sequential, coordinator,\n * shared-state, and broadcast executions. It captures the exact prompt/input\n * Dogpile supplied to the agent, the text returned by the model provider, and\n * the cumulative cost after applying that response.\n *\n * The corresponding durable transcript record contains the same\n * `agentId`/`role`/`input`/`output` contribution without event timing or cost\n * fields. Use this event for live progress UIs and the transcript for replay\n * or downstream application logic.\n *\n * Payload shape:\n *\n * - `type`: always `agent-turn`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the turn completed.\n * - `agentId` and `role`: identify the contributing agent.\n * - `input`: prompt text visible to that agent for this turn.\n * - `output`: generated model text produced by the agent.\n * - `cost`: cumulative token and spend accounting after this turn.\n */\nexport interface TurnEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"agent-turn\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent that produced this turn. */\n readonly agentId: string;\n /** Agent role for this turn. */\n readonly role: string;\n /** Prompt/input visible to the agent for this turn. */\n readonly input: string;\n /** Model output produced by the agent. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n /** Cumulative cost after this turn. */\n readonly cost: CostSummary;\n}\n\n/**\n * One independent contribution captured by a broadcast round event.\n *\n * @remarks\n * Broadcast protocols collect one contribution per participating agent before\n * synthesis. The contribution payload is intentionally smaller than\n * {@link TurnEvent}: it is a round-level summary of model outputs, while the\n * complete prompt/output pair for each agent is still available as individual\n * `agent-turn` events and {@link TranscriptEntry} records.\n *\n * Payload shape:\n *\n * - `agentId`: stable id of the contributing agent.\n * - `role`: model-visible role or perspective used for that contribution.\n * - `output`: generated text contributed independently for the round.\n */\nexport interface BroadcastContribution {\n /** Agent that produced the broadcast contribution. */\n readonly agentId: string;\n /** Agent role for the contribution. */\n readonly role: string;\n /** Independent model output produced for the shared mission. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n}\n\n/**\n * Event emitted after agents broadcast independent contributions for a round.\n *\n * @remarks\n * A `broadcast` event marks the coordination moment where independently\n * generated agent outputs are gathered for a shared round. It does not replace\n * per-agent `agent-turn` events; instead, it groups their outputs by round so\n * observers can render the broadcast barrier and replay the paper protocol's\n * independent-contribution step.\n *\n * Payload shape:\n *\n * - `type`: always `broadcast`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the round finished.\n * - `round`: one-based broadcast round number.\n * - `contributions`: independent outputs collected for this round.\n * - `cost`: cumulative token and spend accounting after the round.\n */\nexport interface BroadcastEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"broadcast\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** One-based broadcast round number. */\n readonly round: number;\n /** Independent contributions collected in this broadcast round. */\n readonly contributions: readonly BroadcastContribution[];\n /** Cumulative cost after this broadcast round. */\n readonly cost: CostSummary;\n}\n\n/**\n * Event emitted when a workflow halts because a configured budget cap fired.\n *\n * @remarks\n * `budget-stop` records the normalized cap class that stopped execution before\n * the final event closes the run. The detail object is JSON-serializable so\n * callers can persist or replay the exact cap, observed value, and limit.\n */\nexport interface BudgetStopEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"budget-stop\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Normalized machine-readable budget stop reason. */\n readonly reason: BudgetStopReason;\n /** Total cost at the stop point. */\n readonly cost: CostSummary;\n /** Completed model-turn iterations at the stop point. */\n readonly iteration: number;\n /** Elapsed runtime in milliseconds at the stop point. */\n readonly elapsedMs: number;\n /** Serializable cap diagnostics. */\n readonly detail: JsonObject;\n}\n\n/**\n * Link from a terminal event to the completed trace transcript.\n *\n * @remarks\n * Final events are emitted before callers await {@link StreamHandle.result},\n * so this compact link tells streaming UIs exactly which transcript artifact\n * the terminal output closes over without duplicating every transcript entry\n * inside the event log.\n */\nexport interface TranscriptLink {\n /** Discriminant for future transcript link variants. */\n readonly kind: \"trace-transcript\";\n /** Number of transcript entries included in the completed trace. */\n readonly entryCount: number;\n /** Zero-based index of the last transcript entry, or `null` for empty runs. */\n readonly lastEntryIndex: number | null;\n}\n\n/**\n * Event emitted when a workflow produces its final output.\n *\n * @remarks\n * `final` is the terminal streaming event for a successful run. Its `output`\n * value matches {@link RunResult.output}, and its `cost` value matches the\n * final aggregate cost returned on the result. Its `transcript` link points to\n * the completed {@link Trace.transcript} entries that produced the terminal\n * output.\n *\n * Payload shape:\n *\n * - `type`: always `final`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when final synthesis completed.\n * - `output`: final synthesized answer returned to the caller.\n * - `cost`: total token and spend accounting for the run.\n * - `transcript`: compact link to the completed trace transcript.\n */\nexport interface FinalEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"final\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Final synthesized answer returned as `RunResult.output`. */\n readonly output: string;\n /** Total cost at completion. */\n readonly cost: CostSummary;\n /** Link to the completed trace transcript. */\n readonly transcript: TranscriptLink;\n /** Optional normalized quality score supplied by a caller-owned evaluator. */\n readonly quality?: NormalizedQualityScore;\n /** Optional serializable evaluation payload supplied by a caller-owned evaluator. */\n readonly evaluation?: RunEvaluation;\n /** Termination condition that stopped the run, when the run ended by policy. */\n readonly termination?: TerminationStopRecord;\n}\n\n/**\n * Successful coordination event emitted by Dogpile and persisted in traces.\n *\n * @remarks\n * `RunEvent` is the discriminated union stored in {@link Trace.events} and\n * used by low-level protocol emit callbacks. Switch on `type` to handle each\n * coordination moment exhaustively:\n *\n * - `role-assignment`: participant/role roster was established.\n * - `model-request`: one provider-neutral model request was started.\n * - `model-response`: one provider-neutral model response completed.\n * - `model-output-chunk`: one streaming model text delta arrived.\n * - `tool-call`: one runtime tool invocation was started.\n * - `tool-result`: one runtime tool invocation completed.\n * - `agent-turn`: one agent completed a prompt/response turn.\n * - `broadcast`: a broadcast round gathered independent contributions.\n * - `budget-stop`: a configured budget cap halted further model turns.\n * - `final`: the run completed and produced the final output.\n *\n * Every variant is JSON-serializable and includes `runId` plus an ISO-8601\n * `at` timestamp so callers can persist, render, or replay the event log\n * without SDK-owned storage.\n *\n * @example\n * ```ts\n * for await (const event of Dogpile.stream(options)) {\n * switch (event.type) {\n * case \"agent-turn\":\n * console.log(event.agentId, event.output);\n * break;\n * case \"final\":\n * console.log(event.output);\n * break;\n * }\n * }\n * ```\n */\nexport type RunEvent =\n | RoleAssignmentEvent\n | ModelRequestEvent\n | ModelResponseEvent\n | ModelOutputChunkEvent\n | ToolCallEvent\n | ToolResultEvent\n | TurnEvent\n | BroadcastEvent\n | BudgetStopEvent\n | FinalEvent;\n\n/**\n * Model activity events yielded by `stream()` and persisted in traces when a\n * protocol exposes provider-call boundaries.\n */\nexport type ModelActivityEvent = ModelRequestEvent | ModelResponseEvent | ModelOutputChunkEvent;\n\n/**\n * Tool activity events yielded by `stream()` and persisted in traces when a\n * protocol or caller-owned adapter invokes runtime tools.\n */\nexport type ToolActivityEvent = ToolCallEvent | ToolResultEvent;\n\n/**\n * Lifecycle event yielded by `stream()`.\n *\n * These events describe workflow coordination state rather than model text.\n * Role assignment establishes the participant roster, while `budget-stop`\n * records a lifecycle halt before the terminal completion event.\n */\nexport type StreamLifecycleEvent = RoleAssignmentEvent | BudgetStopEvent;\n\n/**\n * Output event yielded by `stream()`.\n *\n * These events carry generated agent output or grouped round output while a\n * workflow is still running.\n */\nexport type StreamOutputEvent = ModelActivityEvent | ToolActivityEvent | TurnEvent | BroadcastEvent;\n\n/**\n * Error event yielded by `stream()` when execution rejects.\n *\n * @remarks\n * Stream errors are emitted before {@link StreamHandle.result} rejects so UIs\n * and log collectors can record a terminal failure without wrapping the result\n * promise. The error payload is JSON-serializable and intentionally omits\n * runtime-specific values such as `Error.stack`.\n */\nexport interface StreamErrorEvent {\n /** Discriminant for stream event handling. */\n readonly type: \"error\";\n /** Stable run id when known; empty when failure happened before protocol startup. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Error name when available. */\n readonly name: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Optional serializable diagnostics supplied by the SDK. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Completion event yielded by `stream()` after successful execution.\n */\nexport type StreamCompletionEvent = FinalEvent;\n\n/**\n * Public streaming event union returned by `stream()`.\n *\n * @remarks\n * The union is grouped into lifecycle, output, error, and completion families:\n *\n * - lifecycle: {@link StreamLifecycleEvent}\n * - output: {@link StreamOutputEvent}\n * - error: {@link StreamErrorEvent}\n * - completion: {@link StreamCompletionEvent}\n *\n * Successful stream events are also persisted as {@link RunEvent} values in the\n * completed trace. `error` is stream-only because a failed run has no completed\n * {@link RunResult} trace to return.\n */\nexport type StreamEvent = StreamLifecycleEvent | StreamOutputEvent | StreamErrorEvent | StreamCompletionEvent;\n\n/**\n * Lifecycle status for a live {@link StreamHandle}.\n */\nexport type StreamHandleStatus = \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\n/**\n * Normalized transcript entry captured during a run.\n *\n * @remarks\n * The transcript is an ordered list of model-visible contributions. Each entry\n * represents exactly one agent prompt/response pair in the order Dogpile\n * executed it. Unlike {@link RunEvent}, transcript entries omit lifecycle\n * timing, broadcast grouping, and cumulative cost so the structure stays small\n * and stable for application display, caller-managed persistence, and replay\n * fixtures.\n *\n * Transcript structure:\n *\n * - `agentId`: stable id of the agent that produced the contribution.\n * - `role`: model-visible role or perspective for that contribution.\n * - `input`: prompt text visible to the agent for that turn.\n * - `output`: generated text returned by the model provider.\n * - `toolCalls`: optional ordered tool call/result pairs requested during\n * that turn.\n *\n * `RunResult.transcript` and `Trace.transcript` contain the same ordered\n * entries; the result-level copy exists for ergonomic access while the trace\n * keeps the complete serializable replay artifact together.\n */\nexport interface TranscriptEntry {\n /** Agent that produced the transcript contribution. */\n readonly agentId: string;\n /** Agent role for the contribution. */\n readonly role: string;\n /** Prompt/input visible to the agent. */\n readonly input: string;\n /** Text produced by the agent. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n /** Ordered runtime tool calls and results requested during this turn. */\n readonly toolCalls?: readonly TranscriptToolCall[];\n}\n\n/**\n * Complete transcript artifact for a finished run.\n *\n * @remarks\n * High-level APIs expose `readonly TranscriptEntry[]` directly for ergonomic\n * application use. This named structure is the durable artifact shape for\n * callers that want a self-describing transcript object with the run id, entry\n * count, and final output bundled together for persistence or replay.\n */\nexport interface Transcript {\n /** Transcript artifact discriminant. */\n readonly kind: \"run-transcript\";\n /** Stable run id shared by the source trace and event log. */\n readonly runId: string;\n /** Number of entries in the completed transcript. */\n readonly entryCount: number;\n /** Ordered agent prompt/response entries. */\n readonly entries: readonly TranscriptEntry[];\n /** Final synthesized output produced from these entries. */\n readonly finalOutput: string;\n}\n\n/**\n * Token and spend accounting for a run or turn.\n */\nexport interface CostSummary {\n /** Estimated spend in US dollars. */\n readonly usd: number;\n /** Input tokens consumed. */\n readonly inputTokens: number;\n /** Output tokens generated. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n}\n\n/**\n * Aggregate provider usage reported for a completed run.\n *\n * This mirrors {@link CostSummary} at the non-streaming result boundary so\n * callers can read model usage without treating spend accounting as the only\n * usage artifact. It remains JSON-serializable and runtime-neutral.\n */\nexport interface RunUsage {\n /** Estimated spend in US dollars. */\n readonly usd: number;\n /** Input tokens consumed across all model calls. */\n readonly inputTokens: number;\n /** Output tokens generated across all model calls. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n}\n\n/**\n * Result-level cost and budget accounting for a completed run.\n *\n * @remarks\n * This block makes budget state first-class on {@link RunResult} without\n * forcing application code to unpack the full replay trace. It records the\n * selected tier, caller-supplied caps, optional termination policy, final\n * usage/cost totals, and compact cap-utilization metadata.\n */\nexport interface RunAccounting {\n /** Accounting artifact discriminant. */\n readonly kind: \"run-accounting\";\n /** Named budget/cost tier selected for the run. */\n readonly tier: Tier;\n /** Optional hard caps supplied by the caller. */\n readonly budget?: BudgetCaps;\n /** Optional termination policy used by the protocol. */\n readonly termination?: TerminationCondition;\n /** Total token and spend usage for the run. */\n readonly usage: RunUsage;\n /** Total token and spend cost for the run. */\n readonly cost: CostSummary;\n /** Ordered budget state snapshots derived from cost-bearing events. */\n readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];\n /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */\n readonly usdCapUtilization?: number;\n /** Fraction of the configured total-token cap consumed, when `maxTokens` is present. */\n readonly totalTokenCapUtilization?: number;\n}\n\n/**\n * Normalized quality score for a completed run.\n *\n * Values use the inclusive `0..1` range. The field is optional on\n * {@link RunResult} because production model runs may not have a judge, while\n * benchmark and researcher harnesses can attach a score without changing the\n * single-call result shape.\n */\nexport type NormalizedQualityScore = number;\n\n/**\n * Serializable evaluation payload for a completed run.\n *\n * @remarks\n * Applications and benchmark harnesses can attach caller-owned judge output\n * without making Dogpile core depend on a storage layer, model-specific judge,\n * or Node-only runtime. The `quality` value is mirrored to\n * {@link RunResult.quality} and the terminal {@link FinalEvent} so streaming\n * and non-streaming execution expose the same judged result.\n */\nexport interface RunEvaluation {\n /** Normalized quality score in the inclusive range `0..1`. */\n readonly quality: NormalizedQualityScore;\n /** Optional human-readable judge rationale. */\n readonly rationale?: string;\n /** Optional serializable judge or benchmark metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * JSON-serializable trace returned with every completed workflow.\n *\n * @remarks\n * This is the canonical caller-managed replay artifact. Dogpile core remains\n * stateless, so every SDK-owned fact needed to inspect a completed run is\n * represented as JSON-compatible data here: normalized inputs, budget policy,\n * seed metadata, ordered events, protocol decisions, provider requests and\n * responses, budget snapshots, transcript entries, and the final output.\n *\n * Event order is authoritative. `events[n]` is the source coordination moment\n * for `protocolDecisions[n]`, and `RunEventLog.events` uses the same order as\n * this trace for completed runs. Provider calls are ordered by execution and\n * capture the exact {@link ModelRequest} handed to the configured adapter plus\n * the exact {@link ModelResponse} returned by that adapter, including optional\n * usage and cost telemetry. Current protocol runners keep provider calls\n * one-to-one with transcript entries and completed `agent-turn` events.\n */\nexport interface Trace {\n /** Replay trace schema version. */\n readonly schemaVersion: ReplayTraceSchemaVersion;\n /** Stable id for this workflow run. */\n readonly runId: string;\n /** Protocol that produced this trace. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Configured model provider id used by the run. */\n readonly modelProviderId: string;\n /** Concrete agents that participated in the run. */\n readonly agentsUsed: readonly AgentSpec[];\n /** Normalized caller inputs needed to replay this run. */\n readonly inputs: ReplayTraceRunInputs;\n /** Budget caps and termination policy used by this run. */\n readonly budget: ReplayTraceBudget;\n /** Ordered budget state snapshots derived from cost-bearing events. */\n readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];\n /** Deterministic seed metadata for replay tooling. */\n readonly seed: ReplayTraceSeed;\n /** Ordered protocol decisions derived from the event log. */\n readonly protocolDecisions: readonly ReplayTraceProtocolDecision[];\n /** Provider requests and responses captured during execution. */\n readonly providerCalls: readonly ReplayTraceProviderCall[];\n /** Final output artifact for replay consumers. */\n readonly finalOutput: ReplayTraceFinalOutput;\n /**\n * Ordered coordination and lifecycle events.\n *\n * This is the complete streaming event log captured during execution. It has\n * the same event shapes yielded by {@link StreamHandle} and remains\n * JSON-serializable for caller-managed replay.\n */\n readonly events: readonly RunEvent[];\n /**\n * Complete normalized model-turn transcript.\n *\n * Entries are ordered by execution and contain only agent id, role, input,\n * and output. Use this when the application needs the conversation artifact\n * without streaming lifecycle metadata.\n */\n readonly transcript: readonly TranscriptEntry[];\n}\n\n/**\n * Complete event log returned by non-streaming APIs.\n *\n * This is the result-level counterpart to the live {@link StreamHandle}\n * iterator. It contains the exact ordered events also stored in\n * {@link Trace.events}, plus compact metadata useful for dashboards and tests\n * that do not need to unpack the full trace.\n */\nexport interface RunEventLog {\n /** Event-log artifact discriminant. */\n readonly kind: \"run-event-log\";\n /** Stable id shared by every event in this log. */\n readonly runId: string;\n /** Protocol that produced the event log. */\n readonly protocol: Protocol;\n /** Ordered event kinds for compact coverage checks. */\n readonly eventTypes: readonly RunEvent[\"type\"][];\n /** Number of events captured. */\n readonly eventCount: number;\n /** Complete ordered event log for the run. */\n readonly events: readonly RunEvent[];\n}\n\n/**\n * Run metadata returned by non-streaming APIs.\n *\n * The metadata block gathers stable identifiers and timing boundaries that are\n * otherwise derivable from {@link Trace}. Keeping it explicit makes the\n * single-call result easier to persist, index, and inspect without adding SDK\n * storage.\n */\nexport interface RunMetadata {\n /** Stable id for this workflow run. */\n readonly runId: string;\n /** Protocol that produced this run. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Configured model provider id used by the run. */\n readonly modelProviderId: string;\n /** Concrete agents that participated in the run. */\n readonly agentsUsed: readonly AgentSpec[];\n /** ISO-8601 timestamp of the first event, or an empty string for eventless runs. */\n readonly startedAt: string;\n /** ISO-8601 timestamp of the final event, or an empty string for eventless runs. */\n readonly completedAt: string;\n}\n\n/**\n * Result returned by high-level single-call APIs.\n *\n * The returned shape is\n * `{ output, eventLog, transcript, usage, metadata, accounting, trace, cost, quality, evaluation }`.\n * `output` is the final synthesized answer, `eventLog` is the complete ordered\n * coordination log, `transcript` is the complete agent-turn transcript,\n * `usage` reports token and dollar accounting, and `metadata` exposes stable\n * run identifiers and timing. `accounting` bundles the selected tier, budget\n * caps, final usage/cost, and cap utilization. `trace` remains the complete\n * serializable replay artifact, `cost` is retained as a compatibility alias\n * for `usage`, and `quality` and `evaluation` are present when a judge or\n * benchmark supplies a normalized score and serializable evaluation payload.\n */\nexport interface RunResult {\n /** Final synthesized answer for the supplied intent. */\n readonly output: string;\n /** Complete non-streaming event log captured during the run. */\n readonly eventLog: RunEventLog;\n /** Full serializable trace and event log. */\n readonly trace: Trace;\n /**\n * Complete normalized transcript for direct application use.\n *\n * This duplicates `trace.transcript` so high-level callers can read the\n * ordered agent contributions without unpacking the full trace object.\n */\n readonly transcript: readonly TranscriptEntry[];\n /** Total usage and spend accounting for the run. */\n readonly usage: RunUsage;\n /** Stable ids, selected controls, provider id, participating agents, and timing boundaries. */\n readonly metadata: RunMetadata;\n /** Result-level budget, usage, cost, and cap-utilization accounting. */\n readonly accounting: RunAccounting;\n /** Total cost and token accounting for the run; compatibility alias for `usage`. */\n readonly cost: CostSummary;\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly quality?: NormalizedQualityScore;\n /** Optional serializable evaluation data supplied by a caller-owned evaluator. */\n readonly evaluation?: RunEvaluation;\n}\n\n/**\n * Caller-owned evaluator invoked after protocol execution and before the final\n * result is exposed to `run()` or `stream()` callers.\n */\nexport type RunEvaluator = (result: Omit<RunResult, \"quality\" | \"evaluation\">) => RunEvaluation | Promise<RunEvaluation>;\n\n/**\n * Mission supplied to a high-level Dogpile workflow call.\n *\n * @remarks\n * `intent` is the caller-facing mission statement for the agent collective. It\n * is kept as a named type so applications can expose the same concept without\n * depending on the full {@link DogpileOptions} object.\n */\nexport type MissionIntent = string;\n\n/**\n * Coordination protocol selection accepted by high-level SDK calls.\n *\n * @remarks\n * Pass a named protocol for ergonomic defaults, or a protocol config object\n * when a run needs explicit turn/round limits. The union remains\n * discriminated once normalized through {@link ProtocolConfig}.\n */\nexport type ProtocolSelection = ProtocolName | ProtocolConfig;\n\n/**\n * Compatibility alias for high-level coordination protocol selection.\n */\nexport type CoordinationProtocolSelection = ProtocolSelection;\n\n/**\n * Hard budget caps layered over a selected cost/quality tier.\n *\n * @remarks\n * High-level calls keep `tier` next to `budget`, so the budget object only\n * carries caps and quality weighting. This shape is JSON-serializable and can\n * be copied directly into replay traces.\n */\nexport type BudgetCaps = Omit<Budget, \"tier\">;\n\n/**\n * Cost and budget controls accepted by high-level SDK calls.\n *\n * @remarks\n * Omit `tier` to use the high-level default `balanced` preset. Omit `budget`\n * for an uncapped run beyond the tier preset.\n */\nexport interface BudgetCostTierOptions {\n /**\n * Named budget/cost tier.\n *\n * Supported values are `fast`, `balanced`, and `quality`. Defaults to\n * `balanced` when omitted.\n */\n readonly tier?: BudgetTier;\n /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */\n readonly budget?: BudgetCaps;\n}\n\n/**\n * Options accepted by the high-level single-call workflow APIs.\n *\n * Provide an `intent` and configure a model provider. The high-level surface\n * defaults to the Sequential protocol and `balanced` tier; callers can pass a\n * protocol, tier, agents, temperature, or budget caps to refine execution\n * without constructing an engine.\n */\nexport interface DogpileOptions extends BudgetCostTierOptions {\n /** Mission or intent for the agent collective. */\n readonly intent: MissionIntent;\n /**\n * Coordination protocol, either by name or explicit configuration.\n *\n * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.\n * Named protocols use default configs: `maxTurns: 3` for coordinator,\n * sequential, and shared; `maxRounds: 2` for broadcast.\n */\n readonly protocol?: ProtocolSelection;\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly model: ConfiguredModelProvider;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Optional protocol-agnostic runtime tools available to first-party protocols. */\n readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Optional temperature override. */\n readonly temperature?: number;\n /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */\n readonly terminate?: TerminationCondition;\n /** Optional caller-owned evaluator that supplies quality and evaluation data. */\n readonly evaluate?: RunEvaluator;\n /** Optional deterministic seed recorded in the replay trace. */\n readonly seed?: string | number;\n /** Optional caller cancellation signal passed to provider-facing model requests. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Low-level engine configuration for reusable protocol execution.\n *\n * @remarks\n * Researchers can create one engine with fixed protocol/model/agent settings\n * and run multiple missions through it for controlled comparisons. Application\n * code usually starts with {@link DogpileOptions}; use this escape hatch when\n * you need stable experiment controls, repeated runs against the same model\n * adapter, custom agent rosters, or explicit protocol configs.\n *\n * `budget` is layered over `tier` for caps and quality weighting. The core\n * remains stateless: every run still returns its own serializable trace and\n * transcript, and the caller owns persistence or replay.\n *\n * @example\n * ```ts\n * const engine = createEngine({\n * protocol: { kind: \"sequential\", maxTurns: 4 },\n * tier: \"balanced\",\n * model: provider,\n * agents\n * });\n *\n * const result = await engine.run(\"Compare the protocol variants.\");\n * ```\n */\nexport interface EngineOptions {\n /**\n * Coordination protocol, either by name or explicit configuration.\n *\n * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.\n * Named protocols use default configs: `maxTurns: 3` for coordinator,\n * sequential, and shared; `maxRounds: 2` for broadcast.\n */\n readonly protocol: ProtocolSelection;\n /**\n * Named budget/cost tier.\n *\n * Supported values are `fast`, `balanced`, and `quality`. Use `balanced` as\n * the recommended default when callers do not expose a user preference.\n */\n readonly tier: BudgetTier;\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly model: ConfiguredModelProvider;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Optional protocol-agnostic runtime tools available to first-party protocols. */\n readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Optional temperature override. */\n readonly temperature?: number;\n /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */\n readonly budget?: Omit<Budget, \"tier\">;\n /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */\n readonly terminate?: TerminationCondition;\n /** Optional caller-owned evaluator that supplies quality and evaluation data. */\n readonly evaluate?: RunEvaluator;\n /** Optional deterministic seed recorded in the replay trace. */\n readonly seed?: string | number;\n /** Optional caller cancellation signal passed to provider-facing model requests. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Async event stream returned by `stream()`.\n *\n * @remarks\n * Iterate the handle to receive live {@link StreamEvent} values. Successful\n * lifecycle, output, and completion events are stored in `result.trace.events`\n * in the same order. If execution fails, the stream yields one `error` event\n * and {@link StreamHandle.result} rejects with the original error.\n *\n * @example\n * ```ts\n * const handle = Dogpile.stream(options);\n *\n * for await (const event of handle) {\n * if (event.type === \"agent-turn\") {\n * renderTurn(event.agentId, event.output);\n * }\n * }\n *\n * const result = await handle.result;\n * ```\n */\nexport interface StreamHandle extends AsyncIterable<StreamEvent> {\n /** Current lifecycle state for this handle. */\n readonly status: StreamHandleStatus;\n /** Final result resolved after the stream completes. */\n readonly result: Promise<RunResult>;\n /**\n * Cancel this live stream.\n *\n * Cancellation aborts the active provider-facing request signal, emits a\n * terminal `error` stream event with `code: \"aborted\"` and\n * `status: \"cancelled\"` diagnostics, rejects {@link result}, and closes the\n * consumer-facing iterator. Calling `cancel()` after the handle has already\n * completed is a no-op.\n */\n cancel(): void;\n /**\n * Attach to live events emitted by this run.\n *\n * Subscribers first receive the events already emitted by the handle, then\n * receive live events until they unsubscribe or the run completes. The\n * returned subscription detaches the listener without cancelling the\n * underlying run, so demos and UIs can mount/unmount against a live SDK\n * workflow while the caller still awaits {@link result}.\n */\n subscribe(subscriber: StreamEventSubscriber): StreamSubscription;\n}\n\n/**\n * Callback invoked for each live streaming event.\n */\nexport type StreamEventSubscriber = (event: StreamEvent) => void;\n\n/**\n * Subscription returned by {@link StreamHandle.subscribe}.\n */\nexport interface StreamSubscription {\n /** Stop delivering future events to the subscriber. */\n unsubscribe(): void;\n}\n\n/**\n * Reusable low-level protocol engine.\n *\n * @remarks\n * `Engine` is the extension point behind the high-level `run()`,\n * `stream()`, and `Dogpile.pile()` helpers. It lets research harnesses reuse\n * one normalized protocol configuration across many missions while choosing\n * between batch results and live event streams.\n *\n * The engine does not retain run history. Store each returned\n * {@link RunResult.trace} in caller-managed infrastructure if you need replay,\n * audit, or benchmark aggregation.\n */\nexport interface Engine {\n /** Execute a mission to completion and return the final result. */\n run(intent: string): Promise<RunResult>;\n /** Stream a mission's events while preserving access to the final result. */\n stream(intent: string): StreamHandle;\n}\n","import type {\n AgentSpec,\n Budget,\n CostSummary,\n Protocol,\n ProtocolConfig,\n ReplayTraceBudget,\n ReplayTraceFinalOutput,\n ReplayTraceProtocolDecision,\n ReplayTraceProtocolDecisionType,\n ReplayTraceProviderCall,\n ReplayTraceRunInputs,\n ReplayTraceBudgetStateChange,\n ReplayTraceSeed,\n RunResult,\n RunAccounting,\n RunEvent,\n RunEventLog,\n RunMetadata,\n RunUsage,\n Tier,\n TranscriptEntry,\n TranscriptLink\n} from \"../types.js\";\n\ntype SerializableRecord = Record<string, unknown>;\n\nexport function normalizeProtocol(protocol: Protocol | ProtocolConfig): ProtocolConfig {\n if (typeof protocol !== \"string\") {\n return protocol;\n }\n\n switch (protocol) {\n case \"sequential\":\n return { kind: \"sequential\", maxTurns: 3 };\n case \"coordinator\":\n return { kind: \"coordinator\", maxTurns: 3 };\n case \"broadcast\":\n return { kind: \"broadcast\", maxRounds: 2 };\n case \"shared\":\n return { kind: \"shared\", maxTurns: 3 };\n }\n}\n\nexport function defaultAgents(): readonly AgentSpec[] {\n return [\n { id: \"agent-1\", role: \"planner\", instructions: \"Frame the mission and identify the important constraints.\" },\n { id: \"agent-2\", role: \"critic\", instructions: \"Stress-test the previous contribution and improve weak spots.\" },\n { id: \"agent-3\", role: \"synthesizer\", instructions: \"Produce the final useful answer from the accumulated work.\" }\n ];\n}\n\nexport function orderAgentsForTemperature(\n agents: readonly AgentSpec[],\n temperature: number,\n seed?: string | number\n): readonly AgentSpec[] {\n if (temperature !== 0) {\n return agents;\n }\n\n if (seed !== undefined) {\n return [...agents].sort((left, right) => compareAgentsBySeededSelection(left, right, seed));\n }\n\n return [...agents].sort(compareAgentsByStableIdentity);\n}\n\nfunction compareAgentsBySeededSelection(left: AgentSpec, right: AgentSpec, seed: string | number): number {\n const leftScore = deterministicSelectionScore(seed, left);\n const rightScore = deterministicSelectionScore(seed, right);\n if (leftScore !== rightScore) {\n return leftScore - rightScore;\n }\n\n return compareAgentsByStableIdentity(left, right);\n}\n\nfunction deterministicSelectionScore(seed: string | number, agent: AgentSpec): number {\n return stableHash(`${String(seed)}\\u0000${agent.id}\\u0000${agent.role}\\u0000${agent.instructions ?? \"\"}`);\n}\n\nfunction stableHash(input: string): number {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < input.length; index += 1) {\n hash ^= input.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return hash >>> 0;\n}\n\nfunction compareAgentsByStableIdentity(left: AgentSpec, right: AgentSpec): number {\n const idOrder = left.id.localeCompare(right.id);\n if (idOrder !== 0) {\n return idOrder;\n }\n\n const roleOrder = left.role.localeCompare(right.role);\n if (roleOrder !== 0) {\n return roleOrder;\n }\n\n return (left.instructions ?? \"\").localeCompare(right.instructions ?? \"\");\n}\n\nexport function tierTemperature(tier: Tier): number {\n switch (tier) {\n case \"fast\":\n return 0;\n case \"balanced\":\n return 0.2;\n case \"quality\":\n return 0.4;\n }\n}\n\nexport function emptyCost(): CostSummary {\n return { usd: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function addCost(left: CostSummary, right: CostSummary): CostSummary {\n return {\n usd: left.usd + right.usd,\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n totalTokens: left.totalTokens + right.totalTokens\n };\n}\n\nexport function createTranscriptLink(transcript: readonly TranscriptEntry[]): TranscriptLink {\n return {\n kind: \"trace-transcript\",\n entryCount: transcript.length,\n lastEntryIndex: transcript.length === 0 ? null : transcript.length - 1\n };\n}\n\nexport function createRunEventLog(runId: string, protocol: Protocol, events: readonly RunEvent[]): RunEventLog {\n return {\n kind: \"run-event-log\",\n runId,\n protocol,\n eventTypes: events.map((event) => event.type),\n eventCount: events.length,\n events\n };\n}\n\nexport function createRunUsage(cost: CostSummary): RunUsage {\n return {\n usd: cost.usd,\n inputTokens: cost.inputTokens,\n outputTokens: cost.outputTokens,\n totalTokens: cost.totalTokens\n };\n}\n\nexport function createRunAccounting(options: {\n readonly tier: Tier;\n readonly budget?: Omit<Budget, \"tier\">;\n readonly termination?: ReplayTraceBudget[\"termination\"];\n readonly cost: CostSummary;\n readonly events: readonly RunEvent[];\n}): RunAccounting {\n const usage = createRunUsage(options.cost);\n return {\n kind: \"run-accounting\",\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.termination ? { termination: options.termination } : {}),\n usage,\n cost: options.cost,\n budgetStateChanges: createReplayTraceBudgetStateChanges(options.events),\n ...(options.budget?.maxUsd !== undefined\n ? { usdCapUtilization: options.budget.maxUsd === 0 ? 0 : options.cost.usd / options.budget.maxUsd }\n : {}),\n ...(options.budget?.maxTokens !== undefined\n ? {\n totalTokenCapUtilization:\n options.budget.maxTokens === 0 ? 0 : options.cost.totalTokens / options.budget.maxTokens\n }\n : {})\n };\n}\n\nexport function createRunMetadata(options: {\n readonly runId: string;\n readonly protocol: Protocol;\n readonly tier: Tier;\n readonly modelProviderId: string;\n readonly agentsUsed: readonly AgentSpec[];\n readonly events: readonly RunEvent[];\n}): RunMetadata {\n const firstEvent = options.events[0];\n const lastEvent = options.events.at(-1);\n return {\n runId: options.runId,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.modelProviderId,\n agentsUsed: options.agentsUsed,\n startedAt: firstEvent?.at ?? \"\",\n completedAt: lastEvent?.at ?? \"\"\n };\n}\n\nexport function createReplayTraceRunInputs(options: {\n readonly intent: string;\n readonly protocol: ProtocolConfig;\n readonly tier: Tier;\n readonly modelProviderId: string;\n readonly agents: readonly AgentSpec[];\n readonly temperature: number;\n}): ReplayTraceRunInputs {\n return {\n kind: \"replay-trace-run-inputs\",\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.modelProviderId,\n agents: options.agents,\n temperature: options.temperature\n };\n}\n\nexport function createReplayTraceBudget(options: {\n readonly tier: Tier;\n readonly caps?: Omit<Budget, \"tier\">;\n readonly termination?: ReplayTraceBudget[\"termination\"];\n}): ReplayTraceBudget {\n return {\n kind: \"replay-trace-budget\",\n tier: options.tier,\n ...(options.caps ? { caps: options.caps } : {}),\n ...(options.termination ? { termination: options.termination } : {})\n };\n}\n\nexport function createReplayTraceBudgetStateChanges(\n events: readonly RunEvent[]\n): readonly ReplayTraceBudgetStateChange[] {\n return events.flatMap((event, eventIndex): ReplayTraceBudgetStateChange[] => {\n switch (event.type) {\n case \"agent-turn\":\n case \"broadcast\":\n case \"final\":\n return [\n {\n kind: \"replay-trace-budget-state-change\",\n eventIndex,\n eventType: event.type,\n at: event.at,\n cost: event.cost\n }\n ];\n case \"budget-stop\":\n return [\n {\n kind: \"replay-trace-budget-state-change\",\n eventIndex,\n eventType: event.type,\n at: event.at,\n cost: event.cost,\n iteration: event.iteration,\n elapsedMs: event.elapsedMs,\n budgetReason: event.reason\n }\n ];\n case \"role-assignment\":\n case \"model-request\":\n case \"model-response\":\n case \"model-output-chunk\":\n case \"tool-call\":\n case \"tool-result\":\n return [];\n }\n });\n}\n\nexport function createReplayTraceSeed(seed: string | number | undefined): ReplayTraceSeed {\n if (seed === undefined) {\n return {\n kind: \"replay-trace-seed\",\n source: \"none\",\n value: null\n };\n }\n\n return {\n kind: \"replay-trace-seed\",\n source: \"caller\",\n value: seed\n };\n}\n\nexport function createReplayTraceProtocolDecisions(\n protocol: Protocol,\n events: readonly RunEvent[]\n): readonly ReplayTraceProtocolDecision[] {\n return events.map((event, eventIndex): ReplayTraceProtocolDecision => {\n return createReplayTraceProtocolDecision(protocol, event, eventIndex);\n });\n}\n\nexport function createReplayTraceProtocolDecision(\n protocol: Protocol,\n event: RunEvent,\n eventIndex: number,\n options: {\n readonly decision?: ReplayTraceProtocolDecisionType;\n readonly turn?: number;\n readonly phase?: ReplayTraceProtocolDecision[\"phase\"];\n readonly round?: number;\n readonly transcriptEntryCount?: number;\n readonly contributionCount?: number;\n } = {}\n): ReplayTraceProtocolDecision {\n const base = {\n kind: \"replay-trace-protocol-decision\" as const,\n eventIndex,\n eventType: event.type,\n protocol,\n decision: options.decision ?? defaultProtocolDecision(event),\n at: event.at,\n ...(options.turn !== undefined ? { turn: options.turn } : {}),\n ...(options.phase !== undefined ? { phase: options.phase } : {}),\n ...(options.round !== undefined ? { round: options.round } : {}),\n ...(options.transcriptEntryCount !== undefined ? { transcriptEntryCount: options.transcriptEntryCount } : {}),\n ...(options.contributionCount !== undefined ? { contributionCount: options.contributionCount } : {})\n };\n\n switch (event.type) {\n case \"role-assignment\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role\n };\n case \"model-request\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n callId: event.callId,\n providerId: event.providerId,\n input: event.request.messages.map((message) => message.content).join(\"\\n\")\n };\n case \"model-response\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n callId: event.callId,\n providerId: event.providerId,\n output: event.response.text\n };\n case \"model-output-chunk\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n input: event.input,\n output: event.output\n };\n case \"tool-call\":\n return {\n ...base,\n toolCallId: event.toolCallId,\n tool: event.tool,\n input: stableJsonStringify(event.input),\n ...eventAgentScope(event)\n };\n case \"tool-result\":\n return {\n ...base,\n toolCallId: event.toolCallId,\n tool: event.tool,\n output: stableJsonStringify(event.result),\n ...eventAgentScope(event)\n };\n case \"agent-turn\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n input: event.input,\n output: event.output,\n cost: event.cost\n };\n case \"broadcast\":\n return {\n ...base,\n round: event.round,\n contributionCount: options.contributionCount ?? event.contributions.length,\n cost: event.cost\n };\n case \"budget-stop\":\n return {\n ...base,\n cost: event.cost,\n budgetReason: event.reason\n };\n case \"final\":\n return {\n ...base,\n output: event.output,\n cost: event.cost\n };\n }\n}\n\nfunction defaultProtocolDecision(event: RunEvent): ReplayTraceProtocolDecisionType {\n switch (event.type) {\n case \"role-assignment\":\n return \"assign-role\";\n case \"model-request\":\n return \"start-model-call\";\n case \"model-response\":\n return \"complete-model-call\";\n case \"model-output-chunk\":\n return \"observe-model-output\";\n case \"tool-call\":\n return \"start-tool-call\";\n case \"tool-result\":\n return \"complete-tool-call\";\n case \"agent-turn\":\n return \"select-agent-turn\";\n case \"broadcast\":\n return \"collect-broadcast-round\";\n case \"budget-stop\":\n return \"stop-for-budget\";\n case \"final\":\n return \"finalize-output\";\n }\n}\n\nfunction eventAgentScope(event: {\n readonly agentId?: string;\n readonly role?: string;\n}): Pick<ReplayTraceProtocolDecision, \"agentId\" | \"role\"> {\n return {\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(event.role !== undefined ? { role: event.role } : {})\n };\n}\n\nexport function createReplayTraceFinalOutput(output: string, event: RunEvent): ReplayTraceFinalOutput {\n if (event.type === \"final\") {\n return {\n kind: \"replay-trace-final-output\",\n output,\n cost: event.cost,\n completedAt: event.at,\n transcript: event.transcript\n };\n }\n\n return {\n kind: \"replay-trace-final-output\",\n output,\n cost: emptyCost(),\n completedAt: event.at,\n transcript: {\n kind: \"trace-transcript\",\n entryCount: 0,\n lastEntryIndex: null\n }\n };\n}\n\nexport function nextProviderCallId(\n runId: string,\n providerCalls: readonly ReplayTraceProviderCall[]\n): string {\n return `${runId}:provider-call:${providerCalls.length + 1}`;\n}\n\n/**\n * Normalize completed run artifacts into deterministic JSON shapes.\n *\n * This keeps caller-owned persistence stable across runtimes: object keys are\n * sorted recursively, undefined object fields are omitted, non-finite numbers\n * become JSON `null`, and negative zero is normalized to zero before callers\n * serialize the returned result, trace, event log, transcript, or metadata.\n */\nexport function canonicalizeRunResult(result: RunResult): RunResult {\n const trace = canonicalizeSerializable(result.trace);\n const eventLog: RunEventLog = {\n eventCount: trace.events.length,\n eventTypes: trace.events.map((event) => event.type),\n events: trace.events,\n kind: \"run-event-log\",\n protocol: trace.protocol,\n runId: trace.runId\n };\n const canonicalResult = {\n accounting: canonicalizeSerializable(result.accounting),\n cost: canonicalizeSerializable(result.cost),\n ...(result.evaluation !== undefined ? { evaluation: canonicalizeSerializable(result.evaluation) } : {}),\n eventLog,\n metadata: canonicalizeSerializable(result.metadata),\n output: result.output,\n ...(result.quality !== undefined ? { quality: canonicalizeSerializable(result.quality) } : {}),\n trace,\n transcript: trace.transcript,\n usage: canonicalizeSerializable(result.usage)\n };\n\n return canonicalResult;\n}\n\nexport function stableJsonStringify(value: unknown): string {\n return JSON.stringify(canonicalizeSerializable(value));\n}\n\nexport function canonicalizeSerializable<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalizeSerializable(item)) as T;\n }\n\n if (typeof value === \"number\") {\n if (Object.is(value, -0)) {\n return 0 as T;\n }\n if (!Number.isFinite(value)) {\n return null as T;\n }\n return value;\n }\n\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n const input = value as SerializableRecord;\n const output: SerializableRecord = {};\n for (const key of Object.keys(input).sort()) {\n const child = input[key];\n if (child !== undefined) {\n output[key] = canonicalizeSerializable(child);\n }\n }\n\n return output as T;\n}\n","import { DogpileError, type JsonObject } from \"../types.js\";\n\nexport function throwIfAborted(signal: AbortSignal | undefined, providerId: string): void {\n if (!signal?.aborted) {\n return;\n }\n\n throw createAbortErrorFromSignal(signal, providerId);\n}\n\nexport function createAbortError(providerId: string, detail?: JsonObject, cause?: unknown): DogpileError {\n return new DogpileError({\n code: \"aborted\",\n message: \"The operation was aborted.\",\n retryable: false,\n providerId,\n ...(detail !== undefined ? { detail } : {}),\n ...(cause !== undefined ? { cause } : {})\n });\n}\n\nexport function createAbortErrorFromSignal(signal: AbortSignal, providerId: string): DogpileError {\n if (DogpileError.isInstance(signal.reason)) {\n return signal.reason;\n }\n\n return createAbortError(providerId, undefined, signal.reason);\n}\n\nexport function createTimeoutError(providerId: string, timeoutMs: number): DogpileError {\n return new DogpileError({\n code: \"timeout\",\n message: `The operation timed out after ${timeoutMs}ms.`,\n retryable: true,\n providerId,\n detail: {\n timeoutMs\n }\n });\n}\n","import type { AgentDecision, AgentParticipation } from \"../types.js\";\n\nexport function parseAgentDecision(output: string): AgentDecision | undefined {\n const selectedRole = matchLine(output, /^role_selected:\\s*(.+)$/imu);\n const participation = matchLine(output, /^participation:\\s*(contribute|abstain)$/imu);\n const rationale = matchLine(output, /^rationale:\\s*(.+)$/imu);\n const contribution = matchContribution(output);\n\n if (!selectedRole || !participation || !isAgentParticipation(participation) || !rationale || !contribution) {\n return undefined;\n }\n\n return {\n selectedRole,\n participation,\n rationale,\n contribution\n };\n}\n\nexport function isParticipatingDecision(decision: AgentDecision | undefined): boolean {\n return decision?.participation !== \"abstain\";\n}\n\nfunction matchLine(output: string, pattern: RegExp): string | undefined {\n const match = output.match(pattern);\n return match?.[1]?.trim();\n}\n\nfunction matchContribution(output: string): string | undefined {\n const match = output.match(/^contribution:\\s*\\n([\\s\\S]*)$/imu);\n const contribution = match?.[1]?.trim();\n return contribution && contribution.length > 0 ? contribution : undefined;\n}\n\nexport function isAgentParticipation(value: string): value is AgentParticipation {\n return value === \"contribute\" || value === \"abstain\";\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n ModelRequest,\n ModelResponse,\n RuntimeToolExecutionRequest,\n ReplayTraceProviderCall,\n RunEvent\n} from \"../types.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\n\ninterface GenerateModelTurnOptions {\n readonly model: ConfiguredModelProvider;\n readonly request: ModelRequest;\n readonly runId: string;\n readonly agent: AgentSpec;\n readonly input: string;\n readonly emit: (event: RunEvent) => void;\n readonly callId: string;\n readonly onProviderCall?: (call: ReplayTraceProviderCall) => void;\n}\n\ntype ModelUsage = NonNullable<ModelResponse[\"usage\"]>;\n\nexport async function generateModelTurn(options: GenerateModelTurnOptions): Promise<ModelResponse> {\n const startedAt = new Date().toISOString();\n let response: ModelResponse;\n\n throwIfAborted(options.request.signal, options.model.id);\n\n if (!options.model.stream) {\n response = await options.model.generate(options.request);\n throwIfAborted(options.request.signal, options.model.id);\n recordProviderCall(response, startedAt, options);\n return response;\n }\n\n let text = \"\";\n let chunkIndex = 0;\n let usage: ModelUsage | undefined;\n let costUsd: number | undefined;\n let finishReason: ModelResponse[\"finishReason\"] | undefined;\n let toolRequests: readonly RuntimeToolExecutionRequest[] | undefined;\n let metadata: ModelResponse[\"metadata\"] | undefined;\n\n for await (const chunk of options.model.stream(options.request)) {\n throwIfAborted(options.request.signal, options.model.id);\n text += chunk.text;\n\n options.emit({\n type: \"model-output-chunk\",\n runId: options.runId,\n at: new Date().toISOString(),\n agentId: options.agent.id,\n role: options.agent.role,\n input: options.input,\n chunkIndex,\n text: chunk.text,\n output: text\n });\n chunkIndex += 1;\n\n if (chunk.usage) {\n usage = chunk.usage;\n }\n if (chunk.costUsd !== undefined) {\n costUsd = chunk.costUsd;\n }\n if (chunk.finishReason !== undefined) {\n finishReason = chunk.finishReason;\n }\n if (chunk.toolRequests !== undefined) {\n toolRequests = chunk.toolRequests;\n }\n if (chunk.metadata !== undefined) {\n metadata = chunk.metadata;\n }\n }\n\n response = {\n text,\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(toolRequests && toolRequests.length > 0 ? { toolRequests } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n ...(metadata !== undefined ? { metadata } : {})\n };\n throwIfAborted(options.request.signal, options.model.id);\n recordProviderCall(response, startedAt, options);\n return response;\n}\n\nfunction recordProviderCall(\n response: ModelResponse,\n startedAt: string,\n options: GenerateModelTurnOptions\n): void {\n options.onProviderCall?.({\n kind: \"replay-trace-provider-call\",\n callId: options.callId,\n providerId: options.model.id,\n startedAt,\n completedAt: new Date().toISOString(),\n agentId: options.agent.id,\n role: options.agent.role,\n request: requestForTrace(options.request),\n response\n });\n}\n\nfunction requestForTrace(request: ModelRequest): ModelRequest {\n return {\n messages: request.messages,\n temperature: request.temperature,\n metadata: request.metadata\n };\n}\n","import type {\n BudgetStopReason,\n BudgetTerminationCondition,\n ConvergenceTerminationCondition,\n FirstOfTerminationCondition,\n FirstOfTerminationConditions,\n FirstOfTerminationOutput,\n JudgeEvaluationDecision,\n JudgeStopReason,\n JudgeTerminationCondition,\n JsonObject,\n NormalizedStopReason,\n TerminationStopRecord,\n StopTerminationDecision,\n TerminationCondition,\n TerminationDecision,\n TerminationEvaluationContext,\n TranscriptEntry\n} from \"../types.js\";\n\n/**\n * Create a budget termination condition.\n *\n * The returned object is JSON-serializable and can be used directly in\n * `terminate` or composed with {@link firstOf}.\n */\nexport function budget(options: Omit<BudgetTerminationCondition, \"kind\">): BudgetTerminationCondition {\n return {\n kind: \"budget\",\n ...options\n };\n}\n\n/**\n * Create a convergence termination condition.\n *\n * The condition fires when the run has produced `stableTurns` sufficiently\n * similar protocol outputs.\n */\nexport function convergence(options: Omit<ConvergenceTerminationCondition, \"kind\">): ConvergenceTerminationCondition {\n return {\n kind: \"convergence\",\n ...options\n };\n}\n\n/**\n * Create a judge termination condition.\n *\n * The rubric is stored as serializable configuration so callers can replay or\n * persist traces without SDK-owned state.\n */\nexport function judge(options: Omit<JudgeTerminationCondition, \"kind\">): JudgeTerminationCondition {\n return {\n kind: \"judge\",\n ...options\n };\n}\n\n/**\n * Compose termination conditions so whichever child fires first wins.\n *\n * Conditions are evaluated in the order supplied by the caller. At least one\n * condition is required so the composite is always meaningful and the public\n * type remains a non-empty tuple.\n */\nexport function firstOf(...conditions: FirstOfTerminationConditions): FirstOfTerminationCondition {\n if (conditions.length === 0) {\n throw new RangeError(\"firstOf requires at least one termination condition.\");\n }\n\n return {\n kind: \"firstOf\",\n conditions\n };\n}\n\n/**\n * Evaluate a serializable termination condition against the current run state.\n *\n * Budget, convergence, judge, and firstOf conditions are enforced from their\n * own normalized inputs so one stop class cannot accidentally satisfy another.\n */\nexport function evaluateTermination(\n condition: TerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n switch (condition.kind) {\n case \"budget\":\n return evaluateBudget(condition, context);\n case \"firstOf\":\n return evaluateFirstOf(condition, context).decision;\n case \"convergence\":\n return evaluateConvergence(condition, context);\n case \"judge\":\n return evaluateJudge(condition, context);\n }\n}\n\n/**\n * Evaluate an ordered firstOf composition and return the winning child, if any.\n */\nexport function evaluateFirstOf(\n condition: FirstOfTerminationCondition,\n context: TerminationEvaluationContext\n): FirstOfTerminationOutput {\n const evaluated: TerminationDecision[] = [];\n\n for (const [index, child] of condition.conditions.entries()) {\n const decision = evaluateTermination(child, context);\n evaluated.push(decision);\n\n if (decision.type === \"stop\") {\n return {\n kind: \"firstOf-output\",\n decision,\n winningConditionIndex: index,\n evaluated\n };\n }\n }\n\n return {\n kind: \"firstOf-output\",\n decision: { type: \"continue\", condition },\n winningConditionIndex: null,\n evaluated\n };\n}\n\n/**\n * Evaluate a termination condition and return a trace-ready stop record.\n *\n * Protocol runners use this helper so the first policy decision that halts a\n * run is recorded exactly once on the terminal event.\n */\nexport function evaluateTerminationStop(\n condition: TerminationCondition,\n context: TerminationEvaluationContext\n): TerminationStopRecord | null {\n if (condition.kind === \"firstOf\") {\n const output = evaluateFirstOf(condition, context);\n if (output.decision.type !== \"stop\" || output.winningConditionIndex === null) {\n return null;\n }\n\n const winningCondition = condition.conditions[output.winningConditionIndex];\n if (!winningCondition) {\n throw new RangeError(\"firstOf stop referenced a missing winning condition.\");\n }\n\n return stopRecord(condition, output.decision, {\n kind: \"firstOf-stop\",\n winningConditionIndex: output.winningConditionIndex,\n winningCondition,\n firedCondition: output.decision.condition,\n evaluated: output.evaluated\n });\n }\n\n const decision = evaluateTermination(condition, context);\n if (decision.type !== \"stop\") {\n return null;\n }\n\n return stopRecord(condition, decision);\n}\n\n/**\n * Combine independently evaluated termination decisions with SDK precedence.\n *\n * Budget caps win over judge decisions, and judge decisions win over\n * convergence. This keeps simultaneous stops deterministic while preserving\n * each evaluator's normalized stop reason on the returned decision.\n */\nexport function combineTerminationDecisions(\n decisions: readonly TerminationDecision[]\n): TerminationDecision {\n const stopDecisions = decisions.filter((decision): decision is StopTerminationDecision => decision.type === \"stop\");\n if (stopDecisions.length === 0) {\n const firstDecision = decisions[0];\n if (!firstDecision) {\n throw new RangeError(\"combineTerminationDecisions requires at least one decision.\");\n }\n\n return firstDecision;\n }\n\n return stopDecisions.reduce((winner, candidate) =>\n stopPrecedence(candidate.normalizedReason) < stopPrecedence(winner.normalizedReason) ? candidate : winner\n );\n}\n\n/**\n * Evaluate cost, token, iteration, and timeout caps for a budget condition.\n */\nexport function evaluateBudget(\n condition: BudgetTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const iteration = context.iteration ?? context.transcript.length;\n const elapsedMs = context.elapsedMs ?? 0;\n\n const costStop = stopIfReached(condition, \"maxUsd\", \"cost\", context.cost.usd);\n if (costStop) {\n return costStop;\n }\n\n const tokenStop = stopIfReached(condition, \"maxTokens\", \"tokens\", context.cost.totalTokens);\n if (tokenStop) {\n return tokenStop;\n }\n\n const iterationStop = stopIfReached(condition, \"maxIterations\", \"iterations\", iteration);\n if (iterationStop) {\n return iterationStop;\n }\n\n const timeoutStop = stopIfReached(condition, \"timeoutMs\", \"timeout\", elapsedMs);\n if (timeoutStop) {\n return timeoutStop;\n }\n\n return { type: \"continue\", condition };\n}\n\n/**\n * Evaluate protocol-level convergence from recent coordination outputs.\n *\n * This intentionally ignores budget caps and judge quality state. Budget and\n * judge conditions can be composed with convergence through `firstOf`, but a\n * convergence condition itself only reads protocol output signals.\n */\nexport function evaluateConvergence(\n condition: ConvergenceTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const stableTurns = Math.max(1, Math.ceil(condition.stableTurns));\n if (context.transcript.length < stableTurns) {\n return { type: \"continue\", condition };\n }\n\n const recentEntries = context.transcript.slice(-stableTurns);\n const recentOutputs = recentEntries.map((entry) => entry.output);\n const similarities = consecutiveSimilarities(recentEntries);\n const observedSimilarity = similarities.length === 0 ? 1 : Math.min(...similarities);\n\n if (observedSimilarity < condition.minSimilarity) {\n return { type: \"continue\", condition };\n }\n\n return {\n type: \"stop\",\n condition,\n reason: \"convergence\",\n normalizedReason: \"convergence\",\n detail: {\n protocol: context.protocol,\n stableTurns,\n minSimilarity: condition.minSimilarity,\n observedSimilarity,\n outputs: recentOutputs\n }\n };\n}\n\n/**\n * Evaluate caller-owned judge state without reading budget or convergence data.\n *\n * Explicit accept/reject verdicts always halt. Score-only decisions halt when\n * they meet `minScore`; when `minScore` is omitted, any score-only decision is\n * treated as the judge's terminal decision.\n */\nexport function evaluateJudge(\n condition: JudgeTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const decision = context.judgeDecision ?? scoreDecisionFromQuality(context.quality);\n if (!decision) {\n return { type: \"continue\", condition };\n }\n\n switch (decision.type) {\n case \"accept\":\n return judgeStop(condition, \"accepted\", decision);\n case \"reject\":\n return judgeStop(condition, \"rejected\", decision);\n case \"score\": {\n const minScore = condition.minScore;\n if (minScore !== undefined && decision.score < minScore) {\n return { type: \"continue\", condition };\n }\n\n return judgeStop(condition, \"score-threshold\", decision, minScore);\n }\n }\n}\n\nfunction stopIfReached(\n condition: BudgetTerminationCondition,\n cap: \"maxUsd\" | \"maxTokens\" | \"maxIterations\" | \"timeoutMs\",\n reason: BudgetStopReason,\n observed: number\n): StopTerminationDecision | null {\n const limit = condition[cap];\n if (limit === undefined || observed < limit) {\n return null;\n }\n\n return {\n type: \"stop\",\n condition,\n reason: \"budget\",\n normalizedReason: normalizeBudgetStopReason(reason),\n budgetReason: reason,\n detail: {\n cap,\n limit,\n observed\n }\n };\n}\n\nfunction scoreDecisionFromQuality(quality: number | undefined): JudgeEvaluationDecision | null {\n if (quality === undefined) {\n return null;\n }\n\n return {\n type: \"score\",\n score: quality\n };\n}\n\nfunction judgeStop(\n condition: JudgeTerminationCondition,\n judgeReason: JudgeStopReason,\n decision: JudgeEvaluationDecision,\n minScore?: number\n): StopTerminationDecision {\n return {\n type: \"stop\",\n condition,\n reason: \"judge\",\n normalizedReason: normalizeJudgeStopReason(judgeReason),\n judgeReason,\n detail: judgeStopDetail(decision, minScore)\n };\n}\n\nfunction normalizeBudgetStopReason(reason: BudgetStopReason): NormalizedStopReason {\n switch (reason) {\n case \"cost\":\n return \"budget:cost\";\n case \"tokens\":\n return \"budget:tokens\";\n case \"iterations\":\n return \"budget:iterations\";\n case \"timeout\":\n return \"budget:timeout\";\n }\n}\n\nfunction normalizeJudgeStopReason(reason: JudgeStopReason): NormalizedStopReason {\n switch (reason) {\n case \"accepted\":\n return \"judge:accepted\";\n case \"rejected\":\n return \"judge:rejected\";\n case \"score-threshold\":\n return \"judge:score-threshold\";\n }\n}\n\nfunction stopPrecedence(reason: NormalizedStopReason): number {\n if (reason.startsWith(\"budget:\")) {\n return 0;\n }\n\n if (reason.startsWith(\"judge:\")) {\n return 1;\n }\n\n return 2;\n}\n\nfunction judgeStopDetail(decision: JudgeEvaluationDecision, minScore?: number): JsonObject {\n return {\n decision: decision.type,\n ...(decision.score !== undefined ? { score: decision.score } : {}),\n ...(minScore !== undefined ? { minScore } : {}),\n ...(decision.rationale !== undefined ? { rationale: decision.rationale } : {}),\n ...(decision.metadata !== undefined ? { metadata: decision.metadata } : {})\n };\n}\n\nfunction stopRecord(\n rootCondition: TerminationCondition,\n decision: StopTerminationDecision,\n firstOfRecord?: NonNullable<TerminationStopRecord[\"firstOf\"]>\n): TerminationStopRecord {\n return {\n kind: \"termination-stop\",\n rootCondition,\n firedCondition: decision.condition,\n reason: decision.reason,\n normalizedReason: decision.normalizedReason,\n ...(decision.budgetReason !== undefined ? { budgetReason: decision.budgetReason } : {}),\n ...(decision.judgeReason !== undefined ? { judgeReason: decision.judgeReason } : {}),\n ...(decision.detail !== undefined ? { detail: decision.detail } : {}),\n ...(firstOfRecord !== undefined ? { firstOf: firstOfRecord } : {})\n };\n}\n\nfunction consecutiveSimilarities(entries: readonly TranscriptEntry[]): readonly number[] {\n const similarities: number[] = [];\n\n for (let index = 1; index < entries.length; index += 1) {\n const previous = entries[index - 1];\n const current = entries[index];\n if (previous && current) {\n similarities.push(outputSimilarity(previous.output, current.output));\n }\n }\n\n return similarities;\n}\n\nfunction outputSimilarity(left: string, right: string): number {\n const normalizedLeft = normalizeOutput(left);\n const normalizedRight = normalizeOutput(right);\n\n if (normalizedLeft === normalizedRight) {\n return 1;\n }\n\n const leftTokens = tokenize(normalizedLeft);\n const rightTokens = tokenize(normalizedRight);\n if (leftTokens.length === 0 || rightTokens.length === 0) {\n return 0;\n }\n\n const leftSet = new Set(leftTokens);\n const rightSet = new Set(rightTokens);\n let intersection = 0;\n\n for (const token of leftSet) {\n if (rightSet.has(token)) {\n intersection += 1;\n }\n }\n\n const union = new Set([...leftSet, ...rightSet]).size;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction normalizeOutput(output: string): string {\n return output.trim().toLowerCase();\n}\n\nfunction tokenize(output: string): readonly string[] {\n return output.split(/[^a-z0-9]+/u).filter((token) => token.length > 0);\n}\n","import { DogpileError } from \"../types.js\";\nimport type {\n AgentSpec,\n BudgetCaps,\n BudgetTier,\n ConfiguredModelProvider,\n DogpileOptions,\n EngineOptions,\n JsonObject,\n JsonValue,\n ProtocolConfig,\n ProtocolName,\n ProtocolSelection,\n RuntimeTool,\n TerminationCondition\n} from \"../types.js\";\n\nconst protocolNames = [\"coordinator\", \"sequential\", \"broadcast\", \"shared\"] as const;\nconst budgetTiers = [\"fast\", \"balanced\", \"quality\"] as const;\n\ntype ValidationRule =\n | \"required\"\n | \"non-empty-string\"\n | \"finite-number\"\n | \"non-negative-number\"\n | \"positive-integer\"\n | \"non-negative-integer\"\n | \"range\"\n | \"enum\"\n | \"object\"\n | \"array\"\n | \"boolean\"\n | \"function\"\n | \"json-object\"\n | \"abort-signal\"\n | \"model-provider\"\n | \"runtime-tool\"\n | \"termination-condition\";\n\ninterface ValidationFailureOptions {\n readonly path: string;\n readonly rule: ValidationRule;\n readonly message: string;\n readonly expected: string;\n readonly actual: unknown;\n}\n\n/**\n * Validate high-level caller options before any protocol execution starts.\n */\nexport function validateDogpileOptions(options: DogpileOptions): void {\n requireRecord(options, \"options\");\n validateMissionIntent(options.intent);\n\n if (options.protocol !== undefined) {\n validateProtocolSelection(options.protocol, \"protocol\");\n }\n if (options.tier !== undefined) {\n validateBudgetTier(options.tier, \"tier\");\n }\n\n validateModelProviderRegistration(options.model, \"model\");\n validateOptionalAgents(options.agents, \"agents\");\n validateOptionalRuntimeTools(options.tools, \"tools\");\n validateOptionalTemperature(options.temperature, \"temperature\");\n validateOptionalBudgetCaps(options.budget, \"budget\");\n validateOptionalTerminationCondition(options.terminate, \"terminate\");\n validateOptionalFunction(options.evaluate, \"evaluate\");\n validateOptionalSeed(options.seed, \"seed\");\n validateOptionalAbortSignal(options.signal, \"signal\");\n}\n\nexport function validateMissionIntent(intent: unknown, path = \"intent\"): void {\n validateNonEmptyString(intent, path, \"intent is required.\");\n}\n\n/**\n * Validate low-level engine configuration before normalizing reusable controls.\n */\nexport function validateEngineOptions(options: EngineOptions): void {\n requireRecord(options, \"options\");\n validateProtocolSelection(options.protocol, \"protocol\");\n validateBudgetTier(options.tier, \"tier\");\n validateModelProviderRegistration(options.model, \"model\");\n validateOptionalAgents(options.agents, \"agents\");\n validateOptionalRuntimeTools(options.tools, \"tools\");\n validateOptionalTemperature(options.temperature, \"temperature\");\n validateOptionalBudgetCaps(options.budget, \"budget\");\n validateOptionalTerminationCondition(options.terminate, \"terminate\");\n validateOptionalFunction(options.evaluate, \"evaluate\");\n validateOptionalSeed(options.seed, \"seed\");\n validateOptionalAbortSignal(options.signal, \"signal\");\n}\n\n/**\n * Validate Vercel AI adapter factory options at construction time.\n */\nexport function validateVercelAIProviderOptions(options: unknown): void {\n const record = requireRecord(options, \"options\");\n\n if (record.model === undefined) {\n invalidConfiguration({\n path: \"model\",\n rule: \"required\",\n message: \"model is required.\",\n expected: \"a Vercel AI language model\",\n actual: record.model\n });\n }\n if (typeof record.model === \"string\") {\n validateNonEmptyString(record.model, \"model\", \"model must not be empty.\");\n } else {\n validateVercelAILanguageModel(record.model, \"model\");\n }\n\n validateOptionalNonEmptyString(record.id, \"id\");\n validateOptionalBoolean(record.streaming, \"streaming\");\n validateOptionalFunction(record.generateText, \"generateText\");\n validateOptionalFunction(record.streamText, \"streamText\");\n validateOptionalFunction(record.costEstimator, \"costEstimator\");\n validateOptionalPositiveInteger(record.maxOutputTokens, \"maxOutputTokens\");\n validateOptionalNumberInRange(record.topP, \"topP\", 0, 1);\n validateOptionalPositiveInteger(record.topK, \"topK\");\n validateOptionalNumberInRange(record.presencePenalty, \"presencePenalty\", -2, 2);\n validateOptionalNumberInRange(record.frequencyPenalty, \"frequencyPenalty\", -2, 2);\n validateOptionalStringArray(record.stopSequences, \"stopSequences\");\n validateOptionalInteger(record.seed, \"seed\");\n validateOptionalNonNegativeInteger(record.maxRetries, \"maxRetries\");\n validateOptionalAbortSignal(record.abortSignal, \"abortSignal\");\n validateOptionalHeaders(record.headers, \"headers\");\n validateOptionalProviderOptions(record.providerOptions, \"providerOptions\");\n validateOptionalArray(record.activeTools, \"activeTools\");\n validateOptionalFunction(record.runtimeToolIdForName, \"runtimeToolIdForName\");\n}\n\nfunction validateProtocolSelection(value: ProtocolSelection, path: string): void {\n if (typeof value === \"string\") {\n if (!isProtocolName(value)) {\n invalidConfiguration({\n path,\n rule: \"enum\",\n message: \"protocol must be one of coordinator, sequential, broadcast, or shared.\",\n expected: protocolNames.join(\" | \"),\n actual: value\n });\n }\n return;\n }\n\n validateProtocolConfig(value, path);\n}\n\nfunction validateProtocolConfig(value: ProtocolConfig, path: string): void {\n const record = requireRecord(value, path);\n const kind = record.kind;\n\n if (!isProtocolName(kind)) {\n invalidConfiguration({\n path: `${path}.kind`,\n rule: \"enum\",\n message: \"protocol config kind must be one of coordinator, sequential, broadcast, or shared.\",\n expected: protocolNames.join(\" | \"),\n actual: kind\n });\n }\n\n switch (kind) {\n case \"coordinator\":\n case \"sequential\":\n case \"shared\":\n validateOptionalPositiveInteger(record.maxTurns, `${path}.maxTurns`);\n if (kind === \"shared\") {\n validateOptionalString(record.organizationalMemory, `${path}.organizationalMemory`);\n }\n return;\n case \"broadcast\":\n validateOptionalPositiveInteger(record.maxRounds, `${path}.maxRounds`);\n return;\n }\n}\n\nfunction validateBudgetTier(value: BudgetTier, path: string): void {\n if (!isBudgetTier(value)) {\n invalidConfiguration({\n path,\n rule: \"enum\",\n message: \"tier must be one of fast, balanced, or quality.\",\n expected: budgetTiers.join(\" | \"),\n actual: value\n });\n }\n}\n\n/**\n * Validate configured model provider definitions at registration boundaries.\n */\nexport function validateModelProviderRegistration(value: unknown, path = \"model\"): asserts value is ConfiguredModelProvider {\n const record = requireRecord(value, path);\n validateNonEmptyString(record.id, `${path}.id`, \"model.id is required.\");\n validateFunction(record.generate, `${path}.generate`);\n validateOptionalFunction(record.stream, `${path}.stream`);\n}\n\nfunction validateVercelAILanguageModel(value: unknown, path: string): void {\n const record = requireRecord(value, path);\n\n if (record.specificationVersion !== \"v2\" && record.specificationVersion !== \"v3\") {\n invalidConfiguration({\n path: `${path}.specificationVersion`,\n rule: \"model-provider\",\n message: \"model.specificationVersion must be v2 or v3.\",\n expected: \"v2 | v3\",\n actual: record.specificationVersion\n });\n }\n\n validateNonEmptyString(record.provider, `${path}.provider`, \"model.provider is required.\");\n validateNonEmptyString(record.modelId, `${path}.modelId`, \"model.modelId is required.\");\n validateFunction(record.doGenerate, `${path}.doGenerate`);\n validateFunction(record.doStream, `${path}.doStream`);\n}\n\nfunction validateOptionalAgents(value: readonly AgentSpec[] | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"agents must be an array when provided.\",\n expected: \"readonly AgentSpec[]\",\n actual: value\n });\n }\n if (value.length === 0) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"agents must contain at least one participant when provided.\",\n expected: \"non-empty readonly AgentSpec[]\",\n actual: value\n });\n }\n\n value.forEach((agent, index) => {\n const agentPath = `${path}[${index}]`;\n const record = requireRecord(agent, agentPath);\n validateNonEmptyString(record.id, `${agentPath}.id`, \"agent.id is required.\");\n validateNonEmptyString(record.role, `${agentPath}.role`, \"agent.role is required.\");\n validateOptionalString(record.instructions, `${agentPath}.instructions`);\n });\n}\n\nfunction validateOptionalRuntimeTools(value: readonly RuntimeTool<JsonObject, JsonValue>[] | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateRuntimeToolRegistrations(value, path);\n}\n\n/**\n * Validate runtime tool definitions at registration boundaries.\n */\nexport function validateRuntimeToolRegistrations(value: unknown, path = \"tools\"): void {\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"tools must be an array when provided.\",\n expected: \"readonly RuntimeTool[]\",\n actual: value\n });\n }\n\n value.forEach((tool, index) => validateRuntimeTool(tool, `${path}[${index}]`));\n}\n\nfunction validateRuntimeTool(value: RuntimeTool<JsonObject, JsonValue>, path: string): void {\n const record = requireRecord(value, path);\n const identity = requireRecord(record.identity, `${path}.identity`);\n validateNonEmptyString(identity.id, `${path}.identity.id`, \"tool identity id is required.\");\n validateNonEmptyString(identity.name, `${path}.identity.name`, \"tool identity name is required.\");\n validateOptionalString(identity.namespace, `${path}.identity.namespace`);\n validateOptionalString(identity.version, `${path}.identity.version`);\n validateOptionalString(identity.description, `${path}.identity.description`);\n\n const inputSchema = requireRecord(record.inputSchema, `${path}.inputSchema`);\n if (inputSchema.kind !== \"json-schema\") {\n invalidConfiguration({\n path: `${path}.inputSchema.kind`,\n rule: \"runtime-tool\",\n message: \"tool inputSchema.kind must be json-schema.\",\n expected: \"json-schema\",\n actual: inputSchema.kind\n });\n }\n validateJsonObject(inputSchema.schema, `${path}.inputSchema.schema`);\n validateOptionalString(inputSchema.description, `${path}.inputSchema.description`);\n validateOptionalArray(record.permissions, `${path}.permissions`);\n validateOptionalFunction(record.validateInput, `${path}.validateInput`);\n validateFunction(record.execute, `${path}.execute`);\n}\n\nfunction validateOptionalBudgetCaps(value: BudgetCaps | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateBudgetCaps(value, path);\n}\n\nfunction validateBudgetCaps(value: BudgetCaps, path: string): void {\n const record = requireRecord(value, path);\n validateOptionalNonNegativeNumber(record.maxUsd, `${path}.maxUsd`);\n validateOptionalNonNegativeInteger(record.maxTokens, `${path}.maxTokens`);\n validateOptionalNonNegativeInteger(record.maxIterations, `${path}.maxIterations`);\n validateOptionalNonNegativeInteger(record.timeoutMs, `${path}.timeoutMs`);\n validateOptionalNumberInRange(record.qualityWeight, `${path}.qualityWeight`, 0, 1);\n}\n\nfunction validateOptionalTerminationCondition(value: TerminationCondition | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateTerminationCondition(value, path, new Set<object>());\n}\n\nfunction validateTerminationCondition(value: TerminationCondition, path: string, stack: Set<object>): void {\n const record = requireRecord(value, path);\n if (stack.has(record)) {\n invalidConfiguration({\n path,\n rule: \"termination-condition\",\n message: \"termination conditions must not contain cycles.\",\n expected: \"acyclic termination condition\",\n actual: value\n });\n }\n\n stack.add(record);\n try {\n switch (record.kind) {\n case \"budget\":\n validateBudgetCaps(record, path);\n return;\n case \"convergence\":\n validatePositiveInteger(record.stableTurns, `${path}.stableTurns`);\n validateNumberInRange(record.minSimilarity, `${path}.minSimilarity`, 0, 1);\n return;\n case \"judge\":\n validateJudgeRubric(record.rubric, `${path}.rubric`);\n validateOptionalNumberInRange(record.minScore, `${path}.minScore`, 0, 1);\n return;\n case \"firstOf\":\n validateFirstOfConditions(record.conditions, `${path}.conditions`, stack);\n return;\n default:\n invalidConfiguration({\n path: `${path}.kind`,\n rule: \"termination-condition\",\n message: \"termination condition kind must be budget, convergence, judge, or firstOf.\",\n expected: \"budget | convergence | judge | firstOf\",\n actual: record.kind\n });\n }\n } finally {\n stack.delete(record);\n }\n}\n\nfunction validateFirstOfConditions(value: unknown, path: string, stack: Set<object>): void {\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"firstOf conditions must be a non-empty array.\",\n expected: \"non-empty termination condition array\",\n actual: value\n });\n }\n if (value.length === 0) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"firstOf conditions must contain at least one condition.\",\n expected: \"non-empty termination condition array\",\n actual: value\n });\n }\n\n value.forEach((condition, index) => {\n validateTerminationCondition(condition as TerminationCondition, `${path}[${index}]`, stack);\n });\n}\n\nfunction validateJudgeRubric(value: unknown, path: string): void {\n if (typeof value === \"string\") {\n validateNonEmptyString(value, path, \"judge rubric must not be empty.\");\n return;\n }\n\n validateJsonObject(value, path);\n}\n\nfunction validateOptionalTemperature(value: number | undefined, path: string): void {\n validateOptionalNumberInRange(value, path, 0, 2);\n}\n\nfunction validateOptionalSeed(value: string | number | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return;\n }\n\n invalidConfiguration({\n path,\n rule: \"finite-number\",\n message: \"seed must be a string or finite number when provided.\",\n expected: \"string or finite number\",\n actual: value\n });\n}\n\nfunction validateOptionalHeaders(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n\n const record = requireRecord(value, path);\n for (const [key, headerValue] of Object.entries(record)) {\n if (headerValue !== undefined && typeof headerValue !== \"string\") {\n invalidConfiguration({\n path: `${path}.${key}`,\n rule: \"non-empty-string\",\n message: \"headers values must be strings or undefined.\",\n expected: \"string | undefined\",\n actual: headerValue\n });\n }\n }\n}\n\nfunction validateOptionalProviderOptions(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n\n const record = requireRecord(value, path);\n for (const [key, providerOptions] of Object.entries(record)) {\n validateJsonObject(providerOptions, `${path}.${key}`);\n }\n}\n\nfunction validateJsonObject(value: unknown, path: string): void {\n if (!isJsonValue(value, new Set<object>()) || !isRecord(value)) {\n invalidConfiguration({\n path,\n rule: \"json-object\",\n message: \"value must be a JSON-compatible object.\",\n expected: \"JSON-compatible object\",\n actual: value\n });\n }\n}\n\nfunction isJsonValue(value: unknown, stack: Set<object>): value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return true;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n if (Array.isArray(value)) {\n if (stack.has(value)) {\n return false;\n }\n stack.add(value);\n const valid = value.every((child) => isJsonValue(child, stack));\n stack.delete(value);\n return valid;\n }\n if (isRecord(value)) {\n if (stack.has(value)) {\n return false;\n }\n stack.add(value);\n const valid = Object.values(value).every((child) => isJsonValue(child, stack));\n stack.delete(value);\n return valid;\n }\n\n return false;\n}\n\nfunction validateOptionalString(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"string\") {\n invalidConfiguration({\n path,\n rule: \"non-empty-string\",\n message: \"value must be a string when provided.\",\n expected: \"string\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonEmptyString(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateNonEmptyString(value, path, `${path} must not be empty.`);\n}\n\nfunction validateNonEmptyString(value: unknown, path: string, message: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n invalidConfiguration({\n path,\n rule: \"non-empty-string\",\n message,\n expected: \"non-empty string\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalBoolean(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"boolean\") {\n invalidConfiguration({\n path,\n rule: \"boolean\",\n message: \"value must be a boolean when provided.\",\n expected: \"boolean\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalFunction(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateFunction(value, path);\n}\n\nfunction validateFunction(value: unknown, path: string): void {\n if (typeof value !== \"function\") {\n invalidConfiguration({\n path,\n rule: \"function\",\n message: \"value must be a function.\",\n expected: \"function\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalArray(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"value must be an array when provided.\",\n expected: \"array\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalStringArray(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"value must be an array of strings when provided.\",\n expected: \"string[]\",\n actual: value\n });\n }\n value.forEach((item, index) => validateNonEmptyString(item, `${path}[${index}]`, \"array item must be a string.\"));\n}\n\nfunction validateOptionalAbortSignal(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!isAbortSignalLike(value)) {\n invalidConfiguration({\n path,\n rule: \"abort-signal\",\n message: \"value must be an AbortSignal when provided.\",\n expected: \"AbortSignal\",\n actual: value\n });\n }\n}\n\nfunction isAbortSignalLike(value: unknown): value is AbortSignal {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n typeof value.aborted === \"boolean\" &&\n typeof value.addEventListener === \"function\" &&\n typeof value.removeEventListener === \"function\"\n );\n}\n\nfunction validateOptionalInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateInteger(value, path);\n}\n\nfunction validateInteger(value: unknown, path: string): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || !Number.isInteger(value)) {\n invalidConfiguration({\n path,\n rule: \"finite-number\",\n message: \"value must be a finite integer.\",\n expected: \"finite integer\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalPositiveInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validatePositiveInteger(value, path);\n}\n\nfunction validatePositiveInteger(value: unknown, path: string): void {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n invalidConfiguration({\n path,\n rule: \"positive-integer\",\n message: \"value must be a positive integer.\",\n expected: \"integer >= 1\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonNegativeInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n invalidConfiguration({\n path,\n rule: \"non-negative-integer\",\n message: \"value must be a non-negative integer.\",\n expected: \"integer >= 0\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonNegativeNumber(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n invalidConfiguration({\n path,\n rule: \"non-negative-number\",\n message: \"value must be a non-negative finite number.\",\n expected: \"finite number >= 0\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNumberInRange(value: unknown, path: string, min: number, max: number): void {\n if (value === undefined) {\n return;\n }\n validateNumberInRange(value, path, min, max);\n}\n\nfunction validateNumberInRange(value: unknown, path: string, min: number, max: number): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) {\n invalidConfiguration({\n path,\n rule: \"range\",\n message: `value must be a finite number in the inclusive range ${min}..${max}.`,\n expected: `finite number in ${min}..${max}`,\n actual: value\n });\n }\n}\n\nfunction requireRecord(value: unknown, path: string): Record<string, unknown> {\n if (!isRecord(value)) {\n invalidConfiguration({\n path,\n rule: \"object\",\n message: \"value must be an object.\",\n expected: \"object\",\n actual: value\n });\n }\n\n return value;\n}\n\nfunction invalidConfiguration(options: ValidationFailureOptions): never {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: `Invalid Dogpile configuration at ${options.path}: ${options.message}`,\n retryable: false,\n detail: {\n kind: \"configuration-validation\",\n path: options.path,\n rule: options.rule,\n expected: options.expected,\n received: describeValue(options.actual)\n }\n });\n}\n\nfunction isProtocolName(value: unknown): value is ProtocolName {\n return typeof value === \"string\" && protocolNames.includes(value as ProtocolName);\n}\n\nfunction isBudgetTier(value: unknown): value is BudgetTier {\n return typeof value === \"string\" && budgetTiers.includes(value as BudgetTier);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n if (value === undefined) {\n return \"undefined\";\n }\n if (Array.isArray(value)) {\n return \"array\";\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return String(value);\n }\n return typeof value;\n}\n","import type {\n JsonObject,\n JsonValue,\n RuntimeTool,\n RuntimeToolAdapterContract,\n RuntimeToolAdapterError,\n RuntimeToolExecutionContext,\n RuntimeToolExecutionRequest,\n RuntimeToolExecutor,\n RuntimeToolIdentity,\n RuntimeToolInputSchema,\n RuntimeToolPermission,\n RuntimeToolResult,\n TranscriptToolCall,\n RuntimeToolTraceContext,\n RuntimeToolValidationIssue,\n RuntimeToolValidationResult,\n RunEvent,\n ModelMessage,\n ModelResponse\n} from \"../types.js\";\nimport { validateRuntimeToolRegistrations } from \"./validation.js\";\n\ntype VercelAIToolExecuteOptions = {\n readonly toolCallId: string;\n readonly messages: ModelMessage[];\n readonly abortSignal?: AbortSignal;\n readonly experimental_context: RuntimeToolExecutionContext;\n};\n\ntype VercelAIToolExecuteFunction<Input, Output> = (\n input: Input,\n options: VercelAIToolExecuteOptions\n) => Output | PromiseLike<Output> | AsyncIterable<Output>;\n\ntype VercelAICompatibleSchema<Input> = unknown;\n\n/**\n * Built-in Dogpile tool names with stable protocol-facing semantics.\n */\nexport type DogpileBuiltInToolName = \"webSearch\" | \"codeExec\";\n\n/**\n * Input accepted by the built-in web search tool contract.\n */\nexport interface WebSearchToolInput extends JsonObject {\n readonly query: string;\n readonly maxResults?: number;\n}\n\n/**\n * One normalized web search result.\n */\nexport interface WebSearchToolResult extends JsonObject {\n readonly title: string;\n readonly url: string;\n readonly snippet?: string;\n readonly metadata?: JsonObject;\n}\n\n/**\n * Output returned by the built-in web search tool contract.\n */\nexport interface WebSearchToolOutput extends JsonObject {\n readonly results: WebSearchToolResult[];\n}\n\n/**\n * Fetch implementation accepted by the built-in web search adapter.\n */\nexport type WebSearchFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Request data produced before the built-in web search adapter calls `fetch`.\n */\nexport interface WebSearchFetchRequest {\n readonly url: string | URL;\n readonly init?: RequestInit;\n}\n\n/**\n * Build a search backend request from normalized web search input.\n */\nexport type WebSearchFetchRequestBuilder = (\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => WebSearchFetchRequest;\n\n/**\n * Parse a search backend response into Dogpile's stable web search output.\n */\nexport type WebSearchFetchResponseParser = (\n response: Response,\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => WebSearchToolOutput | Promise<WebSearchToolOutput>;\n\n/**\n * Options for the built-in fetch-based web search adapter.\n */\nexport interface WebSearchToolAdapterOptions {\n readonly endpoint: string | URL;\n readonly fetch?: WebSearchFetch;\n readonly headers?: HeadersInit;\n readonly defaultMaxResults?: number;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly permissions?: readonly RuntimeToolPermission[];\n readonly buildRequest?: WebSearchFetchRequestBuilder;\n readonly parseResponse?: WebSearchFetchResponseParser;\n}\n\n/**\n * Options for the built-in code execution adapter.\n */\nexport interface CodeExecToolAdapterOptions {\n readonly execute: CodeExecSandboxExecutor;\n readonly defaultTimeoutMs?: number;\n readonly maxTimeoutMs?: number;\n readonly languages?: readonly CodeExecToolLanguage[];\n readonly allowNetwork?: boolean;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Input accepted by the built-in code execution tool contract.\n *\n * @remarks\n * Dogpile core does not provide a sandbox implementation. Callers supply the\n * executor while Dogpile normalizes the public tool identity and schema.\n */\nexport interface CodeExecToolInput extends JsonObject {\n readonly language: \"javascript\" | \"typescript\" | \"python\" | \"bash\" | \"shell\";\n readonly code: string;\n readonly timeoutMs?: number;\n}\n\n/**\n * Output returned by the built-in code execution tool contract.\n */\nexport interface CodeExecToolOutput extends JsonObject {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n readonly metadata?: JsonObject;\n}\n\n/**\n * Language identifiers accepted by Dogpile's built-in code execution contract.\n */\nexport type CodeExecToolLanguage = CodeExecToolInput[\"language\"];\n\n/**\n * Executor signature for the built-in web search contract.\n */\nexport type WebSearchToolExecutor = (\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => RuntimeToolResult<WebSearchToolOutput> | Promise<RuntimeToolResult<WebSearchToolOutput>>;\n\n/**\n * Executor signature for the built-in code execution contract.\n */\nexport type CodeExecToolExecutor = (\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext\n) => RuntimeToolResult<CodeExecToolOutput> | Promise<RuntimeToolResult<CodeExecToolOutput>>;\n\n/**\n * Caller-owned sandbox implementation used by Dogpile's built-in code execution adapter.\n */\nexport type CodeExecSandboxExecutor = (\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext\n) => CodeExecToolOutput | Promise<CodeExecToolOutput>;\n\n/**\n * Optional identity fields callers may layer onto built-in Dogpile tools.\n */\nexport interface BuiltInDogpileToolIdentityOptions {\n readonly namespace?: string;\n readonly version?: string;\n readonly description?: string;\n}\n\n/**\n * Definition used to normalize Dogpile's built-in web search tool.\n */\nexport interface WebSearchDogpileToolDefinition {\n readonly name: \"webSearch\";\n readonly execute: WebSearchToolExecutor;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Definition used to normalize Dogpile's built-in code execution tool.\n */\nexport interface CodeExecDogpileToolDefinition {\n readonly name: \"codeExec\";\n readonly execute: CodeExecToolExecutor;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Built-in Dogpile tool definitions accepted by the normalization helper.\n */\nexport type BuiltInDogpileToolDefinition = WebSearchDogpileToolDefinition | CodeExecDogpileToolDefinition;\n\n/**\n * Caller-supplied built-in tool executors keyed by Dogpile's stable built-in names.\n */\nexport interface BuiltInDogpileToolExecutors {\n readonly webSearch?: WebSearchToolExecutor | WebSearchDogpileToolDefinition;\n readonly codeExec?: CodeExecToolExecutor | CodeExecDogpileToolDefinition;\n}\n\nexport type BuiltInDogpileRuntimeTool =\n | RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput>\n | RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput>;\n\n/**\n * Vercel AI SDK tool shape accepted by Dogpile's normalization adapter.\n */\nexport interface VercelAITool<Input extends JsonObject = JsonObject, Output extends JsonValue = JsonValue> {\n readonly description?: string;\n readonly inputSchema: VercelAICompatibleSchema<Input>;\n readonly execute?: VercelAIToolExecuteFunction<Input, Output>;\n}\n\n/**\n * Optional identity fields callers may layer onto normalized Vercel AI tools.\n */\nexport interface VercelAIToolIdentityOptions {\n readonly id?: string;\n readonly namespace?: string;\n readonly version?: string;\n readonly description?: string;\n}\n\n/**\n * Definition used to normalize one Vercel AI SDK tool into Dogpile's runtime tool interface.\n */\nexport interface VercelAIToolDefinition<\n Name extends string = string,\n Input extends JsonObject = JsonObject,\n Output extends JsonValue = JsonValue\n> {\n readonly name: Name;\n readonly tool: VercelAITool<Input, Output>;\n readonly identity?: VercelAIToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly messages?: readonly ModelMessage[];\n}\n\n/**\n * Caller-supplied Vercel AI SDK tool set keyed by model-visible tool name.\n */\nexport interface VercelAIToolSetEntry {\n readonly description?: string;\n readonly inputSchema: VercelAICompatibleSchema<unknown>;\n readonly execute?: VercelAIToolExecuteFunction<never, JsonValue>;\n}\n\n/**\n * Caller-supplied Vercel AI SDK tool set keyed by model-visible tool name.\n */\nexport type VercelAIToolSet = Readonly<Record<string, VercelAIToolSetEntry>>;\n\n/**\n * Options shared while normalizing a Vercel AI SDK tool set.\n */\nexport interface VercelAIToolSetNormalizationOptions {\n readonly namespace?: string;\n readonly version?: string;\n readonly messages?: readonly ModelMessage[];\n readonly identity?: Readonly<Record<string, VercelAIToolIdentityOptions>>;\n}\n\n/**\n * Options for the shared protocol-agnostic runtime tool executor.\n */\nexport interface RuntimeToolExecutorOptions {\n readonly runId: string;\n readonly protocol: RuntimeToolExecutionContext[\"protocol\"];\n readonly tier: RuntimeToolExecutionContext[\"tier\"];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly emit?: (event: RunEvent) => void;\n readonly getTrace?: () => RuntimeToolTraceContext;\n readonly metadata?: JsonObject;\n readonly abortSignal?: AbortSignal;\n readonly makeToolCallId?: (tool: RuntimeToolIdentity, callIndex: number) => string;\n}\n\nconst webSearchIdentity: RuntimeToolIdentity = {\n id: \"dogpile.tools.webSearch\",\n namespace: \"dogpile\",\n name: \"webSearch\",\n version: \"1.0.0\",\n description: \"Search the web through a caller-provided fetch-compatible search adapter.\"\n};\n\nconst codeExecIdentity: RuntimeToolIdentity = {\n id: \"dogpile.tools.codeExec\",\n namespace: \"dogpile\",\n name: \"codeExec\",\n version: \"1.0.0\",\n description: \"Execute code through a caller-provided sandbox adapter.\"\n};\n\nconst webSearchInputSchema: RuntimeToolInputSchema = {\n kind: \"json-schema\",\n description: \"Web search query and optional result cap.\",\n schema: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n maxResults: { type: \"number\", minimum: 1 }\n },\n required: [\"query\"],\n additionalProperties: false\n }\n};\n\nconst codeExecInputSchema: RuntimeToolInputSchema = {\n kind: \"json-schema\",\n description: \"Code snippet plus language and optional timeout.\",\n schema: {\n type: \"object\",\n properties: {\n language: {\n type: \"string\",\n enum: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"]\n },\n code: { type: \"string\" },\n timeoutMs: { type: \"number\", minimum: 1 }\n },\n required: [\"language\", \"code\"],\n additionalProperties: false\n }\n};\n\nconst webSearchPermissions: readonly RuntimeToolPermission[] = [\n {\n kind: \"network\",\n allowPrivateNetwork: false\n }\n];\n\nconst codeExecPermissions: readonly RuntimeToolPermission[] = [\n {\n kind: \"code-execution\",\n sandbox: \"caller-provided\",\n languages: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"],\n allowNetwork: false\n }\n];\n\nconst codeExecLanguages: readonly CodeExecToolLanguage[] = [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"];\n\n/**\n * Return the default Dogpile identity for one built-in tool name.\n */\nexport function builtInDogpileToolIdentity(name: \"webSearch\"): RuntimeToolIdentity;\nexport function builtInDogpileToolIdentity(name: \"codeExec\"): RuntimeToolIdentity;\nexport function builtInDogpileToolIdentity(name: DogpileBuiltInToolName): RuntimeToolIdentity {\n return name === \"webSearch\" ? webSearchIdentity : codeExecIdentity;\n}\n\n/**\n * Return the default Dogpile input schema for one built-in tool name.\n */\nexport function builtInDogpileToolInputSchema(name: \"webSearch\"): RuntimeToolInputSchema;\nexport function builtInDogpileToolInputSchema(name: \"codeExec\"): RuntimeToolInputSchema;\nexport function builtInDogpileToolInputSchema(name: DogpileBuiltInToolName): RuntimeToolInputSchema {\n return name === \"webSearch\" ? webSearchInputSchema : codeExecInputSchema;\n}\n\n/**\n * Return the default permission declarations for one built-in tool name.\n */\nexport function builtInDogpileToolPermissions(name: DogpileBuiltInToolName): readonly RuntimeToolPermission[] {\n return name === \"webSearch\" ? webSearchPermissions : codeExecPermissions;\n}\n\n/**\n * Validate one built-in Dogpile tool input before adapter execution.\n */\nexport function validateBuiltInDogpileToolInput(\n name: \"webSearch\",\n input: Readonly<Partial<WebSearchToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: \"codeExec\",\n input: Readonly<Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: DogpileBuiltInToolName,\n input: Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: DogpileBuiltInToolName,\n input: Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult {\n const issues =\n name === \"webSearch\"\n ? validateWebSearchInput(input as Readonly<Partial<WebSearchToolInput>>)\n : validateCodeExecInput(input as Readonly<Partial<CodeExecToolInput>>);\n\n return issues.length === 0 ? { type: \"valid\" } : { type: \"invalid\", issues };\n}\n\n/**\n * Create the shared runtime tool executor used by every first-party protocol.\n *\n * @remarks\n * The executor owns call id generation, read-only trace context construction,\n * adapter validation, error normalization, and matched `tool-call` /\n * `tool-result` events. Protocols only supply a normalized\n * {@link RuntimeToolExecutionRequest}, which keeps tool execution independent\n * of Coordinator, Sequential, Broadcast, or Shared control flow.\n */\nexport function createRuntimeToolExecutor(options: RuntimeToolExecutorOptions): RuntimeToolExecutor {\n validateRuntimeToolRegistrations(options.tools);\n const tools = Array.from(options.tools);\n let callCount = 0;\n\n return {\n tools,\n async execute(request: RuntimeToolExecutionRequest): Promise<RuntimeToolResult> {\n const tool = tools.find((candidate) => candidate.identity.id === request.toolId);\n const identity = tool?.identity ?? {\n id: request.toolId,\n name: request.toolId\n };\n const callIndex = callCount;\n callCount += 1;\n const toolCallId =\n request.toolCallId ?? options.makeToolCallId?.(identity, callIndex) ?? defaultToolCallId(options.runId, callIndex);\n const context = createExecutionContext(options, request, toolCallId);\n\n options.emit?.({\n type: \"tool-call\",\n runId: options.runId,\n at: new Date().toISOString(),\n toolCallId,\n tool: identity,\n input: request.input,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {})\n });\n\n const result = await executeRuntimeTool(tool, identity, request.input, context);\n\n options.emit?.({\n type: \"tool-result\",\n runId: options.runId,\n at: new Date().toISOString(),\n toolCallId,\n tool: identity,\n result,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {})\n });\n\n return result;\n }\n };\n}\n\n/**\n * Return a JSON-serializable manifest for tools visible to a protocol run.\n */\nexport function runtimeToolManifest(tools: readonly RuntimeTool<JsonObject, JsonValue>[]): JsonObject[] {\n return tools.map((tool) => {\n const inputSchema: JsonObject = {\n kind: tool.inputSchema.kind,\n schema: tool.inputSchema.schema,\n ...(tool.inputSchema.description ? { description: tool.inputSchema.description } : {})\n };\n\n return {\n identity: runtimeToolIdentityManifest(tool.identity),\n inputSchema,\n permissions: Array.from(tool.permissions ?? []).map(runtimeToolPermissionManifest)\n };\n });\n}\n\n/**\n * Return request metadata that makes runtime tools visible to provider\n * adapters, or an empty object when no tools are available.\n */\nexport function runtimeToolAvailability(tools: readonly RuntimeTool<JsonObject, JsonValue>[]): JsonObject {\n const manifest = runtimeToolManifest(tools);\n return manifest.length > 0 ? { tools: manifest } : {};\n}\n\n/**\n * Execute normalized tool requests returned by a provider response.\n */\nexport async function executeModelResponseToolRequests(options: {\n readonly response: ModelResponse;\n readonly executor: RuntimeToolExecutor;\n readonly agentId: string;\n readonly role: string;\n readonly turn: number;\n readonly metadata?: JsonObject;\n}): Promise<readonly TranscriptToolCall[]> {\n const toolCalls: TranscriptToolCall[] = [];\n\n for (const request of options.response.toolRequests ?? []) {\n const result = await options.executor.execute({\n ...request,\n agentId: request.agentId ?? options.agentId,\n role: request.role ?? options.role,\n turn: request.turn ?? options.turn,\n metadata: mergeToolMetadata(options.metadata, request.metadata)\n });\n toolCalls.push({\n toolCallId: result.toolCallId,\n tool: result.tool,\n input: request.input,\n result\n });\n }\n\n return toolCalls;\n}\n\nfunction runtimeToolIdentityManifest(identity: RuntimeToolIdentity): JsonObject {\n return {\n id: identity.id,\n name: identity.name,\n ...(identity.namespace ? { namespace: identity.namespace } : {}),\n ...(identity.version ? { version: identity.version } : {}),\n ...(identity.description ? { description: identity.description } : {})\n };\n}\n\nfunction runtimeToolPermissionManifest(permission: RuntimeToolPermission): JsonObject {\n if (permission.kind === \"network\") {\n return {\n kind: permission.kind,\n ...(permission.allowHosts ? { allowHosts: Array.from(permission.allowHosts) } : {}),\n ...(permission.allowPrivateNetwork === undefined ? {} : { allowPrivateNetwork: permission.allowPrivateNetwork })\n };\n }\n\n if (permission.kind === \"code-execution\") {\n return {\n kind: permission.kind,\n sandbox: permission.sandbox,\n ...(permission.languages ? { languages: Array.from(permission.languages) } : {}),\n ...(permission.allowNetwork === undefined ? {} : { allowNetwork: permission.allowNetwork })\n };\n }\n\n return {\n kind: permission.kind,\n name: permission.name,\n ...(permission.description ? { description: permission.description } : {}),\n ...(permission.metadata ? { metadata: permission.metadata } : {})\n };\n}\n\nfunction validateCodeExecAdapterInput(\n input: Readonly<Partial<CodeExecToolInput>>,\n options: Pick<CodeExecToolAdapterOptions, \"languages\" | \"maxTimeoutMs\" | \"defaultTimeoutMs\">\n): RuntimeToolValidationResult {\n const issues = [...validateCodeExecInput(input)];\n const languages = options.languages ?? codeExecLanguages;\n\n if (typeof input.language === \"string\" && isCodeExecLanguage(input.language) && !languages.includes(input.language)) {\n issues.push({\n code: \"invalid-value\",\n path: \"language\",\n message: \"codeExec.language is not enabled for this adapter.\",\n detail: {\n allowed: Array.from(languages)\n }\n });\n }\n\n const effectiveTimeoutMs = input.timeoutMs ?? options.defaultTimeoutMs;\n if (\n effectiveTimeoutMs !== undefined &&\n options.maxTimeoutMs !== undefined &&\n Number.isFinite(effectiveTimeoutMs) &&\n Number.isFinite(options.maxTimeoutMs) &&\n effectiveTimeoutMs > options.maxTimeoutMs\n ) {\n issues.push({\n code: \"out-of-range\",\n path: input.timeoutMs === undefined ? \"defaultTimeoutMs\" : \"timeoutMs\",\n message: `codeExec.timeoutMs must be less than or equal to ${options.maxTimeoutMs}.`,\n detail: {\n maximum: options.maxTimeoutMs\n }\n });\n }\n\n return issues.length === 0 ? { type: \"valid\" } : { type: \"invalid\", issues };\n}\n\nfunction createExecutionContext(\n options: RuntimeToolExecutorOptions,\n request: RuntimeToolExecutionRequest,\n toolCallId: string\n): RuntimeToolExecutionContext {\n return {\n runId: options.runId,\n toolCallId,\n protocol: options.protocol,\n tier: options.tier,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {}),\n ...(request.turn !== undefined ? { turn: request.turn } : {}),\n ...(options.getTrace ? { trace: options.getTrace() } : {}),\n ...(request.abortSignal ?? options.abortSignal ? { abortSignal: request.abortSignal ?? options.abortSignal } : {}),\n ...(options.metadata || request.metadata ? { metadata: mergeToolMetadata(options.metadata, request.metadata) } : {})\n };\n}\n\nasync function executeRuntimeTool(\n tool: RuntimeTool<JsonObject, JsonValue> | undefined,\n identity: RuntimeToolIdentity,\n input: JsonObject,\n context: RuntimeToolExecutionContext\n): Promise<RuntimeToolResult> {\n if (!tool) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"unavailable\",\n message: `Runtime tool \"${identity.id}\" is not registered.`,\n retryable: false\n }\n };\n }\n\n const validation = validateRuntimeToolInput(tool, input);\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: \"Runtime tool input failed validation.\",\n retryable: false,\n detail: {\n issues: validation.issues.map((issue) => ({\n code: issue.code,\n path: issue.path,\n message: issue.message,\n ...(issue.detail ? { detail: issue.detail } : {})\n }))\n }\n }\n };\n }\n\n try {\n return await tool.execute(input, context);\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n}\n\nfunction validateRuntimeToolInput(\n tool: RuntimeTool<JsonObject, JsonValue>,\n input: JsonObject\n): RuntimeToolValidationResult {\n if (typeof tool.validateInput !== \"function\") {\n return { type: \"valid\" };\n }\n\n return tool.validateInput(input);\n}\n\nfunction mergeToolMetadata(base: JsonObject | undefined, request: JsonObject | undefined): JsonObject {\n return {\n ...(base ?? {}),\n ...(request ?? {})\n };\n}\n\nfunction defaultToolCallId(runId: string, callIndex: number): string {\n return `${runId}:tool-${callIndex + 1}`;\n}\n\n/**\n * Convert an unknown adapter failure into Dogpile's serializable error data.\n */\nexport function normalizeRuntimeToolAdapterError(error: unknown): RuntimeToolAdapterError {\n if (isRuntimeToolAdapterError(error)) {\n return error;\n }\n\n if (error instanceof DOMException && error.name === \"AbortError\") {\n return {\n code: \"aborted\",\n message: error.message || \"Tool execution was aborted.\",\n retryable: true,\n detail: {\n name: error.name\n }\n };\n }\n\n if (error instanceof Error) {\n return {\n code: \"backend-error\",\n message: error.message,\n retryable: false,\n detail: {\n name: error.name\n }\n };\n }\n\n return {\n code: \"unknown\",\n message: \"Tool execution failed with a non-Error value.\",\n retryable: false,\n detail: {\n valueType: typeof error\n }\n };\n}\n\n/**\n * Create Dogpile's built-in fetch-based web search adapter.\n *\n * @remarks\n * The adapter is backend-neutral: by default it sends a GET request with\n * `q` and `limit` query parameters, then accepts either `{ results: [...] }`\n * or a bare array of result objects from the response JSON. Callers can replace\n * request construction or response parsing for a specific search API while\n * keeping Dogpile's shared runtime tool contract, identity, permissions, input\n * validation, and serializable errors.\n */\nexport function createWebSearchToolAdapter(\n options: WebSearchToolAdapterOptions\n): RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput> {\n const identity = mergeIdentity(webSearchIdentity, options.identity);\n\n return normalizeBuiltInDogpileTool({\n name: \"webSearch\",\n ...(options.identity ? { identity: options.identity } : {}),\n ...(options.permissions ? { permissions: options.permissions } : {}),\n async execute(input, context): Promise<RuntimeToolResult<WebSearchToolOutput>> {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n if (!fetchImplementation) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"unavailable\",\n message: \"No fetch implementation is available for webSearch.\",\n retryable: false\n }\n };\n }\n\n const request = options.buildRequest\n ? options.buildRequest(input, context)\n : defaultWebSearchRequest(options, input, context);\n const response = await fetchImplementation(request.url, {\n ...request.init,\n ...(context.abortSignal ? { signal: context.abortSignal } : {})\n });\n\n if (!response.ok) {\n throw {\n code: response.status >= 500 ? \"unavailable\" : \"backend-error\",\n message: `Web search backend returned HTTP ${response.status}.`,\n retryable: response.status === 408 || response.status === 429 || response.status >= 500,\n detail: {\n status: response.status,\n statusText: response.statusText\n }\n } satisfies RuntimeToolAdapterError;\n }\n\n const output = options.parseResponse\n ? await options.parseResponse(response, input, context)\n : await defaultWebSearchResponseParser(response);\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n }\n });\n}\n\n/**\n * Create Dogpile's built-in code execution adapter around a caller-owned sandbox.\n *\n * @remarks\n * Dogpile core stays runtime-portable and never evaluates code itself. This\n * adapter supplies the stable `codeExec` identity, schema, permissions,\n * validation, timeout defaults, abort handling, and serializable errors while\n * the host application owns the sandbox boundary.\n */\nexport function createCodeExecToolAdapter(\n options: CodeExecToolAdapterOptions\n): RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput> {\n const identity = mergeIdentity(codeExecIdentity, options.identity);\n const permissions =\n options.permissions ??\n codeExecPermissionsFor(options.languages ?? codeExecLanguages, options.allowNetwork ?? false);\n const inputSchema = codeExecInputSchemaFor(options.languages ?? codeExecLanguages);\n\n return {\n identity,\n inputSchema,\n permissions,\n validateInput: (input: Readonly<CodeExecToolInput>) => validateCodeExecAdapterInput(input, options),\n async execute(input, context): Promise<RuntimeToolResult<CodeExecToolOutput>> {\n const validation = validateCodeExecAdapterInput(input, options);\n\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: \"Invalid codeExec tool input.\",\n retryable: false,\n detail: {\n issues: validation.issues as unknown as JsonValue\n }\n }\n };\n }\n\n const timeoutMs = input.timeoutMs ?? options.defaultTimeoutMs;\n const executionInput: CodeExecToolInput =\n timeoutMs === undefined\n ? input\n : {\n ...input,\n timeoutMs\n };\n\n try {\n const output = await executeSandboxWithPolicy(options.execute, executionInput, context, timeoutMs);\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n }\n };\n}\n\n/**\n * Normalize one built-in Dogpile tool definition into the shared runtime tool interface.\n */\nexport function normalizeBuiltInDogpileTool(\n definition: WebSearchDogpileToolDefinition\n): RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput>;\nexport function normalizeBuiltInDogpileTool(\n definition: CodeExecDogpileToolDefinition\n): RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput>;\nexport function normalizeBuiltInDogpileTool(definition: BuiltInDogpileToolDefinition): BuiltInDogpileRuntimeTool {\n switch (definition.name) {\n case \"webSearch\": {\n const identity = mergeIdentity(webSearchIdentity, definition.identity);\n const permissions = definition.permissions ?? webSearchPermissions;\n const tool: RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput> = {\n identity,\n inputSchema: definition.inputSchema ?? webSearchInputSchema,\n permissions,\n validateInput: (input: Readonly<WebSearchToolInput>) => validateBuiltInDogpileToolInput(\"webSearch\", input),\n execute: (input: Readonly<WebSearchToolInput>, context: RuntimeToolExecutionContext) =>\n executeBuiltInTool(identity, definition.execute, input, context, \"webSearch\")\n };\n return tool;\n }\n case \"codeExec\": {\n const identity = mergeIdentity(codeExecIdentity, definition.identity);\n const permissions = definition.permissions ?? codeExecPermissions;\n const tool: RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput> = {\n identity,\n inputSchema: definition.inputSchema ?? codeExecInputSchema,\n permissions,\n validateInput: (input: Readonly<CodeExecToolInput>) => validateBuiltInDogpileToolInput(\"codeExec\", input),\n execute: (input: Readonly<CodeExecToolInput>, context: RuntimeToolExecutionContext) =>\n executeBuiltInTool(identity, definition.execute, input, context, \"codeExec\")\n };\n return tool;\n }\n }\n}\n\n/**\n * Normalize configured built-in Dogpile tool executors into runtime tools.\n */\nexport function normalizeBuiltInDogpileTools(tools: BuiltInDogpileToolExecutors): readonly BuiltInDogpileRuntimeTool[] {\n const normalized: BuiltInDogpileRuntimeTool[] = [];\n\n if (tools.webSearch) {\n normalized.push(normalizeBuiltInDogpileTool(asWebSearchDefinition(tools.webSearch)));\n }\n\n if (tools.codeExec) {\n normalized.push(normalizeBuiltInDogpileTool(asCodeExecDefinition(tools.codeExec)));\n }\n\n return normalized;\n}\n\n/**\n * Normalize one Vercel AI SDK tool into Dogpile's shared runtime tool interface.\n */\nexport async function normalizeVercelAITool<\n Name extends string,\n Input extends JsonObject,\n Output extends JsonValue\n>(definition: VercelAIToolDefinition<Name, Input, Output>): Promise<RuntimeTool<Input, Output>> {\n if (!definition.tool.execute) {\n throw new Error(`Vercel AI tool \"${definition.name}\" must define execute() to run inside Dogpile.`);\n }\n\n const identity = vercelAIToolIdentity(definition);\n const inputSchema = definition.inputSchema ?? (await vercelAIInputSchema(definition.tool, definition.name));\n const execute = definition.tool.execute;\n\n return {\n identity,\n inputSchema,\n async execute(input, context): Promise<RuntimeToolResult<Output>> {\n try {\n const output = await resolveVercelAIToolOutput(\n execute(input, {\n toolCallId: context.toolCallId,\n messages: Array.from(definition.messages ?? []),\n ...(context.abortSignal ? { abortSignal: context.abortSignal } : {}),\n experimental_context: context\n })\n );\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"vercel-ai-tool-error\",\n message: error instanceof Error ? error.message : \"Vercel AI tool execution failed.\",\n retryable: false,\n detail: errorDetail(error)\n }\n };\n }\n }\n };\n}\n\n/**\n * Normalize a Vercel AI SDK tool set into runtime tools in caller-defined key order.\n */\nexport async function normalizeVercelAITools(\n tools: VercelAIToolSet,\n options: VercelAIToolSetNormalizationOptions = {}\n): Promise<readonly RuntimeTool<JsonObject, JsonValue>[]> {\n return Promise.all(\n Object.entries(tools).map(([name, tool]) => {\n const identity = removeUndefinedIdentityFields({\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...options.identity?.[name]\n });\n return normalizeVercelAITool({\n name,\n tool: asJsonRuntimeVercelAITool(tool),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(identity ? { identity } : {})\n });\n })\n );\n}\n\nasync function executeBuiltInTool<Input extends object, Output>(\n identity: RuntimeToolIdentity,\n execute: (\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext\n ) => RuntimeToolResult<Output> | Promise<RuntimeToolResult<Output>>,\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext,\n name: DogpileBuiltInToolName\n): Promise<RuntimeToolResult<Output>> {\n const validation = validateBuiltInDogpileToolInput(\n name,\n input as Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n );\n\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: `Invalid ${name} tool input.`,\n retryable: false,\n detail: {\n issues: validation.issues as unknown as JsonValue\n }\n }\n };\n }\n\n try {\n return await execute(input, context);\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n}\n\nfunction asWebSearchDefinition(\n tool: WebSearchToolExecutor | WebSearchDogpileToolDefinition\n): WebSearchDogpileToolDefinition {\n return typeof tool === \"function\" ? { name: \"webSearch\", execute: tool } : tool;\n}\n\nfunction asCodeExecDefinition(tool: CodeExecToolExecutor | CodeExecDogpileToolDefinition): CodeExecDogpileToolDefinition {\n return typeof tool === \"function\" ? { name: \"codeExec\", execute: tool } : tool;\n}\n\nfunction mergeIdentity(\n defaultIdentity: RuntimeToolIdentity,\n options: BuiltInDogpileToolIdentityOptions | undefined\n): RuntimeToolIdentity {\n if (!options) {\n return defaultIdentity;\n }\n\n return {\n ...defaultIdentity,\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.description !== undefined ? { description: options.description } : {})\n };\n}\n\nasync function vercelAIInputSchema<Input extends JsonObject, Output extends JsonValue>(\n tool: VercelAITool<Input, Output>,\n name: string\n): Promise<RuntimeToolInputSchema> {\n const schema = await resolveCompatibleSchema(tool.inputSchema);\n const jsonSchema = asJsonObject(schema, `Vercel AI tool \"${name}\" input schema`);\n\n return {\n kind: \"json-schema\",\n schema: jsonSchema,\n ...(tool.description ? { description: tool.description } : {})\n };\n}\n\nasync function resolveCompatibleSchema<Input>(schema: VercelAICompatibleSchema<Input>): Promise<unknown> {\n if (isJsonSchemaWrapper(schema)) {\n return await schema.jsonSchema;\n }\n\n return schema;\n}\n\nfunction isJsonSchemaWrapper<Input>(\n schema: VercelAICompatibleSchema<Input>\n): schema is { readonly jsonSchema: unknown | PromiseLike<unknown> } {\n return typeof schema === \"object\" && schema !== null && \"jsonSchema\" in schema;\n}\n\nfunction vercelAIToolIdentity<Name extends string, Input extends JsonObject, Output extends JsonValue>(\n definition: VercelAIToolDefinition<Name, Input, Output>\n): RuntimeToolIdentity {\n return {\n id: definition.identity?.id ?? `vercel-ai.tools.${definition.name}`,\n name: definition.name,\n namespace: definition.identity?.namespace ?? \"vercel-ai\",\n ...(definition.identity?.version ? { version: definition.identity.version } : {}),\n ...(definition.identity?.description ?? definition.tool.description\n ? { description: definition.identity?.description ?? definition.tool.description }\n : {})\n };\n}\n\nasync function resolveVercelAIToolOutput<Output extends JsonValue>(\n output: AsyncIterable<Output> | PromiseLike<Output> | Output\n): Promise<Output> {\n if (isAsyncIterable(output)) {\n let lastOutput: Output | undefined;\n\n for await (const chunk of output) {\n lastOutput = chunk;\n }\n\n if (lastOutput === undefined) {\n throw new Error(\"Vercel AI tool async iterable completed without an output.\");\n }\n\n return lastOutput;\n }\n\n return await output;\n}\n\nfunction isAsyncIterable<Output extends JsonValue>(\n value: AsyncIterable<Output> | PromiseLike<Output> | Output\n): value is AsyncIterable<Output> {\n return typeof value === \"object\" && value !== null && Symbol.asyncIterator in value;\n}\n\nfunction asJsonObject(value: unknown, label: string): JsonObject {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`${label} must resolve to a JSON object.`);\n }\n\n return value as JsonObject;\n}\n\nfunction errorDetail(error: unknown): JsonObject {\n if (error instanceof Error) {\n return {\n name: error.name\n };\n }\n\n return {\n valueType: typeof error\n };\n}\n\nfunction defaultWebSearchRequest(\n options: WebSearchToolAdapterOptions,\n input: Readonly<WebSearchToolInput>,\n _context: RuntimeToolExecutionContext\n): WebSearchFetchRequest {\n const url = new URL(String(options.endpoint));\n url.searchParams.set(\"q\", input.query);\n url.searchParams.set(\"limit\", String(input.maxResults ?? options.defaultMaxResults ?? 10));\n\n return {\n url,\n init: {\n method: \"GET\",\n ...(options.headers ? { headers: options.headers } : {})\n }\n };\n}\n\nasync function defaultWebSearchResponseParser(response: Response): Promise<WebSearchToolOutput> {\n const payload: unknown = await response.json();\n const resultValues = Array.isArray(payload)\n ? payload\n : isJsonObject(payload) && Array.isArray(payload.results)\n ? payload.results\n : undefined;\n\n if (!resultValues) {\n throw {\n code: \"backend-error\",\n message: \"Web search backend response must contain a results array.\",\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return {\n results: resultValues.map(normalizeWebSearchResult)\n };\n}\n\nfunction codeExecPermissionsFor(\n languages: readonly CodeExecToolLanguage[],\n allowNetwork: boolean\n): readonly RuntimeToolPermission[] {\n return [\n {\n kind: \"code-execution\",\n sandbox: \"caller-provided\",\n languages,\n allowNetwork\n }\n ];\n}\n\nfunction codeExecInputSchemaFor(languages: readonly CodeExecToolLanguage[]): RuntimeToolInputSchema {\n return {\n kind: \"json-schema\",\n ...(codeExecInputSchema.description ? { description: codeExecInputSchema.description } : {}),\n schema: {\n type: \"object\",\n properties: {\n language: {\n type: \"string\",\n enum: Array.from(languages)\n },\n code: { type: \"string\" },\n timeoutMs: { type: \"number\", minimum: 1 }\n },\n required: [\"language\", \"code\"],\n additionalProperties: false\n }\n };\n}\n\nasync function executeSandboxWithPolicy(\n execute: CodeExecSandboxExecutor,\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext,\n timeoutMs: number | undefined\n): Promise<CodeExecToolOutput> {\n if (context.abortSignal?.aborted) {\n throw {\n code: \"aborted\",\n message: \"Code execution was aborted before the sandbox started.\",\n retryable: true\n } satisfies RuntimeToolAdapterError;\n }\n\n const execution = Promise.resolve().then(() => execute(input, context));\n\n if (timeoutMs === undefined && context.abortSignal === undefined) {\n return await execution;\n }\n\n return await new Promise<CodeExecToolOutput>((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = (): void => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n context.abortSignal?.removeEventListener(\"abort\", abortHandler);\n };\n\n const abortHandler = (): void => {\n cleanup();\n reject({\n code: \"aborted\",\n message: \"Code execution was aborted.\",\n retryable: true\n } satisfies RuntimeToolAdapterError);\n };\n\n if (context.abortSignal) {\n context.abortSignal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n if (timeoutMs !== undefined) {\n timeoutId = setTimeout(() => {\n cleanup();\n reject({\n code: \"timeout\",\n message: `Code execution exceeded timeout of ${timeoutMs}ms.`,\n retryable: true,\n detail: {\n timeoutMs\n }\n } satisfies RuntimeToolAdapterError);\n }, timeoutMs);\n }\n\n execution.then(\n (output) => {\n cleanup();\n resolve(output);\n },\n (error: unknown) => {\n cleanup();\n reject(error);\n }\n );\n });\n}\n\nfunction normalizeWebSearchResult(value: unknown): WebSearchToolResult {\n if (!isJsonObject(value)) {\n throw {\n code: \"backend-error\",\n message: \"Web search result must be a JSON object.\",\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n const title = jsonString(value.title, \"title\");\n const url = jsonString(value.url, \"url\");\n const snippet = optionalJsonString(value.snippet, \"snippet\");\n const metadata = optionalJsonObject(value.metadata, \"metadata\");\n\n return {\n title,\n url,\n ...(snippet !== undefined ? { snippet } : {}),\n ...(metadata !== undefined ? { metadata } : {})\n };\n}\n\nfunction jsonString(value: JsonValue | undefined, fieldName: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a non-empty string.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction optionalJsonString(value: JsonValue | undefined, fieldName: string): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\") {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a string when present.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction optionalJsonObject(value: JsonValue | undefined, fieldName: string): JsonObject | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isJsonObject(value)) {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a JSON object when present.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction validateWebSearchInput(input: Readonly<Partial<WebSearchToolInput>>): readonly RuntimeToolValidationIssue[] {\n const issues: RuntimeToolValidationIssue[] = [];\n\n if (typeof input.query !== \"string\") {\n issues.push({\n code: input.query === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"query\",\n message: \"webSearch.query must be a string.\"\n });\n } else if (input.query.trim().length === 0) {\n issues.push({\n code: \"invalid-value\",\n path: \"query\",\n message: \"webSearch.query must not be empty.\"\n });\n }\n\n if (input.maxResults !== undefined) {\n if (typeof input.maxResults !== \"number\" || !Number.isFinite(input.maxResults)) {\n issues.push({\n code: \"invalid-type\",\n path: \"maxResults\",\n message: \"webSearch.maxResults must be a finite number.\"\n });\n } else if (input.maxResults < 1) {\n issues.push({\n code: \"out-of-range\",\n path: \"maxResults\",\n message: \"webSearch.maxResults must be greater than or equal to 1.\",\n detail: {\n minimum: 1\n }\n });\n }\n }\n\n return issues;\n}\n\nfunction validateCodeExecInput(input: Readonly<Partial<CodeExecToolInput>>): readonly RuntimeToolValidationIssue[] {\n const issues: RuntimeToolValidationIssue[] = [];\n\n if (typeof input.language !== \"string\") {\n issues.push({\n code: input.language === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"language\",\n message: \"codeExec.language must be a string.\"\n });\n } else if (!isCodeExecLanguage(input.language)) {\n issues.push({\n code: \"invalid-value\",\n path: \"language\",\n message: \"codeExec.language must be one of javascript, typescript, python, bash, or shell.\",\n detail: {\n allowed: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"]\n }\n });\n }\n\n if (typeof input.code !== \"string\") {\n issues.push({\n code: input.code === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"code\",\n message: \"codeExec.code must be a string.\"\n });\n }\n\n if (input.timeoutMs !== undefined) {\n if (typeof input.timeoutMs !== \"number\" || !Number.isFinite(input.timeoutMs)) {\n issues.push({\n code: \"invalid-type\",\n path: \"timeoutMs\",\n message: \"codeExec.timeoutMs must be a finite number.\"\n });\n } else if (input.timeoutMs < 1) {\n issues.push({\n code: \"out-of-range\",\n path: \"timeoutMs\",\n message: \"codeExec.timeoutMs must be greater than or equal to 1.\",\n detail: {\n minimum: 1\n }\n });\n }\n }\n\n return issues;\n}\n\nfunction isCodeExecLanguage(value: string): value is CodeExecToolInput[\"language\"] {\n return value === \"javascript\" || value === \"typescript\" || value === \"python\" || value === \"bash\" || value === \"shell\";\n}\n\nfunction isRuntimeToolAdapterError(error: unknown): error is RuntimeToolAdapterError {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error) || !(\"message\" in error)) {\n return false;\n }\n\n const candidate = error as { readonly code: unknown; readonly message: unknown };\n return isRuntimeToolAdapterErrorCode(candidate.code) && typeof candidate.message === \"string\";\n}\n\nfunction isRuntimeToolAdapterErrorCode(value: unknown): value is RuntimeToolAdapterError[\"code\"] {\n return (\n value === \"invalid-input\" ||\n value === \"permission-denied\" ||\n value === \"timeout\" ||\n value === \"aborted\" ||\n value === \"unavailable\" ||\n value === \"backend-error\" ||\n value === \"unknown\"\n );\n}\n\nfunction removeUndefinedIdentityFields(\n identity: VercelAIToolIdentityOptions\n): VercelAIToolIdentityOptions | undefined {\n const normalized: VercelAIToolIdentityOptions = {\n ...(identity.id !== undefined ? { id: identity.id } : {}),\n ...(identity.namespace !== undefined ? { namespace: identity.namespace } : {}),\n ...(identity.version !== undefined ? { version: identity.version } : {}),\n ...(identity.description !== undefined ? { description: identity.description } : {})\n };\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction asJsonRuntimeVercelAITool(tool: VercelAIToolSetEntry): VercelAITool<JsonObject, JsonValue> {\n return tool as unknown as VercelAITool<JsonObject, JsonValue>;\n}\n","import type {\n AgentSpec,\n BroadcastContribution,\n BroadcastProtocolConfig,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\n\ninterface BroadcastRunOptions {\n readonly intent: string;\n readonly protocol: BroadcastProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runBroadcast(options: BroadcastRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxRounds = options.protocol.maxRounds ?? 2;\n let firstRoundContributions: readonly BroadcastContribution[] = [];\n let lastContributions: readonly BroadcastContribution[] = [];\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"broadcast\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of options.agents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n for (let round = 1; round <= maxRounds; round += 1) {\n if (stopIfNeeded()) {\n break;\n }\n\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const turnResults = await Promise.all(\n options.agents.map(async (agent, agentIndex) => {\n const turn = transcript.length + agentIndex + 1;\n const input = buildBroadcastInput(options.intent, round, maxRounds, firstRoundContributions);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"broadcast\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n round,\n ...toolAvailability\n },\n messages: [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ]\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: providerCallIdFor(runId, providerCalls.length + agentIndex + 1),\n onProviderCall(call): void {\n providerCallSlots[agentIndex] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn,\n metadata: {\n round\n }\n });\n throwIfAborted(options.signal, options.model.id);\n\n return {\n agent,\n agentIndex,\n turn,\n input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n })\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n const contributions: BroadcastContribution[] = [];\n for (const result of turnResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n contributions.push({\n agentId: result.agent.id,\n role: result.agent.role,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n round,\n turn: result.turn,\n transcriptEntryCount: transcript.length,\n contributionCount: result.agentIndex + 1\n });\n }\n\n if (contributions.length === 0) {\n break;\n }\n if (round === 1) {\n firstRoundContributions = contributions;\n }\n lastContributions = contributions;\n\n const broadcast: RunEvent = {\n type: \"broadcast\",\n runId,\n at: new Date().toISOString(),\n round,\n contributions,\n cost: totalCost\n };\n emit(broadcast);\n recordProtocolDecision(broadcast, {\n round,\n transcriptEntryCount: transcript.length,\n contributionCount: contributions.length\n });\n\n if (stopIfNeeded()) {\n break;\n }\n }\n\n const output = synthesizeBroadcastOutput(lastContributions);\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"broadcast\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: options.agents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: options.agents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: options.agents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(options.terminate, {\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n });\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Broadcast multi-agent protocol.${instruction}`;\n}\n\nfunction buildBroadcastInput(\n intent: string,\n round: number,\n maxRounds: number,\n firstRoundContributions: readonly BroadcastContribution[]\n): string {\n if (maxRounds === 1) {\n return `Mission: ${intent}\\nBroadcast round ${round}: contribute independently before synthesis.`;\n }\n if (round === 1) {\n return `Mission: ${intent}\\nBroadcast round 1: broadcast your intended role and participation decision. Do not produce the final plan yet.`;\n }\n\n const intentions = firstRoundContributions\n .map((contribution) => `${contribution.role}:${contribution.agentId} => ${contribution.output}`)\n .join(\"\\n\");\n return `Mission: ${intent}\\n\\nRound 1 intentions:\\n${intentions || \"(none)\"}\\n\\nBroadcast round ${round}: make your final contribution or abstention decision informed by all round 1 intentions.`;\n}\n\nfunction synthesizeBroadcastOutput(contributions: readonly BroadcastContribution[]): string {\n return contributions.map((entry) => `${entry.role}:${entry.agentId} => ${entry.output}`).join(\"\\n\");\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CoordinatorProtocolConfig,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RuntimeToolExecutor,\n RunEvent,\n RunResult,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost,\n nextProviderCallId\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\n\ninterface CoordinatorRunOptions {\n readonly intent: string;\n readonly protocol: CoordinatorProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runCoordinator(options: CoordinatorRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const coordinator = activeAgents[0];\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"coordinator\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n if (coordinator) {\n if (!stopIfNeeded()) {\n totalCost = await runCoordinatorTurn({\n agent: coordinator,\n coordinator,\n input: buildCoordinatorPlanInput(options.intent, coordinator),\n phase: \"plan\",\n options,\n runId,\n transcript,\n totalCost,\n providerCalls,\n toolExecutor,\n toolAvailability,\n emit,\n recordProtocolDecision\n });\n stopIfNeeded();\n }\n\n if (!stopIfNeeded()) {\n const workers = activeAgents.slice(1);\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const planTranscript = [...transcript];\n const workerResults = await Promise.all(\n workers.map((agent, index) =>\n runCoordinatorWorkerTurn({\n agent,\n coordinator,\n input: buildWorkerInput(options.intent, planTranscript, coordinator),\n options,\n runId,\n turn: transcript.length + index + 1,\n providerCallId: providerCallIdFor(runId, providerCalls.length + index + 1),\n providerCallIndex: index,\n providerCallSlots,\n toolExecutor,\n toolAvailability,\n emit\n })\n )\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n for (const result of workerResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn: transcript.length,\n phase: \"worker\",\n transcriptEntryCount: transcript.length\n });\n }\n stopIfNeeded();\n }\n\n if (!stopIfNeeded()) {\n totalCost = await runCoordinatorTurn({\n agent: coordinator,\n coordinator,\n input: buildFinalSynthesisInput(options.intent, transcript, coordinator),\n phase: \"final-synthesis\",\n options,\n runId,\n transcript,\n totalCost,\n providerCalls,\n toolExecutor,\n toolAvailability,\n emit,\n recordProtocolDecision\n });\n stopIfNeeded();\n }\n }\n\n const output = transcript.at(-1)?.output ?? \"\";\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"coordinator\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(options.terminate, {\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n });\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\ninterface CoordinatorTurnOptions {\n readonly agent: AgentSpec;\n readonly coordinator: AgentSpec;\n readonly input: string;\n readonly phase: \"plan\" | \"worker\" | \"final-synthesis\";\n readonly options: CoordinatorRunOptions;\n readonly runId: string;\n readonly transcript: TranscriptEntry[];\n readonly totalCost: CostSummary;\n readonly providerCalls: ReplayTraceProviderCall[];\n readonly toolExecutor: RuntimeToolExecutor;\n readonly toolAvailability: JsonObject;\n readonly emit: (event: RunEvent) => void;\n readonly recordProtocolDecision: (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ) => void;\n}\n\nasync function runCoordinatorTurn(turn: CoordinatorTurnOptions): Promise<CostSummary> {\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n const request: ModelRequest = {\n temperature: turn.options.temperature,\n ...(turn.options.signal !== undefined ? { signal: turn.options.signal } : {}),\n metadata: {\n runId: turn.runId,\n protocol: \"coordinator\",\n agentId: turn.agent.id,\n role: turn.agent.role,\n coordinatorAgentId: turn.coordinator.id,\n tier: turn.options.tier,\n phase: turn.phase,\n ...turn.toolAvailability\n },\n messages: [\n {\n role: \"system\",\n content: buildSystemPrompt(turn.agent, turn.coordinator)\n },\n {\n role: \"user\",\n content: turn.input\n }\n ]\n };\n const response = await generateModelTurn({\n model: turn.options.model,\n request,\n runId: turn.runId,\n agent: turn.agent,\n input: turn.input,\n emit: turn.emit,\n callId: nextProviderCallId(turn.runId, turn.providerCalls),\n onProviderCall(call): void {\n turn.providerCalls.push(call);\n }\n });\n const decision = parseAgentDecision(response.text);\n const totalCost = addCost(turn.totalCost, responseCost(response));\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: turn.toolExecutor,\n agentId: turn.agent.id,\n role: turn.agent.role,\n turn: turn.transcript.length + 1,\n metadata: {\n phase: turn.phase\n }\n });\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n turn.transcript.push({\n agentId: turn.agent.id,\n role: turn.agent.role,\n input: turn.input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n ...(toolCalls.length > 0 ? { toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId: turn.runId,\n at: new Date().toISOString(),\n agentId: turn.agent.id,\n role: turn.agent.role,\n input: turn.input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n cost: totalCost\n };\n turn.emit(event);\n turn.recordProtocolDecision(event, {\n turn: turn.transcript.length,\n phase: turn.phase,\n transcriptEntryCount: turn.transcript.length\n });\n\n return totalCost;\n}\n\ninterface CoordinatorWorkerTurnOptions {\n readonly agent: AgentSpec;\n readonly coordinator: AgentSpec;\n readonly input: string;\n readonly options: CoordinatorRunOptions;\n readonly runId: string;\n readonly turn: number;\n readonly providerCallId: string;\n readonly providerCallIndex: number;\n readonly providerCallSlots: ReplayTraceProviderCall[];\n readonly toolExecutor: RuntimeToolExecutor;\n readonly toolAvailability: JsonObject;\n readonly emit: (event: RunEvent) => void;\n}\n\ninterface CoordinatorWorkerTurnResult {\n readonly agent: AgentSpec;\n readonly input: string;\n readonly response: ModelResponse;\n readonly decision: ReturnType<typeof parseAgentDecision>;\n readonly toolCalls: Awaited<ReturnType<typeof executeModelResponseToolRequests>>;\n readonly turnCost: CostSummary;\n}\n\nasync function runCoordinatorWorkerTurn(turn: CoordinatorWorkerTurnOptions): Promise<CoordinatorWorkerTurnResult> {\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n const request: ModelRequest = {\n temperature: turn.options.temperature,\n ...(turn.options.signal !== undefined ? { signal: turn.options.signal } : {}),\n metadata: {\n runId: turn.runId,\n protocol: \"coordinator\",\n agentId: turn.agent.id,\n role: turn.agent.role,\n coordinatorAgentId: turn.coordinator.id,\n tier: turn.options.tier,\n phase: \"worker\",\n ...turn.toolAvailability\n },\n messages: [\n {\n role: \"system\",\n content: buildSystemPrompt(turn.agent, turn.coordinator)\n },\n {\n role: \"user\",\n content: turn.input\n }\n ]\n };\n const response = await generateModelTurn({\n model: turn.options.model,\n request,\n runId: turn.runId,\n agent: turn.agent,\n input: turn.input,\n emit: turn.emit,\n callId: turn.providerCallId,\n onProviderCall(call): void {\n turn.providerCallSlots[turn.providerCallIndex] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: turn.toolExecutor,\n agentId: turn.agent.id,\n role: turn.agent.role,\n turn: turn.turn,\n metadata: {\n phase: \"worker\"\n }\n });\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n return {\n agent: turn.agent,\n input: turn.input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n}\n\nfunction buildSystemPrompt(agent: AgentSpec, coordinator: AgentSpec | undefined): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n const coordinatorText =\n coordinator && agent.id === coordinator.id\n ? \"You are the coordinator: assign work, integrate worker contributions, and produce the final answer.\"\n : `You are a worker managed by coordinator ${coordinator?.id ?? \"unknown\"}.`;\n return `You are ${agent.id}, acting as ${agent.role} in a Coordinator multi-agent protocol. ${coordinatorText}${instruction}`;\n}\n\nfunction buildCoordinatorPlanInput(intent: string, coordinator: AgentSpec): string {\n return `Mission: ${intent}\\nCoordinator ${coordinator.id}: assign the work, name the plan, and provide the first contribution.`;\n}\n\nfunction buildWorkerInput(\n intent: string,\n transcript: readonly TranscriptEntry[],\n coordinator: AgentSpec\n): string {\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nCoordinator: ${coordinator.id}\\nPrior contributions:\\n${prior}\\n\\nFollow the coordinator-managed plan and provide your assigned contribution.`;\n}\n\nfunction buildFinalSynthesisInput(\n intent: string,\n transcript: readonly TranscriptEntry[],\n coordinator: AgentSpec\n): string {\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nCoordinator: ${coordinator.id}\\nPrior contributions:\\n${prior}\\n\\nSynthesize the final answer as the coordinator.`;\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n JsonObject,\n JsonValue,\n SequentialProtocolConfig,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost,\n nextProviderCallId\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { isParticipatingDecision, parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\n\ninterface SequentialRunOptions {\n readonly intent: string;\n readonly protocol: SequentialProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runSequential(options: SequentialRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"sequential\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n for (const [index, agent] of activeAgents.entries()) {\n if (stopIfNeeded()) {\n break;\n }\n\n const turn = index + 1;\n const input = buildSequentialInput(options.intent, transcript);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"sequential\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n turn,\n ...toolAvailability\n },\n messages: [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ]\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: nextProviderCallId(runId, providerCalls),\n onProviderCall(call): void {\n providerCalls.push(call);\n }\n });\n const turnCost = responseCost(response);\n totalCost = addCost(totalCost, turnCost);\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn\n });\n throwIfAborted(options.signal, options.model.id);\n\n transcript.push({\n agentId: agent.id,\n role: agent.role,\n input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n ...(toolCalls.length > 0 ? { toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role,\n input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn,\n transcriptEntryCount: transcript.length\n });\n\n if (stopIfNeeded()) {\n break;\n }\n }\n\n const output = [...transcript].reverse().find((entry) => isParticipatingDecision(entry.decision))?.output ?? \"\";\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"sequential\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? events[0] ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(options.terminate, {\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n });\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Sequential multi-agent protocol.${instruction}`;\n}\n\nfunction buildSequentialInput(intent: string, transcript: readonly TranscriptEntry[]): string {\n if (transcript.length === 0) {\n return `Mission: ${intent}\\nProvide your contribution.`;\n }\n\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nPrior contributions:\\n${prior}\\n\\nContinue the sequence with a useful next contribution.`;\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n SharedProtocolConfig,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\n\ninterface SharedRunOptions {\n readonly intent: string;\n readonly protocol: SharedProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runShared(options: SharedRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const sharedState = options.protocol.organizationalMemory ?? \"\";\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(createReplayTraceProtocolDecision(\"shared\", event, events.length - 1, decisionOptions));\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"shared\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n if (!stopIfNeeded()) {\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const turnResults = await Promise.all(\n activeAgents.map(async (agent, index) => {\n const turn = index + 1;\n const input = buildSharedInput(options.intent, sharedState, turn);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"shared\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n turn,\n ...toolAvailability\n },\n messages: [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ]\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: providerCallIdFor(runId, providerCalls.length + index + 1),\n onProviderCall(call): void {\n providerCallSlots[index] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn\n });\n throwIfAborted(options.signal, options.model.id);\n\n return {\n agent,\n turn,\n input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n })\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n for (const result of turnResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn: result.turn,\n transcriptEntryCount: transcript.length\n });\n }\n stopIfNeeded();\n }\n\n const output = synthesizeSharedOutput(transcript);\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"shared\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"shared\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"shared\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(options.terminate, {\n runId,\n protocol: \"shared\",\n tier: options.tier,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n });\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Shared multi-agent protocol. Read the shared state, update it with your best contribution, and preserve useful prior work.${instruction}`;\n}\n\nfunction buildSharedInput(intent: string, sharedState: string, turn: number): string {\n const state = sharedState ? sharedState : \"(empty)\";\n return `Mission: ${intent}\\nShared turn ${turn}: read the shared state and return an improved shared-state update.\\n\\nShared state:\\n${state}`;\n}\n\nfunction synthesizeSharedOutput(transcript: readonly TranscriptEntry[]): string {\n return transcript.map((entry) => `${entry.role}:${entry.agentId} => ${entry.output}`).join(\"\\n\");\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import { DogpileError } from \"../types.js\";\nimport type {\n BudgetTier,\n DogpileOptions,\n Engine,\n EngineOptions,\n FinalEvent,\n JsonObject,\n JsonValue,\n ProtocolSelection,\n RunEvaluation,\n RunEvent,\n RunResult,\n StreamErrorEvent,\n StreamEvent,\n StreamEventSubscriber,\n StreamHandle,\n StreamHandleStatus,\n Trace\n} from \"../types.js\";\nimport { runBroadcast } from \"./broadcast.js\";\nimport { runCoordinator } from \"./coordinator.js\";\nimport {\n createReplayTraceFinalOutput,\n createReplayTraceBudgetStateChanges,\n canonicalizeRunResult,\n canonicalizeSerializable,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n defaultAgents,\n normalizeProtocol,\n orderAgentsForTemperature,\n tierTemperature\n} from \"./defaults.js\";\nimport { runSequential } from \"./sequential.js\";\nimport { runShared } from \"./shared.js\";\nimport { createAbortErrorFromSignal, createTimeoutError } from \"./cancellation.js\";\nimport { budget as budgetCondition } from \"./termination.js\";\nimport { validateDogpileOptions, validateEngineOptions, validateMissionIntent } from \"./validation.js\";\n\nconst defaultHighLevelProtocol = \"sequential\";\nconst defaultHighLevelTier = \"balanced\";\n\ntype NormalizedDogpileOptions = Omit<DogpileOptions, \"protocol\" | \"tier\"> & {\n readonly protocol: ProtocolSelection;\n readonly tier: BudgetTier;\n};\n\n/**\n * Create a reusable low-level protocol engine.\n *\n * @remarks\n * Use this escape hatch to hold protocol, tier, model, agents, and budget caps\n * constant across repeated missions. Most application code can call\n * {@link run}, {@link stream}, or {@link Dogpile.pile} directly.\n *\n * The returned engine is stateless between calls: each `run()` or `stream()`\n * invocation produces its own serializable trace, event log, and transcript.\n */\nexport function createEngine(options: EngineOptions): Engine {\n validateEngineOptions(options);\n\n const protocol = normalizeProtocol(options.protocol);\n const tools = options.tools ?? [];\n const temperature = options.temperature ?? tierTemperature(options.tier);\n const agents = orderAgentsForTemperature(options.agents ?? defaultAgents(), temperature, options.seed);\n const terminate = options.terminate ?? (options.budget ? conditionFromBudget(options.budget) : undefined);\n\n return {\n run(intent: string): Promise<RunResult> {\n validateMissionIntent(intent);\n\n return runNonStreamingProtocol({\n intent,\n protocol,\n tier: options.tier,\n model: options.model,\n agents,\n tools,\n temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(terminate ? { terminate } : {}),\n ...(options.evaluate ? { evaluate: options.evaluate } : {})\n });\n },\n\n stream(intent: string): StreamHandle {\n validateMissionIntent(intent);\n\n const pendingEvents: StreamEvent[] = [];\n const pendingResolvers: Array<(value: IteratorResult<StreamEvent>) => void> = [];\n const emittedEvents: StreamEvent[] = [];\n const subscribers = new Set<StreamEventSubscriber>();\n const abortController = new AbortController();\n const timeoutLifecycle = createTimeoutAbortLifecycle({\n abortController,\n timeoutMs: runtimeTimeoutMs({ budget: options.budget, terminate }),\n providerId: options.model.id\n });\n const abortRace = createAbortRace(abortController.signal, options.model.id);\n let complete = false;\n let lastRunId = \"\";\n let pendingFinalEvent: FinalEvent | undefined;\n let status: StreamHandleStatus = \"running\";\n let resolveResult!: (result: RunResult) => void;\n let rejectResult!: (error: unknown) => void;\n let removeCallerAbortListener = (): void => {};\n\n const result = new Promise<RunResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n removeCallerAbortListener = wireCallerAbortSignal(options.signal, abortController, cancelRun);\n void execute();\n\n return {\n get status(): StreamHandleStatus {\n return status;\n },\n result,\n cancel(): void {\n cancelRun();\n },\n subscribe(subscriber: StreamEventSubscriber) {\n subscribers.add(subscriber);\n\n for (const event of emittedEvents) {\n subscriber(event);\n }\n\n return {\n unsubscribe(): void {\n subscribers.delete(subscriber);\n }\n };\n },\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n return {\n next(): Promise<IteratorResult<StreamEvent>> {\n const event = pendingEvents.shift();\n if (event) {\n return Promise.resolve({ done: false, value: event });\n }\n if (complete) {\n return Promise.resolve({ done: true, value: undefined });\n }\n return new Promise<IteratorResult<StreamEvent>>((resolve) => {\n pendingResolvers.push(resolve);\n });\n }\n };\n }\n };\n\n async function execute(): Promise<void> {\n if (status !== \"running\") {\n return;\n }\n\n try {\n const baseResult = await abortRace.run(runProtocol({\n intent,\n protocol,\n tier: options.tier,\n model: options.model,\n agents,\n tools,\n temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n signal: abortController.signal,\n ...(terminate ? { terminate } : {}),\n emit(event: RunEvent): void {\n if (status !== \"running\") {\n return;\n }\n\n lastRunId = event.runId;\n if (event.type === \"final\") {\n pendingFinalEvent = event;\n return;\n }\n publish(event);\n }\n }));\n if (status !== \"running\") {\n return;\n }\n\n const finalizedResult = await abortRace.run(applyRunEvaluation(baseResult, options.evaluate));\n if (status !== \"running\") {\n return;\n }\n\n const finalEvent = finalizedResult.trace.events.at(-1);\n if (finalEvent?.type === \"final\") {\n publish(finalEvent);\n } else if (pendingFinalEvent) {\n publish(pendingFinalEvent);\n }\n status = \"completed\";\n closeStream();\n resolveResult(finalizedResult);\n } catch (error: unknown) {\n if (isStreamHandleStatus(status, \"cancelled\")) {\n return;\n }\n\n const runtimeError = timeoutLifecycle.translateError(error);\n status = isCancellationError(runtimeError) ? \"cancelled\" : \"failed\";\n publish(createStreamErrorEvent(runtimeError, lastRunId));\n closeStream();\n rejectResult(runtimeError);\n }\n }\n\n function cancelRun(cause?: unknown): void {\n if (status !== \"running\") {\n return;\n }\n\n const error = createStreamCancellationError(options.model.id, cause);\n status = \"cancelled\";\n abortController.abort(error);\n publish(createStreamErrorEvent(error, lastRunId));\n closeStream();\n rejectResult(error);\n }\n\n function closeStream(): void {\n if (complete) {\n return;\n }\n\n complete = true;\n removeCallerAbortListener();\n timeoutLifecycle.cleanup();\n abortRace.cleanup();\n subscribers.clear();\n for (const resolver of pendingResolvers.splice(0)) {\n resolver({ done: true, value: undefined });\n }\n }\n\n function publish(event: StreamEvent): void {\n if (complete) {\n return;\n }\n\n const canonicalEvent = canonicalizeSerializable(event);\n emittedEvents.push(canonicalEvent);\n\n for (const subscriber of subscribers) {\n try {\n subscriber(canonicalEvent);\n } catch {\n // Subscriber failures should not cancel the underlying SDK run.\n }\n }\n\n const resolver = pendingResolvers.shift();\n if (resolver) {\n resolver({ done: false, value: canonicalEvent });\n return;\n }\n pendingEvents.push(canonicalEvent);\n }\n }\n };\n}\n\nfunction isStreamHandleStatus(status: StreamHandleStatus, expected: StreamHandleStatus): boolean {\n return status === expected;\n}\n\nfunction conditionFromBudget(budget: NonNullable<EngineOptions[\"budget\"]>): ReturnType<typeof budgetCondition> {\n return budgetCondition({\n ...(budget.maxUsd !== undefined ? { maxUsd: budget.maxUsd } : {}),\n ...(budget.maxTokens !== undefined ? { maxTokens: budget.maxTokens } : {}),\n ...(budget.maxIterations !== undefined ? { maxIterations: budget.maxIterations } : {}),\n ...(budget.timeoutMs !== undefined ? { timeoutMs: budget.timeoutMs } : {})\n });\n}\n\ninterface AbortLifecycle {\n readonly signal: AbortSignal | undefined;\n run<T>(operation: Promise<T>): Promise<T>;\n translateError(error: unknown): unknown;\n cleanup(): void;\n}\n\ninterface TimeoutAbortLifecycle {\n translateError(error: unknown): unknown;\n cleanup(): void;\n}\n\nfunction createNonStreamingAbortLifecycle(options: {\n readonly callerSignal?: AbortSignal | undefined;\n readonly timeoutMs?: number | undefined;\n readonly providerId: string;\n}): AbortLifecycle {\n if (options.timeoutMs === undefined) {\n return {\n signal: options.callerSignal,\n async run<T>(operation: Promise<T>): Promise<T> {\n return await operation;\n },\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {}\n };\n }\n\n const abortController = new AbortController();\n const timeoutLifecycle = createTimeoutAbortLifecycle({\n abortController,\n timeoutMs: options.timeoutMs,\n providerId: options.providerId\n });\n const abortRace = createAbortRace(abortController.signal, options.providerId);\n const removeCallerAbortListener = wireCallerAbortSignal(options.callerSignal, abortController, () => {\n abortController.abort(readAbortSignalReason(options.callerSignal));\n });\n\n return {\n signal: abortController.signal,\n async run<T>(operation: Promise<T>): Promise<T> {\n return await abortRace.run(operation);\n },\n translateError(error: unknown): unknown {\n return timeoutLifecycle.translateError(error);\n },\n cleanup(): void {\n timeoutLifecycle.cleanup();\n abortRace.cleanup();\n removeCallerAbortListener();\n }\n };\n}\n\nfunction createTimeoutAbortLifecycle(options: {\n readonly abortController: AbortController;\n readonly timeoutMs?: number | undefined;\n readonly providerId: string;\n}): TimeoutAbortLifecycle {\n if (options.timeoutMs === undefined) {\n return {\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {}\n };\n }\n\n const timeoutError = createTimeoutError(options.providerId, options.timeoutMs);\n const timeoutId = setTimeout(() => {\n options.abortController.abort(timeoutError);\n }, options.timeoutMs);\n\n return {\n translateError(error: unknown): unknown {\n return options.abortController.signal.reason === timeoutError ? timeoutError : error;\n },\n cleanup(): void {\n clearTimeout(timeoutId);\n }\n };\n}\n\nfunction createAbortRace(signal: AbortSignal, providerId: string): AbortLifecycle {\n let cleanupAbortListener = (): void => {};\n\n return {\n signal,\n async run<T>(operation: Promise<T>): Promise<T> {\n if (signal.aborted) {\n throw createAbortErrorFromSignal(signal, providerId);\n }\n\n const abortPromise = new Promise<never>((_, reject) => {\n const abortHandler = (): void => {\n cleanupAbortListener();\n reject(createAbortErrorFromSignal(signal, providerId));\n };\n\n cleanupAbortListener = (): void => {\n signal.removeEventListener(\"abort\", abortHandler);\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n });\n\n try {\n return await Promise.race([operation, abortPromise]);\n } finally {\n cleanupAbortListener();\n cleanupAbortListener = (): void => {};\n }\n },\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {\n cleanupAbortListener();\n cleanupAbortListener = (): void => {};\n }\n };\n}\n\nfunction runtimeTimeoutMs(options: {\n readonly budget?: EngineOptions[\"budget\"] | undefined;\n readonly terminate?: EngineOptions[\"terminate\"] | undefined;\n}): number | undefined {\n const budgetTimeoutMs = options.budget?.timeoutMs;\n const terminationTimeoutMs = timeoutMsFromTermination(options.terminate);\n\n if (budgetTimeoutMs === undefined) {\n return terminationTimeoutMs;\n }\n if (terminationTimeoutMs === undefined) {\n return budgetTimeoutMs;\n }\n return Math.min(budgetTimeoutMs, terminationTimeoutMs);\n}\n\nfunction timeoutMsFromTermination(condition: EngineOptions[\"terminate\"] | undefined): number | undefined {\n if (!condition) {\n return undefined;\n }\n\n switch (condition.kind) {\n case \"budget\":\n return condition.timeoutMs;\n case \"firstOf\":\n return condition.conditions.reduce<number | undefined>((current, child) => {\n const childTimeoutMs = timeoutMsFromTermination(child);\n if (childTimeoutMs === undefined) {\n return current;\n }\n return current === undefined ? childTimeoutMs : Math.min(current, childTimeoutMs);\n }, undefined);\n case \"convergence\":\n case \"judge\":\n return undefined;\n }\n}\n\nfunction readAbortSignalReason(signal: AbortSignal | undefined): unknown {\n return signal?.aborted ? signal.reason : undefined;\n}\n\nfunction createStreamErrorEvent(error: unknown, runId: string): StreamErrorEvent {\n if (DogpileError.isInstance(error)) {\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: error.name,\n message: error.message,\n detail: dogpileErrorStreamDetail(error)\n };\n }\n\n if (error instanceof Error) {\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: error.name,\n message: error.message\n };\n }\n\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: \"Error\",\n message: String(error)\n };\n}\n\nfunction dogpileErrorStreamDetail(error: DogpileError): JsonObject {\n const detail: Record<string, JsonValue> = {\n code: error.code\n };\n\n if (error.providerId !== undefined) {\n detail.providerId = error.providerId;\n }\n if (error.retryable !== undefined) {\n detail.retryable = error.retryable;\n }\n if (error.detail !== undefined) {\n for (const [key, value] of Object.entries(error.detail)) {\n detail[key] = value;\n }\n }\n\n return detail;\n}\n\ninterface RunProtocolOptions {\n readonly intent: string;\n readonly protocol: ReturnType<typeof normalizeProtocol>;\n readonly tier: EngineOptions[\"tier\"];\n readonly model: EngineOptions[\"model\"];\n readonly agents: readonly NonNullable<EngineOptions[\"agents\"]>[number][];\n readonly tools: NonNullable<EngineOptions[\"tools\"]>;\n readonly temperature: number;\n readonly budget?: EngineOptions[\"budget\"];\n readonly seed?: EngineOptions[\"seed\"];\n readonly signal?: EngineOptions[\"signal\"];\n readonly terminate?: EngineOptions[\"terminate\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\ntype NonStreamingProtocolOptions = Omit<RunProtocolOptions, \"emit\"> & Pick<EngineOptions, \"evaluate\">;\n\nasync function runNonStreamingProtocol(options: NonStreamingProtocolOptions): Promise<RunResult> {\n const abortLifecycle = createNonStreamingAbortLifecycle({\n callerSignal: options.signal,\n timeoutMs: runtimeTimeoutMs(options),\n providerId: options.model.id\n });\n\n try {\n const emittedEvents: RunEvent[] = [];\n const result = await abortLifecycle.run(runProtocol({\n ...options,\n ...(abortLifecycle.signal !== undefined ? { signal: abortLifecycle.signal } : {}),\n emit(event: RunEvent): void {\n emittedEvents.push(event);\n }\n }));\n const events = emittedEvents.length > 0 ? emittedEvents : result.trace.events;\n const trace = {\n ...result.trace,\n events,\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n finalOutput: createReplayTraceFinalOutput(result.output, events.at(-1) ?? result.trace.events.at(-1)!)\n };\n\n const runResult = {\n ...result,\n accounting: createRunAccounting({\n tier: trace.tier,\n ...(trace.budget.caps ? { budget: trace.budget.caps } : {}),\n ...(trace.budget.termination ? { termination: trace.budget.termination } : {}),\n cost: result.cost,\n events\n }),\n eventLog: createRunEventLog(trace.runId, trace.protocol, events),\n trace\n };\n return canonicalizeRunResult(await abortLifecycle.run(applyRunEvaluation(runResult, options.evaluate)));\n } catch (error: unknown) {\n throw abortLifecycle.translateError(error);\n } finally {\n abortLifecycle.cleanup();\n }\n}\n\nasync function applyRunEvaluation(\n result: RunResult,\n evaluate: EngineOptions[\"evaluate\"]\n): Promise<RunResult> {\n if (!evaluate) {\n return canonicalizeRunResult(result);\n }\n\n const evaluation = await evaluate(result);\n const events = result.trace.events.map((event, index): RunEvent => {\n if (index !== result.trace.events.length - 1 || event.type !== \"final\") {\n return event;\n }\n\n return finalEventWithEvaluation(event, evaluation);\n });\n const trace = {\n ...result.trace,\n events\n };\n\n return canonicalizeRunResult({\n ...result,\n quality: evaluation.quality,\n evaluation,\n trace,\n eventLog: createRunEventLog(trace.runId, trace.protocol, events)\n });\n}\n\nfunction finalEventWithEvaluation(event: FinalEvent, evaluation: RunEvaluation): FinalEvent {\n return {\n ...event,\n quality: evaluation.quality,\n evaluation\n };\n}\n\nfunction runProtocol(options: RunProtocolOptions): Promise<RunResult> {\n switch (options.protocol.kind) {\n case \"sequential\":\n return runSequential({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"broadcast\":\n return runBroadcast({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"coordinator\":\n return runCoordinator({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"shared\":\n return runShared({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n }\n}\n\n/**\n * Run a multi-agent workflow in a single call.\n *\n * @remarks\n * Supply a mission through `intent` and provide a configured model provider.\n * Omitted high-level controls default to Sequential coordination and the\n * `balanced` tier. The returned\n * {@link RunResult} contains the final `output`, a JSON-serializable `trace`,\n * direct `transcript` access, aggregate `cost`, and optional `quality`.\n *\n * Use {@link createEngine} when a research harness needs to reuse normalized\n * protocol/model/agent settings across many missions.\n */\nexport function run(options: DogpileOptions): Promise<RunResult> {\n validateDogpileOptions(options);\n\n const { intent, ...engineOptions } = withHighLevelDefaults(options);\n return createEngine(engineOptions).run(intent);\n}\n\n/**\n * Stream a multi-agent workflow and await the final result.\n *\n * @remarks\n * The returned handle is an async iterable of {@link RunEvent} values with a\n * `result` promise for the same {@link RunResult} shape returned by\n * {@link run}. This supports live event logs and trace UIs without requiring\n * SDK-managed storage.\n *\n * Streaming and final traces use the same event shapes, so callers can render\n * progress live and persist the completed trace without translation.\n */\nexport function stream(options: DogpileOptions): StreamHandle {\n validateDogpileOptions(options);\n\n const { intent, ...engineOptions } = withHighLevelDefaults(options);\n return createEngine(engineOptions).stream(intent);\n}\n\n/**\n * Rehydrate the public result shape from a saved completed trace artifact.\n *\n * @remarks\n * This is the caller-facing replay entrypoint for persisted traces. It does\n * not call the model provider or require SDK-owned storage; it reconstructs\n * the ergonomic {@link RunResult} wrapper from the JSON-serializable\n * {@link Trace} returned by a previous `run()`, `stream()`, or\n * `Dogpile.pile()` call.\n */\nexport function replay(trace: Trace): RunResult {\n const cost = trace.finalOutput.cost;\n const lastEvent = trace.events.at(-1);\n const baseResult = {\n output: trace.finalOutput.output,\n eventLog: createRunEventLog(trace.runId, trace.protocol, trace.events),\n trace,\n transcript: trace.transcript,\n usage: createRunUsage(cost),\n metadata: createRunMetadata({\n runId: trace.runId,\n protocol: trace.protocol,\n tier: trace.tier,\n modelProviderId: trace.modelProviderId,\n agentsUsed: trace.agentsUsed,\n events: trace.events\n }),\n accounting: createRunAccounting({\n tier: trace.tier,\n ...(trace.budget.caps ? { budget: trace.budget.caps } : {}),\n ...(trace.budget.termination ? { termination: trace.budget.termination } : {}),\n cost,\n events: trace.events\n }),\n cost\n };\n\n if (lastEvent?.type !== \"final\") {\n return baseResult;\n }\n\n return {\n ...baseResult,\n ...(lastEvent.quality !== undefined ? { quality: lastEvent.quality } : {}),\n ...(lastEvent.evaluation !== undefined ? { evaluation: lastEvent.evaluation } : {})\n };\n}\n\n/**\n * Replay a saved completed trace as a stream without invoking a model provider.\n *\n * @remarks\n * This is the streaming counterpart to {@link replay}. It yields the exact\n * saved {@link Trace.events} in order and resolves {@link StreamHandle.result}\n * to the rehydrated {@link RunResult}. Since all data comes from the trace,\n * replay remains storage-free and provider-free.\n */\nexport function replayStream(trace: Trace): StreamHandle {\n const result = Promise.resolve(replay(trace));\n\n return {\n get status(): StreamHandleStatus {\n return \"completed\";\n },\n result,\n cancel(): void {\n // Replay streams are already completed snapshots, so cancellation is a no-op.\n },\n subscribe(subscriber: StreamEventSubscriber) {\n for (const event of trace.events) {\n subscriber(event);\n }\n\n return {\n unsubscribe(): void {\n // Replay subscriptions are finite snapshots; there is no live source to detach from.\n }\n };\n },\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n let index = 0;\n\n return {\n next(): Promise<IteratorResult<StreamEvent>> {\n const event = trace.events[index];\n if (event) {\n index += 1;\n return Promise.resolve({ done: false, value: event });\n }\n\n return Promise.resolve({ done: true, value: undefined });\n }\n };\n }\n };\n}\n\nfunction wireCallerAbortSignal(\n callerSignal: AbortSignal | undefined,\n abortController: AbortController,\n cancelRun: (reason?: unknown) => void\n): () => void {\n if (!callerSignal) {\n return (): void => {};\n }\n\n const cancelFromCaller = (): void => {\n cancelRun(readAbortSignalReason(callerSignal));\n };\n\n if (callerSignal.aborted) {\n cancelFromCaller();\n return (): void => {};\n }\n\n callerSignal.addEventListener(\"abort\", cancelFromCaller, { once: true });\n const remove = (): void => {\n callerSignal.removeEventListener(\"abort\", cancelFromCaller);\n };\n abortController.signal.addEventListener(\"abort\", remove, { once: true });\n return remove;\n}\n\nfunction createStreamCancellationError(providerId: string, cause?: unknown): DogpileError {\n return new DogpileError({\n code: \"aborted\",\n message: \"The operation was aborted.\",\n retryable: false,\n providerId,\n ...(cause !== undefined ? { cause } : {}),\n detail: {\n status: \"cancelled\"\n }\n });\n}\n\nfunction isCancellationError(error: unknown): boolean {\n if (DogpileError.isInstance(error)) {\n return error.code === \"aborted\";\n }\n\n return error instanceof Error && error.name === \"AbortError\";\n}\n\nfunction withHighLevelDefaults(options: DogpileOptions): NormalizedDogpileOptions {\n return {\n ...options,\n protocol: options.protocol ?? defaultHighLevelProtocol,\n tier: options.tier ?? defaultHighLevelTier\n };\n}\n\n/**\n * Branded high-level SDK namespace.\n *\n * `Dogpile.pile()` is the ergonomic caller-facing workflow API. It uses the\n * non-streaming execution path and resolves only after the protocol completes,\n * returning `{ output, eventLog, transcript, usage, metadata, trace, cost,\n * quality }`.\n */\nfunction pile(options: DogpileOptions): Promise<RunResult> {\n return run(options);\n}\n\nexport const Dogpile = {\n pile,\n replay,\n replayStream,\n stream,\n createEngine\n} as const;\n","import { DogpileError } from \"../types.js\";\nimport type {\n ConfiguredModelProvider,\n DogpileErrorCode,\n JsonObject,\n JsonValue,\n ModelFinishReason,\n ModelMessage,\n ModelRequest,\n ModelResponse\n} from \"../types.js\";\n\nconst defaultBaseURL = \"https://api.openai.com/v1\";\nconst defaultPath = \"/chat/completions\";\n\nexport type OpenAICompatibleFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface OpenAICompatibleProviderCostContext {\n readonly providerId: string;\n readonly request: ModelRequest;\n readonly response: OpenAICompatibleChatCompletionResponse;\n readonly usage?: ModelResponse[\"usage\"];\n}\n\nexport type OpenAICompatibleProviderCostEstimator = (\n context: OpenAICompatibleProviderCostContext\n) => number | undefined;\n\nexport interface OpenAICompatibleProviderOptions {\n readonly model: string;\n readonly apiKey?: string;\n readonly baseURL?: string | URL;\n readonly path?: string;\n readonly id?: string;\n readonly headers?: Readonly<Record<string, string | undefined>>;\n readonly fetch?: OpenAICompatibleFetch;\n readonly maxOutputTokens?: number;\n readonly extraBody?: JsonObject;\n readonly costEstimator?: OpenAICompatibleProviderCostEstimator;\n}\n\nexport interface OpenAICompatibleChatCompletionResponse {\n readonly id?: string;\n readonly object?: string;\n readonly created?: number;\n readonly model?: string;\n readonly choices?: readonly OpenAICompatibleChatCompletionChoice[];\n readonly usage?: OpenAICompatibleUsage;\n}\n\nexport interface OpenAICompatibleChatCompletionChoice {\n readonly finish_reason?: string | null;\n readonly message?: {\n readonly content?: unknown;\n };\n}\n\nexport interface OpenAICompatibleUsage extends JsonObject {\n readonly prompt_tokens?: number;\n readonly completion_tokens?: number;\n readonly total_tokens?: number;\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n}\n\nexport function createOpenAICompatibleProvider(options: OpenAICompatibleProviderOptions): ConfiguredModelProvider {\n validateOptions(options);\n\n const providerId = options.id ?? `openai-compatible:${options.model}`;\n const fetchImplementation = options.fetch ?? globalThis.fetch?.bind(globalThis);\n\n if (!fetchImplementation) {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: \"createOpenAICompatibleProvider() requires a fetch implementation in this runtime.\",\n retryable: false,\n providerId,\n detail: {\n kind: \"configuration-validation\",\n path: \"fetch\",\n expected: \"a fetch-compatible function\"\n }\n });\n }\n\n return {\n id: providerId,\n async generate(request: ModelRequest): Promise<ModelResponse> {\n let response: Response;\n\n try {\n response = await fetchImplementation(createURL(options), {\n method: \"POST\",\n headers: createHeaders(options),\n body: JSON.stringify(createBody(options, request)),\n ...(request.signal !== undefined ? { signal: request.signal } : {})\n });\n } catch (error) {\n throw normalizeFetchError(error, providerId);\n }\n\n const payload = await readJson(response, providerId);\n\n if (!response.ok) {\n throw createProviderError(response, payload, providerId);\n }\n\n const completion = asChatCompletionResponse(payload, providerId);\n const text = readAssistantText(completion, providerId);\n const usage = normalizeUsage(completion.usage);\n const finishReason = normalizeFinishReason(completion.choices?.[0]?.finish_reason);\n const costUsd = options.costEstimator?.({\n providerId,\n request,\n response: completion,\n ...(usage ? { usage } : {})\n });\n\n return {\n text,\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n metadata: {\n openAICompatible: responseMetadata(completion)\n }\n };\n }\n };\n}\n\nfunction validateOptions(options: OpenAICompatibleProviderOptions): void {\n if (!isRecord(options)) {\n throwInvalid(\"options\", \"an options object\");\n }\n if (!isNonEmptyString(options.model)) {\n throwInvalid(\"model\", \"a non-empty model id\");\n }\n if (options.apiKey !== undefined && !isNonEmptyString(options.apiKey)) {\n throwInvalid(\"apiKey\", \"a non-empty API key when provided\");\n }\n if (options.id !== undefined && !isNonEmptyString(options.id)) {\n throwInvalid(\"id\", \"a non-empty provider id when provided\");\n }\n if (options.path !== undefined && !isNonEmptyString(options.path)) {\n throwInvalid(\"path\", \"a non-empty request path when provided\");\n }\n if (options.fetch !== undefined && typeof options.fetch !== \"function\") {\n throwInvalid(\"fetch\", \"a fetch-compatible function when provided\");\n }\n if (options.maxOutputTokens !== undefined && (!Number.isInteger(options.maxOutputTokens) || options.maxOutputTokens <= 0)) {\n throwInvalid(\"maxOutputTokens\", \"a positive integer when provided\");\n }\n if (options.costEstimator !== undefined && typeof options.costEstimator !== \"function\") {\n throwInvalid(\"costEstimator\", \"a function when provided\");\n }\n}\n\nfunction throwInvalid(path: string, expected: string): never {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: `Invalid OpenAI-compatible provider option at ${path}.`,\n retryable: false,\n detail: {\n kind: \"configuration-validation\",\n path,\n expected\n }\n });\n}\n\nfunction createURL(options: OpenAICompatibleProviderOptions): URL {\n const baseURL = new URL(String(options.baseURL ?? defaultBaseURL));\n const path = options.path ?? defaultPath;\n return new URL(path.startsWith(\"/\") ? path.slice(1) : path, ensureTrailingSlash(baseURL));\n}\n\nfunction ensureTrailingSlash(url: URL): URL {\n const next = new URL(url);\n if (!next.pathname.endsWith(\"/\")) {\n next.pathname = `${next.pathname}/`;\n }\n return next;\n}\n\nfunction createHeaders(options: OpenAICompatibleProviderOptions): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(options.headers ?? {})) {\n if (value !== undefined) {\n headers.set(key, value);\n }\n }\n headers.set(\"content-type\", \"application/json\");\n if (options.apiKey !== undefined && !headers.has(\"authorization\")) {\n headers.set(\"authorization\", `Bearer ${options.apiKey}`);\n }\n return headers;\n}\n\nfunction createBody(options: OpenAICompatibleProviderOptions, request: ModelRequest): JsonObject {\n return {\n ...(options.extraBody ?? {}),\n model: options.model,\n messages: request.messages.map(toChatMessage),\n temperature: request.temperature,\n ...(options.maxOutputTokens !== undefined ? { max_tokens: options.maxOutputTokens } : {})\n };\n}\n\nfunction toChatMessage(message: ModelMessage): JsonObject {\n return {\n role: message.role,\n content: message.content\n };\n}\n\nasync function readJson(response: Response, providerId: string): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider returned a non-JSON response.\",\n cause: error,\n retryable: response.status >= 500,\n providerId,\n detail: {\n statusCode: response.status,\n statusText: response.statusText\n }\n });\n }\n}\n\nfunction asChatCompletionResponse(payload: unknown, providerId: string): OpenAICompatibleChatCompletionResponse {\n if (!isRecord(payload)) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider response must be a JSON object.\",\n retryable: true,\n providerId\n });\n }\n\n return payload as OpenAICompatibleChatCompletionResponse;\n}\n\nfunction readAssistantText(response: OpenAICompatibleChatCompletionResponse, providerId: string): string {\n const content = response.choices?.[0]?.message?.content;\n const text = normalizeContent(content);\n\n if (!text) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider response did not include assistant text.\",\n retryable: true,\n providerId\n });\n }\n\n return text;\n}\n\nfunction normalizeContent(content: unknown): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n if (!Array.isArray(content)) {\n return \"\";\n }\n\n return content\n .map((part) => {\n if (!isRecord(part)) {\n return \"\";\n }\n const text = part.text;\n return typeof text === \"string\" ? text : \"\";\n })\n .filter(Boolean)\n .join(\"\");\n}\n\nfunction normalizeUsage(usage: OpenAICompatibleUsage | undefined): ModelResponse[\"usage\"] | undefined {\n if (!usage) {\n return undefined;\n }\n\n const inputTokens = readTokenCount(usage.prompt_tokens ?? usage.input_tokens);\n const outputTokens = readTokenCount(usage.completion_tokens ?? usage.output_tokens);\n const totalTokens = readTokenCount(usage.total_tokens) ?? sumIfPresent(inputTokens, outputTokens);\n\n if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined) {\n return undefined;\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens\n };\n}\n\nfunction readTokenCount(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n}\n\nfunction sumIfPresent(left: number | undefined, right: number | undefined): number | undefined {\n return left === undefined || right === undefined ? undefined : left + right;\n}\n\nfunction normalizeFinishReason(reason: string | null | undefined): ModelFinishReason | undefined {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n case \"content-filter\":\n return \"content-filter\";\n case \"tool_calls\":\n case \"tool-calls\":\n return \"tool-calls\";\n case undefined:\n case null:\n return undefined;\n default:\n return \"other\";\n }\n}\n\nfunction responseMetadata(response: OpenAICompatibleChatCompletionResponse): JsonObject {\n return removeUndefined({\n id: response.id,\n object: response.object,\n created: response.created,\n model: response.model,\n usage: isJsonValue(response.usage) ? response.usage : undefined\n });\n}\n\nfunction createProviderError(response: Response, payload: unknown, providerId: string): DogpileError {\n return new DogpileError({\n code: codeForStatus(response.status),\n message: providerResponseErrorMessage(response, payload),\n retryable: response.status === 408 || response.status === 429 || response.status >= 500,\n providerId,\n detail: removeUndefined({\n statusCode: response.status,\n statusText: response.statusText,\n response: isJsonValue(payload) ? payload : undefined\n })\n });\n}\n\nfunction normalizeFetchError(error: unknown, providerId: string): DogpileError {\n if (DogpileError.isInstance(error)) {\n return error;\n }\n\n if (errorName(error) === \"AbortError\") {\n return new DogpileError({\n code: \"aborted\",\n message: providerTransportErrorMessage(error, \"OpenAI-compatible provider request was aborted.\"),\n cause: error,\n retryable: false,\n providerId,\n detail: errorDetail(error)\n });\n }\n\n return new DogpileError({\n code: \"provider-error\",\n message: providerTransportErrorMessage(\n error,\n \"OpenAI-compatible provider request failed before receiving a response.\"\n ),\n cause: error,\n retryable: true,\n providerId,\n detail: errorDetail(error)\n });\n}\n\nfunction codeForStatus(status: number): DogpileErrorCode {\n if (status === 401 || status === 403) {\n return \"provider-authentication\";\n }\n if (status === 404) {\n return \"provider-not-found\";\n }\n if (status === 408 || status === 504) {\n return \"provider-timeout\";\n }\n if (status === 429) {\n return \"provider-rate-limited\";\n }\n if (status >= 500) {\n return \"provider-unavailable\";\n }\n if (status >= 400) {\n return \"provider-invalid-request\";\n }\n return \"provider-error\";\n}\n\nfunction providerResponseErrorMessage(response: Response, payload: unknown): string {\n const providerMessage = isRecord(payload) && isRecord(payload.error) && typeof payload.error.message === \"string\"\n ? payload.error.message\n : undefined;\n return providerMessage ?? `OpenAI-compatible provider request failed with HTTP ${response.status}.`;\n}\n\nfunction errorDetail(error: unknown): JsonObject {\n const detail: Record<string, JsonValue> = {};\n const name = errorName(error);\n\n if (name !== undefined) {\n detail.name = name;\n }\n\n return detail;\n}\n\nfunction errorName(error: unknown): string | undefined {\n return isRecord(error) && typeof error.name === \"string\" ? error.name : undefined;\n}\n\nfunction providerTransportErrorMessage(error: unknown, fallback: string): string {\n return error instanceof Error && error.message ? error.message : fallback;\n}\n\nfunction removeUndefined(values: Record<string, JsonValue | undefined>): JsonObject {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)) as JsonObject;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return typeof value !== \"number\" || Number.isFinite(value);\n }\n\n if (Array.isArray(value)) {\n return value.every(isJsonValue);\n }\n\n if (isRecord(value)) {\n return Object.values(value).every(isJsonValue);\n }\n\n return false;\n}\n"],"mappings":";AAqBA,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;AA+JD,IAAa,eAAe,MAlEtB,yBAAyB,MAAoD;CACjF,OAAgB;;CAEhB;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,SAA8B;AACxC,QAAM,QAAQ,QAAQ;AACtB,OAAK,OAAO,QAAQ;AAEpB,MAAI,QAAQ,cAAc,KAAA,EACxB,MAAK,YAAY,QAAQ;AAE3B,MAAI,QAAQ,eAAe,KAAA,EACzB,MAAK,aAAa,QAAQ;AAE5B,MAAI,QAAQ,WAAW,KAAA,EACrB,MAAK,SAAS,QAAQ;AAExB,MAAI,QAAQ,UAAU,KAAA,EACpB,MAAK,QAAQ,QAAQ;AAGvB,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;CAMnD,OAAO,WAAW,OAAuC;AACvD,MAAI,iBAAiB,iBACnB,QAAO;AAGT,MAAI,CAAC,WAAS,MAAM,CAClB,QAAO;AAGT,SAAO,MAAM,SAAS,kBAAkB,mBAAmB,MAAM,KAAK,IAAI,OAAO,MAAM,YAAY;;;;;CAMrG,SAAqB;AACnB,SAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,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;AAClF,QAAO,OAAO,YAAY,OAAO,QAAQ,OAAO,CAAC,QAAQ,GAAG,WAAW,UAAU,KAAA,EAAU,CAAC;;AAG9F,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,SAAS,iBAAiB,OAAiC;AACzD,QAAO,OAAO,UAAU,YAAY,MAAM,MAAM,CAAC,SAAS;;AAG5D,SAAS,YAAY,OAAoC;AACvD,KAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,OAAO,UAAU,YAAY,OAAO,UAAU,UAC/F,QAAO,OAAO,UAAU,YAAY,OAAO,SAAS,MAAM;AAG5D,KAAI,MAAM,QAAQ,MAAM,CACtB,QAAO,MAAM,MAAM,YAAY;AAGjC,KAAI,SAAS,MAAM,CACjB,QAAO,OAAO,OAAO,MAAM,CAAC,MAAM,YAAY;AAGhD,QAAO"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/types.ts","../../src/runtime/defaults.ts","../../src/runtime/cancellation.ts","../../src/runtime/decisions.ts","../../src/runtime/model.ts","../../src/runtime/termination.ts","../../src/runtime/validation.ts","../../src/runtime/tools.ts","../../src/runtime/wrap-up.ts","../../src/runtime/broadcast.ts","../../src/runtime/coordinator.ts","../../src/runtime/sequential.ts","../../src/runtime/shared.ts","../../src/runtime/engine.ts","../../src/providers/openai-compatible.ts"],"sourcesContent":["/**\n * Primitive JSON value accepted in serializable trace metadata.\n */\nexport type JsonPrimitive = string | number | boolean | null;\n\n/**\n * JSON-compatible value used for trace metadata, model request metadata, and\n * caller-managed replay artifacts.\n *\n * Dogpile core is stateless, so everything needed to inspect or persist a run\n * is represented with serializable data instead of SDK-owned storage.\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonValue[];\n\n/**\n * JSON-compatible object with immutable properties.\n */\nexport interface JsonObject {\n readonly [key: string]: JsonValue;\n}\n\nconst dogpileErrorCodes = [\n \"invalid-configuration\",\n \"aborted\",\n \"timeout\",\n \"provider-authentication\",\n \"provider-invalid-request\",\n \"provider-invalid-response\",\n \"provider-not-found\",\n \"provider-rate-limited\",\n \"provider-timeout\",\n \"provider-unavailable\",\n \"provider-unsupported\",\n \"provider-error\",\n \"unknown\"\n] as const;\n\n/**\n * Stable machine-readable error codes thrown by Dogpile public adapters.\n *\n * @remarks\n * The string values are part of the v1 API contract so JavaScript callers can\n * branch on provider failures without depending on provider SDK classes.\n */\nexport type DogpileErrorCode = (typeof dogpileErrorCodes)[number];\n\n/**\n * Options used to construct a stable Dogpile public error.\n */\nexport interface DogpileErrorOptions<Code extends DogpileErrorCode = DogpileErrorCode> {\n /** Stable machine-readable error code. */\n readonly code: Code;\n /** Human-readable error message. */\n readonly message: string;\n /** Original thrown value, kept off JSON serialization by default. */\n readonly cause?: unknown;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\ninterface DogpileErrorBase<Code extends DogpileErrorCode> extends Error {\n /** Public error class name. */\n readonly name: \"DogpileError\";\n /** Stable machine-readable error code. */\n readonly code: Code;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n /** Original thrown value, if Dogpile wrapped a lower-level failure. */\n readonly cause?: unknown;\n /** JSON-safe representation for logs, traces, and observability tools. */\n toJSON(): JsonObject;\n}\n\nexport type DogpileInvalidConfigurationError = DogpileErrorBase<\"invalid-configuration\">;\nexport type DogpileAbortedError = DogpileErrorBase<\"aborted\">;\nexport type DogpileTimeoutError = DogpileErrorBase<\"timeout\">;\nexport type DogpileProviderAuthenticationError = DogpileErrorBase<\"provider-authentication\">;\nexport type DogpileProviderInvalidRequestError = DogpileErrorBase<\"provider-invalid-request\">;\nexport type DogpileProviderInvalidResponseError = DogpileErrorBase<\"provider-invalid-response\">;\nexport type DogpileProviderNotFoundError = DogpileErrorBase<\"provider-not-found\">;\nexport type DogpileProviderRateLimitedError = DogpileErrorBase<\"provider-rate-limited\">;\nexport type DogpileProviderTimeoutError = DogpileErrorBase<\"provider-timeout\">;\nexport type DogpileProviderUnavailableError = DogpileErrorBase<\"provider-unavailable\">;\nexport type DogpileProviderUnsupportedError = DogpileErrorBase<\"provider-unsupported\">;\nexport type DogpileProviderError = DogpileErrorBase<\"provider-error\">;\nexport type DogpileUnknownError = DogpileErrorBase<\"unknown\">;\n\n/**\n * Public Dogpile error union with stable string code discriminants.\n *\n * @remarks\n * `code` is the discriminant for exhaustive caller handling. The exported\n * `DogpileError` value is still the constructor used to create these errors.\n */\nexport type DogpileError =\n | DogpileInvalidConfigurationError\n | DogpileAbortedError\n | DogpileTimeoutError\n | DogpileProviderAuthenticationError\n | DogpileProviderInvalidRequestError\n | DogpileProviderInvalidResponseError\n | DogpileProviderNotFoundError\n | DogpileProviderRateLimitedError\n | DogpileProviderTimeoutError\n | DogpileProviderUnavailableError\n | DogpileProviderUnsupportedError\n | DogpileProviderError\n | DogpileUnknownError;\n\nexport type DogpileErrorByCode<Code extends DogpileErrorCode> = Extract<DogpileError, { readonly code: Code }>;\n\nexport interface DogpileErrorConstructor {\n new <Code extends DogpileErrorCode>(options: DogpileErrorOptions<Code>): DogpileErrorByCode<Code>;\n readonly prototype: DogpileError;\n /**\n * Cross-realm guard for Dogpile public errors.\n */\n isInstance(error: unknown): error is DogpileError;\n}\n\nclass DogpileErrorImpl extends Error implements DogpileErrorBase<DogpileErrorCode> {\n override name = \"DogpileError\" as const;\n /** Stable machine-readable error code. */\n readonly code: DogpileErrorCode;\n /** Whether caller retry policy may safely retry the same operation. */\n readonly retryable?: boolean;\n /** Configured provider id associated with the failure, when available. */\n readonly providerId?: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n /** Original thrown value, if Dogpile wrapped a lower-level failure. */\n readonly cause?: unknown;\n\n constructor(options: DogpileErrorOptions) {\n super(options.message);\n this.code = options.code;\n\n if (options.retryable !== undefined) {\n this.retryable = options.retryable;\n }\n if (options.providerId !== undefined) {\n this.providerId = options.providerId;\n }\n if (options.detail !== undefined) {\n this.detail = options.detail;\n }\n if (options.cause !== undefined) {\n this.cause = options.cause;\n }\n\n Object.setPrototypeOf(this, new.target.prototype);\n }\n\n /**\n * Cross-realm guard for Dogpile public errors.\n */\n static isInstance(error: unknown): error is DogpileError {\n if (error instanceof DogpileErrorImpl) {\n return true;\n }\n\n if (!isRecord(error)) {\n return false;\n }\n\n return error.name === \"DogpileError\" && isDogpileErrorCode(error.code) && typeof error.message === \"string\";\n }\n\n /**\n * JSON-safe representation for logs, traces, and observability tools.\n */\n toJSON(): JsonObject {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n ...(this.retryable !== undefined ? { retryable: this.retryable } : {}),\n ...(this.providerId !== undefined ? { providerId: this.providerId } : {}),\n ...(this.detail !== undefined ? { detail: this.detail } : {})\n };\n }\n}\n\n/**\n * Public Dogpile error constructor.\n */\nexport const DogpileError = DogpileErrorImpl as DogpileErrorConstructor;\n\nfunction isDogpileErrorCode(value: unknown): value is DogpileErrorCode {\n return typeof value === \"string\" && dogpileErrorCodes.includes(value as DogpileErrorCode);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Coordination protocols supported by the public SDK surface.\n *\n * Supported values:\n *\n * - `coordinator`: a coordinator assigns work and synthesizes a final answer.\n * - `sequential`: agents refine the answer one after another.\n * - `broadcast`: agents answer the same mission independently before merge.\n * - `shared`: agents collaborate through shared state.\n *\n * Passing a string protocol uses the SDK defaults from {@link ProtocolConfig}:\n * `maxTurns: 3` for `coordinator`, `sequential`, and `shared`, and\n * `maxRounds: 2` for `broadcast`.\n */\nexport type Protocol = \"coordinator\" | \"sequential\" | \"broadcast\" | \"shared\";\n\n/**\n * Public coordination protocol selector name.\n *\n * @remarks\n * This alias is the caller-facing literal union shared by high-level calls,\n * low-level engine configuration, traces, events, and benchmark artifacts.\n * `Protocol` remains the short compatibility name for the same public union.\n */\nexport type ProtocolName = Protocol;\n\n/**\n * Named cost and quality presets.\n *\n * Supported values:\n *\n * - `fast`: minimizes latency and spend; default temperature is `0`.\n * - `balanced`: general-purpose tradeoff; default temperature is `0.2`.\n * - `quality`: spends more work on answer quality; default temperature is `0.4`.\n *\n * High-level workflow calls default to `balanced` when callers omit a tier.\n * Low-level engine configuration keeps the tier explicit for repeatable\n * research runs.\n */\nexport type BudgetTier = \"fast\" | \"balanced\" | \"quality\";\n\n/**\n * Short compatibility name for the public budget tier union.\n */\nexport type Tier = BudgetTier;\n\n/**\n * Sequential protocol configuration.\n *\n * Agents contribute in order, with each turn seeing the prior transcript.\n * Default when `protocol: \"sequential\"` is supplied: `{ kind: \"sequential\",\n * maxTurns: 3 }`.\n */\nexport interface SequentialProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"sequential\";\n /** Maximum number of agent turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n /**\n * Floor for convergence and judge termination checks.\n *\n * Budget caps still apply immediately. Defaults to `0` when omitted.\n */\n readonly minTurns?: number;\n}\n\n/**\n * Coordinator protocol configuration.\n *\n * A coordinator manages worker turns and synthesizes the final output.\n * Default when `protocol: \"coordinator\"` is supplied: `{ kind: \"coordinator\",\n * maxTurns: 3 }`.\n */\nexport interface CoordinatorProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"coordinator\";\n /** Maximum number of coordinator-managed turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n /**\n * Floor for convergence and judge termination checks.\n *\n * Budget caps still apply immediately. Defaults to `0` when omitted.\n */\n readonly minTurns?: number;\n}\n\n/**\n * Broadcast protocol configuration.\n *\n * Agents independently answer the same mission before a merge/synthesis step.\n * Default when `protocol: \"broadcast\"` is supplied: `{ kind: \"broadcast\",\n * maxRounds: 2 }`.\n */\nexport interface BroadcastProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"broadcast\";\n /** Maximum number of broadcast/merge rounds to execute; defaults to `2` for named protocols. */\n readonly maxRounds?: number;\n /**\n * Floor for convergence and judge termination checks.\n *\n * Budget caps still apply immediately. Defaults to `0` when omitted.\n */\n readonly minRounds?: number;\n}\n\n/**\n * Shared-state protocol configuration.\n *\n * Agents coordinate by reading and updating a shared working state.\n * Default when `protocol: \"shared\"` is supplied: `{ kind: \"shared\",\n * maxTurns: 3 }`.\n */\nexport interface SharedProtocolConfig {\n /** Discriminant for exhaustive protocol handling. */\n readonly kind: \"shared\";\n /** Maximum number of shared-state turns to execute; defaults to `3` for named protocols. */\n readonly maxTurns?: number;\n /**\n * Floor for convergence and judge termination checks.\n *\n * Budget caps still apply immediately. Defaults to `0` when omitted.\n */\n readonly minTurns?: number;\n /** Optional organizational memory snapshot visible to every shared agent. */\n readonly organizationalMemory?: string;\n}\n\n/**\n * Discriminated protocol configuration union for low-level runs.\n *\n * Use this union when the named {@link Protocol} defaults are too coarse. The\n * `kind` property is the discriminant and supported values are `coordinator`,\n * `sequential`, `broadcast`, and `shared`.\n */\nexport type ProtocolConfig =\n | SequentialProtocolConfig\n | CoordinatorProtocolConfig\n | BroadcastProtocolConfig\n | SharedProtocolConfig;\n\n/**\n * Budget policy composed from a named tier plus optional hard caps.\n *\n * Supported `tier` values are `fast`, `balanced`, and `quality`. The tier\n * selects default execution behavior such as temperature, while `maxUsd`,\n * `maxTokens`, and `qualityWeight` layer caller-owned cost policy over that\n * preset.\n *\n * The SDK should halt before cap breach and report accumulated usage in\n * {@link CostSummary}. `qualityWeight` expresses how strongly the caller values\n * spending additional budget for higher answer quality.\n */\nexport interface Budget {\n /** Named preset used to choose default execution behavior; recommended default is `balanced`. */\n readonly tier: BudgetTier;\n /** Optional maximum spend in US dollars; omit for no SDK-enforced dollar cap. */\n readonly maxUsd?: number;\n /** Optional maximum total token count; omit for no SDK-enforced token cap. */\n readonly maxTokens?: number;\n /** Optional maximum completed model-turn iterations; omit for no SDK-enforced iteration cap. */\n readonly maxIterations?: number;\n /** Optional maximum elapsed runtime in milliseconds; omit for no SDK-enforced timeout cap. */\n readonly timeoutMs?: number;\n /** Optional quality preference in the inclusive range `0..1`; omit to use the tier default. */\n readonly qualityWeight?: number;\n}\n\n/**\n * Serializable termination condition for cost-controlled and quality-aware runs.\n *\n * @remarks\n * Conditions are discriminated by `kind` so callers can compose and inspect\n * stop policies without relying on functions, closures, storage, or\n * runtime-specific state. Use {@link FirstOfTerminationCondition} when multiple\n * conditions should race and the first terminating condition should win.\n */\nexport type TerminationCondition =\n | BudgetTerminationCondition\n | ConvergenceTerminationCondition\n | JudgeTerminationCondition\n | FirstOfTerminationCondition;\n\n/**\n * Primitive, non-composite termination conditions accepted by `firstOf`.\n */\nexport type PrimitiveTerminationCondition =\n | BudgetTerminationCondition\n | ConvergenceTerminationCondition\n | JudgeTerminationCondition;\n\n/**\n * Halt when observed usage reaches or would exceed a configured cap.\n */\nexport interface BudgetTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"budget\";\n /** Optional maximum spend in US dollars. */\n readonly maxUsd?: number;\n /** Optional maximum total token count. */\n readonly maxTokens?: number;\n /** Optional maximum completed model-turn iterations. */\n readonly maxIterations?: number;\n /** Optional maximum elapsed runtime in milliseconds. */\n readonly timeoutMs?: number;\n}\n\n/**\n * Normalized machine-readable reason for a budget stop.\n */\nexport type BudgetStopReason = \"cost\" | \"tokens\" | \"iterations\" | \"timeout\";\n\n/**\n * Halt when recent outputs are stable enough to treat the run as converged.\n */\nexport interface ConvergenceTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"convergence\";\n /** Number of consecutive stable turns required before terminating. */\n readonly stableTurns: number;\n /** Similarity threshold in the inclusive range `0..1`. */\n readonly minSimilarity: number;\n}\n\n/**\n * Halt when a judge accepts, rejects, or scores the current run state.\n */\nexport interface JudgeTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"judge\";\n /** Model-visible rubric or serialized judge configuration. */\n readonly rubric: string | JsonObject;\n /** Optional score threshold in the inclusive range `0..1`. */\n readonly minScore?: number;\n}\n\n/**\n * Normalized machine-readable reason for a judge stop.\n */\nexport type JudgeStopReason = \"accepted\" | \"rejected\" | \"score-threshold\";\n\n/**\n * Normalized machine-readable stop reason across all termination evaluators.\n */\nexport type NormalizedStopReason =\n | \"budget:cost\"\n | \"budget:tokens\"\n | \"budget:iterations\"\n | \"budget:timeout\"\n | \"convergence\"\n | \"judge:accepted\"\n | \"judge:rejected\"\n | \"judge:score-threshold\";\n\n/**\n * Serializable judge decision visible to judge termination evaluators.\n *\n * @remarks\n * Judge decisions are deliberately separate from budget and convergence state:\n * a caller-owned evaluator can record an explicit accept/reject verdict or a\n * normalized score without coupling termination checks to cost caps or protocol\n * transcript similarity.\n */\nexport type JudgeEvaluationDecision =\n | JudgeAcceptDecision\n | JudgeRejectDecision\n | JudgeScoreDecision;\n\n/**\n * Judge verdict that accepts the current run state.\n */\nexport interface JudgeAcceptDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"accept\";\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly score?: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Judge verdict that rejects the current run state.\n */\nexport interface JudgeRejectDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"reject\";\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly score?: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Judge score without a hard accept/reject verdict.\n */\nexport interface JudgeScoreDecision {\n /** Decision discriminant for exhaustive judge handling. */\n readonly type: \"score\";\n /** Normalized quality score in the inclusive range `0..1`. */\n readonly score: NormalizedQualityScore;\n /** Optional serializable rationale for trace diagnostics. */\n readonly rationale?: string;\n /** Optional serializable judge metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Input tuple accepted by a `firstOf(...conditions)` helper.\n */\nexport type FirstOfTerminationConditions = readonly [\n PrimitiveTerminationCondition | FirstOfTerminationCondition,\n ...(PrimitiveTerminationCondition | FirstOfTerminationCondition)[]\n];\n\n/**\n * Composite termination condition where the earliest terminating child wins.\n */\nexport interface FirstOfTerminationCondition {\n /** Discriminant for exhaustive termination handling. */\n readonly kind: \"firstOf\";\n /** Ordered child conditions evaluated by the composite. */\n readonly conditions: FirstOfTerminationConditions;\n}\n\n/**\n * Serializable input passed to a firstOf composition evaluator.\n */\nexport interface FirstOfTerminationInput {\n /** Composition input discriminant for logs and tests. */\n readonly kind: \"firstOf-input\";\n /** Conditions to evaluate in order. */\n readonly conditions: FirstOfTerminationConditions;\n /** Current run state visible to termination evaluators. */\n readonly context: TerminationEvaluationContext;\n}\n\n/**\n * Current run state visible to termination evaluators.\n */\nexport interface TerminationEvaluationContext {\n /** Stable id for the workflow run being evaluated. */\n readonly runId: string;\n /** Protocol currently executing. */\n readonly protocol: Protocol;\n /** Exact normalized protocol configuration when the evaluator needs protocol-specific limits. */\n readonly protocolConfig?: ProtocolConfig;\n /** Cost/quality tier selected for the run. */\n readonly tier: BudgetTier;\n /** Current accumulated cost and token usage. */\n readonly cost: CostSummary;\n /** Completed coordination events available at the evaluation point. */\n readonly events: readonly RunEvent[];\n /** Completed transcript entries available at the evaluation point. */\n readonly transcript: readonly TranscriptEntry[];\n /** Completed model-turn iterations at the evaluation point. */\n readonly iteration?: number;\n /** Protocol-native progress count: turns for sequential/coordinator/shared, rounds for broadcast. */\n readonly protocolIteration?: number;\n /** Elapsed runtime in milliseconds at the evaluation point. */\n readonly elapsedMs?: number;\n /** Effective hard caps visible to this evaluation point. */\n readonly budget?: BudgetCaps;\n /** Remaining headroom computed from the effective hard caps at this evaluation point. */\n readonly remainingBudget?: RemainingBudget;\n /** Optional normalized judge or quality score in the inclusive range `0..1`. */\n readonly quality?: NormalizedQualityScore;\n /** Optional caller-owned judge decision for judge termination checks. */\n readonly judgeDecision?: JudgeEvaluationDecision;\n /** Additional serializable evaluator metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Remaining budget headroom derived from the current evaluation context.\n */\nexport interface RemainingBudget {\n /** Remaining turn iterations before an iteration cap is reached. */\n readonly iterations?: number;\n /** Remaining elapsed milliseconds before a timeout cap is reached. */\n readonly timeoutMs?: number;\n /** Remaining spend in US dollars before a cost cap is reached. */\n readonly usd?: number;\n /** Remaining total tokens before a token cap is reached. */\n readonly tokens?: number;\n}\n\n/**\n * Decision returned by a termination condition evaluator.\n */\nexport type TerminationDecision = ContinueTerminationDecision | StopTerminationDecision;\n\n/**\n * Continue running because a condition has not fired.\n */\nexport interface ContinueTerminationDecision {\n /** Decision discriminant for exhaustive termination handling. */\n readonly type: \"continue\";\n /** Condition that was evaluated. */\n readonly condition: TerminationCondition;\n}\n\n/**\n * Stop running because a condition fired.\n */\nexport interface StopTerminationDecision {\n /** Decision discriminant for exhaustive termination handling. */\n readonly type: \"stop\";\n /** Condition that fired. */\n readonly condition: TerminationCondition;\n /** Machine-readable stop reason. */\n readonly reason: \"budget\" | \"convergence\" | \"judge\";\n /** Normalized machine-readable stop reason across all stop classes. */\n readonly normalizedReason: NormalizedStopReason;\n /** Normalized budget stop reason when `reason` is `budget`. */\n readonly budgetReason?: BudgetStopReason;\n /** Normalized judge stop reason when `reason` is `judge`. */\n readonly judgeReason?: JudgeStopReason;\n /** Optional serializable detail for traces and diagnostics. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Output returned after evaluating a `firstOf` composition.\n */\nexport interface FirstOfTerminationOutput {\n /** Composition output discriminant for logs and tests. */\n readonly kind: \"firstOf-output\";\n /** Final decision for the composite condition. */\n readonly decision: TerminationDecision;\n /** Zero-based index of the child condition that fired, or `null` if none fired. */\n readonly winningConditionIndex: number | null;\n /** Per-child decisions in evaluation order. */\n readonly evaluated: readonly TerminationDecision[];\n}\n\n/**\n * Serializable diagnostics for a firstOf composition that stopped a run.\n */\nexport interface FirstOfTerminationStopRecord {\n /** Composition stop discriminant for trace consumers. */\n readonly kind: \"firstOf-stop\";\n /** Zero-based index of the top-level child condition that fired. */\n readonly winningConditionIndex: number;\n /** Top-level child condition that fired. */\n readonly winningCondition: TerminationCondition;\n /** Concrete condition that produced the stop decision. */\n readonly firedCondition: TerminationCondition;\n /** Per-child decisions in evaluation order. */\n readonly evaluated: readonly TerminationDecision[];\n}\n\n/**\n * Serializable record of the termination condition that stopped a run.\n */\nexport interface TerminationStopRecord {\n /** Stop record discriminant for trace consumers. */\n readonly kind: \"termination-stop\";\n /** Condition supplied to the protocol runner. */\n readonly rootCondition: TerminationCondition;\n /** Concrete condition that fired. */\n readonly firedCondition: TerminationCondition;\n /** Machine-readable stop reason. */\n readonly reason: StopTerminationDecision[\"reason\"];\n /** Normalized machine-readable stop reason across all stop classes. */\n readonly normalizedReason: NormalizedStopReason;\n /** Normalized budget stop reason when the fired condition is budget-based. */\n readonly budgetReason?: BudgetStopReason;\n /** Normalized judge stop reason when the fired condition is judge-based. */\n readonly judgeReason?: JudgeStopReason;\n /** Optional serializable detail from the fired condition. */\n readonly detail?: JsonObject;\n /** firstOf winner diagnostics when the root condition is a composition. */\n readonly firstOf?: FirstOfTerminationStopRecord;\n}\n\n/**\n * Agent participating in a coordinated workflow.\n */\nexport interface AgentSpec {\n /** Stable id written into events, traces, and transcripts. */\n readonly id: string;\n /** Model-visible role or perspective for this agent. */\n readonly role: string;\n /** Optional per-agent instruction appended to the protocol prompt. */\n readonly instructions?: string;\n}\n\n/**\n * Provider-facing model message.\n *\n * @remarks\n * This is the smallest prompt unit handed to a model adapter. Dogpile keeps it\n * provider-neutral so researchers can bridge the same protocol run into Vercel\n * AI SDK models, deterministic fixtures, or custom lab harnesses without\n * changing protocol code.\n */\nexport interface ModelMessage {\n /** Chat role supplied to the configured model provider. */\n readonly role: \"system\" | \"user\" | \"assistant\";\n /** Message text supplied to the configured model provider. */\n readonly content: string;\n}\n\n/**\n * Provider-neutral reason why a model call stopped generating.\n *\n * @remarks\n * This mirrors the Vercel AI SDK's unified finish reasons while keeping\n * Dogpile's core provider contract independent from the `ai` package.\n */\nexport type ModelFinishReason = \"stop\" | \"length\" | \"content-filter\" | \"tool-calls\" | \"error\" | \"other\";\n\n/**\n * Request passed to a configured model provider.\n *\n * @remarks\n * This is the low-level researcher escape hatch for provider adapters. It is\n * intentionally fetch/runtime neutral and does not depend on Node-only APIs,\n * mutable SDK state, or a specific provider package. Adapters can translate\n * `messages` and `temperature` directly into a Vercel AI SDK call while\n * preserving `metadata` for experiment labels, protocol state, replay ids, or\n * provider-specific request annotations.\n *\n * The metadata object must remain JSON-compatible because it is eligible for\n * inclusion in caller-managed traces and benchmark artifacts.\n *\n * @example\n * ```ts\n * const response = await generateText({\n * model,\n * messages: request.messages,\n * temperature: request.temperature\n * });\n * ```\n */\nexport interface ModelRequest {\n /** Ordered chat messages for the next model call. */\n readonly messages: readonly ModelMessage[];\n /** Sampling temperature selected from the tier or caller override. */\n readonly temperature: number;\n /** Optional cancellation signal passed through to fetch-based model adapters. */\n readonly signal?: AbortSignal;\n /** Serializable protocol metadata for tracing and provider adapters. */\n readonly metadata: JsonObject;\n}\n\n/**\n * Response returned by a configured model provider.\n *\n * @remarks\n * Provider adapters return only the text Dogpile should feed back into the\n * active protocol plus optional usage/cost telemetry. Keeping the response\n * small makes deterministic fixtures and cross-runtime adapters easy to write.\n * When the upstream provider cannot report usage or price, omit those fields\n * rather than inventing non-replayable side data.\n */\nexport interface ModelResponse {\n /** Generated text used by the active coordination protocol. */\n readonly text: string;\n /** Optional provider-normalized finish reason for the model call. */\n readonly finishReason?: ModelFinishReason;\n /**\n * Optional provider-neutral runtime tool requests produced by the model adapter.\n *\n * @remarks\n * Adapters that translate Vercel AI SDK tool calls can return normalized\n * requests here. First-party protocols execute them through the shared\n * runtime tool executor and emit matched `tool-call` / `tool-result` events\n * without coupling core to a provider-specific tool-call shape.\n */\n readonly toolRequests?: readonly RuntimeToolExecutionRequest[];\n /** Optional provider-reported token usage. */\n readonly usage?: {\n /** Input tokens consumed by the model call. */\n readonly inputTokens: number;\n /** Output tokens generated by the model call. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n };\n /** Optional provider-reported or adapter-estimated cost in US dollars. */\n readonly costUsd?: number;\n /** Optional provider-adapter metadata normalized to JSON-compatible data. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Version tag for the replay trace artifact schema.\n */\nexport type ReplayTraceSchemaVersion = \"1.0\";\n\n/**\n * Serializable seed metadata recorded with replay traces.\n *\n * @remarks\n * Most providers do not expose deterministic seed control. Dogpile still\n * records an explicit empty seed artifact so replay consumers can distinguish\n * \"no seed supplied\" from a missing trace field.\n */\nexport interface ReplayTraceSeed {\n /** Seed artifact discriminant. */\n readonly kind: \"replay-trace-seed\";\n /** Seed source visible to replay tooling. */\n readonly source: \"caller\" | \"none\";\n /** Caller-supplied seed value, or `null` when no seed was supplied. */\n readonly value: string | number | null;\n}\n\n/**\n * Normalized run inputs persisted inside the replay trace artifact.\n */\nexport interface ReplayTraceRunInputs {\n /** Run input artifact discriminant. */\n readonly kind: \"replay-trace-run-inputs\";\n /** Mission or intent supplied by the caller. */\n readonly intent: string;\n /** Exact normalized protocol config used for execution. */\n readonly protocol: ProtocolConfig;\n /** Selected cost/quality tier. */\n readonly tier: Tier;\n /** Configured model provider id. */\n readonly modelProviderId: string;\n /** Concrete agent roster visible to the protocol. */\n readonly agents: readonly AgentSpec[];\n /** Temperature supplied to provider requests. */\n readonly temperature: number;\n}\n\n/**\n * Budget and stop-policy artifact persisted inside replay traces.\n */\nexport interface ReplayTraceBudget {\n /** Budget artifact discriminant. */\n readonly kind: \"replay-trace-budget\";\n /** Selected cost/quality tier. */\n readonly tier: Tier;\n /** Optional hard caps supplied by the caller. */\n readonly caps?: Omit<Budget, \"tier\">;\n /** Optional composable termination policy used by the protocol. */\n readonly termination?: TerminationCondition;\n}\n\n/**\n * Budget state snapshot derived from a cost-bearing trace event.\n *\n * @remarks\n * Replay consumers can inspect this artifact without walking the full event\n * log. Entries are emitted for model-turn accounting changes, coordination\n * barriers that expose cumulative cost, budget stops, and final completion.\n */\nexport interface ReplayTraceBudgetStateChange {\n /** Budget state artifact discriminant. */\n readonly kind: \"replay-trace-budget-state-change\";\n /** Zero-based event index that exposed this budget state. */\n readonly eventIndex: number;\n /** Source event type for the budget state. */\n readonly eventType: \"agent-turn\" | \"broadcast\" | \"budget-stop\" | \"final\";\n /** ISO-8601 timestamp from the source event. */\n readonly at: string;\n /** Cumulative cost visible at this point in the run. */\n readonly cost: CostSummary;\n /** Completed model-turn iteration count when known. */\n readonly iteration?: number;\n /** Elapsed runtime in milliseconds when known. */\n readonly elapsedMs?: number;\n /** Budget stop reason when this state records a halt. */\n readonly budgetReason?: BudgetStopReason;\n}\n\n/**\n * Provider-neutral protocol decision kinds recorded for replay.\n */\nexport type ReplayTraceProtocolDecisionType =\n | \"assign-role\"\n | \"select-agent-turn\"\n | \"start-model-call\"\n | \"complete-model-call\"\n | \"observe-model-output\"\n | \"start-tool-call\"\n | \"complete-tool-call\"\n | \"collect-broadcast-round\"\n | \"stop-for-budget\"\n | \"finalize-output\";\n\n/**\n * Protocol-level decision appended during execution.\n */\nexport interface ReplayTraceProtocolDecision {\n /** Decision artifact discriminant. */\n readonly kind: \"replay-trace-protocol-decision\";\n /** Zero-based event index that produced this decision. */\n readonly eventIndex: number;\n /** Event type that records the decision. */\n readonly eventType: RunEvent[\"type\"];\n /** Coordination protocol that made the decision. */\n readonly protocol: Protocol;\n /** Provider-neutral decision kind for replay tooling. */\n readonly decision: ReplayTraceProtocolDecisionType;\n /** ISO-8601 timestamp from the source event. */\n readonly at: string;\n /** Agent involved in the decision, when agent-scoped. */\n readonly agentId?: string;\n /** Role involved in the decision, when agent-scoped. */\n readonly role?: string;\n /** Provider call involved in the decision, when model-scoped. */\n readonly callId?: string;\n /** Provider involved in the decision, when model-scoped. */\n readonly providerId?: string;\n /** Tool call involved in the decision, when tool-scoped. */\n readonly toolCallId?: string;\n /** Tool identity involved in the decision, when tool-scoped. */\n readonly tool?: RuntimeToolIdentity;\n /** One-based protocol turn for turn-scoped decisions. */\n readonly turn?: number;\n /** Coordinator phase for coordinator protocol turn decisions. */\n readonly phase?: \"plan\" | \"worker\" | \"final-synthesis\";\n /** One-based broadcast round for grouped broadcast decisions. */\n readonly round?: number;\n /** Number of transcript entries visible after this decision. */\n readonly transcriptEntryCount?: number;\n /** Number of contributions collected at a broadcast barrier. */\n readonly contributionCount?: number;\n /** Prompt/input associated with turn decisions. */\n readonly input?: string;\n /** Output associated with turn or final decisions. */\n readonly output?: string;\n /** Cumulative cost visible at this decision point. */\n readonly cost?: CostSummary;\n /** Normalized budget stop reason for budget-stop decisions. */\n readonly budgetReason?: BudgetStopReason;\n}\n\n/**\n * Provider call metadata and response captured for replay inspection.\n */\nexport interface ReplayTraceProviderCall {\n /** Provider call artifact discriminant. */\n readonly kind: \"replay-trace-provider-call\";\n /** Stable call id within the run. */\n readonly callId: string;\n /** Configured model provider id. */\n readonly providerId: string;\n /** ISO-8601 timestamp before the provider call started. */\n readonly startedAt: string;\n /** ISO-8601 timestamp after the provider call completed. */\n readonly completedAt: string;\n /** Agent that requested this provider call. */\n readonly agentId: string;\n /** Role that requested this provider call. */\n readonly role: string;\n /** Request handed to the configured model provider. */\n readonly request: ModelRequest;\n /** Response returned by the configured model provider. */\n readonly response: ModelResponse;\n}\n\n/**\n * Final output artifact persisted inside replay traces.\n */\nexport interface ReplayTraceFinalOutput {\n /** Final output artifact discriminant. */\n readonly kind: \"replay-trace-final-output\";\n /** Final synthesized output returned by the run. */\n readonly output: string;\n /** Total cost at completion. */\n readonly cost: CostSummary;\n /** ISO-8601 completion timestamp from the terminal event. */\n readonly completedAt: string;\n /** Link to the completed transcript artifact. */\n readonly transcript: TranscriptLink;\n}\n\n/**\n * Incremental text produced by a streaming model provider.\n *\n * @remarks\n * Providers that can surface partial model output should implement\n * {@link ConfiguredModelProvider.stream}. Dogpile concatenates `text` chunks\n * into the completed {@link ModelResponse.text} for transcript and final\n * result compatibility while emitting each chunk as a typed stream/trace event.\n *\n * Usage and cost are optional on chunks because many provider SDKs only expose\n * them at stream completion. When supplied, the last observed usage/cost values\n * are used for the completed model turn.\n */\nexport interface ModelOutputChunk {\n /** Text delta produced by the provider. */\n readonly text: string;\n /** Optional provider-normalized finish reason surfaced on a final chunk. */\n readonly finishReason?: ModelResponse[\"finishReason\"];\n /** Optional provider-neutral runtime tool requests surfaced on a final chunk. */\n readonly toolRequests?: ModelResponse[\"toolRequests\"];\n /** Optional provider-reported token usage for the stream so far or final chunk. */\n readonly usage?: ModelResponse[\"usage\"];\n /** Optional provider-reported or adapter-estimated cost in US dollars. */\n readonly costUsd?: number;\n /** Optional provider-adapter metadata normalized to JSON-compatible data. */\n readonly metadata?: ModelResponse[\"metadata\"];\n}\n\n/**\n * Runtime-neutral model provider configured by the caller.\n *\n * @remarks\n * This is the primary model-extension point. Production adapters can wrap\n * Vercel AI SDK models behind this interface while tests can provide\n * deterministic providers for replayable protocol checks.\n *\n * Implementations should be pure TypeScript and fetch-compatible for Node LTS,\n * Bun, and browser ESM runtimes. Do not assume filesystem access,\n * process globals, or SDK-managed session storage.\n *\n * @example\n * ```ts\n * const provider: ConfiguredModelProvider = {\n * id: \"vercel-ai:model-name\",\n * async generate(request) {\n * const result = await generateText({\n * model,\n * messages: request.messages,\n * temperature: request.temperature\n * });\n *\n * return { text: result.text };\n * }\n * };\n * ```\n */\nexport interface ConfiguredModelProvider {\n /** Stable provider id recorded in traces. */\n readonly id: string;\n /** Generate a response for one protocol-managed model request. */\n generate(request: ModelRequest): Promise<ModelResponse>;\n /**\n * Optionally stream response text for one protocol-managed model request.\n *\n * When present, protocol execution consumes this stream directly and emits\n * `model-output-chunk` events before the completed `agent-turn` event. The\n * fallback `generate()` method remains required for adapters that do not\n * support incremental output and for callers that prefer batch execution.\n */\n stream?(request: ModelRequest): AsyncIterable<ModelOutputChunk>;\n}\n\n/**\n * Stable identity for a runtime tool available to protocol execution.\n *\n * @remarks\n * Tool identity is protocol-agnostic: the same tool can be made visible to\n * coordinator, sequential, broadcast, or shared runs. `id` is the canonical\n * trace key and should remain stable across releases when replay fixtures\n * depend on it. `namespace` and `version` let applications distinguish\n * similarly named tools without baking provider or runtime details into core.\n */\nexport interface RuntimeToolIdentity {\n /** Stable tool id written into tool calls, results, and trace artifacts. */\n readonly id: string;\n /** Human-readable tool name suitable for model-visible descriptions. */\n readonly name: string;\n /** Optional package, product, or caller-owned namespace. */\n readonly namespace?: string;\n /** Optional semantic version or caller-managed revision label. */\n readonly version?: string;\n /** Optional model-visible description of what the tool does. */\n readonly description?: string;\n}\n\n/**\n * Protocol-agnostic input schema for a runtime tool.\n *\n * @remarks\n * Dogpile keeps the schema as JSON-compatible data so callers can translate it\n * into Vercel AI SDK tool definitions, provider-specific function calling, or\n * custom researcher harnesses without importing Node-only validators. The\n * schema should describe a JSON object input; tool execution receives that\n * object as the typed `input` argument.\n */\nexport interface RuntimeToolInputSchema {\n /** Schema discriminant for future schema families. */\n readonly kind: \"json-schema\";\n /** JSON Schema-compatible object describing the tool input. */\n readonly schema: JsonObject;\n /** Optional human-readable input description. */\n readonly description?: string;\n}\n\n/**\n * Immutable trace snapshot visible to a runtime tool during execution.\n *\n * @remarks\n * The snapshot is intentionally read-only and serializable. Tools can inspect\n * coordination history without mutating SDK state or depending on storage.\n */\nexport interface RuntimeToolTraceContext {\n /** Ordered coordination events emitted before this tool execution. */\n readonly events: readonly RunEvent[];\n /** Ordered transcript entries completed before this tool execution. */\n readonly transcript: readonly TranscriptEntry[];\n}\n\n/**\n * Protocol-agnostic execution context passed to runtime tools.\n *\n * @remarks\n * The context gives a tool the active run identity, protocol, tier, optional\n * agent/turn labels, and a read-only trace snapshot. The optional\n * `abortSignal` is runtime-neutral across modern JS runtimes and lets budget\n * or timeout policy cancel long-running fetch-based tools without requiring\n * Node-only APIs.\n */\nexport interface RuntimeToolExecutionContext {\n /** Stable id for the workflow run that requested the tool. */\n readonly runId: string;\n /** Stable id for this individual tool call. */\n readonly toolCallId: string;\n /** Coordination protocol currently executing. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Agent that requested the tool, when execution is agent-scoped. */\n readonly agentId?: string;\n /** Model-visible role of the requesting agent, when available. */\n readonly role?: string;\n /** One-based protocol turn index, when execution is turn-scoped. */\n readonly turn?: number;\n /** Read-only serializable trace state visible at the call boundary. */\n readonly trace?: RuntimeToolTraceContext;\n /** Optional cancellation signal for fetch-based tool implementations. */\n readonly abortSignal?: AbortSignal;\n /** Additional caller-owned serializable execution metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Protocol-neutral request to execute one runtime tool.\n *\n * @remarks\n * First-party protocols use this shape instead of protocol-specific tool call\n * objects. The input and metadata are JSON-compatible so the request-side\n * event can be persisted for caller-managed replay, while `abortSignal`\n * remains an execution-only control for portable fetch-based adapters.\n */\nexport interface RuntimeToolExecutionRequest {\n /** Stable tool id from {@link RuntimeToolIdentity.id}. */\n readonly toolId: string;\n /** Optional caller-supplied call id; generated by the executor when omitted. */\n readonly toolCallId?: string;\n /** JSON-serializable tool input. */\n readonly input: JsonObject;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Model-visible role of the requesting agent, when available. */\n readonly role?: string;\n /** One-based protocol turn index, when execution is turn-scoped. */\n readonly turn?: number;\n /** Optional cancellation signal for this call. */\n readonly abortSignal?: AbortSignal;\n /** Additional caller-owned serializable request metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared protocol-agnostic tool executor used by first-party protocol runners.\n */\nexport interface RuntimeToolExecutor {\n /** Runtime tools available to the active protocol run. */\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Execute one normalized tool request and emit matching tool events. */\n execute(request: RuntimeToolExecutionRequest): Promise<RuntimeToolResult>;\n}\n\n/**\n * JSON-serializable runtime tool error shape.\n *\n * @remarks\n * Tool errors are data, not thrown values, at the public boundary. Adapters may\n * still throw internally, but protocol code should normalize failures into\n * this shape before writing traces so failed tool calls remain replayable.\n */\nexport interface RuntimeToolError {\n /** Machine-readable error code, for example `timeout` or `invalid-input`. */\n readonly code: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Whether the same call may be retried safely by caller policy. */\n readonly retryable?: boolean;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Successful runtime tool execution result.\n */\nexport interface RuntimeToolSuccessResult<Output = JsonValue> {\n /** Result discriminant for exhaustive tool-result handling. */\n readonly type: \"success\";\n /** Stable id matching the execution context call id. */\n readonly toolCallId: string;\n /** Tool identity that produced the result. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool output. */\n readonly output: Output;\n /** Optional serializable result metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Failed runtime tool execution result.\n */\nexport interface RuntimeToolErrorResult {\n /** Result discriminant for exhaustive tool-result handling. */\n readonly type: \"error\";\n /** Stable id matching the execution context call id. */\n readonly toolCallId: string;\n /** Tool identity that produced the error. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable normalized error. */\n readonly error: RuntimeToolError;\n /** Optional serializable result metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Runtime tool result union shared by every coordination protocol.\n */\nexport type RuntimeToolResult<Output = JsonValue> =\n | RuntimeToolSuccessResult<Output>\n | RuntimeToolErrorResult;\n\n/**\n * Tool call/result pair preserved on the transcript entry for the model turn\n * that requested it.\n */\nexport interface TranscriptToolCall {\n /** Stable id shared by the request event and result payload. */\n readonly toolCallId: string;\n /** Tool identity selected for execution. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool input requested by the model/provider adapter. */\n readonly input: JsonObject;\n /** Normalized JSON-serializable tool result returned by the runtime tool. */\n readonly result: RuntimeToolResult;\n}\n\n/**\n * Protocol-agnostic runtime tool definition.\n *\n * @remarks\n * This is the low-level tool escape hatch used by applications and research\n * harnesses. Core owns the orchestration context and serializable result\n * contract; callers own the actual implementation and any fetch-based I/O the\n * tool performs. `inputSchema` is the model-visible JSON contract; optional\n * `validateInput` is the adapter-owned runtime check applied immediately before\n * `execute`.\n */\nexport interface RuntimeTool<Input extends object = JsonObject, Output = JsonValue> {\n /** Stable identity and model-visible description. */\n readonly identity: RuntimeToolIdentity;\n /** JSON-compatible schema for the object input expected by `execute`. */\n readonly inputSchema: RuntimeToolInputSchema;\n /** Optional permissions the adapter needs from caller policy before execution. */\n readonly permissions?: readonly RuntimeToolPermission[];\n /**\n * Optional adapter-owned input validation hook evaluated before execution.\n *\n * @remarks\n * Dogpile validates that this property is callable at registration time.\n * During a tool call, Dogpile invokes it after the `tool-call` event and\n * before `execute`. Returning `{ type: \"invalid\", issues }` prevents\n * `execute` from running and produces a `RuntimeToolErrorResult` with\n * `error.code: \"invalid-input\"` and serializable issue details. Use this\n * hook for deterministic, side-effect-free runtime checks that narrow the\n * JSON input before the tool performs I/O.\n */\n validateInput?(input: Readonly<Input>): RuntimeToolValidationResult;\n /** Execute the tool for one protocol-managed call. */\n execute(\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext\n ): RuntimeToolResult<Output> | Promise<RuntimeToolResult<Output>>;\n}\n\n/**\n * Permission declaration for tool adapters.\n *\n * @remarks\n * Permissions are declarative and serializable. Dogpile core does not grant\n * capabilities itself; applications and protocol harnesses can inspect this\n * data before exposing tools to model-driven execution.\n */\nexport type RuntimeToolPermission =\n | RuntimeToolNetworkPermission\n | RuntimeToolCodeExecutionPermission\n | RuntimeToolCustomPermission;\n\n/**\n * Permission declaration for fetch-compatible network access.\n */\nexport interface RuntimeToolNetworkPermission {\n /** Permission discriminant. */\n readonly kind: \"network\";\n /** Optional host allowlist expected by the adapter. */\n readonly allowHosts?: readonly string[];\n /** Whether private-network destinations may be reached. */\n readonly allowPrivateNetwork?: boolean;\n}\n\n/**\n * Permission declaration for caller-owned code execution sandboxes.\n */\nexport interface RuntimeToolCodeExecutionPermission {\n /** Permission discriminant. */\n readonly kind: \"code-execution\";\n /** Sandbox boundary supplied by the caller or host application. */\n readonly sandbox: \"caller-provided\" | \"none\";\n /** Optional language allowlist exposed by the adapter. */\n readonly languages?: readonly string[];\n /** Whether executed code may perform network I/O inside the sandbox. */\n readonly allowNetwork?: boolean;\n}\n\n/**\n * Permission declaration for adapter-specific capabilities.\n */\nexport interface RuntimeToolCustomPermission {\n /** Permission discriminant. */\n readonly kind: \"custom\";\n /** Stable custom permission name. */\n readonly name: string;\n /** Optional human-readable policy note for caller-owned authorization checks. */\n readonly description?: string;\n /** Optional serializable policy metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared validation issue emitted before a tool adapter executes.\n */\nexport interface RuntimeToolValidationIssue {\n /** Machine-readable validation code. */\n readonly code: \"invalid-type\" | \"missing-field\" | \"invalid-value\" | \"out-of-range\";\n /** Dot-path or field name that failed validation. */\n readonly path: string;\n /** Human-readable validation message. */\n readonly message: string;\n /** Optional serializable diagnostic detail. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Shared validation result for adapter input checks.\n */\nexport type RuntimeToolValidationResult =\n | RuntimeToolValidationValidResult\n | RuntimeToolValidationInvalidResult;\n\n/**\n * Valid adapter input.\n */\nexport interface RuntimeToolValidationValidResult {\n /** Validation discriminant. */\n readonly type: \"valid\";\n}\n\n/**\n * Invalid adapter input.\n */\nexport interface RuntimeToolValidationInvalidResult {\n /** Validation discriminant. */\n readonly type: \"invalid\";\n /** One or more serializable validation issues. */\n readonly issues: readonly RuntimeToolValidationIssue[];\n}\n\n/**\n * Common adapter error codes used by built-in and third-party tools.\n */\nexport type RuntimeToolAdapterErrorCode =\n | \"invalid-input\"\n | \"permission-denied\"\n | \"timeout\"\n | \"aborted\"\n | \"unavailable\"\n | \"backend-error\"\n | \"unknown\";\n\n/**\n * Normalized adapter error data.\n */\nexport interface RuntimeToolAdapterError extends RuntimeToolError {\n /** Common machine-readable adapter error code. */\n readonly code: RuntimeToolAdapterErrorCode;\n}\n\n/**\n * Shared adapter contract implemented by built-in adapters and low-level tools.\n */\nexport interface RuntimeToolAdapterContract<Input extends object = JsonObject, Output = JsonValue>\n extends RuntimeTool<Input, Output> {\n /** Permissions required before this adapter should be exposed or executed. */\n readonly permissions: readonly RuntimeToolPermission[];\n /** Adapter-owned input validation hook. */\n validateInput(input: Readonly<Input>): RuntimeToolValidationResult;\n}\n\n/**\n * Required output artifact for a benchmark task.\n */\nexport interface BenchmarkRequiredArtifact {\n /** Stable artifact name used by scorers and reports. */\n readonly name: string;\n /** Fixture-defined artifact shape, for example `enum` or `markdown_table`. */\n readonly type: string;\n /** Optional human-readable artifact requirement. */\n readonly description?: string;\n /** Optional allowed values for constrained artifacts. */\n readonly allowedValues?: readonly string[];\n}\n\n/**\n * Serializable task input shared by benchmark protocol runners.\n */\nexport interface BenchmarkTaskInput {\n /** Stable benchmark task id. */\n readonly id: string;\n /** Mission text supplied to protocol runners. */\n readonly intent: string;\n /** Optional task title for reports. */\n readonly title?: string;\n /** Optional benchmark difficulty or paper task level, such as `L3`. */\n readonly level?: string;\n /** Required artifacts the run output must contain. */\n readonly requiredArtifacts?: readonly BenchmarkRequiredArtifact[];\n /** Serializable scoring rubric or fixture-specific judging metadata. */\n readonly rubric?: JsonObject;\n /** Additional serializable fixture metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Benchmark budget controls shared by all protocol runners in one comparison.\n */\nexport interface BenchmarkBudget {\n /** Named cost/quality tier selected for the benchmark run. */\n readonly tier: Tier;\n /** Optional maximum spend in US dollars. */\n readonly maxUsd?: number;\n /** Optional maximum input token count. */\n readonly maxInputTokens?: number;\n /** Optional maximum output token count. */\n readonly maxOutputTokens?: number;\n /** Optional maximum total token count. */\n readonly maxTotalTokens?: number;\n /** Optional quality preference in the inclusive range `0..1`. */\n readonly qualityWeight?: number;\n}\n\n/**\n * Benchmark model settings shared across protocol runners.\n *\n * @remarks\n * Research and reproduction workflows use this object to hold provider\n * settings constant while changing only the coordination protocol. The\n * `metadata` field is for serializable experiment labels such as corpus id,\n * prompt template version, model family, or paper reproduction condition.\n */\nexport interface BenchmarkModelSettings {\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly provider: ConfiguredModelProvider;\n /** Optional fixed temperature for controlled reproduction runs. */\n readonly temperature?: number;\n /** Optional deterministic seed recorded for provider adapters that support it. */\n readonly seed?: number;\n /** Additional serializable provider or run metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Shared benchmark runner configuration before selecting a protocol.\n *\n * @remarks\n * This contract carries the task input, budget policy, and model settings that\n * must stay constant when comparing multiple coordination protocols. It is the\n * researcher-facing escape hatch for paper-faithfulness checks: callers can\n * project one task into Sequential, Broadcast, Shared, and Coordinator runs\n * while preserving the same agents, tier, caps, model, and fixture metadata.\n *\n * The object is intentionally JSON-adjacent and storage-free. Persist benchmark\n * inputs, run manifests, and traces in caller-owned systems.\n */\nexport interface BenchmarkRunnerConfig {\n /** Serializable benchmark task input. */\n readonly task: BenchmarkTaskInput;\n /** Shared budget and cap policy. */\n readonly budget: BenchmarkBudget;\n /** Shared model provider and generation settings. */\n readonly model: BenchmarkModelSettings;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Additional serializable benchmark metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * Benchmark configuration for one concrete protocol runner invocation.\n *\n * @remarks\n * Use this derived shape after selecting the protocol under test. It preserves\n * the shared benchmark controls from {@link BenchmarkRunnerConfig} and adds a\n * named or explicit {@link ProtocolConfig}, which lets reproduction code tune\n * protocol-native parameters without widening the high-level API.\n */\nexport interface ProtocolBenchmarkRunConfig extends BenchmarkRunnerConfig {\n /** Protocol being evaluated under the shared benchmark settings. */\n readonly protocol: Protocol | ProtocolConfig;\n}\n\n/**\n * Serializable benchmark protocol descriptor persisted with run artifacts.\n *\n * @remarks\n * Benchmark artifacts record both the normalized protocol name and the exact\n * caller-supplied protocol config so a reproduction harness can distinguish\n * `\"sequential\"` defaults from `{ kind: \"sequential\", maxTurns: 4 }`.\n */\nexport interface BenchmarkProtocolArtifact {\n /** Normalized protocol name used for comparison grouping. */\n readonly kind: Protocol;\n /** Exact protocol value supplied to the runner. */\n readonly config: Protocol | ProtocolConfig;\n}\n\n/**\n * Reproducibility metadata persisted with every benchmark run artifact.\n *\n * @remarks\n * This shape intentionally stores provider identity and serializable model\n * settings, but not the provider implementation itself. Callers own provider\n * construction and external storage; Dogpile owns the portable artifact shape.\n */\nexport interface BenchmarkReproducibilityArtifact {\n /** Benchmark task input used for this run. */\n readonly task: BenchmarkTaskInput;\n /** Shared budget and cap policy used for this run. */\n readonly budget: BenchmarkBudget;\n /** Protocol selected for this run. */\n readonly protocol: BenchmarkProtocolArtifact;\n /** Provider id recorded from the configured model. */\n readonly modelProviderId: string;\n /** Optional fixed temperature used for the run. */\n readonly temperature?: number;\n /** Optional deterministic seed recorded for provider adapters that support it. */\n readonly seed?: number;\n /** Additional serializable provider or run metadata. */\n readonly modelMetadata?: JsonObject;\n /** Concrete agent roster used for the run. */\n readonly agents: readonly AgentSpec[];\n /** Additional serializable benchmark metadata. */\n readonly benchmarkMetadata?: JsonObject;\n}\n\n/**\n * Cost and budget metadata recorded for one benchmark run.\n *\n * @remarks\n * This accounting block is intentionally duplicated from the run result and\n * benchmark controls so benchmark reports can group, filter, and audit spend\n * without unpacking the full trace or reproduction object. Utilization fields\n * are only present when the corresponding cap was configured.\n */\nexport interface BenchmarkCostAccounting {\n /** Accounting artifact discriminant for future benchmark metadata unions. */\n readonly kind: \"benchmark-cost-accounting\";\n /** Named budget/cost tier selected for this benchmark run. */\n readonly tier: Tier;\n /** Shared benchmark budget and cap policy used for this run. */\n readonly budget: BenchmarkBudget;\n /** Total token and spend accounting observed for this run. */\n readonly cost: CostSummary;\n /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */\n readonly usdCapUtilization?: number;\n /** Fraction of the configured total-token cap consumed, when `maxTotalTokens` is present. */\n readonly totalTokenCapUtilization?: number;\n}\n\n/**\n * Structured streaming event log captured for one benchmark run.\n *\n * @remarks\n * Benchmark artifacts keep this log beside the full trace so reproduction\n * harnesses can inspect exactly what the streaming API yielded during the run\n * without unpacking unrelated trace metadata. The `events` array must match\n * `trace.events` for completed runs.\n */\nexport interface BenchmarkStreamingEventLog {\n /** Event-log discriminant for future benchmark observability artifacts. */\n readonly kind: \"benchmark-streaming-event-log\";\n /** Stable run id shared by the benchmark artifact and trace. */\n readonly runId: string;\n /** Protocol whose streaming events were captured. */\n readonly protocol: Protocol;\n /** Ordered event kinds for compact coverage checks. */\n readonly eventTypes: readonly RunEvent[\"type\"][];\n /** Number of streaming events captured. */\n readonly eventCount: number;\n /** Complete ordered streaming events yielded by the run. */\n readonly events: readonly RunEvent[];\n}\n\n/**\n * Serializable score persisted for one protocol benchmark artifact.\n *\n * @remarks\n * The score is protocol-scoped because paper reproduction reports compare the\n * same task across protocol variants. When a judge supplies\n * {@link RunResult.quality}, the benchmark score records that value on a\n * 0..100 scale. Otherwise Dogpile computes a conservative artifact-completeness\n * score from the captured output, transcript, streaming event log, and budget\n * accounting so unjudged benchmark artifacts still carry an auditable score\n * derived from stored data.\n */\nexport interface BenchmarkProtocolScore {\n /** Score artifact discriminant for future benchmark scoring variants. */\n readonly kind: \"benchmark-protocol-score\";\n /** Protocol this score belongs to. */\n readonly protocol: Protocol;\n /** Score in the inclusive range `0..100`. */\n readonly score: number;\n /** Normalized score in the inclusive range `0..1`. */\n readonly normalizedScore: number;\n /** Maximum score for the current scoring scale. */\n readonly maxScore: 100;\n /** How the score was derived. */\n readonly source: \"run-quality\" | \"artifact-completeness\";\n /** Compact scoring dimensions used to compute the stored score. */\n readonly dimensions: readonly BenchmarkScoreDimension[];\n}\n\n/**\n * One serializable dimension contributing to a benchmark protocol score.\n */\nexport interface BenchmarkScoreDimension {\n /** Stable dimension name for reports. */\n readonly name: string;\n /** Earned points for this dimension. */\n readonly score: number;\n /** Maximum points available for this dimension. */\n readonly maxScore: number;\n}\n\n/**\n * Reproducible benchmark output artifact for one protocol run.\n *\n * @remarks\n * This is the storage-free persistence contract for reproduction workflows:\n * callers can write the object to JSON, NDJSON, object storage, or a database\n * without Dogpile depending on Node-only filesystem APIs. It contains the final\n * output, full transcript, a structured streaming event log, full trace, cost\n * summary, and all serializable controls needed to replay the run in\n * caller-managed infrastructure.\n */\nexport interface BenchmarkRunArtifact {\n /** Artifact discriminant for future benchmark artifact unions. */\n readonly kind: \"benchmark-run\";\n /** Schema version for reproducible artifact consumers. */\n readonly schemaVersion: \"1.0\";\n /** Stable run id from the trace. */\n readonly runId: string;\n /** ISO-8601 timestamp derived from the first trace event when available. */\n readonly startedAt: string;\n /** ISO-8601 timestamp derived from the final trace event when available. */\n readonly completedAt: string;\n /** Reproduction controls and serializable fixture inputs. */\n readonly reproducibility: BenchmarkReproducibilityArtifact;\n /** Final output produced by the protocol. */\n readonly output: string;\n /** Complete normalized transcript for this run. */\n readonly transcript: readonly TranscriptEntry[];\n /** Structured streaming event log captured for this benchmark run. */\n readonly eventLog: BenchmarkStreamingEventLog;\n /** Full serializable event log and trace for this run. */\n readonly trace: Trace;\n /** Cost, tier, and benchmark budget metadata for this run. */\n readonly accounting: BenchmarkCostAccounting;\n /** Per-protocol benchmark score computed from the captured artifact data. */\n readonly score: BenchmarkProtocolScore;\n /** Total token and spend accounting for this run. */\n readonly cost: CostSummary;\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly quality?: number;\n}\n\n/**\n * Event emitted when a protocol assigns or records an agent role.\n *\n * @remarks\n * This event normally appears near the beginning of a run and establishes the\n * `agentId`/`role` pair that later turn and transcript records refer to. A\n * renderer can use it to build the participant roster before model output\n * starts streaming.\n *\n * Payload shape:\n *\n * - `type`: always `role-assignment`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the assignment was emitted.\n * - `agentId`: stable agent id used in events, trace, and transcript entries.\n * - `role`: model-visible role or perspective assigned to that agent.\n */\nexport interface RoleAssignmentEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"role-assignment\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent receiving the role assignment. */\n readonly agentId: string;\n /** Role assigned to the agent. */\n readonly role: string;\n}\n\n/**\n * Event emitted when Dogpile is about to ask the configured model provider for\n * one protocol-managed response.\n *\n * @remarks\n * This event is the request-side model activity counterpart to\n * {@link ModelResponseEvent}. Protocol implementations may omit it when they\n * only expose completed turns, but adapters and researcher harnesses can emit\n * it to make provider calls visible in the same streaming event log as agent\n * turns and final output.\n */\nexport interface ModelRequestEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-request\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable provider call id within the run. */\n readonly callId: string;\n /** Configured model provider id receiving the request. */\n readonly providerId: string;\n /** Agent requesting the model call. */\n readonly agentId: string;\n /** Agent role for the active model call. */\n readonly role: string;\n /** Provider-neutral request handed to the model adapter. */\n readonly request: ModelRequest;\n}\n\n/**\n * Event emitted after the configured model provider returns one response.\n *\n * @remarks\n * This event records provider-level model activity without forcing callers to\n * infer it from the higher-level {@link TurnEvent}. The response is the same\n * provider-neutral shape captured in replay traces, so it remains portable and\n * JSON-serializable across Node LTS, Bun, and browser ESM runtimes.\n */\nexport interface ModelResponseEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-response\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable provider call id within the run. */\n readonly callId: string;\n /** Configured model provider id that produced the response. */\n readonly providerId: string;\n /** Agent that requested the model call. */\n readonly agentId: string;\n /** Agent role for the completed model call. */\n readonly role: string;\n /** Provider-neutral response returned by the model adapter. */\n readonly response: ModelResponse;\n}\n\n/**\n * Event emitted while a model turn is still generating text.\n *\n * @remarks\n * `model-output-chunk` lets streaming callers render provider output before\n * the protocol has enough information to commit the completed `agent-turn`\n * transcript entry. It is emitted only when the configured model provider\n * implements {@link ConfiguredModelProvider.stream}; non-streaming providers\n * continue to produce the existing role/turn/final event sequence.\n *\n * Payload shape:\n *\n * - `type`: always `model-output-chunk`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the chunk was observed.\n * - `agentId` and `role`: identify the active generating agent.\n * - `input`: prompt text visible to that agent for this turn.\n * - `chunkIndex`: zero-based chunk index within this model turn.\n * - `text`: text delta from the provider.\n * - `output`: accumulated output for this turn after applying the chunk.\n */\nexport interface ModelOutputChunkEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"model-output-chunk\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent currently producing output. */\n readonly agentId: string;\n /** Agent role for the active turn. */\n readonly role: string;\n /** Prompt/input visible to the agent for this turn. */\n readonly input: string;\n /** Zero-based chunk index within the active model turn. */\n readonly chunkIndex: number;\n /** Text delta produced by the model provider. */\n readonly text: string;\n /** Accumulated output for this turn after applying this chunk. */\n readonly output: string;\n}\n\n/**\n * Event emitted when a runtime tool is invoked by protocol or model policy.\n *\n * @remarks\n * Tools are caller-owned escape hatches. This request-side event keeps tool\n * invocation observable without making Dogpile core depend on Node-only\n * capabilities, a storage layer, or a provider-specific function-call shape.\n */\nexport interface ToolCallEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"tool-call\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable tool call id within the run. */\n readonly toolCallId: string;\n /** Tool identity selected for execution. */\n readonly tool: RuntimeToolIdentity;\n /** JSON-serializable tool input. */\n readonly input: JsonObject;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Agent role that requested the tool, when available. */\n readonly role?: string;\n}\n\n/**\n * Event emitted after a runtime tool returns a normalized result.\n *\n * @remarks\n * Tool failures are data at the public boundary. The result payload uses the\n * same discriminated union as runtime tool adapters, allowing log consumers to\n * render successful outputs and normalized errors exhaustively.\n */\nexport interface ToolResultEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"tool-result\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Stable tool call id within the run. */\n readonly toolCallId: string;\n /** Tool identity that produced the result. */\n readonly tool: RuntimeToolIdentity;\n /** Normalized JSON-serializable tool result. */\n readonly result: RuntimeToolResult;\n /** Agent that requested the tool, when agent-scoped. */\n readonly agentId?: string;\n /** Agent role that requested the tool, when available. */\n readonly role?: string;\n}\n\n/**\n * Provider-normalized participation decision parsed from paper-style agent output.\n *\n * @remarks\n * Dogpile preserves the raw model text on transcript entries and events. When\n * a model emits the labeled fields `role_selected`, `participation`,\n * `rationale`, and `contribution`, protocols also attach this structured\n * metadata so reproduction harnesses can distinguish contribution from\n * voluntary abstention without reparsing raw text.\n */\nexport interface AgentDecision {\n /** Task-specific role selected by the agent for this turn. */\n readonly selectedRole: string;\n /** Whether the agent contributed or voluntarily abstained. */\n readonly participation: AgentParticipation;\n /** Agent-provided rationale for the selected role and participation choice. */\n readonly rationale: string;\n /** Agent-provided contribution text, or abstention explanation. */\n readonly contribution: string;\n}\n\n/**\n * Agent participation state for a paper-style turn decision.\n */\nexport type AgentParticipation = \"contribute\" | \"abstain\";\n\n/**\n * Event emitted after one agent contributes a model turn.\n *\n * @remarks\n * `agent-turn` is the primary streaming payload for sequential, coordinator,\n * shared-state, and broadcast executions. It captures the exact prompt/input\n * Dogpile supplied to the agent, the text returned by the model provider, and\n * the cumulative cost after applying that response.\n *\n * The corresponding durable transcript record contains the same\n * `agentId`/`role`/`input`/`output` contribution without event timing or cost\n * fields. Use this event for live progress UIs and the transcript for replay\n * or downstream application logic.\n *\n * Payload shape:\n *\n * - `type`: always `agent-turn`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the turn completed.\n * - `agentId` and `role`: identify the contributing agent.\n * - `input`: prompt text visible to that agent for this turn.\n * - `output`: generated model text produced by the agent.\n * - `cost`: cumulative token and spend accounting after this turn.\n */\nexport interface TurnEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"agent-turn\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Agent that produced this turn. */\n readonly agentId: string;\n /** Agent role for this turn. */\n readonly role: string;\n /** Prompt/input visible to the agent for this turn. */\n readonly input: string;\n /** Model output produced by the agent. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n /** Cumulative cost after this turn. */\n readonly cost: CostSummary;\n}\n\n/**\n * One independent contribution captured by a broadcast round event.\n *\n * @remarks\n * Broadcast protocols collect one contribution per participating agent before\n * synthesis. The contribution payload is intentionally smaller than\n * {@link TurnEvent}: it is a round-level summary of model outputs, while the\n * complete prompt/output pair for each agent is still available as individual\n * `agent-turn` events and {@link TranscriptEntry} records.\n *\n * Payload shape:\n *\n * - `agentId`: stable id of the contributing agent.\n * - `role`: model-visible role or perspective used for that contribution.\n * - `output`: generated text contributed independently for the round.\n */\nexport interface BroadcastContribution {\n /** Agent that produced the broadcast contribution. */\n readonly agentId: string;\n /** Agent role for the contribution. */\n readonly role: string;\n /** Independent model output produced for the shared mission. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n}\n\n/**\n * Event emitted after agents broadcast independent contributions for a round.\n *\n * @remarks\n * A `broadcast` event marks the coordination moment where independently\n * generated agent outputs are gathered for a shared round. It does not replace\n * per-agent `agent-turn` events; instead, it groups their outputs by round so\n * observers can render the broadcast barrier and replay the paper protocol's\n * independent-contribution step.\n *\n * Payload shape:\n *\n * - `type`: always `broadcast`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when the round finished.\n * - `round`: one-based broadcast round number.\n * - `contributions`: independent outputs collected for this round.\n * - `cost`: cumulative token and spend accounting after the round.\n */\nexport interface BroadcastEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"broadcast\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** One-based broadcast round number. */\n readonly round: number;\n /** Independent contributions collected in this broadcast round. */\n readonly contributions: readonly BroadcastContribution[];\n /** Cumulative cost after this broadcast round. */\n readonly cost: CostSummary;\n}\n\n/**\n * Event emitted when a workflow halts because a configured budget cap fired.\n *\n * @remarks\n * `budget-stop` records the normalized cap class that stopped execution before\n * the final event closes the run. The detail object is JSON-serializable so\n * callers can persist or replay the exact cap, observed value, and limit.\n */\nexport interface BudgetStopEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"budget-stop\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Normalized machine-readable budget stop reason. */\n readonly reason: BudgetStopReason;\n /** Total cost at the stop point. */\n readonly cost: CostSummary;\n /** Completed model-turn iterations at the stop point. */\n readonly iteration: number;\n /** Elapsed runtime in milliseconds at the stop point. */\n readonly elapsedMs: number;\n /** Serializable cap diagnostics. */\n readonly detail: JsonObject;\n}\n\n/**\n * Link from a terminal event to the completed trace transcript.\n *\n * @remarks\n * Final events are emitted before callers await {@link StreamHandle.result},\n * so this compact link tells streaming UIs exactly which transcript artifact\n * the terminal output closes over without duplicating every transcript entry\n * inside the event log.\n */\nexport interface TranscriptLink {\n /** Discriminant for future transcript link variants. */\n readonly kind: \"trace-transcript\";\n /** Number of transcript entries included in the completed trace. */\n readonly entryCount: number;\n /** Zero-based index of the last transcript entry, or `null` for empty runs. */\n readonly lastEntryIndex: number | null;\n}\n\n/**\n * Event emitted when a workflow produces its final output.\n *\n * @remarks\n * `final` is the terminal streaming event for a successful run. Its `output`\n * value matches {@link RunResult.output}, and its `cost` value matches the\n * final aggregate cost returned on the result. Its `transcript` link points to\n * the completed {@link Trace.transcript} entries that produced the terminal\n * output.\n *\n * Payload shape:\n *\n * - `type`: always `final`.\n * - `runId`: stable id shared by every event and trace object for the run.\n * - `at`: ISO-8601 timestamp for when final synthesis completed.\n * - `output`: final synthesized answer returned to the caller.\n * - `cost`: total token and spend accounting for the run.\n * - `transcript`: compact link to the completed trace transcript.\n */\nexport interface FinalEvent {\n /** Discriminant for event rendering and exhaustive switches. */\n readonly type: \"final\";\n /** Stable run id shared by all events in one workflow. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Final synthesized answer returned as `RunResult.output`. */\n readonly output: string;\n /** Total cost at completion. */\n readonly cost: CostSummary;\n /** Link to the completed trace transcript. */\n readonly transcript: TranscriptLink;\n /** Optional normalized quality score supplied by a caller-owned evaluator. */\n readonly quality?: NormalizedQualityScore;\n /** Optional serializable evaluation payload supplied by a caller-owned evaluator. */\n readonly evaluation?: RunEvaluation;\n /** Termination condition that stopped the run, when the run ended by policy. */\n readonly termination?: TerminationStopRecord;\n}\n\n/**\n * Successful coordination event emitted by Dogpile and persisted in traces.\n *\n * @remarks\n * `RunEvent` is the discriminated union stored in {@link Trace.events} and\n * used by low-level protocol emit callbacks. Switch on `type` to handle each\n * coordination moment exhaustively:\n *\n * - `role-assignment`: participant/role roster was established.\n * - `model-request`: one provider-neutral model request was started.\n * - `model-response`: one provider-neutral model response completed.\n * - `model-output-chunk`: one streaming model text delta arrived.\n * - `tool-call`: one runtime tool invocation was started.\n * - `tool-result`: one runtime tool invocation completed.\n * - `agent-turn`: one agent completed a prompt/response turn.\n * - `broadcast`: a broadcast round gathered independent contributions.\n * - `budget-stop`: a configured budget cap halted further model turns.\n * - `final`: the run completed and produced the final output.\n *\n * Every variant is JSON-serializable and includes `runId` plus an ISO-8601\n * `at` timestamp so callers can persist, render, or replay the event log\n * without SDK-owned storage.\n *\n * @example\n * ```ts\n * for await (const event of Dogpile.stream(options)) {\n * switch (event.type) {\n * case \"agent-turn\":\n * console.log(event.agentId, event.output);\n * break;\n * case \"final\":\n * console.log(event.output);\n * break;\n * }\n * }\n * ```\n */\nexport type RunEvent =\n | RoleAssignmentEvent\n | ModelRequestEvent\n | ModelResponseEvent\n | ModelOutputChunkEvent\n | ToolCallEvent\n | ToolResultEvent\n | TurnEvent\n | BroadcastEvent\n | BudgetStopEvent\n | FinalEvent;\n\n/**\n * Model activity events yielded by `stream()` and persisted in traces when a\n * protocol exposes provider-call boundaries.\n */\nexport type ModelActivityEvent = ModelRequestEvent | ModelResponseEvent | ModelOutputChunkEvent;\n\n/**\n * Tool activity events yielded by `stream()` and persisted in traces when a\n * protocol or caller-owned adapter invokes runtime tools.\n */\nexport type ToolActivityEvent = ToolCallEvent | ToolResultEvent;\n\n/**\n * Lifecycle event yielded by `stream()`.\n *\n * These events describe workflow coordination state rather than model text.\n * Role assignment establishes the participant roster, while `budget-stop`\n * records a lifecycle halt before the terminal completion event.\n */\nexport type StreamLifecycleEvent = RoleAssignmentEvent | BudgetStopEvent;\n\n/**\n * Output event yielded by `stream()`.\n *\n * These events carry generated agent output or grouped round output while a\n * workflow is still running.\n */\nexport type StreamOutputEvent = ModelActivityEvent | ToolActivityEvent | TurnEvent | BroadcastEvent;\n\n/**\n * Error event yielded by `stream()` when execution rejects.\n *\n * @remarks\n * Stream errors are emitted before {@link StreamHandle.result} rejects so UIs\n * and log collectors can record a terminal failure without wrapping the result\n * promise. The error payload is JSON-serializable and intentionally omits\n * runtime-specific values such as `Error.stack`.\n */\nexport interface StreamErrorEvent {\n /** Discriminant for stream event handling. */\n readonly type: \"error\";\n /** Stable run id when known; empty when failure happened before protocol startup. */\n readonly runId: string;\n /** ISO-8601 event timestamp. */\n readonly at: string;\n /** Error name when available. */\n readonly name: string;\n /** Human-readable error message. */\n readonly message: string;\n /** Optional serializable diagnostics supplied by the SDK. */\n readonly detail?: JsonObject;\n}\n\n/**\n * Completion event yielded by `stream()` after successful execution.\n */\nexport type StreamCompletionEvent = FinalEvent;\n\n/**\n * Public streaming event union returned by `stream()`.\n *\n * @remarks\n * The union is grouped into lifecycle, output, error, and completion families:\n *\n * - lifecycle: {@link StreamLifecycleEvent}\n * - output: {@link StreamOutputEvent}\n * - error: {@link StreamErrorEvent}\n * - completion: {@link StreamCompletionEvent}\n *\n * Successful stream events are also persisted as {@link RunEvent} values in the\n * completed trace. `error` is stream-only because a failed run has no completed\n * {@link RunResult} trace to return.\n */\nexport type StreamEvent = StreamLifecycleEvent | StreamOutputEvent | StreamErrorEvent | StreamCompletionEvent;\n\n/**\n * Lifecycle status for a live {@link StreamHandle}.\n */\nexport type StreamHandleStatus = \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\n/**\n * Normalized transcript entry captured during a run.\n *\n * @remarks\n * The transcript is an ordered list of model-visible contributions. Each entry\n * represents exactly one agent prompt/response pair in the order Dogpile\n * executed it. Unlike {@link RunEvent}, transcript entries omit lifecycle\n * timing, broadcast grouping, and cumulative cost so the structure stays small\n * and stable for application display, caller-managed persistence, and replay\n * fixtures.\n *\n * Transcript structure:\n *\n * - `agentId`: stable id of the agent that produced the contribution.\n * - `role`: model-visible role or perspective for that contribution.\n * - `input`: prompt text visible to the agent for that turn.\n * - `output`: generated text returned by the model provider.\n * - `toolCalls`: optional ordered tool call/result pairs requested during\n * that turn.\n *\n * `RunResult.transcript` and `Trace.transcript` contain the same ordered\n * entries; the result-level copy exists for ergonomic access while the trace\n * keeps the complete serializable replay artifact together.\n */\nexport interface TranscriptEntry {\n /** Agent that produced the transcript contribution. */\n readonly agentId: string;\n /** Agent role for the contribution. */\n readonly role: string;\n /** Prompt/input visible to the agent. */\n readonly input: string;\n /** Text produced by the agent. */\n readonly output: string;\n /** Optional structured role/participation decision parsed from model output. */\n readonly decision?: AgentDecision;\n /** Ordered runtime tool calls and results requested during this turn. */\n readonly toolCalls?: readonly TranscriptToolCall[];\n}\n\n/**\n * Complete transcript artifact for a finished run.\n *\n * @remarks\n * High-level APIs expose `readonly TranscriptEntry[]` directly for ergonomic\n * application use. This named structure is the durable artifact shape for\n * callers that want a self-describing transcript object with the run id, entry\n * count, and final output bundled together for persistence or replay.\n */\nexport interface Transcript {\n /** Transcript artifact discriminant. */\n readonly kind: \"run-transcript\";\n /** Stable run id shared by the source trace and event log. */\n readonly runId: string;\n /** Number of entries in the completed transcript. */\n readonly entryCount: number;\n /** Ordered agent prompt/response entries. */\n readonly entries: readonly TranscriptEntry[];\n /** Final synthesized output produced from these entries. */\n readonly finalOutput: string;\n}\n\n/**\n * Token and spend accounting for a run or turn.\n */\nexport interface CostSummary {\n /** Estimated spend in US dollars. */\n readonly usd: number;\n /** Input tokens consumed. */\n readonly inputTokens: number;\n /** Output tokens generated. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n}\n\n/**\n * Aggregate provider usage reported for a completed run.\n *\n * This mirrors {@link CostSummary} at the non-streaming result boundary so\n * callers can read model usage without treating spend accounting as the only\n * usage artifact. It remains JSON-serializable and runtime-neutral.\n */\nexport interface RunUsage {\n /** Estimated spend in US dollars. */\n readonly usd: number;\n /** Input tokens consumed across all model calls. */\n readonly inputTokens: number;\n /** Output tokens generated across all model calls. */\n readonly outputTokens: number;\n /** Combined input and output token count. */\n readonly totalTokens: number;\n}\n\n/**\n * Result-level cost and budget accounting for a completed run.\n *\n * @remarks\n * This block makes budget state first-class on {@link RunResult} without\n * forcing application code to unpack the full replay trace. It records the\n * selected tier, caller-supplied caps, optional termination policy, final\n * usage/cost totals, and compact cap-utilization metadata.\n */\nexport interface RunAccounting {\n /** Accounting artifact discriminant. */\n readonly kind: \"run-accounting\";\n /** Named budget/cost tier selected for the run. */\n readonly tier: Tier;\n /** Optional hard caps supplied by the caller. */\n readonly budget?: BudgetCaps;\n /** Optional termination policy used by the protocol. */\n readonly termination?: TerminationCondition;\n /** Total token and spend usage for the run. */\n readonly usage: RunUsage;\n /** Total token and spend cost for the run. */\n readonly cost: CostSummary;\n /** Ordered budget state snapshots derived from cost-bearing events. */\n readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];\n /** Fraction of the configured USD cap consumed, when `maxUsd` is present. */\n readonly usdCapUtilization?: number;\n /** Fraction of the configured total-token cap consumed, when `maxTokens` is present. */\n readonly totalTokenCapUtilization?: number;\n}\n\n/**\n * Normalized quality score for a completed run.\n *\n * Values use the inclusive `0..1` range. The field is optional on\n * {@link RunResult} because production model runs may not have a judge, while\n * benchmark and researcher harnesses can attach a score without changing the\n * single-call result shape.\n */\nexport type NormalizedQualityScore = number;\n\n/**\n * Serializable evaluation payload for a completed run.\n *\n * @remarks\n * Applications and benchmark harnesses can attach caller-owned judge output\n * without making Dogpile core depend on a storage layer, model-specific judge,\n * or Node-only runtime. The `quality` value is mirrored to\n * {@link RunResult.quality} and the terminal {@link FinalEvent} so streaming\n * and non-streaming execution expose the same judged result.\n */\nexport interface RunEvaluation {\n /** Normalized quality score in the inclusive range `0..1`. */\n readonly quality: NormalizedQualityScore;\n /** Optional human-readable judge rationale. */\n readonly rationale?: string;\n /** Optional serializable judge or benchmark metadata. */\n readonly metadata?: JsonObject;\n}\n\n/**\n * JSON-serializable trace returned with every completed workflow.\n *\n * @remarks\n * This is the canonical caller-managed replay artifact. Dogpile core remains\n * stateless, so every SDK-owned fact needed to inspect a completed run is\n * represented as JSON-compatible data here: normalized inputs, budget policy,\n * seed metadata, ordered events, protocol decisions, provider requests and\n * responses, budget snapshots, transcript entries, and the final output.\n *\n * Event order is authoritative. `events[n]` is the source coordination moment\n * for `protocolDecisions[n]`, and `RunEventLog.events` uses the same order as\n * this trace for completed runs. Provider calls are ordered by execution and\n * capture the exact {@link ModelRequest} handed to the configured adapter plus\n * the exact {@link ModelResponse} returned by that adapter, including optional\n * usage and cost telemetry. Current protocol runners keep provider calls\n * one-to-one with transcript entries and completed `agent-turn` events.\n */\nexport interface Trace {\n /** Replay trace schema version. */\n readonly schemaVersion: ReplayTraceSchemaVersion;\n /** Stable id for this workflow run. */\n readonly runId: string;\n /** Protocol that produced this trace. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Configured model provider id used by the run. */\n readonly modelProviderId: string;\n /** Concrete agents that participated in the run. */\n readonly agentsUsed: readonly AgentSpec[];\n /** Normalized caller inputs needed to replay this run. */\n readonly inputs: ReplayTraceRunInputs;\n /** Budget caps and termination policy used by this run. */\n readonly budget: ReplayTraceBudget;\n /** Ordered budget state snapshots derived from cost-bearing events. */\n readonly budgetStateChanges: readonly ReplayTraceBudgetStateChange[];\n /** Deterministic seed metadata for replay tooling. */\n readonly seed: ReplayTraceSeed;\n /** Ordered protocol decisions derived from the event log. */\n readonly protocolDecisions: readonly ReplayTraceProtocolDecision[];\n /** Provider requests and responses captured during execution. */\n readonly providerCalls: readonly ReplayTraceProviderCall[];\n /** Final output artifact for replay consumers. */\n readonly finalOutput: ReplayTraceFinalOutput;\n /**\n * Ordered coordination and lifecycle events.\n *\n * This is the complete streaming event log captured during execution. It has\n * the same event shapes yielded by {@link StreamHandle} and remains\n * JSON-serializable for caller-managed replay.\n */\n readonly events: readonly RunEvent[];\n /**\n * Complete normalized model-turn transcript.\n *\n * Entries are ordered by execution and contain only agent id, role, input,\n * and output. Use this when the application needs the conversation artifact\n * without streaming lifecycle metadata.\n */\n readonly transcript: readonly TranscriptEntry[];\n}\n\n/**\n * Complete event log returned by non-streaming APIs.\n *\n * This is the result-level counterpart to the live {@link StreamHandle}\n * iterator. It contains the exact ordered events also stored in\n * {@link Trace.events}, plus compact metadata useful for dashboards and tests\n * that do not need to unpack the full trace.\n */\nexport interface RunEventLog {\n /** Event-log artifact discriminant. */\n readonly kind: \"run-event-log\";\n /** Stable id shared by every event in this log. */\n readonly runId: string;\n /** Protocol that produced the event log. */\n readonly protocol: Protocol;\n /** Ordered event kinds for compact coverage checks. */\n readonly eventTypes: readonly RunEvent[\"type\"][];\n /** Number of events captured. */\n readonly eventCount: number;\n /** Complete ordered event log for the run. */\n readonly events: readonly RunEvent[];\n}\n\n/**\n * Run metadata returned by non-streaming APIs.\n *\n * The metadata block gathers stable identifiers and timing boundaries that are\n * otherwise derivable from {@link Trace}. Keeping it explicit makes the\n * single-call result easier to persist, index, and inspect without adding SDK\n * storage.\n */\nexport interface RunMetadata {\n /** Stable id for this workflow run. */\n readonly runId: string;\n /** Protocol that produced this run. */\n readonly protocol: Protocol;\n /** Cost/quality tier selected for the run. */\n readonly tier: Tier;\n /** Configured model provider id used by the run. */\n readonly modelProviderId: string;\n /** Concrete agents that participated in the run. */\n readonly agentsUsed: readonly AgentSpec[];\n /** ISO-8601 timestamp of the first event, or an empty string for eventless runs. */\n readonly startedAt: string;\n /** ISO-8601 timestamp of the final event, or an empty string for eventless runs. */\n readonly completedAt: string;\n}\n\n/**\n * Result returned by high-level single-call APIs.\n *\n * The returned shape is\n * `{ output, eventLog, transcript, usage, metadata, accounting, trace, cost, quality, evaluation }`.\n * `output` is the final synthesized answer, `eventLog` is the complete ordered\n * coordination log, `transcript` is the complete agent-turn transcript,\n * `usage` reports token and dollar accounting, and `metadata` exposes stable\n * run identifiers and timing. `accounting` bundles the selected tier, budget\n * caps, final usage/cost, and cap utilization. `trace` remains the complete\n * serializable replay artifact, `cost` is retained as a compatibility alias\n * for `usage`, and `quality` and `evaluation` are present when a judge or\n * benchmark supplies a normalized score and serializable evaluation payload.\n */\nexport interface RunResult {\n /** Final synthesized answer for the supplied intent. */\n readonly output: string;\n /** Complete non-streaming event log captured during the run. */\n readonly eventLog: RunEventLog;\n /** Full serializable trace and event log. */\n readonly trace: Trace;\n /**\n * Complete normalized transcript for direct application use.\n *\n * This duplicates `trace.transcript` so high-level callers can read the\n * ordered agent contributions without unpacking the full trace object.\n */\n readonly transcript: readonly TranscriptEntry[];\n /** Total usage and spend accounting for the run. */\n readonly usage: RunUsage;\n /** Stable ids, selected controls, provider id, participating agents, and timing boundaries. */\n readonly metadata: RunMetadata;\n /** Result-level budget, usage, cost, and cap-utilization accounting. */\n readonly accounting: RunAccounting;\n /** Total cost and token accounting for the run; compatibility alias for `usage`. */\n readonly cost: CostSummary;\n /** Optional normalized quality score in the inclusive range `0..1`. */\n readonly quality?: NormalizedQualityScore;\n /** Optional serializable evaluation data supplied by a caller-owned evaluator. */\n readonly evaluation?: RunEvaluation;\n}\n\n/**\n * Caller-owned evaluator invoked after protocol execution and before the final\n * result is exposed to `run()` or `stream()` callers.\n */\nexport type RunEvaluator = (result: Omit<RunResult, \"quality\" | \"evaluation\">) => RunEvaluation | Promise<RunEvaluation>;\n\n/**\n * Mission supplied to a high-level Dogpile workflow call.\n *\n * @remarks\n * `intent` is the caller-facing mission statement for the agent collective. It\n * is kept as a named type so applications can expose the same concept without\n * depending on the full {@link DogpileOptions} object.\n */\nexport type MissionIntent = string;\n\n/**\n * Coordination protocol selection accepted by high-level SDK calls.\n *\n * @remarks\n * Pass a named protocol for ergonomic defaults, or a protocol config object\n * when a run needs explicit turn/round limits. The union remains\n * discriminated once normalized through {@link ProtocolConfig}.\n */\nexport type ProtocolSelection = ProtocolName | ProtocolConfig;\n\n/**\n * Compatibility alias for high-level coordination protocol selection.\n */\nexport type CoordinationProtocolSelection = ProtocolSelection;\n\n/**\n * Hard budget caps layered over a selected cost/quality tier.\n *\n * @remarks\n * High-level calls keep `tier` next to `budget`, so the budget object only\n * carries caps and quality weighting. This shape is JSON-serializable and can\n * be copied directly into replay traces.\n */\nexport type BudgetCaps = Omit<Budget, \"tier\">;\n\n/**\n * Cost and budget controls accepted by high-level SDK calls.\n *\n * @remarks\n * Omit `tier` to use the high-level default `balanced` preset. Omit `budget`\n * for an uncapped run beyond the tier preset.\n */\nexport interface BudgetCostTierOptions {\n /**\n * Named budget/cost tier.\n *\n * Supported values are `fast`, `balanced`, and `quality`. Defaults to\n * `balanced` when omitted.\n */\n readonly tier?: BudgetTier;\n /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */\n readonly budget?: BudgetCaps;\n}\n\n/**\n * Advisory wrap-up hint injected into the next model turn near a hard cap.\n */\nexport interface WrapUpHintConfig {\n /** Absolute completed model-turn iteration at which to inject the hint once. */\n readonly atIteration?: number;\n /**\n * Fraction of `maxIterations` or `timeoutMs` at which to inject the hint once.\n *\n * `0.8` means the next turn after reaching 80% of a supported cap receives\n * the wrap-up hint.\n */\n readonly atFraction?: number;\n /**\n * Optional custom hint builder. When omitted, the SDK injects a default\n * message that describes the remaining turn and/or time budget.\n */\n readonly inject?: (context: TerminationEvaluationContext) => string;\n}\n\n/**\n * Options accepted by the high-level single-call workflow APIs.\n *\n * Provide an `intent` and configure a model provider. The high-level surface\n * defaults to the Sequential protocol and `balanced` tier; callers can pass a\n * protocol, tier, agents, temperature, or budget caps to refine execution\n * without constructing an engine.\n */\nexport interface DogpileOptions extends BudgetCostTierOptions {\n /** Mission or intent for the agent collective. */\n readonly intent: MissionIntent;\n /**\n * Coordination protocol, either by name or explicit configuration.\n *\n * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.\n * Named protocols use default configs: `maxTurns: 3` for coordinator,\n * sequential, and shared; `maxRounds: 2` for broadcast.\n */\n readonly protocol?: ProtocolSelection;\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly model: ConfiguredModelProvider;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Optional protocol-agnostic runtime tools available to first-party protocols. */\n readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Optional temperature override. */\n readonly temperature?: number;\n /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */\n readonly terminate?: TerminationCondition;\n /** Optional one-shot advisory hint injected into the next model turn near a hard cap. */\n readonly wrapUpHint?: WrapUpHintConfig;\n /** Optional caller-owned evaluator that supplies quality and evaluation data. */\n readonly evaluate?: RunEvaluator;\n /** Optional deterministic seed recorded in the replay trace. */\n readonly seed?: string | number;\n /** Optional caller cancellation signal passed to provider-facing model requests. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Low-level engine configuration for reusable protocol execution.\n *\n * @remarks\n * Researchers can create one engine with fixed protocol/model/agent settings\n * and run multiple missions through it for controlled comparisons. Application\n * code usually starts with {@link DogpileOptions}; use this escape hatch when\n * you need stable experiment controls, repeated runs against the same model\n * adapter, custom agent rosters, or explicit protocol configs.\n *\n * `budget` is layered over `tier` for caps and quality weighting. The core\n * remains stateless: every run still returns its own serializable trace and\n * transcript, and the caller owns persistence or replay.\n *\n * @example\n * ```ts\n * const engine = createEngine({\n * protocol: { kind: \"sequential\", maxTurns: 4 },\n * tier: \"balanced\",\n * model: provider,\n * agents\n * });\n *\n * const result = await engine.run(\"Compare the protocol variants.\");\n * ```\n */\nexport interface EngineOptions {\n /**\n * Coordination protocol, either by name or explicit configuration.\n *\n * Supported names are `coordinator`, `sequential`, `broadcast`, and `shared`.\n * Named protocols use default configs: `maxTurns: 3` for coordinator,\n * sequential, and shared; `maxRounds: 2` for broadcast.\n */\n readonly protocol: ProtocolSelection;\n /**\n * Named budget/cost tier.\n *\n * Supported values are `fast`, `balanced`, and `quality`. Use `balanced` as\n * the recommended default when callers do not expose a user preference.\n */\n readonly tier: BudgetTier;\n /** Caller-configured model provider, typically backed by the Vercel AI SDK. */\n readonly model: ConfiguredModelProvider;\n /** Optional explicit agents; defaults are used when omitted. */\n readonly agents?: readonly AgentSpec[];\n /** Optional protocol-agnostic runtime tools available to first-party protocols. */\n readonly tools?: readonly RuntimeTool<JsonObject, JsonValue>[];\n /** Optional temperature override. */\n readonly temperature?: number;\n /** Optional hard caps layered over the selected tier; omitted fields are uncapped. */\n readonly budget?: Omit<Budget, \"tier\">;\n /** Optional composable termination policy for budget, convergence, judge, or firstOf stop conditions. */\n readonly terminate?: TerminationCondition;\n /** Optional one-shot advisory hint injected into the next model turn near a hard cap. */\n readonly wrapUpHint?: WrapUpHintConfig;\n /** Optional caller-owned evaluator that supplies quality and evaluation data. */\n readonly evaluate?: RunEvaluator;\n /** Optional deterministic seed recorded in the replay trace. */\n readonly seed?: string | number;\n /** Optional caller cancellation signal passed to provider-facing model requests. */\n readonly signal?: AbortSignal;\n}\n\n/**\n * Async event stream returned by `stream()`.\n *\n * @remarks\n * Iterate the handle to receive live {@link StreamEvent} values. Successful\n * lifecycle, output, and completion events are stored in `result.trace.events`\n * in the same order. If execution fails, the stream yields one `error` event\n * and {@link StreamHandle.result} rejects with the original error.\n *\n * @example\n * ```ts\n * const handle = Dogpile.stream(options);\n *\n * for await (const event of handle) {\n * if (event.type === \"agent-turn\") {\n * renderTurn(event.agentId, event.output);\n * }\n * }\n *\n * const result = await handle.result;\n * ```\n */\nexport interface StreamHandle extends AsyncIterable<StreamEvent> {\n /** Current lifecycle state for this handle. */\n readonly status: StreamHandleStatus;\n /** Final result resolved after the stream completes. */\n readonly result: Promise<RunResult>;\n /**\n * Cancel this live stream.\n *\n * Cancellation aborts the active provider-facing request signal, emits a\n * terminal `error` stream event with `code: \"aborted\"` and\n * `status: \"cancelled\"` diagnostics, rejects {@link result}, and closes the\n * consumer-facing iterator. Calling `cancel()` after the handle has already\n * completed is a no-op.\n */\n cancel(): void;\n /**\n * Attach to live events emitted by this run.\n *\n * Subscribers first receive the events already emitted by the handle, then\n * receive live events until they unsubscribe or the run completes. The\n * returned subscription detaches the listener without cancelling the\n * underlying run, so demos and UIs can mount/unmount against a live SDK\n * workflow while the caller still awaits {@link result}.\n */\n subscribe(subscriber: StreamEventSubscriber): StreamSubscription;\n}\n\n/**\n * Callback invoked for each live streaming event.\n */\nexport type StreamEventSubscriber = (event: StreamEvent) => void;\n\n/**\n * Subscription returned by {@link StreamHandle.subscribe}.\n */\nexport interface StreamSubscription {\n /** Stop delivering future events to the subscriber. */\n unsubscribe(): void;\n}\n\n/**\n * Reusable low-level protocol engine.\n *\n * @remarks\n * `Engine` is the extension point behind the high-level `run()`,\n * `stream()`, and `Dogpile.pile()` helpers. It lets research harnesses reuse\n * one normalized protocol configuration across many missions while choosing\n * between batch results and live event streams.\n *\n * The engine does not retain run history. Store each returned\n * {@link RunResult.trace} in caller-managed infrastructure if you need replay,\n * audit, or benchmark aggregation.\n */\nexport interface Engine {\n /** Execute a mission to completion and return the final result. */\n run(intent: string): Promise<RunResult>;\n /** Stream a mission's events while preserving access to the final result. */\n stream(intent: string): StreamHandle;\n}\n","import type {\n AgentSpec,\n Budget,\n CostSummary,\n Protocol,\n ProtocolConfig,\n ReplayTraceBudget,\n ReplayTraceFinalOutput,\n ReplayTraceProtocolDecision,\n ReplayTraceProtocolDecisionType,\n ReplayTraceProviderCall,\n ReplayTraceRunInputs,\n ReplayTraceBudgetStateChange,\n ReplayTraceSeed,\n RunResult,\n RunAccounting,\n RunEvent,\n RunEventLog,\n RunMetadata,\n RunUsage,\n Tier,\n TranscriptEntry,\n TranscriptLink\n} from \"../types.js\";\n\ntype SerializableRecord = Record<string, unknown>;\n\nexport function normalizeProtocol(protocol: Protocol | ProtocolConfig): ProtocolConfig {\n if (typeof protocol !== \"string\") {\n return protocol;\n }\n\n switch (protocol) {\n case \"sequential\":\n return { kind: \"sequential\", maxTurns: 3 };\n case \"coordinator\":\n return { kind: \"coordinator\", maxTurns: 3 };\n case \"broadcast\":\n return { kind: \"broadcast\", maxRounds: 2 };\n case \"shared\":\n return { kind: \"shared\", maxTurns: 3 };\n }\n}\n\nexport function defaultAgents(): readonly AgentSpec[] {\n return [\n { id: \"agent-1\", role: \"planner\", instructions: \"Frame the mission and identify the important constraints.\" },\n { id: \"agent-2\", role: \"critic\", instructions: \"Stress-test the previous contribution and improve weak spots.\" },\n { id: \"agent-3\", role: \"synthesizer\", instructions: \"Produce the final useful answer from the accumulated work.\" }\n ];\n}\n\nexport function orderAgentsForTemperature(\n agents: readonly AgentSpec[],\n temperature: number,\n seed?: string | number\n): readonly AgentSpec[] {\n if (temperature !== 0) {\n return agents;\n }\n\n if (seed !== undefined) {\n return [...agents].sort((left, right) => compareAgentsBySeededSelection(left, right, seed));\n }\n\n return [...agents].sort(compareAgentsByStableIdentity);\n}\n\nfunction compareAgentsBySeededSelection(left: AgentSpec, right: AgentSpec, seed: string | number): number {\n const leftScore = deterministicSelectionScore(seed, left);\n const rightScore = deterministicSelectionScore(seed, right);\n if (leftScore !== rightScore) {\n return leftScore - rightScore;\n }\n\n return compareAgentsByStableIdentity(left, right);\n}\n\nfunction deterministicSelectionScore(seed: string | number, agent: AgentSpec): number {\n return stableHash(`${String(seed)}\\u0000${agent.id}\\u0000${agent.role}\\u0000${agent.instructions ?? \"\"}`);\n}\n\nfunction stableHash(input: string): number {\n let hash = 0x811c9dc5;\n\n for (let index = 0; index < input.length; index += 1) {\n hash ^= input.charCodeAt(index);\n hash = Math.imul(hash, 0x01000193);\n }\n\n return hash >>> 0;\n}\n\nfunction compareAgentsByStableIdentity(left: AgentSpec, right: AgentSpec): number {\n const idOrder = left.id.localeCompare(right.id);\n if (idOrder !== 0) {\n return idOrder;\n }\n\n const roleOrder = left.role.localeCompare(right.role);\n if (roleOrder !== 0) {\n return roleOrder;\n }\n\n return (left.instructions ?? \"\").localeCompare(right.instructions ?? \"\");\n}\n\nexport function tierTemperature(tier: Tier): number {\n switch (tier) {\n case \"fast\":\n return 0;\n case \"balanced\":\n return 0.2;\n case \"quality\":\n return 0.4;\n }\n}\n\nexport function emptyCost(): CostSummary {\n return { usd: 0, inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n}\n\nexport function addCost(left: CostSummary, right: CostSummary): CostSummary {\n return {\n usd: left.usd + right.usd,\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n totalTokens: left.totalTokens + right.totalTokens\n };\n}\n\nexport function createTranscriptLink(transcript: readonly TranscriptEntry[]): TranscriptLink {\n return {\n kind: \"trace-transcript\",\n entryCount: transcript.length,\n lastEntryIndex: transcript.length === 0 ? null : transcript.length - 1\n };\n}\n\nexport function createRunEventLog(runId: string, protocol: Protocol, events: readonly RunEvent[]): RunEventLog {\n return {\n kind: \"run-event-log\",\n runId,\n protocol,\n eventTypes: events.map((event) => event.type),\n eventCount: events.length,\n events\n };\n}\n\nexport function createRunUsage(cost: CostSummary): RunUsage {\n return {\n usd: cost.usd,\n inputTokens: cost.inputTokens,\n outputTokens: cost.outputTokens,\n totalTokens: cost.totalTokens\n };\n}\n\nexport function createRunAccounting(options: {\n readonly tier: Tier;\n readonly budget?: Omit<Budget, \"tier\">;\n readonly termination?: ReplayTraceBudget[\"termination\"];\n readonly cost: CostSummary;\n readonly events: readonly RunEvent[];\n}): RunAccounting {\n const usage = createRunUsage(options.cost);\n return {\n kind: \"run-accounting\",\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.termination ? { termination: options.termination } : {}),\n usage,\n cost: options.cost,\n budgetStateChanges: createReplayTraceBudgetStateChanges(options.events),\n ...(options.budget?.maxUsd !== undefined\n ? { usdCapUtilization: options.budget.maxUsd === 0 ? 0 : options.cost.usd / options.budget.maxUsd }\n : {}),\n ...(options.budget?.maxTokens !== undefined\n ? {\n totalTokenCapUtilization:\n options.budget.maxTokens === 0 ? 0 : options.cost.totalTokens / options.budget.maxTokens\n }\n : {})\n };\n}\n\nexport function createRunMetadata(options: {\n readonly runId: string;\n readonly protocol: Protocol;\n readonly tier: Tier;\n readonly modelProviderId: string;\n readonly agentsUsed: readonly AgentSpec[];\n readonly events: readonly RunEvent[];\n}): RunMetadata {\n const firstEvent = options.events[0];\n const lastEvent = options.events.at(-1);\n return {\n runId: options.runId,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.modelProviderId,\n agentsUsed: options.agentsUsed,\n startedAt: firstEvent?.at ?? \"\",\n completedAt: lastEvent?.at ?? \"\"\n };\n}\n\nexport function createReplayTraceRunInputs(options: {\n readonly intent: string;\n readonly protocol: ProtocolConfig;\n readonly tier: Tier;\n readonly modelProviderId: string;\n readonly agents: readonly AgentSpec[];\n readonly temperature: number;\n}): ReplayTraceRunInputs {\n return {\n kind: \"replay-trace-run-inputs\",\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.modelProviderId,\n agents: options.agents,\n temperature: options.temperature\n };\n}\n\nexport function createReplayTraceBudget(options: {\n readonly tier: Tier;\n readonly caps?: Omit<Budget, \"tier\">;\n readonly termination?: ReplayTraceBudget[\"termination\"];\n}): ReplayTraceBudget {\n return {\n kind: \"replay-trace-budget\",\n tier: options.tier,\n ...(options.caps ? { caps: options.caps } : {}),\n ...(options.termination ? { termination: options.termination } : {})\n };\n}\n\nexport function createReplayTraceBudgetStateChanges(\n events: readonly RunEvent[]\n): readonly ReplayTraceBudgetStateChange[] {\n return events.flatMap((event, eventIndex): ReplayTraceBudgetStateChange[] => {\n switch (event.type) {\n case \"agent-turn\":\n case \"broadcast\":\n case \"final\":\n return [\n {\n kind: \"replay-trace-budget-state-change\",\n eventIndex,\n eventType: event.type,\n at: event.at,\n cost: event.cost\n }\n ];\n case \"budget-stop\":\n return [\n {\n kind: \"replay-trace-budget-state-change\",\n eventIndex,\n eventType: event.type,\n at: event.at,\n cost: event.cost,\n iteration: event.iteration,\n elapsedMs: event.elapsedMs,\n budgetReason: event.reason\n }\n ];\n case \"role-assignment\":\n case \"model-request\":\n case \"model-response\":\n case \"model-output-chunk\":\n case \"tool-call\":\n case \"tool-result\":\n return [];\n }\n });\n}\n\nexport function createReplayTraceSeed(seed: string | number | undefined): ReplayTraceSeed {\n if (seed === undefined) {\n return {\n kind: \"replay-trace-seed\",\n source: \"none\",\n value: null\n };\n }\n\n return {\n kind: \"replay-trace-seed\",\n source: \"caller\",\n value: seed\n };\n}\n\nexport function createReplayTraceProtocolDecisions(\n protocol: Protocol,\n events: readonly RunEvent[]\n): readonly ReplayTraceProtocolDecision[] {\n return events.map((event, eventIndex): ReplayTraceProtocolDecision => {\n return createReplayTraceProtocolDecision(protocol, event, eventIndex);\n });\n}\n\nexport function createReplayTraceProtocolDecision(\n protocol: Protocol,\n event: RunEvent,\n eventIndex: number,\n options: {\n readonly decision?: ReplayTraceProtocolDecisionType;\n readonly turn?: number;\n readonly phase?: ReplayTraceProtocolDecision[\"phase\"];\n readonly round?: number;\n readonly transcriptEntryCount?: number;\n readonly contributionCount?: number;\n } = {}\n): ReplayTraceProtocolDecision {\n const base = {\n kind: \"replay-trace-protocol-decision\" as const,\n eventIndex,\n eventType: event.type,\n protocol,\n decision: options.decision ?? defaultProtocolDecision(event),\n at: event.at,\n ...(options.turn !== undefined ? { turn: options.turn } : {}),\n ...(options.phase !== undefined ? { phase: options.phase } : {}),\n ...(options.round !== undefined ? { round: options.round } : {}),\n ...(options.transcriptEntryCount !== undefined ? { transcriptEntryCount: options.transcriptEntryCount } : {}),\n ...(options.contributionCount !== undefined ? { contributionCount: options.contributionCount } : {})\n };\n\n switch (event.type) {\n case \"role-assignment\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role\n };\n case \"model-request\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n callId: event.callId,\n providerId: event.providerId,\n input: event.request.messages.map((message) => message.content).join(\"\\n\")\n };\n case \"model-response\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n callId: event.callId,\n providerId: event.providerId,\n output: event.response.text\n };\n case \"model-output-chunk\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n input: event.input,\n output: event.output\n };\n case \"tool-call\":\n return {\n ...base,\n toolCallId: event.toolCallId,\n tool: event.tool,\n input: stableJsonStringify(event.input),\n ...eventAgentScope(event)\n };\n case \"tool-result\":\n return {\n ...base,\n toolCallId: event.toolCallId,\n tool: event.tool,\n output: stableJsonStringify(event.result),\n ...eventAgentScope(event)\n };\n case \"agent-turn\":\n return {\n ...base,\n agentId: event.agentId,\n role: event.role,\n input: event.input,\n output: event.output,\n cost: event.cost\n };\n case \"broadcast\":\n return {\n ...base,\n round: event.round,\n contributionCount: options.contributionCount ?? event.contributions.length,\n cost: event.cost\n };\n case \"budget-stop\":\n return {\n ...base,\n cost: event.cost,\n budgetReason: event.reason\n };\n case \"final\":\n return {\n ...base,\n output: event.output,\n cost: event.cost\n };\n }\n}\n\nfunction defaultProtocolDecision(event: RunEvent): ReplayTraceProtocolDecisionType {\n switch (event.type) {\n case \"role-assignment\":\n return \"assign-role\";\n case \"model-request\":\n return \"start-model-call\";\n case \"model-response\":\n return \"complete-model-call\";\n case \"model-output-chunk\":\n return \"observe-model-output\";\n case \"tool-call\":\n return \"start-tool-call\";\n case \"tool-result\":\n return \"complete-tool-call\";\n case \"agent-turn\":\n return \"select-agent-turn\";\n case \"broadcast\":\n return \"collect-broadcast-round\";\n case \"budget-stop\":\n return \"stop-for-budget\";\n case \"final\":\n return \"finalize-output\";\n }\n}\n\nfunction eventAgentScope(event: {\n readonly agentId?: string;\n readonly role?: string;\n}): Pick<ReplayTraceProtocolDecision, \"agentId\" | \"role\"> {\n return {\n ...(event.agentId !== undefined ? { agentId: event.agentId } : {}),\n ...(event.role !== undefined ? { role: event.role } : {})\n };\n}\n\nexport function createReplayTraceFinalOutput(output: string, event: RunEvent): ReplayTraceFinalOutput {\n if (event.type === \"final\") {\n return {\n kind: \"replay-trace-final-output\",\n output,\n cost: event.cost,\n completedAt: event.at,\n transcript: event.transcript\n };\n }\n\n return {\n kind: \"replay-trace-final-output\",\n output,\n cost: emptyCost(),\n completedAt: event.at,\n transcript: {\n kind: \"trace-transcript\",\n entryCount: 0,\n lastEntryIndex: null\n }\n };\n}\n\nexport function nextProviderCallId(\n runId: string,\n providerCalls: readonly ReplayTraceProviderCall[]\n): string {\n return `${runId}:provider-call:${providerCalls.length + 1}`;\n}\n\n/**\n * Normalize completed run artifacts into deterministic JSON shapes.\n *\n * This keeps caller-owned persistence stable across runtimes: object keys are\n * sorted recursively, undefined object fields are omitted, non-finite numbers\n * become JSON `null`, and negative zero is normalized to zero before callers\n * serialize the returned result, trace, event log, transcript, or metadata.\n */\nexport function canonicalizeRunResult(result: RunResult): RunResult {\n const trace = canonicalizeSerializable(result.trace);\n const eventLog: RunEventLog = {\n eventCount: trace.events.length,\n eventTypes: trace.events.map((event) => event.type),\n events: trace.events,\n kind: \"run-event-log\",\n protocol: trace.protocol,\n runId: trace.runId\n };\n const canonicalResult = {\n accounting: canonicalizeSerializable(result.accounting),\n cost: canonicalizeSerializable(result.cost),\n ...(result.evaluation !== undefined ? { evaluation: canonicalizeSerializable(result.evaluation) } : {}),\n eventLog,\n metadata: canonicalizeSerializable(result.metadata),\n output: result.output,\n ...(result.quality !== undefined ? { quality: canonicalizeSerializable(result.quality) } : {}),\n trace,\n transcript: trace.transcript,\n usage: canonicalizeSerializable(result.usage)\n };\n\n return canonicalResult;\n}\n\nexport function stableJsonStringify(value: unknown): string {\n return JSON.stringify(canonicalizeSerializable(value));\n}\n\nexport function canonicalizeSerializable<T>(value: T): T {\n if (Array.isArray(value)) {\n return value.map((item) => canonicalizeSerializable(item)) as T;\n }\n\n if (typeof value === \"number\") {\n if (Object.is(value, -0)) {\n return 0 as T;\n }\n if (!Number.isFinite(value)) {\n return null as T;\n }\n return value;\n }\n\n if (value === null || typeof value !== \"object\") {\n return value;\n }\n\n const input = value as SerializableRecord;\n const output: SerializableRecord = {};\n for (const key of Object.keys(input).sort()) {\n const child = input[key];\n if (child !== undefined) {\n output[key] = canonicalizeSerializable(child);\n }\n }\n\n return output as T;\n}\n","import { DogpileError, type JsonObject } from \"../types.js\";\n\nexport function throwIfAborted(signal: AbortSignal | undefined, providerId: string): void {\n if (!signal?.aborted) {\n return;\n }\n\n throw createAbortErrorFromSignal(signal, providerId);\n}\n\nexport function createAbortError(providerId: string, detail?: JsonObject, cause?: unknown): DogpileError {\n return new DogpileError({\n code: \"aborted\",\n message: \"The operation was aborted.\",\n retryable: false,\n providerId,\n ...(detail !== undefined ? { detail } : {}),\n ...(cause !== undefined ? { cause } : {})\n });\n}\n\nexport function createAbortErrorFromSignal(signal: AbortSignal, providerId: string): DogpileError {\n if (DogpileError.isInstance(signal.reason)) {\n return signal.reason;\n }\n\n return createAbortError(providerId, undefined, signal.reason);\n}\n\nexport function createTimeoutError(providerId: string, timeoutMs: number): DogpileError {\n return new DogpileError({\n code: \"timeout\",\n message: `The operation timed out after ${timeoutMs}ms.`,\n retryable: true,\n providerId,\n detail: {\n timeoutMs\n }\n });\n}\n","import type { AgentDecision, AgentParticipation } from \"../types.js\";\n\nexport function parseAgentDecision(output: string): AgentDecision | undefined {\n const selectedRole = matchLine(output, /^role_selected:\\s*(.+)$/imu);\n const participation = matchLine(output, /^participation:\\s*(contribute|abstain)$/imu);\n const rationale = matchLine(output, /^rationale:\\s*(.+)$/imu);\n const contribution = matchContribution(output);\n\n if (!selectedRole || !participation || !isAgentParticipation(participation) || !rationale || !contribution) {\n return undefined;\n }\n\n return {\n selectedRole,\n participation,\n rationale,\n contribution\n };\n}\n\nexport function isParticipatingDecision(decision: AgentDecision | undefined): boolean {\n return decision?.participation !== \"abstain\";\n}\n\nfunction matchLine(output: string, pattern: RegExp): string | undefined {\n const match = output.match(pattern);\n return match?.[1]?.trim();\n}\n\nfunction matchContribution(output: string): string | undefined {\n const match = output.match(/^contribution:\\s*\\n([\\s\\S]*)$/imu);\n const contribution = match?.[1]?.trim();\n return contribution && contribution.length > 0 ? contribution : undefined;\n}\n\nexport function isAgentParticipation(value: string): value is AgentParticipation {\n return value === \"contribute\" || value === \"abstain\";\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n ModelRequest,\n ModelResponse,\n RuntimeToolExecutionRequest,\n ReplayTraceProviderCall,\n RunEvent\n} from \"../types.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\n\ninterface GenerateModelTurnOptions {\n readonly model: ConfiguredModelProvider;\n readonly request: ModelRequest;\n readonly runId: string;\n readonly agent: AgentSpec;\n readonly input: string;\n readonly emit: (event: RunEvent) => void;\n readonly callId: string;\n readonly onProviderCall?: (call: ReplayTraceProviderCall) => void;\n}\n\ntype ModelUsage = NonNullable<ModelResponse[\"usage\"]>;\n\nexport async function generateModelTurn(options: GenerateModelTurnOptions): Promise<ModelResponse> {\n const startedAt = new Date().toISOString();\n let response: ModelResponse;\n\n throwIfAborted(options.request.signal, options.model.id);\n\n if (!options.model.stream) {\n response = await options.model.generate(options.request);\n throwIfAborted(options.request.signal, options.model.id);\n recordProviderCall(response, startedAt, options);\n return response;\n }\n\n let text = \"\";\n let chunkIndex = 0;\n let usage: ModelUsage | undefined;\n let costUsd: number | undefined;\n let finishReason: ModelResponse[\"finishReason\"] | undefined;\n let toolRequests: readonly RuntimeToolExecutionRequest[] | undefined;\n let metadata: ModelResponse[\"metadata\"] | undefined;\n\n for await (const chunk of options.model.stream(options.request)) {\n throwIfAborted(options.request.signal, options.model.id);\n text += chunk.text;\n\n options.emit({\n type: \"model-output-chunk\",\n runId: options.runId,\n at: new Date().toISOString(),\n agentId: options.agent.id,\n role: options.agent.role,\n input: options.input,\n chunkIndex,\n text: chunk.text,\n output: text\n });\n chunkIndex += 1;\n\n if (chunk.usage) {\n usage = chunk.usage;\n }\n if (chunk.costUsd !== undefined) {\n costUsd = chunk.costUsd;\n }\n if (chunk.finishReason !== undefined) {\n finishReason = chunk.finishReason;\n }\n if (chunk.toolRequests !== undefined) {\n toolRequests = chunk.toolRequests;\n }\n if (chunk.metadata !== undefined) {\n metadata = chunk.metadata;\n }\n }\n\n response = {\n text,\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(toolRequests && toolRequests.length > 0 ? { toolRequests } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n ...(metadata !== undefined ? { metadata } : {})\n };\n throwIfAborted(options.request.signal, options.model.id);\n recordProviderCall(response, startedAt, options);\n return response;\n}\n\nfunction recordProviderCall(\n response: ModelResponse,\n startedAt: string,\n options: GenerateModelTurnOptions\n): void {\n options.onProviderCall?.({\n kind: \"replay-trace-provider-call\",\n callId: options.callId,\n providerId: options.model.id,\n startedAt,\n completedAt: new Date().toISOString(),\n agentId: options.agent.id,\n role: options.agent.role,\n request: requestForTrace(options.request),\n response\n });\n}\n\nfunction requestForTrace(request: ModelRequest): ModelRequest {\n return {\n messages: request.messages,\n temperature: request.temperature,\n metadata: request.metadata\n };\n}\n","import type {\n BroadcastProtocolConfig,\n BudgetStopReason,\n BudgetTerminationCondition,\n ConvergenceTerminationCondition,\n CoordinatorProtocolConfig,\n FirstOfTerminationCondition,\n FirstOfTerminationConditions,\n FirstOfTerminationOutput,\n JudgeEvaluationDecision,\n JudgeStopReason,\n JudgeTerminationCondition,\n JsonObject,\n NormalizedStopReason,\n ProtocolConfig,\n SequentialProtocolConfig,\n SharedProtocolConfig,\n TerminationStopRecord,\n StopTerminationDecision,\n TerminationCondition,\n TerminationDecision,\n TerminationEvaluationContext,\n TranscriptEntry\n} from \"../types.js\";\n\n/**\n * Create a budget termination condition.\n *\n * The returned object is JSON-serializable and can be used directly in\n * `terminate` or composed with {@link firstOf}.\n */\nexport function budget(options: Omit<BudgetTerminationCondition, \"kind\">): BudgetTerminationCondition {\n return {\n kind: \"budget\",\n ...options\n };\n}\n\n/**\n * Create a convergence termination condition.\n *\n * The condition fires when the run has produced `stableTurns` sufficiently\n * similar protocol outputs.\n */\nexport function convergence(options: Omit<ConvergenceTerminationCondition, \"kind\">): ConvergenceTerminationCondition {\n return {\n kind: \"convergence\",\n ...options\n };\n}\n\n/**\n * Create a judge termination condition.\n *\n * The rubric is stored as serializable configuration so callers can replay or\n * persist traces without SDK-owned state.\n */\nexport function judge(options: Omit<JudgeTerminationCondition, \"kind\">): JudgeTerminationCondition {\n return {\n kind: \"judge\",\n ...options\n };\n}\n\n/**\n * Compose termination conditions so whichever child fires first wins.\n *\n * Conditions are evaluated in the order supplied by the caller. At least one\n * condition is required so the composite is always meaningful and the public\n * type remains a non-empty tuple.\n */\nexport function firstOf(...conditions: FirstOfTerminationConditions): FirstOfTerminationCondition {\n if (conditions.length === 0) {\n throw new RangeError(\"firstOf requires at least one termination condition.\");\n }\n\n return {\n kind: \"firstOf\",\n conditions\n };\n}\n\n/**\n * Evaluate a serializable termination condition against the current run state.\n *\n * Budget, convergence, judge, and firstOf conditions are enforced from their\n * own normalized inputs so one stop class cannot accidentally satisfy another.\n */\nexport function evaluateTermination(\n condition: TerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n if (isTerminationFloorBlocked(condition, context)) {\n return { type: \"continue\", condition };\n }\n\n switch (condition.kind) {\n case \"budget\":\n return evaluateBudget(condition, context);\n case \"firstOf\":\n return evaluateFirstOf(condition, context).decision;\n case \"convergence\":\n return evaluateConvergence(condition, context);\n case \"judge\":\n return evaluateJudge(condition, context);\n }\n}\n\n/**\n * Evaluate an ordered firstOf composition and return the winning child, if any.\n */\nexport function evaluateFirstOf(\n condition: FirstOfTerminationCondition,\n context: TerminationEvaluationContext\n): FirstOfTerminationOutput {\n const evaluated: TerminationDecision[] = [];\n\n for (const [index, child] of condition.conditions.entries()) {\n const decision = evaluateTermination(child, context);\n evaluated.push(decision);\n\n if (decision.type === \"stop\") {\n return {\n kind: \"firstOf-output\",\n decision,\n winningConditionIndex: index,\n evaluated\n };\n }\n }\n\n return {\n kind: \"firstOf-output\",\n decision: { type: \"continue\", condition },\n winningConditionIndex: null,\n evaluated\n };\n}\n\n/**\n * Evaluate a termination condition and return a trace-ready stop record.\n *\n * Protocol runners use this helper so the first policy decision that halts a\n * run is recorded exactly once on the terminal event.\n */\nexport function evaluateTerminationStop(\n condition: TerminationCondition,\n context: TerminationEvaluationContext\n): TerminationStopRecord | null {\n if (condition.kind === \"firstOf\") {\n const output = evaluateFirstOf(condition, context);\n if (output.decision.type !== \"stop\" || output.winningConditionIndex === null) {\n return null;\n }\n\n const winningCondition = condition.conditions[output.winningConditionIndex];\n if (!winningCondition) {\n throw new RangeError(\"firstOf stop referenced a missing winning condition.\");\n }\n\n return stopRecord(condition, output.decision, {\n kind: \"firstOf-stop\",\n winningConditionIndex: output.winningConditionIndex,\n winningCondition,\n firedCondition: output.decision.condition,\n evaluated: output.evaluated\n });\n }\n\n const decision = evaluateTermination(condition, context);\n if (decision.type !== \"stop\") {\n return null;\n }\n\n return stopRecord(condition, decision);\n}\n\n/**\n * Warn when a protocol-level termination floor cannot be satisfied because a\n * lower iteration cap will stop the run first.\n */\nexport function warnOnProtocolTerminationMisconfiguration(\n protocol: ProtocolConfig,\n terminate: TerminationCondition | undefined,\n warn: (message: string) => void = console.warn\n): void {\n const minTurns = protocolMinTurns(protocol);\n if (minTurns === undefined || !terminate) {\n return;\n }\n\n const limitingIterationBudget = smallestIterationBudget(terminate);\n if (limitingIterationBudget === undefined || limitingIterationBudget >= minTurns) {\n return;\n }\n\n warn(\n `[dogpile] protocol.minTurns (${minTurns}) exceeds terminate budget maxIterations (${limitingIterationBudget}); maxIterations will win.`\n );\n}\n\n/**\n * Combine independently evaluated termination decisions with SDK precedence.\n *\n * Budget caps win over judge decisions, and judge decisions win over\n * convergence. This keeps simultaneous stops deterministic while preserving\n * each evaluator's normalized stop reason on the returned decision.\n */\nexport function combineTerminationDecisions(\n decisions: readonly TerminationDecision[]\n): TerminationDecision {\n const stopDecisions = decisions.filter((decision): decision is StopTerminationDecision => decision.type === \"stop\");\n if (stopDecisions.length === 0) {\n const firstDecision = decisions[0];\n if (!firstDecision) {\n throw new RangeError(\"combineTerminationDecisions requires at least one decision.\");\n }\n\n return firstDecision;\n }\n\n return stopDecisions.reduce((winner, candidate) =>\n stopPrecedence(candidate.normalizedReason) < stopPrecedence(winner.normalizedReason) ? candidate : winner\n );\n}\n\n/**\n * Evaluate cost, token, iteration, and timeout caps for a budget condition.\n */\nexport function evaluateBudget(\n condition: BudgetTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const iteration = context.iteration ?? context.transcript.length;\n const elapsedMs = context.elapsedMs ?? 0;\n\n const costStop = stopIfReached(condition, \"maxUsd\", \"cost\", context.cost.usd);\n if (costStop) {\n return costStop;\n }\n\n const tokenStop = stopIfReached(condition, \"maxTokens\", \"tokens\", context.cost.totalTokens);\n if (tokenStop) {\n return tokenStop;\n }\n\n const iterationStop = stopIfReached(condition, \"maxIterations\", \"iterations\", iteration);\n if (iterationStop) {\n return iterationStop;\n }\n\n const timeoutStop = stopIfReached(condition, \"timeoutMs\", \"timeout\", elapsedMs);\n if (timeoutStop) {\n return timeoutStop;\n }\n\n return { type: \"continue\", condition };\n}\n\n/**\n * Evaluate protocol-level convergence from recent coordination outputs.\n *\n * This intentionally ignores budget caps and judge quality state. Budget and\n * judge conditions can be composed with convergence through `firstOf`, but a\n * convergence condition itself only reads protocol output signals.\n */\nexport function evaluateConvergence(\n condition: ConvergenceTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const stableTurns = Math.max(1, Math.ceil(condition.stableTurns));\n if (context.transcript.length < stableTurns) {\n return { type: \"continue\", condition };\n }\n\n const recentEntries = context.transcript.slice(-stableTurns);\n const recentOutputs = recentEntries.map((entry) => entry.output);\n const similarities = consecutiveSimilarities(recentEntries);\n const observedSimilarity = similarities.length === 0 ? 1 : Math.min(...similarities);\n\n if (observedSimilarity < condition.minSimilarity) {\n return { type: \"continue\", condition };\n }\n\n return {\n type: \"stop\",\n condition,\n reason: \"convergence\",\n normalizedReason: \"convergence\",\n detail: {\n protocol: context.protocol,\n stableTurns,\n minSimilarity: condition.minSimilarity,\n observedSimilarity,\n outputs: recentOutputs\n }\n };\n}\n\n/**\n * Evaluate caller-owned judge state without reading budget or convergence data.\n *\n * Explicit accept/reject verdicts always halt. Score-only decisions halt when\n * they meet `minScore`; when `minScore` is omitted, any score-only decision is\n * treated as the judge's terminal decision.\n */\nexport function evaluateJudge(\n condition: JudgeTerminationCondition,\n context: TerminationEvaluationContext\n): TerminationDecision {\n const decision = context.judgeDecision ?? scoreDecisionFromQuality(context.quality);\n if (!decision) {\n return { type: \"continue\", condition };\n }\n\n switch (decision.type) {\n case \"accept\":\n return judgeStop(condition, \"accepted\", decision);\n case \"reject\":\n return judgeStop(condition, \"rejected\", decision);\n case \"score\": {\n const minScore = condition.minScore;\n if (minScore !== undefined && decision.score < minScore) {\n return { type: \"continue\", condition };\n }\n\n return judgeStop(condition, \"score-threshold\", decision, minScore);\n }\n }\n}\n\nfunction stopIfReached(\n condition: BudgetTerminationCondition,\n cap: \"maxUsd\" | \"maxTokens\" | \"maxIterations\" | \"timeoutMs\",\n reason: BudgetStopReason,\n observed: number\n): StopTerminationDecision | null {\n const limit = condition[cap];\n if (limit === undefined || observed < limit) {\n return null;\n }\n\n return {\n type: \"stop\",\n condition,\n reason: \"budget\",\n normalizedReason: normalizeBudgetStopReason(reason),\n budgetReason: reason,\n detail: {\n cap,\n limit,\n observed\n }\n };\n}\n\nfunction scoreDecisionFromQuality(quality: number | undefined): JudgeEvaluationDecision | null {\n if (quality === undefined) {\n return null;\n }\n\n return {\n type: \"score\",\n score: quality\n };\n}\n\nfunction judgeStop(\n condition: JudgeTerminationCondition,\n judgeReason: JudgeStopReason,\n decision: JudgeEvaluationDecision,\n minScore?: number\n): StopTerminationDecision {\n return {\n type: \"stop\",\n condition,\n reason: \"judge\",\n normalizedReason: normalizeJudgeStopReason(judgeReason),\n judgeReason,\n detail: judgeStopDetail(decision, minScore)\n };\n}\n\nfunction normalizeBudgetStopReason(reason: BudgetStopReason): NormalizedStopReason {\n switch (reason) {\n case \"cost\":\n return \"budget:cost\";\n case \"tokens\":\n return \"budget:tokens\";\n case \"iterations\":\n return \"budget:iterations\";\n case \"timeout\":\n return \"budget:timeout\";\n }\n}\n\nfunction normalizeJudgeStopReason(reason: JudgeStopReason): NormalizedStopReason {\n switch (reason) {\n case \"accepted\":\n return \"judge:accepted\";\n case \"rejected\":\n return \"judge:rejected\";\n case \"score-threshold\":\n return \"judge:score-threshold\";\n }\n}\n\nfunction stopPrecedence(reason: NormalizedStopReason): number {\n if (reason.startsWith(\"budget:\")) {\n return 0;\n }\n\n if (reason.startsWith(\"judge:\")) {\n return 1;\n }\n\n return 2;\n}\n\nfunction isTerminationFloorBlocked(condition: TerminationCondition, context: TerminationEvaluationContext): boolean {\n if (condition.kind !== \"convergence\" && condition.kind !== \"judge\") {\n return false;\n }\n\n const floor = protocolTerminationFloor(context.protocolConfig);\n if (floor === undefined || floor <= 0) {\n return false;\n }\n\n const progress = protocolProgress(context);\n return progress < floor;\n}\n\nfunction protocolTerminationFloor(protocol: ProtocolConfig | undefined): number | undefined {\n if (!protocol) {\n return undefined;\n }\n\n switch (protocol.kind) {\n case \"broadcast\":\n return protocol.minRounds;\n case \"coordinator\":\n case \"sequential\":\n case \"shared\":\n return protocol.minTurns;\n }\n}\n\nfunction protocolProgress(context: TerminationEvaluationContext): number {\n return context.protocolIteration ?? context.iteration ?? context.transcript.length;\n}\n\nfunction protocolMinTurns(\n protocol: ProtocolConfig\n): SequentialProtocolConfig[\"minTurns\"] | CoordinatorProtocolConfig[\"minTurns\"] | SharedProtocolConfig[\"minTurns\"] {\n switch (protocol.kind) {\n case \"broadcast\":\n return undefined;\n case \"coordinator\":\n case \"sequential\":\n case \"shared\":\n return protocol.minTurns;\n }\n}\n\nfunction smallestIterationBudget(condition: TerminationCondition): number | undefined {\n switch (condition.kind) {\n case \"budget\":\n return condition.maxIterations;\n case \"convergence\":\n case \"judge\":\n return undefined;\n case \"firstOf\": {\n let smallest: number | undefined;\n for (const child of condition.conditions) {\n const budget = smallestIterationBudget(child);\n if (budget === undefined) {\n continue;\n }\n smallest = smallest === undefined ? budget : Math.min(smallest, budget);\n }\n return smallest;\n }\n }\n}\n\nfunction judgeStopDetail(decision: JudgeEvaluationDecision, minScore?: number): JsonObject {\n return {\n decision: decision.type,\n ...(decision.score !== undefined ? { score: decision.score } : {}),\n ...(minScore !== undefined ? { minScore } : {}),\n ...(decision.rationale !== undefined ? { rationale: decision.rationale } : {}),\n ...(decision.metadata !== undefined ? { metadata: decision.metadata } : {})\n };\n}\n\nfunction stopRecord(\n rootCondition: TerminationCondition,\n decision: StopTerminationDecision,\n firstOfRecord?: NonNullable<TerminationStopRecord[\"firstOf\"]>\n): TerminationStopRecord {\n return {\n kind: \"termination-stop\",\n rootCondition,\n firedCondition: decision.condition,\n reason: decision.reason,\n normalizedReason: decision.normalizedReason,\n ...(decision.budgetReason !== undefined ? { budgetReason: decision.budgetReason } : {}),\n ...(decision.judgeReason !== undefined ? { judgeReason: decision.judgeReason } : {}),\n ...(decision.detail !== undefined ? { detail: decision.detail } : {}),\n ...(firstOfRecord !== undefined ? { firstOf: firstOfRecord } : {})\n };\n}\n\nfunction consecutiveSimilarities(entries: readonly TranscriptEntry[]): readonly number[] {\n const similarities: number[] = [];\n\n for (let index = 1; index < entries.length; index += 1) {\n const previous = entries[index - 1];\n const current = entries[index];\n if (previous && current) {\n similarities.push(outputSimilarity(previous.output, current.output));\n }\n }\n\n return similarities;\n}\n\nfunction outputSimilarity(left: string, right: string): number {\n const normalizedLeft = normalizeOutput(left);\n const normalizedRight = normalizeOutput(right);\n\n if (normalizedLeft === normalizedRight) {\n return 1;\n }\n\n const leftTokens = tokenize(normalizedLeft);\n const rightTokens = tokenize(normalizedRight);\n if (leftTokens.length === 0 || rightTokens.length === 0) {\n return 0;\n }\n\n const leftSet = new Set(leftTokens);\n const rightSet = new Set(rightTokens);\n let intersection = 0;\n\n for (const token of leftSet) {\n if (rightSet.has(token)) {\n intersection += 1;\n }\n }\n\n const union = new Set([...leftSet, ...rightSet]).size;\n return union === 0 ? 0 : intersection / union;\n}\n\nfunction normalizeOutput(output: string): string {\n return output.trim().toLowerCase();\n}\n\nfunction tokenize(output: string): readonly string[] {\n return output.split(/[^a-z0-9]+/u).filter((token) => token.length > 0);\n}\n","import { DogpileError } from \"../types.js\";\nimport type {\n AgentSpec,\n BudgetCaps,\n BudgetTier,\n ConfiguredModelProvider,\n DogpileOptions,\n EngineOptions,\n JsonObject,\n JsonValue,\n ProtocolConfig,\n ProtocolName,\n ProtocolSelection,\n RuntimeTool,\n TerminationCondition\n} from \"../types.js\";\n\nconst protocolNames = [\"coordinator\", \"sequential\", \"broadcast\", \"shared\"] as const;\nconst budgetTiers = [\"fast\", \"balanced\", \"quality\"] as const;\n\ntype ValidationRule =\n | \"required\"\n | \"non-empty-string\"\n | \"finite-number\"\n | \"non-negative-number\"\n | \"positive-integer\"\n | \"non-negative-integer\"\n | \"range\"\n | \"enum\"\n | \"object\"\n | \"array\"\n | \"boolean\"\n | \"function\"\n | \"json-object\"\n | \"abort-signal\"\n | \"model-provider\"\n | \"runtime-tool\"\n | \"termination-condition\";\n\ninterface ValidationFailureOptions {\n readonly path: string;\n readonly rule: ValidationRule;\n readonly message: string;\n readonly expected: string;\n readonly actual: unknown;\n}\n\n/**\n * Validate high-level caller options before any protocol execution starts.\n */\nexport function validateDogpileOptions(options: DogpileOptions): void {\n requireRecord(options, \"options\");\n validateMissionIntent(options.intent);\n\n if (options.protocol !== undefined) {\n validateProtocolSelection(options.protocol, \"protocol\");\n }\n if (options.tier !== undefined) {\n validateBudgetTier(options.tier, \"tier\");\n }\n\n validateModelProviderRegistration(options.model, \"model\");\n validateOptionalAgents(options.agents, \"agents\");\n validateOptionalRuntimeTools(options.tools, \"tools\");\n validateOptionalTemperature(options.temperature, \"temperature\");\n validateOptionalBudgetCaps(options.budget, \"budget\");\n validateOptionalTerminationCondition(options.terminate, \"terminate\");\n validateOptionalWrapUpHint(options.wrapUpHint, \"wrapUpHint\");\n validateOptionalFunction(options.evaluate, \"evaluate\");\n validateOptionalSeed(options.seed, \"seed\");\n validateOptionalAbortSignal(options.signal, \"signal\");\n}\n\nexport function validateMissionIntent(intent: unknown, path = \"intent\"): void {\n validateNonEmptyString(intent, path, \"intent is required.\");\n}\n\n/**\n * Validate low-level engine configuration before normalizing reusable controls.\n */\nexport function validateEngineOptions(options: EngineOptions): void {\n requireRecord(options, \"options\");\n validateProtocolSelection(options.protocol, \"protocol\");\n validateBudgetTier(options.tier, \"tier\");\n validateModelProviderRegistration(options.model, \"model\");\n validateOptionalAgents(options.agents, \"agents\");\n validateOptionalRuntimeTools(options.tools, \"tools\");\n validateOptionalTemperature(options.temperature, \"temperature\");\n validateOptionalBudgetCaps(options.budget, \"budget\");\n validateOptionalTerminationCondition(options.terminate, \"terminate\");\n validateOptionalWrapUpHint(options.wrapUpHint, \"wrapUpHint\");\n validateOptionalFunction(options.evaluate, \"evaluate\");\n validateOptionalSeed(options.seed, \"seed\");\n validateOptionalAbortSignal(options.signal, \"signal\");\n}\n\n/**\n * Validate Vercel AI adapter factory options at construction time.\n */\nexport function validateVercelAIProviderOptions(options: unknown): void {\n const record = requireRecord(options, \"options\");\n\n if (record.model === undefined) {\n invalidConfiguration({\n path: \"model\",\n rule: \"required\",\n message: \"model is required.\",\n expected: \"a Vercel AI language model\",\n actual: record.model\n });\n }\n if (typeof record.model === \"string\") {\n validateNonEmptyString(record.model, \"model\", \"model must not be empty.\");\n } else {\n validateVercelAILanguageModel(record.model, \"model\");\n }\n\n validateOptionalNonEmptyString(record.id, \"id\");\n validateOptionalBoolean(record.streaming, \"streaming\");\n validateOptionalFunction(record.generateText, \"generateText\");\n validateOptionalFunction(record.streamText, \"streamText\");\n validateOptionalFunction(record.costEstimator, \"costEstimator\");\n validateOptionalPositiveInteger(record.maxOutputTokens, \"maxOutputTokens\");\n validateOptionalNumberInRange(record.topP, \"topP\", 0, 1);\n validateOptionalPositiveInteger(record.topK, \"topK\");\n validateOptionalNumberInRange(record.presencePenalty, \"presencePenalty\", -2, 2);\n validateOptionalNumberInRange(record.frequencyPenalty, \"frequencyPenalty\", -2, 2);\n validateOptionalStringArray(record.stopSequences, \"stopSequences\");\n validateOptionalInteger(record.seed, \"seed\");\n validateOptionalNonNegativeInteger(record.maxRetries, \"maxRetries\");\n validateOptionalAbortSignal(record.abortSignal, \"abortSignal\");\n validateOptionalHeaders(record.headers, \"headers\");\n validateOptionalProviderOptions(record.providerOptions, \"providerOptions\");\n validateOptionalArray(record.activeTools, \"activeTools\");\n validateOptionalFunction(record.runtimeToolIdForName, \"runtimeToolIdForName\");\n}\n\nfunction validateProtocolSelection(value: ProtocolSelection, path: string): void {\n if (typeof value === \"string\") {\n if (!isProtocolName(value)) {\n invalidConfiguration({\n path,\n rule: \"enum\",\n message: \"protocol must be one of coordinator, sequential, broadcast, or shared.\",\n expected: protocolNames.join(\" | \"),\n actual: value\n });\n }\n return;\n }\n\n validateProtocolConfig(value, path);\n}\n\nfunction validateProtocolConfig(value: ProtocolConfig, path: string): void {\n const record = requireRecord(value, path);\n const kind = record.kind;\n\n if (!isProtocolName(kind)) {\n invalidConfiguration({\n path: `${path}.kind`,\n rule: \"enum\",\n message: \"protocol config kind must be one of coordinator, sequential, broadcast, or shared.\",\n expected: protocolNames.join(\" | \"),\n actual: kind\n });\n }\n\n switch (kind) {\n case \"coordinator\":\n case \"sequential\":\n case \"shared\":\n validateOptionalPositiveInteger(record.maxTurns, `${path}.maxTurns`);\n validateOptionalNonNegativeInteger(record.minTurns, `${path}.minTurns`);\n if (kind === \"shared\") {\n validateOptionalString(record.organizationalMemory, `${path}.organizationalMemory`);\n }\n return;\n case \"broadcast\":\n validateOptionalPositiveInteger(record.maxRounds, `${path}.maxRounds`);\n validateOptionalNonNegativeInteger(record.minRounds, `${path}.minRounds`);\n return;\n }\n}\n\nfunction validateBudgetTier(value: BudgetTier, path: string): void {\n if (!isBudgetTier(value)) {\n invalidConfiguration({\n path,\n rule: \"enum\",\n message: \"tier must be one of fast, balanced, or quality.\",\n expected: budgetTiers.join(\" | \"),\n actual: value\n });\n }\n}\n\n/**\n * Validate configured model provider definitions at registration boundaries.\n */\nexport function validateModelProviderRegistration(value: unknown, path = \"model\"): asserts value is ConfiguredModelProvider {\n const record = requireRecord(value, path);\n validateNonEmptyString(record.id, `${path}.id`, \"model.id is required.\");\n validateFunction(record.generate, `${path}.generate`);\n validateOptionalFunction(record.stream, `${path}.stream`);\n}\n\nfunction validateVercelAILanguageModel(value: unknown, path: string): void {\n const record = requireRecord(value, path);\n\n if (record.specificationVersion !== \"v2\" && record.specificationVersion !== \"v3\") {\n invalidConfiguration({\n path: `${path}.specificationVersion`,\n rule: \"model-provider\",\n message: \"model.specificationVersion must be v2 or v3.\",\n expected: \"v2 | v3\",\n actual: record.specificationVersion\n });\n }\n\n validateNonEmptyString(record.provider, `${path}.provider`, \"model.provider is required.\");\n validateNonEmptyString(record.modelId, `${path}.modelId`, \"model.modelId is required.\");\n validateFunction(record.doGenerate, `${path}.doGenerate`);\n validateFunction(record.doStream, `${path}.doStream`);\n}\n\nfunction validateOptionalAgents(value: readonly AgentSpec[] | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"agents must be an array when provided.\",\n expected: \"readonly AgentSpec[]\",\n actual: value\n });\n }\n if (value.length === 0) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"agents must contain at least one participant when provided.\",\n expected: \"non-empty readonly AgentSpec[]\",\n actual: value\n });\n }\n\n value.forEach((agent, index) => {\n const agentPath = `${path}[${index}]`;\n const record = requireRecord(agent, agentPath);\n validateNonEmptyString(record.id, `${agentPath}.id`, \"agent.id is required.\");\n validateNonEmptyString(record.role, `${agentPath}.role`, \"agent.role is required.\");\n validateOptionalString(record.instructions, `${agentPath}.instructions`);\n });\n}\n\nfunction validateOptionalRuntimeTools(value: readonly RuntimeTool<JsonObject, JsonValue>[] | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateRuntimeToolRegistrations(value, path);\n}\n\n/**\n * Validate runtime tool definitions at registration boundaries.\n */\nexport function validateRuntimeToolRegistrations(value: unknown, path = \"tools\"): void {\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"tools must be an array when provided.\",\n expected: \"readonly RuntimeTool[]\",\n actual: value\n });\n }\n\n value.forEach((tool, index) => validateRuntimeTool(tool, `${path}[${index}]`));\n}\n\nfunction validateRuntimeTool(value: RuntimeTool<JsonObject, JsonValue>, path: string): void {\n const record = requireRecord(value, path);\n const identity = requireRecord(record.identity, `${path}.identity`);\n validateNonEmptyString(identity.id, `${path}.identity.id`, \"tool identity id is required.\");\n validateNonEmptyString(identity.name, `${path}.identity.name`, \"tool identity name is required.\");\n validateOptionalString(identity.namespace, `${path}.identity.namespace`);\n validateOptionalString(identity.version, `${path}.identity.version`);\n validateOptionalString(identity.description, `${path}.identity.description`);\n\n const inputSchema = requireRecord(record.inputSchema, `${path}.inputSchema`);\n if (inputSchema.kind !== \"json-schema\") {\n invalidConfiguration({\n path: `${path}.inputSchema.kind`,\n rule: \"runtime-tool\",\n message: \"tool inputSchema.kind must be json-schema.\",\n expected: \"json-schema\",\n actual: inputSchema.kind\n });\n }\n validateJsonObject(inputSchema.schema, `${path}.inputSchema.schema`);\n validateOptionalString(inputSchema.description, `${path}.inputSchema.description`);\n validateOptionalArray(record.permissions, `${path}.permissions`);\n validateOptionalFunction(record.validateInput, `${path}.validateInput`);\n validateFunction(record.execute, `${path}.execute`);\n}\n\nfunction validateOptionalBudgetCaps(value: BudgetCaps | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateBudgetCaps(value, path);\n}\n\nfunction validateBudgetCaps(value: BudgetCaps, path: string): void {\n const record = requireRecord(value, path);\n validateOptionalNonNegativeNumber(record.maxUsd, `${path}.maxUsd`);\n validateOptionalNonNegativeInteger(record.maxTokens, `${path}.maxTokens`);\n validateOptionalNonNegativeInteger(record.maxIterations, `${path}.maxIterations`);\n validateOptionalNonNegativeInteger(record.timeoutMs, `${path}.timeoutMs`);\n validateOptionalNumberInRange(record.qualityWeight, `${path}.qualityWeight`, 0, 1);\n}\n\nfunction validateOptionalTerminationCondition(value: TerminationCondition | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n\n validateTerminationCondition(value, path, new Set<object>());\n}\n\nfunction validateTerminationCondition(value: TerminationCondition, path: string, stack: Set<object>): void {\n const record = requireRecord(value, path);\n if (stack.has(record)) {\n invalidConfiguration({\n path,\n rule: \"termination-condition\",\n message: \"termination conditions must not contain cycles.\",\n expected: \"acyclic termination condition\",\n actual: value\n });\n }\n\n stack.add(record);\n try {\n switch (record.kind) {\n case \"budget\":\n validateBudgetCaps(record, path);\n return;\n case \"convergence\":\n validatePositiveInteger(record.stableTurns, `${path}.stableTurns`);\n validateNumberInRange(record.minSimilarity, `${path}.minSimilarity`, 0, 1);\n return;\n case \"judge\":\n validateJudgeRubric(record.rubric, `${path}.rubric`);\n validateOptionalNumberInRange(record.minScore, `${path}.minScore`, 0, 1);\n return;\n case \"firstOf\":\n validateFirstOfConditions(record.conditions, `${path}.conditions`, stack);\n return;\n default:\n invalidConfiguration({\n path: `${path}.kind`,\n rule: \"termination-condition\",\n message: \"termination condition kind must be budget, convergence, judge, or firstOf.\",\n expected: \"budget | convergence | judge | firstOf\",\n actual: record.kind\n });\n }\n } finally {\n stack.delete(record);\n }\n}\n\nfunction validateFirstOfConditions(value: unknown, path: string, stack: Set<object>): void {\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"firstOf conditions must be a non-empty array.\",\n expected: \"non-empty termination condition array\",\n actual: value\n });\n }\n if (value.length === 0) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"firstOf conditions must contain at least one condition.\",\n expected: \"non-empty termination condition array\",\n actual: value\n });\n }\n\n value.forEach((condition, index) => {\n validateTerminationCondition(condition as TerminationCondition, `${path}[${index}]`, stack);\n });\n}\n\nfunction validateJudgeRubric(value: unknown, path: string): void {\n if (typeof value === \"string\") {\n validateNonEmptyString(value, path, \"judge rubric must not be empty.\");\n return;\n }\n\n validateJsonObject(value, path);\n}\n\nfunction validateOptionalTemperature(value: number | undefined, path: string): void {\n validateOptionalNumberInRange(value, path, 0, 2);\n}\n\nfunction validateOptionalWrapUpHint(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n\n const record = requireRecord(value, path);\n validateOptionalNonNegativeInteger(record.atIteration, `${path}.atIteration`);\n validateOptionalNumberInRange(record.atFraction, `${path}.atFraction`, 0, 1);\n validateOptionalFunction(record.inject, `${path}.inject`);\n\n if (record.atIteration === undefined && record.atFraction === undefined) {\n invalidConfiguration({\n path,\n rule: \"object\",\n message: \"wrapUpHint must configure atIteration or atFraction.\",\n expected: \"WrapUpHintConfig with atIteration or atFraction\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalSeed(value: string | number | undefined, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value === \"string\") {\n return;\n }\n if (typeof value === \"number\" && Number.isFinite(value)) {\n return;\n }\n\n invalidConfiguration({\n path,\n rule: \"finite-number\",\n message: \"seed must be a string or finite number when provided.\",\n expected: \"string or finite number\",\n actual: value\n });\n}\n\nfunction validateOptionalHeaders(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n\n const record = requireRecord(value, path);\n for (const [key, headerValue] of Object.entries(record)) {\n if (headerValue !== undefined && typeof headerValue !== \"string\") {\n invalidConfiguration({\n path: `${path}.${key}`,\n rule: \"non-empty-string\",\n message: \"headers values must be strings or undefined.\",\n expected: \"string | undefined\",\n actual: headerValue\n });\n }\n }\n}\n\nfunction validateOptionalProviderOptions(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n\n const record = requireRecord(value, path);\n for (const [key, providerOptions] of Object.entries(record)) {\n validateJsonObject(providerOptions, `${path}.${key}`);\n }\n}\n\nfunction validateJsonObject(value: unknown, path: string): void {\n if (!isJsonValue(value, new Set<object>()) || !isRecord(value)) {\n invalidConfiguration({\n path,\n rule: \"json-object\",\n message: \"value must be a JSON-compatible object.\",\n expected: \"JSON-compatible object\",\n actual: value\n });\n }\n}\n\nfunction isJsonValue(value: unknown, stack: Set<object>): value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") {\n return true;\n }\n if (typeof value === \"number\") {\n return Number.isFinite(value);\n }\n if (Array.isArray(value)) {\n if (stack.has(value)) {\n return false;\n }\n stack.add(value);\n const valid = value.every((child) => isJsonValue(child, stack));\n stack.delete(value);\n return valid;\n }\n if (isRecord(value)) {\n if (stack.has(value)) {\n return false;\n }\n stack.add(value);\n const valid = Object.values(value).every((child) => isJsonValue(child, stack));\n stack.delete(value);\n return valid;\n }\n\n return false;\n}\n\nfunction validateOptionalString(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"string\") {\n invalidConfiguration({\n path,\n rule: \"non-empty-string\",\n message: \"value must be a string when provided.\",\n expected: \"string\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonEmptyString(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateNonEmptyString(value, path, `${path} must not be empty.`);\n}\n\nfunction validateNonEmptyString(value: unknown, path: string, message: string): void {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n invalidConfiguration({\n path,\n rule: \"non-empty-string\",\n message,\n expected: \"non-empty string\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalBoolean(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"boolean\") {\n invalidConfiguration({\n path,\n rule: \"boolean\",\n message: \"value must be a boolean when provided.\",\n expected: \"boolean\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalFunction(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateFunction(value, path);\n}\n\nfunction validateFunction(value: unknown, path: string): void {\n if (typeof value !== \"function\") {\n invalidConfiguration({\n path,\n rule: \"function\",\n message: \"value must be a function.\",\n expected: \"function\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalArray(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"value must be an array when provided.\",\n expected: \"array\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalStringArray(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!Array.isArray(value)) {\n invalidConfiguration({\n path,\n rule: \"array\",\n message: \"value must be an array of strings when provided.\",\n expected: \"string[]\",\n actual: value\n });\n }\n value.forEach((item, index) => validateNonEmptyString(item, `${path}[${index}]`, \"array item must be a string.\"));\n}\n\nfunction validateOptionalAbortSignal(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (!isAbortSignalLike(value)) {\n invalidConfiguration({\n path,\n rule: \"abort-signal\",\n message: \"value must be an AbortSignal when provided.\",\n expected: \"AbortSignal\",\n actual: value\n });\n }\n}\n\nfunction isAbortSignalLike(value: unknown): value is AbortSignal {\n if (!isRecord(value)) {\n return false;\n }\n\n return (\n typeof value.aborted === \"boolean\" &&\n typeof value.addEventListener === \"function\" &&\n typeof value.removeEventListener === \"function\"\n );\n}\n\nfunction validateOptionalInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validateInteger(value, path);\n}\n\nfunction validateInteger(value: unknown, path: string): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || !Number.isInteger(value)) {\n invalidConfiguration({\n path,\n rule: \"finite-number\",\n message: \"value must be a finite integer.\",\n expected: \"finite integer\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalPositiveInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n validatePositiveInteger(value, path);\n}\n\nfunction validatePositiveInteger(value: unknown, path: string): void {\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 1) {\n invalidConfiguration({\n path,\n rule: \"positive-integer\",\n message: \"value must be a positive integer.\",\n expected: \"integer >= 1\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonNegativeInteger(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"number\" || !Number.isInteger(value) || value < 0) {\n invalidConfiguration({\n path,\n rule: \"non-negative-integer\",\n message: \"value must be a non-negative integer.\",\n expected: \"integer >= 0\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNonNegativeNumber(value: unknown, path: string): void {\n if (value === undefined) {\n return;\n }\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n invalidConfiguration({\n path,\n rule: \"non-negative-number\",\n message: \"value must be a non-negative finite number.\",\n expected: \"finite number >= 0\",\n actual: value\n });\n }\n}\n\nfunction validateOptionalNumberInRange(value: unknown, path: string, min: number, max: number): void {\n if (value === undefined) {\n return;\n }\n validateNumberInRange(value, path, min, max);\n}\n\nfunction validateNumberInRange(value: unknown, path: string, min: number, max: number): void {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < min || value > max) {\n invalidConfiguration({\n path,\n rule: \"range\",\n message: `value must be a finite number in the inclusive range ${min}..${max}.`,\n expected: `finite number in ${min}..${max}`,\n actual: value\n });\n }\n}\n\nfunction requireRecord(value: unknown, path: string): Record<string, unknown> {\n if (!isRecord(value)) {\n invalidConfiguration({\n path,\n rule: \"object\",\n message: \"value must be an object.\",\n expected: \"object\",\n actual: value\n });\n }\n\n return value;\n}\n\nfunction invalidConfiguration(options: ValidationFailureOptions): never {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: `Invalid Dogpile configuration at ${options.path}: ${options.message}`,\n retryable: false,\n detail: {\n kind: \"configuration-validation\",\n path: options.path,\n rule: options.rule,\n expected: options.expected,\n received: describeValue(options.actual)\n }\n });\n}\n\nfunction isProtocolName(value: unknown): value is ProtocolName {\n return typeof value === \"string\" && protocolNames.includes(value as ProtocolName);\n}\n\nfunction isBudgetTier(value: unknown): value is BudgetTier {\n return typeof value === \"string\" && budgetTiers.includes(value as BudgetTier);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction describeValue(value: unknown): string {\n if (value === null) {\n return \"null\";\n }\n if (value === undefined) {\n return \"undefined\";\n }\n if (Array.isArray(value)) {\n return \"array\";\n }\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n return String(value);\n }\n return typeof value;\n}\n","import type {\n JsonObject,\n JsonValue,\n RuntimeTool,\n RuntimeToolAdapterContract,\n RuntimeToolAdapterError,\n RuntimeToolExecutionContext,\n RuntimeToolExecutionRequest,\n RuntimeToolExecutor,\n RuntimeToolIdentity,\n RuntimeToolInputSchema,\n RuntimeToolPermission,\n RuntimeToolResult,\n TranscriptToolCall,\n RuntimeToolTraceContext,\n RuntimeToolValidationIssue,\n RuntimeToolValidationResult,\n RunEvent,\n ModelMessage,\n ModelResponse\n} from \"../types.js\";\nimport { validateRuntimeToolRegistrations } from \"./validation.js\";\n\ntype VercelAIToolExecuteOptions = {\n readonly toolCallId: string;\n readonly messages: ModelMessage[];\n readonly abortSignal?: AbortSignal;\n readonly experimental_context: RuntimeToolExecutionContext;\n};\n\ntype VercelAIToolExecuteFunction<Input, Output> = (\n input: Input,\n options: VercelAIToolExecuteOptions\n) => Output | PromiseLike<Output> | AsyncIterable<Output>;\n\ntype VercelAICompatibleSchema<Input> = unknown;\n\n/**\n * Built-in Dogpile tool names with stable protocol-facing semantics.\n */\nexport type DogpileBuiltInToolName = \"webSearch\" | \"codeExec\";\n\n/**\n * Input accepted by the built-in web search tool contract.\n */\nexport interface WebSearchToolInput extends JsonObject {\n readonly query: string;\n readonly maxResults?: number;\n}\n\n/**\n * One normalized web search result.\n */\nexport interface WebSearchToolResult extends JsonObject {\n readonly title: string;\n readonly url: string;\n readonly snippet?: string;\n readonly metadata?: JsonObject;\n}\n\n/**\n * Output returned by the built-in web search tool contract.\n */\nexport interface WebSearchToolOutput extends JsonObject {\n readonly results: WebSearchToolResult[];\n}\n\n/**\n * Fetch implementation accepted by the built-in web search adapter.\n */\nexport type WebSearchFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Request data produced before the built-in web search adapter calls `fetch`.\n */\nexport interface WebSearchFetchRequest {\n readonly url: string | URL;\n readonly init?: RequestInit;\n}\n\n/**\n * Build a search backend request from normalized web search input.\n */\nexport type WebSearchFetchRequestBuilder = (\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => WebSearchFetchRequest;\n\n/**\n * Parse a search backend response into Dogpile's stable web search output.\n */\nexport type WebSearchFetchResponseParser = (\n response: Response,\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => WebSearchToolOutput | Promise<WebSearchToolOutput>;\n\n/**\n * Options for the built-in fetch-based web search adapter.\n */\nexport interface WebSearchToolAdapterOptions {\n readonly endpoint: string | URL;\n readonly fetch?: WebSearchFetch;\n readonly headers?: HeadersInit;\n readonly defaultMaxResults?: number;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly permissions?: readonly RuntimeToolPermission[];\n readonly buildRequest?: WebSearchFetchRequestBuilder;\n readonly parseResponse?: WebSearchFetchResponseParser;\n}\n\n/**\n * Options for the built-in code execution adapter.\n */\nexport interface CodeExecToolAdapterOptions {\n readonly execute: CodeExecSandboxExecutor;\n readonly defaultTimeoutMs?: number;\n readonly maxTimeoutMs?: number;\n readonly languages?: readonly CodeExecToolLanguage[];\n readonly allowNetwork?: boolean;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Input accepted by the built-in code execution tool contract.\n *\n * @remarks\n * Dogpile core does not provide a sandbox implementation. Callers supply the\n * executor while Dogpile normalizes the public tool identity and schema.\n */\nexport interface CodeExecToolInput extends JsonObject {\n readonly language: \"javascript\" | \"typescript\" | \"python\" | \"bash\" | \"shell\";\n readonly code: string;\n readonly timeoutMs?: number;\n}\n\n/**\n * Output returned by the built-in code execution tool contract.\n */\nexport interface CodeExecToolOutput extends JsonObject {\n readonly stdout: string;\n readonly stderr: string;\n readonly exitCode: number;\n readonly metadata?: JsonObject;\n}\n\n/**\n * Language identifiers accepted by Dogpile's built-in code execution contract.\n */\nexport type CodeExecToolLanguage = CodeExecToolInput[\"language\"];\n\n/**\n * Executor signature for the built-in web search contract.\n */\nexport type WebSearchToolExecutor = (\n input: Readonly<WebSearchToolInput>,\n context: RuntimeToolExecutionContext\n) => RuntimeToolResult<WebSearchToolOutput> | Promise<RuntimeToolResult<WebSearchToolOutput>>;\n\n/**\n * Executor signature for the built-in code execution contract.\n */\nexport type CodeExecToolExecutor = (\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext\n) => RuntimeToolResult<CodeExecToolOutput> | Promise<RuntimeToolResult<CodeExecToolOutput>>;\n\n/**\n * Caller-owned sandbox implementation used by Dogpile's built-in code execution adapter.\n */\nexport type CodeExecSandboxExecutor = (\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext\n) => CodeExecToolOutput | Promise<CodeExecToolOutput>;\n\n/**\n * Optional identity fields callers may layer onto built-in Dogpile tools.\n */\nexport interface BuiltInDogpileToolIdentityOptions {\n readonly namespace?: string;\n readonly version?: string;\n readonly description?: string;\n}\n\n/**\n * Definition used to normalize Dogpile's built-in web search tool.\n */\nexport interface WebSearchDogpileToolDefinition {\n readonly name: \"webSearch\";\n readonly execute: WebSearchToolExecutor;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Definition used to normalize Dogpile's built-in code execution tool.\n */\nexport interface CodeExecDogpileToolDefinition {\n readonly name: \"codeExec\";\n readonly execute: CodeExecToolExecutor;\n readonly identity?: BuiltInDogpileToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly permissions?: readonly RuntimeToolPermission[];\n}\n\n/**\n * Built-in Dogpile tool definitions accepted by the normalization helper.\n */\nexport type BuiltInDogpileToolDefinition = WebSearchDogpileToolDefinition | CodeExecDogpileToolDefinition;\n\n/**\n * Caller-supplied built-in tool executors keyed by Dogpile's stable built-in names.\n */\nexport interface BuiltInDogpileToolExecutors {\n readonly webSearch?: WebSearchToolExecutor | WebSearchDogpileToolDefinition;\n readonly codeExec?: CodeExecToolExecutor | CodeExecDogpileToolDefinition;\n}\n\nexport type BuiltInDogpileRuntimeTool =\n | RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput>\n | RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput>;\n\n/**\n * Vercel AI SDK tool shape accepted by Dogpile's normalization adapter.\n */\nexport interface VercelAITool<Input extends JsonObject = JsonObject, Output extends JsonValue = JsonValue> {\n readonly description?: string;\n readonly inputSchema: VercelAICompatibleSchema<Input>;\n readonly execute?: VercelAIToolExecuteFunction<Input, Output>;\n}\n\n/**\n * Optional identity fields callers may layer onto normalized Vercel AI tools.\n */\nexport interface VercelAIToolIdentityOptions {\n readonly id?: string;\n readonly namespace?: string;\n readonly version?: string;\n readonly description?: string;\n}\n\n/**\n * Definition used to normalize one Vercel AI SDK tool into Dogpile's runtime tool interface.\n */\nexport interface VercelAIToolDefinition<\n Name extends string = string,\n Input extends JsonObject = JsonObject,\n Output extends JsonValue = JsonValue\n> {\n readonly name: Name;\n readonly tool: VercelAITool<Input, Output>;\n readonly identity?: VercelAIToolIdentityOptions;\n readonly inputSchema?: RuntimeToolInputSchema;\n readonly messages?: readonly ModelMessage[];\n}\n\n/**\n * Caller-supplied Vercel AI SDK tool set keyed by model-visible tool name.\n */\nexport interface VercelAIToolSetEntry {\n readonly description?: string;\n readonly inputSchema: VercelAICompatibleSchema<unknown>;\n readonly execute?: VercelAIToolExecuteFunction<never, JsonValue>;\n}\n\n/**\n * Caller-supplied Vercel AI SDK tool set keyed by model-visible tool name.\n */\nexport type VercelAIToolSet = Readonly<Record<string, VercelAIToolSetEntry>>;\n\n/**\n * Options shared while normalizing a Vercel AI SDK tool set.\n */\nexport interface VercelAIToolSetNormalizationOptions {\n readonly namespace?: string;\n readonly version?: string;\n readonly messages?: readonly ModelMessage[];\n readonly identity?: Readonly<Record<string, VercelAIToolIdentityOptions>>;\n}\n\n/**\n * Options for the shared protocol-agnostic runtime tool executor.\n */\nexport interface RuntimeToolExecutorOptions {\n readonly runId: string;\n readonly protocol: RuntimeToolExecutionContext[\"protocol\"];\n readonly tier: RuntimeToolExecutionContext[\"tier\"];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly emit?: (event: RunEvent) => void;\n readonly getTrace?: () => RuntimeToolTraceContext;\n readonly metadata?: JsonObject;\n readonly abortSignal?: AbortSignal;\n readonly makeToolCallId?: (tool: RuntimeToolIdentity, callIndex: number) => string;\n}\n\nconst webSearchIdentity: RuntimeToolIdentity = {\n id: \"dogpile.tools.webSearch\",\n namespace: \"dogpile\",\n name: \"webSearch\",\n version: \"1.0.0\",\n description: \"Search the web through a caller-provided fetch-compatible search adapter.\"\n};\n\nconst codeExecIdentity: RuntimeToolIdentity = {\n id: \"dogpile.tools.codeExec\",\n namespace: \"dogpile\",\n name: \"codeExec\",\n version: \"1.0.0\",\n description: \"Execute code through a caller-provided sandbox adapter.\"\n};\n\nconst webSearchInputSchema: RuntimeToolInputSchema = {\n kind: \"json-schema\",\n description: \"Web search query and optional result cap.\",\n schema: {\n type: \"object\",\n properties: {\n query: { type: \"string\" },\n maxResults: { type: \"number\", minimum: 1 }\n },\n required: [\"query\"],\n additionalProperties: false\n }\n};\n\nconst codeExecInputSchema: RuntimeToolInputSchema = {\n kind: \"json-schema\",\n description: \"Code snippet plus language and optional timeout.\",\n schema: {\n type: \"object\",\n properties: {\n language: {\n type: \"string\",\n enum: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"]\n },\n code: { type: \"string\" },\n timeoutMs: { type: \"number\", minimum: 1 }\n },\n required: [\"language\", \"code\"],\n additionalProperties: false\n }\n};\n\nconst webSearchPermissions: readonly RuntimeToolPermission[] = [\n {\n kind: \"network\",\n allowPrivateNetwork: false\n }\n];\n\nconst codeExecPermissions: readonly RuntimeToolPermission[] = [\n {\n kind: \"code-execution\",\n sandbox: \"caller-provided\",\n languages: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"],\n allowNetwork: false\n }\n];\n\nconst codeExecLanguages: readonly CodeExecToolLanguage[] = [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"];\n\n/**\n * Return the default Dogpile identity for one built-in tool name.\n */\nexport function builtInDogpileToolIdentity(name: \"webSearch\"): RuntimeToolIdentity;\nexport function builtInDogpileToolIdentity(name: \"codeExec\"): RuntimeToolIdentity;\nexport function builtInDogpileToolIdentity(name: DogpileBuiltInToolName): RuntimeToolIdentity {\n return name === \"webSearch\" ? webSearchIdentity : codeExecIdentity;\n}\n\n/**\n * Return the default Dogpile input schema for one built-in tool name.\n */\nexport function builtInDogpileToolInputSchema(name: \"webSearch\"): RuntimeToolInputSchema;\nexport function builtInDogpileToolInputSchema(name: \"codeExec\"): RuntimeToolInputSchema;\nexport function builtInDogpileToolInputSchema(name: DogpileBuiltInToolName): RuntimeToolInputSchema {\n return name === \"webSearch\" ? webSearchInputSchema : codeExecInputSchema;\n}\n\n/**\n * Return the default permission declarations for one built-in tool name.\n */\nexport function builtInDogpileToolPermissions(name: DogpileBuiltInToolName): readonly RuntimeToolPermission[] {\n return name === \"webSearch\" ? webSearchPermissions : codeExecPermissions;\n}\n\n/**\n * Validate one built-in Dogpile tool input before adapter execution.\n */\nexport function validateBuiltInDogpileToolInput(\n name: \"webSearch\",\n input: Readonly<Partial<WebSearchToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: \"codeExec\",\n input: Readonly<Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: DogpileBuiltInToolName,\n input: Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult;\nexport function validateBuiltInDogpileToolInput(\n name: DogpileBuiltInToolName,\n input: Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n): RuntimeToolValidationResult {\n const issues =\n name === \"webSearch\"\n ? validateWebSearchInput(input as Readonly<Partial<WebSearchToolInput>>)\n : validateCodeExecInput(input as Readonly<Partial<CodeExecToolInput>>);\n\n return issues.length === 0 ? { type: \"valid\" } : { type: \"invalid\", issues };\n}\n\n/**\n * Create the shared runtime tool executor used by every first-party protocol.\n *\n * @remarks\n * The executor owns call id generation, read-only trace context construction,\n * adapter validation, error normalization, and matched `tool-call` /\n * `tool-result` events. Protocols only supply a normalized\n * {@link RuntimeToolExecutionRequest}, which keeps tool execution independent\n * of Coordinator, Sequential, Broadcast, or Shared control flow.\n */\nexport function createRuntimeToolExecutor(options: RuntimeToolExecutorOptions): RuntimeToolExecutor {\n validateRuntimeToolRegistrations(options.tools);\n const tools = Array.from(options.tools);\n let callCount = 0;\n\n return {\n tools,\n async execute(request: RuntimeToolExecutionRequest): Promise<RuntimeToolResult> {\n const tool = tools.find((candidate) => candidate.identity.id === request.toolId);\n const identity = tool?.identity ?? {\n id: request.toolId,\n name: request.toolId\n };\n const callIndex = callCount;\n callCount += 1;\n const toolCallId =\n request.toolCallId ?? options.makeToolCallId?.(identity, callIndex) ?? defaultToolCallId(options.runId, callIndex);\n const context = createExecutionContext(options, request, toolCallId);\n\n options.emit?.({\n type: \"tool-call\",\n runId: options.runId,\n at: new Date().toISOString(),\n toolCallId,\n tool: identity,\n input: request.input,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {})\n });\n\n const result = await executeRuntimeTool(tool, identity, request.input, context);\n\n options.emit?.({\n type: \"tool-result\",\n runId: options.runId,\n at: new Date().toISOString(),\n toolCallId,\n tool: identity,\n result,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {})\n });\n\n return result;\n }\n };\n}\n\n/**\n * Return a JSON-serializable manifest for tools visible to a protocol run.\n */\nexport function runtimeToolManifest(tools: readonly RuntimeTool<JsonObject, JsonValue>[]): JsonObject[] {\n return tools.map((tool) => {\n const inputSchema: JsonObject = {\n kind: tool.inputSchema.kind,\n schema: tool.inputSchema.schema,\n ...(tool.inputSchema.description ? { description: tool.inputSchema.description } : {})\n };\n\n return {\n identity: runtimeToolIdentityManifest(tool.identity),\n inputSchema,\n permissions: Array.from(tool.permissions ?? []).map(runtimeToolPermissionManifest)\n };\n });\n}\n\n/**\n * Return request metadata that makes runtime tools visible to provider\n * adapters, or an empty object when no tools are available.\n */\nexport function runtimeToolAvailability(tools: readonly RuntimeTool<JsonObject, JsonValue>[]): JsonObject {\n const manifest = runtimeToolManifest(tools);\n return manifest.length > 0 ? { tools: manifest } : {};\n}\n\n/**\n * Execute normalized tool requests returned by a provider response.\n */\nexport async function executeModelResponseToolRequests(options: {\n readonly response: ModelResponse;\n readonly executor: RuntimeToolExecutor;\n readonly agentId: string;\n readonly role: string;\n readonly turn: number;\n readonly metadata?: JsonObject;\n}): Promise<readonly TranscriptToolCall[]> {\n const toolCalls: TranscriptToolCall[] = [];\n\n for (const request of options.response.toolRequests ?? []) {\n const result = await options.executor.execute({\n ...request,\n agentId: request.agentId ?? options.agentId,\n role: request.role ?? options.role,\n turn: request.turn ?? options.turn,\n metadata: mergeToolMetadata(options.metadata, request.metadata)\n });\n toolCalls.push({\n toolCallId: result.toolCallId,\n tool: result.tool,\n input: request.input,\n result\n });\n }\n\n return toolCalls;\n}\n\nfunction runtimeToolIdentityManifest(identity: RuntimeToolIdentity): JsonObject {\n return {\n id: identity.id,\n name: identity.name,\n ...(identity.namespace ? { namespace: identity.namespace } : {}),\n ...(identity.version ? { version: identity.version } : {}),\n ...(identity.description ? { description: identity.description } : {})\n };\n}\n\nfunction runtimeToolPermissionManifest(permission: RuntimeToolPermission): JsonObject {\n if (permission.kind === \"network\") {\n return {\n kind: permission.kind,\n ...(permission.allowHosts ? { allowHosts: Array.from(permission.allowHosts) } : {}),\n ...(permission.allowPrivateNetwork === undefined ? {} : { allowPrivateNetwork: permission.allowPrivateNetwork })\n };\n }\n\n if (permission.kind === \"code-execution\") {\n return {\n kind: permission.kind,\n sandbox: permission.sandbox,\n ...(permission.languages ? { languages: Array.from(permission.languages) } : {}),\n ...(permission.allowNetwork === undefined ? {} : { allowNetwork: permission.allowNetwork })\n };\n }\n\n return {\n kind: permission.kind,\n name: permission.name,\n ...(permission.description ? { description: permission.description } : {}),\n ...(permission.metadata ? { metadata: permission.metadata } : {})\n };\n}\n\nfunction validateCodeExecAdapterInput(\n input: Readonly<Partial<CodeExecToolInput>>,\n options: Pick<CodeExecToolAdapterOptions, \"languages\" | \"maxTimeoutMs\" | \"defaultTimeoutMs\">\n): RuntimeToolValidationResult {\n const issues = [...validateCodeExecInput(input)];\n const languages = options.languages ?? codeExecLanguages;\n\n if (typeof input.language === \"string\" && isCodeExecLanguage(input.language) && !languages.includes(input.language)) {\n issues.push({\n code: \"invalid-value\",\n path: \"language\",\n message: \"codeExec.language is not enabled for this adapter.\",\n detail: {\n allowed: Array.from(languages)\n }\n });\n }\n\n const effectiveTimeoutMs = input.timeoutMs ?? options.defaultTimeoutMs;\n if (\n effectiveTimeoutMs !== undefined &&\n options.maxTimeoutMs !== undefined &&\n Number.isFinite(effectiveTimeoutMs) &&\n Number.isFinite(options.maxTimeoutMs) &&\n effectiveTimeoutMs > options.maxTimeoutMs\n ) {\n issues.push({\n code: \"out-of-range\",\n path: input.timeoutMs === undefined ? \"defaultTimeoutMs\" : \"timeoutMs\",\n message: `codeExec.timeoutMs must be less than or equal to ${options.maxTimeoutMs}.`,\n detail: {\n maximum: options.maxTimeoutMs\n }\n });\n }\n\n return issues.length === 0 ? { type: \"valid\" } : { type: \"invalid\", issues };\n}\n\nfunction createExecutionContext(\n options: RuntimeToolExecutorOptions,\n request: RuntimeToolExecutionRequest,\n toolCallId: string\n): RuntimeToolExecutionContext {\n return {\n runId: options.runId,\n toolCallId,\n protocol: options.protocol,\n tier: options.tier,\n ...(request.agentId ? { agentId: request.agentId } : {}),\n ...(request.role ? { role: request.role } : {}),\n ...(request.turn !== undefined ? { turn: request.turn } : {}),\n ...(options.getTrace ? { trace: options.getTrace() } : {}),\n ...(request.abortSignal ?? options.abortSignal ? { abortSignal: request.abortSignal ?? options.abortSignal } : {}),\n ...(options.metadata || request.metadata ? { metadata: mergeToolMetadata(options.metadata, request.metadata) } : {})\n };\n}\n\nasync function executeRuntimeTool(\n tool: RuntimeTool<JsonObject, JsonValue> | undefined,\n identity: RuntimeToolIdentity,\n input: JsonObject,\n context: RuntimeToolExecutionContext\n): Promise<RuntimeToolResult> {\n if (!tool) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"unavailable\",\n message: `Runtime tool \"${identity.id}\" is not registered.`,\n retryable: false\n }\n };\n }\n\n const validation = validateRuntimeToolInput(tool, input);\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: \"Runtime tool input failed validation.\",\n retryable: false,\n detail: {\n issues: validation.issues.map((issue) => ({\n code: issue.code,\n path: issue.path,\n message: issue.message,\n ...(issue.detail ? { detail: issue.detail } : {})\n }))\n }\n }\n };\n }\n\n try {\n return await tool.execute(input, context);\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n}\n\nfunction validateRuntimeToolInput(\n tool: RuntimeTool<JsonObject, JsonValue>,\n input: JsonObject\n): RuntimeToolValidationResult {\n if (typeof tool.validateInput !== \"function\") {\n return { type: \"valid\" };\n }\n\n return tool.validateInput(input);\n}\n\nfunction mergeToolMetadata(base: JsonObject | undefined, request: JsonObject | undefined): JsonObject {\n return {\n ...(base ?? {}),\n ...(request ?? {})\n };\n}\n\nfunction defaultToolCallId(runId: string, callIndex: number): string {\n return `${runId}:tool-${callIndex + 1}`;\n}\n\n/**\n * Convert an unknown adapter failure into Dogpile's serializable error data.\n */\nexport function normalizeRuntimeToolAdapterError(error: unknown): RuntimeToolAdapterError {\n if (isRuntimeToolAdapterError(error)) {\n return error;\n }\n\n if (error instanceof DOMException && error.name === \"AbortError\") {\n return {\n code: \"aborted\",\n message: error.message || \"Tool execution was aborted.\",\n retryable: true,\n detail: {\n name: error.name\n }\n };\n }\n\n if (error instanceof Error) {\n return {\n code: \"backend-error\",\n message: error.message,\n retryable: false,\n detail: {\n name: error.name\n }\n };\n }\n\n return {\n code: \"unknown\",\n message: \"Tool execution failed with a non-Error value.\",\n retryable: false,\n detail: {\n valueType: typeof error\n }\n };\n}\n\n/**\n * Create Dogpile's built-in fetch-based web search adapter.\n *\n * @remarks\n * The adapter is backend-neutral: by default it sends a GET request with\n * `q` and `limit` query parameters, then accepts either `{ results: [...] }`\n * or a bare array of result objects from the response JSON. Callers can replace\n * request construction or response parsing for a specific search API while\n * keeping Dogpile's shared runtime tool contract, identity, permissions, input\n * validation, and serializable errors.\n */\nexport function createWebSearchToolAdapter(\n options: WebSearchToolAdapterOptions\n): RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput> {\n const identity = mergeIdentity(webSearchIdentity, options.identity);\n\n return normalizeBuiltInDogpileTool({\n name: \"webSearch\",\n ...(options.identity ? { identity: options.identity } : {}),\n ...(options.permissions ? { permissions: options.permissions } : {}),\n async execute(input, context): Promise<RuntimeToolResult<WebSearchToolOutput>> {\n const fetchImplementation = options.fetch ?? globalThis.fetch;\n\n if (!fetchImplementation) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"unavailable\",\n message: \"No fetch implementation is available for webSearch.\",\n retryable: false\n }\n };\n }\n\n const request = options.buildRequest\n ? options.buildRequest(input, context)\n : defaultWebSearchRequest(options, input, context);\n const response = await fetchImplementation(request.url, {\n ...request.init,\n ...(context.abortSignal ? { signal: context.abortSignal } : {})\n });\n\n if (!response.ok) {\n throw {\n code: response.status >= 500 ? \"unavailable\" : \"backend-error\",\n message: `Web search backend returned HTTP ${response.status}.`,\n retryable: response.status === 408 || response.status === 429 || response.status >= 500,\n detail: {\n status: response.status,\n statusText: response.statusText\n }\n } satisfies RuntimeToolAdapterError;\n }\n\n const output = options.parseResponse\n ? await options.parseResponse(response, input, context)\n : await defaultWebSearchResponseParser(response);\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n }\n });\n}\n\n/**\n * Create Dogpile's built-in code execution adapter around a caller-owned sandbox.\n *\n * @remarks\n * Dogpile core stays runtime-portable and never evaluates code itself. This\n * adapter supplies the stable `codeExec` identity, schema, permissions,\n * validation, timeout defaults, abort handling, and serializable errors while\n * the host application owns the sandbox boundary.\n */\nexport function createCodeExecToolAdapter(\n options: CodeExecToolAdapterOptions\n): RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput> {\n const identity = mergeIdentity(codeExecIdentity, options.identity);\n const permissions =\n options.permissions ??\n codeExecPermissionsFor(options.languages ?? codeExecLanguages, options.allowNetwork ?? false);\n const inputSchema = codeExecInputSchemaFor(options.languages ?? codeExecLanguages);\n\n return {\n identity,\n inputSchema,\n permissions,\n validateInput: (input: Readonly<CodeExecToolInput>) => validateCodeExecAdapterInput(input, options),\n async execute(input, context): Promise<RuntimeToolResult<CodeExecToolOutput>> {\n const validation = validateCodeExecAdapterInput(input, options);\n\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: \"Invalid codeExec tool input.\",\n retryable: false,\n detail: {\n issues: validation.issues as unknown as JsonValue\n }\n }\n };\n }\n\n const timeoutMs = input.timeoutMs ?? options.defaultTimeoutMs;\n const executionInput: CodeExecToolInput =\n timeoutMs === undefined\n ? input\n : {\n ...input,\n timeoutMs\n };\n\n try {\n const output = await executeSandboxWithPolicy(options.execute, executionInput, context, timeoutMs);\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n }\n };\n}\n\n/**\n * Normalize one built-in Dogpile tool definition into the shared runtime tool interface.\n */\nexport function normalizeBuiltInDogpileTool(\n definition: WebSearchDogpileToolDefinition\n): RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput>;\nexport function normalizeBuiltInDogpileTool(\n definition: CodeExecDogpileToolDefinition\n): RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput>;\nexport function normalizeBuiltInDogpileTool(definition: BuiltInDogpileToolDefinition): BuiltInDogpileRuntimeTool {\n switch (definition.name) {\n case \"webSearch\": {\n const identity = mergeIdentity(webSearchIdentity, definition.identity);\n const permissions = definition.permissions ?? webSearchPermissions;\n const tool: RuntimeToolAdapterContract<WebSearchToolInput, WebSearchToolOutput> = {\n identity,\n inputSchema: definition.inputSchema ?? webSearchInputSchema,\n permissions,\n validateInput: (input: Readonly<WebSearchToolInput>) => validateBuiltInDogpileToolInput(\"webSearch\", input),\n execute: (input: Readonly<WebSearchToolInput>, context: RuntimeToolExecutionContext) =>\n executeBuiltInTool(identity, definition.execute, input, context, \"webSearch\")\n };\n return tool;\n }\n case \"codeExec\": {\n const identity = mergeIdentity(codeExecIdentity, definition.identity);\n const permissions = definition.permissions ?? codeExecPermissions;\n const tool: RuntimeToolAdapterContract<CodeExecToolInput, CodeExecToolOutput> = {\n identity,\n inputSchema: definition.inputSchema ?? codeExecInputSchema,\n permissions,\n validateInput: (input: Readonly<CodeExecToolInput>) => validateBuiltInDogpileToolInput(\"codeExec\", input),\n execute: (input: Readonly<CodeExecToolInput>, context: RuntimeToolExecutionContext) =>\n executeBuiltInTool(identity, definition.execute, input, context, \"codeExec\")\n };\n return tool;\n }\n }\n}\n\n/**\n * Normalize configured built-in Dogpile tool executors into runtime tools.\n */\nexport function normalizeBuiltInDogpileTools(tools: BuiltInDogpileToolExecutors): readonly BuiltInDogpileRuntimeTool[] {\n const normalized: BuiltInDogpileRuntimeTool[] = [];\n\n if (tools.webSearch) {\n normalized.push(normalizeBuiltInDogpileTool(asWebSearchDefinition(tools.webSearch)));\n }\n\n if (tools.codeExec) {\n normalized.push(normalizeBuiltInDogpileTool(asCodeExecDefinition(tools.codeExec)));\n }\n\n return normalized;\n}\n\n/**\n * Normalize one Vercel AI SDK tool into Dogpile's shared runtime tool interface.\n */\nexport async function normalizeVercelAITool<\n Name extends string,\n Input extends JsonObject,\n Output extends JsonValue\n>(definition: VercelAIToolDefinition<Name, Input, Output>): Promise<RuntimeTool<Input, Output>> {\n if (!definition.tool.execute) {\n throw new Error(`Vercel AI tool \"${definition.name}\" must define execute() to run inside Dogpile.`);\n }\n\n const identity = vercelAIToolIdentity(definition);\n const inputSchema = definition.inputSchema ?? (await vercelAIInputSchema(definition.tool, definition.name));\n const execute = definition.tool.execute;\n\n return {\n identity,\n inputSchema,\n async execute(input, context): Promise<RuntimeToolResult<Output>> {\n try {\n const output = await resolveVercelAIToolOutput(\n execute(input, {\n toolCallId: context.toolCallId,\n messages: Array.from(definition.messages ?? []),\n ...(context.abortSignal ? { abortSignal: context.abortSignal } : {}),\n experimental_context: context\n })\n );\n\n return {\n type: \"success\",\n toolCallId: context.toolCallId,\n tool: identity,\n output\n };\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"vercel-ai-tool-error\",\n message: error instanceof Error ? error.message : \"Vercel AI tool execution failed.\",\n retryable: false,\n detail: errorDetail(error)\n }\n };\n }\n }\n };\n}\n\n/**\n * Normalize a Vercel AI SDK tool set into runtime tools in caller-defined key order.\n */\nexport async function normalizeVercelAITools(\n tools: VercelAIToolSet,\n options: VercelAIToolSetNormalizationOptions = {}\n): Promise<readonly RuntimeTool<JsonObject, JsonValue>[]> {\n return Promise.all(\n Object.entries(tools).map(([name, tool]) => {\n const identity = removeUndefinedIdentityFields({\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...options.identity?.[name]\n });\n return normalizeVercelAITool({\n name,\n tool: asJsonRuntimeVercelAITool(tool),\n ...(options.messages ? { messages: options.messages } : {}),\n ...(identity ? { identity } : {})\n });\n })\n );\n}\n\nasync function executeBuiltInTool<Input extends object, Output>(\n identity: RuntimeToolIdentity,\n execute: (\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext\n ) => RuntimeToolResult<Output> | Promise<RuntimeToolResult<Output>>,\n input: Readonly<Input>,\n context: RuntimeToolExecutionContext,\n name: DogpileBuiltInToolName\n): Promise<RuntimeToolResult<Output>> {\n const validation = validateBuiltInDogpileToolInput(\n name,\n input as Readonly<Partial<WebSearchToolInput> | Partial<CodeExecToolInput>>\n );\n\n if (validation.type === \"invalid\") {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: {\n code: \"invalid-input\",\n message: `Invalid ${name} tool input.`,\n retryable: false,\n detail: {\n issues: validation.issues as unknown as JsonValue\n }\n }\n };\n }\n\n try {\n return await execute(input, context);\n } catch (error) {\n return {\n type: \"error\",\n toolCallId: context.toolCallId,\n tool: identity,\n error: normalizeRuntimeToolAdapterError(error)\n };\n }\n}\n\nfunction asWebSearchDefinition(\n tool: WebSearchToolExecutor | WebSearchDogpileToolDefinition\n): WebSearchDogpileToolDefinition {\n return typeof tool === \"function\" ? { name: \"webSearch\", execute: tool } : tool;\n}\n\nfunction asCodeExecDefinition(tool: CodeExecToolExecutor | CodeExecDogpileToolDefinition): CodeExecDogpileToolDefinition {\n return typeof tool === \"function\" ? { name: \"codeExec\", execute: tool } : tool;\n}\n\nfunction mergeIdentity(\n defaultIdentity: RuntimeToolIdentity,\n options: BuiltInDogpileToolIdentityOptions | undefined\n): RuntimeToolIdentity {\n if (!options) {\n return defaultIdentity;\n }\n\n return {\n ...defaultIdentity,\n ...(options.namespace !== undefined ? { namespace: options.namespace } : {}),\n ...(options.version !== undefined ? { version: options.version } : {}),\n ...(options.description !== undefined ? { description: options.description } : {})\n };\n}\n\nasync function vercelAIInputSchema<Input extends JsonObject, Output extends JsonValue>(\n tool: VercelAITool<Input, Output>,\n name: string\n): Promise<RuntimeToolInputSchema> {\n const schema = await resolveCompatibleSchema(tool.inputSchema);\n const jsonSchema = asJsonObject(schema, `Vercel AI tool \"${name}\" input schema`);\n\n return {\n kind: \"json-schema\",\n schema: jsonSchema,\n ...(tool.description ? { description: tool.description } : {})\n };\n}\n\nasync function resolveCompatibleSchema<Input>(schema: VercelAICompatibleSchema<Input>): Promise<unknown> {\n if (isJsonSchemaWrapper(schema)) {\n return await schema.jsonSchema;\n }\n\n return schema;\n}\n\nfunction isJsonSchemaWrapper<Input>(\n schema: VercelAICompatibleSchema<Input>\n): schema is { readonly jsonSchema: unknown | PromiseLike<unknown> } {\n return typeof schema === \"object\" && schema !== null && \"jsonSchema\" in schema;\n}\n\nfunction vercelAIToolIdentity<Name extends string, Input extends JsonObject, Output extends JsonValue>(\n definition: VercelAIToolDefinition<Name, Input, Output>\n): RuntimeToolIdentity {\n return {\n id: definition.identity?.id ?? `vercel-ai.tools.${definition.name}`,\n name: definition.name,\n namespace: definition.identity?.namespace ?? \"vercel-ai\",\n ...(definition.identity?.version ? { version: definition.identity.version } : {}),\n ...(definition.identity?.description ?? definition.tool.description\n ? { description: definition.identity?.description ?? definition.tool.description }\n : {})\n };\n}\n\nasync function resolveVercelAIToolOutput<Output extends JsonValue>(\n output: AsyncIterable<Output> | PromiseLike<Output> | Output\n): Promise<Output> {\n if (isAsyncIterable(output)) {\n let lastOutput: Output | undefined;\n\n for await (const chunk of output) {\n lastOutput = chunk;\n }\n\n if (lastOutput === undefined) {\n throw new Error(\"Vercel AI tool async iterable completed without an output.\");\n }\n\n return lastOutput;\n }\n\n return await output;\n}\n\nfunction isAsyncIterable<Output extends JsonValue>(\n value: AsyncIterable<Output> | PromiseLike<Output> | Output\n): value is AsyncIterable<Output> {\n return typeof value === \"object\" && value !== null && Symbol.asyncIterator in value;\n}\n\nfunction asJsonObject(value: unknown, label: string): JsonObject {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) {\n throw new Error(`${label} must resolve to a JSON object.`);\n }\n\n return value as JsonObject;\n}\n\nfunction errorDetail(error: unknown): JsonObject {\n if (error instanceof Error) {\n return {\n name: error.name\n };\n }\n\n return {\n valueType: typeof error\n };\n}\n\nfunction defaultWebSearchRequest(\n options: WebSearchToolAdapterOptions,\n input: Readonly<WebSearchToolInput>,\n _context: RuntimeToolExecutionContext\n): WebSearchFetchRequest {\n const url = new URL(String(options.endpoint));\n url.searchParams.set(\"q\", input.query);\n url.searchParams.set(\"limit\", String(input.maxResults ?? options.defaultMaxResults ?? 10));\n\n return {\n url,\n init: {\n method: \"GET\",\n ...(options.headers ? { headers: options.headers } : {})\n }\n };\n}\n\nasync function defaultWebSearchResponseParser(response: Response): Promise<WebSearchToolOutput> {\n const payload: unknown = await response.json();\n const resultValues = Array.isArray(payload)\n ? payload\n : isJsonObject(payload) && Array.isArray(payload.results)\n ? payload.results\n : undefined;\n\n if (!resultValues) {\n throw {\n code: \"backend-error\",\n message: \"Web search backend response must contain a results array.\",\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return {\n results: resultValues.map(normalizeWebSearchResult)\n };\n}\n\nfunction codeExecPermissionsFor(\n languages: readonly CodeExecToolLanguage[],\n allowNetwork: boolean\n): readonly RuntimeToolPermission[] {\n return [\n {\n kind: \"code-execution\",\n sandbox: \"caller-provided\",\n languages,\n allowNetwork\n }\n ];\n}\n\nfunction codeExecInputSchemaFor(languages: readonly CodeExecToolLanguage[]): RuntimeToolInputSchema {\n return {\n kind: \"json-schema\",\n ...(codeExecInputSchema.description ? { description: codeExecInputSchema.description } : {}),\n schema: {\n type: \"object\",\n properties: {\n language: {\n type: \"string\",\n enum: Array.from(languages)\n },\n code: { type: \"string\" },\n timeoutMs: { type: \"number\", minimum: 1 }\n },\n required: [\"language\", \"code\"],\n additionalProperties: false\n }\n };\n}\n\nasync function executeSandboxWithPolicy(\n execute: CodeExecSandboxExecutor,\n input: Readonly<CodeExecToolInput>,\n context: RuntimeToolExecutionContext,\n timeoutMs: number | undefined\n): Promise<CodeExecToolOutput> {\n if (context.abortSignal?.aborted) {\n throw {\n code: \"aborted\",\n message: \"Code execution was aborted before the sandbox started.\",\n retryable: true\n } satisfies RuntimeToolAdapterError;\n }\n\n const execution = Promise.resolve().then(() => execute(input, context));\n\n if (timeoutMs === undefined && context.abortSignal === undefined) {\n return await execution;\n }\n\n return await new Promise<CodeExecToolOutput>((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const cleanup = (): void => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n context.abortSignal?.removeEventListener(\"abort\", abortHandler);\n };\n\n const abortHandler = (): void => {\n cleanup();\n reject({\n code: \"aborted\",\n message: \"Code execution was aborted.\",\n retryable: true\n } satisfies RuntimeToolAdapterError);\n };\n\n if (context.abortSignal) {\n context.abortSignal.addEventListener(\"abort\", abortHandler, { once: true });\n }\n\n if (timeoutMs !== undefined) {\n timeoutId = setTimeout(() => {\n cleanup();\n reject({\n code: \"timeout\",\n message: `Code execution exceeded timeout of ${timeoutMs}ms.`,\n retryable: true,\n detail: {\n timeoutMs\n }\n } satisfies RuntimeToolAdapterError);\n }, timeoutMs);\n }\n\n execution.then(\n (output) => {\n cleanup();\n resolve(output);\n },\n (error: unknown) => {\n cleanup();\n reject(error);\n }\n );\n });\n}\n\nfunction normalizeWebSearchResult(value: unknown): WebSearchToolResult {\n if (!isJsonObject(value)) {\n throw {\n code: \"backend-error\",\n message: \"Web search result must be a JSON object.\",\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n const title = jsonString(value.title, \"title\");\n const url = jsonString(value.url, \"url\");\n const snippet = optionalJsonString(value.snippet, \"snippet\");\n const metadata = optionalJsonObject(value.metadata, \"metadata\");\n\n return {\n title,\n url,\n ...(snippet !== undefined ? { snippet } : {}),\n ...(metadata !== undefined ? { metadata } : {})\n };\n}\n\nfunction jsonString(value: JsonValue | undefined, fieldName: string): string {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a non-empty string.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction optionalJsonString(value: JsonValue | undefined, fieldName: string): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value !== \"string\") {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a string when present.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction optionalJsonObject(value: JsonValue | undefined, fieldName: string): JsonObject | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (!isJsonObject(value)) {\n throw {\n code: \"backend-error\",\n message: `Web search result ${fieldName} must be a JSON object when present.`,\n retryable: false\n } satisfies RuntimeToolAdapterError;\n }\n\n return value;\n}\n\nfunction isJsonObject(value: unknown): value is JsonObject {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction validateWebSearchInput(input: Readonly<Partial<WebSearchToolInput>>): readonly RuntimeToolValidationIssue[] {\n const issues: RuntimeToolValidationIssue[] = [];\n\n if (typeof input.query !== \"string\") {\n issues.push({\n code: input.query === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"query\",\n message: \"webSearch.query must be a string.\"\n });\n } else if (input.query.trim().length === 0) {\n issues.push({\n code: \"invalid-value\",\n path: \"query\",\n message: \"webSearch.query must not be empty.\"\n });\n }\n\n if (input.maxResults !== undefined) {\n if (typeof input.maxResults !== \"number\" || !Number.isFinite(input.maxResults)) {\n issues.push({\n code: \"invalid-type\",\n path: \"maxResults\",\n message: \"webSearch.maxResults must be a finite number.\"\n });\n } else if (input.maxResults < 1) {\n issues.push({\n code: \"out-of-range\",\n path: \"maxResults\",\n message: \"webSearch.maxResults must be greater than or equal to 1.\",\n detail: {\n minimum: 1\n }\n });\n }\n }\n\n return issues;\n}\n\nfunction validateCodeExecInput(input: Readonly<Partial<CodeExecToolInput>>): readonly RuntimeToolValidationIssue[] {\n const issues: RuntimeToolValidationIssue[] = [];\n\n if (typeof input.language !== \"string\") {\n issues.push({\n code: input.language === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"language\",\n message: \"codeExec.language must be a string.\"\n });\n } else if (!isCodeExecLanguage(input.language)) {\n issues.push({\n code: \"invalid-value\",\n path: \"language\",\n message: \"codeExec.language must be one of javascript, typescript, python, bash, or shell.\",\n detail: {\n allowed: [\"javascript\", \"typescript\", \"python\", \"bash\", \"shell\"]\n }\n });\n }\n\n if (typeof input.code !== \"string\") {\n issues.push({\n code: input.code === undefined ? \"missing-field\" : \"invalid-type\",\n path: \"code\",\n message: \"codeExec.code must be a string.\"\n });\n }\n\n if (input.timeoutMs !== undefined) {\n if (typeof input.timeoutMs !== \"number\" || !Number.isFinite(input.timeoutMs)) {\n issues.push({\n code: \"invalid-type\",\n path: \"timeoutMs\",\n message: \"codeExec.timeoutMs must be a finite number.\"\n });\n } else if (input.timeoutMs < 1) {\n issues.push({\n code: \"out-of-range\",\n path: \"timeoutMs\",\n message: \"codeExec.timeoutMs must be greater than or equal to 1.\",\n detail: {\n minimum: 1\n }\n });\n }\n }\n\n return issues;\n}\n\nfunction isCodeExecLanguage(value: string): value is CodeExecToolInput[\"language\"] {\n return value === \"javascript\" || value === \"typescript\" || value === \"python\" || value === \"bash\" || value === \"shell\";\n}\n\nfunction isRuntimeToolAdapterError(error: unknown): error is RuntimeToolAdapterError {\n if (typeof error !== \"object\" || error === null || !(\"code\" in error) || !(\"message\" in error)) {\n return false;\n }\n\n const candidate = error as { readonly code: unknown; readonly message: unknown };\n return isRuntimeToolAdapterErrorCode(candidate.code) && typeof candidate.message === \"string\";\n}\n\nfunction isRuntimeToolAdapterErrorCode(value: unknown): value is RuntimeToolAdapterError[\"code\"] {\n return (\n value === \"invalid-input\" ||\n value === \"permission-denied\" ||\n value === \"timeout\" ||\n value === \"aborted\" ||\n value === \"unavailable\" ||\n value === \"backend-error\" ||\n value === \"unknown\"\n );\n}\n\nfunction removeUndefinedIdentityFields(\n identity: VercelAIToolIdentityOptions\n): VercelAIToolIdentityOptions | undefined {\n const normalized: VercelAIToolIdentityOptions = {\n ...(identity.id !== undefined ? { id: identity.id } : {}),\n ...(identity.namespace !== undefined ? { namespace: identity.namespace } : {}),\n ...(identity.version !== undefined ? { version: identity.version } : {}),\n ...(identity.description !== undefined ? { description: identity.description } : {})\n };\n\n return Object.keys(normalized).length > 0 ? normalized : undefined;\n}\n\nfunction asJsonRuntimeVercelAITool(tool: VercelAIToolSetEntry): VercelAITool<JsonObject, JsonValue> {\n return tool as unknown as VercelAITool<JsonObject, JsonValue>;\n}\n","import type {\n BudgetCaps,\n BudgetTier,\n EngineOptions,\n JsonObject,\n ModelMessage,\n Protocol,\n ProtocolConfig,\n RunEvent,\n TerminationCondition,\n TerminationEvaluationContext,\n TranscriptEntry,\n WrapUpHintConfig\n} from \"../types.js\";\n\ninterface WrapUpControllerOptions {\n readonly protocol: ProtocolConfig;\n readonly tier: BudgetTier;\n readonly budget?: BudgetCaps;\n readonly terminate?: TerminationCondition;\n readonly wrapUpHint?: WrapUpHintConfig;\n}\n\ninterface WrapUpContextOptions {\n readonly runId: string;\n readonly protocol: Protocol;\n readonly protocolConfig?: ProtocolConfig;\n readonly cost: TerminationEvaluationContext[\"cost\"];\n readonly events: readonly RunEvent[];\n readonly transcript: readonly TranscriptEntry[];\n readonly iteration?: number;\n readonly protocolIteration?: number;\n readonly elapsedMs?: number;\n readonly metadata?: JsonObject;\n}\n\nexport function createWrapUpHintController(options: WrapUpControllerOptions) {\n const hint = options.wrapUpHint;\n const effectiveBudget = effectiveWrapUpBudget(options.budget, options.terminate);\n let emitted = false;\n\n return {\n context(context: WrapUpContextOptions): TerminationEvaluationContext {\n return wrapUpEvaluationContext({\n ...context,\n tier: options.tier,\n ...(effectiveBudget !== undefined ? { budget: effectiveBudget } : {})\n });\n },\n\n inject(messages: readonly ModelMessage[], context: WrapUpContextOptions): readonly ModelMessage[] {\n if (!hint || emitted) {\n return messages;\n }\n\n const evaluationContext = wrapUpEvaluationContext({\n ...context,\n tier: options.tier,\n ...(effectiveBudget !== undefined ? { budget: effectiveBudget } : {})\n });\n\n if (!shouldInjectWrapUpHint(hint, evaluationContext)) {\n return messages;\n }\n\n const content = (hint.inject ?? defaultWrapUpHint)(evaluationContext);\n emitted = true;\n\n return [\n messages[0] ?? { role: \"system\", content: \"\" },\n { role: \"system\", content },\n ...messages.slice(1)\n ];\n }\n };\n}\n\nfunction wrapUpEvaluationContext(\n options: WrapUpContextOptions & { readonly tier: BudgetTier; readonly budget?: BudgetCaps }\n): TerminationEvaluationContext {\n const iteration = options.iteration ?? options.transcript.length;\n const elapsedMs = options.elapsedMs;\n\n return {\n runId: options.runId,\n protocol: options.protocol,\n tier: options.tier,\n cost: options.cost,\n events: options.events,\n transcript: options.transcript,\n ...(options.protocolConfig !== undefined ? { protocolConfig: options.protocolConfig } : {}),\n ...(iteration !== undefined ? { iteration } : {}),\n ...(options.protocolIteration !== undefined ? { protocolIteration: options.protocolIteration } : {}),\n ...(elapsedMs !== undefined ? { elapsedMs } : {}),\n ...(options.budget !== undefined ? { budget: options.budget } : {}),\n ...(options.budget !== undefined\n ? {\n remainingBudget: remainingBudget(options.budget, {\n cost: options.cost,\n iteration,\n elapsedMs\n })\n }\n : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {})\n };\n}\n\nfunction shouldInjectWrapUpHint(hint: WrapUpHintConfig, context: TerminationEvaluationContext): boolean {\n const iteration = context.iteration ?? context.transcript.length;\n\n if (hint.atIteration !== undefined && iteration >= hint.atIteration) {\n return true;\n }\n\n if (hint.atFraction === undefined || context.budget === undefined) {\n return false;\n }\n\n const fraction = hint.atFraction;\n return (\n capFractionReached(iteration, context.budget.maxIterations, fraction) ||\n capFractionReached(context.elapsedMs, context.budget.timeoutMs, fraction)\n );\n}\n\nfunction capFractionReached(current: number | undefined, limit: number | undefined, fraction: number): boolean {\n if (current === undefined || limit === undefined || limit <= 0) {\n return false;\n }\n\n return current / limit >= fraction;\n}\n\nfunction remainingBudget(\n budget: BudgetCaps,\n current: {\n readonly cost: TerminationEvaluationContext[\"cost\"];\n readonly iteration: number | undefined;\n readonly elapsedMs: number | undefined;\n }\n): NonNullable<TerminationEvaluationContext[\"remainingBudget\"]> {\n return {\n ...(budget.maxIterations !== undefined && current.iteration !== undefined\n ? { iterations: Math.max(0, budget.maxIterations - current.iteration) }\n : {}),\n ...(budget.timeoutMs !== undefined && current.elapsedMs !== undefined\n ? { timeoutMs: Math.max(0, budget.timeoutMs - current.elapsedMs) }\n : {}),\n ...(budget.maxUsd !== undefined ? { usd: Math.max(0, budget.maxUsd - current.cost.usd) } : {}),\n ...(budget.maxTokens !== undefined ? { tokens: Math.max(0, budget.maxTokens - current.cost.totalTokens) } : {})\n };\n}\n\nfunction defaultWrapUpHint(context: TerminationEvaluationContext): string {\n const parts: string[] = [];\n const remaining = context.remainingBudget;\n\n if (remaining?.iterations !== undefined) {\n const label = remaining.iterations === 1 ? \"turn\" : \"turns\";\n parts.push(`${remaining.iterations} ${label} remaining`);\n }\n if (remaining?.timeoutMs !== undefined) {\n parts.push(`${formatRemainingTime(remaining.timeoutMs)} remaining`);\n }\n\n const remainingText =\n parts.length === 0 ? \"You are approaching a configured hard limit.\" : `You are approaching a hard limit with ${parts.join(\" and \")}.`;\n return `[wrap-up] ${remainingText} If you have enough context, package your work now and return a final-ready answer.`;\n}\n\nfunction formatRemainingTime(timeoutMs: number): string {\n if (timeoutMs >= 1_000) {\n return `${(timeoutMs / 1_000).toFixed(1)}s`;\n }\n\n return `${timeoutMs}ms`;\n}\n\nfunction effectiveWrapUpBudget(\n budget: BudgetCaps | undefined,\n terminate: EngineOptions[\"terminate\"]\n): BudgetCaps | undefined {\n const terminationBudget = budgetCapsFromTermination(terminate);\n if (!budget && !terminationBudget) {\n return undefined;\n }\n\n const maxUsd = minCap(budget?.maxUsd, terminationBudget?.maxUsd);\n const maxTokens = minCap(budget?.maxTokens, terminationBudget?.maxTokens);\n const maxIterations = minCap(budget?.maxIterations, terminationBudget?.maxIterations);\n const timeoutMs = minCap(budget?.timeoutMs, terminationBudget?.timeoutMs);\n\n return {\n ...(maxUsd !== undefined ? { maxUsd } : {}),\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n ...(maxIterations !== undefined ? { maxIterations } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {})\n };\n}\n\nfunction budgetCapsFromTermination(condition: TerminationCondition | undefined): BudgetCaps | undefined {\n if (!condition) {\n return undefined;\n }\n\n switch (condition.kind) {\n case \"budget\":\n return {\n ...(condition.maxUsd !== undefined ? { maxUsd: condition.maxUsd } : {}),\n ...(condition.maxTokens !== undefined ? { maxTokens: condition.maxTokens } : {}),\n ...(condition.maxIterations !== undefined ? { maxIterations: condition.maxIterations } : {}),\n ...(condition.timeoutMs !== undefined ? { timeoutMs: condition.timeoutMs } : {})\n };\n case \"firstOf\": {\n let merged: BudgetCaps | undefined;\n for (const child of condition.conditions) {\n merged = mergeBudgetCaps(merged, budgetCapsFromTermination(child));\n }\n return merged;\n }\n case \"convergence\":\n case \"judge\":\n return undefined;\n }\n}\n\nfunction mergeBudgetCaps(left: BudgetCaps | undefined, right: BudgetCaps | undefined): BudgetCaps | undefined {\n if (!left) {\n return right;\n }\n if (!right) {\n return left;\n }\n\n const maxUsd = minCap(left.maxUsd, right.maxUsd);\n const maxTokens = minCap(left.maxTokens, right.maxTokens);\n const maxIterations = minCap(left.maxIterations, right.maxIterations);\n const timeoutMs = minCap(left.timeoutMs, right.timeoutMs);\n\n return {\n ...(maxUsd !== undefined ? { maxUsd } : {}),\n ...(maxTokens !== undefined ? { maxTokens } : {}),\n ...(maxIterations !== undefined ? { maxIterations } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {})\n };\n}\n\nfunction minCap(left: number | undefined, right: number | undefined): number | undefined {\n if (left === undefined) {\n return right;\n }\n if (right === undefined) {\n return left;\n }\n return Math.min(left, right);\n}\n","import type {\n AgentSpec,\n BroadcastContribution,\n BroadcastProtocolConfig,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop, warnOnProtocolTerminationMisconfiguration } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\nimport { createWrapUpHintController } from \"./wrap-up.js\";\n\ninterface BroadcastRunOptions {\n readonly intent: string;\n readonly protocol: BroadcastProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly wrapUpHint?: DogpileOptions[\"wrapUpHint\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runBroadcast(options: BroadcastRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxRounds = options.protocol.maxRounds ?? 2;\n let firstRoundContributions: readonly BroadcastContribution[] = [];\n let lastContributions: readonly BroadcastContribution[] = [];\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n const wrapUpHint = createWrapUpHintController({\n protocol: options.protocol,\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {})\n });\n\n warnOnProtocolTerminationMisconfiguration(options.protocol, options.terminate);\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"broadcast\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of options.agents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n for (let round = 1; round <= maxRounds; round += 1) {\n if (stopIfNeeded()) {\n break;\n }\n\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const turnResults = await Promise.all(\n options.agents.map(async (agent, agentIndex) => {\n const turn = transcript.length + agentIndex + 1;\n const input = buildBroadcastInput(options.intent, round, maxRounds, firstRoundContributions);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"broadcast\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n round,\n ...toolAvailability\n },\n messages: wrapUpHint.inject(\n [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ],\n {\n runId,\n protocol: \"broadcast\",\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n }\n )\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: providerCallIdFor(runId, providerCalls.length + agentIndex + 1),\n onProviderCall(call): void {\n providerCallSlots[agentIndex] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn,\n metadata: {\n round\n }\n });\n throwIfAborted(options.signal, options.model.id);\n\n return {\n agent,\n agentIndex,\n turn,\n input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n })\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n const contributions: BroadcastContribution[] = [];\n for (const result of turnResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n contributions.push({\n agentId: result.agent.id,\n role: result.agent.role,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n round,\n turn: result.turn,\n transcriptEntryCount: transcript.length,\n contributionCount: result.agentIndex + 1\n });\n }\n\n if (contributions.length === 0) {\n break;\n }\n if (round === 1) {\n firstRoundContributions = contributions;\n }\n lastContributions = contributions;\n\n const broadcast: RunEvent = {\n type: \"broadcast\",\n runId,\n at: new Date().toISOString(),\n round,\n contributions,\n cost: totalCost\n };\n emit(broadcast);\n recordProtocolDecision(broadcast, {\n round,\n transcriptEntryCount: transcript.length,\n contributionCount: contributions.length\n });\n\n if (stopIfNeeded()) {\n break;\n }\n }\n\n const output = synthesizeBroadcastOutput(lastContributions);\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"broadcast\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: options.agents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: options.agents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"broadcast\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: options.agents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(\n options.terminate,\n wrapUpHint.context({\n runId,\n protocol: \"broadcast\",\n protocolConfig: options.protocol,\n protocolIteration: broadcastRoundsCompleted(events),\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n })\n );\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction broadcastRoundsCompleted(events: readonly RunEvent[]): number {\n return events.filter((event) => event.type === \"broadcast\").length;\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Broadcast multi-agent protocol.${instruction}`;\n}\n\nfunction buildBroadcastInput(\n intent: string,\n round: number,\n maxRounds: number,\n firstRoundContributions: readonly BroadcastContribution[]\n): string {\n if (maxRounds === 1) {\n return `Mission: ${intent}\\nBroadcast round ${round}: contribute independently before synthesis.`;\n }\n if (round === 1) {\n return `Mission: ${intent}\\nBroadcast round 1: broadcast your intended role and participation decision. Do not produce the final plan yet.`;\n }\n\n const intentions = firstRoundContributions\n .map((contribution) => `${contribution.role}:${contribution.agentId} => ${contribution.output}`)\n .join(\"\\n\");\n return `Mission: ${intent}\\n\\nRound 1 intentions:\\n${intentions || \"(none)\"}\\n\\nBroadcast round ${round}: make your final contribution or abstention decision informed by all round 1 intentions.`;\n}\n\nfunction synthesizeBroadcastOutput(contributions: readonly BroadcastContribution[]): string {\n return contributions.map((entry) => `${entry.role}:${entry.agentId} => ${entry.output}`).join(\"\\n\");\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CoordinatorProtocolConfig,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RuntimeToolExecutor,\n RunEvent,\n RunResult,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost,\n nextProviderCallId\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop, warnOnProtocolTerminationMisconfiguration } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\nimport { createWrapUpHintController } from \"./wrap-up.js\";\n\ninterface CoordinatorRunOptions {\n readonly intent: string;\n readonly protocol: CoordinatorProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly wrapUpHint?: DogpileOptions[\"wrapUpHint\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runCoordinator(options: CoordinatorRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const coordinator = activeAgents[0];\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n const wrapUpHint = createWrapUpHintController({\n protocol: options.protocol,\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {})\n });\n\n warnOnProtocolTerminationMisconfiguration(options.protocol, options.terminate);\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"coordinator\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n if (coordinator) {\n if (!stopIfNeeded()) {\n totalCost = await runCoordinatorTurn({\n agent: coordinator,\n coordinator,\n input: buildCoordinatorPlanInput(options.intent, coordinator),\n phase: \"plan\",\n options,\n runId,\n transcript,\n totalCost,\n providerCalls,\n toolExecutor,\n toolAvailability,\n events,\n startedAtMs,\n wrapUpHint,\n emit,\n recordProtocolDecision\n });\n stopIfNeeded();\n }\n\n if (!stopIfNeeded()) {\n const workers = activeAgents.slice(1);\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const planTranscript = [...transcript];\n const workerResults = await Promise.all(\n workers.map((agent, index) =>\n runCoordinatorWorkerTurn({\n agent,\n coordinator,\n input: buildWorkerInput(options.intent, planTranscript, coordinator),\n options,\n runId,\n turn: transcript.length + index + 1,\n providerCallId: providerCallIdFor(runId, providerCalls.length + index + 1),\n providerCallIndex: index,\n providerCallSlots,\n toolExecutor,\n toolAvailability,\n totalCost,\n events,\n transcript: planTranscript,\n startedAtMs,\n wrapUpHint,\n emit\n })\n )\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n for (const result of workerResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn: transcript.length,\n phase: \"worker\",\n transcriptEntryCount: transcript.length\n });\n }\n stopIfNeeded();\n }\n\n if (!stopIfNeeded()) {\n totalCost = await runCoordinatorTurn({\n agent: coordinator,\n coordinator,\n input: buildFinalSynthesisInput(options.intent, transcript, coordinator),\n phase: \"final-synthesis\",\n options,\n runId,\n transcript,\n totalCost,\n providerCalls,\n toolExecutor,\n toolAvailability,\n events,\n startedAtMs,\n wrapUpHint,\n emit,\n recordProtocolDecision\n });\n stopIfNeeded();\n }\n }\n\n const output = transcript.at(-1)?.output ?? \"\";\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"coordinator\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"coordinator\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(\n options.terminate,\n wrapUpHint.context({\n runId,\n protocol: \"coordinator\",\n protocolConfig: options.protocol,\n protocolIteration: transcript.length,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n })\n );\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\ninterface CoordinatorTurnOptions {\n readonly agent: AgentSpec;\n readonly coordinator: AgentSpec;\n readonly input: string;\n readonly phase: \"plan\" | \"worker\" | \"final-synthesis\";\n readonly options: CoordinatorRunOptions;\n readonly runId: string;\n readonly transcript: TranscriptEntry[];\n readonly totalCost: CostSummary;\n readonly providerCalls: ReplayTraceProviderCall[];\n readonly toolExecutor: RuntimeToolExecutor;\n readonly toolAvailability: JsonObject;\n readonly events: RunEvent[];\n readonly startedAtMs: number;\n readonly wrapUpHint: ReturnType<typeof createWrapUpHintController>;\n readonly emit: (event: RunEvent) => void;\n readonly recordProtocolDecision: (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ) => void;\n}\n\nasync function runCoordinatorTurn(turn: CoordinatorTurnOptions): Promise<CostSummary> {\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n const request: ModelRequest = {\n temperature: turn.options.temperature,\n ...(turn.options.signal !== undefined ? { signal: turn.options.signal } : {}),\n metadata: {\n runId: turn.runId,\n protocol: \"coordinator\",\n agentId: turn.agent.id,\n role: turn.agent.role,\n coordinatorAgentId: turn.coordinator.id,\n tier: turn.options.tier,\n phase: turn.phase,\n ...turn.toolAvailability\n },\n messages: turn.wrapUpHint.inject(\n [\n {\n role: \"system\",\n content: buildSystemPrompt(turn.agent, turn.coordinator)\n },\n {\n role: \"user\",\n content: turn.input\n }\n ],\n {\n runId: turn.runId,\n protocol: \"coordinator\",\n cost: turn.totalCost,\n events: turn.events,\n transcript: turn.transcript,\n iteration: turn.transcript.length,\n elapsedMs: elapsedMs(turn.startedAtMs)\n }\n )\n };\n const response = await generateModelTurn({\n model: turn.options.model,\n request,\n runId: turn.runId,\n agent: turn.agent,\n input: turn.input,\n emit: turn.emit,\n callId: nextProviderCallId(turn.runId, turn.providerCalls),\n onProviderCall(call): void {\n turn.providerCalls.push(call);\n }\n });\n const decision = parseAgentDecision(response.text);\n const totalCost = addCost(turn.totalCost, responseCost(response));\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: turn.toolExecutor,\n agentId: turn.agent.id,\n role: turn.agent.role,\n turn: turn.transcript.length + 1,\n metadata: {\n phase: turn.phase\n }\n });\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n turn.transcript.push({\n agentId: turn.agent.id,\n role: turn.agent.role,\n input: turn.input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n ...(toolCalls.length > 0 ? { toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId: turn.runId,\n at: new Date().toISOString(),\n agentId: turn.agent.id,\n role: turn.agent.role,\n input: turn.input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n cost: totalCost\n };\n turn.emit(event);\n turn.recordProtocolDecision(event, {\n turn: turn.transcript.length,\n phase: turn.phase,\n transcriptEntryCount: turn.transcript.length\n });\n\n return totalCost;\n}\n\ninterface CoordinatorWorkerTurnOptions {\n readonly agent: AgentSpec;\n readonly coordinator: AgentSpec;\n readonly input: string;\n readonly options: CoordinatorRunOptions;\n readonly runId: string;\n readonly turn: number;\n readonly providerCallId: string;\n readonly providerCallIndex: number;\n readonly providerCallSlots: ReplayTraceProviderCall[];\n readonly toolExecutor: RuntimeToolExecutor;\n readonly toolAvailability: JsonObject;\n readonly totalCost: CostSummary;\n readonly events: RunEvent[];\n readonly transcript: readonly TranscriptEntry[];\n readonly startedAtMs: number;\n readonly wrapUpHint: ReturnType<typeof createWrapUpHintController>;\n readonly emit: (event: RunEvent) => void;\n}\n\ninterface CoordinatorWorkerTurnResult {\n readonly agent: AgentSpec;\n readonly input: string;\n readonly response: ModelResponse;\n readonly decision: ReturnType<typeof parseAgentDecision>;\n readonly toolCalls: Awaited<ReturnType<typeof executeModelResponseToolRequests>>;\n readonly turnCost: CostSummary;\n}\n\nasync function runCoordinatorWorkerTurn(turn: CoordinatorWorkerTurnOptions): Promise<CoordinatorWorkerTurnResult> {\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n const request: ModelRequest = {\n temperature: turn.options.temperature,\n ...(turn.options.signal !== undefined ? { signal: turn.options.signal } : {}),\n metadata: {\n runId: turn.runId,\n protocol: \"coordinator\",\n agentId: turn.agent.id,\n role: turn.agent.role,\n coordinatorAgentId: turn.coordinator.id,\n tier: turn.options.tier,\n phase: \"worker\",\n ...turn.toolAvailability\n },\n messages: turn.wrapUpHint.inject(\n [\n {\n role: \"system\",\n content: buildSystemPrompt(turn.agent, turn.coordinator)\n },\n {\n role: \"user\",\n content: turn.input\n }\n ],\n {\n runId: turn.runId,\n protocol: \"coordinator\",\n cost: turn.totalCost,\n events: turn.events,\n transcript: turn.transcript,\n iteration: turn.turn - 1,\n elapsedMs: elapsedMs(turn.startedAtMs)\n }\n )\n };\n const response = await generateModelTurn({\n model: turn.options.model,\n request,\n runId: turn.runId,\n agent: turn.agent,\n input: turn.input,\n emit: turn.emit,\n callId: turn.providerCallId,\n onProviderCall(call): void {\n turn.providerCallSlots[turn.providerCallIndex] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: turn.toolExecutor,\n agentId: turn.agent.id,\n role: turn.agent.role,\n turn: turn.turn,\n metadata: {\n phase: \"worker\"\n }\n });\n throwIfAborted(turn.options.signal, turn.options.model.id);\n\n return {\n agent: turn.agent,\n input: turn.input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n}\n\nfunction buildSystemPrompt(agent: AgentSpec, coordinator: AgentSpec | undefined): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n const coordinatorText =\n coordinator && agent.id === coordinator.id\n ? \"You are the coordinator: assign work, integrate worker contributions, and produce the final answer.\"\n : `You are a worker managed by coordinator ${coordinator?.id ?? \"unknown\"}.`;\n return `You are ${agent.id}, acting as ${agent.role} in a Coordinator multi-agent protocol. ${coordinatorText}${instruction}`;\n}\n\nfunction buildCoordinatorPlanInput(intent: string, coordinator: AgentSpec): string {\n return `Mission: ${intent}\\nCoordinator ${coordinator.id}: assign the work, name the plan, and provide the first contribution.`;\n}\n\nfunction buildWorkerInput(\n intent: string,\n transcript: readonly TranscriptEntry[],\n coordinator: AgentSpec\n): string {\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nCoordinator: ${coordinator.id}\\nPrior contributions:\\n${prior}\\n\\nFollow the coordinator-managed plan and provide your assigned contribution.`;\n}\n\nfunction buildFinalSynthesisInput(\n intent: string,\n transcript: readonly TranscriptEntry[],\n coordinator: AgentSpec\n): string {\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nCoordinator: ${coordinator.id}\\nPrior contributions:\\n${prior}\\n\\nSynthesize the final answer as the coordinator.`;\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n JsonObject,\n JsonValue,\n SequentialProtocolConfig,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost,\n nextProviderCallId\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { isParticipatingDecision, parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop, warnOnProtocolTerminationMisconfiguration } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\nimport { createWrapUpHintController } from \"./wrap-up.js\";\n\ninterface SequentialRunOptions {\n readonly intent: string;\n readonly protocol: SequentialProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly wrapUpHint?: DogpileOptions[\"wrapUpHint\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runSequential(options: SequentialRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n const wrapUpHint = createWrapUpHintController({\n protocol: options.protocol,\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {})\n });\n\n warnOnProtocolTerminationMisconfiguration(options.protocol, options.terminate);\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(\n createReplayTraceProtocolDecision(\"sequential\", event, events.length - 1, decisionOptions)\n );\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n for (const [index, agent] of activeAgents.entries()) {\n if (stopIfNeeded()) {\n break;\n }\n\n const turn = index + 1;\n const input = buildSequentialInput(options.intent, transcript);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"sequential\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n turn,\n ...toolAvailability\n },\n messages: wrapUpHint.inject(\n [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ],\n {\n runId,\n protocol: \"sequential\",\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n }\n )\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: nextProviderCallId(runId, providerCalls),\n onProviderCall(call): void {\n providerCalls.push(call);\n }\n });\n const turnCost = responseCost(response);\n totalCost = addCost(totalCost, turnCost);\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn\n });\n throwIfAborted(options.signal, options.model.id);\n\n transcript.push({\n agentId: agent.id,\n role: agent.role,\n input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n ...(toolCalls.length > 0 ? { toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role,\n input,\n output: response.text,\n ...(decision !== undefined ? { decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn,\n transcriptEntryCount: transcript.length\n });\n\n if (stopIfNeeded()) {\n break;\n }\n }\n\n const output = [...transcript].reverse().find((entry) => isParticipatingDecision(entry.decision))?.output ?? \"\";\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"sequential\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? events[0] ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"sequential\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(\n options.terminate,\n wrapUpHint.context({\n runId,\n protocol: \"sequential\",\n protocolConfig: options.protocol,\n protocolIteration: transcript.length,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n })\n );\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Sequential multi-agent protocol.${instruction}`;\n}\n\nfunction buildSequentialInput(intent: string, transcript: readonly TranscriptEntry[]): string {\n if (transcript.length === 0) {\n return `Mission: ${intent}\\nProvide your contribution.`;\n }\n\n const prior = transcript\n .map((entry) => `${entry.role} (${entry.agentId}): ${entry.output}`)\n .join(\"\\n\\n\");\n return `Mission: ${intent}\\n\\nPrior contributions:\\n${prior}\\n\\nContinue the sequence with a useful next contribution.`;\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n","import type {\n AgentSpec,\n ConfiguredModelProvider,\n CostSummary,\n DogpileOptions,\n JsonObject,\n JsonValue,\n ModelRequest,\n ModelResponse,\n ReplayTraceProtocolDecision,\n ReplayTraceProviderCall,\n RuntimeTool,\n RunEvent,\n RunResult,\n SharedProtocolConfig,\n TerminationCondition,\n TerminationStopRecord,\n Tier,\n TranscriptEntry\n} from \"../types.js\";\nimport {\n addCost,\n createReplayTraceBudget,\n createReplayTraceBudgetStateChanges,\n createReplayTraceFinalOutput,\n createReplayTraceProtocolDecision,\n createReplayTraceRunInputs,\n createReplayTraceSeed,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n createTranscriptLink,\n emptyCost\n} from \"./defaults.js\";\nimport { throwIfAborted } from \"./cancellation.js\";\nimport { parseAgentDecision } from \"./decisions.js\";\nimport { generateModelTurn } from \"./model.js\";\nimport { evaluateTerminationStop, warnOnProtocolTerminationMisconfiguration } from \"./termination.js\";\nimport { createRuntimeToolExecutor, executeModelResponseToolRequests, runtimeToolAvailability } from \"./tools.js\";\nimport { createWrapUpHintController } from \"./wrap-up.js\";\n\ninterface SharedRunOptions {\n readonly intent: string;\n readonly protocol: SharedProtocolConfig;\n readonly tier: Tier;\n readonly model: ConfiguredModelProvider;\n readonly agents: readonly AgentSpec[];\n readonly tools: readonly RuntimeTool<JsonObject, JsonValue>[];\n readonly temperature: number;\n readonly budget?: DogpileOptions[\"budget\"];\n readonly seed?: string | number;\n readonly signal?: AbortSignal;\n readonly terminate?: TerminationCondition;\n readonly wrapUpHint?: DogpileOptions[\"wrapUpHint\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\nexport async function runShared(options: SharedRunOptions): Promise<RunResult> {\n const runId = createRunId();\n const events: RunEvent[] = [];\n const transcript: TranscriptEntry[] = [];\n const protocolDecisions: ReplayTraceProtocolDecision[] = [];\n const providerCalls: ReplayTraceProviderCall[] = [];\n let totalCost = emptyCost();\n const sharedState = options.protocol.organizationalMemory ?? \"\";\n const maxTurns = options.protocol.maxTurns ?? options.agents.length;\n const activeAgents = options.agents.slice(0, maxTurns);\n const startedAtMs = nowMs();\n let stopped = false;\n let termination: TerminationStopRecord | undefined;\n const wrapUpHint = createWrapUpHintController({\n protocol: options.protocol,\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {})\n });\n\n warnOnProtocolTerminationMisconfiguration(options.protocol, options.terminate);\n\n const emit = (event: RunEvent): void => {\n events.push(event);\n options.emit?.(event);\n };\n\n const recordProtocolDecision = (\n event: RunEvent,\n decisionOptions?: Parameters<typeof createReplayTraceProtocolDecision>[3]\n ): void => {\n protocolDecisions.push(createReplayTraceProtocolDecision(\"shared\", event, events.length - 1, decisionOptions));\n };\n\n const toolExecutor = createRuntimeToolExecutor({\n runId,\n protocol: \"shared\",\n tier: options.tier,\n tools: options.tools,\n emit(event): void {\n emit(event);\n recordProtocolDecision(event);\n },\n getTrace: () => ({ events, transcript }),\n ...(options.signal !== undefined ? { abortSignal: options.signal } : {})\n });\n const toolAvailability = runtimeToolAvailability(toolExecutor.tools);\n\n throwIfAborted(options.signal, options.model.id);\n\n for (const agent of activeAgents) {\n const event: RunEvent = {\n type: \"role-assignment\",\n runId,\n at: new Date().toISOString(),\n agentId: agent.id,\n role: agent.role\n };\n emit(event);\n recordProtocolDecision(event);\n }\n\n if (!stopIfNeeded()) {\n const providerCallSlots: ReplayTraceProviderCall[] = [];\n const turnResults = await Promise.all(\n activeAgents.map(async (agent, index) => {\n const turn = index + 1;\n const input = buildSharedInput(options.intent, sharedState, turn);\n const request: ModelRequest = {\n temperature: options.temperature,\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n metadata: {\n runId,\n protocol: \"shared\",\n agentId: agent.id,\n role: agent.role,\n tier: options.tier,\n turn,\n ...toolAvailability\n },\n messages: wrapUpHint.inject(\n [\n {\n role: \"system\",\n content: buildSystemPrompt(agent)\n },\n {\n role: \"user\",\n content: input\n }\n ],\n {\n runId,\n protocol: \"shared\",\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n }\n )\n };\n const response = await generateModelTurn({\n model: options.model,\n request,\n runId,\n agent,\n input,\n emit,\n callId: providerCallIdFor(runId, providerCalls.length + index + 1),\n onProviderCall(call): void {\n providerCallSlots[index] = call;\n }\n });\n const decision = parseAgentDecision(response.text);\n const toolCalls = await executeModelResponseToolRequests({\n response,\n executor: toolExecutor,\n agentId: agent.id,\n role: agent.role,\n turn\n });\n throwIfAborted(options.signal, options.model.id);\n\n return {\n agent,\n turn,\n input,\n response,\n decision,\n toolCalls,\n turnCost: responseCost(response)\n };\n })\n );\n providerCalls.push(...providerCallSlots.filter((call): call is ReplayTraceProviderCall => call !== undefined));\n\n for (const result of turnResults) {\n totalCost = addCost(totalCost, result.turnCost);\n transcript.push({\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n ...(result.toolCalls.length > 0 ? { toolCalls: result.toolCalls } : {})\n });\n\n const event: RunEvent = {\n type: \"agent-turn\",\n runId,\n at: new Date().toISOString(),\n agentId: result.agent.id,\n role: result.agent.role,\n input: result.input,\n output: result.response.text,\n ...(result.decision !== undefined ? { decision: result.decision } : {}),\n cost: totalCost\n };\n emit(event);\n recordProtocolDecision(event, {\n turn: result.turn,\n transcriptEntryCount: transcript.length\n });\n }\n stopIfNeeded();\n }\n\n const output = synthesizeSharedOutput(transcript);\n throwIfAborted(options.signal, options.model.id);\n const final: RunEvent = {\n type: \"final\",\n runId,\n at: new Date().toISOString(),\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript),\n ...(termination !== undefined ? { termination } : {})\n };\n emit(final);\n recordProtocolDecision(final, {\n transcriptEntryCount: transcript.length\n });\n const finalEvent = events.at(-1);\n\n return {\n output,\n eventLog: createRunEventLog(runId, \"shared\", events),\n trace: {\n schemaVersion: \"1.0\",\n runId,\n protocol: \"shared\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n inputs: createReplayTraceRunInputs({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n modelProviderId: options.model.id,\n agents: activeAgents,\n temperature: options.temperature\n }),\n budget: createReplayTraceBudget({\n tier: options.tier,\n ...(options.budget ? { caps: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {})\n }),\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n seed: createReplayTraceSeed(options.seed),\n protocolDecisions,\n providerCalls,\n finalOutput: createReplayTraceFinalOutput(output, finalEvent ?? {\n type: \"final\",\n runId,\n at: \"\",\n output,\n cost: totalCost,\n transcript: createTranscriptLink(transcript)\n }),\n events,\n transcript\n },\n transcript,\n usage: createRunUsage(totalCost),\n metadata: createRunMetadata({\n runId,\n protocol: \"shared\",\n tier: options.tier,\n modelProviderId: options.model.id,\n agentsUsed: activeAgents,\n events\n }),\n accounting: createRunAccounting({\n tier: options.tier,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.terminate ? { termination: options.terminate } : {}),\n cost: totalCost,\n events\n }),\n cost: totalCost\n };\n\n function stopIfNeeded(): boolean {\n throwIfAborted(options.signal, options.model.id);\n\n if (stopped || !options.terminate) {\n return stopped;\n }\n\n const stopRecord = evaluateTerminationStop(\n options.terminate,\n wrapUpHint.context({\n runId,\n protocol: \"shared\",\n protocolConfig: options.protocol,\n protocolIteration: transcript.length,\n cost: totalCost,\n events,\n transcript,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs)\n })\n );\n\n if (!stopRecord) {\n return false;\n }\n\n stopped = true;\n termination = stopRecord;\n if (stopRecord.reason === \"budget\") {\n emitBudgetStop(stopRecord);\n }\n return true;\n }\n\n function emitBudgetStop(record: TerminationStopRecord): void {\n const event: RunEvent = {\n type: \"budget-stop\",\n runId,\n at: new Date().toISOString(),\n reason: record.budgetReason ?? \"cost\",\n cost: totalCost,\n iteration: transcript.length,\n elapsedMs: elapsedMs(startedAtMs),\n detail: record.detail ?? {}\n };\n emit(event);\n recordProtocolDecision(event, {\n transcriptEntryCount: transcript.length\n });\n }\n}\n\nfunction buildSystemPrompt(agent: AgentSpec): string {\n const instruction = agent.instructions ? `\\nInstructions: ${agent.instructions}` : \"\";\n return `You are ${agent.id}, acting as ${agent.role} in a Shared multi-agent protocol. Read the shared state, update it with your best contribution, and preserve useful prior work.${instruction}`;\n}\n\nfunction buildSharedInput(intent: string, sharedState: string, turn: number): string {\n const state = sharedState ? sharedState : \"(empty)\";\n return `Mission: ${intent}\\nShared turn ${turn}: read the shared state and return an improved shared-state update.\\n\\nShared state:\\n${state}`;\n}\n\nfunction synthesizeSharedOutput(transcript: readonly TranscriptEntry[]): string {\n return transcript.map((entry) => `${entry.role}:${entry.agentId} => ${entry.output}`).join(\"\\n\");\n}\n\nfunction responseCost(response: ModelResponse): CostSummary {\n return {\n usd: response.costUsd ?? 0,\n inputTokens: response.usage?.inputTokens ?? 0,\n outputTokens: response.usage?.outputTokens ?? 0,\n totalTokens: response.usage?.totalTokens ?? 0\n };\n}\n\nfunction createRunId(): string {\n const random = globalThis.crypto?.randomUUID?.();\n return random ?? `run-${Date.now().toString(36)}`;\n}\n\nfunction nowMs(): number {\n return globalThis.performance?.now() ?? Date.now();\n}\n\nfunction elapsedMs(startedAtMs: number): number {\n return Math.max(0, nowMs() - startedAtMs);\n}\n\nfunction providerCallIdFor(runId: string, oneBasedIndex: number): string {\n return `${runId}:provider-call:${oneBasedIndex}`;\n}\n","import { DogpileError } from \"../types.js\";\nimport type {\n BudgetTier,\n DogpileOptions,\n Engine,\n EngineOptions,\n FinalEvent,\n JsonObject,\n JsonValue,\n ProtocolSelection,\n RunEvaluation,\n RunEvent,\n RunResult,\n StreamErrorEvent,\n StreamEvent,\n StreamEventSubscriber,\n StreamHandle,\n StreamHandleStatus,\n Trace\n} from \"../types.js\";\nimport { runBroadcast } from \"./broadcast.js\";\nimport { runCoordinator } from \"./coordinator.js\";\nimport {\n createReplayTraceFinalOutput,\n createReplayTraceBudgetStateChanges,\n canonicalizeRunResult,\n canonicalizeSerializable,\n createRunAccounting,\n createRunEventLog,\n createRunMetadata,\n createRunUsage,\n defaultAgents,\n normalizeProtocol,\n orderAgentsForTemperature,\n tierTemperature\n} from \"./defaults.js\";\nimport { runSequential } from \"./sequential.js\";\nimport { runShared } from \"./shared.js\";\nimport { createAbortErrorFromSignal, createTimeoutError } from \"./cancellation.js\";\nimport { budget as budgetCondition } from \"./termination.js\";\nimport { validateDogpileOptions, validateEngineOptions, validateMissionIntent } from \"./validation.js\";\n\nconst defaultHighLevelProtocol = \"sequential\";\nconst defaultHighLevelTier = \"balanced\";\n\ntype NormalizedDogpileOptions = Omit<DogpileOptions, \"protocol\" | \"tier\"> & {\n readonly protocol: ProtocolSelection;\n readonly tier: BudgetTier;\n};\n\n/**\n * Create a reusable low-level protocol engine.\n *\n * @remarks\n * Use this escape hatch to hold protocol, tier, model, agents, and budget caps\n * constant across repeated missions. Most application code can call\n * {@link run}, {@link stream}, or {@link Dogpile.pile} directly.\n *\n * The returned engine is stateless between calls: each `run()` or `stream()`\n * invocation produces its own serializable trace, event log, and transcript.\n */\nexport function createEngine(options: EngineOptions): Engine {\n validateEngineOptions(options);\n\n const protocol = normalizeProtocol(options.protocol);\n const tools = options.tools ?? [];\n const temperature = options.temperature ?? tierTemperature(options.tier);\n const agents = orderAgentsForTemperature(options.agents ?? defaultAgents(), temperature, options.seed);\n const terminate = options.terminate ?? (options.budget ? conditionFromBudget(options.budget) : undefined);\n\n return {\n run(intent: string): Promise<RunResult> {\n validateMissionIntent(intent);\n\n return runNonStreamingProtocol({\n intent,\n protocol,\n tier: options.tier,\n model: options.model,\n agents,\n tools,\n temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(terminate ? { terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {}),\n ...(options.evaluate ? { evaluate: options.evaluate } : {})\n });\n },\n\n stream(intent: string): StreamHandle {\n validateMissionIntent(intent);\n\n const pendingEvents: StreamEvent[] = [];\n const pendingResolvers: Array<(value: IteratorResult<StreamEvent>) => void> = [];\n const emittedEvents: StreamEvent[] = [];\n const subscribers = new Set<StreamEventSubscriber>();\n const abortController = new AbortController();\n const timeoutLifecycle = createTimeoutAbortLifecycle({\n abortController,\n timeoutMs: runtimeTimeoutMs({ budget: options.budget, terminate }),\n providerId: options.model.id\n });\n const abortRace = createAbortRace(abortController.signal, options.model.id);\n let complete = false;\n let lastRunId = \"\";\n let pendingFinalEvent: FinalEvent | undefined;\n let status: StreamHandleStatus = \"running\";\n let resolveResult!: (result: RunResult) => void;\n let rejectResult!: (error: unknown) => void;\n let removeCallerAbortListener = (): void => {};\n\n const result = new Promise<RunResult>((resolve, reject) => {\n resolveResult = resolve;\n rejectResult = reject;\n });\n removeCallerAbortListener = wireCallerAbortSignal(options.signal, abortController, cancelRun);\n void execute();\n\n return {\n get status(): StreamHandleStatus {\n return status;\n },\n result,\n cancel(): void {\n cancelRun();\n },\n subscribe(subscriber: StreamEventSubscriber) {\n subscribers.add(subscriber);\n\n for (const event of emittedEvents) {\n subscriber(event);\n }\n\n return {\n unsubscribe(): void {\n subscribers.delete(subscriber);\n }\n };\n },\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n return {\n next(): Promise<IteratorResult<StreamEvent>> {\n const event = pendingEvents.shift();\n if (event) {\n return Promise.resolve({ done: false, value: event });\n }\n if (complete) {\n return Promise.resolve({ done: true, value: undefined });\n }\n return new Promise<IteratorResult<StreamEvent>>((resolve) => {\n pendingResolvers.push(resolve);\n });\n }\n };\n }\n };\n\n async function execute(): Promise<void> {\n if (status !== \"running\") {\n return;\n }\n\n try {\n const baseResult = await abortRace.run(runProtocol({\n intent,\n protocol,\n tier: options.tier,\n model: options.model,\n agents,\n tools,\n temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n signal: abortController.signal,\n ...(terminate ? { terminate } : {}),\n emit(event: RunEvent): void {\n if (status !== \"running\") {\n return;\n }\n\n lastRunId = event.runId;\n if (event.type === \"final\") {\n pendingFinalEvent = event;\n return;\n }\n publish(event);\n }\n }));\n if (status !== \"running\") {\n return;\n }\n\n const finalizedResult = await abortRace.run(applyRunEvaluation(baseResult, options.evaluate));\n if (status !== \"running\") {\n return;\n }\n\n const finalEvent = finalizedResult.trace.events.at(-1);\n if (finalEvent?.type === \"final\") {\n publish(finalEvent);\n } else if (pendingFinalEvent) {\n publish(pendingFinalEvent);\n }\n status = \"completed\";\n closeStream();\n resolveResult(finalizedResult);\n } catch (error: unknown) {\n if (isStreamHandleStatus(status, \"cancelled\")) {\n return;\n }\n\n const runtimeError = timeoutLifecycle.translateError(error);\n status = isCancellationError(runtimeError) ? \"cancelled\" : \"failed\";\n publish(createStreamErrorEvent(runtimeError, lastRunId));\n closeStream();\n rejectResult(runtimeError);\n }\n }\n\n function cancelRun(cause?: unknown): void {\n if (status !== \"running\") {\n return;\n }\n\n const error = createStreamCancellationError(options.model.id, cause);\n status = \"cancelled\";\n abortController.abort(error);\n publish(createStreamErrorEvent(error, lastRunId));\n closeStream();\n rejectResult(error);\n }\n\n function closeStream(): void {\n if (complete) {\n return;\n }\n\n complete = true;\n removeCallerAbortListener();\n timeoutLifecycle.cleanup();\n abortRace.cleanup();\n subscribers.clear();\n for (const resolver of pendingResolvers.splice(0)) {\n resolver({ done: true, value: undefined });\n }\n }\n\n function publish(event: StreamEvent): void {\n if (complete) {\n return;\n }\n\n const canonicalEvent = canonicalizeSerializable(event);\n emittedEvents.push(canonicalEvent);\n\n for (const subscriber of subscribers) {\n try {\n subscriber(canonicalEvent);\n } catch {\n // Subscriber failures should not cancel the underlying SDK run.\n }\n }\n\n const resolver = pendingResolvers.shift();\n if (resolver) {\n resolver({ done: false, value: canonicalEvent });\n return;\n }\n pendingEvents.push(canonicalEvent);\n }\n }\n };\n}\n\nfunction isStreamHandleStatus(status: StreamHandleStatus, expected: StreamHandleStatus): boolean {\n return status === expected;\n}\n\nfunction conditionFromBudget(budget: NonNullable<EngineOptions[\"budget\"]>): ReturnType<typeof budgetCondition> {\n return budgetCondition({\n ...(budget.maxUsd !== undefined ? { maxUsd: budget.maxUsd } : {}),\n ...(budget.maxTokens !== undefined ? { maxTokens: budget.maxTokens } : {}),\n ...(budget.maxIterations !== undefined ? { maxIterations: budget.maxIterations } : {}),\n ...(budget.timeoutMs !== undefined ? { timeoutMs: budget.timeoutMs } : {})\n });\n}\n\ninterface AbortLifecycle {\n readonly signal: AbortSignal | undefined;\n run<T>(operation: Promise<T>): Promise<T>;\n translateError(error: unknown): unknown;\n cleanup(): void;\n}\n\ninterface TimeoutAbortLifecycle {\n translateError(error: unknown): unknown;\n cleanup(): void;\n}\n\nfunction createNonStreamingAbortLifecycle(options: {\n readonly callerSignal?: AbortSignal | undefined;\n readonly timeoutMs?: number | undefined;\n readonly providerId: string;\n}): AbortLifecycle {\n if (options.timeoutMs === undefined) {\n return {\n signal: options.callerSignal,\n async run<T>(operation: Promise<T>): Promise<T> {\n return await operation;\n },\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {}\n };\n }\n\n const abortController = new AbortController();\n const timeoutLifecycle = createTimeoutAbortLifecycle({\n abortController,\n timeoutMs: options.timeoutMs,\n providerId: options.providerId\n });\n const abortRace = createAbortRace(abortController.signal, options.providerId);\n const removeCallerAbortListener = wireCallerAbortSignal(options.callerSignal, abortController, () => {\n abortController.abort(readAbortSignalReason(options.callerSignal));\n });\n\n return {\n signal: abortController.signal,\n async run<T>(operation: Promise<T>): Promise<T> {\n return await abortRace.run(operation);\n },\n translateError(error: unknown): unknown {\n return timeoutLifecycle.translateError(error);\n },\n cleanup(): void {\n timeoutLifecycle.cleanup();\n abortRace.cleanup();\n removeCallerAbortListener();\n }\n };\n}\n\nfunction createTimeoutAbortLifecycle(options: {\n readonly abortController: AbortController;\n readonly timeoutMs?: number | undefined;\n readonly providerId: string;\n}): TimeoutAbortLifecycle {\n if (options.timeoutMs === undefined) {\n return {\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {}\n };\n }\n\n const timeoutError = createTimeoutError(options.providerId, options.timeoutMs);\n const timeoutId = setTimeout(() => {\n options.abortController.abort(timeoutError);\n }, options.timeoutMs);\n\n return {\n translateError(error: unknown): unknown {\n return options.abortController.signal.reason === timeoutError ? timeoutError : error;\n },\n cleanup(): void {\n clearTimeout(timeoutId);\n }\n };\n}\n\nfunction createAbortRace(signal: AbortSignal, providerId: string): AbortLifecycle {\n let cleanupAbortListener = (): void => {};\n\n return {\n signal,\n async run<T>(operation: Promise<T>): Promise<T> {\n if (signal.aborted) {\n throw createAbortErrorFromSignal(signal, providerId);\n }\n\n const abortPromise = new Promise<never>((_, reject) => {\n const abortHandler = (): void => {\n cleanupAbortListener();\n reject(createAbortErrorFromSignal(signal, providerId));\n };\n\n cleanupAbortListener = (): void => {\n signal.removeEventListener(\"abort\", abortHandler);\n };\n signal.addEventListener(\"abort\", abortHandler, { once: true });\n });\n\n try {\n return await Promise.race([operation, abortPromise]);\n } finally {\n cleanupAbortListener();\n cleanupAbortListener = (): void => {};\n }\n },\n translateError(error: unknown): unknown {\n return error;\n },\n cleanup(): void {\n cleanupAbortListener();\n cleanupAbortListener = (): void => {};\n }\n };\n}\n\nfunction runtimeTimeoutMs(options: {\n readonly budget?: EngineOptions[\"budget\"] | undefined;\n readonly terminate?: EngineOptions[\"terminate\"] | undefined;\n}): number | undefined {\n const budgetTimeoutMs = options.budget?.timeoutMs;\n const terminationTimeoutMs = timeoutMsFromTermination(options.terminate);\n\n if (budgetTimeoutMs === undefined) {\n return terminationTimeoutMs;\n }\n if (terminationTimeoutMs === undefined) {\n return budgetTimeoutMs;\n }\n return Math.min(budgetTimeoutMs, terminationTimeoutMs);\n}\n\nfunction timeoutMsFromTermination(condition: EngineOptions[\"terminate\"] | undefined): number | undefined {\n if (!condition) {\n return undefined;\n }\n\n switch (condition.kind) {\n case \"budget\":\n return condition.timeoutMs;\n case \"firstOf\":\n return condition.conditions.reduce<number | undefined>((current, child) => {\n const childTimeoutMs = timeoutMsFromTermination(child);\n if (childTimeoutMs === undefined) {\n return current;\n }\n return current === undefined ? childTimeoutMs : Math.min(current, childTimeoutMs);\n }, undefined);\n case \"convergence\":\n case \"judge\":\n return undefined;\n }\n}\n\nfunction readAbortSignalReason(signal: AbortSignal | undefined): unknown {\n return signal?.aborted ? signal.reason : undefined;\n}\n\nfunction createStreamErrorEvent(error: unknown, runId: string): StreamErrorEvent {\n if (DogpileError.isInstance(error)) {\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: error.name,\n message: error.message,\n detail: dogpileErrorStreamDetail(error)\n };\n }\n\n if (error instanceof Error) {\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: error.name,\n message: error.message\n };\n }\n\n return {\n type: \"error\",\n runId,\n at: new Date().toISOString(),\n name: \"Error\",\n message: String(error)\n };\n}\n\nfunction dogpileErrorStreamDetail(error: DogpileError): JsonObject {\n const detail: Record<string, JsonValue> = {\n code: error.code\n };\n\n if (error.providerId !== undefined) {\n detail.providerId = error.providerId;\n }\n if (error.retryable !== undefined) {\n detail.retryable = error.retryable;\n }\n if (error.detail !== undefined) {\n for (const [key, value] of Object.entries(error.detail)) {\n detail[key] = value;\n }\n }\n\n return detail;\n}\n\ninterface RunProtocolOptions {\n readonly intent: string;\n readonly protocol: ReturnType<typeof normalizeProtocol>;\n readonly tier: EngineOptions[\"tier\"];\n readonly model: EngineOptions[\"model\"];\n readonly agents: readonly NonNullable<EngineOptions[\"agents\"]>[number][];\n readonly tools: NonNullable<EngineOptions[\"tools\"]>;\n readonly temperature: number;\n readonly budget?: EngineOptions[\"budget\"];\n readonly seed?: EngineOptions[\"seed\"];\n readonly signal?: EngineOptions[\"signal\"];\n readonly terminate?: EngineOptions[\"terminate\"];\n readonly wrapUpHint?: EngineOptions[\"wrapUpHint\"];\n readonly emit?: (event: RunEvent) => void;\n}\n\ntype NonStreamingProtocolOptions = Omit<RunProtocolOptions, \"emit\"> & Pick<EngineOptions, \"evaluate\">;\n\nasync function runNonStreamingProtocol(options: NonStreamingProtocolOptions): Promise<RunResult> {\n const abortLifecycle = createNonStreamingAbortLifecycle({\n callerSignal: options.signal,\n timeoutMs: runtimeTimeoutMs(options),\n providerId: options.model.id\n });\n\n try {\n const emittedEvents: RunEvent[] = [];\n const result = await abortLifecycle.run(runProtocol({\n ...options,\n ...(abortLifecycle.signal !== undefined ? { signal: abortLifecycle.signal } : {}),\n emit(event: RunEvent): void {\n emittedEvents.push(event);\n }\n }));\n const events = emittedEvents.length > 0 ? emittedEvents : result.trace.events;\n const trace = {\n ...result.trace,\n events,\n budgetStateChanges: createReplayTraceBudgetStateChanges(events),\n finalOutput: createReplayTraceFinalOutput(result.output, events.at(-1) ?? result.trace.events.at(-1)!)\n };\n\n const runResult = {\n ...result,\n accounting: createRunAccounting({\n tier: trace.tier,\n ...(trace.budget.caps ? { budget: trace.budget.caps } : {}),\n ...(trace.budget.termination ? { termination: trace.budget.termination } : {}),\n cost: result.cost,\n events\n }),\n eventLog: createRunEventLog(trace.runId, trace.protocol, events),\n trace\n };\n return canonicalizeRunResult(await abortLifecycle.run(applyRunEvaluation(runResult, options.evaluate)));\n } catch (error: unknown) {\n throw abortLifecycle.translateError(error);\n } finally {\n abortLifecycle.cleanup();\n }\n}\n\nasync function applyRunEvaluation(\n result: RunResult,\n evaluate: EngineOptions[\"evaluate\"]\n): Promise<RunResult> {\n if (!evaluate) {\n return canonicalizeRunResult(result);\n }\n\n const evaluation = await evaluate(result);\n const events = result.trace.events.map((event, index): RunEvent => {\n if (index !== result.trace.events.length - 1 || event.type !== \"final\") {\n return event;\n }\n\n return finalEventWithEvaluation(event, evaluation);\n });\n const trace = {\n ...result.trace,\n events\n };\n\n return canonicalizeRunResult({\n ...result,\n quality: evaluation.quality,\n evaluation,\n trace,\n eventLog: createRunEventLog(trace.runId, trace.protocol, events)\n });\n}\n\nfunction finalEventWithEvaluation(event: FinalEvent, evaluation: RunEvaluation): FinalEvent {\n return {\n ...event,\n quality: evaluation.quality,\n evaluation\n };\n}\n\nfunction runProtocol(options: RunProtocolOptions): Promise<RunResult> {\n switch (options.protocol.kind) {\n case \"sequential\":\n return runSequential({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"broadcast\":\n return runBroadcast({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"coordinator\":\n return runCoordinator({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n case \"shared\":\n return runShared({\n intent: options.intent,\n protocol: options.protocol,\n tier: options.tier,\n model: options.model,\n agents: options.agents,\n tools: options.tools,\n temperature: options.temperature,\n ...(options.budget ? { budget: options.budget } : {}),\n ...(options.seed !== undefined ? { seed: options.seed } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.terminate ? { terminate: options.terminate } : {}),\n ...(options.wrapUpHint ? { wrapUpHint: options.wrapUpHint } : {}),\n ...(options.emit ? { emit: options.emit } : {})\n });\n }\n}\n\n/**\n * Run a multi-agent workflow in a single call.\n *\n * @remarks\n * Supply a mission through `intent` and provide a configured model provider.\n * Omitted high-level controls default to Sequential coordination and the\n * `balanced` tier. The returned\n * {@link RunResult} contains the final `output`, a JSON-serializable `trace`,\n * direct `transcript` access, aggregate `cost`, and optional `quality`.\n *\n * Use {@link createEngine} when a research harness needs to reuse normalized\n * protocol/model/agent settings across many missions.\n */\nexport function run(options: DogpileOptions): Promise<RunResult> {\n validateDogpileOptions(options);\n\n const { intent, ...engineOptions } = withHighLevelDefaults(options);\n return createEngine(engineOptions).run(intent);\n}\n\n/**\n * Stream a multi-agent workflow and await the final result.\n *\n * @remarks\n * The returned handle is an async iterable of {@link RunEvent} values with a\n * `result` promise for the same {@link RunResult} shape returned by\n * {@link run}. This supports live event logs and trace UIs without requiring\n * SDK-managed storage.\n *\n * Streaming and final traces use the same event shapes, so callers can render\n * progress live and persist the completed trace without translation.\n */\nexport function stream(options: DogpileOptions): StreamHandle {\n validateDogpileOptions(options);\n\n const { intent, ...engineOptions } = withHighLevelDefaults(options);\n return createEngine(engineOptions).stream(intent);\n}\n\n/**\n * Rehydrate the public result shape from a saved completed trace artifact.\n *\n * @remarks\n * This is the caller-facing replay entrypoint for persisted traces. It does\n * not call the model provider or require SDK-owned storage; it reconstructs\n * the ergonomic {@link RunResult} wrapper from the JSON-serializable\n * {@link Trace} returned by a previous `run()`, `stream()`, or\n * `Dogpile.pile()` call.\n */\nexport function replay(trace: Trace): RunResult {\n const cost = trace.finalOutput.cost;\n const lastEvent = trace.events.at(-1);\n const baseResult = {\n output: trace.finalOutput.output,\n eventLog: createRunEventLog(trace.runId, trace.protocol, trace.events),\n trace,\n transcript: trace.transcript,\n usage: createRunUsage(cost),\n metadata: createRunMetadata({\n runId: trace.runId,\n protocol: trace.protocol,\n tier: trace.tier,\n modelProviderId: trace.modelProviderId,\n agentsUsed: trace.agentsUsed,\n events: trace.events\n }),\n accounting: createRunAccounting({\n tier: trace.tier,\n ...(trace.budget.caps ? { budget: trace.budget.caps } : {}),\n ...(trace.budget.termination ? { termination: trace.budget.termination } : {}),\n cost,\n events: trace.events\n }),\n cost\n };\n\n if (lastEvent?.type !== \"final\") {\n return baseResult;\n }\n\n return {\n ...baseResult,\n ...(lastEvent.quality !== undefined ? { quality: lastEvent.quality } : {}),\n ...(lastEvent.evaluation !== undefined ? { evaluation: lastEvent.evaluation } : {})\n };\n}\n\n/**\n * Replay a saved completed trace as a stream without invoking a model provider.\n *\n * @remarks\n * This is the streaming counterpart to {@link replay}. It yields the exact\n * saved {@link Trace.events} in order and resolves {@link StreamHandle.result}\n * to the rehydrated {@link RunResult}. Since all data comes from the trace,\n * replay remains storage-free and provider-free.\n */\nexport function replayStream(trace: Trace): StreamHandle {\n const result = Promise.resolve(replay(trace));\n\n return {\n get status(): StreamHandleStatus {\n return \"completed\";\n },\n result,\n cancel(): void {\n // Replay streams are already completed snapshots, so cancellation is a no-op.\n },\n subscribe(subscriber: StreamEventSubscriber) {\n for (const event of trace.events) {\n subscriber(event);\n }\n\n return {\n unsubscribe(): void {\n // Replay subscriptions are finite snapshots; there is no live source to detach from.\n }\n };\n },\n [Symbol.asyncIterator](): AsyncIterator<StreamEvent> {\n let index = 0;\n\n return {\n next(): Promise<IteratorResult<StreamEvent>> {\n const event = trace.events[index];\n if (event) {\n index += 1;\n return Promise.resolve({ done: false, value: event });\n }\n\n return Promise.resolve({ done: true, value: undefined });\n }\n };\n }\n };\n}\n\nfunction wireCallerAbortSignal(\n callerSignal: AbortSignal | undefined,\n abortController: AbortController,\n cancelRun: (reason?: unknown) => void\n): () => void {\n if (!callerSignal) {\n return (): void => {};\n }\n\n const cancelFromCaller = (): void => {\n cancelRun(readAbortSignalReason(callerSignal));\n };\n\n if (callerSignal.aborted) {\n cancelFromCaller();\n return (): void => {};\n }\n\n callerSignal.addEventListener(\"abort\", cancelFromCaller, { once: true });\n const remove = (): void => {\n callerSignal.removeEventListener(\"abort\", cancelFromCaller);\n };\n abortController.signal.addEventListener(\"abort\", remove, { once: true });\n return remove;\n}\n\nfunction createStreamCancellationError(providerId: string, cause?: unknown): DogpileError {\n return new DogpileError({\n code: \"aborted\",\n message: \"The operation was aborted.\",\n retryable: false,\n providerId,\n ...(cause !== undefined ? { cause } : {}),\n detail: {\n status: \"cancelled\"\n }\n });\n}\n\nfunction isCancellationError(error: unknown): boolean {\n if (DogpileError.isInstance(error)) {\n return error.code === \"aborted\";\n }\n\n return error instanceof Error && error.name === \"AbortError\";\n}\n\nfunction withHighLevelDefaults(options: DogpileOptions): NormalizedDogpileOptions {\n return {\n ...options,\n protocol: options.protocol ?? defaultHighLevelProtocol,\n tier: options.tier ?? defaultHighLevelTier\n };\n}\n\n/**\n * Branded high-level SDK namespace.\n *\n * `Dogpile.pile()` is the ergonomic caller-facing workflow API. It uses the\n * non-streaming execution path and resolves only after the protocol completes,\n * returning `{ output, eventLog, transcript, usage, metadata, trace, cost,\n * quality }`.\n */\nfunction pile(options: DogpileOptions): Promise<RunResult> {\n return run(options);\n}\n\nexport const Dogpile = {\n pile,\n replay,\n replayStream,\n stream,\n createEngine\n} as const;\n","import { DogpileError } from \"../types.js\";\nimport type {\n ConfiguredModelProvider,\n DogpileErrorCode,\n JsonObject,\n JsonValue,\n ModelFinishReason,\n ModelMessage,\n ModelRequest,\n ModelResponse\n} from \"../types.js\";\n\nconst defaultBaseURL = \"https://api.openai.com/v1\";\nconst defaultPath = \"/chat/completions\";\n\nexport type OpenAICompatibleFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;\n\nexport interface OpenAICompatibleProviderCostContext {\n readonly providerId: string;\n readonly request: ModelRequest;\n readonly response: OpenAICompatibleChatCompletionResponse;\n readonly usage?: ModelResponse[\"usage\"];\n}\n\nexport type OpenAICompatibleProviderCostEstimator = (\n context: OpenAICompatibleProviderCostContext\n) => number | undefined;\n\nexport interface OpenAICompatibleProviderOptions {\n readonly model: string;\n readonly apiKey?: string;\n readonly baseURL?: string | URL;\n readonly path?: string;\n readonly id?: string;\n readonly headers?: Readonly<Record<string, string | undefined>>;\n readonly fetch?: OpenAICompatibleFetch;\n readonly maxOutputTokens?: number;\n readonly extraBody?: JsonObject;\n readonly costEstimator?: OpenAICompatibleProviderCostEstimator;\n}\n\nexport interface OpenAICompatibleChatCompletionResponse {\n readonly id?: string;\n readonly object?: string;\n readonly created?: number;\n readonly model?: string;\n readonly choices?: readonly OpenAICompatibleChatCompletionChoice[];\n readonly usage?: OpenAICompatibleUsage;\n}\n\nexport interface OpenAICompatibleChatCompletionChoice {\n readonly finish_reason?: string | null;\n readonly message?: {\n readonly content?: unknown;\n };\n}\n\nexport interface OpenAICompatibleUsage extends JsonObject {\n readonly prompt_tokens?: number;\n readonly completion_tokens?: number;\n readonly total_tokens?: number;\n readonly input_tokens?: number;\n readonly output_tokens?: number;\n}\n\nexport function createOpenAICompatibleProvider(options: OpenAICompatibleProviderOptions): ConfiguredModelProvider {\n validateOptions(options);\n\n const providerId = options.id ?? `openai-compatible:${options.model}`;\n const fetchImplementation = options.fetch ?? globalThis.fetch?.bind(globalThis);\n\n if (!fetchImplementation) {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: \"createOpenAICompatibleProvider() requires a fetch implementation in this runtime.\",\n retryable: false,\n providerId,\n detail: {\n kind: \"configuration-validation\",\n path: \"fetch\",\n expected: \"a fetch-compatible function\"\n }\n });\n }\n\n return {\n id: providerId,\n async generate(request: ModelRequest): Promise<ModelResponse> {\n let response: Response;\n\n try {\n response = await fetchImplementation(createURL(options), {\n method: \"POST\",\n headers: createHeaders(options),\n body: JSON.stringify(createBody(options, request)),\n ...(request.signal !== undefined ? { signal: request.signal } : {})\n });\n } catch (error) {\n throw normalizeFetchError(error, providerId);\n }\n\n const payload = await readJson(response, providerId);\n\n if (!response.ok) {\n throw createProviderError(response, payload, providerId);\n }\n\n const completion = asChatCompletionResponse(payload, providerId);\n const text = readAssistantText(completion, providerId);\n const usage = normalizeUsage(completion.usage);\n const finishReason = normalizeFinishReason(completion.choices?.[0]?.finish_reason);\n const costUsd = options.costEstimator?.({\n providerId,\n request,\n response: completion,\n ...(usage ? { usage } : {})\n });\n\n return {\n text,\n ...(finishReason !== undefined ? { finishReason } : {}),\n ...(usage ? { usage } : {}),\n ...(costUsd !== undefined ? { costUsd } : {}),\n metadata: {\n openAICompatible: responseMetadata(completion)\n }\n };\n }\n };\n}\n\nfunction validateOptions(options: OpenAICompatibleProviderOptions): void {\n if (!isRecord(options)) {\n throwInvalid(\"options\", \"an options object\");\n }\n if (!isNonEmptyString(options.model)) {\n throwInvalid(\"model\", \"a non-empty model id\");\n }\n if (options.apiKey !== undefined && !isNonEmptyString(options.apiKey)) {\n throwInvalid(\"apiKey\", \"a non-empty API key when provided\");\n }\n if (options.id !== undefined && !isNonEmptyString(options.id)) {\n throwInvalid(\"id\", \"a non-empty provider id when provided\");\n }\n if (options.path !== undefined && !isNonEmptyString(options.path)) {\n throwInvalid(\"path\", \"a non-empty request path when provided\");\n }\n if (options.fetch !== undefined && typeof options.fetch !== \"function\") {\n throwInvalid(\"fetch\", \"a fetch-compatible function when provided\");\n }\n if (options.maxOutputTokens !== undefined && (!Number.isInteger(options.maxOutputTokens) || options.maxOutputTokens <= 0)) {\n throwInvalid(\"maxOutputTokens\", \"a positive integer when provided\");\n }\n if (options.costEstimator !== undefined && typeof options.costEstimator !== \"function\") {\n throwInvalid(\"costEstimator\", \"a function when provided\");\n }\n}\n\nfunction throwInvalid(path: string, expected: string): never {\n throw new DogpileError({\n code: \"invalid-configuration\",\n message: `Invalid OpenAI-compatible provider option at ${path}.`,\n retryable: false,\n detail: {\n kind: \"configuration-validation\",\n path,\n expected\n }\n });\n}\n\nfunction createURL(options: OpenAICompatibleProviderOptions): URL {\n const baseURL = new URL(String(options.baseURL ?? defaultBaseURL));\n const path = options.path ?? defaultPath;\n return new URL(path.startsWith(\"/\") ? path.slice(1) : path, ensureTrailingSlash(baseURL));\n}\n\nfunction ensureTrailingSlash(url: URL): URL {\n const next = new URL(url);\n if (!next.pathname.endsWith(\"/\")) {\n next.pathname = `${next.pathname}/`;\n }\n return next;\n}\n\nfunction createHeaders(options: OpenAICompatibleProviderOptions): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(options.headers ?? {})) {\n if (value !== undefined) {\n headers.set(key, value);\n }\n }\n headers.set(\"content-type\", \"application/json\");\n if (options.apiKey !== undefined && !headers.has(\"authorization\")) {\n headers.set(\"authorization\", `Bearer ${options.apiKey}`);\n }\n return headers;\n}\n\nfunction createBody(options: OpenAICompatibleProviderOptions, request: ModelRequest): JsonObject {\n return {\n ...(options.extraBody ?? {}),\n model: options.model,\n messages: request.messages.map(toChatMessage),\n temperature: request.temperature,\n ...(options.maxOutputTokens !== undefined ? { max_tokens: options.maxOutputTokens } : {})\n };\n}\n\nfunction toChatMessage(message: ModelMessage): JsonObject {\n return {\n role: message.role,\n content: message.content\n };\n}\n\nasync function readJson(response: Response, providerId: string): Promise<unknown> {\n try {\n return await response.json();\n } catch (error) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider returned a non-JSON response.\",\n cause: error,\n retryable: response.status >= 500,\n providerId,\n detail: {\n statusCode: response.status,\n statusText: response.statusText\n }\n });\n }\n}\n\nfunction asChatCompletionResponse(payload: unknown, providerId: string): OpenAICompatibleChatCompletionResponse {\n if (!isRecord(payload)) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider response must be a JSON object.\",\n retryable: true,\n providerId\n });\n }\n\n return payload as OpenAICompatibleChatCompletionResponse;\n}\n\nfunction readAssistantText(response: OpenAICompatibleChatCompletionResponse, providerId: string): string {\n const content = response.choices?.[0]?.message?.content;\n const text = normalizeContent(content);\n\n if (!text) {\n throw new DogpileError({\n code: \"provider-invalid-response\",\n message: \"OpenAI-compatible provider response did not include assistant text.\",\n retryable: true,\n providerId\n });\n }\n\n return text;\n}\n\nfunction normalizeContent(content: unknown): string {\n if (typeof content === \"string\") {\n return content;\n }\n\n if (!Array.isArray(content)) {\n return \"\";\n }\n\n return content\n .map((part) => {\n if (!isRecord(part)) {\n return \"\";\n }\n const text = part.text;\n return typeof text === \"string\" ? text : \"\";\n })\n .filter(Boolean)\n .join(\"\");\n}\n\nfunction normalizeUsage(usage: OpenAICompatibleUsage | undefined): ModelResponse[\"usage\"] | undefined {\n if (!usage) {\n return undefined;\n }\n\n const inputTokens = readTokenCount(usage.prompt_tokens ?? usage.input_tokens);\n const outputTokens = readTokenCount(usage.completion_tokens ?? usage.output_tokens);\n const totalTokens = readTokenCount(usage.total_tokens) ?? sumIfPresent(inputTokens, outputTokens);\n\n if (inputTokens === undefined || outputTokens === undefined || totalTokens === undefined) {\n return undefined;\n }\n\n return {\n inputTokens,\n outputTokens,\n totalTokens\n };\n}\n\nfunction readTokenCount(value: unknown): number | undefined {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n}\n\nfunction sumIfPresent(left: number | undefined, right: number | undefined): number | undefined {\n return left === undefined || right === undefined ? undefined : left + right;\n}\n\nfunction normalizeFinishReason(reason: string | null | undefined): ModelFinishReason | undefined {\n switch (reason) {\n case \"stop\":\n return \"stop\";\n case \"length\":\n return \"length\";\n case \"content_filter\":\n case \"content-filter\":\n return \"content-filter\";\n case \"tool_calls\":\n case \"tool-calls\":\n return \"tool-calls\";\n case undefined:\n case null:\n return undefined;\n default:\n return \"other\";\n }\n}\n\nfunction responseMetadata(response: OpenAICompatibleChatCompletionResponse): JsonObject {\n return removeUndefined({\n id: response.id,\n object: response.object,\n created: response.created,\n model: response.model,\n usage: isJsonValue(response.usage) ? response.usage : undefined\n });\n}\n\nfunction createProviderError(response: Response, payload: unknown, providerId: string): DogpileError {\n return new DogpileError({\n code: codeForStatus(response.status),\n message: providerResponseErrorMessage(response, payload),\n retryable: response.status === 408 || response.status === 429 || response.status >= 500,\n providerId,\n detail: removeUndefined({\n statusCode: response.status,\n statusText: response.statusText,\n response: isJsonValue(payload) ? payload : undefined\n })\n });\n}\n\nfunction normalizeFetchError(error: unknown, providerId: string): DogpileError {\n if (DogpileError.isInstance(error)) {\n return error;\n }\n\n if (errorName(error) === \"AbortError\") {\n return new DogpileError({\n code: \"aborted\",\n message: providerTransportErrorMessage(error, \"OpenAI-compatible provider request was aborted.\"),\n cause: error,\n retryable: false,\n providerId,\n detail: errorDetail(error)\n });\n }\n\n return new DogpileError({\n code: \"provider-error\",\n message: providerTransportErrorMessage(\n error,\n \"OpenAI-compatible provider request failed before receiving a response.\"\n ),\n cause: error,\n retryable: true,\n providerId,\n detail: errorDetail(error)\n });\n}\n\nfunction codeForStatus(status: number): DogpileErrorCode {\n if (status === 401 || status === 403) {\n return \"provider-authentication\";\n }\n if (status === 404) {\n return \"provider-not-found\";\n }\n if (status === 408 || status === 504) {\n return \"provider-timeout\";\n }\n if (status === 429) {\n return \"provider-rate-limited\";\n }\n if (status >= 500) {\n return \"provider-unavailable\";\n }\n if (status >= 400) {\n return \"provider-invalid-request\";\n }\n return \"provider-error\";\n}\n\nfunction providerResponseErrorMessage(response: Response, payload: unknown): string {\n const providerMessage = isRecord(payload) && isRecord(payload.error) && typeof payload.error.message === \"string\"\n ? payload.error.message\n : undefined;\n return providerMessage ?? `OpenAI-compatible provider request failed with HTTP ${response.status}.`;\n}\n\nfunction errorDetail(error: unknown): JsonObject {\n const detail: Record<string, JsonValue> = {};\n const name = errorName(error);\n\n if (name !== undefined) {\n detail.name = name;\n }\n\n return detail;\n}\n\nfunction errorName(error: unknown): string | undefined {\n return isRecord(error) && typeof error.name === \"string\" ? error.name : undefined;\n}\n\nfunction providerTransportErrorMessage(error: unknown, fallback: string): string {\n return error instanceof Error && error.message ? error.message : fallback;\n}\n\nfunction removeUndefined(values: Record<string, JsonValue | undefined>): JsonObject {\n return Object.fromEntries(Object.entries(values).filter(([, value]) => value !== undefined)) as JsonObject;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n}\n\nfunction isJsonValue(value: unknown): value is JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n return typeof value !== \"number\" || Number.isFinite(value);\n }\n\n if (Array.isArray(value)) {\n return value.every(isJsonValue);\n }\n\n if (isRecord(value)) {\n return Object.values(value).every(isJsonValue);\n }\n\n return false;\n}\n"],"mappings":";AAqBA,IAAM,oBAAoB;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;AA+JD,IAAa,eAAe,MAlEtB,yBAAyB,MAAoD;CACjF,OAAgB;;CAEhB;;CAEA;;CAEA;;CAEA;;CAEA;CAEA,YAAY,SAA8B;AACxC,QAAM,QAAQ,QAAQ;AACtB,OAAK,OAAO,QAAQ;AAEpB,MAAI,QAAQ,cAAc,KAAA,EACxB,MAAK,YAAY,QAAQ;AAE3B,MAAI,QAAQ,eAAe,KAAA,EACzB,MAAK,aAAa,QAAQ;AAE5B,MAAI,QAAQ,WAAW,KAAA,EACrB,MAAK,SAAS,QAAQ;AAExB,MAAI,QAAQ,UAAU,KAAA,EACpB,MAAK,QAAQ,QAAQ;AAGvB,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;CAMnD,OAAO,WAAW,OAAuC;AACvD,MAAI,iBAAiB,iBACnB,QAAO;AAGT,MAAI,CAAC,WAAS,MAAM,CAClB,QAAO;AAGT,SAAO,MAAM,SAAS,kBAAkB,mBAAmB,MAAM,KAAK,IAAI,OAAO,MAAM,YAAY;;;;;CAMrG,SAAqB;AACnB,SAAO;GACL,MAAM,KAAK;GACX,MAAM,KAAK;GACX,SAAS,KAAK;GACd,GAAI,KAAK,cAAc,KAAA,IAAY,EAAE,WAAW,KAAK,WAAW,GAAG,EAAE;GACrE,GAAI,KAAK,eAAe,KAAA,IAAY,EAAE,YAAY,KAAK,YAAY,GAAG,EAAE;GACxE,GAAI,K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