pi-profile-switch 0.3.0 → 0.4.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.
Files changed (53) hide show
  1. package/README.md +32 -32
  2. package/README.zh-CN.md +32 -32
  3. package/bin/pi-profile.js +11 -0
  4. package/bin/pi-profile.ts +65 -0
  5. package/bin/postinstall.d.ts +13 -0
  6. package/bin/postinstall.js +88 -0
  7. package/defaults/profiles.json +18 -0
  8. package/examples/profiles.json +31 -5
  9. package/extensions/pi-profile/index.ts +451 -0
  10. package/package.json +10 -17
  11. package/schemas/profiles.schema.json +22 -24
  12. package/src/extension-discovery.ts +347 -0
  13. package/src/json-file.ts +1 -21
  14. package/src/launcher/args.ts +57 -0
  15. package/src/launcher/discovery.ts +64 -0
  16. package/src/launcher/initial-profile.ts +179 -0
  17. package/src/launcher/model-check.ts +52 -0
  18. package/src/launcher/runtime-cleanup.ts +85 -0
  19. package/src/launcher/spawn.ts +82 -0
  20. package/src/mcp-config.ts +37 -153
  21. package/src/mcp-coordination.ts +29 -10
  22. package/src/profile-catalog-store.ts +31 -12
  23. package/src/profile-catalog.ts +44 -63
  24. package/src/profile-resolver.ts +239 -245
  25. package/src/project-trust.ts +82 -0
  26. package/src/runtime-state-store.ts +25 -35
  27. package/src/settings-generator.ts +541 -0
  28. package/src/skill-registry.ts +94 -0
  29. package/src/switching/apply-plan.ts +197 -0
  30. package/src/switching/customize.ts +62 -33
  31. package/src/switching/list-profiles.ts +9 -6
  32. package/src/switching/mcp-toggle.ts +21 -25
  33. package/src/switching/profile-crud.ts +31 -24
  34. package/src/switching/profile-wizard.ts +21 -49
  35. package/src/switching/status.ts +142 -72
  36. package/src/switching/switch-profile.ts +219 -0
  37. package/src/switching/tool-references.ts +40 -0
  38. package/src/workspace.ts +57 -0
  39. package/LICENSE +0 -21
  40. package/examples/profiles.example.json +0 -74
  41. package/extensions/pi-profile-switch/index.ts +0 -744
  42. package/src/adapter-presence.ts +0 -75
  43. package/src/mcp-overlay-file.ts +0 -35
  44. package/src/mcp-overlay.ts +0 -122
  45. package/src/model-selection.ts +0 -64
  46. package/src/name-matching.ts +0 -50
  47. package/src/profile-badge.ts +0 -142
  48. package/src/profile-presets.ts +0 -61
  49. package/src/skill-selection.ts +0 -81
  50. package/src/startup-mcp-scope.ts +0 -262
  51. package/src/startup-selection.ts +0 -144
  52. package/src/switching/activate-profile.ts +0 -115
  53. package/src/switching/apply-profile.ts +0 -131
