pi-doc-injector 0.5.3 → 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 -212
- package/audit.ts +186 -0
- package/cache.ts +23 -5
- package/commands.ts +168 -105
- package/config.ts +134 -61
- 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 +253 -157
- package/injector.ts +90 -5
- package/keyword-gen.ts +157 -36
- package/keyword-llm.ts +24 -16
- package/matcher.ts +86 -25
- package/notifier.ts +37 -37
- package/package.json +13 -7
- package/picomatch.d.ts +4 -1
- package/registry.ts +95 -55
- package/types.ts +26 -2
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 {
|
|
67
|
-
|
|
11
|
+
import type {
|
|
12
|
+
ExtensionAPI,
|
|
13
|
+
ExtensionContext,
|
|
14
|
+
} from "@earendil-works/pi-coding-agent";
|
|
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,9 +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
|
|
91
|
-
let
|
|
92
|
-
let
|
|
49
|
+
let continuedForDocs = false;
|
|
50
|
+
let continuationLimitNotified = false;
|
|
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
|
+
>();
|
|
57
|
+
// filePath → distinct keywords seen so far in the CURRENT streaming message.
|
|
58
|
+
// The streaming matcher scans only a rolling tail window each chunk, so a
|
|
59
|
+
// keyword can scroll out of the window before another appears. Accumulating
|
|
60
|
+
// the union here lets matchThreshold be met across chunks; reset at message_end.
|
|
61
|
+
let streamHits = new Map<string, Set<string>>();
|
|
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
|
+
};
|
|
93
84
|
|
|
94
85
|
// P5.4b — Guard flags for LLM keyword generation
|
|
95
86
|
let keywordGenInFlight = false;
|
|
@@ -105,7 +96,10 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
105
96
|
};
|
|
106
97
|
const getConfig = () => config;
|
|
107
98
|
|
|
108
|
-
const safeSaveCache = async (
|
|
99
|
+
const safeSaveCache = async (
|
|
100
|
+
cwd: string,
|
|
101
|
+
dirtyEntries: Record<string, CacheEntry>,
|
|
102
|
+
) => {
|
|
109
103
|
// MAJOR-2 fix: before saveCache, re-read cache from disk to merge
|
|
110
104
|
// LLM-written entries that may have landed during the scan.
|
|
111
105
|
const freshCache = await loadCache(cwd, notifier);
|
|
@@ -127,23 +121,26 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
127
121
|
const initRegistry = async (cwd: string) => {
|
|
128
122
|
config = await loadConfig(cwd, notifier);
|
|
129
123
|
const docsPath = resolve(cwd, config.docsPath);
|
|
130
|
-
cache =
|
|
124
|
+
cache =
|
|
125
|
+
config.mode === "keywords"
|
|
126
|
+
? await loadCache(cwd, notifier)
|
|
127
|
+
: { version: 1, files: {} };
|
|
131
128
|
registry = await DocRegistry.create(docsPath, config, cache, notifier);
|
|
132
129
|
|
|
133
130
|
const dirty = registry.getDirtyCache();
|
|
134
131
|
if (Object.keys(dirty).length > 0) {
|
|
135
132
|
await safeSaveCache(cwd, dirty);
|
|
136
133
|
}
|
|
137
|
-
|
|
138
|
-
const count = registry.getEntries().length;
|
|
139
134
|
};
|
|
140
135
|
|
|
141
|
-
const buildMatcher = (
|
|
136
|
+
const buildMatcher = (
|
|
137
|
+
options?: Partial<MatcherOptions>,
|
|
138
|
+
): KeywordMatcher | null => {
|
|
142
139
|
if (!registry) return null;
|
|
143
|
-
return new KeywordMatcher(
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
);
|
|
140
|
+
return new KeywordMatcher(registry.getNonInjectedEntries(), {
|
|
141
|
+
matchThreshold: config.mode === "simple" ? 1 : config.matchThreshold,
|
|
142
|
+
...options,
|
|
143
|
+
});
|
|
147
144
|
};
|
|
148
145
|
|
|
149
146
|
// P5.4f — generateKeywordsLLM: sets keywordGenInFlight and sends a user message
|
|
@@ -174,42 +171,50 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
174
171
|
),
|
|
175
172
|
}),
|
|
176
173
|
execute: async (_id, params, _signal, _onUpdate, ctx) => {
|
|
177
|
-
const generated = params.keywords as Array<{
|
|
174
|
+
const generated = params.keywords as Array<{
|
|
175
|
+
path: string;
|
|
176
|
+
keywords: string[];
|
|
177
|
+
}>;
|
|
178
178
|
const { stat } = await import("node:fs/promises");
|
|
179
179
|
let saved = 0;
|
|
180
180
|
for (const item of generated) {
|
|
181
|
-
|
|
182
|
-
const
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
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;
|
|
186
188
|
cache.files[item.path] = {
|
|
187
|
-
// Use the sentinel — never the real mtime — so the next rebuild
|
|
188
|
-
// surfaces this entry as keywordSource: "llm" instead of "cache".
|
|
189
189
|
mtimeMs: LLM_CACHE_SENTINEL,
|
|
190
190
|
keywords: item.keywords.map((k) => k.toLowerCase()).slice(0, 20),
|
|
191
191
|
};
|
|
192
192
|
saved++;
|
|
193
193
|
}
|
|
194
|
-
await saveCache(ctx.cwd, cache);
|
|
194
|
+
if (saved > 0) await saveCache(ctx.cwd, cache);
|
|
195
195
|
llmBatchesCompleted++;
|
|
196
196
|
llmTotalFiles += saved;
|
|
197
197
|
return {
|
|
198
|
-
content: [
|
|
198
|
+
content: [
|
|
199
|
+
{ type: "text" as const, text: `Keywords saved for ${saved} files.` },
|
|
200
|
+
],
|
|
199
201
|
details: undefined as never,
|
|
200
202
|
};
|
|
201
203
|
},
|
|
202
204
|
});
|
|
203
205
|
|
|
204
206
|
// ---- Event: session_start ----
|
|
205
|
-
// Pi
|
|
206
|
-
//
|
|
207
|
-
|
|
208
|
-
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) => {
|
|
209
210
|
// P5.4d — Safety unbind: clear all LLM keyword gen state on session start
|
|
210
211
|
keywordGenInFlight = false;
|
|
211
212
|
llmBatchesCompleted = 0;
|
|
212
213
|
llmTotalFiles = 0;
|
|
214
|
+
clearPendingMatches();
|
|
215
|
+
streamHits.clear();
|
|
216
|
+
continuedForDocs = false;
|
|
217
|
+
continuationLimitNotified = false;
|
|
213
218
|
|
|
214
219
|
// Bind the notifier to the live context FIRST so any warnings emitted
|
|
215
220
|
// during initRegistry below go directly to the TUI instead of being
|
|
@@ -217,8 +222,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
217
222
|
// loadConfig call) are flushed here in arrival order.
|
|
218
223
|
notifier.setContext(ctx);
|
|
219
224
|
|
|
220
|
-
if (event.reason === "reload") return;
|
|
221
|
-
|
|
222
225
|
if (initRegistryPromise) {
|
|
223
226
|
await initRegistryPromise;
|
|
224
227
|
return;
|
|
@@ -236,10 +239,10 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
236
239
|
if (!registry) throw new Error("No registry loaded");
|
|
237
240
|
const effectiveCwd = cwd ?? process.cwd();
|
|
238
241
|
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
242
|
+
if (config.mode === "keywords") {
|
|
243
|
+
cache = await loadCache(effectiveCwd, notifier);
|
|
244
|
+
registry.updateCache(cache);
|
|
245
|
+
}
|
|
243
246
|
|
|
244
247
|
await registry.rebuild();
|
|
245
248
|
|
|
@@ -283,16 +286,13 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
283
286
|
const results = matcher.match(event.text);
|
|
284
287
|
for (const result of results) {
|
|
285
288
|
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
289
|
+
recordPendingReason(result.entry, "input", result.matchedKeywords);
|
|
286
290
|
}
|
|
287
291
|
});
|
|
288
|
-
|
|
289
|
-
//
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
// injected context — no waiting for the next turn.
|
|
293
|
-
pi.on("message_update", async (event, ctx) => {
|
|
294
|
-
// P5.4b — Guard: skip auto-abort logic during LLM keyword generation
|
|
295
|
-
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;
|
|
296
296
|
|
|
297
297
|
if (!enabled || !registry) return;
|
|
298
298
|
|
|
@@ -300,57 +300,60 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
300
300
|
if (msg.role !== "assistant") return;
|
|
301
301
|
|
|
302
302
|
const content = (msg as unknown as { content: unknown }).content;
|
|
303
|
-
textBuffer = extractText(content);
|
|
303
|
+
const textBuffer = extractText(content);
|
|
304
304
|
if (!textBuffer) return;
|
|
305
305
|
|
|
306
|
-
|
|
306
|
+
// Discovery matcher: threshold 1 finds any keyword present in the rolling
|
|
307
|
+
// tail window. The real matchThreshold is applied below against the
|
|
308
|
+
// keywords accumulated across all chunks of this message.
|
|
309
|
+
const matcher = buildMatcher({
|
|
310
|
+
matchThreshold: 1,
|
|
311
|
+
windowSize: config.streamWindowSize,
|
|
312
|
+
});
|
|
307
313
|
if (!matcher) return;
|
|
308
314
|
|
|
309
315
|
const results = matcher.match(textBuffer);
|
|
310
316
|
|
|
311
|
-
let hasNew = false;
|
|
312
317
|
for (const result of results) {
|
|
313
|
-
|
|
314
|
-
|
|
318
|
+
const filePath = result.entry.filePath;
|
|
319
|
+
const seen = streamHits.get(filePath) ?? new Set<string>();
|
|
320
|
+
for (const kw of result.matchedKeywords) seen.add(kw);
|
|
321
|
+
streamHits.set(filePath, seen);
|
|
322
|
+
|
|
323
|
+
if (seen.size >= config.matchThreshold) {
|
|
324
|
+
if (!pendingMatches.has(filePath)) {
|
|
325
|
+
pendingMatches.set(filePath, [...seen]);
|
|
326
|
+
}
|
|
327
|
+
recordPendingReason(result.entry, "assistant", seen);
|
|
315
328
|
}
|
|
316
|
-
pendingMatches.set(result.entry.filePath, result.matchedKeywords);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
if (hasNew && !ctx.isIdle() && !abortingForInjection) {
|
|
320
|
-
abortingForInjection = true;
|
|
321
|
-
ctx.abort();
|
|
322
329
|
}
|
|
323
330
|
});
|
|
324
331
|
|
|
325
|
-
//
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
pi.on("message_end", async (event, _ctx) => {
|
|
329
|
-
if (!enabled || !registry) return;
|
|
330
|
-
const msg = event.message;
|
|
331
|
-
if (msg.role !== "assistant") return;
|
|
332
|
-
textBuffer = "";
|
|
332
|
+
// Hits belong to one assistant message. Clear them after any message ends.
|
|
333
|
+
pi.on("message_end", async () => {
|
|
334
|
+
streamHits.clear();
|
|
333
335
|
});
|
|
334
336
|
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
// session and sent to the LLM as part of the conversation.
|
|
340
|
-
pi.on("before_agent_start", async (event, ctx) => {
|
|
341
|
-
// 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 => {
|
|
342
341
|
if (keywordGenInFlight) return;
|
|
343
342
|
|
|
344
|
-
if (!enabled || !registry
|
|
343
|
+
if (!enabled || !registry) return;
|
|
344
|
+
if (pendingMatches.size === 0) {
|
|
345
|
+
pendingReasons.clear();
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
345
348
|
|
|
346
349
|
const matchedEntries: DocEntry[] = [];
|
|
347
350
|
for (const [filePath] of pendingMatches) {
|
|
348
351
|
const entry = registry.getEntries().find((e) => e.filePath === filePath);
|
|
349
|
-
if (entry) matchedEntries.push(entry);
|
|
352
|
+
if (entry && !entry.injected) matchedEntries.push(entry);
|
|
350
353
|
}
|
|
351
354
|
|
|
352
355
|
if (matchedEntries.length === 0) {
|
|
353
|
-
|
|
356
|
+
clearPendingMatches();
|
|
354
357
|
return;
|
|
355
358
|
}
|
|
356
359
|
|
|
@@ -358,37 +361,138 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
358
361
|
// (default: 80%). This prevents doc injection from pushing the context
|
|
359
362
|
// past the model's limit.
|
|
360
363
|
const usage = ctx.getContextUsage();
|
|
361
|
-
if (
|
|
362
|
-
|
|
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();
|
|
363
400
|
return;
|
|
364
401
|
}
|
|
365
402
|
|
|
366
403
|
const content = buildInjectionContent(matchedEntries, pendingMatches);
|
|
404
|
+
const details: InjectionAuditDetails = {
|
|
405
|
+
version: 1,
|
|
406
|
+
mode: config.mode,
|
|
407
|
+
boundary,
|
|
408
|
+
documents,
|
|
409
|
+
};
|
|
367
410
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
//
|
|
371
|
-
//
|
|
411
|
+
notifyInjection(ctx.ui, matchedEntries, pendingMatches);
|
|
412
|
+
|
|
413
|
+
// Pi exposes no post-commit callback for returned messages/drafts. Mark
|
|
414
|
+
// only after preparation succeeds, immediately before proposing them.
|
|
372
415
|
registry.markInjected(matchedEntries.map((e) => e.filePath));
|
|
416
|
+
clearPendingMatches();
|
|
417
|
+
return { content, details };
|
|
418
|
+
};
|
|
373
419
|
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
// the
|
|
377
|
-
|
|
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
|
+
}
|
|
378
427
|
|
|
379
|
-
|
|
428
|
+
const prepared = prepareInjection(ctx, "before_agent_start");
|
|
429
|
+
if (!prepared) return;
|
|
380
430
|
|
|
381
431
|
return {
|
|
382
432
|
message: {
|
|
383
433
|
customType: "doc-injector",
|
|
384
|
-
content,
|
|
434
|
+
content: prepared.content,
|
|
385
435
|
display: true,
|
|
436
|
+
details: prepared.details,
|
|
386
437
|
},
|
|
387
438
|
};
|
|
388
439
|
});
|
|
389
440
|
|
|
390
|
-
|
|
391
|
-
|
|
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) => {
|
|
392
496
|
// P5.4c — Summary notification from agent_end (BLOCKER-3)
|
|
393
497
|
keywordGenInFlight = false;
|
|
394
498
|
if (llmBatchesCompleted > 0) {
|
|
@@ -399,14 +503,6 @@ export default async function docInjectorExtension(pi: ExtensionAPI) {
|
|
|
399
503
|
llmBatchesCompleted = 0;
|
|
400
504
|
llmTotalFiles = 0;
|
|
401
505
|
}
|
|
402
|
-
|
|
403
|
-
if (abortingForInjection) {
|
|
404
|
-
abortingForInjection = false;
|
|
405
|
-
// Defer sendUserMessage to next tick to avoid re-entrancy issues.
|
|
406
|
-
setTimeout(() => {
|
|
407
|
-
pi.sendUserMessage("continue");
|
|
408
|
-
}, 0);
|
|
409
|
-
}
|
|
410
506
|
});
|
|
411
507
|
|
|
412
508
|
// ---- Commands ----
|