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

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +100 -34
  3. package/dist/dock/registry.js +1 -0
  4. package/dist/extension.js +6 -2
  5. package/dist/mention/autocomplete.d.ts +23 -0
  6. package/dist/mention/autocomplete.js +135 -0
  7. package/dist/mention/catalog.d.ts +26 -0
  8. package/dist/mention/catalog.js +76 -0
  9. package/dist/mention/claude.d.ts +2 -0
  10. package/dist/mention/claude.js +118 -0
  11. package/dist/mention/codex.d.ts +3 -0
  12. package/dist/mention/codex.js +135 -0
  13. package/dist/mention/external.d.ts +15 -0
  14. package/dist/mention/external.js +151 -0
  15. package/dist/mention/index.d.ts +8 -0
  16. package/dist/mention/index.js +150 -0
  17. package/dist/mention/jsonl.d.ts +9 -0
  18. package/dist/mention/jsonl.js +54 -0
  19. package/dist/mention/mention.d.ts +19 -0
  20. package/dist/mention/mention.js +60 -0
  21. package/dist/mention/session.d.ts +18 -0
  22. package/dist/mention/session.js +8 -0
  23. package/dist/mention/text.d.ts +12 -0
  24. package/dist/mention/text.js +47 -0
  25. package/dist/mention/transcript.d.ts +10 -0
  26. package/dist/mention/transcript.js +129 -0
  27. package/dist/panel/defined-section.js +34 -8
  28. package/dist/panel/definition.d.ts +26 -1
  29. package/dist/panel/definition.js +32 -2
  30. package/dist/panel/index.d.ts +3 -2
  31. package/dist/panel/index.js +1 -0
  32. package/dist/panel/panel.js +100 -24
  33. package/dist/panel/section.d.ts +49 -3
  34. package/dist/panel/section.js +59 -12
  35. package/dist/resources/scoped-extension.js +1 -0
  36. package/dist/settings/file-store.js +1 -0
  37. package/docs/dock.md +9 -3
  38. package/docs/panel.md +69 -2
  39. package/docs/public-api-design.md +9 -9
  40. package/docs/recipes.md +3 -8
  41. package/docs/settings.md +1 -1
  42. package/package.json +4 -4
  43. package/src/dock/registry.ts +1 -0
  44. package/src/extension.ts +6 -2
  45. package/src/mention/autocomplete.ts +173 -0
  46. package/src/mention/catalog.ts +84 -0
  47. package/src/mention/claude.ts +127 -0
  48. package/src/mention/codex.ts +144 -0
  49. package/src/mention/external.ts +191 -0
  50. package/src/mention/index.ts +173 -0
  51. package/src/mention/jsonl.ts +56 -0
  52. package/src/mention/mention.ts +90 -0
  53. package/src/mention/session.ts +27 -0
  54. package/src/mention/text.ts +52 -0
  55. package/src/mention/transcript.ts +155 -0
  56. package/src/panel/defined-section.ts +40 -7
  57. package/src/panel/definition.ts +67 -2
  58. package/src/panel/index.ts +4 -0
  59. package/src/panel/panel.ts +105 -23
  60. package/src/panel/section.ts +111 -15
  61. package/src/resources/scoped-extension.ts +1 -0
  62. package/src/settings/file-store.ts +1 -0
package/CHANGELOG.md CHANGED
@@ -21,12 +21,26 @@ All notable changes are documented here using
21
21
 
22
22
  ### Added
23
23
 
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.
24
32
  - **Grouped, conditional and custom-edited Panel fields.** `group` lists fields under a
25
33
  heading, `visible` hides a field (keeping its stored value), and `disabled` returns the
26
34
  reason a field cannot be changed right now. `customEditor` renders your own pi-tui
27
35
  component in the panel and saves through `submit`, validated at the scope fixed when it
28
36
  opened. Custom section hosts gain the matching optional `SettingsPanelField` members;
