@ferris1225/pi-subagents 6.0.5 → 7.0.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@ferris1225/pi-subagents",
3
- "version": "6.0.5",
4
- "description": "A managed sub-agent team for pi: research, implementation, independent review, interactive follow-ups, and Git worktree isolation.",
3
+ "version": "7.0.0",
4
+ "description": "Lead/worker orchestration for Pi: main plans and reviews, configurable workers execute with retained sessions and Git worktree isolation.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "repository": {
@@ -20,7 +20,8 @@
20
20
  "pi-extension",
21
21
  "subagent",
22
22
  "sub-agent",
23
- "delegation"
23
+ "delegation",
24
+ "orchestration"
24
25
  ],
25
26
  "files": [
26
27
  "index.ts",
@@ -36,19 +37,19 @@
36
37
  },
37
38
  "scripts": {
38
39
  "check": "tsc --noEmit && npm test",
39
- "test": "node --test test/*.test.ts",
40
+ "test": "node --test --test-concurrency=4 test/*.test.ts",
40
41
  "prepack": "npm run check"
41
42
  },
42
43
  "peerDependencies": {
43
- "@earendil-works/pi-ai": ">=1.5.0",
44
- "@earendil-works/pi-coding-agent": ">=1.5.0",
45
- "@earendil-works/pi-tui": ">=1.5.0",
44
+ "@earendil-works/pi-ai": ">=1.5.2",
45
+ "@earendil-works/pi-coding-agent": ">=1.5.2",
46
+ "@earendil-works/pi-tui": ">=1.5.2",
46
47
  "typebox": "*"
47
48
  },
