@jini-ai/plugins 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +201 -0
  3. package/README.md +60 -2
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +10 -0
  5. package/dist/glue/attachment-points/content-lifecycle.js +5 -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 +20 -0
  11. package/dist/glue/capability-gate.js +23 -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 +58 -0
  26. package/dist/host/claim-conflicts.d.ts +101 -0
  27. package/dist/host/claim-conflicts.js +139 -0
  28. package/dist/host/declarative-enable.d.ts +43 -0
  29. package/dist/host/declarative-enable.js +73 -0
  30. package/dist/host/discovery-types.d.ts +52 -0
  31. package/dist/host/discovery-types.js +2 -0
  32. package/dist/host/errors.d.ts +20 -0
  33. package/dist/host/errors.js +22 -0
  34. package/dist/host/hook-registry.d.ts +113 -0
  35. package/dist/host/hook-registry.js +190 -0
  36. package/dist/host/index.d.ts +16 -0
  37. package/dist/host/index.js +16 -0
  38. package/dist/host/manifest.d.ts +149 -0
  39. package/dist/host/manifest.js +407 -0
  40. package/dist/host/node/discovery.d.ts +25 -0
  41. package/dist/host/node/discovery.js +217 -0
  42. package/dist/host/node/index.d.ts +7 -0
  43. package/dist/host/node/index.js +7 -0
  44. package/dist/host/node/install.d.ts +73 -0
  45. package/dist/host/node/install.js +301 -0
  46. package/dist/host/node/loader.d.ts +55 -0
  47. package/dist/host/node/loader.js +146 -0
  48. package/dist/host/node/module-snapshot.d.ts +25 -0
  49. package/dist/host/node/module-snapshot.js +53 -0
  50. package/dist/host/node/package-files.d.ts +52 -0
  51. package/dist/host/node/package-files.js +214 -0
  52. package/dist/host/plugin-claims.d.ts +113 -0
  53. package/dist/host/plugin-claims.js +134 -0
  54. package/dist/host/ports.d.ts +196 -0
  55. package/dist/host/ports.js +2 -0
  56. package/dist/host/quarantine.d.ts +19 -0
  57. package/dist/host/quarantine.js +28 -0
  58. package/dist/host/repo.memory.d.ts +27 -0
  59. package/dist/host/repo.memory.js +33 -0
  60. package/dist/host/sql/index.d.ts +4 -0
  61. package/dist/host/sql/index.js +4 -0
  62. package/dist/host/sql/repo.d.ts +38 -0
  63. package/dist/host/sql/repo.js +50 -0
  64. package/dist/host/sql/repo.rows.d.ts +28 -0
  65. package/dist/host/sql/repo.rows.js +28 -0
  66. package/dist/host/uninstall.d.ts +88 -0
  67. package/dist/host/uninstall.js +112 -0
  68. package/dist/host/worker/import-seam.d.ts +45 -0
  69. package/dist/host/worker/import-seam.js +52 -0
  70. package/dist/host/worker/index.d.ts +5 -0
  71. package/dist/host/worker/index.js +5 -0
  72. package/dist/host/worker/protocol.d.ts +62 -0
  73. package/dist/host/worker/protocol.js +31 -0
  74. package/dist/host/worker/run-call.d.ts +27 -0
  75. package/dist/host/worker/run-call.js +76 -0
  76. package/package.json +102 -3
