import { afterEach, expect, test } from 'bun:test'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { z } from 'zod'; import { agentTool, runAgentTask } from '../../../src/tools/agent/agent.js'; import { askUserQuestionTool } from '../../../src/tools/ask/ask.js'; import { skillTool } from '../../../src/tools/skill/skill.js'; import { withAskHandler } from '../../../src/askBridge.js'; import type { LoopEvent, Tool } from '../../../src/plugin-sdk.js'; import { createWorkflowContext, ExecutionScope, } from '../src/runtime/context.js'; import { WorkflowModelError, ModelExecutionOutcome } from '../src/runtime/model.js'; import { WorkflowScheduler } from '../src/runtime/scheduler.js'; import { readWorkflowRuntimeConfig } from '../src/runtime/config.js'; import { Journal } from '../src/journal.js'; import { WorkflowState } from '../src/workflowState.js'; import type { RunContext } from '../src/types.js'; const dirs: string[] = []; test('nonterminal compression diagnostic does not mask a subsequent normal completion', () => { const outcome = new ModelExecutionOutcome(); outcome.observe({ type: 'error', code: 'compact_failed', error: 'continuing without compression' }); expect(() => outcome.assertSuccess('partial', [], [])).toThrow('正常结束'); outcome.observe({ type: 'turn_done' }); expect(() => outcome.assertSuccess('completed', [], [])).not.toThrow(); outcome.observe({ type: 'error', code: 'llm_error', error: 'provider unavailable' }); expect(() => outcome.assertSuccess('completed', [], [])).toThrow('provider unavailable'); }); afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); }); const tools: Tool[] = [ 'Read', 'Bash', 'Write', 'Skill', 'Advisor', 'PresentResult', 'AskUserQuestion', ].map((name) => ({ name, description: name, inputSchema: z.object({}).passthrough(), parameters: { type: 'object', properties: {} }, isReadOnly: !['Bash', 'Write'].includes(name), call: async () => ({ ok: true, content: 'ok' }), })); tools.push(agentTool); test('real Agent child shares single-slot pools without deadlocking parent', async () => { const scheduler = new WorkflowScheduler({ ...readWorkflowRuntimeConfig({}), modelConcurrency: 1, toolConcurrency: 1 }); const scope = new ExecutionScope(scheduler); let reads = 0; const h = await harness(async function* ({ messages }) { if (messages.some(m => m.role === 'tool')) { yield { type: 'text_delta', delta: 'done' }; yield { type: 'done', stopReason: 'stop' }; return; } const child = messages.some(m => m.role === 'user' && String(m.content).includes('child-task')); yield { type: 'tool_call_delta', index: 0, id: child ? 'read' : 'delegate', name: child ? 'Read' : 'Agent', argumentsDelta: JSON.stringify(child ? { file_path: 'a.ts' } : { description: 'child', prompt: 'child-task' }) }; yield { type: 'done', stopReason: 'tool_calls' }; }, async (name, input, signal, context) => { if (name === 'Agent') return runAgentTask(JSON.parse(input), signal, context!); reads++; return { ok: true, content: 'file content' }; }, scope); // The child inherits the parent's catalog ceiling, including Read. await expect(h.wf.model.agent('parent-task', { timeoutMs: 3000, allowedTools: ['Agent', 'Read'], isolated: true })).resolves.toBe('done'); expect(reads).toBe(1); expect(scope.agentToolCalls).toBe(2); await h.state.flush(); }); async function harness( chat: RunContext['chat'], executeTool?: RunContext['executeTool'], scope?: ExecutionScope, toolGate?: NonNullable['toolGate']>, ) { const cwd = await mkdtemp(join(tmpdir(), 'wf-embedded-')); dirs.push(cwd); const state = new WorkflowState(cwd, 'fixture', 'session'); await state.init({}, 'test', []); const journal = new Journal(state.journalPath, { bundleHash: 'test', rootRunId: 'root', }); await journal.load(); const events: LoopEvent[] = []; const ctx = { cwd, provider: { name: 'fixture', model: 'fixture', contextWindow: 100000 }, history: [{ role: 'system', content: 'sys' }], tools, chat, executeTool: executeTool ?? (async () => ({ ok: true, content: 'ok' })), ...(toolGate ? { host: { toolGate } } : {}), } as RunContext; const wf = createWorkflowContext({ ctx, state, journal, scope, emit: (e) => events.push(e), args: {}, workflowName: 'fixture', session: 'session', task: state.taskId, }); return { wf, events, state, journal, ctx }; } test.each(['agent', 'generate'] as const)('%s rejects EOF text and cannot replay it as a successful node', async method => { let calls = 0; const h = await harness(async function* () { calls++; yield { type: 'text_delta', delta: 'partial report' }; // Deliberately no terminal event: the provider disconnected. }); try { for (let attempt = 0; attempt < 2; attempt++) await expect(h.wf.model[method]('inspect', { isolated: true })).rejects.toBeInstanceOf(WorkflowModelError); expect(calls).toBe(2); } finally { await h.state.flush(); } }); test('TAOR: earlier prose cannot mask a later model failure; script may recover', async () => { let calls = 0; const h = await harness(async function* () { calls++; if (calls === 1) { yield { type: 'text_delta', delta: '准备处理' }; yield { type: 'tool_call_delta', index: 0, id: 'read', name: 'Read', argumentsDelta: '{}', }; yield { type: 'done', stopReason: 'tool_calls' }; } else if (calls === 2) throw new Error('provider failed after tool'); else { yield { type: 'text_delta', delta: 'recovered' }; yield { type: 'done', stopReason: 'stop' }; } }); let failure: unknown; try { await h.wf.model.agent('inspect', { isolated: true, allowedTools: ['Read'], }); } catch (error) { failure = error; } expect(failure).toBeInstanceOf(WorkflowModelError); expect((failure as WorkflowModelError).recovery.partialText).toContain( '准备处理', ); expect((failure as WorkflowModelError).recovery.toolNames).toEqual(['Read']); expect((failure as WorkflowModelError).recovery.toolResults).toEqual([ { name: 'Read', ok: true, content: 'ok' }, ]); expect( h.events.some((e) => e.type === 'error' || e.type === 'turn_done'), ).toBe(false); expect(await h.wf.model.generate('recover', { isolated: true })).toBe( 'recovered', ); await h.state.flush(); }); test('embedded tools exclude outer delivery/advisor/ask, preserve explicitly requested tool', async () => { let calls = 0; const h = await harness(async function* (options) { calls++; const names = options.tools?.map((t) => t.name) ?? []; expect(names).toContain('Read'); for (const name of [ 'Advisor', 'PresentResult', 'AskUserQuestion', ]) expect(names).not.toContain(name); yield { type: 'text_delta', delta: 'stage result' }; yield { type: 'done', stopReason: 'stop' }; }); expect( await h.wf.model.agent('生成文件并交付', { allowedTools: [ 'Read', 'Advisor', 'PresentResult', 'AskUserQuestion', ], isolated: true, }), ).toBe('stage result'); expect(calls).toBe(1); await h.state.flush(); }); test('同一工作流执行实例内重复的 AskUserQuestion 复用首次回答', async () => { let askExecutions = 0; const h = await harness(async function* () { yield { type: 'text_delta', delta: 'unused' }; yield { type: 'done', stopReason: 'stop' }; }, async (name) => { if (name === 'AskUserQuestion') { askExecutions++; return { ok: true, content: '用户已回答 AskUserQuestion:\nA1: 清理' }; } return { ok: true, content: 'ok' }; }); const input = { questions: [{ question: '是否清理旧表?', header: '数据库', options: [ { label: '清理', description: '删除旧表数据' }, { label: '保留', description: '保留现有数据' }, ], }], }; await expect(h.wf.tools.call('AskUserQuestion', input)).resolves.toContain('清理'); await expect(h.wf.tools.call('AskUserQuestion', input)).resolves.toContain('清理'); expect(askExecutions).toBe(1); await h.state.flush(); }); test('script calls cannot widen host catalog, replay a revoked ask, or bypass the host gate', async () => { let calls = 0; const h = await harness(undefined, async () => { calls++; return {ok:true, content:'unused'}; }, undefined, async () => ({allow:false, reason:'owner denied'})); const call = () => h.wf.tools.call('Read', {file_path:'a'}); await expect(call()).rejects.toThrow('owner denied'); await expect(h.wf.flow.ask('question', [])).rejects.toThrow('owner denied'); h.ctx.tools = []; await expect(call()).rejects.toThrow('未授权'); await expect(h.wf.flow.ask('question', [])).rejects.toThrow('未授权'); await expect(h.wf.exec.shell('dummy')).rejects.toThrow('未授权'); expect(calls).toBe(0); await h.state.flush(); }); test('flow.ask uses the offered tool and preserves the entire answer; no host reply is not a decision', async () => { const h = await harness(undefined); h.ctx.tools = [askUserQuestionTool]; h.ctx.executeTool = undefined; const question = 'first line\nA1: part of the question'; const answer = 'first line\nA1: part of the answer\n final line'; await expect(h.wf.flow.ask(question, [])).rejects.toThrow('interaction_unavailable'); let calls = 0; await withAskHandler(async qs => { calls++; return [{header:qs[0]!.header,question:qs[0]!.question,selected:[answer]}]; }, async () => { expect(await h.wf.flow.ask(question, [])).toBe(answer); expect(await h.wf.flow.ask(question, [])).toBe(answer); h.ctx.tools = []; await expect(h.wf.flow.ask(question, [])).rejects.toThrow('未授权'); }); expect(calls).toBe(1); await h.state.flush(); }); test('read-only node hides write tools and rejects fabricated Write plus mutating Bash', async () => { let round = 0; const executed: string[] = []; let hostGateCalls = 0; const h = await harness( async function* ({ messages, tools: requestTools }) { if (round++ === 0) { const names = requestTools?.map((tool) => tool.name) ?? []; expect(names).toContain('Read'); expect(names).not.toContain('Bash'); expect(names).not.toContain('Write'); expect(JSON.stringify(messages)).toContain('工作流节点工具边界'); expect(JSON.stringify(messages)).toContain('本节点严格只读'); yield { type: 'tool_call_delta', index: 0, id: 'mutating-shell', name: 'Bash', argumentsDelta: JSON.stringify({ command: 'mkdir -p generated' }), }; // Providers can still fabricate a known tool not included in this schema. yield { type: 'tool_call_delta', index: 1, id: 'fabricated-write', name: 'Write', argumentsDelta: JSON.stringify({ file_path: 'generated/file.ts', content: 'unsafe', }), }; yield { type: 'done', stopReason: 'tool_calls' }; return; } const transcript = JSON.stringify(messages); expect(transcript).toContain('不在当前工作流节点的有效工具集中'); yield { type: 'text_delta', delta: '只读调查完成' }; yield { type: 'done', stopReason: 'stop' }; }, async (name) => { executed.push(name); return { ok: true, content: 'unexpected execution' }; }, undefined, async () => { hostGateCalls++; return { allow: true }; }, ); await expect( h.wf.model.agent('只读调查', { allowedTools: ['Read', 'Bash', 'Write'], toolMode: 'read-only', isolated: true, }), ).resolves.toBe('只读调查完成'); expect(executed).toEqual([]); expect(hostGateCalls).toBe(0); expect( h.events.some( (event) => event.type === 'warning' && String(event.message).includes('已移除写工具:Bash、Write'), ), ).toBe(true); await h.state.flush(); }); test('strict read-only node rejects even apparently read-only shell commands', async () => { let round = 0; const executed: string[] = []; const gateRequests: { name: string; isReadOnly: boolean }[] = []; const h = await harness( async function* () { if (round++ === 0) { yield { type: 'tool_call_delta', index: 0, id: 'git-status', name: 'Bash', argumentsDelta: JSON.stringify({ command: 'git status --short' }), }; yield { type: 'done', stopReason: 'tool_calls' }; return; } yield { type: 'text_delta', delta: 'done' }; yield { type: 'done', stopReason: 'stop' }; }, async (name) => { executed.push(name); return { ok: true, content: 'clean' }; }, undefined, async (request) => { gateRequests.push({ name: request.name, isReadOnly: request.isReadOnly }); return { allow: true }; }, ); await expect( h.wf.model.agent('检查状态', { allowedTools: ['Bash'], toolMode: 'read-only', isolated: true, }), ).resolves.toBe('done'); expect(executed).toEqual([]); expect(gateRequests).toEqual([]); await h.state.flush(); }); test('parallel TAOR nodes share tool and process pools, not just outer model slots', async () => { const scheduler = new WorkflowScheduler({ ...readWorkflowRuntimeConfig({}), toolConcurrency: 1, processConcurrency: 1, }); const scope = new ExecutionScope(scheduler); const active: Record = { Read: 0, Bash: 0 }; const peak: Record = { Read: 0, Bash: 0 }; const h = await harness( async function* ({ messages }) { if (messages.some((m) => m.role === 'tool')) { yield { type: 'text_delta', delta: 'done' }; yield { type: 'done', stopReason: 'stop' }; } else { yield { type: 'tool_call_delta', index: 0, id: 'read', name: 'Read', argumentsDelta: '{}', }; yield { type: 'tool_call_delta', index: 1, id: 'bash', name: 'Bash', argumentsDelta: '{}', }; yield { type: 'done', stopReason: 'tool_calls' }; } }, async (name) => { active[name]++; peak[name] = Math.max(peak[name], active[name]); try { await new Promise((r) => setTimeout(r, 20)); return { ok: true, content: 'ok' }; } finally { active[name]--; } }, scope, ); const batch = await h.wf.flow.pipeline([1, 2, 3], { concurrency: 3, stages: [ async () => h.wf.model.agent('inspect', { isolated: true, allowedTools: ['Read', 'Bash'], }), ], }); expect(batch.succeeded).toBe(3); expect(peak).toEqual({ Read: 1, Bash: 1 }); expect(scope.agentToolCalls).toBe(6); await h.state.flush(); }); test('skill loads actual complete instructions for every isolated node', async () => { let loads = 0; const h = await harness( async function* (messages) { expect(JSON.stringify(messages)).toContain('USE_EXISTING_SCRIPT'); yield { type: 'text_delta', delta: 'done' }; yield { type: 'done', stopReason: 'stop' }; }, async (name, args) => { expect(name).toBe('Skill'); expect(JSON.parse(args).name).toBe('fixture'); loads++; return { ok: true, content: 'Skill: fixture\nRoot: /fixture\nUSE_EXISTING_SCRIPT', }; }, ); await h.wf.model.skill('fixture', 'first', { isolated: true }); await h.wf.model.skill('fixture', 'second', { isolated: true }); expect(loads).toBe(2); await h.state.flush(); }); test('workflow explicitly loads a bundled compatibility skill outside the default catalog', async () => { const h = await harness(async function* ({ messages }) { expect(JSON.stringify(messages)).toContain('这是旧帮助入口'); yield { type: 'text_delta', delta: 'done' }; yield { type: 'done', stopReason: 'stop' }; }, async (name, raw, signal, context) => { expect(name).toBe('Skill'); return skillTool.callWithContext!(skillTool.inputSchema.parse(JSON.parse(raw)), signal, { ...context, surface: 'workflow', }); }); await expect(h.wf.model.skill('compact', '解释压缩用法', { isolated: true })).resolves.toBe('done'); await h.state.flush(); }); test('missing skill stops before model improvises a replacement', async () => { let calls = 0; const h = await harness( async function* () { calls++; yield { type: 'text_delta', delta: 'wrong' }; }, async () => ({ ok: false, error: 'not installed' }), ); await expect(h.wf.model.skill('absent', 'task')).rejects.toThrow( 'not installed', ); expect(calls).toBe(0); await h.state.flush(); }); test('Skill queue counts toward deadline without consuming model capacity', async () => { const scheduler = new WorkflowScheduler({ ...readWorkflowRuntimeConfig({}), toolConcurrency: 1, modelConcurrency: 1 }); const scope = new ExecutionScope(scheduler); const occupied = await scheduler.acquire('tool', 'other'); let loads = 0; const h = await harness(async function* () {}, async () => { loads++; return { ok: true, content: 'instructions' }; }, scope); try { await expect(h.wf.model.skill('fixture', 'task', { timeoutMs: 30 })) .rejects.toMatchObject({ code: 'step_timeout' }); expect(loads).toBe(0); const model = await scheduler.acquire('model', 'probe', AbortSignal.timeout(100)); model.release(); } finally { occupied.release(); } await h.state.flush(); }); test('Skill preparation consumes node deadline and cannot start a late model', async () => { let modelCalls = 0; let loadSignal: AbortSignal | undefined; const h = await harness(async function* () { modelCalls++; yield { type: 'text_delta', delta: 'unexpected' }; }, async (_name, _input, signal) => { loadSignal = signal; await new Promise(resolve => setTimeout(resolve, 180)); return { ok: true, content: 'instructions' }; }); const start = Date.now(); await expect(h.wf.model.skill('fixture', 'task', { timeoutMs: 30 })) .rejects.toMatchObject({ name: 'WorkflowModelError', code: 'step_timeout' }); expect(Date.now() - start).toBeLessThan(150); expect(loadSignal?.aborted).toBe(true); await new Promise(resolve => setTimeout(resolve, 220)); expect(modelCalls).toBe(0); await h.state.flush(); }); test('node deadline is a recoverable failure with evidence, not user cancellation', async () => { const h = await harness(async function* ({ signal }) { yield { type: 'text_delta', delta: 'in progress' }; await new Promise((resolve) => signal!.addEventListener('abort', () => resolve(), { once: true }), ); signal!.throwIfAborted(); }); await expect( h.wf.model.agent('slow', { isolated: true, timeoutMs: 50 }), ).rejects.toMatchObject({ name: 'WorkflowModelError', code: 'step_timeout' }); await h.state.flush(); });