teapot-coding-agent 0.36.7 → 0.36.9

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.
@@ -414,6 +414,19 @@ export class Agent {
414
414
  */
415
415
  pendingPrompts = [];
416
416
  stopRequested = false;
417
+ /**
418
+ * "Finish the round you are in, then stop" — a LIVE UPDATE stop.
419
+ *
420
+ * `stop()` aborts the in-flight LLM call and the running tool, which is right for an operator
421
+ * pressing ■ (they want it to stop NOW). It is wrong for a live update: aborting mid-tool leaves
422
+ * a half-written file and a call that never got its result, and the session then resumes from a
423
+ * state that never existed.
424
+ *
425
+ * Asked for as "動作中のエージェントループを適切なタイミング(ツール実行完了や生成終了などで1ターンが
426
+ * 終わる)で停止する". The loop already checks `stopRequested` at the TOP of each round, so this flag
427
+ * only has to make the loop notice at that boundary instead of being yanked out of it.
428
+ */
429
+ windDownRequested = false;
417
430
  wake = null;
418
431
  /** set while a long-parking tool (wait_children) holds the run chain */
419
432
  parkedByTool = false;
@@ -2235,7 +2248,15 @@ export class Agent {
2235
2248
  }
2236
2249
  /** Main auto-run loop: turn -> tools -> turn ... -> done/idle/stop. */
2237
2250
  async loop() {
2238
- while (!this.stopRequested) {
2251
+ /**
2252
+ * The ROUND BOUNDARY is where a live update stops this loop.
2253
+ *
2254
+ * `windDownRequested` is set by `windDownForUpdate()`; reaching here means the previous round
2255
+ * ran to completion (its tool returned, its generation finished), which is exactly the "1ターン
2256
+ * が終わる" moment the operator asked for. Nothing is aborted, so the log ends on a complete
2257
+ * round and the next process resumes from a real state.
2258
+ */
2259
+ while (!this.stopRequested && !this.windDownRequested) {
2239
2260
  try {
2240
2261
  // stop() aborted the tool signal and nothing re-armed it (only the
2241
2262
  // parkedByTool path ever did), so EVERY tool after a stop returned
@@ -4633,6 +4654,63 @@ export class Agent {
4633
4654
  await this.runChain.catch(() => { });
4634
4655
  await this.log.close();
4635
4656
  }
4657
+ /**
4658
+ * Stop at the NEXT TURN BOUNDARY, without aborting anything.
4659
+ *
4660
+ * This is the live-update stop. `dispose()`/`stop()` abort the in-flight LLM call and kill the
4661
+ * running tool, which is right for ■ but wrong for an update: a tool cut off mid-write leaves a
4662
+ * half-written file, and a call whose result never arrives means the session resumes from a state
4663
+ * that never existed.
4664
+ *
4665
+ * Asked for as "動作中のエージェントループを適切なタイミング(ツール実行完了や生成終了などで1ターン
4666
+ * が終わる)で停止する". `loop()` checks `windDownRequested` at the top of each round, so setting the
4667
+ * flag is enough for a busy agent — the round in flight finishes normally.
4668
+ *
4669
+ * A PARKED agent is the case the flag alone cannot reach: `wait_children` and a background-shell
4670
+ * wait sit in `await` with no round to finish, so they would hold the update until the timeout.
4671
+ * Those are released by waking them (the wait resolves, the loop comes round, and the flag is
4672
+ * seen at the top); nothing is killed, so the child/job keeps existing and the resumed session
4673
+ * can still reach it.
4674
+ *
4675
+ * `idle` agents are already at a boundary — their `windDownRequested` is simply set, so a prompt
4676
+ * arriving between now and the exec does not start a round that would be cut off.
4677
+ */
4678
+ async windDownForUpdate(timeoutMs) {
4679
+ this.windDownRequested = true;
4680
+ // release a parked wait (wait_children / bg-shell) so the loop can come round to the check
4681
+ this.wake?.();
4682
+ if (this.status === "idle") {
4683
+ this.status = "idle";
4684
+ this.statusReason = "paused for a live update";
4685
+ return;
4686
+ }
4687
+ /**
4688
+ * Wait for the round to end, bounded.
4689
+ *
4690
+ * `settled()` resolves when the run chain drains, which is exactly "the turn finished". The
4691
+ * timeout exists only for a wedged agent (an LLM call that never returns); the caller reports
4692
+ * which agents hit it rather than leaving them silently half-stopped.
4693
+ */
4694
+ let timer;
4695
+ try {
4696
+ await Promise.race([
4697
+ this.settled(),
4698
+ new Promise((_, reject) => {
4699
+ timer = setTimeout(() => reject(new Error(`did not reach a turn boundary within ${timeoutMs}ms`)), timeoutMs);
4700
+ }),
4701
+ ]);
4702
+ this.status = "idle";
4703
+ this.statusReason = "paused for a live update";
4704
+ }
4705
+ finally {
4706
+ if (timer)
4707
+ clearTimeout(timer);
4708
+ }
4709
+ }
4710
+ /** true once `windDownForUpdate()` has been asked and the round has ended */
4711
+ get windingDownForUpdate() {
4712
+ return this.windDownRequested;
4713
+ }
4636
4714
  /* ---------- fork / branch management (session layer) ---------- */
4637
4715
  /**
4638
4716
  * Fork the conversation: copy the message history into a fresh branch of the
package/dist/index.js CHANGED
@@ -6,79 +6,9 @@
6
6
  * First run (no config file): boot anyway and finish setup in the web UI.
7
7
  */
8
8
  import { existsSync, realpathSync } from "node:fs";
9
- import { createServer } from "node:net";
10
9
  import { fileURLToPath } from "node:url";
11
10
  import { loadConfig, resolveConfigPath, Master } from "./master.js";
12
11
  import { buildApp, serveApp } from "./server/api.js";
13
- /**
14
- * Resolve once nothing is listening on port/host, i.e. the previous server has
15
- * released it. Used only by the live-update handover: binding while the old
16
- * process still holds the socket fails with EADDRINUSE (#35).
17
- *
18
- * Returns false on timeout so the caller can warn and try anyway, rather than
19
- * hanging a boot forever because of a wedged predecessor.
20
- */
21
- async function waitForPortFree(port, host, timeoutMs) {
22
- const deadline = Date.now() + timeoutMs;
23
- // 0.0.0.0 / :: means "all interfaces" — probe the loopback the old process
24
- // was actually reachable on.
25
- const probeHost = !host || host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
26
- while (Date.now() < deadline) {
27
- const free = await new Promise((resolve) => {
28
- const s = createServer();
29
- s.once("error", () => resolve(false)); // still in use
30
- s.once("listening", () => s.close(() => resolve(true)));
31
- s.listen(port, probeHost);
32
- });
33
- if (free)
34
- return true;
35
- await new Promise((r) => setTimeout(r, 100));
36
- }
37
- return false;
38
- }
39
- /* ---------- live-update handover: keeping the operator's terminal (#35) ---------- */
40
- /** is `pid` still running? (EPERM means alive but not ours to signal) */
41
- function pidAlive(pid) {
42
- try {
43
- process.kill(pid, 0);
44
- return true;
45
- }
46
- catch (e) {
47
- return e.code === "EPERM";
48
- }
49
- }
50
- /**
51
- * Watch the replacement on the operator's behalf.
52
- *
53
- * The terminal is still wired to THIS process, so their Ctrl-C arrives here
54
- * first: forward the signal so the replacement actually stops, and leave once
55
- * it exits — otherwise the shell waits on a supervisor with nothing left to
56
- * supervise and Ctrl-C looks broken.
57
- *
58
- * shutdown() cannot be reused for this: its `shuttingDown` latch is already set
59
- * by the SIGTERM that started the handover, so a later Ctrl-C would be swallowed
60
- * and this process would never exit.
61
- */
62
- function supervise(pid) {
63
- let signalled = false;
64
- const forward = (sig) => {
65
- // Once the replacement is on its way out, stop bouncing signals: a second
66
- // SIGINT arriving during its shutdown would re-raise the same failure and
67
- // the operator would have to press Ctrl-C several times to be heard.
68
- if (signalled)
69
- return;
70
- signalled = true;
71
- try {
72
- process.kill(pid, sig);
73
- }
74
- catch {
75
- /* already gone — the poll loop below notices and exits */
76
- }
77
- };
78
- for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"])
79
- process.on(sig, () => forward(sig));
80
- }
81
- const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
82
12
  /**
83
13
  * Parse `teapot [--port N] [-p N] [--host addr] [--config file] [config.json]`.
84
14
  *
@@ -149,28 +79,15 @@ async function main() {
149
79
  if (hostOverride)
150
80
  config.host = hostOverride;
151
81
  console.log(`[teapot] config: ${configPath}${configExisted ? "" : " (not found — first run)"}`);
152
- // Live update: the process we replace still holds the port. Ask it to release
153
- // it, then WAIT until the port is genuinely free before binding. Binding
154
- // into a live socket died with EADDRINUSE, and because index.ts swallows
155
- // uncaught exceptions ("the master survived") that left two processes running
156
- // while neither served anything — the port then answered nothing at all
157
- // (measured: 1150/1237 probes refused during handover) (#35).
158
- const fromPid = process.env.TEAPOT_RESTART_FROM
159
- ? parseInt(process.env.TEAPOT_RESTART_FROM, 10)
160
- : NaN;
161
- if (!Number.isNaN(fromPid) && fromPid !== process.pid) {
162
- console.log(`[teapot] restart: releasing port from old process ${fromPid}...`);
163
- try {
164
- // Flush the old process's agents and let it release the socket. It must
165
- // NOT wait for us — that would deadlock against our bind below.
166
- process.kill(fromPid, "SIGTERM");
167
- }
168
- catch {
169
- /* already gone */
170
- }
171
- if (!(await waitForPortFree(config.port, config.host, 30_000)))
172
- console.warn(`[teapot] warning: could not confirm ${config.host}:${config.port} is free — binding anyway`);
173
- }
82
+ /**
83
+ * NO PORT HANDOVER DANCE.
84
+ *
85
+ * This used to read `TEAPOT_RESTART_FROM`, SIGTERM the predecessor and poll until the port was
86
+ * free, because the successor was a SEPARATE process racing the old one for one socket. The live
87
+ * update now replaces the process in place with `process.execve`, so the pid never changes: the
88
+ * exec releases the listener as part of replacing the image (verified) and this process is the
89
+ * only one that ever binds. The whole EADDRINUSE window #35 worked around cannot occur.
90
+ */
174
91
  const hasProviders = Object.keys(config.providers ?? {}).length > 0;
175
92
  if (!config.llm.apiKey && !hasProviders)
176
93
  console.warn("[teapot] warning: no API key configured — finish setup in the web UI");
@@ -179,6 +96,24 @@ async function main() {
179
96
  const master = new Master(config, configPath);
180
97
  master.configFileExists = configExisted;
181
98
  await master.start();
99
+ /**
100
+ * LIVE UPDATE: resume what the previous image was running.
101
+ *
102
+ * The set was written to the config by `restartServer()` immediately before the exec, because
103
+ * after a restart the log cannot tell "was working when the update hit" from "finished" or
104
+ * "stopped by the operator" — resuming every configured agent would start work nobody asked for,
105
+ * and resuming none is the bug being fixed ("サーバーを再起動して動作中だったセッションのエージェント
106
+ * ループを再開").
107
+ *
108
+ * Deliberately AFTER `start()` so the agents exist, and BEFORE the port is served so the operator
109
+ * reloading the page sees the resumed sessions already moving.
110
+ */
111
+ if (process.env.TEAPOT_RESUMED) {
112
+ delete process.env.TEAPOT_RESUMED;
113
+ const resumed = await master.resumeAfterUpdate();
114
+ if (resumed.length)
115
+ console.log(`[teapot] live update: ${resumed.length} session(s) resumed`);
116
+ }
182
117
  // ACP mode (#15): JSON-RPC over stdio, no HTTP server. Deliberately placed
183
118
  // AFTER the master is up (so config is resolved and agents work) but BEFORE
184
119
  // serveApp, so an editor launching `teapot --acp` never binds a port.
@@ -191,7 +126,9 @@ async function main() {
191
126
  return;
192
127
  }
193
128
  const app = buildApp(master);
194
- const server = serveApp(app, config.port, config.host);
129
+ // kept for the process lifetime; nothing closes it explicitly any more (the supervisor
130
+ // branch that did is gone — `process.execve` replaces the image and releases the socket)
131
+ serveApp(app, config.port, config.host);
195
132
  /**
196
133
  * Say out loud when the API has no auth, and when it is reachable beyond loopback.
197
134
  *
@@ -205,8 +142,21 @@ async function main() {
205
142
  const noAuth = !(process.env.TEAPOT_API_TOKEN || master.config.password);
206
143
  const beyondLoopback = !!config.host && config.host !== "127.0.0.1" && config.host !== "localhost";
207
144
  if (noAuth) {
208
- console.error("[teapot] no API token set — /api is open to LOCAL clients. Cross-origin writes are refused, " +
209
- "but set TEAPOT_API_TOKEN or config.password before exposing this port.");
145
+ /**
146
+ * On LOOPBACK this is the normal, safe default — so say so plainly instead of printing an
147
+ * alarming "no API token set" on every start.
148
+ *
149
+ * Asked as "no API token setはなんだろう": nothing is wrong. A fresh install has no password
150
+ * because the setup wizard has to reach the API to set one, and binding 127.0.0.1 means only
151
+ * processes on this machine can connect. The message now states that, and is written to stdout
152
+ * at info level — `console.error` made a healthy start look like a fault.
153
+ *
154
+ * The WARNING branch is unchanged and still goes to stderr: that one IS a problem.
155
+ */
156
+ if (!beyondLoopback) {
157
+ console.log("[teapot] auth: none needed — bound to loopback only, so only this machine can reach /api. " +
158
+ "Set TEAPOT_API_TOKEN or config.password before exposing this port.");
159
+ }
210
160
  if (beyondLoopback) {
211
161
  console.error(`[teapot] WARNING: bound to ${config.host} with NO auth — anyone who can reach this port can ` +
212
162
  "drive the agents. Set TEAPOT_API_TOKEN or config.password now.");
@@ -225,27 +175,21 @@ async function main() {
225
175
  if (shuttingDown)
226
176
  return;
227
177
  shuttingDown = true;
228
- // SUPERVISOR MODE. When a live update replaced us we are no longer the
229
- // server, but we are still the process the SHELL waits on and the one that
230
- // owns the terminal; exiting here dumped the operator back to the prompt
231
- // mid-session while the new server kept running in the background (#35). So
232
- // we keep the job slot, forward signals to the replacement, and leave only
233
- // once it is gone. The replacement is the child we spawned ourselves, so we
234
- // hold it directly — no pid through the environment for the two processes to
235
- // disagree over.
236
- if (master.replacementPid !== null) {
237
- const replacement = master.replacementPid;
238
- console.log(`[teapot] handing the terminal to the new server (pid ${replacement})...`);
239
- // Release the port FIRST: the replacement is blocked in waitForPortFree
240
- // waiting for exactly this, and it will SIGTERM us again if we do not go.
241
- await server.close();
242
- console.log("[teapot] port released; supervising the new server");
243
- supervise(replacement);
244
- while (pidAlive(replacement))
245
- await sleep(500);
246
- console.log("[teapot] new server exited; releasing the terminal");
247
- process.exit(0);
248
- }
178
+ /**
179
+ * THERE IS NO SUPERVISOR MODE ANY MORE — and removing it IS the memory-leak fix.
180
+ *
181
+ * The old live update spawned a successor and stayed resident as its supervisor, polling
182
+ * `pidAlive(replacement)` every 500ms for the ENTIRE lifetime of the new server. Everything
183
+ * this process owned stayed alive with it: every agent object and its log handles, every `bus`
184
+ * listener, the 15s master tick, plus three MORE signal handlers that `supervise()` added on
185
+ * top of the ones `shutdown()` had already registered. Each update therefore left another full
186
+ * copy of the server resident, which is the reported leak.
187
+ *
188
+ * `restartServer()` now replaces the image in place with `process.execve`, so there is no
189
+ * successor to supervise: the exec reuses this pid, this process group and this terminal, so
190
+ * nothing is orphaned and nothing lingers. `execve` only resolves if it FAILED, and that path
191
+ * throws inside `restartServer`, so nothing is left trusting this branch.
192
+ */
249
193
  console.log(`\n[teapot] shutting down${signal ? ` (${signal})` : ""}...`);
250
194
  await Promise.allSettled([...master.agents.values()].map((a) => a.dispose()));
251
195
  // During a live update the replacement SIGTERMs us to take the port. Linger
package/dist/master.js CHANGED
@@ -12,7 +12,6 @@ import path from "node:path";
12
12
  import os from "node:os";
13
13
  import { expandTilde } from "./home.js";
14
14
  import { fileURLToPath } from "node:url";
15
- import { spawn } from "node:child_process";
16
15
  import { Agent } from "./agent/agent.js";
17
16
  import { parseSchedule, matches, nextFireAt } from "./scheduler/cron.js";
18
17
  import { bus } from "./bus.js";
@@ -508,6 +507,18 @@ export class Master {
508
507
  this.raw.customThemes = this.config.customThemes;
509
508
  if (this.config.themePrefs !== undefined)
510
509
  this.raw.themePrefs = this.config.themePrefs;
510
+ /**
511
+ * The live-update resume set — and the reason it needs this line is the whole point of it.
512
+ *
513
+ * `resumeAfterUpdate()` CLEARS the set so a crash cannot make a later boot resume hours-old
514
+ * work. Without this mirror the clear lived only in memory, so the file kept the old set and the
515
+ * NEXT update would resume the same sessions again — MEASURED: a boot with
516
+ * `resumeAfterUpdate: ["worker"]` left the file unchanged at `["worker"]` after consuming it.
517
+ *
518
+ * Written unconditionally (not only when defined): `[]` is a meaningful value here, and skipping
519
+ * it is what kept the stale list on disk.
520
+ */
521
+ this.raw.resumeAfterUpdate = this.config.resumeAfterUpdate;
511
522
  if (this.config.shortContext !== undefined)
512
523
  this.raw.shortContext = this.config.shortContext;
513
524
  if (this.config.pluginsDir !== undefined)
@@ -2303,42 +2314,179 @@ When this task is done (or truly blocked), call finish() with a summary for @${p
2303
2314
  console.log(`[teapot] ⌨ closed ${n} terminal(s)`);
2304
2315
  }
2305
2316
  }
2306
- /** Restart the server process (spawns a new master, keeps this one alive until ready). */
2317
+ /**
2318
+ * Live update: stop at a turn boundary, write the resume set, then REPLACE THIS PROCESS IN PLACE.
2319
+ *
2320
+ * ## Why exec instead of spawning a successor
2321
+ *
2322
+ * The previous design spawned a child and kept the old process alive as its supervisor, polling
2323
+ * `pidAlive(replacement)` forever. That is the reported memory leak — and it was structural, not
2324
+ * a stray handle:
2325
+ *
2326
+ * - the OLD process stayed resident for the ENTIRE LIFETIME of the new one, holding its agent
2327
+ * objects, its log file handles, every `bus` listener and its 15s tick;
2328
+ * - `supervise()` added three MORE signal listeners (`SIGINT`/`SIGTERM`/`SIGHUP`) to a process
2329
+ * that had already registered the same three for `shutdown()`, so each update left a process
2330
+ * with doubled handlers;
2331
+ * - and the handover needed a 1.5s sleep plus a port-polling dance in the new process, because
2332
+ * two processes cannot hold one port.
2333
+ *
2334
+ * `process.execve()` (Node 26+) removes the whole category: the image is replaced under the SAME
2335
+ * pid, so the process group, the controlling terminal and therefore the operator's foreground job
2336
+ * all stay put — the daemonization problem #35 fixed by hand cannot occur. The port is released
2337
+ * as part of the exec (verified: a listener bound before `execve` is free immediately after), so
2338
+ * the successor binds with no polling and no window in which both are half-served.
2339
+ *
2340
+ * `execveSync` does not exist; this is the async form. It does not return on success.
2341
+ */
2342
+ /**
2343
+ * How long a live update waits for agents to reach a turn boundary.
2344
+ *
2345
+ * Generous: a round can be a several-minute build. The alternative to waiting is aborting a tool
2346
+ * mid-write, so the cap exists only to bound a wedged agent, and those are reported.
2347
+ */
2348
+ updateWindDownMs = 180_000;
2349
+ /**
2350
+ * Ask every agent to stop at its next turn boundary; returns the ids that did not make it.
2351
+ *
2352
+ * Distinct from `stopAllAgents` (which DISPOSES): disposal aborts in-flight work, and the whole
2353
+ * point here is to leave the log on a completed round. A live update must not truncate the turn
2354
+ * it interrupted.
2355
+ */
2356
+ async windDownAllAgents(timeoutMs = this.updateWindDownMs) {
2357
+ const ids = [...this.agents.keys()];
2358
+ if (!ids.length)
2359
+ return [];
2360
+ console.log(`[teapot] live update: waiting for ${ids.length} agent(s) to reach a turn boundary...`);
2361
+ const stuck = await Promise.all(ids.map(async (id) => {
2362
+ const a = this.agents.get(id);
2363
+ if (!a)
2364
+ return null;
2365
+ try {
2366
+ await a.windDownForUpdate(timeoutMs);
2367
+ return null;
2368
+ }
2369
+ catch {
2370
+ return id;
2371
+ }
2372
+ }));
2373
+ return stuck.filter((v) => v !== null);
2374
+ }
2375
+ /**
2376
+ * The sessions the successor must resume: everything that was WORKING at this moment.
2377
+ *
2378
+ * Captured here (not derived on boot) because after the exec the log cannot distinguish "stopped
2379
+ * by a live update mid-round" from "finished" or "stopped by the operator".
2380
+ */
2381
+ takeResumeSet() {
2382
+ const out = [];
2383
+ for (const [id, a] of this.agents) {
2384
+ // `live` covers running, parked on a tool, and needs_operator — all states where the
2385
+ // operator's mental model is "this thing is in the middle of something".
2386
+ if (a.isLive())
2387
+ out.push(id);
2388
+ }
2389
+ return out;
2390
+ }
2391
+ /**
2392
+ * Resume what the previous image was running, then FORGET the set.
2393
+ *
2394
+ * Called once at boot. Clearing it immediately means a crash before the agents start cannot make
2395
+ * the next boot resume work that has been idle for hours: the set describes one handover.
2396
+ */
2397
+ async resumeAfterUpdate() {
2398
+ const ids = this.config.resumeAfterUpdate ?? [];
2399
+ if (!ids.length)
2400
+ return [];
2401
+ this.config.resumeAfterUpdate = [];
2402
+ this.saveConfig();
2403
+ const started = [];
2404
+ for (const id of ids) {
2405
+ const a = this.agents.get(id);
2406
+ if (!a)
2407
+ continue; // the agent was removed while we were restarting
2408
+ try {
2409
+ a.start("resumed after a live update");
2410
+ started.push(id);
2411
+ }
2412
+ catch (err) {
2413
+ console.error(`[teapot] could not resume ${id}:`, err.message);
2414
+ }
2415
+ }
2416
+ const missing = ids.filter((id) => !this.agents.has(id));
2417
+ if (missing.length)
2418
+ console.log(`[teapot] live update: not resuming removed agent(s): ${missing.join(", ")}`);
2419
+ if (started.length)
2420
+ console.log(`[teapot] live update: resumed ${started.length} session(s)`);
2421
+ return started;
2422
+ }
2307
2423
  async restartServer() {
2308
- console.log("[teapot] restarting server...");
2309
- // Stop all agents first
2310
- await this.stopAllAgents(30_000);
2311
- // Spawn a new process that will become the new master
2312
- // We keep THIS process alive until the new one is ready to accept connections
2313
- const execPath = process.execPath;
2314
- const args = process.argv.slice(1);
2315
- const env = { ...process.env };
2316
- // Tell the new process it's a restart (it will read the version from the old one)
2317
- env.TEAPOT_RESTART_FROM = String(process.pid);
2318
- // Mark OURSELVES as a live-update predecessor too. Our own SIGTERM handler
2319
- // (src/index.ts) lingers when this var is set, so /api/update/restart's
2320
- // response still reaches the browser before we exit — otherwise the new
2321
- // process SIGTERMs us the instant it binds the port and the browser sees a
2322
- // dropped connection instead of {ok:true} (#35).
2323
- process.env.TEAPOT_RESTART_FROM = String(process.pid);
2324
- // #35: remember the replacement so this process can hand the operator's
2325
- // terminal over to it. Without that, the old process exited, the shell's
2326
- // foreground job ended, and the operator was dumped back at the prompt while
2327
- // the new server ran on in the background.
2328
- this.replacementPid = null; // cleared below, once the pid is known
2329
- const child = spawn(execPath, args, {
2330
- // NOT detached, and NOT stdio:"ignore" (#35). Both made the live update
2331
- // silently daemonize: the replacement inherited nothing from this
2332
- // process, so its console.log output vanished — you could not see what it
2333
- // was doing — and it outlived the terminal, so Ctrl-C and a closing
2334
- // shell could no longer stop it. Inheriting stdio keeps the logs on the
2335
- // same console and, without `detached`, the child stays in this process
2336
- // group so it receives the same Ctrl-C.
2337
- stdio: "inherit",
2338
- env,
2339
- });
2340
- this.replacementPid = child.pid ?? null;
2341
- await new Promise((r) => setTimeout(r, 1_500));
2342
- void child; // deliberately not unref()'d — see above
2424
+ console.log("[teapot] live update: restarting...");
2425
+ /**
2426
+ * 1. WIND DOWN — do not abort.
2427
+ *
2428
+ * `stopAllAgents` calls `dispose()`, which aborts the in-flight LLM call and the running tool.
2429
+ * For an operator pressing ■ that is correct; for a live update it cuts a tool off mid-write
2430
+ * and leaves a call whose result never arrives, so the resumed session starts from a state that
2431
+ * never existed. `windDownForUpdate()` instead lets each agent finish its current round.
2432
+ */
2433
+ const interrupted = await this.windDownAllAgents(this.updateWindDownMs);
2434
+ if (interrupted.length)
2435
+ console.log(`[teapot] live update: ${interrupted.length} agent(s) did not reach a turn boundary in ` +
2436
+ `time and were stopped: ${interrupted.join(", ")}`);
2437
+ /**
2438
+ * 2. REMEMBER WHAT TO RESUME.
2439
+ *
2440
+ * Written to the config BEFORE the exec, because after it this process no longer exists. Only
2441
+ * agents that were actually working go in — an idle agent must NOT be started by the new
2442
+ * process, or a live update would begin doing work the operator never asked for.
2443
+ */
2444
+ this.config.resumeAfterUpdate = this.takeResumeSet();
2445
+ this.saveConfig();
2446
+ console.log(`[teapot] live update: ${this.config.resumeAfterUpdate.length} session(s) will resume`);
2447
+ // 3. terminals: closing them is what makes their `detached` spawns safe (see stopAllAgents)
2448
+ const closed = closeAllTerminals();
2449
+ if (closed)
2450
+ console.log(`[teapot] ⌻ closed ${closed} terminal(s)`);
2451
+ /**
2452
+ * 4. EXEC.
2453
+ *
2454
+ * `TEAPOT_RESUMED` tells the new image this was a live update, so it resumes rather than
2455
+ * treating the sessions as merely idle. It also suppresses the "config was edited" banner in
2456
+ * cases where the operator did not touch anything.
2457
+ */
2458
+ const env = { ...process.env, TEAPOT_RESUMED: "1" };
2459
+ const execve = process.execve;
2460
+ if (!execve) {
2461
+ throw new Error("live update needs process.execve (Node 22+); restart the server by hand on this runtime");
2462
+ }
2463
+ console.log("[teapot] live update: replacing this process in place (same pid, same terminal)");
2464
+ /**
2465
+ * Build the argv for the replacement image.
2466
+ *
2467
+ * `process.execArgv` carries runtime flags that must precede the entry file — but under
2468
+ * `node --test` it is polluted with the RUNNER's own flags (`--test-concurrency`,
2469
+ * `--test-isolation=process`, dozens of tuning knobs). Re-passing those made the new image
2470
+ * re-enter test-runner mode instead of booting: MEASURED as
2471
+ * `src/index.ts: bad option: --config`, i.e. the new image never started.
2472
+ *
2473
+ * So only the flags that make a TypeScript entry runnable are forwarded. A flag missing here
2474
+ * simply means the new image boots with node's defaults, which is what a live update wants;
2475
+ * anything else the operator set lives in `env` and the shell.
2476
+ */
2477
+ const FORWARDABLE = /^--(experimental-strip-types|experimental-transform-types|no-warnings|enable-source-maps|import|require|conditions)$/;
2478
+ const forwardable = process.execArgv.filter((a) => FORWARDABLE.test(a.split("=")[0] ?? ""));
2479
+ /**
2480
+ * `args[0]` MUST be the program, exactly as a shell would pass it.
2481
+ *
2482
+ * `execve` does not use the `file` argument as `argv[0]` — node then reads what it thinks is
2483
+ * the first ARGUMENT as the entry point and hands the rest to its own option parser. Verified
2484
+ * in isolation: passing `[script, "--config", …]` yields `script: bad option: --config`, while
2485
+ * `[execPath, script, "--config", …]` boots. The new image would otherwise never start, leaving
2486
+ * the port dark after a live update.
2487
+ */
2488
+ await execve(process.execPath, [process.execPath, ...forwardable, ...process.argv.slice(1)], env);
2489
+ // execve only resolves if it FAILED to exec
2490
+ throw new Error("execve returned without replacing the process");
2343
2491
  }
2344
2492
  }
@@ -1665,16 +1665,37 @@ export function buildApp(master) {
1665
1665
  * needs, and it is already in hand.
1666
1666
  */
1667
1667
  const notFound = (c, what, id) => c.json({ error: `${what} not found: ${id || "(no id given)"}` }, 404);
1668
- app.get("/api/version", (c) => c.json({ version: master.getVersion() }));
1669
- // trigger a full server restart (agents stopped gracefully, new process spawned)
1670
- app.post("/api/update/restart", async (c) => {
1671
- try {
1672
- await master.restartServer();
1673
- return c.json({ ok: true });
1674
- }
1675
- catch (err) {
1676
- return c.json({ error: err.message }, 500);
1677
- }
1668
+ /**
1669
+ * `uptimeSeconds` exists so the UI can tell "the server restarted" apart from "it is still the
1670
+ * old one" even when the VERSION did not change.
1671
+ *
1672
+ * The reload after a live update used to key off `version !== __APP_VERSION__` alone. That is
1673
+ * baked into the bundle at build time, so it works for a published update — but a restart that
1674
+ * ships the same version number (a local build, or a fix released without a bump) left the client
1675
+ * polling for the full timeout while a perfectly healthy server was already answering. Process
1676
+ * uptime is the honest signal: it can only be small if the image was replaced.
1677
+ */
1678
+ app.get("/api/version", (c) => c.json({ version: master.getVersion(), uptimeSeconds: Math.round(process.uptime()) }));
1679
+ /**
1680
+ * Live update: answer FIRST, then replace the process.
1681
+ *
1682
+ * `restartServer()` ends in `process.execve`, which does not return — so awaiting it here meant
1683
+ * the response never flushed and the browser saw `SocketError: other side closed` instead of
1684
+ * `{ok:true}` (MEASURED: "restart endpoint must answer: SocketError"). The browser then could not
1685
+ * tell a successful update from a crashed one, which is exactly the state the reload logic below
1686
+ * has to distinguish.
1687
+ *
1688
+ * So the handler returns immediately and the handover runs on the next tick. That also gives the
1689
+ * pending wind-down (which can take minutes for a long build) room to finish before the image is
1690
+ * replaced.
1691
+ */
1692
+ app.post("/api/update/restart", (c) => {
1693
+ setImmediate(() => {
1694
+ void master.restartServer().catch((err) => {
1695
+ console.error("[teapot] live update failed:", err.message);
1696
+ });
1697
+ });
1698
+ return c.json({ ok: true, restarting: true });
1678
1699
  });
1679
1700
  // scheduled tasks with computed next-fire times (cron visibility for the UI)
1680
1701
  app.get("/api/tasks", (c) => c.json({ tasks: master.tasksView() }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "teapot-coding-agent",
3
- "version": "0.36.7",
3
+ "version": "0.36.9",
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",