@michalkvasnicak/pi-contextor 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/extension.ts +257 -0
- package/package.json +52 -4
- package/skills/contextor/SKILL.md +26 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michal Kvasničák
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/extension.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
2
|
+
import { Container, fuzzyFilter, MouseRegion, Text } from '@earendil-works/pi-tui';
|
|
3
|
+
|
|
4
|
+
const MESSAGE_TYPE = 'contextor-features';
|
|
5
|
+
const QUERY_ENTRY_TYPE = 'contextor-query';
|
|
6
|
+
const INDEX_TIMEOUT_MS = 120_000;
|
|
7
|
+
const LIST_CACHE_MS = 2_000;
|
|
8
|
+
const MAX_SUGGESTIONS = 20;
|
|
9
|
+
const COMPLETION_PREFIX = /(?:^|\s)(#([^\s#{}]*))$/u;
|
|
10
|
+
const FEATURE_REFERENCE = /#\{([^\s{}]+)\}/gu;
|
|
11
|
+
|
|
12
|
+
const CLI_INSTALL_HELP =
|
|
13
|
+
'The Contextor CLI (`contextor`) was not found on Pi’s PATH. ' +
|
|
14
|
+
'Download the archive for this OS and CPU from https://github.com/michalkvasnicak/contextor/releases/latest, ' +
|
|
15
|
+
'extract it, and put the `contextor` executable in a directory on Pi’s PATH. ' +
|
|
16
|
+
'Verify with `contextor --version`, then run `contextor index` in the project and retry.';
|
|
17
|
+
|
|
18
|
+
class ContextorNotFoundError extends Error {}
|
|
19
|
+
|
|
20
|
+
type QueryResult = { locations: string } | { error: unknown };
|
|
21
|
+
|
|
22
|
+
export default function (pi: ExtensionAPI): void {
|
|
23
|
+
const draftQueries = new Map<string, Promise<QueryResult>>();
|
|
24
|
+
const clickedExpansion = new WeakMap<object, { global: boolean; open: boolean }>();
|
|
25
|
+
let featureListCache: { request: Promise<string[]>; expiresAt: number } | undefined;
|
|
26
|
+
|
|
27
|
+
async function runContextor(cwd: string, args: string[], timeout = 5_000): Promise<string> {
|
|
28
|
+
const result = await pi.exec('contextor', args, { cwd, timeout });
|
|
29
|
+
if (result.code !== 0) {
|
|
30
|
+
const stderr = result.stderr.trim();
|
|
31
|
+
// Pi reports spawn failures through stderr rather than throwing them.
|
|
32
|
+
if (stderr === 'spawn contextor ENOENT') {
|
|
33
|
+
throw new ContextorNotFoundError(CLI_INSTALL_HELP);
|
|
34
|
+
}
|
|
35
|
+
throw new Error(stderr || `contextor exited with code ${result.code}`);
|
|
36
|
+
}
|
|
37
|
+
return result.stdout.trim();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function queryFeature(cwd: string, feature: string): Promise<QueryResult> {
|
|
41
|
+
try {
|
|
42
|
+
return { locations: await runContextor(cwd, ['query', '--', feature]) };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return { error };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function collectContext(prompt: string, ctx: ExtensionContext) {
|
|
49
|
+
const features = [
|
|
50
|
+
...new Set(Array.from(prompt.matchAll(FEATURE_REFERENCE), (match) => match[1])),
|
|
51
|
+
];
|
|
52
|
+
const queries = features.map(
|
|
53
|
+
(feature) => draftQueries.get(feature) ?? queryFeature(ctx.cwd, feature),
|
|
54
|
+
);
|
|
55
|
+
draftQueries.clear();
|
|
56
|
+
const results = await Promise.all(queries);
|
|
57
|
+
const attached: string[] = [];
|
|
58
|
+
const blocks: string[] = [];
|
|
59
|
+
let cliMissing = false;
|
|
60
|
+
for (const [index, feature] of features.entries()) {
|
|
61
|
+
const result = results[index];
|
|
62
|
+
if ('error' in result) {
|
|
63
|
+
if (result.error instanceof ContextorNotFoundError) {
|
|
64
|
+
cliMissing = true;
|
|
65
|
+
} else {
|
|
66
|
+
ctx.ui.notify(`Contextor could not query ${feature}: ${String(result.error)}`, 'warning');
|
|
67
|
+
}
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
attached.push(feature);
|
|
71
|
+
blocks.push(`#{${feature}}\n${result.locations || '(no indexed matches)'}`);
|
|
72
|
+
}
|
|
73
|
+
const sections: string[] = [];
|
|
74
|
+
if (blocks.length > 0) {
|
|
75
|
+
sections.push(
|
|
76
|
+
`Contextor feature locations (paths relative to the working directory):\n\n${blocks.join('\n\n')}`,
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
if (cliMissing) sections.push(CLI_INSTALL_HELP);
|
|
80
|
+
if (sections.length > 0) {
|
|
81
|
+
return { content: sections.join('\n\n'), features: attached };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
pi.registerEntryRenderer<{ feature: string; locations: string }>(
|
|
86
|
+
QUERY_ENTRY_TYPE,
|
|
87
|
+
(entry, _options, theme) => {
|
|
88
|
+
if (!entry.data) return undefined;
|
|
89
|
+
const { feature, locations } = entry.data;
|
|
90
|
+
const title = theme.fg('muted', `Contextor: ${feature}`);
|
|
91
|
+
return new Text(`${title}\n${locations || '(no indexed matches)'}`, 1, 0);
|
|
92
|
+
},
|
|
93
|
+
);
|
|
94
|
+
|
|
95
|
+
pi.registerCommand('contextor:query', {
|
|
96
|
+
description: 'Look up an exact feature identifier in the Contextor index',
|
|
97
|
+
handler: async (args, ctx) => {
|
|
98
|
+
const feature = args.trim();
|
|
99
|
+
if (!feature) {
|
|
100
|
+
ctx.ui.notify('Usage: /contextor:query <feature>', 'warning');
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const result = await queryFeature(ctx.cwd, feature);
|
|
104
|
+
if ('error' in result) {
|
|
105
|
+
ctx.ui.notify(`Contextor could not query ${feature}: ${String(result.error)}`, 'error');
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
pi.appendEntry(QUERY_ENTRY_TYPE, { feature, locations: result.locations });
|
|
109
|
+
},
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
pi.registerCommand('contextor:index', {
|
|
113
|
+
description: 'Create or update the Contextor index for the current project',
|
|
114
|
+
handler: async (_args, ctx) => {
|
|
115
|
+
ctx.ui.setStatus('contextor', 'Contextor: indexing…');
|
|
116
|
+
try {
|
|
117
|
+
const summary = await runContextor(ctx.cwd, ['index'], INDEX_TIMEOUT_MS);
|
|
118
|
+
draftQueries.clear();
|
|
119
|
+
featureListCache = undefined;
|
|
120
|
+
ctx.ui.notify(summary ? `Contextor: ${summary}` : 'Contextor index updated', 'info');
|
|
121
|
+
} catch (error) {
|
|
122
|
+
ctx.ui.notify(`Contextor could not update the index: ${String(error)}`, 'error');
|
|
123
|
+
} finally {
|
|
124
|
+
ctx.ui.setStatus('contextor', undefined);
|
|
125
|
+
}
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
pi.on('session_start', (_event, ctx) => {
|
|
130
|
+
draftQueries.clear();
|
|
131
|
+
featureListCache = undefined;
|
|
132
|
+
if (ctx.mode !== 'tui') return;
|
|
133
|
+
|
|
134
|
+
async function listFeatures(): Promise<string[]> {
|
|
135
|
+
try {
|
|
136
|
+
const output = await runContextor(ctx.cwd, ['features', '--format', 'json']);
|
|
137
|
+
const features: unknown = JSON.parse(output);
|
|
138
|
+
if (!Array.isArray(features) || !features.every((feature) => typeof feature === 'string')) {
|
|
139
|
+
throw new Error('expected a JSON array of feature identifiers');
|
|
140
|
+
}
|
|
141
|
+
return features;
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error instanceof ContextorNotFoundError) {
|
|
144
|
+
ctx.ui.notify(error.message, 'error');
|
|
145
|
+
} else {
|
|
146
|
+
ctx.ui.notify(`Contextor could not list features: ${String(error)}`, 'warning');
|
|
147
|
+
}
|
|
148
|
+
return [];
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
ctx.ui.addAutocompleteProvider((current) => ({
|
|
153
|
+
triggerCharacters: ['#'],
|
|
154
|
+
async getSuggestions(lines, cursorLine, cursorCol, options) {
|
|
155
|
+
const beforeCursor = (lines[cursorLine] ?? '').slice(0, cursorCol);
|
|
156
|
+
const match = beforeCursor.match(COMPLETION_PREFIX);
|
|
157
|
+
if (!match) return current.getSuggestions(lines, cursorLine, cursorCol, options);
|
|
158
|
+
|
|
159
|
+
if (!featureListCache || Date.now() >= featureListCache.expiresAt) {
|
|
160
|
+
const cache = {
|
|
161
|
+
request: listFeatures().finally(() => {
|
|
162
|
+
cache.expiresAt = Date.now() + LIST_CACHE_MS;
|
|
163
|
+
}),
|
|
164
|
+
expiresAt: Infinity,
|
|
165
|
+
};
|
|
166
|
+
featureListCache = cache;
|
|
167
|
+
}
|
|
168
|
+
const features = await featureListCache.request;
|
|
169
|
+
if (options.signal.aborted) return null;
|
|
170
|
+
const candidates = match[2]
|
|
171
|
+
? fuzzyFilter(features, match[2], (feature) => feature)
|
|
172
|
+
: features;
|
|
173
|
+
const items = candidates.slice(0, MAX_SUGGESTIONS).map((feature) => ({
|
|
174
|
+
label: feature,
|
|
175
|
+
value: `#{${feature}}`,
|
|
176
|
+
}));
|
|
177
|
+
return items.length > 0 ? { prefix: match[1], items } : null;
|
|
178
|
+
},
|
|
179
|
+
applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
|
|
180
|
+
const feature = prefix.startsWith('#')
|
|
181
|
+
? item.value.match(/^#\{([^\s{}]+)\}$/u)?.[1]
|
|
182
|
+
: undefined;
|
|
183
|
+
if (feature === undefined) {
|
|
184
|
+
return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
|
|
185
|
+
}
|
|
186
|
+
if (!draftQueries.has(feature)) draftQueries.set(feature, queryFeature(ctx.cwd, feature));
|
|
187
|
+
|
|
188
|
+
const line = lines[cursorLine] ?? '';
|
|
189
|
+
const start = cursorCol - prefix.length;
|
|
190
|
+
const suffix = line.slice(cursorCol);
|
|
191
|
+
const insertion = suffix ? item.value : `${item.value} `;
|
|
192
|
+
const updated = [...lines];
|
|
193
|
+
updated[cursorLine] = `${line.slice(0, start)}${insertion}${suffix}`;
|
|
194
|
+
return { lines: updated, cursorLine, cursorCol: start + insertion.length };
|
|
195
|
+
},
|
|
196
|
+
shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
|
|
197
|
+
return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
|
|
198
|
+
},
|
|
199
|
+
}));
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
pi.on('before_agent_start', async (event, ctx) => {
|
|
203
|
+
if (event.messageType !== 'user') return;
|
|
204
|
+
const context = await collectContext(event.prompt, ctx);
|
|
205
|
+
if (context) {
|
|
206
|
+
return {
|
|
207
|
+
message: {
|
|
208
|
+
customType: MESSAGE_TYPE,
|
|
209
|
+
content: context.content,
|
|
210
|
+
details: context.features,
|
|
211
|
+
display: true,
|
|
212
|
+
},
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Steering and follow-up messages can enter an active run without before_agent_start.
|
|
218
|
+
pi.on('input', async (event, ctx) => {
|
|
219
|
+
if (!event.streamingBehavior) return;
|
|
220
|
+
const context = await collectContext(event.text, ctx);
|
|
221
|
+
if (context) return { action: 'transform', text: `${event.text}\n\n${context.content}` };
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
pi.registerMessageRenderer(MESSAGE_TYPE, (message, { expanded, outputPad }, theme) => {
|
|
225
|
+
const features = message.details as string[] | undefined;
|
|
226
|
+
const summary = features?.map((feature) => `#{${feature}}`).join(', ');
|
|
227
|
+
const title = summary ? `Contextor: ${summary}` : 'Contextor: CLI unavailable';
|
|
228
|
+
if (typeof message.content !== 'string')
|
|
229
|
+
return new Text(theme.fg('muted', title), outputPad, 0);
|
|
230
|
+
|
|
231
|
+
// Keep clicks across renderer rebuilds, but let Ctrl+O reset the row to Pi's global state.
|
|
232
|
+
const clicked = clickedExpansion.get(message);
|
|
233
|
+
if (clicked && clicked.global !== expanded) clickedExpansion.delete(message);
|
|
234
|
+
let open = clicked?.global === expanded ? clicked.open : expanded;
|
|
235
|
+
const row = new Container();
|
|
236
|
+
const heading = new Text('', outputPad, 0);
|
|
237
|
+
const details = new Text(message.content, outputPad, 0);
|
|
238
|
+
|
|
239
|
+
function updateRow() {
|
|
240
|
+
heading.setText(theme.fg('muted', `${open ? '▾' : '▸'} ${title}`));
|
|
241
|
+
if (open) row.addChild(details);
|
|
242
|
+
else row.removeChild(details);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
row.addChild(
|
|
246
|
+
new MouseRegion(heading, (event) => {
|
|
247
|
+
if (event.type !== 'click' || event.button !== 'left') return;
|
|
248
|
+
open = !open;
|
|
249
|
+
clickedExpansion.set(message, { global: expanded, open });
|
|
250
|
+
updateRow();
|
|
251
|
+
return { handled: true };
|
|
252
|
+
}),
|
|
253
|
+
);
|
|
254
|
+
updateRow();
|
|
255
|
+
return row;
|
|
256
|
+
});
|
|
257
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@michalkvasnicak/pi-contextor",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Attach indexed feature locations to Pi prompts.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package"
|
|
7
|
+
],
|
|
8
|
+
"license": "MIT",
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/michalkvasnicak/contextor.git",
|
|
12
|
+
"directory": "pi-contextor"
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"extension.ts",
|
|
16
|
+
"skills/"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"publishConfig": {
|
|
20
|
+
"access": "public"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"check": "tsc --noEmit",
|
|
24
|
+
"lint": "oxlint",
|
|
25
|
+
"format": "oxfmt .",
|
|
26
|
+
"format:check": "oxfmt --check .",
|
|
27
|
+
"prepare": "cd .. && husky"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@earendil-works/pi-coding-agent": "1.6.0",
|
|
31
|
+
"@earendil-works/pi-tui": "1.6.0",
|
|
32
|
+
"husky": "^9.1.7",
|
|
33
|
+
"lint-staged": "^17.6.0",
|
|
34
|
+
"oxfmt": "^0.72.0",
|
|
35
|
+
"oxlint": "^1.87.0",
|
|
36
|
+
"typescript": "5.9.3"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
40
|
+
"@earendil-works/pi-tui": "*"
|
|
41
|
+
},
|
|
42
|
+
"lint-staged": {
|
|
43
|
+
"*.{js,jsx,ts,tsx,mjs,cjs,mts,cts,json,jsonc}": "oxfmt --write"
|
|
44
|
+
},
|
|
45
|
+
"packageManager": "pnpm@10.33.2",
|
|
46
|
+
"pi": {
|
|
47
|
+
"extensions": [
|
|
48
|
+
"./extension.ts"
|
|
49
|
+
],
|
|
50
|
+
"skills": [
|
|
51
|
+
"./skills/contextor"
|
|
52
|
+
]
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: contextor
|
|
3
|
+
description: Use when a prompt includes a Contextor feature reference or when adding, updating, or looking up feature annotations in project code or documentation.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Contextor
|
|
7
|
+
|
|
8
|
+
Contextor links a project's feature identifiers to the code and documentation that explain or implement them. In Pi, a reference like `#{billing}` attaches indexed paths, symbols, and line ranges to the prompt, not the source itself. Use those locations as starting points and read the relevant files before editing.
|
|
9
|
+
|
|
10
|
+
## Use only confirmed identifiers
|
|
11
|
+
|
|
12
|
+
**Never invent, rename, or guess a feature identifier.** Run `contextor features` from the target project to list indexed identifiers, then use `contextor query <identifier>` and inspect existing annotations to confirm what a candidate means. Reuse the exact spelling and case. The index can be stale, missing, or incomplete; check project guidance and existing annotations before concluding there is no match.
|
|
13
|
+
|
|
14
|
+
If no existing identifier clearly applies, multiple identifiers are plausible, or a new one is needed, ask the user which exact identifier to use before adding or changing tags. Leave the annotation unchanged or omit it while waiting; do not add a placeholder. `billing` and `refunds` below are syntax examples, not defaults.
|
|
15
|
+
|
|
16
|
+
## Annotate the smallest useful location
|
|
17
|
+
|
|
18
|
+
Tag the declarations, blocks, and documentation that a future agent should read to understand or change the feature. Reuse the same confirmed identifier across code and docs. Prefer a focused tag over a whole-file tag unless the entire file is about the feature.
|
|
19
|
+
|
|
20
|
+
- **Code:** Use the language's native comment syntax and follow existing project conventions. Put `@feature billing` in a doc comment immediately above a named declaration, or `@file-feature billing` in a leading comment if the whole file belongs to the feature. For a block, use comments containing `@feature-start billing` and `@feature-end billing` around the relevant lines.
|
|
21
|
+
- **Markdown:** Put `<!-- @feature billing -->` immediately before a heading to tag its section. For a whole file, use `feature: billing` in YAML front matter, or `feature: [billing, refunds]` for multiple features. Block markers go in HTML comments.
|
|
22
|
+
- **Multiple features:** Use one `@feature` per line in a declaration or section comment. For a block, use a bare `@feature-start` followed by one `@feature` per line in the opening comment, then a bare `@feature-end` in the closing comment.
|
|
23
|
+
|
|
24
|
+
These conventions apply even when Contextor has no parser for the language. A valid source comment can help readers without being indexed. When code isn't indexed, tag a relevant Markdown section and link to the source files and name the key symbols there so the feature is still discoverable.
|
|
25
|
+
|
|
26
|
+
After changing annotations, run `contextor index` from the project root (or `/contextor:index` in Pi), then query the affected identifiers to verify which locations were indexed.
|
package/README.md
DELETED