@ferris1225/pi-subagents 7.0.0 → 7.0.2
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 +70 -0
- package/README.md +42 -31
- package/index.ts +4 -11
- package/package.json +1 -1
- package/src/configuration/config.ts +65 -31
- package/src/configuration/models.ts +9 -42
- package/src/configuration/setup.ts +56 -33
- package/src/configuration/ui.ts +81 -49
- package/src/delegation/agents.ts +7 -7
- package/src/delegation/builtin-agents.ts +39 -17
- package/src/delegation/dispatch.ts +16 -13
- package/src/delegation/orchestration.ts +11 -7
- package/src/delegation/prompt.ts +24 -20
- package/src/execution/background.ts +1 -2
- package/src/execution/cli-run.ts +26 -10
- package/src/execution/run-control.ts +10 -4
- 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/isolation/worktree.ts +47 -15
- package/src/lifecycle/durable.ts +16 -28
- package/src/lifecycle/runtime.ts +6 -2
- package/src/lifecycle/stop.ts +2 -2
- package/src/lifecycle/thread-lifecycle.ts +7 -29
- package/src/lifecycle/thread-restore.ts +5 -6
- package/src/lifecycle/thread-shared.ts +9 -7
- package/src/lifecycle/tools.ts +15 -9
- package/src/presentation/announcements.ts +24 -15
- package/src/presentation/format.ts +51 -25
- package/src/presentation/monitor.ts +2 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,75 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 7.0.2
|
|
4
|
+
|
|
5
|
+
### Orchestration prompts
|
|
6
|
+
|
|
7
|
+
- Frame main as the orchestrator: spend its effort on decisions, send broad
|
|
8
|
+
searches and multi-file reading to the read-only role, and write briefs a
|
|
9
|
+
weaker worker model can execute without guessing (files, symbols, exact
|
|
10
|
+
check commands, design choices settled first).
|
|
11
|
+
- Give Worker and Researcher an ordered method and a fixed handoff
|
|
12
|
+
(`Status/Changes/Checks/Notes`, `Answer/Evidence/Gaps`) so cheaper models stay
|
|
13
|
+
predictable and main reviews faster.
|
|
14
|
+
- After a failed run, re-brief with the correction instead of defaulting to
|
|
15
|
+
doing the work in main. Parallel duplicate rejections now give the same
|
|
16
|
+
follow-up remedy as single dispatch (continue the owner with `subagent_message`).
|
|
17
|
+
- The live orchestration section no longer asks main to run `/subagents-setup`,
|
|
18
|
+
which only the user can do.
|
|
19
|
+
|
|
20
|
+
### Fixes
|
|
21
|
+
|
|
22
|
+
- Worktree integration patches ignore user diff settings (`diff.external`,
|
|
23
|
+
textconv, `diff.noprefix`, `color.ui=always`) that could break or misplace
|
|
24
|
+
`git apply`.
|
|
25
|
+
- On POSIX, an unignored `node_modules` symlink no longer enters every patch;
|
|
26
|
+
the link is removed with `unlink`, never touching the shared dependency tree.
|
|
27
|
+
- Windows long paths apply to every worktree Git command, not only removal.
|
|
28
|
+
- A failing `git worktree prune` after artifacts are already gone no longer
|
|
29
|
+
marks a successful integration as failed.
|
|
30
|
+
- A run stopped just before its child spawned no longer stays `interrupting`
|
|
31
|
+
forever and blocks its phase, and no longer launches a child that is killed
|
|
32
|
+
at once.
|
|
33
|
+
- A worker that settled with a complete answer but whose Pi process shut down
|
|
34
|
+
slower than the grace period is no longer reported as a failed dispatch.
|
|
35
|
+
- Settled runs no longer persist dead child pids that a reused pid could match.
|
|
36
|
+
- Interrupted records keep their original timestamp across restarts, so the
|
|
37
|
+
30-day expiry actually applies.
|
|
38
|
+
- `subagent_stop` requires an exact run id (`#12` accepted); a prefix such as
|
|
39
|
+
`1` no longer stops `#12` and `#15`.
|
|
40
|
+
- A result file that cannot be written no longer loses a successful result;
|
|
41
|
+
a bounded head is inlined with the save error instead.
|
|
42
|
+
- Startup keeps an unreadable or invalid current settings file (and accepts a
|
|
43
|
+
UTF-8 BOM) instead of silently resetting roles to follow main;
|
|
44
|
+
`/subagents-setup` repairs it, keeping every valid field.
|
|
45
|
+
- The startup availability warning uses the session's scoped models, matching
|
|
46
|
+
dispatch.
|
|
47
|
+
- Parallel dispatch applies a top-level `isolation` as the default for tasks.
|
|
48
|
+
- Model-failure notes name the actual role instead of always saying "worker".
|
|
49
|
+
- Remove an unreachable queue cancellation callback and a dead diff branch.
|
|
50
|
+
|
|
51
|
+
## 7.0.1
|
|
52
|
+
|
|
53
|
+
### Breaking changes
|
|
54
|
+
|
|
55
|
+
- Rename `scout` to `researcher` and `artisan` to `worker`, without aliases.
|
|
56
|
+
- Overwrite old settings with configuration version 2. Researcher and Worker
|
|
57
|
+
each have an independent model and thinking preference; neither is migrated.
|
|
58
|
+
- Remove provider aliases, older Pi API shims, opaque-prompt fallback, recovery
|
|
59
|
+
path migration, synthesized record identities, and legacy steering receipts.
|
|
60
|
+
Unsupported recovery files remain untouched and prevent automated cleanup.
|
|
61
|
+
|
|
62
|
+
### Fixes and changes
|
|
63
|
+
|
|
64
|
+
- Restore model selection for each role throughout setup, dispatch, and live
|
|
65
|
+
orchestration. An unavailable model blocks only its assigned role.
|
|
66
|
+
- Redesign setup into Researcher and Worker sections with visible Model,
|
|
67
|
+
Thinking, and role-specific Reset controls. Preserve search, paging, focus,
|
|
68
|
+
Unicode input, and a compact layout for narrow terminals.
|
|
69
|
+
- Keep config replacement atomic and recovery ownership checks intact.
|
|
70
|
+
- Keep automatic releases on patch increments, including three-digit patch
|
|
71
|
+
numbers such as `7.0.100`.
|
|
72
|
+
|
|
3
73
|
## 7.0.0
|
|
4
74
|
|
|
5
75
|
### Breaking changes
|
package/README.md
CHANGED
|
@@ -17,20 +17,23 @@ integration tests use the **Pi 1.5.2 SDK**.
|
|
|
17
17
|
```
|
|
18
18
|
|
|
19
19
|
2. Choose a capable main model with Pi's model selector; it always owns review.
|
|
20
|
-
3. Run `/subagents-setup` and
|
|
20
|
+
3. Run `/subagents-setup` and choose models for **Researcher** and **Worker**.
|
|
21
21
|
4. Give main your task. Orchestration is the default and only workflow.
|
|
22
22
|
|
|
23
|
-
The setup panel has
|
|
23
|
+
The setup panel has two sections: **Researcher** for read-only research and
|
|
24
|
+
**Worker** for implementation and checks. Each has its own **Model**, **Thinking**,
|
|
25
|
+
and **Reset** controls. Both assignments stay visible together.
|
|
24
26
|
Use ↑/↓ and Enter; Esc returns without changing a picker selection. Changes save
|
|
25
27
|
immediately. The model picker supports search, paste, paging, and Tab for details.
|
|
26
|
-
The menu keeps the current main model visible
|
|
27
|
-
|
|
28
|
+
The menu keeps the current main model visible, highlights unavailable assignments,
|
|
29
|
+
and returns focus to the setting you just edited. Long values can be paged with
|
|
30
|
+
PgUp/PgDn, and narrow terminals use a compact list with the role on each row.
|
|
28
31
|
|
|
29
32
|
Workers initially **follow main** with **medium** thinking. Choose a separate
|
|
30
33
|
worker model to use a cheaper model for execution. The extension does not guess
|
|
31
34
|
model quality or promise savings from token prices. A saved thinking preference
|
|
32
35
|
survives model changes and is clamped to the chosen model's supported levels.
|
|
33
|
-
Reset restores Follow main and medium thinking.
|
|
36
|
+
Reset restores Follow main and medium thinking for that role only.
|
|
34
37
|
|
|
35
38
|
The goal is to reduce expensive main-model usage, budget, and quota consumption.
|
|
36
39
|
Total tokens can increase because briefs, separate contexts, and review also cost
|
|
@@ -38,37 +41,42 @@ tokens. Judge savings by total task cost and main-model usage, including retries
|
|
|
38
41
|
and rework. Compact handoffs, retained worker sessions, reuse of valid checks, and
|
|
39
42
|
delegating execution are the mechanisms; no savings benchmark is claimed here.
|
|
40
43
|
|
|
41
|
-
##
|
|
44
|
+
## Configuration and upgrading to 7.0.1
|
|
42
45
|
|
|
43
|
-
**This
|
|
44
|
-
old `pi-subagents.json` is
|
|
45
|
-
|
|
46
|
+
**This update resets settings and renames roles.** On the first session start after upgrading, the
|
|
47
|
+
old `pi-subagents.json` is atomically overwritten with fresh, independent role settings.
|
|
48
|
+
Previous model/thinking values are discarded, with no migration or config backup.
|
|
46
49
|
Pi displays a notice directing you to `/subagents-setup`.
|
|
47
50
|
|
|
48
|
-
The
|
|
49
|
-
|
|
50
|
-
|
|
51
|
+
The role names are now `researcher` and `worker`; previous names are rejected.
|
|
52
|
+
Main continues to own planning and review. There are no role or provider aliases,
|
|
53
|
+
old SDK shims, or recovery-path migrations. Model references must exactly match
|
|
54
|
+
the available registry entry.
|
|
51
55
|
|
|
52
56
|
Only the settings file is reset. Existing sessions, results, worktrees, and
|
|
53
|
-
recovery evidence remain protected.
|
|
54
|
-
|
|
57
|
+
recovery evidence remain protected. Unsupported recovery manifests are left
|
|
58
|
+
untouched and block automated cleanup; they are not converted or resumed.
|
|
55
59
|
|
|
56
60
|
The new configuration is stored at `~/.pi/agent/pi-subagents.json`:
|
|
57
61
|
|
|
58
62
|
```json
|
|
59
63
|
{
|
|
60
|
-
"version":
|
|
61
|
-
"thinking": "medium"
|
|
64
|
+
"version": 2,
|
|
65
|
+
"researcher": { "thinking": "medium" },
|
|
66
|
+
"worker": { "thinking": "medium" }
|
|
62
67
|
}
|
|
63
68
|
```
|
|
64
69
|
|
|
65
|
-
Selecting a
|
|
66
|
-
|
|
67
|
-
|
|
70
|
+
Selecting a model adds `model: "provider/model-id"` inside that role's object.
|
|
71
|
+
Each role's model and thinking are saved independently.
|
|
72
|
+
`PI_CODING_AGENT_DIR` overrides the agent directory.
|
|
73
|
+
An unavailable or out-of-scope model stays configured and blocks only its role until
|
|
68
74
|
availability is restored or you select another model. Provider failures return
|
|
69
75
|
to main with evidence; the extension never starts a main-model worker as a retry.
|
|
70
76
|
Unreadable settings or an invalid model reference also stop new dispatches instead
|
|
71
|
-
of silently selecting main.
|
|
77
|
+
of silently selecting main. Startup leaves such a file untouched and warns; repair
|
|
78
|
+
it by hand or run `/subagents-setup`, which replaces an unreadable file with
|
|
79
|
+
defaults or clears only the invalid model reference. A UTF-8 BOM is accepted.
|
|
72
80
|
|
|
73
81
|
## How orchestration works
|
|
74
82
|
|
|
@@ -76,9 +84,11 @@ of silently selecting main. Repair the file or run `/subagents-setup`.
|
|
|
76
84
|
determine the approach, resolves ambiguity, and defines acceptance criteria
|
|
77
85
|
and write boundaries. It splits complex tasks into simple worker briefs and
|
|
78
86
|
keeps the difficult core when delegation would create more rework.
|
|
79
|
-
2. **Workers execute.** Main sends a self-contained brief
|
|
80
|
-
|
|
81
|
-
|
|
87
|
+
2. **Workers execute.** Main sends a self-contained brief written so a cheaper
|
|
88
|
+
model can act without guessing: files, symbols, acceptance criteria, write
|
|
89
|
+
boundary, and exact check commands. Each worker owns a bounded task and its
|
|
90
|
+
checks, returning a fixed handoff (`Status`, `Changes`, `Checks`, `Notes`;
|
|
91
|
+
researcher: `Answer`, `Evidence`, `Gaps`) that main can review quickly.
|
|
82
92
|
3. **Main reviews.** After worktree integration, main checks the actual diff,
|
|
83
93
|
relevant callers, acceptance criteria, and test evidence. Worker completion
|
|
84
94
|
is explicitly marked as a review handoff, not approval.
|
|
@@ -94,12 +104,12 @@ reviewer. Main avoids repeating completed worker effort. Questions and review-on
|
|
|
94
104
|
implementation. Explicit requests to work in main take precedence. Parallel workers require independent
|
|
95
105
|
scope and disjoint write ownership; a fix and its regression tests share an owner.
|
|
96
106
|
|
|
97
|
-
There are two
|
|
107
|
+
There are two roles, each using its own model/thinking settings:
|
|
98
108
|
|
|
99
109
|
| Scope | Tool parameter | Access |
|
|
100
110
|
| --- | --- | --- |
|
|
101
|
-
| Implementation | `
|
|
102
|
-
| Read-only research | `
|
|
111
|
+
| Implementation | `worker` | Parent's live tools, including codemode; implements and checks the plan |
|
|
112
|
+
| Read-only research | `researcher` | Proven read-only lookups; no commands, builds, tests, or edits |
|
|
103
113
|
|
|
104
114
|
The read-only scope preserves a tool boundary for research. It is not a separate
|
|
105
115
|
reviewer. Children cannot delegate or release. Main and workers exchange briefs,
|
|
@@ -118,7 +128,7 @@ result**. Pass established facts forward and assign only missing work.
|
|
|
118
128
|
|
|
119
129
|
```ts
|
|
120
130
|
subagent({
|
|
121
|
-
agent: "
|
|
131
|
+
agent: "worker",
|
|
122
132
|
task: [
|
|
123
133
|
"Fix cache invalidation in src/cache.ts and its regression test.",
|
|
124
134
|
"Acceptance: a write invalidates the matching key without clearing unrelated keys.",
|
|
@@ -132,8 +142,9 @@ subagent({
|
|
|
132
142
|
```
|
|
133
143
|
|
|
134
144
|
Independent tasks use `tasks: [{ agent, task }, ...]`. Each task can also specify
|
|
135
|
-
`cwd` and `isolation
|
|
136
|
-
|
|
145
|
+
`cwd` and `isolation`; a top-level `isolation` is the default for tasks that omit
|
|
146
|
+
it. Duplicate normalized tasks in the same cwd are rejected while active or
|
|
147
|
+
settled; reuse the result or continue the existing run with `subagent_message`.
|
|
137
148
|
|
|
138
149
|
Use `wait: true` for an immediate dependency. Print/JSON sessions wait by
|
|
139
150
|
default; TUI/RPC sessions return background receipts. A launch receipt is not
|
|
@@ -146,7 +157,7 @@ Answers exceeding 40 lines or 8,000 characters link their full-result artifact.
|
|
|
146
157
|
| `subagent_status({ id: 12 })` | Inspect progress, result, session availability, and recovery paths |
|
|
147
158
|
| `subagent_message({ id: 12, message: "Fix the remaining edge case", wait: true })` | Steer an active worker or continue completed work |
|
|
148
159
|
| `subagent_message({ id: 12, message: "Next bounded task", context: "summary" })` | Start from a compact summary instead of the earlier transcript |
|
|
149
|
-
| `subagent_stop({ id: "12" })` | Stop a run and retire its retained session |
|
|
160
|
+
| `subagent_stop({ id: "12" })` | Stop a run (exact id; `#12` also accepted) and retire its retained session |
|
|
150
161
|
| `subagent_stop({ all: true })` | Stop all active work in this session |
|
|
151
162
|
|
|
152
163
|
Follow-ups use `context: "auto"` by default: a private copy of the retained session,
|
|
@@ -185,7 +196,7 @@ integration into the original checkout is serialized.
|
|
|
185
196
|
|
|
186
197
|
Workers run the native Pi CLI in RPC mode with piped I/O and retained sessions.
|
|
187
198
|
Delegation/control tools are model-only: call them directly, outside codemode.
|
|
188
|
-
Workers inherit reachable tools without activating unrelated direct tools;
|
|
199
|
+
Workers inherit reachable tools without activating unrelated direct tools; researcher
|
|
189
200
|
gets only tools whose metadata proves them read-only.
|
|
190
201
|
|
|
191
202
|
Unattended confirmation/input dialogs are cancelled, never auto-approved. Windows
|
package/index.ts
CHANGED
|
@@ -25,7 +25,7 @@ import { errorMessage, getConfigPath, loadConfig } from "./src/configuration/con
|
|
|
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
29
|
import { buildOrchestrationSection } from "./src/delegation/orchestration.ts";
|
|
30
30
|
import { currentSubagentDepth, getSubagentsRoot } from "./src/execution/spawn.ts";
|
|
31
31
|
import { createDispatchCore } from "./src/lifecycle/dispatch-core.ts";
|
|
@@ -74,7 +74,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
74
74
|
registerCancellationHooks(pi, runtime);
|
|
75
75
|
|
|
76
76
|
pi.registerCommand("subagents-setup", {
|
|
77
|
-
description: "Configure
|
|
77
|
+
description: "Configure Researcher and Worker models and thinking levels",
|
|
78
78
|
handler: async (_args, ctx) => {
|
|
79
79
|
await runSetup(ctx, configPath);
|
|
80
80
|
},
|
|
@@ -111,7 +111,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
111
111
|
});
|
|
112
112
|
registerAnnouncements(pi, runtime);
|
|
113
113
|
|
|
114
|
-
// Install the routing contract as prompt sections
|
|
114
|
+
// Install the routing contract as replaceable prompt sections.
|
|
115
115
|
// A full systemPrompt return forces an opaque prompt and invalidates the cache.
|
|
116
116
|
pi.on("before_agent_start", async (event, ctx) => {
|
|
117
117
|
await runtime.durableRestore;
|
|
@@ -124,13 +124,6 @@ export default function (pi: ExtensionAPI): void {
|
|
|
124
124
|
orchestration = "Worker dispatch is paused because settings could not be loaded: " + errorMessage(error)
|
|
125
125
|
+ " Repair the settings or run /subagents-setup. Do not substitute main-model workers.";
|
|
126
126
|
}
|
|
127
|
-
|
|
128
|
-
if (sections) {
|
|
129
|
-
installDelegationSections(sections, agents, sources, orchestration);
|
|
130
|
-
return undefined;
|
|
131
|
-
}
|
|
132
|
-
const directive = buildDelegationDirective(agents, sources, orchestration);
|
|
133
|
-
if (!directive) return undefined;
|
|
134
|
-
return { systemPrompt: `${event.systemPrompt}\n${directive}` };
|
|
127
|
+
installDelegationSections(event.systemPromptOptions.sections, agents, sources, orchestration);
|
|
135
128
|
});
|
|
136
129
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ferris1225/pi-subagents",
|
|
3
|
-
"version": "7.0.
|
|
3
|
+
"version": "7.0.2",
|
|
4
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",
|
|
@@ -1,27 +1,31 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/** Independent role settings. Legacy configuration is replaced with defaults; a broken current file is kept until setup repairs it. */
|
|
2
2
|
|
|
3
3
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
|
|
7
|
-
export const CONFIG_VERSION =
|
|
8
|
-
export const BUILTIN_AGENT_NAMES = ["
|
|
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];
|
|
9
10
|
const THINKING_LEVEL_VALUES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
10
11
|
export type ThinkingLevel = (typeof THINKING_LEVEL_VALUES)[number];
|
|
11
12
|
export const DEFAULT_THINKING_LEVEL: ThinkingLevel = "medium";
|
|
12
13
|
export const DEFAULT_MAX_RESULT_LINES = 40;
|
|
13
14
|
export const DEFAULT_IDLE_TIMEOUT_SEC = 1800;
|
|
14
15
|
|
|
15
|
-
export interface
|
|
16
|
-
|
|
17
|
-
/** One worker model for both implementation and read-only research. Missing follows main. */
|
|
16
|
+
export interface AgentSettings {
|
|
17
|
+
/** Missing follows the main model. */
|
|
18
18
|
model?: string;
|
|
19
19
|
thinking: ThinkingLevel;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
export type SubagentsConfig = { version: typeof CONFIG_VERSION } & Record<AgentName, AgentSettings>;
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_AGENT_SETTINGS: Readonly<AgentSettings> = Object.freeze({ thinking: DEFAULT_THINKING_LEVEL });
|
|
22
25
|
export const DEFAULT_CONFIG: Readonly<SubagentsConfig> = {
|
|
23
26
|
version: CONFIG_VERSION,
|
|
24
|
-
|
|
27
|
+
researcher: DEFAULT_AGENT_SETTINGS,
|
|
28
|
+
worker: DEFAULT_AGENT_SETTINGS,
|
|
25
29
|
};
|
|
26
30
|
|
|
27
31
|
export function getConfigPath(agentDir: string = getAgentDir()): string {
|
|
@@ -30,24 +34,31 @@ export function getConfigPath(agentDir: string = getAgentDir()): string {
|
|
|
30
34
|
|
|
31
35
|
function isCurrentConfig(raw: unknown): raw is Record<string, unknown> {
|
|
32
36
|
return typeof raw === "object" && raw !== null && !Array.isArray(raw)
|
|
33
|
-
&& (raw as Record<string, unknown>).version === CONFIG_VERSION
|
|
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
|
+
});
|
|
34
42
|
}
|
|
35
43
|
|
|
36
44
|
export function normalizeConfig(raw: unknown): SubagentsConfig {
|
|
37
|
-
const config: SubagentsConfig = { ...
|
|
45
|
+
const config: SubagentsConfig = { version: CONFIG_VERSION, researcher: { ...DEFAULT_AGENT_SETTINGS }, worker: { ...DEFAULT_AGENT_SETTINGS } };
|
|
38
46
|
if (!isCurrentConfig(raw)) return config;
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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;
|
|
53
|
+
}
|
|
54
|
+
if (typeof settings.thinking === "string" && (THINKING_LEVEL_VALUES as readonly string[]).includes(settings.thinking)) {
|
|
55
|
+
config[role].thinking = settings.thinking as ThinkingLevel;
|
|
56
|
+
}
|
|
46
57
|
}
|
|
47
58
|
return config;
|
|
48
59
|
}
|
|
49
60
|
|
|
50
|
-
async function readStoredConfig(configPath: string): Promise<{ exists: boolean; raw?: unknown }> {
|
|
61
|
+
async function readStoredConfig(configPath: string): Promise<{ exists: boolean; raw?: unknown; parseError?: Error }> {
|
|
51
62
|
let text: string;
|
|
52
63
|
try {
|
|
53
64
|
text = await readFile(configPath, "utf8");
|
|
@@ -55,32 +66,53 @@ async function readStoredConfig(configPath: string): Promise<{ exists: boolean;
|
|
|
55
66
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return { exists: false };
|
|
56
67
|
throw error;
|
|
57
68
|
}
|
|
69
|
+
const clean = text.startsWith("\uFEFF") ? text.slice(1) : text;
|
|
58
70
|
try {
|
|
59
|
-
return { exists: true, raw: JSON.parse(
|
|
60
|
-
} catch {
|
|
61
|
-
return { exists: true };
|
|
71
|
+
return { exists: true, raw: JSON.parse(clean) };
|
|
72
|
+
} catch (error) {
|
|
73
|
+
return { exists: true, parseError: error instanceof Error ? error : new Error(String(error)) };
|
|
62
74
|
}
|
|
63
75
|
}
|
|
64
76
|
|
|
65
|
-
/**
|
|
66
|
-
async function writeConfig(config: SubagentsConfig, configPath: string
|
|
77
|
+
/** Replace settings atomically. Callers own the mutation queue. */
|
|
78
|
+
async function writeConfig(config: SubagentsConfig, configPath: string): Promise<void> {
|
|
67
79
|
await mkdir(dirname(configPath), { recursive: true });
|
|
68
80
|
const temporaryPath = configPath + "." + process.pid + "." + Date.now() + ".tmp";
|
|
69
81
|
try {
|
|
70
82
|
await writeFile(temporaryPath, JSON.stringify(config, null, 2) + "\n", "utf8");
|
|
71
|
-
if (removeLegacy) await rm(configPath, { force: true });
|
|
72
83
|
await rename(temporaryPath, configPath);
|
|
73
84
|
} finally {
|
|
74
85
|
await rm(temporaryPath, { force: true }).catch(() => undefined);
|
|
75
86
|
}
|
|
76
87
|
}
|
|
77
88
|
|
|
78
|
-
|
|
79
|
-
|
|
89
|
+
export type ConfigInitialization = "created" | "reset" | "replaced-unreadable" | "repaired";
|
|
90
|
+
|
|
91
|
+
/** Called at startup and setup. A reset affects this config file only, never recovery artifacts.
|
|
92
|
+
* Legacy shapes are always replaced (the upgrade path). An unreadable file or an invalid
|
|
93
|
+
* current-version field is kept at startup so dispatch fails closed instead of silently
|
|
94
|
+
* following main; only an explicit `repair` (setup) rewrites it, keeping every valid field. */
|
|
95
|
+
export async function initializeConfig(
|
|
96
|
+
configPath: string = getConfigPath(),
|
|
97
|
+
options: { repair?: boolean } = {},
|
|
98
|
+
): Promise<ConfigInitialization | undefined> {
|
|
80
99
|
return withFileMutationQueue(configPath, async () => {
|
|
81
100
|
const stored = await readStoredConfig(configPath);
|
|
82
|
-
if (
|
|
83
|
-
|
|
101
|
+
if (stored.parseError) {
|
|
102
|
+
if (!options.repair) return undefined;
|
|
103
|
+
await writeConfig(normalizeConfig(undefined), configPath);
|
|
104
|
+
return "replaced-unreadable";
|
|
105
|
+
}
|
|
106
|
+
if (isCurrentConfig(stored.raw)) {
|
|
107
|
+
const raw = stored.raw;
|
|
108
|
+
const normalized = normalizeConfig(raw);
|
|
109
|
+
const invalid = BUILTIN_AGENT_NAMES.some((role) =>
|
|
110
|
+
(raw[role] as Record<string, unknown>).model !== undefined && !normalized[role].model);
|
|
111
|
+
if (!options.repair || !invalid) return undefined;
|
|
112
|
+
await writeConfig(normalized, configPath);
|
|
113
|
+
return "repaired";
|
|
114
|
+
}
|
|
115
|
+
await writeConfig(normalizeConfig(undefined), configPath);
|
|
84
116
|
return stored.exists ? "reset" : "created";
|
|
85
117
|
});
|
|
86
118
|
}
|
|
@@ -88,13 +120,15 @@ export async function initializeConfig(configPath: string = getConfigPath()): Pr
|
|
|
88
120
|
/** Dispatch reads are side-effect free; startup owns initialization and its user notice. */
|
|
89
121
|
export async function loadConfig(configPath: string = getConfigPath()): Promise<SubagentsConfig> {
|
|
90
122
|
const stored = await readStoredConfig(configPath);
|
|
91
|
-
if (!stored.exists) return
|
|
123
|
+
if (!stored.exists) return normalizeConfig(undefined);
|
|
92
124
|
if (!isCurrentConfig(stored.raw)) {
|
|
93
|
-
throw new Error("
|
|
125
|
+
throw new Error("Subagent settings are invalid or unsupported. Repair the file or run /subagents-setup to replace it with the current configuration.");
|
|
94
126
|
}
|
|
95
127
|
const config = normalizeConfig(stored.raw);
|
|
96
|
-
|
|
97
|
-
|
|
128
|
+
for (const role of BUILTIN_AGENT_NAMES) {
|
|
129
|
+
if ((stored.raw[role] as Record<string, unknown>).model !== undefined && !config[role].model) {
|
|
130
|
+
throw new Error(`Invalid ${role} model reference. Use provider/model-id, remove model to explicitly follow main, or run /subagents-setup to clear it.`);
|
|
131
|
+
}
|
|
98
132
|
}
|
|
99
133
|
return config;
|
|
100
134
|
}
|
|
@@ -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
|
|
|
@@ -51,32 +50,6 @@ function cleanModelRef(ref: string | undefined): string | undefined {
|
|
|
51
50
|
return trimmed || undefined;
|
|
52
51
|
}
|
|
53
52
|
|
|
54
|
-
/**
|
|
55
|
-
* Provider ids Pi renamed while keeping the model id. Pi 1.0.3 renamed
|
|
56
|
-
* `azure-openai-responses` to `azure`. Custom registries can still expose
|
|
57
|
-
* either id, so prefer the exact selection before trying its published alias.
|
|
58
|
-
*/
|
|
59
|
-
const RENAMED_PROVIDER_IDS: Readonly<Record<string, string>> = {
|
|
60
|
-
"azure-openai-responses": "azure",
|
|
61
|
-
};
|
|
62
|
-
|
|
63
|
-
/** Stored ref plus the renamed provider id, when Pi published one. */
|
|
64
|
-
function modelRefAliases(ref: string): readonly string[] {
|
|
65
|
-
const normalized = ref.trim();
|
|
66
|
-
const slash = normalized.indexOf("/");
|
|
67
|
-
if (slash <= 0 || slash >= normalized.length - 1) return [normalized];
|
|
68
|
-
const renamed = RENAMED_PROVIDER_IDS[normalized.slice(0, slash)];
|
|
69
|
-
if (!renamed) return [normalized];
|
|
70
|
-
return [normalized, `${renamed}${normalized.slice(slash)}`];
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Prefer the alias that the live catalog actually lists. */
|
|
74
|
-
function resolveLiveModelRef(ref: string, liveRefs: ReadonlySet<string> | undefined): string | undefined {
|
|
75
|
-
const aliases = modelRefAliases(ref);
|
|
76
|
-
if (!liveRefs) return aliases[0];
|
|
77
|
-
return aliases.find((candidate) => liveRefs.has(candidate));
|
|
78
|
-
}
|
|
79
|
-
|
|
80
53
|
export function modelRef(model: { provider: string; id: string }): string {
|
|
81
54
|
return `${model.provider}/${model.id}`;
|
|
82
55
|
}
|
|
@@ -92,9 +65,7 @@ export function currentModelRef(ctx: Pick<ModelContext, "model">): string | unde
|
|
|
92
65
|
*/
|
|
93
66
|
export function availableModelsInScope(ctx: ModelContext): readonly Model<Api>[] {
|
|
94
67
|
const models = ctx.modelRegistry.getAvailable();
|
|
95
|
-
|
|
96
|
-
// exactly like an empty scope and use the full live registry.
|
|
97
|
-
const scopedModels = ctx.scopedModels ?? [];
|
|
68
|
+
const scopedModels = ctx.scopedModels;
|
|
98
69
|
if (scopedModels.length === 0) return models;
|
|
99
70
|
const scopedRefs = new Set(scopedModels.map((entry) => modelRef(entry.model)));
|
|
100
71
|
return models.filter((model) => scopedRefs.has(modelRef(model)));
|
|
@@ -106,8 +77,7 @@ export function findModelByRef(
|
|
|
106
77
|
): Model<Api> | undefined {
|
|
107
78
|
const normalized = cleanModelRef(ref);
|
|
108
79
|
if (!normalized) return undefined;
|
|
109
|
-
|
|
110
|
-
return models.find((model) => modelRef(model) === liveRef);
|
|
80
|
+
return models.find((model) => modelRef(model) === normalized);
|
|
111
81
|
}
|
|
112
82
|
|
|
113
83
|
/**
|
|
@@ -122,7 +92,7 @@ export function resolveAgentModelRoute(input: AgentModelRouteInput): ResolvedAge
|
|
|
122
92
|
const available = input.availableRefs
|
|
123
93
|
? new Set(input.availableRefs.map((ref) => ref.trim()).filter(Boolean))
|
|
124
94
|
: undefined;
|
|
125
|
-
const resolvedSelectedRef = selectedRef
|
|
95
|
+
const resolvedSelectedRef = selectedRef && (!available || available.has(selectedRef)) ? selectedRef : undefined;
|
|
126
96
|
return {
|
|
127
97
|
primaryRef: selectedRef ? resolvedSelectedRef : mainRef,
|
|
128
98
|
...(selectedRef && !resolvedSelectedRef ? { unavailableSelectedRef: selectedRef } : {}),
|
|
@@ -162,14 +132,11 @@ export function buildModelPickerItems(options: {
|
|
|
162
132
|
if (!byRef.has(ref)) byRef.set(ref, model);
|
|
163
133
|
}
|
|
164
134
|
const configuredRef = cleanModelRef(options.configuredRef);
|
|
165
|
-
const liveConfiguredRef = configuredRef
|
|
166
|
-
? resolveLiveModelRef(configuredRef, new Set(byRef.keys())) ?? configuredRef
|
|
167
|
-
: undefined;
|
|
168
135
|
|
|
169
136
|
const refs = [...byRef.keys()]
|
|
170
137
|
.sort((left, right) => {
|
|
171
|
-
const leftRank = left ===
|
|
172
|
-
const rightRank = right ===
|
|
138
|
+
const leftRank = left === configuredRef ? 0 : left === mainRef ? 1 : 2;
|
|
139
|
+
const rightRank = right === configuredRef ? 0 : right === mainRef ? 1 : 2;
|
|
173
140
|
return leftRank - rightRank || left.localeCompare(right);
|
|
174
141
|
});
|
|
175
142
|
|
|
@@ -182,7 +149,7 @@ export function buildModelPickerItems(options: {
|
|
|
182
149
|
const items: ModelPickerItem[] = [dynamic];
|
|
183
150
|
for (const ref of refs) {
|
|
184
151
|
const model = byRef.get(ref)!;
|
|
185
|
-
const tags = [ref ===
|
|
152
|
+
const tags = [ref === configuredRef ? "configured" : "", ref === mainRef ? "current main" : ""]
|
|
186
153
|
.filter(Boolean);
|
|
187
154
|
const name = model.name.trim() || model.id;
|
|
188
155
|
const duplicateName = [...byRef.values()].some((other) =>
|
|
@@ -190,8 +157,8 @@ export function buildModelPickerItems(options: {
|
|
|
190
157
|
items.push({
|
|
191
158
|
value: ref,
|
|
192
159
|
label: name + " · " + model.provider + (duplicateName ? " (" + model.id + ")" : ""),
|
|
193
|
-
description: ["Reference: " + ref, "Pins this
|
|
194
|
-
saved: ref ===
|
|
160
|
+
description: ["Reference: " + ref, "Pins this role; failures return to main without changing models.", modelCapabilities(model), ...tags].join(" · "),
|
|
161
|
+
saved: ref === configuredRef,
|
|
195
162
|
});
|
|
196
163
|
}
|
|
197
164
|
return items;
|