@jini-ai/plugins 0.7.3-next.1 → 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 (104) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +53 -0
  3. package/dist/host/activation-polling.d.ts +67 -0
  4. package/dist/host/activation-polling.js +113 -0
  5. package/dist/host/activation.d.ts +2 -30
  6. package/dist/host/capability-tools.d.ts +1 -0
  7. package/dist/host/capability-tools.js +4 -4
  8. package/dist/host/contributions.d.ts +2 -9
  9. package/dist/host/hook-refusals.d.ts +49 -0
  10. package/dist/host/hook-refusals.js +65 -0
  11. package/dist/host/index.d.ts +3 -1
  12. package/dist/host/index.js +1 -0
  13. package/dist/host/manifest.js +2 -2
  14. package/dist/host/node/browser-provider-assets.d.ts +2 -1
  15. package/dist/host/node/browser-provider-assets.js +2 -2
  16. package/dist/host/node/discovery.js +5 -5
  17. package/dist/host/node/install.d.ts +6 -1
  18. package/dist/host/node/install.js +22 -20
  19. package/dist/host/node/integrity-command.d.ts +2 -1
  20. package/dist/host/node/integrity-command.js +3 -3
  21. package/dist/host/node/loader.d.ts +3 -2
  22. package/dist/host/node/loader.js +6 -6
  23. package/dist/host/node/module-snapshot.d.ts +4 -3
  24. package/dist/host/node/module-snapshot.js +5 -5
  25. package/dist/host/node/package-files.d.ts +2 -1
  26. package/dist/host/node/package-files.js +6 -6
  27. package/dist/host/node/runtime-activation.d.ts +35 -0
  28. package/dist/host/node/runtime-activation.js +188 -0
  29. package/dist/host/node/runtime-boot.d.ts +16 -0
  30. package/dist/host/node/runtime-boot.js +153 -0
  31. package/dist/host/node/runtime-conflicts.d.ts +38 -0
  32. package/dist/host/node/runtime-conflicts.js +42 -0
  33. package/dist/host/node/runtime-contracts.d.ts +5 -3
  34. package/dist/host/node/runtime-core.js +65 -465
  35. package/dist/host/node/runtime-load-target.d.ts +14 -0
  36. package/dist/host/node/runtime-load-target.js +15 -0
  37. package/dist/host/node/runtime-reload.d.ts +12 -0
  38. package/dist/host/node/runtime-reload.js +107 -0
  39. package/dist/host/node/runtime-state.d.ts +52 -0
  40. package/dist/host/node/runtime-state.js +50 -0
  41. package/dist/host/node/source-drafts.d.ts +1 -1
  42. package/dist/host/node/source-drafts.js +17 -15
  43. package/dist/host/plugin-claims.d.ts +2 -9
  44. package/dist/host/plugin-format.d.ts +5 -5
  45. package/dist/host/plugin-format.js +9 -10
  46. package/dist/host/ports.d.ts +4 -28
  47. package/dist/host/tools/install.js +1 -1
  48. package/dist/host/uninstall.d.ts +2 -2
  49. package/dist/host/worker/import-policy.d.ts +49 -0
  50. package/dist/host/worker/import-policy.js +86 -0
  51. package/dist/host/worker/import-seam.js +21 -2
  52. package/dist/host/worker/index.d.ts +1 -0
  53. package/dist/host/worker/index.js +1 -0
  54. package/dist/host/worker/protocol.d.ts +4 -0
  55. package/dist/host/worker/run-call.js +2 -1
  56. package/dist/host/worker/start.d.ts +18 -1
  57. package/dist/host/worker/start.js +27 -6
  58. package/dist/react/PluginProviderSettingsDialog.d.ts +144 -0
  59. package/dist/react/PluginProviderSettingsDialog.js +54 -0
  60. package/dist/react/plugin-install-port.d.ts +29 -0
  61. package/dist/react/plugin-install-port.js +15 -0
  62. package/dist/runtime/agent-tools.d.ts +174 -0
  63. package/dist/runtime/agent-tools.js +121 -0
  64. package/dist/runtime/built-ins/word-count/count-words.d.ts +21 -0
  65. package/dist/runtime/built-ins/word-count/count-words.js +48 -0
  66. package/dist/runtime/built-ins/word-count/plugin.d.ts +6 -0
  67. package/dist/runtime/built-ins/word-count/plugin.js +12 -0
  68. package/dist/runtime/capability-card.d.ts +22 -0
  69. package/dist/runtime/capability-card.js +30 -0
  70. package/dist/runtime/enable-confirmation-ui.d.ts +28 -0
  71. package/dist/runtime/enable-confirmation-ui.js +54 -0
  72. package/dist/runtime/install-consent.d.ts +12 -0
  73. package/dist/runtime/install-consent.js +27 -0
  74. package/dist/runtime/install-source.d.ts +26 -0
  75. package/dist/runtime/install-source.js +61 -0
  76. package/dist/runtime/install-tool-catalog.d.ts +9 -0
  77. package/dist/runtime/install-tool-catalog.js +25 -0
  78. package/dist/runtime/lower-tool-access.d.ts +17 -0
  79. package/dist/runtime/lower-tool-access.js +14 -0
  80. package/dist/runtime/plugin-export.d.ts +13 -0
  81. package/dist/runtime/plugin-export.js +14 -0
  82. package/dist/runtime/plugin-host-copy.d.ts +17 -0
  83. package/dist/runtime/plugin-host-copy.js +7 -0
  84. package/dist/runtime/plugin-tool-ids.d.ts +18 -0
  85. package/dist/runtime/plugin-tool-ids.js +4 -0
  86. package/dist/runtime/plugin-tool-messages.d.ts +97 -0
  87. package/dist/runtime/plugin-tool-messages.js +90 -0
  88. package/dist/runtime/sdk-resolver.d.ts +60 -0
  89. package/dist/runtime/sdk-resolver.js +97 -0
  90. package/dist/runtime/service-ports.d.ts +43 -0
  91. package/dist/runtime/service-ports.js +3 -0
  92. package/dist/runtime/source-tool-catalog.d.ts +7 -0
  93. package/dist/runtime/source-tool-catalog.js +33 -0
  94. package/dist/runtime/uninstall-confirmation-ui.d.ts +31 -0
  95. package/dist/runtime/uninstall-confirmation-ui.js +38 -0
  96. package/dist/runtime/widget-partials.d.ts +22 -0
  97. package/dist/runtime/widget-partials.js +13 -0
  98. package/dist/site/lipay/manifest.d.ts +10 -0
  99. package/dist/site/lipay/manifest.js +96 -0
  100. package/dist/site/store/manifest.d.ts +10 -0
  101. package/dist/site/store/manifest.js +37 -0
  102. package/package.json +158 -8
  103. package/dist/host/provider-config-source.d.ts +0 -47
  104. package/dist/host/provider-config-source.js +0 -2
