import { z } from "zod/v3"; import { type JudgeReport, type LoopConfig, type OrchestratorState } from "../src/core/loop.js"; import { type CompiledGraph, type GraphDefinition } from "../src/core/graph.js"; import { type FailureCategory, type FailureEvidence, type RecoveryDirective, type RecoveryLedger } from "../src/core/recovery.js"; import { type SchedulerRecoveryBinding } from "../src/core/schedulerRecovery.js"; import { mcpRunJudgeRoutingDecisionSchema, mcpRunPlanRoutingDecisionSchema, type McpRunAdapter, type McpRunClientEvent, type McpRunResponse, type McpRunStartInput } from "./runProtocol.js"; import type { RoutedCompletionAttempt, RoutedCompletionAttemptResult } from "./llm.js"; import type { ArtifactReference, GraphExecutionState } from "../src/core/scheduler.js"; import { type RecoveryArtifactBinding } from "../src/runtime/recoveryArtifacts.js"; type RunRoutingDecision = McpRunResponse["routing"][number]; type PlanRoutingDecision = z.infer; type JudgeRoutingDecision = z.infer; type RunVerdict = NonNullable; type RunOutcome = McpRunResponse["outcome"]; type RunStatus = McpRunResponse["status"]; declare const providerAttemptReservationSchema: z.ZodObject<{ attempt: z.ZodNumber; providerRequestRef: z.ZodString; routingDecision: z.ZodObject<{ decisionId: z.ZodString; policyVersion: z.ZodString; policyDigest: z.ZodString; configDigest: z.ZodString; candidatesDigest: z.ZodString; }, "strict", z.ZodTypeAny, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }>; identity: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; family: z.ZodOptional; }, "strict", z.ZodTypeAny, { provider: string; model: string; family?: string | undefined; }, { provider: string; model: string; family?: string | undefined; }>; thinking: z.ZodEnum<["off", "minimal", "low", "medium", "high", "xhigh", "max"]>; requestedOutputTokens: z.ZodOptional; estimatedCostUsd: z.ZodOptional; } & { providerAttemptIdempotencyKey: z.ZodString; }, "strict", z.ZodTypeAny, { identity: { provider: string; model: string; family?: string | undefined; }; attempt: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }, { identity: { provider: string; model: string; family?: string | undefined; }; attempt: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }>; export type ProviderAttemptReservation = z.infer; export interface ProviderEffectBase { effectId: string; kind: "plan" | "judge" | "debug"; ordinal: number; } declare const providerAttemptEvidenceSchema: z.ZodDiscriminatedUnion<"phase", [z.ZodObject<{ attempt: z.ZodNumber; providerRequestRef: z.ZodString; routingDecision: z.ZodObject<{ decisionId: z.ZodString; policyVersion: z.ZodString; policyDigest: z.ZodString; configDigest: z.ZodString; candidatesDigest: z.ZodString; }, "strict", z.ZodTypeAny, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }>; identity: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; family: z.ZodOptional; }, "strict", z.ZodTypeAny, { provider: string; model: string; family?: string | undefined; }, { provider: string; model: string; family?: string | undefined; }>; thinking: z.ZodEnum<["off", "minimal", "low", "medium", "high", "xhigh", "max"]>; requestedOutputTokens: z.ZodOptional; estimatedCostUsd: z.ZodOptional; } & { providerAttemptIdempotencyKey: z.ZodString; } & { phase: z.ZodLiteral<"failed">; effectId: z.ZodString; kind: z.ZodEnum<["plan", "judge", "debug"]>; ordinal: z.ZodNumber; failureCode: z.ZodEnum<["http_error", "invalid_json", "provider_response_failed", "schema_validation_failed", "truncated", "provider_unconfigured", "missing_api_key", "unsupported_api", "empty_response", "response_too_large"]>; }, "strict", z.ZodTypeAny, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "failed"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; failureCode: "truncated" | "http_error" | "invalid_json" | "provider_response_failed" | "schema_validation_failed" | "provider_unconfigured" | "missing_api_key" | "unsupported_api" | "empty_response" | "response_too_large"; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "failed"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; failureCode: "truncated" | "http_error" | "invalid_json" | "provider_response_failed" | "schema_validation_failed" | "provider_unconfigured" | "missing_api_key" | "unsupported_api" | "empty_response" | "response_too_large"; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }>, z.ZodObject<{ attempt: z.ZodNumber; providerRequestRef: z.ZodString; routingDecision: z.ZodObject<{ decisionId: z.ZodString; policyVersion: z.ZodString; policyDigest: z.ZodString; configDigest: z.ZodString; candidatesDigest: z.ZodString; }, "strict", z.ZodTypeAny, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }>; identity: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; family: z.ZodOptional; }, "strict", z.ZodTypeAny, { provider: string; model: string; family?: string | undefined; }, { provider: string; model: string; family?: string | undefined; }>; thinking: z.ZodEnum<["off", "minimal", "low", "medium", "high", "xhigh", "max"]>; requestedOutputTokens: z.ZodOptional; estimatedCostUsd: z.ZodOptional; } & { providerAttemptIdempotencyKey: z.ZodString; } & { phase: z.ZodLiteral<"unknown">; effectId: z.ZodString; kind: z.ZodEnum<["plan", "judge", "debug"]>; ordinal: z.ZodNumber; failureCode: z.ZodEnum<["timeout", "aborted", "provider_failed"]>; }, "strict", z.ZodTypeAny, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "unknown"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; failureCode: "timeout" | "aborted" | "provider_failed"; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "unknown"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; failureCode: "timeout" | "aborted" | "provider_failed"; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }>, z.ZodObject<{ attempt: z.ZodNumber; providerRequestRef: z.ZodString; routingDecision: z.ZodObject<{ decisionId: z.ZodString; policyVersion: z.ZodString; policyDigest: z.ZodString; configDigest: z.ZodString; candidatesDigest: z.ZodString; }, "strict", z.ZodTypeAny, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }>; identity: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; family: z.ZodOptional; }, "strict", z.ZodTypeAny, { provider: string; model: string; family?: string | undefined; }, { provider: string; model: string; family?: string | undefined; }>; thinking: z.ZodEnum<["off", "minimal", "low", "medium", "high", "xhigh", "max"]>; requestedOutputTokens: z.ZodOptional; estimatedCostUsd: z.ZodOptional; } & { providerAttemptIdempotencyKey: z.ZodString; } & { phase: z.ZodEnum<["awaiting_output_commit", "discarded"]>; effectId: z.ZodString; kind: z.ZodEnum<["plan", "judge", "debug"]>; ordinal: z.ZodNumber; }, "strict", z.ZodTypeAny, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "awaiting_output_commit" | "discarded"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; attempt: number; phase: "awaiting_output_commit" | "discarded"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }>, z.ZodObject<{ attempt: z.ZodNumber; providerRequestRef: z.ZodString; routingDecision: z.ZodObject<{ decisionId: z.ZodString; policyVersion: z.ZodString; policyDigest: z.ZodString; configDigest: z.ZodString; candidatesDigest: z.ZodString; }, "strict", z.ZodTypeAny, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }, { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }>; identity: z.ZodObject<{ provider: z.ZodString; model: z.ZodString; family: z.ZodOptional; }, "strict", z.ZodTypeAny, { provider: string; model: string; family?: string | undefined; }, { provider: string; model: string; family?: string | undefined; }>; thinking: z.ZodEnum<["off", "minimal", "low", "medium", "high", "xhigh", "max"]>; requestedOutputTokens: z.ZodOptional; estimatedCostUsd: z.ZodOptional; } & { providerAttemptIdempotencyKey: z.ZodString; } & { phase: z.ZodLiteral<"output_committed">; effectId: z.ZodString; kind: z.ZodEnum<["plan", "judge", "debug"]>; ordinal: z.ZodNumber; resultRef: z.ZodObject<{ planVersion: z.ZodNumber; nodeId: z.ZodString; contract: z.ZodEffects; path: z.ZodString; sha256: z.ZodString; sizeBytes: z.ZodNumber; }, "strict", z.ZodTypeAny, { planVersion: number; nodeId: string; contract: string; path: string; sha256: string; sizeBytes: number; }, { planVersion: number; nodeId: string; contract: string; path: string; sha256: string; sizeBytes: number; }>; }, "strict", z.ZodTypeAny, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; resultRef: { planVersion: number; nodeId: string; contract: string; path: string; sha256: string; sizeBytes: number; }; attempt: number; phase: "output_committed"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }, { identity: { provider: string; model: string; family?: string | undefined; }; kind: "plan" | "debug" | "judge"; resultRef: { planVersion: number; nodeId: string; contract: string; path: string; sha256: string; sizeBytes: number; }; attempt: number; phase: "output_committed"; ordinal: number; thinking: "low" | "medium" | "high" | "off" | "minimal" | "xhigh" | "max"; routingDecision: { decisionId: string; policyVersion: string; policyDigest: string; configDigest: string; candidatesDigest: string; }; providerRequestRef: string; providerAttemptIdempotencyKey: string; effectId: string; estimatedCostUsd?: number | undefined; requestedOutputTokens?: number | undefined; }>]>; export type ProviderAttemptEvidence = z.infer; export type ProviderEffect = ProviderEffectBase & ({ phase: "prepared"; } | { phase: "attempting"; attempt: ProviderAttemptReservation; } | { phase: "attempted"; result: Exclude; } | { phase: "awaiting_output_commit"; attempt: ProviderAttemptReservation; }); export interface McpRunPreflightRequest { task: string; repoContext?: string; coderIdentity: string; taskFeatures?: McpRunStartInput["taskFeatures"]; } export interface McpRunPlanRequest { task: string; repoContext?: string; taskFeatures?: McpRunStartInput["taskFeatures"]; previousPlan?: string; userFeedback?: string; judgeReports?: JudgeReport[]; diff?: string; signal?: AbortSignal; beforeAttempt: (attempt: RoutedCompletionAttempt) => void | Promise; afterAttempt: (result: RoutedCompletionAttemptResult) => void | Promise; } export interface McpRunJudgeRequest { task: string; plan: string; diff: string; testOutput?: string; coderIdentity: string; taskFeatures?: McpRunStartInput["taskFeatures"]; iteration: number; consecutiveRejections: number; signal?: AbortSignal; beforeAttempt: (attempt: RoutedCompletionAttempt) => void | Promise; afterAttempt: (result: RoutedCompletionAttemptResult) => void | Promise; } export interface McpRunDiagnosisRequest { task: string; plan: string; failureFingerprint: string; observedCategory: FailureCategory; evidenceRefs: readonly string[]; lastVerdict?: JudgeReport; coderIdentity: string; taskFeatures?: McpRunStartInput["taskFeatures"]; signal?: AbortSignal; beforeAttempt: (attempt: RoutedCompletionAttempt) => void | Promise; afterAttempt: (result: RoutedCompletionAttemptResult) => void | Promise; } export interface McpRunProvider { /** * Resolve trusted checker eligibility without a provider/network call. * This is synchronous because start invokes it before run authority exists. */ preflight(input: McpRunPreflightRequest): { coderFamily?: string; requireDifferentCheckerFamily: boolean; }; plan(input: McpRunPlanRequest): Promise<{ plan: string; routing: PlanRoutingDecision; }>; judge(input: McpRunJudgeRequest): Promise; diagnose?(input: McpRunDiagnosisRequest): Promise<{ diagnosis: { rootCauseCategory: FailureCategory; confidence: RecoveryDirective["confidence"]; summary: string; repairScope: string[]; validationRequirements: string[]; topologyAssessment: RecoveryDirective["topologyAssessment"]; }; routing: JudgeRoutingDecision; }>; } /** * Durable state needed by the service. A disk adapter may encode the large * payload fields as artifact references; request records below never contain * raw task, prompt, diff, test, or provider-output text. */ export interface McpRunRecord { runId: string; revision: number; status: Exclude; state: OrchestratorState; repoContext?: string; coderIdentity: string; coderFamily?: string; requireDifferentCheckerFamily: boolean; taskFeatures?: McpRunStartInput["taskFeatures"]; loop: LoopConfig; planVersion: number; routing: RunRoutingDecision[]; lastVerdict?: RunVerdict; terminalMessage?: string; pendingProviderIntent: boolean; providerAttempts: number; providerEffects: ProviderEffectBase[]; providerEvidence: ProviderAttemptEvidence[]; nextProviderEffectOrdinal: number; maxProviderCalls: number; requestAuthority: McpRunRequestAuthority; cancelledCheckpoint?: OrchestratorState; abandonedProviderAttempt?: ProviderEffectBase & { attempt: ProviderAttemptReservation; }; recovery?: McpRunRecoveryEnvelope; } export interface McpRunRecoveryEnvelope { version: 1; binding: Readonly; occurrenceBindings: readonly Readonly[]; ledger: Readonly; artifacts: readonly Readonly[]; executionHistory: readonly Readonly>[]; execution?: Readonly<{ version: 1; failureFingerprint: string; action: "retry" | "repair"; status: "awaiting-client" | "executing-provider" | "completed"; providerKind?: "plan" | "judge"; requestRef?: string; resultRef?: Readonly; }>; } export interface McpRunRecoveryContext { graphDefinition: GraphDefinition; schedulerState: GraphExecutionState; } export type McpRunRecordDraft = Omit; interface McpRunRequestBase { requestRef: string; requestHash: string; mutationEffect: McpRunMutationEffect; providerEffectIds: string[]; } export type McpRunMutationEffect = { operation: "start"; } | { operation: "advance"; event: McpRunClientEvent["type"]; } | { operation: "cancel"; } | { operation: "recover"; }; export type McpRunRequestUpdate = (McpRunRequestBase & { state: "pending"; effect: ProviderEffect; }) | (McpRunRequestBase & { state: "settled"; outcome: RunOutcome; }); export type McpRunRequestRecord = (Extract & { runId: string; reservedRevision: number; authorityDigest: string; eventDigest: string; }) | (Extract & { runId: string; checkpoint: McpRunCheckpointReference; authorityDigest: string; eventDigest: string; }); export type McpRunRequestAuthority = Pick, "state" | "requestRef" | "requestHash" | "mutationEffect" | "providerEffectIds" | "effect"> | Pick, "state" | "requestRef" | "requestHash" | "mutationEffect" | "providerEffectIds" | "outcome">; export interface McpRunCheckpointReference { runId: string; revision: number; } export interface McpRunPublication { record: McpRunRecord; request: McpRunRequestRecord; } export interface McpRunProviderOutput { runId: string; effect: ProviderEffectBase; attempt: ProviderAttemptReservation; contract: "mcp-plan-output-v1" | "mcp-judge-output-v1" | "mcp-debug-output-v1"; bytes: Uint8Array; } /** * Must be called synchronously while the repository's exclusive lease is held, * after revision/request assignment and immediately before any bytes become * visible as authority. A thrown validation error must publish nothing. */ export type McpRunPublicationGuard = (publication: McpRunPublication) => void; export interface McpRunStartTransaction { getRequest(): Promise; /** Atomically create the run, reserve the provider intent, and assign a revision. */ reserve(draft: McpRunRecordDraft, request: Extract, beforePublication: McpRunPublicationGuard): Promise; /** Atomically CAS the run, update the request record, and assign a revision. */ compareAndSwap(expectedRevision: number, draft: McpRunRecordDraft, request: McpRunRequestUpdate, beforePublication: McpRunPublicationGuard): Promise; /** Write immutable provider-result bytes while this lease generation is held. */ writeProviderOutput(input: McpRunProviderOutput): Promise; } export interface McpRunTransaction { get(): Promise; getRequest(requestRef: string): Promise; /** Atomically CAS the run, update the request record, and assign a revision. */ compareAndSwap(expectedRevision: number, draft: McpRunRecordDraft, request: McpRunRequestUpdate, beforePublication: McpRunPublicationGuard): Promise; /** Write immutable provider-result bytes while this lease generation is held. */ writeProviderOutput(input: McpRunProviderOutput): Promise; /** Trusted scheduler state and graph bytes used to anchor the first recovery ledger. */ getRecoveryContext?(): Promise; /** Write one immutable content-addressed artifact while this lease generation is held. */ writeRecoveryArtifact?(input: { runId: string; semanticRef: string; bytes: Uint8Array; }): Promise; } /** * The callback runs under a repository lease. Each transaction write must be * durable before it resolves; the repository, not this service, is the sole * authority that assigns monotonically increasing per-run revisions. */ export interface McpRunRepository { withStartLease(requestRef: string, work: (transaction: McpRunStartTransaction) => Promise): Promise; withRunLease(runId: string, work: (transaction: McpRunTransaction) => Promise): Promise; get(runId: string): Promise; /** * Revision 1 is the immutable creation checkpoint for a run. Durable * adapters must authenticate it through their append-only event/WAL chain; * the service uses it as the external anchor for frozen policy and identity. * This read must remain safe while a run lease is held. */ getCheckpoint(reference: McpRunCheckpointReference): Promise; } /** Parse and authenticate one exact repository publication at a disk boundary. */ export declare function parseMcpRunPublicationAuthority(unparsed: unknown): McpRunPublication; export declare function validateMcpRunRecoveryEnvelope(value: unknown): McpRunRecoveryEnvelope; export interface CreateMcpRunServiceOptions { repository: McpRunRepository; provider: McpRunProvider; loop: LoopConfig; createRunId?: (requestRef: string) => string; maxProviderCalls?: number; /** Test/recovery hook executed after provider return and before settlement. */ afterProviderResult?: (context: { runId: string; effect: ProviderEffect; }) => void | Promise; } export declare function createMcpRunService(options: CreateMcpRunServiceOptions): McpRunAdapter; /** * Derive the only recovery observation the MCP fast-path can currently prove. * The client never supplies category, contract, attempt, or lineage data. */ export declare function deriveMcpRunFailureEvidence(graph: CompiledGraph, binding: SchedulerRecoveryBinding, record: McpRunRecord): FailureEvidence; export declare function providerEffectIdentity(runId: string, kind: ProviderEffectBase["kind"], ordinal: number): string; export declare function providerAttemptIdempotencyKey(runId: string, effect: ProviderEffectBase, attempt: Pick): string; export declare function createMcpRunRequestRecord(update: McpRunRequestUpdate, record: McpRunRecord): McpRunRequestRecord; export {};