@lune_99/pi-lune-extensions-core 0.2.0 → 0.2.1

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
@@ -5,6 +5,83 @@ All notable changes are documented here using
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [0.2.1] - 2026-11-28
9
+
10
+ ### Changed
11
+
12
+ - **Session mentions use configurable cache limits.** Core keeps the newest Pi, Codex and
13
+ Claude Code sessions that fit in its shared, owner-only index at
14
+ `<agentDir>/lune-cache/session-index.json`, defaulting to 4 MB. Each session keeps the
15
+ first 8,000 characters of its first message and searchable text by default; sessions beyond
16
+ the size budget are neither listed nor accepted as references. Configure **Session cache size**
17
+ (1 to 64 MB) and **Session text limit** (a positive integer) under `/lune-core-settings` ›
18
+ **Core › Mention**; both are global and apply at the next list load. Existing cache-size
19
+ overrides are preserved; changing the text limit rereads the source files to restore or trim
20
+ searchable text.
21
+ - **Faster session lists.** Core reads Pi, Codex and Claude Code sessions through its
22
+ index and reads a session file again only when its inode, size or modification time
23
+ changed, so a later session start loads the list in tens of milliseconds instead of
24
+ reading every session file.
25
+
26
+ ### Fixed
27
+
28
+ - **`@@` lists sessions on the first try.** Typing `@@` before the session list had loaded
29
+ showed nothing until you typed it again. `@@` now waits for the first load, and the next
30
+ keystroke ends the wait; a plain `@` still shows file matches at once.
31
+
32
+ ## [0.2.0] - 2026-10-28
33
+
34
+ ### Added
35
+
36
+ - **Codex and Claude Code session mentions.** Both tools' local main sessions now appear
37
+ alongside Pi sessions in the same `@` and `@@` lists, with `[pi]`, `[codex]` and `[claude]`
38
+ source labels padded to one width, and source-specific reference tokens. References preserve
39
+ an exact JSONL copy and filter the active conversation into Markdown; Codex archives and
40
+ both tools' subagents are excluded. Existing catalog, search and reference caches are
41
+ reused, with unchanged external files parsed only once.
42
+ External parser errors are skipped silently so valid sessions and prompt submission remain
43
+ usable; Core Log integration is marked for follow-up.
44
+ - **Secondary menus in the Panel.** `defineSettingsPanel({ menus })` adds rows that open a
45
+ nested page of fields, listed after the declared fields; custom hosts build such rows with
46
+ `createSettingsMenuField`. Menus nest, Esc goes back one level and the title shows the path.
47
+ A menu is built again on every refresh, so its fields can read and write data outside
48
+ Settings, such as files. A declared field with `inMenu` moves onto a menu page instead; see
49
+ the [Panel guide](docs/panel.md#secondary-menus).
50
+ - **Arrow keys switch settings tabs.** In the main list, Right and Left move to the next
51
+ and previous section, like Tab and Shift+Tab. Text inputs, choice lists and custom
52
+ editors still receive the arrows while they are open.
53
+ - **`@` session mentions.** The `@` list in the editor starts with up to three local
54
+ sessions from every project (`[pi]` rows with age, project and title); files whose
55
+ name contains the query stay above them, and file matches are Pi's own. `@@` lists only
56
+ sessions, searching every local session by title, project, id and message text. When you
57
+ send, each `@session:<id>` becomes an `@` reference to a filtered copy under
58
+ `<os.tmpdir()>/pi-lune-session-refs/`, so the agent reads it only when it needs it. The copy
59
+ comes from Pi's `SessionManager.inMemory()` and `buildSessionProjection()` (active branch,
60
+ compaction summary, context edits) and keeps only user prompts, assistant text and the
61
+ compaction summary. The list comes from `SessionManager.listAll()`, reloads in the
62
+ background at most once a minute, and typing never waits for it. An unknown or ambiguous id
63
+ stops the prompt and puts your text back in the editor.
64
+
65
+ ### Changed
66
+
67
+ - **Release metadata and README badges.** Prepare version 0.2.0 for consumers of the new Panel menu API, including Lune Subagent. Add npm version, weekly download and license badges to match the other package READMEs.
68
+ - **Session mention copies use the system temporary directory.** Store filtered transcripts
69
+ under `<os.tmpdir()>/pi-lune-session-refs/` so the operating system can reclaim them according
70
+ to its temporary-file policy. Existing copies under `<agentDir>/tmp/session-refs/` can be
71
+ removed manually once their old references are no longer needed.
72
+
73
+ ### Fixed
74
+
75
+ - **Session mentions expose copies only.** The Markdown reference now points to a complete
76
+ JSONL copy beside it in the system temporary directory, so editing that file cannot modify
77
+ the original session. Projection runs in memory, preserving both files even when Pi upgrades
78
+ an older session format; missing copies are recreated on the next mention.
79
+ - **Session scans cannot notify a retired context.** Late scan failures after reload, session
80
+ replacement or shutdown no longer crash Pi by accessing the previous session's UI.
81
+ Errors from the active session remain visible.
82
+
83
+ ## [0.1.0] - 2026-10-16
84
+
8
85
  > **⚠️ Breaking:** Replace managed extension wrappers with native Pi factories,
