pi-better-subagents 0.20.0 → 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 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/agent-commands.ts CHANGED
@@ -87,7 +87,7 @@ export interface AgentCommandUi {
87
87
  editor(title: string, prefill?: string): Promise<string | undefined>;
88
88
  notify(message: string, type?: "info" | "warning" | "error"): void;
89
89
  setWidget?(key: string, content: string[] | undefined): void;
90
- custom?<T>(factory: (tui: { requestRender(): void }, theme: { fg(color: string, text: string): string }, keybindings: unknown, done: (value: T) => void) => unknown, options?: { overlay: boolean }): Promise<T>;
90
+ custom?<T>(factory: (tui: { requestRender(): void }, theme: { fg(color: string, text: string): string }, keybindings: unknown, done: (value: T) => void) => unknown, options?: { overlay: boolean; overlayOptions?: import("@earendil-works/pi-tui").OverlayOptions }): Promise<T>;
91
91
  }
92
92
 
93
93
  export interface AgentCommandHost {
@@ -724,6 +724,7 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
724
724
  const entries = catalog ?? { entries: [view!], diagnostics: commandResult.diagnostics, revision: "", text: "" };
725
725
  try {
726
726
  host.ui.setWidget?.("agents-catalog", undefined);
727
+ let viewportHeight = 30;
727
728
  await host.ui.custom<void>((tui, theme, _keys, done) =>
728
729
  createCatalogComponent(entries, theme, () => tui.requestRender(), () => done(), view?.id, deps.sessionSettings ? {
729
730
  get: () => presentCatalog(readCatalog(location(host, deps)), deps.enrich),
@@ -740,7 +741,13 @@ async function finishInspection(host: AgentCommandHost, commandResult: AgentComm
740
741
  }
741
742
  return { ok: saved.ok, message: saved.ok ? `Defaults saved (${saved.scope}): ${id}.` : saved.diagnostics.map((item) => item.message).join(" ") };
742
743
  },
743
- } : undefined), { overlay: true });
744
+ } : undefined, () => viewportHeight), {
745
+ overlay: true,
746
+ overlayOptions: {
747
+ anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0,
748
+ visible: (_width, height) => { viewportHeight = height; return true; },
749
+ },
750
+ });
744
751
  if (deps.sessionSettings) {
745
752
  const current = readCatalog(location(host, deps));
746
753
  const refreshed = view ? presentCatalogEntry(current, view.id, deps.enrich) : presentCatalog(current, deps.enrich);
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 = {
package/catalog-ui.ts CHANGED
@@ -34,16 +34,18 @@ function cell(value: string, width: number): string {
34
34
 
35
35
  export function catalogColumns(entry: OperationView | null, width: number): string {
36
36
  const available = Math.max(1, width - 2);
37
- const sourceWidth = available >= 70 ? 11 : 0;
38
- const stateWidth = available >= 48 ? 10 : 0;
39
- const gaps = (sourceWidth ? 2 : 0) + (stateWidth ? 2 : 0) + 2;
40
- const modelWidth = Math.min(Math.max(1, available - gaps - 1), Math.min(28, Math.max(20, Math.floor(available * 0.3))));
41
- const nameWidth = Math.max(1, available - modelWidth - sourceWidth - stateWidth - gaps);
37
+ const sourceWidth = available >= 82 ? 11 : 0;
38
+ const stateWidth = available >= 60 ? 10 : 0;
39
+ const effortWidth = available >= 32 ? 7 : 0;
40
+ const gaps = (sourceWidth ? 2 : 0) + (stateWidth ? 2 : 0) + (effortWidth ? 2 : 0) + 2;
41
+ const modelWidth = Math.min(Math.max(1, available - gaps - effortWidth - sourceWidth - stateWidth - 1), Math.min(28, Math.max(20, Math.floor(available * 0.3))));
42
+ const nameWidth = Math.max(1, available - modelWidth - effortWidth - sourceWidth - stateWidth - gaps);
42
43
  const name = entry ? entry.identity.name || entry.id : "NAME";
43
44
  const model = entry ? modelLabel(entry) : "MODEL";
44
45
  const source = entry ? entry.identity.scope ?? "unknown" : "SOURCE";
45
46
  const status = entry ? stateLabel(entry) : "STATE";
46
- return [cell(name, nameWidth), cell(model, modelWidth), ...(sourceWidth ? [cell(source, sourceWidth)] : []), ...(stateWidth ? [cell(status, stateWidth)] : [])].join(" ").trimEnd();
47
+ const effort = entry ? entry.actualEffort ?? entry.fields?.effort.value ?? "(unset)" : "EFFORT";
48
+ return [cell(name, nameWidth), cell(model, modelWidth), ...(effortWidth ? [cell(effort, effortWidth)] : []), ...(sourceWidth ? [cell(source, sourceWidth)] : []), ...(stateWidth ? [cell(status, stateWidth)] : [])].join(" ").trimEnd();
47
49
  }
48
50
 
49
51
  function wrapLine(text: string, width: number): string[] {
@@ -60,7 +62,7 @@ function wrapLine(text: string, width: number): string[] {
60
62
  return rows;
61
63
  }
62
64
 
63
- export function catalogDetailLines(entry: OperationView): string[] {
65
+ export function catalogDetailLines(entry: OperationView, editable = false): string[] {
64
66
  const lines = [
65
67
  `${entry.identity.name || entry.id} · ${entry.identity.kind ?? "unknown"}`,
66
68
  entry.id,
@@ -73,8 +75,7 @@ export function catalogDetailLines(entry: OperationView): string[] {
73
75
  "",
74
76
  "Configuration",
75
77
  ...(entry.fields ? [
76
- fieldLine("Model", entry.fields.model),
77
- fieldLine("Effort", entry.fields.effort),
78
+ ...(!editable ? [fieldLine("Model", entry.fields.model), fieldLine("Effort", entry.fields.effort)] : []),
78
79
  fieldLine("Tier", entry.fields.tier),
79
80
  ] : []),
80
81
  `Actual ${entry.actualModel ?? "not resolved"}${entry.actualEffort ? ` · ${entry.actualEffort}` : ""}`,
@@ -95,9 +96,10 @@ export function createCatalogComponent(
95
96
  close: () => void,
96
97
  initialId?: string,
97
98
  editor?: CatalogEditor,
99
+ getHeight: () => number = () => 30,
98
100
  ) {
99
101
  let selectedId = initialId ?? catalog.entries[0]?.id;
100
- let mode: "list" | "detail" | "prompt" | "settings" = initialId ? "detail" : "list";
102
+ let mode: "list" | "detail" | "prompt" = initialId ? "detail" : "list";
101
103
  let query = "";
102
104
  let scroll = 0;
103
105
  let settingRow = 0;
@@ -159,7 +161,7 @@ export function createCatalogComponent(
159
161
  const selected = () => filtered().find((entry) => entry.id === selectedId);
160
162
  const detailRows = (entry: OperationView, width: number) => (mode === "prompt"
161
163
  ? [`${entry.identity.name || entry.id} · effective instructions`, "", ...(entry.instructions?.split("\n") ?? ["(none)"])]
162
- : catalogDetailLines(entry))
164
+ : catalogDetailLines(entry, !!editor))
163
165
  .flatMap((text) => text ? wrapLine(text, Math.max(1, width - 2)) : [""]);
164
166
  let lastDetailWidth = 80;
165
167
 
@@ -168,21 +170,32 @@ export function createCatalogComponent(
168
170
  set focused(value: boolean) { focused = value; search.focused = value && !!picker && pickerKey === "model"; },
169
171
  render(width: number): string[] {
170
172
  const safeWidth = Math.max(1, width);
173
+ const height = Math.max(1, Math.floor(getHeight()));
174
+ const footerRows = (editor && mode !== "prompt" ? 2 : 0) + (message ? 2 : 0);
175
+ const diagnosticRows = Math.min(catalog.diagnostics.length, 3);
176
+ const listSize = Math.max(1, height - 5 - footerRows - diagnosticRows - 1);
177
+ const controlRows = editor && mode === "detail" ? (safeWidth < 42 ? 5 : 3) : 0;
178
+ const detailSize = Math.max(1, height - 5 - footerRows - controlRows);
179
+ const fit = (lines: string[]) => {
180
+ const result = lines.slice(0, height).map(line);
181
+ while (result.length < height) result.push("");
182
+ return result;
183
+ };
171
184
  lastDetailWidth = safeWidth;
172
185
  const line = (text: string) => truncateToWidth(text, safeWidth);
173
186
  const rows = filtered();
174
187
  const current = selected();
175
188
  const detailLines = current ? detailRows(current, safeWidth) : [];
176
189
  const selectedIndex = rows.findIndex((entry) => entry.id === selectedId);
177
- const start = Math.max(0, Math.min(selectedIndex - 6, rows.length - 14));
178
- if (picker) return [
190
+ const start = Math.max(0, Math.min(selectedIndex - Math.floor(listSize / 2), rows.length - listSize));
191
+ scroll = Math.max(0, Math.min(scroll, detailLines.length - detailSize));
192
+ if (picker) return fit([
179
193
  theme.fg("accent", `Agents / ${pickerKey}`), "",
180
194
  ...(pickerKey === "model" ? search.render(safeWidth) : []),
181
195
  ...picker.render(safeWidth),
182
196
  ...(message ? [theme.fg(error ? "error" : "muted", message)] : []),
183
- ].map(line);
184
- const lines = mode === "settings" && current ? [
185
- theme.fg("accent", `Agents / ${current.identity.name || current.id}`), "",
197
+ ]);
198
+ const controls = editor && mode === "detail" && current ? [
186
199
  ...["Model", "Effort"].flatMap((label, index) => {
187
200
  const key = index === 0 ? "model" : "effort";
188
201
  const field = current.fields?.[key];
@@ -194,38 +207,41 @@ export function createCatalogComponent(
194
207
  const text = `${settingRow === index ? "> " : " "}${label.padEnd(18)} ${value}`;
195
208
  if (safeWidth < 42) {
196
209
  const title = `${settingRow === index ? "> " : " "}${label}`;
197
- return [settingRow === index ? highlight(title, safeWidth) : title, ...wrapLine(value, Math.max(1, safeWidth - 2)).map((line) => ` ${line}`)];
210
+ return [settingRow === index ? highlight(title, safeWidth) : title, ` ${truncateToWidth(value, Math.max(1, safeWidth - 2))}`];
198
211
  }
199
212
  return [settingRow === index ? highlight(text, safeWidth) : text];
200
213
  }),
201
- ] : mode !== "list" && current ? [
202
- theme.fg("accent", mode === "prompt" ? "Agents / prompt" : "Agents / inspect"),
203
- theme.fg("dim", mode === "prompt" ? "← details · ↑↓ scroll · Esc close" : `${editor ? "e settings · " : ""}p prompt · ← list · ↑↓ scroll · Esc close`),
204
214
  "",
205
- ...detailLines.slice(scroll, scroll + 22).map((text, i) =>
215
+ ] : [];
216
+ const lines = mode !== "list" && current ? [
217
+ theme.fg("accent", mode === "prompt" ? "Agents / prompt" : editor ? `Agents / ${current.identity.name || current.id}` : "Agents / inspect"),
218
+ theme.fg("dim", mode === "prompt" ? "← details · ↑↓ scroll · Esc back" : `${editor ? "Enter change · " : ""}p prompt · ← list · ↑↓ ${editor ? "select / scroll" : "scroll"} · Esc back`),
219
+ "",
220
+ ...controls,
221
+ ...detailLines.slice(scroll, scroll + detailSize).map((text, i) =>
206
222
  i === 0 && scroll === 0 ? theme.fg("accent", text) : text),
207
223
  "",
208
- theme.fg("dim", `Showing ${scroll + 1}-${Math.min(scroll + 22, detailLines.length)} of ${detailLines.length} lines`),
224
+ theme.fg("dim", `Showing ${scroll + 1}-${Math.min(scroll + detailSize, detailLines.length)} of ${detailLines.length} lines`),
209
225
  ] : [
210
226
  theme.fg("accent", `Agents · ${catalog.entries.length} definitions`),
211
227
  theme.fg("dim", "Type to filter · ↑↓ select · Enter inspect · Esc close"),
212
228
  `Search ${query || "(all roles and agents)"}`,
213
229
  "",
214
230
  theme.fg("dim", ` ${catalogColumns(null, safeWidth)}`),
215
- ...rows.slice(start, start + 14).map((entry) => {
231
+ ...rows.slice(start, start + listSize).map((entry) => {
216
232
  const active = selectedId === entry.id;
217
233
  const marker = active ? "›" : " ";
218
234
  const text = `${marker} ${catalogColumns(entry, safeWidth)}`;
219
235
  return active ? highlight(text, safeWidth) : text;
220
236
  }),
221
237
  ...(rows.length === 0 ? [" No matching definitions"] : []),
222
- ...(rows.length > 14 ? [theme.fg("dim", ` ${start + 1}-${Math.min(start + 14, rows.length)} of ${rows.length}`)] : []),
238
+ ...(rows.length > listSize ? [theme.fg("dim", ` ${start + 1}-${Math.min(start + listSize, rows.length)} of ${rows.length}`)] : []),
223
239
  ...catalog.diagnostics.slice(0, 2).map((diagnostic) => theme.fg("warning", `! ${diagnostic.message}`)),
224
240
  ...(catalog.diagnostics.length > 2 ? [theme.fg("warning", `! ${catalog.diagnostics.length - 2} more catalog diagnostics`)] : []),
225
241
  ];
226
- if (editor && mode !== "prompt") lines.push("", theme.fg("dim", mode === "settings" ? "Up/Down Select · Enter Change · ctrl+s Save defaults · Esc Back" : "ctrl+s Save selected defaults"));
242
+ if (editor && mode !== "prompt") lines.push("", theme.fg("dim", "ctrl+s Save selected defaults"));
227
243
  if (message) lines.push("", theme.fg(error ? "error" : "muted", message));
228
- return lines.map(line);
244
+ return fit(lines);
229
245
  },
230
246
  handleInput(data: string): void {
231
247
  const rows = filtered();
@@ -239,25 +255,26 @@ export function createCatalogComponent(
239
255
  }
240
256
  if (editor && matchesKey(data, "ctrl+s")) { save(); return; }
241
257
  if (matchesKey(data, "escape") || matchesKey(data, "left")) {
242
- if (mode === "prompt" || mode === "settings") { mode = "detail"; scroll = 0; }
258
+ if (mode === "prompt") { mode = "detail"; scroll = 0; }
243
259
  else if (mode === "detail") { mode = "list"; scroll = 0; }
244
260
  else if (query) { query = ""; selectedId = catalog.entries[0]?.id; }
245
261
  else { close(); return; }
246
262
  } else if (matchesKey(data, "up") || matchesKey(data, "down")) {
247
263
  const delta = matchesKey(data, "down") ? 1 : -1;
248
- if (mode === "settings") settingRow = Math.max(0, Math.min(1, settingRow + delta));
264
+ if (mode === "detail" && editor && scroll === 0 && (delta < 0 || settingRow === 0)) settingRow = Math.max(0, Math.min(1, settingRow + delta));
249
265
  else if (mode !== "list" && selected()) scroll = Math.max(0, Math.min(detailRows(selected()!, lastDetailWidth).length - 1, scroll + delta));
250
266
  else if (rows.length) selectedId = rows[Math.max(0, Math.min(rows.length - 1, rows.findIndex((entry) => entry.id === selectedId) + delta))]?.id;
251
267
  } else if (matchesKey(data, "enter") && mode === "list" && selected()) {
252
268
  mode = "detail";
269
+ settingRow = 0;
253
270
  scroll = 0;
254
271
  } else if ((data === "p" || data === "P") && mode === "detail" && selected()) {
255
272
  mode = "prompt";
256
273
  scroll = 0;
257
274
  } else if (editor && (data === "e" || data === "E") && mode === "detail" && selected()) {
258
- mode = "settings";
259
275
  settingRow = 0;
260
- } else if (mode === "settings" && (matchesKey(data, "enter") || data === " ")) {
276
+ scroll = 0;
277
+ } else if (editor && mode === "detail" && (matchesKey(data, "enter") || data === " ")) {
261
278
  try { edit(); } catch (cause) { report(cause instanceof Error ? cause.message : String(cause), true); }
262
279
  } else if (mode === "list" && matchesKey(data, "backspace")) {
263
280
  query = query.slice(0, -1);
@@ -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 |
@@ -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. 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
@@ -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 everything, including a tool call that never ends and an orphaned run (child gone, its process group still alive). |
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. With it off, a steer stuck behind a
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 when a command must have a wall-clock
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 that hangs is bounded only when the caller opts into a deadline
205
- or ceiling.
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 `bash` have verified adapters. Extension tools are
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 { 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:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
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
+ }
@@ -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.