@ferris1225/pi-subagents 6.0.5 → 7.0.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/CHANGELOG.md +56 -0
- package/README.md +233 -266
- package/index.ts +13 -12
- package/package.json +11 -10
- package/src/configuration/config.ts +76 -158
- package/src/configuration/models.ts +15 -85
- package/src/configuration/setup.ts +82 -165
- package/src/configuration/ui.ts +97 -178
- package/src/delegation/agents.ts +7 -7
- package/src/delegation/builtin-agents.ts +11 -30
- package/src/delegation/dispatch.ts +18 -28
- package/src/delegation/orchestration.ts +26 -0
- package/src/delegation/prompt.ts +13 -19
- package/src/execution/cli-run.ts +9 -7
- package/src/execution/run-control.ts +5 -7
- package/src/execution/spawn.ts +36 -160
- package/src/isolation/git-command.ts +2 -2
- package/src/isolation/recovery.ts +8 -24
- package/src/isolation/temp-hygiene.ts +1 -1
- package/src/lifecycle/completion.ts +2 -13
- package/src/lifecycle/durable.ts +17 -34
- package/src/lifecycle/stop.ts +2 -2
- package/src/lifecycle/thread-lifecycle.ts +7 -7
- package/src/lifecycle/thread-restore.ts +4 -6
- package/src/lifecycle/thread-shared.ts +12 -20
- package/src/lifecycle/tools.ts +2 -4
- package/src/presentation/announcements.ts +17 -23
- package/src/presentation/format.ts +5 -6
- package/src/presentation/monitor.ts +2 -7
- package/src/configuration/role-migration.ts +0 -39
package/index.ts
CHANGED
|
@@ -21,11 +21,12 @@
|
|
|
21
21
|
|
|
22
22
|
import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
23
23
|
import { Text } from "@earendil-works/pi-tui";
|
|
24
|
-
import { getConfigPath } from "./src/configuration/config.ts";
|
|
24
|
+
import { errorMessage, getConfigPath, loadConfig } from "./src/configuration/config.ts";
|
|
25
25
|
import { runSetup } from "./src/configuration/setup.ts";
|
|
26
26
|
import { loadBuiltinAgents } from "./src/delegation/agents.ts";
|
|
27
27
|
import { registerSubagentTool } from "./src/delegation/dispatch.ts";
|
|
28
|
-
import {
|
|
28
|
+
import { installDelegationSections } from "./src/delegation/prompt.ts";
|
|
29
|
+
import { buildOrchestrationSection } from "./src/delegation/orchestration.ts";
|
|
29
30
|
import { currentSubagentDepth, getSubagentsRoot } from "./src/execution/spawn.ts";
|
|
30
31
|
import { createDispatchCore } from "./src/lifecycle/dispatch-core.ts";
|
|
31
32
|
import { registerCancellationHooks } from "./src/lifecycle/cancellation.ts";
|
|
@@ -73,7 +74,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
73
74
|
registerCancellationHooks(pi, runtime);
|
|
74
75
|
|
|
75
76
|
pi.registerCommand("subagents-setup", {
|
|
76
|
-
description: "Configure
|
|
77
|
+
description: "Configure Researcher and Worker models and thinking levels",
|
|
77
78
|
handler: async (_args, ctx) => {
|
|
78
79
|
await runSetup(ctx, configPath);
|
|
79
80
|
},
|
|
@@ -110,19 +111,19 @@ export default function (pi: ExtensionAPI): void {
|
|
|
110
111
|
});
|
|
111
112
|
registerAnnouncements(pi, runtime);
|
|
112
113
|
|
|
113
|
-
// Install the routing contract as prompt sections
|
|
114
|
+
// Install the routing contract as replaceable prompt sections.
|
|
114
115
|
// A full systemPrompt return forces an opaque prompt and invalidates the cache.
|
|
115
|
-
pi.on("before_agent_start", async (event) => {
|
|
116
|
+
pi.on("before_agent_start", async (event, ctx) => {
|
|
116
117
|
await runtime.durableRestore;
|
|
117
118
|
const agents = loadBuiltinAgents();
|
|
118
119
|
const sources = [...runtime.threads.values()];
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
120
|
+
let orchestration: string;
|
|
121
|
+
try {
|
|
122
|
+
orchestration = buildOrchestrationSection(await loadConfig(configPath), ctx);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
orchestration = "Worker dispatch is paused because settings could not be loaded: " + errorMessage(error)
|
|
125
|
+
+ " Repair the settings or run /subagents-setup. Do not substitute main-model workers.";
|
|
123
126
|
}
|
|
124
|
-
|
|
125
|
-
if (!directive) return undefined;
|
|
126
|
-
return { systemPrompt: `${event.systemPrompt}\n${directive}` };
|
|
127
|
+
installDelegationSections(event.systemPromptOptions.sections, agents, sources, orchestration);
|
|
127
128
|
});
|
|
128
129
|
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ferris1225/pi-subagents",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "7.0.1",
|
|
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.
|
|
44
|
-
"@earendil-works/pi-coding-agent": ">=1.5.
|
|
45
|
-
"@earendil-works/pi-tui": ">=1.5.
|
|
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": "
|
|
50
|
-
"@earendil-works/pi-coding-agent": "
|
|
51
|
-
"@earendil-works/pi-tui": "
|
|
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,120 @@
|
|
|
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
|
+
/** Independent role settings. Unsupported configuration is replaced with defaults. */
|
|
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
|
-
|
|
20
|
-
export const BUILTIN_AGENT_NAMES = ["
|
|
21
|
-
|
|
22
|
-
/** Thinking levels accepted by pi's `--thinking` option. */
|
|
7
|
+
export const CONFIG_VERSION = 2;
|
|
8
|
+
export const BUILTIN_AGENT_NAMES = ["researcher", "worker"] as const;
|
|
9
|
+
export type AgentName = (typeof BUILTIN_AGENT_NAMES)[number];
|
|
23
10
|
const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
24
11
|
export type ThinkingLevel = (typeof THINKING_LEVEL_VALUES)[number];
|
|
25
12
|
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
13
|
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
14
|
export const DEFAULT_IDLE_TIMEOUT_SEC = 1800;
|
|
74
15
|
|
|
75
|
-
export interface
|
|
76
|
-
/**
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
* the role default from `roleThinkingLevel`. */
|
|
80
|
-
agentThinkingLevels: Record<string, ThinkingLevel>;
|
|
16
|
+
export interface AgentSettings {
|
|
17
|
+
/** Missing follows the main model. */
|
|
18
|
+
model?: string;
|
|
19
|
+
thinking: ThinkingLevel;
|
|
81
20
|
}
|
|
82
21
|
|
|
83
|
-
|
|
84
|
-
export const DEFAULT_CONFIG: SubagentsConfig = defaultConfig();
|
|
22
|
+
export type SubagentsConfig = { version: typeof CONFIG_VERSION } & Record<AgentName, AgentSettings>;
|
|
85
23
|
|
|
86
|
-
export
|
|
87
|
-
|
|
88
|
-
|
|
24
|
+
export const DEFAULT_AGENT_SETTINGS: Readonly<AgentSettings> = Object.freeze({ thinking: DEFAULT_THINKING_LEVEL });
|
|
25
|
+
export const DEFAULT_CONFIG: Readonly<SubagentsConfig> = {
|
|
26
|
+
version: CONFIG_VERSION,
|
|
27
|
+
researcher: DEFAULT_AGENT_SETTINGS,
|
|
28
|
+
worker: DEFAULT_AGENT_SETTINGS,
|
|
29
|
+
};
|
|
89
30
|
|
|
90
|
-
function
|
|
91
|
-
return
|
|
31
|
+
export function getConfigPath(agentDir: string = getAgentDir()): string {
|
|
32
|
+
return join(agentDir, "pi-subagents.json");
|
|
92
33
|
}
|
|
93
34
|
|
|
94
|
-
function
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
35
|
+
function isCurrentConfig(raw: unknown): raw is Record<string, unknown> {
|
|
36
|
+
return typeof raw === "object" && raw !== null && !Array.isArray(raw)
|
|
37
|
+
&& (raw as Record<string, unknown>).version === CONFIG_VERSION
|
|
38
|
+
&& BUILTIN_AGENT_NAMES.every((role) => {
|
|
39
|
+
const settings = (raw as Record<string, unknown>)[role];
|
|
40
|
+
return typeof settings === "object" && settings !== null && !Array.isArray(settings);
|
|
41
|
+
});
|
|
99
42
|
}
|
|
100
43
|
|
|
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
44
|
export function normalizeConfig(raw: unknown): SubagentsConfig {
|
|
107
|
-
const config =
|
|
108
|
-
if (!
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
}
|
|
45
|
+
const config: SubagentsConfig = { version: CONFIG_VERSION, researcher: { ...DEFAULT_AGENT_SETTINGS }, worker: { ...DEFAULT_AGENT_SETTINGS } };
|
|
46
|
+
if (!isCurrentConfig(raw)) return config;
|
|
47
|
+
for (const role of BUILTIN_AGENT_NAMES) {
|
|
48
|
+
const settings = raw[role] as Record<string, unknown>;
|
|
49
|
+
if (typeof settings.model === "string") {
|
|
50
|
+
const model = settings.model.trim();
|
|
51
|
+
const slash = model.indexOf("/");
|
|
52
|
+
if (slash > 0 && slash < model.length - 1 && !/\s/u.test(model)) config[role].model = model;
|
|
116
53
|
}
|
|
117
|
-
|
|
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
|
-
}
|
|
54
|
+
if (typeof settings.thinking === "string" && (THINKING_LEVEL_VALUES as readonly string[]).includes(settings.thinking)) {
|
|
55
|
+
config[role].thinking = settings.thinking as ThinkingLevel;
|
|
129
56
|
}
|
|
130
57
|
}
|
|
131
|
-
|
|
132
|
-
config.agentModels = migrateStoredRoleKeys(config.agentModels);
|
|
133
|
-
config.agentThinkingLevels = migrateStoredRoleKeys(config.agentThinkingLevels);
|
|
134
58
|
return config;
|
|
135
59
|
}
|
|
136
60
|
|
|
137
|
-
function
|
|
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> {
|
|
61
|
+
async function readStoredConfig(configPath: string): Promise<{ exists: boolean; raw?: unknown }> {
|
|
152
62
|
let text: string;
|
|
153
63
|
try {
|
|
154
64
|
text = await readFile(configPath, "utf8");
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { exists: false };
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
return { exists: true, raw: JSON.parse(text) };
|
|
155
71
|
} catch {
|
|
156
|
-
|
|
157
|
-
return defaultConfig();
|
|
72
|
+
return { exists: true };
|
|
158
73
|
}
|
|
74
|
+
}
|
|
159
75
|
|
|
160
|
-
|
|
76
|
+
/** Replace settings atomically. Callers own the mutation queue. */
|
|
77
|
+
async function writeConfig(config: SubagentsConfig, configPath: string): Promise<void> {
|
|
78
|
+
await mkdir(dirname(configPath), { recursive: true });
|
|
79
|
+
const temporaryPath = configPath + "." + process.pid + "." + Date.now() + ".tmp";
|
|
161
80
|
try {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
81
|
+
await writeFile(temporaryPath, JSON.stringify(config, null, 2) + "\n", "utf8");
|
|
82
|
+
await rename(temporaryPath, configPath);
|
|
83
|
+
} finally {
|
|
84
|
+
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
165
85
|
}
|
|
86
|
+
}
|
|
166
87
|
|
|
167
|
-
|
|
88
|
+
/** Called at startup and setup. A reset affects this config file only, never recovery artifacts. */
|
|
89
|
+
export async function initializeConfig(configPath: string = getConfigPath()): Promise<"created" | "reset" | undefined> {
|
|
90
|
+
return withFileMutationQueue(configPath, async () => {
|
|
91
|
+
const stored = await readStoredConfig(configPath);
|
|
92
|
+
const raw = stored.raw;
|
|
93
|
+
if (isCurrentConfig(raw) && BUILTIN_AGENT_NAMES.every((role) =>
|
|
94
|
+
(raw[role] as Record<string, unknown>).model === undefined || normalizeConfig(raw)[role].model)) return undefined;
|
|
95
|
+
await writeConfig(normalizeConfig(undefined), configPath);
|
|
96
|
+
return stored.exists ? "reset" : "created";
|
|
97
|
+
});
|
|
98
|
+
}
|
|
168
99
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
100
|
+
/** Dispatch reads are side-effect free; startup owns initialization and its user notice. */
|
|
101
|
+
export async function loadConfig(configPath: string = getConfigPath()): Promise<SubagentsConfig> {
|
|
102
|
+
const stored = await readStoredConfig(configPath);
|
|
103
|
+
if (!stored.exists) return normalizeConfig(undefined);
|
|
104
|
+
if (!isCurrentConfig(stored.raw)) {
|
|
105
|
+
throw new Error("Subagent settings are invalid or unsupported. Run /subagents-setup to initialize the current configuration.");
|
|
106
|
+
}
|
|
107
|
+
const config = normalizeConfig(stored.raw);
|
|
108
|
+
for (const role of BUILTIN_AGENT_NAMES) {
|
|
109
|
+
if ((stored.raw[role] as Record<string, unknown>).model !== undefined && !config[role].model) {
|
|
110
|
+
throw new Error(`Invalid ${role} model reference. Use provider/model-id or remove model to explicitly follow main.`);
|
|
175
111
|
}
|
|
176
112
|
}
|
|
177
|
-
|
|
178
113
|
return config;
|
|
179
114
|
}
|
|
180
115
|
|
|
181
|
-
|
|
182
|
-
|
|
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
|
-
});
|
|
116
|
+
export async function saveConfig(config: SubagentsConfig, configPath: string = getConfigPath()): Promise<void> {
|
|
117
|
+
await withFileMutationQueue(configPath, () => writeConfig(normalizeConfig(config), configPath));
|
|
200
118
|
}
|
|
201
119
|
|
|
202
120
|
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
|
-
*
|
|
5
|
-
*
|
|
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
|
|
|
@@ -15,8 +15,7 @@ import {
|
|
|
15
15
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
16
16
|
import { DEFAULT_THINKING_LEVEL, type ThinkingLevel } from "./config.ts";
|
|
17
17
|
|
|
18
|
-
export type ModelContext = Pick<ExtensionContext, "model" | "modelRegistry"
|
|
19
|
-
Partial<Pick<ExtensionContext, "scopedModels">>;
|
|
18
|
+
export type ModelContext = Pick<ExtensionContext, "model" | "modelRegistry" | "scopedModels">;
|
|
20
19
|
|
|
21
20
|
export const CURRENT_MAIN_MODEL = "__current_main_model__";
|
|
22
21
|
|
|
@@ -35,9 +34,7 @@ export type ModelListEntry = Pick<
|
|
|
35
34
|
export interface ResolvedAgentModelRoute {
|
|
36
35
|
/** Effective first candidate. Undefined means let Pi use its normal default. */
|
|
37
36
|
primaryRef?: string;
|
|
38
|
-
/**
|
|
39
|
-
mainFallbackRef?: string;
|
|
40
|
-
/** Configured ref skipped because Pi does not currently report it available. */
|
|
37
|
+
/** Configured ref that blocks dispatch until it is available or changed. */
|
|
41
38
|
unavailableSelectedRef?: string;
|
|
42
39
|
}
|
|
43
40
|
|
|
@@ -53,32 +50,6 @@ function cleanModelRef(ref: string | undefined): string | undefined {
|
|
|
53
50
|
return trimmed || undefined;
|
|
54
51
|
}
|
|
55
52
|
|
|
56
|
-
/**
|
|
57
|
-
* 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.
|
|
60
|
-
*/
|
|
61
|
-
const RENAMED_PROVIDER_IDS: Readonly<Record<string, string>> = {
|
|
62
|
-
"azure-openai-responses": "azure",
|
|
63
|
-
};
|
|
64
|
-
|
|
65
|
-
/** Stored ref plus the renamed provider id, when Pi published one. */
|
|
66
|
-
function modelRefAliases(ref: string): readonly string[] {
|
|
67
|
-
const normalized = ref.trim();
|
|
68
|
-
const slash = normalized.indexOf("/");
|
|
69
|
-
if (slash <= 0 || slash >= normalized.length - 1) return [normalized];
|
|
70
|
-
const renamed = RENAMED_PROVIDER_IDS[normalized.slice(0, slash)];
|
|
71
|
-
if (!renamed) return [normalized];
|
|
72
|
-
return [normalized, `${renamed}${normalized.slice(slash)}`];
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
/** Prefer the alias that the live catalog actually lists. */
|
|
76
|
-
function resolveLiveModelRef(ref: string, liveRefs: ReadonlySet<string> | undefined): string | undefined {
|
|
77
|
-
const aliases = modelRefAliases(ref);
|
|
78
|
-
if (!liveRefs) return aliases[0];
|
|
79
|
-
return aliases.find((candidate) => liveRefs.has(candidate));
|
|
80
|
-
}
|
|
81
|
-
|
|
82
53
|
export function modelRef(model: { provider: string; id: string }): string {
|
|
83
54
|
return `${model.provider}/${model.id}`;
|
|
84
55
|
}
|
|
@@ -94,9 +65,7 @@ export function currentModelRef(ctx: Pick<ModelContext, "model">): string | unde
|
|
|
94
65
|
*/
|
|
95
66
|
export function availableModelsInScope(ctx: ModelContext): readonly Model<Api>[] {
|
|
96
67
|
const models = ctx.modelRegistry.getAvailable();
|
|
97
|
-
|
|
98
|
-
// exactly like an empty scope and use the full live registry.
|
|
99
|
-
const scopedModels = ctx.scopedModels ?? [];
|
|
68
|
+
const scopedModels = ctx.scopedModels;
|
|
100
69
|
if (scopedModels.length === 0) return models;
|
|
101
70
|
const scopedRefs = new Set(scopedModels.map((entry) => modelRef(entry.model)));
|
|
102
71
|
return models.filter((model) => scopedRefs.has(modelRef(model)));
|
|
@@ -108,37 +77,14 @@ export function findModelByRef(
|
|
|
108
77
|
): Model<Api> | undefined {
|
|
109
78
|
const normalized = cleanModelRef(ref);
|
|
110
79
|
if (!normalized) return undefined;
|
|
111
|
-
|
|
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 };
|
|
80
|
+
return models.find((model) => modelRef(model) === normalized);
|
|
132
81
|
}
|
|
133
82
|
|
|
134
83
|
/**
|
|
135
84
|
* Resolve one agent's runtime route:
|
|
136
85
|
*
|
|
137
|
-
*
|
|
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.
|
|
86
|
+
* Without an override the current main model is primary. An unavailable
|
|
87
|
+
* configured selection blocks dispatch instead of spending main-model quota.
|
|
142
88
|
*/
|
|
143
89
|
export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAgentModelRoute {
|
|
144
90
|
const selectedRef = cleanModelRef(input.selectedRef);
|
|
@@ -146,10 +92,9 @@ export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAge
|
|
|
146
92
|
const available = input.availableRefs
|
|
147
93
|
? new Set(input.availableRefs.map((ref) => ref.trim()).filter(Boolean))
|
|
148
94
|
: undefined;
|
|
149
|
-
const resolvedSelectedRef = selectedRef
|
|
95
|
+
const resolvedSelectedRef = selectedRef && (!available || available.has(selectedRef)) ? selectedRef : undefined;
|
|
150
96
|
return {
|
|
151
|
-
primaryRef: resolvedSelectedRef
|
|
152
|
-
...(resolvedSelectedRef && mainRef && resolvedSelectedRef !== mainRef ? { mainFallbackRef: mainRef } : {}),
|
|
97
|
+
primaryRef: selectedRef ? resolvedSelectedRef : mainRef,
|
|
153
98
|
...(selectedRef && !resolvedSelectedRef ? { unavailableSelectedRef: selectedRef } : {}),
|
|
154
99
|
};
|
|
155
100
|
}
|
|
@@ -187,14 +132,11 @@ export function buildModelPickerItems(options: {
|
|
|
187
132
|
if (!byRef.has(ref)) byRef.set(ref, model);
|
|
188
133
|
}
|
|
189
134
|
const configuredRef = cleanModelRef(options.configuredRef);
|
|
190
|
-
const liveConfiguredRef = configuredRef
|
|
191
|
-
? resolveLiveModelRef(configuredRef, new Set(byRef.keys())) ?? configuredRef
|
|
192
|
-
: undefined;
|
|
193
135
|
|
|
194
136
|
const refs = [...byRef.keys()]
|
|
195
137
|
.sort((left, right) => {
|
|
196
|
-
const leftRank = left ===
|
|
197
|
-
const rightRank = right ===
|
|
138
|
+
const leftRank = left === configuredRef ? 0 : left === mainRef ? 1 : 2;
|
|
139
|
+
const rightRank = right === configuredRef ? 0 : right === mainRef ? 1 : 2;
|
|
198
140
|
return leftRank - rightRank || left.localeCompare(right);
|
|
199
141
|
});
|
|
200
142
|
|
|
@@ -207,7 +149,7 @@ export function buildModelPickerItems(options: {
|
|
|
207
149
|
const items: ModelPickerItem[] = [dynamic];
|
|
208
150
|
for (const ref of refs) {
|
|
209
151
|
const model = byRef.get(ref)!;
|
|
210
|
-
const tags = [ref ===
|
|
152
|
+
const tags = [ref === configuredRef ? "configured" : "", ref === mainRef ? "current main" : ""]
|
|
211
153
|
.filter(Boolean);
|
|
212
154
|
const name = model.name.trim() || model.id;
|
|
213
155
|
const duplicateName = [...byRef.values()].some((other) =>
|
|
@@ -215,21 +157,9 @@ export function buildModelPickerItems(options: {
|
|
|
215
157
|
items.push({
|
|
216
158
|
value: ref,
|
|
217
159
|
label: name + " · " + model.provider + (duplicateName ? " (" + model.id + ")" : ""),
|
|
218
|
-
description: ["Reference: " + ref, "Pins this
|
|
219
|
-
saved: ref ===
|
|
160
|
+
description: ["Reference: " + ref, "Pins this role; failures return to main without changing models.", modelCapabilities(model), ...tags].join(" · "),
|
|
161
|
+
saved: ref === configuredRef,
|
|
220
162
|
});
|
|
221
163
|
}
|
|
222
164
|
return items;
|
|
223
165
|
}
|
|
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
|
-
}
|