@jini-ai/plugins 0.7.3-next.2 → 0.7.3-next.3

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 (100) hide show
  1. package/README.md +53 -0
  2. package/dist/host/activation-polling.d.ts +67 -0
  3. package/dist/host/activation-polling.js +113 -0
  4. package/dist/host/activation.d.ts +2 -30
  5. package/dist/host/contributions.d.ts +2 -9
  6. package/dist/host/hook-refusals.d.ts +49 -0
  7. package/dist/host/hook-refusals.js +65 -0
  8. package/dist/host/index.d.ts +3 -1
  9. package/dist/host/index.js +1 -0
  10. package/dist/host/node/browser-provider-assets.d.ts +2 -1
  11. package/dist/host/node/browser-provider-assets.js +2 -2
  12. package/dist/host/node/discovery.js +4 -4
  13. package/dist/host/node/install.d.ts +6 -1
  14. package/dist/host/node/install.js +20 -18
  15. package/dist/host/node/integrity-command.d.ts +2 -1
  16. package/dist/host/node/integrity-command.js +3 -3
  17. package/dist/host/node/loader.d.ts +3 -2
  18. package/dist/host/node/loader.js +6 -6
  19. package/dist/host/node/module-snapshot.d.ts +4 -3
  20. package/dist/host/node/module-snapshot.js +5 -5
  21. package/dist/host/node/package-files.d.ts +2 -1
  22. package/dist/host/node/package-files.js +6 -6
  23. package/dist/host/node/runtime-activation.d.ts +35 -0
  24. package/dist/host/node/runtime-activation.js +188 -0
  25. package/dist/host/node/runtime-boot.d.ts +16 -0
  26. package/dist/host/node/runtime-boot.js +153 -0
  27. package/dist/host/node/runtime-conflicts.d.ts +38 -0
  28. package/dist/host/node/runtime-conflicts.js +42 -0
  29. package/dist/host/node/runtime-contracts.d.ts +4 -3
  30. package/dist/host/node/runtime-core.js +65 -465
  31. package/dist/host/node/runtime-load-target.d.ts +14 -0
  32. package/dist/host/node/runtime-load-target.js +15 -0
  33. package/dist/host/node/runtime-reload.d.ts +12 -0
  34. package/dist/host/node/runtime-reload.js +107 -0
  35. package/dist/host/node/runtime-state.d.ts +52 -0
  36. package/dist/host/node/runtime-state.js +50 -0
  37. package/dist/host/node/source-drafts.d.ts +1 -1
  38. package/dist/host/node/source-drafts.js +17 -15
  39. package/dist/host/plugin-claims.d.ts +2 -9
  40. package/dist/host/plugin-format.d.ts +5 -5
  41. package/dist/host/plugin-format.js +9 -10
  42. package/dist/host/ports.d.ts +3 -28
  43. package/dist/host/tools/install.js +1 -1
  44. package/dist/host/uninstall.d.ts +2 -2
  45. package/dist/host/worker/import-policy.d.ts +49 -0
  46. package/dist/host/worker/import-policy.js +86 -0
  47. package/dist/host/worker/import-seam.js +21 -2
  48. package/dist/host/worker/index.d.ts +1 -0
  49. package/dist/host/worker/index.js +1 -0
  50. package/dist/host/worker/protocol.d.ts +4 -0
  51. package/dist/host/worker/run-call.js +2 -1
  52. package/dist/host/worker/start.d.ts +18 -1
  53. package/dist/host/worker/start.js +27 -6
  54. package/dist/react/PluginProviderSettingsDialog.d.ts +144 -0
  55. package/dist/react/PluginProviderSettingsDialog.js +54 -0
  56. package/dist/react/plugin-install-port.d.ts +29 -0
  57. package/dist/react/plugin-install-port.js +15 -0
  58. package/dist/runtime/agent-tools.d.ts +174 -0
  59. package/dist/runtime/agent-tools.js +121 -0
  60. package/dist/runtime/built-ins/word-count/count-words.d.ts +21 -0
  61. package/dist/runtime/built-ins/word-count/count-words.js +48 -0
  62. package/dist/runtime/built-ins/word-count/plugin.d.ts +6 -0
  63. package/dist/runtime/built-ins/word-count/plugin.js +12 -0
  64. package/dist/runtime/capability-card.d.ts +22 -0
  65. package/dist/runtime/capability-card.js +30 -0
  66. package/dist/runtime/enable-confirmation-ui.d.ts +28 -0
  67. package/dist/runtime/enable-confirmation-ui.js +54 -0
  68. package/dist/runtime/install-consent.d.ts +12 -0
  69. package/dist/runtime/install-consent.js +27 -0
  70. package/dist/runtime/install-source.d.ts +26 -0
  71. package/dist/runtime/install-source.js +61 -0
  72. package/dist/runtime/install-tool-catalog.d.ts +9 -0
  73. package/dist/runtime/install-tool-catalog.js +25 -0
  74. package/dist/runtime/lower-tool-access.d.ts +17 -0
  75. package/dist/runtime/lower-tool-access.js +14 -0
  76. package/dist/runtime/plugin-export.d.ts +13 -0
  77. package/dist/runtime/plugin-export.js +14 -0
  78. package/dist/runtime/plugin-host-copy.d.ts +17 -0
  79. package/dist/runtime/plugin-host-copy.js +7 -0
  80. package/dist/runtime/plugin-tool-ids.d.ts +18 -0
  81. package/dist/runtime/plugin-tool-ids.js +4 -0
  82. package/dist/runtime/plugin-tool-messages.d.ts +97 -0
  83. package/dist/runtime/plugin-tool-messages.js +90 -0
  84. package/dist/runtime/sdk-resolver.d.ts +60 -0
  85. package/dist/runtime/sdk-resolver.js +97 -0
  86. package/dist/runtime/service-ports.d.ts +43 -0
  87. package/dist/runtime/service-ports.js +3 -0
  88. package/dist/runtime/source-tool-catalog.d.ts +7 -0
  89. package/dist/runtime/source-tool-catalog.js +33 -0
  90. package/dist/runtime/uninstall-confirmation-ui.d.ts +31 -0
  91. package/dist/runtime/uninstall-confirmation-ui.js +38 -0
  92. package/dist/runtime/widget-partials.d.ts +22 -0
  93. package/dist/runtime/widget-partials.js +13 -0
  94. package/dist/site/lipay/manifest.d.ts +10 -0
  95. package/dist/site/lipay/manifest.js +96 -0
  96. package/dist/site/store/manifest.d.ts +10 -0
  97. package/dist/site/store/manifest.js +37 -0
  98. package/package.json +158 -8
  99. package/dist/host/provider-config-source.d.ts +0 -47
  100. package/dist/host/provider-config-source.js +0 -2
