@pluginfinity/engine 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/notes.js ADDED
@@ -0,0 +1,29 @@
1
+ //#region src/notes.ts
2
+ /**
3
+ * Every note kind, in the order they are sorted and printed.
4
+ *
5
+ * @public
6
+ */
7
+ const BUILD_NOTE_KINDS = [
8
+ "dropped",
9
+ "degraded",
10
+ "tool-dropped",
11
+ "hook-omitted"
12
+ ];
13
+ /** The path of notes about the config: hooks and servers. */
14
+ const CONFIG_NOTE_PATH = "config";
15
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
16
+ const order = (a, b) => Number(a.path === "config") - Number(b.path === "config") || compare(a.path, b.path) || BUILD_NOTE_KINDS.indexOf(a.kind) - BUILD_NOTE_KINDS.indexOf(b.kind) || compare(a.name, b.name);
17
+ /** The notes without duplicates, sorted by path (the config last), then kind, then name. */
18
+ const sortNotes = (notes) => {
19
+ const seen = /* @__PURE__ */ new Set();
20
+ return notes.filter((note) => {
21
+ const key = `${note.target}\0${note.path}\0${note.kind}\0${note.name}`;
22
+ if (seen.has(key)) return false;
23
+ seen.add(key);
24
+ return true;
25
+ }).sort(order);
26
+ };
27
+
28
+ //#endregion
29
+ export { BUILD_NOTE_KINDS, CONFIG_NOTE_PATH, sortNotes };
package/operations.js CHANGED
@@ -1,14 +1,19 @@
1
- import { BuildStale, ComponentsInvalid, HookEventUnsupported, HookScriptInvalid, HostRejected, NotImplemented, PackageVersionMissing, PathConflict, TargetDrift } from "./errors.js";
1
+ import { BuildStale, ComponentInvalid, ComponentsInvalid, HookEventUnsupported, HookScriptInvalid, HostRejected, PackageVersionMissing, PathConflict, ShippedFileInvalid, TargetDrift } from "./errors.js";
2
2
  import { isJunk } from "./component.js";
3
3
  import { readAgents, renderAgent } from "./agents.js";
4
4
  import { preparePlugins } from "./selection.js";
5
+ import { ENGINE_VERSION } from "./version.js";
5
6
  import { applyEmit, planEmit } from "./emit.js";
6
7
  import { hookCommandFiles, hookScripts, renderHooks, targetHooks } from "./hooks.js";
7
- import { renderManifest, serializeManifest } from "./manifest.js";
8
+ import { pluginName, renderManifest, serializeManifest } from "./manifest.js";
9
+ import { CONFIG_NOTE_PATH, sortNotes } from "./notes.js";
10
+ import { HOOK_LIB_DIR, hookLibFiles } from "./hook-lib.js";
11
+ import { SERVER_LIB_DIR, serverLibFiles } from "./server-lib.js";
12
+ import { mcpServerNames, renderServers, serverFiles } from "./servers.js";
8
13
  import { readSkills, renderSkill } from "./skills.js";
9
14
  import { Effect, FileSystem, Path, Schema } from "effect";
10
- import { Run } from "@effected/commands";
11
15
  import { KNOWN_TARGET_IDS, TARGETS } from "@pluginfinity/targets";
16
+ import { Run } from "@effected/commands";
12
17
  import { ChildProcess } from "effect/process";
13
18
 
14
19
  //#region src/operations.ts
@@ -66,6 +71,115 @@ const checkScript = (config, script, invoke) => Effect.gen(function* () {
66
71
  problem: "not-executable"
67
72
  }));
68
73
  });
