@jini-ai/plugins 0.5.0 → 0.5.2
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/CHANGELOG.md +10 -0
- package/dist/glue/capability-gate.js +1 -1
- package/dist/host/browser-providers.d.ts +2 -9
- package/dist/host/browser-providers.js +34 -18
- package/dist/host/capability-sdk.js +1 -1
- package/dist/host/claim-conflicts.d.ts +4 -4
- package/dist/host/claim-conflicts.js +4 -4
- package/dist/host/contributions.d.ts +4 -1
- package/dist/host/contributions.js +19 -8
- package/dist/host/discovery-types.d.ts +2 -2
- package/dist/host/hook-registry.js +7 -5
- package/dist/host/index.d.ts +1 -0
- package/dist/host/index.js +1 -0
- package/dist/host/manifest-types.d.ts +103 -0
- package/dist/host/manifest-types.js +2 -0
- package/dist/host/manifest.d.ts +5 -97
- package/dist/host/manifest.js +33 -24
- package/dist/host/node/discovery.js +27 -22
- package/dist/host/node/install.js +257 -192
- package/dist/host/node/loader.js +85 -67
- package/dist/host/node/module-snapshot.js +3 -2
- package/dist/host/node/open-flags.d.ts +18 -0
- package/dist/host/node/open-flags.js +14 -0
- package/dist/host/node/package-files.js +18 -12
- package/dist/host/node/source-drafts.d.ts +2 -0
- package/dist/host/node/source-drafts.js +93 -59
- package/dist/host/plugin-claims.js +6 -4
- package/dist/host/plugin-format.d.ts +14 -0
- package/dist/host/plugin-format.js +21 -0
- package/dist/host/ports.d.ts +4 -4
- package/dist/host/tool-contributions.js +3 -1
- package/dist/host/worker/protocol.js +8 -6
- package/dist/host/worker/run-call.d.ts +1 -1
- package/dist/host/worker/run-call.js +20 -17
- package/package.json +5 -5
package/dist/host/node/loader.js
CHANGED
|
@@ -24,7 +24,7 @@ import { isPluginRelativePath } from "../browser-providers.js";
|
|
|
24
24
|
import * as semver from "semver";
|
|
25
25
|
import { buildCapabilityScopedSdk } from "../capability-sdk.js";
|
|
26
26
|
export { attachLoadedPlugin } from "../attach-loaded-plugin.js";
|
|
27
|
-
/** A packaged artifact's file layout is fixed (ADR-004): `
|
|
27
|
+
/** A packaged artifact's file layout is fixed (ADR-004): `jini.plugin.json` + `server/index.mjs` at
|
|
28
28
|
* the plugin root. `entryPath` is always `<pluginRoot>/server/index.mjs`, so the root two
|
|
29
29
|
* directories up from it is where `manifest.integrity`'s relative file paths resolve from. */
|
|
30
30
|
function derivePluginRoot(entryPath) {
|
|
@@ -61,97 +61,115 @@ export class PluginLoadError extends Error {
|
|
|
61
61
|
this.reason = reason;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
*
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
* @complexity O(file count) for integrity hashing; the `import()`/`setup()` cost beyond that is
|
|
72
|
-
* plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
|
|
73
|
-
* disclosed open gap, not a defect of this function).
|
|
74
|
-
*/
|
|
75
|
-
export async function loadPlugin(required, _optional = {}) {
|
|
76
|
-
const { record, manifest, entryPath, coreDeps } = required;
|
|
77
|
-
const { importModule, tierPolicy, pluginSdkBinding } = required;
|
|
78
|
-
const computeFileHash = (absoluteFilePath) => required.verifyDigest({ absoluteFilePath });
|
|
79
|
-
const runtimeSdkVersion = pluginSdkBinding.runtimeSdkVersion;
|
|
80
|
-
// --- CIC U-001-ORD1: step (1), integrity, MUST complete successfully before step (2)/(3). ---
|
|
81
|
-
const pluginRoot = derivePluginRoot(entryPath);
|
|
82
|
-
if (record.source === "site" && (await isUncoveredExistingEntry(manifest, pluginRoot, entryPath, computeFileHash))) {
|
|
83
|
-
return { loaded: false, reason: "INTEGRITY_FAILED" };
|
|
84
|
-
}
|
|
64
|
+
const failed = (reason) => ({ loaded: false, reason });
|
|
65
|
+
/** Step (1): every listed file is plugin-relative and hashes to its declared value; a site entry
|
|
66
|
+
* file must be listed at all. Returns false on the first failure. */
|
|
67
|
+
async function verifyIntegrity(required) {
|
|
68
|
+
const { manifest, pluginRoot, entryPath, computeFileHash } = required;
|
|
69
|
+
if (required.record.source === "site" && (await isUncoveredExistingEntry(manifest, pluginRoot, entryPath, computeFileHash)))
|
|
70
|
+
return false;
|
|
85
71
|
for (const [relativeFilePath, expectedHash] of Object.entries(manifest.integrity)) {
|
|
86
72
|
if (!isPluginRelativePath({ path: relativeFilePath }))
|
|
87
|
-
return
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
catch {
|
|
93
|
-
return { loaded: false, reason: "INTEGRITY_FAILED" };
|
|
94
|
-
}
|
|
95
|
-
if (actualHash !== expectedHash) {
|
|
96
|
-
return { loaded: false, reason: "INTEGRITY_FAILED" };
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
// --- CIC U-001-ORD1: step (2), sdkRange, MUST complete successfully before step (3). ---
|
|
100
|
-
if (!semver.satisfies(runtimeSdkVersion, manifest.sdkRange)) {
|
|
101
|
-
return { loaded: false, reason: "SDK_RANGE_UNSATISFIED" };
|
|
73
|
+
return false;
|
|
74
|
+
// An unreadable file is an integrity failure, never a raw I/O error.
|
|
75
|
+
const actualHash = await computeFileHash(path.join(pluginRoot, relativeFilePath)).catch(() => undefined);
|
|
76
|
+
if (actualHash !== expectedHash)
|
|
77
|
+
return false;
|
|
102
78
|
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
let importedModule;
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
/** Declared browser providers go through bundled-approval admission; none declared admits trivially. */
|
|
82
|
+
async function admitDeclaredBrowserProviders(required) {
|
|
83
|
+
const { record, manifest, pluginRoot } = required;
|
|
84
|
+
if (!manifest.browserProviders?.length)
|
|
85
|
+
return { admitted: true };
|
|
86
|
+
return admitBrowserProviderAssets({ record, manifest, pluginRoot, approvals: required.approvals ?? [] });
|
|
87
|
+
}
|
|
88
|
+
function isExecutionAdmitted(required) {
|
|
89
|
+
const { tierPolicy, record, manifest } = required;
|
|
90
|
+
return !(manifest.tier === "tier-2" && tierPolicy.execution !== "worker") && tierPolicy.allowLoad({ record, manifest });
|
|
91
|
+
}
|
|
92
|
+
/** Step (3): the only place plugin code is ever evaluated. */
|
|
93
|
+
async function importPluginModule(required) {
|
|
119
94
|
try {
|
|
120
95
|
// Same-version replacement must evaluate the reviewed package again. Build this URL only at
|
|
121
96
|
// step (3), after integrity and SDK compatibility have passed (CIC U-001 order unchanged).
|
|
122
97
|
// Injected import seams keep their original path contract. A fresh filesystem graph refreshes
|
|
123
98
|
// ALL packaged helpers (including nested/dynamic imports and CommonJS require caches).
|
|
124
|
-
const imported = await importModule({ plugin: { pluginId: record.id, packageRoot: pluginRoot }, modulePath: entryPath });
|
|
99
|
+
const imported = await required.importModule({ plugin: { pluginId: required.record.id, packageRoot: required.pluginRoot }, modulePath: required.entryPath });
|
|
125
100
|
if (typeof imported === "string")
|
|
126
|
-
return {
|
|
127
|
-
|
|
101
|
+
return { reason: "CODE_ENTRY_MISSING" };
|
|
102
|
+
return { moduleValue: { default: imported.exported } };
|
|
128
103
|
}
|
|
129
104
|
catch (error) {
|
|
130
105
|
if (error instanceof PluginSnapshotIntegrityError)
|
|
131
|
-
return {
|
|
132
|
-
return {
|
|
133
|
-
}
|
|
134
|
-
// --- Step (4): validate the `definePlugin()` export, build the per-load gated SDK, run setup. ---
|
|
135
|
-
const plugin = pluginSdkBinding.readDefinedPlugin({ moduleValue: importedModule });
|
|
136
|
-
if (!plugin) {
|
|
137
|
-
return { loaded: false, reason: "PLUGIN_EXPORT_INVALID" };
|
|
106
|
+
return { reason: "INTEGRITY_FAILED" };
|
|
107
|
+
return { reason: "CODE_ENTRY_MISSING" };
|
|
138
108
|
}
|
|
109
|
+
}
|
|
110
|
+
/** Step (4): validate the `definePlugin()` export, build the per-load gated SDK, run setup. */
|
|
111
|
+
async function runPluginSetup(required) {
|
|
112
|
+
const { pluginSdkBinding, coreDeps } = required;
|
|
113
|
+
const plugin = pluginSdkBinding.readDefinedPlugin({ moduleValue: required.moduleValue });
|
|
114
|
+
if (!plugin)
|
|
115
|
+
return "PLUGIN_EXPORT_INVALID";
|
|
139
116
|
const sdk = buildCapabilityScopedSdk({
|
|
140
|
-
pluginId: record.id,
|
|
141
|
-
capabilities: manifest.capabilities,
|
|
117
|
+
pluginId: required.record.id,
|
|
118
|
+
capabilities: required.manifest.capabilities,
|
|
142
119
|
coreDeps,
|
|
143
120
|
pluginSdkBinding,
|
|
144
121
|
});
|
|
145
122
|
try {
|
|
146
123
|
await plugin.definition.setup(sdk);
|
|
124
|
+
return undefined;
|
|
147
125
|
}
|
|
148
126
|
catch {
|
|
149
|
-
return
|
|
127
|
+
return "PLUGIN_SETUP_FAILED";
|
|
150
128
|
}
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Executes BR-01's 5-step ordered pipeline for one plugin. See CIC U-001 above for the binding
|
|
132
|
+
* ordering constraint this function's statement order must never invert.
|
|
133
|
+
*
|
|
134
|
+
* @throws Never for an expected pipeline failure (those are reported via the returned `reason`);
|
|
135
|
+
* may propagate an unexpected infrastructure error (e.g. a real filesystem I/O failure unrelated
|
|
136
|
+
* to integrity mismatch).
|
|
137
|
+
* @complexity O(file count) for integrity hashing; the `import()`/`setup()` cost beyond that is
|
|
138
|
+
* plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
|
|
139
|
+
* disclosed open gap, not a defect of this function).
|
|
140
|
+
*/
|
|
141
|
+
export async function loadPlugin(required, _optional = {}) {
|
|
142
|
+
const { record, manifest, entryPath, coreDeps } = required;
|
|
143
|
+
const { importModule, tierPolicy, pluginSdkBinding } = required;
|
|
144
|
+
const computeFileHash = (absoluteFilePath) => required.verifyDigest({ absoluteFilePath });
|
|
145
|
+
// --- CIC U-001-ORD1: step (1), integrity, MUST complete successfully before step (2)/(3). ---
|
|
146
|
+
const pluginRoot = derivePluginRoot(entryPath);
|
|
147
|
+
if (!(await verifyIntegrity({ record, manifest, pluginRoot, entryPath, computeFileHash })))
|
|
148
|
+
return failed("INTEGRITY_FAILED");
|
|
149
|
+
// --- CIC U-001-ORD1: step (2), sdkRange, MUST complete successfully before step (3). ---
|
|
150
|
+
if (!semver.satisfies(pluginSdkBinding.runtimeSdkVersion, manifest.sdkRange))
|
|
151
|
+
return failed("SDK_RANGE_UNSATISFIED");
|
|
152
|
+
const admission = await admitDeclaredBrowserProviders({ record, manifest, pluginRoot, approvals: required.browserProviderApprovals });
|
|
153
|
+
if (!admission.admitted)
|
|
154
|
+
return failed(admission.reason);
|
|
155
|
+
const loaded = { loaded: true, ...(admission.providers ? { browserProviders: admission.providers } : {}) };
|
|
156
|
+
// Declarative plugins never reach an executable importer. A worker port is mandatory for tier-2,
|
|
157
|
+
// and tier-3 must be admitted explicitly by the host (CMS-JINI-MODULAR-DESIGN Rev 3 §5).
|
|
158
|
+
if (manifest.tier === "tier-1")
|
|
159
|
+
return loaded;
|
|
160
|
+
if (!isExecutionAdmitted({ tierPolicy, record, manifest }))
|
|
161
|
+
return failed("CODE_ENTRY_MISSING");
|
|
162
|
+
// --- Step (3): only now, after both prior checks pass, is the plugin's code ever evaluated. ---
|
|
163
|
+
const imported = await importPluginModule({ importModule, record, pluginRoot, entryPath });
|
|
164
|
+
if ("reason" in imported)
|
|
165
|
+
return failed(imported.reason);
|
|
166
|
+
const setupFailure = await runPluginSetup({ pluginSdkBinding, moduleValue: imported.moduleValue, record, manifest, coreDeps });
|
|
167
|
+
if (setupFailure)
|
|
168
|
+
return failed(setupFailure);
|
|
151
169
|
// Step (5) remains composition-owned: setup's gated `addFilter()` handle captures the filter in
|
|
152
170
|
// the caller's `coreDeps`; only after this successful return does the root call the shared
|
|
153
171
|
// `attachLoadedPlugin()` path below. That split prevents a late setup failure from leaving a
|
|
154
172
|
// partially-attached filter behind.
|
|
155
|
-
return
|
|
173
|
+
return loaded;
|
|
156
174
|
}
|
|
157
175
|
//# sourceMappingURL=loader.js.map
|
|
@@ -6,6 +6,7 @@ import { mkdir, mkdtemp, rm, writeFile, lstat } from "node:fs/promises";
|
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import { snapshotSitePluginPackage } from "./install.js";
|
|
9
|
+
import { PLUGIN_MANIFEST_FILENAMES } from "../plugin-format.js";
|
|
9
10
|
export class PluginSnapshotIntegrityError extends Error {
|
|
10
11
|
}
|
|
11
12
|
/**
|
|
@@ -46,8 +47,8 @@ export async function snapshotPluginModuleGraph(required, { writeSnapshotFile =
|
|
|
46
47
|
export function verifyPluginSnapshotIntegrity(required, _options = {}) {
|
|
47
48
|
const { files, integrity } = required;
|
|
48
49
|
for (const [key, bytes] of files) {
|
|
49
|
-
if (key
|
|
50
|
-
continue;
|
|
50
|
+
if (PLUGIN_MANIFEST_FILENAMES.includes(key))
|
|
51
|
+
continue; // legacy alias
|
|
51
52
|
const digest = `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
|
|
52
53
|
if (integrity[key] !== digest)
|
|
53
54
|
throw new PluginSnapshotIntegrityError("Package changed before loading.");
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The flags `package-files.ts` opens every packaged file with, computed from the platform's
|
|
3
|
+
* `fs.constants` passed in, so the Windows shape (no `O_NOFOLLOW`) is as checkable as the POSIX one.
|
|
4
|
+
* Internal to the node tier; not re-exported from `./index.ts`.
|
|
5
|
+
*/
|
|
6
|
+
/** The subset of `fs.constants` the read-only, no-follow open needs. */
|
|
7
|
+
export interface OpenFlagConstants {
|
|
8
|
+
readonly O_RDONLY: number;
|
|
9
|
+
readonly O_NOFOLLOW?: number | undefined;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Read-only, and refusing a final-component symlink wherever the platform can express that.
|
|
13
|
+
* @complexity O(1).
|
|
14
|
+
*/
|
|
15
|
+
export declare function readNoFollowFlags({ constants }: {
|
|
16
|
+
constants: OpenFlagConstants;
|
|
17
|
+
}, _optional?: Record<string, never>): number;
|
|
18
|
+
//# sourceMappingURL=open-flags.d.ts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file The flags `package-files.ts` opens every packaged file with, computed from the platform's
|
|
3
|
+
* `fs.constants` passed in, so the Windows shape (no `O_NOFOLLOW`) is as checkable as the POSIX one.
|
|
4
|
+
* Internal to the node tier; not re-exported from `./index.ts`.
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* Read-only, and refusing a final-component symlink wherever the platform can express that.
|
|
8
|
+
* @complexity O(1).
|
|
9
|
+
*/
|
|
10
|
+
export function readNoFollowFlags({ constants }, _optional = {}) {
|
|
11
|
+
// `O_NOFOLLOW` is undefined on Windows; `?? 0` keeps the open valid there.
|
|
12
|
+
return constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0);
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=open-flags.js.map
|
|
@@ -27,6 +27,9 @@
|
|
|
27
27
|
import { constants } from "node:fs";
|
|
28
28
|
import { lstat, open, readdir, realpath } from "node:fs/promises";
|
|
29
29
|
import path from "node:path";
|
|
30
|
+
import { readNoFollowFlags } from "./open-flags.js";
|
|
31
|
+
/** Every packaged file is opened read-only and without following a final-component symlink. */
|
|
32
|
+
const READ_NO_FOLLOW = readNoFollowFlags({ constants });
|
|
30
33
|
/** Sized for a plugin package (a manifest, an entry file, a handful of skills or assets), not a
|
|
31
34
|
* vendored dependency tree. Sent to the client with every listing so its notices never hardcode them. */
|
|
32
35
|
export const PLUGIN_PACKAGE_FILE_LIMITS = {
|
|
@@ -52,8 +55,7 @@ function omittedFile(relativePath, sizeBytes, omitted) {
|
|
|
52
55
|
}
|
|
53
56
|
/** Code-unit order, so the listing is identical whatever the server's locale. */
|
|
54
57
|
function byName(a, b) {
|
|
55
|
-
|
|
56
|
-
return 0;
|
|
58
|
+
// One directory never lists a name twice, so equal names need no case.
|
|
57
59
|
return a.name < b.name ? -1 : 1;
|
|
58
60
|
}
|
|
59
61
|
/**
|
|
@@ -79,10 +81,9 @@ async function resolvePackageRoot(rootDir, containerDir) {
|
|
|
79
81
|
}
|
|
80
82
|
return rootReal;
|
|
81
83
|
}
|
|
82
|
-
/** Counts one entry against the caps. `false` (and `truncated` set) once a cap is already full.
|
|
84
|
+
/** Counts one entry against the caps. `false` (and `truncated` set) once a cap is already full.
|
|
85
|
+
* Never called once truncated: the level loop and the breadth-first walk both stop first. */
|
|
83
86
|
function admitEntry(state) {
|
|
84
|
-
if (state.truncated)
|
|
85
|
-
return false;
|
|
86
87
|
if (state.files.length >= state.limits.maxFiles || state.entries >= state.limits.maxEntries) {
|
|
87
88
|
state.truncated = true;
|
|
88
89
|
return false;
|
|
@@ -92,8 +93,7 @@ function admitEntry(state) {
|
|
|
92
93
|
}
|
|
93
94
|
async function openNoFollow(absolutePath) {
|
|
94
95
|
try {
|
|
95
|
-
|
|
96
|
-
return await open(absolutePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
96
|
+
return await open(absolutePath, READ_NO_FOLLOW);
|
|
97
97
|
}
|
|
98
98
|
catch (error) {
|
|
99
99
|
const code = errnoCode(error);
|
|
@@ -173,17 +173,23 @@ async function readDirectoryLevel(rootReal, relativeDir, state) {
|
|
|
173
173
|
if (!admitEntry(state))
|
|
174
174
|
break;
|
|
175
175
|
const relativePath = relativeDir === "" ? entry.name : `${relativeDir}/${entry.name}`;
|
|
176
|
-
if (entry
|
|
176
|
+
if (await visitEntry(rootReal, relativePath, entry, state))
|
|
177
177
|
subdirectories.push(relativePath);
|
|
178
|
-
else if (entry.isSymbolicLink())
|
|
179
|
-
state.files.push(omittedFile(relativePath, 0, "symlink"));
|
|
180
|
-
else if (entry.isFile())
|
|
181
|
-
await readFileEntry(path.join(rootReal, relativePath), relativePath, state);
|
|
182
178
|
if (state.truncated)
|
|
183
179
|
break;
|
|
184
180
|
}
|
|
185
181
|
return subdirectories;
|
|
186
182
|
}
|
|
183
|
+
/** Records a symlink or file now; `true` when the entry is a subdirectory for the next level. */
|
|
184
|
+
async function visitEntry(rootReal, relativePath, entry, state) {
|
|
185
|
+
if (entry.isDirectory())
|
|
186
|
+
return true;
|
|
187
|
+
if (entry.isSymbolicLink())
|
|
188
|
+
state.files.push(omittedFile(relativePath, 0, "symlink"));
|
|
189
|
+
else if (entry.isFile())
|
|
190
|
+
await readFileEntry(path.join(rootReal, relativePath), relativePath, state);
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
187
193
|
/**
|
|
188
194
|
* Lists a plugin package's files, breadth-first — so a package's top-level manifest is always listed
|
|
189
195
|
* before a deep subtree can use up the caps.
|
|
@@ -82,6 +82,8 @@ export interface PluginSourceDeps extends ManifestHostPorts {
|
|
|
82
82
|
readonly builtInIds: readonly string[];
|
|
83
83
|
readonly installer: PluginInstallerPort;
|
|
84
84
|
readonly policy: PluginSourcePolicyPort;
|
|
85
|
+
/** Host-specific opt-in instructions; omitted hosts receive a neutral refusal. */
|
|
86
|
+
readonly localInstallDisabledMessage?: string;
|
|
85
87
|
/** Host ABI text, avoiding an external site's dependency on npm package resolution. */
|
|
86
88
|
readonly scaffoldEntry: string;
|
|
87
89
|
/** Re-enters the validated runtime loader; returns false when this workspace has it OFF. */
|
|
@@ -6,6 +6,7 @@ import { tmpdir } from 'node:os';
|
|
|
6
6
|
import * as semver from 'semver';
|
|
7
7
|
import { withFileLock, FileLockTimeoutError } from '@jini-ai/platform/fs/file-lock';
|
|
8
8
|
import { validateManifest, validatePluginIdFormat } from '../manifest.js';
|
|
9
|
+
import { PLUGIN_MANIFEST_FILENAME as MANIFEST, LEGACY_PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, canonicalizePluginManifest } from '../plugin-format.js';
|
|
9
10
|
import { computePluginIntegrity, digestSitePluginSnapshot, snapshotSitePluginPackage } from './install.js';
|
|
10
11
|
export class PluginSourceError extends Error {
|
|
11
12
|
code;
|
|
@@ -16,7 +17,6 @@ export class PluginSourceError extends Error {
|
|
|
16
17
|
}
|
|
17
18
|
}
|
|
18
19
|
export const PLUGIN_SOURCE_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 8 * 1024 * 1024, maxEntries: 512 };
|
|
19
|
-
const MANIFEST = 'tovu.plugin.json';
|
|
20
20
|
function fail(code, message) { throw new PluginSourceError(code, message); }
|
|
21
21
|
function safeId(id) {
|
|
22
22
|
if (typeof id !== 'string' || validatePluginIdFormat({ id }, {}).length)
|
|
@@ -49,15 +49,19 @@ async function confined(root, target) {
|
|
|
49
49
|
for (const segment of ['', ...relative.split(path.sep).filter(Boolean)]) {
|
|
50
50
|
if (segment)
|
|
51
51
|
current = path.join(current, segment);
|
|
52
|
-
|
|
53
|
-
continue;
|
|
54
|
-
const info = await lstat(current);
|
|
55
|
-
if (info.isSymbolicLink() || (info.isFile() && info.nlink !== 1))
|
|
56
|
-
fail('PLUGIN_SOURCE_PATH_INVALID', 'Draft and installed paths must not contain symbolic or hard links.');
|
|
57
|
-
if (current !== target && !info.isDirectory())
|
|
58
|
-
fail('PLUGIN_SOURCE_PATH_INVALID', 'A parent path is not a directory.');
|
|
52
|
+
await assertUnlinkedSegment(current, target);
|
|
59
53
|
}
|
|
60
54
|
}
|
|
55
|
+
/** One existing path segment: never a link or hardlink, and a directory unless it is the target. */
|
|
56
|
+
async function assertUnlinkedSegment(current, target) {
|
|
57
|
+
if (!await exists(current))
|
|
58
|
+
return;
|
|
59
|
+
const info = await lstat(current);
|
|
60
|
+
if (info.isSymbolicLink() || (info.isFile() && info.nlink !== 1))
|
|
61
|
+
fail('PLUGIN_SOURCE_PATH_INVALID', 'Draft and installed paths must not contain symbolic or hard links.');
|
|
62
|
+
if (current !== target && !info.isDirectory())
|
|
63
|
+
fail('PLUGIN_SOURCE_PATH_INVALID', 'A parent path is not a directory.');
|
|
64
|
+
}
|
|
61
65
|
/** Whole-file writes publish by rename, so readers cannot observe a half-written file. */
|
|
62
66
|
async function writeAtomic(root, target, bytes) {
|
|
63
67
|
await confined(root, target);
|
|
@@ -74,6 +78,45 @@ async function writeAtomic(root, target, bytes) {
|
|
|
74
78
|
}
|
|
75
79
|
}
|
|
76
80
|
function jsonBytes(value) { return Buffer.from(JSON.stringify(value, null, 2) + '\n'); }
|
|
81
|
+
/** Path segments and bytes of one draft write, bounded before any filesystem probe. */
|
|
82
|
+
function draftWriteInput(file, content) {
|
|
83
|
+
// Bound path depth before filesystem probes can fail with an OS-specific path-length error.
|
|
84
|
+
const segments = file.split('/');
|
|
85
|
+
if (segments.length > PLUGIN_SOURCE_LIMITS.maxEntries)
|
|
86
|
+
fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 512 entries.');
|
|
87
|
+
if (typeof content !== 'string')
|
|
88
|
+
fail('PLUGIN_SOURCE_INPUT_INVALID', 'File content must be a string.');
|
|
89
|
+
const bytes = Buffer.from(content);
|
|
90
|
+
if (bytes.length > PLUGIN_SOURCE_LIMITS.maxFileBytes)
|
|
91
|
+
fail('PLUGIN_SOURCE_TOO_LARGE', 'A draft file may contain at most 1 MiB.');
|
|
92
|
+
return { segments, bytes };
|
|
93
|
+
}
|
|
94
|
+
/** How many of the write's path segments do not exist yet under `base`. */
|
|
95
|
+
async function missingSegmentCount(base, segments) {
|
|
96
|
+
let missing = 0;
|
|
97
|
+
for (let index = 1; index <= segments.length; index++) {
|
|
98
|
+
if (!await exists(path.join(base, ...segments.slice(0, index))))
|
|
99
|
+
missing++;
|
|
100
|
+
}
|
|
101
|
+
return missing;
|
|
102
|
+
}
|
|
103
|
+
/** The draft's manifest JSON (current name first, then the legacy alias), or a refusal. */
|
|
104
|
+
function parseDraftManifest(files) {
|
|
105
|
+
const filename = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
|
|
106
|
+
try {
|
|
107
|
+
return JSON.parse(filename === undefined ? '' : files.get(filename).toString('utf8'));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
return fail('PLUGIN_MANIFEST_INVALID', `A valid ${MANIFEST} is required.`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
/** A declared version above the latest install is kept; otherwise the latest gets a patch bump.
|
|
114
|
+
* Both inputs are already valid SemVer — `latest` comes from `versions()`, which refuses any
|
|
115
|
+
* unrecognized version folder, and `declaredVersion` passed `validateManifest` — so the bump
|
|
116
|
+
* always yields a version and needs no null check. */
|
|
117
|
+
function nextSealVersion(latest, declaredVersion) {
|
|
118
|
+
return latest && !semver.gt(declaredVersion, latest) ? new semver.SemVer(latest).inc('patch').version : declaredVersion;
|
|
119
|
+
}
|
|
77
120
|
/** Build the bounded Node draft adapter.
|
|
78
121
|
* @param required Site path and injected manifest, installer, policy and reload owners.
|
|
79
122
|
* @param optional.temporaryDir External sealing staging root; defaults to the OS temp directory.
|
|
@@ -132,10 +175,10 @@ export function createPluginSourceService(required, optional = {}) {
|
|
|
132
175
|
await mkdir(drafts, { recursive: true });
|
|
133
176
|
const staging = await mkdtemp(path.join(drafts, '.open-'));
|
|
134
177
|
try {
|
|
135
|
-
for (const [file, bytes] of files) {
|
|
178
|
+
for (const [file, bytes] of canonicalizePluginManifest({ files })) {
|
|
136
179
|
safeFile(file);
|
|
137
180
|
await writeAtomic(root, path.join(staging, file), bytes);
|
|
138
|
-
}
|
|
181
|
+
} // legacy alias
|
|
139
182
|
await confined(root, draft(id));
|
|
140
183
|
await rename(staging, draft(id));
|
|
141
184
|
}
|
|
@@ -158,15 +201,9 @@ export function createPluginSourceService(required, optional = {}) {
|
|
|
158
201
|
}
|
|
159
202
|
async function write(id, file, content) {
|
|
160
203
|
safeFile(file);
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 512 entries.');
|
|
165
|
-
if (typeof content !== 'string')
|
|
166
|
-
fail('PLUGIN_SOURCE_INPUT_INVALID', 'File content must be a string.');
|
|
167
|
-
const bytes = Buffer.from(content);
|
|
168
|
-
if (bytes.length > PLUGIN_SOURCE_LIMITS.maxFileBytes)
|
|
169
|
-
fail('PLUGIN_SOURCE_TOO_LARGE', 'A draft file may contain at most 1 MiB.');
|
|
204
|
+
if (file === LEGACY_PLUGIN_MANIFEST_FILENAME)
|
|
205
|
+
file = MANIFEST; // legacy alias
|
|
206
|
+
const { segments, bytes } = draftWriteInput(file, content);
|
|
170
207
|
const files = await snapshot(draft(id));
|
|
171
208
|
await confined(root, path.join(draft(id), file));
|
|
172
209
|
if (await exists(path.join(draft(id), file)) && (await lstat(path.join(draft(id), file))).isDirectory())
|
|
@@ -174,19 +211,19 @@ export function createPluginSourceService(required, optional = {}) {
|
|
|
174
211
|
files.set(file, bytes);
|
|
175
212
|
const total = [...files.values()].reduce((sum, value) => sum + value.length, 0);
|
|
176
213
|
// The snapshot count includes empty directories, which a files-only map would miss.
|
|
177
|
-
|
|
178
|
-
for (let index = 1; index <= segments.length; index++) {
|
|
179
|
-
if (!await exists(path.join(draft(id), ...segments.slice(0, index))))
|
|
180
|
-
addedEntries++;
|
|
181
|
-
}
|
|
214
|
+
const addedEntries = await missingSegmentCount(draft(id), segments);
|
|
182
215
|
if (total > PLUGIN_SOURCE_LIMITS.maxTotalBytes || files.entryCount + addedEntries > PLUGIN_SOURCE_LIMITS.maxEntries)
|
|
183
216
|
fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 8 MiB or 512 entries.');
|
|
184
217
|
await writeAtomic(root, path.join(draft(id), file), bytes);
|
|
218
|
+
if (file === MANIFEST)
|
|
219
|
+
await rm(path.join(draft(id), LEGACY_PLUGIN_MANIFEST_FILENAME), { force: true }); // legacy alias
|
|
185
220
|
return { bytesWritten: bytes.length };
|
|
186
221
|
}
|
|
187
222
|
async function read(id, file) {
|
|
188
223
|
safeFile(file);
|
|
189
224
|
const files = await snapshot(draft(id));
|
|
225
|
+
if (PLUGIN_MANIFEST_FILENAMES.includes(file))
|
|
226
|
+
file = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)) ?? MANIFEST; // legacy alias
|
|
190
227
|
const bytes = files.get(file);
|
|
191
228
|
if (!bytes)
|
|
192
229
|
fail('PLUGIN_SOURCE_FILE_MISSING', 'The requested file is not in the draft.');
|
|
@@ -201,31 +238,16 @@ export function createPluginSourceService(required, optional = {}) {
|
|
|
201
238
|
* encoder is needed; the folder installer refuses sources inside its own destination. */
|
|
202
239
|
async function publish(id, files, rollbackFrom) {
|
|
203
240
|
if (!required.policy.localInstallEnabled({}, {}))
|
|
204
|
-
fail('PLUGIN_LOCAL_INSTALL_DISABLED', '
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
}
|
|
209
|
-
catch {
|
|
210
|
-
return fail('PLUGIN_MANIFEST_INVALID', 'A valid tovu.plugin.json is required.');
|
|
211
|
-
}
|
|
241
|
+
fail('PLUGIN_LOCAL_INSTALL_DISABLED', required.localInstallDisabledMessage ?? 'Local plugin install is disabled by the host.');
|
|
242
|
+
const raw = parseDraftManifest(files);
|
|
243
|
+
// `validate` checks the manifest against `folderName: id`, so a manifest whose id is missing or
|
|
244
|
+
// differs from the draft id is already refused there (ID_FOLDER_MISMATCH).
|
|
212
245
|
validate(id, raw);
|
|
213
246
|
const manifest = raw;
|
|
214
|
-
|
|
215
|
-
fail('PLUGIN_MANIFEST_INVALID', 'The manifest id must match the draft id.');
|
|
216
|
-
const latest = (await versions(id))[0];
|
|
217
|
-
const declaredVersion = String(manifest.version);
|
|
218
|
-
const version = latest && !semver.gt(declaredVersion, latest) ? semver.inc(latest, 'patch') : declaredVersion;
|
|
219
|
-
if (!version)
|
|
220
|
-
fail('PLUGIN_SOURCE_VERSION_INVALID', 'A valid semantic version is required.');
|
|
247
|
+
const version = nextSealVersion((await versions(id))[0], String(manifest.version));
|
|
221
248
|
const staging = await mkdtemp(path.join(optional.temporaryDir ?? tmpdir(), 'plugin-source-'));
|
|
222
249
|
try {
|
|
223
|
-
|
|
224
|
-
safeFile(file);
|
|
225
|
-
await writeAtomic(staging, path.join(staging, file), bytes);
|
|
226
|
-
}
|
|
227
|
-
const integrity = await computePluginIntegrity({ sourceDir: staging });
|
|
228
|
-
await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, version, integrity }));
|
|
250
|
+
await stageSealedPackage(staging, files, { ...manifest, version });
|
|
229
251
|
const input = { sourceDir: staging };
|
|
230
252
|
const preview = await required.installer.preview(input, { versionAppend: true });
|
|
231
253
|
const plugin = await required.installer.install({ ...input, expectedDigest: preview.digest }, { versionAppend: true });
|
|
@@ -233,25 +255,37 @@ export function createPluginSourceService(required, optional = {}) {
|
|
|
233
255
|
// a draft path. Tier-3 has full server access by owner decision (2026-10-09), so this is an
|
|
234
256
|
// assistant-tool boundary, not isolation from executing code. TODO: sandbox tier-3 later.
|
|
235
257
|
await writeAtomic(root, marker(id, version), jsonBytes({ digest: plugin.digest }));
|
|
236
|
-
|
|
237
|
-
try {
|
|
238
|
-
reloaded = await required.reload({ id }, {});
|
|
239
|
-
}
|
|
240
|
-
catch (error) {
|
|
241
|
-
return { installed: true, plugin, reloaded: false, reloadError: error instanceof Error ? error.message : String(error), ...(rollbackFrom ? { rollbackFrom } : {}) };
|
|
242
|
-
}
|
|
243
|
-
// Failed reloads retain all recovery bytes. The installer owns which versions are safe to
|
|
244
|
-
// retire, including old active pointers belonging to other workspaces.
|
|
245
|
-
for (const retired of await required.pruneVersions({ id }, {})) {
|
|
246
|
-
await confined(root, marker(id, retired));
|
|
247
|
-
await rm(path.dirname(marker(id, retired)), { recursive: true, force: true });
|
|
248
|
-
}
|
|
249
|
-
return { installed: true, plugin, reloaded, ...(rollbackFrom ? { rollbackFrom } : {}) };
|
|
258
|
+
return await reloadAndPrune(id, plugin, rollbackFrom ? { rollbackFrom } : {});
|
|
250
259
|
}
|
|
251
260
|
finally {
|
|
252
261
|
await rm(staging, { recursive: true, force: true });
|
|
253
262
|
}
|
|
254
263
|
}
|
|
264
|
+
/** Writes the draft files, then the manifest with the sealed version and fresh integrity. */
|
|
265
|
+
async function stageSealedPackage(staging, files, manifest) {
|
|
266
|
+
for (const [file, bytes] of canonicalizePluginManifest({ files })) {
|
|
267
|
+
safeFile(file);
|
|
268
|
+
await writeAtomic(staging, path.join(staging, file), bytes);
|
|
269
|
+
} // legacy alias
|
|
270
|
+
const integrity = await computePluginIntegrity({ sourceDir: staging });
|
|
271
|
+
await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, integrity }));
|
|
272
|
+
}
|
|
273
|
+
async function reloadAndPrune(id, plugin, rollback) {
|
|
274
|
+
let reloaded = false;
|
|
275
|
+
try {
|
|
276
|
+
reloaded = await required.reload({ id }, {});
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
return { installed: true, plugin, reloaded: false, reloadError: error instanceof Error ? error.message : String(error), ...rollback };
|
|
280
|
+
}
|
|
281
|
+
// Failed reloads retain all recovery bytes. The installer owns which versions are safe to
|
|
282
|
+
// retire, including old active pointers belonging to other workspaces.
|
|
283
|
+
for (const retired of await required.pruneVersions({ id }, {})) {
|
|
284
|
+
await confined(root, marker(id, retired));
|
|
285
|
+
await rm(path.dirname(marker(id, retired)), { recursive: true, force: true });
|
|
286
|
+
}
|
|
287
|
+
return { installed: true, plugin, reloaded, ...rollback };
|
|
288
|
+
}
|
|
255
289
|
return {
|
|
256
290
|
create: ({ id, name, description }, _options = {}) => locked(id, async () => {
|
|
257
291
|
if (typeof name !== 'string' || !name.trim() || typeof description !== 'string')
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @file
|
|
3
|
-
* what a
|
|
2
|
+
* @file Host plugin conflict rules on top of the neutral detector (`claim-conflicts.ts`):
|
|
3
|
+
* what a plugin manifest claims, who keeps a contested name, and the sentence an operator or an
|
|
4
4
|
* agent reads when a plugin is refused.
|
|
5
5
|
*
|
|
6
6
|
* Spec note: `ADS-memory/specs/005-plugin-system/conflicts.spec.md`.
|
|
@@ -103,7 +103,9 @@ function toPluginConflicts(conflicts, names) {
|
|
|
103
103
|
kind: conflict.kind,
|
|
104
104
|
key: conflict.key,
|
|
105
105
|
heldBy: conflict.heldBy,
|
|
106
|
-
|
|
106
|
+
// Every owner the detector ran over is core or a valid discovered record, and `names` is built
|
|
107
|
+
// from exactly those ids (`resolvePluginConflicts`), so a holder always has a display name.
|
|
108
|
+
heldByName: names.get(conflict.heldBy),
|
|
107
109
|
heldKey: conflict.heldKey,
|
|
108
110
|
}));
|
|
109
111
|
}
|
|
@@ -145,7 +147,7 @@ export function resolvePluginConflicts(required, optional = {}) {
|
|
|
145
147
|
}
|
|
146
148
|
return result;
|
|
147
149
|
}
|
|
148
|
-
/** One conflict, in words: `tool 'x' is provided by plugin 'a' (A)` / `... is reserved by
|
|
150
|
+
/** One conflict, in words: `tool 'x' is provided by plugin 'a' (A)` / `... is reserved by the host core ('/api/*')`. */
|
|
149
151
|
function describeOne(conflict) {
|
|
150
152
|
const holder = conflict.heldBy === CORE_OWNER_ID
|
|
151
153
|
? `is reserved by ${conflict.heldByName}${conflict.heldKey === conflict.key ? "" : ` ('${conflict.heldKey}')`}`
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Plugin wire identifiers. Readers prefer the canonical manifest; publishers emit only it. */
|
|
2
|
+
export declare const PLUGIN_MANIFEST_FILENAME = "jini.plugin.json";
|
|
3
|
+
export declare const LEGACY_PLUGIN_MANIFEST_FILENAME = "tovu.plugin.json";
|
|
4
|
+
export declare const PLUGIN_MANIFEST_FILENAMES: readonly string[];
|
|
5
|
+
export declare const PLUGIN_SDK_SPECIFIER = "@jini-ai/plugin-sdk";
|
|
6
|
+
export declare const LEGACY_PLUGIN_SDK_SPECIFIER = "@tovu/sdk";
|
|
7
|
+
export declare const PLUGIN_SDK_SPECIFIERS: readonly string[];
|
|
8
|
+
/** Preserve the selected manifest's exact bytes while dropping alternate manifest filenames.
|
|
9
|
+
* Missing manifests remain missing so the existing validator owns the diagnostic.
|
|
10
|
+
*/
|
|
11
|
+
export declare function canonicalizePluginManifest<T>(required: {
|
|
12
|
+
files: ReadonlyMap<string, T>;
|
|
13
|
+
}, _optional?: Record<string, never>): Map<string, T>;
|
|
14
|
+
//# sourceMappingURL=plugin-format.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/** Plugin wire identifiers. Readers prefer the canonical manifest; publishers emit only it. */
|
|
2
|
+
export const PLUGIN_MANIFEST_FILENAME = 'jini.plugin.json';
|
|
3
|
+
export const LEGACY_PLUGIN_MANIFEST_FILENAME = 'tovu.plugin.json'; // legacy alias
|
|
4
|
+
export const PLUGIN_MANIFEST_FILENAMES = [PLUGIN_MANIFEST_FILENAME, LEGACY_PLUGIN_MANIFEST_FILENAME]; // legacy alias
|
|
5
|
+
export const PLUGIN_SDK_SPECIFIER = '@jini-ai/plugin-sdk';
|
|
6
|
+
export const LEGACY_PLUGIN_SDK_SPECIFIER = '@tovu/sdk'; // legacy alias
|
|
7
|
+
export const PLUGIN_SDK_SPECIFIERS = [PLUGIN_SDK_SPECIFIER, LEGACY_PLUGIN_SDK_SPECIFIER]; // legacy alias
|
|
8
|
+
/** Preserve the selected manifest's exact bytes while dropping alternate manifest filenames.
|
|
9
|
+
* Missing manifests remain missing so the existing validator owns the diagnostic.
|
|
10
|
+
*/
|
|
11
|
+
export function canonicalizePluginManifest(required, _optional = {}) {
|
|
12
|
+
const files = new Map(required.files);
|
|
13
|
+
const selected = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
|
|
14
|
+
const manifest = selected === undefined ? undefined : files.get(selected);
|
|
15
|
+
for (const name of PLUGIN_MANIFEST_FILENAMES)
|
|
16
|
+
files.delete(name); // legacy alias
|
|
17
|
+
if (selected !== undefined)
|
|
18
|
+
files.set(PLUGIN_MANIFEST_FILENAME, manifest);
|
|
19
|
+
return files;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=plugin-format.js.map
|