@jini-ai/plugins 0.0.0-stage → 0.4.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 (84) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +201 -0
  3. package/README.md +60 -2
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +52 -0
  5. package/dist/glue/attachment-points/content-lifecycle.js +15 -0
  6. package/dist/glue/attachment-points/events.d.ts +12 -0
  7. package/dist/glue/attachment-points/events.js +5 -0
  8. package/dist/glue/attachment-points/tool-registration.d.ts +23 -0
  9. package/dist/glue/attachment-points/tool-registration.js +43 -0
  10. package/dist/glue/capability-gate.d.ts +73 -0
  11. package/dist/glue/capability-gate.js +41 -0
  12. package/dist/glue/dispatch.d.ts +20 -0
  13. package/dist/glue/dispatch.js +9 -0
  14. package/dist/glue/index.d.ts +8 -0
  15. package/dist/glue/index.js +8 -0
  16. package/dist/glue/manifest.d.ts +43 -0
  17. package/dist/glue/manifest.js +106 -0
  18. package/dist/glue/ports.d.ts +60 -0
  19. package/dist/glue/ports.js +2 -0
  20. package/dist/host/activation.d.ts +118 -0
  21. package/dist/host/activation.js +104 -0
  22. package/dist/host/attach-loaded-plugin.d.ts +37 -0
  23. package/dist/host/attach-loaded-plugin.js +19 -0
  24. package/dist/host/capability-sdk.d.ts +74 -0
  25. package/dist/host/capability-sdk.js +94 -0
  26. package/dist/host/claim-conflicts.d.ts +101 -0
  27. package/dist/host/claim-conflicts.js +139 -0
  28. package/dist/host/contributions.d.ts +129 -0
  29. package/dist/host/contributions.js +167 -0
  30. package/dist/host/declarative-enable.d.ts +43 -0
  31. package/dist/host/declarative-enable.js +73 -0
  32. package/dist/host/discovery-types.d.ts +55 -0
  33. package/dist/host/discovery-types.js +2 -0
  34. package/dist/host/errors.d.ts +20 -0
  35. package/dist/host/errors.js +22 -0
  36. package/dist/host/hook-registry.d.ts +113 -0
  37. package/dist/host/hook-registry.js +190 -0
  38. package/dist/host/index.d.ts +19 -0
  39. package/dist/host/index.js +19 -0
  40. package/dist/host/manifest.d.ts +159 -0
  41. package/dist/host/manifest.js +417 -0
  42. package/dist/host/node/discovery.d.ts +32 -0
  43. package/dist/host/node/discovery.js +241 -0
  44. package/dist/host/node/index.d.ts +8 -0
  45. package/dist/host/node/index.js +8 -0
  46. package/dist/host/node/install.d.ts +118 -0
  47. package/dist/host/node/install.js +431 -0
  48. package/dist/host/node/loader.d.ts +55 -0
  49. package/dist/host/node/loader.js +146 -0
  50. package/dist/host/node/module-snapshot.d.ts +25 -0
  51. package/dist/host/node/module-snapshot.js +53 -0
  52. package/dist/host/node/package-files.d.ts +52 -0
  53. package/dist/host/node/package-files.js +214 -0
  54. package/dist/host/node/source-drafts.d.ts +98 -0
  55. package/dist/host/node/source-drafts.js +323 -0
  56. package/dist/host/plugin-claims.d.ts +75 -0
  57. package/dist/host/plugin-claims.js +182 -0
  58. package/dist/host/ports.d.ts +208 -0
  59. package/dist/host/ports.js +2 -0
  60. package/dist/host/quarantine.d.ts +19 -0
  61. package/dist/host/quarantine.js +28 -0
  62. package/dist/host/repo.memory.d.ts +27 -0
  63. package/dist/host/repo.memory.js +33 -0
  64. package/dist/host/source-policy.d.ts +18 -0
  65. package/dist/host/source-policy.js +13 -0
  66. package/dist/host/sql/index.d.ts +4 -0
  67. package/dist/host/sql/index.js +4 -0
  68. package/dist/host/sql/repo.d.ts +38 -0
  69. package/dist/host/sql/repo.js +50 -0
  70. package/dist/host/sql/repo.rows.d.ts +28 -0
  71. package/dist/host/sql/repo.rows.js +28 -0
  72. package/dist/host/tool-contributions.d.ts +26 -0
  73. package/dist/host/tool-contributions.js +42 -0
  74. package/dist/host/uninstall.d.ts +88 -0
  75. package/dist/host/uninstall.js +112 -0
  76. package/dist/host/worker/import-seam.d.ts +45 -0
  77. package/dist/host/worker/import-seam.js +52 -0
  78. package/dist/host/worker/index.d.ts +5 -0
  79. package/dist/host/worker/index.js +5 -0
  80. package/dist/host/worker/protocol.d.ts +62 -0
  81. package/dist/host/worker/protocol.js +31 -0
  82. package/dist/host/worker/run-call.d.ts +27 -0
  83. package/dist/host/worker/run-call.js +76 -0
  84. package/package.json +107 -3
