@bastani/atomic-acp 0.0.5 → 0.0.6

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,9 @@ 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",
273
276
  "--no-session",
274
277
  "-c",
275
278
  "--continue",
@@ -338,7 +341,7 @@ async function removeDir(dir, cleanup) {
338
341
  const delay = delays[attempt];
339
342
  const code = error?.code;
340
343
  if (delay === void 0 || code === void 0 || !RETRYABLE_RM_CODES.has(code)) return;
341
- await new Promise((resolve3) => setTimeout(resolve3, delay));
344
+ await new Promise((resolve2) => setTimeout(resolve2, delay));
342
345
  }
343
346
  }
344
347
  }
@@ -453,7 +456,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
453
456
  constructor(child, adapterExtension) {
454
457
  this.child = child;
455
458
  this.adapterExtension = adapterExtension;
456
- this.exited = new Promise((resolve3) => child.once("exit", () => resolve3()));
459
+ this.exited = new Promise((resolve2) => child.once("exit", () => resolve2()));
457
460
  let stdoutBuffer = "";
458
461
  child.stdout.setEncoding("utf8");
459
462
  child.stdout.on("data", (chunk) => {
@@ -495,7 +498,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
495
498
  throw new AtomicRpcSpawnError(`Could not start Atomic: ${e.message}`, { cause: e });
496
499
  }
497
500
  const args = ["--mode", "rpc", "--no-themes"];
498
- if (params.sessionPath) args.push("--session", params.sessionPath);
501
+ if (params.sessionId !== void 0) args.push("--session", params.sessionId);
499
502
  const adapterExtension = writeAdapterExtension({
500
503
  mcpServers: params.mcpServers,
501
504
  ...params.headless ? { askUserQuestionUnavailable: NO_PERSON_FOR_ASK_USER_QUESTION } : {}
@@ -516,10 +519,10 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
516
519
  throw e;
517
520
  }
518
521
  try {
519
- await new Promise((resolve3, reject) => {
522
+ await new Promise((resolve2, reject) => {
520
523
  const onSpawn = () => {
521
524
  cleanup();
522
- resolve3();
525
+ resolve2();
523
526
  };
524
527
  const onError = (err) => {
525
528
  cleanup();
@@ -553,13 +556,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
553
556
  });
554
557
  const proc = new _AtomicRpcProcess(child, adapterExtension);
555
558
  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
- }
559
+ await proc.getState();
563
560
  } catch {
564
561
  }
565
562
  return proc;
@@ -600,8 +597,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
600
597
  let timer;
601
598
  await Promise.race([
602
599
  this.exited,
603
- new Promise((resolve3) => {
604
- timer = setTimeout(resolve3, DISPOSE_EXIT_WAIT_MS);
600
+ new Promise((resolve2) => {
601
+ timer = setTimeout(resolve2, DISPOSE_EXIT_WAIT_MS);
605
602
  timer.unref?.();
606
603
  })
607
604
  ]);
@@ -697,9 +694,16 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
697
694
  const data = res.data;
698
695
  return { path: String(data?.path ?? "") };
699
696
  }
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)}`);
697
+ /** Saved sessions of the current project, as Atomic's session store lists them. */
698
+ async listSessions() {
699
+ const res = await this.request({ type: "list_sessions" });
700
+ if (!res.success) throw new Error(`Atomic list_sessions failed: ${res.error ?? JSON.stringify(res.data)}`);
701
+ return res.data;
702
+ }
703
+ /** Delete a saved session from Atomic's session store. Atomic refuses to delete its own open session. */
704
+ async deleteSession(sessionId) {
705
+ const res = await this.request({ type: "delete_session", sessionId });
706
+ if (!res.success) throw new Error(`Atomic delete_session failed: ${res.error ?? JSON.stringify(res.data)}`);
703
707
  }
704
708
  async getMessages() {
705
709
  const res = await this.request({ type: "get_messages" });
@@ -713,11 +717,11 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
713
717
  }
714
718
  writeJsonLine(value) {
715
719
  const line = JSON.stringify(value) + "\n";
716
- return new Promise((resolve3, reject) => {
720
+ return new Promise((resolve2, reject) => {
717
721
  try {
718
722
  this.child.stdin.write(line, (err) => {
719
723
  if (err) reject(err);
720
- else resolve3();
724
+ else resolve2();
721
725
  });
722
726
  } catch (e) {
723
727
  reject(e);
@@ -740,7 +744,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
740
744
  const id = crypto.randomUUID();
741
745
  const withId = { ...cmd, id };
742
746
  const timeoutMs = opts?.timeoutMs;
743
- return new Promise((resolve3, reject) => {
747
+ return new Promise((resolve2, reject) => {
744
748
  let timer;
745
749
  const drop = () => {
746
750
  if (timer !== void 0) {
@@ -752,7 +756,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
752
756
  this.pending.set(id, {
753
757
  resolve: (res) => {
754
758
  drop();
755
- resolve3(res);
759
+ resolve2(res);
756
760
  },
757
761
  reject: (error) => {
758
762
  drop();
@@ -775,67 +779,6 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
775
779
  }
776
780
  };
777
781
 
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
782
  // src/acp/translate/atomic-tools.ts
840
783
  function toolResultToText(result) {
841
784
  if (!result) return "";
@@ -866,13 +809,13 @@ ${stderr}`);
866
809
  }
867
810
 
868
811
  // 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";
812
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
813
+ import { basename, join as join3 } from "path";
871
814
 
872
815
  // 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";
816
+ import { existsSync, readFileSync } from "fs";
817
+ import { homedir } from "os";
818
+ import { join as join2, resolve } from "path";
876
819
  function isObject(x) {
877
820
  return Boolean(x) && typeof x === "object" && !Array.isArray(x);
878
821
  }
@@ -888,7 +831,7 @@ function deepMerge(a, b) {
888
831
  function readJsonFile(path) {
889
832
  try {
890
833
  if (!existsSync(path)) return {};
891
- const raw = readFileSync2(path, "utf-8");
834
+ const raw = readFileSync(path, "utf-8");
892
835
  const data = JSON.parse(raw.replace(/^\uFEFF/, ""));
893
836
  return isObject(data) ? data : {};
894
837
  } catch {
@@ -919,12 +862,12 @@ function getSettingsWithLocations(cwd) {
919
862
  {
920
863
  location: "user",
921
864
  baseDirs: agentDirs,
922
- settings: readMergedJsonFiles(agentDirs.map((dir) => join3(dir, "settings.json")))
865
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
923
866
  },
924
867
  {
925
868
  location: "project",
926
869
  baseDirs: projectDirs,
927
- settings: readMergedJsonFiles(projectDirs.map((dir) => join3(dir, "settings.json")))
870
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
928
871
  }
929
872
  ];
930
873
  }
@@ -933,8 +876,8 @@ function getMergedSettings(cwd) {
933
876
  return deepMerge(settings[0].settings, settings[1].settings);
934
877
  }
935
878
  function expandHomePath(value) {
936
- if (value === "~") return homedir2();
937
- if (value.startsWith("~/")) return join3(homedir2(), value.slice(2));
879
+ if (value === "~") return homedir();
880
+ if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
938
881
  return value;
939
882
  }
940
883
  function resolveAtomicPath(value, relativeBase = process.cwd()) {
@@ -954,12 +897,12 @@ function readMergedResourceSettings(cwd) {
954
897
  }
955
898
  function getAgentDir() {
956
899
  const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
957
- return override ? resolveAtomicPath(override) : join3(homedir2(), ".atomic", "agent");
900
+ return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
958
901
  }
959
902
  function getAgentDirs() {
960
903
  const primary = getAgentDir();
961
904
  if (hasAgentDirOverride()) return [primary];
962
- const legacy = join3(homedir2(), ".pi", "agent");
905
+ const legacy = join2(homedir(), ".pi", "agent");
963
906
  return legacy === primary ? [primary] : [primary, legacy];
964
907
  }
965
908
  function getProjectConfigDirs(cwd) {
@@ -1010,7 +953,7 @@ function describeContent(content, frontmatter, sourceStr) {
1010
953
  }
1011
954
  function loadCommandFromFile(path, sourceStr, name = basename(path, ".md")) {
1012
955
  try {
1013
- const rawContent = readFileSync3(path, "utf-8");
956
+ const rawContent = readFileSync2(path, "utf-8");
1014
957
  const { frontmatter, content } = parseFrontmatter(rawContent);
1015
958
  return {
1016
959
  name,
@@ -1030,7 +973,7 @@ function loadCommandsFromDir(dir, source, subdir = "") {
1030
973
  const entries = readdirSync(dir, { withFileTypes: true });
1031
974
  for (const entry of entries) {
1032
975
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
1033
- const fullPath = join4(dir, entry.name);
976
+ const fullPath = join3(dir, entry.name);
1034
977
  const sourceStr = source === "path" ? "(path)" : source === "user" ? subdir ? `(user:${subdir})` : "(user)" : subdir ? `(project:${subdir})` : "(project)";
1035
978
  const command = loadCommandFromFile(fullPath, sourceStr);
1036
979
  if (command) commands.push(command);
@@ -1081,8 +1024,8 @@ function loadSlashCommands(cwd) {
1081
1024
  commands.push(...loadCommandsFromSettingPath(resolved, entry.location));
1082
1025
  }
1083
1026
  }
1084
- const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join4(configDir, "prompts"));
1085
- const userDirs = getAgentDirs().map((agentDir) => join4(agentDir, "prompts"));
1027
+ const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join3(configDir, "prompts"));
1028
+ const userDirs = getAgentDirs().map((agentDir) => join3(agentDir, "prompts"));
1086
1029
  for (const projectDir of projectDirs) commands.push(...loadCommandsFromDir(projectDir, "project"));
1087
1030
  for (const userDir of userDirs) commands.push(...loadCommandsFromDir(userDir, "user"));
1088
1031
  return filterExcluded(commands, excludedPaths);
@@ -1342,7 +1285,6 @@ function toToolCallLocations(args, cwd, line) {
1342
1285
  }
1343
1286
  var SessionManager = class {
1344
1287
  sessions = /* @__PURE__ */ new Map();
1345
- store = new SessionStore();
1346
1288
  /** Dispose all sessions and their underlying Atomic subprocesses. */
1347
1289
  disposeAll() {
1348
1290
  for (const [id] of this.sessions) this.close(id);
@@ -1351,18 +1293,27 @@ var SessionManager = class {
1351
1293
  maybeGet(sessionId) {
1352
1294
  return this.sessions.get(sessionId);
1353
1295
  }
1296
+ /** A registered session for `cwd`, other than `exceptSessionId`, whose Atomic is still running. */
1297
+ findLive(cwd, exceptSessionId) {
1298
+ for (const session of this.sessions.values()) {
1299
+ if (session.cwd === cwd && session.sessionId !== exceptSessionId && !session.proc.hasExited) return session;
1300
+ }
1301
+ return void 0;
1302
+ }
1354
1303
  /**
1355
1304
  * Dispose a session's underlying Atomic process and remove it from the manager.
1356
1305
  * Used when clients explicitly reload a session and we want a fresh Atomic subprocess.
1357
1306
  */
1358
1307
  close(sessionId) {
1359
1308
  const s = this.sessions.get(sessionId);
1360
- if (!s) return;
1309
+ if (!s) return Promise.resolve();
1310
+ this.sessions.delete(sessionId);
1361
1311
  try {
1362
- s.proc.dispose?.();
1312
+ return Promise.resolve(s.proc.dispose?.()).catch(() => {
1313
+ });
1363
1314
  } catch {
1315
+ return Promise.resolve();
1364
1316
  }
1365
- this.sessions.delete(sessionId);
1366
1317
  }
1367
1318
  /** Close all sessions except the one with `keepSessionId`. */
1368
1319
  closeAllExcept(keepSessionId) {
@@ -1393,10 +1344,6 @@ var SessionManager = class {
1393
1344
  state = null;
1394
1345
  }
1395
1346
  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
1347
  const session = new AtomicAcpSession({
1401
1348
  sessionId,
1402
1349
  cwd: params.cwd,
@@ -1522,8 +1469,8 @@ var AtomicAcpSession = class {
1522
1469
  async prompt(message, images = [], title) {
1523
1470
  this.sendStartupInfoOnFirstPromptIfPending();
1524
1471
  const expandedMessage = expandSlashCommand(message, this.fileCommands);
1525
- const turnPromise = new Promise((resolve3, reject) => {
1526
- const queued = { message: expandedMessage, images, title, resolve: resolve3, reject };
1472
+ const turnPromise = new Promise((resolve2, reject) => {
1473
+ const queued = { message: expandedMessage, images, title, resolve: resolve2, reject };
1527
1474
  if (this.pendingTurn) {
1528
1475
  this.turnQueue.push(queued);
1529
1476
  this.emit({
@@ -2074,7 +2021,7 @@ var AtomicAcpSession = class {
2074
2021
  this.fileMutationToolCallIds.add(toolCallId);
2075
2022
  const snapshots = getMutationPaths(args).map((path) => {
2076
2023
  try {
2077
- const oldText = readFileSync4(resolvePath(this.cwd, path), "utf8");
2024
+ const oldText = readFileSync3(resolvePath(this.cwd, path), "utf8");
2078
2025
  if (typeof args?.oldText === "string") line = findUniqueLineNumber(oldText, args.oldText);
2079
2026
  return { path, oldText };
2080
2027
  } catch (error) {
@@ -2146,7 +2093,7 @@ var AtomicAcpSession = class {
2146
2093
  for (const snapshot of snapshots) {
2147
2094
  try {
2148
2095
  const path = resolvePath(this.cwd, snapshot.path);
2149
- const newText = readFileSync4(path, "utf8");
2096
+ const newText = readFileSync3(path, "utf8");
2150
2097
  if (newText !== snapshot.oldText) {
2151
2098
  content ??= [];
2152
2099
  content.push({ type: "diff", path, oldText: snapshot.oldText, newText });
@@ -2273,15 +2220,76 @@ function toToolKind(toolName) {
2273
2220
  }
2274
2221
  }
2275
2222
 
2223
+ // src/acp/session-store.ts
2224
+ import { mkdirSync, readFileSync as readFileSync4, writeFileSync as writeFileSync2 } from "fs";
2225
+ import { dirname } from "path";
2226
+
2227
+ // src/acp/paths.ts
2228
+ import { homedir as homedir2 } from "os";
2229
+ import { join as join4 } from "path";
2230
+ function getAtomicAcpDir() {
2231
+ return join4(homedir2(), ".atomic", "atomic-acp");
2232
+ }
2233
+ function getAtomicAcpSessionMapPath() {
2234
+ return join4(getAtomicAcpDir(), "session-map.json");
2235
+ }
2236
+
2237
+ // src/acp/session-store.ts
2238
+ function ensureParentDir(path) {
2239
+ mkdirSync(dirname(path), { recursive: true });
2240
+ }
2241
+ function loadFile(path) {
2242
+ try {
2243
+ const raw = readFileSync4(path, "utf-8");
2244
+ const parsed = JSON.parse(raw);
2245
+ if (parsed?.version !== 1 || typeof parsed.sessions !== "object" || !parsed.sessions) {
2246
+ return { version: 1, sessions: {} };
2247
+ }
2248
+ return parsed;
2249
+ } catch {
2250
+ return { version: 1, sessions: {} };
2251
+ }
2252
+ }
2253
+ function saveFile(path, data) {
2254
+ ensureParentDir(path);
2255
+ writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
2256
+ }
2257
+ var SessionStore = class {
2258
+ path;
2259
+ constructor(path = getAtomicAcpSessionMapPath()) {
2260
+ this.path = path;
2261
+ }
2262
+ get(sessionId) {
2263
+ const db = loadFile(this.path);
2264
+ return db.sessions[sessionId] ?? null;
2265
+ }
2266
+ upsert(entry) {
2267
+ this.upsertMany([entry]);
2268
+ }
2269
+ /** Record which project each session belongs to; the map is rewritten only when an entry changes. */
2270
+ upsertMany(entries) {
2271
+ const db = loadFile(this.path);
2272
+ let changed = false;
2273
+ for (const { sessionId, cwd } of entries) {
2274
+ if (db.sessions[sessionId]?.cwd === cwd) continue;
2275
+ db.sessions[sessionId] = { sessionId, cwd, updatedAt: (/* @__PURE__ */ new Date()).toISOString() };
2276
+ changed = true;
2277
+ }
2278
+ if (changed) saveFile(this.path, db);
2279
+ }
2280
+ delete(sessionId) {
2281
+ const db = loadFile(this.path);
2282
+ if (!db.sessions[sessionId]) return;
2283
+ delete db.sessions[sessionId];
2284
+ saveFile(this.path, db);
2285
+ }
2286
+ };
2287
+
2276
2288
  // src/acp/headless.ts
2277
2289
  function isHeadlessFromEnv(env = process.env) {
2278
2290
  return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
2279
2291
  }
2280
2292
 
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
2293
  // src/acp/translate/prompt.ts
2286
2294
  function promptToSessionTitle(blocks) {
2287
2295
  const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
@@ -2340,256 +2348,34 @@ ${r.text}`;
2340
2348
  }
2341
2349
 
2342
2350
  // 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);
2351
+ function str2(value) {
2352
+ return typeof value === "string" ? value : void 0;
2353
+ }
2354
+ function isoDate(value) {
2355
+ const date = typeof value === "string" ? new Date(value) : null;
2356
+ return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
2357
+ }
2358
+ function sessionTitle(info, messageCount) {
2359
+ const name = str2(info.name)?.trim();
2360
+ if (name || info.hasName === true) return name ?? "";
2361
+ const firstMessage = messageCount > 0 ? str2(info.firstMessage) : void 0;
2362
+ return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
2363
+ }
2364
+ function parseAtomicSessionList(data) {
2365
+ const sessions = data?.sessions;
2366
+ if (!Array.isArray(sessions)) return [];
2555
2367
  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;
2368
+ for (const raw of sessions) {
2369
+ const info = raw ?? {};
2370
+ const sessionId = str2(info.id);
2371
+ const cwd = str2(info.cwd);
2372
+ if (sessionId === void 0 || !cwd) continue;
2373
+ const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
2374
+ const title = sessionTitle(info, messageCount);
2375
+ if (messageCount === 0 && title === null && info.summary === void 0) continue;
2376
+ items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
2377
+ }
2378
+ return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
2593
2379
  }
2594
2380
 
2595
2381
  // src/acp/translate/atomic-messages.ts
@@ -2637,8 +2423,8 @@ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2637
2423
 
2638
2424
  // src/acp/agent.ts
2639
2425
  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";
2426
+ import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
2427
+ import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2642
2428
  import { spawnSync } from "child_process";
2643
2429
  import { fileURLToPath } from "url";
2644
2430
  var MODEL_CONFIG_ID = "model";
@@ -2712,24 +2498,50 @@ var AtomicAcpAgent = class {
2712
2498
  this.conn = conn;
2713
2499
  void _config;
2714
2500
  }
2715
- cleanupFailedNewSession(sessionId, state) {
2501
+ cleanupFailedNewSession(sessionId) {
2716
2502
  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
2503
  this.store.delete(sessionId);
2725
2504
  }
2726
- findStoredSession(sessionId, cwd) {
2505
+ /**
2506
+ * Run `use` against an Atomic for the project at `cwd`: a running one other than `exceptSessionId`'s,
2507
+ * or one started just for this call. Atomic chooses the session store from its settings.
2508
+ */
2509
+ async withProjectAtomic(cwd, use, exceptSessionId) {
2510
+ const live = this.sessions.findLive(cwd, exceptSessionId);
2511
+ if (live) return use(live.proc);
2512
+ let proc;
2513
+ try {
2514
+ proc = await AtomicRpcProcess.spawn({ cwd, atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND });
2515
+ } catch (error) {
2516
+ if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2517
+ throw error;
2518
+ }
2519
+ try {
2520
+ return await use(proc);
2521
+ } finally {
2522
+ await proc.dispose();
2523
+ }
2524
+ }
2525
+ /** Saved sessions of a project, as Atomic lists them. */
2526
+ async listProjectSessions(cwd) {
2527
+ const sessions = parseAtomicSessionList(await this.withProjectAtomic(cwd, (proc) => proc.listSessions()));
2528
+ this.store.upsertMany(sessions);
2529
+ return sessions;
2530
+ }
2531
+ async findStoredSession(sessionId, cwd) {
2727
2532
  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;
2533
+ if (stored?.cwd && (!cwd || stored.cwd === cwd)) return stored;
2534
+ if (!cwd) return null;
2535
+ const listed = (await this.listProjectSessions(cwd)).some((s) => s.sessionId === sessionId);
2536
+ return listed ? { cwd } : null;
2537
+ }
2538
+ /** The listed title of a session, `''` once its name was cleared; null when Atomic has none. */
2539
+ async readSessionTitle(proc, sessionId) {
2540
+ try {
2541
+ return parseAtomicSessionList(await proc.listSessions()).find((s) => s.sessionId === sessionId)?.title ?? null;
2542
+ } catch {
2543
+ return null;
2544
+ }
2733
2545
  }
2734
2546
  async withSessionOperation(sessionId, operation) {
2735
2547
  const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
@@ -2759,14 +2571,14 @@ var AtomicAcpAgent = class {
2759
2571
  this.sessions.close(sessionId);
2760
2572
  }
2761
2573
  const mcpServers = opts?.mcpServers ?? existing?.mcpServers;
2762
- const stored = this.findStoredSession(sessionId, opts?.cwd);
2574
+ const stored = await this.findStoredSession(sessionId, opts?.cwd);
2763
2575
  if (!stored) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2764
2576
  const cwd = opts?.cwd ?? stored.cwd;
2765
2577
  let proc;
2766
2578
  try {
2767
2579
  proc = await AtomicRpcProcess.spawn({
2768
2580
  cwd,
2769
- sessionPath: stored.sessionFile,
2581
+ sessionId,
2770
2582
  atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND,
2771
2583
  mcpServers: atomicMcpServersForSpawn(mcpServers),
2772
2584
  headless: isHeadlessFromEnv()
@@ -2786,9 +2598,10 @@ var AtomicAcpAgent = class {
2786
2598
  headless: isHeadlessFromEnv()
2787
2599
  });
2788
2600
  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);
2601
+ if (!opts?.deferTitle) {
2602
+ const title = await this.readSessionTitle(proc, sessionId);
2603
+ if (title !== null) await session.publishTitle(title || null, null);
2604
+ }
2792
2605
  return session;
2793
2606
  } catch (error) {
2794
2607
  if (this.sessions.maybeGet(sessionId)?.proc === proc) this.sessions.close(sessionId);
@@ -2871,23 +2684,23 @@ var AtomicAcpAgent = class {
2871
2684
  ]);
2872
2685
  const availableModelsAuthErr = maybeAuthRequiredError(availableModelsErr);
2873
2686
  if (availableModelsAuthErr) {
2874
- this.cleanupFailedNewSession(session.sessionId, state);
2687
+ this.cleanupFailedNewSession(session.sessionId);
2875
2688
  throw availableModelsAuthErr;
2876
2689
  }
2877
2690
  if (availableModelsErr) {
2878
- this.cleanupFailedNewSession(session.sessionId, state);
2691
+ this.cleanupFailedNewSession(session.sessionId);
2879
2692
  throw RequestError4.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2880
2693
  }
2881
2694
  const rawModelsCount = Array.isArray(availableModels?.models) ? availableModels.models.length : 0;
2882
2695
  if (rawModelsCount === 0) {
2883
- this.cleanupFailedNewSession(session.sessionId, state);
2696
+ this.cleanupFailedNewSession(session.sessionId);
2884
2697
  throw RequestError4.authRequired(
2885
2698
  { authMethods: getAuthMethods() },
2886
2699
  "Configure an API key or log in with an OAuth provider."
2887
2700
  );
2888
2701
  }
2889
2702
  if (stateErr && maybeAuthRequiredError(stateErr)) {
2890
- this.cleanupFailedNewSession(session.sessionId, state);
2703
+ this.cleanupFailedNewSession(session.sessionId);
2891
2704
  throw RequestError4.authRequired(
2892
2705
  { authMethods: getAuthMethods() },
2893
2706
  "Configure an API key or log in with an OAuth provider."
@@ -2901,10 +2714,13 @@ var AtomicAcpAgent = class {
2901
2714
  if (stateErr) throw stateErr;
2902
2715
  configuration = await getSessionConfiguration(session.proc, { state, availableModels });
2903
2716
  } catch (err) {
2904
- this.cleanupFailedNewSession(session.sessionId, state);
2717
+ this.cleanupFailedNewSession(session.sessionId);
2905
2718
  throw maybeAuthRequiredError(err) ?? RequestError4.internalError({}, String(err));
2906
2719
  }
2907
2720
  const { configOptions, models, modes } = configuration;
2721
+ if (typeof state?.sessionId === "string") {
2722
+ this.store.upsert({ sessionId: session.sessionId, cwd: params.cwd });
2723
+ }
2908
2724
  const quietStartup = getQuietStartup(params.cwd);
2909
2725
  const updateNotice = buildUpdateNotice();
2910
2726
  const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
@@ -3162,8 +2978,8 @@ ${JSON.stringify(stats, null, 2)}`;
3162
2978
  if (atomicPath) {
3163
2979
  const resolved = realpathSync(atomicPath);
3164
2980
  const pkgRoot = dirname2(dirname2(resolved));
3165
- const p = join6(pkgRoot, "CHANGELOG.md");
3166
- if (existsSync4(p)) return p;
2981
+ const p = join5(pkgRoot, "CHANGELOG.md");
2982
+ if (existsSync3(p)) return p;
3167
2983
  }
3168
2984
  } catch {
3169
2985
  }
@@ -3171,8 +2987,8 @@ ${JSON.stringify(stats, null, 2)}`;
3171
2987
  const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
3172
2988
  const root = String(npmRoot.stdout ?? "").trim();
3173
2989
  if (root) {
3174
- const p = join6(root, "@bastani", "atomic", "CHANGELOG.md");
3175
- if (existsSync4(p)) return p;
2990
+ const p = join5(root, "@bastani", "atomic", "CHANGELOG.md");
2991
+ if (existsSync3(p)) return p;
3176
2992
  }
3177
2993
  } catch {
3178
2994
  }
@@ -3191,7 +3007,7 @@ ${JSON.stringify(stats, null, 2)}`;
3191
3007
  }
3192
3008
  let text = "";
3193
3009
  try {
3194
- text = readFileSync6(changelogPath, "utf-8");
3010
+ text = readFileSync5(changelogPath, "utf-8");
3195
3011
  } catch (e) {
3196
3012
  await this.conn.sessionUpdate({
3197
3013
  sessionId: session.sessionId,
@@ -3215,51 +3031,19 @@ ${JSON.stringify(stats, null, 2)}`;
3215
3031
  }
3216
3032
  if (cmd === "export") {
3217
3033
  const state = await session.proc.getState();
3218
- const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
3219
3034
  const messageCount = typeof state?.messageCount === "number" ? state.messageCount : 0;
3220
- if (!sessionFile || messageCount === 0 || !existsSync4(sessionFile)) {
3221
- await this.conn.sessionUpdate({
3222
- sessionId: session.sessionId,
3223
- update: {
3224
- 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 {
3035
+ if (messageCount === 0) {
3249
3036
  await this.conn.sessionUpdate({
3250
3037
  sessionId: session.sessionId,
3251
3038
  update: {
3252
3039
  sessionUpdate: "agent_message_chunk",
3253
- content: {
3254
- type: "text",
3255
- text: "Couldn't read session file for export. Try sending a prompt first."
3256
- }
3040
+ content: { type: "text", text: "Nothing to export yet (no session messages). Send a prompt first." }
3257
3041
  }
3258
3042
  });
3259
3043
  return { stopReason: "end_turn" };
3260
3044
  }
3261
3045
  const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
3262
- const outputPath = join6(session.cwd, `atomic-session-${safeSessionId}.html`);
3046
+ const outputPath = join5(session.cwd, `atomic-session-${safeSessionId}.html`);
3263
3047
  let resultPath = "";
3264
3048
  try {
3265
3049
  const result = await session.proc.exportHtml(outputPath);
@@ -3355,9 +3139,9 @@ ${JSON.stringify(stats, null, 2)}`;
3355
3139
  return this.listSessionsImpl(params);
3356
3140
  }
3357
3141
  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;
3142
+ const effectiveCwd = params.cwd ?? this.lastSessionCwd ?? process.cwd();
3143
+ if (!isAbsolute2(effectiveCwd)) throw RequestError4.invalidParams(`cwd must be an absolute path: ${effectiveCwd}`);
3144
+ const filtered = await this.listProjectSessions(effectiveCwd);
3361
3145
  const offset = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
3362
3146
  const start = Number.isFinite(offset) && offset > 0 ? offset : 0;
3363
3147
  const PAGE_SIZE = 50;
@@ -3399,8 +3183,7 @@ ${JSON.stringify(stats, null, 2)}`;
3399
3183
  throw err;
3400
3184
  }
3401
3185
  const { configOptions, models, modes } = configuration;
3402
- const stored = this.store.get(params.sessionId);
3403
- const title = stored?.sessionFile ? readAtomicSessionTitle(stored.sessionFile) : null;
3186
+ const title = await this.readSessionTitle(proc, params.sessionId);
3404
3187
  if (title !== null) await session.publishTitle(title || null, null);
3405
3188
  try {
3406
3189
  if (typeof proc.getCommands === "function") atomicCommands = await proc.getCommands();
@@ -3534,22 +3317,16 @@ ${JSON.stringify(stats, null, 2)}`;
3534
3317
  }, 0);
3535
3318
  return response;
3536
3319
  }
3537
- async deleteSession(params) {
3320
+ async unstable_deleteSession(params) {
3538
3321
  return this.withSessionOperation(params.sessionId, () => this.deleteSessionImpl(params));
3539
3322
  }
3540
3323
  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);
3324
+ const { sessionId } = params;
3325
+ const live = this.sessions.maybeGet(sessionId);
3326
+ const cwd = live?.cwd ?? this.store.get(sessionId)?.cwd ?? this.lastSessionCwd ?? process.cwd();
3327
+ if (live) await this.sessions.close(sessionId);
3328
+ await this.withProjectAtomic(cwd, (proc) => proc.deleteSession(sessionId), sessionId);
3329
+ this.store.delete(sessionId);
3553
3330
  return {};
3554
3331
  }
3555
3332
  async unstable_setSessionModel(params) {
@@ -3724,7 +3501,7 @@ function compareSemver(a, b) {
3724
3501
  function resolveAtomicExecutablePath() {
3725
3502
  const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3726
3503
  if (cmd.includes("/") || process.platform === "win32" && /^[a-z]:[\\/]/i.test(cmd)) {
3727
- return existsSync4(cmd) ? cmd : null;
3504
+ return existsSync3(cmd) ? cmd : null;
3728
3505
  }
3729
3506
  const whichCmd = process.platform === "win32" ? "where" : "which";
3730
3507
  const which = spawnSync(whichCmd, [cmd], { encoding: "utf-8" });
@@ -3774,16 +3551,16 @@ function buildStartupInfo(opts) {
3774
3551
  md.push("");
3775
3552
  };
3776
3553
  const contextItems = [];
3777
- const contextPath = join6(opts.cwd, "AGENTS.md");
3778
- if (existsSync4(contextPath)) contextItems.push(contextPath);
3554
+ const contextPath = join5(opts.cwd, "AGENTS.md");
3555
+ if (existsSync3(contextPath)) contextItems.push(contextPath);
3779
3556
  addSection("Context", contextItems);
3780
3557
  const skillsItems = [];
3781
3558
  const pushSkillFromRoot = (root) => {
3782
3559
  try {
3783
- for (const e of readdirSync3(root)) {
3784
- const p = join6(root, e);
3560
+ for (const e of readdirSync2(root)) {
3561
+ const p = join5(root, e);
3785
3562
  try {
3786
- const st = statSync3(p);
3563
+ const st = statSync2(p);
3787
3564
  if (st.isFile() && e.toLowerCase().endsWith(".md")) {
3788
3565
  skillsItems.push(p);
3789
3566
  }
@@ -3795,16 +3572,16 @@ function buildStartupInfo(opts) {
3795
3572
  const dir = stack.pop();
3796
3573
  let entries = [];
3797
3574
  try {
3798
- entries = readdirSync3(dir);
3575
+ entries = readdirSync2(dir);
3799
3576
  } catch {
3800
3577
  continue;
3801
3578
  }
3802
3579
  for (const name of entries) {
3803
3580
  if (name === "node_modules" || name === ".git") continue;
3804
- const p = join6(dir, name);
3581
+ const p = join5(dir, name);
3805
3582
  let st;
3806
3583
  try {
3807
- st = statSync3(p);
3584
+ st = statSync2(p);
3808
3585
  } catch {
3809
3586
  continue;
3810
3587
  }
@@ -3818,32 +3595,32 @@ function buildStartupInfo(opts) {
3818
3595
  } catch {
3819
3596
  }
3820
3597
  };
3821
- const globalSkillsDir = join6(getAgentDir(), "skills");
3598
+ const globalSkillsDir = join5(getAgentDir(), "skills");
3822
3599
  pushSkillFromRoot(globalSkillsDir);
3823
- const legacyAgentsSkillsDir = join6(process.env.HOME ?? "", ".agents", "skills");
3600
+ const legacyAgentsSkillsDir = join5(process.env.HOME ?? "", ".agents", "skills");
3824
3601
  pushSkillFromRoot(legacyAgentsSkillsDir);
3825
- const projectSkillsDir = join6(opts.cwd, ".atomic", "skills");
3602
+ const projectSkillsDir = join5(opts.cwd, ".atomic", "skills");
3826
3603
  pushSkillFromRoot(projectSkillsDir);
3827
3604
  addSection("Skills", skillsItems);
3828
3605
  const promptsItems = [];
3829
3606
  const agentDir = getAgentDir();
3830
- const promptsDir = join6(agentDir, "prompts");
3607
+ const promptsDir = join5(agentDir, "prompts");
3831
3608
  try {
3832
- const prompts = readdirSync3(promptsDir).filter((f) => f.endsWith(".md"));
3609
+ const prompts = readdirSync2(promptsDir).filter((f) => f.endsWith(".md"));
3833
3610
  for (const f of prompts) promptsItems.push(`/${basename2(f, ".md")}`);
3834
3611
  } catch {
3835
3612
  }
3836
3613
  addSection("Prompts", promptsItems);
3837
3614
  const extItems = [];
3838
- const extDir = join6(agentDir, "extensions");
3615
+ const extDir = join5(agentDir, "extensions");
3839
3616
  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));
3617
+ const exts = readdirSync2(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3618
+ for (const f of exts) extItems.push(join5(extDir, f));
3842
3619
  } catch {
3843
3620
  }
3844
- for (const settingsPath of [join6(agentDir, "settings.json"), join6(opts.cwd, ".atomic", "settings.json")]) {
3621
+ for (const settingsPath of [join5(agentDir, "settings.json"), join5(opts.cwd, ".atomic", "settings.json")]) {
3845
3622
  try {
3846
- const settings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
3623
+ const settings = JSON.parse(readFileSync5(settingsPath, "utf-8"));
3847
3624
  const packages = Array.isArray(settings.packages) ? settings.packages : [];
3848
3625
  for (const pkg2 of packages) {
3849
3626
  const source = typeof pkg2 === "string" ? pkg2 : pkg2?.source;
@@ -3866,9 +3643,9 @@ function readNearestPackageJson(metaUrl) {
3866
3643
  try {
3867
3644
  let dir = dirname2(fileURLToPath(metaUrl));
3868
3645
  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"));
3646
+ const p = join5(dir, "package.json");
3647
+ if (existsSync3(p)) {
3648
+ const json = JSON.parse(readFileSync5(p, "utf-8"));
3872
3649
  return { name: json?.name, version: json?.version };
3873
3650
  }
3874
3651
  dir = dirname2(dir);
@@ -3913,7 +3690,7 @@ function parseCliArgs(argv) {
3913
3690
 
3914
3691
  // src/index.ts
3915
3692
  async function writeAndExit(stream2, text, code) {
3916
- await new Promise((resolve3) => stream2.write(text, () => resolve3()));
3693
+ await new Promise((resolve2) => stream2.write(text, () => resolve2()));
3917
3694
  process.exit(code);
3918
3695
  }
3919
3696
  var cli = parseCliArgs(process.argv);
@@ -3953,15 +3730,15 @@ try {
3953
3730
  }
3954
3731
  var input = new WritableStream({
3955
3732
  write(chunk) {
3956
- return new Promise((resolve3) => {
3957
- if (process.stdout.destroyed || !process.stdout.writable) return resolve3();
3733
+ return new Promise((resolve2) => {
3734
+ if (process.stdout.destroyed || !process.stdout.writable) return resolve2();
3958
3735
  try {
3959
3736
  process.stdout.write(chunk, (err) => {
3960
3737
  void err;
3961
- resolve3();
3738
+ resolve2();
3962
3739
  });
3963
3740
  } catch {
3964
- resolve3();
3741
+ resolve2();
3965
3742
  }
3966
3743
  });
3967
3744
  }