@tiens.nguyen/gu-cli 1.0.907 → 1.0.908

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.
@@ -3239,6 +3239,53 @@ def _output_limit_from_error(text) -> int:
3239
3239
  return 0
3240
3240
 
3241
3241
 
3242
+ _DEEPSEEK_V4_RE = re.compile(r"deepseek[-_.]?v4", re.I)
3243
+ # Hosts known to take DeepSeek's own `thinking` request field (GH #430). Another host serving the
3244
+ # same model (OpenRouter, Together, vLLM…) spells the switch differently or not at all, so it
3245
+ # keeps today's request unchanged unless GONEXT_DEEPSEEK_THINKING=off forces the field.
3246
+ _DEEPSEEK_THINKING_HOSTS = frozenset({"api.deepseek.com", "token-plan.maas.qwencloudapi.com"})
3247
+
3248
+
3249
+ def _deepseek_thinking_kwargs(model_id, base_url="", env=None) -> dict:
3250
+ """Request fields that turn DeepSeek V4's thinking OFF in the coding loop (GH #430), or {}.
3251
+
3252
+ Thinking is on by default for DeepSeek V4. gu's loop is TEXT tool calls (<code> blocks, no
3253
+ `tools` field); with thinking on, the model drifts into its NATIVE tool format (DSML markup),
3254
+ restates the task every step and sometimes ends with no answer.
3255
+
3256
+ GONEXT_DEEPSEEK_THINKING: unset → only on a host in _DEEPSEEK_THINKING_HOSTS; "off" → any
3257
+ host; "on" → never (provider default). Every other model gets {}. A host that rejects the
3258
+ field has it dropped once and remembered (_repair_request / _apply_request_shape)."""
3259
+ env = os.environ if env is None else env
3260
+ if not _DEEPSEEK_V4_RE.search(str(model_id or "")):
3261
+ return {}
3262
+ mode = str(env.get("GONEXT_DEEPSEEK_THINKING", "")).strip().lower()
3263
+ if mode in ("on", "1", "true", "yes"):
3264
+ return {}
3265
+ if mode not in ("off", "0", "false", "no"):
3266
+ from urllib.parse import urlparse
3267
+ host = (urlparse(str(base_url or "")).hostname or "").lower().rstrip(".")
3268
+ if host not in _DEEPSEEK_THINKING_HOSTS:
3269
+ return {}
3270
+ return {"extra_body": {"thinking": {"type": "disabled"}}}
3271
+
3272
+
3273
+ def _coding_extra_kwargs(ollama_tweaks: bool, base_url, model_id, env=None):
3274
+ """Extra request fields for the coding model → (kwargs, log line or ""). Pure, so the whole
3275
+ provider matrix is testable (tests/test_coding_extra_kwargs_430.py): ONLY an Ollama server
3276
+ and DeepSeek V4 on an allowed host get anything; every other provider gets {}."""
3277
+ if ollama_tweaks:
3278
+ return ({"reasoning_effort": "none"},
3279
+ "coding server is Ollama → reasoning_effort='none' (disable thinking) + streaming")
3280
+ if _is_anthropic_url(base_url):
3281
+ return {}, ""
3282
+ ds = _deepseek_thinking_kwargs(model_id, base_url, env)
3283
+ if ds:
3284
+ return ds, ("coding model is DeepSeek V4 → thinking off for the tool loop (GH #430; "
3285
+ "GONEXT_DEEPSEEK_THINKING=on to keep it)")
3286
+ return {}, ""
3287
+
3288
+
3242
3289
  def _repair_request(kwargs: dict, err):