9
86
  > `bindSettings` and `registerSettingsPanel`. Split Panel metadata out of
10
87
  > `defineSettings`; import model controls from `/panel`, explicit leases from
@@ -21,26 +98,12 @@ All notable changes are documented here using
21
98
 
22
99
  ### Added
23
100
 
24
- - **Codex and Claude Code session mentions.** Both tools' local main sessions now appear
25
- alongside Pi sessions in the same `@` and `@@` lists, with `[pi]`, `[codex]` and `[claude]`
26
- source labels padded to one width, and source-specific reference tokens. References preserve
27
- an exact JSONL copy and filter the active conversation into Markdown; Codex archives and
28
- both tools' subagents are excluded. Existing catalog, search and reference caches are
29
- reused, with unchanged external files parsed only once.
30
- External parser errors are skipped silently so valid sessions and prompt submission remain
31
- usable; Core Log integration is marked for follow-up.
32
101
  - **Grouped, conditional and custom-edited Panel fields.** `group` lists fields under a
33
102
  heading, `visible` hides a field (keeping its stored value), and `disabled` returns the
34
103
  reason a field cannot be changed right now. `customEditor` renders your own pi-tui
35
104
  component in the panel and saves through `submit`, validated at the scope fixed when it
36
105
  opened. Custom section hosts gain the matching optional `SettingsPanelField` members;
37
106
  see the [Panel guide](docs/panel.md) and [recipes](docs/recipes.md).
38
- - **Secondary menus in the Panel.** `defineSettingsPanel({ menus })` adds rows that open a
39
- nested page of fields, listed after the declared fields; custom hosts build such rows with
40
- `createSettingsMenuField`. Menus nest, Esc goes back one level and the title shows the path.
41
- A menu is built again on every refresh, so its fields can read and write data outside
42
- Settings, such as files. A declared field with `inMenu` moves onto a menu page instead; see
43
- the [Panel guide](docs/panel.md#secondary-menus).
44
107
  - **Independent Settings and Panel definitions.** Immutable declarations separate
45
108
  persistence from presentation. Typed nested paths, dynamic/multiple choices and
46
109
  previews remain available without forcing Settings consumers to load a Panel.
@@ -80,28 +143,9 @@ All notable changes are documented here using
80
143
  `acquire` and `dispose`.
81
144
  - **Recipes and CI.** `docs/recipes.md` collects copy-pasteable examples, and a GitHub
82
145
  Actions workflow runs typecheck, tests and a package dry run.
83
- - **Arrow keys switch settings tabs.** In the main list, Right and Left move to the next
84
- and previous section, like Tab and Shift+Tab. Text inputs, choice lists and custom
85
- editors still receive the arrows while they are open.
86
- - **`@` session mentions.** The `@` list in the editor starts with up to three local
87
- sessions from every project (`[pi]` rows with age, project and title); files whose
88
- name contains the query stay above them, and file matches are Pi's own. `@@` lists only
89
- sessions, searching every local session by title, project, id and message text. When you
90
- send, each `@session:<id>` becomes an `@` reference to a filtered copy under
91
- `<os.tmpdir()>/pi-lune-session-refs/`, so the agent reads it only when it needs it. The copy
92
- comes from Pi's `SessionManager.inMemory()` and `buildSessionProjection()` (active branch,
93
- compaction summary, context edits) and keeps only user prompts, assistant text and the
94
- compaction summary. The list comes from `SessionManager.listAll()`, reloads in the
95
- background at most once a minute, and typing never waits for it. An unknown or ambiguous id
96
- stops the prompt and puts your text back in the editor.
97
146
 
