opensip-cli 0.1.2 → 0.1.4

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 (56) hide show
  1. package/dist/bootstrap/bind-tool-context.d.ts +16 -0
  2. package/dist/bootstrap/bind-tool-context.d.ts.map +1 -0
  3. package/dist/bootstrap/bind-tool-context.js +160 -0
  4. package/dist/bootstrap/bind-tool-context.js.map +1 -0
  5. package/dist/bootstrap/build-per-run-scope.d.ts.map +1 -1
  6. package/dist/bootstrap/build-per-run-scope.js +35 -2
  7. package/dist/bootstrap/build-per-run-scope.js.map +1 -1
  8. package/dist/bootstrap/execute-post-bailout-bootstrap.d.ts +45 -0
  9. package/dist/bootstrap/execute-post-bailout-bootstrap.d.ts.map +1 -0
  10. package/dist/bootstrap/execute-post-bailout-bootstrap.js +108 -0
  11. package/dist/bootstrap/execute-post-bailout-bootstrap.js.map +1 -0
  12. package/dist/bootstrap/plan-pre-action-bootstrap.d.ts +45 -0
  13. package/dist/bootstrap/plan-pre-action-bootstrap.d.ts.map +1 -0
  14. package/dist/bootstrap/plan-pre-action-bootstrap.js +86 -0
  15. package/dist/bootstrap/plan-pre-action-bootstrap.js.map +1 -0
  16. package/dist/bootstrap/pre-action-bootstrap-phases.d.ts +20 -0
  17. package/dist/bootstrap/pre-action-bootstrap-phases.d.ts.map +1 -0
  18. package/dist/bootstrap/pre-action-bootstrap-phases.js +25 -0
  19. package/dist/bootstrap/pre-action-bootstrap-phases.js.map +1 -0
  20. package/dist/bootstrap/pre-action-hook.d.ts +6 -66
  21. package/dist/bootstrap/pre-action-hook.d.ts.map +1 -1
  22. package/dist/bootstrap/pre-action-hook.js +22 -266
  23. package/dist/bootstrap/pre-action-hook.js.map +1 -1
  24. package/dist/bootstrap/pre-action-runtime.d.ts +9 -0
  25. package/dist/bootstrap/pre-action-runtime.d.ts.map +1 -0
  26. package/dist/bootstrap/pre-action-runtime.js +2 -0
  27. package/dist/bootstrap/pre-action-runtime.js.map +1 -0
  28. package/dist/bootstrap/register-tools-bundled.d.ts +28 -0
  29. package/dist/bootstrap/register-tools-bundled.d.ts.map +1 -0
  30. package/dist/bootstrap/register-tools-bundled.js +107 -0
  31. package/dist/bootstrap/register-tools-bundled.js.map +1 -0
  32. package/dist/bootstrap/register-tools-discovery.d.ts +154 -0
  33. package/dist/bootstrap/register-tools-discovery.d.ts.map +1 -0
  34. package/dist/bootstrap/register-tools-discovery.js +385 -0
  35. package/dist/bootstrap/register-tools-discovery.js.map +1 -0
  36. package/dist/bootstrap/register-tools-mount.d.ts +25 -0
  37. package/dist/bootstrap/register-tools-mount.d.ts.map +1 -0
  38. package/dist/bootstrap/register-tools-mount.js +91 -0
  39. package/dist/bootstrap/register-tools-mount.js.map +1 -0
  40. package/dist/bootstrap/register-tools-shared.d.ts +40 -0
  41. package/dist/bootstrap/register-tools-shared.d.ts.map +1 -0
  42. package/dist/bootstrap/register-tools-shared.js +98 -0
  43. package/dist/bootstrap/register-tools-shared.js.map +1 -0
  44. package/dist/bootstrap/register-tools.d.ts +4 -196
  45. package/dist/bootstrap/register-tools.d.ts.map +1 -1
  46. package/dist/bootstrap/register-tools.js +4 -668
  47. package/dist/bootstrap/register-tools.js.map +1 -1
  48. package/dist/commands/mount-command-spec.d.ts +2 -1
  49. package/dist/commands/mount-command-spec.d.ts.map +1 -1
  50. package/dist/commands/mount-command-spec.js +3 -6
  51. package/dist/commands/mount-command-spec.js.map +1 -1
  52. package/dist/env/host-env-specs.d.ts +4 -3
  53. package/dist/env/host-env-specs.d.ts.map +1 -1
  54. package/dist/env/host-env-specs.js +8 -3
  55. package/dist/env/host-env-specs.js.map +1 -1
  56. package/package.json +32 -32
@@ -1,5 +1,3 @@
1
- // @fitness-ignore-file performance-anti-patterns -- sequential await across discovered tool packages preserves load order for plugin-conflict detection; bounded by installed plugin count
2
- // @fitness-ignore-file file-length-limit -- bootstrap composition root: one cohesive tool-admission lifecycle (resolve bundled dir → loadToolManifest → admitTool, across bundled / installed / project-local sources) plus discovery-source ordering and command mounting; splitting fragments the unified admission dispatch (cf. graph.ts's identical waiver for its subcommand-dispatch surface).
3
1
  /**
4
2
  * register-tools — populate the kernel `ToolRegistry` with first-party
5
3
  * tools (fitness / simulation / graph) plus any third-party tool
@@ -12,670 +10,8 @@
12
10
  * a noisy warning when a third-party package happens to ship under a
13
11
  * built-in id.
14
12
  */
