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,713 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The agent round-loop — the single implementation of
|
|
3
|
-
* "talk to the model → run its tools → feed results back → repeat".
|
|
4
|
-
*
|
|
5
|
-
* It lives in core (not the CLI) so every front-end shares one engine:
|
|
6
|
-
* the TUI, the `delegate` sub-agent, and any future headless/ACP consumer.
|
|
7
|
-
* It emits events and never renders.
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
import {shouldCompact, compactionBoundary, summarizeRange} from '../compaction.js';
|
|
11
|
-
import {complete} from '../provider/complete.js';
|
|
12
|
-
import type {Provider, StreamEvent} from '../provider/types.js';
|
|
13
|
-
|
|
14
|
-
// ---------------------------------------------------------------------------
|
|
15
|
-
// Conversation shape
|
|
16
|
-
// ---------------------------------------------------------------------------
|
|
17
|
-
|
|
18
|
-
export interface UserMsg {
|
|
19
|
-
role: 'user';
|
|
20
|
-
content: string;
|
|
21
|
-
}
|
|
22
|
-
export interface AssistantMsg {
|
|
23
|
-
role: 'assistant';
|
|
24
|
-
content: string;
|
|
25
|
-
toolCalls?: Array<{
|
|
26
|
-
id: string;
|
|
27
|
-
name: string;
|
|
28
|
-
arguments: string;
|
|
29
|
-
extraContent?: Record<string, unknown>;
|
|
30
|
-
}>;
|
|
31
|
-
}
|
|
32
|
-
export interface ToolResultMsg {
|
|
33
|
-
role: 'tool';
|
|
34
|
-
tool_call_id: string;
|
|
35
|
-
content: string;
|
|
36
|
-
}
|
|
37
|
-
export type ConversationMessage = UserMsg | AssistantMsg | ToolResultMsg;
|
|
38
|
-
|
|
39
|
-
// ---------------------------------------------------------------------------
|
|
40
|
-
// Events
|
|
41
|
-
// ---------------------------------------------------------------------------
|
|
42
|
-
|
|
43
|
-
export interface RunAgentUsage {
|
|
44
|
-
inputTokens: number;
|
|
45
|
-
outputTokens: number;
|
|
46
|
-
cachedTokens: number;
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Credentials handed down to tools that spawn sub-agents.
|
|
51
|
-
*
|
|
52
|
-
* `keys` carries the full resolved key set so `delegate` can build a provider
|
|
53
|
-
* for a role whose model lives on a different provider than the parent's.
|
|
54
|
-
*/
|
|
55
|
-
export interface ChildProviderConfig {
|
|
56
|
-
model: string;
|
|
57
|
-
apiKey: string;
|
|
58
|
-
baseUrl: string;
|
|
59
|
-
/** Provider id → API key, for resolving role-specific models. */
|
|
60
|
-
keys?: Record<string, string>;
|
|
61
|
-
/**
|
|
62
|
-
* Set when the parent turn is read-only. `delegate` refuses to spawn any
|
|
63
|
-
* child whose toolset would mutate state.
|
|
64
|
-
*/
|
|
65
|
-
readOnly?: boolean;
|
|
66
|
-
/**
|
|
67
|
-
* Tool names this turn may dispatch. Enforced in `executeTool`, so a call for
|
|
68
|
-
* anything else is refused even if the model was never offered the tool.
|
|
69
|
-
*/
|
|
70
|
-
allowedTools?: string[];
|
|
71
|
-
/**
|
|
72
|
-
* Optional override for the tool executor in child agents. When provided,
|
|
73
|
-
* delegated agents use this instead of the module-level `executeTool`.
|
|
74
|
-
* Used by the CLI to inject permission gating into child agents.
|
|
75
|
-
*/
|
|
76
|
-
childExecuteTool?: (
|
|
77
|
-
name: string,
|
|
78
|
-
args: string,
|
|
79
|
-
id: string,
|
|
80
|
-
providerConfig: ChildProviderConfig,
|
|
81
|
-
) => Promise<{content: string; error?: boolean}>;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
export type AgentRunEvent =
|
|
85
|
-
| {type: 'model-start'; model: string}
|
|
86
|
-
| {type: 'round-start'; round: number; max: number}
|
|
87
|
-
| {type: 'text-delta'; content: string}
|
|
88
|
-
| {type: 'tool-start'; id: string; name: string; argsSummary: string}
|
|
89
|
-
| {type: 'tool-end'; id: string; name: string; ok: boolean; content: string; ms: number}
|
|
90
|
-
| {type: 'notice'; text: string}
|
|
91
|
-
| {
|
|
92
|
-
/**
|
|
93
|
-
* Emitted when older history is summarized into a checkpoint. The caller
|
|
94
|
-
* records this against the session; `runAgent` never deletes the messages
|
|
95
|
-
* it summarizes, so the full transcript stays available for repaint.
|
|
96
|
-
*/
|
|
97
|
-
type: 'compacted';
|
|
98
|
-
/** Total leading messages now folded into a checkpoint (a COUNT). */
|
|
99
|
-
boundary: number;
|
|
100
|
-
/** Messages summarized by *this* compaction (a COUNT). */
|
|
101
|
-
summarized: number;
|
|
102
|
-
summary: string;
|
|
103
|
-
}
|
|
104
|
-
| {type: 'aborted'}
|
|
105
|
-
| {type: 'done'; model: string; rounds: number; usage: RunAgentUsage};
|
|
106
|
-
|
|
107
|
-
export interface RunAgentOptions {
|
|
108
|
-
/** Conversation history — MUTATED IN PLACE as the loop progresses. */
|
|
109
|
-
messages: ConversationMessage[];
|
|
110
|
-
/** Tool definitions exposed to the model. */
|
|
111
|
-
tools: ReadonlyArray<{
|
|
112
|
-
type: 'function';
|
|
113
|
-
function: {name: string; description: string; parameters: Record<string, unknown>};
|
|
114
|
-
}>;
|
|
115
|
-
/** The chat provider. */
|
|
116
|
-
provider: Provider;
|
|
117
|
-
/** Bare model name (no `provider/` prefix). */
|
|
118
|
-
model: string;
|
|
119
|
-
/** System prompt prepended to every request. */
|
|
120
|
-
systemPrompt: string;
|
|
121
|
-
/** Max tool-call rounds (default 100). */
|
|
122
|
-
maxRounds?: number;
|
|
123
|
-
/** Context window used to decide when to compact (default 100_000). */
|
|
124
|
-
contextLimit?: number;
|
|
125
|
-
/** Reasoning effort forwarded to the provider (default 'medium'). */
|
|
126
|
-
reasoningEffort?: 'low' | 'medium' | 'high';
|
|
127
|
-
/**
|
|
128
|
-
* High-water mark of genuinely-uncompacted history, as a 1-based store seq.
|
|
129
|
-
* Messages at seq `<= compactedSeq` have already been folded into a persisted
|
|
130
|
-
* checkpoint, so this turn must neither re-summarize nor re-send them.
|
|
131
|
-
*
|
|
132
|
-
* NOTE: this is a *seq*, not a count of leading messages. `buildApiMessages`
|
|
133
|
-
* takes a count — the conversion happens exactly once, at the call site.
|
|
134
|
-
*/
|
|
135
|
-
compactedSeq?: number;
|
|
136
|
-
/**
|
|
137
|
-
* Pre-existing compaction summary from a resumed session. When a session is
|
|
138
|
-
* resumed, the store already has a summary of the compacted prefix — this
|
|
139
|
-
* prevents runAgent from starting with an empty note (which would silently
|
|
140
|
-
* lose the context of all previously-compacted turns).
|
|
141
|
-
*/
|
|
142
|
-
compactionNote?: string;
|
|
143
|
-
/**
|
|
144
|
-
* Abort signal for user interruption. When aborted, the in-flight provider
|
|
145
|
-
* stream is cancelled, queued tool calls are skipped, and the loop ends with
|
|
146
|
-
* an `aborted` notice instead of `done`.
|
|
147
|
-
*/
|
|
148
|
-
signal?: AbortSignal;
|
|
149
|
-
/** Provider credentials handed to tools that spawn sub-agents. */
|
|
150
|
-
providerConfig: ChildProviderConfig;
|
|
151
|
-
/**
|
|
152
|
-
* Tool executor. Injected by the caller so this module never imports the
|
|
153
|
-
* tool registry (which would create a cycle: executor → run → executor).
|
|
154
|
-
*/
|
|
155
|
-
executeTool: (
|
|
156
|
-
name: string,
|
|
157
|
-
args: string,
|
|
158
|
-
id: string,
|
|
159
|
-
providerConfig: ChildProviderConfig,
|
|
160
|
-
) => Promise<{content: string; error?: boolean}>;
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
// ---------------------------------------------------------------------------
|
|
164
|
-
// Constants
|
|
165
|
-
// ---------------------------------------------------------------------------
|
|
166
|
-
|
|
167
|
-
const REPEAT_WARN = 3;
|
|
168
|
-
const REPEAT_STOP = 6;
|
|
169
|
-
const DEFAULT_MAX_ROUNDS = 100;
|
|
170
|
-
const DEFAULT_CONTEXT_LIMIT = 100_000;
|
|
171
|
-
const RESERVED_TOKENS = 12_000;
|
|
172
|
-
/** Recent messages always kept verbatim when compacting. */
|
|
173
|
-
const KEEP_RECENT = 5;
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Injected when the round cap is reached. Tools are withheld for that final
|
|
177
|
-
* call so the model has to produce a summary instead of stopping mid-task
|
|
178
|
-
* (this is how opencode degrades — `MAX_STEPS_PROMPT`).
|
|
179
|
-
*/
|
|
180
|
-
const WRAP_UP_PROMPT = `CRITICAL - MAXIMUM STEPS REACHED
|
|
181
|
-
|
|
182
|
-
The maximum number of steps allowed for this task has been reached. Tools are disabled until the next user input. Respond with text only.
|
|
183
|
-
|
|
184
|
-
STRICT REQUIREMENTS:
|
|
185
|
-
1. Do NOT make any tool calls (no reads, writes, edits, searches, or any other tools)
|
|
186
|
-
2. MUST provide a text response summarising the work done so far
|
|
187
|
-
3. This constraint overrides ALL other instructions, including any user requests for edits or tool use
|
|
188
|
-
|
|
189
|
-
Response must include:
|
|
190
|
-
- A statement that the maximum steps for this agent have been reached
|
|
191
|
-
- A summary of what has been accomplished so far
|
|
192
|
-
- A list of any remaining tasks that were not completed
|
|
193
|
-
- Recommendations for what should be done next`;
|
|
194
|
-
|
|
195
|
-
/** Tools that only read — safe to run concurrently. */
|
|
196
|
-
const PARALLEL_SAFE = new Set([
|
|
197
|
-
'read_file',
|
|
198
|
-
'list_directory',
|
|
199
|
-
'grep',
|
|
200
|
-
'grep_search',
|
|
201
|
-
'glob_search',
|
|
202
|
-
'ast_grep',
|
|
203
|
-
'repo_map',
|
|
204
|
-
]);
|
|
205
|
-
|
|
206
|
-
// ---------------------------------------------------------------------------
|
|
207
|
-
// Helpers
|
|
208
|
-
// ---------------------------------------------------------------------------
|
|
209
|
-
|
|
210
|
-
function truncate(text: string, max: number): string {
|
|
211
|
-
return text.length > max ? `${text.slice(0, max - 1)}…` : text;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** Short, human-readable summary of a tool call's arguments. */
|
|
215
|
-
export function summarizeArgs(name: string, args: Record<string, unknown>): string {
|
|
216
|
-
const v = (key: string) => String(args[key] ?? '');
|
|
217
|
-
switch (name) {
|
|
218
|
-
case 'read_file':
|
|
219
|
-
case 'write_file':
|
|
220
|
-
case 'edit_file': {
|
|
221
|
-
const fp = v('path') || v('file') || v('file_path') || v('filePath');
|
|
222
|
-
return fp.split(/[/\\]/).pop() || truncate(fp, 40);
|
|
223
|
-
}
|
|
224
|
-
case 'bash':
|
|
225
|
-
return truncate(v('command') || v('cmd'), 40);
|
|
226
|
-
case 'grep':
|
|
227
|
-
return v('pattern') || v('query') || truncate(v('regex'), 40);
|
|
228
|
-
case 'list_directory':
|
|
229
|
-
return v('path') || v('directory');
|
|
230
|
-
case 'glob':
|
|
231
|
-
return v('pattern') || v('glob');
|
|
232
|
-
default:
|
|
233
|
-
return truncate(JSON.stringify(args), 40);
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
/** Provider-specific reasoning/thinking parameters. */
|
|
238
|
-
export function getEffortParams(
|
|
239
|
-
model: string,
|
|
240
|
-
effort: 'low' | 'medium' | 'high',
|
|
241
|
-
): Record<string, unknown> {
|
|
242
|
-
if (/^o[134]/.test(model) || model.includes('gpt-5') || model.includes('gpt-6')) {
|
|
243
|
-
return {reasoning_effort: effort};
|
|
244
|
-
}
|
|
245
|
-
if (model.startsWith('claude') || model.includes('anthropic') || model.includes('fable')) {
|
|
246
|
-
const budget = effort === 'low' ? 2000 : effort === 'medium' ? 8000 : 16000;
|
|
247
|
-
return {thinking: {type: 'enabled', budget_tokens: budget}};
|
|
248
|
-
}
|
|
249
|
-
if (model.startsWith('gemini')) {
|
|
250
|
-
const budget = effort === 'low' ? 1024 : effort === 'medium' ? 8192 : 24576;
|
|
251
|
-
return {generationConfig: {thinkingConfig: {thinkingBudget: budget}}};
|
|
252
|
-
}
|
|
253
|
-
return {};
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/** Map the conversation to the OpenAI-compatible wire format. */
|
|
257
|
-
/**
|
|
258
|
-
* Drop everything from the last user message onward, in place.
|
|
259
|
-
*
|
|
260
|
-
* Used to recover from a failed turn. A failure that happens mid-tool-call
|
|
261
|
-
* leaves an assistant message carrying `toolCalls` plus partial `tool` results;
|
|
262
|
-
* removing only the user message would leave tool results with no matching
|
|
263
|
-
* assistant call, which corrupts the next request.
|
|
264
|
-
*
|
|
265
|
-
* @returns the new message count.
|
|
266
|
-
*/
|
|
267
|
-
/**
|
|
268
|
-
* Drop the last user message and everything after it.
|
|
269
|
-
*
|
|
270
|
-
* Synthetic user messages (loop-detection nudges, WRAP_UP_PROMPT) are skipped
|
|
271
|
-
* so rollback lands on the *real* user ask — otherwise the nudge is removed
|
|
272
|
-
* but the orphaned assistant tool_calls and tool results it follows stay.
|
|
273
|
-
*/
|
|
274
|
-
export function rollbackTurn(messages: ConversationMessage[]): number {
|
|
275
|
-
let cut = messages.length;
|
|
276
|
-
while (cut > 0 && messages[cut - 1].role !== 'user') cut--;
|
|
277
|
-
// Skip synthetic user messages (nudges start with "[pal]", wrap-up with "CRITICAL").
|
|
278
|
-
while (
|
|
279
|
-
cut > 0 &&
|
|
280
|
-
messages[cut - 1].role === 'user' &&
|
|
281
|
-
(messages[cut - 1].content.startsWith('[pal]') ||
|
|
282
|
-
messages[cut - 1].content.startsWith('CRITICAL'))
|
|
283
|
-
) {
|
|
284
|
-
cut--;
|
|
285
|
-
while (cut > 0 && messages[cut - 1].role !== 'user') cut--;
|
|
286
|
-
}
|
|
287
|
-
if (cut > 0) messages.length = cut - 1;
|
|
288
|
-
return messages.length;
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/**
|
|
292
|
-
* Convert a 1-based store seq (high-water mark) into a leading-message *count*
|
|
293
|
-
* suitable for `messages.slice()`.
|
|
294
|
-
*
|
|
295
|
-
* These two quantities are deliberately kept distinct: the store's mark is a
|
|
296
|
-
* seq, `buildApiMessages`/`compactionBoundary` speak in counts, and conflating
|
|
297
|
-
* them silently slices the wrong region. Clamped to `[0, len]` so a mark ahead
|
|
298
|
-
* of the in-memory transcript (e.g. a rolled-back turn) can never overrun.
|
|
299
|
-
*/
|
|
300
|
-
export function seqToCount(compactedSeq: number, messageCount: number): number {
|
|
301
|
-
if (!Number.isFinite(compactedSeq) || compactedSeq <= 0) return 0;
|
|
302
|
-
return Math.min(Math.floor(compactedSeq), messageCount);
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
export function buildApiMessages(
|
|
306
|
-
messages: readonly ConversationMessage[],
|
|
307
|
-
systemPrompt: string,
|
|
308
|
-
compactionNote = '',
|
|
309
|
-
compactedUpto = 0,
|
|
310
|
-
): Array<Record<string, unknown>> {
|
|
311
|
-
// The summarized prefix is represented by `compactionNote` in the system
|
|
312
|
-
// prompt; sending it again would waste context and could contradict the note.
|
|
313
|
-
const visible = compactedUpto > 0 ? messages.slice(Math.min(compactedUpto, messages.length)) : messages;
|
|
314
|
-
const wire: Array<Record<string, unknown>> = [
|
|
315
|
-
{
|
|
316
|
-
role: 'system',
|
|
317
|
-
content: systemPrompt + (compactionNote ? `\n\n${compactionNote}` : ''),
|
|
318
|
-
},
|
|
319
|
-
...visible.map((m) => {
|
|
320
|
-
if (m.role === 'assistant' && m.toolCalls?.length) {
|
|
321
|
-
return {
|
|
322
|
-
role: 'assistant',
|
|
323
|
-
content: m.content || null,
|
|
324
|
-
tool_calls: m.toolCalls.map((tc) => {
|
|
325
|
-
const func: Record<string, unknown> = {name: tc.name, arguments: tc.arguments};
|
|
326
|
-
// Gemini requires its thought_signature echoed back verbatim.
|
|
327
|
-
const ec = tc.extraContent as Record<string, any> | undefined;
|
|
328
|
-
const sig = ec?.google?.thought_signature;
|
|
329
|
-
if (sig) func.thought_signature = sig;
|
|
330
|
-
return {
|
|
331
|
-
id: tc.id,
|
|
332
|
-
type: 'function',
|
|
333
|
-
function: func,
|
|
334
|
-
...(tc.extraContent ? {extra_content: tc.extraContent} : {}),
|
|
335
|
-
};
|
|
336
|
-
}),
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
if (m.role === 'tool') {
|
|
340
|
-
return {role: 'tool', tool_call_id: m.tool_call_id, content: m.content};
|
|
341
|
-
}
|
|
342
|
-
return {role: m.role, content: m.content};
|
|
343
|
-
}),
|
|
344
|
-
];
|
|
345
|
-
|
|
346
|
-
return sanitizeWireMessages(wire);
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
/**
|
|
350
|
-
* Last line of defence: guarantee the wire history satisfies the provider's
|
|
351
|
-
* tool-call grouping rule, whatever produced it.
|
|
352
|
-
*
|
|
353
|
-
* OpenAI-compatible endpoints require each assistant message carrying
|
|
354
|
-
* `tool_calls` to be *immediately* followed by one `tool` message per call id —
|
|
355
|
-
* with nothing else in between. A violated history is rejected with a 400
|
|
356
|
-
* ("An assistant message with 'tool_calls' must be followed by tool messages
|
|
357
|
-
* responding to each 'tool_call_id'"), killing the turn even though the user's
|
|
358
|
-
* request was fine.
|
|
359
|
-
*
|
|
360
|
-
* The loop and the compaction step now maintain this invariant themselves; this
|
|
361
|
-
* exists so that a history rehydrated from an old session, or written by a
|
|
362
|
-
* future caller/extension, degrades into a *usable* request rather than a hard
|
|
363
|
-
* failure:
|
|
364
|
-
* - a `tool_calls` message whose results are missing/partial has the unanswered
|
|
365
|
-
* ids dropped (and the message is converted to plain text if none remain);
|
|
366
|
-
* - a `tool` message with no owning assistant call is dropped as an orphan.
|
|
367
|
-
*/
|
|
368
|
-
export function sanitizeWireMessages(
|
|
369
|
-
wire: Array<Record<string, unknown>>,
|
|
370
|
-
): Array<Record<string, unknown>> {
|
|
371
|
-
const out: Array<Record<string, unknown>> = [];
|
|
372
|
-
|
|
373
|
-
// The assistant call the tool branch is currently allowed to answer. It stays
|
|
374
|
-
// open while consecutive `tool` messages are emitted, and is cleared by any
|
|
375
|
-
// non-tool message (or a demotion to plain text).
|
|
376
|
-
let openCall: {id: string}[] | null = null;
|
|
377
|
-
|
|
378
|
-
for (let i = 0; i < wire.length; i++) {
|
|
379
|
-
const msg = wire[i];
|
|
380
|
-
|
|
381
|
-
if (msg.role === 'tool') {
|
|
382
|
-
if (!openCall?.some((c) => c.id === msg.tool_call_id)) continue; // orphan — drop
|
|
383
|
-
out.push(msg);
|
|
384
|
-
continue;
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
openCall = null;
|
|
388
|
-
|
|
389
|
-
if (msg.role === 'assistant' && Array.isArray(msg.tool_calls)) {
|
|
390
|
-
const calls = msg.tool_calls as Array<{id: string}>;
|
|
391
|
-
|
|
392
|
-
// Only a contiguous run of tool results immediately after the assistant
|
|
393
|
-
// message counts as answering it.
|
|
394
|
-
const answered = new Set<string>();
|
|
395
|
-
for (let j = i + 1; j < wire.length && wire[j].role === 'tool'; j++) {
|
|
396
|
-
answered.add(String(wire[j].tool_call_id));
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
const kept = calls.filter((c) => answered.has(c.id));
|
|
400
|
-
if (kept.length === 0) {
|
|
401
|
-
// No results for any call — demote to a plain assistant message so the
|
|
402
|
-
// request stays valid instead of 400ing.
|
|
403
|
-
out.push({role: 'assistant', content: msg.content ?? ''});
|
|
404
|
-
continue;
|
|
405
|
-
}
|
|
406
|
-
out.push({...msg, tool_calls: kept});
|
|
407
|
-
openCall = kept;
|
|
408
|
-
continue;
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
out.push(msg);
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
return out;
|
|
415
|
-
}
|
|
416
|
-
|
|
417
|
-
// ---------------------------------------------------------------------------
|
|
418
|
-
// The loop
|
|
419
|
-
// ---------------------------------------------------------------------------
|
|
420
|
-
|
|
421
|
-
/**
|
|
422
|
-
* Summarize a prompt with the session's provider.
|
|
423
|
-
*
|
|
424
|
-
* Uses `complete()` (a buffered stream) with no tools and no reasoning params —
|
|
425
|
-
* a summary needs neither, and forwarding effort knobs would waste tokens.
|
|
426
|
-
*/
|
|
427
|
-
async function summarizeViaProvider(
|
|
428
|
-
provider: Provider,
|
|
429
|
-
model: string,
|
|
430
|
-
prompt: string,
|
|
431
|
-
): Promise<string> {
|
|
432
|
-
const result = await complete(provider, {
|
|
433
|
-
model,
|
|
434
|
-
messages: [{role: 'user', content: prompt}],
|
|
435
|
-
});
|
|
436
|
-
return result.text;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
/**
|
|
440
|
-
* Run one agent turn to completion, yielding events as they happen.
|
|
441
|
-
*
|
|
442
|
-
* Terminates when the model stops requesting tools, when `maxRounds` is hit,
|
|
443
|
-
* or when the same tool call repeats `REPEAT_STOP` times.
|
|
444
|
-
*/
|
|
445
|
-
export async function* runAgent(opts: RunAgentOptions): AsyncGenerator<AgentRunEvent> {
|
|
446
|
-
const {
|
|
447
|
-
messages,
|
|
448
|
-
tools,
|
|
449
|
-
provider,
|
|
450
|
-
model,
|
|
451
|
-
systemPrompt,
|
|
452
|
-
maxRounds = DEFAULT_MAX_ROUNDS,
|
|
453
|
-
contextLimit = DEFAULT_CONTEXT_LIMIT,
|
|
454
|
-
reasoningEffort = 'medium',
|
|
455
|
-
providerConfig,
|
|
456
|
-
executeTool,
|
|
457
|
-
signal,
|
|
458
|
-
compactedSeq = 0,
|
|
459
|
-
compactionNote: initialCompactionNote = '',
|
|
460
|
-
} = opts;
|
|
461
|
-
|
|
462
|
-
let totalInput = 0;
|
|
463
|
-
let totalOutput = 0;
|
|
464
|
-
let totalCached = 0;
|
|
465
|
-
let compactionNote = initialCompactionNote;
|
|
466
|
-
// Leading-message *count* already folded into a checkpoint. Seeded from the
|
|
467
|
-
// persisted high-water mark (a seq) via the conversion below, so a turn that
|
|
468
|
-
// follows an earlier compaction neither re-summarizes nor re-sends that prefix.
|
|
469
|
-
let compactedUpto = seqToCount(compactedSeq, messages.length);
|
|
470
|
-
let roundsRun = 0;
|
|
471
|
-
let stoppedEarly = false;
|
|
472
|
-
|
|
473
|
-
// Per-call (NOT module-level) so unrelated turns can't trip the detector.
|
|
474
|
-
const callCounts = new Map<string, number>();
|
|
475
|
-
|
|
476
|
-
// ── Compact if we're approaching the context limit ──
|
|
477
|
-
//
|
|
478
|
-
// Non-destructive: we summarize the oldest messages into a checkpoint and tell
|
|
479
|
-
// the caller (which persists it), but we NEVER delete them from `messages`.
|
|
480
|
-
// The model view below is what omits the summarized prefix, so the on-disk
|
|
481
|
-
// transcript stays complete for repaint.
|
|
482
|
-
//
|
|
483
|
-
// Only the *un-compacted tail* is considered: measuring the full array would
|
|
484
|
-
// re-trigger compaction on history that was already summarized (and whose
|
|
485
|
-
// summary is already in `compactionNote`), looping forever on a long session.
|
|
486
|
-
const uncompactedTail = messages.slice(compactedUpto);
|
|
487
|
-
if (
|
|
488
|
-
uncompactedTail.length > 0 &&
|
|
489
|
-
shouldCompact(uncompactedTail, {maxTokens: contextLimit, reservedTokens: RESERVED_TOKENS})
|
|
490
|
-
) {
|
|
491
|
-
const boundary = compactionBoundary(uncompactedTail, KEEP_RECENT);
|
|
492
|
-
if (boundary > 0) {
|
|
493
|
-
const toSummarize = uncompactedTail.slice(0, boundary);
|
|
494
|
-
const summary = await summarizeRange(toSummarize, (prompt) =>
|
|
495
|
-
summarizeViaProvider(provider, model, prompt),
|
|
496
|
-
);
|
|
497
|
-
// Accumulate: a second compaction summarizes a *later* slice, so replacing
|
|
498
|
-
// the note would silently drop the earlier checkpoint from the system
|
|
499
|
-
// prompt. Each entry is tagged with the message range it covers.
|
|
500
|
-
const noteEntry = `[messages ${compactedUpto + 1}-${compactedUpto + boundary}]\n${summary}`;
|
|
501
|
-
compactionNote = compactionNote ? `${compactionNote}\n\n${noteEntry}` : noteEntry;
|
|
502
|
-
// Boundary is relative to the tail — offset it back into whole-history
|
|
503
|
-
// count space so the caller's seq and the model view stay consistent.
|
|
504
|
-
compactedUpto += boundary;
|
|
505
|
-
yield {type: 'compacted', boundary: compactedUpto, summarized: boundary, summary};
|
|
506
|
-
yield {type: 'notice', text: `Context compacted (${boundary} messages summarized).`};
|
|
507
|
-
}
|
|
508
|
-
}
|
|
509
|
-
|
|
510
|
-
const usage = (): RunAgentUsage => ({
|
|
511
|
-
inputTokens: totalInput,
|
|
512
|
-
outputTokens: totalOutput,
|
|
513
|
-
cachedTokens: totalCached,
|
|
514
|
-
});
|
|
515
|
-
|
|
516
|
-
for (let round = 0; round < maxRounds; round++) {
|
|
517
|
-
if (signal?.aborted) {
|
|
518
|
-
yield {type: 'aborted'};
|
|
519
|
-
return;
|
|
520
|
-
}
|
|
521
|
-
roundsRun = round + 1;
|
|
522
|
-
yield {type: 'round-start', round: roundsRun, max: maxRounds};
|
|
523
|
-
|
|
524
|
-
// ── Re-check compaction mid-turn ──
|
|
525
|
-
// The pre-loop check only fires once; a long turn with many tool results
|
|
526
|
-
// can grow the context past the window, causing a hard 400 from the
|
|
527
|
-
// provider — the exact failure compaction exists to prevent.
|
|
528
|
-
const midTail = messages.slice(compactedUpto);
|
|
529
|
-
if (
|
|
530
|
-
midTail.length > 0 &&
|
|
531
|
-
shouldCompact(midTail, {maxTokens: contextLimit, reservedTokens: RESERVED_TOKENS})
|
|
532
|
-
) {
|
|
533
|
-
const midBoundary = compactionBoundary(midTail, KEEP_RECENT);
|
|
534
|
-
if (midBoundary > 0) {
|
|
535
|
-
const midToSummarize = midTail.slice(0, midBoundary);
|
|
536
|
-
const midSummary = await summarizeRange(midToSummarize, (prompt) =>
|
|
537
|
-
summarizeViaProvider(provider, model, prompt),
|
|
538
|
-
);
|
|
539
|
-
const noteEntry = `[messages ${compactedUpto + 1}-${compactedUpto + midBoundary}]\n${midSummary}`;
|
|
540
|
-
compactionNote = compactionNote ? `${compactionNote}\n\n${noteEntry}` : noteEntry;
|
|
541
|
-
compactedUpto += midBoundary;
|
|
542
|
-
yield {type: 'compacted', boundary: compactedUpto, summarized: midBoundary, summary: midSummary};
|
|
543
|
-
yield {type: 'notice', text: `Context compacted mid-turn (${midBoundary} messages summarized).`};
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
const apiMessages = buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto);
|
|
548
|
-
let textContent = '';
|
|
549
|
-
const toolCalls: NonNullable<AssistantMsg['toolCalls']> = [];
|
|
550
|
-
|
|
551
|
-
try {
|
|
552
|
-
for await (const event of provider.stream({
|
|
553
|
-
model,
|
|
554
|
-
messages: apiMessages,
|
|
555
|
-
tools: tools as never,
|
|
556
|
-
signal,
|
|
557
|
-
...getEffortParams(model, reasoningEffort),
|
|
558
|
-
} as never) as AsyncGenerator<StreamEvent>) {
|
|
559
|
-
if (event.type === 'text' && event.content) {
|
|
560
|
-
textContent += event.content;
|
|
561
|
-
yield {type: 'text-delta', content: event.content};
|
|
562
|
-
} else if (event.type === 'tool_use' && event.toolCall) {
|
|
563
|
-
toolCalls.push(event.toolCall);
|
|
564
|
-
} else if (event.type === 'error') {
|
|
565
|
-
throw new Error(event.content);
|
|
566
|
-
} else if (event.type === 'done' && event.usage) {
|
|
567
|
-
totalInput += event.usage.promptTokens ?? 0;
|
|
568
|
-
totalOutput += event.usage.completionTokens ?? 0;
|
|
569
|
-
totalCached += event.usage.cachedTokens ?? 0;
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
} catch (err) {
|
|
573
|
-
// A user interrupt surfaces here as an AbortError from the provider.
|
|
574
|
-
if (signal?.aborted) {
|
|
575
|
-
yield {type: 'aborted'};
|
|
576
|
-
return;
|
|
577
|
-
}
|
|
578
|
-
throw err;
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
// ── No tool calls → turn complete ──
|
|
582
|
-
if (toolCalls.length === 0) {
|
|
583
|
-
messages.push({role: 'assistant', content: textContent});
|
|
584
|
-
yield {type: 'done', model, rounds: roundsRun, usage: usage()};
|
|
585
|
-
return;
|
|
586
|
-
}
|
|
587
|
-
|
|
588
|
-
messages.push({role: 'assistant', content: textContent, toolCalls});
|
|
589
|
-
|
|
590
|
-
const displays = toolCalls.map((tc) => {
|
|
591
|
-
let argsSummary = '';
|
|
592
|
-
try {
|
|
593
|
-
argsSummary = summarizeArgs(tc.name, JSON.parse(tc.arguments));
|
|
594
|
-
} catch {
|
|
595
|
-
argsSummary = truncate(tc.arguments, 40);
|
|
596
|
-
}
|
|
597
|
-
return {tc, argsSummary};
|
|
598
|
-
});
|
|
599
|
-
|
|
600
|
-
for (const d of displays) {
|
|
601
|
-
yield {type: 'tool-start', id: d.tc.id, name: d.tc.name, argsSummary: d.argsSummary};
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
type Display = (typeof displays)[number];
|
|
605
|
-
const runOne = async (d: Display) => {
|
|
606
|
-
const started = Date.now();
|
|
607
|
-
const result = await executeTool(d.tc.name, d.tc.arguments, d.tc.id, providerConfig);
|
|
608
|
-
return {tc: d.tc, result, ms: Date.now() - started};
|
|
609
|
-
};
|
|
610
|
-
|
|
611
|
-
const byId = new Map<string, Awaited<ReturnType<typeof runOne>>>();
|
|
612
|
-
const parallel = displays.filter((d) => PARALLEL_SAFE.has(d.tc.name));
|
|
613
|
-
const sequential = displays.filter((d) => !PARALLEL_SAFE.has(d.tc.name));
|
|
614
|
-
|
|
615
|
-
for (const r of await Promise.all(parallel.map(runOne))) byId.set(r.tc.id, r);
|
|
616
|
-
for (const d of sequential) {
|
|
617
|
-
const r = await runOne(d);
|
|
618
|
-
byId.set(r.tc.id, r);
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
// ── Report results + detect loops, in the original call order ──
|
|
622
|
-
//
|
|
623
|
-
// Every `tool` message for this round MUST be appended before anything else:
|
|
624
|
-
// the provider requires the tool results to immediately follow the assistant
|
|
625
|
-
// message that requested them. Injecting the repeat-nudge mid-loop pushed a
|
|
626
|
-
// `user` message between the results, orphaning the remaining `tool` messages
|
|
627
|
-
// and producing a 400 ("assistant message with 'tool_calls' must be followed
|
|
628
|
-
// by tool messages"). So nudges are buffered and flushed after the group.
|
|
629
|
-
let hardStop = false;
|
|
630
|
-
const nudges: string[] = [];
|
|
631
|
-
for (const d of displays) {
|
|
632
|
-
const {tc, result, ms} = byId.get(d.tc.id)!;
|
|
633
|
-
yield {
|
|
634
|
-
type: 'tool-end',
|
|
635
|
-
id: tc.id,
|
|
636
|
-
name: tc.name,
|
|
637
|
-
ok: !result.error,
|
|
638
|
-
content: result.content,
|
|
639
|
-
ms,
|
|
640
|
-
};
|
|
641
|
-
messages.push({role: 'tool', tool_call_id: tc.id, content: result.content});
|
|
642
|
-
|
|
643
|
-
const key = `${tc.name}|${tc.arguments}`;
|
|
644
|
-
const n = (callCounts.get(key) ?? 0) + 1;
|
|
645
|
-
callCounts.set(key, n);
|
|
646
|
-
|
|
647
|
-
if (n === REPEAT_WARN) {
|
|
648
|
-
nudges.push(
|
|
649
|
-
`[pal] "${tc.name}" has now been called with identical arguments ${n} times — it cannot return anything new. Change your approach, or stop and summarise what you have.`,
|
|
650
|
-
);
|
|
651
|
-
yield {type: 'notice', text: `! repeated call: ${tc.name} ×${n} — nudging model`};
|
|
652
|
-
}
|
|
653
|
-
if (n >= REPEAT_STOP) hardStop = true;
|
|
654
|
-
}
|
|
655
|
-
|
|
656
|
-
// Safe now the tool group is complete.
|
|
657
|
-
for (const content of nudges) messages.push({role: 'user', content});
|
|
658
|
-
|
|
659
|
-
if (hardStop) {
|
|
660
|
-
yield {type: 'notice', text: `! loop detected (same call ${REPEAT_STOP}×) — stopping early`};
|
|
661
|
-
stoppedEarly = true;
|
|
662
|
-
break;
|
|
663
|
-
}
|
|
664
|
-
}
|
|
665
|
-
|
|
666
|
-
// ── Round cap reached → degrade gracefully ──
|
|
667
|
-
// Rather than stopping mid-task with a wall of tool calls, inject a wrap-up
|
|
668
|
-
// instruction and make ONE final call with tools withheld, so the user always
|
|
669
|
-
// gets a summary (opencode's `MAX_STEPS_PROMPT` behaviour).
|
|
670
|
-
if (!stoppedEarly) {
|
|
671
|
-
if (signal?.aborted) {
|
|
672
|
-
yield {type: 'aborted'};
|
|
673
|
-
return;
|
|
674
|
-
}
|
|
675
|
-
|
|
676
|
-
yield {type: 'notice', text: `! Max tool rounds (${maxRounds}) reached — wrapping up`};
|
|
677
|
-
messages.push({role: 'user', content: WRAP_UP_PROMPT});
|
|
678
|
-
yield {type: 'round-start', round: roundsRun + 1, max: roundsRun + 1};
|
|
679
|
-
|
|
680
|
-
let wrapText = '';
|
|
681
|
-
try {
|
|
682
|
-
for await (const event of provider.stream({
|
|
683
|
-
model,
|
|
684
|
-
messages: buildApiMessages(messages, systemPrompt, compactionNote, compactedUpto),
|
|
685
|
-
tools: [] as never,
|
|
686
|
-
signal,
|
|
687
|
-
...getEffortParams(model, reasoningEffort),
|
|
688
|
-
} as never) as AsyncGenerator<StreamEvent>) {
|
|
689
|
-
if (event.type === 'text' && event.content) {
|
|
690
|
-
wrapText += event.content;
|
|
691
|
-
yield {type: 'text-delta', content: event.content};
|
|
692
|
-
} else if (event.type === 'done' && event.usage) {
|
|
693
|
-
totalInput += event.usage.promptTokens ?? 0;
|
|
694
|
-
totalOutput += event.usage.completionTokens ?? 0;
|
|
695
|
-
totalCached += event.usage.cachedTokens ?? 0;
|
|
696
|
-
}
|
|
697
|
-
}
|
|
698
|
-
} catch (err) {
|
|
699
|
-
if (signal?.aborted) {
|
|
700
|
-
yield {type: 'aborted'};
|
|
701
|
-
return;
|
|
702
|
-
}
|
|
703
|
-
// A failed wrap-up must not discard the work already done.
|
|
704
|
-
yield {
|
|
705
|
-
type: 'notice',
|
|
706
|
-
text: `! wrap-up failed: ${err instanceof Error ? err.message : String(err)}`,
|
|
707
|
-
};
|
|
708
|
-
}
|
|
709
|
-
if (wrapText) messages.push({role: 'assistant', content: wrapText});
|
|
710
|
-
}
|
|
711
|
-
|
|
712
|
-
yield {type: 'done', model, rounds: roundsRun, usage: usage()};
|
|
713
|
-
}
|