98
147
  ### Changed
99
148
 
100
- - **Release metadata and README badges.** Prepare version 0.2.0 for consumers of the new Panel menu API, including Lune Subagent. Add npm version, weekly download and license badges to match the other package READMEs.
101
- - **Session mention copies use the system temporary directory.** Store filtered transcripts
102
- under `<os.tmpdir()>/pi-lune-session-refs/` so the operating system can reclaim them according
103
- to its temporary-file policy. Existing copies under `<agentDir>/tmp/session-refs/` can be
104
- removed manually once their old references are no longer needed.
105
149
  - **Deterministic settings tabs.** The renderer pins Core first and orders the other
106
150
  sections by label using JavaScript string comparison, with section ID breaking ties,
107
151
  so tab order no longer follows registration timing. Registration and removal reapply
@@ -164,10 +208,6 @@ All notable changes are documented here using
164
208
 
165
209
  ### Fixed
166
210
 
167
- - **Session mentions expose copies only.** The Markdown reference now points to a complete
168
- JSONL copy beside it in the system temporary directory, so editing that file cannot modify
169
- the original session. Projection runs in memory, preserving both files even when Pi upgrades
170
- an older session format; missing copies are recreated on the next mention.
171
211
  - **Native source entry.** Pi now loads a TypeScript source entry and implementation,
172
212
  so `/reload` replaces Core's handlers; SDK consumers keep compiled exports.
173
213
  - **Optional runtime peer boundaries.** Root and `/panel` imports no longer load
@@ -193,6 +233,3 @@ All notable changes are documented here using
193
233
  its Panel section shows the error and Ctrl+S retries, instead of the section vanishing.
194
234
  - **Incompatible Dock no longer breaks contributors.** `attach` keeps the standalone view
195
235
  and warns through `ctx.ui.notify` instead of throwing when the shared Dock is incompatible.
196
- - **Session scans cannot notify a retired context.** Late scan failures after reload, session
197
- replacement or shutdown no longer crash Pi by accessing the previous session's UI.
198
- Errors from the active session remain visible.
package/README.md CHANGED
@@ -126,8 +126,8 @@ session replacement.
126
126
  ## The settings screen
127
127
 
128
128
  Importing Core as a dependency provides building blocks; it does not register commands.
129
- Load Core's Pi extension entry to add `/lune-core-settings [section-id]` and the reserved
130
- `Core` placeholder section, or register your own command that calls
129
+ Load Core's Pi extension entry to add `/lune-core-settings [section-id]` and the `Core`
130
+ section with Core's own settings, or register your own command that calls
131
131
  `openSettingsPanel(ctx, { section })` from `/panel/tui`.
132
132
  The screen lists Core first, then sections by label (JavaScript string comparison, section
133
133
  ID breaking ties). The renderer entry needs `@earendil-works/pi-tui`; declarations and
@@ -250,11 +250,26 @@ Core leaves both the original session file and the complete JSONL copy unchanged
250
250
  when Pi upgrades an older session format in memory. If an id matches no session or more than one, the
251
251
  prompt is not sent and your text returns to the editor.
252
252
 
253
- Core loads all three sources into its existing `SessionCatalog` when a session starts, using
254
- Pi's `SessionManager.listAll()` for Pi sessions. Lookups use that list and reload it in the background when it is older
255
- than one minute, so a new session can take up to a minute to appear. Typing never waits for
256
- the list. External files whose inode, size and modification time have not changed reuse their
257
- parsed metadata and searchable text; searching also reuses the existing lower-case text cache.
253
+ Core loads all three sources into its `SessionCatalog` when a session starts. It keeps what it
254
+ read from each session file in `<agentDir>/lune-cache/session-index.json`, written owner-only
255
+ because it holds the message text, and reads a file again only when its inode, size or
256
+ modification time changed. Because every load reads the whole index and every change rewrites
257
+ it, the index holds at most 4 MB by default: session files are taken newest first by
258
+ modification time until the next one does not fit. Older sessions are neither read nor listed,
259
+ and a typed reference to one is not found. Open `/lune-core-settings`, then **Core › Mention**,
260
+ to configure **Session cache size** (1 to 64 MB) and **Session text limit** (a positive integer,
261
+ defaulting to 8,000 characters). The text limit applies separately to each session's first
262
+ message and searchable message text, so `@@` searches only those retained characters. Both
263
+ settings are global and apply at the next load of the list; other running Pi processes read
264
+ them again when their next session starts. Changing the text limit rebuilds the cached text,
265
+ so increasing it makes more text searchable. Otherwise Pi sessions get the same fields as
266
+ Pi's `SessionManager.listAll()`. A new index or a changed text limit reads every file that
267
+ fits; with large session stores it can take a few seconds.
268
+ An unreadable index is reported and rebuilt from the session files. Lookups use the list and
269
+ reload it in the background when it is older than one minute, so a new session can take up to
270
+ a minute to appear. A plain `@` never waits for the list. `@@` lists only sessions, so it waits
271
+ for the first load, and your next keystroke ends that wait. Searching reuses the existing
272
+ lower-case text cache.
258
273
  Unchanged reference snapshots reuse `TranscriptCache`. A typed reference that is not in the