@@ -0,0 +1,431 @@
1
+ import { readPluginIdentity, assertPluginIdentityAvailable } from "@jini-ai/core/plugin-directory";
2
+ /** Local-install environment consent is host-owned; archiveReader owns zip-slip/decompression
3
+ * checks and tierPolicy.checkInstall owns publisher admission. */
4
+ /** Site plugin folder installer governed by plugin-install-plan.md, M1a.
5
+ * Installation inspects JSON and bytes only: importing code belongs exclusively to enable.
6
+ * Staging is a sibling of discovery's root, on the same filesystem, so partial copies never list.
7
+ */
8
+ import { constants } from "node:fs";
9
+ import { lstat, realpath, readdir, readFile, open, mkdir, mkdtemp, writeFile, rename, rm } from "node:fs/promises";
10
+ import path from "node:path";
11
+ import { createHash } from "node:crypto";
12
+ import * as semver from "semver";
13
+ import { validateManifest, validatePluginIdFormat } from "../manifest.js";
14
+ export class PluginInstallError extends Error {
15
+ code;
16
+ constructor(code, message) {
17
+ super(message);
18
+ this.code = code;
19
+ this.name = "PluginInstallError";
20
+ }
21
+ }
22
+ const MANIFEST = "tovu.plugin.json";
23
+ const MAX_ENTRIES = 4096;
24
+ const MAX_FILE_BYTES = 16 * 1024 * 1024;
25
+ const MAX_TOTAL_BYTES = 64 * 1024 * 1024;
26
+ const hash = (bytes) => `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
27
+ function fail(code, message) { throw new PluginInstallError(code, message); }
28
+ const inside = (parent, child) => child === parent || child.startsWith(parent + path.sep);
29
+ async function exists(target) {
30
+ try {
31
+ await lstat(target);
32
+ return true;
33
+ }
34
+ catch (e) {
35
+ if (e.code === "ENOENT")
36
+ return false;
37
+ throw e;
38
+ }
39
+ }
40
+ /** Activation callbacks share this guard; the activation service compensates a rejected enable. */
41
+ export async function assertPluginInstallIdle(required, _optional = {}) {
42
+ if (await exists(path.resolve(required.installDir) + "-install-lock"))
43
+ fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
44
+ }
45
+ /** Retain the inspected bytes, rather than copying a mutable source after consent verification. */
46
+ async function snapshot(sourceDir, limits = {}) {
47
+ for (const limit of Object.values(limits)) {
48
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1))
49
+ fail('PLUGIN_SNAPSHOT_LIMIT_INVALID', 'Snapshot limits must be positive safe integers.');
50
+ }
51
+ const maxEntries = Math.min(limits.maxEntries ?? MAX_ENTRIES, MAX_ENTRIES);
52
+ const maxFileBytes = Math.min(limits.maxFileBytes ?? MAX_FILE_BYTES, MAX_FILE_BYTES);
53
+ const maxTotalBytes = Math.min(limits.maxTotalBytes ?? MAX_TOTAL_BYTES, MAX_TOTAL_BYTES);
54
+ const files = new Map();
55
+ let entries = 0;
56
+ let total = 0;
57
+ async function walk(dir, prefix) {
58
+ const stat = await lstat(dir);
59
+ if (!stat.isDirectory() || stat.isSymbolicLink())
60
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package directories must not be symbolic links.");
61
+ for (const name of (await readdir(dir)).sort()) {
62
+ if (++entries > maxEntries)
63
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package has too many entries.");
64
+ const target = path.join(dir, name);
65
+ const relative = prefix + name;
66
+ const info = await lstat(target);
67
+ if (info.isSymbolicLink())
68
+ fail("PLUGIN_PACKAGE_UNSAFE", "Symbolic links are not allowed.");
69
+ if (info.isDirectory()) {
70
+ await walk(target, relative + "/");
71
+ continue;
72
+ }
73
+ if (!info.isFile() || info.nlink !== 1)
74
+ fail("PLUGIN_PACKAGE_UNSAFE", "Only regular files without hard links are allowed.");
75
+ if (info.size > maxFileBytes || total + info.size > maxTotalBytes)
76
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package exceeds the file or total size limit.");
77
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
78
+ try {
79
+ const current = await handle.stat();
80
+ if (!current.isFile() || current.nlink !== 1 || current.ino !== info.ino || current.dev !== info.dev)
81
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
82
+ // A bounded read also protects against a file growing after stat().
83
+ const buffer = Buffer.alloc(info.size + 1);
84
+ let length = 0;
85
+ while (length < buffer.length) {
86
+ const read = await handle.read(buffer, length, buffer.length - length, null);
87
+ if (read.bytesRead === 0)
88
+ break;
89
+ length += read.bytesRead;
90
+ }
91
+ if (length > maxFileBytes || total + length > maxTotalBytes)
92
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package grew past its size limit.");
93
+ if (length > info.size || (await handle.stat()).size !== length)
94
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
95
+ total += length;
96
+ files.set(relative, Buffer.from(buffer.subarray(0, length)));
97
+ }
98
+ finally {
99
+ await handle.close();
100
+ }
101
+ }
102
+ }
103
+ await walk(sourceDir, "");
104
+ return Object.assign(files, { entryCount: entries });
105
+ }
106
+ /** Files a manifest-only package may carry: documentation, data and images — nothing a browser or
107
+ * Node would execute. An allowlist, so a new script-like extension is refused by default (SVG is
108
+ * left out on purpose: it can carry script). */
109
+ const DECLARATIVE_DATA_FILE = /(?:^|\/)(?:LICENSE|[^/]+\.(?:json|md|txt|png|jpe?g|gif|webp))$/;
110
+ /**
111
+ * Tier rules for a sideloaded package. Tier-1 (AW-7, 2026-10-04) is the manifest-only tier ADR-024
112
+ * §1 defines — "zero executable code", so it is safe from any publisher: it may not ship a single
113
+ * code file (its declarations — no code surface, parseable `contentTypes` — are already checked by
114
+ * `validateManifest`). Anything else must
115
+ * still be tier-3 with `server/index.mjs`, because a sideloaded manifest cannot grant itself a
116
+ * verified publisher tier (tier-2 needs the sandbox, which does not exist yet).
117
+ */
118
+ function checkTierAndCode(candidate, files, tierPolicy) {
119
+ if (candidate.tier === "tier-1") {
120
+ const code = [...files.keys()].filter((key) => key !== MANIFEST && !DECLARATIVE_DATA_FILE.test(key));
121
+ if (code.length)
122
+ fail("PLUGIN_MANIFEST_INVALID", `A declarative (tier-1) plugin must not ship code: ${code.join(", ")}`);
123
+ return;
124
+ }
125
+ if (!files.has("server/index.mjs"))
126
+ fail("PLUGIN_MANIFEST_INVALID", "server/index.mjs is required.");
127
+ tierPolicy.checkInstall({ manifest: candidate, files });
128
+ }
129
+ function validatePackage(files, deps) {
130
+ const { builtInIds } = deps;
131
+ let raw;
132
+ try {
133
+ raw = JSON.parse(files.get(MANIFEST)?.toString("utf8") ?? "");
134
+ }
135
+ catch {
136
+ return fail("PLUGIN_MANIFEST_INVALID", "A valid tovu.plugin.json is required.");
137
+ }
138
+ const candidate = raw;
139
+ const id = typeof candidate?.id === "string" ? candidate.id : "";
140
+ if (builtInIds.some((builtin) => builtin.toLowerCase() === id.toLowerCase()))
141
+ fail("PLUGIN_SHADOWS_BUILT_IN", "Package id belongs to a built-in plugin.");
142
+ const result = validateManifest({ ...deps, manifest: raw, folderName: id, builtInIds });
143
+ // The manifest's own messages, so a refused declaration says what is wrong with it.
144
+ if (result.errors.length)
145
+ fail("PLUGIN_MANIFEST_INVALID", result.errors.map((error) => error.message).join("; "));
146
+ // validateManifest owns the id grammar; only the version needs extra path-safety checks.
147
+ if (!candidate || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
148
+ fail("PLUGIN_MANIFEST_INVALID", "Package manifest, id or version is invalid.");
149
+ checkTierAndCode(candidate, files, deps.tierPolicy);
150
+ if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
151
+ fail("PLUGIN_MANIFEST_INVALID", "A name and valid SDK range are required.");
152
+ if (!candidate.integrity || typeof candidate.integrity !== "object" || Array.isArray(candidate.integrity))
153
+ fail("PLUGIN_INTEGRITY_INVALID", "An integrity map is required.");
154
+ const packaged = [...files.keys()].filter((key) => key !== MANIFEST).sort();
155
+ if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
156
+ fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except tovu.plugin.json.");
157
+ for (const key of packaged)
158
+ if (candidate.integrity[key] !== hash(files.get(key)))
159
+ fail("PLUGIN_INTEGRITY_INVALID", `Integrity mismatch: ${key}`);
160
+ return candidate;
161
+ }
162
+ async function checkDestination(manifest, input, deps) {
163
+ const root = path.resolve(deps.installDir);
164
+ const scan = deps.identityFilesystem ?? { lstat, readdir, readFile };
165
+ const entries = await scan.readdir(root).catch((e) => { if (e.code === "ENOENT")
166
+ return []; throw e; });
167
+ const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
168
+ const candidate = { ...identity, family: "site-runtime", localId: manifest.id };
169
+ const builtIns = (deps.builtInManifests ?? []).map(builtIn => ({
170
+ ...readPluginIdentity({ manifest: builtIn, name: builtIn.id, namespace: deps.identityNamespace ?? "tovu" }),
171
+ family: "site-runtime", localId: builtIn.id, version: builtIn.version, enabled: false,
172
+ }));
173
+ try {
174
+ assertPluginIdentityAvailable({ candidate, installed: builtIns });
175
+ }
176
+ catch {
177
+ fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
178
+ }
179
+ const warnUnavailableSlot = (localId, error) => {
180
+ if (!['ENOENT', 'EACCES'].includes(error.code ?? ''))
181
+ throw error;
182
+ // A disappearing/unreadable neighbour is isolated; link refusals and other I/O faults remain fatal.
183
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed slot is unavailable; omitted from identity admission.`);
184
+ };
185
+ for (const localId of entries) {
186
+ const slot = path.join(root, localId);
187
+ let versions;
188
+ try {
189
+ const info = await scan.lstat(slot);
190
+ if (info.isSymbolicLink())
191
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
192
+ if (!info.isDirectory())
193
+ continue;
194
+ versions = await scan.readdir(slot);
195
+ }
196
+ catch (error) {
197
+ warnUnavailableSlot(localId, error);
198
+ continue;
199
+ }
200
+ for (const version of versions) {
201
+ if (!semver.valid(version))
202
+ continue;
203
+ const versionDir = path.join(slot, version);
204
+ try {
205
+ const versionInfo = await scan.lstat(versionDir);
206
+ if (versionInfo.isSymbolicLink())
207
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin version must not be a link.");
208
+ if (!versionInfo.isDirectory())
209
+ continue;
210
+ }
211
+ catch (error) {
212
+ warnUnavailableSlot(localId, error);
213
+ continue;
214
+ }
215
+ const manifestPath = path.join(versionDir, MANIFEST);
216
+ let installed;
217
+ try {
218
+ const manifestInfo = await scan.lstat(manifestPath);
219
+ if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
220
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
221
+ const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
222
+ installed = readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace ?? "tovu" });
223
+ }
224
+ catch (error) {
225
+ if (error instanceof PluginInstallError)
226
+ throw error;
227
+ // Preserve link refusals while isolating one broken unrelated manifest.
228
+ (deps.warn ?? console.warn)(`Plugin '${localId}': installed identity manifest is unreadable or invalid; omitted from identity admission.`);
229
+ continue;
230
+ }
231
+ try {
232
+ assertPluginIdentityAvailable({ candidate,
233
+ installed: [{ ...installed, family: "site-runtime", localId, version, enabled: false }] });
234
+ }
235
+ catch {
236
+ fail("PLUGIN_ID_CONFLICT", "The publisher-qualified plugin id conflicts with an installed package.");
237
+ }
238
+ }
239
+ }
240
+ if (entries.some((name) => name.toLowerCase() === manifest.id.toLowerCase() && name !== manifest.id))
241
+ fail("PLUGIN_ID_CONFLICT", "A plugin id differs only by letter case.");
242
+ if (await exists(path.join(path.dirname(root), path.basename(root) + "-trash", manifest.id)))
243
+ fail("PLUGIN_IN_TRASH", "Restore or delete this plugin in Trash first.");
244
+ const slot = path.join(root, manifest.id);
245
+ const versionExists = await exists(path.join(slot, manifest.version));
246
+ if ((!deps.versionAppend || versionExists) && (await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === manifest.id.toLowerCase() && row.enabled))
247
+ fail("PLUGIN_ENABLED", "Turn the plugin off in every workspace first.");
248
+ if (!(await exists(slot)))
249
+ return undefined;
250
+ const stat = await lstat(slot);
251
+ if (!stat.isDirectory() || stat.isSymbolicLink())
252
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
253
+ const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
254
+ if (versions.some((version) => !semver.valid(version)))
255
+ fail("PLUGIN_ID_CONFLICT", "Existing plugin has an unrecognized version folder.");
256
+ const latest = versions.sort(semver.rcompare)[0];
257
+ if (latest && semver.lt(manifest.version, latest))
258
+ fail("PLUGIN_DOWNGRADE", "Installing an older version is not allowed.");
259
+ if (versions.some((version) => semver.eq(version, manifest.version)) && (deps.versionAppend || !input.replace))
260
+ fail("PLUGIN_VERSION_EXISTS", deps.versionAppend ? "Version append requires a new version; installed bytes are immutable." : "This version exists. Choose replace explicitly.");
261
+ return latest;
262
+ }
263
+ /** Retire obsolete immutable source releases after a successful controlled reload.
264
+ * All workspace active pointers survive, plus the newest three versions for rollback.
265
+ * Uses the installer's publication lock so pruning cannot overlap a package install.
266
+ * @returns Retired version names; dotfiles are unrelated metadata and remain untouched.
267
+ * @throws PluginInstallError for unsafe paths, invalid version slots or an active install.
268
+ * @complexity O(V log V + A) for V installed versions and A activation rows, then one removal per retired version.
269
+ */
270
+ export async function pruneSitePluginVersions(required, _optional = {}) {
271
+ if (validatePluginIdFormat({ id: required.id }).length)
272
+ fail('PLUGIN_PACKAGE_UNSAFE', 'Invalid plugin id.');
273
+ const root = path.resolve(required.installDir);
274
+ const slot = path.join(root, required.id);
275
+ for (const target of [root, slot]) {
276
+ const info = await lstat(target);
277
+ if (!info.isDirectory() || info.isSymbolicLink())
278
+ fail('PLUGIN_PACKAGE_UNSAFE', 'Installed plugin directory must not be a link.');
279
+ }
280
+ return withPluginInstallLock({ root, run: async () => {
281
+ const versions = (await readdir(slot)).filter(name => !name.startsWith('.'));
282
+ if (versions.some(version => !semver.valid(version)))
283
+ fail('PLUGIN_ID_CONFLICT', 'Existing plugin has an unrecognized version folder.');
284
+ const retained = new Set(versions.sort(semver.rcompare).slice(0, 3));
285
+ for (const row of await required.repo.listAll())
286
+ if (row.pluginId === required.id && row.enabled)
287
+ retained.add(row.version);
288
+ const retired = versions.filter(version => !retained.has(version));
289
+ for (const version of retired)
290
+ await rm(path.join(slot, version), { recursive: true, force: true });
291
+ return retired;
292
+ } });
293
+ }
294
+ async function inspect(input, deps) {
295
+ const files = input.archive !== undefined ? new Map([...await deps.archiveReader({ archive: input.archive })].map(([key, bytes]) => [key, Buffer.from(bytes)])) : await inspectFolder(input.sourceDir, deps);
296
+ const manifest = validatePackage(files, deps);
297
+ const upgradeFrom = await checkDestination(manifest, input, deps);
298
+ // Include manifest bytes: changed capabilities/name/version must invalidate human consent too.
299
+ const digest = digestSitePluginSnapshot({ files });
300
+ const identity = readPluginIdentity({ manifest: manifest, name: manifest.id, namespace: deps.identityNamespace ?? "tovu" });
301
+ const preview = { warnings: identity.warnings, publisherId: identity.id, provides: identity.provides, keywords: identity.keywords, id: manifest.id, name: manifest.name, version: manifest.version, tier: manifest.tier, capabilities: manifest.capabilities, hooks: manifest.hooks, hasCode: manifest.tier !== "tier-1", contentTypes: deps.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => decl.key), conflicts: await deps.conflicts({ manifest }), digest, ...(upgradeFrom ? { upgradeFrom } : {}) };
302
+ return { files, manifest, preview };
303
+ }
304
+ async function inspectFolder(source, deps) {
305
+ const sourceDir = await realpath(source).catch(() => fail("PLUGIN_SOURCE_INVALID", "Source folder was not found."));
306
+ if ((await lstat(source)).isSymbolicLink())
307
+ fail("PLUGIN_PACKAGE_UNSAFE", "Source folder must not be a link.");
308
+ // Canonicalize existing ancestors too: lexical checks alone miss symlink aliases.
309
+ async function canonical(target) {
310
+ try {
311
+ return await realpath(target);
312
+ }
313
+ catch (e) {
314
+ if (e.code !== "ENOENT")
315
+ throw e;
316
+ return path.join(await canonical(path.dirname(target)), path.basename(target));
317
+ }
318
+ }
319
+ const root = await canonical(path.resolve(deps.installDir));
320
+ for (const destination of [root, root + "-staging", root + "-trash"]) {
321
+ if (inside(destination, sourceDir) || inside(sourceDir, destination))
322
+ fail("PLUGIN_SOURCE_INVALID", "Source must be separate from installed, staging and Trash folders.");
323
+ }
324
+ return snapshot(sourceDir);
325
+ }
326
+ /** Loader uses the same bounded, link-free byte snapshot, then verifies the retained bytes. */
327
+ export async function snapshotSitePluginPackage(required, optional = {}) {
328
+ return snapshot(required.sourceDir, optional);
329
+ }
330
+ /** The installer's consent digest, also used to bind site-authored provenance to exact bytes.
331
+ * @returns A SHA-256 digest covering the manifest and every retained file.
332
+ */
333
+ export function digestSitePluginSnapshot(required, _optional = {}) {
334
+ return hash(Buffer.from(JSON.stringify([...required.files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
335
+ }
336
+ export async function computePluginIntegrity(required, _optional = {}) {
337
+ return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => key !== MANIFEST).map(([key, bytes]) => [key, hash(bytes)]));
338
+ }
339
+ export async function previewSitePluginInstall(required, _optional = {}) {
340
+ return (await inspect(required, required.deps)).preview;
341
+ }
342
+ /** Directory lock is also cross-process: CLI and admin cannot replace the same site concurrently. */
343
+ async function withPluginInstallLock(required, _optional = {}) {
344
+ const lock = required.root + '-install-lock';
345
+ await mkdir(path.dirname(required.root), { recursive: true });
346
+ try {
347
+ await mkdir(lock);
348
+ }
349
+ catch (error) {
350
+ if (error.code === 'EEXIST')
351
+ fail('PLUGIN_INSTALL_BUSY', 'Another install is in progress.');
352
+ throw error;
353
+ }
354
+ try {
355
+ return await required.run();
356
+ }
357
+ finally {
358
+ await rm(lock, { recursive: true, force: true });
359
+ }
360
+ }
361
+ /** Publication and retention use the same installer-owned cross-process lock. */
362
+ export async function installSitePlugin(required, _optional = {}) {
363
+ const optional = required.deps;
364
+ const root = path.resolve(optional.installDir);
365
+ const { files, manifest, preview } = await inspect(required, optional);
366
+ if (preview.digest !== required.expectedDigest)
367
+ fail("PLUGIN_CHANGED_SINCE_PREVIEW", "Package changed since preview. Review it again.");
368
+ for (const target of [root, root + "-staging", root + "-trash"]) {
369
+ if (await exists(target)) {
370
+ const info = await lstat(target);
371
+ if (!info.isDirectory() || info.isSymbolicLink())
372
+ fail("PLUGIN_PACKAGE_UNSAFE", "Install, staging and Trash roots must be real directories.");
373
+ }
374
+ }
375
+ return withPluginInstallLock({ root, run: async () => {
376
+ let staging;
377
+ try {
378
+ await mkdir(root + "-staging", { recursive: true });
379
+ staging = await mkdtemp(path.join(root + "-staging", "install-"));
380
+ const stagedSlot = path.join(staging, "new");
381
+ const versionDir = path.join(stagedSlot, manifest.version);
382
+ for (const [key, bytes] of files) {
383
+ const target = path.join(versionDir, key);
384
+ await mkdir(path.dirname(target), { recursive: true });
385
+ await writeFile(target, bytes, { flag: "wx" });
386
+ }
387
+ await checkDestination(manifest, required, optional);
388
+ await mkdir(root, { recursive: true });
389
+ const live = path.join(root, manifest.id);
390
+ if (!(await exists(live))) {
391
+ await rename(stagedSlot, live);
392
+ }
393
+ else {
394
+ const liveVersion = path.join(live, manifest.version);
395
+ const backup = path.join(staging, "old");
396
+ const replaced = await exists(liveVersion);
397
+ if (replaced)
398
+ await rename(liveVersion, backup);
399
+ try {
400
+ await rename(versionDir, liveVersion);
401
+ }
402
+ catch (error) {
403
+ if (replaced) {
404
+ try {
405
+ await rename(backup, liveVersion);
406
+ }
407
+ catch {
408
+ // Never let cleanup erase the sole remaining copy when rollback itself fails.
409
+ staging = undefined;
410
+ fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
411
+ }
412
+ }
413
+ throw error;
414
+ }
415
+ // Publish first, retire old versions second: discovery always sees a complete upgrade.
416
+ if (!optional.versionAppend) {
417
+ for (const version of await readdir(live)) {
418
+ if (version !== manifest.version)
419
+ await rm(path.join(live, version), { recursive: true, force: true });
420
+ }
421
+ }
422
+ }
423
+ return preview;
424
+ }
425
+ finally {
426
+ if (staging)
427
+ await rm(staging, { recursive: true, force: true });
428
+ }
429
+ } });
430
+ }
431
+ //# sourceMappingURL=install.js.map
@@ -0,0 +1,55 @@
1
+ import { type CapabilityScopedSdkCoreDeps } from "../capability-sdk.js";
2
+ import type { PluginDiscoveryRecord } from "../discovery-types.js";
3
+ import type { PluginManifest } from "../manifest.js";
4
+ import type { HookPoints, PluginSdkBinding, PluginModuleImportPort, VerifyDigestPort, PluginTierPolicy } from "../ports.js";
5
+ export { attachLoadedPlugin } from "../attach-loaded-plugin.js";
6
+ /** Host-owned SDK, import, digest and tier-admission contracts for one ordered load. */
7
+ export interface LoadPluginRequired<H extends HookPoints = HookPoints> {
8
+ readonly pluginSdkBinding: PluginSdkBinding<H>;
9
+ readonly importModule: PluginModuleImportPort;
10
+ readonly verifyDigest: VerifyDigestPort;
11
+ readonly tierPolicy: PluginTierPolicy;
12
+ /** The plugin's already-discovered, statically-valid record (a plugin with a non-`valid` static
13
+ * `status` must never reach `loadPlugin` at all — that guard lives in the caller, BR-05). */
14
+ readonly record: PluginDiscoveryRecord;
15
+ readonly manifest: PluginManifest;
16
+ /** Absolute filesystem path (or, for a built-in, an in-process module identifier) to the
17
+ * plugin's entry point — the exact thing step (3) `import()`s. */
18
+ readonly entryPath: string;
19
+ /** Per-load core handles composed by the application root. `loadPlugin()` owns the imported
20
+ * module and therefore owns building the capability-scoped SDK passed to its `setup()` call;
21
+ * the root owns what each granted handle actually delegates to. */
22
+ readonly coreDeps: CapabilityScopedSdkCoreDeps;
23
+ }
24
+ export type LoadPluginOptional = Record<string, never>;
25
+ export type PluginLoadFailureReason = "INTEGRITY_FAILED" | "SDK_RANGE_UNSATISFIED" | "CODE_ENTRY_MISSING" | "PLUGIN_EXPORT_INVALID" | "PLUGIN_SETUP_FAILED";
26
+ export type PluginEnableFailureReason = PluginLoadFailureReason | "PLUGIN_HOOK_NOT_ATTACHED" | "PLUGIN_HOOK_ATTACH_FAILED";
27
+ /** Raised by the composition root after converting `loadPlugin()`'s expected early-return result
28
+ * into the enable path's error channel. HTTP maps this to `PLUGIN_LOAD_FAILED`; agent tools receive
29
+ * the same typed error directly. */
30
+ export declare class PluginLoadError extends Error {
31
+ readonly pluginId: string;
32
+ readonly reason: PluginEnableFailureReason;
33
+ constructor(pluginId: string, reason: PluginEnableFailureReason, options?: {
34
+ cause?: unknown;
35
+ });
36
+ }
37
+ export type LoadPluginResult = {
38
+ readonly loaded: true;
39
+ } | {
40
+ readonly loaded: false;
41
+ readonly reason: PluginLoadFailureReason;
42
+ };
43
+ /**
44
+ * Executes BR-01's 5-step ordered pipeline for one plugin. See CIC U-001 above for the binding
45
+ * ordering constraint this function's statement order must never invert.
46
+ *
47
+ * @throws Never for an expected pipeline failure (those are reported via the returned `reason`);
48
+ * may propagate an unexpected infrastructure error (e.g. a real filesystem I/O failure unrelated
49
+ * to integrity mismatch).
50
+ * @complexity O(file count) for integrity hashing; the `import()`/`setup()` cost beyond that is
51
+ * plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
52
+ * disclosed open gap, not a defect of this function).
53
+ */
54
+ export declare function loadPlugin<H extends HookPoints>(required: LoadPluginRequired<H>, _optional?: LoadPluginOptional): Promise<LoadPluginResult>;
55
+ //# sourceMappingURL=loader.d.ts.map
@@ -0,0 +1,146 @@
1
+ /** SDK version, hashing and executable import are required host ports. The importer must retain
2
+ * the fresh snapshot and containment guarantees described below. */
3
+ /**
4
+ * @file `loadPlugin()` — BR-01's ordered load pipeline (SPEC-005 REQ-03).
5
+ * The signature and JSDoc are design-frozen under implementation outline C-008.
6
+ * Host-supplied SDK versions respect ADR-005's public-export boundary; do not deep-import the
7
+ * SDK's package.json to discover a version.
8
+ * Verify packaged-file integrity, check the host SDK version against manifest.sdkRange, then
9
+ * import executable code, validate its export and run setup with a capability-scoped SDK.
10
+ * Hook attachment is composition-owned: see the successful return path and attachLoadedPlugin.
11
+ *
12
+ * CIC U-001 (Binding, ESCALATE_SECURITY): integrity and SDK compatibility MUST both pass before
13
+ * any plugin code is evaluated, even at module-evaluation time. Deviating from that ordering
14
+ * requires a recorded [CIC_DEVIATION_APPROVED] entry under
15
+ * reports/pipeline/005-plugin-system/critical-internal-constraints.md U-001.
16
+ *
17
+ * Injectable import and digest ports let checks observe that rejected code was never imported,
18
+ * without depending on real module resolution (CIC Verification Surface Rule).
19
+ */
20
+ import { PluginSnapshotIntegrityError } from "./module-snapshot.js";
21
+ import path from "node:path";
22
+ import * as semver from "semver";
23
+ import { buildCapabilityScopedSdk } from "../capability-sdk.js";
24
+ export { attachLoadedPlugin } from "../attach-loaded-plugin.js";
25
+ /** A packaged artifact's file layout is fixed (ADR-004): `tovu.plugin.json` + `server/index.mjs` at
26
+ * the plugin root. `entryPath` is always `<pluginRoot>/server/index.mjs`, so the root two
27
+ * directories up from it is where `manifest.integrity`'s relative file paths resolve from. */
28
+ function derivePluginRoot(entryPath) {
29
+ return path.dirname(path.dirname(entryPath));
30
+ }
31
+ /**
32
+ * True when a site plugin's entry file exists but `manifest.integrity` has no hash for it. Without
33
+ * this, an empty (or entry-less) map passes step (1) vacuously and step (3) imports unverified code.
34
+ * A MISSING entry is left to step (3), which reports it as `CODE_ENTRY_MISSING` (AC-12).
35
+ * @complexity One file hash.
36
+ */
37
+ async function isUncoveredExistingEntry(manifest, pluginRoot, entryPath, computeFileHash) {
38
+ const entryKey = path.relative(pluginRoot, entryPath).split(path.sep).join("/");
39
+ if (Object.hasOwn(manifest.integrity, entryKey))
40
+ return false;
41
+ try {
42
+ await computeFileHash(entryPath);
43
+ return true;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /** Raised by the composition root after converting `loadPlugin()`'s expected early-return result
50
+ * into the enable path's error channel. HTTP maps this to `PLUGIN_LOAD_FAILED`; agent tools receive
51
+ * the same typed error directly. */
52
+ export class PluginLoadError extends Error {
53
+ pluginId;
54
+ reason;
55
+ constructor(pluginId, reason, options) {
56
+ super(`plugin '${pluginId}' failed to load (${reason})`, options);
57
+ this.name = "PluginLoadError";
58
+ this.pluginId = pluginId;
59
+ this.reason = reason;
60
+ }
61
+ }
62
+ /**
63
+ * Executes BR-01's 5-step ordered pipeline for one plugin. See CIC U-001 above for the binding
64
+ * ordering constraint this function's statement order must never invert.
65
+ *
66
+ * @throws Never for an expected pipeline failure (those are reported via the returned `reason`);
67
+ * may propagate an unexpected infrastructure error (e.g. a real filesystem I/O failure unrelated
68
+ * to integrity mismatch).
69
+ * @complexity O(file count) for integrity hashing; the `import()`/`setup()` cost beyond that is
70
+ * plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
71
+ * disclosed open gap, not a defect of this function).
72
+ */
73
+ export async function loadPlugin(required, _optional = {}) {
74
+ const { record, manifest, entryPath, coreDeps } = required;
75
+ const { importModule, tierPolicy, pluginSdkBinding } = required;
76
+ const computeFileHash = (absoluteFilePath) => required.verifyDigest({ absoluteFilePath });
77
+ const runtimeSdkVersion = pluginSdkBinding.runtimeSdkVersion;
78
+ // --- CIC U-001-ORD1: step (1), integrity, MUST complete successfully before step (2)/(3). ---
79
+ const pluginRoot = derivePluginRoot(entryPath);
80
+ if (record.source === "site" && (await isUncoveredExistingEntry(manifest, pluginRoot, entryPath, computeFileHash))) {
81
+ return { loaded: false, reason: "INTEGRITY_FAILED" };
82
+ }
83
+ for (const [relativeFilePath, expectedHash] of Object.entries(manifest.integrity)) {
84
+ let actualHash;
85
+ try {
86
+ actualHash = await computeFileHash(path.join(pluginRoot, relativeFilePath));
87
+ }
88
+ catch {
89
+ return { loaded: false, reason: "INTEGRITY_FAILED" };
90
+ }
91
+ if (actualHash !== expectedHash) {
92
+ return { loaded: false, reason: "INTEGRITY_FAILED" };
93
+ }
94
+ }
95
+ // --- CIC U-001-ORD1: step (2), sdkRange, MUST complete successfully before step (3). ---
96
+ if (!semver.satisfies(runtimeSdkVersion, manifest.sdkRange)) {
97
+ return { loaded: false, reason: "SDK_RANGE_UNSATISFIED" };
98
+ }
99
+ // Declarative plugins never reach an executable importer. A worker port is mandatory for tier-2,
100
+ // and tier-3 must be admitted explicitly by the host (CMS-JINI-MODULAR-DESIGN Rev 3 §5).
101
+ if (manifest.tier === "tier-1")
102
+ return { loaded: true };
103
+ if ((manifest.tier === "tier-2" && tierPolicy.execution !== "worker") || !tierPolicy.allowLoad({ record, manifest })) {
104
+ return { loaded: false, reason: "CODE_ENTRY_MISSING" };
105
+ }
106
+ // --- Step (3): only now, after both prior checks pass, is the plugin's code ever evaluated. ---
107
+ let importedModule;
108
+ try {
109
+ // Same-version replacement must evaluate the reviewed package again. Build this URL only at
110
+ // step (3), after integrity and SDK compatibility have passed (CIC U-001 order unchanged).
111
+ // Injected import seams keep their original path contract. A fresh filesystem graph refreshes
112
+ // ALL packaged helpers (including nested/dynamic imports and CommonJS require caches).
113
+ const imported = await importModule({ plugin: { pluginId: record.id, packageRoot: pluginRoot }, modulePath: entryPath });
114
+ if (typeof imported === "string")
115
+ return { loaded: false, reason: "CODE_ENTRY_MISSING" };
116
+ importedModule = { default: imported.exported };
117
+ }
118
+ catch (error) {
119
+ if (error instanceof PluginSnapshotIntegrityError)
120
+ return { loaded: false, reason: "INTEGRITY_FAILED" };
121
+ return { loaded: false, reason: "CODE_ENTRY_MISSING" };
122
+ }
123
+ // --- Step (4): validate the `definePlugin()` export, build the per-load gated SDK, run setup. ---
124
+ const plugin = pluginSdkBinding.readDefinedPlugin({ moduleValue: importedModule });
125
+ if (!plugin) {
126
+ return { loaded: false, reason: "PLUGIN_EXPORT_INVALID" };
127
+ }
128
+ const sdk = buildCapabilityScopedSdk({
129
+ pluginId: record.id,
130
+ capabilities: manifest.capabilities,
131
+ coreDeps,
132
+ pluginSdkBinding,
133
+ });
134
+ try {
135
+ await plugin.definition.setup(sdk);
136
+ }
137
+ catch {
138
+ return { loaded: false, reason: "PLUGIN_SETUP_FAILED" };
139
+ }
140
+ // Step (5) remains composition-owned: setup's gated `addFilter()` handle captures the filter in
141
+ // the caller's `coreDeps`; only after this successful return does the root call the shared
142
+ // `attachLoadedPlugin()` path below. That split prevents a late setup failure from leaving a
143
+ // partially-attached filter behind.
144
+ return { loaded: true };
145
+ }
146
+ //# sourceMappingURL=loader.js.map
@@ -0,0 +1,25 @@
1
+ /** Site-plugin graph isolation. A fresh filesystem identity covers relative ESM, dynamic imports
2
+ * and CommonJS requires together; a query on the entry alone covers only that entry.
3
+ * Snapshots live outside discovery and remain available for late dynamic imports until shutdown.
4
+ */
5
+ import { writeFile } from "node:fs/promises";
6
+ import type { PluginManifest } from "../manifest.js";
7
+ export declare class PluginSnapshotIntegrityError extends Error {
8
+ }
9
+ /**
10
+ * Copies a site plugin's verified package into a fresh, read-only runtime snapshot and returns the
11
+ * snapshot's server entry. Every file must match the manifest's integrity map, and every listed file
12
+ * must exist; a failed copy removes the half-written snapshot.
13
+ * @param required.pluginRoot The installed package directory.
14
+ * @param required.manifest The installed manifest whose `integrity` map is enforced.
15
+ * @param optional.writeSnapshotFile File writer for the snapshot; defaults to `fs.writeFile`.
16
+ * @throws {PluginSnapshotIntegrityError} On a changed/missing file or a linked runtime root.
17
+ * @complexity O(total package bytes).
18
+ */
19
+ export declare function snapshotPluginModuleGraph(required: {
20
+ pluginRoot: string;
21
+ manifest: PluginManifest;
22
+ }, { writeSnapshotFile }?: {
23
+ writeSnapshotFile?: typeof writeFile;
24
+ }): Promise<string>;
25
+ //# sourceMappingURL=module-snapshot.d.ts.map