Skip to content

Open-source, local-first AI agent for real work.

21.7 KB
Raw Blame
import {
	AI_ERROR_CODES,
	AIError,
	type AssistantMessage,
	AssistantMessageEventStream,
	getAIErrorDetails,
	type Message,
	type Model,
	type UserMessage,
} from "@vetta/ai";
import { describe, expect, it } from "vitest";
import {
	AgentCoreTurnEngine,
	type RuntimeSnapshot,
	type RuntimeToolDefinition,
	type SessionContextRecord,
	SessionInputQueue,
	type SessionInputQueueSnapshot,
	type TurnEngineEvent,
	type TurnEnginePort,
} from "../../src/kernel/index.js";
import { StatelessAgentCoreTurnEngine } from "../../src/kernel/stateless-agent-core-turn-engine.js";

describe("StatelessAgentCoreTurnEngine", () => {
	it("does not announce or invoke a provider when cancelled during credential preparation", async () => {
		const abort = new AbortController();
		const observations: unknown[] = [];
		let providerCalls = 0;
		let resolveCredentials: (value: string) => void = () => undefined;
		let markPreparing: () => void = () => undefined;
		const credentials = new Promise<string>((resolve) => {
			resolveCredentials = resolve;
		});
		const preparing = new Promise<void>((resolve) => {
			markPreparing = resolve;
		});
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			resolveApiKey: () => {
				markPreparing();
				return credentials;
			},
			streamFn: () => {
				providerCalls += 1;
				return recordedStream(assistant([{ type: "text", text: "hello" }]));
			},
		});
		const execution = (async () => {
			for await (const _event of engine.execute({
				sessionId: "session-1",
				turnId: "turn-1",
				snapshot: snapshot(),
				messages: [user("hello")],
				signal: abort.signal,
				reportObservation: async (observation) => {
					observations.push(observation);
				},
			})) {
				/* Drain the terminal cancellation events. */
			}
		})();
		const cancelled = expect(execution).rejects.toMatchObject({ name: "AbortError" });
		await preparing;
		abort.abort();
		resolveCredentials("test-key");
		await cancelled;
		expect(observations).toEqual([]);
		expect(providerCalls).toBe(0);
	});

	it("announces the provider request after credentials and context preparation, before opening the stream", async () => {
		const order: string[] = [];
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			resolveApiKey: async () => {
				order.push("credentials");
				return "test-key";
			},
			streamFn: () => {
				order.push("provider");
				return recordedStream(assistant([{ type: "text", text: "hello" }]));
			},
		});
		const events: TurnEngineEvent[] = [];
		for await (const event of engine.execute({
			sessionId: "session-1",
			turnId: "turn-1",
			snapshot: {
				...snapshot(),
				contextCompositionPublisher: {
					publishContextComposition: async (report) => {
						if (report.phase === "prepared") order.push("context");
					},
				},
			},
			messages: [user("hello")],
			signal: new AbortController().signal,
			reportObservation: async (observation) => {
				expect(observation).toMatchObject({ type: "model.request.started", modelCallIndex: 0 });
				order.push("request-start");
			},
		}))
			events.push(event);
		expect(order).toEqual(["credentials", "context", "request-start", "provider"]);
		expect(events.at(-1)).toMatchObject({ type: "completed" });
	});

	it("keeps the production facade aligned with the stateless text projection", async () => {
		const response = assistant([{ type: "text", text: "done" }]);
		const legacy = await run(new AgentCoreTurnEngine(options([response])), snapshot());
		const modern = await run(new StatelessAgentCoreTurnEngine(options([response])), snapshot());

		expect(canonicalEvents(modern)).toEqual(canonicalEvents(legacy));
	});

	it("keeps the production facade aligned with the stateless tool-loop projection", async () => {
		const responses = [
			assistant([{ type: "toolCall", id: "call-1", name: "echo", arguments: { value: "hello" } }], "toolUse"),
			assistant([{ type: "text", text: "finished" }]),
		];
		const tool: RuntimeToolDefinition = {
			name: "echo",
			label: "Echo",
			description: "Echo a value",
			inputSchema: {
				type: "object",
				properties: { value: { type: "string" } },
				required: ["value"],
			},
			async execute({ input, onUpdate, reportPhase }) {
				reportPhase?.("reading");
				onUpdate?.({ content: [{ type: "text", text: "partial" }], details: { stage: "reading" } });
				return { content: [{ type: "text", text: String(input.value) }], details: { stage: "done" } };
			},
		};
		const legacy = await run(new AgentCoreTurnEngine(options(responses)), snapshot([tool]));
		const modern = await run(new StatelessAgentCoreTurnEngine(options(responses)), snapshot([tool]));

		expect(canonicalEvents(modern)).toEqual(canonicalEvents(legacy));
	});

	it("completes more than 100 model calls with the default limits", async () => {
		const toolRounds = 101;
		let toolExecutions = 0;
		const responses = Array.from({ length: toolRounds }, (_, index) =>
			assistant([{ type: "toolCall", id: `call-${index + 1}`, name: "repeat", arguments: {} }], "toolUse"),
		);
		responses.push(assistant([{ type: "text", text: "completed after the legacy default" }]));
		const tool: RuntimeToolDefinition = {
			name: "repeat",
			label: "Repeat",
			description: "Repeat",
			inputSchema: { type: "object" },
			async execute() {
				toolExecutions += 1;
				return { content: [{ type: "text", text: "done" }] };
			},
		};

		const events = await run(new StatelessAgentCoreTurnEngine(options(responses)), snapshot([tool]));

		expect(toolExecutions).toBe(toolRounds);
		expect(events.at(-1)).toMatchObject({ type: "completed", stopReason: "stop" });
	});

	it("executes more than 1000 tool calls with the default limits", async () => {
		const toolCalls = 1_001;
		let toolExecutions = 0;
		const responses = [
			assistant(
				Array.from({ length: toolCalls }, (_, index) => ({
					type: "toolCall" as const,
					id: `call-${index + 1}`,
					name: "repeat",
					arguments: {},
				})),
				"toolUse",
			),
			assistant([{ type: "text", text: "completed after the legacy tool-call default" }]),
		];
		const tool: RuntimeToolDefinition = {
			name: "repeat",
			label: "Repeat",
			description: "Repeat",
			inputSchema: { type: "object" },
			async execute() {
				toolExecutions += 1;
				return { content: [{ type: "text", text: "done" }] };
			},
		};

		const events = await run(new StatelessAgentCoreTurnEngine(options(responses)), snapshot([tool]));

		expect(toolExecutions).toBe(toolCalls);
		expect(events.at(-1)).toMatchObject({ type: "completed", stopReason: "stop" });
	});

	it("keeps checkpoint provider messages separate from subsequent Runtime context", async () => {
		const contexts: Message[][] = [];
		const responses = [
			assistant([{ type: "toolCall", id: "call-1", name: "echo", arguments: { value: "hello" } }], "toolUse"),
			assistant([{ type: "text", text: "done" }]),
		];
		let responseIndex = 0;
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: (_model, context) => {
				contexts.push([...context.messages]);
				const response = responses[responseIndex];
				if (!response) throw new Error(`Missing response at index ${responseIndex}`);
				responseIndex += 1;
				return recordedStream(response);
			},
		});
		const durable = user("durable");
		const events: TurnEngineEvent[] = [];
		let modelCheckpoints = 0;
		const modelCallIndexes: number[] = [];
		const tool: RuntimeToolDefinition = {
			name: "echo",
			label: "Echo",
			description: "Echo",
			inputSchema: { type: "object" },
			async execute() {
				return { content: [{ type: "text", text: "echoed" }] };
			},
		};

		for await (const event of engine.execute({
			sessionId: "session-1",
			turnId: "turn-1",
			snapshot: snapshot([tool]),
			messages: [user("initial")],
			signal: new AbortController().signal,
			checkpoint: async ({ reason, messages, modelCallIndex }) => {
				if (reason !== "model_call") return { messages };
				if (modelCallIndex === undefined) throw new Error("Missing model call index");
				modelCallIndexes.push(modelCallIndex);
				modelCheckpoints += 1;
				return modelCheckpoints === 1 ? { messages: [user("provider")], contextMessages: [durable] } : { messages };
			},
		})) {
			events.push(event);
		}

		expect(contexts[0]).toEqual([user("provider")]);
		expect(contexts[1]?.map(({ role }) => role)).toEqual(["user", "assistant", "toolResult"]);
		expect(contexts[1]?.[0]).toEqual(durable);
		expect(modelCallIndexes).toEqual([0, 1]);
		expect(
			events
				.filter(
					(event): event is Extract<TurnEngineEvent, { type: "execution_observation" }> =>
						event.type === "execution_observation",
				)
				.find(({ observation }) => observation.type === "agent.end"),
		).toMatchObject({
			observation: {
				type: "agent.end",
				messages: [
					{ kind: "message", message: { role: "assistant" } },
					{ kind: "message", message: { role: "toolResult" } },
					{ kind: "message", message: { role: "assistant" } },
				],
			},
		});
	});

	it("delivers queued context via appendQueuedContext without duplicating it as a message event", async () => {
		const queue = new SessionInputQueue();
		const record: SessionContextRecord = {
			type: "prompt_attachment_context",
			content: "<prompt_attachments>[]</prompt_attachments>",
			modelVisible: true,
			display: false,
		};
		queue.steer({ message: user("badge too big"), context: [record] });

		const contexts: Message[][] = [];
		const responses = [
			assistant([{ type: "toolCall", id: "call-1", name: "echo", arguments: { value: "hi" } }], "toolUse"),
			assistant([{ type: "text", text: "done" }]),
		];
		let responseIndex = 0;
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: (_model, context) => {
				contexts.push([...context.messages]);
				const response = responses[responseIndex];
				if (!response) throw new Error(`Missing response at index ${responseIndex}`);
				responseIndex += 1;
				return recordedStream(response);
			},
		});
		const tool: RuntimeToolDefinition = {
			name: "echo",
			label: "Echo",
			description: "Echo",
			inputSchema: { type: "object" },
			async execute() {
				return { content: [{ type: "text", text: "echoed" }] };
			},
		};
		const appended: SessionContextRecord[][] = [];
		const events: TurnEngineEvent[] = [];
		for await (const event of engine.execute({
			sessionId: "session-1",
			turnId: "turn-1",
			snapshot: snapshot([tool]),
			messages: [user("hello")],
			signal: new AbortController().signal,
			inputQueue: queue,
			appendQueuedContext: async (records) => {
				appended.push([...records]);
			},
		})) {
			events.push(event);
		}

		// context 经 appendQueuedContext 落盘一次,不再以 message 事件双份持久化。
		expect(appended).toEqual([[record]]);
		const userMessages = events.filter(
			(event): event is Extract<TurnEngineEvent, { type: "message" }> =>
				event.type === "message" && event.message.role === "user",
		);
		expect(userMessages).toHaveLength(1);
		expect(userMessages[0]?.message.content).toBe("badge too big");
		// 模型在注入点仍按「context 在前、user 消息在后」看到两者。
		const injected = contexts[1]?.map(({ role, content }) => ({ role, content }));
		expect(injected).toContainEqual({ role: "user", content: record.content });
		expect(injected).toContainEqual({ role: "user", content: "badge too big" });
		expect((injected ?? []).findIndex(({ content }) => content === record.content)).toBeLessThan(
			(injected ?? []).findIndex(({ content }) => content === "badge too big"),
		);
	});

	it("rejects provider failures without consuming queued follow-up input", async () => {
		const queue = new SessionInputQueue();
		queue.followUp({ message: user("retry later") });
		const failure = new AIError(AI_ERROR_CODES.RATE_LIMITED, "provider quota exceeded", {
			retryable: true,
			statusCode: 429,
			provider: "openai",
			modelId: "recorded-model",
			requestId: "request-1",
		});
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: () => errorStream(assistant([{ type: "text", text: "failed" }], "error"), failure),
		});

		await expect(run(engine, snapshot(), queue)).rejects.toMatchObject({
			name: AI_ERROR_CODES.RATE_LIMITED,
			message: "provider quota exceeded",
			failure: {
				code: AI_ERROR_CODES.RATE_LIMITED,
				retryable: true,
				origin: "provider",
				details: {
					statusCode: 429,
					provider: "openai",
					modelId: "recorded-model",
					requestId: "request-1",
				},
			},
		});
		expect(queue.pendingCount).toBe(1);
	});

	it("normalizes a provider-returned assistant error into a structured turn failure", async () => {
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: () =>
				recordedStream({
					...assistant([{ type: "text", text: "upstream failed" }], "error"),
					errorMessage: "upstream failed",
				}),
		});

		await expect(run(engine, snapshot())).rejects.toMatchObject({
			failure: { code: "PROVIDER_ERROR", message: "upstream failed", origin: "provider", retryable: false },
		});
	});

	it("preserves a provider error returned as a failed agent result without failure metadata", async () => {
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: () =>
				recordedStream({
					...assistant([{ type: "text", text: "quota exhausted" }], "error"),
					errorMessage: "quota exhausted",
				}),
		});

		await expect(run(engine, snapshot())).rejects.toMatchObject({
			failure: { code: "PROVIDER_ERROR", message: "quota exhausted", origin: "provider", retryable: false },
		});
	});

	it("propagates cancellation to the provider stream and rejects the turn", async () => {
		const controller = new AbortController();
		let markStarted: (() => void) | undefined;
		const started = new Promise<void>((resolve) => {
			markStarted = resolve;
		});
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: (_model, _context, streamOptions) => {
				const stream = new AssistantMessageEventStream();
				streamOptions?.signal?.addEventListener(
					"abort",
					() => stream.push({ type: "error", reason: "aborted", error: assistant([], "aborted") }),
					{ once: true },
				);
				markStarted?.();
				return stream;
			},
		});
		const execution = run(engine, snapshot(), undefined, controller.signal);
		await started;

		controller.abort("cancelled by test");

		await expect(execution).rejects.toMatchObject({ name: "AbortError" });
	});

	it("never mirrors continuation-policy messages through the user input queue", async () => {
		// 续跑消息一旦进 inputQueue,queue.changed 镜像(ADR-0060)就会在 UI 上补出
		// 一个用户气泡,而规范历史按 origin 过滤掉它 —— 两侧永远对不上账。
		const snapshots: SessionInputQueueSnapshot[] = [];
		const queue = new SessionInputQueue({ onChange: (entry) => snapshots.push(entry) });
		queue.followUp({ message: user("user follow-up"), messageId: "user-follow-up-id" });
		let collected = false;
		const continuationPolicy = {
			async collect() {
				if (collected) return [];
				collected = true;
				return [{ message: user("CONTINUE_INTERNAL"), source: "model-length" }];
			},
		};
		const responses = [
			assistant([{ type: "text", text: "first" }]),
			assistant([{ type: "text", text: "second" }]),
			assistant([{ type: "text", text: "third" }]),
		];
		const contexts: Message[][] = [];
		let responseIndex = 0;
		const engine = new StatelessAgentCoreTurnEngine({
			model: model(),
			streamFn: (_model, context) => {
				contexts.push([...context.messages]);
				const response = responses[responseIndex];
				if (!response) throw new Error(`Missing response at index ${responseIndex}`);
				responseIndex += 1;
				return recordedStream(response);
			},
		});

		const events = await run(engine, { ...snapshot(), continuationPolicy }, queue);

		// 用户可见投影只保留非 internal 条目;续跑消息必须被标记为 internal。
		const visible = snapshots.flatMap((entry) =>
			entry.entries.filter((queued) => !queued.internal).map((queued) => queued.input.message?.content),
		);
		expect(visible).toContain("user follow-up");
		expect(visible).not.toContain("CONTINUE_INTERNAL");
		const continuationEntries = snapshots.flatMap((entry) =>
			entry.entries.filter((queued) => queued.input.message?.content === "CONTINUE_INTERNAL"),
		);
		expect(continuationEntries.length).toBeGreaterThan(0);
		expect(continuationEntries.every((queued) => queued.internal === true)).toBe(true);
		// 仍然进入模型上下文,并带 continuation 溯源。
		expect(contexts.at(-1)?.some(({ content }) => content === "CONTINUE_INTERNAL")).toBe(true);
		const continuation = events.find(
			(event) => event.type === "message" && event.message.content === "CONTINUE_INTERNAL",
		);
		expect(continuation && "origin" in continuation ? continuation.origin : undefined).toEqual({
			kind: "continuation",
			source: "model-length",
		});
		const userFollowUp = events.find(
			(event) => event.type === "message" && event.message.content === "user follow-up",
		);
		expect(userFollowUp).toMatchObject({ messageId: "user-follow-up-id" });
	});
});

