-
Notifications
You must be signed in to change notification settings - Fork 121
feat: Implement workflow generation command with YAML validation and LLM integration #37
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
krishvsoni
wants to merge
4
commits into
open-gitagent:main
Choose a base branch
from
krishvsoni:feat/issue-9-workflow-llm-generator
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
b0f87bc
feat: Implement workflow generation command with YAML validation and …
krishvsoni 6f8f1a4
feat: Enhance workflow generation with dependency validation and forc…
krishvsoni 1940e75
feat: Add skill validation and allow missing skills option in workflo…
krishvsoni dd7ae52
feat: Add validation for forward depends_on references in workflow
krishvsoni File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| { | ||
| "$schema": "http://json-schema.org/draft-07/schema#", | ||
| "$id": "https://gitagent.dev/spec/workflow.schema.json", | ||
| "title": "Gitagent SkillFlow Workflow", | ||
| "description": "A SkillFlow workflow: a named sequence of steps, where each step invokes a skill with a prompt. Runtime semantics are defined by src/workflows.ts.", | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "required": ["name", "description", "steps"], | ||
| "properties": { | ||
| "name": { | ||
| "type": "string", | ||
| "description": "Kebab-case identifier for the workflow. Used as the file name.", | ||
| "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" | ||
| }, | ||
| "description": { | ||
| "type": "string", | ||
| "description": "One-line description of what the workflow does.", | ||
| "minLength": 1 | ||
| }, | ||
| "steps": { | ||
| "type": "array", | ||
| "description": "Ordered list of steps. Steps execute top-to-bottom.", | ||
| "minItems": 1, | ||
| "items": { "$ref": "#/definitions/step" } | ||
| } | ||
| }, | ||
| "definitions": { | ||
| "step": { | ||
| "type": "object", | ||
| "additionalProperties": false, | ||
| "required": ["skill", "prompt"], | ||
| "properties": { | ||
| "id": { | ||
| "type": "string", | ||
| "description": "Optional snake_case identifier for the step. Used when other steps reference this one via depends_on.", | ||
| "pattern": "^[a-z0-9]+(_[a-z0-9]+)*$" | ||
| }, | ||
| "skill": { | ||
| "type": "string", | ||
| "description": "Name of an installed skill (kebab-case) the step will invoke. Must match an entry in the agent's skills/ directory, or 'approval' for a human-review step.", | ||
| "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$" | ||
| }, | ||
| "prompt": { | ||
| "type": "string", | ||
| "description": "The natural-language instruction passed to the skill for this step.", | ||
| "minLength": 1 | ||
| }, | ||
| "channel": { | ||
| "type": "string", | ||
| "description": "Optional channel/destination for the step output (e.g. a Slack channel name).", | ||
| "minLength": 1 | ||
| }, | ||
| "depends_on": { | ||
| "type": "array", | ||
| "description": "Optional list of step ids that must complete before this step runs.", | ||
| "items": { | ||
| "type": "string", | ||
| "pattern": "^[a-z0-9]+(_[a-z0-9]+)*$" | ||
| }, | ||
| "uniqueItems": true | ||
| }, | ||
| "requires_approval": { | ||
| "type": "boolean", | ||
| "description": "If true, the workflow pauses for human approval before this step runs." | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,243 @@ | ||
| import { existsSync } from "fs"; | ||
| import { mkdir, readFile, writeFile } from "fs/promises"; | ||
| import { join, resolve, sep } from "path"; | ||
| import { discoverSkills } from "../skills.js"; | ||
| import { validateSkillReferences, validateWorkflow } from "../utils/schemas.js"; | ||
| import { generateWorkflow, type LlmClient } from "../utils/workflow-generator.js"; | ||
|
|
||
| interface GenerateFlags { | ||
| dir: string; | ||
| prompt?: string; | ||
| refine?: string; | ||
| model?: string; | ||
| apiKey?: string; | ||
| dryRun: boolean; | ||
| force?: boolean; | ||
| allowMissingSkills?: boolean; | ||
| } | ||
|
|
||
| const RED = (s: string) => `\x1b[31m${s}\x1b[0m`; | ||
| const GREEN = (s: string) => `\x1b[32m${s}\x1b[0m`; | ||
| const DIM = (s: string) => `\x1b[2m${s}\x1b[0m`; | ||
| const BOLD = (s: string) => `\x1b[1m${s}\x1b[0m`; | ||
|
|
||
| const MAX_RETRIES = 2; | ||
|
|
||
| function printHelp(): void { | ||
| console.log(`${BOLD("gitagent workflow")} — generate SkillFlow workflows from natural language | ||
|
|
||
| Usage: | ||
| gitagent workflow generate [options] | ||
|
|
||
| Options: | ||
| -d, --dir <path> Agent directory (default: current directory) | ||
| -p, --prompt <text> Natural-language description of the workflow (required) | ||
| --refine <file> Refine an existing workflow YAML by applying --prompt as an instruction | ||
| (must be a path inside the agent directory) | ||
| -m, --model <spec> LLM model in provider:model form (default: openai:gpt-4o) | ||
| --api-key <key> API key for the provider (falls back to OPENAI_API_KEY or <PROVIDER>_API_KEY) | ||
| --dry-run Print the generated YAML to stdout instead of writing a file | ||
| -f, --force Overwrite workflows/<name>.yaml if it already exists | ||
| (without this flag an existing file is never replaced) | ||
| --allow-missing-skills | ||
| Accept steps that reference skills which are not installed | ||
| (by default generation fails rather than writing a workflow | ||
| that cannot run) | ||
| -h, --help Show this help message | ||
|
|
||
| Examples: | ||
| gitagent workflow generate -p "every morning summarize unread emails and post to Slack" | ||
| gitagent workflow generate -p "add a human approval step before the Slack post" --refine workflows/morning-digest.yaml | ||
| `); | ||
| } | ||
|
|
||
| // Reads the value that follows a flag, erroring out when the flag is the last | ||
| // token. Without this, argv[++i] yields undefined and the failure surfaces far | ||
| // from the parse site (e.g. resolve(undefined) throwing a bare TypeError). | ||
| function valueFor(argv: string[], i: number, flag: string): string { | ||
| const v = argv[i + 1]; | ||
| if (v === undefined) { | ||
| console.error(RED(`${flag} requires a value`)); | ||
| process.exit(2); | ||
| } | ||
| return v; | ||
| } | ||
|
|
||
| function parseFlags(argv: string[]): GenerateFlags { | ||
| const flags: GenerateFlags = { dir: process.cwd(), dryRun: false }; | ||
| for (let i = 0; i < argv.length; i++) { | ||
| const a = argv[i]; | ||
| switch (a) { | ||
| case "-d": | ||
| case "--dir": | ||
| flags.dir = valueFor(argv, i++, a); | ||
| break; | ||
| case "-p": | ||
| case "--prompt": | ||
| flags.prompt = valueFor(argv, i++, a); | ||
| break; | ||
| case "--refine": | ||
| flags.refine = valueFor(argv, i++, a); | ||
| break; | ||
| case "-m": | ||
| case "--model": | ||
| flags.model = valueFor(argv, i++, a); | ||
| break; | ||
| case "--api-key": | ||
| flags.apiKey = valueFor(argv, i++, a); | ||
| break; | ||
| case "--dry-run": | ||
| flags.dryRun = true; | ||
| break; | ||
| case "-f": | ||
| case "--force": | ||
| flags.force = true; | ||
| break; | ||
| case "--allow-missing-skills": | ||
| flags.allowMissingSkills = true; | ||
| break; | ||
| case "-h": | ||
| case "--help": | ||
| printHelp(); | ||
| process.exit(0); | ||
| break; | ||
| default: | ||
| if (!a.startsWith("-") && flags.prompt === undefined) { | ||
| flags.prompt = a; | ||
| } else { | ||
| console.error(RED(`Unknown option: ${a}`)); | ||
| process.exit(2); | ||
| } | ||
| } | ||
| } | ||
| return flags; | ||
| } | ||
|
|
||
| function slugify(name: string): string { | ||
| const cleaned = name | ||
| .toLowerCase() | ||
| .trim() | ||
| .replace(/[^a-z0-9-]+/g, "-") | ||
| .replace(/^-+|-+$/g, "") | ||
| .replace(/-+/g, "-"); | ||
| return cleaned || "workflow"; | ||
| } | ||
|
|
||
| export interface RunGenerateOptions { | ||
| flags: GenerateFlags; | ||
| llm?: LlmClient; | ||
| } | ||
|
|
||
| export async function runGenerate(opts: RunGenerateOptions): Promise<{ filePath?: string; yaml: string; }> { | ||
| const { flags } = opts; | ||
| if (!flags.prompt || !flags.prompt.trim()) { | ||
| throw new Error("--prompt is required"); | ||
| } | ||
|
|
||
| const agentDir = resolve(flags.dir); | ||
| const skills = await discoverSkills(agentDir); | ||
| const skillNames = skills.map((s) => s.name); | ||
|
|
||
| let previousWorkflow: string | undefined; | ||
| if (flags.refine) { | ||
| // resolve() ignores the base when the second argument is absolute, so an | ||
| // absolute path or a ../ traversal would otherwise read (and ship to the | ||
| // LLM) any file on disk. Keep --refine inside the agent directory. | ||
| const refinePath = resolve(agentDir, flags.refine); | ||
|
krishvsoni marked this conversation as resolved.
|
||
| if (refinePath !== agentDir && !refinePath.startsWith(agentDir + sep)) { | ||
| throw new Error(`--refine path must be inside the agent directory: ${refinePath}`); | ||
| } | ||
| previousWorkflow = await readFile(refinePath, "utf-8"); | ||
| } | ||
|
|
||
| let promptForLlm = flags.prompt.trim(); | ||
| let lastErrors: string[] = []; | ||
| let yaml = ""; | ||
|
|
||
| for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { | ||
| console.error(DIM(attempt === 0 ? "Generating workflow..." : `Retry ${attempt}/${MAX_RETRIES} — fixing validation errors...`)); | ||
| yaml = await generateWorkflow({ | ||
| prompt: promptForLlm, | ||
| skills, | ||
| previousWorkflow, | ||
| model: flags.model, | ||
| apiKey: flags.apiKey, | ||
| llm: opts.llm, | ||
| }); | ||
| const result = validateWorkflow(yaml); | ||
| // A schema-valid workflow can still name skills that aren't installed, | ||
| // which would only surface as a run-time failure. Fold that into the same | ||
| // retry loop so the model gets a chance to pick real skills. | ||
| const skillErrors = result.valid && !flags.allowMissingSkills | ||
| ? validateSkillReferences(result.data!, skillNames) | ||
| : []; | ||
| if (result.valid && skillErrors.length === 0) { | ||
| lastErrors = []; | ||
| break; | ||
| } | ||
| lastErrors = [...result.errors, ...skillErrors]; | ||
| if (attempt < MAX_RETRIES) { | ||
| promptForLlm = | ||
| `${flags.prompt.trim()}\n\nThe previous attempt failed schema validation or referenced skills that are not installed. Fix these errors and return the full YAML again:\n` + | ||
| lastErrors.map((e) => `- ${e}`).join("\n"); | ||
| } | ||
| } | ||
|
|
||
| if (lastErrors.length > 0) { | ||
| console.error(RED("\nWorkflow validation failed after retries:")); | ||
| for (const e of lastErrors) console.error(RED(` - ${e}`)); | ||
| if (lastErrors.some((e) => e.includes("is not an installed skill"))) { | ||
| console.error(DIM(`\nInstalled skills: ${skillNames.join(", ") || "(none)"}`)); | ||
| console.error( | ||
| DIM( | ||
| "Create the missing skill(s) under skills/ first, or re-run with --allow-missing-skills to write the workflow anyway.", | ||
| ), | ||
| ); | ||
| } | ||
| console.error(DIM("\nLast generated YAML:\n")); | ||
| console.error(yaml); | ||
| throw new Error("Validation failed after retries"); | ||
| } | ||
|
|
||
| if (flags.dryRun) { | ||
| process.stdout.write(yaml.endsWith("\n") ? yaml : yaml + "\n"); | ||
| return { yaml }; | ||
| } | ||
|
|
||
| // Parse the validated YAML to get the workflow name for the file path. | ||
|
krishvsoni marked this conversation as resolved.
|
||
| const validated = validateWorkflow(yaml).data!; | ||
| const slug = slugify(validated.name); | ||
| const workflowsDir = join(agentDir, "workflows"); | ||
| const filePath = join(workflowsDir, `${slug}.yaml`); | ||
| if (!flags.force && existsSync(filePath)) { | ||
| throw new Error( | ||
| `${filePath} already exists. Re-run with --force to overwrite it, or use --dry-run to preview the generated workflow.`, | ||
| ); | ||
| } | ||
| await mkdir(workflowsDir, { recursive: true }); | ||
| await writeFile(filePath, yaml.endsWith("\n") ? yaml : yaml + "\n", "utf-8"); | ||
| console.error(GREEN(`\nWrote workflow to ${filePath}`)); | ||
| return { filePath, yaml }; | ||
| } | ||
|
|
||
| export async function handleWorkflowCommand(argv: string[]): Promise<void> { | ||
| // argv is the raw process.argv tail starting at the 'workflow' token. | ||
| // argv[0] === "workflow"; argv[1] is the sub-command. | ||
| const sub = argv[1]; | ||
| if (!sub || sub === "-h" || sub === "--help") { | ||
| printHelp(); | ||
| return; | ||
| } | ||
| if (sub !== "generate") { | ||
| console.error(RED(`Unknown subcommand: ${sub}`)); | ||
| printHelp(); | ||
| process.exit(2); | ||
| } | ||
| const flags = parseFlags(argv.slice(2)); | ||
| try { | ||
| await runGenerate({ flags }); | ||
| } catch (err: any) { | ||
| console.error(RED(`\nError: ${err?.message ?? String(err)}`)); | ||
| process.exit(1); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.