pi-subagents-extend 0.1.0 → 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/README.md CHANGED
@@ -22,9 +22,10 @@ The package ships on npm with the sandbox helper prebuilt for linux-x64 and linu
22
22
  install needs neither Rust nor a network beyond npm:
23
23
 
24
24
  ```bash
25
- pi install npm:pi-subagents-extend@0.1.0 # the exact version is the pin
25
+ pi install npm:pi-subagents-extend
26
26
  ```
27
27
 
28
+
28
29
  From a checkout instead (contributing, or a change you want to try before it ships):
29
30
 
30
31
  ```bash
@@ -41,16 +42,15 @@ If the helper is missing or does not match the platform, a session with `bash` e
41
42
  starts — it names the path the package carries and the `PI_SUBAGENTS_EXTEND_HELPER_PATH` override,
42
43
  rather than waiting for the first `bash` call to fail.
43
44
 
44
- A role is declared in the agent's own markdown: `subagentOnlyExtensions` names the md-role loader, and
45
- the `extend` block carries its policy. `.pi/agents/` in this repository has ten working examples —
45
+ A role is declared in the agent's own markdown: the `extend` block carries its policy. `.pi/agents/` in
46
+ this repository has ten working examples —
46
47
  `coder-bash.md` is the shortest one to copy.
47
48
 
48
49
  ```markdown
49
50
  ---
50
51
  name: worker
51
52
  description: Implements a task within the given scope
52
- systemPromptMode: append # replace drops the <active_agent> tag the loader reads
53
- subagentOnlyExtensions: /path/to/pi-subagents-extend/.pi/agent-profiles/md-role.ts
53
+ systemPromptMode: append # replace drops the <active_agent> tag the extension reads
54
54
  extend:
55
55
  permissions:
56
56
  scope: ["src/auth/**"]
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-subagents-extend",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Everything a pi session needs around subagents: scope what a delegated subagent may touch, and keep main-agent-only context out of child prompts",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -40,6 +40,9 @@
40
40
  "prepack": "cp -f ../../README.md ../../LICENSE .",
41
41
  "lint": "eslint ."
42
42
  },