function options(responses: readonly AssistantMessage[]) {
	let index = 0;
	return {
		model: model(),
		streamFn: () => {
			const response = responses[index];
			if (!response) throw new Error(`Missing response at index ${index}`);
			index += 1;
			return recordedStream(response);
		},
	};
}

function recordedStream(message: AssistantMessage): AssistantMessageEventStream {
	const stream = new AssistantMessageEventStream();
	queueMicrotask(() => {
		stream.push({
			type: "done",
			reason: message.stopReason === "toolUse" ? "toolUse" : "stop",
			message,
		});
	});
	return stream;
}

function errorStream(message: AssistantMessage, failure?: AIError): AssistantMessageEventStream {
	const stream = new AssistantMessageEventStream();
	queueMicrotask(() =>
		stream.push({
			type: "error",
			reason: "error",
			error: message,
			...(failure ? { failure: getAIErrorDetails(failure) } : {}),
		}),
	);
	return stream;
}

function model(): Model<"openai-responses"> {
	return {
		id: "recorded-model",
		name: "Recorded Model",
		api: "openai-responses",
		provider: "openai",
		baseUrl: "https://example.invalid",
		reasoning: false,
		input: ["text"],
		cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
		contextWindow: 8_000,
		maxTokens: 1_000,
	};
}

