@tiens.nguyen/gu-cli 1.0.841 → 1.0.843

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.
@@ -324,86 +324,6 @@ export function findDevInstalls({ roots = browserRoots(), extDir = extensionDir(
324
324
  return found;
325
325
  }
326
326
 
327
- // THE PUBLISHED EXTENSION, FOUND IN CHROME'S OWN RECORDS (#386, GitHub #176). Its ID is fixed by the
328
- // store (the last part of the store URL), so a profile has it when its preferences list that ID
329
- // from anywhere but an unpacked folder. Disabled is told apart: it is installed but cannot connect.
330
- export const STORE_EXTENSION_ID = "ldfcjapmdbgdkdhlbdkbkiankneabagj";
331
-
332
- export function findStoreInstalls({ roots = browserRoots(), id = STORE_EXTENSION_ID } = {}) {
333
- const found = [];
334
- for (const { browser, dir } of roots) {
335
- let profiles = [];
336
- try {
337
- profiles = readdirSync(dir).filter((p) => p === "Default" || /^Profile \d+$/.test(p));
338
- } catch {
339
- continue;
340
- }
341
- for (const profile of profiles) {
342
- for (const file of ["Secure Preferences", "Preferences"]) {
343
- let e;
344
- try {
345
- e = JSON.parse(readFileSync(join(dir, profile, file), "utf8"))?.extensions?.settings?.[id];
346
- } catch {
347
- continue;
348
- }
349
- if (!e || UNPACKED.has(e.location)) continue;
350
- const reasons = Array.isArray(e.disable_reasons) ? e.disable_reasons.length : Number(e.disable_reasons) || 0;
351
- found.push({ browser, profile, id, disabled: e.state === 0 || reasons > 0 });
352
- break;
353
- }
354
- }
355
- }
356
- return found;
357
- }
358
-
359
- /**
360
- * Where the install stands, and what to tell the user — PURE, so every stage can be tested.
361
- * → { stage, lines }: "remove-dev" (a developer copy would block the store one, #148), "add" (not
362
- * in Chrome yet), "enable" (added but switched off), "connect" (added, not connected yet), "done".
363
- */
364
- export function installStage({ dev = [], store = [], status = {}, storeUrl = STORE_URL } = {}) {
365
- if (status.connected && status.installType === "normal") {
366
- return { stage: "done", lines: [`✓ gu browser is connected (Chrome Web Store, v${status.version ?? "?"}).`] };
367
- }
368
- if (dev.length) {
369
- return {
370
- stage: "remove-dev",
371
- lines: [
372
- "1. First remove the developer copy of gu browser — only one can connect.",
373
- " In chrome://extensions (gu opened it), click Remove on this one:",
374
- ...dev.map((d) => ` ${d.browser} · ${d.profile} · ID ${d.id}`),
375
- " Waiting for it to be removed…",
376
- ],
377
- };
378
- }
379
- if (!store.length) {
380
- return {
381
- stage: "add",
382
- lines: [
383
- "1. Add gu browser to Chrome: on its store page, click \"Add to Chrome\".",
384
- ` ${storeUrl}`,
385
- " (gu opened the page for you.) Waiting for it to be added…",
386
- ],
387
- };
388
- }
389
- if (store.every((s) => s.disabled)) {
390
- return {
391
- stage: "enable",
392
- lines: [
393
- "2. gu browser is added but switched off. In chrome://extensions, turn it on.",
394
- " Waiting for it to be turned on…",
395
- ],
396
- };
397
- }
398
- return {
399
- stage: "connect",
400
- lines: [
401
- "2. gu browser is added. Waiting for it to connect to gu…",
402
- " Keep Chrome open — it connects within 30 s, or click its icon → Connect now.",
403
- ],
404
- };
405
- }
406
-
407
327
  // gu's own leftovers of the developer install, in ~/.gonext.
408
328
  export function localLeftovers() {
409
329
  return [extensionDir(), statePath(), seenPath(), logPath()].filter((p) => existsSync(p));
@@ -8312,8 +8312,13 @@ _BROWSER_LINE = (
8312
8312
 
8313
8313
  # Background shells (task #360). Never `&` (refused) — background=True is the way to say it.
8314
8314
  _BG_LINE = ("A LONG job (build, deploy, big test run) → run_command(…, background=True), then "
8315
- "shell_output(<id>, wait_seconds=…) to wait for it; a command still running at its "
8316
- "timeout moves to the background by itself instead of being killed.\n")
8315
+ "shell_output(<id>, wait_seconds=540) to wait for it in ONE call — never several short "
8316
+ "polls; a build whose result you need next is simpler as one run_command(…, "
8317
+ "timeout_seconds=600). A command still running at its timeout moves to the background "
8318
+ "by itself instead of being killed. Setup every command needs (exports) goes ONCE in "
8319
+ "<workspace>/.gonext/env, which is sourced before each command. A recipe that WORKED "
8320
+ "after effort (a login, build flags, a deploy path) or a short project summary goes as "
8321
+ "ONE line in <workspace>/.gonext/notes.md, shown at the start of every later turn.\n")
8317
8322
 
8318
8323
 
8319
8324
  # What to do instead, said where quoting broke — in gu's own pre-check (an unbalanced quote never
@@ -8438,6 +8443,29 @@ def _test_commands_line(root: str) -> str:
8438
8443
  return line
8439
8444
 
8440
8445
 
8446
+ _WS_NOTES_CAP = 1500
8447
+
8448
+
8449
+ def _ws_notes_line(root: str, cap: int = _WS_NOTES_CAP) -> str:
8450
+ """<workspace>/.gonext/notes.md shown in every turn's context (GitHub #184, turn review #389):
8451
+ a recipe that worked (turn #7 spent ~15 steps rediscovering turn #6's App Store login) and a
8452
+ short project summary (turns #4/#5/#8 each re-read the same docs). Capped; "" when absent."""
8453
+ if not root:
8454
+ return ""
8455
+ p = os.path.join(root, ".gonext", "notes.md")
8456
+ try:
8457
+ with open(p, encoding="utf-8", errors="replace") as fh:
8458
+ txt = fh.read(cap + 1).strip()
8459
+ except OSError:
8460
+ return ""
8461
+ if not txt:
8462
+ return ""
8463
+ if len(txt) > cap:
8464
+ txt = txt[:cap].rstrip() + " …(cut — keep notes.md short)"
8465
+ return (" WORKSPACE NOTES (.gonext/notes.md — recipes and facts saved by earlier turns; use them "
8466
+ "before rediscovering):\n" + "\n".join(f" {l}" for l in txt.splitlines()) + "\n")
8467
+
8468
+
8441
8469
  def _test_digest(output: str, cwd: str = "") -> str:
8442
8470
  """gu_test_digest.digest, or "" if the module is missing — a summary must never fail a command."""
8443
8471
  try:
@@ -9895,6 +9923,25 @@ def _patch_dotted_imports() -> bool:
9895
9923
  return True
9896
9924
 
9897
9925
 
9926
+ _SANDBOX_PREIMPORTS = "import json\nimport re\nimport base64\n"
9927
+
9928
+
9929
+ def _preimport_sandbox(agent) -> bool:
9930
+ """json, re and base64 are already imported in the agent's code sandbox (GitHub #183, turn
9931
+ review #389): a step that used json.loads without its own `import json` failed and cost a
9932
+ whole step. Runs through the executor's own import check, so nothing new is allowed. False
9933
+ when there is no Python executor (ToolCallingAgent) or the import is refused."""
9934
+ ex = getattr(agent, "python_executor", None)
9935
+ if ex is None:
9936
+ return False
9937
+ try:
9938
+ ex(_SANDBOX_PREIMPORTS)
9939
+ return True
9940
+ except Exception as e: # noqa: BLE001
9941
+ _log(f"sandbox pre-import skipped: {type(e).__name__}: {e}")
9942
+ return False
9943
+
9944
+
9898
9945
  def _run_state_cwd() -> str:
9899
9946
  """The folder the last shell line ended in, this turn — or ""."""
9900
9947
  p = _RUN_STATE["path"]
@@ -9916,9 +9963,22 @@ def _run_state_set_cwd(cwd: str) -> None:
9916
9963
  pass
9917
9964
 
9918
9965
 
9966
+ def _ws_env_file(root: str = "") -> str:
9967
+ """<workspace>/.gonext/env when it exists, else "" (GitHub #181, turn review #389): the setup
9968
+ every command needs (`export DEVELOPER_DIR=…; export LC_ALL=…`) is written there ONCE and
9969
+ sourced before each run_command line, instead of being repeated on every call."""
9970
+ try:
9971
+ root = root or _default_ws_root()
9972
+ except Exception: # noqa: BLE001
9973
+ return ""
9974
+ p = os.path.join(root or "", ".gonext", "env")
9975
+ return p if root and os.path.isfile(p) else ""
9976
+
9977
+
9919
9978
  def _run_state_wrapper() -> str:
9920
- """The outer script: $1 the line, $2 the exit file, $3 the state file."""
9921
- return ('[ -f "$3" ] && . "$3" >/dev/null 2>&1; '
9979
+ """The outer script: $1 the line, $2 the exit file, $3 the state file, $4 the env file."""
9980
+ # $4: the workspace's .gonext/env (GitHub #181) — sourced first, so this turn's own exports win.
9981
+ return ('[ -n "$4" ] && [ -f "$4" ] && . "$4" >/dev/null 2>&1; [ -f "$3" ] && . "$3" >/dev/null 2>&1; '
9922
9982
  "trap '__gu_rc=$?; echo $__gu_rc > \"$2\"; "
9923
9983
  f"export -p | grep -vE \"{_RUN_STATE_SKIP}\" > \"$3.tmp\" 2>/dev/null && mv -f \"$3.tmp\" \"$3\"; "
9924
9984
  "pwd > \"$3.cwd\"; exit $__gu_rc' EXIT; "
@@ -11266,6 +11326,7 @@ def run_agent_chat(cfg):
11266
11326
  _ws_current_line
11267
11327
  + f" Other registered workspaces (use only if the user names them): {_ws_names}\n"
11268
11328
  + _ws_tests_line
11329
+ + _ws_notes_line(_WS_ACTIVE or "")
11269
11330
  + _ws_servers_line
11270
11331
  + f" Current folder contents:\n"
11271
11332
  + "\n".join(f" {line}" for line in _ws_overview.splitlines()) + "\n"
@@ -12336,10 +12397,14 @@ def run_agent_chat(cfg):
12336
12397
  if _completion_gate["nudged"]:
12337
12398
  return True # already nudged once this turn — accept, never loop
12338
12399
  ans = str(final_answer if final_answer is not None else "")
12339
- if _PUNT_RE.search(ans):
12400
+ _m = _PUNT_RE.search(ans)
12401
+ if _m:
12340
12402
  _completion_gate["nudged"] = True
12403
+ # GitHub #185: quote the words that tripped the gate, so a finished task is fixed by
12404
+ # rewording that phrase instead of redoing the work (turn review #389, item 7).
12341
12405
  raise ValueError(
12342
- "NOT DONE YET — your answer hands the work back to the user. Do ONE of these, "
12406
+ f"NOT DONE YET — your answer hands the work back to the user (it says \"{_m.group(0)}\"). "
12407
+ "If the work IS done and verified, just drop that phrase and answer again. Otherwise do ONE of these, "
12343
12408
  "then call final_answer:\n"
12344
12409
  " 1) DO it yourself with your tools, VERIFY it — run it, run the test, or "
12345
12410
  "re-read the file to confirm the change took — and answer WITH that evidence; OR\n"
@@ -15387,7 +15452,7 @@ def run_agent_chat(cfg):
15387
15452
  if (_scan and not _ps) else []
15388
15453
  _builtin = sorted({w for w in _words if w in _SHELL_STATE_BUILTINS})
15389
15454
  _use_shell = bool(_scan) and (_ps or _shell_needed(_scan) or bool(_builtin) or bool(
15390
- _RUN_STATE["path"] and os.path.exists(_RUN_STATE["path"])))
15455
+ _RUN_STATE["path"] and os.path.exists(_RUN_STATE["path"])) or bool(_ws_env_file()))
15391
15456
  _bg_err = ((_ps_background_error(_scan) if _ps else _shell_background_error(_scan))
15392
15457
  if _use_shell else None)
15393
15458
  if _bg_err:
@@ -15602,7 +15667,8 @@ def run_agent_chat(cfg):
15602
15667
  # Git Bash reads C:/x, not C:\x, inside the line it runs.
15603
15668
  _fs = (lambda x: x.replace("\\", "/")) if _IS_WINDOWS else (lambda x: x)
15604
15669
  argv = [_shell_bin, "-c", _run_state_wrapper(),
15605
- _fs(_shell_bin), _cmd_text, _fs(exit_path), _fs(_run_state_path())]
15670
+ _fs(_shell_bin), _cmd_text, _fs(exit_path), _fs(_run_state_path()),
15671
+ _fs(_ws_env_file())]
15606
15672
  else:
15607
15673
  argv, _attrib_note = _with_attribution(argv, _attribution_settings(wd))
15608
15674
  if _attrib_note:
@@ -15943,7 +16009,14 @@ def run_agent_chat(cfg):
15943
16009
  if _dg:
15944
16010
  head += "\n" + _dg
15945
16011
  tail_note = ""
15946
- if not new.strip() and int(sh.get("read_offset") or 0) == 0:
16012
+ if not new.strip() and st["state"] != "running" and int(sh.get("read_offset") or 0) > 0:
16013
+ # GitHub #182: the end was read by an earlier poll — say how it ended anyway,
16014
+ # rather than "No new output" that sends the agent to grep the log.
16015
+ lt = _file_tail(str(sh.get("log") or ""), 3000).strip()
16016
+ if lt:
16017
+ tail_note = (f"\nIt has ended; the end of its output (read before):\n"
16018
+ f"{_ws_distill_output(lt)}")
16019
+ elif not new.strip() and int(sh.get("read_offset") or 0) == 0:
15947
16020
  lf = _shell_log_file(str(sh.get("command") or ""), str(sh.get("workdir") or ""))
15948
16021
  lt = _file_tail(lf).strip() if lf else ""
15949
16022
  if lt:
@@ -16395,7 +16468,7 @@ def run_agent_chat(cfg):
16395
16468
  # so this wall clock is a last-resort backstop, not the primary guard.
16396
16469
  agent_kwargs["executor_kwargs"] = {"timeout_seconds": 660}
16397
16470
  agent_kwargs["additional_authorized_imports"] = [
16398
- "json", "base64", "urllib", "urllib.request", "urllib.error"
16471
+ "json", "base64", "re", "urllib", "urllib.request", "urllib.error"
16399
16472
  ]
16400
16473
  # THE SYSTEM PROMPT IS THE API'S SCAFFOLD (task #246): the stock templates are loaded
16401
16474
  # for everything else (planning, final-answer, managed agents) and ONLY system_prompt
@@ -16421,6 +16494,7 @@ def run_agent_chat(cfg):
16421
16494
  _log(f"prompt scaffold code-agent {'local file' if _scaffold_source != 'api' else f'v{_scaffold_version}'}")
16422
16495
  agent = _ToolAgent(**agent_kwargs)
16423
16496
  _agent_ref["a"] = agent # let step_callback trim this agent's step memory (#63)
16497
+ _preimport_sandbox(agent)
16424
16498
  # At the step budget the run ends WITHOUT final_answer (_maxsteps_partial hit). Offer
16425
16499
  # to keep going instead of dead-ending (task #80): a terminal user says Yes → extend
16426
16500
  # the budget to a large ceiling and CONTINUE with the existing memory (reset=False,
package/gu-repl.mjs CHANGED
@@ -139,7 +139,7 @@ import {
139
139
  import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
140
140
  import { isScaffoldStep, isGroupableStep, stepGroupMark, stepGroupRows, relativizePaths } from "./step-group.mjs";
141
141
  import { clearLogsNoticeText } from "./clear-logs.mjs";
142
- import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, findStoreInstalls, installStage, openExtensionsPage, openStorePage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
142
+ import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
143
143
  import { commandLogFile, killShell, logTail, markAnnounced, readShells, recapQuestion, shellsToRecap, statusText as shellStatusText, renderShellDetails, shellPanelRows, shellPickerLabel, shellState, shellsNotice } from "./shell-details.mjs";
144
144
  import { discoverSkills, matchSkillCommand } from "./skills.mjs";
145
145
  import { appendNew, archivePathFor, archivedWorkspaceKey, markReset, seedArchive } from "./conversation-archive.mjs";
@@ -9620,100 +9620,30 @@ function printShellDetails(rec) {
9620
9620
  // /browser (#363): the extension's connection, else how to install it.
9621
9621
  async function showBrowser() {
9622
9622
  const st = await bridgeStatus().catch(() => ({ running: false, connected: false }));
9623
- const lines = browserReport(st, { allowed: allowedIn(resolve(process.cwd())), storeInstalled: findStoreInstalls().length > 0 });
9623
+ const lines = browserReport(st, { allowed: allowedIn(resolve(process.cwd())) });
9624
9624
  console.log("");
9625
9625
  for (const [i, l] of lines.entries()) console.log(GUTTER + (i === 0 && st.connected ? accent(l) : l.startsWith("⚠") ? yellow(l) : dim(l)));
9626
9626
  console.log("");
9627
9627
  paintBar();
9628
9628
  }
9629
9629
 
9630
- // /browser install (#150; guided since #386, GitHub #176): the published extension, for the agent to
9631
- // use YOUR Chrome — the way Claude Code sets up its Chrome extension. gu walks it through to the end:
9632
- // a developer copy is removed first (it would block the store one, #148), then the store page is
9633
- // opened, and the panel in place of the input box (#384) shows each stage live until the store copy
9634
- // is CONNECTED — or Esc stops waiting. gu's own window still needs none of this.
9630
+ // /browser install (#150): the extension, for the agent to use YOUR Chrome. Optional — gu's own
9631
+ // window needs nothing. The store page once published; until then the developer way.
9635
9632
  async function browserInstall() {
9636
- if (listPickerActive || approvalActive) return;
9637
- const done = (line) => {
9638
- console.log("\n" + GUTTER + line + "\n");
9639
- paintBar();
9640
- };
9633
+ let folder = extensionDir();
9641
9634
  if (!STORE_URL) {
9642
- // No published listing configured (GU_BROWSER_STORE_URL=""): the developer way, as before.
9643
- let folder = extensionDir();
9644
9635
  try {
9645
9636
  folder = installExtensionFiles();
9646
9637
  } catch (e) {
9647
9638
  console.log(GUTTER + yellow(`could not copy the extension to ${folder}: ${e.message}`));
9648
9639
  }
9649
- await bridgeStatus().catch(() => null);
9650
- console.log("");
9651
- for (const l of installSteps(folder, process.platform, "")) console.log(GUTTER + dim(l));
9652
- if (helpInstall(folder)) console.log(GUTTER + dim("(Opened chrome://extensions and copied the folder to your clipboard.)"));
9653
- console.log("");
9654
- paintBar();
9655
- return;
9656
9640
  }
9657
- let status = await bridgeStatus().catch(() => ({ running: false, connected: false }));
9658
- const opened = new Set();
9659
- const state = () => {
9660
- const st = installStage({ dev: findDevInstalls(), store: findStoreInstalls(), status });
9661
- // Open the page each stage needs, once.
9662
- if (st.stage === "remove-dev" && !opened.has("ext")) { opened.add("ext"); openExtensionsPage(); }
9663
- if (st.stage === "add" && !opened.has("store")) { opened.add("store"); openStorePage(); }
9664
- if (st.stage === "enable" && !opened.has("ext2")) { opened.add("ext2"); openExtensionsPage(); }
9665
- return st;
9666
- };
9667
- let st = state();
9668
- if (st.stage === "done") return done(accent(st.lines[0]));
9669
- if (!barPinned()) {
9670
- // No zone to wait in: say what to do once.
9671
- console.log("");
9672
- for (const l of st.lines) console.log(GUTTER + dim(l));
9673
- console.log(GUTTER + dim("Then type /browser — it should say connected.") + "\n");
9674
- paintBar();
9675
- return;
9676
- }
9677
- let polling = false;
9678
- const poll = setInterval(async () => {
9679
- if (polling) return;
9680
- polling = true;
9681
- try {
9682
- status = await bridgeStatus({ waitMs: 0 }).catch(() => status);
9683
- st = state();
9684
- if (st.stage === "done") {
9685
- clearInterval(poll);
9686
- closeZonePanel();
9687
- done(accent(st.lines[0]) + dim(" The agent can use your Chrome now."));
9688
- }
9689
- } finally {
9690
- polling = false;
9691
- }
9692
- }, 2000);
9693
- openZonePanel({
9694
- refreshMs: 1000,
9695
- rows: (width) => {
9696
- // A row the panel would clip is WRAPPED instead: the store link is 84 characters, and a link
9697
- // cut short at 80 columns cannot be copied.
9698
- const room = Math.max(20, width - 1 - GUTTER.length);
9699
- const wrap = (l) => {
9700
- const out = [];
9701
- for (let rest = l; rest.length; rest = rest.slice(room)) out.push(rest.slice(0, room));
9702
- return out.length ? out : [""];
9703
- };
9704
- return [
9705
- GUTTER + bold(accent("Install gu browser")) + dim(" — so the agent can use your own Chrome"),
9706
- "",
9707
- ...st.lines.flatMap((l) => wrap(/https?:\/\//.test(l) ? l.trim() : l).map((r) => GUTTER + (/^\d\./.test(l) ? r : dim(r)))),
9708
- "",
9709
- GUTTER + dim("Esc to stop waiting · /browser install picks up where you left off"),
9710
- ];
9711
- },
9712
- onClose: () => {
9713
- clearInterval(poll);
9714
- if (st.stage !== "done") done(dim("(stopped waiting — /browser install picks up where you left off)"));
9715
- },
9716
- });
9641
+ await bridgeStatus().catch(() => null); // running, so a fresh install has something to connect to
9642
+ console.log("");
9643
+ for (const l of installSteps(folder)) console.log(GUTTER + dim(l));
9644
+ if (STORE_URL ? openExtensionsPage() : helpInstall(folder)) console.log(GUTTER + dim(STORE_URL ? "(Opened Chrome.)" : "(Opened chrome://extensions and copied the folder to your clipboard.)"));
9645
+ console.log("");
9646
+ paintBar();
9717
9647
  }
9718
9648
 
9719
9649
  // /browser cleanup (#145, #147): remove the developer (unpacked) install so the Chrome Web Store
@@ -10830,11 +10760,7 @@ async function approvalPrompt(command) {
10830
10760
  process.stdout.write(
10831
10761
  "\n" + yellow("🌐 Allow gu to use a web browser?") + dim(" (no answer in ~3 min = Yes, this time)") + "\n" +
10832
10762
  dim(` It wants to: ${what || "open a page"}`) + "\n" +
10833
- dim(" In your Chrome if the gu extension is there, else in gu's own Chrome window.") + "\n" +
10834
- // #386: the way to "your Chrome", said where the question is asked.
10835
- (STORE_URL && !findStoreInstalls().length
10836
- ? dim(" To use your own Chrome (your logins): /browser install adds the gu extension.") + "\n"
10837
- : "")
10763
+ dim(" In your Chrome if the gu extension is there, else in gu's own Chrome window.") + "\n"
10838
10764
  );
10839
10765
  // "Yes, this time" is THE default (#380, GitHub #167): highlighted, so Enter allows it once, and
10840
10766
  // also what an unanswered question becomes — the countdown used to sit on "No", which read as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.841",
3
+ "version": "1.0.843",
4
4
  "description": "Gu CLI — the gu terminal plus the local worker that runs agent / OCR / PDF / embedding jobs on your Mac (Ollama / MLX / OpenAI-compatible).",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/shell-details.mjs CHANGED
@@ -368,13 +368,23 @@ export function markAnnounced(ids, { path = shellsPath() } = {}) {
368
368
  }
369
369
 
370
370
  /** The recap question the terminal asks for finished shells. */
371
- export function recapQuestion(entries) {
371
+ export function recapQuestion(entries, { tailLines = 40 } = {}) {
372
372
  const parts = entries.map(({ rec, st }) =>
373
373
  `shell ${rec.id} ${statusText(st)} after ${fmtRuntime(st.runtime)} (${String(rec.command ?? "").replace(/\s+/g, " ").trim().slice(0, 120)})`);
374
374
  const ids = entries.map(({ rec }) => `shell_output('${rec.id}')`).join(", ");
375
+ // GitHub #180 (turn review #389): every recap turn spent its first step on shell_output just to
376
+ // see the result. The end of each shell's output goes in the question itself; several finished
377
+ // shells share one question.
378
+ const tails = entries.map(({ rec }) => {
379
+ const t = rec.log ? logTail(rec.log, { lines: tailLines }) : [];
380
+ return t.length ? `\n--- end of shell ${rec.id} output ---\n${t.map((l) => l.slice(0, 300)).join("\n")}` : "";
381
+ }).join("");
382
+ const read = tails ? `The last lines of the output are below — call ${ids} only if you need more.`
383
+ : `Read the result with ${ids}.`;
375
384
  // #376: come back to the work, not only report on it — a failed build is the next thing to fix,
376
385
  // a finished one may be the step before the next; a recap only when nothing is left to do.
377
386
  return `[gu: background ${entries.length === 1 ? "shell" : "shells"} finished — ${parts.join("; ")}] `
378
- + `Read the result with ${ids}. If it failed, find out why and fix it. If it was a step of the task you `
379
- + `were doing, carry on with the next step now. If nothing is left to do, tell me in one or two lines what happened.`;
387
+ + `${read} If it failed, find out why and fix it. If it was a step of the task you `
388
+ + `were doing, carry on with the next step now. If nothing is left to do, tell me in one or two lines what happened.`
389
+ + tails;
380
390
  }