@alexwkleung/reika 0.1.1 → 0.2.0
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 +5 -0
- package/README.zh-CN.md +5 -0
- package/dist/config.js +50 -2
- package/dist/headless.js +2 -0
- package/dist/tools/_danger.js +1 -1
- package/dist/tools/_heredoc.js +405 -0
- package/dist/tools/_markdown.js +13 -105
- package/dist/tools/_readonly.js +52 -38
- package/dist/tools/_sandbox.js +141 -10
- package/dist/tools/_writetargets.js +1 -46
- package/dist/tools/bash.js +7 -9
- package/dist/ui/App.js +25 -0
- package/dist/ui/Question.js +1 -1
- package/dist/ui/Suggestions.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -137,6 +137,7 @@ The same pages are on the website, [reikacode.com](https://reikacode.com).
|
|
|
137
137
|
| [Platforms](docs/platforms.md) | Requirements, running on a weak machine, what differs on Linux and Windows |
|
|
138
138
|
| [Architecture and caveats](docs/architecture.md) | How the harness works, and known limitations |
|
|
139
139
|
| [Contributing](CONTRIBUTING.md) | Scripts, design philosophy, a pointer to `AGENTS.md`, and external contributor guidelines |
|
|
140
|
+
| [Changelog](CHANGELOG.md) | What changed in each release |
|
|
140
141
|
|
|
141
142
|
## Inspired by
|
|
142
143
|
|
|
@@ -149,3 +150,7 @@ Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|
|
|
149
150
|
## Supporting our work
|
|
150
151
|
|
|
151
152
|
If Reika is useful to you, consider supporting it via [GitHub Sponsors](https://github.com/sponsors/alexwkleung), [Ko-fi](https://ko-fi.com/alexwkleung), or [Buy Me a Coffee](https://buymeacoffee.com/alexwkleung). See [Support](docs/support.md) for what it funds and other ways to help.
|
|
153
|
+
|
|
154
|
+
## Contact
|
|
155
|
+
|
|
156
|
+
Bugs go to [GitHub Issues](https://github.com/alexwkleung/reika/issues), questions and ideas to [Discussions](https://github.com/alexwkleung/reika/discussions), and security reports go through [SECURITY.md](SECURITY.md). For anything else, email [hello@reikacode.com](mailto:hello@reikacode.com).
|
package/README.zh-CN.md
CHANGED
|
@@ -136,6 +136,7 @@ cd your-project && reika
|
|
|
136
136
|
| [平台](docs/platforms.md) | 运行要求、在弱机器上运行、Linux 和 Windows 上的差异 |
|
|
137
137
|
| [架构与注意事项](docs/architecture.md) | 框架如何工作,以及已知限制 |
|
|
138
138
|
| [贡献](CONTRIBUTING.md) | 脚本、设计理念、`AGENTS.md` 指引,以及外部贡献者指南 |
|
|
139
|
+
| [更新日志](CHANGELOG.md)(英文) | 每个版本的变更 |
|
|
139
140
|
|
|
140
141
|
## 灵感来自
|
|
141
142
|
|
|
@@ -148,3 +149,7 @@ Apache License 2.0。见 [LICENSE](LICENSE) 和 [NOTICE](NOTICE)。
|
|
|
148
149
|
## 支持我们的工作
|
|
149
150
|
|
|
150
151
|
如果 Reika 对你有用,可以考虑通过 [GitHub Sponsors](https://github.com/sponsors/alexwkleung)、[Ko-fi](https://ko-fi.com/alexwkleung) 或 [Buy Me a Coffee](https://buymeacoffee.com/alexwkleung) 支持这个项目。
|
|
152
|
+
|
|
153
|
+
## 联系
|
|
154
|
+
|
|
155
|
+
Bug 请提交到 [GitHub Issues](https://github.com/alexwkleung/reika/issues),问题和想法请发到 [Discussions](https://github.com/alexwkleung/reika/discussions),安全问题请按 [SECURITY.md](SECURITY.md) 私下报告。其他事情可以发邮件到 [hello@reikacode.com](mailto:hello@reikacode.com)。
|
package/dist/config.js
CHANGED
|
@@ -1,14 +1,61 @@
|
|
|
1
1
|
import dotenv from 'dotenv';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { join } from 'node:path';
|
|
4
5
|
import { DEFAULT_MIN_GEN_TOKENS } from './provider/budget.js';
|
|
5
6
|
import { parseMcpServers } from './mcp/config.js';
|
|
7
|
+
// The cwd .env belongs to whatever repo reika was opened in, which may not be the user's. A cloned
|
|
8
|
+
// repo's file must not turn the sandbox or approvals off, start a program (MCP), redirect where
|
|
9
|
+
// requests or logs go, or reach child processes (NODE_OPTIONS, GIT_*, TMPDIR — the last also names
|
|
10
|
+
// a sandbox-writable path), so only REIKA_* keys are read from it and these are not.
|
|
11
|
+
const PROJECT_ENV_DENIED = new Set([
|
|
12
|
+
'REIKA_SANDBOX',
|
|
13
|
+
'REIKA_AUTO_APPROVE',
|
|
14
|
+
'REIKA_MCP',
|
|
15
|
+
'REIKA_MCP_SERVERS',
|
|
16
|
+
'REIKA_PASTE_FETCH',
|
|
17
|
+
'REIKA_SKILL_AUTO',
|
|
18
|
+
'REIKA_URL_GROUNDING',
|
|
19
|
+
'REIKA_CDP_SEARCH',
|
|
20
|
+
'REIKA_CDP_PORT',
|
|
21
|
+
'REIKA_DEBUG_FILE',
|
|
22
|
+
]);
|
|
23
|
+
export function isDeniedFromProjectEnv(key) {
|
|
24
|
+
// Every endpoint and key, including REIKA_<NAME>_BASE_URL for a profile the global file defines.
|
|
25
|
+
return PROJECT_ENV_DENIED.has(key) || /_(URL|API_KEY)$/.test(key);
|
|
26
|
+
}
|
|
27
|
+
// Returns the denied keys that would otherwise have taken effect, for the startup notice.
|
|
28
|
+
export function applyProjectEnv(text, env) {
|
|
29
|
+
const ignored = [];
|
|
30
|
+
for (const [key, value] of Object.entries(dotenv.parse(text))) {
|
|
31
|
+
if (!key.startsWith('REIKA_') || key in env)
|
|
32
|
+
continue;
|
|
33
|
+
if (isDeniedFromProjectEnv(key))
|
|
34
|
+
ignored.push(key);
|
|
35
|
+
else
|
|
36
|
+
env[key] = value;
|
|
37
|
+
}
|
|
38
|
+
return ignored;
|
|
39
|
+
}
|
|
40
|
+
export function projectEnvNotice(ignored) {
|
|
41
|
+
if (ignored.length === 0)
|
|
42
|
+
return undefined;
|
|
43
|
+
return `Ignored ${ignored.join(', ')} from ./.env: settings for the sandbox, approvals, endpoints, keys and MCP servers are read only from your shell or ~/.config/reika/.env.`;
|
|
44
|
+
}
|
|
45
|
+
function readTextOrEmpty(path) {
|
|
46
|
+
try {
|
|
47
|
+
return readFileSync(path, 'utf8');
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return '';
|
|
51
|
+
}
|
|
52
|
+
}
|
|
6
53
|
// Precedence: shell env > cwd .env > ~/.config/reika/.env
|
|
7
|
-
//
|
|
54
|
+
// Neither file overrides a key already set, so loading cwd first then global gives the right order.
|
|
8
55
|
// The keys already present before dotenv runs are the ones set at launch (`REIKA_X=1 reika`, or an
|
|
9
56
|
// export in the shell rc); the persisted session state (#365) defers to those and beats the files.
|
|
10
57
|
const launchEnvKeys = new Set(Object.keys(process.env));
|
|
11
|
-
|
|
58
|
+
const ignoredProjectEnvKeys = applyProjectEnv(readTextOrEmpty(join(process.cwd(), '.env')), process.env);
|
|
12
59
|
dotenv.config({ path: join(homedir(), '.config', 'reika', '.env') });
|
|
13
60
|
export function setAtLaunch(name) {
|
|
14
61
|
return launchEnvKeys.has(name);
|
|
@@ -88,6 +135,7 @@ export function loadConfig() {
|
|
|
88
135
|
cdpPort: parseIntOrUndef(process.env.REIKA_CDP_PORT),
|
|
89
136
|
profiles,
|
|
90
137
|
...parseModeModels(process.env.REIKA_MODE_MODELS, profiles, models),
|
|
138
|
+
projectEnvNotice: projectEnvNotice(ignoredProjectEnvKeys),
|
|
91
139
|
maxSearchesPerTurn: parseInt(process.env.REIKA_MAX_SEARCHES_PER_TURN ?? '3', 10),
|
|
92
140
|
maxFetchesPerTurn: parseInt(process.env.REIKA_MAX_FETCHES_PER_TURN ?? '5', 10),
|
|
93
141
|
bashTimeoutMs: parseInt(process.env.REIKA_BASH_TIMEOUT_MS ?? '1800000', 10),
|
package/dist/headless.js
CHANGED
|
@@ -110,6 +110,8 @@ export async function runHeadless(args, io) {
|
|
|
110
110
|
// The same startup line the TUI shows for a REIKA_MODE_MODELS entry it could not use (#616).
|
|
111
111
|
for (const problem of config.modeModelErrors ?? [])
|
|
112
112
|
io.stderr(`reika: ${problem}\n`);
|
|
113
|
+
if (config.projectEnvNotice)
|
|
114
|
+
io.stderr(`reika: ${config.projectEnvNotice}\n`);
|
|
113
115
|
// An MCP tool typed as a slash command (#265): the same direct call the TUI makes, answered with
|
|
114
116
|
// the tool's own output instead of a model turn. There is no question for the model to answer —
|
|
115
117
|
// the user named the tool and its arguments — so this runs before any prompt is built.
|
package/dist/tools/_danger.js
CHANGED
|
@@ -10,7 +10,7 @@ import { existsSync } from 'node:fs';
|
|
|
10
10
|
import { homedir } from 'node:os';
|
|
11
11
|
import { dirname, join, resolve } from 'node:path';
|
|
12
12
|
import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
|
|
13
|
-
import { stripHeredocs } from './
|
|
13
|
+
import { stripHeredocs } from './_heredoc.js';
|
|
14
14
|
import { maskMarkdownData } from './_markdown.js';
|
|
15
15
|
// Workflow-policy commands: not destructive (a commit is local and reversible, a push is
|
|
16
16
|
// recoverable), but they record or publish work, and the user generally wants to stay in the
|
|
@@ -0,0 +1,405 @@
|
|
|
1
|
+
// Heredocs, as one notion shared by every question that asks about them (#685). The readers used to
|
|
2
|
+
// be three regexes (here, `_markdown.ts`, `bash.ts`), each with its own idea of where an operator
|
|
3
|
+
// is and where a body ends, and every disagreement between a regex and the shell was a hole in
|
|
4
|
+
// whichever direction the caller was not guarding: a body read too SHORT leaves its lines to be
|
|
5
|
+
// parsed as commands (over-denies), a body read too LONG hides the real commands after it — and for
|
|
6
|
+
// the verb readers (`networkDecision`, `detectDangerousPatterns`) a hidden command is one that
|
|
7
|
+
// keeps the network or skips its prompt. So this is a lexer, not a pattern: it walks the command the
|
|
8
|
+
// way `/bin/sh` does, far enough to know which `<<` the shell parses as an operator and which lines
|
|
9
|
+
// it then reads as body.
|
|
10
|
+
//
|
|
11
|
+
// stripHeredocs / expandingHeredocBodies — the text with every body cut, for the verb readers, and
|
|
12
|
+
// the bodies the shell still expands, for the substitution question (#163, #278).
|
|
13
|
+
// hasHeredocOperator — may this text hold a heredoc body at all? `maskSingleQuotedData` asks it
|
|
14
|
+
// before trusting a quote mask: a body is not quote-parsed, so an apostrophe in one pairs with
|
|
15
|
+
// the next and blanks a `$(…)` that really runs.
|
|
16
|
+
// scanHeredocs — the spans themselves, for `_markdown.ts` (which blanks bodies in place) and the
|
|
17
|
+
// `bash.ts` hint (which asks whether one sits inside a `$(…)`).
|
|
18
|
+
// scanQuotes — the quoting REGIONS of the same walk, for `_readonly.ts`'s two masks (#695). It is
|
|
19
|
+
// the same read of the same text: what the shell calls quoted data here is what the heredoc
|
|
20
|
+
// readers skip as text there, which is why it is one walk and not a second idea of quoting.
|
|
21
|
+
//
|
|
22
|
+
// What the lexer follows, each one a way a regex had disagreed with the shell:
|
|
23
|
+
// - quoting and escapes: a `<<` inside quotes is text, and `\<<<EOF` is a literal `<` and then a
|
|
24
|
+
// real `<<EOF` — the operator is a run of `<` the shell itself splits, never a substring;
|
|
25
|
+
// - the run: exactly two `<` open a heredoc, three a here-string (whose operand IS quote-parsed),
|
|
26
|
+
// and a longer run is a syntax error, which nothing runs past;
|
|
27
|
+
// - the delimiter is the whole shell WORD after the operator, with its quotes and backslashes
|
|
28
|
+
// removed (`<<"EOF"x` ends at `EOFx`, `<<END-X` at `END-X`);
|
|
29
|
+
// - the terminator is a line that is EXACTLY the delimiter — leading tabs allowed only for `<<-`,
|
|
30
|
+
// trailing whitespace never — plus bash's own extension inside a `$(…)`, where `EOF)` closes
|
|
31
|
+
// both (macOS `/bin/sh` is bash 3.2; zsh and dash reject that shape);
|
|
32
|
+
// - comments, `$((…))` and `((…))`: a `<<` in a comment is text, and in arithmetic it is a shift.
|
|
33
|
+
//
|
|
34
|
+
// Anything the lexer cannot read exactly sets `uncertain`, and every export fails closed on it: the
|
|
35
|
+
// guard fires, nothing is stripped (body lines stay in front of the verb readers, which over-deny),
|
|
36
|
+
// and the whole command counts as an expanding body (which the raw substitution test then reads).
|
|
37
|
+
// What ends an unquoted shell word — and so also what lets a `#` after it open a comment.
|
|
38
|
+
const WORD_END_RE = /[\s;&|<>()]/;
|
|
39
|
+
export function scanHeredocs(command) {
|
|
40
|
+
const heredocs = [];
|
|
41
|
+
const quotes = [];
|
|
42
|
+
let unclosedQuote = false;
|
|
43
|
+
let ambiguousQuote = false;
|
|
44
|
+
let uncertain = false;
|
|
45
|
+
const stack = [{ kind: 'top', parens: 0 }];
|
|
46
|
+
let pending = [];
|
|
47
|
+
const n = command.length;
|
|
48
|
+
let i = 0;
|
|
49
|
+
const innermostCloser = () => {
|
|
50
|
+
for (let k = stack.length - 1; k >= 0; k--) {
|
|
51
|
+
if (stack[k].kind === 'sub')
|
|
52
|
+
return ')';
|
|
53
|
+
if (stack[k].kind === 'tick')
|
|
54
|
+
return '`';
|
|
55
|
+
}
|
|
56
|
+
return undefined;
|
|
57
|
+
};
|
|
58
|
+
while (i < n) {
|
|
59
|
+
const frame = stack[stack.length - 1];
|
|
60
|
+
const ch = command[i];
|
|
61
|
+
if (frame.kind === 'dq') {
|
|
62
|
+
if (ch === '\\')
|
|
63
|
+
i += 2;
|
|
64
|
+
else if (ch === '"') {
|
|
65
|
+
stack.pop();
|
|
66
|
+
if (frame.quoteAt !== undefined) {
|
|
67
|
+
quotes.push({ start: frame.quoteAt, end: i + 1, kind: 'double' });
|
|
68
|
+
}
|
|
69
|
+
i++;
|
|
70
|
+
}
|
|
71
|
+
else if (ch === '`') {
|
|
72
|
+
stack.push({ kind: 'tick', parens: 0 });
|
|
73
|
+
i++;
|
|
74
|
+
}
|
|
75
|
+
else if (ch === '$' && command[i + 1] === '(') {
|
|
76
|
+
const arith = command[i + 2] === '(';
|
|
77
|
+
stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
|
|
78
|
+
i += arith ? 3 : 2;
|
|
79
|
+
}
|
|
80
|
+
else
|
|
81
|
+
i++;
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
if (frame.kind === 'arith') {
|
|
85
|
+
// A shift, not an operator — but `$((` can also be a `$(` holding a subshell, and the lexer
|
|
86
|
+
// does not decide which, so a `<<` here is the one thing it cannot read exactly.
|
|
87
|
+
if (ch === '<' && command[i + 1] === '<') {
|
|
88
|
+
uncertain = true;
|
|
89
|
+
i += 2;
|
|
90
|
+
}
|
|
91
|
+
else if (ch === '(') {
|
|
92
|
+
frame.parens++;
|
|
93
|
+
i++;
|
|
94
|
+
}
|
|
95
|
+
else if (ch === ')') {
|
|
96
|
+
if (frame.parens > 0) {
|
|
97
|
+
frame.parens--;
|
|
98
|
+
i++;
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
stack.pop();
|
|
102
|
+
i += command[i + 1] === ')' ? 2 : 1;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
else
|
|
106
|
+
i++;
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
// A command context: the top level, a `$(…)`, a backtick or a process substitution.
|
|
110
|
+
if (ch === '\\') {
|
|
111
|
+
i += 2;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (ch === "'") {
|
|
115
|
+
const close = command.indexOf("'", i + 1);
|
|
116
|
+
if (close === -1) {
|
|
117
|
+
// An unterminated quote is a syntax error: nothing runs. The lexer stops with it, and says
|
|
118
|
+
// so — the mask callers must not fill in the rest by guessing.
|
|
119
|
+
unclosedQuote = true;
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
quotes.push({ start: i, end: close + 1, kind: 'single' });
|
|
123
|
+
i = close + 1;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (ch === '$' && command[i + 1] === "'") {
|
|
127
|
+
// ANSI-C quoting, the one single-quoted form a backslash escapes inside.
|
|
128
|
+
let j = i + 2;
|
|
129
|
+
while (j < n && command[j] !== "'")
|
|
130
|
+
j += command[j] === '\\' ? 2 : 1;
|
|
131
|
+
// dash, `/bin/sh` on Debian/Ubuntu, has no `$'…'`: it reads `$` and then a plain `'…'`
|
|
132
|
+
// closed by the FIRST `'`. Where an escaped quote makes the two closes differ, the text after
|
|
133
|
+
// it is a command in one shell and data in the other, and `bash` runs `/bin/sh -c`.
|
|
134
|
+
if (command.indexOf("'", i + 2) !== (j < n ? j : -1)) {
|
|
135
|
+
ambiguousQuote = true;
|
|
136
|
+
uncertain = true;
|
|
137
|
+
}
|
|
138
|
+
if (j >= n) {
|
|
139
|
+
unclosedQuote = true;
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
quotes.push({ start: i, end: j + 1, kind: 'ansi' });
|
|
143
|
+
i = j + 1;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (ch === '"') {
|
|
147
|
+
stack.push({ kind: 'dq', parens: 0, quoteAt: i });
|
|
148
|
+
i++;
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (ch === '`') {
|
|
152
|
+
if (frame.kind === 'tick')
|
|
153
|
+
stack.pop();
|
|
154
|
+
else
|
|
155
|
+
stack.push({ kind: 'tick', parens: 0 });
|
|
156
|
+
i++;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
if (ch === '$' && command[i + 1] === '(') {
|
|
160
|
+
const arith = command[i + 2] === '(';
|
|
161
|
+
stack.push({ kind: arith ? 'arith' : 'sub', parens: 0 });
|
|
162
|
+
i += arith ? 3 : 2;
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (ch === '#' && (i === 0 || WORD_END_RE.test(command[i - 1]))) {
|
|
166
|
+
const nl = command.indexOf('\n', i);
|
|
167
|
+
i = nl === -1 ? n : nl;
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (ch === '(') {
|
|
171
|
+
if (command[i + 1] === '(' && (i === 0 || WORD_END_RE.test(command[i - 1]))) {
|
|
172
|
+
stack.push({ kind: 'arith', parens: 0 });
|
|
173
|
+
i += 2;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
frame.parens++;
|
|
177
|
+
i++;
|
|
178
|
+
}
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
if (ch === ')') {
|
|
182
|
+
if (frame.parens > 0)
|
|
183
|
+
frame.parens--;
|
|
184
|
+
else if (frame.kind === 'sub')
|
|
185
|
+
stack.pop();
|
|
186
|
+
i++;
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
if ((ch === '<' || ch === '>') && command[i + 1] === '(') {
|
|
190
|
+
// Process substitution runs a command of its own, with its own heredocs.
|
|
191
|
+
stack.push({ kind: 'sub', parens: 0 });
|
|
192
|
+
i += 2;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
if (ch === '<') {
|
|
196
|
+
let run = 0;
|
|
197
|
+
while (command[i + run] === '<')
|
|
198
|
+
run++;
|
|
199
|
+
if (run === 3) {
|
|
200
|
+
i += 3;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (run !== 2) {
|
|
204
|
+
// `<` is a redirect; four or more is a syntax error the lexer does not try to split.
|
|
205
|
+
if (run > 3)
|
|
206
|
+
uncertain = true;
|
|
207
|
+
i += run;
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
let j = i + 2;
|
|
211
|
+
const dash = command[j] === '-';
|
|
212
|
+
if (dash)
|
|
213
|
+
j++;
|
|
214
|
+
while (command[j] === ' ' || command[j] === '\t')
|
|
215
|
+
j++;
|
|
216
|
+
const word = readDelimiterWord(command, j);
|
|
217
|
+
if (!word) {
|
|
218
|
+
uncertain = true;
|
|
219
|
+
i = j;
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
pending.push({
|
|
223
|
+
opAt: i,
|
|
224
|
+
wordEnd: word.end,
|
|
225
|
+
delimiter: word.delimiter,
|
|
226
|
+
literal: word.literal,
|
|
227
|
+
dash,
|
|
228
|
+
inSubstitution: innermostCloser() !== undefined,
|
|
229
|
+
closer: innermostCloser(),
|
|
230
|
+
depth: stack.length,
|
|
231
|
+
});
|
|
232
|
+
i = word.end;
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (ch === '\n' && pending.length > 0) {
|
|
236
|
+
let pos = i + 1;
|
|
237
|
+
for (const p of pending) {
|
|
238
|
+
if (p.depth !== stack.length)
|
|
239
|
+
uncertain = true;
|
|
240
|
+
const body = readBody(command, pos, p);
|
|
241
|
+
heredocs.push({
|
|
242
|
+
...pendingFields(p),
|
|
243
|
+
bodyStart: pos,
|
|
244
|
+
bodyEnd: body.bodyEnd,
|
|
245
|
+
end: body.end,
|
|
246
|
+
});
|
|
247
|
+
pos = body.end;
|
|
248
|
+
}
|
|
249
|
+
pending = [];
|
|
250
|
+
i = pos;
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
i++;
|
|
254
|
+
}
|
|
255
|
+
// An operator whose line never ended has no body — the shell reads none — but it is still an
|
|
256
|
+
// operator, so the guard fires on it and the strip still takes its delimiter word.
|
|
257
|
+
for (const p of pending)
|
|
258
|
+
heredocs.push({ ...pendingFields(p), bodyStart: n, bodyEnd: n, end: n });
|
|
259
|
+
// A double quote still open at the end never closed. The other frames (`$(…)`, a backtick,
|
|
260
|
+
// arithmetic) do not matter here: the text inside them is quote-parsed the same way whether or not
|
|
261
|
+
// the `)` ever arrives, so the spans read there are good either way.
|
|
262
|
+
if (stack.some(f => f.kind === 'dq'))
|
|
263
|
+
unclosedQuote = true;
|
|
264
|
+
return { heredocs, quotes, unclosedQuote, ambiguousQuote, uncertain };
|
|
265
|
+
}
|
|
266
|
+
function pendingFields(p) {
|
|
267
|
+
return {
|
|
268
|
+
opAt: p.opAt,
|
|
269
|
+
wordEnd: p.wordEnd,
|
|
270
|
+
delimiter: p.delimiter,
|
|
271
|
+
literal: p.literal,
|
|
272
|
+
inSubstitution: p.inSubstitution,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
// The delimiter WORD, with quote removal done the way the shell does it. `literal` is true only for a
|
|
276
|
+
// quote: all four shells measured (sh, bash, dash, zsh) also make a `<<\EOF` body literal, since a
|
|
277
|
+
// backslash quotes a character of the word, but reading it as expanding is the fail-closed side —
|
|
278
|
+
// it costs a local read (`git apply -`, `hash-object --stdin`) a network allow it did not need,
|
|
279
|
+
// where the other side would hand a `$(…)` in that body the network if any shell disagreed. A
|
|
280
|
+
// substitution in the word is not expanded by the shell either, but where its `)` falls is the
|
|
281
|
+
// lexer's guess, so that word is not read at all.
|
|
282
|
+
function readDelimiterWord(command, start) {
|
|
283
|
+
let delimiter = '';
|
|
284
|
+
let literal = false;
|
|
285
|
+
let j = start;
|
|
286
|
+
while (j < command.length && !WORD_END_RE.test(command[j])) {
|
|
287
|
+
const ch = command[j];
|
|
288
|
+
if (ch === '\\') {
|
|
289
|
+
if (j + 1 >= command.length || command[j + 1] === '\n')
|
|
290
|
+
return undefined;
|
|
291
|
+
delimiter += command[j + 1];
|
|
292
|
+
j += 2;
|
|
293
|
+
}
|
|
294
|
+
else if (ch === "'") {
|
|
295
|
+
const close = command.indexOf("'", j + 1);
|
|
296
|
+
if (close === -1)
|
|
297
|
+
return undefined;
|
|
298
|
+
delimiter += command.slice(j + 1, close);
|
|
299
|
+
literal = true;
|
|
300
|
+
j = close + 1;
|
|
301
|
+
}
|
|
302
|
+
else if (ch === '"') {
|
|
303
|
+
let k = j + 1;
|
|
304
|
+
while (k < command.length && command[k] !== '"') {
|
|
305
|
+
if (command[k] === '\\' && /["\\$`]/.test(command[k + 1] ?? ''))
|
|
306
|
+
k++;
|
|
307
|
+
delimiter += command[k];
|
|
308
|
+
k++;
|
|
309
|
+
}
|
|
310
|
+
if (k >= command.length)
|
|
311
|
+
return undefined;
|
|
312
|
+
literal = true;
|
|
313
|
+
j = k + 1;
|
|
314
|
+
}
|
|
315
|
+
else if (ch === '`' || (ch === '$' && command[j + 1] === '(')) {
|
|
316
|
+
return undefined;
|
|
317
|
+
}
|
|
318
|
+
else {
|
|
319
|
+
delimiter += ch;
|
|
320
|
+
j++;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if (j === start || delimiter === '')
|
|
324
|
+
return undefined;
|
|
325
|
+
return { delimiter, literal, end: j };
|
|
326
|
+
}
|
|
327
|
+
function readBody(command, start, p) {
|
|
328
|
+
let pos = start;
|
|
329
|
+
while (pos < command.length) {
|
|
330
|
+
const nl = command.indexOf('\n', pos);
|
|
331
|
+
const lineEnd = nl === -1 ? command.length : nl;
|
|
332
|
+
const line = command.slice(pos, lineEnd);
|
|
333
|
+
const tabs = p.dash ? (/^\t*/.exec(line)?.[0].length ?? 0) : 0;
|
|
334
|
+
const text = line.slice(tabs);
|
|
335
|
+
if (text === p.delimiter)
|
|
336
|
+
return { bodyEnd: pos, end: nl === -1 ? lineEnd : nl + 1 };
|
|
337
|
+
// bash closes a heredoc at `EOF)` inside a `$(…)` (and `EOF\`` inside backticks); the closer is
|
|
338
|
+
// left for the lexer to close the substitution with.
|
|
339
|
+
if (p.closer && text.startsWith(p.delimiter + p.closer)) {
|
|
340
|
+
return { bodyEnd: pos, end: pos + tabs + p.delimiter.length };
|
|
341
|
+
}
|
|
342
|
+
pos = lineEnd + 1;
|
|
343
|
+
}
|
|
344
|
+
return { bodyEnd: command.length, end: command.length };
|
|
345
|
+
}
|
|
346
|
+
export function hasHeredocOperator(command) {
|
|
347
|
+
return heredocOperatorIn(scanHeredocs(command));
|
|
348
|
+
}
|
|
349
|
+
function heredocOperatorIn(scan) {
|
|
350
|
+
return scan.uncertain || scan.heredocs.length > 0;
|
|
351
|
+
}
|
|
352
|
+
// The quoting regions of a command, for the length-preserving masks in `_readonly.ts` (#695). Same
|
|
353
|
+
// walk as `scanHeredocs`, because the two questions are the same read: a region this call reports as
|
|
354
|
+
// quoted data is one the heredoc readers skip as text (`$'…'`, a quoted delimiter, prose in a
|
|
355
|
+
// double-quoted `--body`), and a region it reports nothing about is one the shell parses as commands.
|
|
356
|
+
//
|
|
357
|
+
// `uncertain` is the quoting walk's own doubt — an unterminated quote, or a `$'…'` bash and dash
|
|
358
|
+
// close at different quotes — not `HeredocScan.uncertain`. Everything that makes the heredoc half
|
|
359
|
+
// unsure (a `<<` in arithmetic, a run of four `<`, a delimiter word it cannot read) is about `<`, and
|
|
360
|
+
// folding it in would refuse the mask over a `<<` that has nothing to do with quoting. That is not a
|
|
361
|
+
// claim the walk reads such text correctly: after an unreadable delimiter it quote-parses a body the
|
|
362
|
+
// shell does not. What keeps that from hiding a command today is that a stray quote in the body
|
|
363
|
+
// leaves the walk unclosed, so the mask blanks nothing — a mask that trusted a partial walk would
|
|
364
|
+
// lose that.
|
|
365
|
+
export function scanQuotes(command) {
|
|
366
|
+
const scan = scanHeredocs(command);
|
|
367
|
+
return {
|
|
368
|
+
spans: scan.quotes,
|
|
369
|
+
uncertain: scan.unclosedQuote || scan.ambiguousQuote,
|
|
370
|
+
heredocOperator: heredocOperatorIn(scan),
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
// The command with each heredoc's operator, delimiter word, body and terminator line cut, and the
|
|
374
|
+
// rest of the operator's line kept — `cat <<EOF > out.md` still writes `out.md`, and
|
|
375
|
+
// `… <<EOF && curl x` still runs `curl`, which a cut through to the body's end used to hide. Also
|
|
376
|
+
// read by the sandbox's network classifier (#163): a body's lines would otherwise split into
|
|
377
|
+
// segments whose "verb" is prose, denying `gh issue comment --body-file - <<EOF …`.
|
|
378
|
+
export function stripHeredocs(command) {
|
|
379
|
+
const scan = scanHeredocs(command);
|
|
380
|
+
if (scan.uncertain)
|
|
381
|
+
return command;
|
|
382
|
+
const cuts = scan.heredocs.flatMap(h => [
|
|
383
|
+
[h.opAt, h.wordEnd],
|
|
384
|
+
[h.bodyStart, h.end],
|
|
385
|
+
]);
|
|
386
|
+
cuts.sort((a, b) => b[0] - a[0]);
|
|
387
|
+
let s = command;
|
|
388
|
+
for (const [from, to] of cuts)
|
|
389
|
+
s = s.slice(0, from) + s.slice(to);
|
|
390
|
+
return s;
|
|
391
|
+
}
|
|
392
|
+
// The heredoc bodies the shell EXPANDS, which `stripHeredocs` cuts away with the rest: `$…` and a
|
|
393
|
+
// backtick in a body are only data when the delimiter was quoted, so `<<EOF` runs what `<<'EOF'`
|
|
394
|
+
// pastes. Cutting them answers the verb question correctly and the substitution question wrongly,
|
|
395
|
+
// because a `$(…)` in an expanding body DOES run, with whatever network the line's `git`/`gh` verb
|
|
396
|
+
// was granted — so the caller re-reads these. The newline before the terminator ends the body
|
|
397
|
+
// rather than belonging to it.
|
|
398
|
+
export function expandingHeredocBodies(command) {
|
|
399
|
+
const scan = scanHeredocs(command);
|
|
400
|
+
if (scan.uncertain)
|
|
401
|
+
return [command];
|
|
402
|
+
return scan.heredocs
|
|
403
|
+
.filter(h => !h.literal && h.bodyEnd > h.bodyStart)
|
|
404
|
+
.map(h => command.slice(h.bodyStart, h.bodyEnd).replace(/\n$/, ''));
|
|
405
|
+
}
|
package/dist/tools/_markdown.js
CHANGED
|
@@ -22,9 +22,8 @@
|
|
|
22
22
|
// verbatim and the ordinary scan still answers for them. That is the same rule `_sandbox.ts` applies
|
|
23
23
|
// to heredoc bodies (data for the verb question, re-read for the substitution one), narrowed here to
|
|
24
24
|
// text we can name as Markdown.
|
|
25
|
+
import { scanHeredocs } from './_heredoc.js';
|
|
25
26
|
import { maskQuoted } from './_readonly.js';
|
|
26
|
-
// Matched exactly as `_writetargets.ts` matches it: `<<EOF`, `<<-EOF`, `<<'EOF'`, `<<"EOF"`.
|
|
27
|
-
const HEREDOC_OP_RE = /<<-?\s*(['"]?)(\w+)\1/g;
|
|
28
27
|
// The extensions that make a written file Markdown. `mdx` rides along because it is read as
|
|
29
28
|
// Markdown with JSX in it; a component file is not what this is for, and a false negative there
|
|
30
29
|
// costs one missed label on an uncommon shape.
|
|
@@ -76,51 +75,21 @@ export function maskMarkdownData(command) {
|
|
|
76
75
|
// Heredoc bodies whose segment writes Markdown. The operator's own segment is what decides, not the
|
|
77
76
|
// line: two heredocs on one line are two different commands more often than they are one.
|
|
78
77
|
function heredocRegions(command) {
|
|
79
|
-
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
// does not start one).
|
|
78
|
+
// The operators come off the RAW command and the segments off the quote mask, because
|
|
79
|
+
// `gh pr create --body "$(cat <<'EOF' … EOF)"` puts the operator INSIDE the double-quoted value the
|
|
80
|
+
// mask blanks. Which `<<` is live — never one in quoted prose (`--title 'use <<EOF'`), always one
|
|
81
|
+
// inside a `$(…)` — is `scanHeredocs`' answer, the same one the sandbox and the danger scan get.
|
|
82
|
+
// A scan it cannot read exactly blanks nothing: the danger labels then over-report, never hide.
|
|
83
|
+
const scan = scanHeredocs(command);
|
|
84
|
+
if (scan.uncertain)
|
|
85
|
+
return [];
|
|
88
86
|
const view = maskQuoted(command);
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
// offsets, and a tail it mutates while another pass is still reading it is a bug waiting to
|
|
93
|
-
// happen (a second heredoc's operator lands inside the first body's hole and the scan never
|
|
94
|
-
// resumes — measured, and it silently turned the rule off for everything after the first heredoc).
|
|
95
|
-
const spans = [];
|
|
96
|
-
for (const m of command.matchAll(HEREDOC_OP_RE)) {
|
|
97
|
-
// A `<<` the shell treats as literal text is not an operator — never in a plain quoted string
|
|
98
|
-
// (`echo 'see <<EOF here' > NOTES.md` writes a sentence) and never in a single-quoted run at
|
|
99
|
-
// all. Only inside a `$( )` or backtick substitution does a quoted `<<` start a real heredoc.
|
|
100
|
-
// Reading a literal one as an operator manufactures a body that swallows real commands on the
|
|
101
|
-
// following lines — measured: `echo 'docs say <<EOF' > NOTES.md\nrm -rf /x` went unflagged.
|
|
102
|
-
if (!heredocOperatorIsLive(command, m.index))
|
|
103
|
-
continue;
|
|
104
|
-
const bodyStart = command.indexOf('\n', m.index);
|
|
105
|
-
if (bodyStart === -1)
|
|
106
|
-
break;
|
|
107
|
-
const endRe = new RegExp(`^\\s*${m[2]}\\s*$`, 'm');
|
|
108
|
-
const rest = command.slice(bodyStart + 1);
|
|
109
|
-
const end = endRe.exec(rest);
|
|
110
|
-
spans.push({
|
|
111
|
-
start: bodyStart + 1,
|
|
112
|
-
end: bodyStart + 1 + (end ? end.index : rest.length),
|
|
113
|
-
opAt: m.index,
|
|
114
|
-
quoted: m[1] !== '',
|
|
115
|
-
});
|
|
116
|
-
if (spans.some(s2 => bodyStart + 1 > s2.start && bodyStart + 1 < s2.end))
|
|
117
|
-
break;
|
|
118
|
-
}
|
|
119
|
-
for (const span of spans) {
|
|
120
|
-
const seg = segmentAt(command, view, span.opAt);
|
|
87
|
+
const out = [];
|
|
88
|
+
for (const h of scan.heredocs) {
|
|
89
|
+
const seg = segmentAt(command, view, h.opAt);
|
|
121
90
|
if (!seg || !isMarkdownSegment(seg.text))
|
|
122
91
|
continue;
|
|
123
|
-
out.push({ start:
|
|
92
|
+
out.push({ start: h.bodyStart, end: h.bodyEnd, expands: !h.literal });
|
|
124
93
|
}
|
|
125
94
|
return out;
|
|
126
95
|
}
|
|
@@ -266,67 +235,6 @@ function isMarkdownSegment(seg) {
|
|
|
266
235
|
function unquote(word) {
|
|
267
236
|
return word.replace(/['"]/g, '');
|
|
268
237
|
}
|
|
269
|
-
// The quoted runs of the command, paired EXACTLY as `maskQuoted` pairs them (same regex), so the
|
|
270
|
-
// question "is this offset inside a quoted string?" has one answer across this file.
|
|
271
|
-
const QUOTED_RUN_RE = /"[^"]*"|'[^']*'/g;
|
|
272
|
-
function quotedRunAt(command, at) {
|
|
273
|
-
for (const m of command.matchAll(QUOTED_RUN_RE)) {
|
|
274
|
-
const start = m.index ?? 0;
|
|
275
|
-
if (at >= start && at < start + m[0].length)
|
|
276
|
-
return { start, end: start + m[0].length };
|
|
277
|
-
}
|
|
278
|
-
return undefined;
|
|
279
|
-
}
|
|
280
|
-
// Whether the shell parses the `<<` at `at` as a heredoc operator. Outside quotes it always does.
|
|
281
|
-
// A single-quoted run is literal all the way through — even `$( )` in it does not expand. Inside a
|
|
282
|
-
// double-quoted run the `<<` is literal text UNLESS it sits in a `$( )` or backtick substitution,
|
|
283
|
-
// where the substituted text is parsed as a command again (`--body "$(cat <<'EOF' …)"` is the
|
|
284
|
-
// common shape). An unterminated `$(`/backtick still counts as live: either the whole command is a
|
|
285
|
-
// parse error (nothing runs, so blanking the body costs nothing) or the closer is past a heredoc
|
|
286
|
-
// body's unbalanced quote — and there the body is real data that SHOULD be blanked.
|
|
287
|
-
function heredocOperatorIsLive(command, at) {
|
|
288
|
-
const run = quotedRunAt(command, at);
|
|
289
|
-
if (!run)
|
|
290
|
-
return true;
|
|
291
|
-
if (command[run.start] === "'")
|
|
292
|
-
return false;
|
|
293
|
-
let inSub = 0;
|
|
294
|
-
let inSingle = false;
|
|
295
|
-
let inBacktick = false;
|
|
296
|
-
for (let i = run.start + 1; i < at; i++) {
|
|
297
|
-
const ch = command[i];
|
|
298
|
-
if (inSingle) {
|
|
299
|
-
if (ch === "'")
|
|
300
|
-
inSingle = false;
|
|
301
|
-
continue;
|
|
302
|
-
}
|
|
303
|
-
if (inBacktick) {
|
|
304
|
-
if (ch === '`')
|
|
305
|
-
inBacktick = false;
|
|
306
|
-
continue;
|
|
307
|
-
}
|
|
308
|
-
if (ch === '\\') {
|
|
309
|
-
i++;
|
|
310
|
-
continue;
|
|
311
|
-
}
|
|
312
|
-
if (inSub > 0 && ch === "'") {
|
|
313
|
-
inSingle = true;
|
|
314
|
-
continue;
|
|
315
|
-
}
|
|
316
|
-
if (ch === '`') {
|
|
317
|
-
inBacktick = true;
|
|
318
|
-
continue;
|
|
319
|
-
}
|
|
320
|
-
if (ch === '$' && command[i + 1] === '(') {
|
|
321
|
-
inSub++;
|
|
322
|
-
i++;
|
|
323
|
-
continue;
|
|
324
|
-
}
|
|
325
|
-
if (ch === ')' && inSub > 0)
|
|
326
|
-
inSub--;
|
|
327
|
-
}
|
|
328
|
-
return inSub > 0 || inBacktick;
|
|
329
|
-
}
|
|
330
238
|
// Blank a stretch of data, keeping the newlines (so line-based parsers downstream see the same
|
|
331
239
|
// shape) and — only where the shell still expands them — the substitutions inside it.
|
|
332
240
|
function blankData(text, expands) {
|
package/dist/tools/_readonly.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { scanQuotes } from './_heredoc.js';
|
|
1
2
|
// Shell commands that only READ — asked as TWO questions, because the two callers pull in opposite
|
|
2
3
|
// directions and collapsing them costs whichever one is on the losing side.
|
|
3
4
|
//
|
|
@@ -147,49 +148,50 @@ const SUBSTITUTION_RE = /\$\(|`|<\(|>\(/;
|
|
|
147
148
|
function dropEscapedSubstitutionChars(raw) {
|
|
148
149
|
return raw.replace(/\\\\/g, '').replace(/\\[`$]/g, '');
|
|
149
150
|
}
|
|
151
|
+
// Blank the ranges a caller asks for, preserving length and everything else. Spans nest (a `'…'`
|
|
152
|
+
// inside a `$(…)` inside a `"…"`), so they are sorted and merged first and the string is built once:
|
|
153
|
+
// rebuilding it per span was quadratic, and a long `python3 -c` carries thousands of quoted words.
|
|
154
|
+
function blankSpans(command, spans, take) {
|
|
155
|
+
const ranges = spans.filter(take).sort((a, b) => a.start - b.start);
|
|
156
|
+
let out = '';
|
|
157
|
+
let pos = 0;
|
|
158
|
+
for (const r of ranges) {
|
|
159
|
+
if (r.end <= pos)
|
|
160
|
+
continue;
|
|
161
|
+
const start = Math.max(r.start, pos);
|
|
162
|
+
out += command.slice(pos, start) + ' '.repeat(r.end - start);
|
|
163
|
+
pos = r.end;
|
|
164
|
+
}
|
|
165
|
+
return out + command.slice(pos);
|
|
166
|
+
}
|
|
150
167
|
// What a substitution check should actually read: the command with the regions where a `$(` or a
|
|
151
168
|
// backtick is DATA blanked out, length-preserving so any offset taken against it still lines up.
|
|
152
169
|
// Two contexts blank, one refuses to answer:
|
|
153
170
|
//
|
|
154
|
-
// - inside SINGLE quotes (a `'` opens the run, the next `'` closes it
|
|
155
|
-
//
|
|
156
|
-
//
|
|
171
|
+
// - inside SINGLE quotes, including the `$'…'` form (a `'` opens the run, the next `'` closes it,
|
|
172
|
+
// and the lexer knows a `\'` outside them is a literal quote rather than an opener): `grep -c
|
|
173
|
+
// '```'` is a pattern, not a command. Double-quoted runs are skipped over rather than blanked, so
|
|
174
|
+
// an apostrophe in prose (`echo "it's $(curl evil)"`) cannot be mistaken for an opening quote and
|
|
157
175
|
// swallow the substitution beside it.
|
|
158
|
-
// - NOTHING when a
|
|
159
|
-
// expands unless the delimiter was quoted — so an apostrophe inside one (`it's`)
|
|
160
|
-
// the next and blank a command that runs. The delimiter's own quoting is what
|
|
161
|
-
// is `
|
|
162
|
-
// caller reads as "test the raw string" and denies as it does today.
|
|
176
|
+
// - NOTHING when a heredoc OPERATOR is in the text. A heredoc body is not quote-parsed at all —
|
|
177
|
+
// its `$(…)` expands unless the delimiter was quoted — so an apostrophe inside one (`it's`)
|
|
178
|
+
// would pair with the next and blank a command that runs. The delimiter's own quoting is what
|
|
179
|
+
// decides, and that is `_heredoc.ts`'s question, not this one: an unclear heredoc means no
|
|
180
|
+
// blanking, which the caller reads as "test the raw string" and denies as it does today.
|
|
163
181
|
//
|
|
164
|
-
//
|
|
165
|
-
//
|
|
182
|
+
// `hasHeredocOperator`, not `includes('<<')`: the guard fires on the operator, and on any delimiter
|
|
183
|
+
// form the detector cannot read — but a `<<` that is part of a longer run cannot open a heredoc at
|
|
184
|
+
// all, so it no longer refuses the mask. `git grep -c '^<<<<<<<' FETCH_HEAD` beside a quoted
|
|
185
|
+
// backtick lost its network to the blanket test (#685).
|
|
186
|
+
//
|
|
187
|
+
// Returns undefined when the walk cannot read the quoting (`echo don't` leaves a `'` open, and an
|
|
188
|
+
// unterminated quote is a syntax error nothing runs past) — the same fallback, because a mask that
|
|
189
|
+
// guesses where a quote ends is how a substitution gets hidden.
|
|
166
190
|
export function maskSingleQuotedData(command) {
|
|
167
|
-
|
|
191
|
+
const scan = scanQuotes(command);
|
|
192
|
+
if (scan.heredocOperator || scan.uncertain)
|
|
168
193
|
return undefined;
|
|
169
|
-
|
|
170
|
-
let i = 0;
|
|
171
|
-
while (i < command.length) {
|
|
172
|
-
const ch = command[i];
|
|
173
|
-
if (ch === '"') {
|
|
174
|
-
const end = command.indexOf('"', i + 1);
|
|
175
|
-
if (end === -1)
|
|
176
|
-
return undefined;
|
|
177
|
-
out += command.slice(i, end + 1);
|
|
178
|
-
i = end + 1;
|
|
179
|
-
}
|
|
180
|
-
else if (ch === "'") {
|
|
181
|
-
const end = command.indexOf("'", i + 1);
|
|
182
|
-
if (end === -1)
|
|
183
|
-
return undefined;
|
|
184
|
-
out += ' '.repeat(end + 1 - i);
|
|
185
|
-
i = end + 1;
|
|
186
|
-
}
|
|
187
|
-
else {
|
|
188
|
-
out += ch;
|
|
189
|
-
i++;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
return out;
|
|
194
|
+
return blankSpans(command, scan.spans, s => s.kind !== 'double');
|
|
193
195
|
}
|
|
194
196
|
// The one call a command line makes. `dropEscapedSubstitutionChars` first (a `\$(` is a literal),
|
|
195
197
|
// then the single-quote mask when it can be built; an unmaskable command keeps the raw test.
|
|
@@ -351,10 +353,22 @@ function segmentIsReadOnly(segment, recognized, planReads) {
|
|
|
351
353
|
return true;
|
|
352
354
|
}
|
|
353
355
|
// Blank out quoted regions while preserving length, so a scan can tell syntax from data and a
|
|
354
|
-
// segment offset still indexes the raw command.
|
|
355
|
-
//
|
|
356
|
+
// segment offset still indexes the raw command. The regions come from `_heredoc.ts`'s walk, so the
|
|
357
|
+
// mask agrees with `/bin/sh` about where a quote opens: `\'` outside quotes is a literal quote and
|
|
358
|
+
// not an opening one (`cat f \"; touch pwned \"` is TWO commands), `$'…'` is a quoted run of its own,
|
|
359
|
+
// and a `'` inside a `$(…)` inside a `"…"` is quoted data while the `$(…)` it sits in is not.
|
|
360
|
+
//
|
|
361
|
+
// It is a walk and not a regex, so it cannot pair a quote with the wrong partner (`maskQuoted` used
|
|
362
|
+
// to pair `\"` with the next `"`, blanking the `; touch pwned` between them — #695).
|
|
363
|
+
//
|
|
364
|
+
// A command whose quoting the walk cannot read blanks NOTHING: the separators, redirects and command
|
|
365
|
+
// names all stay in view, and every caller reads that as the more dangerous text it partly is. The
|
|
366
|
+
// alternative — masking up to the point of confusion — is what hides a second command.
|
|
356
367
|
export function maskQuoted(command) {
|
|
357
|
-
|
|
368
|
+
const scan = scanQuotes(command);
|
|
369
|
+
if (scan.uncertain)
|
|
370
|
+
return command;
|
|
371
|
+
return blankSpans(command, scan.spans, () => true);
|
|
358
372
|
}
|
|
359
373
|
// Cut the command at every separator that sits OUTSIDE quotes, returning each segment's RAW text —
|
|
360
374
|
// a search pattern like "a;b" carries separators that are data, not syntax, so the split walks the
|
package/dist/tools/_sandbox.js
CHANGED
|
@@ -2,8 +2,8 @@ import { realpathSync } from 'node:fs';
|
|
|
2
2
|
import { homedir, tmpdir } from 'node:os';
|
|
3
3
|
import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
|
|
4
4
|
import { execFileSync, spawnSync } from 'node:child_process';
|
|
5
|
+
import { expandingHeredocBodies, stripHeredocs } from './_heredoc.js';
|
|
5
6
|
import { dropCarriers, hasExecutableSubstitution, hasRawSubstitution, maskQuoted, splitSegments, words, INSPECTION_COMMANDS, } from './_readonly.js';
|
|
6
|
-
import { expandingHeredocBodies, stripHeredocs } from './_writetargets.js';
|
|
7
7
|
// Kernel-enforced confinement for model-chosen shell commands (#163). Seatbelt (`sandbox-exec`)
|
|
8
8
|
// only: bubblewrap has no port-level network filtering, so a sandboxed process gets its own
|
|
9
9
|
// loopback and cannot reach the host's model server — the one thing bash needs localhost for. The
|
|
@@ -141,12 +141,136 @@ const NET_PIPE_COMMANDS = new Set([...INSPECTION_COMMANDS, 'sleep'].filter(c =>
|
|
|
141
141
|
// `find`'s exec family runs an arbitrary command per match. `git -c <key>=<value>` can name one
|
|
142
142
|
// through more keys than are worth enumerating — `alias.x='!cmd'`, `core.sshCommand`, `core.pager`,
|
|
143
143
|
// `credential.helper`, `diff.external`, `core.hooksPath` — so `-c` (and `--config-env`) is refused
|
|
144
|
-
// the allow outright: a `git
|
|
145
|
-
// ls-remote need the network. Same class through the environment (`GIT_SSH_COMMAND=./x.sh git
|
|
144
|
+
// the allow outright (below): a `git -c core.pager=cat log` loses nothing, since only fetch/pull/
|
|
145
|
+
// clone/ls-remote need the network. Same class through the environment (`GIT_SSH_COMMAND=./x.sh git
|
|
146
146
|
// fetch`, `PAGER=./x.sh gh pr view`), so an env-assignment prefix keeps the allow only when its name
|
|
147
147
|
// is on a short list of settings that cannot name a program.
|
|
148
148
|
const FIND_EXEC_RE = /^-(?:exec|execdir|ok|okdir)$/;
|
|
149
|
-
|
|
149
|
+
// A `git` segment keeps the allow only when nothing on its own command line can name a program, and
|
|
150
|
+
// the line is read in two halves because git parses it in two. The GLOBAL prefix (between the verb
|
|
151
|
+
// and the subcommand) is git's own parser, which takes exact spellings only (`--no-pag` is "unknown
|
|
152
|
+
// option"), so it is read against an allowlist and an unrecognized flag refuses: `-c`/`--config-env`
|
|
153
|
+
// set any config key, `--exec-path=<dir>` picks where `git-remote-https` comes from, and a value
|
|
154
|
+
// flag missing from the list would hide every `-c` behind its value word (`git --attr-source HEAD
|
|
155
|
+
// -c alias.z='!cmd' z` ran the alias when `--attr-source` was not on it) — so the next one git adds
|
|
156
|
+
// costs a false deny, never a hole. Past the subcommand a `-c` is that subcommand's (`git grep -c`
|
|
157
|
+
// counts, `git log -c` is the combined diff, `git switch -c` creates), and scanning every argument
|
|
158
|
+
// for it cost a whole call its network the first time a model ran `git ls-remote …; git grep -c`.
|
|
159
|
+
// What CAN name a program there is enumerated per subcommand below, and read the way parse-options
|
|
160
|
+
// reads it: a long option matches any unambiguous abbreviation (`--upl=cmd` ran as `--upload-pack`)
|
|
161
|
+
// and short options bundle (`-qu cmd` ran as `-u`), so both are matched, not just the spelling a
|
|
162
|
+
// model usually writes. `--` ends the options; what follows is operands. The remainder is config the
|
|
163
|
+
// repo already holds (`git config core.sshCommand …` in one call, `git fetch` in the next) — the
|
|
164
|
+
// same class as a writable `.git/hooks`, accepted under the confused-model threat.
|
|
165
|
+
const GIT_GLOBAL_FLAGS = new Set([
|
|
166
|
+
'-v',
|
|
167
|
+
'--version',
|
|
168
|
+
'-h',
|
|
169
|
+
'--help',
|
|
170
|
+
'--html-path',
|
|
171
|
+
'--man-path',
|
|
172
|
+
'--info-path',
|
|
173
|
+
'--exec-path', // bare, it prints the path; `--exec-path=<dir>` is refused
|
|
174
|
+
'-p',
|
|
175
|
+
'--paginate',
|
|
176
|
+
'-P',
|
|
177
|
+
'--no-pager',
|
|
178
|
+
'--no-replace-objects',
|
|
179
|
+
'--no-lazy-fetch',
|
|
180
|
+
'--no-optional-locks',
|
|
181
|
+
'--no-advice',
|
|
182
|
+
'--bare',
|
|
183
|
+
'--literal-pathspecs',
|
|
184
|
+
'--glob-pathspecs',
|
|
185
|
+
'--noglob-pathspecs',
|
|
186
|
+
'--icase-pathspecs',
|
|
187
|
+
]);
|
|
188
|
+
// Value globals, which git also accepts as `--flag=<value>` (all but `-C`). The value is a path,
|
|
189
|
+
// a ref or a name — none runs anything — and it is the NEXT word in the space form, so it is
|
|
190
|
+
// skipped rather than read as the subcommand. A value that looks like a flag is not taken, so
|
|
191
|
+
// `git -C -c k=v log` keeps scanning and refuses.
|
|
192
|
+
const GIT_GLOBAL_VALUE_FLAGS = new Set([
|
|
193
|
+
'-C',
|
|
194
|
+
'--git-dir',
|
|
195
|
+
'--work-tree',
|
|
196
|
+
'--namespace',
|
|
197
|
+
'--super-prefix',
|
|
198
|
+
'--attr-source',
|
|
199
|
+
'--list-cmds',
|
|
200
|
+
]);
|
|
201
|
+
// Subcommand options that run a program the model wrote. `--template` plants hooks that run at
|
|
202
|
+
// checkout and clone's `--config` is `-c` again, so both belong here although neither is spelled
|
|
203
|
+
// as a command. Long names apply to every subcommand: none has a harmless option abbreviated by
|
|
204
|
+
// these, and `push --exec`/`archive --exec` mean the same as `rebase --exec`.
|
|
205
|
+
const GIT_PROGRAM_LONG_FLAGS = [
|
|
206
|
+
'upload-pack',
|
|
207
|
+
'receive-pack',
|
|
208
|
+
'exec',
|
|
209
|
+
'extcmd',
|
|
210
|
+
'open-files-in-pager',
|
|
211
|
+
'template',
|
|
212
|
+
'config',
|
|
213
|
+
];
|
|
214
|
+
// Short spellings per subcommand: the letters that name a program, and the letters whose value is
|
|
215
|
+
// the rest of the bundle (so `-bcute` is branch `cute`, not `-c`). An unlisted value letter only
|
|
216
|
+
// makes the read stricter.
|
|
217
|
+
const GIT_PROGRAM_SHORT_FLAGS = {
|
|
218
|
+
clone: { run: 'cu', value: 'bojcu' },
|
|
219
|
+
grep: { run: 'O', value: 'efABCmO' },
|
|
220
|
+
rebase: { run: 'x', value: 'sXxC' },
|
|
221
|
+
difftool: { run: 'x', value: 'tx' },
|
|
222
|
+
};
|
|
223
|
+
// Whole subcommands (or a subcommand's first operand) whose job is running a command.
|
|
224
|
+
const GIT_PROGRAM_SUBCOMMANDS = new Set(['filter-branch', 'submodule foreach', 'bisect run']);
|
|
225
|
+
function gitSubcommandRunsProgram(sub, args) {
|
|
226
|
+
if (GIT_PROGRAM_SUBCOMMANDS.has(sub))
|
|
227
|
+
return true;
|
|
228
|
+
const first = args.find(a => !a.startsWith('-'));
|
|
229
|
+
if (first && GIT_PROGRAM_SUBCOMMANDS.has(`${sub} ${first}`))
|
|
230
|
+
return true;
|
|
231
|
+
const short = GIT_PROGRAM_SHORT_FLAGS[sub];
|
|
232
|
+
for (const a of args) {
|
|
233
|
+
if (a === '--')
|
|
234
|
+
return false;
|
|
235
|
+
if (a.startsWith('--')) {
|
|
236
|
+
const name = a.slice(2).split('=')[0];
|
|
237
|
+
if (name.length >= 2 && GIT_PROGRAM_LONG_FLAGS.some(f => f.startsWith(name)))
|
|
238
|
+
return true;
|
|
239
|
+
}
|
|
240
|
+
else if (short && a.startsWith('-')) {
|
|
241
|
+
for (const ch of a.slice(1)) {
|
|
242
|
+
if (short.run.includes(ch))
|
|
243
|
+
return true;
|
|
244
|
+
if (short.value.includes(ch))
|
|
245
|
+
break;
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
// Called with the git segment's OWN words (verb, `timeout`/`xargs` carrier and xargs flags already
|
|
252
|
+
// dropped), so a carrier's data cannot pose as the verb's arguments: `xargs -I git git -c k=v
|
|
253
|
+
// fetch` would otherwise find the `-I` placeholder where it looks for `git`.
|
|
254
|
+
function gitArgsRunProgram(args) {
|
|
255
|
+
for (let i = 0; i < args.length; i++) {
|
|
256
|
+
const a = args[i];
|
|
257
|
+
if (!a.startsWith('-'))
|
|
258
|
+
return gitSubcommandRunsProgram(a, args.slice(i + 1));
|
|
259
|
+
if (GIT_GLOBAL_FLAGS.has(a))
|
|
260
|
+
continue;
|
|
261
|
+
const name = a.split('=')[0];
|
|
262
|
+
if (GIT_GLOBAL_VALUE_FLAGS.has(name)) {
|
|
263
|
+
if (a.includes('='))
|
|
264
|
+
continue;
|
|
265
|
+
if (args[i + 1] !== undefined && !args[i + 1].startsWith('-')) {
|
|
266
|
+
i++;
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
return false;
|
|
273
|
+
}
|
|
150
274
|
const HARMLESS_ENV = new Set([
|
|
151
275
|
'GIT_TERMINAL_PROMPT',
|
|
152
276
|
'GIT_OPTIONAL_LOCKS',
|
|
@@ -193,9 +317,13 @@ const HARMLESS_ENV = new Set([
|
|
|
193
317
|
// for; a value naming a program is a program the output gets piped into.
|
|
194
318
|
const PAGER_ENV = new Set(['PAGER', 'GIT_PAGER', 'GH_PAGER']);
|
|
195
319
|
const ENV_ASSIGN_RE = /^([A-Za-z_]\w*)=(.*)$/;
|
|
196
|
-
// Whether a segment's leading env assignments can all be trusted not to redirect what runs.
|
|
320
|
+
// Whether a segment's leading env assignments can all be trusted not to redirect what runs. Read
|
|
321
|
+
// past the same wrappers `VERB_PREFIX_RE` strips to find the verb, or `env GIT_SSH_COMMAND=./x.sh
|
|
322
|
+
// git fetch` stopped at `env`, found no assignment, and kept the allow its bare spelling is refused.
|
|
197
323
|
function envPrefixHarmless(segment) {
|
|
198
324
|
for (const w of words(segment.trim())) {
|
|
325
|
+
if (PREFIX_WORDS.has(w))
|
|
326
|
+
continue;
|
|
199
327
|
const m = ENV_ASSIGN_RE.exec(w);
|
|
200
328
|
if (!m)
|
|
201
329
|
return true; // past the assignments
|
|
@@ -217,6 +345,8 @@ const REDIRECT_AMP_RE = /\d*>&\d*|&>>?/g;
|
|
|
217
345
|
// Wrappers that don't change what a segment runs (the same set `_danger.ts` strips), plus the
|
|
218
346
|
// keywords a compound can open with. Stripped before the verb is read.
|
|
219
347
|
const VERB_PREFIX_RE = /^(?:(?:[A-Za-z_]\w*=\S*|sudo|command|nohup|exec|env|time|if|then|else|elif|do|while|until|!)\s+)+/;
|
|
348
|
+
// The same wrappers as words, for `envPrefixHarmless`, which reads them one at a time.
|
|
349
|
+
export const PREFIX_WORDS = new Set('sudo command nohup exec env time if then else elif do while until !'.split(' '));
|
|
220
350
|
// Substitution runs a nested command the verb check never sees; `_readonly.ts` owns that test
|
|
221
351
|
// (`hasExecutableSubstitution`) so the sandbox and the plan gate cannot drift on which contexts are
|
|
222
352
|
// DATA.
|
|
@@ -232,7 +362,7 @@ const XARGS_VALUE_FLAGS = new Set(['-I', '-n', '-P', '-L', '-s', '-d', '-E', '-J
|
|
|
232
362
|
// stays checked — which also keeps the unbounded poll (`while true; do sleep 5; gh pr view …; done`)
|
|
233
363
|
// out of the allow.
|
|
234
364
|
const SHELL_STRUCTURE_RE = /^(?:do|done)$|^for\s+\w+\s+in(?:\s|$)/;
|
|
235
|
-
function
|
|
365
|
+
function effectiveWords(segment) {
|
|
236
366
|
// `timeout` and `xargs` each name the command they run rather than being it, so both are skipped to
|
|
237
367
|
// reach it — a carrier inside the command xargs runs included.
|
|
238
368
|
let ws = dropCarriers(words(segment.trim().replace(VERB_PREFIX_RE, '')));
|
|
@@ -245,7 +375,7 @@ function effectiveVerb(segment) {
|
|
|
245
375
|
}
|
|
246
376
|
ws = dropCarriers(ws.slice(i));
|
|
247
377
|
}
|
|
248
|
-
return ws
|
|
378
|
+
return ws;
|
|
249
379
|
}
|
|
250
380
|
/**
|
|
251
381
|
* Whether `command` may run sandboxed WITH network: every segment is a `NET_VERBS` command or one
|
|
@@ -285,14 +415,15 @@ export function networkDecision(command) {
|
|
|
285
415
|
let net = false;
|
|
286
416
|
let blockedBy;
|
|
287
417
|
for (const seg of segments) {
|
|
288
|
-
const
|
|
418
|
+
const ws = effectiveWords(seg);
|
|
419
|
+
const verb = ws[0];
|
|
289
420
|
if (!verb)
|
|
290
421
|
return { allowed: false };
|
|
291
|
-
const args =
|
|
422
|
+
const args = ws.slice(1);
|
|
292
423
|
if (NET_VERBS.has(verb)) {
|
|
293
424
|
if (!envPrefixHarmless(seg))
|
|
294
425
|
return { allowed: false };
|
|
295
|
-
if (verb === 'git' && args
|
|
426
|
+
if (verb === 'git' && gitArgsRunProgram(args))
|
|
296
427
|
return { allowed: false };
|
|
297
428
|
net = true;
|
|
298
429
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolve } from 'node:path';
|
|
2
|
+
import { stripHeredocs } from './_heredoc.js';
|
|
2
3
|
import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
|
|
3
4
|
// The files a shell command names as things it will write — the fallback change detector for a
|
|
4
5
|
// project with no git (#278). Best-effort by construction: it sees the shapes a model reaches for
|
|
@@ -8,8 +9,6 @@ import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
|
|
|
8
9
|
//
|
|
9
10
|
// Pure: absolute paths out, resolved against `cwd` with any leading `cd` hops applied.
|
|
10
11
|
const MAX_TARGETS = 20;
|
|
11
|
-
// `<<EOF … EOF`: the body is data, and its lines would otherwise parse as commands with redirects.
|
|
12
|
-
const HEREDOC_RE = /<<-?\s*(['"]?)(\w+)\1/;
|
|
13
12
|
export function writeTargets(command, cwd) {
|
|
14
13
|
const stripped = stripHeredocs(command);
|
|
15
14
|
const out = new Set();
|
|
@@ -98,47 +97,3 @@ function commandTargets(name, args) {
|
|
|
98
97
|
return [];
|
|
99
98
|
}
|
|
100
99
|
}
|
|
101
|
-
// Also read by the sandbox's network classifier (#163): a heredoc body's lines would otherwise
|
|
102
|
-
// split into segments whose "verb" is prose, denying `gh issue comment --body-file - <<EOF …`.
|
|
103
|
-
export function stripHeredocs(command) {
|
|
104
|
-
let s = command;
|
|
105
|
-
for (let m = HEREDOC_RE.exec(s); m; m = HEREDOC_RE.exec(s)) {
|
|
106
|
-
const bodyStart = s.indexOf('\n', m.index);
|
|
107
|
-
if (bodyStart === -1)
|
|
108
|
-
break;
|
|
109
|
-
const endRe = new RegExp(`^\\s*${m[2]}\\s*$`, 'm');
|
|
110
|
-
const rest = s.slice(bodyStart + 1);
|
|
111
|
-
const end = endRe.exec(rest);
|
|
112
|
-
const bodyEnd = end ? bodyStart + 1 + end.index + end[0].length : s.length;
|
|
113
|
-
// Keep the `<<` operator text off the next pass by cutting it out with the body.
|
|
114
|
-
s = s.slice(0, m.index) + s.slice(bodyEnd);
|
|
115
|
-
}
|
|
116
|
-
return s;
|
|
117
|
-
}
|
|
118
|
-
// The heredoc bodies the shell EXPANDS, which `stripHeredocs` deliberately cuts away with the rest:
|
|
119
|
-
// `$…` and a backtick in a body are only data when the DELIMITER was quoted, so `<<EOF` runs what
|
|
120
|
-
// `<<'EOF'` pastes. Dropping them answers the verb question correctly ("what commands does this
|
|
121
|
-
// line run" — a body's prose runs nothing) and the substitution question wrongly, because a `$(…)`
|
|
122
|
-
// in an expanding body DOES run, with whatever network the line's `git`/`gh` verb was granted.
|
|
123
|
-
// Walked exactly like `stripHeredocs` — each body cut before the next match — so prose inside one
|
|
124
|
-
// can never be read as a heredoc operator of its own.
|
|
125
|
-
export function expandingHeredocBodies(command) {
|
|
126
|
-
const bodies = [];
|
|
127
|
-
let s = command;
|
|
128
|
-
for (let m = HEREDOC_RE.exec(s); m; m = HEREDOC_RE.exec(s)) {
|
|
129
|
-
const quoted = m[1] !== '';
|
|
130
|
-
const bodyStart = s.indexOf('\n', m.index);
|
|
131
|
-
if (bodyStart === -1)
|
|
132
|
-
break;
|
|
133
|
-
const endRe = new RegExp(`^\\s*${m[2]}\\s*$`, 'm');
|
|
134
|
-
const rest = s.slice(bodyStart + 1);
|
|
135
|
-
const end = endRe.exec(rest);
|
|
136
|
-
const bodyEnd = end ? bodyStart + 1 + end.index + end[0].length : s.length;
|
|
137
|
-
// An unterminated heredoc swallows the rest, which is what the shell does with it too. The
|
|
138
|
-
// newline before the delimiter line terminates the body rather than belonging to it.
|
|
139
|
-
if (!quoted)
|
|
140
|
-
bodies.push(rest.slice(0, end ? end.index : rest.length).replace(/\n$/, ''));
|
|
141
|
-
s = s.slice(0, m.index) + s.slice(bodyEnd);
|
|
142
|
-
}
|
|
143
|
-
return bodies;
|
|
144
|
-
}
|
package/dist/tools/bash.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
2
|
import { buildCappedFooter, buildSpillFooter, spillEnabled, spillResult } from './_spill.js';
|
|
3
3
|
import { detectDangerousPatterns } from './_danger.js';
|
|
4
|
+
import { scanHeredocs } from './_heredoc.js';
|
|
4
5
|
import { remoteUrlRisk } from './_exfil.js';
|
|
5
6
|
import { declineSummary } from '../approval.js';
|
|
6
7
|
import { SANDBOX_EXEC_ERROR_PREFIX, SANDBOX_PROFILE_ERROR_CODE, broadWorkdirNotice, isBroadWorkdir, networkAllowedFor, sandboxArgv, sandboxFooter, sandboxNotice, sandboxPlan, sandboxRefusedWrite, } from './_sandbox.js';
|
|
@@ -579,26 +580,23 @@ function searchHint(command, output) {
|
|
|
579
580
|
//
|
|
580
581
|
// Held to the failing signal — non-zero exit, that message, and a heredoc inside a `$(…)` — so it
|
|
581
582
|
// costs nothing on every other command and nothing in the prompt. The issue names the observed
|
|
582
|
-
// command as `$(cat <<`; the
|
|
583
|
-
//
|
|
584
|
-
// the same way)
|
|
585
|
-
// of every one of those unhandled.
|
|
586
|
-
// extra line and would otherwise read as a marker plus a quoted word. The span between `$(` and
|
|
587
|
-
// `<<` is unanchored on purpose: stopping at the first `)` missed a reader that carries one
|
|
588
|
-
// (`sed 's/(x)/y/' <<'EOF'`), and the message gate is what carries the discrimination.
|
|
583
|
+
// command as `$(cat <<`; the test is the shape of the CAUSE instead — any heredoc `_heredoc.ts`
|
|
584
|
+
// reads inside a `$(…)` or backtick, whatever its reader, whitespace or delimiter form (`<<\EOF` is
|
|
585
|
+
// POSIX's own spelling and fails the same way) — because they are the same pre-scan, and a literal
|
|
586
|
+
// match would leave the neighbour of every one of those unhandled.
|
|
589
587
|
//
|
|
590
588
|
// Darwin only: `execStream` hardcodes `/bin/sh`, and on a Linux where that is bash 5 the same
|
|
591
589
|
// command parses — but bash 5 prints the same message for a genuinely unbalanced command, and the
|
|
592
590
|
// hint would then tell the model its broken command is correct and blame a platform it is not on.
|
|
593
591
|
const UNPAIRED_QUOTE_RE = /unexpected EOF while looking for matching/;
|
|
594
|
-
const HEREDOC_IN_SUBSTITUTION_RE = /\$\([\s\S]*?(?:^|[^<])<<(?!<)-?\s*['"\\]?\w/;
|
|
595
592
|
export function heredocSubstitutionHint(command, code, output, platform = process.platform) {
|
|
596
593
|
if (platform !== 'darwin')
|
|
597
594
|
return '';
|
|
598
595
|
// Same guard as sandboxFooter's: a signal death is not a status this message can arrive with.
|
|
599
596
|
if (code === null || code === 0)
|
|
600
597
|
return '';
|
|
601
|
-
if (!UNPAIRED_QUOTE_RE.test(output) ||
|
|
598
|
+
if (!UNPAIRED_QUOTE_RE.test(output) ||
|
|
599
|
+
!scanHeredocs(command).heredocs.some(h => h.inSubstitution))
|
|
602
600
|
return '';
|
|
603
601
|
return ('\n\n(reika: macOS /bin/sh is bash 3.2, which reads the inside of a $(…) as ordinary shell ' +
|
|
604
602
|
'text rather than treating a <<EOF body as opaque — so an apostrophe in the body (ordinary ' +
|
package/dist/ui/App.js
CHANGED
|
@@ -293,6 +293,8 @@ export function App() {
|
|
|
293
293
|
const modelPinnedRef = useRef(false);
|
|
294
294
|
const inputValueRef = useRef('');
|
|
295
295
|
inputValueRef.current = inputValue;
|
|
296
|
+
// What the box held when the ask_user answer field opened, so backing out discards only the answer.
|
|
297
|
+
const preAnswerDraftRef = useRef('');
|
|
296
298
|
const suggestionStateRef = useRef(null);
|
|
297
299
|
suggestionStateRef.current = suggestionState;
|
|
298
300
|
const suggestionSelectedRef = useRef(0);
|
|
@@ -477,6 +479,13 @@ export function App() {
|
|
|
477
479
|
{ role: 'system', content: problem, tone: 'warn', skipAutosave: true },
|
|
478
480
|
]);
|
|
479
481
|
}
|
|
482
|
+
if (cfg.projectEnvNotice) {
|
|
483
|
+
const content = cfg.projectEnvNotice;
|
|
484
|
+
setMessages(prev => [
|
|
485
|
+
...prev,
|
|
486
|
+
{ role: 'system', content, tone: 'warn', skipAutosave: true },
|
|
487
|
+
]);
|
|
488
|
+
}
|
|
480
489
|
// MCP: what connected, what failed, and any config error (#265). The healthy summary is the
|
|
481
490
|
// only line that is good news — the shape `connectNotices` emits — so everything else that
|
|
482
491
|
// reaches here (a server that did not start, a document that did not parse) is worth
|
|
@@ -643,6 +652,20 @@ export function App() {
|
|
|
643
652
|
setPending(null);
|
|
644
653
|
}
|
|
645
654
|
if (questionRef.current) {
|
|
655
|
+
// Typing an answer or a note (#651): ctrl-c backs out of the field to the option list
|
|
656
|
+
// instead of dropping the question. The field is live and owns the keyboard, so this is the
|
|
657
|
+
// only route back to the list, and ask_user is one-shot — dropping it here throws away the
|
|
658
|
+
// menu the turn is waiting on. The list keeps the abort, so a second ctrl-c still ends the
|
|
659
|
+
// dialog. Returned rather than fallen through: nothing has been decided, and the code below
|
|
660
|
+
// would abort the whole turn with it. The typed answer is discarded — left in the box it
|
|
661
|
+
// outlives the question and one stray Enter queues it as the next prompt — but a draft that
|
|
662
|
+
// was there before the field opened comes back.
|
|
663
|
+
if (questionTypingRef.current) {
|
|
664
|
+
setInputValue(preAnswerDraftRef.current);
|
|
665
|
+
setSuggestionState(null);
|
|
666
|
+
setQuestionTyping(null);
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
646
669
|
questionRef.current.resolve(null);
|
|
647
670
|
setQuestion(null);
|
|
648
671
|
setQuestionTyping(null);
|
|
@@ -749,6 +772,7 @@ export function App() {
|
|
|
749
772
|
// Tab on an option: take it, but add a note in your own words. The model gets both.
|
|
750
773
|
if (key.tab && questionSelectedRef.current < last) {
|
|
751
774
|
const forIndex = questionSelectedRef.current;
|
|
775
|
+
preAnswerDraftRef.current = inputValueRef.current;
|
|
752
776
|
queueMicrotask(() => setQuestionTyping({ forIndex }));
|
|
753
777
|
return;
|
|
754
778
|
}
|
|
@@ -758,6 +782,7 @@ export function App() {
|
|
|
758
782
|
// Deferred a microtask: this same keypress is dispatched to every useInput handler with
|
|
759
783
|
// re-renders in between, so enabling Input synchronously hands it the very Enter that
|
|
760
784
|
// opened it and submits an empty answer.
|
|
785
|
+
preAnswerDraftRef.current = inputValueRef.current;
|
|
761
786
|
queueMicrotask(() => setQuestionTyping({}));
|
|
762
787
|
return;
|
|
763
788
|
}
|
package/dist/ui/Question.js
CHANGED
|
@@ -54,7 +54,7 @@ export function Question({ request, selectedIndex, typing, width, rows = process
|
|
|
54
54
|
const label = tagAt >= 0 ? wrapped.slice(0, tagAt) : wrapped;
|
|
55
55
|
return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : theme.secondary, children: num }), _jsx(Text, { color: selected ? theme.accent : undefined, children: label }), tagAt >= 0 ? _jsx(Text, { color: theme.info, children: wrapped.slice(tagAt) }) : null] }), fit.showDescriptions && descriptions[i] ? (_jsx(Text, { color: theme.muted, children: ' '.repeat(hang) + descriptions[i] })) : null] }, i));
|
|
56
56
|
}), _jsxs(Text, { children: [_jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : undefined, children: selectedIndex === request.options.length ? '› ' : ' ' }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: `${request.options.length + 1}. ` }), _jsx(Text, { color: selectedIndex === request.options.length ? theme.accent : theme.secondary, children: ownAnswer })] })] })), _jsx(Box, { marginTop: 1, children: _jsx(Text, { color: theme.muted, children: typing
|
|
57
|
-
? 'enter submit · ctrl-c
|
|
57
|
+
? 'enter submit · ctrl-c back to the options'
|
|
58
58
|
: '↑↓ or 1-9 navigate · enter select · tab add a note · ctrl-c abort' }) })] }));
|
|
59
59
|
}
|
|
60
60
|
// Labels are full sentences and wrap on any ordinary terminal. Ink has no hanging indent, so a
|
package/dist/ui/Suggestions.js
CHANGED
|
@@ -42,7 +42,7 @@ export function Suggestions({ state, selectedIndex, }) {
|
|
|
42
42
|
const selected = start + j === selectedIndex;
|
|
43
43
|
// One Text with nested runs (not siblings): on wrap Ink drops the char at
|
|
44
44
|
// a sibling boundary, which would clip a long item.
|
|
45
|
-
return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : undefined, children: truncate(item.display, maxDisplay) })] }, start + j));
|
|
45
|
+
return (_jsxs(Text, { children: [_jsx(Text, { color: selected ? theme.accent : undefined, children: start + visible < total && j === visible - 1 ? '↓ ' : selected ? '› ' : ' ' }), _jsx(Text, { color: selected ? theme.accent : undefined, children: truncate(item.display, maxDisplay) })] }, start + j));
|
|
46
46
|
}), _jsx(Box, { marginTop: 1, children: _jsxs(Text, { color: theme.muted, children: ['↑↓ navigate · tab/enter accept · esc dismiss', total > visible ? ` · ${selectedIndex + 1}/${total}` : ''] }) })] }));
|
|
47
47
|
}
|
|
48
48
|
function truncate(s, max) {
|