pi-better-subagents 0.27.2 → 0.28.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/index.ts CHANGED
@@ -62,12 +62,12 @@ import { resolveExtensions, extensionArgs } from "./extensions.ts";
62
62
  import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
63
63
  import { canonicalizePath, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
64
64
  import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
65
- import { APPLY_PATCH, describeTaskTools, planTaskTools } from "./subagent-tools.ts";
65
+ import { APPLY_PATCH, describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
66
66
  import {
67
67
  announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
68
68
  } from "./permission-policy.ts";
69
69
  import { resolveSubagentWorkspace } from "./git-workspace.ts";
70
- import { dirname, join } from "node:path";
70
+ import { dirname, isAbsolute, join } from "node:path";
71
71
  import {
72
72
  baseDir,
73
73
  taskWorkspaceDir,
@@ -164,6 +164,16 @@ import {
164
164
  } from "./continuation.ts";
165
165
  import { createHash } from "node:crypto";
166
166
  import { assertThinkingLevel, parseModelThinking, type ThinkingLevel } from "./thinking.ts";
167
+ import {
168
+ absolutizeSkillPaths,
169
+ configuredSkillExposure,
170
+ describeSkillExposure,
171
+ normalizeSkillExposure,
172
+ resolveSkillExposure,
173
+ skillLaunchArgs,
174
+ type SkillExposureMode,
175
+ } from "./skills.ts";
176
+ import type { DiscoveredSkill } from "./skill-picker.ts";
167
177
  import { createAgentOperations } from "./agent-operations.ts";
168
178
  import { createAgentSessionSettings } from "./agent-session-settings.ts";
169
179
  import {
@@ -209,6 +219,7 @@ import {
209
219
  type WorkerOperationsHost,
210
220
  } from "./worker-waits.ts";
211
221
  import { defaultUserRoot, type CatalogSnapshot } from "./catalog-store.ts";
222
+ import { restrictContextFilesToWorktree } from "./shared-worktree-context.ts";
212
223
 
213
224
  const SUBAGENT_MODE_ACTIONS: readonly AutocompleteItem[] = [
214
225
  { value: "settings", label: "settings", description: "Open delegation mode and concurrency settings" },
@@ -1827,6 +1838,31 @@ function sameLaunchTools(left: unknown, right: string): boolean {
1827
1838
  return typeof left === "string" && normalizeTools(left) === normalizeTools(right);
1828
1839
  }
1829
1840
 
1841
+ /**
1842
+ * A continuation may repeat its launch's skill exposure, and only that. The
1843
+ * saved paths are absolute (frozen at launch), so a caller repeating relative
1844
+ * paths is compared against the recipe's own workspace.
1845
+ *
1846
+ * Discovery and `[]` are different choices and must never compare equal: a
1847
+ * recipe with no `skills` key means "the child discovers the user catalog", and
1848
+ * an explicit `[]` means "load no skills at all". Treating an absent key as an
1849
+ * empty list would accept a continuation that silently disables discovery for a
1850
+ * conversation that was launched with it.
1851
+ */
1852
+ function sameLaunchSkills(value: unknown, recipe: ContinuationPlan["recipe"]): boolean {
1853
+ let requested: string[] | undefined;
1854
+ try {
1855
+ requested = normalizeSkillExposure(value, "skills");
1856
+ } catch {
1857
+ return false;
1858
+ }
1859
+ if (requested === undefined) return false;
1860
+ const saved = recipe.skills;
1861
+ if (saved === undefined) return false;
1862
+ const resolved = requested.length === 0 ? [] : absolutizeSkillPaths(requested, recipe.cwd);
1863
+ return resolved.length === saved.length && resolved.every((path, index) => path === saved[index]);
1864
+ }
1865
+
1830
1866
  function sameLaunchRoles(left: unknown, right: string | readonly string[] | undefined): boolean {
1831
1867
  if (typeof left === "string") return left === right;
1832
1868
  if (Array.isArray(left) && Array.isArray(right)) {
@@ -1851,6 +1887,7 @@ function continuationLaunchConflicts(
1851
1887
  check("alias", (value) => value === recipe.alias);
1852
1888
  check("tools", (value) => sameLaunchTools(value, recipe.tools));
1853
1889
  check("exclude_tools", (value) => typeof value === "string" && normalizeTools(value) === normalizeTools(recipe.excludeTools ?? ""));
1890
+ check("skills", (value) => sameLaunchSkills(value, recipe));
1854
1891
  check("clean", (value) => value === recipe.clean);
1855
1892
  check("sandbox", (value) => value === recipe.sandbox);
1856
1893
  check("sandbox_dir", (value) => sameLaunchPath(value, recipe.sandboxDir));
@@ -1942,12 +1979,86 @@ function catalogRoleSchema(purpose: string) {
1942
1979
  ], { description: `${one} ${many}` }));
1943
1980
  }
1944
1981
 
1982
+ /** Loaded Pi skill metadata from the current prompt resources. No model call, no directory scan. */
1983
+ function discoveredSkillsFromContext(ctx: { getSystemPromptOptions?: () => { skills?: readonly unknown[] } }): DiscoveredSkill[] {
1984
+ try {
1985
+ const loaded = ctx.getSystemPromptOptions?.().skills ?? [];
1986
+ const skills: DiscoveredSkill[] = [];
1987
+ for (const raw of loaded) {
1988
+ if (!raw || typeof raw !== "object") continue;
1989
+ const skill = raw as {
1990
+ name?: unknown; description?: unknown; filePath?: unknown; baseDir?: unknown;
1991
+ sourceInfo?: { source?: unknown };
1992
+ };
1993
+ if (typeof skill.name !== "string" || !skill.name || typeof skill.filePath !== "string" || !skill.filePath) continue;
1994
+ skills.push({
1995
+ name: skill.name,
1996
+ description: typeof skill.description === "string" ? skill.description : "",
1997
+ path: skill.filePath,
1998
+ ...(typeof skill.baseDir === "string" ? { baseDir: skill.baseDir } : {}),
1999
+ ...(typeof skill.sourceInfo?.source === "string" ? { source: skill.sourceInfo.source } : {}),
2000
+ });
2001
+ }
2002
+ return skills;
2003
+ } catch {
2004
+ return [];
2005
+ }
2006
+ }
2007
+
1945
2008
  export default function (pi: ExtensionAPI) {
2009
+ // A standalone Subagents install has no Harness extension, so the parent
2010
+ // session applies the same linked-worktree project boundary as its children.
2011
+ pi.on("before_agent_start", (event) => {
2012
+ restrictContextFilesToWorktree(event.systemPromptOptions, PiCodingAgent.getAgentDir());
2013
+ });
1946
2014
  initializeNavigatorPanels(pi);
1947
2015
  const agentSessionSettings = createAgentSessionSettings(pi);
1948
2016
  let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
1949
2017
  let delegationOverride: DelegationMode | undefined;
1950
2018
  let capOverride: number | undefined;
2019
+ interface SkillSelection { mode: SkillExposureMode; paths: string[] }
2020
+ let skillsOverride: SkillSelection | undefined;
2021
+ const savedSkills = (): SkillSelection & { source: "config" | "default"; error?: string } => {
2022
+ try {
2023
+ return configuredSkillExposure(loadConfig().defaultSkills);
2024
+ } catch (error) {
2025
+ return {
2026
+ mode: "inherit", paths: [], source: "config",
2027
+ error: error instanceof Error ? error.message : String(error),
2028
+ };
2029
+ }
2030
+ };
2031
+ const activeSkills = (): SkillSelection & { source: "session" | "config" | "default"; error?: string } => {
2032
+ if (skillsOverride) return { ...skillsOverride, source: "session" };
2033
+ return savedSkills();
2034
+ };
2035
+ /** The same active default a launch sees, shaped for catalog inspection. */
2036
+ const readSkillDefaults = () => {
2037
+ const skills = activeSkills();
2038
+ const value = skills.mode === "inherit" ? undefined : [...skills.paths];
2039
+ const error = skills.error ?? (skills.mode === "explicit" && skills.paths.length === 0
2040
+ ? "Selected skills has no paths. Add at least one skill path or choose No skill catalog."
2041
+ : undefined);
2042
+ return { value, source: skills.source, ...(error ? { error } : {}) };
2043
+ };
2044
+ const changeSkills = (mode: SkillExposureMode, paths: readonly string[]): void => {
2045
+ if (mode !== "explicit" && paths.length > 0) throw new Error("Only Selected skills carries a path list.");
2046
+ if (mode === "explicit" && paths.some((path) => !isAbsolute(path))) {
2047
+ throw new Error("Enter absolute skill paths so every child resolves the same files.");
2048
+ }
2049
+ const next = { mode, paths: [...paths] };
2050
+ skillsOverride = next;
2051
+ pi.appendEntry("pi-better-subagents-skills", { version: 1, ...next });
2052
+ };
2053
+ /** The current-session choice, with `{}` preserving explicit discovery. */
2054
+ const sessionSkillChoice = (): { value?: unknown } | undefined => {
2055
+ if (!skillsOverride) return undefined;
2056
+ if (skillsOverride.mode === "explicit" && skillsOverride.paths.length === 0) {
2057
+ throw new Error("Selected skills has no paths. Add at least one skill path or choose No skill catalog before launching.");
2058
+ }
2059
+ if (skillsOverride.mode === "inherit") return {};
2060
+ return { value: skillsOverride.mode === "none" ? [] : [...skillsOverride.paths] };
2061
+ };
1951
2062
  const activeConcurrencyCap = (): number => capOverride ?? normalizeConcurrencyCap(loadConfig().maxConcurrent);
1952
2063
  const changeCap = (cap: number): void => {
1953
2064
  if (!isConcurrencyCap(cap)) throw new Error("Concurrent subagents must be a positive whole number.");
@@ -1961,8 +2072,10 @@ export default function (pi: ExtensionAPI) {
1961
2072
  const resetSettings = (): void => {
1962
2073
  capOverride = undefined;
1963
2074
  delegationOverride = undefined;
2075
+ skillsOverride = undefined;
1964
2076
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
1965
2077
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2078
+ pi.appendEntry("pi-better-subagents-skills", { version: 1, mode: null });
1966
2079
  };
1967
2080
  const activeDelegationMode = (): DelegationMode => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
1968
2081
  const countRunning = () =>
@@ -1996,7 +2109,30 @@ export default function (pi: ExtensionAPI) {
1996
2109
  }, countRunning(), getSharedCapacityGate(countRunning).pending);
1997
2110
  const saveSettings = (): { ok: boolean; message: string } => {
1998
2111
  try {
1999
- writeSubagentSettings({ delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap() });
2112
+ const skills = activeSkills();
2113
+ if (!skillsOverride && skills.error) {
2114
+ return {
2115
+ ok: false,
2116
+ message: `Cannot save subagent defaults: the saved defaultSkills value is invalid (${skills.error}). ` +
2117
+ `Choose a skill mode in this session to replace it, or fix the saved config first.`,
2118
+ };
2119
+ }
2120
+ if (skills.mode === "explicit" && skills.paths.length === 0) {
2121
+ return { ok: false, message: "Add at least one skill path, or choose No skill catalog to load none." };
2122
+ }
2123
+ // Saving mode and cap must not write a skill key into a config that
2124
+ // never had one. Discovery only replaces a saved choice when a saved
2125
+ // skill value already exists.
2126
+ const savedSkillValue = loadConfig().defaultSkills;
2127
+ const hasSavedSkillChoice = savedSkillValue !== undefined && savedSkillValue !== null;
2128
+ writeSubagentSettings({
2129
+ delegationMode: activeDelegationMode(),
2130
+ maxConcurrent: activeConcurrencyCap(),
2131
+ ...(skills.mode === "inherit" && !hasSavedSkillChoice ? {} : {
2132
+ // null is an explicit discovery choice; it must override a saved path list.
2133
+ defaultSkills: skills.mode === "inherit" ? null : [...skills.paths],
2134
+ }),
2135
+ });
2000
2136
  resetSettings();
2001
2137
  return { ok: true, message: "Subagent defaults saved." };
2002
2138
  } catch (error) {
@@ -2025,6 +2161,7 @@ export default function (pi: ExtensionAPI) {
2025
2161
  const restoreDelegationMode = (ctx: ExtensionContext): void => {
2026
2162
  delegationOverride = undefined;
2027
2163
  capOverride = undefined;
2164
+ skillsOverride = undefined;
2028
2165
  const branch = ctx.sessionManager?.getBranch?.();
2029
2166
  if (!Array.isArray(branch)) return;
2030
2167
  for (const entry of branch) {
@@ -2035,6 +2172,19 @@ export default function (pi: ExtensionAPI) {
2035
2172
  else if (isConcurrencyCap(data.maxConcurrent)) capOverride = data.maxConcurrent;
2036
2173
  }
2037
2174
  }
2175
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-skills") {
2176
+ const data = entry.data as { version?: unknown; mode?: unknown; paths?: unknown } | null;
2177
+ if (data?.version !== 1) continue;
2178
+ if (data.mode === null) {
2179
+ skillsOverride = undefined;
2180
+ } else if ((data.mode === "inherit" || data.mode === "none") && Array.isArray(data.paths) && data.paths.length === 0) {
2181
+ skillsOverride = { mode: data.mode, paths: [] };
2182
+ } else if (data.mode === "explicit" && Array.isArray(data.paths)
2183
+ && data.paths.every((path): path is string => typeof path === "string" && isAbsolute(path))) {
2184
+ skillsOverride = { mode: "explicit", paths: [...data.paths] };
2185
+ }
2186
+ continue;
2187
+ }
2038
2188
  if (entry.type !== "custom" || entry.customType !== "pi-better-subagents-delegation") continue;
2039
2189
  const data = entry.data as { version?: unknown; mode?: unknown } | null;
2040
2190
  if (data?.version !== 1) continue;
@@ -2141,6 +2291,8 @@ export default function (pi: ExtensionAPI) {
2141
2291
  type SpawnParams = {
2142
2292
  prompt: string; name?: string; model?: string; thinking?: ThinkingLevel; tools?: string;
2143
2293
  exclude_tools?: string; clean?: boolean; sandbox?: boolean;
2294
+ /** Skill exposure for this launch; omit to inherit catalog/config/discovery. */
2295
+ skills?: readonly string[];
2144
2296
  sandbox_dir?: string; callback?: boolean; cwd?: string;
2145
2297
  git_clone_workspace?: boolean; approve?: boolean; allow_nested?: boolean;
2146
2298
  agent?: string; role?: string | readonly string[]; alias?: string;
@@ -2207,6 +2359,11 @@ export default function (pi: ExtensionAPI) {
2207
2359
  modelNote?: string;
2208
2360
  }> {
2209
2361
  assertThinkingLevel(p.thinking);
2362
+ // Skill exposure is a caller choice, not a launch: validate its shape
2363
+ // before any attempt directory or capacity effect exists. A continuation
2364
+ // validates too, so a malformed repeat is a shape error rather than being
2365
+ // reported as a recipe conflict.
2366
+ normalizeSkillExposure(p.skills, "skills");
2210
2367
  // A conversation parked on an observed wait resumes through the
2211
2368
  // coordinator's claim. An ordinary manual continuation would leave that
2212
2369
  // automatic resume armed for the same assignment, so it is refused until
@@ -2322,6 +2479,28 @@ export default function (pi: ExtensionAPI) {
2322
2479
  const cwd = workspace.cwd;
2323
2480
  const requestedSandboxDir = workspace.requestedSandboxDir;
2324
2481
 
2482
+ // Skill exposure is decided once per attempt. A continuation replays the
2483
+ // frozen recipe (including its absence, which keeps discovery); a fresh
2484
+ // launch resolves launch option → catalog role/agent → this session's
2485
+ // default → saved config default → discovery. Relative paths belong to
2486
+ // the workspace the child runs in.
2487
+ const sessionSkills = resume ? undefined : sessionSkillChoice();
2488
+ if (!resume && !sessionSkills) {
2489
+ const saved = savedSkills();
2490
+ if (saved.error) {
2491
+ throw new Error(`Cannot read config defaultSkills: ${saved.error}`);
2492
+ }
2493
+ }
2494
+ const skills = resolveSkillExposure(resume
2495
+ ? { saved: { paths: resume.recipe.skills }, cwd }
2496
+ : {
2497
+ requested: p.skills,
2498
+ catalog: p.catalog?.effective?.skills?.value,
2499
+ session: sessionSkills,
2500
+ configured: cfg.defaultSkills,
2501
+ cwd,
2502
+ });
2503
+
2325
2504
  if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
2326
2505
  writeFileSync(promptPathFor(id), p.prompt);
2327
2506
 
@@ -2395,13 +2574,51 @@ export default function (pi: ExtensionAPI) {
2395
2574
  }).tools.join(",");
2396
2575
  }
2397
2576
  const bridgeToolNames = new Set<string>(bridgeEnabled ? bridgePlan.tools : []);
2577
+ // A bridge tool the supervisor withholds (no production schema, clean,
2578
+ // excluded) explains itself better than extension admission would.
2579
+ const withheldBridgeReasons = new Map<string, string>(bridgePlan.withheld.map((tool) => [tool.name, tool.reason]));
2580
+ // Candidates for the task-tool plan: exclusions and bridge-supplied
2581
+ // names never reach extension admission.
2582
+ const plannedTools = allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name));
2398
2583
  const taskTools = sandboxEnabled ? planTaskTools({
2399
- requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name)),
2584
+ requested: plannedTools,
2400
2585
  settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
2401
2586
  processAccess: permissionPlan.permissions?.processAccess ?? "off",
2402
2587
  builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
2403
2588
  toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
2404
2589
  }) : undefined;
2590
+ // One effective selection feeds the task policy, child preflight, worker
2591
+ // bridge and frozen recipe, so a refused tool cannot leak into any of them
2592
+ // (#669). A name this attempt requires - the caller's explicit `tools`, or a
2593
+ // continuation's frozen loadout - refuses the launch instead of narrowing it;
2594
+ // an inherited default is dropped from the child with the reason.
2595
+ const requiredToolNames = new Set(requestedTools === undefined
2596
+ ? []
2597
+ : requestedTools.split(",").map((name) => name.trim()).filter(Boolean));
2598
+ const toolSelection = taskTools
2599
+ ? selectEffectiveTaskTools({
2600
+ tools: allow.split(",").filter(Boolean), plan: taskTools, required: requiredToolNames,
2601
+ })
2602
+ : undefined;
2603
+ if (toolSelection?.required.length) {
2604
+ const detail = toolSelection.required
2605
+ .map((tool) => `${tool.name} (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join(", ");
2606
+ throw resume
2607
+ ? new ContinuationError(
2608
+ `Cannot continue ${resume.prior.id}: its frozen launch requires tool(s) this parent can no longer provide: ${detail}. ` +
2609
+ `Launch a new run instead of continuing this conversation.`,
2610
+ )
2611
+ : new Error(
2612
+ `Requested tool(s) are not available in the task sandbox: ${detail}. ` +
2613
+ `Remove them from the tools list, or make them available in /sandbox (Subagents · Tools); nothing was launched.`,
2614
+ );
2615
+ }
2616
+ if (toolSelection) {
2617
+ if (plannedTools.length > 0 && toolSelection.tools.length === 0) {
2618
+ throw new Error(`No requested tool has a verified task sandbox adapter: ${toolSelection.refused.map((tool) => `${tool.name} (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join(", ")}.`);
2619
+ }
2620
+ allow = toolSelection.tools.join(",");
2621
+ }
2405
2622
  const dependencyOptions = {
2406
2623
  model, virtual: (() => {
2407
2624
  const slash = model?.indexOf("/") ?? -1;
@@ -2485,21 +2702,17 @@ export default function (pi: ExtensionAPI) {
2485
2702
  ...commandExtArgs,
2486
2703
  ...(model ? ["--model", model] : []),
2487
2704
  ...(thinking ? ["--thinking", thinking] : []),
2705
+ ...skillLaunchArgs(skills),
2488
2706
  ...(allow && !sandboxEnabled ? ["--tools", allow] : []),
2489
2707
  ...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
2490
2708
  ...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
2491
2709
  p.prompt,
2492
2710
  ];
2493
2711
 
2494
- const piBin = resolvePiBinary();
2495
2712
  const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
2496
- const unavailable = taskTools?.refused.filter((tool) => selectedTools.includes(tool.name)) ?? [];
2497
- const unavailableTools = unavailable.map((tool) => tool.name);
2498
- if (sandboxEnabled && selectedTools.length && unavailableTools.length === selectedTools.length) {
2499
- throw new Error(`No requested tool has a verified task sandbox adapter: ${unavailable.map((tool) => `${tool.name} (${tool.reason})`).join(", ")}.`);
2500
- }
2713
+ const dropped = toolSelection?.dropped ?? [];
2501
2714
  const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
2502
- root: requestedSandboxDir, controlDir: join(runDir(id), "control"), piBin,
2715
+ root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
2503
2716
  tools: selectedTools,
2504
2717
  permissions: permissionPlan.permissions && { ...permissionPlan.permissions, ...commandSettings },
2505
2718
  applyPatch: taskTools?.applyPatch === true,
@@ -2528,7 +2741,7 @@ export default function (pi: ExtensionAPI) {
2528
2741
  try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
2529
2742
  });
2530
2743
  }
2531
- const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), piBin, ...args] };
2744
+ const cmd = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] } : { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
2532
2745
  const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
2533
2746
 
2534
2747
  // Reservations prevent competing admissions, but do not grandfather
@@ -2644,6 +2857,7 @@ export default function (pi: ExtensionAPI) {
2644
2857
  effort: thinking,
2645
2858
  tools: allow,
2646
2859
  excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
2860
+ skills: skills.mode === "inherit" ? undefined : [...skills.paths],
2647
2861
  clean,
2648
2862
  allowNested,
2649
2863
  approve,
@@ -2665,6 +2879,8 @@ export default function (pi: ExtensionAPI) {
2665
2879
  id, name: launchName, status: "running",
2666
2880
  pid: spawned.pid, spawnPid: process.pid, spawnPidStartTime: parentStartToken(), model,
2667
2881
  effort: thinking, cwd,
2882
+ ...(skills.mode === "inherit" ? {} : { skills: [...skills.paths] }),
2883
+ skillsSource: skills.source,
2668
2884
  ...identity,
2669
2885
  promptPreview: p.prompt.slice(0, 200),
2670
2886
  startedAt, logPath: logPathFor(id), sessionId,
@@ -2762,14 +2978,16 @@ export default function (pi: ExtensionAPI) {
2762
2978
  : resolution.specs.length
2763
2979
  ? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
2764
2980
  : `Runtime: isolated · built-in tools only\n`;
2765
- const warn = (unavailable.length ? `Task sandbox: ${unavailable.map((tool) => `${tool.name} disabled (${tool.reason})`).join("; ")}.\n` : "") +
2981
+ const warn = (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
2766
2982
  (!sandboxEnabled && resolution.unmapped.length
2767
2983
  ? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
2768
2984
  `${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
2769
2985
  `Add a toolExtensions entry in config.json.\n`
2770
2986
  : "");
2771
2987
  const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
2772
- return { id, meta, spawned, runtime: runtime + (meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""), warn, sandboxDir, modelNote };
2988
+ // The resolved skill exposure rides with the runtime summary, which every
2989
+ // launch and continuation message already prints.
2990
+ return { id, meta, spawned, runtime: `${runtime}${describeSkillExposure(skills)}\n${meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""}`, warn, sandboxDir, modelNote };
2773
2991
  } catch (error) {
2774
2992
  // A launch that never committed metadata is not a run: drop
2775
2993
  // everything the attempt created so the registry keeps no
@@ -3040,13 +3258,13 @@ export default function (pi: ExtensionAPI) {
3040
3258
  "After subagent_spawn, do NOT call subagent_output or subagent_result in a loop to wait for the result, and do NOT sleep. The run completes on its own and reports back on the next turn.",
3041
3259
  "Call subagent_result after a completion or attention callback, or when the user explicitly asks for the result. Use subagent_output only when the user explicitly asks how a run is progressing; never use either tool to poll.",
3042
3260
  ...SUBAGENT_ORCHESTRATION_GUIDELINES,
3043
- "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3261
+ "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3044
3262
  ...CATALOG_GUIDELINES,
3045
3263
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
3046
3264
  "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. No progress for stuck_minutes (default 10) wakes you once without stopping the run. Elapsed-time limits are opt-in: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
3047
3265
  "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
3048
3266
  "Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
3049
- "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
3267
+ "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
3050
3268
  "Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
3051
3269
  ],
3052
3270
  parameters: Type.Object({
@@ -3061,6 +3279,7 @@ export default function (pi: ExtensionAPI) {
3061
3279
  thinking: Type.Optional(Type.String({ description: "Reasoning effort for the child: off, minimal, low, medium, high, xhigh, or max. Omit to use the agent or role default; without one, the Pi/model default." })),
3062
3280
  tools: Type.Optional(Type.String({ description: "Tool allowlist: comma-separated names the child may use (e.g. 'read,bash,web_fetch'). This ALSO selects which extensions load — only packages backing a requested tool are loaded. Defaults to the configured safe set." })),
3063
3281
  exclude_tools: Type.Optional(Type.String({ description: "Comma-separated tool denylist, applied on top of the allowlist." })),
3282
+ skills: Type.Optional(Type.Array(Type.String(), { description: "Skill exposure for the child. Omit to inherit the catalog role/agent choice, then config defaultSkills, then user-catalog discovery. [] loads no skills (--no-skills). Absolute paths load exactly those skills (--no-skills --skill <path>), which is how a task that names one SKILL.md by path avoids advertising the whole catalog. Relative paths resolve against the child workspace." })),
3064
3283
  clean: Type.Optional(Type.Boolean({ description: "Run a hermetic child with NO extensions at all (only built-ins: read, bash, edit, write). Default false — the extensions backing the requested tools load, so web_fetch and model auth (e.g. xai) work." })),
3065
3284
  sandbox: Type.Optional(Type.Boolean({ description: "Use the human Subagents profile from /sandbox. Defaults to off without published settings. True requests kernel confinement; false cannot bypass an enabled human profile." })),
3066
3285
  sandbox_dir: Type.Optional(Type.String({ description: "Confine writes to (and run the child in) this directory instead of the working dir. Created if missing." })),
@@ -3229,6 +3448,7 @@ export default function (pi: ExtensionAPI) {
3229
3448
  thinking: Type.Optional(Type.String({ description: "Reasoning effort applied to every job: off, minimal, low, medium, high, xhigh, or max." })),
3230
3449
  tools: Type.Optional(Type.String({ description: "Tool allowlist applied to every job." })),
3231
3450
  exclude_tools: Type.Optional(Type.String({ description: "Comma-separated tool denylist applied to every job." })),
3451
+ skills: Type.Optional(Type.Array(Type.String(), { description: "Skill exposure applied to every job. Per-job skills override this. [] loads no skills; absolute paths load exactly those skills; omit to inherit discovery." })),
3232
3452
  sandbox: Type.Optional(Type.Boolean({ description: "Use the human Subagents profile; false cannot override an enabled profile. Defaults to off without published settings; true requests kernel confinement." })),
3233
3453
  sandbox_dir: Type.Optional(Type.String({ description: "Writable root for every job." })),
3234
3454
  callback: Type.Optional(Type.Boolean({ description: "Default TRUE: post result back on completion." })),
@@ -3251,6 +3471,7 @@ export default function (pi: ExtensionAPI) {
3251
3471
  thinking: Type.Optional(Type.String()),
3252
3472
  tools: Type.Optional(Type.String()),
3253
3473
  exclude_tools: Type.Optional(Type.String()),
3474
+ skills: Type.Optional(Type.Array(Type.String())),
3254
3475
  sandbox: Type.Optional(Type.Boolean()),
3255
3476
  sandbox_dir: Type.Optional(Type.String()),
3256
3477
  callback: Type.Optional(Type.Boolean()),
@@ -3502,6 +3723,8 @@ export default function (pi: ExtensionAPI) {
3502
3723
  const agentOperations = createAgentOperations({
3503
3724
  projectConfigDirName,
3504
3725
  sessionSettings: agentSessionSettings,
3726
+ readSkillDefaults,
3727
+ discoverSkills: (commandCtx) => discoveredSkillsFromContext(commandCtx),
3505
3728
  editableModels: () => catalogModelRegistry?.getAvailable().map((model) => `${model.provider}/${model.id}`) ?? [],
3506
3729
  propagateCommandContext(commandCtx) {
3507
3730
  noteCatalogHost(catalogHostFrom(commandCtx));
@@ -3532,21 +3755,28 @@ export default function (pi: ExtensionAPI) {
3532
3755
  const next = await ctx.ui.custom<"agents" | undefined>((tui, theme, _kb, done) => createSubagentSettingsPage(theme, {
3533
3756
  get: () => {
3534
3757
  const settings = effectiveSettings();
3758
+ const skills = activeSkills();
3535
3759
  return {
3536
3760
  mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
3537
3761
  modeSource: settings.sources.delegationMode,
3538
3762
  capSource: settings.sources.maxConcurrent,
3539
3763
  defaultMode: normalizeDelegationMode(loadConfig().delegationMode),
3540
3764
  defaultCap: normalizeConcurrencyCap(loadConfig().maxConcurrent),
3765
+ skillsMode: skills.mode, skillsPaths: skills.paths, skillsSource: skills.source,
3766
+ skillsError: skills.error,
3541
3767
  };
3542
3768
  },
3543
- changeMode, changeCap, save: saveSettings, reset: resetSettings,
3769
+ changeMode, changeCap, changeSkills, save: saveSettings, reset: resetSettings,
3770
+ discoverSkills: () => discoveredSkillsFromContext(ctx),
3544
3771
  // Close this page first; the catalog opens after ui.custom resolves.
3545
3772
  openAgents: () => done("agents"),
3546
3773
  }, () => { refreshBackgroundWorkNavigator(ctx); tui.requestRender(); }, () => done(undefined)));
3547
3774
  if (next === "agents") await agentOperations.openCatalog(ctx);
3548
3775
  } else {
3549
- ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. Use /subagents mode <mode> or /subagents cap <number>; /subagents save persists both.`, "info");
3776
+ const skills = activeSkills();
3777
+ const skillChoice = skills.mode === "inherit" ? "discovery"
3778
+ : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3779
+ ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. Skills: ${skillChoice}. Use /subagents mode <mode>, cap <number>, or settings; /subagents save persists them.`, "info");
3550
3780
  }
3551
3781
  };
3552
3782
  const contribution = { id: "subagents", label: "Subagents", command: "/subagents settings", open: openSettings };
@@ -3571,7 +3801,14 @@ export default function (pi: ExtensionAPI) {
3571
3801
  }
3572
3802
  const requested = tokens[1];
3573
3803
  if (tokens.length === 1 && tokens[0] === "save") {
3574
- if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}.`))) {
3804
+ const skills = activeSkills();
3805
+ if (skills.mode === "explicit" && skills.paths.length === 0) {
3806
+ ctx.ui.notify("Add at least one skill path, or choose No skill catalog to load none.", "warning");
3807
+ return;
3808
+ }
3809
+ const skillChoice = skills.mode === "inherit" ? "skill discovery"
3810
+ : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3811
+ if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()} and ${skillChoice}.`))) {
3575
3812
  ctx.ui.notify("Subagent defaults unchanged.", "info");
3576
3813
  return;
3577
3814
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.27.2",
3
+ "version": "0.28.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",
package/registry.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import type { RunTiming } from "./timing.ts";
16
+ import type { SkillExposureSource } from "./skills.ts";
16
17
  import { execFileSync } from "node:child_process";
17
18
  import { createHash, randomBytes } from "node:crypto";
18
19
  import { closeSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
@@ -109,6 +110,12 @@ export interface LaunchRecipe {
109
110
  /** Effective tool allowlist (already adjusted for confinement). */
110
111
  tools: string;
111
112
  excludeTools?: string;
113
+ /**
114
+ * Effective skill exposure: absent means discovery of the user catalog,
115
+ * `[]` means none, and paths mean exactly those skills. Recipes written
116
+ * before skill controls existed have no key and keep discovery.
117
+ */
118
+ skills?: string[];
112
119
  clean: boolean;
113
120
  allowNested: boolean;
114
121
  approve: boolean;
@@ -191,6 +198,10 @@ export interface RunMeta {
191
198
  model?: string;
192
199
  /** Reasoning effort passed to the child via Pi's --thinking option. */
193
200
  effort?: string;
201
+ /** Effective skill exposure when it is not discovery; absent means discovery. */
202
+ skills?: string[];
203
+ /** Which layer chose that exposure: launch, catalog, config, default, or a replayed recipe. */
204
+ skillsSource?: SkillExposureSource;
194
205
  cwd: string;
195
206
  /** First ~200 chars of the task prompt, for listings. */
196
207
  promptPreview: string;