@pluginfinity/engine 0.0.1 → 0.1.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/manifest.js ADDED
@@ -0,0 +1,45 @@
1
+ //#region src/manifest.ts
2
+ /** The name a target publishes under: its override, else the config's. */
3
+ const pluginName = (config, id) => {
4
+ const setting = config[id];
5
+ return typeof setting === "object" && setting.name !== void 0 ? setting.name : config.name;
6
+ };
7
+ const FORMATS = {
8
+ "claude-plugin-json": (_target, fields) => fields,
9
+ "agent-plugins-1.0": (target, fields) => {
10
+ if (target.manifest.schema === void 0) throw new Error("an agent-plugins-1.0 target must pin its manifest $schema");
11
+ return {
12
+ $schema: target.manifest.schema,
13
+ ...fields
14
+ };
15
+ }
16
+ };
17
+ /**
18
+ * Render a target's manifest from the config and the package version: the
19
+ * format's record, cut to the target's key allowlist, in allowlist order, with
20
+ * unset keys left out.
21
+ *
22
+ * @public
23
+ */
24
+ const renderManifest = (target, id, config, version) => {
25
+ const record = FORMATS[target.manifest.format](target, {
26
+ name: pluginName(config, id),
27
+ version,
28
+ description: config.description,
29
+ author: config.author,
30
+ homepage: config.homepage,
31
+ repository: config.repository,
32
+ license: config.license,
33
+ keywords: config.keywords
34
+ });
35
+ return Object.fromEntries(target.manifest.keys.filter((key) => record[key] !== void 0).map((key) => [key, record[key]]));
36
+ };
37
+ /**
38
+ * The bytes a manifest is written as: tab-indented JSON with a final newline.
39
+ *
40
+ * @public
41
+ */
42
+ const serializeManifest = (manifest) => `${JSON.stringify(manifest, null, " ")}\n`;
43
+
44
+ //#endregion
45
+ export { renderManifest, serializeManifest };
package/operations.js CHANGED
@@ -1,22 +1,268 @@
1
- import { NotImplemented } from "./errors.js";
1
+ import { BuildStale, ComponentsInvalid, HookEventUnsupported, HookScriptInvalid, HostRejected, NotImplemented, PackageVersionMissing, PathConflict, TargetDrift } from "./errors.js";
2
+ import { isJunk } from "./component.js";
3
+ import { readAgents, renderAgent } from "./agents.js";
2
4
  import { preparePlugins } from "./selection.js";
3
- import { Effect } from "effect";
5
+ import { applyEmit, planEmit } from "./emit.js";
6
+ import { hookCommandFiles, hookScripts, renderHooks, targetHooks } from "./hooks.js";
7
+ import { renderManifest, serializeManifest } from "./manifest.js";
8
+ import { readSkills, renderSkill } from "./skills.js";
9
+ import { Effect, FileSystem, Path, Schema } from "effect";
10
+ import { Run } from "@effected/commands";
11
+ import { KNOWN_TARGET_IDS, TARGETS } from "@pluginfinity/targets";
12
+ import { ChildProcess } from "effect/process";
4
13
 
5
14
  //#region src/operations.ts
