pi-subagents-extend 0.0.0-stage → 0.1.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 +21 -0
- package/README.md +133 -2
- package/bin/pi-subagents-extend-helper-linux-arm64 +0 -0
- package/bin/pi-subagents-extend-helper-linux-x64 +0 -0
- package/package.json +63 -4
- package/skills/pi-subagents-extend/SKILL.md +312 -0
- package/skills/pi-subagents-extend-context/SKILL.md +103 -0
- package/skills/pi-subagents-extend-probes/SKILL.md +151 -0
- package/src/bash/env.ts +108 -0
- package/src/bash/index.ts +27 -0
- package/src/bash/network.ts +97 -0
- package/src/bash/programs.ts +367 -0
- package/src/bash/rules.ts +247 -0
- package/src/bash/tokens.ts +169 -0
- package/src/bash/unreachable.ts +429 -0
- package/src/budgets.ts +89 -0
- package/src/child-context.ts +24 -0
- package/src/context-scope.ts +93 -0
- package/src/deliverable.ts +216 -0
- package/src/dependencies.ts +320 -0
- package/src/handoff-hint.ts +69 -0
- package/src/index.ts +181 -0
- package/src/main-context.ts +30 -0
- package/src/main-skills.ts +77 -0
- package/src/notices.ts +299 -0
- package/src/paths/index.ts +165 -0
- package/src/policy/glob.ts +146 -0
- package/src/policy/index.ts +36 -0
- package/src/policy/payload.ts +312 -0
- package/src/probe.ts +495 -0
- package/src/role-config.ts +434 -0
- package/src/sandbox/grants.ts +339 -0
- package/src/sandbox/helper.ts +137 -0
- package/src/sandbox/index.ts +12 -0
- package/src/sandbox/spec.ts +285 -0
- package/src/sandbox-note.ts +194 -0
- package/src/wiring/agent-start.ts +371 -0
- package/src/wiring/context.ts +216 -0
- package/src/wiring/misc.ts +55 -0
- package/src/wiring/session-start.ts +69 -0
- package/src/wiring/tool-call/anchor.ts +138 -0
- package/src/wiring/tool-call/bash-path.ts +0 -0
- package/src/wiring/tool-call/dispatch-preflight.ts +0 -0
- package/src/wiring/tool-call/judge.ts +585 -0
- package/src/wiring/tool-call/original-args.ts +64 -0
- package/src/wiring/tool-call/paths.ts +235 -0
- package/src/wiring/tool-result.ts +68 -0
- package/src/worktree-default.ts +27 -0
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pi-subagents-extend-context
|
|
3
|
+
description: When AGENTS.md mixes in main-agent-only content — delegation discipline, waiting policy, reporting conventions, main-agent-only write-permission boundaries — that a subagent would read as wasted context and mistake for its own duties. Strips the sections fenced by <!-- main-agent-only:start --> from the subagent's copy of AGENTS.md, and holds rules that are wholly the main agent's in .pi/main-only.md, injected into the main session only. Covers the division of labour of the three entry points, how to write the markers, the fallback when a marker is left unclosed, and the trade-off against the all-or-nothing inheritProjectContext switch.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Context isolation: let AGENTS.md feed only what should be fed
|
|
7
|
+
|
|
8
|
+
`AGENTS.md` goes in whole: a subagent reads it together with the passages that only mean something to the main agent — how to delegate, how to wait for the result, reporting conventions — wasting context, and it may also mistake the main agent's actions for its own duties.
|
|
9
|
+
|
|
10
|
+
This skill solves that: **the main agent sees everything, a subagent sees the version with the main-agent-only parts removed.**
|
|
11
|
+
|
|
12
|
+
The file scope and the bash allowlist are in `pi-subagents-extend`, the probe criteria are in `pi-subagents-extend-probes`. The three are independent, so you can use only one of them.
|
|
13
|
+
|
|
14
|
+
A subagent installing dependencies in a `worktree` is a separate matter (`worktreeSetupHook`), also covered by `pi-subagents-extend`.
|
|
15
|
+
|
|
16
|
+
## When to use it: who this content belongs to
|
|
17
|
+
|
|
18
|
+
| Content | Where | Visible to a subagent |
|
|
19
|
+
| --- | --- | --- |
|
|
20
|
+
| Rules a subagent must follow too (terminology, acceptance commands, no git push, code style) | an ordinary `AGENTS.md` section | yes |
|
|
21
|
+
| Content only the main agent needs, but that reads better written together with the repository rules | fenced in `AGENTS.md` by `<!-- main-agent-only:start -->` | no (stripped) |
|
|
22
|
+
| Content that is wholly the main agent's (how to delegate, the waiting and follow-up rhythm, how to talk to the user) | `.pi/main-only.md` | no (injected into the main session only) |
|
|
23
|
+
|
|
24
|
+
The three can be mixed. The test is simple: **would a subagent do the wrong thing by following it** — if yes, fence it or move it.
|
|
25
|
+
|
|
26
|
+
## How to write the markers
|
|
27
|
+
|
|
28
|
+
```markdown
|
|
29
|
+
# Repository conventions
|
|
30
|
+
|
|
31
|
+
## Terminology
|
|
32
|
+
|
|
33
|
+
**Upstream**: means the upstream API.
|
|
34
|
+
|
|
35
|
+
<!-- main-agent-only:start -->
|
|
36
|
+
## Delegation
|
|
37
|
+
|
|
38
|
+
Delegate with the `subagent` tool and wait for its result before deciding the next step.
|
|
39
|
+
Reporting format: which files were changed, what was run, what the result was.
|
|
40
|
+
<!-- main-agent-only:end -->
|
|
41
|
+
|
|
42
|
+
## Acceptance
|
|
43
|
+
|
|
44
|
+
`mise run test` all green.
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The whole span (both comments and the trailing blank line included) is deleted from the subagent's prompt, while the main agent reads it as usual. The comments themselves are transparent to the model, so the main agent sees no extra marker noise.
|
|
48
|
+
|
|
49
|
+
There is only one rule: **the markers must close in pairs**. When there is a start but no end, that whole span is kept as it is, not stripped, and a warning is recorded in the session — better that a subagent sees one passage too many than that half a file is deleted on a guess about where the boundary is.
|
|
50
|
+
|
|
51
|
+
## The main-agent-only file
|
|
52
|
+
|
|
53
|
+
`.pi/main-only.md` (relative to the project root, the path is fixed). If it exists it is injected; if it does not, nothing happens.
|
|
54
|
+
|
|
55
|
+
The injection uses pi's `sections` rather than replacing the whole prompt: pi diffs per section, so a change only appends one system message and the earlier prompt cache still hits.
|
|
56
|
+
|
|
57
|
+
```markdown
|
|
58
|
+
<!-- .pi/main-only.md -->
|
|
59
|
+
## Delegation and collaboration
|
|
60
|
+
|
|
61
|
+
Always delegate with extensionBindings, scope it to the task, never to the whole repository.
|
|
62
|
+
While a subagent runs asynchronously, do not sit and wait; do something else, and collect the result when it comes back.
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
The content enters the prompt as it is, with no processing and no added heading — write it however you want it to look.
|
|
66
|
+
|
|
67
|
+
## Division of labour of the three entry points (read this when changing an agent definition)
|
|
68
|
+
|
|
69
|
+
Three entry points are wrapped, and they are loaded differently, **so do not declare them together**:
|
|
70
|
+
|
|
71
|
+
| Entry point | Who loads it | Behaviour |
|
|
72
|
+
| --- | --- | --- |
|
|
73
|
+
| `src/index.ts` | the agent's `subagentOnlyExtensions` + ambient loading | the permission scope and the bash allowlist (not covered here) |
|
|
74
|
+
| `src/main-context.ts` | ambient loading only (`pi.extensions` in `package.json`, i.e. the project `.pi/extensions/` symlink or a global install) | injects `.pi/main-only.md` in the main session; in a background subagent it strips the markers instead |
|
|
75
|
+
| `src/child-context.ts` | declared only by the agent's `subagentOnlyExtensions` | strips the markers, never injects |
|
|
76
|
+
|
|
77
|
+
In the agent definition both paths go on one line:
|
|
78
|
+
|
|
79
|
+
```yaml
|
|
80
|
+
subagentOnlyExtensions: /path/to/pi-subagents-extend/packages/pi-plugin/src/index.ts, /path/to/pi-subagents-extend/packages/pi-plugin/src/child-context.ts
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Why split into two files instead of one: **a foreground subagent cannot be distinguished from the main session within the process**. A foreground subagent is a session in the same process without `PI_SUBAGENT_CHILD`, with an environment identical to the main session's; a background subagent is a separate process and has that variable. So the "main-agent-only" logic can only determine its audience by the loading path, not by a runtime check. The `PI_SUBAGENT_CHILD === "1"` in `main-context.ts` exists to hold back background subagents — that file is also loaded by ambient loading, otherwise it would leak.
|
|
84
|
+
|
|
85
|
+
## The trade-off with inheritProjectContext
|
|
86
|
+
|
|
87
|
+
pi-subagents has a ready-made switch: `inheritProjectContext: false` makes the subagent **not read AGENTS.md at all** (in the implementation it simply turns on `noContextFiles`, so the file is never even read).
|
|
88
|
+
|
|
89
|
+
- When the repository rules mean nothing to subagents, this is the easiest option, with zero code.
|
|
90
|
+
- But as soon as one repository rule should also be followed by subagents (acceptance commands, no git push, terminology), switching everything off means copying those into every agent definition, and with many agents that becomes duplicated maintenance.
|
|
91
|
+
|
|
92
|
+
The marker approach of this skill keeps a single file and a single place to maintain. The two do not conflict: with `inheritProjectContext: false` the markers naturally have no meaning either (the file is not read in at all); an agent set to `false` does not need to declare `child-context.ts`.
|
|
93
|
+
|
|
94
|
+
Also note subagents with `context: "fork"`: they take the parent's whole system prompt along with the project context, so the markers are stripped by `child-context.ts`, but the injection of `.pi/main-only.md` already happened in the parent's prompt — an unexpected leftover. **If you want isolation, do not use fork context.**
|
|
95
|
+
|
|
96
|
+
## Troubleshooting
|
|
97
|
+
|
|
98
|
+
| Symptom | Cause |
|
|
99
|
+
| --- | --- |
|
|
100
|
+
| The subagent still reads the content inside the markers | the agent definition does not declare `child-context.ts`; or that run was a fork context |
|
|
101
|
+
| The subagent reads `.pi/main-only.md` | that file was put into AGENTS.md or into some skill, it does not spread by itself; or the agent used fork context |
|
|
102
|
+
| The main session does not see `.pi/main-only.md` | the extension is not loaded via ambient loading (declaring it only in `subagentOnlyExtensions` means it is not loaded in the main session) |
|
|
103
|
+
| You see a warning about an `unclosed <!-- main-agent-only:start -->` | one half of the marker pair is missing, add `<!-- main-agent-only:end -->` |
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: pi-subagents-extend-probes
|
|
3
|
+
description: For a subagent that is idling, stuck, or spinning — keeps re-reading the same spot, re-runs the same failing command verbatim, keeps trying after the task is effectively complete, or starts creating probe litter files. Probes detect read-only idling, repeating a command, finished early, writing litter, and permission refusals; a hit blocks that call, and once a stop condition is reached the turn ends immediately. Documents the maxDenies and probe fields of pi-subagents-extend/1 in extensionBindings with their defaults, the difference between warn and stop (stop is a hard stop with no wrap-up turn), and what the parent agent should look at after a subagent is stopped. Scope and the bash allowlist are covered in pi-subagents-extend.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Probes: detecting subagent idling and ineffective work
|
|
7
|
+
|
|
8
|
+
The scope restriction (`scope`) only governs which files a subagent can touch; probes watch whether it is making progress. Both live in the same delegation's `extensionBindings` and share the `pi-subagents-extend/1` namespace.
|
|
9
|
+
|
|
10
|
+
## When it applies
|
|
11
|
+
|
|
12
|
+
| Symptom | Criterion |
|
|
13
|
+
| --- | --- |
|
|
14
|
+
| Repeatedly reading the same file/directory with no write operations | read-only idling |
|
|
15
|
+
| The same kind of command or path keeps failing, but is retried verbatim every time | repeating a command |
|
|
16
|
+
| The task is effectively done (typecheck already passed) but it keeps trying | finished early |
|
|
17
|
+
| Leaving temporary probe files in the repository | writing litter |
|
|
18
|
+
| Repeatedly hitting the same permission refusal | permission refusal |
|
|
19
|
+
|
|
20
|
+
When a criterion hits, the current tool_call is blocked with a reason; once a stop condition is reached the turn ends immediately (every blocked result carries `terminate`), with no wrap-up turn.
|
|
21
|
+
|
|
22
|
+
## Default behavior
|
|
23
|
+
|
|
24
|
+
When `probe` is not written, only two pure error signals are active, so collateral damage is low:
|
|
25
|
+
|
|
26
|
+
| Criterion | Default | Notes |
|
|
27
|
+
| --- | --- | --- |
|
|
28
|
+
| repeating a command | on, `repeatBash: 3` | The same bash command verbatim (after trim) the 3rd time → warn, the 4th → stop |
|
|
29
|
+
| permission refusal | on, `maxDenies: 5` and `maxWriteDenies: 2` | The 5th consecutive **authorization-type** refusal → warn (asking it to escalate), the 6th → hard stop. Only refusals that a parent agent granting broader authorization could resolve are counted: paths outside the read scope, commands not in the allowlist, read budget, tools not in `allowTools`, bash entirely disabled. **Write refusals have their own budget**: the 2nd write refusal warns, the 3rd hard-stops; the two budgets do not share a counter. Both are **consecutive**: an allowed working call resets the count, while `contact_supervisor`/`structured_output` do not count as progress and do not reset it |
|
|
30
|
+
|
|
31
|
+
The three criteria that can misfire on slow tasks must be explicitly configured: `probe: {}` turns on all defaults at once, writing only some fields turns on just those, and `probe: false` turns everything off.
|
|
32
|
+
|
|
33
|
+
| Criterion | Fields | Default (after explicit enable) | Trigger |
|
|
34
|
+
| --- | --- | --- | --- |
|
|
35
|
+
| read-only idling | `probe.idleWriteMs` / `probe.abortGraceMs` | 6 minutes / 2 minutes | No write activity for this long → warn; after the grace period → stop |
|
|
36
|
+
| finished early | `probe.successIdleMs` / `probe.successPatterns` | 5 minutes / `["fail=0", "0 failed", ...]` | After bash output matches a success marker, no new changes for this long → stop |
|
|
37
|
+
| writing litter | `probe.forbidWritePatterns` | `[]` | A `write`/`edit` target path matches the regex → that write is refused outright |
|
|
38
|
+
|
|
39
|
+
## What counts as "write activity"
|
|
40
|
+
|
|
41
|
+
Only two kinds of events reset the idle timer:
|
|
42
|
+
|
|
43
|
+
1. `edit` / `write` tool calls
|
|
44
|
+
2. bash commands matching the `bash.write` column
|
|
45
|
+
|
|
46
|
+
A repeat counts only when its **output did not change**. The same command returning new output is
|
|
47
|
+
progress — that is what measuring a repository looks like — so the count resets and a warning already
|
|
48
|
+
issued is withdrawn. A child that is genuinely stuck prints the same thing every time and still walks
|
|
49
|
+
into the threshold.
|
|
50
|
+
|
|
51
|
+
Only **read-class** commands are counted for spinning: a command that writes (the `bash.write` column, or an `edit`/`write` call) is progress, so it clears the counts and cancels a warning already issued. A coder that edits a file and re-runs the same test command is therefore never stopped by this criterion — a config that lists an interpreter in the `write` column (`node`, `python3`) exempts that interpreter's commands entirely.
|
|
52
|
+
|
|
53
|
+
Commands in the `bash.read` column, and `read` / `grep` / `find` / `ls`, do not count. So "spinning with read-only bash commands" and "repeatedly scanning with read tools" are both judged as idling — this is intentional: no amount of read-only commands counts as progress.
|
|
54
|
+
|
|
55
|
+
Corollary: if a task genuinely needs extensive read-only investigation, either loosen `idleWriteMs` or set `readOnly: true` (which skips both time-based criteria, "read-only idling" and "finished early").
|
|
56
|
+
|
|
57
|
+
## Configuration template
|
|
58
|
+
|
|
59
|
+
```json
|
|
60
|
+
{
|
|
61
|
+
"pi-subagents-extend/1": {
|
|
62
|
+
"permissions": {
|
|
63
|
+
"scope": ["src/auth/**"],
|
|
64
|
+
"bash": { "allow": ["pnpm run typecheck", "pnpm test"], "writable": true },
|
|
65
|
+
"maxDenies": 5,
|
|
66
|
+
"probe": {
|
|
67
|
+
"idleWriteMs": 360000,
|
|
68
|
+
"abortGraceMs": 120000,
|
|
69
|
+
"successIdleMs": 300000,
|
|
70
|
+
"successPatterns": ["0 failed"],
|
|
71
|
+
"forbidWritePatterns": ["scratch/.*", "_tmp-.*"]
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Stop semantics (what the parent agent must know)
|
|
79
|
+
|
|
80
|
+
warn only blocks a single tool_call and writes the reason to it; stop is a **hard stop**: every blocked result carries `terminate`, and pi ends the turn when the whole batch of tool results is terminating (`docs/extensions.md`). The call that trips the stop gets the full reason; calls after it get a status line ("the run was stopped earlier") rather than the old reason over again. A stop fired by a timer (idling, finished early) has no call to answer, so the first boundary after it delivers the reason and only the later ones get the status line, because that reason names the action that caused the stop and a subagent that changed course reads it as a verdict on the new command. `contact_supervisor` and `structured_output` stay open either way. Therefore:
|
|
81
|
+
|
|
82
|
+
- **There is no wrap-up turn after a stop.** The subagent gets no further chance to "write a final report"; the parent agent has to infer what happened from what was produced before the stop plus the refusal reasons. If you want the subagent to explain itself, have it report before it crosses the line.
|
|
83
|
+
- **Escalation channels are unaffected by a stop.** `contact_supervisor` / `intercom` / `structured_output` are checked before the stop decision and are always allowed through — this only truly saves you when **the same batch contains an allowed result** (the batch is not entirely terminating, so the turn continues): the stopped subagent can still get "where I am stuck and what I need" out.
|
|
84
|
+
- A `[sandbox]` annotation at the end of a result (network disabled, write out of bounds) is **not a refusal**: it only explains a call that already failed inside the sandbox; it does not count toward permission refusals, does not trigger a stop, and does not consume the read budget. Do not treat it as "refused again"; just follow the suggestion inside (use `contact_supervisor` if authorization is needed).
|
|
85
|
+
- The stop reason is not a judgment of the current call. The text explicitly says "which criterion stopped the run" and names the call that triggered it; do not treat the path in it as "the path that was just refused" — that is history.
|
|
86
|
+
|
|
87
|
+
## Notes for the parent agent
|
|
88
|
+
|
|
89
|
+
- The "finished early" trap: after a success marker hits, it only stops once there are no new changes, so a task that still has work after verification will be judged "time to finish". **Put the verification command as the last step of the task**, or do not configure this criterion.
|
|
90
|
+
- `successPatterns` defaults to test-summary markers like `fail=0` / `0 failed`; if the project uses a different output format, write your own (e.g. `no errors`, `All files pass`). Do not use overly broad `ok` or `passed` — almost every command would match.
|
|
91
|
+
- To stop a subagent from carelessly writing debug files, use `forbidWritePatterns` to name the project's own temporary file patterns (e.g. `scratch/.*`, `_tmp-.*`). A hit refuses that single write, without stopping the run.
|
|
92
|
+
- Frequent "repeating a command" in the same delegation indicates a problem with the task description (it asks for the same action repeatedly); fix the task first instead of raising `repeatBash`.
|
|
93
|
+
- **Permission refusal** only counts **authorization-type** refusals, judged by whether the parent agent could resolve it by granting broader authorization or adjusting settings. Counted: paths outside the read scope (including using `.` as a path), commands not in the allowlist, read budget exhausted, tools not in `allowTools`, bash entirely disabled. **Write refusals are counted separately** (`maxWriteDenies`, default 2): a subagent whose scope is readable but whose `writeScope` is narrower keeps trying to write, which is a usage mistake answered by delivering the report — not evidence that the grant was wrong. The refusal names the write scope and says so, and the read budget is untouched by it. Not counted: usage errors (missing path, shell metacharacters, empty command), hard rules (tools that are permanently unavailable such as `powershell`/`codemode`, and the role md's `bash.deny`), and the dependency gate (a lockfile directory with no `node_modules/.bin`), which reports an unfinished install rather than a grant that does not fit — counting these against the budget would let a single parameter typo kill a long task prematurely. When a subagent reports a usage error, fix the task to be clearer instead of masking it with a larger `maxDenies`.
|
|
94
|
+
- Probes only handle deterministic signals. Semantic-level missed tests and unsafe changes are left to pi-subagents' built-in LLM watchdog (`subagents.watchdog`); the two complement each other.
|
|
95
|
+
|
|
96
|
+
## Working with pi-subagents' built-in capabilities
|
|
97
|
+
|
|
98
|
+
Delegation rules (how to write a brief, one writer per cwd, how to use resume/steer) follow **pi-subagents' built-in skill**; this skill only covers the probe layer: scope restrictions govern "what can be touched", probes govern "whether progress is being made".
|
|
99
|
+
|
|
100
|
+
pi-subagents' own skill defines how to wait; this skill does not restate it. To check details, read one section on demand rather than reading it all:
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
subagent({ action: "guide", options: { topic: "tool-reference/execution-parameters" } })
|
|
104
|
+
subagent({ action: "guide", options: { topic: "workflows/supervisor-coordination-child-asks-parent" } })
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
The topics listed below are real section names in pi-subagents' bundled documentation; after a version upgrade, read them at the same address.
|
|
108
|
+
|
|
109
|
+
| What you want to look up | guide topic |
|
|
110
|
+
| --- | --- |
|
|
111
|
+
| `timeoutMs` / `toolTimeoutMs` / `checkpointBeforeDeadlineMs` / `toolBudget` / `extensionBindings` | `tool-reference/execution-parameters` |
|
|
112
|
+
| Subagent status and transcript | `tool-reference/status` |
|
|
113
|
+
| Retaining subagents, resume eligibility | `tool-reference/retained-children` |
|
|
114
|
+
| Exact semantics of resume / steer / stop | `tool-reference/resume`, `tool-reference/steer`, `tool-reference/stop` |
|
|
115
|
+
| Acceptance evidence and gates | `tool-reference/acceptance-gates` |
|
|
116
|
+
| A subagent proactively asking its parent (`contact_supervisor`) | `workflows/supervisor-coordination-child-asks-parent` |
|
|
117
|
+
| When the LLM watchdog runs and model choice | `watchdog/when-it-runs`, `watchdog/choosing-a-model` |
|
|
118
|
+
|
|
119
|
+
Probes only handle deterministic signals (counts, time, path patterns); the items below handle other concerns and need no probe once configured.
|
|
120
|
+
|
|
121
|
+
### Division of labor
|
|
122
|
+
|
|
123
|
+
| Need | What to use | How to configure |
|
|
124
|
+
| --- | --- | --- |
|
|
125
|
+
| Overall cap on how long a run may take | Native run-level deadline | `options.timeoutMs` (or agent frontmatter `timeoutMs`); when it expires the run is over |
|
|
126
|
+
| A single tool call hangs | Native tool deadline | Known-fast commands default to 5 minutes; change with `options.toolTimeoutMs` |
|
|
127
|
+
| Wrap up before the deadline | Native checkpoint steer | `options.checkpointBeforeDeadlineMs` (**async single agent only**): delivers "checkpoint and stop" at the next tool boundary before the deadline, asking for changed files / build-test status / remaining work |
|
|
128
|
+
| Cap on total tool calls | Native `toolBudget` | `{ soft, hard, block }`; at hard, read/grep/find/ls are blocked by default. **Do not set it for implementation subagents** (reads get blocked before writes) |
|
|
129
|
+
| Semantic quality: missed tests, out-of-scope changes, loop risk | Native LLM watchdog | `subagents.watchdog`, boundary review + cadence review every N tools; high severity is surfaced to the model |
|
|
130
|
+
| Delivery acceptance: which files changed, whether tests ran | Native acceptance gate | `options.gate: "pnpm test"` or `acceptance: { level, criteria, evidence, verify }` |
|
|
131
|
+
| Subagent needs resources/authorization mid-task | `contact_supervisor` / `intercom` | Always allowed; the parent can also interject via `subagent({ action: "steer", id, message })` |
|
|
132
|
+
| Idling, spinning, not finishing after verification, writing temporary files carelessly | **Probes** | The items above in this document |
|
|
133
|
+
|
|
134
|
+
### How they combine
|
|
135
|
+
|
|
136
|
+
**Probes + run deadline.** The deadline governs total duration; probes govern "acting but not progressing". When both are on, note: `checkpointBeforeDeadlineMs` sends a wrap-up steer before the deadline, and if a probe also judges idling at that moment, the subagent receives both instructions at once — whichever arrives first wins. In practice: back the main task with `timeoutMs`, and set `idleWriteMs` to about a third of `timeoutMs` so idling is caught earlier than the overall timeout.
|
|
137
|
+
|
|
138
|
+
**Probes + acceptance gate.** "Finished early" infers that verification passed from success markers in bash output — it is heuristic; real acceptance should be left to the gate — `gate: "pnpm test"` is executed by the host and recorded as evidence. So: **hand the verification command to the gate and do not configure `successPatterns` in probes to guess**. When both are on, if `successPatterns` matches too early (e.g. the command's echo rather than the real result), a subagent still working will be misjudged as done.
|
|
139
|
+
|
|
140
|
+
**Probes + permission refusals + steer.** After a stop from permission refusals, the parent agent has two options: re-delegate a fresh task (exploratory tasks, low cost) or `resume` the retained session with added authorization (long tasks you do not want to redo). `resume` reuses the original subagent's session and contract; the bindings belong to a new launch and can be changed.
|
|
141
|
+
|
|
142
|
+
**Probes + LLM watchdog.** They do not conflict; they use different configuration channels: probes go through `extensionBindings`, the watchdog through `subagents.watchdog` in settings. The watchdog has its own `stalemateRepeats` (default 3 identical warnings) that ends a turn — that is at the semantic level; the probe's repeating criterion is at the command level. Both may fire at once; they are not billed twice and do not need to disable each other.
|
|
143
|
+
|
|
144
|
+
**Probes + background runs.** Background (`async: true`) subagents run in a separate process and probes work as usual; `checkpointBeforeDeadlineMs` only works on async single agents. Foreground blocking runs have no such wrap-up mechanism, and a probe stop is a **hard stop**: the turn ends immediately, with no chance for the subagent to write a report.
|
|
145
|
+
|
|
146
|
+
### Things not to stack
|
|
147
|
+
|
|
148
|
+
- **Do not set `toolBudget.hard` for implementation subagents**: it blocks reads and searches first, the subagent gets less context and idles more easily, and the probe then kills the run — it looks like a probe misfire. To restrict, limit the scope (`scope`) and duration (`timeoutMs`).
|
|
149
|
+
- **Do not configure the same verification in both `successPatterns` and the gate**: one place deciding success is enough; two places tend to disagree over time.
|
|
150
|
+
- **Do not use `probe: false` to "save effort"**: by default only repeating and permission refusals are on, so turning it off gives up the two cheapest error signals. To actually silence it, write a specific relaxation such as `probe: { repeatBash: 50 }`.
|
|
151
|
+
|
package/src/bash/env.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bash 前置赋值(`FOO=1 cmd`)的处理。
|
|
3
|
+
*
|
|
4
|
+
* 从 bash/index.ts 拆出来的安全控制层:剥出命令前连续的赋值,
|
|
5
|
+
* 并拦下能注入代码或换掉要跑的程序的黑名单名字。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const ASSIGNMENT_HEAD = /^[A-Za-z_][A-Za-z0-9_]*\+?=/;
|
|
9
|
+
|
|
10
|
+
// 与 ASSIGNMENT_HEAD 同判:剥直通包装器时用来跳过 `env FOO=1 cmd` 里的赋值。
|
|
11
|
+
export const ASSIGNMENT_LIKE = /^[A-Za-z_][A-Za-z0-9_]*\+?=/;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* 前缀赋值里那些能改变「跑哪个程序」或者「往进程里塞代码」的名字。
|
|
15
|
+
*
|
|
16
|
+
* 这一层不是严格沙箱,是让子代理走在既定轨道上的辅助(定位如此:放行多了可以事后补,卡太死
|
|
17
|
+
* 反而妨碍干活),所以这里是**黑名单**而不是白名单:挡住已知的注入入口,其余名字照常放行。
|
|
18
|
+
* 漏一个就是一次放宽 —— 这是刻意接受的代价,每一条都对应一个可验证的注入方式:
|
|
19
|
+
*
|
|
20
|
+
* LD_* / DYLD_* 往任意进程加载共享库
|
|
21
|
+
* NODE_* / npm_config_* node 预加载模块;实测 `NODE_OPTIONS=--require=/tmp/x.js node -e ""`
|
|
22
|
+
* 直接执行了 /tmp/x.js
|
|
23
|
+
* PYTHON* / PERL* / RUBY* 解释器预加载
|
|
24
|
+
* GIT_* / PAGER / LESSOPEN 被允许的 git 子命令、分页器里跑任意程序
|
|
25
|
+
* BASH_ENV / ENV / BASH_FUNC_* shell 启动时执行
|
|
26
|
+
* PATH / IFS 换掉要跑的程序 / 改变词法
|
|
27
|
+
*
|
|
28
|
+
* 刻意**不含** HOME:它是最常见的痛点写法(`HOME=/tmp/pi-home node x.mjs`),而借它注入要
|
|
29
|
+
* 额外满足若干条件(例如宿主的 pager 只在 tty 下才起)。这条边界是取舍,不是疏漏。
|
|
30
|
+
*/
|
|
31
|
+
const DENIED_ENV_NAMES = new Set(["PATH", "IFS", "ENV", "PAGER", "LESSOPEN", "LESSCLOSE", "MANPAGER", "BASH_ENV", "SHELLOPTS"]);
|
|
32
|
+
const DENIED_ENV_PREFIXES = [
|
|
33
|
+
"LD_",
|
|
34
|
+
"DYLD_",
|
|
35
|
+
"NODE_",
|
|
36
|
+
"npm_config_",
|
|
37
|
+
"NPM_CONFIG_",
|
|
38
|
+
"PYTHON",
|
|
39
|
+
"PERL",
|
|
40
|
+
"RUBY",
|
|
41
|
+
"GIT_",
|
|
42
|
+
"BASH_FUNC_",
|
|
43
|
+
"JAVA_TOOL_",
|
|
44
|
+
"_JAVA_",
|
|
45
|
+
"MALLOC_",
|
|
46
|
+
];
|
|
47
|
+
|
|
48
|
+
export function isDeniedEnvName(name: string): boolean {
|
|
49
|
+
if (DENIED_ENV_NAMES.has(name)) return true;
|
|
50
|
+
return DENIED_ENV_PREFIXES.some((prefix) => name.startsWith(prefix));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 前置赋值的名字,以及剥掉前缀之后剩下的命令。 */
|
|
54
|
+
export interface LeadingAssignments {
|
|
55
|
+
names: string[];
|
|
56
|
+
rest: string;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* 扫出最前面连续的 `NAME=value` 赋值,返回名字与剩下的命令。
|
|
61
|
+
*
|
|
62
|
+
* 逐字符扫而不是按空白切词:值可以被引号包住(`HOME="/tmp/my home"`),按空白切会把它切成两半,
|
|
63
|
+
* 剩下半截 `home"` 当程序名,于是另一条合法命令被误拒 —— 那正是这个补丁要修的那类失败。
|
|
64
|
+
* 名字允许在 `=` 前带一个 `+`(`A+=1` 是追加赋值,bash 同样当赋值看)。
|
|
65
|
+
* 引号没闭合时值一直吃到末尾,剩下的命令为空,空命令永不匹配(fail closed)。
|
|
66
|
+
*/
|
|
67
|
+
export function leadingAssignments(command: string): LeadingAssignments {
|
|
68
|
+
const text = command.trim();
|
|
69
|
+
const names: string[] = [];
|
|
70
|
+
let i = 0;
|
|
71
|
+
for (;;) {
|
|
72
|
+
while (i < text.length && /\s/.test(text[i] as string)) i += 1;
|
|
73
|
+
const head = ASSIGNMENT_HEAD.exec(text.slice(i));
|
|
74
|
+
if (!head) break;
|
|
75
|
+
names.push(head[0].replace(/\+?=$/, ""));
|
|
76
|
+
let j = i + head[0].length;
|
|
77
|
+
let quote: string | undefined;
|
|
78
|
+
while (j < text.length) {
|
|
79
|
+
const ch = text[j] as string;
|
|
80
|
+
if (quote) {
|
|
81
|
+
if (ch === "\\" && quote === '"') {
|
|
82
|
+
j += 2;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (ch === quote) quote = undefined;
|
|
86
|
+
j += 1;
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
if (ch === "'" || ch === '"') {
|
|
90
|
+
quote = ch;
|
|
91
|
+
j += 1;
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
if (/\s/.test(ch)) break;
|
|
95
|
+
j += 1;
|
|
96
|
+
}
|
|
97
|
+
i = j;
|
|
98
|
+
}
|
|
99
|
+
return { names, rest: i === 0 ? text : text.slice(i).trim() };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 前置赋值里命中黑名单的名字,供拒绝文案点名。命中即拒:带上它,「被允许的命令」就变成了
|
|
104
|
+
* 「跑我自己的代码」,白名单等于没写。
|
|
105
|
+
*/
|
|
106
|
+
export function deniedEnvAssignment(command: string): string | undefined {
|
|
107
|
+
return leadingAssignments(command).names.find((name) => isDeniedEnvName(name));
|
|
108
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bash 白名单:唯一入口。
|
|
3
|
+
*
|
|
4
|
+
* 实现按层拆在 src/bash/ 下(env / programs / network / tokens / rules / unreachable),
|
|
5
|
+
* 这里只转出口;调用方一律从本文件 import。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export { deniedEnvAssignment, leadingAssignments, type LeadingAssignments } from "./env.ts";
|
|
9
|
+
export { commandAccess, isUnknownProgram } from "./programs.ts";
|
|
10
|
+
export { requiresNetwork } from "./network.ts";
|
|
11
|
+
export { commandSegments, pathCandidates, shellTokens, tokens } from "./tokens.ts";
|
|
12
|
+
export {
|
|
13
|
+
allEntries,
|
|
14
|
+
classifyCommand,
|
|
15
|
+
commandMatches,
|
|
16
|
+
deniedEntry,
|
|
17
|
+
firstToken,
|
|
18
|
+
listedJoin,
|
|
19
|
+
MAX_LISTED,
|
|
20
|
+
parseBashRule,
|
|
21
|
+
stringList,
|
|
22
|
+
type BashAccess,
|
|
23
|
+
type BashMatch,
|
|
24
|
+
type BashRule,
|
|
25
|
+
type UnreachableEntry,
|
|
26
|
+
} from "./rules.ts";
|
|
27
|
+
export { commandNeedsNoManifest, unreachableEntries } from "./unreachable.ts";
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 离线沙箱里「一跑就挂」的网络命令判定。
|
|
3
|
+
*
|
|
4
|
+
* 从 bash/index.ts 拆出来的网络层:裸 netns 是丢包而不是拒连,这一类命令要在 spawn
|
|
5
|
+
* 之前拒掉。判据看剥掉前置赋值、包装器与路径前缀后的第一个 token。
|
|
6
|
+
* bash/index.ts 仍是唯一入口,requiresNetwork 由它转出口。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { basename } from "node:path";
|
|
10
|
+
import { leadingAssignments } from "./env.ts";
|
|
11
|
+
import { gitSubcommandIndex, peelWrappers } from "./programs.ts";
|
|
12
|
+
import { shellTokens } from "./tokens.ts";
|
|
13
|
+
|
|
14
|
+
const NETWORK_PROGRAMS = new Set([
|
|
15
|
+
"curl", "wget", "nc", "ncat", "netcat", "telnet", "ssh", "scp", "sftp",
|
|
16
|
+
"ping", "dig", "host", "nslookup", "traceroute", "gh",
|
|
17
|
+
]);
|
|
18
|
+
const NETWORK_SUBCOMMANDS: Record<string, string[]> = {
|
|
19
|
+
docker: ["pull", "push", "login"],
|
|
20
|
+
npm: ["publish"],
|
|
21
|
+
pnpm: ["publish"],
|
|
22
|
+
yarn: ["publish"],
|
|
23
|
+
};
|
|
24
|
+
const GIT_NETWORK_SUBCOMMANDS = new Set(["clone", "fetch", "pull", "push", "ls-remote"]);
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* curl 的 URL 参数是否全是 file: 协议:读了也不出网,裸 netns 里照常工作。
|
|
28
|
+
* 带任何其他 scheme(http/https/ftp/…)就仍按网络判;不含 scheme 的裸 host 不在这里放行。
|
|
29
|
+
*/
|
|
30
|
+
function curlOnlyReadsFiles(args: string[]): boolean {
|
|
31
|
+
let sawFileUrl = false;
|
|
32
|
+
for (const arg of args) {
|
|
33
|
+
if (/^file:/i.test(arg)) {
|
|
34
|
+
sawFileUrl = true;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(arg)) return false; // 别的 scheme 要出网
|
|
38
|
+
}
|
|
39
|
+
return sawFileUrl;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// curl 的查询旗标打印完本地信息就退出;放在任何 URL 之前都成立,不能当成要出网而误拒。
|
|
43
|
+
const CURL_LOCAL_QUERY_FLAGS = new Set(["--version", "-V", "--help", "-h"]);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 离线沙箱里「一跑就挂」的网络命令判定。
|
|
47
|
+
*
|
|
48
|
+
* 裸 netns 是丢包而不是拒连:`curl` 没有输出也没有错误,事后注解(networkFailureNote)
|
|
49
|
+
* 等不到触发文本,所以要在 spawn 之前拒掉这一类。判据放在共用层,不按角色各写一份。
|
|
50
|
+
*
|
|
51
|
+
* 宁可少拒,不许误拒:只认确定的程序名与子命令;`git status`、`pnpm install`、
|
|
52
|
+
* `cargo fetch`、`npm run …`、`pnpm --dir … run …` 都能从缓存或本地工作,一律放行;
|
|
53
|
+
* 拿不准的也放行。名单看剥掉前置赋值、包装器与路径前缀后的第一个 token,动态拼出来的
|
|
54
|
+
* 程序名(`$TOOL`、`$(…)`)不判 —— 这一层是引导,不是防黑客,而且 shell 元字符本来就会被先拒掉。
|
|
55
|
+
* 引号里的东西刻意不解析:`bash -c "curl …"` 不判;直通包装器(env/sudo/…)则剥开看它真正跑谁。
|
|
56
|
+
*
|
|
57
|
+
* @returns 需要网络的程序名(有子命令时一并给出,如 `git fetch`),否则 null。
|
|
58
|
+
*/
|
|
59
|
+
export function requiresNetwork(command: string): string | null {
|
|
60
|
+
const words = shellTokens(leadingAssignments(command).rest);
|
|
61
|
+
const effective = peelWrappers(words);
|
|
62
|
+
if (!effective || effective.length === 0) return null;
|
|
63
|
+
// 绝对路径也要认:`/usr/bin/curl` 与 `curl` 是同一个程序。
|
|
64
|
+
const program = basename(effective[0] as string);
|
|
65
|
+
// `gh --version` / `version` / `help` / `config get` 只读本地配置,不外出。
|
|
66
|
+
if (program === "gh") {
|
|
67
|
+
const sub = effective[1];
|
|
68
|
+
if (sub === "--version" || sub === "version" || sub === "help") return null;
|
|
69
|
+
if (sub === "config" && effective[2] === "get") return null;
|
|
70
|
+
return "gh";
|
|
71
|
+
}
|
|
72
|
+
if (NETWORK_PROGRAMS.has(program)) {
|
|
73
|
+
if (program === "curl" && CURL_LOCAL_QUERY_FLAGS.has(effective[1] ?? "")) return null;
|
|
74
|
+
// `curl file:///…` 是本地文件读取,裸 netns 下也能成。
|
|
75
|
+
if (program === "curl" && curlOnlyReadsFiles(effective.slice(1))) return null;
|
|
76
|
+
return program;
|
|
77
|
+
}
|
|
78
|
+
if (program === "git") {
|
|
79
|
+
const located = gitSubcommandIndex(effective);
|
|
80
|
+
// 子命令位置认不全时网络也认不出:沿用本层「拿不准就放行」的口径,不误拒本地命令。
|
|
81
|
+
if (!located.certain) return null;
|
|
82
|
+
const sub = effective[located.index];
|
|
83
|
+
if (sub && GIT_NETWORK_SUBCOMMANDS.has(sub)) return `git ${sub}`;
|
|
84
|
+
const next = effective[located.index + 1];
|
|
85
|
+
// `git remote -v` / `git submodule update` 只看本地;带上 update 才去网络上取。
|
|
86
|
+
if (sub === "remote" && next === "update") return "git remote update";
|
|
87
|
+
if (sub === "submodule" && next === "update" && effective.slice(located.index + 2).includes("--remote")) {
|
|
88
|
+
return "git submodule update --remote";
|
|
89
|
+
}
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
// 原型链上的键(toString 之类)不是程序名:用 hasOwn 而不是直接索引。
|
|
93
|
+
if (!Object.hasOwn(NETWORK_SUBCOMMANDS, program)) return null;
|
|
94
|
+
const sub = effective[1];
|
|
95
|
+
const list = NETWORK_SUBCOMMANDS[program] as string[];
|
|
96
|
+
return sub && list.includes(sub) ? `${program} ${sub}` : null;
|
|
97
|
+
}
|