pi-session-mcp 0.7.1 → 0.8.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.
Files changed (66) hide show
  1. package/.pi-session-mcp-cli/config.js +47 -7
  2. package/.pi-session-mcp-cli/doctor.js +75 -2
  3. package/.pi-session-mcp-cli/execution-profile.js +1 -0
  4. package/.pi-session-mcp-cli/override-lock.js +125 -0
  5. package/.pi-session-mcp-cli/setup-platform.js +195 -0
  6. package/.pi-session-mcp-cli/setup-result.js +8 -0
  7. package/.pi-session-mcp-cli/skill-catalog.js +35 -0
  8. package/.pi-session-mcp-cli/skill-customize.js +268 -0
  9. package/.pi-session-mcp-cli/skill-library.js +188 -0
  10. package/CHANGELOG.md +176 -0
  11. package/README.md +15 -3
  12. package/dist/capabilities.d.ts +1 -0
  13. package/dist/capabilities.js +2 -1
  14. package/dist/client-adapters/mcp-verifier.js +6 -2
  15. package/dist/config.d.ts +4 -0
  16. package/dist/config.js +47 -7
  17. package/dist/doctor.d.ts +7 -1
  18. package/dist/doctor.js +75 -2
  19. package/dist/execution-profile.d.ts +4 -0
  20. package/dist/execution-profile.js +1 -0
  21. package/dist/override-lock.d.ts +34 -0
  22. package/dist/override-lock.js +125 -0
  23. package/dist/pi-adapter.d.ts +7 -5
  24. package/dist/pi-adapter.js +1 -0
  25. package/dist/pi-skills.d.ts +17 -0
  26. package/dist/pi-skills.js +64 -0
  27. package/dist/sdk-pi-adapter.d.ts +7 -3
  28. package/dist/sdk-pi-adapter.js +82 -16
  29. package/dist/server.js +1 -0
  30. package/dist/session-registry.d.ts +8 -6
  31. package/dist/session-registry.js +3 -2
  32. package/dist/setup-cli.d.ts +2 -0
  33. package/dist/setup-cli.js +16 -0
  34. package/dist/setup-main.d.ts +1 -1
  35. package/dist/setup-main.js +18 -3
  36. package/dist/setup-ownership.d.ts +9 -0
  37. package/dist/setup-ownership.js +32 -5
  38. package/dist/setup-skills.d.ts +76 -0
  39. package/dist/setup-skills.js +586 -0
  40. package/dist/setup.d.ts +7 -0
  41. package/dist/setup.js +49 -6
  42. package/dist/skill-catalog.d.ts +26 -0
  43. package/dist/skill-catalog.js +35 -0
  44. package/dist/skill-customize.d.ts +41 -0
  45. package/dist/skill-customize.js +268 -0
  46. package/dist/skill-library.d.ts +106 -0
  47. package/dist/skill-library.js +188 -0
  48. package/docs/acceptance.md +593 -1
  49. package/docs/adr/0006-pi-extension-allowlist.md +3 -0
  50. package/docs/adr/0007-profile-skill-selection.md +228 -0
  51. package/docs/architecture.md +10 -6
  52. package/docs/client-setup-design.md +219 -1
  53. package/docs/client-setup.md +86 -3
  54. package/docs/doctor-design.md +9 -1
  55. package/docs/installation.md +128 -5
  56. package/docs/pi-extensions-design.md +28 -4
  57. package/docs/releasing.md +18 -9
  58. package/docs/session-mcp.md +7 -2
  59. package/docs/skills.md +616 -0
  60. package/docs/threat-model.md +19 -2
  61. package/docs/tool-contracts.md +9 -5
  62. package/package.json +2 -1
  63. package/pi-session-mcp.example.json +9 -3
  64. package/skills/pi-session-implementation/SKILL.md +42 -0
  65. package/skills/pi-session-orchestration/SKILL.md +94 -0
  66. package/skills/pi-session-review/SKILL.md +58 -0
package/README.md CHANGED
@@ -18,6 +18,7 @@ Reasons to do that:
18
18
  - **Follow-up turns keep their context.** A session stays open across prompts, so a follow-up question does not pay for the same exploration twice.
19
19
  - **You set the limits, not the agent.** The client can only pick from the workspaces and profiles in your configuration file. It cannot name a directory, a model, a provider or a permission level, and the default profile is read-only.
20
20
  - **Exactly the extra tools a task needs.** A profile can grant individual tools of local stdio MCP servers to its sessions, and nothing else from those servers.
21
+ - **Role instructions you control.** A profile can select Pi skills from a catalog in your configuration, such as the implementation and review skills this package ships, or your own versions of them. The client cannot choose skills. The package also ships an orchestration skill for the controlling agent, which `setup` installs into Claude Code and Codex.
21
22
  - **Predictable to automate.** Sessions and turns have a small set of states and stable error codes. Results contain no paths, credentials, prompts or raw provider errors.
22
23
  - **Small footprint.** No daemon, no network listener and no stored state. An offline `doctor` checks an installation, and `setup` registers, verifies and removes the server reproducibly.
23
24
 
@@ -29,7 +30,7 @@ It is not the right tool when:
29
30
 
30
31
  ## Status
31
32
 
32
- The package version is **0.7.1**.
33
+ The package version is **0.8.1**.
33
34
 
34
35
  - **Pre-1.0.** The public tool contract is stable within a minor line: a change to tools, fields, states or error codes needs a new minor release.
