repoburg 1.3.279 → 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);
@@ -41840,6 +41852,10 @@ function isSessionBusy(db2, session, opts) {
41840
41852
  );
41841
41853
  return false;
41842
41854
  }
41855
+ function turnResponse(db2, turnId) {
41856
+ const row = db2.prepare("SELECT agent_response FROM turns WHERE id = ?").get(turnId);
41857
+ return row?.agent_response || null;
41858
+ }
41843
41859
  function recomputeSessionRunning(db2, sessionId, idleStatus = "active", hasUnreviewed = false) {
41844
41860
  const live = db2.prepare(
41845
41861
  `SELECT COUNT(*) AS c,
@@ -42023,6 +42039,10 @@ function recoverInterruptedTurns(db2, opts) {
42023
42039
  ORDER BY t.created_at ASC`
42024
42040
  ).all();
42025
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();
42026
42046
  const items = db2.prepare("UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress'").run(now);
42027
42047
  let waiting = 0;
42028
42048
  let failed = 0;
@@ -42107,6 +42127,7 @@ var timerDue = 0;
42107
42127
  var scanning = null;
42108
42128
  var rescanDelay = null;
42109
42129
  var probeFailures = 0;
42130
+ var orphansReaped = Promise.resolve();
42110
42131
  function canResumeRuntime(runtimeType) {
42111
42132
  return hasProvider(runtimeType) && typeof getProvider(runtimeType).resumeInterruptedTurn === "function";
42112
42133
  }
@@ -42116,6 +42137,9 @@ function startAutoResume(opts = {}) {
42116
42137
  config = cfg;
42117
42138
  probe = opts.probe ?? (() => probeApi());
42118
42139
  probeFailures = 0;
42140
+ orphansReaped = reapAllOrphans().catch((err) => {
42141
+ console.error("[resume] could not clean up after the previous host:", err);
42142
+ });
42119
42143
  const summary = recoverInterruptedTurns(getDb(), { canResume: canResumeRuntime });
42120
42144
  unsubscribe = onTurnInterrupted((event) => {
42121
42145
  scheduleScan(event.reason === "network" ? cfg.networkDelayMs : cfg.delayMs);
@@ -42167,6 +42191,7 @@ async function runScan() {
42167
42191
  async function scan() {
42168
42192
  const cfg = config;
42169
42193
  if (!cfg || !cfg.enabled) return;
42194
+ await orphansReaped;
42170
42195
  const db2 = getDb();
42171
42196
  const waiting = db2.prepare(
42172
42197
  `SELECT id, session_id, interrupted_at, resume_attempts FROM turns
@@ -43604,7 +43629,7 @@ async function registerMaintenanceRoutes(fastify) {
43604
43629
  import http2 from "node:http";
43605
43630
 
43606
43631
  // src/vscode-web/manager.ts
43607
- import { spawn as spawn2 } from "node:child_process";
43632
+ import { execFile as execFile2, spawn as spawn2 } from "node:child_process";
43608
43633
  import { existsSync } from "node:fs";
43609
43634
  import http from "node:http";
43610
43635
  import net from "node:net";
@@ -43724,6 +43749,7 @@ var IDLE_CHECK_MS = 3e4;
43724
43749
  var STARTUP_TIMEOUT_MS = 9e4;
43725
43750
  var PROBE_INTERVAL_MS = 500;
43726
43751
  var SIGKILL_GRACE_MS = 5e3;
43752
+ var SHUTDOWN_GRACE_MS = 1e3;
43727
43753
  function resolveCodeCli() {
43728
43754
  const override = process.env.AGENTPANE_VSCODE_CLI;
43729
43755
  if (override) return override;
@@ -43753,11 +43779,16 @@ function defaultSpawnServeWeb(port, token, folder, id) {
43753
43779
  if (folder) args.push("--default-folder", folder);
43754
43780
  return spawn2(resolveCodeCli(), args, { stdio: ["ignore", "pipe", "pipe"], detached: true });
43755
43781
  }
43756
- function defaultProbe(port, token) {
43782
+ function isReadyStatus(status) {
43783
+ return status < 500 && status !== 403;
43784
+ }
43785
+ function defaultProbe(port, token, id) {
43757
43786
  return new Promise((resolve, reject) => {
43758
- 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) => {
43759
43788
  res.resume();
43760
- resolve();
43789
+ const status = res.statusCode ?? 500;
43790
+ if (isReadyStatus(status)) resolve();
43791
+ else reject(new Error(`serve-web answered ${status}`));
43761
43792
  });
43762
43793
  req.on("error", reject);
43763
43794
  req.setTimeout(2e3, () => {
@@ -43765,6 +43796,33 @@ function defaultProbe(port, token) {
43765
43796
  });
43766
43797
  });
43767
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
+ }
43768
43826
  function findFreePort() {
43769
43827
  return new Promise((resolve, reject) => {
43770
43828
  const server = net.createServer();
@@ -43790,6 +43848,11 @@ var VscodeWebManager = class {
43790
43848
  this.deps = deps;
43791
43849
  }
43792
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;
43793
43856
  checkTimer = null;
43794
43857
  /** Instance by id (proxy + WS upgrade lookup). */
43795
43858
  getInstance(id) {
@@ -43815,11 +43878,32 @@ var VscodeWebManager = class {
43815
43878
  this.markAccessed(id);
43816
43879
  return statusOf(existing);
43817
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);
43818
43890
  await this.evictIfNeeded();
43819
43891
  await this.spawnInstance(id, folder);
43820
43892
  this.startIdleCheck();
43821
43893
  return this.status(id);
43822
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
+ }
43823
43907
  /** Enforce the cap: stop the least-recently-accessed active instance. */
43824
43908
  async evictIfNeeded() {
43825
43909
  const active = [...this.instances.values()].filter((i) => i.state === "running" || i.state === "starting");
@@ -43891,7 +43975,7 @@ var VscodeWebManager = class {
43891
43975
  return;
43892
43976
  }
43893
43977
  try {
43894
- await this.deps.probe(inst.port, inst.token);
43978
+ await this.deps.probe(inst.port, inst.token, inst.id);
43895
43979
  clearInterval(timer2);
43896
43980
  if (inst.state === "starting") {
43897
43981
  inst.state = "running";
@@ -43914,6 +43998,17 @@ var VscodeWebManager = class {
43914
43998
  this.killChild(child, id);
43915
43999
  return { ...statusOf(inst), state: "stopped" };
43916
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
+ }
43917
44012
  /** Kill the instance's whole process tree (SIGTERM → SIGKILL after grace).
43918
44013
  * The group kill misses the code-server node child (it re-sessions itself),
43919
44014
  * so also sweep by the instance-unique --server-base-path argument. */
@@ -43925,17 +44020,15 @@ var VscodeWebManager = class {
43925
44020
  child.kill("SIGTERM");
43926
44021
  }
43927
44022
  }
43928
- this.sweepTree(id, "SIGTERM");
43929
- 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);
43930
44027
  }
43931
- /** Signal every process whose command line carries this instance's base path. */
43932
- sweepTree(id, signal) {
43933
- try {
43934
- spawn2("pkill", [signal === "SIGKILL" ? "-9" : "-TERM", "-f", `server-base-path /vscode/${id}`], {
43935
- stdio: "ignore"
43936
- });
43937
- } catch {
43938
- }
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");
43939
44032
  }
43940
44033
  /** Periodic idle check — stops instances silent past the 15-minute window. */
43941
44034
  startIdleCheck() {
@@ -43958,7 +44051,9 @@ function getVscodeWebManager() {
43958
44051
  spawnServeWeb: defaultSpawnServeWeb,
43959
44052
  probe: defaultProbe,
43960
44053
  now: () => Date.now(),
43961
- syncProfile
44054
+ syncProfile,
44055
+ sweepTree: defaultSweepTree,
44056
+ findOrphans: defaultFindOrphans
43962
44057
  });
43963
44058
  }
43964
44059
  return instance;
@@ -98487,10 +98582,15 @@ viewer; it refreshes via AgentPane.onStateChanged(cb).
98487
98582
 
98488
98583
  Headless contract for apps that declare tools:
98489
98584
  - register AgentPane.onToolCall(handler) synchronously at startup
98585
+ - the handler gets one payload, handler({ callId, name, tool, args }), the
98586
+ same as in the tab; a handler declaring two parameters still gets the
98587
+ older headless form ('tool_call', payload)
98490
98588
  - tool handlers must not depend on the DOM or the live UI
98491
- - headless state is the instance of the CALLING session's workspace
98492
- ('' = global when the caller has no known workspace); open tabs
98493
- sync via onStateChanged
98589
+ - headless state is the instance of the CALLING session's workspace; open
98590
+ tabs sync via onStateChanged. A session in a subfolder uses the workspace
98591
+ above it; one in an app folder, or with no workspace, uses the global
98592
+ instance. A path the pane does not know (unregistered, deleted) fails the
98593
+ call with "Unknown workspace", and no state is read or written
98494
98594
  - createSession/submitTurn/openSession/openUrl are not available in the
98495
98595
  headless runtime
98496
98596
  - stored files are: getFile(ref)/fileUrl(ref)/uploadFile({ name, type, data })
@@ -98499,7 +98599,8 @@ Headless contract for apps that declare tools:
98499
98599
 
98500
98600
  If the app cannot load headless (broken app.js, no handler), the pane
98501
98601
  falls back to relaying calls into the OPEN app iframe \u2014 the app must be
98502
- open in AgentPane for a tool call to succeed in that case.
98602
+ open in AgentPane, on the calling session's workspace, for a tool call to
98603
+ succeed in that case.
98503
98604
 
98504
98605
  ## Result contract
98505
98606
 
@@ -99263,7 +99364,8 @@ function getHeadlessToolHandler(appId, workspace = "") {
99263
99364
  return Promise.resolve(next);
99264
99365
  },
99265
99366
  onToolCall: (cb) => {
99266
- if (typeof cb === "function") handler = cb;
99367
+ if (typeof cb !== "function") return;
99368
+ handler = cb.length >= 2 ? (payload) => cb("tool_call", payload) : (payload) => cb(payload);
99267
99369
  },
99268
99370
  resolveToolCall: (callId, result) => {
99269
99371
  resolveHeadlessToolCall(String(callId), result);
@@ -99347,7 +99449,7 @@ function dispatchHeadlessToolCall(handler, tool, args) {
99347
99449
  pendingCalls.set(callId, { resolve, reject, timer: timer2 });
99348
99450
  });
99349
99451
  try {
99350
- handler("tool_call", { callId, tool, name: tool, args: args ?? {} });
99452
+ handler({ callId, tool, name: tool, args: args ?? {} });
99351
99453
  } catch (err) {
99352
99454
  const pending = pendingCalls.get(callId);
99353
99455
  if (pending) {
@@ -99426,12 +99528,12 @@ function dispatchAppTool(toolName, args, workspace = "") {
99426
99528
  pendingCalls2.delete(callId);
99427
99529
  reject(
99428
99530
  new Error(
99429
- `Mini app '${appId}' did not answer tool '${localName}' within ${TOOL_CALL_TIMEOUT_MS / 1e3}s \u2014 open the app in AgentPane or fix its headless load.`
99531
+ `Mini app '${appId}' did not answer tool '${localName}' within ${TOOL_CALL_TIMEOUT_MS / 1e3}s \u2014 open the app in AgentPane (${workspace ? `workspace ${workspace}` : "global instance"}) or fix its headless load.`
99430
99532
  )
99431
99533
  );
99432
99534
  }, TOOL_CALL_TIMEOUT_MS);
99433
99535
  pendingCalls2.set(callId, { resolve, reject, timer: timer2, appId });
99434
- broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {} });
99536
+ broadcast("app:tool_call", { appId, callId, tool: localName, args: args ?? {}, workspace });
99435
99537
  });
99436
99538
  return { callId, result };
99437
99539
  }
@@ -99456,8 +99558,14 @@ var FILE_UPLOAD_BODY_LIMIT = Math.ceil(APP_FILE_MAX_BYTES * 4 / 3) + 64 * 1024;
99456
99558
  var IMPORT_FILE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
99457
99559
  function resolveToolWorkspace(workspace) {
99458
99560
  if (!workspace) return "";
99459
- const row = getDb().prepare("SELECT 1 FROM workspaces WHERE path = ? AND deleted = 0").get(workspace);
99460
- return row ? workspace : "";
99561
+ const rows = getDb().prepare("SELECT path, deleted FROM workspaces").all();
99562
+ const active = rows.filter((w) => !w.deleted).map((w) => w.path);
99563
+ if (active.includes(workspace)) return workspace;
99564
+ const cwd = path7.isAbsolute(workspace) ? path7.resolve(workspace) : "";
99565
+ if (isInAppFolder(cwd)) return "";
99566
+ const covering = rows.filter((w) => cwd === w.path || cwd.startsWith(w.path + path7.sep)).sort((a, b) => b.path.length - a.path.length)[0];
99567
+ if (covering && !covering.deleted) return covering.path;
99568
+ throw new Error(`Unknown workspace: ${workspace}. Known workspaces: ${active.join(", ") || "none"}`);
99461
99569
  }
99462
99570
  var IMPORT_MAX_FILES = 50;
99463
99571
  var IMPORT_MAX_FILE_BYTES = 512 * 1024;
@@ -101323,6 +101431,7 @@ async function startTurn(session, turn) {
101323
101431
  broadcast("turn:failed", { sessionId: session.id, turnId: turn.id, error: errMsg });
101324
101432
  return;
101325
101433
  }
101434
+ const response = turnResponse(db3, turn.id);
101326
101435
  if (p.usage !== void 0) {
101327
101436
  db3.prepare("UPDATE turns SET status = ?, token_usage = ?, updated_at = ? WHERE id = ?").run(
101328
101437
  "completed",
@@ -101330,10 +101439,10 @@ async function startTurn(session, turn) {
101330
101439
  now2,
101331
101440
  turn.id
101332
101441
  );
101333
- broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, usage: p.usage, hasUnreviewed: true });
101442
+ broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, usage: p.usage, hasUnreviewed: true, response });
101334
101443
  } else {
101335
101444
  db3.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("completed", now2, turn.id);
101336
- broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, hasUnreviewed: true });
101445
+ broadcast("turn:completed", { sessionId: session.id, turnId: turn.id, hasUnreviewed: true, response });
101337
101446
  }
101338
101447
  recomputeSessionRunning(db3, session.id, "active", true);
101339
101448
  syncThreadTitle(session.id);
@@ -101843,6 +101952,64 @@ function classifyApiError({ error, status, text }) {
101843
101952
  return "fatal";
101844
101953
  }
101845
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
+
101846
102013
  // src/claude/claude-provider.ts
101847
102014
  var PromptQueue = class {
101848
102015
  buffer = [];
@@ -101890,6 +102057,7 @@ var cachedCommands = null;
101890
102057
  var thinkingAccumulator = /* @__PURE__ */ new Map();
101891
102058
  var streamingMessageIds = /* @__PURE__ */ new Map();
101892
102059
  var publishedBackgroundTasks = /* @__PURE__ */ new Map();
102060
+ var TASK_OUTCOME_WAIT_MS = 2e3;
101893
102061
  var THREAD_KEY_SEPARATOR = ":thread:";
101894
102062
  function sessionIdOfKey(key) {
101895
102063
  const i = key.indexOf(THREAD_KEY_SEPARATOR);
@@ -102048,6 +102216,7 @@ function handleLoopError(entry, sessionId, errMsg, db2) {
102048
102216
  if (!entry.turnId) return;
102049
102217
  const turnId = entry.turnId;
102050
102218
  const now = (/* @__PURE__ */ new Date()).toISOString();
102219
+ closeTaskItems(db2, sessionId, entry.threadId ?? null);
102051
102220
  const staleItems = db2.prepare(
102052
102221
  "UPDATE items SET status = 'failed', updated_at = ? WHERE status = 'in_progress' AND turn_id IN (SELECT id FROM turns WHERE session_id = ?)"
102053
102222
  ).run(now, sessionId);
@@ -102088,6 +102257,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102088
102257
  const resumeId = mapKey !== void 0 ? resumeSessionId : resumeSessionId ?? session.external_thread_id ?? void 0;
102089
102258
  const rescue = resume && resumeId ? resume : void 0;
102090
102259
  const env = spawnEnv(rescue);
102260
+ let cliPid = null;
102091
102261
  const options = {
102092
102262
  cwd: session.cwd ?? process.cwd(),
102093
102263
  model: session.model ?? void 0,
@@ -102097,7 +102267,11 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102097
102267
  ...CLI_OVERRIDE,
102098
102268
  ...session.model_reasoning_effort ? { effort: session.model_reasoning_effort } : {},
102099
102269
  ...resumeId ? { resume: resumeId } : {},
102100
- ...env ? { env } : {}
102270
+ ...env ? { env } : {},
102271
+ onProcessSpawned: (pid) => {
102272
+ cliPid = pid;
102273
+ recordCliProcess(db2, pid, session.id);
102274
+ }
102101
102275
  };
102102
102276
  const promptQueue = new PromptQueue();
102103
102277
  const q = query({ prompt: promptQueue, options });
@@ -102113,6 +102287,7 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102113
102287
  lastApiError: null
102114
102288
  };
102115
102289
  sessionMap2.set(key, entry);
102290
+ startFinishedSweep();
102116
102291
  if (rescue) {
102117
102292
  armRescueWatchdog(entry, rescueWaitMs() * 4);
102118
102293
  q.initializationResult().then(
@@ -102125,12 +102300,16 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102125
102300
  entry.messageLoop = (async () => {
102126
102301
  try {
102127
102302
  for await (const message of q) {
102303
+ trackIdle(entry, message);
102128
102304
  if (isBackgroundTasksChanged(message)) {
102129
102305
  handleBackgroundTasksChanged(message, session.id, entry);
102130
102306
  continue;
102131
102307
  }
102132
102308
  const currentTurnId = entry.turnId;
102133
- if (!currentTurnId) continue;
102309
+ if (!currentTurnId) {
102310
+ handleTaskFrame(message, session.id, entry, db2);
102311
+ continue;
102312
+ }
102134
102313
  if (entry.resume && !trackResumeFrame(entry, message, db2)) continue;
102135
102314
  await handleMessage(message, session.id, currentTurnId, entry, db2);
102136
102315
  }
@@ -102160,6 +102339,15 @@ async function ensureSessionStarted(session, mapKey, resumeSessionId, resume) {
102160
102339
  }
102161
102340
  if (sessionMap2.get(key) === entry) sessionMap2.delete(key);
102162
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
+ }
102163
102351
  }
102164
102352
  })();
102165
102353
  return entry;
@@ -102288,24 +102476,8 @@ async function handleMessage(message, sessionId, turnId, entry, db2) {
102288
102476
  entry,
102289
102477
  db2
102290
102478
  );
102291
- } else if (sub === "task_progress") {
102292
- handleTaskProgress(
102293
- message,
102294
- sessionId,
102295
- turnId,
102296
- entry,
102297
- db2
102298
- );
102299
- } else if (sub === "task_updated") {
102300
- handleTaskUpdated(message, sessionId, turnId, db2);
102301
- } else if (sub === "task_notification") {
102302
- handleTaskNotification(
102303
- message,
102304
- sessionId,
102305
- turnId,
102306
- entry,
102307
- db2
102308
- );
102479
+ } else if (sub === "task_progress" || sub === "task_updated" || sub === "task_notification") {
102480
+ handleTaskFrame(message, sessionId, entry, db2);
102309
102481
  } else if (sub === "api_retry") {
102310
102482
  const m = message;
102311
102483
  broadcast("turn:retrying", {
@@ -102526,10 +102698,31 @@ function handleTaskStarted(message, sessionId, turnId, entry, db2) {
102526
102698
  "item:started"
102527
102699
  );
102528
102700
  }
102529
- 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) {
102530
102723
  const m = message;
102531
- const row = db2.prepare("SELECT data FROM items WHERE external_item_id = ? AND turn_id = ?").get(m.task_id, turnId);
102532
- if (!row) return;
102724
+ const row = findTaskItem(db2, sessionId, m.task_id);
102725
+ if (row?.status !== "in_progress") return;
102533
102726
  const existing = row.data ? JSON.parse(row.data) : {};
102534
102727
  let output = existing.output ?? "";
102535
102728
  const taskType = existing.task_type ?? "unknown";
@@ -102555,15 +102748,15 @@ function handleTaskProgress(message, sessionId, turnId, entry, db2) {
102555
102748
  db2,
102556
102749
  { type: "background_task", data: updatedData, externalId: m.task_id },
102557
102750
  sessionId,
102558
- turnId,
102751
+ row.turn_id,
102559
102752
  "in_progress",
102560
102753
  "item:updated"
102561
102754
  );
102562
102755
  }
102563
- function handleTaskUpdated(message, sessionId, turnId, db2) {
102756
+ function handleTaskUpdated(message, sessionId, db2) {
102564
102757
  const m = message;
102565
- const row = db2.prepare("SELECT data FROM items WHERE external_item_id = ? AND turn_id = ?").get(m.task_id, turnId);
102566
- if (!row) return;
102758
+ const row = findTaskItem(db2, sessionId, m.task_id);
102759
+ if (row?.status !== "in_progress") return;
102567
102760
  const existing = row.data ? JSON.parse(row.data) : {};
102568
102761
  const updatedData = {
102569
102762
  ...existing,
@@ -102575,14 +102768,14 @@ function handleTaskUpdated(message, sessionId, turnId, db2) {
102575
102768
  db2,
102576
102769
  { type: "background_task", data: updatedData, externalId: m.task_id },
102577
102770
  sessionId,
102578
- turnId,
102771
+ row.turn_id,
102579
102772
  "in_progress",
102580
102773
  "item:updated"
102581
102774
  );
102582
102775
  }
102583
- function handleTaskNotification(message, sessionId, turnId, entry, db2) {
102776
+ function handleTaskNotification(message, sessionId, entry, db2) {
102584
102777
  const m = message;
102585
- 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);
102586
102779
  if (!row) return;
102587
102780
  const existing = row.data ? JSON.parse(row.data) : {};
102588
102781
  const taskType = existing.task_type ?? "unknown";
@@ -102607,18 +102800,51 @@ function handleTaskNotification(message, sessionId, turnId, entry, db2) {
102607
102800
  db2,
102608
102801
  { type: "background_task", data: updatedData, externalId: m.task_id },
102609
102802
  sessionId,
102610
- turnId,
102803
+ row.turn_id,
102611
102804
  itemStatus,
102612
102805
  "item:completed"
102613
102806
  );
102614
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
+ }
102615
102836
  function isBackgroundTasksChanged(message) {
102616
102837
  return message.type === "system" && "subtype" in message && message.subtype === "background_tasks_changed";
102617
102838
  }
102618
102839
  function handleBackgroundTasksChanged(message, sessionId, entry) {
102619
102840
  const m = message;
102620
- 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 }));
102621
102846
  publishBackgroundTasks(sessionId);
102847
+ if (endedIds.length > 0) closeTaskItemsSoon(sessionId, entry.threadId ?? null, endedIds);
102622
102848
  }
102623
102849
  async function handleResultMessage(message, sessionId, turnId, entry, db2) {
102624
102850
  const parentToolUseId = message.parent_tool_use_id ?? null;
@@ -102652,6 +102878,7 @@ async function handleResultMessage(message, sessionId, turnId, entry, db2) {
102652
102878
  function completeTurn(db2, sessionId, turnId, usage) {
102653
102879
  markTurnResumed(db2, turnId, { settle: true });
102654
102880
  const now = (/* @__PURE__ */ new Date()).toISOString();
102881
+ const response = turnResponse(db2, turnId);
102655
102882
  if (usage) {
102656
102883
  db2.prepare("UPDATE turns SET status = ?, token_usage = ?, updated_at = ? WHERE id = ?").run(
102657
102884
  "completed",
@@ -102659,10 +102886,10 @@ function completeTurn(db2, sessionId, turnId, usage) {
102659
102886
  now,
102660
102887
  turnId
102661
102888
  );
102662
- broadcast("turn:completed", { sessionId, turnId, usage, hasUnreviewed: true });
102889
+ broadcast("turn:completed", { sessionId, turnId, usage, hasUnreviewed: true, response });
102663
102890
  } else {
102664
102891
  db2.prepare("UPDATE turns SET status = ?, updated_at = ? WHERE id = ?").run("completed", now, turnId);
102665
- broadcast("turn:completed", { sessionId, turnId, hasUnreviewed: true });
102892
+ broadcast("turn:completed", { sessionId, turnId, hasUnreviewed: true, response });
102666
102893
  }
102667
102894
  recomputeSessionRunning(db2, sessionId, "active", true);
102668
102895
  syncThreadTitle2(sessionId);
@@ -102729,6 +102956,7 @@ async function interruptTurn2(sessionId, threadId) {
102729
102956
  broadcast("turn:cancelled", { sessionId, turnId });
102730
102957
  streamingMessageIds.delete(turnId);
102731
102958
  entry.turnId = null;
102959
+ entry.idleSince = Date.now();
102732
102960
  return true;
102733
102961
  } catch {
102734
102962
  entry.closeReason = "clear";
@@ -102809,6 +103037,52 @@ function clearAllThreads2() {
102809
103037
  sessionMap2.clear();
102810
103038
  titleGenerating2.clear();
102811
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
+ }
102812
103086
  }
102813
103087
  async function setModel(sessionId, model) {
102814
103088
  const entry = sessionMap2.get(sessionId);
@@ -102884,6 +103158,10 @@ async function shutdown2() {
102884
103158
  }
102885
103159
  clearAllThreads2();
102886
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
+ }
102887
103165
  async function resumeInterruptedTurn(session, turn, opts) {
102888
103166
  if (turn.thread_id) throw new Error("Discussion-thread turns cannot be resumed");
102889
103167
  const live = sessionMap2.get(session.id);
@@ -103043,6 +103321,7 @@ var claudeProvider = {
103043
103321
  stopTask,
103044
103322
  listBackgroundTasks,
103045
103323
  resumeInterruptedTurn,
103324
+ reapOrphans,
103046
103325
  shutdown: shutdown2
103047
103326
  };
103048
103327
 
@@ -104685,6 +104964,26 @@ async function createAgentPaneApp(dbPath) {
104685
104964
  return { fastify, wss: wss2 };
104686
104965
  }
104687
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
+
104688
104987
  // src/index.ts
104689
104988
  var PORT = Number(process.env.AGENT_PANE_PORT ?? 3003);
104690
104989
  async function main() {
@@ -104715,12 +105014,11 @@ async function main() {
104715
105014
  fastify.log.error(err);
104716
105015
  process.exit(1);
104717
105016
  }
104718
- startAutoResume();
105017
+ startHostServices();
104719
105018
  async function gracefulShutdown(signal) {
104720
105019
  fastify.log.info(`Received ${signal}, shutting down...`);
104721
- stopAutoResume();
104722
- await shutdownAllProviders();
104723
- await fastify.close();
105020
+ await shutdownHost();
105021
+ await closeServer(fastify, wss2);
104724
105022
  process.exit(0);
104725
105023
  }
104726
105024
  process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));