diff --git a/.github/workflows/agent-e2e.yml b/.github/workflows/agent-e2e.yml index 539eb2bb..51c1535d 100644 --- a/.github/workflows/agent-e2e.yml +++ b/.github/workflows/agent-e2e.yml @@ -94,9 +94,27 @@ jobs: mcp-testkit --transport http --port 3001 & sleep 2 + # Deterministic decision provider for suite 24 (Jev decision routing). + # Only decision inference is faked; chat LLM calls use the real keys. + - name: Start fake decision provider + run: | + node e2e/fixtures/fake-providers.mjs > fake-providers.log 2>&1 & + # Any HTTP status (the fake answers a bodyless GET with 400) means it is listening. + for i in $(seq 1 20); do + code=$(curl -s -o /dev/null -w '%{http_code}' http://localhost:9911/ || true) + if [ "$code" != "000" ]; then echo "fake providers ready"; exit 0; fi + sleep 0.5 + done + echo "::error::fake providers did not start" + cat fake-providers.log + exit 1 + - name: Start server run: | - java -jar conductor-server-boot.jar --server.port=8080 > server.log 2>&1 & + java -jar conductor-server-boot.jar --server.port=8080 \ + --conductor.ai.decision.endpoint=http://localhost:9911/v1/systemone \ + --conductor.ai.decision.api-key=fake-key \ + > server.log 2>&1 & - name: Wait for server health run: | @@ -155,4 +173,5 @@ jobs: path: | results/ server.log + fake-providers.log retention-days: 14 diff --git a/SDK_NEW_LANGUAGE_GUIDE.md b/SDK_NEW_LANGUAGE_GUIDE.md index dd2dc2db..9ece0a53 100644 --- a/SDK_NEW_LANGUAGE_GUIDE.md +++ b/SDK_NEW_LANGUAGE_GUIDE.md @@ -1337,7 +1337,7 @@ All builders follow the convention: **first argument is always `taskReferenceNam | `httpPollTask` | `(refName, inputParameters, optional?)` | | `inlineTask` | `(refName, script, evaluatorType?, optional?)` | | `subWorkflowTask` | `(refName, workflowName, version?, optional?)` | -| `switchTask` | `(refName, expression, decisionCases?, defaultCase?, optional?)` | +| `switchTask` | `(refName, expression, decisionCases?, defaultCase?, optional?, evaluatorType?)` | | `forkTask` | `(refName, forkTasks)` | | `forkTaskJoin` | `(refName, forkTasks, optional?)` → returns `[ForkJoinTask, JoinTask]` | | `joinTask` | `(refName, joinOn, optional?)` | @@ -1465,6 +1465,16 @@ an agents layer, mirror that catalog — e.g.: | `agents/03-multi-agent.ts` | Multi-agent orchestration | | `agents/09-human-in-the-loop.ts` | Human-in-the-loop AI | | `agents/04-mcp-weather.ts` | MCP tool integration | +| `ai-decision-routing.ts` | Synchronous decision SWITCH with inline branches | +| `agents/decision-router.ts` | Decision ToolDef selector routes to chat agents | +| `agents/decision-tool.ts` | Chat agent uses a branchless decision SWITCH tool | + +Decision support reuses `switchTask` (sixth argument `evaluatorType: "decision"`; the +expression names the choice question, and `inputParameters` carry model/state/questions) +and `ToolDef` (`toolType: "decision"`). Router tools serialize as +`{name, kind: "decision", model, questions, provider?}` and must have exactly one choice +question whose choices are the sub-agent names; `synthesize: false` skips the final parent +LLM step. No new client methods or builders are required. #### 7.4 API Journey Examples (9 files) diff --git a/docs/agents/reference/agent-definition.md b/docs/agents/reference/agent-definition.md index 25959980..3908ee63 100644 --- a/docs/agents/reference/agent-definition.md +++ b/docs/agents/reference/agent-definition.md @@ -15,7 +15,8 @@ Key `AgentOptions` fields: | `tools` | `unknown[]` | `tool()` wrappers, built-in tool defs, framework tools. | | `agents` | `Agent[]` | Sub-agents (multi-agent). | | `strategy` | `Strategy` | `'sequential' \| 'parallel' \| 'handoff' \| 'router' \| 'round_robin' \| 'random' \| 'swarm' \| 'manual' \| 'plan_execute'`. | -| `router` | `Agent \| (() => string)` | Required for `strategy: 'router'`. | +| `router` | `Agent \| ToolDef \| (() => string)` | Required for `strategy: 'router'`. A ToolDef must use `toolType: 'decision'` with `config.model` and nonempty `config.questions`; optional `config.provider` is forwarded. | +| `synthesize` | `boolean` | Default `true`. Set `false` to return specialist output without a final LLM synthesis step. | | `outputType` | Zod schema or JSON Schema | Structured output. | | `guardrails` | `unknown[]` | Guardrail defs / instances. | | `handoffs` | `HandoffCondition[]` | `OnTextMention` / `OnToolResult` / `OnCondition`. | diff --git a/docs/agents/reference/agent-schema.json b/docs/agents/reference/agent-schema.json index 9d88d12f..cf77c47f 100644 --- a/docs/agents/reference/agent-schema.json +++ b/docs/agents/reference/agent-schema.json @@ -5,6 +5,18 @@ "description": "The public wire shape emitted by AgentConfigSerializer.serializeAgent() under agentConfig.", "$ref": "#/$defs/agentConfig", "$defs": { + "decisionRouter": { + "type": "object", + "required": ["name", "kind", "model", "questions"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "kind": { "const": "decision" }, + "model": { "type": "string", "minLength": 1 }, + "provider": { "type": "string" }, + "questions": { "type": "object", "minProperties": 1 } + }, + "additionalProperties": false + }, "taskReference": { "type": "object", "required": ["taskName"], @@ -52,7 +64,8 @@ "tools": { "type": "array", "items": { "$ref": "#/$defs/tool" } }, "agents": { "type": "array", "items": { "$ref": "#/$defs/agentConfig" } }, "strategy": { "type": "string" }, - "router": { "anyOf": [{ "$ref": "#/$defs/taskReference" }, { "$ref": "#/$defs/agentConfig" }] }, + "router": { "anyOf": [{ "$ref": "#/$defs/taskReference" }, { "$ref": "#/$defs/agentConfig" }, { "$ref": "#/$defs/decisionRouter" }] }, + "synthesize": { "type": "boolean" }, "outputType": { "type": "object", "properties": { diff --git a/docs/agents/reference/agent-schema.md b/docs/agents/reference/agent-schema.md index 210bda8c..d3998c12 100644 --- a/docs/agents/reference/agent-schema.md +++ b/docs/agents/reference/agent-schema.md @@ -14,6 +14,11 @@ recursively via the same function. The published allowing intentionally open JSON payloads (tool `inputSchema`/`outputSchema`, `metadata`, guardrail/termination/handoff objects, and per-toolType `config`). +A decision ToolDef in `router` emits `{ name, kind: "decision", model, questions, +provider? }` instead of a nested agent. `model` and nonempty `questions` are required; +an absent provider is omitted. A normal tool emits `toolType: "decision"` with its +config unchanged. `synthesize: false` disables the final specialist synthesis step. + ## Framework-passthrough shapes Two agent kinds bypass the general shape above and emit a minimal diff --git a/docs/api-reference/task-generators.md b/docs/api-reference/task-generators.md index d0aefcdc..084cde85 100644 --- a/docs/api-reference/task-generators.md +++ b/docs/api-reference/task-generators.md @@ -62,6 +62,21 @@ const task = switchTask( ); ``` +The sixth argument selects the evaluator (default `"value-param"`). With +`"javascript"` the expression is a script. With `"decision"` the server runs +decision inference: the expression names the choice question, and the task's +`inputParameters` carry `model`, `state`, `questions`, and an optional +`provider`. See [examples/ai-decision-routing.ts](../../examples/ai-decision-routing.ts). + +```typescript +const route = switchTask("route_ref", "route", { billing: [...], technical: [...] }, [], undefined, "decision"); +route.inputParameters = { + model: "jev-1.13", + state: "${workflow.input.request}", + questions: { route: { type: "choice", instructions: "...", choices: { billing: "...", technical: "..." } } }, +}; +``` + ## Fork-Join Task _System Task_ - Executes multiple task branches in parallel and waits for all to complete. diff --git a/e2e/fixtures/fake-providers.mjs b/e2e/fixtures/fake-providers.mjs new file mode 100644 index 00000000..c09c19c8 --- /dev/null +++ b/e2e/fixtures/fake-providers.mjs @@ -0,0 +1,96 @@ +/* global process, console */ +// Deterministic stand-ins for the providers behind Jev decision SWITCHes. +// +// POST /v1/systemone — system-one decision API (conductor.ai.decision.endpoint) +// POST /v1/responses — OpenAI Responses API (conductor.ai.openai.base-url), +// only when FAKE_OPENAI=1; CI uses the real provider. +// +// Decision answers are keyword based: for each choice question, the first +// choice whose key or description shares a word stem with the state wins, +// otherwise the first choice. The fake OpenAI model calls the first function +// tool named in its instructions (or the first tool) once with +// {"state": }, then answers with text that echoes the tool +// output. Run: node e2e/fixtures/fake-providers.mjs (PORT, default 9911) +import http from "node:http"; + +const port = Number(process.env.PORT ?? 9911); +const fakeOpenAI = process.env.FAKE_OPENAI === "1"; +const stems = (s) => + new Set((String(s).toLowerCase().match(/[a-z]+/g) ?? []).filter((w) => w.length > 3).map((w) => w.slice(0, 6))); + +function decide(req) { + const state = typeof req.state === "string" ? req.state : JSON.stringify(req.state ?? ""); + const stateStems = stems(state); + const answers = {}; + for (const [name, q] of Object.entries(req.questions ?? {})) { + if (q.type === "choice") { + const keys = Object.keys(q.criteria ?? {}); + const hit = keys.find((k) => [...stems(`${k} ${q.criteria[k]}`)].some((w) => stateStems.has(w))); + answers[name] = { type: "choice", choice: hit ?? keys[0], confidence: 0.9 }; + } else if (q.type === "score") { + answers[name] = { type: "score", score: 0, confidence: 0.9 }; + } else { + answers[name] = { type: "noul", noul: 0.5, confidence: 0.9 }; + } + } + return { + id: `fake-decision-${Date.now()}`, + model: req.model, + answers, + usage: { input_tokens: 42, output_tokens: 1, cost: 0.0001 }, + }; +} + +const textOf = (content) => + typeof content === "string" ? content : (content ?? []).map((p) => p.text ?? "").join(""); + +function respond(req) { + const items = typeof req.input === "string" ? [{ type: "message", role: "user", content: req.input }] : req.input ?? []; + const userText = textOf(items.filter((i) => (i.type ?? "message") === "message" && i.role === "user").at(-1)?.content); + const toolOutputs = items.filter((i) => i.type === "function_call_output"); + const tools = (req.tools ?? []).filter((t) => t.type === "function"); + const base = { id: `fake-resp-${Date.now()}`, object: "response", model: req.model, status: "completed" }; + const usage = { input_tokens: 10, output_tokens: 5, total_tokens: 15 }; + if (tools.length > 0 && toolOutputs.length === 0) { + const tool = tools.find((t) => (req.instructions ?? "").includes(t.name)) ?? tools[0]; + const callId = `call_${Date.now()}`; + return { + ...base, + usage, + output: [{ type: "function_call", id: `fc_${callId}`, call_id: callId, name: tool.name, arguments: JSON.stringify({ state: userText }), status: "completed" }], + }; + } + const text = toolOutputs.length > 0 ? `FAKE_ANSWER tool=${toolOutputs.at(-1).output}` : `FAKE_ANSWER ${userText}`; + return { + ...base, + usage, + output_text: text, + output: [{ type: "message", id: "msg_fake", role: "assistant", status: "completed", content: [{ type: "output_text", text, annotations: [] }] }], + }; +} + +http + .createServer((req, res) => { + let body = ""; + req.on("data", (c) => (body += c)); + req.on("end", () => { + let json; + try { + json = JSON.parse(body); + } catch { + res.writeHead(400).end(); + return; + } + let out; + if (req.method === "POST" && req.url?.endsWith("/systemone")) out = decide(json); + else if (fakeOpenAI && req.method === "POST" && req.url?.endsWith("/responses")) out = respond(json); + if (!out) { + res.writeHead(404).end(); + return; + } + console.log(JSON.stringify({ path: req.url, model: json.model, out: out.answers ?? out.output?.[0]?.type })); + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify(out)); + }); + }) + .listen(port, () => console.log(`fake providers on :${port} (openai=${fakeOpenAI})`)); diff --git a/e2e/test_suite24_decision_routing.test.ts b/e2e/test_suite24_decision_routing.test.ts new file mode 100644 index 00000000..ccc9359d --- /dev/null +++ b/e2e/test_suite24_decision_routing.test.ts @@ -0,0 +1,245 @@ +/** + * Suite 24: Jev decision routing — decision-backed SWITCH, decision router, decision tool. + * + * The server must route decision inference to the deterministic fake in + * e2e/fixtures/fake-providers.mjs: + * + * node e2e/fixtures/fake-providers.mjs & + * java -jar conductor-server-boot.jar \ + * --conductor.ai.decision.endpoint=http://localhost:9911/v1/systemone \ + * --conductor.ai.decision.api-key=fake-key + * + * The fake picks the choice whose key or description shares a word stem with + * the state, so every routing assertion is exact. Chat steps (router children, + * the decision-tool agent) use the configured LLM; their text is not asserted. + */ + +import { describe, it, expect, beforeAll, afterAll, jest } from '@jest/globals'; +import { Agent, AgentRuntime } from '@io-orkes/conductor-javascript/agents'; +import type { ToolDef } from '@io-orkes/conductor-javascript/agents'; +import { ConductorWorkflow, OrkesClients, inlineTask, switchTask } from '../src/sdk'; +import type { WorkflowExecutor } from '../src/sdk'; +import type { Workflow } from '../src/open-api'; +import { checkServerHealth, MODEL, TIMEOUT, getWorkflow, expectMsg } from './helpers'; + +jest.setTimeout(900_000); + +const SUFFIX = Date.now(); +const QUESTION = { + type: 'choice', + instructions: 'Choose the team best suited to handle this request.', + choices: { + billing: 'Payments, invoices, refunds, or subscriptions.', + technical: 'Errors, outages, or product troubleshooting.', + }, +}; +const BILLING_REQUEST = 'I was charged twice on my latest invoice.'; +const TECHNICAL_REQUEST = 'The product crashes with an error on startup.'; + +type Task = NonNullable[number]; +type Def = Record; + +let runtime: AgentRuntime; +let executor: WorkflowExecutor; + +beforeAll(async () => { + if (!(await checkServerHealth())) throw new Error('Server not available'); + runtime = new AgentRuntime(); + executor = (await OrkesClients.from()).getWorkflowClient(); +}); + +afterAll(async () => { + await runtime?.shutdown(); +}); + +function routingWorkflow(name: string, provider?: string) { + const billing = inlineTask('handle_billing', '({team: "billing"})'); + const technical = inlineTask('handle_technical', '({team: "technical"})'); + const decision = switchTask('route_request', 'route', { billing: [billing], technical: [technical] }, [], undefined, 'decision'); + decision.inputParameters = { + model: 'jev-1.13', + ...(provider !== undefined && { provider }), + state: '${workflow.input.request}', + questions: { route: QUESTION }, + }; + return new ConductorWorkflow(executor, name, 1) + .add([decision]) + .outputParameters({ selectedCase: '${route_request.output.selectedCase}' }); +} + +async function runToTerminal(id: string): Promise { + const deadline = Date.now() + 120_000; + for (;;) { + const wf = await executor.getWorkflow(id, true); + if (['COMPLETED', 'FAILED', 'TIMED_OUT', 'TERMINATED'].includes(wf.status ?? '')) return wf; + if (Date.now() > deadline) throw new Error(`workflow ${id} still ${wf.status}`); + await new Promise((r) => setTimeout(r, 1000)); + } +} + +function collectTasks(tasks: unknown, out: Def[] = []): Def[] { + for (const t of (tasks as Def[] | undefined) ?? []) { + out.push(t); + collectTasks(t.loopOver, out); + collectTasks(t.defaultCase, out); + for (const branch of Object.values((t.decisionCases as Record) ?? {})) collectTasks(branch, out); + for (const fork of (t.forkTasks as unknown[][] | undefined) ?? []) collectTasks(fork, out); + } + return out; +} + +function decisionRouterAgent(name: string, provider?: string) { + const billingName = `billing_${SUFFIX}`; + const technicalName = `technical_${SUFFIX}`; + const selector: ToolDef = { + name: `selector_${SUFFIX}`, + description: 'Choose the support agent.', + toolType: 'decision', + inputSchema: { type: 'object', properties: {} }, + config: { + model: 'jev-1.13', + ...(provider !== undefined && { provider }), + questions: { + agent: { + type: 'choice', + instructions: 'Choose the right support team.', + choices: { [billingName]: 'Payments and invoices', [technicalName]: 'Product errors and troubleshooting' }, + }, + }, + }, + }; + const agent = new Agent({ + name, + strategy: 'router', + router: selector, + agents: [ + new Agent({ name: billingName, model: MODEL, instructions: 'Answer billing questions in one sentence.' }), + new Agent({ name: technicalName, model: MODEL, instructions: 'Answer technical questions in one sentence.' }), + ], + maxTurns: 1, + synthesize: false, + }); + return { agent, billingName, technicalName }; +} + +// ── Traditional workflow: decision-backed SWITCH ────────────────────── + +describe('Suite 24: decision-backed SWITCH', () => { + const name = `jssdk_e2e_decision_switch_${SUFFIX}`; + + beforeAll(async () => { + await routingWorkflow(name).register(true); + }); + + it.each([ + ['billing', BILLING_REQUEST, 'handle_billing', 'handle_technical'], + ['technical', TECHNICAL_REQUEST, 'handle_technical', 'handle_billing'], + ])('routes to %s and runs only that branch', async (expected, request, ran, skipped) => { + const id = await executor.startWorkflow({ name, version: 1, input: { request } }); + const wf = await runToTerminal(id); + expectMsg(wf.status, `workflow ${id}: ${wf.reasonForIncompletion}`).toBe('COMPLETED'); + expect(wf.output?.selectedCase).toBe(expected); + + const refs = (wf.tasks ?? []).map((t: Task) => t.referenceTaskName); + expect(refs).toContain(ran); + expect(refs).not.toContain(skipped); + + const sw = (wf.tasks ?? []).find((t: Task) => t.referenceTaskName === 'route_request'); + expect(sw?.taskType).toBe('SWITCH'); + expect(sw?.outputData).toMatchObject({ + selectedCase: expected, + model: 'jev-1.13', + answers: { route: { type: 'choice', choice: expected } }, + }); + expect(typeof sw?.outputData?.latencyMs).toBe('number'); + }); + + it('fails the workflow without retrying when the provider is not configured', async () => { + const failing = `jssdk_e2e_decision_unconfigured_${SUFFIX}`; + await routingWorkflow(failing, 'unconfigured_provider').register(true); + const id = await executor.startWorkflow({ name: failing, version: 1, input: { request: BILLING_REQUEST } }); + const wf = await runToTerminal(id); + expect(wf.status).toBe('FAILED'); + expect(wf.reasonForIncompletion ?? '').toContain('Decision'); + // Exactly one SWITCH attempt, failed, never retried; no branch scheduled. + const tasks = (wf.tasks ?? []).map((t: Task) => ({ + ref: t.referenceTaskName, + status: t.status, + retryCount: t.retryCount, + retried: t.retried, + })); + expect(tasks).toEqual([{ ref: 'route_request', status: 'FAILED', retryCount: 0, retried: false }]); + }); +}); + +// ── Agent router with a decision ToolDef selector ───────────────────── + +describe('Suite 24: decision router agent', () => { + it('compiles the selector into one decision SWITCH over the child agents', async () => { + const { agent, billingName, technicalName } = decisionRouterAgent(`jssdk_e2e_decision_router_plan_${SUFFIX}`, 'typesafe'); + const plan = (await runtime.plan(agent)) as { workflowDef?: Def }; + const tasks = collectTasks(plan.workflowDef?.tasks); + + const decisions = tasks.filter((t) => t.type === 'SWITCH' && t.evaluatorType === 'decision'); + expect(decisions).toHaveLength(1); + const [router] = decisions; + expect(router.expression).toBe('agent'); + expect(Object.keys(router.decisionCases as Def).sort()).toEqual([billingName, technicalName].sort()); + expect(router.inputParameters).toMatchObject({ model: 'jev-1.13', provider: 'typesafe' }); + + // synthesize: false — no parent synthesis LLM step after the specialist. + const finalRefs = tasks.filter((t) => String(t.taskReferenceName).endsWith('_final')); + expect(finalRefs).toHaveLength(0); + }); + + it('runs the child agent the decision selects', async () => { + const { agent, billingName, technicalName } = decisionRouterAgent(`jssdk_e2e_decision_router_${SUFFIX}`); + const result = await runtime.run(agent, BILLING_REQUEST, { timeoutSeconds: TIMEOUT / 1000 }); + expectMsg(result.status, `${result.executionId}: ${String(result.error)}`).toBe('COMPLETED'); + + const wf = (await getWorkflow(result.executionId)) as { tasks?: Def[] }; + const router = (wf.tasks ?? []).find((t) => t.taskType === 'SWITCH' && (t.outputData as Def | undefined)?.selectedCase !== undefined && String(t.referenceTaskName).includes('_router')); + expect((router?.outputData as Def | undefined)?.selectedCase).toBe(billingName); + + const children = (wf.tasks ?? []).filter((t) => t.taskType === 'SUB_WORKFLOW').map((t) => String(t.referenceTaskName)); + expect(children.some((r) => r.includes(billingName))).toBe(true); + expect(children.some((r) => r.includes(technicalName))).toBe(false); + }); +}); + +// ── Decision as a tool inside a chat agent ──────────────────────────── + +describe('Suite 24: decision tool', () => { + it('executes the tool call as a branchless decision SWITCH', async () => { + const classify: ToolDef = { + name: 'classify_request', + description: 'Classify the customer request before answering.', + toolType: 'decision', + inputSchema: { type: 'object', properties: { state: { type: 'string' } }, required: ['state'] }, + config: { model: 'jev-1.13', questions: { department: { ...QUESTION } } }, + }; + const agent = new Agent({ + name: `jssdk_e2e_decision_tool_${SUFFIX}`, + model: MODEL, + maxTurns: 3, + instructions: + 'You have one tool: classify_request. Call classify_request exactly once with the ' + + 'customer message as state, then answer in one sentence.', + tools: [classify], + }); + + // Whether a real LLM chooses to call the tool is not deterministic. Rerun only + // when the run completed without a tool call; any other failure fails at once. + let decisionCalls: Def[] = []; + for (let attempt = 1; attempt <= 3 && decisionCalls.length === 0; attempt++) { + const result = await runtime.run(agent, BILLING_REQUEST, { timeoutSeconds: TIMEOUT / 1000 }); + expectMsg(result.status, `attempt ${attempt} ${result.executionId}: ${String(result.error)}`).toBe('COMPLETED'); + const wf = (await getWorkflow(result.executionId)) as { tasks?: Def[] }; + decisionCalls = (wf.tasks ?? []).filter( + (t) => t.taskType === 'SWITCH' && ((t.outputData as Def | undefined)?.answers as Def | undefined)?.department !== undefined, + ); + } + expectMsg(decisionCalls.length, 'LLM never called classify_request in 3 runs').toBeGreaterThanOrEqual(1); + expect((decisionCalls[0].outputData as Def).selectedCase).toBe('billing'); + }); +}); diff --git a/examples/README.md b/examples/README.md index 363b3e12..02f84497 100644 --- a/examples/README.md +++ b/examples/README.md @@ -43,6 +43,7 @@ npx ts-node examples/workers-e2e.ts | **[kitchensink.ts](kitchensink.ts)** | All major task types in one workflow | `npx ts-node examples/kitchensink.ts` | | **[workflow-ops.ts](workflow-ops.ts)** | Lifecycle: start, pause, resume, terminate, restart, retry, search | `npx ts-node examples/workflow-ops.ts` | | **[test-workflows.ts](test-workflows.ts)** | Unit testing with mock task outputs (no workers needed) | `npx ts-node examples/test-workflows.ts` | +| **[ai-decision-routing.ts](ai-decision-routing.ts)** | Server-side decision SWITCH routes to inline billing/technical branches | `npx tsx examples/ai-decision-routing.ts` | ### AI Agents @@ -59,6 +60,8 @@ for the full catalog and environment setup (`CONDUCTOR_SERVER_URL`, | **[agents/04-mcp-weather.ts](agents/04-mcp-weather.ts)** | MCP tool discovery + invocation for real-time data | `npx tsx examples/agents/04-mcp-weather.ts` | | **[agents/09-human-in-the-loop.ts](agents/09-human-in-the-loop.ts)** | Agent pauses for human approval mid-run | `npx tsx examples/agents/09-human-in-the-loop.ts` | | **[agents/15-agent-discussion.ts](agents/15-agent-discussion.ts)** | Multi-turn debate between agents with opposing viewpoints | `npx tsx examples/agents/15-agent-discussion.ts` | +| **[agents/decision-router.ts](agents/decision-router.ts)** | Decision ToolDef routes to billing/technical chat agents | `npx tsx examples/agents/decision-router.ts --run` | +| **[agents/decision-tool.ts](agents/decision-tool.ts)** | Chat agent calls a branchless decision tool | `npx tsx examples/agents/decision-tool.ts` | ### Monitoring diff --git a/examples/agents/README.md b/examples/agents/README.md index f4475696..bb0c657c 100644 --- a/examples/agents/README.md +++ b/examples/agents/README.md @@ -149,6 +149,14 @@ cd examples/agents/openai && npx tsx 01-basic-agent.ts ## Basic Examples +JEV examples require a server with synchronous decision SWITCH support and a configured +decision provider (`CONDUCTOR_DECISION_PROVIDER=openrouter` when using OpenRouter). +Run [decision-router.ts](decision-router.ts) with `--run` to route to a billing or +technical chat agent, or [decision-tool.ts](decision-tool.ts) to call a decision tool +from a chat agent. Both use `CONDUCTOR_AGENT_LLM_MODEL` (default `openai/gpt-4o-mini`) +and need no JavaScript workers. [../ai-decision-routing.ts](../ai-decision-routing.ts) +demonstrates a traditional workflow with inline branches and no chat model. + | # | Example | What it demonstrates | |---|---------|---------------------| | 01 | [Basic Agent](01-basic-agent.ts) | Simplest possible agent — single LLM, no tools | diff --git a/examples/agents/decision-router.ts b/examples/agents/decision-router.ts new file mode 100644 index 00000000..3ee9a833 --- /dev/null +++ b/examples/agents/decision-router.ts @@ -0,0 +1,63 @@ +/** + * Route to billing or technical chat agents using a decision ToolDef selector. + * No JavaScript worker or parent chat model is needed. + * + * CONDUCTOR_SERVER_URL=http://localhost:8080/api CONDUCTOR_DECISION_PROVIDER=openrouter \ + * npx tsx examples/agents/decision-router.ts [--run] + * Without --run, prints the server-compiled plan without inference. + */ +import { Agent, AgentRuntime } from "@io-orkes/conductor-javascript/agents"; +import type { ToolDef } from "@io-orkes/conductor-javascript/agents"; + +function supportRouter() { + const model = process.env.CONDUCTOR_AGENT_LLM_MODEL ?? "openai/gpt-4o-mini"; + const selector: ToolDef = { + name: "support_selector", + description: "Choose the support agent that should handle the request.", + toolType: "decision", + inputSchema: { type: "object", properties: {} }, + config: { + model: "jev-1.13", + ...(process.env.CONDUCTOR_DECISION_PROVIDER !== undefined && { provider: process.env.CONDUCTOR_DECISION_PROVIDER }), + questions: { + agent: { + type: "choice", + instructions: "Choose the right support team.", + choices: { billing_javascript: "Payments and invoices", technical_javascript: "Product errors and troubleshooting" }, + }, + }, + }, + }; + return new Agent({ + name: "decision_support_router_javascript", + strategy: "router", + router: selector, + agents: [ + new Agent({ name: "billing_javascript", model, instructions: "Help the customer with billing and invoice questions." }), + new Agent({ name: "technical_javascript", model, instructions: "Help the customer troubleshoot product issues." }), + ], + maxTurns: 1, + synthesize: false, + }); +} + +async function main() { + const runtime = new AgentRuntime(); + try { + const agent = supportRouter(); + if (!process.argv.includes("--run")) { + console.log(JSON.stringify(await runtime.plan(agent), null, 2)); + return; + } + await runtime.deploy(agent); + const handle = await runtime.start(agent, "The customer reports a duplicate charge on the latest invoice.", { timeoutSeconds: 120 }); + console.log("Execution:", handle.executionId); + const result = await handle.wait(); + if (!result.isSuccess) throw new Error(`${result.status}: ${result.error}`); + console.log(JSON.stringify(result.output, null, 2)); + } finally { + await runtime.shutdown(); + } +} + +main().catch((error: unknown) => { console.error(error); process.exitCode = 1; }); diff --git a/examples/agents/decision-tool.ts b/examples/agents/decision-tool.ts new file mode 100644 index 00000000..c642fc7a --- /dev/null +++ b/examples/agents/decision-tool.ts @@ -0,0 +1,52 @@ +/** + * Use a branchless decision SWITCH as a tool inside a normal chat agent. + * The server executes both inference calls; no JavaScript worker is needed. + * + * CONDUCTOR_SERVER_URL=http://localhost:8080/api CONDUCTOR_DECISION_PROVIDER=openrouter \ + * npx tsx examples/agents/decision-tool.ts + */ +import { Agent, AgentRuntime } from "@io-orkes/conductor-javascript/agents"; +import type { ToolDef } from "@io-orkes/conductor-javascript/agents"; + +const classifyRequest: ToolDef = { + name: "classify_request", + description: "Classify the customer request before answering.", + toolType: "decision", + inputSchema: { + type: "object", + properties: { state: { type: "string" } }, + required: ["state"], + }, + config: { + model: "jev-1.13", + ...(process.env.CONDUCTOR_DECISION_PROVIDER !== undefined && { provider: process.env.CONDUCTOR_DECISION_PROVIDER }), + questions: { + department: { + type: "choice", + instructions: "Choose the correct support department.", + choices: { billing: "Payments and invoices", technical: "Product errors and troubleshooting" }, + }, + }, + }, +}; + +const supportAgent = new Agent({ + name: "decision_tool_support_javascript", + model: process.env.CONDUCTOR_AGENT_LLM_MODEL ?? "openai/gpt-4o-mini", + instructions: "Call classify_request before answering the customer.", + tools: [classifyRequest], +}); + +async function main() { + const runtime = new AgentRuntime(); + try { + const result = await runtime.run(supportAgent, "I was charged twice on my latest invoice.", { timeoutSeconds: 120 }); + if (!result.isSuccess) throw new Error(`${result.status}: ${result.error}`); + console.log("Execution:", result.executionId); + console.log(JSON.stringify(result.output, null, 2)); + } finally { + await runtime.shutdown(); + } +} + +main().catch((error: unknown) => { console.error(error); process.exitCode = 1; }); diff --git a/examples/ai-decision-routing.ts b/examples/ai-decision-routing.ts new file mode 100644 index 00000000..480fa5bf --- /dev/null +++ b/examples/ai-decision-routing.ts @@ -0,0 +1,76 @@ +/** + * Route a request with one synchronous, decision-backed SWITCH and inline branches. + * The server evaluates the decision; no JavaScript worker is needed. + * + * CONDUCTOR_SERVER_URL=http://localhost:8080/api CONDUCTOR_DECISION_PROVIDER=openrouter \ + * npx tsx examples/ai-decision-routing.ts [--request "Product crashes on startup"] + */ +import { parseArgs } from "node:util"; +import { setTimeout } from "node:timers/promises"; +import { ConductorWorkflow, OrkesClients, inlineTask, switchTask } from "../src/sdk"; +import type { WorkflowExecutor } from "../src/sdk"; + +function createWorkflow(executor: WorkflowExecutor, model = "jev-1.13", provider?: string) { + const billing = inlineTask("handle_billing", '({team: "billing", nextAction: "review_invoice", message: "Check invoice line items and payment records.", request: $.request})'); + billing.inputParameters.request = "${workflow.input.request}"; + const technical = inlineTask("handle_technical", '({team: "technical", nextAction: "collect_diagnostics", message: "Collect error logs and steps to reproduce.", request: $.request})'); + technical.inputParameters.request = "${workflow.input.request}"; + + // "decision" evaluator: the expression names the choice question to route on. + const decision = switchTask("route_request", "route", { billing: [billing], technical: [technical] }, [], undefined, "decision"); + decision.inputParameters = { + model, + ...(provider !== undefined && { provider }), + state: "${workflow.input.request}", + questions: { + route: { + type: "choice", + instructions: "Choose the team best suited to handle this request.", + choices: { + billing: "Payments, invoices, refunds, or subscriptions.", + technical: "Errors, outages, or product troubleshooting.", + }, + }, + }, + }; + const result = inlineTask("selected_result", "$.billing || $.technical"); + result.inputParameters.billing = "${handle_billing.output.result}"; + result.inputParameters.technical = "${handle_technical.output.result}"; + return new ConductorWorkflow(executor, "ai_decision_routing_javascript", 1) + .add([decision, result]) + .outputParameters({ + selectedCase: "${route_request.output.selectedCase}", + answers: "${route_request.output.answers}", + usage: "${route_request.output.usage}", + cost: "${route_request.output.usage.cost}", + latencyMs: "${route_request.output.latencyMs}", + result: "${selected_result.output.result}", + }); +} + +async function main() { + const { values } = parseArgs({ options: { + request: { type: "string", default: "I was charged twice on my latest invoice." }, + model: { type: "string", default: "jev-1.13" }, + provider: { type: "string", default: process.env.CONDUCTOR_DECISION_PROVIDER }, + } }); + const clients = await OrkesClients.from(); + const executor = clients.getWorkflowClient(); + const workflow = createWorkflow(executor, values.model, values.provider); + await workflow.register(true); + const id = await workflow.startWorkflow({ request: values.request }); + console.log("Workflow:", id); + const deadline = Date.now() + 120_000; + while (Date.now() < deadline) { + const run = await executor.getWorkflow(id, false); + if (["COMPLETED", "FAILED", "TIMED_OUT", "TERMINATED"].includes(run.status ?? "")) { + if (run.status !== "COMPLETED") throw new Error(`${run.status}: ${run.reasonForIncompletion}`); + console.log(JSON.stringify(run.output, null, 2)); + return; + } + await setTimeout(1000); + } + throw new Error(`Timed out waiting for workflow ${id}`); +} + +main().catch((error: unknown) => { console.error(error); process.exitCode = 1; }); diff --git a/src/agents/__tests__/serializer.test.ts b/src/agents/__tests__/serializer.test.ts index 405ba843..285e49bb 100644 --- a/src/agents/__tests__/serializer.test.ts +++ b/src/agents/__tests__/serializer.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect } from "@jest/globals"; import { z } from "zod"; import { AgentConfigSerializer } from "../serializer.js"; import { Agent, PromptTemplate, scatterGather } from "../agent.js"; +import type { ToolDef } from "../types.js"; import type { CallbackHandler, TerminationCondition, HandoffCondition } from "../agent.js"; import { tool, @@ -17,6 +18,66 @@ import { const serializer = new AgentConfigSerializer(); +describe("decision tools", () => { + const selector: ToolDef = { + name: "support_selector", + description: "Choose a team", + toolType: "decision", + inputSchema: { type: "object" }, + config: { model: "jev-1.13", questions: { agent: { type: "choice", choices: { billing: "Invoices" } } } }, + }; + const routed = (router: ToolDef) => new Agent({ + name: "support", + strategy: "router", + router, + agents: [new Agent({ name: "billing", model: "openai/gpt-4o-mini" })], + synthesize: false, + }); + + it("serializes a model-less decision router without a worker or implicit provider", () => { + const config = serializer.serializeAgent(routed(selector)); + expect(config.router).toEqual({ name: selector.name, kind: "decision", ...selector.config }); + expect(config.external).toBe(false); + expect(config.synthesize).toBe(false); + expect(config).not.toHaveProperty("model"); + expect(config.router).not.toHaveProperty("provider"); + expect(config.router).not.toHaveProperty("taskName"); + expect(serializer.serializeAgent(new Agent({ name: "chat" }))).not.toHaveProperty("synthesize"); + }); + + it("preserves an explicit provider and ordinary decision tool configuration", () => { + const withProvider = { ...selector, config: { ...selector.config, provider: "openrouter" } }; + expect(serializer.serializeAgent(routed(withProvider)).router).toMatchObject({ provider: "openrouter" }); + const config = serializer.serializeAgent(new Agent({ name: "chat", tools: [withProvider] })); + expect(config.tools).toEqual([{ + name: selector.name, description: selector.description, inputSchema: selector.inputSchema, + toolType: "decision", config: withProvider.config, + }]); + }); + + const choice = (choices: Record, type = "choice") => ({ type, instructions: "Pick", choices }); + + it.each([ + [{ ...selector, toolType: "http" }, "got toolType 'http'"], + [{ ...selector, toolType: undefined }, "got an object without toolType"], + [{ ...selector, config: { questions: { agent: {} } } }, "requires 'model'"], + [{ ...selector, config: { model: "jev-1.13", questions: {} } }, "requires 'questions'"], + // choice keys must be exactly the sub-agent names + [{ ...selector, config: { model: "jev-1.13", questions: { agent: choice({ invoices: "Invoices" }) } } }, "found 0"], + [{ ...selector, config: { model: "jev-1.13", questions: { agent: choice({ billing: "A", extra: "B" }) } } }, "found 0"], + [{ ...selector, config: { model: "jev-1.13", questions: { agent: choice({ billing: "A" }, "score") } } }, "found 0"], + [{ ...selector, config: { model: "jev-1.13", questions: { a: choice({ billing: "A" }), b: choice({ billing: "B" }) } } }, "found 2"], + ])("rejects an invalid router configuration (%#)", (router, message) => { + expect(() => serializer.serializeAgent(routed(router as ToolDef))).toThrow(message as string); + }); + + it("accepts extra non-routing questions next to the routing choice question", () => { + const questions = { agent: choice({ billing: "A" }), urgent: { type: "boolean", instructions: "Urgent?" } }; + const router = { ...selector, config: { model: "jev-1.13", questions } }; + expect(serializer.serializeAgent(routed(router)).router).toMatchObject({ questions }); + }); +}); + // ── serialize() — full payload ───────────────────────────── describe("AgentConfigSerializer.serialize()", () => { diff --git a/src/agents/agent.ts b/src/agents/agent.ts index 5c8d20cc..0f0f16e5 100644 --- a/src/agents/agent.ts +++ b/src/agents/agent.ts @@ -1,4 +1,4 @@ -import type { Strategy, CodeExecutionConfig, CliConfig, PrefillToolCall } from "./types.js"; +import type { Strategy, CodeExecutionConfig, CliConfig, PrefillToolCall, ToolDef } from "./types.js"; import { agentTool } from "./tool.js"; import { ConfigurationError } from "./errors.js"; import { ClaudeCode } from "./claude-code.js"; @@ -94,7 +94,9 @@ export interface AgentOptions { tools?: unknown[]; // Normalized via normalizeToolInput at serialization agents?: Agent[]; strategy?: Strategy; - router?: Agent | ((...args: unknown[]) => string); + router?: Agent | ToolDef | ((...args: unknown[]) => string); + /** Append an LLM synthesis step after specialist agents complete (default true). */ + synthesize?: boolean; outputType?: unknown; // ZodSchema or JSON Schema object guardrails?: unknown[]; memory?: ConversationMemory; @@ -204,7 +206,8 @@ export class Agent { readonly tools: unknown[]; readonly agents: Agent[]; readonly strategy?: Strategy; - readonly router?: Agent | ((...args: unknown[]) => string); + readonly router?: Agent | ToolDef | ((...args: unknown[]) => string); + readonly synthesize: boolean; readonly outputType?: unknown; readonly guardrails: unknown[]; readonly memory?: ConversationMemory; @@ -274,6 +277,7 @@ export class Agent { this.agents = options.agents ?? []; this.strategy = options.strategy; this.router = options.router; + this.synthesize = options.synthesize ?? true; this.outputType = options.outputType; this.guardrails = options.guardrails ?? []; this.memory = options.memory; @@ -381,7 +385,7 @@ export class Agent { if (this.strategy === "router" && !this.router) { throw new ConfigurationError( `Agent '${this.name}' uses strategy='router' but no 'router' parameter was provided. ` + - `Provide an Agent or function as the router.`, + `Provide an Agent, decision ToolDef, or function as the router.`, ); } diff --git a/src/agents/serializer.ts b/src/agents/serializer.ts index 801f8962..6b763b62 100644 --- a/src/agents/serializer.ts +++ b/src/agents/serializer.ts @@ -9,6 +9,7 @@ import type { } from "./agent.js"; import { normalizeToolInput, isZodSchema } from "./tool.js"; import type { ToolDef } from "./types.js"; +import { ConfigurationError } from "./errors.js"; // ── Wire format types ───────────────────────────────────── @@ -166,7 +167,11 @@ export class AgentConfigSerializer { // Router if (agent.router !== undefined && agent.router !== null) { - config.router = this.serializeRouter(agent.router, agent.name); + config.router = this.serializeRouter( + agent.router, + agent.name, + agent.agents.map((child) => child.name), + ); } // Output type @@ -195,6 +200,7 @@ export class AgentConfigSerializer { if (agent.reasoningEffort !== undefined) config.reasoningEffort = agent.reasoningEffort; config.timeoutSeconds = agent.timeoutSeconds; config.external = agent.external; + if (!agent.synthesize) config.synthesize = false; if (agent.stateful) config.stateful = true; // stopWhen @@ -465,8 +471,9 @@ export class AgentConfigSerializer { } private serializeRouter( - router: Agent | ((...args: unknown[]) => string), + router: Agent | ToolDef | ((...args: unknown[]) => string), agentName: string, + childNames: string[], ): unknown { if (router instanceof Agent) { return this.serializeAgent(router); @@ -474,7 +481,44 @@ export class AgentConfigSerializer { if (typeof router === "function") { return { taskName: `${agentName}_router_fn` }; } - return router; + if (router.toolType !== "decision") { + const received = router.toolType === undefined ? "an object without toolType" : `toolType '${router.toolType}'`; + throw new ConfigurationError( + `Only a decision ToolDef can be used as a router (agent '${agentName}' got ${received}). ` + + `Use an Agent, a function, or a ToolDef with toolType 'decision'.`, + ); + } + const config = router.config; + if (!config?.model) { + throw new ConfigurationError("Decision router tool config requires 'model'"); + } + if (!config.questions || Object.keys(config.questions).length === 0) { + throw new ConfigurationError("Decision router tool config requires 'questions'"); + } + // Same rule the server enforces at compile time: exactly one choice question + // whose choice keys are the sub-agent names. + const expected = [...new Set(childNames)].sort(); + const matching = Object.values(config.questions as Record).filter((q) => { + const question = q as { type?: unknown; choices?: unknown } | null; + if (question?.type !== "choice" || typeof question.choices !== "object" || question.choices === null) { + return false; + } + const keys = Object.keys(question.choices).sort(); + return keys.length === expected.length && keys.every((k, i) => k === expected[i]); + }); + if (matching.length !== 1) { + throw new ConfigurationError( + `Decision router '${router.name}' requires exactly one choice question whose choices ` + + `are the sub-agent names [${expected.join(", ")}]; found ${matching.length}`, + ); + } + return { + name: router.name, + kind: "decision", + model: config.model, + questions: config.questions, + ...(config.provider != null && { provider: config.provider }), + }; } private serializeMemory(memory: ConversationMemory): Record { diff --git a/src/agents/types.ts b/src/agents/types.ts index d19e108d..3078e856 100644 --- a/src/agents/types.ts +++ b/src/agents/types.ts @@ -91,6 +91,7 @@ export interface GuardrailDef { */ export type ToolType = | "worker" + | "decision" | "http" | "api" | "mcp" diff --git a/src/open-api/types.ts b/src/open-api/types.ts index 4248b437..e26e5958 100644 --- a/src/open-api/types.ts +++ b/src/open-api/types.ts @@ -236,7 +236,7 @@ export interface SwitchTaskDef extends CommonTaskDef { type: TaskType.SWITCH; decisionCases: Record; defaultCase: TaskDefTypes[]; - evaluatorType: "value-param" | "javascript"; + evaluatorType: "value-param" | "javascript" | "decision"; expression: string; optional?: boolean; } diff --git a/src/sdk/builders/tasks/__tests__/factory.test.ts b/src/sdk/builders/tasks/__tests__/factory.test.ts index fffbb6b4..d8eebb4c 100644 --- a/src/sdk/builders/tasks/__tests__/factory.test.ts +++ b/src/sdk/builders/tasks/__tests__/factory.test.ts @@ -325,6 +325,26 @@ describe("switchTask", () => { type: "SWITCH", }); }); + + it("passes the expression through for a decision evaluator", () => { + const task = switchTask("route", "team", { billing: [], technical: [] }, [], undefined, "decision"); + expect(task).toMatchObject({ + evaluatorType: "decision", + expression: "team", + inputParameters: {}, + decisionCases: { billing: [], technical: [] }, + type: "SWITCH", + }); + }); + + it("passes the script through for a javascript evaluator", () => { + const task = switchTask("route", "$.tier === 'gold' ? 'vip' : 'std'", {}, [], undefined, "javascript"); + expect(task).toMatchObject({ + evaluatorType: "javascript", + expression: "$.tier === 'gold' ? 'vip' : 'std'", + inputParameters: {}, + }); + }); }); describe("terminateTask", () => { diff --git a/src/sdk/builders/tasks/switch.ts b/src/sdk/builders/tasks/switch.ts index 3c904638..ba324a55 100644 --- a/src/sdk/builders/tasks/switch.ts +++ b/src/sdk/builders/tasks/switch.ts @@ -1,20 +1,27 @@ import { TaskType, SwitchTaskDef, TaskDefTypes } from "../../../open-api"; +/** + * With the default `"value-param"` evaluator, `expression` is the value to + * switch on. With any other evaluator, `expression` is passed through as-is: + * a script for `"javascript"`, or the choice question name for `"decision"` + * (set the decision inputs — `model`, `state`, `questions`, optional + * `provider` — on `inputParameters`). + */ export const switchTask = ( taskReferenceName: string, expression: string, decisionCases: Record = {}, defaultCase: TaskDefTypes[] = [], - optional?: boolean + optional?: boolean, + evaluatorType: SwitchTaskDef["evaluatorType"] = "value-param" ): SwitchTaskDef => ({ name: taskReferenceName, taskReferenceName, decisionCases, - evaluatorType: "value-param", - inputParameters: { - switchCaseValue: expression, - }, - expression: "switchCaseValue", + evaluatorType, + inputParameters: + evaluatorType === "value-param" ? { switchCaseValue: expression } : {}, + expression: evaluatorType === "value-param" ? "switchCaseValue" : expression, defaultCase, type: TaskType.SWITCH, optional,