@tiens.nguyen/gu-cli 1.0.842 → 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.
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.842",
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
  }