repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/plugins/chef/executor.ts

Raw
File outline
import type { Client } from "@opencode-ai/sdk";
import { zodToJsonSchema } from "zod-to-json-schema";
import type {
  GateDefinition,
  ParallelDefinition,
  PhaseDefinition,
  PipelineDefinition,
  RetryPolicy,
  StepDefinition,
  WhenDefinition,
} from "./pipeline/builder";
import { Store } from "./store";

// Error taxonomy
export class ChefError extends Error {
  constructor(
    message: string,
    public readonly type: string,
  ) {
    super(message);
    this.name = "ChefError";
  }
}

export class AgentTimeoutError extends ChefError {
  constructor(stepName: string, timeout: number) {
    super(`Step "${stepName}" timed out after ${timeout}ms`, "agent_timeout");
    this.name = "AgentTimeoutError";
  }
}

export class AgentError extends ChefError {
  constructor(stepName: string, message: string) {
    super(`Agent error in "${stepName}": ${message}`, "agent_error");
    this.name = "AgentError";
  }
}

export class GateFailureError extends ChefError {
  constructor(gateName: string, message: string) {
    super(`Gate "${gateName}" failed: ${message}`, "gate_failure");
    this.name = "GateFailureError";
  }
}

export class MaxIterationsError extends ChefError {
  constructor(max: number) {
    super(`Max loop iterations (${max}) reached`, "max_iterations");
    this.name = "MaxIterationsError";
  }
}

export class SchemaValidationError extends ChefError {
  constructor(stepName: string, message: string) {
    super(
      `Schema validation failed for "${stepName}": ${message}`,
      "schema_validation",
    );
    this.name = "SchemaValidationError";
  }
}

const DEFAULT_MAX_LOOP_ITERATIONS = 10;
const DEFAULT_RETRY: RetryPolicy = {
  maxAttempts: 1,
  backoffMs: 1000,
  retryOn: undefined,
};

export class Executor {
  private maxLoopIterations: number;

  constructor(
    private store: Store,
    private client: Client,
    private definition: PipelineDefinition,
    options?: { maxLoopIterations?: number },
  ) {
    this.maxLoopIterations = options?.maxLoopIterations ??
      DEFAULT_MAX_LOOP_ITERATIONS;
  }

  private async cleanupSession(sessionId: string): Promise<void> {
    await this.client.session.delete({ path: { id: sessionId } }).catch(
      (e) => {
        console.warn(
          `Chef: session cleanup failed for ${sessionId}:`,
          e?.message ?? e,
        );
      },
    );
  }

  async execute(pipelineId: string, input: any): Promise<any> {
    const instance = this.store.getPipeline(pipelineId);
    if (!instance) {
      throw new Error(`Pipeline ${pipelineId} not found`);
    }

    let context: any = JSON.parse(instance.context ?? "{}");
    const phases = this.definition.phases;
    let loopIterations = 0;

    for (let i = instance.current_phase; i < phases.length; i++) {
      // Check if pipeline was aborted
      const current = this.store.getPipeline(pipelineId);
      if (current && current.status === "aborted") {
        return { status: "aborted", context };
      }

      const phase = phases[i];

      // Update current phase
      this.store.updatePipeline(pipelineId, {
        current_phase: i,
        status: "running",
      });

      try {
        const result = await this.executePhase(phase, context, pipelineId);

        if (result.status === "needs_input") {
          this.store.updatePipeline(pipelineId, {
            status: "needs_input",
            context: JSON.stringify(context),
          });
          return { status: "needs_input", context };
        }

        if (result.status === "loop") {
          loopIterations++;
          if (loopIterations > this.maxLoopIterations) {
            this.store.updatePipeline(pipelineId, {
              status: "failed",
              context: JSON.stringify(context),
            });
            return {
              status: "failed",
              error: new MaxIterationsError(this.maxLoopIterations).message,
            };
          }
          const targetIndex = phases.findIndex((p) => p.name === result.target);
          if (targetIndex >= 0) {
            i = targetIndex - 1; // -1 because loop will increment
            continue;
          }
        }

        if (result.status === "failed") {
          this.store.updatePipeline(pipelineId, {
            status: "failed",
            context: JSON.stringify(context),
          });
          return { status: "failed", error: result.error };
        }

        // Merge output into context
        if (result.output) {
          context[phase.name] = result.output;
          this.store.updatePipeline(pipelineId, {
            context: JSON.stringify(context),
          });
        }
      } catch (error: any) {
        this.store.updatePipeline(pipelineId, {
          status: "failed",
        });
        throw error;
      }
    }

    // Pipeline completed
    this.store.updatePipeline(pipelineId, {
      status: "completed",
      current_phase: phases.length,
    });

    return { status: "completed", context };
  }

