@pal-code/core 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/package.json +38 -0
- package/src/agent/events.ts +36 -0
- package/src/agent/fallback.ts +344 -0
- package/src/agent/index.ts +35 -0
- package/src/agent/roles.ts +193 -0
- package/src/agent/run.ts +713 -0
- package/src/agent/scope.ts +34 -0
- package/src/agent/todos.ts +66 -0
- package/src/compaction.ts +243 -0
- package/src/config.ts +387 -0
- package/src/extensions.ts +234 -0
- package/src/index.ts +157 -0
- package/src/logger.ts +54 -0
- package/src/provider/auth.ts +153 -0
- package/src/provider/complete.ts +63 -0
- package/src/provider/index.ts +6 -0
- package/src/provider/openrouter.ts +304 -0
- package/src/provider/pick-model.ts +43 -0
- package/src/provider/registry.ts +222 -0
- package/src/provider/types.ts +61 -0
- package/src/registry.ts +63 -0
- package/src/repo-map.ts +177 -0
- package/src/session/index.ts +2 -0
- package/src/session/store.ts +677 -0
- package/src/session/types.ts +72 -0
- package/src/snapshots.ts +107 -0
- package/src/tools/definitions.ts +365 -0
- package/src/tools/executor.ts +1364 -0
- package/src/tools/index.ts +5 -0
- package/src/tools/search.ts +201 -0
|
@@ -0,0 +1,34 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,243 @@
|
|
|
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
|
+
|