@jini-ai/plugins 0.7.2 → 0.7.3-next.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 (81) hide show
  1. package/README.md +1 -1
  2. package/dist/core/manifest-keys.d.ts +8 -0
  3. package/dist/core/manifest-keys.js +16 -0
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +6 -7
  5. package/dist/glue/attachment-points/content-lifecycle.js +1 -1
  6. package/dist/glue/capability-gate.d.ts +2 -2
  7. package/dist/glue/manifest.js +2 -12
  8. package/dist/host/activation.d.ts +4 -5
  9. package/dist/host/admin-response.d.ts +2 -3
  10. package/dist/host/attach-loaded-plugin.d.ts +4 -4
  11. package/dist/host/attach-loaded-plugin.js +2 -2
  12. package/dist/host/browser-providers.d.ts +1 -1
  13. package/dist/host/capability-sdk.d.ts +8 -7
  14. package/dist/host/capability-sdk.js +39 -31
  15. package/dist/host/capability-tools.d.ts +4 -3
  16. package/dist/host/capability-tools.js +250 -238
  17. package/dist/host/contributions.d.ts +7 -66
  18. package/dist/host/contributions.js +64 -51
  19. package/dist/host/declarative-content-types.d.ts +6 -6
  20. package/dist/host/declarative-content-types.js +141 -135
  21. package/dist/host/declarative-enable.js +1 -1
  22. package/dist/host/discovery-types.d.ts +3 -3
  23. package/dist/host/hook-registry.d.ts +9 -9
  24. package/dist/host/hook-registry.js +86 -76
  25. package/dist/host/index.d.ts +1 -2
  26. package/dist/host/index.js +1 -1
  27. package/dist/host/manifest-types.d.ts +6 -59
  28. package/dist/host/manifest.d.ts +6 -5
  29. package/dist/host/manifest.js +5 -41
  30. package/dist/host/node/discovery.d.ts +1 -1
  31. package/dist/host/node/discovery.js +5 -6
  32. package/dist/host/node/index.d.ts +3 -0
  33. package/dist/host/node/index.js +2 -0
  34. package/dist/host/node/install.js +4 -4
  35. package/dist/host/node/integrity-command.d.ts +8 -0
  36. package/dist/host/node/integrity-command.js +26 -0
  37. package/dist/host/node/invocation-binding.d.ts +1 -1
  38. package/dist/host/node/invocation-binding.js +1 -1
  39. package/dist/host/node/loader.d.ts +3 -2
  40. package/dist/host/node/loader.js +12 -12
  41. package/dist/host/node/module-snapshot.d.ts +20 -0
  42. package/dist/host/node/module-snapshot.js +31 -0
  43. package/dist/host/node/open-flags.d.ts +4 -1
  44. package/dist/host/node/open-flags.js +1 -1
  45. package/dist/host/node/package-files.js +1 -1
  46. package/dist/host/node/provider-artifact.d.ts +1 -2
  47. package/dist/host/node/runtime-contracts.d.ts +238 -0
  48. package/dist/host/node/runtime-contracts.js +2 -0
  49. package/dist/host/node/runtime-core.d.ts +1 -243
  50. package/dist/host/node/runtime-core.js +18 -114
  51. package/dist/host/node/runtime-load-target.d.ts +44 -0
  52. package/dist/host/node/runtime-load-target.js +45 -0
  53. package/dist/host/node/runtime-package-location.d.ts +45 -0
  54. package/dist/host/node/runtime-package-location.js +57 -0
  55. package/dist/host/node/source-drafts.d.ts +4 -2
  56. package/dist/host/node/source-drafts.js +107 -39
  57. package/dist/host/ports.d.ts +2 -38
  58. package/dist/host/provider-contributions.d.ts +2 -14
  59. package/dist/host/provider-contributions.js +1 -1
  60. package/dist/host/provider-host.d.ts +4 -19
  61. package/dist/host/provider-host.js +83 -71
  62. package/dist/host/provider-revision-watch.d.ts +36 -0
  63. package/dist/host/provider-revision-watch.js +52 -0
  64. package/dist/host/provider-setting-required.d.ts +1 -7
  65. package/dist/host/provider-setting-required.js +1 -18
  66. package/dist/host/provider-settings-migrations.d.ts +1 -1
  67. package/dist/host/repo.memory.d.ts +1 -1
  68. package/dist/host/repo.memory.js +1 -1
  69. package/dist/host/sql/repo.d.ts +4 -3
  70. package/dist/host/sql/repo.rows.js +2 -2
  71. package/dist/host/tool-contributions.d.ts +2 -1
  72. package/dist/host/tool-contributions.js +1 -0
  73. package/dist/host/tools/install.js +1 -0
  74. package/dist/host/tools/management.js +97 -83
  75. package/dist/host/uninstall.d.ts +1 -1
  76. package/dist/host/worker/import-seam.d.ts +2 -2
  77. package/dist/host/worker/protocol.d.ts +2 -2
  78. package/dist/host/worker/run-call.d.ts +2 -1
  79. package/dist/host/worker/run-call.js +2 -2
  80. package/dist/host/worker/start.js +1 -1
  81. package/package.json +7 -17