function snapshot(tools: readonly RuntimeToolDefinition[] = []): RuntimeSnapshot {
	return {
		id: "snapshot-1",
		instructions: [{ id: "base", content: "Base instruction", priority: 0 }],
		tools: new Map(tools.map((tool) => [tool.name, tool])),
		contextProviders: [],
		contextStrategy: {
			async prepare(input) {
				return { messages: input.messages, estimatedTokens: 0 };
			},
		},
		toolPolicy: { authorize: async () => true },
		tokenBudget: 8_000,
		reservedOutputTokens: 1_000,
		observers: [],
	};
}

function user(content: string): UserMessage {
	return { role: "user", content, timestamp: 1 };
}

function assistant(
	content: AssistantMessage["content"],
	stopReason: AssistantMessage["stopReason"] = "stop",
): AssistantMessage {
	return {
		role: "assistant",
		content,
		api: "openai-responses",
		provider: "openai",
		model: "recorded-model",
		usage: {
			input: 1,
			output: 1,
			cacheRead: 0,
			cacheWrite: 0,
			totalTokens: 2,
			cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
		},
		stopReason,
		timestamp: 2,
	};
}

async function run(
	engine: TurnEnginePort,
	runtimeSnapshot: RuntimeSnapshot,
	inputQueue?: SessionInputQueue,
	signal: AbortSignal = new AbortController().signal,
): Promise<TurnEngineEvent[]> {
	const events: TurnEngineEvent[] = [];
	for await (const event of engine.execute({
		sessionId: "session-1",
		turnId: "turn-1",
		snapshot: runtimeSnapshot,
		messages: [user("hello")],
		signal,
		inputQueue,
	})) {
		events.push(event);
	}
	return events;
}