29
37
  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).
30
44
  - **Independent Settings and Panel definitions.** Immutable declarations separate
31
45
  persistence from presentation. Typed nested paths, dynamic/multiple choices and
32
46
  previews remain available without forcing Settings consumers to load a Panel.
@@ -66,9 +80,28 @@ All notable changes are documented here using
66
80
  `acquire` and `dispose`.
67
81
  - **Recipes and CI.** `docs/recipes.md` collects copy-pasteable examples, and a GitHub
68
82
  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.
69
97
 
70
98
  ### Changed
71
99
 
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.
72
105
  - **Deterministic settings tabs.** The renderer pins Core first and orders the other
73
106
  sections by label using JavaScript string comparison, with section ID breaking ties,
74
107
  so tab order no longer follows registration timing. Registration and removal reapply
@@ -131,6 +164,10 @@ All notable changes are documented here using
131
164
 
132
165
  ### Fixed
133
166
 
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.
134
171
  - **Native source entry.** Pi now loads a TypeScript source entry and implementation,
135
172
  so `/reload` replaces Core's handlers; SDK consumers keep compiled exports.
136
173
  - **Optional runtime peer boundaries.** Root and `/panel` imports no longer load
@@ -156,3 +193,6 @@ All notable changes are documented here using
156
193
  its Panel section shows the error and Ctrl+S retries, instead of the section vanishing.
157
194
  - **Incompatible Dock no longer breaks contributors.** `attach` keeps the standalone view
158
195
  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
