pi-better-subagents 0.22.2 → 0.23.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/package.json CHANGED
@@ -1,9 +1,19 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.22.2",
3
+ "version": "0.23.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",
7
+ "bin": {
8
+ "pi-agent-catalog": "./agent-catalog.mjs"
9
+ },
10
+ "exports": {
11
+ "./catalog": "./worker-catalog.ts",
12
+ "./catalog-store": "./catalog-store.ts",
13
+ "./catalog-resolver": "./catalog-resolver.ts",
14
+ "./model-resolution-core": "./model-resolution-core.ts",
15
+ "./*": "./*"
16
+ },
7
17
  "keywords": [
8
18
  "pi-package",
9
19
  "pi-extension",
@@ -51,6 +61,7 @@
51
61
  "docs/agent-catalog.md",
52
62
  "docs/agent-catalog-operations.md",
53
63
  "docs/agent-model-resolution.md",
64
+ "docs/worker-catalog.md",
54
65
  "docs/agent-catalog-lifecycle.md",
55
66
  "docs/agent-catalog-acceptance.md",
56
67
  "docs/failure-observations.md"
@@ -64,6 +75,7 @@
64
75
  "proper-lockfile": "^4.1.2",
65
76
  "shell-quote": "1.12.0",
66
77
  "smol-toml": "1.9.0",
78
+ "tsx": "^4.22.3",
67
79
  "yaml": "^2.9.1"
68
80
  }
69
81
  }
@@ -10,4 +10,5 @@ defaults:
10
10
  tier: balanced
11
11
  ---
12
12
  Implement the requested change in the existing system and own focused tests. Preserve behavior the task did not ask to change, and record what you verified.
13
+ When a check fails, report the failing step, the error message and where the evidence is; an exit code alone is not a failure report. Keep the first failure separate from later cleanup errors. Send long command output to a file and read only the tail or the matching lines.
13
14
  Do not define product policy or own broad architecture decisions; route those to Product Manager or Architect. Independent critique belongs to Reviewer, not the implementer.
package/task-guard.ts CHANGED
@@ -7,6 +7,8 @@ import { SANDBOX_POLICY_CHANNEL, SANDBOX_POLICY_REQUEST_CHANNEL } from "./permis
7
7
  import { failureDispositionTool, intentBashDefinition } from "./child-incidents.ts";
8
8
  import { DISPOSITION_TOOL } from "./incident-model.ts";
9
9
  import { SandboxDiagnostics, diagnosticPackageVersion } from "./shared-sandbox-diagnostics.ts";
10
+ import { fileURLToPath } from "node:url";
11
+ import { claimTaskToolOwner } from "./task-tool-owner.ts";
10
12
 
11
13
  const TRUSTED_INLINE_SOURCE = "<inline:task-sandbox>";
12
14
 
@@ -31,7 +33,7 @@ export function trustedToolRefusal(policy: TaskPolicy, name: string, sourcePath:
31
33
  return undefined;
32
34
  }
33
35
 
34
- export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (error: unknown) => never): void {
36
+ export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (error: unknown) => never, ownedTools = false): void {
35
37
  const policy = parseTaskPolicy(input);
36
38
  const support = describeSandboxSupport();
37
39
  if (!support.supported) throw new Error(`Task sandbox unavailable: ${support.reason}`);
@@ -54,9 +56,10 @@ export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (erro
54
56
  diagnosticsWarned = true;
55
57
  },
56
58
  });
