teapot-coding-agent 0.37.122 → 0.37.124

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,7 +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
+ import { claimsContextLimit, claimsOwnLimit, usageLine } from "./context-claim.js";
12
12
  import { namesBlocker } from "./blocker.js";
13
13
  import { mcp } from "./mcp-registry.js";
14
14
  import { flattenToolName } from "./mcp-registry.js";
@@ -16,8 +16,7 @@ import { metaToolSpecs } from "./meta-tools.js";
16
16
  import { skillRootsFingerprint, foreignSkillRoots } from "./skills.js";
17
17
  import { extractRules, enforceRules, RULES_HEADING } from "./compact-rules.js";
18
18
  import { bus } from "../bus.js";
19
- export const AUTO_CONTINUE_NUDGE = "[harness] " +
20
- "Continue working toward the current goal. If you are blocked, explain why briefly. " +
19
+ export const AUTO_CONTINUE_NUDGE = "Continue working toward the current goal. If you are blocked, explain why briefly. " +
21
20
  "When the goal is genuinely met — or truly blocked — call finish() " +
22
21
  "(finish(goalComplete=true) when met, finish(goalComplete=false) when blocked) " +
23
22
  "instead of replying in prose; prose here does not stop the loop.";
@@ -27,7 +26,7 @@ export function autoContinueNudge(goalText) {
27
26
  return AUTO_CONTINUE_NUDGE;
28
27
  return `${AUTO_CONTINUE_NUDGE}\nCurrent goal:\n=====\n${goal.slice(0, 1500)}\n=====`;
29
28
  }
30
- export const PROGRESS_REQUEST = "[harness] Please give a brief progress report now: what you are doing, goal progress, " +
29
+ export const PROGRESS_REQUEST = "Please give a brief progress report now: what you are doing, goal progress, " +
31
30
  "what you recently tried, any problems, and your next step. Keep it under 10 lines. " +
32
31
  "Record it with the report_progress TOOL (doing, goalStatus, recent, problems, next) — " +
33
32
  "call that tool; do NOT answer in prose, which would just duplicate this request.";
