pal-code 0.0.5
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/LICENSE +21 -0
- package/README.md +169 -0
- package/SYSTEM.md +146 -0
- package/bin/pal-code.js +131 -0
- package/package.json +68 -0
- package/packages/cli/README.md +77 -0
- package/packages/cli/src/agent-panel.ts +94 -0
- package/packages/cli/src/commands/ext.ts +79 -0
- package/packages/cli/src/commands/mcp-registry.ts +136 -0
- package/packages/cli/src/commands/mcp.ts +186 -0
- package/packages/cli/src/commands.ts +153 -0
- package/packages/cli/src/components/message-box.ts +35 -0
- package/packages/cli/src/components/permission-prompt.ts +185 -0
- package/packages/cli/src/components/render-history.ts +143 -0
- package/packages/cli/src/components/run-view.ts +256 -0
- package/packages/cli/src/components/sidebar.ts +120 -0
- package/packages/cli/src/components/status-line.ts +26 -0
- package/packages/cli/src/config.ts +107 -0
- package/packages/cli/src/index.ts +1606 -0
- package/packages/cli/src/overlays/key-input.ts +167 -0
- package/packages/cli/src/overlays/model-picker.ts +106 -0
- package/packages/cli/src/overlays/session-picker.ts +168 -0
- package/packages/cli/src/overlays/wizard.ts +145 -0
- package/packages/cli/src/state.ts +133 -0
- package/packages/cli/src/theme.ts +88 -0
- package/packages/cli/src/turn.ts +266 -0
- package/packages/cli/src/utils/cost.ts +111 -0
- package/packages/cli/src/utils/format.test.ts +167 -0
- package/packages/cli/src/utils/format.ts +248 -0
- package/packages/cli/src/utils/highlight.ts +358 -0
- package/packages/cli/src/utils/permissions.ts +196 -0
- package/packages/core/src/agent/events.ts +36 -0
- package/packages/core/src/agent/fallback.test.ts +99 -0
- package/packages/core/src/agent/fallback.ts +344 -0
- package/packages/core/src/agent/index.ts +35 -0
- package/packages/core/src/agent/protocol.test.ts +136 -0
- package/packages/core/src/agent/resume-compaction.test.ts +116 -0
- package/packages/core/src/agent/roles.ts +188 -0
- package/packages/core/src/agent/run.test.ts +207 -0
- package/packages/core/src/agent/run.ts +713 -0
- package/packages/core/src/agent/scope.ts +34 -0
- package/packages/core/src/agent/todos.ts +66 -0
- package/packages/core/src/compaction.protocol.test.ts +90 -0
- package/packages/core/src/compaction.test.ts +101 -0
- package/packages/core/src/compaction.ts +243 -0
- package/packages/core/src/config.test.ts +40 -0
- package/packages/core/src/config.ts +387 -0
- package/packages/core/src/extensions.ts +178 -0
- package/packages/core/src/index.ts +157 -0
- package/packages/core/src/logger.ts +54 -0
- package/packages/core/src/provider/auth.ts +153 -0
- package/packages/core/src/provider/complete.ts +63 -0
- package/packages/core/src/provider/index.ts +6 -0
- package/packages/core/src/provider/openrouter.test.ts +59 -0
- package/packages/core/src/provider/openrouter.ts +304 -0
- package/packages/core/src/provider/pick-model.ts +43 -0
- package/packages/core/src/provider/registry.ts +222 -0
- package/packages/core/src/provider/types.ts +61 -0
- package/packages/core/src/repo-map.ts +177 -0
- package/packages/core/src/session/index.ts +2 -0
- package/packages/core/src/session/migration.test.ts +104 -0
- package/packages/core/src/session/store-v2-repair.test.ts +209 -0
- package/packages/core/src/session/store.test.ts +235 -0
- package/packages/core/src/session/store.ts +677 -0
- package/packages/core/src/session/types.ts +72 -0
- package/packages/core/src/snapshots.ts +107 -0
- package/packages/core/src/tools/definitions.ts +365 -0
- package/packages/core/src/tools/executor.test.ts +122 -0
- package/packages/core/src/tools/executor.ts +1363 -0
- package/packages/core/src/tools/index.ts +5 -0
- package/packages/core/src/tools/search.ts +201 -0
- package/scripts/postinstall.js +121 -0
- package/scripts/preinstall.js +51 -0
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fallback / retry policy — the "keep the turn alive" wrapper around runAgent.
|
|
3
|
+
*
|
|
4
|
+
* This lives in core, not the CLI, because it *decides* what the agent does
|
|
5
|
+
* (which model to try next, whether to back off, whether to give up). The CLI
|
|
6
|
+
* only renders the events this yields.
|
|
7
|
+
*
|
|
8
|
+
* Strategy: same provider first (same rate-limit pool), then cross-provider.
|
|
9
|
+
* - quota exhausted → switch immediately (retrying burns RPM for nothing)
|
|
10
|
+
* - rate limited → exponential backoff, `maxRetries` attempts, then switch
|
|
11
|
+
* - other retryable → backoff, `maxRetries` attempts, then switch
|
|
12
|
+
* - anything else → rethrow
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {createOpenRouterProvider} from '../provider/openrouter.js';
|
|
16
|
+
import {PROVIDERS, providerForModel} from '../provider/registry.js';
|
|
17
|
+
import type {ProviderDef} from '../provider/registry.js';
|
|
18
|
+
import type {ProviderKeys} from '../provider/auth.js';
|
|
19
|
+
import type {Provider} from '../provider/types.js';
|
|
20
|
+
import {
|
|
21
|
+
runAgent,
|
|
22
|
+
type AgentRunEvent,
|
|
23
|
+
type ConversationMessage,
|
|
24
|
+
type RunAgentOptions,
|
|
25
|
+
} from './run.js';
|
|
26
|
+
|
|
27
|
+
export function sleep(ms: number): Promise<void> {
|
|
28
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function isRetryableError(msg: string): boolean {
|
|
32
|
+
// Transient transport failures. Bun says "Was there a typo in the url or
|
|
33
|
+
// port?"; Node says "fetch failed". Neither is the model's fault and both
|
|
34
|
+
// usually succeed on a retry — without this they killed the whole turn.
|
|
35
|
+
if (
|
|
36
|
+
/typo in the url|fetch failed|socket|network|ECONNRESET|ECONNREFUSED|ENOTFOUND|ETIMEDOUT|EAI_AGAIN|EPIPE|terminated/i.test(
|
|
37
|
+
msg,
|
|
38
|
+
)
|
|
39
|
+
) {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
return (
|
|
43
|
+
msg.includes('429') ||
|
|
44
|
+
msg.includes('Rate') ||
|
|
45
|
+
msg.includes('FreeUsage') ||
|
|
46
|
+
msg.includes('403') ||
|
|
47
|
+
msg.includes('unavailable') ||
|
|
48
|
+
msg.includes('UNAVAILABLE') ||
|
|
49
|
+
msg.includes('503') ||
|
|
50
|
+
msg.includes('timed out')
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Quota exhaustion = do NOT retry (burns RPM for nothing). Switch provider. */
|
|
55
|
+
export function isQuotaExhausted(msg: string): boolean {
|
|
56
|
+
return (
|
|
57
|
+
msg.includes('FreeUsage') ||
|
|
58
|
+
msg.includes('quota') ||
|
|
59
|
+
msg.includes('Quota') ||
|
|
60
|
+
msg.includes('insufficient_quota') ||
|
|
61
|
+
msg.includes('billing')
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** RPM rate limit = brief backoff + limited retries, then switch. */
|
|
66
|
+
export function isRateLimited(msg: string): boolean {
|
|
67
|
+
return msg.includes('429') || msg.includes('Rate limit') || msg.includes('rate-limit');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** True when a provider is usable: it has a key, or is explicitly keyless. */
|
|
71
|
+
export function providerAccessible(
|
|
72
|
+
def: {id: string; keyOptional?: boolean},
|
|
73
|
+
keys: ProviderKeys,
|
|
74
|
+
): boolean {
|
|
75
|
+
return Boolean(keys[def.id]) || def.keyOptional === true;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Short display name for a `provider/model` spec. */
|
|
79
|
+
export function shortModel(model: string): string {
|
|
80
|
+
return model.split('/').pop()?.split(':')[0] ?? model;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Per-provider `/models` cache. `null` = the fetch failed. */
|
|
84
|
+
const liveModels = new Map<string, string[] | null>();
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Live model ids for a provider, cached. Returns `null` when the fetch fails so
|
|
88
|
+
* callers can distinguish "unknown" from "empty".
|
|
89
|
+
*/
|
|
90
|
+
export async function fetchProviderModels(
|
|
91
|
+
def: ProviderDef,
|
|
92
|
+
apiKey: string,
|
|
93
|
+
): Promise<string[] | null> {
|
|
94
|
+
if (liveModels.has(def.id)) return liveModels.get(def.id) ?? null;
|
|
95
|
+
try {
|
|
96
|
+
const p = createOpenRouterProvider({
|
|
97
|
+
id: def.id,
|
|
98
|
+
baseUrl: def.baseUrl,
|
|
99
|
+
apiKey: apiKey || (def.keyOptional ? 'public' : ''),
|
|
100
|
+
headers: def.headers,
|
|
101
|
+
modelPrefix: def.modelPrefix,
|
|
102
|
+
});
|
|
103
|
+
await p.init();
|
|
104
|
+
const ids = (await p.models()).map((m) => m.id);
|
|
105
|
+
liveModels.set(def.id, ids.length > 0 ? ids : null);
|
|
106
|
+
return ids.length > 0 ? ids : null;
|
|
107
|
+
} catch {
|
|
108
|
+
liveModels.set(def.id, null);
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Clear the `/models` cache (used after a key change). */
|
|
114
|
+
export function clearModelCache(): void {
|
|
115
|
+
liveModels.clear();
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Live ids, falling back to the provider's curated list. */
|
|
119
|
+
export async function resolveModelIds(def: ProviderDef, apiKey: string): Promise<string[]> {
|
|
120
|
+
const ids = await fetchProviderModels(def, apiKey);
|
|
121
|
+
// When keyOptional with no real key, filter to only free models to avoid
|
|
122
|
+
// wasting fallback attempts on paid models that require billing.
|
|
123
|
+
const isKeyless = def.keyOptional === true && !apiKey;
|
|
124
|
+
if (ids && ids.length > 0) {
|
|
125
|
+
if (isKeyless && def.freeModelPattern) {
|
|
126
|
+
const re = new RegExp(def.freeModelPattern);
|
|
127
|
+
const free = ids.filter((id) => re.test(id));
|
|
128
|
+
return free.length > 0 ? free : def.fallbackModels;
|
|
129
|
+
}
|
|
130
|
+
return ids;
|
|
131
|
+
}
|
|
132
|
+
return def.fallbackModels;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Default provider factory: registry base URL + `PAL`-agnostic env override. */
|
|
136
|
+
export function createProviderFor(modelSpec: string, keys: ProviderKeys): Provider {
|
|
137
|
+
const {provider: def} = providerForModel(modelSpec, Object.keys(keys));
|
|
138
|
+
const envOverride = process.env[`${def.id.toUpperCase()}_BASE_URL`];
|
|
139
|
+
return createOpenRouterProvider({
|
|
140
|
+
id: def.id,
|
|
141
|
+
baseUrl: envOverride ?? def.baseUrl,
|
|
142
|
+
apiKey: keys[def.id] ?? (def.keyOptional ? 'public' : ''),
|
|
143
|
+
headers: def.headers,
|
|
144
|
+
modelPrefix: def.modelPrefix,
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export interface RunWithFallbackOptions {
|
|
149
|
+
/** Conversation history — MUTATED IN PLACE. */
|
|
150
|
+
messages: ConversationMessage[];
|
|
151
|
+
/** Tool definitions exposed to the model. */
|
|
152
|
+
tools: RunAgentOptions['tools'];
|
|
153
|
+
/** Requested `provider/model` spec. */
|
|
154
|
+
model: string;
|
|
155
|
+
systemPrompt: string;
|
|
156
|
+
maxToolRounds?: number;
|
|
157
|
+
contextLimit?: number;
|
|
158
|
+
reasoningEffort?: 'low' | 'medium' | 'high';
|
|
159
|
+
/**
|
|
160
|
+
* 1-based store seq of genuinely-uncompacted history. Passed straight through
|
|
161
|
+
* to `runAgent`, which seeded its own count-space mark from it.
|
|
162
|
+
*/
|
|
163
|
+
compactedSeq?: number;
|
|
164
|
+
/**
|
|
165
|
+
* Pre-existing compaction summary from a resumed session. Threaded through
|
|
166
|
+
* to `runAgent` so resumed sessions don't lose their compacted context.
|
|
167
|
+
*/
|
|
168
|
+
compactionNote?: string;
|
|
169
|
+
/** Retries per model before switching (default 1). */
|
|
170
|
+
maxRetries?: number;
|
|
171
|
+
/** Base backoff in ms; doubles each attempt (default 2000). */
|
|
172
|
+
retryBaseMs?: number;
|
|
173
|
+
keys: ProviderKeys;
|
|
174
|
+
executeTool: RunAgentOptions['executeTool'];
|
|
175
|
+
/**
|
|
176
|
+
* Optional override for the tool executor in child agents. When provided,
|
|
177
|
+
* delegated agents use this instead of the module-level `executeTool`.
|
|
178
|
+
* Used by the CLI to inject permission gating into child agents.
|
|
179
|
+
*/
|
|
180
|
+
childExecuteTool?: RunAgentOptions['executeTool'];
|
|
181
|
+
signal?: AbortSignal;
|
|
182
|
+
/** Read-only turn — `delegate` may not spawn anything that mutates state. */
|
|
183
|
+
readOnly?: boolean;
|
|
184
|
+
/**
|
|
185
|
+
* Tool names this turn may dispatch. Enforced in `executeTool`, so a
|
|
186
|
+
* hallucinated call for an unoffered tool is refused rather than run.
|
|
187
|
+
*/
|
|
188
|
+
allowedTools?: string[];
|
|
189
|
+
/** Injectable for tests. */
|
|
190
|
+
createProvider?: (modelSpec: string, keys: ProviderKeys) => Provider;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Drive `runAgent` with provider/model fallback.
|
|
195
|
+
*
|
|
196
|
+
* Yields the inner `AgentRunEvent`s, plus:
|
|
197
|
+
* - `{type:'model-start'}` when it commits to a model (so the UI can relabel)
|
|
198
|
+
* - `{type:'notice'}` for each fallback/backoff decision
|
|
199
|
+
*
|
|
200
|
+
* Returns normally when a model completes the turn (including a user abort).
|
|
201
|
+
* Throws only when every candidate model failed.
|
|
202
|
+
*/
|
|
203
|
+
export async function* runWithFallback(
|
|
204
|
+
opts: RunWithFallbackOptions,
|
|
205
|
+
): AsyncGenerator<AgentRunEvent> {
|
|
206
|
+
const {
|
|
207
|
+
messages,
|
|
208
|
+
tools,
|
|
209
|
+
model,
|
|
210
|
+
systemPrompt,
|
|
211
|
+
maxToolRounds,
|
|
212
|
+
contextLimit,
|
|
213
|
+
reasoningEffort,
|
|
214
|
+
compactedSeq,
|
|
215
|
+
compactionNote,
|
|
216
|
+
maxRetries = 1,
|
|
217
|
+
retryBaseMs = 2000,
|
|
218
|
+
keys,
|
|
219
|
+
executeTool,
|
|
220
|
+
childExecuteTool,
|
|
221
|
+
signal,
|
|
222
|
+
readOnly,
|
|
223
|
+
allowedTools,
|
|
224
|
+
createProvider = createProviderFor,
|
|
225
|
+
} = opts;
|
|
226
|
+
|
|
227
|
+
const {provider: baseDef, model: baseModel} = providerForModel(model, Object.keys(keys));
|
|
228
|
+
|
|
229
|
+
// Same provider: other models from its live list. Never invented — if the
|
|
230
|
+
// fetch failed there are simply no same-provider fallbacks.
|
|
231
|
+
const sameProviderModels: string[] = [];
|
|
232
|
+
if (providerAccessible(baseDef, keys)) {
|
|
233
|
+
const ids = await resolveModelIds(baseDef, keys[baseDef.id] ?? '');
|
|
234
|
+
for (const id of ids) {
|
|
235
|
+
if (id !== baseModel) sameProviderModels.push(`${baseDef.id}/${id}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Cross provider: only accessible providers, at their default model.
|
|
240
|
+
const crossProviderModels = PROVIDERS.filter(
|
|
241
|
+
(p) => p.id !== baseDef.id && providerAccessible(p, keys),
|
|
242
|
+
).map((p) => `${p.id}/${p.defaultModel}`);
|
|
243
|
+
|
|
244
|
+
const modelsToTry = [model, ...sameProviderModels, ...crossProviderModels];
|
|
245
|
+
|
|
246
|
+
// Track consecutive quota exhaustion per provider. If ALL models from a
|
|
247
|
+
// provider share the same quota pool (e.g. Zen free tier), short-circuit
|
|
248
|
+
// after the first quota failure — retrying the remaining models wastes time.
|
|
249
|
+
const quotaExhaustedProviders = new Set<string>();
|
|
250
|
+
|
|
251
|
+
for (const modelSpec of modelsToTry) {
|
|
252
|
+
const {provider: modelDef, model: bareModel} = providerForModel(modelSpec, Object.keys(keys));
|
|
253
|
+
if (!providerAccessible(modelDef, keys)) continue;
|
|
254
|
+
|
|
255
|
+
// Skip remaining models from a provider whose entire quota is exhausted.
|
|
256
|
+
if (quotaExhaustedProviders.has(modelDef.id)) continue;
|
|
257
|
+
|
|
258
|
+
// Handed to tools so `delegate` can spawn a working child agent.
|
|
259
|
+
const providerConfig = {
|
|
260
|
+
model: bareModel,
|
|
261
|
+
apiKey: keys[modelDef.id] ?? (modelDef.keyOptional ? 'public' : ''),
|
|
262
|
+
baseUrl: modelDef.baseUrl,
|
|
263
|
+
keys: keys as Record<string, string>,
|
|
264
|
+
// Carried through to `executeTool` so a read-only turn's `delegate` can
|
|
265
|
+
// refuse to spawn anything that would mutate files.
|
|
266
|
+
readOnly: readOnly ?? false,
|
|
267
|
+
// Carried through so `executeTool` can refuse a tool the turn may not use.
|
|
268
|
+
allowedTools,
|
|
269
|
+
// CLI-injected permission-gated executor for child agents.
|
|
270
|
+
childExecuteTool,
|
|
271
|
+
};
|
|
272
|
+
|
|
273
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
274
|
+
// Snapshot the message count so a mid-turn failure can be rolled back.
|
|
275
|
+
// runAgent mutates `messages` in place; without rollback a retryable
|
|
276
|
+
// transport error on round 3 leaves rounds 1–2's assistant + tool
|
|
277
|
+
// messages in history, causing duplicate tool execution on retry.
|
|
278
|
+
const snapshotLen = messages.length;
|
|
279
|
+
try {
|
|
280
|
+
const provider = createProvider(modelSpec, keys);
|
|
281
|
+
await provider.init();
|
|
282
|
+
yield {type: 'model-start', model: modelSpec};
|
|
283
|
+
|
|
284
|
+
yield* runAgent({
|
|
285
|
+
messages,
|
|
286
|
+
tools,
|
|
287
|
+
provider,
|
|
288
|
+
model: bareModel,
|
|
289
|
+
systemPrompt,
|
|
290
|
+
maxRounds: maxToolRounds,
|
|
291
|
+
contextLimit,
|
|
292
|
+
reasoningEffort,
|
|
293
|
+
compactedSeq,
|
|
294
|
+
compactionNote,
|
|
295
|
+
providerConfig,
|
|
296
|
+
executeTool,
|
|
297
|
+
signal,
|
|
298
|
+
});
|
|
299
|
+
return;
|
|
300
|
+
} catch (err) {
|
|
301
|
+
// Roll back any messages appended during the failed attempt so the
|
|
302
|
+
// retry starts from a clean state — no orphaned assistant or tool rows.
|
|
303
|
+
messages.length = snapshotLen;
|
|
304
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
305
|
+
|
|
306
|
+
if (isQuotaExhausted(msg)) {
|
|
307
|
+
yield {
|
|
308
|
+
type: 'notice',
|
|
309
|
+
text: `${modelSpec} quota exhausted — skipping remaining ${modelDef.id} models`,
|
|
310
|
+
};
|
|
311
|
+
quotaExhaustedProviders.add(modelDef.id);
|
|
312
|
+
break; // next model (from a different provider)
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (isRateLimited(msg)) {
|
|
316
|
+
if (attempt < maxRetries) {
|
|
317
|
+
const delay = retryBaseMs * 2 ** attempt;
|
|
318
|
+
yield {
|
|
319
|
+
type: 'notice',
|
|
320
|
+
text: `${modelSpec} rate-limited, retry in ${delay / 1000}s…`,
|
|
321
|
+
};
|
|
322
|
+
await sleep(delay);
|
|
323
|
+
continue;
|
|
324
|
+
}
|
|
325
|
+
yield {type: 'notice', text: `${modelSpec} exhausted, trying next…`};
|
|
326
|
+
break;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (isRetryableError(msg)) {
|
|
330
|
+
if (attempt < maxRetries) {
|
|
331
|
+
await sleep(retryBaseMs * 2 ** attempt);
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
throw err;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
yield {type: 'notice', text: 'All models failed (rate limits). Try again in a few minutes.'};
|
|
343
|
+
throw new Error('All models failed');
|
|
344
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export {runAgent, summarizeArgs, getEffortParams, buildApiMessages, seqToCount} from './run.js';
|
|
2
|
+
export {
|
|
3
|
+
runWithFallback,
|
|
4
|
+
resolveModelIds,
|
|
5
|
+
fetchProviderModels,
|
|
6
|
+
clearModelCache,
|
|
7
|
+
createProviderFor,
|
|
8
|
+
providerAccessible,
|
|
9
|
+
shortModel,
|
|
10
|
+
isRetryableError,
|
|
11
|
+
isQuotaExhausted,
|
|
12
|
+
isRateLimited,
|
|
13
|
+
sleep,
|
|
14
|
+
} from './fallback.js';
|
|
15
|
+
export type {RunWithFallbackOptions} from './fallback.js';
|
|
16
|
+
export type {
|
|
17
|
+
AgentRunEvent,
|
|
18
|
+
RunAgentOptions,
|
|
19
|
+
RunAgentUsage,
|
|
20
|
+
ConversationMessage,
|
|
21
|
+
UserMsg,
|
|
22
|
+
AssistantMsg,
|
|
23
|
+
ToolResultMsg,
|
|
24
|
+
} from './run.js';
|
|
25
|
+
export {
|
|
26
|
+
setTodos,
|
|
27
|
+
getTodos,
|
|
28
|
+
clearTodos,
|
|
29
|
+
formatTodos,
|
|
30
|
+
snapshotTodos,
|
|
31
|
+
restoreTodos,
|
|
32
|
+
} from './todos.js';
|
|
33
|
+
export type {Todo, TodoStatus} from './todos.js';
|
|
34
|
+
export {captureRunScope, restoreRunScope} from './scope.js';
|
|
35
|
+
export type {RunScope} from './scope.js';
|
|
@@ -0,0 +1,136 @@
|
|
|
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
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
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
|
+
});
|