From be131544fcb015fce464058d5debfc73f6db2aee Mon Sep 17 00:00:00 2001 From: Vignesh Date: Sun, 29 Nov 2026 04:12:34 +0530 Subject: [PATCH] refactor(agents): introduce AgentStepExecutor boundary Move provider-backed single-stage execution out of WorkflowEngine into ProviderStepExecutor behind a typed AgentStepExecutor interface. WorkflowEngine and runOrchestrator accept an optional executor; default behavior is unchanged. --- packages/agents/src/index.ts | 7 + packages/agents/src/orchestrator/index.ts | 9 +- packages/agents/src/workflow/engine.ts | 536 +----------------- .../src/workflow/provider-step-executor.ts | 515 +++++++++++++++++ packages/agents/src/workflow/step-executor.ts | 30 + packages/agents/test/step-executor.test.ts | 81 +++ 6 files changed, 659 insertions(+), 519 deletions(-) create mode 100644 packages/agents/src/workflow/provider-step-executor.ts create mode 100644 packages/agents/src/workflow/step-executor.ts create mode 100644 packages/agents/test/step-executor.test.ts diff --git a/packages/agents/src/index.ts b/packages/agents/src/index.ts index 02353a4..353ebf2 100644 --- a/packages/agents/src/index.ts +++ b/packages/agents/src/index.ts @@ -30,6 +30,13 @@ export type { WorkflowEmit, } from "./workflow/types.js"; export type { WorkflowEngineOptions, WorkflowRunMeta } from "./workflow/engine.js"; +export { ProviderStepExecutor } from "./workflow/provider-step-executor.js"; +export type { ProviderStepExecutorOptions } from "./workflow/provider-step-executor.js"; +export type { + AgentStepExecutor, + StepExecutionRequest, + StepExecutionResult, +} from "./workflow/step-executor.js"; // base export type { AgentRunResult, AgentRuntimeControls } from "./agents/base.agent.js"; diff --git a/packages/agents/src/orchestrator/index.ts b/packages/agents/src/orchestrator/index.ts index 0e7e032..4781e22 100644 --- a/packages/agents/src/orchestrator/index.ts +++ b/packages/agents/src/orchestrator/index.ts @@ -27,6 +27,7 @@ import { } from "../provider/mock.data.js"; import { SkillRegistry } from "../skills/registry.js"; import { WorkflowEngine } from "../workflow/engine.js"; +import type { AgentStepExecutor } from "../workflow/step-executor.js"; import { selectWorkflow } from "../workflow/router.js"; import type { WorkflowDefinition, WorkflowState } from "../workflow/types.js"; @@ -38,6 +39,8 @@ export type OrchestratorOptions = { emit: (event: SSEEvent) => void; provider: LLMProvider; cache: AgentCache; + /** Overrides the default provider-backed step execution (mock/replay testing). */ + executor?: AgentStepExecutor; }; type ResolvedExecution = { @@ -588,7 +591,7 @@ async function getSkillRegistry(): Promise { } export async function runOrchestrator(options: OrchestratorOptions): Promise { - const { jobId, prompt, projectName, execution, emit, provider, cache } = options; + const { jobId, prompt, projectName, execution, emit, provider, cache, executor } = options; const resolvedExecution = resolveExecution(execution); const skillRegistry = await getSkillRegistry(); @@ -598,10 +601,8 @@ export async function runOrchestrator(options: OrchestratorOptions): Promise; @@ -17,242 +9,23 @@ export type WorkflowRunMeta = { tokensByAgent: Partial>; }; +/** + * Pass `executor` to supply your own step execution, or pass + * `provider` + `cache` + `skillRegistry` to use the default ProviderStepExecutor. + */ export type WorkflowEngineOptions = { jobId: string; userGoal: string; - provider: LLMProvider; - cache: AgentCache; emit: WorkflowEmit; - skillRegistry: SkillRegistry; -}; - -function nowIso(): string { - return new Date().toISOString(); -} - -function estimateTokens(text: string): number { - const normalized = text.trim(); - if (normalized.length === 0) { - return 0; - } - - return Math.max(1, Math.ceil(normalized.length / 4)); -} - -function serializeOutput(value: unknown): string { - if (typeof value === "string") { - return value; - } - - try { - return JSON.stringify(value, null, 2); - } catch { - return String(value); - } -} - -function compactStateForPrompt(state: WorkflowState): string { - const entries = Object.entries(state); - if (entries.length === 0) { - return "(no previous step output yet)"; - } - - return entries - .map(([key, value]) => { - const normalized = value.length > 2000 ? `${value.slice(0, 2000)}\n...(truncated)` : value; - return `## ${key}\n${normalized}`; - }) - .join("\n\n"); -} - -function buildStepUserPrompt(step: WorkflowStep, skillBody: string, goal: string, state: WorkflowState): string { - return [ - `Workflow step: ${step.id}`, - `Target state key: ${step.stateKey}`, - "", - "Original user goal:", - goal, - "", - "Current workflow context:", - compactStateForPrompt(state), - "", - "Active skill instructions:", - skillBody, - "", - "Return strict JSON object output for this step.", - ].join("\n"); -} - -function buildCompressionPrompt(compressionTarget: number, stepOutputText: string): string { - return [ - `Summarise the following in under ${compressionTarget} tokens, preserving all file names,`, - "technology decisions, and structural choices. Omit code implementations:", - "Return strict JSON only in this exact shape: { \"summary\": string }.", - stepOutputText, - ].join("\n"); -} - -function toCompressedString(output: unknown): string { - if (typeof output === "string") { - return output.trim(); - } - - if (output !== null && typeof output === "object" && !Array.isArray(output)) { - const summaryCandidate = (output as Record)["summary"]; - if (typeof summaryCandidate === "string" && summaryCandidate.trim().length > 0) { - return summaryCandidate.trim(); - } - } - - return serializeOutput(output).trim(); -} - -function fallbackCompress(stepOutputText: string, compressionTarget: number): string { - const normalized = stepOutputText.trim(); - if (normalized.length === 0) { - return "{}"; - } - - const maxChars = Math.max(320, compressionTarget * 8); - if (normalized.length <= maxChars) { - return normalized; - } - - return `${normalized.slice(0, maxChars)}\n...(compression fallback: truncated)`; -} - -function hasRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function validateStepOutput(step: WorkflowStep, output: unknown): void { - // Special handling for codegen which can be either string or record - if (step.stateKey === "codegen") { - const isString = typeof output === "string"; - if (isString) { - // Convert string output to structured format for downstream processing - return; // String is valid, will be wrapped when processing - } - if (!hasRecord(output)) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - const hasGeneratedFiles = Array.isArray(output["generatedSourceFiles"]); - const hasFileMap = hasRecord(output["files"]); - if (!hasGeneratedFiles && !hasFileMap) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - - if (!hasRecord(output)) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - - switch (step.stateKey) { - case "plan": { - const hasProjectName = typeof output["projectName"] === "string"; - const hasStack = hasRecord(output["stack"]); - const hasFolder = Array.isArray(output["folderStructure"]); - if (!hasProjectName || !hasStack || !hasFolder) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - case "schema": { - if (!Array.isArray(output["entities"]) || !Array.isArray(output["relationships"])) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - case "api": { - if (!Array.isArray(output["routePlan"])) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - case "frontend": { - if (!Array.isArray(output["frontendPages"])) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - case "devops": { - const hasInfra = hasRecord(output["infraPlan"]); - const hasFilesPlan = Array.isArray(output["generatedFilesPlan"]); - if (!hasInfra || !hasFilesPlan) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - case "reviewer": { - if (!Array.isArray(output["reviewerNotes"])) { - throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); - } - return; - } - default: - return; - } -} - -function agentStarted(jobId: string, agent: AgentName): SSEEvent { - return { type: "agent_started", jobId, agent, timestamp: nowIso(), payload: {} }; -} - -function agentToken(jobId: string, agentId: AgentName, token: string): SSEEvent { - return { - type: "agent_token", - jobId, - agentId, - token, - timestamp: Date.now(), - }; -} - -function agentComplete(jobId: string, agentId: AgentName, fullOutput: unknown): SSEEvent { - return { - type: "agent_complete", - jobId, - agentId, - fullOutput, - timestamp: Date.now(), - }; -} - -function agentCompleted( - jobId: string, - agent: AgentName, - payload: { - durationMs: number; - cached: boolean; - inputTokens: number; - outputTokens: number; - totalTokens: number; - tokensUsed: number; - estimatedInputTokens: number; - compressionPasses: number; - providerInputTokens: number; - providerOutputTokens: number; - model: string; - }, -): SSEEvent { - return { - type: "agent_completed", - jobId, - agent, - timestamp: nowIso(), - payload, - }; -} - -function agentFailed(jobId: string, agent: AgentName, error: string): SSEEvent { - return { type: "agent_failed", jobId, agent, timestamp: nowIso(), payload: { error } }; -} +} & ({ executor: AgentStepExecutor } | ProviderStepExecutorOptions); export class WorkflowEngine { private lastRunMeta: WorkflowRunMeta | undefined; + private readonly executor: AgentStepExecutor; - constructor(private readonly options: WorkflowEngineOptions) {} + constructor(private readonly options: WorkflowEngineOptions) { + this.executor = "executor" in options ? options.executor : new ProviderStepExecutor(options); + } getLastRunMeta(): WorkflowRunMeta | undefined { return this.lastRunMeta; @@ -265,7 +38,14 @@ export class WorkflowEngine { let totalTokensUsed = 0; for (const step of workflow.steps) { - const stepResult = await this.runStep(workflow, step, state); + const stepResult = await this.executor.execute({ + jobId: this.options.jobId, + goal: this.options.userGoal, + workflow, + step, + state, + emit: this.options.emit, + }); state[step.stateKey] = stepResult.compressedOutput; rawOutputsByStateKey[step.stateKey] = stepResult.rawOutput; @@ -281,278 +61,4 @@ export class WorkflowEngine { return state; } - - private async runStep( - workflow: WorkflowDefinition, - step: WorkflowStep, - state: WorkflowState, - ): Promise { - const skillBody = await this.options.skillRegistry.loadSkill(step.skill); - const config = AGENT_CONFIGS[step.agent]; - const userPrompt = buildStepUserPrompt(step, skillBody, this.options.userGoal, state); - const estimatedInputTokens = estimateTokens(userPrompt) + estimateTokens(skillBody); - - this.options.emit(agentStarted(this.options.jobId, step.agent)); - - let primary: ProviderCallOutput; - let cachedPrimary = false; - const primaryCacheKey = this.options.cache.hash({ - type: "workflow-step", - workflowId: workflow.id, - stepId: step.id, - skill: step.skill, - prompt: userPrompt, - model: config.model, - maxOutputTokens: config.maxOutputTokens, - }); - - try { - const primaryCachedEntry = this.options.cache.get(primaryCacheKey); - if (primaryCachedEntry !== undefined) { - cachedPrimary = true; - primary = { - output: primaryCachedEntry.output, - tokensUsed: 0, - durationMs: 0, - inputTokens: 0, - outputTokens: 0, - model: config.model, - }; - } else { - const streamedChunks: string[] = []; - primary = await this.options.provider.call({ - agentName: step.agent, - input: { - workflowId: workflow.id, - stepId: step.id, - stepSkill: step.skill, - goal: this.options.userGoal, - state, - }, - options: { - systemPrompt: "Execute the requested workflow step and return strict JSON object output only.", - userPrompt, - model: config.model, - maxInputTokens: config.maxInputTokens, - maxOutputTokens: config.maxOutputTokens, - temperature: config.temperature, - }, - onToken: (chunk) => { - if (chunk.length === 0) { - return; - } - streamedChunks.push(chunk); - this.options.emit(agentToken(this.options.jobId, step.agent, chunk)); - }, - }); - - this.options.cache.set(primaryCacheKey, primary.output); - - // If provider responded without streaming callback, emit the full output once for UI parity. - if (streamedChunks.length === 0) { - const fallbackToken = serializeOutput(primary.output); - if (fallbackToken.length > 0) { - this.options.emit(agentToken(this.options.jobId, step.agent, fallbackToken)); - } - } - } - - try { - validateStepOutput(step, primary.output); - } catch (validationError) { - // One self-correction pass: weak/free models frequently emit malformed - // or incomplete JSON. Rather than fail the whole job, show the model its - // own output plus the validation error and ask for a corrected version. - const repaired = await this.attemptRepair( - workflow, - step, - config, - userPrompt, - primary.output, - validationError instanceof Error ? validationError.message : String(validationError), - ); - primary = { - ...primary, - output: repaired.output, - tokensUsed: primary.tokensUsed + repaired.tokensUsed, - }; - this.options.cache.set(primaryCacheKey, primary.output); - validateStepOutput(step, primary.output); - } - - // Convert raw code string to structured format for codegen - let normalizedOutput = primary.output; - if (step.agent === "codegen" && typeof primary.output === "string") { - normalizedOutput = { - generatedSourceFiles: [ - { - path: "generated-code.ts", - language: "typescript", - content: primary.output, - }, - ], - }; - } - - this.options.emit(agentComplete(this.options.jobId, step.agent, normalizedOutput)); - - const providerInputTokens = primary.inputTokens ?? estimatedInputTokens; - const serializedPrimary = serializeOutput(normalizedOutput); - const providerOutputTokens = primary.outputTokens ?? estimateTokens(serializedPrimary); - const totalTokens = primary.tokensUsed > 0 - ? primary.tokensUsed - : providerInputTokens + providerOutputTokens; - - this.options.emit( - agentCompleted(this.options.jobId, step.agent, { - durationMs: primary.durationMs, - cached: cachedPrimary, - inputTokens: providerInputTokens, - outputTokens: providerOutputTokens, - totalTokens, - tokensUsed: totalTokens, - estimatedInputTokens, - compressionPasses: 1, - providerInputTokens, - providerOutputTokens, - model: primary.model ?? config.model, - }), - ); - - if (step.agent === "codegen") { - return { - rawOutput: normalizedOutput, - compressedOutput: serializeOutput(normalizedOutput), - tokensUsed: totalTokens, - }; - } - - const compressedOutput = await this.compressStepOutput( - workflow, - step, - normalizedOutput, - config.model, - config.temperature, - ); - - return { - rawOutput: normalizedOutput, - compressedOutput: compressedOutput.text, - tokensUsed: totalTokens + compressedOutput.tokensUsed, - }; - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.options.emit(agentFailed(this.options.jobId, step.agent, message)); - throw error; - } - } - - private async attemptRepair( - workflow: WorkflowDefinition, - step: WorkflowStep, - config: AgentConfig, - originalUserPrompt: string, - badOutput: unknown, - validationError: string, - ): Promise<{ output: unknown; tokensUsed: number }> { - const repairPrompt = [ - "Your previous response for this workflow step was invalid and must be corrected.", - "", - `Validation error: ${validationError}`, - "", - "Your previous (invalid) output was:", - serializeOutput(badOutput), - "", - "Original step instructions:", - originalUserPrompt, - "", - "Return ONLY the corrected, strict JSON object for this step. No markdown, no code fences, no commentary.", - ].join("\n"); - - const response = await this.options.provider.call({ - agentName: step.agent, - input: { - workflowId: workflow.id, - stepId: step.id, - repair: true, - }, - options: { - systemPrompt: - "You repair invalid workflow-step output. Return strict JSON object output only that satisfies the stated schema.", - userPrompt: repairPrompt, - model: config.model, - maxInputTokens: config.maxInputTokens, - maxOutputTokens: config.maxOutputTokens, - temperature: 0, - }, - }); - - return { - output: response.output, - tokensUsed: response.tokensUsed, - }; - } - - private async compressStepOutput( - workflow: WorkflowDefinition, - step: WorkflowStep, - stepOutput: unknown, - model: string, - temperature: number, - ): Promise<{ text: string; tokensUsed: number }> { - const stepOutputText = serializeOutput(stepOutput); - const prompt = buildCompressionPrompt(step.compressionTarget, stepOutputText); - - const cacheKey = this.options.cache.hash({ - type: "workflow-compression", - workflowId: workflow.id, - stepId: step.id, - target: step.compressionTarget, - model, - prompt, - }); - - const cached = this.options.cache.get(cacheKey); - if (cached !== undefined) { - return { - text: toCompressedString(cached.output), - tokensUsed: 0, - }; - } - - const response = await this.options.provider.call({ - agentName: step.agent, - input: { - workflowId: workflow.id, - stepId: step.id, - compressionTarget: step.compressionTarget, - }, - options: { - systemPrompt: "You compress structured output without dropping key architecture details. Return strict JSON object output only.", - userPrompt: prompt, - model, - maxInputTokens: Math.max(128, step.compressionTarget * 4), - maxOutputTokens: Math.max(64, step.compressionTarget + 80), - temperature: Math.min(temperature, 0.2), - }, - }).catch((error) => { - const message = error instanceof Error ? error.message : String(error); - process.stderr.write( - `[workflow] compression fallback for ${workflow.id}/${step.id}: ${message}\n`, - ); - - return { - output: { summary: fallbackCompress(stepOutputText, step.compressionTarget) }, - tokensUsed: 0, - durationMs: 0, - } as ProviderCallOutput; - }); - - this.options.cache.set(cacheKey, response.output); - - return { - text: toCompressedString(response.output), - tokensUsed: response.tokensUsed, - }; - } } diff --git a/packages/agents/src/workflow/provider-step-executor.ts b/packages/agents/src/workflow/provider-step-executor.ts new file mode 100644 index 0000000..8f801e4 --- /dev/null +++ b/packages/agents/src/workflow/provider-step-executor.ts @@ -0,0 +1,515 @@ +import type { AgentName, AgentConfig, SSEEvent } from "@stackforge/shared"; +import { AGENT_CONFIGS } from "../config/agent.configs.js"; +import type { AgentCache } from "../cache/agent.cache.js"; +import type { LLMProvider, ProviderCallOutput } from "../provider/provider.interface.js"; +import type { SkillRegistry } from "../skills/registry.js"; +import type { WorkflowDefinition, WorkflowStep, WorkflowState } from "./types.js"; +import type { AgentStepExecutor, StepExecutionRequest, StepExecutionResult } from "./step-executor.js"; + +export type ProviderStepExecutorOptions = { + provider: LLMProvider; + cache: AgentCache; + skillRegistry: SkillRegistry; +}; + +function nowIso(): string { + return new Date().toISOString(); +} + +function estimateTokens(text: string): number { + const normalized = text.trim(); + if (normalized.length === 0) { + return 0; + } + + return Math.max(1, Math.ceil(normalized.length / 4)); +} + +function serializeOutput(value: unknown): string { + if (typeof value === "string") { + return value; + } + + try { + return JSON.stringify(value, null, 2); + } catch { + return String(value); + } +} + +function compactStateForPrompt(state: WorkflowState): string { + const entries = Object.entries(state); + if (entries.length === 0) { + return "(no previous step output yet)"; + } + + return entries + .map(([key, value]) => { + const normalized = value.length > 2000 ? `${value.slice(0, 2000)}\n...(truncated)` : value; + return `## ${key}\n${normalized}`; + }) + .join("\n\n"); +} + +function buildStepUserPrompt(step: WorkflowStep, skillBody: string, goal: string, state: WorkflowState): string { + return [ + `Workflow step: ${step.id}`, + `Target state key: ${step.stateKey}`, + "", + "Original user goal:", + goal, + "", + "Current workflow context:", + compactStateForPrompt(state), + "", + "Active skill instructions:", + skillBody, + "", + "Return strict JSON object output for this step.", + ].join("\n"); +} + +function buildCompressionPrompt(compressionTarget: number, stepOutputText: string): string { + return [ + `Summarise the following in under ${compressionTarget} tokens, preserving all file names,`, + "technology decisions, and structural choices. Omit code implementations:", + "Return strict JSON only in this exact shape: { \"summary\": string }.", + stepOutputText, + ].join("\n"); +} + +function toCompressedString(output: unknown): string { + if (typeof output === "string") { + return output.trim(); + } + + if (output !== null && typeof output === "object" && !Array.isArray(output)) { + const summaryCandidate = (output as Record)["summary"]; + if (typeof summaryCandidate === "string" && summaryCandidate.trim().length > 0) { + return summaryCandidate.trim(); + } + } + + return serializeOutput(output).trim(); +} + +function fallbackCompress(stepOutputText: string, compressionTarget: number): string { + const normalized = stepOutputText.trim(); + if (normalized.length === 0) { + return "{}"; + } + + const maxChars = Math.max(320, compressionTarget * 8); + if (normalized.length <= maxChars) { + return normalized; + } + + return `${normalized.slice(0, maxChars)}\n...(compression fallback: truncated)`; +} + +function hasRecord(value: unknown): value is Record { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function validateStepOutput(step: WorkflowStep, output: unknown): void { + // Special handling for codegen which can be either string or record + if (step.stateKey === "codegen") { + const isString = typeof output === "string"; + if (isString) { + // Convert string output to structured format for downstream processing + return; // String is valid, will be wrapped when processing + } + if (!hasRecord(output)) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + const hasGeneratedFiles = Array.isArray(output["generatedSourceFiles"]); + const hasFileMap = hasRecord(output["files"]); + if (!hasGeneratedFiles && !hasFileMap) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + + if (!hasRecord(output)) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + + switch (step.stateKey) { + case "plan": { + const hasProjectName = typeof output["projectName"] === "string"; + const hasStack = hasRecord(output["stack"]); + const hasFolder = Array.isArray(output["folderStructure"]); + if (!hasProjectName || !hasStack || !hasFolder) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + case "schema": { + if (!Array.isArray(output["entities"]) || !Array.isArray(output["relationships"])) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + case "api": { + if (!Array.isArray(output["routePlan"])) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + case "frontend": { + if (!Array.isArray(output["frontendPages"])) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + case "devops": { + const hasInfra = hasRecord(output["infraPlan"]); + const hasFilesPlan = Array.isArray(output["generatedFilesPlan"]); + if (!hasInfra || !hasFilesPlan) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + case "reviewer": { + if (!Array.isArray(output["reviewerNotes"])) { + throw new Error(`Invalid output shape for step '${step.id}' (${step.stateKey})`); + } + return; + } + default: + return; + } +} + +function agentStarted(jobId: string, agent: AgentName): SSEEvent { + return { type: "agent_started", jobId, agent, timestamp: nowIso(), payload: {} }; +} + +function agentToken(jobId: string, agentId: AgentName, token: string): SSEEvent { + return { + type: "agent_token", + jobId, + agentId, + token, + timestamp: Date.now(), + }; +} + +function agentComplete(jobId: string, agentId: AgentName, fullOutput: unknown): SSEEvent { + return { + type: "agent_complete", + jobId, + agentId, + fullOutput, + timestamp: Date.now(), + }; +} + +function agentCompleted( + jobId: string, + agent: AgentName, + payload: { + durationMs: number; + cached: boolean; + inputTokens: number; + outputTokens: number; + totalTokens: number; + tokensUsed: number; + estimatedInputTokens: number; + compressionPasses: number; + providerInputTokens: number; + providerOutputTokens: number; + model: string; + }, +): SSEEvent { + return { + type: "agent_completed", + jobId, + agent, + timestamp: nowIso(), + payload, + }; +} + +function agentFailed(jobId: string, agent: AgentName, error: string): SSEEvent { + return { type: "agent_failed", jobId, agent, timestamp: nowIso(), payload: { error } }; +} + +/** + * Default AgentStepExecutor: runs one stage through an LLMProvider with + * caching, streaming, output validation, one repair pass, and compression. + */ +export class ProviderStepExecutor implements AgentStepExecutor { + constructor(private readonly options: ProviderStepExecutorOptions) {} + + async execute(request: StepExecutionRequest): Promise { + const { workflow, step, state, jobId, goal, emit } = request; + const skillBody = await this.options.skillRegistry.loadSkill(step.skill); + const config = AGENT_CONFIGS[step.agent]; + const userPrompt = buildStepUserPrompt(step, skillBody, goal, state); + const estimatedInputTokens = estimateTokens(userPrompt) + estimateTokens(skillBody); + + emit(agentStarted(jobId, step.agent)); + + let primary: ProviderCallOutput; + let cachedPrimary = false; + const primaryCacheKey = this.options.cache.hash({ + type: "workflow-step", + workflowId: workflow.id, + stepId: step.id, + skill: step.skill, + prompt: userPrompt, + model: config.model, + maxOutputTokens: config.maxOutputTokens, + }); + + try { + const primaryCachedEntry = this.options.cache.get(primaryCacheKey); + if (primaryCachedEntry !== undefined) { + cachedPrimary = true; + primary = { + output: primaryCachedEntry.output, + tokensUsed: 0, + durationMs: 0, + inputTokens: 0, + outputTokens: 0, + model: config.model, + }; + } else { + const streamedChunks: string[] = []; + primary = await this.options.provider.call({ + agentName: step.agent, + input: { + workflowId: workflow.id, + stepId: step.id, + stepSkill: step.skill, + goal: goal, + state, + }, + options: { + systemPrompt: "Execute the requested workflow step and return strict JSON object output only.", + userPrompt, + model: config.model, + maxInputTokens: config.maxInputTokens, + maxOutputTokens: config.maxOutputTokens, + temperature: config.temperature, + }, + onToken: (chunk) => { + if (chunk.length === 0) { + return; + } + streamedChunks.push(chunk); + emit(agentToken(jobId, step.agent, chunk)); + }, + }); + + this.options.cache.set(primaryCacheKey, primary.output); + + // If provider responded without streaming callback, emit the full output once for UI parity. + if (streamedChunks.length === 0) { + const fallbackToken = serializeOutput(primary.output); + if (fallbackToken.length > 0) { + emit(agentToken(jobId, step.agent, fallbackToken)); + } + } + } + + try { + validateStepOutput(step, primary.output); + } catch (validationError) { + // One self-correction pass: weak/free models frequently emit malformed + // or incomplete JSON. Rather than fail the whole job, show the model its + // own output plus the validation error and ask for a corrected version. + const repaired = await this.attemptRepair( + workflow, + step, + config, + userPrompt, + primary.output, + validationError instanceof Error ? validationError.message : String(validationError), + ); + primary = { + ...primary, + output: repaired.output, + tokensUsed: primary.tokensUsed + repaired.tokensUsed, + }; + this.options.cache.set(primaryCacheKey, primary.output); + validateStepOutput(step, primary.output); + } + + // Convert raw code string to structured format for codegen + let normalizedOutput = primary.output; + if (step.agent === "codegen" && typeof primary.output === "string") { + normalizedOutput = { + generatedSourceFiles: [ + { + path: "generated-code.ts", + language: "typescript", + content: primary.output, + }, + ], + }; + } + + emit(agentComplete(jobId, step.agent, normalizedOutput)); + + const providerInputTokens = primary.inputTokens ?? estimatedInputTokens; + const serializedPrimary = serializeOutput(normalizedOutput); + const providerOutputTokens = primary.outputTokens ?? estimateTokens(serializedPrimary); + const totalTokens = primary.tokensUsed > 0 + ? primary.tokensUsed + : providerInputTokens + providerOutputTokens; + + emit( + agentCompleted(jobId, step.agent, { + durationMs: primary.durationMs, + cached: cachedPrimary, + inputTokens: providerInputTokens, + outputTokens: providerOutputTokens, + totalTokens, + tokensUsed: totalTokens, + estimatedInputTokens, + compressionPasses: 1, + providerInputTokens, + providerOutputTokens, + model: primary.model ?? config.model, + }), + ); + + if (step.agent === "codegen") { + return { + rawOutput: normalizedOutput, + compressedOutput: serializeOutput(normalizedOutput), + tokensUsed: totalTokens, + }; + } + + const compressedOutput = await this.compressStepOutput( + workflow, + step, + normalizedOutput, + config.model, + config.temperature, + ); + + return { + rawOutput: normalizedOutput, + compressedOutput: compressedOutput.text, + tokensUsed: totalTokens + compressedOutput.tokensUsed, + }; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + emit(agentFailed(jobId, step.agent, message)); + throw error; + } + } + + private async attemptRepair( + workflow: WorkflowDefinition, + step: WorkflowStep, + config: AgentConfig, + originalUserPrompt: string, + badOutput: unknown, + validationError: string, + ): Promise<{ output: unknown; tokensUsed: number }> { + const repairPrompt = [ + "Your previous response for this workflow step was invalid and must be corrected.", + "", + `Validation error: ${validationError}`, + "", + "Your previous (invalid) output was:", + serializeOutput(badOutput), + "", + "Original step instructions:", + originalUserPrompt, + "", + "Return ONLY the corrected, strict JSON object for this step. No markdown, no code fences, no commentary.", + ].join("\n"); + + const response = await this.options.provider.call({ + agentName: step.agent, + input: { + workflowId: workflow.id, + stepId: step.id, + repair: true, + }, + options: { + systemPrompt: + "You repair invalid workflow-step output. Return strict JSON object output only that satisfies the stated schema.", + userPrompt: repairPrompt, + model: config.model, + maxInputTokens: config.maxInputTokens, + maxOutputTokens: config.maxOutputTokens, + temperature: 0, + }, + }); + + return { + output: response.output, + tokensUsed: response.tokensUsed, + }; + } + + private async compressStepOutput( + workflow: WorkflowDefinition, + step: WorkflowStep, + stepOutput: unknown, + model: string, + temperature: number, + ): Promise<{ text: string; tokensUsed: number }> { + const stepOutputText = serializeOutput(stepOutput); + const prompt = buildCompressionPrompt(step.compressionTarget, stepOutputText); + + const cacheKey = this.options.cache.hash({ + type: "workflow-compression", + workflowId: workflow.id, + stepId: step.id, + target: step.compressionTarget, + model, + prompt, + }); + + const cached = this.options.cache.get(cacheKey); + if (cached !== undefined) { + return { + text: toCompressedString(cached.output), + tokensUsed: 0, + }; + } + + const response = await this.options.provider.call({ + agentName: step.agent, + input: { + workflowId: workflow.id, + stepId: step.id, + compressionTarget: step.compressionTarget, + }, + options: { + systemPrompt: "You compress structured output without dropping key architecture details. Return strict JSON object output only.", + userPrompt: prompt, + model, + maxInputTokens: Math.max(128, step.compressionTarget * 4), + maxOutputTokens: Math.max(64, step.compressionTarget + 80), + temperature: Math.min(temperature, 0.2), + }, + }).catch((error) => { + const message = error instanceof Error ? error.message : String(error); + process.stderr.write( + `[workflow] compression fallback for ${workflow.id}/${step.id}: ${message}\n`, + ); + + return { + output: { summary: fallbackCompress(stepOutputText, step.compressionTarget) }, + tokensUsed: 0, + durationMs: 0, + } as ProviderCallOutput; + }); + + this.options.cache.set(cacheKey, response.output); + + return { + text: toCompressedString(response.output), + tokensUsed: response.tokensUsed, + }; + } +} diff --git a/packages/agents/src/workflow/step-executor.ts b/packages/agents/src/workflow/step-executor.ts new file mode 100644 index 0000000..7a854f6 --- /dev/null +++ b/packages/agents/src/workflow/step-executor.ts @@ -0,0 +1,30 @@ +import type { WorkflowDefinition, WorkflowEmit, WorkflowState, WorkflowStep } from "./types.js"; + +export type StepExecutionRequest = { + jobId: string; + goal: string; + workflow: WorkflowDefinition; + step: WorkflowStep; + /** Compressed outputs of previously completed steps, keyed by stateKey. */ + state: WorkflowState; + /** The executor is responsible for emitting this step's SSE events. */ + emit: WorkflowEmit; +}; + +export type StepExecutionResult = { + /** Structured output used to assemble the blueprint. */ + rawOutput: unknown; + /** Compact form handed to later steps as context. */ + compressedOutput: string; + tokensUsed: number; +}; + +/** + * Executes a single pipeline stage (planner, schema, api, frontend, devops, + * reviewer, codegen). Implementations throw on failure after emitting + * `agent_failed`. WorkflowEngine owns ordering and state; it knows nothing + * about providers, prompts, or caching. + */ +export interface AgentStepExecutor { + execute(request: StepExecutionRequest): Promise; +} diff --git a/packages/agents/test/step-executor.test.ts b/packages/agents/test/step-executor.test.ts new file mode 100644 index 0000000..794596d --- /dev/null +++ b/packages/agents/test/step-executor.test.ts @@ -0,0 +1,81 @@ +/// +import { describe, expect, it } from "bun:test"; +import type { SSEEvent } from "@stackforge/shared"; +import { AgentCache } from "../src/cache/agent.cache.js"; +import { MockProvider } from "../src/provider/mock.provider.js"; +import { runOrchestrator } from "../src/orchestrator/index.js"; +import type { AgentStepExecutor } from "../src/workflow/step-executor.js"; +import { + buildApiOutput, + buildCodegenOutput, + buildDevopsOutput, + buildFrontendOutput, + buildPlannerOutput, + buildReviewerOutput, + buildSchemaOutput, +} from "../src/provider/mock.data.js"; + +describe("AgentStepExecutor boundary", () => { + it("runOrchestrator uses a supplied executor instead of the provider", async () => { + const calledAgents: string[] = []; + const executor: AgentStepExecutor = { + async execute({ step }) { + calledAgents.push(step.agent); + const outputs: Record = { + plan: buildPlannerOutput("exec-test"), + schema: buildSchemaOutput(), + api: buildApiOutput(), + frontend: buildFrontendOutput(), + devops: buildDevopsOutput("exec-test"), + reviewer: buildReviewerOutput(), + codegen: buildCodegenOutput("exec-test"), + }; + return { rawOutput: outputs[step.stateKey], compressedOutput: "{}", tokensUsed: 1 }; + }, + }; + + const provider = new MockProvider(); + let providerCalls = 0; + const originalCall = provider.call.bind(provider); + provider.call = (input) => { + providerCalls += 1; + return originalCall(input); + }; + + const events: SSEEvent[] = []; + const blueprint = await runOrchestrator({ + jobId: "job-exec", + prompt: "Build a task tracker", + projectName: "exec-test", + emit: (event) => events.push(event), + provider, + cache: new AgentCache(), + executor, + }); + + expect(calledAgents).toEqual(["planner", "schema", "api", "frontend", "devops", "reviewer", "codegen"]); + expect(providerCalls).toBe(0); + expect(blueprint.projectName).toBe("exec-test"); + }); + + it("propagates executor failures", async () => { + const executor: AgentStepExecutor = { + async execute({ step }) { + if (step.agent === "api") throw new Error("api stage exploded"); + return { rawOutput: {}, compressedOutput: "{}", tokensUsed: 0 }; + }, + }; + + await expect( + runOrchestrator({ + jobId: "job-fail", + prompt: "Build a task tracker", + projectName: "x", + emit: () => {}, + provider: new MockProvider(), + cache: new AgentCache(), + executor, + }), + ).rejects.toThrow("api stage exploded"); + }); +});