15
+ const PackageVersion = Schema.fromJsonString(Schema.Struct({ version: Schema.String }));
16
+ /** The version every manifest copies: `version` in the `package.json` beside the config. */
17
+ const readVersion = (root) => Effect.gen(function* () {
18
+ const fs = yield* FileSystem.FileSystem;
19
+ const file = (yield* Path.Path).join(root, "package.json");
20
+ const text = yield* fs.readFileString(file).pipe(Effect.mapError(() => new PackageVersionMissing({ path: file })));
21
+ const { version } = yield* Schema.decodeUnknownEffect(PackageVersion)(text).pipe(Effect.mapError(() => new PackageVersionMissing({ path: file })));
22
+ return version;
23
+ });
24
+ const targetOf = (id) => {
25
+ const entry = TARGETS.find((candidate) => candidate.id === id);
26
+ if (entry === void 0) throw new Error(`no registry entry for target "${id}"`);
27
+ return entry.target;
28
+ };
29
+ /** Every file under `dir`, as `/`-separated paths relative to `root`; none when `dir` is absent. */
30
+ const sourceFiles = (root, dir) => Effect.gen(function* () {
31
+ const fs = yield* FileSystem.FileSystem;
32
+ const path = yield* Path.Path;
33
+ const absolute = path.join(root, dir);
34
+ if (!(yield* fs.exists(absolute))) return [];
35
+ const files = [];
36
+ for (const entry of yield* fs.readDirectory(absolute, { recursive: true })) {
37
+ if (isJunk(path.basename(entry))) continue;
38
+ if ((yield* fs.stat(path.join(absolute, entry))).type === "File") files.push(`${dir}/${entry.split(path.sep).join("/")}`);
39
+ }
40
+ return files.sort();
41
+ });
42
+ /** A source file copied verbatim: its bytes and its own mode. */
43
+ const copyFile = (root, file) => Effect.gen(function* () {
44
+ const fs = yield* FileSystem.FileSystem;
45
+ const absolute = (yield* Path.Path).join(root, file);
46
+ const info = yield* fs.stat(absolute);
47
+ return {
48
+ path: file,
49
+ content: yield* fs.readFile(absolute),
50
+ mode: info.mode & 511
51
+ };
52
+ });
53
+ /** Fail with `HookScriptInvalid` unless `script` exists, and is executable under `exec`. */
54
+ const checkScript = (config, script, invoke) => Effect.gen(function* () {
55
+ const fs = yield* FileSystem.FileSystem;
56
+ const path = yield* Path.Path;
57
+ const info = yield* fs.stat(path.join(config.root, script)).pipe(Effect.option);
58
+ if (info._tag === "None" || info.value.type !== "File") return yield* Effect.fail(new HookScriptInvalid({
59
+ path: config.path,
60
+ script,
61
+ problem: "missing"
62
+ }));
63
+ if (invoke === "exec" && (info.value.mode & 73) === 0) return yield* Effect.fail(new HookScriptInvalid({
64
+ path: config.path,
65
+ script,
66
+ problem: "not-executable"
67
+ }));
68
+ });
6
69
  /**
7
- * Regenerate `builds/<id>/`. Runs the real front half (find, load, check the
8
- * targets), then stops with `NotImplemented`.
70
+ * Render every requested target of one plugin and compare each with its build
71
+ * directory.
72
+ *
73
+ * @remarks
74
+ * Each target ships the source `hooks/` directory whole, so a script can
75
+ * source its own helpers, except scripts only another target's hooks run; a
76
+ * script outside `hooks/` ships to the targets that run it.
77
+ */
78
+ const planPlugin = (prepared) => Effect.gen(function* () {
79
+ const path = yield* Path.Path;
80
+ const config = prepared.config;
81
+ 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
+ const invoke = config.config.scripts?.invoke ?? "bash";
85
+ const hooks = prepared.targets.map((id) => {
86
+ const target = targetOf(id);
87
+ return {
88
+ id,
89
+ target,
90
+ ...targetHooks(target, id, config.config)
91
+ };
92
+ });
93
+ for (const { id, unsupported } of hooks) if (unsupported.length > 0) return yield* Effect.fail(new HookEventUnsupported({
94
+ path: config.path,
95
+ target: id,
96
+ events: unsupported.map((u) => u.event)
97
+ }));
98
+ const filesOf = (events) => [...hookScripts(events), ...hookCommandFiles(events)];
99
+ const everyScript = new Set(hooks.flatMap(({ events }) => filesOf(events)));
100
+ for (const { events } of hooks) {
101
+ for (const script of hookScripts(events)) yield* checkScript(config, script, invoke);
102
+ for (const file of hookCommandFiles(events)) yield* checkScript(config, file, "bash");
103
+ }
104
+ const hooksDir = yield* sourceFiles(config.root, "hooks");
105
+ const { skills, failures: skillFailures } = yield* readSkills(config.root, KNOWN_TARGET_IDS);
106
+ const { agents, failures: agentFailures } = yield* readAgents(config.root, KNOWN_TARGET_IDS);
107
+ const failures = [...skillFailures, ...agentFailures];
108
+ const collect = (effect) => effect.pipe(Effect.catchTag("ComponentInvalid", (error) => Effect.sync(() => {
109
+ if (!failures.some((seen) => seen.message === error.message)) failures.push(error);
110
+ })));
111
+ const planned = [];
112
+ for (const { id, target, events } of hooks) {
113
+ const own = new Set(filesOf(events));
114
+ const shipped = [...hooksDir.filter((file) => own.has(file) || !everyScript.has(file)), ...[...own].filter((script) => !script.startsWith("hooks/"))];
115
+ const copied = [];
116
+ for (const file of shipped) copied.push(yield* copyFile(config.root, file));
117
+ const manifest = renderManifest(target, id, config.config, version);
118
+ const generated = [{
119
+ path: target.manifest.path,
120
+ content: serializeManifest(manifest)
121
+ }];
122
+ 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))) ?? []);
128
+ 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);
131
+ }
132
+ const copiedPaths = new Set(copied.map((file) => file.path));
133
+ const conflict = generated.find((file) => copiedPaths.has(file.path));
134
+ if (conflict !== void 0) return yield* Effect.fail(new PathConflict({
135
+ path: config.path,
136
+ target: id,
137
+ file: conflict.path
138
+ }));
139
+ const files = [...generated, ...copied];
140
+ const out = path.join(config.root, "builds", id);
141
+ const plan = yield* planEmit(out, files);
142
+ planned.push({
143
+ config: config.path,
144
+ target: id,
145
+ out,
146
+ plan,
147
+ files,
148
+ name: String(manifest.name),
149
+ version
150
+ });
151
+ }
152
+ if (failures.length > 0) return yield* Effect.fail(new ComponentsInvalid({
153
+ path: config.path,
154
+ components: failures
155
+ }));
156
+ return planned;
157
+ });
158
+ /** Fail with `BuildStale` when any target's build directory differs. */
159
+ const requireClean = (config, planned) => {
160
+ const drift = planned.filter((target) => !target.plan.clean).map(({ target, plan }) => TargetDrift.make({
161
+ target,
162
+ added: plan.added,
163
+ changed: plan.changed,
164
+ removed: plan.removed
165
+ }));
166
+ return drift.length === 0 ? Effect.void : Effect.fail(new BuildStale({
167
+ path: config,
168
+ targets: drift
169
+ }));
170
+ };
171
+ /**
172
+ * Regenerate `builds/<id>/` for every selected plugin and target, writing
173
+ * only what differs. With `check`, write nothing and fail with
174
+ * `BuildStale` when anything differs.
9
175
  *
10
176
  * @public
11
177
  */
