pal-code 0.0.7 → 0.0.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +9 -2
- package/packages/cli/src/index.ts +2 -4
- package/packages/cli/src/utils/format.test.ts +0 -167
- package/packages/core/src/agent/fallback.test.ts +0 -99
- package/packages/core/src/agent/protocol.test.ts +0 -136
- package/packages/core/src/agent/resume-compaction.test.ts +0 -116
- package/packages/core/src/agent/run.test.ts +0 -207
- package/packages/core/src/compaction.protocol.test.ts +0 -90
- package/packages/core/src/compaction.test.ts +0 -101
- package/packages/core/src/config.test.ts +0 -40
- package/packages/core/src/provider/openrouter.test.ts +0 -59
- package/packages/core/src/session/migration.test.ts +0 -104
- package/packages/core/src/session/store-v2-repair.test.ts +0 -209
- package/packages/core/src/session/store.test.ts +0 -235
- package/packages/core/src/tools/executor.test.ts +0 -122
- package/scripts/sync-version.js +0 -35
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {
|
|
3
|
-
runAgent,
|
|
4
|
-
type ConversationMessage,
|
|
5
|
-
type AgentRunEvent,
|
|
6
|
-
type RunAgentOptions,
|
|
7
|
-
} from './run.js';
|
|
8
|
-
|
|
9
|
-
type FakeEvent =
|
|
10
|
-
| {type: 'text'; content: string}
|
|
11
|
-
| {type: 'tool_use'; toolCall: {id: string; name: string; arguments: string}}
|
|
12
|
-
| {
|
|
13
|
-
type: 'done';
|
|
14
|
-
usage?: {
|
|
15
|
-
promptTokens: number;
|
|
16
|
-
completionTokens: number;
|
|
17
|
-
totalTokens: number;
|
|
18
|
-
cachedTokens?: number;
|
|
19
|
-
};
|
|
20
|
-
}
|
|
21
|
-
| {type: 'error'; content: string};
|
|
22
|
-
|
|
23
|
-
/** A provider stub that replays one scripted response per round. */
|
|
24
|
-
function makeProvider(responses: FakeEvent[][]) {
|
|
25
|
-
return {
|
|
26
|
-
async *stream(): AsyncGenerator<FakeEvent> {
|
|
27
|
-
const chunks = responses.shift() ?? [];
|
|
28
|
-
for (const chunk of chunks) yield chunk;
|
|
29
|
-
},
|
|
30
|
-
};
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
async function collect(gen: AsyncGenerator<AgentRunEvent>): Promise<AgentRunEvent[]> {
|
|
34
|
-
const out: AgentRunEvent[] = [];
|
|
35
|
-
for await (const ev of gen) out.push(ev);
|
|
36
|
-
return out;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function opts(
|
|
40
|
-
overrides: {messages: ConversationMessage[]; provider: unknown} & Record<string, unknown>,
|
|
41
|
-
): RunAgentOptions {
|
|
42
|
-
return {
|
|
43
|
-
tools: [],
|
|
44
|
-
model: 'test-model',
|
|
45
|
-
systemPrompt: 'You are helpful.',
|
|
46
|
-
providerConfig: {model: 'test-model', apiKey: 'k', baseUrl: 'https://example.test'},
|
|
47
|
-
executeTool: async () => ({content: 'ok'}),
|
|
48
|
-
...overrides,
|
|
49
|
-
} as unknown as RunAgentOptions;
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
test('runAgent: yields text and records the assistant message', async () => {
|
|
53
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'Hi'}];
|
|
54
|
-
const provider = makeProvider([
|
|
55
|
-
[
|
|
56
|
-
{type: 'text', content: 'Hello'},
|
|
57
|
-
{type: 'done', usage: {promptTokens: 10, completionTokens: 2, totalTokens: 12}},
|
|
58
|
-
],
|
|
59
|
-
]);
|
|
60
|
-
|
|
61
|
-
const events = await collect(runAgent(opts({messages, provider})));
|
|
62
|
-
|
|
63
|
-
expect(events.some((e) => e.type === 'text-delta')).toBe(true);
|
|
64
|
-
const done = events.find((e) => e.type === 'done');
|
|
65
|
-
expect(done && done.type === 'done' ? done.usage.inputTokens : -1).toBe(10);
|
|
66
|
-
expect(messages[messages.length - 1]).toEqual({role: 'assistant', content: 'Hello'});
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
test('runAgent: executes tool calls and feeds results back to the model', async () => {
|
|
70
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'Read a.ts'}];
|
|
71
|
-
const provider = makeProvider([
|
|
72
|
-
[
|
|
73
|
-
{type: 'tool_use', toolCall: {id: 'c1', name: 'read_file', arguments: '{"path":"a.ts"}'}},
|
|
74
|
-
{type: 'done'},
|
|
75
|
-
],
|
|
76
|
-
[
|
|
77
|
-
{type: 'text', content: 'Got it.'},
|
|
78
|
-
{type: 'done', usage: {promptTokens: 20, completionTokens: 5, totalTokens: 25}},
|
|
79
|
-
],
|
|
80
|
-
]);
|
|
81
|
-
|
|
82
|
-
const events = await collect(
|
|
83
|
-
runAgent(
|
|
84
|
-
opts({
|
|
85
|
-
messages,
|
|
86
|
-
provider,
|
|
87
|
-
executeTool: async (name: string, args: string, id: string) => {
|
|
88
|
-
expect(name).toBe('read_file');
|
|
89
|
-
expect(args).toBe('{"path":"a.ts"}');
|
|
90
|
-
expect(id).toBe('c1');
|
|
91
|
-
return {content: 'line 1: hi'};
|
|
92
|
-
},
|
|
93
|
-
}),
|
|
94
|
-
),
|
|
95
|
-
);
|
|
96
|
-
|
|
97
|
-
expect(events.some((e) => e.type === 'tool-start')).toBe(true);
|
|
98
|
-
expect(events.some((e) => e.type === 'tool-end')).toBe(true);
|
|
99
|
-
expect(
|
|
100
|
-
messages.some((m) => m.role === 'tool' && (m as {tool_call_id: string}).tool_call_id === 'c1'),
|
|
101
|
-
).toBe(true);
|
|
102
|
-
expect(messages[messages.length - 1]).toEqual({role: 'assistant', content: 'Got it.'});
|
|
103
|
-
});
|
|
104
|
-
|
|
105
|
-
test('runAgent: enforces maxRounds', async () => {
|
|
106
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'loop'}];
|
|
107
|
-
const provider = makeProvider([
|
|
108
|
-
[
|
|
109
|
-
{type: 'tool_use', toolCall: {id: 'c1', name: 'bash', arguments: '{"command":"a"}'}},
|
|
110
|
-
{type: 'done'},
|
|
111
|
-
],
|
|
112
|
-
[
|
|
113
|
-
{type: 'tool_use', toolCall: {id: 'c2', name: 'bash', arguments: '{"command":"b"}'}},
|
|
114
|
-
{type: 'done'},
|
|
115
|
-
],
|
|
116
|
-
]);
|
|
117
|
-
|
|
118
|
-
const events = await collect(runAgent(opts({messages, provider, maxRounds: 1})));
|
|
119
|
-
|
|
120
|
-
const notices = events.filter((e): e is {type: 'notice'; text: string} => e.type === 'notice');
|
|
121
|
-
expect(notices.some((n) => n.text.includes('Max tool rounds'))).toBe(true);
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
test('runAgent: stops early when an identical tool call repeats', async () => {
|
|
125
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'spin'}];
|
|
126
|
-
// Same name + identical arguments every round — mirrors a stuck model.
|
|
127
|
-
const same = {
|
|
128
|
-
type: 'tool_use' as const,
|
|
129
|
-
toolCall: {id: 'c', name: 'bash', arguments: '{"command":"x"}'},
|
|
130
|
-
};
|
|
131
|
-
const provider = makeProvider([
|
|
132
|
-
[same, {type: 'done'}],
|
|
133
|
-
[same, {type: 'done'}],
|
|
134
|
-
[same, {type: 'done'}],
|
|
135
|
-
[same, {type: 'done'}],
|
|
136
|
-
[same, {type: 'done'}],
|
|
137
|
-
[same, {type: 'done'}],
|
|
138
|
-
[same, {type: 'done'}],
|
|
139
|
-
]);
|
|
140
|
-
|
|
141
|
-
const events = await collect(runAgent(opts({messages, provider, maxRounds: 50})));
|
|
142
|
-
|
|
143
|
-
const notices = events.filter((e): e is {type: 'notice'; text: string} => e.type === 'notice');
|
|
144
|
-
expect(notices.some((n) => n.text.includes('loop detected'))).toBe(true);
|
|
145
|
-
expect(notices.some((n) => n.text.includes('Max tool rounds'))).toBe(false);
|
|
146
|
-
});
|
|
147
|
-
|
|
148
|
-
test('runAgent: a pre-aborted signal ends the turn immediately', async () => {
|
|
149
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'Hi'}];
|
|
150
|
-
const provider = makeProvider([]);
|
|
151
|
-
const controller = new AbortController();
|
|
152
|
-
controller.abort();
|
|
153
|
-
|
|
154
|
-
const events = await collect(runAgent(opts({messages, provider, signal: controller.signal})));
|
|
155
|
-
const types = events.map((e) => e.type);
|
|
156
|
-
|
|
157
|
-
expect(types).toContain('aborted');
|
|
158
|
-
expect(types).not.toContain('done');
|
|
159
|
-
});
|
|
160
|
-
|
|
161
|
-
test('runAgent: the round cap degrades into a tools-disabled summary', async () => {
|
|
162
|
-
const messages: ConversationMessage[] = [{role: 'user', content: 'Do a long task'}];
|
|
163
|
-
const toolCountsPerCall: number[] = [];
|
|
164
|
-
|
|
165
|
-
// Round 1 asks for a tool; the wrap-up call must be made with tools withheld.
|
|
166
|
-
const provider = {
|
|
167
|
-
async *stream(o: {tools?: unknown[]}): AsyncGenerator<FakeEvent> {
|
|
168
|
-
toolCountsPerCall.push(Array.isArray(o.tools) ? o.tools.length : -1);
|
|
169
|
-
if (toolCountsPerCall.length === 1) {
|
|
170
|
-
yield {
|
|
171
|
-
type: 'tool_use',
|
|
172
|
-
toolCall: {id: 'c1', name: 'read_file', arguments: '{"path":"a.ts"}'},
|
|
173
|
-
};
|
|
174
|
-
yield {type: 'done'};
|
|
175
|
-
} else {
|
|
176
|
-
yield {type: 'text', content: 'Summary: reached the step cap, nothing else done.'};
|
|
177
|
-
yield {type: 'done'};
|
|
178
|
-
}
|
|
179
|
-
},
|
|
180
|
-
};
|
|
181
|
-
|
|
182
|
-
const events = await collect(
|
|
183
|
-
runAgent(
|
|
184
|
-
opts({
|
|
185
|
-
messages,
|
|
186
|
-
provider,
|
|
187
|
-
maxRounds: 1,
|
|
188
|
-
tools: [
|
|
189
|
-
{type: 'function', function: {name: 'read_file', description: 'read', parameters: {}}},
|
|
190
|
-
],
|
|
191
|
-
}),
|
|
192
|
-
),
|
|
193
|
-
);
|
|
194
|
-
|
|
195
|
-
const types = events.map((e) => e.type);
|
|
196
|
-
expect(types).toContain('done');
|
|
197
|
-
expect(types).toContain('notice');
|
|
198
|
-
|
|
199
|
-
// Two model calls: the capped round (1 tool) then the wrap-up (0 tools).
|
|
200
|
-
expect(toolCountsPerCall.length).toBe(2);
|
|
201
|
-
expect(toolCountsPerCall[0]).toBe(1);
|
|
202
|
-
expect(toolCountsPerCall[1]).toBe(0);
|
|
203
|
-
|
|
204
|
-
// The forced summary is streamed and persisted so the user always sees it.
|
|
205
|
-
expect(events.some((e) => e.type === 'text-delta' && e.content.includes('Summary'))).toBe(true);
|
|
206
|
-
expect(messages[messages.length - 1]?.content).toContain('Summary');
|
|
207
|
-
});
|
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {compactMessages, type CompactableMessage} from './compaction.js';
|
|
3
|
-
|
|
4
|
-
type Wire = Record<string, unknown> & {role: string; tool_call_id?: string};
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Same invariant the provider enforces: every assistant message with `tool_calls`
|
|
8
|
-
* is immediately followed by one `tool` message per call id. Returns an error
|
|
9
|
-
* description, or null when valid.
|
|
10
|
-
*/
|
|
11
|
-
function protocolViolation(messages: CompactableMessage[]): string | null {
|
|
12
|
-
for (let i = 0; i < messages.length; i++) {
|
|
13
|
-
const msg = messages[i];
|
|
14
|
-
if (msg.role !== 'assistant' || !msg.toolCalls?.length) continue;
|
|
15
|
-
|
|
16
|
-
const ids = msg.toolCalls.map((tc) => tc.id);
|
|
17
|
-
const seen: string[] = [];
|
|
18
|
-
for (let j = i + 1; j < messages.length; j++) {
|
|
19
|
-
if (messages[j].role !== 'tool') break;
|
|
20
|
-
seen.push(String(messages[j].tool_call_id));
|
|
21
|
-
}
|
|
22
|
-
if (seen.join(',') !== ids.join(',')) {
|
|
23
|
-
return `assistant#${i} wants [${ids}] but got [${seen}]`;
|
|
24
|
-
}
|
|
25
|
-
}
|
|
26
|
-
// Orphaned tool results (no owning assistant) are equally invalid.
|
|
27
|
-
for (let i = 0; i < messages.length; i++) {
|
|
28
|
-
if (messages[i].role !== 'tool') continue;
|
|
29
|
-
let owner = -1;
|
|
30
|
-
for (let j = i - 1; j >= 0; j--) {
|
|
31
|
-
if (messages[j].role === 'assistant') {
|
|
32
|
-
owner = j;
|
|
33
|
-
break;
|
|
34
|
-
}
|
|
35
|
-
if (messages[j].role === 'user') break;
|
|
36
|
-
}
|
|
37
|
-
const owns =
|
|
38
|
-
owner >= 0 && messages[owner].toolCalls?.some((tc) => tc.id === messages[i].tool_call_id);
|
|
39
|
-
if (!owns) return `orphan tool result ${messages[i].tool_call_id} at #${i}`;
|
|
40
|
-
}
|
|
41
|
-
return null;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
/** A history of multi-call turns, each with a bulky tool result block. */
|
|
45
|
-
function makeToolHeavyConversation(turns: number): CompactableMessage[] {
|
|
46
|
-
const messages: CompactableMessage[] = [{role: 'user', content: 'do work'}];
|
|
47
|
-
for (let t = 0; t < turns; t++) {
|
|
48
|
-
const ids = [`t${t}a`, `t${t}b`, `t${t}c`];
|
|
49
|
-
messages.push({
|
|
50
|
-
role: 'assistant',
|
|
51
|
-
content: '',
|
|
52
|
-
toolCalls: ids.map((id) => ({id, name: 'read_file', arguments: `{"path":"${id}"}`})),
|
|
53
|
-
});
|
|
54
|
-
for (const id of ids) {
|
|
55
|
-
messages.push({
|
|
56
|
-
role: 'tool',
|
|
57
|
-
tool_call_id: id,
|
|
58
|
-
content: `result for ${id} ` + 'x'.repeat(1500),
|
|
59
|
-
});
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return messages;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
test('compactMessages: never splits an assistant tool_calls group under any boundary', () => {
|
|
66
|
-
// Sweep every possible split by varying the size of the leading filler, so the
|
|
67
|
-
// old/recent boundary lands at many different offsets within the groups.
|
|
68
|
-
// Compaction truncates content but never drops messages, so group adjacency
|
|
69
|
-
// must survive regardless of where the boundary falls.
|
|
70
|
-
for (let filler = 0; filler <= 10; filler++) {
|
|
71
|
-
const messages: CompactableMessage[] = [
|
|
72
|
-
{role: 'user', content: 'a'.repeat(filler * 400)},
|
|
73
|
-
...makeToolHeavyConversation(6),
|
|
74
|
-
];
|
|
75
|
-
const {messages: compacted} = compactMessages(messages, {maxTokens: 800, reservedTokens: 100});
|
|
76
|
-
const violation = protocolViolation(compacted);
|
|
77
|
-
expect(`filler=${filler}: ${violation}`).toBe(`filler=${filler}: null`);
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
test('compactMessages: preserves group integrity when the boundary lands on a tool result', () => {
|
|
82
|
-
const messages: CompactableMessage[] = makeToolHeavyConversation(4);
|
|
83
|
-
const {messages: compacted} = compactMessages(messages, {maxTokens: 500, reservedTokens: 50});
|
|
84
|
-
expect(protocolViolation(compacted)).toBeNull();
|
|
85
|
-
// The whole point: some tool results were actually trimmed (compaction ran).
|
|
86
|
-
const trimmed = compacted.filter((m) => m.role === 'tool' && m.content.length < 1500);
|
|
87
|
-
expect(trimmed.length).toBeGreaterThan(0);
|
|
88
|
-
// And every message survives — nothing is dropped.
|
|
89
|
-
expect(compacted.length).toBe(messages.length);
|
|
90
|
-
});
|
|
@@ -1,101 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {
|
|
3
|
-
compactMessages,
|
|
4
|
-
shouldCompact,
|
|
5
|
-
estimateMessagesTokens,
|
|
6
|
-
type CompactableMessage,
|
|
7
|
-
} from './compaction.js';
|
|
8
|
-
|
|
9
|
-
function makeConversation(length: number): CompactableMessage[] {
|
|
10
|
-
const messages: CompactableMessage[] = [];
|
|
11
|
-
for (let i = 0; i < length; i++) {
|
|
12
|
-
messages.push({
|
|
13
|
-
role: i % 2 === 0 ? 'user' : 'assistant',
|
|
14
|
-
content: `message number ${i}`,
|
|
15
|
-
});
|
|
16
|
-
}
|
|
17
|
-
return messages;
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
test('shouldCompact: false for small conversations', () => {
|
|
21
|
-
const messages = makeConversation(5);
|
|
22
|
-
expect(shouldCompact(messages, {maxTokens: 100_000, reservedTokens: 12_000})).toBe(false);
|
|
23
|
-
});
|
|
24
|
-
|
|
25
|
-
test('estimateMessagesTokens: scales with content', () => {
|
|
26
|
-
expect(estimateMessagesTokens([{role: 'user', content: 'short'}])).toBeGreaterThan(0);
|
|
27
|
-
expect(estimateMessagesTokens([{role: 'user', content: 'a'.repeat(400)}])).toBeGreaterThan(
|
|
28
|
-
estimateMessagesTokens([{role: 'user', content: 'a'}]),
|
|
29
|
-
);
|
|
30
|
-
});
|
|
31
|
-
|
|
32
|
-
test('compactMessages: never injects a system message into a caller-owned history', () => {
|
|
33
|
-
const messages = makeConversation(30);
|
|
34
|
-
const {messages: compacted, summary} = compactMessages(messages, {
|
|
35
|
-
maxTokens: 100,
|
|
36
|
-
reservedTokens: 50,
|
|
37
|
-
});
|
|
38
|
-
|
|
39
|
-
expect(summary).toContain('Context compacted');
|
|
40
|
-
expect(compacted.some((m) => m.role === 'system')).toBe(false);
|
|
41
|
-
// First message role is preserved (no synthetic system prefix).
|
|
42
|
-
expect(compacted[0]?.role).toBe(messages[0]?.role);
|
|
43
|
-
});
|
|
44
|
-
|
|
45
|
-
test('compactMessages: folds the summary into an existing leading system message', () => {
|
|
46
|
-
const messages: CompactableMessage[] = [
|
|
47
|
-
{role: 'system', content: 'You are a helpful agent.'},
|
|
48
|
-
...makeConversation(30),
|
|
49
|
-
];
|
|
50
|
-
|
|
51
|
-
const {messages: compacted, summary} = compactMessages(messages, {
|
|
52
|
-
maxTokens: 100,
|
|
53
|
-
reservedTokens: 50,
|
|
54
|
-
});
|
|
55
|
-
|
|
56
|
-
const systems = compacted.filter((m) => m.role === 'system');
|
|
57
|
-
expect(systems).toHaveLength(1);
|
|
58
|
-
expect(compacted[0]?.content).toContain('You are a helpful agent.');
|
|
59
|
-
expect(compacted[0]?.content).toContain(summary);
|
|
60
|
-
});
|
|
61
|
-
|
|
62
|
-
test('compactMessages: never splits a tool_calls group across old/recent', () => {
|
|
63
|
-
// KEEP_RECENT is 5; build a transcript whose split point falls INSIDE a tool
|
|
64
|
-
// group so the naive slice would orphan a `tool` message.
|
|
65
|
-
const group = (id: string): CompactableMessage[] => [
|
|
66
|
-
{role: 'assistant', content: '', toolCalls: [{id, name: 'bash', arguments: '{}'}]},
|
|
67
|
-
{role: 'tool', tool_call_id: id, content: 'x'.repeat(900)},
|
|
68
|
-
];
|
|
69
|
-
const messages: CompactableMessage[] = [
|
|
70
|
-
{role: 'user', content: 'go'},
|
|
71
|
-
{role: 'assistant', content: 'a'.repeat(4000)},
|
|
72
|
-
{role: 'user', content: 'go2'},
|
|
73
|
-
{role: 'assistant', content: 'b'.repeat(4000)},
|
|
74
|
-
{role: 'user', content: 'go3'},
|
|
75
|
-
...group('c1'),
|
|
76
|
-
...group('c2'),
|
|
77
|
-
];
|
|
78
|
-
|
|
79
|
-
const {messages: compacted} = compactMessages(messages, {maxTokens: 500, reservedTokens: 100});
|
|
80
|
-
|
|
81
|
-
// No `tool` message may appear without its owning assistant `tool_calls`
|
|
82
|
-
// message present earlier in the array.
|
|
83
|
-
const callIds = new Set<string>();
|
|
84
|
-
for (const m of compacted) {
|
|
85
|
-
if (m.role === 'assistant' && m.toolCalls) for (const tc of m.toolCalls) callIds.add(tc.id);
|
|
86
|
-
if (m.role === 'tool') expect(callIds.has(m.tool_call_id ?? '')).toBe(true);
|
|
87
|
-
}
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
test('compactMessages: truncates large tool results', () => {
|
|
91
|
-
const messages: CompactableMessage[] = [
|
|
92
|
-
{role: 'user', content: 'run it'},
|
|
93
|
-
{role: 'assistant', content: 'ok', toolCalls: [{id: 'c1', name: 'bash', arguments: '{}'}]},
|
|
94
|
-
{role: 'tool', tool_call_id: 'c1', content: 'x'.repeat(2000)},
|
|
95
|
-
];
|
|
96
|
-
|
|
97
|
-
const {messages: compacted} = compactMessages(messages, {maxTokens: 10, reservedTokens: 5});
|
|
98
|
-
const toolMessage = compacted.find((m) => m.role === 'tool');
|
|
99
|
-
expect(toolMessage).toBeDefined();
|
|
100
|
-
expect((toolMessage?.content ?? '').length).toBeLessThan(2000);
|
|
101
|
-
});
|
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {isPathIgnored, filterEntries, checkFileSize, type ToolConfig} from './config.js';
|
|
3
|
-
|
|
4
|
-
const config: ToolConfig = {
|
|
5
|
-
ignore: ['node_modules', '*.log', 'dist'],
|
|
6
|
-
ignoreLargeFiles: true,
|
|
7
|
-
maxFileSizeKB: 1,
|
|
8
|
-
readLineLimit: 2000,
|
|
9
|
-
};
|
|
10
|
-
|
|
11
|
-
test('isPathIgnored: matches basename patterns', () => {
|
|
12
|
-
expect(isPathIgnored('node_modules/pkg/index.ts', config)).toBe(true);
|
|
13
|
-
});
|
|
14
|
-
|
|
15
|
-
test('isPathIgnored: matches directory segments anywhere in the path', () => {
|
|
16
|
-
expect(isPathIgnored('src/node_modules/pkg/index.ts', config)).toBe(true);
|
|
17
|
-
});
|
|
18
|
-
|
|
19
|
-
test('isPathIgnored: matches extension patterns', () => {
|
|
20
|
-
expect(isPathIgnored('logs/app.log', config)).toBe(true);
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
test('isPathIgnored: does not match unrelated paths', () => {
|
|
24
|
-
expect(isPathIgnored('src/app.ts', config)).toBe(false);
|
|
25
|
-
expect(isPathIgnored('src/app.ts.logs', config)).toBe(false);
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
test('filterEntries: removes ignored directory entries', () => {
|
|
29
|
-
const entries = [
|
|
30
|
-
{name: 'src', isDirectory: true},
|
|
31
|
-
{name: 'node_modules', isDirectory: true},
|
|
32
|
-
{name: 'README.md', isDirectory: false},
|
|
33
|
-
];
|
|
34
|
-
const filtered = filterEntries(entries, '.', config);
|
|
35
|
-
expect(filtered.map((e) => e.name)).toEqual(['src', 'README.md']);
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
test('checkFileSize: returns null when size limiting is disabled', () => {
|
|
39
|
-
expect(checkFileSize('anything.ts', {...config, ignoreLargeFiles: false})).toBeNull();
|
|
40
|
-
});
|
|
@@ -1,59 +0,0 @@
|
|
|
1
|
-
import {test, expect, afterEach} from 'bun:test';
|
|
2
|
-
import {createOpenRouterProvider} from './openrouter.js';
|
|
3
|
-
|
|
4
|
-
const originalFetch = globalThis.fetch;
|
|
5
|
-
|
|
6
|
-
afterEach(() => {
|
|
7
|
-
globalThis.fetch = originalFetch;
|
|
8
|
-
});
|
|
9
|
-
|
|
10
|
-
function sseResponse(chunks: string[]): Response {
|
|
11
|
-
const encoder = new TextEncoder();
|
|
12
|
-
const stream = new ReadableStream<Uint8Array>({
|
|
13
|
-
start(controller) {
|
|
14
|
-
for (const chunk of chunks) {
|
|
15
|
-
controller.enqueue(encoder.encode(chunk));
|
|
16
|
-
}
|
|
17
|
-
controller.close();
|
|
18
|
-
},
|
|
19
|
-
});
|
|
20
|
-
return new Response(stream, {status: 200});
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
test('OpenRouterProvider: accumulates fragmented tool calls into one tool_use event', async () => {
|
|
24
|
-
globalThis.fetch = (async () =>
|
|
25
|
-
sseResponse([
|
|
26
|
-
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_1","function":{"name":"read_file","arguments":""}}]},"finish_reason":null}]}\n\n',
|
|
27
|
-
'data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"path\\":\\"a.ts\\"}"}}]},"finish_reason":null}]}\n\n',
|
|
28
|
-
'data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}\n\n',
|
|
29
|
-
'data: {"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":2,"total_tokens":12}}\n\n',
|
|
30
|
-
'data: [DONE]\n\n',
|
|
31
|
-
])) as unknown as typeof fetch;
|
|
32
|
-
|
|
33
|
-
const provider = createOpenRouterProvider({
|
|
34
|
-
id: 'test',
|
|
35
|
-
baseUrl: 'https://example.com/v1',
|
|
36
|
-
apiKey: 'sk-test',
|
|
37
|
-
});
|
|
38
|
-
await provider.init();
|
|
39
|
-
|
|
40
|
-
const events = [];
|
|
41
|
-
for await (const event of provider.stream({
|
|
42
|
-
model: 'test-model',
|
|
43
|
-
messages: [{role: 'user', content: 'hi'}],
|
|
44
|
-
tools: [],
|
|
45
|
-
})) {
|
|
46
|
-
events.push(event);
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
const toolUses = events.filter((e) => e.type === 'tool_use');
|
|
50
|
-
expect(toolUses).toHaveLength(1);
|
|
51
|
-
expect(toolUses[0]?.toolCall).toEqual({
|
|
52
|
-
id: 'call_1',
|
|
53
|
-
name: 'read_file',
|
|
54
|
-
arguments: '{"path":"a.ts"}',
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
const done = events.find((e) => e.type === 'done');
|
|
58
|
-
expect(done?.usage?.promptTokens).toBe(10);
|
|
59
|
-
});
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
import {test, expect} from 'bun:test';
|
|
2
|
-
import {rm} from 'fs/promises';
|
|
3
|
-
import {rmSync} from 'fs';
|
|
4
|
-
import {join} from 'path';
|
|
5
|
-
import {Database} from 'bun:sqlite';
|
|
6
|
-
import {SessionStore} from './store.js';
|
|
7
|
-
|
|
8
|
-
const DB_PATH = join(import.meta.dir, '.test-migration.db');
|
|
9
|
-
|
|
10
|
-
/** Build a v0 database: sessions table with a JSON `messages` blob column. */
|
|
11
|
-
function seedLegacyDb(): void {
|
|
12
|
-
// Start from a clean slate — a leftover file from a previous run would make
|
|
13
|
-
// the CREATE TABLE fail and mis-attribute the error.
|
|
14
|
-
rmSync(DB_PATH, {force: true});
|
|
15
|
-
rmSync(`${DB_PATH}-wal`, {force: true});
|
|
16
|
-
rmSync(`${DB_PATH}-shm`, {force: true});
|
|
17
|
-
|
|
18
|
-
const db = new Database(DB_PATH);
|
|
19
|
-
db.exec(`
|
|
20
|
-
CREATE TABLE sessions (
|
|
21
|
-
id TEXT PRIMARY KEY,
|
|
22
|
-
title TEXT,
|
|
23
|
-
messages TEXT NOT NULL,
|
|
24
|
-
input_tokens INTEGER NOT NULL DEFAULT 0,
|
|
25
|
-
output_tokens INTEGER NOT NULL DEFAULT 0,
|
|
26
|
-
cached_tokens INTEGER NOT NULL DEFAULT 0,
|
|
27
|
-
cost REAL NOT NULL DEFAULT 0,
|
|
28
|
-
created_at INTEGER NOT NULL,
|
|
29
|
-
updated_at INTEGER NOT NULL
|
|
30
|
-
);
|
|
31
|
-
`);
|
|
32
|
-
const history = [
|
|
33
|
-
{role: 'user', content: 'first'},
|
|
34
|
-
{role: 'assistant', content: 'second'},
|
|
35
|
-
{role: 'tool', tool_call_id: 'c1', content: 'third'},
|
|
36
|
-
];
|
|
37
|
-
db.run(
|
|
38
|
-
'INSERT INTO sessions (id, title, messages, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
|
39
|
-
['legacy-1', 'Old session', JSON.stringify(history), 1000, 2000],
|
|
40
|
-
);
|
|
41
|
-
// A row with malformed JSON must not abort the migration.
|
|
42
|
-
db.run(
|
|
43
|
-
'INSERT INTO sessions (id, title, messages, created_at, updated_at) VALUES (?, ?, ?, ?, ?)',
|
|
44
|
-
['legacy-bad', 'Broken', '{not json', 1000, 2000],
|
|
45
|
-
);
|
|
46
|
-
db.close();
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
test('migration: explodes legacy JSON blobs into message rows', () => {
|
|
50
|
-
seedLegacyDb();
|
|
51
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
52
|
-
store.init();
|
|
53
|
-
|
|
54
|
-
try {
|
|
55
|
-
const rows = store.getMessages('legacy-1');
|
|
56
|
-
expect(rows.map((r) => r.seq)).toEqual([1, 2, 3]);
|
|
57
|
-
expect(rows.map((r) => r.role)).toEqual(['user', 'assistant', 'tool']);
|
|
58
|
-
expect(rows[2].toolCallId).toBe('c1');
|
|
59
|
-
|
|
60
|
-
const session = store.get('legacy-1');
|
|
61
|
-
expect(session?.title).toBe('Old session');
|
|
62
|
-
expect(session?.messages).toEqual([
|
|
63
|
-
{role: 'user', content: 'first'},
|
|
64
|
-
{role: 'assistant', content: 'second'},
|
|
65
|
-
{role: 'tool', tool_call_id: 'c1', content: 'third'},
|
|
66
|
-
]);
|
|
67
|
-
|
|
68
|
-
// The malformed row survives as an empty session (no rows exploded).
|
|
69
|
-
expect(store.getMessages('legacy-bad')).toEqual([]);
|
|
70
|
-
} finally {
|
|
71
|
-
store.close();
|
|
72
|
-
}
|
|
73
|
-
});
|
|
74
|
-
|
|
75
|
-
test('migration: re-running on a migrated DB is a no-op (idempotent)', () => {
|
|
76
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
77
|
-
store.init();
|
|
78
|
-
try {
|
|
79
|
-
// A second init on the same file must not duplicate rows or throw.
|
|
80
|
-
store.init();
|
|
81
|
-
expect(store.getMessages('legacy-1').length).toBe(3);
|
|
82
|
-
} finally {
|
|
83
|
-
store.close();
|
|
84
|
-
}
|
|
85
|
-
});
|
|
86
|
-
|
|
87
|
-
test('migration: appends continue after migrated history', () => {
|
|
88
|
-
const store = new SessionStore({dbPath: DB_PATH});
|
|
89
|
-
store.init();
|
|
90
|
-
try {
|
|
91
|
-
store.appendMessage('legacy-1', {role: 'user', content: 'after migration'});
|
|
92
|
-
const rows = store.getMessages('legacy-1');
|
|
93
|
-
expect(rows.map((r) => r.seq)).toEqual([1, 2, 3, 4]);
|
|
94
|
-
expect(rows[3].content).toBe('after migration');
|
|
95
|
-
} finally {
|
|
96
|
-
store.close();
|
|
97
|
-
}
|
|
98
|
-
});
|
|
99
|
-
|
|
100
|
-
test('migration cleanup', async () => {
|
|
101
|
-
await rm(DB_PATH, {force: true});
|
|
102
|
-
await rm(`${DB_PATH}-wal`, {force: true});
|
|
103
|
-
await rm(`${DB_PATH}-shm`, {force: true});
|
|
104
|
-
});
|