@jini-ai/plugins 0.6.22 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/host/admin-response.d.ts +93 -0
  3. package/dist/host/admin-response.js +32 -0
  4. package/dist/host/capability-tools.d.ts +369 -0
  5. package/dist/host/capability-tools.js +306 -0
  6. package/dist/host/declarative-content-types.d.ts +245 -0
  7. package/dist/host/declarative-content-types.js +270 -0
  8. package/dist/host/index.d.ts +3 -0
  9. package/dist/host/index.js +3 -0
  10. package/dist/host/manifest.d.ts +1 -4
  11. package/dist/host/manifest.js +2 -5
  12. package/dist/host/node/archive-policy.d.ts +57 -0
  13. package/dist/host/node/archive-policy.js +115 -0
  14. package/dist/host/node/index.d.ts +3 -0
  15. package/dist/host/node/index.js +3 -0
  16. package/dist/host/node/install.d.ts +1 -4
  17. package/dist/host/node/install.js +2 -8
  18. package/dist/host/node/invocation-binding.d.ts +45 -0
  19. package/dist/host/node/invocation-binding.js +69 -0
  20. package/dist/host/node/runtime-core.d.ts +273 -0
  21. package/dist/host/node/runtime-core.js +613 -0
  22. package/dist/host/node/source-drafts.d.ts +1 -5
  23. package/dist/host/node/source-drafts.js +2 -8
  24. package/dist/host/plugin-claims.d.ts +2 -1
  25. package/dist/host/plugin-claims.js +1 -1
  26. package/dist/host/plugin-format.d.ts +4 -0
  27. package/dist/host/plugin-format.js +4 -0
  28. package/dist/host/plugin-tool-errors.d.ts +11 -0
  29. package/dist/host/plugin-tool-errors.js +19 -0
  30. package/dist/host/tools/contract.d.ts +397 -0
  31. package/dist/host/tools/contract.js +7 -0
  32. package/dist/host/tools/index.d.ts +7 -0
  33. package/dist/host/tools/index.js +6 -0
  34. package/dist/host/tools/install.d.ts +12 -0
  35. package/dist/host/tools/install.js +71 -0
  36. package/dist/host/tools/management.d.ts +51 -0
  37. package/dist/host/tools/management.js +607 -0
  38. package/dist/host/tools/source.d.ts +14 -0
  39. package/dist/host/tools/source.js +95 -0
  40. package/dist/host/worker/index.d.ts +1 -0
  41. package/dist/host/worker/index.js +1 -0
  42. package/dist/host/worker/start.d.ts +44 -0
  43. package/dist/host/worker/start.js +31 -0
  44. package/package.json +16 -9