function canonicalEvents(events: readonly TurnEngineEvent[]): unknown[] {
	return events.map((event) => {
		if (event.type === "message") {
			return { type: event.type, role: event.message.role, content: event.message.content, origin: event.origin };
		}
		if (event.type === "completed") return event;
		if (event.type === "observation") {
			return {
				type: event.type,
				observation: canonicalObservation(event.observation),
			};
		}
		return {
			type: event.type,
			observation: canonicalObservation(event.observation),
		};
	});
}

function canonicalObservation(
	observation: Exclude<TurnEngineEvent, { type: "message" } | { type: "completed" }>["observation"],
): unknown {
	if (observation.type === "tool.execution.start" || observation.type === "tool.start") {
		return { type: observation.type, toolCallId: observation.toolCallId, toolName: observation.toolName };
	}
	if (observation.type === "tool.execution.update" || observation.type === "tool.update") {
		return { type: observation.type, toolCallId: observation.toolCallId, toolName: observation.toolName };
	}
	if (observation.type === "tool.execution.phase" || observation.type === "tool.phase") {
		return { type: observation.type, toolCallId: observation.toolCallId, label: observation.label };
	}
	if (observation.type === "tool.execution.end" || observation.type === "tool.end") {
		return { type: observation.type, toolCallId: observation.toolCallId, isError: observation.isError };
	}
	if (observation.type === "message.start" || observation.type === "message.end") {
		return { type: observation.type, kind: observation.message.kind };
	}
	if (observation.type === "message.update") return { type: observation.type };
	if (observation.type === "turn.end") {
		return {
			type: observation.type,
			stopReason: observation.message.role === "assistant" ? observation.message.stopReason : undefined,
			tools: observation.toolResults.length,
		};
	}
	if (observation.type === "agent.end") return { type: observation.type, messages: observation.messages.length };
	if (observation.type === "lifecycle") return { type: observation.type, phase: observation.phase };
	return { type: observation.type };
}