@@ -1,246 +1,4 @@
1
- import { type PluginLookupPort } from "@jini-ai/core/plugin-directory";
2
- import type { Clock as ClockPort } from "@jini-ai/core/primitives";
3
- import { type PluginActivationRepoPort } from "../activation.js";
4
- import { type PluginContributionRegistry } from "../contributions.js";
5
- import type { AdmittedBrowserProvider } from "../browser-providers.js";
6
- import type { ArchiveReaderPort, BundledBrowserProviderApproval, DeclarativeContentTypesPort, DeclaredContentTypePorts, PluginModuleImportPort, PluginSdkBinding, PluginTierPolicy, VerifyDigestPort } from "../ports.js";
7
- import { type PluginSourcePolicyPort } from "../source-policy.js";
8
- import type { BuiltInPluginSource, PluginDiscoveryRecord } from "../discovery-types.js";
9
- import { type HookRegistry } from "../hook-registry.js";
10
- import type { PluginManifest } from "../manifest-types.js";
11
- import type { ExtensionClaim } from "../claim-conflicts.js";
12
- import { type PluginConflict } from "../plugin-claims.js";
13
- import { type PluginInstallerPort } from "./install.js";
14
- import { createPluginModuleSnapshotLifecycle } from "./module-snapshot.js";
15
- import { type PluginSourcePort } from "./source-drafts.js";
16
- import { type PluginPackageFiles } from "./package-files.js";
17
- import type { Tier2CallRunner } from "../worker/protocol.js";
18
- import type { RunTier2CallRequired } from "../worker/run-call.js";
19
- /** Executable metadata for one compiled-in plugin. Discovery consumes only `manifest`; the enable
20
- * callback consumes the import seam after integrity/sdkRange checks. Site-artifact sources can use
21
- * the same shape once their install-dir resolver is composed here.
22
- * @agent-note `importModule` is reached only through `loadPlugin()` after integrity and `sdkRange`
23
- * passed; the host owns the entry path and importer. */
24
- export interface PluginRuntimeSource extends BuiltInPluginSource {
25
- readonly source: "built-in";
26
- readonly entryPath: string;
27
- readonly importModule: (entryPath: string) => Promise<unknown>;
28
- /** The built-in's own source folder, shown read-only by the admin Plugins screen's
29
- * package-files viewer (a host route). Omitted ⇒ that viewer lists no files. */
30
- readonly sourceDir?: string;
31
- }
32
- /** Thrown when `pluginId` is not safe to use as a filesystem path segment
33
- * under `installDir` — either it fails {@link SAFE_PLUGIN_ID_SEGMENT}'s allowlist, or (defense in
34
- * depth, in case some future caller's id validation elsewhere ever drifts) the resolved absolute
35
- * path would land outside `installDir` after resolution. Deliberately fails closed on EITHER
36
- * check independently, not just the one presumed sufficient.
37
- * @agent-note Error identity: hosts re-export this ONE class (never a copy) so `instanceof` and
38
- * `name === "PluginUninstallPathError"` hold across the host's routes and tests. */
39
- export declare class PluginUninstallPathError extends Error {
40
- constructor(pluginId: string);
41
- }
42
- /** What {@link createPluginRuntimeCore} returns: one runtime's shared handles.
43
- * @agent-note Every member closes over the SAME repo, workspace, hook/contribution/provider registries
44
- * and pending-attachment set; hosts adapt members (e.g. positional SDK types) without rebuilding them. */
45
- export interface PluginRuntimeCoreBindings {
46
- /** Call after provider teardown and stopped hook users; drains copies and releases owned graphs. */
47
- readonly dispose: (required: Record<string, never>, optional?: Record<string, never>) => Promise<void>;
48
- /** Successfully attached, admitted providers only; disable/quarantine retires their assets. */
49
- readonly browserProviders: (input: Record<string, never>, options?: Record<string, never>) => {
50
- generation: number;
51
- providers: readonly AdmittedBrowserProvider[];
52
- };
53
- readonly pluginSource?: PluginSourcePort;
54
- readonly pluginSourcePolicy: PluginSourcePolicyPort;
55
- /** Actual loaded snapshot revision, used by the existing cross-process activation poll. */
56
- readonly pluginLoadedVersion: (required: {
57
- id: string;
58
- }, optional?: Record<string, never>) => string | undefined;
59
- readonly pluginInstaller?: PluginInstallerPort;
60
- readonly hookRegistry: HookRegistry;
61
- readonly pluginContributions: PluginContributionRegistry;
62
- /** Provider factories of admitted provider plugins only (`createPluginProviderHost` reads this).
63
- * Separate from `pluginContributions`, whose route/tool/widget snapshots carry no providers. */
64
- readonly providerContributions: PluginContributionRegistry;
65
- /**
66
- * Boot-only: loads the given provider plugins when each is installed and enabled here, admitting
67
- * their factories into `providerContributions`. Provider plugins are loaded nowhere else (boot
68
- * re-attach and enable skip them), so a running provider is never replaced mid-process; enabling
69
- * one takes effect at the next boot, disabling or quarantining one retires it immediately.
70
- * @returns The ids actually loaded. Per-plugin failures are logged and skipped, never thrown.
71
- */
72
- readonly loadProviderPlugins: (required: {
73
- pluginIds: readonly string[];
74
- }, optional?: {
75
- timeoutMs?: number;
76
- }) => Promise<readonly string[]>;
77
- /** Installed + enabled plugins here that declare providers, with their declarations (manifest only). */
78
- readonly listProviderPlugins: (required: Record<string, never>, optional?: Record<string, never>) => Promise<readonly {
79
- pluginId: string;
80
- providers: NonNullable<NonNullable<PluginManifest["contributes"]>["providers"]>;
81
- }[]>;
82
- readonly discoverPlugins: () => Promise<readonly PluginDiscoveryRecord[]>;
83
- /** Discovery with the enabled activations' version pins: the versions boot runs (a pin never falls forward). */
84
- readonly discoverActivePlugins: () => Promise<readonly PluginDiscoveryRecord[]>;
85
- readonly onPluginEnabled: (pluginId: string) => Promise<void>;
86
- readonly onPluginDisabled: (pluginId: string) => void;
87
- readonly locatePluginPackageDirs: (pluginId: string) => Promise<{
88
- liveParent: string;
89
- liveNames: readonly string[];
90
- parkedDir: string;
91
- }>;
92
- /** Lists one discovered plugin's own files, read-only and bounded, for the admin Plugins
93
- * screen's package-files viewer — see {@link resolvePackageLocation} and
94
- * `Jini/packages/plugins/src/host/node/package-files.ts`. Rejects with `PluginPackagePathError` for an
95
- * unsafe id/version or a directory that resolves outside its container. */
96
- readonly readPluginPackageFiles: (record: PluginDiscoveryRecord) => Promise<PluginPackageFiles>;
97
- /** @agent-note Positional adapter over the shared hook registry; the entry object is passed
98
- * through untouched so every host payload field reaches each filter. */
99
- readonly beforeSaveHook: (entry: Parameters<HookRegistry["runBeforeSave"]>[0]["entry"]) => ReturnType<HookRegistry["runBeforeSave"]>;
100
- /** Admin preview (AW-7): one attached plugin's beforeSave patch for a draft, nothing saved or
101
- * counted toward quarantine. `null` ⇒ not attached. See `HookRegistry.previewBeforeSave`.
102
- * @agent-note Preview writes nothing and counts nothing toward quarantine. */
103
- readonly previewPluginBeforeSave: (pluginId: string, entry: Parameters<HookRegistry["previewBeforeSave"]>[0]["entry"]) => ReturnType<HookRegistry["previewBeforeSave"]>;
104
- /**
105
- * P0a fix (2026-09-23): re-runs `onPluginEnabled` for every plugin `activationRepo` durably
106
- * marks `enabled` for THIS composition's `workspaceId`. Before this existed, nothing replayed
107
- * that durable state into a freshly-constructed (empty) `hookRegistry` — a plugin enabled in a
108
- * prior process looked enabled in the admin UI and in `listAll()`, but its filter/action/
109
- * contribution never fired again until an operator disabled and re-enabled it. Best-effort: one
110
- * plugin failing to re-attach (e.g. its package was removed from disk) is logged and skipped, not
111
- * thrown, so it can never block the rest of boot (mirrors `seedBundledAgentPlugins`'s own
112
- * per-package isolation).
113
- */
114
- readonly attachEnabledPluginsAtBoot: () => Promise<void>;
115
- /** Every discovered plugin that has a name conflict right now — an enabled loser, or a plugin that
116
- * is off and WOULD be refused if turned on — for the admin screen and the host's plugin-list tool. See
117
- * `Jini/packages/plugins/src/host/plugin-claims.ts`'s `resolvePluginConflicts`. */
118
- readonly listPluginConflicts: () => Promise<ReadonlyMap<string, readonly PluginConflict[]>>;
119
- }
120
- /**
121
- * The host bag spread into discovery, conflicts, enable, load, the Tier-2 seam, install and the
122
- * source service. Extract-s6 L1b: a local port so the runtime core imports no host module.
123
- * @agent-note Second-host rule: build ONE bag per runtime and keep it for the runtime's lifetime;
124
- * every member is host-owned (capability vocabulary, declared content types, core owner name,
125
- * identity namespace, install-disabled wording, tier policy, archive reader, digest format and the
126
- * per-load invocation binding factory). The archive reader is always host-supplied (no fallback).
127
- */
128
- export interface PluginRuntimeHostBinding {
129
- readonly capabilityVocabulary: readonly string[];
130
- readonly declarativeContentTypes: DeclarativeContentTypesPort;
131
- readonly coreOwnerName: string;
132
- readonly identityNamespace: string;
133
- readonly localInstallDisabledMessage: string;
134
- readonly tierPolicy: PluginTierPolicy;
135
- readonly archiveReader: ArchiveReaderPort;
136
- readonly verifyDigest: VerifyDigestPort;
137
- readonly createInvocationCoreDeps: RunTier2CallRequired["createInvocationCoreDeps"];
138
- }
139
- /** Only the tracker member the runtime calls. @agent-note The host supplies the event vocabulary
140
- * through `quarantineTelemetry`; the runtime never names an event, user or property itself. */
141
- export interface PluginRuntimeTracker<TEvent, TOptions> {
142
- capture(event: TEvent, options: TOptions): unknown;
143
- }
144
- /** Install admission + plugin lookup. @agent-note `withInstallIdentity` must serialize admission
145
- * of one candidate identity and run `run` at most once; it is read per install, never cached. */
146
- export interface PluginRuntimeLookup extends PluginLookupPort {
147
- /**
148
- * Admits one site-runtime publisher identity, then publishes it by running `run`.
149
- * @agent-note Second-host rule: the runtime only names the candidate; identity custody is the
150
- * host's, and this port must perform the WHOLE sequence, in this order:
151
- * 1. take ONE lock shared by every publisher of every plugin family the host runs, across all
152
- * processes that can publish into the same install (a per-process or per-family mutex is not
153
- * enough: two families could then both publish the same `publisher/local` identity);
154
- * 2. under that lock, read a FRESH admission inventory of all families (never a cached list),
155
- * including disabled installs, reserved/built-in identities and any other reservation;
156
- * 3. assert the candidate identity is available against that inventory, refusing a clash with any
157
- * other family or owner and allowing only a permitted upgrade of the same plugin's identity;
158
- * 4. run `run` (which publishes the install) while STILL holding the same lock, at most once,
159
- * and release the lock only after it settles. The site installer itself checks only its own
160
- * install directory and built-ins; it cannot see another family's reservation.
161
- */
162
- withInstallIdentity<T>(required: {
163
- candidate: {
164
- id: string;
165
- localId: string;
166
- family: "site-runtime";
167
- };
168
- run: () => Promise<T>;
169
- }): Promise<T>;
170
- }
171
- /** Host wording the runtime surfaces. @agent-note Exact host bytes; names of host tools, manifest
172
- * file names and route prefixes live here, never in the runtime. */
173
- export interface PluginRuntimeText {
174
- /** Source written to a new local plugin draft. */
175
- readonly scaffoldEntry: string;
176
- /** Reload refusal when a re-sealed version widens capabilities (`added` in manifest order). */
177
- readonly reloadApprovalRequired: (required: {
178
- added: readonly string[];
179
- }) => string;
180
- /** Quarantine reason when a source reload and the restored-version reload both failed. */
181
- readonly restoreFailedReason: string;
182
- }
183
- /**
184
- * Required inputs of the plugin-owned runtime core (extract-s6 L1b seam; moved here in L1c).
185
- * @agent-note Second-host rule: `pluginSourcePolicy`, `tier2CallRunner` and `pluginSdkBinding` have
186
- * NO defaults here — the host owns env/policy, the worker entry/runner/timeout, and the SDK (hook
187
- * ids, version, `beforeSaveHook`). `activationRepo` and the hook registry built here are shared by
188
- * save AND preview of this one runtime. The Tier-2 runner must register its SDK resolver before
189
- * importing. `createModuleImporter` is two-stage; see its own note.
190
- */
191
- export interface PluginRuntimeCoreRequired<TEvent = unknown, TOptions = unknown> {
192
- readonly workspaceId: string;
193
- readonly clock: ClockPort;
194
- readonly activationRepo: PluginActivationRepoPort;
195
- readonly sources: readonly PluginRuntimeSource[];
196
- readonly pluginSourcePolicy: PluginSourcePolicyPort;
197
- readonly tier2CallRunner: Tier2CallRunner;
198
- readonly pluginSdkBinding: PluginSdkBinding;
199
- readonly hostBinding: PluginRuntimeHostBinding;
200
- /**
201
- * Builds the module importer for one load target.
202
- * @agent-note Second-host rule: two stages, with different guarantees.
203
- * 1. Factory call: the runtime calls this while preparing the `loadPlugin` arguments, BEFORE that
204
- * load's integrity and `sdkRange` checks run, and possibly for a package those checks then
205
- * reject. The call must therefore only build a closure: no import, no snapshot, no file read,
206
- * no executable loading of any kind.
207
- * 2. Returned importer: invoked by the loader only AFTER admission (integrity, `sdkRange`). For a
208
- * site package it must (a) enforce containment: the resolved entry stays inside the plugin's
209
- * real package root, with links refused; (b) import a FRESH identity of the entire dependency
210
- * graph on every load, never a cached module, so a replaced package never runs stale helpers;
211
- * (c) keep any snapshot it takes, when `snapshots` is given, alive for late/lazy imports until
212
- * that lifecycle is disposed. A plain cached `import()` adapter violates (b). An injected
213
- * `importModule` seam (built-in, worker or test) keeps its original path.
214
- */
215
- readonly createModuleImporter: (required: {
216
- manifest: PluginManifest;
217
- source: "built-in" | "site";
218
- }, optional?: {
219
- importModule?: (entryPath: string) => Promise<unknown>;
220
- snapshots?: NonNullable<ReturnType<typeof createPluginModuleSnapshotLifecycle>>;
221
- }) => PluginModuleImportPort;
222
- readonly text: PluginRuntimeText;
223
- /** Host projection of one quarantine into its own telemetry event; called only when `tracker` is set. */
224
- readonly quarantineTelemetry: (required: {
225
- pluginId: string;
226
- }) => {
227
- event: TEvent;
228
- options: TOptions;
229
- };
230
- }
231
- /** Optional inputs; each omitted value keeps the documented default.
232
- * @agent-note `dispose()` must run after provider teardown and stopped hook users; it drains
233
- * pending attachments, then releases module snapshots. Load epochs retire stale generations. */
234
- export interface PluginRuntimeCoreOptional<TEvent = unknown, TOptions = unknown> {
235
- readonly tracker?: () => PluginRuntimeTracker<TEvent, TOptions>;
236
- readonly lookup?: () => PluginRuntimeLookup | undefined;
237
- readonly browserProviderApprovals?: readonly BundledBrowserProviderApproval[];
238
- readonly bundledEnabledIds?: readonly string[];
239
- readonly failureThreshold?: number;
240
- readonly installDir?: string;
241
- readonly coreClaims?: readonly ExtensionClaim[];
242
- readonly declaredContentTypes?: DeclaredContentTypePorts;
243
- }
1
+ import type { PluginRuntimeCoreRequired, PluginRuntimeCoreOptional, PluginRuntimeCoreBindings } from "./runtime-contracts.js";
244
2
  /**
245
3
  * The plugin-owned runtime algorithm behind the host's composition wrapper (extract-s6 L1b seam,
246
4
  * moved here in L1c). Reads no host module: every host value arrives through
@@ -9,8 +9,10 @@
9
9
  */