@@ -248,6 +247,14 @@ export class Agent {
248
247
  lastTurnEndedAt = null;
249
248
  /** the last assistant text, so the loop can tell a context-limit stop from a real one (#201) */
250
249
  lastAssistantText = "";
250
+ /**
251
+ * The last turn's REASONING.
252
+ *
253
+ * The claim usually lives here, not in the visible text: akku1139/teapot#201's follow-up shows a turn whose
254
+ * reasoning reads "My context is nearly exhausted … let me give a final status and stop" while the message it
255
+ * sends is an ordinary status. Checking only the message missed exactly the case that was reported.
256
+ */
257
+ lastReasoning = "";
251
258
  /** how many times this stale round has been answered — bounded so the answer cannot become the loop */
252
259
  contextClaimNudges = 0;
253
260
  /** #200: a finish(false) that names no blocker is questioned once, never twice */
@@ -264,16 +271,39 @@ export class Agent {
264
271
  * (#201) or inside `finish(goalComplete=false)`'s summary, which is how it actually arrived three times in
265
272
  * `mediapad-t5-root-attempt-2-2601e254` (#200 is the same event seen as a stopping habit).
266
273
  */
274
+ /**
275
+ * The answer to "I have run out of context".
276
+ *
277
+ * ONE answer for both things that get said this way: the (false) claim that the window is full, and the real
278
+ * stuck-in-my-own-reasoning case. They are hard to tell apart from the text — "どっちのパターンでも同じようなこと
279
+ * 喋るから混同してる可能性もある" — so the answer does not try: it states the MEASURED window and asks for a new
280
+ * perspective, which is the useful half of both.
281
+ */
267
282
  contextClaimAnswer(where) {
268
- return (`${this.timeAnchor()}\n[harness] ` +
269
- (where === "finish"
270
- ? "That finish() was refused: its summary gives the context window as the blocker, and the window is not yours to run out of."
271
- : "You stopped because of the context window.") +
272
- ` The numbers above are measured, not estimated — the harness compacts automatically and has just done so.` +
273
- `\nContinue the task. If this is a FALSE POSITIVE (you were quoting that phrase in a report rather than ` +
274
- `stopping for it), say so and carry on, or call finish() with your summary if the work is actually done. ` +
275
- `If you are genuinely blocked, finish(goalComplete=false) with a blocker that is NOT the context size — and ` +
276
- `weigh it against the current goal first: a goal that is met is finish(goalComplete=true), not a stop.`);
283
+ const head = where === "finish"
284
+ ? "That finish() was refused: it gives the context window as the blocker, and the window is not yours to run out of."
285
+ : "You stopped, giving the context window as the reason.";
286
+ return (`${this.timeAnchor()}\n${head} The numbers above are MEASURED, compaction is automatic and has ` +
287
+ `just run — so how much window is left is not something you have to guess, and continuing the same way ` +
288
+ `would land you here again in a few turns. Change the perspective instead:\n` +
289
+ `1. Write down what you have LEARNED (add_memory) and what is LEFT (set_todo), so nothing depends on ` +
290
+ `holding this conversation in your head.\n` +
291
+ `2. Name the exact question you cannot answer ("I cannot tell whether X, because Y") and call ask_user with ` +
292
+ `it — or list what you have already ruled out and pick a different mechanism that produces the same evidence.\n` +
293
+ `3. Choose the SMALLEST next step that produces evidence — one experiment, not a longer version of the same ` +
294
+ `attempt.\n` +
295
+ `If this is a FALSE POSITIVE (you were quoting the phrase), say so and carry on. finish(goalComplete=false) ` +
296
+ `only with a blocker that is NOT the context size.`);
297
+ }
298
+ /**
299
+ * A harness message: the time/usage anchor, then the body with any `[harness]` marker of its own removed.
300
+ *
301
+ * The marker is added HERE, once — the templates no longer carry it. They all used to start with `[harness]`, and
302
+ * so does the anchor line, so every composed message opened with it twice: "auto-continueとコンテキストウィンドウで
303
+ * [harness] が重複する問題". Adding it at construction also means a body written without the marker cannot forget.
304
+ */
305
+ harnessMessage(body) {
306
+ return `${this.timeAnchor()}\n${body.replace(/^\[harness\]\s*/, "")}`;
277
307
  }
278
308
  timeAnchor() {
279
309
  const clock = turnAnchor({
@@ -1456,14 +1486,24 @@ export class Agent {
1456
1486
  * carry on. Bounded, and reset by any round that does actual work, so the answer cannot become its own
1457
1487
  * spin.
1458
1488
  */
1489
+ /**
1490
+ * Either claim — "the window is full" (false, and corrected with numbers) or "I cannot see the next
1491
+ * step" (real, and answered with a new perspective) — takes the same route. They are too similar in the
1492
+ * text to separate safely, and the one answer covers both.
1493
+ */
1494
+ const windowClaim = claimsContextLimit(this.lastAssistantText) ||
1495
+ claimsContextLimit(this.lastReasoning) ||
1496
+ claimsOwnLimit(this.lastAssistantText) ||
1497
+ claimsOwnLimit(this.lastReasoning);
1459
1498
  if (this.contextClaimNudges < 2 &&
1460
1499
  !this.awaitingUser &&
1461
- claimsContextLimit(this.lastAssistantText)) {
1500
+ windowClaim) {
1462
1501
  this.contextClaimNudges += 1;
1463
1502
  await this.log.append("system_note", this.currentSession, this.currentBranch, {
1464
1503
  event: "context-claim-answered",
1465
1504
  attempt: this.contextClaimNudges,
1466
- 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)",
1505
+ via: "stop",
1506
+ detail: "the agent stopped blaming its remaining capacity — the harness compacted and answered with the measured window plus a fresh-perspective instruction (#201)",
1467
1507
  });
1468
1508
  await this.maybeCompact(true);
1469
1509
  const msg = this.contextClaimAnswer("stop");
@@ -1498,10 +1538,9 @@ export class Agent {
1498
1538
  continue;
1499
1539
  }
1500
1540
  const isSub = !!this.opts.parent;
1501
- const anchor = this.timeAnchor();
1502
1541
  const nudge = isSub
1503
- ? `${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().`
1504
- : `${anchor}\n${autoContinueNudge(this.goal.text)}`;
1542
+ ? this.harnessMessage(`[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().`)
1543
+ : this.harnessMessage(autoContinueNudge(this.goal.text));
1505
1544
  await this.log.append("prompt", this.currentSession, this.currentBranch, {
1506
1545
  source: "harness",
1507
1546
  text: nudge,
@@ -1599,7 +1638,10 @@ export class Agent {
1599
1638
  if (fin.goalComplete !== true &&
1600
1639
  !this.awaitingUser &&
1601
1640
  this.contextClaimNudges < 2 &&
1602
- claimsContextLimit(String(fin.summary ?? ""))) {
1641
+ (claimsContextLimit(String(fin.summary ?? "")) ||
1642
+ claimsContextLimit(this.lastReasoning) ||
1643
+ claimsOwnLimit(String(fin.summary ?? "")) ||
1644
+ claimsOwnLimit(this.lastReasoning))) {
1603
1645
  this.contextClaimNudges += 1;
1604
1646
  await this.log.append("system_note", this.currentSession, this.currentBranch, {
1605
1647
  event: "context-claim-answered",
@@ -1645,11 +1687,11 @@ export class Agent {
1645
1687
  event: "finish-without-blocker",
1646
1688
  detail: "finish(goalComplete=false) named no blocker while the harness saw none either — asked for one instead of ending the round (#200)",
1647
1689
  });
1648
- const msg = `${this.timeAnchor()}\n[harness] That finish() was refused: its summary names no blocker, and ` +
1690
+ const msg = this.harnessMessage(`[harness] That finish() was refused: its summary names no blocker, and ` +
1649
1691
  `nothing in the harness agrees with one — the context window above is measured, compaction is ` +
1650
1692
  `automatic, and your tools have not been failing.\nContinue the task. If you ARE blocked, name it ` +
1651
1693
  `concretely: what you tried, what exactly failed, and why it cannot be worked around — then ` +
1652
- `finish(goalComplete=false). If the goal is met, that is finish(goalComplete=true), not a stop.`;
1694
+ `finish(goalComplete=false). If the goal is met, that is finish(goalComplete=true), not a stop.`);
1653
1695
  await this.answerMeta(call, "(finish refused: no blocker named — say what actually failed)");
1654
1696
  await this.log.append("prompt", this.currentSession, this.currentBranch, { source: "harness", text: msg });
1655
1697
  this.messages.push({ role: "user", content: msg });
@@ -2063,6 +2105,7 @@ export class Agent {
2063
2105
  reasoning: res.reasoning,
2064
2106
  });
2065
2107
  this.lastAssistantText = m.content ?? "";
2108
+ this.lastReasoning = res.reasoning ?? "";
2066
2109
  /**
2067
2110
  * Reset the "stop was questioned" counters only on REAL work.
2068
2111
  *
@@ -2600,7 +2643,7 @@ export class Agent {
2600
2643
  this.lastProgressAt = Date.now();
2601
2644
  this.activityChars = 0;
2602
2645
  this.turnsSinceProgress = 0;
2603
- const request = `${this.timeAnchor()}\n${PROGRESS_REQUEST}`;
2646
+ const request = this.harnessMessage(PROGRESS_REQUEST);
2604
2647
  await this.log.append("prompt", this.currentSession, this.currentBranch, {
2605
2648
  source: "harness",
2606
2649
  text: request,
@@ -26,6 +26,11 @@ const STOP_PATTERNS = [
26
26
  /上下文[^。\n]{0,10}(?:快|即将|要)?(?:用满|耗尽|不足)/,
27
27
  /(?:token|上下文)[^。\n]{0,12}(?:预算|额度)[^。\n]{0,12}(?:不足|耗尽)/,
28
28
  /(?:context|token)s?[\s-]*(?:window|limit)[^.\n]{0,40}(?:stop|halt|end|paus|abort)/i,
29
+ // the reasoning-side phrasing measured in akku1139/teapot#201's follow-up report
30
+ /context (?:is |was )?(?:nearly |almost )?(?:exhausted|full|gone|out)/i,
31
+ /out of context (?:to|for)/i,
32
+ /can'?t reliably continue/i,
33
+ /context[- ]blocked/i,
29
34
  // deepseek-ai/DeepSeek-V3#1737 / #1744: the web product's own wording, reproduced by the model
30
35
  /le?ngth\s*limit[^.\n]{0,20}(?:reached|exceeded|hit)/i,
31
36
  /(?:your )?chat limit (?:has )?(?:finished|been reached|reached)/i,
@@ -74,3 +79,30 @@ export function usageLine(used, budget) {
74
79
  const pct = Math.max(0, Math.min(100, Math.round((used / budget) * 100)));
75
80
  return `context ${pct}% (${fmt(used)}/${fmt(budget)} tokens)`;
76
81
  }
82
+ /**
83
+ * …and the OTHER thing that gets reported as "context is exhausted": the model has run out of its own ideas.
84
+ *
85
+ * "コンテキストが尽きたっていうのがコンテキストウィンドウが尽きたと勘違いしてるパターンと、自力の推論の限界に達した
86
+ * 場合がありそう" — two different problems with different answers. The window case is false and gets corrected with
87
+ * numbers; being STUCK is real, and telling the model to continue would just spin. What a stuck agent needs is to
88
+ * name the question it cannot answer and hand it over (ask_user) or change angle — not another turn of the same.
89
+ */
90
+ const OWN_LIMIT_PATTERNS = [
91
+ /(?:reasoning|analysis|own) (?:limit|limits|capacity)s?\b/i,
92
+ /reached (?:the )?limits? of my (?:reasoning|analysis|understanding)/i,
93
+ /can'?t (?:reason|figure|work) (?:this |it )?out (?:any (?:further|longer))?/i,
94
+ /no (?:further|more) (?:ideas|approaches|options|progress)/i,
95
+ /(?:推論|思考|自力)[^。\n]{0,12}(?:限界|行き詰|手詰)/,
96
+ /(?:打つ手|手立て|これ以上)[^。\n]{0,10}(?:ない|尽きた|思いつかない)/,
97
+ /行き詰ま(?:った|り)/,
98
+ /(?:无法再|想不出|推理到极限)/,
99
+ ];
100
+ export function claimsOwnLimit(text) {
101
+ const raw = String(text ?? "");
102
+ if (!raw.trim())
103
+ return false;
104
+ const t = withoutQuotedBlocks(raw);
105
+ if (!t.trim())
106
+ return false;
107
+ return OWN_LIMIT_PATTERNS.some((re) => re.test(t));
108
+ }
@@ -176,7 +176,7 @@ export class McpRegistry {
176
176
  }
177
177
  try {
178
178
  const r = await this.servers.get(parts.server).connection.call(parts.tool, args);
179
- return { ok: r.ok, text: r.text };
179
+ return { ok: r.ok, text: r.text, ...(r.images?.length ? { images: r.images } : {}) };
180
180
  }
181
181
  catch (err) {
182
182
  const st = this.servers.get(parts.server);
package/dist/agent/mcp.js CHANGED
@@ -11,15 +11,46 @@ async function mcpSdk() {
11
11
  }
12
12
  return sdkPromise;
13
13
  }
14
- function resultText(result) {
14
+ export function resultText(result) {
15
15
  const parts = [];
16
+ const images = [];
17
+ let extraImages = 0;
18
+ const bytes = (b64) => Math.round((b64.length * 3) / 4);
16
19
  for (const c of result?.content ?? []) {
17
- if (c?.type === "text" && typeof c.text === "string")
20
+ if (!c)
21
+ continue;
22
+ if (c.type === "text" && typeof c.text === "string") {
18
23
  parts.push(c.text);
19
- else if (c?.type)
20
- parts.push(`[${c.type} content omitted]`);
24
+ }
25
+ else if (c.type === "image" && typeof c.data === "string" && c.data) {
26
+ const mime = c.mimeType || "image/png";
27
+ const name = `mcp-image-${images.length + 1}.${mime.split("/")[1] ?? "png"}`;
28
+ if (images.length === 0)
29
+ images.push({ url: `data:${mime};base64,${c.data}`, name });
30
+ else
31
+ extraImages++;
32
+ parts.push(`[image: ${mime}, ${Math.round(bytes(c.data) / 1024)}KB]`);
33
+ }
34
+ else if (c.type === "resource" && c.resource) {
35
+ const r = c.resource;
36
+ if (typeof r.text === "string")
37
+ parts.push(r.text);
38
+ else if (typeof r.blob === "string") {
39
+ parts.push(`[resource ${r.mimeType || "unknown"} · ${r.uri || "embedded"} · ${Math.round(bytes(r.blob) / 1024)}KB]`);
40
+ }
41
+ else
42
+ parts.push(`[resource ${r.uri || "embedded"}]`);
43
+ }
44
+ else if (c.type === "audio" && typeof c.data === "string") {
45
+ parts.push(`[audio: ${c.mimeType || "unknown"}, ${Math.round(bytes(c.data) / 1024)}KB — not readable by the model]`);
46
+ }
47
+ else if (c.type) {
48
+ parts.push(`[${c.type} content: ${Math.round(bytes(String(c.data ?? "")) / 1024)}KB]`);
49
+ }
21
50
  }
22
- return { text: parts.join("\n") || "(no content)", ok: result?.isError !== true };
51
+ if (extraImages > 0)
52
+ parts.push(`(+${extraImages} more image(s) shown as metadata — only the first is attached)`);
53
+ return { text: parts.join("\n") || "(no content)", ok: result?.isError !== true, images };
23
54
  }
24
55
  function toTools(list, server) {
25
56
  const out = [];
@@ -2297,7 +2297,8 @@ export async function executeTool(name, rawArgs, ctx) {
2297
2297
  const r = await mcp.call(flattenToolName(entry.serverId, entry.name), callArgs);
2298
2298
  if (!r)
2299
2299
  return { ok: false, result: `unknown tool: ${entry.name}` };
2300
- return { ok: r.ok, result: r.text };
2300
+ // an MCP server may answer with an image; carry the first one the same way `read_file` does (#203)
2301
+ return { ok: r.ok, result: r.text, ...(r.images?.[0] ? { image: r.images[0] } : {}) };
2301
2302
  }
2302
2303
  if (name.startsWith(MCP_PREFIX)) {
2303
2304
  if (ctx.signal?.aborted)
@@ -2312,7 +2313,7 @@ export async function executeTool(name, rawArgs, ctx) {
2312
2313
  const r = await mcp.call(name, args);
2313
2314
  if (!r)
2314
2315
  return { ok: false, result: `unknown tool: ${name}` };
2315
- return { ok: r.ok, result: r.text };
2316
+ return { ok: r.ok, result: r.text, ...(r.images?.[0] ? { image: r.images[0] } : {}) };
2316
2317
  }
2317
2318
  const def = TOOLS.find((t) => t.name === name);
2318
2319
  if (!def)
@@ -875,6 +875,26 @@ export function buildApp(master) {
875
875
  a.start("prompt");
876
876
  return c.json({ ok: true, promptId, queued: a.snapshot().pendingPrompts });
877
877
  });
878
+ /**
879
+ * Force-load and follow a skill.
880
+ *
881
+ * The wording lives HERE, not in the browser: it is a harness message, and the frontend used to compose it and
882
+ * post it with `source: "harness"` — which put harness-authored text in the UI and let the client claim the
883
+ * harness role. The goal notification two hundred lines down already worked this way; this is the same shape.
884
+ */
885
+ app.post("/api/agents/:id/skill", async (c) => {
886
+ const a = master.agents.get(c.req.param("id"));
887
+ if (!a)
888
+ return notFound(c, "agent", c.req.param("id"));
889
+ const body = await c.req.json().catch(() => null);
890
+ const name = String(body?.name ?? "").trim();
891
+ if (!name)
892
+ return c.json({ error: "name required" }, 400);
893
+ const promptId = a.enqueuePrompt(`[harness] Force-load and follow the skill "${name}" now: call load_skill("${name}") and execute its playbook for the current task.`, "harness");
894
+ if (a.status !== "running")
895
+ a.start("skill");
896
+ return c.json({ ok: true, promptId });
897
+ });
878
898
  app.post("/api/agents/:id/prompt/cancel", async (c) => {
879
899
  const a = master.agents.get(c.req.param("id"));
880
900
  if (!a)
@@ -1,5 +1,5 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
2
+ import { existsSync, readFileSync, readlinkSync } from "node:fs";
3
3
  import { toolShellFor } from "../agent/tools.js";
4
4
  export function terminalShellFor(platform, env, exists = existsSync) {
5
5
  return toolShellFor(platform, env, exists).file;
@@ -46,6 +46,7 @@ export function createTerminal(agentId, workspace, title) {
46
46
  const id = `t${++seq}-${Date.now().toString(36)}`;
47
47
  const t = {
48
48
  id,
49
+ workspace,
49
50
  agentId,
50
51
  title: title?.trim().slice(0, 60) || `shell ${live.length + 1}`,
51
52
  child,
@@ -86,11 +87,35 @@ export function createTerminal(agentId, workspace, title) {
86
87
  console.log(`[teapot] ⌨ terminal open: ${id} ${agentId} @ ${workspace} (${hasScript ? "pty" : "pipe"})`);
87
88
  return { ok: true, terminal: infoOf(t) };
88
89
  }
90
+ /**
91
+ * The shell's current directory, for the tab label.
92
+ *
93
+ * The pty is spawned through `script`, so `t.child.pid` is script's — the SHELL is its child, and it is the shell
94
+ * whose cwd moves when the operator `cd`s. Reading `/proc/<pid>/cwd` is Linux-only and deliberately falls back to
95
+ * the workspace: a wrong label is worse than a generic one, and this must never throw.
96
+ */
97
+ function shellCwd(t) {
98
+ try {
99
+ const kids = readFileSync(`/proc/${t.child.pid}/task/${t.child.pid}/children`, "utf8").trim().split(/\s+/);
100
+ for (const pid of kids) {
101
+ if (!pid)
102
+ continue;
103
+ const cwd = readlinkSync(`/proc/${pid}/cwd`);
104
+ if (cwd)
105
+ return cwd;
106
+ }
107
+ }
108
+ catch {
109
+ /* not Linux, or the process is gone */
110
+ }
111
+ return t.workspace;
112
+ }
89
113
  function infoOf(t) {
90
114
  return {
91
115
  id: t.id,
92
116
  agentId: t.agentId,
93
117
  title: t.title,
118
+ cwd: shellCwd(t),
94
119
  clients: sinks.get(t.id)?.size ?? 0,
95
120
  createdAt: t.createdAt,
96
121
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.37.122",
3
+ "version": "0.37.124",
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",