@@ -0,0 +1,613 @@
1
+ /**
2
+ * @file The plugin-owned runtime core: discovery, conflict gates, enable/load/attach, boot re-attach,
3
+ * provider admission, install/source/reload wiring and package-file location for ONE host runtime.
4
+ * Moved from the host composition root (extract-s6 L1c; seamed in place in L1b) with its original
5
+ * text. Every host value (env/policy, Tier-2 runner and worker entry, SDK binding, importer, archive
6
+ * reader, telemetry vocabulary, lookup/admission and wording) is a required or optional input.
7
+ * @agent-note Second-host rule: a host calls {@link createPluginRuntimeCore} once per runtime and wires
8
+ * its own values; nothing here reads env, names a host tool/route/manifest file, or imports a host.
9
+ */
10
+ import { lstat } from "node:fs/promises";
11
+ import path from "node:path";
12
+ import { formatErrorForLog, redactSecrets } from "@jini-ai/core";
13
+ import { createPluginLookupFacade } from "@jini-ai/core/plugin-directory";
14
+ import { setPluginEnabled } from "../activation.js";
15
+ import { initializeBundledPlugins } from "../bundled-initialization.js";
16
+ import { createPluginContributionCapture, createPluginContributionRegistry } from "../contributions.js";
17
+ import { addedPluginCapabilities, pluginCapabilitySet } from "../source-policy.js";
18
+ import { enableDeclaredPlugin } from "../declarative-enable.js";
19
+ import { createHookRegistry } from "../hook-registry.js";
20
+ import { quarantinePlugin } from "../quarantine.js";
21
+ import { describeBootConflictQuarantine, PluginConflictError, resolvePluginConflicts } from "../plugin-claims.js";
22
+ import { attachLoadedPlugin } from "../attach-loaded-plugin.js";
23
+ import { assertPluginInstallIdle, installSitePlugin, previewSitePluginInstall, pruneSitePluginVersions } from "./install.js";
24
+ import { createPluginModuleSnapshotLifecycle, PluginSnapshotLifecycleError } from "./module-snapshot.js";
25
+ import { createPluginSourceService } from "./source-drafts.js";
26
+ import { discoverPlugins as discoverPluginRuntimePlugins, siteEntryPath } from "./discovery.js";
27
+ import { PluginPackagePathError, readPluginPackageFiles as readPluginPackageDirectory } from "./package-files.js";
28
+ import { loadPlugin, PluginLoadError } from "./loader.js";
29
+ import { createTier2ImportSeam } from "../worker/import-seam.js";
30
+ /**
31
+ * Resolves ONE enable attempt's load target (Milestone 1b, 2026-08-20): a compiled-in built-in
32
+ * plugin uses the composition root's own static `PluginRuntimeSource` — entirely unchanged from
33
+ * before this slice, so every existing built-in test (including ones that inject a synthetic
34
+ * `entryPath`/`importModule`, e.g. the auto-quarantine fixture) keeps behaving identically. A
35
+ * site-installed plugin has no static source to find, so its target is derived instead from the
36
+ * SAME discovery record `onPluginEnabled` already fetched this call — reusing `record.manifest`
37
+ * (see that field's own doc for why this, not a second file read, is the TOCTOU-safe choice) and
38
+ * `siteEntryPath()`'s REQ-02 layout convention.
39
+ *
40
+ * Deliberately does not itself touch integrity/`sdkRange`/`import()` — those stay exactly where
41
+ * CIC U-001 requires them, inside `loadPlugin()`'s own fixed step order. This function only decides
42
+ * WHICH manifest/entryPath/import-hook `loadPlugin()` is handed; it never calls `import()` itself
43
+ * and never lets a caller reach one without going through `loadPlugin()`'s ordering first.
44
+ *
45
+ * @returns `null` when the id is neither a known built-in nor a valid, installDir-reachable site
46
+ * record — the caller's existing fail-closed `PLUGIN_EXPORT_INVALID` behavior is unchanged.
47
+ * @complexity O(sources.length) — one linear scan of the static built-in list; no I/O of its own.
48
+ */
49
+ function resolveLoadTarget(params) {
50
+ const { pluginId, sources, record, installDir } = params;
51
+ const builtIn = sources.find((candidate) => candidate.manifest.id === pluginId);
52
+ if (builtIn) {
53
+ return {
54
+ manifest: builtIn.manifest,
55
+ entryPath: builtIn.entryPath,
56
+ attachmentSource: builtIn.source,
57
+ importModule: builtIn.importModule,
58
+ };
59
+ }
60
+ if (record.source === "site" && installDir !== undefined && record.manifest !== undefined) {
61
+ return {
62
+ manifest: record.manifest,
63
+ entryPath: siteEntryPath({ installDir, id: record.id, version: record.version }),
64
+ attachmentSource: record.source,
65
+ };
66
+ }
67
+ return null;
68
+ }
69
+ /**
70
+ * A plugin id safe to use as a single filesystem path segment (Milestone 2, 2026-08-20) — the same
71
+ * character class `src/features/agent-plugins/layout.ts`'s `SAFE_PLUGIN_ID_PATTERN` uses,
72
+ * independently declared here rather than imported: that module is a DIFFERENT, unrelated plugin
73
+ * system (agent-plugins.org format; see this file's own `PluginRuntimeSource` doc history and
74
+ * Milestone 1's handoff for why the two are never wired together), and importing from it would
75
+ * create exactly that coupling for a one-line regex. `.` and `-` are allowed mid-string (matching
76
+ * real semver-adjacent plugin ids like `word-count`) but the pattern has no `/`, no `..`, and no
77
+ * leading/trailing separator — it cannot itself produce a path-traversal segment.
78
+ */
79
+ const SAFE_PLUGIN_ID_SEGMENT = /^[a-z0-9]+(?:[-.][a-z0-9]+)*$/;
80
+ /** Thrown when `pluginId` is not safe to use as a filesystem path segment
81
+ * under `installDir` — either it fails {@link SAFE_PLUGIN_ID_SEGMENT}'s allowlist, or (defense in
82
+ * depth, in case some future caller's id validation elsewhere ever drifts) the resolved absolute
83
+ * path would land outside `installDir` after resolution. Deliberately fails closed on EITHER
84
+ * check independently, not just the one presumed sufficient.
85
+ * @agent-note Error identity: hosts re-export this ONE class (never a copy) so `instanceof` and
86
+ * `name === "PluginUninstallPathError"` hold across the host's routes and tests. */
87
+ export class PluginUninstallPathError extends Error {
88
+ constructor(pluginId) {
89
+ super(`plugin id '${pluginId}' is not a safe filesystem path segment — refusing to remove it`);
90
+ this.name = "PluginUninstallPathError";
91
+ }
92
+ }
93
+ /** A site plugin's version folder name as discovery read it from disk: one segment, no
94
+ * separator, no leading dot. Checked together with {@link SAFE_PLUGIN_ID_SEGMENT} before either is
95
+ * joined into a path. */
96
+ const SAFE_VERSION_SEGMENT = /^[0-9A-Za-z][0-9A-Za-z.+-]*$/;
97
+ /**
98
+ * Where one discovered plugin's files live, for the package-files viewer: a built-in's own
99
+ * `sourceDir`, or a site plugin's `<installDir>/<id>/<version>/` (REQ-02's layout, the same one
100
+ * `siteEntryPath()` joins). The directory is its own container for a built-in; `installDir` is the
101
+ * container for a site plugin, so `readPluginPackageFiles()`'s realpath check keeps a symlinked id
102
+ * or version folder from reaching outside it.
103
+ *
104
+ * @returns `null` when there is no directory to show: a built-in without `sourceDir`, or a site
105
+ * record while `installDir` is unset.
106
+ * @throws {PluginPackagePathError} a site record's id or version is not one safe path segment — a
107
+ * site record's id comes from its own manifest, so it is untrusted text until checked here.
108
+ * @complexity O(sources.length).
109
+ */
110
+ function resolvePackageLocation(params) {
111
+ const { record, sources, installDir } = params;
112
+ if (record.source === "built-in") {
113
+ const sourceDir = sources.find((candidate) => candidate.manifest.id === record.id)?.sourceDir;
114
+ return sourceDir === undefined ? null : { rootDir: sourceDir, containerDir: sourceDir };
115
+ }
116
+ if (installDir === undefined)
117
+ return null;
118
+ if (!SAFE_PLUGIN_ID_SEGMENT.test(record.id) || !SAFE_VERSION_SEGMENT.test(record.version)) {
119
+ throw new PluginPackagePathError(`plugin '${record.id}' version '${record.version}' is not a safe path segment`);
120
+ }
121
+ return { rootDir: path.join(installDir, record.id, record.version), containerDir: installDir };
122
+ }
123
+ /** True when a manifest declares provider factories (`contributes.providers`). */
124
+ function declaresProviders({ manifest }) {
125
+ return (manifest?.contributes?.providers?.length ?? 0) > 0;
126
+ }
127
+ /**
128
+ * The plugin-owned runtime algorithm behind the host's composition wrapper (extract-s6 L1b seam,
129
+ * moved here in L1c). Reads no host module: every host value arrives through
130
+ * {@link PluginRuntimeCoreRequired}/{@link PluginRuntimeCoreOptional}.
131
+ * @agent-note Callback order is unchanged: quarantine writes the activation row, then telemetry;
132
+ * enable loads (integrity, sdkRange, resolver, import, setup) before attach; a disable or newer
133
+ * load during import retires the older epoch.
134
+ * @agent-note Shared state: ONE `activationRepo`/`workspaceId`, ONE hook registry (save AND preview),
135
+ * ONE contribution and provider registry and ONE pending-attachment set per call; the host must not
136
+ * build a second registry or queue beside it. Each plugin load asks the host's
137
+ * `hostBinding.createInvocationCoreDeps` once, so there is exactly one invocation AsyncLocalStorage
138
+ * per load.
139
+ * @agent-note Lifecycle: `dispose()` sets closing, drains pending attachments, then releases module
140
+ * snapshots; attachments refused after that reject with `PluginSnapshotLifecycleError`. Load epochs
141
+ * retire stale generations; version pins come from enabled activation rows (never fall forward).
142
+ * @agent-note Reload: a source reload that widens capabilities throws the host's
143
+ * `text.reloadApprovalRequired` and keeps the approved version running; a failed reload re-enters the
144
+ * same loader for the restored row, and if that fails too the plugin is quarantined with
145
+ * `text.restoreFailedReason`.
146
+ * @agent-note Import order: `loadPlugin()` runs integrity and `sdkRange` before the importer; a Tier-2
147
+ * plugin is never imported in-process (the host runner registers its SDK resolver before importing).
148
+ * Preview (`previewPluginBeforeSave`) writes nothing and counts nothing toward quarantine.
149
+ * @agent-note The host owns the SDK binding, the Tier-2 worker entry/runner/timeout, env and source
150
+ * policy, telemetry vocabulary, lookup/admission and all wording. Errors keep their identity:
151
+ * `PluginLoadError`, `PluginConflictError`, `PluginSnapshotLifecycleError`, `PluginPackagePathError`
152
+ * and {@link PluginUninstallPathError} are thrown as the same classes the package exports.
153
+ * @example createPluginRuntimeCore({ workspaceId, clock, activationRepo, sources, pluginSourcePolicy, tier2CallRunner, pluginSdkBinding, hostBinding, createModuleImporter, text, quarantineTelemetry }, { installDir })
154
+ */
155
+ export function createPluginRuntimeCore(required, optional = {}) {
156
+ const { activationRepo, clock, sources } = required;
157
+ const { installDir } = optional;
158
+ const quarantineDeps = { clock, repo: activationRepo, onQuarantined: ({ pluginId }) => {
159
+ const tracker = optional.tracker?.();
160
+ if (!tracker)
161
+ return undefined;
162
+ const { event, options } = required.quarantineTelemetry({ pluginId });
163
+ return tracker.capture(event, options);
164
+ } };
165
+ const runtimeBinding = { ...required.hostBinding, pluginSdkBinding: required.pluginSdkBinding };
166
+ // The install directory owns versions; its sibling runtime directory owns executable graphs.
167
+ const snapshots = installDir === undefined ? undefined : createPluginModuleSnapshotLifecycle({ runtimeRoot: path.resolve(installDir) + "-runtime" });
168
+ const pendingAttachments = new Set();
169
+ let closing = false;
170
+ const { pluginSourcePolicy } = required;
171
+ const loadedVersions = new Map();
172
+ const browserProviders = new Map();
173
+ let browserGeneration = 0;
174
+ const pluginContributions = createPluginContributionRegistry({});
175
+ const providerContributions = createPluginContributionRegistry({});
176
+ // Only boot's configured selection may admit provider factories (`loadProviderPlugins`).
177
+ const selectedProviders = new Set();
178
+ const loadEpochs = new Map();
179
+ const { tier2CallRunner } = required;
180
+ const hookRegistry = createHookRegistry({ pluginSdkBinding: required.pluginSdkBinding }, {
181
+ ...(optional.failureThreshold === undefined ? {} : { failureThreshold: optional.failureThreshold }),
182
+ onQuarantine: async (input) => {
183
+ onPluginDisabled(input.pluginId);
184
+ await quarantinePlugin({ deps: quarantineDeps, input });
185
+ },
186
+ });
187
+ // Reachability fix (previously always omitted `installDir`, so a plugin placed on disk was
188
+ // never scanned no matter how the composition root itself was configured — see this function's
189
+ // required-params doc).
190
+ const discoverPlugins = () => discoverPluginRuntimePlugins({ ...runtimeBinding, builtIns: sources, ...(installDir === undefined ? {} : { installDir }) });
191
+ /** Retained versions make the activation row's existing active pointer meaningful at boot
192
+ * and reload. A newly installed version is not running until controlled reload advances it. */
193
+ async function discoverActivePlugins() {
194
+ const rows = await activationRepo.listAll();
195
+ const versions = new Map(rows.filter(row => row.workspaceId === required.workspaceId && row.enabled).map(row => [row.pluginId, row.version]));
196
+ return discoverPluginRuntimePlugins({ ...runtimeBinding, builtIns: sources, ...(installDir === undefined ? {} : { installDir }) }, { versions });
197
+ }
198
+ const coreClaims = optional.coreClaims ?? [];
199
+ async function listPluginConflicts(discovery, optional = {}) {
200
+ const [records, activations] = await Promise.all([discovery ?? discoverPlugins(), activationRepo.listAll()]);
201
+ return resolvePluginConflicts({ ...runtimeBinding, workspaceId: required.workspaceId, discovery: records, activations, coreClaims }, optional);
202
+ }
203
+ /** Install preview (2026-10-04): what the staged package would clash with if turned on in THIS
204
+ * workspace now. A synthetic valid record stands in for it and REPLACES an installed version of the
205
+ * same id, so an upgrade is judged by its new manifest only. */
206
+ async function installPreviewConflicts(required) {
207
+ const { manifest } = required;
208
+ const staged = { id: manifest.id, name: manifest.name, version: manifest.version, source: "site", tier: manifest.tier, status: "valid", errors: [], manifest };
209
+ const discovery = [...(await discoverPlugins()).filter((record) => record.id !== manifest.id), staged];
210
+ return (await listPluginConflicts(discovery, { candidateId: manifest.id })).get(manifest.id) ?? [];
211
+ }
212
+ /** Enable-time conflict gate (2026-10-04): runs before `loadPlugin()`, so a plugin that would
213
+ * take a name core or an enabled plugin holds never has its code imported. The candidate is
214
+ * ordered after every enabled plugin — it is the newer one by definition. */
215
+ async function assertNoConflicts(pluginId, discovery) {
216
+ const conflicts = (await listPluginConflicts(discovery, { candidateId: pluginId })).get(pluginId);
217
+ if (conflicts)
218
+ throw new PluginConflictError({ pluginId, conflicts });
219
+ }
220
+ async function onPluginEnabled(pluginId) {
221
+ // A package replacement and an enable cannot race: save-before-callback activation is
222
+ // compensated if install owns the directory lock, while installs refuse an enabled row.
223
+ if (installDir !== undefined)
224
+ await assertPluginInstallIdle({ installDir });
225
+ const discovery = await discoverActivePlugins();
226
+ const record = discovery.find((candidate) => candidate.id === pluginId);
227
+ if (!record) {
228
+ throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
229
+ }
230
+ await assertNoConflicts(pluginId, discovery);
231
+ // Provider plugins initialize once, at boot, before application work (`loadProviderPlugins`).
232
+ if (declaresProviders({ manifest: record.manifest }))
233
+ return undefined;
234
+ // No manifest ⇒ an invalid record: `attachPlugin`'s own fail-closed path reports it.
235
+ if (!record.manifest)
236
+ return attachPlugin(pluginId, record);
237
+ // Declared contributions (AW-7 Tier 1) are applied only now, after the conflict gate; a tier-1
238
+ // plugin's `loadCode` is never called.
239
+ await enableDeclaredPlugin({ ...runtimeBinding, pluginId, workspaceId: required.workspaceId, manifest: record.manifest, loadCode: () => attachPlugin(pluginId, record), unloadCode: () => onPluginDisabled(pluginId) }, optional.declaredContentTypes ? { contentTypes: optional.declaredContentTypes } : {});
240
+ loadedVersions.set(pluginId, record.version);
241
+ return undefined;
242
+ }
243
+ /** Load + attach one already-cleared plugin — `onPluginEnabled`'s body after its gates, shared
244
+ * with boot, which clears every enabled plugin in ONE pass instead (see
245
+ * `attachEnabledPluginsAtBoot`: per-plugin "candidate last" ordering would refuse the older
246
+ * winner of a boot-time pair as well as the newer one). */
247
+ function attachPlugin(pluginId, record) {
248
+ if (closing)
249
+ return Promise.reject(new PluginSnapshotLifecycleError({ code: "SNAPSHOTS_CLOSED" }));
250
+ const attachment = performPluginAttachment(pluginId, record);
251
+ pendingAttachments.add(attachment);
252
+ void attachment.then(() => pendingAttachments.delete(attachment), () => pendingAttachments.delete(attachment));
253
+ return attachment;
254
+ }
255
+ /** Keep import and setup in the same shutdown drain: setup may make late graph imports too. */
256
+ async function performPluginAttachment(pluginId, record) {
257
+ const epoch = (loadEpochs.get(pluginId) ?? 0) + 1;
258
+ loadEpochs.set(pluginId, epoch);
259
+ const target = resolveLoadTarget({ pluginId, sources, record, installDir });
260
+ if (!target) {
261
+ throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
262
+ }
263
+ const { manifest, entryPath, attachmentSource } = target;
264
+ // The SDK backing (content.read/extend bound to the running filter, single declared beforeSave
265
+ // filter) is shared with the Tier-2 worker — see `invocation-core-deps.ts`.
266
+ const invocation = runtimeBinding.createInvocationCoreDeps({ pluginId, declaredHooks: manifest.hooks });
267
+ const capture = createPluginContributionCapture({ manifest });
268
+ let scopedSdk;
269
+ const coreDeps = { ...invocation.coreDeps, contributions: capture };
270
+ // CIC U-001: the importer FACTORY runs here, before loadPlugin's integrity/sdkRange checks, so
271
+ // it must stay inert; loadPlugin invokes the returned importer only after those checks. A site
272
+ // target takes the contained immutable snapshot; built-in seams retain their original path.
273
+ const moduleImporter = resolveRuntimeImporter({ target, record });
274
+ const result = await loadPlugin({ ...runtimeBinding, record, manifest, entryPath, coreDeps, importModule: moduleImporter,
275
+ browserProviderApprovals: optional.browserProviderApprovals ?? [],
276
+ providerContributions: { registry: providerContributions, isSelected: ({ pluginId: id }) => selectedProviders.has(id) },
277
+ pluginSdkBinding: { ...runtimeBinding.pluginSdkBinding,
278
+ buildSdk: ({ sdk }) => {
279
+ const host = optional.lookup?.();
280
+ scopedSdk = { ...runtimeBinding.pluginSdkBinding.buildSdk({ sdk }),
281
+ ...(host ? { plugins: createPluginLookupFacade({ lookup: host }) } : {}),
282
+ };
283
+ return scopedSdk;
284
+ },
285
+ },
286
+ }, {});
287
+ if (!result.loaded) {
288
+ throw new PluginLoadError(pluginId, result.reason);
289
+ }
290
+ // A disable or a newer load during import/setup must not resurrect the retired generation.
291
+ if (loadEpochs.get(pluginId) !== epoch || !scopedSdk)
292
+ throw new PluginLoadError(pluginId, 'PLUGIN_SETUP_FAILED');
293
+ const contributions = capture.seal({ sdk: scopedSdk });
294
+ const filter = invocation.capturedFilter();
295
+ if (manifest.hooks.includes(required.pluginSdkBinding.beforeSaveHook) && filter === null) {
296
+ throw new PluginLoadError(pluginId, "PLUGIN_HOOK_NOT_ATTACHED");
297
+ }
298
+ publishPluginAttachment({ pluginId, manifest, attachmentSource, filter, contributions,
299
+ providers: result.browserProviders ?? [], version: record.version });
300
+ }
301
+ function resolveRuntimeImporter({ target, record }, _options = {}) {
302
+ // Tier 2 (ADR-024 §3/§4): the plugin's code must never be imported into this process. Its
303
+ // import seam probes it in a fresh worker and hands `loadPlugin()` a proxy whose filter is an
304
+ // RPC; supplied as `loadPlugin()`'s required `importModule` port, so integrity + sdkRange
305
+ // still run first (CIC U-001). Only a built-in reaches here as tier-2: discovery marks a site
306
+ // tier-2 package invalid (the worker is no sandbox yet). Were site tier-2 ever allowed, its worker
307
+ // would need the seam's `resolveWorkerEntry` pointed at the integrity-checked module snapshot,
308
+ // since an injected worker seam bypasses the host's default snapshot importer.
309
+ return target.manifest.tier === "tier-2"
310
+ ? createTier2ImportSeam({ ...runtimeBinding, manifest: target.manifest, runCall: tier2CallRunner })
311
+ : required.createModuleImporter({ manifest: target.manifest, source: record.source }, {
312
+ ...(target.importModule === undefined ? {} : { importModule: target.importModule }),
313
+ ...(snapshots === undefined ? {} : { snapshots }),
314
+ });
315
+ }
316
+ function publishPluginAttachment({ pluginId, manifest, attachmentSource, filter, contributions, providers, version }, _options = {}) {
317
+ if (filter === null) {
318
+ pluginContributions.replace({ contributions });
319
+ retainBrowserProviders({ pluginId, providers });
320
+ hookRegistry.detach({ pluginId });
321
+ loadedVersions.set(pluginId, version);
322
+ return;
323
+ }
324
+ try {
325
+ attachLoadedPlugin({
326
+ pluginId,
327
+ source: attachmentSource,
328
+ hookRegistry,
329
+ filter,
330
+ declaredFields: manifest.fields,
331
+ });
332
+ pluginContributions.replace({ contributions });
333
+ retainBrowserProviders({ pluginId, providers });
334
+ loadedVersions.set(pluginId, version);
335
+ }
336
+ catch (error) {
337
+ hookRegistry.detach({ pluginId });
338
+ throw new PluginLoadError(pluginId, "PLUGIN_HOOK_ATTACH_FAILED", { cause: error });
339
+ }
340
+ }
341
+ /** Publish admission only after successful attachment; no partial setup can leak assets.
342
+ * @complexity O(1) map replacement; Jini already owns the immutable asset bytes.
343
+ */
344
+ function retainBrowserProviders({ pluginId, providers }) {
345
+ if (providers.length === 0 && !browserProviders.has(pluginId))
346
+ return;
347
+ browserProviders.set(pluginId, providers);
348
+ browserGeneration++;
349
+ }
350
+ function onPluginDisabled(pluginId) {
351
+ if (browserProviders.delete(pluginId))
352
+ browserGeneration++;
353
+ loadEpochs.set(pluginId, (loadEpochs.get(pluginId) ?? 0) + 1);
354
+ pluginContributions.detach({ pluginId });
355
+ // Retires the provider generation: the provider host disposes its initialized resources.
356
+ selectedProviders.delete(pluginId);
357
+ providerContributions.detach({ pluginId });
358
+ hookRegistry.detach({ pluginId });
359
+ loadedVersions.delete(pluginId);
360
+ }
361
+ /** Boot-time conflict pass (2026-10-04): the newer plugin of every conflicting pair is turned off
362
+ * through the same durable quarantine record hook failures use, with the clash as its reason, so
363
+ * it shows on the admin row and stays off on the next boot instead of racing the older one. */
364
+ async function quarantineConflictingAtBoot(conflicts, enabledIds) {
365
+ const quarantined = new Set();
366
+ for (const [pluginId, pluginConflicts] of conflicts) {
367
+ if (!enabledIds.has(pluginId))
368
+ continue;
369
+ const reason = describeBootConflictQuarantine({ conflicts: pluginConflicts });
370
+ await quarantinePlugin({ deps: quarantineDeps, input: { pluginId, workspaceId: required.workspaceId, consecutiveFailures: 0, reason } });
371
+ onPluginDisabled(pluginId);
372
+ // eslint-disable-next-line no-console
373
+ console.warn(`[plugin-runtime] '${pluginId}' quarantined at boot: ${reason}`);
374
+ quarantined.add(pluginId);
375
+ }
376
+ return quarantined;
377
+ }
378
+ async function initializeBootDefaults(_required, _options = {}) {
379
+ // Serialize first-boot defaults with boot attachment. Existing disabled/quarantined rows win.
380
+ const initialized = await initializeBundledPlugins({
381
+ deps: { clock, repo: activationRepo, discovery: optional.bundledEnabledIds?.length ? await discoverPlugins().catch((error) => {
382
+ console.warn("[plugin-runtime] bundled discovery failed; chart providers remain unavailable", formatErrorForLog({ error }));
383
+ return [];
384
+ }) : [], onEnabled: onPluginEnabled, onDisabled: onPluginDisabled },
385
+ input: { workspaceId: required.workspaceId, pluginIds: optional.bundledEnabledIds ?? [] },
386
+ });
387
+ for (const failure of initialized.failed)
388
+ console.warn(redactSecrets({ input: `[plugin-runtime] bundled initialization failed for '${failure.pluginId}'` }, { redactPii: false }), formatErrorForLog({ error: failure.error }));
389
+ return initialized;
390
+ }
391
+ async function attachEnabledPluginsAtBoot() {
392
+ await snapshots?.ready;
393
+ const initialized = await initializeBootDefaults({}, {});
394
+ const records = await activationRepo.listAll();
395
+ const enabledHere = records.filter((record) => record.workspaceId === required.workspaceId && record.enabled);
396
+ if (enabledHere.length === 0)
397
+ return;
398
+ let discovery;
399
+ let quarantined;
400
+ try {
401
+ discovery = await discoverActivePlugins();
402
+ quarantined = await quarantineConflictingAtBoot(await listPluginConflicts(discovery), new Set(enabledHere.map((record) => record.pluginId)));
403
+ }
404
+ catch (error) {
405
+ // Fail closed: without a finished conflict pass there is no telling which of two clashing
406
+ // plugins should run, so none is attached this boot (each would previously have failed its
407
+ // own discovery read here anyway). Logged, not thrown — same isolation as a per-plugin failure.
408
+ // eslint-disable-next-line no-console
409
+ console.warn(`[plugin-runtime] boot conflict check failed, no plugin attached: ${redactSecrets({ input: error instanceof Error ? error.message : String(error) }, { redactPii: false })}`);
410
+ for (const record of enabledHere)
411
+ onPluginDisabled(record.pluginId);
412
+ return;
413
+ }
414
+ for (const record of enabledHere) {
415
+ // The initializer already attached it.
416
+ if (quarantined.has(record.pluginId) || initialized.enabled.includes(record.pluginId))
417
+ continue;
418
+ await reattachBootPlugin({ pluginId: record.pluginId, discovery });
419
+ }
420
+ }
421
+ async function reattachBootPlugin({ pluginId, discovery }, _options = {}) {
422
+ try {
423
+ if (installDir !== undefined)
424
+ await assertPluginInstallIdle({ installDir });
425
+ const discovered = discovery.find((candidate) => candidate.id === pluginId);
426
+ if (!discovered)
427
+ throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
428
+ // A tier-1 plugin has no code to re-attach; its declared types were stored at enable.
429
+ // Provider plugins were already loaded by `loadProviderPlugins`, ahead of application work.
430
+ if (discovered.manifest?.tier === "tier-1" || declaresProviders({ manifest: discovered.manifest }))
431
+ return;
432
+ await attachPlugin(pluginId, discovered);
433
+ }
434
+ catch (error) {
435
+ // eslint-disable-next-line no-console
436
+ console.warn(`[plugin-runtime] boot re-attach failed for '${pluginId}': ${redactSecrets({ input: error instanceof Error ? error.message : String(error) }, { redactPii: false })}`);
437
+ }
438
+ }
439
+ /** Import + setup of one selected provider plugin, bounded: boot never waits on a stalled plugin. On the
440
+ * deadline the caller revokes the selection (`onPluginDisabled`), so a late setup cannot publish. */
441
+ async function attachProviderWithin({ record, timeoutMs }) {
442
+ let timer;
443
+ const deadline = new Promise((_, reject) => {
444
+ timer = setTimeout(() => reject(new Error(`provider plugin load timed out after ${timeoutMs} ms`)), timeoutMs);
445
+ });
446
+ const attached = attachPlugin(record.id, record);
447
+ // Observed even after the deadline wins, so a late failure is never an unhandled rejection.
448
+ attached.catch(() => { });
449
+ try {
450
+ await Promise.race([attached, deadline]);
451
+ }
452
+ finally {
453
+ clearTimeout(timer);
454
+ }
455
+ }
456
+ async function listProviderPlugins(_required, _options = {}) {
457
+ const enabled = new Set((await activationRepo.listAll())
458
+ .filter((row) => row.workspaceId === required.workspaceId && row.enabled).map((row) => row.pluginId));
459
+ return (await discoverActivePlugins())
460
+ .filter((record) => enabled.has(record.id) && declaresProviders({ manifest: record.manifest }))
461
+ .map((record) => ({ pluginId: record.id, providers: record.manifest.contributes.providers }));
462
+ }
463
+ async function loadProviderPlugins({ pluginIds }, options = {}) {
464
+ const wanted = new Set(pluginIds);
465
+ if (wanted.size === 0)
466
+ return [];
467
+ const enabled = new Set((await activationRepo.listAll())
468
+ .filter((row) => row.workspaceId === required.workspaceId && row.enabled).map((row) => row.pluginId));
469
+ const loaded = [];
470
+ for (const record of await discoverActivePlugins()) {
471
+ if (!wanted.has(record.id) || !enabled.has(record.id) || !declaresProviders({ manifest: record.manifest }))
472
+ continue;
473
+ selectedProviders.add(record.id);
474
+ try {
475
+ await attachProviderWithin({ record, timeoutMs: options.timeoutMs ?? 10_000 });
476
+ loaded.push(record.id);
477
+ }
478
+ catch (error) {
479
+ onPluginDisabled(record.id);
480
+ console.warn(`[plugin-runtime] provider plugin '${record.id}' failed to load; its contract stays on the noop: ${redactSecrets({ input: error instanceof Error ? error.message : String(error) }, { redactPii: false })}`);
481
+ }
482
+ }
483
+ return loaded;
484
+ }
485
+ async function locatePluginPackageDirs(pluginId) {
486
+ if (installDir === undefined) {
487
+ throw new Error(`locatePluginPackageDirs: no installDir configured for this composition root — cannot remove '${pluginId}'`);
488
+ }
489
+ if (!SAFE_PLUGIN_ID_SEGMENT.test(pluginId)) {
490
+ throw new PluginUninstallPathError(pluginId);
491
+ }
492
+ const installRoot = path.resolve(installDir);
493
+ const liveDir = path.resolve(installRoot, pluginId);
494
+ if (liveDir === installRoot || !liveDir.startsWith(installRoot + path.sep)) {
495
+ throw new PluginUninstallPathError(pluginId);
496
+ }
497
+ const parkedRoot = path.resolve(path.dirname(installRoot), `${path.basename(installRoot)}-trash`);
498
+ const parkedDir = path.resolve(parkedRoot, pluginId);
499
+ if (parkedDir === parkedRoot || !parkedDir.startsWith(parkedRoot + path.sep)) {
500
+ throw new PluginUninstallPathError(pluginId);
501
+ }
502
+ const liveNames = await lstat(liveDir).then(() => [pluginId], (error) => {
503
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
504
+ return [];
505
+ throw error;
506
+ });
507
+ return { liveParent: installRoot, liveNames, parkedDir };
508
+ }
509
+ async function readPluginPackageFiles(record) {
510
+ const location = resolvePackageLocation({ record, sources, installDir });
511
+ if (location === null)
512
+ return { files: [], truncated: false };
513
+ return readPluginPackageDirectory({ input: location });
514
+ }
515
+ const pluginInstaller = installDir === undefined ? undefined : {
516
+ preview: (input, options = {}) => previewSitePluginInstall({ ...input, deps: { ...runtimeBinding, ...options, installDir, builtInIds: sources.map((source) => source.manifest.id), builtInManifests: sources.map((source) => source.manifest), repo: activationRepo, conflicts: installPreviewConflicts } }),
517
+ install: async (input, options = {}) => {
518
+ const deps = { ...runtimeBinding, ...options, installDir, builtInIds: sources.map((source) => source.manifest.id), builtInManifests: sources.map((source) => source.manifest), repo: activationRepo, conflicts: installPreviewConflicts };
519
+ const preview = await previewSitePluginInstall({ ...input, deps });
520
+ // Admission uses this manifest's identity; publication must retain those exact bytes.
521
+ const run = () => installSitePlugin({ ...input, expectedDigest: input.expectedDigest ?? preview.digest, deps });
522
+ const host = optional.lookup?.();
523
+ if (!host)
524
+ return run();
525
+ return host.withInstallIdentity({ candidate: { id: preview.publisherId ?? `unknown/${preview.id}`, localId: preview.id, family: "site-runtime" }, run });
526
+ },
527
+ };
528
+ async function reloadActivation({ row, id, discovery }, _options = {}) {
529
+ const here = row.workspaceId === required.workspaceId;
530
+ try {
531
+ await setPluginEnabled({ deps: { clock, repo: activationRepo, discovery,
532
+ onEnabled: here ? onPluginEnabled : async () => { }, onDisabled: here ? onPluginDisabled : () => { } },
533
+ input: { workspaceId: row.workspaceId, pluginId: id, enabled: true } });
534
+ }
535
+ catch (error) {
536
+ if (here)
537
+ await restoreReloadedPlugin({ id, workspaceId: row.workspaceId });
538
+ throw error;
539
+ }
540
+ }
541
+ async function assertReloadApproved({ id, enabledCount, discovery }, _options = {}) {
542
+ // Consent gap (2026-10-12): a re-seal that widens what a running plugin can reach waits for
543
+ // the owner. Thrown here, the source service reports it as reloadError and keeps every
544
+ // retained version; the approved version keeps running until the owner re-approves it.
545
+ const next = discovery.find(record => record.id === id)?.manifest;
546
+ const added = enabledCount > 0 && next ? addedPluginCapabilities({ approved: await pluginSource?.readApproval({ id }, {}), next: pluginCapabilitySet({ manifest: next }) }) : [];
547
+ if (added.length > 0)
548
+ throw new Error(required.text.reloadApprovalRequired({ added }));
549
+ }
550
+ async function restoreReloadedPlugin({ id, workspaceId }, _options = {}) {
551
+ // setPluginEnabled already restored the old activation row. Re-enter the same loader
552
+ // to pin its retained bytes, rather than turning a working plugin off for a bad update.
553
+ try {
554
+ await onPluginEnabled(id);
555
+ }
556
+ catch (rollbackError) {
557
+ console.warn(`[plugin-runtime] Plugin '${id}' restored-version reload failed`, formatErrorForLog({ error: rollbackError }));
558
+ onPluginDisabled(id);
559
+ await quarantinePlugin({ deps: quarantineDeps, input: { pluginId: id, workspaceId, consecutiveFailures: 0, reason: required.text.restoreFailedReason } });
560
+ }
561
+ }
562
+ const pluginSource = composeSourceService({}, {});
563
+ function composeSourceService(_required, _options = {}) {
564
+ if (installDir === undefined || pluginInstaller === undefined)
565
+ return undefined;
566
+ return createPluginSourceService({
567
+ ...runtimeBinding, installDir, installer: pluginInstaller, policy: pluginSourcePolicy,
568
+ pruneVersions: ({ id }) => pruneSitePluginVersions({ id, installDir, repo: activationRepo }),
569
+ builtInIds: sources.map(source => source.manifest.id),
570
+ scaffoldEntry: required.text.scaffoldEntry,
571
+ reload: async ({ id }) => {
572
+ const enabled = (await activationRepo.listAll()).filter(row => row.pluginId === id && row.enabled);
573
+ const discovery = await discoverPlugins();
574
+ await assertReloadApproved({ id, enabledCount: enabled.length, discovery });
575
+ // Load here before publishing active pointers to other processes. Their existing poll sees
576
+ // a version change and re-enters the same validated loader, replacing module snapshots.
577
+ enabled.sort((a, b) => Number(b.workspaceId === required.workspaceId) - Number(a.workspaceId === required.workspaceId));
578
+ for (const row of enabled) {
579
+ await reloadActivation({ row, id, discovery });
580
+ }
581
+ return enabled.some(row => row.workspaceId === required.workspaceId);
582
+ },
583
+ });
584
+ }
585
+ return {
586
+ dispose: async (input, options = {}) => {
587
+ closing = true;
588
+ await Promise.allSettled([...pendingAttachments]);
589
+ await snapshots?.dispose(input, options);
590
+ },
591
+ browserProviders: () => ({ generation: browserGeneration, providers: [...browserProviders.values()].flat() }),
592
+ ...(pluginInstaller === undefined ? {} : { pluginInstaller }),
593
+ ...(pluginSource === undefined ? {} : { pluginSource }),
594
+ pluginSourcePolicy,
595
+ pluginLoadedVersion: ({ id }) => loadedVersions.get(id),
596
+ hookRegistry,
597
+ pluginContributions,
598
+ providerContributions,
599
+ loadProviderPlugins,
600
+ listProviderPlugins,
601
+ discoverPlugins,
602
+ discoverActivePlugins,
603
+ onPluginEnabled,
604
+ onPluginDisabled,
605
+ locatePluginPackageDirs,
606
+ readPluginPackageFiles,
607
+ beforeSaveHook: (entry) => hookRegistry.runBeforeSave({ entry }),
608
+ previewPluginBeforeSave: (pluginId, entry) => hookRegistry.previewBeforeSave({ pluginId, entry }),
609
+ attachEnabledPluginsAtBoot,
610
+ listPluginConflicts: () => listPluginConflicts(),
611
+ };
612
+ }
613
+ //# sourceMappingURL=runtime-core.js.map
@@ -2,10 +2,7 @@ import { type FileLockOptions } from '@jini-ai/platform/fs/file-lock';
2
2
  import type { ManifestHostPorts } from '../ports.js';