3243
3290
  """One fix for a 400 that rejected the request SHAPE. Pure.
3244
3291
 
@@ -3272,7 +3319,16 @@ def _repair_request(kwargs: dict, err):
3272
3319
  bad = [p for p in _unsupported_sampling_params(err) if p in kw]
3273
3320
  if bad:
3274
3321
  return _without_params(kw, bad), "drop:" + ",".join(bad)
3275
- # 4. any other optional field the provider says it does not know
3322
+ # 4. a host that does not know DeepSeek's `thinking` field (GH #430)
3323
+ eb = kw.get("extra_body")
3324
+ if isinstance(eb, dict) and "thinking" in eb and "thinking" in msg:
3325
+ eb = {k: v for k, v in eb.items() if k != "thinking"}
3326
+ if eb:
3327
+ kw["extra_body"] = eb
3328
+ else:
3329
+ kw.pop("extra_body")
3330
+ return kw, "drop:thinking"
3331
+ # 5. any other optional field the provider says it does not know
3276
3332
  if rejects:
3277
3333
  names = [n for n in re.findall(r"['\"`]([a-z_]+)['\"`]", msg)
3278
3334
  if n in _DROPPABLE_PARAMS and n in kw]
@@ -3359,7 +3415,15 @@ def _apply_request_shape(kwargs: dict, key: str, model: str) -> dict:
3359
3415
  if old in kw and new not in kw:
3360
3416
  kw[new] = kw.pop(old)
3361
3417
  for p in entry.get("drop") or []:
3362
- if p not in ("model", "messages", "stream"):
3418
+ if p == "thinking" and isinstance(kw.get("extra_body"), dict):
3419
+ # Lives INSIDE extra_body (GH #430): a top-level pop would miss it and every
3420
+ # request would pay the 400 again.
3421
+ eb = {k: v for k, v in kw["extra_body"].items() if k != "thinking"}
3422
+ if eb:
3423
+ kw["extra_body"] = eb
3424
+ else:
3425
+ kw.pop("extra_body")
3426
+ elif p not in ("model", "messages", "stream"):
3363
3427
  kw.pop(p, None)
3364
3428
  return _clamp_output_budget(kw, model, entry.get("max_out") or 0)
3365
3429
 
@@ -3409,6 +3473,9 @@ def _create_with_repair(client, **kwargs):
3409
3473
  elif action.startswith("clamp:"):
3410
3474
  _log(f"model {model!r} caps its output at {new_kw[action[6:]]} tokens; "
3411
3475
  "retrying with it (remembered)")
3476
+ elif action == "drop:thinking":
3477
+ _log(f"host rejects the thinking field for {model!r}; retrying without it "
3478
+ "(remembered, GH #430)")
3412
3479
  else:
3413
3480
  _log(f"model {model!r} rejects {', '.join(dropped)}; "
3414
3481
  "retrying at the model's own default")
@@ -4789,8 +4856,16 @@ def _fallback_recap(steps, last_text="") -> str:
4789
4856
  tried = []
4790
4857
  for st in (steps or [])[-8:]:
4791
4858
  did = str(st.get("did") or "").strip().replace(chr(10), " ")
4792
- m = re.search(r"([a-z_]+\([^\n]{0,70})", did)
4793
- label = (m.group(1) if m else did)[:70].strip()
4859
+ # A whole identifier only (GH #430): the old pattern matched the tail of "Image(" as
4860
+ # "mage(" and always picked the wrapper "print(" — useless labels like
4861
+ # "- mage(contentsOfFile: path)". Skip print/len/str wrappers, take the tool call.
4862
+ label = ""
4863
+ for m in re.finditer(r"(?<![\w.])([a-z_][a-z0-9_]*)\(", did):
4864
+ if m.group(1) not in ("print", "len", "str", "repr", "list", "dict", "int", "sorted"):
4865
+ label = did[m.start():m.start() + 70].strip()
4866
+ break
4867
+ if not label:
4868
+ label = did[:70].strip()
4794
4869
  if label:
4795
4870
  tried.append("- " + label)
4796
4871
  last = str(last_text or "").strip()
@@ -4804,6 +4879,15 @@ def _fallback_recap(steps, last_text="") -> str:
4804
4879
  return chr(10).join(out)
4805
4880
 
4806
4881
 
4882
+ def _answer_is_blank(answer) -> bool:
4883
+ """True when a final answer shows the user nothing: None, whitespace, or only tool-call
4884
+ markup that _strip_tool_tags removes (GH #430)."""
4885
+ try:
4886
+ return not _strip_tool_tags(_humanize_answer(answer).strip())
4887
+ except Exception: # noqa: BLE001
4888
+ return not str(answer or "").strip()
4889
+
4890
+
4807
4891
  def _humanize_answer(result) -> str:
4808
4892
  """Task #131: a final answer that is a dict/list (or a string that is just a JSON /
4809
4893
  Python-dict literal, as DeepSeek produces) is rendered as readable markdown instead of
@@ -13040,6 +13124,17 @@ def run_agent_chat(cfg):
13040
13124
  def _final_answer_gate(final_answer, memory, agent=None):
13041
13125
  """smolagents final_answer_check. True = accept; raising = reject with the message
13042
13126
  the model then sees. Only nudges when the answer hands the job back to the user."""
13127
+ # GH #430: an answer that is empty, or only tool-call markup the user never sees,
13128
+ # goes back to the model ONCE — it still has the whole turn in context, unlike any
13129
+ # repair after the run. Its own flag, so it never uses up the punt nudge below.
13130
+ if _answer_is_blank(final_answer) and not _completion_gate.get("blank_nudged"):
13131
+ _completion_gate["blank_nudged"] = True
13132
+ _log("final_answer was empty or only tool-call markup → asking for the answer (GH #430)")
13133
+ raise ValueError(
13134
+ "Your final_answer is EMPTY (or only tool-call markup, which the user never sees). "
13135
+ "Call final_answer again with the actual answer to the user's question, in plain "
13136
+ "words, based on what your steps found. If the work is unfinished, say what is "
13137
+ "done and what is left.")
13043
13138
  if _completion_gate["nudged"]:
13044
13139
  return True # already nudged once this turn — accept, never loop
13045
13140
  ans = str(final_answer if final_answer is not None else "")
@@ -14782,12 +14877,12 @@ def run_agent_chat(cfg):
14782
14877
  # honor reasoning_effort="none". Thinking burned ~430 of 487 output tokens in
14783
14878
  # the live test — minutes per step on a slow GPU — so disable it explicitly.
14784
14879
  # Sniffed per-server because MLX might reject the unknown param.
14785
- extra_model_kwargs = {}
14786
14880
  # `coding_backend` was resolved once, above, and `coding_flags` derives everything
14787
14881
  # from it — do NOT re-derive any of this from the kind or a URL sniff here.
14788
- if coding_flags["ollama_tweaks"]:
14789
- _log("coding server is Ollama → reasoning_effort='none' (disable thinking) + streaming")
14790
- extra_model_kwargs["reasoning_effort"] = "none"
14882
+ extra_model_kwargs, _extra_why = _coding_extra_kwargs(
14883
+ coding_flags["ollama_tweaks"], coding_base_url, coding_model_id)
14884
+ if _extra_why:
14885
+ _log(_extra_why)
14791
14886
  _stream_coder = coding_flags["stream"]
14792
14887
  _log(f"coding backend: {coding_backend} ({_backend_why}; "
14793
14888
  f"kind={coding_kind or 'auto'}, {_host_of(coding_base_url)}) "
@@ -17347,7 +17442,11 @@ def run_agent_chat(cfg):
17347
17442
  _emit({"type": "step", "text": _retr})
17348
17443
  _log(f"retrieval summary: {_c(_retr)}")
17349
17444
  _emit({"type": "step", "text": "Composing answer…"})
17350
- final_text = (_strip_tool_tags(_humanize_answer(result).strip())
17445
+ # GH #430: a blank final_answer was already sent back once by _final_answer_gate (the
17446
+ # model still had the turn in context then). No context-free summary call here — it
17447
+ # could claim work it never verified. What is left is the honest recap.
17448
+ final_text = _strip_tool_tags(_humanize_answer(result).strip())
17449
+ final_text = (final_text
17351
17450
  or _fallback_recap(_turn_steps, _last_obs.get("text"))
17352
17451
  or "[No result]")
17353
17452
  _log(f"done (deterministic, no summarizer call): {len(final_text)} chars")
package/gu-repl.mjs CHANGED
@@ -157,6 +157,7 @@ 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, queuedNotice, typingNotice, droppedNote } from "./turn-queue.mjs"; // GH #429: questions typed during a turn wait here
160
161
  import { globalPrefixOf } from "./install-path.mjs";
161
162
  import { indentBlock, commandBlockRows, wrapIndented } from "./terminal-layout.mjs"; // every line of an Allow-prompt detail indented (#189); wrapped + collapsible command (#204)
162
163
  import { firstGuOnPath, pathGuMismatch, guOnPathIsCurrent, updateAttemptRecord, repeatUpdateNotice } from "./update-verify.mjs";
@@ -2150,6 +2151,15 @@ const describeApiFailure = (err, what) => {
2150
2151
  return `${what}: ${err?.message ?? err}`;
2151
2152
  };
2152
2153
  const _lineQueue = [];
2154
+ // GH #429: lines submitted WHILE A TURN RUNS wait here (FIFO); the main loop runs them one by one
2155
+ // after the turn. Kept apart from _lineQueue, which every failed turn empties on purpose (#92).
2156
+ const turnQueue = createTurnQueue();
2157
+ /** A turn that did not finish throws its queued questions away — say how many, once. */
2158
+ function dropQueuedQuestions() {
2159
+ const n = turnQueue.clear();
2160
+ if (n > 0) console.log(GUTTER + dim(droppedNote(n)));
2161
+ return n;
2162
+ }
2153
2163
  // EVERY reader waiting for a submitted line, innermost LAST (task #182 follow-up).
2154
2164
  //
2155
2165
  // This was ONE slot, and a second reader silently overwrote the first. That is fine while every
@@ -2181,17 +2191,25 @@ rl.on("line", (l) => {
2181
2191
  rl.cursor = 0;
2182
2192
  return;
2183
2193
  }
2184
- // While a turn is running, IGNORE typed input entirely — no type-ahead, no queued
2185
- // next question. Only Ctrl+C (handled via SIGINT) does anything mid-turn. Clear the
2186
- // line buffer so nothing the user typed leaks into the next prompt.
2194
+ // While a turn is running, Enter QUEUES what was typed (GH #429; it used to be dropped, #92/#258).
2195
+ // The main loop runs the queue one question at a time after the turn. Ctrl+C aborts the turn
2196
+ // AND empties the queue. An empty Enter is ignored.
2187
2197
  if (following) {
2188
2198
  rl.line = "";
2189
2199
  rl.cursor = 0;
2190
- // No frozen row to carry the notice (piped, or a window too short to pin one): say it once
2191
- // here, on the Enter that would have sent it (#258).
2192
- if (typedDuringTurn && !barPinned()) {
2193
- process.stdout.write(dim(`\n ${TYPED_DURING_TURN_NOTICE.trim()}\n`));
2194
- }
2200
+ const queued = imageStore.expand(expandPasteTokens(stripAnsiEscapes(l))).trim();
2201
+ imageStore.clear();
2202
+ typedDuringTurn = false;
2203
+ turnTyping.reset();
2204
+ if (queued) {
2205
+ if (turnQueue.push(queued)) {
2206
+ // No frozen row to carry the count (piped, or a window too short to pin one): say it here.
2207
+ if (barPinned()) paintBar();
2208
+ else process.stdout.write(dim(`\n (queued — ${turnQueue.size} waiting; runs when this turn finishes)\n`));
2209
+ } else {
2210
+ process.stdout.write(dim(`\n (${turnQueue.size} questions are already queued — wait for one to run)\n`));
2211
+ }
2212
+ } else if (barPinned()) paintBar();
2195
2213
  return;
2196
2214
  }
2197
2215
  // Enter left the cursor on the row where the live slash-hint started — erase it so the
@@ -3274,8 +3292,8 @@ function frozenZone() {
3274
3292
  // sits in the scrolling output while the caret lives down here, so with the echo muted at
3275
3293
  // BOTH ends the terminal reacted to a keystroke in no visible way at all. One bullet per
3276
3294
  // character, so the row cannot carry the key and typing is still obviously working.
3277
- line: inputLineFor({ line: rl.line, visible: inputVisible, secret: secretInput }),
3278
- cursor: inputVisible ? rl.cursor ?? rl.line.length : 0,
3295
+ line: inputLineFor({ line: rl.line, visible: inputVisible || (following && typedDuringTurn), secret: secretInput }),
3296
+ cursor: inputVisible || (following && typedDuringTurn) ? rl.cursor ?? rl.line.length : 0,
3279
3297
  rule: (w) => dim("─".repeat(w)),
3280
3298
  maxRows: maxInputRows(),
3281
3299
  // The typed line is selectable too (task #177), and the highlight is applied HERE rather
@@ -4812,13 +4830,20 @@ if (process.stdin.isTTY) {
4812
4830
  // be sent — say so in the input row now, not after they have typed the whole thing (#258).
4813
4831
  // Not every printable key is typing: a mouse report or cursor reply whose ESC came alone
4814
4832
  // arrives as "[", "^[[", "[12;5R" (Windows, GH #382) — the detector sits those out.
4815
- if (turnTyping.feed(_ch, key) && !typedDuringTurn) {
4816
- typedDuringTurn = true;
4817
- if (barPinned()) paintBar();
4833
+ if (turnTyping.feed(_ch, key) && !typedDuringTurn) typedDuringTurn = true;
4834
+ // GH #429: once the user is really typing, the line is a DRAFT for the queue — kept and drawn
4835
+ // in the input row; Enter queues it. Before that (terminal replies, nav keys) it stays wiped.
4836
+ if (typedDuringTurn) {
4837
+ if (key && (key.name === "up" || key.name === "down")) {
4838
+ rl.line = turnDraft; // history recall is not typing — put the draft back
4839
+ rl.cursor = rl.line.length;
4840
+ } else turnDraft = rl.line;
4841
+ } else {
4842
+ rl.line = "";
4843
+ rl.cursor = 0;
4818
4844
  }
4819
- rl.line = "";
4820
- rl.cursor = 0;
4821
4845
  rl.historyIndex = -1;
4846
+ if (barPinned()) paintBar();
4822
4847
  return;
4823
4848
  }
4824
4849
  // AT THE PROMPT, Ctrl+T opens the newest printed thought block (task #148) — the no-mouse
@@ -11419,9 +11444,8 @@ let following = false;
11419
11444
  // typed while the previous one was still queued simply vanished. Now the input row says so the
11420
11445
  // moment a key lands, and keeps saying it until the turn ends. Nothing is queued or sent.
11421
11446
  let typedDuringTurn = false;
11447
+ let turnDraft = ""; // GH #429: what is being typed for the queue while a turn runs
11422
11448
  const turnTyping = createTurnTypingDetector(); // what counts as typing during a turn (GH #382)
11423
- const TYPED_DURING_TURN_NOTICE = "(a turn is running — typing is not sent; type it again when it finishes) ";
11424
- const TYPED_DURING_TURN_SHORT = "(turn running — not sent) ";
11425
11449
  // "? support" clicked during a turn (GH #382): it opens when the turn ends; Ctrl-C ends it now.
11426
11450
  let supportAfterTurn = false;
11427
11451
  const SUPPORT_AFTER_TURN_NOTICE = "(support opens when this turn ends — Ctrl-C stops the turn now) ";
@@ -11429,9 +11453,6 @@ const SUPPORT_AFTER_TURN_SHORT = "(support after this turn — Ctrl-C) ";
11429
11453
  // After the first Ctrl-C the turn is stopping; a worker that never answers needs a second one.
11430
11454
  const SUPPORT_AFTER_STOP_NOTICE = "(support opens when this turn ends — Ctrl-C again to stop waiting) ";
11431
11455
  const SUPPORT_AFTER_STOP_SHORT = "(support after this turn — Ctrl-C again) ";
11432
- /** The notice that fits: the input row must never wrap because of its label (#109/#132). */
11433
- const typedNotice = (width) =>
11434
- visibleLen(TYPED_DURING_TURN_NOTICE) + 12 <= width ? TYPED_DURING_TURN_NOTICE : TYPED_DURING_TURN_SHORT;
11435
11456
  /** What the input row says during a turn instead of ">>", or "" — queued support comes first. */
11436
11457
  const turnRowNotice = (width) =>
11437
11458
  !following
@@ -11440,7 +11461,7 @@ const turnRowNotice = (width) =>
11440
11461
  ? cancelRequested
11441
11462
  ? visibleLen(SUPPORT_AFTER_STOP_NOTICE) + 12 <= width ? SUPPORT_AFTER_STOP_NOTICE : SUPPORT_AFTER_STOP_SHORT
11442
11463
  : visibleLen(SUPPORT_AFTER_TURN_NOTICE) + 12 <= width ? SUPPORT_AFTER_TURN_NOTICE : SUPPORT_AFTER_TURN_SHORT
11443
- : typedDuringTurn ? typedNotice(width) : "";
11464
+ : typedDuringTurn ? typingNotice(width) : queuedNotice(turnQueue.size, width);
11444
11465
  // Is the turn we are following one this terminal STARTED, or another terminal's that we merely
11445
11466
  // attached to (task #211)? `attached` is local to runAgentTurn, and onInterrupt — which lives in
11446
11467
  // main() — had no way to ask. So Ctrl+C while watching somebody else's agent took the "cancel my
@@ -15265,6 +15286,7 @@ async function main() {
15265
15286
  // not just detach. The worker sees the "cancelled" status and kills the Python
15266
15287
  // agent; the poll loop then returns cleanly with the "(cancelled)" note.
15267
15288
  cancelRequested = true;
15289
+ dropQueuedQuestions(); // GH #429: stopping the turn also drops what waits behind it
15268
15290
  if (supportAfterTurn && barPinned()) paintBar(); // its row now says "Ctrl-C again" (GH #382)
15269
15291
  const jobId = currentJobId;
15270
15292
  // #307: while the question is still held (nothing printed yet), nothing goes to the
@@ -15281,6 +15303,7 @@ async function main() {
15281
15303
  // Second Ctrl+C (or no jobId yet): give up waiting locally. The worker keeps
15282
15304
  // trying to stop, but we stop following.
15283
15305
  followAborted = true;
15306
+ dropQueuedQuestions();
15284
15307
  if (pendingEcho === null) process.stdout.write("\n" + GUTTER + red("^C ")); // #307
15285
15308
  }
15286
15309
  } else {
@@ -15378,6 +15401,8 @@ async function main() {
15378
15401
  _lineQueue.unshift("/support");
15379
15402
  }
15380
15403
  mainPromptWaiting = true; // a finished background shell may start a recap turn now (#362)
15404
+ // GH #429: the next question typed during the turn that just ended runs now, in order.
15405
+ if (turnQueue.size > 0 && _lineQueue.length === 0) _lineQueue.push(turnQueue.shift());
15381
15406
  for (;;) {
15382
15407
  lineRaw = await nextLine();
15383
15408
  const echoed = enterEchoed;
@@ -16011,6 +16036,7 @@ async function main() {
16011
16036
  // is kept out of it. Its status says it was not done, and still stands.
16012
16037
  await markInterrupted(cwd, history, taskLine, "failed");
16013
16038
  if (_lineQueue.length > 0) _lineQueue.length = 0;
16039
+ dropQueuedQuestions();
16014
16040
  // …but REMEMBER it, so "continue" retries the real question once the cause is fixed
16015
16041
  // (typically /model to a working coder). Deliberately not the same thing as putting it
16016
16042
  // back in history: this is a one-shot resume, not a persisted turn.
@@ -16081,6 +16107,7 @@ async function main() {
16081
16107
  // that's typed AFTER the cancel note, so it arrives through the live waiter, not the
16082
16108
  // queue.
16083
16109
  if (_lineQueue.length > 0) _lineQueue.length = 0;
16110
+ dropQueuedQuestions();
16084
16111
  // Ctrl+C cancel already printed its own "(cancelled)" note in runAgentTurn — a
16085
16112
  // second "(no answer)" line here would be redundant/misleading.
16086
16113
  if (cancelled) {
@@ -16103,6 +16130,7 @@ async function main() {
16103
16130
  // Same reasoning as the no-answer branch (bug #92): don't let input buffered during a
16104
16131
  // turn that just threw auto-fire the next one.
16105
16132
  if (_lineQueue.length > 0) _lineQueue.length = 0;
16133
+ dropQueuedQuestions();
16106
16134
  await rememberUnfinishedTask(cwd, taskLine); // …and "continue" can retry it (task #150)
16107
16135
  // #302 part 3: the connection went, not the turn — keep its job so "continue" follows it.
16108
16136
  lostTurn = err?.lostJobId ? { jobId: err.lostJobId, taskLine } : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tiens.nguyen/gu-cli",
3
- "version": "1.0.907",
3
+ "version": "1.0.908",
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",
@@ -81,6 +81,7 @@
81
81
  "python-windows.mjs",
82
82
  "terminal-hover.mjs",
83
83
  "terminal-layout.mjs",
84
+ "turn-queue.mjs",
84
85
  "terminal-viewport.mjs",
85
86
  "terminal-copy.mjs",
86
87
  "version-check.mjs",
package/turn-queue.mjs ADDED
@@ -0,0 +1,55 @@
1
+ // QUEUE FOR QUESTIONS TYPED WHILE A TURN IS RUNNING (GH #429).
2
+ //
3
+ // Typing during a turn used to be dropped ("typing is not sent; type it again when it finishes").
4
+ // Now Enter queues the question (FIFO) and the main loop runs it when the current turn has ended.
5
+ // Pure and terminal-free so the order / limits / texts are unit-testable.
6
+
7
+ export const MAX_QUEUED_QUESTIONS = 20;
8
+
9
+ /** What the input row says while the user is typing during a turn. */
10
+ export const TYPING_NOTICE = "(turn running — Enter queues your question for when it finishes) ";
11
+ export const TYPING_SHORT = "(Enter queues it) ";
12
+
13
+ export function createTurnQueue({ max = MAX_QUEUED_QUESTIONS } = {}) {
14
+ const items = [];
15
+ return {
16
+ /** → true when queued, false when the queue is full. */
17
+ push(item) {
18
+ if (items.length >= max) return false;
19
+ items.push(item);
20
+ return true;
21
+ },
22
+ /** The oldest queued item, or null. */
23
+ shift() {
24
+ return items.length ? items.shift() : null;
25
+ },
26
+ /** Drop everything → how many were dropped. */
27
+ clear() {
28
+ const n = items.length;
29
+ items.length = 0;
30
+ return n;
31
+ },
32
+ get size() {
33
+ return items.length;
34
+ },
35
+ };
36
+ }
37
+
38
+ const fits = (s, width) => s.length + 12 <= width;
39
+
40
+ /** The input-row label while questions wait and nothing is being typed; "" when the queue is empty. */
41
+ export function queuedNotice(n, width = 80) {
42
+ if (!n) return "";
43
+ const long = `(${n} queued — runs after this turn; Ctrl-C drops them) `;
44
+ return fits(long, width) ? long : `(${n} queued) `;
45
+ }
46
+
47
+ /** The typing label that fits the row. */
48
+ export function typingNotice(width = 80) {
49
+ return fits(TYPING_NOTICE, width) ? TYPING_NOTICE : TYPING_SHORT;
50
+ }
51
+
52
+ /** One line for the transcript when queued questions are thrown away. */
53
+ export function droppedNote(n) {
54
+ return `(${n} queued question${n === 1 ? "" : "s"} not run — the turn did not finish; type ${n === 1 ? "it" : "them"} again)`;
55
+ }