@@ -9,28 +9,13 @@
9
9
  */
10
10
  import { lstat } from "node:fs/promises";
11
11
  import path from "node:path";
12
- import { describeErrorForLog, redactSecrets } from "@jini-ai/core";
13
- import { observed } from "@jini-ai/core/errors/idioms";
14
- import { createPluginLookupFacade } from "@jini-ai/core/plugin-directory";
15
- import { createConsoleLogger } from "@jini-ai/core/primitives";
16
- import { setPluginEnabled } from "../activation.js";
17
- import { initializeBundledPlugins } from "../bundled-initialization.js";
18
- import { createPluginContributionCapture, createPluginContributionRegistry } from "../contributions.js";
19
- import { addedPluginCapabilities, pluginCapabilitySet } from "../source-policy.js";
20
- import { enableDeclaredPlugin } from "../declarative-enable.js";
21
- import { createHookRegistry } from "../hook-registry.js";
22
- import { quarantinePlugin } from "../quarantine.js";
23
- import { describeBootConflictQuarantine, PluginConflictError, resolvePluginConflicts } from "../plugin-claims.js";
24
- import { attachLoadedPlugin } from "../attach-loaded-plugin.js";
25
- import { assertPluginInstallIdle, installSitePlugin, previewSitePluginInstall, pruneSitePluginVersions } from "./install.js";
26
- import { createPluginModuleSnapshotLifecycle, PluginSnapshotLifecycleError } from "./module-snapshot.js";
27
- import { createPluginSourceService } from "./source-drafts.js";
28
- import { discoverPlugins as discoverPluginRuntimePlugins } from "./discovery.js";
29
12
  import { readPluginPackageFiles as readPluginPackageDirectory } from "./package-files.js";
30
- import { loadPlugin, PluginLoadError } from "./loader.js";
31
- import { createTier2ImportSeam } from "../worker/import-seam.js";
32
- import { resolveLoadTarget, declaresProviders } from "./runtime-load-target.js";
33
13
  import { SAFE_PLUGIN_ID_SEGMENT, PluginUninstallPathError, resolvePackageLocation } from "./runtime-package-location.js";
14
+ import { disposeRuntime, onPluginDisabled, onPluginEnabled, quarantineHookFailure } from "./runtime-activation.js";
15
+ import { attachEnabledPluginsAtBoot, listProviderPlugins, loadProviderPlugins } from "./runtime-boot.js";
16
+ import { discoverActivePlugins, discoverPlugins, listPluginConflicts } from "./runtime-conflicts.js";
17
+ import { composeSourceService, createPluginInstaller } from "./runtime-reload.js";
18
+ import { createRuntimeState } from "./runtime-state.js";
34
19
  /**
35
20
  * The plugin-owned runtime algorithm behind the host's composition wrapper (extract-s6 L1b seam,
36
21
  * moved here in L1c). Reads no host module: every host value arrives through
@@ -60,458 +45,73 @@ import { SAFE_PLUGIN_ID_SEGMENT, PluginUninstallPathError, resolvePackageLocatio
60
45
  * @example createPluginRuntimeCore({ workspaceId, clock, activationRepo, sources, pluginSourcePolicy, tier2CallRunner, pluginSdkBinding, hostBinding, createModuleImporter, text, quarantineTelemetry }, { installDir })
61
46
  */
