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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pal-code",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "A terminal coding agent with BYOK, tool use, and extensions",
5
5
  "license": "MIT",
6
6
  "engines": {
@@ -18,11 +18,14 @@
18
18
  },
19
19
  "files": [
20
20
  "bin/",
21
- "scripts/",
21
+ "scripts/postinstall.js",
22
+ "scripts/preinstall.js",
22
23
  "packages/cli/src/**/*.ts",
23
24
  "packages/cli/src/**/*.tsx",
24
25
  "packages/core/src/**/*.ts",
25
26
  "packages/core/src/**/*.tsx",
27
+ "!**/*.test.ts",
28
+ "!**/*.test.js",
26
29
  "!packages/core/src/**/*.test.db",
27
30
  "!packages/core/src/**/*.test-*.db",
28
31
  "SYSTEM.md",
@@ -64,6 +67,10 @@
64
67
  "anthropic",
65
68
  "gemini"
66
69
  ],
70
+ "dependencies": {
71
+ "@earendil-works/pi-tui": "^0.85.1",
72
+ "cheerio": "^1.0.0"
73
+ },
67
74
  "devDependencies": {
68
75
  "@biomejs/biome": "^2.5.13",
69
76
  "@types/bun": "latest",
@@ -26,8 +26,6 @@ import {
26
26
  detectCapabilities,
27
27
  } from '@earendil-works/pi-tui';
28
28
  import type {TUI} from '@earendil-works/pi-tui';
29
- import pkg from '../package.json';
30
-
31
29
  import {c, editorTheme, agentColors, agentLabels, colorByName} from './theme.js';
32
30
  import {generateTitle, sanitizeTitle, formatMessageTimestamp} from './utils/format.js';
33
31
  import {MessageBox} from './components/message-box.js';
@@ -82,8 +80,8 @@ import type {SessionStore as SessionStoreType} from '@pal/core';
82
80
  // Model lists are now resolved dynamically from each provider's /models endpoint
83
81
  // (see buildModelOptions). Static curated lists live in @pal/core PROVIDERS as fallback.
84
82
 
85
- // Single source of truth — no more drift from package.json.
86
- const VERSION = pkg.version;
83
+ // Version synced from version.json via `node scripts/sync-version.js`.
84
+ const VERSION = '0.0.9';
87
85
 
88
86
  import {showModelSelector} from './overlays/model-picker.js';
89
87
  import {showKeyInput} from './overlays/key-input.js';
@@ -1,167 +0,0 @@
1
- import {describe, expect, test} from 'bun:test';
2
- import {stripTerminalSequences} from '@earendil-works/pi-tui';
3
-
4
- import {userMessageBox, wrapText, truncate, displayWidth} from './format.js';
5
-
6
- const plain = (s: string) => stripTerminalSequences(s);
7
-
8
- /** Every row of the box must be exactly `width` visible columns wide. */
9
- function expectRectangular(box: string, width: number) {
10
- const W = Math.max(6, Math.floor(width));
11
- const lines = box.split('\n');
12
- for (const line of lines) {
13
- expect(displayWidth(line)).toBe(W);
14
- }
15
- expect(plain(lines[0]!).startsWith('╭')).toBe(true);
16
- expect(plain(lines.at(-1)!).startsWith('╰')).toBe(true);
17
- }
18
-
19
- const ROLES = ['pal', 'build', 'architect', 'web-search', ''] as const;
20
-
21
- const INPUTS: Array<[string, string]> = [
22
- ['short', 'hello'],
23
- ['multiline', 'first line\nsecond line'],
24
- ['wraps', 'the quick brown fox jumps over the lazy dog and keeps running'],
25
- ['empty', ''],
26
- ['whitespace', ' '],
27
- ['trailing newline', 'done\n'],
28
- ['crlf', 'a\r\nb'],
29
- ['tabs', '\tindented\ttext'],
30
- ['ansi', `\x1b[31mred\x1b[0m and \x1b[1mbold\x1b[0m`],
31
- ['cjk', '你好世界,这是一个测试'],
32
- ['emoji', 'ship it 🚀🎉 with 👨‍👩‍👧 family'],
33
- ['long word', 'x'.repeat(120)],
34
- ];
35
-
36
- describe('userMessageBox', () => {
37
- test('every row is exactly `width` columns for all widths, roles and inputs', () => {
38
- for (const width of [2, 4, 6, 8, 12, 20, 40, 80]) {
39
- for (const role of ROLES) {
40
- for (const [name, input] of INPUTS) {
41
- const box = userMessageBox(input, width, role);
42
- try {
43
- expectRectangular(box, width);
44
- } catch (err) {
45
- throw new Error(`width=${width} role=${role || '(empty)'} input=${name}: ${err}`);
46
- }
47
- }
48
- }
49
- }
50
- });
51
-
52
- test('shows the role tag once it fits, and drops it when it does not', () => {
53
- expect(plain(userMessageBox('hi', 40, 'build'))).toContain('[builder]');
54
- // '[build]' is 9 wide; it needs width >= 15.
55
- expect(plain(userMessageBox('hi', 14, 'build'))).not.toContain('[builder]');
56
- });
57
-
58
- test('timestamped header stays rectangular across widths, roles and stamps', () => {
59
- const stamps = ['Mon 14:30', 'Mon 15 Jan 14:30', 'Mon 15 Jan 2025 14:30', ''];
60
- for (const width of [2, 4, 6, 8, 12, 20, 30, 40, 80, 120]) {
61
- for (const role of ROLES) {
62
- for (const ts of stamps) {
63
- const box = userMessageBox('hello', width, role, ts);
64
- try {
65
- expectRectangular(box, width);
66
- } catch (err) {
67
- throw new Error(`width=${width} role=${role || '(empty)'} ts="${ts}": ${err}`);
68
- }
69
- }
70
- }
71
- }
72
- });
73
-
74
- test('timestamp renders opposite the tag when there is room', () => {
75
- const box = plain(userMessageBox('hi', 60, 'build', 'Mon 14:30'));
76
- const header = box.split('\n')[0]!;
77
- expect(header).toContain('[builder]');
78
- expect(header).toContain('Mon 14:30');
79
- // tag left of timestamp
80
- expect(header.indexOf('[builder]')).toBeLessThan(header.indexOf('Mon 14:30'));
81
- });
82
-
83
- test('timestamp is dropped before the tag when the box is narrow', () => {
84
- // Wide enough for '[builder]' (needs 15) but not for tag + timestamp.
85
- const box = plain(userMessageBox('hi', 16, 'build', 'Mon 15 Jan 2025 14:30'));
86
- const header = box.split('\n')[0]!;
87
- expect(header).toContain('[builder]');
88
- expect(header).not.toContain('2025');
89
- });
90
-
91
- test('renders a golden box for a short message', () => {
92
- const expected =
93
- `╭─ [pal] ${'─'.repeat(10)}╮\n` + `│ hi${' '.repeat(14)} │\n` + `╰${'─'.repeat(18)}╯`;
94
- expect(plain(userMessageBox('hi', 20, 'pal'))).toBe(expected);
95
- });
96
-
97
- test('never throws on degenerate widths', () => {
98
- for (const width of [-10, 0, 1, 3, 5]) {
99
- expect(() => userMessageBox('hello world', width, 'pal')).not.toThrow();
100
- }
101
- });
102
- });
103
-
104
- describe('wrapText', () => {
105
- test('wraps words to the given width', () => {
106
- expect(wrapText('one two three four', 8)).toEqual(['one two', 'three', 'four']);
107
- });
108
-
109
- test('hard-breaks words longer than the width', () => {
110
- const lines = wrapText('abcdefghij', 4);
111
- expect(lines.every((l) => displayWidth(l) <= 4)).toBe(true);
112
- expect(lines.join('')).toBe('abcdefghij');
113
- });
114
-
115
- test('splits on CRLF, CR and LF alike', () => {
116
- expect(wrapText('a\r\nb\rc\nd', 10)).toEqual(['a', 'b', 'c', 'd']);
117
- });
118
-
119
- test('keeps a hanging indent on continuation lines', () => {
120
- const lines = wrapText(' alpha beta gamma delta', 12);
121
- for (const line of lines.slice(1)) expect(line.startsWith(' ')).toBe(true);
122
- });
123
-
124
- test('preserves ANSI styling across the wrap', () => {
125
- const lines = wrapText('\x1b[31mred red red red red\x1b[0m', 7);
126
- expect(lines.every((l) => displayWidth(l) <= 7)).toBe(true);
127
- expect(lines.join('')).toContain('red');
128
- });
129
-
130
- test('returns a single empty line for empty input', () => {
131
- expect(wrapText('', 10)).toEqual(['']);
132
- });
133
- });
134
-
135
- describe('truncate', () => {
136
- test('never returns more than `max` characters', () => {
137
- const text = 'hello world';
138
- for (let max = -2; max <= text.length + 2; max++) {
139
- expect(truncate(text, max).length).toBeLessThanOrEqual(Math.max(0, max));
140
- }
141
- });
142
-
143
- test('adds an ellipsis when there is room for one', () => {
144
- expect(truncate('hello world', 8)).toBe('hello...');
145
- });
146
-
147
- test('hard-cuts when the budget cannot fit an ellipsis', () => {
148
- expect(truncate('hello world', 3)).toBe('hel');
149
- expect(truncate('hello world', 0)).toBe('');
150
- expect(truncate('hello world', -5)).toBe('');
151
- });
152
-
153
- test('leaves short enough text untouched', () => {
154
- expect(truncate('hi', 5)).toBe('hi');
155
- expect(truncate('', 5)).toBe('');
156
- });
157
- });
158
-
159
- describe('displayWidth', () => {
160
- test('ignores ANSI codes', () => {
161
- expect(displayWidth('\x1b[31mred\x1b[0m')).toBe(3);
162
- });
163
-
164
- test('counts wide characters as two columns', () => {
165
- expect(displayWidth('你好')).toBe(4);
166
- });
167
- });
@@ -1,99 +0,0 @@
1
- import {test, expect} from 'bun:test';
2
- import {isRetryableError, isQuotaExhausted, isRateLimited, shortModel} from './fallback.js';
3
- import {rollbackTurn, type ConversationMessage} from './run.js';
4
-
5
- // ── error classification ─────────────────────────────────────────────────────
6
- // Getting this wrong is expensive: treating a transient network blip as fatal
7
- // kills the whole turn (this actually happened — Bun's "Was there a typo in the
8
- // url or port?" was unclassified and ended a `judge my project` run).
9
-
10
- test('isRetryableError: transient transport failures are retryable', () => {
11
- for (const msg of [
12
- 'Was there a typo in the url or port?',
13
- 'fetch failed',
14
- 'ECONNRESET',
15
- 'ECONNREFUSED',
16
- 'ENOTFOUND',
17
- 'ETIMEDOUT',
18
- 'EAI_AGAIN',
19
- 'socket hang up',
20
- ]) {
21
- expect(isRetryableError(msg)).toBe(true);
22
- }
23
- });
24
-
25
- test('isRetryableError: a user abort must NOT be retried', () => {
26
- // Aborting is intentional — retrying it would fight the Esc key.
27
- expect(isRetryableError('The operation was aborted')).toBe(false);
28
- expect(isRetryableError('AbortError')).toBe(false);
29
- });
30
-
31
- test('isRetryableError: rate/availability errors are retryable', () => {
32
- for (const msg of [
33
- '429 Too Many Requests',
34
- 'Rate limit exceeded',
35
- '503 Service Unavailable',
36
- 'unavailable',
37
- ]) {
38
- expect(isRetryableError(msg)).toBe(true);
39
- }
40
- });
41
-
42
- test('isRetryableError: a genuine 4xx validation error is NOT retryable', () => {
43
- expect(isRetryableError('400 Invalid model name')).toBe(false);
44
- expect(isRetryableError('JSON Parse error: Unexpected EOF')).toBe(false);
45
- });
46
-
47
- test('isQuotaExhausted: quota errors must not be retried', () => {
48
- expect(isQuotaExhausted('insufficient_quota')).toBe(true);
49
- expect(isQuotaExhausted('FreeUsageLimitError')).toBe(true);
50
- expect(isQuotaExhausted('429 rate limit')).toBe(false);
51
- });
52
-
53
- test('isRateLimited: only actual RPM limits', () => {
54
- expect(isRateLimited('429 Too Many Requests')).toBe(true);
55
- expect(isRateLimited('rate-limit exceeded')).toBe(true);
56
- expect(isRateLimited('503 unavailable')).toBe(false);
57
- });
58
-
59
- test('shortModel strips provider prefix and variant suffix', () => {
60
- expect(shortModel('deepseek/deepseek-v4-pro')).toBe('deepseek-v4-pro');
61
- expect(shortModel('openrouter/anthropic/claude:high')).toBe('claude');
62
- expect(shortModel('bare-model')).toBe('bare-model');
63
- });
64
-
65
- // ── rollback ─────────────────────────────────────────────────────────────────
66
- // A failure mid-tool leaves assistant(toolCalls) + tool results behind. Dropping
67
- // only the user message corrupts the next request.
68
-
69
- function user(content: string): ConversationMessage {
70
- return {role: 'user', content};
71
- }
72
-
73
- test('rollbackTurn: drops a bare unanswered user message', () => {
74
- const messages: ConversationMessage[] = [user('one'), user('two')];
75
- expect(rollbackTurn(messages)).toBe(1);
76
- expect(messages).toEqual([user('one')]);
77
- });
78
-
79
- test('rollbackTurn: drops the whole failing round, keeping prior turns', () => {
80
- // A failure mid-tool leaves assistant(toolCalls) + a partial tool result.
81
- const messages: ConversationMessage[] = [
82
- user('first turn'),
83
- {role: 'assistant', content: 'done, anything else?'},
84
- user('the failed turn'),
85
- {role: 'assistant', content: '', toolCalls: [{id: 'c1', name: 'read_file', arguments: '{}'}]},
86
- {role: 'tool', tool_call_id: 'c1', content: 'partial…'},
87
- ];
88
- expect(rollbackTurn(messages)).toBe(2);
89
- expect(messages).toEqual([
90
- user('first turn'),
91
- {role: 'assistant', content: 'done, anything else?'},
92
- ]);
93
- });
94
-
95
- test('rollbackTurn: leaves a transcript with no user message untouched', () => {
96
- const messages: ConversationMessage[] = [{role: 'tool', tool_call_id: 'c1', content: 'orphan'}];
97
- expect(rollbackTurn(messages)).toBe(1);
98
- expect(messages.length).toBe(1);
99
- });
@@ -1,136 +0,0 @@
1
- import {test, expect} from 'bun:test';
2
- import {runAgent, buildApiMessages, type ConversationMessage, type AgentRunEvent} from './run.js';
3
-
4
- type Wire = Record<string, unknown> & {role: string; tool_call_id?: string};
5
-
6
- /**
7
- * The invariant an OpenAI-compatible endpoint enforces: every assistant message
8
- * carrying `tool_calls` must be immediately followed by one `tool` message per
9
- * call id — nothing else may sit between them. A violation returns:
10
- * 400 "An assistant message with 'tool_calls' must be followed by tool messages
11
- * responding to each 'tool_call_id'."
12
- */
13
- function assertProtocolValid(wire: Wire[]): void {
14
- for (let i = 0; i < wire.length; i++) {
15
- const msg = wire[i];
16
- if (msg.role !== 'assistant' || !Array.isArray(msg.tool_calls)) continue;
17
-
18
- const ids = (msg.tool_calls as Array<{id: string}>).map((tc) => tc.id);
19
- const expected = new Set(ids);
20
- const seen: string[] = [];
21
-
22
- for (let j = i + 1; j < wire.length; j++) {
23
- const next = wire[j];
24
- if (next.role !== 'tool') break; // any non-tool message ends the group
25
- seen.push(String(next.tool_call_id));
26
- }
27
-
28
- expect({assistantId: i, seen}).toEqual({assistantId: i, seen: ids});
29
- for (const id of seen) expected.delete(id);
30
- expect([...expected]).toEqual([]);
31
- }
32
- }
33
-
34
- type FakeEvent =
35
- | {type: 'text'; content: string}
36
- | {type: 'tool_use'; toolCall: {id: string; name: string; arguments: string}}
37
- | {type: 'done'; usage?: {promptTokens: number; completionTokens: number; totalTokens: number}}
38
- | {type: 'error'; content: string};
39
-
40
- async function collect(gen: AsyncGenerator<AgentRunEvent>): Promise<AgentRunEvent[]> {
41
- const out: AgentRunEvent[] = [];
42
- for await (const ev of gen) out.push(ev);
43
- return out;
44
- }
45
-
46
- test('repro: the repeat-nudge must not split a tool_calls group', async () => {
47
- // Two tools per round with IDENTICAL args so the repeat counter trips while
48
- // the group is still being written. Round 1: calls trip the counter (×3)
49
- // and emit the "[pal] ... repeated" nudge. That nudge is a `user` message.
50
- const messages: ConversationMessage[] = [{role: 'user', content: 'spin'}];
51
-
52
- const dup = (id: string) => ({
53
- type: 'tool_use' as const,
54
- toolCall: {id, name: 'bash', arguments: '{"command":"x"}'},
55
- });
56
-
57
- // 4 identical calls in one round → n=1,2,3 → nudge fires after the 3rd,
58
- // leaving the 4th tool result to be appended AFTER the nudge.
59
- const provider = {
60
- async *stream(): AsyncGenerator<FakeEvent> {
61
- yield dup('c1');
62
- yield dup('c2');
63
- yield dup('c3');
64
- yield dup('c4');
65
- yield {type: 'done'};
66
- },
67
- };
68
-
69
- await collect(
70
- runAgent({
71
- messages,
72
- tools: [],
73
- model: 'test',
74
- systemPrompt: 'sys',
75
- provider: provider as never,
76
- providerConfig: {model: 'test', apiKey: 'k', baseUrl: 'http://x'},
77
- executeTool: async () => ({content: 'ok'}),
78
- maxRounds: 1,
79
- } as never),
80
- );
81
-
82
- const wire = buildApiMessages(messages, 'sys') as Wire[];
83
- assertProtocolValid(wire);
84
- });
85
-
86
- // ── sanitizeWireMessages: the safety net for histories we did NOT build ───────
87
-
88
- test('sanitize: drops a tool_calls id whose result never arrived', async () => {
89
- const {sanitizeWireMessages} = await import('./run.js');
90
- const wire = sanitizeWireMessages([
91
- {role: 'system', content: 'sys'},
92
- {
93
- role: 'assistant',
94
- content: '',
95
- tool_calls: [
96
- {id: 'a', type: 'function', function: {name: 'x', arguments: '{}'}},
97
- {id: 'b', type: 'function', function: {name: 'y', arguments: '{}'}},
98
- ],
99
- },
100
- {role: 'tool', tool_call_id: 'a', content: 'ok'},
101
- // 'b' never got a result (e.g. crash mid-round, or old session).
102
- ]);
103
-
104
- assertProtocolValid(wire as Wire[]);
105
- const assistant = wire.find((m) => m.role === 'assistant') as {tool_calls: Array<{id: string}>};
106
- expect(assistant.tool_calls.map((c) => c.id)).toEqual(['a']);
107
- });
108
-
109
- test('sanitize: drops an orphaned tool result with no owning assistant call', async () => {
110
- const {sanitizeWireMessages} = await import('./run.js');
111
- const wire = sanitizeWireMessages([
112
- {role: 'system', content: 'sys'},
113
- {role: 'user', content: 'hi'},
114
- {role: 'tool', tool_call_id: 'ghost', content: 'stray'},
115
- ]);
116
-
117
- expect(wire.some((m) => m.role === 'tool')).toBe(false);
118
- assertProtocolValid(wire as Wire[]);
119
- });
120
-
121
- test('sanitize: demotes a tool_calls message with zero results to plain text', async () => {
122
- const {sanitizeWireMessages} = await import('./run.js');
123
- const wire = sanitizeWireMessages([
124
- {role: 'system', content: 'sys'},
125
- {
126
- role: 'assistant',
127
- content: 'thinking…',
128
- tool_calls: [{id: 'a', type: 'function', function: {name: 'x', arguments: '{}'}}],
129
- },
130
- ]);
131
-
132
- const assistant = wire.find((m) => m.role === 'assistant') as Record<string, unknown>;
133
- expect(assistant.tool_calls).toBeUndefined();
134
- expect(assistant.content).toBe('thinking…');
135
- assertProtocolValid(wire as Wire[]);
136
- });
@@ -1,116 +0,0 @@
1
- import {test, expect} from 'bun:test';
2
- import {rm} from 'fs/promises';
3
- import {join} from 'path';
4
- import {SessionStore} from '../session/store.js';
5
- import {seqToCount, buildApiMessages, type ConversationMessage} from './run.js';
6
-
7
- const DB_PATH = join(import.meta.dir, '.test-resume.db');
8
-
9
- /** Fresh store per test; the file is removed on exit so state can't leak. */
10
- function withStore<T>(fn: (store: SessionStore) => T): T {
11
- const store = new SessionStore({dbPath: DB_PATH});
12
- store.init();
13
- try {
14
- return fn(store);
15
- } finally {
16
- store.close();
17
- void rm(DB_PATH, {force: true});
18
- }
19
- }
20
-
21
- const convo: ConversationMessage[] = [
22
- {role: 'user', content: 'one'},
23
- {role: 'assistant', content: 'two'},
24
- {role: 'user', content: 'three'},
25
- {role: 'assistant', content: 'four'},
26
- {role: 'user', content: 'five'},
27
- ];
28
-
29
- /**
30
- * The bug this guards: the mark was persisted on every compaction but never
31
- * read back, so a resumed session re-sent (and re-summarized) the whole
32
- * already-compacted prefix. These tests pin the seq→count arithmetic that
33
- * makes resume correct, without needing a provider or the CLI.
34
- */
35
- test('seqToCount: a 1-based seq maps to a leading-message count', () => {
36
- // Store seqs are 1-based: seq 3 means the first 3 messages are summarized.
37
- expect(seqToCount(3, 5)).toBe(3);
38
- // A mark ahead of the in-memory transcript must clamp, not overrun.
39
- expect(seqToCount(99, 5)).toBe(5);
40
- // 0 / absent means nothing was compacted.
41
- expect(seqToCount(0, 5)).toBe(0);
42
- expect(seqToCount(Number.NaN, 5)).toBe(0);
43
- });
44
-
45
- test('resumed session: the summarized prefix is excluded from the wire', () => {
46
- withStore((store) => {
47
- const s = store.create(convo);
48
- // Summarize the first three messages, then "resume" by reloading the rows.
49
- store.recordCompaction(s.id, 1, 3, 'summary of one..three');
50
- expect(store.getCompactedUpto(s.id)).toBe(3);
51
-
52
- // Resume reconstructs the FULL transcript from stored rows, in seq order.
53
- const resumed = store.getMessages(s.id).map((r) => ({
54
- role: r.role,
55
- content: r.content,
56
- })) as ConversationMessage[];
57
- expect(resumed.length).toBe(5);
58
-
59
- // The model view hides the summarized prefix and carries the summary note.
60
- const compactedUpto = seqToCount(store.getCompactedUpto(s.id), resumed.length);
61
- expect(compactedUpto).toBe(3);
62
-
63
- const wire = buildApiMessages(resumed, 'sys', 'summary of one..three', compactedUpto);
64
- const contents = wire.filter((m) => m.role !== 'system').map((m) => m.content);
65
-
66
- expect(contents).toEqual(['four', 'five']);
67
- expect(contents).not.toContain('one');
68
- // The summary note rides along in the system prompt so context isn't lost.
69
- expect(String(wire[0].content)).toContain('summary of one..three');
70
- });
71
- });
72
-
73
- test('no compaction recorded: resume sends the whole transcript', () => {
74
- withStore((store) => {
75
- const s = store.create(convo);
76
- expect(store.getCompactedUpto(s.id)).toBe(0);
77
-
78
- const resumed = store.getMessages(s.id).map((r) => ({
79
- role: r.role,
80
- content: r.content,
81
- })) as ConversationMessage[];
82
- const compactedUpto = seqToCount(store.getCompactedUpto(s.id), resumed.length);
83
-
84
- const wire = buildApiMessages(resumed, 'sys', '', compactedUpto);
85
- expect(wire.filter((m) => m.role !== 'system').map((m) => m.content)).toEqual([
86
- 'one',
87
- 'two',
88
- 'three',
89
- 'four',
90
- 'five',
91
- ]);
92
- });
93
- });
94
-
95
- test('rolled-back turn resets the mark, so resume over-sends rather than mis-slices', () => {
96
- withStore((store) => {
97
- const s = store.create(convo);
98
- store.recordCompaction(s.id, 1, 5, 'summary of all five');
99
- expect(store.getCompactedUpto(s.id)).toBe(5);
100
-
101
- // A failed turn drops the suffix that overlapped the mark.
102
- store.deleteMessagesFrom(s.id, 3);
103
- expect(store.getCompactedUpto(s.id)).toBe(0);
104
-
105
- const resumed = store.getMessages(s.id).map((r) => ({
106
- role: r.role,
107
- content: r.content,
108
- })) as ConversationMessage[];
109
- const compactedUpto = seqToCount(store.getCompactedUpto(s.id), resumed.length);
110
- expect(compactedUpto).toBe(0);
111
-
112
- // Degrades to sending everything — never a slice past the end.
113
- const wire = buildApiMessages(resumed, 'sys', '', compactedUpto);
114
- expect(wire.filter((m) => m.role !== 'system').map((m) => m.content)).toEqual(['one', 'two']);
115
- });
116
- });