@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,323 @@
1
+ /** Site-scoped source authoring. Drafts never enter discovery; publication belongs to the
2
+ * existing installer. Node filesystem effects live here, host SDK/policy/reload stay ports. */
3
+ import { lstat, mkdir, mkdtemp, readdir, rename, rm, writeFile, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import * as semver from 'semver';
7
+ import { withFileLock, FileLockTimeoutError } from '@jini-ai/platform/fs/file-lock';
8
+ import { validateManifest, validatePluginIdFormat } from '../manifest.js';
9
+ import { computePluginIntegrity, digestSitePluginSnapshot, snapshotSitePluginPackage } from './install.js';
10
+ export class PluginSourceError extends Error {
11
+ code;
12
+ constructor(code, message) {
13
+ super(message);
14
+ this.code = code;
15
+ this.name = 'PluginSourceError';
16
+ }
17
+ }
18
+ export const PLUGIN_SOURCE_LIMITS = { maxFileBytes: 1024 * 1024, maxTotalBytes: 8 * 1024 * 1024, maxEntries: 512 };
19
+ const MANIFEST = 'tovu.plugin.json';
20
+ function fail(code, message) { throw new PluginSourceError(code, message); }
21
+ function safeId(id) {
22
+ if (typeof id !== 'string' || validatePluginIdFormat({ id }, {}).length)
23
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'Use a lowercase plugin id of at most 50 characters containing letters, numbers and hyphens.');
24
+ }
25
+ /** Reject both POSIX and Windows absolute/traversal syntax, even on a POSIX host. */
26
+ function safeFile(file) {
27
+ if (typeof file !== 'string' || !file || file.includes('\\') || file.includes('\0') || path.posix.isAbsolute(file) || path.win32.isAbsolute(file) || file.split('/').some(part => !part || part === '.' || part === '..')) {
28
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'File paths must be relative to the draft, without .., absolute paths or empty segments.');
29
+ }
30
+ }
31
+ async function exists(target) {
32
+ try {
33
+ await lstat(target);
34
+ return true;
35
+ }
36
+ catch (error) {
37
+ if (error.code === 'ENOENT')
38
+ return false;
39
+ throw error;
40
+ }
41
+ }
42
+ /** Checks every existing segment, including the configured root. Like the installer, this
43
+ * rejects links and hardlinks; a hostile concurrent native process is outside this boundary. */
44
+ async function confined(root, target) {
45
+ const relative = path.relative(root, target);
46
+ if (relative)
47
+ safeFile(relative.split(path.sep).join('/'));
48
+ let current = root;
49
+ for (const segment of ['', ...relative.split(path.sep).filter(Boolean)]) {
50
+ if (segment)
51
+ current = path.join(current, segment);
52
+ if (!await exists(current))
53
+ continue;
54
+ const info = await lstat(current);
55
+ if (info.isSymbolicLink() || (info.isFile() && info.nlink !== 1))
56
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'Draft and installed paths must not contain symbolic or hard links.');
57
+ if (current !== target && !info.isDirectory())
58
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'A parent path is not a directory.');
59
+ }
60
+ }
61
+ /** Whole-file writes publish by rename, so readers cannot observe a half-written file. */
62
+ async function writeAtomic(root, target, bytes) {
63
+ await confined(root, target);
64
+ await mkdir(path.dirname(target), { recursive: true });
65
+ const temporary = await mkdtemp(path.join(path.dirname(target), '.write-'));
66
+ try {
67
+ const file = path.join(temporary, 'file');
68
+ await writeFile(file, bytes, { flag: 'wx', mode: 0o600 });
69
+ await confined(root, target);
70
+ await rename(file, target);
71
+ }
72
+ finally {
73
+ await rm(temporary, { recursive: true, force: true });
74
+ }
75
+ }
76
+ function jsonBytes(value) { return Buffer.from(JSON.stringify(value, null, 2) + '\n'); }
77
+ /** Build the bounded Node draft adapter.
78
+ * @param required Site path and injected manifest, installer, policy and reload owners.
79
+ * @param optional.temporaryDir External sealing staging root; defaults to the OS temp directory.
80
+ * @returns The source tool port. Typed source/install errors describe refusals; filesystem faults reject.
81
+ * @example createPluginSourceService({ ...host, installDir, installer, policy, reload, builtInIds: [], scaffoldEntry }, {})
82
+ * @complexity O(package bytes) per operation, capped at 8 MiB / 512 entries.
83
+ */
84
+ export function createPluginSourceService(required, optional = {}) {
85
+ const root = path.resolve(required.installDir);
86
+ const drafts = path.join(root, '.drafts');
87
+ const draft = (id) => path.join(drafts, id);
88
+ const marker = (id, version) => path.join(drafts, '.sealed', id, version, 'digest.json');
89
+ /** Cross-process source lock serializes edits with seal snapshots. Installer keeps its own
90
+ * publication lock. Platform records pid/time and reclaims only dead owners; age alone must
91
+ * never steal a long seal from a live process. Token-owned release preserves a replacement. */
92
+ async function locked(id, action, options = {}) {
93
+ safeId(id);
94
+ if (required.builtInIds.some(builtIn => builtIn.toLowerCase() === id))
95
+ fail('PLUGIN_SHADOWS_BUILT_IN', 'Built-in plugin source cannot be edited.');
96
+ await confined(root, root);
97
+ if (options.createRoot)
98
+ await mkdir(root, { recursive: true });
99
+ else if (!await exists(root))
100
+ fail('PLUGIN_SOURCE_DRAFT_MISSING', 'Create or open a plugin draft first.');
101
+ try {
102
+ return await withFileLock({ lockPath: root + '-source-lock', run: action }, { ...optional.lockPorts, timeoutMs: 100, staleMs: Infinity });
103
+ }
104
+ catch (error) {
105
+ if (error instanceof FileLockTimeoutError)
106
+ fail('PLUGIN_SOURCE_BUSY', 'Another source operation is in progress. Retry after it finishes.');
107
+ throw error;
108
+ }
109
+ }
110
+ async function versions(id) {
111
+ const slot = path.join(root, id);
112
+ await confined(root, slot);
113
+ if (!await exists(slot))
114
+ return [];
115
+ const entries = (await readdir(slot)).filter(name => !name.startsWith('.'));
116
+ if (entries.some(version => !semver.valid(version)))
117
+ fail('PLUGIN_SOURCE_VERSION_INVALID', 'Installed plugin has an unrecognized version folder.');
118
+ return entries.sort(semver.rcompare);
119
+ }
120
+ async function snapshot(location) {
121
+ await confined(root, location);
122
+ if (!await exists(location))
123
+ fail('PLUGIN_SOURCE_DRAFT_MISSING', 'Open an installed plugin with plugin_source_open or scaffold it with plugin_source_create first.');
124
+ return snapshotSitePluginPackage({ sourceDir: location }, PLUGIN_SOURCE_LIMITS);
125
+ }
126
+ async function putDraft(id, files) {
127
+ await confined(root, draft(id));
128
+ await confined(root, drafts);
129
+ await mkdir(drafts, { recursive: true });
130
+ const staging = await mkdtemp(path.join(drafts, '.open-'));
131
+ try {
132
+ for (const [file, bytes] of files) {
133
+ safeFile(file);
134
+ await writeAtomic(root, path.join(staging, file), bytes);
135
+ }
136
+ await confined(root, draft(id));
137
+ await rename(staging, draft(id));
138
+ }
139
+ finally {
140
+ await rm(staging, { recursive: true, force: true });
141
+ }
142
+ }
143
+ async function open(id) {
144
+ await confined(root, draft(id));
145
+ if (await exists(draft(id))) {
146
+ await snapshot(draft(id));
147
+ return { created: false };
148
+ }
149
+ const latest = (await versions(id))[0];
150
+ if (!latest)
151
+ fail('PLUGIN_SOURCE_NOT_INSTALLED', 'No installed version exists. Use plugin_source_create to scaffold this plugin.');
152
+ const files = await snapshot(path.join(root, id, latest));
153
+ await putDraft(id, files);
154
+ return { created: true };
155
+ }
156
+ async function write(id, file, content) {
157
+ safeFile(file);
158
+ // Bound path depth before filesystem probes can fail with an OS-specific path-length error.
159
+ const segments = file.split('/');
160
+ if (segments.length > PLUGIN_SOURCE_LIMITS.maxEntries)
161
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 512 entries.');
162
+ if (typeof content !== 'string')
163
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'File content must be a string.');
164
+ const bytes = Buffer.from(content);
165
+ if (bytes.length > PLUGIN_SOURCE_LIMITS.maxFileBytes)
166
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'A draft file may contain at most 1 MiB.');
167
+ const files = await snapshot(draft(id));
168
+ await confined(root, path.join(draft(id), file));
169
+ if (await exists(path.join(draft(id), file)) && (await lstat(path.join(draft(id), file))).isDirectory())
170
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'The requested file path is a directory.');
171
+ files.set(file, bytes);
172
+ const total = [...files.values()].reduce((sum, value) => sum + value.length, 0);
173
+ // The snapshot count includes empty directories, which a files-only map would miss.
174
+ let addedEntries = 0;
175
+ for (let index = 1; index <= segments.length; index++) {
176
+ if (!await exists(path.join(draft(id), ...segments.slice(0, index))))
177
+ addedEntries++;
178
+ }
179
+ if (total > PLUGIN_SOURCE_LIMITS.maxTotalBytes || files.entryCount + addedEntries > PLUGIN_SOURCE_LIMITS.maxEntries)
180
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 8 MiB or 512 entries.');
181
+ await writeAtomic(root, path.join(draft(id), file), bytes);
182
+ return { bytesWritten: bytes.length };
183
+ }
184
+ async function read(id, file) {
185
+ safeFile(file);
186
+ const files = await snapshot(draft(id));
187
+ const bytes = files.get(file);
188
+ if (!bytes)
189
+ fail('PLUGIN_SOURCE_FILE_MISSING', 'The requested file is not in the draft.');
190
+ return { content: bytes.toString('utf8'), bytes: bytes.length, digest: digestSitePluginSnapshot({ files: new Map([[file, bytes]]) }) };
191
+ }
192
+ function validate(id, manifest) {
193
+ const errors = validateManifest({ ...required, manifest, folderName: id, builtInIds: required.builtInIds }).errors;
194
+ if (errors.length)
195
+ fail('PLUGIN_MANIFEST_INVALID', errors.map(error => error.message).join('; '));
196
+ }
197
+ /** Install a sealed, immutable copy outside discovery's tree. No alternate installer or ZIP
198
+ * encoder is needed; the folder installer refuses sources inside its own destination. */
199
+ async function publish(id, files, rollbackFrom) {
200
+ if (!required.policy.localInstallEnabled({}, {}))
201
+ fail('PLUGIN_LOCAL_INSTALL_DISABLED', 'Hosted plugin installs require TOVU_PLUGIN_LOCAL_INSTALL=1.');
202
+ let raw;
203
+ try {
204
+ raw = JSON.parse(files.get(MANIFEST)?.toString('utf8') ?? '');
205
+ }
206
+ catch {
207
+ return fail('PLUGIN_MANIFEST_INVALID', 'A valid tovu.plugin.json is required.');
208
+ }
209
+ validate(id, raw);
210
+ const manifest = raw;
211
+ if (manifest.id !== id)
212
+ fail('PLUGIN_MANIFEST_INVALID', 'The manifest id must match the draft id.');
213
+ const latest = (await versions(id))[0];
214
+ const declaredVersion = String(manifest.version);
215
+ const version = latest && !semver.gt(declaredVersion, latest) ? semver.inc(latest, 'patch') : declaredVersion;
216
+ if (!version)
217
+ fail('PLUGIN_SOURCE_VERSION_INVALID', 'A valid semantic version is required.');
218
+ const staging = await mkdtemp(path.join(optional.temporaryDir ?? tmpdir(), 'plugin-source-'));
219
+ try {
220
+ for (const [file, bytes] of files) {
221
+ safeFile(file);
222
+ await writeAtomic(staging, path.join(staging, file), bytes);
223
+ }
224
+ const integrity = await computePluginIntegrity({ sourceDir: staging });
225
+ await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, version, integrity }));
226
+ const input = { sourceDir: staging };
227
+ const preview = await required.installer.preview(input, { versionAppend: true });
228
+ const plugin = await required.installer.install({ ...input, expectedDigest: preview.digest }, { versionAppend: true });
229
+ // Host-owned, digest-bound provenance cannot be claimed by a manifest or written through
230
+ // a draft path. Tier-3 has full server access by owner decision (2026-10-09), so this is an
231
+ // assistant-tool boundary, not isolation from executing code. TODO: sandbox tier-3 later.
232
+ await writeAtomic(root, marker(id, version), jsonBytes({ digest: plugin.digest }));
233
+ let reloaded = false;
234
+ try {
235
+ reloaded = await required.reload({ id }, {});
236
+ }
237
+ catch (error) {
238
+ return { installed: true, plugin, reloaded: false, reloadError: error instanceof Error ? error.message : String(error), ...(rollbackFrom ? { rollbackFrom } : {}) };
239
+ }
240
+ // Failed reloads retain all recovery bytes. The installer owns which versions are safe to
241
+ // retire, including old active pointers belonging to other workspaces.
242
+ for (const retired of await required.pruneVersions({ id }, {})) {
243
+ await confined(root, marker(id, retired));
244
+ await rm(path.dirname(marker(id, retired)), { recursive: true, force: true });
245
+ }
246
+ return { installed: true, plugin, reloaded, ...(rollbackFrom ? { rollbackFrom } : {}) };
247
+ }
248
+ finally {
249
+ await rm(staging, { recursive: true, force: true });
250
+ }
251
+ }
252
+ return {
253
+ create: ({ id, name, description }, _options = {}) => locked(id, async () => {
254
+ if (typeof name !== 'string' || !name.trim() || typeof description !== 'string')
255
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'A name and description are required.');
256
+ if (Buffer.byteLength(name + description) > 64 * 1024)
257
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Scaffold metadata exceeds 64 KiB.');
258
+ await confined(root, draft(id));
259
+ if (await exists(draft(id)) || (await versions(id)).length)
260
+ return open(id);
261
+ // Description belongs in README: the host manifest validator forbids that top-level key.
262
+ const manifest = { id, name, version: '0.1.0', engine: 1, sdkRange: '^' + required.pluginSdkBinding.runtimeSdkVersion, tier: 'tier-3', capabilities: [], hooks: [], fields: [], integrity: {} };
263
+ validate(id, manifest);
264
+ await putDraft(id, new Map([[MANIFEST, jsonBytes(manifest)], ['server/index.mjs', Buffer.from(required.scaffoldEntry)], ['README.md', Buffer.from(`${name}\n\n${description}\n\nSite-local tier-3 plugin. Full server access; sandboxing is deferred.\n`)]]));
265
+ const integrity = await computePluginIntegrity({ sourceDir: draft(id) });
266
+ await writeAtomic(root, path.join(draft(id), MANIFEST), jsonBytes({ ...manifest, integrity }));
267
+ return { created: true };
268
+ }, { createRoot: true }),
269
+ open: ({ id }, _options = {}) => locked(id, () => open(id)),
270
+ list: ({ id }, _options = {}) => locked(id, async () => ({ files: [...await snapshot(draft(id))].map(([file, bytes]) => ({ path: file, bytes: bytes.length })) })),
271
+ read: ({ id, path: file }, _options = {}) => locked(id, () => read(id, file)),
272
+ write: ({ id, path: file, content }, _options = {}) => locked(id, () => write(id, file, content)),
273
+ edit: ({ id, path: file, oldString, newString, replaceAll }, _options = {}) => locked(id, async () => {
274
+ if (typeof oldString !== 'string' || !oldString || typeof newString !== 'string' || (replaceAll !== undefined && typeof replaceAll !== 'boolean'))
275
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'Provide a nonempty oldString, a newString and optional boolean replaceAll.');
276
+ const { content, bytes } = await read(id, file);
277
+ const parts = content.split(oldString);
278
+ const replacements = parts.length - 1;
279
+ if (!replacements || (replacements > 1 && !replaceAll))
280
+ fail('PLUGIN_SOURCE_EDIT_MISMATCH', 'oldString must match exactly once; use more context or replaceAll:true. Nothing was written.');
281
+ // Bound replacement expansion BEFORE joining: many short matches must not allocate a
282
+ // huge string only to have write() refuse it afterwards. write() also checks actual bytes.
283
+ const projectedBytes = bytes + replacements * (Buffer.byteLength(newString) - Buffer.byteLength(oldString));
284
+ if (projectedBytes > PLUGIN_SOURCE_LIMITS.maxFileBytes)
285
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'An edited draft file may contain at most 1 MiB.');
286
+ return { ...await write(id, file, parts.join(newString)), replacements };
287
+ }),
288
+ delete: ({ id, path: file }, options = {}) => locked(id, async () => {
289
+ const current = await read(id, file);
290
+ if (options.expectedDigest !== undefined && current.digest !== options.expectedDigest)
291
+ fail('PLUGIN_SOURCE_CHANGED', 'The draft file changed while awaiting approval. Nothing was deleted; review it again.');
292
+ const target = path.join(draft(id), file);
293
+ await confined(root, target);
294
+ await unlink(target);
295
+ return { deleted: true };
296
+ }),
297
+ seal: ({ id }, _options = {}) => locked(id, async () => publish(id, await snapshot(draft(id)))),
298
+ rollback: ({ id }, _options = {}) => locked(id, async () => {
299
+ const previous = (await versions(id))[1];
300
+ if (!previous)
301
+ fail('PLUGIN_SOURCE_NO_ROLLBACK', 'No previous installed version is available.');
302
+ return publish(id, await snapshot(path.join(root, id, previous)), previous);
303
+ }),
304
+ isSealedHere: async ({ id, version }, _options = {}) => {
305
+ safeId(id);
306
+ if (required.builtInIds.some(builtIn => builtIn.toLowerCase() === id) || !await exists(root))
307
+ return false;
308
+ // Provenance and installed packages are immutable and published by rename. A read needs
309
+ // no source lock; enabling during a seal must not fail with PLUGIN_SOURCE_BUSY.
310
+ if (!semver.valid(version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version))
311
+ return false;
312
+ const provenance = marker(id, version);
313
+ await confined(root, provenance);
314
+ if (!await exists(provenance))
315
+ return false;
316
+ const parent = path.dirname(provenance);
317
+ const markers = await snapshotSitePluginPackage({ sourceDir: parent }, PLUGIN_SOURCE_LIMITS);
318
+ const digest = JSON.parse(markers.get(path.basename(provenance)).toString('utf8')).digest;
319
+ return digest === digestSitePluginSnapshot({ files: await snapshot(path.join(root, id, version)) });
320
+ },
321
+ };
322
+ }
323
+ //# sourceMappingURL=source-drafts.js.map
@@ -0,0 +1,75 @@
1
+ import type { ManifestHostPorts } from "./ports.js";
2
+ import type { PluginActivationRecord } from "./activation.js";
3
+ import { type ClaimMode, type ExtensionClaim } from "./claim-conflicts.js";
4
+ import type { PluginDiscoveryRecord } from "./discovery-types.js";
5
+ import { CORE_OWNER_ID, type PluginManifest } from "./manifest.js";
6
+ /** The owner id core's claims are filed under, and how messages name it. */
7
+ export { CORE_OWNER_ID };
8
+ /**
9
+ * `plugin_capability_<pluginId>` — the agent tool `capability-tool-registrations.ts` generates for a
10
+ * plugin that declares `fields` (hyphens folded to underscores, matching `agent_plugin_<pluginId>`'s
11
+ * own scheme). Moved here from that file (2026-10-04) so the tool's registration and the claim it
12
+ * makes for conflict detection derive the id from ONE function and cannot drift apart.
13
+ */
14
+ export declare function capabilityToolIdFor({ pluginId }: {
15
+ pluginId: string;
16
+ }, _optional?: Record<string, never>): string;
17
+ /** One conflict, as the admin screen and the agent see it — the detector's conflict plus the
18
+ * holder's display name. */
19
+ export interface PluginConflict {
20
+ readonly kind: string;
21
+ readonly key: string;
22
+ readonly heldBy: string;
23
+ readonly heldByName: string;
24
+ readonly heldKey: string;
25
+ }
26
+ /** Every claim one manifest makes (see this file's header for the four sources). */
27
+ export declare function pluginClaimsFromManifest(required: {
28
+ readonly manifest: PluginManifest;
29
+ } & Pick<ManifestHostPorts, "pluginSdkBinding" | "declarativeContentTypes">, optional?: {
30
+ readonly hookSemantics?: Readonly<Record<string, ClaimMode>>;
31
+ }): ExtensionClaim[];
32
+ export interface ResolvePluginConflictsRequired extends Pick<ManifestHostPorts, "pluginSdkBinding" | "declarativeContentTypes" | "coreOwnerName"> {
33
+ readonly workspaceId: string;
34
+ readonly discovery: readonly PluginDiscoveryRecord[];
35
+ readonly activations: readonly PluginActivationRecord[];
36
+ readonly coreClaims: readonly ExtensionClaim[];
37
+ }
38
+ export interface ResolvePluginConflictsOptional {
39
+ /** The plugin being turned on right now — ordered after every other enabled plugin. */
40
+ readonly candidateId?: string;
41
+ readonly hookSemantics?: Readonly<Record<string, ClaimMode>>;
42
+ }
43
+ /**
44
+ * Every plugin in `discovery` that has a conflict: an ENABLED plugin that loses to core or an
45
+ * earlier-enabled plugin, and a valid plugin that is OFF but would lose if turned on now.
46
+ *
47
+ * @complexity O(P · S²) — one detector pass for the enabled set plus one per disabled plugin, each
48
+ * over a site's handful of plugins.
49
+ */
50
+ export declare function resolvePluginConflicts(required: ResolvePluginConflictsRequired, optional?: ResolvePluginConflictsOptional): ReadonlyMap<string, readonly PluginConflict[]>;
51
+ /** Every conflict in words, `; `-joined — shared by the enable refusal and the boot quarantine reason. */
52
+ export declare function describeConflictList({ conflicts }: {
53
+ conflicts: readonly PluginConflict[];
54
+ }, _optional?: Record<string, never>): string;
55
+ /** The operator- and agent-facing sentence for a refused plugin: what clashes, who holds it, what to do. */
56
+ export declare function describePluginConflicts(required: {
57
+ readonly pluginId: string;
58
+ readonly conflicts: readonly PluginConflict[];
59
+ }, _optional?: Record<string, never>): string;
60
+ /** The durable quarantine reason when boot turns a plugin off for a conflict (shown on the admin row). */
61
+ export declare function describeBootConflictQuarantine({ conflicts }: {
62
+ conflicts: readonly PluginConflict[];
63
+ }, _optional?: Record<string, never>): string;
64
+ /** Thrown by the enable path when a plugin would take a name core or an enabled plugin holds.
65
+ * Its message is built only from plugin ids/names and the manifest's own declared names, so it is
66
+ * safe to show an agent verbatim (see `tool-registrations.ts`'s model-facing rule). */
67
+ export declare class PluginConflictError extends Error {
68
+ readonly pluginId: string;
69
+ readonly conflicts: readonly PluginConflict[];
70
+ constructor(required: {
71
+ readonly pluginId: string;
72
+ readonly conflicts: readonly PluginConflict[];
73
+ }, _optional?: Record<string, never>);
74
+ }
75
+ //# sourceMappingURL=plugin-claims.d.ts.map
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @file Tovu's plugin conflict rules on top of the neutral detector (`claim-conflicts.ts`):
3
+ * what a `tovu.plugin.json` claims, who keeps a contested name, and the sentence an operator or an
4
+ * agent reads when a plugin is refused.
5
+ *
6
+ * Spec note: `ADS-memory/specs/005-plugin-system/conflicts.spec.md`.
7
+ *
8
+ * ## What a plugin claims
9
+ * - every `contributes` entry (routes, tools, tables, settings, widgets, permissions) — exclusive;
10
+ * - every hook it attaches, with the HOST's semantics for that hook ({@link PLUGIN_HOOK_SEMANTICS}):
11
+ * `content.entry.beforeSave` is a shared pipeline — every enabled filter runs in TB-01 order and
12
+ * writes only its own `ext.{id}` namespace (BR-04), so two plugins on it is the design, not a
13
+ * clash. A hook this table does not know is treated as EXCLUSIVE: a newly added hook point that
14
+ * nobody classified must fail safe (refuse the second plugin) rather than silently stack;
15
+ * - its generated capability tool (`plugin_capability_<id>`) when it declares `fields`, because
16
+ * that tool is registered in the same agent tool registry as everything else;
17
+ * - every content type it declares (`contentTypes[].key`, kind `content-type`, AW-7 Tier 1) — one
18
+ * key is one Collection, so the second plugin to declare `faq` is refused here instead of
19
+ * silently sharing (or schema-clashing on) the first one's type.
20
+ * Field paths are NOT claims: `validateManifest` already forces them under `ext.{id}.`, and ids are
21
+ * unique (ID_DUPLICATE / SHADOWS_BUILT_IN), so two plugins can never name the same field.
22
+ *
23
+ * ## Who wins
24
+ * Core first, always. Then plugins in the order they were turned on (activation `updatedAt`
25
+ * ascending; built-in before site, then id, only to break exact ties), so the plugin that was
26
+ * already working keeps working and the NEWER one is refused. At enable time the plugin being
27
+ * turned on is placed last regardless of timestamps — it is by definition the newer one, even
28
+ * when a coarse or fixed clock gives it the same `updatedAt` as an earlier plugin.
29
+ *
30
+ * ## Where it runs (composition: `server/runtime/composition/plugin-runtime.ts`)
31
+ * - enable (admin route, agent tool, activation poll): `onPluginEnabled` throws
32
+ * {@link PluginConflictError} before any plugin code is imported; `setPluginEnabled` then restores
33
+ * the prior activation row, so a refused enable leaves nothing half-on;
34
+ * - boot: `attachEnabledPluginsAtBoot` resolves every enabled plugin together and QUARANTINES the
35
+ * losers through `quarantine.ts` (the same durable "disabled + reason" record hook failures use);
36
+ * - list (admin screen, `plugins_list`): `listPluginConflicts` reports enabled losers and the clash a
37
+ * disabled plugin WOULD hit if turned on now, so the operator sees it before clicking.
38
+ */
39
+ import { pluginToolIdFor } from './contributions.js';
40
+ import { normalizeRoute, resolveClaimConflicts } from "./claim-conflicts.js";
41
+ import { CORE_OWNER_ID } from "./manifest.js";
42
+ /** The owner id core's claims are filed under, and how messages name it. */
43
+ export { CORE_OWNER_ID };
44
+ /** How each host hook point arbitrates several plugins (see this file's header). */
45
+ // Hook semantics are supplied by PluginSdkBinding; product hook names remain host-owned.
46
+ /** `contributes` list -> claim kind. */
47
+ const CONTRIBUTION_KINDS = [
48
+ ["routes", "route"],
49
+ ["tools", "tool"],
50
+ ["tables", "table"],
51
+ ["settings", "setting"],
52
+ ["widgets", "widget"],
53
+ ["permissions", "permission"],
54
+ ];
55
+ /**
56
+ * `plugin_capability_<pluginId>` — the agent tool `capability-tool-registrations.ts` generates for a
57
+ * plugin that declares `fields` (hyphens folded to underscores, matching `agent_plugin_<pluginId>`'s
58
+ * own scheme). Moved here from that file (2026-10-04) so the tool's registration and the claim it
59
+ * makes for conflict detection derive the id from ONE function and cannot drift apart.
60
+ */
61
+ export function capabilityToolIdFor({ pluginId }, _optional = {}) {
62
+ return `plugin_capability_${pluginId.replace(/-/g, "_")}`;
63
+ }
64
+ /** Every claim one manifest makes (see this file's header for the four sources). */
65
+ export function pluginClaimsFromManifest(required, optional = {}) {
66
+ const { manifest } = required;
67
+ const hookSemantics = optional.hookSemantics ?? required.pluginSdkBinding.hookSemantics;
68
+ const contributes = manifest.contributes ?? {};
69
+ const declared = CONTRIBUTION_KINDS.flatMap(([list, kind]) => (contributes[list] ?? []).flatMap((key) => {
70
+ // Claim the mounted identity, not the plugin-local spelling. Two plugins may both search
71
+ // or serve /items without competing for either other's names or a core tool's name.
72
+ if (list === 'routes')
73
+ return normalizeRoute({ key }).map(slot => {
74
+ const space = slot.indexOf(' ');
75
+ return { kind, key: `${slot.slice(0, space)} /api/p/${manifest.id}${slot.slice(space + 1)}`, mode: 'exclusive' };
76
+ });
77
+ return [{ kind, key: list === 'tools' ? pluginToolIdFor({ pluginId: manifest.id, name: key }) : key, mode: 'exclusive' }];
78
+ }));
79
+ const hooks = manifest.hooks.map((key) => ({ kind: "hook", key, mode: hookSemantics[key] ?? "exclusive" }));
80
+ const generated = manifest.fields.length > 0 ? [{ kind: "tool", key: capabilityToolIdFor({ pluginId: manifest.id }), mode: "exclusive" }] : [];
81
+ const contentTypes = required.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => ({ kind: "content-type", key: decl.key, mode: "exclusive" }));
82
+ return [...declared, ...hooks, ...generated, ...contentTypes];
83
+ }
84
+ const SOURCE_RANK = { "built-in": 0, site: 1 };
85
+ /** Earliest-enabled first; `candidateId` always last (see this file's header, "Who wins"). */
86
+ function comparePrecedence(candidateId) {
87
+ return (a, b) => {
88
+ const candidateOrder = Number(a.record.id === candidateId) - Number(b.record.id === candidateId);
89
+ if (candidateOrder !== 0)
90
+ return candidateOrder;
91
+ const timeOrder = a.activation.updatedAt.localeCompare(b.activation.updatedAt);
92
+ if (timeOrder !== 0)
93
+ return timeOrder;
94
+ const sourceOrder = SOURCE_RANK[a.record.source] - SOURCE_RANK[b.record.source];
95
+ return sourceOrder !== 0 ? sourceOrder : a.record.id.localeCompare(b.record.id);
96
+ };
97
+ }
98
+ function hasManifest(record) {
99
+ return record.status === "valid" && record.manifest !== undefined;
100
+ }
101
+ function toPluginConflicts(conflicts, names) {
102
+ return conflicts.map((conflict) => ({
103
+ kind: conflict.kind,
104
+ key: conflict.key,
105
+ heldBy: conflict.heldBy,
106
+ heldByName: names.get(conflict.heldBy) ?? conflict.heldBy,
107
+ heldKey: conflict.heldKey,
108
+ }));
109
+ }
110
+ /**
111
+ * Every plugin in `discovery` that has a conflict: an ENABLED plugin that loses to core or an
112
+ * earlier-enabled plugin, and a valid plugin that is OFF but would lose if turned on now.
113
+ *
114
+ * @complexity O(P · S²) — one detector pass for the enabled set plus one per disabled plugin, each
115
+ * over a site's handful of plugins.
116
+ */
117
+ export function resolvePluginConflicts(required, optional = {}) {
118
+ const { workspaceId, discovery, activations, coreClaims } = required;
119
+ const claimsOf = (record) => ({
120
+ id: record.id,
121
+ claims: pluginClaimsFromManifest({ ...required, manifest: record.manifest }, optional.hookSemantics ? { hookSemantics: optional.hookSemantics } : {}),
122
+ });
123
+ const here = new Map(activations.filter((row) => row.workspaceId === workspaceId).map((row) => [row.pluginId, row]));
124
+ const valid = discovery.filter(hasManifest);
125
+ const enabled = valid
126
+ .flatMap((record) => {
127
+ const activation = here.get(record.id);
128
+ return activation?.enabled ? [{ record, activation }] : [];
129
+ })
130
+ .sort(comparePrecedence(optional.candidateId));
131
+ const names = new Map([[CORE_OWNER_ID, required.coreOwnerName], ...valid.map((record) => [record.id, record.name])]);
132
+ const core = { id: CORE_OWNER_ID, claims: coreClaims };
133
+ const live = resolveClaimConflicts({ owners: [core, ...enabled.map((each) => claimsOf(each.record))] });
134
+ const result = new Map();
135
+ for (const [ownerId, conflicts] of live.refused)
136
+ result.set(ownerId, toPluginConflicts(conflicts, names));
137
+ const accepted = new Set(live.accepted);
138
+ const holders = [core, ...enabled.filter((each) => accepted.has(each.record.id)).map((each) => claimsOf(each.record))];
139
+ for (const record of valid) {
140
+ if (here.get(record.id)?.enabled)
141
+ continue;
142
+ const wouldBe = resolveClaimConflicts({ owners: [...holders, claimsOf(record)] }).refused.get(record.id);
143
+ if (wouldBe)
144
+ result.set(record.id, toPluginConflicts(wouldBe, names));
145
+ }
146
+ return result;
147
+ }
148
+ /** One conflict, in words: `tool 'x' is provided by plugin 'a' (A)` / `... is reserved by Tovu core ('/api/*')`. */
149
+ function describeOne(conflict) {
150
+ const holder = conflict.heldBy === CORE_OWNER_ID
151
+ ? `is reserved by ${conflict.heldByName}${conflict.heldKey === conflict.key ? "" : ` ('${conflict.heldKey}')`}`
152
+ : `is provided by plugin '${conflict.heldBy}' (${conflict.heldByName})`;
153
+ return `${conflict.kind} '${conflict.key}' ${holder}`;
154
+ }
155
+ /** Every conflict in words, `; `-joined — shared by the enable refusal and the boot quarantine reason. */
156
+ export function describeConflictList({ conflicts }, _optional = {}) {
157
+ return conflicts.map(describeOne).join("; ");
158
+ }
159
+ /** The operator- and agent-facing sentence for a refused plugin: what clashes, who holds it, what to do. */
160
+ export function describePluginConflicts(required, _optional = {}) {
161
+ const { pluginId, conflicts } = required;
162
+ return (`Plugin '${pluginId}' was not turned on because it claims things already in use: ` +
163
+ `${describeConflictList({ conflicts })}. Turn off the other plugin first, or keep '${pluginId}' off.`);
164
+ }
165
+ /** The durable quarantine reason when boot turns a plugin off for a conflict (shown on the admin row). */
166
+ export function describeBootConflictQuarantine({ conflicts }, _optional = {}) {
167
+ return `Turned off at startup because it claims things already in use: ${describeConflictList({ conflicts })}. Turn off the other plugin, then turn this one back on.`;
168
+ }
169
+ /** Thrown by the enable path when a plugin would take a name core or an enabled plugin holds.
170
+ * Its message is built only from plugin ids/names and the manifest's own declared names, so it is
171
+ * safe to show an agent verbatim (see `tool-registrations.ts`'s model-facing rule). */
172
+ export class PluginConflictError extends Error {
173
+ pluginId;
174
+ conflicts;
175
+ constructor(required, _optional = {}) {
176
+ super(describePluginConflicts(required));
177
+ this.name = "PluginConflictError";
178
+ this.pluginId = required.pluginId;
179
+ this.conflicts = required.conflicts;
180
+ }
181
+ }
182
+ //# sourceMappingURL=plugin-claims.js.map