35
36
  - **Linux and macOS**, Node.js 22.19.0 or newer. macOS is tested in CI on macOS 15 and 26 on Apple silicon; Intel Macs run the same code but are untested. Setup acceptance on a real Mac is recorded for Claude Code only; Codex is still pending. See [Acceptance](docs/acceptance.md#status). On other platforms `setup` refuses with `platform_unsupported`.
@@ -76,9 +77,17 @@ pi-session-mcp-setup --apply --target claude-code:user:pi-session-mcp
76
77
  pi-session-mcp-setup --verify --target claude-code:user:pi-session-mcp
77
78
  ```
78
79
 
79
- Use `codex:user:pi-session-mcp` for Codex. The example configuration contains placeholders only: replace the workspace, provider and model with real local values, and never add credentials to the file.
80
+ Use `codex:user:pi-session-mcp` for Codex. The example configuration contains placeholders only: replace the workspace, provider and model with real local values, and never add credentials to the file. The example also registers the two worker skills with `builtin:` references, which resolve to the skills in the package, so the copied example needs no path edits for skills (see [Pi skills](docs/skills.md)).
80
81
 
81
- `pi-session-mcp-doctor` is an offline health check. `pi-session-mcp-setup` plans by default, changes a client registration only with an explicit operation, and never replaces an existing divergent registration. Neither needs credentials, a provider or a model.
82
+ `--apply` registers the server and also installs the controller skill `pi-session-orchestration` for that client, so the agent knows how to drive Pi worker sessions: Claude Code `user` and `local` get `~/.claude/skills/`, Claude Code `project` gets `.claude/skills/` of the project, and Codex gets `~/.agents/skills/`. Setup never replaces a skill it did not install or that you modified. To adjust a skill, copy it into the override directory next to your configuration file and edit the copy:
83
+
84
+ ```bash
85
+ pi-session-mcp-setup --apply --customize-skill pi-session-review
86
+ ```
87
+
88
+ To add a skill of your own, create `skills/<name>/SKILL.md` next to the configuration file and reference it as `builtin:<name>`. Do not edit the installed package or the installed copy in the client.
89
+
90
+ `pi-session-mcp-doctor` is an offline health check. `pi-session-mcp-setup` plans by default, changes a client registration or skill only with an explicit operation, and never replaces an existing divergent registration or a skill it did not install. Neither needs credentials, a provider or a model.
82
91
 
83
92
  The [installation guide](docs/installation.md) also covers installing from a release tag with the exact locked dependency tree, the configuration rules, existing registrations, configuration changes, upgrades and removal.
84
93
 
@@ -104,6 +113,7 @@ The [installation guide](docs/installation.md) also covers installing from a rel
104
113
  - A workspace alias maps to a directory. Clients can select aliases only.
105
114
  - An execution profile binds a permission profile (`read-only` or `coding`), a provider, a model and a thinking level. Exactly one profile is the default, and it must be `read-only`.
106
115
  - A profile can grant individual tools of local stdio MCP servers to its sessions; see [External MCP tools in embedded sessions](docs/session-mcp.md).
116
+ - An optional top-level `skillCatalog` maps skill aliases to `builtin:<name>` (a skill of the package or of your override directory) or to a `SKILL.md` file, and a profile's optional `skills` selects aliases from it. A profile without `skills` gets no skills. See [Pi skills](docs/skills.md).
107
117
  - The server reads the file once at startup. Start a new client session after changing it.
108
118
 
109
119
  ## Run it by hand
@@ -144,6 +154,7 @@ Operate:
144
154
  - [Installation](docs/installation.md)
145
155
  - [Client setup reference](docs/client-setup.md): manual registration, the tool flow, deadlines and troubleshooting
146
156
  - [External MCP tools in embedded sessions](docs/session-mcp.md)
157
+ - [Pi skills in execution profiles](docs/skills.md)
147
158
  - [Changelog](CHANGELOG.md)
148
159
 
149
160
  Contract and design:
@@ -157,6 +168,7 @@ Contract and design:
157
168
  - [ADR 0002: embedded Pi SDK](docs/adr/0002-embedded-pi-sdk.md)
158
169
  - [ADR 0003: no new feature phase after the MVP](docs/adr/0003-post-mvp-maintenance.md)
159
170
  - [ADR 0004: setup accepts clients by contract, not by version](docs/adr/0004-client-contract-not-version.md)
171
+ - [ADR 0007: execution profiles select Pi skills from an operator catalog](docs/adr/0007-profile-skill-selection.md)
160
172
 
161
173
  Maintain:
162
174
 
@@ -22,5 +22,6 @@ export declare function projectCapabilities(workspaces: ReadonlyMap<string, stri
22
22
  model: string;
23
23
  thinkingLevel: import("./execution-profile.js").ThinkingLevel;
24
24
  extensions: string[];
25
+ skills: string[];
25
26
  }[];
26
27
  };
@@ -14,7 +14,7 @@ export function projectCapabilities(workspaces, executionProfiles, configuration
14
14
  .map((alias) => ({ alias })),
15
15
  executionProfiles: [...executionProfiles.values()]
16
16
  .sort((left, right) => compareAliases(left.alias, right.alias))
17
- .map(({ alias, default: isDefault, permissionProfile, provider, model, thinkingLevel, extensions }) => ({
17
+ .map(({ alias, default: isDefault, permissionProfile, provider, model, thinkingLevel, extensions, skills }) => ({
18
18
  alias,
19
19
  default: isDefault,
20
20
  permissionProfile,
@@ -22,6 +22,7 @@ export function projectCapabilities(workspaces, executionProfiles, configuration
22
22
  model,
23
23
  thinkingLevel,
24
24
  extensions: (extensions ?? []).map((extension) => extension.spec),
25
+ skills: (skills ?? []).map((skill) => skill.alias),
25
26
  })),
26
27
  };
27
28
  }
@@ -1,4 +1,5 @@
1
1
  import { MAX_PROFILE_EXTENSIONS, parseExtensionSpec } from "../extension-spec.js";
2
+ import { MAX_PROFILE_SKILLS } from "../skill-catalog.js";
2
3
  import { PACKAGE_NAME, PACKAGE_VERSION } from "../package-metadata.js";
3
4
  export const MCP_VERIFY_TIMEOUT_MS = 5_000;
4
5
  export const MCP_MAX_FRAME_BYTES = 65_536;
@@ -99,7 +100,7 @@ function validCapabilities(value) {
99
100
  if (!profile || typeof profile !== "object")
100
101
  return false;
101
102
  const record = profile;
102
- return exactKeys(record, ["alias", "default", "permissionProfile", "provider", "model", "thinkingLevel", "extensions"])
103
+ return exactKeys(record, ["alias", "default", "permissionProfile", "provider", "model", "thinkingLevel", "extensions", "skills"])
103
104
  && typeof record.alias === "string" && ALIAS_PATTERN.test(record.alias)
104
105
  && typeof record.default === "boolean"
105
106
  && (record.permissionProfile === "read-only" || record.permissionProfile === "coding")
@@ -107,7 +108,10 @@ function validCapabilities(value) {
107
108
  && typeof record.model === "string" && record.model.length > 0 && record.model.length <= 256
108
109
  && typeof record.thinkingLevel === "string" && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(record.thinkingLevel)
109
110
  && Array.isArray(record.extensions) && record.extensions.length <= MAX_PROFILE_EXTENSIONS
110
- && record.extensions.every((spec) => typeof spec === "string" && parseExtensionSpec(spec) !== undefined);
111
+ && record.extensions.every((spec) => typeof spec === "string" && parseExtensionSpec(spec) !== undefined)
112
+ && Array.isArray(record.skills) && record.skills.length <= MAX_PROFILE_SKILLS
113
+ && record.skills.every((skill) => typeof skill === "string" && ALIAS_PATTERN.test(skill))
114
+ && new Set(record.skills).size === record.skills.length;
111
115
  }))
112
116
  return false;
113
117
  const defaults = profiles.filter((profile) => profile.default === true);
package/dist/config.d.ts CHANGED
@@ -7,6 +7,7 @@ export declare class ConfigError extends Error {
7
7
  }
8
8
  export declare const configSchema: z.ZodObject<{
9
9
  workspaces: z.ZodRecord<z.ZodString, z.ZodString>;
10
+ skillCatalog: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
10
11
  executionProfiles: z.ZodRecord<z.ZodString, z.ZodObject<{
11
12
  default: z.ZodBoolean;
12
13
  permissionProfile: z.ZodEnum<{
@@ -26,6 +27,7 @@ export declare const configSchema: z.ZodObject<{
26
27
  }>;
27
28
  mcpServers: z.ZodOptional<z.ZodCustom<Readonly<Record<string, import("./mcp-config.js").McpServerConfig>>, Readonly<Record<string, import("./mcp-config.js").McpServerConfig>>>>;
28
29
  extensions: z.ZodOptional<z.ZodArray<z.ZodString>>;
30
+ skills: z.ZodOptional<z.ZodArray<z.ZodString>>;
29
31
  }, z.core.$strict>>;
30
32
  }, z.core.$strict>;
31
33
  /** The only supported reload behavior: a running controller keeps the snapshot it loaded at startup. */
@@ -42,6 +44,8 @@ export interface AppConfig {
42
44
  readonly executionProfiles: ReadonlyMap<string, ConfiguredExecutionProfile>;
43
45
  readonly defaultExecutionProfile: string;
44
46
  readonly configuration: ConfigurationMetadata;
47
+ /** Absolute skill override directory next to the configuration file. Internal; never projected. */
48
+ readonly skillOverrideDirectory: string;
45
49
  }
46
50
  /**
47
51
  * The configuration path comes only from the caller or from `PI_SESSION_MCP_CONFIG`.
package/dist/config.js CHANGED
@@ -4,16 +4,20 @@ import { dirname, resolve } from "node:path";
4
4
  import { z } from "zod";
5
5
  import { MAX_PROFILE_EXTENSIONS, parseExtensionSpec } from "./extension-spec.js";
6
6
  import { isMcpServers, snapshotMcpServers } from "./mcp-config.js";
7
+ import { builtinSkillName, isSkillCatalogPath, MAX_PROFILE_SKILLS, MAX_SKILL_CATALOG_ENTRIES } from "./skill-catalog.js";
7
8
  import { ALIAS_PATTERN, ImmutableMap, } from "./execution-profile.js";
9
+ import { builtinSkillPath, skillOverrideDirectory } from "./skill-library.js";
8
10
  const alias = z.string().regex(ALIAS_PATTERN);
9
11
  const permissionProfile = z.enum(["read-only", "coding"]);
10
12
  const thinkingLevel = z.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
11
13
  const extensionSpec = z.string().refine((value) => parseExtensionSpec(value) !== undefined);
14
+ const skillCatalogPath = z.string().refine(isSkillCatalogPath);
12
15
  const profileSchema = z.object({
13
16
  default: z.boolean(), permissionProfile, provider: z.string().trim().min(1).max(256),
14
17
  model: z.string().trim().min(1).max(256), thinkingLevel,
15
18
  mcpServers: z.custom((value) => isMcpServers(value)).optional(),
16
19
  extensions: z.array(extensionSpec).max(MAX_PROFILE_EXTENSIONS).optional(),
20
+ skills: z.array(alias).max(MAX_PROFILE_SKILLS).optional(),
17
21
  }).strict().superRefine((profile, context) => {
18
22
  if (profile.mcpServers !== undefined && !isMcpServers(profile.mcpServers, profile.permissionProfile)) {
19
23
  context.addIssue({ code: "custom", path: ["mcpServers"], message: "MCP tool grants do not match the permission profile" });
@@ -24,6 +28,9 @@ const profileSchema = z.object({
24
28
  context.addIssue({ code: "custom", path: ["extensions"], message: "An extension package may appear only once per profile" });
25
29
  }
26
30
  }
31
+ if (profile.skills !== undefined && new Set(profile.skills).size !== profile.skills.length) {
32
+ context.addIssue({ code: "custom", path: ["skills"], message: "A skill alias may appear only once per profile" });
33
+ }
27
34
  });
28
35
  const CONFIG_ERROR_MESSAGES = {
29
36
  config_path_required: "Configuration path is required",
@@ -40,6 +47,7 @@ export class ConfigError extends Error {
40
47
  }
41
48
  export const configSchema = z.object({
42
49
  workspaces: z.record(alias, z.string().min(1)),
50
+ skillCatalog: z.record(alias, skillCatalogPath).refine((catalog) => Object.keys(catalog).length <= MAX_SKILL_CATALOG_ENTRIES).optional(),
43
51
  executionProfiles: z.record(alias, profileSchema).superRefine((profiles, context) => {
44
52
  const entries = Object.entries(profiles);
45
53
  if (entries.length === 0)
@@ -50,13 +58,39 @@ export const configSchema = z.object({
50
58
  if (defaults.length === 1 && defaults[0][1].permissionProfile !== "read-only")
51
59
  context.addIssue({ code: "custom", message: "The default execution profile must be read-only" });
52
60
  }),
53
- }).strict();
61
+ }).strict().superRefine((config, context) => {
62
+ // A profile may select only cataloged skills; there is no implicit or default skill.
63
+ const catalog = config.skillCatalog ?? {};
64
+ for (const [profileAlias, profile] of Object.entries(config.executionProfiles)) {
65
+ if ((profile.skills ?? []).some((skill) => !Object.hasOwn(catalog, skill))) {
66
+ context.addIssue({ code: "custom", path: ["executionProfiles", profileAlias, "skills"], message: "A selected skill must be a skillCatalog alias" });
67
+ }
68
+ }
69
+ });
54
70
  /** The only supported reload behavior: a running controller keeps the snapshot it loaded at startup. */
55
71
  export const RELOAD_POLICY = "restart-required";
56
72
  export const CONFIGURATION_FINGERPRINT_PATTERN = /^sha256:[0-9a-f]{64}$/;
57
73
  function configurationFingerprint(bytes) {
58
74
  return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
59
75
  }
76
+ /**
77
+ * Resolves a profile's selection against the catalog. Catalog paths resolve like workspaces,
78
+ * against the configuration file's directory. Two selected aliases on the same path would
79
+ * load one skill twice under different public names, so they invalidate the configuration.
80
+ * A `builtin:<name>` value resolves to the library skill: the operator's override, else the shipped one.
81
+ */
82
+ function resolveSkillSelection(selected, catalog, base, overrideDirectory) {
83
+ if (selected === undefined || selected.length === 0)
84
+ return undefined;
85
+ const resolveEntry = (value) => {
86
+ const builtin = builtinSkillName(value);
87
+ return builtin === undefined ? resolve(base, value) : builtinSkillPath(builtin, { overrideDirectory });
88
+ };
89
+ const skills = selected.map((skill) => Object.freeze({ alias: skill, path: resolveEntry(catalog[skill]) }));
90
+ if (new Set(skills.map((skill) => skill.path)).size !== skills.length)
91
+ throw new ConfigError("invalid_execution_profile_config");
92
+ return Object.freeze(skills);
93
+ }
60
94
  /**
61
95
  * The configuration path comes only from the caller or from `PI_SESSION_MCP_CONFIG`.
62
96
  * There is no default file: a server's working directory is the client's project,
@@ -85,14 +119,20 @@ export async function loadConfig(path = process.env.PI_SESSION_MCP_CONFIG) {
85
119
  throw error;
86
120
  }
87
121
  const base = dirname(absoluteConfig);
122
+ const overrideDirectory = skillOverrideDirectory(absoluteConfig);
88
123
  const workspaces = new ImmutableMap(Object.entries(parsed.workspaces).map(([key, value]) => [key, resolve(base, value)]));
89
- const executionProfiles = new ImmutableMap(Object.entries(parsed.executionProfiles).map(([key, { mcpServers, extensions, ...value }]) => [key, Object.freeze({
90
- alias: key, ...value,
91
- ...(mcpServers === undefined ? {} : { mcpServers: snapshotMcpServers(mcpServers) }),
92
- ...(extensions === undefined ? {} : { extensions: Object.freeze(extensions.map((spec) => parseExtensionSpec(spec))) }),
93
- })]));
124
+ const catalog = parsed.skillCatalog ?? {};
125
+ const executionProfiles = new ImmutableMap(Object.entries(parsed.executionProfiles).map(([key, { mcpServers, extensions, skills, ...value }]) => {
126
+ const selection = resolveSkillSelection(skills, catalog, base, overrideDirectory);
127
+ return [key, Object.freeze({
128
+ alias: key, ...value,
129
+ ...(mcpServers === undefined ? {} : { mcpServers: snapshotMcpServers(mcpServers) }),
130
+ ...(extensions === undefined ? {} : { extensions: Object.freeze(extensions.map((spec) => parseExtensionSpec(spec))) }),
131
+ ...(selection === undefined ? {} : { skills: selection }),
132
+ })];
133
+ }));
94
134
  const defaultEntry = [...executionProfiles].find(([, profile]) => profile.default);
95
135
  if (!defaultEntry)
96
136
  throw new Error("Execution profile configuration is invalid");
97
- return { workspaces, executionProfiles, defaultExecutionProfile: defaultEntry[0], configuration };
137
+ return { workspaces, executionProfiles, defaultExecutionProfile: defaultEntry[0], configuration, skillOverrideDirectory: overrideDirectory };
98
138
  }
package/dist/doctor.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  import { type AppConfig } from "./config.js";
2
2
  import { type ExtensionSpec } from "./extension-spec.js";
3
+ import { type ReleasedSkillTree } from "./skill-library.js";
3
4
  export type DoctorSeverity = "ok" | "warning" | "error";
4
5
  export type DoctorExitCode = 0 | 1 | 2 | 64;
5
- export type DoctorCheckId = "node_version_unsupported" | "package_metadata_unreadable" | "build_missing" | "build_stale" | "version_mismatch" | "config_missing" | "config_unreadable" | "config_invalid" | "workspace_missing" | "workspace_not_directory" | "workspace_unreadable" | "workspace_not_writable" | "extension_missing" | "extension_version_mismatch";
6
+ export type DoctorCheckId = "node_version_unsupported" | "package_metadata_unreadable" | "build_missing" | "build_stale" | "version_mismatch" | "config_missing" | "config_unreadable" | "config_invalid" | "workspace_missing" | "workspace_not_directory" | "workspace_unreadable" | "workspace_not_writable" | "extension_missing" | "extension_version_mismatch" | "skill_missing" | "skill_unreadable" | "skill_duplicate" | "skill_override_outdated";
6
7
  export interface DoctorCheck {
7
8
  readonly id: DoctorCheckId;
8
9
  readonly severity: DoctorSeverity;
@@ -30,8 +31,11 @@ export interface DoctorFileSystem {
30
31
  readonly isDirectory: () => boolean;
31
32
  readonly isFile: () => boolean;
32
33
  readonly mtimeMs?: number;
34
+ readonly size?: number;
33
35
  }>;
34
36
  readonly access: (path: string, mode: number) => Promise<void>;
37
+ /** Canonical path; defaults to the real file system when an injected fake omits it. */
38
+ readonly realpath?: (path: string) => Promise<string>;
35
39
  }
36
40
  export interface DoctorDependencies {
37
41
  readonly packageRoot?: string;
@@ -41,6 +45,8 @@ export interface DoctorDependencies {
41
45
  readonly packageMetadata?: () => Promise<DoctorPackageMetadata>;
42
46
  /** Reads the installed manifest of a pinned extension; never imports extension code. */
43
47
  readonly resolveExtension?: (extension: ExtensionSpec) => Promise<string>;
48
+ /** Reference trees that resolve legacy skill bases; defaults to the released shipped skills. */
49
+ readonly releasedSkillTrees?: readonly ReleasedSkillTree[];
44
50
  }
45
51
  export declare function runDoctor(dependencies?: DoctorDependencies): Promise<DoctorResult>;
46
52
  export declare function renderDoctorJson(result: DoctorResult): string;
package/dist/doctor.js CHANGED
@@ -1,11 +1,14 @@
1
- import { access, readFile, readdir, stat } from "node:fs/promises";
1
+ import { access, readFile, readdir, realpath, stat } from "node:fs/promises";
2
2
  import { constants } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { loadConfig } from "./config.js";
5
5
  import { PiExtensionError } from "./extension-spec.js";
6
6
  import { readPackageMetadata } from "./package-metadata.js";
7
+ import { MAX_SKILL_FILE_BYTES } from "./skill-catalog.js";
8
+ import { readSkillBases, SkillBasesError } from "./skill-customize.js";
9
+ import { LEGACY_SKILL_TREE_FINGERPRINT_PATTERN, readSkillTree, releasedSkillFingerprint, shippedSkillsDirectory } from "./skill-library.js";
7
10
  const defaultFileSystem = { readFile, stat, access };
8
- const CHECK_ORDER = ["node_version_unsupported", "package_metadata_unreadable", "build_missing", "build_stale", "version_mismatch", "config_missing", "config_unreadable", "config_invalid", "workspace_missing", "workspace_not_directory", "workspace_unreadable", "workspace_not_writable", "extension_missing", "extension_version_mismatch"];
11
+ const CHECK_ORDER = ["node_version_unsupported", "package_metadata_unreadable", "build_missing", "build_stale", "version_mismatch", "config_missing", "config_unreadable", "config_invalid", "workspace_missing", "workspace_not_directory", "workspace_unreadable", "workspace_not_writable", "extension_missing", "extension_version_mismatch", "skill_missing", "skill_unreadable", "skill_duplicate", "skill_override_outdated"];
9
12
  function failure(id, subject, remediation) { return Object.freeze({ id, severity: "error", subject, remediation }); }
10
13
  function warning(id, subject, remediation) { return Object.freeze({ id, severity: "warning", subject, remediation }); }
11
14
  function ok(id, subject) { return Object.freeze({ id, severity: "ok", subject }); }
@@ -62,6 +65,44 @@ async function productionBuildInputMtimes(root) {
62
65
  }
63
66
  return mtimes;
64
67
  }
68
+ /**
69
+ * Compares the shipped skills with the fingerprints recorded when the operator copied them.
70
+ * Reads only the bases file and the shipped files, takes no lock and writes nothing: the bases
71
+ * file is replaced atomically, so a read sees either the old or the new content.
72
+ */
73
+ async function skillOverrideChecks(overrideDirectory, shippedDirectory, released) {
74
+ if (overrideDirectory === undefined)
75
+ return [];
76
+ let bases;
77
+ try {
78
+ bases = await readSkillBases(overrideDirectory);
79
+ }
80
+ catch (error) {
81
+ if (error instanceof SkillBasesError)
82
+ return [warning("skill_override_outdated", "skill:bases", "repair or remove the skill bases file")];
83
+ throw error;
84
+ }
85
+ const checks = [];
86
+ for (const [name, base] of Object.entries(bases).sort(([a], [b]) => a.localeCompare(b))) {
87
+ let fingerprint;
88
+ try {
89
+ fingerprint = (await readSkillTree(join(shippedDirectory, name))).fingerprint;
90
+ }
91
+ catch {
92
+ continue;
93
+ }
94
+ const command = `pi-session-mcp-setup --apply --customize-skill ${name}`;
95
+ // A legacy base is meaningful only as the version 2 value of the released original it names.
96
+ const recorded = LEGACY_SKILL_TREE_FINGERPRINT_PATTERN.test(base) ? releasedSkillFingerprint(name, base, released) : base;
97
+ if (recorded === undefined)
98
+ checks.push(warning("skill_override_outdated", `skill:${name}`, `the recorded base predates version 2 fingerprints and cannot be confirmed; review the shipped skill, then run ${command}`));
99
+ else
100
+ checks.push(recorded === fingerprint
101
+ ? ok("skill_override_outdated", `skill:${name}`)
102
+ : warning("skill_override_outdated", `skill:${name}`, `review the changed shipped skill, then run ${command}`));
103
+ }
104
+ return checks;
105
+ }
65
106
  export async function runDoctor(dependencies = {}) {
66
107
  const fs = dependencies.fileSystem ?? defaultFileSystem;
67
108
  const root = dependencies.packageRoot ?? process.cwd();
@@ -195,6 +236,38 @@ export async function runDoctor(dependencies = {}) {
195
236
  }
196
237
  }
197
238
  }
239
+ if (config) {
240
+ for (const [alias, profile] of [...config.executionProfiles].sort(([a], [b]) => a.localeCompare(b))) {
241
+ const canonical = new Set();
242
+ for (const skill of profile.skills ?? []) {
243
+ const subject = `${alias}:${skill.alias}`;
244
+ let real;
245
+ try {
246
+ const info = await fs.stat(skill.path);
247
+ if (!info.isFile() || (info.size ?? 0) > MAX_SKILL_FILE_BYTES)
248
+ throw new Error("unusable skill file");
249
+ await fs.access(skill.path, constants.R_OK);
250
+ real = await (fs.realpath ?? realpath)(skill.path);
251
+ }
252
+ catch (error) {
253
+ if (isMissing(error))
254
+ checks.push(failure("skill_missing", subject, "create the skill file or fix its skillCatalog entry"));
255
+ else
256
+ checks.push(ok("skill_missing", subject), failure("skill_unreadable", subject, "point the skillCatalog entry to a readable SKILL.md within the size limit"));
257
+ continue;
258
+ }
259
+ checks.push(ok("skill_missing", subject), ok("skill_unreadable", subject));
260
+ if (canonical.has(real))
261
+ checks.push(failure("skill_duplicate", subject, "select each skill file only once per profile"));
262
+ else {
263
+ canonical.add(real);
264
+ checks.push(ok("skill_duplicate", subject));
265
+ }
266
+ }
267
+ }
268
+ }
269
+ if (config)
270
+ checks.push(...await skillOverrideChecks(config.skillOverrideDirectory, shippedSkillsDirectory(dependencies.packageRoot), dependencies.releasedSkillTrees));
198
271
  const rank = new Map(CHECK_ORDER.map((id, index) => [id, index]));
199
272
  checks.sort((a, b) => (rank.get(a.id) ?? 999) - (rank.get(b.id) ?? 999) || a.subject.localeCompare(b.subject));
200
273
  const hasError = checks.some((check) => check.severity === "error");
@@ -1,5 +1,6 @@
1
1
  import type { ExtensionSpec } from "./extension-spec.js";
2
2
  import { type McpServers } from "./mcp-config.js";
3
+ import type { SkillSelection } from "./skill-catalog.js";
3
4
  export declare const ALIAS_PATTERN: RegExp;
4
5
  export type PermissionProfile = "read-only" | "coding";
5
6
  export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
@@ -13,6 +14,8 @@ export interface ConfiguredExecutionProfile {
13
14
  readonly thinkingLevel: ThinkingLevel;
14
15
  readonly mcpServers?: McpServers;
15
16
  readonly extensions?: readonly ExtensionSpec[];
17
+ /** The selected catalog skills in configured order; absent when the profile selects none. */
18
+ readonly skills?: readonly SkillSelection[];
16
19
  }
17
20
  /** The immutable, server-side selection passed to the Pi adapter. */
18
21
  export interface ResolvedExecutionProfile {
@@ -23,6 +26,7 @@ export interface ResolvedExecutionProfile {
23
26
  readonly thinkingLevel: ThinkingLevel;
24
27
  readonly mcpServers?: McpServers;
25
28
  readonly extensions?: readonly ExtensionSpec[];
29
+ readonly skills?: readonly SkillSelection[];
26
30
  }
27
31
  export declare function toResolvedExecutionProfile(profile: ConfiguredExecutionProfile): ResolvedExecutionProfile;
28
32
  /** A small read-only map implementation which has no mutating methods at runtime. */
@@ -9,6 +9,7 @@ export function toResolvedExecutionProfile(profile) {
9
9
  thinkingLevel: profile.thinkingLevel,
10
10
  ...(profile.mcpServers === undefined ? {} : { mcpServers: snapshotMcpServers(profile.mcpServers) }),
11
11
  ...(profile.extensions === undefined ? {} : { extensions: profile.extensions }),
12
+ ...(profile.skills === undefined ? {} : { skills: profile.skills }),
12
13
  });
13
14
  }
14
15
  /** A small read-only map implementation which has no mutating methods at runtime. */
@@ -0,0 +1,34 @@
1
+ import { type StatfsReader } from "./setup-platform.js";
2
+ /**
3
+ * The kernel lock that serializes every read-modify-write of the skill bases file across
4
+ * processes. It lives on a stable lock file, never on the bases file: that file is replaced by a
5
+ * rename, which would move the lock onto an unlinked inode. The lock file is never deleted, and a
6
+ * holder that dies releases the lock through the kernel.
7
+ */
8
+ export declare const SKILL_BASES_LOCK_FILE = ".pi-session-mcp-bases.lock";
9
+ export declare const DEFAULT_OVERRIDE_LOCK_TIMEOUT_MS = 30000;
10
+ export declare class OverrideLockError extends Error {
11
+ readonly code: "override_lock_busy" | "override_lock_unavailable";
12
+ constructor(code: "override_lock_busy" | "override_lock_unavailable");
13
+ }
14
+ export interface OverrideLockOptions {
15
+ /** Acquisition bound; a busy lock after this fails with `override_lock_busy`. */
16
+ readonly timeoutMs?: number;
17
+ readonly signal?: AbortSignal;
18
+ /** Test seams for the platform gate; the defaults describe this process. */
19
+ readonly platform?: NodeJS.Platform;
20
+ readonly flockCandidates?: readonly string[];
21
+ readonly isTrustedBinary?: (path: string) => boolean;
22
+ readonly readStatfs?: StatfsReader;
23
+ }
24
+ export interface OverrideLock {
25
+ /** Closes the descriptor that holds the lock; safe to call more than once. */
26
+ release(): Promise<void>;
27
+ }
28
+ /**
29
+ * Takes the exclusive lock for one override directory, which must exist. Fails closed: an
30
+ * unsupported platform, a missing trusted `flock`, an unsupported filesystem, a link or non-file
31
+ * at the lock path and a descriptor that no longer names the path all end in
32
+ * `override_lock_unavailable`.
33
+ */
34
+ export declare function acquireOverrideLock(overrideDirectory: string, options?: OverrideLockOptions): Promise<OverrideLock>;
@@ -0,0 +1,125 @@
1
+ import { spawn } from "node:child_process";
2
+ import { constants } from "node:fs";
3
+ import { lstat, open } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { assertSupportedFilesystem, currentSetupPlatform, isTrustedSystemBinary, openLockedDarwin } from "./setup-platform.js";
6
+ /**
7
+ * The kernel lock that serializes every read-modify-write of the skill bases file across
8
+ * processes. It lives on a stable lock file, never on the bases file: that file is replaced by a
9
+ * rename, which would move the lock onto an unlinked inode. The lock file is never deleted, and a
10
+ * holder that dies releases the lock through the kernel.
11
+ */
12
+ export const SKILL_BASES_LOCK_FILE = ".pi-session-mcp-bases.lock";
13
+ export const DEFAULT_OVERRIDE_LOCK_TIMEOUT_MS = 30_000;
14
+ const MIN_LOCK_TIMEOUT_MS = 50;
15
+ const MAX_LOCK_TIMEOUT_MS = 120_000;
16
+ /** Exit status of `flock -E` when the lock stayed busy for the whole wait. */
17
+ const FLOCK_BUSY_EXIT = 75;
18
+ const FLOCK_CANDIDATES = ["/usr/bin/flock", "/bin/flock"];
19
+ export class OverrideLockError extends Error {
20
+ code;
21
+ constructor(code) {
22
+ super("Skill override lock is not available");
23
+ this.code = code;
24
+ this.name = "OverrideLockError";
25
+ }
26
+ }
27
+ /**
28
+ * Takes the exclusive lock for one override directory, which must exist. Fails closed: an
29
+ * unsupported platform, a missing trusted `flock`, an unsupported filesystem, a link or non-file
30
+ * at the lock path and a descriptor that no longer names the path all end in
31
+ * `override_lock_unavailable`.
32
+ */
33
+ export async function acquireOverrideLock(overrideDirectory, options = {}) {
34
+ const platform = currentSetupPlatform(options.platform);
35
+ if (!platform)
36
+ throw new OverrideLockError("override_lock_unavailable");
37
+ const timeoutMs = Number.isFinite(options.timeoutMs) ? Math.max(MIN_LOCK_TIMEOUT_MS, Math.min(options.timeoutMs, MAX_LOCK_TIMEOUT_MS)) : DEFAULT_OVERRIDE_LOCK_TIMEOUT_MS;
38
+ const flockPath = platform === "linux" ? flockBinary(options) : undefined;
39
+ if (platform === "linux" && flockPath === undefined)
40
+ throw new OverrideLockError("override_lock_unavailable");
41
+ try {
42
+ await assertSupportedFilesystem(overrideDirectory, platform, options.readStatfs);
43
+ }
44
+ catch {
45
+ throw new OverrideLockError("override_lock_unavailable");
46
+ }
47
+ const lockPath = join(overrideDirectory, SKILL_BASES_LOCK_FILE);
48
+ let handle;
49
+ try {
50
+ // macOS takes the kernel lock at open time; on Linux the trusted flock locks this very
51
+ // open file description, so the lock outlives the flock process and ends with this descriptor.
52
+ handle = await openLockFile(lockPath, platform, timeoutMs, options.signal);
53
+ if (flockPath !== undefined)
54
+ await lockWithFlock(flockPath, handle.fd, timeoutMs, options.signal);
55
+ // The path may have been replaced while waiting: the lock only counts on the file it names.
56
+ const [descriptor, linked] = await Promise.all([handle.stat(), lstat(lockPath)]);
57
+ if (!descriptor.isFile() || !linked.isFile() || descriptor.dev !== linked.dev || descriptor.ino !== linked.ino)
58
+ throw new OverrideLockError("override_lock_unavailable");
59
+ }
60
+ catch (error) {
61
+ await handle?.close().catch(() => undefined);
62
+ throw error instanceof OverrideLockError ? error : new OverrideLockError("override_lock_unavailable");
63
+ }
64
+ const held = handle;
65
+ let released = false;
66
+ return {
67
+ async release() {
68
+ if (released)
69
+ return;
70
+ released = true;
71
+ await held.close().catch(() => undefined);
72
+ },
73
+ };
74
+ }
75
+ function flockBinary(options) {
76
+ const trusted = options.isTrustedBinary ?? ((path) => isTrustedSystemBinary(path));
77
+ return (options.flockCandidates ?? FLOCK_CANDIDATES).find((candidate) => trusted(candidate));
78
+ }
79
+ async function openLockFile(lockPath, platform, timeoutMs, signal) {
80
+ try {
81
+ if (platform === "darwin")
82
+ return await openLockedDarwin(lockPath, { timeoutMs, ...(signal ? { signal } : {}) });
83
+ return await open(lockPath, constants.O_CREAT | constants.O_RDWR | constants.O_NOFOLLOW, 0o600);
84
+ }
85
+ catch (error) {
86
+ throw new OverrideLockError(error.message === "ownership_lock_busy" ? "override_lock_busy" : "override_lock_unavailable");
87
+ }
88
+ }
89
+ function lockWithFlock(flockPath, lockFd, timeoutMs, signal) {
90
+ return new Promise((resolve, reject) => {
91
+ if (signal?.aborted) {
92
+ reject(new OverrideLockError("override_lock_unavailable"));
93
+ return;
94
+ }
95
+ let locker;
96
+ try {
97
+ // flock parses fractional seconds with the locale's decimal separator, so only whole
98
+ // seconds go on the command line. The exact bound is the timer below, which stops flock.
99
+ const wholeSeconds = String(Math.max(1, Math.ceil(timeoutMs / 1_000)));
100
+ locker = spawn(flockPath, ["-E", String(FLOCK_BUSY_EXIT), "-w", wholeSeconds, "3"], { stdio: ["ignore", "ignore", "ignore", lockFd], detached: true });
101
+ }
102
+ catch {
103
+ reject(new OverrideLockError("override_lock_unavailable"));
104
+ return;
105
+ }
106
+ let expired = false;
107
+ const stop = () => { if (locker.pid !== undefined) {
108
+ try {
109
+ process.kill(-locker.pid, "SIGKILL");
110
+ }
111
+ catch { /* already gone */ }
112
+ } };
113
+ const cleanup = () => { clearTimeout(bound); signal?.removeEventListener("abort", stop); };
114
+ const bound = setTimeout(() => { expired = true; stop(); }, timeoutMs);
115
+ signal?.addEventListener("abort", stop, { once: true });
116
+ locker.once("error", () => { cleanup(); reject(new OverrideLockError("override_lock_unavailable")); });
117
+ locker.once("close", (code) => {
118
+ cleanup();
119
+ if (code === 0)
120
+ resolve();
121
+ else
122
+ reject(new OverrideLockError(code === FLOCK_BUSY_EXIT || expired ? "override_lock_busy" : "override_lock_unavailable"));
123
+ });
124
+ });
125
+ }
@@ -13,7 +13,7 @@ export interface PiAppliedSelection {
13
13
  readonly model: string;
14
14
  readonly thinkingLevel: ThinkingLevel;
15
15
  }
16
- export type PiSessionCreationErrorCode = "unknown_provider" | "unknown_model" | "local_authentication_missing" | "local_authentication_unavailable" | "model_unavailable" | "thinking_level_unavailable" | "execution_selection_mismatch" | "external_mcp_unavailable" | "external_mcp_no_tools" | "external_mcp_grant_tool_missing" | "external_mcp_activation_mismatch" | "extension_not_installed" | "extension_version_mismatch" | "extension_load_failed" | "extension_tool_conflict" | "pi_session_creation_failed";
16
+ export type PiSessionCreationErrorCode = "unknown_provider" | "unknown_model" | "local_authentication_missing" | "local_authentication_unavailable" | "model_unavailable" | "thinking_level_unavailable" | "execution_selection_mismatch" | "external_mcp_unavailable" | "external_mcp_no_tools" | "external_mcp_grant_tool_missing" | "external_mcp_activation_mismatch" | "extension_not_installed" | "extension_version_mismatch" | "extension_load_failed" | "extension_tool_conflict" | "skill_load_failed" | "pi_session_creation_failed";
17
17
  export declare class PiSessionCreationError extends Error {
18
18
  readonly code: PiSessionCreationErrorCode;
19
19
  constructor(code: PiSessionCreationErrorCode);
@@ -23,10 +23,12 @@ export interface PiSessionHandle {
23
23
  /** Only whitelisted, post-verified selection metadata may cross the adapter boundary. */
24
24
  readonly appliedSelection: PiAppliedSelection;
25
25
  /**
26
- * `onActivity` is an optional content-free liveness callback, invoked after a completed
27
- * tool execution and after a completed assistant message. It receives no event payload
28
- * and must only be used for timestamping; it never carries tool names, arguments,
29
- * results, text, paths, or credentials.
26
+ * `onActivity` is an optional content-free liveness callback, invoked on observed public
27
+ * SDK activity of the running prompt: assistant message start, update and end, and tool
28
+ * execution start, update and end. Streaming is activity, not evidence of finished or
29
+ * useful work, and internal work without a public event stays invisible. It receives no
30
+ * event payload and must only be used for timestamping; it never carries tool names,
31
+ * arguments, results, text, paths, or credentials.
30
32
  */
31
33
  prompt(text: string, preflight: (accepted: boolean) => void, onActivity?: () => void): Promise<PiTurnOutcome>;
32
34
  abort(): Promise<void>;
@@ -14,6 +14,7 @@ const PI_SESSION_CREATION_MESSAGES = {
14
14
  extension_version_mismatch: "Configured Pi extension version is not installed",
15
15
  extension_load_failed: "Configured Pi extension could not be loaded",
16
16
  extension_tool_conflict: "Configured Pi extension tools conflict",
17
+ skill_load_failed: "Configured Pi skill could not be loaded",
17
18
  pi_session_creation_failed: "Pi session creation failed",
18
19
  };
19
20
  export class PiSessionCreationError extends Error {
@@ -0,0 +1,17 @@
1
+ import { type Stats } from "node:fs";
2
+ import { loadSkills, type Skill } from "@earendil-works/pi-coding-agent";
3
+ import { PiSessionCreationError } from "./pi-adapter.js";
4
+ import { type SkillSelection } from "./skill-catalog.js";
5
+ export declare class PiSkillError extends PiSessionCreationError {
6
+ readonly alias?: string | undefined;
7
+ constructor(alias?: string | undefined);
8
+ }
9
+ interface SkillDependencies {
10
+ readonly stat: (path: string) => Promise<Stats>;
11
+ readonly access: (path: string, mode: number) => Promise<void>;
12
+ readonly realpath: (path: string) => Promise<string>;
13
+ readonly loadSkills: typeof loadSkills;
14
+ }
15
+ /** Load only the configured files, independently of package discovery and SDK deduplication. */
16
+ export declare function loadSelectedSkills(selection: readonly SkillSelection[], cwd: string, dependencies?: Partial<SkillDependencies>): Promise<Skill[]>;
17
+ export {};