259
274
  list makes Core reload it before sending the prompt. Invalid or unsupported Codex and Claude
260
275
  Code files are silently excluded, and failed parses are cached until their files change.
@@ -322,7 +337,7 @@ required on `PATH` for `npm run dev` and the interactive demo.
322
337
  | `src/resources/` | Instance-local reverse-order cleanup and `scopedExtension`, independent of other domains |
323
338
  | `src/testing/` | `createSettingsSandbox`, the public test helper exported as `/testing` |
324
339
  | `src/core/host.ts` | The single process-local discovery boundary for shared services |
325
- | `src/core/settings.ts`, `src/core/panel.ts` | Core's own configuration and placeholder panel declarations |
340
+ | `src/core/settings.ts`, `src/core/panel.ts` | Core's own configuration, such as the Mention menu, and its panel declarations |
326
341
  | `extension.ts`, `src/extension.ts` | Native Pi entry, the shared settings command and Core's Settings/Panel ownership |
327
342
  | `test/harness/` | Isolated Settings fixtures and temporary storage |
328
343
  | `.github/workflows/ci.yml` | CI: `npm ci`, typecheck, tests and a package dry run |
@@ -1 +1,6 @@
1
- export declare const corePanel: import("../index.ts").SettingsPanelDefinition<import("typebox").TObject<{}>>;
1
+ export declare const corePanel: import("../index.ts").SettingsPanelDefinition<import("typebox").TObject<{
2
+ mention: import("typebox").TObject<{
3
+ cacheSizeMB: import("typebox").TInteger;
4
+ textLimit: import("typebox").TInteger;
5
+ }>;
6
+ }>>;
@@ -1,6 +1,31 @@
1
1
  import { defineSettingsPanel } from "../panel/definition.js";
2
- import { coreSettings } from "./settings.js";
2
+ import { coreSettings, MENTION_CACHE_MAX_MB, MENTION_CACHE_MIN_MB } from "./settings.js";
3
3
  export const corePanel = defineSettingsPanel(coreSettings, {
4
4
  id: "core",
5
5
  label: "Core",
6
+ fields: (field) => [
7
+ field(["mention", "cacheSizeMB"], {
8
+ label: "Session cache size",
9
+ description: `The index on disk behind the @ and @@ session lists, ${MENTION_CACHE_MIN_MB} to ` +
10
+ `${MENTION_CACHE_MAX_MB} MB. Sessions older than what fits are not listed and ` +
11
+ `cannot be mentioned. Larger values retain more sessions and take longer to load.`,
12
+ inMenu: "mention",
13
+ formatValue: (value) => `${value} MB`,
14
+ }),
15
+ field(["mention", "textLimit"], {
16
+ label: "Session text limit",
17
+ description: "Characters kept from each session's first message and searchable text. " +
18
+ "Use a positive integer; a change applies at the next load of the session list.",
19
+ inMenu: "mention",
20
+ formatValue: (value) => `${value} characters`,
21
+ }),
22
+ ],
23
+ menus: [
24
+ {
25
+ id: "mention",
26
+ label: "Mention",
27
+ description: "Settings for @ and @@ session mentions.",
28
+ summary: ({ values }) => `cache ${values.mention.cacheSizeMB} MB · text ${values.mention.textLimit} chars`,
29
+ },
30
+ ],
6
31
  });
@@ -1,2 +1,10 @@
1
1
  import { Type } from "typebox";