48
49
  "devDependencies": {
49
- "@earendil-works/pi-ai": "^1.5.0",
50
- "@earendil-works/pi-coding-agent": "^1.5.0",
51
- "@earendil-works/pi-tui": "^1.5.0",
50
+ "@earendil-works/pi-ai": "1.5.2",
51
+ "@earendil-works/pi-coding-agent": "1.5.2",
52
+ "@earendil-works/pi-tui": "1.5.2",
52
53
  "@types/node": "^22.10.0",
53
54
  "typebox": "^1.3.27",
54
55
  "typescript": "^5.9.0"
@@ -1,202 +1,106 @@
1
- /**
2
- * Configuration load/save for pi-subagents.
3
- *
4
- * Config lives at <agentDir>/pi-subagents.json (agentDir defaults to ~/.pi/agent
5
- * and honors PI_CODING_AGENT_DIR). The only user-tunable surface is the model
6
- * and thinking level per role; all built-in roles are always enabled and
7
- * every operational default is a constant. Parsing is defensive: invalid
8
- * fields fall back to defaults instead of throwing, so a hand-edited or
9
- * partially-written file can never break the extension at runtime. Unknown
10
- * top-level keys from older versions are dropped; unknown role keys are retained
11
- * and legacy role names migrated. The normalized shape is persisted on load.
12
- */
1
+ /** Versioned worker settings. Legacy role configurations are replaced, never migrated. */
13
2
 
14
3
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
15
4
  import { dirname, join } from "node:path";
16
5
  import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
17
- import { migrateStoredRoleKeys } from "./role-migration.ts";
18
6
 
19
- /** Full catalog of agents shipped with the package; all of them always run. */
20
- export const BUILTIN_AGENT_NAMES = ["scout", "artisan", "sentinel"] as const;
21
-
22
- /** Thinking levels accepted by pi's `--thinking` option. */
7
+ export const CONFIG_VERSION = 1;
8
+ export const BUILTIN_AGENT_NAMES = ["scout", "artisan"] as const;
23
9
  const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
24
10
  export type ThinkingLevel = (typeof THINKING_LEVEL_VALUES)[number];
25
11
  export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
26
-
27
- /** Role-owned default reasoning strength. A `/subagents-setup` override wins;
28
- * there is no per-call thinking. */
29
- export function roleThinkingLevel(agentName: string): ThinkingLevel {
30
- switch (agentName) {
31
- case "scout":
32
- return "low";
33
- case "artisan":
34
- case "sentinel":
35
- return "high";
36
- default:
37
- return DEFAULT_THINKING_LEVEL;
38
- }
39
- }
40
-
41
- /** Responsibility line shown for a built-in's selected setup row. */
42
- export interface AgentProfile {
43
- /** What this role owns, shown for its selected setup row. */
44
- remark: string;
45
- }
46
-
47
- export const AGENT_PROFILES: Record<(typeof BUILTIN_AGENT_NAMES)[number], AgentProfile> = {
48
- scout: {
49
- remark: "Bounded code, documentation, or web research with citations. No commands or edits.",
50
- },
51
- artisan: {
52
- remark: "Implement one substantial change with its tests and verification.",
53
- },
54
- sentinel: {
55
- remark: "Inspect an implementation or diff and challenge claims or assumptions for defects and regressions. No edits.",
56
- },
57
- };
58
-
59
- export function agentProfile(name: string): AgentProfile | undefined {
60
- return (AGENT_PROFILES as Record<string, AgentProfile | undefined>)[name];
61
- }
62
-
63
- /** How many lines of a sub-agent result the completion message may carry.
64
- * Wide fan-outs multiply completion blocks, so deliveries stay compact and the
65
- * full text lives in the on-disk result artifact. */
66
12
  export const DEFAULT_MAX_RESULT_LINES = 40;
67
-
68
- const CONFIG_FILE_NAME = "pi-subagents.json";
69
-
70
- /** Idle timeout in seconds: a sub-agent whose stdout (JSON event stream) goes
71
- * silent for this long is terminated; a configured agent model then hands
72
- * off to the current main model. */
73
13
  export const DEFAULT_IDLE_TIMEOUT_SEC = 1800;
74
14
 
75
15
  export interface SubagentsConfig {
76
- /** Per-agent model override, keyed by agent name, as "provider/model-id". */
77
- agentModels: Record<string, string>;
78
- /** Optional per-agent thinking override from `/subagents-setup`. Missing =
79
- * the role default from `roleThinkingLevel`. */
80
- agentThinkingLevels: Record<string, ThinkingLevel>;
16
+ version: typeof CONFIG_VERSION;
17
+ /** One worker model for both implementation and read-only research. Missing follows main. */
18
+ model?: string;
19
+ thinking: ThinkingLevel;
81
20
  }
82
21
 
83
- /** The default every load starts from; `defaultConfig` keeps the shape in one place. */
84
- export const DEFAULT_CONFIG: SubagentsConfig = defaultConfig();
22
+ export const DEFAULT_CONFIG: Readonly<SubagentsConfig> = {
23
+ version: CONFIG_VERSION,
24
+ thinking: DEFAULT_THINKING_LEVEL,
25
+ };
85
26
 
86
27
  export function getConfigPath(agentDir: string = getAgentDir()): string {
87
- return join(agentDir, CONFIG_FILE_NAME);
88
- }
89
-
90
- function isRecord(value: unknown): value is Record<string, unknown> {
91
- return typeof value === "object" && value !== null && !Array.isArray(value);
28
+ return join(agentDir, "pi-subagents.json");
92
29
  }
93
30
 
94
- function isModelReference(value: unknown): value is string {
95
- if (typeof value !== "string") return false;
96
- const normalized = value.trim();
97
- const slash = normalized.indexOf("/");
98
- return slash > 0 && slash < normalized.length - 1 && !/\s/u.test(normalized);
31
+ function isCurrentConfig(raw: unknown): raw is Record<string, unknown> {
32
+ return typeof raw === "object" && raw !== null && !Array.isArray(raw)
33
+ && (raw as Record<string, unknown>).version === CONFIG_VERSION;
99
34
  }
100
35
 
101
- /**
102
- * Merge a raw parsed JSON value over the defaults, dropping invalid fields and
103
- * migrating legacy role names after validation so valid canonical values win.
104
- * Exported for tests.
105
- */
106
36
  export function normalizeConfig(raw: unknown): SubagentsConfig {
107
- const config = defaultConfig();
108
- if (!isRecord(raw)) return config;
109
-
110
- if (isRecord(raw.agentModels)) {
111
- for (const [rawKey, value] of Object.entries(raw.agentModels)) {
112
- const key = rawKey.trim();
113
- if (key !== "" && isModelReference(value)) {
114
- config.agentModels[key] = value.trim();
115
- }
116
- }
37
+ const config: SubagentsConfig = { ...DEFAULT_CONFIG };
38
+ if (!isCurrentConfig(raw)) return config;
39
+ if (typeof raw.model === "string") {
40
+ const model = raw.model.trim();
41
+ const slash = model.indexOf("/");
42
+ if (slash > 0 && slash < model.length - 1 && !/\s/u.test(model)) config.model = model;
117
43
  }
118
-
119
- if (isRecord(raw.agentThinkingLevels)) {
120
- for (const [rawKey, value] of Object.entries(raw.agentThinkingLevels)) {
121
- const key = rawKey.trim();
122
- if (
123
- key !== "" &&
124
- typeof value === "string" &&
125
- (THINKING_LEVEL_VALUES as readonly string[]).includes(value)
126
- ) {
127
- config.agentThinkingLevels[key] = value as ThinkingLevel;
128
- }
129
- }
44
+ if (typeof raw.thinking === "string" && (THINKING_LEVEL_VALUES as readonly string[]).includes(raw.thinking)) {
45
+ config.thinking = raw.thinking as ThinkingLevel;
130
46
  }
131
-
132
- config.agentModels = migrateStoredRoleKeys(config.agentModels);
133
- config.agentThinkingLevels = migrateStoredRoleKeys(config.agentThinkingLevels);
134
47
  return config;
135
48
  }
136
49
 
137
- function defaultConfig(): SubagentsConfig {
138
- return {
139
- agentModels: {},
140
- agentThinkingLevels: {},
141
- };
142
- }
143
-
144
- /**
145
- * Load config. A missing file is a normal state and yields the defaults (not an error).
146
- * A corrupt file also falls back to defaults rather than throwing, so startup never breaks.
147
- * Valid fields are normalized and unknown fields are omitted when the config is saved.
148
- */
149
- export async function loadConfig(
150
- configPath: string = getConfigPath(),
151
- ): Promise<SubagentsConfig> {
50
+ async function readStoredConfig(configPath: string): Promise<{ exists: boolean; raw?: unknown }> {
152
51
  let text: string;
153
52
  try {
154
53
  text = await readFile(configPath, "utf8");
54
+ } catch (error) {
55
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { exists: false };
56
+ throw error;
57
+ }
58
+ try {
59
+ return { exists: true, raw: JSON.parse(text) };
155
60
  } catch {
156
- // Missing or unreadable: fall back to defaults but do not crash startup.
157
- return defaultConfig();
61
+ return { exists: true };
158
62
  }
63
+ }
159
64
 
160
- let parsed: unknown;
65
+ /** Prepare the replacement before removing a legacy file. Callers own the mutation queue. */
66
+ async function writeConfig(config: SubagentsConfig, configPath: string, removeLegacy = false): Promise<void> {
67
+ await mkdir(dirname(configPath), { recursive: true });
68
+ const temporaryPath = configPath + "." + process.pid + "." + Date.now() + ".tmp";
161
69
  try {
162
- parsed = JSON.parse(text);
163
- } catch {
164
- return defaultConfig();
70
+ await writeFile(temporaryPath, JSON.stringify(config, null, 2) + "\n", "utf8");
71
+ if (removeLegacy) await rm(configPath, { force: true });
72
+ await rename(temporaryPath, configPath);
73
+ } finally {
74
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
165
75
  }
76
+ }
166
77
 
167
- const config = normalizeConfig(parsed);
78
+ /** Called at startup and setup. A reset affects this config file only, never recovery artifacts. */
79
+ export async function initializeConfig(configPath: string = getConfigPath()): Promise<"created" | "reset" | undefined> {
80
+ return withFileMutationQueue(configPath, async () => {
81
+ const stored = await readStoredConfig(configPath);
82
+ if (isCurrentConfig(stored.raw) && (stored.raw.model === undefined || normalizeConfig(stored.raw).model)) return undefined;
83
+ await writeConfig({ ...DEFAULT_CONFIG }, configPath, stored.exists);
84
+ return stored.exists ? "reset" : "created";
85
+ });
86
+ }
168
87
 
169
- // Persist the canonical shape when invalid or unknown fields were omitted.
170
- if (JSON.stringify(config) !== JSON.stringify(parsed)) {
171
- try {
172
- await saveConfig(config, configPath);
173
- } catch {
174
- // Non-fatal: keep the in-memory config for this run.
175
- }
88
+ /** Dispatch reads are side-effect free; startup owns initialization and its user notice. */
89
+ export async function loadConfig(configPath: string = getConfigPath()): Promise<SubagentsConfig> {
90
+ const stored = await readStoredConfig(configPath);
91
+ if (!stored.exists) return { ...DEFAULT_CONFIG };
92
+ if (!isCurrentConfig(stored.raw)) {
93
+ throw new Error("Worker settings are invalid or incompatible. Run /subagents-setup to initialize the new configuration.");
94
+ }
95
+ const config = normalizeConfig(stored.raw);
96
+ if (stored.raw.model !== undefined && !config.model) {
97
+ throw new Error("Invalid worker model reference. Use provider/model-id or remove model to explicitly follow main.");
176
98
  }
177
-
178
99
  return config;
179
100
  }
180
101
 
181
- /**
182
- * Save config atomically (temp file + rename) serialized through pi's per-file
183
- * mutation queue so concurrent writers cannot interleave.
184
- */
185
- export async function saveConfig(
186
- config: SubagentsConfig,
187
- configPath: string = getConfigPath(),
188
- ): Promise<void> {
189
- const normalized = normalizeConfig(config);
190
- await mkdir(dirname(configPath), { recursive: true });
191
- await withFileMutationQueue(configPath, async () => {
192
- const temporaryPath = `${configPath}.${process.pid}.${Date.now()}.tmp`;
193
- try {
194
- await writeFile(temporaryPath, `${JSON.stringify(normalized, null, 2)}\n`, "utf8");
195
- await rename(temporaryPath, configPath);
196
- } finally {
197
- await rm(temporaryPath, { force: true }).catch(() => undefined);
198
- }
199
- });
102
+ export async function saveConfig(config: SubagentsConfig, configPath: string = getConfigPath()): Promise<void> {
103
+ await withFileMutationQueue(configPath, () => writeConfig(normalizeConfig(config), configPath));
200
104
  }
201
105
 
202
106
  export function errorMessage(error: unknown): string {
@@ -1,8 +1,8 @@
1
1
  /*
2
2
  * Model routing, capability-aware thinking, and setup-picker helpers.
3
3
  *
4
- * Runtime has one explicit fallback only: a configured agent model hands
5
- * off directly to the current main-window model. Setup lists only currently
4
+ * A configured worker never escalates to the main model automatically.
5
+ * Setup lists only currently
6
6
  * available models and derives thinking choices from Pi's model metadata.
7
7
  */
8
8
 
@@ -35,9 +35,7 @@ export type ModelListEntry = Pick<
35
35
  export interface ResolvedAgentModelRoute {
36
36
  /** Effective first candidate. Undefined means let Pi use its normal default. */
37
37
  primaryRef?: string;
38
- /** Current main-window model when it differs from the selection. */
39
- mainFallbackRef?: string;
40
- /** Configured ref skipped because Pi does not currently report it available. */
38
+ /** Configured ref that blocks dispatch until it is available or changed. */
41
39
  unavailableSelectedRef?: string;
42
40
  }
43
41
 
@@ -55,8 +53,8 @@ function cleanModelRef(ref: string | undefined): string | undefined {
55
53
 
56
54
  /**
57
55
  * Provider ids Pi renamed while keeping the model id. Pi 1.0.3 renamed
58
- * `azure-openai-responses` to `azure`. The old id stays valid on earlier 1.0
59
- * hosts, so a stored override follows whichever id the live catalog still has.
56
+ * `azure-openai-responses` to `azure`. Custom registries can still expose
57
+ * either id, so prefer the exact selection before trying its published alias.
60
58
  */
61
59
  const RENAMED_PROVIDER_IDS: Readonly<Record<string, string>> = {
62
60
  "azure-openai-responses": "azure",
@@ -108,37 +106,15 @@ export function findModelByRef(
108
106
  ): Model<Api> | undefined {
109
107
  const normalized = cleanModelRef(ref);
110
108
  if (!normalized) return undefined;
111
- const aliases = new Set(modelRefAliases(normalized));
112
- return models.find((model) => aliases.has(modelRef(model)));
113
- }
114
-
115
- /** Split persisted agent model overrides into the ones Pi still reports as
116
- * available and the stale ones. Stale refs are dropped at session start (with
117
- * a user notice) so the config never carries models that can no longer run. */
118
- export function filterUnavailableModelOverrides(
119
- agentModels: Record<string, string>,
120
- models: readonly Model<Api>[],
121
- ): { kept: Record<string, string>; dropped: Array<{ agent: string; ref: string }> } {
122
- const kept: Record<string, string> = {};
123
- const dropped: Array<{ agent: string; ref: string }> = [];
124
- for (const [agent, ref] of Object.entries(agentModels)) {
125
- const model = findModelByRef(models, ref);
126
- // Persist the id the live catalog uses, so a renamed provider does not
127
- // stay stored under the id Pi no longer registers.
128
- if (model) kept[agent] = modelRef(model);
129
- else dropped.push({ agent, ref });
130
- }
131
- return { kept, dropped };
109
+ const liveRef = resolveLiveModelRef(normalized, new Set(models.map(modelRef)));
110
+ return models.find((model) => modelRef(model) === liveRef);
132
111
  }
133
112
 
134
113
  /**
135
114
  * Resolve one agent's runtime route:
136
115
  *
137
- * configured selection -> current main-window model
138
- *
139
- * Without an override the current main model is primary, so an agent never
140
- * pins its own model. A configured selection that Pi no longer reports as
141
- * available is skipped immediately instead of spawning a doomed child.
116
+ * Without an override the current main model is primary. An unavailable
117
+ * configured selection blocks dispatch instead of spending main-model quota.
142
118
  */
143
119
  export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAgentModelRoute {
144
120
  const selectedRef = cleanModelRef(input.selectedRef);
@@ -148,8 +124,7 @@ export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAge
148
124
  : undefined;
149
125
  const resolvedSelectedRef = selectedRef ? resolveLiveModelRef(selectedRef, available) : undefined;
150
126
  return {
151
- primaryRef: resolvedSelectedRef ?? mainRef,
152
- ...(resolvedSelectedRef && mainRef && resolvedSelectedRef !== mainRef ? { mainFallbackRef: mainRef } : {}),
127
+ primaryRef: selectedRef ? resolvedSelectedRef : mainRef,
153
128
  ...(selectedRef && !resolvedSelectedRef ? { unavailableSelectedRef: selectedRef } : {}),
154
129
  };
155
130
  }
@@ -215,21 +190,9 @@ export function buildModelPickerItems(options: {
215
190
  items.push({
216
191
  value: ref,
217
192
  label: name + " · " + model.provider + (duplicateName ? " (" + model.id + ")" : ""),
218
- description: ["Reference: " + ref, "Pins this model; falls back to main if unavailable or it fails.", modelCapabilities(model), ...tags].join(" · "),
193
+ description: ["Reference: " + ref, "Pins this worker; failures return to main without changing models.", modelCapabilities(model), ...tags].join(" · "),
219
194
  saved: ref === liveConfiguredRef,
220
195
  });
221
196
  }
222
197
  return items;
223
198
  }
224
-
225
- /** The dynamic choice removes the persisted per-agent override. */
226
- export function applyAgentModelChoice(
227
- current: Record<string, string>,
228
- agentName: string,
229
- choice: string,
230
- ): Record<string, string> {
231
- const next = { ...current };
232
- if (choice === CURRENT_MAIN_MODEL) delete next[agentName];
233
- else next[agentName] = choice.trim();
234
- return next;
235
- }