| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401 |
- import { describe, expect, it } from 'vitest'
- import { Context } from 'cordis'
- import LlmService, { createUserMessage, 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, { defineContentToolFixture } 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<void> {
- return (agent as Agent & { done: Promise<void> }).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<void> {
- 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.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }))
- }
- describe('agent loop', () => {
- it.each([0, -1, 1.5, Number.NaN, Number.MAX_SAFE_INTEGER + 1])(
- 'rejects invalid AgentOptions.maxTokens %s before publication',
- async (maxTokens) => {
- const ctx = await harness(new MockAdapter([]))
- expect(() => ctx.agentLoop.create(
- SessionId('invalid-max-tokens'),
- { provider: 'mock', model: 'mock', maxTokens },
- )).toThrow('agent maxTokens must be a positive safe integer')
- expect(ctx.agents.list()).toEqual([])
- expect(ctx.sessions.list()).toEqual([])
- },
- )
- it('seeds a valid AgentOptions.maxTokens into the first model request', async () => {
- const adapter = new MockAdapter([textResponse('bounded')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(
- SessionId('valid-max-tokens'),
- { provider: 'mock', model: 'mock', maxTokens: 256 },
- )
- send(agent, 'use the configured output limit')
- await waitForIdle(ctx, agent)
- expect(adapter.requests[0]?.maxTokens).toBe(256)
- })
- 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(defineContentToolFixture({
- 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('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(defineContentToolFixture({
- 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) => {
- if (error instanceof Error) 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, _signal, next) => {
- const config = await 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('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: [], contexts: [], 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('materializes changed runtime context at the history tail without rewriting the system header', async () => {
- const adapter = new MockAdapter([
- textResponse('one'),
- textResponse('two'),
- textResponse('three'),
- textResponse('four'),
- textResponse('five'),
- ])
- const ctx = await harness(adapter)
- let mode = 'read-only'
- const dispose = ctx.systemPrompt.context({ name: 'policy', order: 0, text: () => `Mode: ${mode}.` })
- const agent = ctx.agentLoop.create(SessionId('a-runtime-context'), { provider: 'mock', model: 'mock' })
- const contextEvents = () => agent.session.events.flatMap(event =>
- event.type === 'user/message'
- && event.data.source.kind === 'plugin'
- && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
- ? [event]
- : [])
- send(agent, 'first')
- await waitForIdle(ctx, agent)
- expect(contextEvents()).toHaveLength(1)
- expect(contextEvents()[0]?.data.content).toEqual([{
- type: 'text',
- text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nMode: read-only.',
- }])
- send(agent, 'unchanged')
- await waitForIdle(ctx, agent)
- expect(contextEvents()).toHaveLength(1)
- mode = 'danger-full-access'
- send(agent, 'changed')
- await waitForIdle(ctx, agent)
- expect(contextEvents()).toHaveLength(2)
- const changedBlock = contextEvents()[1]?.data.content[0]
- expect(changedBlock?.type).toBe('text')
- if (changedBlock?.type !== 'text') throw new Error('changed runtime context is not text')
- expect(changedBlock.text).toContain('danger-full-access')
- dispose()
- send(agent, 'cleared')
- await waitForIdle(ctx, agent)
- expect(contextEvents()).toHaveLength(3)
- expect(contextEvents()[2]?.data.content).toEqual([{
- type: 'text',
- text: 'Current runtime context: none. Earlier runtime-context snapshots no longer apply.',
- }])
- send(agent, 'still clear')
- await waitForIdle(ctx, agent)
- expect(contextEvents()).toHaveLength(3)
- expect(adapter.requests.map(request => request.system)).toEqual(Array(5).fill(adapter.requests[0]?.system))
- expect(agent.session.events.filter(event => event.type === 'request/header')).toHaveLength(1)
- })
- it('re-emits unchanged runtime context when a surface replacement removed the retained snapshot', async () => {
- const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
- const ctx = await harness(adapter)
- ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
- const agent = ctx.agentLoop.create(SessionId('a-runtime-context-compacted'), { provider: 'mock', model: 'mock' })
- send(agent, 'first')
- await waitForIdle(ctx, agent)
- const contextEvent = agent.session.events.find(event =>
- event.type === 'user/message'
- && event.data.source.kind === 'plugin'
- && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt')
- if (contextEvent?.type !== 'user/message') throw new Error('first turn did not materialize runtime context')
- agent.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'compacted summary' }],
- source: { kind: 'plugin', plugin: 'test-compaction' },
- }), {
- surfaceOp: { op: 'replace', start: contextEvent.seq, end: contextEvent.seq },
- sourceEventSeqs: [contextEvent.seq],
- })
- send(agent, 'after compaction')
- await waitForIdle(ctx, agent)
- const runtimeContexts = agent.session.events.flatMap(event =>
- event.type === 'user/message'
- && event.data.source.kind === 'plugin'
- && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
- ? [event]
- : [])
- expect(runtimeContexts).toHaveLength(2)
- expect(adapter.requests[1]?.messages.some(message =>
- message.source.kind === 'plugin'
- && message.source.plugin === '@deepseek-ai/dsh-system-prompt')).toBe(true)
- })
- it('clears compacted runtime context after the active set becomes empty', async () => {
- const adapter = new MockAdapter([textResponse('one'), textResponse('two')])
- const ctx = await harness(adapter)
- const dispose = ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
- const agent = ctx.agentLoop.create(SessionId('a-runtime-context-compacted-clear'), { provider: 'mock', model: 'mock' })
- send(agent, 'first')
- await waitForIdle(ctx, agent)
- const contextEvent = agent.session.events.find(event =>
- event.type === 'user/message'
- && event.data.source.kind === 'plugin'
- && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt')
- if (contextEvent?.type !== 'user/message') throw new Error('first turn did not materialize runtime context')
- agent.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'summary retaining old mode: read-only' }],
- source: { kind: 'plugin', plugin: 'test-compaction' },
- }), {
- surfaceOp: { op: 'replace', start: contextEvent.seq, end: contextEvent.seq },
- sourceEventSeqs: [contextEvent.seq],
- })
- dispose()
- send(agent, 'after compaction')
- await waitForIdle(ctx, agent)
- const clearing = adapter.requests[1]?.messages.find(message =>
- message.source.kind === 'plugin'
- && message.source.plugin === '@deepseek-ai/dsh-system-prompt')
- expect(clearing?.content).toEqual([{
- type: 'text',
- text: 'Current runtime context: none. Earlier runtime-context snapshots no longer apply.',
- }])
- })
- it('does not clear runtime context after an unrelated replacement', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a-runtime-context-unrelated-compaction'), { provider: 'mock', model: 'mock' })
- const original = agent.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'old context' }],
- source: { kind: 'plugin', plugin: 'test-context' },
- }), { surfaceOp: 'append' })
- agent.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'compacted summary' }],
- source: { kind: 'plugin', plugin: 'test-compaction' },
- }), {
- surfaceOp: { op: 'replace', start: original.seq, end: original.seq },
- sourceEventSeqs: [original.seq],
- })
- send(agent, 'after compaction')
- await waitForIdle(ctx, agent)
- expect(adapter.requests[0]?.messages.some(message =>
- message.source.kind === 'plugin'
- && message.source.plugin === '@deepseek-ai/dsh-system-prompt')).toBe(false)
- })
- it('replaces a malformed retained runtime-context message with the current complete snapshot', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- ctx.systemPrompt.context({ name: 'policy', order: 0, text: 'Mode: read-only.' })
- const agent = ctx.agentLoop.create(SessionId('a-runtime-context-malformed'), { provider: 'mock', model: 'mock' })
- agent.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'broken' }, { type: 'text', text: 'snapshot' }],
- source: { kind: 'plugin', plugin: '@deepseek-ai/dsh-system-prompt' },
- }), { surfaceOp: 'append' })
- send(agent, 'repair context')
- await waitForIdle(ctx, agent)
- const runtimeContexts = agent.session.events.flatMap(event =>
- event.type === 'user/message'
- && event.data.source.kind === 'plugin'
- && event.data.source.plugin === '@deepseek-ai/dsh-system-prompt'
- ? [event]
- : [])
- expect(runtimeContexts).toHaveLength(2)
- expect(runtimeContexts[1]?.data.content).toEqual([{
- type: 'text',
- text: 'Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nMode: read-only.',
- }])
- })
- 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<StreamChunk, { type: 'text-delta' }> => 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(defineContentToolFixture({
- name: 'slow',
- description: '',
- parameters: {},
- async execute() {
- // steer while the turn is running (during tool execution)
- agent.steer(createUserMessage({ content: [{ type: 'text', text: 'change of plans' }], source: { kind: 'user' } }))
- 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 preserves one turn per send', 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(createUserMessage({ content: [{ type: 'text', text: 'first idle steer' }], source: { kind: 'user' } }))
- agent.steer(createUserMessage({ content: [{ type: 'text', text: 'second idle steer' }], source: { kind: 'user' } }))
- 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(agent.session.events.filter(event => event.type === 'steering/message')).toEqual([])
- expect(adapter.requests).toHaveLength(2)
- expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('first idle steer')
- expect(JSON.stringify(adapter.requests[0]?.messages)).not.toContain('second idle steer')
- expect(JSON.stringify(adapter.requests[1]?.messages)).toContain('second idle steer')
- })
- it('keeps steering staged after a failed step until the next admitted turn', async () => {
- const adapter = new MockAdapter([textResponse('recovered')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('failed-steering'), { provider: 'mock', model: 'mock' })
- let fail = true
- ctx.on('agent/step', (subject) => {
- if (subject !== agent || !fail) return
- fail = false
- subject.steer(createUserMessage({ content: [{ type: 'text', text: 'pending steering' }], source: { kind: 'user' } }))
- throw new Error('step failed')
- })
- send(agent, 'prompt')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(0)
- expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
- expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(false)
- send(agent, 'resume')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(1)
- expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
- expect(agent.session.events.some(event => event.type === 'steering/message')).toBe(true)
- expect(JSON.stringify(adapter.requests[0]?.messages)).toContain('pending steering')
- })
- it('inject() while idle appends context without opening a turn', 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(createUserMessage({ content: [{ type: 'text', text: 'file changed: a.ts' }], source: { kind: 'plugin', plugin: 'watcher' } }))
- expect(agent.status).toBe('idle')
- expect(adapter.requests).toHaveLength(0)
- expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(0)
- expect(agent.session.events.at(-1)).toMatchObject({
- type: 'user/message',
- data: {
- role: 'user',
- content: [{ type: 'text', text: 'file changed: a.ts' }],
- source: { kind: 'plugin', plugin: 'watcher' },
- },
- })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(1)
- const flat = JSON.stringify(adapter.requests[0]!.messages)
- expect(flat).toContain('file changed: a.ts')
- expect(flat).not.toContain('<context source=')
- })
- it('inject() persists structured context content verbatim with durable source', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('raw-context'), { provider: 'mock', model: 'mock' })
- const text = '<system-reminder>Additional instructions from: pkg/AGENTS.md</system-reminder>'
- agent.inject(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'plugin', plugin: 'workspace-context' } }))
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- const contextEvent = agent.session.events.find(event => event.type === 'user/message' && event.data.source.kind === 'plugin')
- expect(contextEvent?.type === 'user/message' && contextEvent.data.source)
- .toEqual({ kind: 'plugin', plugin: 'workspace-context' })
- const requestText = JSON.stringify(adapter.requests[0]!.messages)
- expect(requestText).toContain('Additional instructions from: pkg/AGENTS.md')
- expect(requestText).not.toContain('<context source=')
- })
- it('defers inject() during tool execution until after the tool result', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'noticer', {}, 'calling'),
- textResponse('done'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let visibleDuringTool = false
- ctx.tools.register(defineContentToolFixture({
- name: 'noticer',
- description: 'injects a notice',
- parameters: {},
- async execute() {
- await Promise.resolve()
- const first = { type: 'text' as const, text: 'mid-turn notice' }
- agent.inject(createUserMessage({ content: [first], source: { kind: 'plugin', plugin: 'x' } }))
- first.text = 'mutated after inject'
- agent.inject(createUserMessage({ content: [{ type: 'text', text: 'second notice' }], source: { kind: 'plugin', plugin: 'x' } }))
- visibleDuringTool = agent.session.events.some(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
- return [{ type: 'text', text: 'ok' }]
- },
- }))
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(visibleDuringTool).toBe(false)
- // The injection stays in the open turn, but its user-role context cannot
- // split the assistant tool call from the provider's tool-result message.
- const turnStarts = agent.session.events.filter(e => e.type === 'turn/start')
- expect(turnStarts).toHaveLength(1)
- const ts0 = turnStarts[0]!
- expect(ts0.type === 'turn/start' && ts0.data.trigger.kind).toBe('message')
- const result = agent.session.events.find(e => e.type === 'tool/result')!
- const contexts = agent.session.events.filter(e => e.type === 'user/message' && e.data.source.kind === 'plugin')
- expect(contexts).toHaveLength(2)
- expect(result.seq).toBeLessThan(contexts[0]!.seq)
- expect(contexts.flatMap(event => event.type === 'user/message' ? event.data.content : []))
- .toEqual([
- { type: 'text', text: 'mid-turn notice' },
- { type: 'text', text: 'second notice' },
- ])
- const secondRequest = adapter.requests[1]!.messages
- const resultIndex = secondRequest.findIndex(message =>
- message.content.some(block => block.type === 'tool-result'))
- const contextIndexes = secondRequest.flatMap((message, index) =>
- message.content.some(block => block.type === 'text'
- && (block.text.includes('mid-turn notice') || block.text.includes('second notice')))
- ? [index]
- : [])
- expect(resultIndex).toBeGreaterThanOrEqual(0)
- expect(contextIndexes).toHaveLength(2)
- expect(contextIndexes.every(index => index > resultIndex)).toBe(true)
- })
- it('rejects non-JSON context before it enters the active tool-batch FIFO', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'invalid-injector', {}, 'calling'),
- textResponse('done'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('invalid-context'), { provider: 'mock', model: 'mock' })
- ctx.tools.register(defineContentToolFixture({
- name: 'invalid-injector',
- description: 'attempts an invalid context injection',
- parameters: {},
- async execute() {
- expect(() => {
- agent.inject(createUserMessage({ content: [{ type: 'text', text: 'invalid' }], source: { kind: 'plugin', plugin: 'test', bigint: 1n } as never }))
- }).toThrow('agent context must be losslessly JSON-serializable')
- return [{ type: 'text', text: 'rejected invalid context' }]
- },
- }))
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(agent.session.events.some(event => event.type === 'user/message' && event.data.source.kind === 'plugin')).toBe(false)
- })
- it('agent/turn-stopping can steer another step (/loop pattern)', async () => {
- const adapter = new MockAdapter([
- textResponse('step 1'),
- textResponse('step 2'),
- textResponse('step 3'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let steps = 0
- ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
- ctx.on('agent/turn-stopping', (subject) => {
- if (steps < 3) {
- subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue' }], source: { kind: 'plugin', plugin: 'loop-test' } }))
- }
- })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(steps).toBe(3)
- expect(adapter.requests).toHaveLength(3)
- })
- it('a tool can conclude the turn despite owing a follow-up request', async () => {
- const adapter = new MockAdapter([toolCallResponse('c1', 'echo', { text: 'x' })])
- const ctx = await harness(adapter)
- ctx.tools.register(defineContentToolFixture({
- name: 'echo',
- description: '',
- parameters: { text: { type: 'string' } },
- async execute(args, exec) {
- exec.concludeTurn()
- return [{ type: 'text', text: String(args.text) }]
- },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- // only one model call despite the tool call requesting a follow-up
- expect(adapter.requests).toHaveLength(1)
- // The tool still executes and durably records its result.
- expect(agent.session.events.some(e => e.type === 'tool/result')).toBe(true)
- })
- it('a concluding tool result beats steering that arrived during the same step', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'finalize', {}),
- textResponse('next turn reply'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- ctx.tools.register(defineContentToolFixture({
- name: 'finalize',
- description: '',
- parameters: {},
- async execute(_args, exec) {
- // Steering lands while the concluding tool is still executing.
- agent.steer(createUserMessage({ content: [{ type: 'text', text: 'late steering' }], source: { kind: 'user' } }))
- exec.concludeTurn()
- return [{ type: 'text', text: 'final' }]
- },
- }))
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- // The terminal result stands: no extra request reopens the concluded turn.
- expect(adapter.requests).toHaveLength(1)
- const events = agent.session.events.map(event => event.type)
- expect(events.filter(type => type === 'turn/end')).toHaveLength(1)
- // The steering is durable inside the concluded turn and feeds the NEXT
- // turn's request instead of being dropped or re-queued.
- expect(events).toContain('steering/message')
- send(agent, 'follow up')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(2)
- const texts = adapter.requests[1]!.messages
- .flatMap(message => message.content)
- .filter(block => block.type === 'text')
- .map(block => block.text)
- expect(texts).toContain('late steering')
- })
- it('agent/request waterfall switches models by returning a replacement config; the switch is logged', async () => {
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- ctx.on('agent/request', async (_agent, _turn, _step, _signal, next) => {
- const config = await next()
- // The seed is frozen — config is not a mutable per-call knob; a switch
- // is proposed by returning a replacement, and the loop logs it.
- expect(Object.isFrozen(config)).toBe(true)
- expect(() => { (config as { model: string }).model = 'other-model' }).toThrow(TypeError)
- return { ...config, model: 'other-model' }
- })
- send(agent, 'hi')
- await waitForIdle(ctx, agent)
- expect(adapter.requests[0]!.model).toBe('other-model')
- // The header event records what the request ACTUALLY used — the switch is
- // a reconstructable fact, not silent drift.
- const headerEvent = agent.session.events.find(e => e.type === 'request/header')
- expect(headerEvent?.type === 'request/header' && headerEvent.data.header.config.model).toBe('other-model')
- })
- it('agent/step fires once per step before the step is opened', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'echo', {}, 'calling echo'),
- textResponse('done'),
- ])
- const ctx = await harness(adapter)
- ctx.tools.register(defineContentToolFixture({
- name: 'echo', description: 'echo', parameters: {},
- async execute() { return [{ type: 'text', text: 'echoed' }] },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const fires: { turn: number; step: number; signal: AbortSignal }[] = []
- ctx.on('agent/step', (subject, turn, step, signal) => {
- if (subject === agent) fires.push({ turn, step, signal })
- })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(fires.map(({ turn, step }) => ({ turn, step }))).toEqual([
- { turn: 1, step: 1 },
- { turn: 1, step: 2 },
- ])
- expect(fires.every(({ signal }) => signal instanceof AbortSignal)).toBe(true)
- })
- it('agent/step fires BEFORE the step it precedes opens (events land outside the step)', async () => {
- // The append lands before step/start, yet derive happens afterwards and the
- // same step's request must include it.
- const adapter = new MockAdapter([textResponse('ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let injected = false
- ctx.on('agent/step', (subject) => {
- if (subject === agent && !injected) {
- injected = true
- subject.session.append('user/message', createUserMessage({
- content: [{ type: 'text', text: 'INJECTED-IN-PRE-STEP' }],
- source: { kind: 'plugin', plugin: 'test' },
- }), { surfaceOp: 'append' })
- }
- })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- // The adapter's request includes the node injected during pre-step (derive
- // reflects it).
- const text = JSON.stringify(adapter.requests[0]!.messages)
- expect(text).toContain('INJECTED-IN-PRE-STEP')
- // And the injected event sits BEFORE the first step/start in the log —
- // the seam fired outside the step.
- const events = agent.session.events
- const injectedSeq = events.find(e => e.type === 'user/message' && e.data.source.kind === 'plugin')!.seq
- const firstStepStartSeq = events.find(e => e.type === 'step/start')!.seq
- expect(injectedSeq).toBeLessThan(firstStepStartSeq)
- })
- it('a throwing agent/step listener ends the turn (error), not the loop', async () => {
- // Before step/start, a pre-step throw reaches the turn catch: no step needs
- // closing, the turn records error, and the loop remains available.
- const adapter = new MockAdapter([textResponse('second turn ok')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let throwOnce = true
- ctx.on('agent/step', () => {
- if (throwOnce) { throwOnce = false; throw new Error('boom in pre-step') }
- })
- const errors: Error[] = []
- ctx.on('agent/error', (_a, _t, _s, error) => {
- if (error instanceof Error) errors.push(error)
- })
- send(agent, 'first')
- await waitForIdle(ctx, agent)
- // The first turn failed at step 1 (no model call happened), surfaced via
- // agent/error, with the durable failure on turn/end.reason.
- expect(errors).toHaveLength(1)
- expect(errors[0]!.message).toContain('boom in pre-step')
- expect(adapter.requests.length).toBe(0)
- const firstTurnEnd = agent.session.events.find(e => e.type === 'turn/end')
- expect(firstTurnEnd?.type === 'turn/end' && firstTurnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
- // The step opened-and-closed count stays balanced even though it never ran.
- const types = agent.session.events.map(e => e.type)
- expect(types.filter(t => t === 'step/start').length).toBe(types.filter(t => t === 'step/end').length)
- // The loop survived: a second prompt runs a normal completed turn.
- send(agent, 'second')
- await waitForIdle(ctx, agent)
- expect(adapter.requests.length).toBe(1)
- const lastTurnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
- expect(lastTurnEnd?.type === 'turn/end' && lastTurnEnd.data.reason).toEqual({ kind: 'completed' })
- })
- it('cancel() mid-stream ends the turn with reason aborted', async () => {
- const adapter = new MockAdapter(['hang'])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- // wait until the stream is hanging, then cancel
- await new Promise(r => setTimeout(r, 30))
- expect(agent.status).toBe('running')
- agent.cancel({ kind: 'user' })
- await waitForIdle(ctx, agent)
- expect(reasons).toEqual([{ kind: 'aborted' }])
- })
- it('surfaces max-tokens as the turn-end reason when the last step is cut off', async () => {
- // A single step that ends with a max-tokens finish (no tool calls): the
- // turn stops by default and ends max-tokens, not completed.
- const adapter = new MockAdapter([maxTokensResponse('truncat')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(1)
- expect(reasons).toEqual([{ kind: 'max-tokens' }])
- // Assert the durable row, not only the live listener.
- const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
- expect(turnEnd!.data.reason).toEqual({ kind: 'max-tokens' })
- })
- it('a max-tokens step earlier in a turn still surfaces as max-tokens after a later completed step', async () => {
- // Step 1 is cut off (max-tokens, no tool calls → would stop by default), so continuation
- // must be FORCED to reach step 2 which finishes normally (stop).
- const adapter = new MockAdapter([
- maxTokensResponse('first half'),
- textResponse('second half'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let steps = 0
- ctx.on('session/event', (_session, event) => { if (event.type === 'step/end') steps++ })
- // Force exactly one continuation (step 1 → step 2), then defer to default
- // (step 2 is a plain stop with no tool calls → stops).
- ctx.on('agent/turn-stopping', (subject) => {
- if (steps < 2) {
- subject.steer(createUserMessage({ content: [{ type: 'text', text: 'continue after truncation' }], source: { kind: 'plugin', plugin: 'max-tokens-test' } }))
- }
- })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(steps).toBe(2)
- expect(adapter.requests).toHaveLength(2)
- expect(adapter.requests[1]!.messages).toEqual([
- {
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'go' }],
- source: { kind: 'user' },
- },
- {
- id: expect.any(String) as unknown,
- role: 'assistant',
- content: [{ type: 'text', text: 'first half' }],
- source: { kind: 'model', provider: 'mock', model: 'mock' },
- },
- {
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'continue after truncation' }],
- source: { kind: 'plugin', plugin: 'max-tokens-test' },
- },
- ])
- expect(reasons).toEqual([{ kind: 'max-tokens' }])
- })
- it('a completed step after no max-tokens keeps the turn completed (max-tokens does not leak across turns)', async () => {
- // Two consecutive turns: turn 1 is cut off (max-tokens), turn 2 is a clean
- // stop. The per-turn reason must be independent — turn 2 ends completed.
- const adapter = new MockAdapter([maxTokensResponse('cut'), textResponse('clean')])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'first')
- await waitForIdle(ctx, agent)
- send(agent, 'second')
- await waitForIdle(ctx, agent)
- expect(reasons).toEqual([{ kind: 'max-tokens' }, { kind: 'completed' }])
- })
- it('does not dispatch tool calls from a max-tokens-truncated step', async () => {
- const callId = CallId('c1')
- const adapter = new MockAdapter([[
- { type: 'block-start', index: 0, blockType: 'tool-call' },
- { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
- { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
- { type: 'usage', usage: { inputTokens: 10, outputTokens: 5 } },
- { type: 'finish', reason: { kind: 'max-tokens' } },
- ]])
- const ctx = await harness(adapter)
- let executions = 0
- ctx.tools.register(defineContentToolFixture({
- name: 'echo',
- description: '',
- parameters: { text: { type: 'string' } },
- async execute() {
- executions += 1
- return [{ type: 'text', text: 'should not run' }]
- },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(executions).toBe(0)
- expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
- expect(agent.session.deriveMessages()).toEqual([{
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'go' }],
- source: { kind: 'user' },
- }])
- expect(reasons).toEqual([{ kind: 'max-tokens' }])
- // Empty content still needs an assistant/message to carry usage; derivation
- // skips that host so it does not create a spurious assistant turn.
- const assistantMessage = agent.session.events.find(e => e.type === 'assistant/message')
- expect(assistantMessage?.type === 'assistant/message' && assistantMessage.data).toEqual({
- turn: 1,
- step: 1,
- message: {
- id: expect.any(String) as unknown,
- role: 'assistant',
- content: [],
- source: { kind: 'model', provider: 'mock', model: 'mock' },
- },
- usage: { inputTokens: 10, outputTokens: 5 },
- })
- })
- it('appends an empty completion anchor for a max-tokens step with no usage', async () => {
- // The truncated tool call is dropped from durable content, while the
- // successful provider call still needs an exact replay anchor.
- const callId = CallId('c1')
- const adapter = new MockAdapter([[
- { type: 'block-start', index: 0, blockType: 'tool-call' },
- { type: 'tool-call-delta', index: 0, id: callId, name: 'echo', argumentsDelta: '{"text":"x"}' },
- { type: 'block-end', index: 0, block: { type: 'tool-call', id: callId, name: 'echo', arguments: '{"text":"x"}' } },
- { type: 'finish', reason: { kind: 'max-tokens' } },
- ]])
- const ctx = await harness(adapter)
- ctx.tools.register(defineContentToolFixture({
- name: 'echo',
- description: '',
- parameters: { text: { type: 'string' } },
- async execute() { return [{ type: 'text', text: 'should not run' }] },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(reasons).toEqual([{ kind: 'max-tokens' }])
- const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
- expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
- turn: 1,
- step: 1,
- message: {
- id: expect.any(String) as unknown,
- role: 'assistant',
- content: [],
- source: { kind: 'model', provider: 'mock', model: 'mock' },
- },
- })
- expect(assistant.sourceEventSeqs?.length).toBeGreaterThan(0)
- expect(agent.session.deriveMessages()).toEqual([{
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'go' }],
- source: { kind: 'user' },
- }])
- })
- it('appends an empty completion anchor for a normal stop with no usage', async () => {
- // A clean content-less call stays absent from derived messages but remains
- // a durable successful-call boundary for replay consumers.
- const adapter = new MockAdapter([[{ type: 'finish', reason: { kind: 'stop' } }]])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const reasons: TurnEndReason[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(reasons).toEqual([{ kind: 'completed' }])
- const assistant = agent.session.events.find(e => e.type === 'assistant/message')!
- expect(assistant.type === 'assistant/message' && assistant.data).toEqual({
- turn: 1,
- step: 1,
- message: {
- id: expect.any(String) as unknown,
- role: 'assistant',
- content: [],
- source: { kind: 'model', provider: 'mock', model: 'mock' },
- },
- })
- expect(assistant.sourceEventSeqs?.length).toBe(1)
- expect(agent.session.deriveMessages()).toEqual([{
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'go' }],
- source: { kind: 'user' },
- }])
- })
- it('keeps safe max-tokens assistant content while dropping truncated tool calls', async () => {
- const callId = CallId('c1')
- const adapter = new MockAdapter([[
- { type: 'block-start', index: 0, blockType: 'text' },
- { type: 'text-delta', index: 0, text: 'partial text' },
- { type: 'block-end', index: 0, block: { type: 'text', text: 'partial text' } },
- { type: 'block-start', index: 1, blockType: 'tool-call' },
- { type: 'tool-call-delta', index: 1, id: callId, name: 'echo', argumentsDelta: '{"text"' },
- { type: 'finish', reason: { kind: 'max-tokens' } },
- ]])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(agent.session.events.some(e => e.type === 'tool/call')).toBe(false)
- expect(agent.session.deriveMessages()).toEqual([
- {
- id: expect.any(String) as unknown,
- role: 'user',
- content: [{ type: 'text', text: 'go' }],
- source: { kind: 'user' },
- },
- {
- id: expect.any(String) as unknown,
- role: 'assistant',
- content: [{ type: 'text', text: 'partial text' }],
- source: { kind: 'model', provider: 'mock', model: 'mock' },
- },
- ])
- })
- it('contains a step/end observer failure without changing continuation', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'echo', { text: 'x' }),
- textResponse('continued after tool call'),
- ])
- const ctx = await harness(adapter)
- ctx.tools.register(defineContentToolFixture({
- name: 'echo',
- description: '',
- parameters: { text: { type: 'string' } },
- async execute(args) {
- return [{ type: 'text', text: String(args.text) }]
- },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- let threw = false
- // Post-commit session observers cannot control the loop. The tool call still
- // drives the second model request, and the turn completes normally.
- ctx.on('session/event', (_session, event) => {
- if (event.type === 'step/end' && !threw) { threw = true; throw new Error('bad step/end listener') }
- })
- send(agent, 'go')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(2)
- const turnEnd = agent.session.events.findLast(e => e.type === 'turn/end')
- expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason.kind).toBe('completed')
- })
- it('keeps a reentrant agent/inbox/enqueue send as the next independent turn', 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' })
- let nested = false
- ctx.on('agent/inbox/enqueue', (subject) => {
- if (subject !== agent || nested) return
- nested = true
- send(agent, 'queued listener message')
- })
- const idle = waitForIdle(ctx, agent)
- send(agent, 'outer message')
- await idle
- const turns = agent.session.events.filter(event => event.type === 'turn/start')
- const messages = agent.session.events
- .filter(event => event.type === 'user/message')
- .map(event => event.data.content)
- expect(turns).toHaveLength(2)
- expect(messages).toEqual([
- [{ type: 'text', text: 'outer message' }],
- [{ type: 'text', text: 'queued listener message' }],
- ])
- })
- it('preserves independent turn sources across an adjacent microtask send', 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.followup(createUserMessage({ content: [{ type: 'text', text: 'user message' }], source: { kind: 'user' } }))
- await Promise.resolve()
- agent.followup(createUserMessage({ content: [{ type: 'text', text: 'plugin message' }], source: { kind: 'plugin', plugin: 'test' } }))
- await idle
- const triggers = agent.session.events
- .filter(event => event.type === 'turn/start')
- .map(event => event.data.trigger)
- const sources = agent.session.events
- .filter(event => event.type === 'user/message')
- .map(event => event.data.source)
- expect(triggers).toEqual([
- { kind: 'message', source: { kind: 'user' } },
- { kind: 'message', source: { kind: 'plugin', plugin: 'test' } },
- ])
- expect(sources).toEqual([
- { kind: 'user' },
- { kind: 'plugin', plugin: 'test' },
- ])
- })
- it('keeps a session-listener send after dequeue in the following turn', 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 turns: number[] = []
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/start') turns.push(event.data.turn) })
- // queue two messages while idle — first starts turn 1 immediately;
- // queue the second during turn 1 when the first assistant chunk streams
- let queued = false
- ctx.on('session/event', (_s, event) => {
- if (event.type === 'assistant/chunk' && !queued) {
- queued = true
- send(agent, 'second message')
- }
- })
- send(agent, 'first message')
- await waitForIdle(ctx, agent)
- expect(turns).toEqual([1, 2])
- expect(adapter.requests).toHaveLength(2)
- expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('first')
- expect(JSON.stringify(adapter.requests[1]!.messages)).toContain('second message')
- })
- it('keeps a model-adapter callback send in the following turn', async () => {
- const agentRef: { current?: Agent } = {}
- const adapter = new MockAdapter([
- () => {
- const agent = agentRef.current
- if (agent === undefined) throw new Error('model callback ran before agent setup')
- send(agent, 'model callback message')
- return textResponse('first')
- },
- textResponse('second'),
- ])
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- agentRef.current = agent
- const idle = waitForIdle(ctx, agent)
- send(agent, 'outer message')
- await idle
- const messages = agent.session.events
- .filter(event => event.type === 'user/message')
- .map(event => event.data.content)
- expect(agent.session.events.filter(event => event.type === 'turn/start')).toHaveLength(2)
- expect(messages).toEqual([
- [{ type: 'text', text: 'outer message' }],
- [{ type: 'text', text: 'model callback message' }],
- ])
- })
- it('errors from the model surface as agent/error and end the turn', async () => {
- const adapter = new MockAdapter([]) // script exhausted → throws
- const ctx = await harness(adapter)
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- const errors: Error[] = []
- const reasons: TurnEndReason[] = []
- ctx.on('agent/error', (_agent, _turn, _step, error) => {
- if (error instanceof Error) errors.push(error)
- })
- ctx.on('session/event', (_s, event) => { if (event.type === 'turn/end') reasons.push(event.data.reason) })
- send(agent, 'hi')
- await waitForIdle(ctx, agent)
- expect(errors).toHaveLength(1)
- expect(errors[0]!.message).toContain('script exhausted')
- expect(reasons[0]).toMatchObject({ kind: 'error' })
- // The durable failure lives entirely on turn/end.reason (with the failing
- // step), not a standalone error event.
- const turnEnd = agent.session.events.find(e => e.type === 'turn/end')
- expect(turnEnd?.type === 'turn/end' && turnEnd.data.reason).toMatchObject({ kind: 'error', step: 1 })
- })
- it('disposing the loop fiber mid-turn stops the loop (HMR safety)', async () => {
- const adapter = new MockAdapter(['hang'])
- const ctx = await harness(adapter)
- let agent!: Agent
- const fiber = await ctx.plugin(Object.assign((inner: Context) => {
- agent = inner.agentLoop.create(SessionId('scoped'), { provider: 'mock', model: 'mock' })
- }, { inject: ['agentLoop'] }))
- expect(ctx.agents.get(SessionId('scoped'))).toBe(agent)
- send(agent, 'go')
- await new Promise(r => setTimeout(r, 30))
- expect(agent.status).toBe('running')
- await fiber.dispose()
- await driverDone(agent)
- expect(ctx.agents.get(SessionId('scoped'))).toBeUndefined()
- })
- it('creates agents from config on startup', async () => {
- const adapter = new MockAdapter([textResponse('from config')])
- const ctx = new Context()
- await ctx.plugin(LlmService)
- await ctx.plugin(SessionStore)
- await ctx.plugin(SystemPrompt)
- await ctx.plugin(ToolRegistry)
- await ctx.plugin(AgentRegistry)
- await ctx.plugin(AgentLoop, {
- agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock' }],
- })
- ctx.llm.registerAdapter(['mock'], adapter)
- const agent = ctx.agents.list()[0]!
- expect(agent).toBeDefined()
- expect(agent.id).toBe(agent.session.id)
- expect(agent.id).toMatch(/^config-agent-session-/)
- expect(agent.options.model).toBe('mock')
- // the agent is alive: send triggers a turn
- send(agent, 'hi')
- await waitForIdle(ctx, agent)
- expect(adapter.requests).toHaveLength(1)
- })
- it('attaches config agent cwd to the fresh session header', async () => {
- const ctx = new Context()
- await ctx.plugin(LlmService)
- await ctx.plugin(SessionStore)
- await ctx.plugin(SystemPrompt)
- await ctx.plugin(ToolRegistry)
- await ctx.plugin(AgentRegistry)
- await ctx.plugin(AgentLoop, {
- agents: [{ id: SessionId('config-agent'), provider: 'mock', model: 'mock', cwd: '/work/project' }],
- })
- const agent = ctx.agents.list()[0]!
- expect(agent.session.header.cwd).toBe('/work/project')
- })
- it('replays a session log into an identical derived history', async () => {
- const adapter = new MockAdapter([
- toolCallResponse('c1', 'echo', { text: 'x' }),
- textResponse('done'),
- ])
- const ctx = await harness(adapter)
- ctx.tools.register(defineContentToolFixture({
- name: 'echo',
- description: '',
- parameters: { text: { type: 'string' } },
- async execute(args) {
- return [{ type: 'text', text: String(args.text) }]
- },
- }))
- const agent = ctx.agentLoop.create(SessionId('a1'), { provider: 'mock', model: 'mock' })
- send(agent, 'run')
- await waitForIdle(ctx, agent)
- const replayed = ctx.sessions.create(SessionId('replayed'), { seed: [...agent.session.events] })
- expect(replayed.deriveMessages()).toEqual(agent.session.deriveMessages())
- // event-by-event identity of types over the inherited prefix
- expect(replayed.events.slice(0, agent.session.seq).map(e => e.type)).toEqual(
- agent.session.events.map(e => e.type))
- expect(replayed.events.at(-1)?.type).toBe('session/end-seed')
- })
- })
|