@jini-ai/plugins 0.5.1 → 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.
Files changed (112) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/host/browser-providers.d.ts +2 -9
  3. package/dist/host/browser-providers.js +34 -18
  4. package/dist/host/contributions.d.ts +4 -1
  5. package/dist/host/contributions.js +19 -8
  6. package/dist/host/discovery-types.d.ts +1 -1
  7. package/dist/host/hook-registry.js +7 -5
  8. package/dist/host/manifest-types.d.ts +103 -0
  9. package/dist/host/manifest-types.js +2 -0
  10. package/dist/host/manifest.d.ts +2 -94
  11. package/dist/host/manifest.js +27 -19
  12. package/dist/host/node/discovery.js +23 -18
  13. package/dist/host/node/install.js +252 -200
  14. package/dist/host/node/loader.js +84 -66
  15. package/dist/host/node/open-flags.d.ts +18 -0
  16. package/dist/host/node/open-flags.js +14 -0
  17. package/dist/host/node/package-files.js +18 -12
  18. package/dist/host/node/source-drafts.js +83 -56
  19. package/dist/host/plugin-claims.js +3 -1
  20. package/dist/host/ports.d.ts +1 -1
  21. package/dist/host/tool-contributions.js +3 -1
  22. package/dist/host/worker/protocol.js +8 -6
  23. package/dist/host/worker/run-call.js +20 -17
  24. package/package.json +5 -5
  25. package/dist/glue/attachment-points/content-lifecycle.d.ts.map +0 -1
  26. package/dist/glue/attachment-points/content-lifecycle.js.map +0 -1
  27. package/dist/glue/attachment-points/events.d.ts.map +0 -1
  28. package/dist/glue/attachment-points/events.js.map +0 -1
  29. package/dist/glue/attachment-points/tool-registration.d.ts.map +0 -1
  30. package/dist/glue/attachment-points/tool-registration.js.map +0 -1
  31. package/dist/glue/capability-gate.d.ts.map +0 -1
  32. package/dist/glue/capability-gate.js.map +0 -1
  33. package/dist/glue/dispatch.d.ts.map +0 -1
  34. package/dist/glue/dispatch.js.map +0 -1
  35. package/dist/glue/index.d.ts.map +0 -1
  36. package/dist/glue/index.js.map +0 -1
  37. package/dist/glue/manifest.d.ts.map +0 -1
  38. package/dist/glue/manifest.js.map +0 -1
  39. package/dist/glue/ports.d.ts.map +0 -1
  40. package/dist/glue/ports.js.map +0 -1
  41. package/dist/host/activation.d.ts.map +0 -1
  42. package/dist/host/activation.js.map +0 -1
  43. package/dist/host/attach-loaded-plugin.d.ts.map +0 -1
  44. package/dist/host/attach-loaded-plugin.js.map +0 -1
  45. package/dist/host/browser-providers.d.ts.map +0 -1
  46. package/dist/host/browser-providers.js.map +0 -1
  47. package/dist/host/bundled-initialization.d.ts.map +0 -1
  48. package/dist/host/bundled-initialization.js.map +0 -1
  49. package/dist/host/capability-sdk.d.ts.map +0 -1
  50. package/dist/host/capability-sdk.js.map +0 -1
  51. package/dist/host/claim-conflicts.d.ts.map +0 -1
  52. package/dist/host/claim-conflicts.js.map +0 -1
  53. package/dist/host/contributions.d.ts.map +0 -1
  54. package/dist/host/contributions.js.map +0 -1
  55. package/dist/host/declarative-enable.d.ts.map +0 -1
  56. package/dist/host/declarative-enable.js.map +0 -1
  57. package/dist/host/discovery-types.d.ts.map +0 -1
  58. package/dist/host/discovery-types.js.map +0 -1
  59. package/dist/host/errors.d.ts.map +0 -1
  60. package/dist/host/errors.js.map +0 -1
  61. package/dist/host/hook-registry.d.ts.map +0 -1
  62. package/dist/host/hook-registry.js.map +0 -1
  63. package/dist/host/index.d.ts.map +0 -1
  64. package/dist/host/index.js.map +0 -1
  65. package/dist/host/manifest.d.ts.map +0 -1
  66. package/dist/host/manifest.js.map +0 -1
  67. package/dist/host/node/browser-provider-assets.d.ts.map +0 -1
  68. package/dist/host/node/browser-provider-assets.js.map +0 -1
  69. package/dist/host/node/discovery.d.ts.map +0 -1
  70. package/dist/host/node/discovery.js.map +0 -1
  71. package/dist/host/node/index.d.ts.map +0 -1
  72. package/dist/host/node/index.js.map +0 -1
  73. package/dist/host/node/install.d.ts.map +0 -1
  74. package/dist/host/node/install.js.map +0 -1
  75. package/dist/host/node/loader.d.ts.map +0 -1
  76. package/dist/host/node/loader.js.map +0 -1
  77. package/dist/host/node/module-snapshot.d.ts.map +0 -1
  78. package/dist/host/node/module-snapshot.js.map +0 -1
  79. package/dist/host/node/package-files.d.ts.map +0 -1
  80. package/dist/host/node/package-files.js.map +0 -1
  81. package/dist/host/node/source-drafts.d.ts.map +0 -1
  82. package/dist/host/node/source-drafts.js.map +0 -1
  83. package/dist/host/plugin-claims.d.ts.map +0 -1
  84. package/dist/host/plugin-claims.js.map +0 -1
  85. package/dist/host/plugin-format.d.ts.map +0 -1
  86. package/dist/host/plugin-format.js.map +0 -1
  87. package/dist/host/ports.d.ts.map +0 -1
  88. package/dist/host/ports.js.map +0 -1
  89. package/dist/host/quarantine.d.ts.map +0 -1
  90. package/dist/host/quarantine.js.map +0 -1
  91. package/dist/host/repo.memory.d.ts.map +0 -1
  92. package/dist/host/repo.memory.js.map +0 -1
  93. package/dist/host/source-policy.d.ts.map +0 -1
  94. package/dist/host/source-policy.js.map +0 -1
  95. package/dist/host/sql/index.d.ts.map +0 -1
  96. package/dist/host/sql/index.js.map +0 -1
  97. package/dist/host/sql/repo.d.ts.map +0 -1
  98. package/dist/host/sql/repo.js.map +0 -1
  99. package/dist/host/sql/repo.rows.d.ts.map +0 -1
  100. package/dist/host/sql/repo.rows.js.map +0 -1
  101. package/dist/host/tool-contributions.d.ts.map +0 -1
  102. package/dist/host/tool-contributions.js.map +0 -1
  103. package/dist/host/uninstall.d.ts.map +0 -1
  104. package/dist/host/uninstall.js.map +0 -1
  105. package/dist/host/worker/import-seam.d.ts.map +0 -1
  106. package/dist/host/worker/import-seam.js.map +0 -1
  107. package/dist/host/worker/index.d.ts.map +0 -1
  108. package/dist/host/worker/index.js.map +0 -1
  109. package/dist/host/worker/protocol.d.ts.map +0 -1
  110. package/dist/host/worker/protocol.js.map +0 -1
  111. package/dist/host/worker/run-call.d.ts.map +0 -1
  112. package/dist/host/worker/run-call.js.map +0 -1
