@bastani/atomic-acp 0.0.5 → 0.0.7

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.
package/dist/index.js CHANGED
@@ -140,10 +140,10 @@ function requestExtensionDialog(conn, sessionId, ev, form, signal, onClientCanno
140
140
  cancelled: true
141
141
  };
142
142
  if (signal?.aborted) return Promise.resolve(cancelled);
143
- return new Promise((resolve3) => {
143
+ return new Promise((resolve2) => {
144
144
  const finish = (response) => {
145
145
  signal?.removeEventListener("abort", abort);
146
- resolve3(response);
146
+ resolve2(response);
147
147
  };
148
148
  const abort = () => finish(cancelled);
149
149
  signal?.addEventListener("abort", abort, { once: true });
@@ -242,7 +242,7 @@ function maybeAuthRequiredError(err) {
242
242
  }
243
243
 
244
244
  // src/acp/session.ts
245
- import { readFileSync as readFileSync4 } from "fs";
245
+ import { readFileSync as readFileSync3 } from "fs";
246
246
  import { isAbsolute, resolve as resolvePath } from "path";
247
247
 
248
248
  // src/atomic-rpc/process.ts
@@ -270,6 +270,11 @@ var RESERVED_ATOMIC_ARGS = /* @__PURE__ */ new Set([
270
270
  "--session",
271
271
  "--session-id",
272
272
  "--session-dir",
273
+ "--session-store",
274
+ "--session-prefix",
275
+ "--import",
276
+ "--storage",
277
+ "--storage-file",
273
278
  "--no-session",
274
279
  "-c",
275
280
  "--continue",
@@ -338,7 +343,7 @@ async function removeDir(dir, cleanup) {
338
343
  const delay = delays[attempt];
339
344
  const code = error?.code;
340
345
  if (delay === void 0 || code === void 0 || !RETRYABLE_RM_CODES.has(code)) return;
341
- await new Promise((resolve3) => setTimeout(resolve3, delay));
346
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
342
347
  }
343
348
  }
344
349
  }
@@ -453,7 +458,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
453
458
  constructor(child, adapterExtension) {
454
459
  this.child = child;
455
460
  this.adapterExtension = adapterExtension;
456
- this.exited = new Promise((resolve3) => child.once("exit", () => resolve3()));
461
+ this.exited = new Promise((resolve2) => child.once("exit", () => resolve2()));
457
462
  let stdoutBuffer = "";
458
463
  child.stdout.setEncoding("utf8");
459
464
  child.stdout.on("data", (chunk) => {
@@ -495,7 +500,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
495
500
  throw new AtomicRpcSpawnError(`Could not start Atomic: ${e.message}`, { cause: e });
496
501
  }
497
502
  const args = ["--mode", "rpc", "--no-themes"];
498
- if (params.sessionPath) args.push("--session", params.sessionPath);
503
+ if (params.sessionId !== void 0) args.push("--session", params.sessionId);
499
504
  const adapterExtension = writeAdapterExtension({
500
505
  mcpServers: params.mcpServers,
501
506
  ...params.headless ? { askUserQuestionUnavailable: NO_PERSON_FOR_ASK_USER_QUESTION } : {}
@@ -516,10 +521,10 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
516
521
  throw e;
517
522
  }
518
523
  try {
519
- await new Promise((resolve3, reject) => {
524
+ await new Promise((resolve2, reject) => {
520
525
  const onSpawn = () => {
521
526
  cleanup();
522
- resolve3();
527
+ resolve2();
523
528
  };
524
529
  const onError = (err) => {
525
530
  cleanup();
@@ -553,13 +558,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
553
558
  });
554
559
  const proc = new _AtomicRpcProcess(child, adapterExtension);
555
560
  try {
556
- const state = await proc.getState();
557
- const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
558
- if (sessionFile) {
559
- const { mkdirSync: mkdirSync2 } = await import("fs");
560
- const { dirname: dirname3 } = await import("path");
561
- mkdirSync2(dirname3(sessionFile), { recursive: true });
562
- }
561
+ await proc.getState();
563
562
  } catch {
564
563
  }
565
564
  return proc;
@@ -600,8 +599,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
600
599
  let timer;
601
600
  await Promise.race([
602
601
  this.exited,
603
- new Promise((resolve3) => {
604
- timer = setTimeout(resolve3, DISPOSE_EXIT_WAIT_MS);
602
+ new Promise((resolve2) => {
603
+ timer = setTimeout(resolve2, DISPOSE_EXIT_WAIT_MS);
605
604
  timer.unref?.();
606
605
  })
607
606
  ]);
@@ -697,9 +696,25 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
697
696
  const data = res.data;
698
697
  return { path: String(data?.path ?? "") };
699
698
  }
700
- async switchSession(sessionPath) {
701
- const res = await this.request({ type: "switch_session", sessionPath });
702
- if (!res.success) throw new Error(`Atomic switch_session failed: ${res.error ?? JSON.stringify(res.data)}`);
699
+ /** Saved sessions of the current project, as Atomic's session store lists them. */
700
+ async listSessions() {
701
+ const res = await this.request({ type: "list_sessions" });
702
+ if (!res.success) throw new Error(`Atomic list_sessions failed: ${res.error ?? JSON.stringify(res.data)}`);
703
+ return res.data;
704
+ }
705
+ /** Delete a saved session from Atomic's session store. Atomic refuses to delete its own open session. */
706
+ async deleteSession(sessionId) {
707
+ const res = await this.request({ type: "delete_session", sessionId });
708
+ if (!res.success) throw new Error(`Atomic delete_session failed: ${res.error ?? JSON.stringify(res.data)}`);
709
+ }
710
+ /**
711
+ * Recover work an earlier Atomic left unfinished in the open session: replay interrupted deliveries
712
+ * in a turn that streams as usual. Since 0.9.40 Atomic does this only when asked, once the transcript is shown.
713
+ */
714
+ async startPendingRecovery(reason) {
715
+ const res = await this.request({ type: "start_pending_recovery", reason });
716
+ if (!res.success) throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
717
+ return res.data;
703
718
  }
704
719
  async getMessages() {
705
720
  const res = await this.request({ type: "get_messages" });
@@ -713,11 +728,11 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
713
728
  }
714
729
  writeJsonLine(value) {
715
730
  const line = JSON.stringify(value) + "\n";
716
- return new Promise((resolve3, reject) => {
731
+ return new Promise((resolve2, reject) => {
717
732
  try {
718
733
  this.child.stdin.write(line, (err) => {
719
734
  if (err) reject(err);
720
- else resolve3();
735
+ else resolve2();
721
736
  });
722
737
  } catch (e) {
723
738
  reject(e);
@@ -740,7 +755,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
740
755
  const id = crypto.randomUUID();
741
756
  const withId = { ...cmd, id };
742
757
  const timeoutMs = opts?.timeoutMs;
743
- return new Promise((resolve3, reject) => {
758
+ return new Promise((resolve2, reject) => {
744
759
  let timer;
745
760
  const drop = () => {
746
761
  if (timer !== void 0) {
@@ -752,7 +767,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
752
767
  this.pending.set(id, {
753
768
  resolve: (res) => {
754
769
  drop();
755
- resolve3(res);
770
+ resolve2(res);
756
771
  },
757
772
  reject: (error) => {
758
773
  drop();
@@ -775,67 +790,6 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
775
790
  }
776
791
  };
777
792
 
778
- // src/acp/session-store.ts
779
- import { mkdirSync, readFileSync, writeFileSync as writeFileSync2 } from "fs";
780
- import { dirname } from "path";
781
-
782
- // src/acp/paths.ts
783
- import { homedir } from "os";
784
- import { join as join2 } from "path";
785
- function getAtomicAcpDir() {
786
- return join2(homedir(), ".atomic", "atomic-acp");
787
- }
788
- function getAtomicAcpSessionMapPath() {
789
- return join2(getAtomicAcpDir(), "session-map.json");
790
- }
791
-
792
- // src/acp/session-store.ts
793
- function ensureParentDir(path) {
794
- mkdirSync(dirname(path), { recursive: true });
795
- }
796
- function loadFile(path) {
797
- try {
798
- const raw = readFileSync(path, "utf-8");
799
- const parsed = JSON.parse(raw);
800
- if (parsed?.version !== 1 || typeof parsed.sessions !== "object" || !parsed.sessions) {
801
- return { version: 1, sessions: {} };
802
- }
803
- return parsed;
804
- } catch {
805
- return { version: 1, sessions: {} };
806
- }
807
- }
808
- function saveFile(path, data) {
809
- ensureParentDir(path);
810
- writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
811
- }
812
- var SessionStore = class {
813
- path;
814
- constructor(path = getAtomicAcpSessionMapPath()) {
815
- this.path = path;
816
- }
817
- get(sessionId) {
818
- const db = loadFile(this.path);
819
- return db.sessions[sessionId] ?? null;
820
- }
821
- upsert(entry) {
822
- const db = loadFile(this.path);
823
- db.sessions[entry.sessionId] = {
824
- sessionId: entry.sessionId,
825
- cwd: entry.cwd,
826
- sessionFile: entry.sessionFile,
827
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
828
- };
829
- saveFile(this.path, db);
830
- }
831
- delete(sessionId) {
832
- const db = loadFile(this.path);
833
- if (!db.sessions[sessionId]) return;
834
- delete db.sessions[sessionId];
835
- saveFile(this.path, db);
836
- }
837
- };
838
-
839
793
  // src/acp/translate/atomic-tools.ts
840
794
  function toolResultToText(result) {
841
795
  if (!result) return "";
@@ -866,13 +820,13 @@ ${stderr}`);
866
820
  }
867
821
 
868
822
  // src/acp/slash-commands.ts
869
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync3, statSync } from "fs";
870
- import { basename, join as join4 } from "path";
823
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
824
+ import { basename, join as join3 } from "path";
871
825
 
872
826
  // src/acp/atomic-settings.ts
873
- import { existsSync, readFileSync as readFileSync2 } from "fs";
874
- import { homedir as homedir2 } from "os";
875
- import { join as join3, resolve } from "path";
827
+ import { existsSync, readFileSync } from "fs";
828
+ import { homedir } from "os";
829
+ import { join as join2, resolve } from "path";
876
830
  function isObject(x) {
877
831
  return Boolean(x) && typeof x === "object" && !Array.isArray(x);
878
832
  }
@@ -888,7 +842,7 @@ function deepMerge(a, b) {
888
842
  function readJsonFile(path) {
889
843
  try {
890
844
  if (!existsSync(path)) return {};
891
- const raw = readFileSync2(path, "utf-8");
845
+ const raw = readFileSync(path, "utf-8");
892
846
  const data = JSON.parse(raw.replace(/^\uFEFF/, ""));
893
847
  return isObject(data) ? data : {};
894
848
  } catch {
@@ -919,12 +873,12 @@ function getSettingsWithLocations(cwd) {
919
873
  {
920
874
  location: "user",
921
875
  baseDirs: agentDirs,
922
- settings: readMergedJsonFiles(agentDirs.map((dir) => join3(dir, "settings.json")))
876
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
923
877
  },
924
878
  {
925
879
  location: "project",
926
880
  baseDirs: projectDirs,
927
- settings: readMergedJsonFiles(projectDirs.map((dir) => join3(dir, "settings.json")))
881
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
928
882
  }
929
883
  ];
930
884
  }
@@ -933,8 +887,8 @@ function getMergedSettings(cwd) {
933
887
  return deepMerge(settings[0].settings, settings[1].settings);
934
888
  }
935
889
  function expandHomePath(value) {
936
- if (value === "~") return homedir2();
937
- if (value.startsWith("~/")) return join3(homedir2(), value.slice(2));
890
+ if (value === "~") return homedir();
891
+ if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
938
892
  return value;
939
893
  }
940
894
  function resolveAtomicPath(value, relativeBase = process.cwd()) {
@@ -954,12 +908,12 @@ function readMergedResourceSettings(cwd) {
954
908
  }
955
909
  function getAgentDir() {
956
910
  const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
957
- return override ? resolveAtomicPath(override) : join3(homedir2(), ".atomic", "agent");
911
+ return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
958
912
  }
959
913
  function getAgentDirs() {
960
914
  const primary = getAgentDir();
961
915
  if (hasAgentDirOverride()) return [primary];
962
- const legacy = join3(homedir2(), ".pi", "agent");
916
+ const legacy = join2(homedir(), ".pi", "agent");
963
917
  return legacy === primary ? [primary] : [primary, legacy];
964
918
  }
965
919
  function getProjectConfigDirs(cwd) {
@@ -1010,7 +964,7 @@ function describeContent(content, frontmatter, sourceStr) {
1010
964
  }
1011
965
  function loadCommandFromFile(path, sourceStr, name = basename(path, ".md")) {
1012
966
  try {
1013
- const rawContent = readFileSync3(path, "utf-8");
967
+ const rawContent = readFileSync2(path, "utf-8");
1014
968
  const { frontmatter, content } = parseFrontmatter(rawContent);
1015
969
  return {
1016
970
  name,
@@ -1030,7 +984,7 @@ function loadCommandsFromDir(dir, source, subdir = "") {
1030
984
  const entries = readdirSync(dir, { withFileTypes: true });
1031
985
  for (const entry of entries) {
1032
986
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
1033
- const fullPath = join4(dir, entry.name);
987
+ const fullPath = join3(dir, entry.name);
1034
988
  const sourceStr = source === "path" ? "(path)" : source === "user" ? subdir ? `(user:${subdir})` : "(user)" : subdir ? `(project:${subdir})` : "(project)";
1035
989
  const command = loadCommandFromFile(fullPath, sourceStr);
1036
990
  if (command) commands.push(command);
@@ -1081,8 +1035,8 @@ function loadSlashCommands(cwd) {
1081
1035
  commands.push(...loadCommandsFromSettingPath(resolved, entry.location));
1082
1036
  }
1083
1037
  }
1084
- const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join4(configDir, "prompts"));
1085
- const userDirs = getAgentDirs().map((agentDir) => join4(agentDir, "prompts"));
1038
+ const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join3(configDir, "prompts"));
1039
+ const userDirs = getAgentDirs().map((agentDir) => join3(agentDir, "prompts"));
1086
1040
  for (const projectDir of projectDirs) commands.push(...loadCommandsFromDir(projectDir, "project"));
1087
1041
  for (const userDir of userDirs) commands.push(...loadCommandsFromDir(userDir, "user"));
1088
1042
  return filterExcluded(commands, excludedPaths);
@@ -1342,7 +1296,6 @@ function toToolCallLocations(args, cwd, line) {
1342
1296
  }
1343
1297
  var SessionManager = class {
1344
1298
  sessions = /* @__PURE__ */ new Map();
1345
- store = new SessionStore();
1346
1299
  /** Dispose all sessions and their underlying Atomic subprocesses. */
1347
1300
  disposeAll() {
1348
1301
  for (const [id] of this.sessions) this.close(id);
@@ -1351,18 +1304,27 @@ var SessionManager = class {
1351
1304
  maybeGet(sessionId) {
1352
1305
  return this.sessions.get(sessionId);
1353
1306
  }
1307
+ /** A registered session for `cwd`, other than `exceptSessionId`, whose Atomic is still running. */
1308
+ findLive(cwd, exceptSessionId) {
1309
+ for (const session of this.sessions.values()) {
1310
+ if (session.cwd === cwd && session.sessionId !== exceptSessionId && !session.proc.hasExited) return session;
1311
+ }
1312
+ return void 0;
1313
+ }
1354
1314
  /**
1355
1315
  * Dispose a session's underlying Atomic process and remove it from the manager.
1356
1316
  * Used when clients explicitly reload a session and we want a fresh Atomic subprocess.
1357
1317
  */
1358
1318
  close(sessionId) {
1359
1319
  const s = this.sessions.get(sessionId);
1360
- if (!s) return;
1320
+ if (!s) return Promise.resolve();
1321
+ this.sessions.delete(sessionId);
1361
1322
  try {
1362
- s.proc.dispose?.();
1323
+ return Promise.resolve(s.proc.dispose?.()).catch(() => {
1324
+ });
1363
1325
  } catch {
1326
+ return Promise.resolve();
1364
1327
  }
1365
- this.sessions.delete(sessionId);
1366
1328
  }
1367
1329
  /** Close all sessions except the one with `keepSessionId`. */
1368
1330
  closeAllExcept(keepSessionId) {
@@ -1393,10 +1355,6 @@ var SessionManager = class {
1393
1355
  state = null;
1394
1356
  }
1395
1357
  const sessionId = typeof state?.sessionId === "string" ? state.sessionId : crypto.randomUUID();
1396
- const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
1397
- if (sessionFile) {
1398
- this.store.upsert({ sessionId, cwd: params.cwd, sessionFile });
1399
- }
1400
1358
  const session = new AtomicAcpSession({
1401
1359
  sessionId,
1402
1360
  cwd: params.cwd,
@@ -1522,8 +1480,8 @@ var AtomicAcpSession = class {
1522
1480
  async prompt(message, images = [], title) {
1523
1481
  this.sendStartupInfoOnFirstPromptIfPending();
1524
1482
  const expandedMessage = expandSlashCommand(message, this.fileCommands);
1525
- const turnPromise = new Promise((resolve3, reject) => {
1526
- const queued = { message: expandedMessage, images, title, resolve: resolve3, reject };
1483
+ const turnPromise = new Promise((resolve2, reject) => {
1484
+ const queued = { message: expandedMessage, images, title, resolve: resolve2, reject };
1527
1485
  if (this.pendingTurn) {
1528
1486
  this.turnQueue.push(queued);
1529
1487
  this.emit({
@@ -2074,7 +2032,7 @@ var AtomicAcpSession = class {
2074
2032
  this.fileMutationToolCallIds.add(toolCallId);
2075
2033
  const snapshots = getMutationPaths(args).map((path) => {
2076
2034
  try {
2077
- const oldText = readFileSync4(resolvePath(this.cwd, path), "utf8");
2035
+ const oldText = readFileSync3(resolvePath(this.cwd, path), "utf8");
2078
2036
  if (typeof args?.oldText === "string") line = findUniqueLineNumber(oldText, args.oldText);
2079
2037
  return { path, oldText };
2080
2038
  } catch (error) {
@@ -2146,7 +2104,7 @@ var AtomicAcpSession = class {
2146
2104
  for (const snapshot of snapshots) {
2147
2105
  try {
2148
2106
  const path = resolvePath(this.cwd, snapshot.path);
2149
- const newText = readFileSync4(path, "utf8");
2107
+ const newText = readFileSync3(path, "utf8");
2150
2108
  if (newText !== snapshot.oldText) {
2151
2109
  content ??= [];
2152
2110
  content.push({ type: "diff", path, oldText: snapshot.oldText, newText });
@@ -2273,15 +2231,76 @@ function toToolKind(toolName) {
2273
2231
  }
2274
2232
  }
2275
2233
 
2234
+ // src/acp/session-store.ts
2235
+ import { mkdirSync, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
2236
+ import { dirname } from "path";
2237
+
2238
+ // src/acp/paths.ts
2239
+ import { homedir as homedir2 } from "os";
2240
+ import { join as join4 } from "path";
2241
+ function getAtomicAcpDir() {
2242
+ return join4(homedir2(), ".atomic", "atomic-acp");
2243
+ }
2244
+ function getAtomicAcpSessionMapPath() {
2245
+ return join4(getAtomicAcpDir(), "session-map.json");
2246
+ }
2247
+
2248
+ // src/acp/session-store.ts
2249
+ function ensureParentDir(path) {
2250
+ mkdirSync(dirname(path), { recursive: true });
2251
+ }
2252
+ function loadFile(path) {
2253
+ try {
2254
+ const raw = readFileSync4(path, "utf-8");
2255
+ const parsed = JSON.parse(raw);
2256
+ if (parsed?.version !== 1 || typeof parsed.sessions !== "object" || !parsed.sessions) {
2257
+ return { version: 1, sessions: {} };
2258
+ }
2259
+ return parsed;
2260
+ } catch {
2261
+ return { version: 1, sessions: {} };
2262
+ }
2263
+ }
2264
+ function saveFile(path, data) {
2265
+ ensureParentDir(path);
2266
+ writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
2267
+ }
2268
+ var SessionStore = class {
2269
+ path;
2270
+ constructor(path = getAtomicAcpSessionMapPath()) {
2271
+ this.path = path;
2272
+ }
2273
+ get(sessionId) {
2274
+ const db = loadFile(this.path);
2275
+ return db.sessions[sessionId] ?? null;
2276
+ }
2277
+ upsert(entry) {
2278
+ this.upsertMany([entry]);
2279
+ }
2280
+ /** Record which project each session belongs to; the map is rewritten only when an entry changes. */
2281
+ upsertMany(entries) {
2282
+ const db = loadFile(this.path);
2283
+ let changed = false;
2284
+ for (const { sessionId, cwd } of entries) {
2285
+ if (db.sessions[sessionId]?.cwd === cwd) continue;
2286
+ db.sessions[sessionId] = { sessionId, cwd, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2287
+ changed = true;
2288
+ }
2289
+ if (changed) saveFile(this.path, db);
2290
+ }
2291
+ delete(sessionId) {
2292
+ const db = loadFile(this.path);
2293
+ if (!db.sessions[sessionId]) return;
2294
+ delete db.sessions[sessionId];
2295
+ saveFile(this.path, db);
2296
+ }
2297
+ };
2298
+
2276
2299
  // src/acp/headless.ts
2277
2300
  function isHeadlessFromEnv(env = process.env) {
2278
2301
  return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
2279
2302
  }
2280
2303
 
2281
- // src/acp/atomic-sessions.ts
2282
- import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2, openSync, readSync, closeSync, existsSync as existsSync3 } from "fs";
2283
- import { join as join5, resolve as resolve2 } from "path";
2284
-
2285
2304
  // src/acp/translate/prompt.ts
2286
2305
  function promptToSessionTitle(blocks) {
2287
2306
  const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
@@ -2340,256 +2359,34 @@ ${r.text}`;
2340
2359
  }
2341
2360
 
2342
2361
  // src/acp/atomic-sessions.ts
2343
- var DEFAULT_TAIL_BYTES = 256 * 1024;
2344
- var DEFAULT_HEAD_BYTES = 64 * 1024;
2345
- function readSessionDirFromSettings(settingsPaths, cwd) {
2346
- try {
2347
- if (!settingsPaths.some((settingsPath) => existsSync3(settingsPath))) return null;
2348
- const data = readMergedJsonFiles(settingsPaths);
2349
- const sessionDir = data.sessionDir;
2350
- if (typeof sessionDir !== "string" || !sessionDir.trim()) return null;
2351
- return resolveAtomicPath(sessionDir, cwd);
2352
- } catch {
2353
- return null;
2354
- }
2355
- }
2356
- function getAtomicSessionsDir(cwd) {
2357
- const envSessionDir = process.env.ATOMIC_CODING_AGENT_SESSION_DIR?.trim() || process.env.PI_CODING_AGENT_SESSION_DIR?.trim();
2358
- if (envSessionDir) {
2359
- return resolveAtomicPath(envSessionDir, cwd ?? process.cwd());
2360
- }
2361
- const atomicCwd = cwd ? resolve2(cwd) : process.cwd();
2362
- const agentDir = getAgentDir();
2363
- const projectSessionDir = cwd ? readSessionDirFromSettings(
2364
- getProjectConfigDirs(cwd).map((configDir) => join5(configDir, "settings.json")),
2365
- atomicCwd
2366
- ) : null;
2367
- return projectSessionDir ?? readSessionDirFromSettings(
2368
- getAgentDirs().map((configDir) => join5(configDir, "settings.json")),
2369
- atomicCwd
2370
- ) ?? join5(agentDir, "sessions");
2371
- }
2372
- function walkJsonlFiles(dir, out) {
2373
- let entries;
2374
- try {
2375
- entries = readdirSync2(dir, { withFileTypes: true, encoding: "utf8" });
2376
- } catch {
2377
- return;
2378
- }
2379
- for (const e of entries) {
2380
- const name = typeof e.name === "string" ? e.name : String(e.name);
2381
- const p = join5(dir, name);
2382
- if (e.isDirectory()) walkJsonlFiles(p, out);
2383
- else if (e.isFile() && name.endsWith(".jsonl")) out.push(p);
2384
- }
2385
- }
2386
- function readFirstLine(path) {
2387
- const fd = openSync(path, "r");
2388
- try {
2389
- const buf = Buffer.alloc(DEFAULT_HEAD_BYTES);
2390
- const n = readSync(fd, buf, 0, buf.length, 0);
2391
- if (n <= 0) return null;
2392
- const s = buf.subarray(0, n).toString("utf-8");
2393
- const idx = s.indexOf("\n");
2394
- return idx === -1 ? s.trim() : s.slice(0, idx).trim();
2395
- } catch {
2396
- return null;
2397
- } finally {
2398
- try {
2399
- closeSync(fd);
2400
- } catch {
2401
- }
2402
- }
2403
- }
2404
- function readTail(path, tailBytes = DEFAULT_TAIL_BYTES) {
2405
- const st = statSync2(path);
2406
- const start = Math.max(0, st.size - tailBytes);
2407
- const len = st.size - start;
2408
- const fd = openSync(path, "r");
2409
- try {
2410
- const buf = Buffer.alloc(len);
2411
- const n = readSync(fd, buf, 0, buf.length, start);
2412
- return buf.subarray(0, n).toString("utf-8");
2413
- } finally {
2414
- try {
2415
- closeSync(fd);
2416
- } catch {
2417
- }
2418
- }
2419
- }
2420
- function parseSessionHeader(firstLine) {
2421
- try {
2422
- const obj = JSON.parse(firstLine);
2423
- if (obj?.type !== "session") return null;
2424
- const sessionId = typeof obj?.id === "string" ? obj.id : null;
2425
- const cwd = typeof obj?.cwd === "string" ? obj.cwd : null;
2426
- if (!sessionId || !cwd) return null;
2427
- return { sessionId, cwd };
2428
- } catch {
2429
- return null;
2430
- }
2431
- }
2432
- function pickTitleFromTail(tail) {
2433
- const lines = tail.split(/\r?\n/);
2434
- for (let i = lines.length - 1; i >= 0; i--) {
2435
- const line = lines[i].trim();
2436
- if (!line) continue;
2437
- try {
2438
- const obj = JSON.parse(line);
2439
- if (obj?.type === "session_info" && typeof obj?.name === "string") {
2440
- return obj.name.trim();
2441
- }
2442
- } catch {
2443
- }
2444
- }
2445
- return null;
2446
- }
2447
- function scanSessionInfoNameFromFile(path) {
2448
- const fd = openSync(path, "r");
2449
- try {
2450
- const buf = Buffer.alloc(256 * 1024);
2451
- let leftover = "";
2452
- let offset = 0;
2453
- let lastName = null;
2454
- while (true) {
2455
- const n = readSync(fd, buf, 0, buf.length, offset);
2456
- if (n <= 0) break;
2457
- offset += n;
2458
- const chunk = leftover + buf.subarray(0, n).toString("utf8");
2459
- const lines = chunk.split(/\r?\n/);
2460
- leftover = lines.pop() ?? "";
2461
- for (const line0 of lines) {
2462
- const line = line0.trim();
2463
- if (!line) continue;
2464
- try {
2465
- const obj = JSON.parse(line);
2466
- if (obj?.type === "session_info" && typeof obj?.name === "string") {
2467
- lastName = obj.name.trim();
2468
- }
2469
- } catch {
2470
- }
2471
- }
2472
- }
2473
- const tailLine = leftover.trim();
2474
- if (tailLine) {
2475
- try {
2476
- const obj = JSON.parse(tailLine);
2477
- if (obj?.type === "session_info" && typeof obj?.name === "string") {
2478
- lastName = obj.name.trim();
2479
- }
2480
- } catch {
2481
- }
2482
- }
2483
- return lastName;
2484
- } catch {
2485
- return null;
2486
- } finally {
2487
- try {
2488
- closeSync(fd);
2489
- } catch {
2490
- }
2491
- }
2492
- }
2493
- function pickUpdatedAtFromTail(tail) {
2494
- const lines = tail.split(/\r?\n/);
2495
- for (let i = lines.length - 1; i >= 0; i--) {
2496
- const line = lines[i].trim();
2497
- if (!line) continue;
2498
- try {
2499
- const obj = JSON.parse(line);
2500
- if (obj?.type !== "message") continue;
2501
- const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
2502
- if (!ts) continue;
2503
- const d = new Date(ts);
2504
- if (Number.isFinite(d.getTime())) return d.toISOString();
2505
- } catch {
2506
- }
2507
- }
2508
- for (let i = lines.length - 1; i >= 0; i--) {
2509
- const line = lines[i].trim();
2510
- if (!line) continue;
2511
- try {
2512
- const obj = JSON.parse(line);
2513
- const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
2514
- if (!ts) continue;
2515
- const d = new Date(ts);
2516
- if (Number.isFinite(d.getTime())) return d.toISOString();
2517
- } catch {
2518
- }
2519
- }
2520
- return null;
2521
- }
2522
- function pickFallbackTitleFromHead(path) {
2523
- try {
2524
- const lines = readFileSync5(path, "utf8").split(/\r?\n/);
2525
- for (const line of lines.slice(0, 2e3)) {
2526
- if (!line.trim()) continue;
2527
- try {
2528
- const entry = JSON.parse(line);
2529
- if (entry.type !== "message" || entry.message?.role !== "user") continue;
2530
- const content = entry.message.content;
2531
- const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.filter(
2532
- (block) => typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string"
2533
- ) : [];
2534
- const title = promptToSessionTitle(blocks);
2535
- if (title) return title;
2536
- } catch {
2537
- }
2538
- }
2539
- } catch {
2540
- }
2541
- return null;
2542
- }
2543
- function readAtomicSessionTitle(path, tail) {
2544
- try {
2545
- const name = pickTitleFromTail(tail ?? readTail(path)) ?? scanSessionInfoNameFromFile(path);
2546
- return name ?? pickFallbackTitleFromHead(path);
2547
- } catch {
2548
- return null;
2549
- }
2550
- }
2551
- function listAtomicSessions(cwd) {
2552
- const sessionsDir = getAtomicSessionsDir(cwd);
2553
- const files = [];
2554
- walkJsonlFiles(sessionsDir, files);
2362
+ function str2(value) {
2363
+ return typeof value === "string" ? value : void 0;
2364
+ }
2365
+ function isoDate(value) {
2366
+ const date = typeof value === "string" ? new Date(value) : null;
2367
+ return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
2368
+ }
2369
+ function sessionTitle(info, messageCount) {
2370
+ const name = str2(info.name)?.trim();
2371
+ if (name || info.hasName === true) return name ?? "";
2372
+ const firstMessage = messageCount > 0 ? str2(info.firstMessage) : void 0;
2373
+ return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
2374
+ }
2375
+ function parseAtomicSessionList(data) {
2376
+ const sessions = data?.sessions;
2377
+ if (!Array.isArray(sessions)) return [];
2555
2378
  const items = [];
2556
- for (const file of files) {
2557
- const first = readFirstLine(file);
2558
- if (!first) continue;
2559
- const header = parseSessionHeader(first);
2560
- if (!header) continue;
2561
- let updatedAt = null;
2562
- let title = null;
2563
- try {
2564
- const tail = readTail(file);
2565
- title = readAtomicSessionTitle(file, tail);
2566
- updatedAt = pickUpdatedAtFromTail(tail);
2567
- } catch {
2568
- }
2569
- if (!updatedAt) {
2570
- try {
2571
- updatedAt = statSync2(file).mtime.toISOString();
2572
- } catch {
2573
- updatedAt = null;
2574
- }
2575
- }
2576
- items.push({
2577
- sessionId: header.sessionId,
2578
- cwd: header.cwd,
2579
- title,
2580
- updatedAt,
2581
- sessionFile: file
2582
- });
2583
- }
2584
- items.sort((a, b) => {
2585
- const aa = a.updatedAt ?? "";
2586
- const bb = b.updatedAt ?? "";
2587
- return bb.localeCompare(aa);
2588
- });
2589
- return items;
2590
- }
2591
- function findAtomicSession(sessionId, cwd) {
2592
- return listAtomicSessions(cwd).find((s) => s.sessionId === sessionId && (!cwd || s.cwd === cwd)) ?? null;
2379
+ for (const raw of sessions) {
2380
+ const info = raw ?? {};
2381
+ const sessionId = str2(info.id);
2382
+ const cwd = str2(info.cwd);
2383
+ if (sessionId === void 0 || !cwd) continue;
2384
+ const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
2385
+ const title = sessionTitle(info, messageCount);
2386
+ if (messageCount === 0 && title === null && info.summary === void 0) continue;
2387
+ items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
2388
+ }
2389
+ return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
2593
2390
  }
2594
2391
 
2595
2392
  // src/acp/translate/atomic-messages.ts
@@ -2637,8 +2434,8 @@ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2637
2434
 
2638
2435
  // src/acp/agent.ts
2639
2436
  import { isAbsolute as isAbsolute2 } from "path";
2640
- import { existsSync as existsSync4, readFileSync as readFileSync6, realpathSync, readdirSync as readdirSync3, statSync as statSync3, unlinkSync } from "fs";
2641
- import { join as join6, dirname as dirname2, basename as basename2 } from "path";
2437
+ import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
2438
+ import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2642
2439
  import { spawnSync } from "child_process";
2643
2440
  import { fileURLToPath } from "url";
2644
2441
  var MODEL_CONFIG_ID = "model";
@@ -2712,24 +2509,50 @@ var AtomicAcpAgent = class {
2712
2509
  this.conn = conn;
2713
2510
  void _config;
2714
2511
  }
2715
- cleanupFailedNewSession(sessionId, state) {
2512
+ cleanupFailedNewSession(sessionId) {
2716
2513
  this.sessions.close(sessionId);
2717
- const sessionFile = typeof state?.sessionFile === "string" && state.sessionFile.trim() ? state.sessionFile : this.store.get(sessionId)?.sessionFile;
2718
- if (typeof sessionFile === "string" && sessionFile.trim()) {
2719
- try {
2720
- if (existsSync4(sessionFile)) unlinkSync(sessionFile);
2721
- } catch {
2722
- }
2723
- }
2724
2514
  this.store.delete(sessionId);
2725
2515
  }
2726
- findStoredSession(sessionId, cwd) {
2516
+ /**
2517
+ * Run `use` against an Atomic for the project at `cwd`: a running one other than `exceptSessionId`'s,
2518
+ * or one started just for this call. Atomic chooses the session store from its settings.
2519
+ */
2520
+ async withProjectAtomic(cwd, use, exceptSessionId) {
2521
+ const live = this.sessions.findLive(cwd, exceptSessionId);
2522
+ if (live) return use(live.proc);
2523
+ let proc;
2524
+ try {
2525
+ proc = await AtomicRpcProcess.spawn({ cwd, atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND });
2526
+ } catch (error) {
2527
+ if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2528
+ throw error;
2529
+ }
2530
+ try {
2531
+ return await use(proc);
2532
+ } finally {
2533
+ await proc.dispose();
2534
+ }
2535
+ }
2536
+ /** Saved sessions of a project, as Atomic lists them. */
2537
+ async listProjectSessions(cwd) {
2538
+ const sessions = parseAtomicSessionList(await this.withProjectAtomic(cwd, (proc) => proc.listSessions()));
2539
+ this.store.upsertMany(sessions);
2540
+ return sessions;
2541
+ }
2542
+ async findStoredSession(sessionId, cwd) {
2727
2543
  const stored = this.store.get(sessionId);
2728
- if (stored?.cwd && stored.sessionFile && (!cwd || stored.cwd === cwd)) return stored;
2729
- const discovered = findAtomicSession(sessionId, cwd);
2730
- if (!discovered) return null;
2731
- this.store.upsert({ sessionId, cwd: discovered.cwd, sessionFile: discovered.sessionFile });
2732
- return discovered;
2544
+ if (stored?.cwd && (!cwd || stored.cwd === cwd)) return stored;
2545
+ if (!cwd) return null;
2546
+ const listed = (await this.listProjectSessions(cwd)).some((s) => s.sessionId === sessionId);
2547
+ return listed ? { cwd } : null;
2548
+ }
2549
+ /** The listed title of a session, `''` once its name was cleared; null when Atomic has none. */
2550
+ async readSessionTitle(proc, sessionId) {
2551
+ try {
2552
+ return parseAtomicSessionList(await proc.listSessions()).find((s) => s.sessionId === sessionId)?.title ?? null;
2553
+ } catch {
2554
+ return null;
2555
+ }
2733
2556
  }
2734
2557
  async withSessionOperation(sessionId, operation) {
2735
2558
  const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
@@ -2759,14 +2582,14 @@ var AtomicAcpAgent = class {
2759
2582
  this.sessions.close(sessionId);
2760
2583
  }
2761
2584
  const mcpServers = opts?.mcpServers ?? existing?.mcpServers;
2762
- const stored = this.findStoredSession(sessionId, opts?.cwd);
2585
+ const stored = await this.findStoredSession(sessionId, opts?.cwd);
2763
2586
  if (!stored) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2764
2587
  const cwd = opts?.cwd ?? stored.cwd;
2765
2588
  let proc;
2766
2589
  try {
2767
2590
  proc = await AtomicRpcProcess.spawn({
2768
2591
  cwd,
2769
- sessionPath: stored.sessionFile,
2592
+ sessionId,
2770
2593
  atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND,
2771
2594
  mcpServers: atomicMcpServersForSpawn(mcpServers),
2772
2595
  headless: isHeadlessFromEnv()
@@ -2786,9 +2609,11 @@ var AtomicAcpAgent = class {
2786
2609
  headless: isHeadlessFromEnv()
2787
2610
  });
2788
2611
  this.lastSessionCwd = cwd;
2789
- this.store.upsert({ sessionId, cwd, sessionFile: stored.sessionFile });
2790
- const title = readAtomicSessionTitle(stored.sessionFile);
2791
- if (!opts?.deferTitle && title !== null) await session.publishTitle(title || null, null);
2612
+ if (!opts?.deferTitle) {
2613
+ const title = await this.readSessionTitle(proc, sessionId);
2614
+ if (title !== null) await session.publishTitle(title || null, null);
2615
+ }
2616
+ if (!opts?.deferRecovery) startPendingRecovery(proc);
2792
2617
  return session;
2793
2618
  } catch (error) {
2794
2619
  if (this.sessions.maybeGet(sessionId)?.proc === proc) this.sessions.close(sessionId);
@@ -2871,23 +2696,23 @@ var AtomicAcpAgent = class {
2871
2696
  ]);
2872
2697
  const availableModelsAuthErr = maybeAuthRequiredError(availableModelsErr);
2873
2698
  if (availableModelsAuthErr) {
2874
- this.cleanupFailedNewSession(session.sessionId, state);
2699
+ this.cleanupFailedNewSession(session.sessionId);
2875
2700
  throw availableModelsAuthErr;
2876
2701
  }
2877
2702
  if (availableModelsErr) {
2878
- this.cleanupFailedNewSession(session.sessionId, state);
2703
+ this.cleanupFailedNewSession(session.sessionId);
2879
2704
  throw RequestError4.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2880
2705
  }
2881
2706
  const rawModelsCount = Array.isArray(availableModels?.models) ? availableModels.models.length : 0;
2882
2707
  if (rawModelsCount === 0) {
2883
- this.cleanupFailedNewSession(session.sessionId, state);
2708
+ this.cleanupFailedNewSession(session.sessionId);
2884
2709
  throw RequestError4.authRequired(
2885
2710
  { authMethods: getAuthMethods() },
2886
2711
  "Configure an API key or log in with an OAuth provider."
2887
2712
  );
2888
2713
  }
2889
2714
  if (stateErr && maybeAuthRequiredError(stateErr)) {
2890
- this.cleanupFailedNewSession(session.sessionId, state);
2715
+ this.cleanupFailedNewSession(session.sessionId);
2891
2716
  throw RequestError4.authRequired(
2892
2717
  { authMethods: getAuthMethods() },
2893
2718
  "Configure an API key or log in with an OAuth provider."
@@ -2901,10 +2726,13 @@ var AtomicAcpAgent = class {
2901
2726
  if (stateErr) throw stateErr;
2902
2727
  configuration = await getSessionConfiguration(session.proc, { state, availableModels });
2903
2728
  } catch (err) {
2904
- this.cleanupFailedNewSession(session.sessionId, state);
2729
+ this.cleanupFailedNewSession(session.sessionId);
2905
2730
  throw maybeAuthRequiredError(err) ?? RequestError4.internalError({}, String(err));
2906
2731
  }
2907
2732
  const { configOptions, models, modes } = configuration;
2733
+ if (typeof state?.sessionId === "string") {
2734
+ this.store.upsert({ sessionId: session.sessionId, cwd: params.cwd });
2735
+ }
2908
2736
  const quietStartup = getQuietStartup(params.cwd);
2909
2737
  const updateNotice = buildUpdateNotice();
2910
2738
  const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
@@ -3162,8 +2990,8 @@ ${JSON.stringify(stats, null, 2)}`;
3162
2990
  if (atomicPath) {
3163
2991
  const resolved = realpathSync(atomicPath);
3164
2992
  const pkgRoot = dirname2(dirname2(resolved));
3165
- const p = join6(pkgRoot, "CHANGELOG.md");
3166
- if (existsSync4(p)) return p;
2993
+ const p = join5(pkgRoot, "CHANGELOG.md");
2994
+ if (existsSync3(p)) return p;
3167
2995
  }
3168
2996
  } catch {
3169
2997
  }
@@ -3171,8 +2999,8 @@ ${JSON.stringify(stats, null, 2)}`;
3171
2999
  const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
3172
3000
  const root = String(npmRoot.stdout ?? "").trim();
3173
3001
  if (root) {
3174
- const p = join6(root, "@bastani", "atomic", "CHANGELOG.md");
3175
- if (existsSync4(p)) return p;
3002
+ const p = join5(root, "@bastani", "atomic", "CHANGELOG.md");
3003
+ if (existsSync3(p)) return p;
3176
3004
  }
3177
3005
  } catch {
3178
3006
  }
@@ -3191,7 +3019,7 @@ ${JSON.stringify(stats, null, 2)}`;
3191
3019
  }
3192
3020
  let text = "";
3193
3021
  try {
3194
- text = readFileSync6(changelogPath, "utf-8");
3022
+ text = readFileSync5(changelogPath, "utf-8");
3195
3023
  } catch (e) {
3196
3024
  await this.conn.sessionUpdate({
3197
3025
  sessionId: session.sessionId,
@@ -3215,51 +3043,19 @@ ${JSON.stringify(stats, null, 2)}`;
3215
3043
  }
3216
3044
  if (cmd === "export") {
3217
3045
  const state = await session.proc.getState();
3218
- const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
3219
3046
  const messageCount = typeof state?.messageCount === "number" ? state.messageCount : 0;
3220
- if (!sessionFile || messageCount === 0 || !existsSync4(sessionFile)) {
3047
+ if (messageCount === 0) {
3221
3048
  await this.conn.sessionUpdate({
3222
3049
  sessionId: session.sessionId,
3223
3050
  update: {
3224
3051
  sessionUpdate: "agent_message_chunk",
3225
- content: {
3226
- type: "text",
3227
- text: "Nothing to export yet (no session messages). Send a prompt first."
3228
- }
3229
- }
3230
- });
3231
- return { stopReason: "end_turn" };
3232
- }
3233
- try {
3234
- const raw = readFileSync6(sessionFile, "utf-8");
3235
- if (raw.trim().length === 0) {
3236
- await this.conn.sessionUpdate({
3237
- sessionId: session.sessionId,
3238
- update: {
3239
- sessionUpdate: "agent_message_chunk",
3240
- content: {
3241
- type: "text",
3242
- text: "Nothing to export yet (empty session file). Send a prompt first."
3243
- }
3244
- }
3245
- });
3246
- return { stopReason: "end_turn" };
3247
- }
3248
- } catch {
3249
- await this.conn.sessionUpdate({
3250
- sessionId: session.sessionId,
3251
- update: {
3252
- sessionUpdate: "agent_message_chunk",
3253
- content: {
3254
- type: "text",
3255
- text: "Couldn't read session file for export. Try sending a prompt first."
3256
- }
3052
+ content: { type: "text", text: "Nothing to export yet (no session messages). Send a prompt first." }
3257
3053
  }
3258
3054
  });
3259
3055
  return { stopReason: "end_turn" };
3260
3056
  }
3261
3057
  const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
3262
- const outputPath = join6(session.cwd, `atomic-session-${safeSessionId}.html`);
3058
+ const outputPath = join5(session.cwd, `atomic-session-${safeSessionId}.html`);
3263
3059
  let resultPath = "";
3264
3060
  try {
3265
3061
  const result = await session.proc.exportHtml(outputPath);
@@ -3355,9 +3151,9 @@ ${JSON.stringify(stats, null, 2)}`;
3355
3151
  return this.listSessionsImpl(params);
3356
3152
  }
3357
3153
  async listSessionsImpl(params) {
3358
- const effectiveCwd = params.cwd ?? this.lastSessionCwd;
3359
- const all = listAtomicSessions(effectiveCwd ?? void 0);
3360
- const filtered = effectiveCwd ? all.filter((s) => s.cwd === effectiveCwd) : all;
3154
+ const effectiveCwd = params.cwd ?? this.lastSessionCwd ?? process.cwd();
3155
+ if (!isAbsolute2(effectiveCwd)) throw RequestError4.invalidParams(`cwd must be an absolute path: ${effectiveCwd}`);
3156
+ const filtered = await this.listProjectSessions(effectiveCwd);
3361
3157
  const offset = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
3362
3158
  const start = Number.isFinite(offset) && offset > 0 ? offset : 0;
3363
3159
  const PAGE_SIZE = 50;
@@ -3382,7 +3178,8 @@ ${JSON.stringify(stats, null, 2)}`;
3382
3178
  const session = await this.restoreSessionImpl(params.sessionId, {
3383
3179
  cwd: params.cwd,
3384
3180
  mcpServers: params.mcpServers,
3385
- deferTitle: true
3181
+ deferTitle: true,
3182
+ deferRecovery: true
3386
3183
  });
3387
3184
  const proc = session.proc;
3388
3185
  const fileCommands = loadSlashCommands(params.cwd);
@@ -3399,8 +3196,7 @@ ${JSON.stringify(stats, null, 2)}`;
3399
3196
  throw err;
3400
3197
  }
3401
3198
  const { configOptions, models, modes } = configuration;
3402
- const stored = this.store.get(params.sessionId);
3403
- const title = stored?.sessionFile ? readAtomicSessionTitle(stored.sessionFile) : null;
3199
+ const title = await this.readSessionTitle(proc, params.sessionId);
3404
3200
  if (title !== null) await session.publishTitle(title || null, null);
3405
3201
  try {
3406
3202
  if (typeof proc.getCommands === "function") atomicCommands = await proc.getCommands();
@@ -3506,6 +3302,7 @@ ${JSON.stringify(stats, null, 2)}`;
3506
3302
  };
3507
3303
  setTimeout(() => {
3508
3304
  void (async () => {
3305
+ startPendingRecovery(proc);
3509
3306
  await session.publishContextUsage();
3510
3307
  try {
3511
3308
  if (atomicCommandsErr || !atomicCommands) throw atomicCommandsErr;
@@ -3534,22 +3331,16 @@ ${JSON.stringify(stats, null, 2)}`;
3534
3331
  }, 0);
3535
3332
  return response;
3536
3333
  }
3537
- async deleteSession(params) {
3334
+ async unstable_deleteSession(params) {
3538
3335
  return this.withSessionOperation(params.sessionId, () => this.deleteSessionImpl(params));
3539
3336
  }
3540
3337
  async deleteSessionImpl(params) {
3541
- const stored = this.store.get(params.sessionId);
3542
- const discovered = findAtomicSession(params.sessionId);
3543
- const sessionFile = stored?.sessionFile ?? discovered?.sessionFile;
3544
- this.sessions.close(params.sessionId);
3545
- if (sessionFile) {
3546
- try {
3547
- unlinkSync(sessionFile);
3548
- } catch (error) {
3549
- if (error.code !== "ENOENT") throw error;
3550
- }
3551
- }
3552
- this.store.delete(params.sessionId);
3338
+ const { sessionId } = params;
3339
+ const live = this.sessions.maybeGet(sessionId);
3340
+ const cwd = live?.cwd ?? this.store.get(sessionId)?.cwd ?? this.lastSessionCwd ?? process.cwd();
3341
+ if (live) await this.sessions.close(sessionId);
3342
+ await this.withProjectAtomic(cwd, (proc) => proc.deleteSession(sessionId), sessionId);
3343
+ this.store.delete(sessionId);
3553
3344
  return {};
3554
3345
  }
3555
3346
  async unstable_setSessionModel(params) {
@@ -3585,6 +3376,10 @@ ${JSON.stringify(stats, null, 2)}`;
3585
3376
  return { configOptions };
3586
3377
  }
3587
3378
  };
3379
+ function startPendingRecovery(proc) {
3380
+ void proc.startPendingRecovery("resume").catch(() => {
3381
+ });
3382
+ }
3588
3383
  async function getThinkingState(proc, pre) {
3589
3384
  const state = pre?.state ?? await proc.getState();
3590
3385
  const available = await proc.getAvailableThinkingLevels();
@@ -3724,7 +3519,7 @@ function compareSemver(a, b) {
3724
3519
  function resolveAtomicExecutablePath() {
3725
3520
  const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3726
3521
  if (cmd.includes("/") || process.platform === "win32" && /^[a-z]:[\\/]/i.test(cmd)) {
3727
- return existsSync4(cmd) ? cmd : null;
3522
+ return existsSync3(cmd) ? cmd : null;
3728
3523
  }
3729
3524
  const whichCmd = process.platform === "win32" ? "where" : "which";
3730
3525
  const which = spawnSync(whichCmd, [cmd], { encoding: "utf-8" });
@@ -3774,16 +3569,16 @@ function buildStartupInfo(opts) {
3774
3569
  md.push("");
3775
3570
  };
3776
3571
  const contextItems = [];
3777
- const contextPath = join6(opts.cwd, "AGENTS.md");
3778
- if (existsSync4(contextPath)) contextItems.push(contextPath);
3572
+ const contextPath = join5(opts.cwd, "AGENTS.md");
3573
+ if (existsSync3(contextPath)) contextItems.push(contextPath);
3779
3574
  addSection("Context", contextItems);
3780
3575
  const skillsItems = [];
3781
3576
  const pushSkillFromRoot = (root) => {
3782
3577
  try {
3783
- for (const e of readdirSync3(root)) {
3784
- const p = join6(root, e);
3578
+ for (const e of readdirSync2(root)) {
3579
+ const p = join5(root, e);
3785
3580
  try {
3786
- const st = statSync3(p);
3581
+ const st = statSync2(p);
3787
3582
  if (st.isFile() && e.toLowerCase().endsWith(".md")) {
3788
3583
  skillsItems.push(p);
3789
3584
  }
@@ -3795,16 +3590,16 @@ function buildStartupInfo(opts) {
3795
3590
  const dir = stack.pop();
3796
3591
  let entries = [];
3797
3592
  try {
3798
- entries = readdirSync3(dir);
3593
+ entries = readdirSync2(dir);
3799
3594
  } catch {
3800
3595
  continue;
3801
3596
  }
3802
3597
  for (const name of entries) {
3803
3598
  if (name === "node_modules" || name === ".git") continue;
3804
- const p = join6(dir, name);
3599
+ const p = join5(dir, name);
3805
3600
  let st;
3806
3601
  try {
3807
- st = statSync3(p);
3602
+ st = statSync2(p);
3808
3603
  } catch {
3809
3604
  continue;
3810
3605
  }
@@ -3818,32 +3613,32 @@ function buildStartupInfo(opts) {
3818
3613
  } catch {
3819
3614
  }
3820
3615
  };
3821
- const globalSkillsDir = join6(getAgentDir(), "skills");
3616
+ const globalSkillsDir = join5(getAgentDir(), "skills");
3822
3617
  pushSkillFromRoot(globalSkillsDir);
3823
- const legacyAgentsSkillsDir = join6(process.env.HOME ?? "", ".agents", "skills");
3618
+ const legacyAgentsSkillsDir = join5(process.env.HOME ?? "", ".agents", "skills");
3824
3619
  pushSkillFromRoot(legacyAgentsSkillsDir);
3825
- const projectSkillsDir = join6(opts.cwd, ".atomic", "skills");
3620
+ const projectSkillsDir = join5(opts.cwd, ".atomic", "skills");
3826
3621
  pushSkillFromRoot(projectSkillsDir);
3827
3622
  addSection("Skills", skillsItems);
3828
3623
  const promptsItems = [];
3829
3624
  const agentDir = getAgentDir();
3830
- const promptsDir = join6(agentDir, "prompts");
3625
+ const promptsDir = join5(agentDir, "prompts");
3831
3626
  try {
3832
- const prompts = readdirSync3(promptsDir).filter((f) => f.endsWith(".md"));
3627
+ const prompts = readdirSync2(promptsDir).filter((f) => f.endsWith(".md"));
3833
3628
  for (const f of prompts) promptsItems.push(`/${basename2(f, ".md")}`);
3834
3629
  } catch {
3835
3630
  }
3836
3631
  addSection("Prompts", promptsItems);
3837
3632
  const extItems = [];
3838
- const extDir = join6(agentDir, "extensions");
3633
+ const extDir = join5(agentDir, "extensions");
3839
3634
  try {
3840
- const exts = readdirSync3(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3841
- for (const f of exts) extItems.push(join6(extDir, f));
3635
+ const exts = readdirSync2(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3636
+ for (const f of exts) extItems.push(join5(extDir, f));
3842
3637
  } catch {
3843
3638
  }
3844
- for (const settingsPath of [join6(agentDir, "settings.json"), join6(opts.cwd, ".atomic", "settings.json")]) {
3639
+ for (const settingsPath of [join5(agentDir, "settings.json"), join5(opts.cwd, ".atomic", "settings.json")]) {
3845
3640
  try {
3846
- const settings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
3641
+ const settings = JSON.parse(readFileSync5(settingsPath, "utf-8"));
3847
3642
  const packages = Array.isArray(settings.packages) ? settings.packages : [];
3848
3643
  for (const pkg2 of packages) {
3849
3644
  const source = typeof pkg2 === "string" ? pkg2 : pkg2?.source;
@@ -3866,9 +3661,9 @@ function readNearestPackageJson(metaUrl) {
3866
3661
  try {
3867
3662
  let dir = dirname2(fileURLToPath(metaUrl));
3868
3663
  for (let i = 0; i < 6; i++) {
3869
- const p = join6(dir, "package.json");
3870
- if (existsSync4(p)) {
3871
- const json = JSON.parse(readFileSync6(p, "utf-8"));
3664
+ const p = join5(dir, "package.json");
3665
+ if (existsSync3(p)) {
3666
+ const json = JSON.parse(readFileSync5(p, "utf-8"));
3872
3667
  return { name: json?.name, version: json?.version };
3873
3668
  }
3874
3669
  dir = dirname2(dir);
@@ -3913,7 +3708,7 @@ function parseCliArgs(argv) {
3913
3708
 
3914
3709
  // src/index.ts
3915
3710
  async function writeAndExit(stream2, text, code) {
3916
- await new Promise((resolve3) => stream2.write(text, () => resolve3()));
3711
+ await new Promise((resolve2) => stream2.write(text, () => resolve2()));
3917
3712
  process.exit(code);
3918
3713
  }
3919
3714
  var cli = parseCliArgs(process.argv);
@@ -3953,15 +3748,15 @@ try {
3953
3748
  }
3954
3749
  var input = new WritableStream({
3955
3750
  write(chunk) {
3956
- return new Promise((resolve3) => {
3957
- if (process.stdout.destroyed || !process.stdout.writable) return resolve3();
3751
+ return new Promise((resolve2) => {
3752
+ if (process.stdout.destroyed || !process.stdout.writable) return resolve2();
3958
3753
  try {
3959
3754
  process.stdout.write(chunk, (err) => {
3960
3755
  void err;
3961
- resolve3();
3756
+ resolve2();
3962
3757
  });
3963
3758
  } catch {
3964
- resolve3();
3759
+ resolve2();
3965
3760
  }
3966
3761
  });
3967
3762
  }