74
+ /** Whether `real` is `root` or under it; both are real paths. */
75
+ const isInside = (root, real) => real === root || real.startsWith(`${root}/`);
76
+ /** Whether a plugin-relative path has no empty, `.` or `..` segment. */
77
+ const isNormal = (file) => file.split("/").every((segment) => segment !== "" && segment !== "." && segment !== "..");
78
+ /**
79
+ * A plugin-relative path with its empty, `.` and `..` segments resolved, or
80
+ * `undefined` when it climbs out of the plugin root.
81
+ */
82
+ const canonical = (file) => {
83
+ const segments = [];
84
+ for (const segment of file.split("/")) {
85
+ if (segment === "" || segment === ".") continue;
86
+ if (segment !== "..") segments.push(segment);
87
+ else if (segments.pop() === void 0) return void 0;
88
+ }
89
+ return segments.join("/");
90
+ };
91
+ /**
92
+ * The files one canonical, plugin-relative path ships: the file, or every
93
+ * file under the directory. `spelled` is the path as written, which is what
94
+ * is checked for existence, so a trailing `/` after a file fails as missing.
95
+ * Every shipped file must resolve inside the plugin, through any symlink.
96
+ */
97
+ const expandShipped = (config, file, spelled, referencedBy) => Effect.gen(function* () {
98
+ const fs = yield* FileSystem.FileSystem;
99
+ const path = yield* Path.Path;
100
+ const fail = (named, problem) => Effect.fail(new ShippedFileInvalid({
101
+ path: config.path,
102
+ file: named,
103
+ referencedBy,
104
+ problem
105
+ }));
106
+ const info = yield* fs.stat(path.join(config.root, spelled)).pipe(Effect.option);
107
+ if (info._tag === "None" || info.value.type !== "File" && info.value.type !== "Directory") return yield* fail(spelled, "missing");
108
+ const files = info.value.type === "Directory" ? yield* sourceFiles(config.root, file) : [file];
109
+ const root = yield* fs.realPath(config.root);
110
+ for (const listed of files) if (!isInside(root, yield* fs.realPath(path.join(config.root, listed)))) return yield* fail(listed, "outside-root");
111
+ return files;
112
+ });
113
+ /**
114
+ * The files `entries` name, each canonical: each file, or every file under
115
+ * each directory. Every one must exist and resolve inside the plugin.
116
+ */
117
+ const listedFiles = (config, entries) => Effect.gen(function* () {
118
+ const fail = (file, problem) => Effect.fail(new ShippedFileInvalid({
119
+ path: config.path,
120
+ file,
121
+ referencedBy: "files",
122
+ problem
123
+ }));
124
+ const out = [];
125
+ for (const entry of entries) {
126
+ const file = canonical(entry);
127
+ if (file === void 0) return yield* fail(entry, "outside-root");
128
+ if (file === "") return yield* fail(entry, "not-normal");
129
+ out.push(...yield* expandShipped(config, file, file, "files"));
130
+ }
131
+ return out;
132
+ });
133
+ /**
134
+ * The files a server reference ships, failing with `ShippedFileInvalid`
135
+ * unless it is written without `.`, `..` or empty segments (a directory may
136
+ * end in one `/`) and exists inside the plugin. A file ships alone and a
137
+ * directory ships every file under it, like a `files` entry. A whole
138
+ * `command` must be a file, and executable.
139
+ */
140
+ const serverShipped = (config, spelled, referencedBy, command) => Effect.gen(function* () {
141
+ const fs = yield* FileSystem.FileSystem;
142
+ const path = yield* Path.Path;
143
+ const fail = (problem) => Effect.fail(new ShippedFileInvalid({
144
+ path: config.path,
145
+ file: spelled,
146
+ referencedBy,
147
+ problem
148
+ }));
149
+ const file = spelled.endsWith("/") ? spelled.slice(0, -1) : spelled;
150
+ if (!isNormal(file)) return yield* fail("not-normal");
151
+ if (command) {
152
+ const info = yield* fs.stat(path.join(config.root, file)).pipe(Effect.option);
153
+ if (info._tag === "Some" && info.value.type === "Directory") return yield* fail("directory");
154
+ }
155
+ const files = yield* expandShipped(config, file, spelled, referencedBy);
156
+ if (command) {
157
+ if (((yield* fs.stat(path.join(config.root, file))).mode & 73) === 0) return yield* fail("not-executable");
158
+ }
159
+ return files;
160
+ });
161
+ /**
162
+ * What a target's skill and agent bodies may name: the skills and agents it
163
+ * builds, every file of those skills, and the plugin's own MCP servers. Agent
164
+ * ids and skill commands use the plugin's name on this target; own MCP tools
165
+ * are named, and their run-time `{plugin}` filled, by its Claude name, which
166
+ * Claude Code namespaces MCP tools with.
167
+ */
168
+ const tokenContext = (target, id, config, skills, agents) => {
169
+ const plugin = pluginName(config, id);
170
+ const built = skills.filter((skill) => skill.frontmatter.targets?.[id] !== false);
171
+ return {
172
+ target,
173
+ plugin,
174
+ skills: new Set(built.map((skill) => skill.name)),
175
+ agents: new Set(agents.filter((agent) => agent.frontmatter.targets?.[id] !== false).map((agent) => agent.name)),
176
+ skillFiles: new Set(built.flatMap((skill) => [`${skill.name}/SKILL.md`, ...skill.files.map((file) => `${skill.name}/${file}`)])),
177
+ own: {
178
+ plugin: pluginName(config, "claude"),
179
+ servers: mcpServerNames(id, config)
180
+ }
181
+ };
182
+ };
69
183
  /**
70
184
  * Render every requested target of one plugin and compare each with its build
71
185
  * directory.
@@ -73,14 +187,25 @@ const checkScript = (config, script, invoke) => Effect.gen(function* () {
73
187
  * @remarks
74
188
  * Each target ships the source `hooks/` directory whole, so a script can
75
189
  * source its own helpers, except scripts only another target's hooks run; a
76
- * script outside `hooks/` ships to the targets that run it.
190
+ * script outside `hooks/` ships to the targets that run it. A target with
191
+ * hooks also gets the hook library under `hooks/lib/pluginfinity/`. That path
192
+ * is always reserved, whether or not the target has hooks: no source file may
193
+ * be at it or under it.
194
+ *
195
+ * Each target also ships the files its local MCP and LSP servers name after
196
+ * `${PLUGIN_ROOT}/` (written without `.` or `..` segments, inside the plugin,
197
+ * and an executable file when a whole `command`; a named directory ships every
198
+ * file under it), and every file the `files` key lists, each once. A target
199
+ * with a local server gets the server library under `lib/pluginfinity/`,
200
+ * which is reserved the same way. A target that writes its servers inline
201
+ * in its manifest also reserves the server file its host loads by default
202
+ * (Claude Code's `.mcp.json` and `.lsp.json`), but only when this plugin
203
+ * has servers of that kind inline.
77
204
  */
