teapot-coding-agent 0.37.26 → 0.37.28

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.
@@ -4783,14 +4783,33 @@ export class Agent {
4783
4783
  /**
4784
4784
  * Wait for the round to end, bounded.
4785
4785
  *
4786
- * `settled()` resolves when the run chain drains, which is exactly "the turn finished". The
4787
- * timeout exists only for a wedged agent (an LLM call that never returns); the caller reports
4788
- * which agents hit it rather than leaving them silently half-stopped.
4786
+ * `settled()` resolves when the run chain drains, which is "the turn finished" — but a
4787
+ * BACKGROUND SHELL is not on that chain. The round deliberately ends while a dev server,
4788
+ * watcher or long build keeps running (`hasRunningBgShells` breaks the loop instead of nagging),
4789
+ * so `settled()` is already resolved and this used to return immediately.
4790
+ *
4791
+ * MEASURED: an update then reached `dispose()`, which calls `killBgShells` — a live update killed
4792
+ * every background job on the machine, with no wait and no notice. A background job is work in
4793
+ * flight, which is the whole reason `isLive()` counts it, so it must be waited for here too.
4794
+ *
4795
+ * The timeout exists only for a wedged agent (an LLM call that never returns, or a job that will
4796
+ * never exit); the caller reports which agents hit it rather than leaving them silently
4797
+ * half-stopped.
4789
4798
  */
4790
4799
  let timer;
4800
+ const done = async () => {
4801
+ await this.settled();
4802
+ // wait out any background job this agent owns, polling the same owner-scoped question
4803
+ // `isLive()` uses — a sibling's job in the shared workspace is not this agent's work
4804
+ while (hasRunningBgShellsFor(this.toolCtx.cwd, this.opts.id)) {
4805
+ if (this.stopRequested)
4806
+ break;
4807
+ await this.sleepInterruptible(500);
4808
+ }
4809
+ };
4791
4810
  try {
4792
4811
  await Promise.race([
4793
- this.settled(),
4812
+ done(),
4794
4813
  new Promise((_, reject) => {
4795
4814
  timer = setTimeout(() => reject(new Error(`did not reach a turn boundary within ${timeoutMs}ms`)), timeoutMs);
4796
4815
  }),
package/dist/master.js CHANGED
@@ -409,6 +409,17 @@ export function sanitizeAgentId(id) {
409
409
  }
410
410
  export class Master {
411
411
  agents = new Map();
412
+ /**
413
+ * Configured agents that could NOT be loaded, with the reason.
414
+ *
415
+ * `addAgent` throws when an entry is unusable (no model configured, duplicate id, unknown
416
+ * provider) and the boot loop skips it so one bad entry cannot take the server down. The skip was
417
+ * SILENT, though, and the agent's sessions stayed in `/api/sessions` — so the sidebar offered a
418
+ * timeline that `/api/agents/<id>/events` answered with 404, and the UI sat on "loading timeline…"
419
+ * (reported as "セッション切り替えがバカ重い"). Recording the reason turns that into something the
420
+ * UI can explain.
421
+ */
422
+ unavailableAgents = new Map();
412
423
  /** Agent Plugins loaded at boot (#162); their skill roots are offered to every agent */
413
424
  plugins = [];
414
425
  /**
@@ -855,8 +866,11 @@ export class Master {
855
866
  // archived agents keep their config entry and their history but do not run;
856
867
  // starting one would spend a provider request and mint/rewrite a session for
857
868
  // something the operator deliberately put away.
858
- if (ac.archived)
869
+ if (ac.archived) {
870
+ // archived: not started, but its history must stay readable (the sidebar lists it)
871
+ this.unavailableAgents.set(ac.id, "archived");
859
872
  continue;
873
+ }
860
874
  try {
861
875
  await this.addAgent(ac);
862
876
  }
@@ -864,6 +878,7 @@ export class Master {
864
878
  // one bad entry (duplicate id, unknown provider, …) must not take the
865
879
  // whole master down — skip it loudly and keep serving the rest
866
880
  console.error(`[teapot] skipping agent "${ac.id}": ${err.message}`);
881
+ this.unavailableAgents.set(ac.id, err.message);
867
882
  }
868
883
  }
869
884
  for (const t of this.config.tasks ?? []) {
@@ -1709,19 +1724,50 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
1709
1724
  * manifests: 493 agents were silently moved to empty sessions, and the
1710
1725
  * mapping back was only recoverable from these `agent` fields.
1711
1726
  */
1727
+ /**
1728
+ * The owning agent, from the log's FIRST line.
1729
+ *
1730
+ * Read with a bounded `readSync` rather than `readFileSync(...).split("\n").find(...)`.
1731
+ *
1732
+ * MEASURED on this machine: 831 session logs totalling 471.8MB, the largest 50.6MB, nine of them
1733
+ * over 10MB. `readFileSync` decoded a whole log to reach its first line, and `split("\n")`
1734
+ * allocated an array of every line in it — for ONE field of the first event. Called once per
1735
+ * directory while resolving sessions, that is tens of megabytes of transient allocation per pass,
1736
+ * which is the baseline this boot carried.
1737
+ *
1738
+ * The first line is the first event (the log is append-only, in order), so a single small read
1739
+ * answers the question.
1740
+ */
1712
1741
  logOwner(dirName) {
1742
+ let fd;
1713
1743
  try {
1714
- const first = readFileSync(path.join(this.sessionsRoot(), dirName, "chat.jsonl"), "utf8")
1715
- .split("\n")
1716
- .find((l) => l.trim());
1717
- if (!first)
1744
+ fd = openSync(path.join(this.sessionsRoot(), dirName, "chat.jsonl"), "r");
1745
+ const buf = Buffer.alloc(8 * 1024);
1746
+ const n = readSync(fd, buf, 0, buf.length, 0);
1747
+ if (n <= 0)
1748
+ return null;
1749
+ // a torn final line cannot be the one we want: take the first COMPLETE line
1750
+ const head = buf.subarray(0, n).toString("utf8");
1751
+ const nl = head.indexOf("\n");
1752
+ const line = (nl >= 0 ? head.slice(0, nl) : head).trim();
1753
+ if (!line)
1718
1754
  return null;
1719
- const parsed = JSON.parse(first);
1755
+ const parsed = JSON.parse(line);
1720
1756
  return typeof parsed.agent === "string" && parsed.agent ? parsed.agent : null;
1721
1757
  }
1722
1758
  catch {
1723
1759
  return null; // no log / unreadable head — cannot prove anything
1724
1760
  }
1761
+ finally {
1762
+ if (fd !== undefined) {
1763
+ try {
1764
+ closeSync(fd);
1765
+ }
1766
+ catch {
1767
+ /* already closed */
1768
+ }
1769
+ }
1770
+ }
1725
1771
  }
1726
1772
  /**
1727
1773
  * A human title for a session dir, from its first user prompt, or null.
@@ -2268,6 +2314,16 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2268
2314
  tick() {
2269
2315
  const now = new Date();
2270
2316
  const minuteKey = Math.floor(now.getTime() / 60_000);
2317
+ /**
2318
+ * Push the runtime numbers instead of making every tab poll them.
2319
+ *
2320
+ * `/api/metrics` was fetched on a 30s timer by each connected client, which is a GET whose
2321
+ * ANSWER the server already has — the one shape a push socket makes redundant. It rides this
2322
+ * existing 15s tick (the same "no extra timers" rule as the rest of the master) and a client that
2323
+ * was asleep simply re-reads over HTTP on wake, which is what the recovery path is for.
2324
+ */
2325
+ if (bus.listenerCount("update") > 0)
2326
+ bus.emit("update", { kind: "metrics", metrics: this.metrics() });
2271
2327
  for (const t of this.tasks) {
2272
2328
  try {
2273
2329
  if (!matches(t.schedule, now))
@@ -2283,6 +2339,8 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2283
2339
  if (!agent)
2284
2340
  continue;
2285
2341
  console.log(`[teapot] scheduled task "${t.task.id}" -> agent ${t.task.agent}`);
2342
+ // "last"/"next" changed, so the schedule table the UI shows is now stale
2343
+ bus.emit("update", { kind: "tasks", tasks: this.tasksView() });
2286
2344
  void (async () => {
2287
2345
  if (t.task.forked)
2288
2346
  await agent.fork();
@@ -2429,10 +2487,18 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2429
2487
  /**
2430
2488
  * How long a live update waits for agents to reach a turn boundary.
2431
2489
  *
2432
- * Generous: a round can be a several-minute build. The alternative to waiting is aborting a tool
2433
- * mid-write, so the cap exists only to bound a wedged agent, and those are reported.
2490
+ * It must be comparable to a TOOL's own ceiling, not to a human's patience. MEASURED: a live update
2491
+ * waited 180s while a `bash` call was in flight, gave up, and killed it — the timeline then showed
2492
+ * `✖ fail … not completed — the agent restarted while this tool was running` for work that was
2493
+ * about to return (that call had been running ~300s, well within the 3600s a `bash` call may take).
2494
+ * Waiting too SHORT is what turns a clean update into a truncated turn.
2495
+ *
2496
+ * 15 minutes: three times the longest call seen in the wild (a ~300s `bash`) and still short of a
2497
+ * `bash` call's own 3600s ceiling. Waiting an entire tool ceiling would block the update for an
2498
+ * hour, which defeats the purpose of updating; waiting 180s interrupted work that was about to
2499
+ * finish. The interrupted case is not lost — the resumed session is told exactly what happened.
2434
2500
  */
2435
- updateWindDownMs = 180_000;
2501
+ updateWindDownMs = 900_000;
2436
2502
  /**
2437
2503
  * Ask every agent to stop at its next turn boundary; returns the ids that did not make it.
2438
2504
  *
@@ -2441,9 +2507,22 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2441
2507
  * it interrupted.
2442
2508
  */
2443
2509
  async windDownAllAgents(timeoutMs = this.updateWindDownMs) {
2444
- const ids = [...this.agents.keys()];
2445
- if (!ids.length)
2510
+ /**
2511
+ * Only agents with WORK IN FLIGHT need to be waited for.
2512
+ *
2513
+ * This asked every loaded agent, and the log then said "waiting for 440 agent(s)" on a machine
2514
+ * with one working session (MEASURED: 511 configured, 71 archived, 440 loaded). The count was
2515
+ * false in the most alarming direction — it read as 440 interrupted jobs — and the call itself is
2516
+ * not free: each idle agent gets a `windDownRequested` flag set and a `wake()`, which is
2517
+ * pointless state churn on agents that are doing nothing.
2518
+ */
2519
+ const ids = [...this.agents.entries()]
2520
+ .filter(([, a]) => a.isLive())
2521
+ .map(([id]) => id);
2522
+ if (!ids.length) {
2523
+ console.log("[teapot] live update: nothing is running — no need to wait for a turn boundary");
2446
2524
  return [];
2525
+ }
2447
2526
  console.log(`[teapot] live update: waiting for ${ids.length} agent(s) to reach a turn boundary...`);
2448
2527
  const stuck = await Promise.all(ids.map(async (id) => {
2449
2528
  const a = this.agents.get(id);
@@ -2548,6 +2627,24 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2548
2627
  throw new Error("live update needs process.execve (Node 22+); restart the server by hand on this runtime");
2549
2628
  }
2550
2629
  console.log("[teapot] live update: replacing this process in place (same pid, same terminal)");
2630
+ /**
2631
+ * Give the heap back BEFORE the new image allocates its own.
2632
+ *
2633
+ * `execve` replaces the image in place, so the outgoing heap is still resident while the incoming
2634
+ * one grows. MEASURED on a long-lived server: `VmHWM` reached 1092MB after an update while the
2635
+ * steady state was 323MB, and the boot peak was visible in the status banner as
2636
+ * `602.4MB / 423.3MB`. A sandbox boot of the same 832 sessions measured only 250MB, so the extra
2637
+ * gigabyte is not the data — it is two heaps overlapping.
2638
+ *
2639
+ * `global.gc` exists only with `--expose-gc`; without it this is a cheap no-op and the peak simply
2640
+ * stays as it was, which is the old behaviour.
2641
+ */
2642
+ const gc = globalThis.gc;
2643
+ if (typeof gc === "function") {
2644
+ // twice: the first pass frees what is unreachable, the second collects what the first freed
2645
+ gc();
2646
+ gc();
2647
+ }
2551
2648
  /**
2552
2649
  * Build the argv for the replacement image.
2553
2650
  *
@@ -2561,7 +2658,7 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2561
2658
  * simply means the new image boots with node's defaults, which is what a live update wants;
2562
2659
  * anything else the operator set lives in `env` and the shell.
2563
2660
  */
2564
- const FORWARDABLE = /^--(experimental-strip-types|experimental-transform-types|no-warnings|enable-source-maps|import|require|conditions)$/;
2661
+ const FORWARDABLE = /^--(experimental-strip-types|experimental-transform-types|no-warnings|enable-source-maps|import|require|conditions|expose-gc)$/;
2565
2662
  const forwardable = process.execArgv.filter((a) => FORWARDABLE.test(a.split("=")[0] ?? ""));
2566
2663
  /**
2567
2664
  * `args[0]` MUST be the program, exactly as a shell would pass it.
@@ -1600,8 +1600,41 @@ export function buildApp(master) {
1600
1600
  }
1601
1601
  app.get("/api/agents/:id/events", async (c) => {
1602
1602
  const a = master.agents.get(c.req.param("id"));
1603
- if (!a)
1603
+ if (!a) {
1604
+ /**
1605
+ * An agent that FAILED TO LOAD still owns its history.
1606
+ *
1607
+ * `addAgent` throws for an unusable entry (no model configured, unknown provider) and boot
1608
+ * skips it, but its session directories remain on disk and `/api/sessions` lists them — so the
1609
+ * sidebar offered a timeline this endpoint answered with 404 and the UI sat on "loading
1610
+ * timeline…". MEASURED: `teapot-9` and `mediapad-t5-root-attempt` on this machine, each with a
1611
+ * 13–23MB log that could not be opened at all.
1612
+ *
1613
+ * Reading is safe: the log is an append-only file, the events are the same shape, and the
1614
+ * caller only ever renders them. The response says WHY the agent is not live so the UI can
1615
+ * explain it instead of showing a dead panel.
1616
+ */
1617
+ const why = master.unavailableAgents.get(c.req.param("id"));
1618
+ if (why) {
1619
+ const sessionQ = c.req.query("session");
1620
+ // the caller always names a session (the UI routes by internal id); fall back to the
1621
+ // newest dir this agent owns so a bare request still answers something
1622
+ const dir = sessionQ ?? master.sessionsOf(c.req.param("id"))[0]?.id;
1623
+ const file = dir ? path.join(master.sessionsRoot(), dir, "chat.jsonl") : null;
1624
+ if (file) {
1625
+ const limit = Math.min(Number(c.req.query("limit") ?? 2000), 20000);
1626
+ const tail = await readEventsTail(file, limit);
1627
+ return c.json({
1628
+ events: tail.events,
1629
+ total: tail.total,
1630
+ partial: tail.truncated,
1631
+ // the agent cannot run, but its history is readable — say so plainly
1632
+ unavailable: why,
1633
+ });
1634
+ }
1635
+ }
1604
1636
  return notFound(c, "agent", c.req.param("id"));
1637
+ }
1605
1638
  // the frontend pairs a tool_call with its tool_result by walking the
1606
1639
  // events it holds, so a window that can contain a result WITHOUT its call
1607
1640
  // strands the bash row at "waiting for output…" forever — the call scrolled
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.37.26",
3
+ "version": "0.37.28",
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",