@@ -12,7 +12,7 @@ import path from "node:path";
12
12
  import { createHash } from "node:crypto";
13
13
  import * as semver from "semver";
14
14
  import { validateManifest, validatePluginIdFormat } from "../manifest.js";
15
- import { PLUGIN_MANIFEST_FILENAME as MANIFEST, PLUGIN_MANIFEST_FILENAMES, canonicalizePluginManifest } from "../plugin-format.js";
15
+ import { PLUGIN_MANIFEST_FILENAME as MANIFEST, pluginManifestFilenames, canonicalizePluginManifest } from "../plugin-format.js";
16
16
  export { PluginInstallError } from '../plugin-tool-errors.js';
17
17
  const MAX_ENTRIES = 4096;
18
18
  const MAX_FILE_BYTES = 16 * 1024 * 1024;
@@ -132,9 +132,9 @@ const DECLARATIVE_DATA_FILE = /(?:^|\/)(?:LICENSE|[^/]+\.(?:json|md|txt|png|jpe?
132
132
  * still be tier-3 with `server/index.mjs`, because a sideloaded manifest cannot grant itself a
133
133
  * verified publisher tier (tier-2 needs the sandbox, which does not exist yet).
134
134
  */
135
- function checkTierAndCode(candidate, files, tierPolicy) {
135
+ function checkTierAndCode(candidate, files, tierPolicy, optional = {}) {
136
136
  if (candidate.tier === "tier-1") {
137
- const code = [...files.keys()].filter((key) => !PLUGIN_MANIFEST_FILENAMES.includes(key) && !DECLARATIVE_DATA_FILE.test(key)); // legacy alias
137
+ const code = [...files.keys()].filter((key) => !pluginManifestFilenames({}, optional).includes(key) && !DECLARATIVE_DATA_FILE.test(key)); // legacy alias
138
138
  if (code.length)
139
139
  fail("PLUGIN_MANIFEST_INVALID", `A declarative (tier-1) plugin must not ship code: ${code.join(", ")}`);
140
140
  return;
@@ -144,8 +144,8 @@ function checkTierAndCode(candidate, files, tierPolicy) {
144
144
  tierPolicy.checkInstall({ manifest: candidate, files });
145
145
  }
146
146
  /** The parsed manifest JSON (current name first, then the legacy alias), or a refusal. */
147
- function parseManifestFile(files) {
148
- const filename = PLUGIN_MANIFEST_FILENAMES.find(name => files.has(name)); // legacy alias
147
+ function parseManifestFile(files, optional = {}) {
148
+ const filename = pluginManifestFilenames({}, optional).find(name => files.has(name)); // legacy alias
149
149
  try {
150
150
  return JSON.parse(filename === undefined ? "" : files.get(filename).toString("utf8"));
151
151
  }
@@ -156,8 +156,8 @@ function parseManifestFile(files) {
156
156
  /** Integrity must list exactly every packaged file except plugin manifests, each hash matching.
157
157
  * Its shape needs no check here: `validatePackage` only calls this after `validateManifest` passed,
158
158
  * which requires `integrity` and refuses anything but a plain object of sha256 strings. */
159
- function assertIntegrity(candidate, files) {
160
- const packaged = [...files.keys()].filter((key) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).sort(); // legacy alias
159
+ function assertIntegrity(candidate, files, optional = {}) {
160
+ const packaged = [...files.keys()].filter((key) => !pluginManifestFilenames({}, optional).includes(key)).sort(); // legacy alias
161
161
  if (JSON.stringify(Object.keys(candidate.integrity).sort()) !== JSON.stringify(packaged))
162
162
  fail("PLUGIN_INTEGRITY_INVALID", "Integrity must list exactly every file except plugin manifests.");
163
163
  for (const key of packaged)
@@ -166,7 +166,7 @@ function assertIntegrity(candidate, files) {
166
166
  }
167
167
  function validatePackage(files, deps) {
168
168
  const { builtInIds } = deps;
169
- const raw = parseManifestFile(files);
169
+ const raw = parseManifestFile(files, deps);
170
170
  const id = typeof raw?.id === "string" ? raw.id : "";
171
171
  if (builtInIds.some((builtin) => builtin.toLowerCase() === id.toLowerCase()))
172
172
  fail("PLUGIN_SHADOWS_BUILT_IN", "Package id belongs to a built-in plugin.");
@@ -178,14 +178,14 @@ function validatePackage(files, deps) {
178
178
  // accepts only a canonical SemVer version (`isExactSemver`), whose alphabet [0-9A-Za-z.+-] starting
179
179
  // with a digit is already path-safe — so the version can name an install folder as-is.
180
180
  const candidate = raw;
181
- checkTierAndCode(candidate, files, deps.tierPolicy);
181
+ checkTierAndCode(candidate, files, deps.tierPolicy, deps);
182
182
  if (typeof candidate.name !== "string" || !candidate.name.trim() || typeof candidate.sdkRange !== "string" || !semver.validRange(candidate.sdkRange))
183
183
  fail("PLUGIN_MANIFEST_INVALID", "A name and valid SDK range are required.");
184
- assertIntegrity(candidate, files);
184
+ assertIntegrity(candidate, files, deps);
185
185
  return candidate;
186
186
  }
187
187
  function identityOf(manifest, deps, name = manifest.id) {
188
- return readPluginIdentity({ manifest: manifest, name, namespace: deps.identityNamespace });
188
+ return readPluginIdentity({ manifest: manifest, name, namespace: deps.identityNamespace, legacyNamespace: deps.legacyIdentityNamespace });
189
189
  }
190
190
  function assertIdentityFree(candidate, installed) {
191
191
  try {
@@ -227,8 +227,8 @@ async function isScannableVersion(required) {
227
227
  return false;
228
228
  }
229
229
  }
230
- async function findInstalledManifest(scan, versionDir) {
231
- for (const filename of PLUGIN_MANIFEST_FILENAMES) { // legacy alias
230
+ async function findInstalledManifest(scan, versionDir, optional = {}) {
231
+ for (const filename of pluginManifestFilenames({}, optional)) { // legacy alias
232
232
  const candidatePath = path.join(versionDir, filename);
233
233
  try {
234
234
  await scan.lstat(candidatePath);
@@ -245,12 +245,12 @@ async function findInstalledManifest(scan, versionDir) {
245
245
  async function readInstalledIdentity(required) {
246
246
  const { scan, localId, deps } = required;
247
247
  try {
248
- const manifestPath = await findInstalledManifest(scan, required.versionDir);
248
+ const manifestPath = await findInstalledManifest(scan, required.versionDir, deps);
249
249
  const manifestInfo = await scan.lstat(manifestPath);
250
250
  if (!manifestInfo.isFile() || manifestInfo.isSymbolicLink())
251
251
  fail("PLUGIN_PACKAGE_UNSAFE", "Installed plugin manifests must not be links.");
252
252
  const installedManifest = JSON.parse(await scan.readFile(manifestPath, "utf8"));
253
- return readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace });
253
+ return readPluginIdentity({ manifest: installedManifest, name: localId, namespace: deps.identityNamespace, legacyNamespace: deps.legacyIdentityNamespace });
254
254
  }
255
255
  catch (error) {
256
256
  if (error instanceof PluginInstallError)
@@ -392,8 +392,8 @@ export async function snapshotSitePluginPackage(required, optional = {}) {
392
392
  export function digestSitePluginSnapshot(required, _optional = {}) {
393
393
  return hash(Buffer.from(JSON.stringify([...required.files].map(([key, bytes]) => [key, hash(bytes)]).sort(([a], [b]) => a < b ? -1 : 1))));
394
394
  }
395
- export async function computePluginIntegrity(required, _optional = {}) {
396
- return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => !PLUGIN_MANIFEST_FILENAMES.includes(key)).map(([key, bytes]) => [key, hash(bytes)])); // legacy alias
395
+ export async function computePluginIntegrity(required, optional = {}) {
396
+ return Object.fromEntries([...await snapshot(required.sourceDir)].filter(([key]) => !pluginManifestFilenames({}, optional).includes(key)).map(([key, bytes]) => [key, hash(bytes)])); // legacy alias
397
397
  }
398
398
  export async function previewSitePluginInstall(required, _optional = {}) {
399
399
  return (await inspect(required, required.deps)).preview;
@@ -418,8 +418,8 @@ async function withPluginInstallLock(required, _optional = {}) {
418
418
  }
419
419
  }
420
420
  /** Writes the retained bytes (manifest canonicalized) into a fresh staged version folder. */
421
- async function writeStagedVersion(required) {
422
- for (const [key, bytes] of canonicalizePluginManifest({ files: required.files })) { // legacy alias
421
+ async function writeStagedVersion(required, optional = {}) {
422
+ for (const [key, bytes] of canonicalizePluginManifest({ files: required.files }, optional)) { // legacy alias
423
423
  const target = path.join(required.versionDir, key);
424
424
  await mkdir(path.dirname(target), { recursive: true });
425
425
  await writeFile(target, bytes, { flag: "wx" });
@@ -467,6 +467,7 @@ export async function installSitePlugin(required, _optional = {}) {
467
467
  const { files, manifest, preview } = await inspect(required, optional);
468
468
  if (preview.digest !== required.expectedDigest)
469
469
  fail("PLUGIN_CHANGED_SINCE_PREVIEW", "Package changed since preview. Review it again.");
470
+ optional.signal?.throwIfAborted();
470
471
  for (const target of [root, root + "-staging", root + "-trash"]) {
471
472
  if (await exists(target))
472
473
  assertRealDirectory(await lstat(target), "Install, staging and Trash roots must be real directories.");
@@ -476,9 +477,10 @@ export async function installSitePlugin(required, _optional = {}) {
476
477
  try {
477
478
  await mkdir(root + "-staging", { recursive: true });
478
479
  staging = await mkdtemp(path.join(root + "-staging", "install-"));
479
- await writeStagedVersion({ versionDir: path.join(staging, "new", manifest.version), files });
480
+ await writeStagedVersion({ versionDir: path.join(staging, "new", manifest.version), files }, optional);
480
481
  await checkDestination(manifest, required, optional);
481
482
  await mkdir(root, { recursive: true });
483
+ optional.signal?.throwIfAborted();
482
484
  await publishStaged({ live: path.join(root, manifest.id), staging, manifest, versionAppend: optional.versionAppend }).catch((error) => {
483
485
  // Never let cleanup erase the sole remaining copy when rollback itself fails.
484
486
  if (error instanceof PluginInstallError && error.code === "PLUGIN_INSTALL_RECOVERY_REQUIRED")
@@ -1,8 +1,9 @@
1
+ import { type PluginManifestReadOptions } from '../plugin-format.js';
1
2
  /** Authoring helper: hashes bytes only; never imports the package's entry point. */
2
3
  export declare function runPluginIntegrityCommand(required: {
3
4
  dir: string;
4
5
  write?: boolean;
5
- }, optional?: {
6
+ }, optional?: PluginManifestReadOptions & {
6
7
  output?: (message: string) => void;
7
8
  }): Promise<void>;
8
9
  //# sourceMappingURL=integrity-command.d.ts.map
@@ -3,13 +3,13 @@ import path from "node:path";
3
3
  import { readFile, readdir, writeFile, rename, rm } from "node:fs/promises";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { computePluginIntegrity } from './install.js';
6
- import { PLUGIN_MANIFEST_FILENAME, PLUGIN_MANIFEST_FILENAMES } from '../plugin-format.js';
6
+ import { PLUGIN_MANIFEST_FILENAME, pluginManifestFilenames } from '../plugin-format.js';
7
7
  /** Authoring helper: hashes bytes only; never imports the package's entry point. */
8
8
  export async function runPluginIntegrityCommand(required, optional = {}) {
9
- const integrity = await computePluginIntegrity({ sourceDir: required.dir });
9
+ const integrity = await computePluginIntegrity({ sourceDir: required.dir }, optional);
10
10
  if (required.write) {
11
11
  const names = await readdir(required.dir);
12
- const sourceName = PLUGIN_MANIFEST_FILENAMES.find((name) => names.includes(name)) ?? PLUGIN_MANIFEST_FILENAME; // legacy alias
12
+ const sourceName = pluginManifestFilenames({}, optional).find((name) => names.includes(name)) ?? PLUGIN_MANIFEST_FILENAME; // legacy alias
13
13
  const manifest = JSON.parse(await readFile(path.join(required.dir, sourceName), "utf8"));
14
14
  const manifestPath = path.join(required.dir, PLUGIN_MANIFEST_FILENAME);
15
15
  const staged = manifestPath + ".tmp-" + randomUUID();
@@ -1,3 +1,4 @@
1
+ import type { PluginManifestReadOptions } from "../plugin-format.js";
1
2
  import { type AdmittedBrowserProvider } from "../browser-providers.js";
2
3
  import type { BundledBrowserProviderApproval } from "../ports.js";
3
4
  import { type PluginContributionRegistry } from '../contributions.js';
@@ -35,7 +36,7 @@ export interface LoadPluginRequired<H extends HookPoints = HookPoints> {
35
36
  /** Compiled-in review records; absent means all browser providers are refused. */
36
37
  readonly browserProviderApprovals?: readonly BundledBrowserProviderApproval[];
37
38
  }
38
- export type LoadPluginOptional = Record<string, never>;
39
+ export type LoadPluginOptional = PluginManifestReadOptions;
39
40
  export type PluginLoadFailureReason = "INTEGRITY_FAILED" | "SDK_RANGE_UNSATISFIED" | "CODE_ENTRY_MISSING" | "PLUGIN_EXPORT_INVALID" | "PLUGIN_SETUP_FAILED" | "BROWSER_PROVIDER_FORBIDDEN" | "BROWSER_PROVIDER_INVALID" | "PROVIDER_NOT_SELECTED" | "PROVIDER_ADMISSION_FAILED";
40
41
  export type PluginEnableFailureReason = PluginLoadFailureReason | "PLUGIN_HOOK_NOT_ATTACHED" | "PLUGIN_HOOK_ATTACH_FAILED";
41
42
  /** Raised by the composition root after converting `loadPlugin()`'s expected early-return result
@@ -66,5 +67,5 @@ export type LoadPluginResult = {
66
67
  * plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
67
68
  * disclosed open gap, not a defect of this function).
68
69
  */
69
- export declare function loadPlugin<H extends HookPoints>(required: LoadPluginRequired<H>, _optional?: LoadPluginOptional): Promise<LoadPluginResult>;
70
+ export declare function loadPlugin<H extends HookPoints>(required: LoadPluginRequired<H>, optional?: LoadPluginOptional): Promise<LoadPluginResult>;
70
71
  //# sourceMappingURL=loader.d.ts.map
@@ -82,11 +82,11 @@ async function verifyIntegrity(required) {
82
82
  return true;
83
83
  }
84
84
  /** Declared browser providers go through bundled-approval admission; none declared admits trivially. */
85
- async function admitDeclaredBrowserProviders(required) {
85
+ async function admitDeclaredBrowserProviders(required, optional = {}) {
86
86
  const { record, manifest, pluginRoot } = required;
87
87
  if (!manifest.browserProviders?.length)
88
88
  return { admitted: true };
89
- return admitBrowserProviderAssets({ record, manifest, pluginRoot, approvals: required.approvals ?? [] });
89
+ return admitBrowserProviderAssets({ record, manifest, pluginRoot, approvals: required.approvals ?? [] }, optional);
90
90
  }
91
91
  function isExecutionAdmitted(required) {
92
92
  const { tierPolicy, record, manifest } = required;
@@ -156,7 +156,7 @@ function publishProviderCapture(required) {
156
156
  return undefined;
157
157
  }
158
158
  /** Integrity and SDK compatibility remain ordered before any executable importer. */
159
- async function admitPluginPackage(required) {
159
+ async function admitPluginPackage(required, optional = {}) {
160
160
  const { record, manifest, entryPath } = required;
161
161
  const pluginRoot = derivePluginRoot(entryPath);
162
162
  const computeFileHash = (absoluteFilePath) => required.verifyDigest({ absoluteFilePath });
@@ -166,7 +166,7 @@ async function admitPluginPackage(required) {
166
166
  // --- Step (2), sdkRange, MUST complete successfully before step (3). ---
167
167
  if (!semver.satisfies(required.pluginSdkBinding.runtimeSdkVersion, manifest.sdkRange))
168
168
  return { failure: 'SDK_RANGE_UNSATISFIED' };
169
- const admission = await admitDeclaredBrowserProviders({ record, manifest, pluginRoot, approvals: required.browserProviderApprovals });
169
+ const admission = await admitDeclaredBrowserProviders({ record, manifest, pluginRoot, approvals: required.browserProviderApprovals }, optional);
170
170
  if (!admission.admitted)
171
171
  return { failure: admission.reason };
172
172
  return { pluginRoot, loaded: { loaded: true, ...(admission.providers ? { browserProviders: admission.providers } : {}) } };
@@ -190,9 +190,9 @@ function isProviderSelected(required) {
190
190
  * plugin-defined and unbounded — no latency budget is specified (ADR `scalability` axis, a
191
191
  * disclosed open gap, not a defect of this function).
192
192
  */
193
- export async function loadPlugin(required, _optional = {}) {
193
+ export async function loadPlugin(required, optional = {}) {
194
194
  const { record, manifest, coreDeps, importModule, pluginSdkBinding } = required;
195
- const admission = await admitPluginPackage(required);
195
+ const admission = await admitPluginPackage(required, optional);
196
196
  if ('failure' in admission)
197
197
  return failed(admission.failure);
198
198
  const { pluginRoot, loaded } = admission;
@@ -5,6 +5,7 @@
5
5
  import * as nativeFs from "node:fs/promises";
6
6
  import type { PluginManifest } from "../manifest.js";
7
7
  import type { PluginModuleImportPort } from "../ports.js";
8
+ import { type PluginManifestReadOptions } from "../plugin-format.js";
8
9
  export declare class PluginSnapshotIntegrityError extends Error {
9
10
  }
10
11
  /** Lifecycle failures have a stable category without exposing package paths or file contents. */
@@ -82,7 +83,7 @@ export declare function createPluginModuleSnapshotLifecycle({ runtimeRoot }: {
82
83
  export declare function snapshotPluginModuleGraph(required: {
83
84
  pluginRoot: string;
84
85
  manifest: PluginManifest;
85
- }, optional?: SnapshotWriteOptions & {
86
+ }, optional?: SnapshotWriteOptions & PluginManifestReadOptions & {
86
87
  lifecycle?: PluginModuleSnapshotLifecycle;
87
88
  }): Promise<string>;
88
89
  /** The package integrity owner, shared by executable snapshots and retained browser assets.
@@ -91,7 +92,7 @@ export declare function snapshotPluginModuleGraph(required: {
91
92
  export declare function verifyPluginSnapshotIntegrity(required: {
92
93
  files: ReadonlyMap<string, Uint8Array>;
93
94
  integrity: Readonly<Record<string, string>>;
94
- }, _options?: Record<string, never>): void;
95
+ }, optional?: PluginManifestReadOptions): void;
95
96
  /** Adapts the product's module seam to Jini's registry. A built-in/test seam retains its original path;
96
97
  * a site entry is contained and snapshotted only after Jini verifies integrity and SDK range.
97
98
  * Same-version replacement needs a fresh filesystem identity for ALL helpers, including late
@@ -107,7 +108,7 @@ export declare function verifyPluginSnapshotIntegrity(required: {
107
108
  export declare function createPluginModuleImporter(required: {
108
109
  manifest: PluginManifest;
109
110
  source: "built-in" | "site";
110
- }, optional?: {
111
+ }, optional?: PluginManifestReadOptions & {
111
112
  importModule?: (entryPath: string) => Promise<unknown>;
112
113
  snapshots?: PluginModuleSnapshotLifecycle;
113
114
  }): PluginModuleImportPort;
@@ -8,7 +8,7 @@ import { createHash } from "node:crypto";
8
8
  import path from "node:path";
9
9
  import { pathToFileURL } from "node:url";
10
10
  import { snapshotSitePluginPackage } from "./install.js";
11
- import { PLUGIN_MANIFEST_FILENAMES } from "../plugin-format.js";
11
+ import { pluginManifestFilenames } from "../plugin-format.js";
12
12
  import { isPluginRelativePath } from "../browser-providers.js";
13
13
  export class PluginSnapshotIntegrityError extends Error {
14
14
  }
@@ -201,7 +201,7 @@ export function createPluginModuleSnapshotLifecycle({ runtimeRoot }, { fs = nati
201
201
  */
202
202
  export async function snapshotPluginModuleGraph(required, optional = {}) {
203
203
  const files = await snapshotSitePluginPackage({ sourceDir: required.pluginRoot });
204
- verifyPluginSnapshotIntegrity({ files, integrity: required.manifest.integrity });
204
+ verifyPluginSnapshotIntegrity({ files, integrity: required.manifest.integrity }, optional);
205
205
  const cacheRoot = path.dirname(path.dirname(required.pluginRoot)) + "-runtime";
206
206
  if (optional.lifecycle) {
207
207
  if (optional.lifecycle.runtimeRoot !== path.resolve(cacheRoot))
@@ -215,10 +215,10 @@ export async function snapshotPluginModuleGraph(required, optional = {}) {
215
215
  /** The package integrity owner, shared by executable snapshots and retained browser assets.
216
216
  * @throws {PluginSnapshotIntegrityError} A retained file differs from a reviewed digest or is missing.
217
217
  */
218
- export function verifyPluginSnapshotIntegrity(required, _options = {}) {
218
+ export function verifyPluginSnapshotIntegrity(required, optional = {}) {
219
219
  const { files, integrity } = required;
220
220
  for (const [key, bytes] of files) {
221
- if (PLUGIN_MANIFEST_FILENAMES.includes(key))
221
+ if (pluginManifestFilenames({}, optional).includes(key))
222
222
  continue; // legacy alias
223
223
  const digest = `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
224
224
  if (integrity[key] !== digest)
@@ -253,7 +253,7 @@ export function createPluginModuleImporter(required, optional = {}) {
253
253
  // The immutable snapshot owner rejects symlinks/hardlinks and checks every retained byte.
254
254
  if (!entry.startsWith(root + path.sep))
255
255
  return `module path '${modulePath}' escapes the plugin root`;
256
- entryPath = await snapshotPluginModuleGraph({ pluginRoot: plugin.packageRoot, manifest: required.manifest }, optional.snapshots ? { lifecycle: optional.snapshots } : {});
256
+ entryPath = await snapshotPluginModuleGraph({ pluginRoot: plugin.packageRoot, manifest: required.manifest }, { legacyManifestFilenames: optional.legacyManifestFilenames, ...(optional.snapshots ? { lifecycle: optional.snapshots } : {}) });
257
257
  }
258
258
  const imported = await import(pathToFileURL(entryPath).href);
259
259
  return { exported: imported.default };
@@ -1,4 +1,5 @@
1
1
  import type { PluginDiscoveryRecord } from "../discovery-types.js";
2
+ import { type PluginManifestReadOptions } from "../plugin-format.js";
2
3
  export interface PluginPackageFileLimits {
3
4
  readonly maxFiles: number;
4
5
  /** Files, symlinks, and directories visited — bounds `readdir` calls on a wide, deep tree. */
@@ -76,5 +77,5 @@ export interface SitePluginPackage {
76
77
  export declare function listSitePluginPackage(required: {
77
78
  installDir: string;
78
79
  record: PluginDiscoveryRecord;
79
- }, _optional?: Record<string, never>): Promise<SitePluginPackage>;
80
+ }, optional?: PluginManifestReadOptions): Promise<SitePluginPackage>;
80
81
  //# sourceMappingURL=package-files.d.ts.map
@@ -29,7 +29,7 @@ import { lstat, open, readdir, realpath } from "node:fs/promises";
29
29
  import path from "node:path";
30
30
  import { readAtMost, readNoFollowFlags } from "./open-flags.js";
31
31
  import { isPluginRelativePath } from "../browser-providers.js";
32
- import { PLUGIN_MANIFEST_FILENAMES } from "../plugin-format.js";
32
+ import { pluginManifestFilenames } from "../plugin-format.js";
33
33
  import { sitePluginRoot } from "./discovery.js";
34
34
  /** Every packaged file is opened read-only and without following a final-component symlink. */
35
35
  const READ_NO_FOLLOW = readNoFollowFlags({ constants });
@@ -218,8 +218,8 @@ export async function readPluginPackageFiles(required, optional = {}) {
218
218
  return { files: state.files, truncated: state.truncated };
219
219
  }
220
220
  /** The manifest discovery reads (current name first, then the legacy alias), or `undefined`. */
221
- async function presentManifestName(rootReal) {
222
- for (const name of PLUGIN_MANIFEST_FILENAMES) { // legacy alias
221
+ async function presentManifestName(rootReal, optional = {}) {
222
+ for (const name of pluginManifestFilenames({}, optional)) { // legacy alias
223
223
  if (await lstat(path.join(rootReal, name)).then(() => true, (error) => errnoCode(error) === "ENOENT" ? false : Promise.reject(error)))
224
224
  return name;
225
225
  }
@@ -237,17 +237,17 @@ async function presentManifestName(rootReal) {
237
237
  * `installDir`, or has no manifest.
238
238
  * @complexity O(integrity entries) plus two `realpath`s and up to two `lstat`s.
239
239
  */
240
- export async function listSitePluginPackage(required, _optional = {}) {
240
+ export async function listSitePluginPackage(required, optional = {}) {
241
241
  const { installDir, record } = required;
242
242
  const { manifest } = record;
243
243
  if (record.source !== "site" || record.status !== "valid" || manifest === undefined) {
244
244
  throw new PluginPackagePathError(`'${record.id}' is not a valid installed site plugin`);
245
245
  }
246
- const integrity = Object.entries(manifest.integrity).filter(([key]) => !PLUGIN_MANIFEST_FILENAMES.includes(key));
246
+ const integrity = Object.entries(manifest.integrity).filter(([key]) => !pluginManifestFilenames({}, optional).includes(key));
247
247
  if (integrity.some(([key]) => !isPluginRelativePath({ path: key })))
248
248
  throw new PluginPackagePathError(`'${record.id}' lists a file outside its package`);
249
249
  const rootDir = await resolvePackageRoot(sitePluginRoot({ installDir, id: record.id, version: record.version }), installDir);
250
- const manifestName = rootDir === null ? undefined : await presentManifestName(rootDir);
250
+ const manifestName = rootDir === null ? undefined : await presentManifestName(rootDir, optional);
251
251
  if (rootDir === null || manifestName === undefined)
252
252
  throw new PluginPackagePathError(`'${record.id}' ${record.version} is not installed`);
253
253
  return {
@@ -0,0 +1,35 @@
1
+ import type { PluginDiscoveryRecord } from "../discovery-types.js";
2
+ import type { RuntimeState } from "./runtime-state.js";
3
+ /** The hook registry's failure handler: disable the plugin's live state, then write the quarantine row. */
4
+ export declare function quarantineHookFailure<E, O>({ state, input }: {
5
+ state: RuntimeState<E, O>;
6
+ input: {
7
+ pluginId: string;
8
+ workspaceId: string;
9
+ consecutiveFailures: number;
10
+ reason: string;
11
+ };
12
+ }, _options?: {}): Promise<void>;
13
+ export declare function onPluginEnabled<E, O>({ state, pluginId }: {
14
+ state: RuntimeState<E, O>;
15
+ pluginId: string;
16
+ }, _options?: {}): Promise<void>;
17
+ /** Load + attach one already-cleared plugin — `onPluginEnabled`'s body after its gates, shared
18
+ * with boot, which clears every enabled plugin in ONE pass instead (see
19
+ * `attachEnabledPluginsAtBoot`: per-plugin "candidate last" ordering would refuse the older
20
+ * winner of a boot-time pair as well as the newer one). */
21
+ export declare function attachPlugin<E, O>({ state, pluginId, record }: {
22
+ state: RuntimeState<E, O>;
23
+ pluginId: string;
24
+ record: PluginDiscoveryRecord;
25
+ }, _options?: {}): Promise<void>;
26
+ /** Shutdown: refuse new attachments, drain in-flight ones, then release the module snapshots. */
27
+ export declare function disposeRuntime<E, O>({ state, input }: {
28
+ state: RuntimeState<E, O>;
29
+ input: Parameters<NonNullable<RuntimeState<E, O>["snapshots"]>["dispose"]>[0];
30
+ }, options?: Parameters<NonNullable<RuntimeState<E, O>["snapshots"]>["dispose"]>[1]): Promise<void>;
31
+ export declare function onPluginDisabled<E, O>({ state, pluginId }: {
32
+ state: RuntimeState<E, O>;
33
+ pluginId: string;
34
+ }, _options?: {}): void;
35
+ //# sourceMappingURL=runtime-activation.d.ts.map
@@ -0,0 +1,188 @@
1
+ import { createPluginLookupFacade } from "@jini-ai/core/plugin-directory";
2
+ import { createPluginContributionCapture } from "../contributions.js";
3
+ import { enableDeclaredPlugin } from "../declarative-enable.js";
4
+ import { quarantinePlugin } from "../quarantine.js";
5
+ import { attachLoadedPlugin } from "../attach-loaded-plugin.js";
6
+ import { assertPluginInstallIdle } from "./install.js";
7
+ import { PluginSnapshotLifecycleError } from "./module-snapshot.js";
8
+ import { loadPlugin, PluginLoadError } from "./loader.js";
9
+ import { createTier2ImportSeam } from "../worker/import-seam.js";
10
+ import { resolveLoadTarget, declaresProviders, withRegisteredPackageRoot } from "./runtime-load-target.js";
11
+ import { assertNoConflicts, discoverActivePlugins } from "./runtime-conflicts.js";
12
+ /** The hook registry's failure handler: disable the plugin's live state, then write the quarantine row. */
13
+ export async function quarantineHookFailure({ state, input }, _options = {}) {
14
+ onPluginDisabled({ state, pluginId: input.pluginId });
15
+ await quarantinePlugin({ deps: state.quarantineDeps, input });
16
+ }
17
+ export async function onPluginEnabled({ state, pluginId }, _options = {}) {
18
+ const { installDir, required, optional, runtimeBinding } = state;
19
+ // A package replacement and an enable cannot race: save-before-callback activation is
20
+ // compensated if install owns the directory lock, while installs refuse an enabled row.
21
+ if (installDir !== undefined)
22
+ await assertPluginInstallIdle({ installDir });
23
+ const discovery = await discoverActivePlugins({ state });
24
+ const record = discovery.find((candidate) => candidate.id === pluginId);
25
+ if (!record) {
26
+ throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
27
+ }
28
+ await assertNoConflicts({ state, pluginId, discovery });
29
+ // Provider plugins initialize once, at boot, before application work (`loadProviderPlugins`).
30
+ if (declaresProviders({ manifest: record.manifest }))
31
+ return undefined;
32
+ // No manifest ⇒ an invalid record: `attachPlugin`'s own fail-closed path reports it.
33
+ if (!record.manifest)
34
+ return attachPlugin({ state, pluginId, record });
35
+ // Declared contributions (AW-7 Tier 1) are applied only now, after the conflict gate; a tier-1
36
+ // plugin's `loadCode` is never called.
37
+ await enableDeclaredPlugin({ ...runtimeBinding, pluginId, workspaceId: required.workspaceId, manifest: record.manifest, loadCode: () => attachPlugin({ state, pluginId, record }), unloadCode: () => onPluginDisabled({ state, pluginId }) }, optional.declaredContentTypes ? { contentTypes: optional.declaredContentTypes } : {});
38
+ state.loadedVersions.set(pluginId, record.version);
39
+ return undefined;
40
+ }
41
+ /** Load + attach one already-cleared plugin — `onPluginEnabled`'s body after its gates, shared
42
+ * with boot, which clears every enabled plugin in ONE pass instead (see
43
+ * `attachEnabledPluginsAtBoot`: per-plugin "candidate last" ordering would refuse the older
44
+ * winner of a boot-time pair as well as the newer one). */
45
+ export function attachPlugin({ state, pluginId, record }, _options = {}) {
46
+ if (state.closing)
47
+ return Promise.reject(new PluginSnapshotLifecycleError({ code: "SNAPSHOTS_CLOSED" }));
48
+ const attachment = performPluginAttachment({ state, pluginId, record });
49
+ state.pendingAttachments.add(attachment);
50
+ void attachment.then(() => state.pendingAttachments.delete(attachment), () => state.pendingAttachments.delete(attachment));
51
+ return attachment;
52
+ }
53
+ /** Shutdown: refuse new attachments, drain in-flight ones, then release the module snapshots. */
54
+ export async function disposeRuntime({ state, input }, options = {}) {
55
+ state.closing = true;
56
+ await Promise.allSettled([...state.pendingAttachments]);
57
+ await state.snapshots?.dispose(input, options);
58
+ }
59
+ /** Keep import and setup in the same shutdown drain: setup may make late graph imports too. */
60
+ async function performPluginAttachment({ state, pluginId, record }, _options = {}) {
61
+ const { epoch, target, invocation, capture } = beginAttachment({ state, pluginId, record });
62
+ const { manifest, attachmentSource } = target;
63
+ const sdkSlot = { sdk: undefined };
64
+ const result = await loadPlugin(buildLoadInput({ state, record, target, invocation, capture, sdkSlot }), state.runtimeBinding);
65
+ if (!result.loaded) {
66
+ throw new PluginLoadError(pluginId, result.reason);
67
+ }
68
+ // A disable or a newer load during import/setup must not resurrect the retired generation.
69
+ const scopedSdk = assertAttachmentCurrent({ state, pluginId, epoch, scopedSdk: sdkSlot.sdk });
70
+ const contributions = capture.seal({ sdk: scopedSdk });
71
+ const filter = invocation.capturedFilter();
72
+ assertBeforeSaveFilterAttached({ state, pluginId, manifest, filter });
73
+ publishPluginAttachment({ state, pluginId, manifest, attachmentSource, filter, contributions,
74
+ providers: result.browserProviders ?? [], version: record.version });
75
+ }
76
+ /** Bump the load epoch (retiring any older generation), then resolve what to load. */
77
+ function beginAttachment({ state, pluginId, record }, _options = {}) {
78
+ const epoch = (state.loadEpochs.get(pluginId) ?? 0) + 1;
79
+ state.loadEpochs.set(pluginId, epoch);
80
+ const target = resolveLoadTarget({ pluginId, sources: state.required.sources, record, installDir: state.installDir });
81
+ if (!target) {
82
+ throw new PluginLoadError(pluginId, "PLUGIN_EXPORT_INVALID");
83
+ }
84
+ // The SDK backing (content.read/extend bound to the running filter, single declared beforeSave
85
+ // filter) is shared with the Tier-2 worker — see `invocation-core-deps.ts`.
86
+ const invocation = state.runtimeBinding.createInvocationCoreDeps({ pluginId, declaredHooks: target.manifest.hooks });
87
+ const capture = createPluginContributionCapture({ manifest: target.manifest });
88
+ return { epoch, target, invocation, capture };
89
+ }
90
+ /** The `loadPlugin` argument for one attachment. `sdkSlot` receives the scoped SDK the plugin was built with. */
91
+ function buildLoadInput({ state, record, target, invocation, capture, sdkSlot }, _options = {}) {
92
+ const { runtimeBinding, optional } = state;
93
+ const { manifest, entryPath } = target;
94
+ const coreDeps = { ...invocation.coreDeps, contributions: capture };
95
+ // The importer FACTORY runs here, before loadPlugin's integrity/sdkRange checks, so
96
+ // it must stay inert; loadPlugin invokes the returned importer only after those checks. A site
97
+ // target takes the contained immutable snapshot; built-in seams retain their original path.
98
+ const moduleImporter = resolveRuntimeImporter({ state, target, record });
99
+ return { ...runtimeBinding, record, manifest, entryPath, coreDeps, importModule: moduleImporter,
100
+ browserProviderApprovals: optional.browserProviderApprovals ?? [],
101
+ providerContributions: { registry: state.providerContributions, isSelected: ({ pluginId: id }) => state.selectedProviders.has(id) },
102
+ pluginSdkBinding: { ...runtimeBinding.pluginSdkBinding,
103
+ buildSdk: ({ sdk }) => {
104
+ const host = optional.lookup?.();
105
+ sdkSlot.sdk = { ...runtimeBinding.pluginSdkBinding.buildSdk({ sdk }),
106
+ ...(host ? { plugins: createPluginLookupFacade({ lookup: host }) } : {}),
107
+ };
108
+ return sdkSlot.sdk;
109
+ },
110
+ },
111
+ };
112
+ }
113
+ /** Decision: the attachment is still the newest generation and produced an SDK, else the setup failed. */
114
+ function assertAttachmentCurrent({ state, pluginId, epoch, scopedSdk }, _options = {}) {
115
+ if (state.loadEpochs.get(pluginId) !== epoch || !scopedSdk)
116
+ throw new PluginLoadError(pluginId, 'PLUGIN_SETUP_FAILED');
117
+ return scopedSdk;
118
+ }
119
+ /** Decision: a plugin that declares the beforeSave hook must actually have attached its filter. */
120
+ function assertBeforeSaveFilterAttached({ state, pluginId, manifest, filter }, _options = {}) {
121
+ if (manifest.hooks.includes(state.required.pluginSdkBinding.beforeSaveHook) && filter === null) {
122
+ throw new PluginLoadError(pluginId, "PLUGIN_HOOK_NOT_ATTACHED");
123
+ }
124
+ }
125
+ function resolveRuntimeImporter({ state, target, record }, _options = {}) {
126
+ const { snapshots } = state;
127
+ // Tier 2: the plugin's code must never be imported into this process. Its
128
+ // import seam probes it in a fresh worker and hands `loadPlugin()` a proxy whose filter is an
129
+ // RPC; supplied as `loadPlugin()`'s required `importModule` port, so integrity + sdkRange
130
+ // still run first. Only a built-in reaches here as tier-2: discovery marks a site
131
+ // tier-2 package invalid (the worker is no sandbox yet). Were site tier-2 ever allowed, its worker
132
+ // would need the seam's `resolveWorkerEntry` pointed at the integrity-checked module snapshot,
133
+ // since an injected worker seam bypasses the host's default snapshot importer.
134
+ return target.manifest.tier === "tier-2"
135
+ ? withRegisteredPackageRoot({ importModule: createTier2ImportSeam({ ...state.runtimeBinding, manifest: target.manifest, runCall: state.required.tier2CallRunner }), packageRoot: target.packageRoot })
136
+ : state.required.createModuleImporter({ manifest: target.manifest, source: record.source }, {
137
+ legacyManifestFilenames: state.runtimeBinding.legacyManifestFilenames,
138
+ ...(target.importModule === undefined ? {} : { importModule: target.importModule }),
139
+ ...(snapshots === undefined ? {} : { snapshots }),
140
+ });
141
+ }
142
+ function publishPluginAttachment({ state, pluginId, manifest, attachmentSource, filter, contributions, providers, version }, _options = {}) {
143
+ const { hookRegistry, pluginContributions, loadedVersions } = state;
144
+ if (filter === null) {
145
+ pluginContributions.replace({ contributions });
146
+ retainBrowserProviders({ state, pluginId, providers });
147
+ hookRegistry.detach({ pluginId });
148
+ loadedVersions.set(pluginId, version);
149
+ return;
150
+ }
151
+ try {
152
+ attachLoadedPlugin({
153
+ pluginId,
154
+ source: attachmentSource,
155
+ hookRegistry,
156
+ filter,
157
+ declaredFields: manifest.fields,
158
+ });
159
+ pluginContributions.replace({ contributions });
160
+ retainBrowserProviders({ state, pluginId, providers });
161
+ loadedVersions.set(pluginId, version);
162
+ }
163
+ catch (error) {
164
+ hookRegistry.detach({ pluginId });
165
+ throw new PluginLoadError(pluginId, "PLUGIN_HOOK_ATTACH_FAILED", { cause: error });
166
+ }
167
+ }
168
+ /** Publish admission only after successful attachment; no partial setup can leak assets.
169
+ * @complexity O(1) map replacement; Jini already owns the immutable asset bytes.
170
+ */
171
+ function retainBrowserProviders({ state, pluginId, providers }, _options = {}) {
172
+ if (providers.length === 0 && !state.browserProviders.has(pluginId))
173
+ return;
174
+ state.browserProviders.set(pluginId, providers);
175
+ state.browserGeneration++;
176
+ }
177
+ export function onPluginDisabled({ state, pluginId }, _options = {}) {
178
+ if (state.browserProviders.delete(pluginId))
179
+ state.browserGeneration++;
180
+ state.loadEpochs.set(pluginId, (state.loadEpochs.get(pluginId) ?? 0) + 1);
181
+ state.pluginContributions.detach({ pluginId });
182
+ // Retires the provider generation: the provider host disposes its initialized resources.
183
+ state.selectedProviders.delete(pluginId);
184
+ state.providerContributions.detach({ pluginId });
185
+ state.hookRegistry.detach({ pluginId });
186
+ state.loadedVersions.delete(pluginId);
187
+ }
188
+ //# sourceMappingURL=runtime-activation.js.map
@@ -0,0 +1,16 @@
1
+ import type { RuntimeState } from "./runtime-state.js";
2
+ type RuntimeArgs<E, O> = {
3
+ state: RuntimeState<E, O>;
4
+ };
5
+ export declare function attachEnabledPluginsAtBoot<E, O>({ state }: RuntimeArgs<E, O>, _options?: {}): Promise<void>;
6
+ export declare function listProviderPlugins<E, O>({ state }: RuntimeArgs<E, O>, _options?: {}): Promise<{
7
+ pluginId: string;
8
+ providers: readonly import("@jini-ai/core/contracts/plugin-sdk").PluginProviderDeclaration[];
9
+ }[]>;
10
+ export declare function loadProviderPlugins<E, O>({ state, pluginIds }: RuntimeArgs<E, O> & {
11
+ pluginIds: readonly string[];
12
+ }, options?: {
13
+ timeoutMs?: number;
14
+ }): Promise<readonly string[]>;
15
+ export {};
16
+ //# sourceMappingURL=runtime-boot.d.ts.map