import { describe, expect, it } from 'vitest'; import type { ModeContext, ModeDef, MoxxyEvent, ProviderDef, ToolCallContext } from '@moxxy/sdk'; import { asSkillId, defineMode, defineProvider, definePlugin, defineTool, executeToolUses, z } from '@moxxy/sdk'; import { Session } from './session.js'; import { runTurn, collectTurn } from './run-turn.js'; // A loop that emits N assistant_message events that include `turnId` in the // text, then returns. It does NOT touch the provider, so concurrency is // dominated by the awaits inside the loop body (deterministic interleave via // the microtask queue). function makeMarkerLoop(name: string, n: number): ModeDef { return defineMode({ name, run: async function* (ctx: ModeContext): AsyncIterable { for (let i = 0; i < n; i++) { // Yield to the microtask queue so two concurrent runs interleave. await Promise.resolve(); await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: `${ctx.turnId}:${i}`, }); } }, }); } function makeNoopProvider(): ProviderDef { const models = [{ id: 'noop-1' }]; return defineProvider({ name: 'noop', models, createClient: () => ({ name: 'noop', models, stream: async function* () { // unused — the test loop doesn't call into the provider. }, countTokens: async () => 0, }), }); } function buildSession(): Session { const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'test-loop-and-provider', version: '0.0.0', providers: [makeNoopProvider()], modes: [makeMarkerLoop('marker', 3)], }), ); session.providers.setActive('noop'); session.modes.setActive('marker'); return session; } describe('runTurn turnId filtering', () => { it('forwards a custom model context window into the mode context', async () => { let observedWindow: number | undefined; const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic(definePlugin({ name: 'custom-model-context-test', version: '0.0.0', providers: [makeNoopProvider()], modes: [defineMode({ name: 'custom-window-echo', run: async function* (ctx: ModeContext): AsyncIterable { observedWindow = ctx.contextWindowOverride; await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: 'ok', stopReason: 'end_turn', }); }, })], })); session.providers.setActive('noop'); session.modes.setActive('custom-window-echo'); await collectTurn(session, 'hello', { model: 'vendor/model-v2', contextWindow: 200_000 }); expect(observedWindow).toBe(200_000); }); it('prepares dynamic provider metadata before the mode receives its context', async () => { const fallbackModels = [{ id: 'fallback', contextWindow: 8_192, supportsTools: true, supportsStreaming: true, }]; const clientModels = [...fallbackModels]; let prepared = 0; const client = { name: 'local', models: clientModels, prepareModel: async (model: string) => { prepared += 1; clientModels.splice(0, clientModels.length, { id: model, contextWindow: 4_096, supportsTools: true, supportsStreaming: true, }); }, stream: async function* () {}, countTokens: async () => 0, }; const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic(definePlugin({ name: 'prepared-provider-test', version: '0.0.0', providers: [defineProvider({ name: 'local', models: fallbackModels, createClient: () => client, })], modes: [defineMode({ name: 'context-window-echo', run: async function* (ctx: ModeContext): AsyncIterable { const descriptor = ctx.provider.models.find((candidate) => candidate.id === ctx.model); await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: String(descriptor?.contextWindow), }); }, })], })); session.providers.setActive('local'); session.modes.setActive('context-window-echo'); const events = await collectTurn(session, 'measure', { model: 'bielik' }); expect(prepared).toBe(1); expect(events.find((event) => event.type === 'assistant_message')).toMatchObject({ text: '4096', }); }); it('continues the last resolved session model when no model override is supplied', async () => { const models = [{ id: 'noop-default' }, { id: 'noop-sticky' }]; const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'test-sticky-model', version: '0.0.0', providers: [ defineProvider({ name: 'noop', models, createClient: () => ({ name: 'noop', models, stream: async function* () {}, countTokens: async () => 0, }), }), ], modes: [ defineMode({ name: 'model-echo', run: async function* (ctx: ModeContext): AsyncIterable { await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: ctx.model, }); }, }), ], }), ); session.providers.setActive('noop'); session.modes.setActive('model-echo'); session.lastResolvedModel = 'noop-sticky'; const events = await collectTurn(session, 'continue'); expect(events.find((e) => e.type === 'assistant_message')).toMatchObject({ text: 'noop-sticky', }); }); describe('the model a turn runs on when it names none', () => { const models = [{ id: 'noop-first' }, { id: 'noop-chosen' }, { id: 'noop-last' }, { id: 'noop-small' }]; const otherModels = [{ id: 'other-first' }, { id: 'other-chosen' }]; const modelEcho = (starterModel?: string): Session => { const starter = starterModel ? { starterModel } : {}; const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'test-default-model', version: '0.0.0', providers: [ defineProvider({ name: 'noop', models, ...starter, createClient: () => ({ name: 'noop', models, ...starter, stream: async function* () {}, countTokens: async () => 0 }), }), defineProvider({ name: 'other', models: otherModels, createClient: () => ({ name: 'other', models: otherModels, stream: async function* () {}, countTokens: async () => 0 }), }), ], modes: [ defineMode({ name: 'model-echo', run: async function* (ctx: ModeContext): AsyncIterable { await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: ctx.model, }); }, }), ], }), ); session.providers.setActive('noop'); session.modes.setActive('model-echo'); return session; }; const ranOn = async (session: Session, model?: string): Promise => (await collectTurn(session, 'go', model ? { model } : {})).find((e) => e.type === 'assistant_message'); it("is the one set as the provider's default, not the first the provider lists", async () => { const session = modelEcho(); session.defaultModels = { noop: 'noop-chosen' }; expect(session.getInfo().defaultModel).toBe('noop-chosen'); expect(await ranOn(session)).toMatchObject({ text: 'noop-chosen' }); }); it('stays the model the conversation last ran on, whatever the default says', async () => { const session = modelEcho(); session.defaultModels = { noop: 'noop-chosen' }; session.lastResolvedModel = 'noop-last'; expect(session.getInfo().defaultModel).toBe('noop-last'); expect(await ranOn(session)).toMatchObject({ text: 'noop-last' }); }); it("is the new provider's default once the conversation switches provider, never the old provider's model", async () => { const session = modelEcho(); session.defaultModels = { noop: 'noop-chosen', other: 'other-chosen' }; expect(await ranOn(session, 'noop-last')).toMatchObject({ text: 'noop-last' }); session.providers.setActive('other'); expect(session.getInfo().defaultModel).toBe('other-chosen'); expect(await ranOn(session)).toMatchObject({ text: 'other-chosen' }); expect(await ranOn(session, 'other-first')).toMatchObject({ text: 'other-first' }); expect(await ranOn(session)).toMatchObject({ text: 'other-first' }); }); it('gives way to the model the turn names', async () => { const session = modelEcho(); session.defaultModels = { noop: 'noop-chosen' }; expect(await ranOn(session, 'noop-first')).toMatchObject({ text: 'noop-first' }); }); it("is the provider's first model when no default is set, and a default for another provider is not used", async () => { const session = modelEcho(); session.defaultModels = { other: 'elsewhere' }; expect(session.getInfo().defaultModel).toBe('noop-first'); expect(await ranOn(session)).toMatchObject({ text: 'noop-first' }); }); it("is the provider's starter model when no default is set, not the first it lists", async () => { const session = modelEcho('noop-small'); expect(session.getInfo().defaultModel).toBe('noop-small'); expect(await ranOn(session)).toMatchObject({ text: 'noop-small' }); }); it('gives the starter model way to the default the person set and to the model the conversation ran on', async () => { const session = modelEcho('noop-small'); session.defaultModels = { noop: 'noop-chosen' }; expect(await ranOn(session)).toMatchObject({ text: 'noop-chosen' }); session.lastResolvedModel = 'noop-last'; expect(await ranOn(session)).toMatchObject({ text: 'noop-last' }); }); it('starts a new conversation (/new) on the starter model, not the one the old conversation ran on', async () => { const session = modelEcho('noop-small'); expect(await ranOn(session, 'noop-first')).toMatchObject({ text: 'noop-first' }); await session.reset(); expect(session.getInfo().defaultModel).toBe('noop-small'); expect(await ranOn(session)).toMatchObject({ text: 'noop-small' }); }); it("tells every surface each provider's starter model, also for a provider that is not active", () => { const session = modelEcho('noop-small'); session.providers.setActive('other'); const providers = session.getInfo().providers; expect(providers.find((p) => p.name === 'noop')?.starterModel).toBe('noop-small'); expect(providers.find((p) => p.name === 'other')).not.toHaveProperty('starterModel'); }); it('is the first model when the starter model is not among those the provider lists', async () => { const session = modelEcho('noop-retired'); expect(session.getInfo().defaultModel).toBe('noop-first'); expect(await ranOn(session)).toMatchObject({ text: 'noop-first' }); }); it('reports the starter model while the provider is replaced and not built again yet', () => { const session = modelEcho(); session.providers.replace( defineProvider({ name: 'noop', models, starterModel: 'noop-small', createClient: () => ({ name: 'noop', models, stream: async function* () {}, countTokens: async () => 0 }), }), ); expect(session.getInfo().defaultModel).toBe('noop-small'); }); it('is not reported while no provider is active', () => { expect(new Session({ cwd: '/tmp', silent: true }).getInfo().defaultModel).toBeUndefined(); }); }); it('a single turn surfaces all of its own events', async () => { const session = buildSession(); const events = await collectTurn(session, 'hi'); const turnIds = new Set(events.map((e) => e.turnId)); expect(turnIds.size).toBe(1); expect(events.filter((e) => e.type === 'assistant_message')).toHaveLength(3); }); it('two concurrent turns do not cross-contaminate', async () => { const session = buildSession(); const [eventsA, eventsB] = await Promise.all([ collectTurn(session, 'A'), collectTurn(session, 'B'), ]); const turnIdA = eventsA[0]?.turnId; const turnIdB = eventsB[0]?.turnId; expect(turnIdA).toBeDefined(); expect(turnIdB).toBeDefined(); expect(turnIdA).not.toBe(turnIdB); // Every event in each result must carry the same turnId as the first // event of that result. Without the filter at run-turn.ts, A's events // would include B's events and vice versa. expect(eventsA.every((e) => e.turnId === turnIdA)).toBe(true); expect(eventsB.every((e) => e.turnId === turnIdB)).toBe(true); // Each turn yields user_prompt + 3 assistant_message events. expect(eventsA.filter((e) => e.type === 'assistant_message')).toHaveLength(3); expect(eventsB.filter((e) => e.type === 'assistant_message')).toHaveLength(3); }); it('does not leak a subscription when startTurn throws after subscribe', async () => { const session = buildSession(); // Force startTurn to throw by removing the active loop strategy after // creating the session — getActive() will throw before we touch the log. session.modes.unregister('marker'); let listenerCountBefore = 0; let listenerCountAfter = 0; // Peek at the listener set size via subscribing/unsubscribing a no-op // (subscribe returns identity-keyed unsubscribers; we infer the leak by // running runTurn many times and checking the log still works normally). const probe = session.log.subscribe(() => {}); listenerCountBefore = 1; probe(); let threw = false; try { for await (const _ of runTurn(session, 'will fail')) { void _; } } catch { threw = true; } expect(threw).toBe(true); const probe2 = session.log.subscribe(() => {}); listenerCountAfter = 1; probe2(); // If runTurn leaked its subscription, the EventLog's listener count would // have grown; we can't observe that directly, but we can verify the next // turn still receives a clean event stream (no spurious replays). expect(listenerCountAfter).toBe(listenerCountBefore); }); }); describe('runTurn threads real cwd/env into onToolCall hooks', () => { it('the dispatchToolCall hook ctx carries the session cwd/env, not empty placeholders', async () => { const captured: { cwd?: string; envFoo?: string } = {}; const SESSION_CWD = '/tmp/policy-cwd'; // A mode that dispatches a single tool use through the shared dispatcher // (the same path default/goal use), so the onToolCall hook fires with the // ModeContext-derived cwd/env. const dispatchMode = defineMode({ name: 'dispatch-one', run: async function* (ctx: ModeContext): AsyncIterable { yield* executeToolUses(ctx, [{ id: 'c1', name: 'noop', input: {} }], 1); }, }); const session = new Session({ cwd: SESSION_CWD, silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'cwd-env-probe', version: '0.0.0', providers: [makeNoopProvider()], modes: [dispatchMode], tools: [ defineTool({ name: 'noop', description: '', inputSchema: z.object({}), handler: () => 'ok', }), ], hooks: { onToolCall: (ctx: ToolCallContext) => { captured.cwd = ctx.cwd; captured.envFoo = ctx.env.PATH; // a real env var that always exists }, }, }), ); session.providers.setActive('noop'); session.modes.setActive('dispatch-one'); await collectTurn(session, 'go'); // Previously hardcoded '' / {}, which silently defeated path-based policy // hooks. Must now be the real session cwd + a populated env. expect(captured.cwd).toBe(SESSION_CWD); expect(captured.envFoo).toBe(process.env.PATH); }); }); describe('runTurn worst-case hardening', () => { it('aborting iteration early aborts the strategy promptly (no full background run)', async () => { let observedAbort = false; // A mode that loops indefinitely until its signal aborts. If the consumer's // early `break` did NOT abort the turn, this would run forever and the // generator's `finally` would hang awaiting it. const foreverMode = defineMode({ name: 'forever', run: async function* (ctx: ModeContext): AsyncIterable { for (let i = 0; ; i++) { if (ctx.signal.aborted) { observedAbort = true; return; } await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: `tick-${i}`, }); await new Promise((r) => setTimeout(r, 5)); } }, }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'forever-plugin', version: '0.0.0', providers: [makeNoopProvider()], modes: [foreverMode], }), ); session.providers.setActive('noop'); session.modes.setActive('forever'); // Break out after the first event — the generator must abort the strategy // in its finally and return promptly (this await would never resolve if the // turn ran to its non-existent completion in the background). for await (const event of runTurn(session, 'go')) { if (event.type === 'assistant_message') break; } expect(observedAbort).toBe(true); expect(session.signal.aborted).toBe(false); // session-level signal untouched }); it('an abandoned turn does NOT apply a mode switch it requested before being abandoned', async () => { // A mode that immediately requests a hand-off, then loops until aborted and // returns CLEANLY (no throw) on `signal.aborted` — so strategyError stays // null. If the post-turn switch were gated only on `!strategyError`, an // abandoned (consumer-broke-early) turn would silently flip the session into // 'other' behind the user's back. It must stay on the original mode. const requestThenLoop = defineMode({ name: 'requester', run: async function* (ctx: ModeContext): AsyncIterable { ctx.requestModeSwitch('other'); for (let i = 0; ; i++) { if (ctx.signal.aborted) return; // clean return on abandonment await ctx.emit({ type: 'assistant_message', sessionId: ctx.sessionId, turnId: ctx.turnId, source: 'assistant', text: `tick-${i}`, }); await new Promise((r) => setTimeout(r, 5)); } }, }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'switch-on-abandon', version: '0.0.0', providers: [makeNoopProvider()], modes: [requestThenLoop, defineMode({ name: 'other', run: async function* () {} })], }), ); session.providers.setActive('noop'); session.modes.setActive('requester'); // Abandon after the first event — the strategy aborts and returns cleanly. for await (const event of runTurn(session, 'go')) { if (event.type === 'assistant_message') break; } // The requested switch must be DROPPED because the turn was abandoned. expect(session.modes.getActive().name).toBe('requester'); }); it('a completed turn still applies a requested mode switch', async () => { // The positive case: a mode that requests a switch and completes normally // hands off as before — the abandonment gate must not regress this. const requestThenDone = defineMode({ name: 'handoff', run: async function* (ctx: ModeContext): AsyncIterable { ctx.requestModeSwitch('target'); }, }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'switch-on-complete', version: '0.0.0', providers: [makeNoopProvider()], modes: [requestThenDone, defineMode({ name: 'target', run: async function* () {} })], }), ); session.providers.setActive('noop'); session.modes.setActive('handoff'); await collectTurn(session, 'go'); expect(session.modes.getActive().name).toBe('target'); }); it('fires turnEnd even when the strategy throws (paired with turnStart)', async () => { const calls: string[] = []; const throwingMode = defineMode({ name: 'throws', run: async function* (): AsyncIterable { throw new Error('strategy boom'); }, }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'lifecycle-probe', version: '0.0.0', providers: [makeNoopProvider()], modes: [throwingMode], hooks: { onTurnStart: () => { calls.push('start'); }, onTurnEnd: () => { calls.push('end'); }, }, }), ); session.providers.setActive('noop'); session.modes.setActive('throws'); let threw = false; try { await collectTurn(session, 'go'); } catch { threw = true; } expect(threw).toBe(true); // turnEnd must pair with turnStart even on the error path — no leaked // turn-scoped plugin state. expect(calls).toEqual(['start', 'end']); }); it('a missing active provider records the prompt + a structured error, then rejects', async () => { const session = new Session({ cwd: '/tmp', silent: true }); // No provider registered/active — getActive() throws. session.pluginHost.registerStatic( definePlugin({ name: 'mode-only', version: '0.0.0', modes: [makeMarkerLoop('marker', 1)], }), ); session.modes.setActive('marker'); let threw = false; try { await collectTurn(session, 'remember me'); } catch { threw = true; } expect(threw).toBe(true); // The user prompt is preserved (not silently discarded) and a structured // error event was logged so channels see a normal failed turn. const events = session.log.slice(); const prompt = events.find((e) => e.type === 'user_prompt'); expect((prompt as { text?: string } | undefined)?.text).toBe('remember me'); const error = events.find((e) => e.type === 'error'); expect(error).toBeDefined(); expect((error as { kind?: string }).kind).toBe('fatal'); }); it('a provider advertising no models fails fast (no opaque "default" model id)', async () => { const emptyModelsProvider = defineProvider({ name: 'empty', models: [], createClient: () => ({ name: 'empty', models: [], stream: async function* () {}, countTokens: async () => 0, }), }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'empty-models', version: '0.0.0', providers: [emptyModelsProvider], modes: [makeMarkerLoop('marker', 1)], }), ); session.providers.setActive('empty'); session.modes.setActive('marker'); await expect(collectTurn(session, 'go')).rejects.toThrow(/no models configured/i); // lastResolvedModel never gets the bogus sentinel. expect(session.lastResolvedModel).toBeNull(); }); }); describe('runTurn with a skill called by an @ mention', () => { function buildMentionSession(seen: { tools?: string[]; reached?: string; prompt?: MoxxyEvent }): Session { const session = new Session({ cwd: '/tmp', silent: true }); const tool = (name: string) => defineTool({ name, description: name, inputSchema: z.object({}), handler: async () => name }); session.pluginHost.registerStatic(definePlugin({ name: 'mention-test', version: '0.0.0', providers: [makeNoopProvider()], tools: [tool('browser_click'), tool('computer_click')], modes: [defineMode({ name: 'mention-echo', run: async function* (ctx: ModeContext): AsyncIterable { seen.tools = ctx.tools.list().map((t) => t.name); seen.reached = await ctx.tools.execute('browser_click', {}, ctx.signal).then(String, (err: Error) => err.message); seen.prompt = ctx.log.slice().find((e) => e.type === 'user_prompt' && e.turnId === ctx.turnId); }, })], })); session.skills.register({ id: asSkillId('plugin/computer-control'), path: '/skills/computer-control.md', scope: 'plugin', frontmatter: { name: 'computer-control', description: 'desktop apps', aliases: ['computer-use'], 'disallowed-tools': ['browser_*'] }, body: 'Drive the desktop app the user named.', }); session.providers.setActive('noop'); session.modes.setActive('mention-echo'); return session; } it('hands the turn the skill and keeps the in-window browser out of it', async () => { const seen: { tools?: string[]; reached?: string; prompt?: MoxxyEvent } = {}; await collectTurn(buildMentionSession(seen), '@computer_use otwórz Canvę w Arc'); expect(seen.tools).toEqual(['computer_click']); expect(seen.reached).toMatch(/browser_click is off for this request/); expect(seen.prompt).toMatchObject({ text: '@computer_use otwórz Canvę w Arc', attachments: [{ kind: 'file', name: 'computer-control skill' }], }); }); it('leaves a prompt without the mention, and the next turn, as they were', async () => { const seen: { tools?: string[]; reached?: string; prompt?: MoxxyEvent } = {}; const session = buildMentionSession(seen); await collectTurn(session, '@computer_use otwórz Arc'); await collectTurn(session, 'otwórz stronę'); expect(seen.tools).toEqual(['browser_click', 'computer_click']); expect(seen.reached).toBe('browser_click'); expect(seen.prompt).not.toHaveProperty('attachments'); }); it('keeps the withheld tools out of the sub-agents the turn starts', async () => { const seen: { tools?: string[]; reached?: string; prompt?: MoxxyEvent } = {}; const session = buildMentionSession(seen); const child: { tools?: string[]; reached?: string; filtered?: string[] } = {}; session.pluginHost.registerStatic(definePlugin({ name: 'mention-subagents', version: '0.0.0', modes: [ defineMode({ name: 'tools-echo', run: async function* (ctx: ModeContext): AsyncIterable { const names = ctx.tools.list().map((t) => t.name); if (ctx.systemPrompt === 'filtered') { child.filtered = names; return; } child.tools = names; child.reached = await ctx.tools.execute('browser_click', {}, ctx.signal).then(String, (err: Error) => err.message); }, }), defineMode({ name: 'spawn-child', run: async function* (ctx: ModeContext): AsyncIterable { await ctx.subagents?.spawn({ prompt: 'look', mode: 'tools-echo' }); await ctx.subagents?.spawn({ prompt: 'look', mode: 'tools-echo', systemPrompt: 'filtered', allowedTools: ['browser_click', 'computer_click'] }); }, }), ], })); session.modes.setActive('spawn-child'); await collectTurn(session, '@computer_use otwórz Arc'); expect(child.tools).toEqual(['computer_click']); expect(child.reached).toMatch(/browser_click is off for this request/); expect(child.filtered).toEqual(['computer_click']); }); it('does not take a mention from a prompt a trigger wrote', async () => { const seen: { tools?: string[]; reached?: string; prompt?: MoxxyEvent } = {}; await collectTurn(buildMentionSession(seen), 'webhook payload: @computer_use', { origin: { kind: 'webhook', name: 'gh' } }); expect(seen.tools).toEqual(['browser_click', 'computer_click']); expect(seen.prompt).not.toHaveProperty('attachments'); }); }); describe('runTurn with tools meant for one mode', () => { // goal_abandon is goal mode's own way out; offered in a plain browser task, // the model took it and gave up on work it could do. function buildModesSession(seen: Record): Session { const session = new Session({ cwd: '/tmp', silent: true }); const tool = (name: string, modes?: string[]) => defineTool({ name, description: name, inputSchema: z.object({}), handler: async () => name, ...(modes ? { modes } : {}) }); const echo = (name: string, spawn?: string) => defineMode({ name, run: async function* (ctx: ModeContext): AsyncIterable { seen[name] = { tools: ctx.tools.list().map((t) => t.name), reached: await ctx.tools.execute('goal_abandon', {}, ctx.signal).then(String, (err: Error) => err.message), }; if (spawn) await ctx.subagents?.spawn({ prompt: 'look', mode: spawn }); }, }); session.pluginHost.registerStatic(definePlugin({ name: 'modes-test', version: '0.0.0', providers: [makeNoopProvider()], tools: [tool('Read'), tool('goal_abandon', ['goal'])], modes: [echo('default'), echo('goal', 'default')], })); session.providers.setActive('noop'); return session; } it('leaves a tool meant for another mode out of the turn', async () => { const seen: Record = {}; const session = buildModesSession(seen); session.modes.setActive('default'); await collectTurn(session, 'otwórz stronę'); expect(seen['default']?.tools).toEqual(['Read']); expect(seen['default']?.reached).toMatch(/goal_abandon is not available in default mode/); }); it('offers it in its own mode, and a sub-agent sees the tools of the mode it runs', async () => { const seen: Record = {}; const session = buildModesSession(seen); session.modes.setActive('goal'); await collectTurn(session, 'zrób to'); expect(seen['goal']).toEqual({ tools: ['Read', 'goal_abandon'], reached: 'goal_abandon' }); expect(seen['default']?.tools).toEqual(['Read']); }); }); describe('runTurn — a question left waiting when the person writes again', () => { const colour = { id: 'q1', question: 'Which colour?', options: [{ id: 'red', label: 'Red' }], multiSelect: false, allowOther: true, }; /** A mode whose first turn asks and reports what came back; later turns just end. */ function sessionThatAsks(outcomes: unknown[]): Session { const asker = defineMode({ name: 'asker', run: async function* (ctx: ModeContext): AsyncIterable { if (ctx.log.ofType('user_prompt').length > 1) return; outcomes.push(ctx.ask ? await ctx.ask([colour]) : 'no ask'); }, }); const session = new Session({ cwd: '/tmp', silent: true }); session.pluginHost.registerStatic( definePlugin({ name: 'asking-mode', version: '0.0.0', providers: [makeNoopProvider()], modes: [asker] }), ); session.providers.setActive('noop'); session.modes.setActive('asker'); session.questions.attachSurface(); return session; } const openQuestions = (session: Session) => session.log.ofType('plugin_event').filter((e) => e.subtype === 'question_asked').length - session.log.ofType('plugin_event').filter((e) => e.subtype === 'question_resolved').length; it("closes the earlier turn's question, so that turn ends instead of holding the conversation", async () => { const outcomes: unknown[] = []; const session = sessionThatAsks(outcomes); const first = collectTurn(session, 'fix the page'); await new Promise((resolve) => setTimeout(resolve, 20)); expect(openQuestions(session)).toBe(1); await collectTurn(session, 'did you build the new dist?'); await first; expect(outcomes).toEqual([{ kind: 'dismissed', reason: 'cancelled', note: 'new-message' }]); expect(openQuestions(session)).toBe(0); }); it('leaves the question open for a turn the agent started by itself', async () => { const outcomes: unknown[] = []; const session = sessionThatAsks(outcomes); void collectTurn(session, 'fix the page'); await new Promise((resolve) => setTimeout(resolve, 20)); await collectTurn(session, 'List files finished in the background', { origin: { kind: 'agent', name: 'List files finished in the background' } }); expect(outcomes).toEqual([]); expect(openQuestions(session)).toBe(1); }); });