Repository navigation
Expand file tree
/
Copy pathloop-engine.test.ts
More file actions
180 lines (163 loc) · 8.26 KB
/
Copy pathloop-engine.test.ts
File metadata and controls
180 lines (163 loc) · 8.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
/**
* loop-engine 单元测试
*
* 测试 ReAct Loop 引擎的核心功能:
* - 单轮执行 (runTurn)
* - 主循环 (runLoop) 退出条件
* - 退出摘要构建
*/
import { describe, it, expect, mock, beforeEach } from "bun:test";
import type { Message, LoopState, ApiResponse, ApiUsage } from "../src/types.js";
import type { LoopConfig } from "../src/config.js";
// 构造基础 config
function makeConfig(overrides: Partial<LoopConfig> = {}): LoopConfig {
return {
model: "deepseek-chat", maxTurns: 50, mode: "auto", endpoint: "native",
api: { baseUrl: "https://api.deepseek.com", timeoutMs: 120000, maxRetries: 3, retryDelayMs: 1000 },
thinking: { enabled: true, autoDisableThreshold: 0.95 },
budget: { compactionThreshold: 0.90, hardStopThreshold: 0.98, budgetLimit: null },
tools: { bashTimeoutMs: 60000, bashMaxOutputBytes: 51200, bashDeadlineMs: 2000, readMaxLines: 2000, globMaxResults: 500, grepMaxResults: 250 },
guard: { enabled: true },
convergence: { idleRoundsThreshold: 3, consecutiveErrorThreshold: 4, stagnantOutputHashWindow: 3, taskCompletionMinConfidence: 0.8 },
output: { color: false, progressIntervalMs: 5000, summaryOnExit: true },
...overrides,
};
}
function makeApiResponse(overrides: Partial<ApiResponse> = {}): ApiResponse {
return {
content: "hello", reasoningContent: "thinking...", toolCalls: [],
finishReason: "stop",
usage: { promptTokens: 100, completionTokens: 50, reasoningTokens: 200 },
...overrides,
};
}
function makeState(overrides: Partial<LoopState> = {}): LoopState {
return {
turn: 1, maxTurns: 50,
budget: { promptTokens: 0, completionTokens: 0, reasoningTokens: 0, maxContext: 128000, used: 0 },
messages: [], interrupted: false, idleRoundsCounter: 0,
consecutiveBashErrors: 0, recentOutputHashes: [], lastFinishReason: null,
toolCallStatsThisTurn: { total: 0, blocked: 0, succeeded: 0 },
...overrides,
};
}
describe("loop-engine", () => {
describe("runTurn", () => {
it("should call chatFn and return response", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runTurn } = await import("../src/loop-engine.js");
const messages: Message[] = [{ role: "user", content: "hello" }];
const state = makeState();
const config = makeConfig();
const result = await runTurn(messages, state, config, chatFn);
expect(result.response.content).toBe("hello");
expect(chatFn).toHaveBeenCalledTimes(1);
expect(result.terminate).toBe(false);
});
it("should increment idle counter when no tool calls", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState({ idleRoundsCounter: 0 });
const result = await runTurn([{ role: "user", content: "hi" }], state, makeConfig(), chatFn);
expect(state.idleRoundsCounter).toBe(1);
});
it("should update budget with usage from API response", async () => {
const chatFn = mock(async () => makeApiResponse({
usage: { promptTokens: 500, completionTokens: 300, reasoningTokens: 200 },
}));
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
await runTurn([{ role: "user", content: "test" }], state, makeConfig(), chatFn);
expect(state.budget.promptTokens).toBe(500);
expect(state.budget.completionTokens).toBe(300);
expect(state.budget.reasoningTokens).toBe(200);
expect(state.budget.used).toBe(1000);
});
it("should set lastFinishReason from API response", async () => {
const chatFn = mock(async () => makeApiResponse({ finishReason: "stop" }));
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
await runTurn([{ role: "user", content: "test" }], state, makeConfig(), chatFn);
expect(state.lastFinishReason).toBe("stop");
});
it("should reset consecutiveBashErrors on non-bash-tool turn", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState({ consecutiveBashErrors: 3 });
await runTurn([{ role: "user", content: "test" }], state, makeConfig(), chatFn);
expect(state.consecutiveBashErrors).toBe(0);
});
it("should append tool_call messages to returned messages array", async () => {
const chatFn = mock(async () => makeApiResponse({
toolCalls: [
{ id: "call_1", type: "function" as const, index: 0, function: { name: "read", arguments: '{"file_path":"/tmp/test"}' } },
],
}));
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
const result = await runTurn([{ role: "user", content: "read file" }], state, makeConfig(), chatFn);
// Should have appended assistant message + tool result message
expect(result.messages.length).toBe(3);
});
it("should track tool call stats per turn", async () => {
const chatFn = mock(async () => makeApiResponse({
toolCalls: [
{ id: "call_1", type: "function" as const, index: 0, function: { name: "read", arguments: '{"file_path":"/tmp/test"}' } },
{ id: "call_2", type: "function" as const, index: 1, function: { name: "grep", arguments: '{"pattern":"foo"}' } },
],
}));
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
await runTurn([{ role: "user", content: "read and grep" }], state, makeConfig(), chatFn);
expect(state.toolCallStatsThisTurn.total).toBe(2);
});
it("should return empty toolResults when no tool calls are present", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
const result = await runTurn([{ role: "user", content: "hi" }], state, makeConfig(), chatFn);
expect(result.toolResults).toEqual([]);
});
it("should record hash in recentOutputHashes for stagnant detection", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runTurn } = await import("../src/loop-engine.js");
const state = makeState();
await runTurn([{ role: "user", content: "task" }], state, makeConfig(), chatFn);
expect(state.recentOutputHashes.length).toBe(1);
});
});
describe("runLoop", () => {
it("should initialize state with turn=0 and empty budget", async () => {
const chatFn = mock(async () => makeApiResponse({ finishReason: "stop" }));
const { runLoop } = await import("../src/loop-engine.js");
const messages: Message[] = [{ role: "user", content: "do something" }];
const summary = await runLoop(messages, makeConfig({ maxTurns: 1 }), chatFn);
expect(summary.totalTurns).toBe(1);
expect(summary.status).toBe("task_completed");
});
it("should terminate on max_turns when limits exceeded", async () => {
const chatFn = mock(async () => makeApiResponse());
const { runLoop } = await import("../src/loop-engine.js");
const messages: Message[] = [{ role: "user", content: "do something" }];
const summary = await runLoop(messages, makeConfig({ maxTurns: 3 }), chatFn);
expect(summary.status).toBe("task_completed");
// Each turn with no tool calls = idle round, 3 idle rounds = no_progress termination
expect(["task_completed", "no_progress", "max_turns"]).toContain(summary.status);
});
it("should include token and cost data in exit summary", async () => {
const chatFn = mock(async () => makeApiResponse({
usage: { promptTokens: 1000, completionTokens: 500, reasoningTokens: 2000 },
}));
const { runLoop } = await import("../src/loop-engine.js");
const messages: Message[] = [{ role: "user", content: "task" }];
const summary = await runLoop(messages, makeConfig({ maxTurns: 1 }), chatFn);
expect(summary.tokens.prompt).toBe(1000);
expect(summary.tokens.completion).toBe(500);
expect(summary.tokens.reasoning).toBe(2000);
expect(summary.tokens.total).toBe(3500);
expect(summary.cost.total).toBeGreaterThan(0);
expect(summary.guardBlocks).toBe(0);
expect(summary.exitCode).toBe(0);
});
});
});