@lune_99/pi-lune-extensions-core 0.1.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.
Files changed (77) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +117 -36
  3. package/dist/core/panel.d.ts +6 -1
  4. package/dist/core/panel.js +26 -1
  5. package/dist/core/settings.d.ts +9 -1
  6. package/dist/core/settings.js +36 -2
  7. package/dist/dock/registry.js +1 -0
  8. package/dist/extension.js +10 -2
  9. package/dist/mention/autocomplete.d.ts +25 -0
  10. package/dist/mention/autocomplete.js +140 -0
  11. package/dist/mention/budget.d.ts +8 -0
  12. package/dist/mention/budget.js +10 -0
  13. package/dist/mention/catalog.d.ts +43 -0
  14. package/dist/mention/catalog.js +117 -0
  15. package/dist/mention/claude.d.ts +2 -0
  16. package/dist/mention/claude.js +118 -0
  17. package/dist/mention/codex.d.ts +3 -0
  18. package/dist/mention/codex.js +135 -0
  19. package/dist/mention/external.d.ts +15 -0
  20. package/dist/mention/external.js +145 -0
  21. package/dist/mention/index.d.ts +17 -0
  22. package/dist/mention/index.js +151 -0
  23. package/dist/mention/jsonl.d.ts +9 -0
  24. package/dist/mention/jsonl.js +54 -0
  25. package/dist/mention/mention.d.ts +19 -0
  26. package/dist/mention/mention.js +60 -0
  27. package/dist/mention/pi.d.ts +11 -0
  28. package/dist/mention/pi.js +172 -0
  29. package/dist/mention/session-index.d.ts +66 -0
  30. package/dist/mention/session-index.js +303 -0
  31. package/dist/mention/session.d.ts +18 -0
  32. package/dist/mention/session.js +8 -0
  33. package/dist/mention/text.d.ts +12 -0
  34. package/dist/mention/text.js +47 -0
  35. package/dist/mention/transcript.d.ts +10 -0
  36. package/dist/mention/transcript.js +129 -0
  37. package/dist/panel/defined-section.js +34 -8
  38. package/dist/panel/definition.d.ts +26 -1
  39. package/dist/panel/definition.js +32 -2
  40. package/dist/panel/index.d.ts +3 -2
  41. package/dist/panel/index.js +1 -0
  42. package/dist/panel/panel.js +109 -29
  43. package/dist/panel/section.d.ts +49 -3
  44. package/dist/panel/section.js +59 -12
  45. package/dist/resources/scoped-extension.js +1 -0
  46. package/dist/settings/file-store.js +1 -0
  47. package/docs/dock.md +9 -3
  48. package/docs/panel.md +69 -2
  49. package/docs/public-api-design.md +9 -9
  50. package/docs/recipes.md +3 -8
  51. package/docs/settings.md +1 -1
  52. package/package.json +4 -4
  53. package/src/core/panel.ts +29 -1
  54. package/src/core/settings.ts +42 -2
  55. package/src/dock/registry.ts +1 -0
  56. package/src/extension.ts +11 -2
  57. package/src/mention/autocomplete.ts +177 -0
  58. package/src/mention/budget.ts +11 -0
  59. package/src/mention/catalog.ts +133 -0
  60. package/src/mention/claude.ts +127 -0
  61. package/src/mention/codex.ts +144 -0
  62. package/src/mention/external.ts +190 -0
  63. package/src/mention/index.ts +193 -0
  64. package/src/mention/jsonl.ts +56 -0
  65. package/src/mention/mention.ts +90 -0
  66. package/src/mention/pi.ts +192 -0
  67. package/src/mention/session-index.ts +356 -0
  68. package/src/mention/session.ts +27 -0
  69. package/src/mention/text.ts +52 -0
  70. package/src/mention/transcript.ts +155 -0
  71. package/src/panel/defined-section.ts +40 -7
  72. package/src/panel/definition.ts +67 -2
  73. package/src/panel/index.ts +4 -0
  74. package/src/panel/panel.ts +115 -29
  75. package/src/panel/section.ts +111 -15
  76. package/src/resources/scoped-extension.ts +1 -0
  77. package/src/settings/file-store.ts +1 -0
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
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
@@ -123,8 +126,8 @@ session replacement.
123
126
  ## The settings screen
124
127
 
125
128
  Importing Core as a dependency provides building blocks; it does not register commands.
126
- Load Core's Pi extension entry to add `/lune-core-settings [section-id]` and the reserved
127
- `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
128
131
  `openSettingsPanel(ctx, { section })` from `/panel/tui`.
129
132
  The screen lists Core first, then sections by label (JavaScript string comparison, section
130
133
  ID breaking ties). The renderer entry needs `@earendil-works/pi-tui`; declarations and
@@ -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,81 @@ 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 `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.
273
+ Unchanged reference snapshots reuse `TranscriptCache`. A typed reference that is not in the
274
+ list makes Core reload it before sending the prompt. Invalid or unsupported Codex and Claude
275
+ Code files are silently excluded, and failed parses are cached until their files change.
276
+ An invalid Codex title index leaves titles derived from the session messages. If an external
277
+ session becomes invalid after selection, its reference stays as typed while the rest of the
278
+ prompt is sent normally. Parser failures will be recorded in Core Log once it is available.
279
+
280
+ Mentions are part of Core's Pi entry only; importing the SDK does not activate them.
281
+
201
282
  ## API and guides
