@bastani/atomic 0.9.38-alpha.8 → 0.9.38-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.38-alpha.9] - 2026-10-17
6
+
7
+ ### Fixed
8
+
9
+ - Fixed slow interactive startup on machines with many sessions saved before the SQLite default, a follow-up to [#3721](https://github.com/bastani-inc/atomic/pull/3721). Opening a session by its exact ID, which the interactive engine does at launch, now looks up only that session instead of scanning `~/.atomic/agent/sessions`. `/resume`, `--resume`, and `--continue` list unconverted sessions larger than 32 KiB from their first message and most recent entries rather than parsing every file, so their message count is a lower bound and `/resume` search sees only that text until you open one, which still converts it in full.
10
+
5
11
  ## [0.9.38-alpha.8] - 2026-10-17
6
12
 
7
13
  ### Changed
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/intercom",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "private": true,
5
5
  "description": "Atomic extension providing a private coordination channel between parent and child agent sessions. Fork of: https://github.com/nicobailon/pi-intercom",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/mcp",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "private": true,
5
5
  "description": "Atomic's pi-compatible MCP integration for server connections, OAuth, tools, resources, and terminal management.",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/subagents",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "private": true,
5
5
  "description": "Atomic extension for delegating tasks to subagents with parallel execution. Fork of: https://github.com/nicobailon/pi-subagents",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/web-access",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "private": true,
5
5
  "description": "Atomic extension for web search, URL fetching, GitHub repo cloning, PDF/video extraction. Fork of: https://github.com/nicobailon/pi-web-access",
6
6
  "contributors": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/workflows",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "private": true,
5
5
  "description": "Atomic extension for multi-stage workflow authoring and execution.",
6
6
  "contributors": [
@@ -8,7 +8,8 @@ import type { SessionListQuery, SessionRecordHeader, SessionSnapshot, SessionSto
8
8
  * work. A legacy session is converted into the database only when it is opened,
9
9
  * following pi's migrate-on-load pattern; afterwards it is read from the database
10
10
  * like any other session. The JSONL files are never modified. Deleting a session
11
- * records its ID so a legacy copy of it is not listed again.
11
+ * records its ID so a legacy copy of it is not listed again. Listing reads a large legacy
12
+ * session only from its two ends, so its cost does not grow with the size of the history.
12
13
  */
13
14
  export declare class LegacySessionStore implements SessionStore {
14
15
  private readonly inner;
@@ -49,9 +50,11 @@ export declare class LegacySessionStore implements SessionStore {
49
50
  private legacyFiles;
50
51
  /** Header-only index of the legacy directory, read once; nothing writes legacy sessions any more. */
51
52
  private legacyIndex;
52
- /** Summaries are cached per store until a copy of the session changes on disk. */
53
+ /**
54
+ * Listing rows are cached per store until a copy of the session changes on disk. A row is built
55
+ * from bounded reads, not a full parse, so listing does not cost the size of the history.
56
+ */
53
57
  private summarize;
54
- private fileStamp;
55
58
  private legacyStore;
56
59
  private deletionDatabase;
57
60
  private isDeleted;
@@ -1 +1 @@
1
- {"version":3,"file":"legacy-session-store.d.ts","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAMnE,OAAO,KAAK,EACX,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB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AAS,CAAC,CAI5E;IAEK,MAAM,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAQ7C;IAEM,IAAI,CAAC,KAAK,EAAE,gBAAgB,GAAG,aAAa,CAAC,cAAc,CAAC,CAalE;IAEK,cAAc,CAAC,KAAK,EAAE;QAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;QACrB,QAAQ,CAAC,eAAe,CAAC,EAAE,OAAO,CAAC;KACnC,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAUtC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAY3B;IAED,gFAAgF;YAClE,OAAO;IAYrB,qGAAqG;YACvF,UAAU;YAcV,UAAU;YAMT,WAAW;IAc1B,qGAAqG;IACrG,OAAO,CAAC,WAAW;IAmBnB,kFAAkF;YACpE,SAAS;YAUT,SAAS;IAUvB,OAAO,CAAC,WAAW;IAOnB,OAAO,CAAC,gBAAgB;YAUV,SAAS;YAKT,WAAW;CAIzB"}
1
+ {"version":3,"file":"legacy-session-store.d.ts","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAOnE,OAAO,KAAK,EACX,gBAAgB,EAChB,mBAAmB,EACnB,eAAe,EACf,YAAY,EACZ,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,MAAM,YAAY,CAAC;AAIpB;;;;;;;;;;GAUG;AACH,qBAAa,kBAAmB,YAAW,YAAY;IACtD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAe;IACrC,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAS;IACtC,OAAO,CAAC,MAAM,CAAC,CAAyC;IACxD,OAAO,CAAC,KAAK,CAAC,CAA4D;IAC1E,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA0F;IACp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SAAS,CAAC,CAUtC;IAEK,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAY3B;IAED,gFAAgF;YAClE,OAAO;IAYrB,qGAAqG;YACvF,UAAU;YAcV,UAAU;YAMT,WAAW;IAc1B,qGAAqG;IACrG,OAAO,CAAC,WAAW;IAmBnB;;;OAGG;YACW,SAAS;IA0BvB,OAAO,CAAC,WAAW;IAOnB,OAAO,CAAC,gBAAgB;YAUV,SAAS;YAKT,WAAW;CAIzB"}
@@ -4,6 +4,7 @@ import { createSessionCwdMatcher } from "../../../utils/canonical-path.js";
4
4
  import { openNodeSqliteDatabase } from "../node-sqlite.js";
5
5
  import { SessionExistsError, SessionNotFoundError } from "./errors.js";
6
6
  import { JsonlSessionStore } from "./jsonl-session-store.js";
7
+ import { summarizeLegacySession } from "./legacy-session-summary.js";
7
8
  import { summarizeSession } from "./session-summary.js";
8
9
  const DELETED_TABLE = "session_legacy_deleted";
9
10
  /**
@@ -14,7 +15,8 @@ const DELETED_TABLE = "session_legacy_deleted";
14
15
  * work. A legacy session is converted into the database only when it is opened,
15
16
  * following pi's migrate-on-load pattern; afterwards it is read from the database
16
17
  * like any other session. The JSONL files are never modified. Deleting a session
17
- * records its ID so a legacy copy of it is not listed again.
18
+ * records its ID so a legacy copy of it is not listed again. Listing reads a large legacy
19
+ * session only from its two ends, so its cost does not grow with the size of the history.
18
20
  */
19
21
  export class LegacySessionStore {
20
22
  inner;
@@ -182,24 +184,36 @@ export class LegacySessionStore {
182
184
  })();
183
185
  return this.index;
184
186
  }
185
- /** Summaries are cached per store until a copy of the session changes on disk. */
187
+ /**
188
+ * Listing rows are cached per store until a copy of the session changes on disk. A row is built
189
+ * from bounded reads, not a full parse, so listing does not cost the size of the history.
190
+ */
186
191
  async summarize(sessionId) {
187
- const stamp = await this.fileStamp(sessionId);
192
+ const copies = await Promise.all(((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => ({
193
+ file,
194
+ stats: await stat(file.location).catch(() => undefined),
195
+ })));
196
+ const stamp = copies
197
+ .map(({ stats }) => (stats === undefined ? "missing" : `${stats.size}:${stats.mtimeMs}`))
198
+ .join("|");
188
199
  const cached = this.summaries.get(sessionId);
189
200
  if (cached !== undefined && cached.stamp === stamp)
190
201
  return cached.summary ?? undefined;
191
- const snapshot = await this.readLegacy(sessionId);
192
- const summary = snapshot === undefined ? null : summarizeSession(snapshot);
202
+ let summary = null;
203
+ for (const { file, stats } of copies) {
204
+ if (stats === undefined)
205
+ continue;
206
+ try {
207
+ summary = await summarizeLegacySession(file, stats.size, stats.mtimeMs);
208
+ break;
209
+ }
210
+ catch {
211
+ // Try the next copy.
212
+ }
213
+ }
193
214
  this.summaries.set(sessionId, { stamp, summary });
194
215
  return summary ?? undefined;
195
216
  }
196
- async fileStamp(sessionId) {
197
- const stamps = await Promise.all(((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => {
198
- const stats = await stat(file.location).catch(() => undefined);
199
- return stats === undefined ? "missing" : `${stats.size}:${stats.mtimeMs}`;
200
- }));
201
- return stamps.join("|");
202
- }
203
217
  legacyStore() {
204
218
  this.legacy ??= existsSync(this.legacyDirectory)
205
219
  ? JsonlSessionStore.open(this.legacyDirectory, { scanExisting: false }).catch(() => undefined)
@@ -1 +1 @@
1
- {"version":3,"file":"legacy-session-store.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAG3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAyB,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAA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,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;YAC9F,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC,MAAM,CAAC;IACpB,CAAC;IAEO,gBAAgB;QACvB,IAAI,CAAC,SAAS,KAAK,sBAAsB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;YACpF,MAAM,QAAQ,CAAC,IAAI,CAClB,8BAA8B,aAAa,oDAAoD,CAC/F,CAAC;YACF,OAAO,QAAQ,CAAC;QACjB,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC;IACvB,CAAC;IAEO,KAAK,CAAC,SAAS,CAAC,SAAiB;QACxC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAC/C,OAAO,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,kBAAkB,aAAa,eAAe,EAAE,SAAS,CAAC,CAAC,KAAK,SAAS,CAAC;IACtG,CAAC;IAEO,KAAK,CAAC,WAAW,CAAC,SAAiB;QAC1C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAC/C,MAAM,QAAQ,CAAC,GAAG,CAAC,yBAAyB,aAAa,gBAAgB,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IACnG,CAAC;CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createSessionCwdMatcher } from \"../../../utils/canonical-path.ts\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { SqliteDatabase } from \"../database.js\";\nimport { openNodeSqliteDatabase } from \"../node-sqlite.js\";\nimport { SessionExistsError, SessionNotFoundError } from \"./errors.js\";\nimport { type JsonlSessionFile, JsonlSessionStore } from \"./jsonl-session-store.js\";\nimport { summarizeSession } from \"./session-summary.js\";\nimport type {\n\tSessionListQuery,\n\tSessionRecordHeader,\n\tSessionSnapshot,\n\tSessionStore,\n\tSessionSummary,\n\tSessionWriteOptions,\n\tStorageDescriptor,\n} from \"./types.js\";\n\nconst DELETED_TABLE = \"session_legacy_deleted\";\n\n/**\n * The default session store, plus the JSONL sessions saved before it existed.\n *\n * Sessions from before the SQLite default stay in `<agentDir>/sessions` and are\n * listed from there, so `/resume` and `--continue` show them without any upfront\n * work. A legacy session is converted into the database only when it is opened,\n * following pi's migrate-on-load pattern; afterwards it is read from the database\n * like any other session. The JSONL files are never modified. Deleting a session\n * records its ID so a legacy copy of it is not listed again.\n */\nexport class LegacySessionStore implements SessionStore {\n\tprivate readonly inner: SessionStore;\n\tprivate readonly legacyDirectory: string;\n\tprivate readonly databasePath: string;\n\tprivate legacy?: Promise<JsonlSessionStore | undefined>;\n\tprivate index?: Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>>;\n\tprivate readonly summaries = new Map<string, { readonly stamp: string; readonly summary: SessionSummary | null }>();\n\tprivate deletions?: Promise<SqliteDatabase>;\n\n\tconstructor(inner: SessionStore, options: { readonly legacyDirectory: string; readonly databasePath: string }) {\n\t\tthis.inner = inner;\n\t\tthis.legacyDirectory = options.legacyDirectory;\n\t\tthis.databasePath = options.databasePath;\n\t}\n\n\tget descriptor(): StorageDescriptor {\n\t\treturn this.inner.descriptor;\n\t}\n\n\tcreate(header: SessionRecordHeader, entries: readonly SessionEntry[]): Promise<{ readonly lastSeq: number }> {\n\t\treturn this.inner.create(header, entries);\n\t}\n\n\tasync append(\n\t\tsessionId: string,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.append(sessionId, entries, options);\n\t}\n\n\tasync replace(\n\t\tsessionId: string,\n\t\theader: SessionRecordHeader,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.replace(sessionId, header, entries, options);\n\t}\n\n\tasync load(sessionId: string): Promise<SessionSnapshot> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.load(sessionId);\n\t}\n\n\tasync readHeader(sessionId: string): Promise<SessionRecordHeader | undefined> {\n\t\tconst header = await this.inner.readHeader(sessionId);\n\t\tif (header !== undefined) return header;\n\t\treturn (await this.findLegacy(sessionId))?.header;\n\t}\n\n\tasync delete(sessionId: string): Promise<void> {\n\t\tconst legacy = await this.findLegacy(sessionId);\n\t\tif (legacy !== undefined) await this.markDeleted(sessionId);\n\t\ttry {\n\t\t\tawait this.inner.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError) || legacy === undefined) throw error;\n\t\t}\n\t}\n\n\tasync *list(query: SessionListQuery): AsyncIterable<SessionSummary> {\n\t\tconst listed = new Set<string>();\n\t\tfor await (const summary of this.inner.list(query)) {\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif (listed.has(file.header.id) || (await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary === undefined) continue;\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t}\n\n\tasync findMostRecent(query: {\n\t\treadonly cwd: string;\n\t\treadonly includeInternal?: boolean;\n\t}): Promise<SessionSummary | undefined> {\n\t\tlet latest = await this.inner.findMostRecent(query);\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif ((await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary !== undefined && (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt))) {\n\t\t\t\tlatest = summary;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tconst legacy = this.legacy;\n\t\tconst deletions = this.deletions;\n\t\tthis.legacy = undefined;\n\t\tthis.deletions = undefined;\n\t\tthis.index = undefined;\n\t\tthis.summaries.clear();\n\t\tawait Promise.all([\n\t\t\tlegacy?.then((store) => store?.close()).catch(() => {}),\n\t\t\tdeletions?.then((database) => database.close()).catch(() => {}),\n\t\t]);\n\t\tawait this.inner.close();\n\t}\n\n\t/** Convert one legacy session into the database the first time it is needed. */\n\tprivate async convert(sessionId: string): Promise<void> {\n\t\tif ((await this.inner.readHeader(sessionId)) !== undefined) return;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tif (snapshot === undefined) return;\n\t\ttry {\n\t\t\tawait this.inner.create(snapshot.header, snapshot.entries);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionExistsError)) throw error;\n\t\t}\n\t\tif (await this.isDeleted(sessionId)) await this.inner.delete(sessionId).catch(() => {});\n\t}\n\n\t/** The first readable copy of a legacy session; a damaged duplicate does not hide a readable one. */\n\tprivate async readLegacy(sessionId: string): Promise<SessionSnapshot | undefined> {\n\t\tif (await this.isDeleted(sessionId)) return undefined;\n\t\tfor (const file of (await this.legacyIndex()).get(sessionId) ?? []) {\n\t\t\ttry {\n\t\t\t\tconst snapshot = await file.read();\n\t\t\t\tsummarizeSession(snapshot);\n\t\t\t\treturn snapshot;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async findLegacy(sessionId: string): Promise<JsonlSessionFile | undefined> {\n\t\tconst file = (await this.legacyIndex()).get(sessionId)?.[0];\n\t\tif (file === undefined || (await this.isDeleted(sessionId))) return undefined;\n\t\treturn file;\n\t}\n\n\tprivate async *legacyFiles(query: {\n\t\treadonly cwd?: string;\n\t\treadonly includeInternal?: boolean;\n\t}): AsyncIterable<JsonlSessionFile> {\n\t\tconst matchesCwd = query.cwd === undefined ? undefined : createSessionCwdMatcher(query.cwd);\n\t\tfor (const [file] of (await this.legacyIndex()).values()) {\n\t\t\tif (file === undefined) continue;\n\t\t\tif (matchesCwd && !matchesCwd(file.header.cwd)) continue;\n\t\t\tif (!query.includeInternal && file.header.internal) continue;\n\t\t\tif (await this.isDeleted(file.header.id)) continue;\n\t\t\tyield file;\n\t\t}\n\t}\n\n\t/** Header-only index of the legacy directory, read once; nothing writes legacy sessions any more. */\n\tprivate legacyIndex(): Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>> {\n\t\tthis.index ??= (async () => {\n\t\t\tconst files = new Map<string, JsonlSessionFile[]>();\n\t\t\tconst legacy = await this.legacyStore();\n\t\t\tif (legacy === undefined) return files;\n\t\t\ttry {\n\t\t\t\tfor await (const file of legacy.scanFiles()) {\n\t\t\t\t\tconst copies = files.get(file.header.id);\n\t\t\t\t\tif (copies) copies.push(file);\n\t\t\t\t\telse files.set(file.header.id, [file]);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// An unreadable legacy directory leaves only the sessions already in the database.\n\t\t\t}\n\t\t\treturn files;\n\t\t})();\n\t\treturn this.index;\n\t}\n\n\t/** Summaries are cached per store until a copy of the session changes on disk. */\n\tprivate async summarize(sessionId: string): Promise<SessionSummary | undefined> {\n\t\tconst stamp = await this.fileStamp(sessionId);\n\t\tconst cached = this.summaries.get(sessionId);\n\t\tif (cached !== undefined && cached.stamp === stamp) return cached.summary ?? undefined;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tconst summary = snapshot === undefined ? null : summarizeSession(snapshot);\n\t\tthis.summaries.set(sessionId, { stamp, summary });\n\t\treturn summary ?? undefined;\n\t}\n\n\tprivate async fileStamp(sessionId: string): Promise<string> {\n\t\tconst stamps = await Promise.all(\n\t\t\t((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => {\n\t\t\t\tconst stats = await stat(file.location).catch(() => undefined);\n\t\t\t\treturn stats === undefined ? \"missing\" : `${stats.size}:${stats.mtimeMs}`;\n\t\t\t}),\n\t\t);\n\t\treturn stamps.join(\"|\");\n\t}\n\n\tprivate legacyStore(): Promise<JsonlSessionStore | undefined> {\n\t\tthis.legacy ??= existsSync(this.legacyDirectory)\n\t\t\t? JsonlSessionStore.open(this.legacyDirectory, { scanExisting: false }).catch(() => undefined)\n\t\t\t: Promise.resolve(undefined);\n\t\treturn this.legacy;\n\t}\n\n\tprivate deletionDatabase(): Promise<SqliteDatabase> {\n\t\tthis.deletions ??= openNodeSqliteDatabase(this.databasePath).then(async (database) => {\n\t\t\tawait database.exec(\n\t\t\t\t`CREATE TABLE IF NOT EXISTS ${DELETED_TABLE}(id TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`,\n\t\t\t);\n\t\t\treturn database;\n\t\t});\n\t\treturn this.deletions;\n\t}\n\n\tprivate async isDeleted(sessionId: string): Promise<boolean> {\n\t\tconst database = await this.deletionDatabase();\n\t\treturn (await database.get(`SELECT id FROM ${DELETED_TABLE} WHERE id = ?`, sessionId)) !== undefined;\n\t}\n\n\tprivate async markDeleted(sessionId: string): Promise<void> {\n\t\tconst database = await this.deletionDatabase();\n\t\tawait database.run(`INSERT OR IGNORE INTO ${DELETED_TABLE} VALUES (?, ?)`, sessionId, Date.now());\n\t}\n}\n"]}
1
+ {"version":3,"file":"legacy-session-store.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AACxC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kCAAkC,CAAC;AAG3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,EAAyB,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AACrE,OAAO,EAA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U,CAAC,IAAI,CAAC,eAAe,CAAC;YAC/C,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,eAAe,EAAE,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;YAC9F,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;QAC9B,OAAO,IAAI,CAAC,MAAM,CAAC;IACpB,CAAC;IAEO,gBAAgB;QACvB,IAAI,CAAC,SAAS,KAAK,sBAAsB,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,IAAI,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;YACpF,MAAM,QAAQ,CAAC,IAAI,CAClB,8BAA8B,aAAa,oDAAoD,CAC/F,CAAC;YACF,OAAO,QAAQ,CAAC;QACjB,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC,SAAS,CAAC;IACvB,CAAC;IAEO,KAAK,CAAC,SAAS,CAAC,SAAiB;QACxC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAC/C,OAAO,CAAC,MAAM,QAAQ,CAAC,GAAG,CAAC,kBAAkB,aAAa,eAAe,EAAE,SAAS,CAAC,CAAC,KAAK,SAAS,CAAC;IACtG,CAAC;IAEO,KAAK,CAAC,WAAW,CAAC,SAAiB;QAC1C,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,gBAAgB,EAAE,CAAC;QAC/C,MAAM,QAAQ,CAAC,GAAG,CAAC,yBAAyB,aAAa,gBAAgB,EAAE,SAAS,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IACnG,CAAC;CACD","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { stat } from \"node:fs/promises\";\nimport { createSessionCwdMatcher } from \"../../../utils/canonical-path.ts\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { SqliteDatabase } from \"../database.js\";\nimport { openNodeSqliteDatabase } from \"../node-sqlite.js\";\nimport { SessionExistsError, SessionNotFoundError } from \"./errors.js\";\nimport { type JsonlSessionFile, JsonlSessionStore } from \"./jsonl-session-store.js\";\nimport { summarizeLegacySession } from \"./legacy-session-summary.js\";\nimport { summarizeSession } from \"./session-summary.js\";\nimport type {\n\tSessionListQuery,\n\tSessionRecordHeader,\n\tSessionSnapshot,\n\tSessionStore,\n\tSessionSummary,\n\tSessionWriteOptions,\n\tStorageDescriptor,\n} from \"./types.js\";\n\nconst DELETED_TABLE = \"session_legacy_deleted\";\n\n/**\n * The default session store, plus the JSONL sessions saved before it existed.\n *\n * Sessions from before the SQLite default stay in `<agentDir>/sessions` and are\n * listed from there, so `/resume` and `--continue` show them without any upfront\n * work. A legacy session is converted into the database only when it is opened,\n * following pi's migrate-on-load pattern; afterwards it is read from the database\n * like any other session. The JSONL files are never modified. Deleting a session\n * records its ID so a legacy copy of it is not listed again. Listing reads a large legacy\n * session only from its two ends, so its cost does not grow with the size of the history.\n */\nexport class LegacySessionStore implements SessionStore {\n\tprivate readonly inner: SessionStore;\n\tprivate readonly legacyDirectory: string;\n\tprivate readonly databasePath: string;\n\tprivate legacy?: Promise<JsonlSessionStore | undefined>;\n\tprivate index?: Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>>;\n\tprivate readonly summaries = new Map<string, { readonly stamp: string; readonly summary: SessionSummary | null }>();\n\tprivate deletions?: Promise<SqliteDatabase>;\n\n\tconstructor(inner: SessionStore, options: { readonly legacyDirectory: string; readonly databasePath: string }) {\n\t\tthis.inner = inner;\n\t\tthis.legacyDirectory = options.legacyDirectory;\n\t\tthis.databasePath = options.databasePath;\n\t}\n\n\tget descriptor(): StorageDescriptor {\n\t\treturn this.inner.descriptor;\n\t}\n\n\tcreate(header: SessionRecordHeader, entries: readonly SessionEntry[]): Promise<{ readonly lastSeq: number }> {\n\t\treturn this.inner.create(header, entries);\n\t}\n\n\tasync append(\n\t\tsessionId: string,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.append(sessionId, entries, options);\n\t}\n\n\tasync replace(\n\t\tsessionId: string,\n\t\theader: SessionRecordHeader,\n\t\tentries: readonly SessionEntry[],\n\t\toptions: SessionWriteOptions,\n\t): Promise<{ readonly lastSeq: number }> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.replace(sessionId, header, entries, options);\n\t}\n\n\tasync load(sessionId: string): Promise<SessionSnapshot> {\n\t\tawait this.convert(sessionId);\n\t\treturn this.inner.load(sessionId);\n\t}\n\n\tasync readHeader(sessionId: string): Promise<SessionRecordHeader | undefined> {\n\t\tconst header = await this.inner.readHeader(sessionId);\n\t\tif (header !== undefined) return header;\n\t\treturn (await this.findLegacy(sessionId))?.header;\n\t}\n\n\tasync delete(sessionId: string): Promise<void> {\n\t\tconst legacy = await this.findLegacy(sessionId);\n\t\tif (legacy !== undefined) await this.markDeleted(sessionId);\n\t\ttry {\n\t\t\tawait this.inner.delete(sessionId);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionNotFoundError) || legacy === undefined) throw error;\n\t\t}\n\t}\n\n\tasync *list(query: SessionListQuery): AsyncIterable<SessionSummary> {\n\t\tconst listed = new Set<string>();\n\t\tfor await (const summary of this.inner.list(query)) {\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif (listed.has(file.header.id) || (await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary === undefined) continue;\n\t\t\tlisted.add(summary.id);\n\t\t\tyield summary;\n\t\t}\n\t}\n\n\tasync findMostRecent(query: {\n\t\treadonly cwd: string;\n\t\treadonly includeInternal?: boolean;\n\t}): Promise<SessionSummary | undefined> {\n\t\tlet latest = await this.inner.findMostRecent(query);\n\t\tfor await (const file of this.legacyFiles(query)) {\n\t\t\tif ((await this.inner.readHeader(file.header.id)) !== undefined) continue;\n\t\t\tconst summary = await this.summarize(file.header.id);\n\t\t\tif (summary !== undefined && (!latest || Date.parse(summary.modifiedAt) > Date.parse(latest.modifiedAt))) {\n\t\t\t\tlatest = summary;\n\t\t\t}\n\t\t}\n\t\treturn latest;\n\t}\n\n\tasync close(): Promise<void> {\n\t\tconst legacy = this.legacy;\n\t\tconst deletions = this.deletions;\n\t\tthis.legacy = undefined;\n\t\tthis.deletions = undefined;\n\t\tthis.index = undefined;\n\t\tthis.summaries.clear();\n\t\tawait Promise.all([\n\t\t\tlegacy?.then((store) => store?.close()).catch(() => {}),\n\t\t\tdeletions?.then((database) => database.close()).catch(() => {}),\n\t\t]);\n\t\tawait this.inner.close();\n\t}\n\n\t/** Convert one legacy session into the database the first time it is needed. */\n\tprivate async convert(sessionId: string): Promise<void> {\n\t\tif ((await this.inner.readHeader(sessionId)) !== undefined) return;\n\t\tconst snapshot = await this.readLegacy(sessionId);\n\t\tif (snapshot === undefined) return;\n\t\ttry {\n\t\t\tawait this.inner.create(snapshot.header, snapshot.entries);\n\t\t} catch (error) {\n\t\t\tif (!(error instanceof SessionExistsError)) throw error;\n\t\t}\n\t\tif (await this.isDeleted(sessionId)) await this.inner.delete(sessionId).catch(() => {});\n\t}\n\n\t/** The first readable copy of a legacy session; a damaged duplicate does not hide a readable one. */\n\tprivate async readLegacy(sessionId: string): Promise<SessionSnapshot | undefined> {\n\t\tif (await this.isDeleted(sessionId)) return undefined;\n\t\tfor (const file of (await this.legacyIndex()).get(sessionId) ?? []) {\n\t\t\ttry {\n\t\t\t\tconst snapshot = await file.read();\n\t\t\t\tsummarizeSession(snapshot);\n\t\t\t\treturn snapshot;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async findLegacy(sessionId: string): Promise<JsonlSessionFile | undefined> {\n\t\tconst file = (await this.legacyIndex()).get(sessionId)?.[0];\n\t\tif (file === undefined || (await this.isDeleted(sessionId))) return undefined;\n\t\treturn file;\n\t}\n\n\tprivate async *legacyFiles(query: {\n\t\treadonly cwd?: string;\n\t\treadonly includeInternal?: boolean;\n\t}): AsyncIterable<JsonlSessionFile> {\n\t\tconst matchesCwd = query.cwd === undefined ? undefined : createSessionCwdMatcher(query.cwd);\n\t\tfor (const [file] of (await this.legacyIndex()).values()) {\n\t\t\tif (file === undefined) continue;\n\t\t\tif (matchesCwd && !matchesCwd(file.header.cwd)) continue;\n\t\t\tif (!query.includeInternal && file.header.internal) continue;\n\t\t\tif (await this.isDeleted(file.header.id)) continue;\n\t\t\tyield file;\n\t\t}\n\t}\n\n\t/** Header-only index of the legacy directory, read once; nothing writes legacy sessions any more. */\n\tprivate legacyIndex(): Promise<ReadonlyMap<string, readonly JsonlSessionFile[]>> {\n\t\tthis.index ??= (async () => {\n\t\t\tconst files = new Map<string, JsonlSessionFile[]>();\n\t\t\tconst legacy = await this.legacyStore();\n\t\t\tif (legacy === undefined) return files;\n\t\t\ttry {\n\t\t\t\tfor await (const file of legacy.scanFiles()) {\n\t\t\t\t\tconst copies = files.get(file.header.id);\n\t\t\t\t\tif (copies) copies.push(file);\n\t\t\t\t\telse files.set(file.header.id, [file]);\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t// An unreadable legacy directory leaves only the sessions already in the database.\n\t\t\t}\n\t\t\treturn files;\n\t\t})();\n\t\treturn this.index;\n\t}\n\n\t/**\n\t * Listing rows are cached per store until a copy of the session changes on disk. A row is built\n\t * from bounded reads, not a full parse, so listing does not cost the size of the history.\n\t */\n\tprivate async summarize(sessionId: string): Promise<SessionSummary | undefined> {\n\t\tconst copies = await Promise.all(\n\t\t\t((await this.legacyIndex()).get(sessionId) ?? []).map(async (file) => ({\n\t\t\t\tfile,\n\t\t\t\tstats: await stat(file.location).catch(() => undefined),\n\t\t\t})),\n\t\t);\n\t\tconst stamp = copies\n\t\t\t.map(({ stats }) => (stats === undefined ? \"missing\" : `${stats.size}:${stats.mtimeMs}`))\n\t\t\t.join(\"|\");\n\t\tconst cached = this.summaries.get(sessionId);\n\t\tif (cached !== undefined && cached.stamp === stamp) return cached.summary ?? undefined;\n\t\tlet summary: SessionSummary | null = null;\n\t\tfor (const { file, stats } of copies) {\n\t\t\tif (stats === undefined) continue;\n\t\t\ttry {\n\t\t\t\tsummary = await summarizeLegacySession(file, stats.size, stats.mtimeMs);\n\t\t\t\tbreak;\n\t\t\t} catch {\n\t\t\t\t// Try the next copy.\n\t\t\t}\n\t\t}\n\t\tthis.summaries.set(sessionId, { stamp, summary });\n\t\treturn summary ?? undefined;\n\t}\n\n\tprivate legacyStore(): Promise<JsonlSessionStore | undefined> {\n\t\tthis.legacy ??= existsSync(this.legacyDirectory)\n\t\t\t? JsonlSessionStore.open(this.legacyDirectory, { scanExisting: false }).catch(() => undefined)\n\t\t\t: Promise.resolve(undefined);\n\t\treturn this.legacy;\n\t}\n\n\tprivate deletionDatabase(): Promise<SqliteDatabase> {\n\t\tthis.deletions ??= openNodeSqliteDatabase(this.databasePath).then(async (database) => {\n\t\t\tawait database.exec(\n\t\t\t\t`CREATE TABLE IF NOT EXISTS ${DELETED_TABLE}(id TEXT PRIMARY KEY, deleted_at INTEGER NOT NULL)`,\n\t\t\t);\n\t\t\treturn database;\n\t\t});\n\t\treturn this.deletions;\n\t}\n\n\tprivate async isDeleted(sessionId: string): Promise<boolean> {\n\t\tconst database = await this.deletionDatabase();\n\t\treturn (await database.get(`SELECT id FROM ${DELETED_TABLE} WHERE id = ?`, sessionId)) !== undefined;\n\t}\n\n\tprivate async markDeleted(sessionId: string): Promise<void> {\n\t\tconst database = await this.deletionDatabase();\n\t\tawait database.run(`INSERT OR IGNORE INTO ${DELETED_TABLE} VALUES (?, ?)`, sessionId, Date.now());\n\t}\n}\n"]}
@@ -0,0 +1,11 @@
1
+ import type { JsonlSessionFile } from "./jsonl-session-store.js";
2
+ import type { SessionSummary } from "./types.js";
3
+ /**
4
+ * Summarizes an unconverted legacy session without parsing all of it. A session larger than the
5
+ * window is described by its header, the lines up to its first user message, and the lines in its
6
+ * last window. Names, summaries and search text written in between are not seen, and the message
7
+ * count is a lower bound; opening the session converts it in full. A line in either end that
8
+ * cannot be parsed marks the copy as damaged, as it would for a full read.
9
+ */
10
+ export declare function summarizeLegacySession(file: JsonlSessionFile, size: number, modifiedMs: number): Promise<SessionSummary>;
11
+ //# sourceMappingURL=legacy-session-summary.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-session-summary.d.ts","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-summary.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAOjE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AA4EjD;;;;;;GAMG;AACH,wBAAsB,sBAAsB,CAC3C,IAAI,EAAE,gBAAgB,EACtB,IAAI,EAAE,MAAM,EACZ,UAAU,EAAE,MAAM,GAChB,OAAO,CAAC,cAAc,CAAC,CAazB"}
@@ -0,0 +1,103 @@
1
+ import { open } from "node:fs/promises";
2
+ import { applySessionSummaryEntries, materializeSessionSummaryMetadata, summarizeSession, } from "./session-summary.js";
3
+ /** A session this size or smaller is read whole; a larger one is read from its two ends only. */
4
+ const SUMMARY_WINDOW_BYTES = 32 * 1024;
5
+ /** How far into a large session to look for its first user message before reading it whole. */
6
+ const HEAD_SCAN_LIMIT_BYTES = 256 * 1024;
7
+ const HEAD_CHUNK_BYTES = 16 * 1024;
8
+ const NEWLINE = 10;
9
+ function applyLine(scan, line) {
10
+ if (!line.trim())
11
+ return;
12
+ const { state, texts } = applySessionSummaryEntries(scan.state, [JSON.parse(line)]);
13
+ scan.state = state;
14
+ for (const { text } of texts)
15
+ scan.texts.push(text);
16
+ }
17
+ /** Reads entries up to the first user message; returns the offset after the last line consumed. */
18
+ async function scanHead(handle, scan) {
19
+ const chunk = Buffer.alloc(HEAD_CHUNK_BYTES);
20
+ let pending = Buffer.alloc(0);
21
+ let offset = 0;
22
+ let end = 0;
23
+ let header = true;
24
+ while (offset < HEAD_SCAN_LIMIT_BYTES) {
25
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, offset);
26
+ if (bytesRead === 0) {
27
+ if (pending.length > 0)
28
+ applyLine(scan, pending.toString("utf8"));
29
+ return { end: end + pending.length, complete: true };
30
+ }
31
+ offset += bytesRead;
32
+ pending = Buffer.concat([pending, chunk.subarray(0, bytesRead)]);
33
+ for (let newline = pending.indexOf(NEWLINE); newline !== -1; newline = pending.indexOf(NEWLINE)) {
34
+ const line = pending.subarray(0, newline).toString("utf8");
35
+ pending = pending.subarray(newline + 1);
36
+ end += newline + 1;
37
+ if (header)
38
+ header = false;
39
+ else
40
+ applyLine(scan, line);
41
+ if (scan.state.firstMessage)
42
+ return { end, complete: true };
43
+ }
44
+ }
45
+ return { end, complete: false };
46
+ }
47
+ /**
48
+ * Reads the last window of the file, from the first whole line in it, never re-reading the head.
49
+ * Returns false when the window skips part of the file and holds no complete message, so the
50
+ * latest message time is unknown and the caller must read the session whole.
51
+ */
52
+ async function scanTail(handle, size, headEnd, scan) {
53
+ const start = Math.max(size - SUMMARY_WINDOW_BYTES, headEnd);
54
+ if (start >= size)
55
+ return true;
56
+ const skipsMiddle = start > headEnd;
57
+ const bytes = Buffer.alloc(size - start + 1);
58
+ let filled = 0;
59
+ while (filled < bytes.length) {
60
+ const { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, start - 1 + filled);
61
+ if (bytesRead === 0)
62
+ break;
63
+ filled += bytesRead;
64
+ }
65
+ let from = 1;
66
+ if (bytes[0] !== NEWLINE) {
67
+ const newline = bytes.subarray(0, filled).indexOf(NEWLINE, 1);
68
+ if (newline === -1)
69
+ return !skipsMiddle;
70
+ from = newline + 1;
71
+ }
72
+ if (skipsMiddle)
73
+ scan.state = { ...scan.state, latestMessageTime: null };
74
+ for (const line of bytes.subarray(from, filled).toString("utf8").split("\n"))
75
+ applyLine(scan, line);
76
+ return !skipsMiddle || scan.state.latestMessageTime !== null;
77
+ }
78
+ /**
79
+ * Summarizes an unconverted legacy session without parsing all of it. A session larger than the
80
+ * window is described by its header, the lines up to its first user message, and the lines in its
81
+ * last window. Names, summaries and search text written in between are not seen, and the message
82
+ * count is a lower bound; opening the session converts it in full. A line in either end that
83
+ * cannot be parsed marks the copy as damaged, as it would for a full read.
84
+ */
85
+ export async function summarizeLegacySession(file, size, modifiedMs) {
86
+ if (size <= SUMMARY_WINDOW_BYTES)
87
+ return summarizeSession(await file.read());
88
+ const scan = { state: applySessionSummaryEntries(undefined, []).state, texts: [] };
89
+ const handle = await open(file.location, "r");
90
+ try {
91
+ const head = await scanHead(handle, scan);
92
+ if (!head.complete)
93
+ return summarizeSession(await file.read());
94
+ if (!(await scanTail(handle, size, head.end, scan)))
95
+ return summarizeSession(await file.read());
96
+ }
97
+ finally {
98
+ await handle.close();
99
+ }
100
+ const state = { ...scan.state, latestMessageTime: scan.state.latestMessageTime ?? modifiedMs };
101
+ return { ...materializeSessionSummaryMetadata(file.header, state), searchText: scan.texts.join(" ") };
102
+ }
103
+ //# sourceMappingURL=legacy-session-summary.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"legacy-session-summary.js","sourceRoot":"","sources":["../../../../src/core/storage/session/legacy-session-summary.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAGzD,OAAO,EACN,0BAA0B,EAC1B,iCAAiC,EAEjC,gBAAgB,GAChB,MAAM,sBAAsB,CAAC;AAG9B,iGAAiG;AACjG,MAAM,oBAAoB,GAAG,EAAE,GAAG,IAAI,CAAC;AAEvC,+FAA+F;AAC/F,MAAM,qBAAqB,GAAG,GAAG,GAAG,IAAI,CAAC;AACzC,MAAM,gBAAgB,GAAG,EAAE,GAAG,IAAI,CAAC;AACnC,MAAM,OAAO,GAAG,EAAE,CAAC;AAOnB,SAAS,SAAS,CAAC,IAAU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SAAS,EAAE,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC;IACzF,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;IAC9C,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;QAC1C,IAAI,CAAC,IAAI,CAAC,QAAQ;YAAE,OAAO,gBAAgB,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QAC/D,IAAI,CAAC,CAAC,MAAM,QAAQ,CAAC,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;YAAE,OAAO,gBAAgB,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;IACjG,CAAC;YAAS,CAAC;QACV,MAAM,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IACD,MAAM,KAAK,GAAG,EAAE,GAAG,IAAI,CAAC,KAAK,EAAE,iBAAiB,EAAE,IAAI,CAAC,KAAK,CAAC,iBAAiB,IAAI,UAAU,EAAE,CAAC;IAC/F,OAAO,EAAE,GAAG,iCAAiC,CAAC,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC,EAAE,UAAU,EAAE,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AACvG,CAAC","sourcesContent":["import { type FileHandle, open } from \"node:fs/promises\";\nimport type { SessionEntry } from \"../../session-manager-types.ts\";\nimport type { JsonlSessionFile } from \"./jsonl-session-store.js\";\nimport {\n\tapplySessionSummaryEntries,\n\tmaterializeSessionSummaryMetadata,\n\ttype SessionSummaryState,\n\tsummarizeSession,\n} from \"./session-summary.js\";\nimport type { SessionSummary } from \"./types.js\";\n\n/** A session this size or smaller is read whole; a larger one is read from its two ends only. */\nconst SUMMARY_WINDOW_BYTES = 32 * 1024;\n\n/** How far into a large session to look for its first user message before reading it whole. */\nconst HEAD_SCAN_LIMIT_BYTES = 256 * 1024;\nconst HEAD_CHUNK_BYTES = 16 * 1024;\nconst NEWLINE = 10;\n\ninterface Scan {\n\tstate: SessionSummaryState;\n\ttexts: string[];\n}\n\nfunction applyLine(scan: Scan, line: string): void {\n\tif (!line.trim()) return;\n\tconst { state, texts } = applySessionSummaryEntries(scan.state, [JSON.parse(line) as SessionEntry]);\n\tscan.state = state;\n\tfor (const { text } of texts) scan.texts.push(text);\n}\n\n/** Reads entries up to the first user message; returns the offset after the last line consumed. */\nasync function scanHead(handle: FileHandle, scan: Scan): Promise<{ end: number; complete: boolean }> {\n\tconst chunk = Buffer.alloc(HEAD_CHUNK_BYTES);\n\tlet pending = Buffer.alloc(0);\n\tlet offset = 0;\n\tlet end = 0;\n\tlet header = true;\n\twhile (offset < HEAD_SCAN_LIMIT_BYTES) {\n\t\tconst { bytesRead } = await handle.read(chunk, 0, chunk.length, offset);\n\t\tif (bytesRead === 0) {\n\t\t\tif (pending.length > 0) applyLine(scan, pending.toString(\"utf8\"));\n\t\t\treturn { end: end + pending.length, complete: true };\n\t\t}\n\t\toffset += bytesRead;\n\t\tpending = Buffer.concat([pending, chunk.subarray(0, bytesRead)]);\n\t\tfor (let newline = pending.indexOf(NEWLINE); newline !== -1; newline = pending.indexOf(NEWLINE)) {\n\t\t\tconst line = pending.subarray(0, newline).toString(\"utf8\");\n\t\t\tpending = pending.subarray(newline + 1);\n\t\t\tend += newline + 1;\n\t\t\tif (header) header = false;\n\t\t\telse applyLine(scan, line);\n\t\t\tif (scan.state.firstMessage) return { end, complete: true };\n\t\t}\n\t}\n\treturn { end, complete: false };\n}\n\n/**\n * Reads the last window of the file, from the first whole line in it, never re-reading the head.\n * Returns false when the window skips part of the file and holds no complete message, so the\n * latest message time is unknown and the caller must read the session whole.\n */\nasync function scanTail(handle: FileHandle, size: number, headEnd: number, scan: Scan): Promise<boolean> {\n\tconst start = Math.max(size - SUMMARY_WINDOW_BYTES, headEnd);\n\tif (start >= size) return true;\n\tconst skipsMiddle = start > headEnd;\n\tconst bytes = Buffer.alloc(size - start + 1);\n\tlet filled = 0;\n\twhile (filled < bytes.length) {\n\t\tconst { bytesRead } = await handle.read(bytes, filled, bytes.length - filled, start - 1 + filled);\n\t\tif (bytesRead === 0) break;\n\t\tfilled += bytesRead;\n\t}\n\tlet from = 1;\n\tif (bytes[0] !== NEWLINE) {\n\t\tconst newline = bytes.subarray(0, filled).indexOf(NEWLINE, 1);\n\t\tif (newline === -1) return !skipsMiddle;\n\t\tfrom = newline + 1;\n\t}\n\tif (skipsMiddle) scan.state = { ...scan.state, latestMessageTime: null };\n\tfor (const line of bytes.subarray(from, filled).toString(\"utf8\").split(\"\\n\")) applyLine(scan, line);\n\treturn !skipsMiddle || scan.state.latestMessageTime !== null;\n}\n\n/**\n * Summarizes an unconverted legacy session without parsing all of it. A session larger than the\n * window is described by its header, the lines up to its first user message, and the lines in its\n * last window. Names, summaries and search text written in between are not seen, and the message\n * count is a lower bound; opening the session converts it in full. A line in either end that\n * cannot be parsed marks the copy as damaged, as it would for a full read.\n */\nexport async function summarizeLegacySession(\n\tfile: JsonlSessionFile,\n\tsize: number,\n\tmodifiedMs: number,\n): Promise<SessionSummary> {\n\tif (size <= SUMMARY_WINDOW_BYTES) return summarizeSession(await file.read());\n\tconst scan: Scan = { state: applySessionSummaryEntries(undefined, []).state, texts: [] };\n\tconst handle = await open(file.location, \"r\");\n\ttry {\n\t\tconst head = await scanHead(handle, scan);\n\t\tif (!head.complete) return summarizeSession(await file.read());\n\t\tif (!(await scanTail(handle, size, head.end, scan))) return summarizeSession(await file.read());\n\t} finally {\n\t\tawait handle.close();\n\t}\n\tconst state = { ...scan.state, latestMessageTime: scan.state.latestMessageTime ?? modifiedMs };\n\treturn { ...materializeSessionSummaryMetadata(file.header, state), searchText: scan.texts.join(\" \") };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"main-session.d.ts","sourceRoot":"","sources":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ACvB,MAAM,EAAE,IAAI,EACZ,eAAe,EAAE,eAAe,EAChC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,GAC5C,OAAO,CAAC,YAAY,GAAG,SAAS,CAAC,CA6BnC;AAED,wBAAsB,oBAAoB,CACzC,MAAM,EAAE,IAAI,EACZ,GAAG,EAAE,MAAM,EACX,UAAU,EAAE,MAAM,GAAG,SAAS,EAC9B,eAAe,EAAE,eAAe,EAChC,YAAY,CAAC,EAAE,YAAY,GAAG,gBAAgB,GAC5C,OAAO,CAAC,cAAc,CAAC,CA2BzB;AAmGD,wBAAsB,0BAA0B,CAC/C,KAAK,EAAE,eAAe,EACtB,eAAe,EAAE,eAAe,GAC9B,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CA8B7B"}
@@ -19,10 +19,13 @@ async function findLocalSessionByExactId(sessionId, cwd, store) {
19
19
  return header &&
20
20
  !classifiedWorkflowMetadata(header) &&
21
21
  createSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))
22
- ? { id: header.id }
22
+ ? { id: header.id, cwd: header.cwd }
23
23
  : undefined;
24
24
  }
25
25
  async function resolveSessionId(sessionArg, cwd, store) {
26
+ const exact = await findLocalSessionByExactId(sessionArg, cwd, store).catch(() => undefined);
27
+ if (exact)
28
+ return { type: "local", id: exact.id, cwd: exact.cwd };
26
29
  const localSessions = await SessionManager.list(cwd, store, undefined, { includeInternal: true });
27
30
  const resolution = await resolveSessionIdTargetAcrossScopes(sessionArg, localSessions, () => SessionManager.listAll(store, undefined, { includeInternal: true }));
28
31
  if (resolution.kind === "exact" || resolution.kind === "unique_prefix") {
@@ -1 +1 @@
1
- {"version":3,"file":"main-session.js","sourceRoot":"","sources":["../src/main-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAChH,OAAO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,IAAI,OAAO,EAAE,CAAC;gBACb,OAAO;YACR,CAAC;YACD,OAAO,GAAG,IAAI,CAAC;YACf,EAAE,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,CAAC,MAAM,CAAC,CAAC;QACjB,CAAC,CAAC;QAEF,MAAM,QAAQ,GAAG,IAAI,0BAA0B,CAC9C,6BAA6B,CAAC,KAAK,CAAC,EACpC,CAAC,UAAU,EAAE,QAAQ,CAAC,EACtB,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,EACzE,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,EACvB,EAAE,GAAG,EAAE,EAAE,EAAE,CACX,CAAC;QACF,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACtB,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACtB,EAAE,CAAC,KAAK,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { createInterface } from \"node:readline\";\nimport { ProcessTerminal, setCapabilityOverrides, setKeybindings, TuiMainScreen } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport type { Args } from \"./cli/args.ts\";\nimport { selectSession } from \"./cli/session-picker.ts\";\nimport { getAgentDir } from \"./config.js\";\nimport { KeybindingsManager } from \"./core/keybindings.ts\";\nimport { formatMissingSessionCwdPrompt, type SessionCwdIssue } from \"./core/session-cwd.ts\";\nimport { ownedSessionManagerStores } from \"./core/session-lifecycle-work.ts\";\nimport { assertValidSessionId, SessionManager } from \"./core/session-manager.ts\";\nimport { classifiedWorkflowMetadata, workflowSessionMetadataFromEnv } from \"./core/session-manager-classification.ts\";\nimport { resolveSessionStore, selectSessionStorage } from \"./core/session-storage.js\";\nimport type { SettingsManager } from \"./core/settings-manager.ts\";\nimport { type StorageSelection, storageSelectionKey } from \"./core/storage/provider.js\";\nimport type { SessionStore } from \"./core/storage/session/types.js\";\nimport { ExtensionSelectorComponent } from \"./modes/interactive/components/extension-selector.ts\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.js\";\nimport { resolveSessionIdTargetAcrossScopes } from \"./session-id-target.js\";\nimport { createSessionCwdMatcher, resolvePath } from \"./utils/paths.ts\";\n\ntype ResolvedSession =\n\t| { type: \"local\" | \"global\"; id: string; cwd: string }\n\t| { type: \"error\"; message: string }\n\t| { type: \"not_found\"; arg: string };\n\nasync function findLocalSessionByExactId(sessionId: string, cwd: string, store: SessionStore) {\n\tconst header = await store.readHeader(sessionId);\n\treturn header &&\n\t\t!classifiedWorkflowMetadata(header) &&\n\t\tcreateSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))\n\t\t? { id: header.id }\n\t\t: undefined;\n}\n\nasync function resolveSessionId(sessionArg: string, cwd: string, store: SessionStore): Promise<ResolvedSession> {\n\tconst localSessions = await SessionManager.list(cwd, store, undefined, { includeInternal: true });\n\tconst resolution = await resolveSessionIdTargetAcrossScopes(sessionArg, localSessions, () =>\n\t\tSessionManager.listAll(store, undefined, { includeInternal: true }),\n\t);\n\tif (resolution.kind === \"exact\" || resolution.kind === \"unique_prefix\") {\n\t\treturn {\n\t\t\ttype: resolution.scope,\n\t\t\tid: resolution.session.id,\n\t\t\tcwd: resolution.session.cwd,\n\t\t};\n\t}\n\tif (resolution.kind === \"ambiguous\" || resolution.kind === \"malformed\") {\n\t\treturn { type: \"error\", message: resolution.message };\n\t}\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nexport class SessionSelectorConflictError extends Error {\n\treadonly code = \"SessionSelectorConflict\";\n\treadonly conflictingFlags: readonly string[];\n\n\tconstructor(conflictingFlags: readonly string[]) {\n\t\tsuper(\n\t\t\t`--import cannot be combined with ${conflictingFlags.join(\", \")}. Use --import alone, optionally with --no-session or --session-dir.`,\n\t\t);\n\t\tthis.name = \"SessionSelectorConflictError\";\n\t\tthis.conflictingFlags = conflictingFlags;\n\t}\n}\n\nexport function validateImportFlags(parsed: Args): void {\n\tif (parsed.import === undefined) return;\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.fork !== undefined ? \"--fork\" : undefined,\n\t\tparsed.sessionId !== undefined ? \"--session-id\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\tif (conflictingFlags.length > 0) throw new SessionSelectorConflictError(conflictingFlags);\n}\n\nexport function validateForkFlags(parsed: Args): void {\n\tif (parsed.fork === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nexport function validateSessionIdFlags(parsed: Args): void {\n\tif (parsed.sessionId === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tassertValidSessionId(parsed.sessionId);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\nasync function forkSessionOrExit(\n\tsourceId: string,\n\tcwd: string,\n\tstore: SessionStore,\n\tsessionId?: string,\n): Promise<SessionManager> {\n\ttry {\n\t\tconst source = await SessionManager.open(store, sourceId);\n\t\treturn await source.forkTo(cwd, store, { id: sessionId });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function openSessionOrExit(sessionId: string, store: SessionStore): Promise<SessionManager> {\n\ttry {\n\t\treturn await SessionManager.open(store, sessionId);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nexport async function applyInheritedWorkflowSessionClassification(\n\tsessionManager: SessionManager,\n\tenv: Record<string, string | undefined> = process.env,\n): Promise<SessionManager> {\n\tconst metadata = workflowSessionMetadataFromEnv(env);\n\tif (metadata) await sessionManager.markSessionInternal(metadata);\n\treturn sessionManager;\n}\n\nconst initialStorageKeys = new WeakMap<SessionManager, string>();\nconst provisionalSessions = new WeakSet<SessionManager>();\n\nasync function createProvisionalSession(store: SessionStore, cwd: string, id?: string): Promise<SessionManager> {\n\tconst manager = await SessionManager.create(store, cwd, { id });\n\tprovisionalSessions.add(manager);\n\treturn manager;\n}\n\n/** Finalize a CLI-owned provisional store after trusted settings become available. */\nexport async function refreshSessionStorage(\n\tmanager: SessionManager,\n\tparsed: Args,\n\tsettingsManager: SettingsManager,\n\tsessionStore?: SessionStore | StorageSelection,\n): Promise<SessionStore | undefined> {\n\t// An opened conversation belongs to the store that supplied it, even when its\n\t// project's newly trusted settings select a different store for new sessions.\n\tif (!provisionalSessions.has(manager) || manager.getEntries().length > 0) return undefined;\n\tconst options = {\n\t\tsessionStore,\n\t\tsettings: settingsManager.getSettings(),\n\t\tnoSession: parsed.noSession,\n\t\tsessionDir: parsed.sessionDir,\n\t\tsessionStorePath: parsed.sessionStorePath,\n\t\tsessionPrefix: parsed.sessionPrefix,\n\t};\n\tconst selection = selectSessionStorage(manager.getCwd(), options);\n\tif (\"load\" in selection) return undefined;\n\tconst key = storageSelectionKey(selection, getAgentDir());\n\tconst initialKey = initialStorageKeys.get(manager);\n\tif (initialKey === undefined || key === initialKey) return undefined;\n\tconst previous = manager.getSessionStore();\n\tconst next = await resolveSessionStore(manager.getCwd(), options);\n\ttry {\n\t\tawait manager.rebindStore(next, true);\n\t} catch (error) {\n\t\tawait next.close();\n\t\tthrow error;\n\t}\n\tinitialStorageKeys.set(manager, key);\n\townedSessionManagerStores.set(manager, next);\n\tawait previous.close();\n\treturn next;\n}\n\nexport async function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n\tsessionStore?: SessionStore | StorageSelection,\n): Promise<SessionManager> {\n\tvalidateImportFlags(parsed);\n\tconst store = await resolveSessionStore(cwd, {\n\t\tsessionStore,\n\t\tsettings: settingsManager.getSettings(),\n\t\tnoSession: parsed.noSession,\n\t\tsessionDir: parsed.sessionDir ?? sessionDir,\n\t\tsessionStorePath: parsed.sessionStorePath,\n\t\tsessionPrefix: parsed.sessionPrefix,\n\t});\n\ttry {\n\t\tconst manager = await createSessionManagerWithStore(parsed, cwd, settingsManager, store);\n\t\tif (store !== sessionStore) ownedSessionManagerStores.set(manager, store);\n\t\tconst selection = selectSessionStorage(cwd, {\n\t\t\tsessionStore,\n\t\t\tsettings: settingsManager.getSettings(),\n\t\t\tnoSession: parsed.noSession,\n\t\t\tsessionDir: parsed.sessionDir ?? sessionDir,\n\t\t\tsessionStorePath: parsed.sessionStorePath,\n\t\t\tsessionPrefix: parsed.sessionPrefix,\n\t\t});\n\t\tif (!(\"load\" in selection)) initialStorageKeys.set(manager, storageSelectionKey(selection, getAgentDir()));\n\t\treturn manager;\n\t} catch (error) {\n\t\tif (store !== sessionStore) await store.close();\n\t\tthrow error;\n\t}\n}\n\nasync function createSessionManagerWithStore(\n\tparsed: Args,\n\tcwd: string,\n\tsettingsManager: SettingsManager,\n\tstore: SessionStore,\n): Promise<SessionManager> {\n\tif (parsed.import !== undefined) return SessionManager.importFromJsonl(resolvePath(parsed.import, cwd), cwd, store);\n\tif (parsed.noSession) return createProvisionalSession(store, cwd, parsed.sessionId);\n\n\tif (parsed.fork !== undefined) {\n\t\tif (parsed.sessionId !== undefined) {\n\t\t\tconst existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, store);\n\t\t\tif (existingTarget) {\n\t\t\t\tconsole.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\n\t\tconst resolved = await resolveSessionId(parsed.fork, cwd, store);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.id, cwd, store, parsed.sessionId);\n\t\t\tcase \"error\":\n\t\t\t\tconsole.error(chalk.red(`Error: ${resolved.message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t\tthrow new Error(\"unreachable\");\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session !== undefined) {\n\t\tconst resolved = await resolveSessionId(parsed.session, cwd, store);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"local\":\n\t\t\t\treturn openSessionOrExit(resolved.id, store);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.id, cwd, store);\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tconsole.error(chalk.red(`Error: ${resolved.message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t\tthrow new Error(\"unreachable\");\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\tinitTheme(settingsManager.getTheme(), true);\n\t\ttry {\n\t\t\tconst selected = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, store, onProgress),\n\t\t\t\t(onProgress) => SessionManager.listAll(store, onProgress),\n\t\t\t\tsettingsManager,\n\t\t\t\tstore.descriptor.adapter === \"jsonl\" ? undefined : (id) => store.delete(id),\n\t\t\t);\n\t\t\tif (selected === null) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn openSessionOrExit(selected.id, store);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\tconst recent = await store.findMostRecent({ cwd: resolvePath(cwd) });\n\t\treturn recent ? SessionManager.open(store, recent.id) : createProvisionalSession(store, cwd);\n\t}\n\n\tif (parsed.sessionId !== undefined) {\n\t\tconst existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, store);\n\t\tif (existingSession) {\n\t\t\treturn openSessionOrExit(existingSession.id, store);\n\t\t}\n\t\tconsole.error(chalk.yellow(`No session found with id '${parsed.sessionId}'; creating a new session.`));\n\t}\n\n\treturn createProvisionalSession(store, cwd, parsed.sessionId);\n}\n\nexport async function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise<string | undefined> {\n\tsetCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides());\n\tinitTheme(settingsManager.getTheme());\n\tsetKeybindings(KeybindingsManager.create());\n\n\treturn new Promise((resolve) => {\n\t\tconst ui = new TuiMainScreen(new ProcessTerminal(), settingsManager.getShowHardwareCursor(), getAgentDir());\n\t\tui.setClearOnShrink(settingsManager.getClearOnShrink());\n\n\t\tlet settled = false;\n\t\tconst finish = (result: string | undefined) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tui.stop();\n\t\t\tresolve(result);\n\t\t};\n\n\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\tformatMissingSessionCwdPrompt(issue),\n\t\t\t[\"Continue\", \"Cancel\"],\n\t\t\t(option) => finish(option === \"Continue\" ? issue.fallbackCwd : undefined),\n\t\t\t() => finish(undefined),\n\t\t\t{ tui: ui },\n\t\t);\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector);\n\t\tui.start();\n\t});\n}\n"]}
1
+ {"version":3,"file":"main-session.js","sourceRoot":"","sources":["../src/main-session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,eAAe,EAAE,sBAAsB,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AAChH,OAAO,KAAK,MAAM,OAAO,CAAC;AAE1B,OAAO,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAAE,6BAA6B,EAAwB,MAAM,uBAAuB,CAAC;AAC5F,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,cA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AAE,CAAC;gBACb,OAAO;YACR,CAAC;YACD,OAAO,GAAG,IAAI,CAAC;YACf,EAAE,CAAC,IAAI,EAAE,CAAC;YACV,OAAO,CAAC,MAAM,CAAC,CAAC;QACjB,CAAC,CAAC;QAEF,MAAM,QAAQ,GAAG,IAAI,0BAA0B,CAC9C,6BAA6B,CAAC,KAAK,CAAC,EACpC,CAAC,UAAU,EAAE,QAAQ,CAAC,EACtB,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC,CAAC,SAAS,CAAC,EACzE,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,EACvB,EAAE,GAAG,EAAE,EAAE,EAAE,CACX,CAAC;QACF,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACtB,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;QACtB,EAAE,CAAC,KAAK,EAAE,CAAC;IACZ,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { createInterface } from \"node:readline\";\nimport { ProcessTerminal, setCapabilityOverrides, setKeybindings, TuiMainScreen } from \"@earendil-works/pi-tui\";\nimport chalk from \"chalk\";\nimport type { Args } from \"./cli/args.ts\";\nimport { selectSession } from \"./cli/session-picker.ts\";\nimport { getAgentDir } from \"./config.js\";\nimport { KeybindingsManager } from \"./core/keybindings.ts\";\nimport { formatMissingSessionCwdPrompt, type SessionCwdIssue } from \"./core/session-cwd.ts\";\nimport { ownedSessionManagerStores } from \"./core/session-lifecycle-work.ts\";\nimport { assertValidSessionId, SessionManager } from \"./core/session-manager.ts\";\nimport { classifiedWorkflowMetadata, workflowSessionMetadataFromEnv } from \"./core/session-manager-classification.ts\";\nimport { resolveSessionStore, selectSessionStorage } from \"./core/session-storage.js\";\nimport type { SettingsManager } from \"./core/settings-manager.ts\";\nimport { type StorageSelection, storageSelectionKey } from \"./core/storage/provider.js\";\nimport type { SessionStore } from \"./core/storage/session/types.js\";\nimport { ExtensionSelectorComponent } from \"./modes/interactive/components/extension-selector.ts\";\nimport { initTheme, stopThemeWatcher } from \"./modes/interactive/theme/theme.js\";\nimport { resolveSessionIdTargetAcrossScopes } from \"./session-id-target.js\";\nimport { createSessionCwdMatcher, resolvePath } from \"./utils/paths.ts\";\n\ntype ResolvedSession =\n\t| { type: \"local\" | \"global\"; id: string; cwd: string }\n\t| { type: \"error\"; message: string }\n\t| { type: \"not_found\"; arg: string };\n\nasync function findLocalSessionByExactId(sessionId: string, cwd: string, store: SessionStore) {\n\tconst header = await store.readHeader(sessionId);\n\treturn header &&\n\t\t!classifiedWorkflowMetadata(header) &&\n\t\tcreateSessionCwdMatcher(resolvePath(cwd))(resolvePath(header.cwd))\n\t\t? { id: header.id, cwd: header.cwd }\n\t\t: undefined;\n}\n\nasync function resolveSessionId(sessionArg: string, cwd: string, store: SessionStore): Promise<ResolvedSession> {\n\tconst exact = await findLocalSessionByExactId(sessionArg, cwd, store).catch(() => undefined);\n\tif (exact) return { type: \"local\", id: exact.id, cwd: exact.cwd };\n\tconst localSessions = await SessionManager.list(cwd, store, undefined, { includeInternal: true });\n\tconst resolution = await resolveSessionIdTargetAcrossScopes(sessionArg, localSessions, () =>\n\t\tSessionManager.listAll(store, undefined, { includeInternal: true }),\n\t);\n\tif (resolution.kind === \"exact\" || resolution.kind === \"unique_prefix\") {\n\t\treturn {\n\t\t\ttype: resolution.scope,\n\t\t\tid: resolution.session.id,\n\t\t\tcwd: resolution.session.cwd,\n\t\t};\n\t}\n\tif (resolution.kind === \"ambiguous\" || resolution.kind === \"malformed\") {\n\t\treturn { type: \"error\", message: resolution.message };\n\t}\n\treturn { type: \"not_found\", arg: sessionArg };\n}\n\n/** Prompt user for yes/no confirmation */\nasync function promptConfirm(message: string): Promise<boolean> {\n\treturn new Promise((resolve) => {\n\t\tconst rl = createInterface({\n\t\t\tinput: process.stdin,\n\t\t\toutput: process.stdout,\n\t\t});\n\t\trl.question(`${message} [y/N] `, (answer) => {\n\t\t\trl.close();\n\t\t\tresolve(answer.toLowerCase() === \"y\" || answer.toLowerCase() === \"yes\");\n\t\t});\n\t});\n}\n\nexport class SessionSelectorConflictError extends Error {\n\treadonly code = \"SessionSelectorConflict\";\n\treadonly conflictingFlags: readonly string[];\n\n\tconstructor(conflictingFlags: readonly string[]) {\n\t\tsuper(\n\t\t\t`--import cannot be combined with ${conflictingFlags.join(\", \")}. Use --import alone, optionally with --no-session or --session-dir.`,\n\t\t);\n\t\tthis.name = \"SessionSelectorConflictError\";\n\t\tthis.conflictingFlags = conflictingFlags;\n\t}\n}\n\nexport function validateImportFlags(parsed: Args): void {\n\tif (parsed.import === undefined) return;\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.fork !== undefined ? \"--fork\" : undefined,\n\t\tparsed.sessionId !== undefined ? \"--session-id\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\tif (conflictingFlags.length > 0) throw new SessionSelectorConflictError(conflictingFlags);\n}\n\nexport function validateForkFlags(parsed: Args): void {\n\tif (parsed.fork === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t\tparsed.noSession ? \"--no-session\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --fork cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nexport function validateSessionIdFlags(parsed: Args): void {\n\tif (parsed.sessionId === undefined) return;\n\n\tconst conflictingFlags = [\n\t\tparsed.session !== undefined ? \"--session\" : undefined,\n\t\tparsed.continue ? \"--continue\" : undefined,\n\t\tparsed.resume ? \"--resume\" : undefined,\n\t].filter((flag): flag is string => flag !== undefined);\n\n\tif (conflictingFlags.length > 0) {\n\t\tconsole.error(chalk.red(`Error: --session-id cannot be combined with ${conflictingFlags.join(\", \")}`));\n\t\tprocess.exit(1);\n\t}\n\n\ttry {\n\t\tassertValidSessionId(parsed.sessionId);\n\t} catch (error: unknown) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\nasync function forkSessionOrExit(\n\tsourceId: string,\n\tcwd: string,\n\tstore: SessionStore,\n\tsessionId?: string,\n): Promise<SessionManager> {\n\ttry {\n\t\tconst source = await SessionManager.open(store, sourceId);\n\t\treturn await source.forkTo(cwd, store, { id: sessionId });\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nasync function openSessionOrExit(sessionId: string, store: SessionStore): Promise<SessionManager> {\n\ttry {\n\t\treturn await SessionManager.open(store, sessionId);\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\tconsole.error(chalk.red(`Error: ${message}`));\n\t\tprocess.exit(1);\n\t}\n}\n\nexport async function applyInheritedWorkflowSessionClassification(\n\tsessionManager: SessionManager,\n\tenv: Record<string, string | undefined> = process.env,\n): Promise<SessionManager> {\n\tconst metadata = workflowSessionMetadataFromEnv(env);\n\tif (metadata) await sessionManager.markSessionInternal(metadata);\n\treturn sessionManager;\n}\n\nconst initialStorageKeys = new WeakMap<SessionManager, string>();\nconst provisionalSessions = new WeakSet<SessionManager>();\n\nasync function createProvisionalSession(store: SessionStore, cwd: string, id?: string): Promise<SessionManager> {\n\tconst manager = await SessionManager.create(store, cwd, { id });\n\tprovisionalSessions.add(manager);\n\treturn manager;\n}\n\n/** Finalize a CLI-owned provisional store after trusted settings become available. */\nexport async function refreshSessionStorage(\n\tmanager: SessionManager,\n\tparsed: Args,\n\tsettingsManager: SettingsManager,\n\tsessionStore?: SessionStore | StorageSelection,\n): Promise<SessionStore | undefined> {\n\t// An opened conversation belongs to the store that supplied it, even when its\n\t// project's newly trusted settings select a different store for new sessions.\n\tif (!provisionalSessions.has(manager) || manager.getEntries().length > 0) return undefined;\n\tconst options = {\n\t\tsessionStore,\n\t\tsettings: settingsManager.getSettings(),\n\t\tnoSession: parsed.noSession,\n\t\tsessionDir: parsed.sessionDir,\n\t\tsessionStorePath: parsed.sessionStorePath,\n\t\tsessionPrefix: parsed.sessionPrefix,\n\t};\n\tconst selection = selectSessionStorage(manager.getCwd(), options);\n\tif (\"load\" in selection) return undefined;\n\tconst key = storageSelectionKey(selection, getAgentDir());\n\tconst initialKey = initialStorageKeys.get(manager);\n\tif (initialKey === undefined || key === initialKey) return undefined;\n\tconst previous = manager.getSessionStore();\n\tconst next = await resolveSessionStore(manager.getCwd(), options);\n\ttry {\n\t\tawait manager.rebindStore(next, true);\n\t} catch (error) {\n\t\tawait next.close();\n\t\tthrow error;\n\t}\n\tinitialStorageKeys.set(manager, key);\n\townedSessionManagerStores.set(manager, next);\n\tawait previous.close();\n\treturn next;\n}\n\nexport async function createSessionManager(\n\tparsed: Args,\n\tcwd: string,\n\tsessionDir: string | undefined,\n\tsettingsManager: SettingsManager,\n\tsessionStore?: SessionStore | StorageSelection,\n): Promise<SessionManager> {\n\tvalidateImportFlags(parsed);\n\tconst store = await resolveSessionStore(cwd, {\n\t\tsessionStore,\n\t\tsettings: settingsManager.getSettings(),\n\t\tnoSession: parsed.noSession,\n\t\tsessionDir: parsed.sessionDir ?? sessionDir,\n\t\tsessionStorePath: parsed.sessionStorePath,\n\t\tsessionPrefix: parsed.sessionPrefix,\n\t});\n\ttry {\n\t\tconst manager = await createSessionManagerWithStore(parsed, cwd, settingsManager, store);\n\t\tif (store !== sessionStore) ownedSessionManagerStores.set(manager, store);\n\t\tconst selection = selectSessionStorage(cwd, {\n\t\t\tsessionStore,\n\t\t\tsettings: settingsManager.getSettings(),\n\t\t\tnoSession: parsed.noSession,\n\t\t\tsessionDir: parsed.sessionDir ?? sessionDir,\n\t\t\tsessionStorePath: parsed.sessionStorePath,\n\t\t\tsessionPrefix: parsed.sessionPrefix,\n\t\t});\n\t\tif (!(\"load\" in selection)) initialStorageKeys.set(manager, storageSelectionKey(selection, getAgentDir()));\n\t\treturn manager;\n\t} catch (error) {\n\t\tif (store !== sessionStore) await store.close();\n\t\tthrow error;\n\t}\n}\n\nasync function createSessionManagerWithStore(\n\tparsed: Args,\n\tcwd: string,\n\tsettingsManager: SettingsManager,\n\tstore: SessionStore,\n): Promise<SessionManager> {\n\tif (parsed.import !== undefined) return SessionManager.importFromJsonl(resolvePath(parsed.import, cwd), cwd, store);\n\tif (parsed.noSession) return createProvisionalSession(store, cwd, parsed.sessionId);\n\n\tif (parsed.fork !== undefined) {\n\t\tif (parsed.sessionId !== undefined) {\n\t\t\tconst existingTarget = await findLocalSessionByExactId(parsed.sessionId, cwd, store);\n\t\t\tif (existingTarget) {\n\t\t\t\tconsole.error(chalk.red(`Session already exists with id '${parsed.sessionId}'`));\n\t\t\t\tprocess.exit(1);\n\t\t\t}\n\t\t}\n\n\t\tconst resolved = await resolveSessionId(parsed.fork, cwd, store);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"local\":\n\t\t\tcase \"global\":\n\t\t\t\treturn forkSessionOrExit(resolved.id, cwd, store, parsed.sessionId);\n\t\t\tcase \"error\":\n\t\t\t\tconsole.error(chalk.red(`Error: ${resolved.message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t\tthrow new Error(\"unreachable\");\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.session !== undefined) {\n\t\tconst resolved = await resolveSessionId(parsed.session, cwd, store);\n\n\t\tswitch (resolved.type) {\n\t\t\tcase \"local\":\n\t\t\t\treturn openSessionOrExit(resolved.id, store);\n\n\t\t\tcase \"global\": {\n\t\t\t\tconsole.log(chalk.yellow(`Session found in different project: ${resolved.cwd}`));\n\t\t\t\tconst shouldFork = await promptConfirm(\"Fork this session into current directory?\");\n\t\t\t\tif (!shouldFork) {\n\t\t\t\t\tconsole.log(chalk.dim(\"Aborted.\"));\n\t\t\t\t\tprocess.exit(0);\n\t\t\t\t}\n\t\t\t\treturn forkSessionOrExit(resolved.id, cwd, store);\n\t\t\t}\n\t\t\tcase \"error\":\n\t\t\t\tconsole.error(chalk.red(`Error: ${resolved.message}`));\n\t\t\t\tprocess.exit(1);\n\t\t\t\tthrow new Error(\"unreachable\");\n\n\t\t\tcase \"not_found\":\n\t\t\t\tconsole.error(chalk.red(`No session found matching '${resolved.arg}'`));\n\t\t\t\tprocess.exit(1);\n\t\t}\n\t}\n\n\tif (parsed.resume) {\n\t\tinitTheme(settingsManager.getTheme(), true);\n\t\ttry {\n\t\t\tconst selected = await selectSession(\n\t\t\t\t(onProgress) => SessionManager.list(cwd, store, onProgress),\n\t\t\t\t(onProgress) => SessionManager.listAll(store, onProgress),\n\t\t\t\tsettingsManager,\n\t\t\t\tstore.descriptor.adapter === \"jsonl\" ? undefined : (id) => store.delete(id),\n\t\t\t);\n\t\t\tif (selected === null) {\n\t\t\t\tconsole.log(chalk.dim(\"No session selected\"));\n\t\t\t\tprocess.exit(0);\n\t\t\t}\n\t\t\treturn openSessionOrExit(selected.id, store);\n\t\t} finally {\n\t\t\tstopThemeWatcher();\n\t\t}\n\t}\n\n\tif (parsed.continue) {\n\t\tconst recent = await store.findMostRecent({ cwd: resolvePath(cwd) });\n\t\treturn recent ? SessionManager.open(store, recent.id) : createProvisionalSession(store, cwd);\n\t}\n\n\tif (parsed.sessionId !== undefined) {\n\t\tconst existingSession = await findLocalSessionByExactId(parsed.sessionId, cwd, store);\n\t\tif (existingSession) {\n\t\t\treturn openSessionOrExit(existingSession.id, store);\n\t\t}\n\t\tconsole.error(chalk.yellow(`No session found with id '${parsed.sessionId}'; creating a new session.`));\n\t}\n\n\treturn createProvisionalSession(store, cwd, parsed.sessionId);\n}\n\nexport async function promptForMissingSessionCwd(\n\tissue: SessionCwdIssue,\n\tsettingsManager: SettingsManager,\n): Promise<string | undefined> {\n\tsetCapabilityOverrides(settingsManager.getTerminalCapabilityOverrides());\n\tinitTheme(settingsManager.getTheme());\n\tsetKeybindings(KeybindingsManager.create());\n\n\treturn new Promise((resolve) => {\n\t\tconst ui = new TuiMainScreen(new ProcessTerminal(), settingsManager.getShowHardwareCursor(), getAgentDir());\n\t\tui.setClearOnShrink(settingsManager.getClearOnShrink());\n\n\t\tlet settled = false;\n\t\tconst finish = (result: string | undefined) => {\n\t\t\tif (settled) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tsettled = true;\n\t\t\tui.stop();\n\t\t\tresolve(result);\n\t\t};\n\n\t\tconst selector = new ExtensionSelectorComponent(\n\t\t\tformatMissingSessionCwdPrompt(issue),\n\t\t\t[\"Continue\", \"Cancel\"],\n\t\t\t(option) => finish(option === \"Continue\" ? issue.fallbackCwd : undefined),\n\t\t\t() => finish(undefined),\n\t\t\t{ tui: ui },\n\t\t);\n\t\tui.addChild(selector);\n\t\tui.setFocus(selector);\n\t\tui.start();\n\t});\n}\n"]}
package/docs/docs.json CHANGED
@@ -60,8 +60,7 @@
60
60
  "group": "Models and providers",
61
61
  "pages": [
62
62
  "providers",
63
- "llama-cpp",
64
- "nvidia-rtx-llama-cpp"
63
+ "llama-cpp"
65
64
  ]
66
65
  },
67
66
  {
@@ -260,6 +259,10 @@
260
259
  "source": "/tree",
261
260
  "destination": "/sessions"
262
261
  },
262
+ {
263
+ "source": "/nvidia-rtx-llama-cpp",
264
+ "destination": "/llama-cpp#nvidia-rtx-recipes"
265
+ },
263
266
  {
264
267
  "source": "/tools/edit",
265
268
  "destination": "/tools#edit"
package/docs/llama-cpp.md CHANGED
@@ -32,7 +32,7 @@ llama-server \
32
32
 
33
33
  Single-file models can sit directly in the model directory. Put multimodal and multi-shard models in separate subdirectories with their projection or shard files. Restart the router after manually adding files. Per-model context sizes and other options can be set with [model presets](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md#model-presets).
34
34
 
35
- For settings tuned to a specific NVIDIA GPU and model, see [Run Atomic with NVIDIA RTX and llama.cpp](/nvidia-rtx-llama-cpp).
35
+ For settings tuned to a specific NVIDIA GPU and model, see [NVIDIA RTX recipes](#nvidia-rtx-recipes).
36
36
 
37
37
  ## Configure Atomic
38
38
 
@@ -70,6 +70,99 @@ If the router disconnects, choose **Retry** to reconnect and refresh state witho
70
70
 
71
71
  Each llama model uses the router-reported loaded context (`meta.n_ctx`, then training context, otherwise Atomic's fallback) for both `contextWindow` and `maxTokens`; Atomic no longer applies a separate 16K output cap. The server remains authoritative and may impose a smaller practical generation limit.
72
72
 
73
+ ## NVIDIA RTX recipes
74
+
75
+ [NVIDIA Local AI Inference Recipes](https://nvidia.github.io/local-ai-inference-recipes/index.html) provides llama.cpp settings tuned for specific NVIDIA hardware and models. Each recipe gives a single-model `llama-server` command. Convert it into a router preset so the router can serve it alongside other models. The examples below use Windows PowerShell.
76
+
77
+ ### Before you begin
78
+
79
+ 1. Open the [recipe catalog](https://nvidia.github.io/local-ai-inference-recipes/index.html), select your hardware, operating system, and model, then choose **llama.cpp**. Check the prerequisites and memory requirements. Keep the recipe's launch command for the conversion below.
80
+ 2. Install llama.cpp with the recipe's setup instructions. The recipe's settings depend on its build, for example CUDA support or speculative decoding options.
81
+ 3. Run `llama-server --help` and check that it lists `--models-preset`. Without it, the build cannot load the recipe as a router preset. Use a newer build that still meets the recipe's requirements.
82
+ 4. Install Atomic with the [Quickstart](/quickstart). On native Windows, also see [Run Atomic on Windows](/windows).
83
+
84
+ ### Convert the recipe to a preset
85
+
86
+ A preset lists the settings for one or more models. Each section name becomes the model ID shown in Atomic. Save the preset next to `llama-server`, or pass its full path when starting the router.
87
+
88
+ Convert each option from the recipe command into one preset line:
89
+
90
+ - Remove the leading dashes: `--ctx-size 65536` becomes `ctx-size = 65536`.
91
+ - Write options without a value as `true`: `--jinja` becomes `jinja = true`.
92
+ - Remove quotes and PowerShell line-continuation backticks around values.
93
+ - Leave out `--host` and `--port`. They belong on the router command line.
94
+ - Add `load-on-startup = true` so the router loads the model when it starts.
95
+ - Replace short model-file options with their long preset keys:
96
+
97
+ | Recipe option | Preset key |
98
+ |---|---|
99
+ | `-hf` | `hf-repo` |
100
+ | `-hff` | `hf-file` |
101
+ | `-hfrd` | `hf-repo-draft` |
102
+ | `--spec-draft-model` | `spec-draft-model` |
103
+
104
+ For example, this recipe command:
105
+
106
+ ```powershell
107
+ llama-server.exe -hf "unsloth/Qwen3.8-27B-GGUF" `
108
+ -hff "Qwen3.8-27B-UD-Q4_K_M.gguf" `
109
+ -hfrd "z-lab/Qwen3.8-27B-DFlash2-GGUF" `
110
+ --spec-draft-model "Qwen3.8-27B-DFlash2-Q4_K_M.gguf" `
111
+ --no-mmproj `
112
+ --host 127.0.0.1 `
113
+ --port 9931 `
114
+ --batch-size 4096 `
115
+ --ubatch-size 1024 `
116
+ --ctx-size 65536 `
117
+ --parallel 1 `
118
+ -ngl 999 `
119
+ --jinja `
120
+ --chat-template-kwargs '{"preserve_thinking":true}' `
121
+ --spec-type draft-dflash `
122
+ --spec-draft-n-max 7 `
123
+ --spec-draft-backend-sampling
124
+ ```
125
+
126
+ becomes `qwen3.8-27b.ini`:
127
+
128
+ ```ini
129
+ version = 1
130
+
131
+ [qwen3.8-27b]
132
+ load-on-startup = true
133
+ hf-repo = unsloth/Qwen3.8-27B-GGUF
134
+ hf-file = Qwen3.8-27B-UD-Q4_K_M.gguf
135
+ hf-repo-draft = z-lab/Qwen3.8-27B-DFlash2-GGUF
136
+ spec-draft-model = Qwen3.8-27B-DFlash2-Q4_K_M.gguf
137
+ no-mmproj = true
138
+ batch-size = 4096
139
+ ubatch-size = 1024
140
+ ctx-size = 65536
141
+ parallel = 1
142
+ ngl = 999
143
+ jinja = true
144
+ chat-template-kwargs = {"preserve_thinking":true}
145
+ spec-type = draft-dflash
146
+ spec-draft-n-max = 7
147
+ spec-draft-backend-sampling = true
148
+ ```
149
+
150
+ ### Start the recipe router
151
+
152
+ Open PowerShell in the llama.cpp folder and run:
153
+
154
+ ```powershell
155
+ .\llama-server.exe --models-preset qwen3.8-27b.ini --host 127.0.0.1 --port 8080
156
+ ```
157
+
158
+ If the recipe requires a Hugging Face token, set `$env:HF_TOKEN` in the same PowerShell window before starting the router. On its first start, the router downloads the model files.
159
+
160
+ Use the [health checks](#troubleshooting) to confirm that the server is ready. In Windows PowerShell, use `curl.exe` rather than `curl`, which PowerShell maps to a different command. The model is ready when `/models` lists `qwen3.8-27b` with the status `loaded`.
161
+
162
+ Then follow [Configure Atomic](#configure-atomic) and connect to `http://127.0.0.1:8080`. The preset section name is the model ID, so select `qwen3.8-27b` in `/model` for this example.
163
+
164
+ NVIDIA recipe memory settings assume that only the selected model uses the GPU. If `/llama` shows other loaded models, unload them before using the recipe model.
165
+
73
166
  ## Classification
74
167
 
75
168
  Classifier models answer typed `choice`, `bool`, and `score` questions about JSON state, like TypeSafe's Jev models, so a local model can make `model: "auto"` routing decisions. Extensions can call `ctx.modelRegistry.classify()` and codemode scripts can call `models.classify()`; see [Classifier models](/models#use-classifier-models). Atomic lists llama.cpp models as classifiers in two ways:
package/docs/sessions.md CHANGED
@@ -12,7 +12,7 @@ Sessions auto-save to the local SQLite database at `~/.atomic/workflows/journal.
12
12
 
13
13
  To choose another store, set `sessions.storage` in settings. Use shared `storage` to select one database for both sessions and workflow runs. JSONL is available only when explicitly selected. Memory is available through `--no-session`, `{ "memory": true }` in settings, or an explicit SDK option; it is never a fallback for a failed persistent store.
14
14
 
15
- When the default SQLite store is selected, sessions saved before it became the default stay in `~/.atomic/agent/sessions` and appear in `/resume` and `--continue` next to newer ones. This includes sessions in formats 1, 2, and 3 and early 0.9.38 alpha sessions. A session is copied into the database the first time you open it, with `/resume`, `--continue`, `--session`, or `--fork`, and is read from the database afterwards. The original files are never modified or deleted, unreadable files are skipped, and workflow stage sessions stay hidden from `/resume` but remain openable by session ID. Deleting one of these sessions keeps it out of the list. Selecting a store yourself, as described below, shows only that store.
15
+ When the default SQLite store is selected, sessions saved before it became the default stay in `~/.atomic/agent/sessions` and appear in `/resume` and `--continue` next to newer ones. This includes sessions in formats 1, 2, and 3 and early 0.9.38 alpha sessions. A session is copied into the database the first time you open it, with `/resume`, `--continue`, `--session`, or `--fork`, and is read from the database afterwards. The original files are never modified or deleted, unreadable files are skipped, and workflow stage sessions stay hidden from `/resume` but remain openable by session ID. Until a session larger than 32 KiB is opened, the list shows it from its first message and its most recent entries, so its message count may be understated and `/resume` search matches only that text; opening it shows the full session. Deleting one of these sessions keeps it out of the list. Selecting a store yourself, as described below, shows only that store.
16
16
 
17
17
  Project-local storage settings apply after you approve project trust, including on the first launch. Atomic re-selects storage before saving a new conversation; resumed conversations stay in their original store. Generated resume commands for JSONL sessions include `--session-dir`; keep that option when reopening the conversation, even if the directory was previously the default.
18
18
 
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@bastani/atomic",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@bastani/atomic",
9
- "version": "0.9.38-alpha.8",
9
+ "version": "0.9.38-alpha.9",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
- "@bastani/atomic-natives": "0.9.38-alpha.8",
13
- "@bastani/pi-ai": "0.9.38-alpha.8",
12
+ "@bastani/atomic-natives": "0.9.38-alpha.9",
13
+ "@bastani/pi-ai": "0.9.38-alpha.9",
14
14
  "@earendil-works/pi-agent-core": "1.3.0",
15
15
  "@earendil-works/pi-codemode": "1.3.0",
16
16
  "@earendil-works/pi-tui": "1.3.0",
@@ -427,18 +427,18 @@
427
427
  }
428
428
  },
429
429
  "node_modules/@bastani/atomic-natives": {
430
- "version": "0.9.38-alpha.8",
431
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives/-/atomic-natives-0.9.38-alpha.8.tgz",
430
+ "version": "0.9.38-alpha.9",
431
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives/-/atomic-natives-0.9.38-alpha.9.tgz",
432
432
  "license": "MIT",
433
433
  "optionalDependencies": {
434
- "@bastani/atomic-natives-darwin-arm64": "0.9.38-alpha.8",
435
- "@bastani/atomic-natives-darwin-x64": "0.9.38-alpha.8",
436
- "@bastani/atomic-natives-linux-arm64-gnu": "0.9.38-alpha.8",
437
- "@bastani/atomic-natives-linux-arm64-musl": "0.9.38-alpha.8",
438
- "@bastani/atomic-natives-linux-x64-gnu": "0.9.38-alpha.8",
439
- "@bastani/atomic-natives-linux-x64-musl": "0.9.38-alpha.8",
440
- "@bastani/atomic-natives-win32-arm64-msvc": "0.9.38-alpha.8",
441
- "@bastani/atomic-natives-win32-x64-msvc": "0.9.38-alpha.8"
434
+ "@bastani/atomic-natives-darwin-arm64": "0.9.38-alpha.9",
435
+ "@bastani/atomic-natives-darwin-x64": "0.9.38-alpha.9",
436
+ "@bastani/atomic-natives-linux-arm64-gnu": "0.9.38-alpha.9",
437
+ "@bastani/atomic-natives-linux-arm64-musl": "0.9.38-alpha.9",
438
+ "@bastani/atomic-natives-linux-x64-gnu": "0.9.38-alpha.9",
439
+ "@bastani/atomic-natives-linux-x64-musl": "0.9.38-alpha.9",
440
+ "@bastani/atomic-natives-win32-arm64-msvc": "0.9.38-alpha.9",
441
+ "@bastani/atomic-natives-win32-x64-msvc": "0.9.38-alpha.9"
442
442
  },
443
443
  "engines": {
444
444
  "bun": ">=1.4.2",
@@ -446,8 +446,8 @@
446
446
  }
447
447
  },
448
448
  "node_modules/@bastani/atomic-natives-darwin-arm64": {
449
- "version": "0.9.38-alpha.8",
450
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-arm64/-/atomic-natives-darwin-arm64-0.9.38-alpha.8.tgz",
449
+ "version": "0.9.38-alpha.9",
450
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-arm64/-/atomic-natives-darwin-arm64-0.9.38-alpha.9.tgz",
451
451
  "license": "MIT",
452
452
  "os": [
453
453
  "darwin"
@@ -458,8 +458,8 @@
458
458
  "optional": true
459
459
  },
460
460
  "node_modules/@bastani/atomic-natives-darwin-x64": {
461
- "version": "0.9.38-alpha.8",
462
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-x64/-/atomic-natives-darwin-x64-0.9.38-alpha.8.tgz",
461
+ "version": "0.9.38-alpha.9",
462
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-darwin-x64/-/atomic-natives-darwin-x64-0.9.38-alpha.9.tgz",
463
463
  "license": "MIT",
464
464
  "os": [
465
465
  "darwin"
@@ -470,8 +470,8 @@
470
470
  "optional": true
471
471
  },
472
472
  "node_modules/@bastani/atomic-natives-linux-arm64-gnu": {
473
- "version": "0.9.38-alpha.8",
474
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-gnu/-/atomic-natives-linux-arm64-gnu-0.9.38-alpha.8.tgz",
473
+ "version": "0.9.38-alpha.9",
474
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-gnu/-/atomic-natives-linux-arm64-gnu-0.9.38-alpha.9.tgz",
475
475
  "license": "MIT",
476
476
  "os": [
477
477
  "linux"
@@ -485,8 +485,8 @@
485
485
  "optional": true
486
486
  },
487
487
  "node_modules/@bastani/atomic-natives-linux-arm64-musl": {
488
- "version": "0.9.38-alpha.8",
489
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-musl/-/atomic-natives-linux-arm64-musl-0.9.38-alpha.8.tgz",
488
+ "version": "0.9.38-alpha.9",
489
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-arm64-musl/-/atomic-natives-linux-arm64-musl-0.9.38-alpha.9.tgz",
490
490
  "license": "MIT",
491
491
  "os": [
492
492
  "linux"
@@ -500,8 +500,8 @@
500
500
  "optional": true
501
501
  },
502
502
  "node_modules/@bastani/atomic-natives-linux-x64-gnu": {
503
- "version": "0.9.38-alpha.8",
504
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-gnu/-/atomic-natives-linux-x64-gnu-0.9.38-alpha.8.tgz",
503
+ "version": "0.9.38-alpha.9",
504
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-gnu/-/atomic-natives-linux-x64-gnu-0.9.38-alpha.9.tgz",
505
505
  "license": "MIT",
506
506
  "os": [
507
507
  "linux"
@@ -515,8 +515,8 @@
515
515
  "optional": true
516
516
  },
517
517
  "node_modules/@bastani/atomic-natives-linux-x64-musl": {
518
- "version": "0.9.38-alpha.8",
519
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-musl/-/atomic-natives-linux-x64-musl-0.9.38-alpha.8.tgz",
518
+ "version": "0.9.38-alpha.9",
519
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-linux-x64-musl/-/atomic-natives-linux-x64-musl-0.9.38-alpha.9.tgz",
520
520
  "license": "MIT",
521
521
  "os": [
522
522
  "linux"
@@ -530,8 +530,8 @@
530
530
  "optional": true
531
531
  },
532
532
  "node_modules/@bastani/atomic-natives-win32-arm64-msvc": {
533
- "version": "0.9.38-alpha.8",
534
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-arm64-msvc/-/atomic-natives-win32-arm64-msvc-0.9.38-alpha.8.tgz",
533
+ "version": "0.9.38-alpha.9",
534
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-arm64-msvc/-/atomic-natives-win32-arm64-msvc-0.9.38-alpha.9.tgz",
535
535
  "license": "MIT",
536
536
  "os": [
537
537
  "win32"
@@ -542,8 +542,8 @@
542
542
  "optional": true
543
543
  },
544
544
  "node_modules/@bastani/atomic-natives-win32-x64-msvc": {
545
- "version": "0.9.38-alpha.8",
546
- "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-x64-msvc/-/atomic-natives-win32-x64-msvc-0.9.38-alpha.8.tgz",
545
+ "version": "0.9.38-alpha.9",
546
+ "resolved": "https://registry.npmjs.org/@bastani/atomic-natives-win32-x64-msvc/-/atomic-natives-win32-x64-msvc-0.9.38-alpha.9.tgz",
547
547
  "license": "MIT",
548
548
  "os": [
549
549
  "win32"
@@ -554,8 +554,8 @@
554
554
  "optional": true
555
555
  },
556
556
  "node_modules/@bastani/pi-ai": {
557
- "version": "0.9.38-alpha.8",
558
- "resolved": "https://registry.npmjs.org/@bastani/pi-ai/-/pi-ai-0.9.38-alpha.8.tgz",
557
+ "version": "0.9.38-alpha.9",
558
+ "resolved": "https://registry.npmjs.org/@bastani/pi-ai/-/pi-ai-0.9.38-alpha.9.tgz",
559
559
  "license": "MIT",
560
560
  "dependencies": {
561
561
  "@anthropic-ai/sdk": "0.129.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bastani/atomic",
3
- "version": "0.9.38-alpha.8",
3
+ "version": "0.9.38-alpha.9",
4
4
  "description": "Atomic coding agent CLI with read, bash, edit, write tools and session management",
5
5
  "type": "module",
6
6
  "atomicConfig": {
@@ -89,8 +89,8 @@
89
89
  "prepublishOnly": "bun run clean && bun run build && bun run shrinkwrap"
90
90
  },
91
91
  "dependencies": {
92
- "@bastani/atomic-natives": "0.9.38-alpha.8",
93
- "@bastani/pi-ai": "0.9.38-alpha.8",
92
+ "@bastani/atomic-natives": "0.9.38-alpha.9",
93
+ "@bastani/pi-ai": "0.9.38-alpha.9",
94
94
  "@earendil-works/pi-agent-core": "1.3.0",
95
95
  "@earendil-works/pi-codemode": "1.3.0",
96
96
  "@earendil-works/pi-tui": "1.3.0",
@@ -1,101 +0,0 @@
1
- ---
2
- title: "Local models on NVIDIA RTX"
3
- description: "Convert NVIDIA llama.cpp recipes into router presets for Atomic."
4
- ---
5
-
6
- # Run Atomic with NVIDIA RTX and llama.cpp
7
-
8
- [NVIDIA Local AI Inference Recipes](https://nvidia.github.io/local-ai-inference-recipes/index.html) provides llama.cpp settings tuned for specific NVIDIA hardware and models. Each recipe gives a single-model `llama-server` command. Atomic works with the llama.cpp router, which can serve and manage several models, so this guide converts the recipe command into a router preset.
9
-
10
- The examples below use Windows PowerShell. See [Local Models with llama.cpp](/llama-cpp) for Atomic's complete router and model-management reference.
11
-
12
- ## Before you begin
13
-
14
- 1. Open the [recipe catalog](https://nvidia.github.io/local-ai-inference-recipes/index.html), select your hardware, operating system, and model, then choose **llama.cpp**. Check the prerequisites and memory requirements. Keep the recipe's launch command for the conversion below.
15
- 2. Install llama.cpp with the recipe's setup instructions. The recipe's settings depend on its build, for example CUDA support or speculative decoding options.
16
- 3. Run `llama-server --help` and check that it lists `--models-preset`. Without it, the build cannot load the recipe as a router preset. Use a newer build that still meets the recipe's requirements.
17
- 4. Install Atomic with the [Quickstart](/quickstart). On native Windows, also see [Run Atomic on Windows](/windows).
18
-
19
- ## Convert the recipe to a preset
20
-
21
- A preset lists the settings for one or more models. Each section name becomes the model ID shown in Atomic. Save the preset next to `llama-server`, or pass its full path when starting the router.
22
-
23
- Convert each option from the recipe command into one preset line:
24
-
25
- - Remove the leading dashes: `--ctx-size 65536` becomes `ctx-size = 65536`.
26
- - Write options without a value as `true`: `--jinja` becomes `jinja = true`.
27
- - Remove quotes and PowerShell line-continuation backticks around values.
28
- - Leave out `--host` and `--port`. They belong on the router command line.
29
- - Add `load-on-startup = true` so the router loads the model when it starts.
30
- - Replace short model-file options with their long preset keys:
31
-
32
- | Recipe option | Preset key |
33
- |---|---|
34
- | `-hf` | `hf-repo` |
35
- | `-hff` | `hf-file` |
36
- | `-hfrd` | `hf-repo-draft` |
37
- | `--spec-draft-model` | `spec-draft-model` |
38
-
39
- For example, this recipe command:
40
-
41
- ```powershell
42
- llama-server.exe -hf "unsloth/Qwen3.8-27B-GGUF" `
43
- -hff "Qwen3.8-27B-UD-Q4_K_M.gguf" `
44
- -hfrd "z-lab/Qwen3.8-27B-DFlash2-GGUF" `
45
- --spec-draft-model "Qwen3.8-27B-DFlash2-Q4_K_M.gguf" `
46
- --no-mmproj `
47
- --host 127.0.0.1 `
48
- --port 9931 `
49
- --batch-size 4096 `
50
- --ubatch-size 1024 `
51
- --ctx-size 65536 `
52
- --parallel 1 `
53
- -ngl 999 `
54
- --jinja `
55
- --chat-template-kwargs '{"preserve_thinking":true}' `
56
- --spec-type draft-dflash `
57
- --spec-draft-n-max 7 `
58
- --spec-draft-backend-sampling
59
- ```
60
-
61
- becomes `qwen3.8-27b.ini`:
62
-
63
- ```ini
64
- version = 1
65
-
66
- [qwen3.8-27b]
67
- load-on-startup = true
68
- hf-repo = unsloth/Qwen3.8-27B-GGUF
69
- hf-file = Qwen3.8-27B-UD-Q4_K_M.gguf
70
- hf-repo-draft = z-lab/Qwen3.8-27B-DFlash2-GGUF
71
- spec-draft-model = Qwen3.8-27B-DFlash2-Q4_K_M.gguf
72
- no-mmproj = true
73
- batch-size = 4096
74
- ubatch-size = 1024
75
- ctx-size = 65536
76
- parallel = 1
77
- ngl = 999
78
- jinja = true
79
- chat-template-kwargs = {"preserve_thinking":true}
80
- spec-type = draft-dflash
81
- spec-draft-n-max = 7
82
- spec-draft-backend-sampling = true
83
- ```
84
-
85
- ## Start the router
86
-
87
- Open PowerShell in the llama.cpp folder and run:
88
-
89
- ```powershell
90
- .\llama-server.exe --models-preset qwen3.8-27b.ini --host 127.0.0.1 --port 8080
91
- ```
92
-
93
- If the recipe requires a Hugging Face token, set `$env:HF_TOKEN` in the same PowerShell window before starting the router. On its first start, the router downloads the model files.
94
-
95
- Use the [router health checks](/llama-cpp#troubleshooting) to confirm that the server is ready. In Windows PowerShell, use `curl.exe` rather than `curl`, which PowerShell maps to a different command. The model is ready when `/models` lists `qwen3.8-27b` with the status `loaded`.
96
-
97
- ## Use the model in Atomic
98
-
99
- Follow [Configure Atomic](/llama-cpp#configure-atomic) and connect to `http://127.0.0.1:8080`. The preset section name is the model ID, so select `qwen3.8-27b` in `/model` for this example.
100
-
101
- NVIDIA recipe memory settings assume that only the selected model uses the GPU. If `/llama` shows other loaded models, unload them before using the recipe model.