  private async executePhase(
    phase: PhaseDefinition,
    context: any,
    pipelineId: string,
  ): Promise<
    { status: string; output?: any; error?: string; target?: string }
  > {
    switch (phase.type) {
      case "step":
        return this.executeStep(phase, context, pipelineId);

      case "gate":
        return this.executeGate(phase, context, pipelineId);

      case "parallel":
        return this.executeParallel(phase, context, pipelineId);

      case "when":
        return this.executeWhen(phase, context);

      default:
        throw new Error(`Unknown phase type: ${(phase as any).type}`);
    }
  }

  private async executeStep(
    step: StepDefinition,
    context: any,
    pipelineId: string,
    parentPhaseId?: string,
  ): Promise<{ status: string; output?: any; error?: string }> {
    const phase = parentPhaseId
      ? (this.store.getPhase(parentPhaseId) ??
        this.store.createPhase(pipelineId, step.name))
      : this.store.createPhase(pipelineId, step.name);
    const retry: RetryPolicy = step.retry ?? DEFAULT_RETRY;
    let lastError: any;

    for (let attempt = 0; attempt < retry.maxAttempts; attempt++) {
      let sessionId: string | undefined;

      try {
        // Create fresh session for each attempt
        const session = await this.client.session.create({
          body: {
            title: `Chef: ${step.name}${
              attempt > 0 ? ` (retry ${attempt})` : ""
            }`,
            agent: step.agent,
          },
        });
        sessionId = session.id;

        // Inject context
        const contextParts: any[] = [
          {
            type: "text",
            text: `Previous context:\n${JSON.stringify(context, null, 2)}`,
          },
        ];

        // On retry, inject previous error as feedback
        if (attempt > 0 && lastError) {
          contextParts.push({
            type: "text",
            text:
              `Previous attempt failed with: ${lastError.message}. Please correct this and try again.`,
          });
        }

        await this.client.session.prompt({
          path: { id: session.id },
          body: {
            noReply: true,
            parts: contextParts,
          },
        });

        // Execute with structured output
        const prompt = typeof step.prompt === "function"
          ? step.prompt(context)
          : step.prompt;

        const jsonSchema = zodToJsonSchema(step.output);

        // Build prompt promise
        const promptPromise = this.client.session.prompt({
          path: { id: session.id },
          body: {
            parts: [{ type: "text", text: prompt }],
            format: {
              type: "json_schema",
              schema: jsonSchema,
              retryCount: 2,
            },
          },
        });

        // Apply timeout if configured
        let result: any;
        if (step.timeout) {
          result = await Promise.race([
            promptPromise,
            new Promise<never>((_, reject) =>
              setTimeout(
                () => reject(new AgentTimeoutError(step.name, step.timeout!)),
                step.timeout,
              )
            ),
          ]);
        } else {
          result = await promptPromise;
        }

        const output = result.data.info.structured_output;

        // Update phase state
        this.store.updatePhase(phase.id, {
          status: "completed",
          output: JSON.stringify(output),
          completed_at: Date.now(),
          attempts: attempt + 1,
        });

        return { status: "completed", output };
      } catch (error: any) {
        lastError = error;

        // Try to abort timed-out sessions
        if (sessionId && error instanceof AgentTimeoutError) {
          try {
            await this.client.session.delete({ path: { id: sessionId } });
            sessionId = undefined; // prevent double-delete in finally
          } catch {
            // best-effort abort
          }
        }

        this.store.updatePhase(phase.id, {
          attempts: attempt + 1,
          error: error.message,
        });

        // Check if error type is retryable
        const shouldRetry = retry.retryOn === undefined ||
          retry.retryOn.includes(error.type) ||
          retry.retryOn.includes("all");

        if (!shouldRetry || attempt >= retry.maxAttempts - 1) {
          break;
        }

        // Exponential backoff before retry
        const delay = retry.backoffMs * Math.pow(2, attempt);
        console.warn(
          `Chef: Step "${step.name}" attempt ${
            attempt + 1
          } failed, retrying in ${delay}ms...`,
        );
        await new Promise((r) => setTimeout(r, delay));
      } finally {
        if (sessionId) {
          await this.cleanupSession(sessionId);
        }
      }
    }

    // All attempts exhausted
    this.store.updatePhase(phase.id, {
      status: "failed",
      error: lastError?.message ?? "Unknown error",
    });

    return { status: "failed", error: lastError?.message ?? "Unknown error" };
  }

