X402 Workflow Engine
The “X402” workflow is implemented inlib/x402.ts and used by the Idea → Intent → Platform → Payment → Execute → Completion flow. It manages:
- Stages —
WorkflowStageand transitions - Context —
WorkflowContextwith all stage outputs - Persistence —
getWorkflowContextDB,updateWorkflowContextDB,createWorkflowContextDB(Prisma); in-memorygetWorkflowContext,updateWorkflowContext,createWorkflowContextas fallback
Workflow Stages
| Stage | API / Trigger | Main data produced |
|---|---|---|
| idea_input | POST /api/idea | idea, analysis, clarifyingQuestions |
| intent_analysis | POST /api/intent | answers, refinedRequirements |
| platform_selection | POST /api/platform | platformOptions, selectedPlatform (later), supabaseIntegration |
| payment_processing | POST /api/payment or Dodo | paymentDetails (wallet/signature or dodoPaymentId) |
| execution | POST /api/execute | executionResult |
| completion | — | UI only; uses executionResult |
State Management
WorkflowContext
WorkflowContext in lib/x402.ts:
sessionId,currentStage,createdAt,updatedAtidea,analysis,clarifyingQuestions,answers,refinedRequirementsplatformOptions,selectedPlatform,supabaseIntegrationpaymentDetails(e.g.walletAddress,amountScript,transactionSignature,paymentMethod,dodoPaymentId)executionResult(agents, deliverables,review_passed, etc.)
Persistence
- DB (preferred):
getWorkflowContextDB,createWorkflowContextDB,updateWorkflowContextDBmap to theWorkflowmodel inprisma/schema.prisma. Some fields (e.g.platformOptions,executionResult) are not fully stored in DB; the code merges with in-memory when needed. - In-memory:
workflowStore = new Map<string, WorkflowContext>(). Used when DB calls fail or for backwards compatibility.
execute can rebuild a minimal context from prisma.workflow if the full context is missing.
Transitions
getNextStage(current)— Returns the next stage in order, ornullatcompletion.validateStageTransition(from, to)— Allows same stage or the immediate next stage only.
Error Handling
- Missing context — Idea: create context if new
sessionId. Intent/Platform/Payment/Execute: return 400 with a message to restart or complete the previous stage; Execute may try to rebuild from DB. - DB vs in-memory — On Prisma/connection errors, APIs log and fall back to in-memory; some fields (e.g.
platformOptions) may be missing if only in memory. - Execute-specific:
- No
refinedRequirements→ build minimal fromideaif present, else 400. - No
selectedPlatform→ 400. - Transaction signature invalid → 400.
- Any requested agent disabled (
isAgentEnabled) → 503 with list of disabled agents.
- No
- AI (OpenRouter) errors — Propagated from
processIdea,refineIntent,selectPlatform,executeX402Workflow; APIs return 500 with the error message. - Platform templates — On per-file generation failure,
generateFileContentWithAgentusesgenerateFileContentas a fallback so the run can still complete.