@@ -1,5 +1,7 @@
1
1
  # Pi Lune Core
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@lune_99/pi-lune-extensions-core.svg)](https://www.npmjs.com/package/@lune_99/pi-lune-extensions-core) [![npm downloads](https://img.shields.io/npm/dw/@lune_99/pi-lune-extensions-core.svg)](https://www.npmjs.com/package/@lune_99/pi-lune-extensions-core) [![license](https://img.shields.io/npm/l/@lune_99/pi-lune-extensions-core.svg)](LICENSE)
4
+
3
5
  Shared building blocks for [Pi](https://github.com/earendil-works/pi) extensions:
4
6
 
5
7
  - **Settings** — typed options stored as JSON files, with defaults, a global and a
@@ -11,7 +13,8 @@ Shared building blocks for [Pi](https://github.com/earendil-works/pi) extensions
11
13
  set up when Pi shuts the session down.
12
14
 
13
15
  Your features stay in your own extension. Core does not replace Pi's factories, events,
14
- commands, model registry or error handling.
16
+ commands, model registry or error handling. Core's own Pi entry adds one small feature:
17
+ [`@` session mentions](#mentions).
15
18
 
16
19
  ## Quick start
17
20
 
@@ -56,7 +59,7 @@ What each piece does:
56
59
  - `defineSettings` and `defineSettingsPanel` only describe things. They read no files and
57
60
  can live at module level.
58
61
  - `bindSettings(pi, settings)` loads the values when a Pi session starts. The returned
59
- *binding* hands you a *view* with `await binding.view(ctx)`; call it inside your Pi event
62
+ _binding_ hands you a _view_ with `await binding.view(ctx)`; call it inside your Pi event
60
63
  handlers. A view is the session's current values: `view.get(key)`, `view.set(key, value)`,
61
64
  `view.snapshot()` and `view.subscribe(listener)`.
62
65
  - `registerSettingsPanel(panel, binding)` adds the section to the settings screen. It works
@@ -75,10 +78,10 @@ More copy-pasteable examples (model picker, API keys, migrations, tests, Dock) a
75
78
  Each settings `id` gets its own small JSON file per level, holding only the values a user
76
79
  changed:
77
80
 
78
- | Level | File |
79
- | --- | --- |
80
- | Global | `<agentDir>/lune-settings/<id>.json` — `~/.pi/agent` by default, or `PI_CODING_AGENT_DIR` |
81
- | Project | `<project>/.pi/lune-settings/<id>.json` |
81
+ | Level | File |
82
+ | ------- | ----------------------------------------------------------------------------------------- |
83
+ | Global | `<agentDir>/lune-settings/<id>.json` — `~/.pi/agent` by default, or `PI_CODING_AGENT_DIR` |
84
+ | Project | `<project>/.pi/lune-settings/<id>.json` |
82
85
 
83
86
  Project values override global values, which override the defaults in your schema.
84
87
  A damaged file only affects its own `id`. Because settings may hold secrets such as API
@@ -135,7 +138,8 @@ text for strings, a number editor for `number`/`integer`, JSON otherwise. String
135
138
  masked with `secret: true`; `globalOnly` rows are marked "global only" in the project view;
136
139
  untrusted projects show a banner and refuse project edits. Fields can be listed under
137
140
  group headings, shown or disabled conditionally, and edited with your own pi-tui component
138
- via `customEditor`; see the [recipes](docs/recipes.md) and [Panel guide](docs/panel.md).
141
+ via `customEditor`. Secondary menus open a nested page of fields from one row, for entries
142
+ kept outside Settings; see the [recipes](docs/recipes.md) and [Panel guide](docs/panel.md).
139
143
 
140
144
  Core registers no appearance changes. The Lune header, palettes and tool cards live in the
141
145
  independent `@lune_99/pi-core-theme` extension, which adds its own `Theme` section.
@@ -164,12 +168,14 @@ import { defineSettingsPanel, modelChoices } from "@lune_99/pi-lune-extensions-c
164
168
 
165
169
  const panel = defineSettingsPanel(modelSettings, {
166
170
  label: "Model settings",
167
- fields: [{
168
- path: "model",
169
- choiceSource: modelChoices({
170
- specialChoices: [{ value: null, label: "Follow session model" }],
171
- }),
172
- }],
171
+ fields: [
172
+ {
173
+ path: "model",
174
+ choiceSource: modelChoices({
175
+ specialChoices: [{ value: null, label: "Follow session model" }],
176
+ }),
177
+ },
178
+ ],
173
179
  });
174
180
  ```
175
181
 
@@ -198,6 +204,66 @@ renderer stays active; in the incompatible case `attach` also warns through
198
204
  `ctx.ui.notify` instead of throwing. Core never invents business status or starts a Dock UI.
199
205
  See [Dock](docs/dock.md).
200
206
 
207
+ ## Mentions
208
+
209
+ Core's Pi entry adds local Pi, Codex and Claude Code sessions to the same `@` completion list.
210
+
211
+ The list after `@` starts with up to three local sessions from every project, newest first.
212
+ Each row shows its source (`[pi]`, `[codex]` or `[claude]`), age, project and title.
213
+ Type after `@` to filter by source, title, project or id. Files whose name contains what you typed come before
214
+ the sessions, so Tab still picks the file you typed. File matches are Pi's own.
215
+
216
+ Type `@@` to list only sessions from all three tools together. It searches by source, title, project, id and
217
+ the text of its messages, and shows up to 50 matches.
218
+
219
+ ```text
220
+ 继续这个 @@recap
221
+ → [pi] 3d lune-pi 调查recap现在生成的条件是什么
222
+ [claude] 6d lune-recap 如果我把recap的焦点检测去掉会怎么样?
223
+ ```
224
+
225
+ Picking a row inserts `@session:<id>` for Pi, `@codex:<id>` for Codex or `@claude:<id>` for
226
+ Claude Code. The prefixes identify references; both completion lists combine all three sources.
227
+ Codex reads `<CODEX_HOME>/sessions/` (default `~/.codex/sessions/`) and Claude Code reads
228
+ `<CLAUDE_CONFIG_DIR>/projects/` (default `~/.claude/projects/`). Codex archived sessions and
229
+ both tools' subagent sessions are excluded. Codex titles come from its optional
230
+ `session_index.jsonl`; Claude Code uses its custom or generated session title.
231
+
232
+ When you send the prompt, Core saves an exact JSONL copy in the system temporary directory.
233
+ Pi rebuilds its active branch with `SessionManager.inMemory()` and `buildSessionProjection()`,
234
+ including compaction and context edits. Codex applies compaction replacement history and turn
235
+ rollbacks; Claude Code follows the active parent chain and reconnects messages preserved by
236
+ compaction. The filtered copy keeps your prompts, assistant text and readable compaction
237
+ summaries. Thinking, images, tool calls and output, system context and encrypted compaction
238
+ payloads are left out. The result is written to
239
+ `<os.tmpdir()>/pi-lune-session-refs/<source>.<session id>.<snapshot hash>.md` (at most 40 KB), and the token
240
+ becomes an `@` reference to that file, so the agent reads it only when it needs it.
241
+ The Markdown links to the complete `<source>.<session id>.<snapshot hash>.jsonl` copy in the same
242
+ directory for details it leaves out; it does not expose the original session file path.
243
+ Copies remain available across Pi restarts until the operating system reclaims them; cleanup
244
+ timing depends on its temporary-file policy. Mentioning a session again recreates a missing
245
+ Markdown or JSONL copy. Changed session contents or titles produce a new pair of copies, preserving
246
+ earlier references. Existing copies under `<agentDir>/tmp/session-refs/` can be removed manually when their
247
+ old references are no longer needed.
248
+
249
+ Core leaves both the original session file and the complete JSONL copy unchanged, including
250
+ when Pi upgrades an older session format in memory. If an id matches no session or more than one, the
251
+ prompt is not sent and your text returns to the editor.
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.
258
+ Unchanged reference snapshots reuse `TranscriptCache`. A typed reference that is not in the
259
+ list makes Core reload it before sending the prompt. Invalid or unsupported Codex and Claude
260
+ Code files are silently excluded, and failed parses are cached until their files change.
261
+ An invalid Codex title index leaves titles derived from the session messages. If an external
262
+ session becomes invalid after selection, its reference stays as typed while the rest of the
263
+ prompt is sent normally. Parser failures will be recorded in Core Log once it is available.
264
+
265
+ Mentions are part of Core's Pi entry only; importing the SDK does not activate them.
266
+
201
267
  ## API and guides
202
268
 
203
269
  The root exports `defineSettings`, `bindSettings`, `readGlobalSettings`,
@@ -208,14 +274,14 @@ optional peers needed by the capabilities you use (supported ranges: pi-ai `^1.0
208
274
  pi-coding-agent `^1.0.4`, pi-tui `^1.0.0`, typebox `^1.3.27`). The default file backend loads
209
275
  Pi's path API when settings are first acquired.
210
276
 
211
- | Entry | Purpose |
212
- | --- | --- |
213
- | `/settings` | Definitions, bindings, `readGlobalSettings`, typed views, paths and notification errors |
214
- | `/panel` | Panel definitions, registrations, choice/preview types and `modelChoices` |
215
- | `/panel/tui` | `openSettingsPanel` and its terminal renderer |
216
- | `/dock` | `createDockContribution`, Dock snapshot types and `LUNE_DOCK_PROTOCOL_VERSION` |
217
- | `/resources` | `ResourceScope`, `scopedExtension` and the disposable contract |
218
- | `/testing` | `createSettingsSandbox` for tests; never import it from production code |
277
+ | Entry | Purpose |
278
+ | ------------ | --------------------------------------------------------------------------------------- |
279
+ | `/settings` | Definitions, bindings, `readGlobalSettings`, typed views, paths and notification errors |
280
+ | `/panel` | Panel definitions, registrations, choice/preview types and `modelChoices` |
281
+ | `/panel/tui` | `openSettingsPanel` and its terminal renderer |
282
+ | `/dock` | `createDockContribution`, Dock snapshot types and `LUNE_DOCK_PROTOCOL_VERSION` |
283
+ | `/resources` | `ResourceScope`, `scopedExtension` and the disposable contract |
284
+ | `/testing` | `createSettingsSandbox` for tests; never import it from production code |
219
285
 
220
286
  Guides:
221
287
 
@@ -248,19 +314,19 @@ required on `PATH` for `npm run dev` and the interactive demo.
248
314
 
249
315
  ### Find the right module
250
316
 
251
- | Path | Responsibility |
252
- | --- | --- |
253
- | `src/settings/` | Definitions, session binding, leased views, per-namespace file storage and migrations |
254
- | `src/panel/` | Panel declarations, binding projection, choices and terminal rendering |
255
- | `src/dock/` | Dock contributions, UI-scoped registry and protocol checks |
256
- | `src/resources/` | Instance-local reverse-order cleanup and `scopedExtension`, independent of other domains |
257
- | `src/testing/` | `createSettingsSandbox`, the public test helper exported as `/testing` |
258
- | `src/core/host.ts` | The single process-local discovery boundary for shared services |
259
- | `src/core/settings.ts`, `src/core/panel.ts` | Core's own configuration and placeholder panel declarations |
260
- | `extension.ts`, `src/extension.ts` | Native Pi entry, the shared settings command and Core's Settings/Panel ownership |
261
- | `test/harness/` | Isolated Settings fixtures and temporary storage |
262
- | `.github/workflows/ci.yml` | CI: `npm ci`, typecheck, tests and a package dry run |
263
- | `test/tui/` | The offline interactive demo and its mock provider |
317
+ | Path | Responsibility |
318
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------- |
319
+ | `src/settings/` | Definitions, session binding, leased views, per-namespace file storage and migrations |
320
+ | `src/panel/` | Panel declarations, binding projection, choices and terminal rendering |
321
+ | `src/dock/` | Dock contributions, UI-scoped registry and protocol checks |
322
+ | `src/resources/` | Instance-local reverse-order cleanup and `scopedExtension`, independent of other domains |
323
+ | `src/testing/` | `createSettingsSandbox`, the public test helper exported as `/testing` |
324
+ | `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 |
326
+ | `extension.ts`, `src/extension.ts` | Native Pi entry, the shared settings command and Core's Settings/Panel ownership |
327
+ | `test/harness/` | Isolated Settings fixtures and temporary storage |
328
+ | `.github/workflows/ci.yml` | CI: `npm ci`, typecheck, tests and a package dry run |
329
+ | `test/tui/` | The offline interactive demo and its mock provider |
264
330
 
265
331
  Keep business workflows in their own extensions. Use intentional package exports rather
266
332
  than private source imports; do not turn binding readiness into a general session framework.
@@ -95,6 +95,7 @@ export function createDockRegistry() {
95
95
  notifyPresence(state.contributions.values(), false);
96
96
  }
97
97
  catch (cleanupError) {
98
+ // eslint-disable-next-line preserve-caught-error -- AggregateError.errors retains both failures.
98
99
  throw new AggregateError([error, cleanupError], "Lune dock host attachment and cleanup failed");
99
100
  }
100
101
  throw error;
package/dist/extension.js CHANGED
@@ -1,15 +1,18 @@
1
1
  /**
2
- * Optional Pi package entry for the shared command and Core's own settings section.
2
+ * Optional Pi package entry for the shared command, Core's own settings section and `@`
3
+ * session mentions.
3
4
  *
4
5
  * SDK consumers do not need this extension for Host discovery or settings storage.
5
6
  * Consumer plugins register their own sections; this entry owns only Core's Settings
6
- * binding and Panel registration. It opts into /panel/tui and terminal peers.
7
+ * binding and Panel registration. It opts into /panel/tui and terminal peers. Session
8
+ * mentions live only behind this entry, so importing the SDK never activates them.
7
9
  */
8
10
  import { corePanel } from "./core/panel.js";
9
11
  import { coreSettings } from "./core/settings.js";
10
12
  import { registerSettingsPanel } from "./panel/registration.js";
11
13
  import { openSettingsPanel } from "./panel/tui.js";
12
14
  import { scopedExtension } from "./resources/scoped-extension.js";
15
+ import { installMentions } from "./mention/index.js";
13
16
  import { bindSettings } from "./settings/binding.js";
14
17
  /**
15
18
  * Register the shared command without acquiring any consumer's configuration.
@@ -31,4 +34,5 @@ export default scopedExtension((pi, resources) => {
31
34
  await openSettingsPanel(ctx, { section: args.trim() || undefined });
32
35
  },
33
36
  });
37
+ installMentions(pi, resources);
34
38
  });
@@ -0,0 +1,23 @@
1
+ import type { AutocompleteProvider } from "@earendil-works/pi-tui";
2
+ import type { SessionCatalog } from "./catalog.ts";
3
+ import { type LocalSession } from "./session.ts";
4
+ /** `@@query` lists sessions only and searches their messages too. */
5
+ export declare const SESSION_TRIGGER = "@@";
6
+ export interface MentionAutocompleteOptions {
7
+ catalog: SessionCatalog;
8
+ /** The running session's file, left out of the list. */
9
+ currentSessionFile: string | undefined;
10
+ }
11
+ /**
12
+ * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
13
+ * Everything that is not an `@` token goes to the provider underneath.
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.
17
+ */
18
+ export declare function createMentionAutocomplete(current: AutocompleteProvider, options: MentionAutocompleteOptions): AutocompleteProvider;
19
+ /**
20
+ * Id and title matches rank above project matches, which rank above matches in the session's
21
+ * messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
22
+ */
23
+ export declare function matchSessions(sessions: readonly LocalSession[], query: string, excludePath: string | undefined, searchText: boolean): LocalSession[];
@@ -0,0 +1,135 @@
1
+ import { mentionToken } from "./mention.js";
2
+ import { SOURCE_NAMES } from "./session.js";
3
+ import { formatAge, projectName, SEPARATOR, sessionTitle, TOKEN_BOUNDARY } from "./text.js";
4
+ /** `@@query` lists sessions only and searches their messages too. */
5
+ export const SESSION_TRIGGER = "@@";
6
+ /** Source tags are padded to the widest one so the age and project columns line up. */
7
+ const SOURCE_TAG_WIDTH = Math.max(...Object.keys(SOURCE_NAMES).map((source) => source.length + 2));
8
+ /** Session rows in the list for a plain `@query`. */
9
+ const SESSION_ROWS = 3;
10
+ /** Rows for `@@query`; the search itself covers every local session. */
11
+ const SESSION_LIST_ROWS = 50;
12
+ /** An `@` at a word start, up to the cursor. A quote after it is pi's quoted path syntax. */
13
+ const AT_WORD = new RegExp(`${TOKEN_BOUNDARY}(@(?:(?!${SEPARATOR})[^"])*)$`, "u");
14
+ /**
15
+ * `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
16
+ * Everything that is not an `@` token goes to the provider underneath.
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.
20
+ */
21
+ export function createMentionAutocomplete(current, options) {
22
+ // The editor passes back the item objects it received, so membership marks session rows.
23
+ const sessionRows = new WeakSet();
24
+ const sessionItems = (query, limit, searchText) => {
25
+ const sessions = options.catalog.snapshot();
26
+ const now = Date.now();
27
+ return matchSessions(sessions, query, options.currentSessionFile, searchText)
28
+ .slice(0, limit)
29
+ .map((session) => {
30
+ const item = sessionItem(session, sessions, now);
31
+ sessionRows.add(item);
32
+ return item;
33
+ });
34
+ };
35
+ return {
36
+ triggerCharacters: current.triggerCharacters,
37
+ shouldTriggerFileCompletion: current.shouldTriggerFileCompletion
38
+ ? (lines, cursorLine, cursorCol) => current.shouldTriggerFileCompletion(lines, cursorLine, cursorCol)
39
+ : undefined,
40
+ async getSuggestions(lines, cursorLine, cursorCol, request) {
41
+ const prefix = AT_WORD.exec((lines[cursorLine] ?? "").slice(0, cursorCol))?.[1];
42
+ if (!prefix)
43
+ return current.getSuggestions(lines, cursorLine, cursorCol, request);
44
+ if (prefix.startsWith(SESSION_TRIGGER)) {
45
+ const query = prefix.slice(SESSION_TRIGGER.length);
46
+ const items = sessionItems(query, SESSION_LIST_ROWS, true);
47
+ return items.length > 0 ? { items, prefix } : null;
48
+ }
49
+ const query = prefix.slice(1);
50
+ // A folder in the query names a path.
51
+ const sessions = query.includes("/") ? [] : sessionItems(query, SESSION_ROWS, false);
52
+ const files = await current.getSuggestions(lines, cursorLine, cursorCol, request);
53
+ if (request.signal.aborted)
54
+ return null;
55
+ // No rows to add, or the provider underneath read a different token.
56
+ if (sessions.length === 0 || (files && files.prefix !== prefix))
57
+ return files;
58
+ const items = withSessions(files?.items ?? [], sessions, query);
59
+ return items.length > 0 ? { items, prefix } : null;
60
+ },
61
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
62
+ if (!sessionRows.has(item)) {
63
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
64
+ }
65
+ const line = lines[cursorLine] ?? "";
66
+ const start = cursorCol - prefix.length;
67
+ const inserted = `${item.value} `;
68
+ const next = [...lines];
69
+ next[cursorLine] = line.slice(0, start) + inserted + line.slice(cursorCol);
70
+ return { lines: next, cursorLine, cursorCol: start + inserted.length };
71
+ },
72
+ };
73
+ }
74
+ /**
75
+ * Sessions come first, except after files whose name contains the query. The editor selects the
76
+ * first row, so Tab after a typed file name still picks that file and not a session.
77
+ */
78
+ function withSessions(files, sessions, query) {
79
+ const needle = query.toLowerCase();
80
+ const named = needle
81
+ ? files.filter((item) => item.label.replace(/\/$/, "").toLowerCase().includes(needle))
82
+ : [];
83
+ const others = files.filter((item) => !named.includes(item));
84
+ return [...named, ...sessions, ...others];
85
+ }
86
+ // The catalog keeps one list until its next reload, so the lower-case copies are made once per
87
+ // session and list, not once per keystroke.
88
+ const searches = new WeakMap();
89
+ function searchOf(session) {
90
+ let search = searches.get(session);
91
+ if (!search) {
92
+ search = {
93
+ id: session.id.toLowerCase(),
94
+ title: sessionTitle(session).toLowerCase(),
95
+ project: projectName(session).toLowerCase(),
96
+ source: SOURCE_NAMES[session.source].toLowerCase(),
97
+ };
98
+ searches.set(session, search);
99
+ }
100
+ return search;
101
+ }
102
+ /**
103
+ * Id and title matches rank above project matches, which rank above matches in the session's
104
+ * messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
105
+ */
106
+ export function matchSessions(sessions, query, excludePath, searchText) {
107
+ const needle = query.toLowerCase();
108
+ return sessions
109
+ .filter((session) => session.path !== excludePath && session.messageCount > 0)
110
+ .map((session) => ({ session, rank: needle ? matchRank(session, needle, searchText) : 1 }))
111
+ .filter(({ rank }) => rank > 0)
112
+ .sort((a, b) => b.rank - a.rank)
113
+ .map(({ session }) => session);
114
+ }
115
+ function matchRank(session, needle, searchText) {
116
+ const search = searchOf(session);
117
+ if (search.id.startsWith(needle) || search.title.includes(needle))
118
+ return 3;
119
+ if (search.project.includes(needle) || search.source.includes(needle))
120
+ return 2;
121
+ if (!searchText)
122
+ return 0;
123
+ search.text ??= session.allMessagesText.toLowerCase();
124
+ return search.text.includes(needle) ? 1 : 0;
125
+ }
126
+ /** Source, age and project fill pi's label column, which leaves the wide one for the title. */
127
+ function sessionItem(session, sessions, now) {
128
+ const source = `[${session.source}]`.padEnd(SOURCE_TAG_WIDTH);
129
+ const age = formatAge(now - session.modified.getTime()).padStart(3);
130
+ return {
131
+ value: mentionToken(session, sessions),
132
+ label: `${source} ${age} ${projectName(session)}`,
133
+ description: sessionTitle(session),
134
+ };
135
+ }
@@ -0,0 +1,26 @@
1
+ import type { LocalSession } from "./session.ts";
2
+ /**
3
+ * Local Pi, Codex and Claude Code main sessions, newest activity first.
4
+ *
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.
8
+ */
9
+ export declare class SessionCatalog {
10
+ private readonly sessionDir;
11
+ private readonly onBackgroundError;
12
+ private readonly abort;
13
+ private readonly external;
14
+ private sessions;
15
+ private loaded;
16
+ private loadedAt;
17
+ private loading;
18
+ constructor(sessionDir: string, onBackgroundError: (error: unknown) => void);
19
+ /** The cached list, empty before the first load. A stale list starts a background reload. */
20
+ snapshot(): readonly LocalSession[];
21
+ /** Waits only for the first load; later lookups return the cached list at once. */
22
+ list(): Promise<readonly LocalSession[]>;
23
+ /** Concurrent callers share one load. */
24
+ reload(): Promise<readonly LocalSession[]>;
25
+ dispose(): void;
26
+ }
@@ -0,0 +1,76 @@
1
+ import { dirname, join, resolve } from "node:path";
2
+ import { getAgentDir, SessionManager } from "@earendil-works/pi-coding-agent";
3
+ import { ExternalSessions } from "./external.js";
4
+ /** A list older than this is reloaded in the background on the next lookup. */
5
+ const REFRESH_AFTER_MS = 60_000;
6
+ /**
7
+ * Local Pi, Codex and Claude Code main sessions, newest activity first.
8
+ *
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
+ */
13
+ export class SessionCatalog {
14
+ sessionDir;
15
+ onBackgroundError;
16
+ abort = new AbortController();
17
+ external = new ExternalSessions();
18
+ sessions = [];
19
+ loaded = false;
20
+ loadedAt = 0;
21
+ loading;
22
+ constructor(sessionDir, onBackgroundError) {
23
+ this.sessionDir = sessionDir;
24
+ this.onBackgroundError = onBackgroundError;
25
+ }
26
+ /** The cached list, empty before the first load. A stale list starts a background reload. */
27
+ 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
+ }
35
+ return this.sessions;
36
+ }
37
+ /** Waits only for the first load; later lookups return the cached list at once. */
38
+ async list() {
39
+ return this.loaded ? this.snapshot() : this.reload();
40
+ }
41
+ /** Concurrent callers share one load. */
42
+ reload() {
43
+ 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(() => {
59
+ this.loading = undefined;
60
+ });
61
+ return this.loading;
62
+ }
63
+ dispose() {
64
+ this.abort.abort();
65
+ this.external.clear();
66
+ }
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);
76
+ }
@@ -0,0 +1,2 @@
1
+ import type { ExternalSession } from "./session.ts";
2
+ export declare function parseClaudeSession(content: string, path: string): ExternalSession | undefined;