@@ -0,0 +1,73 @@
1
+ import { type PluginManifest, type PluginTier } from "../manifest.js";
2
+ import type { ArchiveReaderPort, ManifestHostPorts, PluginTierPolicy } from "../ports.js";
3
+ import type { PluginActivationRepoPort } from "../activation.js";
4
+ import type { PluginConflict } from "../plugin-claims.js";
5
+ export declare class PluginInstallError extends Error {
6
+ readonly code: string;
7
+ constructor(code: string, message: string);
8
+ }
9
+ export interface PluginInstallPreview {
10
+ id: string;
11
+ name: string;
12
+ version: string;
13
+ tier: PluginTier;
14
+ capabilities: readonly string[];
15
+ hooks: readonly string[];
16
+ /** `false` only for a tier-1 (manifest-only) package — the runtime never imports anything for it. */
17
+ hasCode: boolean;
18
+ digest: string;
19
+ upgradeFrom?: string;
20
+ /** Content-type keys the manifest declares (AW-7 Tier 1); created when the plugin is turned on. */
21
+ contentTypes: readonly string[];
22
+ /** What turning it on would clash with — see {@link PluginInstallDeps.conflicts}. Informational
23
+ * only: not part of the consent digest, and enable re-checks (the enable-time conflict gate). */
24
+ conflicts: readonly PluginConflict[];
25
+ }
26
+ export type PluginInstallInput = ({
27
+ sourceDir: string;
28
+ archive?: never;
29
+ } | {
30
+ archive: Uint8Array;
31
+ sourceDir?: never;
32
+ }) & {
33
+ replace?: boolean;
34
+ };
35
+ export interface PluginInstallDeps extends ManifestHostPorts {
36
+ readonly archiveReader: ArchiveReaderPort;
37
+ readonly tierPolicy: PluginTierPolicy;
38
+ installDir: string;
39
+ builtInIds: readonly string[];
40
+ repo: Pick<PluginActivationRepoPort, "listAll">;
41
+ /** Names the staged manifest would take that core or an enabled plugin already holds. Install is
42
+ * site-wide but activation is per workspace: the admin root answers for the workspace it serves
43
+ * (`composePluginRuntime`); the CLI, which names no workspace, answers none. */
44
+ conflicts: (required: {
45
+ manifest: PluginManifest;
46
+ }, optional?: Record<string, never>) => Promise<readonly PluginConflict[]>;
47
+ }
48
+ export interface PluginInstallerPort {
49
+ preview(required: PluginInstallInput, optional?: Record<string, never>): Promise<PluginInstallPreview>;
50
+ install(required: PluginInstallInput & {
51
+ expectedDigest: string;
52
+ }, optional?: Record<string, never>): Promise<PluginInstallPreview>;
53
+ }
54
+ /** Activation callbacks share this guard; the activation service compensates a rejected enable. */
55
+ export declare function assertPluginInstallIdle(required: {
56
+ installDir: string;
57
+ }, _optional?: Record<string, never>): Promise<void>;
58
+ /** Loader uses the same bounded, link-free byte snapshot, then verifies the retained bytes. */
59
+ export declare function snapshotSitePluginPackage(required: {
60
+ sourceDir: string;
61
+ }, _optional?: Record<string, never>): Promise<Map<string, Buffer>>;
62
+ export declare function computePluginIntegrity(required: {
63
+ sourceDir: string;
64
+ }, _optional?: Record<string, never>): Promise<Record<string, string>>;
65
+ export declare function previewSitePluginInstall(required: PluginInstallInput & {
66
+ deps: PluginInstallDeps;
67
+ }, _optional?: Record<string, never>): Promise<PluginInstallPreview>;
68
+ /** Directory lock is also cross-process: CLI and admin cannot replace the same site concurrently. */
69
+ export declare function installSitePlugin(required: PluginInstallInput & {
70
+ expectedDigest: string;
71
+ deps: PluginInstallDeps;
72
+ }, _optional?: Record<string, never>): Promise<PluginInstallPreview>;
73
+ //# sourceMappingURL=install.d.ts.map
@@ -0,0 +1,301 @@
1
+ /** Local-install environment consent is host-owned; archiveReader owns zip-slip/decompression
2
+ * checks and tierPolicy.checkInstall owns publisher admission. */
3
+ /** Site plugin folder installer governed by plugin-install-plan.md, M1a.
4
+ * Installation inspects JSON and bytes only: importing code belongs exclusively to enable.
5
+ * Staging is a sibling of discovery's root, on the same filesystem, so partial copies never list.
6
+ */
7
+ import { constants } from "node:fs";
8
+ import { lstat, realpath, readdir, open, mkdir, mkdtemp, writeFile, rename, rm } from "node:fs/promises";
9
+ import path from "node:path";
10
+ import { createHash } from "node:crypto";
11
+ import * as semver from "semver";
12
+ import { validateManifest } from "../manifest.js";
13
+ export class PluginInstallError extends Error {
14
+ code;
15
+ constructor(code, message) {
16
+ super(message);
17
+ this.code = code;
18
+ this.name = "PluginInstallError";
19
+ }
20
+ }
21
+ const MANIFEST = "tovu.plugin.json";
22
+ const MAX_ENTRIES = 4096;
23
+ const MAX_FILE_BYTES = 16 * 1024 * 1024;
24
+ const MAX_TOTAL_BYTES = 64 * 1024 * 1024;
25
+ const hash = (bytes) => `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
26
+ function fail(code, message) { throw new PluginInstallError(code, message); }
27
+ const inside = (parent, child) => child === parent || child.startsWith(parent + path.sep);
28
+ async function exists(target) {
29
+ try {
30
+ await lstat(target);
31
+ return true;
32
+ }
33
+ catch (e) {
34
+ if (e.code === "ENOENT")
35
+ return false;
36
+ throw e;
37
+ }
38
+ }
39
+ /** Activation callbacks share this guard; the activation service compensates a rejected enable. */
40
+ export async function assertPluginInstallIdle(required, _optional = {}) {
41
+ if (await exists(path.resolve(required.installDir) + "-install-lock"))
42
+ fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
43
+ }
44
+ /** Retain the inspected bytes, rather than copying a mutable source after consent verification. */
45
+ async function snapshot(sourceDir) {
46
+ const files = new Map();
47
+ let entries = 0;
48
+ let total = 0;
49
+ async function walk(dir, prefix) {
50
+ const stat = await lstat(dir);
51
+ if (!stat.isDirectory() || stat.isSymbolicLink())
52
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package directories must not be symbolic links.");
53
+ for (const name of (await readdir(dir)).sort()) {
54
+ if (++entries > MAX_ENTRIES)
55
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package has too many entries.");
56
+ const target = path.join(dir, name);
57
+ const relative = prefix + name;
58
+ const info = await lstat(target);
59
+ if (info.isSymbolicLink())
60
+ fail("PLUGIN_PACKAGE_UNSAFE", "Symbolic links are not allowed.");
61
+ if (info.isDirectory()) {
62
+ await walk(target, relative + "/");
63
+ continue;
64
+ }
65
+ if (!info.isFile() || info.nlink !== 1)
66
+ fail("PLUGIN_PACKAGE_UNSAFE", "Only regular files without hard links are allowed.");
67
+ if (info.size > MAX_FILE_BYTES || total + info.size > MAX_TOTAL_BYTES)
68
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package exceeds the file or total size limit.");
69
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
70
+ try {
71
+ const current = await handle.stat();
72
+ if (!current.isFile() || current.nlink !== 1 || current.ino !== info.ino || current.dev !== info.dev)
73
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
74
+ // A bounded read also protects against a file growing after stat().
75
+ const buffer = Buffer.alloc(info.size + 1);
76
+ let length = 0;
77
+ while (length < buffer.length) {
78
+ const read = await handle.read(buffer, length, buffer.length - length, null);
79
+ if (read.bytesRead === 0)
80
+ break;
81
+ length += read.bytesRead;
82
+ }
83
+ if (length > MAX_FILE_BYTES || total + length > MAX_TOTAL_BYTES)
84
+ fail("PLUGIN_PACKAGE_TOO_LARGE", "Package grew past its size limit.");
85
+ if (length > info.size || (await handle.stat()).size !== length)
86
+ fail("PLUGIN_PACKAGE_UNSAFE", "Package changed while reading.");
87
+ total += length;
88
+ files.set(relative, Buffer.from(buffer.subarray(0, length)));
89
+ }
90
+ finally {
91
+ await handle.close();
92
+ }
93
+ }
94
+ }
95
+ await walk(sourceDir, "");
96
+ return files;
97
+ }
98
+ /** Files a manifest-only package may carry: documentation, data and images — nothing a browser or
99
+ * Node would execute. An allowlist, so a new script-like extension is refused by default (SVG is
100
+ * left out on purpose: it can carry script). */
101
+ const DECLARATIVE_DATA_FILE = /(?:^|\/)(?:LICENSE|[^/]+\.(?:json|md|txt|png|jpe?g|gif|webp))$/;
102
+ /**
103
+ * Tier rules for a sideloaded package. Tier-1 (AW-7, 2026-10-04) is the manifest-only tier ADR-024
104
+ * §1 defines — "zero executable code", so it is safe from any publisher: it may not ship a single
105
+ * code file (its declarations — no code surface, parseable `contentTypes` — are already checked by
106
+ * `validateManifest`). Anything else must
107
+ * still be tier-3 with `server/index.mjs`, because a sideloaded manifest cannot grant itself a
108
+ * verified publisher tier (tier-2 needs the sandbox, which does not exist yet).
109
+ */
110
+ function checkTierAndCode(candidate, files, tierPolicy) {
111
+ if (candidate.tier === "tier-1") {
112
+ const code = [...files.keys()].filter((key) => key !== MANIFEST && !DECLARATIVE_DATA_FILE.test(key));
113
+ if (code.length)
114
+ fail("PLUGIN_MANIFEST_INVALID", `A declarative (tier-1) plugin must not ship code: ${code.join(", ")}`);
115
+ return;
116
+ }
117
+ if (!files.has("server/index.mjs"))
118
+ fail("PLUGIN_MANIFEST_INVALID", "server/index.mjs is required.");
119
+ tierPolicy.checkInstall({ manifest: candidate, files });
120
+ }
121
+ function validatePackage(files, deps) {
122
+ const { builtInIds } = deps;
123
+ let raw;
124
+ try {
125
+ raw = JSON.parse(files.get(MANIFEST)?.toString("utf8") ?? "");
126
+ }
127
+ catch {
128
+ return fail("PLUGIN_MANIFEST_INVALID", "A valid tovu.plugin.json is required.");
129
+ }
130
+ const candidate = raw;
131
+ const id = typeof candidate?.id === "string" ? candidate.id : "";
132
+ if (builtInIds.some((builtin) => builtin.toLowerCase() === id.toLowerCase()))
133
+ fail("PLUGIN_SHADOWS_BUILT_IN", "Package id belongs to a built-in plugin.");
134
+ const result = validateManifest({ ...deps, manifest: raw, folderName: id, builtInIds });
135
+ // The manifest's own messages, so a refused declaration says what is wrong with it.
136
+ if (result.errors.length)
137
+ fail("PLUGIN_MANIFEST_INVALID", result.errors.map((error) => error.message).join("; "));
138
+ if (!candidate || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(id) || typeof candidate.version !== "string" || !semver.valid(candidate.version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(candidate.version))
139
+ fail("PLUGIN_MANIFEST_INVALID", "Package manifest, id or version is invalid.");
140
+ checkTierAndCode(candidate, files, deps.tierPolicy);
141
+ if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
142
+ fail("PLUGIN_MANIFEST_INVALID", "A name and valid SDK range are required.");
143
+ if (!candidate.integrity || typeof candidate.integrity !== "object" || Array.isArray(candidate.integrity))
144
+ fail("PLUGIN_INTEGRITY_INVALID", "An integrity map is required.");
145
+ const packaged = [...files.keys()].filter((key) => key !== MANIFEST).sort();
146
+ if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
147
+ fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except tovu.plugin.json.");
148
+ for (const key of packaged)
149
+ if (candidate.integrity[key] !== hash(files.get(key)))
150
+ fail("PLUGIN_INTEGRITY_INVALID", `Integrity mismatch: ${key}`);
151
+ return candidate;
152
+ }
153
+ async function checkDestination(manifest, input, deps) {
154
+ const root = path.resolve(deps.installDir);
155
+ const entries = await readdir(root).catch((e) => { if (e.code === "ENOENT")
156
+ return []; throw e; });
157
+ if (entries.some((name) => name.toLowerCase() === manifest.id.toLowerCase() && name !== manifest.id))
158
+ fail("PLUGIN_ID_CONFLICT", "A plugin id differs only by letter case.");
159
+ if (await exists(path.join(path.dirname(root), path.basename(root) + "-trash", manifest.id)))
160
+ fail("PLUGIN_IN_TRASH", "Restore or delete this plugin in Trash first.");
161
+ if ((await deps.repo.listAll()).some((row) => row.pluginId.toLowerCase() === manifest.id.toLowerCase() && row.enabled))
162
+ fail("PLUGIN_ENABLED", "Turn the plugin off in every workspace first.");
163
+ const slot = path.join(root, manifest.id);
164
+ if (!(await exists(slot)))
165
+ return undefined;
166
+ const stat = await lstat(slot);
167
+ if (!stat.isDirectory() || stat.isSymbolicLink())
168
+ fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin directory must not be a link.");
169
+ const versions = await readdir(slot);
170
+ if (versions.some((version) => !semver.valid(version)))
171
+ fail("PLUGIN_ID_CONFLICT", "Existing plugin has an unrecognized version folder.");
172
+ const latest = versions.sort(semver.rcompare)[0];
173
+ if (latest && semver.lt(manifest.version, latest))
174
+ fail("PLUGIN_DOWNGRADE", "Installing an older version is not allowed.");
175
+ if (versions.some((version) => semver.eq(version, manifest.version)) && !input.replace)
176
+ fail("PLUGIN_VERSION_EXISTS", "This version exists. Choose replace explicitly.");
177
+ return latest;
178
+ }
179
+ async function inspect(input, deps) {
180
+ 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);
181
+ const manifest = validatePackage(files, deps);
182
+ const upgradeFrom = await checkDestination(manifest, input, deps);
183
+ // Include manifest bytes: changed capabilities/name/version must invalidate human consent too.
184
+ const digest = hash(Buffer.from(JSON.stringify([...files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0))));
185
+ const preview = { 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 } : {}) };
186
+ return { files, manifest, preview };
187
+ }
188
+ async function inspectFolder(source, deps) {
189
+ const sourceDir = await realpath(source).catch(() => fail("PLUGIN_SOURCE_INVALID", "Source folder was not found."));
190
+ if ((await lstat(source)).isSymbolicLink())
191
+ fail("PLUGIN_PACKAGE_UNSAFE", "Source folder must not be a link.");
192
+ // Canonicalize existing ancestors too: lexical checks alone miss symlink aliases.
193
+ async function canonical(target) {
194
+ try {
195
+ return await realpath(target);
196
+ }
197
+ catch (e) {
198
+ if (e.code !== "ENOENT")
199
+ throw e;
200
+ return path.join(await canonical(path.dirname(target)), path.basename(target));
201
+ }
202
+ }
203
+ const root = await canonical(path.resolve(deps.installDir));
204
+ for (const destination of [root, root + "-staging", root + "-trash"]) {
205
+ if (inside(destination, sourceDir) || inside(sourceDir, destination))
206
+ fail("PLUGIN_SOURCE_INVALID", "Source must be separate from installed, staging and Trash folders.");
207
+ }
208
+ return snapshot(sourceDir);
209
+ }
210
+ /** Loader uses the same bounded, link-free byte snapshot, then verifies the retained bytes. */
211
+ export async function snapshotSitePluginPackage(required, _optional = {}) {
212
+ return snapshot(required.sourceDir);
213
+ }
214
+ export async function computePluginIntegrity(required, _optional = {}) {
215
+ return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => key !== MANIFEST).map(([key, bytes]) => [key, hash(bytes)]));
216
+ }
217
+ export async function previewSitePluginInstall(required, _optional = {}) {
218
+ return (await inspect(required, required.deps)).preview;
219
+ }
220
+ /** Directory lock is also cross-process: CLI and admin cannot replace the same site concurrently. */
221
+ export async function installSitePlugin(required, _optional = {}) {
222
+ const optional = required.deps;
223
+ const root = path.resolve(optional.installDir);
224
+ const { files, manifest, preview } = await inspect(required, optional);
225
+ if (preview.digest !== required.expectedDigest)
226
+ fail("PLUGIN_CHANGED_SINCE_PREVIEW", "Package changed since preview. Review it again.");
227
+ for (const target of [root, root + "-staging", root + "-trash"]) {
228
+ if (await exists(target)) {
229
+ const info = await lstat(target);
230
+ if (!info.isDirectory() || info.isSymbolicLink())
231
+ fail("PLUGIN_PACKAGE_UNSAFE", "Install, staging and Trash roots must be real directories.");
232
+ }
233
+ }
234
+ const lock = root + "-install-lock";
235
+ await mkdir(path.dirname(root), { recursive: true });
236
+ try {
237
+ await mkdir(lock);
238
+ }
239
+ catch (e) {
240
+ if (e.code === "EEXIST")
241
+ fail("PLUGIN_INSTALL_BUSY", "Another install is in progress.");
242
+ throw e;
243
+ }
244
+ let staging;
245
+ try {
246
+ await mkdir(root + "-staging", { recursive: true });
247
+ staging = await mkdtemp(path.join(root + "-staging", "install-"));
248
+ const stagedSlot = path.join(staging, "new");
249
+ const versionDir = path.join(stagedSlot, manifest.version);
250
+ for (const [key, bytes] of files) {
251
+ const target = path.join(versionDir, key);
252
+ await mkdir(path.dirname(target), { recursive: true });
253
+ await writeFile(target, bytes, { flag: "wx" });
254
+ }
255
+ await checkDestination(manifest, required, optional);
256
+ await mkdir(root, { recursive: true });
257
+ const live = path.join(root, manifest.id);
258
+ if (!(await exists(live))) {
259
+ await rename(stagedSlot, live);
260
+ }
261
+ else {
262
+ const liveVersion = path.join(live, manifest.version);
263
+ const backup = path.join(staging, "old");
264
+ const replaced = await exists(liveVersion);
265
+ if (replaced)
266
+ await rename(liveVersion, backup);
267
+ try {
268
+ await rename(versionDir, liveVersion);
269
+ }
270
+ catch (error) {
271
+ if (replaced) {
272
+ try {
273
+ await rename(backup, liveVersion);
274
+ }
275
+ catch {
276
+ // Never let cleanup erase the sole remaining copy when rollback itself fails.
277
+ staging = undefined;
278
+ fail("PLUGIN_INSTALL_RECOVERY_REQUIRED", `Restore the previous version from ${backup} before retrying.`);
279
+ }
280
+ }
281
+ throw error;
282
+ }
283
+ // Publish first, retire old versions second: discovery always sees a complete upgrade.
284
+ for (const version of await readdir(live)) {
285
+ if (version !== manifest.version)
286
+ await rm(path.join(live, version), { recursive: true, force: true });
287
+ }
288
+ }
289
+ return preview;
290
+ }
291
+ finally {
292
+ try {
293
+ if (staging)
294
+ await rm(staging, { recursive: true, force: true });
295
+ }
296
+ finally {
297
+ await rm(lock, { recursive: true, force: true });
298
+ }
299
+ }
300
+ }
301
+ //# 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
@@ -0,0 +1,53 @@
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 { mkdir, mkdtemp, rm, writeFile, lstat } from "node:fs/promises";
6
+ import { createHash } from "node:crypto";
7
+ import path from "node:path";
8
+ import { snapshotSitePluginPackage } from "./install.js";
9
+ export class PluginSnapshotIntegrityError extends Error {
10
+ }
11
+ /**
12
+ * Copies a site plugin's verified package into a fresh, read-only runtime snapshot and returns the
13
+ * snapshot's server entry. Every file must match the manifest's integrity map, and every listed file
14
+ * must exist; a failed copy removes the half-written snapshot.
15
+ * @param required.pluginRoot The installed package directory.
16
+ * @param required.manifest The installed manifest whose `integrity` map is enforced.
17
+ * @param optional.writeSnapshotFile File writer for the snapshot; defaults to `fs.writeFile`.
18
+ * @throws {PluginSnapshotIntegrityError} On a changed/missing file or a linked runtime root.
19
+ * @complexity O(total package bytes).
20
+ */
21
+ export async function snapshotPluginModuleGraph(required, { writeSnapshotFile = writeFile } = {}) {
22
+ const files = await snapshotSitePluginPackage({ sourceDir: required.pluginRoot });
23
+ for (const [key, bytes] of files) {
24
+ if (key === "tovu.plugin.json")
25
+ continue;
26
+ const digest = `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
27
+ if (required.manifest.integrity[key] !== digest)
28
+ throw new PluginSnapshotIntegrityError("Package changed before loading.");
29
+ }
30
+ for (const key of Object.keys(required.manifest.integrity)) {
31
+ if (!files.has(key))
32
+ throw new PluginSnapshotIntegrityError("Package file disappeared before loading.");
33
+ }
34
+ const cacheRoot = path.dirname(path.dirname(required.pluginRoot)) + "-runtime";
35
+ await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
36
+ const info = await lstat(cacheRoot);
37
+ if (!info.isDirectory() || info.isSymbolicLink())
38
+ throw new PluginSnapshotIntegrityError("Runtime snapshot root must not be a link.");
39
+ const snapshotRoot = await mkdtemp(path.join(cacheRoot, "load-"));
40
+ try {
41
+ for (const [key, bytes] of files) {
42
+ const destination = path.join(snapshotRoot, key);
43
+ await mkdir(path.dirname(destination), { recursive: true });
44
+ await writeSnapshotFile(destination, bytes, { flag: "wx", mode: 0o400 });
45
+ }
46
+ return path.join(snapshotRoot, "server/index.mjs");
47
+ }
48
+ catch (error) {
49
+ await rm(snapshotRoot, { recursive: true, force: true });
50
+ throw error;
51
+ }
52
+ }
53
+ //# sourceMappingURL=module-snapshot.js.map