repoburg 1.3.280 → 1.3.281

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.
@@ -41101,6 +41101,12 @@ function createTables(database) {
41101
41101
  UNIQUE(app_id, workspace_path)
41102
41102
  );
41103
41103
 
41104
+ CREATE TABLE IF NOT EXISTS cli_processes (
41105
+ pid INTEGER PRIMARY KEY,
41106
+ session_id TEXT NOT NULL,
41107
+ created_at TEXT NOT NULL
41108
+ );
41109
+
41104
41110
  CREATE INDEX IF NOT EXISTS idx_turns_session_id ON turns(session_id);
41105
41111
  CREATE INDEX IF NOT EXISTS idx_items_turn_id ON items(turn_id);
41106
41112
  CREATE INDEX IF NOT EXISTS idx_workspaces_path ON workspaces(path);
@@ -41381,6 +41387,11 @@ function listAllBackgroundTasks() {
41381
41387
  }
41382
41388
  return bySession;
41383
41389
  }
41390
+ async function reapAllOrphans() {
41391
+ for (const provider of providers.values()) {
41392
+ await provider.reapOrphans?.();
41393
+ }
41394
+ }
41384
41395
  async function shutdownAllProviders() {
41385
41396
  for (const provider of providers.values()) {
41386
41397
  await provider.shutdown();
@@ -41497,10 +41508,11 @@ async function registerSessionRoutes(fastify) {
41497
41508
  fastify.delete("/api/sessions/:id", async (request, reply) => {
41498
41509
  const { id } = request.params;
41499
41510
  const db2 = getDb();
41500
- const existing = db2.prepare("SELECT id FROM sessions WHERE id = ?").get(id);
41511
+ const existing = db2.prepare("SELECT id, runtime_type FROM sessions WHERE id = ?").get(id);
41501
41512
  if (!existing) {
41502
41513
  return reply.code(404).send({ error: "Session not found" });
41503
41514
  }
41515
+ if (hasProvider(existing.runtime_type)) getProvider(existing.runtime_type).clearThread(id);
41504
41516
  db2.prepare("DELETE FROM items WHERE turn_id IN (SELECT id FROM turns WHERE session_id = ?)").run(id);
41505
41517
  db2.prepare("DELETE FROM turns WHERE session_id = ?").run(id);
41506
41518
  db2.prepare("DELETE FROM sessions WHERE id = ?").run(id);
@@ -42027,6 +42039,10 @@ function recoverInterruptedTurns(db2, opts) {
42027
42039
  ORDER BY t.created_at ASC`
42028
42040
  ).all();
42029
42041
  const now = (/* @__PURE__ */ new Date()).toISOString();
42042
+ db2.prepare(
42043
+ `UPDATE items SET data = json_set(COALESCE(data, '{}'), '$.status', 'stopped')
42044
+ WHERE status = 'in_progress' AND type = 'background_task' AND json_valid(COALESCE(data, '{}'))`
42045
+ ).run();
42030
42046
  const items = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress'").run(now);
42031
42047
  let waiting = 0;
42032
42048
  let failed = 0;
@@ -42111,6 +42127,7 @@ var timerDue = 0;
42111
42127
  var scanning = null;
42112
42128
  var rescanDelay = null;
42113
42129
  var probeFailures = 0;
42130
+ var orphansReaped = Promise.resolve();
42114
42131
  function canResumeRuntime(runtimeType) {
42115
42132
  return hasProvider(runtimeType) && typeof getProvider(runtimeType).resumeInterruptedTurn === "function";
42116
42133
  }
@@ -42120,6 +42137,9 @@ function startAutoResume(opts = {}) {
42120
42137
  config = cfg;
42121
42138
  probe = opts.probe ?? (() => probeApi());
42122
42139
  probeFailures = 0;
42140
+ orphansReaped = reapAllOrphans().catch((err) => {
42141
+ console.error("[resume] could not clean up after the previous host:", err);
42142
+ });
42123
42143
  const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime });
42124
42144
  unsubscribe = onTurnInterrupted((event) => {
42125
42145
  scheduleScan(event.reason === "network" ? cfg.networkDelayMs : cfg.delayMs);
@@ -42171,6 +42191,7 @@ async function runScan() {
42171
42191
  async function scan() {
42172
42192
  const cfg = config;
42173
42193
  if (!cfg || !cfg.enabled) return;
42194
+ await orphansReaped;
42174
42195
  const db2 = getDb();
42175
42196
  const waiting = db2.prepare(
42176
42197
  `SELECT id, session_id, interrupted_at, resume_attempts FROM turns
@@ -43608,7 +43629,7 @@ async function registerMaintenanceRoutes(fastify) {
43608
43629
  import http2 from "node:http";
43609
43630
 
43610
43631
  // src/vscode-web/manager.ts
43611
- import { spawn as spawn2 } from "node:child_process";
43632
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
43612
43633
  import { existsSync } from "node:fs";
43613
43634
  import http from "node:http";
43614
43635
  import net from "node:net";
@@ -43728,6 +43749,7 @@ var IDLE_CHECK_MS = 3e4;
43728
43749
  var STARTUP_TIMEOUT_MS = 9e4;
43729
43750
  var PROBE_INTERVAL_MS = 500;
43730
43751
  var SIGKILL_GRACE_MS = 5e3;
43752
+ var SHUTDOWN_GRACE_MS = 1e3;
43731
43753
  function resolveCodeCli() {
43732
43754
  const override = process.env.AGENTPANE_VSCODE_CLI;
43733
43755
  if (override) return override;
@@ -43757,11 +43779,16 @@ function defaultSpawnServeWeb(port, token, folder, id) {
43757
43779
  if (folder) args.push("--default-folder", folder);
43758
43780
  return spawn2(resolveCodeCli(), args, { stdio: ["ignore", "pipe", "pipe"], detached: true });
43759
43781
  }
43760
- function defaultProbe(port, token) {
43782
+ function isReadyStatus(status) {
43783
+ return status < 500 && status !== 403;
43784
+ }
43785
+ function defaultProbe(port, token, id) {
43761
43786
  return new Promise((resolve, reject) => {
43762
- const req = http.get(`http://127.0.0.1:${port}/vscode/?tkn=${token}`, (res) => {
43787
+ const req = http.get(`http://127.0.0.1:${port}/vscode/${id}/?tkn=${token}`, (res) => {
43763
43788
  res.resume();
43764
- resolve();
43789
+ const status = res.statusCode ?? 500;
43790
+ if (isReadyStatus(status)) resolve();
43791
+ else reject(new Error(`serve-web answered ${status}`));
43765
43792
  });
43766
43793
  req.on("error", reject);
43767
43794
  req.setTimeout(2e3, () => {
@@ -43769,6 +43796,33 @@ function defaultProbe(port, token) {
43769
43796
  });
43770
43797
  });
43771
43798
  }
43799
+ function defaultSweepTree(id, signal) {
43800
+ return new Promise((resolve) => {
43801
+ const pkill = spawn2("pkill", [signal === "SIGKILL" ? "-9" : "-TERM", "-f", `server-base-path /vscode/${id}`], {
43802
+ stdio: "ignore"
43803
+ });
43804
+ pkill.on("error", () => resolve());
43805
+ pkill.on("close", () => resolve());
43806
+ });
43807
+ }
43808
+ function parseOrphanInstanceIds(psOutput, dataDir = VSCODE_WEB_DATA_DIR) {
43809
+ const ids = /* @__PURE__ */ new Set();
43810
+ for (const line of psOutput.split("\n")) {
43811
+ const command = /^\s*1\s+(.*)$/.exec(line)?.[1];
43812
+ if (!command?.includes(" serve-web ") || !command.includes(`--server-data-dir ${dataDir}`)) continue;
43813
+ const id = /--server-base-path \/vscode\/(\S+)/.exec(command)?.[1];
43814
+ if (id) ids.add(id);
43815
+ }
43816
+ return [...ids];
43817
+ }
43818
+ function defaultFindOrphans() {
43819
+ return new Promise((resolve) => {
43820
+ const args = ["-axww", "-o", "ppid=", "-o", "command="];
43821
+ execFile2("ps", args, { maxBuffer: 32 * 1024 * 1024 }, (err, stdout) => {
43822
+ resolve(err ? [] : parseOrphanInstanceIds(stdout));
43823
+ });
43824
+ });
43825
+ }
43772
43826
  function findFreePort() {
43773
43827
  return new Promise((resolve, reject) => {
43774
43828
  const server = net.createServer();
@@ -43794,6 +43848,11 @@ var VscodeWebManager = class {
43794
43848
  this.deps = deps;
43795
43849
  }
43796
43850
  instances = /* @__PURE__ */ new Map();
43851
+ /** Starts under way, by id: a second caller joins instead of spawning again. */
43852
+ pendingStarts = /* @__PURE__ */ new Map();
43853
+ /** Delayed sweeps of stopped trees, by id. */
43854
+ sweeps = /* @__PURE__ */ new Map();
43855
+ orphanSearch = null;
43797
43856
  checkTimer = null;
43798
43857
  /** Instance by id (proxy + WS upgrade lookup). */
43799
43858
  getInstance(id) {
@@ -43819,11 +43878,32 @@ var VscodeWebManager = class {
43819
43878
  this.markAccessed(id);
43820
43879
  return statusOf(existing);
43821
43880
  }
43881
+ const pending = this.pendingStarts.get(id);
43882
+ if (pending) return pending;
43883
+ const starting = this.startInstance(id, folder).finally(() => this.pendingStarts.delete(id));
43884
+ this.pendingStarts.set(id, starting);
43885
+ return starting;
43886
+ }
43887
+ async startInstance(id, folder) {
43888
+ await this.reapOrphans();
43889
+ await this.sweeps.get(id);
43822
43890
  await this.evictIfNeeded();
43823
43891
  await this.spawnInstance(id, folder);
43824
43892
  this.startIdleCheck();
43825
43893
  return this.status(id);
43826
43894
  }
43895
+ /** Kill the instances a host that died left running. Searches once: this
43896
+ * manager's own instances must never be taken for orphans. */
43897
+ reapOrphans() {
43898
+ this.orphanSearch ??= this.deps.findOrphans().then(
43899
+ (ids) => {
43900
+ if (ids.length > 0) console.log(`[vscode-web] stopping ${ids.length} instance(s) left by the previous host`);
43901
+ for (const id of ids) this.killChild(null, id);
43902
+ },
43903
+ (err) => console.error("[vscode-web] orphan search failed:", err)
43904
+ );
43905
+ return this.orphanSearch;
43906
+ }
43827
43907
  /** Enforce the cap: stop the least-recently-accessed active instance. */
43828
43908
  async evictIfNeeded() {
43829
43909
  const active = [...this.instances.values()].filter((i) => i.state === "running" || i.state === "starting");
@@ -43895,7 +43975,7 @@ var VscodeWebManager = class {
43895
43975
  return;
43896
43976
  }
43897
43977
  try {
43898
- await this.deps.probe(inst.port, inst.token);
43978
+ await this.deps.probe(inst.port, inst.token, inst.id);
43899
43979
  clearInterval(timer2);
43900
43980
  if (inst.state === "starting") {
43901
43981
  inst.state = "running";
@@ -43918,6 +43998,17 @@ var VscodeWebManager = class {
43918
43998
  this.killChild(child, id);
43919
43999
  return { ...statusOf(inst), state: "stopped" };
43920
44000
  }
44001
+ /** Stop every instance for good and wait for their trees to die: the host is
44002
+ * going down, so a delayed sweep would never run. */
44003
+ async stopAll() {
44004
+ if (this.checkTimer) clearInterval(this.checkTimer);
44005
+ this.checkTimer = null;
44006
+ const ids = /* @__PURE__ */ new Set([...this.instances.keys(), ...this.sweeps.keys()]);
44007
+ if (ids.size === 0) return;
44008
+ await Promise.all([...this.instances.keys()].map((id) => this.stop(id)));
44009
+ await new Promise((resolve) => setTimeout(resolve, SHUTDOWN_GRACE_MS));
44010
+ await Promise.all([...ids].map((id) => this.deps.sweepTree(id, "SIGKILL")));
44011
+ }
43921
44012
  /** Kill the instance's whole process tree (SIGTERM → SIGKILL after grace).
43922
44013
  * The group kill misses the code-server node child (it re-sessions itself),
43923
44014
  * so also sweep by the instance-unique --server-base-path argument. */
@@ -43929,17 +44020,15 @@ var VscodeWebManager = class {
43929
44020
  child.kill("SIGTERM");
43930
44021
  }
43931
44022
  }
43932
- this.sweepTree(id, "SIGTERM");
43933
- setTimeout(() => this.sweepTree(id, "SIGKILL"), SIGKILL_GRACE_MS).unref();
44023
+ const sweep = this.sweep(id).finally(() => {
44024
+ if (this.sweeps.get(id) === sweep) this.sweeps.delete(id);
44025
+ });
44026
+ this.sweeps.set(id, sweep);
43934
44027
  }
43935
- /** Signal every process whose command line carries this instance's base path. */
43936
- sweepTree(id, signal) {
43937
- try {
43938
- spawn2("pkill", [signal === "SIGKILL" ? "-9" : "-TERM", "-f", `server-base-path /vscode/${id}`], {
43939
- stdio: "ignore"
43940
- });
43941
- } catch {
43942
- }
44028
+ async sweep(id) {
44029
+ await this.deps.sweepTree(id, "SIGTERM");
44030
+ await new Promise((resolve) => setTimeout(resolve, SIGKILL_GRACE_MS).unref());
44031
+ await this.deps.sweepTree(id, "SIGKILL");
43943
44032
  }
43944
44033
  /** Periodic idle check — stops instances silent past the 15-minute window. */
43945
44034
  startIdleCheck() {
@@ -43962,7 +44051,9 @@ function getVscodeWebManager() {
43962
44051
  spawnServeWeb: defaultSpawnServeWeb,
43963
44052
  probe: defaultProbe,
43964
44053
  now: () => Date.now(),
43965
- syncProfile
44054
+ syncProfile,
44055
+ sweepTree: defaultSweepTree,
44056
+ findOrphans: defaultFindOrphans
43966
44057
  });
43967
44058
  }
43968
44059
  return instance;
@@ -101861,6 +101952,64 @@ function classifyApiError({ error, status, text }) {
101861
101952
  return "fatal";
101862
101953
  }
101863
101954
 
101955
+ // src/claude/cli-orphans.ts
101956
+ import { execFile as execFile3 } from "node:child_process";
101957
+ var TERM_GRACE_MS = 2e3;
101958
+ var POLL_MS = 100;
101959
+ function inspectProcess(pid) {
101960
+ return new Promise((resolve) => {
101961
+ execFile3("ps", ["-ww", "-o", "ppid=", "-o", "command=", "-p", String(pid)], (err, stdout) => {
101962
+ const match = err ? null : /^\s*(\d+)\s+(.*)$/s.exec(stdout);
101963
+ resolve(match ? { ppid: Number(match[1]), command: match[2].trim() } : null);
101964
+ });
101965
+ });
101966
+ }
101967
+ var defaultDeps = {
101968
+ inspect: inspectProcess,
101969
+ kill: (pid, signal) => {
101970
+ try {
101971
+ process.kill(pid, signal);
101972
+ } catch {
101973
+ }
101974
+ },
101975
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms))
101976
+ };
101977
+ function isOrphanCli(info) {
101978
+ return info.ppid === 1 && info.command.includes("claude") && info.command.includes("stream-json");
101979
+ }
101980
+ async function endProcess(pid, deps) {
101981
+ deps.kill(pid, "SIGTERM");
101982
+ for (let waited = 0; waited < TERM_GRACE_MS; waited += POLL_MS) {
101983
+ await deps.sleep(POLL_MS);
101984
+ if (!await deps.inspect(pid)) return;
101985
+ }
101986
+ deps.kill(pid, "SIGKILL");
101987
+ }
101988
+ function recordCliProcess(db2, pid, sessionId) {
101989
+ db2.prepare("INSERT OR REPLACE INTO cli_processes (pid, session_id, created_at) VALUES (?, ?, ?)").run(
101990
+ pid,
101991
+ sessionId,
101992
+ (/* @__PURE__ */ new Date()).toISOString()
101993
+ );
101994
+ }
101995
+ function forgetCliProcess(db2, pid) {
101996
+ db2.prepare("DELETE FROM cli_processes WHERE pid = ?").run(pid);
101997
+ }
101998
+ async function reapOrphanCliProcesses(db2, deps = defaultDeps) {
101999
+ const rows = db2.prepare("SELECT pid FROM cli_processes").all();
102000
+ const ended = await Promise.all(
102001
+ rows.map(async ({ pid }) => {
102002
+ const info = await deps.inspect(pid);
102003
+ if (info?.ppid === process.pid) return false;
102004
+ const orphan = info !== null && isOrphanCli(info);
102005
+ if (orphan) await endProcess(pid, deps);
102006
+ forgetCliProcess(db2, pid);
102007
+ return orphan;
102008
+ })
102009
+ );
102010
+ return ended.filter(Boolean).length;
102011
+ }
102012
+
101864
102013
  // src/claude/claude-provider.ts
101865
102014
  var PromptQueue = class {
101866
102015
  buffer = [];
@@ -101908,6 +102057,7 @@ var cachedCommands = null;
101908
102057
  var thinkingAccumulator = /* @__PURE__ */ new Map();
101909
102058
  var streamingMessageIds = /* @__PURE__ */ new Map();
101910
102059
  var publishedBackgroundTasks = /* @__PURE__ */ new Map();
102060
+ var TASK_OUTCOME_WAIT_MS = 2e3;
101911
102061
  var THREAD_KEY_SEPARATOR = ":thread:";
101912
102062
  function sessionIdOfKey(key) {
101913
102063
  const i = key.indexOf(THREAD_KEY_SEPARATOR);
@@ -102066,6 +102216,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
102066
102216
  if (!entry.turnId) return;
102067
102217
  const turnId = entry.turnId;
102068
102218
  const now = (/* @__PURE__ */ new Date()).toISOString();
102219
+ closeTaskItems(db2, sessionId, entry.threadId ?? null);
102069
102220
  const staleItems = db2.prepare(
102070
102221
  "UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress' AND turn_id IN (SELECT id FROM turns WHERE session_id = ?)"
102071
102222
  ).run(now, sessionId);
@@ -102106,6 +102257,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102106
102257
  const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
102107
102258
  const rescue = resume && resumeId ? resume : void 0;
102108
102259
  const env = spawnEnv(rescue);
102260
+ let cliPid = null;
102109
102261
  const options = {
102110
102262
  cwd: session.cwd ?? process.cwd(),
102111
102263
  model: session.model ?? void 0,
@@ -102115,7 +102267,11 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102115
102267
  ...CLI_OVERRIDE,
102116
102268
  ...session.model_reasoning_effort ? { effort: session.model_reasoning_effort } : {},
102117
102269
  ...resumeId ? { resume: resumeId } : {},
102118
- ...env ? { env } : {}
102270
+ ...env ? { env } : {},
102271
+ onProcessSpawned: (pid) => {
102272
+ cliPid = pid;
102273
+ recordCliProcess(db2, pid, session.id);
102274
+ }
102119
102275
  };
102120
102276
  const promptQueue = new PromptQueue();
102121
102277
  const q = query({ prompt: promptQueue, options });
@@ -102131,6 +102287,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102131
102287
  lastApiError: null
102132
102288
  };
102133
102289
  sessionMap2.set(key, entry);
102290
+ startFinishedSweep();
102134
102291
  if (rescue) {
102135
102292
  armRescueWatchdog(entry, rescueWaitMs() * 4);
102136
102293
  q.initializationResult().then(
@@ -102143,12 +102300,16 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102143
102300
  entry.messageLoop = (async () => {
102144
102301
  try {
102145
102302
  for await (const message of q) {
102303
+ trackIdle(entry, message);
102146
102304
  if (isBackgroundTasksChanged(message)) {
102147
102305
  handleBackgroundTasksChanged(message, session.id, entry);
102148
102306
  continue;
102149
102307
  }
102150
102308
  const currentTurnId = entry.turnId;
102151
- if (!currentTurnId) continue;
102309
+ if (!currentTurnId) {
102310
+ handleTaskFrame(message, session.id, entry, db2);
102311
+ continue;
102312
+ }
102152
102313
  if (entry.resume && !trackResumeFrame(entry, message, db2)) continue;
102153
102314
  await handleMessage(message, session.id, currentTurnId, entry, db2);
102154
102315
  }
@@ -102178,6 +102339,15 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102178
102339
  }
102179
102340
  if (sessionMap2.get(key) === entry) sessionMap2.delete(key);
102180
102341
  dropBackgroundTasks(session.id, entry);
102342
+ if (entry.closeReason !== "shutdown") {
102343
+ try {
102344
+ if (cliPid !== null) forgetCliProcess(db2, cliPid);
102345
+ const taskIds = sessionMap2.has(key) ? entry.liveTaskIds ?? [] : void 0;
102346
+ closeTaskItems(db2, session.id, entry.threadId ?? null, taskIds);
102347
+ } catch (err) {
102348
+ console.error(`[claude] cleanup after CLI exit failed for session ${session.id}:`, err.message);
102349
+ }
102350
+ }
102181
102351
  }
102182
102352
  })();
102183
102353
  return entry;
@@ -102306,24 +102476,8 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
102306
102476
  entry,
102307
102477
  db2
102308
102478
  );
102309
- } else if (sub === "task_progress") {
102310
- handleTaskProgress(
102311
- message,
102312
- sessionId,
102313
- turnId,
102314
- entry,
102315
- db2
102316
- );
102317
- } else if (sub === "task_updated") {
102318
- handleTaskUpdated(message, sessionId, turnId, db2);
102319
- } else if (sub === "task_notification") {
102320
- handleTaskNotification(
102321
- message,
102322
- sessionId,
102323
- turnId,
102324
- entry,
102325
- db2
102326
- );
102479
+ } else if (sub === "task_progress" || sub === "task_updated" || sub === "task_notification") {
102480
+ handleTaskFrame(message, sessionId, entry, db2);
102327
102481
  } else if (sub === "api_retry") {
102328
102482
  const m = message;
102329
102483
  broadcast("turn:retrying", {
@@ -102544,10 +102698,31 @@ function handleTaskStarted(message, sessionId, turnId, entry, db2) {
102544
102698
  "item:started"
102545
102699
  );
102546
102700
  }
102547
- function handleTaskProgress(message, sessionId, turnId, entry, db2) {
102701
+ function findTaskItem(db2, sessionId, taskId) {
102702
+ return db2.prepare(
102703
+ `SELECT i.turn_id, i.data, i.status FROM items i JOIN turns t ON t.id = i.turn_id
102704
+ WHERE t.session_id = ? AND i.external_item_id = ? AND i.type = 'background_task'
102705
+ ORDER BY i.created_at DESC LIMIT 1`
102706
+ ).get(sessionId, taskId);
102707
+ }
102708
+ function handleTaskFrame(message, sessionId, entry, db2) {
102709
+ if (message.type !== "system") return;
102710
+ switch (message.subtype) {
102711
+ case "task_progress":
102712
+ handleTaskProgress(message, sessionId, entry, db2);
102713
+ break;
102714
+ case "task_updated":
102715
+ handleTaskUpdated(message, sessionId, db2);
102716
+ break;
102717
+ case "task_notification":
102718
+ handleTaskNotification(message, sessionId, entry, db2);
102719
+ break;
102720
+ }
102721
+ }
102722
+ function handleTaskProgress(message, sessionId, entry, db2) {
102548
102723
  const m = message;
102549
- const row = db2.prepare("SELECT data FROM items WHERE external_item_id = ? AND turn_id = ?").get(m.task_id, turnId);
102550
- if (!row) return;
102724
+ const row = findTaskItem(db2, sessionId, m.task_id);
102725
+ if (row?.status !== "in_progress") return;
102551
102726
  const existing = row.data ? JSON.parse(row.data) : {};
102552
102727
  let output = existing.output ?? "";
102553
102728
  const taskType = existing.task_type ?? "unknown";
@@ -102573,15 +102748,15 @@ function handleTaskProgress(message, sessionId, turnId, entry, db2) {
102573
102748
  db2,
102574
102749
  { type: "background_task", data: updatedData, externalId: m.task_id },
102575
102750
  sessionId,
102576
- turnId,
102751
+ row.turn_id,
102577
102752
  "in_progress",
102578
102753
  "item:updated"
102579
102754
  );
102580
102755
  }
102581
- function handleTaskUpdated(message, sessionId, turnId, db2) {
102756
+ function handleTaskUpdated(message, sessionId, db2) {
102582
102757
  const m = message;
102583
- const row = db2.prepare("SELECT data FROM items WHERE external_item_id = ? AND turn_id = ?").get(m.task_id, turnId);
102584
- if (!row) return;
102758
+ const row = findTaskItem(db2, sessionId, m.task_id);
102759
+ if (row?.status !== "in_progress") return;
102585
102760
  const existing = row.data ? JSON.parse(row.data) : {};
102586
102761
  const updatedData = {
102587
102762
  ...existing,
@@ -102593,14 +102768,14 @@ function handleTaskUpdated(message, sessionId, turnId, db2) {
102593
102768
  db2,
102594
102769
  { type: "background_task", data: updatedData, externalId: m.task_id },
102595
102770
  sessionId,
102596
- turnId,
102771
+ row.turn_id,
102597
102772
  "in_progress",
102598
102773
  "item:updated"
102599
102774
  );
102600
102775
  }
102601
- function handleTaskNotification(message, sessionId, turnId, entry, db2) {
102776
+ function handleTaskNotification(message, sessionId, entry, db2) {
102602
102777
  const m = message;
102603
- const row = db2.prepare("SELECT data FROM items WHERE external_item_id = ? AND turn_id = ?").get(m.task_id, turnId);
102778
+ const row = findTaskItem(db2, sessionId, m.task_id);
102604
102779
  if (!row) return;
102605
102780
  const existing = row.data ? JSON.parse(row.data) : {};
102606
102781
  const taskType = existing.task_type ?? "unknown";
@@ -102625,18 +102800,51 @@ function handleTaskNotification(message, sessionId, turnId, entry, db2) {
102625
102800
  db2,
102626
102801
  { type: "background_task", data: updatedData, externalId: m.task_id },
102627
102802
  sessionId,
102628
- turnId,
102803
+ row.turn_id,
102629
102804
  itemStatus,
102630
102805
  "item:completed"
102631
102806
  );
102632
102807
  }
102808
+ function closeTaskItems(db2, sessionId, threadId, taskIds) {
102809
+ const rows = db2.prepare(
102810
+ `SELECT i.turn_id, i.external_item_id, i.data FROM items i JOIN turns t ON t.id = i.turn_id
102811
+ WHERE t.session_id = ? AND t.thread_id IS ? AND i.type = 'background_task' AND i.status = 'in_progress'`
102812
+ ).all(sessionId, threadId);
102813
+ for (const row of rows) {
102814
+ if (taskIds && !taskIds.includes(row.external_item_id)) continue;
102815
+ const data = row.data ? JSON.parse(row.data) : {};
102816
+ const status = ["completed", "failed", "killed"].includes(data.status) ? data.status : "stopped";
102817
+ upsertItem(
102818
+ db2,
102819
+ { type: "background_task", data: { ...data, status }, externalId: row.external_item_id },
102820
+ sessionId,
102821
+ row.turn_id,
102822
+ status === "completed" ? "completed" : "failed",
102823
+ "item:completed"
102824
+ );
102825
+ }
102826
+ }
102827
+ function closeTaskItemsSoon(sessionId, threadId, taskIds) {
102828
+ setTimeout(() => {
102829
+ try {
102830
+ closeTaskItems(getDb(), sessionId, threadId, taskIds);
102831
+ } catch (err) {
102832
+ console.error(`[claude] could not close ended tasks of session ${sessionId}:`, err.message);
102833
+ }
102834
+ }, TASK_OUTCOME_WAIT_MS).unref?.();
102835
+ }
102633
102836
  function isBackgroundTasksChanged(message) {
102634
102837
  return message.type === "system" && "subtype" in message && message.subtype === "background_tasks_changed";
102635
102838
  }
102636
102839
  function handleBackgroundTasksChanged(message, sessionId, entry) {
102637
102840
  const m = message;
102638
- entry.backgroundTasks = (m.tasks ?? []).filter((t) => !t.ambient).map((t) => ({ task_id: t.task_id, task_type: t.task_type, description: t.description }));
102841
+ const tasks = m.tasks ?? [];
102842
+ const liveIds = tasks.map((t) => t.task_id);
102843
+ const endedIds = (entry.liveTaskIds ?? []).filter((id) => !liveIds.includes(id));
102844
+ entry.liveTaskIds = liveIds;
102845
+ entry.backgroundTasks = tasks.filter((t) => !t.ambient).map((t) => ({ task_id: t.task_id, task_type: t.task_type, description: t.description }));
102639
102846
  publishBackgroundTasks(sessionId);
102847
+ if (endedIds.length > 0) closeTaskItemsSoon(sessionId, entry.threadId ?? null, endedIds);
102640
102848
  }
102641
102849
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
102642
102850
  const parentToolUseId = message.parent_tool_use_id ?? null;
@@ -102748,6 +102956,7 @@ async function interruptTurn2(sessionId, threadId) {
102748
102956
  broadcast("turn:cancelled", { sessionId, turnId });
102749
102957
  streamingMessageIds.delete(turnId);
102750
102958
  entry.turnId = null;
102959
+ entry.idleSince = Date.now();
102751
102960
  return true;
102752
102961
  } catch {
102753
102962
  entry.closeReason = "clear";
@@ -102828,6 +103037,52 @@ function clearAllThreads2() {
102828
103037
  sessionMap2.clear();
102829
103038
  titleGenerating2.clear();
102830
103039
  for (const sessionId of [...publishedBackgroundTasks.keys()]) publishBackgroundTasks(sessionId);
103040
+ if (finishedSweepTimer) clearInterval(finishedSweepTimer);
103041
+ finishedSweepTimer = null;
103042
+ closableSince.clear();
103043
+ }
103044
+ var FINISHED_CLOSE_MS = 5 * 6e4;
103045
+ var FINISHED_SWEEP_MS = 3e4;
103046
+ var closableSince = /* @__PURE__ */ new Map();
103047
+ var finishedSweepTimer = null;
103048
+ function startFinishedSweep() {
103049
+ if (finishedSweepTimer) return;
103050
+ finishedSweepTimer = setInterval(() => sweepFinishedSessions(), FINISHED_SWEEP_MS);
103051
+ finishedSweepTimer.unref?.();
103052
+ }
103053
+ function trackIdle(entry, message) {
103054
+ if (isModelFrame(message)) {
103055
+ entry.idleSince = null;
103056
+ } else if (message.type === "result" && !message.parent_tool_use_id) {
103057
+ entry.idleSince = Date.now();
103058
+ }
103059
+ }
103060
+ function sweepFinishedSessions(now = Date.now()) {
103061
+ try {
103062
+ const db2 = getDb();
103063
+ const sessionIds = new Set([...sessionMap2.keys()].map(sessionIdOfKey));
103064
+ for (const id of closableSince.keys()) {
103065
+ if (!sessionIds.has(id)) closableSince.delete(id);
103066
+ }
103067
+ for (const id of sessionIds) {
103068
+ const session = db2.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
103069
+ const entries = [...sessionMap2].filter(([key]) => sessionIdOfKey(key) === id).map(([, entry]) => entry);
103070
+ const closable = session?.lifecycle === "finished" && !isSessionBusy(db2, session) && sessionBackgroundTasks(id).length === 0 && entries.every((entry) => !entry.resume && entry.idleSince !== null);
103071
+ if (!closable) {
103072
+ closableSince.delete(id);
103073
+ continue;
103074
+ }
103075
+ if (!closableSince.has(id)) closableSince.set(id, now);
103076
+ const since = Math.max(closableSince.get(id), ...entries.map((entry) => entry.idleSince ?? 0));
103077
+ if (now - since >= FINISHED_CLOSE_MS) {
103078
+ console.log(`[claude] closing the CLI of finished session ${id}`);
103079
+ closableSince.delete(id);
103080
+ clearThread2(id);
103081
+ }
103082
+ }
103083
+ } catch (err) {
103084
+ console.error("[claude] finished-session sweep failed:", err.message);
103085
+ }
102831
103086
  }
102832
103087
  async function setModel(sessionId, model) {
102833
103088
  const entry = sessionMap2.get(sessionId);
@@ -102903,6 +103158,10 @@ async function shutdown2() {
102903
103158
  }
102904
103159
  clearAllThreads2();
102905
103160
  }
103161
+ async function reapOrphans() {
103162
+ const ended = await reapOrphanCliProcesses(getDb());
103163
+ if (ended > 0) console.log(`[claude] ended ${ended} CLI process(es) left by the previous host`);
103164
+ }
102906
103165
  async function resumeInterruptedTurn(session, turn, opts) {
102907
103166
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
102908
103167
  const live = sessionMap2.get(session.id);
@@ -103062,6 +103321,7 @@ var claudeProvider = {
103062
103321
  stopTask,
103063
103322
  listBackgroundTasks,
103064
103323
  resumeInterruptedTurn,
103324
+ reapOrphans,
103065
103325
  shutdown: shutdown2
103066
103326
  };
103067
103327
 
@@ -104704,6 +104964,26 @@ async function createAgentPaneApp(dbPath) {
104704
104964
  return { fastify, wss: wss2 };
104705
104965
  }
104706
104966
 
104967
+ // src/host-lifecycle.ts
104968
+ var CLOSE_TIMEOUT_MS = 3e3;
104969
+ function startHostServices() {
104970
+ startAutoResume();
104971
+ void getVscodeWebManager().reapOrphans();
104972
+ }
104973
+ async function shutdownHost() {
104974
+ stopAutoResume();
104975
+ await shutdownAllProviders();
104976
+ await getVscodeWebManager().stopAll();
104977
+ }
104978
+ async function closeServer(fastify, wss2, timeoutMs = CLOSE_TIMEOUT_MS) {
104979
+ for (const client of wss2.clients) client.terminate();
104980
+ await Promise.race([
104981
+ fastify.close(),
104982
+ // Covers what `wss` does not own, like proxied /vscode sockets.
104983
+ new Promise((resolve) => setTimeout(resolve, timeoutMs).unref())
104984
+ ]);
104985
+ }
104986
+
104707
104987
  // src/index.ts
104708
104988
  var PORT = Number(process.env.AGENT_PANE_PORT ?? 3003);
104709
104989
  async function main() {
@@ -104734,12 +105014,11 @@ async function main() {
104734
105014
  fastify.log.error(err);
104735
105015
  process.exit(1);
104736
105016
  }
104737
- startAutoResume();
105017
+ startHostServices();
104738
105018
  async function gracefulShutdown(signal) {
104739
105019
  fastify.log.info(`Received ${signal}, shutting down...`);
104740
- stopAutoResume();
104741
- await shutdownAllProviders();
104742
- await fastify.close();
105020
+ await shutdownHost();
105021
+ await closeServer(fastify, wss2);
104743
105022
  process.exit(0);
104744
105023
  }
104745
105024
  process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));