import { describe, expect, it } from 'vitest' import { Context } from 'cordis' import LlmService, { CallId, StreamChunk } from '@deepseek-ai/dsh-llm' import SessionStore, { SessionId, TurnEndReason } from '@deepseek-ai/dsh-session' import SystemPrompt from '@deepseek-ai/dsh-system-prompt' import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools' import AgentRegistry, { type Agent } from '@deepseek-ai/dsh-agent' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import { MockAdapter, maxTokensResponse, textResponse, toolCallResponse } from './mock-adapter.ts' function driverDone(agent: Agent): Promise { return (agent as Agent & { done: Promise }).done } async function harness(adapter: MockAdapter, persona = '') { const ctx = new Context() await ctx.plugin(LlmService) await ctx.plugin(SessionStore) await ctx.plugin(SystemPrompt, { persona }) await ctx.plugin(ToolRegistry) await ctx.plugin(AgentRegistry) await ctx.plugin(AgentLoop, { agents: [] }) ctx.llm.registerAdapter(['mock'], adapter) return ctx } /** * Wait for the agent's NEXT transition to idle. Always event-based: callers * invoke this right after send(), when the loop hasn't woken yet (status is * still 'idle' synchronously), so polling the current status would lie. */ function waitForIdle(ctx: Context, agent: Agent): Promise { return new Promise((resolve) => { const dispose = ctx.on('agent/status', (subject, status) => { if (subject === agent && status === 'idle') { dispose() resolve() } }) }) } function send(agent: Agent, text: string) { agent.send([{ type: 'text', text }]) } describe('agent loop', () => { it('runs a simple turn: queued message → model → idle, with ordered events', async () => { const adapter = new MockAdapter([textResponse('hello there')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) // All boundaries — turn and step — are durable session events on the // session/event feed (no agent/* mirror). Record them in fire order to // assert the full boundary nesting. const order: string[] = [] ctx.on('session/event', (_session, event) => { if (event.type === 'turn/start' || event.type === 'step/start' || event.type === 'step/end' || event.type === 'turn/end') { order.push(event.type) } }) send(agent, 'hi') await waitForIdle(ctx, agent) expect(order).toEqual(['turn/start', 'step/start', 'step/end', 'turn/end']) const types = agent.session.events.map(e => e.type) // turn/start opens the turn, THEN the queued user message is recorded inside // it (every event is turn-enclosed), then the assembled message (carrying the // step's usage). expect(types[0]).toBe('turn/start') expect(types[1]).toBe('user/message') expect(types).toContain('assistant/message') const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message') expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data.usage).toEqual({ inputTokens: 10, outputTokens: 'hello there'.length }) expect(types.at(-1)).toBe('turn/end') // derived history: user + assistant const messages = agent.session.deriveMessages() expect(messages.map(m => m.role)).toEqual(['user', 'assistant']) expect(messages[1]!.content).toEqual([{ type: 'text', text: 'hello there' }]) }) it('round-trips tool calls: model requests tool → executes → result in next request', async () => { const adapter = new MockAdapter([ toolCallResponse('c1', 'echo', { text: 'ping' }, 'calling echo'), textResponse('done'), ]) const ctx = await harness(adapter) ctx.tools.register(defineTool({ name: 'echo', description: 'echo back', parameters: { text: { type: 'string' } }, async execute(args) { return [{ type: 'text', text: `echo: ${args.text}` }] }, })) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) send(agent, 'use the tool') await waitForIdle(ctx, agent) // two model calls happened (tool-call step, then final step) expect(adapter.requests).toHaveLength(2) // the second request's derived history contains the tool result const secondMessages = adapter.requests[1]!.messages const toolResultMessage = secondMessages.find(m => m.content.some(b => b.type === 'tool-result')) expect(toolResultMessage).toBeDefined() const block = toolResultMessage!.content.find(b => b.type === 'tool-result')! expect(block).toMatchObject({ toolCallId: 'c1', isError: false }) expect((block).content).toEqual([{ type: 'text', text: 'echo: ping' }]) // session log records call + result const types = agent.session.events.map(e => e.type) expect(types).toContain('tool/call') expect(types).toContain('tool/result') }) it('threads a tool-attached meta (execute object return) onto the tool/result event', async () => { const adapter = new MockAdapter([ toolCallResponse('c1', 'writer', { path: 'a.txt' }, 'writing'), textResponse('done'), ]) const ctx = await harness(adapter) // A tool that returns the { content, meta } object form: the loop must // persist `meta` on the tool/result event so a UI reproduces the card on replay. ctx.tools.register(defineTool({ name: 'writer', description: 'writes a file', parameters: { path: { type: 'string' } }, async execute() { return { content: [{ type: 'text', text: 'ok' }], meta: { diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] } } }, })) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) send(agent, 'use the tool') await waitForIdle(ctx, agent) const toolResult = agent.session.events.find(e => e.type === 'tool/result') expect(toolResult?.type === 'tool/result' && toolResult.data.meta) .toEqual({ diffs: [{ path: 'a.txt', oldText: null, newText: 'x' }] }) }) it('renders harness identity, then the persona, then tool guidance — with {{variables}} resolved', async () => { const adapter = new MockAdapter([textResponse('ok')]) // The persona is a TEMPLATE: {{model}} is the loop-registered variable // projecting this agent's configured model, so the model knows its own name. const ctx = await harness(adapter, 'You are a test agent on {{model}}.') ctx.systemPrompt.section({ name: 'tool:noop', order: 100, text: 'Use the noop tool wisely.' }) ctx.tools.register(defineTool({ name: 'noop', description: 'does nothing', parameters: {}, async execute() { return [] }, })) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) send(agent, 'hi') await waitForIdle(ctx, agent) const request = adapter.requests[0] expect(request!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou are a test agent on mock.\n\nUse the noop tool wisely.') expect(request!.tools?.map(t => t.name)).toEqual(['noop']) }) it('resolves {{cwd}} from the agent session workspace (factory create with meta.cwd)', async () => { const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter, 'Working in {{cwd}}.') const handle = await ctx.agents.create({ sessionId: SessionId('s-cwd'), meta: { cwd: '/work/space' }, agentOptions: { provider: 'mock', model: 'mock' }, }) const agent = handle.agent send(agent, 'hi') await waitForIdle(ctx, agent) expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nWorking in /work/space.') }) it('contains a strict-variable render failure: the turn errors, the loop keeps serving turns', async () => { // A missing cwd variable must fail one turn without preventing a later valid turn. const adapter = new MockAdapter([textResponse('ok after rescue')]) const ctx = await harness(adapter, 'In {{cwd}}.') const errors: Error[] = [] ctx.on('agent/error', (_agent, _turn, _step, error) => void errors.push(error)) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) send(agent, 'hi') await waitForIdle(ctx, agent) expect(adapter.requests).toHaveLength(0) // the request was never sent expect(errors.some(e => e.message.includes('no value for this assembly'))).toBe(true) const turnEnd = agent.session.events.find(e => e.type === 'turn/end') expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('error') // The loop survived: a waterfall listener rescues {{cwd}} and the SAME // agent completes a real model turn. ctx.on('system-prompt/assemble', async (assembly, _context, next) => { assembly.variables['cwd'] = '/rescued' return next() }) send(agent, 'again') await waitForIdle(ctx, agent) expect(adapter.requests).toHaveLength(1) expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nIn /rescued.') const turnEnds = agent.session.events.filter(e => e.type === 'turn/end') expect(turnEnds).toHaveLength(2) expect(turnEnds[1]?.type === 'turn/end' && turnEnds[1].data.reason.kind).toBe('completed') }) it('supports the model-via-agent/request path with a {{model}} persona: the supplier states it via the assemble waterfall', async () => { // AgentOptions.model unset: the model arrives in the agent/request // waterfall (the loop's documented fallback — see runStep's no-model // error). {{model}} renders BEFORE that waterfall, so the SAME plugin // states the fact early on system-prompt/assemble — the owner of a // late-bound fact owns stating it wherever it is claimed. const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter, 'You run on {{model}}.') ctx.on('system-prompt/assemble', async (assembly, _context, next) => { assembly.variables['provider'] = 'mock' assembly.variables['model'] = 'mock' return next() }) ctx.on('agent/request', async (_agent, _turn, _step, config, _next) => { return { ...config, provider: 'mock', model: 'mock' } }) const agent = ctx.agentLoop.create(SessionId('a-late-model'), {}) send(agent, 'hi') await waitForIdle(ctx, agent) expect(adapter.requests).toHaveLength(1) expect(adapter.requests[0]!.model).toBe('mock') expect(adapter.requests[0]!.system).toBe('You are an AI agent powered by the DeepSeek Harness SDK.\n\nYou run on mock.') }) it.each([ ['BigInt', { n: 1n }], ['Map', new Map([['key', 'value']])], ['class instance', new (class ResultMeta { x = 1 })()], ])('normalizes non-JSON tool meta (%s) before the durable result commit', async (_kind, meta) => { const adapter = new MockAdapter([ toolCallResponse('bad-meta-call', 'bad-meta', {}, 'calling'), textResponse('recovered'), ]) const ctx = await harness(adapter) ctx.tools.register(defineTool({ name: 'bad-meta', description: 'returns invalid durable metadata', parameters: {}, execute: () => Promise.resolve({ content: [{ type: 'text' as const, text: 'apparent success' }], meta }), })) const agent = ctx.agentLoop.create(SessionId('bad-meta-agent'), { provider: 'mock', model: 'mock' }) send(agent, 'use the tool') await waitForIdle(ctx, agent) const result = agent.session.events.find(event => event.type === 'tool/result') expect(result?.type).toBe('tool/result') if (result?.type === 'tool/result') { expect(result.data.callId).toBe('bad-meta-call') expect(result.data.isError).toBe(true) expect(result.data.meta).toBeUndefined() expect(result.data.content).toEqual([{ type: 'text', text: 'Error: tool result must be losslessly JSON-serializable', }]) } // The normalized failure was durably logged and fed back to the model; the // turn continued normally instead of failing after an apparent success. expect(adapter.requests).toHaveLength(2) expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('losslessly JSON-serializable') }) it('omits the system field when a system-prompt/assemble veto empties the assembly', async () => { // The documented escape valve: a deployment that must drop the harness // openers short-circuits the assemble waterfall; the request then carries // NO system field at all (not an empty string). const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter) ctx.on('system-prompt/assemble', async () => ({ sections: [], tools: [], variables: {} })) const agent = ctx.agentLoop.create(SessionId('a-no-system'), { provider: 'mock', model: 'mock' }) send(agent, 'hi') await waitForIdle(ctx, agent) expect(adapter.requests).toHaveLength(1) expect('system' in adapter.requests[0]!).toBe(false) }) it('records raw chunks for replay as assistant/chunk session events', async () => { const adapter = new MockAdapter([textResponse('abc')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) send(agent, 'hi') await waitForIdle(ctx, agent) const chunkEvents = agent.session.events.filter(e => e.type === 'assistant/chunk') // textResponse('abc') = block-start + 3 deltas + block-end + usage + finish = 7 expect(chunkEvents).toHaveLength(7) // replay: chunk events alone re-assemble to the recorded assistant message const deltaText = chunkEvents .flatMap(e => e.type === 'assistant/chunk' ? [e.data.chunk] : []) .filter((c: StreamChunk): c is Extract => c.type === 'text-delta') .map(c => c.text) .join('') expect(deltaText).toBe('abc') }) it('injects steering between steps and continues the turn', async () => { const adapter = new MockAdapter([ toolCallResponse('c1', 'slow', {}), textResponse('addressed the steering'), ]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) ctx.tools.register(defineTool({ name: 'slow', description: '', parameters: {}, async execute() { // steer while the turn is running (during tool execution) agent.steer([{ type: 'text', text: 'change of plans' }]) return [{ type: 'text', text: 'tool done' }] }, })) send(agent, 'start') await waitForIdle(ctx, agent) const types = agent.session.events.map(e => e.type) expect(types).toContain('steering/message') // steering recorded before the second step's request derived its history const steeringSeq = agent.session.events.find(e => e.type === 'steering/message')!.seq const secondStepStart = agent.session.events.filter(e => e.type === 'step/start')[1] expect(secondStepStart).toBeDefined() expect(steeringSeq).toBeLessThan(secondStepStart!.seq) // the second model request saw the steering content const secondRequest = adapter.requests[1] const flat = JSON.stringify(secondRequest!.messages) expect(flat).toContain('change of plans') }) it('same-tick idle steering inherits one-send-one-turn FIFO behavior', async () => { const adapter = new MockAdapter([textResponse('first'), textResponse('second')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) const idle = waitForIdle(ctx, agent) agent.steer([{ type: 'text', text: 'first idle steer' }]) agent.steer([{ type: 'text', text: 'second idle steer' }]) await idle expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2) expect(agent.session.events .filter(event => event.type === 'user/message') .map(event => event.data.content)).toEqual([ [{ type: 'text', text: 'first idle steer' }], [{ type: 'text', text: 'second idle steer' }], ]) expect(adapter.requests).toHaveLength(2) }) it('inject() while idle wraps context in a one-shot turn, visible to the next request', async () => { const adapter = new MockAdapter([textResponse('ok')]) const ctx = await harness(adapter) const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' }) agent.inject([{ type: 'text', text: 'file changed: a.ts' }], { source: { kind: 'plugin', plugin: 'watcher' } }) // The idle inject records a self-contained turn (turn/start → context/message // → turn/end) so the event stays turn-enclosed, but does NOT run the model. await new Promise(r => setTimeout(r, 20)) expect(agent.status).toBe('idle') expect(adapter.requests).toHaveLength(0) const injectedTurn = agent.session.events.filter(e => e.type === 'turn/start') expect(injectedTurn).toHaveLength(1) const it0 = injectedTurn[0]! expect(it0.type === 'turn/start' && it0.data.trigger.kind).toBe('injection') expect(agent.session.events.at(-1)!.type).toBe('turn/end') // turn-enclosed send(agent, 'go') await waitForIdle(ctx, agent) const flat = JSON.stringify(adapter.requests[0]!.messages) expect(flat).toContain('file changed: a.ts') expect(flat).not.toContain('