43
+ "peerDependencies": {
44
+ "@earendil-works/pi-coding-agent": "*"
45
+ },
43
46
  "devDependencies": {
44
47
  "@earendil-works/pi-coding-agent": "^1.4.0",
45
48
  "@eslint/js": "^10.0.1",
@@ -29,14 +29,11 @@ The delegation rules themselves (how to write the brief, how to wait, one cwd, o
29
29
 
30
30
  ## Prerequisites
31
31
 
32
- The delegated agent must be able to load this extension. Choose one:
33
-
34
- - declare `subagentOnlyExtensions: /path/to/pi-subagents-extend/packages/pi-plugin/src/index.ts` in the agent definition's frontmatter (works for foreground and background subagents; recommended);
32
+ The delegated agent must be able to load this extension:
35
33
  - the extension is installed globally (`~/.pi/agent/extensions/pi-subagents-extend`) and this delegation sets `async: true` (only background subagents use ambient discovery).
36
34
 
37
35
  Without the extension loaded, passing bindings does nothing: no interception happens.
38
36
 
39
- A role md loads the extension through the md-role loader (`.pi/agent-profiles/md-role.ts`, which passes no profile name), so listing `…/src/index.ts` beside it is not needed (see [Area roles](#area-roles-one-md-per-code-area-policy-inside-the-md)).
40
37
  If the project uses the `<!-- main-agent-only:start -->` marker, add `, …/src/child-context.ts` to the same line, otherwise the subagent reads the main-agent-only sections (see skill `pi-subagents-extend-context`).
41
38
 
42
39
  Allowlisted commands run under the sandbox helper (the Rust binary in `packages/helper`): the file scope is enforced by Landlock, the network is off by default (all outbound TCP/UDP is cut and DNS resolution fails, but loopback works inside the sandbox, so a local server can be started and reached), and processes and capabilities are isolated as well (the host processes are invisible, the command has no capability at all). The host needs Landlock ABI 7 (Linux 6.15+); when the helper is missing or the kernel is too old, bash stays disabled (the remaining features are unaffected).
@@ -195,10 +192,8 @@ One file holds the area's write grant, its allowlist, its budget and the one com
195
192
  the work, and a dispatch to that role needs only `agent`, `model` and `task`; a per-dispatch
196
193
  `extensionBindings` payload narrows one task further on top of that default.
197
194
 
198
- The mechanism: the extension is loaded by a loader that passes **no** profile name
199
- (`.pi/agent-profiles/md-role.ts`, which is just `export default activate`), declared in the role
200
- md's `subagentOnlyExtensions`. Nothing reads a bindings file; the reader recomputes the policy
201
- from the merged fields, so a md that supplies `scope` produces an active policy with no other
195
+ The mechanism: nothing reads a bindings file; the reader recomputes the policy from the merged fields,
196
+ so a md that supplies `scope` produces an active policy with no other configuration at all.
202
197
  A dispatch that carries neither bindings nor a role md with an `extend`
203
198
  block leaves the extension loaded and inactive — fail open. A md that **exists and declares
204
199
  an `extend` block but cannot be applied** — unreadable file, invalid YAML, `extend` not an
@@ -11,13 +11,6 @@ import { fileURLToPath } from "node:url";
11
11
  /** helper 的名字:找它、报它、文档里写它都用这一个常量。 */
12
12
  const HELPER_NAME = "pi-subagents-extend-helper";
13
13
 
14
- /**
15
- * 找 helper:环境变量优先,其次包装好的 bin/,最后仓内 cargo 产物。
16
- *
17
- * 第三个候选是给「源码 checkout + 软链加载」这种用法的:cargo 建好了但没跑
18
- * `pnpm run build:helper` 把产物拷进 bin/ 时,bash 不该整体失效 —— 这是改名后
19
- * 真实踩到的坑。npm 安装的副本没有 ../helper,那一条自然落空。
20
- */
21
14
  /**
22
15
  * helper 候选路径。纯函数,便于直接钉住候选及其顺序:环境变量不是候选,
23
16
  * 而是覆盖(设了但不存在就不往下找,否则「指错了」会静默用上另一个)。
@@ -12,6 +12,7 @@ import { dependencyGateVerdict } from "../../dependencies.ts";
12
12
  import { expandPath, privatisedDirs, resolveComparable, underRoot } from "../../paths/index.ts";
13
13
  import { buildSpec, detectPnpmStore, describeHelper, dropSpecFile, helperPath, SANDBOX_DEVICE_PATHS, scratchDir, wrapInSandbox, writeSpecFile } from "../../sandbox/index.ts";
14
14
  import type { Wiring } from "../context.ts";
15
+ import { originalCommand } from "./original-args.ts";
15
16
  import { bail, deny, pathToolVerdict, preview, writeBail } from "./paths.ts";
16
17
 
17
18
  /**
@@ -407,7 +408,12 @@ export const judgeToolCall = async ({
407
408
  // 把后一类算进预算,会让一次参数写错就提前判死长任务。
408
409
 
409
410
  if (event.toolName === "bash") {
410
- const command = String((event.input as { command?: unknown })?.command ?? "").trim();
411
+ // pi 的 tool_call 处理器共用可变的 event.input:先注册的处理器改了它,后面的看到的是改过的
412
+ // 值,顺序由加载顺序决定。实测 rtk 把命令换成 `rtk <cmd>`,白名单记的是模型原本那条,于是
413
+ // 整个会话的 bash 全被拒。判定因此用 transcript 里模型原本那条命令(见 original-args.ts),
414
+ // 执行用当前值:同伴的改写留在沙箱内层照常生效。
415
+ const rewritten = String((event.input as { command?: unknown })?.command ?? "").trim();
416
+ const command = originalCommand(ctx, event.toolCallId) ?? rewritten;
411
417
  const rule = w.policy.bash;
412
418
  if (!rule) {
413
419
  return bail(
@@ -541,7 +547,7 @@ export const judgeToolCall = async ({
541
547
  specFile,
542
548
  });
543
549
  (event.input as { command?: string }).command = wrapInSandbox(
544
- command,
550
+ rewritten,
545
551
  specFile,
546
552
  helper,
547
553
  // helper 的「网络已隔离」提示每会话只值一次:本会话还没播报过就照常播报;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * 模型**原始**工具参数:按 toolCallId 从会话 transcript 里取回。
3
+ *
4
+ * 为什么需要:pi 的 tool_call 处理器共用同一个可变的 `event.input`,先注册的处理器改了它,
5
+ * 后面的处理器看到的就是改过的值(pi 文档 extensions.md 的 In-place mutation),而处理器顺序
6
+ * 由扩展的加载顺序决定,不在本扩展手里。实测 rtk(把命令改写成 `rtk <cmd>` 省 token)先跑,
7
+ * 于是判定读到 `rtk git status`,与我们记的 bash.allow 里的 `git status` 永远匹配不上 ——
8
+ * 整个会话的 bash 全被拒,而模型根本没那么写过。
9
+ *
10
+ * transcript 里存的是模型实际输出的 arguments,不受处理器链改写影响,所以判定以它为准;
11
+ * 处理器链上的改写仍然保留,作为被沙箱包住的内层命令执行,两边的意图都不丢。
12
+ */
13
+ interface ToolCallBlock {
14
+ type?: string;
15
+ id?: string;
16
+ arguments?: unknown;
17
+ }
18
+
19
+ const asArguments = (block: ToolCallBlock): Record<string, unknown> | undefined => {
20
+ const raw = block.arguments;
21
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) return raw as Record<string, unknown>;
22
+ // 某些宿主把 arguments 存成 JSON 字符串;解析不出来就当没有,绝不让它变成判定失败。
23
+ if (typeof raw === "string") {
24
+ try {
25
+ const parsed: unknown = JSON.parse(raw);
26
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as Record<string, unknown>) : undefined;
27
+ } catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ return undefined;
32
+ };
33
+
34
+ /**
35
+ * 在 transcript 条目里找 toolCallId 对应的工具调用参数。找不到返回 undefined ——
36
+ * 嵌套调用(`<parent>/<n>`)按定义不落在 transcript 里,调用方要退回 `event.input`。
37
+ */
38
+ export function originalToolArguments(entries: readonly unknown[], toolCallId: string): Record<string, unknown> | undefined {
39
+ if (!toolCallId) return undefined;
40
+ for (let i = entries.length - 1; i >= 0; i -= 1) {
41
+ const entry = entries[i] as { message?: { content?: unknown } } | undefined;
42
+ const content = entry?.message?.content;
43
+ if (!Array.isArray(content)) continue;
44
+ for (const block of content as ToolCallBlock[]) {
45
+ if (block?.type !== "toolCall" || block.id !== toolCallId) continue;
46
+ const args = asArguments(block);
47
+ if (args) return args;
48
+ }
49
+ }
50
+ return undefined;
51
+ }
52
+
53
+ /**
54
+ * 取原始命令字符串:判定 bash 时的入口。宿主没给 sessionManager(测试替身、旧宿主)、
55
+ * transcript 里没有这一条、或者参数里没有 command 时都返回 undefined,调用方退回 event.input。
56
+ */
57
+ export function originalCommand(ctx: unknown, toolCallId: string): string | undefined {
58
+ const sessionManager = (ctx as { sessionManager?: { getBranch?: () => unknown } } | undefined)?.sessionManager;
59
+ const entries = sessionManager?.getBranch?.();
60
+ if (!Array.isArray(entries)) return undefined;
61
+ const args = originalToolArguments(entries, toolCallId);
62
+ const command = args?.command;
63
+ return typeof command === "string" && command.trim() ? command.trim() : undefined;
64
+ }