202
283
 
203
284
  The root exports `defineSettings`, `bindSettings`, `readGlobalSettings`,
@@ -208,14 +289,14 @@ optional peers needed by the capabilities you use (supported ranges: pi-ai `^1.0
208
289
  pi-coding-agent `^1.0.4`, pi-tui `^1.0.0`, typebox `^1.3.27`). The default file backend loads
209
290
  Pi's path API when settings are first acquired.
210
291
 
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 |
292
+ | Entry | Purpose |
293
+ | ------------ | --------------------------------------------------------------------------------------- |
294
+ | `/settings` | Definitions, bindings, `readGlobalSettings`, typed views, paths and notification errors |
295
+ | `/panel` | Panel definitions, registrations, choice/preview types and `modelChoices` |
296
+ | `/panel/tui` | `openSettingsPanel` and its terminal renderer |
297
+ | `/dock` | `createDockContribution`, Dock snapshot types and `LUNE_DOCK_PROTOCOL_VERSION` |
298
+ | `/resources` | `ResourceScope`, `scopedExtension` and the disposable contract |
299
+ | `/testing` | `createSettingsSandbox` for tests; never import it from production code |
219
300
 
220
301
  Guides:
221
302
 
@@ -248,19 +329,19 @@ required on `PATH` for `npm run dev` and the interactive demo.
248
329
 
249
330
  ### Find the right module
250
331
 
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 |
332
+ | Path | Responsibility |
333
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------- |
334
+ | `src/settings/` | Definitions, session binding, leased views, per-namespace file storage and migrations |
335
+ | `src/panel/` | Panel declarations, binding projection, choices and terminal rendering |
336
+ | `src/dock/` | Dock contributions, UI-scoped registry and protocol checks |
337
+ | `src/resources/` | Instance-local reverse-order cleanup and `scopedExtension`, independent of other domains |
338
+ | `src/testing/` | `createSettingsSandbox`, the public test helper exported as `/testing` |
339
+ | `src/core/host.ts` | The single process-local discovery boundary for shared services |
340
+ | `src/core/settings.ts`, `src/core/panel.ts` | Core's own configuration, such as the Mention menu, and its panel declarations |
341
+ | `extension.ts`, `src/extension.ts` | Native Pi entry, the shared settings command and Core's Settings/Panel ownership |
342
+ | `test/harness/` | Isolated Settings fixtures and temporary storage |
343
+ | `.github/workflows/ci.yml` | CI: `npm ci`, typecheck, tests and a package dry run |
344
+ | `test/tui/` | The offline interactive demo and its mock provider |
264
345
 
265
346
  Keep business workflows in their own extensions. Use intentional package exports rather
266
347
  than private source imports; do not turn binding readiness into a general session framework.
@@ -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
  });
@@ -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,19 @@
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";
16
+ import { megabytes } from "./mention/budget.js";
13
17
  import { bindSettings } from "./settings/binding.js";
14
18
  /**
15
19
  * Register the shared command without acquiring any consumer's configuration.
@@ -31,4 +35,8 @@ export default scopedExtension((pi, resources) => {
31
35
  await openSettingsPanel(ctx, { section: args.trim() || undefined });
32
36
  },
33
37
  });
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
+ });
34
42
  });
@@ -0,0 +1,25 @@
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
+ * 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.
19
+ */
20
+ export declare function createMentionAutocomplete(current: AutocompleteProvider, options: MentionAutocompleteOptions): AutocompleteProvider;
21
+ /**
22
+ * Id and title matches rank above project matches, which rank above matches in the session's
23
+ * messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
24
+ */
25
+ export declare function matchSessions(sessions: readonly LocalSession[], query: string, excludePath: string | undefined, searchText: boolean): LocalSession[];
@@ -0,0 +1,140 @@
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
+ * 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.
22
+ */
23
+ export function createMentionAutocomplete(current, options) {
24
+ // The editor passes back the item objects it received, so membership marks session rows.
25
+ const sessionRows = new WeakSet();
26
+ const sessionItems = (query, limit, searchText) => {
27
+ const sessions = options.catalog.snapshot();
28
+ const now = Date.now();
29
+ return matchSessions(sessions, query, options.currentSessionFile, searchText)
30
+ .slice(0, limit)
31
+ .map((session) => {
32
+ const item = sessionItem(session, sessions, now);
33
+ sessionRows.add(item);
34
+ return item;
35
+ });
36
+ };
37
+ return {
38
+ triggerCharacters: current.triggerCharacters,
39
+ shouldTriggerFileCompletion: current.shouldTriggerFileCompletion
40
+ ? (lines, cursorLine, cursorCol) => current.shouldTriggerFileCompletion(lines, cursorLine, cursorCol)
41
+ : undefined,
42
+ async getSuggestions(lines, cursorLine, cursorCol, request) {
43
+ const prefix = AT_WORD.exec((lines[cursorLine] ?? "").slice(0, cursorCol))?.[1];
44
+ if (!prefix)
45
+ return current.getSuggestions(lines, cursorLine, cursorCol, request);
46
+ if (prefix.startsWith(SESSION_TRIGGER)) {
47
+ await options.catalog.whenLoaded(request.signal);
48
+ if (request.signal.aborted)
49
+ return null;
50
+ const query = prefix.slice(SESSION_TRIGGER.length);
51
+ const items = sessionItems(query, SESSION_LIST_ROWS, true);
52
+ return items.length > 0 ? { items, prefix } : null;
53
+ }
54
+ const query = prefix.slice(1);
55
+ // A folder in the query names a path.
56
+ const sessions = query.includes("/") ? [] : sessionItems(query, SESSION_ROWS, false);
57
+ const files = await current.getSuggestions(lines, cursorLine, cursorCol, request);
58
+ if (request.signal.aborted)
59
+ return null;
60
+ // No rows to add, or the provider underneath read a different token.
61
+ if (sessions.length === 0 || (files && files.prefix !== prefix))
62
+ return files;
63
+ const items = withSessions(files?.items ?? [], sessions, query);
64
+ return items.length > 0 ? { items, prefix } : null;
65
+ },
66
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
67
+ if (!sessionRows.has(item)) {
68
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
69
+ }
70
+ const line = lines[cursorLine] ?? "";
71
+ const start = cursorCol - prefix.length;
72
+ const inserted = `${item.value} `;
73
+ const next = [...lines];
74
+ next[cursorLine] = line.slice(0, start) + inserted + line.slice(cursorCol);
75
+ return { lines: next, cursorLine, cursorCol: start + inserted.length };
76
+ },
77
+ };
78
+ }
79
+ /**
80
+ * Sessions come first, except after files whose name contains the query. The editor selects the
81
+ * first row, so Tab after a typed file name still picks that file and not a session.
82
+ */
83
+ function withSessions(files, sessions, query) {
84
+ const needle = query.toLowerCase();
85
+ const named = needle
86
+ ? files.filter((item) => item.label.replace(/\/$/, "").toLowerCase().includes(needle))
87
+ : [];
88
+ const others = files.filter((item) => !named.includes(item));
89
+ return [...named, ...sessions, ...others];
90
+ }
91
+ // The catalog keeps one list until its next reload, so the lower-case copies are made once per
92
+ // session and list, not once per keystroke.
93
+ const searches = new WeakMap();
94
+ function searchOf(session) {
95
+ let search = searches.get(session);
96
+ if (!search) {
97
+ search = {
98
+ id: session.id.toLowerCase(),
99
+ title: sessionTitle(session).toLowerCase(),
100
+ project: projectName(session).toLowerCase(),
101
+ source: SOURCE_NAMES[session.source].toLowerCase(),
102
+ };
103
+ searches.set(session, search);
104
+ }
105
+ return search;
106
+ }
107
+ /**
108
+ * Id and title matches rank above project matches, which rank above matches in the session's
109
+ * messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
110
+ */
111
+ export function matchSessions(sessions, query, excludePath, searchText) {
112
+ const needle = query.toLowerCase();
113
+ return sessions
114
+ .filter((session) => session.path !== excludePath && session.messageCount > 0)
115
+ .map((session) => ({ session, rank: needle ? matchRank(session, needle, searchText) : 1 }))
116
+ .filter(({ rank }) => rank > 0)
117
+ .sort((a, b) => b.rank - a.rank)
118
+ .map(({ session }) => session);
119
+ }
120
+ function matchRank(session, needle, searchText) {
121
+ const search = searchOf(session);
122
+ if (search.id.startsWith(needle) || search.title.includes(needle))
123
+ return 3;
124
+ if (search.project.includes(needle) || search.source.includes(needle))
125
+ return 2;
126
+ if (!searchText)
127
+ return 0;
128
+ search.text ??= session.allMessagesText.toLowerCase();
129
+ return search.text.includes(needle) ? 1 : 0;
130
+ }
131
+ /** Source, age and project fill pi's label column, which leaves the wide one for the title. */
132
+ function sessionItem(session, sessions, now) {
133
+ const source = `[${session.source}]`.padEnd(SOURCE_TAG_WIDTH);
134
+ const age = formatAge(now - session.modified.getTime()).padStart(3);
135
+ return {
136
+ value: mentionToken(session, sessions),
137
+ label: `${source} ${age} ${projectName(session)}`,
138
+ description: sessionTitle(session),
139
+ };
140
+ }
@@ -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
+ }