@@ -61,97 +61,115 @@ export class PluginLoadError extends Error {
61
61
  this.reason = reason;
62
62
  }
63
63
  }
64
- /**
65
- * Executes BR-01's 5-step ordered pipeline for one plugin. See CIC U-001 above for the binding
66
- * ordering constraint this function's statement order must never invert.
67
- *
68
- * @throws Never for an expected pipeline failure (those are reported via the returned `reason`);
69
- * may propagate an unexpected infrastructure error (e.g. a real filesystem I/O failure unrelated
70
- * to integrity mismatch).
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 { loaded: false, reason: "INTEGRITY_FAILED" };
88
- let actualHash;
89
- try {
90
- actualHash = await computeFileHash(path.join(pluginRoot, relativeFilePath));
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
- let browserProviders;
104
- if (manifest.browserProviders?.length) {
105
- const admission = await admitBrowserProviderAssets({ record, manifest, pluginRoot, approvals: required.browserProviderApprovals ?? [] });
106
- if (!admission.admitted)
107
- return { loaded: false, reason: admission.reason };
108
- browserProviders = admission.providers;
109
- }
110
- // Declarative plugins never reach an executable importer. A worker port is mandatory for tier-2,
111
- // and tier-3 must be admitted explicitly by the host (CMS-JINI-MODULAR-DESIGN Rev 3 §5).
112
- if (manifest.tier === "tier-1")
113
- return { loaded: true, ...(browserProviders ? { browserProviders } : {}) };
114
- if ((manifest.tier === "tier-2" && tierPolicy.execution !== "worker") || !tierPolicy.allowLoad({ record, manifest })) {
115
- return { loaded: false, reason: "CODE_ENTRY_MISSING" };
116
- }
117
- // --- Step (3): only now, after both prior checks pass, is the plugin's code ever evaluated. ---
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 { loaded: false, reason: "CODE_ENTRY_MISSING" };
127
- importedModule = { default: imported.exported };
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 { loaded: false, reason: "INTEGRITY_FAILED" };
132
- return { loaded: false, reason: "CODE_ENTRY_MISSING" };
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 { loaded: false, reason: "PLUGIN_SETUP_FAILED" };
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 { loaded: true, ...(browserProviders ? { browserProviders } : {}) };
173
+ return loaded;
156
174
  }
157
175
  //# sourceMappingURL=loader.js.map
@@ -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
- if (a.name === b.name)
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
- // `O_NOFOLLOW` is undefined on Windows; `?? 0` keeps the open valid there.
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.isDirectory())
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.
@@ -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
- if (!await exists(current))
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.
@@ -160,15 +203,7 @@ export function createPluginSourceService(required, optional = {}) {
160
203
  safeFile(file);
161
204
  if (file === LEGACY_PLUGIN_MANIFEST_FILENAME)
162
205
  file = MANIFEST; // legacy alias
163
- // Bound path depth before filesystem probes can fail with an OS-specific path-length error.
164
- const segments = file.split('/');
165
- if (segments.length > PLUGIN_SOURCE_LIMITS.maxEntries)
166
- fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 512 entries.');
167
- if (typeof content !== 'string')
168
- fail('PLUGIN_SOURCE_INPUT_INVALID', 'File content must be a string.');
169
- const bytes = Buffer.from(content);
170
- if (bytes.length > PLUGIN_SOURCE_LIMITS.maxFileBytes)
171
- fail('PLUGIN_SOURCE_TOO_LARGE', 'A draft file may contain at most 1 MiB.');
206
+ const { segments, bytes } = draftWriteInput(file, content);
172
207
  const files = await snapshot(draft(id));
173
208
  await confined(root, path.join(draft(id), file));
174
209
  if (await exists(path.join(draft(id), file)) && (await lstat(path.join(draft(id), file))).isDirectory())
@@ -176,11 +211,7 @@ export function createPluginSourceService(required, optional = {}) {
176
211
  files.set(file, bytes);
177
212
  const total = [...files.values()].reduce((sum, value) => sum + value.length, 0);
178
213
  // The snapshot count includes empty directories, which a files-only map would miss.
179
- let addedEntries = 0;
180
- for (let index = 1; index <= segments.length; index++) {
181
- if (!await exists(path.join(draft(id), ...segments.slice(0, index))))
182
- addedEntries++;
183
- }
214
+ const addedEntries = await missingSegmentCount(draft(id), segments);
184
215
  if (total > PLUGIN_SOURCE_LIMITS.maxTotalBytes || files.entryCount + addedEntries > PLUGIN_SOURCE_LIMITS.maxEntries)
185
216
  fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 8 MiB or 512 entries.');
186
217
  await writeAtomic(root, path.join(draft(id), file), bytes);
@@ -208,31 +239,15 @@ export function createPluginSourceService(required, optional = {}) {
208
239
  async function publish(id, files, rollbackFrom) {
209
240
  if (!required.policy.localInstallEnabled({}, {}))
210
241
  fail('PLUGIN_LOCAL_INSTALL_DISABLED', required.localInstallDisabledMessage ?? 'Local plugin install is disabled by the host.');
211
- let raw;
212
- const filename = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
213
- try {
214
- raw = JSON.parse(filename === undefined ? '' : files.get(filename).toString('utf8'));
215
- }
216
- catch {
217
- return fail('PLUGIN_MANIFEST_INVALID', `A valid ${MANIFEST} is required.`);
218
- }
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).
219
245
  validate(id, raw);
220
246
  const manifest = raw;
221
- if (manifest.id !== id)
222
- fail('PLUGIN_MANIFEST_INVALID', 'The manifest id must match the draft id.');
223
- const latest = (await versions(id))[0];
224
- const declaredVersion = String(manifest.version);
225
- const version = latest && !semver.gt(declaredVersion, latest) ? semver.inc(latest, 'patch') : declaredVersion;
226
- if (!version)
227
- fail('PLUGIN_SOURCE_VERSION_INVALID', 'A valid semantic version is required.');
247
+ const version = nextSealVersion((await versions(id))[0], String(manifest.version));
228
248
  const staging = await mkdtemp(path.join(optional.temporaryDir ?? tmpdir(), 'plugin-source-'));
229
249
  try {
230
- for (const [file, bytes] of canonicalizePluginManifest({ files })) {
231
- safeFile(file);
232
- await writeAtomic(staging, path.join(staging, file), bytes);
233
- } // legacy alias
234
- const integrity = await computePluginIntegrity({ sourceDir: staging });
235
- await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, version, integrity }));
250
+ await stageSealedPackage(staging, files, { ...manifest, version });
236
251
  const input = { sourceDir: staging };
237
252
  const preview = await required.installer.preview(input, { versionAppend: true });
238
253
  const plugin = await required.installer.install({ ...input, expectedDigest: preview.digest }, { versionAppend: true });
@@ -240,25 +255,37 @@ export function createPluginSourceService(required, optional = {}) {
240
255
  // a draft path. Tier-3 has full server access by owner decision (2026-10-09), so this is an
241
256
  // assistant-tool boundary, not isolation from executing code. TODO: sandbox tier-3 later.
242
257
  await writeAtomic(root, marker(id, version), jsonBytes({ digest: plugin.digest }));
243
- let reloaded = false;
244
- try {
245
- reloaded = await required.reload({ id }, {});
246
- }
247
- catch (error) {
248
- return { installed: true, plugin, reloaded: false, reloadError: error instanceof Error ? error.message : String(error), ...(rollbackFrom ? { rollbackFrom } : {}) };
249
- }
250
- // Failed reloads retain all recovery bytes. The installer owns which versions are safe to
251
- // retire, including old active pointers belonging to other workspaces.
252
- for (const retired of await required.pruneVersions({ id }, {})) {
253
- await confined(root, marker(id, retired));
254
- await rm(path.dirname(marker(id, retired)), { recursive: true, force: true });
255
- }
256
- return { installed: true, plugin, reloaded, ...(rollbackFrom ? { rollbackFrom } : {}) };
258
+ return await reloadAndPrune(id, plugin, rollbackFrom ? { rollbackFrom } : {});
257
259
  }
258
260
  finally {
259
261
  await rm(staging, { recursive: true, force: true });
260
262
  }
261
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
+ }
262
289
  return {
263
290
  create: ({ id, name, description }, _options = {}) => locked(id, async () => {
264
291
  if (typeof name !== 'string' || !name.trim() || typeof description !== 'string')
@@ -103,7 +103,9 @@ function toPluginConflicts(conflicts, names) {
103
103
  kind: conflict.kind,
104
104
  key: conflict.key,
105
105
  heldBy: conflict.heldBy,
106
- heldByName: names.get(conflict.heldBy) ?? conflict.heldBy,
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
  }
@@ -1,5 +1,5 @@
1
1
  /** Host contracts only. No product SDK, content-type implementation or executable importer lives here. */
