@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,43 @@
1
+ /** Host-independent collect-all manifest validation; vocabularies are host inputs. */
2
+ export interface GlueVocabulary {
3
+ readonly capabilities: readonly string[];
4
+ readonly callSites: readonly string[];
5
+ }
6
+ export type GlueCallSite = string;
7
+ export type GlueCapability = string;
8
+ export interface GlueManifestAttachment {
9
+ readonly callSite: GlueCallSite;
10
+ readonly [payloadKey: string]: unknown;
11
+ }
12
+ export interface GlueManifest {
13
+ readonly id: string;
14
+ readonly version: string;
15
+ readonly sdkRange: string;
16
+ readonly capabilities: readonly GlueCapability[];
17
+ readonly attachments: readonly GlueManifestAttachment[];
18
+ }
19
+ export interface GlueManifestValidationError {
20
+ readonly code: string;
21
+ readonly file: string | null;
22
+ readonly message: string;
23
+ }
24
+ export interface ValidateGlueManifestRequired {
25
+ readonly manifest: unknown;
26
+ readonly vocabulary: GlueVocabulary;
27
+ }
28
+ export type ValidateGlueManifestOptional = Record<string, never>;
29
+ export interface ValidateGlueManifestResult {
30
+ readonly errors: readonly GlueManifestValidationError[];
31
+ }
32
+ export declare function validateGlueManifest(required: ValidateGlueManifestRequired, _optional?: ValidateGlueManifestOptional): ValidateGlueManifestResult;
33
+ export type GlueCallSiteDispatchStatus = {
34
+ readonly wired: true;
35
+ } | {
36
+ readonly wired: false;
37
+ readonly code: "UNWIRED_CALL_SITE";
38
+ };
39
+ export declare function resolveCallSiteDispatch({ callSite, wiredCallSites }: {
40
+ callSite: GlueCallSite;
41
+ wiredCallSites: readonly GlueCallSite[];
42
+ }, _optional?: Record<string, never>): GlueCallSiteDispatchStatus;
43
+ //# sourceMappingURL=manifest.d.ts.map
@@ -0,0 +1,106 @@
1
+ const REQUIRED_KEYS = ["id", "version", "sdkRange", "capabilities", "attachments"];
2
+ const ALLOWED_KEYS = new Set(REQUIRED_KEYS);
3
+ const ID_PATTERN = /^[a-z0-9-]+$/;
4
+ const MAX_ID_LENGTH = 50;
5
+ function malformed(message) {
6
+ return { code: "MANIFEST_MALFORMED", file: null, message };
7
+ }
8
+ function validateKeys(raw) {
9
+ const errors = [];
10
+ for (const key of Object.keys(raw)) {
11
+ if (!ALLOWED_KEYS.has(key)) {
12
+ errors.push(malformed(`unknown manifest key '${key}'`));
13
+ }
14
+ }
15
+ for (const key of REQUIRED_KEYS) {
16
+ if (raw[key] === undefined) {
17
+ errors.push(malformed(`missing required manifest field '${key}'`));
18
+ }
19
+ }
20
+ return errors;
21
+ }
22
+ function validateId(raw) {
23
+ const errors = [];
24
+ const id = typeof raw.id === "string" ? raw.id : undefined;
25
+ if (raw.id !== undefined && id === undefined) {
26
+ errors.push(malformed("'id' must be a string"));
27
+ }
28
+ if (id !== undefined && (!ID_PATTERN.test(id) || id.length < 1 || id.length > MAX_ID_LENGTH)) {
29
+ errors.push(malformed(`id '${id}' must match ${ID_PATTERN} and be 1-${MAX_ID_LENGTH} characters`));
30
+ }
31
+ return errors;
32
+ }
33
+ function validateVersionAndSdkRange(raw) {
34
+ const errors = [];
35
+ if (raw.version !== undefined && typeof raw.version !== "string") {
36
+ errors.push(malformed("'version' must be a string"));
37
+ }
38
+ if (raw.sdkRange !== undefined && typeof raw.sdkRange !== "string") {
39
+ errors.push(malformed("'sdkRange' must be a string"));
40
+ }
41
+ return errors;
42
+ }
43
+ function validateCapabilities(raw, vocabulary) {
44
+ const errors = [];
45
+ const capabilities = Array.isArray(raw.capabilities) ? raw.capabilities : [];
46
+ if (raw.capabilities !== undefined && !Array.isArray(raw.capabilities)) {
47
+ errors.push(malformed("'capabilities' must be an array"));
48
+ }
49
+ for (const capability of capabilities) {
50
+ if (typeof capability !== "string" || !vocabulary.capabilities.includes(capability)) {
51
+ errors.push({
52
+ code: "CAPABILITY_UNKNOWN",
53
+ file: null,
54
+ message: `capability '${String(capability)}' is outside the supplied capability vocabulary`,
55
+ });
56
+ }
57
+ }
58
+ return errors;
59
+ }
60
+ function validateAttachment(attachment, vocabulary) {
61
+ if (typeof attachment !== "object" || attachment === null || Array.isArray(attachment)) {
62
+ return [malformed("each 'attachments' entry must be an object")];
63
+ }
64
+ const callSite = attachment.callSite;
65
+ if (typeof callSite !== "string" || !vocabulary.callSites.includes(callSite)) {
66
+ return [
67
+ {
68
+ code: "CALL_SITE_UNKNOWN",
69
+ file: null,
70
+ message: `call site '${String(callSite)}' is outside the supplied call-site vocabulary`,
71
+ },
72
+ ];
73
+ }
74
+ return [];
75
+ }
76
+ function validateAttachments(raw, vocabulary) {
77
+ const errors = [];
78
+ const attachments = Array.isArray(raw.attachments) ? raw.attachments : [];
79
+ if (raw.attachments !== undefined && !Array.isArray(raw.attachments)) {
80
+ errors.push(malformed("'attachments' must be an array"));
81
+ }
82
+ for (const attachment of attachments) {
83
+ errors.push(...validateAttachment(attachment, vocabulary));
84
+ }
85
+ return errors;
86
+ }
87
+ export function validateGlueManifest(required, _optional = {}) {
88
+ const { manifest, vocabulary } = required;
89
+ if (typeof manifest !== "object" || manifest === null || Array.isArray(manifest)) {
90
+ return { errors: [malformed("glue manifest must be a JSON object")] };
91
+ }
92
+ // Treat the input as a read-only bag of unknown values — never assigned back into.
93
+ const raw = manifest;
94
+ const errors = [
95
+ ...validateKeys(raw),
96
+ ...validateId(raw),
97
+ ...validateVersionAndSdkRange(raw),
98
+ ...validateCapabilities(raw, vocabulary),
99
+ ...validateAttachments(raw, vocabulary),
100
+ ];
101
+ return { errors };
102
+ }
103
+ export function resolveCallSiteDispatch({ callSite, wiredCallSites }, _optional = {}) {
104
+ return wiredCallSites.includes(callSite) ? { wired: true } : { wired: false, code: "UNWIRED_CALL_SITE" };
105
+ }
106
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,60 @@
1
+ export interface GlueFieldDecl {
2
+ readonly path: string;
3
+ readonly type: 'string' | 'integer' | 'number' | 'boolean';
4
+ }
5
+ export type GlueContentLifecycleFilter = (required: {
6
+ entry: Readonly<Record<string, unknown>>;
7
+ ctx: {
8
+ readonly moduleId: string;
9
+ readonly workspaceId: string;
10
+ };
11
+ }) => Readonly<Record<string, unknown>> | Promise<Readonly<Record<string, unknown>>>;
12
+ export interface GlueToolRegistration {
13
+ readonly toolId: string;
14
+ readonly handler: (required: Readonly<Record<string, unknown>>, optional?: Readonly<Record<string, unknown>>) => unknown;
15
+ }
16
+ export type GlueChangeSetCommand = unknown;
17
+ /** Host implementations own persistence, containment and dispatch. Mounting tools must be atomic. */
18
+ export interface GlueHostPort {
19
+ attachContentLifecycleFilter(required: {
20
+ moduleId: string;
21
+ filter: GlueContentLifecycleFilter;
22
+ declaredFields: readonly GlueFieldDecl[];
23
+ }): void;
24
+ registerTools(required: {
25
+ moduleId: string;
26
+ registrations: readonly GlueToolRegistration[];
27
+ }): void;
28
+ subscribeEvent(required: {
29
+ moduleId: string;
30
+ eventName: string;
31
+ handler: (required: {
32
+ payload: unknown;
33
+ }) => Promise<void> | void;
34
+ }): void;
35
+ registerAdminNav(required: {
36
+ moduleId: string;
37
+ payload: Readonly<Record<string, unknown>>;
38
+ }): void;
39
+ contributeRender(required: {
40
+ moduleId: string;
41
+ payload: Readonly<Record<string, unknown>>;
42
+ }): void;
43
+ registerHttpRoute(required: {
44
+ moduleId: string;
45
+ payload: Readonly<Record<string, unknown>>;
46
+ }): void;
47
+ runChangeSet(required: {
48
+ command: GlueChangeSetCommand;
49
+ }): Promise<unknown>;
50
+ snapshotBlob(required: {
51
+ content: Uint8Array | string;
52
+ }): Promise<{
53
+ readonly hash: string;
54
+ }>;
55
+ restoreBlob(required: {
56
+ hash: string;
57
+ }): Promise<Uint8Array>;
58
+ }
59
+ export type { GlueCallSite, GlueCapability } from './manifest.js';
60
+ //# sourceMappingURL=ports.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ports.js.map
@@ -0,0 +1,118 @@
1
+ /**
2
+ * @file `setPluginEnabled()` / `getActivation()` — gateway-backed enable/disable feature functions
3
+ * (SPEC-005 REQ-07; BR-05; AC-02/AC-13; INV-03/INV-05).
4
+ *
5
+ * Purpose:
6
+ * Mirrors `src/features/presentation/presentation.ts`'s `setActiveTheme`/`getPresentationSettings`
7
+ * shape exactly (Module Map) — a plain feature function, validated and typed-error-throwing, that
8
+ * the ROUTE layer (`src/server/routes/admin/plugins/set-enabled.ts`, C-016) wraps in
9
+ * `executeCommand` (mirrors `admin/posts/update.ts`'s `executeCommand`-wrapped shape, per the
10
+ * ADR's API/Event Contract Summary) — NOT wrapped here. This function itself performs BR-05's
11
+ * three-step precondition evaluation and, on success, upserts the `PluginActivationRecord` and
12
+ * (on enable) invokes the injected load hook / (on disable) the injected unload hook — it does not
13
+ * call the gateway itself.
14
+ *
15
+ * `ext.{pluginId}` data is never touched by either transition (INV-03) — this module has no
16
+ * dependency on `posts.ext` at all, by construction (it only ever touches `plugin_activations`).
17
+ *
18
+ * Architectural role:
19
+ * TDD-certified implementation (implementation outline C-011/C-012). Signatures and JSDoc are
20
+ * design-frozen; `setPluginEnabled()` runs BR-05's three-step evaluation, upserts the activation
21
+ * row, then invokes the injected `onEnabled`/`onDisabled` side effect. If that side effect throws
22
+ * after the row was saved, `restoreOnSideEffectFailure()` compensates — restoring the prior record,
23
+ * or deleting it for a first-time enable/disable — best-effort, before rethrowing the original
24
+ * error unmasked. `getActivation()` is a thin read. Both satisfy
25
+ * `__tests__/integration/activation.integration.test.ts`.
26
+ */
27
+ import type { Clock as ClockPort, UUID } from "@jini-ai/core/primitives";
28
+ import type { PluginDiscoveryRecord } from "./discovery-types.js";
29
+ /** `plugin_activations` row (durable, behind the gateway) — state.spec.md §2. */
30
+ export interface PluginActivationRecord {
31
+ readonly pluginId: string;
32
+ readonly workspaceId: UUID;
33
+ /** The active (enabled) installed version — the "active pointer" (ADR-004). */
34
+ readonly version: string;
35
+ readonly enabled: boolean;
36
+ readonly updatedAt: string;
37
+ /** Present only while automatic quarantine is active. A normal enable/disable save omits these
38
+ * fields, which clears the durable marker and makes re-enable the operator recovery action. */
39
+ readonly quarantinedAt?: string;
40
+ readonly quarantineReason?: string;
41
+ readonly quarantineFailureCount?: number;
42
+ }
43
+ /** Persistence contract — shaped identically to `PresentationSettingsRepoPort` (rule-of-two, two
44
+ * adapters from day one: `repo.memory.ts` / `repo.sqlite.ts`). */
45
+ export interface PluginActivationRepoPort {
46
+ getActivation(required: {
47
+ workspaceId: UUID;
48
+ pluginId: string;
49
+ }, optional?: Record<string, never>): Promise<PluginActivationRecord | null>;
50
+ save(record: PluginActivationRecord, optional?: Record<string, never>): Promise<void>;
51
+ deleteActivation(required: {
52
+ workspaceId: UUID;
53
+ pluginId: string;
54
+ }, optional?: Record<string, never>): Promise<void>;
55
+ /** Every row across every workspace — used by discovery's `enabled` projection and by any
56
+ * future migration, mirrors `PresentationSettingsRepoPort.listAll`. */
57
+ listAll(required?: Record<string, never>, optional?: Record<string, never>): Promise<PluginActivationRecord[]>;
58
+ }
59
+ export declare class PluginNotFoundError extends Error {
60
+ }
61
+ export declare class PluginInvalidError extends Error {
62
+ }
63
+ export declare class PluginIncompatibleError extends Error {
64
+ }
65
+ export interface SetPluginEnabledDeps {
66
+ clock: ClockPort;
67
+ repo: PluginActivationRepoPort;
68
+ /** The current discovery snapshot — used to evaluate BR-05's "id present in discovery" and
69
+ * (when enabling) "status 'valid'" preconditions. Callers pass a fresh `discoverPlugins()`
70
+ * result; this function does not call discovery itself (keeps it a pure state-transition step
71
+ * over an already-known snapshot, easier to test deterministically). */
72
+ discovery: readonly PluginDiscoveryRecord[];
73
+ /** Invoked on a successful enable transition, after the activation row is saved — the actual
74
+ * `loadPlugin()`/hook-attach side effect. Optional so this function stays testable without a
75
+ * real loader; a real composition root always supplies one. */
76
+ onEnabled?: (pluginId: string) => Promise<void>;
77
+ /** Invoked on a successful disable transition — detaches the plugin's hooks
78
+ * (`hook-registry.ts`'s `detach`). Optional for the same testability reason as `onEnabled`. */
79
+ onDisabled?: (pluginId: string) => void;
80
+ }
81
+ export interface SetPluginEnabledInput {
82
+ readonly workspaceId: UUID;
83
+ readonly pluginId: string;
84
+ readonly enabled: boolean;
85
+ }
86
+ export interface SetPluginEnabledRequired {
87
+ deps: SetPluginEnabledDeps;
88
+ input: SetPluginEnabledInput;
89
+ }
90
+ export type SetPluginEnabledOptional = Record<string, never>;
91
+ /**
92
+ * BR-05's three-step evaluation: (1) id present in discovery ⇒ else `PluginNotFoundError`;
93
+ * (2) when enabling, discovered `status` is `"valid"` ⇒ else `PluginInvalidError`/
94
+ * `PluginIncompatibleError`; (3) upsert the activation row and invoke the load/unload side
95
+ * effect. Disable has no validity precondition (BR-05) — a plugin that became invalid after being
96
+ * enabled can always still be disabled.
97
+ *
98
+ * @throws {PluginNotFoundError} the plugin id is not present in the given discovery snapshot.
99
+ * @throws {PluginInvalidError} enabling a plugin whose discovered `status` is `"invalid"`.
100
+ * @throws {PluginIncompatibleError} enabling a plugin whose discovered `status` is `"incompatible"`.
101
+ */
102
+ export declare function setPluginEnabled(required: SetPluginEnabledRequired, _optional?: SetPluginEnabledOptional): Promise<{
103
+ activation: PluginActivationRecord;
104
+ }>;
105
+ export interface GetActivationRequired {
106
+ deps: {
107
+ repo: PluginActivationRepoPort;
108
+ };
109
+ input: {
110
+ workspaceId: UUID;
111
+ pluginId: string;
112
+ };
113
+ }
114
+ export type GetActivationOptional = Record<string, never>;
115
+ /** Reads current activation state for projection into `PLUGINS_LIST` (state.spec.md §5). `null`
116
+ * means "never enabled" (treated as disabled), not an error. */
117
+ export declare function getActivation(required: GetActivationRequired, _optional?: GetActivationOptional): Promise<PluginActivationRecord | null>;
118
+ //# sourceMappingURL=activation.d.ts.map
@@ -0,0 +1,104 @@
1
+ import { nowIso as clockNowIso } from "@jini-ai/core/primitives";
2
+ /**
3
+ * Restores the repo to its pre-transition state after a side-effect hook (`onEnabled`/
4
+ * `onDisabled`) throws: writes back the record that existed before this transition, or — for a
5
+ * first-time enable/disable where no prior record existed — deletes the row `setPluginEnabled`
6
+ * just created. Best-effort: a compensation failure must never mask the original side-effect
7
+ * error, so this swallows its own failure and lets the caller rethrow the original.
8
+ *
9
+ * @complexity O(1) — one repo write.
10
+ */
11
+ async function restoreOnSideEffectFailure(repo, existing, target) {
12
+ try {
13
+ if (existing) {
14
+ await repo.save(existing);
15
+ }
16
+ else {
17
+ await repo.deleteActivation(target);
18
+ }
19
+ }
20
+ catch {
21
+ // Compensation is best-effort; its failure must not mask the original side-effect error.
22
+ }
23
+ }
24
+ export class PluginNotFoundError extends Error {
25
+ }
26
+ export class PluginInvalidError extends Error {
27
+ }
28
+ export class PluginIncompatibleError extends Error {
29
+ }
30
+ /** BR-05 step 2: enabling requires a `"valid"` discovered status — `"incompatible"` gets its own
31
+ * typed error (a fixable-only-by-an-SDK-upgrade condition) distinct from any other non-`"valid"`
32
+ * status. Never called for a disable — BR-05 has no validity precondition on that direction. */
33
+ function assertPluginEnableAllowed(pluginId, status) {
34
+ if (status === "incompatible") {
35
+ throw new PluginIncompatibleError(`plugin '${pluginId}' is incompatible with this runtime's SDK version`);
36
+ }
37
+ if (status !== "valid") {
38
+ throw new PluginInvalidError(`plugin '${pluginId}' failed validation and cannot be enabled`);
39
+ }
40
+ }
41
+ /** The active-version pointer only ever advances on a genuine enable (REQ-02's "active pointer");
42
+ * disabling must not silently re-point it to whatever discovery currently reports as latest — it
43
+ * preserves whichever version was actually active (AC-13: disable's version is unchanged from the
44
+ * enable it inverts). */
45
+ function resolveActivationVersion(enabled, discoveredVersion, existingVersion) {
46
+ if (enabled)
47
+ return discoveredVersion;
48
+ return existingVersion ?? discoveredVersion;
49
+ }
50
+ /** Invokes the enable/disable side effect and, on failure, compensates and rethrows the ORIGINAL
51
+ * error unmasked — one `try`/`catch` instead of the identical pair an enable/disable if/else used
52
+ * to each carry, since both directions need exactly the same failure handling. */
53
+ async function applyActivationSideEffect(deps, input, existing, target) {
54
+ try {
55
+ if (input.enabled) {
56
+ await deps.onEnabled?.(input.pluginId);
57
+ }
58
+ else {
59
+ deps.onDisabled?.(input.pluginId);
60
+ }
61
+ }
62
+ catch (error) {
63
+ await restoreOnSideEffectFailure(deps.repo, existing, target);
64
+ throw error;
65
+ }
66
+ }
67
+ /**
68
+ * BR-05's three-step evaluation: (1) id present in discovery ⇒ else `PluginNotFoundError`;
69
+ * (2) when enabling, discovered `status` is `"valid"` ⇒ else `PluginInvalidError`/
70
+ * `PluginIncompatibleError`; (3) upsert the activation row and invoke the load/unload side
71
+ * effect. Disable has no validity precondition (BR-05) — a plugin that became invalid after being
72
+ * enabled can always still be disabled.
73
+ *
74
+ * @throws {PluginNotFoundError} the plugin id is not present in the given discovery snapshot.
75
+ * @throws {PluginInvalidError} enabling a plugin whose discovered `status` is `"invalid"`.
76
+ * @throws {PluginIncompatibleError} enabling a plugin whose discovered `status` is `"incompatible"`.
77
+ */
78
+ export async function setPluginEnabled(required, _optional = {}) {
79
+ const { deps, input } = required;
80
+ const discovered = deps.discovery.find((record) => record.id === input.pluginId);
81
+ if (!discovered) {
82
+ throw new PluginNotFoundError(`plugin '${input.pluginId}' was not found in the current discovery snapshot`);
83
+ }
84
+ if (input.enabled)
85
+ assertPluginEnableAllowed(input.pluginId, discovered.status);
86
+ const existing = await deps.repo.getActivation({ workspaceId: input.workspaceId, pluginId: input.pluginId });
87
+ const version = resolveActivationVersion(input.enabled, discovered.version, existing?.version);
88
+ const activation = {
89
+ pluginId: input.pluginId,
90
+ workspaceId: input.workspaceId,
91
+ version,
92
+ enabled: input.enabled,
93
+ updatedAt: clockNowIso({ clock: deps.clock }),
94
+ };
95
+ await deps.repo.save(activation);
96
+ await applyActivationSideEffect(deps, input, existing, { workspaceId: input.workspaceId, pluginId: input.pluginId });
97
+ return { activation };
98
+ }
99
+ /** Reads current activation state for projection into `PLUGINS_LIST` (state.spec.md §5). `null`
100
+ * means "never enabled" (treated as disabled), not an error. */
101
+ export async function getActivation(required, _optional = {}) {
102
+ return required.deps.repo.getActivation(required.input);
103
+ }
104
+ //# sourceMappingURL=activation.js.map
@@ -0,0 +1,37 @@
1
+ import type { BeforeSaveFilter } from "./ports.js";
2
+ import type { AttachmentSource, HookRegistry, HookRegistryFieldDecl } from "./hook-registry.js";
3
+ export interface AttachLoadedPluginRequired {
4
+ /** The plugin/glue-module id `hookRegistry.attach()` files this attachment under. */
5
+ readonly pluginId: string;
6
+ /** Who attached this filter — widened by ADR-057 Decision 3 to include `"glue"`, so Site Glue's
7
+ * content-lifecycle attachment point can call this function directly rather than forking it. */
8
+ readonly source: AttachmentSource;
9
+ /** The live registry this load's filter attaches to — one long-lived instance per process
10
+ * (`hook-registry.ts`'s own doc comment), supplied by the caller, never constructed here. */
11
+ readonly hookRegistry: HookRegistry;
12
+ /** The filter obtained from step (4) — i.e. whatever the caller's own `setup()` invocation (with
13
+ * a capability-scoped SDK gating `hooks.attach`) produced. This function does not invoke `setup()`
14
+ * itself: the SDK shape a `setup()` call receives differs by caller (plugin-runtime's own 3-member
15
+ * `PluginCapability` vocabulary for real plugins; Site Glue's 8-member `GlueCapability` vocabulary
16
+ * for glue modules), so building and gating that SDK stays the caller's responsibility. What is
17
+ * genuinely shared — and was genuinely dead before this extraction — is the attach step itself. */
18
+ readonly filter: BeforeSaveFilter;
19
+ readonly declaredFields: readonly HookRegistryFieldDecl[];
20
+ }
21
+ export type AttachLoadedPluginOptional = Record<string, never>;
22
+ /**
23
+ * The real (not stub) extraction of `loadPlugin()`'s dead step (5) — ADR-057 Decision 2.1. Attaches
24
+ * one already-obtained filter to the given hook registry under `(pluginId, source)`, widened beyond
25
+ * `loader.ts`'s original `"built-in" | "site"` scope to also accept `"glue"`. Before ADR-057, no
26
+ * production code ever called `hookRegistry.attach()` at all (verified by grep, see `hook-registry.ts`'s
27
+ * corrected header) — Site Glue's content-lifecycle attachment point is this function's first real
28
+ * caller; a future fix to `loadPlugin()`'s own dead steps (4)-(5) is expected to call this same
29
+ * function from its real activation path rather than re-implementing the attach step a second time.
30
+ *
31
+ * @throws Nothing of its own — propagates whatever `hookRegistry.attach()` itself throws (today,
32
+ * nothing; `attach()` is a plain `Map.set`).
33
+ * @complexity O(1) — a single delegated call, no iteration or I/O of its own.
34
+ * @overallScore 100/100
35
+ */
36
+ export declare function attachLoadedPlugin(required: AttachLoadedPluginRequired, _optional?: AttachLoadedPluginOptional): void;
37
+ //# sourceMappingURL=attach-loaded-plugin.d.ts.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * The real (not stub) extraction of `loadPlugin()`'s dead step (5) — ADR-057 Decision 2.1. Attaches
3
+ * one already-obtained filter to the given hook registry under `(pluginId, source)`, widened beyond
4
+ * `loader.ts`'s original `"built-in" | "site"` scope to also accept `"glue"`. Before ADR-057, no
5
+ * production code ever called `hookRegistry.attach()` at all (verified by grep, see `hook-registry.ts`'s
6
+ * corrected header) — Site Glue's content-lifecycle attachment point is this function's first real
7
+ * caller; a future fix to `loadPlugin()`'s own dead steps (4)-(5) is expected to call this same
8
+ * function from its real activation path rather than re-implementing the attach step a second time.
9
+ *
10
+ * @throws Nothing of its own — propagates whatever `hookRegistry.attach()` itself throws (today,
11
+ * nothing; `attach()` is a plain `Map.set`).
12
+ * @complexity O(1) — a single delegated call, no iteration or I/O of its own.
13
+ * @overallScore 100/100
14
+ */
15
+ export function attachLoadedPlugin(required, _optional = {}) {
16
+ const { pluginId, source, hookRegistry, filter, declaredFields } = required;
17
+ hookRegistry.attach({ pluginId, source, filter, declaredFields });
18
+ }
19
+ //# sourceMappingURL=attach-loaded-plugin.js.map
@@ -0,0 +1,74 @@
1
+ /**
2
+ * @file `buildCapabilityScopedSdk()` — builds the per-load `PluginSdk` handle (SPEC-005 REQ-04;
3
+ * CIC U-003, `ESCALATE_SECURITY`).
4
+ *
5
+ * Purpose:
6
+ * REQ-04: "the SDK object handed to the plugin exposes ONLY the granted surface. A plugin
7
+ * invoking a surface it did not declare fails at the SDK boundary (`CAPABILITY_DENIED`)."
8
+ *
9
+ * **CIC U-003 (Binding, ESCALATE_SECURITY):** a naive reading of REQ-04 could satisfy "exposes
10
+ * only the granted surface" by simply OMITTING ungranted properties (`sdk.content = granted ?
11
+ * {...} : undefined`). That is the wrong implementation — AC-05's contract requires a classified,
12
+ * catchable `CAPABILITY_DENIED` error, not a bare `TypeError` from calling a method on
13
+ * `undefined`. This function must therefore always expose a callable at every one of the three
14
+ * v1 capability positions (`content.read`, `content.extend`, `addFilter`) — granted capabilities
15
+ * get the real implementation (delegating to `coreDeps`), ungranted capabilities get a stub that
16
+ * SYNCHRONOUSLY throws a typed `CapabilityDeniedError` naming the missing capability. Any
17
+ * deviation from "always present, never absent" requires a recorded
18
+ * `[CIC_DEVIATION_APPROVED]` entry — see
19
+ * `reports/pipeline/005-plugin-system/critical-internal-constraints.md` U-003.
20
+ *
21
+ * Built fresh per plugin load (never a shared module-level singleton, ADR Decision item 2) — a
22
+ * new `PluginSdk` object is constructed for every `loadPlugin()` call, closing over that one
23
+ * plugin's own `pluginId` and granted capability set only.
24
+ *
25
+ * Architectural role:
26
+ * TDD-certified implementation (implementation outline C-009, CIC U-003). Signature and JSDoc are
27
+ * design-frozen; `buildCapabilityScopedSdk()` returns fresh per-plugin delegates for granted
28
+ * capabilities and present, typed-denial stubs for every ungranted surface.
29
+ */
30
+ import type { BeforeSaveFilter, ContentEntryDraft, PluginSdk, HookPoints, PluginSdkBinding } from "./ports.js";
31
+ import type { PluginCapability } from "./manifest.js";
32
+ /** Thrown synchronously when a plugin invokes an SDK surface it did not declare a capability for
33
+ * (REQ-04, INV-02). Classified so `hook-registry.ts` can catch it specifically and map the
34
+ * containing content operation to `PLUGIN_HOOK_FAILED` (BR-07), distinct from any other thrown
35
+ * error a plugin's own code might raise. */
36
+ export declare class CapabilityDeniedError extends Error {
37
+ readonly pluginId: string;
38
+ readonly capability: PluginCapability;
39
+ constructor(pluginId: string, capability: PluginCapability);
40
+ }
41
+ /** The three real, plugin-instance-scoped callbacks `capability-sdk.ts` wraps with capability
42
+ * gating. Supplied by the caller (the loader, at load time, closing over that specific plugin
43
+ * load's `hook-registry.ts` state) — this module never reaches into `hook-registry.ts` directly. */
44
+ export interface CapabilityScopedSdkCoreDeps {
45
+ /** Backing implementation for the granted `content.read()` surface. */
46
+ getCurrentEntry(): Readonly<ContentEntryDraft>;
47
+ /** Backing implementation for the granted `content.extend()` surface — writes into this
48
+ * plugin's own `ext.{pluginId}.{field}` namespace (validated by BR-06 at the caller). */
49
+ writeExtField(field: string, value: string | number | boolean): void;
50
+ /** Backing implementation for the granted `addFilter()` surface. */
51
+ attachFilter(hookName: string, filter: BeforeSaveFilter): void;
52
+ readonly contributions?: Pick<PluginSdk, 'routes' | 'tools' | 'widgets'>;
53
+ }
54
+ export interface BuildCapabilityScopedSdkRequired<H extends HookPoints = HookPoints> {
55
+ readonly pluginSdkBinding: PluginSdkBinding<H>;
56
+ readonly pluginId: string;
57
+ /** The manifest's declared capability set (already validated against the v1 vocabulary by
58
+ * `validateManifest()` — this function trusts its input is well-formed capability strings). */
59
+ readonly capabilities: readonly PluginCapability[];
60
+ readonly coreDeps: CapabilityScopedSdkCoreDeps;
61
+ }
62
+ export type BuildCapabilityScopedSdkOptional = Record<string, never>;
63
+ /**
64
+ * Builds one plugin's capability-scoped `PluginSdk` handle. Every one of the three v1 surfaces is
65
+ * always present on the returned object (CIC U-003) — granted surfaces delegate to `coreDeps`,
66
+ * ungranted surfaces are stubs that throw `CapabilityDeniedError` when invoked (never at build
67
+ * time — the stub itself is a normal, present function; only CALLING it throws).
68
+ *
69
+ * @throws Nothing at build time. The returned object's ungranted-surface stubs throw
70
+ * `CapabilityDeniedError` synchronously when invoked by the plugin.
71
+ * @complexity O(capabilities.length) to build the granted set; every surface check is O(1).
72
+ */
73
+ export declare function buildCapabilityScopedSdk<H extends HookPoints>(required: BuildCapabilityScopedSdkRequired<H>, _optional?: BuildCapabilityScopedSdkOptional): PluginSdk<H>;
74
+ //# sourceMappingURL=capability-sdk.d.ts.map
@@ -0,0 +1,94 @@
1
+ /** Thrown synchronously when a plugin invokes an SDK surface it did not declare a capability for
2
+ * (REQ-04, INV-02). Classified so `hook-registry.ts` can catch it specifically and map the
3
+ * containing content operation to `PLUGIN_HOOK_FAILED` (BR-07), distinct from any other thrown
4
+ * error a plugin's own code might raise. */
5
+ export class CapabilityDeniedError extends Error {
6
+ pluginId;
7
+ capability;
8
+ constructor(pluginId, capability) {
9
+ super(`plugin '${pluginId}' invoked '${capability}' without declaring it in its manifest capabilities`);
10
+ this.name = "CapabilityDeniedError";
11
+ this.pluginId = pluginId;
12
+ this.capability = capability;
13
+ }
14
+ }
15
+ /**
16
+ * Builds one plugin's capability-scoped `PluginSdk` handle. Every one of the three v1 surfaces is
17
+ * always present on the returned object (CIC U-003) — granted surfaces delegate to `coreDeps`,
18
+ * ungranted surfaces are stubs that throw `CapabilityDeniedError` when invoked (never at build
19
+ * time — the stub itself is a normal, present function; only CALLING it throws).
20
+ *
21
+ * @throws Nothing at build time. The returned object's ungranted-surface stubs throw
22
+ * `CapabilityDeniedError` synchronously when invoked by the plugin.
23
+ * @complexity O(capabilities.length) to build the granted set; every surface check is O(1).
24
+ */
25
+ export function buildCapabilityScopedSdk(required, _optional = {}) {
26
+ const { pluginId, capabilities, coreDeps } = required;
27
+ const granted = new Set(capabilities);
28
+ /**
29
+ * Wraps one capability-gated surface: returns `real` when `capability` is granted, otherwise a
30
+ * stub that synchronously throws `CapabilityDeniedError` when invoked. CIC U-003's binding
31
+ * property — every surface is always a present, callable function, never an absent property.
32
+ */
33
+ function gate(capability, real) {
34
+ if (granted.has(capability)) {
35
+ return real;
36
+ }
37
+ return ((..._args) => {
38
+ throw new CapabilityDeniedError(pluginId, capability);
39
+ });
40
+ }
41
+ const sdk = {
42
+ content: {
43
+ read: gate("content.read", () => coreDeps.getCurrentEntry()),
44
+ extend: gate("content.extend", (field, value) => coreDeps.writeExtField(field, value)),
45
+ },
46
+ addFilter: gate("hooks.attach", (hookName, filter) => coreDeps.attachFilter(hookName, filter)),
47
+ routes: { add: gate("http.route.register", (input, options = {}) => {
48
+ if (!coreDeps.contributions)
49
+ throw new Error('plugin routes are not bound by this host');
50
+ coreDeps.contributions.routes.add(input, options);
51
+ }) },
52
+ tools: { add: gate("tools.register", (input, options = {}) => {
53
+ if (!coreDeps.contributions)
54
+ throw new Error('plugin tools are not bound by this host');
55
+ coreDeps.contributions.tools.add(input, options);
56
+ }) },
57
+ widgets: { add: gate("render.contribute", (input, options = {}) => {
58
+ if (!coreDeps.contributions)
59
+ throw new Error('plugin widgets are not bound by this host');
60
+ coreDeps.contributions.widgets.add(input, options);
61
+ }) },
62
+ // V1 rationale retained: `ActionHookName`/`ContributionHookName` (@tovu/sdk hooks.ts) have no
63
+ // catalog members yet (hooks v2 plan §3.3 Waves 1/2 land in a later slice), so no name
64
+ // type-checks as an argument to either legacy surface. They remain present-but-unreachable,
65
+ // following the same "always present" contract as addFilter, gated on hooks.attach. There
66
+ // is still no action-hook coreDeps backing until a hook is cataloged. Explicit contribution
67
+ // records below now have real route/tool/widget owners and use those owners' capabilities.
68
+ // No action hooks are cataloged. Preserve CIC U-003's callable denial boundary, but remove
69
+ // the silent no-op: a granted unsupported action fails explicitly until a real owner exists.
70
+ addAction: gate("hooks.attach", (..._args) => { throw new Error('no plugin action hooks are cataloged'); }),
71
+ addContribution: (input, options = {}) => {
72
+ // Legacy positional hook calls have no contribution hook in the catalog. Deny first for
73
+ // ungranted hooks, preserving the old SDK's classified security failure.
74
+ if (!input || typeof input !== 'object') {
75
+ gate("hooks.attach", () => { throw new Error('use an explicit route, tool or widget contribution'); })();
76
+ return;
77
+ }
78
+ switch (input.kind) {
79
+ case 'route':
80
+ sdk.routes.add(input.value, options);
81
+ return;
82
+ case 'tool':
83
+ sdk.tools.add(input.value, options);
84
+ return;
85
+ case 'widget':
86
+ sdk.widgets.add(input.value, options);
87
+ return;
88
+ default: throw new Error('unsupported plugin contribution kind');
89
+ }
90
+ },
91
+ };
92
+ return required.pluginSdkBinding.buildSdk({ sdk });
93
+ }
94
+ //# sourceMappingURL=capability-sdk.js.map