10
10
  import { lstat } from "node:fs/promises";
11
11
  import path from "node:path";
12
- import { formatErrorForLog, redactSecrets } from "@jini-ai/core";
12
+ import { describeErrorForLog, redactSecrets } from "@jini-ai/core";
13
+ import { observed } from "@jini-ai/core/errors/idioms";
13
14
  import { createPluginLookupFacade } from "@jini-ai/core/plugin-directory";
15
+ import { createConsoleLogger } from "@jini-ai/core/primitives";
14
16
  import { setPluginEnabled } from "../activation.js";
15
17
  import { initializeBundledPlugins } from "../bundled-initialization.js";
16
18
  import { createPluginContributionCapture, createPluginContributionRegistry } from "../contributions.js";
@@ -23,107 +25,12 @@ import { attachLoadedPlugin } from "../attach-loaded-plugin.js";
23
25
  import { assertPluginInstallIdle, installSitePlugin, previewSitePluginInstall, pruneSitePluginVersions } from "./install.js";
24
26
  import { createPluginModuleSnapshotLifecycle, PluginSnapshotLifecycleError } from "./module-snapshot.js";
25
27
  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 { discoverPlugins as discoverPluginRuntimePlugins } from "./discovery.js";
29
+ import { readPluginPackageFiles as readPluginPackageDirectory } from "./package-files.js";
28
30
  import { loadPlugin, PluginLoadError } from "./loader.js";
