@tiens.nguyen/gu-cli 1.0.940 → 1.0.942

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/budget-view.mjs CHANGED
@@ -79,7 +79,7 @@ export function budgetTable(rows, now = new Date()) {
79
79
 
80
80
  /**
81
81
  * What /budget prints, as { tone: "ok" | "warn" | "error", lines }. `site` is the web base
82
- * (siteUrl(): https://gu.getmarsic.cc or GU_SITE_URL).
82
+ * (siteUrl(): https://gucli.com or GU_SITE_URL).
83
83
  */
84
84
  export function budgetLines(result, { site, now = new Date() } = {}) {
85
85
  const base = String(site || "https://gu.getmarsic.cc").replace(/\/+$/, "");
package/cli-token.mjs CHANGED
@@ -107,7 +107,7 @@ export const TOKEN_PREFIX = "gu1";
107
107
  export const STALE_AFTER_DAYS = 30;
108
108
  export const RENEW_EVERY_MS = { client: 86_400_000, expert: 7 * 86_400_000 };
109
109
  /** Where the notices send people. Overridable for staging. */
110
- export const DEFAULT_SITE = "https://gu.getmarsic.cc";
110
+ export const DEFAULT_SITE = "https://gucli.com"; // GH #602: the site people know; gu.getmarsic.cc only redirects
111
111
 
112
112
  export function publicKey(env = process.env) {
113
113
  return String(env.GU_CLI_TOKEN_PUBLIC_KEY ?? "").trim() || EMBEDDED_PUBLIC_KEY;
@@ -692,6 +692,42 @@ export function parseLicenseFlag(argv) {
692
692
  return "";
693
693
  }
694
694
 
695
+ /**
696
+ * GH #603: `gu --cloud <code>` — the Cloud link an admin sent (the page at gucli.com/cloud/<code>
697
+ * shows the command). The whole link pasted works too. → "CL-XXXXXXXXXXXX", or "" when absent or
698
+ * not a link code.
699
+ */
700
+ export function parseCloudFlag(argv) {
701
+ const args = Array.isArray(argv) ? argv : [];
702
+ let raw = "";
703
+ for (let i = 0; i < args.length; i += 1) {
704
+ const a = String(args[i] ?? "");
705
+ if (a === "--cloud") raw = String(args[i + 1] ?? "");
706
+ else if (a.startsWith("--cloud=")) raw = a.slice("--cloud=".length);
707
+ }
708
+ const m = /(?:^|\/)(CL-[A-Z0-9]{12})\/?$/i.exec(raw.trim());
709
+ return m ? m[1].toUpperCase() : "";
710
+ }
711
+
712
+ /**
713
+ * GH #603: is this Cloud link usable? Asks the hosted API's public lookup. → { ok, why, email }.
714
+ * Soft on a network failure (ok: true, unverified: true) — the claim after sign-in checks again.
715
+ */
716
+ export async function checkCloudLink(code, { hostedBase, fetchImpl = fetch, timeoutMs = 8000 } = {}) {
717
+ try {
718
+ const r = await fetchImpl(`${String(hostedBase).replace(/\/+$/, "")}/api/cloud-links/${encodeURIComponent(code)}`, {
719
+ signal: AbortSignal.timeout(timeoutMs),
720
+ });
721
+ const body = await r.json().catch(() => ({}));
722
+ if (r.status === 404) return { ok: false, why: "That Cloud link doesn't exist — check you copied all of it." };
723
+ if (!r.ok) return { ok: true, unverified: true, why: "" };
724
+ if (!body.active) return { ok: false, why: "That Cloud link was removed. Ask the person who sent it for a new one." };
725
+ return { ok: true, why: "", email: String(body.email ?? "") };
726
+ } catch {
727
+ return { ok: true, unverified: true, why: "" };
728
+ }
729
+ }
730
+
695
731
  /**
696
732
  * What a first run DOES about the mode question.
697
733
  *
@@ -704,7 +740,9 @@ export function parseLicenseFlag(argv) {
704
740
  * what the license-gated menu is for. Pure, so the rule is a test row rather than something to
705
741
  * re-read in the REPL.
706
742
  */
707
- export function resolveFirstRunMode({ licenseToken, expertAvailable } = {}) {
743
+ export function resolveFirstRunMode({ licenseToken, expertAvailable, cloudCode = "" } = {}) {
744
+ // GH #603: a Cloud link decides it — no menu, no private default.
745
+ if (String(cloudCode ?? "").trim()) return { ask: false, mode: "client" };
708
746
  if (String(licenseToken ?? "").trim()) return { ask: true, mode: null };
709
747
  if (expertAvailable) return { ask: false, mode: "client-expert" };
710
748
  return { ask: false, mode: "client" };
package/device-login.mjs CHANGED
@@ -115,11 +115,24 @@ export async function saveWorkerKey({ apiBase = DEFAULT_API_BASE, workerKey, log
115
115
  return { apiBase: base, workerKey: key, envFile };
116
116
  }
117
117
 
118
- function openBrowser(url) {
119
- const cmd =
120
- platform() === "darwin" ? "open" : platform() === "win32" ? "start" : "xdg-open";
118
+ /**
119
+ * How to open `url` in the default browser → [command, args].
120
+ *
121
+ * GH #603: Windows used execFile("start", [url]) — but `start` is a cmd.exe built-in, not a program,
122
+ * so it failed with ENOENT and the sign-in page never opened (the user had to copy the printed URL).
123
+ * explorer.exe opens a URL in the default browser, as browser-command.mjs already does, and — unlike
124
+ * `cmd /c start` — never reads the URL's & as a command separator.
125
+ */
126
+ export function browserOpenCommand(url, os = platform()) {
127
+ if (os === "darwin") return ["open", [url]];
128
+ if (os === "win32") return ["explorer.exe", [url]];
129
+ return ["xdg-open", [url]];
130
+ }
131
+
132
+ export function openBrowser(url) {
133
+ const [cmd, args] = browserOpenCommand(url);
121
134
  try {
122
- execFile(cmd, [url], () => {}); // best-effort; the URL is also printed
135
+ execFile(cmd, args, () => {}); // best-effort; the URL is also printed
123
136
  } catch {
124
137
  /* the user can open it manually */
125
138
  }
@@ -9229,7 +9229,7 @@ def _ws_ps_command_risk(scan, denyset, wd="", allowset=None, roots=None):
9229
9229
  return (None, None, None)
9230
9230
 
9231
9231
 
9232
- def _with_attribution_text(command, scan, settings):
9232
+ def _with_attribution_text(command, scan, settings, powershell=False):
9233
9233
  """_with_attribution for a SHELL line: the co-author trailer is inserted into the text right
9234
9234
  after each top-level `git … commit` word. → (command, note). A gh pr create body written as a
9235
9235
  heredoc cannot be appended to safely, so it is left alone and said so in the note."""
@@ -9251,6 +9251,31 @@ def _with_attribution_text(command, scan, settings):
9251
9251
  notes.append(f"co-author trailer added ({name})")
9252
9252
  if settings.get("pr") and any(c["argv"][:3] == ["gh", "pr", "create"] for c in cmds):
9253
9253
  notes.append("PR footer not added (shell form)")
9254
+ # A comment's --body in a bash line: its literal text is re-quoted with the co-author line added.
9255
+ # Only when the word has no $ or ` (the shell would expand those) and only for bash: PowerShell
9256
+ # quotes differently. A body from a file or heredoc is left alone, and the note says so.
9257
+ footer = _comment_footer(settings)
9258
+ if footer and not powershell:
9259
+ edits = []
9260
+ for c in cmds:
9261
+ verb = _gh_verb(c["argv"])
9262
+ if verb not in _GH_COMMENTS:
9263
+ continue
9264
+ at = _body_at(c["argv"])
9265
+ if not at or footer in at[1] or (email and email.lower() in at[1].lower()):
9266
+ if not at:
9267
+ notes.append(f"co-author line not added ({verb[0]} {verb[1]} body from a file)")
9268
+ continue
9269
+ k, body, inline = at
9270
+ a, b = c["spans"][k]
9271
+ if "$" in command[a:b] or "`" in command[a:b]:
9272
+ notes.append(f"co-author line not added ({verb[0]} {verb[1]} body uses $ or `)")
9273
+ continue
9274
+ new = body.rstrip() + f"\n\n{footer}"
9275
+ edits.append((a, b, _shlex.quote("--body=" + new if inline else new)))
9276
+ notes.append(f"co-author line added to the {verb[0]} {verb[1]} ({name})")
9277
+ for a, b, text in sorted(edits, reverse=True):
9278
+ command = command[:a] + text + command[b:]
9254
9279
  return command, "; ".join(notes)
9255
9280
 
9256
9281
 
@@ -10182,9 +10207,35 @@ def _ws_delete_outside_reason(argv, wd, roots=None):
10182
10207
  #
10183
10208
  # Settings, ~/.gu/settings.json then <project>/.gu/settings.json (the project wins):
10184
10209
  # "attribution": {"commit": true, "pr": true, "name": "gu", "email": "…"}
10185
- _ATTRIBUTION_DEFAULT = {"commit": True, "pr": True, "name": "gu",
10210
+ _ATTRIBUTION_DEFAULT = {"commit": True, "pr": True, "comment": True, "name": "gu",
10186
10211
  "email": "334027377+gu-marsic-agent@users.noreply.github.com"}
10187
10212
  _PR_FOOTER = "Generated with gu"
10213
+ # Comments and issues gu writes on GitHub end with the same co-author line as its commits, so a board
10214
+ # (sunday#37) can show gu next to the person who posted them. "comment": false in the settings turns it off.
10215
+ _GH_COMMENTS = (("issue", "comment"), ("pr", "comment"), ("issue", "create"))
10216
+
10217
+
10218
+ def _gh_verb(argv):
10219
+ """("pr", "create"), ("issue", "comment")… for a gh command, else None."""
10220
+ if len(argv) >= 3 and os.path.basename(str(argv[0])).lower() in ("gh", "gh.exe"):
10221
+ return (argv[1], argv[2])
10222
+ return None
10223
+
10224
+
10225
+ def _comment_footer(settings):
10226
+ name = str(settings.get("name") or "").strip()
10227
+ email = str(settings.get("email") or "").strip()
10228
+ return f"Co-Authored-By: {name} <{email}>" if settings.get("comment") and name and email else ""
10229
+
10230
+
10231
+ def _body_at(argv):
10232
+ """(index, value, is "--body=" form) of the body given on the command line, or None."""
10233
+ for k, a in enumerate(argv):
10234
+ if a in ("--body", "-b") and k + 1 < len(argv):
10235
+ return k + 1, argv[k + 1], False
10236
+ if a.startswith("--body="):
10237
+ return k, a[len("--body="):], True
10238
+ return None
10188
10239
  _GIT_GLOBAL_WITH_VALUE = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--exec-path",
10189
10240
  "--super-prefix", "--config-env"}
10190
10241
 
@@ -10233,7 +10284,8 @@ def _with_attribution(argv, settings):
10233
10284
 
10234
10285
  git commit → `--trailer "Co-Authored-By: gu <email>"` (git ≥ 2.32; git places it after any
10235
10286
  other trailers and skips it when the same one is already last). Skipped when the message
10236
- already names that email (the model wrote it itself). gh pr create → a footer on --body.
10287
+ already names that email (the model wrote it itself). gh pr create → a footer on --body;
10288
+ gh issue comment / pr comment / issue create → the same co-author line at the end of --body.
10237
10289
  """
10238
10290
  argv = list(argv)
10239
10291
  name = str(settings.get("name") or "").strip()
@@ -10244,19 +10296,19 @@ def _with_attribution(argv, settings):
10244
10296
  return argv, ""
10245
10297
  return argv[:i + 1] + ["--trailer", f"Co-Authored-By: {name} <{email}>"] + argv[i + 1:], \
10246
10298
  f"co-author trailer added ({name})"
10247
- if (argv[:3] == ["gh", "pr", "create"] or (argv and os.path.basename(argv[0]).lower() == "gh.exe"
10248
- and argv[1:3] == ["pr", "create"])) and settings.get("pr"):
10249
- for k, a in enumerate(argv):
10250
- if a in ("--body", "-b") and k + 1 < len(argv):
10251
- if _PR_FOOTER not in argv[k + 1]:
10252
- argv[k + 1] = argv[k + 1].rstrip() + f"\n\n{_PR_FOOTER}"
10253
- return argv, "PR footer added"
10254
- return argv, ""
10255
- if a.startswith("--body="):
10256
- if _PR_FOOTER not in a:
10257
- argv[k] = a.rstrip() + f"\n\n{_PR_FOOTER}"
10258
- return argv, "PR footer added"
10259
- return argv, ""
10299
+ verb = _gh_verb(argv)
10300
+ footer, note = "", ""
10301
+ if verb == ("pr", "create") and settings.get("pr"):
10302
+ footer, note = _PR_FOOTER, "PR footer added"
10303
+ elif verb in _GH_COMMENTS:
10304
+ footer, note = _comment_footer(settings), f"co-author line added to the {verb[0]} {verb[1]} ({name})"
10305
+ if footer:
10306
+ at = _body_at(argv)
10307
+ if at and footer not in at[1] and not (email and email.lower() in at[1].lower()):
10308
+ k, body, inline = at
10309
+ body = body.rstrip() + f"\n\n{footer}"
10310
+ argv[k] = ("--body=" + body) if inline else body
10311
+ return argv, note
10260
10312
  return argv, ""
10261
10313
 
10262
10314
 
@@ -12097,7 +12149,10 @@ def run_agent_chat(cfg):
12097
12149
  # HOOKS (task #270): onStart on the first turn of a gu session, onAsk on every question. What
12098
12150
  # they print goes in beside the task; exit 2 from onAsk stops the turn before any model call.
12099
12151
  import gu_hooks as _hooks_mod
12100
- _hooks = _hooks_mod.from_cfg(cfg, _log)
12152
+ # GH #584: the between-turns RAG index pass (ragIndexOnly) gets the turn's own config: it is NOT a turn,
12153
+ # so no hooks. Its onAsk saved the question a second time, after onTurnEnd, so the memory skill thought
12154
+ # every gu session in a local-RAG folder was still unfinished — and never offered it to "where were we".
12155
+ _hooks = None if cfg.get("ragIndexOnly") else _hooks_mod.from_cfg(cfg, _log)
12101
12156
  _hook_context = ""
12102
12157
  if _hooks:
12103
12158
  _hr_parts, _hr_warn = [], []
@@ -13176,6 +13231,15 @@ def run_agent_chat(cfg):
13176
13231
  "continue the investigation/edit from here:\n"
13177
13232
  f"Previous task: {_ck.get('task', '')}\n" + "\n".join(_kept)
13178
13233
  )
13234
+ # GH #585: how the earlier turns of this conversation got their answers (commands,
13235
+ # servers, files) — the history above holds only the answers.
13236
+ import gu_turn_trail as _trail_mod
13237
+ _trail = _trail_mod.block(_WS_ACTIVE, [m.get("content", "") for m in messages[:last_user_idx]
13238
+ if m.get("role") == "user"],
13239
+ local_model=_is_local_url(coding_base_url))
13240
+ if _trail:
13241
+ _log(f"turn trail: {len(_trail)} chars of earlier turns' steps folded into the task")
13242
+ task_text += "\n\n" + _trail
13179
13243
 
13180
13244
  # ORDER (task #86 — prefix-cache fix): STATIC first, VARIABLE last.
13181
13245
  # The ~16k-char tool reference is byte-identical between turns; leading with it
@@ -17512,7 +17576,7 @@ def run_agent_chat(cfg):
17512
17576
  _gp = _ps_mod()
17513
17577
  _cmd_text, _attrib_note = _with_attribution_text(
17514
17578
  command, dict(_scan, commands=_gp.ps_commands(_scan["tokens"])),
17515
- _attribution_settings(wd))
17579
+ _attribution_settings(wd), powershell=True)
17516
17580
  _ps_cmd = log_path[:-4] + ".cmd.ps1"
17517
17581
  _ps_wrap = log_path[:-4] + ".ps1"
17518
17582
  with open(_ps_cmd, "w", encoding="utf-8") as _fh:
@@ -18475,9 +18539,12 @@ def run_agent_chat(cfg):
18475
18539
  _log(f"onToolDone hooks on {_n_wrapped} tool(s)")
18476
18540
  # Fill in the numbered tool list now that the REAL tool objects exist — see
18477
18541
  # _render_numbered_tool_list and the {{TOOL_LIST}} placeholder left in tool_hint.
18542
+ # The FIRST one only (the tool reference comes first): the task below it can quote the
18543
+ # placeholder — an earlier turn's step that grepped for it (GH #585) — and is left as it is.
18478
18544
  task_with_hint = task_with_hint.replace(
18479
18545
  "{{TOOL_LIST}}",
18480
18546
  f"You have {len(agent_tools)} tools:\n" + _render_numbered_tool_list(agent_tools),
18547
+ 1,
18481
18548
  )
18482
18549
  agent_kwargs = dict(
18483
18550
  tools=agent_tools,
@@ -18719,6 +18786,10 @@ def run_agent_chat(cfg):
18719
18786
  except Exception as _ce: # noqa: BLE001
18720
18787
  _log(f"browser cleanup skipped: {type(_ce).__name__}: {_ce}")
18721
18788
  _emit({"type": "final", "text": final_text})
18789
+ # GH #585: the answer says WHAT was found, not how; the next turn gets the steps too.
18790
+ if _WS_ACTIVE and _turn_steps and not cfg.get("ragIndexOnly"):
18791
+ import gu_turn_trail as _trail_mod
18792
+ _log(f"turn trail: {_trail_mod.save(_WS_ACTIVE, latest_user_text, _turn_steps)} step(s) kept for the next turns")
18722
18793
  # onTurnEnd (task #270): after the answer is out, so a slow hook never delays it.
18723
18794
  if _hooks and _hooks.has("onTurnEnd"):
18724
18795
  _te = _hooks.run("onTurnEnd", {"question": latest_user_text, "answer": final_text,
package/gu-cli.mjs CHANGED
@@ -1081,10 +1081,9 @@ if (args[0] === "token-usage" || args[0] === "tokens") {
1081
1081
  console.log(`\n Opening ${pageUrl}`);
1082
1082
  console.log(" (the link is single-use and expires in a few minutes)\n");
1083
1083
  try {
1084
- const { execFile } = await import("node:child_process");
1085
- const { platform } = await import("node:os");
1086
- const cmd = platform() === "darwin" ? "open" : platform() === "win32" ? "start" : "xdg-open";
1087
- execFile(cmd, [url], () => {});
1084
+ // GH #603: one helper — `start` is a cmd.exe built-in, so on Windows it never opened anything.
1085
+ const { openBrowser } = await import("./device-login.mjs");
1086
+ openBrowser(url);
1088
1087
  } catch {
1089
1088
  /* best-effort; the URL is printed below */
1090
1089
  }
@@ -4039,7 +4038,8 @@ function _runBetweenTurnsIndex({ python, pythonArgs, scriptPath, input, jobActiv
4039
4038
  });
4040
4039
  child.on("error", () => { release(); });
4041
4040
  child.stdin.write(
4042
- JSON.stringify({ ...cfg, ragIndexOnly: true, ragIndexRoot: jobActiveWorkspace })
4041
+ // GH #584: not a turn — no hooks (its onAsk re-opened the turn that had just ended in the memory skill).
4042
+ JSON.stringify({ ...cfg, hooks: undefined, hookSession: undefined, ragIndexOnly: true, ragIndexRoot: jobActiveWorkspace })
4043
4043
  );
4044
4044
  child.stdin.end();
4045
4045
  console.log(`[gu-worker] between-turns index started for ${jobActiveWorkspace}`);
@@ -5736,6 +5736,29 @@ function logLevelNow() {
5736
5736
  if (now - _levelCache.at > 500) _levelCache = { at: now, level: currentLevel() };
5737
5737
  return _levelCache.level;
5738
5738
  }
5739
+ /**
5740
+ * GH #594 #1: on a gudb computer, saved model prompts/replies older than 30 days are removed by
5741
+ * the worker — at start, then daily. Rows and usage numbers stay; no compacting (no long lock
5742
+ * while gu works — SQLite reuses the freed space, so the file stops growing). The manual cleanup
5743
+ * (/clear-logs) still removes text older than 14 days and compacts.
5744
+ */
5745
+ async function startGudbRetention() {
5746
+ try {
5747
+ const ce = await import("./client-expert-api.mjs");
5748
+ if (ce.readLocalDb() !== "gudb") return;
5749
+ const gs = await import("./gudb-size.mjs");
5750
+ const run = () => {
5751
+ const r = gs.autoClearOldText();
5752
+ if (r?.error) console.log(`[gu-worker] database: old saved text not removed (${r.error})`);
5753
+ else if (r?.cleared) console.log(`[gu-worker] database: saved model text older than ${gs.AUTO_KEEP_TEXT_DAYS} days removed from ${r.cleared} step(s)`);
5754
+ };
5755
+ run();
5756
+ setInterval(run, 24 * 3_600_000).unref();
5757
+ } catch (e) {
5758
+ console.log(`[gu-worker] database retention unavailable (${e?.message ?? e})`);
5759
+ }
5760
+ }
5761
+
5739
5762
  async function startLogPolicy() {
5740
5763
  try {
5741
5764
  const lp = await import("./log-policy.mjs");
@@ -5823,6 +5846,7 @@ async function main() {
5823
5846
  }
5824
5847
  MY_INSTANCE_ID = await (await import("./daemon-control.mjs")).getInstanceId();
5825
5848
  await startLogPolicy();
5849
+ void startGudbRetention(); // GH #594 #1
5826
5850
  console.log(
5827
5851
  `[gu-worker] polling ${apiBase} every ${pollMs}ms (local_health concurrency=${localHealthConcurrency}` +
5828
5852
  `, agent concurrency=${agentConcurrency})` +