pi-doc-injector 0.6.0 → 0.8.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/README.md +76 -201
- package/audit.ts +186 -0
- package/cache.ts +55 -7
- package/commands.ts +168 -105
- package/config.ts +134 -55
- package/docs/async-subagent-bug.md +4 -196
- package/docs/publish.md +9 -7
- package/docs/test-md.md +16 -1
- package/docs/typescript-hardening.md +38 -0
- package/docs/workflow-md.md +16 -1
- package/globber.ts +29 -12
- package/index.ts +262 -187
- package/injector.ts +93 -5
- package/keyword-gen.ts +161 -37
- package/keyword-llm.ts +24 -16
- package/matcher.ts +57 -19
- package/notifier.ts +36 -36
- package/package.json +16 -9
- package/registry.ts +92 -53
- package/types.ts +9 -1
- package/picomatch.d.ts +0 -11
package/index.ts
CHANGED
|
@@ -1,79 +1,38 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
2
|
+
* Pi extension that selects project docs from user input or assistant text/thinking.
|
|
3
|
+
* The default matcher uses docs/{name}.md; keyword matching is opt-in.
|
|
4
|
+
* Simple assistant matches inject at the completed turn boundary, with at most
|
|
5
|
+
* one doc-triggered continuation per user run. Keyword matches wait for the
|
|
6
|
+
* next run. Neither path aborts or sends a synthetic user message.
|
|
3
7
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
* ## Injection Model: CustomMessage (NOT system prompt)
|
|
8
|
-
*
|
|
9
|
-
* On match, the extension returns a `message` field from `before_agent_start`
|
|
10
|
-
* (a `CustomMessage` with `customType: "doc-injector"`). Pi appends this to the
|
|
11
|
-
* session and sends it to the LLM as part of the conversation — the system
|
|
12
|
-
* prompt is NEVER mutated.
|
|
13
|
-
*
|
|
14
|
-
* Why a message and not the system prompt:
|
|
15
|
-
* - The system prompt is the highest-value Anthropic prompt-cache slot. Each
|
|
16
|
-
* unique system prompt text breaks the cache (5-min TTL by default).
|
|
17
|
-
* Appending per-turn doc content there would invalidate the cache on every
|
|
18
|
-
* first injection.
|
|
19
|
-
* - A `message` only adds to the conversation prefix, leaving the system
|
|
20
|
-
* prompt cache warm across turns.
|
|
21
|
-
*
|
|
22
|
-
* ## Streaming Model
|
|
23
|
-
*
|
|
24
|
-
* This extension relies on Pi's streaming event contract:
|
|
25
|
-
* - `message_update`: Fires with the FULL accumulated assistant content on each
|
|
26
|
-
* streaming chunk. The extension replaces (not appends to) its text buffer
|
|
27
|
-
* on each update.
|
|
28
|
-
* - `message_end`: Fires once when the assistant's response is complete.
|
|
29
|
-
* The extension finalizes matches and notifies the user.
|
|
30
|
-
* - `before_agent_start`: Fires before the next agent turn. The extension
|
|
31
|
-
* returns a `message` carrying the matched docs and marks them as injected.
|
|
32
|
-
*
|
|
33
|
-
* ## Injection Lifecycle
|
|
34
|
-
*
|
|
35
|
-
* The `injected` flag is per-session: when `session_start` fires, the registry
|
|
36
|
-
* is recreated from scratch (via initRegistry), resetting all flags. Within a
|
|
37
|
-
* session, once a doc is injected, it won't be re-injected unless the user
|
|
38
|
-
* manually runs `/doc-inject reset`.
|
|
39
|
-
*
|
|
40
|
-
* ## Double-Injection Prevention
|
|
41
|
-
*
|
|
42
|
-
* Two independent guards make duplicate injection impossible in a session:
|
|
43
|
-
*
|
|
44
|
-
* 1. **Matcher-level guard**: `buildMatcher()` calls `getNonInjectedEntries()`,
|
|
45
|
-
* so already-injected docs are excluded from the candidate set. The
|
|
46
|
-
* `pendingMatches` map is only populated from the matcher's output, so
|
|
47
|
-
* once a doc is injected, the next `input` event cannot re-match it.
|
|
48
|
-
*
|
|
49
|
-
* 2. **Mark guard**: `markInjected()` is called inside `before_agent_start`
|
|
50
|
-
* AFTER the build step but BEFORE the return value is processed. This
|
|
51
|
-
* means the flag flips synchronously with the LLM call — even if the
|
|
52
|
-
* session is reloaded mid-turn, the next `buildMatcher()` won't see the
|
|
53
|
-
* doc as a candidate.
|
|
54
|
-
*
|
|
55
|
-
* The two guards are redundant by design: if matcher exclusion ever fails
|
|
56
|
-
* (e.g. a race), the mark step still prevents the doc from being sent twice.
|
|
57
|
-
*
|
|
58
|
-
* ## Race Condition Note
|
|
59
|
-
*
|
|
60
|
-
* If `resources_discover` (rebuild) fires while `before_agent_start` is running,
|
|
61
|
-
* `registry.entries` gets replaced. The `matchedEntries` array would hold stale
|
|
62
|
-
* references. The current code is safe because `pendingMatches` (a Map by filePath)
|
|
63
|
-
* is cleared after injection, and `markInjected()` operates on the registry's
|
|
64
|
-
* current entries, not the stale array.
|
|
8
|
+
* Injection uses CustomMessages from before_agent_start or turn_end drafts.
|
|
9
|
+
* The system prompt is not changed.
|
|
65
10
|
*/
|
|
66
|
-
import type {
|
|
11
|
+
import type {
|
|
12
|
+
ExtensionAPI,
|
|
13
|
+
ExtensionContext,
|
|
14
|
+
} from "@earendil-works/pi-coding-agent";
|
|
67
15
|
import { Type } from "typebox";
|
|
68
16
|
import { resolve } from "node:path";
|
|
69
|
-
import { loadCache,
|
|
17
|
+
import { loadCache, mergeAndSaveCache } from "./cache";
|
|
70
18
|
import { loadConfig } from "./config";
|
|
19
|
+
import {
|
|
20
|
+
type InjectionAuditDetails,
|
|
21
|
+
type InjectionMatchSource,
|
|
22
|
+
type InjectionTrigger,
|
|
23
|
+
} from "./audit";
|
|
71
24
|
import { buildInjectionContent, notifyInjection } from "./injector";
|
|
72
25
|
import { buildKeywordGenPrompt } from "./keyword-llm";
|
|
73
|
-
import { extractText, KeywordMatcher } from "./matcher";
|
|
26
|
+
import { extractText, extractTextBlocks, KeywordMatcher } from "./matcher";
|
|
74
27
|
import { ExtensionNotifier, type Notifier } from "./notifier";
|
|
75
28
|
import { DocRegistry } from "./registry";
|
|
76
|
-
import {
|
|
29
|
+
import {
|
|
30
|
+
LLM_CACHE_SENTINEL,
|
|
31
|
+
type DocEntry,
|
|
32
|
+
type KeywordCache,
|
|
33
|
+
type CacheEntry,
|
|
34
|
+
type MatcherOptions,
|
|
35
|
+
} from "./types";
|
|
77
36
|
import { registerCommands } from "./commands";
|
|
78
37
|
|
|
79
38
|
export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
@@ -87,66 +46,89 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
87
46
|
let registry: DocRegistry | null = null;
|
|
88
47
|
let initRegistryPromise: Promise<void> | null = null;
|
|
89
48
|
let enabled = true;
|
|
90
|
-
let
|
|
49
|
+
let continuedForDocs = false;
|
|
50
|
+
let continuationLimitNotified = false;
|
|
91
51
|
let pendingMatches = new Map<string, string[]>(); // filePath → matchedKeywords (docs that met the threshold)
|
|
52
|
+
// filePath → source → distinct matched terms that caused the pending match.
|
|
53
|
+
let pendingReasons = new Map<
|
|
54
|
+
string,
|
|
55
|
+
Map<InjectionMatchSource, Set<string>>
|
|
56
|
+
>();
|
|
92
57
|
// filePath → distinct keywords seen so far in the CURRENT streaming message.
|
|
93
58
|
// The streaming matcher scans only a rolling tail window each chunk, so a
|
|
94
59
|
// keyword can scroll out of the window before another appears. Accumulating
|
|
95
60
|
// the union here lets matchThreshold be met across chunks; reset at message_end.
|
|
96
61
|
let streamHits = new Map<string, Set<string>>();
|
|
97
|
-
|
|
62
|
+
const clearPendingMatches = () => {
|
|
63
|
+
pendingMatches.clear();
|
|
64
|
+
pendingReasons.clear();
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
const recordPendingReason = (
|
|
68
|
+
entry: DocEntry,
|
|
69
|
+
source: InjectionMatchSource,
|
|
70
|
+
matchedKeywords: Iterable<string>,
|
|
71
|
+
) => {
|
|
72
|
+
let reasons = pendingReasons.get(entry.filePath);
|
|
73
|
+
if (!reasons) {
|
|
74
|
+
reasons = new Map();
|
|
75
|
+
pendingReasons.set(entry.filePath, reasons);
|
|
76
|
+
}
|
|
77
|
+
let terms = reasons.get(source);
|
|
78
|
+
if (!terms) {
|
|
79
|
+
terms = new Set();
|
|
80
|
+
reasons.set(source, terms);
|
|
81
|
+
}
|
|
82
|
+
for (const keyword of matchedKeywords) terms.add(keyword);
|
|
83
|
+
};
|
|
98
84
|
|
|
99
85
|
// P5.4b — Guard flags for LLM keyword generation
|
|
100
86
|
let keywordGenInFlight = false;
|
|
101
87
|
let llmBatchesCompleted = 0;
|
|
102
88
|
let llmTotalFiles = 0;
|
|
103
89
|
let cache: KeywordCache = { version: 1, files: {} };
|
|
90
|
+
// Reuse compiled patterns across chunks; discard them when the registry changes.
|
|
91
|
+
let streamMatcher: KeywordMatcher | null = null;
|
|
104
92
|
|
|
105
93
|
// ---- Helpers ----
|
|
106
94
|
const getRegistry = () => registry;
|
|
95
|
+
const invalidateStreamMatcher = () => {
|
|
96
|
+
streamMatcher = null;
|
|
97
|
+
};
|
|
98
|
+
const resetInjectionState = () => {
|
|
99
|
+
registry?.markAllNotInjected();
|
|
100
|
+
invalidateStreamMatcher();
|
|
101
|
+
};
|
|
107
102
|
const getEnabled = () => enabled;
|
|
108
103
|
const setEnabled = (v: boolean) => {
|
|
109
104
|
enabled = v;
|
|
110
105
|
};
|
|
111
106
|
const getConfig = () => config;
|
|
112
107
|
|
|
113
|
-
const safeSaveCache = async (cwd: string, dirtyEntries: Record<string, CacheEntry>) => {
|
|
114
|
-
// MAJOR-2 fix: before saveCache, re-read cache from disk to merge
|
|
115
|
-
// LLM-written entries that may have landed during the scan.
|
|
116
|
-
const freshCache = await loadCache(cwd, notifier);
|
|
117
|
-
const mergedCache: KeywordCache = { version: 1, files: {} };
|
|
118
|
-
|
|
119
|
-
// Start with fresh (disk) entries — includes any LLM writes during scan
|
|
120
|
-
for (const [key, entry] of Object.entries(freshCache.files)) {
|
|
121
|
-
mergedCache.files[key] = entry;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
// Overlay dirty entries from this scan (scan results take precedence)
|
|
125
|
-
for (const [key, entry] of Object.entries(dirtyEntries)) {
|
|
126
|
-
mergedCache.files[key] = entry;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
await saveCache(cwd, mergedCache);
|
|
130
|
-
};
|
|
131
|
-
|
|
132
108
|
const initRegistry = async (cwd: string) => {
|
|
133
109
|
config = await loadConfig(cwd, notifier);
|
|
134
110
|
const docsPath = resolve(cwd, config.docsPath);
|
|
135
|
-
cache =
|
|
111
|
+
cache =
|
|
112
|
+
config.mode === "keywords"
|
|
113
|
+
? await loadCache(cwd, notifier)
|
|
114
|
+
: { version: 1, files: {} };
|
|
136
115
|
registry = await DocRegistry.create(docsPath, config, cache, notifier);
|
|
116
|
+
invalidateStreamMatcher();
|
|
137
117
|
|
|
138
118
|
const dirty = registry.getDirtyCache();
|
|
139
119
|
if (Object.keys(dirty).length > 0) {
|
|
140
|
-
await
|
|
120
|
+
await mergeAndSaveCache(cwd, dirty, notifier);
|
|
141
121
|
}
|
|
142
122
|
};
|
|
143
123
|
|
|
144
|
-
const buildMatcher = (
|
|
124
|
+
const buildMatcher = (
|
|
125
|
+
options?: Partial<MatcherOptions>,
|
|
126
|
+
): KeywordMatcher | null => {
|
|
145
127
|
if (!registry) return null;
|
|
146
|
-
return new KeywordMatcher(
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
);
|
|
128
|
+
return new KeywordMatcher(registry.getNonInjectedEntries(), {
|
|
129
|
+
matchThreshold: config.mode === "simple" ? 1 : config.matchThreshold,
|
|
130
|
+
...options,
|
|
131
|
+
});
|
|
150
132
|
};
|
|
151
133
|
|
|
152
134
|
// P5.4f — generateKeywordsLLM: sets keywordGenInFlight and sends a user message
|
|
@@ -161,8 +143,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
161
143
|
};
|
|
162
144
|
|
|
163
145
|
// P5.4a — Inline tool registration (BLOCKER-2 fix).
|
|
164
|
-
// Registered inside the factory for closure access to cache, cwd, saveCache,
|
|
165
|
-
// and llmBatchesCompleted. Uses real mtime from stat().
|
|
166
146
|
pi.registerTool({
|
|
167
147
|
name: "_doc_injector_keywords",
|
|
168
148
|
label: "Doc Injector Keywords",
|
|
@@ -177,42 +157,55 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
177
157
|
),
|
|
178
158
|
}),
|
|
179
159
|
execute: async (_id, params, _signal, _onUpdate, ctx) => {
|
|
180
|
-
const generated = params.keywords as Array<{
|
|
160
|
+
const generated = params.keywords as Array<{
|
|
161
|
+
path: string;
|
|
162
|
+
keywords: string[];
|
|
163
|
+
}>;
|
|
181
164
|
const { stat } = await import("node:fs/promises");
|
|
182
165
|
let saved = 0;
|
|
166
|
+
const dirtyEntries: Record<string, CacheEntry> = {};
|
|
183
167
|
for (const item of generated) {
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
168
|
+
// Only documents in the registry may receive generated keywords.
|
|
169
|
+
const entry = registry
|
|
170
|
+
?.getEntries()
|
|
171
|
+
.find((doc) => doc.relativePath === item.path);
|
|
172
|
+
if (config.mode !== "keywords" || !entry) continue;
|
|
173
|
+
const fileStat = await stat(entry.filePath).catch(() => null);
|
|
174
|
+
if (!fileStat?.isFile()) continue;
|
|
175
|
+
dirtyEntries[item.path] = {
|
|
192
176
|
mtimeMs: LLM_CACHE_SENTINEL,
|
|
193
177
|
keywords: item.keywords.map((k) => k.toLowerCase()).slice(0, 20),
|
|
194
178
|
};
|
|
195
179
|
saved++;
|
|
196
180
|
}
|
|
197
|
-
|
|
181
|
+
if (saved > 0) {
|
|
182
|
+
await mergeAndSaveCache(ctx.cwd, dirtyEntries, notifier);
|
|
183
|
+
invalidateStreamMatcher();
|
|
184
|
+
}
|
|
198
185
|
llmBatchesCompleted++;
|
|
199
186
|
llmTotalFiles += saved;
|
|
200
187
|
return {
|
|
201
|
-
content: [
|
|
188
|
+
content: [
|
|
189
|
+
{ type: "text" as const, text: `Keywords saved for ${saved} files.` },
|
|
190
|
+
],
|
|
202
191
|
details: undefined as never,
|
|
203
192
|
};
|
|
204
193
|
},
|
|
205
194
|
});
|
|
206
195
|
|
|
207
196
|
// ---- Event: session_start ----
|
|
208
|
-
// Pi
|
|
209
|
-
//
|
|
210
|
-
|
|
211
|
-
pi.on("session_start", async (event, ctx) => {
|
|
197
|
+
// Pi creates a fresh extension runtime on reload and session replacement.
|
|
198
|
+
// Initialize on every session_start; deduplicate only concurrent calls.
|
|
199
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
212
200
|
// P5.4d — Safety unbind: clear all LLM keyword gen state on session start
|
|
213
201
|
keywordGenInFlight = false;
|
|
214
202
|
llmBatchesCompleted = 0;
|
|
215
203
|
llmTotalFiles = 0;
|
|
204
|
+
clearPendingMatches();
|
|
205
|
+
streamHits.clear();
|
|
206
|
+
continuedForDocs = false;
|
|
207
|
+
continuationLimitNotified = false;
|
|
208
|
+
invalidateStreamMatcher();
|
|
216
209
|
|
|
217
210
|
// Bind the notifier to the live context FIRST so any warnings emitted
|
|
218
211
|
// during initRegistry below go directly to the TUI instead of being
|
|
@@ -220,8 +213,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
220
213
|
// loadConfig call) are flushed here in arrival order.
|
|
221
214
|
notifier.setContext(ctx);
|
|
222
215
|
|
|
223
|
-
if (event.reason === "reload") return;
|
|
224
|
-
|
|
225
216
|
if (initRegistryPromise) {
|
|
226
217
|
await initRegistryPromise;
|
|
227
218
|
return;
|
|
@@ -239,16 +230,17 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
239
230
|
if (!registry) throw new Error("No registry loaded");
|
|
240
231
|
const effectiveCwd = cwd ?? process.cwd();
|
|
241
232
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
233
|
+
if (config.mode === "keywords") {
|
|
234
|
+
cache = await loadCache(effectiveCwd, notifier);
|
|
235
|
+
registry.updateCache(cache);
|
|
236
|
+
}
|
|
246
237
|
|
|
247
238
|
await registry.rebuild();
|
|
239
|
+
invalidateStreamMatcher();
|
|
248
240
|
|
|
249
241
|
const dirty = registry.getDirtyCache();
|
|
250
242
|
if (Object.keys(dirty).length > 0) {
|
|
251
|
-
await
|
|
243
|
+
await mergeAndSaveCache(effectiveCwd, dirty, notifier);
|
|
252
244
|
}
|
|
253
245
|
|
|
254
246
|
const count = registry.getEntries().length;
|
|
@@ -286,16 +278,13 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
286
278
|
const results = matcher.match(event.text);
|
|
287
279
|
for (const result of results) {
|
|
288
280
|
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
281
|
+
recordPendingReason(result.entry, "input", result.matchedKeywords);
|
|
289
282
|
}
|
|
290
283
|
});
|
|
291
|
-
|
|
292
|
-
//
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
// injected context — no waiting for the next turn.
|
|
296
|
-
pi.on("message_update", async (event, ctx) => {
|
|
297
|
-
// P5.4b — Guard: skip auto-abort logic during LLM keyword generation
|
|
298
|
-
if (keywordGenInFlight) return;
|
|
284
|
+
// Keyword mode retains its streaming tail and distinct-keyword accumulation.
|
|
285
|
+
// Simple mode scans only finalized blocks at turn_end, never chunk prefixes.
|
|
286
|
+
pi.on("message_update", async (event, _ctx) => {
|
|
287
|
+
if (keywordGenInFlight || config.mode !== "keywords") return;
|
|
299
288
|
|
|
300
289
|
if (!enabled || !registry) return;
|
|
301
290
|
|
|
@@ -303,71 +292,62 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
303
292
|
if (msg.role !== "assistant") return;
|
|
304
293
|
|
|
305
294
|
const content = (msg as unknown as { content: unknown }).content;
|
|
306
|
-
textBuffer = extractText(content);
|
|
295
|
+
const textBuffer = extractText(content);
|
|
307
296
|
if (!textBuffer) return;
|
|
308
297
|
|
|
309
|
-
// Discovery
|
|
310
|
-
//
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
298
|
+
// Discovery uses threshold 1 per chunk; streamHits applies the configured
|
|
299
|
+
// threshold across the whole message. Reuse compiled patterns between chunks.
|
|
300
|
+
if (!streamMatcher) {
|
|
301
|
+
streamMatcher = buildMatcher({
|
|
302
|
+
matchThreshold: 1,
|
|
303
|
+
windowSize: config.streamWindowSize,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
if (!streamMatcher) return;
|
|
314
307
|
|
|
315
|
-
const results =
|
|
308
|
+
const results = streamMatcher.match(textBuffer);
|
|
316
309
|
|
|
317
|
-
let hasNew = false;
|
|
318
310
|
for (const result of results) {
|
|
319
311
|
const filePath = result.entry.filePath;
|
|
320
312
|
const seen = streamHits.get(filePath) ?? new Set<string>();
|
|
321
313
|
for (const kw of result.matchedKeywords) seen.add(kw);
|
|
322
314
|
streamHits.set(filePath, seen);
|
|
323
315
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
316
|
+
if (seen.size >= config.matchThreshold) {
|
|
317
|
+
if (!pendingMatches.has(filePath)) {
|
|
318
|
+
pendingMatches.set(filePath, [...seen]);
|
|
319
|
+
}
|
|
320
|
+
recordPendingReason(result.entry, "assistant", seen);
|
|
329
321
|
}
|
|
330
322
|
}
|
|
331
|
-
|
|
332
|
-
if (hasNew && !ctx.isIdle() && !abortingForInjection) {
|
|
333
|
-
abortingForInjection = true;
|
|
334
|
-
ctx.abort();
|
|
335
|
-
}
|
|
336
323
|
});
|
|
337
324
|
|
|
338
|
-
//
|
|
339
|
-
|
|
340
|
-
// and auto-abort-triggered injections. message_end now just resets state.
|
|
341
|
-
// State resets run BEFORE the role/registry guards so a non-assistant
|
|
342
|
-
// message_end (e.g. tool result, user message) can never leak a stale
|
|
343
|
-
// textBuffer or streamHits into the next assistant turn.
|
|
344
|
-
pi.on("message_end", async (event, _ctx) => {
|
|
345
|
-
textBuffer = "";
|
|
325
|
+
// Hits belong to one assistant message. Clear them after any message ends.
|
|
326
|
+
pi.on("message_end", async () => {
|
|
346
327
|
streamHits.clear();
|
|
347
|
-
|
|
348
|
-
const msg = event.message;
|
|
349
|
-
if (msg.role !== "assistant") return;
|
|
328
|
+
invalidateStreamMatcher();
|
|
350
329
|
});
|
|
351
330
|
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
// session and sent to the LLM as part of the conversation.
|
|
357
|
-
pi.on("before_agent_start", async (event, ctx) => {
|
|
358
|
-
// P5.4b — Guard: skip injection during LLM keyword generation
|
|
331
|
+
const prepareInjection = (
|
|
332
|
+
ctx: ExtensionContext,
|
|
333
|
+
boundary: InjectionAuditDetails["boundary"],
|
|
334
|
+
): { content: string; details: InjectionAuditDetails } | undefined => {
|
|
359
335
|
if (keywordGenInFlight) return;
|
|
360
336
|
|
|
361
|
-
if (!enabled || !registry
|
|
337
|
+
if (!enabled || !registry) return;
|
|
338
|
+
if (pendingMatches.size === 0) {
|
|
339
|
+
pendingReasons.clear();
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
362
342
|
|
|
363
343
|
const matchedEntries: DocEntry[] = [];
|
|
364
344
|
for (const [filePath] of pendingMatches) {
|
|
365
345
|
const entry = registry.getEntries().find((e) => e.filePath === filePath);
|
|
366
|
-
if (entry) matchedEntries.push(entry);
|
|
346
|
+
if (entry && !entry.injected) matchedEntries.push(entry);
|
|
367
347
|
}
|
|
368
348
|
|
|
369
349
|
if (matchedEntries.length === 0) {
|
|
370
|
-
|
|
350
|
+
clearPendingMatches();
|
|
371
351
|
return;
|
|
372
352
|
}
|
|
373
353
|
|
|
@@ -375,37 +355,139 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
375
355
|
// (default: 80%). This prevents doc injection from pushing the context
|
|
376
356
|
// past the model's limit.
|
|
377
357
|
const usage = ctx.getContextUsage();
|
|
378
|
-
if (
|
|
379
|
-
|
|
358
|
+
if (
|
|
359
|
+
usage &&
|
|
360
|
+
usage.tokens &&
|
|
361
|
+
usage.tokens > 0 &&
|
|
362
|
+
usage.percent &&
|
|
363
|
+
usage.percent > config.contextThreshold
|
|
364
|
+
) {
|
|
365
|
+
clearPendingMatches();
|
|
366
|
+
ctx.ui.notify(
|
|
367
|
+
`Doc injection skipped: context usage exceeds ${config.contextThreshold}%.`,
|
|
368
|
+
"warning",
|
|
369
|
+
);
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const documents = matchedEntries.map((entry) => {
|
|
374
|
+
const reasons = pendingReasons.get(entry.filePath);
|
|
375
|
+
const triggers: InjectionTrigger[] = [];
|
|
376
|
+
if (reasons) {
|
|
377
|
+
for (const [source, keywords] of reasons) {
|
|
378
|
+
if (keywords.size > 0) {
|
|
379
|
+
triggers.push({
|
|
380
|
+
source,
|
|
381
|
+
matchedKeywords: [...keywords],
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return {
|
|
387
|
+
relativePath: entry.relativePath,
|
|
388
|
+
keywordSource: entry.keywordSource,
|
|
389
|
+
triggers,
|
|
390
|
+
};
|
|
391
|
+
});
|
|
392
|
+
if (documents.some((document) => document.triggers.length === 0)) {
|
|
393
|
+
clearPendingMatches();
|
|
380
394
|
return;
|
|
381
395
|
}
|
|
382
396
|
|
|
383
397
|
const content = buildInjectionContent(matchedEntries, pendingMatches);
|
|
398
|
+
const details: InjectionAuditDetails = {
|
|
399
|
+
version: 1,
|
|
400
|
+
mode: config.mode,
|
|
401
|
+
boundary,
|
|
402
|
+
documents,
|
|
403
|
+
};
|
|
384
404
|
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
//
|
|
388
|
-
//
|
|
405
|
+
notifyInjection(ctx.ui, matchedEntries, pendingMatches);
|
|
406
|
+
|
|
407
|
+
// Pi exposes no post-commit callback for returned messages/drafts. Mark
|
|
408
|
+
// only after preparation succeeds, immediately before proposing them.
|
|
389
409
|
registry.markInjected(matchedEntries.map((e) => e.filePath));
|
|
410
|
+
invalidateStreamMatcher();
|
|
411
|
+
clearPendingMatches();
|
|
412
|
+
return { content, details };
|
|
413
|
+
};
|
|
390
414
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
// the
|
|
394
|
-
|
|
415
|
+
// Preserve user-input injection before the first provider request.
|
|
416
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
417
|
+
// Low-level agent starts/retries must not replenish the continuation cap.
|
|
418
|
+
if (event.messageType === "user") {
|
|
419
|
+
continuedForDocs = false;
|
|
420
|
+
continuationLimitNotified = false;
|
|
421
|
+
}
|
|
395
422
|
|
|
396
|
-
|
|
423
|
+
const prepared = prepareInjection(ctx, "before_agent_start");
|
|
424
|
+
if (!prepared) return;
|
|
397
425
|
|
|
398
426
|
return {
|
|
399
427
|
message: {
|
|
400
428
|
customType: "doc-injector",
|
|
401
|
-
content,
|
|
429
|
+
content: prepared.content,
|
|
402
430
|
display: true,
|
|
431
|
+
details: prepared.details,
|
|
403
432
|
},
|
|
404
433
|
};
|
|
405
434
|
});
|
|
406
435
|
|
|
407
|
-
|
|
408
|
-
|
|
436
|
+
pi.on("turn_end", async (event, ctx) => {
|
|
437
|
+
if (
|
|
438
|
+
config.mode !== "simple" ||
|
|
439
|
+
keywordGenInFlight ||
|
|
440
|
+
!enabled ||
|
|
441
|
+
!registry ||
|
|
442
|
+
event.outcome !== "completed" ||
|
|
443
|
+
event.message.role !== "assistant"
|
|
444
|
+
)
|
|
445
|
+
return;
|
|
446
|
+
|
|
447
|
+
// The assistant and tools are already persisted. Scan every completed
|
|
448
|
+
// thinking/text block in full, independently, without a sliding window.
|
|
449
|
+
const matcher = buildMatcher();
|
|
450
|
+
if (!matcher) return;
|
|
451
|
+
for (const block of extractTextBlocks(event.message.content)) {
|
|
452
|
+
for (const result of matcher.match(block)) {
|
|
453
|
+
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
454
|
+
recordPendingReason(result.entry, "assistant", result.matchedKeywords);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
if (pendingMatches.size === 0) return;
|
|
458
|
+
|
|
459
|
+
if (continuedForDocs) {
|
|
460
|
+
if (!continuationLimitNotified) {
|
|
461
|
+
ctx.ui.notify(
|
|
462
|
+
"Doc continuation limit reached; additional matching docs will wait for the next user run.",
|
|
463
|
+
"info",
|
|
464
|
+
);
|
|
465
|
+
continuationLimitNotified = true;
|
|
466
|
+
}
|
|
467
|
+
return;
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const prepared = prepareInjection(ctx, "turn_end");
|
|
471
|
+
if (!prepared) return;
|
|
472
|
+
continuedForDocs = true;
|
|
473
|
+
return {
|
|
474
|
+
entries: [
|
|
475
|
+
...event.entries,
|
|
476
|
+
{
|
|
477
|
+
type: "custom_message" as const,
|
|
478
|
+
customType: "doc-injector",
|
|
479
|
+
content: `${prepared.content}\nContinue the user's current task using these documents as reference.`,
|
|
480
|
+
display: true,
|
|
481
|
+
details: { ...prepared.details, turnIndex: event.turnIndex },
|
|
482
|
+
},
|
|
483
|
+
],
|
|
484
|
+
// Natural tool/steering continuation satisfies this same next request.
|
|
485
|
+
continue: true,
|
|
486
|
+
};
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
// ---- Event: agent_end (LLM keyword batch summary) ----
|
|
490
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
409
491
|
// P5.4c — Summary notification from agent_end (BLOCKER-3)
|
|
410
492
|
keywordGenInFlight = false;
|
|
411
493
|
if (llmBatchesCompleted > 0) {
|
|
@@ -416,19 +498,12 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
416
498
|
llmBatchesCompleted = 0;
|
|
417
499
|
llmTotalFiles = 0;
|
|
418
500
|
}
|
|
419
|
-
|
|
420
|
-
if (abortingForInjection) {
|
|
421
|
-
abortingForInjection = false;
|
|
422
|
-
// Defer sendUserMessage to next tick to avoid re-entrancy issues.
|
|
423
|
-
setTimeout(() => {
|
|
424
|
-
pi.sendUserMessage("continue");
|
|
425
|
-
}, 0);
|
|
426
|
-
}
|
|
427
501
|
});
|
|
428
502
|
|
|
429
503
|
// ---- Commands ----
|
|
430
504
|
registerCommands(pi, {
|
|
431
505
|
getRegistry,
|
|
506
|
+
resetInjectionState,
|
|
432
507
|
getEnabled,
|
|
433
508
|
setEnabled,
|
|
434
509
|
reloadRegistry,
|