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,358 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Lightweight syntax highlighting for terminal code blocks.
|
|
3
|
+
*
|
|
4
|
+
* Zero dependencies — keyword + regex based. Covers the most common
|
|
5
|
+
* languages well enough for agent output (TS, JS, Python, JSON, Shell, Go, Rust).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import {c} from '../theme.js';
|
|
9
|
+
|
|
10
|
+
// Per-language keyword sets
|
|
11
|
+
const KEYWORDS: Record<string, Set<string> | null> = {
|
|
12
|
+
typescript: new Set([
|
|
13
|
+
'import',
|
|
14
|
+
'export',
|
|
15
|
+
'from',
|
|
16
|
+
'const',
|
|
17
|
+
'let',
|
|
18
|
+
'var',
|
|
19
|
+
'function',
|
|
20
|
+
'async',
|
|
21
|
+
'await',
|
|
22
|
+
'return',
|
|
23
|
+
'if',
|
|
24
|
+
'else',
|
|
25
|
+
'for',
|
|
26
|
+
'while',
|
|
27
|
+
'do',
|
|
28
|
+
'switch',
|
|
29
|
+
'case',
|
|
30
|
+
'break',
|
|
31
|
+
'continue',
|
|
32
|
+
'new',
|
|
33
|
+
'class',
|
|
34
|
+
'extends',
|
|
35
|
+
'implements',
|
|
36
|
+
'interface',
|
|
37
|
+
'type',
|
|
38
|
+
'enum',
|
|
39
|
+
'namespace',
|
|
40
|
+
'try',
|
|
41
|
+
'catch',
|
|
42
|
+
'finally',
|
|
43
|
+
'throw',
|
|
44
|
+
'typeof',
|
|
45
|
+
'instanceof',
|
|
46
|
+
'in',
|
|
47
|
+
'of',
|
|
48
|
+
'as',
|
|
49
|
+
'static',
|
|
50
|
+
'private',
|
|
51
|
+
'public',
|
|
52
|
+
'protected',
|
|
53
|
+
'readonly',
|
|
54
|
+
'abstract',
|
|
55
|
+
'override',
|
|
56
|
+
'default',
|
|
57
|
+
'void',
|
|
58
|
+
'null',
|
|
59
|
+
'undefined',
|
|
60
|
+
'true',
|
|
61
|
+
'false',
|
|
62
|
+
'this',
|
|
63
|
+
'super',
|
|
64
|
+
'satisfies',
|
|
65
|
+
'keyof',
|
|
66
|
+
'infer',
|
|
67
|
+
'extends',
|
|
68
|
+
'never',
|
|
69
|
+
'unknown',
|
|
70
|
+
'any',
|
|
71
|
+
]),
|
|
72
|
+
javascript: null, // alias → typescript
|
|
73
|
+
python: new Set([
|
|
74
|
+
'import',
|
|
75
|
+
'from',
|
|
76
|
+
'def',
|
|
77
|
+
'class',
|
|
78
|
+
'return',
|
|
79
|
+
'if',
|
|
80
|
+
'elif',
|
|
81
|
+
'else',
|
|
82
|
+
'for',
|
|
83
|
+
'while',
|
|
84
|
+
'break',
|
|
85
|
+
'continue',
|
|
86
|
+
'try',
|
|
87
|
+
'except',
|
|
88
|
+
'finally',
|
|
89
|
+
'raise',
|
|
90
|
+
'with',
|
|
91
|
+
'as',
|
|
92
|
+
'yield',
|
|
93
|
+
'lambda',
|
|
94
|
+
'pass',
|
|
95
|
+
'del',
|
|
96
|
+
'global',
|
|
97
|
+
'nonlocal',
|
|
98
|
+
'assert',
|
|
99
|
+
'and',
|
|
100
|
+
'or',
|
|
101
|
+
'not',
|
|
102
|
+
'in',
|
|
103
|
+
'is',
|
|
104
|
+
'True',
|
|
105
|
+
'False',
|
|
106
|
+
'None',
|
|
107
|
+
'self',
|
|
108
|
+
'async',
|
|
109
|
+
'await',
|
|
110
|
+
]),
|
|
111
|
+
go: new Set([
|
|
112
|
+
'package',
|
|
113
|
+
'import',
|
|
114
|
+
'func',
|
|
115
|
+
'return',
|
|
116
|
+
'if',
|
|
117
|
+
'else',
|
|
118
|
+
'for',
|
|
119
|
+
'range',
|
|
120
|
+
'switch',
|
|
121
|
+
'case',
|
|
122
|
+
'default',
|
|
123
|
+
'break',
|
|
124
|
+
'continue',
|
|
125
|
+
'go',
|
|
126
|
+
'defer',
|
|
127
|
+
'select',
|
|
128
|
+
'chan',
|
|
129
|
+
'struct',
|
|
130
|
+
'interface',
|
|
131
|
+
'map',
|
|
132
|
+
'type',
|
|
133
|
+
'var',
|
|
134
|
+
'const',
|
|
135
|
+
'nil',
|
|
136
|
+
'true',
|
|
137
|
+
'false',
|
|
138
|
+
]),
|
|
139
|
+
rust: new Set([
|
|
140
|
+
'fn',
|
|
141
|
+
'let',
|
|
142
|
+
'mut',
|
|
143
|
+
'const',
|
|
144
|
+
'struct',
|
|
145
|
+
'enum',
|
|
146
|
+
'impl',
|
|
147
|
+
'trait',
|
|
148
|
+
'pub',
|
|
149
|
+
'use',
|
|
150
|
+
'mod',
|
|
151
|
+
'crate',
|
|
152
|
+
'self',
|
|
153
|
+
'super',
|
|
154
|
+
'return',
|
|
155
|
+
'if',
|
|
156
|
+
'else',
|
|
157
|
+
'for',
|
|
158
|
+
'while',
|
|
159
|
+
'loop',
|
|
160
|
+
'match',
|
|
161
|
+
'break',
|
|
162
|
+
'continue',
|
|
163
|
+
'move',
|
|
164
|
+
'ref',
|
|
165
|
+
'async',
|
|
166
|
+
'await',
|
|
167
|
+
'where',
|
|
168
|
+
'true',
|
|
169
|
+
'false',
|
|
170
|
+
'Some',
|
|
171
|
+
'None',
|
|
172
|
+
'Ok',
|
|
173
|
+
'Err',
|
|
174
|
+
'Self',
|
|
175
|
+
]),
|
|
176
|
+
bash: new Set([
|
|
177
|
+
'if',
|
|
178
|
+
'then',
|
|
179
|
+
'else',
|
|
180
|
+
'elif',
|
|
181
|
+
'fi',
|
|
182
|
+
'for',
|
|
183
|
+
'while',
|
|
184
|
+
'do',
|
|
185
|
+
'done',
|
|
186
|
+
'case',
|
|
187
|
+
'esac',
|
|
188
|
+
'function',
|
|
189
|
+
'return',
|
|
190
|
+
'exit',
|
|
191
|
+
'echo',
|
|
192
|
+
'export',
|
|
193
|
+
'local',
|
|
194
|
+
'readonly',
|
|
195
|
+
'source',
|
|
196
|
+
'alias',
|
|
197
|
+
'unalias',
|
|
198
|
+
'set',
|
|
199
|
+
'unset',
|
|
200
|
+
'shift',
|
|
201
|
+
'eval',
|
|
202
|
+
'exec',
|
|
203
|
+
'true',
|
|
204
|
+
'false',
|
|
205
|
+
'in',
|
|
206
|
+
]),
|
|
207
|
+
shell: null, // alias → bash
|
|
208
|
+
sh: null,
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
// Aliases
|
|
212
|
+
KEYWORDS.javascript = KEYWORDS.typescript;
|
|
213
|
+
KEYWORDS.js = KEYWORDS.typescript;
|
|
214
|
+
KEYWORDS.ts = KEYWORDS.typescript;
|
|
215
|
+
KEYWORDS.jsx = KEYWORDS.typescript;
|
|
216
|
+
KEYWORDS.tsx = KEYWORDS.typescript;
|
|
217
|
+
KEYWORDS.py = KEYWORDS.python;
|
|
218
|
+
KEYWORDS.rs = KEYWORDS.rust;
|
|
219
|
+
KEYWORDS.shell = KEYWORDS.bash;
|
|
220
|
+
|
|
221
|
+
/** Map language → keyword set. Returns null if language is unknown. */
|
|
222
|
+
function getKeywords(lang: string): Set<string> | null {
|
|
223
|
+
const lower = lang.toLowerCase().trim();
|
|
224
|
+
return KEYWORDS[lower] ?? null;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Simple syntax highlighter for terminal output.
|
|
229
|
+
*
|
|
230
|
+
* Applies ANSI colors to keywords, strings, comments, and numbers.
|
|
231
|
+
* Falls back to plain text for unknown languages.
|
|
232
|
+
*/
|
|
233
|
+
export function highlightCode(code: string, lang?: string): string[] {
|
|
234
|
+
const lines = code.split('\n');
|
|
235
|
+
|
|
236
|
+
if (!lang) return lines.map((l) => `${c.bright_black}${l}${c.reset}`);
|
|
237
|
+
|
|
238
|
+
const keywords = getKeywords(lang);
|
|
239
|
+
|
|
240
|
+
// JSON gets special treatment — highlight keys and string values differently
|
|
241
|
+
if (lang === 'json') return lines.map((l) => highlightJson(l));
|
|
242
|
+
|
|
243
|
+
return lines.map((line) => {
|
|
244
|
+
if (keywords) {
|
|
245
|
+
return highlightLine(line, keywords);
|
|
246
|
+
}
|
|
247
|
+
// Unknown language — just dim the code
|
|
248
|
+
return `${c.bright_black}${line}${c.reset}`;
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Highlight a single line of code.
|
|
254
|
+
*
|
|
255
|
+
* Strategy: walk the line character by character, tracking state
|
|
256
|
+
* (normal / in-string / in-comment) to avoid highlighting keywords
|
|
257
|
+
* that appear inside strings or comments.
|
|
258
|
+
*/
|
|
259
|
+
function highlightLine(line: string, keywords: Set<string>): string {
|
|
260
|
+
let result = '';
|
|
261
|
+
let i = 0;
|
|
262
|
+
|
|
263
|
+
while (i < line.length) {
|
|
264
|
+
const ch = line[i];
|
|
265
|
+
|
|
266
|
+
// Line comment — rest of line is comment
|
|
267
|
+
if (ch === '/' && line[i + 1] === '/') {
|
|
268
|
+
result += `${c.bright_black}${line.slice(i)}${c.reset}`;
|
|
269
|
+
return result;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Hash comment (Python, Shell)
|
|
273
|
+
if (ch === '#') {
|
|
274
|
+
result += `${c.bright_black}${line.slice(i)}${c.reset}`;
|
|
275
|
+
return result;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Block comment start /* ... */
|
|
279
|
+
if (ch === '/' && line[i + 1] === '*') {
|
|
280
|
+
const end = line.indexOf('*/', i + 2);
|
|
281
|
+
if (end !== -1) {
|
|
282
|
+
result += `${c.bright_black}${line.slice(i, end + 2)}${c.reset}`;
|
|
283
|
+
i = end + 2;
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
result += `${c.bright_black}${line.slice(i)}${c.reset}`;
|
|
287
|
+
return result;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Strings (single, double, backtick)
|
|
291
|
+
if (ch === '"' || ch === "'" || ch === '`') {
|
|
292
|
+
const quote = ch;
|
|
293
|
+
let j = i + 1;
|
|
294
|
+
while (j < line.length && line[j] !== quote) {
|
|
295
|
+
if (line[j] === '\\') j++; // skip escaped char
|
|
296
|
+
j++;
|
|
297
|
+
}
|
|
298
|
+
j = Math.min(j + 1, line.length); // include closing quote
|
|
299
|
+
result += `${c.green}${line.slice(i, j)}${c.reset}`;
|
|
300
|
+
i = j;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// Numbers
|
|
305
|
+
if (/[0-9]/.test(ch) && (i === 0 || /[\s(,=+\-*/<>![]/.test(line[i - 1]))) {
|
|
306
|
+
let j = i;
|
|
307
|
+
while (j < line.length && /[0-9._xXabcdefABCDEF]/.test(line[j])) j++;
|
|
308
|
+
result += `${c.magenta}${line.slice(i, j)}${c.reset}`;
|
|
309
|
+
i = j;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// Words (potential keywords)
|
|
314
|
+
if (/[a-zA-Z_$]/.test(ch)) {
|
|
315
|
+
let j = i;
|
|
316
|
+
while (j < line.length && /[a-zA-Z0-9_$]/.test(line[j])) j++;
|
|
317
|
+
const word = line.slice(i, j);
|
|
318
|
+
|
|
319
|
+
if (keywords.has(word)) {
|
|
320
|
+
result += `${c.cyan}${c.bold}${word}${c.reset}`;
|
|
321
|
+
} else if (i > 0 && line[i - 1] === '.') {
|
|
322
|
+
// Method/property access
|
|
323
|
+
result += `${c.yellow}${word}${c.reset}`;
|
|
324
|
+
} else {
|
|
325
|
+
result += word;
|
|
326
|
+
}
|
|
327
|
+
i = j;
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Operators and punctuation
|
|
332
|
+
result += ch;
|
|
333
|
+
i++;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
return result;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* Highlight JSON — differentiate keys from string values.
|
|
341
|
+
*
|
|
342
|
+
* { "key": "value" }
|
|
343
|
+
* ^^^^ ^^^^^^^^
|
|
344
|
+
* cyan green
|
|
345
|
+
*/
|
|
346
|
+
function highlightJson(line: string): string {
|
|
347
|
+
return (
|
|
348
|
+
line
|
|
349
|
+
// Keys: "key":
|
|
350
|
+
.replace(/"([^"\\]*)"(\s*:)/g, `${c.cyan}$1${c.reset}$2`)
|
|
351
|
+
// String values: "value"
|
|
352
|
+
.replace(/"([^"\\]*)"(?!\s*:)/g, `${c.green}"$1"${c.reset}`)
|
|
353
|
+
// Booleans and null
|
|
354
|
+
.replace(/\b(true|false|null)\b/g, `${c.magenta}$1${c.reset}`)
|
|
355
|
+
// Numbers
|
|
356
|
+
.replace(/\b(-?[0-9]+\.?[0-9]*)\b/g, `${c.magenta}$1${c.reset}`)
|
|
357
|
+
);
|
|
358
|
+
}
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Permission gate — wraps executeTool to check rules before dispatching.
|
|
3
|
+
*
|
|
4
|
+
* When a tool call needs approval, the gate sets state.overlayMode to
|
|
5
|
+
* 'permission' and awaits the user's response via state.permissionResolver.
|
|
6
|
+
* The TUI key handler in index.ts routes y/n/a/Esc to the resolver.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import {checkPermission, loadPermissionConfig, detectDangerousBash} from '@pal/core';
|
|
10
|
+
import type {PermissionConfig} from '@pal/core';
|
|
11
|
+
import type {ToolResult} from '@pal/core';
|
|
12
|
+
|
|
13
|
+
import {state} from '../state.js';
|
|
14
|
+
|
|
15
|
+
/** Extract the file path from a tool call's args (for file tools). */
|
|
16
|
+
function extractFilePath(toolName: string, args: Record<string, unknown>): string | null {
|
|
17
|
+
if (toolName === 'bash') return null; // bash uses command, not path
|
|
18
|
+
const path = args.path ?? args.filePath ?? args.file;
|
|
19
|
+
return typeof path === 'string' ? path : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Extract the bash command string from args. */
|
|
23
|
+
function extractCommand(toolName: string, args: Record<string, unknown>): string | null {
|
|
24
|
+
if (toolName !== 'bash') return null;
|
|
25
|
+
const cmd = args.command ?? args.cmd;
|
|
26
|
+
return typeof cmd === 'string' ? cmd : null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** The target string used for permission matching. */
|
|
30
|
+
function permissionTarget(toolName: string, args: Record<string, unknown>): string | null {
|
|
31
|
+
return extractFilePath(toolName, args) ?? extractCommand(toolName, args);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Result of a permission check before the tool runs. */
|
|
35
|
+
export type PermissionDecision =
|
|
36
|
+
| {allowed: true}
|
|
37
|
+
| {allowed: false; reason: string};
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Check whether a tool call is permitted.
|
|
41
|
+
*
|
|
42
|
+
* - 'allow' → immediately permitted
|
|
43
|
+
* - 'deny' → immediately denied (built-in sensitive rules or user config)
|
|
44
|
+
* - 'ask' → show overlay, await user response
|
|
45
|
+
*
|
|
46
|
+
* "Always" adds the pattern to the session whitelist so future calls skip
|
|
47
|
+
* the prompt.
|
|
48
|
+
*/
|
|
49
|
+
export async function checkToolPermission(
|
|
50
|
+
toolName: string,
|
|
51
|
+
args: Record<string, unknown>,
|
|
52
|
+
config?: PermissionConfig,
|
|
53
|
+
): Promise<PermissionDecision> {
|
|
54
|
+
const permConfig = config ?? loadPermissionConfig();
|
|
55
|
+
const target = permissionTarget(toolName, args);
|
|
56
|
+
|
|
57
|
+
// No extractable target (e.g., todo, verify, delegate) → use defaults only
|
|
58
|
+
const matchTarget = target ?? '*';
|
|
59
|
+
|
|
60
|
+
// Phase 6: Always deny known dangerous bash patterns — overrides everything
|
|
61
|
+
if (toolName === 'bash' && target) {
|
|
62
|
+
const danger = detectDangerousBash(target);
|
|
63
|
+
if (danger) {
|
|
64
|
+
return {
|
|
65
|
+
allowed: false,
|
|
66
|
+
reason: `Blocked: ${danger}. This command is too dangerous for an agent to run.`,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const decision = checkPermission(toolName, matchTarget, permConfig, state.permissionWhitelist);
|
|
72
|
+
|
|
73
|
+
if (decision === 'allow') return {allowed: true};
|
|
74
|
+
if (decision === 'deny') {
|
|
75
|
+
return {
|
|
76
|
+
allowed: false,
|
|
77
|
+
reason: `Permission denied: ${toolName} on "${matchTarget}" is not permitted.`,
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 'ask' — show the interactive prompt and await user response
|
|
82
|
+
return askUser(toolName, args, matchTarget, permConfig);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Show the permission overlay and wait for the user to respond.
|
|
87
|
+
*
|
|
88
|
+
* Returns a promise that resolves when the user presses y, a, n, or Esc.
|
|
89
|
+
* If another permission prompt is already active, this request is queued
|
|
90
|
+
* and shown sequentially after the current one is resolved.
|
|
91
|
+
*/
|
|
92
|
+
function askUser(
|
|
93
|
+
toolName: string,
|
|
94
|
+
args: Record<string, unknown>,
|
|
95
|
+
target: string,
|
|
96
|
+
config: PermissionConfig,
|
|
97
|
+
): Promise<PermissionDecision> {
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
// Build a summary of what the agent wants to do
|
|
100
|
+
const summary = buildPermissionSummary(toolName, args, target);
|
|
101
|
+
|
|
102
|
+
const onResult = (allow: boolean) => {
|
|
103
|
+
if (!allow) {
|
|
104
|
+
resolve({allowed: false, reason: `Permission denied by user for ${toolName}.`});
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
resolve({allowed: true});
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// If a permission prompt is already active, queue this one
|
|
111
|
+
if (state.permissionResolver) {
|
|
112
|
+
state.permissionQueue.push({resolver: onResult, toolName, target, summary});
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Store the resolver — index.ts key handler will call this
|
|
117
|
+
state.permissionResolver = (allow: boolean) => {
|
|
118
|
+
state.permissionResolver = null;
|
|
119
|
+
|
|
120
|
+
onResult(allow);
|
|
121
|
+
|
|
122
|
+
// If there are queued permissions, show the next one immediately
|
|
123
|
+
// (don't null pendingPermission — swap atomically to avoid flicker)
|
|
124
|
+
if (state.permissionQueue.length > 0) {
|
|
125
|
+
showNextQueuedPermission();
|
|
126
|
+
} else {
|
|
127
|
+
state.overlayMode = 'none';
|
|
128
|
+
state.pendingPermission = null;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
|
|
132
|
+
// Store the permission context so the overlay can display it
|
|
133
|
+
state.pendingPermission = {toolName, target, summary};
|
|
134
|
+
state.overlayMode = 'permission';
|
|
135
|
+
|
|
136
|
+
// Show the centered permission modal (removes editor, adds prompt to messages)
|
|
137
|
+
state.showPermissionModal();
|
|
138
|
+
|
|
139
|
+
// Force a render so the status-line indicator appears
|
|
140
|
+
state.refreshStatusLine();
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Pop the next queued permission request and update the already-mounted
|
|
146
|
+
* prompt component in-place. No need to re-add to the DOM — the
|
|
147
|
+
* PermissionPrompt reads state.pendingPermission on each render.
|
|
148
|
+
*/
|
|
149
|
+
function showNextQueuedPermission(): void {
|
|
150
|
+
const next = state.permissionQueue.shift();
|
|
151
|
+
if (!next) return;
|
|
152
|
+
|
|
153
|
+
state.permissionResolver = (allow: boolean) => {
|
|
154
|
+
state.permissionResolver = null;
|
|
155
|
+
|
|
156
|
+
next.resolver(allow);
|
|
157
|
+
|
|
158
|
+
// Continue processing the queue
|
|
159
|
+
if (state.permissionQueue.length > 0) {
|
|
160
|
+
showNextQueuedPermission();
|
|
161
|
+
} else {
|
|
162
|
+
state.overlayMode = 'none';
|
|
163
|
+
state.pendingPermission = null;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
// Swap the pending permission atomically — the mounted PermissionPrompt
|
|
168
|
+
// component reads this on each render, so it updates in-place.
|
|
169
|
+
state.pendingPermission = {toolName: next.toolName, target: next.target, summary: next.summary};
|
|
170
|
+
state.refreshStatusLine();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Build a human-readable summary of what the agent wants to do.
|
|
175
|
+
* Shown in the permission overlay.
|
|
176
|
+
*/
|
|
177
|
+
function buildPermissionSummary(
|
|
178
|
+
toolName: string,
|
|
179
|
+
args: Record<string, unknown>,
|
|
180
|
+
target: string,
|
|
181
|
+
): string {
|
|
182
|
+
switch (toolName) {
|
|
183
|
+
case 'write_file':
|
|
184
|
+
return `Write to ${target}`;
|
|
185
|
+
case 'edit_file':
|
|
186
|
+
return `Edit ${target}`;
|
|
187
|
+
case 'edit_block':
|
|
188
|
+
return `Edit blocks in ${target}`;
|
|
189
|
+
case 'bash':
|
|
190
|
+
return `Run: ${target.length > 80 ? target.slice(0, 77) + '...' : target}`;
|
|
191
|
+
case 'read_file':
|
|
192
|
+
return `Read ${target}`;
|
|
193
|
+
default:
|
|
194
|
+
return `${toolName}: ${target}`;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent lifecycle events — lets the UI observe sub-agents spawned by `delegate`
|
|
3
|
+
* without the tool executor knowing anything about the TUI.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
export type AgentEvent =
|
|
7
|
+
| {type: 'delegate-start'; id: string; task: string}
|
|
8
|
+
| {type: 'delegate-round'; id: string; round: number}
|
|
9
|
+
| {type: 'delegate-tool'; id: string; tool: string}
|
|
10
|
+
| {type: 'delegate-done'; id: string; summary: string; error?: boolean}
|
|
11
|
+
| {type: 'todos-updated'; todos: readonly {content: string; status: string}[]}
|
|
12
|
+
/** The agent asks the front-end to switch primary agent (e.g. → plan mode). */
|
|
13
|
+
| {type: 'primary-request'; name: string; reason?: string};
|
|
14
|
+
|
|
15
|
+
type Listener = (ev: AgentEvent) => void;
|
|
16
|
+
|
|
17
|
+
const listeners = new Set<Listener>();
|
|
18
|
+
|
|
19
|
+
/** Subscribe to agent events. Returns an unsubscribe function. */
|
|
20
|
+
export function onAgentEvent(fn: Listener): () => void {
|
|
21
|
+
listeners.add(fn);
|
|
22
|
+
return () => {
|
|
23
|
+
listeners.delete(fn);
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Emit an agent event to all subscribers. Never throws. */
|
|
28
|
+
export function emitAgentEvent(ev: AgentEvent): void {
|
|
29
|
+
for (const fn of [...listeners]) {
|
|
30
|
+
try {
|
|
31
|
+
fn(ev);
|
|
32
|
+
} catch {
|
|
33
|
+
/* a broken listener must not break the agent */
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
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
|
+
});
|