@tiens.nguyen/gu-cli 1.0.940 → 1.0.941
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/gonext_agent_chat.py +89 -18
- package/gu-cli.mjs +26 -1
- package/gu-repl.mjs +288 -8
- package/gu_turn_trail.py +138 -0
- package/gudb-size.mjs +198 -0
- package/memory-task.mjs +85 -0
- package/next-suggestion.mjs +13 -8
- package/package.json +4 -1
- package/terminal-layout.mjs +24 -0
package/gonext_agent_chat.py
CHANGED
|
@@ -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
|
-
|
|
10248
|
-
|
|
10249
|
-
|
|
10250
|
-
|
|
10251
|
-
|
|
10252
|
-
|
|
10253
|
-
|
|
10254
|
-
|
|
10255
|
-
|
|
10256
|
-
|
|
10257
|
-
|
|
10258
|
-
|
|
10259
|
-
|
|
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
|
-
|
|
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
|
@@ -4039,7 +4039,8 @@ function _runBetweenTurnsIndex({ python, pythonArgs, scriptPath, input, jobActiv
|
|
|
4039
4039
|
});
|
|
4040
4040
|
child.on("error", () => { release(); });
|
|
4041
4041
|
child.stdin.write(
|
|
4042
|
-
|
|
4042
|
+
// GH #584: not a turn — no hooks (its onAsk re-opened the turn that had just ended in the memory skill).
|
|
4043
|
+
JSON.stringify({ ...cfg, hooks: undefined, hookSession: undefined, ragIndexOnly: true, ragIndexRoot: jobActiveWorkspace })
|
|
4043
4044
|
);
|
|
4044
4045
|
child.stdin.end();
|
|
4045
4046
|
console.log(`[gu-worker] between-turns index started for ${jobActiveWorkspace}`);
|
|
@@ -5736,6 +5737,29 @@ function logLevelNow() {
|
|
|
5736
5737
|
if (now - _levelCache.at > 500) _levelCache = { at: now, level: currentLevel() };
|
|
5737
5738
|
return _levelCache.level;
|
|
5738
5739
|
}
|
|
5740
|
+
/**
|
|
5741
|
+
* GH #594 #1: on a gudb computer, saved model prompts/replies older than 30 days are removed by
|
|
5742
|
+
* the worker — at start, then daily. Rows and usage numbers stay; no compacting (no long lock
|
|
5743
|
+
* while gu works — SQLite reuses the freed space, so the file stops growing). The manual cleanup
|
|
5744
|
+
* (/clear-logs) still removes text older than 14 days and compacts.
|
|
5745
|
+
*/
|
|
5746
|
+
async function startGudbRetention() {
|
|
5747
|
+
try {
|
|
5748
|
+
const ce = await import("./client-expert-api.mjs");
|
|
5749
|
+
if (ce.readLocalDb() !== "gudb") return;
|
|
5750
|
+
const gs = await import("./gudb-size.mjs");
|
|
5751
|
+
const run = () => {
|
|
5752
|
+
const r = gs.autoClearOldText();
|
|
5753
|
+
if (r?.error) console.log(`[gu-worker] database: old saved text not removed (${r.error})`);
|
|
5754
|
+
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)`);
|
|
5755
|
+
};
|
|
5756
|
+
run();
|
|
5757
|
+
setInterval(run, 24 * 3_600_000).unref();
|
|
5758
|
+
} catch (e) {
|
|
5759
|
+
console.log(`[gu-worker] database retention unavailable (${e?.message ?? e})`);
|
|
5760
|
+
}
|
|
5761
|
+
}
|
|
5762
|
+
|
|
5739
5763
|
async function startLogPolicy() {
|
|
5740
5764
|
try {
|
|
5741
5765
|
const lp = await import("./log-policy.mjs");
|
|
@@ -5823,6 +5847,7 @@ async function main() {
|
|
|
5823
5847
|
}
|
|
5824
5848
|
MY_INSTANCE_ID = await (await import("./daemon-control.mjs")).getInstanceId();
|
|
5825
5849
|
await startLogPolicy();
|
|
5850
|
+
void startGudbRetention(); // GH #594 #1
|
|
5826
5851
|
console.log(
|
|
5827
5852
|
`[gu-worker] polling ${apiBase} every ${pollMs}ms (local_health concurrency=${localHealthConcurrency}` +
|
|
5828
5853
|
`, agent concurrency=${agentConcurrency})` +
|
package/gu-repl.mjs
CHANGED
|
@@ -80,6 +80,7 @@ import {
|
|
|
80
80
|
createMouseReportReader,
|
|
81
81
|
stripLeakedMouseReports,
|
|
82
82
|
agentPickerItems,
|
|
83
|
+
agentsPanelRows,
|
|
83
84
|
agentsIndicator,
|
|
84
85
|
classifyCliArg,
|
|
85
86
|
maskKey,
|
|
@@ -149,6 +150,7 @@ import {
|
|
|
149
150
|
import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
|
|
150
151
|
import { isScaffoldStep, isGroupableStep, stepGroupRows, stepRowSpans, relativizePaths } from "./step-group.mjs";
|
|
151
152
|
import { clearLogsNoticeText } from "./clear-logs.mjs";
|
|
153
|
+
import { gudbNotice as gudbNoticeSync, lowDiskNotice } from "./gudb-size.mjs"; // GH #594, #597
|
|
152
154
|
import { commandAllowedIn, commandAllowProject, commandAllowSource, commandForget, commandProjectAllowed, sourcedFileOf, PROJECT_CHOICE } from "./command-allow.mjs";
|
|
153
155
|
import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
|
|
154
156
|
import { commandLogFile, killShell, logTail, markAnnounced, readShells, recapQuestion, runningShells, shellsToRecap, statusText as shellStatusText, renderShellDetails, shellPanelRows, shellPickerLabel, shellState, shellsNotice } from "./shell-details.mjs";
|
|
@@ -156,7 +158,8 @@ import { discoverSkills, matchSkillCommand } from "./skills.mjs";
|
|
|
156
158
|
import { appendNew, archivePathFor, archivedWorkspaceKey, markReset, seedArchive } from "./conversation-archive.mjs";
|
|
157
159
|
import { addAllowRule, listServers as listMcpServers } from "./mcp-config.mjs";
|
|
158
160
|
import { unapprovedProjectServers } from "./mcp-command.mjs";
|
|
159
|
-
import { readHooks } from "./hooks-config.mjs";
|
|
161
|
+
import { readHooks, hooksForTurn, sessionForTurn } from "./hooks-config.mjs";
|
|
162
|
+
import { memoryRuntime, currentTask, setTask, memoryBarText, taskPickerLabels } from "./memory-task.mjs"; // GH #595
|
|
160
163
|
import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
|
|
161
164
|
import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
|
|
162
165
|
import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
|
|
@@ -1143,6 +1146,7 @@ const COMMANDS = [
|
|
|
1143
1146
|
{ name: "/tokens", desc: "break down the last prompt sent to the coding model — how much of it was RAG" },
|
|
1144
1147
|
{ name: "/voucher", usage: "/voucher CODE", desc: "use a voucher code — free days for this computer's trial or your free account, or a free model allowance" },
|
|
1145
1148
|
{ name: "/support", desc: "send the gu support team a request with gu's logs attached (secrets masked) — shows what goes first, then asks" },
|
|
1149
|
+
{ name: "/backup-db", desc: "back up gu's built-in database safely (SQLite's own backup, consistent while gu runs) — keeps the last 3" },
|
|
1146
1150
|
{ name: "/clear-logs", desc: "show what gu's logs, RAG indexes and old API versions take on disk, then ask what to clear — the logs first" },
|
|
1147
1151
|
{ name: "/cost", usage: "/cost [all]", desc: "what this session and the last turn cost, and the price of the model in use — \"all\" shows every price (prices update by themselves)" },
|
|
1148
1152
|
// ONE name, /new (user, #278). /reset and /clear still work (HIDDEN_COMMANDS) for habit and
|
|
@@ -1151,6 +1155,7 @@ const COMMANDS = [
|
|
|
1151
1155
|
{ name: "/hooks", usage: "/hooks [list|approve|unapprove]", desc: "hooks: commands gu runs on onStart, onAsk, onToolDone, onTurnEnd — list them, approve this project's" },
|
|
1152
1156
|
{ name: "/mcp", usage: "/mcp [list|tools|add|remove|enable|disable|approve|allow|disallow|reconnect]", desc: "MCP servers: see which connect, add one (asks step by step), choose which tools run without asking" },
|
|
1153
1157
|
{ name: "/switch-skill", usage: "/switch-skill [claude|gu]", desc: "whose skills, MCP servers and hooks this folder uses — Claude Code's (.claude) or gu's own (.gu)" },
|
|
1158
|
+
{ name: "/task", desc: "choose the task the memory skill records this session's work under (shown at the bottom)" },
|
|
1154
1159
|
{ name: "/resume", desc: "carry on the last unfinished task in this folder — Claude Code's or gu's — from where it stopped (memory skill)" },
|
|
1155
1160
|
{ name: "/skill-pack", usage: "/skill-pack <name> [--out <file>] [--runtime <dir>]", desc: "pack a skill (gu's or Claude's) with its MCP servers, hooks and code into one zip for another machine" },
|
|
1156
1161
|
{ name: "/skill-install", usage: "/skill-install <zip|folder> [--gu] [--claude] [--dry-run]", desc: "install a packed skill for gu and Claude Code (whichever is set up here)" },
|
|
@@ -1813,6 +1818,16 @@ function applyClick({ row, col }) {
|
|
|
1813
1818
|
void runLimitsSeen();
|
|
1814
1819
|
return;
|
|
1815
1820
|
}
|
|
1821
|
+
if (diskRowTarget && row === updateRowAbs &&
|
|
1822
|
+
col - 1 >= diskRowTarget.from && col - 1 < diskRowTarget.to) {
|
|
1823
|
+
void runClearLogs(); // what gu itself can free
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
if (gudbRowTarget && row === updateRowAbs &&
|
|
1827
|
+
col - 1 >= gudbRowTarget.from && col - 1 < gudbRowTarget.to) {
|
|
1828
|
+
void runCleanOldData(); // GH #594: one click, no questions
|
|
1829
|
+
return;
|
|
1830
|
+
}
|
|
1816
1831
|
if (logsRowTarget && row === updateRowAbs &&
|
|
1817
1832
|
col - 1 >= logsRowTarget.from && col - 1 < logsRowTarget.to) {
|
|
1818
1833
|
void runClearLogs();
|
|
@@ -2541,6 +2556,17 @@ rl.on("line", (l) => {
|
|
|
2541
2556
|
imageStore.clear();
|
|
2542
2557
|
typedDuringTurn = false;
|
|
2543
2558
|
turnTyping.reset();
|
|
2559
|
+
// GH #588: /model during a turn opens the picker NOW — it used to go to the agent as a note.
|
|
2560
|
+
// The running job carries its own coder (its payload), so the choice is for the next turn.
|
|
2561
|
+
if (/^\/models?$/i.test(queued)) {
|
|
2562
|
+
void chooseModelDuringTurn();
|
|
2563
|
+
return;
|
|
2564
|
+
}
|
|
2565
|
+
// GH #595: /task mid-turn — the rest of this turn's steps are filed under the chosen task.
|
|
2566
|
+
if (/^\/tasks?$/i.test(queued)) {
|
|
2567
|
+
void runTaskCommand();
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2544
2570
|
// GH #506: with a running job, the text goes to the agent's NEXT step (appended after the
|
|
2545
2571
|
// current step's result — cache-safe). Not read by the end of the turn = the next question.
|
|
2546
2572
|
// GH #514: like chat — no notices. Pinned, it waits as a ">> " row above the input box until the agent
|
|
@@ -2826,9 +2852,65 @@ function slashCloseSeq(line, cursor, cols) {
|
|
|
2826
2852
|
// so the bar reflects it and Shift+Tab cycles it; wiring it to actually gate the agent's
|
|
2827
2853
|
// edits is a deliberate follow-up.
|
|
2828
2854
|
let editMode = "accept"; // "accept" | "manual"
|
|
2829
|
-
const modeLineText = () =>
|
|
2830
|
-
white("✎ " + (editMode === "accept" ? "accept edits on" : "manually edit")) +
|
|
2831
|
-
|
|
2855
|
+
const modeLineText = () => {
|
|
2856
|
+
const base = white("✎ " + (editMode === "accept" ? "accept edits on" : "manually edit")) + dim(" (shift+tab to switch)");
|
|
2857
|
+
const quick = quickBarHint(quickModels) ? dim(" " + quickBarHint(quickModels)) : "";
|
|
2858
|
+
// GH #595: the task the memory skill files this session's work under — yellow when it is only the
|
|
2859
|
+
// project's newest open task (not chosen for this session): that is how work gets misfiled.
|
|
2860
|
+
const width = Math.max(20, process.stdout.columns || 80) - GUTTER.length - 1;
|
|
2861
|
+
const room = width - visibleLen(base) - 3;
|
|
2862
|
+
const mem = memoryBarText(memCurrent, Math.min(room, 70));
|
|
2863
|
+
if (!mem.text || room < 16) return base + quick;
|
|
2864
|
+
const memPart = " " + (mem.guess ? yellow(mem.text) : dim(mem.text));
|
|
2865
|
+
return base + memPart + (visibleLen(base + memPart + quick) <= width ? quick : "");
|
|
2866
|
+
};
|
|
2867
|
+
// GH #595: the memory skill's current task for this session (null = no memory here / not installed for gu).
|
|
2868
|
+
let memCurrent = null;
|
|
2869
|
+
let memRuntimeFound = null;
|
|
2870
|
+
async function refreshMemoryTask() {
|
|
2871
|
+
try {
|
|
2872
|
+
const cwd = resolve(process.cwd());
|
|
2873
|
+
memRuntimeFound = memoryRuntime(hooksForTurn({ cwd }));
|
|
2874
|
+
const next = memRuntimeFound ? await currentTask({ runtime: memRuntimeFound, cwd, session: sessionForTurn(cwd)?.id ?? "" }) : null;
|
|
2875
|
+
const changed = JSON.stringify(next?.task ?? null) + next?.chosen !== JSON.stringify(memCurrent?.task ?? null) + memCurrent?.chosen;
|
|
2876
|
+
memCurrent = next;
|
|
2877
|
+
if (changed && barPinned()) paintBar();
|
|
2878
|
+
} catch {
|
|
2879
|
+
/* the bar just says nothing about memory */
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
/**
|
|
2883
|
+
* /task (GH #595): choose the task the memory files this session's work under. The list is the
|
|
2884
|
+
* project's open tasks, newest first, the current one marked.
|
|
2885
|
+
*/
|
|
2886
|
+
async function runTaskCommand() {
|
|
2887
|
+
if (listPickerActive || approvalActive) return;
|
|
2888
|
+
await refreshMemoryTask();
|
|
2889
|
+
if (!memRuntimeFound) {
|
|
2890
|
+
console.log("\n" + GUTTER + dim("The memory skill isn't installed for gu — /skills shows how to add it.") + "\n");
|
|
2891
|
+
return;
|
|
2892
|
+
}
|
|
2893
|
+
if (!memCurrent?.open?.length) {
|
|
2894
|
+
console.log("\n" + GUTTER + dim("No open tasks in this project's memory. Ask gu to create one (\"create a task …\").") + "\n");
|
|
2895
|
+
return;
|
|
2896
|
+
}
|
|
2897
|
+
const width = Math.max(20, process.stdout.columns || 80);
|
|
2898
|
+
console.log("");
|
|
2899
|
+
console.log(dim(` Record this session's work under which task? (${PICK_HINT}):`));
|
|
2900
|
+
const at = memCurrent.open.findIndex((t) => t.id === memCurrent.task?.id);
|
|
2901
|
+
const pick = await pickFromList(taskPickerLabels(memCurrent, width), Math.max(0, at));
|
|
2902
|
+
if (pick < 0) {
|
|
2903
|
+
console.log(dim(" (cancelled)\n"));
|
|
2904
|
+
paintBar();
|
|
2905
|
+
return;
|
|
2906
|
+
}
|
|
2907
|
+
const cwd = resolve(process.cwd());
|
|
2908
|
+
const t = await setTask({ runtime: memRuntimeFound, cwd, session: sessionForTurn(cwd)?.id ?? "", id: memCurrent.open[pick].id });
|
|
2909
|
+
if (t) console.log(GUTTER + accent(`✓ this session's work is recorded under #${t.id} ${t.title}`) + "\n");
|
|
2910
|
+
else console.log(GUTTER + red("couldn't switch the task — the memory skill didn't answer") + "\n");
|
|
2911
|
+
await refreshMemoryTask();
|
|
2912
|
+
paintBar();
|
|
2913
|
+
}
|
|
2832
2914
|
// Token usage for the bar's middle row (task #104): the LAST turn's code-model input +
|
|
2833
2915
|
// output, then the coder's lifetime output total. Unlike the old per-turn print, this row is
|
|
2834
2916
|
// ALWAYS on screen — a turn that did no code-model work honestly reads "0", and the lifetime
|
|
@@ -3554,6 +3636,12 @@ function zoneNotice(width) {
|
|
|
3554
3636
|
const shells = shellsNotice(shellEntries, { cwd: process.cwd() });
|
|
3555
3637
|
if (shells) items.push({ key: "shells", clickable: true, paint: shells.tone === "warn" ? yellow : accent, text: shells.text });
|
|
3556
3638
|
// LAST, so it is the first to give way on a narrow window: housekeeping, never urgent (#329).
|
|
3639
|
+
// GH #597: a nearly full disk — before the database item: nothing can be saved once it is full.
|
|
3640
|
+
const disk = lowDiskNotice(diskFree);
|
|
3641
|
+
if (disk) items.push({ key: "disk", clickable: true, paint: yellow, text: disk.text });
|
|
3642
|
+
// GH #594: the database, when it is big enough to matter (1 GB; yellow from 5 GB).
|
|
3643
|
+
const db = gudbNoticeSync(gudbSize);
|
|
3644
|
+
if (db) items.push({ key: "gudb", clickable: true, paint: db.urgent ? yellow : dim, text: db.text });
|
|
3557
3645
|
const logs = clearLogsNoticeText(logsBytes);
|
|
3558
3646
|
if (logs) items.push({ key: "logs", clickable: true, paint: dim, text: logs });
|
|
3559
3647
|
return noticeRow(items, { width, gutter: GUTTER });
|
|
@@ -3676,6 +3764,8 @@ function frozenZone() {
|
|
|
3676
3764
|
agentsRowTarget = notice?.spans.agents ?? null;
|
|
3677
3765
|
limitsRowTarget = notice?.spans.limits ?? null;
|
|
3678
3766
|
logsRowTarget = notice?.spans.logs ?? null;
|
|
3767
|
+
gudbRowTarget = notice?.spans.gudb ?? null;
|
|
3768
|
+
diskRowTarget = notice?.spans.disk ?? null;
|
|
3679
3769
|
shellsRowTarget = notice?.spans.shells ?? null;
|
|
3680
3770
|
jumpSpan = notice?.spans.jump ?? null;
|
|
3681
3771
|
return { ...zone, rows, statusRows: sep, noticeRow: Boolean(notice) };
|
|
@@ -3746,7 +3836,7 @@ function paintBar() {
|
|
|
3746
3836
|
// THE NOTICE ROW is the one directly above the separator (#318) — never the separator itself.
|
|
3747
3837
|
const noticeAbs = zone.noticeRow ? sepAbs - 1 : 0;
|
|
3748
3838
|
jumpRowTarget = scrolledBack() && jumpSpan ? { row: noticeAbs, ...jumpSpan } : null;
|
|
3749
|
-
updateRowAbs = updateRowTarget || agentsRowTarget || limitsRowTarget || logsRowTarget || shellsRowTarget ? noticeAbs : 0;
|
|
3839
|
+
updateRowAbs = updateRowTarget || agentsRowTarget || limitsRowTarget || logsRowTarget || gudbRowTarget || diskRowTarget || shellsRowTarget ? noticeAbs : 0;
|
|
3750
3840
|
// preserveCaret:false — the save slot holds the OUTPUT position (see regionUi), and the caret
|
|
3751
3841
|
// is parked on the input line right after, so there is nothing to preserve here.
|
|
3752
3842
|
ui(
|
|
@@ -3910,6 +4000,8 @@ let agentsRowTarget = null;
|
|
|
3910
4000
|
let limitsRowTarget = null;
|
|
3911
4001
|
// …and "clear logs · 175 MB" (#329), shown only once the logs are worth a row.
|
|
3912
4002
|
let logsRowTarget = null;
|
|
4003
|
+
let gudbRowTarget = null; // GH #594
|
|
4004
|
+
let diskRowTarget = null; // GH #597
|
|
3913
4005
|
// …and "1 shell running (click)" (#360) — a long command the agent left running in the background.
|
|
3914
4006
|
let shellsRowTarget = null;
|
|
3915
4007
|
// A terminal left with a scrolling region is a broken shell — a hard guarantee, like the
|
|
@@ -7793,6 +7885,28 @@ async function quickSwitch() {
|
|
|
7793
7885
|
}
|
|
7794
7886
|
}
|
|
7795
7887
|
|
|
7888
|
+
/**
|
|
7889
|
+
* GH #588: /model while a turn runs. The pickers work mid-turn (a command approval uses one), and
|
|
7890
|
+
* the turn keeps the coder it was sent with — its job payload names it — so the choice simply
|
|
7891
|
+
* waits for the next turn. Say which model finishes this one, so the bar's new name can't mislead.
|
|
7892
|
+
*/
|
|
7893
|
+
async function chooseModelDuringTurn() {
|
|
7894
|
+
if (listPickerActive || approvalActive || zonePanel) return;
|
|
7895
|
+
const before = { url: activeCodingUrl(), model: activeCodingModelId() };
|
|
7896
|
+
console.log("");
|
|
7897
|
+
try {
|
|
7898
|
+
await chooseModel();
|
|
7899
|
+
} catch (e) {
|
|
7900
|
+
console.log(GUTTER + red(`could not change the model: ${e?.message ?? e}`));
|
|
7901
|
+
}
|
|
7902
|
+
const after = { url: activeCodingUrl(), model: activeCodingModelId() };
|
|
7903
|
+
const changed = after.url !== before.url || after.model !== before.model;
|
|
7904
|
+
if (changed && following) {
|
|
7905
|
+
console.log(GUTTER + accent(`✓ your next turn uses ${after.model}`) + dim(` — this one finishes on ${before.model}`) + "\n");
|
|
7906
|
+
}
|
|
7907
|
+
paintBar();
|
|
7908
|
+
}
|
|
7909
|
+
|
|
7796
7910
|
async function chooseModel() {
|
|
7797
7911
|
let probe;
|
|
7798
7912
|
try {
|
|
@@ -9809,7 +9923,83 @@ async function runLimitsSeen() {
|
|
|
9809
9923
|
let logsBytes = 0; // what the notice shows; only the logs are measured for it (a handful of stats)
|
|
9810
9924
|
let clearLogsBusy = false;
|
|
9811
9925
|
|
|
9926
|
+
let gudbSize = 0; // GH #594: the local database's size, when this computer uses gudb (else 0)
|
|
9927
|
+
let diskFree = null; // GH #597: free bytes where ~/.gu lives; null = not measured
|
|
9928
|
+
async function refreshGudbSize() {
|
|
9929
|
+
try {
|
|
9930
|
+
const { readLocalDb } = await import("./client-expert-api.mjs");
|
|
9931
|
+
const was = gudbSize;
|
|
9932
|
+
const gs = await import("./gudb-size.mjs");
|
|
9933
|
+
gudbSize = readLocalDb() === "gudb" ? gs.gudbBytes() : 0;
|
|
9934
|
+
// GH #597: free disk where gu keeps its data — on every computer, a full disk stops everything.
|
|
9935
|
+
const wasDisk = lowDiskNotice(diskFree)?.text;
|
|
9936
|
+
diskFree = gs.freeDiskBytes();
|
|
9937
|
+
if ((gs.gudbNotice(was)?.text !== gs.gudbNotice(gudbSize)?.text || wasDisk !== lowDiskNotice(diskFree)?.text) && barPinned()) paintBar();
|
|
9938
|
+
} catch {
|
|
9939
|
+
/* a housekeeping notice is never worth an error */
|
|
9940
|
+
}
|
|
9941
|
+
}
|
|
9942
|
+
|
|
9943
|
+
/**
|
|
9944
|
+
* /backup-db (GH #598): a copy made by SQLite itself (VACUUM INTO) — a plain file copy of a running
|
|
9945
|
+
* database can be broken or miss what is still in its WAL file. ~/.gu/gudb/backups, newest 3 kept.
|
|
9946
|
+
*/
|
|
9947
|
+
async function runBackupDb() {
|
|
9948
|
+
const { readLocalDb } = await import("./client-expert-api.mjs");
|
|
9949
|
+
if (readLocalDb() !== "gudb") {
|
|
9950
|
+
console.log(GUTTER + dim("This computer doesn't use gu's built-in database — nothing to back up here.") + "\n");
|
|
9951
|
+
return;
|
|
9952
|
+
}
|
|
9953
|
+
const gs = await import("./gudb-size.mjs");
|
|
9954
|
+
const r = await withPendingStatus("backing up the database", async () => gs.backupGudb());
|
|
9955
|
+
const tilde = (p) => (p.startsWith(homedir()) ? "~" + p.slice(homedir().length) : p);
|
|
9956
|
+
if (r.error) console.log(GUTTER + red(`couldn't back up: ${r.error}`) + "\n");
|
|
9957
|
+
else {
|
|
9958
|
+
console.log(GUTTER + accent(`✓ backed up — ${tilde(r.file)} (${gs.gudbHuman(r.bytes)})`) +
|
|
9959
|
+
(r.removed.length ? dim(` · ${r.removed.length} older backup${r.removed.length === 1 ? "" : "s"} removed, the last ${gs.KEEP_BACKUPS} kept`) : ""));
|
|
9960
|
+
console.log(GUTTER + dim("To restore: quit gu, then put that file in place of ~/.gu/gudb/gu.db (and delete gu.db-wal and gu.db-shm).") + "\n");
|
|
9961
|
+
}
|
|
9962
|
+
paintBar();
|
|
9963
|
+
}
|
|
9964
|
+
|
|
9965
|
+
/**
|
|
9966
|
+
* "Clean old data" (GH #594, the owner's suggestion): ONE click on the database notice, no
|
|
9967
|
+
* questions — saved model prompts/replies older than 30 days go (rows and usage numbers stay),
|
|
9968
|
+
* then the file is compacted so the disk space comes back. /clear-logs keeps the step-by-step
|
|
9969
|
+
* version, which can go down to 14 days.
|
|
9970
|
+
*/
|
|
9971
|
+
let cleanOldDataBusy = false;
|
|
9972
|
+
async function runCleanOldData() {
|
|
9973
|
+
if (cleanOldDataBusy || listPickerActive || approvalActive) return;
|
|
9974
|
+
// Compacting locks the database: gu's API would wait on it in the middle of a turn.
|
|
9975
|
+
if (following) {
|
|
9976
|
+
console.log("\n" + GUTTER + dim("Clean old data waits for this turn to finish — click it again then.") + "\n");
|
|
9977
|
+
return;
|
|
9978
|
+
}
|
|
9979
|
+
cleanOldDataBusy = true;
|
|
9980
|
+
try {
|
|
9981
|
+
const gs = await import("./gudb-size.mjs");
|
|
9982
|
+
console.log("\n" + GUTTER + dim(`Cleaning saved model text older than ${gs.AUTO_KEEP_TEXT_DAYS} days and compacting — this can take a minute…`));
|
|
9983
|
+
const r = await withPendingStatus("cleaning old data", async () => gs.clearOldText({ days: gs.AUTO_KEEP_TEXT_DAYS }));
|
|
9984
|
+
if (r.error) {
|
|
9985
|
+
console.log(GUTTER + red(`couldn't clean: ${r.error}`) + "\n");
|
|
9986
|
+
} else {
|
|
9987
|
+
const size = `${gs.gudbHuman(r.before)} → ${gs.gudbHuman(r.after)}`;
|
|
9988
|
+
if (r.cleared) console.log(GUTTER + accent(`✓ old data cleaned — ${r.cleared} step${r.cleared === 1 ? "" : "s"}, ${size}`));
|
|
9989
|
+
else console.log(GUTTER + accent(`✓ compacted — ${size}`) + dim(` · nothing was older than ${gs.AUTO_KEEP_TEXT_DAYS} days`));
|
|
9990
|
+
if (!r.compacted) console.log(GUTTER + yellow("The file couldn't be compacted now (gu was busy or the disk is too full) — the space is reused for new data."));
|
|
9991
|
+
if (gs.gudbNotice(r.after)) console.log(GUTTER + dim(`Still big: it is mostly recent. /clear-logs can remove saved text older than ${gs.KEEP_TEXT_DAYS} days.`));
|
|
9992
|
+
console.log("");
|
|
9993
|
+
}
|
|
9994
|
+
} finally {
|
|
9995
|
+
cleanOldDataBusy = false;
|
|
9996
|
+
await refreshGudbSize();
|
|
9997
|
+
paintBar();
|
|
9998
|
+
}
|
|
9999
|
+
}
|
|
10000
|
+
|
|
9812
10001
|
async function refreshLogsSize() {
|
|
10002
|
+
void refreshGudbSize();
|
|
9813
10003
|
try {
|
|
9814
10004
|
const { surveyLogs } = await import("./clear-logs.mjs");
|
|
9815
10005
|
const was = clearLogsNoticeText(logsBytes);
|
|
@@ -9992,6 +10182,32 @@ async function runClearLogs() {
|
|
|
9992
10182
|
}
|
|
9993
10183
|
}
|
|
9994
10184
|
|
|
10185
|
+
// 4. THE DATABASE (GH #594) — the saved prompt/response text of older steps; the rows and the
|
|
10186
|
+
// usage numbers stay. Only on a gudb computer, and only when there is old text to remove.
|
|
10187
|
+
const gs = await import("./gudb-size.mjs");
|
|
10188
|
+
const { readLocalDb } = await import("./client-expert-api.mjs");
|
|
10189
|
+
const dbs = readLocalDb() === "gudb" ? gs.surveyGudb() : null;
|
|
10190
|
+
if (dbs?.oldText.rows) {
|
|
10191
|
+
question(`Also remove saved model prompts and replies older than ${dbs.days} days from gu's database — ${cl.humanSize(dbs.oldText.bytes)} in ${dbs.oldText.rows} step${dbs.oldText.rows === 1 ? "" : "s"}? (database: ${cl.humanSize(dbs.bytes)})`);
|
|
10192
|
+
// Can't be undone (like RAG and the API above), so No is the first row.
|
|
10193
|
+
const go = await pickFromList(["No — keep it", "Yes — remove that text" + dim(" · usage numbers, jobs and settings stay")], 0);
|
|
10194
|
+
if (go < 0) return cancelled();
|
|
10195
|
+
if (go === 1) {
|
|
10196
|
+
console.log(GUTTER + dim("Removing and compacting the database…"));
|
|
10197
|
+
const r = gs.clearOldText();
|
|
10198
|
+
if (r.error) console.log(GUTTER + red(`couldn't clean the database — ${r.error}`));
|
|
10199
|
+
else {
|
|
10200
|
+
freed.push({ what: "gudb", freed: r.freed });
|
|
10201
|
+
console.log(GUTTER + accent(`✓ text removed from ${r.cleared} step${r.cleared === 1 ? "" : "s"} — ${cl.humanSize(r.freed)} freed`) +
|
|
10202
|
+
(r.compacted ? "" : yellow(" (the file couldn't be compacted now — gu was busy or the disk is full; it shrinks on the next cleanup)")));
|
|
10203
|
+
}
|
|
10204
|
+
} else {
|
|
10205
|
+
console.log(GUTTER + dim("database text kept"));
|
|
10206
|
+
}
|
|
10207
|
+
} else if (dbs) {
|
|
10208
|
+
console.log("\n" + GUTTER + dim(`gu's database: ${cl.humanSize(dbs.bytes)} — no saved text older than ${dbs.days} days.`));
|
|
10209
|
+
}
|
|
10210
|
+
|
|
9995
10211
|
const total = freed.reduce((n, f) => n + f.freed, 0);
|
|
9996
10212
|
console.log("\n" + GUTTER + (freed.length ? bold(`${cl.humanSize(total)} freed in all.`) : dim("Nothing removed.")) + "\n");
|
|
9997
10213
|
} catch (e) {
|
|
@@ -11322,8 +11538,8 @@ async function showShells() {
|
|
|
11322
11538
|
},
|
|
11323
11539
|
});
|
|
11324
11540
|
}
|
|
11325
|
-
async function refreshOtherAgents() {
|
|
11326
|
-
if (!barPinned() || following) return;
|
|
11541
|
+
async function refreshOtherAgents({ force = false } = {}) {
|
|
11542
|
+
if (!force && (!barPinned() || following)) return;
|
|
11327
11543
|
try {
|
|
11328
11544
|
const r = await fetch(`${apiBase}/api/worker/jobs`, {
|
|
11329
11545
|
headers: { "X-Worker-Key": workerKey },
|
|
@@ -11365,7 +11581,10 @@ async function showOtherAgents() {
|
|
|
11365
11581
|
// `listResolve`, stranding the first promise forever with the keyboard still routed to a
|
|
11366
11582
|
// picker nobody can finish. Also refused during a turn: acting on another agent means
|
|
11367
11583
|
// starting a follow, and this terminal can only run one turn.
|
|
11368
|
-
if (listPickerActive || approvalActive
|
|
11584
|
+
if (listPickerActive || approvalActive) return;
|
|
11585
|
+
// GH #586: during this terminal's own turn the click used to return here and do nothing.
|
|
11586
|
+
// The pickers can't run then (switching is a turn of its own) — a panel can.
|
|
11587
|
+
if (following) return void showOtherAgentsPanel();
|
|
11369
11588
|
const width = Math.max(20, process.stdout.columns || 80);
|
|
11370
11589
|
const agents = otherAgents; // …the snapshot this list is about; the poller may replace it
|
|
11371
11590
|
// THE PICKER IS THE LIST. It used to print the agents and stop there, so now that each one
|
|
@@ -11422,6 +11641,56 @@ async function showOtherAgents() {
|
|
|
11422
11641
|
submitSyntheticLine(ATTACH_PREFIX + agent.id);
|
|
11423
11642
|
}
|
|
11424
11643
|
|
|
11644
|
+
/**
|
|
11645
|
+
* GH #586: the other agents IN PLACE OF THE INPUT BOX, while this terminal's turn runs — the same
|
|
11646
|
+
* kind of panel as a shell's details (#384). ↑↓ choose, s twice stops one, Esc closes. Switching
|
|
11647
|
+
* to one is a turn, so it waits for this one to end (a click then opens the picker).
|
|
11648
|
+
*/
|
|
11649
|
+
async function showOtherAgentsPanel() {
|
|
11650
|
+
if (zonePanel) return;
|
|
11651
|
+
await refreshOtherAgents({ force: true }); // the 20s poll skips during a turn: the count may be old
|
|
11652
|
+
let sel = 0;
|
|
11653
|
+
let note = "";
|
|
11654
|
+
let armed = ""; // the id "s" was pressed on once
|
|
11655
|
+
const items = () => agentPickerItems(otherAgents, { width: Math.max(20, process.stdout.columns || 80) });
|
|
11656
|
+
openZonePanel({
|
|
11657
|
+
refreshMs: 1000,
|
|
11658
|
+
rows: (width, room) => agentsPanelRows({
|
|
11659
|
+
items: items(), sel, width, rows: Math.min(room, items().length + 2), note, gutter: GUTTER,
|
|
11660
|
+
style: { title: (t) => bold(accent(t)), mark: accent, dim },
|
|
11661
|
+
}),
|
|
11662
|
+
onKey: (key) => {
|
|
11663
|
+
const list = items();
|
|
11664
|
+
if (!list.length) return;
|
|
11665
|
+
if (key?.name === "up" || key?.name === "down") {
|
|
11666
|
+
sel = Math.min(list.length - 1, Math.max(0, sel + (key.name === "up" ? -1 : 1)));
|
|
11667
|
+
armed = "";
|
|
11668
|
+
note = "";
|
|
11669
|
+
} else if (key?.name === "s" && !key.ctrl && !key.meta) {
|
|
11670
|
+
const it = list[Math.min(sel, list.length - 1)];
|
|
11671
|
+
// Stopping can't be undone: the first s asks, the second does it.
|
|
11672
|
+
if (armed !== it.id) {
|
|
11673
|
+
armed = it.id;
|
|
11674
|
+
note = "press s again to stop it — its unsaved work is lost · any other key: no";
|
|
11675
|
+
} else {
|
|
11676
|
+
armed = "";
|
|
11677
|
+
note = "stopping…";
|
|
11678
|
+
const title = String((otherAgents.find((a) => a.id === it.id)?.title) ?? "that agent");
|
|
11679
|
+
void stopOtherAgent(it.id, title.length > 60 ? title.slice(0, 60) + "…" : title).then(() => {
|
|
11680
|
+
note = "";
|
|
11681
|
+
sel = Math.max(0, Math.min(sel, items().length - 1));
|
|
11682
|
+
paintBar();
|
|
11683
|
+
});
|
|
11684
|
+
}
|
|
11685
|
+
} else {
|
|
11686
|
+
armed = "";
|
|
11687
|
+
note = "";
|
|
11688
|
+
}
|
|
11689
|
+
paintBar();
|
|
11690
|
+
},
|
|
11691
|
+
});
|
|
11692
|
+
}
|
|
11693
|
+
|
|
11425
11694
|
/**
|
|
11426
11695
|
* Stop one of the account's other agents — the same POST Ctrl+C makes for this terminal's turn.
|
|
11427
11696
|
*
|
|
@@ -16062,6 +16331,7 @@ async function main() {
|
|
|
16062
16331
|
archivedUpTo = await seedArchive(cwd, history).catch(() => history.length);
|
|
16063
16332
|
// A new gu session (task #270): the agent runs onStart hooks on the first turn it sees this id.
|
|
16064
16333
|
await startHookSession(cwd);
|
|
16334
|
+
void refreshMemoryTask(); // GH #595: which task this session's work goes to, on the bar
|
|
16065
16335
|
if (history.length > 0) {
|
|
16066
16336
|
const turns = history.filter((m) => m.role === "user").length;
|
|
16067
16337
|
console.log(
|
|
@@ -16641,6 +16911,7 @@ async function main() {
|
|
|
16641
16911
|
const where = await startNewConversation(cwd, history);
|
|
16642
16912
|
history.length = 0;
|
|
16643
16913
|
await startHookSession(cwd); // a fresh session: onStart hooks run again (#270)
|
|
16914
|
+
void refreshMemoryTask(); // GH #595: a new session has no task of its own yet
|
|
16644
16915
|
console.log(
|
|
16645
16916
|
GUTTER + dim("New conversation started — this folder's settings are unchanged.") + "\n" +
|
|
16646
16917
|
GUTTER + dim(kept
|
|
@@ -16662,6 +16933,14 @@ async function main() {
|
|
|
16662
16933
|
await runClearLogs();
|
|
16663
16934
|
continue;
|
|
16664
16935
|
}
|
|
16936
|
+
if (line === "/task" || line === "/tasks") {
|
|
16937
|
+
await runTaskCommand();
|
|
16938
|
+
continue;
|
|
16939
|
+
}
|
|
16940
|
+
if (line === "/backup-db") {
|
|
16941
|
+
await runBackupDb();
|
|
16942
|
+
continue;
|
|
16943
|
+
}
|
|
16665
16944
|
if (line === "/support") {
|
|
16666
16945
|
await runSupport();
|
|
16667
16946
|
continue;
|
|
@@ -16988,6 +17267,7 @@ async function main() {
|
|
|
16988
17267
|
if (fellBack) printFallbackLine(fellBack);
|
|
16989
17268
|
// GH #536: maybe a suggested next message — not when a queued question runs next anyway.
|
|
16990
17269
|
if (turnQueue.size === 0 && _lineQueue.length === 0) offerNextHint(taskLine, answer);
|
|
17270
|
+
void refreshMemoryTask(); // GH #595: the turn may have created or switched the task
|
|
16991
17271
|
} else {
|
|
16992
17272
|
// A turn that ended WITHOUT an answer (Ctrl+C cancel, or an abort/failure) must not
|
|
16993
17273
|
// silently launch another turn. Any keystrokes the user typed DURING the dead turn
|
package/gu_turn_trail.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
"""GH #585: what earlier turns of this conversation RAN, for the turns after them.
|
|
2
|
+
|
|
3
|
+
The history carries only each turn's ANSWER. An answer says "I connected to the production
|
|
4
|
+
MongoDB", never how (ssh to the server, mongosh there, the URI in the server's .env), so the
|
|
5
|
+
next question searched for the database again from zero. Each finished turn now leaves its
|
|
6
|
+
steps here (one file per folder, secrets hidden), and a later turn of the SAME conversation
|
|
7
|
+
gets them back: only turns whose question is still in the history it was sent.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
import time
|
|
16
|
+
|
|
17
|
+
KEEP_TURNS = 6 # turns kept per folder
|
|
18
|
+
STEP_DID = 400 # chars of a step's code kept
|
|
19
|
+
STEP_FOUND = 400 # chars of what it found
|
|
20
|
+
BLOCK_BUDGET = 3500 # chars handed to the next turn, newest steps first (~1k tokens)
|
|
21
|
+
# A model on this machine or the LAN reads its prompt slowly (ollama1: ~2.3 tokens/s), so 1k
|
|
22
|
+
# more tokens is minutes on every turn's first step. There it gets the commands only (~300 tokens).
|
|
23
|
+
LOCAL_BUDGET = 1200
|
|
24
|
+
|
|
25
|
+
_RULES = [
|
|
26
|
+
# An env name (.env, export, docker -e): MONGODB_URI=…, DB_PASSWORD=…, GH_TOKEN=…
|
|
27
|
+
(re.compile(r"(\b[A-Z0-9_]*(?:SECRET|PASSWORD|PASSWD|PWD|TOKEN|API_?KEY|ACCESS_KEY|PRIVATE_KEY|_KEY|_URI|_URL|DSN|AUTH|CREDENTIALS?|COOKIE)[A-Z0-9_]*\s*=\s*[\"']?)([^\s\"']+)"), r"\1***"),
|
|
28
|
+
# A config key (JSON, YAML): "password": "…", apiKey: …
|
|
29
|
+
(re.compile(r"(?i)([\"']?\b(?:password|passwd|secret|client_?secret|token|access_?token|refresh_?token|api_?key|apikey|access_?key|private_?key)[\"']?\s*[:=]\s*[\"']?)([^\s\"',}]+)"), r"\1***"),
|
|
30
|
+
# scheme://user:password@host
|
|
31
|
+
(re.compile(r"(?i)\b([a-z][a-z0-9+.-]*://[^\s:/@]+:)([^\s@/]+)@"), r"\1***@"),
|
|
32
|
+
# Authorization headers
|
|
33
|
+
(re.compile(r"(?i)(authorization:\s*[a-z]+\s+)[^\s'\"]+"), r"\1***"),
|
|
34
|
+
(re.compile(r"(?i)\b(bearer)\s+[A-Za-z0-9._~+/=-]{12,}"), r"\1 ***"),
|
|
35
|
+
# --password x / --token=x
|
|
36
|
+
(re.compile(r"(?i)(--?(?:password|passwd|pass|token|api-key|secret)[= ])(\S+)"), r"\1***"),
|
|
37
|
+
# well-known key shapes
|
|
38
|
+
(re.compile(r"\b(?:sk-[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{20,}|gh[pousr]_[A-Za-z0-9]{20,}|wk_[A-Za-z0-9]{16,}|AKIA[0-9A-Z]{16}|xox[abprs]-[A-Za-z0-9-]{10,})"), "***"),
|
|
39
|
+
]
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def redact(text: str) -> str:
|
|
43
|
+
s = str(text or "")
|
|
44
|
+
for rx, sub in _RULES:
|
|
45
|
+
s = rx.sub(sub, s)
|
|
46
|
+
return s
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _clip(s: str, n: int) -> str:
|
|
50
|
+
s = str(s or "").strip()
|
|
51
|
+
return s if len(s) <= n else s[: n - 1] + "…"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def path_for(workspace: str, home: str | None = None) -> str:
|
|
55
|
+
h = hashlib.sha256(workspace.encode("utf-8")).hexdigest()[:32]
|
|
56
|
+
base = os.path.join(home or os.path.expanduser("~"), ".gu", "agent-turns")
|
|
57
|
+
os.makedirs(base, exist_ok=True)
|
|
58
|
+
return os.path.join(base, f"{h}.trail.json")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _key(q: str) -> str:
|
|
62
|
+
"""A question as the history keeps it: gu may append notes under it later (GH #514)."""
|
|
63
|
+
return re.sub(r"\s+", " ", str(q or "")).strip().lower()[:160]
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _load(path: str) -> list:
|
|
67
|
+
try:
|
|
68
|
+
with open(path, encoding="utf-8") as f:
|
|
69
|
+
d = json.load(f)
|
|
70
|
+
return d if isinstance(d, list) else []
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
return []
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def save(workspace: str, question: str, steps: list, home: str | None = None) -> int:
|
|
76
|
+
"""Record a finished turn's steps. Returns how many were kept. Never raises."""
|
|
77
|
+
try:
|
|
78
|
+
kept = []
|
|
79
|
+
for st in steps or []:
|
|
80
|
+
if not isinstance(st, dict):
|
|
81
|
+
continue
|
|
82
|
+
did = _clip(redact(st.get("did")), STEP_DID)
|
|
83
|
+
if not did:
|
|
84
|
+
continue
|
|
85
|
+
kept.append({"did": did, "found": _clip(redact(st.get("found")), STEP_FOUND)})
|
|
86
|
+
if not kept or not _key(question):
|
|
87
|
+
return 0
|
|
88
|
+
path = path_for(workspace, home)
|
|
89
|
+
turns = [t for t in _load(path) if t.get("q") != _key(question)]
|
|
90
|
+
turns.append({"q": _key(question), "asked": _clip(question, 200), "at": int(time.time()), "steps": kept})
|
|
91
|
+
tmp = path + ".tmp"
|
|
92
|
+
with open(tmp, "w", encoding="utf-8") as f:
|
|
93
|
+
json.dump(turns[-KEEP_TURNS:], f)
|
|
94
|
+
os.replace(tmp, path)
|
|
95
|
+
return len(kept)
|
|
96
|
+
except Exception: # noqa: BLE001
|
|
97
|
+
return 0
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def block(workspace: str, earlier_questions: list, home: str | None = None, budget: int | None = None,
|
|
101
|
+
local_model: bool = False) -> str:
|
|
102
|
+
"""The steps of the earlier turns of THIS conversation, newest first within the budget,
|
|
103
|
+
shown oldest first. Empty when none is in the history (a new conversation, or /clear).
|
|
104
|
+
local_model: the coder runs on this machine or the LAN — commands only, a smaller budget."""
|
|
105
|
+
if budget is None:
|
|
106
|
+
budget = LOCAL_BUDGET if local_model else BLOCK_BUDGET
|
|
107
|
+
try:
|
|
108
|
+
asked = {_key(q) for q in earlier_questions if _key(q)}
|
|
109
|
+
if not asked:
|
|
110
|
+
return ""
|
|
111
|
+
def _in_history(t):
|
|
112
|
+
k = t.get("q", "")
|
|
113
|
+
return any(a.startswith(k) or k.startswith(a) for a in asked)
|
|
114
|
+
turns = [t for t in _load(path_for(workspace, home)) if _in_history(t)]
|
|
115
|
+
if not turns:
|
|
116
|
+
return ""
|
|
117
|
+
parts, used = [], 0
|
|
118
|
+
for t in reversed(turns):
|
|
119
|
+
segs = []
|
|
120
|
+
for st in reversed(t.get("steps") or []):
|
|
121
|
+
seg = f" - ran: {st.get('did', '')}" + (
|
|
122
|
+
f"\n found: {st['found']}" if st.get("found") and not local_model else "")
|
|
123
|
+
if used + len(seg) > budget:
|
|
124
|
+
break
|
|
125
|
+
segs.append(seg)
|
|
126
|
+
used += len(seg)
|
|
127
|
+
if segs:
|
|
128
|
+
parts.append(f"Turn \"{t.get('asked', '')}\":\n" + "\n".join(reversed(segs)))
|
|
129
|
+
if used >= budget:
|
|
130
|
+
break
|
|
131
|
+
if not parts:
|
|
132
|
+
return ""
|
|
133
|
+
return ("WHAT EARLIER TURNS OF THIS CONVERSATION RAN (their answers above don't say how). "
|
|
134
|
+
"Reuse what worked — the same command, server, file or path — instead of searching "
|
|
135
|
+
"again. Secrets show as ***: read them again from where that step found them.\n"
|
|
136
|
+
+ "\n".join(reversed(parts)))
|
|
137
|
+
except Exception: # noqa: BLE001
|
|
138
|
+
return ""
|
package/gudb-size.mjs
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GH #594: gu's local database (gudb, ~/.gu/gudb/gu.db) — how big it is, what makes it big, and
|
|
3
|
+
* the one safe cleanup.
|
|
4
|
+
*
|
|
5
|
+
* Measured on the owner's Mac (2026-12-04): 25 MB after two days, 94% of it ONE field — the full
|
|
6
|
+
* prompt kept for every model step (`promptText` in c_agent_code_responses), saved only when "keep
|
|
7
|
+
* full model responses" is on. A busy day added 17 MB. Nothing else in gudb grows like that, and
|
|
8
|
+
* nothing expired it.
|
|
9
|
+
*
|
|
10
|
+
* The cleanup removes that saved TEXT (prompt and response) from steps older than N days and
|
|
11
|
+
* keeps every row — the usage numbers (tokens, model, time) stay. Then it compacts the file.
|
|
12
|
+
* Never touches jobs, settings, keys, workspaces or billing.
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, mkdirSync, readdirSync, rmSync, statSync, statfsSync } from "node:fs";
|
|
15
|
+
import { createRequire } from "node:module";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { dirname, join } from "node:path";
|
|
18
|
+
|
|
19
|
+
// Same path as client-expert-api.mjs gudbFile — not imported, so gu-repl can load this at startup cheaply.
|
|
20
|
+
export const gudbFile = (home = homedir()) => join(home, ".gu", "gudb", "gu.db");
|
|
21
|
+
|
|
22
|
+
/** A notice from here on; yellow from URGENT on. */
|
|
23
|
+
export const GUDB_NOTICE_BYTES = 1024 ** 3; // 1 GB
|
|
24
|
+
export const GUDB_URGENT_BYTES = 5 * 1024 ** 3; // 5 GB
|
|
25
|
+
/** Saved text older than this is what the cleanup offers to remove. */
|
|
26
|
+
export const KEEP_TEXT_DAYS = 14;
|
|
27
|
+
/** GH #594 #1: older than this, the worker removes it by itself (daily). The rows stay. */
|
|
28
|
+
export const AUTO_KEEP_TEXT_DAYS = 30;
|
|
29
|
+
/** GH #597: below this much free disk, gu warns — SQLite can't write, and compacting needs room. */
|
|
30
|
+
export const LOW_DISK_BYTES = 2 * 1024 ** 3;
|
|
31
|
+
/** GH #598: backups kept by /backup-db, newest first. */
|
|
32
|
+
export const KEEP_BACKUPS = 3;
|
|
33
|
+
|
|
34
|
+
const TABLE = "c_agent_code_responses";
|
|
35
|
+
|
|
36
|
+
function open(path, { readOnly = true } = {}) {
|
|
37
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
38
|
+
const db = new DatabaseSync(path, readOnly ? { readOnly: true } : {});
|
|
39
|
+
db.exec("PRAGMA busy_timeout = 5000;");
|
|
40
|
+
return db;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The file with its WAL and shared-memory files: what it takes on disk. */
|
|
44
|
+
export function gudbBytes(path = gudbFile()) {
|
|
45
|
+
let n = 0;
|
|
46
|
+
for (const p of [path, `${path}-wal`, `${path}-shm`]) {
|
|
47
|
+
try {
|
|
48
|
+
n += statSync(p).size;
|
|
49
|
+
} catch {
|
|
50
|
+
/* not there */
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return n;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const cutoffIso = (days, now = Date.now()) => new Date(now - days * 86_400_000).toISOString();
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* What is in it. → { path, bytes, text: { bytes, rows }, oldText: { bytes, rows }, days } — or null
|
|
60
|
+
* when there is no gudb here (Cloud mode, a Mongo computer) or it can't be read.
|
|
61
|
+
*/
|
|
62
|
+
export function surveyGudb({ path = gudbFile(), days = KEEP_TEXT_DAYS, now = Date.now() } = {}) {
|
|
63
|
+
if (!existsSync(path)) return null;
|
|
64
|
+
let db;
|
|
65
|
+
try {
|
|
66
|
+
db = open(path);
|
|
67
|
+
const has = db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(TABLE);
|
|
68
|
+
const sum = (where, ...args) => has
|
|
69
|
+
? db.prepare(`SELECT COUNT(*) AS rows, COALESCE(SUM(COALESCE(LENGTH(json_extract(doc,'$.promptText')),0) + COALESCE(LENGTH(json_extract(doc,'$.text')),0)),0) AS bytes
|
|
70
|
+
FROM ${TABLE} WHERE (json_extract(doc,'$.promptText') <> '' OR json_extract(doc,'$.text') <> '') ${where}`).get(...args)
|
|
71
|
+
: { rows: 0, bytes: 0 };
|
|
72
|
+
const text = sum("");
|
|
73
|
+
const oldText = sum("AND json_extract(doc,'$.createdAt') < ?", cutoffIso(days, now));
|
|
74
|
+
return { path, bytes: gudbBytes(path), text: { bytes: Number(text.bytes), rows: Number(text.rows) },
|
|
75
|
+
oldText: { bytes: Number(oldText.bytes), rows: Number(oldText.rows) }, days };
|
|
76
|
+
} catch {
|
|
77
|
+
return null;
|
|
78
|
+
} finally {
|
|
79
|
+
try { db?.close(); } catch { /* closed */ }
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Remove the saved prompt/response text from steps older than `days`, keep the rows, then compact.
|
|
85
|
+
* → { cleared: rows, before, after, freed } or { error }.
|
|
86
|
+
* Compacting (VACUUM) needs free disk about the size of the file, and waits for gu's API to be idle.
|
|
87
|
+
*/
|
|
88
|
+
export function clearOldText({ path = gudbFile(), days = KEEP_TEXT_DAYS, now = Date.now(), compact = true } = {}) {
|
|
89
|
+
const before = gudbBytes(path);
|
|
90
|
+
let db;
|
|
91
|
+
try {
|
|
92
|
+
db = open(path, { readOnly: false });
|
|
93
|
+
const r = db.prepare(`UPDATE ${TABLE} SET doc = json_remove(doc, '$.promptText', '$.text')
|
|
94
|
+
WHERE json_extract(doc,'$.createdAt') < ?
|
|
95
|
+
AND (json_extract(doc,'$.promptText') IS NOT NULL OR json_extract(doc,'$.text') IS NOT NULL)`)
|
|
96
|
+
.run(cutoffIso(days, now));
|
|
97
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
98
|
+
// Without compacting the file keeps its size, but SQLite reuses the freed pages for new rows —
|
|
99
|
+
// so the AUTOMATIC run (no long lock while gu works) still stops the growth.
|
|
100
|
+
let compacted = false;
|
|
101
|
+
if (compact) {
|
|
102
|
+
try {
|
|
103
|
+
db.exec("VACUUM;");
|
|
104
|
+
compacted = true;
|
|
105
|
+
} catch {
|
|
106
|
+
/* busy, or no room: the text is gone anyway; the space comes back next time */
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE);");
|
|
110
|
+
const after = gudbBytes(path);
|
|
111
|
+
return { cleared: Number(r.changes), before, after, freed: Math.max(0, before - after), compacted };
|
|
112
|
+
} catch (e) {
|
|
113
|
+
return { error: String(e?.message ?? e) };
|
|
114
|
+
} finally {
|
|
115
|
+
try { db?.close(); } catch { /* closed */ }
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const human = (n) => {
|
|
120
|
+
const u = ["B", "KB", "MB", "GB", "TB"];
|
|
121
|
+
let i = 0;
|
|
122
|
+
let v = Number(n) || 0;
|
|
123
|
+
while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; }
|
|
124
|
+
return `${v >= 10 || i === 0 ? Math.round(v) : v.toFixed(1)} ${u[i]}`;
|
|
125
|
+
};
|
|
126
|
+
export { human as gudbHuman };
|
|
127
|
+
|
|
128
|
+
/** The notice row's item, or "" below the threshold. → { text, urgent } | null */
|
|
129
|
+
export function gudbNotice(bytes, { threshold = GUDB_NOTICE_BYTES, urgent = GUDB_URGENT_BYTES } = {}) {
|
|
130
|
+
const n = Number(bytes) || 0;
|
|
131
|
+
if (n < threshold) return null;
|
|
132
|
+
return { text: `gu database ${human(n)} · clean old data (click)`, urgent: n >= urgent };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Free bytes on the disk that holds `dir` (or its nearest existing parent). null when unknown. */
|
|
136
|
+
export function freeDiskBytes(dir = join(homedir(), ".gu")) {
|
|
137
|
+
let d = dir;
|
|
138
|
+
while (d && !existsSync(d)) {
|
|
139
|
+
const up = dirname(d);
|
|
140
|
+
if (up === d) break;
|
|
141
|
+
d = up;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const st = statfsSync(d);
|
|
145
|
+
return Number(st.bavail) * Number(st.bsize);
|
|
146
|
+
} catch {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** GH #597: the notice row's item when the disk is nearly full, else null. */
|
|
152
|
+
export function lowDiskNotice(free, { threshold = LOW_DISK_BYTES } = {}) {
|
|
153
|
+
if (free == null || free >= threshold) return null;
|
|
154
|
+
return { text: `disk almost full · ${human(free)} free (click)`, urgent: true };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The worker's daily run (GH #594 #1): saved text older than 30 days goes, rows stay, no compacting.
|
|
159
|
+
* → the clearOldText result, or null when there is no gudb here.
|
|
160
|
+
*/
|
|
161
|
+
export function autoClearOldText({ path = gudbFile(), days = AUTO_KEEP_TEXT_DAYS, now = Date.now() } = {}) {
|
|
162
|
+
if (!existsSync(path)) return null;
|
|
163
|
+
return clearOldText({ path, days, now, compact: false });
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* GH #598: a backup made BY SQLITE (VACUUM INTO) — consistent even while gu's API writes, WAL
|
|
168
|
+
* included, which a plain file copy is not. → { file, bytes, removed } or { error }.
|
|
169
|
+
* Refused when the disk would be left under LOW_DISK_BYTES; keeps the newest `keep`.
|
|
170
|
+
*/
|
|
171
|
+
export function backupGudb({ path = gudbFile(), dir = join(dirname(path), "backups"), keep = KEEP_BACKUPS,
|
|
172
|
+
now = Date.now(), free = freeDiskBytes(dirname(path)) } = {}) {
|
|
173
|
+
if (!existsSync(path)) return { error: "there is no gu database on this computer" };
|
|
174
|
+
const size = gudbBytes(path);
|
|
175
|
+
if (free != null && free - size < LOW_DISK_BYTES) {
|
|
176
|
+
return { error: `not enough free disk: a backup needs about ${human(size)} and would leave less than ${human(LOW_DISK_BYTES)} free` };
|
|
177
|
+
}
|
|
178
|
+
// 20261204-120000: sorts by time, matches the pattern the pruning below looks for
|
|
179
|
+
const stamp = new Date(now).toISOString().slice(0, 19).replace(/[-:]/g, "").replace("T", "-");
|
|
180
|
+
const file = join(dir, `gu-${stamp}.db`);
|
|
181
|
+
let db;
|
|
182
|
+
try {
|
|
183
|
+
mkdirSync(dir, { recursive: true });
|
|
184
|
+
if (existsSync(file)) rmSync(file);
|
|
185
|
+
db = open(path);
|
|
186
|
+
db.prepare("VACUUM INTO ?").run(file);
|
|
187
|
+
} catch (e) {
|
|
188
|
+
return { error: String(e?.message ?? e) };
|
|
189
|
+
} finally {
|
|
190
|
+
try { db?.close(); } catch { /* closed */ }
|
|
191
|
+
}
|
|
192
|
+
const all = readdirSync(dir).filter((f) => /^gu-\d{8}-\d{6}\.db$/.test(f)).sort().reverse();
|
|
193
|
+
const removed = [];
|
|
194
|
+
for (const old of all.slice(Math.max(1, keep))) {
|
|
195
|
+
try { rmSync(join(dir, old)); removed.push(old); } catch { /* left */ }
|
|
196
|
+
}
|
|
197
|
+
return { file, bytes: statSync(file).size, removed };
|
|
198
|
+
}
|
package/memory-task.mjs
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GH #595: WHICH TASK the memory skill is recording this session's work under — on gu's bar, so a
|
|
3
|
+
* misfiling is seen before the work is done, not after. Reported 2026-12-04: a morning's laggy-call
|
|
4
|
+
* investigation in meetings was filed under the open JBL task, and nothing on screen said so.
|
|
5
|
+
*
|
|
6
|
+
* gu and Claude Code share ONE memory (the same skill runtime, the same .claude-memory in the
|
|
7
|
+
* project), so the question is never "which skill" — it is "which task". The memory's own CLI
|
|
8
|
+
* answers it (current-task: what a message naming no task would be filed under), and /task
|
|
9
|
+
* switches it (set-task).
|
|
10
|
+
*/
|
|
11
|
+
import { execFile } from "node:child_process";
|
|
12
|
+
import { existsSync } from "node:fs";
|
|
13
|
+
import { dirname, join } from "node:path";
|
|
14
|
+
|
|
15
|
+
/** The memory runtime gu's hooks run, from the hooks config → { python, cli } or null when not installed. */
|
|
16
|
+
export function memoryRuntime(hooks) {
|
|
17
|
+
for (const groups of Object.values(hooks ?? {})) {
|
|
18
|
+
for (const g of Array.isArray(groups) ? groups : []) {
|
|
19
|
+
for (const h of g?.hooks ?? []) {
|
|
20
|
+
const script = (h?.args ?? []).find((a) => /memory_hook\.py$/.test(String(a)));
|
|
21
|
+
if (!script || !h.command) continue;
|
|
22
|
+
const cli = join(dirname(dirname(String(script))), "memory_cli.py");
|
|
23
|
+
if (existsSync(cli)) return { python: String(h.command), cli };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function run(runtime, args, { timeoutMs = 8000, execImpl = execFile } = {}) {
|
|
31
|
+
return new Promise((resolve) => {
|
|
32
|
+
execImpl(runtime.python, [runtime.cli, ...args], { timeout: timeoutMs, encoding: "utf8" }, (err, stdout) => {
|
|
33
|
+
if (err) return resolve(null);
|
|
34
|
+
try {
|
|
35
|
+
resolve(JSON.parse(String(stdout)));
|
|
36
|
+
} catch {
|
|
37
|
+
resolve(null);
|
|
38
|
+
}
|
|
39
|
+
});
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** → { project, task: {id,title,status}|null, chosen, open: [...] } or null (no memory here / not readable). */
|
|
44
|
+
export async function currentTask({ runtime, cwd, session = "", execImpl } = {}) {
|
|
45
|
+
if (!runtime || !cwd) return null;
|
|
46
|
+
const r = await run(runtime, ["current-task", "--cwd", cwd, "--session", session], { execImpl });
|
|
47
|
+
return r?.current ?? null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** File this session's next steps under task `id`. → { id, title } or null. */
|
|
51
|
+
export async function setTask({ runtime, cwd, session, id, execImpl } = {}) {
|
|
52
|
+
if (!runtime || !cwd || !session) return null;
|
|
53
|
+
const r = await run(runtime, ["set-task", "--cwd", cwd, "--session", session, "--task", String(id)], { execImpl });
|
|
54
|
+
return r?.task ?? null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const clip = (s, n) => {
|
|
58
|
+
const a = Array.from(String(s ?? "").replace(/\s+/g, " ").trim());
|
|
59
|
+
return a.length <= n ? a.join("") : a.slice(0, Math.max(1, n - 1)).join("") + "…";
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The bar's text, in `room` columns, or "" when there is nothing to say (no memory here).
|
|
64
|
+
* `guess`: the task was NOT chosen for this session — it is only the project's newest open one,
|
|
65
|
+
* which is exactly how work gets misfiled; the caller paints that yellow.
|
|
66
|
+
*/
|
|
67
|
+
export function memoryBarText(cur, room = 40) {
|
|
68
|
+
if (!cur) return { text: "", guess: false };
|
|
69
|
+
const tail = " (/task)";
|
|
70
|
+
if (!cur.task) return { text: clip("◆ memory: no task yet", room - tail.length) + tail, guess: false };
|
|
71
|
+
const head = `◆ memory → #${cur.task.id} `;
|
|
72
|
+
const titleRoom = room - head.length - tail.length;
|
|
73
|
+
if (titleRoom < 6) return { text: clip(`◆ #${cur.task.id}`, Math.max(4, room - tail.length)) + tail, guess: !cur.chosen };
|
|
74
|
+
return { text: head + clip(cur.task.title, titleRoom) + tail, guess: !cur.chosen };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The /task picker's rows: the open tasks, the current one marked. */
|
|
78
|
+
export function taskPickerLabels(cur, width = 80) {
|
|
79
|
+
const rows = Array.isArray(cur?.open) ? cur.open : [];
|
|
80
|
+
return rows.map((t) => {
|
|
81
|
+
const mark = cur?.task && t.id === cur.task.id ? "● " : " ";
|
|
82
|
+
const status = t.status === "in_progress" ? "" : ` · ${t.status}`;
|
|
83
|
+
return mark + clip(`#${t.id} ${t.title}`, Math.max(20, width - 12 - status.length)) + status;
|
|
84
|
+
});
|
|
85
|
+
}
|
package/next-suggestion.mjs
CHANGED
|
@@ -28,7 +28,9 @@ export const SUGGESTION_MAX_CHARS = 80;
|
|
|
28
28
|
/** Shorter than this, an answer is a greeting or a one-liner: nothing follows from it. */
|
|
29
29
|
export const MIN_ANSWER_CHARS = 40;
|
|
30
30
|
/** The side call waits this long at most; after that there is simply no suggestion. */
|
|
31
|
-
|
|
31
|
+
// GH #587: a reasoning coder (deepseek-v4-pro) thinks first — 8s was often over before it answered.
|
|
32
|
+
// Nothing waits on it: a late suggestion is still shown if the prompt is still empty.
|
|
33
|
+
export const SUGGEST_TIMEOUT_MS = 20_000;
|
|
32
34
|
|
|
33
35
|
/** Gate 1: is this turn worth asking about at all? */
|
|
34
36
|
export function shouldSuggest({ question = "", answer = "", enabled = true } = {}) {
|
|
@@ -41,12 +43,15 @@ export function shouldSuggest({ question = "", answer = "", enabled = true } = {
|
|
|
41
43
|
|
|
42
44
|
const SYSTEM =
|
|
43
45
|
"You predict the user's NEXT message to a coding assistant in a terminal. You are shown the " +
|
|
44
|
-
"user's last request and the end of the assistant's answer. If the answer
|
|
45
|
-
"
|
|
46
|
-
"
|
|
47
|
-
"user would type it: 2 to 12 words, an instruction or a short
|
|
48
|
-
"
|
|
49
|
-
"
|
|
46
|
+
"user's last request and the end of the assistant's answer. If the answer leads to a next " +
|
|
47
|
+
"message — it asks the user to confirm or choose (for example \"Shall I merge?\"), offers a " +
|
|
48
|
+
"next step, or lists what is \"left for you\" / waits for the user's go-ahead — reply with ONLY " +
|
|
49
|
+
"that message, written as the user would type it: 2 to 12 words, an instruction or a short " +
|
|
50
|
+
"reply such as \"yes, merge it\" or \"go ahead, upload the DMG\", in the language the user " +
|
|
51
|
+
"writes in. When it offers SEVERAL options, pick the one the answer recommends, else the " +
|
|
52
|
+
"simplest one, and name it (\"just upload the notarized DMG\") — never a bare \"yes\" that " +
|
|
53
|
+
"could mean either. Reply with exactly NONE only when the answer leads nowhere (a plain fact, " +
|
|
54
|
+
"an explanation, a finished task with nothing offered). No quotes, no explanation, never a question.";
|
|
50
55
|
|
|
51
56
|
const tail = (s, n) => {
|
|
52
57
|
const chars = Array.from(String(s ?? ""));
|
|
@@ -58,7 +63,7 @@ export function suggestionRequest(model, { question = "", answer = "" } = {}) {
|
|
|
58
63
|
return {
|
|
59
64
|
model,
|
|
60
65
|
stream: false,
|
|
61
|
-
max_tokens:
|
|
66
|
+
max_tokens: 800, // GH #587: room for a reasoning model to think and still answer (300 could run out first)
|
|
62
67
|
messages: [
|
|
63
68
|
{ role: "system", content: SYSTEM },
|
|
64
69
|
{ role: "user", content: `User's request:\n${q}\n\nEnd of the assistant's answer:\n${tail(answer, ANSWER_TAIL_MAX)}` },
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tiens.nguyen/gu-cli",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.941",
|
|
4
4
|
"description": "gu: the coding agent in your terminal. It reads your repo, makes the change and runs the tests, with your own models (Ollama or any OpenAI-compatible provider). Free installs keep the agent, its API and its database on your machine. macOS, Linux and Windows.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -121,6 +121,8 @@
|
|
|
121
121
|
"support-bundle.mjs",
|
|
122
122
|
"support-command.mjs",
|
|
123
123
|
"clear-logs.mjs",
|
|
124
|
+
"gudb-size.mjs",
|
|
125
|
+
"memory-task.mjs",
|
|
124
126
|
"platform-tools.mjs",
|
|
125
127
|
"job-pools.mjs",
|
|
126
128
|
"agent-stop.mjs",
|
|
@@ -201,6 +203,7 @@
|
|
|
201
203
|
"gu_free_budget.py",
|
|
202
204
|
"turn-notes.mjs",
|
|
203
205
|
"gu_hooks.py",
|
|
206
|
+
"gu_turn_trail.py",
|
|
204
207
|
"prompt_scaffold_check.py",
|
|
205
208
|
"gonext_transcribe.py",
|
|
206
209
|
"gonext_mlx_embed.py",
|
package/terminal-layout.mjs
CHANGED
|
@@ -2752,7 +2752,31 @@ export function agentPickerItems(rows, { width = 80 } = {}) {
|
|
|
2752
2752
|
return out;
|
|
2753
2753
|
}
|
|
2754
2754
|
|
|
2755
|
+
/**
|
|
2756
|
+
* The other agents as a PANEL in place of the input box (GH #586) — what the "N agents running
|
|
2757
|
+
* (click)" link opens while this terminal's own turn runs. The picker can't be used then
|
|
2758
|
+
* (switching to another agent is a turn of its own), and the click used to do nothing at all.
|
|
2759
|
+
* items: agentPickerItems(); sel: the highlighted row; note: one line about what just happened.
|
|
2760
|
+
*/
|
|
2761
|
+
export function agentsPanelRows({ items = [], sel = 0, width = 80, rows = 10, note = "", gutter = " ",
|
|
2762
|
+
style = {} } = {}) {
|
|
2763
|
+
const S = { title: (t) => t, mark: (t) => t, dim: (t) => t, ...style };
|
|
2764
|
+
const room = Math.max(1, rows - 2); // title + footer
|
|
2765
|
+
const n = items.length;
|
|
2766
|
+
const at = Math.min(Math.max(0, sel | 0), Math.max(0, n - 1));
|
|
2767
|
+
const from = Math.max(0, Math.min(at - room + 1, n - room));
|
|
2768
|
+
const out = [gutter + S.title(n ? `Your other running agents (${n})` : "No other agents running for your account.")];
|
|
2769
|
+
for (let i = from; i < Math.min(n, from + room); i++) {
|
|
2770
|
+
const label = items[i].label.slice(0, Math.max(10, width - gutter.length - 3));
|
|
2771
|
+
out.push(gutter + (i === at ? S.mark("▸ " + label) : " " + label));
|
|
2772
|
+
}
|
|
2773
|
+
out.push(gutter + S.dim(note || (n ? "↑↓ choose · s stop it · Esc close — to switch to one, click again after this turn"
|
|
2774
|
+
: "Esc close")));
|
|
2775
|
+
return out;
|
|
2776
|
+
}
|
|
2777
|
+
|
|
2755
2778
|
export const HIDDEN_COMMANDS = [
|
|
2779
|
+
"/tasks", // GH #595: the same as /task — listed once
|
|
2756
2780
|
"/provider", // and /providers — /model's picker carries "add or change an
|
|
2757
2781
|
"/providers", // OpenAI-compatible provider…" in every branch, so listing this
|
|
2758
2782
|
// too offered two doors into one setting (reported as confusing)
|