3
3
  import type { PluginSourcePolicyPort } from '../source-policy.js';
4
4
  import { type PluginInstallerPort, type PluginInstallPreview } from './install.js';
5
- export declare class PluginSourceError extends Error {
6
- readonly code: string;
7
- constructor(code: string, message: string);
8
- }
5
+ export { PluginSourceError } from '../plugin-tool-errors.js';
9
6
  export declare const PLUGIN_SOURCE_LIMITS: {
10
7
  readonly maxFileBytes: number;
11
8
  readonly maxTotalBytes: number;
@@ -102,5 +99,4 @@ export declare function createPluginSourceService(required: PluginSourceDeps, op
102
99
  temporaryDir?: string;
103
100
  lockPorts?: Pick<FileLockOptions, 'clock' | 'process' | 'hostname'>;
104
101
  }): PluginSourcePort;
105
- export {};
106
102
  //# sourceMappingURL=source-drafts.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { PluginSourceError } from '../plugin-tool-errors.js';
1
2
  /** Site-scoped source authoring. Drafts never enter discovery; publication belongs to the
2
3
  * existing installer. Node filesystem effects live here, host SDK/policy/reload stay ports. */
3
4
  import { lstat, mkdir, mkdtemp, readdir, readFile, rename, rm, writeFile, unlink } from 'node:fs/promises';
@@ -8,14 +9,7 @@ import { withFileLock, FileLockTimeoutError } from '@jini-ai/platform/fs/file-lo
8
9
  import { validateManifest, validatePluginIdFormat } from '../manifest.js';
9
10
  import { PLUGIN_MANIFEST_FILENAME as MANIFEST, LEGACY_PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES, canonicalizePluginManifest } from '../plugin-format.js';
10
11
  import { computePluginIntegrity, digestSitePluginSnapshot, snapshotSitePluginPackage } from './install.js';
11
- export class PluginSourceError extends Error {
12
- code;
13
- constructor(code, message) {
14
- super(message);
15
- this.code = code;
16
- this.name = 'PluginSourceError';
17
- }
18
- }
12
+ export { PluginSourceError } from '../plugin-tool-errors.js';
19
13
  export const PLUGIN_SOURCE_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 8 * 1024 * 1024, maxEntries: 512 };
20
14
  function fail(code, message) { throw new PluginSourceError(code, message); }
21
15
  function safeId(id) {