2
- import type { PluginManifest, PluginValidationError } from './manifest.js';
2
+ import type { PluginManifest, PluginValidationError } from './manifest-types.js';
3
3
  import type { PluginDiscoveryRecord } from './discovery-types.js';
4
4
  import type { ClaimMode } from './claim-conflicts.js';
5
5
  /** Plain serializable entry envelope; hosts extend it with their own hook payload fields. */
@@ -11,7 +11,9 @@ export function buildPluginContributionToolRegistrations(required, _optional = {
11
11
  return {
12
12
  descriptor: {
13
13
  id: pluginToolIdFor({ pluginId: snapshot.pluginId, name: tool.name }), description: tool.description,
14
- inputSchema: tool.inputSchema, readOnly: false, requiresConfirmation: required.metadata.approval?.confirmation !== 'direct',
14
+ // A self-declared effect may only add confirmation, never remove it: `read` stays not-read-only.
15
+ inputSchema: tool.inputSchema, readOnly: false,
16
+ requiresConfirmation: tool.effect === 'destructive' || required.metadata.approval?.confirmation !== 'direct',
15
17
  timeoutMs: 30000, maxOutputBytes: 65536, metadata: required.metadata,
16
18
  },
17
19
  policy: { authorize: async (ctx) => {
@@ -2,6 +2,12 @@ const FAILURE_STAGES = new Set(["import", "export", "setup", "hook"]);
2
2
  function invalidReply() {
3
3
  return new Error("invalid tier-2 worker reply");
4
4
  }
5
+ function decodeFailureReply({ reply }, _optional = {}) {
6
+ if (typeof reply.stage !== "string" || !FAILURE_STAGES.has(reply.stage) || typeof reply.error !== "string") {
7
+ throw invalidReply();
8
+ }
9
+ return { ok: false, stage: reply.stage, error: reply.error };
10
+ }
5
11
  /**
6
12
  * Validates an untrusted worker message as the reply to a request of `expectedKind`. The worker
7
13
  * runs plugin code, so its message is checked like any other external input.
@@ -13,12 +19,8 @@ export function decodeTier2Reply({ message, expectedKind }, _optional = {}) {
13
19
  if (typeof message !== "object" || message === null)
14
20
  throw invalidReply();
15
21
  const reply = message;
16
- if (reply.ok === false) {
17
- if (typeof reply.stage !== "string" || !FAILURE_STAGES.has(reply.stage) || typeof reply.error !== "string") {
18
- throw invalidReply();
19
- }
20
- return { ok: false, stage: reply.stage, error: reply.error };
21
- }
22
+ if (reply.ok === false)
23
+ return decodeFailureReply({ reply });
22
24
  if (reply.ok !== true || reply.kind !== expectedKind)
23
25
  throw invalidReply();
24
26
  if (expectedKind === "beforeSave")
@@ -18,6 +18,25 @@ import { buildCapabilityScopedSdk } from "../capability-sdk.js";
18
18
  function failed(stage, error) {
19
19
  return { ok: false, stage, error: error instanceof Error ? error.message : String(error) };
20
20
  }
21
+ async function runBeforeSave({ pluginId, request, filter }, _optional = {}) {
22
+ if (!filter)
23
+ return failed("hook", `plugin '${pluginId}' attached no beforeSave filter`);
24
+ let patch;
25
+ try {
26
+ patch = await filter(request.entry, request.ctx);
27
+ }
28
+ catch (error) {
29
+ return failed("hook", error);
30
+ }
31
+ try {
32
+ // postMessage would otherwise throw a DataCloneError outside any reply, which the server can
33
+ // only see as a crashed worker; checking here keeps it a plugin-attributed hook failure.
34
+ return { ok: true, kind: "beforeSave", patch: structuredClone(patch) };
35
+ }
36
+ catch (error) {
37
+ return failed("hook", `plugin '${pluginId}' returned a value that cannot cross the worker boundary: ${error.message}`);
38
+ }
39
+ }
21
40
  /**
22
41
  * Runs one Tier-2 request against the plugin's code in the current thread.
23
42
  *
@@ -55,22 +74,6 @@ export async function runTier2Call(required, _optional = {}) {
55
74
  if (request.kind === "probe") {
56
75
  return { ok: true, kind: "probe", hooks: filter ? [HOOK_CONTENT_ENTRY_BEFORE_SAVE] : [] };
57
76
  }
58
- if (!filter)
59
- return failed("hook", `plugin '${pluginId}' attached no beforeSave filter`);
60
- let patch;
61
- try {
62
- patch = await filter(request.entry, request.ctx);
63
- }
64
- catch (error) {
65
- return failed("hook", error);
66
- }
67
- try {
68
- // postMessage would otherwise throw a DataCloneError outside any reply, which the server can
69
- // only see as a crashed worker; checking here keeps it a plugin-attributed hook failure.
70
- return { ok: true, kind: "beforeSave", patch: structuredClone(patch) };
71
- }
72
- catch (error) {
73
- return failed("hook", `plugin '${pluginId}' returned a value that cannot cross the worker boundary: ${error.message}`);
74
- }
77
+ return runBeforeSave({ pluginId, request, filter });
75
78
  }
76
79
  //# sourceMappingURL=run-call.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/plugins",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Host-independent extension glue and site-plugin runtime with injected SDK, trust, archive and storage ports.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -72,7 +72,7 @@
72
72
  "registry": "https://registry.npmjs.org"
73
73
  },
74
74
  "dependencies": {
75
- "@jini-ai/core": "^0.4.5"
75
+ "@jini-ai/core": "^0.4.9"
76
76
  },
77
77
  "peerDependencies": {
78
78
  "@jini-ai/platform": "^0.5.3",
@@ -98,9 +98,9 @@
98
98
  "semver": "^7.6.2",
99
99
  "@types/semver": "^7.5.8",
100
100
  "kysely": "^0.29.6",
101
- "@jini-ai/platform": "^0.5.6",
102
- "@jini-ai/core": "^0.4.5",
103
- "@jini-ai/db": "0.3.4"
101
+ "@jini-ai/core": "^0.4.9",
102
+ "@jini-ai/platform": "^0.5.10",
103
+ "@jini-ai/db": "0.3.6"
104
104
  },
105
105
  "scripts": {
106
106
  "build": "tsc -p tsconfig.json",
@@ -1 +0,0 @@
1
- {"version":3,"file":"content-lifecycle.d.ts","sourceRoot":"","sources":["../../../src/glue/attachment-points/content-lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAEH,OAAO,KAAK,EAAE,0BAA0B,EAAE,aAAa,EAAgB,MAAM,aAAa,CAAC;AAE3F,MAAM,WAAW,kCAAkC,CAAC,MAAM,GAAG,0BAA0B;IACrF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC5B;;iDAE6C;IAC3C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,cAAc,EAAE,SAAS,aAAa,EAAE,CAAC;IAClD,QAAQ,CAAC,QAAQ,EAAE;QAAE,4BAA4B,CAAC,QAAQ,EAAE;YAAE,QAAQ,EAAE,MAAM,CAAC;YAAC,MAAM,EAAE,MAAM,CAAC;YAAC,cAAc,EAAE,SAAS,aAAa,EAAE,CAAA;SAAE,GAAG,IAAI,CAAA;KAAE,CAAC;CACrJ;AAED,MAAM,MAAM,kCAAkC,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAEvE;;;;;;;;;GASG;AACH,wBAAgB,0BAA0B,CAAC,MAAM,GAAG,0BAA0B,EAC5E,QAAQ,EAAE,kCAAkC,CAAC,MAAM,CAAC,EACpD,SAAS,GAAE,kCAAuC,GACjD,IAAI,CAGN"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"content-lifecycle.js","sourceRoot":"","sources":["../../../src/glue/attachment-points/content-lifecycle.ts"],"names":[],"mappings":"AAsCA;;;;;;;;;GASG;AACH,MAAM,UAAU,0BAA0B,CACxC,QAAoD,EACpD,YAAgD,EAAE;IAElD,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IAChE,QAAQ,CAAC,4BAA4B,CAAC,EAAE,QAAQ,EAAE,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC;AAC9E,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../../../src/glue/attachment-points/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEhD,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,OAAO,EAAE,CAAC,QAAQ,EAAE;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC3E,QAAQ,CAAC,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC;CACzD;AAED,MAAM,MAAM,0BAA0B,GAAG,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;AAE/D,wBAAgB,kBAAkB,CAChC,QAAQ,EAAE,0BAA0B,EACpC,SAAS,GAAE,0BAA+B,GACzC,IAAI,CAGN"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"events.js","sourceRoot":"","sources":["../../../src/glue/attachment-points/events.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,kBAAkB,CAChC,QAAoC,EACpC,YAAwC,EAAE;IAE1C,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC;IAC5D,QAAQ,CAAC,cAAc,CAAC,EAAE,QAAQ,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC;AAC5D,CAAC"}