12
- const build = (input) => preparePlugins(input).pipe(Effect.andThen(Effect.fail(new NotImplemented({ operation: "build" }))));
178
+ const build = (input) => Effect.gen(function* () {
179
+ const builds = [];
180
+ for (const prepared of yield* preparePlugins(input)) {
181
+ const planned = yield* planPlugin(prepared);
182
+ if (input.check) yield* requireClean(prepared.config.path, planned);
183
+ 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({
185
+ config,
186
+ target,
187
+ out,
188
+ plan
189
+ });
190
+ }
191
+ return builds;
192
+ });
193
+ const CopilotPluginList = Schema.fromJsonString(Schema.Array(Schema.Struct({
194
+ name: Schema.String,
195
+ version: Schema.optionalKey(Schema.String),
196
+ source: Schema.String
197
+ })));
198
+ const commandLine = (command, args) => [command, ...args].join(" ");
199
+ /** Run a host CLI, turning a spawn failure into `HostRejected`. */
200
+ const runHost = (target, command, args) => Run.collect(ChildProcess.make(command, [...args])).pipe(Effect.mapError((error) => new HostRejected({
201
+ path: target.out,
202
+ target: target.target,
203
+ command: commandLine(command, args),
204
+ output: error.message
205
+ })));
206
+ const HOST_CHECKS = {
207
+ claude: (target) => Effect.gen(function* () {
208
+ const args = [
209
+ "plugin",
210
+ "validate",
211
+ target.out
212
+ ];
213
+ const output = yield* runHost(target, "claude", args);
214
+ if (output.exitCode !== 0) return yield* Effect.fail(new HostRejected({
215
+ path: target.out,
216
+ target: target.target,
217
+ command: commandLine("claude", args),
218
+ output: `${output.stdout}\n${output.stderr}`.trim()
219
+ }));
220
+ }),
221
+ copilot: (target) => Effect.gen(function* () {
222
+ const args = [
223
+ "--plugin-dir",
224
+ target.out,
225
+ "plugin",
226
+ "list",
227
+ "--json"
228
+ ];
229
+ const command = commandLine("copilot", args);
230
+ const reject = (output) => Effect.fail(new HostRejected({
231
+ path: target.out,
232
+ target: target.target,
233
+ command,
234
+ output
235
+ }));
236
+ const output = yield* runHost(target, "copilot", args);
237
+ if (output.exitCode !== 0) return yield* reject(`${output.stdout}\n${output.stderr}`.trim());
238
+ const loaded = (yield* Schema.decodeUnknownEffect(CopilotPluginList)(output.stdout).pipe(Effect.catch(() => reject(`could not read the plugin list: ${output.stdout.trim()}`)))).find((plugin) => plugin.source === "external" && plugin.name === target.name);
239
+ if (loaded === void 0) return yield* reject(`copilot did not load a plugin named "${target.name}"`);
240
+ if (loaded.version !== target.version) return yield* reject(`copilot loaded version ${loaded.version ?? "(none)"}, expected ${target.version}`);
241
+ })
242
+ };
13
243
  /**
14
- * Validate the plugin. Runs the real front half, then stops with
15
- * `NotImplemented`.
244
+ * Validate every selected plugin and target: the build directory must match a
245
+ * fresh build, then each host's CLI must accept it unless `skipHosts`.
16
246
  *
17
247
  * @public
18
248
  */
