pi-better-subagents 0.20.1 → 0.21.1

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
@@ -33,16 +33,17 @@ 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
 
40
40
  The user config sets `delegationMode` to `manual`, `adaptive` (default), or
41
41
  `coordinator`. `/subagents settings` (or `/subagents`) opens a settings page
42
- for delegation mode and the concurrent-subagent cap (default 4). Edits apply to
42
+ for delegation mode and the concurrent-subagent cap (default 6). Edits apply to
43
43
  this session and persist across reloads; Ctrl+S saves both as defaults, and
44
44
  Reset to defaults clears
45
- session overrides. `/subagents mode manual|adaptive|coordinator` and
45
+ session overrides. Agents opens the same catalog as `/agents`.
46
+ `/subagents mode manual|adaptive|coordinator` and
46
47
  `/subagents cap <number>` are command equivalents; `/subagents save` persists
47
48
  both. Lowering the cap blocks new single and batch launches, including launches
48
49
  still preparing, without stopping running work. Saved configuration changes are
package/catalog-schema.ts CHANGED
@@ -72,12 +72,13 @@ export const PARSER_LIMITS = {
72
72
  * runtime already uses. Tiers are catalog policy, not benchmark rankings.
73
73
  */
74
74
  export const APPROVED_ROLE_DEFAULTS = [
75
- { id: "role.researcher", name: "Researcher", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
75
+ { id: "role.researcher", name: "Researcher", model: "openai/gpt-6.1-terra", effort: "medium", tier: "balanced" },
76
76
  { id: "role.explorer", name: "Explorer", model: "openai/gpt-6-luna", effort: "medium", tier: "efficient" },
77
77
  { id: "role.product-manager", name: "Product Manager", model: "openai/gpt-6.1-sol", effort: "medium", tier: "balanced" },
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 = {
package/config.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "defaultModel": null,
3
3
  "defaultTools": "read, bash, edit, write, web_search, web_fetch",
4
- "maxConcurrent": 4,
4
+ "maxConcurrent": 6,
5
5
  "delegationMode": "adaptive",
6
6
 
7
7
  "toolExtensions": {
package/config.ts CHANGED
@@ -73,7 +73,7 @@ export interface SubagentConfig extends TimingSettings {
73
73
  }
74
74
 
75
75
  /** Concurrency cap when config.json sets none. */
76
- export const DEFAULT_MAX_CONCURRENT = 4;
76
+ export const DEFAULT_MAX_CONCURRENT = 6;
77
77
 
78
78
  export function isConcurrencyCap(value: unknown): value is number {
79
79
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
@@ -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` six bundled defaults | `/agents list` must show all six role ids |
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` six defaults | not launched (would call gpt-6) |
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 |
@@ -100,18 +100,20 @@ Model availability, same-tier fallback, and nearest-effort adjustment are not de
100
100
 
101
101
  | Role | Stored id | Name | Model | Effort | Tier |
102
102
  | --- | --- | --- | --- | --- | --- |
103
- | `researcher` | `role.researcher` | Researcher | `openai/gpt-6.1-sol` | medium | balanced |
103
+ | `researcher` | `role.researcher` | Researcher | `openai/gpt-6.1-terra` | medium | balanced |
104
104
  | `explorer` | `role.explorer` | Explorer | `openai/gpt-6-luna` | medium | efficient |
105
105
  | `product-manager` | `role.product-manager` | Product Manager | `openai/gpt-6.1-sol` | medium | balanced |
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. Each role's instruction body names excluded work and the neighboring role
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
@@ -19,7 +19,8 @@ Set `delegationMode` in the user config described under
19
19
  `coordinator` (default `adaptive`). This controls foreground delegation guidance,
20
20
  not child permissions or catalog definitions. `/subagents settings` (or simply
21
21
  `/subagents`) opens the terminal settings page with mode and concurrent-subagent
22
- cap controls and Reset to defaults. The page uses the same selected-row and
22
+ cap controls, an Agents shortcut to `/agents`, and Reset to defaults.
23
+ The page uses the same selected-row and
23
24
  active-cell styling as `/sandbox`, with one editable value column.
24
25
  Edits automatically persist for this session, including across reloads; Escape
25
26
  closes the page without undoing them.
@@ -35,7 +36,7 @@ Command equivalents also work outside the terminal UI:
35
36
  /subagents reset
36
37
  ```
37
38
 
38
- The cap defaults to 4 and applies to both single and batch launches. Lowering it
39
+ The cap defaults to 6 and applies to both single and batch launches. Lowering it
39
40
  below the running count leaves existing work untouched and blocks new admissions
40
41
  until capacity becomes available. Slots already reserved by an in-flight launch
41
42
  remain admitted. Settings apply to this parent Pi process, not
@@ -164,7 +165,7 @@ one.
164
165
  |---------|---------|--------------|
165
166
  | 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
167
  | 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 everything, including a tool call that never ends and an orphaned run (child gone, its process group still alive). |
168
+ | 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
169
  | 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
170
 
170
171
  `0` turns a control off. `null` or an omitted value means "inherit": on
@@ -175,10 +176,10 @@ may be fractional. A job's own number (including `0`) wins over `shared`.
175
176
  **Known limits of the deadline hold.**
176
177
 
177
178
  - `max_minutes: 0` turns the ceiling off, and the ceiling is the only control
178
- that bounds a tool call that never ends. With it off, a steer stuck behind a
179
+ that bounds the whole run including a tool call that never ends. A separate
180
+ sandbox command time limit can bound individual commands. With the run ceiling off, a steer stuck behind a
179
181
  hung tool call is never delivered, the deadline stop stays held, and the run
180
- is never stopped. Opt into a ceiling when a command must have a wall-clock
181
- bound.
182
+ is never stopped by that deadline. Opt into a ceiling to bound the whole run.
182
183
  - The parent reads at most the last 32 MiB of a child log after `/reload`. If
183
184
  the log is larger and the running tool call started before that window, the
184
185
  parent cannot see the call, so the hold is lost and grace counts from when
@@ -201,8 +202,8 @@ harness remembers up to 4096 distinct calls per run as fixed-size hashes of the
201
202
  name and normalized arguments; past that the oldest is forgotten, so a call from
202
203
  long ago counts again. Time the child spends waiting on a running tool call does not count toward the
203
204
  stuck window, so a child in the middle of a 20-minute test run is waiting, not
204
- stuck. A command that hangs is bounded only when the caller opts into a deadline
205
- or ceiling.
205
+ stuck. A hanging command can be bounded by the sandbox command time limit; the run
206
+ ceiling separately bounds the whole run.
206
207
  The other stuck signal is the existing escalation: the same operation failing
207
208
  three times wakes the parent once as an `Action required` incident
208
209
  ([failure observations](failure-observations.md)).
@@ -300,7 +301,7 @@ an enabled human profile. Saved enabled profiles and session choices stay enable
300
301
  cache directories when Outside is Read or Read/write. Credential and control
301
302
  denials retain precedence. See the permission details below.
302
303
  - **Tool allowlist.** Confined children admit only verified read/write/edit/bash
303
- implementations, the guarded `apply_patch`, and the trusted tools ticked in
304
+ implementations, guarded `run_application`, the guarded `apply_patch`, and the trusted tools ticked in
304
305
  `/sandbox`. The fixed `process_list` adapter is available with Process access
305
306
  set to Read. Other requested tools are reported as unavailable, with the reason.
306
307
  - **No runaway recursion.** Confined children cannot spawn nested agents.
@@ -350,7 +351,27 @@ Network Off blocks task network access while Pi's provider transport remains
350
351
  available. The confined file worker has an 8 MiB file limit and rejects larger
351
352
  files explicitly; use confined commands for larger files when commands are On.
352
353
 
353
- `read`, `write`, `edit`, and `bash` have verified adapters. Extension tools are
354
+ `read`, `write`, `edit`, `bash`, and `run_application` have guarded adapters.
355
+ With Run applications On and Shell scripts Off, a requested `bash` capability is
356
+ replaced by `run_application`, subject to `exclude_tools`; a read-only tool
357
+ selection does not gain application execution. Direct `run_application` takes
358
+ `executable: string`, `args: string[]`, and optional `timeout: number` and
359
+ spawns without a shell inside the OS sandbox. Shell scripts Off also blocks
360
+ explicit shell-interpreter launches, including aliases. Applications such as
361
+ `pnpm` and `pytest` can still invoke scripts internally, so this is not a ban
362
+ on every descendant shell or a guarantee of termination.
363
+
364
+ The Command time limit is an immutable maximum per command. A smaller requested
365
+ timeout wins; omitting or increasing the request cannot bypass the cap. Cleanup
366
+ covers ordinary process-group descendants, not deliberate daemons. This limit
367
+ is separate from the subagent run ceiling. Shell scripts defaults On and the
368
+ limit defaults to No limit, including for legacy profiles. To opt in, set
369
+ Subagents → Sandbox On, Run applications On, Shell scripts Off, and Command time
370
+ limit to 10 min in `/sandbox`, then press Ctrl+S. New launches capture the policy;
371
+ running children keep theirs. An incompatible older consumer is rejected rather
372
+ than silently dropping these restrictions.
373
+
374
+ Extension tools are
354
375
  chosen in `/sandbox` → Subagents · Tools
355
376
  ([ADR 0009](../../../docs/adr/0009-guarded-and-trusted-subagent-tools.md)):
356
377
 
@@ -461,7 +482,7 @@ The effective config also sets:
461
482
  - `delegationMode` — foreground policy (`manual`, `adaptive`, or `coordinator`;
462
483
  default `adaptive`). `/subagents mode ...` changes only the current session.
463
484
  `/subagents save` saves mode and cap together as config defaults.
464
- - `maxConcurrent` — positive whole-number concurrency cap (**default 4**).
485
+ - `maxConcurrent` — positive whole-number concurrency cap (**default 6**).
465
486
  `/subagents cap <number>` overrides it for this session. Both single and batch
466
487
  admissions respect the cap; existing runs are never stopped by a cap change.
467
488
  Use `/subagents settings` to edit both controls or `/subagents reset` to return
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 { observeSandboxPermissions, resolveSubagentPermissions } from "./permission-policy.ts";
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
- // process_list is installed by the mandatory task guard, not an SDK builtin or extension mapping.
1758
- tools: sandboxEnabled ? allow.split(",").filter((name) => name !== "process_list" && (TASK_BUILTINS as readonly string[]).includes(name)).join(",") : allow,
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, permissions: permissionPlan.permissions,
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
- pi.registerTool(acceptanceSpawnTool);
2027
+ registerSpawnTool(acceptanceSpawnTool);
2003
2028
 
2004
2029
  // ---- subagent_spawn_batch -------------------------------------------
2005
- pi.registerTool({
2030
+ registerSpawnTool({
2006
2031
  name: "subagent_spawn_batch",
2007
2032
  label: "Spawn Subagent Batch",
2008
2033
  description:
@@ -2273,7 +2298,7 @@ export default function (pi: ExtensionAPI) {
2273
2298
  });
2274
2299
  const openSettings = async (ctx: ExtensionCommandContext): Promise<void> => {
2275
2300
  if (ctx.mode === "tui" && ctx.hasUI && typeof ctx.ui.custom === "function") {
2276
- await ctx.ui.custom<void>((tui, theme, _kb, done) => createSubagentSettingsPage(theme, {
2301
+ const next = await ctx.ui.custom<"agents" | undefined>((tui, theme, _kb, done) => createSubagentSettingsPage(theme, {
2277
2302
  get: () => {
2278
2303
  const settings = effectiveSettings();
2279
2304
  return {
@@ -2285,7 +2310,10 @@ export default function (pi: ExtensionAPI) {
2285
2310
  };
2286
2311
  },
2287
2312
  changeMode, changeCap, save: saveSettings, reset: resetSettings,
2288
- }, () => { refreshBackgroundWorkNavigator(ctx); tui.requestRender(); }, () => done()));
2313
+ // Close this page first; the catalog opens after ui.custom resolves.
2314
+ openAgents: () => done("agents"),
2315
+ }, () => { refreshBackgroundWorkNavigator(ctx); tui.requestRender(); }, () => done(undefined)));
2316
+ if (next === "agents") await agentOperations.openCatalog(ctx);
2289
2317
  } else {
2290
2318
  ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. Use /subagents mode <mode> or /subagents cap <number>; /subagents save persists both.`, "info");
2291
2319
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.20.1",
3
+ "version": "0.21.1",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -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
+ }
@@ -5,7 +5,7 @@ id: role.researcher
5
5
  name: Researcher
6
6
  description: Owns external-source evidence and factual uncertainty; excludes repo mapping and changes.
7
7
  defaults:
8
- model: openai/gpt-6.1-sol
8
+ model: openai/gpt-6.1-terra
9
9
  effort: medium
10
10
  tier: balanced
11
11
  ---
@@ -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/settings-page.ts CHANGED
@@ -18,9 +18,11 @@ export interface SubagentSettingsHandlers {
18
18
  changeCap(cap: number): void;
19
19
  save(): { ok: boolean; message: string };
20
20
  reset(): void;
21
+ /** Opens the same catalog as `/agents`. The caller closes this page first. */
22
+ openAgents?(): void;
21
23
  }
22
24
 
23
- const labels = ["Delegation mode", "Concurrent subagents", "Reset to defaults"];
25
+ const labels = ["Delegation mode", "Concurrent subagents", "Agents", "Reset to defaults"];
24
26
 
25
27
  function cell(text: string, width: number): string {
26
28
  const clipped = Tui.truncateToWidth(text, width, "");
@@ -57,6 +59,8 @@ export function createSubagentSettingsPage(
57
59
  input.handleInput("\x05");
58
60
  input.focused = focused;
59
61
  report("");
62
+ } else if (row === 2) {
63
+ handlers.openAgents?.();
60
64
  } else {
61
65
  handlers.reset();
62
66
  report("Session settings reset to saved defaults.");
@@ -118,7 +122,7 @@ export function createSubagentSettingsPage(
118
122
  const lines: string[] = [theme.fg("accent", theme.bold(" Subagent settings")), ""];
119
123
  labels.forEach((label, index) => {
120
124
  const selected = index === row;
121
- if (index === 2) lines.push("");
125
+ if (index === labels.length - 1) lines.push("");
122
126
  const title = theme.fg(selected ? "accent" : "text", marker(selected) + label);
123
127
  if (index >= 2) {
124
128
  lines.push(highlight(title, selected));