repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/plugins/chef/chef.ts

Raw
import { type Plugin, tool } from "@opencode-ai/plugin";
import { join } from "path";
import { glob } from "glob";
import { Store } from "./store";
import { Executor } from "./executor";
import type {
  GateDefinition,
  PipelineDefinition,
  StepDefinition,
} from "./pipeline/builder";

export const ChefPlugin: Plugin = async ({
  client,
  project,
  directory,
  worktree,
}) => {
  // Initialize store
  const store = new Store(directory);

  // Load pipeline definitions
  const pipelinesDir = join(directory, ".opencode/chef/pipelines");
  const pipelines = new Map<string, PipelineDefinition>();

  async function loadPipelines() {
    // Fetch available agents for validation
    let agentNames: Set<string> = new Set();
    try {
      const agents = await client.app.agents();
      agentNames = new Set(agents.map((a: any) => a.id ?? a.name));
    } catch {
      console.warn(
        "Chef: Could not fetch agent list, skipping agent validation",
      );
    }

    try {
      const files = await glob("*.ts", { cwd: pipelinesDir });

      for (const file of files) {
        try {
          const module = await import(join(pipelinesDir, file));
          const exported = module.default;

          if (!exported) continue;

          let definition: PipelineDefinition;
          let hasBuilder = false;

          if (typeof exported.build === "function") {
            definition = exported.build();
            hasBuilder = true;
          } else if (exported.name && exported.phases) {
            definition = exported;
          } else {
            continue;
          }

          // Run structural validation
          if (hasBuilder && typeof exported.validate === "function") {
            const result = exported.validate();
            if (!result.valid) {
              console.warn(
                `Chef: Pipeline "${definition.name}" has validation errors:`,
              );
              for (const err of result.errors) {
                console.warn(`  - ${err}`);
              }
            }
          }

          // Check agent names exist
          for (const phase of definition.phases) {
            if (
              phase.type === "step" &&
              !agentNames.has((phase as StepDefinition).agent)
            ) {
              console.warn(
                `Chef: Pipeline "${definition.name}" step "${phase.name}" references unknown agent "${
                  (phase as StepDefinition).agent
                }"`,
              );
            }
            if (
              phase.type === "gate" && (phase as GateDefinition).agent &&
              !agentNames.has((phase as GateDefinition).agent!)
            ) {
              console.warn(
                `Chef: Pipeline "${definition.name}" gate "${phase.name}" references unknown agent "${
                  (phase as GateDefinition).agent
                }"`,
              );
            }
            if (phase.type === "parallel") {
              for (const s of (phase as any).steps) {
                if (!agentNames.has(s.agent)) {
                  console.warn(
                    `Chef: Pipeline "${definition.name}" parallel step "${s.name}" references unknown agent "${s.agent}"`,
                  );
                }
              }
            }
          }

          pipelines.set(definition.name, definition);
        } catch (error) {
          console.error(`Chef: Failed to load pipeline ${file}:`, error);
        }
      }
    } catch (error) {
      // Pipelines directory doesn't exist yet
      console.log("Chef: No pipelines directory found");
    }
  }

  await loadPipelines();

  return {
    tool: {
      "pipeline.start": tool({
        description: "Start a new pipeline execution",
        args: {
          name: tool.schema.string().describe("Pipeline name"),
          input: tool.schema.any().optional().describe("Pipeline input data"),
        },
        async execute(args, context) {
          const definition = pipelines.get(args.name);

          if (!definition) {
            return `Pipeline "${args.name}" not found. Available pipelines: ${
              Array.from(pipelines.keys()).join(", ")
            }`;
          }

          // Create pipeline instance
          const instance = store.createPipeline(args.name, args.input || {});

          // Execute pipeline
          const executor = new Executor(store, client, definition);

          try {
            const result = await executor.execute(
              instance.id,
              args.input || {},
            );

            return JSON.stringify(
              {
                pipeline_id: instance.id,
                status: result.status,
                context: result.context,
              },
              null,
              2,
            );
          } catch (error: any) {
            store.updatePipeline(instance.id, {
              status: "failed",
            });

            return `Pipeline execution failed: ${error.message}`;
          }
        },
      }),

      "pipeline.status": tool({
        description: "Check status of pipeline(s)",
        args: {
          id: tool.schema.string().optional().describe(
            "Pipeline ID (optional, defaults to all running)",
          ),
        },
        async execute(args, context) {
          if (args.id) {
            const pipeline = store.getPipeline(args.id);

            if (!pipeline) {
              return `Pipeline ${args.id} not found`;
            }

            return JSON.stringify(pipeline, null, 2);
          }

          const running = store.listPipelines("running");
          return JSON.stringify(running, null, 2);
        },
      }),

      "pipeline.continue": tool({
        description: "Continue a pipeline after needs_input",
        args: {
          id: tool.schema.string().describe("Pipeline ID"),
          input: tool.schema.any().describe("Input data for next phase"),
        },
        async execute(args, context) {
          const instance = store.getPipeline(args.id);

          if (!instance) {
            return `Pipeline ${args.id} not found`;
          }

          if (instance.status !== "needs_input") {
            return `Pipeline ${args.id} is not waiting for input (status: ${instance.status})`;
          }

          const definition = pipelines.get(instance.definition);
          if (!definition) {
            return `Pipeline definition ${instance.definition} not found`;
          }

          // Merge input into context
          const pipelineContext = JSON.parse(instance.context);
          Object.assign(pipelineContext, args.input);
          store.updatePipeline(args.id, {
            context: JSON.stringify(pipelineContext),
            status: "running",
          });

          // Continue execution
          const executor = new Executor(store, client, definition);

          try {
            const result = await executor.execute(args.id, pipelineContext);

            return JSON.stringify(
              {
                pipeline_id: args.id,
                status: result.status,
                context: result.context,
              },
              null,
              2,
            );
          } catch (error: any) {
            store.updatePipeline(args.id, {
              status: "failed",
            });

            return `Pipeline execution failed: ${error.message}`;
          }
        },
      }),

      "pipeline.abort": tool({
        description: "Abort a running pipeline",
        args: {
          id: tool.schema.string().describe("Pipeline ID"),
        },
        async execute(args, context) {
          const instance = store.getPipeline(args.id);

          if (!instance) {
            return `Pipeline ${args.id} not found`;
          }

          store.updatePipeline(args.id, {
            status: "aborted",
          });

          return `Pipeline ${args.id} aborted`;
        },
      }),

      "pipeline.list": tool({
        description: "List available pipelines",
        args: {},
        async execute(args, context) {
          const names = Array.from(pipelines.keys());

          return `Available pipelines:\n${
            names.map((n) => `- ${n}`).join("\n")
          }\n\nLoad custom pipelines by creating .opencode/chef/pipelines/*.ts files`;
        },
      }),
    },
  };
};

export default ChefPlugin;