2
- export declare const coreSettings: import("../settings/definition.ts").DefinedSettings<Type.TObject<{}>>;
2
+ /** Bounds of the session index size a user can choose, in megabytes. */
3
+ export declare const MENTION_CACHE_MIN_MB = 1;
4
+ export declare const MENTION_CACHE_MAX_MB = 64;
5
+ export declare const coreSettings: import("../settings/definition.ts").DefinedSettings<Type.TObject<{
6
+ mention: Type.TObject<{
7
+ cacheSizeMB: Type.TInteger;
8
+ textLimit: Type.TInteger;
9
+ }>;
10
+ }>>;
@@ -1,7 +1,41 @@
1
1
  import { Type } from "typebox";
2
+ import { INDEX_BUDGET_MB, SESSION_TEXT_LIMIT } from "../mention/budget.js";
2
3
  import { defineSettings } from "../settings/definition.js";
3
- // Reserve Core's namespace without introducing settings solely for the placeholder.
4
+ /** Bounds of the session index size a user can choose, in megabytes. */
5
+ export const MENTION_CACHE_MIN_MB = 1;
6
+ export const MENTION_CACHE_MAX_MB = 64;
4
7
  export const coreSettings = defineSettings({
5
8
  id: "pi-lune-extensions-core",
6
- schema: Type.Object({}),
9
+ schema: Type.Object({
10
+ mention: Type.Object({
11
+ cacheSizeMB: Type.Integer({
12
+ minimum: MENTION_CACHE_MIN_MB,
13
+ maximum: MENTION_CACHE_MAX_MB,
14
+ default: INDEX_BUDGET_MB,
15
+ }),
16
+ textLimit: Type.Integer({ minimum: 1, default: SESSION_TEXT_LIMIT }),
17
+ }, {
18
+ additionalProperties: false,
19
+ default: { cacheSizeMB: INDEX_BUDGET_MB, textLimit: SESSION_TEXT_LIMIT },
20
+ }),
21
+ }),
22
+ migrations: [
23
+ (overrides) => {
24
+ const mention = overrides["mention"];
25
+ // Object overrides replace the whole value, so the new leaf needs a migration.
26
+ if (typeof mention === "object" &&
27
+ mention !== null &&
28
+ !Array.isArray(mention) &&
29
+ !Object.hasOwn(mention, "textLimit")) {
30
+ return {
31
+ ...overrides,
32
+ mention: { ...mention, textLimit: SESSION_TEXT_LIMIT },
33
+ };
34
+ }
35
+ return overrides;
36
+ },
37
+ ],
38
+ // Every Pi process shares one index file. Projects with different sizes would make each
39
+ // process trim what the other read, so the file is read again on every load.
40
+ globalOnly: ["mention"],
7
41
  });
package/dist/extension.js CHANGED
@@ -13,6 +13,7 @@ import { registerSettingsPanel } from "./panel/registration.js";
13
13
  import { openSettingsPanel } from "./panel/tui.js";
14
14
  import { scopedExtension } from "./resources/scoped-extension.js";
15
15
  import { installMentions } from "./mention/index.js";
16
+ import { megabytes } from "./mention/budget.js";
16
17
  import { bindSettings } from "./settings/binding.js";
17
18
  /**
18
19
  * Register the shared command without acquiring any consumer's configuration.
@@ -34,5 +35,8 @@ export default scopedExtension((pi, resources) => {
34
35
  await openSettingsPanel(ctx, { section: args.trim() || undefined });
35
36
  },
36
37
  });
37
- installMentions(pi, resources);
38
+ installMentions(pi, resources, {
39
+ indexBudget: async (ctx) => megabytes((await settings.view(ctx)).get("mention").cacheSizeMB),
40
+ indexTextLimit: async (ctx) => (await settings.view(ctx)).get("mention").textLimit,
41
+ });
38
42
  });
@@ -12,8 +12,10 @@ export interface MentionAutocompleteOptions {
12
12
  * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
13
13
  * Everything that is not an `@` token goes to the provider underneath.
14
14
  *
15
- * Nothing here waits for the session list: the rows come from what the catalog has read. The
16
- * editor runs one request at a time, so a slow request would delay every later keystroke.
15
+ * A plain `@` never waits for the session list: its rows come from what the catalog has read,
16
+ * so file matches are not delayed. `@@` lists nothing but sessions, and the editor asks again
17
+ * only on a keystroke, so before the first load it waits for that load instead of answering
18
+ * empty. The editor aborts a pending request on the next keystroke, which ends the wait.
17
19
  */
