@jini-ai/plugins 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/LICENSE +201 -0
  3. package/README.md +60 -2
  4. package/dist/glue/attachment-points/content-lifecycle.d.ts +52 -0
  5. package/dist/glue/attachment-points/content-lifecycle.js +15 -0
  6. package/dist/glue/attachment-points/events.d.ts +12 -0
  7. package/dist/glue/attachment-points/events.js +5 -0
  8. package/dist/glue/attachment-points/tool-registration.d.ts +23 -0
  9. package/dist/glue/attachment-points/tool-registration.js +43 -0
  10. package/dist/glue/capability-gate.d.ts +73 -0
  11. package/dist/glue/capability-gate.js +41 -0
  12. package/dist/glue/dispatch.d.ts +20 -0
  13. package/dist/glue/dispatch.js +9 -0
  14. package/dist/glue/index.d.ts +8 -0
  15. package/dist/glue/index.js +8 -0
  16. package/dist/glue/manifest.d.ts +43 -0
  17. package/dist/glue/manifest.js +106 -0
  18. package/dist/glue/ports.d.ts +60 -0
  19. package/dist/glue/ports.js +2 -0
  20. package/dist/host/activation.d.ts +118 -0
  21. package/dist/host/activation.js +104 -0
  22. package/dist/host/attach-loaded-plugin.d.ts +37 -0
  23. package/dist/host/attach-loaded-plugin.js +19 -0
  24. package/dist/host/capability-sdk.d.ts +74 -0
  25. package/dist/host/capability-sdk.js +94 -0
  26. package/dist/host/claim-conflicts.d.ts +101 -0
  27. package/dist/host/claim-conflicts.js +139 -0
  28. package/dist/host/contributions.d.ts +129 -0
  29. package/dist/host/contributions.js +167 -0
  30. package/dist/host/declarative-enable.d.ts +43 -0
  31. package/dist/host/declarative-enable.js +73 -0
  32. package/dist/host/discovery-types.d.ts +55 -0
  33. package/dist/host/discovery-types.js +2 -0
  34. package/dist/host/errors.d.ts +20 -0
  35. package/dist/host/errors.js +22 -0
  36. package/dist/host/hook-registry.d.ts +113 -0
  37. package/dist/host/hook-registry.js +190 -0
  38. package/dist/host/index.d.ts +19 -0
  39. package/dist/host/index.js +19 -0
  40. package/dist/host/manifest.d.ts +159 -0
  41. package/dist/host/manifest.js +417 -0
  42. package/dist/host/node/discovery.d.ts +32 -0
  43. package/dist/host/node/discovery.js +241 -0
  44. package/dist/host/node/index.d.ts +8 -0
  45. package/dist/host/node/index.js +8 -0
  46. package/dist/host/node/install.d.ts +118 -0
  47. package/dist/host/node/install.js +431 -0
  48. package/dist/host/node/loader.d.ts +55 -0
  49. package/dist/host/node/loader.js +146 -0
  50. package/dist/host/node/module-snapshot.d.ts +25 -0
  51. package/dist/host/node/module-snapshot.js +53 -0
  52. package/dist/host/node/package-files.d.ts +52 -0
  53. package/dist/host/node/package-files.js +214 -0
  54. package/dist/host/node/source-drafts.d.ts +98 -0
  55. package/dist/host/node/source-drafts.js +323 -0
  56. package/dist/host/plugin-claims.d.ts +75 -0
  57. package/dist/host/plugin-claims.js +182 -0
  58. package/dist/host/ports.d.ts +208 -0
  59. package/dist/host/ports.js +2 -0
  60. package/dist/host/quarantine.d.ts +19 -0
  61. package/dist/host/quarantine.js +28 -0
  62. package/dist/host/repo.memory.d.ts +27 -0
  63. package/dist/host/repo.memory.js +33 -0
  64. package/dist/host/source-policy.d.ts +18 -0
  65. package/dist/host/source-policy.js +13 -0
  66. package/dist/host/sql/index.d.ts +4 -0
  67. package/dist/host/sql/index.js +4 -0
  68. package/dist/host/sql/repo.d.ts +38 -0
  69. package/dist/host/sql/repo.js +50 -0
  70. package/dist/host/sql/repo.rows.d.ts +28 -0
  71. package/dist/host/sql/repo.rows.js +28 -0
  72. package/dist/host/tool-contributions.d.ts +26 -0
  73. package/dist/host/tool-contributions.js +42 -0
  74. package/dist/host/uninstall.d.ts +88 -0
  75. package/dist/host/uninstall.js +112 -0
  76. package/dist/host/worker/import-seam.d.ts +45 -0
  77. package/dist/host/worker/import-seam.js +52 -0
  78. package/dist/host/worker/index.d.ts +5 -0
  79. package/dist/host/worker/index.js +5 -0
  80. package/dist/host/worker/protocol.d.ts +62 -0
  81. package/dist/host/worker/protocol.js +31 -0
  82. package/dist/host/worker/run-call.d.ts +27 -0
  83. package/dist/host/worker/run-call.js +76 -0
  84. package/package.json +107 -3
