pi-doc-injector 0.6.0 → 0.7.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 +50 -213
- package/audit.ts +186 -0
- package/cache.ts +23 -5
- 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/workflow-md.md +16 -1
- package/globber.ts +2 -6
- package/index.ts +237 -158
- package/injector.ts +90 -5
- package/keyword-gen.ts +157 -36
- package/keyword-llm.ts +24 -16
- package/matcher.ts +46 -19
- package/notifier.ts +36 -36
- package/package.json +10 -6
- package/picomatch.d.ts +4 -1
- package/registry.ts +92 -53
- package/types.ts +9 -1
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
17
|
import { loadCache, saveCache } 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,14 +46,41 @@ 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;
|
|
@@ -110,7 +96,10 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
110
96
|
};
|
|
111
97
|
const getConfig = () => config;
|
|
112
98
|
|
|
113
|
-
const safeSaveCache = async (
|
|
99
|
+
const safeSaveCache = async (
|
|
100
|
+
cwd: string,
|
|
101
|
+
dirtyEntries: Record<string, CacheEntry>,
|
|
102
|
+
) => {
|
|
114
103
|
// MAJOR-2 fix: before saveCache, re-read cache from disk to merge
|
|
115
104
|
// LLM-written entries that may have landed during the scan.
|
|
116
105
|
const freshCache = await loadCache(cwd, notifier);
|
|
@@ -132,7 +121,10 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
132
121
|
const initRegistry = async (cwd: string) => {
|
|
133
122
|
config = await loadConfig(cwd, notifier);
|
|
134
123
|
const docsPath = resolve(cwd, config.docsPath);
|
|
135
|
-
cache =
|
|
124
|
+
cache =
|
|
125
|
+
config.mode === "keywords"
|
|
126
|
+
? await loadCache(cwd, notifier)
|
|
127
|
+
: { version: 1, files: {} };
|
|
136
128
|
registry = await DocRegistry.create(docsPath, config, cache, notifier);
|
|
137
129
|
|
|
138
130
|
const dirty = registry.getDirtyCache();
|
|
@@ -141,12 +133,14 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
141
133
|
}
|
|
142
134
|
};
|
|
143
135
|
|
|
144
|
-
const buildMatcher = (
|
|
136
|
+
const buildMatcher = (
|
|
137
|
+
options?: Partial<MatcherOptions>,
|
|
138
|
+
): KeywordMatcher | null => {
|
|
145
139
|
if (!registry) return null;
|
|
146
|
-
return new KeywordMatcher(
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
);
|
|
140
|
+
return new KeywordMatcher(registry.getNonInjectedEntries(), {
|
|
141
|
+
matchThreshold: config.mode === "simple" ? 1 : config.matchThreshold,
|
|
142
|
+
...options,
|
|
143
|
+
});
|
|
150
144
|
};
|
|
151
145
|
|
|
152
146
|
// P5.4f — generateKeywordsLLM: sets keywordGenInFlight and sends a user message
|
|
@@ -177,42 +171,50 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
177
171
|
),
|
|
178
172
|
}),
|
|
179
173
|
execute: async (_id, params, _signal, _onUpdate, ctx) => {
|
|
180
|
-
const generated = params.keywords as Array<{
|
|
174
|
+
const generated = params.keywords as Array<{
|
|
175
|
+
path: string;
|
|
176
|
+
keywords: string[];
|
|
177
|
+
}>;
|
|
181
178
|
const { stat } = await import("node:fs/promises");
|
|
182
179
|
let saved = 0;
|
|
183
180
|
for (const item of generated) {
|
|
184
|
-
|
|
185
|
-
const
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
181
|
+
// Only documents in the registry may receive generated keywords.
|
|
182
|
+
const entry = registry
|
|
183
|
+
?.getEntries()
|
|
184
|
+
.find((doc) => doc.relativePath === item.path);
|
|
185
|
+
if (config.mode !== "keywords" || !entry) continue;
|
|
186
|
+
const fileStat = await stat(entry.filePath).catch(() => null);
|
|
187
|
+
if (!fileStat?.isFile()) continue;
|
|
189
188
|
cache.files[item.path] = {
|
|
190
|
-
// Use the sentinel — never the real mtime — so the next rebuild
|
|
191
|
-
// surfaces this entry as keywordSource: "llm" instead of "cache".
|
|
192
189
|
mtimeMs: LLM_CACHE_SENTINEL,
|
|
193
190
|
keywords: item.keywords.map((k) => k.toLowerCase()).slice(0, 20),
|
|
194
191
|
};
|
|
195
192
|
saved++;
|
|
196
193
|
}
|
|
197
|
-
await saveCache(ctx.cwd, cache);
|
|
194
|
+
if (saved > 0) await saveCache(ctx.cwd, cache);
|
|
198
195
|
llmBatchesCompleted++;
|
|
199
196
|
llmTotalFiles += saved;
|
|
200
197
|
return {
|
|
201
|
-
content: [
|
|
198
|
+
content: [
|
|
199
|
+
{ type: "text" as const, text: `Keywords saved for ${saved} files.` },
|
|
200
|
+
],
|
|
202
201
|
details: undefined as never,
|
|
203
202
|
};
|
|
204
203
|
},
|
|
205
204
|
});
|
|
206
205
|
|
|
207
206
|
// ---- Event: session_start ----
|
|
208
|
-
// Pi
|
|
209
|
-
//
|
|
210
|
-
|
|
211
|
-
pi.on("session_start", async (event, ctx) => {
|
|
207
|
+
// Pi creates a fresh extension runtime on reload and session replacement.
|
|
208
|
+
// Initialize on every session_start; deduplicate only concurrent calls.
|
|
209
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
212
210
|
// P5.4d — Safety unbind: clear all LLM keyword gen state on session start
|
|
213
211
|
keywordGenInFlight = false;
|
|
214
212
|
llmBatchesCompleted = 0;
|
|
215
213
|
llmTotalFiles = 0;
|
|
214
|
+
clearPendingMatches();
|
|
215
|
+
streamHits.clear();
|
|
216
|
+
continuedForDocs = false;
|
|
217
|
+
continuationLimitNotified = false;
|
|
216
218
|
|
|
217
219
|
// Bind the notifier to the live context FIRST so any warnings emitted
|
|
218
220
|
// during initRegistry below go directly to the TUI instead of being
|
|
@@ -220,8 +222,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
220
222
|
// loadConfig call) are flushed here in arrival order.
|
|
221
223
|
notifier.setContext(ctx);
|
|
222
224
|
|
|
223
|
-
if (event.reason === "reload") return;
|
|
224
|
-
|
|
225
225
|
if (initRegistryPromise) {
|
|
226
226
|
await initRegistryPromise;
|
|
227
227
|
return;
|
|
@@ -239,10 +239,10 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
239
239
|
if (!registry) throw new Error("No registry loaded");
|
|
240
240
|
const effectiveCwd = cwd ?? process.cwd();
|
|
241
241
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
242
|
+
if (config.mode === "keywords") {
|
|
243
|
+
cache = await loadCache(effectiveCwd, notifier);
|
|
244
|
+
registry.updateCache(cache);
|
|
245
|
+
}
|
|
246
246
|
|
|
247
247
|
await registry.rebuild();
|
|
248
248
|
|
|
@@ -286,16 +286,13 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
286
286
|
const results = matcher.match(event.text);
|
|
287
287
|
for (const result of results) {
|
|
288
288
|
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
289
|
+
recordPendingReason(result.entry, "input", result.matchedKeywords);
|
|
289
290
|
}
|
|
290
291
|
});
|
|
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;
|
|
292
|
+
// Keyword mode retains its streaming tail and distinct-keyword accumulation.
|
|
293
|
+
// Simple mode scans only finalized blocks at turn_end, never chunk prefixes.
|
|
294
|
+
pi.on("message_update", async (event, _ctx) => {
|
|
295
|
+
if (keywordGenInFlight || config.mode !== "keywords") return;
|
|
299
296
|
|
|
300
297
|
if (!enabled || !registry) return;
|
|
301
298
|
|
|
@@ -303,71 +300,60 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
303
300
|
if (msg.role !== "assistant") return;
|
|
304
301
|
|
|
305
302
|
const content = (msg as unknown as { content: unknown }).content;
|
|
306
|
-
textBuffer = extractText(content);
|
|
303
|
+
const textBuffer = extractText(content);
|
|
307
304
|
if (!textBuffer) return;
|
|
308
305
|
|
|
309
306
|
// Discovery matcher: threshold 1 finds any keyword present in the rolling
|
|
310
307
|
// tail window. The real matchThreshold is applied below against the
|
|
311
308
|
// keywords accumulated across all chunks of this message.
|
|
312
|
-
const matcher = buildMatcher({
|
|
309
|
+
const matcher = buildMatcher({
|
|
310
|
+
matchThreshold: 1,
|
|
311
|
+
windowSize: config.streamWindowSize,
|
|
312
|
+
});
|
|
313
313
|
if (!matcher) return;
|
|
314
314
|
|
|
315
315
|
const results = matcher.match(textBuffer);
|
|
316
316
|
|
|
317
|
-
let hasNew = false;
|
|
318
317
|
for (const result of results) {
|
|
319
318
|
const filePath = result.entry.filePath;
|
|
320
319
|
const seen = streamHits.get(filePath) ?? new Set<string>();
|
|
321
320
|
for (const kw of result.matchedKeywords) seen.add(kw);
|
|
322
321
|
streamHits.set(filePath, seen);
|
|
323
322
|
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
323
|
+
if (seen.size >= config.matchThreshold) {
|
|
324
|
+
if (!pendingMatches.has(filePath)) {
|
|
325
|
+
pendingMatches.set(filePath, [...seen]);
|
|
326
|
+
}
|
|
327
|
+
recordPendingReason(result.entry, "assistant", seen);
|
|
329
328
|
}
|
|
330
329
|
}
|
|
331
|
-
|
|
332
|
-
if (hasNew && !ctx.isIdle() && !abortingForInjection) {
|
|
333
|
-
abortingForInjection = true;
|
|
334
|
-
ctx.abort();
|
|
335
|
-
}
|
|
336
330
|
});
|
|
337
331
|
|
|
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 = "";
|
|
332
|
+
// Hits belong to one assistant message. Clear them after any message ends.
|
|
333
|
+
pi.on("message_end", async () => {
|
|
346
334
|
streamHits.clear();
|
|
347
|
-
if (!enabled || !registry) return;
|
|
348
|
-
const msg = event.message;
|
|
349
|
-
if (msg.role !== "assistant") return;
|
|
350
335
|
});
|
|
351
336
|
|
|
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
|
|
337
|
+
const prepareInjection = (
|
|
338
|
+
ctx: ExtensionContext,
|
|
339
|
+
boundary: InjectionAuditDetails["boundary"],
|
|
340
|
+
): { content: string; details: InjectionAuditDetails } | undefined => {
|
|
359
341
|
if (keywordGenInFlight) return;
|
|
360
342
|
|
|
361
|
-
if (!enabled || !registry
|
|
343
|
+
if (!enabled || !registry) return;
|
|
344
|
+
if (pendingMatches.size === 0) {
|
|
345
|
+
pendingReasons.clear();
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
362
348
|
|
|
363
349
|
const matchedEntries: DocEntry[] = [];
|
|
364
350
|
for (const [filePath] of pendingMatches) {
|
|
365
351
|
const entry = registry.getEntries().find((e) => e.filePath === filePath);
|
|
366
|
-
if (entry) matchedEntries.push(entry);
|
|
352
|
+
if (entry && !entry.injected) matchedEntries.push(entry);
|
|
367
353
|
}
|
|
368
354
|
|
|
369
355
|
if (matchedEntries.length === 0) {
|
|
370
|
-
|
|
356
|
+
clearPendingMatches();
|
|
371
357
|
return;
|
|
372
358
|
}
|
|
373
359
|
|
|
@@ -375,37 +361,138 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
375
361
|
// (default: 80%). This prevents doc injection from pushing the context
|
|
376
362
|
// past the model's limit.
|
|
377
363
|
const usage = ctx.getContextUsage();
|
|
378
|
-
if (
|
|
379
|
-
|
|
364
|
+
if (
|
|
365
|
+
usage &&
|
|
366
|
+
usage.tokens &&
|
|
367
|
+
usage.tokens > 0 &&
|
|
368
|
+
usage.percent &&
|
|
369
|
+
usage.percent > config.contextThreshold
|
|
370
|
+
) {
|
|
371
|
+
clearPendingMatches();
|
|
372
|
+
ctx.ui.notify(
|
|
373
|
+
`Doc injection skipped: context usage exceeds ${config.contextThreshold}%.`,
|
|
374
|
+
"warning",
|
|
375
|
+
);
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const documents = matchedEntries.map((entry) => {
|
|
380
|
+
const reasons = pendingReasons.get(entry.filePath);
|
|
381
|
+
const triggers: InjectionTrigger[] = [];
|
|
382
|
+
if (reasons) {
|
|
383
|
+
for (const [source, keywords] of reasons) {
|
|
384
|
+
if (keywords.size > 0) {
|
|
385
|
+
triggers.push({
|
|
386
|
+
source,
|
|
387
|
+
matchedKeywords: [...keywords],
|
|
388
|
+
});
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
return {
|
|
393
|
+
relativePath: entry.relativePath,
|
|
394
|
+
keywordSource: entry.keywordSource,
|
|
395
|
+
triggers,
|
|
396
|
+
};
|
|
397
|
+
});
|
|
398
|
+
if (documents.some((document) => document.triggers.length === 0)) {
|
|
399
|
+
clearPendingMatches();
|
|
380
400
|
return;
|
|
381
401
|
}
|
|
382
402
|
|
|
383
403
|
const content = buildInjectionContent(matchedEntries, pendingMatches);
|
|
404
|
+
const details: InjectionAuditDetails = {
|
|
405
|
+
version: 1,
|
|
406
|
+
mode: config.mode,
|
|
407
|
+
boundary,
|
|
408
|
+
documents,
|
|
409
|
+
};
|
|
410
|
+
|
|
411
|
+
notifyInjection(ctx.ui, matchedEntries, pendingMatches);
|
|
384
412
|
|
|
385
|
-
//
|
|
386
|
-
//
|
|
387
|
-
// matcher ever produced a duplicate match, markInjected prevents a
|
|
388
|
-
// second send.
|
|
413
|
+
// Pi exposes no post-commit callback for returned messages/drafts. Mark
|
|
414
|
+
// only after preparation succeeds, immediately before proposing them.
|
|
389
415
|
registry.markInjected(matchedEntries.map((e) => e.filePath));
|
|
416
|
+
clearPendingMatches();
|
|
417
|
+
return { content, details };
|
|
418
|
+
};
|
|
390
419
|
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
// the
|
|
394
|
-
|
|
420
|
+
// Preserve user-input injection before the first provider request.
|
|
421
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
422
|
+
// Low-level agent starts/retries must not replenish the continuation cap.
|
|
423
|
+
if (event.messageType === "user") {
|
|
424
|
+
continuedForDocs = false;
|
|
425
|
+
continuationLimitNotified = false;
|
|
426
|
+
}
|
|
395
427
|
|
|
396
|
-
|
|
428
|
+
const prepared = prepareInjection(ctx, "before_agent_start");
|
|
429
|
+
if (!prepared) return;
|
|
397
430
|
|
|
398
431
|
return {
|
|
399
432
|
message: {
|
|
400
433
|
customType: "doc-injector",
|
|
401
|
-
content,
|
|
434
|
+
content: prepared.content,
|
|
402
435
|
display: true,
|
|
436
|
+
details: prepared.details,
|
|
403
437
|
},
|
|
404
438
|
};
|
|
405
439
|
});
|
|
406
440
|
|
|
407
|
-
|
|
408
|
-
|
|
441
|
+
pi.on("turn_end", async (event, ctx) => {
|
|
442
|
+
if (
|
|
443
|
+
config.mode !== "simple" ||
|
|
444
|
+
keywordGenInFlight ||
|
|
445
|
+
!enabled ||
|
|
446
|
+
!registry ||
|
|
447
|
+
event.outcome !== "completed" ||
|
|
448
|
+
event.message.role !== "assistant"
|
|
449
|
+
)
|
|
450
|
+
return;
|
|
451
|
+
|
|
452
|
+
// The assistant and tools are already persisted. Scan every completed
|
|
453
|
+
// thinking/text block in full, independently, without a sliding window.
|
|
454
|
+
const matcher = buildMatcher();
|
|
455
|
+
if (!matcher) return;
|
|
456
|
+
for (const block of extractTextBlocks(event.message.content)) {
|
|
457
|
+
for (const result of matcher.match(block)) {
|
|
458
|
+
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
459
|
+
recordPendingReason(result.entry, "assistant", result.matchedKeywords);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (pendingMatches.size === 0) return;
|
|
463
|
+
|
|
464
|
+
if (continuedForDocs) {
|
|
465
|
+
if (!continuationLimitNotified) {
|
|
466
|
+
ctx.ui.notify(
|
|
467
|
+
"Doc continuation limit reached; additional matching docs will wait for the next user run.",
|
|
468
|
+
"info",
|
|
469
|
+
);
|
|
470
|
+
continuationLimitNotified = true;
|
|
471
|
+
}
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
const prepared = prepareInjection(ctx, "turn_end");
|
|
476
|
+
if (!prepared) return;
|
|
477
|
+
continuedForDocs = true;
|
|
478
|
+
return {
|
|
479
|
+
entries: [
|
|
480
|
+
...event.entries,
|
|
481
|
+
{
|
|
482
|
+
type: "custom_message" as const,
|
|
483
|
+
customType: "doc-injector",
|
|
484
|
+
content: `${prepared.content}\nContinue the user's current task using these documents as reference.`,
|
|
485
|
+
display: true,
|
|
486
|
+
details: { ...prepared.details, turnIndex: event.turnIndex },
|
|
487
|
+
},
|
|
488
|
+
],
|
|
489
|
+
// Natural tool/steering continuation satisfies this same next request.
|
|
490
|
+
continue: true,
|
|
491
|
+
};
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
// ---- Event: agent_end (LLM keyword batch summary) ----
|
|
495
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
409
496
|
// P5.4c — Summary notification from agent_end (BLOCKER-3)
|
|
410
497
|
keywordGenInFlight = false;
|
|
411
498
|
if (llmBatchesCompleted > 0) {
|
|
@@ -416,14 +503,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
416
503
|
llmBatchesCompleted = 0;
|
|
417
504
|
llmTotalFiles = 0;
|
|
418
505
|
}
|
|
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
506
|
});
|
|
428
507
|
|
|
429
508
|
// ---- Commands ----
|