62
47
  export function createPluginRuntimeCore(required, optional = {}) {
63
- const { activationRepo, clock, sources } = required;
64
- const { installDir } = optional;
65
- const quarantineDeps = { clock, repo: activationRepo, onQuarantined: ({ pluginId }) => {
66
- const tracker = optional.tracker?.();
67
- if (!tracker)
68
- return undefined;
69
- const { event, options } = required.quarantineTelemetry({ pluginId });
70
- return tracker.capture(event, options);
71
- } };
72
- const runtimeBinding = { ...required.hostBinding, pluginSdkBinding: required.pluginSdkBinding };
73
- // The install directory owns versions; its sibling runtime directory owns executable graphs.
74
- const snapshots = installDir === undefined ? undefined : createPluginModuleSnapshotLifecycle({ runtimeRoot: path.resolve(installDir) + "-runtime" });
75
- const pendingAttachments = new Set();
76
- let closing = false;
77
- const { pluginSourcePolicy } = required;
78
- const loadedVersions = new Map();
79
- const browserProviders = new Map();
80
- let browserGeneration = 0;
81
- const pluginContributions = createPluginContributionRegistry({});
82
- const providerContributions = createPluginContributionRegistry({});
83
- // Only boot's configured selection may admit provider factories (`loadProviderPlugins`).
84
- const selectedProviders = new Set();
85
- const loadEpochs = new Map();
86
- const { tier2CallRunner } = required;
87
- const hookRegistry = createHookRegistry({ pluginSdkBinding: required.pluginSdkBinding }, {
88
- ...(optional.failureThreshold === undefined ? {} : { failureThreshold: optional.failureThreshold }),
89
- onQuarantine: async (input) => {
90
- onPluginDisabled(input.pluginId);
91
- await quarantinePlugin({ deps: quarantineDeps, input });
92
- },
48
+ const state = createRuntimeState({
49
+ required, optional, onHookQuarantine: (input) => quarantineHookFailure({ state, input }),
93
50
  });
94
- // Reachability fix (previously always omitted `installDir`, so a plugin placed on disk was
95
- // never scanned no matter how the composition root itself was configured — see this function's
96
- // required-params doc).
97
- const discoverPlugins = () => discoverPluginRuntimePlugins({ ...runtimeBinding, builtIns: sources, ...(installDir === undefined ? {} : { installDir }) });
98
- /** Retained versions make the activation row's existing active pointer meaningful at boot
99
- * and reload. A newly installed version is not running until controlled reload advances it. */
100
- async function discoverActivePlugins() {
101
- const rows = await activationRepo.listAll();
102
- const versions = new Map(rows.filter(row => row.workspaceId === required.workspaceId && row.enabled).map(row => [row.pluginId, row.version]));
103
- return discoverPluginRuntimePlugins({ ...runtimeBinding, builtIns: sources, ...(installDir === undefined ? {} : { installDir }) }, { versions });
104
- }
105
- const coreClaims = optional.coreClaims ?? [];
106
- async function listPluginConflicts(discovery, optional = {}) {
107
- const [records, activations] = await Promise.all([discovery ?? discoverPlugins(), activationRepo.listAll()]);
108
- return resolvePluginConflicts({ ...runtimeBinding, workspaceId: required.workspaceId, discovery: records, activations, coreClaims }, optional);
109
- }
110
- /** Install preview (2026-10-04): what the staged package would clash with if turned on in THIS
111
- * workspace now. A synthetic valid record stands in for it and REPLACES an installed version of the
112
- * same id, so an upgrade is judged by its new manifest only. */
113
- async function installPreviewConflicts(required) {
114
- const { manifest } = required;
115
- const staged = { id: manifest.id, name: manifest.name, version: manifest.version, source: "site", tier: manifest.tier, status: "valid", errors: [], manifest };
116
- const discovery = [...(await discoverPlugins()).filter((record) => record.id !== manifest.id), staged];
117
- return (await listPluginConflicts(discovery, { candidateId: manifest.id })).get(manifest.id) ?? [];
118
- }
119
- /** Enable-time conflict gate (2026-10-04): runs before `loadPlugin()`, so a plugin that would
120
- * take a name core or an enabled plugin holds never has its code imported. The candidate is
121
- * ordered after every enabled plugin — it is the newer one by definition. */
122
- async function assertNoConflicts(pluginId, discovery) {
123
- const conflicts = (await listPluginConflicts(discovery, { candidateId: pluginId })).get(pluginId);
124
- if (conflicts)
125
- throw new PluginConflictError({ pluginId, conflicts });
126
- }
127
- async function onPluginEnabled(pluginId) {
128
- // A package replacement and an enable cannot race: save-before-callback activation is
129
- // compensated if install owns the directory lock, while installs refuse an enabled row.
130
- if (installDir !== undefined)
131
- await assertPluginInstallIdle({ installDir });
132
- const discovery = await discoverActivePlugins();
133
- const record = discovery.find((candidate) => candidate.id === pluginId);
134
- if (!record) {
135
- throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
136
- }
137
- await assertNoConflicts(pluginId, discovery);
138
- // Provider plugins initialize once, at boot, before application work (`loadProviderPlugins`).
139
- if (declaresProviders({ manifest: record.manifest }))
140
- return undefined;
141
- // No manifest ⇒ an invalid record: `attachPlugin`'s own fail-closed path reports it.
142
- if (!record.manifest)
143
- return attachPlugin(pluginId, record);
144
- // Declared contributions (AW-7 Tier 1) are applied only now, after the conflict gate; a tier-1
145
- // plugin's `loadCode` is never called.
146
- await enableDeclaredPlugin({ ...runtimeBinding, pluginId, workspaceId: required.workspaceId, manifest: record.manifest, loadCode: () => attachPlugin(pluginId, record), unloadCode: () => onPluginDisabled(pluginId) }, optional.declaredContentTypes ? { contentTypes: optional.declaredContentTypes } : {});
147
- loadedVersions.set(pluginId, record.version);
148
- return undefined;
149
- }
150
- /** Load + attach one already-cleared plugin — `onPluginEnabled`'s body after its gates, shared
151
- * with boot, which clears every enabled plugin in ONE pass instead (see
152
- * `attachEnabledPluginsAtBoot`: per-plugin "candidate last" ordering would refuse the older
153
- * winner of a boot-time pair as well as the newer one). */
154
- function attachPlugin(pluginId, record) {
155
- if (closing)
156
- return Promise.reject(new PluginSnapshotLifecycleError({ code: "SNAPSHOTS_CLOSED" }));
157
- const attachment = performPluginAttachment(pluginId, record);
158
- pendingAttachments.add(attachment);
159
- void attachment.then(() => pendingAttachments.delete(attachment), () => pendingAttachments.delete(attachment));
160
- return attachment;
161
- }
162
- /** Keep import and setup in the same shutdown drain: setup may make late graph imports too. */
163
- async function performPluginAttachment(pluginId, record) {
164
- const epoch = (loadEpochs.get(pluginId) ?? 0) + 1;
165
- loadEpochs.set(pluginId, epoch);
166
- const target = resolveLoadTarget({ pluginId, sources, record, installDir });
167
- if (!target) {
168
- throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
169
- }
170
- const { manifest, entryPath, attachmentSource } = target;
171
- // The SDK backing (content.read/extend bound to the running filter, single declared beforeSave
172
- // filter) is shared with the Tier-2 worker — see `invocation-core-deps.ts`.
173
- const invocation = runtimeBinding.createInvocationCoreDeps({ pluginId, declaredHooks: manifest.hooks });
174
- const capture = createPluginContributionCapture({ manifest });
175
- let scopedSdk;
176
- const coreDeps = { ...invocation.coreDeps, contributions: capture };
177
- // The importer FACTORY runs here, before loadPlugin's integrity/sdkRange checks, so
178
- // it must stay inert; loadPlugin invokes the returned importer only after those checks. A site
179
- // target takes the contained immutable snapshot; built-in seams retain their original path.
180
- const moduleImporter = resolveRuntimeImporter({ target, record });
181
- const result = await loadPlugin({ ...runtimeBinding, record, manifest, entryPath, coreDeps, importModule: moduleImporter,
182
- browserProviderApprovals: optional.browserProviderApprovals ?? [],
183
- providerContributions: { registry: providerContributions, isSelected: ({ pluginId: id }) => selectedProviders.has(id) },
184
- pluginSdkBinding: { ...runtimeBinding.pluginSdkBinding,
185
- buildSdk: ({ sdk }) => {
186
- const host = optional.lookup?.();
187
- scopedSdk = { ...runtimeBinding.pluginSdkBinding.buildSdk({ sdk }),
188
- ...(host ? { plugins: createPluginLookupFacade({ lookup: host }) } : {}),
189
- };
190
- return scopedSdk;
191
- },
192
- },
193
- }, {});
194
- if (!result.loaded) {
195
- throw new PluginLoadError(pluginId, result.reason);
196
- }
197
- // A disable or a newer load during import/setup must not resurrect the retired generation.
198
- if (loadEpochs.get(pluginId) !== epoch || !scopedSdk)
199
- throw new PluginLoadError(pluginId, 'PLUGIN_SETUP_FAILED');
200
- const contributions = capture.seal({ sdk: scopedSdk });
201
- const filter = invocation.capturedFilter();
202
- if (manifest.hooks.includes(required.pluginSdkBinding.beforeSaveHook) && filter === null) {
203
- throw new PluginLoadError(pluginId, "PLUGIN_HOOK_NOT_ATTACHED");
204
- }
205
- publishPluginAttachment({ pluginId, manifest, attachmentSource, filter, contributions,
206
- providers: result.browserProviders ?? [], version: record.version });
207
- }
208
- function resolveRuntimeImporter({ target, record }, _options = {}) {
209
- // Tier 2: the plugin's code must never be imported into this process. Its
210
- // import seam probes it in a fresh worker and hands `loadPlugin()` a proxy whose filter is an
211
- // RPC; supplied as `loadPlugin()`'s required `importModule` port, so integrity + sdkRange
212
- // still run first. Only a built-in reaches here as tier-2: discovery marks a site
213
- // tier-2 package invalid (the worker is no sandbox yet). Were site tier-2 ever allowed, its worker
214
- // would need the seam's `resolveWorkerEntry` pointed at the integrity-checked module snapshot,
215
- // since an injected worker seam bypasses the host's default snapshot importer.
216
- return target.manifest.tier === "tier-2"
217
- ? createTier2ImportSeam({ ...runtimeBinding, manifest: target.manifest, runCall: tier2CallRunner })
218
- : required.createModuleImporter({ manifest: target.manifest, source: record.source }, {
219
- ...(target.importModule === undefined ? {} : { importModule: target.importModule }),
220
- ...(snapshots === undefined ? {} : { snapshots }),
221
- });
222
- }
223
- function publishPluginAttachment({ pluginId, manifest, attachmentSource, filter, contributions, providers, version }, _options = {}) {
224
- if (filter === null) {
225
- pluginContributions.replace({ contributions });
226
- retainBrowserProviders({ pluginId, providers });
227
- hookRegistry.detach({ pluginId });
228
- loadedVersions.set(pluginId, version);
229
- return;
230
- }
231
- try {
232
- attachLoadedPlugin({
233
- pluginId,
234
- source: attachmentSource,
235
- hookRegistry,
236
- filter,
237
- declaredFields: manifest.fields,
238
- });
239
- pluginContributions.replace({ contributions });
240
- retainBrowserProviders({ pluginId, providers });
241
- loadedVersions.set(pluginId, version);
242
- }
243
- catch (error) {
244
- hookRegistry.detach({ pluginId });
245
- throw new PluginLoadError(pluginId, "PLUGIN_HOOK_ATTACH_FAILED", { cause: error });
246
- }
247
- }
248
- /** Publish admission only after successful attachment; no partial setup can leak assets.
249
- * @complexity O(1) map replacement; Jini already owns the immutable asset bytes.
250
- */
251
- function retainBrowserProviders({ pluginId, providers }) {
252
- if (providers.length === 0 && !browserProviders.has(pluginId))
253
- return;
254
- browserProviders.set(pluginId, providers);
255
- browserGeneration++;
256
- }
257
- function onPluginDisabled(pluginId) {
258
- if (browserProviders.delete(pluginId))
259
- browserGeneration++;
260
- loadEpochs.set(pluginId, (loadEpochs.get(pluginId) ?? 0) + 1);
261
- pluginContributions.detach({ pluginId });
262
- // Retires the provider generation: the provider host disposes its initialized resources.
263
- selectedProviders.delete(pluginId);
264
- providerContributions.detach({ pluginId });
265
- hookRegistry.detach({ pluginId });
266
- loadedVersions.delete(pluginId);
267
- }
268
- /** Boot-time conflict pass (2026-10-04): the newer plugin of every conflicting pair is turned off
269
- * through the same durable quarantine record hook failures use, with the clash as its reason, so
270
- * it shows on the admin row and stays off on the next boot instead of racing the older one. */
271
- async function quarantineConflictingAtBoot(conflicts, enabledIds) {
272
- const quarantined = new Set();
273
- for (const [pluginId, pluginConflicts] of conflicts) {
274
- if (!enabledIds.has(pluginId))
275
- continue;
276
- const reason = describeBootConflictQuarantine({ conflicts: pluginConflicts });
277
- await quarantinePlugin({ deps: quarantineDeps, input: { pluginId, workspaceId: required.workspaceId, consecutiveFailures: 0, reason } });
278
- onPluginDisabled(pluginId);
279
- createConsoleLogger({ prefix: '' }).warn({ message: `[plugin-runtime] '${pluginId}' quarantined at boot: ${reason}` });
280
- quarantined.add(pluginId);
281
- }
282
- return quarantined;
283
- }
284
- async function initializeBootDefaults(_required, _options = {}) {
285
- // Serialize first-boot defaults with boot attachment. Existing disabled/quarantined rows win.
286
- const initialized = await initializeBundledPlugins({
287
- deps: { clock, repo: activationRepo, discovery: optional.bundledEnabledIds?.length ? await discoverPlugins().catch((error) => {
288
- console.warn("[plugin-runtime] bundled discovery failed; chart providers remain unavailable", describeErrorForLog({ err: error }));
289
- return [];
290
- }) : [], onEnabled: onPluginEnabled, onDisabled: onPluginDisabled },
291
- input: { workspaceId: required.workspaceId, pluginIds: optional.bundledEnabledIds ?? [] },
292
- });
293
- for (const failure of initialized.failed)
294
- console.warn(redactSecrets({ input: `[plugin-runtime] bundled initialization failed for '${failure.pluginId}'` }, { redactPii: false }), describeErrorForLog({ err: failure.error }));
295
- return initialized;
296
- }
297
- async function attachEnabledPluginsAtBoot() {
298
- await snapshots?.ready;
299
- const initialized = await initializeBootDefaults({}, {});
300
- const records = await activationRepo.listAll();
301
- const enabledHere = records.filter((record) => record.workspaceId === required.workspaceId && record.enabled);
302
- if (enabledHere.length === 0)
303
- return;
304
- let discovery;
305
- let quarantined;
306
- try {
307
- discovery = await discoverActivePlugins();
308
- quarantined = await quarantineConflictingAtBoot(await listPluginConflicts(discovery), new Set(enabledHere.map((record) => record.pluginId)));
309
- }
310
- catch (error) {
311
- // Fail closed: without a finished conflict pass there is no telling which of two clashing
312
- // plugins should run, so none is attached this boot (each would previously have failed its
313
- // own discovery read here anyway). Logged, not thrown — same isolation as a per-plugin failure.
314
- createConsoleLogger({ prefix: '' }).warn({ message: '[plugin-runtime] boot conflict check failed, no plugin attached' }, { error });
315
- for (const record of enabledHere)
316
- onPluginDisabled(record.pluginId);
317
- return;
318
- }
319
- for (const record of enabledHere) {
320
- // The initializer already attached it.
321
- if (quarantined.has(record.pluginId) || initialized.enabled.includes(record.pluginId))
322
- continue;
323
- await reattachBootPlugin({ pluginId: record.pluginId, discovery });
324
- }
325
- }
326
- async function reattachBootPlugin({ pluginId, discovery }, _options = {}) {
327
- try {
328
- if (installDir !== undefined)
329
- await assertPluginInstallIdle({ installDir });
330
- const discovered = discovery.find((candidate) => candidate.id === pluginId);
331
- if (!discovered)
332
- throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
333
- // A tier-1 plugin has no code to re-attach; its declared types were stored at enable.
334
- // Provider plugins were already loaded by `loadProviderPlugins`, ahead of application work.
335
- if (discovered.manifest?.tier === "tier-1" || declaresProviders({ manifest: discovered.manifest }))
336
- return;
337
- await attachPlugin(pluginId, discovered);
338
- }
339
- catch (error) {
340
- createConsoleLogger({ prefix: '' }).warn({ message: `[plugin-runtime] boot re-attach failed for '${pluginId}'` }, { error });
341
- }
342
- }
343
- /** Import + setup of one selected provider plugin, bounded: boot never waits on a stalled plugin. On the
344
- * deadline the caller revokes the selection (`onPluginDisabled`), so a late setup cannot publish. */
345
- async function attachProviderWithin({ record, timeoutMs }) {
346
- let timer;
347
- const deadline = new Promise((_, reject) => {
348
- timer = setTimeout(() => reject(new Error(`provider plugin load timed out after ${timeoutMs} ms`)), timeoutMs);
349
- });
350
- const attached = attachPlugin(record.id, record);
351
- // Observed even after the deadline wins, so a late failure is never an unhandled rejection.
352
- observed({ promise: attached });
353
- try {
354
- await Promise.race([attached, deadline]);
355
- }
356
- finally {
357
- clearTimeout(timer);
358
- }
359
- }
360
- async function listProviderPlugins(_required, _options = {}) {
361
- const enabled = new Set((await activationRepo.listAll())
362
- .filter((row) => row.workspaceId === required.workspaceId && row.enabled).map((row) => row.pluginId));
363
- return (await discoverActivePlugins())
364
- .filter((record) => enabled.has(record.id) && declaresProviders({ manifest: record.manifest }))
365
- .map((record) => ({ pluginId: record.id, providers: record.manifest.contributes.providers }));
366
- }
367
- async function loadProviderPlugins({ pluginIds }, options = {}) {
368
- const wanted = new Set(pluginIds);
369
- if (wanted.size === 0)
370
- return [];
371
- const enabled = new Set((await activationRepo.listAll())
372
- .filter((row) => row.workspaceId === required.workspaceId && row.enabled).map((row) => row.pluginId));
373
- const loaded = [];
374
- for (const record of await discoverActivePlugins()) {
375
- if (!wanted.has(record.id) || !enabled.has(record.id) || !declaresProviders({ manifest: record.manifest }))
376
- continue;
377
- selectedProviders.add(record.id);
378
- try {
379
- await attachProviderWithin({ record, timeoutMs: options.timeoutMs ?? 10_000 });
380
- loaded.push(record.id);
381
- }
382
- catch (error) {
383
- onPluginDisabled(record.id);
384
- console.warn(`[plugin-runtime] provider plugin '${record.id}' failed to load; its contract stays on the noop: ${describeErrorForLog({ err: error })}`);
385
- }
386
- }
387
- return loaded;
388
- }
389
- async function locatePluginPackageDirs(pluginId) {
390
- if (installDir === undefined) {
391
- throw new Error(`locatePluginPackageDirs: no installDir configured for this composition root — cannot remove '${pluginId}'`);
392
- }
393
- if (!SAFE_PLUGIN_ID_SEGMENT.test(pluginId)) {
394
- throw new PluginUninstallPathError(pluginId);
395
- }
396
- const installRoot = path.resolve(installDir);
397
- const liveDir = path.resolve(installRoot, pluginId);
398
- if (liveDir === installRoot || !liveDir.startsWith(installRoot + path.sep)) {
399
- throw new PluginUninstallPathError(pluginId);
400
- }
401
- const parkedRoot = path.resolve(path.dirname(installRoot), `${path.basename(installRoot)}-trash`);
402
- const parkedDir = path.resolve(parkedRoot, pluginId);
403
- if (parkedDir === parkedRoot || !parkedDir.startsWith(parkedRoot + path.sep)) {
404
- throw new PluginUninstallPathError(pluginId);
405
- }
406
- const liveNames = await lstat(liveDir).then(() => [pluginId], (error) => {
407
- if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
408
- return [];
409
- throw error;
410
- });
411
- return { liveParent: installRoot, liveNames, parkedDir };
412
- }
413
- async function readPluginPackageFiles(record) {
414
- const location = resolvePackageLocation({ record, sources, installDir });
415
- if (location === null)
416
- return { files: [], truncated: false };
417
- return readPluginPackageDirectory({ input: location });
418
- }
419
- const pluginInstaller = installDir === undefined ? undefined : {
420
- 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 } }),
421
- install: async (input, options = {}) => {
422
- const deps = { ...runtimeBinding, ...options, installDir, builtInIds: sources.map((source) => source.manifest.id), builtInManifests: sources.map((source) => source.manifest), repo: activationRepo, conflicts: installPreviewConflicts };
423
- const preview = await previewSitePluginInstall({ ...input, deps });
424
- // Admission uses this manifest's identity; publication must retain those exact bytes.
425
- const run = () => installSitePlugin({ ...input, expectedDigest: input.expectedDigest ?? preview.digest, deps });
426
- const host = optional.lookup?.();
427
- if (!host)
428
- return run();
429
- return host.withInstallIdentity({ candidate: { id: preview.publisherId ?? `unknown/${preview.id}`, localId: preview.id, family: "site-runtime" }, run });
430
- },
431
- };
432
- async function reloadActivation({ row, id, discovery }, _options = {}) {
433
- const here = row.workspaceId === required.workspaceId;
434
- try {
435
- await setPluginEnabled({ deps: { clock, repo: activationRepo, discovery,
436
- onEnabled: here ? onPluginEnabled : async () => { }, onDisabled: here ? onPluginDisabled : () => { } },
437
- input: { workspaceId: row.workspaceId, pluginId: id, enabled: true } });
438
- }
439
- catch (error) {
440
- if (here)
441
- await restoreReloadedPlugin({ id, workspaceId: row.workspaceId });
442
- throw error;
443
- }
444
- }
445
- async function assertReloadApproved({ id, enabledCount, discovery }, _options = {}) {
446
- // Consent gap (2026-10-12): a re-seal that widens what a running plugin can reach waits for
447
- // the owner. Thrown here, the source service reports it as reloadError and keeps every
448
- // retained version; the approved version keeps running until the owner re-approves it.
449
- const next = discovery.find(record => record.id === id)?.manifest;
450
- const added = enabledCount > 0 && next ? addedPluginCapabilities({ approved: await pluginSource?.readApproval({ id }, {}), next: pluginCapabilitySet({ manifest: next }) }) : [];
451
- if (added.length > 0)
452
- throw new Error(required.text.reloadApprovalRequired({ added }));
453
- }
454
- async function restoreReloadedPlugin({ id, workspaceId }, _options = {}) {
455
- // setPluginEnabled already restored the old activation row. Re-enter the same loader
456
- // to pin its retained bytes, rather than turning a working plugin off for a bad update.
457
- try {
458
- await onPluginEnabled(id);
459
- }
460
- catch (rollbackError) {
461
- console.warn(`[plugin-runtime] Plugin '${id}' restored-version reload failed`, describeErrorForLog({ err: rollbackError }));
462
- onPluginDisabled(id);
463
- await quarantinePlugin({ deps: quarantineDeps, input: { pluginId: id, workspaceId, consecutiveFailures: 0, reason: required.text.restoreFailedReason } });
464
- }
465
- }
466
- const pluginSource = composeSourceService({}, {});
467
- function composeSourceService(_required, _options = {}) {
468
- if (installDir === undefined || pluginInstaller === undefined)
469
- return undefined;
470
- return createPluginSourceService({
471
- ...runtimeBinding, installDir, installer: pluginInstaller, policy: pluginSourcePolicy,
472
- pruneVersions: ({ id }) => pruneSitePluginVersions({ id, installDir, repo: activationRepo }),
473
- builtInIds: sources.map(source => source.manifest.id),
474
- scaffoldEntry: required.text.scaffoldEntry,
475
- reload: async ({ id }) => {
476
- const enabled = (await activationRepo.listAll()).filter(row => row.pluginId === id && row.enabled);
477
- const discovery = await discoverPlugins();
478
- await assertReloadApproved({ id, enabledCount: enabled.length, discovery });
479
- // Load here before publishing active pointers to other processes. Their existing poll sees
480
- // a version change and re-enters the same validated loader, replacing module snapshots.
481
- enabled.sort((a, b) => Number(b.workspaceId === required.workspaceId) - Number(a.workspaceId === required.workspaceId));
482
- for (const row of enabled) {
483
- await reloadActivation({ row, id, discovery });
484
- }
485
- return enabled.some(row => row.workspaceId === required.workspaceId);
486
- },
487
- });
488
- }
51
+ const pluginInstaller = createPluginInstaller({ state });
52
+ const pluginSource = composeSourceService({ state, pluginInstaller });
53
+ return bindRuntime({ state, pluginInstaller, pluginSource });
54
+ }
55
+ /** The public bindings: each phase helper partially applied to the one shared state. */
56
+ function bindRuntime({ state, pluginInstaller, pluginSource }, _options = {}) {
57
+ const { hookRegistry } = state;
489
58
  return {
490
- dispose: async (input, options = {}) => {
491
- closing = true;
492
- await Promise.allSettled([...pendingAttachments]);
493
- await snapshots?.dispose(input, options);
494
- },
495
- browserProviders: () => ({ generation: browserGeneration, providers: [...browserProviders.values()].flat() }),
59
+ dispose: async (input, options = {}) => disposeRuntime({ state, input }, options),
60
+ browserProviders: () => ({ generation: state.browserGeneration, providers: [...state.browserProviders.values()].flat() }),
496
61
  ...(pluginInstaller === undefined ? {} : { pluginInstaller }),
497
62
  ...(pluginSource === undefined ? {} : { pluginSource }),
498
- pluginSourcePolicy,
499
- pluginLoadedVersion: ({ id }) => loadedVersions.get(id),
63
+ pluginSourcePolicy: state.required.pluginSourcePolicy,
64
+ pluginLoadedVersion: ({ id }) => state.loadedVersions.get(id),
500
65
  hookRegistry,
501
- pluginContributions,
502
- providerContributions,
503
- loadProviderPlugins,
504
- listProviderPlugins,
505
- discoverPlugins,
506
- discoverActivePlugins,
507
- onPluginEnabled,
508
- onPluginDisabled,
509
- locatePluginPackageDirs,
510
- readPluginPackageFiles,
66
+ pluginContributions: state.pluginContributions,
67
+ providerContributions: state.providerContributions,
68
+ loadProviderPlugins: (input, options) => loadProviderPlugins({ state, ...input }, options),
69
+ listProviderPlugins: (_required, _options) => listProviderPlugins({ state }),
70
+ discoverPlugins: () => discoverPlugins({ state }),
71
+ discoverActivePlugins: () => discoverActivePlugins({ state }),
72
+ onPluginEnabled: (pluginId) => onPluginEnabled({ state, pluginId }),
73
+ onPluginDisabled: (pluginId) => onPluginDisabled({ state, pluginId }),
74
+ locatePluginPackageDirs: (pluginId) => locatePluginPackageDirs({ installDir: state.installDir, pluginId }),
75
+ readPluginPackageFiles: (record) => readPluginPackageFiles({ state, record }),
511
76
  beforeSaveHook: (entry) => hookRegistry.runBeforeSave({ entry }),
512
77
  previewPluginBeforeSave: (pluginId, entry) => hookRegistry.previewBeforeSave({ pluginId, entry }),
513
- attachEnabledPluginsAtBoot,
514
- listPluginConflicts: () => listPluginConflicts(),
78
+ attachEnabledPluginsAtBoot: () => attachEnabledPluginsAtBoot({ state }),
79
+ listPluginConflicts: () => listPluginConflicts({ state }),
515
80
  };
516
81
  }
