@tiens.nguyen/gu-cli 1.0.922 → 1.0.928
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/add-server.mjs +4 -2
- package/agent-model-command.mjs +7 -1
- package/coding-key-prompt.mjs +20 -0
- package/coding-provider-setup.mjs +20 -0
- package/command-allow.mjs +73 -8
- package/embed-model-command.mjs +10 -0
- package/gonext_agent_chat.py +126 -23
- package/gu-repl.mjs +132 -57
- package/model-setup-ui.mjs +2 -2
- package/package.json +1 -1
- package/turn-notes.mjs +19 -7
- package/turn-queue.mjs +4 -20
package/add-server.mjs
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* server kind ("dialect": an Ollama's /api/tags vs an OpenAI-compatible /v1/models) lives in
|
|
15
15
|
* serverTarget() and listRequest().
|
|
16
16
|
*/
|
|
17
|
-
import { defaultProviderUrl, ensureV1Root, hostLocality, isAnthropicUrl, isCancelWord, modelListRequest, normalizeProviderUrl, parseProviderModels, MAX_MODELS_PER_SERVER } from "./coding-provider-setup.mjs";
|
|
17
|
+
import { defaultProviderUrl, ensureV1Root, hostLocality, isAnthropicUrl, isKeylessHost, isCancelWord, modelListRequest, normalizeProviderUrl, parseProviderModels, MAX_MODELS_PER_SERVER } from "./coding-provider-setup.mjs";
|
|
18
18
|
|
|
19
19
|
// Re-exported: the add-server screen's own name for the rule every URL prompt shares.
|
|
20
20
|
export { isCancelWord };
|
|
@@ -144,7 +144,9 @@ export function roleRefusal(role, target) {
|
|
|
144
144
|
export function keyRequirement(target) {
|
|
145
145
|
if (!target?.ok) return "none";
|
|
146
146
|
if (target.dialect === "ollama") return target.cloud ? "required" : "none";
|
|
147
|
-
|
|
147
|
+
if (target.locality === "loopback" || target.locality === "private") return "optional";
|
|
148
|
+
// A known LAN name (ollama1.getmarsic.cc, GH #521): Enter skips the key here too.
|
|
149
|
+
return isKeylessHost(target.host) ? "optional" : "required";
|
|
148
150
|
}
|
|
149
151
|
|
|
150
152
|
/**
|
package/agent-model-command.mjs
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
20
|
import { modelRetired, ensureV1Root, isAnthropicUrl, modelListRequest } from "./coding-provider-setup.mjs";
|
|
21
|
-
import { isOllamaCloudUrl } from "./coding-key-prompt.mjs";
|
|
21
|
+
import { isOllamaCloudUrl, isLocalNetworkUrl } from "./coding-key-prompt.mjs";
|
|
22
22
|
|
|
23
23
|
|
|
24
24
|
/**
|
|
@@ -278,6 +278,12 @@ export function agentModelsFromBody(dialect, body, now = Date.now()) {
|
|
|
278
278
|
* or LAN Ollama does not.
|
|
279
279
|
*/
|
|
280
280
|
export function agentSourceNeedsKey(source) {
|
|
281
|
+
if (!agentSourceCanUseKey(source)) return false;
|
|
282
|
+
return !(source.dialect === "openai" && isLocalNetworkUrl(source.row.url));
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** MAY this source be given a key? Its stored key is sent, and "API keys for …" is offered (GH #521). */
|
|
286
|
+
export function agentSourceCanUseKey(source) {
|
|
281
287
|
const row = source?.row;
|
|
282
288
|
if (!row) return false;
|
|
283
289
|
return source.dialect === "openai" || isOllamaCloudUrl(String(row.url ?? ""));
|
package/coding-key-prompt.mjs
CHANGED
|
@@ -26,6 +26,7 @@ const identity = (s) => s;
|
|
|
26
26
|
*/
|
|
27
27
|
import { keyInUse } from "./server-keys.mjs";
|
|
28
28
|
import { resultLine } from "./first-hi.mjs";
|
|
29
|
+
import { isKeylessHost } from "./coding-provider-setup.mjs";
|
|
29
30
|
|
|
30
31
|
export const SECRET_KEY_HINT = "type or paste the key, then press Enter — it stays masked";
|
|
31
32
|
|
|
@@ -80,9 +81,28 @@ export function isOllamaCloudUrl(url) {
|
|
|
80
81
|
* belief that Ollama never authenticates — true of a local or LAN Ollama, false of ollama.com.
|
|
81
82
|
*/
|
|
82
83
|
export function codingNeedsKey(kind, url) {
|
|
84
|
+
return codingCanUseKey(kind, url) && !(kind === "openai" && isLocalNetworkUrl(url));
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* MAY this coder be given a key? Wider than "must have one": an OpenAI-compatible server on your own
|
|
89
|
+
* network works without a key, but can be set to ask for one, so ctrl+k must still reach it (GH #521).
|
|
90
|
+
*/
|
|
91
|
+
export function codingCanUseKey(kind, url) {
|
|
83
92
|
return kind === "openai" || (kind === "ollama" && isOllamaCloudUrl(url));
|
|
84
93
|
}
|
|
85
94
|
|
|
95
|
+
/** This machine, a private network or a known LAN name — the same rule "add a provider" and the API use. */
|
|
96
|
+
export function isLocalNetworkUrl(url) {
|
|
97
|
+
let host;
|
|
98
|
+
try {
|
|
99
|
+
host = new URL(String(url ?? "").trim()).hostname;
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
return isKeylessHost(host);
|
|
104
|
+
}
|
|
105
|
+
|
|
86
106
|
/**
|
|
87
107
|
* @param payload the /agent-payload `payload` object (reads codingKeyMissing/codingKeyModel).
|
|
88
108
|
* @param deps.askSecret async (prompt) => string — masked input; "" means the user skipped.
|
|
@@ -28,6 +28,26 @@ const METADATA_HOSTS = new Set([
|
|
|
28
28
|
const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
29
29
|
|
|
30
30
|
/** Loopback, LAN, or a name that can only resolve inside a network. */
|
|
31
|
+
/**
|
|
32
|
+
* NAMES THAT WRAP A LAN BOX (GH #521). The owner's own Ollama servers get a public-looking DNS name
|
|
33
|
+
* (ollama1.getmarsic.cc → 192.168.x). Matched NARROWLY — ollama<number>.getmarsic.cc and nothing
|
|
34
|
+
* else under that domain — so no hosted provider can ever be read as keyless. Keep in step with
|
|
35
|
+
* KEYLESS_LAN_NAME in api/src/store/settingsTypes.ts.
|
|
36
|
+
*/
|
|
37
|
+
export const KEYLESS_LAN_NAME = /^ollama\d*\.getmarsic\.cc$/;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* May this server be called WITHOUT a key? This machine, a private network, or a known LAN name.
|
|
41
|
+
* Only the key question reads this; hostLocality stays the truth about WHERE a host is (it also
|
|
42
|
+
* guesses http vs https, which a wrapped name must not change).
|
|
43
|
+
*/
|
|
44
|
+
export function isKeylessHost(hostname) {
|
|
45
|
+
const where = hostLocality(hostname);
|
|
46
|
+
if (where === "loopback" || where === "private") return true;
|
|
47
|
+
const host = String(hostname ?? "").toLowerCase().replace(/:\d+$/, "").replace(/\.$/, "");
|
|
48
|
+
return KEYLESS_LAN_NAME.test(host);
|
|
49
|
+
}
|
|
50
|
+
|
|
31
51
|
export function hostLocality(hostname) {
|
|
32
52
|
let host = String(hostname ?? "").toLowerCase().replace(/\.$/, "");
|
|
33
53
|
// A PORT MAY COME ALONG. Callers hand this both a bare hostname (from URL.hostname) and a
|
package/command-allow.mjs
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// question ("a destructive command ...") can be skipped by it - sudo, the denylist and deletes
|
|
4
4
|
// outside the project are never covered by it.
|
|
5
5
|
import { readFileSync, writeFileSync, mkdirSync, realpathSync } from "node:fs";
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
6
7
|
import { dirname, join, sep } from "node:path";
|
|
7
8
|
import { homedir } from "node:os";
|
|
8
9
|
|
|
@@ -14,22 +15,86 @@ const real = (p) => {
|
|
|
14
15
|
return p;
|
|
15
16
|
}
|
|
16
17
|
};
|
|
17
|
-
|
|
18
|
+
function readAll() {
|
|
18
19
|
try {
|
|
19
|
-
const
|
|
20
|
-
return
|
|
20
|
+
const j = JSON.parse(readFileSync(commandAllowPath(), "utf8"));
|
|
21
|
+
return j && typeof j === "object" ? j : {};
|
|
21
22
|
} catch {
|
|
22
|
-
return
|
|
23
|
+
return {};
|
|
23
24
|
}
|
|
24
25
|
}
|
|
26
|
+
function writeAll(j) {
|
|
27
|
+
mkdirSync(dirname(commandAllowPath()), { recursive: true });
|
|
28
|
+
writeFileSync(commandAllowPath(), JSON.stringify(j, null, 2));
|
|
29
|
+
}
|
|
30
|
+
const inside = (f, r) => f === r || f.startsWith(r.replace(/[\\/]+$/, "") + sep);
|
|
31
|
+
export function commandAllowList() {
|
|
32
|
+
const f = readAll().folders;
|
|
33
|
+
return Array.isArray(f) ? f : [];
|
|
34
|
+
}
|
|
25
35
|
/** Is `folder` on the list, or inside a folder that is (a project covers its subfolders)? */
|
|
26
36
|
export function commandAllowedIn(folder) {
|
|
27
37
|
const f = real(folder);
|
|
28
|
-
return commandAllowList().some((r) => f
|
|
38
|
+
return commandAllowList().some((r) => inside(f, r));
|
|
29
39
|
}
|
|
40
|
+
/** Add the folder, or (allow=false) take it back. */
|
|
30
41
|
export function commandAllowIn(folder, allow = true) {
|
|
31
42
|
const f = real(folder);
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
43
|
+
const j = readAll();
|
|
44
|
+
j.folders = [...commandAllowList().filter((x) => x !== f), ...(allow ? [f] : [])];
|
|
45
|
+
writeAll(j);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// "Yes, don't ask again for this project" (GH #515): no "Allow running this command?" at all here —
|
|
49
|
+
// including sudo and deletes outside the project. A list of its own, so an older, narrower yes
|
|
50
|
+
// ("always in this folder", destructive commands only) is never widened to this.
|
|
51
|
+
export const PROJECT_CHOICE = "Yes, don't ask again for this project";
|
|
52
|
+
export function projectList() {
|
|
53
|
+
const l = readAll().projects;
|
|
54
|
+
return Array.isArray(l) ? l : [];
|
|
55
|
+
}
|
|
56
|
+
export function commandProjectAllowed(folder) {
|
|
57
|
+
const f = real(folder);
|
|
58
|
+
return projectList().some((r) => inside(f, r));
|
|
59
|
+
}
|
|
60
|
+
export function commandAllowProject(folder) {
|
|
61
|
+
const f = real(folder);
|
|
62
|
+
const j = readAll();
|
|
63
|
+
j.projects = [...projectList().filter((x) => x !== f), f];
|
|
64
|
+
writeAll(j);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* /command forget — gu asks again HERE. Every remembered yes that reaches this folder goes: one given
|
|
69
|
+
* for it, inside it, or for a folder above it (which covered it).
|
|
70
|
+
*/
|
|
71
|
+
export function commandForget(folder) {
|
|
72
|
+
const f = real(folder);
|
|
73
|
+
const reaches = (r) => inside(f, String(r)) || inside(String(r), f);
|
|
74
|
+
const j = readAll();
|
|
75
|
+
j.folders = commandAllowList().filter((r) => !reaches(r));
|
|
76
|
+
j.projects = projectList().filter((r) => !reaches(r));
|
|
77
|
+
j.sourced = sourcedList().filter((e) => !reaches(e.folder));
|
|
78
|
+
writeAll(j);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// "Yes, don't ask again for this file" on the `source` question (GH #515): remembered for the file's
|
|
82
|
+
// CONTENTS — once it changes, gu asks again (a yes must not cover whatever is written into it later).
|
|
83
|
+
export const SOURCE_FILE_MARK = " · file: ";
|
|
84
|
+
/** The file the question is about, from its reason; "" for any other question. */
|
|
85
|
+
export function sourcedFileOf(why) {
|
|
86
|
+
const s = String(why ?? "");
|
|
87
|
+
if (!/^it runs text as code \((source|\.)\)/.test(s)) return "";
|
|
88
|
+
const i = s.indexOf(SOURCE_FILE_MARK);
|
|
89
|
+
return i < 0 ? "" : s.slice(i + SOURCE_FILE_MARK.length).trim();
|
|
90
|
+
}
|
|
91
|
+
export function sourcedList() {
|
|
92
|
+
const l = readAll().sourced;
|
|
93
|
+
return Array.isArray(l) ? l : [];
|
|
94
|
+
}
|
|
95
|
+
export function commandAllowSource(folder, path) {
|
|
96
|
+
const entry = { folder: real(folder), path, sha256: createHash("sha256").update(readFileSync(path)).digest("hex") };
|
|
97
|
+
const j = readAll();
|
|
98
|
+
j.sourced = [...sourcedList().filter((e) => !(e.path === path && e.folder === entry.folder)), entry];
|
|
99
|
+
writeAll(j);
|
|
35
100
|
}
|
package/embed-model-command.mjs
CHANGED
|
@@ -224,6 +224,16 @@ export function embedNotice({ state, model } = {}) {
|
|
|
224
224
|
return "no embed model — RAG is off · /embed-model";
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
+
/**
|
|
228
|
+
* AN OPEN WINDOW ON OLD CODE (GH #513): the gu on disk has another version than the one this window started
|
|
229
|
+
* with (a deploy, /update elsewhere, npm). Say so — never restart the window: what is on screen would go.
|
|
230
|
+
*/
|
|
231
|
+
export function versionNoticeRows(running, onDisk) {
|
|
232
|
+
const known = (v) => /^\d+\.\d+\.\d+/.test(String(v ?? ""));
|
|
233
|
+
if (!known(running) || !known(onDisk) || running === onDisk) return [];
|
|
234
|
+
return [`gu ${onDisk} is on this computer — Ctrl+C, then gu, to use it`];
|
|
235
|
+
}
|
|
236
|
+
|
|
227
237
|
/**
|
|
228
238
|
* WHICH SETUP ROWS THE BOTTOM BAR SHOWS (first-run noise, #188). A fresh install used to stack
|
|
229
239
|
* three warnings at once. Now they come in order of need, and pure (no OS-specific logic):
|
package/gonext_agent_chat.py
CHANGED
|
@@ -24,6 +24,7 @@ Emits NDJSON lines on stdout:
|
|
|
24
24
|
{"type": "final", "text": "..."} — assistant answer
|
|
25
25
|
"""
|
|
26
26
|
import contextlib
|
|
27
|
+
import hashlib
|
|
27
28
|
import json
|
|
28
29
|
import os
|
|
29
30
|
import random
|
|
@@ -1805,6 +1806,28 @@ def _sentinel_against_ollama(agent_base_url, agent_model_id, probe=None):
|
|
|
1805
1806
|
)
|
|
1806
1807
|
|
|
1807
1808
|
|
|
1809
|
+
def _server_of(url) -> tuple:
|
|
1810
|
+
"""(scheme, host, port) of a server URL, so that two paths on one server compare equal."""
|
|
1811
|
+
try:
|
|
1812
|
+
u = urlparse(str(url or "").strip())
|
|
1813
|
+
scheme = (u.scheme or "").lower()
|
|
1814
|
+
return scheme, (u.hostname or "").lower(), u.port or {"http": 80, "https": 443}.get(scheme)
|
|
1815
|
+
except ValueError:
|
|
1816
|
+
return str(url or ""), "", None
|
|
1817
|
+
|
|
1818
|
+
|
|
1819
|
+
def _coder_auth_key(coding_api_key, coding_base_url, agent_api_key, agent_base_url) -> str:
|
|
1820
|
+
"""The key sent to the coding server. A KEY BELONGS TO A SERVER (#245, GH #521): with no
|
|
1821
|
+
coding key, the chat model's key is used only when both are the same server. Any other server
|
|
1822
|
+
gets the placeholder "local" — never another provider's key (a keyless LAN box would have been
|
|
1823
|
+
sent the hosted chat key over plain http)."""
|
|
1824
|
+
if coding_api_key:
|
|
1825
|
+
return coding_api_key
|
|
1826
|
+
if _server_of(coding_base_url) == _server_of(agent_base_url):
|
|
1827
|
+
return agent_api_key
|
|
1828
|
+
return "local"
|
|
1829
|
+
|
|
1830
|
+
|
|
1808
1831
|
def _resolve_coding_target(agent_base_url, agent_model_id, raw_coding_base, raw_coding_model,
|
|
1809
1832
|
*, agent_api_key="", coding_api_key="", detect=None):
|
|
1810
1833
|
"""WHICH SERVER AND WHICH MODEL NAME does the CODE half of a turn actually use?
|
|
@@ -1846,7 +1869,9 @@ def _resolve_coding_target(agent_base_url, agent_model_id, raw_coding_base, raw_
|
|
|
1846
1869
|
# A DIFFERENT dedicated coding server. If no model name was given, ask the
|
|
1847
1870
|
# server which model it serves (mlx_lm.server otherwise tries to download a
|
|
1848
1871
|
# mismatched name from HF and 404s).
|
|
1849
|
-
detected = raw_coding_model or detect(
|
|
1872
|
+
detected = raw_coding_model or detect(
|
|
1873
|
+
raw_coding_base,
|
|
1874
|
+
_coder_auth_key(coding_api_key, raw_coding_base, agent_api_key, agent_base_url))
|
|
1850
1875
|
if detected:
|
|
1851
1876
|
return raw_coding_base, detected
|
|
1852
1877
|
_log(
|
|
@@ -4081,10 +4106,14 @@ def _plain_reply(messages: list, base_url: str, api_key: str, model_id: str,
|
|
|
4081
4106
|
# raw nginx 502 page can be a whole document) for whichever caller logs/surfaces it.
|
|
4082
4107
|
# The FIRST error is the model the user asked for; when the stand-in failed differently
|
|
4083
4108
|
# (e.g. a 502 on the fallback), the real cause would otherwise be hidden.
|
|
4084
|
-
|
|
4085
|
-
|
|
4086
|
-
|
|
4087
|
-
|
|
4109
|
+
# WHO did not answer (GH #521): "Connection error." alone named neither model nor server.
|
|
4110
|
+
def _who(t):
|
|
4111
|
+
return f"{t[1]} at {_host_of(t[0])}"
|
|
4112
|
+
|
|
4113
|
+
if first_err is not None and last_err is not first_err:
|
|
4114
|
+
raise RuntimeError(f"couldn't get a response ({_who(targets[0])}: {_clip(str(first_err), 110)}; "
|
|
4115
|
+
f"then {_who(targets[-1])}: {_clip(str(last_err), 70)})")
|
|
4116
|
+
raise RuntimeError(f"couldn't get a response ({_who(targets[0])}: {_clip(str(last_err), 160)})")
|
|
4088
4117
|
|
|
4089
4118
|
|
|
4090
4119
|
# A model-server call can fail for two very different reasons, and they deserve
|
|
@@ -8709,7 +8738,7 @@ def _ws_write_outside_reason(redirects, wd, roots=None):
|
|
|
8709
8738
|
return "it writes a file OUTSIDE the project (" + ", ".join(outside[:3]) + ")"
|
|
8710
8739
|
|
|
8711
8740
|
|
|
8712
|
-
def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
|
|
8741
|
+
def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None, env_file=None):
|
|
8713
8742
|
"""The run policy for a SHELL line, applied to each simple command in it.
|
|
8714
8743
|
|
|
8715
8744
|
→ (refuse, hard_reason, ask_reason): `refuse` is a finished error message (allowlist — never
|
|
@@ -8754,22 +8783,43 @@ def _ws_shell_command_risk(scan, denyset, wd="", allowset=None, roots=None):
|
|
|
8754
8783
|
and all(x.startswith("-") for x in a[1:]):
|
|
8755
8784
|
msg = f"it pipes text into {r}, which runs that text as code"
|
|
8756
8785
|
return (None, msg, msg)
|
|
8786
|
+
# `cd sub && rm -rf x`: judge a delete (or a sourced file) from the folder the shell will be in.
|
|
8787
|
+
cwds, cur = {}, wd
|
|
8788
|
+
for c in top:
|
|
8789
|
+
a = c["argv"]
|
|
8790
|
+
if a and a[0] == "cd" and len(a) >= 2 and c["sep"] not in ("|", "|&"):
|
|
8791
|
+
cur = os.path.normpath(os.path.join(cur or os.getcwd(),
|
|
8792
|
+
os.path.expanduser(_shell_path_to_native(a[1]))))
|
|
8793
|
+
cwds[id(c)] = cur
|
|
8794
|
+
# GH #515: gu sources <workspace>/.gonext/env ITSELF before every line (#181), so a line that sources
|
|
8795
|
+
# that same file adds nothing — never ask. Another file the user said yes to for good is not asked
|
|
8796
|
+
# while it is unchanged, and only when nothing but `cd` (or such sources) runs before it in the line:
|
|
8797
|
+
# anything else could rewrite it first.
|
|
8798
|
+
own_env = _ws_env_file() if env_file is None else env_file
|
|
8799
|
+
top_ids = [id(c) for c in top]
|
|
8800
|
+
untouched = set() # top commands with only cd / cleared sources before them
|
|
8801
|
+
clean_so_far = True
|
|
8802
|
+
for c in top:
|
|
8803
|
+
if clean_so_far:
|
|
8804
|
+
untouched.add(id(c))
|
|
8805
|
+
a = c["argv"]
|
|
8806
|
+
if not (a and (a[0] == "cd" or (a[0] in ("source", ".") and len(a) == 2)) and not c["redirects"]):
|
|
8807
|
+
clean_so_far = False
|
|
8757
8808
|
for c in every:
|
|
8758
8809
|
a = c["argv"]
|
|
8759
8810
|
if not a:
|
|
8760
8811
|
continue
|
|
8761
8812
|
if a[0] in _SHELL_EVAL_RUNNERS:
|
|
8813
|
+
target = _sourced_file(a, cwds.get(id(c), wd))
|
|
8814
|
+
if target:
|
|
8815
|
+
if own_env and target == os.path.realpath(own_env):
|
|
8816
|
+
continue
|
|
8817
|
+
if id(c) in top_ids and id(c) in untouched and _cmd_source_allowed(target, wd):
|
|
8818
|
+
continue
|
|
8819
|
+
return (None, None, f"it runs text as code ({a[0]}){_SOURCE_FILE_MARK}{target}")
|
|
8762
8820
|
return (None, None, f"it runs text as code ({a[0]})")
|
|
8763
8821
|
if "$" in a[0] or "`" in a[0]:
|
|
8764
8822
|
return (None, None, f"the program to run is only known at run time ({a[0][:40]})")
|
|
8765
|
-
# `cd sub && rm -rf x`: judge a delete from the folder the shell will be in when it runs.
|
|
8766
|
-
cwds, cur = {}, wd
|
|
8767
|
-
for c in top:
|
|
8768
|
-
a = c["argv"]
|
|
8769
|
-
if a and a[0] == "cd" and len(a) >= 2 and c["sep"] not in ("|", "|&"):
|
|
8770
|
-
cur = os.path.normpath(os.path.join(cur or os.getcwd(),
|
|
8771
|
-
os.path.expanduser(_shell_path_to_native(a[1]))))
|
|
8772
|
-
cwds[id(c)] = cur
|
|
8773
8823
|
for c in every:
|
|
8774
8824
|
here = cwds.get(id(c), wd)
|
|
8775
8825
|
if (_WS_DESTRUCTIVE_RE.search(" ".join(c["argv"]))
|
|
@@ -8828,6 +8878,23 @@ def _ps_native_paths(paths, wd):
|
|
|
8828
8878
|
return out
|
|
8829
8879
|
|
|
8830
8880
|
|
|
8881
|
+
# gu-repl.mjs reads the path after this mark to offer "don't ask again for this file" (GH #515).
|
|
8882
|
+
_SOURCE_FILE_MARK = " · file: "
|
|
8883
|
+
|
|
8884
|
+
|
|
8885
|
+
def _sourced_file(argv, wd):
|
|
8886
|
+
"""The real path `source X` / `. X` would read, or "" when it cannot be known for sure: extra
|
|
8887
|
+
arguments, a name only known at run time, a bare name (bash searches PATH for it), no such file."""
|
|
8888
|
+
if len(argv) != 2 or argv[0] not in ("source", "."):
|
|
8889
|
+
return ""
|
|
8890
|
+
p = argv[1]
|
|
8891
|
+
if "/" not in p or any(ch in p for ch in "$`*?[\t\n"):
|
|
8892
|
+
return ""
|
|
8893
|
+
p = os.path.expanduser(_shell_path_to_native(p))
|
|
8894
|
+
full = os.path.realpath(p if os.path.isabs(p) else os.path.join(wd or os.getcwd(), p))
|
|
8895
|
+
return full if os.path.isfile(full) else ""
|
|
8896
|
+
|
|
8897
|
+
|
|
8831
8898
|
def _ws_ps_command_risk(scan, denyset, wd="", allowset=None, roots=None):
|
|
8832
8899
|
"""_ws_shell_command_risk for a PowerShell line. Same contract: (refuse, hard, ask)."""
|
|
8833
8900
|
gp = _ps_mod()
|
|
@@ -9126,7 +9193,8 @@ _BG_LINE = ("A LONG job (build, deploy, big test run) → run_command(…, backg
|
|
|
9126
9193
|
"polls; a build whose result you need next is simpler as one run_command(…, "
|
|
9127
9194
|
"timeout_seconds=600). A command still running at its timeout moves to the background "
|
|
9128
9195
|
"by itself instead of being killed. Setup every command needs (exports) goes ONCE in "
|
|
9129
|
-
"<workspace>/.gonext/env, which
|
|
9196
|
+
"<workspace>/.gonext/env, which gu sources before each command by itself (never `source` "
|
|
9197
|
+
"it in a command). A recipe that WORKED "
|
|
9130
9198
|
"after effort (a login, build flags, a deploy path) or a short project summary goes as "
|
|
9131
9199
|
"ONE line in <workspace>/.gonext/notes.md, shown at the start of every later turn.\n")
|
|
9132
9200
|
|
|
@@ -9937,6 +10005,34 @@ def _cmd_allow_path():
|
|
|
9937
10005
|
return os.environ.get("GU_COMMAND_ALLOW") or os.path.join(os.path.expanduser("~"), ".gonext", "command-allow.json")
|
|
9938
10006
|
|
|
9939
10007
|
|
|
10008
|
+
def _cmd_source_allowed(path, wd):
|
|
10009
|
+
"""Did the user say "don't ask again for this file" (GH #515), here, for exactly these contents?"""
|
|
10010
|
+
try:
|
|
10011
|
+
with open(_cmd_allow_path(), encoding="utf-8") as f:
|
|
10012
|
+
entries = json.load(f).get("sourced") or []
|
|
10013
|
+
with open(path, "rb") as fh:
|
|
10014
|
+
digest = hashlib.sha256(fh.read()).hexdigest()
|
|
10015
|
+
here = os.path.realpath(wd or os.getcwd())
|
|
10016
|
+
return any(isinstance(e, dict) and e.get("path") == path and e.get("sha256") == digest
|
|
10017
|
+
and isinstance(e.get("folder"), str) and _ws_is_inside(here, [e["folder"]])
|
|
10018
|
+
for e in entries)
|
|
10019
|
+
except (OSError, ValueError, AttributeError, TypeError):
|
|
10020
|
+
return False
|
|
10021
|
+
|
|
10022
|
+
|
|
10023
|
+
def _cmd_project_allowed(folder):
|
|
10024
|
+
"""Is `folder` in a project the user said "don't ask again for this project" in (GH #515)?"""
|
|
10025
|
+
if not folder:
|
|
10026
|
+
return False
|
|
10027
|
+
try:
|
|
10028
|
+
with open(_cmd_allow_path(), encoding="utf-8") as f:
|
|
10029
|
+
projects = json.load(f).get("projects") or []
|
|
10030
|
+
real = os.path.realpath(folder)
|
|
10031
|
+
return any(isinstance(r, str) and r and _ws_is_inside(real, [r]) for r in projects)
|
|
10032
|
+
except (OSError, ValueError, AttributeError, TypeError):
|
|
10033
|
+
return False
|
|
10034
|
+
|
|
10035
|
+
|
|
9940
10036
|
def _cmd_allowed_in(folder):
|
|
9941
10037
|
"""Is `folder` on the always-allow list, or inside a folder that is?"""
|
|
9942
10038
|
if not folder:
|
|
@@ -11421,6 +11517,7 @@ def run_agent_chat(cfg):
|
|
|
11421
11517
|
agent_base_url, agent_model_id, raw_coding_base, raw_coding_model,
|
|
11422
11518
|
agent_api_key=agent_api_key, coding_api_key=coding_api_key,
|
|
11423
11519
|
)
|
|
11520
|
+
coder_key = _coder_auth_key(coding_api_key, coding_base_url, agent_api_key, agent_base_url)
|
|
11424
11521
|
# A coder WAS chosen and the chat model is doing its work (#343): its server would not say
|
|
11425
11522
|
# which model it serves. Said when the agent path starts — a plain chat turn does no coding,
|
|
11426
11523
|
# so there is nothing to have fallen back from.
|
|
@@ -12237,7 +12334,7 @@ def run_agent_chat(cfg):
|
|
|
12237
12334
|
# Small prompt → fast. Fall back to the coding model if the chat model is down.
|
|
12238
12335
|
answer = _plain_reply(messages, agent_base_url, agent_api_key, agent_model_id,
|
|
12239
12336
|
coding_base_url, coding_model_id,
|
|
12240
|
-
|
|
12337
|
+
coder_key)
|
|
12241
12338
|
_log(f"plain reply: {len(answer)} chars")
|
|
12242
12339
|
_emit({"type": "final", "text": answer})
|
|
12243
12340
|
return
|
|
@@ -13559,7 +13656,8 @@ def run_agent_chat(cfg):
|
|
|
13559
13656
|
import gu_turn_notes as _turn_notes
|
|
13560
13657
|
_n = _turn_notes.add_to_step(step_log, _job_id)
|
|
13561
13658
|
if _n:
|
|
13562
|
-
|
|
13659
|
+
# GH #514: a marker, not a message — gu moves the user's own words into the history here.
|
|
13660
|
+
_emit({"type": "step", "text": f"__USERNOTE__::{_n}"})
|
|
13563
13661
|
_log(f"step {step_num}: {_n} user note(s) added for the next step")
|
|
13564
13662
|
except Exception as e: # noqa: BLE001
|
|
13565
13663
|
_log(f"user note skip: {e}")
|
|
@@ -14600,8 +14698,8 @@ def run_agent_chat(cfg):
|
|
|
14600
14698
|
) from e
|
|
14601
14699
|
raise _AgentConfigError(
|
|
14602
14700
|
f"The agent coding backend ({_host}) rejected the request: "
|
|
14603
|
-
"NO coding API key
|
|
14604
|
-
"
|
|
14701
|
+
"NO coding API key is saved for it. Enter the API key for "
|
|
14702
|
+
"this coding backend — in "
|
|
14605
14703
|
"gu: press ctrl+k; on the web: Settings → Agent "
|
|
14606
14704
|
"(OpenAI-compatible, or Ollama with an https://ollama.com URL — "
|
|
14607
14705
|
"local Ollama needs no key)."
|
|
@@ -14611,8 +14709,7 @@ def run_agent_chat(cfg):
|
|
|
14611
14709
|
# key here 401s against a cloud coder, so the "This server has:
|
|
14612
14710
|
# …" hint — the only useful part of this error — silently
|
|
14613
14711
|
# vanished exactly when it was needed.
|
|
14614
|
-
ids = _list_model_ids(coding_base_url,
|
|
14615
|
-
coding_api_key or agent_api_key)
|
|
14712
|
+
ids = _list_model_ids(coding_base_url, coder_key)
|
|
14616
14713
|
have = f" This server has: {', '.join(ids)}." if ids else ""
|
|
14617
14714
|
raise _AgentConfigError(
|
|
14618
14715
|
f"The agent coding model {coding_model_id!r} does not "
|
|
@@ -15256,8 +15353,8 @@ def run_agent_chat(cfg):
|
|
|
15256
15353
|
model = _LoggingModel(
|
|
15257
15354
|
model_id=coding_model_id,
|
|
15258
15355
|
api_base=coding_base_url,
|
|
15259
|
-
# Task #108:
|
|
15260
|
-
api_key=
|
|
15356
|
+
# Task #108: the coding key; without one, the chat key only on the chat server (GH #521).
|
|
15357
|
+
api_key=coder_key,
|
|
15261
15358
|
# Stream for Ollama / OpenAI-compatible so a long generation keeps the connection
|
|
15262
15359
|
# warm and can't trip a reverse-proxy idle read-timeout (smolagents still gets the
|
|
15263
15360
|
# full text). Only a local MLX coder stays non-streaming.
|
|
@@ -16715,6 +16812,12 @@ def run_agent_chat(cfg):
|
|
|
16715
16812
|
# question is dropped, not that one.
|
|
16716
16813
|
_ask_reason = None if (_accept_edits or _ro_line) else (
|
|
16717
16814
|
"accept edits is off, so every command is confirmed first")
|
|
16815
|
+
# GH #515: "Yes, don't ask again for this project" — every command question, of every
|
|
16816
|
+
# kind. Only where someone can be asked (web and unattended runs keep their blocks), and
|
|
16817
|
+
# accept edits switched off (Shift+Tab) still confirms: that is the user asking to be asked.
|
|
16818
|
+
if _ask_reason and _interactive_approval and _cmd_project_allowed(wd or _WS_ACTIVE or _default_ws_root()):
|
|
16819
|
+
_ask_reason = None if (_accept_edits or _ro_line) else (
|
|
16820
|
+
"accept edits is off, so every command is confirmed first")
|
|
16718
16821
|
if _ask_reason:
|
|
16719
16822
|
if _priv and _facts:
|
|
16720
16823
|
_ask_reason += f" — {_facts['why']}"
|
package/gu-repl.mjs
CHANGED
|
@@ -146,7 +146,7 @@ import {
|
|
|
146
146
|
import { completedFlush, splitLiveStream } from "./completed-flush.mjs";
|
|
147
147
|
import { isScaffoldStep, isGroupableStep, stepGroupMark, stepGroupRows, relativizePaths } from "./step-group.mjs";
|
|
148
148
|
import { clearLogsNoticeText } from "./clear-logs.mjs";
|
|
149
|
-
import {
|
|
149
|
+
import { commandAllowedIn, commandAllowProject, commandAllowSource, commandForget, commandProjectAllowed, sourcedFileOf, PROJECT_CHOICE } from "./command-allow.mjs";
|
|
150
150
|
import { allowIn, allowedIn, bridgeCommand, browserReport, bridgeStatus, extensionDir, findDevInstalls, helpInstall, installExtensionFiles, installSteps, localLeftovers, openExtensionsPage, removeLocalFiles, STORE_URL, stopBridge } from "./browser-command.mjs";
|
|
151
151
|
import { commandLogFile, killShell, logTail, markAnnounced, readShells, recapQuestion, runningShells, shellsToRecap, statusText as shellStatusText, renderShellDetails, shellPanelRows, shellPickerLabel, shellState, shellsNotice } from "./shell-details.mjs";
|
|
152
152
|
import { discoverSkills, matchSkillCommand } from "./skills.mjs";
|
|
@@ -157,12 +157,12 @@ import { readHooks } from "./hooks-config.mjs";
|
|
|
157
157
|
import { readSkillSource, sourceLabel, SKILL_SOURCE_KEY } from "./skill-source.mjs";
|
|
158
158
|
import { codingBannerLabel, isOllamaCloudUrl, SECRET_KEY_HINT } from "./coding-key-prompt.mjs";
|
|
159
159
|
import { questionEchoText, thoughtPrintSeq, wrapDiffText } from "./terminal-layout.mjs";
|
|
160
|
-
import { createTurnQueue,
|
|
161
|
-
import { sendNote, takeUnread, sweepOldNotes,
|
|
160
|
+
import { createTurnQueue, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
|
|
161
|
+
import { sendNote, takeUnread, sweepOldNotes, parseUserNote, questionWithNotes, USERNOTE_PREFIX } from "./turn-notes.mjs"; // GH #506: …or go to the running turn
|
|
162
162
|
import { globalPrefixOf } from "./install-path.mjs";
|
|
163
163
|
import { indentBlock, commandBlockRows, wrapIndented } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
|
|
164
164
|
import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
|
|
165
|
-
import { embedNotice, embedState, setupNoticeRows } from "./embed-model-command.mjs";
|
|
165
|
+
import { embedNotice, embedState, setupNoticeRows, versionNoticeRows } from "./embed-model-command.mjs";
|
|
166
166
|
import { createConnectionWatch, modelHostsOf, offlineLine, probeReachable, stalledLine } from "./connection-watch.mjs";
|
|
167
167
|
import { HINTS, pickHint, hintRow, hintFits, HINT_AFTER_SECONDS } from "./hints.mjs";
|
|
168
168
|
import { normalizeQuick, quickReady, quickTarget, quickBarHint, quickWarning, QUICK_MAX } from "./quick-models.mjs";
|
|
@@ -239,6 +239,19 @@ const REPL_VERSION = (() => {
|
|
|
239
239
|
return "unknown";
|
|
240
240
|
}
|
|
241
241
|
})();
|
|
242
|
+
// The version on disk NOW, looked at every 20 s (GH #513). Unreadable (npm half-way through) → keep the last.
|
|
243
|
+
let diskVersion = REPL_VERSION;
|
|
244
|
+
setInterval(() => {
|
|
245
|
+
try {
|
|
246
|
+
const v = JSON.parse(readFileSync(join(DIR, "package.json"), "utf8")).version;
|
|
247
|
+
if (v && v !== diskVersion) {
|
|
248
|
+
diskVersion = v;
|
|
249
|
+
if (barPinned()) paintBar();
|
|
250
|
+
}
|
|
251
|
+
} catch {
|
|
252
|
+
/* try again next time */
|
|
253
|
+
}
|
|
254
|
+
}, 20_000).unref();
|
|
242
255
|
const ENV_FILE = join(homedir(), ".gonext", "worker.env");
|
|
243
256
|
const WS_FILE = join(homedir(), ".gonext", "workspaces.json");
|
|
244
257
|
const SESSIONS_DIR = join(homedir(), ".gonext", "sessions");
|
|
@@ -1240,6 +1253,27 @@ function pendingEchoRows() {
|
|
|
1240
1253
|
if (lines.length > 3) shown.push(dim(`${GUTTER}… ${lines.length - 3} more line(s)`));
|
|
1241
1254
|
return [...shown, ""];
|
|
1242
1255
|
}
|
|
1256
|
+
/** A message typed during a turn, drawn as every asked question is (GH #514). */
|
|
1257
|
+
function pastQuestion(text) {
|
|
1258
|
+
return questionEchoText(imageMarkersForDisplay(text), {
|
|
1259
|
+
width: process.stdout.columns || 80,
|
|
1260
|
+
paintPrompt: () => PROMPT_PAST,
|
|
1261
|
+
}) + "\n";
|
|
1262
|
+
}
|
|
1263
|
+
/** What waits for the agent, above the input box: dim ">> " rows, at most 3 lines each and 6 in all. */
|
|
1264
|
+
function waitingNoteRows() {
|
|
1265
|
+
if (!following) return [];
|
|
1266
|
+
const width = Math.max(20, process.stdout.columns || 80);
|
|
1267
|
+
const texts = [...waitingNotes.filter((n) => !n.shown).map((n) => n.text), ...turnQueue.list()];
|
|
1268
|
+
const rows = [];
|
|
1269
|
+
for (const t of texts) {
|
|
1270
|
+
const lines = pastQuestion(t).replace(/\n+$/, "").split("\n").map((l) => stripAnsiEscapes(l));
|
|
1271
|
+
rows.push(...lines.slice(0, 3).map((l) => dim(clipVisible(l, width - 1))));
|
|
1272
|
+
if (lines.length > 3) rows.push(dim(`${GUTTER}… ${lines.length - 3} more line(s)`));
|
|
1273
|
+
}
|
|
1274
|
+
if (!rows.length) return [];
|
|
1275
|
+
return ["", ...(rows.length > 6 ? [...rows.slice(0, 5), dim(`${GUTTER}… ${rows.length - 5} more line(s) waiting`)] : rows)];
|
|
1276
|
+
}
|
|
1243
1277
|
function flushPendingEcho() {
|
|
1244
1278
|
if (pendingEcho === null) return;
|
|
1245
1279
|
const text = pendingEcho;
|
|
@@ -2211,18 +2245,17 @@ rl.on("line", (l) => {
|
|
|
2211
2245
|
turnTyping.reset();
|
|
2212
2246
|
// GH #506: with a running job, the text goes to the agent's NEXT step (appended after the
|
|
2213
2247
|
// current step's result — cache-safe). Not read by the end of the turn = the next question.
|
|
2248
|
+
// GH #514: like chat — no notices. Pinned, it waits as a ">> " row above the input box until the agent
|
|
2249
|
+
// reads it; with no frozen rows (piped, a tiny window) it is written into the history at once.
|
|
2214
2250
|
if (queued && currentJobId && !cancelRequested && sendNote(currentJobId, queued)) {
|
|
2215
|
-
|
|
2216
|
-
// Pinned: the input row says it (a line written mid-turn would break the zone, #321).
|
|
2251
|
+
waitingNotes.push({ text: queued, shown: !barPinned() });
|
|
2217
2252
|
if (barPinned()) paintBar();
|
|
2218
|
-
else process.stdout.write(
|
|
2253
|
+
else process.stdout.write("\n" + pastQuestion(queued) + "\n");
|
|
2219
2254
|
return;
|
|
2220
2255
|
}
|
|
2221
2256
|
if (queued) {
|
|
2222
2257
|
if (turnQueue.push(queued)) {
|
|
2223
|
-
// No frozen row to carry the count (piped, or a window too short to pin one): say it here.
|
|
2224
2258
|
if (barPinned()) paintBar();
|
|
2225
|
-
else process.stdout.write(dim(`\n (queued — ${turnQueue.size} waiting; runs when this turn finishes)\n`));
|
|
2226
2259
|
} else {
|
|
2227
2260
|
process.stdout.write(dim(`\n (${turnQueue.size} questions are already queued — wait for one to run)\n`));
|
|
2228
2261
|
}
|
|
@@ -3091,7 +3124,8 @@ const footerBuilt = () =>
|
|
|
3091
3124
|
// Task #14: the skipped-setup warning — persistent (not a timed notice), red, its own row.
|
|
3092
3125
|
// …then the fallback rows (#343), YELLOW: a different model is doing the work — a warning,
|
|
3093
3126
|
// where the red rows above mean something is not set up at all.
|
|
3094
|
-
|
|
3127
|
+
// …and (GH #513), yellow too: this window runs older code than the gu now on this computer.
|
|
3128
|
+
missing: [...missingNoticeRows().map((r) => red(r)), ...fallbackNoticeRows().map((r) => yellow(r)), ...versionNoticeRows(REPL_VERSION, diskVersion).map((r) => yellow(r))],
|
|
3095
3129
|
});
|
|
3096
3130
|
const footerRows = () => footerBuilt().rows;
|
|
3097
3131
|
// An ask()'s hint lines (#305), drawn in yellow under its input while it waits. Plain text.
|
|
@@ -3252,7 +3286,7 @@ function closeZonePanel() {
|
|
|
3252
3286
|
function frozenZone() {
|
|
3253
3287
|
const width = Math.max(20, process.stdout.columns || 80);
|
|
3254
3288
|
if (zonePanel) {
|
|
3255
|
-
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows];
|
|
3289
|
+
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows, ...waitingNoteRows()];
|
|
3256
3290
|
// At least four rows of conversation stay visible, as with a tall input (maxInputRows).
|
|
3257
3291
|
const room = Math.max(3, viewportRows() - status.length - 2 - 4);
|
|
3258
3292
|
let body = [];
|
|
@@ -3275,7 +3309,7 @@ function frozenZone() {
|
|
|
3275
3309
|
// statusShown is already false — the prompt simply refuses to render any.
|
|
3276
3310
|
// #307: a question held until its turn prints anything sits on top of the status block — where
|
|
3277
3311
|
// it will land once committed, so nothing moves when it does.
|
|
3278
|
-
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows];
|
|
3312
|
+
const status = footerActive ? [] : [...pendingEchoRows(), ...liveStatusRows, ...waitingNoteRows()];
|
|
3279
3313
|
// THE SEPARATOR CARRIES NOTHING (#318). What used to ride on it — jump-to-bottom, the update
|
|
3280
3314
|
// control, the gu token notice, the agents count — is on its own NOTICE ROW above it; the head
|
|
3281
3315
|
// is just the rule, with no blank to lift a control off the typed line.
|
|
@@ -9796,7 +9830,7 @@ async function chooseAgentModel() {
|
|
|
9796
9830
|
// THE CURRENT PROVIDER'S OWN ROWS, ON THIS LIST (#248). They were one step down, behind "other
|
|
9797
9831
|
// models, providers and API keys…" — which read like the "add a provider" row under it.
|
|
9798
9832
|
const source = am.agentListSource(settings);
|
|
9799
|
-
const
|
|
9833
|
+
const canUseKey = am.agentSourceCanUseKey(source);
|
|
9800
9834
|
for (;;) {
|
|
9801
9835
|
// The first row is the default and the way back to ONE model: the coding model talks too (GH #397).
|
|
9802
9836
|
const labels = [
|
|
@@ -9827,7 +9861,7 @@ async function chooseAgentModel() {
|
|
|
9827
9861
|
const pickOn = async ({ rep, own }) => own
|
|
9828
9862
|
? agentModelOnServer({ back: true, start: "models" })
|
|
9829
9863
|
: addServer({ role: "agent", dialect: rep.kind === "ollama" ? "ollama" : "openai", url: rep.url, back: true });
|
|
9830
|
-
const KEYS = curHost &&
|
|
9864
|
+
const KEYS = curHost && canUseKey ? labels.length : -1;
|
|
9831
9865
|
if (KEYS >= 0) labels.push(actionRow(`API keys for ${curHost} — switch, add or remove…`));
|
|
9832
9866
|
const ADD = labels.length;
|
|
9833
9867
|
labels.push(actionRow("add a provider — Claude API, OpenAI, Kimi, Ollama…"));
|
|
@@ -9968,12 +10002,13 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
|
|
|
9968
10002
|
// at all, so api.openai.com answered 401 however right the stored key was. Asked for the key
|
|
9969
10003
|
// bound to THIS provider row — the same one the API will send with each turn.
|
|
9970
10004
|
const needsKey = am.agentSourceNeedsKey(source);
|
|
10005
|
+
const canUseKey = am.agentSourceCanUseKey(source);
|
|
9971
10006
|
const listHost = url ? hostOf(url) : "";
|
|
9972
10007
|
let listKey = "";
|
|
9973
10008
|
let keyProblem = false;
|
|
9974
|
-
if (
|
|
10009
|
+
if (canUseKey) {
|
|
9975
10010
|
listKey = (await withPendingStatus(`reading the key for ${listHost}`, () => fetchCodingKey(String(source.row?.id ?? "")))).key;
|
|
9976
|
-
if (!listKey) {
|
|
10011
|
+
if (!listKey && needsKey) {
|
|
9977
10012
|
keyProblem = true;
|
|
9978
10013
|
failure = `no API key is stored for ${listHost}`;
|
|
9979
10014
|
}
|
|
@@ -9995,7 +10030,7 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
|
|
|
9995
10030
|
proxyFetch(url, { headers: am.agentListHeaders(listKey, url), signal: AbortSignal.timeout(10000) })
|
|
9996
10031
|
);
|
|
9997
10032
|
if (!r.ok) failure = `HTTP ${r.status}`;
|
|
9998
|
-
if (!r.ok &&
|
|
10033
|
+
if (!r.ok && canUseKey && (r.status === 401 || r.status === 403)) keyProblem = true;
|
|
9999
10034
|
else models = am.agentModelsFromBody(source.dialect, await r.json().catch(() => null));
|
|
10000
10035
|
// A 200 with nothing in it is not a working list. Saying "the box answered but listed no
|
|
10001
10036
|
// models" is a different diagnosis from "unreachable", and the user can act on it.
|
|
@@ -10038,7 +10073,7 @@ async function agentModelOnServer({ back = false, start = "menu" } = {}) {
|
|
|
10038
10073
|
let firstAction = "models";
|
|
10039
10074
|
if (start !== "models") {
|
|
10040
10075
|
console.log(dim(` Agent model — the one that TALKS: ${current || "unset"} on ${listHost}`));
|
|
10041
|
-
const menu = am.agentMenuOptions({ host: listHost, modelCount: models.length, needsKey });
|
|
10076
|
+
const menu = am.agentMenuOptions({ host: listHost, modelCount: models.length, needsKey: canUseKey });
|
|
10042
10077
|
const first = await pickFromList(menu.map((o) => o.label), 0, { back });
|
|
10043
10078
|
if (first === PICK_BACK) return BACK;
|
|
10044
10079
|
firstAction = first >= 0 ? menu[first].action : "cancel";
|
|
@@ -10990,17 +11025,19 @@ async function coderKeyState(override = "") {
|
|
|
10990
11025
|
? choices.find((c) => c.id === override)
|
|
10991
11026
|
: choices.find((c) => c.isDefault);
|
|
10992
11027
|
// Kind AND url: an Ollama coder at https://ollama.com needs a key; a local one does not.
|
|
10993
|
-
const { codingNeedsKey } = await import("./coding-key-prompt.mjs");
|
|
11028
|
+
const { codingNeedsKey, codingCanUseKey } = await import("./coding-key-prompt.mjs");
|
|
10994
11029
|
const needsKey = codingNeedsKey(active?.kind, active?.url);
|
|
11030
|
+
const canUseKey = codingCanUseKey(active?.kind, active?.url);
|
|
10995
11031
|
return {
|
|
10996
11032
|
needsKey,
|
|
11033
|
+
canUseKey,
|
|
10997
11034
|
model: p.codingKeyModel || active?.model || "the coding model",
|
|
10998
11035
|
missing: (codingKeyMissingKnown = needsKey && p.codingKeyMissing === true),
|
|
10999
11036
|
// ASKED FOR THIS BACKEND, not for the account (task #223 follow-up): with several
|
|
11000
11037
|
// providers the account default is a different credential from the one this coder gets,
|
|
11001
11038
|
// so the masked tail shown here named a key that would never be used.
|
|
11002
11039
|
stored:
|
|
11003
|
-
|
|
11040
|
+
canUseKey && p.codingKeyMissing !== true
|
|
11004
11041
|
? (await fetchCodingKey(typeof active?.backendId === "string" ? active.backendId : ""))
|
|
11005
11042
|
.key
|
|
11006
11043
|
: "",
|
|
@@ -11011,7 +11048,7 @@ async function coderKeyState(override = "") {
|
|
|
11011
11048
|
provider: typeof active?.label === "string" ? active.label : "",
|
|
11012
11049
|
};
|
|
11013
11050
|
} catch {
|
|
11014
|
-
return { needsKey: false, model: "", missing: false, stored: "", backendId: "", provider: "" };
|
|
11051
|
+
return { needsKey: false, canUseKey: false, model: "", missing: false, stored: "", backendId: "", provider: "" };
|
|
11015
11052
|
}
|
|
11016
11053
|
}
|
|
11017
11054
|
|
|
@@ -11198,7 +11235,7 @@ async function replaceCodingKey({ back = false } = {}) {
|
|
|
11198
11235
|
const ks = await withPendingStatus("checking the coding model", () =>
|
|
11199
11236
|
coderKeyState(sessionCodingModel)
|
|
11200
11237
|
);
|
|
11201
|
-
if (!ks.
|
|
11238
|
+
if (!ks.canUseKey) {
|
|
11202
11239
|
console.log(
|
|
11203
11240
|
"\n" + GUTTER + dim(`${ks.model || "This coding model"} needs no API key — nothing to set.\n`)
|
|
11204
11241
|
);
|
|
@@ -11624,11 +11661,7 @@ const turnRowNotice = (width) =>
|
|
|
11624
11661
|
? cancelRequested
|
|
11625
11662
|
? visibleLen(SUPPORT_AFTER_STOP_NOTICE) + 12 <= width ? SUPPORT_AFTER_STOP_NOTICE : SUPPORT_AFTER_STOP_SHORT
|
|
11626
11663
|
: visibleLen(SUPPORT_AFTER_TURN_NOTICE) + 12 <= width ? SUPPORT_AFTER_TURN_NOTICE : SUPPORT_AFTER_TURN_SHORT
|
|
11627
|
-
:
|
|
11628
|
-
? typingNotice(width)
|
|
11629
|
-
: notesSent
|
|
11630
|
-
? sentNotice(notesSent, width)
|
|
11631
|
-
: queuedNotice(turnQueue.size, width);
|
|
11664
|
+
: "";
|
|
11632
11665
|
// Is the turn we are following one this terminal STARTED, or another terminal's that we merely
|
|
11633
11666
|
// attached to (task #211)? `attached` is local to runAgentTurn, and onInterrupt — which lives in
|
|
11634
11667
|
// main() — had no way to ask. So Ctrl+C while watching somebody else's agent took the "cancel my
|
|
@@ -11636,7 +11669,9 @@ const turnRowNotice = (width) =>
|
|
|
11636
11669
|
// non-destructive way back to your own prompt, which is the bug this flag exists to fix.
|
|
11637
11670
|
let followingAttached = false;
|
|
11638
11671
|
let followAborted = false;
|
|
11639
|
-
|
|
11672
|
+
// GH #506/#514: what was typed during this turn — waiting for the agent, and what it has read.
|
|
11673
|
+
let waitingNotes = []; // {text, shown} — shown: already in the history (unpinned)
|
|
11674
|
+
let readNotes = []; // texts the agent read, kept with this turn's question
|
|
11640
11675
|
let currentJobId = null; // the running turn's jobId — so Ctrl+C can cancel it server-side
|
|
11641
11676
|
let cancelRequested = false; // a cancel POST has been sent for the current turn
|
|
11642
11677
|
// Interactive command-approval gate: while the agent is paused on a risky command, the
|
|
@@ -11683,14 +11718,16 @@ function drawApprovalOptions(redraw) {
|
|
|
11683
11718
|
// Both rows are a handful of columns wide, so they survive any resize on ONE physical row
|
|
11684
11719
|
// each and the \x1b[2A count stays exact — which is why a resize can simply redraw here.
|
|
11685
11720
|
const yes = approvalSel === 0 ? accent("▸ Yes") : dim(" Yes");
|
|
11721
|
+
const always = approvalSel === 1 ? accent("▸ " + PROJECT_CHOICE) : dim(" " + PROJECT_CHOICE);
|
|
11686
11722
|
const tail = approvalDeadline ? " (auto-No in " + countdownLabel(approvalDeadline - Date.now()) + ")" : "";
|
|
11687
|
-
const no = approvalSel ===
|
|
11723
|
+
const no = approvalSel === 2 ? accent("▸ No" + tail) : dim(" No" + tail);
|
|
11724
|
+
const alwaysRow = clipVisible(GUTTER + always, Math.max(20, process.stdout.columns || 80) - 1);
|
|
11688
11725
|
const noRow = clipVisible(GUTTER + no, Math.max(20, process.stdout.columns || 80) - 1);
|
|
11689
11726
|
if (!redraw && barPinned() && !scrolledBack()) {
|
|
11690
11727
|
const content = displayRows(transcript.lines(), Math.max(20, process.stdout.columns || 80) - 1).length;
|
|
11691
11728
|
approvalOpenedOver = { content, pad: currentPad(content), height: viewportHeight() };
|
|
11692
11729
|
}
|
|
11693
|
-
regionUi((redraw ? "\x1b[
|
|
11730
|
+
regionUi((redraw ? "\x1b[3A" : "") + "\x1b[K" + GUTTER + yes + "\n\x1b[K" + alwaysRow + "\n\x1b[K" + noRow + "\n");
|
|
11694
11731
|
}
|
|
11695
11732
|
/** #204: the command block of the open Yes/No prompt — Ctrl+O toggles it (a click does too). */
|
|
11696
11733
|
let approvalCommandBlock = null;
|
|
@@ -11712,7 +11749,7 @@ function printApprovalCommand(shown, { toggle = true } = {}) {
|
|
|
11712
11749
|
if (thoughtBlocks.length > 200) thoughtBlocks = thoughtBlocks.slice(-200);
|
|
11713
11750
|
return block;
|
|
11714
11751
|
}
|
|
11715
|
-
function finishApproval(allow, timedOut = false) {
|
|
11752
|
+
function finishApproval(allow, timedOut = false, forProject = false) {
|
|
11716
11753
|
if (!approvalActive) return;
|
|
11717
11754
|
approvalActive = false;
|
|
11718
11755
|
approvalCommandBlock = null;
|
|
@@ -11724,21 +11761,21 @@ function finishApproval(allow, timedOut = false) {
|
|
|
11724
11761
|
const over = approvalOpenedOver;
|
|
11725
11762
|
approvalOpenedOver = null;
|
|
11726
11763
|
if (over && barPinned() && !scrolledBack() && over.height === viewportHeight()) {
|
|
11727
|
-
setPad(blockClosedPad({ contentRows: over.content, pad: over.pad, height: over.height, blockRows:
|
|
11764
|
+
setPad(blockClosedPad({ contentRows: over.content, pad: over.pad, height: over.height, blockRows: 3 }), over.content);
|
|
11728
11765
|
}
|
|
11729
|
-
// Settle the picker: overwrite the
|
|
11730
|
-
process.stdout.write("\x1b[
|
|
11766
|
+
// Settle the picker: overwrite the three option lines with a single result line.
|
|
11767
|
+
process.stdout.write("\x1b[3A\x1b[J" + GUTTER + (allow ? accent("▸ Yes — running it") : red(timedOut ? "▸ No — no answer in time, skipped" : "▸ No — skipped")) + "\n");
|
|
11731
11768
|
const r = approvalResolve;
|
|
11732
11769
|
approvalResolve = null;
|
|
11733
|
-
if (r) r(!!allow);
|
|
11770
|
+
if (r) r(allow && forProject ? "project" : !!allow);
|
|
11734
11771
|
}
|
|
11735
11772
|
function onApprovalKey(key) {
|
|
11736
11773
|
if (!key) return;
|
|
11737
11774
|
if (key.name === "up" || key.name === "down") {
|
|
11738
|
-
approvalSel = key.name === "up" ?
|
|
11775
|
+
approvalSel = Math.min(2, Math.max(0, approvalSel + (key.name === "up" ? -1 : 1))); // Yes · this project · No
|
|
11739
11776
|
drawApprovalOptions(true);
|
|
11740
11777
|
} else if (key.name === "return" || key.name === "enter") {
|
|
11741
|
-
finishApproval(approvalSel ===
|
|
11778
|
+
finishApproval(approvalSel !== 2, false, approvalSel === 1);
|
|
11742
11779
|
} else if (key.ctrl && key.name === "o" && approvalCommandBlock && thoughtBlocks.includes(approvalCommandBlock)) {
|
|
11743
11780
|
toggleThoughtBlock(approvalCommandBlock); // #204: expand/collapse the long command
|
|
11744
11781
|
}
|
|
@@ -11914,36 +11951,37 @@ async function approvalPrompt(command) {
|
|
|
11914
11951
|
printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped (#204)
|
|
11915
11952
|
process.stdout.write(indentBlock(why, { indent: GUTTER, paint: dim }) + "\n");
|
|
11916
11953
|
const idx = await pickFromList(
|
|
11917
|
-
["Yes", "Yes for all later ones (turns accept edits on)", "No"],
|
|
11954
|
+
["Yes", "Yes for all later ones (turns accept edits on)", PROJECT_CHOICE, "No"],
|
|
11918
11955
|
0,
|
|
11919
|
-
{ timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex:
|
|
11956
|
+
{ timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 3 }
|
|
11920
11957
|
);
|
|
11921
11958
|
if (idx === 1 && editMode === "manual") {
|
|
11922
11959
|
switchEditMode();
|
|
11923
11960
|
process.stdout.write(dim(" (won't ask for later commands — shift+tab to go back to manual)\n"));
|
|
11924
11961
|
}
|
|
11925
|
-
|
|
11962
|
+
if (idx === 2) rememberProject();
|
|
11963
|
+
return { allow: idx >= 0 && idx <= 2, dontAsk: false };
|
|
11926
11964
|
}
|
|
11927
|
-
// GH #
|
|
11928
|
-
|
|
11929
|
-
|
|
11930
|
-
|
|
11931
|
-
printApprovalCommand(shown, { toggle: false }); // a list picker follows — shown whole, wrapped
|
|
11965
|
+
// GH #515 — `source <file>`: a yes can be remembered for that file while it stays unchanged.
|
|
11966
|
+
const sourced = process.stdin.isTTY ? sourcedFileOf(why) : "";
|
|
11967
|
+
if (sourced) {
|
|
11968
|
+
printApprovalCommand(shown, { toggle: false });
|
|
11932
11969
|
process.stdout.write(indentBlock(why, { indent: GUTTER, paint: dim }) + "\n");
|
|
11933
11970
|
const idx = await pickFromList(
|
|
11934
|
-
["Yes", "Yes,
|
|
11971
|
+
["Yes", "Yes, don't ask again for this file", PROJECT_CHOICE, "No"],
|
|
11935
11972
|
0,
|
|
11936
|
-
{ timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex:
|
|
11973
|
+
{ timeoutMs: COMMAND_APPROVAL_MS, timeoutIndex: 3 }
|
|
11937
11974
|
);
|
|
11975
|
+
if (idx === 2) rememberProject();
|
|
11938
11976
|
if (idx === 1) {
|
|
11939
11977
|
try {
|
|
11940
|
-
|
|
11941
|
-
process.stdout.write(dim(" (won't ask about
|
|
11978
|
+
commandAllowSource(resolve(process.cwd()), sourced);
|
|
11979
|
+
process.stdout.write(dim(" (won't ask about this file again unless it changes — /command forget undoes it)\n"));
|
|
11942
11980
|
} catch (e) {
|
|
11943
11981
|
process.stdout.write(yellow(` could not save that (${e?.message || e}) — allowed this once\n`));
|
|
11944
11982
|
}
|
|
11945
11983
|
}
|
|
11946
|
-
return { allow: idx
|
|
11984
|
+
return { allow: idx >= 0 && idx <= 2, dontAsk: false };
|
|
11947
11985
|
}
|
|
11948
11986
|
const allow = await new Promise((resolve) => {
|
|
11949
11987
|
if (!process.stdin.isTTY) {
|
|
@@ -11970,7 +12008,22 @@ async function approvalPrompt(command) {
|
|
|
11970
12008
|
orig(v);
|
|
11971
12009
|
};
|
|
11972
12010
|
});
|
|
11973
|
-
|
|
12011
|
+
if (allow === "project") rememberProject();
|
|
12012
|
+
return { allow: Boolean(allow), dontAsk: false };
|
|
12013
|
+
}
|
|
12014
|
+
/** GH #515: no more command questions in this project — and say exactly what that covers. */
|
|
12015
|
+
function rememberProject() {
|
|
12016
|
+
try {
|
|
12017
|
+
commandAllowProject(resolve(process.cwd()));
|
|
12018
|
+
// They asked not to be asked: the manual-edits switch (which confirms every command) goes back on.
|
|
12019
|
+
if (editMode === "manual") switchEditMode();
|
|
12020
|
+
process.stdout.write(
|
|
12021
|
+
GUTTER + dim("No more command questions here — sudo and outside deletes included.") + "\n" +
|
|
12022
|
+
GUTTER + dim("/command forget undoes it.") + "\n"
|
|
12023
|
+
);
|
|
12024
|
+
} catch (e) {
|
|
12025
|
+
process.stdout.write(yellow(` could not save that (${e?.message || e}) — allowed this once\n`));
|
|
12026
|
+
}
|
|
11974
12027
|
}
|
|
11975
12028
|
// Generic arrow-key list picker (↑/↓ + Enter) — used by /server so you navigate instead
|
|
11976
12029
|
// of typing a number. Same mechanism as the Yes/No approval picker above, generalized to
|
|
@@ -13836,6 +13889,22 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
|
|
|
13836
13889
|
// Task #343: another model took over. Swallowed from the action list — it goes on the
|
|
13837
13890
|
// BAR, now, in yellow — and the turn leaves one line about it once it has ended (see the
|
|
13838
13891
|
// caller), so a fallback that lasted a single step can still be found afterwards.
|
|
13892
|
+
// GH #514: the agent just read what was typed — it becomes part of the history HERE, between its steps.
|
|
13893
|
+
if (line.startsWith(USERNOTE_PREFIX)) {
|
|
13894
|
+
const taken = waitingNotes.splice(0, parseUserNote(line));
|
|
13895
|
+
if (taken.length) {
|
|
13896
|
+
readNotes.push(...taken.map((n) => n.text));
|
|
13897
|
+
const unseen = taken.filter((n) => !n.shown);
|
|
13898
|
+
if (unseen.length) {
|
|
13899
|
+
releaseHeldThought();
|
|
13900
|
+
onContent();
|
|
13901
|
+
process.stdout.write((lastWasBlank ? "" : "\n") + unseen.map((n) => pastQuestion(n.text)).join("\n") + "\n");
|
|
13902
|
+
lastWasBlank = true;
|
|
13903
|
+
}
|
|
13904
|
+
}
|
|
13905
|
+
lastContentAt = Date.now();
|
|
13906
|
+
continue;
|
|
13907
|
+
}
|
|
13839
13908
|
if (line.startsWith(MODELFALLBACK_PREFIX)) {
|
|
13840
13909
|
const fb = parseModelFallback(line);
|
|
13841
13910
|
if (fb) {
|
|
@@ -14486,7 +14555,7 @@ async function runAgentTurn(history, { attachJobId = "", ownJob = false } = {})
|
|
|
14486
14555
|
}
|
|
14487
14556
|
}
|
|
14488
14557
|
currentJobId = null;
|
|
14489
|
-
|
|
14558
|
+
waitingNotes = [];
|
|
14490
14559
|
// Drop anything typed (but not submitted) during the turn — echo was muted, so it's
|
|
14491
14560
|
// invisible; without this it would surface on the next prompt.
|
|
14492
14561
|
rl.line = "";
|
|
@@ -15819,12 +15888,14 @@ async function main() {
|
|
|
15819
15888
|
}
|
|
15820
15889
|
if (line === "/command forget" || line === "/command status") {
|
|
15821
15890
|
const here = resolve(process.cwd());
|
|
15822
|
-
if (line === "/command forget")
|
|
15891
|
+
if (line === "/command forget") commandForget(here);
|
|
15823
15892
|
console.log("\n" + GUTTER + (line === "/command forget"
|
|
15824
|
-
? accent("✓ gu asks again before
|
|
15825
|
-
: (
|
|
15826
|
-
? accent("
|
|
15827
|
-
:
|
|
15893
|
+
? accent("✓ gu asks again before risky commands in this folder.")
|
|
15894
|
+
: commandProjectAllowed(here)
|
|
15895
|
+
? accent("gu never asks before a command in this project.") + dim(" (/command forget undoes it)")
|
|
15896
|
+
: commandAllowedIn(here)
|
|
15897
|
+
? accent("Destructive commands run without asking in this folder.") + dim(" (/command forget undoes it)")
|
|
15898
|
+
: dim("gu asks before risky commands in this folder.")) + "\n");
|
|
15828
15899
|
paintBar();
|
|
15829
15900
|
continue;
|
|
15830
15901
|
}
|
|
@@ -16228,6 +16299,7 @@ async function main() {
|
|
|
16228
16299
|
// another model's price on it.
|
|
16229
16300
|
const turnCoder = { url: activeCodingUrl(), model: activeCodingModelId() };
|
|
16230
16301
|
turnFallback = null; // #343: nothing has fallen back in THIS turn yet
|
|
16302
|
+
readNotes = []; // #514
|
|
16231
16303
|
if (reattach) console.log(GUTTER + dim("following the turn that was running when the connection went…\n"));
|
|
16232
16304
|
const turn = await runAgentTurn(history, reattach ? { attachJobId: reattach.jobId, ownJob: true } : {});
|
|
16233
16305
|
// NOT SENT (licence block, or the token prompt declined): runAgentTurn already said so.
|
|
@@ -16286,6 +16358,9 @@ async function main() {
|
|
|
16286
16358
|
if (fellBack) printFallbackLine(fellBack);
|
|
16287
16359
|
} else if (answer) {
|
|
16288
16360
|
noteTaskSuccess();
|
|
16361
|
+
// GH #514: the next turns know what was added while this one ran.
|
|
16362
|
+
const asked = history[history.length - 1];
|
|
16363
|
+
if (readNotes.length && asked?.role === "user") asked.content = questionWithNotes(asked.content, readNotes);
|
|
16289
16364
|
history.push({ role: "assistant", content: answer });
|
|
16290
16365
|
// Persist after every successful turn (not just on clean exit) — an ungraceful
|
|
16291
16366
|
// termination (killed terminal, force-quit) would otherwise lose the whole
|
package/model-setup-ui.mjs
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
*
|
|
19
19
|
* PURE. Everything here is strings in, strings out, so the whole table is a test.
|
|
20
20
|
*/
|
|
21
|
-
import { hostLocality } from "./coding-provider-setup.mjs";
|
|
21
|
+
import { hostLocality, isKeylessHost } from "./coding-provider-setup.mjs";
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* What an Esc-aware prompt resolves to when Esc is pressed. A string no one can type (it starts
|
|
@@ -67,7 +67,7 @@ export function createHinter() {
|
|
|
67
67
|
*/
|
|
68
68
|
export function shouldAskKey({ typed, host }) {
|
|
69
69
|
if (!String(typed ?? "").trim()) return false;
|
|
70
|
-
return hostLocality(host) === "public";
|
|
70
|
+
return hostLocality(host) === "public" && !isKeylessHost(host);
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
/** The server refused to list its models without credentials. */
|
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.928",
|
|
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",
|
package/turn-notes.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// NOTES FOR THE RUNNING TURN (GH #506).
|
|
1
|
+
// NOTES FOR THE RUNNING TURN (GH #506, shown like chat messages since #514).
|
|
2
2
|
//
|
|
3
3
|
// Enter during a turn used to QUEUE the question for after the turn (#429). Now it is written to
|
|
4
4
|
// ~/.gonext/turn-notes/<jobId>.jsonl, and the agent (gu_turn_notes.py) adds it after its current
|
|
@@ -67,11 +67,23 @@ export function sweepOldNotes(home, now = Date.now()) {
|
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
|
|
70
|
-
/**
|
|
71
|
-
|
|
70
|
+
/**
|
|
71
|
+
* IT LOOKS LIKE CHATTING (GH #514) — no notices. On Enter the message waits as a ">> …" row above the input
|
|
72
|
+
* box; when the agent reads it, it reports `__USERNOTE__::<count>` as a step, and gu moves that many rows into
|
|
73
|
+
* the history at that very point, drawn like any question.
|
|
74
|
+
*/
|
|
75
|
+
export const USERNOTE_PREFIX = "__USERNOTE__::";
|
|
72
76
|
|
|
73
|
-
/**
|
|
74
|
-
export function
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
+
/** → how many notes the agent just read; 0 when the line is not that report. */
|
|
78
|
+
export function parseUserNote(line) {
|
|
79
|
+
const s = String(line ?? "").trim();
|
|
80
|
+
if (!s.startsWith(USERNOTE_PREFIX)) return 0;
|
|
81
|
+
const n = Number(s.slice(USERNOTE_PREFIX.length));
|
|
82
|
+
return Number.isInteger(n) && n > 0 ? n : 0;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** The turn's question as the next turns see it: what was added while it ran belongs to it. */
|
|
86
|
+
export function questionWithNotes(question, notes) {
|
|
87
|
+
const added = (notes ?? []).map((t) => String(t).trim()).filter(Boolean);
|
|
88
|
+
return added.length ? `${question}\n\n[Added by the user while you were working]\n${added.join("\n\n")}` : question;
|
|
77
89
|
}
|
package/turn-queue.mjs
CHANGED
|
@@ -6,12 +6,6 @@
|
|
|
6
6
|
|
|
7
7
|
export const MAX_QUEUED_QUESTIONS = 20;
|
|
8
8
|
|
|
9
|
-
/** What the input row says while the user is typing during a turn. */
|
|
10
|
-
// GH #506: Enter now hands the text to the RUNNING turn (turn-notes.mjs); the queue below keeps what
|
|
11
|
-
// the agent did not read before the turn ended.
|
|
12
|
-
export const TYPING_NOTICE = "(turn running — Enter sends it to the agent's next step) ";
|
|
13
|
-
export const TYPING_SHORT = "(Enter sends it) ";
|
|
14
|
-
|
|
15
9
|
export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
16
10
|
const items = [];
|
|
17
11
|
return {
|
|
@@ -29,6 +23,10 @@ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
|
29
23
|
items.unshift(...take);
|
|
30
24
|
return take.length;
|
|
31
25
|
},
|
|
26
|
+
/** The waiting items, oldest first (GH #514: shown above the input box). */
|
|
27
|
+
list() {
|
|
28
|
+
return [...items];
|
|
29
|
+
},
|
|
32
30
|
shift() {
|
|
33
31
|
return items.length ? items.shift() : null;
|
|
34
32
|
},
|
|
@@ -44,20 +42,6 @@ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
|
|
|
44
42
|
};
|
|
45
43
|
}
|
|
46
44
|
|
|
47
|
-
const fits = (s, width) => s.length + 12 <= width;
|
|
48
|
-
|
|
49
|
-
/** The input-row label while questions wait and nothing is being typed; "" when the queue is empty. */
|
|
50
|
-
export function queuedNotice(n, width = 80) {
|
|
51
|
-
if (!n) return "";
|
|
52
|
-
const long = `(${n} queued — runs after this turn; Ctrl-C drops them) `;
|
|
53
|
-
return fits(long, width) ? long : `(${n} queued) `;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** The typing label that fits the row. */
|
|
57
|
-
export function typingNotice(width = 80) {
|
|
58
|
-
return fits(TYPING_NOTICE, width) ? TYPING_NOTICE : TYPING_SHORT;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
45
|
/** One line for the transcript when queued questions are thrown away. */
|
|
62
46
|
export function droppedNote(n) {
|
|
63
47
|
return `(${n} queued question${n === 1 ? "" : "s"} not run — the turn did not finish; type ${n === 1 ? "it" : "them"} again)`;
|