78
205
  const planPlugin = (prepared) => Effect.gen(function* () {
79
206
  const path = yield* Path.Path;
80
207
  const config = prepared.config;
81
208
  const version = yield* readVersion(config.root);
82
- const settings = prepared.targets.map((id) => config.config[id]);
83
- if (config.config.mcpServers !== void 0 || settings.some((setting) => typeof setting === "object" && setting.mcpServers !== void 0)) return yield* Effect.fail(new NotImplemented({ operation: "build of mcpServers" }));
84
209
  const invoke = config.config.scripts?.invoke ?? "bash";
85
210
  const hooks = prepared.targets.map((id) => {
86
211
  const target = targetOf(id);
@@ -96,45 +221,94 @@ const planPlugin = (prepared) => Effect.gen(function* () {
96
221
  events: unsupported.map((u) => u.event)
97
222
  }));
98
223
  const filesOf = (events) => [...hookScripts(events), ...hookCommandFiles(events)];
99
- const everyScript = new Set(hooks.flatMap(({ events }) => filesOf(events)));
224
+ const everyScript = new Set(config.targets.flatMap((id) => filesOf(targetHooks(targetOf(id), id, config.config).events)));
100
225
  for (const { events } of hooks) {
101
226
  for (const script of hookScripts(events)) yield* checkScript(config, script, invoke);
102
227
  for (const file of hookCommandFiles(events)) yield* checkScript(config, file, "bash");
103
228
  }
104
229
  const hooksDir = yield* sourceFiles(config.root, "hooks");
230
+ const listed = yield* listedFiles(config, config.config.files ?? []);
105
231
  const { skills, failures: skillFailures } = yield* readSkills(config.root, KNOWN_TARGET_IDS);
106
232
  const { agents, failures: agentFailures } = yield* readAgents(config.root, KNOWN_TARGET_IDS);
107
233
  const failures = [...skillFailures, ...agentFailures];
108
- const collect = (effect) => effect.pipe(Effect.catchTag("ComponentInvalid", (error) => Effect.sync(() => {
234
+ const keep = (error) => {
109
235
  if (!failures.some((seen) => seen.message === error.message)) failures.push(error);
110
- })));
236
+ };
237
+ const collect = (effect) => effect.pipe(Effect.catchTag("ComponentInvalid", (error) => Effect.sync(() => keep(error))), Effect.catchTag("ComponentsInvalid", (error) => Effect.sync(() => error.components.forEach(keep))));
111
238
  const planned = [];
112
- for (const { id, target, events } of hooks) {
239
+ for (const { id, target, events, omitted } of hooks) {
240
+ const notes = omitted.map((event) => ({
241
+ target: id,
242
+ path: CONFIG_NOTE_PATH,
243
+ kind: "hook-omitted",
244
+ name: event
245
+ }));
113
246
  const own = new Set(filesOf(events));
114
- const shipped = [...hooksDir.filter((file) => own.has(file) || !everyScript.has(file)), ...[...own].filter((script) => !script.startsWith("hooks/"))];
247
+ const servers = serverFiles(target, id, config.config);
248
+ const serverFilesShipped = [];
249
+ for (const file of servers.commands) serverFilesShipped.push(...yield* serverShipped(config, file, servers.owners.get(file) ?? "mcpServers", true));
250
+ for (const file of servers.others) serverFilesShipped.push(...yield* serverShipped(config, file, servers.owners.get(file) ?? "mcpServers", false));
251
+ const shipped = [.../* @__PURE__ */ new Set([
252
+ ...hooksDir.filter((file) => own.has(file) || !everyScript.has(file)),
253
+ ...[...own].filter((script) => !script.startsWith("hooks/")),
254
+ ...serverFilesShipped,
255
+ ...listed
256
+ ])];
115
257
  const copied = [];
116
258
  for (const file of shipped) copied.push(yield* copyFile(config.root, file));
117
- const manifest = renderManifest(target, id, config.config, version);
259
+ const rendered = renderServers(target, id, config.config, pluginName(config.config, id), SERVER_LIB_DIR);
260
+ if (rendered.issues.length > 0) {
261
+ const issue = new ComponentInvalid({
262
+ path: config.path,
263
+ target: id,
264
+ issues: rendered.issues
265
+ });
266
+ if (!failures.some((seen) => seen.message === issue.message)) failures.push(issue);
267
+ }
268
+ const manifest = renderManifest(target, id, config.config, version, rendered.manifest);
118
269
  const generated = [{
119
270
  path: target.manifest.path,
120
271
  content: serializeManifest(manifest)
121
272
  }];
122
273
  const hooksFile = renderHooks(target, events, invoke);
123
- if (hooksFile !== void 0) generated.push({
124
- path: target.hooks.path,
125
- content: hooksFile
126
- });
127
- for (const skill of skills) generated.push(...(yield* collect(renderSkill(target, id, skill, KNOWN_TARGET_IDS))) ?? []);
274
+ if (hooksFile !== void 0) {
275
+ generated.push({
276
+ path: target.hooks.path,
277
+ content: hooksFile
278
+ });
279
+ generated.push(...hookLibFiles(id, String(manifest.name), ENGINE_VERSION));
280
+ }
281
+ generated.push(...rendered.files);
282
+ notes.push(...rendered.notes);
283
+ if (rendered.stdio) generated.push(...serverLibFiles());
284
+ const tokens = tokenContext(target, id, config.config, skills, agents);
285
+ for (const skill of skills) {
286
+ const skillRender = yield* collect(renderSkill(target, id, skill, KNOWN_TARGET_IDS, tokens));
287
+ if (skillRender === void 0) continue;
288
+ generated.push(...skillRender.files);
289
+ notes.push(...skillRender.notes);
290
+ }
128
291
  for (const agent of agents) {
129
- const file = yield* collect(renderAgent(target, id, agent, KNOWN_TARGET_IDS));
130
- if (file !== void 0) generated.push(file);
292
+ const agentRender = yield* collect(renderAgent(target, id, agent, KNOWN_TARGET_IDS, tokens));
293
+ if (agentRender === void 0) continue;
294
+ generated.push(agentRender.file);
295
+ notes.push(...agentRender.notes);
131
296
  }
297
+ const reservedFiles = new Set([target.mcp.placement, target.lsp.placement].flatMap((placement) => placement._tag === "manifest" && placement.key in rendered.manifest ? [placement.reserves] : []));
298
+ const reserved = copied.find((file) => reservedFiles.has(file.path) || ["hooks/lib/pluginfinity", "lib/pluginfinity"].some((dir) => file.path === dir || file.path.startsWith(`${dir}/`)));
299
+ if (reserved !== void 0) return yield* Effect.fail(new PathConflict({
300
+ path: config.path,
301
+ target: id,
302
+ file: reserved.path,
303
+ conflict: reservedFiles.has(reserved.path) ? "reserved-server-file" : "reserved-dir"
304
+ }));
132
305
  const copiedPaths = new Set(copied.map((file) => file.path));
133
306
  const conflict = generated.find((file) => copiedPaths.has(file.path));
134
307
  if (conflict !== void 0) return yield* Effect.fail(new PathConflict({
135
308
  path: config.path,
136
309
  target: id,
137
- file: conflict.path
310
+ file: conflict.path,
311
+ conflict: "generated"
138
312
  }));
139
313
  const files = [...generated, ...copied];
140
314
  const out = path.join(config.root, "builds", id);
@@ -144,6 +318,7 @@ const planPlugin = (prepared) => Effect.gen(function* () {
144
318
  target: id,
145
319
  out,
146
320
  plan,
321
+ notes: sortNotes(notes),
147
322
  files,
148
323
  name: String(manifest.name),
149
324
  version
@@ -181,11 +356,12 @@ const build = (input) => Effect.gen(function* () {
181
356
  const planned = yield* planPlugin(prepared);
182
357
  if (input.check) yield* requireClean(prepared.config.path, planned);
183
358
  else for (const target of planned) yield* applyEmit(target.out, target.files, target.plan);
184
- for (const { config, target, out, plan } of planned) builds.push({
359
+ for (const { config, target, out, plan, notes } of planned) builds.push({
185
360
  config,
186
361
  target,
187
362
  out,
188
- plan
363
+ plan,
364
+ notes
189
365
  });
190
366
  }
191
367
  return builds;
@@ -257,7 +433,8 @@ const validate = (input) => Effect.gen(function* () {
257
433
  config: target.config,
258
434
  target: target.target,
259
435
  out: target.out,
260
- host: input.skipHosts ? "skipped" : "passed"
436
+ host: input.skipHosts ? "skipped" : "passed",
437
+ notes: target.notes
261
438
  });
262
439
  }
263
440
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluginfinity/engine",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "description": "The pluginfinity build pipeline shared by every pluginfinity front end: config discovery, read, transform per target, emit and check.",
6
6
  "keywords": [
@@ -35,13 +35,13 @@
35
35
  },
36
36
  "dependencies": {
37
37
  "@effected/commands": "^0.11.0",
38
- "@effected/engine": "^0.3.0",
38
+ "@effected/engine": "^0.4.0",
39
39
  "@effected/glob": "^0.10.0",
40
40
  "@effected/semver": "^0.11.0",
41
41
  "@effected/walker": "^0.15.0",
42
- "@effected/yaml": "^0.19.0",
43
- "@pluginfinity/core": "0.1.1",
44
- "@pluginfinity/targets": "0.1.1",
42
+ "@effected/yaml": "^0.19.1",
43
+ "@pluginfinity/core": "0.2.1",
44
+ "@pluginfinity/targets": "0.2.1",
45
45
  "jiti": "^2.6.1"
46
46
  },
47
47
  "peerDependencies": {
@@ -0,0 +1,9 @@
1
+ //#region src/server-lib.generated.ts
2
+ /** The server library's files, embedded so a build needs no asset on disk. */
3
+ const SERVER_LIB_FILES = [{
4
+ name: "server.sh",
5
+ content: "# shellcheck shell=sh\n# pluginfinity server library. `pluginfinity build` writes this file into every\n# target that has a local MCP or LSP server; do not edit a copy under builds/,\n# the next build overwrites it.\n#\n# Source it first in a launcher, and keep `set -u` (or write\n# ${PLUGINFINITY_LIB:?run by the host}) so a launcher run outside the host fails loudly:\n# . \"$PLUGINFINITY_LIB/server.sh\"\n#\n# POSIX sh. Writes nothing to stdout, which carries the server's protocol.\n\n_pf_server_lib_dir=$(cd \"$(dirname \"$PLUGINFINITY_LIB/server.sh\")\" && pwd -P)\n\n# claude or copilot.\nserver_host() { printf '%s\\n' \"${PLUGINFINITY_HOST:-unknown}\"; }\n\n# The build root the launcher runs from.\nserver_plugin_root() { (cd \"$_pf_server_lib_dir/../..\" && pwd -P); }\n\n# Append a line to the plugin's server error log.\nserver_log() {\n _pf_dir=\"${XDG_STATE_HOME:-${HOME:-/nonexistent}/.local/state}/pluginfinity/${PLUGINFINITY_PLUGIN:-unknown}\"\n mkdir -p \"$_pf_dir\" 2>/dev/null || return 0\n printf '%s [%s] %s\\n' \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\" \"$(server_host)\" \"$*\" >>\"$_pf_dir/server-error.log\" 2>/dev/null || return 0\n}\n\n# The project the session works in. Prints it and returns 0, or prints nothing\n# and returns 1 when there is none to report:\n# - Claude with CLAUDE_PROJECT_DIR set: that directory.\n# - Otherwise, when the working directory is the plugin root or inside it:\n# nothing, status 1. Copilot starts an MCP server with its cwd at the plugin\n# root and gives it no project directory, so that cwd says nothing about the\n# project. On Copilot, MCP servers get no project directory; a server should\n# ask its MCP client for roots.\n# - Otherwise: the closest directory above $PWD holding .git, else $PWD\n# (Copilot starts LSP servers at the git root).\nserver_project_dir() {\n if [ \"${PLUGINFINITY_HOST:-}\" = claude ] && [ -n \"${CLAUDE_PROJECT_DIR:-}\" ]; then\n printf '%s\\n' \"$CLAUDE_PROJECT_DIR\"\n return 0\n fi\n _pf_root=$(server_plugin_root)\n _pf_cwd=$(pwd -P)\n case \"$_pf_cwd\" in\n \"$_pf_root\" | \"$_pf_root\"/*) return 1 ;;\n esac\n _pf_probe=$PWD\n while [ -n \"$_pf_probe\" ] && [ \"$_pf_probe\" != / ]; do\n if [ -e \"$_pf_probe/.git\" ]; then\n printf '%s\\n' \"$_pf_probe\"\n return 0\n fi\n _pf_probe=$(dirname \"$_pf_probe\")\n done\n printf '%s\\n' \"$PWD\"\n}\n\n# npm, pnpm, yarn or bun: package.json's packageManager first, then lockfiles.\n_pf_detect_pm() { # project\n _pf_pm=\"\"\n if [ -f \"$1/package.json\" ]; then\n _pf_pm=$(grep -o '\"packageManager\"[[:space:]]*:[[:space:]]*\"[^\"]*\"' \"$1/package.json\" 2>/dev/null |\n sed -E 's/.*:[[:space:]]*\"([a-z]+)@.*/\\1/')\n fi\n case \"$_pf_pm\" in npm | pnpm | yarn | bun)\n printf '%s\\n' \"$_pf_pm\"\n return 0\n ;;\n esac\n if [ -f \"$1/pnpm-lock.yaml\" ]; then\n printf 'pnpm\\n'\n elif [ -f \"$1/bun.lock\" ] || [ -f \"$1/bun.lockb\" ]; then\n printf 'bun\\n'\n elif [ -f \"$1/yarn.lock\" ]; then\n printf 'yarn\\n'\n else\n printf 'npm\\n'\n fi\n}\n\n_pf_install_line() { # pm package\n case \"$1\" in\n pnpm) printf ' pnpm add -D %s\\n' \"$2\" ;;\n yarn) printf ' yarn add -D %s\\n' \"$2\" ;;\n bun) printf ' bun add -d %s\\n' \"$2\" ;;\n *) printf ' npm install --save-dev %s\\n' \"$2\" ;;\n esac\n}\n\n# Exec the project's node_modules/.bin/<bin>, else npx --yes <package>. With no\n# project directory (see server_project_dir) it skips the lookup and the\n# install hint, and goes straight to npx. An optional `--install <package>`\n# straight after the two positionals names a different package in the install\n# hint only; npx still runs <package>. Later args pass through untouched.\nserver_exec_bin() { # bin package [--install install-package] [args...]\n _pf_bin=$1\n _pf_pkg=$2\n _pf_install=$2\n shift 2\n if [ \"${1:-}\" = --install ] && [ $# -ge 2 ]; then\n _pf_install=$2\n shift 2\n fi\n if _pf_project=$(server_project_dir); then\n if [ -x \"$_pf_project/node_modules/.bin/$_pf_bin\" ]; then\n exec \"$_pf_project/node_modules/.bin/$_pf_bin\" \"$@\"\n fi\n _pf_pm=$(_pf_detect_pm \"$_pf_project\")\n {\n printf '%s: %s is not installed in %s.\\n' \"${PLUGINFINITY_PLUGIN:-plugin}\" \"$_pf_bin\" \"$_pf_project\"\n printf 'Install it with:\\n'\n _pf_install_line \"$_pf_pm\" \"$_pf_install\"\n } >&2\n else\n printf '%s: no project directory is known, so %s cannot be looked up in node_modules.\\n' \\\n \"${PLUGINFINITY_PLUGIN:-plugin}\" \"$_pf_bin\" >&2\n fi\n printf 'Falling back to \"npx --yes %s\".\\n' \"$_pf_pkg\" >&2\n exec npx --yes \"$_pf_pkg\" \"$@\"\n}\n"
6
+ }];
7
+
8
+ //#endregion
9
+ export { SERVER_LIB_FILES };
package/server-lib.js ADDED
@@ -0,0 +1,21 @@
1
+ import { SERVER_LIB_FILES } from "./server-lib.generated.js";
2
+
3
+ //#region src/server-lib.ts
4
+ /**
5
+ * Where every build that has a local server gets the server library, relative to the build root.
6
+ *
7
+ * @public
8
+ */
9
+ const SERVER_LIB_DIR = "lib/pluginfinity";
10
+ /**
11
+ * The server library, as one target's build writes it.
12
+ *
13
+ * @public
14
+ */
15
+ const serverLibFiles = () => SERVER_LIB_FILES.map((file) => ({
16
+ path: `${SERVER_LIB_DIR}/${file.name}`,
17
+ content: file.content
18
+ }));
19
+
20
+ //#endregion
21
+ export { SERVER_LIB_DIR, serverLibFiles };
package/servers.js ADDED
@@ -0,0 +1,256 @@
1
+ import { ConfigIssue } from "./errors.js";
2
+ import { CONFIG_NOTE_PATH } from "./notes.js";
3
+
4
+ //#region src/servers.ts
5
+ const PLACEHOLDER = `\${PLUGIN_ROOT}`;
6
+ const ROOT_FILE = /\$\{PLUGIN_ROOT\}\/([^\s"'`;|&<>()$:,]+)/g;
7
+ const HOST_ROOT = /\$\{(?:CLAUDE|COPILOT)_PLUGIN_ROOT\}|\$(?:CLAUDE_|COPILOT_)?PLUGIN_ROOT(?![A-Za-z0-9_])/;
8
+ const merged = (id, config, key) => {
9
+ const setting = config[id];
10
+ const base = config[key] ?? {};
11
+ const own = typeof setting === "object" ? setting[key] ?? {} : {};
12
+ const out = /* @__PURE__ */ new Map();
13
+ for (const [name, server] of Object.entries(base)) out.set(name, [
14
+ name,
15
+ key,
16
+ server
17
+ ]);
18
+ for (const [name, server] of Object.entries(own)) out.set(name, [
19
+ name,
20
+ `${id}.${key}`,
21
+ server
22
+ ]);
23
+ return [...out.values()];
24
+ };
25
+ /**
26
+ * The names of every MCP server the target builds: the base servers and the
27
+ * target's own.
28
+ */
29
+ const mcpServerNames = (id, config) => new Set(merged(id, config, "mcpServers").map(([name]) => name));
30
+ const isStdio = (server) => server.type === void 0 || server.type === "stdio";
31
+ const rewrite = (value, root) => {
32
+ if (typeof value === "string") return value.replaceAll(PLACEHOLDER, root);
33
+ if (Array.isArray(value)) return value.map((item) => rewrite(item, root));
34
+ if (typeof value === "object" && value !== null) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, rewrite(v, root)]));
35
+ return value;
36
+ };
37
+ const MCP_ROOT_FIELDS = [
38
+ "command",
39
+ "args",
40
+ "env",
41
+ "cwd"
42
+ ];
43
+ const LSP_ROOT_FIELDS = [
44
+ "command",
45
+ "args",
46
+ "env",
47
+ "workspaceFolder"
48
+ ];
49
+ const strings = (value) => {
50
+ if (typeof value === "string") return [value];
51
+ if (Array.isArray(value)) return value.flatMap(strings);
52
+ if (typeof value === "object" && value !== null) return Object.values(value).flatMap(strings);
53
+ return [];
54
+ };
55
+ const hostSpellings = (server, fields, key, issues) => {
56
+ for (const field of fields) {
57
+ const spelled = strings(server[field]).find((value) => HOST_ROOT.test(value))?.match(HOST_ROOT)?.[0];
58
+ if (spelled === void 0) continue;
59
+ issues.push(ConfigIssue.make({
60
+ key: `${key}.${field}`,
61
+ message: `${spelled} is one host's spelling of the plugin root; write \${PLUGIN_ROOT} and the build rewrites it for each target`
62
+ }));
63
+ }
64
+ };
65
+ const only = (server, fields) => Object.fromEntries(Object.entries(server).filter(([field]) => fields.includes(field)));
66
+ const rewriteFields = (server, fields, root) => Object.fromEntries(Object.entries(server).map(([field, value]) => [field, fields.includes(field) ? rewrite(value, root) : value]));
67
+ const serialize = (value) => `${JSON.stringify(value, null, " ")}\n`;
68
+ const injectedEnv = (id, plugin, root, libDir) => ({
69
+ PLUGINFINITY_HOST: id,
70
+ PLUGINFINITY_PLUGIN: plugin,
71
+ PLUGINFINITY_LIB: `${root}/${libDir}`
72
+ });
73
+ const withEnv = (server, env) => ({
74
+ ...server,
75
+ env: {
76
+ ...server.env ?? {},
77
+ ...env
78
+ }
79
+ });
80
+ const rootOf = (spelling, key, issues) => {
81
+ if (typeof spelling === "string") return spelling;
82
+ issues.push(ConfigIssue.make({
83
+ key,
84
+ message: spelling.note
85
+ }));
86
+ };
87
+ const mapField = (entry, field, value, out, key, issues, dropped) => {
88
+ switch (entry?._tag) {
89
+ case "keep":
90
+ out[field] = value;
91
+ return;
92
+ case "rename":
93
+ out[entry.to] = value;
94
+ return;
95
+ case "drop":
96
+ dropped.push(key);
97
+ return;
98
+ case "unresolved":
99
+ issues.push(ConfigIssue.make({
100
+ key,
101
+ message: entry.note
102
+ }));
103
+ return;
104
+ default: issues.push(ConfigIssue.make({
105
+ key,
106
+ message: `no server rule for field ${field}`
107
+ }));
108
+ }
109
+ };
110
+ const mcpEntries = ({ servers, env, root, issues }, copilot) => {
111
+ const out = {};
112
+ for (const [name, origin, server] of servers) {
113
+ if (!isStdio(server)) {
114
+ out[name] = copilot && server.type === "http" ? {
115
+ ...server,
116
+ type: "streamable-http"
117
+ } : { ...server };
118
+ continue;
119
+ }
120
+ hostSpellings(server, MCP_ROOT_FIELDS, `${origin}.${name}`, issues);
121
+ const rewritten = rewriteFields(server, MCP_ROOT_FIELDS, root);
122
+ if (!copilot && "cwd" in rewritten) {
123
+ issues.push(ConfigIssue.make({
124
+ key: `${origin}.${name}.cwd`,
125
+ message: "Claude Code ignores an MCP server's cwd (it runs in the project directory); set cwd under copilot.mcpServers or cd in the launcher instead"
126
+ }));
127
+ delete rewritten.cwd;
128
+ }
129
+ out[name] = copilot ? {
130
+ type: "stdio",
131
+ ...withEnv(rewritten, env)
132
+ } : withEnv(rewritten, env);
133
+ }
134
+ return out;
135
+ };
136
+ const MCP_ENCODERS = {
137
+ "claude-mcp-servers": (input) => mcpEntries(input, false),
138
+ "agent-plugins-mcp-1.0": (input) => ({
139
+ ...input.target.mcp.schema === void 0 ? {} : { $schema: input.target.mcp.schema },
140
+ mcpServers: mcpEntries(input, true)
141
+ })
142
+ };
143
+ const lspEntries = ({ target, servers, env, root, issues, dropped }) => {
144
+ const out = {};
145
+ for (const [name, origin, server] of servers) {
146
+ const entry = {};
147
+ hostSpellings(server, LSP_ROOT_FIELDS, `${origin}.${name}`, issues);
148
+ for (const [field, value] of Object.entries(rewriteFields(server, LSP_ROOT_FIELDS, root))) mapField(target.lsp.fields[field], field, value, entry, `${origin}.${name}.${field}`, issues, dropped);
149
+ out[name] = withEnv(entry, env);
150
+ }
151
+ return out;
152
+ };
153
+ const LSP_ENCODERS = {
154
+ "claude-lsp-servers": (input) => lspEntries(input),
155
+ "copilot-lsp-json": (input) => ({ lspServers: lspEntries(input) })
156
+ };
157
+ const place = (placement, value, files, manifest) => {
158
+ if (placement._tag === "file") files.push({
159
+ path: placement.path,
160
+ content: serialize(value)
161
+ });
162
+ else manifest[placement.key] = value;
163
+ };
164
+ /**
165
+ * The target's MCP and LSP configs: base servers with the target's
166
+ * overrides applied by name, `${PLUGIN_ROOT}` rewritten to the target's
167
+ * spelling, LSP fields mapped through the target's field map, and the
168
+ * server-library variables added to every local server's `env`. Each config
169
+ * goes where the target places it: a file of its own, or inline under a
170
+ * manifest key, for `renderManifest` to write.
171
+ *
172
+ * @public
173
+ */
174
+ const renderServers = (target, id, config, plugin, libDir) => {
175
+ const issues = [];
176
+ const dropped = [];
177
+ const files = [];
178
+ const manifest = {};
179
+ const mcp = merged(id, config, "mcpServers");
180
+ const lsp = merged(id, config, "lspServers");
181
+ if (mcp.length > 0) {
182
+ const root = rootOf(target.pluginRoot.mcp, "mcpServers", issues);
183
+ if (root !== void 0) {
184
+ const env = injectedEnv(id, plugin, root, libDir);
185
+ const value = MCP_ENCODERS[target.mcp.format]({
186
+ target,
187
+ servers: mcp,
188
+ env,
189
+ root,
190
+ issues
191
+ });
192
+ place(target.mcp.placement, value, files, manifest);
193
+ }
194
+ }
195
+ if (lsp.length > 0) {
196
+ const root = rootOf(target.pluginRoot.lsp, "lspServers", issues);
197
+ if (root !== void 0) {
198
+ const env = injectedEnv(id, plugin, root, libDir);
199
+ const value = LSP_ENCODERS[target.lsp.format]({
200
+ target,
201
+ servers: lsp,
202
+ env,
203
+ root,
204
+ issues,
205
+ dropped
206
+ });
207
+ place(target.lsp.placement, value, files, manifest);
208
+ }
209
+ }
210
+ return {
211
+ files,
212
+ manifest,
213
+ issues,
214
+ stdio: mcp.some(([, , server]) => isStdio(server)) || lsp.length > 0,
215
+ notes: dropped.map((name) => ({
216
+ target: id,
217
+ path: CONFIG_NOTE_PATH,
218
+ kind: "dropped",
219
+ name
220
+ }))
221
+ };
222
+ };
223
+ const filesIn = (value) => strings(value).flatMap((text) => [...text.matchAll(ROOT_FILE)].map((match) => match[1] ?? ""));
224
+ /**
225
+ * The plugin files a target's servers name after `${PLUGIN_ROOT}/`: those a
226
+ * whole `command` names, which must be executable, and every other one.
227
+ * Only the fields the root placeholder is documented in are scanned.
228
+ *
229
+ * @public
230
+ */
231
+ const serverFiles = (target, id, config) => {
232
+ const mcp = merged(id, config, "mcpServers").flatMap(([name, origin, server]) => isStdio(server) ? [[`${origin}.${name}`, only(server, MCP_ROOT_FIELDS)]] : []);
233
+ const lsp = merged(id, config, "lspServers").map(([name, origin, server]) => [`${origin}.${name}`, only(server, LSP_ROOT_FIELDS.filter((field) => target.lsp.fields[field]?._tag !== "unresolved"))]);
234
+ const servers = [...mcp, ...lsp];
235
+ const commands = /* @__PURE__ */ new Set();
236
+ const others = /* @__PURE__ */ new Set();
237
+ const owners = /* @__PURE__ */ new Map();
238
+ for (const [owner, server] of servers) {
239
+ const command = typeof server.command === "string" ? server.command : "";
240
+ const whole = command.startsWith(`${PLACEHOLDER}/`) && filesIn(command)[0] === command.slice(PLACEHOLDER.length + 1);
241
+ if (whole) commands.add(command.slice(PLACEHOLDER.length + 1));
242
+ for (const file of filesIn({
243
+ ...server,
244
+ command: whole ? "" : command
245
+ })) others.add(file);
246
+ for (const file of filesIn(server)) if (!owners.has(file)) owners.set(file, owner);
247
+ }
248
+ return {
249
+ commands: [...commands],
250
+ others: [...others].filter((file) => !commands.has(file)),
251
+ owners
252
+ };
253
+ };
254
+
255
+ //#endregion
256
+ export { mcpServerNames, renderServers, serverFiles };