15
- import { existsSync, readFileSync } from 'node:fs';
16
- import { createRequire } from 'node:module';
17
- import { dirname, join } from 'node:path';
18
- import { fileURLToPath } from 'node:url';
19
- import { admitTool, assertManifestMatchesTool, discoverAuthoredToolSidecars, discoverToolPackagesFromAnchors, loadToolManifest, logger, PluginIncompatibleError, PROJECT_LOCAL_MANIFEST_FILE, resolveProjectContext, resolveProjectPaths, resolveUserPaths, } from '@opensip-cli/core';
20
- import { mountCommandSpec } from '../commands/mount-command-spec.js';
21
- import { admitToolPackage, importToolRuntime, } from './admit-tool-package.js';
22
- import { isProjectLocalToolTrusted } from './tool-trust.js';
23
- /** `module` field on every structured log event emitted from this file. */
24
- const BOOTSTRAP_MODULE = 'cli:bootstrap';
25
- /** Used to resolve the bundled engine package dirs from the CLI's own module graph. */
26
- const requireFromHere = createRequire(import.meta.url);
27
- /**
28
- * Bundled first-party tools are now data-driven (platform-ergonomics Workstream A).
29
- * The source of truth is the co-located JSON manifest (single edit site when
30
- * adding a first-party tool). Loaded via fs + import.meta.url (works in both
31
- * src dev and dist/ after tsc; the json is committed under src/ and must be
32
- * present next to the .js in dist at runtime — ensured by package "files": ["dist"]
33
- * + manual cp in build or future asset plugin; no resolveJsonModule dep).
34
- */
35
- const manifestUrl = new URL('bundled-tools.manifest.json', import.meta.url);
36
- const bundledManifest = JSON.parse(readFileSync(fileURLToPath(manifestUrl), 'utf8'));
37
- export const BUNDLED_TOOL_PACKAGES = bundledManifest.bundledPackages;
38
- /**
39
- * The ADR-0038 back-compat pin: the tool IDS whose `init` scaffold dirs the
40
- * pre-registry-driven CLI ALWAYS created (fit/sim). The composition root warns
41
- * (`cli.tool.expected_bundled_absent`) when one of these is missing from the
42
- * populated registry, so a build whose {@link BUNDLED_TOOL_PACKAGES} drifted
43
- * (a tool removed, a packaging variant) under-scaffolds LOUDLY instead of
44
- * silently.
45
- *
46
- * Now derived from the same manifest as BUNDLED_TOOL_PACKAGES (Workstream A)
47
- * so a single edit keeps them in sync. `graph` is correctly absent: it never
48
- * scaffolded (`pluginLayout` undefined).
49
- */
50
- export const EXPECTED_SCAFFOLDING_TOOL_IDS = bundledManifest.scaffoldingToolIds;
51
- /**
52
- * Resolve a bundled tool's PACKAGE DIR — the directory whose `package.json`
53
- * carries the `opensipTools` manifest.
54
- *
55
- * The `./package.json` subpath is not declared in each engine's `exports`,
56
- * so `require.resolve('<pkg>/package.json')` throws. Instead we resolve the
57
- * package's MAIN entry (a bare-name resolve, always permitted by `exports`)
58
- * and walk up to the nearest ancestor directory that has a `package.json`
59
- * whose `name` matches `packageName`. That ancestor IS the tool's own
60
- * package dir under both the source layout and pnpm's workspace-injected
61
- * `node_modules` layout (verified against fitness/simulation/graph here).
62
- *
63
- * @returns the resolved package directory, or `undefined` when the package
64
- * cannot be resolved (should never happen for a bundled direct dep).
65
- */
66
- function resolveBundledPackageDir(packageName) {
67
- let resolvedEntry;
68
- try {
69
- resolvedEntry = requireFromHere.resolve(packageName);
70
- }
71
- catch (error) {
72
- // A bundled direct dep failing to resolve is a packaging fault — log it
73
- // so the subsequent fail-closed throw is diagnosable, then signal the
74
- // unresolved state to the caller (which raises PluginIncompatibleError).
75
- logger.debug({
76
- evt: 'cli.tool.bundled_unresolved',
77
- module: BOOTSTRAP_MODULE,
78
- packageName,
79
- error: error instanceof Error ? error.message : String(error),
80
- });
81
- return undefined;
82
- }
83
- let dir = dirname(resolvedEntry);
84
- for (let i = 0; i < 50; i++) {
85
- const pkgPath = join(dir, 'package.json');
86
- if (existsSync(pkgPath)) {
87
- try {
88
- const json = JSON.parse(readFileSync(pkgPath, 'utf8'));
89
- if (json.name === packageName)
90
- return dir;
91
- }
92
- catch {
93
- // @swallow-ok unreadable package.json on the walk-up — keep climbing.
94
- }
95
- }
96
- const parent = dirname(dir);
97
- if (parent === dir)
98
- break;
99
- dir = parent;
100
- }
101
- return undefined;
102
- }
103
- /**
104
- * Resolve a bundled tool package's on-disk directory, requiring success.
105
- *
106
- * @throws {PluginIncompatibleError} when the package directory cannot be
107
- * resolved on disk (its manifest is unreadable).
108
- */
109
- function resolveRequiredBundledPackageDir(packageName) {
110
- const dir = resolveBundledPackageDir(packageName);
111
- if (dir !== undefined)
112
- return dir;
113
- throw new PluginIncompatibleError(`bundled tool '${packageName}' could not be resolved on disk; its manifest is unreadable`, { diagnostic: 'package directory not resolvable' });
114
- }
115
- // The runtime-load primitive (`importToolRuntime` + `ToolRuntimeLoad`) and the
116
- // full admission SEQUENCE (`admitToolPackage`) live in `admit-tool-package.ts`
117
- // (ADR-0041: one validator, four consumers). This file keeps the per-source
118
- // POLICY: bundled fails closed below; the installed/authored legs skip with
119
- // diagnostics.
120
- /**
121
- * Register the bundled first-party tools into the supplied registry, each one
122
- * flowing through the SAME admit → dynamic-import → register path the external
123
- * path uses (launch cutover — replaces the static-import + gate path).
124
- *
125
- * Per package name: `resolveBundledPackageDir` → `loadToolManifest('bundled')`
126
- * → `admitTool({ source: 'bundled', explicitlyRequested: true })` →
127
- * `importToolRuntime` (dynamic import + shape validation) → drift guard →
128
- * `registry.register`. A bundled tool ships with the CLI, so it is always
129
- * explicitly present: a missing/incompatible manifest or a runtime that fails
130
- * to load is FAIL-CLOSED (never a silent skip). The recorded `ToolProvenance`
131
- * (source `'bundled'`, trusted-by-shipping) and manifest are pushed onto the
132
- * optional collectors so the composition root can surface provenance
133
- * (`plugin list`) and seed the per-run capability registry (§5.3).
134
- *
135
- * @param registry The per-invocation tool registry to populate.
136
- * @param provenance Optional sink for the admitted tools' provenance records.
137
- * @param manifests Optional sink for the admitted tools' manifests (§5.3).
138
- * @param packages The bundled package names to load (defaults to
139
- * {@link BUNDLED_TOOL_PACKAGES}; injectable so the fail-closed paths are
140
- * testable with fixture packages).
141
- * @throws {PluginIncompatibleError} when a bundled tool cannot be resolved,
142
- * has no conformant manifest, is out of range, or its runtime fails to load
143
- * — mapped to `EXIT_CODES.PLUGIN_INCOMPATIBLE` (exit 5) by the CLI boundary.
144
- */
145
- export async function registerFirstPartyTools(registry, provenance = [], manifests = [], packages = BUNDLED_TOOL_PACKAGES) {
146
- for (const packageName of packages) {
147
- const dir = resolveRequiredBundledPackageDir(packageName);
148
- // The shared admission SEQUENCE (ADR-0041). The bundled POLICY below maps
149
- // each failed section to the exact fail-closed error this path always
150
- // threw — a bundled tool ships with the CLI, so every failure is a
151
- // packaging fault, never a silent skip.
152
- const report = await admitToolPackage({
153
- dir,
154
- source: 'bundled',
155
- packageName,
156
- // A bundled tool ships with the CLI; it is always explicitly present,
157
- // so an incompatible manifest fails the run rather than skipping.
158
- explicitlyRequested: true,
159
- });
160
- if (!report.ok) {
161
- // @fitness-ignore-next-line detached-promises -- synchronous never-returning thrower; the heuristic mistakes the bare call for an unawaited promise
162
- throwBundledAdmissionFailure(packageName, report);
163
- }
164
- /* v8 ignore next 3 -- throwBundledAdmissionFailure never returns on a failed report; this guard narrows types */
165
- if (report.tool === undefined ||
166
- report.provenance === undefined ||
167
- report.manifest === undefined) {
168
- throw new PluginIncompatibleError(`bundled tool '${packageName}' produced an incomplete admission report`, { diagnostic: 'incomplete admission report' });
169
- }
170
- registry.register(report.tool);
171
- provenance.push(report.provenance);
172
- // Record the manifest so the pre-action-hook can register this tool's
173
- // declared capability domains into the per-run capability registry
174
- // (launch, §5.3).
175
- manifests.push(report.manifest);
176
- }
177
- }
178
- /**
179
- * The bundled FAIL-CLOSED policy: convert a failed {@link AdmissionReport}
180
- * into the same `PluginIncompatibleError` (message + diagnostic) the inline
181
- * pipeline threw before the ADR-0041 factoring. Never returns.
182
- *
183
- * @throws {PluginIncompatibleError} always (or rethrows the original
184
- * coherence error from `assertManifestMatchesTool`, preserving its type).
185
- */
186
- function throwBundledAdmissionFailure(packageName, report) {
187
- const failed = report.sections.find((s) => !s.ok);
188
- const failedSection = failed?.section;
189
- if (failedSection === 'manifest') {
190
- throw new PluginIncompatibleError(`bundled tool '${packageName}' has no conformant package.json#opensipTools manifest`, { diagnostic: 'manifest missing or malformed' });
191
- }
192
- const id = report.manifest?.id ?? packageName;
193
- if (failedSection === 'compatibility') {
194
- if (report.compatibilityDecision === 'fail-closed') {
195
- throw new PluginIncompatibleError(`bundled tool '${id}' is incompatible: ${failed?.diagnostic ?? 'compatibility gate rejected it'}`, { diagnostic: failed?.diagnostic });
196
- }
197
- if (report.compatibilityDecision === 'skip') {
198
- // Should not happen for an in-range bundled tool, but never silently
199
- // drop a bundled tool — surface it loudly.
200
- throw new PluginIncompatibleError(`bundled tool '${id}' was skipped by the compatibility gate: ${failed?.diagnostic ?? 'unknown reason'}`, { diagnostic: failed?.diagnostic });
201
- }
202
- throw new PluginIncompatibleError(`bundled tool '${id}' reached an unknown admission decision`, { diagnostic: 'unknown admission decision' });
203
- }
204
- if (failedSection === 'runtime-load' || failedSection === 'tool-shape') {
205
- const reason = report.runtimeLoadReason ?? 'import-failed';
206
- const detailSuffix = report.runtimeLoadDetail ? `: ${report.runtimeLoadDetail}` : '';
207
- throw new PluginIncompatibleError(`bundled tool '${id}' failed to load via the plugin path (${reason}${detailSuffix})`, { diagnostic: `bundled tool runtime load failed: ${reason}` });
208
- }
209
- if (failedSection === 'manifest-runtime-coherence' && report.coherenceError instanceof Error) {
210
- // Preserve the original drift-guard error type + message untouched.
211
- // (assertManifestMatchesTool always throws Error subclasses; the
212
- // instanceof narrowing satisfies only-throw-error without a cast.)
213
- throw report.coherenceError;
214
- }
215
- /* v8 ignore next 4 -- defensive: a failed report always carries a failed section */
216
- throw new PluginIncompatibleError(`bundled tool '${packageName}' failed admission for an unknown reason`, { diagnostic: 'unknown admission failure' });
217
- }
218
- /**
219
- * Build the ordered tool-discovery sources. Order is precedence
220
- * (first-occurrence-wins on duplicate name):
221
- *
222
- * 1. project-local `.runtime/plugins/tool` — `plugin add --project`
223
- * 2. project tree (walk up from cwd) — plain `npm install @tool`
224
- * 3. user-global `~/.opensip-cli/plugins/tool` — `plugin add` (default)
225
- * 4. CLI install dir (walk up) — `npm i -g @tool`
226
- *
227
- * A project-local pin therefore shadows a user-global install of the same
228
- * tool. Project-root resolution is best-effort: an unresolvable context
229
- * (e.g. running outside any project) simply contributes no `.runtime`
230
- * source.
231
- */
232
- export function buildToolDiscoverySources(cwd, cliInstallDir) {
233
- const sources = [];
234
- try {
235
- const project = resolveProjectContext({ cwd, cwdExplicit: false });
236
- if (project.scope === 'project') {
237
- sources.push({
238
- dir: resolveProjectPaths(project.projectRoot).pluginsDir('tool'),
239
- mode: 'scanDir',
240
- });
241
- }
242
- }
243
- catch {
244
- // @swallow-ok no resolvable project context (e.g. running outside any
245
- // project) → contribute no project-local tool source. Best-effort by
246
- // documented contract; see the JSDoc on buildToolDiscoverySources.
247
- }
248
- sources.push({ dir: cwd, mode: 'walkUp' }, { dir: resolveUserPaths().pluginsDir('tool'), mode: 'scanDir' }, { dir: cliInstallDir, mode: 'walkUp' });
249
- return sources;
250
- }
251
- /**
252
- * Run the admission gate over a discovered INSTALLED tool package
253
- * before its module is imported. Reads the static
254
- * `package.json#opensipTools` manifest and runs the shared `admitTool` gate
255
- * (source `'installed'`, best-effort `explicitlyRequested: false` so an
256
- * incompatible installed tool skips rather than failing the whole CLI).
257
- *
258
- * Returns:
259
- * - `undefined` — skip this package (no conformant manifest, gate skipped
260
- * it, or its id collides with a built-in). The reason is logged.
261
- * - the admission `{ provenance, manifest }` — the manifest is conformant +
262
- * compatible; the caller continues to import + register, and records the
263
- * provenance/manifest only AFTER the runtime actually registered (so
264
- * `plugin list` and the capability registry never see a tool whose import
265
- * subsequently failed — matching the bundled/authored legs).
266
- *
267
- * Public launch: the grace window ended. A discovered `kind:'tool'` package whose
268
- * manifest is missing/malformed (`loadToolManifest` → undefined) or declares no
269
- * `apiVersion` (`admitTool` → skip via {@link checkCompatibility}) is no longer
270
- * admitted off the marker alone — it is rejected with a diagnostic.
271
- */
272
- function admitInstalledTool(pkg, builtInIds) {
273
- const manifest = loadToolManifest('installed', pkg.packageDir);
274
- if (manifest === undefined) {
275
- // Launch: a discovered tool with no conformant manifest is no longer admitted
276
- // off the `kind:'tool'` marker alone (the grace window ended) — skip it.
277
- process.stderr.write(`opensip: tool package ${pkg.name} has no conformant package.json#opensipTools manifest — skipping\n`);
278
- logger.warn({
279
- evt: 'cli.tool.manifest_invalid',
280
- module: BOOTSTRAP_MODULE,
281
- name: pkg.name,
282
- });
283
- return undefined;
284
- }
285
- if (builtInIds.has(manifest.id))
286
- return undefined; // builtInIds are human ids from manifests (compat)
287
- const result = admitTool({
288
- manifest,
289
- source: 'installed',
290
- dir: pkg.packageDir,
291
- packageName: pkg.name,
292
- // Best-effort: discovery alone can't tell whether THIS run targets this
293
- // tool's command, so default false → incompatible installed tools skip.
294
- explicitlyRequested: false,
295
- });
296
- if (result.decision !== 'admit')
297
- return undefined;
298
- return { provenance: result.provenance, manifest: result.manifest };
299
- }
300
- /**
301
- * Discover and register third-party tool packages from npm — any
302
- * `package.json` declaring `opensipTools.kind === 'tool'`. Built-in
303
- * ids are skipped to avoid double-registration warnings. Discovery spans
304
- * the supplied sources (the user-global tool host dir, the project tree +
305
- * its `.runtime` tool host dir, and the CLI install dir — see
306
- * {@link buildToolDiscoverySources}).
307
- *
308
- * Each discovered package runs through the SAME `admitTool` gate the
309
- * bundled path uses (launch, Phase 3) BEFORE its module is imported:
310
- * the static `package.json#opensipTools` manifest is read with source
311
- * `'installed'`, the compatibility gate runs, and only an `admit` verdict
312
- * proceeds to import + register. An installed tool is best-effort
313
- * `explicitlyRequested: false`, so an incompatible one `skip`s (logged)
314
- * rather than failing the whole CLI — a stray incompatible plugin must not
315
- * take fit/graph/sim down. Admitted tools' `ToolProvenance` is pushed onto
316
- * the optional `provenance` collector for Phase 4's `plugin list`.
317
- *
318
- * @param provenance Optional sink for admitted tools' provenance records.
319
- */
320
- /**
321
- * Emit the best-effort stderr line + structured warning for a discovered
322
- * INSTALLED tool whose runtime failed to load. Each `ToolRuntimeLoad` failure
323
- * reason maps to its own message + event (preserving the admission diagnostics) —
324
- * an installed tool's load failure skips it, never crashing the CLI.
325
- */
326
- function emitInstalledLoadFailure(name, load) {
327
- if (load.reason === 'no-entry') {
328
- process.stderr.write(`opensip: tool package ${name} has no resolvable entry point — skipping\n`);
329
- logger.warn({ evt: 'cli.tool.no_entry', module: BOOTSTRAP_MODULE, name });
330
- return;
331
- }
332
- if (load.reason === 'invalid-shape') {
333
- process.stderr.write(`opensip: tool package ${name} does not export a valid \`tool\` — skipping\n`);
334
- logger.warn({
335
- evt: 'cli.tool.invalid_shape',
336
- module: BOOTSTRAP_MODULE,
337
- name,
338
- });
339
- return;
340
- }
341
- process.stderr.write(`opensip: failed to load tool ${name}: ${load.detail ?? 'import failed'}\n`);
342
- logger.warn({
343
- evt: 'cli.tool.load_failed',
344
- module: BOOTSTRAP_MODULE,
345
- name,
346
- error: load.detail,
347
- });
348
- }
349
- export async function discoverAndRegisterToolPackages(registry, opts, builtInIds, provenance = [], manifests = []) {
350
- // `builtInIds` is the set of already-registered bundled-tool *human ids* (manifest.id)
351
- // to skip on a name collision (launch — passed explicitly by the composition root, which
352
- // derives it from the bundled MANIFESTS it just loaded; compare against runtime
353
- // metadata.name for the human key).
354
- const discovered = discoverToolPackagesFromAnchors(opts.sources);
355
- for (const pkg of discovered) {
356
- try {
357
- // Compatibility gate BEFORE import (launch). `undefined` means the
358
- // gate skipped it (or it's a built-in id); an admission means import +
359
- // register as before.
360
- const admission = admitInstalledTool(pkg, builtInIds);
361
- if (admission === undefined)
362
- continue;
363
- // Load the runtime through the SHARED dynamic-import path (launch) — the
364
- // same `importToolRuntime` the bundled path uses. Resolves the entry
365
- // from `packageDir` so a tool living in a host dir off the CLI's own
366
- // module-resolution path still loads. An installed tool is best-effort:
367
- // any load failure skips-with-diagnostic (it must not take fit/graph/sim
368
- // down), in contrast to the bundled path's fail-closed.
369
- const load = await importToolRuntime(pkg.packageDir);
370
- if (!load.ok) {
371
- emitInstalledLoadFailure(pkg.name, load);
372
- continue;
373
- }
374
- // builtInIds holds human ids (from bundled manifests); compare against runtime human name
375
- if (builtInIds.has(load.tool.metadata.name ?? load.tool.metadata.id))
376
- continue;
377
- // Drift guard — the SAME manifest⇔runtime identity check the bundled and
378
- // authored legs run. For an installed tool a mismatch throws into the
379
- // surrounding catch (skip-with-diagnostic posture), never crashing the CLI.
380
- assertManifestMatchesTool(admission.manifest, load.tool);
381
- registry.register(load.tool, { sourcePackage: pkg.name });
382
- // Record provenance + manifest only now that the tool actually
383
- // registered — `plugin list` and the per-run capability registry must
384
- // never include a tool whose runtime failed to load (parity with the
385
- // bundled/authored legs, which also record after registration).
386
- provenance.push(admission.provenance);
387
- manifests.push(admission.manifest);
388
- }
389
- catch (error) {
390
- const msg = error instanceof Error ? error.message : String(error);
391
- process.stderr.write(`opensip: failed to load tool ${pkg.name}: ${msg}\n`);
392
- logger.warn({
393
- evt: 'cli.tool.load_failed',
394
- module: BOOTSTRAP_MODULE,
395
- name: pkg.name,
396
- error: msg,
397
- });
398
- }
399
- }
400
- }
401
- /**
402
- * The shared admission TAIL for both authored sources.
403
- * When `preloadedManifest` is supplied we use that snapshot (no re-read) so a
404
- * prior trust decision (project-local) and the compat gate see the identical
405
- * declaration. This removes the TOCTOU between the trust-bearing read and the
406
- * gate read for the deny-by-default authored path.
407
- *
408
- * @throws {PluginIncompatibleError} when the sidecar is missing/malformed or
409
- * the tool is compatibility-incompatible.
410
- */
411
- function admitAuthoredTool(source, dir, preloadedManifest) {
412
- // When a preloaded manifest is supplied (project-local trust path), we use
413
- // that exact snapshot for the compat gate. This eliminates a TOCTOU between
414
- // the read that decided "this id is allowlisted" and the read that feeds the
415
- // compatibility check. The later dynamic import of the .mjs still sees
416
- // whatever is on disk at execution time (inherent for authored code).
417
- const rawManifest = preloadedManifest ?? loadToolManifest(source, dir);
418
- if (rawManifest === undefined) {
419
- throw new PluginIncompatibleError(`${source} tool at '${dir}' has no conformant ${PROJECT_LOCAL_MANIFEST_FILE} sidecar`, { diagnostic: 'manifest missing or malformed' });
420
- }
421
- const result = admitTool({
422
- manifest: rawManifest,
423
- source,
424
- dir,
425
- // An authored tool (placed in the project tree or the user's home dir) was
426
- // explicitly authored by the user, so an incompatible one fails the run
427
- // rather than skipping silently.
428
- explicitlyRequested: true,
429
- });
430
- if (result.decision !== 'admit') {
431
- throw new PluginIncompatibleError(`${source} tool '${rawManifest.id}' is incompatible: ${result.diagnostic ?? 'compatibility gate rejected it'}`, { diagnostic: result.diagnostic });
432
- }
433
- return { provenance: result.provenance, manifest: result.manifest };
434
- }
435
- /**
436
- * Admit (or reject) a single PROJECT-LOCAL authored tool under the
437
- * deny-by-default trust policy (launch, Phase 3 Task 3.2; wired into
438
- * production discovery in the launch contract).
439
- *
440
- * A project-local tool is authored code under
441
- * `<project>/opensip-cli/tools/<name>/` declaring its identity via a JSON
442
- * sidecar (`opensip-tool.manifest.json`). It is read + gated WITHOUT importing
443
- * its module:
444
- *
445
- * 1. `loadToolManifest('project-local', dir)` — identity only, no code run.
446
- * 2. Trust check — {@link isProjectLocalToolTrusted}. Not allowlisted ⇒
447
- * throw {@link PluginIncompatibleError} (fail-closed, exit 5) before any
448
- * import. Allowlisted ⇒ run the shared compatibility tail; an incompatible
449
- * explicitly-trusted tool is likewise fail-closed.
450
- *
451
- * Returns the admitted tool's `{ provenance, manifest }` on success. The trust
452
- * decision always precedes import (it is the FIRST statement here, ahead of the
453
- * shared {@link admitAuthoredTool} tail).
454
- *
455
- * @throws {PluginIncompatibleError} when the tool has no conformant sidecar
456
- * manifest, is not allowlisted, or is compatibility-incompatible.
457
- */
458
- export function admitProjectLocalTool(args) {
459
- // Trust decision FIRST — deny-by-default, before any compatibility maths
460
- // and (critically) before the tool's module could ever be imported. The id
461
- // is read from the sidecar identity, so load the manifest once here for the
462
- // trust check, then hand the same dir to the shared tail.
463
- const manifest = loadToolManifest('project-local', args.dir);
464
- if (manifest === undefined) {
465
- throw new PluginIncompatibleError(`project-local tool at '${args.dir}' has no conformant ${PROJECT_LOCAL_MANIFEST_FILE} sidecar`, { diagnostic: 'manifest missing or malformed' });
466
- }
467
- if (!isProjectLocalToolTrusted(manifest.id, args.env)) {
468
- throw new PluginIncompatibleError(`project-local tool '${manifest.id}' is not trusted to load (deny-by-default). ` +
469
- `Allowlist it via OPENSIP_CLI_ALLOW_PROJECT_TOOLS='${manifest.id}' to admit it.`, { diagnostic: 'project-local tool not allowlisted (deny-by-default)' });
470
- }
471
- // Pass the manifest we just loaded (and whose id we just trusted) so the
472
- // compat gate in the tail sees the identical declaration. Closes the
473
- // read-re-read TOCTOU for the deny-by-default path.
474
- return admitAuthoredTool('project-local', args.dir, manifest);
475
- }
476
- /**
477
- * Admit a single USER-GLOBAL authored tool — the trusted-by-default sibling of
478
- * {@link admitProjectLocalTool}.
479
- *
480
- * A user-global tool is an authored sidecar under
481
- * `~/.opensip-cli/tools/<name>/`. The user deliberately placed it in their
482
- * own home dir (the `npm i -g` analogue for authored code), so there is **no
483
- * allowlist gate** — it is trusted-by-default. It still reads the static
484
- * sidecar and runs `admitTool` BEFORE the module could be imported (the shared
485
- * {@link admitAuthoredTool} tail), so trust-before-import holds for this leg
486
- * too: a global tool the user explicitly authored is fail-closed on a
487
- * missing/incompatible manifest, never a silent skip.
488
- *
489
- * @throws {PluginIncompatibleError} when the tool has no conformant sidecar
490
- * manifest or is compatibility-incompatible.
491
- */
492
- export function admitUserGlobalTool(args) {
493
- // No trust gate — `user-global` is trusted-by-shipping-into-$HOME.
494
- return admitAuthoredTool('user-global', args.dir);
495
- }
496
- /**
497
- * Discover + admit + register AUTHORED Tool sidecars from the two authored
498
- * roots, then dynamic-import each admitted runtime through the shared
499
- * `importToolRuntime` seam — the same admit → import → register path the
500
- * bundled and installed legs travel (ADR-0027; this is the leg that makes the
501
- * dormant {@link admitProjectLocalTool} live).
502
- *
503
- * Two roots, two trust postures:
504
- * - **global** (`~/.opensip-cli/tools/`) → {@link admitUserGlobalTool},
505
- * trusted-by-default.
506
- * - **project** (`<project>/opensip-cli/tools/`) → {@link admitProjectLocalTool},
507
- * deny-by-default (allowlist via `OPENSIP_CLI_ALLOW_PROJECT_TOOLS`).
508
- *
509
- * Global is processed FIRST so a project-authored tool cannot shadow a same-id
510
- * global one — matching the `~/.opensip-cli/plugins` precedence note in
511
- * {@link buildToolDiscoverySources} (first-writer-wins via the registry).
512
- * `builtInIds` are skipped so an authored tool never shadows a bundled one.
513
- *
514
- * **Trust-before-import.** For each candidate, the admit step (which EMBEDS the
515
- * trust decision — deny-by-default inside `admitProjectLocalTool`) runs to
516
- * completion BEFORE `importToolRuntime`. A non-allowlisted project tool THROWS
517
- * `PluginIncompatibleError` (exit 5) here, propagated out of the walk: it must
518
- * fail the run loudly — that is the clone-protection contract.
519
- *
520
- * **Error-posture asymmetry (deliberate).** An un-allowlisted *project* tool is
521
- * fail-closed by policy (clone-risk; the user must opt in). A *global* tool that
522
- * fails to load is also fail-closed (the user explicitly authored it into
523
- * `$HOME`). This differs from the *installed* npm leg, where a stray bad plugin
524
- * skips-with-diagnostic so it can't take fit/graph/sim down — authored tools are
525
- * first-party-intent, installed tools are ambient.
526
- *
527
- * @param registry The per-invocation tool registry to populate.
528
- * @param opts.projectAuthoredDir `resolveProjectPaths(root).authoredToolsDir`,
529
- * or `undefined` when there is no resolvable project context.
530
- * @param opts.globalAuthoredDir `resolveUserPaths().authoredToolsDir`.
531
- * @param opts.env Environment carrying the project allowlist (default
532
- * `process.env`); injectable for tests.
533
- * @param builtInIds Bundled-tool ids to skip on a name collision.
534
- * @param provenance Sink for admitted authored tools' provenance records.
535
- * @param manifests Sink for admitted authored tools' manifests (§5.3).
536
- * @throws {PluginIncompatibleError} for an un-allowlisted project tool, or any
537
- * authored tool whose sidecar/runtime is missing/incompatible (fail-closed).
538
- */
539
- export async function discoverAndRegisterAuthoredTools(registry, opts, builtInIds, provenance = [], manifests = []) {
540
- // Global FIRST (trusted-by-default), then project (deny-by-default).
541
- for (const candidate of discoverAuthoredToolSidecars(opts.globalAuthoredDir)) {
542
- await admitAndRegisterAuthored({
543
- registry,
544
- admission: admitUserGlobalTool({ dir: candidate.dir }),
545
- dir: candidate.dir,
546
- builtInIds,
547
- provenance,
548
- manifests,
549
- });
550
- }
551
- if (opts.projectAuthoredDir !== undefined) {
552
- for (const candidate of discoverAuthoredToolSidecars(opts.projectAuthoredDir)) {
553
- // admitProjectLocalTool embeds the deny-by-default trust gate; a
554
- // non-allowlisted tool THROWS here, BEFORE importToolRuntime below.
555
- await admitAndRegisterAuthored({
556
- registry,
557
- admission: admitProjectLocalTool({ dir: candidate.dir, env: opts.env }),
558
- dir: candidate.dir,
559
- builtInIds,
560
- provenance,
561
- manifests,
562
- });
563
- }
564
- }
565
- }
566
- /**
567
- * Shared register-step for an already-ADMITTED authored tool: skip a
568
- * built-in-id collision, dynamic-import the runtime (fail-closed on failure —
569
- * an authored tool is first-party-intent), run the manifest⇔runtime drift
570
- * guard, register, and record provenance + manifest. Admission (incl. the trust
571
- * decision) has already happened by the time this is called — so import here
572
- * never precedes a trust decision.
573
- *
574
- * @throws {PluginIncompatibleError} when the authored tool's runtime fails to
575
- * load via the plugin path — an authored tool is first-party-intent, so a
576
- * load failure is fail-closed (surfaced), never silently skipped.
577
- */
578
- async function admitAndRegisterAuthored(args) {
579
- const { registry, admission, dir, builtInIds, provenance, manifests } = args;
580
- const { provenance: prov, manifest } = admission;
581
- // Never shadow a bundled tool (defense in depth; the registry also dedupes).
582
- if (builtInIds.has(prov.id))
583
- return;
584
- const load = await importToolRuntime(dir);
585
- if (!load.ok) {
586
- const detailSuffix = load.detail ? `: ${load.detail}` : '';
587
- throw new PluginIncompatibleError(`${prov.source} tool '${prov.id}' failed to load via the plugin path (${load.reason}${detailSuffix})`, { diagnostic: `authored tool runtime load failed: ${load.reason}` });
588
- }
589
- // Drift guard: the static sidecar and the runtime tool are two declarations
590
- // of the same identity — catch a sidecar that fell out of sync.
591
- assertManifestMatchesTool(manifest, load.tool);
592
- registry.register(load.tool);
593
- provenance.push(prov);
594
- manifests.push(manifest);
595
- }
596
- /**
597
- * Walk the registry and mount each tool's commands onto `program`. This is
598
- * **step 8** of the tool lifecycle (launch, §5.4) — see
599
- * {@link runToolLifecycle}.
600
- *
601
- * Public launch: there is ONE command surface — the tool's declared `commandSpecs`,
602
- * mounted by `mountCommandSpec`. `register()` and the raw-Commander `program`
603
- * handle on the tool context are gone, so the host owns `program` and passes it
604
- * in here (the tool never touches Commander). A tool with no `commandSpecs` is a
605
- * mis-declaration: it contributes no commands, surfaced loudly via
606
- * `cli.tool.no_command_surface`.
607
- *
608
- * Failures are isolated per tool — one tool whose spec fails to mount must not
609
- * take the whole CLI down. The failure is logged + stderr-warned, then we
610
- * continue with the next tool.
611
- *
612
- * @param registry The per-invocation tool registry to walk.
613
- * @param program The root Commander program (host-owned; the composition root
614
- * passes it — it is no longer reachable through the tool context, §8).
615
- * @param ctx The per-invocation handler context (render/emit/scope — no program).
616
- */
617
- export function mountAllToolCommands(registry, program, ctx) {
618
- for (const tool of registry.list()) {
619
- try {
620
- mountOneTool(program, tool, ctx);
621
- }
622
- catch (error) {
623
- const msg = error instanceof Error ? error.message : String(error);
624
- const human = tool.metadata.name ?? tool.metadata.id;
625
- process.stderr.write(`opensip: tool ${human} failed to mount: ${msg}\n`);
626
- logger.warn({
627
- evt: 'cli.tool.register_failed',
628
- module: BOOTSTRAP_MODULE,
629
- toolId: tool.metadata.id, // stable UUID
630
- toolName: human,
631
- error: msg,
632
- });
633
- }
634
- }
635
- // ADR-0021: one shared help shape across every mounted command — uniform
636
- // option/subcommand ordering and a docs footer — applied here (the single
637
- // place that has walked every tool's commands) rather than per tool.
638
- applySharedHelpConfiguration(program);
639
- }
640
- /**
641
- * Mount ONE tool's commands from its declared `commandSpecs` — the only command
642
- * surface (public launch). Extracted so {@link mountAllToolCommands} keeps its
643
- * per-tool failure isolation around a single call. A tool with no `commandSpecs`
644
- * contributes nothing and is surfaced via `cli.tool.no_command_surface`.
645
- */
646
- function mountOneTool(program, tool, ctx) {
647
- if (tool.commandSpecs !== undefined && tool.commandSpecs.length > 0) {
648
- for (const spec of tool.commandSpecs) {
649
- // `Tool.commandSpecs` is `CommandSpec<unknown, ToolCliContext>[]`, which
650
- // is assignable to the mounter's `HostCommandSpec` (handler contravariance
651
- // — an `unknown`-opts handler accepts a `Record`-opts call). No cast.
652
- mountCommandSpec(program, spec, ctx);
653
- }
654
- return;
655
- }
656
- // No declarative command surface — a mis-declared tool contributes no commands.
657
- // Surface it rather than silently mounting nothing.
658
- logger.warn({
659
- evt: 'cli.tool.no_command_surface',
660
- module: BOOTSTRAP_MODULE,
661
- toolId: tool.metadata.id, // stable
662
- toolName: tool.metadata.name ?? tool.metadata.id,
663
- detail: 'tool declares no commandSpecs; no commands mounted',
664
- });
665
- }
666
- const DOCS_HELP_FOOTER = '\nDocs: https://opensip.ai/docs/opensip-cli';
667
- /**
668
- * Apply one help configuration to the root program and every (sub)command:
669
- * options + subcommands sort alphabetically so the help reads the same across
670
- * `fit`/`graph`/`sim`, and the root help ends with a docs pointer (ADR-0021).
671
- */
672
- function applySharedHelpConfiguration(program) {
673
- const configure = (cmd) => {
674
- cmd.configureHelp({ sortOptions: true, sortSubcommands: true });
675
- for (const sub of cmd.commands)
676
- configure(sub);
677
- };
678
- configure(program);
679
- program.addHelpText('after', DOCS_HELP_FOOTER);
680
- }
13
+ export { BUNDLED_TOOL_PACKAGES, EXPECTED_SCAFFOLDING_TOOL_IDS } from './register-tools-shared.js';
14
+ export { registerFirstPartyTools } from './register-tools-bundled.js';
15
+ export { buildToolDiscoverySources, discoverAndRegisterToolPackages, admitProjectLocalTool, admitUserGlobalTool, discoverAndRegisterAuthoredTools, } from './register-tools-discovery.js';
16
+ export { mountAllToolCommands } from './register-tools-mount.js';
681
17
  //# sourceMappingURL=register-tools.js.map