29
31
  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
- }
32
+ import { resolveLoadTarget, declaresProviders } from "./runtime-load-target.js";
33
+ import { SAFE_PLUGIN_ID_SEGMENT, PluginUninstallPathError, resolvePackageLocation } from "./runtime-package-location.js";
127
34
  /**
128
35
  * The plugin-owned runtime algorithm behind the host's composition wrapper (extract-s6 L1b seam,
129
36
  * moved here in L1c). Reads no host module: every host value arrives through
@@ -267,7 +174,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
267
174
  const capture = createPluginContributionCapture({ manifest });
268
175
  let scopedSdk;
269
176
  const coreDeps = { ...invocation.coreDeps, contributions: capture };
270
- // CIC U-001: the importer FACTORY runs here, before loadPlugin's integrity/sdkRange checks, so
177
+ // The importer FACTORY runs here, before loadPlugin's integrity/sdkRange checks, so
271
178
  // it must stay inert; loadPlugin invokes the returned importer only after those checks. A site
272
179
  // target takes the contained immutable snapshot; built-in seams retain their original path.
273
180
  const moduleImporter = resolveRuntimeImporter({ target, record });
@@ -299,10 +206,10 @@ export function createPluginRuntimeCore(required, optional = {}) {
299
206
  providers: result.browserProviders ?? [], version: record.version });
300
207
  }
301
208
  function resolveRuntimeImporter({ target, record }, _options = {}) {
302
- // Tier 2 (ADR-024 §3/§4): the plugin's code must never be imported into this process. Its
209
+ // Tier 2: the plugin's code must never be imported into this process. Its
303
210
  // import seam probes it in a fresh worker and hands `loadPlugin()` a proxy whose filter is an
304
211
  // 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
212
+ // still run first. Only a built-in reaches here as tier-2: discovery marks a site
306
213
  // tier-2 package invalid (the worker is no sandbox yet). Were site tier-2 ever allowed, its worker
307
214
  // would need the seam's `resolveWorkerEntry` pointed at the integrity-checked module snapshot,
308
215
  // since an injected worker seam bypasses the host's default snapshot importer.
@@ -369,8 +276,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
369
276
  const reason = describeBootConflictQuarantine({ conflicts: pluginConflicts });
370
277
  await quarantinePlugin({ deps: quarantineDeps, input: { pluginId, workspaceId: required.workspaceId, consecutiveFailures: 0, reason } });
371
278
  onPluginDisabled(pluginId);
372
- // eslint-disable-next-line no-console
373
- console.warn(`[plugin-runtime] '${pluginId}' quarantined at boot: ${reason}`);
279
+ createConsoleLogger({ prefix: '' }).warn({ message: `[plugin-runtime] '${pluginId}' quarantined at boot: ${reason}` });
374
280
  quarantined.add(pluginId);
375
281
  }
376
282
  return quarantined;
@@ -379,13 +285,13 @@ export function createPluginRuntimeCore(required, optional = {}) {
379
285
  // Serialize first-boot defaults with boot attachment. Existing disabled/quarantined rows win.
380
286
  const initialized = await initializeBundledPlugins({
381
287
  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 }));
288
+ console.warn("[plugin-runtime] bundled discovery failed; chart providers remain unavailable", describeErrorForLog({ err: error }));
383
289
  return [];
384
290
  }) : [], onEnabled: onPluginEnabled, onDisabled: onPluginDisabled },
385
291
  input: { workspaceId: required.workspaceId, pluginIds: optional.bundledEnabledIds ?? [] },
386
292
  });
387
293
  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 }));
294
+ console.warn(redactSecrets({ input: `[plugin-runtime] bundled initialization failed for '${failure.pluginId}'` }, { redactPii: false }), describeErrorForLog({ err: failure.error }));
389
295
  return initialized;
390
296
  }
391
297
  async function attachEnabledPluginsAtBoot() {
@@ -405,8 +311,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
405
311
  // Fail closed: without a finished conflict pass there is no telling which of two clashing
406
312
  // plugins should run, so none is attached this boot (each would previously have failed its
407
313
  // 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 })}`);
314
+ createConsoleLogger({ prefix: '' }).warn({ message: '[plugin-runtime] boot conflict check failed, no plugin attached' }, { error });
410
315
  for (const record of enabledHere)
411
316
  onPluginDisabled(record.pluginId);
412
317
  return;
@@ -432,8 +337,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
432
337
  await attachPlugin(pluginId, discovered);
433
338
  }
434
339
  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 })}`);
340
+ createConsoleLogger({ prefix: '' }).warn({ message: `[plugin-runtime] boot re-attach failed for '${pluginId}'` }, { error });
437
341
  }
438
342
  }
439
343
  /** Import + setup of one selected provider plugin, bounded: boot never waits on a stalled plugin. On the
@@ -445,7 +349,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
445
349
  });
446
350
  const attached = attachPlugin(record.id, record);
447
351
  // Observed even after the deadline wins, so a late failure is never an unhandled rejection.
448
- attached.catch(() => { });
352
+ observed({ promise: attached });
449
353
  try {
450
354
  await Promise.race([attached, deadline]);
451
355
  }
@@ -477,7 +381,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
477
381
  }
478
382
  catch (error) {
479
383
  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 })}`);
384
+ console.warn(`[plugin-runtime] provider plugin '${record.id}' failed to load; its contract stays on the noop: ${describeErrorForLog({ err: error })}`);
481
385
  }
482
386
  }
483
387
  return loaded;
@@ -554,7 +458,7 @@ export function createPluginRuntimeCore(required, optional = {}) {
554
458
  await onPluginEnabled(id);
555
459
  }
556
460
  catch (rollbackError) {
557
- console.warn(`[plugin-runtime] Plugin '${id}' restored-version reload failed`, formatErrorForLog({ error: rollbackError }));
461
+ console.warn(`[plugin-runtime] Plugin '${id}' restored-version reload failed`, describeErrorForLog({ err: rollbackError }));
558
462
  onPluginDisabled(id);
559
463
  await quarantinePlugin({ deps: quarantineDeps, input: { pluginId: id, workspaceId, consecutiveFailures: 0, reason: required.text.restoreFailedReason } });
560
464
  }
@@ -0,0 +1,44 @@
1
+ import type { PluginManifest } from "../manifest-types.js";
2
+ import type { PluginDiscoveryRecord } from "../discovery-types.js";
3
+ import type { AttachmentSource } from "../hook-registry.js";
4
+ import type { PluginRuntimeSource } from "./runtime-contracts.js";
5
+ /** What `loadPlugin()` and `attachLoadedPlugin()` need for one enable attempt, resolved by
6
+ * {@link resolveLoadTarget}. `importModule` is omitted (not `undefined`-valued) for a site target
7
+ * so the host binding supplies the contained snapshot importer; only a built-in target carries
8
+ * an explicit scalar override (its test/production seam, unchanged by this type). */
9
+ export interface PluginLoadTarget {
10
+ readonly manifest: PluginManifest;
11
+ readonly entryPath: string;
12
+ readonly attachmentSource: AttachmentSource;
13
+ readonly importModule?: (entryPath: string) => Promise<unknown>;
14
+ }
15
+ /**
16
+ * Resolves ONE enable attempt's load target (Milestone 1b, 2026-08-20): a compiled-in built-in
17
+ * plugin uses the composition root's own static `PluginRuntimeSource` — entirely unchanged from
18
+ * before this slice, so every existing built-in test (including ones that inject a synthetic
19
+ * `entryPath`/`importModule`, e.g. the auto-quarantine fixture) keeps behaving identically. A
20
+ * site-installed plugin has no static source to find, so its target is derived instead from the
21
+ * SAME discovery record `onPluginEnabled` already fetched this call — reusing `record.manifest`
22
+ * (see that field's own doc for why this, not a second file read, is the TOCTOU-safe choice) and
23
+ * `siteEntryPath()`'s REQ-02 layout convention.
24
+ *
25
+ * Deliberately does not itself touch integrity/`sdkRange`/`import()` — those stay exactly where
26
+ * they are required, inside `loadPlugin()`'s own fixed step order. This function only decides
27
+ * WHICH manifest/entryPath/import-hook `loadPlugin()` is handed; it never calls `import()` itself
28
+ * and never lets a caller reach one without going through `loadPlugin()`'s ordering first.
29
+ *
30
+ * @returns `null` when the id is neither a known built-in nor a valid, installDir-reachable site
31
+ * record — the caller's existing fail-closed `PLUGIN_EXPORT_INVALID` behavior is unchanged.
32
+ * @complexity O(sources.length) — one linear scan of the static built-in list; no I/O of its own.
33
+ */
34
+ export declare function resolveLoadTarget(params: {
35
+ pluginId: string;
36
+ sources: readonly PluginRuntimeSource[];
37
+ record: PluginDiscoveryRecord;
38
+ installDir: string | undefined;
39
+ }): PluginLoadTarget | null;
40
+ /** True when a manifest declares provider factories (`contributes.providers`). */
41
+ export declare function declaresProviders({ manifest }: {
42
+ manifest: PluginManifest | undefined;
43
+ }): boolean;
44
+ //# sourceMappingURL=runtime-load-target.d.ts.map
@@ -0,0 +1,45 @@
1
+ import { siteEntryPath } from "./discovery.js";
2
+ /**
3
+ * Resolves ONE enable attempt's load target (Milestone 1b, 2026-08-20): a compiled-in built-in
4
+ * plugin uses the composition root's own static `PluginRuntimeSource` — entirely unchanged from
5
+ * before this slice, so every existing built-in test (including ones that inject a synthetic
6
+ * `entryPath`/`importModule`, e.g. the auto-quarantine fixture) keeps behaving identically. A
7
+ * site-installed plugin has no static source to find, so its target is derived instead from the
8
+ * SAME discovery record `onPluginEnabled` already fetched this call — reusing `record.manifest`
9
+ * (see that field's own doc for why this, not a second file read, is the TOCTOU-safe choice) and
10
+ * `siteEntryPath()`'s REQ-02 layout convention.
11
+ *
12
+ * Deliberately does not itself touch integrity/`sdkRange`/`import()` — those stay exactly where
13
+ * they are required, inside `loadPlugin()`'s own fixed step order. This function only decides
14
+ * WHICH manifest/entryPath/import-hook `loadPlugin()` is handed; it never calls `import()` itself
15
+ * and never lets a caller reach one without going through `loadPlugin()`'s ordering first.
16
+ *
17
+ * @returns `null` when the id is neither a known built-in nor a valid, installDir-reachable site
18
+ * record — the caller's existing fail-closed `PLUGIN_EXPORT_INVALID` behavior is unchanged.
19
+ * @complexity O(sources.length) — one linear scan of the static built-in list; no I/O of its own.
20
+ */
21
+ export function resolveLoadTarget(params) {
22
+ const { pluginId, sources, record, installDir } = params;
23
+ const builtIn = sources.find((candidate) => candidate.manifest.id === pluginId);
24
+ if (builtIn) {
25
+ return {
26
+ manifest: builtIn.manifest,
27
+ entryPath: builtIn.entryPath,
28
+ attachmentSource: builtIn.source,
29
+ importModule: builtIn.importModule,
30
+ };
31
+ }
32
+ if (record.source === "site" && installDir !== undefined && record.manifest !== undefined) {
33
+ return {
34
+ manifest: record.manifest,
35
+ entryPath: siteEntryPath({ installDir, id: record.id, version: record.version }),
36
+ attachmentSource: record.source,
37
+ };
38
+ }
39
+ return null;
40
+ }
41
+ /** True when a manifest declares provider factories (`contributes.providers`). */
42
+ export function declaresProviders({ manifest }) {
43
+ return (manifest?.contributes?.providers?.length ?? 0) > 0;
44
+ }
45
+ //# sourceMappingURL=runtime-load-target.js.map
@@ -0,0 +1,45 @@
1
+ import type { PluginDiscoveryRecord } from "../discovery-types.js";
2
+ import type { PluginRuntimeSource } from "./runtime-contracts.js";
3
+ /**
4
+ * A plugin id safe to use as a single filesystem path segment (Milestone 2, 2026-08-20) — the same
5
+ * character class `src/features/agent-plugins/layout.ts`'s `SAFE_PLUGIN_ID_PATTERN` uses,
6
+ * independently declared here rather than imported: that module is a DIFFERENT, unrelated plugin
7
+ * system (agent-plugins.org format; see this file's own `PluginRuntimeSource` doc history and
8
+ * Milestone 1's handoff for why the two are never wired together), and importing from it would
9
+ * create exactly that coupling for a one-line regex. `.` and `-` are allowed mid-string (matching
10
+ * real semver-adjacent plugin ids like `word-count`) but the pattern has no `/`, no `..`, and no
11
+ * leading/trailing separator — it cannot itself produce a path-traversal segment.
12
+ */
13
+ export declare const SAFE_PLUGIN_ID_SEGMENT: RegExp;
14
+ /** Thrown when `pluginId` is not safe to use as a filesystem path segment
15
+ * under `installDir` — either it fails {@link SAFE_PLUGIN_ID_SEGMENT}'s allowlist, or (defense in
16
+ * depth, in case some future caller's id validation elsewhere ever drifts) the resolved absolute
17
+ * path would land outside `installDir` after resolution. Deliberately fails closed on EITHER
18
+ * check independently, not just the one presumed sufficient.
19
+ * @agent-note Error identity: hosts re-export this ONE class (never a copy) so `instanceof` and
20
+ * `name === "PluginUninstallPathError"` hold across the host's routes and tests. */
21
+ export declare class PluginUninstallPathError extends Error {
22
+ constructor(pluginId: string);
23
+ }
24
+ /**
25
+ * Where one discovered plugin's files live, for the package-files viewer: a built-in's own
26
+ * `sourceDir`, or a site plugin's `<installDir>/<id>/<version>/` (REQ-02's layout, the same one
27
+ * `siteEntryPath()` joins). The directory is its own container for a built-in; `installDir` is the
28
+ * container for a site plugin, so `readPluginPackageFiles()`'s realpath check keeps a symlinked id
29
+ * or version folder from reaching outside it.
30
+ *
31
+ * @returns `null` when there is no directory to show: a built-in without `sourceDir`, or a site
32
+ * record while `installDir` is unset.
33
+ * @throws {PluginPackagePathError} a site record's id or version is not one safe path segment — a
34
+ * site record's id comes from its own manifest, so it is untrusted text until checked here.
35
+ * @complexity O(sources.length).
36
+ */
37
+ export declare function resolvePackageLocation(params: {
38
+ record: PluginDiscoveryRecord;
39
+ sources: readonly PluginRuntimeSource[];
40
+ installDir: string | undefined;
41
+ }): {
42
+ rootDir: string;
43
+ containerDir: string;
44
+ } | null;
45
+ //# sourceMappingURL=runtime-package-location.d.ts.map