  private async executeGate(
    gate: GateDefinition,
    context: any,
    pipelineId: string,
  ): Promise<
    { status: string; output?: any; error?: string; target?: string }
  > {
    const phase = this.store.createPhase(pipelineId, gate.name);
    let sessionId: string | undefined;

    try {
      // If gate has an agent, execute it
      if (gate.agent) {
        const session = await this.client.session.create({
          body: {
            title: `Chef Gate: ${gate.name}`,
            agent: gate.agent,
          },
        });
        sessionId = session.id;

        // Inject context
        await this.client.session.prompt({
          path: { id: session.id },
          body: {
            noReply: true,
            parts: [
              {
                type: "text",
                text: `Context:\n${
                  JSON.stringify(context, null, 2)
                }\n\nEvaluate this gate.`,
              },
            ],
          },
        });

        const jsonSchema = zodToJsonSchema(gate.expect);

        const result = await this.client.session.prompt({
          path: { id: session.id },
          body: {
            parts: [{ type: "text", text: "Evaluate gate conditions" }],
            format: {
              type: "json_schema",
              schema: jsonSchema,
              retryCount: 2,
            },
          },
        });

        const output = result.data.info.structured_output;

        // Validate against expectation
        const validated = gate.expect.parse(output);

        this.store.updatePhase(phase.id, {
          status: "completed",
          output: JSON.stringify(validated),
          completed_at: Date.now(),
        });

        return { status: "completed", output: validated };
      } else {
        // Direct validation without agent
        const validated = gate.expect.parse(context);

        this.store.updatePhase(phase.id, {
          status: "completed",
          output: JSON.stringify(validated),
          completed_at: Date.now(),
        });

        return { status: "completed", output: validated };
      }
    } catch (error: any) {
      this.store.updatePhase(phase.id, {
        status: "failed",
        error: error.message,
      });

      // If gate has onFail, loop back to target phase
      if (gate.onFail) {
        console.warn(
          `Chef: Gate "${gate.name}" failed, looping back to "${gate.onFail}"`,
        );
        return { status: "loop", target: gate.onFail };
      }

      return { status: "failed", error: error.message };
    } finally {
      if (sessionId) {
        await this.cleanupSession(sessionId);
      }
    }
  }

  private async executeParallel(
    parallel: ParallelDefinition,
    context: any,
    pipelineId: string,
  ): Promise<{ status: string; output?: any; error?: string }> {
    const phase = this.store.createPhase(pipelineId, parallel.name);

    try {
      const results = await Promise.all(
        parallel.steps.map((step) =>
          this.executeStep(step, context, pipelineId, phase.id)
        ),
      );

      // Check if any failed
      const failed = results.find((r) => r.status === "failed");
      if (failed) {
        this.store.updatePhase(phase.id, {
          status: "failed",
          error: failed.error,
        });
        return failed;
      }

      const outputs = results.reduce((acc, r, i) => {
        acc[parallel.steps[i].name] = r.output;
        return acc;
      }, {} as any);

      this.store.updatePhase(phase.id, {
        status: "completed",
        output: JSON.stringify(outputs),
        completed_at: Date.now(),
      });

      return { status: "completed", output: outputs };
    } catch (error: any) {
      this.store.updatePhase(phase.id, {
        status: "failed",
        error: error.message,
      });

      return { status: "failed", error: error.message };
    }
  }

  private executeWhen(
    when: WhenDefinition,
    context: any,
  ): { status: string; target?: string } {
    const conditionMet = when.condition(context);

    if (conditionMet && when.loopTarget) {
      return { status: "loop", target: when.loopTarget };
    }

    return { status: "completed" };
  }
}