@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.
- package/CHANGELOG.md +77 -0
- package/README.md +117 -36
- package/dist/core/panel.d.ts +6 -1
- package/dist/core/panel.js +26 -1
- package/dist/core/settings.d.ts +9 -1
- package/dist/core/settings.js +36 -2
- package/dist/dock/registry.js +1 -0
- package/dist/extension.js +10 -2
- package/dist/mention/autocomplete.d.ts +25 -0
- package/dist/mention/autocomplete.js +140 -0
- package/dist/mention/budget.d.ts +8 -0
- package/dist/mention/budget.js +10 -0
- package/dist/mention/catalog.d.ts +43 -0
- package/dist/mention/catalog.js +117 -0
- package/dist/mention/claude.d.ts +2 -0
- package/dist/mention/claude.js +118 -0
- package/dist/mention/codex.d.ts +3 -0
- package/dist/mention/codex.js +135 -0
- package/dist/mention/external.d.ts +15 -0
- package/dist/mention/external.js +145 -0
- package/dist/mention/index.d.ts +17 -0
- package/dist/mention/index.js +151 -0
- package/dist/mention/jsonl.d.ts +9 -0
- package/dist/mention/jsonl.js +54 -0
- package/dist/mention/mention.d.ts +19 -0
- package/dist/mention/mention.js +60 -0
- package/dist/mention/pi.d.ts +11 -0
- package/dist/mention/pi.js +172 -0
- package/dist/mention/session-index.d.ts +66 -0
- package/dist/mention/session-index.js +303 -0
- package/dist/mention/session.d.ts +18 -0
- package/dist/mention/session.js +8 -0
- package/dist/mention/text.d.ts +12 -0
- package/dist/mention/text.js +47 -0
- package/dist/mention/transcript.d.ts +10 -0
- package/dist/mention/transcript.js +129 -0
- package/dist/panel/defined-section.js +34 -8
- package/dist/panel/definition.d.ts +26 -1
- package/dist/panel/definition.js +32 -2
- package/dist/panel/index.d.ts +3 -2
- package/dist/panel/index.js +1 -0
- package/dist/panel/panel.js +109 -29
- package/dist/panel/section.d.ts +49 -3
- package/dist/panel/section.js +59 -12
- package/dist/resources/scoped-extension.js +1 -0
- package/dist/settings/file-store.js +1 -0
- package/docs/dock.md +9 -3
- package/docs/panel.md +69 -2
- package/docs/public-api-design.md +9 -9
- package/docs/recipes.md +3 -8
- package/docs/settings.md +1 -1
- package/package.json +4 -4
- package/src/core/panel.ts +29 -1
- package/src/core/settings.ts +42 -2
- package/src/dock/registry.ts +1 -0
- package/src/extension.ts +11 -2
- package/src/mention/autocomplete.ts +177 -0
- package/src/mention/budget.ts +11 -0
- package/src/mention/catalog.ts +133 -0
- package/src/mention/claude.ts +127 -0
- package/src/mention/codex.ts +144 -0
- package/src/mention/external.ts +190 -0
- package/src/mention/index.ts +193 -0
- package/src/mention/jsonl.ts +56 -0
- package/src/mention/mention.ts +90 -0
- package/src/mention/pi.ts +192 -0
- package/src/mention/session-index.ts +356 -0
- package/src/mention/session.ts +27 -0
- package/src/mention/text.ts +52 -0
- package/src/mention/transcript.ts +155 -0
- package/src/panel/defined-section.ts +40 -7
- package/src/panel/definition.ts +67 -2
- package/src/panel/index.ts +4 -0
- package/src/panel/panel.ts +115 -29
- package/src/panel/section.ts +111 -15
- package/src/resources/scoped-extension.ts +1 -0
- package/src/settings/file-store.ts +1 -0
package/docs/panel.md
CHANGED
|
@@ -71,7 +71,12 @@ the error is shown; if `disabled` throws, editing is blocked and the error is sh
|
|
|
71
71
|
```ts
|
|
72
72
|
fields: [
|
|
73
73
|
{ path: "enabled", label: "Enabled" },
|
|
74
|
-
{
|
|
74
|
+
{
|
|
75
|
+
path: "retries",
|
|
76
|
+
label: "Retries",
|
|
77
|
+
group: "Advanced",
|
|
78
|
+
visible: ({ values }) => values.enabled,
|
|
79
|
+
},
|
|
75
80
|
{
|
|
76
81
|
path: "level",
|
|
77
82
|
label: "Level",
|
|
@@ -105,6 +110,65 @@ built for `/panel/host` (the `SettingsPanelField` type from `/panel`) gain the o
|
|
|
105
110
|
`visible(ctx, scope)`, `disabled(ctx, scope)` and `customEditor(hostContext)`, where the
|
|
106
111
|
host context omits `values`. See the [recipes](recipes.md) for complete examples.
|
|
107
112
|
|
|
113
|
+
## Secondary menus
|
|
114
|
+
|
|
115
|
+
A secondary menu is a row that opens a nested page of fields inside the same frame. Use it for
|
|
116
|
+
entries that a fixed field list cannot hold, such as records kept in files. Declared panels
|
|
117
|
+
take `menus`, listed after the fields in the same group order rules:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
defineSettingsPanel(settings, {
|
|
121
|
+
label: "Agents",
|
|
122
|
+
fields: (field) => [field("enabled", { label: "Enabled" })],
|
|
123
|
+
menus: [
|
|
124
|
+
{
|
|
125
|
+
id: "files",
|
|
126
|
+
label: "Agent files",
|
|
127
|
+
summary: ({ scope }) => `${listFiles(scope).length} files`,
|
|
128
|
+
open: ({ scope }) => ({
|
|
129
|
+
fields: listFiles(scope).map((file) => fileField(file, scope)),
|
|
130
|
+
emptyMessage: "No agent files yet.",
|
|
131
|
+
}),
|
|
132
|
+
},
|
|
133
|
+
],
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
`open({ values, scope, context })` returns a `SettingsMenu`: host-level `SettingsPanelField`
|
|
138
|
+
objects, which the consumer builds with its own `inspect`, `set` and `reset`, and an optional
|
|
139
|
+
`emptyMessage`. A menu ID must not repeat a field ID (a path, or a nested path as JSON).
|
|
140
|
+
|
|
141
|
+
To move declared Settings fields onto a page, give the menu no `open` and name it in each
|
|
142
|
+
field's `inMenu`. The page lists those fields in their declared order, with the usual editors,
|
|
143
|
+
scopes and group rules, and the section no longer lists them:
|
|
144
|
+
|
|
145
|
+
```ts
|
|
146
|
+
defineSettingsPanel(settings, {
|
|
147
|
+
label: "Routing",
|
|
148
|
+
fields: (field) => [
|
|
149
|
+
field("enabled", { label: "Enabled" }),
|
|
150
|
+
field(["tiers", "fast"], { label: "Fast", inMenu: "tiers" }),
|
|
151
|
+
field(["tiers", "strong"], { label: "Strong", inMenu: "tiers" }),
|
|
152
|
+
],
|
|
153
|
+
menus: [{ id: "tiers", label: "Tiers", summary: ({ values }) => describe(values.tiers) }],
|
|
154
|
+
});
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A menu needs either `open` or at least one field that names it, not both, and `inMenu` must
|
|
158
|
+
name a menu of the same panel.
|
|
159
|
+
`summary`, `visible` and `disabled` work like the matching field options. Custom hosts build a
|
|
160
|
+
menu row with `createSettingsMenuField({ id, label, scopes, summary?, menu })`, and menu fields
|
|
161
|
+
may be menu rows themselves, so menus nest.
|
|
162
|
+
|
|
163
|
+
The renderer marks menu rows with `→` and shows the summary as the row value. Enter opens the
|
|
164
|
+
menu, Esc goes back one level, and the title shows the path, such as
|
|
165
|
+
`Lune settings › Agents › reviewer · global`. The open menu is kept as the IDs on its path and
|
|
166
|
+
built again from its rows on every refresh: after each save, scope switch (Ctrl+G) or reload.
|
|
167
|
+
Its fields therefore follow external data, and a menu whose row disappears closes; keep row IDs
|
|
168
|
+
stable when an entry changes. Switching sections closes every menu. A menu row has no value:
|
|
169
|
+
Ctrl+R on it reports that the settings inside it are reset there, and `set` and `reset` of a
|
|
170
|
+
`createSettingsMenuField` row reject.
|
|
171
|
+
|
|
108
172
|
## Opening and keyboard controls
|
|
109
173
|
|
|
110
174
|
Import `openSettingsPanel` from `/panel/tui`, not `/panel`.
|
|
@@ -120,9 +184,12 @@ Equal labels are ordered by section ID using the same comparison. Membership cha
|
|
|
120
184
|
reapply this order while preserving the selected section if it remains registered.
|
|
121
185
|
The registry itself still returns registration order.
|
|
122
186
|
|
|
123
|
-
- Main list: Tab/Shift+Tab switch sections; Ctrl+G switches global/project;
|
|
187
|
+
- Main list: Tab/Shift+Tab or Right/Left switch sections; Ctrl+G switches global/project;
|
|
124
188
|
Ctrl+R resets the selected override; Ctrl+S reloads the active section (or retries one that failed to load).
|
|
189
|
+
Enter on a menu row opens it; Escape goes back one menu, then closes the panel.
|
|
125
190
|
- Editor: Enter saves; Ctrl+S saves and then reloads; Escape discards the candidate.
|
|
191
|
+
Text inputs, choice lists and custom editors keep Left/Right, so arrows do not switch
|
|
192
|
+
sections while one is open.
|
|
126
193
|
- Choice list: type to search; Tab switches candidate ranges; Ctrl+R explicitly refreshes
|
|
127
194
|
supported sources; Space toggles multiple selections.
|
|
128
195
|
- Preview choices render unsaved candidates; persistence occurs only on confirmation.
|
|
@@ -32,15 +32,15 @@ internal observer, without another lifecycle owner or public subscription API.
|
|
|
32
32
|
|
|
33
33
|
## Initialization and ownership
|
|
34
34
|
|
|
35
|
-
| Resource
|
|
36
|
-
|
|
|
37
|
-
| Static Settings/Panel definitions
|
|
38
|
-
| Binding listeners and pending acquisition
|
|
39
|
-
| View, subscriptions and backend token
|
|
40
|
-
| Shared namespaces and file queues
|
|
41
|
-
| Panel section and binding subscription
|
|
42
|
-
| Editor, choices, preview and interaction subscriptions | Open Panel interaction
|
|
43
|
-
| Business timers, requests and local objects
|
|
35
|
+
| Resource | Owner | Retirement |
|
|
36
|
+
| ------------------------------------------------------ | ------------------------------- | ---------------------------------------- |
|
|
37
|
+
| Static Settings/Panel definitions | Declaring plugin | No runtime resources |
|
|
38
|
+
| Binding listeners and pending acquisition | SettingsBinding | Shutdown/explicit dispose |
|
|
39
|
+
| View, subscriptions and backend token | Binding or explicit lease owner | Session retirement |
|
|
40
|
+
| Shared namespaces and file queues | Core Host | Last reference/queue settlement |
|
|
41
|
+
| Panel section and binding subscription | SettingsPanelRegistration | Dispose/binding retirement |
|
|
42
|
+
| Editor, choices, preview and interaction subscriptions | Open Panel interaction | Close/section removal/view retirement |
|
|
43
|
+
| Business timers, requests and local objects | Plugin | Its native lifecycle and business policy |
|
|
44
44
|
|
|
45
45
|
`scopedExtension((pi, resources) => ...)` is the preferred wrapper: it creates the
|
|
46
46
|
ResourceScope, registers its `session_shutdown` disposer first, runs setup, and disposes
|
package/docs/recipes.md
CHANGED
|
@@ -86,9 +86,7 @@ reference with Pi when you use it:
|
|
|
86
86
|
|
|
87
87
|
```ts
|
|
88
88
|
const reference = view.get("model");
|
|
89
|
-
const model = reference
|
|
90
|
-
? ctx.modelRegistry.find(reference.provider, reference.id)
|
|
91
|
-
: ctx.model; // "Follow session model"
|
|
89
|
+
const model = reference ? ctx.modelRegistry.find(reference.provider, reference.id) : ctx.model; // "Follow session model"
|
|
92
90
|
```
|
|
93
91
|
|
|
94
92
|
## React to changes
|
|
@@ -134,7 +132,7 @@ const settings = defineSettings({
|
|
|
134
132
|
|
|
135
133
|
Rules of thumb:
|
|
136
134
|
|
|
137
|
-
- The current version is `migrations.length + 1`. Stored data at version
|
|
135
|
+
- The current version is `migrations.length + 1`. Stored data at version _n_ passes through
|
|
138
136
|
`migrations[n - 1]`, so append new migrations and never reorder or delete shipped ones.
|
|
139
137
|
- A migration receives an isolated copy of one file's overrides (no defaults, no
|
|
140
138
|
`$version`) and returns the overrides for the next version. Keep it synchronous and pure.
|
|
@@ -322,10 +320,7 @@ class ListEditor implements SettingsEditorComponent {
|
|
|
322
320
|
readonly help = "Enter save · comma-separated";
|
|
323
321
|
private readonly input = new Input();
|
|
324
322
|
|
|
325
|
-
constructor(
|
|
326
|
-
value: readonly string[],
|
|
327
|
-
submit: (value: string[]) => void,
|
|
328
|
-
) {
|
|
323
|
+
constructor(value: readonly string[], submit: (value: string[]) => void) {
|
|
329
324
|
this.input.setValue(value.join(", "));
|
|
330
325
|
this.input.onSubmit = (text) =>
|
|
331
326
|
submit(
|
package/docs/settings.md
CHANGED
|
@@ -59,7 +59,7 @@ keys.
|
|
|
59
59
|
|
|
60
60
|
### Schema evolution
|
|
61
61
|
|
|
62
|
-
The current version is `migrations.length + 1`. Stored data at version
|
|
62
|
+
The current version is `migrations.length + 1`. Stored data at version _n_ is passed through
|
|
63
63
|
`migrations[n - 1]`, then onward, when the file is loaded; the upgraded file is written back
|
|
64
64
|
with its new `$version`. A migration receives an isolated copy of one scope's overrides
|
|
65
65
|
(no defaults, no `$` metadata) and returns the next version's overrides; keep it
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lune_99/pi-lune-extensions-core",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Shared infrastructure for the Lune series of Pi extensions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -102,9 +102,9 @@
|
|
|
102
102
|
},
|
|
103
103
|
"dependencies": {},
|
|
104
104
|
"devDependencies": {
|
|
105
|
-
"@earendil-works/pi-ai": "
|
|
106
|
-
"@earendil-works/pi-coding-agent": "
|
|
107
|
-
"@earendil-works/pi-tui": "
|
|
105
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
106
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
107
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
108
108
|
"@types/node": "^22.20.2",
|
|
109
109
|
"typescript": "5.9.3"
|
|
110
110
|
},
|
package/src/core/panel.ts
CHANGED
|
@@ -1,7 +1,35 @@
|
|
|
1
1
|
import { defineSettingsPanel } from "../panel/definition.ts";
|
|
2
|
-
import { coreSettings } from "./settings.ts";
|
|
2
|
+
import { coreSettings, MENTION_CACHE_MAX_MB, MENTION_CACHE_MIN_MB } from "./settings.ts";
|
|
3
3
|
|
|
4
4
|
export const corePanel = defineSettingsPanel(coreSettings, {
|
|
5
5
|
id: "core",
|
|
6
6
|
label: "Core",
|
|
7
|
+
fields: (field) => [
|
|
8
|
+
field(["mention", "cacheSizeMB"], {
|
|
9
|
+
label: "Session cache size",
|
|
10
|
+
description:
|
|
11
|
+
`The index on disk behind the @ and @@ session lists, ${MENTION_CACHE_MIN_MB} to ` +
|
|
12
|
+
`${MENTION_CACHE_MAX_MB} MB. Sessions older than what fits are not listed and ` +
|
|
13
|
+
`cannot be mentioned. Larger values retain more sessions and take longer to load.`,
|
|
14
|
+
inMenu: "mention",
|
|
15
|
+
formatValue: (value) => `${value} MB`,
|
|
16
|
+
}),
|
|
17
|
+
field(["mention", "textLimit"], {
|
|
18
|
+
label: "Session text limit",
|
|
19
|
+
description:
|
|
20
|
+
"Characters kept from each session's first message and searchable text. " +
|
|
21
|
+
"Use a positive integer; a change applies at the next load of the session list.",
|
|
22
|
+
inMenu: "mention",
|
|
23
|
+
formatValue: (value) => `${value} characters`,
|
|
24
|
+
}),
|
|
25
|
+
],
|
|
26
|
+
menus: [
|
|
27
|
+
{
|
|
28
|
+
id: "mention",
|
|
29
|
+
label: "Mention",
|
|
30
|
+
description: "Settings for @ and @@ session mentions.",
|
|
31
|
+
summary: ({ values }) =>
|
|
32
|
+
`cache ${values.mention.cacheSizeMB} MB · text ${values.mention.textLimit} chars`,
|
|
33
|
+
},
|
|
34
|
+
],
|
|
7
35
|
});
|
package/src/core/settings.ts
CHANGED
|
@@ -1,8 +1,48 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
+
import { INDEX_BUDGET_MB, SESSION_TEXT_LIMIT } from "../mention/budget.ts";
|
|
2
3
|
import { defineSettings } from "../settings/definition.ts";
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
/** Bounds of the session index size a user can choose, in megabytes. */
|
|
6
|
+
export const MENTION_CACHE_MIN_MB = 1;
|
|
7
|
+
export const MENTION_CACHE_MAX_MB = 64;
|
|
8
|
+
|
|
5
9
|
export const coreSettings = defineSettings({
|
|
6
10
|
id: "pi-lune-extensions-core",
|
|
7
|
-
schema: Type.Object({
|
|
11
|
+
schema: Type.Object({
|
|
12
|
+
mention: Type.Object(
|
|
13
|
+
{
|
|
14
|
+
cacheSizeMB: Type.Integer({
|
|
15
|
+
minimum: MENTION_CACHE_MIN_MB,
|
|
16
|
+
maximum: MENTION_CACHE_MAX_MB,
|
|
17
|
+
default: INDEX_BUDGET_MB,
|
|
18
|
+
}),
|
|
19
|
+
textLimit: Type.Integer({ minimum: 1, default: SESSION_TEXT_LIMIT }),
|
|
20
|
+
},
|
|
21
|
+
{
|
|
22
|
+
additionalProperties: false,
|
|
23
|
+
default: { cacheSizeMB: INDEX_BUDGET_MB, textLimit: SESSION_TEXT_LIMIT },
|
|
24
|
+
},
|
|
25
|
+
),
|
|
26
|
+
}),
|
|
27
|
+
migrations: [
|
|
28
|
+
(overrides) => {
|
|
29
|
+
const mention = overrides["mention"];
|
|
30
|
+
// Object overrides replace the whole value, so the new leaf needs a migration.
|
|
31
|
+
if (
|
|
32
|
+
typeof mention === "object" &&
|
|
33
|
+
mention !== null &&
|
|
34
|
+
!Array.isArray(mention) &&
|
|
35
|
+
!Object.hasOwn(mention, "textLimit")
|
|
36
|
+
) {
|
|
37
|
+
return {
|
|
38
|
+
...overrides,
|
|
39
|
+
mention: { ...mention, textLimit: SESSION_TEXT_LIMIT },
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return overrides;
|
|
43
|
+
},
|
|
44
|
+
],
|
|
45
|
+
// Every Pi process shares one index file. Projects with different sizes would make each
|
|
46
|
+
// process trim what the other read, so the file is read again on every load.
|
|
47
|
+
globalOnly: ["mention"],
|
|
8
48
|
});
|
package/src/dock/registry.ts
CHANGED
|
@@ -140,6 +140,7 @@ export function createDockRegistry(): DockRegistry {
|
|
|
140
140
|
try {
|
|
141
141
|
notifyPresence(state.contributions.values(), false);
|
|
142
142
|
} catch (cleanupError) {
|
|
143
|
+
// eslint-disable-next-line preserve-caught-error -- AggregateError.errors retains both failures.
|
|
143
144
|
throw new AggregateError(
|
|
144
145
|
[error, cleanupError],
|
|
145
146
|
"Lune dock host attachment and cleanup failed",
|
package/src/extension.ts
CHANGED
|
@@ -1,15 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Optional Pi package entry for the shared command
|
|
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.ts";
|
|
9
11
|
import { coreSettings } from "./core/settings.ts";
|
|
10
12
|
import { registerSettingsPanel } from "./panel/registration.ts";
|
|
11
13
|
import { openSettingsPanel } from "./panel/tui.ts";
|
|
12
14
|
import { scopedExtension } from "./resources/scoped-extension.ts";
|
|
15
|
+
import { installMentions } from "./mention/index.ts";
|
|
16
|
+
import { megabytes } from "./mention/budget.ts";
|
|
13
17
|
import { bindSettings } from "./settings/binding.ts";
|
|
14
18
|
|
|
15
19
|
/**
|
|
@@ -32,4 +36,9 @@ export default scopedExtension((pi, resources) => {
|
|
|
32
36
|
await openSettingsPanel(ctx, { section: args.trim() || undefined });
|
|
33
37
|
},
|
|
34
38
|
});
|
|
39
|
+
installMentions(pi, resources, {
|
|
40
|
+
indexBudget: async (ctx) =>
|
|
41
|
+
megabytes((await settings.view(ctx)).get("mention").cacheSizeMB),
|
|
42
|
+
indexTextLimit: async (ctx) => (await settings.view(ctx)).get("mention").textLimit,
|
|
43
|
+
});
|
|
35
44
|
});
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import type { AutocompleteItem, AutocompleteProvider } from "@earendil-works/pi-tui";
|
|
2
|
+
import type { SessionCatalog } from "./catalog.ts";
|
|
3
|
+
import { mentionToken } from "./mention.ts";
|
|
4
|
+
import { SOURCE_NAMES, type LocalSession } from "./session.ts";
|
|
5
|
+
import { formatAge, projectName, SEPARATOR, sessionTitle, TOKEN_BOUNDARY } from "./text.ts";
|
|
6
|
+
|
|
7
|
+
/** `@@query` lists sessions only and searches their messages too. */
|
|
8
|
+
export const SESSION_TRIGGER = "@@";
|
|
9
|
+
/** Source tags are padded to the widest one so the age and project columns line up. */
|
|
10
|
+
const SOURCE_TAG_WIDTH = Math.max(...Object.keys(SOURCE_NAMES).map((source) => source.length + 2));
|
|
11
|
+
/** Session rows in the list for a plain `@query`. */
|
|
12
|
+
const SESSION_ROWS = 3;
|
|
13
|
+
/** Rows for `@@query`; the search itself covers every local session. */
|
|
14
|
+
const SESSION_LIST_ROWS = 50;
|
|
15
|
+
/** An `@` at a word start, up to the cursor. A quote after it is pi's quoted path syntax. */
|
|
16
|
+
const AT_WORD = new RegExp(`${TOKEN_BOUNDARY}(@(?:(?!${SEPARATOR})[^"])*)$`, "u");
|
|
17
|
+
|
|
18
|
+
export interface MentionAutocompleteOptions {
|
|
19
|
+
catalog: SessionCatalog;
|
|
20
|
+
/** The running session's file, left out of the list. */
|
|
21
|
+
currentSessionFile: string | undefined;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* `@query` lists matching sessions with pi's own file matches, and `@@query` lists sessions only.
|
|
26
|
+
* Everything that is not an `@` token goes to the provider underneath.
|
|
27
|
+
*
|
|
28
|
+
* A plain `@` never waits for the session list: its rows come from what the catalog has read,
|
|
29
|
+
* so file matches are not delayed. `@@` lists nothing but sessions, and the editor asks again
|
|
30
|
+
* only on a keystroke, so before the first load it waits for that load instead of answering
|
|
31
|
+
* empty. The editor aborts a pending request on the next keystroke, which ends the wait.
|
|
32
|
+
*/
|
|
33
|
+
export function createMentionAutocomplete(
|
|
34
|
+
current: AutocompleteProvider,
|
|
35
|
+
options: MentionAutocompleteOptions,
|
|
36
|
+
): AutocompleteProvider {
|
|
37
|
+
// The editor passes back the item objects it received, so membership marks session rows.
|
|
38
|
+
const sessionRows = new WeakSet<AutocompleteItem>();
|
|
39
|
+
const sessionItems = (query: string, limit: number, searchText: boolean) => {
|
|
40
|
+
const sessions = options.catalog.snapshot();
|
|
41
|
+
const now = Date.now();
|
|
42
|
+
return matchSessions(sessions, query, options.currentSessionFile, searchText)
|
|
43
|
+
.slice(0, limit)
|
|
44
|
+
.map((session) => {
|
|
45
|
+
const item = sessionItem(session, sessions, now);
|
|
46
|
+
sessionRows.add(item);
|
|
47
|
+
return item;
|
|
48
|
+
});
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
triggerCharacters: current.triggerCharacters,
|
|
53
|
+
shouldTriggerFileCompletion: current.shouldTriggerFileCompletion
|
|
54
|
+
? (lines, cursorLine, cursorCol) =>
|
|
55
|
+
current.shouldTriggerFileCompletion!(lines, cursorLine, cursorCol)
|
|
56
|
+
: undefined,
|
|
57
|
+
|
|
58
|
+
async getSuggestions(lines, cursorLine, cursorCol, request) {
|
|
59
|
+
const prefix = AT_WORD.exec((lines[cursorLine] ?? "").slice(0, cursorCol))?.[1];
|
|
60
|
+
if (!prefix) return current.getSuggestions(lines, cursorLine, cursorCol, request);
|
|
61
|
+
if (prefix.startsWith(SESSION_TRIGGER)) {
|
|
62
|
+
await options.catalog.whenLoaded(request.signal);
|
|
63
|
+
if (request.signal.aborted) return null;
|
|
64
|
+
const query = prefix.slice(SESSION_TRIGGER.length);
|
|
65
|
+
const items = sessionItems(query, SESSION_LIST_ROWS, true);
|
|
66
|
+
return items.length > 0 ? { items, prefix } : null;
|
|
67
|
+
}
|
|
68
|
+
const query = prefix.slice(1);
|
|
69
|
+
// A folder in the query names a path.
|
|
70
|
+
const sessions = query.includes("/") ? [] : sessionItems(query, SESSION_ROWS, false);
|
|
71
|
+
const files = await current.getSuggestions(lines, cursorLine, cursorCol, request);
|
|
72
|
+
if (request.signal.aborted) return null;
|
|
73
|
+
// No rows to add, or the provider underneath read a different token.
|
|
74
|
+
if (sessions.length === 0 || (files && files.prefix !== prefix)) return files;
|
|
75
|
+
const items = withSessions(files?.items ?? [], sessions, query);
|
|
76
|
+
return items.length > 0 ? { items, prefix } : null;
|
|
77
|
+
},
|
|
78
|
+
|
|
79
|
+
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
80
|
+
if (!sessionRows.has(item)) {
|
|
81
|
+
return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
82
|
+
}
|
|
83
|
+
const line = lines[cursorLine] ?? "";
|
|
84
|
+
const start = cursorCol - prefix.length;
|
|
85
|
+
const inserted = `${item.value} `;
|
|
86
|
+
const next = [...lines];
|
|
87
|
+
next[cursorLine] = line.slice(0, start) + inserted + line.slice(cursorCol);
|
|
88
|
+
return { lines: next, cursorLine, cursorCol: start + inserted.length };
|
|
89
|
+
},
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Sessions come first, except after files whose name contains the query. The editor selects the
|
|
95
|
+
* first row, so Tab after a typed file name still picks that file and not a session.
|
|
96
|
+
*/
|
|
97
|
+
function withSessions(
|
|
98
|
+
files: readonly AutocompleteItem[],
|
|
99
|
+
sessions: readonly AutocompleteItem[],
|
|
100
|
+
query: string,
|
|
101
|
+
): AutocompleteItem[] {
|
|
102
|
+
const needle = query.toLowerCase();
|
|
103
|
+
const named = needle
|
|
104
|
+
? files.filter((item) => item.label.replace(/\/$/, "").toLowerCase().includes(needle))
|
|
105
|
+
: [];
|
|
106
|
+
const others = files.filter((item) => !named.includes(item));
|
|
107
|
+
return [...named, ...sessions, ...others];
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
interface SessionSearch {
|
|
111
|
+
id: string;
|
|
112
|
+
title: string;
|
|
113
|
+
project: string;
|
|
114
|
+
source: string;
|
|
115
|
+
text?: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// The catalog keeps one list until its next reload, so the lower-case copies are made once per
|
|
119
|
+
// session and list, not once per keystroke.
|
|
120
|
+
const searches = new WeakMap<LocalSession, SessionSearch>();
|
|
121
|
+
|
|
122
|
+
function searchOf(session: LocalSession): SessionSearch {
|
|
123
|
+
let search = searches.get(session);
|
|
124
|
+
if (!search) {
|
|
125
|
+
search = {
|
|
126
|
+
id: session.id.toLowerCase(),
|
|
127
|
+
title: sessionTitle(session).toLowerCase(),
|
|
128
|
+
project: projectName(session).toLowerCase(),
|
|
129
|
+
source: SOURCE_NAMES[session.source].toLowerCase(),
|
|
130
|
+
};
|
|
131
|
+
searches.set(session, search);
|
|
132
|
+
}
|
|
133
|
+
return search;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Id and title matches rank above project matches, which rank above matches in the session's
|
|
138
|
+
* messages. Equal ranks keep the catalog's newest-first order because the sort is stable.
|
|
139
|
+
*/
|
|
140
|
+
export function matchSessions(
|
|
141
|
+
sessions: readonly LocalSession[],
|
|
142
|
+
query: string,
|
|
143
|
+
excludePath: string | undefined,
|
|
144
|
+
searchText: boolean,
|
|
145
|
+
): LocalSession[] {
|
|
146
|
+
const needle = query.toLowerCase();
|
|
147
|
+
return sessions
|
|
148
|
+
.filter((session) => session.path !== excludePath && session.messageCount > 0)
|
|
149
|
+
.map((session) => ({ session, rank: needle ? matchRank(session, needle, searchText) : 1 }))
|
|
150
|
+
.filter(({ rank }) => rank > 0)
|
|
151
|
+
.sort((a, b) => b.rank - a.rank)
|
|
152
|
+
.map(({ session }) => session);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function matchRank(session: LocalSession, needle: string, searchText: boolean): number {
|
|
156
|
+
const search = searchOf(session);
|
|
157
|
+
if (search.id.startsWith(needle) || search.title.includes(needle)) return 3;
|
|
158
|
+
if (search.project.includes(needle) || search.source.includes(needle)) return 2;
|
|
159
|
+
if (!searchText) return 0;
|
|
160
|
+
search.text ??= session.allMessagesText.toLowerCase();
|
|
161
|
+
return search.text.includes(needle) ? 1 : 0;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** Source, age and project fill pi's label column, which leaves the wide one for the title. */
|
|
165
|
+
function sessionItem(
|
|
166
|
+
session: LocalSession,
|
|
167
|
+
sessions: readonly LocalSession[],
|
|
168
|
+
now: number,
|
|
169
|
+
): AutocompleteItem {
|
|
170
|
+
const source = `[${session.source}]`.padEnd(SOURCE_TAG_WIDTH);
|
|
171
|
+
const age = formatAge(now - session.modified.getTime()).padStart(3);
|
|
172
|
+
return {
|
|
173
|
+
value: mentionToken(session, sessions),
|
|
174
|
+
label: `${source} ${age} ${projectName(session)}`,
|
|
175
|
+
description: sessionTitle(session),
|
|
176
|
+
};
|
|
177
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
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
|
+
|
|
8
|
+
/** Megabytes (MiB) to bytes. */
|
|
9
|
+
export function megabytes(size: number): number {
|
|
10
|
+
return size * 1024 * 1024;
|
|
11
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { SESSION_TEXT_LIMIT } from "./budget.ts";
|
|
2
|
+
import { ExternalSessions } from "./external.ts";
|
|
3
|
+
import { PiSessions } from "./pi.ts";
|
|
4
|
+
import { INDEX_BUDGET_BYTES, SessionIndex, sessionIndexFile } from "./session-index.ts";
|
|
5
|
+
import type { LocalSession } from "./session.ts";
|
|
6
|
+
|
|
7
|
+
/** A list older than this is reloaded in the background on the next lookup. */
|
|
8
|
+
const REFRESH_AFTER_MS = 60_000;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The newest local Pi, Codex and Claude Code main sessions that fit the index budget, newest
|
|
12
|
+
* activity first. Each load asks for the budget again, so a changed setting applies to the
|
|
13
|
+
* next load.
|
|
14
|
+
*
|
|
15
|
+
* Every load checks each session file and reads only those that changed since the saved
|
|
16
|
+
* index. Lookups serve the cached list and reload it in the background. The owner disposes
|
|
17
|
+
* the catalog on session shutdown; a load that finishes later is discarded.
|
|
18
|
+
*/
|
|
19
|
+
export class SessionCatalog {
|
|
20
|
+
private readonly onBackgroundError: (error: unknown) => void;
|
|
21
|
+
private readonly budget: () => Promise<number>;
|
|
22
|
+
private readonly textLimit: () => Promise<number>;
|
|
23
|
+
private readonly abort = new AbortController();
|
|
24
|
+
private readonly index = new SessionIndex(sessionIndexFile());
|
|
25
|
+
private readonly pi: PiSessions;
|
|
26
|
+
private readonly external = new ExternalSessions();
|
|
27
|
+
private sessions: readonly LocalSession[] = [];
|
|
28
|
+
private loaded = false;
|
|
29
|
+
private loadedAt = 0;
|
|
30
|
+
private loading: Promise<readonly LocalSession[]> | undefined;
|
|
31
|
+
|
|
32
|
+
/** `budget` gives the bytes the session index may keep. */
|
|
33
|
+
constructor(
|
|
34
|
+
sessionDir: string,
|
|
35
|
+
onBackgroundError: (error: unknown) => void,
|
|
36
|
+
budget: () => Promise<number> = async () => INDEX_BUDGET_BYTES,
|
|
37
|
+
textLimit: () => Promise<number> = async () => SESSION_TEXT_LIMIT,
|
|
38
|
+
) {
|
|
39
|
+
this.pi = new PiSessions(sessionDir);
|
|
40
|
+
this.onBackgroundError = onBackgroundError;
|
|
41
|
+
this.budget = budget;
|
|
42
|
+
this.textLimit = textLimit;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** The cached list, empty before the first load. A stale list starts a background reload. */
|
|
46
|
+
snapshot(): readonly LocalSession[] {
|
|
47
|
+
if (Date.now() - this.loadedAt > REFRESH_AFTER_MS) this.refreshInBackground();
|
|
48
|
+
return this.sessions;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Waits only for the first load; later lookups return the cached list at once. */
|
|
52
|
+
async list(): Promise<readonly LocalSession[]> {
|
|
53
|
+
return this.loaded ? this.snapshot() : this.reload();
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Settles when the first load does or when `signal` aborts. Whoever started the load
|
|
58
|
+
* handles its failure, so a waiting caller only reads snapshot() again.
|
|
59
|
+
*
|
|
60
|
+
* A failed first load is retried here. snapshot() only retries a stale list, and `@@`
|
|
61
|
+
* would otherwise stay empty for a minute after a transient read error.
|
|
62
|
+
*/
|
|
63
|
+
async whenLoaded(signal: AbortSignal): Promise<void> {
|
|
64
|
+
if (this.loaded) return;
|
|
65
|
+
this.refreshInBackground();
|
|
66
|
+
const loading = this.loading;
|
|
67
|
+
if (!loading || signal.aborted) return;
|
|
68
|
+
await new Promise<void>((resolve) => {
|
|
69
|
+
const settle = () => {
|
|
70
|
+
signal.removeEventListener("abort", settle);
|
|
71
|
+
resolve();
|
|
72
|
+
};
|
|
73
|
+
signal.addEventListener("abort", settle, { once: true });
|
|
74
|
+
loading.then(settle, settle);
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Concurrent callers share one load. */
|
|
79
|
+
reload(): Promise<readonly LocalSession[]> {
|
|
80
|
+
this.loadedAt = Date.now();
|
|
81
|
+
this.loading ??= this.load().finally(() => {
|
|
82
|
+
this.loading = undefined;
|
|
83
|
+
});
|
|
84
|
+
return this.loading;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
dispose(): void {
|
|
88
|
+
this.abort.abort();
|
|
89
|
+
this.external.clear();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
private async load(): Promise<readonly LocalSession[]> {
|
|
93
|
+
const signal = this.abort.signal;
|
|
94
|
+
// A failed index only costs a full read; the scan below writes a new one.
|
|
95
|
+
await this.index.load(signal).catch((error: unknown) => this.report(error));
|
|
96
|
+
// Settings that cannot be read are reported where they are edited; the session list
|
|
97
|
+
// keeps working with the default size instead.
|
|
98
|
+
this.index.budget = await this.budget().catch(() => INDEX_BUDGET_BYTES);
|
|
99
|
+
this.index.textLimit = await this.textLimit().catch(() => SESSION_TEXT_LIMIT);
|
|
100
|
+
const [pi, external] = await Promise.all([
|
|
101
|
+
this.pi.list(signal),
|
|
102
|
+
this.external.list(signal, this.onBackgroundError),
|
|
103
|
+
]);
|
|
104
|
+
// Pi first, so sessions with equal activity times keep listAll's order.
|
|
105
|
+
const { sessions: listed, errors } = await this.index.scan([...pi, ...external], signal);
|
|
106
|
+
signal.throwIfAborted();
|
|
107
|
+
if (errors.length > 0) {
|
|
108
|
+
this.report(
|
|
109
|
+
new AggregateError(errors, errors.map((error) => error.message).join("\n")),
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
await this.index.save().catch((error: unknown) => this.report(error));
|
|
113
|
+
signal.throwIfAborted();
|
|
114
|
+
const sessions = listed.sort(
|
|
115
|
+
(left, right) => right.modified.getTime() - left.modified.getTime(),
|
|
116
|
+
);
|
|
117
|
+
this.sessions = sessions;
|
|
118
|
+
this.loaded = true;
|
|
119
|
+
return sessions;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private refreshInBackground(): void {
|
|
123
|
+
if (this.loading || this.abort.signal.aborted) return;
|
|
124
|
+
this.reload().catch((error: unknown) => {
|
|
125
|
+
if (!this.abort.signal.aborted) this.onBackgroundError(error);
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
private report(error: unknown): void {
|
|
130
|
+
this.abort.signal.throwIfAborted();
|
|
131
|
+
this.onBackgroundError(error);
|
|
132
|
+
}
|
|
133
|
+
}
|