pi-better-subagents 0.20.1 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/catalog-schema.ts +1 -0
- package/docs/agent-catalog-acceptance.md +2 -2
- package/docs/agent-catalog.md +3 -1
- package/docs/usage.md +28 -8
- package/index.ts +32 -7
- package/package.json +1 -1
- package/permission-policy.ts +132 -1
- package/roles/role.writer.md +12 -0
- package/shared-sandbox-core.ts +92 -0
- package/shared-task-application.ts +185 -0
- package/shared-task-exec.ts +315 -0
- package/shared-task-sandbox.ts +28 -94
- package/shared-task-tools.ts +1 -1
- package/task-guard.ts +9 -3
- package/task-policy.ts +90 -7
package/README.md
CHANGED
|
@@ -33,7 +33,7 @@ pi -e npm:pi-better-subagents
|
|
|
33
33
|
|
|
34
34
|
Sandboxing starts Off for fresh settings, including standalone subagents without published settings. Explicit saved profiles and session choices remain unchanged. Set `sandbox:true` for a confined launch; `sandbox:false` cannot bypass a human-enabled Subagents profile.
|
|
35
35
|
|
|
36
|
-
Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or newer. `/sandbox` controls the independent Subagents profile, which each launch freezes. Pi handles its own startup, authentication, and provider connection; task tools obey the selected file, command, and network permissions. Outside project defaults to Write: tasks write across home and temp but can remove files outside the workspace only in temp, hidden home directories, and worktree folders (Linux keeps ordinary home folders read-only instead). Confined children admit `read`, `write`, `edit`, and `bash`, the guarded `apply_patch` (Codex patches that follow the file rules), and the trusted tools ticked in `/sandbox` → Subagents · Tools (default `web_fetch` and `web_search`), which run outside the file rules. Other requested tools are reported as unavailable, with the reason. See [usage notes](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md#write-sandbox) for the runtime boundary and supported configurations.
|
|
36
|
+
Linux confinement requires a usable `bubblewrap` backend and Pi SDK 0.82.1 or newer. `/sandbox` controls the independent Subagents profile, which each launch freezes. Pi handles its own startup, authentication, and provider connection; task tools obey the selected file, command, and network permissions. Outside project defaults to Write: tasks write across home and temp but can remove files outside the workspace only in temp, hidden home directories, and worktree folders (Linux keeps ordinary home folders read-only instead). Confined children admit `read`, `write`, `edit`, and policy-permitted `bash` or guarded `run_application`, the guarded `apply_patch` (Codex patches that follow the file rules), and the trusted tools ticked in `/sandbox` → Subagents · Tools (default `web_fetch` and `web_search`), which run outside the file rules. Other requested tools are reported as unavailable, with the reason. For direct applications without shell scripts, set Subagents → Sandbox On, Run applications On, Shell scripts Off, and Command time limit to 10 min in `/sandbox`, then press Ctrl+S. This is an explicit choice, not the default. New launches capture the policy; running children keep theirs. See [usage notes](https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md#write-sandbox) for the runtime boundary and supported configurations.
|
|
37
37
|
|
|
38
38
|
## Delegation Modes
|
|
39
39
|
|
package/catalog-schema.ts
CHANGED
|
@@ -78,6 +78,7 @@ export const APPROVED_ROLE_DEFAULTS = [
|
|
|
78
78
|
{ id: "role.developer", name: "Developer", model: "openai/gpt-6.1-sol", effort: "high", tier: "balanced" },
|
|
79
79
|
{ id: "role.reviewer", name: "Reviewer", model: "openai/gpt-6-astra", effort: "medium", tier: "frontier" },
|
|
80
80
|
{ id: "role.architect", name: "Architect", model: "openai/gpt-6-astra", effort: "high", tier: "frontier" },
|
|
81
|
+
{ id: "role.writer", name: "Writer", model: "openai/gpt-6.1-terra", effort: "medium", tier: undefined },
|
|
81
82
|
] as const;
|
|
82
83
|
|
|
83
84
|
export const DiagnosticCodes = {
|
|
@@ -29,13 +29,13 @@ Without `PI_CATALOG_REAL_PI=1` the test skips and default `npm test` does not ca
|
|
|
29
29
|
|
|
30
30
|
| ID | Executable-path tests (not coordinator reasoning) | Real Pi in this harness |
|
|
31
31
|
| --- | --- | --- |
|
|
32
|
-
| T01 | `catalog.test.mjs`
|
|
32
|
+
| T01 | `catalog.test.mjs` bundled defaults | `/agents list` must show all bundled role ids |
|
|
33
33
|
| T02 | `catalog.test.mjs` two agents, role unchanged | one personal create; not a second independent agent |
|
|
34
34
|
| T03 | `catalog-lifecycle.test.mjs` navigator detail fields | `catalog-navigator-live-row.acceptance.test.mjs`: same-parent running row for `Live Row Agent` |
|
|
35
35
|
| T04 | `catalog-identity.test.mjs` concurrent numeric labels | one fresh registry numeric label; not a second process |
|
|
36
36
|
| T05 | identity + lifecycle alias collision | one `developer-checkout` label; collision suffix not repeated |
|
|
37
37
|
| T06 | lifecycle repeated runs / rename snapshot | not re-run here |
|
|
38
|
-
| T07 | `model-resolution.test.mjs`
|
|
38
|
+
| T07 | `model-resolution.test.mjs` bundled defaults | not launched (would call gpt-6) |
|
|
39
39
|
| T08 | model-resolution precedence | not a separate real launch |
|
|
40
40
|
| T09 | model-resolution same-tier | real role `role.acceptance-same-tier` if the coordinator omits model |
|
|
41
41
|
| T10 | model-resolution foreground | real role `role.acceptance-foreground` if the coordinator omits model |
|
package/docs/agent-catalog.md
CHANGED
|
@@ -106,12 +106,14 @@ Model availability, same-tier fallback, and nearest-effort adjustment are not de
|
|
|
106
106
|
| `developer` | `role.developer` | Developer | `openai/gpt-6.1-sol` | high | balanced |
|
|
107
107
|
| `reviewer` | `role.reviewer` | Reviewer | `openai/gpt-6-astra` | medium | frontier |
|
|
108
108
|
| `architect` | `role.architect` | Architect | `openai/gpt-6-astra` | high | frontier |
|
|
109
|
+
| `writer` | `role.writer` | Writer | `openai/gpt-6.1-terra` | medium | unset |
|
|
109
110
|
|
|
110
111
|
Bundled descriptions are routing boundaries for coordinator mode. Researcher owns
|
|
111
112
|
external and documentary evidence; Explorer maps repository code paths; Product
|
|
112
113
|
Manager owns user-visible requirements; Architect owns technical boundaries;
|
|
113
114
|
Developer owns implementation and focused tests; Reviewer owns independent change
|
|
114
|
-
review
|
|
115
|
+
review; Writer owns drafting, editing, and polishing written content. Writer has
|
|
116
|
+
no configured fallback tier. Each role's instruction body names excluded work and the neighboring role
|
|
115
117
|
that owns it. Project and personal definitions may replace these bundled roles, so
|
|
116
118
|
coordinators inspect the current effective descriptions rather than assuming this
|
|
117
119
|
table is unchanged.
|
package/docs/usage.md
CHANGED
|
@@ -164,7 +164,7 @@ one.
|
|
|
164
164
|
|---------|---------|--------------|
|
|
165
165
|
| Soft deadline (`deadline_minutes`) | Off | When configured, the child gets one steering message (delivered through Pi's steer queue after its current tool call finishes): stop starting new work, commit or save what is done, and report what is complete, what is not, and where the work is. The parent gets one wake saying so. |
|
|
166
166
|
| Grace (`grace_minutes`) | 5 | Grace starts when the steering message actually reaches the child, which is after its current tool call. While the message is still waiting behind a running tool call, the deadline stop is held, so a test run that began just before the deadline is not killed mid-run. If the child has not finished by the end of grace, the harness stops it; the ordinary completion callback reports `killed; stopped: deadline`. A child that completes inside grace is not stopped; its surfaces say `deadline: finished in grace`. |
|
|
167
|
-
| Hard ceiling (`max_minutes`) | Off | When configured, the run is stopped at once, without grace or a steer, and reported as `stopped: ceiling`. The ceiling bounds
|
|
167
|
+
| Hard ceiling (`max_minutes`) | Off | When configured, the run is stopped at once, without grace or a steer, and reported as `stopped: ceiling`. The ceiling bounds the run, including a tool call that never ends and an orphaned run (child gone, its process group still alive). |
|
|
168
168
|
| Stuck window (`stuck_minutes`) | 10 | No progress (see below) for this long wakes the parent once (`stuck`). It never stops the run. After new progress, a later stuck spell wakes again. |
|
|
169
169
|
|
|
170
170
|
`0` turns a control off. `null` or an omitted value means "inherit": on
|
|
@@ -175,10 +175,10 @@ may be fractional. A job's own number (including `0`) wins over `shared`.
|
|
|
175
175
|
**Known limits of the deadline hold.**
|
|
176
176
|
|
|
177
177
|
- `max_minutes: 0` turns the ceiling off, and the ceiling is the only control
|
|
178
|
-
that bounds a tool call that never ends.
|
|
178
|
+
that bounds the whole run including a tool call that never ends. A separate
|
|
179
|
+
sandbox command time limit can bound individual commands. With the run ceiling off, a steer stuck behind a
|
|
179
180
|
hung tool call is never delivered, the deadline stop stays held, and the run
|
|
180
|
-
is never stopped. Opt into a ceiling
|
|
181
|
-
bound.
|
|
181
|
+
is never stopped by that deadline. Opt into a ceiling to bound the whole run.
|
|
182
182
|
- The parent reads at most the last 32 MiB of a child log after `/reload`. If
|
|
183
183
|
the log is larger and the running tool call started before that window, the
|
|
184
184
|
parent cannot see the call, so the hold is lost and grace counts from when
|
|
@@ -201,8 +201,8 @@ harness remembers up to 4096 distinct calls per run as fixed-size hashes of the
|
|
|
201
201
|
name and normalized arguments; past that the oldest is forgotten, so a call from
|
|
202
202
|
long ago counts again. Time the child spends waiting on a running tool call does not count toward the
|
|
203
203
|
stuck window, so a child in the middle of a 20-minute test run is waiting, not
|
|
204
|
-
stuck. A command
|
|
205
|
-
|
|
204
|
+
stuck. A hanging command can be bounded by the sandbox command time limit; the run
|
|
205
|
+
ceiling separately bounds the whole run.
|
|
206
206
|
The other stuck signal is the existing escalation: the same operation failing
|
|
207
207
|
three times wakes the parent once as an `Action required` incident
|
|
208
208
|
([failure observations](failure-observations.md)).
|
|
@@ -300,7 +300,7 @@ an enabled human profile. Saved enabled profiles and session choices stay enable
|
|
|
300
300
|
cache directories when Outside is Read or Read/write. Credential and control
|
|
301
301
|
denials retain precedence. See the permission details below.
|
|
302
302
|
- **Tool allowlist.** Confined children admit only verified read/write/edit/bash
|
|
303
|
-
implementations, the guarded `apply_patch`, and the trusted tools ticked in
|
|
303
|
+
implementations, guarded `run_application`, the guarded `apply_patch`, and the trusted tools ticked in
|
|
304
304
|
`/sandbox`. The fixed `process_list` adapter is available with Process access
|
|
305
305
|
set to Read. Other requested tools are reported as unavailable, with the reason.
|
|
306
306
|
- **No runaway recursion.** Confined children cannot spawn nested agents.
|
|
@@ -350,7 +350,27 @@ Network Off blocks task network access while Pi's provider transport remains
|
|
|
350
350
|
available. The confined file worker has an 8 MiB file limit and rejects larger
|
|
351
351
|
files explicitly; use confined commands for larger files when commands are On.
|
|
352
352
|
|
|
353
|
-
`read`, `write`, `edit`, and `
|
|
353
|
+
`read`, `write`, `edit`, `bash`, and `run_application` have guarded adapters.
|
|
354
|
+
With Run applications On and Shell scripts Off, a requested `bash` capability is
|
|
355
|
+
replaced by `run_application`, subject to `exclude_tools`; a read-only tool
|
|
356
|
+
selection does not gain application execution. Direct `run_application` takes
|
|
357
|
+
`executable: string`, `args: string[]`, and optional `timeout: number` and
|
|
358
|
+
spawns without a shell inside the OS sandbox. Shell scripts Off also blocks
|
|
359
|
+
explicit shell-interpreter launches, including aliases. Applications such as
|
|
360
|
+
`pnpm` and `pytest` can still invoke scripts internally, so this is not a ban
|
|
361
|
+
on every descendant shell or a guarantee of termination.
|
|
362
|
+
|
|
363
|
+
The Command time limit is an immutable maximum per command. A smaller requested
|
|
364
|
+
timeout wins; omitting or increasing the request cannot bypass the cap. Cleanup
|
|
365
|
+
covers ordinary process-group descendants, not deliberate daemons. This limit
|
|
366
|
+
is separate from the subagent run ceiling. Shell scripts defaults On and the
|
|
367
|
+
limit defaults to No limit, including for legacy profiles. To opt in, set
|
|
368
|
+
Subagents → Sandbox On, Run applications On, Shell scripts Off, and Command time
|
|
369
|
+
limit to 10 min in `/sandbox`, then press Ctrl+S. New launches capture the policy;
|
|
370
|
+
running children keep theirs. An incompatible older consumer is rejected rather
|
|
371
|
+
than silently dropping these restrictions.
|
|
372
|
+
|
|
373
|
+
Extension tools are
|
|
354
374
|
chosen in `/sandbox` → Subagents · Tools
|
|
355
375
|
([ADR 0009](../../../docs/adr/0009-guarded-and-trusted-subagent-tools.md)):
|
|
356
376
|
|
package/index.ts
CHANGED
|
@@ -57,11 +57,13 @@ import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
|
|
|
57
57
|
import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
|
|
58
58
|
import { appendExecutionPolicy } from "./shared-execution-policy.ts";
|
|
59
59
|
import { resolveExtensions, extensionArgs } from "./extensions.ts";
|
|
60
|
-
import { prepareTaskRuntime } from "./task-policy.ts";
|
|
60
|
+
import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
|
|
61
61
|
import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
|
|
62
62
|
import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
|
|
63
63
|
import { APPLY_PATCH, describeTaskTools, planTaskTools } from "./subagent-tools.ts";
|
|
64
|
-
import {
|
|
64
|
+
import {
|
|
65
|
+
announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
|
|
66
|
+
} from "./permission-policy.ts";
|
|
65
67
|
import { resolveSubagentWorkspace } from "./git-workspace.ts";
|
|
66
68
|
import { join } from "node:path";
|
|
67
69
|
import {
|
|
@@ -1559,6 +1561,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
1559
1561
|
ensureSubagentProvider();
|
|
1560
1562
|
registerSubagentsGoalProvider(pi);
|
|
1561
1563
|
observeSandboxPermissions(pi);
|
|
1564
|
+
// Record admission identities during registration: inventory actions are not
|
|
1565
|
+
// available while extensions load. A later replacement must fail the identity check.
|
|
1566
|
+
const registeredSpawnSchemas = new Map<string, object>();
|
|
1567
|
+
const registerSpawnTool: ExtensionAPI["registerTool"] = (definition) => {
|
|
1568
|
+
registeredSpawnSchemas.set(definition.name, definition.parameters);
|
|
1569
|
+
pi.registerTool(definition);
|
|
1570
|
+
};
|
|
1571
|
+
announceExecutionAdapter(pi, {
|
|
1572
|
+
parametersFor: (name) => registeredSpawnSchemas.get(name),
|
|
1573
|
+
runApplication: (TASK_BUILTINS as readonly string[]).includes(RUN_APPLICATION),
|
|
1574
|
+
});
|
|
1562
1575
|
let acceptanceResultToolRef: { execute: (toolCallId: string, params: { id: string }) => Promise<unknown> } | undefined;
|
|
1563
1576
|
function publishAcceptanceHooks(tool?: NonNullable<typeof acceptanceResultToolRef>): void {
|
|
1564
1577
|
if (process.env.PI_CATALOG_ACCEPTANCE_PROBE !== "1") return;
|
|
@@ -1746,6 +1759,16 @@ export default function (pi: ExtensionAPI) {
|
|
|
1746
1759
|
if (sandboxEnabled && p.tools === undefined && permissionPlan.permissions?.processAccess === "read") {
|
|
1747
1760
|
allow = [...new Set([...allow.split(","), "process_list"])].join(",");
|
|
1748
1761
|
}
|
|
1762
|
+
// Shell Off confines the child to directly launched applications: a requested bash
|
|
1763
|
+
// becomes the guarded run_application builtin. Exclusions stay exclusions (an excluded
|
|
1764
|
+
// run_application leaves bash out rather than restoring it), and a read-only loadout
|
|
1765
|
+
// keeps no command capability at all.
|
|
1766
|
+
const commandSettings = resolveCommandSettings(permissionPlan.permissions);
|
|
1767
|
+
if (sandboxEnabled && !commandSettings.shell) {
|
|
1768
|
+
allow = applyDirectApplicationLoadout(allow.split(",").filter(Boolean), {
|
|
1769
|
+
shell: false, excluded: requestedExcludes,
|
|
1770
|
+
}).tools.join(",");
|
|
1771
|
+
}
|
|
1749
1772
|
const taskTools = sandboxEnabled ? planTaskTools({
|
|
1750
1773
|
requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
|
|
1751
1774
|
settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
|
|
@@ -1754,8 +1777,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
1754
1777
|
toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
|
|
1755
1778
|
}) : undefined;
|
|
1756
1779
|
const resolution = resolveExtensions({
|
|
1757
|
-
//
|
|
1758
|
-
|
|
1780
|
+
// Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
|
|
1781
|
+
// are task builtins that the mandatory guard installs and activates itself.
|
|
1782
|
+
tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
|
|
1759
1783
|
model, clean, allowNested: sandboxEnabled ? false : p.allow_nested, config: cfg,
|
|
1760
1784
|
});
|
|
1761
1785
|
const { args: resolvedExtArgs, missing } = extensionArgs(resolution, resolveExtensionPath);
|
|
@@ -1803,7 +1827,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
1803
1827
|
}
|
|
1804
1828
|
const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
|
|
1805
1829
|
root: requestedSandboxDir, controlDir: join(runDir(id), "control"), piBin,
|
|
1806
|
-
tools: selectedTools,
|
|
1830
|
+
tools: selectedTools,
|
|
1831
|
+
permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
|
|
1807
1832
|
applyPatch: taskTools?.applyPatch === true,
|
|
1808
1833
|
extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
|
|
1809
1834
|
extensionPaths: extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
|
|
@@ -1999,10 +2024,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
1999
2024
|
},
|
|
2000
2025
|
};
|
|
2001
2026
|
acceptanceSpawnToolRef = acceptanceSpawnTool;
|
|
2002
|
-
|
|
2027
|
+
registerSpawnTool(acceptanceSpawnTool);
|
|
2003
2028
|
|
|
2004
2029
|
// ---- subagent_spawn_batch -------------------------------------------
|
|
2005
|
-
|
|
2030
|
+
registerSpawnTool({
|
|
2006
2031
|
name: "subagent_spawn_batch",
|
|
2007
2032
|
label: "Spawn Subagent Batch",
|
|
2008
2033
|
description:
|
package/package.json
CHANGED
package/permission-policy.ts
CHANGED
|
@@ -5,15 +5,55 @@ export const SANDBOX_POLICY_REQUEST_CHANNEL = "pi-better-sandbox:policy-request"
|
|
|
5
5
|
|
|
6
6
|
type Access = "off" | "read" | "write" | "read-write";
|
|
7
7
|
type CredentialAccess = "off" | "read" | "read-write";
|
|
8
|
+
|
|
9
|
+
/** Largest single-command cap a timer can hold: 2_147_483 seconds is 2_147_483_000 ms. */
|
|
10
|
+
export const MAX_COMMAND_TIMEOUT_SECONDS = 2_147_483;
|
|
11
|
+
|
|
12
|
+
/** A positive finite number of seconds no larger than {@link MAX_COMMAND_TIMEOUT_SECONDS}. */
|
|
13
|
+
export function isCommandTimeoutSeconds(value: unknown): value is number {
|
|
14
|
+
return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= MAX_COMMAND_TIMEOUT_SECONDS;
|
|
15
|
+
}
|
|
16
|
+
|
|
8
17
|
export type PermissionProfile = Readonly<{
|
|
9
18
|
enabled: boolean;
|
|
10
19
|
projectFiles: Access;
|
|
11
20
|
outsideProject: Access;
|
|
12
21
|
storedCredentials: CredentialAccess;
|
|
22
|
+
/** Master switch for task command execution. */
|
|
13
23
|
commands: boolean;
|
|
14
24
|
network: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Optional refinement of `commands`: may a task command be interpreted by a
|
|
27
|
+
* shell? Absent means yes (the historical behavior). Off confines a task to
|
|
28
|
+
* directly launched applications through the guarded run_application tool.
|
|
29
|
+
*/
|
|
30
|
+
shell?: boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Optional outer cap for one task command, in seconds. Absent or null means
|
|
33
|
+
* no cap; a value is validated here and copied into the immutable child policy.
|
|
34
|
+
*/
|
|
35
|
+
commandTimeoutSeconds?: number | null;
|
|
15
36
|
processAccess?: "off" | "read";
|
|
16
37
|
}>;
|
|
38
|
+
|
|
39
|
+
/** The resolved command switches a launch uses: absent settings take their documented default. */
|
|
40
|
+
export type CommandSettings = Readonly<{ shell: boolean; commandTimeoutSeconds: number | null }>;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Resolve the optional command switches. Absent `shell` is On (the historical
|
|
44
|
+
* behavior); an absent or null cap means no cap. Invalid values never reach
|
|
45
|
+
* here: the bus snapshot validator refuses them first.
|
|
46
|
+
*/
|
|
47
|
+
export function resolveCommandSettings(
|
|
48
|
+
permissions: { shell?: boolean; commandTimeoutSeconds?: number | null } | undefined,
|
|
49
|
+
): CommandSettings {
|
|
50
|
+
return Object.freeze({
|
|
51
|
+
shell: permissions?.shell !== false,
|
|
52
|
+
commandTimeoutSeconds: isCommandTimeoutSeconds(permissions?.commandTimeoutSeconds)
|
|
53
|
+
? permissions.commandTimeoutSeconds
|
|
54
|
+
: null,
|
|
55
|
+
});
|
|
56
|
+
}
|
|
17
57
|
export type PermissionSnapshot = Readonly<{
|
|
18
58
|
permissions?: PermissionProfile;
|
|
19
59
|
subagentPermissions?: PermissionProfile;
|
|
@@ -40,13 +80,18 @@ function profile(value: unknown): PermissionProfile {
|
|
|
40
80
|
const access = (v: unknown): v is Access => credential(v) || v === "write";
|
|
41
81
|
if (typeof p.enabled !== "boolean" || typeof p.commands !== "boolean" || typeof p.network !== "boolean" ||
|
|
42
82
|
!access(p.projectFiles) || !access(p.outsideProject) || !credential(p.storedCredentials) ||
|
|
43
|
-
(p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read")
|
|
83
|
+
(p.processAccess !== undefined && p.processAccess !== "off" && p.processAccess !== "read") ||
|
|
84
|
+
(p.shell !== undefined && typeof p.shell !== "boolean") ||
|
|
85
|
+
(p.commandTimeoutSeconds !== undefined && p.commandTimeoutSeconds !== null && !isCommandTimeoutSeconds(p.commandTimeoutSeconds))) {
|
|
44
86
|
throw new Error("Invalid sandbox permission profile; update permissions in the sandbox UI.");
|
|
45
87
|
}
|
|
88
|
+
// Copy only what the publisher sent: absent optional settings keep their default meaning.
|
|
46
89
|
return Object.freeze({
|
|
47
90
|
enabled: p.enabled, commands: p.commands, network: p.network,
|
|
48
91
|
projectFiles: p.projectFiles, outsideProject: p.outsideProject, storedCredentials: p.storedCredentials,
|
|
49
92
|
...(p.processAccess === undefined ? {} : { processAccess: p.processAccess }),
|
|
93
|
+
...(p.shell === undefined ? {} : { shell: p.shell }),
|
|
94
|
+
...(p.commandTimeoutSeconds === undefined ? {} : { commandTimeoutSeconds: p.commandTimeoutSeconds }),
|
|
50
95
|
});
|
|
51
96
|
}
|
|
52
97
|
|
|
@@ -113,3 +158,89 @@ export function resolveSubagentPermissions(pi: unknown, requestedSandbox: boolea
|
|
|
113
158
|
const { enabled: _enabled, ...permissions } = child;
|
|
114
159
|
return { sandboxEnabled: true, enforced: true, permissions, tools };
|
|
115
160
|
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Consumer capability handshake for the shell / direct-application / time controls.
|
|
164
|
+
*
|
|
165
|
+
* The producer (`pi-better-sandbox`) publishes `shell` and
|
|
166
|
+
* `commandTimeoutSeconds` in the Subagents permission profile. A consumer that
|
|
167
|
+
* predates this contract silently ignores both: a `shell:false` profile would
|
|
168
|
+
* still hand the child a shell, and a cap would never be applied. So the producer
|
|
169
|
+
* emits `pi-better-subagents:execution-adapter-request` before it admits a
|
|
170
|
+
* subagent launch under either setting, and refuses the launch when this package
|
|
171
|
+
* does not answer.
|
|
172
|
+
*
|
|
173
|
+
* Request payload: `{ version: 1, name: "subagent_spawn" | "subagent_spawn_batch", reply(value) }`.
|
|
174
|
+
* Reply: `{ version: 1, parameters }` where `parameters` is the exact object
|
|
175
|
+
* registered for that tool, so the producer binds admission to this package's own
|
|
176
|
+
* registration rather than to a copied schema. The reply is the whole wire
|
|
177
|
+
* contract: the producer reads nothing else from this package, so no descriptor
|
|
178
|
+
* or status event is published here.
|
|
179
|
+
*
|
|
180
|
+
* The event bus establishes compatibility, not authentication: the producer still
|
|
181
|
+
* checks the tool's host-owned source, as it does for background admission.
|
|
182
|
+
*/
|
|
183
|
+
export const EXECUTION_ADAPTER_REQUEST_CHANNEL = "pi-better-subagents:execution-adapter-request";
|
|
184
|
+
export const EXECUTION_ADAPTER_VERSION = 1;
|
|
185
|
+
|
|
186
|
+
export type ExecutionAdapterRequest = Readonly<{
|
|
187
|
+
version?: unknown;
|
|
188
|
+
name?: unknown;
|
|
189
|
+
reply?: (value: unknown) => void;
|
|
190
|
+
}>;
|
|
191
|
+
|
|
192
|
+
type ExecutionAdapterInstallation = { shutdown(): void };
|
|
193
|
+
|
|
194
|
+
/** One live installation per bus: `shutdown` is both the reload and the session end. */
|
|
195
|
+
const installations = new WeakMap<EventBus, ExecutionAdapterInstallation>();
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Answer the producer's admission request for one of this package's own tools.
|
|
199
|
+
*
|
|
200
|
+
* Each call replaces the previous installation on the same bus, so a reload or a
|
|
201
|
+
* second factory registration serves the newest schema snapshot instead of the
|
|
202
|
+
* one captured by whichever load happened to run first. `session_shutdown`
|
|
203
|
+
* removes the answer, so a closed session leaves no compatibility proof behind
|
|
204
|
+
* for the next one.
|
|
205
|
+
*/
|
|
206
|
+
export function announceExecutionAdapter(pi: unknown, options: {
|
|
207
|
+
/** Exact registered `parameters` object for a tool this package registers, if any. */
|
|
208
|
+
parametersFor: (name: string) => object | undefined;
|
|
209
|
+
/** The guarded run_application builtin is installed for confined children. */
|
|
210
|
+
runApplication: boolean;
|
|
211
|
+
}): void {
|
|
212
|
+
const bus = busOf(pi);
|
|
213
|
+
if (!bus) return;
|
|
214
|
+
installations.get(bus)?.shutdown();
|
|
215
|
+
const { parametersFor } = options;
|
|
216
|
+
// The producer asks only while Shell scripts is Off or a command time limit is
|
|
217
|
+
// set. Without the guarded direct-application builtin this package cannot honor
|
|
218
|
+
// Shell scripts Off, so it proves no compatibility rather than letting the
|
|
219
|
+
// producer drop the restriction (ADR 0019: reject, never silently drop).
|
|
220
|
+
const answerable = options.runApplication === true;
|
|
221
|
+
const unsubscribe: unknown = bus.on(EXECUTION_ADAPTER_REQUEST_CHANNEL, (data) => {
|
|
222
|
+
if (!answerable) return;
|
|
223
|
+
const request = (data ?? {}) as ExecutionAdapterRequest;
|
|
224
|
+
if (request.version !== EXECUTION_ADAPTER_VERSION || typeof request.name !== "string" ||
|
|
225
|
+
typeof request.reply !== "function") return;
|
|
226
|
+
const parameters = parametersFor(request.name);
|
|
227
|
+
// No reply for a tool this package does not register: the launch stays refused.
|
|
228
|
+
if (parameters) request.reply(Object.freeze({ version: EXECUTION_ADAPTER_VERSION, parameters }));
|
|
229
|
+
});
|
|
230
|
+
let active = true;
|
|
231
|
+
const installation: ExecutionAdapterInstallation = {
|
|
232
|
+
shutdown() {
|
|
233
|
+
if (!active) return;
|
|
234
|
+
active = false;
|
|
235
|
+
// A newer installation has already replaced this one; leave it in place.
|
|
236
|
+
if (installations.get(bus) === installation) installations.delete(bus);
|
|
237
|
+
if (typeof unsubscribe === "function") (unsubscribe as () => void)();
|
|
238
|
+
},
|
|
239
|
+
};
|
|
240
|
+
installations.set(bus, installation);
|
|
241
|
+
// `pi.on` is absent in narrow fixtures that only carry an event bus.
|
|
242
|
+
const onLifecycle = (pi as { on?: unknown } | null | undefined)?.on;
|
|
243
|
+
if (typeof onLifecycle === "function") {
|
|
244
|
+
(onLifecycle as (event: string, handler: () => void) => unknown).call(pi, "session_shutdown", installation.shutdown);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
---
|
|
2
|
+
schema: pi-agent/v1
|
|
3
|
+
kind: role
|
|
4
|
+
id: role.writer
|
|
5
|
+
name: Writer
|
|
6
|
+
description: Owns drafting, editing, and polishing written content; excludes product policy and production code.
|
|
7
|
+
defaults:
|
|
8
|
+
model: openai/gpt-6.1-terra
|
|
9
|
+
effort: medium
|
|
10
|
+
---
|
|
11
|
+
Draft, edit, and polish written content for the requested audience and purpose. Follow the supplied brief, source material, terminology, and applicable writing guidance. Preserve facts, figures, citations, and constraints; flag missing evidence instead of inventing it.
|
|
12
|
+
Do not define product policy or implement production code. Route product decisions to Product Manager, missing external evidence to Researcher, and code changes to Developer. This role does not change tools, sandbox, or controls selected at launch.
|
package/shared-sandbox-core.ts
CHANGED
|
@@ -58,7 +58,16 @@ export type SandboxPermissions = {
|
|
|
58
58
|
projectFiles: SandboxFileAccess;
|
|
59
59
|
outsideProject: SandboxFileAccess;
|
|
60
60
|
storedCredentials: "off" | "read" | "read-write";
|
|
61
|
+
/** Run applications: the master switch for command execution (bash and run_application). */
|
|
61
62
|
commands: boolean;
|
|
63
|
+
/** Shell scripts inside commands; omitted (legacy) profiles keep shell execution On. */
|
|
64
|
+
shell?: boolean;
|
|
65
|
+
/**
|
|
66
|
+
* Cap for every command path, in seconds. The effective timeout is
|
|
67
|
+
* `min(requested, cap)`, and the cap applies when the caller omits a timeout.
|
|
68
|
+
* Omitted or null means no limit. Must be positive, finite and <= 2147483.
|
|
69
|
+
*/
|
|
70
|
+
commandTimeoutSeconds?: number | null;
|
|
62
71
|
network: boolean;
|
|
63
72
|
/** Fixed process_list adapter only; omitted legacy profiles keep it Off. */
|
|
64
73
|
processAccess?: "off" | "read";
|
|
@@ -103,6 +112,89 @@ export type SandboxTarget = {
|
|
|
103
112
|
execArgs: readonly string[];
|
|
104
113
|
};
|
|
105
114
|
|
|
115
|
+
export const SHELL_EXECUTABLE_NAMES = Object.freeze([
|
|
116
|
+
"sh", "bash", "zsh", "dash", "ksh", "ksh93", "mksh", "pdksh", "ash", "csh", "tcsh", "fish",
|
|
117
|
+
"yash", "posh", "rbash", "busybox", "pwsh", "powershell", "cmd",
|
|
118
|
+
] as const);
|
|
119
|
+
|
|
120
|
+
// Fixed runtime code starts after confinement. The launch data is JSON, never
|
|
121
|
+
// env/shell syntax. Native execve never falls back to a command interpreter.
|
|
122
|
+
const APPLICATION_RUNNER = `
|
|
123
|
+
const fs = require("node:fs");
|
|
124
|
+
const path = require("node:path");
|
|
125
|
+
const spec = JSON.parse(process.argv[1]);
|
|
126
|
+
function resolveExecutable(executable) {
|
|
127
|
+
if (executable.includes(path.sep)) return path.resolve(executable);
|
|
128
|
+
const directories = (spec.env.PATH || spec.env.Path || "").split(path.delimiter);
|
|
129
|
+
const resolved = directories.map(directory => path.resolve(directory || ".", executable)).find(candidate => {
|
|
130
|
+
try { fs.accessSync(candidate, fs.constants.X_OK); return fs.statSync(candidate).isFile(); }
|
|
131
|
+
catch { return false; }
|
|
132
|
+
});
|
|
133
|
+
if (!resolved) throw new Error("Executable not found: " + executable);
|
|
134
|
+
return resolved;
|
|
135
|
+
}
|
|
136
|
+
function isShellInterpreter(interpreter) {
|
|
137
|
+
const canonical = fs.realpathSync(interpreter);
|
|
138
|
+
if (spec.shellNames.includes(path.basename(interpreter)) || spec.shellNames.includes(path.basename(canonical))) return true;
|
|
139
|
+
const target = fs.statSync(canonical, { bigint: true });
|
|
140
|
+
const directories = new Set(["/bin", "/usr/bin", ...(spec.env.PATH || spec.env.Path || "").split(path.delimiter)]);
|
|
141
|
+
for (const directory of directories) for (const name of spec.shellNames) {
|
|
142
|
+
try {
|
|
143
|
+
const known = fs.statSync(path.resolve(directory || ".", name), { bigint: true });
|
|
144
|
+
if (target.dev === known.dev && target.ino === known.ino) return true;
|
|
145
|
+
} catch { /* A shell need not exist in every executable directory. */ }
|
|
146
|
+
}
|
|
147
|
+
return false;
|
|
148
|
+
}
|
|
149
|
+
function verifyExecutable(executable, depth = 0) {
|
|
150
|
+
if (depth > 4) throw new Error("Too many shebang interpreters.");
|
|
151
|
+
fs.accessSync(executable, fs.constants.X_OK);
|
|
152
|
+
const fd = fs.openSync(executable, "r");
|
|
153
|
+
const header = Buffer.alloc(4096);
|
|
154
|
+
let size;
|
|
155
|
+
try { size = fs.readSync(fd, header, 0, header.length, 0); }
|
|
156
|
+
finally { fs.closeSync(fd); }
|
|
157
|
+
const magic = size >= 4 ? header.readUInt32BE(0) : 0;
|
|
158
|
+
const binary = [0x7f454c46, 0xfeedface, 0xcefaedfe, 0xfeedfacf, 0xcffaedfe,
|
|
159
|
+
0xcafebabe, 0xbebafeca, 0xcafebabf, 0xbfbafeca].includes(magic);
|
|
160
|
+
const script = size >= 2 && header[0] === 35 && header[1] === 33;
|
|
161
|
+
if (!binary && !script) throw new Error("Executable has no supported binary format or shebang; shell fallback is disabled.");
|
|
162
|
+
if (!spec.shell && script) {
|
|
163
|
+
const words = header.subarray(2, size).toString("utf8").split(/\\r?\\n/, 1)[0].trim().split(/\\s+/);
|
|
164
|
+
let interpreter = resolveExecutable(words[0]);
|
|
165
|
+
if (path.basename(fs.realpathSync(interpreter)) === "env") {
|
|
166
|
+
if (words.length !== 2 || words[1].startsWith("-") || words[1].includes("=")) {
|
|
167
|
+
throw new Error("Sandbox: Shell scripts are Off; an env shebang must name one direct interpreter without options.");
|
|
168
|
+
}
|
|
169
|
+
interpreter = resolveExecutable(words[1]);
|
|
170
|
+
}
|
|
171
|
+
if (isShellInterpreter(interpreter)) {
|
|
172
|
+
throw new Error("Sandbox: Shell scripts are Off; the executable uses a shell shebang.");
|
|
173
|
+
}
|
|
174
|
+
verifyExecutable(interpreter, depth + 1);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
try {
|
|
178
|
+
if (typeof process.execve !== "function") {
|
|
179
|
+
throw new Error("Direct application execution requires Node.js with process.execve (22.15+ or 24+). Update Node.js; no shell fallback was run.");
|
|
180
|
+
}
|
|
181
|
+
const executable = resolveExecutable(spec.executable);
|
|
182
|
+
verifyExecutable(executable);
|
|
183
|
+
process.execve(executable, [executable, ...spec.args], spec.env);
|
|
184
|
+
} catch (error) {
|
|
185
|
+
console.error(error.code === "ENOEXEC" ? "Executable format is unsupported; shell fallback is disabled." : error.message);
|
|
186
|
+
process.exitCode = 126;
|
|
187
|
+
}
|
|
188
|
+
`;
|
|
189
|
+
|
|
190
|
+
/** Fixed post-boundary launcher for literal argv, without env assignment or shell fallback. */
|
|
191
|
+
export function directApplicationTarget(
|
|
192
|
+
executable: string, args: readonly string[], env: NodeJS.ProcessEnv, shell: boolean,
|
|
193
|
+
): SandboxTarget {
|
|
194
|
+
return { execPath: canonicalizePath(process.execPath), execArgs: ["--eval", APPLICATION_RUNNER,
|
|
195
|
+
JSON.stringify({ executable, args, env, shell, shellNames: SHELL_EXECUTABLE_NAMES })] };
|
|
196
|
+
}
|
|
197
|
+
|
|
106
198
|
export type SandboxCommandArgs = SandboxTarget & {
|
|
107
199
|
/** Where the macOS backend writes its generated SBPL profile. */
|
|
108
200
|
profilePath: string;
|