18
20
  export declare function createMentionAutocomplete(current: AutocompleteProvider, options: MentionAutocompleteOptions): AutocompleteProvider;
19
21
  /**
@@ -15,8 +15,10 @@ const AT_WORD = new RegExp(`${TOKEN_BOUNDARY}(@(?:(?!${SEPARATOR})[^"])*)$`, "u"
15
15
  * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
16
16
  * Everything that is not an `@` token goes to the provider underneath.
17
17
  *
18
- * Nothing here waits for the session list: the rows come from what the catalog has read. The
19
- * editor runs one request at a time, so a slow request would delay every later keystroke.
18
+ * A plain `@` never waits for the session list: its rows come from what the catalog has read,
19
+ * so file matches are not delayed. `@@` lists nothing but sessions, and the editor asks again
20
+ * only on a keystroke, so before the first load it waits for that load instead of answering
21
+ * empty. The editor aborts a pending request on the next keystroke, which ends the wait.
20
22
  */
21
23
  export function createMentionAutocomplete(current, options) {
22
24
  // The editor passes back the item objects it received, so membership marks session rows.
@@ -42,6 +44,9 @@ export function createMentionAutocomplete(current, options) {
42
44
  if (!prefix)
43
45
  return current.getSuggestions(lines, cursorLine, cursorCol, request);
44
46
  if (prefix.startsWith(SESSION_TRIGGER)) {
47
+ await options.catalog.whenLoaded(request.signal);
48
+ if (request.signal.aborted)
49
+ return null;
45
50
  const query = prefix.slice(SESSION_TRIGGER.length);
46
51
  const items = sessionItems(query, SESSION_LIST_ROWS, true);
47
52
  return items.length > 0 ? { items, prefix } : null;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * The default size of the session index. Kept free of runtime imports, because Core's settings
3
+ * declare it as their default and the settings screen loads them.
4
+ */
5
+ export declare const INDEX_BUDGET_MB = 4;
6
+ export declare const SESSION_TEXT_LIMIT = 8000;
7
+ /** Megabytes (MiB) to bytes. */
8
+ export declare function megabytes(size: number): number;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * The default size of the session index. Kept free of runtime imports, because Core's settings
3
+ * declare it as their default and the settings screen loads them.
4
+ */
5
+ export const INDEX_BUDGET_MB = 4;
6
+ export const SESSION_TEXT_LIMIT = 8_000;
7
+ /** Megabytes (MiB) to bytes. */
8
+ export function megabytes(size) {
9
+ return size * 1024 * 1024;
10
+ }
@@ -1,26 +1,43 @@
1
1
  import type { LocalSession } from "./session.ts";
2
2
  /**
3
- * Local Pi, Codex and Claude Code main sessions, newest activity first.
3
+ * The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
4
+ * activity first. Each load asks for the budget again, so a changed setting applies to the
5
+ * next load.
4
6
  *
5
- * Listing reads every session file (about a second for a few hundred sessions), so lookups
6
- * serve the cached list and reload it in the background. The owner disposes the catalog on
7
- * session shutdown; a load that finishes later is discarded.
7
+ * Every load checks each session file and reads only those that changed since the saved
8
+ * index. Lookups serve the cached list and reload it in the background. The owner disposes
9
+ * the catalog on session shutdown; a load that finishes later is discarded.
8
10
  */
9
11
  export declare class SessionCatalog {
10
- private readonly sessionDir;
11
12
  private readonly onBackgroundError;
13
+ private readonly budget;
14
+ private readonly textLimit;
12
15
  private readonly abort;
16
+ private readonly index;
17
+ private readonly pi;
13
18
  private readonly external;
14
19
  private sessions;
15
20
  private loaded;
16
21
  private loadedAt;
17
22
  private loading;
18
- constructor(sessionDir: string, onBackgroundError: (error: unknown) => void);
23
+ /** `budget` gives the bytes the session index may keep. */
24
+ constructor(sessionDir: string, onBackgroundError: (error: unknown) => void, budget?: () => Promise<number>, textLimit?: () => Promise<number>);
19
25
  /** The cached list, empty before the first load. A stale list starts a background reload. */
20
26
  snapshot(): readonly LocalSession[];
21
27
  /** Waits only for the first load; later lookups return the cached list at once. */
22
28
  list(): Promise<readonly LocalSession[]>;
29
+ /**
30
+ * Settles when the first load does or when `signal` aborts. Whoever started the load
31
+ * handles its failure, so a waiting caller only reads snapshot() again.
32
+ *
33
+ * A failed first load is retried here. snapshot() only retries a stale list, and `@@`
34
+ * would otherwise stay empty for a minute after a transient read error.
35
+ */
36
+ whenLoaded(signal: AbortSignal): Promise<void>;
23
37
  /** Concurrent callers share one load. */
24
38
  reload(): Promise<readonly LocalSession[]>;
25
39
  dispose(): void;
40
+ private load;
41
+ private refreshInBackground;
42
+ private report;
26
43
  }
@@ -1,61 +1,74 @@
1
- import { dirname, join, resolve } from "node:path";
2
- import { getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
1
+ import { SESSION_TEXT_LIMIT } from "./budget.js";
3
2
  import { ExternalSessions } from "./external.js";
3
+ import { PiSessions } from "./pi.js";
4
+ import { INDEX_BUDGET_BYTES, SessionIndex, sessionIndexFile } from "./session-index.js";
4
5
  /** A list older than this is reloaded in the background on the next lookup. */
5
6
  const REFRESH_AFTER_MS = 60_000;
6
7
  /**
7
- * Local Pi, Codex and Claude Code main sessions, newest activity first.
8
+ * The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
9
+ * activity first. Each load asks for the budget again, so a changed setting applies to the
10
+ * next load.
8
11
  *
9
- * Listing reads every session file (about a second for a few hundred sessions), so lookups
10
- * serve the cached list and reload it in the background. The owner disposes the catalog on
11
- * session shutdown; a load that finishes later is discarded.
12
+ * Every load checks each session file and reads only those that changed since the saved
13
+ * index. Lookups serve the cached list and reload it in the background. The owner disposes
14
+ * the catalog on session shutdown; a load that finishes later is discarded.
12
15
  */
13
16
  export class SessionCatalog {
14
- sessionDir;
15
17
  onBackgroundError;
18
+ budget;
19
+ textLimit;
16
20
  abort = new AbortController();
21
+ index = new SessionIndex(sessionIndexFile());
22
+ pi;
17
23
  external = new ExternalSessions();
18
24
  sessions = [];
19
25
  loaded = false;
20
26
  loadedAt = 0;
21
27
  loading;
22
- constructor(sessionDir, onBackgroundError) {
23
- this.sessionDir = sessionDir;
28
+ /** `budget` gives the bytes the session index may keep. */
29
+ constructor(sessionDir, onBackgroundError, budget = async () => INDEX_BUDGET_BYTES, textLimit = async () => SESSION_TEXT_LIMIT) {
30
+ this.pi = new PiSessions(sessionDir);
24
31
  this.onBackgroundError = onBackgroundError;
32
+ this.budget = budget;
33
+ this.textLimit = textLimit;
25
34
  }
26
35
  /** The cached list, empty before the first load. A stale list starts a background reload. */
27
36
  snapshot() {
28
- const stale = Date.now() - this.loadedAt > REFRESH_AFTER_MS;
29
- if (stale && !this.loading && !this.abort.signal.aborted) {
30
- this.reload().catch((error) => {
31
- if (!this.abort.signal.aborted)
32
- this.onBackgroundError(error);
33
- });
34
- }
37
+ if (Date.now() - this.loadedAt > REFRESH_AFTER_MS)
38
+ this.refreshInBackground();
35
39
  return this.sessions;
36
40
  }
37
41
  /** Waits only for the first load; later lookups return the cached list at once. */
38
42
  async list() {
39
43
  return this.loaded ? this.snapshot() : this.reload();
40
44
  }
45
+ /**
46
+ * Settles when the first load does or when `signal` aborts. Whoever started the load
47
+ * handles its failure, so a waiting caller only reads snapshot() again.
48
+ *
49
+ * A failed first load is retried here. snapshot() only retries a stale list, and `@@`
50
+ * would otherwise stay empty for a minute after a transient read error.
51
+ */
52
+ async whenLoaded(signal) {
53
+ if (this.loaded)
54
+ return;
55
+ this.refreshInBackground();
56
+ const loading = this.loading;
57
+ if (!loading || signal.aborted)
58
+ return;
59
+ await new Promise((resolve) => {
60
+ const settle = () => {
61
+ signal.removeEventListener("abort", settle);
62
+ resolve();
63
+ };
64
+ signal.addEventListener("abort", settle, { once: true });
65
+ loading.then(settle, settle);
66
+ });
67
+ }
41
68
  /** Concurrent callers share one load. */
42
69
  reload() {
43
70
  this.loadedAt = Date.now();
44
- this.loading ??= Promise.all([
45
- listSessions(this.sessionDir, this.abort.signal),
46
- this.external.list(this.abort.signal, this.onBackgroundError),
47
- ])
48
- .then(([pi, external]) => {
49
- this.abort.signal.throwIfAborted();
50
- const sessions = [
51
- ...pi.map((session) => ({ ...session, source: "pi" })),
52
- ...external,
53
- ].sort((left, right) => right.modified.getTime() - left.modified.getTime());
54
- this.sessions = sessions;
55
- this.loaded = true;
56
- return sessions;
57
- })
58
- .finally(() => {
71
+ this.loading ??= this.load().finally(() => {
59
72
  this.loading = undefined;
60
73
  });
61
74
  return this.loading;
@@ -64,13 +77,41 @@ export class SessionCatalog {
64
77
  this.abort.abort();
65
78
  this.external.clear();
66
79
  }
67
- }
68
- function listSessions(sessionDir, signal) {
69
- // Matches the "all" scope of /resume: the default store keeps one folder per project under
70
- // the agent's sessions root, and a custom session directory holds every session itself.
71
- const root = join(getAgentDir(), "sessions");
72
- const custom = sessionDir !== "" && resolve(dirname(sessionDir)) !== resolve(root);
73
- return custom
74
- ? SessionManager.listAll(sessionDir, undefined, signal)
75
- : SessionManager.listAll(undefined, signal);
80
+ async load() {
81
+ const signal = this.abort.signal;
82
+ // A failed index only costs a full read; the scan below writes a new one.
83
+ await this.index.load(signal).catch((error) => this.report(error));
84
+ // Settings that cannot be read are reported where they are edited; the session list
85
+ // keeps working with the default size instead.
86
+ this.index.budget = await this.budget().catch(() => INDEX_BUDGET_BYTES);
87
+ this.index.textLimit = await this.textLimit().catch(() => SESSION_TEXT_LIMIT);
88
+ const [pi, external] = await Promise.all([
89
+ this.pi.list(signal),
90
+ this.external.list(signal, this.onBackgroundError),
91
+ ]);
92
+ // Pi first, so sessions with equal activity times keep listAll's order.
93
+ const { sessions: listed, errors } = await this.index.scan([...pi, ...external], signal);
94
+ signal.throwIfAborted();
95
+ if (errors.length > 0) {
96
+ this.report(new AggregateError(errors, errors.map((error) => error.message).join("\n")));
97
+ }
98
+ await this.index.save().catch((error) => this.report(error));
99
+ signal.throwIfAborted();
100
+ const sessions = listed.sort((left, right) => right.modified.getTime() - left.modified.getTime());
101
+ this.sessions = sessions;
102
+ this.loaded = true;
103
+ return sessions;
104
+ }
105
+ refreshInBackground() {
106
+ if (this.loading || this.abort.signal.aborted)
107
+ return;
108
+ this.reload().catch((error) => {
109
+ if (!this.abort.signal.aborted)
110
+ this.onBackgroundError(error);
111
+ });
112
+ }
113
+ report(error) {
114
+ this.abort.signal.throwIfAborted();
115
+ this.onBackgroundError(error);
116
+ }
76
117
  }
@@ -1,12 +1,12 @@
1
- import { type ExternalSession, type LocalSession, type SessionSource } from "./session.ts";
1
+ import { type ExternalSession, type SessionSource } from "./session.ts";
2
+ import type { SessionFile } from "./session-index.ts";
2
3
  type ExternalSource = Exclude<SessionSource, "pi">;
3
- /** File metadata caches belong to the running Pi session, just like the combined catalog. */
4
+ /** Codex and Claude Code session files; the Codex title index is cached per Pi session. */
4
5
  export declare class ExternalSessions {
5
6
  private readonly codexHome;
6
7
  private readonly claudeHome;
7
- private readonly cached;
8
8
  private titleIndex;
9
- list(signal: AbortSignal, report: (error: unknown) => void): Promise<LocalSession[]>;
9
+ list(signal: AbortSignal, report: (error: unknown) => void): Promise<SessionFile[]>;
10
10
  clear(): void;
11
11
  private paths;
12
12
  private codexNames;