19
- const validate = (input) => preparePlugins(input).pipe(Effect.andThen(Effect.fail(new NotImplemented({ operation: "validate" }))));
249
+ const validate = (input) => Effect.gen(function* () {
250
+ const validations = [];
251
+ for (const prepared of yield* preparePlugins(input)) {
252
+ const planned = yield* planPlugin(prepared);
253
+ yield* requireClean(prepared.config.path, planned);
254
+ for (const target of planned) {
255
+ if (!input.skipHosts) yield* HOST_CHECKS[target.target](target);
256
+ validations.push({
257
+ config: target.config,
258
+ target: target.target,
259
+ out: target.out,
260
+ host: input.skipHosts ? "skipped" : "passed"
261
+ });
262
+ }
263
+ }
264
+ return validations;
265
+ });
20
266
 
21
267
  //#endregion
22
268
  export { build, validate };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pluginfinity/engine",
3
- "version": "0.0.1",
3
+ "version": "0.1.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": [
@@ -39,8 +39,9 @@
39
39
  "@effected/glob": "^0.10.0",
40
40
  "@effected/semver": "^0.11.0",
41
41
  "@effected/walker": "^0.15.0",
42
- "@pluginfinity/core": "0.0.1",
43
- "@pluginfinity/targets": "0.0.1",
42
+ "@effected/yaml": "^0.19.0",
43
+ "@pluginfinity/core": "0.1.1",
44
+ "@pluginfinity/targets": "0.1.1",
44
45
  "jiti": "^2.6.1"
45
46
  },
