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.
@@ -1,199 +1,7 @@
1
- # Doc-Injector & Async Subagents Bug Analysis
1
+ # Historical: async subagent conflict
2
2
 
3
- ## Overview
3
+ Earlier versions of this extension called `ctx.abort()` when assistant output matched a doc, then sent a synthetic `continue` message from `agent_end`. This could interrupt async subagent workflows. The old implementation is described in repository history.
4
4
 
5
- The doc-injector extension causes spinner hangs when used alongside async subagent workflows (e.g., `subagent_isolated`, `subagent_with_context` with `async: true`).
5
+ The extension no longer aborts the assistant response or sends `continue`. Matches in assistant text or thinking stay pending and are injected from `before_agent_start` on the next agent run. User input matches still inject before the immediate response.
6
6
 
7
- ## Root Cause
8
-
9
- ### The Flow
10
-
11
- 1. Parent spawns async subagents with `async: true, notifyOnComplete: "inject"`
12
- 2. Parent streams output (e.g., "I've launched 5 agents...")
13
- 3. Doc-injector's `message_update` fires, detects keyword match
14
- 4. Doc-injector calls `ctx.abort()` to abort current turn
15
- 5. `agent_end` fires → extension injects `"continue"` via `setTimeout()`
16
- 6. Parent receives `"continue"` → immediately calls `get_subagent_result x5`
17
- 7. Subagents still running → results not available → **spinner stuck**
18
-
19
- ### Why This Happens
20
-
21
- The current doc-injector design assumes it can abort the current turn and restart immediately with injected docs. This works for simple single-turn workflows but breaks async subagent workflows because:
22
-
23
- 1. **The injected `"continue"` disrupts the expected flow** - parent should wait for `notifyOnComplete: "inject"` messages, not immediately poll for results
24
- 2. **`get_subagent_result` blocks** - when called before subagents finish, it hangs the parent thread
25
- 3. **The abort signal is shared** - in some subagent implementations (e.g., the `subagent` tool in pi-subagentura), async subagents explicitly don't inherit the parent abort signal. But the injected `"continue"` still breaks the flow
26
-
27
- ### Key Code Path (doc-injector/index.ts)
28
-
29
- ```typescript
30
- // message_update handler - triggers abort on keyword match
31
- pi.on("message_update", async (event, ctx) => {
32
- if (hasNew && !ctx.isIdle() && !abortingForInjection) {
33
- abortingForInjection = true;
34
- ctx.abort(); // ← PROBLEM: aborts current turn
35
- }
36
- });
37
-
38
- // agent_end handler - injects "continue" after abort
39
- pi.on("agent_end", async (event, ctx) => {
40
- if (abortingForInjection) {
41
- abortingForInjection = false;
42
- setTimeout(() => {
43
- pi.sendUserMessage("continue"); // ← PROBLEM: disrupts async flow
44
- }, 0);
45
- }
46
- });
47
- ```
48
-
49
- ## Subagentura System Context
50
-
51
- ### How Async Subagents Work
52
-
53
- The subagentura system (`/Users/applesucks/dev/pi-agents/subagent.ts`) spawns async subagents that:
54
-
55
- 1. Run in the same process (not subprocess)
56
- 2. Have independent session/context
57
- 3. Signal via `notifyOnComplete: "inject"` - results injected as user messages when complete
58
- 4. Use `get_subagent_result` to poll/block for results
59
-
60
- ### Key Line (subagent.ts line 541, 744)
61
-
62
- ```typescript
63
- signal: undefined, // async: don't inherit parent signal (would abort subagent when tool returns)
64
- ```
65
-
66
- ### Option A: Remove ctx.abort() Entirely (Recommended)
67
-
68
- **Change:** Never call `ctx.abort()` in `message_update`. Just record matches and inject on next turn.
69
-
70
- **Pros:**
71
- - ✅ Simplest fix
72
- - ✅ Works with ANY async workflow automatically
73
- - ✅ No special-casing for subagents
74
-
75
- **Cons:**
76
- - ❌ Loses "immediate injection during streaming" optimization
77
- - ❌ Docs injected on next turn instead of immediately
78
-
79
- **Implementation:**
80
- ```typescript
81
- pi.on("message_update", async (event, ctx) => {
82
- if (keywordGenInFlight) return;
83
- if (!enabled || !registry) return;
84
- if (msg.role !== "assistant") return;
85
-
86
- const content = (msg as unknown as { content: unknown }).content;
87
- textBuffer = extractText(content);
88
- if (!textBuffer) return;
89
-
90
- const matcher = buildMatcher();
91
- if (!matcher) return;
92
-
93
- const results = matcher.match(textBuffer);
94
- for (const result of results) {
95
- if (!pendingMatches.has(result.entry.filePath)) {
96
- hasNew = true; // Just record - don't abort
97
- }
98
- pendingMatches.set(result.entry.filePath, result.matchedKeywords);
99
- }
100
-
101
- // REMOVE: ctx.abort() entirely
102
- // Just let the turn complete naturally
103
- });
104
- ```
105
-
106
- ### Option B: Detect Async Subagents Before Aborting
107
-
108
- **Change:** Check if assistant just spawned async subagents, skip abort if so.
109
-
110
- **Pros:**
111
- - ✅ Preserves immediate injection behavior
112
- - ✅ Subagents continue running
113
-
114
- **Cons:**
115
- - ❌ Fragile - depends on detecting specific tool call patterns
116
- - ❌ Doesn't scale to other async workflows
117
-
118
- ### Option C: Only Inject on User Input
119
-
120
- **Change:** Only trigger immediate injection on `input` event (user messages), not on assistant streaming.
121
-
122
- **Pros:**
123
- - ✅ Clean separation of concerns
124
- - ✅ User intent gets immediate response
125
-
126
- **Cons:**
127
- - ❌ Loses streaming injection optimization
128
- - ❌ Still may not handle all async edge cases
129
-
130
- ## Recommendation
131
-
132
- **Use Option A:** Remove `ctx.abort()` entirely.
133
-
134
- The streaming injection optimization is not worth the complexity and the risk of breaking async workflows. Most keyword matches from assistant streaming are not time-critical - they can wait for the next turn.
135
-
136
- ## Additional Notes
137
-
138
- ### The notifyOnComplete:"inject" Flow
139
-
140
- 1. Parent spawns `async: true, notifyOnComplete: "inject"`
141
- 2. Parent continues immediately (doesn't wait)
142
- 3. Each subagent runs independently
143
- 4. When subagent completes, result is injected as user message via `pi.sendUserMessage()`
144
- 5. Parent receives the injected result and continues naturally
145
-
146
- This flow is designed to work without any intervention from the parent. Breaking it with `ctx.abort()` + `"continue"` defeats the purpose.
147
-
148
- ### Session Context
149
-
150
- Each subagent runs in its **own session** with its own doc-injector instance. Doc injection in subagent sessions is fine - they inject their own docs into their own context. The problem is only in the **parent session**.
151
-
152
- ## References
153
-
154
- - doc-injector: `/Users/applesucks/dev/pi-docs/index.ts`
155
- - subagentura: `/Users/applesucks/dev/pi-agents/subagent.ts`
156
- - subagentura helpers: `/Users/applesucks/dev/pi-agents/helpers.ts`
157
-
158
- ## Web Research Summary
159
-
160
- ### Official Documentation
161
-
162
- From `pi.dev/docs/latest/extensions`, the key lifecycle events are:
163
-
164
- - `before_agent_start` - Fires after user submits prompt, **before** agent loop. Can inject a message and/or modify system prompt.
165
- - `agent_start` / `agent_end` - Fires once per user prompt
166
- - `message_update` - Fires during streaming output
167
- - `input` - Fires on user input
168
-
169
- **Important note from docs:** "For critical events (before_agent_start, context, tool_call), if all handlers fail, the system continues with default behavior."
170
-
171
- ### Key Extension API Points
172
-
173
- 1. **`ctx.abort()`** - "Request a graceful shutdown of pi. Interactive mode: Deferred until the agent becomes idle (after processing all queued steering and follow-up messages)."
174
- 2. **`ctx.signal`** - Available for extensions to forward cancellation into nested model calls, fetch(), and other abort-aware work.
175
- 3. **`before_agent_start`** - The recommended injection point for context, as it runs before the agent loop starts.
176
-
177
- ### Related GitHub Issues
178
-
179
- - [Issue #624](https://github.com/earendil-works/pi/issues/624): "before_agent_start event does not properly inject message" - indicates there have been historical issues with injection timing
180
- - [Issue #2660](https://github.com/earendil-works/pi/issues/2660): "Expose abort signal on ExtensionContext" - led to `ctx.signal` being added
181
-
182
- ### Subagent Extensions Found
183
-
184
- 1. **tintinweb/pi-subagents** (`pi.dev/packages/pi-subagents`)
185
- - Claude Code-style autonomous subagents
186
- - Spawns agents in isolated sessions
187
- - Run in foreground or background
188
- - Similar to subagentura
189
-
190
- 2. **nicobailon/pi-subagents** (GitHub)
191
- - Async subagent delegation with truncation, artifacts, session sharing
192
-
193
- ### Conclusion from Web Research
194
-
195
- No documented solutions exist for the specific conflict between streaming injection (via `ctx.abort()`) and async subagent workflows. The recommended approach based on official docs is:
196
-
197
- 1. Use `before_agent_start` for context injection (runs before agent loop)
198
- 2. Avoid `ctx.abort()` during streaming - it disrupts any workflow that expects continuous streaming
199
- 3. The `input` event is the cleanest injection point for user-driven context since it represents new user intent
7
+ If immediate mid-response injection is proposed again, test it against Pi's current agent lifecycle and async tools first. `agent_end` is not a final-idle signal; see [Pi's extension lifecycle](https://pi.dev/docs/latest/extensions#agent_start--agent_end--agent_before_settle--agent_settled).
package/docs/publish.md CHANGED
@@ -27,6 +27,7 @@ No `NPM_TOKEN` secret, no token rotation, nothing to leak.
27
27
  ## Versioning
28
28
 
29
29
  We follow [Semantic Versioning](https://semver.org/):
30
+
30
31
  - **MAJOR** — incompatible API changes
31
32
  - **MINOR** — backwards-compatible functionality additions
32
33
  - **PATCH** — backwards-compatible bug fixes
@@ -34,10 +35,10 @@ We follow [Semantic Versioning](https://semver.org/):
34
35
  ## Release Process
35
36
 
36
37
  ```bash
37
- # 1. Edit version in package.json (e.g., 0.1.1 → 0.1.2)
38
+ # 1. Set the same version in package.json and the root package entry in package-lock.json
38
39
 
39
40
  # 2. Commit, tag, and push
40
- git add package.json
41
+ git add package.json package-lock.json
41
42
  git commit -m "chore: bump version to X.Y.Z"
42
43
  git tag vX.Y.Z
43
44
  git push origin master
@@ -54,6 +55,7 @@ git push origin master --follow-tags
54
55
  ## CI/CD
55
56
 
56
57
  The `Publish` workflow triggers on `v*` tags and:
58
+
57
59
  - Runs `npm ci`
58
60
  - Verifies tag matches `package.json` version
59
61
  - Runs `npm test`
@@ -80,8 +82,8 @@ After that, configure the trusted publisher and all future releases go through C
80
82
 
81
83
  ## Troubleshooting
82
84
 
83
- | Issue | Solution |
84
- |-------|----------|
85
- | Workflow didn't run | Verify tag exists: `git ls-remote origin refs/tags/vX.Y.Z` |
86
- | 404 on publish | Verify trusted publisher config on npmjs.com matches exactly |
87
- | Version already published | Bump to a new version |
85
+ | Issue | Solution |
86
+ | ------------------------- | ------------------------------------------------------------ |
87
+ | Workflow didn't run | Verify tag exists: `git ls-remote origin refs/tags/vX.Y.Z` |
88
+ | 404 on publish | Verify trusted publisher config on npmjs.com matches exactly |
89
+ | Version already published | Bump to a new version |
package/docs/test-md.md CHANGED
@@ -1,6 +1,18 @@
1
1
  ---
2
2
  title: "Testing Workflow"
3
- keywords: [test, testing, unit test, integration test, tdd, jest, vitest, assert, mock, stub]
3
+ keywords:
4
+ [
5
+ test,
6
+ testing,
7
+ unit test,
8
+ integration test,
9
+ tdd,
10
+ jest,
11
+ vitest,
12
+ assert,
13
+ mock,
14
+ stub,
15
+ ]
4
16
  ---
5
17
 
6
18
  # Testing Workflow
@@ -39,16 +51,19 @@ npm run test:coverage
39
51
  ## Test Categories
40
52
 
41
53
  ### Unit Tests
54
+
42
55
  - Test individual functions in isolation
43
56
  - Mock external dependencies
44
57
  - Fast execution (< 100ms per test)
45
58
 
46
59
  ### Integration Tests
60
+
47
61
  - Test module interactions
48
62
  - May use real dependencies
49
63
  - Slower than unit tests
50
64
 
51
65
  ### End-to-End Tests
66
+
52
67
  - Test complete user workflows
53
68
  - Run against a staging environment
54
69
  - Slowest but most valuable
@@ -1,6 +1,19 @@
1
1
  ---
2
2
  title: "Development Workflow"
3
- keywords: [workflow, development, coding, git, branch, commit, pull request, review, ci, cd, pipeline]
3
+ keywords:
4
+ [
5
+ workflow,
6
+ development,
7
+ coding,
8
+ git,
9
+ branch,
10
+ commit,
11
+ pull request,
12
+ review,
13
+ ci,
14
+ cd,
15
+ pipeline,
16
+ ]
4
17
  ---
5
18
 
6
19
  # Development Workflow
@@ -28,6 +41,7 @@ This document describes the standard development workflow for this project.
28
41
  ## Commit Messages
29
42
 
30
43
  Follow Conventional Commits:
44
+
31
45
  ```
32
46
  type(scope): description
33
47
 
@@ -46,6 +60,7 @@ docs(readme): update installation steps
46
60
  ## CI/CD Pipeline
47
61
 
48
62
  The pipeline runs on every push:
63
+
49
64
  1. Lint check
50
65
  2. Type check
51
66
  3. Unit tests
package/globber.ts CHANGED
@@ -23,14 +23,10 @@ export function createGlobFilter(
23
23
  exclude: string[],
24
24
  ): GlobFilter {
25
25
  const includeMatcher =
26
- include.length > 0
27
- ? picomatch(include, { dot: true })
28
- : null;
26
+ include.length > 0 ? picomatch(include, { dot: true }) : null;
29
27
 
30
28
  const excludeMatcher =
31
- exclude.length > 0
32
- ? picomatch(exclude, { dot: true })
33
- : null;
29
+ exclude.length > 0 ? picomatch(exclude, { dot: true }) : null;
34
30
 
35
31
  return {
36
32
  match(relativePath: string): boolean {