teapot-coding-agent 0.37.111 → 0.37.112

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.
@@ -8,6 +8,7 @@ import { createCatalog } from "./tool-catalog.js";
8
8
  import { resetToolCatalog, executeTool, toolSpecs, currentSkills, safeJoin, isContextOverflow, isRequestNodeLimit, hasRunningBgShells, hasRunningBgShellsFor, killBgShells, runningBgShellCount } from "./tools.js";
9
9
  import { effortChoosable } from "./llm.js";
10
10
  import { turnAnchor } from "./timing.js";
11
+ import { claimsContextLimit, usageLine } from "./context-claim.js";
11
12
  import { mcp } from "./mcp-registry.js";
12
13
  import { flattenToolName } from "./mcp-registry.js";
13
14
  import { metaToolSpecs } from "./meta-tools.js";
@@ -240,6 +241,10 @@ export class Agent {
240
241
  awaitingUser = false;
241
242
  /** when the previous round finished, for the time anchor in harness messages (#194) */
242
243
  lastTurnEndedAt = null;
244
+ /** the last assistant text, so the loop can tell a context-limit stop from a real one (#201) */
245
+ lastAssistantText = "";
246
+ /** how many times this stale round has been answered — bounded so the answer cannot become the loop */
247
+ contextClaimNudges = 0;
243
248
  /**
244
249
  * "21:04 · 1h12m into this session · 3m since the last turn".
245
250
  *
@@ -248,7 +253,20 @@ export class Agent {
248
253
  * — a five minute exploit and a device reboot read exactly like an instant in the transcript.
249
254
  */
250
255
  timeAnchor() {
251
- return turnAnchor({ now: Date.now(), startedAt: this.stats.startedAt, lastTurnAt: this.lastTurnEndedAt });
256
+ const clock = turnAnchor({
257
+ now: Date.now(),
258
+ startedAt: this.stats.startedAt,
259
+ lastTurnAt: this.lastTurnEndedAt,
260
+ });
261
+ /**
262
+ * …plus the one fact the model otherwise GUESSES: how much of the window is actually used.
263
+ *
264
+ * deepseek-ai/DeepSeek-V3#1669 measured a model declaring "上下文余量不足" at 44-47% of the window, after a
265
+ * compaction had succeeded — the numbers were never in front of it, so it inferred exhaustion from elapsed
266
+ * time and task size. Telling it the real percentage each turn costs nothing (this line is already
267
+ * per-message) and removes the inference.
268
+ */
269
+ return `${clock} · ${usageLine(this.contextSizeForBudgeting(), this.opts.contextTokenBudget)}`;
252
270
  }
253
271
  activityChars = 0;
254
272
  turnsSinceProgress = 0;
@@ -1405,6 +1423,42 @@ export class Agent {
1405
1423
  this.goal.status !== "active" ||
1406
1424
  !this.goal.text.trim())
1407
1425
  break;
1426
+ /**
1427
+ * The model stopped and blamed the context window (#201).
1428
+ *
1429
+ * "コンテキスト上限のため停止します" with no tool call and no finish() is not a blocker the model is
1430
+ * entitled to declare: compaction is the harness's job and it runs automatically. Accepting the claim
1431
+ * counted the round as idle until `maxConsecutiveIdleRounds` stopped the loop — measured three times in
1432
+ * `mediapad-t5-root-attempt-2-2601e254`. So the loop answers it: compact for real, then say so and
1433
+ * carry on. Bounded, and reset by any round that does actual work, so the answer cannot become its own
1434
+ * spin.
1435
+ */
1436
+ if (this.contextClaimNudges < 2 &&
1437
+ !this.awaitingUser &&
1438
+ claimsContextLimit(this.lastAssistantText)) {
1439
+ this.contextClaimNudges += 1;
1440
+ await this.log.append("system_note", this.currentSession, this.currentBranch, {
1441
+ event: "context-claim-answered",
1442
+ attempt: this.contextClaimNudges,
1443
+ detail: "the agent stopped because of the context window — compaction is the harness's job, so it compacted and told the agent to continue (#201)",
1444
+ });
1445
+ await this.maybeCompact(true);
1446
+ const msg = `${this.timeAnchor()}\n[harness] You stopped because of the context window. The numbers above are ` +
1447
+ `measured, not estimated: the harness compacts automatically and has just done so, so running out ` +
1448
+ `of window is not something you can decide. Continue the task.\n` +
1449
+ `If this is a FALSE POSITIVE — you were quoting that phrase in a report rather than stopping for it — ` +
1450
+ `say so and carry on, or call finish() with your summary if the work is actually done. If you are ` +
1451
+ `genuinely blocked, finish(goalComplete=false) with a blocker that is NOT the context size, and weigh ` +
1452
+ `it against the current goal first: a goal that is met is finish(goalComplete=true), not a stop.`;
1453
+ await this.log.append("prompt", this.currentSession, this.currentBranch, {
1454
+ source: "harness",
1455
+ text: msg,
1456
+ });
1457
+ this.messages.push({ role: "user", content: msg });
1458
+ this.lastAssistantText = "";
1459
+ this.consecutiveIdleRounds = 0;
1460
+ continue;
1461
+ }
1408
1462
  if (++this.consecutiveIdleRounds > this.opts.maxConsecutiveIdleRounds) {
1409
1463
  this.consecutiveIdleRounds = 0;
1410
1464
  await this.log.append("system_note", this.currentSession, this.currentBranch, {
@@ -1924,6 +1978,9 @@ export class Agent {
1924
1978
  toolCalls: m.tool_calls?.map((c) => ({ id: c.id, name: c.function.name })),
1925
1979
  reasoning: res.reasoning,
1926
1980
  });
1981
+ this.lastAssistantText = m.content ?? "";
1982
+ if (m.tool_calls?.length)
1983
+ this.contextClaimNudges = 0;
1927
1984
  this.messages.push(m);
1928
1985
  this.turnsSinceProgress++;
1929
1986
  this.activityChars += m.content?.length ?? 0;
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Does this assistant message claim the CONTEXT WINDOW is why it stopped?
3
+ *
4
+ * Measured in `mediapad-t5-root-attempt-2-2601e254`: three times the model ended a turn with prose —
5
+ * "コンテキスト上限のため一旦区切ります" / "コンテキスト上限のため停止します" — with no tool call and no
6
+ * `finish()`. The loop treats that as an idle round, counts it against `maxConsecutiveIdleRounds`, and stops.
7
+ *
8
+ * The claim is also FALSE in this harness: compaction is the harness's job and it runs automatically, so
9
+ * "out of context" is not a blocker the model is entitled to stop for. Recognising the claim is what lets the
10
+ * loop answer it (compact, then say so) instead of accepting it.
11
+ *
12
+ * Deliberately narrow: it must catch the STOPPING claim, not any mention of the topic. "コンテキスト上限に
13
+ * 注意しながら続けます" is not a reason given for stopping, and matching it would derail a working turn.
14
+ */
15
+ /**
16
+ * Phrasings measured in this project and in the report it links
17
+ * (deepseek-ai/DeepSeek-V3#1669: "上下文余量不足" / "上下文快用满了" after a compaction that had left the window
18
+ * at 44-47% used).
19
+ */
20
+ const STOP_PATTERNS = [
21
+ /コンテキスト(?:の)?上限[^。\n]{0,20}(?:停止|区切|終了|中断|打ち切)/,
22
+ /コンテキスト(?:の)?上限のため/,
23
+ /トークン(?:数)?(?:の)?上限[^。\n]{0,20}(?:停止|区切|終了|中断|打ち切)/,
24
+ // the same claim in the languages the model actually writes in
25
+ /上下文[^。\n]{0,20}(?:余量|余裕)[^。\n]{0,20}(?:不足|不够|快满|用满)/,
26
+ /上下文[^。\n]{0,10}(?:快|即将|要)?(?:用满|耗尽|不足)/,
27
+ /(?:token|上下文)[^。\n]{0,12}(?:预算|额度)[^。\n]{0,12}(?:不足|耗尽)/,
28
+ /(?:context|token)s?[\s-]*(?:window|limit)[^.\n]{0,40}(?:stop|halt|end|paus|abort)/i,
29
+ // deepseek-ai/DeepSeek-V3#1737 / #1744: the web product's own wording, reproduced by the model
30
+ /le?ngth\s*limit[^.\n]{0,20}(?:reached|exceeded|hit)/i,
31
+ /(?:your )?chat limit (?:has )?(?:finished|been reached|reached)/i,
32
+ /(?:limit|full|exhausted|reached)[^.\n]{0,40}start (?:a )?new chat/i,
33
+ /(?:running (?:low on|out of) context|not enough context (?:left|remaining)|context (?:is )?(?:almost )?(?:full|exhausted)|out of context (?:space|budget))/i,
34
+ /(?:stop|halt|end|paus|abort)[a-z]*\s+(?:here|now)?\s*(?:because|due to)[^.\n]{0,40}(?:context|token)/i,
35
+ /stopping (?:here )?(?:because|due to)[^.\n]{0,40}(?:context|token)/i,
36
+ ];
37
+ /**
38
+ * Strip what the agent is REPORTING from what it is SAYING.
39
+ *
40
+ * A turn that summarises an investigation legitimately quotes a log line — "コンテキスト上限のため停止します"
41
+ * inside a fenced block or a `>` quote is evidence, not a reason to stop. Matching it would force a continue on
42
+ * a model that is doing exactly the right thing, which is why the quoted forms are removed before matching.
43
+ */
44
+ function withoutQuotedBlocks(text) {
45
+ const kept = [];
46
+ let fence = false;
47
+ for (const line of text.split(/\r?\n/)) {
48
+ if (/^\s*```/.test(line)) {
49
+ fence = !fence;
50
+ continue;
51
+ }
52
+ if (fence)
53
+ continue;
54
+ if (/^\s*>/.test(line))
55
+ continue;
56
+ kept.push(line);
57
+ }
58
+ return kept.join("\n");
59
+ }
60
+ export function claimsContextLimit(text) {
61
+ const raw = String(text ?? "");
62
+ if (!raw.trim())
63
+ return false;
64
+ const t = withoutQuotedBlocks(raw);
65
+ if (!t.trim())
66
+ return false;
67
+ return STOP_PATTERNS.some((re) => re.test(t));
68
+ }
69
+ /** "68k/200k tokens (34%)" — the ground truth the model does not otherwise have */
70
+ export function usageLine(used, budget) {
71
+ const fmt = (n) => (n >= 1_000 ? `${Math.round(n / 1_000)}k` : String(Math.max(0, Math.round(n))));
72
+ if (!Number.isFinite(budget) || budget <= 0)
73
+ return `context ${fmt(used)} tokens used`;
74
+ const pct = Math.max(0, Math.min(100, Math.round((used / budget) * 100)));
75
+ return `context ${pct}% (${fmt(used)}/${fmt(budget)} tokens)`;
76
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.37.111",
3
+ "version": "0.37.112",
4
4
  "description": "A lightweight, always-on multi-agent harness for AI coding agents",
5
5
  "type": "module",
6
6
  "license": "AGPL-3.0-or-later",