@alexwkleung/reika 0.4.0 → 0.5.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.
@@ -256,11 +256,115 @@ const MAX_OPERANDS = { uniq: 1 };
256
256
  // ladder scores as "not inspection" is one it lets a withdrawn model keep circling on.
257
257
  const VALUE_FLAGS = { uniq: new Set(['-f', '-s', '-w']) };
258
258
  // Split into words the way the shell does, keeping a quoted run with spaces in it as ONE word, then
259
- // drop the quote characters. Quoting changes nothing about how a command reads its own arguments, so
260
- // `find . '-delete'` must be seen as the flag it is.
261
- export const WORD_RE = /(?:[^\s'"]|'[^']*'|"[^"]*")+/g;
259
+ // remove the quoting the way the shell does. Quoting changes nothing about how a command reads its
260
+ // own arguments, so `find . '-delete'` must be seen as the flag it is — and so must `-de\lete`,
261
+ // `\" -delete \"` and `$'\x2ddelete'`. Every reader that decides on these words is an allowlist
262
+ // (plan mode's read-only bash, the sandbox's network allow), so a word read differently from the
263
+ // shell is a flag the allowlist never saw: the first cut ignored backslashes, which joined
264
+ // `\" -delete \"` into one quoted word, and dropped quote characters without decoding `$'…'`.
265
+ export const WORD_RE = /(?:\$'(?:[^'\\]|\\[\s\S])*'|\$?"(?:[^"\\]|\\[\s\S])*"|'[^']*'|\\[\s\S]?|[^\s'"\\])+/g;
262
266
  export function words(segment) {
263
- return (segment.match(WORD_RE) ?? []).map(w => w.replace(/['"]/g, ''));
267
+ return (segment.match(WORD_RE) ?? []).map(dequote);
268
+ }
269
+ // What a backslash keeps its meaning before inside `"…"`; before anything else it is literal there.
270
+ const DOUBLE_QUOTE_ESCAPES = '$`"\\\n';
271
+ const ANSI_C_ESCAPES = {
272
+ a: '\x07',
273
+ b: '\b',
274
+ e: '\x1b',
275
+ E: '\x1b',
276
+ f: '\f',
277
+ n: '\n',
278
+ r: '\r',
279
+ t: '\t',
280
+ v: '\v',
281
+ '\\': '\\',
282
+ "'": "'",
283
+ '"': '"',
284
+ '?': '?',
285
+ };
286
+ export function dequote(word) {
287
+ let out = '';
288
+ let i = 0;
289
+ while (i < word.length) {
290
+ const c = word[i];
291
+ if (c === '\\') {
292
+ // A backslash-newline is a line continuation and disappears; a trailing one is literal.
293
+ const next = word[i + 1];
294
+ if (next === undefined)
295
+ out += '\\';
296
+ else if (next !== '\n')
297
+ out += next;
298
+ i += 2;
299
+ }
300
+ else if (c === "'") {
301
+ const end = word.indexOf("'", i + 1);
302
+ out += word.slice(i + 1, end < 0 ? word.length : end);
303
+ i = end < 0 ? word.length : end + 1;
304
+ }
305
+ else if (c === '$' && word[i + 1] === "'") {
306
+ i = readAnsiC(word, i + 2, s => (out += s));
307
+ }
308
+ else if (c === '$' && word[i + 1] === '"') {
309
+ i++;
310
+ }
311
+ else if (c === '"') {
312
+ i++;
313
+ while (i < word.length && word[i] !== '"') {
314
+ if (word[i] === '\\' && DOUBLE_QUOTE_ESCAPES.includes(word[i + 1] ?? '')) {
315
+ if (word[i + 1] !== '\n')
316
+ out += word[i + 1];
317
+ i += 2;
318
+ }
319
+ else
320
+ out += word[i++];
321
+ }
322
+ i++;
323
+ }
324
+ else {
325
+ out += c;
326
+ i++;
327
+ }
328
+ }
329
+ return out;
330
+ }
331
+ // Bash's `$'…'` escapes, decoded so `$'\x2ddelete'` reads as the `-delete` it is.
332
+ function readAnsiC(word, start, emit) {
333
+ let i = start;
334
+ while (i < word.length && word[i] !== "'") {
335
+ if (word[i] !== '\\') {
336
+ emit(word[i++]);
337
+ continue;
338
+ }
339
+ const next = word[i + 1] ?? '';
340
+ const rest = word.slice(i + 2);
341
+ const hex = (max) => new RegExp(`^[0-9a-fA-F]{1,${max}}`).exec(rest)?.[0];
342
+ if (next in ANSI_C_ESCAPES) {
343
+ emit(ANSI_C_ESCAPES[next]);
344
+ i += 2;
345
+ }
346
+ else if (/[0-7]/.test(next)) {
347
+ const digits = /^[0-7]{1,3}/.exec(word.slice(i + 1))[0];
348
+ emit(String.fromCharCode(parseInt(digits, 8) & 0xff));
349
+ i += 1 + digits.length;
350
+ }
351
+ else if ((next === 'x' || next === 'u' || next === 'U') &&
352
+ hex(next === 'x' ? 2 : next === 'u' ? 4 : 8)) {
353
+ const digits = hex(next === 'x' ? 2 : next === 'u' ? 4 : 8);
354
+ const code = parseInt(digits, 16);
355
+ emit(code <= 0x10ffff ? String.fromCodePoint(code) : '');
356
+ i += 2 + digits.length;
357
+ }
358
+ else if (next === 'c' && i + 2 < word.length) {
359
+ emit(String.fromCharCode(word.charCodeAt(i + 2) & 0x1f));
360
+ i += 3;
361
+ }
362
+ else {
363
+ emit('\\' + next);
364
+ i += 2;
365
+ }
366
+ }
367
+ return i + 1;
264
368
  }
265
369
  // The carrier that bounds ONE command and changes nothing else about it, skipped so both readers see
266
370
  // the command itself. `timeout 120 gh issue view 621 --json title,body` is the shape a model writes
@@ -370,6 +474,30 @@ export function maskQuoted(command) {
370
474
  return command;
371
475
  return blankSpans(command, scan.spans, () => true);
372
476
  }
477
+ // `maskQuoted` with the command text inside quotes given back: a `$(…)` or a backtick inside `"…"`
478
+ // runs, separators and all, while one inside `'…'` is a character. An escaped character is data too,
479
+ // so `make \`-newline-`install` stays one command and `a\;` ends nothing. For a reader that asks where
480
+ // the shell's own separators are. Regions apply outermost first, so an inner one decides its text.
481
+ export function maskShellData(command) {
482
+ const scan = scanQuotes(command);
483
+ if (scan.uncertain)
484
+ return command;
485
+ const regions = [
486
+ ...scan.spans.map(s => ({ start: s.start, end: s.end, data: true })),
487
+ ...scan.substitutions.map(s => ({ start: s.start, end: s.end, data: false })),
488
+ ].sort((a, b) => a.start - b.start || b.end - a.end);
489
+ const out = command.split('');
490
+ for (const r of regions) {
491
+ for (let i = r.start; i < r.end; i++)
492
+ out[i] = r.data ? ' ' : command[i];
493
+ }
494
+ for (const i of scan.escapes) {
495
+ out[i] = ' ';
496
+ if (i + 1 < out.length)
497
+ out[i + 1] = ' ';
498
+ }
499
+ return out.join('');
500
+ }
373
501
  // Cut the command at every separator that sits OUTSIDE quotes, returning each segment's RAW text —
374
502
  // a search pattern like "a;b" carries separators that are data, not syntax, so the split walks the
375
503
  // mask while the slices come from the original.
@@ -1,6 +1,6 @@
1
1
  import { resolve } from 'node:path';
2
2
  import { stripHeredocs } from './_heredoc.js';
3
- import { WORD_RE, maskQuoted, splitSegments } from './_readonly.js';
3
+ import { WORD_RE, dequote, maskQuoted, splitSegments } from './_readonly.js';
4
4
  // The files a shell command names as things it will write — the fallback change detector for a
5
5
  // project with no git (#278). Best-effort by construction: it sees the shapes a model reaches for
6
6
  // when it edits through the shell (a heredoc or `echo` into a redirect, `sed -i`, `tee`, `cp`/`mv`,
@@ -23,12 +23,12 @@ export function writeTargets(command, cwd) {
23
23
  // not. `>&1`-style descriptor dups name no file.
24
24
  const m = REDIRECT_WORD_RE.exec(rawWords[i]);
25
25
  if (m) {
26
- const target = unquote(m[1] || rawWords[++i] || '');
26
+ const target = dequote(m[1] || rawWords[++i] || '');
27
27
  if (target && !target.startsWith('&'))
28
28
  targets.push(target);
29
29
  continue;
30
30
  }
31
- const w = unquote(rawWords[i]);
31
+ const w = dequote(rawWords[i]);
32
32
  if (w !== '')
33
33
  bare.push(w);
34
34
  }
@@ -52,9 +52,6 @@ export function writeTargets(command, cwd) {
52
52
  }
53
53
  // `&` is a segment separator, so `&>f` arrives as a segment starting with `>f`.
54
54
  const REDIRECT_WORD_RE = /^\d?>>?(.*)$/;
55
- function unquote(word) {
56
- return word.replace(/['"]/g, '');
57
- }
58
55
  // Files a command writes by its own convention, from its operands.
59
56
  function commandTargets(name, args) {
60
57
  const operands = [];
package/dist/ui/App.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
3
3
  import { Box, Static, Text, useApp, useInput } from 'ink';
4
- import { dirname, isAbsolute, join, resolve } from 'node:path';
4
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
5
5
  import { homedir } from 'node:os';
6
6
  import { Splash } from './Splash.js';
7
7
  import { Scrollback } from './Scrollback.js';
@@ -22,7 +22,7 @@ import { loadLastState, persistableMode, saveLastState, startMode, startProfiles
22
22
  import { autoApproveForced, autoApproves, effectiveAutoApprove, formatUnattendedDeclines, } from '../approval.js';
23
23
  import { bootstrap } from '../context/bootstrap.js';
24
24
  import { budgetWarning, formatBudget } from '../context/bundlesize.js';
25
- import { debugLog } from '../debug.js';
25
+ import { debugLog, processSessionStem } from '../debug.js';
26
26
  import { addFileToIndex } from '../context/files.js';
27
27
  import { saveTranscript, TRANSCRIPT_VERSION, } from '../store/transcript.js';
28
28
  import {} from '../agent/loop.js';
@@ -50,6 +50,7 @@ import { buildSummary, hasActivity } from './summary.js';
50
50
  import { QueuedList } from './QueuedList.js';
51
51
  import { queueReceipt } from './queue.js';
52
52
  import { expandPastes, rememberPaste } from './pastes.js';
53
+ import { buildShellRunsBlock, captureShellRun, holdShellRun, shellRunBudget, } from '../agent/shellruns.js';
53
54
  import { invokeMcpTool, parseMcpArgs } from '../mcp/tools.js';
54
55
  // How long the "Typechecking" indicator lingers after a check settles, so a sub-second warm check
55
56
  // still reads. Long enough to perceive, short enough not to imply the check is still running.
@@ -188,6 +189,8 @@ export function App() {
188
189
  // input buffer. Ref-held: the buffer's marker is the visible state, this is just its payload,
189
190
  // and re-rendering on paste would fight the Input's own cursor bookkeeping.
190
191
  const imageAttachmentsRef = useRef([]);
192
+ // Shell-mode runs since the last prompt, prepended to the next one (agent/shellruns.ts).
193
+ const heldShellRunsRef = useRef([]);
191
194
  // Text from pastes too large to sit in the input buffer, keyed by the `[Pasted text #N +412 lines]` marker
192
195
  // holding its place there (ui/pastes.ts). Ref-held for the same reason as image attachments.
193
196
  // Unlike them it is NOT consumed at submit: the marker is plain text the user can recall from
@@ -310,6 +313,7 @@ export function App() {
310
313
  // The file this session auto-saves to (#1), fixed at its first save so every later save rewrites
311
314
  // one file. null until then, and again after /new, so a new conversation gets a new file.
312
315
  const sessionPathRef = useRef(null);
316
+ const sessionStemClaimedRef = useRef(false);
313
317
  const autosaveTimerRef = useRef(null);
314
318
  // Writes run one after another: two in flight could rename out of order and leave the older
315
319
  // snapshot on disk.
@@ -968,6 +972,10 @@ export function App() {
968
972
  ? { agent: stash.agent ?? [], chat: messagesRef.current }
969
973
  : { agent: messagesRef.current, chat: stash.chat ?? [] };
970
974
  };
975
+ // The basename only: enough to find the transcript under history/, no home path in the log.
976
+ const logSessionFile = (path) => {
977
+ debugLog(`[reika:debug] session file=${basename(path)}`);
978
+ };
971
979
  const autosaveNow = () => {
972
980
  if (autosaveTimerRef.current !== null) {
973
981
  clearTimeout(autosaveTimerRef.current);
@@ -982,7 +990,14 @@ export function App() {
982
990
  if (turns === 0 || turns <= (autosaveHoldRef.current ?? 0))
983
991
  return autosaveChainRef.current;
984
992
  autosaveHoldRef.current = null;
985
- sessionPathRef.current ??= newSessionPath(projectHistoryDir(bundle.cwd), new Date());
993
+ if (sessionPathRef.current === null) {
994
+ // The process's first transcript shares the debug log's name (#761); a later /new gets its
995
+ // own, and the log line below is what pairs it.
996
+ const stem = sessionStemClaimedRef.current ? undefined : processSessionStem();
997
+ sessionStemClaimedRef.current = true;
998
+ sessionPathRef.current = newSessionPath(projectHistoryDir(bundle.cwd), new Date(), stem);
999
+ logSessionFile(sessionPathRef.current);
1000
+ }
986
1001
  const path = sessionPathRef.current;
987
1002
  const meta = transcriptMeta(sides.agent, bundle.cwd, statusRef.current === 'busy');
988
1003
  autosaveChainRef.current = autosaveChainRef.current
@@ -1063,8 +1078,10 @@ export function App() {
1063
1078
  resetConversation();
1064
1079
  // A project session carries on in its own file; a manual save from the root is left as it was
1065
1080
  // and the continuation gets a project file of its own on its next save.
1066
- if (dirname(entry.path) === projectDir)
1081
+ if (dirname(entry.path) === projectDir) {
1067
1082
  sessionPathRef.current = entry.path;
1083
+ logSessionFile(entry.path);
1084
+ }
1068
1085
  autosaveHoldRef.current = countRealTurns(sides.agent) + countRealTurns(sides.chat);
1069
1086
  const inChat = modeRef.current === 'chat';
1070
1087
  const active = inChat ? sides.chat : sides.agent;
@@ -1255,6 +1272,7 @@ export function App() {
1255
1272
  // may be a different model on different hardware (#204): the tok/s chip goes with the token
1256
1273
  // counts it sits next to.
1257
1274
  resetConversation(true);
1275
+ heldShellRunsRef.current = [];
1258
1276
  sessionRef.current?.switchSide('agent');
1259
1277
  setDecodeRate(undefined);
1260
1278
  setApprovals({ approved: 0, declined: 0 });
@@ -1748,8 +1766,8 @@ export function App() {
1748
1766
  const runShell = async (command) => {
1749
1767
  if (!bundle)
1750
1768
  return;
1751
- // Shell mode is "raw bash, no model" — the command echo stays in the scrollback but is
1752
- // kept out of the model history (its output, the `shell` message below, is UI-only too).
1769
+ // Shell mode is "raw bash, no model" — the echo and the `shell` message below are UI-only. The
1770
+ // model sees the run through the held copy, attached to the next prompt.
1753
1771
  const echo = { role: 'user', content: command, meta: true };
1754
1772
  setMessages(prev => [...prev, echo]);
1755
1773
  setStatus('busy');
@@ -1777,6 +1795,7 @@ export function App() {
1777
1795
  output: result.payload ?? '',
1778
1796
  };
1779
1797
  setMessages(prev => [...prev, shellMsg]);
1798
+ heldShellRunsRef.current = holdShellRun(heldShellRunsRef.current, await captureShellRun(command, result.exitCode ?? null, result.payload ?? ''));
1780
1799
  }
1781
1800
  catch (e) {
1782
1801
  setMessages(prev => [...prev, { role: 'error', content: e.message }]);
@@ -2223,6 +2242,13 @@ export function App() {
2223
2242
  // request to fetch a link inside it. The marker survives in `display`, keeping the user
2224
2243
  // bubble (and the input history entry) short while the model gets the full text.
2225
2244
  modelText = expandPastes(modelText, pastedTextsRef.current);
2245
+ // Chat's history is its own, and its tools could not act on a run anyway: held for the
2246
+ // agent side.
2247
+ if (heldShellRunsRef.current.length > 0 && modeRef.current !== 'chat') {
2248
+ const budget = shellRunBudget(sessionRef.current?.config.contextWindow);
2249
+ modelText = `${buildShellRunsBlock(heldShellRunsRef.current, budget)}\n\n${modelText}`;
2250
+ heldShellRunsRef.current = [];
2251
+ }
2226
2252
  }
2227
2253
  finally {
2228
2254
  setExpanding(null);
@@ -12,7 +12,7 @@ import { scrubDisplay, scrubOutput } from './scrub.js';
12
12
  import { DiffView } from './DiffView.js';
13
13
  import { changeLabel, formatDurationMs, toolLabel, toolTimer, toolVerb } from './format.js';
14
14
  import { contentWidth, hangingWrap } from './layout.js';
15
- import { foldSpilledReasoning, foldedAssistantFields } from './reasoningfold.js';
15
+ import { foldedAssistantFields, foldedLiveFields } from './reasoningfold.js';
16
16
  export function Scrollback({ messages, streaming, streamingReasoning, streamingTool, streamingNested = false, streamingNote = false, streamingCommand = false, pendingTool = '', pendingToolMs = 0, chromeRows = 0, showHeldWorked = true, }) {
17
17
  // The live (non-Static) region must never grow taller than the viewport: Ink can't
18
18
  // erase a frame taller than the screen, which is what produces the "duplicated
@@ -29,7 +29,7 @@ export function Scrollback({ messages, streaming, streamingReasoning, streamingT
29
29
  // and whose block is sized for that aside's shape.
30
30
  const folded = streamingNote
31
31
  ? { reasoning: streamingReasoning, content: streaming }
32
- : foldSpilledReasoning(streamingReasoning, streaming);
32
+ : foldedLiveFields(streamingReasoning, streaming);
33
33
  // Each block's fixed rows: its marginTop, plus the reasoning block's "Thinking" label. The block
34
34
  // builders are the memoized ones: a render where this block's text (or width, or the terminal's
35
35
  // columns) is unchanged reuses the rows it built last time instead of re-parsing the same text.
@@ -0,0 +1,24 @@
1
+ // A model reads its own earlier `content` as its own voice, and a carried continuation tail (#284)
2
+ // puts reika's marker there: `[reika: N chars of your earlier reasoning trimmed …]`. A verbose model
3
+ // then opens a LATER reply the same way — observed on mimo-v2.6-pro (#745): a reply with its own
4
+ // tool call opening with `[reika: 26476 chars …]` (the harness had written 26465) and an invented
5
+ // `[tool result omitted: repeated from earlier]`, a stub reika never emits. Both rendered as the
6
+ // answer. So the match is on the shape, not on reika's exact strings: the copy is never exact.
7
+ //
8
+ // Head only, line by line: that is where the tail template puts the marker, and further down the
9
+ // same text is just as likely the model quoting reika's markers on purpose (a review of this code).
10
+ // Display/transcript only, like the reasoning fold — the Message the loop keeps and sends back is
11
+ // untouched.
12
+ const HARNESS_ECHO_LINE = /^\s*(?:\[reika:[^\]\n]*\]|\(reika:[^)\n]*\)|\[tool (?:result|output)[^\]\n]*\])\s*$/;
13
+ export function stripHarnessEcho(content) {
14
+ let rest = content;
15
+ for (;;) {
16
+ const lead = rest.match(/^\s*/)[0].length;
17
+ const nl = rest.indexOf('\n', lead);
18
+ const line = nl < 0 ? rest : rest.slice(0, nl);
19
+ if (!line.trim() || !HARNESS_ECHO_LINE.test(line))
20
+ break;
21
+ rest = nl < 0 ? '' : rest.slice(nl + 1);
22
+ }
23
+ return rest === content ? content : rest.trimStart();
24
+ }
@@ -1,3 +1,4 @@
1
+ import { stripHarnessEcho } from './harnessecho.js';
1
2
  // The endpoint's reasoning parser ends the thinking channel at the first literal think tag it sees
2
3
  // in the stream — including one the model wrote *inside* its own reasoning, e.g. while quoting
3
4
  // `--reasoning-format`, or describing this very bug. The parser consumes the tag, ends
@@ -51,6 +52,12 @@ export function foldedAssistantFields(msg) {
51
52
  const folded = foldSpilledReasoning(msg.reasoning, msg.content);
52
53
  return {
53
54
  ...(folded.reasoning ? { reasoning: folded.reasoning } : {}),
54
- content: folded.content,
55
+ content: stripHarnessEcho(folded.content),
55
56
  };
56
57
  }
58
+ // The live region's half of the same display pass, so a streamed reply that opens on a copied
59
+ // harness marker never shows it and then drops it on commit.
60
+ export function foldedLiveFields(reasoning, content) {
61
+ const folded = foldSpilledReasoning(reasoning, content);
62
+ return { reasoning: folded.reasoning, content: stripHarnessEcho(folded.content) };
63
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexwkleung/reika",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",