pal-code 0.0.7 → 0.0.10
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/README.md +3 -3
- package/SYSTEM.md +3 -3
- package/bin/pal-code.js +37 -11
- package/package.json +11 -11
- package/packages/cli/README.md +2 -2
- package/packages/cli/src/commands/ext.ts +1 -1
- package/packages/cli/src/commands.ts +1 -1
- package/packages/cli/src/components/render-history.ts +2 -2
- package/packages/cli/src/config.ts +2 -2
- package/packages/cli/src/index.ts +8 -10
- package/packages/cli/src/overlays/key-input.ts +1 -1
- package/packages/cli/src/overlays/model-picker.ts +2 -2
- package/packages/cli/src/overlays/session-picker.ts +1 -1
- package/packages/cli/src/overlays/wizard.ts +1 -1
- package/packages/cli/src/state.ts +2 -2
- package/packages/cli/src/turn.ts +14 -9
- package/packages/cli/src/utils/permissions.ts +3 -3
- package/packages/cli/src/utils/format.test.ts +0 -167
- package/packages/core/src/agent/events.ts +0 -36
- package/packages/core/src/agent/fallback.test.ts +0 -99
- package/packages/core/src/agent/fallback.ts +0 -344
- package/packages/core/src/agent/index.ts +0 -35
- 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/roles.ts +0 -188
- package/packages/core/src/agent/run.test.ts +0 -207
- package/packages/core/src/agent/run.ts +0 -713
- package/packages/core/src/agent/scope.ts +0 -34
- package/packages/core/src/agent/todos.ts +0 -66
- package/packages/core/src/compaction.protocol.test.ts +0 -90
- package/packages/core/src/compaction.test.ts +0 -101
- package/packages/core/src/compaction.ts +0 -243
- package/packages/core/src/config.test.ts +0 -40
- package/packages/core/src/config.ts +0 -387
- package/packages/core/src/extensions.ts +0 -178
- package/packages/core/src/index.ts +0 -157
- package/packages/core/src/logger.ts +0 -54
- package/packages/core/src/provider/auth.ts +0 -153
- package/packages/core/src/provider/complete.ts +0 -63
- package/packages/core/src/provider/index.ts +0 -6
- package/packages/core/src/provider/openrouter.test.ts +0 -59
- package/packages/core/src/provider/openrouter.ts +0 -304
- package/packages/core/src/provider/pick-model.ts +0 -43
- package/packages/core/src/provider/registry.ts +0 -222
- package/packages/core/src/provider/types.ts +0 -61
- package/packages/core/src/repo-map.ts +0 -177
- package/packages/core/src/session/index.ts +0 -2
- 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/session/store.ts +0 -677
- package/packages/core/src/session/types.ts +0 -72
- package/packages/core/src/snapshots.ts +0 -107
- package/packages/core/src/tools/definitions.ts +0 -365
- package/packages/core/src/tools/executor.test.ts +0 -122
- package/packages/core/src/tools/executor.ts +0 -1363
- package/packages/core/src/tools/index.ts +0 -5
- package/packages/core/src/tools/search.ts +0 -201
- package/scripts/postinstall.js +0 -121
- package/scripts/preinstall.js +0 -51
- package/scripts/sync-version.js +0 -35
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Run scope — snapshot/restore of the mutable module state a nested run could
|
|
3
|
-
* clobber.
|
|
4
|
-
*
|
|
5
|
-
* core keeps a little module-level state for ergonomics (the todo list, the
|
|
6
|
-
* tracked shell cwd). That's fine for a single interactive turn, but `delegate`
|
|
7
|
-
* starts a *nested* run inside the same process: a child that calls `todo` or
|
|
8
|
-
* `cd`s would silently overwrite the parent's plan and working directory.
|
|
9
|
-
*
|
|
10
|
-
* Wrapping the child in capture/restore keeps the two runs isolated without
|
|
11
|
-
* threading a context object through every tool signature.
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import {getTodos, restoreTodos, type Todo} from './todos.js';
|
|
15
|
-
import {getShellCwd, setShellCwd} from '../tools/executor.js';
|
|
16
|
-
|
|
17
|
-
export interface RunScope {
|
|
18
|
-
todos: Todo[];
|
|
19
|
-
shellCwd: string;
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Capture the state a nested run must not leak into its parent. */
|
|
23
|
-
export function captureRunScope(): RunScope {
|
|
24
|
-
return {
|
|
25
|
-
todos: getTodos().map((t) => ({...t})),
|
|
26
|
-
shellCwd: getShellCwd(),
|
|
27
|
-
};
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
/** Restore a scope captured by `captureRunScope`. Safe to call in a `finally`. */
|
|
31
|
-
export function restoreRunScope(scope: RunScope): void {
|
|
32
|
-
restoreTodos(scope.todos);
|
|
33
|
-
setShellCwd(scope.shellCwd);
|
|
34
|
-
}
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Task plan for multi-step work.
|
|
3
|
-
*
|
|
4
|
-
* The model writes the full list on every `todo` call (replace semantics, like
|
|
5
|
-
* OpenCode's todowrite). Keeping the list in one place lets the UI render live
|
|
6
|
-
* progress and lets the model see "am I done?" without re-exploring.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
export type TodoStatus = 'pending' | 'in_progress' | 'completed' | 'cancelled';
|
|
10
|
-
|
|
11
|
-
export interface Todo {
|
|
12
|
-
content: string;
|
|
13
|
-
status: TodoStatus;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
const VALID_STATUS: readonly TodoStatus[] = ['pending', 'in_progress', 'completed', 'cancelled'];
|
|
17
|
-
|
|
18
|
-
let todos: Todo[] = [];
|
|
19
|
-
|
|
20
|
-
/** Replace the whole list. Returns the normalised list. */
|
|
21
|
-
export function setTodos(next: readonly Todo[]): Todo[] {
|
|
22
|
-
todos = next
|
|
23
|
-
.filter((t) => t && typeof t.content === 'string' && t.content.trim().length > 0)
|
|
24
|
-
.map((t) => ({
|
|
25
|
-
content: t.content.trim().slice(0, 200),
|
|
26
|
-
status: VALID_STATUS.includes(t.status) ? t.status : 'pending',
|
|
27
|
-
}))
|
|
28
|
-
.slice(0, 50);
|
|
29
|
-
return todos;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
/** Current list (live reference — treat as read-only). */
|
|
33
|
-
export function getTodos(): readonly Todo[] {
|
|
34
|
-
return todos;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/** Drop all items (new session / clear). */
|
|
38
|
-
export function clearTodos(): void {
|
|
39
|
-
todos = [];
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
* Copy of the current list, for restoring after a nested run (`delegate`)
|
|
44
|
-
* that used `todo` and would otherwise clobber the parent's plan.
|
|
45
|
-
*/
|
|
46
|
-
export function snapshotTodos(): Todo[] {
|
|
47
|
-
return todos.map((t) => ({...t}));
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
/** Restore a snapshot taken by `snapshotTodos`. */
|
|
51
|
-
export function restoreTodos(snapshot: readonly Todo[]): void {
|
|
52
|
-
todos = snapshot.map((t) => ({...t}));
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
/** Compact one-line-per-item rendering used as the tool result. */
|
|
56
|
-
export function formatTodos(list: readonly Todo[] = todos): string {
|
|
57
|
-
if (list.length === 0) return '(no todos)';
|
|
58
|
-
const mark: Record<TodoStatus, string> = {
|
|
59
|
-
pending: '[ ]',
|
|
60
|
-
in_progress: '[~]',
|
|
61
|
-
completed: '[x]',
|
|
62
|
-
cancelled: '[-]',
|
|
63
|
-
};
|
|
64
|
-
const done = list.filter((t) => t.status === 'completed').length;
|
|
65
|
-
return `${done}/${list.length} done\n${list.map((t) => `${mark[t.status]} ${t.content}`).join('\n')}`;
|
|
66
|
-
}
|
|
@@ -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,243 +0,0 @@
|
|
|
1
|
-
// Structural message shape — works with both the CLI's local Message union
|
|
2
|
-
// and the provider Message type. Only needs role/content/toolCalls.
|
|
3
|
-
export interface CompactableMessage {
|
|
4
|
-
role: string;
|
|
5
|
-
content: string;
|
|
6
|
-
toolCalls?: Array<{
|
|
7
|
-
id: string;
|
|
8
|
-
name: string;
|
|
9
|
-
arguments: string;
|
|
10
|
-
extraContent?: Record<string, unknown>;
|
|
11
|
-
}>;
|
|
12
|
-
tool_call_id?: string;
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const CHARS_PER_TOKEN = 4;
|
|
16
|
-
|
|
17
|
-
/** Estimates the token count for the given text. */
|
|
18
|
-
export function estimateTokens(text: string): number {
|
|
19
|
-
return Math.ceil(text.length / CHARS_PER_TOKEN);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export function estimateMessagesTokens(messages: CompactableMessage[]): number {
|
|
23
|
-
return messages.reduce((sum, m) => {
|
|
24
|
-
let tokens = estimateTokens(m.content || '') + 4;
|
|
25
|
-
// Count tool-call arguments — a transcript dominated by large write_file
|
|
26
|
-
// bodies or long bash commands would otherwise under-count massively.
|
|
27
|
-
if (m.toolCalls) {
|
|
28
|
-
for (const tc of m.toolCalls) {
|
|
29
|
-
tokens += estimateTokens(tc.arguments);
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return sum + tokens;
|
|
33
|
-
}, 0);
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
export interface CompactionConfig {
|
|
37
|
-
maxTokens: number;
|
|
38
|
-
reservedTokens: number;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export function shouldCompact(messages: CompactableMessage[], config: CompactionConfig): boolean {
|
|
42
|
-
const used = estimateMessagesTokens(messages);
|
|
43
|
-
return used > config.maxTokens - config.reservedTokens;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
const KEEP_RECENT = 5;
|
|
47
|
-
const TOOL_TRUNCATE = 200;
|
|
48
|
-
const ASSISTANT_TRUNCATE = 500;
|
|
49
|
-
|
|
50
|
-
export function compactMessages<T extends CompactableMessage>(
|
|
51
|
-
messages: T[],
|
|
52
|
-
config: CompactionConfig,
|
|
53
|
-
): {messages: T[]; summary: string} {
|
|
54
|
-
if (!shouldCompact(messages, config)) {
|
|
55
|
-
return {messages, summary: ''};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
if (messages.length <= KEEP_RECENT + 1) {
|
|
59
|
-
return compactToolResults(messages);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
// Never inject a synthetic `system` message mid-conversation: the caller owns
|
|
63
|
-
// the system prompt. If the caller already stored it as the first message,
|
|
64
|
-
// fold the compaction note into that single system message instead.
|
|
65
|
-
const hasSystem = messages[0]?.role === 'system';
|
|
66
|
-
const body = hasSystem ? messages.slice(1) : messages;
|
|
67
|
-
// The old/recent split must never fall between an assistant message that
|
|
68
|
-
// carries `tool_calls` and the `tool` messages answering it. If it does, the
|
|
69
|
-
// trimmed half keeps one side and drops the other, and the provider rejects
|
|
70
|
-
// the history with a 400 ("assistant message with 'tool_calls' must be
|
|
71
|
-
// followed by tool messages responding to each 'tool_call_id'").
|
|
72
|
-
// Walk the boundary backwards until it sits at a clean group edge.
|
|
73
|
-
const split = safeSplitIndex(body, body.length - KEEP_RECENT);
|
|
74
|
-
const old = body.slice(0, split);
|
|
75
|
-
const recent = body.slice(split);
|
|
76
|
-
|
|
77
|
-
const summary = `[Context compacted: ${old.length} older messages truncated to save tokens]`;
|
|
78
|
-
|
|
79
|
-
const compacted = old.map((m) => {
|
|
80
|
-
if (m.role === 'tool') {
|
|
81
|
-
return {...m, content: truncateContent(m.content, TOOL_TRUNCATE)};
|
|
82
|
-
}
|
|
83
|
-
if (m.role === 'assistant' && m.toolCalls) {
|
|
84
|
-
return {
|
|
85
|
-
...m,
|
|
86
|
-
content: truncateContent(m.content, 100),
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
if (m.role === 'assistant' && m.content) {
|
|
90
|
-
return {...m, content: truncateContent(m.content, ASSISTANT_TRUNCATE)};
|
|
91
|
-
}
|
|
92
|
-
return m;
|
|
93
|
-
});
|
|
94
|
-
|
|
95
|
-
if (hasSystem) {
|
|
96
|
-
const system = messages[0];
|
|
97
|
-
const mergedSystem: T = {
|
|
98
|
-
...system,
|
|
99
|
-
content: system.content ? `${system.content}\n\n${summary}` : summary,
|
|
100
|
-
};
|
|
101
|
-
return {messages: [mergedSystem, ...compacted, ...recent], summary};
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
return {messages: [...compacted, ...recent], summary};
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
* Adjust an old/recent split point so it never lands inside a tool-call group.
|
|
109
|
-
*
|
|
110
|
-
* A group is an `assistant` message with `toolCalls` followed by one `tool`
|
|
111
|
-
* message per call. Slicing through the middle of that group leaves the two
|
|
112
|
-
* halves inconsistent — the provider then rejects the request with a 400.
|
|
113
|
-
*
|
|
114
|
-
* We move the boundary *backwards* to the start of the group, so the whole
|
|
115
|
-
* group stays in `recent` (kept verbatim) rather than being split.
|
|
116
|
-
*/
|
|
117
|
-
function safeSplitIndex(messages: CompactableMessage[], split: number): number {
|
|
118
|
-
let i = Math.max(0, Math.min(split, messages.length));
|
|
119
|
-
// If the first message of `recent` is a `tool` result, its owning assistant
|
|
120
|
-
// call is just before the boundary — walk back to include it.
|
|
121
|
-
while (i > 0 && messages[i]?.role === 'tool') i--;
|
|
122
|
-
return i;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
function compactToolResults<T extends CompactableMessage>(
|
|
126
|
-
messages: T[],
|
|
127
|
-
): {messages: T[]; summary: string} {
|
|
128
|
-
const compacted = messages.map((m) => {
|
|
129
|
-
if (m.role === 'tool' && m.content && estimateTokens(m.content) > TOOL_TRUNCATE) {
|
|
130
|
-
return {...m, content: truncateContent(m.content, TOOL_TRUNCATE)};
|
|
131
|
-
}
|
|
132
|
-
return m;
|
|
133
|
-
});
|
|
134
|
-
return {messages: compacted, summary: '[Large tool results truncated]'};
|
|
135
|
-
}
|
|
136
|
-
|
|
137
|
-
function truncateContent(content: string, maxChars: number): string {
|
|
138
|
-
if (!content || content.length <= maxChars) return content;
|
|
139
|
-
return (
|
|
140
|
-
content.slice(0, maxChars) + `\n... [truncated, ${content.length - maxChars} chars removed]`
|
|
141
|
-
);
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// ---------------------------------------------------------------------------
|
|
145
|
-
// Model view — the ONLY thing sent to the provider
|
|
146
|
-
// ---------------------------------------------------------------------------
|
|
147
|
-
|
|
148
|
-
export interface ModelView<T extends CompactableMessage> {
|
|
149
|
-
/** Messages the model should see (everything after the high-water mark). */
|
|
150
|
-
messages: T[];
|
|
151
|
-
/** Summary text to fold into the system prompt ('' when nothing compacted). */
|
|
152
|
-
note: string;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
/**
|
|
156
|
-
* Build the view the model is fed.
|
|
157
|
-
*
|
|
158
|
-
* This is the single source of truth for "what the model sees": the compaction
|
|
159
|
-
* trigger, the persisted high-water mark, and the request payload must all agree,
|
|
160
|
-
* otherwise the boundary drifts and we either resend summarized history or drop
|
|
161
|
-
* unsummarized turns.
|
|
162
|
-
*
|
|
163
|
-
* `compactedUpto` is a COUNT of leading messages already folded into `note`
|
|
164
|
-
* (1-based seq equivalence). Everything at or below it is replaced by the note;
|
|
165
|
-
* everything above it is sent verbatim.
|
|
166
|
-
*/
|
|
167
|
-
export function buildModelView<T extends CompactableMessage>(
|
|
168
|
-
messages: readonly T[],
|
|
169
|
-
compactedUpto: number,
|
|
170
|
-
note: string,
|
|
171
|
-
): ModelView<T> {
|
|
172
|
-
if (compactedUpto <= 0) return {messages: messages as T[], note: ''};
|
|
173
|
-
const kept = (messages as T[]).slice(Math.min(compactedUpto, messages.length));
|
|
174
|
-
return {messages: kept, note};
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// ---------------------------------------------------------------------------
|
|
178
|
-
// LLM-backed summarization
|
|
179
|
-
// ---------------------------------------------------------------------------
|
|
180
|
-
|
|
181
|
-
/** Minimal provider surface needed to summarize (keeps this module provider-free). */
|
|
182
|
-
export interface Summarizer {
|
|
183
|
-
(prompt: string): Promise<string>;
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
const SUMMARY_SYSTEM_PROMPT =
|
|
187
|
-
'You compress coding-agent conversation history. Produce a dense, factual ' +
|
|
188
|
-
'summary that preserves decisions made, files changed, commands run, errors ' +
|
|
189
|
-
'encountered, and any constraints or preferences the user stated. Omit ' +
|
|
190
|
-
'pleasantries and redundant tool output. Write in compact prose or bullets. ' +
|
|
191
|
-
'Do not address the user; this summary replaces the messages it describes.';
|
|
192
|
-
|
|
193
|
-
/**
|
|
194
|
-
* Summarize a range of older messages into a checkpoint string.
|
|
195
|
-
*
|
|
196
|
-
* Falls back to a deterministic truncation summary when the model call fails,
|
|
197
|
-
* so a flaky provider never aborts the turn (the worst case is a less useful —
|
|
198
|
-
* but still valid — checkpoint).
|
|
199
|
-
*/
|
|
200
|
-
export async function summarizeRange(
|
|
201
|
-
messages: readonly CompactableMessage[],
|
|
202
|
-
summarize: Summarizer,
|
|
203
|
-
): Promise<string> {
|
|
204
|
-
const transcript = messages
|
|
205
|
-
.map((m) => {
|
|
206
|
-
const role = m.role === 'tool' ? 'tool' : m.role;
|
|
207
|
-
const body = m.content?.trim() ? m.content.trim() : '(no text)';
|
|
208
|
-
const calls = m.toolCalls?.length
|
|
209
|
-
? `\n[tool calls: ${m.toolCalls.map((c) => c.name).join(', ')}]`
|
|
210
|
-
: '';
|
|
211
|
-
return `<${role}>\n${body}${calls}`;
|
|
212
|
-
})
|
|
213
|
-
.join('\n\n');
|
|
214
|
-
|
|
215
|
-
const prompt = `${SUMMARY_SYSTEM_PROMPT}\n\n---\n\nConversation to summarize:\n\n${transcript}`;
|
|
216
|
-
|
|
217
|
-
try {
|
|
218
|
-
const summary = (await summarize(prompt)).trim();
|
|
219
|
-
if (summary) return summary;
|
|
220
|
-
} catch {
|
|
221
|
-
// fall through to the deterministic fallback
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
return `[Context compacted: ${messages.length} older messages summarized]`;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/**
|
|
228
|
-
* Pick the seq boundary to compact up to, without ever splitting a tool-call
|
|
229
|
-
* group. Returns the count of leading messages that may be summarized away.
|
|
230
|
-
*
|
|
231
|
-
* The boundary is walked backwards over `tool` messages so an assistant message
|
|
232
|
-
* carrying `tool_calls` is never separated from the results answering it — the
|
|
233
|
-
* exact rule `sanitizeWireMessages` enforces at the wire.
|
|
234
|
-
*/
|
|
235
|
-
export function compactionBoundary<T extends CompactableMessage>(
|
|
236
|
-
messages: readonly T[],
|
|
237
|
-
keepRecent: number,
|
|
238
|
-
): number {
|
|
239
|
-
let split = Math.max(0, messages.length - keepRecent);
|
|
240
|
-
while (split > 0 && messages[split]?.role === 'tool') split--;
|
|
241
|
-
return split;
|
|
242
|
-
}
|
|
243
|
-
|
|
@@ -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
|
-
});
|