82
+ /** Decision: the live and parked directories for `pluginId`, both proven to stay inside their roots. */
83
+ function resolveUninstallPaths({ installDir, pluginId }, _options = {}) {
84
+ if (!SAFE_PLUGIN_ID_SEGMENT.test(pluginId)) {
85
+ throw new PluginUninstallPathError(pluginId);
86
+ }
87
+ const installRoot = path.resolve(installDir);
88
+ const liveDir = path.resolve(installRoot, pluginId);
89
+ if (liveDir === installRoot || !liveDir.startsWith(installRoot + path.sep)) {
90
+ throw new PluginUninstallPathError(pluginId);
91
+ }
92
+ const parkedRoot = path.resolve(path.dirname(installRoot), `${path.basename(installRoot)}-trash`);
93
+ const parkedDir = path.resolve(parkedRoot, pluginId);
94
+ if (parkedDir === parkedRoot || !parkedDir.startsWith(parkedRoot + path.sep)) {
95
+ throw new PluginUninstallPathError(pluginId);
96
+ }
97
+ return { installRoot, liveDir, parkedDir };
98
+ }
99
+ async function locatePluginPackageDirs({ installDir, pluginId }, _options = {}) {
100
+ if (installDir === undefined) {
101
+ throw new Error(`locatePluginPackageDirs: no installDir configured for this composition root — cannot remove '${pluginId}'`);
102
+ }
103
+ const { installRoot, liveDir, parkedDir } = resolveUninstallPaths({ installDir, pluginId });
104
+ const liveNames = await lstat(liveDir).then(() => [pluginId], (error) => {
105
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT")
106
+ return [];
107
+ throw error;
108
+ });
109
+ return { liveParent: installRoot, liveNames, parkedDir };
110
+ }
111
+ async function readPluginPackageFiles({ state, record }, _options = {}) {
112
+ const location = resolvePackageLocation({ record, sources: state.required.sources, installDir: state.installDir });
113
+ if (location === null)
114
+ return { files: [], truncated: false };
115
+ return readPluginPackageDirectory({ input: location });
116
+ }
517
117
  //# sourceMappingURL=runtime-core.js.map
