diff --git a/.config/config.json b/.config/config.json index 9a63b79..397a80f 100644 --- a/.config/config.json +++ b/.config/config.json @@ -1,34 +1,72 @@ { + "defaultModel": "gpt-6-luna", + "modelAliases": { + "gpt-5": "gpt-6.2-sol", + "gpt-5.1": "gpt-6.2-sol", + "gpt-5.2": "gpt-6.2-sol", + "gpt-5-mini": "gpt-6.1-terra", + "gpt-5-nano": "gpt-6-luna" + }, "providers": [ { "id": "openai", "name": "OpenAI", + "type": "openai", "enabled": true, + "apiKeyEnv": "OPENAI_API_KEY", "models": [ { - "id": "gpt-5", - "name": "GPT-5", - "reasoningEfforts": ["minimal", "low", "medium", "high"] + "id": "gpt-6.2-astra", + "name": "GPT-6.2 Astra", + "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "low" }, { - "id": "gpt-5-mini", - "name": "GPT-5 Mini", - "reasoningEfforts": ["minimal", "low", "medium", "high"] + "id": "gpt-6.2-sol", + "name": "GPT-6.2 Sol", + "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "low" }, { - "id": "gpt-5-nano", - "name": "GPT-5 Nano", - "reasoningEfforts": ["minimal", "low", "medium", "high"] + "id": "gpt-6.1-terra", + "name": "GPT-6.1 Terra", + "reasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "low" }, { - "id": "gpt-5.1", - "name": "GPT-5.1", - "reasoningEfforts": ["none", "low", "medium", "high"] + "id": "gpt-6-luna", + "name": "GPT-6 Luna", + "reasoningEfforts": ["none", "low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "low" + } + ] + }, + { + "id": "anthropic", + "name": "Anthropic", + "type": "anthropic", + "enabled": true, + "apiKeyEnv": "ANTHROPIC_API_KEY", + "models": [ + { + "id": "claude-opus-5-5", + "name": "Claude Opus 5.5", + "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "medium", + "refusalFallback": true + }, + { + "id": "claude-sonnet-5-5", + "name": "Claude Sonnet 5.5", + "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "medium", + "refusalFallback": true }, { - "id": "gpt-5.2", - "name": "GPT-5.2", - "reasoningEfforts": ["none", "low", "medium", "high", "xhigh"] + "id": "claude-haiku-5-5", + "name": "Claude Haiku 5.5", + "reasoningEfforts": ["low", "medium", "high", "xhigh", "max"], + "defaultReasoningEffort": "medium" } ] } diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index cbeae54..a8f1fc3 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: - node-version: [20.x] + node-version: [22.x, 24.x] steps: - uses: actions/checkout@v4 @@ -38,6 +38,9 @@ jobs: - name: Typecheck run: npm run typecheck + - name: Test + run: npm test + - name: Build run: npm run build diff --git a/AGENTS.md b/AGENTS.md index 3d3cdc9..d505cbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,7 +10,8 @@ This repository is an npm workspace monorepo: - `packages/workflow-engine`: Reusable workflow runtime. - `design-system/`: Git submodule with UI tokens/components. - `data/runs/`: Runtime run snapshots (gitignored). -- `.config/config.json`: Provider/model definitions (committed). +- `.config/config.json`: Provider/model definitions (committed); schema in `docs/configuration.md`. +- `apps/server/src/llm`: provider router and adapters (OpenAI Agents SDK, Anthropic SDK). - `.config/default-workflow.json`: Optional startup workflow (gitignored). Server routes: @@ -19,6 +20,7 @@ Server routes: - `POST /api/run` (batch JSON run) - `POST /api/resume-stream` (SSE resume, primary) - `POST /api/resume` (batch JSON resume) +- `POST /api/cancel` (stop a running or paused run) - `GET /api/run/:runId` (active/persisted run fetch) - `GET /api/config` (provider/model config) - `GET /api/default-workflow` (optional startup workflow) @@ -31,8 +33,8 @@ Server routes: - `npm run build`: Build server and web app. - `npm run build:packages`: Build shared packages. - `npm run lint`: Run ESLint. -- `npm run typecheck`: Typecheck server and web workspaces. -- `npm test`: Run repo test gate (`workflow-engine` + server typecheck scripts). +- `npm run typecheck`: Typecheck every workspace. +- `npm test`: Build shared packages, then run Vitest in the engine, server and web workspaces. ## Coding Style & Naming Conventions @@ -44,8 +46,9 @@ Server routes: ## Testing Guidelines -- CI checks in `.github/workflows/pr.yml`: `lint`, `build:packages`, `typecheck`, `build`. -- Web workspace uses Vitest (`npm --workspace apps/web run test`). +- CI checks in `.github/workflows/pr.yml`: `lint`, `build:packages`, `typecheck`, `test`, `build`. +- Every workspace with logic uses Vitest (`npm --workspace run test`). The engine and server suites use a stub LLM; the server's SDK suite runs the real Agents SDK against a scripted model, so no API key is needed. +- Server and package sources are ES modules compiled with `NodeNext`: relative imports need a `.js` extension. - Prefer targeted `*.test.ts` files near changed behavior. ## Commit & Pull Request Guidelines @@ -58,7 +61,9 @@ Server routes: ## Security & Configuration Tips -- Set `OPENAI_API_KEY` before running agent workflows. +- Set the API key of each provider you use (`OPENAI_API_KEY`, `ANTHROPIC_API_KEY`) before running agent workflows. +- Providers and models live in `.config/config.json`; keys stay in the environment, named by each provider's `apiKeyEnv`. +- Do not hard-code model ids in source: add them to `.config/config.json` (and `modelAliases` for retired ids). - Never commit secrets, `.env` files, or generated data from `data/runs/`. ## Design System Policy diff --git a/CLAUDE.md b/CLAUDE.md index 2365ca8..aa8df4f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -25,6 +25,7 @@ In the UI, `Condition` maps to runtime node type `"if"` in workflow JSON and per - `POST /api/run` - `POST /api/resume-stream` - `POST /api/resume` +- `POST /api/cancel` - `GET /api/run/:runId` - `GET /api/config` - `GET /api/default-workflow` @@ -41,6 +42,8 @@ npm run typecheck npm test npm --workspace apps/web run test +npm --workspace apps/server run test +npm --workspace packages/workflow-engine run test ``` ## Architecture Notes @@ -88,10 +91,10 @@ git submodule update --init --recursive ## Configuration -- `OPENAI_API_KEY`: required for agent-node execution. +- `OPENAI_API_KEY` / `ANTHROPIC_API_KEY`: key for each provider whose models are used. - `PORT`: server port (default `3000`). - `PROJECT_ROOT`: optional root override. -- `.config/config.json`: provider/model config served by API. +- `.config/config.json`: providers, models, default model and aliases; routes each Agent node to a provider (`apps/server/src/llm`). Schema in `docs/configuration.md`. - `.config/default-workflow.json`: optional startup workflow (gitignored). ## References diff --git a/README.md b/README.md index 1be0848..b1a5d80 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,8 @@ Visual editor + runtime for building, executing, and auditing agentic LLM workfl ## Quick Start +Requires Node.js 20.19 or newer. + 1. Install dependencies: ```bash @@ -21,9 +23,12 @@ npm install 2. Configure environment: ```bash -export OPENAI_API_KEY="sk-..." +export OPENAI_API_KEY="sk-..." # OpenAI models +export ANTHROPIC_API_KEY="sk-ant-..." # Claude models ``` +Set the key for each provider you want to use. Providers and models are defined in `.config/config.json` (see [Configuration](./docs/configuration.md)). + 3. Start integrated dev server: ```bash @@ -40,9 +45,9 @@ npm run dev | `npm run dev:web` | Web-only dev server on `5173` (proxying `/api`). | | `npm run build` | Build server and web app. | | `npm run build:packages` | Build `packages/types` and `packages/workflow-engine`. | -| `npm run typecheck` | Typecheck server and web workspaces. | +| `npm run typecheck` | Typecheck every workspace. | | `npm run lint` | ESLint across repo TypeScript files. | -| `npm test` | Current test gate (`workflow-engine` + server typecheck script). | +| `npm test` | Build shared packages, then run the Vitest suites of the engine, server and web app. | ## Repository Structure diff --git a/apps/server/package.json b/apps/server/package.json index c44b9d5..ac8f8a5 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,25 +1,30 @@ { - "name": "@agentic/server", + "name": "@agentflow/server", "version": "1.0.0", "private": true, "main": "dist/index.js", "scripts": { - "dev": "tsx watch --ignore ../web --ignore ../../apps/web --ignore ../../data src/index.ts", + "dev": "tsx watch --ignore ../web --ignore ../../data src/index.ts", "build": "tsc -b tsconfig.json", "clean": "rm -rf dist tsconfig.tsbuildinfo", "start": "NODE_ENV=production node dist/index.js", "typecheck": "tsc -p tsconfig.json --noEmit", - "test": "npm run typecheck" + "test": "vitest run" }, "dependencies": { - "@openai/agents": "^0.1.0", - "@agentic/types": "file:../../packages/types", - "@agentic/workflow-engine": "file:../../packages/workflow-engine", - "cors": "^2.8.5", - "express": "^4.19.2" + "@agentflow/types": "file:../../packages/types", + "@agentflow/workflow-engine": "file:../../packages/workflow-engine", + "@anthropic-ai/sdk": "^1.10.0", + "@openai/agents": "^0.22.0", + "express": "^5.3.0", + "zod": "^4.6.7" }, "devDependencies": { - "@types/cors": "^2.8.17", - "@types/express": "^4.17.21" + "@types/express": "^5.0.6", + "@types/node": "^26.6.6" + }, + "type": "module", + "engines": { + "node": ">=20.19" } } diff --git a/apps/server/src/app.test.ts b/apps/server/src/app.test.ts new file mode 100644 index 0000000..50fac9a --- /dev/null +++ b/apps/server/src/app.test.ts @@ -0,0 +1,390 @@ +import fs from 'node:fs/promises'; +import type { AddressInfo } from 'node:net'; +import type { Server } from 'node:http'; +import os from 'node:os'; +import path from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import type { WorkflowGraph, WorkflowRunRecord, WorkflowRunResult } from '@agentflow/types'; +import type { AgentInvocation, AgentRespondOptions, WorkflowLLM } from '@agentflow/workflow-engine'; +import { createApp } from './app.js'; +import { restorePausedRuns } from './services/restore.js'; +import { RunStore } from './store/run-store.js'; + +type StreamEvent = { type: string; runId?: string; result?: WorkflowRunResult; message?: string }; + +const node = (id: string, type: string, data: Record = {}) => ({ id, type, x: 0, y: 0, data }); + +const agentGraph: WorkflowGraph = { + nodes: [node('start', 'start', { initialInput: 'hi' }), node('a', 'agent')], + connections: [{ source: 'start', target: 'a' }] +}; + +const approvalGraph: WorkflowGraph = { + nodes: [node('start', 'start', { initialInput: 'hi' }), node('gate', 'approval'), node('a', 'agent')], + connections: [ + { source: 'start', target: 'gate' }, + { source: 'gate', target: 'a', sourceHandle: 'approve' } + ] +}; + +let tempDir: string; +let server: Server | undefined; +let baseUrl: string; +let store: RunStore; + +async function startServer(llm?: WorkflowLLM): Promise { + store = new RunStore(); + const { app } = createApp({ llm, runsDir: path.join(tempDir, 'runs'), projectRoot: tempDir, store, sseHeartbeatMs: 10 }); + server = await new Promise((resolve) => { + const listening = app.listen(0, '127.0.0.1', () => resolve(listening)); + }); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api`; +} + +const post = (route: string, body: unknown) => + fetch(`${baseUrl}${route}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }); + +const postJson = async (route: string, body: unknown): Promise => + (await post(route, body)).json() as Promise; + +const readRecord = async (runId: string): Promise => + JSON.parse(await fs.readFile(path.join(tempDir, 'runs', `run_${runId}.json`), 'utf-8')) as WorkflowRunRecord; + +/** Reads SSE events from a response, yielding each parsed `data:` payload. */ +async function* readEvents(response: Response): AsyncGenerator { + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let buffer = ''; + for (;;) { + const { done, value } = await reader.read(); + if (done) return; + buffer += decoder.decode(value, { stream: true }); + const blocks = buffer.split('\n\n'); + buffer = blocks.pop() ?? ''; + for (const block of blocks) { + if (block.startsWith('data: ')) yield JSON.parse(block.slice(6)) as StreamEvent; + } + } +} + +const echoLlm: WorkflowLLM = { respond: async (invocation: AgentInvocation) => `echo:${invocation.userContent}` }; + +beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'agentflow-server-')); +}); + +afterEach(async () => { + await new Promise((resolve) => { + if (!server) return resolve(); + server.closeAllConnections(); + server.close(() => resolve()); + }); + server = undefined; + await fs.rm(tempDir, { recursive: true, force: true }); +}); + +describe('run endpoints', () => { + it('rejects malformed graphs with details', async () => { + await startServer(echoLlm); + const response = await post('/run', { graph: { nodes: [{ id: 'a' }], connections: [] } }); + expect(response.status).toBe(400); + expect(await response.json()).toEqual({ + error: 'Invalid workflow graph payload', + details: ['nodes[0].type must be a non-empty string.'] + }); + }); + + it('requires an LLM for agent workflows', async () => { + await startServer(); + expect((await post('/run', { graph: agentGraph })).status).toBe(503); + expect((await post('/run-stream', { graph: agentGraph })).status).toBe(503); + }); + + it('does not send CORS headers', async () => { + await startServer(echoLlm); + const preflight = await fetch(`${baseUrl}/run`, { + method: 'OPTIONS', + headers: { Origin: 'https://evil.example', 'Access-Control-Request-Method': 'POST' } + }); + expect(preflight.headers.get('access-control-allow-origin')).toBeNull(); + }); + + it('runs a workflow, persists it and serves it back by id', async () => { + await startServer(echoLlm); + const result = await postJson('/run', { graph: agentGraph }); + + expect(result.status).toBe('completed'); + expect(result.runId).toMatch(/^[0-9a-f-]{36}$/); + expect(result.state.a).toBe('echo:hi'); + expect(result.workflow).toEqual(agentGraph); + expect(store.size).toBe(0); + expect((await readRecord(result.runId)).status).toBe('completed'); + + const fetched = (await (await fetch(`${baseUrl}/run/${result.runId}`)).json()) as WorkflowRunResult; + expect(fetched).toMatchObject({ runId: result.runId, status: 'completed', waitingForInput: false }); + }); + + it('gives concurrent runs different ids', async () => { + await startServer(echoLlm); + const results = await Promise.all(Array.from({ length: 5 }, () => postJson('/run', { graph: agentGraph }))); + expect(new Set(results.map((result) => result.runId)).size).toBe(5); + }); + + it('streams start, log and done events', async () => { + await startServer(echoLlm); + const events: StreamEvent[] = []; + for await (const event of readEvents(await post('/run-stream', { graph: agentGraph }))) events.push(event); + + expect(events[0].type).toBe('start'); + expect(events.at(-1)).toMatchObject({ type: 'done', result: { status: 'completed', runId: events[0].runId } }); + expect(events.filter((event) => event.type === 'log').length).toBeGreaterThan(2); + }); + + it('sends heartbeat comments while a call is in flight', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + await startServer({ + respond: async () => { + await gate; + return 'done'; + } + }); + const response = await post('/run-stream', { graph: agentGraph }); + const reader = response.body!.getReader(); + const decoder = new TextDecoder(); + let text = ''; + while (!text.includes(': ping')) { + const { value, done } = await reader.read(); + if (done) break; + text += decoder.decode(value, { stream: true }); + } + release(); + await reader.cancel(); + expect(text).toContain(': ping\n\n'); + }); + + it('rejects run ids that are not safe file names', async () => { + await startServer(echoLlm); + expect((await fetch(`${baseUrl}/run/..%2F..%2Fpackage`)).status).toBe(400); + expect((await fetch(`${baseUrl}/run/unknown-run`)).status).toBe(404); + }); +}); + +describe('pause, resume and cancel', () => { + it('pauses on approval and completes after resume', async () => { + await startServer(echoLlm); + const paused = await postJson('/run', { graph: approvalGraph }); + expect(paused).toMatchObject({ status: 'paused', waitingForInput: true, currentNodeId: 'gate' }); + expect(store.size).toBe(1); + + const resumed = await postJson('/resume', { runId: paused.runId, input: { decision: 'approve' } }); + expect(resumed.status).toBe('completed'); + expect(store.size).toBe(0); + expect((await readRecord(paused.runId)).status).toBe('completed'); + }); + + it('validates resume requests', async () => { + await startServer(echoLlm); + expect((await post('/resume', {})).status).toBe(400); + expect((await post('/resume', { runId: 'missing' })).status).toBe(404); + expect((await post('/resume-stream', { runId: 'missing' })).status).toBe(404); + const paused = await postJson('/run', { graph: approvalGraph }); + expect((await post('/resume', { runId: paused.runId, input: 42 })).status).toBe(400); + }); + + it('refuses a second resume while the first is executing', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + await startServer({ + respond: async () => { + await gate; + return 'done'; + } + }); + const paused = await postJson('/run', { graph: approvalGraph }); + const body = { runId: paused.runId, input: { decision: 'approve' } }; + + const first = post('/resume', body); + await expect.poll(() => store.isBusy(paused.runId)).toBe(true); + expect((await post('/resume-stream', body)).status).toBe(409); + release(); + expect(((await (await first).json()) as WorkflowRunResult).status).toBe('completed'); + }); + + it('cancels a paused run', async () => { + await startServer(echoLlm); + const paused = await postJson('/run', { graph: approvalGraph }); + + const cancelled = await postJson('/cancel', { runId: paused.runId }); + expect(cancelled).toMatchObject({ status: 'cancelled', waitingForInput: false, currentNodeId: null }); + expect(store.size).toBe(0); + expect((await readRecord(paused.runId)).status).toBe('cancelled'); + expect((await post('/resume', { runId: paused.runId, input: { decision: 'approve' } })).status).toBe(404); + expect((await post('/cancel', { runId: paused.runId })).status).toBe(404); + }); + + it('cancels a running stream and aborts the model call', async () => { + let aborted = false; + await startServer({ + respond: (_invocation: AgentInvocation, options?: AgentRespondOptions) => + new Promise((_resolve, reject) => { + options?.signal?.addEventListener('abort', () => { + aborted = true; + reject(new Error('aborted')); + }); + }) + }); + + const events = readEvents(await post('/run-stream', { graph: agentGraph })); + const first = (await events.next()).value as StreamEvent; + expect(first.type).toBe('start'); + await expect.poll(() => store.get(first.runId!)?.getLogs().some((entry) => entry.type === 'start_prompt')).toBe(true); + + const cancelled = await postJson('/cancel', { runId: first.runId }); + expect(cancelled.status).toBe('cancelled'); + + let last: StreamEvent | undefined; + for await (const event of events) last = event; + expect(last).toMatchObject({ type: 'done', result: { status: 'cancelled' } }); + expect(aborted).toBe(true); + expect(store.size).toBe(0); + expect((await readRecord(first.runId!)).status).toBe('cancelled'); + }); + + it('keeps a run going when the stream client disconnects', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + await startServer({ + respond: async () => { + await gate; + return 'finished anyway'; + } + }); + const controller = new AbortController(); + const response = await fetch(`${baseUrl}/run-stream`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ graph: agentGraph }), + signal: controller.signal + }); + const first = (await readEvents(response).next()).value as StreamEvent; + controller.abort(); + + expect(((await (await fetch(`${baseUrl}/run/${first.runId}`)).json()) as WorkflowRunResult).status).toBe('running'); + release(); + await expect.poll(() => store.size).toBe(0); + expect((await readRecord(first.runId!)).state?.a).toBe('finished anyway'); + }); +}); + +describe('paused run restore', () => { + const pausedRecord = (runId: string): WorkflowRunRecord => ({ + runId, + workflow: approvalGraph, + logs: [], + status: 'paused', + state: { start: 'hi', previous_output: 'hi', pre_approval_output: 'hi' }, + currentNodeId: 'gate', + waitingForInput: true + }); + + const writeRecord = async (record: WorkflowRunRecord) => { + const runsDir = path.join(tempDir, 'runs'); + await fs.mkdir(runsDir, { recursive: true }); + await fs.writeFile(path.join(runsDir, `run_${record.runId}.json`), JSON.stringify(record)); + }; + + it('restores resumable runs and skips finished, expired and unreadable ones', async () => { + const runsDir = path.join(tempDir, 'runs'); + await writeRecord(pausedRecord('fresh')); + await writeRecord({ ...pausedRecord('finished'), status: 'completed', waitingForInput: false }); + await fs.writeFile(path.join(runsDir, 'run_broken.json'), '{not json'); + const restoreStore = new RunStore(); + + const restored = await restorePausedRuns({ runsDir, store: restoreStore, llm: echoLlm, pausedRunTtlMs: 60_000 }); + expect(restored).toBe(1); + expect(restoreStore.get('fresh')?.getStatus()).toBe('paused'); + + const later = new RunStore(); + const expired = await restorePausedRuns({ + runsDir, + store: later, + pausedRunTtlMs: 60_000, + now: () => Date.now() + 120_000 + }); + expect(expired).toBe(0); + }); + + it('resumes a restored run through the API', async () => { + await writeRecord(pausedRecord('1772129193363')); + await startServer(echoLlm); + await restorePausedRuns({ runsDir: path.join(tempDir, 'runs'), store, llm: echoLlm, pausedRunTtlMs: 60_000 }); + + const resumed = await postJson('/resume', { runId: '1772129193363', input: { decision: 'approve' } }); + expect(resumed.status).toBe('completed'); + expect(resumed.state.a).toBe('echo:hi'); + }); +}); + +describe('provider configuration', () => { + it('uses the preflight check, public config and default model it is given', async () => { + store = new RunStore(); + const seenModels: string[] = []; + const { app } = createApp({ + llm: { + respond: async (invocation: AgentInvocation) => { + seenModels.push(invocation.model); + return 'ok'; + } + }, + runsDir: path.join(tempDir, 'runs'), + projectRoot: tempDir, + store, + preflight: (graph) => + graph.nodes.some((node) => node.data?.model === 'claude-x') + ? { status: 503, error: 'ANTHROPIC_API_KEY is required to run Agent nodes that use Anthropic models.' } + : null, + getPublicConfig: () => ({ defaultModel: 'model-from-config', providers: [] }), + getDefaultModel: () => 'model-from-config' + }); + server = await new Promise((resolve) => { + const listening = app.listen(0, '127.0.0.1', () => resolve(listening)); + }); + baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/api`; + + expect(await (await fetch(`${baseUrl}/config`)).json()).toEqual({ defaultModel: 'model-from-config', providers: [] }); + + const blocked = await post('/run-stream', { + graph: { nodes: [node('start', 'start'), node('a', 'agent', { model: 'claude-x' })], connections: [] } + }); + expect(blocked.status).toBe(503); + expect(((await blocked.json()) as { error: string }).error).toMatch(/ANTHROPIC_API_KEY is required/); + + await postJson('/run', { graph: agentGraph }); + expect(seenModels).toEqual(['model-from-config']); + }); +}); + +describe('project files', () => { + it('returns 404 when config files are absent and serves them when present', async () => { + await startServer(); + expect((await fetch(`${baseUrl}/config`)).status).toBe(404); + expect((await fetch(`${baseUrl}/default-workflow`)).status).toBe(404); + + await fs.mkdir(path.join(tempDir, '.config')); + await fs.writeFile(path.join(tempDir, '.config', 'config.json'), JSON.stringify({ providers: [] })); + await fs.writeFile(path.join(tempDir, '.config', 'default-workflow.json'), JSON.stringify({ nodes: 'nope' })); + expect(await (await fetch(`${baseUrl}/config`)).json()).toEqual({ providers: [] }); + expect((await fetch(`${baseUrl}/default-workflow`)).status).toBe(400); + }); +}); diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts new file mode 100644 index 0000000..066666e --- /dev/null +++ b/apps/server/src/app.ts @@ -0,0 +1,43 @@ +import express, { type Express } from 'express'; +import type { WorkflowLLM } from '@agentflow/workflow-engine'; +import { createWorkflowRouter } from './routes/workflows.js'; +import type { WorkflowRouterOptions } from './routes/workflows.js'; +import { RunStore } from './store/run-store.js'; + +export interface CreateAppOptions { + llm?: WorkflowLLM; + runsDir: string; + projectRoot: string; + maxSteps?: number; + store?: RunStore; + sseHeartbeatMs?: number; + preflight?: WorkflowRouterOptions['preflight']; + getPublicConfig?: WorkflowRouterOptions['getPublicConfig']; + getDefaultModel?: WorkflowRouterOptions['getDefaultModel']; +} + +/** + * Builds the API application. The web UI is served from the same origin, so no + * CORS headers are sent: other sites cannot start runs against a local server. + */ +export function createApp(options: CreateAppOptions): { app: Express; store: RunStore } { + const store = options.store ?? new RunStore(); + const app = express(); + app.disable('x-powered-by'); + app.use(express.json({ limit: '1mb' })); + app.use( + '/api', + createWorkflowRouter({ + llm: options.llm, + store, + runsDir: options.runsDir, + projectRoot: options.projectRoot, + maxSteps: options.maxSteps, + sseHeartbeatMs: options.sseHeartbeatMs, + preflight: options.preflight, + getPublicConfig: options.getPublicConfig, + getDefaultModel: options.getDefaultModel + }) + ); + return { app, store }; +} diff --git a/apps/server/src/config.ts b/apps/server/src/config.ts index d3a3331..b71f142 100644 --- a/apps/server/src/config.ts +++ b/apps/server/src/config.ts @@ -1,15 +1,24 @@ -import fs from 'node:fs'; import path from 'node:path'; +import { DEFAULT_MAX_STEPS } from '@agentflow/workflow-engine'; -const FALLBACK_ROOT = path.resolve(__dirname, '..', '..', '..'); +const FALLBACK_ROOT = path.resolve(import.meta.dirname, '..', '..', '..'); const PROJECT_ROOT = process.env.PROJECT_ROOT || FALLBACK_ROOT; -const RUNS_DIR = path.resolve(PROJECT_ROOT, 'data', 'runs'); +const DEFAULT_PAUSED_RUN_TTL_HOURS = 24; -fs.mkdirSync(RUNS_DIR, { recursive: true }); +function positiveNumber(raw: string | undefined, fallback: number): number { + const value = Number(raw); + return Number.isFinite(value) && value > 0 ? value : fallback; +} export const config = { port: Number(process.env.PORT ?? 3000), - runsDir: RUNS_DIR, + runsDir: path.resolve(PROJECT_ROOT, 'data', 'runs'), projectRoot: PROJECT_ROOT, - openAiApiKey: process.env.OPENAI_API_KEY ?? '' + /** Node executions allowed per run or resume before a loop is stopped. */ + maxSteps: Math.floor(positiveNumber(process.env.WORKFLOW_MAX_STEPS, DEFAULT_MAX_STEPS)), + /** Paused runs older than this are not restored into memory on startup. */ + pausedRunTtlMs: + positiveNumber(process.env.PAUSED_RUN_TTL_HOURS, DEFAULT_PAUSED_RUN_TTL_HOURS) * 60 * 60 * 1000 }; + +export type AppConfig = typeof config; diff --git a/apps/server/src/index.ts b/apps/server/src/index.ts index d13dca2..9d98674 100644 --- a/apps/server/src/index.ts +++ b/apps/server/src/index.ts @@ -1,96 +1,78 @@ import fs from 'node:fs'; import path from 'node:path'; -import express, { type Request, type Response } from 'express'; -import cors from 'cors'; -import type { WorkflowRunRecord } from '@agentic/types'; -import WorkflowEngine, { type WorkflowLLM } from '@agentic/workflow-engine'; -import { config } from './config'; -import { logger } from './logger'; -import { createWorkflowRouter } from './routes/workflows'; -import { OpenAIAgentsLLMService } from './services/openai-agents-llm'; -import { addWorkflow } from './store/active-workflows'; +import express, { type NextFunction, type Request, type Response } from 'express'; +import { createApp } from './app.js'; +import { config } from './config.js'; +import { logger } from './logger.js'; +import { ConfigError, ConfigStore } from './llm/app-config.js'; +import type { ConfigSnapshot } from './llm/app-config.js'; +import { ProviderRouterLLM } from './llm/router.js'; +import { restorePausedRuns } from './services/restore.js'; const isProduction = process.env.NODE_ENV === 'production'; -const webRoot = path.resolve(__dirname, '../../web'); +const webRoot = path.resolve(import.meta.dirname, '../../web'); const webDist = path.join(webRoot, 'dist'); -/** - * On startup, scan the runs directory for persisted paused runs and re-hydrate - * each one back into the active-workflows Map so that `POST /api/resume` works - * even after a server restart. - */ -function restorePausedRuns(runsDir: string, llm?: WorkflowLLM): void { - let files: string[]; +/** Returns undefined (after logging why) when the configuration cannot be used. */ +function readConfig(store: ConfigStore): ConfigSnapshot | undefined { try { - files = fs.readdirSync(runsDir).filter((f) => f.startsWith('run_') && f.endsWith('.json')); - } catch (err) { - const code = (err as NodeJS.ErrnoException).code; - if (code !== 'ENOENT') { - logger.warn('Failed to scan runs directory %s: %s', runsDir, String(err)); - } - return; + return store.get(); + } catch (error) { + if (!(error instanceof ConfigError)) throw error; + logger.warn(error.message); + return undefined; } +} - for (const file of files) { - try { - const record = JSON.parse( - fs.readFileSync(path.join(runsDir, file), 'utf-8') - ) as WorkflowRunRecord; - - if ( - record.status === 'paused' && - record.waitingForInput === true && - record.state !== undefined && - record.currentNodeId != null - ) { - const engine = new WorkflowEngine(record.workflow, { - runId: record.runId, - llm, - initialState: { - state: record.state, - currentNodeId: record.currentNodeId, - status: 'paused', - waitingForInput: true, - logs: record.logs - } - }); - addWorkflow(engine); - logger.info('Restored paused run %s from disk', record.runId); - } - } catch (err) { - logger.warn('Skipped unreadable run file %s: %s', file, String(err)); +function logProviders(snapshot: ConfigSnapshot): void { + for (const provider of snapshot.config.providers) { + if (!provider.enabled) continue; + if (snapshot.isAvailable(provider)) { + logger.info('%s enabled with %d models (%s detected)', provider.name, provider.models.length, provider.apiKeyEnv); + } else { + logger.warn('%s models are unavailable: %s is not set', provider.name, provider.apiKeyEnv); } } + logger.info('Default model: %s', snapshot.defaultModel ?? 'none'); } async function bootstrap() { - const app = express(); - app.use(cors()); - app.use(express.json({ limit: '1mb' })); + const configStore = ConfigStore.forProject(config.projectRoot); + const llmService = new ProviderRouterLLM(() => configStore.get()); + const snapshot = readConfig(configStore); + if (snapshot) logProviders(snapshot); - let llmService: WorkflowLLM | undefined; - if (config.openAiApiKey) { - logger.info('OPENAI_API_KEY detected, enabling live OpenAI Agents SDK backend'); - llmService = new OpenAIAgentsLLMService(); - } else { - logger.warn('OPENAI_API_KEY missing. Agent workflows will be rejected.'); - } + await fs.promises.mkdir(config.runsDir, { recursive: true }); - restorePausedRuns(config.runsDir, llmService); + const { app, store } = createApp({ + llm: llmService, + runsDir: config.runsDir, + projectRoot: config.projectRoot, + maxSteps: config.maxSteps, + preflight: (graph) => llmService.preflight(graph), + getPublicConfig: () => readConfig(configStore)?.toPublic(), + getDefaultModel: () => readConfig(configStore)?.defaultModel + }); - app.use('/api', createWorkflowRouter(llmService)); + await restorePausedRuns({ + runsDir: config.runsDir, + store, + llm: llmService, + maxSteps: config.maxSteps, + defaultModel: snapshot?.defaultModel, + pausedRunTtlMs: config.pausedRunTtlMs + }); if (isProduction) { if (fs.existsSync(webDist)) { app.use(express.static(webDist)); - app.get('*', (_req: Request, res: Response) => { + app.get('/{*path}', (_req: Request, res: Response) => { res.sendFile(path.join(webDist, 'index.html')); }); } else { logger.warn('Built web assets missing. Run `npm run build:web` before starting in production.'); } } else { - const fsPromises = fs.promises; const { createServer: createViteServer } = await import('vite'); const vite = await createViteServer({ root: webRoot, @@ -99,7 +81,7 @@ async function bootstrap() { appType: 'custom' }); app.use(vite.middlewares); - app.use('*', async (req: Request, res: Response, next) => { + app.use(async (req: Request, res: Response, next: NextFunction) => { const isHtmlRequest = req.method === 'GET' && !req.originalUrl.startsWith('/api') && @@ -112,11 +94,10 @@ async function bootstrap() { } try { - const url = req.originalUrl; const templatePath = path.join(webRoot, 'index.html'); - let template = await fsPromises.readFile(templatePath, 'utf-8'); - template = await vite.transformIndexHtml(url, template); - res.status(200).set({ 'Content-Type': 'text/html' }).end(template); + const template = await fs.promises.readFile(templatePath, 'utf-8'); + const html = await vite.transformIndexHtml(req.originalUrl, template); + res.status(200).set({ 'Content-Type': 'text/html' }).end(html); } catch (error) { vite.ssrFixStacktrace(error as Error); next(error); diff --git a/apps/server/src/llm/anthropic-adapter.test.ts b/apps/server/src/llm/anthropic-adapter.test.ts new file mode 100644 index 0000000..febcca2 --- /dev/null +++ b/apps/server/src/llm/anthropic-adapter.test.ts @@ -0,0 +1,159 @@ +import Anthropic from '@anthropic-ai/sdk'; +import { describe, expect, it } from 'vitest'; +import { AnthropicAdapter } from './anthropic-adapter.js'; +import type { AgentRequest } from './provider-adapter.js'; + +type RequestBody = Record & { + messages: Array<{ role: string; content: unknown }>; + tools?: Array>; +}; + +type ScriptedResponse = { content: Array>; stop_reason: string; stop_details?: unknown }; + +/** + * The real Anthropic SDK and tool runner, with only the HTTP layer replaced: + * every request body is recorded and answered from a script. + */ +function fakeClient(script: (body: RequestBody, call: number) => ScriptedResponse) { + const bodies: RequestBody[] = []; + const headers: Headers[] = []; + const client = new Anthropic({ + apiKey: 'test-key', + maxRetries: 0, + fetch: async (_url, init) => { + const body = JSON.parse(String(init?.body)) as RequestBody; + bodies.push(body); + headers.push(new Headers(init?.headers)); + const reply = script(body, bodies.length); + return new Response( + JSON.stringify({ + id: `msg_${bodies.length}`, + type: 'message', + role: 'assistant', + model: body.model, + stop_sequence: null, + usage: { input_tokens: 1, output_tokens: 1 }, + ...reply + }), + { status: 200, headers: { 'content-type': 'application/json' } } + ); + } + }); + return { client, bodies, headers }; +} + +const text = (value: string): ScriptedResponse => ({ content: [{ type: 'text', text: value }], stop_reason: 'end_turn' }); + +const baseRequest: AgentRequest = { + agentName: 'Tester', + systemPrompt: 'Be brief.', + userContent: 'What is 2 + 2?', + model: 'claude-opus-5-5', + webSearch: false, + subagentTools: [] +}; + +describe('AnthropicAdapter', () => { + it('sends the prompt, model, effort and output cap to the Messages API', async () => { + const { client, bodies } = fakeClient(() => text(' four ')); + const adapter = new AnthropicAdapter({ apiKey: 'unused', client }); + + const output = await adapter.run({ ...baseRequest, reasoningEffort: 'high', maxOutputTokens: 4096 }); + + expect(output).toBe('four'); + expect(bodies).toHaveLength(1); + expect(bodies[0]).toMatchObject({ + model: 'claude-opus-5-5', + max_tokens: 4096, + system: 'Be brief.', + output_config: { effort: 'high' }, + messages: [{ role: 'user', content: 'What is 2 + 2?' }] + }); + // Thinking is left to the model's adaptive default and no sampling parameters are sent. + expect(bodies[0]).not.toHaveProperty('thinking'); + expect(bodies[0]).not.toHaveProperty('temperature'); + expect(bodies[0]).not.toHaveProperty('thread'); + expect(bodies[0]).not.toHaveProperty('fallbacks'); + }); + + it('adds the web search server tool and the refusal fallback when configured', async () => { + const { client, bodies, headers } = fakeClient(() => text('ok')); + const adapter = new AnthropicAdapter({ apiKey: 'unused', client }); + + await adapter.run({ ...baseRequest, webSearch: true, refusalFallback: true }); + + expect(bodies[0].tools).toEqual([{ type: 'web_search_20260209', name: 'web_search', max_uses: 5 }]); + expect(bodies[0].fallbacks).toBe('default'); + expect(headers[0].get('anthropic-beta')).toContain('server-side-fallback-2026-07-01'); + }); + + it('runs subagent tools and returns their output to the model', async () => { + const { client, bodies } = fakeClient((_body, call) => + call === 1 + ? { + content: [{ type: 'tool_use', id: 'toolu_1', name: 'subagent_helper_node_2', input: { input: 'look this up' } }], + stop_reason: 'tool_use' + } + : text('parent done') + ); + const adapter = new AnthropicAdapter({ apiKey: 'unused', client }); + const subagentInputs: string[] = []; + + const output = await adapter.run({ + ...baseRequest, + subagentTools: [ + { + name: 'subagent_helper_node_2', + description: 'Delegates work to subagent Helper.', + run: async (input) => { + subagentInputs.push(input); + return 'child findings'; + } + } + ] + }); + + expect(output).toBe('parent done'); + expect(subagentInputs).toEqual(['look this up']); + expect(bodies[0].tools?.[0]).toMatchObject({ + name: 'subagent_helper_node_2', + description: 'Delegates work to subagent Helper.', + input_schema: { type: 'object', required: ['input'] } + }); + expect(bodies).toHaveLength(2); + expect(JSON.stringify(bodies[1].messages)).toContain('child findings'); + expect(JSON.stringify(bodies[1].messages)).toContain('toolu_1'); + }); + + it('replaces an empty user message, which the API would reject', async () => { + const { client, bodies } = fakeClient(() => text('ok')); + await new AnthropicAdapter({ apiKey: 'unused', client }).run({ ...baseRequest, userContent: ' ' }); + expect(bodies[0].messages[0].content).toBe('(no input)'); + }); + + it('turns a refusal into an error with the explanation', async () => { + const { client } = fakeClient(() => ({ + content: [], + stop_reason: 'refusal', + stop_details: { type: 'refusal', category: 'cyber', explanation: 'This request was declined.' } + })); + await expect(new AnthropicAdapter({ apiKey: 'unused', client }).run(baseRequest)).rejects.toThrow( + 'The model declined this request: This request was declined.' + ); + }); + + it('reports hitting the output limit before any answer', async () => { + const { client } = fakeClient(() => ({ content: [], stop_reason: 'max_tokens' })); + await expect(new AnthropicAdapter({ apiKey: 'unused', client }).run(baseRequest)).rejects.toThrow(/output token limit/); + }); + + it('stops when the signal aborts', async () => { + const controller = new AbortController(); + controller.abort(); + const { client, bodies } = fakeClient(() => text('never')); + await expect( + new AnthropicAdapter({ apiKey: 'unused', client }).run({ ...baseRequest, signal: controller.signal }) + ).rejects.toThrow(); + expect(bodies).toHaveLength(0); + }); +}); diff --git a/apps/server/src/llm/anthropic-adapter.ts b/apps/server/src/llm/anthropic-adapter.ts new file mode 100644 index 0000000..1f3c80a --- /dev/null +++ b/apps/server/src/llm/anthropic-adapter.ts @@ -0,0 +1,96 @@ +import Anthropic from '@anthropic-ai/sdk'; +import { betaTool } from '@anthropic-ai/sdk/helpers/beta/json-schema'; +import { MAX_AGENT_TURNS, SUBAGENT_INPUT_DESCRIPTION } from './provider-adapter.js'; +import type { AgentRequest, ProviderAdapter } from './provider-adapter.js'; + +type ToolRunnerParams = Parameters[0]; +type RunnerTool = ToolRunnerParams['tools'][number]; +type Effort = NonNullable['effort']>; + +/** Non-streaming requests stay under the SDK's HTTP timeout at this size. */ +const DEFAULT_MAX_OUTPUT_TOKENS = 16_000; +const WEB_SEARCH_MAX_USES = 5; +const REFUSAL_FALLBACK_BETA = 'server-side-fallback-2026-07-01'; +/** The Messages API rejects an empty user message. */ +const EMPTY_INPUT_PLACEHOLDER = '(no input)'; + +export interface AnthropicAdapterOptions { + apiKey: string; + baseUrl?: string; + /** Replaces the SDK client, for tests. */ + client?: Anthropic; +} + +/** Claude models, through the Anthropic SDK's tool runner. */ +export class AnthropicAdapter implements ProviderAdapter { + private readonly client: Anthropic; + + constructor(options: AnthropicAdapterOptions) { + this.client = options.client ?? new Anthropic({ apiKey: options.apiKey, baseURL: options.baseUrl }); + } + + async run(request: AgentRequest): Promise { + const tools: RunnerTool[] = request.subagentTools.map((subagent) => + betaTool({ + name: subagent.name, + description: subagent.description, + inputSchema: { + type: 'object', + properties: { input: { type: 'string', description: SUBAGENT_INPUT_DESCRIPTION } }, + required: ['input'], + additionalProperties: false + }, + run: ({ input }) => subagent.run(input) + }) + ); + + if (request.webSearch) { + // A server tool: Anthropic runs the search, so there is no `run` function. + tools.push({ type: 'web_search_20260209', name: 'web_search', max_uses: WEB_SEARCH_MAX_USES }); + } + + const params: ToolRunnerParams = { + model: request.model, + max_tokens: request.maxOutputTokens ?? DEFAULT_MAX_OUTPUT_TOKENS, + system: request.systemPrompt, + messages: [{ role: 'user', content: request.userContent.trim() ? request.userContent : EMPTY_INPUT_PLACEHOLDER }], + tools, + max_iterations: MAX_AGENT_TURNS, + // Send the whole conversation each turn instead of relying on a + // server-held thread, which proxies and some platforms do not support. + thread: false, + stream: false + }; + + // Thinking is adaptive by default on current Claude models; effort is the + // one depth control they all accept. + if (request.reasoningEffort) { + params.output_config = { effort: request.reasoningEffort as Effort }; + } + + if (request.refusalFallback) { + params.betas = [REFUSAL_FALLBACK_BETA]; + params.fallbacks = 'default'; + } + + const message = await this.client.beta.messages.toolRunner(params, { signal: request.signal }).runUntilDone(); + + if (message.stop_reason === 'refusal') { + const explanation = message.stop_details?.explanation; + throw new Error(explanation ? `The model declined this request: ${explanation}` : 'The model declined this request.'); + } + + const text = message.content + .flatMap((block) => (block.type === 'text' ? [block.text] : [])) + .join('') + .trim(); + + if (!text) { + if (message.stop_reason === 'max_tokens') { + throw new Error('The model reached its output token limit before writing an answer.'); + } + return 'Model returned no text output.'; + } + return text; + } +} diff --git a/apps/server/src/llm/app-config.test.ts b/apps/server/src/llm/app-config.test.ts new file mode 100644 index 0000000..904c592 --- /dev/null +++ b/apps/server/src/llm/app-config.test.ts @@ -0,0 +1,146 @@ +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { ConfigError, ConfigSnapshot, ConfigStore, parseAppConfig } from './app-config.js'; + +const twoProviders = { + defaultModel: 'claude-a', + modelAliases: { 'old-model': 'gpt-a' }, + providers: [ + { + id: 'openai', + name: 'OpenAI', + models: [{ id: 'gpt-a', name: 'GPT A', reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'low' }] + }, + { + id: 'anthropic', + name: 'Anthropic', + type: 'anthropic', + models: [{ id: 'claude-a', reasoningEfforts: ['medium'], refusalFallback: true, maxOutputTokens: 8000 }] + } + ] +}; + +describe('parseAppConfig', () => { + it('fills in defaults so files written before provider types existed still load', () => { + const config = parseAppConfig({ + providers: [{ id: 'openai', name: 'OpenAI', enabled: true, models: [{ id: 'gpt-5', name: 'GPT-5', reasoningEfforts: ['low'] }] }] + }); + expect(config.providers[0]).toMatchObject({ + type: 'openai', + apiKeyEnv: 'OPENAI_API_KEY', + api: 'responses', + enabled: true + }); + expect(config.modelAliases).toEqual({}); + }); + + it('reads provider and model options', () => { + const config = parseAppConfig(twoProviders); + expect(config.providers[1]).toMatchObject({ type: 'anthropic', apiKeyEnv: 'ANTHROPIC_API_KEY' }); + expect(config.providers[1].models[0]).toMatchObject({ + id: 'claude-a', + name: 'claude-a', + refusalFallback: true, + maxOutputTokens: 8000 + }); + }); + + it.each([ + [{}, /"providers" array/], + [{ providers: [{ id: 'mistral', models: [] }] }, /type must be "openai" or "anthropic"/], + [{ providers: [{ id: 'openai', api: 'soap', models: [] }] }, /api must be/], + [{ providers: [{ id: 'openai', models: [{ id: '' }] }] }, /models\[0\]\.id/], + [{ providers: [{ id: 'openai', models: [{ id: 'm', reasoningEfforts: ['low'], defaultReasoningEffort: 'max' }] }] }, /defaultReasoningEffort/], + [{ providers: [{ id: 'openai', models: [{ id: 'm' }] }, { id: 'openai', models: [] }] }, /Provider id "openai" is duplicated/], + [{ providers: [{ id: 'a', type: 'openai', models: [{ id: 'm' }] }, { id: 'b', type: 'openai', models: [{ id: 'm' }] }] }, /listed by both "a" and "b"/], + [{ defaultModel: 'nope', providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /defaultModel "nope"/], + [{ modelAliases: { old: 'nope' }, providers: [{ id: 'openai', models: [{ id: 'm' }] }] }, /modelAliases\["old"\]/] + ])('rejects invalid configuration %#', (raw, message) => { + expect(() => parseAppConfig(raw)).toThrow(ConfigError); + expect(() => parseAppConfig(raw)).toThrow(message); + }); + + it('allows the same model id in a disabled provider', () => { + const config = parseAppConfig({ + providers: [ + { id: 'a', type: 'openai', models: [{ id: 'm' }] }, + { id: 'b', type: 'openai', enabled: false, models: [{ id: 'm' }] } + ] + }); + expect(config.providers).toHaveLength(2); + }); +}); + +describe('ConfigSnapshot', () => { + const snapshot = (env: NodeJS.ProcessEnv) => new ConfigSnapshot(parseAppConfig(twoProviders), env); + + it('resolves a model to its provider and key', () => { + const lookup = snapshot({ OPENAI_API_KEY: 'sk-test' }).lookup('gpt-a'); + expect(lookup).toMatchObject({ ok: true, resolved: { provider: { id: 'openai' }, model: { id: 'gpt-a' }, apiKey: 'sk-test' } }); + }); + + it('follows aliases and falls back to the default model', () => { + const both = snapshot({ OPENAI_API_KEY: 'a', ANTHROPIC_API_KEY: 'b' }); + expect(both.lookup('old-model')).toMatchObject({ ok: true, resolved: { model: { id: 'gpt-a' } } }); + expect(both.lookup(undefined)).toMatchObject({ ok: true, resolved: { model: { id: 'claude-a' } } }); + expect(both.lookup(' ')).toMatchObject({ ok: true, resolved: { model: { id: 'claude-a' } } }); + }); + + it('explains a missing key and an unknown model', () => { + const noKeys = snapshot({}); + expect(noKeys.lookup('claude-a')).toEqual({ + ok: false, + reason: 'missing_key', + message: 'ANTHROPIC_API_KEY is required to run Agent nodes that use Anthropic models.' + }); + expect(noKeys.lookup('gpt-99')).toMatchObject({ ok: false, reason: 'unknown_model' }); + }); + + it('prefers a provider with a key when no default model is configured', () => { + const config = parseAppConfig({ ...twoProviders, defaultModel: undefined }); + expect(new ConfigSnapshot(config, { ANTHROPIC_API_KEY: 'k' }).defaultModel).toBe('claude-a'); + expect(new ConfigSnapshot(config, {}).defaultModel).toBe('gpt-a'); + }); + + it('exposes availability but no key names or base URLs to the browser', () => { + const publicConfig = snapshot({ OPENAI_API_KEY: 'sk-secret' }).toPublic(); + expect(publicConfig.providers.map((p) => [p.id, p.available])).toEqual([ + ['openai', true], + ['anthropic', false] + ]); + expect(publicConfig.defaultModel).toBe('claude-a'); + const serialized = JSON.stringify(publicConfig); + expect(serialized).not.toContain('sk-secret'); + expect(serialized).not.toContain('API_KEY'); + }); +}); + +describe('ConfigStore', () => { + it('reloads when the file changes and reports a missing or broken file', () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'agentflow-config-')); + const file = path.join(dir, 'config.json'); + const store = new ConfigStore(file, {}); + expect(() => store.get()).toThrow(/not found/); + + fs.writeFileSync(file, JSON.stringify(twoProviders)); + expect(store.get().defaultModel).toBe('claude-a'); + expect(store.get()).toBe(store.get()); + + fs.writeFileSync(file, JSON.stringify({ ...twoProviders, defaultModel: 'gpt-a' })); + fs.utimesSync(file, new Date(), new Date(Date.now() + 5000)); + expect(store.get().defaultModel).toBe('gpt-a'); + + fs.writeFileSync(file, '{broken'); + fs.utimesSync(file, new Date(), new Date(Date.now() + 10000)); + expect(() => store.get()).toThrow(/not valid JSON/); + fs.rmSync(dir, { recursive: true, force: true }); + }); + + it('accepts the configuration shipped with the project', () => { + const shipped = ConfigStore.forProject(path.resolve(import.meta.dirname, '../../../..'), {}).get(); + expect(shipped.config.providers.map((p) => p.type)).toEqual(['openai', 'anthropic']); + expect(shipped.lookup(undefined)).toMatchObject({ ok: false, reason: 'missing_key' }); + }); +}); diff --git a/apps/server/src/llm/app-config.ts b/apps/server/src/llm/app-config.ts new file mode 100644 index 0000000..4d55e53 --- /dev/null +++ b/apps/server/src/llm/app-config.ts @@ -0,0 +1,296 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +export type ProviderType = 'openai' | 'anthropic'; +export type OpenAiApi = 'responses' | 'chat_completions'; + +export interface ModelConfig { + id: string; + name: string; + /** Effort values offered in the editor. Empty when the model has no effort setting. */ + reasoningEfforts: string[]; + /** Used when a node has no effort or one the model does not accept. */ + defaultReasoningEffort?: string; + /** Output token cap per model call (Anthropic `max_tokens`). */ + maxOutputTokens?: number; + /** Anthropic only: let the API re-run a declined request on a fallback model. */ + refusalFallback?: boolean; +} + +export interface ProviderConfig { + id: string; + name: string; + type: ProviderType; + enabled: boolean; + /** Name of the environment variable that holds the API key. Keys never live in the file. */ + apiKeyEnv: string; + /** Optional API base URL, for a proxy or an OpenAI-compatible service. */ + baseUrl?: string; + /** OpenAI-type providers only. `chat_completions` is for OpenAI-compatible services. */ + api: OpenAiApi; + models: ModelConfig[]; +} + +export interface AppConfig { + /** Model used by agent nodes that do not name one. Defaults to the first available model. */ + defaultModel?: string; + /** Maps model ids found in older saved workflows to current ones. */ + modelAliases: Record; + providers: ProviderConfig[]; +} + +export class ConfigError extends Error { + constructor(message: string) { + super(message); + this.name = 'ConfigError'; + } +} + +const DEFAULT_API_KEY_ENV: Record = { + openai: 'OPENAI_API_KEY', + anthropic: 'ANTHROPIC_API_KEY' +}; + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function requireString(value: unknown, where: string): string { + if (typeof value !== 'string' || !value.trim()) { + throw new ConfigError(`${where} must be a non-empty string.`); + } + return value.trim(); +} + +function optionalString(value: unknown, where: string): string | undefined { + if (value === undefined || value === null) return undefined; + return requireString(value, where); +} + +function parseModel(raw: unknown, where: string): ModelConfig { + if (!isObject(raw)) throw new ConfigError(`${where} must be an object.`); + const id = requireString(raw.id, `${where}.id`); + const efforts = raw.reasoningEfforts ?? []; + if (!Array.isArray(efforts) || efforts.some((effort) => typeof effort !== 'string' || !effort)) { + throw new ConfigError(`${where}.reasoningEfforts must be an array of strings.`); + } + const defaultReasoningEffort = optionalString(raw.defaultReasoningEffort, `${where}.defaultReasoningEffort`); + if (defaultReasoningEffort && !efforts.includes(defaultReasoningEffort)) { + throw new ConfigError(`${where}.defaultReasoningEffort must be one of reasoningEfforts.`); + } + const maxOutputTokens = raw.maxOutputTokens; + if ( + maxOutputTokens !== undefined && + (typeof maxOutputTokens !== 'number' || !Number.isInteger(maxOutputTokens) || maxOutputTokens <= 0) + ) { + throw new ConfigError(`${where}.maxOutputTokens must be a positive integer.`); + } + return { + id, + name: optionalString(raw.name, `${where}.name`) ?? id, + reasoningEfforts: efforts as string[], + defaultReasoningEffort, + maxOutputTokens: maxOutputTokens as number | undefined, + refusalFallback: raw.refusalFallback === true + }; +} + +function parseProvider(raw: unknown, where: string): ProviderConfig { + if (!isObject(raw)) throw new ConfigError(`${where} must be an object.`); + const id = requireString(raw.id, `${where}.id`); + // `type` may be omitted when the id already names a supported provider, + // which is how configuration files written before `type` existed look. + const type = optionalString(raw.type, `${where}.type`) ?? id; + if (type !== 'openai' && type !== 'anthropic') { + throw new ConfigError(`${where}.type must be "openai" or "anthropic" (got "${type}").`); + } + const api = optionalString(raw.api, `${where}.api`) ?? 'responses'; + if (api !== 'responses' && api !== 'chat_completions') { + throw new ConfigError(`${where}.api must be "responses" or "chat_completions".`); + } + if (!Array.isArray(raw.models)) throw new ConfigError(`${where}.models must be an array.`); + return { + id, + name: optionalString(raw.name, `${where}.name`) ?? id, + type, + enabled: raw.enabled !== false, + apiKeyEnv: optionalString(raw.apiKeyEnv, `${where}.apiKeyEnv`) ?? DEFAULT_API_KEY_ENV[type], + baseUrl: optionalString(raw.baseUrl, `${where}.baseUrl`), + api, + models: raw.models.map((model, index) => parseModel(model, `${where}.models[${index}]`)) + }; +} + +/** Validates and normalises the contents of `.config/config.json`. */ +export function parseAppConfig(raw: unknown): AppConfig { + if (!isObject(raw) || !Array.isArray(raw.providers)) { + throw new ConfigError('config.json must be an object with a "providers" array.'); + } + const providers = raw.providers.map((provider, index) => parseProvider(provider, `providers[${index}]`)); + + const providerIds = new Set(); + const modelOwners = new Map(); + for (const provider of providers) { + if (providerIds.has(provider.id)) throw new ConfigError(`Provider id "${provider.id}" is duplicated.`); + providerIds.add(provider.id); + if (!provider.enabled) continue; + for (const model of provider.models) { + const owner = modelOwners.get(model.id); + if (owner) { + throw new ConfigError(`Model id "${model.id}" is listed by both "${owner}" and "${provider.id}".`); + } + modelOwners.set(model.id, provider.id); + } + } + + const modelAliases: Record = {}; + if (raw.modelAliases !== undefined) { + if (!isObject(raw.modelAliases)) throw new ConfigError('modelAliases must be an object.'); + for (const [alias, target] of Object.entries(raw.modelAliases)) { + const targetId = requireString(target, `modelAliases["${alias}"]`); + if (!modelOwners.has(targetId)) { + throw new ConfigError(`modelAliases["${alias}"] points to "${targetId}", which no enabled provider lists.`); + } + modelAliases[alias] = targetId; + } + } + + const defaultModel = optionalString(raw.defaultModel, 'defaultModel'); + if (defaultModel && !modelOwners.has(defaultModel)) { + throw new ConfigError(`defaultModel "${defaultModel}" is not listed by any enabled provider.`); + } + + return { defaultModel, modelAliases, providers }; +} + +export interface ResolvedModel { + provider: ProviderConfig; + model: ModelConfig; + /** Empty when the provider's key variable is not set. */ + apiKey: string; +} + +export type ModelLookup = + | { ok: true; resolved: ResolvedModel } + | { ok: false; reason: 'unknown_model' | 'missing_key'; message: string }; + +/** A parsed configuration together with the environment it reads keys from. */ +export class ConfigSnapshot { + constructor( + readonly config: AppConfig, + private readonly env: NodeJS.ProcessEnv = process.env + ) {} + + private apiKey(provider: ProviderConfig): string { + return (this.env[provider.apiKeyEnv] ?? '').trim(); + } + + isAvailable(provider: ProviderConfig): boolean { + return provider.enabled && this.apiKey(provider) !== ''; + } + + /** The configured default, or the first model of a provider that has a key. */ + get defaultModel(): string | undefined { + if (this.config.defaultModel) return this.config.defaultModel; + const enabled = this.config.providers.filter((provider) => provider.enabled); + const preferred = enabled.find((provider) => this.isAvailable(provider) && provider.models.length > 0); + return (preferred ?? enabled.find((provider) => provider.models.length > 0))?.models[0]?.id; + } + + lookup(requestedModel: string | undefined): ModelLookup { + const requested = requestedModel?.trim() || this.defaultModel; + if (!requested) { + return { ok: false, reason: 'unknown_model', message: 'No models are configured in .config/config.json.' }; + } + const modelId = this.config.modelAliases[requested] ?? requested; + for (const provider of this.config.providers) { + if (!provider.enabled) continue; + const model = provider.models.find((candidate) => candidate.id === modelId); + if (!model) continue; + const apiKey = this.apiKey(provider); + if (!apiKey) { + return { + ok: false, + reason: 'missing_key', + message: `${provider.apiKeyEnv} is required to run Agent nodes that use ${provider.name} models.` + }; + } + return { ok: true, resolved: { provider, model, apiKey } }; + } + return { + ok: false, + reason: 'unknown_model', + message: `Model "${requested}" is not listed by any enabled provider in .config/config.json.` + }; + } + + /** What the browser receives: no key names, no base URLs. */ + toPublic(): PublicAppConfig { + return { + defaultModel: this.defaultModel, + modelAliases: this.config.modelAliases, + providers: this.config.providers.map((provider) => ({ + id: provider.id, + name: provider.name, + enabled: provider.enabled, + available: this.isAvailable(provider), + models: provider.models.map((model) => ({ + id: model.id, + name: model.name, + reasoningEfforts: model.reasoningEfforts, + defaultReasoningEffort: model.defaultReasoningEffort + })) + })) + }; + } +} + +export interface PublicAppConfig { + defaultModel?: string; + modelAliases: Record; + providers: Array<{ + id: string; + name: string; + enabled: boolean; + available: boolean; + models: Array>; + }>; +} + +/** + * Loads `.config/config.json` and reloads it when the file changes, so models + * and providers can be edited without restarting the server. + */ +export class ConfigStore { + private cached?: { mtimeMs: number; snapshot: ConfigSnapshot }; + + constructor( + private readonly filePath: string, + private readonly env: NodeJS.ProcessEnv = process.env + ) {} + + static forProject(projectRoot: string, env: NodeJS.ProcessEnv = process.env): ConfigStore { + return new ConfigStore(path.join(projectRoot, '.config', 'config.json'), env); + } + + /** Throws `ConfigError` when the file is missing or invalid. */ + get(): ConfigSnapshot { + let mtimeMs: number; + try { + mtimeMs = fs.statSync(this.filePath).mtimeMs; + } catch { + throw new ConfigError(`Configuration file not found: ${this.filePath}`); + } + if (this.cached?.mtimeMs === mtimeMs) return this.cached.snapshot; + + let raw: unknown; + try { + raw = JSON.parse(fs.readFileSync(this.filePath, 'utf-8')); + } catch (error) { + throw new ConfigError(`config.json is not valid JSON: ${error instanceof Error ? error.message : String(error)}`); + } + const snapshot = new ConfigSnapshot(parseAppConfig(raw), this.env); + this.cached = { mtimeMs, snapshot }; + return snapshot; + } +} diff --git a/apps/server/src/llm/openai-adapter.test.ts b/apps/server/src/llm/openai-adapter.test.ts new file mode 100644 index 0000000..8a34053 --- /dev/null +++ b/apps/server/src/llm/openai-adapter.test.ts @@ -0,0 +1,118 @@ +import { describe, expect, it } from 'vitest'; +import type { Model, ModelProvider, ModelRequest, ModelResponse } from '@openai/agents'; +import { Usage } from '@openai/agents'; +import { OpenAIAdapter } from './openai-adapter.js'; +import type { AgentRequest } from './provider-adapter.js'; + +type Reply = { text: string } | { tool: string; input: string }; + +/** A scripted model: the real Agents SDK runs the loop, only the model call is faked. */ +function fakeProvider(script: (request: ModelRequest, modelName: string) => Reply | Promise) { + const requests: Array<{ modelName: string; request: ModelRequest }> = []; + let callCounter = 0; + const provider: ModelProvider = { + getModel(modelName?: string): Model { + const name = modelName ?? 'default'; + return { + async getResponse(request: ModelRequest): Promise { + requests.push({ modelName: name, request }); + const reply = await script(request, name); + const output: ModelResponse['output'] = + 'text' in reply + ? [{ type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: reply.text }] }] + : [ + { + type: 'function_call', + callId: `call_${++callCounter}`, + name: reply.tool, + arguments: JSON.stringify({ input: reply.input }), + status: 'completed' + } + ]; + return { usage: new Usage(), output }; + }, + async *getStreamedResponse() { + throw new Error('Streaming is not used by this adapter'); + } + }; + } + }; + return { provider, requests }; +} + +const hasToolOutput = (request: ModelRequest): boolean => + Array.isArray(request.input) && request.input.some((item) => item.type === 'function_call_result'); + +const baseRequest: AgentRequest = { + agentName: 'Tester', + systemPrompt: 'Be brief.', + userContent: 'What is 2 + 2?', + model: 'test-model', + webSearch: false, + subagentTools: [] +}; + +describe('OpenAIAdapter', () => { + it('sends the prompt, model, effort and web search tool through the Agents SDK', async () => { + const { provider, requests } = fakeProvider(() => ({ text: ' final answer ' })); + const adapter = new OpenAIAdapter({ apiKey: 'test', modelProvider: provider }); + + const output = await adapter.run({ ...baseRequest, reasoningEffort: 'low', webSearch: true }); + + expect(output).toBe('final answer'); + expect(requests).toHaveLength(1); + expect(requests[0].modelName).toBe('test-model'); + expect(requests[0].request.systemInstructions).toBe('Be brief.'); + expect(requests[0].request.modelSettings.reasoning?.effort).toBe('low'); + expect(requests[0].request.tools.map((tool) => tool.name)).toEqual(['web_search']); + }); + + it('exposes subagents as function tools and feeds their answers back to the model', async () => { + const { provider, requests } = fakeProvider((request) => + hasToolOutput(request) ? { text: 'parent done' } : { tool: 'subagent_helper_node_2', input: 'look this up' } + ); + const adapter = new OpenAIAdapter({ apiKey: 'test', modelProvider: provider }); + const subagentInputs: string[] = []; + + const output = await adapter.run({ + ...baseRequest, + subagentTools: [ + { + name: 'subagent_helper_node_2', + description: 'Delegates work to subagent Helper.', + run: async (input) => { + subagentInputs.push(input); + return 'child findings'; + } + } + ] + }); + + expect(output).toBe('parent done'); + expect(subagentInputs).toEqual(['look this up']); + expect(requests[0].request.tools[0]).toMatchObject({ + name: 'subagent_helper_node_2', + description: 'Delegates work to subagent Helper.' + }); + expect(JSON.stringify(requests[1].request.input)).toContain('child findings'); + }); + + it('rejects web search for Chat Completions providers', async () => { + const { provider } = fakeProvider(() => ({ text: 'unused' })); + const adapter = new OpenAIAdapter({ apiKey: 'test', api: 'chat_completions', modelProvider: provider }); + await expect(adapter.run({ ...baseRequest, webSearch: true })).rejects.toThrow(/Web Search is not available/); + }); + + it('stops when the signal aborts', async () => { + const controller = new AbortController(); + const { provider } = fakeProvider( + (request) => + new Promise((_resolve, reject) => { + request.signal?.addEventListener('abort', () => reject(new Error('aborted by signal'))); + controller.abort(); + }) + ); + const adapter = new OpenAIAdapter({ apiKey: 'test', modelProvider: provider }); + await expect(adapter.run({ ...baseRequest, signal: controller.signal })).rejects.toThrow(); + }); +}); diff --git a/apps/server/src/llm/openai-adapter.ts b/apps/server/src/llm/openai-adapter.ts new file mode 100644 index 0000000..bd5c00e --- /dev/null +++ b/apps/server/src/llm/openai-adapter.ts @@ -0,0 +1,87 @@ +import { Agent, OpenAIProvider, Runner, tool, webSearchTool } from '@openai/agents'; +import type { ModelProvider, ModelSettings, Tool } from '@openai/agents'; +import { z } from 'zod'; +import type { OpenAiApi } from './app-config.js'; +import { MAX_AGENT_TURNS, SUBAGENT_INPUT_DESCRIPTION } from './provider-adapter.js'; +import type { AgentRequest, ProviderAdapter } from './provider-adapter.js'; + +type ReasoningEffort = NonNullable['effort']>; + +export interface OpenAIAdapterOptions { + apiKey: string; + baseUrl?: string; + api?: OpenAiApi; + /** Replaces the SDK's OpenAI provider, for tests. */ + modelProvider?: ModelProvider; +} + +function toTextOutput(finalOutput: unknown): string { + if (typeof finalOutput === 'string') return finalOutput.trim(); + if (finalOutput === undefined || finalOutput === null) return 'Model returned no text output.'; + return JSON.stringify(finalOutput); +} + +/** + * OpenAI and OpenAI-compatible services, through the OpenAI Agents SDK. + * Each adapter has its own client, so several providers of this type can be + * configured side by side with different keys and base URLs. + */ +export class OpenAIAdapter implements ProviderAdapter { + private readonly runner: Runner; + + private readonly api: OpenAiApi; + + constructor(options: OpenAIAdapterOptions) { + this.api = options.api ?? 'responses'; + const modelProvider = + options.modelProvider ?? + new OpenAIProvider({ + apiKey: options.apiKey, + baseURL: options.baseUrl, + useResponses: this.api === 'responses' + }); + // Trace export goes to OpenAI with the process-wide key, which is wrong + // for proxies and compatible services, so it stays off. + this.runner = new Runner({ modelProvider, tracingDisabled: true }); + } + + async run(request: AgentRequest): Promise { + const tools: Tool[] = []; + + if (request.webSearch) { + if (this.api !== 'responses') { + throw new Error( + `Web Search is not available for "${request.model}": its provider uses the Chat Completions API.` + ); + } + tools.push(webSearchTool()); + } + + for (const subagent of request.subagentTools) { + tools.push( + tool({ + name: subagent.name, + description: subagent.description, + parameters: z.object({ input: z.string().describe(SUBAGENT_INPUT_DESCRIPTION) }), + execute: ({ input }) => subagent.run(input) + }) + ); + } + + const agent = new Agent({ + name: request.agentName, + instructions: request.systemPrompt, + model: request.model, + tools, + modelSettings: request.reasoningEffort + ? { reasoning: { effort: request.reasoningEffort as ReasoningEffort } } + : undefined + }); + + const result = await this.runner.run(agent, request.userContent, { + maxTurns: MAX_AGENT_TURNS, + signal: request.signal + }); + return toTextOutput(result.finalOutput); + } +} diff --git a/apps/server/src/llm/provider-adapter.ts b/apps/server/src/llm/provider-adapter.ts new file mode 100644 index 0000000..4cc2d29 --- /dev/null +++ b/apps/server/src/llm/provider-adapter.ts @@ -0,0 +1,31 @@ +/** A subagent exposed to a parent agent as a callable tool. */ +export interface SubagentTool { + name: string; + description: string; + /** Runs the subagent on the task text the parent model wrote and returns its answer. */ + run: (input: string) => Promise; +} + +/** One agent run, already resolved to a provider and model. */ +export interface AgentRequest { + agentName: string; + systemPrompt: string; + userContent: string; + model: string; + reasoningEffort?: string; + webSearch: boolean; + subagentTools: SubagentTool[]; + maxOutputTokens?: number; + refusalFallback?: boolean; + signal?: AbortSignal; +} + +/** Runs an agent loop (model calls plus tool calls) against one provider. */ +export interface ProviderAdapter { + run: (request: AgentRequest) => Promise; +} + +/** Upper bound on model turns in one agent run, so a tool loop cannot run forever. */ +export const MAX_AGENT_TURNS = 20; + +export const SUBAGENT_INPUT_DESCRIPTION = 'The task for the subagent, with all the context it needs.'; diff --git a/apps/server/src/llm/router.test.ts b/apps/server/src/llm/router.test.ts new file mode 100644 index 0000000..fccd097 --- /dev/null +++ b/apps/server/src/llm/router.test.ts @@ -0,0 +1,191 @@ +import { describe, expect, it } from 'vitest'; +import type { AgentRuntimeEvent } from '@agentflow/workflow-engine'; +import { ConfigSnapshot, parseAppConfig } from './app-config.js'; +import type { AgentRequest, ProviderAdapter } from './provider-adapter.js'; +import { ProviderRouterLLM, toToolName } from './router.js'; + +const config = parseAppConfig({ + defaultModel: 'gpt-a', + modelAliases: { 'gpt-old': 'gpt-a' }, + providers: [ + { + id: 'openai', + name: 'OpenAI', + models: [{ id: 'gpt-a', reasoningEfforts: ['low', 'high'], defaultReasoningEffort: 'low' }] + }, + { + id: 'anthropic', + name: 'Anthropic', + type: 'anthropic', + models: [{ id: 'claude-a', reasoningEfforts: ['medium', 'max'], defaultReasoningEffort: 'medium', refusalFallback: true }] + } + ] +}); + +const allKeys = { OPENAI_API_KEY: 'openai-key', ANTHROPIC_API_KEY: 'anthropic-key' }; + +/** Fake adapters that record what each provider was asked to run. */ +function setup( + env: NodeJS.ProcessEnv, + behaviour: (providerId: string, request: AgentRequest) => Promise | string = (id) => `${id} answer` +) { + const requests: Array<{ providerId: string; request: AgentRequest }> = []; + let adaptersCreated = 0; + const router = new ProviderRouterLLM( + () => new ConfigSnapshot(config, env), + ({ provider }): ProviderAdapter => { + adaptersCreated += 1; + return { + run: async (request) => { + requests.push({ providerId: provider.id, request }); + return behaviour(provider.id, request); + } + }; + } + ); + return { router, requests, adapterCount: () => adaptersCreated }; +} + +const invocation = (model: string, extra: Record = {}) => ({ + systemPrompt: 'system', + userContent: 'hello', + model, + ...extra +}); + +describe('ProviderRouterLLM', () => { + it('sends each model to the provider that lists it', async () => { + const { router, requests, adapterCount } = setup(allKeys); + + expect(await router.respond(invocation('gpt-a'))).toBe('openai answer'); + expect(await router.respond(invocation('claude-a'))).toBe('anthropic answer'); + expect(await router.respond(invocation('gpt-old'))).toBe('openai answer'); + + expect(requests.map((entry) => [entry.providerId, entry.request.model])).toEqual([ + ['openai', 'gpt-a'], + ['anthropic', 'claude-a'], + ['openai', 'gpt-a'] + ]); + expect(requests[1].request.refusalFallback).toBe(true); + expect(adapterCount()).toBe(2); + }); + + it('keeps a supported effort and replaces an unsupported one with the model default', async () => { + const { router, requests } = setup(allKeys); + await router.respond(invocation('gpt-a', { reasoningEffort: 'high' })); + await router.respond(invocation('claude-a', { reasoningEffort: 'low' })); + await router.respond(invocation('gpt-a')); + expect(requests.map((entry) => entry.request.reasoningEffort)).toEqual(['high', 'medium', 'low']); + }); + + it('passes the web search flag and abort signal through', async () => { + const { router, requests } = setup(allKeys); + const controller = new AbortController(); + await router.respond(invocation('gpt-a', { tools: { web_search: true } }), { signal: controller.signal }); + expect(requests[0].request.webSearch).toBe(true); + expect(requests[0].request.signal).toBe(controller.signal); + }); + + it('fails with a clear message for an unknown model or a missing key', async () => { + const { router } = setup({ OPENAI_API_KEY: 'k' }); + await expect(router.respond(invocation('gpt-99'))).rejects.toThrow(/"gpt-99" is not listed/); + await expect(router.respond(invocation('claude-a'))).rejects.toThrow(/ANTHROPIC_API_KEY is required/); + }); + + it('runs subagents on their own provider and reports the calls', async () => { + const events: AgentRuntimeEvent[] = []; + const { router, requests } = setup(allKeys, async (providerId, request) => { + if (request.subagentTools.length === 0) return `${providerId}:${request.userContent}`; + const outputs = []; + for (const subagent of request.subagentTools) outputs.push(await subagent.run(`task for ${subagent.name}`)); + return `${providerId}[${outputs.join(' | ')}]`; + }); + + const output = await router.respond( + invocation('gpt-a', { + tools: { subagents: true }, + subagents: [ + { + nodeId: 'node_2', + agentName: 'Researcher', + systemPrompt: 'research', + model: 'claude-a', + tools: { subagents: true }, + subagents: [{ nodeId: 'node_3', agentName: 'Checker', systemPrompt: 'check', model: 'gpt-a' }] + } + ] + }), + { parentNodeId: 'node_1', onRuntimeEvent: (event) => events.push(event) } + ); + + expect(output).toBe('openai[anthropic[openai:task for subagent_checker_node_3]]'); + expect(requests.map((entry) => [entry.providerId, entry.request.agentName])).toEqual([ + ['openai', 'Workflow Agent'], + ['anthropic', 'Researcher'], + ['openai', 'Checker'] + ]); + expect(requests[0].request.subagentTools[0].description).toContain('Delegates work to subagent Researcher'); + + expect(events.map((event) => [event.type, event.subagentNodeId, event.depth])).toEqual([ + ['subagent_call_start', 'node_2', 1], + ['subagent_call_start', 'node_3', 2], + ['subagent_call_end', 'node_3', 2], + ['subagent_call_end', 'node_2', 1] + ]); + expect(events.every((event) => event.parentNodeId === 'node_1')).toBe(true); + expect(events[1].parentCallId).toBe(events[0].callId); + expect(events[2].callId).toBe(events[1].callId); + }); + + it('reports a failed subagent call and lets the error reach the parent', async () => { + const events: AgentRuntimeEvent[] = []; + const { router } = setup(allKeys, async (_providerId, request) => { + if (request.subagentTools.length === 0) throw new Error('child exploded'); + return request.subagentTools[0].run('go'); + }); + + await expect( + router.respond( + invocation('gpt-a', { subagents: [{ nodeId: 'n2', agentName: 'Child', systemPrompt: 's', model: 'gpt-a' }] }), + { onRuntimeEvent: (event) => events.push(event) } + ) + ).rejects.toThrow('child exploded'); + expect(events.map((event) => event.type)).toEqual(['subagent_call_start', 'subagent_call_error']); + expect(events[1].message).toBe('child exploded'); + }); + + describe('preflight', () => { + const graph = (...models: Array) => ({ + nodes: [ + { id: 's', type: 'start', x: 0, y: 0 }, + ...models.map((model, index) => ({ id: `a${index}`, type: 'agent', x: 0, y: 0, data: { model } })) + ], + connections: [] + }); + + it('accepts graphs whose models all have keys, and graphs without agents', () => { + expect(setup(allKeys).router.preflight(graph('gpt-a', 'claude-a', undefined, 'gpt-old'))).toBeNull(); + expect(setup({}).router.preflight(graph())).toBeNull(); + }); + + it('returns 503 for a missing key and 400 for an unknown model', () => { + const { router } = setup({ OPENAI_API_KEY: 'k' }); + expect(router.preflight(graph('gpt-a', 'claude-a'))).toEqual({ + status: 503, + error: 'ANTHROPIC_API_KEY is required to run Agent nodes that use Anthropic models.' + }); + expect(router.preflight(graph('gpt-99'))).toMatchObject({ status: 400 }); + }); + }); +}); + +describe('toToolName', () => { + it('builds provider-safe names of at most 64 characters', () => { + expect(toToolName('Research Helper!', 'node_2')).toBe('subagent_research_helper_node_2'); + expect(toToolName('', 'node_7')).toBe('subagent_agent_node_7'); + const long = toToolName('A'.repeat(200), 'node_12'); + expect(long).toHaveLength(64); + expect(long.endsWith('_node_12')).toBe(true); + expect(long).toMatch(/^[a-z0-9_]+$/); + }); +}); diff --git a/apps/server/src/llm/router.ts b/apps/server/src/llm/router.ts new file mode 100644 index 0000000..aaffcc0 --- /dev/null +++ b/apps/server/src/llm/router.ts @@ -0,0 +1,231 @@ +import { randomUUID } from 'node:crypto'; +import type { WorkflowGraph } from '@agentflow/types'; +import type { + AgentInvocation, + AgentRespondOptions, + AgentRuntimeEvent, + AgentSubagentInvocation, + AgentToolsConfig, + WorkflowLLM +} from '@agentflow/workflow-engine'; +import { AnthropicAdapter } from './anthropic-adapter.js'; +import type { ConfigSnapshot, ResolvedModel } from './app-config.js'; +import { ConfigError } from './app-config.js'; +import { OpenAIAdapter } from './openai-adapter.js'; +import type { ProviderAdapter, SubagentTool } from './provider-adapter.js'; + +const MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION = 280; +const MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION = 4; +/** Tool names are limited to 64 characters by both providers. */ +const MAX_TOOL_NAME_LENGTH = 64; +const ROOT_NODE_ID = '__root__'; + +type AgentSpec = Pick< + AgentInvocation, + 'systemPrompt' | 'model' | 'reasoningEffort' | 'tools' | 'subagents' +> & { agentName: string }; + +interface RunContext { + snapshot: ConfigSnapshot; + rootNodeId: string; + depth: number; + parentCallId?: string; + signal?: AbortSignal; + onRuntimeEvent?: (event: AgentRuntimeEvent) => void; +} + +export type AdapterFactory = (resolved: ResolvedModel) => ProviderAdapter; + +export interface RunPreflightFailure { + status: 400 | 503; + error: string; +} + +export function toToolName(agentName: string, nodeId: string): string { + const nameSlug = + agentName + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '_') + .replace(/^_+|_+$/g, '') || 'agent'; + const nodeSlug = nodeId.replace(/[^a-zA-Z0-9_]+/g, '_').toLowerCase(); + const prefix = `subagent_${nameSlug}`.slice(0, Math.max(1, MAX_TOOL_NAME_LENGTH - nodeSlug.length - 1)); + return `${prefix}_${nodeSlug}`.slice(-MAX_TOOL_NAME_LENGTH); +} + +function formatToolKeyLabel(toolKey: string): string { + if (toolKey === 'web_search') return 'Web Search'; + if (toolKey === 'subagents') return 'Subagents'; + return toolKey + .split('_') + .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) + .join(' '); +} + +function getEnabledToolLabels(tools: AgentToolsConfig | undefined): string[] { + if (!tools) return []; + return Object.entries(tools) + .filter(([, enabled]) => Boolean(enabled)) + .map(([toolKey]) => formatToolKeyLabel(toolKey)); +} + +function summarizeSystemPrompt(systemPrompt: string): string { + const normalized = systemPrompt.replace(/\s+/g, ' ').trim(); + if (!normalized) return 'No system prompt provided.'; + if (normalized.length <= MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION) return normalized; + return `${normalized.slice(0, MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION).trimEnd()}…`; +} + +function subagentName(subagent: AgentSubagentInvocation): string { + return (subagent.agentName || 'Agent').trim() || 'Agent'; +} + +function summarizeNestedSubagents(subagents: AgentSubagentInvocation[] | undefined): string { + const names = (subagents ?? []).map(subagentName); + if (names.length === 0) return 'None'; + if (names.length <= MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION) return names.join(', '); + const visible = names.slice(0, MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION).join(', '); + return `${visible}, +${names.length - MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION} more`; +} + +function buildSubagentToolDescription(subagent: AgentSubagentInvocation): string { + const toolLabels = getEnabledToolLabels(subagent.tools); + return ( + `Delegates work to subagent ${subagentName(subagent)}. ` + + `System prompt: ${summarizeSystemPrompt(subagent.systemPrompt)} ` + + `Available tools: ${toolLabels.length > 0 ? toolLabels.join(', ') : 'None'}. ` + + `Nested subagents: ${summarizeNestedSubagents(subagent.subagents)}.` + ); +} + +function defaultAdapterFactory({ provider, apiKey }: ResolvedModel): ProviderAdapter { + if (provider.type === 'anthropic') { + return new AnthropicAdapter({ apiKey, baseUrl: provider.baseUrl }); + } + return new OpenAIAdapter({ apiKey, baseUrl: provider.baseUrl, api: provider.api }); +} + +/** + * The engine's LLM: sends each agent to the provider that lists its model in + * `.config/config.json`. Subagents are plain function tools that call back + * into this router, so a parent and its subagents may use different providers. + */ +export class ProviderRouterLLM implements WorkflowLLM { + private readonly adapters = new Map(); + + constructor( + private readonly getSnapshot: () => ConfigSnapshot, + private readonly createAdapter: AdapterFactory = defaultAdapterFactory + ) {} + + async respond(invocation: AgentInvocation, options?: AgentRespondOptions): Promise { + return this.runAgent( + { ...invocation, agentName: 'Workflow Agent' }, + invocation.userContent, + { + snapshot: this.getSnapshot(), + rootNodeId: options?.parentNodeId || ROOT_NODE_ID, + depth: 0, + signal: options?.signal, + onRuntimeEvent: options?.onRuntimeEvent + } + ); + } + + /** + * Checks before a run starts that every agent node names a configured model + * whose provider has an API key. Returns null when the graph can run. + */ + preflight(graph: WorkflowGraph): RunPreflightFailure | null { + const agentNodes = graph.nodes.filter((node) => node.type === 'agent'); + if (agentNodes.length === 0) return null; + + let snapshot: ConfigSnapshot; + try { + snapshot = this.getSnapshot(); + } catch (error) { + if (error instanceof ConfigError) return { status: 503, error: error.message }; + throw error; + } + + for (const node of agentNodes) { + const model = typeof node.data?.model === 'string' ? node.data.model : undefined; + const lookup = snapshot.lookup(model); + if (!lookup.ok) { + return { status: lookup.reason === 'missing_key' ? 503 : 400, error: lookup.message }; + } + } + return null; + } + + private adapterFor(resolved: ResolvedModel): ProviderAdapter { + const { provider, apiKey } = resolved; + // Keyed by everything a client is built from, so an edited config or a + // rotated key gets a fresh client. + const cacheKey = JSON.stringify([provider.id, provider.type, provider.baseUrl, provider.api, apiKey]); + let adapter = this.adapters.get(cacheKey); + if (!adapter) { + adapter = this.createAdapter(resolved); + this.adapters.set(cacheKey, adapter); + } + return adapter; + } + + private async runAgent(spec: AgentSpec, userContent: string, context: RunContext): Promise { + const lookup = context.snapshot.lookup(spec.model); + if (!lookup.ok) throw new Error(lookup.message); + const { model } = lookup.resolved; + + const requestedEffort = spec.reasoningEffort; + const reasoningEffort = + requestedEffort && model.reasoningEfforts.includes(requestedEffort) + ? requestedEffort + : model.defaultReasoningEffort; + + return this.adapterFor(lookup.resolved).run({ + agentName: spec.agentName, + systemPrompt: spec.systemPrompt, + userContent, + model: model.id, + reasoningEffort, + webSearch: Boolean(spec.tools?.web_search), + subagentTools: (spec.subagents ?? []).map((subagent) => this.toSubagentTool(subagent, context)), + maxOutputTokens: model.maxOutputTokens, + refusalFallback: model.refusalFallback, + signal: context.signal + }); + } + + private toSubagentTool(subagent: AgentSubagentInvocation, parent: RunContext): SubagentTool { + const name = subagentName(subagent); + return { + name: toToolName(name, subagent.nodeId), + description: buildSubagentToolDescription(subagent), + run: async (input: string) => { + const event: AgentRuntimeEvent = { + type: 'subagent_call_start', + parentNodeId: parent.rootNodeId, + subagentNodeId: subagent.nodeId, + subagentName: name, + callId: randomUUID(), + parentCallId: parent.parentCallId, + depth: parent.depth + 1 + }; + parent.onRuntimeEvent?.(event); + try { + const output = await this.runAgent({ ...subagent, agentName: name }, input, { + ...parent, + depth: event.depth, + parentCallId: event.callId + }); + parent.onRuntimeEvent?.({ ...event, type: 'subagent_call_end' }); + return output; + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + parent.onRuntimeEvent?.({ ...event, type: 'subagent_call_error', message }); + throw error; + } + } + }; + } +} diff --git a/apps/server/src/logger.ts b/apps/server/src/logger.ts index 9427efd..ee57ee2 100644 --- a/apps/server/src/logger.ts +++ b/apps/server/src/logger.ts @@ -1,7 +1,10 @@ - +import { format } from 'node:util'; + +/** Supports printf-style placeholders (`%s`, `%d`) in the first argument. */ +const line = (level: string, args: unknown[]): string => `[${level}] ${format(...args)}`; + export const logger = { - info: (...args: unknown[]) => console.log('[INFO]', ...args), - warn: (...args: unknown[]) => console.warn('[WARN]', ...args), - error: (...args: unknown[]) => console.error('[ERROR]', ...args) + info: (...args: unknown[]) => console.log(line('INFO', args)), + warn: (...args: unknown[]) => console.warn(line('WARN', args)), + error: (...args: unknown[]) => console.error(line('ERROR', args)) }; - diff --git a/apps/server/src/routes/workflows.ts b/apps/server/src/routes/workflows.ts index a865eaf..3119a93 100644 --- a/apps/server/src/routes/workflows.ts +++ b/apps/server/src/routes/workflows.ts @@ -1,314 +1,286 @@ -import fs from 'node:fs'; +import fs from 'node:fs/promises'; import path from 'node:path'; import type { Request, Response, Router } from 'express'; import { Router as createRouter } from 'express'; -import type { WorkflowGraph, WorkflowLogEntry, WorkflowRunRecord, WorkflowRunResult } from '@agentic/types'; -import type { WorkflowLLM } from '@agentic/workflow-engine'; -import WorkflowEngine from '@agentic/workflow-engine'; -import { addWorkflow, getWorkflow, removeWorkflow } from '../store/active-workflows'; -import { saveRunRecord } from '../services/persistence'; -import { config } from '../config'; -import { logger } from '../logger'; +import type { WorkflowGraph, WorkflowLogEntry, WorkflowRunRecord, WorkflowRunResult } from '@agentflow/types'; +import type { WorkflowLLM } from '@agentflow/workflow-engine'; +import { WorkflowEngine, validateWorkflowGraph } from '@agentflow/workflow-engine'; +import type { RunStore } from '../store/run-store.js'; +import { isValidRunId, readRunRecord, saveRunRecord } from '../services/persistence.js'; +import { logger } from '../logger.js'; + +const DEFAULT_SSE_HEARTBEAT_MS = 15_000; + +export interface WorkflowRouterOptions { + llm?: WorkflowLLM; + store: RunStore; + runsDir: string; + projectRoot: string; + maxSteps?: number; + /** + * Checks that a graph can run (models configured, provider keys present). + * Without it, any graph with an agent node needs `llm` to be set. + */ + preflight?: (graph: WorkflowGraph) => { status: number; error: string } | null; + /** Browser-safe provider and model configuration for `GET /config`. */ + getPublicConfig?: () => unknown; + /** Model for agent nodes that do not name one. */ + getDefaultModel?: () => string | undefined; + /** Interval between SSE comment lines that keep idle proxies from closing the stream. */ + sseHeartbeatMs?: number; +} + +type StreamEvent = + | { type: 'start'; runId: string } + | { type: 'log'; entry: WorkflowLogEntry } + | { type: 'done'; result: WorkflowRunResult } + | { type: 'error'; message: string }; -function validateGraph(graph: WorkflowGraph | undefined): graph is WorkflowGraph { - return Boolean(graph && Array.isArray(graph.nodes) && Array.isArray(graph.connections)); +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); } -async function persistResult(engine: WorkflowEngine, result: WorkflowRunResult) { - try { - const workflow = getEngineWorkflow(engine); +function isResumeInput(input: unknown): input is string | Record | undefined { + return ( + input === undefined || + typeof input === 'string' || + (typeof input === 'object' && input !== null && !Array.isArray(input)) + ); +} - if (!workflow) { - throw new Error('Workflow graph not available on engine instance'); - } +export function createWorkflowRouter(options: WorkflowRouterOptions): Router { + const { llm, store, runsDir, projectRoot, maxSteps } = options; + const heartbeatMs = options.sseHeartbeatMs ?? DEFAULT_SSE_HEARTBEAT_MS; + const router = createRouter(); + const withWorkflow = (engine: WorkflowEngine, result: WorkflowRunResult): WorkflowRunResult => ({ + ...result, + workflow: engine.getGraph() + }); + + const persist = async (engine: WorkflowEngine, result: WorkflowRunResult): Promise => { const record: WorkflowRunRecord = { runId: result.runId, - workflow, + workflow: engine.getGraph(), logs: result.logs, status: result.status, state: result.state, currentNodeId: result.currentNodeId, waitingForInput: result.waitingForInput }; - - await saveRunRecord(config.runsDir, record); - } catch (error) { - logger.error('Failed to persist run result', error); - } -} - -function getEngineWorkflow(engine: WorkflowEngine): WorkflowGraph | undefined { - // Backward compatibility: fall back to private graph if getGraph is unavailable. - const engineAny = engine as WorkflowEngine & { getGraph?: () => WorkflowGraph }; - if (typeof engineAny.getGraph === 'function') { - return engineAny.getGraph(); - } - return Reflect.get(engine, 'graph') as WorkflowGraph | undefined; -} - -function setEngineOnLog( - engine: WorkflowEngine, - onLog?: (entry: WorkflowLogEntry) => void -): void { - const engineAny = engine as WorkflowEngine & { setOnLog?: (handler?: (entry: WorkflowLogEntry) => void) => void }; - if (typeof engineAny.setOnLog === 'function') { - engineAny.setOnLog(onLog); - } -} - -export function createWorkflowRouter(llm?: WorkflowLLM): Router { - const router = createRouter(); - const activeResumeModes = new Map(); - - const tryAcquireResumeLock = (runId: string, mode: 'stream' | 'json'): boolean => { - if (activeResumeModes.has(runId)) { - return false; - } - activeResumeModes.set(runId, mode); - return true; - }; - - const releaseResumeLock = (runId: string, mode: 'stream' | 'json'): void => { - if (activeResumeModes.get(runId) === mode) { - activeResumeModes.delete(runId); + try { + await saveRunRecord(runsDir, record); + } catch (error) { + logger.error('Failed to persist run result', error); } }; - router.post('/run', async (req: Request, res: Response) => { - const { graph } = req.body as { graph?: WorkflowGraph }; - - if (!validateGraph(graph)) { - res.status(400).json({ error: 'Invalid workflow graph payload' }); - return; - } - - const hasAgentNode = graph.nodes.some((node) => node.type === 'agent'); - if (hasAgentNode && !llm) { - res.status(503).json({ - error: 'OPENAI_API_KEY is required to run workflows with Agent nodes.' - }); - return; - } - + /** + * Runs one engine step (`run` or `resume`) under the per-run lock, persists + * the outcome and drops finished runs from memory. + */ + const execute = async ( + engine: WorkflowEngine, + step: () => Promise, + onLog?: (entry: WorkflowLogEntry) => void + ): Promise => { + const runId = engine.getRunId(); + engine.setOnLog(onLog); try { - const runId = Date.now().toString(); - const engine = new WorkflowEngine(graph, { runId, llm }); - addWorkflow(engine); - - const result = await engine.run(); - await persistResult(engine, result); - + const result = await step(); + await persist(engine, result); if (result.status !== 'paused') { - removeWorkflow(runId); + store.remove(runId); } - - const workflow = getEngineWorkflow(engine) ?? graph; - res.json({ ...result, workflow }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - logger.error('Failed to execute workflow', message); - res.status(500).json({ error: 'Failed to execute workflow', details: message }); + return withWorkflow(engine, result); + } finally { + engine.setOnLog(undefined); + store.unlock(runId); } - }); - - router.post('/run-stream', async (req: Request, res: Response) => { - const { graph } = req.body as { graph?: WorkflowGraph }; + }; - if (!validateGraph(graph)) { - res.status(400).json({ error: 'Invalid workflow graph payload' }); - return; + /** Validates a run request. Sends the error response and returns null when invalid. */ + const parseRunRequest = (req: Request, res: Response): WorkflowGraph | null => { + const validation = validateWorkflowGraph((req.body as { graph?: unknown } | undefined)?.graph); + if (!validation.ok) { + res.status(400).json({ error: 'Invalid workflow graph payload', details: validation.errors }); + return null; } - - const hasAgentNode = graph.nodes.some((node) => node.type === 'agent'); - if (hasAgentNode && !llm) { - res.status(503).json({ - error: 'OPENAI_API_KEY is required to run workflows with Agent nodes.' - }); - return; + const hasAgentNode = validation.graph.nodes.some((node) => node.type === 'agent'); + const failure = options.preflight + ? options.preflight(validation.graph) + : hasAgentNode && !llm + ? { status: 503, error: 'No LLM backend is configured to run workflows with Agent nodes.' } + : null; + if (failure) { + res.status(failure.status).json({ error: failure.error }); + return null; } + return validation.graph; + }; - res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); - res.setHeader('Connection', 'keep-alive'); - res.flushHeaders(); - - let clientDisconnected = false; - res.on('close', () => { clientDisconnected = true; }); - - const sendEvent = (data: object) => { - if (clientDisconnected) return; - res.write(`data: ${JSON.stringify(data)}\n\n`); - }; - - let engine: WorkflowEngine | undefined; - try { - const runId = Date.now().toString(); - engine = new WorkflowEngine(graph, { runId, llm }); - setEngineOnLog(engine, (entry) => sendEvent({ type: 'log', entry })); - addWorkflow(engine); - sendEvent({ type: 'start', runId }); - - const result = await engine.run(); - await persistResult(engine, result); - - if (result.status !== 'paused') { - removeWorkflow(runId); - } - - const workflow = getEngineWorkflow(engine) ?? graph; - sendEvent({ type: 'done', result: { ...result, workflow } }); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - logger.error('Failed to execute workflow stream', message); - sendEvent({ type: 'error', message }); - } finally { - if (engine) { - setEngineOnLog(engine); - } - res.end(); - } - }); + const startEngine = (graph: WorkflowGraph): WorkflowEngine => { + const engine = new WorkflowEngine(graph, { llm, maxSteps, defaultModel: options.getDefaultModel?.() }); + store.add(engine); + store.tryLock(engine.getRunId()); + return engine; + }; - router.post('/resume-stream', async (req: Request, res: Response) => { - const { runId, input } = req.body as { runId?: string; input?: unknown }; - if (!runId) { + /** Finds a paused run and takes its lock. Sends the error response and returns null on failure. */ + const acquireResumableRun = (req: Request, res: Response): { engine: WorkflowEngine; input: string | Record | undefined } | null => { + const { runId, input } = (req.body ?? {}) as { runId?: unknown; input?: unknown }; + if (!isValidRunId(runId)) { res.status(400).json({ error: 'runId is required' }); - return; + return null; } - - const engine = getWorkflow(runId); + if (!isResumeInput(input)) { + res.status(400).json({ error: 'input must be a string or an object' }); + return null; + } + const engine = store.get(runId); if (!engine) { res.status(404).json({ error: 'Run ID not found' }); - return; + return null; } - if (!tryAcquireResumeLock(runId, 'stream')) { - res.status(409).json({ error: 'Run is already being resumed. Use a single resume endpoint per run.' }); - return; + if (!store.tryLock(runId)) { + res.status(409).json({ error: 'Run is already executing. Wait for it to pause before resuming.' }); + return null; } + return { engine, input }; + }; + const openEventStream = (res: Response) => { res.setHeader('Content-Type', 'text/event-stream'); - res.setHeader('Cache-Control', 'no-cache'); + res.setHeader('Cache-Control', 'no-cache, no-transform'); res.setHeader('Connection', 'keep-alive'); + res.setHeader('X-Accel-Buffering', 'no'); res.flushHeaders(); - let clientDisconnected = false; - res.on('close', () => { clientDisconnected = true; }); - - const sendEvent = (data: object) => { - if (clientDisconnected) return; - res.write(`data: ${JSON.stringify(data)}\n\n`); + let open = true; + const heartbeat = setInterval(() => { + if (open) res.write(': ping\n\n'); + }, heartbeatMs); + heartbeat.unref(); + // A closed stream does not cancel the run: the client can reload and pick + // it up again through GET /run/:runId. Cancelling is explicit (POST /cancel). + res.on('close', () => { + open = false; + clearInterval(heartbeat); + }); + + return { + send: (event: StreamEvent) => { + if (open) res.write(`data: ${JSON.stringify(event)}\n\n`); + }, + end: () => { + clearInterval(heartbeat); + if (open) res.end(); + } }; + }; + const streamExecution = async ( + res: Response, + engine: WorkflowEngine, + step: () => Promise + ): Promise => { + const stream = openEventStream(res); try { - setEngineOnLog(engine, (entry) => sendEvent({ type: 'log', entry })); - sendEvent({ type: 'start', runId }); - - const result = await engine.resume(input as Record); - await persistResult(engine, result); - - if (result.status !== 'paused') { - removeWorkflow(runId); - } - - const workflow = getEngineWorkflow(engine); - sendEvent({ type: 'done', result: workflow ? { ...result, workflow } : result }); + stream.send({ type: 'start', runId: engine.getRunId() }); + const result = await execute(engine, step, (entry) => stream.send({ type: 'log', entry })); + stream.send({ type: 'done', result }); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - logger.error('Failed to resume workflow stream', message); - sendEvent({ type: 'error', message }); + const message = errorMessage(error); + logger.error('Workflow stream failed', message); + stream.send({ type: 'error', message }); } finally { - releaseResumeLock(runId, 'stream'); - setEngineOnLog(engine); - res.end(); + stream.end(); } - }); + }; - router.post('/resume', async (req: Request, res: Response) => { - const { runId, input } = req.body as { runId?: string; input?: unknown }; - if (!runId) { - res.status(400).json({ error: 'runId is required' }); - return; + const respondWithExecution = async ( + res: Response, + engine: WorkflowEngine, + step: () => Promise + ): Promise => { + try { + res.json(await execute(engine, step)); + } catch (error) { + const message = errorMessage(error); + logger.error('Workflow execution failed', message); + res.status(500).json({ error: 'Failed to execute workflow', details: message }); } + }; - const engine = getWorkflow(runId); - if (!engine) { - res.status(404).json({ error: 'Run ID not found' }); - return; - } - if (!tryAcquireResumeLock(runId, 'json')) { - res.status(409).json({ error: 'Run is already being resumed. Use a single resume endpoint per run.' }); - return; - } + router.post('/run', async (req: Request, res: Response) => { + const graph = parseRunRequest(req, res); + if (!graph) return; + const engine = startEngine(graph); + await respondWithExecution(res, engine, () => engine.run()); + }); - try { - setEngineOnLog(engine); - const result = await engine.resume(input as Record); - await persistResult(engine, result); + router.post('/run-stream', async (req: Request, res: Response) => { + const graph = parseRunRequest(req, res); + if (!graph) return; + const engine = startEngine(graph); + await streamExecution(res, engine, () => engine.run()); + }); - if (result.status !== 'paused') { - removeWorkflow(runId); - } + router.post('/resume', async (req: Request, res: Response) => { + const run = acquireResumableRun(req, res); + if (!run) return; + await respondWithExecution(res, run.engine, () => run.engine.resume(run.input)); + }); - const workflow = getEngineWorkflow(engine); - res.json(workflow ? { ...result, workflow } : result); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - logger.error('Failed to resume workflow', message); - res.status(500).json({ error: 'Failed to resume workflow', details: message }); - } finally { - releaseResumeLock(runId, 'json'); - } + router.post('/resume-stream', async (req: Request, res: Response) => { + const run = acquireResumableRun(req, res); + if (!run) return; + await streamExecution(res, run.engine, () => run.engine.resume(run.input)); }); - router.get('/default-workflow', (_req: Request, res: Response) => { - const filePath = path.join(config.projectRoot, '.config', 'default-workflow.json'); - if (!fs.existsSync(filePath)) { - res.status(404).json({ error: 'No default workflow found' }); + router.post('/cancel', async (req: Request, res: Response) => { + const { runId } = (req.body ?? {}) as { runId?: unknown }; + if (!isValidRunId(runId)) { + res.status(400).json({ error: 'runId is required' }); return; } - try { - const raw = fs.readFileSync(filePath, 'utf-8'); - const graph = JSON.parse(raw) as WorkflowGraph; - if (!validateGraph(graph)) { - res.status(400).json({ error: 'default-workflow.json is not a valid workflow graph' }); - return; - } - res.json(graph); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - logger.error('Failed to read default workflow', message); - res.status(500).json({ error: 'Failed to read default workflow', details: message }); + const engine = store.get(runId); + if (!engine || !engine.cancel()) { + res.status(404).json({ error: 'Run is not active' }); + return; } + + const result = engine.getResult(); + // A run that is executing is persisted and removed by the request that + // drives it, once its in-flight calls have unwound. A paused run has no + // such request, so it is finalised here. + if (!store.isBusy(runId)) { + await persist(engine, result); + store.remove(runId); + } + res.json(withWorkflow(engine, result)); }); - router.get('/run/:runId', (req: Request, res: Response) => { + router.get('/run/:runId', async (req: Request, res: Response) => { const { runId } = req.params; - - // Reject anything that isn't a plain numeric timestamp to prevent path traversal - if (!/^\d+$/.test(runId)) { + if (!isValidRunId(runId)) { res.status(400).json({ error: 'Invalid runId' }); return; } - // Check in-memory first — catches engines that are still running or paused - const engine = getWorkflow(runId); + // In-memory first: covers runs that are still executing or paused. + const engine = store.get(runId); if (engine) { - const result = engine.getResult(); - const workflow = getEngineWorkflow(engine); - res.json(workflow ? { ...result, workflow } : result); + res.json(withWorkflow(engine, engine.getResult())); return; } - // Fall back to the persisted run record on disk - const filePath = path.join(config.runsDir, `run_${runId}.json`); - if (!fs.existsSync(filePath)) { - res.status(404).json({ error: 'Run not found' }); - return; - } try { - const record = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as WorkflowRunRecord; - // Reconstruct WorkflowRunResult using persisted fields where available + const record = await readRunRecord(runsDir, runId); + if (!record) { + res.status(404).json({ error: 'Run not found' }); + return; + } const result: WorkflowRunResult = { runId: record.runId, status: record.status, @@ -320,22 +292,54 @@ export function createWorkflowRouter(llm?: WorkflowLLM): Router { }; res.json(result); } catch (error) { - const message = error instanceof Error ? error.message : String(error); - res.status(500).json({ error: 'Failed to read run record', details: message }); + res.status(500).json({ error: 'Failed to read run record', details: errorMessage(error) }); } }); - router.get('/config', (_req: Request, res: Response) => { - const filePath = path.join(config.projectRoot, '.config', 'config.json'); - if (!fs.existsSync(filePath)) { - res.status(404).json({ error: 'No config found' }); - return; + const readProjectJson = async (fileName: string): Promise => { + try { + return JSON.parse(await fs.readFile(path.join(projectRoot, '.config', fileName), 'utf-8')); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined; + throw error; } + }; + + router.get('/default-workflow', async (_req: Request, res: Response) => { try { - const raw = fs.readFileSync(filePath, 'utf-8'); - res.json(JSON.parse(raw)); + const graph = await readProjectJson('default-workflow.json'); + if (graph === undefined) { + res.status(404).json({ error: 'No default workflow found' }); + return; + } + const validation = validateWorkflowGraph(graph); + if (!validation.ok) { + res.status(400).json({ + error: 'default-workflow.json is not a valid workflow graph', + details: validation.errors + }); + return; + } + res.json(validation.graph); + } catch (error) { + const message = errorMessage(error); + logger.error('Failed to read default workflow', message); + res.status(500).json({ error: 'Failed to read default workflow', details: message }); + } + }); + + router.get('/config', async (_req: Request, res: Response) => { + try { + const appConfig = options.getPublicConfig + ? options.getPublicConfig() + : await readProjectJson('config.json'); + if (appConfig === undefined) { + res.status(404).json({ error: 'No config found' }); + return; + } + res.json(appConfig); } catch (error) { - const message = error instanceof Error ? error.message : String(error); + const message = errorMessage(error); logger.error('Failed to read config', message); res.status(500).json({ error: 'Failed to read config', details: message }); } diff --git a/apps/server/src/services/openai-agents-llm.ts b/apps/server/src/services/openai-agents-llm.ts deleted file mode 100644 index c2ef979..0000000 --- a/apps/server/src/services/openai-agents-llm.ts +++ /dev/null @@ -1,526 +0,0 @@ -import type { - AgentInvocation, - AgentRespondOptions, - AgentRuntimeEvent, - AgentSubagentInvocation, - AgentToolsConfig, - WorkflowLLM -} from '@agentic/workflow-engine'; - -type ToolCallDetails = { - toolCall?: { - callId?: unknown; - id?: unknown; - }; -}; - -type AgentsSdkTool = { - name?: unknown; -}; - -type AgentsSdkAgent = { - asTool: (options: { - toolName?: string; - toolDescription?: string; - runOptions?: { maxTurns?: number }; - }) => AgentsSdkTool; - on( - event: 'agent_start', - listener: (context: unknown, agent: AgentsSdkAgent) => void - ): void; - on( - event: 'agent_end', - listener: (context: unknown, output: string) => void - ): void; - on( - event: 'agent_tool_start', - listener: (context: unknown, tool: AgentsSdkTool, details: ToolCallDetails) => void - ): void; - on( - event: 'agent_tool_end', - listener: ( - context: unknown, - tool: AgentsSdkTool, - result: string, - details: ToolCallDetails - ) => void - ): void; -}; - -type AgentsSdkRunner = { - on( - event: 'agent_start', - listener: (context: unknown, agent: AgentsSdkAgent) => void - ): void; - on( - event: 'agent_end', - listener: (context: unknown, agent: AgentsSdkAgent, output: string) => void - ): void; - on( - event: 'agent_tool_start', - listener: ( - context: unknown, - agent: AgentsSdkAgent, - tool: AgentsSdkTool, - details: ToolCallDetails - ) => void - ): void; - on( - event: 'agent_tool_end', - listener: ( - context: unknown, - agent: AgentsSdkAgent, - tool: AgentsSdkTool, - result: string, - details: ToolCallDetails - ) => void - ): void; - run: ( - agent: AgentsSdkAgent, - input: string, - options?: { maxTurns?: number } - ) => Promise<{ finalOutput?: unknown }>; -}; - -type AgentsSdkModule = { - Agent: new (config: Record) => AgentsSdkAgent; - Runner: new () => AgentsSdkRunner; - webSearchTool: () => AgentsSdkTool; -}; - -type AgentNodeMeta = { - nodeId: string; - agentName: string; - parentNodeId?: string; -}; - -type AgentContextState = { - nodeId: string; - depth: number; - activeCallId?: string; -}; - -type PendingChildCall = { - callId: string; - depth: number; -}; - -type AgentBuildRegistry = { - toolRegistry: Map; - agentRegistry: WeakMap; - agentsByNodeId: Map; -}; - -let sdkModulePromise: Promise | null = null; -const MAX_AGENT_TURNS = 20; -const MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION = 280; -const MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION = 4; - -async function loadAgentsSdk(): Promise { - if (!sdkModulePromise) { - sdkModulePromise = (new Function('moduleName', 'return import(moduleName);') as ( - moduleName: string - ) => Promise)('@openai/agents').catch((error: unknown) => { - sdkModulePromise = null; - const message = error instanceof Error ? error.message : String(error); - throw new Error( - `OpenAI Agents SDK is required but '@openai/agents' is unavailable: ${message}` - ); - }); - } - return sdkModulePromise; -} - -function isObject(value: unknown): value is object { - return typeof value === 'object' && value !== null; -} - -function toToolName(agentName: string, nodeId: string): string { - const nameSlug = agentName - .trim() - .toLowerCase() - .replace(/[^a-z0-9]+/g, '_') - .replace(/^_+|_+$/g, ''); - const fallbackName = nameSlug || 'agent'; - const nodeSlug = nodeId.replace(/[^a-zA-Z0-9_]+/g, '_'); - return `subagent_${fallbackName}_${nodeSlug}`.toLowerCase(); -} - -function getAgentName(invocation: AgentInvocation | AgentSubagentInvocation): string { - if ( - 'agentName' in invocation && - typeof invocation.agentName === 'string' && - invocation.agentName.trim() - ) { - return invocation.agentName.trim(); - } - return 'Workflow Agent'; -} - -function getToolName(tool: AgentsSdkTool): string | null { - return typeof tool.name === 'string' && tool.name.trim() ? tool.name : null; -} - -function getToolCallId(details: ToolCallDetails): string | null { - const callId = details.toolCall?.callId; - if (typeof callId === 'string' && callId.trim()) { - return callId; - } - const id = details.toolCall?.id; - if (typeof id === 'string' && id.trim()) { - return id; - } - return null; -} - -function formatToolKeyLabel(toolKey: string): string { - if (toolKey === 'web_search') return 'Web Search'; - if (toolKey === 'subagents') return 'Subagents'; - return toolKey - .split('_') - .map((part) => part.charAt(0).toUpperCase() + part.slice(1)) - .join(' '); -} - -function getEnabledToolLabels(tools: AgentToolsConfig | undefined): string[] { - if (!tools) return []; - return Object.entries(tools) - .filter(([, enabled]) => Boolean(enabled)) - .map(([toolKey]) => formatToolKeyLabel(toolKey)); -} - -function summarizeSystemPrompt(systemPrompt: string): string { - const normalized = systemPrompt.replace(/\s+/g, ' ').trim(); - if (!normalized) { - return 'No system prompt provided.'; - } - if (normalized.length <= MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION) { - return normalized; - } - return `${normalized.slice(0, MAX_SUBAGENT_PROMPT_CHARS_IN_DESCRIPTION).trimEnd()}…`; -} - -function summarizeNestedSubagents(subagents: AgentSubagentInvocation[] | undefined): string { - const nested = subagents ?? []; - if (nested.length === 0) { - return 'None'; - } - - const names = nested.map((entry) => (entry.agentName || 'Agent').trim() || 'Agent'); - if (names.length <= MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION) { - return names.join(', '); - } - - const visibleNames = names.slice(0, MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION).join(', '); - const remaining = names.length - MAX_NESTED_SUBAGENT_NAMES_IN_DESCRIPTION; - return `${visibleNames}, +${remaining} more`; -} - -function buildSubagentToolDescription( - subagentName: string, - subagent: AgentSubagentInvocation -): string { - const toolLabels = getEnabledToolLabels(subagent.tools); - const toolSummary = toolLabels.length > 0 ? toolLabels.join(', ') : 'None'; - const promptSummary = summarizeSystemPrompt(subagent.systemPrompt); - const nestedSubagentSummary = summarizeNestedSubagents(subagent.subagents); - return `Delegates work to subagent ${subagentName}. System prompt: ${promptSummary} Available tools: ${toolSummary}. Nested subagents: ${nestedSubagentSummary}.`; -} - -function buildSdkAgent( - invocation: AgentInvocation | AgentSubagentInvocation, - sdk: AgentsSdkModule, - nodeId: string, - registry: AgentBuildRegistry, - ancestry: Set = new Set() -): AgentsSdkAgent { - if (ancestry.has(nodeId)) { - throw new Error(`Subagent cycle detected while building SDK agent tree at "${nodeId}".`); - } - - const nextAncestry = new Set(ancestry); - nextAncestry.add(nodeId); - const tools = buildAgentTools(invocation, sdk, registry, nodeId, nextAncestry); - const agentName = getAgentName(invocation); - - const agentConfig: Record = { - name: agentName, - instructions: invocation.systemPrompt, - model: invocation.model - }; - - if (tools.length > 0) { - agentConfig.tools = tools; - } - - if (invocation.reasoningEffort) { - agentConfig.modelSettings = { - reasoning: { - effort: invocation.reasoningEffort - } - }; - } - - const agent = new sdk.Agent(agentConfig); - registry.agentRegistry.set(agent as object, { nodeId, agentName }); - registry.agentsByNodeId.set(nodeId, agent); - return agent; -} - -function buildAgentTools( - invocation: AgentInvocation | AgentSubagentInvocation, - sdk: AgentsSdkModule, - registry: AgentBuildRegistry, - parentNodeId: string, - ancestry: Set -): AgentsSdkTool[] { - const tools: AgentsSdkTool[] = []; - - if (invocation.tools?.web_search) { - tools.push(sdk.webSearchTool()); - } - - const subagents = invocation.subagents ?? []; - for (const subagent of subagents) { - const childAgent = buildSdkAgent(subagent, sdk, subagent.nodeId, registry, ancestry); - const childAgentName = (subagent.agentName || 'Agent').trim() || 'Agent'; - const toolName = toToolName(childAgentName, subagent.nodeId); - registry.toolRegistry.set(toolName, { - nodeId: subagent.nodeId, - agentName: childAgentName, - parentNodeId - }); - - tools.push( - childAgent.asTool({ - toolName, - toolDescription: buildSubagentToolDescription(childAgentName, subagent), - runOptions: { maxTurns: MAX_AGENT_TURNS } - }) - ); - } - - return tools; -} - -function toTextOutput(finalOutput: unknown): string { - if (typeof finalOutput === 'string') { - return finalOutput.trim(); - } - if (finalOutput === undefined || finalOutput === null) { - return 'Model returned no text output.'; - } - return JSON.stringify(finalOutput); -} - -function emitRuntimeEvent( - options: AgentRespondOptions | undefined, - event: AgentRuntimeEvent -): void { - options?.onRuntimeEvent?.(event); -} - -export class OpenAIAgentsLLMService implements WorkflowLLM { - async respond( - invocation: AgentInvocation, - options?: AgentRespondOptions - ): Promise { - const sdk = await loadAgentsSdk(); - const rootNodeId = options?.parentNodeId || '__root__'; - - const registry: AgentBuildRegistry = { - toolRegistry: new Map(), - agentRegistry: new WeakMap(), - agentsByNodeId: new Map() - }; - - const agent = buildSdkAgent(invocation, sdk, rootNodeId, registry); - const runner = new sdk.Runner(); - - const pendingChildCallsByNodeId = new Map(); - const contextStateByContext = new WeakMap(); - const activeSubagentCalls = new Map(); - const activeSubagentCallIdsByNodeId = new Map(); - const generatedCallIdsByToolName = new Map(); - let syntheticCallCounter = 0; - - const getSyntheticCallId = (toolName: string): string => { - syntheticCallCounter += 1; - return `${toolName}_${syntheticCallCounter}`; - }; - - const getResolvedCallIdForToolEnd = ( - toolName: string, - subagentNodeId: string, - details: ToolCallDetails - ): string => { - const explicitCallId = getToolCallId(details); - if (explicitCallId) { - return explicitCallId; - } - - const generatedCallIds = generatedCallIdsByToolName.get(toolName); - if (generatedCallIds && generatedCallIds.length > 0) { - const nextGeneratedCallId = generatedCallIds.shift(); - if (generatedCallIds.length === 0) { - generatedCallIdsByToolName.delete(toolName); - } - if (nextGeneratedCallId) { - return nextGeneratedCallId; - } - } - - const activeCallIdsForNode = activeSubagentCallIdsByNodeId.get(subagentNodeId); - if (activeCallIdsForNode && activeCallIdsForNode.length > 0) { - return activeCallIdsForNode[activeCallIdsForNode.length - 1]; - } - - return getSyntheticCallId(toolName); - }; - - const handleAgentStart = (nodeId: string, context: unknown): void => { - if (!isObject(context)) return; - - const pendingQueue = pendingChildCallsByNodeId.get(nodeId); - const pendingCall = pendingQueue?.shift(); - if (pendingQueue && pendingQueue.length === 0) { - pendingChildCallsByNodeId.delete(nodeId); - } - - contextStateByContext.set(context, { - nodeId, - depth: pendingCall?.depth ?? 0, - activeCallId: pendingCall?.callId - }); - }; - - const handleAgentEnd = (context: unknown): void => { - if (!isObject(context)) return; - contextStateByContext.delete(context); - }; - - const handleAgentToolStart = ( - sourceNodeId: string, - context: unknown, - tool: AgentsSdkTool, - details: ToolCallDetails - ): void => { - const toolName = getToolName(tool); - if (!toolName) return; - - const subagentMeta = registry.toolRegistry.get(toolName); - if (!subagentMeta) return; - - const contextState = isObject(context) ? contextStateByContext.get(context) : undefined; - const explicitCallId = getToolCallId(details); - const callId = explicitCallId ?? getSyntheticCallId(toolName); - if (!explicitCallId) { - const generatedCallIds = generatedCallIdsByToolName.get(toolName) ?? []; - generatedCallIds.push(callId); - generatedCallIdsByToolName.set(toolName, generatedCallIds); - } - let parentCallId = contextState?.activeCallId; - let parentDepth = contextState?.depth; - - if (!parentCallId) { - const activeParentCalls = activeSubagentCallIdsByNodeId.get(sourceNodeId); - const fallbackParentCallId = activeParentCalls?.[activeParentCalls.length - 1]; - if (fallbackParentCallId) { - parentCallId = fallbackParentCallId; - parentDepth = activeSubagentCalls.get(fallbackParentCallId)?.depth; - } - } - - const depth = (parentDepth ?? 0) + 1; - const event: AgentRuntimeEvent = { - type: 'subagent_call_start', - parentNodeId: rootNodeId, - subagentNodeId: subagentMeta.nodeId, - subagentName: subagentMeta.agentName, - callId, - parentCallId, - depth - }; - - activeSubagentCalls.set(callId, event); - const activeCallIdsForNode = activeSubagentCallIdsByNodeId.get(subagentMeta.nodeId) ?? []; - activeCallIdsForNode.push(callId); - activeSubagentCallIdsByNodeId.set(subagentMeta.nodeId, activeCallIdsForNode); - emitRuntimeEvent(options, event); - - const pendingQueue = pendingChildCallsByNodeId.get(subagentMeta.nodeId) ?? []; - pendingQueue.push({ callId, depth }); - pendingChildCallsByNodeId.set(subagentMeta.nodeId, pendingQueue); - }; - - const handleAgentToolEnd = (tool: AgentsSdkTool, details: ToolCallDetails): void => { - const toolName = getToolName(tool); - if (!toolName) return; - - const subagentMeta = registry.toolRegistry.get(toolName); - if (!subagentMeta) return; - - const callId = getResolvedCallIdForToolEnd(toolName, subagentMeta.nodeId, details); - - const startEvent = activeSubagentCalls.get(callId); - const resolvedSubagentNodeId = startEvent?.subagentNodeId ?? subagentMeta.nodeId; - const activeCallIdsForNode = activeSubagentCallIdsByNodeId.get(resolvedSubagentNodeId); - if (activeCallIdsForNode && activeCallIdsForNode.length > 0) { - const callIndex = activeCallIdsForNode.lastIndexOf(callId); - if (callIndex >= 0) { - activeCallIdsForNode.splice(callIndex, 1); - } - if (activeCallIdsForNode.length === 0) { - activeSubagentCallIdsByNodeId.delete(resolvedSubagentNodeId); - } - } - - const event: AgentRuntimeEvent = { - type: 'subagent_call_end', - parentNodeId: rootNodeId, - subagentNodeId: resolvedSubagentNodeId, - subagentName: startEvent?.subagentName ?? subagentMeta.agentName, - callId, - parentCallId: startEvent?.parentCallId, - depth: startEvent?.depth ?? 1 - }; - - emitRuntimeEvent(options, event); - activeSubagentCalls.delete(callId); - }; - - registry.agentsByNodeId.forEach((registeredAgent, registeredNodeId) => { - registeredAgent.on('agent_start', (context) => { - handleAgentStart(registeredNodeId, context); - }); - registeredAgent.on('agent_end', (context) => { - handleAgentEnd(context); - }); - registeredAgent.on('agent_tool_start', (context, tool, details) => { - handleAgentToolStart(registeredNodeId, context, tool, details); - }); - registeredAgent.on('agent_tool_end', (_context, tool, _result, details) => { - handleAgentToolEnd(tool, details); - }); - }); - - try { - const result = await runner.run(agent, invocation.userContent, { - maxTurns: MAX_AGENT_TURNS - }); - return toTextOutput(result.finalOutput); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - activeSubagentCalls.forEach((activeCall) => { - emitRuntimeEvent(options, { - ...activeCall, - type: 'subagent_call_error', - message - }); - }); - activeSubagentCalls.clear(); - activeSubagentCallIdsByNodeId.clear(); - throw error instanceof Error ? error : new Error(message); - } - } -} diff --git a/apps/server/src/services/persistence.ts b/apps/server/src/services/persistence.ts index d0cf904..195cc33 100644 --- a/apps/server/src/services/persistence.ts +++ b/apps/server/src/services/persistence.ts @@ -1,9 +1,67 @@ import fs from 'node:fs/promises'; import path from 'node:path'; -import type { WorkflowRunRecord } from '@agentic/types'; +import type { WorkflowRunRecord } from '@agentflow/types'; + +/** Run ids become file names, so only a conservative character set is accepted. */ +export const RUN_ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/; + +export function isValidRunId(runId: unknown): runId is string { + return typeof runId === 'string' && RUN_ID_PATTERN.test(runId); +} + +function runFilePath(runsDir: string, runId: string): string { + if (!isValidRunId(runId)) { + throw new Error(`Invalid run id "${runId}"`); + } + return path.join(runsDir, `run_${runId}.json`); +} export async function saveRunRecord(runsDir: string, record: WorkflowRunRecord): Promise { await fs.mkdir(runsDir, { recursive: true }); - const filePath = path.join(runsDir, `run_${record.runId}.json`); - await fs.writeFile(filePath, JSON.stringify(record, null, 2), 'utf-8'); + const filePath = runFilePath(runsDir, record.runId); + // Write to a temporary file first so a crash never leaves a truncated record. + const tempPath = `${filePath}.${process.pid}.tmp`; + await fs.writeFile(tempPath, JSON.stringify(record, null, 2), 'utf-8'); + await fs.rename(tempPath, filePath); +} + +export async function readRunRecord(runsDir: string, runId: string): Promise { + try { + const raw = await fs.readFile(runFilePath(runsDir, runId), 'utf-8'); + return JSON.parse(raw) as WorkflowRunRecord; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null; + throw error; + } +} + +export interface StoredRunFile { + record: WorkflowRunRecord; + modifiedAtMs: number; +} + +/** Reads every readable run record; unreadable files are reported and skipped. */ +export async function listRunRecords( + runsDir: string, + onSkip: (file: string, error: unknown) => void = () => {} +): Promise { + let files: string[]; + try { + files = (await fs.readdir(runsDir)).filter((f) => f.startsWith('run_') && f.endsWith('.json')); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; + throw error; + } + + const results: StoredRunFile[] = []; + for (const file of files) { + const filePath = path.join(runsDir, file); + try { + const [raw, stats] = await Promise.all([fs.readFile(filePath, 'utf-8'), fs.stat(filePath)]); + results.push({ record: JSON.parse(raw) as WorkflowRunRecord, modifiedAtMs: stats.mtimeMs }); + } catch (error) { + onSkip(file, error); + } + } + return results; } diff --git a/apps/server/src/services/restore.ts b/apps/server/src/services/restore.ts new file mode 100644 index 0000000..73ec5d6 --- /dev/null +++ b/apps/server/src/services/restore.ts @@ -0,0 +1,67 @@ +import type { WorkflowLLM } from '@agentflow/workflow-engine'; +import { WorkflowEngine } from '@agentflow/workflow-engine'; +import { logger } from '../logger.js'; +import type { RunStore } from '../store/run-store.js'; +import { isValidRunId, listRunRecords } from './persistence.js'; + +export interface RestoreOptions { + runsDir: string; + store: RunStore; + llm?: WorkflowLLM; + maxSteps?: number; + defaultModel?: string; + /** Paused runs whose record is older than this stay on disk but are not restored. */ + pausedRunTtlMs: number; + now?: () => number; +} + +/** + * Re-hydrates persisted paused runs into memory so they can be resumed after a + * server restart. Returns the number of restored runs. + */ +export async function restorePausedRuns(options: RestoreOptions): Promise { + const now = options.now ?? Date.now; + let stored; + try { + stored = await listRunRecords(options.runsDir, (file, error) => { + logger.warn('Skipped unreadable run file %s: %s', file, String(error)); + }); + } catch (error) { + logger.warn('Failed to scan runs directory %s: %s', options.runsDir, String(error)); + return 0; + } + + let restored = 0; + for (const { record, modifiedAtMs } of stored) { + const isResumable = + isValidRunId(record.runId) && + record.status === 'paused' && + record.waitingForInput === true && + record.state !== undefined && + record.currentNodeId != null; + if (!isResumable) continue; + + if (now() - modifiedAtMs > options.pausedRunTtlMs) { + logger.info('Paused run %s expired and was not restored', record.runId); + continue; + } + + const engine = new WorkflowEngine(record.workflow, { + runId: record.runId, + llm: options.llm, + maxSteps: options.maxSteps, + defaultModel: options.defaultModel, + initialState: { + state: record.state ?? {}, + currentNodeId: record.currentNodeId ?? null, + status: 'paused', + waitingForInput: true, + logs: record.logs + } + }); + options.store.add(engine); + restored += 1; + logger.info('Restored paused run %s from disk', record.runId); + } + return restored; +} diff --git a/apps/server/src/store/active-workflows.ts b/apps/server/src/store/active-workflows.ts deleted file mode 100644 index c03638f..0000000 --- a/apps/server/src/store/active-workflows.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type WorkflowEngine from '@agentic/workflow-engine'; - -const workflows = new Map(); - -export function addWorkflow(engine: WorkflowEngine): void { - workflows.set(engine.getRunId(), engine); -} - -export function getWorkflow(runId: string): WorkflowEngine | undefined { - return workflows.get(runId); -} - -export function removeWorkflow(runId: string): void { - workflows.delete(runId); -} - diff --git a/apps/server/src/store/run-store.ts b/apps/server/src/store/run-store.ts new file mode 100644 index 0000000..7897699 --- /dev/null +++ b/apps/server/src/store/run-store.ts @@ -0,0 +1,41 @@ +import type { WorkflowEngine } from '@agentflow/workflow-engine'; + +/** In-memory registry of runs that are executing or paused. */ +export class RunStore { + private readonly engines = new Map(); + + /** Runs with an in-flight `run()` or `resume()` call. */ + private readonly busy = new Set(); + + add(engine: WorkflowEngine): void { + this.engines.set(engine.getRunId(), engine); + } + + get(runId: string): WorkflowEngine | undefined { + return this.engines.get(runId); + } + + remove(runId: string): void { + this.engines.delete(runId); + this.busy.delete(runId); + } + + /** Returns false if another request is already executing this run. */ + tryLock(runId: string): boolean { + if (this.busy.has(runId)) return false; + this.busy.add(runId); + return true; + } + + unlock(runId: string): void { + this.busy.delete(runId); + } + + isBusy(runId: string): boolean { + return this.busy.has(runId); + } + + get size(): number { + return this.engines.size; + } +} diff --git a/apps/server/tsconfig.json b/apps/server/tsconfig.json index faccc32..1105280 100644 --- a/apps/server/tsconfig.json +++ b/apps/server/tsconfig.json @@ -7,12 +7,10 @@ "declaration": true, "declarationMap": true }, - "include": [ - "src" - ], + "include": ["src"], + "exclude": ["src/**/*.test.ts"], "references": [ { "path": "../../packages/types" }, { "path": "../../packages/workflow-engine" } ] } - diff --git a/apps/web/docs/run-readiness.md b/apps/web/docs/run-readiness.md index 2846101..5b75404 100644 --- a/apps/web/docs/run-readiness.md +++ b/apps/web/docs/run-readiness.md @@ -4,9 +4,9 @@ This document defines exactly when the **Run Workflow** button is enabled in the Code source of truth: -- `apps/web/src/app/workflow-editor.ts` -- `getRunDisableReason()` -- `updateRunButton()` +- `apps/web/src/app/graph/validation.ts`: `getRunDisableReason()` (pure; covered rule by rule in `validation.test.ts`) +- `apps/web/src/app/workflow-editor.ts`: `updateRunButton()` +- `apps/web/src/app/run/run-controller.ts`: run, pause, cancel and recovery states Related docs: @@ -20,7 +20,13 @@ Run button is disabled when editor state is not `idle`: - `running`: label is `Running...` - `paused`: label is `Paused` -Cancel button is only shown while state is `running`. +The **Clear Canvas** button is disabled in the same two states. + +The Cancel button is shown while state is `running` or `paused`. It calls `POST /api/cancel`, which stops the run on the server; closing the page or the stream does not stop a run. A paused run can therefore be abandoned without approving or rejecting. While the cancel request is in flight the button is disabled; if the request fails, the run stays as it was and Cancel can be pressed again. + +Undo and redo are unavailable while state is not `idle`. + +The reason a button is disabled is shown on hover and is also exposed to assistive technology through `aria-describedby`. ## Graph Validation Rules (Idle State) @@ -39,11 +45,11 @@ Run button is disabled when any condition below is true: - `Start` node has no outgoing execution connection. - Nothing is reachable after `Start`. - A reachable `Condition` node has neither condition branch nor fallback (`false`) branch. -- A reachable `Approval` node has neither `approve` nor `reject` outgoing branch. +- A reachable `Approval` node (or a legacy `input` node, its name before the upgrade) has neither `approve` nor `reject` outgoing branch. ## Explicitly Allowed (Does Not Block Run) -- Circular regular execution connections (non-subagent loops). +- Circular regular execution connections (non-subagent loops). The server stops a run that exceeds its step limit and reports it as an error in the Run Console. - Unreachable/disconnected nodes outside `Start`-reachable path. - `Condition` node with only one connected branch. - `Approval` node with only one connected branch. @@ -53,10 +59,14 @@ Run button is disabled when any condition below is true: Even when UI preflight passes, backend can still reject execution: -- Workflows containing `agent` nodes require `OPENAI_API_KEY`. +- Every `agent` node must use a model listed in `.config/config.json` (`400` otherwise). +- The provider of each model used must have its API key set, for example `OPENAI_API_KEY` or `ANTHROPIC_API_KEY` (`503` otherwise). - Server can return runtime validation/execution errors. +- A run that loops past the server's step limit fails with an error. Run and resume are executed through streaming endpoints: - `POST /api/run-stream` - `POST /api/resume-stream` + +If a resume request fails, the editor asks the server for the run's current state. When the run is still waiting, the approval card is shown again so the decision can be retried. diff --git a/apps/web/index.html b/apps/web/index.html index eafe352..0cb868f 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -2,7 +2,6 @@ - AgentFlow @@ -26,18 +25,19 @@
- + +

Nodes

-
-
- Agent +
+
+ Agent
-
- Condition +
+ Condition
-
- User Approval +
+ User Approval
@@ -54,7 +54,7 @@

Nodes

- +
@@ -65,7 +65,7 @@

Nodes

Run Console

-
+
System ready. Build your flow, craft a prompt, then run.
@@ -79,12 +79,13 @@

Run Console

>
- + + diff --git a/apps/web/package.json b/apps/web/package.json index e4ca02c..3dceca4 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,5 +1,5 @@ { - "name": "@agentic/web", + "name": "@agentflow/web", "version": "1.0.0", "private": true, "type": "module", @@ -9,15 +9,17 @@ "build": "tsc -p tsconfig.json --noEmit && vite build", "preview": "vite preview", "typecheck": "tsc -p tsconfig.json --noEmit", - "test": "vitest" + "test": "vitest run", + "test:watch": "vitest" }, "dependencies": { - "@agentic/types": "file:../../packages/types" + "@agentflow/types": "file:../../packages/types" }, "devDependencies": { - "@types/node": "^22.8.4", - "typescript": "^5.6.3", - "vite": "^5.4.10", - "vitest": "^2.1.4" + "@types/node": "^26.6.6", + "jsdom": "^31.0.1", + "typescript": "^6.0.3", + "vite": "^8.3.8", + "vitest": "^5.1.1" } } diff --git a/apps/web/src/app/canvas/connections.ts b/apps/web/src/app/canvas/connections.ts new file mode 100644 index 0000000..cd0d728 --- /dev/null +++ b/apps/web/src/app/canvas/connections.ts @@ -0,0 +1,408 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { CONNECTION_DRAG_THRESHOLD_PX, INPUT_HANDLE, SUBAGENT_HANDLE, SUBAGENT_TARGET_HANDLE } from '../constants'; +import type { EditorHost } from '../editor-host'; +import { getIfConditionIndexFromHandle } from '../graph/if-conditions'; +import { + canNodeBecomeSubagentTarget, + getConnectionValidationError, + getSubagentTargetIds +} from '../graph/validation'; +import { getNodeAccessibleName } from '../nodes/node-view'; +import { isTargetPortHandle } from '../nodes/ports'; +import type { ConnectionStart } from '../types'; +import { + getConnectionEndPoint, + getConnectionStartPoint, + getPathD, + shouldAggregateCollapsedIfPorts +} from './geometry'; + +const SVG_NS = 'http://www.w3.org/2000/svg'; + +type ReconnectState = { + connection: WorkflowConnection; + index: number; +}; + +type LinePress = ReconnectState & { + clientX: number; + clientY: number; +}; + +export function isSameConnection(a: WorkflowConnection | null, b: WorkflowConnection | null): boolean { + if (!a || !b) return false; + return a.source === b.source && + a.target === b.target && + a.sourceHandle === b.sourceHandle && + a.targetHandle === b.targetHandle; +} + +export function getConnectionLineClass( + sourceHandle?: string, + options: { editable?: boolean; reconnecting?: boolean; selected?: boolean } = {} +): string { + const classes = ['connection-line']; + if (options.editable) { + classes.push('editable'); + } + if (sourceHandle === SUBAGENT_HANDLE) { + classes.push('connection-line-subagent'); + } + if (options.reconnecting) { + classes.push('reconnecting'); + } + if (options.selected) { + classes.push('selected'); + } + return classes.join(' '); +} + +/** + * Connection lines: rendering, creating by dragging from a port (or from the + * keyboard), reconnecting by dragging a line, selecting and deleting. + */ +export class ConnectionsController { + private tempConnection: SVGPathElement | null = null; + + private connectionStart: ConnectionStart | null = null; + + /** The connection being re-dragged; it is out of the list until dropped. */ + private reconnecting: ReconnectState | null = null; + + /** A press on a line that has not moved far enough to count as a drag yet. */ + private linePress: LinePress | null = null; + + constructor(private readonly host: EditorHost) {} + + /** True while a connection is being created or re-dragged. */ + isConnecting(): boolean { + return this.connectionStart !== null; + } + + // --- Creating connections --- + + onPortMouseDown(e: MouseEvent, nodeId: string, handle: string): void { + e.stopPropagation(); + e.preventDefault(); + if (!this.host.connectionsLayer) return; + this.host.setCanvasValidationMessage(null); + const started = this.startConnectionFrom(nodeId, handle, this.host.viewport.screenToWorld(e.clientX, e.clientY)); + if (!started || !this.connectionStart) return; + + this.tempConnection = document.createElementNS(SVG_NS, 'path'); + this.tempConnection.setAttribute('class', getConnectionLineClass(handle)); + this.tempConnection.setAttribute('d', `M ${this.connectionStart.x} ${this.connectionStart.y} L ${this.connectionStart.x} ${this.connectionStart.y}`); + this.host.connectionsLayer.appendChild(this.tempConnection); + } + + onPortMouseUp(e: MouseEvent, nodeId: string, handle: string): void { + e.stopPropagation(); + this.completeConnectionAt(nodeId, handle); + } + + /** Enter/Space on a port: start a connection from a source port, or finish one on a target port. */ + onPortKeyActivate(nodeId: string, handle: string): void { + if (isTargetPortHandle(handle)) { + if (!this.connectionStart) { + this.host.setCanvasValidationMessage('Start from an output connector, then choose this input.'); + return; + } + this.completeConnectionAt(nodeId, handle); + return; + } + + this.cancelPendingConnection(); + if (this.startConnectionFrom(nodeId, handle, null)) { + this.host.setCanvasValidationMessage( + 'Connection started. Focus a target input connector and press Enter, or press Escape to cancel.' + ); + } + } + + private startConnectionFrom(nodeId: string, handle: string, fallbackPoint: { x: number; y: number } | null): boolean { + const sourceNode = this.host.store.nodes.find((candidate) => candidate.id === nodeId); + if (sourceNode && shouldAggregateCollapsedIfPorts(sourceNode) && getIfConditionIndexFromHandle(handle) !== null) { + return false; + } + const startPoint = sourceNode + ? getConnectionStartPoint(sourceNode, handle) + : fallbackPoint ?? { x: 0, y: 0 }; + this.connectionStart = { nodeId, handle, x: startPoint.x, y: startPoint.y }; + return true; + } + + private completeConnectionAt(nodeId: string, handle: string): void { + if (!this.connectionStart) return; + + let connected = false; + if (this.connectionStart.nodeId === nodeId) { + // Dropped on the node it started from: not a connection. + } else if (this.connectionStart.handle === SUBAGENT_HANDLE && handle !== SUBAGENT_TARGET_HANDLE) { + this.host.setCanvasValidationMessage('Subagent links must connect to the top green subagent connector.'); + } else if (this.connectionStart.handle !== SUBAGENT_HANDLE && handle === SUBAGENT_TARGET_HANDLE) { + this.host.setCanvasValidationMessage('Regular workflow links must connect to the side input connector.'); + } else { + connected = this.applyPendingConnection({ + source: this.connectionStart.nodeId, + target: nodeId, + sourceHandle: this.connectionStart.handle, + targetHandle: INPUT_HANDLE + }); + } + + if (!connected) { + this.restoreReconnectingConnection(); + } + this.reconnecting = null; + this.clearPendingConnectionDragState(); + this.host.renderConnections(); + this.host.updateRunButton(); + if (connected) { + this.host.commitHistory(); + } + } + + /** Adds the connection when it is new and valid. */ + applyPendingConnection(nextConnection: WorkflowConnection): boolean { + const { nodes, connections } = this.host.store; + const duplicateExists = connections.some((conn) => isSameConnection(conn, nextConnection)); + if (duplicateExists) { + return false; + } + + const validationError = getConnectionValidationError(nodes, connections, nextConnection); + if (validationError) { + this.host.setCanvasValidationMessage(validationError); + return false; + } + + this.host.setCanvasValidationMessage(null); + connections.push(nextConnection); + return true; + } + + private restoreReconnectingConnection(): void { + if (!this.reconnecting) return; + const { connections } = this.host.store; + const { connection, index } = this.reconnecting; + if (!connections.some((conn) => isSameConnection(conn, connection))) { + connections.splice(Math.min(index, connections.length), 0, connection); + } + this.reconnecting = null; + } + + private clearPendingConnectionDragState(): void { + if (this.tempConnection) { + this.tempConnection.remove(); + } + this.connectionStart = null; + this.tempConnection = null; + } + + /** Escape: abandon the connection being made and put a re-dragged line back. */ + cancelPendingConnection(): boolean { + if (!this.connectionStart && !this.linePress) return false; + this.linePress = null; + const wasReconnecting = this.reconnecting !== null; + this.restoreReconnectingConnection(); + this.clearPendingConnectionDragState(); + if (wasReconnecting) { + this.host.renderConnections(); + this.host.updateRunButton(); + } + return true; + } + + // --- Selecting and re-dragging existing lines --- + + private onConnectionLineMouseDown(e: MouseEvent, connection: WorkflowConnection, index: number): void { + e.stopPropagation(); + e.preventDefault(); + this.linePress = { connection, index, clientX: e.clientX, clientY: e.clientY }; + } + + private beginReconnect(press: LinePress, e: MouseEvent): void { + const { host } = this; + if (!host.connectionsLayer) return; + const { connection } = press; + const sourceNode = host.store.nodes.find((n) => n.id === connection.source); + if (!sourceNode) return; + const index = host.store.connections.findIndex((conn) => isSameConnection(conn, connection)); + if (index < 0) return; + + const startPoint = getConnectionStartPoint(sourceNode, connection.sourceHandle); + const world = host.viewport.screenToWorld(e.clientX, e.clientY); + + this.reconnecting = { connection, index }; + this.connectionStart = { + nodeId: connection.source, + handle: connection.sourceHandle ?? '', + x: startPoint.x, + y: startPoint.y + }; + + // Take the original connection out while it is being dragged. + host.store.connections.splice(index, 1); + if (isSameConnection(host.store.selectedConnection, connection)) { + host.store.selectedConnection = null; + } + host.renderConnections(); + host.updateRunButton(); + + // Create temp connection for dragging + this.tempConnection = document.createElementNS(SVG_NS, 'path'); + this.tempConnection.setAttribute( + 'class', + getConnectionLineClass(connection.sourceHandle, { reconnecting: true }) + ); + this.tempConnection.setAttribute( + 'd', + getPathD(startPoint.x, startPoint.y, world.x, world.y, connection.sourceHandle) + ); + host.connectionsLayer.appendChild(this.tempConnection); + } + + handleDocumentMouseMove(e: MouseEvent): void { + if (this.linePress) { + const travelled = Math.hypot(e.clientX - this.linePress.clientX, e.clientY - this.linePress.clientY); + if (travelled >= CONNECTION_DRAG_THRESHOLD_PX) { + const press = this.linePress; + this.linePress = null; + this.beginReconnect(press, e); + } + } + + if (this.tempConnection && this.connectionStart) { + const world = this.host.viewport.screenToWorld(e.clientX, e.clientY); + this.tempConnection.setAttribute( + 'd', + getPathD( + this.connectionStart.x, + this.connectionStart.y, + world.x, + world.y, + this.connectionStart.handle + ) + ); + } + } + + /** + * A mouse release that no target port handled. A plain click on a line + * selects it. A re-dragged line released on empty canvas is removed; released + * over a connector that cannot take it, it goes back where it was. + */ + handleDocumentMouseUp(e: MouseEvent): void { + if (this.linePress) { + const { connection } = this.linePress; + this.linePress = null; + this.host.selectConnection(connection); + return; + } + if (!this.tempConnection) return; + + if (this.reconnecting) { + const overPort = e.target instanceof Element && e.target.closest('.port') !== null; + if (overPort) { + this.restoreReconnectingConnection(); + } else { + this.reconnecting = null; + this.host.setCanvasValidationMessage('Connection removed. Press Ctrl/Cmd+Z to undo.'); + this.host.commitHistory(); + } + this.host.renderConnections(); + this.host.updateRunButton(); + } + this.clearPendingConnectionDragState(); + } + + /** Removes a connection (keyboard Delete on a selected line). */ + deleteConnection(connection: WorkflowConnection): void { + const { store } = this.host; + const index = store.connections.findIndex((conn) => isSameConnection(conn, connection)); + if (index < 0) return; + store.connections.splice(index, 1); + if (isSameConnection(store.selectedConnection, connection)) { + store.selectedConnection = null; + } + this.host.renderConnections(); + this.host.updateRunButton(); + this.host.commitHistory(); + } + + // --- Rendering --- + + render(): void { + const { host } = this; + if (!host.connectionsLayer) return; + const { nodes, connections } = host.store; + this.updateSubagentTargetNodeStyles(); + const connectionsLayer = host.connectionsLayer; + // Clear only permanent lines + const lines = Array.from(connectionsLayer.querySelectorAll('.connection-line')); + lines.forEach((line) => { + if (line !== this.tempConnection) line.remove(); + }); + + if (host.store.selectedConnection && !connections.some((conn) => isSameConnection(conn, host.store.selectedConnection))) { + host.store.selectedConnection = null; + } + + connections.forEach((conn, index) => { + const sourceNode = nodes.find((n) => n.id === conn.source); + const targetNode = nodes.find((n) => n.id === conn.target); + if (!sourceNode || !targetNode) return; + + const startPoint = getConnectionStartPoint(sourceNode, conn.sourceHandle); + const endPoint = getConnectionEndPoint(targetNode, conn.sourceHandle); + + const path = document.createElementNS(SVG_NS, 'path'); + path.setAttribute('class', getConnectionLineClass(conn.sourceHandle, { + editable: true, + selected: isSameConnection(host.store.selectedConnection, conn) + })); + path.setAttribute('d', getPathD(startPoint.x, startPoint.y, endPoint.x, endPoint.y, conn.sourceHandle)); + path.dataset.connectionIndex = String(index); + path.dataset.sourceNodeId = conn.source; + path.dataset.sourceHandle = conn.sourceHandle ?? ''; + path.dataset.targetNodeId = conn.target; + path.setAttribute('tabindex', '0'); + path.setAttribute('role', 'button'); + path.setAttribute( + 'aria-label', + `Connection from ${getNodeAccessibleName(sourceNode)} to ${getNodeAccessibleName(targetNode)}. Press Delete to remove.` + ); + path.addEventListener('mousedown', (e) => this.onConnectionLineMouseDown(e, conn, index)); + path.addEventListener('focus', () => host.selectConnection(conn)); + connectionsLayer.appendChild(path); + }); + host.scheduleSave(); + } + + /** Marks the selected line without re-rendering (keeps keyboard focus on it). */ + syncSelectionClasses(): void { + const { host } = this; + if (!host.connectionsLayer) return; + const { connections, selectedConnection } = host.store; + host.connectionsLayer.querySelectorAll('.connection-line.editable').forEach((line) => { + if (!(line instanceof SVGElement)) return; + const conn = connections[Number(line.dataset.connectionIndex)]; + line.classList.toggle('selected', Boolean(conn) && isSameConnection(selectedConnection, conn)); + }); + } + + private updateSubagentTargetNodeStyles(): void { + const { nodes, connections } = this.host.store; + const subagentTargets = getSubagentTargetIds(connections); + nodes.forEach((node) => { + const el = document.getElementById(node.id); + if (!el) return; + const isSubagentTarget = node.type === 'agent' && subagentTargets.has(node.id); + el.classList.toggle('subagent-target-node', isSubagentTarget); + const isSubagentCandidate = + node.type === 'agent' && + (isSubagentTarget || canNodeBecomeSubagentTarget(nodes, connections, node.id)); + el.classList.toggle('subagent-candidate-node', isSubagentCandidate); + }); + } +} diff --git a/apps/web/src/app/canvas/geometry.ts b/apps/web/src/app/canvas/geometry.ts new file mode 100644 index 0000000..c1bb6c4 --- /dev/null +++ b/apps/web/src/app/canvas/geometry.ts @@ -0,0 +1,194 @@ +import { + APPROVE_HANDLE, + COLLAPSED_NODE_FALLBACK_HEIGHT, + DEFAULT_HEADER_CENTER_Y, + DEFAULT_NODE_WIDTH, + DEFAULT_SECONDARY_CENTER_Y, + EXPANDED_NODE_FALLBACK_HEIGHT, + EXPANDED_NODE_WIDTH, + IF_FALLBACK_HANDLE, + IF_PORT_BASE_TOP, + IF_PORT_STEP, + PORT_RADIUS, + REJECT_HANDLE, + SUBAGENT_CURVE_MIN_OFFSET, + SUBAGENT_CURVE_RATIO, + SUBAGENT_HANDLE, + SUBAGENT_PORT_MIN_TOP +} from '../constants'; +import { getIfConditionIndexFromHandle, getIfConditions } from '../graph/if-conditions'; +import type { EditorNode, Point } from '../types'; + +// Port and connection positions are measured from the rendered node when it is +// mounted, with fixed fallbacks otherwise. + +export function getNodeWidth(node: EditorNode | null | undefined): number { + if (!node) return DEFAULT_NODE_WIDTH; + if (node.data && !node.data.collapsed) { + return EXPANDED_NODE_WIDTH; + } + // For collapsed nodes, read the actual rendered width. Since there is no + // CSS width transition on .node, the class toggle is instant and + // offsetWidth forces a synchronous reflow that returns the correct value. + const el = document.getElementById(node.id); + return el ? (el.offsetWidth || DEFAULT_NODE_WIDTH) : DEFAULT_NODE_WIDTH; +} + +export function getNodeHeaderCenterYOffset(node: EditorNode): number { + const nodeEl = document.getElementById(node.id); + const headerEl = nodeEl?.querySelector('.node-header'); + if (!(headerEl instanceof HTMLElement)) return DEFAULT_HEADER_CENTER_Y; + return Math.round(headerEl.offsetTop + (headerEl.offsetHeight / 2)); +} + +export function getNodeHeaderPortTop(node: EditorNode): number { + return getNodeHeaderCenterYOffset(node) - PORT_RADIUS; +} + +export function getNodeSecondaryCenterYOffset(node: EditorNode): number { + const nodeEl = document.getElementById(node.id); + const headerEl = nodeEl?.querySelector('.node-header'); + if (!(nodeEl instanceof HTMLElement) || !(headerEl instanceof HTMLElement)) { + return DEFAULT_SECONDARY_CENTER_Y; + } + const bodyTop = headerEl.offsetTop + headerEl.offsetHeight; + const bodyHeight = Math.max(nodeEl.offsetHeight - bodyTop, PORT_RADIUS * 2); + return Math.round(bodyTop + (bodyHeight / 2)); +} + +export function getNodeSecondaryPortTop(node: EditorNode): number { + return getNodeSecondaryCenterYOffset(node) - PORT_RADIUS; +} + +export function getSubagentPortTop(node: EditorNode): number { + const nodeEl = document.getElementById(node.id); + const height = nodeEl?.offsetHeight + ?? (node.data?.collapsed ? COLLAPSED_NODE_FALLBACK_HEIGHT : EXPANDED_NODE_FALLBACK_HEIGHT); + return Math.max(SUBAGENT_PORT_MIN_TOP, height - PORT_RADIUS); +} + +function getIfPortTop(index: number): number { + return IF_PORT_BASE_TOP + (index * IF_PORT_STEP); +} + +export function shouldAggregateCollapsedIfPorts(node: EditorNode): boolean { + return node.type === 'if' && Boolean(node.data?.collapsed) && getIfConditions(node).length > 1; +} + +export function getIfConditionPortTop(node: EditorNode, index: number): number { + if (node.data?.collapsed) { + return getNodeHeaderPortTop(node); + } + + const nodeEl = document.getElementById(node.id); + if (!nodeEl) { + return getIfPortTop(index); + } + + const conditionRows = Array.from(nodeEl.querySelectorAll('.condition-row')) as HTMLElement[]; + const row = conditionRows[index]; + if (!row) { + return getIfPortTop(index); + } + + return Math.round(row.offsetTop + (row.offsetHeight / 2) - PORT_RADIUS); +} + +export function getIfFallbackPortTop(node: EditorNode): number { + const conditions = getIfConditions(node); + if (node.data?.collapsed) { + return getNodeSecondaryPortTop(node); + } + + const nodeEl = document.getElementById(node.id); + if (!nodeEl) { + return getIfPortTop(conditions.length); + } + + const conditionRows = Array.from(nodeEl.querySelectorAll('.condition-row')) as HTMLElement[]; + const addConditionButton = nodeEl.querySelector('.add-condition-btn') as HTMLElement | null; + if (addConditionButton) { + return Math.round(addConditionButton.offsetTop + (addConditionButton.offsetHeight / 2) - PORT_RADIUS); + } + if (conditionRows.length === 0) { + return getIfPortTop(conditions.length); + } + + const lastRow = conditionRows[conditionRows.length - 1]; + const lastCenterTop = lastRow.offsetTop + (lastRow.offsetHeight / 2) - PORT_RADIUS; + const dynamicStep = conditionRows.length > 1 + ? conditionRows[conditionRows.length - 1].offsetTop - conditionRows[conditionRows.length - 2].offsetTop + : IF_PORT_STEP; + + return Math.round(lastCenterTop + dynamicStep); +} + +export function getOutputPortCenterYOffset(node: EditorNode, sourceHandle?: string): number { + if (sourceHandle === SUBAGENT_HANDLE) { + return getSubagentPortTop(node) + PORT_RADIUS; + } + + if (node.type === 'if') { + if (shouldAggregateCollapsedIfPorts(node)) { + if (sourceHandle === IF_FALLBACK_HANDLE) { + return getNodeSecondaryCenterYOffset(node); + } + const conditionIndex = getIfConditionIndexFromHandle(sourceHandle); + if (conditionIndex !== null) { + return getNodeHeaderCenterYOffset(node); + } + } + if (sourceHandle === IF_FALLBACK_HANDLE) { + return getIfFallbackPortTop(node) + PORT_RADIUS; + } + const conditionIndex = getIfConditionIndexFromHandle(sourceHandle); + if (conditionIndex !== null) { + return getIfConditionPortTop(node, conditionIndex) + PORT_RADIUS; + } + } + + if (sourceHandle === APPROVE_HANDLE) return getNodeHeaderCenterYOffset(node); + if (sourceHandle === REJECT_HANDLE) return getNodeSecondaryCenterYOffset(node); + return getNodeHeaderCenterYOffset(node); +} + +export function getConnectionStartPoint(sourceNode: EditorNode, sourceHandle?: string): Point { + if (sourceHandle === SUBAGENT_HANDLE) { + return { + x: sourceNode.x + (getNodeWidth(sourceNode) / 2), + y: sourceNode.y + getSubagentPortTop(sourceNode) + PORT_RADIUS + }; + } + return { + x: sourceNode.x + getNodeWidth(sourceNode), + y: sourceNode.y + getOutputPortCenterYOffset(sourceNode, sourceHandle) + }; +} + +export function getConnectionEndPoint(targetNode: EditorNode, sourceHandle?: string): Point { + if (sourceHandle === SUBAGENT_HANDLE) { + return { + x: targetNode.x + (getNodeWidth(targetNode) / 2), + y: targetNode.y + }; + } + return { + x: targetNode.x, + y: targetNode.y + getNodeHeaderCenterYOffset(targetNode) + }; +} + +export function getPathD( + startX: number, + startY: number, + endX: number, + endY: number, + sourceHandle?: string +): string { + if (sourceHandle === SUBAGENT_HANDLE) { + const verticalControlOffset = Math.max(SUBAGENT_CURVE_MIN_OFFSET, Math.abs(endY - startY) * SUBAGENT_CURVE_RATIO); + return `M ${startX} ${startY} C ${startX} ${startY + verticalControlOffset}, ${endX} ${endY - verticalControlOffset}, ${endX} ${endY}`; + } + const controlPointOffset = Math.abs(endX - startX) * 0.5; + return `M ${startX} ${startY} C ${startX + controlPointOffset} ${startY}, ${endX - controlPointOffset} ${endY}, ${endX} ${endY}`; +} diff --git a/apps/web/src/app/canvas/viewport.test.ts b/apps/web/src/app/canvas/viewport.test.ts new file mode 100644 index 0000000..26856fc --- /dev/null +++ b/apps/web/src/app/canvas/viewport.test.ts @@ -0,0 +1,28 @@ +import { describe, expect, it } from 'vitest'; + +import { MAX_ZOOM, MIN_ZOOM } from '../constants'; +import { clampScale, zoomViewportAt } from './viewport'; + +describe('viewport zoom', () => { + it('clamps the scale', () => { + expect(clampScale(10)).toBe(MAX_ZOOM); + expect(clampScale(0.01)).toBe(MIN_ZOOM); + expect(clampScale(1.25)).toBe(1.25); + }); + + it('keeps the world point under the anchor fixed', () => { + const before = { x: 40, y: -20, scale: 1 }; + const anchor = { x: 300, y: 200 }; + const after = zoomViewportAt(before, 1.5, anchor); + + const worldBefore = { x: (anchor.x - before.x) / before.scale, y: (anchor.y - before.y) / before.scale }; + const worldAfter = { x: (anchor.x - after.x) / after.scale, y: (anchor.y - after.y) / after.scale }; + expect(after.scale).toBe(1.5); + expect(worldAfter.x).toBeCloseTo(worldBefore.x); + expect(worldAfter.y).toBeCloseTo(worldBefore.y); + }); + + it('does not zoom past the limits', () => { + expect(zoomViewportAt({ x: 0, y: 0, scale: 1 }, 50, { x: 10, y: 10 }).scale).toBe(MAX_ZOOM); + }); +}); diff --git a/apps/web/src/app/canvas/viewport.ts b/apps/web/src/app/canvas/viewport.ts new file mode 100644 index 0000000..7fab0f0 --- /dev/null +++ b/apps/web/src/app/canvas/viewport.ts @@ -0,0 +1,87 @@ +import { MAX_ZOOM, MIN_ZOOM } from '../constants'; +import type { Point, Viewport } from '../types'; + +export function clampScale(scale: number): number { + return Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, scale)); +} + +/** + * Returns the viewport after changing the scale so that the world point under + * `anchor` (canvas-relative screen coordinates) stays under it. + */ +export function zoomViewportAt(viewport: Viewport, nextScale: number, anchor: Point): Viewport { + const scale = clampScale(nextScale); + const worldX = (anchor.x - viewport.x) / viewport.scale; + const worldY = (anchor.y - viewport.y) / viewport.scale; + return { + scale, + x: anchor.x - worldX * scale, + y: anchor.y - worldY * scale + }; +} + +/** Pan/zoom state of the canvas and the screen <-> world conversions. */ +export class ViewportController { + viewport: Viewport = { x: 0, y: 0, scale: 1 }; + + constructor( + private readonly canvas: HTMLElement | null, + private readonly canvasStage: HTMLElement | null, + private readonly zoomValue: HTMLElement | null + ) {} + + apply(): void { + if (this.canvasStage) { + this.canvasStage.style.transform = `translate(${this.viewport.x}px, ${this.viewport.y}px) scale(${this.viewport.scale})`; + } + if (this.zoomValue) { + this.zoomValue.textContent = `${Math.round(this.viewport.scale * 100)}%`; + } + } + + screenToWorld(clientX: number, clientY: number): Point { + if (!this.canvas) return { x: 0, y: 0 }; + const rect = this.canvas.getBoundingClientRect(); + return { + x: (clientX - rect.left - this.viewport.x) / this.viewport.scale, + y: (clientY - rect.top - this.viewport.y) / this.viewport.scale + }; + } + + /** World coordinates of the centre of the visible canvas, or null before layout. */ + getVisibleCenterWorld(): Point | null { + if (!this.canvas) return null; + const rect = this.canvas.getBoundingClientRect(); + if (!rect.width || !rect.height) return null; + return { + x: (rect.width / 2 - this.viewport.x) / this.viewport.scale, + y: (rect.height / 2 - this.viewport.y) / this.viewport.scale + }; + } + + /** Zoom in fixed steps (toolbar buttons), anchored at the canvas centre. */ + zoomByStep(stepPercent: number): void { + if (!this.canvas) return; + const snappedScale = Math.round(this.viewport.scale * 10) / 10; + const newScale = clampScale(snappedScale + stepPercent / 100); + if (newScale === this.viewport.scale) return; + const rect = this.canvas.getBoundingClientRect(); + this.viewport = zoomViewportAt(this.viewport, newScale, { x: rect.width / 2, y: rect.height / 2 }); + this.apply(); + } + + /** Zoom to an arbitrary scale keeping the point under the cursor fixed. */ + zoomAtClientPoint(nextScale: number, clientX: number, clientY: number): void { + if (!this.canvas) return; + const scale = clampScale(nextScale); + if (scale === this.viewport.scale) return; + const rect = this.canvas.getBoundingClientRect(); + this.viewport = zoomViewportAt(this.viewport, scale, { x: clientX - rect.left, y: clientY - rect.top }); + this.apply(); + } + + panTo(x: number, y: number): void { + this.viewport = { ...this.viewport, x, y }; + this.apply(); + } +} diff --git a/apps/web/src/app/chat/approval-card.ts b/apps/web/src/app/chat/approval-card.ts new file mode 100644 index 0000000..cc6ad70 --- /dev/null +++ b/apps/web/src/app/chat/approval-card.ts @@ -0,0 +1,113 @@ +import type { ApprovalDecision } from '../types'; + +export type ApprovalRequestCard = { + container: HTMLElement; + approveBtn: HTMLButtonElement; + rejectBtn: HTMLButtonElement; +}; + +/** Turns `container` into the "Approved"/"Rejected" result card. */ +export function renderApprovalResultCard(container: HTMLElement, decision: ApprovalDecision, note: string = ''): void { + container.className = 'chat-message approval-result'; + container.classList.add(decision === 'approve' ? 'approved' : 'rejected'); + + const trimmedNote = (note || '').trim(); + const icon = decision === 'approve' ? '✓' : '✗'; + const text = decision === 'approve' ? 'Approved' : 'Rejected'; + + container.innerHTML = ''; + + const labelEl = document.createElement('span'); + labelEl.className = 'chat-message-label'; + labelEl.textContent = 'Approval decision'; + container.appendChild(labelEl); + + const content = document.createElement('div'); + content.className = 'approval-result-content'; + + const status = document.createElement('div'); + status.className = 'approval-result-status'; + + const iconEl = document.createElement('span'); + iconEl.className = 'approval-result-icon'; + iconEl.setAttribute('aria-hidden', 'true'); + iconEl.textContent = icon; + status.appendChild(iconEl); + + const textEl = document.createElement('span'); + textEl.className = 'approval-result-text'; + textEl.textContent = text; + status.appendChild(textEl); + + content.appendChild(status); + + if (trimmedNote) { + const noteEl = document.createElement('div'); + noteEl.className = 'approval-result-note'; + noteEl.textContent = trimmedNote; + content.appendChild(noteEl); + } + + container.appendChild(content); +} + +/** Builds the card that asks the user to approve or reject. */ +export function buildApprovalRequestCard( + messageText: string, + onDecision: (decision: ApprovalDecision) => void +): ApprovalRequestCard { + const message = document.createElement('div'); + message.className = 'chat-message approval-request'; + + const labelEl = document.createElement('span'); + labelEl.className = 'chat-message-label'; + labelEl.textContent = 'Approval required'; + message.appendChild(labelEl); + + const body = document.createElement('div'); + body.className = 'approval-body'; + + const textEl = document.createElement('div'); + textEl.className = 'approval-text'; + textEl.textContent = messageText; + body.appendChild(textEl); + + const helperEl = document.createElement('div'); + helperEl.className = 'approval-helper'; + helperEl.textContent = 'Choose how this workflow should proceed.'; + body.appendChild(helperEl); + + const actions = document.createElement('div'); + actions.className = 'approval-actions'; + + const rejectBtn = document.createElement('button'); + rejectBtn.type = 'button'; + rejectBtn.className = 'button button-secondary reject-btn'; + rejectBtn.textContent = 'Reject'; + + const approveBtn = document.createElement('button'); + approveBtn.type = 'button'; + approveBtn.className = 'button button-primary approve-btn'; + approveBtn.textContent = 'Approve'; + + rejectBtn.addEventListener('click', () => onDecision('reject')); + approveBtn.addEventListener('click', () => onDecision('approve')); + + actions.appendChild(rejectBtn); + actions.appendChild(approveBtn); + body.appendChild(actions); + message.appendChild(body); + + return { container: message, approveBtn, rejectBtn }; +} + +/** Reads the decision and feedback back out of an `input_received` log line. */ +export function parseApprovalInputLog(content: string): { decision: ApprovalDecision; note: string } { + const decisionPrefixMatch = content.match(/(?:^|\n)\s*(?:Decision|Status)\s*:\s*(approve|approved|reject|rejected)\b/i); + const sentencePrefixMatch = content.match(/(?:^|\n)\s*User\s+(approved|rejected)\b/i); + const rawDecision = (decisionPrefixMatch?.[1] || sentencePrefixMatch?.[1] || 'approve').toLowerCase(); + const decision = rawDecision.startsWith('reject') ? 'reject' : 'approve'; + const feedbackMatch = content.match(/feedback:\s*(.*)$/i); + const note = feedbackMatch?.[1]?.trim() || ''; + return { decision, note }; +} diff --git a/apps/web/src/app/chat/chat-view.ts b/apps/web/src/app/chat/chat-view.ts new file mode 100644 index 0000000..448bfaa --- /dev/null +++ b/apps/web/src/app/chat/chat-view.ts @@ -0,0 +1,360 @@ +import type { WorkflowLogEntry } from '@agentflow/types'; +import { CHAT_PINNED_THRESHOLD_PX, GENERIC_AGENT_SPINNER_KEY } from '../constants'; +import { renderMarkdown } from '../markdown'; +import type { ApprovalDecision, EditorNode } from '../types'; +import type { ApprovalRequestCard } from './approval-card'; +import { buildApprovalRequestCard, parseApprovalInputLog, renderApprovalResultCard } from './approval-card'; +import { SubagentTree, isSubagentCallLogType, parseSubagentRuntimeLogPayload } from './subagent-tree'; + +export type ChatRole = 'system' | 'user' | 'agent' | 'error'; + +type PendingApproval = ApprovalRequestCard & { + nodeId: string | null; +}; + +export type ChatViewDeps = { + /** Looks a node up in the graph of the active run (or the canvas when idle). */ + getRunNodeById: (nodeId: string | null | undefined) => EditorNode | undefined; + getPrimaryAgentName: () => string; + onApprovalDecision: (decision: ApprovalDecision) => void; +}; + +function mapLogEntryToRole(entry: WorkflowLogEntry): ChatRole | null { + const type = entry.type || ''; + if (type.includes('llm_response')) return 'agent'; + if (type.includes('llm_error') || type === 'error') return 'error'; + if (type.includes('input_received')) return 'user'; + return null; +} + +function formatLogContent(entry: WorkflowLogEntry): string { + const content: unknown = entry.content; + return typeof content === 'string' ? content : ''; +} + +function getInitialPromptFromLogs(logs: WorkflowLogEntry[]): string | null { + const entry = logs.find((item) => item?.type === 'start_prompt' && typeof item.content === 'string' && item.content.trim()); + return entry?.content ?? null; +} + +/** The Run Console: messages, "agent is working" spinners and the approval card. */ +export class ChatView { + private readonly pendingAgentMessages = new Map(); + + private readonly pendingAgentMessageCounts = new Map(); + + private readonly subagentTree = new SubagentTree((key) => this.pendingAgentMessages.get(key)); + + private pendingApproval: PendingApproval | null = null; + + /** The "Approved"/"Rejected" card of a decision that is still being sent. */ + private submittedApprovalCard: HTMLElement | null = null; + + constructor( + private readonly chatMessages: HTMLElement | null, + private readonly deps: ChatViewDeps + ) {} + + // --- Scrolling --- + + private isPinnedToBottom(): boolean { + const el = this.chatMessages; + if (!el) return true; + return el.scrollHeight - el.scrollTop - el.clientHeight <= CHAT_PINNED_THRESHOLD_PX; + } + + /** Appends and follows the conversation, unless the user has scrolled up to read. */ + private append(element: HTMLElement): void { + if (!this.chatMessages) return; + const pinned = this.isPinnedToBottom(); + this.chatMessages.appendChild(element); + if (pinned) { + this.chatMessages.scrollTop = this.chatMessages.scrollHeight; + } + } + + // --- Messages --- + + reset(systemMessage?: string): void { + if (!this.chatMessages) return; + this.chatMessages.innerHTML = ''; + this.pendingAgentMessages.clear(); + this.pendingAgentMessageCounts.clear(); + this.subagentTree.clear(); + this.pendingApproval = null; + this.submittedApprovalCard = null; + if (systemMessage) { + const message = document.createElement('div'); + message.className = 'chat-message system'; + message.textContent = systemMessage; + this.chatMessages.appendChild(message); + } + } + + startSession(promptText: string): void { + this.reset(); + if (promptText.trim()) { + this.appendChatMessage(promptText, 'user'); + } + } + + appendStatusMessage(text: string, type: string = ''): void { + const message = document.createElement('div'); + message.className = `chat-message status ${type}`; + message.textContent = text; + this.append(message); + } + + appendChatMessage(text: string, role: ChatRole = 'system', agentName?: string): void { + if (!this.chatMessages) return; + const message = document.createElement('div'); + message.className = `chat-message ${role}`; + const normalizedText = + role === 'error' && !String(text).trim().toLowerCase().startsWith('error:') + ? `Error: ${text}` + : text; + if (role === 'agent') { + const label = document.createElement('span'); + label.className = 'chat-message-label'; + label.textContent = agentName || this.deps.getPrimaryAgentName(); + message.appendChild(label); + } + const body = document.createElement('div'); + if (role === 'agent') { + body.className = 'chat-message-body markdown'; + body.innerHTML = renderMarkdown(normalizedText); + } else { + body.textContent = normalizedText; + } + message.appendChild(body); + this.append(message); + } + + private getAgentNameForNode(nodeId: string): string { + const node = this.deps.getRunNodeById(nodeId); + return (node?.data?.agentName || '').trim() || 'Agent'; + } + + // --- Spinners --- + + hasSpinners(): boolean { + return this.pendingAgentMessages.size > 0; + } + + showAgentSpinner(name?: string, nodeId?: string): void { + if (!this.chatMessages) return; + const spinnerKey = nodeId || GENERIC_AGENT_SPINNER_KEY; + const currentCount = this.pendingAgentMessageCounts.get(spinnerKey) ?? 0; + this.pendingAgentMessageCounts.set(spinnerKey, currentCount + 1); + if (currentCount > 0 && this.pendingAgentMessages.has(spinnerKey)) return; + const resolvedName = name || this.deps.getPrimaryAgentName(); + const spinner = document.createElement('div'); + spinner.className = 'chat-message agent spinner'; + const label = document.createElement('span'); + label.className = 'chat-message-label'; + label.textContent = resolvedName; + spinner.appendChild(label); + const body = document.createElement('div'); + body.className = 'chat-spinner-row'; + const text = document.createElement('span'); + text.className = 'chat-spinner-text'; + text.textContent = `${resolvedName} is working`; + const dots = document.createElement('span'); + dots.className = 'chat-spinner'; + dots.setAttribute('aria-hidden', 'true'); + dots.innerHTML = ''; + body.appendChild(text); + body.appendChild(dots); + spinner.appendChild(body); + + this.append(spinner); + this.pendingAgentMessages.set(spinnerKey, spinner); + } + + hideAgentSpinner(nodeId?: string): void { + if (nodeId) { + const currentCount = this.pendingAgentMessageCounts.get(nodeId) ?? 0; + if (currentCount > 1) { + this.pendingAgentMessageCounts.set(nodeId, currentCount - 1); + return; + } + this.pendingAgentMessageCounts.delete(nodeId); + const spinner = this.pendingAgentMessages.get(nodeId); + if (!spinner) return; + spinner.remove(); + this.pendingAgentMessages.delete(nodeId); + this.subagentTree.clear(nodeId); + return; + } + + this.pendingAgentMessages.forEach((spinner) => spinner.remove()); + this.pendingAgentMessages.clear(); + this.pendingAgentMessageCounts.clear(); + this.subagentTree.clear(); + } + + // --- Approval card --- + + showApprovalMessage(nodeId: string | null): void { + if (!this.chatMessages) return; + this.clearApprovalMessage(); + const node = this.deps.getRunNodeById(nodeId); + const messageText = node?.data?.prompt || 'Approval required before continuing.'; + const card = buildApprovalRequestCard(messageText, (decision) => this.deps.onApprovalDecision(decision)); + this.append(card.container); + this.pendingApproval = { ...card, nodeId }; + } + + getPendingApprovalNodeId(): string | null { + return this.pendingApproval?.nodeId ?? null; + } + + clearApprovalMessage(): void { + if (this.pendingApproval?.container) { + this.pendingApproval.container.remove(); + } + this.pendingApproval = null; + } + + setApprovalButtonsDisabled(disabled: boolean): void { + if (!this.pendingApproval) return; + this.pendingApproval.approveBtn.disabled = disabled; + this.pendingApproval.rejectBtn.disabled = disabled; + } + + /** Shows the decision in place of the request while it is sent to the server. */ + replaceApprovalWithResult(decision: ApprovalDecision, note: string): void { + if (!this.pendingApproval?.container) return; + + const container = this.pendingApproval.container; + renderApprovalResultCard(container, decision, note); + this.submittedApprovalCard = container; + this.pendingApproval = null; + } + + /** The decision reached the server; its card is now a permanent part of the log. */ + confirmSubmittedApproval(): void { + this.submittedApprovalCard = null; + } + + /** The decision could not be sent: remove its card so the request can be shown again. */ + discardSubmittedApproval(): void { + this.submittedApprovalCard?.remove(); + this.submittedApprovalCard = null; + } + + // --- Log entries --- + + private isApprovalInputLog(entry: WorkflowLogEntry): boolean { + if (!entry || entry.type !== 'input_received') return false; + const node = this.deps.getRunNodeById(entry.nodeId); + // `input` is the pre-upgrade name of the approval node. + return node?.type === 'approval' || node?.type === 'input'; + } + + private handleSubagentLogEntry(entry: WorkflowLogEntry, options: { createSpinnerIfMissing?: boolean } = {}): void { + const payload = parseSubagentRuntimeLogPayload(entry); + if (!payload) return; + + const spinnerKey = + payload.parentNodeId || + (typeof entry?.nodeId === 'string' ? entry.nodeId : GENERIC_AGENT_SPINNER_KEY); + const createSpinnerIfMissing = options.createSpinnerIfMissing ?? true; + + if (!this.pendingAgentMessages.has(spinnerKey) && createSpinnerIfMissing) { + this.showAgentSpinner(this.getAgentNameForNode(spinnerKey), spinnerKey); + } + if (!this.pendingAgentMessages.has(spinnerKey)) { + return; + } + + this.subagentTree.handleEntry(spinnerKey, entry.type, payload); + } + + /** Applies one live log entry (from the stream, or newly seen while polling). */ + onLogEntry(entry: WorkflowLogEntry): void { + const type = entry.type || ''; + if (type === 'step_start') { + const node = this.deps.getRunNodeById(entry.nodeId); + if (node?.type === 'agent') { + this.hideAgentSpinner(GENERIC_AGENT_SPINNER_KEY); + this.showAgentSpinner(this.getAgentNameForNode(entry.nodeId), entry.nodeId); + } + } else if (isSubagentCallLogType(type)) { + this.handleSubagentLogEntry(entry); + } else if (type === 'llm_response') { + this.hideAgentSpinner(GENERIC_AGENT_SPINNER_KEY); + this.hideAgentSpinner(entry.nodeId); + this.appendChatMessage(entry.content || '', 'agent', this.getAgentNameForNode(entry.nodeId)); + } else if (type === 'llm_error' || type === 'error') { + this.hideAgentSpinner(GENERIC_AGENT_SPINNER_KEY); + const node = this.deps.getRunNodeById(entry.nodeId); + if (node?.type === 'agent') { + this.hideAgentSpinner(entry.nodeId); + } + this.appendChatMessage(entry.content || '', 'error'); + } + } + + /** Rebuilds the whole conversation from a run's logs (after a reload). */ + renderChatFromLogs(logs: WorkflowLogEntry[] = []): void { + if (!this.chatMessages) return; + this.reset(); + const initialPromptFromLogs = getInitialPromptFromLogs(logs); + if (initialPromptFromLogs) { + this.appendChatMessage(initialPromptFromLogs, 'user'); + } + const activeAgentNodeCounts = new Map(); + const subagentEntries: WorkflowLogEntry[] = []; + logs.forEach((entry) => { + const entryNodeId = typeof entry?.nodeId === 'string' ? entry.nodeId : null; + const entryNode = entryNodeId ? this.deps.getRunNodeById(entryNodeId) : undefined; + if (entry.type === 'step_start' && entryNode?.type === 'agent' && entryNodeId) { + const nextCount = (activeAgentNodeCounts.get(entryNodeId) ?? 0) + 1; + activeAgentNodeCounts.set(entryNodeId, nextCount); + } + if ( + (entry.type === 'llm_response' || entry.type === 'llm_error' || entry.type === 'error') && + entryNode?.type === 'agent' && + entryNodeId + ) { + const nextCount = (activeAgentNodeCounts.get(entryNodeId) ?? 0) - 1; + if (nextCount > 0) { + activeAgentNodeCounts.set(entryNodeId, nextCount); + } else { + activeAgentNodeCounts.delete(entryNodeId); + } + } + + if (isSubagentCallLogType(entry.type || '')) { + subagentEntries.push(entry); + return; + } + + if (this.isApprovalInputLog(entry)) { + const approvalText = formatLogContent(entry); + if (approvalText) { + const { decision, note } = parseApprovalInputLog(approvalText); + const message = document.createElement('div'); + renderApprovalResultCard(message, decision, note); + this.append(message); + } + return; + } + const role = mapLogEntryToRole(entry); + if (!role) return; + const text = formatLogContent(entry); + if (!text) return; + const agentName = role === 'agent' ? this.getAgentNameForNode(entry.nodeId) : undefined; + this.appendChatMessage(text, role, agentName); + }); + + activeAgentNodeCounts.forEach((activeCount, nodeId) => { + for (let i = 0; i < activeCount; i += 1) { + this.showAgentSpinner(this.getAgentNameForNode(nodeId), nodeId); + } + }); + + subagentEntries.forEach((entry) => this.handleSubagentLogEntry(entry, { createSpinnerIfMissing: false })); + } +} diff --git a/apps/web/src/app/chat/subagent-tree.ts b/apps/web/src/app/chat/subagent-tree.ts new file mode 100644 index 0000000..d5e1512 --- /dev/null +++ b/apps/web/src/app/chat/subagent-tree.ts @@ -0,0 +1,282 @@ +import type { WorkflowLogEntry } from '@agentflow/types'; +import type { SubagentCallStatus, SubagentRuntimeLogPayload } from '../types'; + +export function isSubagentCallLogType(type: string): boolean { + return ( + type === 'subagent_call_start' || + type === 'subagent_call_end' || + type === 'subagent_call_error' + ); +} + +export function parseSubagentRuntimeLogPayload(entry: WorkflowLogEntry): SubagentRuntimeLogPayload | null { + if (!isSubagentCallLogType(entry?.type || '')) { + return null; + } + if (typeof entry?.content !== 'string' || !entry.content.trim()) { + return null; + } + + try { + const parsed = JSON.parse(entry.content) as Partial; + if ( + typeof parsed.callId !== 'string' || + typeof parsed.subagentNodeId !== 'string' || + typeof parsed.subagentName !== 'string' || + typeof parsed.depth !== 'number' + ) { + return null; + } + return { + callId: parsed.callId, + subagentNodeId: parsed.subagentNodeId, + subagentName: parsed.subagentName, + depth: parsed.depth, + parentCallId: typeof parsed.parentCallId === 'string' ? parsed.parentCallId : undefined, + parentNodeId: typeof parsed.parentNodeId === 'string' ? parsed.parentNodeId : undefined, + message: typeof parsed.message === 'string' ? parsed.message : undefined + }; + } catch { + return null; + } +} + +/** + * The nested list of subagent calls shown inside an agent's "is working" + * spinner message. Spinner elements are owned by the chat view and looked up + * by key through `getSpinner`. + */ +export class SubagentTree { + private readonly callElements = new Map(); + + private readonly callSpinnerKeys = new Map(); + + private readonly spinnerCallIds = new Map>(); + + private readonly callStatuses = new Map(); + + constructor(private readonly getSpinner: (spinnerKey: string) => HTMLElement | undefined) {} + + /** Forgets the calls of one spinner, or of all spinners when no key is given. */ + clear(spinnerKey?: string): void { + if (spinnerKey) { + const callIds = this.spinnerCallIds.get(spinnerKey); + if (callIds) { + callIds.forEach((callId) => { + this.callElements.delete(callId); + this.callSpinnerKeys.delete(callId); + this.callStatuses.delete(callId); + }); + } + this.spinnerCallIds.delete(spinnerKey); + return; + } + + this.callElements.clear(); + this.callSpinnerKeys.clear(); + this.spinnerCallIds.clear(); + this.callStatuses.clear(); + } + + /** Applies one subagent log entry to the spinner identified by `spinnerKey`. */ + handleEntry(spinnerKey: string, type: string, payload: SubagentRuntimeLogPayload): void { + if (type === 'subagent_call_start') { + const item = this.ensureCallItem(spinnerKey, payload); + if (item) { + this.setCallItemStatus(payload.callId, 'running'); + } + this.updateSummary(spinnerKey); + return; + } + + const mappedStatus = type === 'subagent_call_error' ? 'failed' : 'completed'; + this.setCallItemStatus(payload.callId, mappedStatus, payload.message); + this.updateSummary(spinnerKey); + } + + private ensureList(spinner: HTMLElement): HTMLElement { + const existing = spinner.querySelector('.chat-subagent-list'); + if (existing instanceof HTMLElement) { + return existing; + } + const created = document.createElement('div'); + created.className = 'chat-subagent-list'; + spinner.appendChild(created); + return created; + } + + private ensureSummary(spinner: HTMLElement): HTMLElement { + const existing = spinner.querySelector('.chat-subagent-summary'); + if (existing instanceof HTMLElement) { + return existing; + } + + const list = this.ensureList(spinner); + const created = document.createElement('div'); + created.className = 'chat-subagent-summary'; + spinner.insertBefore(created, list); + return created; + } + + private updateToggleState(item: HTMLElement): void { + const toggle = item.querySelector('.chat-subagent-toggle'); + if (!(toggle instanceof HTMLButtonElement)) return; + + const hasChildren = item.classList.contains('has-children'); + if (!hasChildren) { + toggle.hidden = true; + toggle.disabled = true; + toggle.textContent = ''; + toggle.removeAttribute('aria-label'); + toggle.removeAttribute('aria-expanded'); + return; + } + + const isCollapsed = item.classList.contains('collapsed'); + toggle.hidden = false; + toggle.disabled = false; + toggle.textContent = isCollapsed ? '▸' : '▾'; + toggle.setAttribute('aria-label', isCollapsed ? 'Expand nested subagents' : 'Collapse nested subagents'); + toggle.setAttribute('aria-expanded', String(!isCollapsed)); + } + + private markItemHasChildren(callId: string): void { + const parentItem = this.callElements.get(callId); + if (!parentItem) return; + parentItem.classList.add('has-children'); + parentItem.classList.remove('collapsed'); + this.updateToggleState(parentItem); + } + + private updateSummary(spinnerKey: string): void { + const spinner = this.getSpinner(spinnerKey); + if (!spinner) return; + + const callIds = this.spinnerCallIds.get(spinnerKey); + if (!callIds || callIds.size === 0) { + const existing = spinner.querySelector('.chat-subagent-summary'); + if (existing instanceof HTMLElement) { + existing.remove(); + } + return; + } + + let running = 0; + let completed = 0; + let failed = 0; + + callIds.forEach((callId) => { + const status = this.callStatuses.get(callId); + if (status === 'running') running += 1; + else if (status === 'completed') completed += 1; + else if (status === 'failed') failed += 1; + }); + + const summary = this.ensureSummary(spinner); + const parts = [`${running} running`, `${completed} done`]; + if (failed > 0) { + parts.push(`${failed} failed`); + } + summary.textContent = `Subagents: ${parts.join(' · ')}`; + } + + private ensureCallItem(spinnerKey: string, payload: SubagentRuntimeLogPayload): HTMLElement | null { + const existing = this.callElements.get(payload.callId); + if (existing) { + return existing; + } + + const spinner = this.getSpinner(spinnerKey); + if (!spinner) { + return null; + } + + const item = document.createElement('div'); + item.className = 'chat-subagent-item running'; + item.dataset.callId = payload.callId; + item.dataset.depth = String(payload.depth); + + const row = document.createElement('div'); + row.className = 'chat-subagent-row'; + const main = document.createElement('div'); + main.className = 'chat-subagent-main'; + const toggle = document.createElement('button'); + toggle.type = 'button'; + toggle.className = 'chat-subagent-toggle'; + toggle.hidden = true; + toggle.disabled = true; + toggle.addEventListener('click', (event) => { + event.preventDefault(); + item.classList.toggle('collapsed'); + this.updateToggleState(item); + }); + const name = document.createElement('span'); + name.className = 'chat-subagent-name'; + name.textContent = payload.subagentName; + main.appendChild(toggle); + main.appendChild(name); + const status = document.createElement('span'); + status.className = 'chat-subagent-status'; + row.appendChild(main); + row.appendChild(status); + item.appendChild(row); + + const children = document.createElement('div'); + children.className = 'chat-subagent-children'; + item.appendChild(children); + + const parentContainer = payload.parentCallId + ? (() => { + this.markItemHasChildren(payload.parentCallId); + return this.callElements.get(payload.parentCallId)?.querySelector('.chat-subagent-children'); + })() + : null; + const hostContainer = parentContainer instanceof HTMLElement + ? parentContainer + : this.ensureList(spinner); + hostContainer.appendChild(item); + this.updateToggleState(item); + + this.callElements.set(payload.callId, item); + this.callSpinnerKeys.set(payload.callId, spinnerKey); + const callIdsForSpinner = this.spinnerCallIds.get(spinnerKey) ?? new Set(); + callIdsForSpinner.add(payload.callId); + this.spinnerCallIds.set(spinnerKey, callIdsForSpinner); + return item; + } + + private setCallItemStatus( + callId: string, + statusClass: SubagentCallStatus, + message?: string + ): void { + const item = this.callElements.get(callId); + if (!item) return; + this.callStatuses.set(callId, statusClass); + item.classList.remove('running', 'completed', 'failed'); + item.classList.add(statusClass); + const statusEl = item.querySelector('.chat-subagent-status'); + if (!(statusEl instanceof HTMLElement)) return; + statusEl.classList.remove('running-indicator', 'done-indicator'); + statusEl.replaceChildren(); + + if (statusClass === 'running') { + statusEl.classList.add('running-indicator'); + statusEl.setAttribute('aria-label', 'Running'); + const spinner = document.createElement('span'); + spinner.className = 'chat-spinner chat-spinner-inline'; + spinner.setAttribute('aria-hidden', 'true'); + spinner.innerHTML = ''; + statusEl.appendChild(spinner); + return; + } + if (statusClass === 'completed') { + statusEl.classList.add('done-indicator'); + statusEl.setAttribute('aria-label', 'Done'); + statusEl.textContent = '✓'; + return; + } + statusEl.removeAttribute('aria-label'); + statusEl.textContent = message && message.trim() ? message.trim() : 'Failed'; + } +} diff --git a/apps/web/src/app/constants.ts b/apps/web/src/app/constants.ts new file mode 100644 index 0000000..11f3076 --- /dev/null +++ b/apps/web/src/app/constants.ts @@ -0,0 +1,90 @@ +import type { IfCondition, ToolConfig } from './types'; + +export const EXPANDED_NODE_WIDTH = 420; +/** Fallback width when a node has not been mounted yet. */ +export const DEFAULT_NODE_WIDTH = 150; +export const COLLAPSED_NODE_FALLBACK_HEIGHT = 96; +export const EXPANDED_NODE_FALLBACK_HEIGHT = 220; +export const EXPANDED_AGENT_FALLBACK_HEIGHT = 240; + +export const TOOLS_CONFIG: ToolConfig[] = [ + { key: 'web_search', label: 'Web Search', iconClass: 'icon-globe' }, + { key: 'subagents', label: 'Subagents', iconClass: 'icon-engineering-manager' } +]; + +// Fallbacks for when `/api/config` cannot be loaded. The real model list +// comes from `.config/config.json` on the server. +export const DEFAULT_MODEL = 'gpt-6-luna'; +export const DEFAULT_REASONING_EFFORT = 'low'; +export const DEFAULT_MODEL_OPTIONS = ['gpt-6.2-sol', 'gpt-6.1-terra', 'gpt-6-luna']; +export const DEFAULT_MODEL_EFFORTS: Record = { + 'gpt-6.2-sol': ['low', 'medium', 'high', 'xhigh', 'max'], + 'gpt-6.1-terra': ['none', 'low', 'medium', 'high', 'xhigh', 'max'], + 'gpt-6-luna': ['none', 'low', 'medium', 'high', 'xhigh', 'max'] +}; +export const DEFAULT_MODEL_LABELS: Record = { + 'gpt-6.2-sol': 'GPT-6.2 Sol', + 'gpt-6.1-terra': 'GPT-6.1 Terra', + 'gpt-6-luna': 'GPT-6 Luna' +}; + +export const IF_CONDITION_HANDLE_PREFIX = 'condition-'; +export const IF_FALLBACK_HANDLE = 'false'; +/** Handle used by graphs saved before multi-condition nodes existed. */ +export const LEGACY_IF_TRUE_HANDLE = 'true'; +export const SUBAGENT_HANDLE = 'subagent'; +export const SUBAGENT_TARGET_HANDLE = 'subagent-target'; +export const INPUT_HANDLE = 'input'; +export const OUTPUT_HANDLE = 'output'; +export const APPROVE_HANDLE = 'approve'; +export const REJECT_HANDLE = 'reject'; + +export const IF_PORT_BASE_TOP = 45; +export const IF_PORT_STEP = 30; +export const SUBAGENT_PORT_MIN_TOP = 42; +export const DEFAULT_HEADER_CENTER_Y = 24; +export const DEFAULT_SECONDARY_CENTER_Y = 81; +export const PORT_RADIUS = 6; +export const AGGREGATE_PORT_RADIUS = 8; +export const SUBAGENT_CURVE_MIN_OFFSET = 40; +export const SUBAGENT_CURVE_RATIO = 0.35; + +export const PREVIOUS_OUTPUT_TEMPLATE = '{{PREVIOUS_OUTPUT}}'; +export const GENERIC_AGENT_SPINNER_KEY = '__generic_agent_spinner__'; + +export const IF_CONDITION_OPERATORS = [ + { value: 'equal', label: 'Equal' }, + { value: 'contains', label: 'Contains' } +]; +export const DEFAULT_IF_CONDITION: IfCondition = { operator: 'equal', value: '' }; +export const DEFAULT_APPROVAL_PROMPT = 'Review and approve this step.'; + +export const MIN_ZOOM = 0.5; +export const MAX_ZOOM = 2; +export const ZOOM_BUTTON_STEP_PERCENT = 10; +/** Scale change per wheel pixel when zooming with Ctrl/Cmd + wheel or a pinch. */ +export const WHEEL_ZOOM_SENSITIVITY = 0.0015; + +export const CANVAS_MESSAGE_TIMEOUT_MS = 4500; +export const SAVE_DEBOUNCE_MS = 500; +export const RUN_POLL_INTERVAL_MS = 2000; +export const HISTORY_LIMIT = 100; +/** Pointer travel (px) before a press on a connection becomes a reconnect drag. */ +export const CONNECTION_DRAG_THRESHOLD_PX = 4; +export const KEYBOARD_NODE_NUDGE_PX = 10; +/** Distance from the bottom (px) within which the chat keeps auto-scrolling. */ +export const CHAT_PINNED_THRESHOLD_PX = 48; + +export const START_NODE_FALLBACK_POSITION = { x: 370, y: 310 }; +export const START_NODE_APPROX_SIZE = { width: 120, height: 60 }; +export const DUPLICATE_NODE_SPACING = 24; +export const DUPLICATE_NODE_MIN_WORLD_Y = 16; +export const KEYBOARD_ADD_NODE_STAGGER_PX = 24; + +export const DEFAULT_RIGHT_PANEL_WIDTH = 320; +export const SPLIT_PANEL_MIN_LEFT = 40; +export const SPLIT_PANEL_MAX_LEFT = 80; +export const SPLIT_PANEL_MIN_RIGHT = 20; + +export const WORKFLOW_STORAGE_KEY = 'agentflow-workflow'; +export const RUN_ID_STORAGE_KEY = 'agentflow-run-id'; diff --git a/apps/web/src/app/ds-components.test.ts b/apps/web/src/app/ds-components.test.ts new file mode 100644 index 0000000..c778caa --- /dev/null +++ b/apps/web/src/app/ds-components.test.ts @@ -0,0 +1,136 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from 'vitest'; +import { dropdownSupportsGroups } from './ds-loader'; +import type { DropdownCtor, ModalCtor, SplitPanelCtor } from './ds-loader'; +import { flattenGroupedItems } from './model-catalog'; + +/** + * Contract tests against the real design-system submodule: they construct each + * component the way the editor does, so a submodule bump that changes an API + * the editor relies on fails here instead of in the browser. + */ +const component = async (relativePath: string): Promise => { + // Kept as two steps so Vite does not treat this as a bundled asset URL. + const testFileUrl: string = import.meta.url; + const moduleUrl = new URL(`../../../../design-system/components/${relativePath}`, testFileUrl).href; + return ((await import(/* @vite-ignore */ moduleUrl)) as { default: T }).default; +}; + +describe('design-system components used by the editor', () => { + it('dropdown: renders items, reports selection and removes its document listeners on destroy', async () => { + const Dropdown = await component('dropdown/dropdown.js'); + const added = vi.spyOn(document, 'addEventListener'); + const removed = vi.spyOn(document, 'removeEventListener'); + const container = document.createElement('div'); + document.body.appendChild(container); + const onSelect = vi.fn(); + + const dropdown = new Dropdown(container, { + placeholder: 'Select model', + items: [ + { value: 'gpt-5', label: 'GPT-5' }, + { value: 'gpt-5-mini', label: 'GPT-5 Mini' } + ], + selectedValue: 'gpt-5', + width: '100%', + onSelect + }); + + expect(container.textContent).toContain('GPT-5'); + const options = container.querySelectorAll('[role="option"]'); + expect(options).toHaveLength(2); + options[1].click(); + expect(onSelect).toHaveBeenCalledWith('gpt-5-mini', expect.anything()); + + expect(typeof dropdown.destroy).toBe('function'); + dropdown.destroy?.(); + const documentListeners = added.mock.calls.map(([type, listener]) => ({ type, listener })); + for (const { type, listener } of documentListeners) { + expect(removed.mock.calls.some(([t, l]) => t === type && l === listener)).toBe(true); + } + added.mockRestore(); + removed.mockRestore(); + }); + + it('dropdown: grouped model items render with headings, or with prefixed labels before group support', async () => { + const Dropdown = await component('dropdown/dropdown.js'); + const grouped = [ + { label: 'OpenAI', items: [{ value: 'gpt-a', label: 'GPT A' }] }, + { label: 'Anthropic', items: [{ value: 'claude-a', label: 'Claude A' }] } + ]; + const supportsGroups = dropdownSupportsGroups(Dropdown); + const container = document.createElement('div'); + document.body.appendChild(container); + + const dropdown = new Dropdown(container, { + placeholder: 'Select model', + items: supportsGroups ? grouped : flattenGroupedItems(grouped), + selectedValue: 'claude-a', + width: '100%', + onSelect: () => {} + }); + + const optionLabels = Array.from(container.querySelectorAll('[role="option"]')).map((o) => o.textContent?.trim()); + const headings = Array.from(container.querySelectorAll('[role="group"]')).map((group) => + document.getElementById(group.getAttribute('aria-labelledby') ?? '')?.textContent + ); + if (supportsGroups) { + expect(headings).toEqual(['OpenAI', 'Anthropic']); + expect(optionLabels).toEqual(['GPT A', 'Claude A']); + } else { + expect(headings).toEqual([]); + expect(optionLabels).toEqual(['OpenAI · GPT A', 'Anthropic · Claude A']); + } + dropdown.destroy?.(); + }); + + it('modal: opens, runs footer button handlers and closes', async () => { + const Modal = await component('modal/modal.js'); + const content = document.createElement('p'); + content.textContent = 'Clear the canvas?'; + const onClose = vi.fn(); + + const modal = new Modal({ + size: 'small', + title: 'Confirm', + content, + footerButtons: [ + { label: 'Cancel', type: 'secondary', onClick: (_event, instance) => instance.close() }, + { label: 'Clear', type: 'primary', onClick: (_event, instance) => instance.close() } + ], + onClose + }); + modal.open(); + + const dialog = document.querySelector('[role="dialog"]'); + expect(dialog?.textContent).toContain('Clear the canvas?'); + const confirm = Array.from(dialog?.querySelectorAll('button') ?? []).find((b) => b.textContent?.trim() === 'Clear'); + confirm?.click(); + expect(onClose).toHaveBeenCalledTimes(1); + modal.destroy(); + + expect(typeof Modal.createHelpModal).toBe('function'); + const help = Modal.createHelpModal({ title: 'Help / User Guide', content: '

Guide

' }); + expect(typeof help.open).toBe('function'); + help.destroy(); + }); + + it('split panel: exposes both panels and a named divider', async () => { + // jsdom has no ResizeObserver; the component only uses it to re-apply the split. + vi.stubGlobal('ResizeObserver', class { + observe(): void {} + unobserve(): void {} + disconnect(): void {} + }); + const SplitPanel = await component('split-panel/split-panel.js'); + const layout = document.createElement('div'); + document.body.appendChild(layout); + + const split = new SplitPanel(layout, { initialSplit: 70, minLeft: 30, minRight: 20, dividerLabel: 'Resize run console' }); + + expect(split.getLeftPanel()).toBeInstanceOf(HTMLElement); + expect(split.getRightPanel()).toBeInstanceOf(HTMLElement); + expect(layout.querySelector('[aria-label="Resize run console"]')).not.toBeNull(); + vi.unstubAllGlobals(); + }); +}); diff --git a/apps/web/src/app/ds-loader.ts b/apps/web/src/app/ds-loader.ts new file mode 100644 index 0000000..227128b --- /dev/null +++ b/apps/web/src/app/ds-loader.ts @@ -0,0 +1,146 @@ +import type { ConfirmOptions } from './types'; + +export type DropdownItem = { + value: string; + label: string; +}; + +/** Options under a heading. Needs a design-system dropdown with group support. */ +export type DropdownGroup = { + label: string; + items: DropdownItem[]; +}; + +export type DropdownEntry = DropdownItem | DropdownGroup; + +export type DropdownConfig = { + placeholder: string; + items: DropdownEntry[]; + selectedValue: string; + width: string; + onSelect: (value: string) => void; +}; + +export type DropdownInstance = { + destroy?: () => void; +}; + +export type DropdownCtor = new (container: HTMLElement, config: DropdownConfig) => DropdownInstance; + +/** Whether this design-system dropdown accepts group entries (added after the pinned 2026-10 version). */ +export function dropdownSupportsGroups(ctor: DropdownCtor): boolean { + return typeof (ctor as { flattenOptions?: unknown }).flattenOptions === 'function'; +} + +export type SplitPanelInstance = { + getLeftPanel: () => HTMLElement; + getRightPanel: () => HTMLElement; +}; + +export type SplitPanelCtor = new ( + container: Element, + options: { initialSplit: number; minLeft: number; minRight: number; dividerLabel?: string } +) => SplitPanelInstance; + +export type ModalInstance = { + open: () => void; + close: () => void; + destroy: () => void; +}; + +type ModalFooterButton = { + label: string; + type: 'primary' | 'secondary'; + onClick: (_event: Event, instance: ModalInstance) => void; +}; + +export type ModalCtor = (new (options: { + size: 'small' | 'medium' | 'large'; + title: string; + content: HTMLElement; + footerButtons: ModalFooterButton[]; + onClose: () => void; +}) => ModalInstance) & { + createHelpModal: (options: { title: string; content: string }) => ModalInstance; +}; + +const componentCache = new Map>(); + +/** + * Loads a design-system component module (served from the `design-system` + * submodule under `/design-system/`) and returns its default export. + */ +function loadDesignSystemComponent(componentPath: string): Promise { + let pending = componentCache.get(componentPath); + if (!pending) { + const modulePath = `${window.location.origin}/design-system/components/${componentPath}`; + pending = import(/* @vite-ignore */ modulePath).then( + (mod) => (mod as { default: T }).default + ); + // A failed load must not be cached, or the component could never recover. + pending.catch(() => componentCache.delete(componentPath)); + componentCache.set(componentPath, pending); + } + return pending as Promise; +} + +export function getDropdownCtor(): Promise { + return loadDesignSystemComponent('dropdown/dropdown.js'); +} + +export function getSplitPanelCtor(): Promise { + return loadDesignSystemComponent('split-panel/split-panel.js'); +} + +export function getModalCtor(): Promise { + return loadDesignSystemComponent('modal/modal.js'); +} + +export async function openConfirmModal(options: ConfirmOptions = {}): Promise { + const { + title = 'Confirm', + message = 'Are you sure?', + confirmLabel = 'Confirm', + cancelLabel = 'Cancel' + } = options; + + try { + const ModalCtor = await getModalCtor(); + const content = document.createElement('p'); + content.textContent = message; + + return await new Promise((resolve) => { + let confirmed = false; + + const modal = new ModalCtor({ + size: 'small', + title, + content, + footerButtons: [ + { + label: cancelLabel, + type: 'secondary', + onClick: (_event, instance) => instance.close() + }, + { + label: confirmLabel, + type: 'primary', + onClick: (_event, instance) => { + confirmed = true; + instance.close(); + } + } + ], + onClose: () => { + modal.destroy(); + resolve(confirmed); + } + }); + + modal.open(); + }); + } catch (error) { + console.warn('Failed to initialize DS confirm modal', error); + return window.confirm(message); + } +} diff --git a/apps/web/src/app/editor-host.ts b/apps/web/src/app/editor-host.ts new file mode 100644 index 0000000..59f863b --- /dev/null +++ b/apps/web/src/app/editor-host.ts @@ -0,0 +1,60 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import type { ViewportController } from './canvas/viewport'; +import type { EditorNode } from './types'; + +/** Mutable editor state shared by the canvas modules. */ +export type EditorStore = { + nodes: EditorNode[]; + connections: WorkflowConnection[]; + nextNodeId: number; + selectedNodeId: string | null; + selectedConnection: WorkflowConnection | null; + /** Model ids offered in the picker, from every provider that has an API key. */ + modelOptions: string[]; + modelEfforts: Record; + /** Display names by model id. */ + modelLabels: Record; + /** Provider display name by model id. */ + modelProviders: Record; + /** Effort preselected for a model, by model id. */ + modelDefaultEfforts: Record; + /** Model given to new agent nodes. */ + defaultModel: string; +}; + +/** Pointer and keyboard handlers a port element forwards to. */ +export interface PortInteractions { + onPortMouseDown(event: MouseEvent, nodeId: string, handle: string): void; + onPortMouseUp(event: MouseEvent, nodeId: string, handle: string): void; + onPortKeyActivate(nodeId: string, handle: string): void; +} + +/** + * What the canvas modules (node view, node forms, connections) need from the + * editor. Implemented by `WorkflowEditor`, the composition root. + */ +export interface EditorHost extends PortInteractions { + readonly store: EditorStore; + readonly viewport: ViewportController; + readonly nodesLayer: HTMLElement | null; + readonly connectionsLayer: SVGSVGElement | HTMLElement | null; + + renderConnections(): void; + scheduleConnectionLayoutSync(): void; + refreshNodePorts(node: EditorNode): void; + rerenderNodeForm(node: EditorNode): void; + updateRunButton(): void; + /** Debounced save; also records an undo step once the edits settle. */ + scheduleSave(): void; + /** Records an undo step now (for discrete edits such as connect or delete). */ + commitHistory(): void; + setCanvasValidationMessage(message: string | null): void; + + selectNode(id: string | null): void; + selectConnection(connection: WorkflowConnection | null): void; + requestDeleteNode(id: string): Promise; + duplicateAgentNode(node: EditorNode): void; + toggleNodeCollapsed(node: EditorNode): void; + beginNodeDrag(node: EditorNode, event: MouseEvent): void; + nudgeNode(node: EditorNode, dx: number, dy: number): void; +} diff --git a/apps/web/src/app/graph/history.test.ts b/apps/web/src/app/graph/history.test.ts new file mode 100644 index 0000000..af351d4 --- /dev/null +++ b/apps/web/src/app/graph/history.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from 'vitest'; + +import type { WorkflowGraphPayload } from '../types'; +import { GraphHistory } from './history'; + +const graph = (...ids: string[]): WorkflowGraphPayload => ({ + nodes: ids.map((id) => ({ id, type: 'agent', x: 0, y: 0, data: {} })), + connections: [] +}); +const ids = (value: WorkflowGraphPayload | null) => value?.nodes.map((node) => node.id) ?? null; + +describe('GraphHistory', () => { + it('has nothing to undo or redo at first', () => { + const history = new GraphHistory(graph('a')); + expect(history.canUndo()).toBe(false); + expect(history.canRedo()).toBe(false); + expect(history.undo(graph('a'))).toBeNull(); + expect(history.redo(graph('a'))).toBeNull(); + }); + + it('undoes and redoes observed steps', () => { + const history = new GraphHistory(graph('a')); + history.observe(graph('a', 'b')); + history.observe(graph('a', 'b', 'c')); + + expect(ids(history.undo(graph('a', 'b', 'c')))).toEqual(['a', 'b']); + expect(ids(history.undo(graph('a', 'b')))).toEqual(['a']); + expect(history.undo(graph('a'))).toBeNull(); + expect(ids(history.redo(graph('a')))).toEqual(['a', 'b']); + expect(ids(history.redo(graph('a', 'b')))).toEqual(['a', 'b', 'c']); + expect(history.redo(graph('a', 'b', 'c'))).toBeNull(); + }); + + it('ignores an observation that changes nothing', () => { + const history = new GraphHistory(graph('a')); + expect(history.observe(graph('a'))).toBe(false); + expect(history.canUndo()).toBe(false); + }); + + it('does not create steps for view-only fields', () => { + const history = new GraphHistory(graph('a')); + const collapsed = graph('a'); + collapsed.nodes[0].data = { collapsed: true, initialInput: 'hello' }; + expect(history.observe(collapsed)).toBe(false); + }); + + it('captures an unobserved edit before undoing, so it can be redone', () => { + const history = new GraphHistory(graph('a')); + // The live graph changed but the debounced observe has not run yet. + expect(ids(history.undo(graph('a', 'b')))).toEqual(['a']); + expect(ids(history.redo(graph('a')))).toEqual(['a', 'b']); + }); + + it('drops the redo stack after a new edit', () => { + const history = new GraphHistory(graph('a')); + history.observe(graph('a', 'b')); + history.undo(graph('a', 'b')); + history.observe(graph('a', 'x')); + expect(history.canRedo()).toBe(false); + expect(history.redo(graph('a', 'x'))).toBeNull(); + // An unobserved edit also invalidates redo. + history.undo(graph('a', 'x')); + expect(history.redo(graph('a', 'y'))).toBeNull(); + }); + + it('is bounded', () => { + const history = new GraphHistory(graph('n0'), 3); + for (let i = 1; i <= 10; i += 1) history.observe(graph(`n${i}`)); + const seen: Array = []; + let current = graph('n10'); + for (let i = 0; i < 5; i += 1) { + const previous = history.undo(current); + seen.push(ids(previous)); + if (previous) current = previous; + } + expect(seen).toEqual([['n9'], ['n8'], ['n7'], null, null]); + }); + + it('returns copies, so later mutation does not corrupt history', () => { + const history = new GraphHistory(graph('a')); + const live = graph('a', 'b'); + history.observe(live); + live.nodes[1].id = 'mutated'; + const restored = history.undo(graph('a', 'b')); + if (restored) restored.nodes[0].id = 'mutated-too'; + expect(ids(history.redo(graph('a')))).toEqual(['a', 'b']); + expect(ids(history.undo(graph('a', 'b')))).toEqual(['a']); + }); + + it('forgets everything on reset', () => { + const history = new GraphHistory(graph('a')); + history.observe(graph('a', 'b')); + history.reset(graph('z')); + expect(history.canUndo()).toBe(false); + expect(history.undo(graph('z'))).toBeNull(); + }); +}); diff --git a/apps/web/src/app/graph/history.ts b/apps/web/src/app/graph/history.ts new file mode 100644 index 0000000..238eb57 --- /dev/null +++ b/apps/web/src/app/graph/history.ts @@ -0,0 +1,85 @@ +import { HISTORY_LIMIT } from '../constants'; +import type { WorkflowGraphPayload } from '../types'; + +/** View-only fields: changing them is not an edit, so they never create an undo step. */ +const VIEW_ONLY_KEYS = new Set(['collapsed', 'initialInput']); + +function cloneGraph(graph: WorkflowGraphPayload): WorkflowGraphPayload { + return JSON.parse(JSON.stringify(graph)) as WorkflowGraphPayload; +} + +function fingerprint(graph: WorkflowGraphPayload): string { + return JSON.stringify(graph, (key, value: unknown) => (VIEW_ONLY_KEYS.has(key) ? undefined : value)); +} + +type Snapshot = { + graph: WorkflowGraphPayload; + key: string; +}; + +/** + * Bounded undo/redo history of graph snapshots. + * + * Callers `observe()` the graph after edits. Rapid edits (typing) are coalesced + * by the caller observing on a debounce; `undo()`/`redo()` first observe the + * live graph so an edit that has not been observed yet is never lost. + */ +export class GraphHistory { + private past: Snapshot[] = []; + + private present: Snapshot; + + private future: Snapshot[] = []; + + constructor(initial: WorkflowGraphPayload, private readonly limit: number = HISTORY_LIMIT) { + this.present = { graph: cloneGraph(initial), key: fingerprint(initial) }; + } + + /** Forget everything and start from `graph` (after loading or clearing). */ + reset(graph: WorkflowGraphPayload): void { + this.past = []; + this.future = []; + this.present = { graph: cloneGraph(graph), key: fingerprint(graph) }; + } + + /** Records `graph` as a new step when it differs from the current one. */ + observe(graph: WorkflowGraphPayload): boolean { + const key = fingerprint(graph); + if (key === this.present.key) return false; + this.past.push(this.present); + if (this.past.length > this.limit) { + this.past.splice(0, this.past.length - this.limit); + } + this.present = { graph: cloneGraph(graph), key }; + this.future = []; + return true; + } + + canUndo(): boolean { + return this.past.length > 0; + } + + canRedo(): boolean { + return this.future.length > 0; + } + + /** Returns the graph to restore, or null when there is nothing to undo. */ + undo(current: WorkflowGraphPayload): WorkflowGraphPayload | null { + this.observe(current); + const previous = this.past.pop(); + if (!previous) return null; + this.future.push(this.present); + this.present = previous; + return cloneGraph(previous.graph); + } + + /** Returns the graph to restore, or null when there is nothing to redo. */ + redo(current: WorkflowGraphPayload): WorkflowGraphPayload | null { + if (this.observe(current)) return null; + const next = this.future.pop(); + if (!next) return null; + this.past.push(this.present); + this.present = next; + return cloneGraph(next.graph); + } +} diff --git a/apps/web/src/app/graph/if-conditions.test.ts b/apps/web/src/app/graph/if-conditions.test.ts new file mode 100644 index 0000000..d5345fd --- /dev/null +++ b/apps/web/src/app/graph/if-conditions.test.ts @@ -0,0 +1,121 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { describe, expect, it } from 'vitest'; + +import type { EditorNode } from '../types'; +import { + getIfConditionHandle, + getIfConditionIndexFromHandle, + getIfConditions, + normalizeIfCondition, + removeIfCondition +} from './if-conditions'; +import { upgradeLegacyGraph } from './legacy-upgrade'; + +const ifNode = (values: string[]): EditorNode => ({ + id: 'c', + type: 'if', + x: 0, + y: 0, + data: { conditions: values.map((value) => ({ operator: 'equal' as const, value })) } +}); +const edge = (source: string, target: string, sourceHandle: string): WorkflowConnection => + ({ source, target, sourceHandle, targetHandle: 'input' }); + +describe('if-condition helpers', () => { + it('normalises unknown shapes', () => { + expect(normalizeIfCondition(null)).toEqual({ operator: 'equal', value: '' }); + expect(normalizeIfCondition({ operator: 'contains', value: 'x' })).toEqual({ operator: 'contains', value: 'x' }); + expect(normalizeIfCondition({ operator: 'weird', value: 3 })).toEqual({ operator: 'equal', value: '' }); + }); + + it('maps handles to indexes, including the legacy true handle', () => { + expect(getIfConditionHandle(2)).toBe('condition-2'); + expect(getIfConditionIndexFromHandle('condition-2')).toBe(2); + expect(getIfConditionIndexFromHandle('true')).toBe(0); + expect(getIfConditionIndexFromHandle('false')).toBeNull(); + expect(getIfConditionIndexFromHandle('condition-x')).toBeNull(); + expect(getIfConditionIndexFromHandle(undefined)).toBeNull(); + }); + + it('always returns at least one condition', () => { + const node: EditorNode = { id: 'c', type: 'if', x: 0, y: 0 }; + expect(getIfConditions(node)).toEqual([{ operator: 'equal', value: '' }]); + expect(node.data?.conditions).toHaveLength(1); + }); +}); + +describe('removeIfCondition', () => { + it('drops the removed branch and re-indexes the later ones', () => { + const node = ifNode(['a', 'b', 'c']); + const connections = [ + edge('s', 'c', 'output'), + edge('c', 'x', 'condition-0'), + edge('c', 'y', 'condition-1'), + edge('c', 'z', 'condition-2'), + edge('c', 'f', 'false'), + edge('other', 'q', 'condition-1') + ]; + + const next = removeIfCondition(node, 1, connections); + + expect(node.data?.conditions?.map((condition) => condition.value)).toEqual(['a', 'c']); + expect(next).toEqual([ + edge('s', 'c', 'output'), + edge('c', 'x', 'condition-0'), + edge('c', 'z', 'condition-1'), + edge('c', 'f', 'false'), + edge('other', 'q', 'condition-1') + ]); + }); + + it('keeps the last remaining condition', () => { + const node = ifNode(['only']); + const connections = [edge('c', 'x', 'condition-0')]; + expect(removeIfCondition(node, 0, connections)).toBe(connections); + expect(node.data?.conditions).toHaveLength(1); + }); +}); + +describe('upgradeLegacyGraph', () => { + it('turns input nodes into approval nodes with a default prompt', () => { + const nodes: EditorNode[] = [{ id: 'n', type: 'input', x: 0, y: 0, data: {} }]; + expect(upgradeLegacyGraph(nodes, [])).toBe(true); + expect(nodes[0].type).toBe('approval'); + expect(nodes[0].data?.prompt).toBe('Review and approve this step.'); + }); + + it('keeps an existing prompt on a legacy input node', () => { + const nodes: EditorNode[] = [{ id: 'n', type: 'input', x: 0, y: 0, data: { prompt: 'Check it' } }]; + upgradeLegacyGraph(nodes, []); + expect(nodes[0].data?.prompt).toBe('Check it'); + }); + + it('fills in missing agent tool flags', () => { + const nodes: EditorNode[] = [{ id: 'a', type: 'agent', x: 0, y: 0, data: { tools: { web_search: true } } }]; + expect(upgradeLegacyGraph(nodes, [])).toBe(true); + expect(nodes[0].data?.tools).toEqual({ web_search: true, subagents: false }); + }); + + it('converts a legacy condition string and the true handle', () => { + const nodes: EditorNode[] = [{ id: 'c', type: 'if', x: 0, y: 0, data: { condition: 'yes' } }]; + const connections = [edge('c', 'x', 'true'), edge('c', 'y', 'false'), edge('other', 'z', 'true')]; + expect(upgradeLegacyGraph(nodes, connections)).toBe(true); + expect(nodes[0].data?.conditions).toEqual([{ operator: 'contains', value: 'yes' }]); + expect(nodes[0].data && 'condition' in nodes[0].data).toBe(false); + expect(connections.map((connection) => connection.sourceHandle)).toEqual(['condition-0', 'false', 'true']); + }); + + it('reports no change for an up-to-date graph, however often it runs', () => { + const nodes: EditorNode[] = [ + { id: 's', type: 'start', x: 0, y: 0, data: {} }, + { id: 'a', type: 'agent', x: 0, y: 0, data: { tools: { web_search: false, subagents: true } } }, + { id: 'c', type: 'if', x: 0, y: 0, data: { conditions: [{ operator: 'contains', value: 'x' }] } }, + { id: 'p', type: 'approval', x: 0, y: 0, data: { prompt: 'ok' } } + ]; + const connections = [edge('c', 'a', 'condition-0')]; + const before = JSON.stringify({ nodes, connections }); + expect(upgradeLegacyGraph(nodes, connections)).toBe(false); + expect(upgradeLegacyGraph(nodes, connections)).toBe(false); + expect(JSON.stringify({ nodes, connections })).toBe(before); + }); +}); diff --git a/apps/web/src/app/graph/if-conditions.ts b/apps/web/src/app/graph/if-conditions.ts new file mode 100644 index 0000000..4cf1f03 --- /dev/null +++ b/apps/web/src/app/graph/if-conditions.ts @@ -0,0 +1,79 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { + DEFAULT_IF_CONDITION, + IF_CONDITION_HANDLE_PREFIX, + LEGACY_IF_TRUE_HANDLE +} from '../constants'; +import type { EditorNode, IfCondition } from '../types'; + +export function normalizeIfCondition(condition: unknown): IfCondition { + const asRecord = (typeof condition === 'object' && condition !== null) ? condition as Partial : undefined; + const candidateOperator = asRecord?.operator; + const rawValue = asRecord?.value; + return { + operator: candidateOperator === 'contains' ? 'contains' : 'equal', + value: typeof rawValue === 'string' ? rawValue : '' + }; +} + +export function getIfConditionHandle(index: number): string { + return `${IF_CONDITION_HANDLE_PREFIX}${index}`; +} + +export function getIfConditionIndexFromHandle(handle: string | undefined): number | null { + if (handle === LEGACY_IF_TRUE_HANDLE) return 0; + if (typeof handle !== 'string' || !handle.startsWith(IF_CONDITION_HANDLE_PREFIX)) return null; + const parsedIndex = Number.parseInt(handle.slice(IF_CONDITION_HANDLE_PREFIX.length), 10); + return Number.isInteger(parsedIndex) && parsedIndex >= 0 ? parsedIndex : null; +} + +/** Returns the node's conditions, normalising them in place (always at least one). */ +export function getIfConditions(node: EditorNode): IfCondition[] { + if (!node.data) node.data = {}; + if (!Array.isArray(node.data.conditions) || node.data.conditions.length === 0) { + node.data.conditions = [{ ...DEFAULT_IF_CONDITION }]; + } + node.data.conditions = node.data.conditions.map((condition) => normalizeIfCondition(condition)); + return node.data.conditions; +} + +/** + * Removes one condition from the node and returns the connection list with the + * removed branch dropped and the later branches re-indexed. + */ +export function removeIfCondition( + node: EditorNode, + conditionIndex: number, + connections: WorkflowConnection[] +): WorkflowConnection[] { + const conditions = getIfConditions(node); + if (conditions.length <= 1) return connections; + if (!node.data) return connections; + + node.data.conditions = conditions.filter((_, index) => index !== conditionIndex); + return connections.reduce((nextConnections, connection) => { + if (connection.source !== node.id) { + nextConnections.push(connection); + return nextConnections; + } + + const sourceIndex = getIfConditionIndexFromHandle(connection.sourceHandle); + if (sourceIndex === null) { + nextConnections.push(connection); + return nextConnections; + } + if (sourceIndex === conditionIndex) { + return nextConnections; + } + if (sourceIndex > conditionIndex) { + nextConnections.push({ + ...connection, + sourceHandle: getIfConditionHandle(sourceIndex - 1) + }); + return nextConnections; + } + + nextConnections.push(connection); + return nextConnections; + }, []); +} diff --git a/apps/web/src/app/graph/legacy-upgrade.ts b/apps/web/src/app/graph/legacy-upgrade.ts new file mode 100644 index 0000000..5e5c4b9 --- /dev/null +++ b/apps/web/src/app/graph/legacy-upgrade.ts @@ -0,0 +1,81 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { DEFAULT_APPROVAL_PROMPT, DEFAULT_IF_CONDITION, LEGACY_IF_TRUE_HANDLE } from '../constants'; +import type { AgentTools, EditorNode } from '../types'; +import { getIfConditionHandle, normalizeIfCondition } from './if-conditions'; + +/** + * Upgrades graphs saved by older versions, in place: + * - `input` nodes become `approval` nodes; + * - agent `tools` always has both boolean flags; + * - a Condition node's single `condition` string becomes a `conditions` list; + * - the Condition node's `true` handle becomes `condition-0`. + * + * Saved workflows in localStorage and course-supplied default workflows can + * still have these shapes, so this must keep working. + * + * @returns true only when something actually changed. + */ +export function upgradeLegacyGraph(nodes: EditorNode[], connections: WorkflowConnection[]): boolean { + let updated = false; + const ifNodeIds = new Set(); + + nodes.forEach((node) => { + if (node.type === 'input') { + node.type = 'approval'; + if (!node.data) node.data = {}; + if (node.data.prompt === undefined) { + node.data.prompt = DEFAULT_APPROVAL_PROMPT; + } + updated = true; + } + + if (node.type === 'agent') { + if (!node.data) node.data = {}; + const tools: AgentTools = (node.data.tools && typeof node.data.tools === 'object') + ? node.data.tools + : {}; + const nextTools = { + web_search: Boolean(tools.web_search), + subagents: Boolean(tools.subagents) + }; + if ( + !node.data.tools || + node.data.tools.web_search !== nextTools.web_search || + node.data.tools.subagents !== nextTools.subagents + ) { + node.data.tools = nextTools; + updated = true; + } + } + + if (node.type === 'if') { + ifNodeIds.add(node.id); + if (!node.data) node.data = {}; + const before = JSON.stringify(node.data.conditions ?? null); + const rawLegacyCondition = typeof node.data.condition === 'string' ? node.data.condition : ''; + const rawConditions: unknown[] = Array.isArray(node.data.conditions) && node.data.conditions.length > 0 + ? node.data.conditions + : 'condition' in node.data + ? [{ operator: 'contains', value: rawLegacyCondition }] + : [{ ...DEFAULT_IF_CONDITION }]; + node.data.conditions = rawConditions.map((condition) => normalizeIfCondition(condition)); + if (JSON.stringify(node.data.conditions) !== before) { + updated = true; + } + if ('condition' in node.data) { + delete node.data.condition; + updated = true; + } + } + }); + + connections.forEach((connection) => { + if (!ifNodeIds.has(connection.source)) return; + if (connection.sourceHandle === LEGACY_IF_TRUE_HANDLE) { + connection.sourceHandle = getIfConditionHandle(0); + updated = true; + } + }); + + return updated; +} diff --git a/apps/web/src/app/graph/validation.test.ts b/apps/web/src/app/graph/validation.test.ts new file mode 100644 index 0000000..69b9faa --- /dev/null +++ b/apps/web/src/app/graph/validation.test.ts @@ -0,0 +1,228 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { describe, expect, it } from 'vitest'; + +import type { EditorNode } from '../types'; +import { + canNodeBecomeSubagentTarget, + getConnectionValidationError, + getRunDisableReason, + getSubagentGraphValidationError, + isValidGraphInput +} from './validation'; + +const node = (id: string, type: string, data: EditorNode['data'] = {}): EditorNode => ({ id, type, x: 0, y: 0, data }); +const agent = (id: string, subagents = false): EditorNode => + node(id, 'agent', { tools: { web_search: false, subagents } }); +const edge = (source: string, target: string, sourceHandle = 'output', targetHandle: string | undefined = 'input'): WorkflowConnection => + ({ source, target, sourceHandle, targetHandle }); +const sub = (source: string, target: string): WorkflowConnection => edge(source, target, 'subagent'); + +describe('isValidGraphInput', () => { + it('accepts graphs whose nodes have string ids and types', () => { + expect(isValidGraphInput({ nodes: [{ id: 'a', type: 'start' }], connections: [] })).toBe(true); + }); + + it('rejects malformed values', () => { + expect(isValidGraphInput(null)).toBe(false); + expect(isValidGraphInput({ nodes: [] })).toBe(false); + expect(isValidGraphInput({ nodes: [{ id: 1, type: 'start' }], connections: [] })).toBe(false); + expect(isValidGraphInput({ nodes: [{ id: 'a' }], connections: [] })).toBe(false); + }); +}); + +describe('getRunDisableReason', () => { + const start = node('s', 'start'); + + it('allows a connected Start -> Agent workflow', () => { + expect(getRunDisableReason([start, agent('a')], [edge('s', 'a')])).toBeNull(); + }); + + it('requires a Start node', () => { + expect(getRunDisableReason([agent('a')], [])).toBe('Add a Start node to run the workflow.'); + }); + + it('rejects more than one Start node', () => { + expect(getRunDisableReason([start, node('s2', 'start')], [])).toBe('Use only one Start node before running.'); + }); + + it('rejects connections that reference a missing node', () => { + expect(getRunDisableReason([start, agent('a')], [edge('s', 'a'), edge('a', 'ghost')])).toBe( + 'Fix broken connections before running.' + ); + expect(getRunDisableReason([start, agent('a')], [edge('s', 'a'), edge('ghost', 'a')])).toBe( + 'Fix broken connections before running.' + ); + }); + + it('reports invalid subagent structures', () => { + const reason = getRunDisableReason([start, agent('a'), agent('b')], [edge('s', 'a'), sub('a', 'b')]); + expect(reason).toBe('Enable Subagents on the parent agent before linking subagents.'); + }); + + it('requires Start to have an outgoing execution connection', () => { + expect(getRunDisableReason([start, agent('a')], [])).toBe('Connect Start to another node before running.'); + }); + + it('requires a reachable Condition node to have a branch', () => { + const nodes = [start, node('c', 'if')]; + expect(getRunDisableReason(nodes, [edge('s', 'c')])).toBe('Connect at least one branch for each Condition node.'); + }); + + it('accepts a Condition node with only a condition branch or only the fallback', () => { + const nodes = [start, node('c', 'if'), agent('a')]; + expect(getRunDisableReason(nodes, [edge('s', 'c'), edge('c', 'a', 'condition-0')])).toBeNull(); + expect(getRunDisableReason(nodes, [edge('s', 'c'), edge('c', 'a', 'false')])).toBeNull(); + expect(getRunDisableReason(nodes, [edge('s', 'c'), edge('c', 'a', 'true')])).toBeNull(); + }); + + it('requires a reachable approval node to have a branch', () => { + const reason = 'Connect at least one branch for each User Approval node.'; + expect(getRunDisableReason([start, node('p', 'approval')], [edge('s', 'p')])).toBe(reason); + expect(getRunDisableReason([start, node('p', 'input')], [edge('s', 'p')])).toBe(reason); + }); + + it('accepts an approval node with only one branch', () => { + const nodes = [start, node('p', 'approval'), agent('a')]; + expect(getRunDisableReason(nodes, [edge('s', 'p'), edge('p', 'a', 'approve')])).toBeNull(); + expect(getRunDisableReason(nodes, [edge('s', 'p'), edge('p', 'a', 'reject')])).toBeNull(); + }); + + it('ignores unreachable nodes', () => { + const nodes = [start, agent('a'), node('c', 'if'), node('p', 'approval')]; + expect(getRunDisableReason(nodes, [edge('s', 'a')])).toBeNull(); + }); + + it('allows loops in the regular flow', () => { + const nodes = [start, agent('a'), node('c', 'if')]; + const connections = [edge('s', 'a'), edge('a', 'c'), edge('c', 'a', 'false')]; + expect(getRunDisableReason(nodes, connections)).toBeNull(); + }); + + it('allows nested acyclic subagent chains', () => { + const nodes = [start, agent('a', true), agent('b', true), agent('c')]; + expect(getRunDisableReason(nodes, [edge('s', 'a'), sub('a', 'b'), sub('b', 'c')])).toBeNull(); + }); +}); + +describe('getSubagentGraphValidationError', () => { + it('returns null without subagent links', () => { + expect(getSubagentGraphValidationError([agent('a'), agent('b')], [edge('a', 'b')])).toBeNull(); + }); + + it('requires agent nodes at both ends', () => { + expect(getSubagentGraphValidationError([node('c', 'if'), agent('b')], [sub('c', 'b')])).toBe( + 'Subagent links must start from an Agent node.' + ); + expect(getSubagentGraphValidationError([agent('a', true), node('c', 'if')], [sub('a', 'c')])).toBe( + 'Subagent links must target an Agent node.' + ); + }); + + it('requires the input target handle, and accepts it omitted', () => { + const nodes = [agent('a', true), agent('b')]; + expect(getSubagentGraphValidationError(nodes, [edge('a', 'b', 'subagent', 'other')])).toBe( + 'Subagent links must connect to the target input handle.' + ); + expect(getSubagentGraphValidationError(nodes, [edge('a', 'b', 'subagent', undefined)])).toBeNull(); + }); + + it('rejects self references', () => { + expect(getSubagentGraphValidationError([agent('a', true)], [sub('a', 'a')])).toBe( + 'An agent cannot be a subagent of itself.' + ); + }); + + it('rejects a subagent with two parents', () => { + const nodes = [agent('a', true), agent('b', true), agent('c')]; + expect(getSubagentGraphValidationError(nodes, [sub('a', 'c'), sub('b', 'c')])).toBe( + 'A subagent can belong to only one parent agent.' + ); + }); + + it('rejects subagent targets that are part of the regular flow', () => { + const nodes = [node('s', 'start'), agent('a', true), agent('b')]; + const message = 'Subagent targets cannot be connected to regular workflow execution edges.'; + expect(getSubagentGraphValidationError(nodes, [sub('a', 'b'), edge('s', 'b')])).toBe(message); + expect(getSubagentGraphValidationError(nodes, [sub('a', 'b'), edge('b', 'a')])).toBe(message); + }); + + it('rejects cycles and names them', () => { + const nodes = [agent('a', true), agent('b', true), agent('c', true)]; + const error = getSubagentGraphValidationError(nodes, [sub('a', 'b'), sub('b', 'c'), sub('c', 'a')]); + expect(error).toBe('Subagent hierarchy must be acyclic. Cycle: a -> b -> c -> a'); + }); +}); + +describe('getConnectionValidationError', () => { + it('rejects connections to missing nodes', () => { + expect(getConnectionValidationError([agent('a')], [], edge('a', 'ghost'))).toBe( + 'Connection source or target node is missing.' + ); + }); + + it('allows a regular connection between regular nodes', () => { + expect(getConnectionValidationError([agent('a'), agent('b')], [], edge('a', 'b'))).toBeNull(); + }); + + it('applies the subagent source and target rules', () => { + expect(getConnectionValidationError([node('c', 'if'), agent('b')], [], sub('c', 'b'))).toBe( + 'Only agent nodes can define subagents.' + ); + expect(getConnectionValidationError([agent('a'), agent('b')], [], sub('a', 'b'))).toBe( + 'Enable Subagents on the parent agent before adding subagent links.' + ); + expect(getConnectionValidationError([agent('a', true), node('c', 'if')], [], sub('a', 'c'))).toBe( + 'Subagent links can only target agent nodes.' + ); + expect(getConnectionValidationError([agent('a', true)], [], sub('a', 'a'))).toBe( + 'An agent cannot be a subagent of itself.' + ); + }); + + it('accepts a subagent link with the target handle omitted, like the graph check does', () => { + const nodes = [agent('a', true), agent('b')]; + expect(getConnectionValidationError(nodes, [], edge('a', 'b', 'subagent', undefined))).toBeNull(); + expect(getConnectionValidationError(nodes, [], edge('a', 'b', 'subagent', 'other'))).toBe( + 'Subagent links must connect to the target input handle.' + ); + }); + + it('keeps subagent targets out of the regular flow', () => { + const nodes = [agent('a', true), agent('b'), agent('c')]; + const existing = [sub('a', 'b')]; + expect(getConnectionValidationError(nodes, existing, edge('b', 'c'))).toBe( + 'Subagent targets cannot be used as sources in regular workflow edges.' + ); + expect(getConnectionValidationError(nodes, existing, edge('c', 'b'))).toBe( + 'Subagent targets cannot be used as targets in regular workflow edges.' + ); + }); + + it('rejects making a node with execution edges a subagent', () => { + const nodes = [agent('a', true), agent('b'), agent('c')]; + expect(getConnectionValidationError(nodes, [edge('b', 'c')], sub('a', 'b'))).toBe( + 'Subagent targets cannot be connected to regular workflow execution edges.' + ); + }); + + it('rejects a second parent and a cycle', () => { + const nodes = [agent('a', true), agent('b', true), agent('c', true)]; + expect(getConnectionValidationError(nodes, [sub('a', 'c')], sub('b', 'c'))).toBe( + 'A subagent can belong to only one parent agent.' + ); + expect(getConnectionValidationError(nodes, [sub('a', 'b'), sub('b', 'c')], sub('c', 'a'))).toContain( + 'Subagent hierarchy must be acyclic.' + ); + }); +}); + +describe('canNodeBecomeSubagentTarget', () => { + it('is true only for a free agent with an eligible parent', () => { + const nodes = [agent('a', true), agent('b'), node('c', 'if')]; + expect(canNodeBecomeSubagentTarget(nodes, [], 'b')).toBe(true); + expect(canNodeBecomeSubagentTarget(nodes, [], 'c')).toBe(false); + expect(canNodeBecomeSubagentTarget(nodes, [], 'a')).toBe(false); + expect(canNodeBecomeSubagentTarget(nodes, [sub('a', 'b')], 'b')).toBe(false); + expect(canNodeBecomeSubagentTarget(nodes, [edge('b', 'c')], 'b')).toBe(false); + }); +}); diff --git a/apps/web/src/app/graph/validation.ts b/apps/web/src/app/graph/validation.ts new file mode 100644 index 0000000..f7bffcd --- /dev/null +++ b/apps/web/src/app/graph/validation.ts @@ -0,0 +1,283 @@ +import type { WorkflowConnection } from '@agentflow/types'; +import { APPROVE_HANDLE, IF_FALLBACK_HANDLE, INPUT_HANDLE, REJECT_HANDLE, SUBAGENT_HANDLE } from '../constants'; +import type { EditorNode, WorkflowGraphPayload } from '../types'; +import { getIfConditionIndexFromHandle } from './if-conditions'; + +export function isValidGraphInput(value: unknown): value is WorkflowGraphPayload { + if (!value || typeof value !== 'object') return false; + const graph = value as { nodes?: unknown; connections?: unknown }; + if (!Array.isArray(graph.nodes) || !Array.isArray(graph.connections)) return false; + return graph.nodes.every((node) => { + if (!node || typeof node !== 'object') return false; + const candidate = node as { id?: unknown; type?: unknown }; + return typeof candidate.id === 'string' && typeof candidate.type === 'string'; + }); +} + +export function isSubagentConnection(connection: WorkflowConnection): boolean { + return connection.sourceHandle === SUBAGENT_HANDLE; +} + +export function getSubagentConnections(connections: WorkflowConnection[]): WorkflowConnection[] { + return connections.filter((connection) => isSubagentConnection(connection)); +} + +export function getExecutionConnections(connections: WorkflowConnection[]): WorkflowConnection[] { + return connections.filter((connection) => !isSubagentConnection(connection)); +} + +export function isSubagentTargetNode(nodeId: string, connections: WorkflowConnection[]): boolean { + return connections.some( + (connection) => + isSubagentConnection(connection) && + connection.target === nodeId + ); +} + +export function getSubagentTargetIds(connections: WorkflowConnection[]): Set { + const targetIds = new Set(); + getSubagentConnections(connections).forEach((connection) => { + targetIds.add(connection.target); + }); + return targetIds; +} + +function isInputTargetHandle(handle: string | undefined): boolean { + return !handle || handle === INPUT_HANDLE; +} + +export function getSubagentGraphValidationError( + nodes: EditorNode[], + connections: WorkflowConnection[] +): string | null { + const subagentConnections = getSubagentConnections(connections); + if (subagentConnections.length === 0) { + return null; + } + + const nodeById = new Map(nodes.map((node) => [node.id, node])); + const incomingSubagentCounts = new Map(); + const adjacency = new Map(); + + for (const connection of subagentConnections) { + const sourceNode = nodeById.get(connection.source); + const targetNode = nodeById.get(connection.target); + + if (!sourceNode || sourceNode.type !== 'agent') { + return 'Subagent links must start from an Agent node.'; + } + if (!targetNode || targetNode.type !== 'agent') { + return 'Subagent links must target an Agent node.'; + } + if (!sourceNode.data?.tools || !sourceNode.data.tools.subagents) { + return 'Enable Subagents on the parent agent before linking subagents.'; + } + if (!isInputTargetHandle(connection.targetHandle)) { + return 'Subagent links must connect to the target input handle.'; + } + if (connection.source === connection.target) { + return 'An agent cannot be a subagent of itself.'; + } + + incomingSubagentCounts.set( + connection.target, + (incomingSubagentCounts.get(connection.target) ?? 0) + 1 + ); + if ((incomingSubagentCounts.get(connection.target) ?? 0) > 1) { + return 'A subagent can belong to only one parent agent.'; + } + + const adjacent = adjacency.get(connection.source) ?? []; + adjacent.push(connection.target); + adjacency.set(connection.source, adjacent); + } + + const executionConnections = getExecutionConnections(connections); + for (const targetId of incomingSubagentCounts.keys()) { + const hasExecutionEdges = executionConnections.some( + (connection) => connection.source === targetId || connection.target === targetId + ); + if (hasExecutionEdges) { + return 'Subagent targets cannot be connected to regular workflow execution edges.'; + } + } + + const visitState = new Map(); + const visit = (nodeId: string, path: string[]): string | null => { + const state = visitState.get(nodeId); + if (state === 'visiting') { + // `path` already ends with `nodeId`, the node that closes the cycle. + const cycleStart = path.indexOf(nodeId); + const cyclePath = path.slice(cycleStart).join(' -> '); + return `Subagent hierarchy must be acyclic. Cycle: ${cyclePath}`; + } + if (state === 'visited') return null; + + visitState.set(nodeId, 'visiting'); + const neighbors = adjacency.get(nodeId) ?? []; + for (const neighbor of neighbors) { + const error = visit(neighbor, [...path, neighbor]); + if (error) return error; + } + visitState.set(nodeId, 'visited'); + return null; + }; + + for (const nodeId of adjacency.keys()) { + const error = visit(nodeId, [nodeId]); + if (error) { + return error; + } + } + + return null; +} + +/** Validates adding `nextConnection` to `connections`. Returns a message, or null when allowed. */ +export function getConnectionValidationError( + nodes: EditorNode[], + connections: WorkflowConnection[], + nextConnection: WorkflowConnection +): string | null { + const sourceNode = nodes.find((node) => node.id === nextConnection.source); + const targetNode = nodes.find((node) => node.id === nextConnection.target); + if (!sourceNode || !targetNode) { + return 'Connection source or target node is missing.'; + } + + const candidateConnections = [...connections, nextConnection]; + + if (isSubagentConnection(nextConnection)) { + if (sourceNode.type !== 'agent') { + return 'Only agent nodes can define subagents.'; + } + if (!sourceNode.data?.tools || !sourceNode.data.tools.subagents) { + return 'Enable Subagents on the parent agent before adding subagent links.'; + } + if (targetNode.type !== 'agent') { + return 'Subagent links can only target agent nodes.'; + } + if (!isInputTargetHandle(nextConnection.targetHandle)) { + return 'Subagent links must connect to the target input handle.'; + } + if (nextConnection.source === nextConnection.target) { + return 'An agent cannot be a subagent of itself.'; + } + } else { + if (isSubagentTargetNode(nextConnection.source, candidateConnections)) { + return 'Subagent targets cannot be used as sources in regular workflow edges.'; + } + if (isSubagentTargetNode(nextConnection.target, candidateConnections)) { + return 'Subagent targets cannot be used as targets in regular workflow edges.'; + } + } + + return getSubagentGraphValidationError(nodes, candidateConnections); +} + +export function canNodeBecomeSubagentTarget( + nodes: EditorNode[], + connections: WorkflowConnection[], + nodeId: string +): boolean { + const targetNode = nodes.find((node) => node.id === nodeId); + if (!targetNode || targetNode.type !== 'agent') { + return false; + } + + if (isSubagentTargetNode(nodeId, connections)) { + return false; + } + + const candidateParents = nodes.filter( + (node) => + node.type === 'agent' && + node.id !== nodeId && + Boolean(node.data?.tools?.subagents) + ); + + return candidateParents.some((parentNode) => { + const candidateConnection: WorkflowConnection = { + source: parentNode.id, + target: nodeId, + sourceHandle: SUBAGENT_HANDLE, + targetHandle: INPUT_HANDLE + }; + return !getConnectionValidationError(nodes, connections, candidateConnection); + }); +} + +/** + * Run-readiness preflight. Returns the reason the workflow cannot run, or null. + * The rules are documented in `apps/web/docs/run-readiness.md`. + */ +export function getRunDisableReason(nodes: EditorNode[], connections: WorkflowConnection[]): string | null { + const startNodes = nodes.filter((node) => node.type === 'start'); + if (startNodes.length === 0) { + return 'Add a Start node to run the workflow.'; + } + if (startNodes.length > 1) { + return 'Use only one Start node before running.'; + } + + const nodeIdSet = new Set(nodes.map((node) => node.id)); + const hasBrokenConnection = connections.some( + (conn) => !nodeIdSet.has(conn.source) || !nodeIdSet.has(conn.target) + ); + if (hasBrokenConnection) { + return 'Fix broken connections before running.'; + } + + const subagentGraphError = getSubagentGraphValidationError(nodes, connections); + if (subagentGraphError) { + return subagentGraphError; + } + + const startNode = startNodes[0]; + const adjacency = new Map(); + getExecutionConnections(connections).forEach((conn) => { + const outgoing = adjacency.get(conn.source) ?? []; + outgoing.push(conn); + adjacency.set(conn.source, outgoing); + }); + + const startConnections = adjacency.get(startNode.id) ?? []; + if (startConnections.length === 0) { + return 'Connect Start to another node before running.'; + } + + const reachable = new Set([startNode.id]); + const queue: string[] = [startNode.id]; + while (queue.length > 0) { + const nodeId = queue.shift() as string; + const next = adjacency.get(nodeId) ?? []; + next.forEach((conn) => { + if (!reachable.has(conn.target)) { + reachable.add(conn.target); + queue.push(conn.target); + } + }); + } + + for (const node of nodes) { + if (!reachable.has(node.id)) continue; + const outgoing = adjacency.get(node.id) ?? []; + if (node.type === 'if') { + const hasConditionBranch = outgoing.some((conn) => getIfConditionIndexFromHandle(conn.sourceHandle) !== null); + const hasFallbackBranch = outgoing.some((conn) => conn.sourceHandle === IF_FALLBACK_HANDLE); + if (!hasConditionBranch && !hasFallbackBranch) { + return 'Connect at least one branch for each Condition node.'; + } + } + // `input` is the pre-upgrade name of the approval node. + if (node.type === 'approval' || node.type === 'input') { + const hasApprove = outgoing.some((conn) => conn.sourceHandle === APPROVE_HANDLE); + const hasReject = outgoing.some((conn) => conn.sourceHandle === REJECT_HANDLE); + if (!hasApprove && !hasReject) { + return 'Connect at least one branch for each User Approval node.'; + } + } + } + + return null; +} diff --git a/apps/web/src/app/markdown.test.ts b/apps/web/src/app/markdown.test.ts new file mode 100644 index 0000000..d95c35d --- /dev/null +++ b/apps/web/src/app/markdown.test.ts @@ -0,0 +1,132 @@ +import { describe, expect, it } from 'vitest'; + +import { escapeHtml, renderMarkdown, sanitizeLinkUrl } from './markdown'; + +describe('escapeHtml', () => { + it('escapes HTML metacharacters', () => { + expect(escapeHtml(`&`)).toBe( + '<img src=x onerror="a('b')">&' + ); + }); +}); + +describe('sanitizeLinkUrl', () => { + it('allows http, https and mailto', () => { + expect(sanitizeLinkUrl('https://example.com/a?b=1&c=2')).toBe('https://example.com/a?b=1&c=2'); + expect(sanitizeLinkUrl('HTTP://example.com')).toBe('HTTP://example.com'); + expect(sanitizeLinkUrl('mailto:someone@example.com')).toBe('mailto:someone@example.com'); + }); + + it('rejects script, data and unknown schemes, and relative URLs', () => { + expect(sanitizeLinkUrl('javascript:alert(1)')).toBeNull(); + expect(sanitizeLinkUrl('JaVaScRiPt:alert(1)')).toBeNull(); + expect(sanitizeLinkUrl('data:text/html,')).toBeNull(); + expect(sanitizeLinkUrl('vbscript:x')).toBeNull(); + expect(sanitizeLinkUrl('file:///etc/passwd')).toBeNull(); + expect(sanitizeLinkUrl('/relative/path')).toBeNull(); + expect(sanitizeLinkUrl('//evil.example')).toBeNull(); + }); + + it('strips control characters before checking the scheme', () => { + const controlChar = String.fromCharCode(1); + const tab = String.fromCharCode(9); + expect(sanitizeLinkUrl(`${controlChar}javascript:alert(1)`)).toBeNull(); + expect(sanitizeLinkUrl(`java${tab}script:alert(1)`)).toBeNull(); + expect(sanitizeLinkUrl(`${controlChar}https://example.com`)).toBe('https://example.com'); + }); +}); + +describe('renderMarkdown', () => { + it('escapes raw HTML in text', () => { + const html = renderMarkdown('Hello '); + expect(html).not.toContain('