/** * Tests for SkilledOpenApiPlugin construction + dynamicProviders shape. * * The plugin is decorated with @Plugin which doesn't run side effects we can * easily exercise without a full FrontMCP scope; instead we focus on: * - constructor parses options strictly (zod throws on invalid input) * - constructor warns when dev=true or requireSignature=false * - dynamicProviders returns the expected provider tokens * - asCredentialResolverToken cast helper is callable (covers symbols.ts) */ import 'reflect-metadata'; import { promises as fs } from 'node:fs'; import * as os from 'node:os'; import * as path from 'node:path'; import { BundleStore, type BundleStoreTelemetry } from '@frontmcp/adapters/skills'; import { ZodError } from '@frontmcp/lazy-zod'; import { MemoryCredentialResolver } from '../executor/credential-resolver'; import { HiddenOpRegistry } from '../registry/hidden-op.registry'; import { AuthorityGuard } from '../security/authority-guard'; import { VaultRefListedTwiceError } from '../skilled-openapi.errors'; import SkilledOpenApiPlugin from '../skilled-openapi.plugin'; import { asCredentialResolverToken, SkilledOpenApiConfig, SkilledOpenApiCredentialResolver, } from '../skilled-openapi.symbols'; import { skilledOpenApiPluginOptionsSchema } from '../skilled-openapi.types'; import { BundleSyncService } from '../sync/bundle-sync.service'; /** A scope's `batchListChanges`, for the fake scopes: runs the change. */ const batchListChanges = async (change: () => T | Promise): Promise => change(); const validBundle = { schemaVersion: 1, bundleId: 'plugin:test', version: '1', generatedAt: '2026-05-04T00:00:00Z', sourceDigest: 'a'.repeat(64), services: [{ id: 'svc', baseUrl: 'http://127.0.0.1:9999' }], authBindings: { def: { kind: 'none' } }, skills: [], operations: {}, }; describe('SkilledOpenApiPlugin', () => { describe('constructor', () => { it('parses minimal valid options', () => { const plugin = new SkilledOpenApiPlugin({ source: { type: 'static', path: '/tmp/x.json' }, }); expect(plugin.options.source.type).toBe('static'); expect(plugin.options.requireSignature).toBe(true); }); it('throws on invalid options (zod)', () => { expect(() => new SkilledOpenApiPlugin({ source: { type: 'static' } as never })).toThrow(); }); describe('a vaultRef listed under both credentials and authProviders', () => { const listedTwice = { source: { type: 'static' as const, path: '/x' }, credentials: { 'billing-token': 'server-token', 'reports-token': 'reports' }, authProviders: { 'billing-token': 'billing', 'crm-token': 'crm' }, }; it('is refused when the plugin is installed', () => { expect(() => SkilledOpenApiPlugin.dynamicProviders(listedTwice)).toThrow( new VaultRefListedTwiceError(['billing-token']), ); }); it('is refused when the plugin is built', () => { expect(() => new SkilledOpenApiPlugin(listedTwice)).toThrow(VaultRefListedTwiceError); }); it('is refused by the exported options schema', () => { const result = skilledOpenApiPluginOptionsSchema.safeParse(listedTwice); expect(result.success).toBe(false); expect(result.error?.issues).toEqual([ expect.objectContaining({ path: ['authProviders'], message: new VaultRefListedTwiceError(['billing-token']).message, }), ]); }); it('still reports another bad option as a ZodError', () => { const badKeysListedTwice = { ...listedTwice, trustedKeys: 'not-a-list' as never }; expect(() => new SkilledOpenApiPlugin(badKeysListedTwice)).toThrow(ZodError); }); it('names the vaultRef in the error', () => { expect(new VaultRefListedTwiceError(['billing-token']).message).toBe( 'SkilledOpenApiPlugin: vaultRef "billing-token" is listed under both credentials and authProviders, so ' + "its binding would send the caller's own credential and never the server's. Keep each vaultRef in one of " + 'the two.', ); }); }); it('warns on dev=true', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, dev: true }); expect(warn).toHaveBeenCalledWith(expect.stringMatching(/dev=true: signature verification BYPASSED/)); } finally { warn.mockRestore(); } }); // In 1.8.7 `dev: true` left `requireSignature` at its default `true`, so an unsigned bundle // was still rejected. it('turns the signature requirement off with dev=true', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { const plugin = new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, dev: true }); expect(plugin.options.requireSignature).toBe(false); expect(plugin.options.outbound.allowHttp).toBe(true); } finally { warn.mockRestore(); } }); it('keeps an explicit requireSignature=true with dev=true, and says so', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { const plugin = new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, dev: true, requireSignature: true, }); expect(plugin.options.requireSignature).toBe(true); expect(warn).toHaveBeenCalledWith(expect.stringMatching(/dev=true: signature verification kept/)); } finally { warn.mockRestore(); } }); it('resolves the requirement in the config the providers share', () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/x' }, dev: true }); const config = providers.find((p) => (p as { provide: unknown }).provide === SkilledOpenApiConfig) as { useValue: SkilledOpenApiConfig; }; expect(config.useValue.options.requireSignature).toBe(false); }); it('warns on requireSignature=false without dev=true', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, requireSignature: false, }); expect(warn).toHaveBeenCalledWith(expect.stringMatching(/requireSignature=false/)); } finally { warn.mockRestore(); } }); it.each([ [undefined, false], ['hostname' as const, true], ['approved-address' as const, false], ])('with egressProxy and egressProxyConnectTo %p, warns about the proxy: %p', (egressProxyConnectTo, warns) => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, outbound: { egressProxy: 'http://proxy.internal:3128', egressProxyConnectTo }, }); const proxyWarnings = warn.mock.calls.filter(([message]) => String(message).includes('egressProxyConnectTo')); expect(proxyWarnings).toHaveLength(warns ? 1 : 0); } finally { warn.mockRestore(); } }); it('says once at startup, by default, that the egress proxy is asked for approved addresses and how to switch', () => { const info = jest.spyOn(console, 'info').mockImplementation(() => {}); try { new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, outbound: { egressProxy: 'http://proxy.internal:3128' }, }); expect(info).toHaveBeenCalledTimes(1); expect(info).toHaveBeenCalledWith(expect.stringContaining("egressProxyConnectTo: 'hostname'")); } finally { info.mockRestore(); } }); it.each([undefined, 'approved-address' as const])( 'refuses a SOCKS egressProxy at startup with egressProxyConnectTo %p', (egressProxyConnectTo) => { expect( () => new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, outbound: { egressProxy: 'socks5://proxy.internal:1080', egressProxyConnectTo }, }), ).toThrow( /needs an http: or https: proxy.*Set outbound\.egressProxyConnectTo: 'hostname' to keep a SOCKS proxy/, ); }, ); it("keeps a SOCKS egressProxy with egressProxyConnectTo 'hostname'", () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { expect( () => new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, outbound: { egressProxy: 'socks5://proxy.internal:1080', egressProxyConnectTo: 'hostname' }, }), ).not.toThrow(); } finally { warn.mockRestore(); } }); it('reports an egressProxy that is not a URL as an option error, not a bare TypeError', () => { const build = () => new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' }, outbound: { egressProxy: '10.0.0.1:3128', egressProxyConnectTo: 'approved-address' }, }); expect(build).toThrow(/egressProxy/); expect(build).not.toThrow(/Invalid URL$/); }); it('does not warn when both requireSignature=true and dev=false (default safe config)', () => { const warn = jest.spyOn(console, 'warn').mockImplementation(() => {}); try { new SkilledOpenApiPlugin({ source: { type: 'static', path: '/x' } }); expect(warn).not.toHaveBeenCalled(); } finally { warn.mockRestore(); } }); }); describe('dynamicProviders', () => { it('returns providers for config / hidden-ops / bundle-store / resolver / guard / sync', () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/x' }, }); const tokens = providers.map((p) => (p as { provide: unknown }).provide); expect(tokens).toContain(SkilledOpenApiConfig); expect(tokens).toContain(HiddenOpRegistry); expect(tokens).toContain(BundleStore); expect(tokens).toContain(MemoryCredentialResolver); expect(tokens).not.toContain(SkilledOpenApiCredentialResolver); expect(tokens).toContain(AuthorityGuard); expect(tokens).toContain(BundleSyncService); }); it('seeds the in-memory credential resolver from `credentials` option', async () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/x' }, credentials: { 'demo-token': 'sk_xxx' }, }); const credProvider = providers.find((p) => (p as { provide: unknown }).provide === MemoryCredentialResolver) as { useValue: MemoryCredentialResolver; }; const value = await credProvider.useValue.resolve('demo-token', { bundleId: 'b' }); expect(value).toBe('sk_xxx'); }); it('bundle-sync factory boots a static source and applies the bundle', async () => { // Build a tmp bundle file the static source can load. const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-test-')); const bundlePath = path.join(tmpDir, 'bundle.json'); await fs.writeFile(bundlePath, JSON.stringify(validBundle), 'utf8'); const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: bundlePath }, requireSignature: false, dev: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; // Build minimal scope/registry/store stubs so the factory can run. const fakeLogger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn().mockReturnThis(), }; const fakeScope = { logger: fakeLogger, registerHealthProbe: jest.fn(), batchListChanges, skills: { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 's', unregister: async () => {} })), unregisterSkill: jest.fn(async () => false), }, }; const hiddenOps = new HiddenOpRegistry(); const bundleStore = new BundleStore(); const sync = await syncProvider.useFactory(fakeScope, hiddenOps, bundleStore); expect(sync).toBeInstanceOf(BundleSyncService); // Poll up to 1s for the deferred source.start() → bundle apply path. const deadline = Date.now() + 1000; while (Date.now() < deadline && !bundleStore.current()) { await new Promise((r) => setTimeout(r, 25)); } expect(bundleStore.current()?.bundleId).toBe('plugin:test'); await fs.rm(tmpDir, { recursive: true, force: true }); }); it('applies the first bundle once the scope is ready, though a timer fires before it (#1169)', async () => { const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-test-')); const bundlePath = path.join(tmpDir, 'bundle.json'); const bundleWithSkill = { ...validBundle, skills: [{ id: 's', name: 'S', description: 'd', instructions: 'i', operationIds: [] }], }; await fs.writeFile(bundlePath, JSON.stringify(bundleWithSkill), 'utf8'); const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: bundlePath }, requireSignature: false, dev: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; const fakeLogger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn().mockReturnThis(), }; let scopeReady!: () => void; const fakeScope: Record = { logger: fakeLogger, registerHealthProbe: jest.fn(), batchListChanges, skills: undefined, ready: new Promise((resolve) => { scopeReady = resolve; }), }; const bundleStore = new BundleStore(); await syncProvider.useFactory(fakeScope, new HiddenOpRegistry(), bundleStore); await new Promise((r) => setTimeout(r, 50)); expect(fakeLogger.error).not.toHaveBeenCalled(); fakeScope['skills'] = { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 's', unregister: async () => {} })), unregisterSkill: jest.fn(async () => false), }; scopeReady(); const deadline = Date.now() + 1000; while (Date.now() < deadline && !bundleStore.current()) { await new Promise((r) => setTimeout(r, 25)); } expect(bundleStore.current()?.bundleId).toBe('plugin:test'); await fs.rm(tmpDir, { recursive: true, force: true }); }); it('lazy skill-registry proxy throws when scope.skills is missing', async () => { const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-test-')); const bundlePath = path.join(tmpDir, 'bundle.json'); // Bundle with at least one skill so apply() reaches registerSkillContent // (empty skills would never trigger the proxy access). const bundleWithSkill = { ...validBundle, skills: [{ id: 's', name: 'S', description: 'd', instructions: 'i', operationIds: [] }], }; await fs.writeFile(bundlePath, JSON.stringify(bundleWithSkill), 'utf8'); const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: bundlePath }, requireSignature: false, dev: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; // Logger.child must return an object that ALSO routes its calls back to // the root mocks; the proxy throw is logged via scope.logger.child(...) // inside the factory. const sharedWarn = jest.fn(); const sharedError = jest.fn(); const childLogger = { warn: sharedWarn, info: jest.fn(), error: sharedError, debug: jest.fn(), verbose: jest.fn(), child: jest.fn(function this_(): unknown { return this; }), }; const fakeLogger = { warn: sharedWarn, info: jest.fn(), error: sharedError, debug: jest.fn(), verbose: jest.fn(), child: jest.fn(() => childLogger), }; const fakeScope = { logger: fakeLogger, registerHealthProbe: jest.fn(), skills: undefined }; const sync = await syncProvider.useFactory(fakeScope, new HiddenOpRegistry(), new BundleStore()); expect(sync).toBeInstanceOf(BundleSyncService); const deadline = Date.now() + 1500; while (Date.now() < deadline && sharedWarn.mock.calls.length + sharedError.mock.calls.length === 0) { await new Promise((r) => setTimeout(r, 25)); } expect(sharedWarn.mock.calls.length + sharedError.mock.calls.length).toBeGreaterThan(0); await fs.rm(tmpDir, { recursive: true, force: true }); }); it("registers per-op internal tools, built on the plugin's providers, when scope.tools is available", async () => { // Use a bundle with an operation so the sync flow drives the factory's // registerToolInstance call — verifying not just construction but the // full wiring: factory → toolRegistry → registerToolInstance. const bundleWithOp = { ...validBundle, skills: [ { id: 'invoices', name: 'Invoices', description: 'Manage invoices.', instructions: '# Invoices', operationIds: ['createInvoice'], }, ], operations: { createInvoice: { operationId: 'createInvoice', serviceId: 'svc', httpMethod: 'POST', pathTemplate: '/v1/invoices', inputSchema: {}, outputSchema: {}, mapper: [], authBindingRef: 'def', }, }, }; const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'plugin-test-')); const bundlePath = path.join(tmpDir, 'bundle.json'); await fs.writeFile(bundlePath, JSON.stringify(bundleWithOp), 'utf8'); const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: bundlePath }, requireSignature: false, dev: true, exposeOperationsAsInternalTools: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; const fakeLogger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn().mockReturnThis(), }; const fakeTools = { registerToolInstance: jest.fn((tool: { providers: unknown }) => tool), unregisterToolInstance: jest.fn(() => true), getToolsForListing: jest.fn(() => []), getTools: jest.fn(() => []), }; const fakeScope = { logger: fakeLogger, registerHealthProbe: jest.fn(), batchListChanges, skills: { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 'invoices', unregister: async () => {} })), unregisterSkill: jest.fn(async () => false), }, tools: fakeTools, }; const pluginProviders = { getActiveScope: () => ({ logger: fakeLogger, hooks: { registerHooks: jest.fn() } }) }; const sync = await syncProvider.useFactory(fakeScope, new HiddenOpRegistry(), new BundleStore(), pluginProviders); expect(sync).toBeInstanceOf(BundleSyncService); // Wait up to 1s for the deferred source.start() → bundle apply → tool // factory registration chain to complete. const deadline = Date.now() + 1000; while (Date.now() < deadline && fakeTools.registerToolInstance.mock.calls.length === 0) { await new Promise((r) => setTimeout(r, 25)); } expect(fakeTools.registerToolInstance).toHaveBeenCalled(); expect(fakeTools.registerToolInstance.mock.calls[0][0].providers).toBe(pluginProviders); await fs.rm(tmpDir, { recursive: true, force: true }); }); // The server builds plugin providers while its plugins initialize, BEFORE it creates the scope's // tool registry. In 1.8.7 the factory read `scope.tools` right then, found nothing, and turned // the per-operation tools off for good. describe('when scope.tools does not exist yet as the factory runs', () => { const bundleWithOp = { ...validBundle, skills: [{ id: 'invoices', name: 'Invoices', description: 'd', instructions: 'i', operationIds: ['getInv'] }], operations: { getInv: { operationId: 'getInv', serviceId: 'svc', httpMethod: 'GET', pathTemplate: '/v1/invoices', inputSchema: {}, outputSchema: {}, mapper: [], authBindingRef: 'def', }, }, }; const silentLogger = () => { const logger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn(() => logger), }; return logger; }; const pluginProvidersOf = (logger: ReturnType) => ({ getActiveScope: () => ({ logger, hooks: { registerHooks: jest.fn() } }), }); const buildSync = async (scope: { logger: ReturnType } & Record) => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'inline', content: bundleWithOp }, dev: true, exposeOperationsAsInternalTools: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; return syncProvider.useFactory( scope, new HiddenOpRegistry(), new BundleStore(), pluginProvidersOf(scope.logger), ); }; it('registers the operation tools in the registry the scope has by the time the bundle applies', async () => { const logger = silentLogger(); const scope: { logger: typeof logger } & Record = { logger, registerHealthProbe: jest.fn(), batchListChanges, skills: { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 'invoices', unregister: async () => {} })), }, tools: undefined, }; const sync = await buildSync(scope); const tools = { registerToolInstance: jest.fn(), unregisterToolInstance: jest.fn(() => true) }; scope['tools'] = tools; // the scope creates its tool registry after the plugins await sync.ensureReady(); expect(tools.registerToolInstance).toHaveBeenCalledTimes(1); expect(logger.warn).not.toHaveBeenCalled(); }); it('logs, and still applies the bundle, when the scope never gets a tool registry', async () => { const logger = silentLogger(); const scope = { logger, registerHealthProbe: jest.fn(), batchListChanges, skills: { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 'invoices', unregister: async () => {} })), }, }; const bundleStore = new BundleStore(); const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'inline', content: bundleWithOp }, dev: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; const sync = await syncProvider.useFactory( scope, new HiddenOpRegistry(), bundleStore, pluginProvidersOf(logger), ); await sync.ensureReady(); expect(logger.warn).toHaveBeenCalledWith(expect.stringMatching(/scope\.tools not available/)); expect(bundleStore.current()?.bundleId).toBe('plugin:test'); }); }); describe("the plugin's /readyz check", () => { const quietLogger = () => { const logger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn(() => logger), }; return logger; }; /** Builds the sync service and returns the check it registered on the scope. */ const registeredHealthCheck = async (options: Parameters[0]) => { const registerHealthProbe = jest.fn(); const scope = { logger: quietLogger(), registerHealthProbe, batchListChanges, skills: { notifyListChanged: jest.fn(), registerSkillContent: jest.fn(async () => ({ id: 's', unregister: async () => {} })), }, }; const syncProvider = SkilledOpenApiPlugin.dynamicProviders(options).find( (p) => (p as { provide: unknown }).provide === BundleSyncService, ) as { useFactory: (...args: unknown[]) => Promise }; await syncProvider.useFactory(scope, new HiddenOpRegistry(), new BundleStore()); expect(registerHealthProbe).toHaveBeenCalledTimes(1); return registerHealthProbe.mock.calls[0][0] as { name: string; check: () => Promise }; }; it('reports the loaded bundle by id and version', async () => { const probe = await registeredHealthCheck({ source: { type: 'inline', content: validBundle }, dev: true }); expect(probe.name).toBe('skilled-openapi'); expect(await probe.check()).toEqual({ status: 'healthy', details: { state: 'loaded', bundleId: 'plugin:test', bundleVersion: '1' }, }); }); it('reports a bundle that failed to load as unhealthy, with why', async () => { const probe = await registeredHealthCheck({ source: { type: 'inline', content: validBundle }, requireSignature: true, }); expect(await probe.check()).toEqual({ status: 'unhealthy', details: { state: 'failed', lastSync: { status: 'refused', bundleId: 'plugin:test', bundleVersion: '1', reason: 'bundle missing integrity envelope', at: expect.any(String), }, }, error: 'no skill bundle is loaded: bundle plugin:test@1 was not applied: bundle missing integrity envelope', }); }); }); it('skips OperationToolFactory wiring when exposeOperationsAsInternalTools=false', async () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/this/does/not/exist' }, requireSignature: false, dev: true, exposeOperationsAsInternalTools: false, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; const fakeLogger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn().mockReturnThis(), }; const fakeScope = { logger: fakeLogger, registerHealthProbe: jest.fn(), skills: { registerSkillContent: jest.fn() }, }; const sync = await syncProvider.useFactory(fakeScope, new HiddenOpRegistry(), new BundleStore()); expect(sync).toBeInstanceOf(BundleSyncService); // No operation tool is registered, so nothing reaches for scope.tools. expect(fakeLogger.warn).not.toHaveBeenCalledWith(expect.stringMatching(/scope\.tools/)); }); it('bundle-sync factory tolerates a malformed source config', async () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ // Use a static source with a path that doesn't exist — source.start() // throws but the factory must not throw itself. source: { type: 'static', path: '/this/does/not/exist' }, requireSignature: false, dev: true, }); const syncProvider = providers.find((p) => (p as { provide: unknown }).provide === BundleSyncService) as { useFactory: (...args: unknown[]) => Promise; }; const fakeLogger = { warn: jest.fn(), info: jest.fn(), error: jest.fn(), debug: jest.fn(), verbose: jest.fn(), child: jest.fn().mockReturnThis(), }; const fakeScope = { logger: fakeLogger, registerHealthProbe: jest.fn(), skills: { registerSkillContent: jest.fn(), unregisterSkill: jest.fn() }, }; const sync = await syncProvider.useFactory(fakeScope, new HiddenOpRegistry(), new BundleStore()); expect(sync).toBeInstanceOf(BundleSyncService); const deadline = Date.now() + 1000; while (Date.now() < deadline && fakeLogger.error.mock.calls.length === 0) { await new Promise((r) => setTimeout(r, 25)); } expect(fakeLogger.error).toHaveBeenCalledWith(expect.stringMatching(/initial bundle sync failed/)); }); }); describe('BundleStore useFactory + resolveBundleTelemetry', () => { // Drives the BundleStore provider's useFactory and the // resolveBundleTelemetry helper. Each branch of the helper (no-providers / // providers.get throws / providers.get returns non-factory / providers.get // returns a real factory) is exercised by a separate scope. const findBundleStoreProvider = ( providers: ReturnType, ): { useFactory: (...args: unknown[]) => BundleStore } => { const p = providers.find((entry) => (entry as { provide: unknown }).provide === BundleStore) as { useFactory: (...args: unknown[]) => BundleStore; }; return p; }; const baseDyn = () => SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/x' } }); it('returns a BundleStore when scope.providers is missing entirely', () => { const { useFactory } = findBundleStoreProvider(baseDyn()); const store = useFactory({} as never); expect(store).toBeInstanceOf(BundleStore); }); it('returns a BundleStore when providers.get is not a function', () => { const { useFactory } = findBundleStoreProvider(baseDyn()); const store = useFactory({ providers: { get: 'not-a-fn' } } as never); expect(store).toBeInstanceOf(BundleStore); }); it('handles providers.get throwing (observability not installed)', () => { const { useFactory } = findBundleStoreProvider(baseDyn()); const providers = { get: jest.fn(() => { throw new Error('token not registered'); }), }; const store = useFactory({ providers } as never); expect(store).toBeInstanceOf(BundleStore); expect(providers.get).toHaveBeenCalled(); }); it('rejects a factory whose createCounter is not callable', () => { const { useFactory } = findBundleStoreProvider(baseDyn()); const providers = { get: jest.fn(() => ({ createCounter: 'not-a-fn' })), }; const store = useFactory({ providers } as never); expect(store).toBeInstanceOf(BundleStore); }); it('wires telemetry callbacks when providers.get returns a real factory', () => { const { useFactory } = findBundleStoreProvider(baseDyn()); const counter = { add: jest.fn() }; const span = { end: jest.fn(), setAttribute: jest.fn() }; const factory = { createCounter: jest.fn(() => counter), startSpan: jest.fn(() => span), }; const providers = { get: jest.fn(() => factory) }; const store = useFactory({ providers } as never); expect(store).toBeInstanceOf(BundleStore); // The store carries telemetry whose callbacks delegate to the factory — // exercise both paths so the wrapper arrows on resolveBundleTelemetry's // return value are reached. const telemetry = (store as unknown as { telemetry?: BundleStoreTelemetry }).telemetry; if (telemetry) { telemetry.createCounter('bundle.pulls', 'pulls-desc'); telemetry.startSpan('skill.bundle.swap', { v: '1' }); expect(factory.createCounter).toHaveBeenCalledWith('bundle.pulls', 'pulls-desc'); expect(factory.startSpan).toHaveBeenCalledWith('skill.bundle.swap', { v: '1' }); } }); }); describe('AuthorityGuard useFactory', () => { it('builds an AuthorityGuard with a scoped child logger', () => { const providers = SkilledOpenApiPlugin.dynamicProviders({ source: { type: 'static', path: '/x' }, }); const ag = providers.find((p) => (p as { provide: unknown }).provide === AuthorityGuard) as { useFactory: (...args: unknown[]) => AuthorityGuard; }; const child = jest.fn(); const guard = ag.useFactory({ logger: { child: child.mockReturnValue({ info: jest.fn(), warn: jest.fn() }) }, } as never); expect(guard).toBeInstanceOf(AuthorityGuard); expect(child).toHaveBeenCalledWith('skilled-openapi:authority'); }); }); describe('symbols', () => { it('asCredentialResolverToken returns the resolver typed as the abstract token', async () => { const resolver = new MemoryCredentialResolver({ k: 'v' }); const token = asCredentialResolverToken(resolver); expect(await token.resolve('k', { bundleId: 'b', authInfo: {} })).toBe('v'); }); it('SkilledOpenApiConfig.outbound exposes the parsed outbound options', () => { const config = new SkilledOpenApiConfig({ source: { type: 'static', path: '/x', watch: false }, requireSignature: true, trustedKeys: [], dev: false, outbound: { allowPrivateNetworks: false, maxConcurrencyPerHost: 5, defaultTimeoutMs: 1000, defaultMaxResponseBytes: 1024, allowHttp: false, }, sourceConflictPolicy: 'static-wins', } as never); expect(config.outbound.maxConcurrencyPerHost).toBe(5); }); }); });