@@ -2,6 +2,7 @@ import type { PluginManifest } from "../manifest-types.js";
2
2
  import type { PluginDiscoveryRecord } from "../discovery-types.js";
3
3
  import type { AttachmentSource } from "../hook-registry.js";
4
4
  import type { PluginRuntimeSource } from "./runtime-contracts.js";
5
+ import type { PluginModuleImportPort } from "../ports.js";
5
6
  /** What `loadPlugin()` and `attachLoadedPlugin()` need for one enable attempt, resolved by
6
7
  * {@link resolveLoadTarget}. `importModule` is omitted (not `undefined`-valued) for a site target
7
8
  * so the host binding supplies the contained snapshot importer; only a built-in target carries
@@ -11,6 +12,9 @@ export interface PluginLoadTarget {
11
12
  readonly entryPath: string;
12
13
  readonly attachmentSource: AttachmentSource;
13
14
  readonly importModule?: (entryPath: string) => Promise<unknown>;
15
+ /** A built-in's declared `sourceDir`: its registered package root for the Tier-2 worker's import
16
+ * policy. Omitted ⇒ the loader's root derived from the entry's `<root>/server/index.mjs` layout. */
17
+ readonly packageRoot?: string;
14
18
  }
15
19
  /**
16
20
  * Resolves ONE enable attempt's load target (Milestone 1b, 2026-08-20): a compiled-in built-in
@@ -41,4 +45,14 @@ export declare function resolveLoadTarget(params: {
41
45
  export declare function declaresProviders({ manifest }: {
42
46
  manifest: PluginManifest | undefined;
43
47
  }): boolean;
48
+ /**
49
+ * The importer with the target's registered package root in place of the loader's layout-derived
50
+ * one; unchanged when the target declares none. Applied to the Tier-2 worker seam only, whose
51
+ * import policy scopes "the plugin's own files" to that root.
52
+ * @complexity O(1) per import.
53
+ */
54
+ export declare function withRegisteredPackageRoot(required: {
55
+ importModule: PluginModuleImportPort;
56
+ packageRoot: string | undefined;
57
+ }, _optional?: Record<string, never>): PluginModuleImportPort;
44
58
  //# sourceMappingURL=runtime-load-target.d.ts.map