@@ -0,0 +1,219 @@
1
+ /**
2
+ * SwitchProfile: the in-session switching orchestrator (ticket 05).
3
+ *
4
+ * Runs inside Pi (the extension's `/profile use` / `/profile reload`), but
5
+ * is written dependency-injected so unit tests never need a real Pi.
6
+ *
7
+ * Flow (`/profile use <name>`):
8
+ * 1. wait for the agent to be idle (Pi's native `ctx.waitForIdle()`) — a
9
+ * running turn is never torn down
10
+ * 2. snapshot the runtime dir's settings.json + pi-profile.json in memory
11
+ * 3. re-resolve through the full launcher path (trust check, catalogs,
12
+ * discovery, registry, model/MCP validation) against the REAL agent
13
+ * dir — any failure here leaves the runtime untouched
14
+ * 4. rewrite the runtime files in place (the running process's
15
+ * PI_CODING_AGENT_DIR cannot move) and mark the plan
16
+ * `persistSelection` so the post-reload extension instance saves the
17
+ * selection + rollback anchor
18
+ * 5. `ctx.reload()` — Pi re-reads settings from disk, re-executes
19
+ * extensions, preserves the session
20
+ * 6. VERIFY the reload ran: interactive Pi swallows reload refusals and
21
+ * errors (showError) instead of rejecting, so a resolved promise is
22
+ * not proof. A real reload invalidates this extension context — the
23
+ * `assertStale` probe throws iff that happened. A silent skip rolls
24
+ * back exactly like a rejection: restore the snapshot, reload again.
25
+ * The runtime never sits half-switched.
26
+ *
27
+ * `/profile reload` is the same path minus the `switchedFrom` marker (no
28
+ * change summary) and preserving however the current profile became active
29
+ * (transient launch selections stay transient).
30
+ */
31
+
32
+ import { readFile, writeFile } from "node:fs/promises";
33
+ import path from "node:path";
34
+
35
+ import { resolveInitialProfile } from "../launcher/initial-profile.ts";
36
+ import { RuntimeStateStore, type RuntimeOverlay } from "../runtime-state-store.ts";
37
+ import { getGlobalStateDir } from "../workspace.ts";
38
+ import { writeRuntimeFiles } from "../settings-generator.ts";
39
+ import { readLaunchPlanFile } from "./apply-plan.ts";
40
+
41
+ export class SwitchError extends Error {
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "SwitchError";
45
+ }
46
+ }
47
+
48
+ export interface SwitchDeps {
49
+ /** The active generated runtime dir (the running Pi's agent dir). */
50
+ runtimeDir: string;
51
+ /** The user's real agent dir (from the launch plan; trust, catalogs,
52
+ * registries, and state all live there). */
53
+ realAgentDir: string;
54
+ /** The project working directory. */
55
+ cwd: string;
56
+ /** Pi's native idle wait (ctx.waitForIdle): resolves when the current
57
+ * turn/compaction finishes. */
58
+ waitForIdle(): Promise<void>;
59
+ reload(): Promise<void>;
60
+ /** Throws iff this extension context has been invalidated — proof the
61
+ * reload actually re-executed extensions. Interactive Pi swallows reload
62
+ * refusals/failures instead of rejecting, so without this probe a
63
+ * skipped reload would be misreported as a successful switch. Optional
64
+ * for tests; always provided by the extension. */
65
+ assertStale?(): void;
66
+ }
67
+
68
+ export interface SwitchResult {
69
+ profile: string;
70
+ warnings: string[];
71
+ }
72
+
73
+ interface RuntimeSnapshot {
74
+ settings?: string;
75
+ plan?: string;
76
+ }
77
+
78
+ async function readIfExists(filePath: string): Promise<string | undefined> {
79
+ try {
80
+ return await readFile(filePath, "utf8");
81
+ } catch (error) {
82
+ // Absence is expected (first launch); anything else (permissions,
83
+ // unreadable dir) must not silently disable rollback protection.
84
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
85
+ throw error;
86
+ }
87
+ }
88
+
89
+ async function snapshotRuntimeFiles(runtimeDir: string): Promise<RuntimeSnapshot> {
90
+ return {
91
+ settings: await readIfExists(path.join(runtimeDir, "settings.json")),
92
+ plan: await readIfExists(path.join(runtimeDir, "pi-profile.json")),
93
+ };
94
+ }
95
+
96
+ async function restoreRuntimeFiles(runtimeDir: string, snapshot: RuntimeSnapshot): Promise<void> {
97
+ if (snapshot.settings !== undefined) {
98
+ await writeFile(path.join(runtimeDir, "settings.json"), snapshot.settings);
99
+ }
100
+ if (snapshot.plan !== undefined) {
101
+ await writeFile(path.join(runtimeDir, "pi-profile.json"), snapshot.plan);
102
+ }
103
+ }
104
+
105
+ /** Waits are delegated to Pi's native `ctx.waitForIdle()` (see SwitchDeps);
106
+ * no polling loop lives here. */
107
+
108
+ /** Reads the current plan file for `switchedFrom`/persistence. A missing or
109
+ * malformed plan means the session is not profile-managed: switching still
110
+ * works, with no prior name to report. */
111
+ async function readCurrentPlan(runtimeDir: string): Promise<{ profile?: string; persistSelection: boolean }> {
112
+ const plan = await readLaunchPlanFile(runtimeDir);
113
+ return { profile: plan?.profile, persistSelection: plan?.persistSelection === true };
114
+ }
115
+
116
+ export async function switchProfile(
117
+ name: string | undefined,
118
+ deps: SwitchDeps,
119
+ options?: { reloadCurrent?: boolean; overlay?: RuntimeOverlay | null; clearOverlay?: boolean },
120
+ ): Promise<SwitchResult> {
121
+ const current = await readCurrentPlan(deps.runtimeDir);
122
+ const target = options?.reloadCurrent === true ? (current.profile ?? name) : name;
123
+ if (target === undefined) {
124
+ throw new SwitchError("no active profile to reload");
125
+ }
126
+
127
+ // Overlay resolution: explicit `overlay` wins (customize), explicit
128
+ // `null` suppresses (reset/switch), and a plain `/profile reload`
129
+ // re-applies the stored overlay so runtime and state never diverge.
130
+ let overlay = options?.overlay;
131
+ if (overlay === undefined && options?.reloadCurrent === true && current.profile !== undefined) {
132
+ const currentPlan = await readLaunchPlanFile(deps.runtimeDir);
133
+ if (currentPlan?.agentDir !== undefined) {
134
+ const stateDir = currentPlan.source === "project" ? path.join(deps.cwd, ".pi") : getGlobalStateDir(currentPlan.agentDir);
135
+ overlay = (await new RuntimeStateStore(stateDir).read()).overlay ?? null;
136
+ }
137
+ }
138
+
139
+ await deps.waitForIdle();
140
+
141
+ // Snapshot before resolving so the rollback target always exists.
142
+ const snapshot = await snapshotRuntimeFiles(deps.runtimeDir);
143
+
144
+ // Full launcher resolution: trust gate, catalogs, discovery, dependency
145
+ // closure, model + MCP validation. Failures here leave the runtime
146
+ // untouched — nothing was written yet.
147
+ const resolved = await resolveInitialProfile(
148
+ target,
149
+ { agentDir: deps.realAgentDir, cwd: deps.cwd },
150
+ { overlay: overlay ?? undefined },
151
+ );
152
+
153
+ const isSwitch = !options?.reloadCurrent && target !== current.profile;
154
+ // Carry the pre-switch resolved sets into the new plan for status deltas.
155
+ const previousPlan = await readLaunchPlanFile(deps.runtimeDir);
156
+ const previousResolved =
157
+ previousPlan?.resolved !== undefined
158
+ ? {
159
+ skills: previousPlan.resolved.skills.map((skill) => skill.name),
160
+ extensions: previousPlan.resolved.extensions.map((entry) => entry.id),
161
+ ...(previousPlan.tools !== undefined ? { tools: previousPlan.tools } : {}),
162
+ ...(previousPlan.mcps !== undefined ? { mcps: previousPlan.mcps } : {}),
163
+ }
164
+ : undefined;
165
+ await writeRuntimeFiles(deps.runtimeDir, resolved.plan, {
166
+ agentDir: deps.realAgentDir,
167
+ discovery: resolved.discovery,
168
+ projectSettings: resolved.projectSettings,
169
+ planExtras: {
170
+ ...(isSwitch && current.profile !== undefined ? { switchedFrom: current.profile } : {}),
171
+ // `/profile use` persists; `/profile reload` keeps the current
172
+ // profile's existing persistence (launch selections stay transient).
173
+ persistSelection: options?.reloadCurrent === true ? current.persistSelection : true,
174
+ // A switch discards the previous profile's overlay; the post-reload
175
+ // instance drops it from the state file. Customize/reset manage the
176
+ // overlay directly and never set this.
177
+ ...(options?.clearOverlay === true ? { clearOverlay: true } : {}),
178
+ ...(previousResolved !== undefined ? { previousResolved } : {}),
179
+ },
180
+ });
181
+
182
+ const rollback = async (cause: string): Promise<never> => {
183
+ // Restore the verified snapshot and reload again — the runtime must
184
+ // never sit half-switched. State files were not written yet (the
185
+ // post-reload extension instance owns them), so nothing else moved.
186
+ await restoreRuntimeFiles(deps.runtimeDir, snapshot);
187
+ try {
188
+ await deps.reload();
189
+ } catch {
190
+ // The restore reload failing too is reported through the original error.
191
+ }
192
+ throw new SwitchError(
193
+ `activation of profile "${target}" failed; restored the previous settings. Cause: ${cause}`,
194
+ );
195
+ };
196
+
197
+ try {
198
+ await deps.reload();
199
+ } catch (error) {
200
+ await rollback(error instanceof Error ? error.message : String(error));
201
+ }
202
+
203
+ // Interactive Pi reports reload refusals/failures via the UI instead of
204
+ // rejecting — verify the reload actually re-executed extensions (which
205
+ // invalidates this context) before calling the switch a success.
206
+ if (deps.assertStale !== undefined) {
207
+ let stale = false;
208
+ try {
209
+ deps.assertStale();
210
+ } catch {
211
+ stale = true;
212
+ }
213
+ if (!stale) {
214
+ await rollback("Pi did not run the reload (refused or failed silently)");
215
+ }
216
+ }
217
+
218
+ return { profile: resolved.plan.profile, warnings: resolved.warnings };
219
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Tool reference expansion against Pi's LIVE tool registry.
3
+ *
4
+ * Pre-spawn, the resolver expands tool globs against built-in names only
5
+ * (extension tools are unknowable before extension code runs). Post session
6
+ * start, the extension re-expands the raw references against
7
+ * `pi.getAllTools()`, which includes extension- and MCP-provided names.
8
+ * Literal references that match nothing are reported, not silently dropped
9
+ * (Pi's setActiveTools ignores unknown names).
10
+ */
11
+
12
+ import { minimatch } from "minimatch";
13
+
14
+ export interface ToolExpansion {
15
+ expanded: string[];
16
+ /** Literal references no live tool provides. */
17
+ droppedLiterals: string[];
18
+ }
19
+
20
+ export function expandToolReferences(references: string[], liveToolNames: string[]): ToolExpansion {
21
+ const live = new Set(liveToolNames);
22
+ const expanded = new Set<string>();
23
+ const droppedLiterals: string[] = [];
24
+ for (const reference of references) {
25
+ if (reference.includes("*") || reference.includes("?")) {
26
+ for (const name of liveToolNames) {
27
+ if (minimatch(name, reference)) {
28
+ expanded.add(name);
29
+ }
30
+ }
31
+ continue;
32
+ }
33
+ if (live.has(reference)) {
34
+ expanded.add(reference);
35
+ } else {
36
+ droppedLiterals.push(reference);
37
+ }
38
+ }
39
+ return { expanded: [...expanded], droppedLiterals };
40
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Workspace management for pi-profile-switch.
3
+ *
4
+ * Rooted at `~/.pi-profile-switch` (or `PI_PROFILE_SWITCH_DIR` override).
5
+ * Contains:
6
+ * - `profiles.json`: global profile definitions catalog
7
+ * - `instances/`: instance runtime directories for forked pi processes
8
+ */
9
+
10
+ import { existsSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import path from "node:path";
13
+
14
+ export function getProfileSwitchDir(): string {
15
+ const env = process.env.PI_PROFILE_SWITCH_DIR;
16
+ if (env && env.trim()) {
17
+ return path.resolve(env.trim());
18
+ }
19
+ return path.join(homedir(), ".pi-profile-switch");
20
+ }
21
+
22
+ export function getGlobalProfilesPath(): string {
23
+ return path.join(getProfileSwitchDir(), "profiles.json");
24
+ }
25
+
26
+ export function resolveGlobalProfilesPath(agentDir: string): string {
27
+ const preferred = getGlobalProfilesPath();
28
+ if (existsSync(preferred)) {
29
+ return preferred;
30
+ }
31
+ // Fallback for legacy ~/.pi/agent/profiles.json
32
+ const fallback = path.join(agentDir, "profiles.json");
33
+ if (existsSync(fallback)) {
34
+ return fallback;
35
+ }
36
+ return preferred;
37
+ }
38
+
39
+ export function getInstancesRootDir(): string {
40
+ return path.join(getProfileSwitchDir(), "instances");
41
+ }
42
+
43
+ export function getGlobalStateDir(agentDir?: string): string {
44
+ const preferred = getProfileSwitchDir();
45
+ const preferredState = path.join(preferred, "pi-profile-state.json");
46
+ if (existsSync(preferredState)) {
47
+ return preferred;
48
+ }
49
+ if (agentDir) {
50
+ const fallbackState = path.join(agentDir, "pi-profile-state.json");
51
+ if (existsSync(fallbackState)) {
52
+ return agentDir;
53
+ }
54
+ }
55
+ return agentDir ?? preferred;
56
+ }
57
+
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 VincentFF
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,74 +0,0 @@
1
- {
2
- "schemaVersion": 1,
3
- "profiles": {
4
- "read-only": {
5
- "label": "Read-only",
6
- "description": "Read-only session; no skills or MCP servers assumed — add your own.",
7
- "tools": [
8
- "read",
9
- "grep",
10
- "find",
11
- "ls"
12
- ],
13
- "instructions": "Read-only session: inspect and report; never create, edit, rename, or delete files.\nIf a change is needed, describe it in your reply instead of applying it.\nDo not run commands that modify state (installs, formatters, commits, pushes, network writes).\nPrefer an available skill or MCP tool when it fits the request; otherwise use the tools you have.\nGround claims in evidence: cite file:line and separate verified facts from inferences.\nReply in English."
14
- },
15
- "review": {
16
- "label": "Code review",
17
- "description": "Review a diff or a branch: read the change, report findings, modify nothing.",
18
- "skills": [
19
- "code-review",
20
- "git-*"
21
- ],
22
- "mcp": [
23
- "github"
24
- ],
25
- "tools": [
26
- "read",
27
- "grep",
28
- "find",
29
- "ls",
30
- "bash"
31
- ],
32
- "model": {
33
- "provider": "anthropic",
34
- "id": "claude-sonnet-4-5",
35
- "thinkingLevel": "high"
36
- },
37
- "instructions": "Review only: read the change under review, then report findings with file:line evidence.\nNever edit tracked files, commit, or push; describe the required fix instead.\nSeparate verified behavior from suspected issues."
38
- },
39
- "plan": {
40
- "label": "Plan",
41
- "description": "Research a change and write the plan; no edits, no implementation.",
42
- "skills": [],
43
- "tools": [
44
- "read",
45
- "grep",
46
- "find",
47
- "ls",
48
- "bash"
49
- ],
50
- "instructions": "Planning session: research the code first, then write the plan in your reply.\nDo not create, edit, rename, or delete files."
51
- },
52
- "implement": {
53
- "label": "Implement",
54
- "description": "Full tool access for implementing a change end to end.",
55
- "skills": [
56
- "git-commit",
57
- "test-*"
58
- ],
59
- "mcp": [
60
- "github"
61
- ],
62
- "tools": [
63
- "read",
64
- "grep",
65
- "find",
66
- "ls",
67
- "bash",
68
- "edit",
69
- "write"
70
- ],
71
- "instructions": "Implement the requested change: read before writing, keep the diff minimal.\nRun the tests that cover your change and report the exact commands."
72
- }
73
- }
74
- }