@@ -0,0 +1,88 @@
1
+ import type { PluginActivationRepoPort } from "./activation.js";
2
+ import type { PluginDiscoveryRecord } from "./discovery-types.js";
3
+ import type { RemoveEntity } from "./ports.js";
4
+ /** A built-in plugin has no on-disk artifact — there is nothing for `DELETE .../plugins/:id` to
5
+ * remove. Distinct from `PluginNotFoundError` (id doesn't exist at all) so the route can map each
6
+ * to its own status code (mirrors `PluginInvalidError`/`PluginIncompatibleError` both being
7
+ * distinct from `PluginNotFoundError` in `activation.ts`). */
8
+ export declare class PluginNotUninstallableError extends Error {
9
+ }
10
+ /** The plugin is currently enabled in at least one workspace. Since the on-disk artifact is
11
+ * instance-wide (shared across every workspace this `installDir` serves), uninstalling while ANY
12
+ * workspace still has it enabled would silently break that workspace's runtime. */
13
+ export declare class PluginEnabledError extends Error {
14
+ }
15
+ /** The plugin a human confirmed uninstalling is no longer the name and version discovery reports — see
16
+ * `UninstallPluginOptional.confirmedPreview`. Nothing was removed. */
17
+ export declare class PluginChangedSincePreviewError extends Error {
18
+ }
19
+ export declare class PluginAlreadyInTrashError extends Error {
20
+ }
21
+ export type RemovePluginFn = RemoveEntity;
22
+ export interface UninstallPluginDeps {
23
+ readonly repo: PluginActivationRepoPort;
24
+ /** Caller-supplied fresh discovery snapshot — same convention as `SetPluginEnabledDeps.discovery`
25
+ * (`activation.ts`): this function evaluates preconditions over an already-known snapshot rather
26
+ * than calling discovery itself, so it stays deterministic and testable without a real
27
+ * filesystem scan. */
28
+ readonly discovery: readonly PluginDiscoveryRecord[];
29
+ readonly remove: RemovePluginFn;
30
+ }
31
+ export interface UninstallPluginInput {
32
+ readonly pluginId: string;
33
+ readonly workspaceId: string;
34
+ readonly at: string;
35
+ readonly actor: {
36
+ principalId: string;
37
+ pluginId?: string | null;
38
+ };
39
+ }
40
+ export interface UninstallPluginRequired {
41
+ deps: UninstallPluginDeps;
42
+ input: UninstallPluginInput;
43
+ }
44
+ export interface UninstallPluginOptional {
45
+ /** The preview a human confirmed. When given, the uninstall refuses before `remove` (so nothing is removed)
46
+ * unless the record it resolves still has the previewed name and version (t91 F2.2). The admin HTTP route has no
47
+ * gap between showing and removing, and omits it. */
48
+ readonly confirmedPreview?: PluginUninstallPreview;
49
+ }
50
+ export interface UninstallPluginResult {
51
+ readonly trashed: true;
52
+ }
53
+ /** What a human confirmation dialog needs to describe truthfully what is about to be removed.
54
+ * Mirrors `agent-plugins/uninstall.ts`'s own `AgentPluginUninstallPreview` for the sibling family,
55
+ * for the identical reason: the preview carries no host path, only the fields a dialog may say out
56
+ * loud. */
57
+ export interface PluginUninstallPreview {
58
+ readonly pluginId: string;
59
+ readonly name: string;
60
+ readonly version: string;
61
+ }
62
+ /**
63
+ * Evaluates `uninstallPlugin()`'s preconditions and returns what a confirmation dialog needs to name
64
+ * — performing no mutation, so a caller can raise that dialog only once the target is known-good.
65
+ *
66
+ * @throws {PluginNotFoundError} `required.input.pluginId` is absent from `deps.discovery`.
67
+ * @throws {PluginNotUninstallableError} the discovered record's `source` is `"built-in"`.
68
+ * @throws {PluginEnabledError} the plugin is enabled in one or more workspaces.
69
+ * @complexity O(activation rows for this plugin) — delegates to `resolveUninstallTarget`.
70
+ */
71
+ export declare function previewUninstallPlugin(required: UninstallPluginRequired, _optional?: Record<string, never>): Promise<PluginUninstallPreview>;
72
+ /**
73
+ * Moves a site-installed plugin to Trash. Activation rows stay in place until permanent purge.
74
+ *
75
+ * @throws {PluginNotFoundError} `input.pluginId` is absent from `deps.discovery`.
76
+ * @throws {PluginNotUninstallableError} the discovered record's `source` is `"built-in"`.
77
+ * @throws {PluginEnabledError} the plugin is enabled in one or more workspaces.
78
+ * @throws {PluginChangedSincePreviewError} `optional.confirmedPreview` was given and the record's name or version differs from it.
79
+ * @complexity O(activation rows for this plugin) plus one delegated remove.
80
+ */
81
+ export declare function uninstallPlugin(required: UninstallPluginRequired, optional?: UninstallPluginOptional): Promise<UninstallPluginResult>;
82
+ export declare function forgetPluginActivations(required: {
83
+ pluginId: string;
84
+ deps: {
85
+ repo: PluginActivationRepoPort;
86
+ };
87
+ }, _optional?: Record<string, never>): Promise<void>;
88
+ //# sourceMappingURL=uninstall.d.ts.map
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @file Site-plugin removal policy. Removal moves package files to the shared Trash adapter;
3
+ * activation rows remain until permanent purge so restore brings the plugin back disabled.
4
+ */
5
+ import { PluginNotFoundError } from "./activation.js";
6
+ /** A built-in plugin has no on-disk artifact — there is nothing for `DELETE .../plugins/:id` to
7
+ * remove. Distinct from `PluginNotFoundError` (id doesn't exist at all) so the route can map each
8
+ * to its own status code (mirrors `PluginInvalidError`/`PluginIncompatibleError` both being
9
+ * distinct from `PluginNotFoundError` in `activation.ts`). */
10
+ export class PluginNotUninstallableError extends Error {
11
+ }
12
+ /** The plugin is currently enabled in at least one workspace. Since the on-disk artifact is
13
+ * instance-wide (shared across every workspace this `installDir` serves), uninstalling while ANY
14
+ * workspace still has it enabled would silently break that workspace's runtime. */
15
+ export class PluginEnabledError extends Error {
16
+ }
17
+ /** The plugin a human confirmed uninstalling is no longer the name and version discovery reports — see
18
+ * `UninstallPluginOptional.confirmedPreview`. Nothing was removed. */
19
+ export class PluginChangedSincePreviewError extends Error {
20
+ }
21
+ export class PluginAlreadyInTrashError extends Error {
22
+ }
23
+ /**
24
+ * Evaluates `uninstallPlugin()`'s two preconditions with no mutation. Factored out so
25
+ * `previewUninstallPlugin` (below) and `uninstallPlugin` share exactly one place these rules are
26
+ * expressed, and so a refusal reaches a caller BEFORE it asks a human to confirm anything — asking
27
+ * "uninstall this?" about a built-in or still-enabled plugin would be a dialog with no honest
28
+ * "yes" behind it.
29
+ *
30
+ * @throws {PluginNotFoundError} `pluginId` is absent from `deps.discovery`.
31
+ * @throws {PluginNotUninstallableError} the discovered record's `source` is `"built-in"`.
32
+ * @throws {PluginEnabledError} the plugin is enabled in one or more workspaces.
33
+ * @complexity O(activation rows for this plugin) — one `listAll()` scan (bounded by total
34
+ * activation rows in this instance).
35
+ */
36
+ async function resolveUninstallTarget(deps, pluginId) {
37
+ const record = deps.discovery.find((candidate) => candidate.id === pluginId);
38
+ if (!record) {
39
+ throw new PluginNotFoundError(`plugin '${pluginId}' was not found in the current discovery snapshot`);
40
+ }
41
+ if (record.source === "built-in") {
42
+ throw new PluginNotUninstallableError(`plugin '${pluginId}' is a built-in plugin and cannot be uninstalled`);
43
+ }
44
+ const allActivations = await deps.repo.listAll();
45
+ const matching = allActivations.filter((activation) => activation.pluginId === pluginId);
46
+ if (matching.some((activation) => activation.enabled)) {
47
+ throw new PluginEnabledError(`plugin '${pluginId}' is enabled in at least one workspace and must be disabled everywhere before it can be uninstalled`);
48
+ }
49
+ return { record };
50
+ }
51
+ /**
52
+ * Evaluates `uninstallPlugin()`'s preconditions and returns what a confirmation dialog needs to name
53
+ * — performing no mutation, so a caller can raise that dialog only once the target is known-good.
54
+ *
55
+ * @throws {PluginNotFoundError} `required.input.pluginId` is absent from `deps.discovery`.
56
+ * @throws {PluginNotUninstallableError} the discovered record's `source` is `"built-in"`.
57
+ * @throws {PluginEnabledError} the plugin is enabled in one or more workspaces.
58
+ * @complexity O(activation rows for this plugin) — delegates to `resolveUninstallTarget`.
59
+ */
60
+ export async function previewUninstallPlugin(required, _optional = {}) {
61
+ const { record } = await resolveUninstallTarget(required.deps, required.input.pluginId);
62
+ return { pluginId: record.id, name: record.name, version: record.version };
63
+ }
64
+ /**
65
+ * Moves a site-installed plugin to Trash. Activation rows stay in place until permanent purge.
66
+ *
67
+ * @throws {PluginNotFoundError} `input.pluginId` is absent from `deps.discovery`.
68
+ * @throws {PluginNotUninstallableError} the discovered record's `source` is `"built-in"`.
69
+ * @throws {PluginEnabledError} the plugin is enabled in one or more workspaces.
70
+ * @throws {PluginChangedSincePreviewError} `optional.confirmedPreview` was given and the record's name or version differs from it.
71
+ * @complexity O(activation rows for this plugin) plus one delegated remove.
72
+ */
73
+ export async function uninstallPlugin(required, optional = {}) {
74
+ const { deps, input } = required;
75
+ const { record } = await resolveUninstallTarget(deps, input.pluginId);
76
+ assertUnchangedSincePreview(record, optional.confirmedPreview);
77
+ const result = await deps.remove({
78
+ workspaceId: input.workspaceId,
79
+ id: input.pluginId,
80
+ display: { title: record.name, subtitle: `${record.id} ${record.version}` },
81
+ at: input.at,
82
+ expectedVersion: null,
83
+ actor: input.actor,
84
+ });
85
+ if (result.ok)
86
+ return { trashed: true };
87
+ if (result.reason === "blocked") {
88
+ throw new PluginAlreadyInTrashError(`plugin '${input.pluginId}' is already in the Trash`);
89
+ }
90
+ throw new PluginNotFoundError(`plugin '${input.pluginId}' was not found while moving it to the Trash`);
91
+ }
92
+ export async function forgetPluginActivations(required, _optional = {}) {
93
+ for (const activation of await required.deps.repo.listAll()) {
94
+ if (activation.pluginId === required.pluginId) {
95
+ await required.deps.repo.deleteActivation({ workspaceId: activation.workspaceId, pluginId: required.pluginId });
96
+ }
97
+ }
98
+ }
99
+ /**
100
+ * Refuses when the record resolved now does not carry the name and version the confirmed preview showed.
101
+ * @throws {PluginChangedSincePreviewError} Name or version differs.
102
+ * @complexity O(1).
103
+ */
104
+ function assertUnchangedSincePreview(record, confirmedPreview) {
105
+ if (confirmedPreview === undefined)
106
+ return;
107
+ if (record.name === confirmedPreview.name && record.version === confirmedPreview.version)
108
+ return;
109
+ throw new PluginChangedSincePreviewError(`plugin '${record.id}' changed after its uninstall was previewed (previewed ${confirmedPreview.name} ${confirmedPreview.version}; ` +
110
+ `now ${record.name} ${record.version}) — nothing was removed`);
111
+ }
112
+ //# sourceMappingURL=uninstall.js.map
@@ -0,0 +1,45 @@
1
+ /** The required SDK binding supplies hook ids and definePlugin. The importer accepts the
2
+ * shared contribution-loader object contract and yields { exported }. */
3
+ /**
4
+ * @file `createTier2ImportSeam()` — the `importModule` a Tier-2 plugin's `loadPlugin()` call is
5
+ * given (ADR-024 §3/§4). It never imports the plugin's code into the server process. Instead it
6
+ * probes the plugin in a fresh worker (import + setup + report attached hooks) and returns a
7
+ * PROXY `definePlugin()` module whose `setup()` attaches an RPC filter: each filter call is one
8
+ * more fresh worker that imports, sets up, runs the real filter and replies.
9
+ *
10
+ * Injected through `loadPlugin()`'s own `importModule` option, so CIC U-001 is untouched: integrity
11
+ * and sdkRange are verified before this function is ever called (it IS step 3), and the proxy then
12
+ * goes through the same export validation, capability-scoped `setup()` and attach path as an
13
+ * in-process plugin. Probe failures are mapped onto the loader's own reasons rather than new ones:
14
+ * a failed import rejects (`CODE_ENTRY_MISSING`), a missing export returns a module without one
15
+ * (`PLUGIN_EXPORT_INVALID`), a failed setup returns a proxy whose setup throws (`PLUGIN_SETUP_FAILED`).
16
+ *
17
+ * A failed or timed-out filter call throws, so `hook-registry.ts` fails the save closed and counts
18
+ * the failure toward quarantine exactly as it does for a throwing Tier-3 filter.
19
+ */
20
+ import type { PluginSdkBinding, PluginModuleImportPort } from "../ports.js";
21
+ import type { PluginManifest } from "../manifest.js";
22
+ import type { Tier2CallRunner } from "./protocol.js";
23
+ export interface CreateTier2ImportSeamRequired {
24
+ readonly pluginSdkBinding: PluginSdkBinding;
25
+ /** The loader-validated manifest; its id, capabilities and hooks are what the worker enforces. */
26
+ readonly manifest: PluginManifest;
27
+ /** Runs one request in a fresh isolated worker (`server/runtime/plugin-tier2/run-in-worker.ts`). */
28
+ readonly runCall: Tier2CallRunner;
29
+ }
30
+ export interface CreateTier2ImportSeamOptional {
31
+ /** Maps the loader's entry path to what the worker imports. A site plugin passes its
32
+ * integrity-checked module snapshot here (the loader skips its own snapshot when an import seam
33
+ * is injected); a built-in omits it and the worker imports `entryPath` itself. */
34
+ readonly resolveWorkerEntry?: (required: {
35
+ entryPath: string;
36
+ }, optional?: Record<string, never>) => Promise<string>;
37
+ }
38
+ /**
39
+ * Builds the Tier-2 `importModule` seam for one plugin load.
40
+ *
41
+ * @returns An importer resolving to a proxy module; see the file header for the failure mapping.
42
+ * @complexity O(1) plus one worker round trip per import and per filter call.
43
+ */
44
+ export declare function createTier2ImportSeam(required: CreateTier2ImportSeamRequired, optional?: CreateTier2ImportSeamOptional): PluginModuleImportPort;
45
+ //# sourceMappingURL=import-seam.d.ts.map
@@ -0,0 +1,52 @@
1
+ function invalidReply() {
2
+ return new Error("invalid tier-2 worker reply");
3
+ }
4
+ /**
5
+ * Builds the Tier-2 `importModule` seam for one plugin load.
6
+ *
7
+ * @returns An importer resolving to a proxy module; see the file header for the failure mapping.
8
+ * @complexity O(1) plus one worker round trip per import and per filter call.
9
+ */
10
+ export function createTier2ImportSeam(required, optional = {}) {
11
+ const { manifest, runCall, pluginSdkBinding } = required;
12
+ const HOOK_CONTENT_ENTRY_BEFORE_SAVE = pluginSdkBinding.beforeSaveHook;
13
+ const definePlugin = (definition) => pluginSdkBinding.definePlugin(definition);
14
+ return async ({ modulePath: entryPath }) => {
15
+ const plugin = {
16
+ pluginId: manifest.id,
17
+ entryPath: optional.resolveWorkerEntry ? await optional.resolveWorkerEntry({ entryPath }) : entryPath,
18
+ // Same cast `loadPlugin()` makes: validateManifest() has already checked every token.
19
+ capabilities: manifest.capabilities,
20
+ hooks: manifest.hooks,
21
+ };
22
+ const probe = await runCall({ kind: "probe", plugin });
23
+ if (!probe.ok) {
24
+ if (probe.stage === "import")
25
+ throw new Error(probe.error);
26
+ if (probe.stage === "export")
27
+ return { exported: {} };
28
+ return { exported: definePlugin({ setup() { throw new Error(probe.error); } }) };
29
+ }
30
+ if (probe.kind !== "probe")
31
+ throw invalidReply();
32
+ const attachesBeforeSave = probe.hooks.includes(HOOK_CONTENT_ENTRY_BEFORE_SAVE);
33
+ return {
34
+ exported: definePlugin({
35
+ setup(sdk) {
36
+ if (!attachesBeforeSave)
37
+ return;
38
+ sdk.addFilter(HOOK_CONTENT_ENTRY_BEFORE_SAVE, async (entry, ctx) => {
39
+ const reply = await runCall({ kind: "beforeSave", plugin, entry, ctx });
40
+ if (!reply.ok)
41
+ throw new Error(reply.error);
42
+ if (reply.kind !== "beforeSave")
43
+ throw invalidReply();
44
+ // hook-registry validates the patch against the manifest's declared fields (BR-06).
45
+ return reply.patch;
46
+ });
47
+ },
48
+ }),
49
+ };
50
+ };
51
+ }
52
+ //# sourceMappingURL=import-seam.js.map
@@ -0,0 +1,5 @@
1
+ /** Worker ABI and injected executable materialization. */
2
+ export * from './import-seam.js';
3
+ export * from './protocol.js';
4
+ export * from './run-call.js';
5
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ /** Worker ABI and injected executable materialization. */
2
+ export * from './import-seam.js';
3
+ export * from './protocol.js';
4
+ export * from './run-call.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,62 @@
1
+ /**
2
+ * @file The Tier-2 plugin ABI wire protocol (ADR-024 §3/§4): what the server sends a fresh worker
3
+ * for one call, and what the worker replies. Both directions are structured-clone-only data — no
4
+ * functions, no class instances, no live core objects — because they cross a `worker_threads`
5
+ * boundary, and because the same messages must later cross a real process sandbox unchanged.
6
+ *
7
+ * One request = one fresh worker: import the plugin, run `setup()` against a fresh
8
+ * capability-scoped SDK, then either report which hooks it attached (`probe`, run once at enable
9
+ * time) or run its beforeSave filter on one entry (`beforeSave`, run per save/preview).
10
+ */
11
+ import type { ContentEntryDraft, HookContext } from "../ports.js";
12
+ import type { PluginCapability } from "../manifest.js";
13
+ /** Everything the worker needs to know about the plugin — taken from the already-validated
14
+ * manifest on the server side; the worker never reads a manifest itself. */
15
+ export interface Tier2PluginRef {
16
+ readonly pluginId: string;
17
+ /** Absolute file path or `file:` URL of the code the worker imports (a site plugin's integrity-
18
+ * checked module snapshot, a built-in's own file). */
19
+ readonly entryPath: string;
20
+ readonly capabilities: readonly PluginCapability[];
21
+ readonly hooks: readonly string[];
22
+ }
23
+ export type Tier2Request = {
24
+ readonly kind: "probe";
25
+ readonly plugin: Tier2PluginRef;
26
+ } | {
27
+ readonly kind: "beforeSave";
28
+ readonly plugin: Tier2PluginRef;
29
+ readonly entry: Readonly<ContentEntryDraft>;
30
+ readonly ctx: HookContext;
31
+ };
32
+ /** Where a failed call stopped. `import` and `export` map to `loadPlugin()`'s `CODE_ENTRY_MISSING`
33
+ * and `PLUGIN_EXPORT_INVALID`, `setup` to `PLUGIN_SETUP_FAILED`, `hook` to a failed filter run. */
34
+ export type Tier2FailureStage = "import" | "export" | "setup" | "hook";
35
+ export type Tier2Reply = {
36
+ readonly ok: true;
37
+ readonly kind: "probe";
38
+ readonly hooks: readonly string[];
39
+ } | {
40
+ readonly ok: true;
41
+ readonly kind: "beforeSave";
42
+ readonly patch: unknown;
43
+ } | {
44
+ readonly ok: false;
45
+ readonly stage: Tier2FailureStage;
46
+ readonly error: string;
47
+ };
48
+ /** Runs one Tier-2 request somewhere isolated and resolves to the worker's reply. Rejects on a
49
+ * transport failure (timeout, crash, heap limit, malformed reply). */
50
+ export type Tier2CallRunner = (request: Tier2Request) => Promise<Tier2Reply>;
51
+ /**
52
+ * Validates an untrusted worker message as the reply to a request of `expectedKind`. The worker
53
+ * runs plugin code, so its message is checked like any other external input.
54
+ *
55
+ * @throws Error `invalid tier-2 worker reply` for any other shape, or a success of the wrong kind.
56
+ * @complexity O(h) for h reported hook names.
57
+ */
58
+ export declare function decodeTier2Reply({ message, expectedKind }: {
59
+ message: unknown;
60
+ expectedKind: Tier2Request["kind"];
61
+ }, _optional?: Record<string, never>): Tier2Reply;
62
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1,31 @@
1
+ const FAILURE_STAGES = new Set(["import", "export", "setup", "hook"]);
2
+ function invalidReply() {
3
+ return new Error("invalid tier-2 worker reply");
4
+ }
5
+ /**
6
+ * Validates an untrusted worker message as the reply to a request of `expectedKind`. The worker
7
+ * runs plugin code, so its message is checked like any other external input.
8
+ *
9
+ * @throws Error `invalid tier-2 worker reply` for any other shape, or a success of the wrong kind.
10
+ * @complexity O(h) for h reported hook names.
11
+ */
12
+ export function decodeTier2Reply({ message, expectedKind }, _optional = {}) {
13
+ if (typeof message !== "object" || message === null)
14
+ throw invalidReply();
15
+ const reply = message;
16
+ if (reply.ok === false) {
17
+ if (typeof reply.stage !== "string" || !FAILURE_STAGES.has(reply.stage) || typeof reply.error !== "string") {
18
+ throw invalidReply();
19
+ }
20
+ return { ok: false, stage: reply.stage, error: reply.error };
21
+ }
22
+ if (reply.ok !== true || reply.kind !== expectedKind)
23
+ throw invalidReply();
24
+ if (expectedKind === "beforeSave")
25
+ return { ok: true, kind: "beforeSave", patch: reply.patch };
26
+ const { hooks } = reply;
27
+ if (!Array.isArray(hooks) || !hooks.every((hook) => typeof hook === "string"))
28
+ throw invalidReply();
29
+ return { ok: true, kind: "probe", hooks };
30
+ }
31
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1,27 @@
1
+ import type { BeforeSaveFilter, PluginSdkBinding, PluginModuleImportPort } from "../ports.js";
2
+ import type { CapabilityScopedSdkCoreDeps } from "../capability-sdk.js";
3
+ import type { Tier2Reply, Tier2Request } from "./protocol.js";
4
+ export interface RunTier2CallRequired {
5
+ readonly request: Tier2Request;
6
+ /** Imports the plugin entry. The worker entry supplies real `import()` after registering the
7
+ * `@tovu/sdk` resolver; tests supply a fake. */
8
+ readonly importModule: PluginModuleImportPort;
9
+ readonly pluginSdkBinding: PluginSdkBinding;
10
+ readonly createInvocationCoreDeps: (required: {
11
+ pluginId: string;
12
+ declaredHooks: readonly string[];
13
+ }, optional?: Record<string, never>) => {
14
+ readonly coreDeps: CapabilityScopedSdkCoreDeps;
15
+ capturedFilter(): BeforeSaveFilter | null;
16
+ };
17
+ }
18
+ export type RunTier2CallOptional = Record<string, never>;
19
+ /**
20
+ * Runs one Tier-2 request against the plugin's code in the current thread.
21
+ *
22
+ * @returns A structured-clone-safe reply; never rejects for a plugin-side failure.
23
+ * @complexity O(1) own work plus the plugin's import, setup and filter cost (bounded by the
24
+ * worker's timeout and heap limits on the server side, not here).
25
+ */
26
+ export declare function runTier2Call(required: RunTier2CallRequired, _optional?: RunTier2CallOptional): Promise<Tier2Reply>;
27
+ //# sourceMappingURL=run-call.d.ts.map
@@ -0,0 +1,76 @@
1
+ /** The application injects the existing invocation and export-validation owners. */
2
+ /**
3
+ * @file `runTier2Call()` — the worker-side half of one Tier-2 plugin call (ADR-024 §3/§4).
4
+ *
5
+ * Pure apart from the injected importer: import the plugin, validate its `definePlugin()` export
6
+ * with the SAME check `loadPlugin()` uses, build the SAME capability-scoped SDK over the SAME
7
+ * invocation backing the in-process path uses, run `setup()`, then either report the attached hooks
8
+ * (`probe`) or run the beforeSave filter on one entry (`beforeSave`). Every failure becomes a
9
+ * `{ ok: false, stage, error }` reply instead of a throw, so the server can tell "the plugin's code
10
+ * failed" (a reply) from "the worker itself died or ran out of time" (a rejected call).
11
+ *
12
+ * The server-side manifest checks (integrity, sdkRange — CIC U-001) have already run before any
13
+ * request reaches this function; it never sees a plugin the loader has not cleared.
14
+ */
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { buildCapabilityScopedSdk } from "../capability-sdk.js";
18
+ function failed(stage, error) {
19
+ return { ok: false, stage, error: error instanceof Error ? error.message : String(error) };
20
+ }
21
+ /**
22
+ * Runs one Tier-2 request against the plugin's code in the current thread.
23
+ *
24
+ * @returns A structured-clone-safe reply; never rejects for a plugin-side failure.
25
+ * @complexity O(1) own work plus the plugin's import, setup and filter cost (bounded by the
26
+ * worker's timeout and heap limits on the server side, not here).
27
+ */
28
+ export async function runTier2Call(required, _optional = {}) {
29
+ const { request, importModule, pluginSdkBinding, createInvocationCoreDeps } = required;
30
+ const HOOK_CONTENT_ENTRY_BEFORE_SAVE = pluginSdkBinding.beforeSaveHook;
31
+ const { pluginId, entryPath, capabilities, hooks } = request.plugin;
32
+ let moduleValue;
33
+ try {
34
+ const packageRoot = path.dirname(path.dirname(entryPath.startsWith("file:") ? fileURLToPath(entryPath) : entryPath));
35
+ const imported = await importModule({ plugin: { pluginId, packageRoot }, modulePath: entryPath });
36
+ if (typeof imported === "string")
37
+ return failed("import", imported);
38
+ moduleValue = { default: imported.exported };
39
+ }
40
+ catch (error) {
41
+ return failed("import", error);
42
+ }
43
+ const plugin = pluginSdkBinding.readDefinedPlugin({ moduleValue });
44
+ if (!plugin)
45
+ return failed("export", `plugin '${pluginId}' does not default-export definePlugin(...)`);
46
+ const invocation = createInvocationCoreDeps({ pluginId, declaredHooks: hooks });
47
+ const sdk = buildCapabilityScopedSdk({ pluginId, capabilities, coreDeps: invocation.coreDeps, pluginSdkBinding });
48
+ try {
49
+ await plugin.definition.setup(sdk);
50
+ }
51
+ catch (error) {
52
+ return failed("setup", error);
53
+ }
54
+ const filter = invocation.capturedFilter();
55
+ if (request.kind === "probe") {
56
+ return { ok: true, kind: "probe", hooks: filter ? [HOOK_CONTENT_ENTRY_BEFORE_SAVE] : [] };
57
+ }
58
+ if (!filter)
59
+ return failed("hook", `plugin '${pluginId}' attached no beforeSave filter`);
60
+ let patch;
61
+ try {
62
+ patch = await filter(request.entry, request.ctx);
63
+ }
64
+ catch (error) {
65
+ return failed("hook", error);
66
+ }
67
+ try {
68
+ // postMessage would otherwise throw a DataCloneError outside any reply, which the server can
69
+ // only see as a crashed worker; checking here keeps it a plugin-attributed hook failure.
70
+ return { ok: true, kind: "beforeSave", patch: structuredClone(patch) };
71
+ }
72
+ catch (error) {
73
+ return failed("hook", `plugin '${pluginId}' returned a value that cannot cross the worker boundary: ${error.message}`);
74
+ }
75
+ }
76
+ //# sourceMappingURL=run-call.js.map
package/package.json CHANGED
@@ -1,6 +1,110 @@
1
1
  {
2
2
  "name": "@jini-ai/plugins",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.4.1",
4
+ "description": "Host-independent extension glue and site-plugin runtime with injected SDK, trust, archive and storage ports.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/AINSEP/Jini.git",
9
+ "directory": "packages/plugins"
10
+ },
11
+ "jini": {
12
+ "domain": "tooling",
13
+ "kind": "plugin-packaging",
14
+ "runtime": "universal",
15
+ "entries": {
16
+ "./glue": "universal",
17
+ "./host": "universal",
18
+ "./host/node": "node",
19
+ "./host/worker": "node",
20
+ "./host/sql": "node"
21
+ },
22
+ "isolation": {
23
+ "forbidden": {
24
+ "./host": [
25
+ "node:"
26
+ ]
27
+ }
28
+ }
29
+ },
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "exports": {
33
+ "./glue": {
34
+ "types": "./dist/glue/index.d.ts",
35
+ "import": "./dist/glue/index.js",
36
+ "default": "./dist/glue/index.js"
37
+ },
38
+ "./host": {
39
+ "types": "./dist/host/index.d.ts",
40
+ "import": "./dist/host/index.js",
41
+ "default": "./dist/host/index.js"
42
+ },
43
+ "./host/node": {
44
+ "types": "./dist/host/node/index.d.ts",
45
+ "import": "./dist/host/node/index.js",
46
+ "default": "./dist/host/node/index.js"
47
+ },
48
+ "./host/worker": {
49
+ "types": "./dist/host/worker/index.d.ts",
50
+ "import": "./dist/host/worker/index.js",
51
+ "default": "./dist/host/worker/index.js"
52
+ },
53
+ "./host/sql": {
54
+ "types": "./dist/host/sql/index.d.ts",
55
+ "import": "./dist/host/sql/index.js",
56
+ "default": "./dist/host/sql/index.js"
57
+ }
58
+ },
59
+ "files": [
60
+ "dist",
61
+ "README.md",
62
+ "CHANGELOG.md",
63
+ "LICENSE",
64
+ "!dist/**/*.test.js",
65
+ "!dist/**/*.test.d.ts",
66
+ "!dist/**/*.test.js.map",
67
+ "!dist/**/*.test.d.ts.map",
68
+ "!dist/**/__tests__/**"
69
+ ],
70
+ "publishConfig": {
71
+ "access": "public",
72
+ "registry": "https://registry.npmjs.org"
73
+ },
74
+ "dependencies": {
75
+ "@jini-ai/core": "^0.4.3"
76
+ },
77
+ "peerDependencies": {
78
+ "@jini-ai/platform": "^0.5.3",
79
+ "semver": "^7.6.2",
80
+ "kysely": "^0.29.6",
81
+ "@jini-ai/db": "^0.3.2"
82
+ },
83
+ "peerDependenciesMeta": {
84
+ "@jini-ai/platform": {
85
+ "optional": true
86
+ },
87
+ "semver": {
88
+ "optional": true
89
+ },
90
+ "kysely": {
91
+ "optional": true
92
+ },
93
+ "@jini-ai/db": {
94
+ "optional": true
95
+ }
96
+ },
97
+ "devDependencies": {
98
+ "semver": "^7.6.2",
99
+ "@types/semver": "^7.5.8",
100
+ "kysely": "^0.29.6",
101
+ "@jini-ai/core": "^0.4.3",
102
+ "@jini-ai/platform": "^0.5.3",
103
+ "@jini-ai/db": "0.3.2"
104
+ },
105
+ "scripts": {
106
+ "build": "tsc -p tsconfig.json",
107
+ "typecheck": "tsc -p tsconfig.json --noEmit",
108
+ "test": "vitest run"
109
+ }
6
110
  }