@jini-ai/plugins 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,104 @@
1
+ import { type FileLockOptions } from '@jini-ai/platform/fs/file-lock';
2
+ import type { ManifestHostPorts } from '../ports.js';
3
+ import type { PluginSourcePolicyPort } from '../source-policy.js';
4
+ import { type PluginInstallerPort, type PluginInstallPreview } from './install.js';
5
+ export declare class PluginSourceError extends Error {
6
+ readonly code: string;
7
+ constructor(code: string, message: string);
8
+ }
9
+ export declare const PLUGIN_SOURCE_LIMITS: {
10
+ readonly maxFileBytes: number;
11
+ readonly maxTotalBytes: number;
12
+ readonly maxEntries: 512;
13
+ };
14
+ type Options = Record<string, never>;
15
+ type Id = {
16
+ id: string;
17
+ };
18
+ type File = Id & {
19
+ path: string;
20
+ };
21
+ export interface PluginSourceSealResult {
22
+ readonly installed: true;
23
+ readonly plugin: PluginInstallPreview;
24
+ readonly reloaded: boolean;
25
+ readonly reloadError?: string;
26
+ readonly rollbackFrom?: string;
27
+ }
28
+ /** Only relative paths and model-facing facts cross this port; no local filesystem handles. */
29
+ export interface PluginSourcePort {
30
+ create(required: Id & {
31
+ name: string;
32
+ description: string;
33
+ }, optional?: Options): Promise<{
34
+ created: boolean;
35
+ }>;
36
+ open(required: Id, optional?: Options): Promise<{
37
+ created: boolean;
38
+ }>;
39
+ list(required: Id, optional?: Options): Promise<{
40
+ files: readonly {
41
+ path: string;
42
+ bytes: number;
43
+ }[];
44
+ }>;
45
+ read(required: File, optional?: Options): Promise<{
46
+ content: string;
47
+ bytes: number;
48
+ digest: string;
49
+ }>;
50
+ write(required: File & {
51
+ content: string;
52
+ }, optional?: Options): Promise<{
53
+ bytesWritten: number;
54
+ }>;
55
+ edit(required: File & {
56
+ oldString: string;
57
+ newString: string;
58
+ replaceAll?: boolean;
59
+ }, optional?: Options): Promise<{
60
+ bytesWritten: number;
61
+ replacements: number;
62
+ }>;
63
+ delete(required: File, optional?: {
64
+ expectedDigest?: string;
65
+ }): Promise<{
66
+ deleted: true;
67
+ }>;
68
+ seal(required: Id, optional?: Options): Promise<PluginSourceSealResult>;
69
+ rollback(required: Id, optional?: Options): Promise<PluginSourceSealResult>;
70
+ isSealedHere(required: Id & {
71
+ version: string;
72
+ }, optional?: Options): Promise<boolean>;
73
+ /** The capability set (`pluginCapabilitySet`) the owner last approved for this id, if any. */
74
+ readApproval(required: Id, optional?: Options): Promise<readonly string[] | undefined>;
75
+ /** Host-only: called after the owner confirmed an enable. Never exposed as a model tool. */
76
+ recordApproval(required: Id & {
77
+ capabilities: readonly string[];
78
+ }, optional?: Options): Promise<void>;
79
+ }
80
+ export interface PluginSourceDeps extends ManifestHostPorts {
81
+ readonly installDir: string;
82
+ readonly builtInIds: readonly string[];
83
+ readonly installer: PluginInstallerPort;
84
+ readonly policy: PluginSourcePolicyPort;
85
+ /** Host ABI text, avoiding an external site's dependency on npm package resolution. */
86
+ readonly scaffoldEntry: string;
87
+ /** Re-enters the validated runtime loader; returns false when this workspace has it OFF. */
88
+ readonly reload: (required: Id, optional?: Options) => Promise<boolean>;
89
+ /** Installer-owned retention runs only after reload succeeds; preserves every active pointer. */
90
+ readonly pruneVersions: (required: Id, optional?: Options) => Promise<readonly string[]>;
91
+ }
92
+ /** Build the bounded Node draft adapter.
93
+ * @param required Site path and injected manifest, installer, policy and reload owners.
94
+ * @param optional.temporaryDir External sealing staging root; defaults to the OS temp directory.
95
+ * @returns The source tool port. Typed source/install errors describe refusals; filesystem faults reject.
96
+ * @example createPluginSourceService({ ...host, installDir, installer, policy, reload, builtInIds: [], scaffoldEntry }, {})
97
+ * @complexity O(package bytes) per operation, capped at 8 MiB / 512 entries.
98
+ */
99
+ export declare function createPluginSourceService(required: PluginSourceDeps, optional?: {
100
+ temporaryDir?: string;
101
+ lockPorts?: Pick<FileLockOptions, 'clock' | 'process' | 'hostname'>;
102
+ }): PluginSourcePort;
103
+ export {};
104
+ //# sourceMappingURL=source-drafts.d.ts.map
@@ -0,0 +1,349 @@
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, readFile, 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
+ // Beside the per-version provenance markers, so version pruning never removes it and no draft
90
+ // path (ids cannot start with '.') can write it. Per site: one approval covers every workspace.
91
+ const approval = (id) => path.join(drafts, '.sealed', id, 'approved.json');
92
+ /** Cross-process source lock serializes edits with seal snapshots. Installer keeps its own
93
+ * publication lock. Platform records pid/time and reclaims only dead owners; age alone must
94
+ * never steal a long seal from a live process. Token-owned release preserves a replacement. */
95
+ async function locked(id, action, options = {}) {
96
+ safeId(id);
97
+ if (required.builtInIds.some(builtIn => builtIn.toLowerCase() === id))
98
+ fail('PLUGIN_SHADOWS_BUILT_IN', 'Built-in plugin source cannot be edited.');
99
+ await confined(root, root);
100
+ if (options.createRoot)
101
+ await mkdir(root, { recursive: true });
102
+ else if (!await exists(root))
103
+ fail('PLUGIN_SOURCE_DRAFT_MISSING', 'Create or open a plugin draft first.');
104
+ try {
105
+ return await withFileLock({ lockPath: root + '-source-lock', run: action }, { ...optional.lockPorts, timeoutMs: 100, staleMs: Infinity });
106
+ }
107
+ catch (error) {
108
+ if (error instanceof FileLockTimeoutError)
109
+ fail('PLUGIN_SOURCE_BUSY', 'Another source operation is in progress. Retry after it finishes.');
110
+ throw error;
111
+ }
112
+ }
113
+ async function versions(id) {
114
+ const slot = path.join(root, id);
115
+ await confined(root, slot);
116
+ if (!await exists(slot))
117
+ return [];
118
+ const entries = (await readdir(slot)).filter(name => !name.startsWith('.'));
119
+ if (entries.some(version => !semver.valid(version)))
120
+ fail('PLUGIN_SOURCE_VERSION_INVALID', 'Installed plugin has an unrecognized version folder.');
121
+ return entries.sort(semver.rcompare);
122
+ }
123
+ async function snapshot(location) {
124
+ await confined(root, location);
125
+ if (!await exists(location))
126
+ fail('PLUGIN_SOURCE_DRAFT_MISSING', 'Open an installed plugin with plugin_source_open or scaffold it with plugin_source_create first.');
127
+ return snapshotSitePluginPackage({ sourceDir: location }, PLUGIN_SOURCE_LIMITS);
128
+ }
129
+ async function putDraft(id, files) {
130
+ await confined(root, draft(id));
131
+ await confined(root, drafts);
132
+ await mkdir(drafts, { recursive: true });
133
+ const staging = await mkdtemp(path.join(drafts, '.open-'));
134
+ try {
135
+ for (const [file, bytes] of files) {
136
+ safeFile(file);
137
+ await writeAtomic(root, path.join(staging, file), bytes);
138
+ }
139
+ await confined(root, draft(id));
140
+ await rename(staging, draft(id));
141
+ }
142
+ finally {
143
+ await rm(staging, { recursive: true, force: true });
144
+ }
145
+ }
146
+ async function open(id) {
147
+ await confined(root, draft(id));
148
+ if (await exists(draft(id))) {
149
+ await snapshot(draft(id));
150
+ return { created: false };
151
+ }
152
+ const latest = (await versions(id))[0];
153
+ if (!latest)
154
+ fail('PLUGIN_SOURCE_NOT_INSTALLED', 'No installed version exists. Use plugin_source_create to scaffold this plugin.');
155
+ const files = await snapshot(path.join(root, id, latest));
156
+ await putDraft(id, files);
157
+ return { created: true };
158
+ }
159
+ async function write(id, file, content) {
160
+ safeFile(file);
161
+ // Bound path depth before filesystem probes can fail with an OS-specific path-length error.
162
+ const segments = file.split('/');
163
+ if (segments.length > PLUGIN_SOURCE_LIMITS.maxEntries)
164
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 512 entries.');
165
+ if (typeof content !== 'string')
166
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'File content must be a string.');
167
+ const bytes = Buffer.from(content);
168
+ if (bytes.length > PLUGIN_SOURCE_LIMITS.maxFileBytes)
169
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'A draft file may contain at most 1 MiB.');
170
+ const files = await snapshot(draft(id));
171
+ await confined(root, path.join(draft(id), file));
172
+ if (await exists(path.join(draft(id), file)) && (await lstat(path.join(draft(id), file))).isDirectory())
173
+ fail('PLUGIN_SOURCE_PATH_INVALID', 'The requested file path is a directory.');
174
+ files.set(file, bytes);
175
+ const total = [...files.values()].reduce((sum, value) => sum + value.length, 0);
176
+ // The snapshot count includes empty directories, which a files-only map would miss.
177
+ let addedEntries = 0;
178
+ for (let index = 1; index <= segments.length; index++) {
179
+ if (!await exists(path.join(draft(id), ...segments.slice(0, index))))
180
+ addedEntries++;
181
+ }
182
+ if (total > PLUGIN_SOURCE_LIMITS.maxTotalBytes || files.entryCount + addedEntries > PLUGIN_SOURCE_LIMITS.maxEntries)
183
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Draft exceeds 8 MiB or 512 entries.');
184
+ await writeAtomic(root, path.join(draft(id), file), bytes);
185
+ return { bytesWritten: bytes.length };
186
+ }
187
+ async function read(id, file) {
188
+ safeFile(file);
189
+ const files = await snapshot(draft(id));
190
+ const bytes = files.get(file);
191
+ if (!bytes)
192
+ fail('PLUGIN_SOURCE_FILE_MISSING', 'The requested file is not in the draft.');
193
+ return { content: bytes.toString('utf8'), bytes: bytes.length, digest: digestSitePluginSnapshot({ files: new Map([[file, bytes]]) }) };
194
+ }
195
+ function validate(id, manifest) {
196
+ const errors = validateManifest({ ...required, manifest, folderName: id, builtInIds: required.builtInIds }).errors;
197
+ if (errors.length)
198
+ fail('PLUGIN_MANIFEST_INVALID', errors.map(error => error.message).join('; '));
199
+ }
200
+ /** Install a sealed, immutable copy outside discovery's tree. No alternate installer or ZIP
201
+ * encoder is needed; the folder installer refuses sources inside its own destination. */
202
+ async function publish(id, files, rollbackFrom) {
203
+ if (!required.policy.localInstallEnabled({}, {}))
204
+ fail('PLUGIN_LOCAL_INSTALL_DISABLED', 'Hosted plugin installs require TOVU_PLUGIN_LOCAL_INSTALL=1.');
205
+ let raw;
206
+ try {
207
+ raw = JSON.parse(files.get(MANIFEST)?.toString('utf8') ?? '');
208
+ }
209
+ catch {
210
+ return fail('PLUGIN_MANIFEST_INVALID', 'A valid tovu.plugin.json is required.');
211
+ }
212
+ validate(id, raw);
213
+ const manifest = raw;
214
+ if (manifest.id !== id)
215
+ fail('PLUGIN_MANIFEST_INVALID', 'The manifest id must match the draft id.');
216
+ const latest = (await versions(id))[0];
217
+ const declaredVersion = String(manifest.version);
218
+ const version = latest && !semver.gt(declaredVersion, latest) ? semver.inc(latest, 'patch') : declaredVersion;
219
+ if (!version)
220
+ fail('PLUGIN_SOURCE_VERSION_INVALID', 'A valid semantic version is required.');
221
+ const staging = await mkdtemp(path.join(optional.temporaryDir ?? tmpdir(), 'plugin-source-'));
222
+ try {
223
+ for (const [file, bytes] of files) {
224
+ safeFile(file);
225
+ await writeAtomic(staging, path.join(staging, file), bytes);
226
+ }
227
+ const integrity = await computePluginIntegrity({ sourceDir: staging });
228
+ await writeAtomic(staging, path.join(staging, MANIFEST), jsonBytes({ ...manifest, version, integrity }));
229
+ const input = { sourceDir: staging };
230
+ const preview = await required.installer.preview(input, { versionAppend: true });
231
+ const plugin = await required.installer.install({ ...input, expectedDigest: preview.digest }, { versionAppend: true });
232
+ // Host-owned, digest-bound provenance cannot be claimed by a manifest or written through
233
+ // a draft path. Tier-3 has full server access by owner decision (2026-10-09), so this is an
234
+ // assistant-tool boundary, not isolation from executing code. TODO: sandbox tier-3 later.
235
+ await writeAtomic(root, marker(id, version), jsonBytes({ digest: plugin.digest }));
236
+ let reloaded = false;
237
+ try {
238
+ reloaded = await required.reload({ id }, {});
239
+ }
240
+ catch (error) {
241
+ return { installed: true, plugin, reloaded: false, reloadError: error instanceof Error ? error.message : String(error), ...(rollbackFrom ? { rollbackFrom } : {}) };
242
+ }
243
+ // Failed reloads retain all recovery bytes. The installer owns which versions are safe to
244
+ // retire, including old active pointers belonging to other workspaces.
245
+ for (const retired of await required.pruneVersions({ id }, {})) {
246
+ await confined(root, marker(id, retired));
247
+ await rm(path.dirname(marker(id, retired)), { recursive: true, force: true });
248
+ }
249
+ return { installed: true, plugin, reloaded, ...(rollbackFrom ? { rollbackFrom } : {}) };
250
+ }
251
+ finally {
252
+ await rm(staging, { recursive: true, force: true });
253
+ }
254
+ }
255
+ return {
256
+ create: ({ id, name, description }, _options = {}) => locked(id, async () => {
257
+ if (typeof name !== 'string' || !name.trim() || typeof description !== 'string')
258
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'A name and description are required.');
259
+ if (Buffer.byteLength(name + description) > 64 * 1024)
260
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'Scaffold metadata exceeds 64 KiB.');
261
+ await confined(root, draft(id));
262
+ if (await exists(draft(id)) || (await versions(id)).length)
263
+ return open(id);
264
+ // Description belongs in README: the host manifest validator forbids that top-level key.
265
+ const manifest = { id, name, version: '0.1.0', engine: 1, sdkRange: '^' + required.pluginSdkBinding.runtimeSdkVersion, tier: 'tier-3', capabilities: [], hooks: [], fields: [], integrity: {} };
266
+ validate(id, manifest);
267
+ 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`)]]));
268
+ const integrity = await computePluginIntegrity({ sourceDir: draft(id) });
269
+ await writeAtomic(root, path.join(draft(id), MANIFEST), jsonBytes({ ...manifest, integrity }));
270
+ return { created: true };
271
+ }, { createRoot: true }),
272
+ open: ({ id }, _options = {}) => locked(id, () => open(id)),
273
+ list: ({ id }, _options = {}) => locked(id, async () => ({ files: [...await snapshot(draft(id))].map(([file, bytes]) => ({ path: file, bytes: bytes.length })) })),
274
+ read: ({ id, path: file }, _options = {}) => locked(id, () => read(id, file)),
275
+ write: ({ id, path: file, content }, _options = {}) => locked(id, () => write(id, file, content)),
276
+ edit: ({ id, path: file, oldString, newString, replaceAll }, _options = {}) => locked(id, async () => {
277
+ if (typeof oldString !== 'string' || !oldString || typeof newString !== 'string' || (replaceAll !== undefined && typeof replaceAll !== 'boolean'))
278
+ fail('PLUGIN_SOURCE_INPUT_INVALID', 'Provide a nonempty oldString, a newString and optional boolean replaceAll.');
279
+ const { content, bytes } = await read(id, file);
280
+ const parts = content.split(oldString);
281
+ const replacements = parts.length - 1;
282
+ if (!replacements || (replacements > 1 && !replaceAll))
283
+ fail('PLUGIN_SOURCE_EDIT_MISMATCH', 'oldString must match exactly once; use more context or replaceAll:true. Nothing was written.');
284
+ // Bound replacement expansion BEFORE joining: many short matches must not allocate a
285
+ // huge string only to have write() refuse it afterwards. write() also checks actual bytes.
286
+ const projectedBytes = bytes + replacements * (Buffer.byteLength(newString) - Buffer.byteLength(oldString));
287
+ if (projectedBytes > PLUGIN_SOURCE_LIMITS.maxFileBytes)
288
+ fail('PLUGIN_SOURCE_TOO_LARGE', 'An edited draft file may contain at most 1 MiB.');
289
+ return { ...await write(id, file, parts.join(newString)), replacements };
290
+ }),
291
+ delete: ({ id, path: file }, options = {}) => locked(id, async () => {
292
+ const current = await read(id, file);
293
+ if (options.expectedDigest !== undefined && current.digest !== options.expectedDigest)
294
+ fail('PLUGIN_SOURCE_CHANGED', 'The draft file changed while awaiting approval. Nothing was deleted; review it again.');
295
+ const target = path.join(draft(id), file);
296
+ await confined(root, target);
297
+ await unlink(target);
298
+ return { deleted: true };
299
+ }),
300
+ seal: ({ id }, _options = {}) => locked(id, async () => publish(id, await snapshot(draft(id)))),
301
+ rollback: ({ id }, _options = {}) => locked(id, async () => {
302
+ const previous = (await versions(id))[1];
303
+ if (!previous)
304
+ fail('PLUGIN_SOURCE_NO_ROLLBACK', 'No previous installed version is available.');
305
+ return publish(id, await snapshot(path.join(root, id, previous)), previous);
306
+ }),
307
+ isSealedHere: async ({ id, version }, _options = {}) => {
308
+ safeId(id);
309
+ if (required.builtInIds.some(builtIn => builtIn.toLowerCase() === id) || !await exists(root))
310
+ return false;
311
+ // Provenance and installed packages are immutable and published by rename. A read needs
312
+ // no source lock; enabling during a seal must not fail with PLUGIN_SOURCE_BUSY.
313
+ if (!semver.valid(version) || !/^[0-9A-Za-z][0-9A-Za-z.+-]*$/.test(version))
314
+ return false;
315
+ const provenance = marker(id, version);
316
+ await confined(root, provenance);
317
+ if (!await exists(provenance))
318
+ return false;
319
+ const parent = path.dirname(provenance);
320
+ const markers = await snapshotSitePluginPackage({ sourceDir: parent }, PLUGIN_SOURCE_LIMITS);
321
+ const digest = JSON.parse(markers.get(path.basename(provenance)).toString('utf8')).digest;
322
+ return digest === digestSitePluginSnapshot({ files: await snapshot(path.join(root, id, version)) });
323
+ },
324
+ // Lock-free like isSealedHere: rename-published, and enabling during a seal must not fail BUSY.
325
+ readApproval: async ({ id }, _options = {}) => {
326
+ safeId(id);
327
+ if (!await exists(root))
328
+ return undefined;
329
+ await confined(root, approval(id));
330
+ if (!await exists(approval(id)))
331
+ return undefined;
332
+ // A damaged record means "not approved": the owner is simply asked again.
333
+ let parsed;
334
+ try {
335
+ parsed = JSON.parse(await readFile(approval(id), 'utf8')).capabilities;
336
+ }
337
+ catch {
338
+ return undefined;
339
+ }
340
+ return Array.isArray(parsed) && parsed.every(entry => typeof entry === 'string') ? parsed : undefined;
341
+ },
342
+ recordApproval: async ({ id, capabilities }, _options = {}) => {
343
+ safeId(id);
344
+ await mkdir(root, { recursive: true });
345
+ await writeAtomic(root, approval(id), jsonBytes({ capabilities: [...capabilities] }));
346
+ },
347
+ };
348
+ }
349
+ //# sourceMappingURL=source-drafts.js.map
@@ -1,41 +1,3 @@
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
1
  import type { ManifestHostPorts } from "./ports.js";
40
2
  import type { PluginActivationRecord } from "./activation.js";
41
3
  import { type ClaimMode, type ExtensionClaim } from "./claim-conflicts.js";
@@ -1,4 +1,43 @@
1
- import { resolveClaimConflicts } from "./claim-conflicts.js";
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";
2
41
  import { CORE_OWNER_ID } from "./manifest.js";
3
42
  /** The owner id core's claims are filed under, and how messages name it. */
4
43
  export { CORE_OWNER_ID };
@@ -27,7 +66,16 @@ export function pluginClaimsFromManifest(required, optional = {}) {
27
66
  const { manifest } = required;
28
67
  const hookSemantics = optional.hookSemantics ?? required.pluginSdkBinding.hookSemantics;
29
68
  const contributes = manifest.contributes ?? {};
30
- const declared = CONTRIBUTION_KINDS.flatMap(([list, kind]) => (contributes[list] ?? []).map((key) => ({ kind, key, mode: "exclusive" })));
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
+ }));
31
79
  const hooks = manifest.hooks.map((key) => ({ kind: "hook", key, mode: hookSemantics[key] ?? "exclusive" }));
32
80
  const generated = manifest.fields.length > 0 ? [{ kind: "tool", key: capabilityToolIdFor({ pluginId: manifest.id }), mode: "exclusive" }] : [];
33
81
  const contentTypes = required.declarativeContentTypes.parse({ value: manifest.contentTypes }).decls.map((decl) => ({ kind: "content-type", key: decl.key, mode: "exclusive" }));
@@ -16,13 +16,23 @@ export type ExtPatch = Readonly<Record<string, string | number | boolean>>;
16
16
  export type BeforeSaveFilter = (entry: Readonly<ContentEntryDraft>, ctx: HookContext) => ExtPatch | Promise<ExtPatch>;
17
17
  export type HookPoints = Readonly<Record<string, unknown>>;
18
18
  export interface PluginSdk<H extends HookPoints = HookPoints> {
19
+ readonly plugins?: import("@jini-ai/core/plugin-directory").PluginLookupPort;
19
20
  readonly content: {
20
21
  read(): Readonly<ContentEntryDraft>;
21
22
  extend(field: string, value: string | number | boolean): void;
22
23
  };
23
24
  addFilter<K extends keyof H & string>(hookName: K, filter: H[K] extends (...args: never[]) => unknown ? H[K] : BeforeSaveFilter): void;
25
+ readonly routes: {
26
+ add(required: import('./contributions.js').PluginRouteContribution, optional?: Record<string, never>): void;
27
+ };
28
+ readonly tools: {
29
+ add(required: import('./contributions.js').PluginToolContribution, optional?: Record<string, never>): void;
30
+ };
31
+ readonly widgets: {
32
+ add(required: import('./contributions.js').PluginWidgetContribution, optional?: Record<string, never>): void;
33
+ };
24
34
  addAction(...args: never[]): void;
25
- addContribution(...args: never[]): void;
35
+ addContribution(required: import('./contributions.js').PluginContribution, optional?: Record<string, never>): void;
26
36
  }
27
37
  export interface DefinedPlugin<H extends HookPoints = HookPoints> {
28
38
  readonly definition: {
@@ -100,6 +110,8 @@ export interface DeclarativeContentTypesPort {
100
110
  }, optional?: Record<string, never>): Promise<unknown>;
101
111
  }
102
112
  export interface ManifestHostPorts<H extends HookPoints = HookPoints> {
113
+ /** Namespace containing publisher id/provides; default retains the existing site contract. */
114
+ readonly identityNamespace?: string;
103
115
  readonly pluginSdkBinding: PluginSdkBinding<H>;
104
116
  readonly capabilityVocabulary: readonly string[];
105
117
  readonly declarativeContentTypes: DeclarativeContentTypesPort;
@@ -0,0 +1,38 @@
1
+ import type { PluginManifest } from "./manifest.js";
2
+ /** Host-injected deployment policy. Environment interpretation belongs to composition adapters. */
3
+ export interface PluginSourcePolicyPort {
4
+ localInstallEnabled(required?: Record<string, never>, optional?: Record<string, never>): boolean;
5
+ /** `added` is what this version declares beyond the owner's last approval (see `addedPluginCapabilities`). */
6
+ confirmEnable(required: {
7
+ sealedHere: boolean;
8
+ added: readonly string[];
9
+ }, optional?: Record<string, never>): boolean;
10
+ }
11
+ /** Local authoring runs directly; hosted sideloading retains the host's explicit opt-in.
12
+ * Enabling asks the owner unless the package was sealed on this site AND adds nothing beyond the
13
+ * owner's last approval. Tier-3 code runs in-process with full server authority, so "sealed here"
14
+ * (possibly by the assistant itself) is never consent on its own (owner, 2026-10-12).
15
+ * @param required Deployment facts supplied by the host.
16
+ * @param _optional Reserved factory options.
17
+ * @returns The shared install/enable policy, with no environment reads.
18
+ * @example createPluginSourcePolicy({ hosted: false, localInstallOptIn: false }, {})
19
+ */
20
+ export declare function createPluginSourcePolicy(required: {
21
+ hosted: boolean;
22
+ localInstallOptIn: boolean;
23
+ }, _optional?: {}): PluginSourcePolicyPort;
24
+ /** Everything a manifest lets the plugin reach, as stable `kind:name` entries. Code may change
25
+ * freely between versions without re-asking; only a new entry here is a widening. The tier is an
26
+ * entry so a tier-1 package that becomes tier-3 (code execution) counts as widened.
27
+ * @complexity O(n log n) in the number of declared entries.
28
+ */
29
+ export declare function pluginCapabilitySet({ manifest }: {
30
+ manifest: Pick<PluginManifest, "tier" | "capabilities" | "hooks" | "fields" | "contentTypes" | "contributes">;
31
+ }, _optional?: {}): readonly string[];
32
+ /** Entries of `next` absent from `approved`; with no approval on record, all of `next`.
33
+ * @complexity O(n + m). */
34
+ export declare function addedPluginCapabilities({ approved, next }: {
35
+ approved: readonly string[] | undefined;
36
+ next: readonly string[];
37
+ }, _optional?: {}): readonly string[];
38
+ //# sourceMappingURL=source-policy.d.ts.map