korveniq 1.0.6 → 1.0.7
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 +33 -6
- package/bin/index.js +3 -0
- package/endpoints.json +2 -1
- package/lib/api.js +8 -0
- package/lib/approval-report.js +215 -0
- package/lib/approval-transport.js +97 -0
- package/lib/build-profile.json +2 -2
- package/lib/chat.js +45 -14
- package/lib/endpoints.js +2 -1
- package/lib/exec-policy.js +8 -2
- package/lib/headless.js +1 -1
- package/lib/net-forward.js +27 -0
- package/lib/net-proxy.js +165 -0
- package/lib/paste.js +330 -0
- package/lib/pkg-install.js +275 -0
- package/lib/realtime.js +47 -0
- package/lib/sandbox-net.js +243 -0
- package/lib/sandbox.js +50 -17
- package/lib/select-menu.js +27 -8
- package/lib/suggestions.js +8 -2
- package/lib/tool-parser.js +13 -49
- package/lib/tools.js +268 -46
- package/lib/update-restart.js +53 -0
- package/lib/update-source.js +14 -2
- package/lib/update-view.js +59 -1
- package/lib/update.js +123 -5
- package/lib/utils.js +59 -10
- package/package.json +1 -1
package/lib/sandbox.js
CHANGED
|
@@ -17,7 +17,11 @@
|
|
|
17
17
|
* - write inside the workspace only with --allow edit (bubblewrap additionally needs --allow delete: it cannot
|
|
18
18
|
* tell a delete from a write, so it never grants one alone)
|
|
19
19
|
* - delete / rename-away files only with --allow delete (seatbelt: file-write-unlink is denied separately)
|
|
20
|
-
* - network
|
|
20
|
+
* - external network only with --allow network (or the registries of an approved package installation,
|
|
21
|
+
* through the CLI's filtering proxy: lib/net-proxy.js)
|
|
22
|
+
* - this computer only (loopback) Linux: always, inside a private namespace the host is not part of. macOS: when a
|
|
23
|
+
* person allows it; see lib/sandbox-net.js for what that can and cannot enforce
|
|
24
|
+
* - unix sockets only with --allow network
|
|
21
25
|
* - read of credential stores (Korveniq settings, ~/.ssh, ~/.aws, cloud / registry tokens, the keychain service), and of
|
|
22
26
|
* .env / key files in the workspace (seatbelt) never
|
|
23
27
|
* - write to .git/hooks and .git/config never
|
|
@@ -122,7 +126,7 @@ function sanitizeEnv(env) {
|
|
|
122
126
|
* What a backend can actually grant for the requested permissions. A permission that cannot be enforced separately is
|
|
123
127
|
* not granted (never "granted but unenforced").
|
|
124
128
|
* @param {'seatbelt'|'bubblewrap'} backend
|
|
125
|
-
* @param {{ edit?: boolean, delete?: boolean, network?: boolean }} allow
|
|
129
|
+
* @param {{ edit?: boolean, delete?: boolean, network?: boolean, local?: boolean }} allow
|
|
126
130
|
*/
|
|
127
131
|
function effective(backend, allow = {}) {
|
|
128
132
|
const notes = [];
|
|
@@ -139,7 +143,9 @@ function effective(backend, allow = {}) {
|
|
|
139
143
|
notes.push('--allow delete has no effect on shell commands without --allow edit (the workspace is read-only)');
|
|
140
144
|
unlink = false;
|
|
141
145
|
}
|
|
142
|
-
|
|
146
|
+
// Under bubblewrap a sandbox without network still has its own loopback: "this computer only" is what it always has.
|
|
147
|
+
const local = !allow.network && (backend === 'bubblewrap' || Boolean(allow.local));
|
|
148
|
+
return { writeWorkspace, unlink, network: Boolean(allow.network), local, notes };
|
|
143
149
|
}
|
|
144
150
|
|
|
145
151
|
// ---------------------------------------------------------------------------
|
|
@@ -158,7 +164,7 @@ function sbRegexLiteral(p) {
|
|
|
158
164
|
* The SBPL profile. Later rules win, so the order is: allow everything, deny every write, re-allow the narrow places,
|
|
159
165
|
* then deny the things that stay forbidden inside them.
|
|
160
166
|
*/
|
|
161
|
-
function buildSeatbeltProfile({ root, tmpDir, credentials, eff, home = null, extraRead = [] }) {
|
|
167
|
+
function buildSeatbeltProfile({ root, tmpDir, credentials, eff, home = null, extraRead = [], denyPorts = [], proxyPort = null }) {
|
|
162
168
|
const lines = ['(version 1)', '(allow default)'];
|
|
163
169
|
lines.push('(deny file-write*)');
|
|
164
170
|
// Processes may not call setpgid (82) or setsid (147), so the usual daemonizing (fork + setsid, as perl, python, shells do it) cannot
|
|
@@ -176,7 +182,15 @@ function buildSeatbeltProfile({ root, tmpDir, credentials, eff, home = null, ext
|
|
|
176
182
|
lines.push(`(allow file-write-unlink (subpath ${sbString(tmpDir)}))`);
|
|
177
183
|
}
|
|
178
184
|
}
|
|
179
|
-
if (!eff.network)
|
|
185
|
+
if (!eff.network) {
|
|
186
|
+
lines.push('(deny network*)');
|
|
187
|
+
if (proxyPort) {
|
|
188
|
+
// An approved package installation: the registry proxy of the CLI and nothing else.
|
|
189
|
+
lines.push(`(allow network-outbound (remote tcp "localhost:${Number(proxyPort)}"))`);
|
|
190
|
+
} else if (eff.local) {
|
|
191
|
+
lines.push(...seatbeltLocalRules(denyPorts));
|
|
192
|
+
}
|
|
193
|
+
}
|
|
180
194
|
// Credential stores are not writable either, even when the workspace is a folder above them.
|
|
181
195
|
if (credentials.length) lines.push(`(deny file-write* ${credentials.map((p) => `(subpath ${sbString(p)})`).join(' ')})`);
|
|
182
196
|
// The user's home is unreadable except the workspace and the toolchain locations above. (file-read-metadata stays allowed:
|
|
@@ -192,6 +206,8 @@ function buildSeatbeltProfile({ root, tmpDir, credentials, eff, home = null, ext
|
|
|
192
206
|
const r = sbRegexLiteral(root);
|
|
193
207
|
lines.push(`(deny file-read* (regex #"^${r}/(.*/)?\\.env(\\.[^/]*)?$") (regex #"^${r}/(.*/)?(id_rsa|id_dsa|id_ecdsa|id_ed25519|\\.netrc|\\.pgpass|\\.htpasswd)$") (regex #"^${r}/.*\\.(pem|key|pfx|p12|keystore|jks|ppk)$"))`);
|
|
194
208
|
lines.push(`(allow file-read* (regex #"^${r}/(.*/)?\\.env\\.(example|sample|template|dist)$"))`);
|
|
209
|
+
// A public list of certificate authorities that Python's pip and requests load from inside a virtual environment: not a secret.
|
|
210
|
+
lines.push(`(allow file-read* (regex #"^${r}/(.*/)?site-packages/(pip/_vendor/)?certifi/cacert\\.pem$"))`);
|
|
195
211
|
// Services that act for the caller outside the sandbox (a "confused deputy"): the keychain daemons (`security find-generic-password`),
|
|
196
212
|
// Launch Services (`open -a`), Apple Events (`osascript` driving other apps), the pasteboard (`pbpaste`) and the preferences
|
|
197
213
|
// daemon (`defaults write` changes files the sandbox itself may not touch). Each of these was shown to work from inside a
|
|
@@ -202,13 +218,28 @@ function buildSeatbeltProfile({ root, tmpDir, credentials, eff, home = null, ext
|
|
|
202
218
|
return `${lines.join('\n')}\n`;
|
|
203
219
|
}
|
|
204
220
|
|
|
221
|
+
/**
|
|
222
|
+
* TCP to and from this computer, except the ports in `denyPorts`. NOTE: seatbelt's "localhost" matches every address of
|
|
223
|
+
* this machine, 0.0.0.0 included, so listening is NOT limited to loopback here (lib/sandbox-net.js watches for that).
|
|
224
|
+
* The "(with no-report)" is required: without it the later deny does not override the allow (checked at run time).
|
|
225
|
+
*/
|
|
226
|
+
function seatbeltLocalRules(denyPorts = []) {
|
|
227
|
+
return [
|
|
228
|
+
'(allow network-bind (local tcp "localhost:*"))',
|
|
229
|
+
'(allow network-inbound (local tcp "localhost:*"))',
|
|
230
|
+
'(allow network-outbound (remote tcp "localhost:*"))',
|
|
231
|
+
...denyPorts.map((p) => `(deny network-outbound (remote tcp "localhost:${Number(p)}") (with no-report))`),
|
|
232
|
+
];
|
|
233
|
+
}
|
|
234
|
+
|
|
205
235
|
// ---------------------------------------------------------------------------
|
|
206
236
|
// bubblewrap (Linux)
|
|
207
237
|
// ---------------------------------------------------------------------------
|
|
208
238
|
|
|
209
|
-
function buildBwrapArgs({ root, cwd, tmpDir, credentials, eff, home = null, extraRead = [], secrets = [], seccompFd = null }) {
|
|
239
|
+
function buildBwrapArgs({ root, cwd, tmpDir, credentials, eff, home = null, extraRead = [], secrets = [], seccompFd = null, joined = false }) {
|
|
210
240
|
const args = ['--die-with-parent', '--new-session', '--unshare-pid', '--unshare-ipc', '--unshare-uts', '--unshare-cgroup-try'];
|
|
211
|
-
|
|
241
|
+
// `joined`: the command is started inside an existing private namespace (lib/sandbox-net.js) and stays there.
|
|
242
|
+
if (!eff.network && !joined) args.push('--unshare-net');
|
|
212
243
|
args.push('--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc');
|
|
213
244
|
// /run holds the host's service sockets (docker.sock, the D-Bus and systemd buses, ssh/gpg agents): a pathname unix socket is not
|
|
214
245
|
// scoped by a network namespace, so a process that can still SEE it can connect to it. Hide it; keep the resolver config DNS needs.
|
|
@@ -308,6 +339,7 @@ function buildSeccompFilter(arch = process.arch) {
|
|
|
308
339
|
// ---------------------------------------------------------------------------
|
|
309
340
|
|
|
310
341
|
const TEMPLATE_ENV = /\.env\.(example|sample|template|dist)$/i;
|
|
342
|
+
const PUBLIC_CA_BUNDLE = /[\\/]site-packages[\\/](pip[\\/]_vendor[\\/])?certifi[\\/]cacert\.pem$/; // public certificate authorities (certifi)
|
|
311
343
|
const secretScanCache = new Map(); // root -> { at, files }
|
|
312
344
|
const SECRET_SCAN_TTL_MS = 20_000;
|
|
313
345
|
|
|
@@ -336,7 +368,7 @@ function findWorkspaceSecrets(root, { maxEntries = 200_000, deadlineMs = 1000 }
|
|
|
336
368
|
const full = path.join(dir, d.name);
|
|
337
369
|
if (d.isDirectory()) {
|
|
338
370
|
if (d.name !== '.git' && d.name !== 'node_modules') stack.push(full);
|
|
339
|
-
} else if ((d.isFile() || d.isSymbolicLink()) && !TEMPLATE_ENV.test(d.name) && secretReason(full)) files.push(full);
|
|
371
|
+
} else if ((d.isFile() || d.isSymbolicLink()) && !TEMPLATE_ENV.test(d.name) && !(d.isFile() && PUBLIC_CA_BUNDLE.test(full)) && secretReason(full)) files.push(full);
|
|
340
372
|
}
|
|
341
373
|
}
|
|
342
374
|
secretScanCache.set(root, { at: Date.now(), files });
|
|
@@ -485,7 +517,7 @@ function resetDetection() {
|
|
|
485
517
|
* @param {object} [opts.backendInfo] override detection (tests)
|
|
486
518
|
* @returns {{ available: false, reason: string } | { available: true, backend: string, effective: object, tmpDir: string, wrap: Function, cleanup: Function, describe: object }}
|
|
487
519
|
*/
|
|
488
|
-
function prepare({ root, cwd = null, allow = {}, home = os.homedir(), configDir = null, backendInfo = null }) {
|
|
520
|
+
function prepare({ root, cwd = null, allow = {}, home = os.homedir(), configDir = null, backendInfo = null, namespace = null, denyPorts = [], proxyPort = null }) {
|
|
489
521
|
const info = backendInfo || detect();
|
|
490
522
|
if (!info.available) return { available: false, reason: info.reason || 'no sandbox backend' };
|
|
491
523
|
const realRoot = fs.realpathSync(root);
|
|
@@ -524,7 +556,7 @@ function prepare({ root, cwd = null, allow = {}, home = os.homedir(), configDir
|
|
|
524
556
|
};
|
|
525
557
|
let wrap;
|
|
526
558
|
if (info.backend === 'seatbelt') {
|
|
527
|
-
const profile = buildSeatbeltProfile({ root: realRoot, tmpDir, credentials, eff, home: realHome, extraRead });
|
|
559
|
+
const profile = buildSeatbeltProfile({ root: realRoot, tmpDir, credentials, eff, home: realHome, extraRead, denyPorts, proxyPort });
|
|
528
560
|
wrap = (file, args) => ({ file: info.binary, args: ['-p', profile, file, ...args], env: { TMPDIR: tmpDir, TMP: tmpDir, TEMP: tmpDir }, fdFiles: [] });
|
|
529
561
|
} else {
|
|
530
562
|
const secrets = findWorkspaceSecrets(realRoot);
|
|
@@ -540,12 +572,12 @@ function prepare({ root, cwd = null, allow = {}, home = os.homedir(), configDir
|
|
|
540
572
|
fs.writeFileSync(filterFile, filter, { mode: 0o600 });
|
|
541
573
|
}
|
|
542
574
|
// fdIndex: where the caller puts the filter's file descriptor in the child's stdio array.
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
fdFiles: filterFile ? [{ index: fdIndex, path: filterFile }] : []
|
|
548
|
-
}
|
|
575
|
+
const joined = !eff.network && Boolean(namespace);
|
|
576
|
+
wrap = (file, args, { fdIndex = 4 } = {}) => {
|
|
577
|
+
const bwrapArgs = [...(joined ? namespace.bwrapArgs : []), ...buildBwrapArgs({ root: realRoot, cwd: realCwd, tmpDir, credentials, eff, home: realHome, extraRead, secrets, seccompFd: filterFile ? fdIndex : null, joined }), file, ...args];
|
|
578
|
+
const command = joined ? namespace.enter([info.binary, ...bwrapArgs]) : { file: info.binary, args: bwrapArgs };
|
|
579
|
+
return { ...command, env: { TMPDIR: '/tmp', TMP: '/tmp', TEMP: '/tmp' }, fdFiles: filterFile ? [{ index: fdIndex, path: filterFile }] : [] };
|
|
580
|
+
};
|
|
549
581
|
}
|
|
550
582
|
return {
|
|
551
583
|
available: true,
|
|
@@ -554,7 +586,7 @@ function prepare({ root, cwd = null, allow = {}, home = os.homedir(), configDir
|
|
|
554
586
|
tmpDir,
|
|
555
587
|
wrap,
|
|
556
588
|
cleanup,
|
|
557
|
-
describe: { backend: info.backend, workspaceWritable: eff.writeWorkspace, deletesAllowed: eff.unlink, network: eff.network, notes: eff.notes },
|
|
589
|
+
describe: { backend: info.backend, workspaceWritable: eff.writeWorkspace, deletesAllowed: eff.unlink, network: eff.network, local: eff.local, notes: eff.notes },
|
|
558
590
|
};
|
|
559
591
|
}
|
|
560
592
|
|
|
@@ -567,6 +599,7 @@ module.exports = {
|
|
|
567
599
|
credentialPaths,
|
|
568
600
|
sanitizeEnv,
|
|
569
601
|
buildSeatbeltProfile,
|
|
602
|
+
seatbeltLocalRules,
|
|
570
603
|
buildBwrapArgs,
|
|
571
604
|
buildSeccompFilter,
|
|
572
605
|
findWorkspaceSecrets,
|
package/lib/select-menu.js
CHANGED
|
@@ -10,17 +10,25 @@
|
|
|
10
10
|
* Up/Down (or k/j, Tab) move, Enter confirms, Esc and Ctrl+C cancel (the caller treats a cancel as "no").
|
|
11
11
|
* The letter keys given as `key` on an option, and the digits 1-9, only MOVE the highlight: a stray
|
|
12
12
|
* keystroke never approves anything, Enter always decides. The highlighted option at the start is
|
|
13
|
-
* `initial`;
|
|
13
|
+
* `initial`; the CLI's yes/no menus start on "Yes".
|
|
14
14
|
*
|
|
15
15
|
* Each redraw is one write (cursor up + clear + the whole frame), so nothing flickers or repeats.
|
|
16
|
+
* Keys pressed before the menu is on screen (typed ahead while a reply was coming in) are read and thrown away
|
|
17
|
+
* first: nobody can answer a question they have not seen.
|
|
18
|
+
*
|
|
19
|
+
* A paste never answers: what it holds moves nothing and its line breaks confirm nothing (lib/paste.js). Esc and
|
|
20
|
+
* Ctrl+C, which only refuse, always work.
|
|
21
|
+
*
|
|
16
22
|
* Raw mode and the 'keypress' listeners are restored on every way out. Without a TTY the caller
|
|
17
23
|
* must not use this (see canSelect()).
|
|
18
24
|
*/
|
|
19
25
|
|
|
20
26
|
const readline = require('readline');
|
|
21
27
|
const { theme, symbols } = require('./ui');
|
|
28
|
+
const paste = require('./paste');
|
|
22
29
|
|
|
23
30
|
const ESC = '\x1b';
|
|
31
|
+
const TYPE_AHEAD_MS = 50; // long enough for input that is already waiting to arrive
|
|
24
32
|
const POINTER = symbols.bullet === '⏺' ? '❯' : '>';
|
|
25
33
|
|
|
26
34
|
/** True when both ends are a terminal, so arrow keys can work. */
|
|
@@ -78,7 +86,13 @@ function selectMenu({ question, options, initial = 0, input = process.stdin, out
|
|
|
78
86
|
drawnRows = rowsOf(text, output.columns);
|
|
79
87
|
};
|
|
80
88
|
|
|
89
|
+
function discard(_str, key = {}) {
|
|
90
|
+
if (key.ctrl && key.name === 'c') finish(true);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
paste.track(input); // (before the key decoder starts)
|
|
81
94
|
readline.emitKeypressEvents(input);
|
|
95
|
+
paste.enable(output);
|
|
82
96
|
const wasRaw = input.isRaw;
|
|
83
97
|
input.setRawMode(true);
|
|
84
98
|
input.resume();
|
|
@@ -88,6 +102,7 @@ function selectMenu({ question, options, initial = 0, input = process.stdin, out
|
|
|
88
102
|
if (settled) return;
|
|
89
103
|
settled = true;
|
|
90
104
|
input.removeListener('keypress', onKey);
|
|
105
|
+
input.removeListener('keypress', discard);
|
|
91
106
|
input.removeListener('end', onEnd);
|
|
92
107
|
input.removeListener('close', onEnd);
|
|
93
108
|
try {
|
|
@@ -115,12 +130,10 @@ function selectMenu({ question, options, initial = 0, input = process.stdin, out
|
|
|
115
130
|
if (settled) return;
|
|
116
131
|
if (key.ctrl && key.name === 'c') return finish(true);
|
|
117
132
|
if (key.ctrl && key.name === 'd') return finish(true);
|
|
133
|
+
if (key.name === 'escape') return finish(true); // refusing is always safe
|
|
134
|
+
if (key.name === 'return' || key.name === 'enter') return paste.confirmEnter(input, () => finish(false));
|
|
135
|
+
if (!paste.deliberate(input)) return;
|
|
118
136
|
switch (key.name) {
|
|
119
|
-
case 'escape':
|
|
120
|
-
return finish(true);
|
|
121
|
-
case 'return':
|
|
122
|
-
case 'enter':
|
|
123
|
-
return finish(false);
|
|
124
137
|
case 'up':
|
|
125
138
|
return move(-1);
|
|
126
139
|
case 'down':
|
|
@@ -144,10 +157,16 @@ function selectMenu({ question, options, initial = 0, input = process.stdin, out
|
|
|
144
157
|
finish(true); // input ended: never approve
|
|
145
158
|
}
|
|
146
159
|
|
|
147
|
-
input.on('keypress', onKey);
|
|
148
160
|
input.once('end', onEnd);
|
|
149
161
|
input.once('close', onEnd);
|
|
150
|
-
|
|
162
|
+
// Take what is already waiting in the terminal's buffer and drop it; only Ctrl+C still counts. Then show the menu.
|
|
163
|
+
input.on('keypress', discard);
|
|
164
|
+
setTimeout(() => {
|
|
165
|
+
input.removeListener('keypress', discard);
|
|
166
|
+
if (settled) return;
|
|
167
|
+
input.on('keypress', onKey);
|
|
168
|
+
draw();
|
|
169
|
+
}, TYPE_AHEAD_MS);
|
|
151
170
|
});
|
|
152
171
|
}
|
|
153
172
|
|
package/lib/suggestions.js
CHANGED
|
@@ -52,12 +52,12 @@ const width = (s) => [...s].length;
|
|
|
52
52
|
* @param {() => boolean} [opts.active] false while typing a continuation line
|
|
53
53
|
* @param {() => void} [opts.onKey] every key the user presses
|
|
54
54
|
* @param {(item) => boolean} [opts.needsArgument] Tab on this item adds a space
|
|
55
|
-
* @returns {{ detach: () => void, clear: () => void, render: () => void }}
|
|
55
|
+
* @returns {{ detach: () => void, clear: () => void, render: () => void, refresh: () => void }}
|
|
56
56
|
*/
|
|
57
57
|
function attachSuggestions(rl, { rlKeypress, compute, max = 8, active = () => true, onKey = () => {}, needsArgument = () => false }) {
|
|
58
58
|
const input = rl.input;
|
|
59
59
|
const output = rl.output;
|
|
60
|
-
if (!rlKeypress || !output.isTTY) return { detach() {}, clear() {}, render() {} };
|
|
60
|
+
if (!rlKeypress || !output.isTTY) return { detach() {}, clear() {}, render() {}, refresh() {} };
|
|
61
61
|
|
|
62
62
|
let items = [];
|
|
63
63
|
let pending = false;
|
|
@@ -208,6 +208,12 @@ function attachSuggestions(rl, { rlKeypress, compute, max = 8, active = () => tr
|
|
|
208
208
|
},
|
|
209
209
|
clear,
|
|
210
210
|
render,
|
|
211
|
+
/** The line was changed from outside (a paste): work out the list again. */
|
|
212
|
+
refresh() {
|
|
213
|
+
if (detached) return;
|
|
214
|
+
update();
|
|
215
|
+
render();
|
|
216
|
+
},
|
|
211
217
|
};
|
|
212
218
|
}
|
|
213
219
|
|
package/lib/tool-parser.js
CHANGED
|
@@ -38,12 +38,8 @@
|
|
|
38
38
|
* Markers are deliberately strict (a whole line that is only a path, a
|
|
39
39
|
* relative path with an extension) so example snippets are not saved.
|
|
40
40
|
*
|
|
41
|
-
*
|
|
42
|
-
*
|
|
43
|
-
* still approves it, even in autonomous mode). "$ " prompts are stripped;
|
|
44
|
-
* when a block uses them, the lines without a prompt are treated as sample
|
|
45
|
-
* output and dropped. Blocks in other languages (console, powershell, js, …)
|
|
46
|
-
* are never run.
|
|
41
|
+
* Commands are NEVER taken from Markdown: a ```bash / ```sh / ```shell block is part of the answer, shown to the user
|
|
42
|
+
* and nothing else. A command runs only from a <tool_call> block (or a native tool call). Phase 3.20.
|
|
47
43
|
*
|
|
48
44
|
* ToolCallFilter (streaming) and extractToolCalls (final text) apply the same
|
|
49
45
|
* rules, so what is hidden on screen is exactly what gets executed.
|
|
@@ -225,30 +221,13 @@ function fenceTarget({ info, prevLine, firstLine }) {
|
|
|
225
221
|
return { path, source, lang: parsed.lang };
|
|
226
222
|
}
|
|
227
223
|
|
|
228
|
-
// Languages whose code blocks are proposed as commands (POSIX shells only).
|
|
229
|
-
const COMMAND_LANGS = new Set(['bash', 'sh', 'shell', 'zsh']);
|
|
230
|
-
|
|
231
224
|
/**
|
|
232
|
-
*
|
|
233
|
-
*
|
|
234
|
-
*/
|
|
235
|
-
function commandFromBody(bodyLines) {
|
|
236
|
-
const lines = bodyLines.map((l) => l.replace(/\s+$/, ''));
|
|
237
|
-
const prompted = lines.filter((l) => /^\s*\$\s/.test(l));
|
|
238
|
-
const picked = prompted.length ? prompted.map((l) => l.replace(/^\s*\$\s+/, '')) : lines;
|
|
239
|
-
const command = picked.join('\n').replace(/^\n+|\n+$/g, '');
|
|
240
|
-
return command.split('\n').some((l) => l.trim() && !l.trim().startsWith('#')) ? command : '';
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
/**
|
|
244
|
-
* What a fenced block is: a file to write, a command to propose, or plain text.
|
|
245
|
-
* Files win, so **setup.sh** above a ```bash block is written, not run.
|
|
246
|
-
* @returns {{ kind: 'file', path, source, lang } | { kind: 'command' } | null}
|
|
225
|
+
* What a fenced block is: a file to write, or plain text. A block of commands is always plain text.
|
|
226
|
+
* @returns {{ kind: 'file', path, source, lang } | null}
|
|
247
227
|
*/
|
|
248
228
|
function classifyFence(opts) {
|
|
249
229
|
const target = fenceTarget(opts);
|
|
250
|
-
|
|
251
|
-
return COMMAND_LANGS.has(parseInfo(opts.info).lang) ? { kind: 'command' } : null;
|
|
230
|
+
return target ? { kind: 'file', ...target } : null;
|
|
252
231
|
}
|
|
253
232
|
|
|
254
233
|
const FENCE_OPEN_RE = /^([ \t]{0,3})(`{3,}|~{3,})(.*)$/;
|
|
@@ -303,22 +282,18 @@ function fenceBlocks(text) {
|
|
|
303
282
|
return blocks;
|
|
304
283
|
}
|
|
305
284
|
|
|
306
|
-
/** Turn a raw fence block into a
|
|
285
|
+
/** Turn a raw fence block into a write_file payload, or null. */
|
|
307
286
|
function toolFence(b) {
|
|
308
287
|
const what = classifyFence({ info: b.info, prevLine: b.prevLine, firstLine: b.bodyLines[0] });
|
|
309
288
|
if (!what) return null;
|
|
310
289
|
const base = { start: b.start, end: b.end, ...(b.unclosed ? { unclosed: true } : {}) };
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
return { kind: 'file', ...base, path: what.path, source: what.source, content: contentLines.length ? `${contentLines.join('\n')}\n` : '' };
|
|
314
|
-
}
|
|
315
|
-
return { kind: 'command', ...base, command: commandFromBody(b.bodyLines) };
|
|
290
|
+
const contentLines = what.source === 'comment' ? b.bodyLines.slice(1) : b.bodyLines;
|
|
291
|
+
return { kind: 'file', ...base, path: what.path, source: what.source, content: contentLines.length ? `${contentLines.join('\n')}\n` : '' };
|
|
316
292
|
}
|
|
317
293
|
|
|
318
294
|
/**
|
|
319
|
-
* Fenced blocks in `text` that are tool calls: files
|
|
320
|
-
* @returns {Array<{ kind: 'file'
|
|
321
|
-
* source?: string, content?: string, command?: string, unclosed?: boolean }>}
|
|
295
|
+
* Fenced blocks in `text` that are tool calls: files only.
|
|
296
|
+
* @returns {Array<{ kind: 'file', start: number, end: number, path: string, source: string, content: string, unclosed?: boolean }>}
|
|
322
297
|
*/
|
|
323
298
|
function findToolFences(text) {
|
|
324
299
|
return fenceBlocks(text).map(toolFence).filter(Boolean);
|
|
@@ -524,17 +499,6 @@ function extractToolCalls({ text = '', message = null, nonces = null, markerHint
|
|
|
524
499
|
} else {
|
|
525
500
|
calls.push({ name: 'write_file', args: { path: open.path, content: blockContent(body, { exact: Boolean(open.nonce) }) } });
|
|
526
501
|
}
|
|
527
|
-
} else if (r.kind === 'fence' && r.fence.kind === 'command') {
|
|
528
|
-
const f = r.fence;
|
|
529
|
-
if (f.unclosed) {
|
|
530
|
-
calls.push({
|
|
531
|
-
name: null,
|
|
532
|
-
truncated: true,
|
|
533
|
-
error: 'Your reply was cut off in the middle of a shell code block, so the command was not run. Resend it in a <tool_call> block.',
|
|
534
|
-
});
|
|
535
|
-
} else if (f.command) {
|
|
536
|
-
calls.push({ name: 'execute_bash', args: { command: f.command }, fallback: true });
|
|
537
|
-
}
|
|
538
502
|
} else if (r.kind === 'fence') {
|
|
539
503
|
const f = r.fence;
|
|
540
504
|
if (f.unclosed) {
|
|
@@ -614,7 +578,7 @@ function partialPrefixLength(text, tag) {
|
|
|
614
578
|
|
|
615
579
|
/**
|
|
616
580
|
* Hide tool calls while a reply streams: XML blocks, and code blocks that
|
|
617
|
-
* name a file (same rules as extractToolCalls). push() returns the text that
|
|
581
|
+
* name a file (same rules as extractToolCalls; every other code block is shown). push() returns the text that
|
|
618
582
|
* is safe to print. onEnter(label) fires when a hidden block starts.
|
|
619
583
|
*
|
|
620
584
|
* Modes: text -> xml | fence-pending -> fence-hidden | fence-visible -> text.
|
|
@@ -751,7 +715,7 @@ class ToolCallFilter {
|
|
|
751
715
|
: classifyFence({ info: this.fence.info, prevLine: this.fence.prevLine, firstLine });
|
|
752
716
|
if (what) {
|
|
753
717
|
this.mode = 'fence-hidden';
|
|
754
|
-
this.onEnter(
|
|
718
|
+
this.onEnter(`Writing ${what.path}`);
|
|
755
719
|
} else {
|
|
756
720
|
out += this.emit(`${this.fence.openLine}\n`);
|
|
757
721
|
this.mode = 'fence-visible';
|
|
@@ -841,7 +805,7 @@ class ToolCallFilter {
|
|
|
841
805
|
let rest = '';
|
|
842
806
|
if (this.mode === 'text') {
|
|
843
807
|
rest = this.buffer;
|
|
844
|
-
// The reply ended in the middle of a fence line that names a file
|
|
808
|
+
// The reply ended in the middle of a fence line that names a file:
|
|
845
809
|
// the parser treats that as a cut-off code block, so it stays hidden here too.
|
|
846
810
|
const open = FENCE_OPEN_RE.exec(this.buffer);
|
|
847
811
|
if (open && !this.buffer.includes('\n') && !(open[2][0] === '`' && open[3].includes('`'))) {
|