@tduyng/pi-subagent 0.0.0-stage → 0.0.2
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 +178 -0
- package/README.md +80 -2
- package/package.json +51 -4
- package/src/bulk-read.ts +147 -0
- package/src/lib/child-runtime.ts +18 -0
- package/src/log-reducer.ts +242 -0
- package/src/redact.ts +17 -0
- package/src/subagent/agent.ts +112 -0
- package/src/subagent/drive.ts +187 -0
- package/src/subagent/durable.ts +271 -0
- package/src/subagent/format.ts +241 -0
- package/src/subagent/guards/cloak.ts +396 -0
- package/src/subagent/guards/git-interceptor.ts +73 -0
- package/src/subagent/helpers.ts +212 -0
- package/src/subagent/index.ts +853 -0
- package/src/subagent/recover.ts +268 -0
- package/src/subagent/session.ts +87 -0
- package/src/subagent/state.ts +63 -0
- package/src/subagent/structured.ts +202 -0
- package/src/subagent/types.ts +109 -0
- package/src/subagent/viewer.ts +184 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
Use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 tduyng
|
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @tduyng/pi-subagent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Delegates work to child pi sessions running in-process. The parent stays lean because the child reads the files, returns one message plus a file list and usage stats, and then its context is discarded. Each finished child also appends its usage to `<agentDir>/overhead.jsonl` under the parent's session, so `/cost` can show what the delegation spent alongside the conversation.
|
|
4
|
+
|
|
5
|
+
## How delegation works
|
|
6
|
+
|
|
7
|
+
The `subagent` tool sends one task, or up to `MAX_TASKS` tasks, to a child
|
|
8
|
+
session. At most `MAX_CONCURRENT` children run at once. Each child runs on the
|
|
9
|
+
current model unless a task, profile, or `subagent.json` override changes it.
|
|
10
|
+
The child sees the task prompt, does the work, and returns one message. The
|
|
11
|
+
parent never carries the child's exploration.
|
|
12
|
+
|
|
13
|
+
Use `scout` for read-only file and document search, code tracing, analysis, and
|
|
14
|
+
short sourced summaries. Omitting `agent` selects `scout`. It is the cheap
|
|
15
|
+
default for I/O-heavy work. `subagent.json` supplies its low-cost model.
|
|
16
|
+
|
|
17
|
+
Use `verifier` only
|
|
18
|
+
after an artifact exists and the task explicitly asks for verification or
|
|
19
|
+
review. Keep ordinary implementation, debugging, design, builds, tests, and lint
|
|
20
|
+
in the parent session.
|
|
21
|
+
|
|
22
|
+
### Resume ids
|
|
23
|
+
|
|
24
|
+
A child that reaches its turn budget is told to wrap up and gets a fresh budget in the same session, so a cap never turns work into a failure. If the child still stops early, its last text comes back as a `[partial answer]`. Salvage walks the whole transcript for that text, not just the last message, so a child stopped mid-tool-burst still returns what it wrote. Every failed task prints a `resume:` id. Pass `resume: "<id>"` (or `"all"`) to continue where it stopped instead of paying for the investigation again. An optional `task` alongside `resume` steers the continuation. Failed sessions are kept 30 minutes, completed ones 5.
|
|
25
|
+
|
|
26
|
+
A deadline is reported as a timeout, not a cancellation. Pi keeps any final text produced before the deadline, marks it partial, and retains the session for resume.
|
|
27
|
+
|
|
28
|
+
Every run also writes `run.json` under `<agent-dir>/subagents/<session-id>/<run-id>/` with the task prompt, model, tools, and the path to each child session. The file is rewritten after each task transition, so it survives the process. Reopening the same Pi session reads it back: children interrupted less than ten minutes ago are resumed from their saved sessions and their result arrives as a `subagent-durable` message, while older interruptions are listed with their resume ids. `resume` therefore works after a restart, not only inside the process that started the child.
|
|
29
|
+
|
|
30
|
+
### Worktree isolation
|
|
31
|
+
|
|
32
|
+
With `isolation: "worktree"`, each child runs in its own git worktree on a branch named `pi-task-<id>`, so concurrent children never edit the same checkout and a commit a child makes outlives the checkout. The task result names the branch.
|
|
33
|
+
|
|
34
|
+
### Structured output
|
|
35
|
+
|
|
36
|
+
Pass `schema` to ask the child to call a `structured_output` tool exactly once. The parsed payload comes back in the task result. If the child finishes without calling the tool, the extension re-prompts the same session up to three times, so the investigation is not paid for twice. If it still refuses, the text answer stands and the task completes marked partial. If a provider rejects the schema tool, the extension removes it and retries once in plain-text mode.
|
|
37
|
+
|
|
38
|
+
### Fork context
|
|
39
|
+
|
|
40
|
+
With `context: "fork"`, the parent's conversation history is replayed into the child as context entries.
|
|
41
|
+
|
|
42
|
+
## Agent profiles
|
|
43
|
+
|
|
44
|
+
The `/agents` command lists agent profiles, which are markdown files with YAML frontmatter in `<agent-dir>/agents` or `.pi/agents`. Project agents shadow user agents of the same name. Each profile specifies a tool list, model, thinking level, limits, and optional color for the widget. Profiles can also set `inheritProjectContext` and `inheritSkills` to control whether the child picks up the parent project's context files and skills, and `systemPromptMode: replace` to swap the default system prompt instead of appending to it. The `subagent` widget in the TUI shows up to 8 running and recently finished children, with a summary line of counts by status. Navigate with Down/Up, Enter opens a live transcript viewer, d/x dismisses.
|
|
45
|
+
|
|
46
|
+
## Bulk-read guard
|
|
47
|
+
|
|
48
|
+
The guard blocks reads of files above `BULK_READ_MIN_LINES` lines (default 350). It also blocks `cat`, `less`, and `more` commands that would dump large files. The second call for the same path passes through, so the file stays reachable. A read passes when it returns fewer lines than the threshold, whether that comes from a `limit`, an `offset`, a small file, or `head`/`tail` on their 10-line default, and so does a piped command.
|
|
49
|
+
|
|
50
|
+
## Log reducer
|
|
51
|
+
|
|
52
|
+
Build or test logs above 4,096 bytes, matched by diagnostic command patterns, get replaced with a short receipt of quoted lines. Every quote is verified byte-for-byte against the archived original. If validation fails, the full log reaches the model untouched. The reducer runs on `tool_result`, so the swap happens before the result enters history. The raw log is archived next to the session for full access.
|
|
53
|
+
|
|
54
|
+
## Design
|
|
55
|
+
|
|
56
|
+
- The default safe delegation is read-only I/O: `scout` searches, traces, analyses, and summarizes without editing or running commands.
|
|
57
|
+
- `verifier` is reserved for explicit verification of an existing artifact. It may write only its verification report, never implementation files.
|
|
58
|
+
- Ordinary implementation, debugging, design, builds, tests, and lint stay in the parent session.
|
|
59
|
+
- The tool rejects concurrent write-capable tasks. Read-only scouts may still run in parallel. A call whose task texts normalize to the same request is rejected, so one question does not get paid for twice.
|
|
60
|
+
- Children see one prompt and return one message. No sequential pipelines.
|
|
61
|
+
- Children cannot spawn their own subagents. No grandchildren.
|
|
62
|
+
- The `subagent` tool schema is present on every turn, and it lists only the fields a model sets: `task`, `agent`, `cwd`, `isolation`, `schema`, `context`, and `resume`. `label`, `thinking`, `model`, `timeoutMs`, and `maxTurns` are profile policy. They still work when a scripted caller passes them, and three of them already resolved to the profile before the split.
|
|
63
|
+
- The `subagent` tool schema is present on every turn. The `bulk-read` and `log-reducer` extensions add no tool schemas. They run as event handlers. The registry holds at most 50 tasks. The widget shows at most 8 rows. The `touched` file list per task is capped at 12 entries. Progress updates emit at most once every 250ms.
|
|
64
|
+
- Child deadlines default to 30 minutes. A shorter `timeoutMs` or profile `maxExecutionTimeMs` is raised to 30 minutes, while longer values pass through. A profile deadline beyond the 32-bit setTimeout ceiling (2,147,483,647 ms) clamps to the ceiling. Node would round a larger delay down to 1 ms and kill the child instantly, so the clamp degrades a bad value to a very long deadline.
|
|
65
|
+
- Children inherit the parent's model by default. Thinking does not inherit: it resolves from the task's `thinking`, then the profile, then `subagent.json`, then `medium`.
|
|
66
|
+
|
|
67
|
+
## Install
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
pi install npm:@tduyng/pi-subagent
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Local checkout: `pi install /path/to/dotfiles/pi/agent/extensions/pi-subagent`
|
|
74
|
+
|
|
75
|
+
## Configure
|
|
76
|
+
|
|
77
|
+
- `subagent.json` in the agent dir (`~/.pi/agent/`) sets the default child model and thinking level. A project's `.pi/subagent.json` overrides either field. Shape: `{ "model": "provider/model-id", "thinking": "medium" }`, both optional. `thinking` is one of `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`. Unset, it is `medium`. No file means children inherit the parent's model.
|
|
78
|
+
- `BULK_READ=0` disables the bulk-read guard. `BULK_READ_MIN_LINES` sets the line threshold (default 350).
|
|
79
|
+
- `PI_LOG_REDUCER=0` disables the log reducer.
|
|
80
|
+
- `PI_LOG_REDUCER_TIMEOUT_MS` sets the reducer deadline. The default is 15 seconds and the maximum is 60 seconds.
|
|
81
|
+
- Agent profiles are markdown files with YAML frontmatter in `~/.pi/agent/agents/` or `.pi/agents/` (project shadowing user on name collision).
|
package/package.json
CHANGED
|
@@ -1,6 +1,53 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tduyng/pi-subagent",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.2",
|
|
4
|
+
"description": "Delegation to in-process child sessions: a subagent tool with agent profiles and worktree isolation, a side chat, a guard that redirects bulk reads, and a verified log reducer.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi",
|
|
7
|
+
"pi-package",
|
|
8
|
+
"pi-extension",
|
|
9
|
+
"pi-coding-agent",
|
|
10
|
+
"subagent",
|
|
11
|
+
"delegation",
|
|
12
|
+
"parallel",
|
|
13
|
+
"tokens"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://gitlab.com/tduyng/pi-agent/-/tree/main/extensions/pi-subagent#readme",
|
|
16
|
+
"bugs": "https://gitlab.com/tduyng/pi-agent/-/issues",
|
|
17
|
+
"license": "Apache-2.0",
|
|
18
|
+
"author": "tduyng",
|
|
19
|
+
"repository": {
|
|
20
|
+
"type": "git",
|
|
21
|
+
"url": "git+https://gitlab.com/tduyng/pi-agent.git",
|
|
22
|
+
"directory": "extensions/pi-subagent"
|
|
23
|
+
},
|
|
24
|
+
"type": "module",
|
|
25
|
+
"files": [
|
|
26
|
+
"src",
|
|
27
|
+
"!src/**/*.test.ts",
|
|
28
|
+
"README.md",
|
|
29
|
+
"LICENSE"
|
|
30
|
+
],
|
|
31
|
+
"peerDependencies": {
|
|
32
|
+
"@earendil-works/pi-ai": "*",
|
|
33
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
34
|
+
"@earendil-works/pi-tui": "*"
|
|
35
|
+
},
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"pi": {
|
|
40
|
+
"extensions": [
|
|
41
|
+
"./src/subagent/index.ts",
|
|
42
|
+
"./src/bulk-read.ts",
|
|
43
|
+
"./src/log-reducer.ts"
|
|
44
|
+
]
|
|
45
|
+
},
|
|
46
|
+
"exports": {
|
|
47
|
+
".": "./src/subagent/index.ts",
|
|
48
|
+
"./agent": "./src/subagent/agent.ts"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"ata-validator": "^1.62.1"
|
|
52
|
+
}
|
|
53
|
+
}
|
package/src/bulk-read.ts
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { closeSync, openSync, readSync, statSync } from 'node:fs'
|
|
2
|
+
import { isAbsolute, resolve } from 'node:path'
|
|
3
|
+
import { isToolCallEventType, type ExtensionAPI, type ToolCallEvent } from '@earendil-works/pi-coding-agent'
|
|
4
|
+
|
|
5
|
+
const DEFAULT_MIN_LINES = 350
|
|
6
|
+
const HUGE_BYTES = 2_000_000
|
|
7
|
+
const CHUNK_BYTES = 64 * 1024
|
|
8
|
+
|
|
9
|
+
function minLines(): number {
|
|
10
|
+
const raw = Number(process.env['BULK_READ_MIN_LINES'])
|
|
11
|
+
return Number.isInteger(raw) && raw > 0 ? raw : DEFAULT_MIN_LINES
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Lines in a file, reading in chunks and stopping once `cap` is passed. A caller that only
|
|
16
|
+
* needs to know a file is over the threshold never reads the whole of a large file, and a
|
|
17
|
+
* caller that needs the exact count passes no cap.
|
|
18
|
+
*/
|
|
19
|
+
export function lineCount(absolutePath: string, cap = Number.MAX_SAFE_INTEGER): number | null {
|
|
20
|
+
try {
|
|
21
|
+
if (statSync(absolutePath).size > HUGE_BYTES) return Number.MAX_SAFE_INTEGER
|
|
22
|
+
const fd = openSync(absolutePath, 'r')
|
|
23
|
+
try {
|
|
24
|
+
const buffer = Buffer.allocUnsafe(CHUNK_BYTES)
|
|
25
|
+
let lines = 0
|
|
26
|
+
let last = 0
|
|
27
|
+
let position = 0
|
|
28
|
+
while (true) {
|
|
29
|
+
const bytes = readSync(fd, buffer, 0, CHUNK_BYTES, position)
|
|
30
|
+
if (bytes === 0) break
|
|
31
|
+
for (let index = 0; index < bytes; index += 1) {
|
|
32
|
+
if (buffer[index] === 10) lines += 1
|
|
33
|
+
}
|
|
34
|
+
last = buffer[bytes - 1] ?? 0
|
|
35
|
+
position += bytes
|
|
36
|
+
if (lines > cap) return lines
|
|
37
|
+
}
|
|
38
|
+
return last === 10 ? lines : lines + 1
|
|
39
|
+
} finally {
|
|
40
|
+
closeSync(fd)
|
|
41
|
+
}
|
|
42
|
+
} catch {
|
|
43
|
+
return null
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const DUMP_DEFAULT_LINES = {
|
|
48
|
+
cat: Number.POSITIVE_INFINITY,
|
|
49
|
+
less: Number.POSITIVE_INFINITY,
|
|
50
|
+
more: Number.POSITIVE_INFINITY,
|
|
51
|
+
head: 10,
|
|
52
|
+
tail: 10
|
|
53
|
+
} as const
|
|
54
|
+
|
|
55
|
+
function isDumpTool(name: string): name is keyof typeof DUMP_DEFAULT_LINES {
|
|
56
|
+
return name in DUMP_DEFAULT_LINES
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function dumpTarget(command: string, threshold: number): string | null {
|
|
60
|
+
if (/[|><;&]/.test(command)) return null
|
|
61
|
+
|
|
62
|
+
const parts = command.trim().split(/\s+/)
|
|
63
|
+
const tool = parts.shift()
|
|
64
|
+
if (tool === undefined || !isDumpTool(tool)) return null
|
|
65
|
+
|
|
66
|
+
let bound: number = DUMP_DEFAULT_LINES[tool]
|
|
67
|
+
const counted = tool === 'head' || tool === 'tail'
|
|
68
|
+
const files: string[] = []
|
|
69
|
+
for (let i = 0; i < parts.length; i += 1) {
|
|
70
|
+
const part = parts[i] ?? ''
|
|
71
|
+
if (counted && (part === '-n' || part === '-c')) {
|
|
72
|
+
i += 1
|
|
73
|
+
bound = Number(parts[i]) || bound
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
const short = /^-(\d+)$/.exec(part)
|
|
77
|
+
if (counted && short?.[1] !== undefined) {
|
|
78
|
+
bound = Number(short[1])
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
if (part.startsWith('-')) continue
|
|
82
|
+
files.push(part)
|
|
83
|
+
}
|
|
84
|
+
if (files.length !== 1 || bound < threshold) return null
|
|
85
|
+
return files[0] ?? null
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function redirect(path: string, lines: number, threshold: number): string {
|
|
89
|
+
return (
|
|
90
|
+
`bulk-read blocked this read: ${path} is at least ${lines} lines (threshold ${threshold}), ` +
|
|
91
|
+
`and its contents would stay in context and be re-billed every later turn.\n` +
|
|
92
|
+
`Pick one:\n` +
|
|
93
|
+
` - Outline it, cheapest and usually enough. Call outline on ${path} for its declarations ` +
|
|
94
|
+
`and line spans, then read the span you need with offset and limit. Use grep when you know a name.\n` +
|
|
95
|
+
` - Filter it in codemode when you need the whole file and only a slice of it. ` +
|
|
96
|
+
`Await tools.read in a script and text() just the lines you keep.\n` +
|
|
97
|
+
` - Delegate it when you need the whole file's meaning rather than a few lines. Call ` +
|
|
98
|
+
`subagent with a task naming this file and the exact question, e.g. "Read ${path} and ` +
|
|
99
|
+
`list the functions that touch the database, with line numbers." The child reads it on ` +
|
|
100
|
+
`a cheap model and you get back only the answer.\n` +
|
|
101
|
+
`Read the whole file only if you truly need all of it; repeating this exact call will go through.`
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export default function bulkReadExtension(pi: ExtensionAPI): void {
|
|
106
|
+
if (/^(0|false|no|off)$/i.test(process.env['BULK_READ'] ?? '')) return
|
|
107
|
+
|
|
108
|
+
const refused = new Set<string>()
|
|
109
|
+
|
|
110
|
+
pi.on('session_start', (event) => {
|
|
111
|
+
if (event.reason === 'new') refused.clear()
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
pi.on('tool_call', (event: ToolCallEvent, ctx) => {
|
|
115
|
+
// A nested call is codemode, where the script decides what reaches context.
|
|
116
|
+
if (event.parentToolCallId !== undefined) return undefined
|
|
117
|
+
|
|
118
|
+
const threshold = minLines()
|
|
119
|
+
let path: string
|
|
120
|
+
let skipLines = 0
|
|
121
|
+
let limit: number | undefined
|
|
122
|
+
if (isToolCallEventType('read', event)) {
|
|
123
|
+
limit = event.input.limit
|
|
124
|
+
if (limit !== undefined && limit < threshold) return undefined
|
|
125
|
+
skipLines = Math.max(0, (event.input.offset ?? 1) - 1)
|
|
126
|
+
path = event.input.path
|
|
127
|
+
} else if (isToolCallEventType('bash', event)) {
|
|
128
|
+
const target = dumpTarget(event.input.command, threshold)
|
|
129
|
+
if (target === null) return undefined
|
|
130
|
+
path = target
|
|
131
|
+
} else {
|
|
132
|
+
return undefined
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const absolute = isAbsolute(path) ? path : resolve(ctx.cwd, path)
|
|
136
|
+
if (refused.has(absolute)) return undefined
|
|
137
|
+
|
|
138
|
+
const total = lineCount(absolute, skipLines + threshold)
|
|
139
|
+
if (total === null) return undefined
|
|
140
|
+
const lines = Math.max(0, total - skipLines)
|
|
141
|
+
const returned = limit === undefined ? lines : Math.min(lines, limit)
|
|
142
|
+
if (returned < threshold) return undefined
|
|
143
|
+
|
|
144
|
+
refused.add(absolute)
|
|
145
|
+
return { block: true, reason: redirect(path, returned, threshold) }
|
|
146
|
+
})
|
|
147
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { type ExtensionContext } from '@earendil-works/pi-coding-agent'
|
|
2
|
+
import { ModelRuntime } from '@earendil-works/pi-coding-agent'
|
|
3
|
+
|
|
4
|
+
export async function createChildModelRuntime(ctx: Pick<ExtensionContext, 'modelRegistry'>): Promise<ModelRuntime> {
|
|
5
|
+
const runtime = await ModelRuntime.create()
|
|
6
|
+
for (const providerId of ctx.modelRegistry.getRegisteredProviderIds()) {
|
|
7
|
+
const config = ctx.modelRegistry.getRegisteredProviderConfig(providerId)
|
|
8
|
+
if (config) {
|
|
9
|
+
runtime.registerProvider(providerId, config)
|
|
10
|
+
continue
|
|
11
|
+
}
|
|
12
|
+
const native = ctx.modelRegistry.getRegisteredNativeProvider(providerId)
|
|
13
|
+
if (native) {
|
|
14
|
+
runtime.registerNativeProvider(native)
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
return runtime
|
|
18
|
+
}
|