46
47
  "peerDependencies": {
package/skills.js ADDED
@@ -0,0 +1,132 @@
1
+ import { applyHostBlocks } from "./body.js";
2
+ import { appendSections, mapFrontmatter } from "./frontmatter.js";
3
+ import { decodeComponent, frontmatterText, invalid, isJunk, issue, overlayIssues, toLf, unknownTargets } from "./component.js";
4
+ import { ComponentName, SKILL_FIELDS, SkillFrontmatter } from "@pluginfinity/core";
5
+ import { Effect, FileSystem, Path, Schema } from "effect";
6
+
7
+ //#region src/skills.ts
8
+ /**
9
+ * The most characters a built skill's `description` may hold: the Agent
10
+ * Skills spec's limit, which Copilot enforces.
11
+ *
12
+ * @public
13
+ */
14
+ const SKILL_DESCRIPTION_MAX = 1024;
15
+ /** Every file under `dir`, as sorted `/`-separated relative paths. */
16
+ const filesUnder = (dir) => Effect.gen(function* () {
17
+ const fs = yield* FileSystem.FileSystem;
18
+ const path = yield* Path.Path;
19
+ const files = [];
20
+ for (const entry of yield* fs.readDirectory(dir, { recursive: true })) {
21
+ if (isJunk(path.basename(entry))) continue;
22
+ if ((yield* fs.stat(path.join(dir, entry))).type === "File") files.push(entry.split(path.sep).join("/"));
23
+ }
24
+ return files.sort();
25
+ });
26
+ /** Read and decode one skill directory. */
27
+ const readSkill = (dir, name, known) => Effect.gen(function* () {
28
+ const fs = yield* FileSystem.FileSystem;
29
+ const file = (yield* Path.Path).join(dir, "SKILL.md");
30
+ if (!Schema.is(ComponentName)(name)) return yield* Effect.fail(invalid(dir, [issue("", "the directory name must be 1 to 64 characters of a-z, 0-9 and single hyphens")]));
31
+ if (!(yield* fs.exists(file))) return yield* Effect.fail(invalid(dir, [issue("", "the skill has no SKILL.md")]));
32
+ const { frontmatter, frontmatterText: text, body, bodyOffset } = yield* decodeComponent(file, yield* fs.readFileString(file), SkillFrontmatter);
33
+ const problems = [...frontmatter.name !== void 0 && frontmatter.name !== name ? [issue("name", `must equal the directory name "${name}"`)] : [], ...unknownTargets(frontmatter.targets, known)];
34
+ if (problems.length > 0) return yield* Effect.fail(invalid(file, problems));
35
+ return {
36
+ name,
37
+ path: file,
38
+ frontmatter,
39
+ frontmatterText: text,
40
+ body,
41
+ bodyOffset,
42
+ files: (yield* filesUnder(dir)).filter((entry) => entry !== "SKILL.md")
43
+ };
44
+ });
45
+ /**
46
+ * Read every skill under `<root>/skills/`, sorted by name; none when the
47
+ * directory is absent. A skill that does not decode is collected in
48
+ * `failures` rather than stopping the read, so one build reports them all.
49
+ *
50
+ * @public
51
+ */
52
+ const readSkills = (root, known) => Effect.gen(function* () {
53
+ const fs = yield* FileSystem.FileSystem;
54
+ const path = yield* Path.Path;
55
+ const dir = path.join(root, "skills");
56
+ if (!(yield* fs.exists(dir))) return {
57
+ skills: [],
58
+ failures: []
59
+ };
60
+ const skills = [];
61
+ const failures = [];
62
+ for (const entry of (yield* fs.readDirectory(dir)).sort()) {
63
+ const skillDir = path.join(dir, entry);
64
+ if ((yield* fs.stat(skillDir)).type !== "Directory") continue;
65
+ const skill = yield* readSkill(skillDir, entry, known).pipe(Effect.catchTag("ComponentInvalid", (error) => Effect.sync(() => void failures.push(error))));
66
+ if (skill !== void 0) skills.push(skill);
67
+ }
68
+ return {
69
+ skills,
70
+ failures
71
+ };
72
+ });
73
+ /**
74
+ * Render one skill for a target, or `undefined` when its `targets` block
75
+ * excludes it: `SKILL.md` with the target's frontmatter and host blocks
76
+ * applied, `.md` support files with host blocks applied, and every other
77
+ * file copied. Every file keeps its source mode.
78
+ *
79
+ * @public
80
+ */
81
+ const renderSkill = (target, id, skill, known) => Effect.gen(function* () {
82
+ const fs = yield* FileSystem.FileSystem;
83
+ const path = yield* Path.Path;
84
+ const block = skill.frontmatter.targets?.[id];
85
+ if (block === false) return void 0;
86
+ const mapped = mapFrontmatter(target, target.skills.fields, target.skills.hostFields, skill.frontmatter, block ?? {});
87
+ const problems = [
88
+ ...yield* overlayIssues(SkillFrontmatter, SKILL_FIELDS, skill.frontmatter, block ?? {}, id),
89
+ ...mapped.unresolved.map((field) => issue(field.field, `${id} leaves this field unresolved (${field.note})`)),
90
+ ...mapped.unknown.map((key) => issue(`targets.${id}.${key}`, `not a skill field or a ${id} skill field`))
91
+ ];
92
+ const { name: _name, description, ...rest } = mapped.fields;
93
+ if (typeof description === "string" && description.length > 1024) problems.push(issue("description", `is ${description.length} characters on ${id}, over the ${SKILL_DESCRIPTION_MAX} limit; set a shorter targets.${id}.description`));
94
+ const body = applyHostBlocks(skill.body, id, known);
95
+ if ("problem" in body) return yield* Effect.fail(invalid(skill.path, [issue(`line ${body.problem.line + skill.bodyOffset}`, body.problem.message)]));
96
+ if (problems.length > 0) return yield* Effect.fail(invalid(skill.path, problems, id));
97
+ const yaml = yield* frontmatterText({
98
+ name: skill.name,
99
+ description,
100
+ ...rest
101
+ }, skill);
102
+ const dir = path.dirname(skill.path);
103
+ const out = `${target.skills.dir}/${skill.name}`;
104
+ const files = [{
105
+ path: `${out}/SKILL.md`,
106
+ content: `---\n${yaml}---\n${appendSections("text" in body ? body.text : "", mapped.sections)}`,
107
+ mode: (yield* fs.stat(skill.path)).mode & 511
108
+ }];
109
+ for (const file of skill.files) {
110
+ const absolute = path.join(dir, file);
111
+ const mode = (yield* fs.stat(absolute)).mode & 511;
112
+ if (!file.endsWith(".md")) {
113
+ files.push({
114
+ path: `${out}/${file}`,
115
+ content: yield* fs.readFile(absolute),
116
+ mode
117
+ });
118
+ continue;
119
+ }
120
+ const processed = applyHostBlocks(toLf(yield* fs.readFileString(absolute)), id, known);
121
+ if ("problem" in processed) return yield* Effect.fail(invalid(absolute, [issue(`line ${processed.problem.line}`, processed.problem.message)]));
122
+ files.push({
123
+ path: `${out}/${file}`,
124
+ content: processed.text,
125
+ mode
126
+ });
127
+ }
128
+ return files;
129
+ });
130
+
131
+ //#endregion
132
+ export { SKILL_DESCRIPTION_MAX, readSkills, renderSkill };
package/version.js CHANGED
@@ -12,7 +12,7 @@
12
12
  *
13
13
  * @public
14
14
  */
15
- const ENGINE_VERSION = "0.0.1";
15
+ const ENGINE_VERSION = "0.1.1";
16
16
 
17
17
  //#endregion
18
18
  export { ENGINE_VERSION };