teapot-coding-agent 0.37.110 → 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.
@@ -7,6 +7,8 @@ import { auditPrompt, parseAuditVerdict } from "./goal-audit.js";
7
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
+ import { turnAnchor } from "./timing.js";
11
+ import { claimsContextLimit, usageLine } from "./context-claim.js";
10
12
  import { mcp } from "./mcp-registry.js";
11
13
  import { flattenToolName } from "./mcp-registry.js";
12
14
  import { metaToolSpecs } from "./meta-tools.js";
@@ -237,6 +239,35 @@ export class Agent {
237
239
  pendingSubReport = "";
238
240
  compactPhase = "";
239
241
  awaitingUser = false;
242
+ /** when the previous round finished, for the time anchor in harness messages (#194) */
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;
248
+ /**
249
+ * "21:04 · 1h12m into this session · 3m since the last turn".
250
+ *
251
+ * Attached to harness-generated prompts only: the system prompt is the provider's prefix-cache anchor, so a
252
+ * clock in there would invalidate the cache on every request. Reported as "AIが時間把握するのが極めて下手"
253
+ * — a five minute exploit and a device reboot read exactly like an instant in the transcript.
254
+ */
255
+ timeAnchor() {
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)}`;
270
+ }
240
271
  activityChars = 0;
241
272
  turnsSinceProgress = 0;
242
273
  consecutiveToolErrors = 0;
@@ -1392,6 +1423,42 @@ export class Agent {
1392
1423
  this.goal.status !== "active" ||
1393
1424
  !this.goal.text.trim())
1394
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
+ }
1395
1462
  if (++this.consecutiveIdleRounds > this.opts.maxConsecutiveIdleRounds) {
1396
1463
  this.consecutiveIdleRounds = 0;
1397
1464
  await this.log.append("system_note", this.currentSession, this.currentBranch, {
@@ -1414,9 +1481,10 @@ export class Agent {
1414
1481
  continue;
1415
1482
  }
1416
1483
  const isSub = !!this.opts.parent;
1484
+ const anchor = this.timeAnchor();
1417
1485
  const nudge = isSub
1418
- ? `[harness] Auto-nudge. Re-anchor on YOUR task — and only that:\n\n${this.goal.text.slice(0, 1500)}\n\nThe inherited conversation is reference only; other agents own any older tasks in it. If your task is complete, call finish() now instead of continuing. If blocked, explain why briefly and finish().`
1419
- : autoContinueNudge(this.goal.text);
1486
+ ? `${anchor}\n[harness] Auto-nudge. Re-anchor on YOUR task — and only that:\n\n${this.goal.text.slice(0, 1500)}\n\nThe inherited conversation is reference only; other agents own any older tasks in it. If your task is complete, call finish() now instead of continuing. If blocked, explain why briefly and finish().`
1487
+ : `${anchor}\n${autoContinueNudge(this.goal.text)}`;
1420
1488
  await this.log.append("prompt", this.currentSession, this.currentBranch, {
1421
1489
  source: "harness",
1422
1490
  text: nudge,
@@ -1457,6 +1525,7 @@ export class Agent {
1457
1525
  return;
1458
1526
  }
1459
1527
  }
1528
+ this.lastTurnEndedAt = Date.now();
1460
1529
  if (!this.stopRequested && !this.awaitingUser)
1461
1530
  this.setStatus("idle", "round complete");
1462
1531
  }
@@ -1909,6 +1978,9 @@ export class Agent {
1909
1978
  toolCalls: m.tool_calls?.map((c) => ({ id: c.id, name: c.function.name })),
1910
1979
  reasoning: res.reasoning,
1911
1980
  });
1981
+ this.lastAssistantText = m.content ?? "";
1982
+ if (m.tool_calls?.length)
1983
+ this.contextClaimNudges = 0;
1912
1984
  this.messages.push(m);
1913
1985
  this.turnsSinceProgress++;
1914
1986
  this.activityChars += m.content?.length ?? 0;
@@ -2435,7 +2507,7 @@ export class Agent {
2435
2507
  this.lastProgressAt = Date.now();
2436
2508
  this.activityChars = 0;
2437
2509
  this.turnsSinceProgress = 0;
2438
- const request = PROGRESS_REQUEST;
2510
+ const request = `${this.timeAnchor()}\n${PROGRESS_REQUEST}`;
2439
2511
  await this.log.append("prompt", this.currentSession, this.currentBranch, {
2440
2512
  source: "harness",
2441
2513
  text: request,
@@ -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
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * A time anchor for harness-generated messages.
3
+ *
4
+ * Reported as "AIが時間把握するのが極めて下手": a five minute exploit, a device reboot, a progress report — and the
5
+ * model narrating it as if no time had passed. Tool results carry `[took 12.3s]` for the call just made, but
6
+ * nothing tells it what time it is NOW or how long it has been going, so a long wait and an instant are
7
+ * indistinguishable in the transcript.
8
+ *
9
+ * Only harness-injected messages get this. It cannot go in the system prompt: that text is the provider's
10
+ * prefix-cache anchor, and a timestamp there would invalidate the cache on every single request.
11
+ */
12
+ /** "0s" / "45s" / "12m" / "1h12m" / "2d3h" — one unit of resolution, never more than two parts */
13
+ export function shortDuration(ms) {
14
+ const secs = Math.max(0, Math.round(ms / 1000));
15
+ if (secs < 60)
16
+ return `${secs}s`;
17
+ const mins = Math.round(secs / 60);
18
+ if (mins < 60)
19
+ return `${mins}m`;
20
+ const hours = Math.floor(mins / 60);
21
+ const remMins = mins % 60;
22
+ if (hours < 24)
23
+ return remMins ? `${hours}h${remMins}m` : `${hours}h`;
24
+ const days = Math.floor(hours / 24);
25
+ const remHours = hours % 24;
26
+ return remHours ? `${days}d${remHours}h` : `${days}d`;
27
+ }
28
+ /**
29
+ * `[harness] 21:04 · 1h12m into this session · last turn ended 3m ago`
30
+ *
31
+ * `startedAt` is the ISO timestamp of the session's first turn; anything unparseable simply drops that part
32
+ * rather than injecting "NaN" into a prompt.
33
+ */
34
+ export function turnAnchor(args) {
35
+ const clock = new Date(args.now);
36
+ const hh = String(clock.getHours()).padStart(2, "0");
37
+ const mm = String(clock.getMinutes()).padStart(2, "0");
38
+ const parts = [`${hh}:${mm}`];
39
+ const start = args.startedAt ? Date.parse(args.startedAt) : Number.NaN;
40
+ if (Number.isFinite(start) && args.now >= start)
41
+ parts.push(`${shortDuration(args.now - start)} into this session`);
42
+ if (args.lastTurnAt && args.now >= args.lastTurnAt) {
43
+ const gap = args.now - args.lastTurnAt;
44
+ // below a few seconds the gap is noise, not information
45
+ if (gap >= 3_000)
46
+ parts.push(`${shortDuration(gap)} since the last turn`);
47
+ }
48
+ return `[harness] ${parts.join(" · ")}`;
49
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.37.110",
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",