@@ -27,6 +27,9 @@ export function resolveLoadTarget(params) {
27
27
  entryPath: builtIn.entryPath,
28
28
  attachmentSource: builtIn.source,
29
29
  importModule: builtIn.importModule,
30
+ // A built-in's entry may sit directly in its sourceDir, where the loader's layout guess would
31
+ // name the folder holding EVERY built-in as this one's package.
32
+ ...(builtIn.sourceDir === undefined ? {} : { packageRoot: builtIn.sourceDir }),
30
33
  };
31
34
  }
32
35
  if (record.source === "site" && installDir !== undefined && record.manifest !== undefined) {
@@ -42,4 +45,16 @@ export function resolveLoadTarget(params) {
42
45
  export function declaresProviders({ manifest }) {
43
46
  return (manifest?.contributes?.providers?.length ?? 0) > 0;
44
47
  }
48
+ /**
49
+ * The importer with the target's registered package root in place of the loader's layout-derived
50
+ * one; unchanged when the target declares none. Applied to the Tier-2 worker seam only, whose
51
+ * import policy scopes "the plugin's own files" to that root.
52
+ * @complexity O(1) per import.
53
+ */
54
+ export function withRegisteredPackageRoot(required, _optional = {}) {
55
+ const { importModule, packageRoot } = required;
56
+ if (packageRoot === undefined)
57
+ return importModule;
58
+ return (call) => importModule({ ...call, plugin: { ...call.plugin, packageRoot } });
59
+ }
45
60
  //# sourceMappingURL=runtime-load-target.js.map
@@ -0,0 +1,12 @@
1
+ import { type PluginInstallerPort } from "./install.js";
2
+ import { type PluginSourcePort } from "./source-drafts.js";
3
+ import type { RuntimeState } from "./runtime-state.js";
4
+ type RuntimeArgs<E, O> = {
5
+ state: RuntimeState<E, O>;
6
+ };
7
+ export declare function createPluginInstaller<E, O>({ state }: RuntimeArgs<E, O>, _options?: {}): PluginInstallerPort | undefined;
8
+ export declare function composeSourceService<E, O>({ state, pluginInstaller }: RuntimeArgs<E, O> & {
9
+ pluginInstaller: PluginInstallerPort | undefined;
10
+ }, _options?: {}): PluginSourcePort | undefined;
11
+ export {};
12
+ //# sourceMappingURL=runtime-reload.d.ts.map