@mastra/code-sdk 1.15.0-alpha.11 → 1.15.0-alpha.13
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.
- package/dist/acp/agent.js +2 -1
- package/dist/acp/agent.js.map +1 -1
- package/dist/acp/event-mapper.js +0 -2
- package/dist/acp/event-mapper.js.map +1 -1
- package/dist/acp.js +1 -2
- package/dist/agent-connections/registry.js.map +1 -1
- package/dist/agent-connections/signal-provider.js.map +1 -1
- package/dist/agent-connections/state-processor.js.map +1 -1
- package/dist/agent-connections/tools.js +26 -24
- package/dist/agent-connections/tools.js.map +1 -1
- package/dist/agents/instructions.js +3 -2
- package/dist/agents/instructions.js.map +1 -1
- package/dist/agents/mastracode-gateway.js +35 -27
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.d.ts.map +1 -1
- package/dist/agents/memory.js +16 -2
- package/dist/agents/memory.js.map +1 -1
- package/dist/agents/prompts/agent-instructions.js +1 -1
- package/dist/agents/prompts/agent-instructions.js.map +1 -1
- package/dist/agents/prompts/index.js +3 -2
- package/dist/agents/prompts/index.js.map +1 -1
- package/dist/agents/prompts/plan.js +2 -1
- package/dist/agents/prompts/plan.js.map +1 -1
- package/dist/agents/sandbox-filesystem.d.ts +28 -0
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
- package/dist/agents/sandbox-filesystem.js +81 -2
- package/dist/agents/sandbox-filesystem.js.map +1 -1
- package/dist/agents/tools.d.ts.map +1 -1
- package/dist/agents/tools.js +18 -12
- package/dist/agents/tools.js.map +1 -1
- package/dist/agents/workspace.js +2 -1
- package/dist/agents/workspace.js.map +1 -1
- package/dist/auth/account-rotation-processor.js +2 -1
- package/dist/auth/account-rotation-processor.js.map +1 -1
- package/dist/auth/providers/anthropic.js +2 -2
- package/dist/auth/providers/anthropic.js.map +1 -1
- package/dist/auth/providers/github-copilot.js +1 -1
- package/dist/auth/providers/github-copilot.js.map +1 -1
- package/dist/auth/providers/openai-codex.js +3 -2
- package/dist/auth/providers/openai-codex.js.map +1 -1
- package/dist/auth/providers/xai.js +1 -1
- package/dist/auth/providers/xai.js.map +1 -1
- package/dist/clipboard/index.js +5 -4
- package/dist/clipboard/index.js.map +1 -1
- package/dist/evals/context-builder.js +1 -3
- package/dist/evals/context-builder.js.map +1 -1
- package/dist/evals/scorers/outcome.js +2 -1
- package/dist/evals/scorers/outcome.js.map +1 -1
- package/dist/factory/remote-controller.js.map +1 -1
- package/dist/factory/remote-session.js +1 -3
- package/dist/factory/remote-session.js.map +1 -1
- package/dist/headless/cli.js +2 -1
- package/dist/headless/cli.js.map +1 -1
- package/dist/headless/run-mc.js +9 -9
- package/dist/headless/run-mc.js.map +1 -1
- package/dist/hooks/executor.js +3 -1
- package/dist/hooks/executor.js.map +1 -1
- package/dist/hooks/manager.js +40 -26
- package/dist/hooks/manager.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +14 -10
- package/dist/index.js.map +1 -1
- package/dist/knowledge-inspector.js +2 -2
- package/dist/knowledge-inspector.js.map +1 -1
- package/dist/lsp/server.js +4 -2
- package/dist/lsp/server.js.map +1 -1
- package/dist/mcp/manager.d.ts.map +1 -1
- package/dist/mcp/manager.js +14 -2
- package/dist/mcp/manager.js.map +1 -1
- package/dist/onboarding/settings.js +5 -2
- package/dist/onboarding/settings.js.map +1 -1
- package/dist/platform/index.js +5 -3
- package/dist/platform/index.js.map +1 -1
- package/dist/plugins/loader.js +3 -1
- package/dist/plugins/loader.js.map +1 -1
- package/dist/plugins/manager.js +2 -1
- package/dist/plugins/manager.js.map +1 -1
- package/dist/plugins/package-link.js.map +1 -1
- package/dist/plugins/scaffold.js +4 -2
- package/dist/plugins/scaffold.js.map +1 -1
- package/dist/plugins/signal-lane.js.map +1 -1
- package/dist/process-memory-diagnostics.js +2 -1
- package/dist/process-memory-diagnostics.js.map +1 -1
- package/dist/providers/amazon-bedrock-gateway.js +2 -1
- package/dist/providers/amazon-bedrock-gateway.js.map +1 -1
- package/dist/providers/amazon-bedrock.js +2 -2
- package/dist/providers/amazon-bedrock.js.map +1 -1
- package/dist/providers/claude-max.js +13 -9
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot-gateway.js.map +1 -1
- package/dist/providers/github-copilot.js +13 -12
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/openai-codex.js +14 -11
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/provider-thinking.js.map +1 -1
- package/dist/providers/thinking-request.js +1 -1
- package/dist/providers/thinking-request.js.map +1 -1
- package/dist/schedules/run-script.js +1 -1
- package/dist/schedules/run-script.js.map +1 -1
- package/dist/schedules/scheduler.js.map +1 -1
- package/dist/tools/request-sandbox-access.js +7 -5
- package/dist/tools/request-sandbox-access.js.map +1 -1
- package/dist/tools/utils.js +3 -1
- package/dist/tools/utils.js.map +1 -1
- package/dist/tools/web-search.d.ts +13 -11
- package/dist/tools/web-search.d.ts.map +1 -1
- package/dist/tools/web-search.js +21 -15
- package/dist/tools/web-search.js.map +1 -1
- package/dist/utils/debug-log.js +2 -2
- package/dist/utils/debug-log.js.map +1 -1
- package/dist/utils/gateway-sync.js +1 -1
- package/dist/utils/gateway-sync.js.map +1 -1
- package/dist/utils/local-observability.d.ts +1 -1
- package/dist/utils/local-observability.d.ts.map +1 -1
- package/dist/utils/local-observability.js +1 -1
- package/dist/utils/local-observability.js.map +1 -1
- package/dist/utils/prune-cli.js +10 -8
- package/dist/utils/prune-cli.js.map +1 -1
- package/dist/utils/signals-pubsub.js.map +1 -1
- package/dist/utils/slash-command-processor.js +1 -1
- package/dist/utils/slash-command-processor.js.map +1 -1
- package/dist/utils/stdin-pipe.js +1 -1
- package/dist/utils/stdin-pipe.js.map +1 -1
- package/dist/utils/storage-factory.d.ts.map +1 -1
- package/dist/utils/storage-factory.js +1 -1
- package/dist/utils/storage-factory.js.map +1 -1
- package/dist/utils/storage-maintenance.js +1 -1
- package/dist/utils/storage-maintenance.js.map +1 -1
- package/dist/utils/update-check.js +2 -1
- package/dist/utils/update-check.js.map +1 -1
- package/dist/workflows/register-primitives.js +1 -1
- package/dist/workflows/register-primitives.js.map +1 -1
- package/package.json +12 -12
package/dist/plugins/loader.js
CHANGED
|
@@ -6,7 +6,9 @@ import { pathToFileURL } from "url";
|
|
|
6
6
|
import { isSignalProvider } from "@mastra/core/signals";
|
|
7
7
|
//#region src/plugins/loader.ts
|
|
8
8
|
async function loadPlugins(options) {
|
|
9
|
-
const
|
|
9
|
+
const globalRegistry = options.globalRegistry ?? loadPluginRegistry(path.join(getPluginRoot("global", options), "plugins.json"));
|
|
10
|
+
const projectRegistry = options.projectRegistry ?? loadPluginRegistry(path.join(getPluginRoot("project", options), "plugins.json"));
|
|
11
|
+
const records = mergePluginRegistries(globalRegistry, projectRegistry);
|
|
10
12
|
const loaded = [];
|
|
11
13
|
for (const record of records) {
|
|
12
14
|
if (record.blocked) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loader.js","names":[],"sources":["../../src/plugins/loader.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { isSignalProvider } from '@mastra/core/signals';\nimport type { SignalProvider } from '@mastra/core/signals';\n\nimport type {\n MastraCodePlugin,\n MastraCodePluginConfigSchema,\n MastraCodePluginConfigValues,\n MastraCodePluginContext,\n MastraCodePluginProcessorEntries,\n MastraCodePluginRuntime,\n MastraCodePluginSignalProviderEntries,\n MastraCodePluginToolEntries,\n MastraCodePluginTools,\n MastraCodeToolRenderConfig,\n} from '../plugin.js';\nimport { getPluginRoot } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, mergePluginRegistries } from './registry.js';\nimport type { LoadedPlugin, LoadedPluginProcessors, PluginRegistry, ScopedInstalledPluginRecord } from './types.js';\n\nexport type LoadPluginRecordOptions = PluginPathOptions & {\n /** Lazy accessors for Mastra Code's runtime, passed on to plugin field resolvers. */\n runtime?: MastraCodePluginRuntime;\n};\n\nexport type LoadPluginsOptions = LoadPluginRecordOptions & {\n globalRegistry?: PluginRegistry;\n projectRegistry?: PluginRegistry;\n};\n\nexport async function loadPlugins(options: LoadPluginsOptions): Promise<LoadedPlugin[]> {\n const globalRegistry =\n options.globalRegistry ?? loadPluginRegistry(path.join(getPluginRoot('global', options), 'plugins.json'));\n const projectRegistry =\n options.projectRegistry ?? loadPluginRegistry(path.join(getPluginRoot('project', options), 'plugins.json'));\n const records = mergePluginRegistries(globalRegistry, projectRegistry);\n const loaded: LoadedPlugin[] = [];\n\n for (const record of records) {\n if (record.blocked) {\n loaded.push({ ...record, status: 'blocked', tools: {}, toolNames: [] });\n continue;\n }\n if (!record.enabled) {\n loaded.push({ ...record, status: 'inactive', tools: {}, toolNames: [] });\n continue;\n }\n\n loaded.push(await loadPluginRecord(record, options));\n }\n\n return markToolConflicts(loaded);\n}\n\nexport async function loadPluginRecord(\n record: ScopedInstalledPluginRecord,\n options: LoadPluginRecordOptions,\n): Promise<LoadedPlugin> {\n try {\n const entryPath = resolvePluginEntryPath(record, options);\n const plugin = await importPluginModule(entryPath);\n if (plugin.id !== record.id) {\n throw new Error(`Plugin id mismatch: registry has \"${record.id}\" but module exports \"${plugin.id}\"`);\n }\n\n const configSchema = validatePluginConfigSchema(plugin.config);\n const configValues = resolvePluginConfigValues(configSchema, record.config);\n const pluginDir = path.dirname(entryPath);\n const pluginRoot = resolvePluginRoot(record, options);\n const context: MastraCodePluginContext = {\n cwd: options.projectRoot,\n scope: record.scope,\n pluginDir,\n config: configValues,\n // Accessors, not instances: plugins load before the controller and the\n // session exist, so a plugin resolves these when it needs them, not now.\n getController: options.runtime?.getController,\n getActiveSession: options.runtime?.getActiveSession,\n getStorage: options.runtime?.getStorage,\n };\n const { tools, renderConfigs } = await resolvePluginTools(plugin, context);\n const processors = await resolvePluginProcessors(plugin, context);\n const signalProviders = await resolvePluginSignalProviders(plugin, context);\n const instructions = await resolvePluginInstructions(plugin, context);\n\n return {\n ...record,\n name: plugin.name,\n version: plugin.version ?? record.version,\n description: plugin.description,\n instructions,\n status: 'active',\n tools,\n renderConfigs,\n toolNames: Object.keys(tools).sort(),\n processors,\n signalProviders,\n skillPaths: resolveExistingAssetDirs(pluginRoot, 'skills'),\n commandPaths: resolveExistingAssetDirs(pluginRoot, 'commands'),\n configSchema,\n configValues,\n };\n } catch (error) {\n return {\n ...record,\n status: 'load failed',\n error: error instanceof Error ? error.message : String(error),\n tools: {},\n toolNames: [],\n };\n }\n}\n\nexport async function loadPluginFromEntry(entryPath: string): Promise<MastraCodePlugin> {\n return validatePluginExport(await importPluginModule(entryPath));\n}\n\nexport function resolvePluginRoot(record: ScopedInstalledPluginRecord, options: PluginPathOptions): string {\n const scopeRoot = path.resolve(getPluginRoot(record.scope, options));\n const pluginRoot = path.resolve(path.isAbsolute(record.path) ? record.path : path.join(scopeRoot, record.path));\n if (record.source === 'github' && !isInsideDirectory(pluginRoot, scopeRoot)) {\n throw new Error(`Plugin path for \"${record.id}\" must be inside the ${record.scope} plugin directory`);\n }\n return pluginRoot;\n}\n\nexport function resolvePluginEntryPath(record: ScopedInstalledPluginRecord, options: PluginPathOptions): string {\n const pluginRoot = resolvePluginRoot(record, options);\n const entryPath = path.resolve(pluginRoot, record.entry);\n if (!isInsideDirectory(entryPath, pluginRoot)) {\n throw new Error(`Plugin entry for \"${record.id}\" must be inside the plugin directory`);\n }\n return entryPath;\n}\n\nexport function isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\nfunction resolveExistingAssetDirs(pluginRoot: string, dirname: 'skills' | 'commands'): string[] {\n const dir = path.join(pluginRoot, dirname);\n try {\n return fs.statSync(dir).isDirectory() ? [dir] : [];\n } catch {\n return [];\n }\n}\n\nasync function importPluginModule(entryPath: string): Promise<MastraCodePlugin> {\n if (path.extname(entryPath) !== '.ts') {\n throw new Error(\n `Unsupported plugin entry extension \"${path.extname(entryPath)}\". V1 plugins must use .ts entries.`,\n );\n }\n\n const url = pathToFileURL(entryPath);\n const contentHash = Buffer.from(await globalThis.crypto.subtle.digest('SHA-1', fs.readFileSync(entryPath))).toString(\n 'hex',\n );\n const stat = fs.statSync(entryPath, { bigint: true });\n url.searchParams.set('contentHash', contentHash);\n url.searchParams.set('mtimeNs', stat.mtimeNs.toString());\n const mod = (await import(url.href)) as { default?: unknown; plugin?: unknown };\n return validatePluginExport(mod.default ?? mod.plugin);\n}\n\nfunction validatePluginExport(value: unknown): MastraCodePlugin {\n if (!value || typeof value !== 'object') {\n throw new Error('Plugin module must export a plugin object as default or named \"plugin\" export');\n }\n\n const plugin = value as MastraCodePlugin;\n if (typeof plugin.id !== 'string' || plugin.id.trim().length === 0) {\n throw new Error('Plugin id must be a non-empty string');\n }\n\n if (plugin.tools !== undefined && typeof plugin.tools !== 'object' && typeof plugin.tools !== 'function') {\n throw new Error('Plugin tools must be an object or function');\n }\n\n if (\n plugin.processors !== undefined &&\n typeof plugin.processors !== 'object' &&\n typeof plugin.processors !== 'function'\n ) {\n throw new Error('Plugin processors must be an array, object, or function');\n }\n\n if (\n plugin.signalProviders !== undefined &&\n !Array.isArray(plugin.signalProviders) &&\n typeof plugin.signalProviders !== 'function'\n ) {\n throw new Error('Plugin signal providers must be an array or function');\n }\n\n return plugin;\n}\n\nasync function resolvePluginTools(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<{ tools: MastraCodePluginTools; renderConfigs: Record<string, MastraCodeToolRenderConfig> }> {\n if (!plugin.tools) return { tools: {}, renderConfigs: {} };\n const entries = typeof plugin.tools === 'function' ? await plugin.tools(context) : plugin.tools;\n if (!entries || typeof entries !== 'object' || Array.isArray(entries)) {\n throw new Error('Plugin tools function must return an object');\n }\n return normalizePluginToolEntries(entries);\n}\n\n/** Mirrors {@link resolvePluginTools}: object-or-function, resolved with the same context. */\nasync function resolvePluginProcessors(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<LoadedPluginProcessors> {\n if (!plugin.processors) return { input: [], output: [] };\n const entries = typeof plugin.processors === 'function' ? await plugin.processors(context) : plugin.processors;\n if (!entries || typeof entries !== 'object') {\n throw new Error('Plugin processors function must return an array or object');\n }\n return normalizePluginProcessorEntries(entries);\n}\n\nasync function resolvePluginSignalProviders(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<MastraCodePluginSignalProviderEntries> {\n if (!plugin.signalProviders) return [];\n const entries =\n typeof plugin.signalProviders === 'function' ? await plugin.signalProviders(context) : plugin.signalProviders;\n if (!Array.isArray(entries)) {\n throw new Error('Plugin signal providers function must return an array');\n }\n for (const [index, provider] of entries.entries()) {\n if (!isPluginSignalProvider(provider)) {\n throw new Error(\n `Plugin signal provider at index ${index} must be a SignalProvider (an object with an id that implements connect, startPolling, stop and __registerMastra)`,\n );\n }\n }\n return entries;\n}\n\n/**\n * Structural, not `instanceof`.\n *\n * A plugin that depends on a published provider package — the motivating case, a plugin wrapping\n * `@mastra/github-signals` — installs that package's own copy of `@mastra/core`, so its provider is\n * never an instance of the `SignalProvider` class Mastra Code loaded. `isSignalProvider` would reject\n * a perfectly working provider. Nothing in the lifecycle needs class identity: the lane only calls\n * these methods, so the methods are what is checked.\n */\nfunction isPluginSignalProvider(value: unknown): value is SignalProvider<string> {\n if (isSignalProvider(value)) return true;\n if (!value || typeof value !== 'object') return false;\n const candidate = value as Partial<SignalProvider<string>> & { __registerMastra?: unknown };\n return (\n typeof candidate.id === 'string' &&\n candidate.id.length > 0 &&\n typeof candidate.connect === 'function' &&\n typeof candidate.startPolling === 'function' &&\n typeof candidate.stop === 'function' &&\n typeof candidate.__registerMastra === 'function'\n );\n}\n\n/** A bare array is shorthand for the input lane, the common case. */\nfunction normalizePluginProcessorEntries(entries: MastraCodePluginProcessorEntries): LoadedPluginProcessors {\n const input = Array.isArray(entries) ? entries : (entries.input ?? []);\n const output = Array.isArray(entries) ? [] : (entries.output ?? []);\n if (!Array.isArray(input) || !Array.isArray(output)) {\n throw new Error('Plugin processor lanes must be arrays');\n }\n for (const processor of [...input, ...output]) {\n if (!processor || typeof processor !== 'object' || typeof processor.id !== 'string') {\n throw new Error('Plugin processors must be objects with an id');\n }\n }\n return { input, output };\n}\n\nasync function resolvePluginInstructions(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<string | undefined> {\n if (plugin.instructions === undefined) return undefined;\n const instructions =\n typeof plugin.instructions === 'function' ? await plugin.instructions(context) : plugin.instructions;\n if (typeof instructions !== 'string') {\n throw new Error('Plugin instructions must be a string');\n }\n const trimmed = instructions.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizePluginToolEntries(entries: MastraCodePluginToolEntries): {\n tools: MastraCodePluginTools;\n renderConfigs: Record<string, MastraCodeToolRenderConfig>;\n} {\n const tools: MastraCodePluginTools = {};\n const renderConfigs: Record<string, MastraCodeToolRenderConfig> = {};\n for (const [name, entry] of Object.entries(entries)) {\n if (!isToolEntryObject(entry)) {\n throw new Error(`Plugin tool \"${name}\" must be an object with a tool property`);\n }\n tools[name] = entry.tool;\n if (entry.render) renderConfigs[name] = entry.render;\n }\n return { tools, renderConfigs };\n}\n\nfunction isToolEntryObject(entry: MastraCodePluginToolEntries[string]): entry is MastraCodePluginToolEntries[string] {\n if (!entry || typeof entry !== 'object' || !('tool' in entry)) return false;\n const tool = (entry as { tool?: unknown }).tool;\n return !!tool && typeof tool === 'object' && !Array.isArray(tool);\n}\n\nfunction validatePluginConfigSchema(schema: unknown): MastraCodePluginConfigSchema | undefined {\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return undefined;\n const validated: MastraCodePluginConfigSchema = {};\n for (const [key, option] of Object.entries(schema)) {\n if (!option || typeof option !== 'object' || Array.isArray(option)) continue;\n const record = option as Record<string, unknown>;\n if (record.type !== 'model' && record.type !== 'boolean' && record.type !== 'string') continue;\n validated[key] = {\n type: record.type,\n ...(typeof record.label === 'string' ? { label: record.label } : {}),\n ...(typeof record.description === 'string' ? { description: record.description } : {}),\n ...(typeof record.default === 'string' || typeof record.default === 'boolean' ? { default: record.default } : {}),\n };\n }\n return Object.keys(validated).length > 0 ? validated : undefined;\n}\n\nfunction resolvePluginConfigValues(\n schema: MastraCodePluginConfigSchema | undefined,\n recordValues: Record<string, unknown> | undefined,\n): MastraCodePluginConfigValues {\n const values: MastraCodePluginConfigValues = {};\n if (!schema) return values;\n for (const [key, option] of Object.entries(schema)) {\n const value = recordValues?.[key];\n if (option.type === 'boolean') {\n values[key] = typeof value === 'boolean' ? value : typeof option.default === 'boolean' ? option.default : false;\n continue;\n }\n values[key] = typeof value === 'string' ? value : typeof option.default === 'string' ? option.default : undefined;\n }\n return values;\n}\n\nexport function collectActivePluginTools(plugins: LoadedPlugin[]): MastraCodePluginTools {\n const tools: MastraCodePluginTools = {};\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [name, tool] of Object.entries(plugin.tools)) {\n if (!(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n return tools;\n}\n\nfunction markToolConflicts(plugins: LoadedPlugin[]): LoadedPlugin[] {\n const seen = new Map<string, string>();\n return plugins.map(plugin => {\n if (plugin.status !== 'active') return plugin;\n const conflicts = plugin.toolNames.filter(toolName => seen.has(toolName));\n for (const toolName of plugin.toolNames) {\n if (!seen.has(toolName)) seen.set(toolName, plugin.id);\n }\n return conflicts.length > 0 ? { ...plugin, status: 'conflicted', conflicts } : plugin;\n });\n}\n"],"mappings":";;;;;;;AAkCA,eAAsB,YAAY,SAAsD;CAKtF,MAAM,UAAU,sBAHd,QAAQ,kBAAkB,mBAAmB,KAAK,KAAK,cAAc,UAAU,OAAO,GAAG,cAAc,CAAC,GAExG,QAAQ,mBAAmB,mBAAmB,KAAK,KAAK,cAAc,WAAW,OAAO,GAAG,cAAc,CAAC,CACvC;CACrE,MAAM,SAAyB,CAAC;CAEhC,KAA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CACA,OAAO;AACT;AAEA,SAAgB,yBAAyB,SAAgD;CACvF,MAAM,QAA+B,CAAC;CACtC,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,WAAW,UAAU;EAChC,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,KAAK,GACpD,IAAI,EAAE,QAAQ,QACZ,MAAM,QAAQ;CAGpB;CACA,OAAO;AACT;AAEA,SAAS,kBAAkB,SAAyC;CAClE,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO,QAAQ,KAAI,WAAU;EAC3B,IAAI,OAAO,WAAW,UAAU,OAAO;EACvC,MAAM,YAAY,OAAO,UAAU,QAAO,aAAY,KAAK,IAAI,QAAQ,CAAC;EACxE,KAAK,MAAM,YAAY,OAAO,WAC5B,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG,KAAK,IAAI,UAAU,OAAO,EAAE;EAEvD,OAAO,UAAU,SAAS,IAAI;GAAE,GAAG;GAAQ,QAAQ;GAAc;EAAU,IAAI;CACjF,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"loader.js","names":[],"sources":["../../src/plugins/loader.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { pathToFileURL } from 'node:url';\n\nimport { isSignalProvider } from '@mastra/core/signals';\nimport type { SignalProvider } from '@mastra/core/signals';\n\nimport type {\n MastraCodePlugin,\n MastraCodePluginConfigSchema,\n MastraCodePluginConfigValues,\n MastraCodePluginContext,\n MastraCodePluginProcessorEntries,\n MastraCodePluginRuntime,\n MastraCodePluginSignalProviderEntries,\n MastraCodePluginToolEntries,\n MastraCodePluginTools,\n MastraCodeToolRenderConfig,\n} from '../plugin.js';\nimport { getPluginRoot } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, mergePluginRegistries } from './registry.js';\nimport type { LoadedPlugin, LoadedPluginProcessors, PluginRegistry, ScopedInstalledPluginRecord } from './types.js';\n\nexport type LoadPluginRecordOptions = PluginPathOptions & {\n /** Lazy accessors for Mastra Code's runtime, passed on to plugin field resolvers. */\n runtime?: MastraCodePluginRuntime;\n};\n\nexport type LoadPluginsOptions = LoadPluginRecordOptions & {\n globalRegistry?: PluginRegistry;\n projectRegistry?: PluginRegistry;\n};\n\nexport async function loadPlugins(options: LoadPluginsOptions): Promise<LoadedPlugin[]> {\n const globalRegistry =\n options.globalRegistry ?? loadPluginRegistry(path.join(getPluginRoot('global', options), 'plugins.json'));\n const projectRegistry =\n options.projectRegistry ?? loadPluginRegistry(path.join(getPluginRoot('project', options), 'plugins.json'));\n const records = mergePluginRegistries(globalRegistry, projectRegistry);\n const loaded: LoadedPlugin[] = [];\n\n for (const record of records) {\n if (record.blocked) {\n loaded.push({ ...record, status: 'blocked', tools: {}, toolNames: [] });\n continue;\n }\n if (!record.enabled) {\n loaded.push({ ...record, status: 'inactive', tools: {}, toolNames: [] });\n continue;\n }\n\n loaded.push(await loadPluginRecord(record, options));\n }\n\n return markToolConflicts(loaded);\n}\n\nexport async function loadPluginRecord(\n record: ScopedInstalledPluginRecord,\n options: LoadPluginRecordOptions,\n): Promise<LoadedPlugin> {\n try {\n const entryPath = resolvePluginEntryPath(record, options);\n const plugin = await importPluginModule(entryPath);\n if (plugin.id !== record.id) {\n throw new Error(`Plugin id mismatch: registry has \"${record.id}\" but module exports \"${plugin.id}\"`);\n }\n\n const configSchema = validatePluginConfigSchema(plugin.config);\n const configValues = resolvePluginConfigValues(configSchema, record.config);\n const pluginDir = path.dirname(entryPath);\n const pluginRoot = resolvePluginRoot(record, options);\n const context: MastraCodePluginContext = {\n cwd: options.projectRoot,\n scope: record.scope,\n pluginDir,\n config: configValues,\n // Accessors, not instances: plugins load before the controller and the\n // session exist, so a plugin resolves these when it needs them, not now.\n getController: options.runtime?.getController,\n getActiveSession: options.runtime?.getActiveSession,\n getStorage: options.runtime?.getStorage,\n };\n const { tools, renderConfigs } = await resolvePluginTools(plugin, context);\n const processors = await resolvePluginProcessors(plugin, context);\n const signalProviders = await resolvePluginSignalProviders(plugin, context);\n const instructions = await resolvePluginInstructions(plugin, context);\n\n return {\n ...record,\n name: plugin.name,\n version: plugin.version ?? record.version,\n description: plugin.description,\n instructions,\n status: 'active',\n tools,\n renderConfigs,\n toolNames: Object.keys(tools).sort(),\n processors,\n signalProviders,\n skillPaths: resolveExistingAssetDirs(pluginRoot, 'skills'),\n commandPaths: resolveExistingAssetDirs(pluginRoot, 'commands'),\n configSchema,\n configValues,\n };\n } catch (error) {\n return {\n ...record,\n status: 'load failed',\n error: error instanceof Error ? error.message : String(error),\n tools: {},\n toolNames: [],\n };\n }\n}\n\nexport async function loadPluginFromEntry(entryPath: string): Promise<MastraCodePlugin> {\n return validatePluginExport(await importPluginModule(entryPath));\n}\n\nexport function resolvePluginRoot(record: ScopedInstalledPluginRecord, options: PluginPathOptions): string {\n const scopeRoot = path.resolve(getPluginRoot(record.scope, options));\n const pluginRoot = path.resolve(path.isAbsolute(record.path) ? record.path : path.join(scopeRoot, record.path));\n if (record.source === 'github' && !isInsideDirectory(pluginRoot, scopeRoot)) {\n throw new Error(`Plugin path for \"${record.id}\" must be inside the ${record.scope} plugin directory`);\n }\n return pluginRoot;\n}\n\nexport function resolvePluginEntryPath(record: ScopedInstalledPluginRecord, options: PluginPathOptions): string {\n const pluginRoot = resolvePluginRoot(record, options);\n const entryPath = path.resolve(pluginRoot, record.entry);\n if (!isInsideDirectory(entryPath, pluginRoot)) {\n throw new Error(`Plugin entry for \"${record.id}\" must be inside the plugin directory`);\n }\n return entryPath;\n}\n\nexport function isInsideDirectory(targetPath: string, root: string): boolean {\n const resolvedTarget = path.resolve(targetPath);\n const resolvedRoot = path.resolve(root);\n return resolvedTarget === resolvedRoot || resolvedTarget.startsWith(resolvedRoot + path.sep);\n}\n\nfunction resolveExistingAssetDirs(pluginRoot: string, dirname: 'skills' | 'commands'): string[] {\n const dir = path.join(pluginRoot, dirname);\n try {\n return fs.statSync(dir).isDirectory() ? [dir] : [];\n } catch {\n return [];\n }\n}\n\nasync function importPluginModule(entryPath: string): Promise<MastraCodePlugin> {\n if (path.extname(entryPath) !== '.ts') {\n throw new Error(\n `Unsupported plugin entry extension \"${path.extname(entryPath)}\". V1 plugins must use .ts entries.`,\n );\n }\n\n const url = pathToFileURL(entryPath);\n const contentHash = Buffer.from(await globalThis.crypto.subtle.digest('SHA-1', fs.readFileSync(entryPath))).toString(\n 'hex',\n );\n const stat = fs.statSync(entryPath, { bigint: true });\n url.searchParams.set('contentHash', contentHash);\n url.searchParams.set('mtimeNs', stat.mtimeNs.toString());\n const mod = (await import(url.href)) as { default?: unknown; plugin?: unknown };\n return validatePluginExport(mod.default ?? mod.plugin);\n}\n\nfunction validatePluginExport(value: unknown): MastraCodePlugin {\n if (!value || typeof value !== 'object') {\n throw new Error('Plugin module must export a plugin object as default or named \"plugin\" export');\n }\n\n const plugin = value as MastraCodePlugin;\n if (typeof plugin.id !== 'string' || plugin.id.trim().length === 0) {\n throw new Error('Plugin id must be a non-empty string');\n }\n\n if (plugin.tools !== undefined && typeof plugin.tools !== 'object' && typeof plugin.tools !== 'function') {\n throw new Error('Plugin tools must be an object or function');\n }\n\n if (\n plugin.processors !== undefined &&\n typeof plugin.processors !== 'object' &&\n typeof plugin.processors !== 'function'\n ) {\n throw new Error('Plugin processors must be an array, object, or function');\n }\n\n if (\n plugin.signalProviders !== undefined &&\n !Array.isArray(plugin.signalProviders) &&\n typeof plugin.signalProviders !== 'function'\n ) {\n throw new Error('Plugin signal providers must be an array or function');\n }\n\n return plugin;\n}\n\nasync function resolvePluginTools(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<{ tools: MastraCodePluginTools; renderConfigs: Record<string, MastraCodeToolRenderConfig> }> {\n if (!plugin.tools) return { tools: {}, renderConfigs: {} };\n const entries = typeof plugin.tools === 'function' ? await plugin.tools(context) : plugin.tools;\n if (!entries || typeof entries !== 'object' || Array.isArray(entries)) {\n throw new Error('Plugin tools function must return an object');\n }\n return normalizePluginToolEntries(entries);\n}\n\n/** Mirrors {@link resolvePluginTools}: object-or-function, resolved with the same context. */\nasync function resolvePluginProcessors(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<LoadedPluginProcessors> {\n if (!plugin.processors) return { input: [], output: [] };\n const entries = typeof plugin.processors === 'function' ? await plugin.processors(context) : plugin.processors;\n if (!entries || typeof entries !== 'object') {\n throw new Error('Plugin processors function must return an array or object');\n }\n return normalizePluginProcessorEntries(entries);\n}\n\nasync function resolvePluginSignalProviders(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<MastraCodePluginSignalProviderEntries> {\n if (!plugin.signalProviders) return [];\n const entries =\n typeof plugin.signalProviders === 'function' ? await plugin.signalProviders(context) : plugin.signalProviders;\n if (!Array.isArray(entries)) {\n throw new Error('Plugin signal providers function must return an array');\n }\n for (const [index, provider] of entries.entries()) {\n if (!isPluginSignalProvider(provider)) {\n throw new Error(\n `Plugin signal provider at index ${index} must be a SignalProvider (an object with an id that implements connect, startPolling, stop and __registerMastra)`,\n );\n }\n }\n return entries;\n}\n\n/**\n * Structural, not `instanceof`.\n *\n * A plugin that depends on a published provider package — the motivating case, a plugin wrapping\n * `@mastra/github-signals` — installs that package's own copy of `@mastra/core`, so its provider is\n * never an instance of the `SignalProvider` class Mastra Code loaded. `isSignalProvider` would reject\n * a perfectly working provider. Nothing in the lifecycle needs class identity: the lane only calls\n * these methods, so the methods are what is checked.\n */\nfunction isPluginSignalProvider(value: unknown): value is SignalProvider<string> {\n if (isSignalProvider(value)) return true;\n if (!value || typeof value !== 'object') return false;\n const candidate = value as Partial<SignalProvider<string>> & { __registerMastra?: unknown };\n return (\n typeof candidate.id === 'string' &&\n candidate.id.length > 0 &&\n typeof candidate.connect === 'function' &&\n typeof candidate.startPolling === 'function' &&\n typeof candidate.stop === 'function' &&\n typeof candidate.__registerMastra === 'function'\n );\n}\n\n/** A bare array is shorthand for the input lane, the common case. */\nfunction normalizePluginProcessorEntries(entries: MastraCodePluginProcessorEntries): LoadedPluginProcessors {\n const input = Array.isArray(entries) ? entries : (entries.input ?? []);\n const output = Array.isArray(entries) ? [] : (entries.output ?? []);\n if (!Array.isArray(input) || !Array.isArray(output)) {\n throw new Error('Plugin processor lanes must be arrays');\n }\n for (const processor of [...input, ...output]) {\n if (!processor || typeof processor !== 'object' || typeof processor.id !== 'string') {\n throw new Error('Plugin processors must be objects with an id');\n }\n }\n return { input, output };\n}\n\nasync function resolvePluginInstructions(\n plugin: MastraCodePlugin,\n context: MastraCodePluginContext,\n): Promise<string | undefined> {\n if (plugin.instructions === undefined) return undefined;\n const instructions =\n typeof plugin.instructions === 'function' ? await plugin.instructions(context) : plugin.instructions;\n if (typeof instructions !== 'string') {\n throw new Error('Plugin instructions must be a string');\n }\n const trimmed = instructions.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n}\n\nfunction normalizePluginToolEntries(entries: MastraCodePluginToolEntries): {\n tools: MastraCodePluginTools;\n renderConfigs: Record<string, MastraCodeToolRenderConfig>;\n} {\n const tools: MastraCodePluginTools = {};\n const renderConfigs: Record<string, MastraCodeToolRenderConfig> = {};\n for (const [name, entry] of Object.entries(entries)) {\n if (!isToolEntryObject(entry)) {\n throw new Error(`Plugin tool \"${name}\" must be an object with a tool property`);\n }\n tools[name] = entry.tool;\n if (entry.render) renderConfigs[name] = entry.render;\n }\n return { tools, renderConfigs };\n}\n\nfunction isToolEntryObject(entry: MastraCodePluginToolEntries[string]): entry is MastraCodePluginToolEntries[string] {\n if (!entry || typeof entry !== 'object' || !('tool' in entry)) return false;\n const tool = (entry as { tool?: unknown }).tool;\n return !!tool && typeof tool === 'object' && !Array.isArray(tool);\n}\n\nfunction validatePluginConfigSchema(schema: unknown): MastraCodePluginConfigSchema | undefined {\n if (!schema || typeof schema !== 'object' || Array.isArray(schema)) return undefined;\n const validated: MastraCodePluginConfigSchema = {};\n for (const [key, option] of Object.entries(schema)) {\n if (!option || typeof option !== 'object' || Array.isArray(option)) continue;\n const record = option as Record<string, unknown>;\n if (record.type !== 'model' && record.type !== 'boolean' && record.type !== 'string') continue;\n validated[key] = {\n type: record.type,\n ...(typeof record.label === 'string' ? { label: record.label } : {}),\n ...(typeof record.description === 'string' ? { description: record.description } : {}),\n ...(typeof record.default === 'string' || typeof record.default === 'boolean' ? { default: record.default } : {}),\n };\n }\n return Object.keys(validated).length > 0 ? validated : undefined;\n}\n\nfunction resolvePluginConfigValues(\n schema: MastraCodePluginConfigSchema | undefined,\n recordValues: Record<string, unknown> | undefined,\n): MastraCodePluginConfigValues {\n const values: MastraCodePluginConfigValues = {};\n if (!schema) return values;\n for (const [key, option] of Object.entries(schema)) {\n const value = recordValues?.[key];\n if (option.type === 'boolean') {\n values[key] = typeof value === 'boolean' ? value : typeof option.default === 'boolean' ? option.default : false;\n continue;\n }\n values[key] = typeof value === 'string' ? value : typeof option.default === 'string' ? option.default : undefined;\n }\n return values;\n}\n\nexport function collectActivePluginTools(plugins: LoadedPlugin[]): MastraCodePluginTools {\n const tools: MastraCodePluginTools = {};\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [name, tool] of Object.entries(plugin.tools)) {\n if (!(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n return tools;\n}\n\nfunction markToolConflicts(plugins: LoadedPlugin[]): LoadedPlugin[] {\n const seen = new Map<string, string>();\n return plugins.map(plugin => {\n if (plugin.status !== 'active') return plugin;\n const conflicts = plugin.toolNames.filter(toolName => seen.has(toolName));\n for (const toolName of plugin.toolNames) {\n if (!seen.has(toolName)) seen.set(toolName, plugin.id);\n }\n return conflicts.length > 0 ? { ...plugin, status: 'conflicted', conflicts } : plugin;\n });\n}\n"],"mappings":";;;;;;;AAkCA,eAAsB,YAAY,SAAsD;CACtF,MAAM,iBACJ,QAAQ,kBAAkB,mBAAmB,KAAK,KAAK,cAAc,UAAU,OAAO,GAAG,cAAc,CAAC;CAC1G,MAAM,kBACJ,QAAQ,mBAAmB,mBAAmB,KAAK,KAAK,cAAc,WAAW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GAC1G;EACF;EACA,OAAO,OAAO,OAAO,UAAU,WAAW,QAAQ,OAAO,OAAO,YAAY,WAAW,OAAO,UAAU,KAAA;CAC1G;CACA,OAAO;AACT;AAEA,SAAgB,yBAAyB,SAAgD;CACvF,MAAM,QAA+B,CAAC;CACtC,KAAK,MAAM,UAAU,SAAS;EAC5B,IAAI,OAAO,WAAW,UAAU;EAChC,KAAK,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,OAAO,KAAK,GACpD,IAAI,EAAE,QAAQ,QACZ,MAAM,QAAQ;CAGpB;CACA,OAAO;AACT;AAEA,SAAS,kBAAkB,SAAyC;CAClE,MAAM,uBAAO,IAAI,IAAoB;CACrC,OAAO,QAAQ,KAAI,WAAU;EAC3B,IAAI,OAAO,WAAW,UAAU,OAAO;EACvC,MAAM,YAAY,OAAO,UAAU,QAAO,aAAY,KAAK,IAAI,QAAQ,CAAC;EACxE,KAAK,MAAM,YAAY,OAAO,WAC5B,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG,KAAK,IAAI,UAAU,OAAO,EAAE;EAEvD,OAAO,UAAU,SAAS,IAAI;GAAE,GAAG;GAAQ,QAAQ;GAAc;EAAU,IAAI;CACjF,CAAC;AACH"}
|
package/dist/plugins/manager.js
CHANGED
|
@@ -441,7 +441,8 @@ var PluginManager = class {
|
|
|
441
441
|
savePluginRegistry(paths.registryPath, removePluginRecord(registry, pluginId));
|
|
442
442
|
if (record.source === "github") {
|
|
443
443
|
const checkoutPath = path.resolve(path.isAbsolute(record.path) ? record.path : path.join(paths.root, record.path));
|
|
444
|
-
|
|
444
|
+
const githubSourcesPath = path.resolve(paths.sourcesPath, "github");
|
|
445
|
+
if (isInsideDirectory(checkoutPath, githubSourcesPath)) fs.rmSync(checkoutPath, {
|
|
445
446
|
recursive: true,
|
|
446
447
|
force: true
|
|
447
448
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"manager.js","names":[],"sources":["../../src/plugins/manager.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { SignalProvider } from '@mastra/core/signals';\nimport { execa } from 'execa';\n\nimport type { MastraCodePluginConfigValue, MastraCodePluginRuntime } from '../plugin.js';\nimport { getEntryPackageRoot, installPluginDependenciesForEntry } from './dependencies.js';\nimport { discoverLocalPlugins, installGithubPlugin, installLocalPlugin, NON_INTERACTIVE_GIT_ENV } from './install.js';\nimport type { InstallPluginOptions } from './install.js';\nimport { collectActivePluginTools, isInsideDirectory, loadPlugins, resolvePluginEntryPath } from './loader.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\nimport { getPluginScopePaths } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, removePluginRecord, savePluginRegistry, setPluginRecord } from './registry.js';\nimport type { LoadedPlugin, PluginContribution, PluginProcessorEntries, PluginScope } from './types.js';\n\nconst GITHUB_PLUGIN_POLL_INTERVAL_MS = 60_000;\n\nfunction gitExecOptions(cwd: string) {\n return { cwd, env: NON_INTERACTIVE_GIT_ENV };\n}\n\nfunction getEntryVersion(entryPath: string): string {\n const stat = fs.statSync(entryPath, { bigint: true });\n return `${stat.mtimeNs}:${stat.size}`;\n}\n\ntype PluginManagerOptions = PluginPathOptions & {\n githubCliPath?: string;\n /**\n * Lazy accessors for Mastra Code's runtime, handed to plugin field resolvers on\n * every load and reload.\n */\n runtime?: MastraCodePluginRuntime;\n};\n\nexport class PluginManager {\n private loadedPlugins: LoadedPlugin[] = [];\n private readonly pluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly rawPluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly toolRenderConfigs = new Map<string, NonNullable<LoadedPlugin['renderConfigs']>[string]>();\n private readonly watchedLocalEntries = new Set<string>();\n private readonly localEntryVersions = new Map<string, string>();\n /** Last known git HEAD per GitHub checkout, kept current by the poller. */\n private readonly githubCheckoutHeads = new Map<string, string>();\n private githubPollTimer: ReturnType<typeof setInterval> | undefined;\n private githubPollInFlight: Promise<boolean> | undefined;\n private reloadInFlight: Promise<LoadedPlugin[]> | undefined;\n private readonly reloadListeners = new Set<(plugins: LoadedPlugin[]) => void | Promise<void>>();\n private readonly githubUpdateListeners = new Set<(pluginNames: string[]) => void | Promise<void>>();\n private runtime: MastraCodePluginRuntime | undefined;\n\n constructor(private readonly options: PluginManagerOptions) {\n this.runtime = options.runtime;\n }\n\n /**\n * Publish (or replace) the runtime accessors handed to plugin field resolvers.\n * Takes effect on the next load or reload. `createMastraCode` calls this for\n * every manager it uses — including an injected one — so a manager constructed\n * without a runtime still exposes `getController`/`getActiveSession` to plugins.\n * A manager shared across controllers sees the most recent controller's accessors.\n */\n setRuntime(runtime: MastraCodePluginRuntime): void {\n this.runtime = runtime;\n }\n\n onReload(listener: (plugins: LoadedPlugin[]) => void | Promise<void>): () => void {\n this.reloadListeners.add(listener);\n return () => this.reloadListeners.delete(listener);\n }\n\n /** Notified with the display names of GitHub plugins that were updated by the background poll. */\n onGithubPluginsUpdated(listener: (pluginNames: string[]) => void | Promise<void>): () => void {\n this.githubUpdateListeners.add(listener);\n return () => this.githubUpdateListeners.delete(listener);\n }\n\n async reload(): Promise<LoadedPlugin[]> {\n if (this.reloadInFlight) return this.reloadInFlight;\n\n this.reloadInFlight = (async () => {\n this.loadedPlugins = await loadPlugins({ ...this.options, runtime: this.runtime });\n await this.stampLoadedPlugins(this.loadedPlugins);\n this.updateLocalEntryWatchers(this.loadedPlugins);\n this.updateGithubPoller(this.loadedPlugins);\n this.updatePluginRenderConfigs(this.loadedPlugins);\n this.updatePluginTools(collectActivePluginTools(this.loadedPlugins));\n await this.notifyReloadListeners(this.loadedPlugins);\n return this.loadedPlugins;\n })().finally(() => {\n this.reloadInFlight = undefined;\n });\n\n return this.reloadInFlight;\n }\n\n async listPlugins(): Promise<LoadedPlugin[]> {\n if (this.loadedPlugins.length === 0) {\n await this.reload();\n }\n return this.loadedPlugins;\n }\n\n getLoadedPlugins(): LoadedPlugin[] {\n return this.loadedPlugins;\n }\n\n getPluginTools() {\n return this.pluginTools;\n }\n\n getToolRenderConfig(toolName: string) {\n return this.toolRenderConfigs.get(toolName);\n }\n\n getPluginSkillPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : []));\n }\n\n getPluginCommandPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.commandPaths ?? []) : []));\n }\n\n getPluginInstructions(): string[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n );\n }\n\n /**\n * Processors contributed by active plugins, tagged with the plugin that owns\n * each one. Reads already-resolved state — no filesystem access — because the\n * agent's processor lanes call this before every request.\n */\n getPluginProcessors(): PluginProcessorEntries {\n return {\n input: this.collectActive(plugin => plugin.processors?.input ?? []),\n output: this.collectActive(plugin => plugin.processors?.output ?? []),\n };\n }\n\n /** Signal providers contributed by active plugins, tagged with their owning plugin. */\n getPluginSignalProviders(): PluginContribution<SignalProvider<string>>[] {\n return this.collectActive(plugin => plugin.signalProviders ?? []);\n }\n\n private collectActive<TValue>(select: (plugin: LoadedPlugin) => TValue[]): PluginContribution<TValue>[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active'\n ? select(plugin).map(value => ({ pluginId: plugin.id, versionStamp: plugin.versionStamp ?? '', value }))\n : [],\n );\n }\n\n private async notifyReloadListeners(plugins: LoadedPlugin[]): Promise<void> {\n await Promise.all([...this.reloadListeners].map(listener => Promise.resolve(listener(plugins))));\n }\n\n /**\n * Stamps each plugin with a value that changes when its contributions should\n * be rebuilt. Runs on every reload, so it stays off the network: GitHub heads\n * come from the cache the poller keeps current and cost one `git rev-parse`\n * per checkout the first time it is seen.\n */\n private async stampLoadedPlugins(plugins: LoadedPlugin[]): Promise<void> {\n for (const plugin of plugins) {\n plugin.versionStamp = [\n plugin.status,\n await this.readSourceStamp(plugin),\n JSON.stringify(plugin.configValues ?? {}),\n ].join('|');\n }\n }\n\n private async readSourceStamp(plugin: LoadedPlugin): Promise<string> {\n try {\n if (plugin.source === 'github') {\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n let head = this.githubCheckoutHeads.get(checkoutPath);\n if (head === undefined) {\n head = await this.readGitHead(checkoutPath);\n this.githubCheckoutHeads.set(checkoutPath, head);\n }\n return head;\n }\n return getEntryVersion(resolvePluginEntryPath(plugin, this.options));\n } catch {\n // A plugin that failed to load has no readable source. Its stamp is then\n // status + config, which is enough to notice when it starts working.\n return '';\n }\n }\n\n private updatePluginRenderConfigs(plugins: LoadedPlugin[]): void {\n this.toolRenderConfigs.clear();\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [toolName, renderConfig] of Object.entries(plugin.renderConfigs ?? {})) {\n if (!this.toolRenderConfigs.has(toolName)) {\n this.toolRenderConfigs.set(toolName, renderConfig);\n }\n }\n }\n }\n\n private updatePluginTools(nextTools: ReturnType<typeof collectActivePluginTools>): void {\n for (const name of Object.keys(this.rawPluginTools)) {\n if (!(name in nextTools)) {\n delete this.rawPluginTools[name];\n delete this.pluginTools[name];\n }\n }\n\n for (const [name, tool] of Object.entries(nextTools)) {\n this.rawPluginTools[name] = tool;\n if (!this.pluginTools[name]) {\n this.pluginTools[name] = this.createLiveToolProxy(name);\n }\n this.syncLiveToolProxy(name, tool);\n }\n }\n\n private createLiveToolProxy(toolName: string) {\n return {\n execute: async (...args: any[]) => {\n await this.reloadChangedLocalPlugins();\n const latestTool = this.rawPluginTools[toolName];\n if (!latestTool?.execute) {\n throw new Error(`Plugin tool \"${toolName}\" is no longer available`);\n }\n return (latestTool.execute as (...args: any[]) => unknown)(...args);\n },\n } as LoadedPlugin['tools'][string];\n }\n\n private syncLiveToolProxy(toolName: string, tool: LoadedPlugin['tools'][string]): void {\n const proxy = this.pluginTools[toolName];\n if (!proxy) return;\n const mutableProxy = proxy as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableProxy)) {\n delete mutableProxy[key];\n }\n Object.assign(proxy, tool);\n proxy.execute = this.createLiveToolProxy(toolName).execute;\n }\n\n private async reloadChangedLocalPlugins(): Promise<void> {\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n const entryPath = resolvePluginEntryPath(plugin, this.options);\n const currentVersion = getEntryVersion(entryPath);\n if (this.localEntryVersions.get(entryPath) !== currentVersion) {\n await this.reload();\n return;\n }\n }\n }\n\n private updateLocalEntryWatchers(plugins: LoadedPlugin[]): void {\n const nextEntries = new Set<string>();\n for (const plugin of plugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n let entryPath: string;\n let entryVersion: string;\n try {\n entryPath = resolvePluginEntryPath(plugin, this.options);\n entryVersion = getEntryVersion(entryPath);\n } catch {\n continue;\n }\n nextEntries.add(entryPath);\n this.localEntryVersions.set(entryPath, entryVersion);\n if (this.watchedLocalEntries.has(entryPath)) continue;\n\n const watcher = fs.watchFile(entryPath, { interval: 500 }, (current, previous) => {\n if (current.mtimeMs === previous.mtimeMs) return;\n void this.reload().catch(() => undefined);\n });\n watcher.unref?.();\n this.watchedLocalEntries.add(entryPath);\n }\n\n for (const entryPath of this.watchedLocalEntries) {\n if (nextEntries.has(entryPath)) continue;\n fs.unwatchFile(entryPath);\n this.watchedLocalEntries.delete(entryPath);\n this.localEntryVersions.delete(entryPath);\n }\n }\n\n private updateGithubPoller(plugins: LoadedPlugin[]): void {\n const hasGithubPlugin = plugins.some(\n plugin => plugin.source === 'github' && plugin.status !== 'inactive' && plugin.status !== 'blocked',\n );\n if (hasGithubPlugin && !this.githubPollTimer) {\n this.githubPollTimer = setInterval(() => {\n void this.pollGithubSourcesForUpdates().catch(() => undefined);\n }, GITHUB_PLUGIN_POLL_INTERVAL_MS);\n this.githubPollTimer.unref?.();\n }\n if (!hasGithubPlugin && this.githubPollTimer) {\n clearInterval(this.githubPollTimer);\n this.githubPollTimer = undefined;\n }\n }\n\n async pollGithubSourcesForUpdates(): Promise<boolean> {\n if (this.githubPollInFlight) return this.githubPollInFlight;\n this.githubPollInFlight = this.pollGithubSourcesForUpdatesOnce().finally(() => {\n this.githubPollInFlight = undefined;\n });\n return this.githubPollInFlight;\n }\n\n private async pollGithubSourcesForUpdatesOnce(): Promise<boolean> {\n const changedCheckouts = new Set<string>();\n const seen = new Set<string>();\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'github' || plugin.status === 'inactive' || plugin.status === 'blocked') continue;\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n if (seen.has(checkoutPath) || !fs.existsSync(path.join(checkoutPath, '.git'))) continue;\n seen.add(checkoutPath);\n\n const before = await this.readGitHead(checkoutPath);\n const checkoutChanged = await this.refreshGithubCheckout(plugin, checkoutPath, before);\n const after = await this.readGitHead(checkoutPath);\n // Feed the cache before reloading: the stamp is computed during reload and\n // has to see the new head, or a real update would look unchanged.\n this.githubCheckoutHeads.set(checkoutPath, after);\n if (checkoutChanged || before !== after) changedCheckouts.add(checkoutPath);\n }\n\n if (changedCheckouts.size === 0) return false;\n\n await this.reload();\n // Derive names from the reloaded state so a manifest display-name change reports the new name.\n // Multiple plugins can share one checkout — report every plugin whose source changed.\n const updatedPluginNames = this.loadedPlugins\n .filter(\n plugin =>\n plugin.source === 'github' &&\n plugin.status !== 'inactive' &&\n plugin.status !== 'blocked' &&\n changedCheckouts.has(this.resolvePluginSourcePath(plugin)),\n )\n .map(plugin => plugin.name ?? plugin.id);\n await this.notifyGithubUpdateListeners(updatedPluginNames);\n return true;\n }\n\n private async notifyGithubUpdateListeners(pluginNames: string[]): Promise<void> {\n await Promise.all([...this.githubUpdateListeners].map(listener => Promise.resolve(listener(pluginNames))));\n }\n\n private async refreshGithubCheckout(\n plugin: LoadedPlugin,\n checkoutPath: string,\n currentHead: string,\n ): Promise<boolean> {\n await execa('git', ['fetch', 'origin'], gitExecOptions(checkoutPath));\n const upstream = await this.resolveGitUpstream(checkoutPath, plugin.ref);\n if (!upstream) return false;\n const [localOnly, remoteOnly] = await this.readGitAheadBehind(checkoutPath, upstream);\n const hasLocalChanges = await this.hasGitWorkingTreeChanges(checkoutPath);\n\n if (localOnly > 0 || hasLocalChanges) {\n await this.backupGitCheckout(checkoutPath, currentHead, hasLocalChanges);\n }\n\n if (remoteOnly > 0 || localOnly > 0 || hasLocalChanges) {\n await execa('git', ['reset', '--hard', upstream], gitExecOptions(checkoutPath));\n try {\n await installPluginDependenciesForEntry(checkoutPath, plugin.entry);\n ensureMastraCodePackageLink(getEntryPackageRoot(checkoutPath, plugin.entry));\n } catch (error) {\n await execa('git', ['reset', '--hard', currentHead], gitExecOptions(checkoutPath));\n throw error;\n }\n return true;\n }\n\n return false;\n }\n\n private async backupGitCheckout(\n checkoutPath: string,\n currentHead: string,\n includeWorkingTree: boolean,\n ): Promise<void> {\n const backupBranch = this.createGitBackupBranchName(currentHead);\n\n if (includeWorkingTree) {\n const currentBranch = await this.readGitCurrentBranch(checkoutPath);\n await execa('git', ['switch', '-c', backupBranch], gitExecOptions(checkoutPath));\n await execa('git', ['add', '-A'], gitExecOptions(checkoutPath));\n const hasStagedChanges = await this.hasGitStagedChanges(checkoutPath);\n if (hasStagedChanges) {\n await execa(\n 'git',\n [\n '-c',\n 'user.name=Mastra Code',\n '-c',\n 'user.email=noreply@mastra.ai',\n 'commit',\n '-m',\n 'chore: backup local plugin checkout changes',\n ],\n gitExecOptions(checkoutPath),\n );\n }\n await this.restoreGitCheckout(checkoutPath, currentBranch, currentHead);\n return;\n }\n\n await execa('git', ['branch', backupBranch, 'HEAD'], gitExecOptions(checkoutPath));\n }\n\n private async resolveGitUpstream(cwd: string, installedRef?: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\n 'git',\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],\n gitExecOptions(cwd),\n );\n return stdout.trim();\n } catch {\n return installedRef ? undefined : 'origin/main';\n }\n }\n\n private async readGitAheadBehind(cwd: string, upstream: string): Promise<[number, number]> {\n const { stdout } = await execa(\n 'git',\n ['rev-list', '--left-right', '--count', `HEAD...${upstream}`],\n gitExecOptions(cwd),\n );\n const [ahead = '0', behind = '0'] = stdout.trim().split(/\\s+/);\n return [Number(ahead) || 0, Number(behind) || 0];\n }\n\n private async hasGitWorkingTreeChanges(cwd: string): Promise<boolean> {\n const { stdout } = await execa('git', ['status', '--porcelain'], gitExecOptions(cwd));\n return stdout.trim().length > 0;\n }\n\n private async hasGitStagedChanges(cwd: string): Promise<boolean> {\n try {\n await execa('git', ['diff', '--cached', '--quiet'], gitExecOptions(cwd));\n return false;\n } catch {\n return true;\n }\n }\n\n private async restoreGitCheckout(cwd: string, branch: string | undefined, fallbackHead: string): Promise<void> {\n if (branch) {\n await execa('git', ['switch', branch], gitExecOptions(cwd));\n return;\n }\n await execa('git', ['checkout', fallbackHead], gitExecOptions(cwd));\n }\n\n private async readGitCurrentBranch(cwd: string): Promise<string | undefined> {\n const { stdout } = await execa('git', ['branch', '--show-current'], gitExecOptions(cwd));\n const branch = stdout.trim();\n return branch.length > 0 ? branch : undefined;\n }\n\n private createGitBackupBranchName(currentHead: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return `mastracode/plugin-backup/${timestamp}-${currentHead.slice(0, 8)}`;\n }\n\n private resolvePluginSourcePath(plugin: LoadedPlugin): string {\n const paths = getPluginScopePaths(plugin.scope, this.options);\n // Normalized so cache keys derived here match the `path.resolve`-normalized\n // key that `uninstall` deletes with.\n return path.resolve(path.isAbsolute(plugin.path) ? plugin.path : path.join(paths.root, plugin.path));\n }\n\n private async readGitHead(cwd: string): Promise<string> {\n const { stdout } = await execa('git', ['rev-parse', 'HEAD'], gitExecOptions(cwd));\n return stdout.trim();\n }\n\n discoverLocal(searchRoot = '.'): ReturnType<typeof discoverLocalPlugins> {\n return discoverLocalPlugins(searchRoot, this.options);\n }\n\n async installLocal(\n localPath: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry'> = {},\n ): Promise<string> {\n const id = await installLocalPlugin(localPath, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async installGithub(\n url: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry' | 'ref' | 'onOutput' | 'signal'> = {},\n ): Promise<string> {\n const id = await installGithubPlugin(url, scope, { ...this.options, ...options });\n // Installing over an existing checkout replaces it at the same path, so the\n // cached head would make a genuinely different commit stamp as unchanged and\n // leave the previous signal providers running.\n this.githubCheckoutHeads.clear();\n await this.reload();\n return id;\n }\n\n async setEnabled(pluginId: string, scope: PluginScope, enabled: boolean): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, { ...record, enabled }));\n await this.reload();\n }\n\n async setConfigValue(\n pluginId: string,\n scope: PluginScope,\n key: string,\n value: MastraCodePluginConfigValue,\n ): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n const config = { ...(record.config ?? {}) };\n if (value === undefined || value === '') {\n delete config[key];\n } else {\n config[key] = value;\n }\n const nextRecord = { ...record, config: Object.keys(config).length > 0 ? config : undefined };\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, nextRecord));\n await this.reload();\n }\n\n async uninstall(pluginId: string, scope: PluginScope): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n\n savePluginRegistry(paths.registryPath, removePluginRecord(registry, pluginId));\n if (record.source === 'github') {\n const checkoutPath = path.resolve(\n path.isAbsolute(record.path) ? record.path : path.join(paths.root, record.path),\n );\n const githubSourcesPath = path.resolve(paths.sourcesPath, 'github');\n if (isInsideDirectory(checkoutPath, githubSourcesPath)) {\n fs.rmSync(checkoutPath, { recursive: true, force: true });\n }\n this.githubCheckoutHeads.delete(checkoutPath);\n }\n await this.reload();\n }\n}\n"],"mappings":";;;;;;;;;;AAiBA,MAAM,iCAAiC;AAEvC,SAAS,eAAe,KAAa;CACnC,OAAO;EAAE;EAAK,KAAK;CAAwB;AAC7C;AAEA,SAAS,gBAAgB,WAA2B;CAClD,MAAM,OAAO,GAAG,SAAS,WAAW,EAAE,QAAQ,KAAK,CAAC;CACpD,OAAO,GAAG,KAAK,QAAQ,GAAG,KAAK;AACjC;AAWA,IAAa,gBAAb,MAA2B;CAgBI;CAf7B,gBAAwC,CAAC;CACzC,cAA4E,CAAC;CAC7E,iBAA+E,CAAC;CAChF,oCAAqC,IAAI,IAAgE;CACzG,sCAAuC,IAAI,IAAY;CACvD,qCAAsC,IAAI,IAAoB;;CAE9D,sCAAuC,IAAI,IAAoB;CAC/D;CACA;CACA;CACA,kCAAmC,IAAI,IAAuD;CAC9F,wCAAyC,IAAI,IAAqD;CAClG;CAEA,YAAY,SAAgD;EAA/B,KAAA,UAAA;EAC3B,KAAK,UAAU,QAAQ;CACzB;;;;;;;;CASA,WAAW,SAAwC;EACjD,KAAK,UAAU;CACjB;CAEA,SAAS,UAAyE;EAChF,KAAK,gBAAgB,IAAI,QAAQ;EACjC,aAAa,KAAK,gBAAgB,OAAO,QAAQ;CACnD;;CAGA,uBAAuB,UAAuE;EAC5F,KAAK,sBAAsB,IAAI,QAAQ;EACvC,aAAa,KAAK,sBAAsB,OAAO,QAAQ;CACzD;CAEA,MAAM,SAAkC;EACtC,IAAI,KAAK,gBAAgB,OAAO,KAAK;EAErC,KAAK,kBAAkB,YAAY;GACjC,KAAK,gBAAgB,MAAM,YAAY;IAAE,GAAG,KAAK;IAAS,SAAS,KAAK;GAAQ,CAAC;GACjF,MAAM,KAAK,mBAAmB,KAAK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,wBAAwB,MAAM,OAAO;EAE3E,MAAM,SAAS,EAAE,GAAI,OAAO,UAAU,CAAC,EAAG;EAC1C,IAAI,UAAU,KAAA,KAAa,UAAU,IACnC,OAAO,OAAO;OAEd,OAAO,OAAO;EAEhB,MAAM,aAAa;GAAE,GAAG;GAAQ,QAAQ,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS,KAAA;EAAU;EAC5F,mBAAmB,MAAM,cAAc,gBAAgB,UAAU,UAAU,UAAU,CAAC;EACtF,MAAM,KAAK,OAAO;CACpB;CAEA,MAAM,UAAU,UAAkB,OAAmC;EACnE,MAAM,QAAQ,oBAAoB,OAAO,KAAK,OAAO;EACrD,MAAM,WAAW,mBAAmB,MAAM,YAAY;EACtD,MAAM,SAAS,SAAS,QAAQ;EAChC,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,WAAW,SAAS,wBAAwB,MAAM,OAAO;EAG3E,mBAAmB,MAAM,cAAc,mBAAmB,UAAU,QAAQ,CAAC;EAC7E,IAAI,OAAO,WAAW,UAAU;GAC9B,MAAM,eAAe,KAAK,QACxB,KAAK,WAAW,OAAO,IAAI,IAAI,OAAO,OAAO,KAAK,KAAK,MAAM,MAAM,OAAO,IAAI,CAChF;GAEA,IAAI,kBAAkB,cADI,KAAK,QAAQ,MAAM,aAAa,QACN,CAAC,GACnD,GAAG,OAAO,cAAc;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GAE1D,KAAK,oBAAoB,OAAO,YAAY;EAC9C;EACA,MAAM,KAAK,OAAO;CACpB;AACF"}
|
|
1
|
+
{"version":3,"file":"manager.js","names":[],"sources":["../../src/plugins/manager.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { SignalProvider } from '@mastra/core/signals';\nimport { execa } from 'execa';\n\nimport type { MastraCodePluginConfigValue, MastraCodePluginRuntime } from '../plugin.js';\nimport { getEntryPackageRoot, installPluginDependenciesForEntry } from './dependencies.js';\nimport { discoverLocalPlugins, installGithubPlugin, installLocalPlugin, NON_INTERACTIVE_GIT_ENV } from './install.js';\nimport type { InstallPluginOptions } from './install.js';\nimport { collectActivePluginTools, isInsideDirectory, loadPlugins, resolvePluginEntryPath } from './loader.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\nimport { getPluginScopePaths } from './paths.js';\nimport type { PluginPathOptions } from './paths.js';\nimport { loadPluginRegistry, removePluginRecord, savePluginRegistry, setPluginRecord } from './registry.js';\nimport type { LoadedPlugin, PluginContribution, PluginProcessorEntries, PluginScope } from './types.js';\n\nconst GITHUB_PLUGIN_POLL_INTERVAL_MS = 60_000;\n\nfunction gitExecOptions(cwd: string) {\n return { cwd, env: NON_INTERACTIVE_GIT_ENV };\n}\n\nfunction getEntryVersion(entryPath: string): string {\n const stat = fs.statSync(entryPath, { bigint: true });\n return `${stat.mtimeNs}:${stat.size}`;\n}\n\ntype PluginManagerOptions = PluginPathOptions & {\n githubCliPath?: string;\n /**\n * Lazy accessors for Mastra Code's runtime, handed to plugin field resolvers on\n * every load and reload.\n */\n runtime?: MastraCodePluginRuntime;\n};\n\nexport class PluginManager {\n private loadedPlugins: LoadedPlugin[] = [];\n private readonly pluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly rawPluginTools: ReturnType<typeof collectActivePluginTools> = {};\n private readonly toolRenderConfigs = new Map<string, NonNullable<LoadedPlugin['renderConfigs']>[string]>();\n private readonly watchedLocalEntries = new Set<string>();\n private readonly localEntryVersions = new Map<string, string>();\n /** Last known git HEAD per GitHub checkout, kept current by the poller. */\n private readonly githubCheckoutHeads = new Map<string, string>();\n private githubPollTimer: ReturnType<typeof setInterval> | undefined;\n private githubPollInFlight: Promise<boolean> | undefined;\n private reloadInFlight: Promise<LoadedPlugin[]> | undefined;\n private readonly reloadListeners = new Set<(plugins: LoadedPlugin[]) => void | Promise<void>>();\n private readonly githubUpdateListeners = new Set<(pluginNames: string[]) => void | Promise<void>>();\n private runtime: MastraCodePluginRuntime | undefined;\n\n constructor(private readonly options: PluginManagerOptions) {\n this.runtime = options.runtime;\n }\n\n /**\n * Publish (or replace) the runtime accessors handed to plugin field resolvers.\n * Takes effect on the next load or reload. `createMastraCode` calls this for\n * every manager it uses — including an injected one — so a manager constructed\n * without a runtime still exposes `getController`/`getActiveSession` to plugins.\n * A manager shared across controllers sees the most recent controller's accessors.\n */\n setRuntime(runtime: MastraCodePluginRuntime): void {\n this.runtime = runtime;\n }\n\n onReload(listener: (plugins: LoadedPlugin[]) => void | Promise<void>): () => void {\n this.reloadListeners.add(listener);\n return () => this.reloadListeners.delete(listener);\n }\n\n /** Notified with the display names of GitHub plugins that were updated by the background poll. */\n onGithubPluginsUpdated(listener: (pluginNames: string[]) => void | Promise<void>): () => void {\n this.githubUpdateListeners.add(listener);\n return () => this.githubUpdateListeners.delete(listener);\n }\n\n async reload(): Promise<LoadedPlugin[]> {\n if (this.reloadInFlight) return this.reloadInFlight;\n\n this.reloadInFlight = (async () => {\n this.loadedPlugins = await loadPlugins({ ...this.options, runtime: this.runtime });\n await this.stampLoadedPlugins(this.loadedPlugins);\n this.updateLocalEntryWatchers(this.loadedPlugins);\n this.updateGithubPoller(this.loadedPlugins);\n this.updatePluginRenderConfigs(this.loadedPlugins);\n this.updatePluginTools(collectActivePluginTools(this.loadedPlugins));\n await this.notifyReloadListeners(this.loadedPlugins);\n return this.loadedPlugins;\n })().finally(() => {\n this.reloadInFlight = undefined;\n });\n\n return this.reloadInFlight;\n }\n\n async listPlugins(): Promise<LoadedPlugin[]> {\n if (this.loadedPlugins.length === 0) {\n await this.reload();\n }\n return this.loadedPlugins;\n }\n\n getLoadedPlugins(): LoadedPlugin[] {\n return this.loadedPlugins;\n }\n\n getPluginTools() {\n return this.pluginTools;\n }\n\n getToolRenderConfig(toolName: string) {\n return this.toolRenderConfigs.get(toolName);\n }\n\n getPluginSkillPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.skillPaths ?? []) : []));\n }\n\n getPluginCommandPaths(): string[] {\n return this.loadedPlugins.flatMap(plugin => (plugin.status === 'active' ? (plugin.commandPaths ?? []) : []));\n }\n\n getPluginInstructions(): string[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active' && plugin.instructions ? [plugin.instructions] : [],\n );\n }\n\n /**\n * Processors contributed by active plugins, tagged with the plugin that owns\n * each one. Reads already-resolved state — no filesystem access — because the\n * agent's processor lanes call this before every request.\n */\n getPluginProcessors(): PluginProcessorEntries {\n return {\n input: this.collectActive(plugin => plugin.processors?.input ?? []),\n output: this.collectActive(plugin => plugin.processors?.output ?? []),\n };\n }\n\n /** Signal providers contributed by active plugins, tagged with their owning plugin. */\n getPluginSignalProviders(): PluginContribution<SignalProvider<string>>[] {\n return this.collectActive(plugin => plugin.signalProviders ?? []);\n }\n\n private collectActive<TValue>(select: (plugin: LoadedPlugin) => TValue[]): PluginContribution<TValue>[] {\n return this.loadedPlugins.flatMap(plugin =>\n plugin.status === 'active'\n ? select(plugin).map(value => ({ pluginId: plugin.id, versionStamp: plugin.versionStamp ?? '', value }))\n : [],\n );\n }\n\n private async notifyReloadListeners(plugins: LoadedPlugin[]): Promise<void> {\n await Promise.all([...this.reloadListeners].map(listener => Promise.resolve(listener(plugins))));\n }\n\n /**\n * Stamps each plugin with a value that changes when its contributions should\n * be rebuilt. Runs on every reload, so it stays off the network: GitHub heads\n * come from the cache the poller keeps current and cost one `git rev-parse`\n * per checkout the first time it is seen.\n */\n private async stampLoadedPlugins(plugins: LoadedPlugin[]): Promise<void> {\n for (const plugin of plugins) {\n plugin.versionStamp = [\n plugin.status,\n await this.readSourceStamp(plugin),\n JSON.stringify(plugin.configValues ?? {}),\n ].join('|');\n }\n }\n\n private async readSourceStamp(plugin: LoadedPlugin): Promise<string> {\n try {\n if (plugin.source === 'github') {\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n let head = this.githubCheckoutHeads.get(checkoutPath);\n if (head === undefined) {\n head = await this.readGitHead(checkoutPath);\n this.githubCheckoutHeads.set(checkoutPath, head);\n }\n return head;\n }\n return getEntryVersion(resolvePluginEntryPath(plugin, this.options));\n } catch {\n // A plugin that failed to load has no readable source. Its stamp is then\n // status + config, which is enough to notice when it starts working.\n return '';\n }\n }\n\n private updatePluginRenderConfigs(plugins: LoadedPlugin[]): void {\n this.toolRenderConfigs.clear();\n for (const plugin of plugins) {\n if (plugin.status !== 'active') continue;\n for (const [toolName, renderConfig] of Object.entries(plugin.renderConfigs ?? {})) {\n if (!this.toolRenderConfigs.has(toolName)) {\n this.toolRenderConfigs.set(toolName, renderConfig);\n }\n }\n }\n }\n\n private updatePluginTools(nextTools: ReturnType<typeof collectActivePluginTools>): void {\n for (const name of Object.keys(this.rawPluginTools)) {\n if (!(name in nextTools)) {\n delete this.rawPluginTools[name];\n delete this.pluginTools[name];\n }\n }\n\n for (const [name, tool] of Object.entries(nextTools)) {\n this.rawPluginTools[name] = tool;\n if (!this.pluginTools[name]) {\n this.pluginTools[name] = this.createLiveToolProxy(name);\n }\n this.syncLiveToolProxy(name, tool);\n }\n }\n\n private createLiveToolProxy(toolName: string) {\n return {\n execute: async (...args: any[]) => {\n await this.reloadChangedLocalPlugins();\n const latestTool = this.rawPluginTools[toolName];\n if (!latestTool?.execute) {\n throw new Error(`Plugin tool \"${toolName}\" is no longer available`);\n }\n return (latestTool.execute as (...args: any[]) => unknown)(...args);\n },\n } as LoadedPlugin['tools'][string];\n }\n\n private syncLiveToolProxy(toolName: string, tool: LoadedPlugin['tools'][string]): void {\n const proxy = this.pluginTools[toolName];\n if (!proxy) return;\n const mutableProxy = proxy as unknown as Record<string, unknown>;\n for (const key of Object.keys(mutableProxy)) {\n delete mutableProxy[key];\n }\n Object.assign(proxy, tool);\n proxy.execute = this.createLiveToolProxy(toolName).execute;\n }\n\n private async reloadChangedLocalPlugins(): Promise<void> {\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n const entryPath = resolvePluginEntryPath(plugin, this.options);\n const currentVersion = getEntryVersion(entryPath);\n if (this.localEntryVersions.get(entryPath) !== currentVersion) {\n await this.reload();\n return;\n }\n }\n }\n\n private updateLocalEntryWatchers(plugins: LoadedPlugin[]): void {\n const nextEntries = new Set<string>();\n for (const plugin of plugins) {\n if (plugin.source !== 'local' || plugin.status !== 'active') continue;\n let entryPath: string;\n let entryVersion: string;\n try {\n entryPath = resolvePluginEntryPath(plugin, this.options);\n entryVersion = getEntryVersion(entryPath);\n } catch {\n continue;\n }\n nextEntries.add(entryPath);\n this.localEntryVersions.set(entryPath, entryVersion);\n if (this.watchedLocalEntries.has(entryPath)) continue;\n\n const watcher = fs.watchFile(entryPath, { interval: 500 }, (current, previous) => {\n if (current.mtimeMs === previous.mtimeMs) return;\n void this.reload().catch(() => undefined);\n });\n watcher.unref?.();\n this.watchedLocalEntries.add(entryPath);\n }\n\n for (const entryPath of this.watchedLocalEntries) {\n if (nextEntries.has(entryPath)) continue;\n fs.unwatchFile(entryPath);\n this.watchedLocalEntries.delete(entryPath);\n this.localEntryVersions.delete(entryPath);\n }\n }\n\n private updateGithubPoller(plugins: LoadedPlugin[]): void {\n const hasGithubPlugin = plugins.some(\n plugin => plugin.source === 'github' && plugin.status !== 'inactive' && plugin.status !== 'blocked',\n );\n if (hasGithubPlugin && !this.githubPollTimer) {\n this.githubPollTimer = setInterval(() => {\n void this.pollGithubSourcesForUpdates().catch(() => undefined);\n }, GITHUB_PLUGIN_POLL_INTERVAL_MS);\n this.githubPollTimer.unref?.();\n }\n if (!hasGithubPlugin && this.githubPollTimer) {\n clearInterval(this.githubPollTimer);\n this.githubPollTimer = undefined;\n }\n }\n\n async pollGithubSourcesForUpdates(): Promise<boolean> {\n if (this.githubPollInFlight) return this.githubPollInFlight;\n this.githubPollInFlight = this.pollGithubSourcesForUpdatesOnce().finally(() => {\n this.githubPollInFlight = undefined;\n });\n return this.githubPollInFlight;\n }\n\n private async pollGithubSourcesForUpdatesOnce(): Promise<boolean> {\n const changedCheckouts = new Set<string>();\n const seen = new Set<string>();\n for (const plugin of this.loadedPlugins) {\n if (plugin.source !== 'github' || plugin.status === 'inactive' || plugin.status === 'blocked') continue;\n const checkoutPath = this.resolvePluginSourcePath(plugin);\n if (seen.has(checkoutPath) || !fs.existsSync(path.join(checkoutPath, '.git'))) continue;\n seen.add(checkoutPath);\n\n const before = await this.readGitHead(checkoutPath);\n const checkoutChanged = await this.refreshGithubCheckout(plugin, checkoutPath, before);\n const after = await this.readGitHead(checkoutPath);\n // Feed the cache before reloading: the stamp is computed during reload and\n // has to see the new head, or a real update would look unchanged.\n this.githubCheckoutHeads.set(checkoutPath, after);\n if (checkoutChanged || before !== after) changedCheckouts.add(checkoutPath);\n }\n\n if (changedCheckouts.size === 0) return false;\n\n await this.reload();\n // Derive names from the reloaded state so a manifest display-name change reports the new name.\n // Multiple plugins can share one checkout — report every plugin whose source changed.\n const updatedPluginNames = this.loadedPlugins\n .filter(\n plugin =>\n plugin.source === 'github' &&\n plugin.status !== 'inactive' &&\n plugin.status !== 'blocked' &&\n changedCheckouts.has(this.resolvePluginSourcePath(plugin)),\n )\n .map(plugin => plugin.name ?? plugin.id);\n await this.notifyGithubUpdateListeners(updatedPluginNames);\n return true;\n }\n\n private async notifyGithubUpdateListeners(pluginNames: string[]): Promise<void> {\n await Promise.all([...this.githubUpdateListeners].map(listener => Promise.resolve(listener(pluginNames))));\n }\n\n private async refreshGithubCheckout(\n plugin: LoadedPlugin,\n checkoutPath: string,\n currentHead: string,\n ): Promise<boolean> {\n await execa('git', ['fetch', 'origin'], gitExecOptions(checkoutPath));\n const upstream = await this.resolveGitUpstream(checkoutPath, plugin.ref);\n if (!upstream) return false;\n const [localOnly, remoteOnly] = await this.readGitAheadBehind(checkoutPath, upstream);\n const hasLocalChanges = await this.hasGitWorkingTreeChanges(checkoutPath);\n\n if (localOnly > 0 || hasLocalChanges) {\n await this.backupGitCheckout(checkoutPath, currentHead, hasLocalChanges);\n }\n\n if (remoteOnly > 0 || localOnly > 0 || hasLocalChanges) {\n await execa('git', ['reset', '--hard', upstream], gitExecOptions(checkoutPath));\n try {\n await installPluginDependenciesForEntry(checkoutPath, plugin.entry);\n ensureMastraCodePackageLink(getEntryPackageRoot(checkoutPath, plugin.entry));\n } catch (error) {\n await execa('git', ['reset', '--hard', currentHead], gitExecOptions(checkoutPath));\n throw error;\n }\n return true;\n }\n\n return false;\n }\n\n private async backupGitCheckout(\n checkoutPath: string,\n currentHead: string,\n includeWorkingTree: boolean,\n ): Promise<void> {\n const backupBranch = this.createGitBackupBranchName(currentHead);\n\n if (includeWorkingTree) {\n const currentBranch = await this.readGitCurrentBranch(checkoutPath);\n await execa('git', ['switch', '-c', backupBranch], gitExecOptions(checkoutPath));\n await execa('git', ['add', '-A'], gitExecOptions(checkoutPath));\n const hasStagedChanges = await this.hasGitStagedChanges(checkoutPath);\n if (hasStagedChanges) {\n await execa(\n 'git',\n [\n '-c',\n 'user.name=Mastra Code',\n '-c',\n 'user.email=noreply@mastra.ai',\n 'commit',\n '-m',\n 'chore: backup local plugin checkout changes',\n ],\n gitExecOptions(checkoutPath),\n );\n }\n await this.restoreGitCheckout(checkoutPath, currentBranch, currentHead);\n return;\n }\n\n await execa('git', ['branch', backupBranch, 'HEAD'], gitExecOptions(checkoutPath));\n }\n\n private async resolveGitUpstream(cwd: string, installedRef?: string): Promise<string | undefined> {\n try {\n const { stdout } = await execa(\n 'git',\n ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}'],\n gitExecOptions(cwd),\n );\n return stdout.trim();\n } catch {\n return installedRef ? undefined : 'origin/main';\n }\n }\n\n private async readGitAheadBehind(cwd: string, upstream: string): Promise<[number, number]> {\n const { stdout } = await execa(\n 'git',\n ['rev-list', '--left-right', '--count', `HEAD...${upstream}`],\n gitExecOptions(cwd),\n );\n const [ahead = '0', behind = '0'] = stdout.trim().split(/\\s+/);\n return [Number(ahead) || 0, Number(behind) || 0];\n }\n\n private async hasGitWorkingTreeChanges(cwd: string): Promise<boolean> {\n const { stdout } = await execa('git', ['status', '--porcelain'], gitExecOptions(cwd));\n return stdout.trim().length > 0;\n }\n\n private async hasGitStagedChanges(cwd: string): Promise<boolean> {\n try {\n await execa('git', ['diff', '--cached', '--quiet'], gitExecOptions(cwd));\n return false;\n } catch {\n return true;\n }\n }\n\n private async restoreGitCheckout(cwd: string, branch: string | undefined, fallbackHead: string): Promise<void> {\n if (branch) {\n await execa('git', ['switch', branch], gitExecOptions(cwd));\n return;\n }\n await execa('git', ['checkout', fallbackHead], gitExecOptions(cwd));\n }\n\n private async readGitCurrentBranch(cwd: string): Promise<string | undefined> {\n const { stdout } = await execa('git', ['branch', '--show-current'], gitExecOptions(cwd));\n const branch = stdout.trim();\n return branch.length > 0 ? branch : undefined;\n }\n\n private createGitBackupBranchName(currentHead: string): string {\n const timestamp = new Date().toISOString().replace(/[:.]/g, '-');\n return `mastracode/plugin-backup/${timestamp}-${currentHead.slice(0, 8)}`;\n }\n\n private resolvePluginSourcePath(plugin: LoadedPlugin): string {\n const paths = getPluginScopePaths(plugin.scope, this.options);\n // Normalized so cache keys derived here match the `path.resolve`-normalized\n // key that `uninstall` deletes with.\n return path.resolve(path.isAbsolute(plugin.path) ? plugin.path : path.join(paths.root, plugin.path));\n }\n\n private async readGitHead(cwd: string): Promise<string> {\n const { stdout } = await execa('git', ['rev-parse', 'HEAD'], gitExecOptions(cwd));\n return stdout.trim();\n }\n\n discoverLocal(searchRoot = '.'): ReturnType<typeof discoverLocalPlugins> {\n return discoverLocalPlugins(searchRoot, this.options);\n }\n\n async installLocal(\n localPath: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry'> = {},\n ): Promise<string> {\n const id = await installLocalPlugin(localPath, scope, { ...this.options, ...options });\n await this.reload();\n return id;\n }\n\n async installGithub(\n url: string,\n scope: PluginScope,\n options: Pick<InstallPluginOptions, 'entry' | 'ref' | 'onOutput' | 'signal'> = {},\n ): Promise<string> {\n const id = await installGithubPlugin(url, scope, { ...this.options, ...options });\n // Installing over an existing checkout replaces it at the same path, so the\n // cached head would make a genuinely different commit stamp as unchanged and\n // leave the previous signal providers running.\n this.githubCheckoutHeads.clear();\n await this.reload();\n return id;\n }\n\n async setEnabled(pluginId: string, scope: PluginScope, enabled: boolean): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, { ...record, enabled }));\n await this.reload();\n }\n\n async setConfigValue(\n pluginId: string,\n scope: PluginScope,\n key: string,\n value: MastraCodePluginConfigValue,\n ): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n const config = { ...(record.config ?? {}) };\n if (value === undefined || value === '') {\n delete config[key];\n } else {\n config[key] = value;\n }\n const nextRecord = { ...record, config: Object.keys(config).length > 0 ? config : undefined };\n savePluginRegistry(paths.registryPath, setPluginRecord(registry, pluginId, nextRecord));\n await this.reload();\n }\n\n async uninstall(pluginId: string, scope: PluginScope): Promise<void> {\n const paths = getPluginScopePaths(scope, this.options);\n const registry = loadPluginRegistry(paths.registryPath);\n const record = registry.plugins[pluginId];\n if (!record) {\n throw new Error(`Plugin \"${pluginId}\" is not installed in ${scope} scope`);\n }\n\n savePluginRegistry(paths.registryPath, removePluginRecord(registry, pluginId));\n if (record.source === 'github') {\n const checkoutPath = path.resolve(\n path.isAbsolute(record.path) ? record.path : path.join(paths.root, record.path),\n );\n const githubSourcesPath = path.resolve(paths.sourcesPath, 'github');\n if (isInsideDirectory(checkoutPath, githubSourcesPath)) {\n fs.rmSync(checkoutPath, { recursive: true, force: true });\n }\n this.githubCheckoutHeads.delete(checkoutPath);\n }\n await this.reload();\n }\n}\n"],"mappings":";;;;;;;;;;AAiB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O,KAAK,MAAM,CAAC,CAAC,SAAS,IAAI,SAAS,KAAA;EAAU;EAC5F,mBAAmB,MAAM,cAAc,gBAAgB,UAAU,UAAU,UAAU,CAAC;EACtF,MAAM,KAAK,OAAO;CACpB;CAEA,MAAM,UAAU,UAAkB,OAAmC;EACnE,MAAM,QAAQ,oBAAoB,OAAO,KAAK,OAAO;EACrD,MAAM,WAAW,mBAAmB,MAAM,YAAY;EACtD,MAAM,SAAS,SAAS,QAAQ;EAChC,IAAI,CAAC,QACH,MAAM,IAAI,MAAM,WAAW,SAAS,wBAAwB,MAAM,OAAO;EAG3E,mBAAmB,MAAM,cAAc,mBAAmB,UAAU,QAAQ,CAAC;EAC7E,IAAI,OAAO,WAAW,UAAU;GAC9B,MAAM,eAAe,KAAK,QACxB,KAAK,WAAW,OAAO,IAAI,IAAI,OAAO,OAAO,KAAK,KAAK,MAAM,MAAM,OAAO,IAAI,CAChF;GACA,MAAM,oBAAoB,KAAK,QAAQ,MAAM,aAAa,QAAQ;GAClE,IAAI,kBAAkB,cAAc,iBAAiB,GACnD,GAAG,OAAO,cAAc;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;GAE1D,KAAK,oBAAoB,OAAO,YAAY;EAC9C;EACA,MAAM,KAAK,OAAO;CACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-link.js","names":[],"sources":["../../src/plugins/package-link.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));\n\nlet cachedPackageRoot: string | undefined;\n\n// This module ships in @mastra/code-sdk, so the `mastracode` package root is\n// resolved lazily: from the module location (source tree / bundled dist), or —\n// for the published CLI where the sdk is an external dependency — from the\n// entry script, which lives inside the `mastracode` package.\nfunction mastraCodePackageRoot(): string {\n if (cachedPackageRoot === undefined) {\n try {\n cachedPackageRoot = findMastraCodePackageRoot(MODULE_DIR);\n } catch (error) {\n const entryScript = process.argv[1];\n if (!entryScript) throw error;\n cachedPackageRoot = findMastraCodePackageRoot(path.dirname(fs.realpathSync(entryScript)));\n }\n }\n return cachedPackageRoot;\n}\n\nfunction readPackageName(dir: string): string | undefined {\n const packageJsonPath = path.join(dir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return undefined;\n return (JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string }).name;\n}\n\nexport function findMastraCodePackageRoot(startDir: string): string {\n let currentDir = path.resolve(startDir);\n\n while (true) {\n const packageName = readPackageName(currentDir);\n if (packageName === 'mastracode') {\n return currentDir;\n }\n if (packageName === '@mastra/code-sdk') {\n // The `mastracode` package sits next to the sdk: mastracode/sdk ↔\n // mastracode/tui in the source tree, node_modules/@mastra/code-sdk ↔\n // node_modules/mastracode when installed.\n for (const candidate of [\n path.resolve(currentDir, '..', 'tui'),\n path.resolve(currentDir, '..', '..', 'mastracode'),\n ]) {\n if (readPackageName(candidate) === 'mastracode') {\n return candidate;\n }\n }\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n throw new Error(`Could not find mastracode package root from ${startDir}`);\n }\n currentDir = parentDir;\n }\n}\n\nexport function ensureMastraCodePackageLink(pluginDir: string): void {\n if (declaresInstallableMastraCodeDependency(pluginDir)) {\n return;\n }\n\n const packageRoot = mastraCodePackageRoot();\n const nodeModulesDir = path.join(pluginDir, 'node_modules');\n const linkPath = path.join(nodeModulesDir, 'mastracode');\n try {\n if (fs.realpathSync(linkPath) === fs.realpathSync(packageRoot)) {\n return;\n }\n fs.rmSync(linkPath, { recursive: true, force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n fs.mkdirSync(nodeModulesDir, { recursive: true });\n fs.symlinkSync(packageRoot, linkPath, 'dir');\n}\n\nfunction declaresInstallableMastraCodeDependency(pluginDir: string): boolean {\n const packageJsonPath = path.join(pluginDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return false;\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as {\n dependencies?: Record<string, unknown>;\n devDependencies?: Record<string, unknown>;\n optionalDependencies?: Record<string, unknown>;\n };\n\n return Boolean(\n packageJson.dependencies?.mastracode ??\n packageJson.devDependencies?.mastracode ??\n packageJson.optionalDependencies?.mastracode,\n );\n}\n"],"mappings":";;;;AAIA,MAAM,aAAa,KAAK,QAAQ,cAAc,
|
|
1
|
+
{"version":3,"file":"package-link.js","names":[],"sources":["../../src/plugins/package-link.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));\n\nlet cachedPackageRoot: string | undefined;\n\n// This module ships in @mastra/code-sdk, so the `mastracode` package root is\n// resolved lazily: from the module location (source tree / bundled dist), or —\n// for the published CLI where the sdk is an external dependency — from the\n// entry script, which lives inside the `mastracode` package.\nfunction mastraCodePackageRoot(): string {\n if (cachedPackageRoot === undefined) {\n try {\n cachedPackageRoot = findMastraCodePackageRoot(MODULE_DIR);\n } catch (error) {\n const entryScript = process.argv[1];\n if (!entryScript) throw error;\n cachedPackageRoot = findMastraCodePackageRoot(path.dirname(fs.realpathSync(entryScript)));\n }\n }\n return cachedPackageRoot;\n}\n\nfunction readPackageName(dir: string): string | undefined {\n const packageJsonPath = path.join(dir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return undefined;\n return (JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as { name?: string }).name;\n}\n\nexport function findMastraCodePackageRoot(startDir: string): string {\n let currentDir = path.resolve(startDir);\n\n while (true) {\n const packageName = readPackageName(currentDir);\n if (packageName === 'mastracode') {\n return currentDir;\n }\n if (packageName === '@mastra/code-sdk') {\n // The `mastracode` package sits next to the sdk: mastracode/sdk ↔\n // mastracode/tui in the source tree, node_modules/@mastra/code-sdk ↔\n // node_modules/mastracode when installed.\n for (const candidate of [\n path.resolve(currentDir, '..', 'tui'),\n path.resolve(currentDir, '..', '..', 'mastracode'),\n ]) {\n if (readPackageName(candidate) === 'mastracode') {\n return candidate;\n }\n }\n }\n\n const parentDir = path.dirname(currentDir);\n if (parentDir === currentDir) {\n throw new Error(`Could not find mastracode package root from ${startDir}`);\n }\n currentDir = parentDir;\n }\n}\n\nexport function ensureMastraCodePackageLink(pluginDir: string): void {\n if (declaresInstallableMastraCodeDependency(pluginDir)) {\n return;\n }\n\n const packageRoot = mastraCodePackageRoot();\n const nodeModulesDir = path.join(pluginDir, 'node_modules');\n const linkPath = path.join(nodeModulesDir, 'mastracode');\n try {\n if (fs.realpathSync(linkPath) === fs.realpathSync(packageRoot)) {\n return;\n }\n fs.rmSync(linkPath, { recursive: true, force: true });\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n\n fs.mkdirSync(nodeModulesDir, { recursive: true });\n fs.symlinkSync(packageRoot, linkPath, 'dir');\n}\n\nfunction declaresInstallableMastraCodeDependency(pluginDir: string): boolean {\n const packageJsonPath = path.join(pluginDir, 'package.json');\n if (!fs.existsSync(packageJsonPath)) return false;\n\n const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as {\n dependencies?: Record<string, unknown>;\n devDependencies?: Record<string, unknown>;\n optionalDependencies?: Record<string, unknown>;\n };\n\n return Boolean(\n packageJson.dependencies?.mastracode ??\n packageJson.devDependencies?.mastracode ??\n packageJson.optionalDependencies?.mastracode,\n );\n}\n"],"mappings":";;;;AAIA,MAAM,aAAa,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;AAE9D,IAAI;AAMJ,SAAS,wBAAgC;CACvC,IAAI,sBAAsB,KAAA,GACxB,IAAI;EACF,oBAAoB,0BAA0B,UAAU;CAC1D,SAAS,OAAO;EACd,MAAM,cAAc,QAAQ,KAAK;EACjC,IAAI,CAAC,aAAa,MAAM;EACxB,oBAAoB,0BAA0B,KAAK,QAAQ,GAAG,aAAa,WAAW,CAAC,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AAI,CAAC,GAAG,WAAW,eAAe,GAAG,OAAO;CAE5C,MAAM,cAAc,KAAK,MAAM,GAAG,aAAa,iBAAiB,MAAM,CAAC;CAMvE,OAAO,QACL,YAAY,cAAc,cAC1B,YAAY,iBAAiB,cAC7B,YAAY,sBAAsB,UACpC;AACF"}
|
package/dist/plugins/scaffold.js
CHANGED
|
@@ -44,10 +44,12 @@ function scaffoldPlugin(targetDir, options = {}) {
|
|
|
44
44
|
}
|
|
45
45
|
function writeScaffoldManifest(originalTarget, scaffoldDir, pluginId, pluginName, options) {
|
|
46
46
|
const projectRoot = options.projectRoot ?? process.cwd();
|
|
47
|
-
|
|
47
|
+
const manifestRoot = isBarePluginName(originalTarget) ? projectRoot : scaffoldDir;
|
|
48
|
+
const entry = isBarePluginName(originalTarget) ? path.join(path.relative(projectRoot, scaffoldDir), "src/index.ts") : "src/index.ts";
|
|
49
|
+
upsertPluginManifestEntry(manifestRoot, {
|
|
48
50
|
id: pluginId,
|
|
49
51
|
name: pluginName,
|
|
50
|
-
entry:
|
|
52
|
+
entry: entry.split(path.sep).join("/")
|
|
51
53
|
});
|
|
52
54
|
}
|
|
53
55
|
function formatScaffoldSuccess(targetDir) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scaffold.js","names":[],"sources":["../../src/plugins/scaffold.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { upsertPluginManifestEntry } from './manifest.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\n\nexport type ScaffoldPluginOptions = {\n id?: string;\n name?: string;\n projectRoot?: string;\n configDir?: string;\n};\n\nexport function resolveScaffoldTarget(\n target: string,\n options: Pick<ScaffoldPluginOptions, 'projectRoot' | 'configDir'> = {},\n): string {\n if (isBarePluginName(target)) {\n return path.join(\n options.projectRoot ?? process.cwd(),\n options.configDir ?? DEFAULT_CONFIG_DIR,\n 'plugins',\n 'sources',\n 'local',\n target,\n );\n }\n return path.resolve(options.projectRoot ?? process.cwd(), target);\n}\n\nexport function scaffoldPlugin(targetDir: string, options: ScaffoldPluginOptions = {}): string {\n const dir = resolveScaffoldTarget(targetDir, options);\n if (fs.existsSync(dir) && fs.readdirSync(dir).length > 0) {\n throw new Error(`Directory already exists and is not empty: ${targetDir}`);\n }\n\n const packageName =\n path\n .basename(dir)\n .toLowerCase()\n .replace(/[^a-z0-9_.-]+/g, '-')\n .replace(/^-|-$/g, '') || 'mastracode-plugin';\n const pluginId = options.id ?? packageName;\n const pluginName = options.name ?? humanizeName(packageName);\n\n fs.mkdirSync(path.join(dir, 'src'), { recursive: true });\n fs.writeFileSync(\n path.join(dir, 'package.json'),\n `${JSON.stringify(\n {\n name: packageName,\n type: 'module',\n exports: './src/index.ts',\n peerDependencies: {\n mastracode: '*',\n },\n devDependencies: {\n typescript: '^5.9.3',\n },\n scripts: {\n check: 'tsc --noEmit',\n },\n },\n null,\n 2,\n )}\\n`,\n );\n fs.writeFileSync(\n path.join(dir, 'tsconfig.json'),\n `${JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2024',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n verbatimModuleSyntax: true,\n erasableSyntaxOnly: true,\n skipLibCheck: true,\n noEmit: true,\n },\n include: ['src/**/*.ts'],\n },\n null,\n 2,\n )}\\n`,\n );\n fs.writeFileSync(path.join(dir, 'src/index.ts'), renderIndex(pluginId, pluginName));\n fs.writeFileSync(path.join(dir, 'README.md'), renderReadme(pluginName, pluginId));\n writeScaffoldManifest(targetDir, dir, pluginId, pluginName, options);\n ensureMastraCodePackageLink(dir);\n return dir;\n}\n\nfunction writeScaffoldManifest(\n originalTarget: string,\n scaffoldDir: string,\n pluginId: string,\n pluginName: string,\n options: ScaffoldPluginOptions,\n): void {\n const projectRoot = options.projectRoot ?? process.cwd();\n const manifestRoot = isBarePluginName(originalTarget) ? projectRoot : scaffoldDir;\n const entry = isBarePluginName(originalTarget)\n ? path.join(path.relative(projectRoot, scaffoldDir), 'src/index.ts')\n : 'src/index.ts';\n upsertPluginManifestEntry(manifestRoot, {\n id: pluginId,\n name: pluginName,\n entry: entry.split(path.sep).join('/'),\n });\n}\n\nexport function formatScaffoldSuccess(targetDir: string): string {\n return [\n `Created Mastra Code plugin scaffold at ${targetDir}`,\n '',\n 'Next steps:',\n ` cd ${targetDir}`,\n ' pnpm install',\n ' pnpm check',\n ' mastracode',\n ' /plugins',\n ' Install new plugin → Local path',\n ].join('\\n');\n}\n\nfunction isBarePluginName(target: string): boolean {\n return !path.isAbsolute(target) && !target.startsWith('.') && !target.includes('/') && !target.includes('\\\\');\n}\n\nfunction renderIndex(pluginId: string, pluginName: string): string {\n return `import { createTool, defineMastraCodePlugin, z } from 'mastracode/plugin';\n\nexport default defineMastraCodePlugin({\n id: ${JSON.stringify(pluginId)},\n name: ${JSON.stringify(pluginName)},\n description: 'A Mastra Code tool plugin.',\n tools: {\n example_tool: {\n tool: createTool({\n id: 'example_tool',\n description: 'Echo a message from the scaffolded plugin.',\n inputSchema: z.object({\n message: z.string(),\n }),\n execute: async context => {\n return { message: context.message };\n },\n }),\n },\n },\n});\n`;\n}\n\nfunction renderReadme(pluginName: string, pluginId: string): string {\n return `# ${pluginName}\n\nMastra Code tool plugin: \\`${pluginId}\\`.\n\n## Develop\n\n\\`\\`\\`sh\npnpm install\npnpm check\n\\`\\`\\`\n\n## Install locally\n\nOpen Mastra Code, run \\`/plugins\\`, and install this directory as a local plugin.\n`;\n}\n\nfunction humanizeName(value: string): string {\n return (\n value\n .split(/[-_.]+/g)\n .filter(Boolean)\n .map(part => part[0]?.toUpperCase() + part.slice(1))\n .join(' ') || 'Mastra Code Plugin'\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,sBACd,QACA,UAAoE,CAAC,GAC7D;CACR,IAAI,iBAAiB,MAAM,GACzB,OAAO,KAAK,KACV,QAAQ,eAAe,QAAQ,IAAI,GACnC,QAAQ,aAAA,eACR,WACA,WACA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;AAEA,SAAS,sBACP,gBACA,aACA,UACA,YACA,SACM;CACN,MAAM,cAAc,QAAQ,eAAe,QAAQ,IAAI;
|
|
1
|
+
{"version":3,"file":"scaffold.js","names":[],"sources":["../../src/plugins/scaffold.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { upsertPluginManifestEntry } from './manifest.js';\nimport { ensureMastraCodePackageLink } from './package-link.js';\n\nexport type ScaffoldPluginOptions = {\n id?: string;\n name?: string;\n projectRoot?: string;\n configDir?: string;\n};\n\nexport function resolveScaffoldTarget(\n target: string,\n options: Pick<ScaffoldPluginOptions, 'projectRoot' | 'configDir'> = {},\n): string {\n if (isBarePluginName(target)) {\n return path.join(\n options.projectRoot ?? process.cwd(),\n options.configDir ?? DEFAULT_CONFIG_DIR,\n 'plugins',\n 'sources',\n 'local',\n target,\n );\n }\n return path.resolve(options.projectRoot ?? process.cwd(), target);\n}\n\nexport function scaffoldPlugin(targetDir: string, options: ScaffoldPluginOptions = {}): string {\n const dir = resolveScaffoldTarget(targetDir, options);\n if (fs.existsSync(dir) && fs.readdirSync(dir).length > 0) {\n throw new Error(`Directory already exists and is not empty: ${targetDir}`);\n }\n\n const packageName =\n path\n .basename(dir)\n .toLowerCase()\n .replace(/[^a-z0-9_.-]+/g, '-')\n .replace(/^-|-$/g, '') || 'mastracode-plugin';\n const pluginId = options.id ?? packageName;\n const pluginName = options.name ?? humanizeName(packageName);\n\n fs.mkdirSync(path.join(dir, 'src'), { recursive: true });\n fs.writeFileSync(\n path.join(dir, 'package.json'),\n `${JSON.stringify(\n {\n name: packageName,\n type: 'module',\n exports: './src/index.ts',\n peerDependencies: {\n mastracode: '*',\n },\n devDependencies: {\n typescript: '^5.9.3',\n },\n scripts: {\n check: 'tsc --noEmit',\n },\n },\n null,\n 2,\n )}\\n`,\n );\n fs.writeFileSync(\n path.join(dir, 'tsconfig.json'),\n `${JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2024',\n module: 'NodeNext',\n moduleResolution: 'NodeNext',\n strict: true,\n verbatimModuleSyntax: true,\n erasableSyntaxOnly: true,\n skipLibCheck: true,\n noEmit: true,\n },\n include: ['src/**/*.ts'],\n },\n null,\n 2,\n )}\\n`,\n );\n fs.writeFileSync(path.join(dir, 'src/index.ts'), renderIndex(pluginId, pluginName));\n fs.writeFileSync(path.join(dir, 'README.md'), renderReadme(pluginName, pluginId));\n writeScaffoldManifest(targetDir, dir, pluginId, pluginName, options);\n ensureMastraCodePackageLink(dir);\n return dir;\n}\n\nfunction writeScaffoldManifest(\n originalTarget: string,\n scaffoldDir: string,\n pluginId: string,\n pluginName: string,\n options: ScaffoldPluginOptions,\n): void {\n const projectRoot = options.projectRoot ?? process.cwd();\n const manifestRoot = isBarePluginName(originalTarget) ? projectRoot : scaffoldDir;\n const entry = isBarePluginName(originalTarget)\n ? path.join(path.relative(projectRoot, scaffoldDir), 'src/index.ts')\n : 'src/index.ts';\n upsertPluginManifestEntry(manifestRoot, {\n id: pluginId,\n name: pluginName,\n entry: entry.split(path.sep).join('/'),\n });\n}\n\nexport function formatScaffoldSuccess(targetDir: string): string {\n return [\n `Created Mastra Code plugin scaffold at ${targetDir}`,\n '',\n 'Next steps:',\n ` cd ${targetDir}`,\n ' pnpm install',\n ' pnpm check',\n ' mastracode',\n ' /plugins',\n ' Install new plugin → Local path',\n ].join('\\n');\n}\n\nfunction isBarePluginName(target: string): boolean {\n return !path.isAbsolute(target) && !target.startsWith('.') && !target.includes('/') && !target.includes('\\\\');\n}\n\nfunction renderIndex(pluginId: string, pluginName: string): string {\n return `import { createTool, defineMastraCodePlugin, z } from 'mastracode/plugin';\n\nexport default defineMastraCodePlugin({\n id: ${JSON.stringify(pluginId)},\n name: ${JSON.stringify(pluginName)},\n description: 'A Mastra Code tool plugin.',\n tools: {\n example_tool: {\n tool: createTool({\n id: 'example_tool',\n description: 'Echo a message from the scaffolded plugin.',\n inputSchema: z.object({\n message: z.string(),\n }),\n execute: async context => {\n return { message: context.message };\n },\n }),\n },\n },\n});\n`;\n}\n\nfunction renderReadme(pluginName: string, pluginId: string): string {\n return `# ${pluginName}\n\nMastra Code tool plugin: \\`${pluginId}\\`.\n\n## Develop\n\n\\`\\`\\`sh\npnpm install\npnpm check\n\\`\\`\\`\n\n## Install locally\n\nOpen Mastra Code, run \\`/plugins\\`, and install this directory as a local plugin.\n`;\n}\n\nfunction humanizeName(value: string): string {\n return (\n value\n .split(/[-_.]+/g)\n .filter(Boolean)\n .map(part => part[0]?.toUpperCase() + part.slice(1))\n .join(' ') || 'Mastra Code Plugin'\n );\n}\n"],"mappings":";;;;;;AAcA,SAAgB,sBACd,QACA,UAAoE,CAAC,GAC7D;CACR,IAAI,iBAAiB,MAAM,GACzB,OAAO,KAAK,KACV,QAAQ,eAAe,QAAQ,IAAI,GACnC,QAAQ,aAAA,eACR,WACA,WACA,SACA,MACF;CAEF,OAAO,KAAK,QAAQ,QAAQ,eAAe,QAAQ,IAAI,GAAG,MAAM;AAClE;AAEA,SAAgB,eAAe,WAAmB,UAAiC,CAAC,GAAW;CAC7F,MAAM,MAAM,sBAAsB,WAAW,OAAO;CACpD,IAAI,GAAG,WAAW,GAAG,KAAK,GAAG,YAAY,GAAG,CAAC,CAAC,SAAS,GACrD,MAAM,IAAI,MAAM,8CAA8C,WAAW;CAG3E,MAAM,cACJ,KACG,SAAS,GAAG,CAAC,CACb,YAAY,CAAC,CACb,QAAQ,kBAAkB,GAAG,CAAC,CAC9B,QAAQ,UAAU,EAAE,KAAK;CAC9B,MAAM,WAAW,QAAQ,MAAM;CAC/B,MAAM,aAAa,QAAQ,QAAQ,aAAa,WAAW;CAE3D,GAAG,UAAU,KAAK,KAAK,KAAK,KAAK,GAAG,EAAE,WAAW,KAAK,CAAC;CACvD,GAAG,cACD,KAAK,KAAK,KAAK,cAAc,GAC7B,GAAG,KAAK,UACN;EACE,MAAM;EACN,MAAM;EACN,SAAS;EACT,kBAAkB,EAChB,YAAY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4B;CACjE,OAAO;;;QAGD,KAAK,UAAU,QAAQ,EAAE;UACvB,KAAK,UAAU,UAAU,EAAE;;;;;;;;;;;;;;;;;;AAkBrC;AAEA,SAAS,aAAa,YAAoB,UAA0B;CAClE,OAAO,KAAK,WAAW;;6BAEI,SAAS;;;;;;;;;;;;;AAatC;AAEA,SAAS,aAAa,OAAuB;CAC3C,OACE,MACG,MAAM,SAAS,CAAC,CAChB,OAAO,OAAO,CAAC,CACf,KAAI,SAAQ,KAAK,EAAE,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,CACnD,KAAK,GAAG,KAAK;AAEpB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"signal-lane.js","names":["#live","#reservedProviderIds","#onError","#inputProcessors","#outputProcessors","#retire","#isProviderIdTaken","#startPending","#rebuildProcessors","#mastra","#agent","#runStart","#failProvider","#stopProvider"],"sources":["../../src/plugins/signal-lane.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { InputProcessorOrWorkflow, OutputProcessorOrWorkflow } from '@mastra/core/processors';\nimport type { SignalProvider } from '@mastra/core/signals';\n\nimport type { PluginContribution } from './types.js';\n\ntype LiveProvider = {\n pluginId: string;\n provider: SignalProvider<string>;\n versionStamp: string;\n started: boolean;\n};\n\nexport type PluginSignalLaneOptions = {\n /**\n * Ids of providers Mastra Code wires itself (through the Agent constructor).\n * The lane refuses to start a provider that collides with one of them:\n * two live instances of the same provider silently clobber each other's\n * polling, and the built-ins are invisible to the lane's own registry.\n */\n reservedProviderIds?: string[];\n onError?: (message: string, error: unknown) => void;\n};\n\n/**\n * Owns the lifecycle of signal providers contributed by plugins.\n *\n * Providers are long-lived; processors are per-request. The Agent constructor\n * conflates the two — it harvests a provider's processors into a closure that\n * can never be undone — so plugin providers are deliberately kept out of the\n * `signals` array and driven from here instead, through the same public methods\n * the constructor uses. That is what makes a provider removable when its plugin\n * is disabled, updated or uninstalled.\n */\nexport class PluginSignalLane {\n readonly #live = new Map<string, LiveProvider>();\n readonly #reservedProviderIds: Set<string>;\n readonly #onError: (message: string, error: unknown) => void;\n #agent: Agent | undefined;\n #mastra: Mastra | undefined;\n // Replaced wholesale, never mutated: a request that already resolved its\n // processors keeps the array it read, so a reload mid-request cannot change\n // the pipeline underneath it.\n #inputProcessors: InputProcessorOrWorkflow[] = [];\n #outputProcessors: OutputProcessorOrWorkflow[] = [];\n\n constructor(options: PluginSignalLaneOptions = {}) {\n this.#reservedProviderIds = new Set(options.reservedProviderIds ?? []);\n this.#onError =\n options.onError ??\n ((message, error) => {\n console.warn(message, error);\n });\n }\n\n getInputProcessors(): readonly InputProcessorOrWorkflow[] {\n return this.#inputProcessors;\n }\n\n getOutputProcessors(): readonly OutputProcessorOrWorkflow[] {\n return this.#outputProcessors;\n }\n\n /**\n * Reconciles the live providers against a freshly loaded plugin list.\n *\n * A plugin whose stamp is unchanged keeps the provider instance it already\n * has, and the freshly resolved one is dropped without ever being registered,\n * connected or polled — reload re-runs every plugin's resolver, so unchanged\n * plugins hand over new instances on every call.\n *\n * Providers of plugins that went inactive, failed to load or were uninstalled\n * are absent from the contributions and get stopped here.\n */\n sync(contributions: PluginContribution<SignalProvider<string>>[]): void {\n const seen = new Set<string>();\n\n for (const { pluginId, versionStamp, value: provider } of contributions) {\n const key = `${pluginId}::${provider.id}`;\n seen.add(key);\n\n const live = this.#live.get(key);\n if (live && live.versionStamp === versionStamp) continue;\n if (live) this.#retire(key, live);\n\n if (this.#isProviderIdTaken(provider.id)) {\n this.#onError(\n `Plugin \"${pluginId}\" signal provider \"${provider.id}\" is already running; refusing to start a second instance.`,\n undefined,\n );\n seen.delete(key);\n continue;\n }\n\n this.#live.set(key, { pluginId, provider, versionStamp, started: false });\n }\n\n for (const [key, live] of this.#live) {\n if (!seen.has(key)) this.#retire(key, live);\n }\n\n this.#startPending();\n this.#rebuildProcessors();\n }\n\n /**\n * Called once Mastra exists. Providers resolved before then are registered and\n * started here — without a Mastra instance a provider has no storage, and\n * nothing else will ever hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n setMastra(mastra: Mastra, agent: Agent): void {\n this.#mastra = mastra;\n this.#agent = agent;\n this.#startPending();\n this.#rebuildProcessors();\n }\n\n /**\n * Retires every live provider and empties both processor lanes. The inverse of\n * `sync()`, for a caller that is done with this lane — an embedder sharing one\n * `PluginManager` across controllers would otherwise leave a controller's\n * providers polling after it is gone.\n */\n stopAll(): void {\n for (const [key, live] of this.#live) this.#retire(key, live);\n this.#rebuildProcessors();\n }\n\n #startPending(): void {\n const mastra = this.#mastra;\n const agent = this.#agent;\n if (!mastra || !agent) return;\n\n for (const [key, live] of this.#live) {\n if (live.started) continue;\n try {\n live.provider.__registerMastra(mastra);\n live.provider.connect(agent);\n live.provider.startPolling();\n live.started = true;\n // `start()` is the provider's own warm-up and may do network work, so it\n // is not awaited — this runs on the boot path and on every plugin\n // reload, and a slow provider must not hold either up. The Agent\n // constructor treats it the same way (agent.ts: `void provider.start?.()`).\n void this.#runStart(key, live);\n } catch (error) {\n this.#failProvider(key, live, error);\n }\n }\n }\n\n async #runStart(key: string, live: LiveProvider): Promise<void> {\n try {\n await live.provider.start?.();\n // Retired or replaced while warming up: whatever `start()` just armed was\n // armed after this provider was stopped, so it is stopped again. Without\n // this a provider replaced mid-warm-up keeps working against the thread\n // its successor is now watching.\n if (this.#live.get(key) !== live) this.#stopProvider(live);\n } catch (error) {\n if (this.#live.get(key) !== live) {\n this.#stopProvider(live);\n return;\n }\n this.#failProvider(key, live, error);\n this.#rebuildProcessors();\n }\n }\n\n /**\n * Isolated: one failing provider does not take down its plugin's tools,\n * commands, skills or sibling providers. A plugin author who wants a provider\n * treated as required throws from the `signalProviders` resolver instead,\n * which fails the whole plugin record.\n */\n #failProvider(key: string, live: LiveProvider, error: unknown): void {\n this.#onError(`Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to start:`, error);\n this.#retire(key, live);\n }\n\n #retire(key: string, live: LiveProvider): void {\n this.#stopProvider(live);\n this.#live.delete(key);\n }\n\n #stopProvider(live: LiveProvider): void {\n try {\n live.provider.stop();\n } catch (error) {\n this.#onError(`Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to stop:`, error);\n }\n }\n\n #isProviderIdTaken(providerId: string): boolean {\n if (this.#reservedProviderIds.has(providerId)) return true;\n for (const live of this.#live.values()) {\n if (live.provider.id === providerId) return true;\n }\n return false;\n }\n\n #rebuildProcessors(): void {\n const input: InputProcessorOrWorkflow[] = [];\n const output: OutputProcessorOrWorkflow[] = [];\n for (const live of this.#live.values()) {\n // Only started providers contribute: one that has not been handed Mastra\n // yet has no storage, so running its processors would fail on the first\n // request rather than wait for the lifecycle to complete.\n if (!live.started) continue;\n // Guarded like every other provider call: a throwing getter drops that\n // provider's processors from this rebuild instead of unwinding the whole\n // lane mid-sync. Both getters are read before either lane is touched so a\n // provider never contributes input processors without its output ones.\n try {\n const providerInput = live.provider.getInputProcessors?.() ?? [];\n const providerOutput = live.provider.getOutputProcessors?.() ?? [];\n input.push(...providerInput);\n output.push(...providerOutput);\n } catch (error) {\n this.#onError(\n `Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to provide processors:`,\n error,\n );\n }\n }\n this.#inputProcessors = input;\n this.#outputProcessors = output;\n }\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAa,mBAAb,MAA8B;CAC5B,wBAAiB,IAAI,IAA0B;CAC/C;CACA;CACA;CACA;CAIA,mBAA+C,CAAC;CAChD,oBAAiD,CAAC;CAElD,YAAY,UAAmC,CAAC,GAAG;EACjD,KAAKC,uBAAuB,IAAI,IAAI,QAAQ,uBAAuB,CAAC,CAAC;EACrE,KAAKC,WACH,QAAQ,aACN,SAAS,UAAU;GACnB,QAAQ,KAAK,SAAS,KAAK;EAC7B;CACJ;CAEA,qBAA0D;EACxD,OAAO,KAAKC;CACd;CAEA,sBAA4D;EAC1D,OAA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,qBAAqB,KAAK,CAAC;IAC/D,MAAM,iBAAiB,KAAK,SAAS,sBAAsB,KAAK,CAAC;IACjE,MAAM,KAAK,GAAG,aAAa;IAC3B,OAAO,KAAK,GAAG,cAAc;GAC/B,SAAS,OAAO;IACd,KAAKE,SACH,WAAW,KAAK,SAAS,qBAAqB,KAAK,SAAS,GAAG,kCAC/D,KACF;GACF;EACF;EACA,KAAKC,mBAAmB;EACxB,KAAKC,oBAAoB;CAC3B;AACF"}
|
|
1
|
+
{"version":3,"file":"signal-lane.js","names":[],"sources":["../../src/plugins/signal-lane.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { InputProcessorOrWorkflow, OutputProcessorOrWorkflow } from '@mastra/core/processors';\nimport type { SignalProvider } from '@mastra/core/signals';\n\nimport type { PluginContribution } from './types.js';\n\ntype LiveProvider = {\n pluginId: string;\n provider: SignalProvider<string>;\n versionStamp: string;\n started: boolean;\n};\n\nexport type PluginSignalLaneOptions = {\n /**\n * Ids of providers Mastra Code wires itself (through the Agent constructor).\n * The lane refuses to start a provider that collides with one of them:\n * two live instances of the same provider silently clobber each other's\n * polling, and the built-ins are invisible to the lane's own registry.\n */\n reservedProviderIds?: string[];\n onError?: (message: string, error: unknown) => void;\n};\n\n/**\n * Owns the lifecycle of signal providers contributed by plugins.\n *\n * Providers are long-lived; processors are per-request. The Agent constructor\n * conflates the two — it harvests a provider's processors into a closure that\n * can never be undone — so plugin providers are deliberately kept out of the\n * `signals` array and driven from here instead, through the same public methods\n * the constructor uses. That is what makes a provider removable when its plugin\n * is disabled, updated or uninstalled.\n */\nexport class PluginSignalLane {\n readonly #live = new Map<string, LiveProvider>();\n readonly #reservedProviderIds: Set<string>;\n readonly #onError: (message: string, error: unknown) => void;\n #agent: Agent | undefined;\n #mastra: Mastra | undefined;\n // Replaced wholesale, never mutated: a request that already resolved its\n // processors keeps the array it read, so a reload mid-request cannot change\n // the pipeline underneath it.\n #inputProcessors: InputProcessorOrWorkflow[] = [];\n #outputProcessors: OutputProcessorOrWorkflow[] = [];\n\n constructor(options: PluginSignalLaneOptions = {}) {\n this.#reservedProviderIds = new Set(options.reservedProviderIds ?? []);\n this.#onError =\n options.onError ??\n ((message, error) => {\n console.warn(message, error);\n });\n }\n\n getInputProcessors(): readonly InputProcessorOrWorkflow[] {\n return this.#inputProcessors;\n }\n\n getOutputProcessors(): readonly OutputProcessorOrWorkflow[] {\n return this.#outputProcessors;\n }\n\n /**\n * Reconciles the live providers against a freshly loaded plugin list.\n *\n * A plugin whose stamp is unchanged keeps the provider instance it already\n * has, and the freshly resolved one is dropped without ever being registered,\n * connected or polled — reload re-runs every plugin's resolver, so unchanged\n * plugins hand over new instances on every call.\n *\n * Providers of plugins that went inactive, failed to load or were uninstalled\n * are absent from the contributions and get stopped here.\n */\n sync(contributions: PluginContribution<SignalProvider<string>>[]): void {\n const seen = new Set<string>();\n\n for (const { pluginId, versionStamp, value: provider } of contributions) {\n const key = `${pluginId}::${provider.id}`;\n seen.add(key);\n\n const live = this.#live.get(key);\n if (live && live.versionStamp === versionStamp) continue;\n if (live) this.#retire(key, live);\n\n if (this.#isProviderIdTaken(provider.id)) {\n this.#onError(\n `Plugin \"${pluginId}\" signal provider \"${provider.id}\" is already running; refusing to start a second instance.`,\n undefined,\n );\n seen.delete(key);\n continue;\n }\n\n this.#live.set(key, { pluginId, provider, versionStamp, started: false });\n }\n\n for (const [key, live] of this.#live) {\n if (!seen.has(key)) this.#retire(key, live);\n }\n\n this.#startPending();\n this.#rebuildProcessors();\n }\n\n /**\n * Called once Mastra exists. Providers resolved before then are registered and\n * started here — without a Mastra instance a provider has no storage, and\n * nothing else will ever hand it one: the Agent propagates Mastra only to the\n * providers in its own `signals` array, which these deliberately are not in.\n */\n setMastra(mastra: Mastra, agent: Agent): void {\n this.#mastra = mastra;\n this.#agent = agent;\n this.#startPending();\n this.#rebuildProcessors();\n }\n\n /**\n * Retires every live provider and empties both processor lanes. The inverse of\n * `sync()`, for a caller that is done with this lane — an embedder sharing one\n * `PluginManager` across controllers would otherwise leave a controller's\n * providers polling after it is gone.\n */\n stopAll(): void {\n for (const [key, live] of this.#live) this.#retire(key, live);\n this.#rebuildProcessors();\n }\n\n #startPending(): void {\n const mastra = this.#mastra;\n const agent = this.#agent;\n if (!mastra || !agent) return;\n\n for (const [key, live] of this.#live) {\n if (live.started) continue;\n try {\n live.provider.__registerMastra(mastra);\n live.provider.connect(agent);\n live.provider.startPolling();\n live.started = true;\n // `start()` is the provider's own warm-up and may do network work, so it\n // is not awaited — this runs on the boot path and on every plugin\n // reload, and a slow provider must not hold either up. The Agent\n // constructor treats it the same way (agent.ts: `void provider.start?.()`).\n void this.#runStart(key, live);\n } catch (error) {\n this.#failProvider(key, live, error);\n }\n }\n }\n\n async #runStart(key: string, live: LiveProvider): Promise<void> {\n try {\n await live.provider.start?.();\n // Retired or replaced while warming up: whatever `start()` just armed was\n // armed after this provider was stopped, so it is stopped again. Without\n // this a provider replaced mid-warm-up keeps working against the thread\n // its successor is now watching.\n if (this.#live.get(key) !== live) this.#stopProvider(live);\n } catch (error) {\n if (this.#live.get(key) !== live) {\n this.#stopProvider(live);\n return;\n }\n this.#failProvider(key, live, error);\n this.#rebuildProcessors();\n }\n }\n\n /**\n * Isolated: one failing provider does not take down its plugin's tools,\n * commands, skills or sibling providers. A plugin author who wants a provider\n * treated as required throws from the `signalProviders` resolver instead,\n * which fails the whole plugin record.\n */\n #failProvider(key: string, live: LiveProvider, error: unknown): void {\n this.#onError(`Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to start:`, error);\n this.#retire(key, live);\n }\n\n #retire(key: string, live: LiveProvider): void {\n this.#stopProvider(live);\n this.#live.delete(key);\n }\n\n #stopProvider(live: LiveProvider): void {\n try {\n live.provider.stop();\n } catch (error) {\n this.#onError(`Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to stop:`, error);\n }\n }\n\n #isProviderIdTaken(providerId: string): boolean {\n if (this.#reservedProviderIds.has(providerId)) return true;\n for (const live of this.#live.values()) {\n if (live.provider.id === providerId) return true;\n }\n return false;\n }\n\n #rebuildProcessors(): void {\n const input: InputProcessorOrWorkflow[] = [];\n const output: OutputProcessorOrWorkflow[] = [];\n for (const live of this.#live.values()) {\n // Only started providers contribute: one that has not been handed Mastra\n // yet has no storage, so running its processors would fail on the first\n // request rather than wait for the lifecycle to complete.\n if (!live.started) continue;\n // Guarded like every other provider call: a throwing getter drops that\n // provider's processors from this rebuild instead of unwinding the whole\n // lane mid-sync. Both getters are read before either lane is touched so a\n // provider never contributes input processors without its output ones.\n try {\n const providerInput = live.provider.getInputProcessors?.() ?? [];\n const providerOutput = live.provider.getOutputProcessors?.() ?? [];\n input.push(...providerInput);\n output.push(...providerOutput);\n } catch (error) {\n this.#onError(\n `Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to provide processors:`,\n error,\n );\n }\n }\n this.#inputProcessors = input;\n this.#outputProcessors = output;\n }\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAa,mBAAb,MAA8B;CAC5B,wBAAiB,IAAI,IAA0B;CAC/C;CACA;CACA;CACA;CAIA,mBAA+C,CAAC;CAChD,oBAAiD,CAAC;CAElD,YAAY,UAAmC,CAAC,GAAG;EACjD,KAAK,uBAAuB,IAAI,IAAI,QAAQ,uBAAuB,CAAC,CAAC;EACrE,KAAK,WACH,QAAQ,aACN,SAAS,UAAU;GACnB,QAAQ,KAAK,SAAS,KAAK;EAC7B;CACJ;CAEA,qBAA0D;EACxD,OAAO,KAAK;CACd;CAEA,sBAA4D;EAC1D,OAAO,KAAK;CACd;;;;;;;;;;;;CAaA,KAAK,eAAmE;EACtE,MAAM,uBAAO,IAAI,IAAY;EAE7B,KAAK,MAAM,EAAE,UAAU,cAAc,OAAO,cAAc,eAAe;GACvE,MAAM,MAAM,GAAG,SAAS,IAAI,SAAS;GACrC,KAAK,IAAI,GAAG;GAEZ,MAAM,OAAO,KAAK,MAAM,IA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C3B;AACF"}
|
|
@@ -41,7 +41,8 @@ function parseBoundedInteger(env, name, fallback, minimum, maximum) {
|
|
|
41
41
|
}
|
|
42
42
|
function getDefaultProfileParentDirectory() {
|
|
43
43
|
if (process.env.MASTRA_APP_DATA_DIR) return join(process.env.MASTRA_APP_DATA_DIR, "profiles");
|
|
44
|
-
|
|
44
|
+
const baseDirectory = platform$1 === "darwin" ? join(homedir(), "Library", "Application Support") : platform$1 === "win32" ? process.env.APPDATA || join(homedir(), "AppData", "Roaming") : process.env.XDG_DATA_HOME || join(homedir(), ".local", "share");
|
|
45
|
+
return join(baseDirectory, "mastracode", "profiles");
|
|
45
46
|
}
|
|
46
47
|
function parseProcessMemoryDiagnosticsEnvironment(env = process.env) {
|
|
47
48
|
return {
|