57
- const boundary = installTaskTools(pi, { controller, cwd: process.cwd(), shellPath: () => shellPath,
59
+ const toolApi = ownedTools ? { ...pi, registerTool: claimTaskToolOwner(pi) } : pi;
60
+ const installBoundary = () => installTaskTools(toolApi, { controller, cwd: process.cwd(), shellPath: () => shellPath,
58
61
  diagnostics,
59
- trustedSources: [TRUSTED_INLINE_SOURCE],
62
+ trustedSources: [ownedTools ? fileURLToPath(new URL("./task-tool-owner.ts", import.meta.url)) : TRUSTED_INLINE_SOURCE],
60
63
  // Structured command intent (#315): validated before the confined command runs.
61
64
  bashDefinition: (cwd, operations) => intentBashDefinition(cwd, operations) as any,
62
65
  applyPatch: policy.applyPatch,
@@ -66,6 +69,9 @@ export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (erro
66
69
  admitExtensionTool: (name, _input, sourcePath) => (name === DISPOSITION_TOOL && sourcePath === TRUSTED_INLINE_SOURCE) ||
67
70
  trustedToolRefusal(policy, name, sourcePath) === undefined,
68
71
  });
72
+ // Defer owned registrations until after SDK duplicate-name diagnostics.
73
+ // The final session_start handler still installs and verifies them before activation.
74
+ let boundary = ownedTools ? undefined : installBoundary();
69
75
  pi.registerTool(failureDispositionTool(() => currentCwd) as any);
70
76
  const profile = Object.freeze({ enabled: true, ...policy.permissions });
71
77
  const status = Object.freeze({
@@ -80,6 +86,7 @@ export default function taskGuard(pi: ExtensionAPI, input: unknown, fatal: (erro
80
86
  try {
81
87
  shellPath = SettingsManager.create(ctx.cwd, policy.agentDir, { projectTrusted: false }).getShellPath();
82
88
  currentCwd = ctx.cwd;
89
+ boundary ??= installBoundary();
83
90
  boundary.register(ctx.cwd);
84
91
  const builtins: readonly string[] = policy.applyPatch ? [...TASK_BUILTINS, ...GUARDED_TASK_TOOLS] : TASK_BUILTINS;
85
92
  const known = new Set<string>(builtins);
package/task-runtime.mjs CHANGED
@@ -29,9 +29,12 @@ try {
29
29
  const guard = await load.import(fileURLToPath(new URL("./task-guard.ts", import.meta.url)), { default: true });
30
30
  if (typeof guard !== "function") throw new Error("Task guard has no extension factory.");
31
31
  const { main } = await import(pathToFileURL(join(dirname(sdkEntry), "main.js")).href);
32
- await main(args, {
32
+ // SDK tool names belong to the first extension registering them. Reserve a
33
+ // source before provider/trusted packages, but keep activation in the final guard.
34
+ const ownerPath = fileURLToPath(new URL("./task-tool-owner.ts", import.meta.url));
35
+ await main(["--extension", ownerPath, ...args], {
33
36
  extensionFactories: [{ name: "task-sandbox", factory: async (pi) => {
34
- try { await guard(pi, policy, fail); } catch (error) { fail(error); }
37
+ try { await guard(pi, policy, fail, true); } catch (error) { fail(error); }
35
38
  } }],
36
39
  });
37
40
  } catch (error) {
@@ -0,0 +1,21 @@
1
+ /** Loaded before third-party extensions so guarded tools win SDK name resolution. */
2
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
+
4
+ const CLAIM_CHANNEL = "pi-better-subagents:claim-task-tool-owner";
5
+ type RegisterTool = ExtensionAPI["registerTool"];
6
+
7
+ export default function taskToolOwner(pi: ExtensionAPI): void {
8
+ const unsubscribe = pi.events.on(CLAIM_CHANNEL, (claim) => {
9
+ if (typeof claim !== "function") return;
10
+ unsubscribe();
11
+ claim(pi.registerTool.bind(pi));
12
+ });
13
+ }
14
+
15
+ /** Hand registration to the final guard without changing the SDK's source attribution. */
16
+ export function claimTaskToolOwner(pi: ExtensionAPI): RegisterTool {
17
+ let register: RegisterTool | undefined;
18
+ pi.events.emit(CLAIM_CHANNEL, (owner: RegisterTool) => { register = owner; });
19
+ if (!register) throw new Error("Task tool owner was not installed before extension loading.");
20
+ return register;
21
+ }
@@ -0,0 +1,162 @@
1
+ /** Shared worker planning. No Pi imports, provider discovery, or child execution. */
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { loadCatalog, type CatalogSnapshot } from "./catalog-store.ts";
5
+ import { resolveSelection } from "./catalog-resolver.ts";
6
+ import { resolveModel, type ModelDecision, type ResolvableModel } from "./model-resolution-core.ts";
7
+ import { THINKING_LEVELS, type ThinkingLevel } from "./thinking.ts";
8
+ import type { TierPolicy } from "./tier-policy.ts";
9
+
10
+ export const WORKER_ROLES = {
11
+ implementer: "developer",
12
+ explorer: "explorer",
13
+ diagnoser: "developer",
14
+ reviewer: "reviewer",
15
+ } as const;
16
+ export type WorkerSlot = keyof typeof WORKER_ROLES;
17
+ export type WorkerRole = typeof WORKER_ROLES[WorkerSlot];
18
+ export type WorkerHost = "pi" | "codex" | "claude-code";
19
+
20
+ export interface WorkerOverride { model?: string; effort?: ThinkingLevel }
21
+ export interface AvailableWorkerModel {
22
+ /** Canonical identity; never inferred from a native host model name. */
23
+ model: string;
24
+ nativeModel?: string;
25
+ supportedEfforts: readonly ThinkingLevel[];
26
+ }
27
+ export interface WorkerCatalogRequest {
28
+ version: 1;
29
+ harness: WorkerHost;
30
+ cwd: string;
31
+ userRoot?: string;
32
+ projectTrusted?: boolean;
33
+ available: readonly AvailableWorkerModel[];
34
+ foregroundModel?: string;
35
+ /** Non-Pi hosts must explicitly opt into foreground fallback. */
36
+ fallbackToForeground?: boolean;
37
+ /** Current-turn launch controls. Prompt text is not model selection. */
38
+ launchCapabilities?: { model: boolean; effort: boolean; instructions: boolean };
39
+ /** Explicit host configuration, below task overrides and above role defaults. */
40
+ hostPreferences?: Partial<Record<WorkerRole, WorkerOverride>>;
41
+ overrides?: Partial<Record<WorkerSlot, WorkerOverride>>;
42
+ tiers?: TierPolicy;
43
+ }
44
+ export interface WorkerDiagnostic { code: string; message: string; blocking: boolean; slot?: WorkerSlot }
45
+ export interface WorkerPlan {
46
+ role: WorkerRole;
47
+ model: string | null;
48
+ nativeModel: string | null;
49
+ effort: ThinkingLevel | null;
50
+ instructions: string;
51
+ selection: { model: ModelDecision["modelSelection"]; effort: ModelDecision["effortSelection"] } | null;
52
+ launch: null | Record<string, unknown>;
53
+ catalogDigest: string;
54
+ diagnostics: WorkerDiagnostic[];
55
+ }
56
+ export interface WorkerCatalogPlan {
57
+ version: 1;
58
+ ok: boolean;
59
+ harness: WorkerHost;
60
+ catalogDigest: string;
61
+ slots: Record<WorkerSlot, WorkerPlan>;
62
+ diagnostics: WorkerDiagnostic[];
63
+ }
64
+
65
+ export function planWorkers(request: WorkerCatalogRequest, snapshot?: CatalogSnapshot): WorkerCatalogPlan {
66
+ validateRequest(request);
67
+ const catalog = snapshot ?? loadCatalog({
68
+ cwd: request.cwd,
69
+ userRoot: request.userRoot ?? process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"),
70
+ projectTrusted: request.projectTrusted === true,
71
+ });
72
+ const models: ResolvableModel[] = request.available.map((entry) => {
73
+ const slash = entry.model.indexOf("/");
74
+ return {
75
+ provider: entry.model.slice(0, slash), id: entry.model.slice(slash + 1),
76
+ reasoning: entry.supportedEfforts.some((level) => level !== "off"),
77
+ supportedEffortLevels: [...entry.supportedEfforts],
78
+ };
79
+ });
80
+ const slots = Object.fromEntries(Object.entries(WORKER_ROLES).map(([slot, role]) => {
81
+ const key = slot as WorkerSlot;
82
+ const resolved = resolveSelection(catalog, { roleId: `role.${role}` });
83
+ const worker: WorkerPlan = {
84
+ role, model: null, nativeModel: null, effort: null,
85
+ instructions: resolved.effective?.instructions ?? "", selection: null,
86
+ launch: null, catalogDigest: catalog.digest,
87
+ diagnostics: resolved.diagnostics.map((item) => ({ code: item.code, message: item.message, blocking: item.blocking, slot: key })),
88
+ };
89
+ if (!resolved.launchable || !resolved.effective) return [key, worker];
90
+ const override = request.overrides?.[key];
91
+ const hostPreference = request.hostPreferences?.[role];
92
+ const decision = resolveModel({
93
+ effective: resolved.effective,
94
+ registry: { getAvailable: () => models }, tiers: request.tiers,
95
+ foregroundModel: request.harness === "pi" || request.fallbackToForeground === true ? request.foregroundModel : undefined,
96
+ invocation: { model: override?.model, thinking: override?.effort },
97
+ authoritative: { model: hostPreference?.model, effort: hostPreference?.effort },
98
+ });
99
+ worker.model = decision.modelSelection.actual;
100
+ worker.effort = decision.effortSelection.actual;
101
+ worker.selection = { model: decision.modelSelection, effort: decision.effortSelection };
102
+ worker.diagnostics.push(...decision.diagnostics.map((item) => ({ code: item.code, message: item.message, blocking: item.blocking, slot: key })));
103
+ if (decision.status !== "ready") return [key, worker];
104
+ const available = request.available.find((item) => item.model === worker.model);
105
+ worker.nativeModel = available?.nativeModel ?? (request.harness === "pi" ? worker.model : null);
106
+ if (request.harness === "pi") {
107
+ // Let the live Pi catalog apply its own defaults; do not turn them into invocation overrides.
108
+ worker.launch = {
109
+ role,
110
+ ...(decision.modelSelection.explicitRequest ? { model: worker.model } : {}),
111
+ ...(decision.effortSelection.explicit && worker.effort ? { thinking: worker.effort } : {}),
112
+ };
113
+ } else if (!worker.nativeModel || request.launchCapabilities?.model !== true ||
114
+ request.launchCapabilities?.instructions !== true || (worker.effort !== null && request.launchCapabilities?.effort !== true)) {
115
+ worker.diagnostics.push({ code: "host-launch-unsupported", message: `${request.harness} must advertise model, instruction, and requested effort controls and an explicit nativeModel mapping. Prompt text cannot select a model.`, blocking: true, slot: key });
116
+ } else {
117
+ worker.launch = { model: worker.nativeModel, effort: worker.effort, instructions: worker.instructions };
118
+ }
119
+ return [key, worker];
120
+ })) as Record<WorkerSlot, WorkerPlan>;
121
+ if (slots.implementer.model && slots.implementer.model === slots.reviewer.model) {
122
+ slots.reviewer.launch = null;
123
+ slots.reviewer.diagnostics.push({ code: "reviewer-not-independent", message: "Implementer and reviewer resolve to the same model. Configure a distinct reviewer; no replacement was invented.", blocking: true, slot: "reviewer" });
124
+ }
125
+ const diagnostics = Object.values(slots).flatMap((slot) => slot.diagnostics);
126
+ const ok = Object.values(slots).every((slot) => slot.launch !== null) && !diagnostics.some((item) => item.blocking);
127
+ // A failed preflight is not a partial launch authorization.
128
+ if (!ok) for (const slot of Object.values(slots)) slot.launch = null;
129
+ return { version: 1, ok, harness: request.harness, catalogDigest: catalog.digest, slots, diagnostics };
130
+ }
131
+
132
+ function validateRequest(request: WorkerCatalogRequest): void {
133
+ if (!request || request.version !== 1 || !["pi", "codex", "claude-code"].includes(request.harness) ||
134
+ typeof request.cwd !== "string" || !request.cwd.trim() || !Array.isArray(request.available)) {
135
+ throw new Error("invalid-worker-request: supply version 1, harness, cwd, and current-host available model capabilities.");
136
+ }
137
+ const ids = new Set<string>();
138
+ const nativeIds = new Set<string>();
139
+ for (const model of request.available) {
140
+ if (!model || typeof model.model !== "string" || !/^[^\s/@]+\/[^\s@]+$/.test(model.model) || ids.has(model.model) ||
141
+ !Array.isArray(model.supportedEfforts) || model.supportedEfforts.length === 0 ||
142
+ model.supportedEfforts.some((level: ThinkingLevel) => !THINKING_LEVELS.includes(level)) ||
143
+ new Set(model.supportedEfforts).size !== model.supportedEfforts.length ||
144
+ (model.nativeModel !== undefined && (typeof model.nativeModel !== "string" || !model.nativeModel.trim() || nativeIds.has(model.nativeModel)))) {
145
+ throw new Error("invalid-model-capabilities: supply unique provider/model identities, native mappings, and verified supportedEfforts.");
146
+ }
147
+ ids.add(model.model);
148
+ if (model.nativeModel) nativeIds.add(model.nativeModel);
149
+ }
150
+ for (const [preferences, allowed] of [[request.overrides, Object.keys(WORKER_ROLES)], [request.hostPreferences, Object.values(WORKER_ROLES)]] as const) {
151
+ if (preferences === undefined) continue;
152
+ if (!preferences || typeof preferences !== "object" || Array.isArray(preferences)) throw new Error("invalid-worker-preferences: expected an object.");
153
+ for (const [key, preference] of Object.entries(preferences)) {
154
+ if (!(allowed as readonly string[]).includes(key) || !preference || typeof preference !== "object" || Array.isArray(preference) ||
155
+ Object.keys(preference).some((field) => !["model", "effort"].includes(field)) ||
156
+ (preference.model !== undefined && (typeof preference.model !== "string" || !preference.model.trim())) ||
157
+ (preference.effort !== undefined && !THINKING_LEVELS.includes(preference.effort))) {
158
+ throw new Error(`invalid-worker-preferences: invalid model or effort for ${key}.`);
159
+ }
160
+ }
161
+ }
162
+ }