@mastra/code-sdk 1.21.0-alpha.6 → 1.21.0-alpha.8
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 +0 -2
- package/dist/acp/errors.js +0 -2
- package/dist/acp/event-mapper.js +0 -2
- package/dist/acp/index.js +0 -2
- package/dist/acp/runtime.js +0 -2
- package/dist/acp/server.js +0 -2
- package/dist/acp/skills.js +0 -2
- package/dist/agent-connections/messaging-processor.js +0 -2
- package/dist/agent-connections/ownership.js +0 -2
- package/dist/agent-connections/registry.js +0 -2
- package/dist/agent-connections/session-advertisement.js +0 -2
- package/dist/agent-connections/signal-provider.js +0 -2
- package/dist/agent-connections/state-processor.js +0 -2
- package/dist/agent-connections/thread-state.js +0 -2
- package/dist/agent-connections/tools.js +0 -2
- package/dist/agent-connections/types.js +0 -2
- package/dist/agent-connections/untrusted-text.js +0 -2
- package/dist/agents/background-completion-events.js +0 -2
- package/dist/agents/background-completion.js +0 -2
- package/dist/agents/context-audit.js +0 -2
- package/dist/agents/credential-resolver.js +0 -2
- package/dist/agents/custom-provider-source.js +0 -2
- package/dist/agents/fastembed-subprocess.d.ts +21 -0
- package/dist/agents/fastembed-subprocess.js +88 -8
- package/dist/agents/instructions.js +0 -2
- package/dist/agents/mastracode-gateway.d.ts +3 -1
- package/dist/agents/mastracode-gateway.js +11 -5
- package/dist/agents/memory.js +0 -2
- package/dist/agents/model.js +15 -8
- package/dist/agents/modes/build.js +0 -2
- package/dist/agents/modes/explore.js +0 -2
- package/dist/agents/modes/plan.js +0 -2
- package/dist/agents/prompts/agent-instructions.js +0 -2
- package/dist/agents/prompts/build.js +0 -2
- package/dist/agents/prompts/fast.js +0 -2
- package/dist/agents/prompts/index.js +0 -2
- package/dist/agents/prompts/model.js +0 -2
- package/dist/agents/prompts/plan.js +0 -2
- package/dist/agents/prompts/tool-guidance.js +0 -2
- package/dist/agents/sandbox-filesystem.js +0 -2
- package/dist/agents/subagents/execute.js +0 -2
- package/dist/agents/subagents/explore.js +0 -2
- package/dist/agents/subagents/index.js +0 -2
- package/dist/agents/subagents/plan.js +0 -2
- package/dist/agents/thread-caveman-state.js +0 -2
- package/dist/agents/tool-availability.js +0 -2
- package/dist/agents/tools.js +0 -2
- package/dist/agents/workflow-builder-agent.js +0 -2
- package/dist/agents/workspace.js +0 -2
- package/dist/analytics.js +0 -2
- package/dist/auth/account-rotation-processor.js +3 -5
- package/dist/auth/account-routing-context.js +0 -2
- package/dist/auth/authorization-input.js +0 -2
- package/dist/auth/device-code.js +0 -2
- package/dist/auth/pkce.js +0 -2
- package/dist/auth/provider-auth-error.js +0 -2
- package/dist/auth/providers/anthropic.js +0 -2
- package/dist/auth/providers/github-copilot.js +0 -2
- package/dist/auth/providers/kimi-coding.js +0 -2
- package/dist/auth/providers/openai-codex.js +0 -2
- package/dist/auth/providers/xai.js +0 -2
- package/dist/auth/storage.js +0 -2
- package/dist/clipboard/index.js +0 -2
- package/dist/constants.js +0 -2
- package/dist/error-classification.js +0 -2
- package/dist/evals/context-builder.js +0 -2
- package/dist/evals/scorers/classify-command.js +0 -2
- package/dist/evals/scorers/efficiency.js +0 -2
- package/dist/evals/scorers/extract-tools.js +0 -2
- package/dist/evals/scorers/outcome.js +0 -2
- package/dist/experimental-agent.js +0 -2
- package/dist/factory/client.js +0 -2
- package/dist/factory/remote-controller.js +0 -2
- package/dist/factory/remote-session.js +0 -2
- package/dist/goal-manager.js +0 -2
- package/dist/goal-signal.js +0 -2
- package/dist/headless/cli.js +5 -2
- package/dist/headless/flags.js +0 -2
- package/dist/headless/format.js +0 -2
- package/dist/headless/policy.js +0 -2
- package/dist/headless/run-mc.js +7 -4
- package/dist/headless/types.js +0 -2
- package/dist/hooks/config.js +0 -2
- package/dist/hooks/executor.js +0 -2
- package/dist/hooks/manager.js +0 -2
- package/dist/hooks/types.js +0 -2
- package/dist/index.js +5 -5
- package/dist/ipc/ipc-reporter.js +0 -2
- package/dist/knowledge-inspector.js +0 -2
- package/dist/knowledge-scope-id.js +0 -2
- package/dist/knowledge-scope.js +0 -2
- package/dist/lsp/client.js +0 -2
- package/dist/lsp/language.js +0 -2
- package/dist/lsp/manager.js +0 -2
- package/dist/lsp/server.js +0 -2
- package/dist/lsp/workspace.js +0 -2
- package/dist/mcp/config.js +0 -2
- package/dist/mcp/manager.js +0 -2
- package/dist/mcp/state.js +0 -2
- package/dist/onboarding/custom-packs.js +0 -2
- package/dist/onboarding/custom-providers.js +0 -2
- package/dist/onboarding/om-settings.js +0 -2
- package/dist/onboarding/pack-activation.js +0 -2
- package/dist/onboarding/packs.js +0 -2
- package/dist/onboarding/settings.js +0 -2
- package/dist/permissions.js +0 -2
- package/dist/platform/index.js +0 -2
- package/dist/plugin.js +0 -2
- package/dist/plugins/dependencies.js +0 -2
- package/dist/plugins/install.js +0 -2
- package/dist/plugins/loader.js +0 -2
- package/dist/plugins/manager.js +0 -2
- package/dist/plugins/manifest.js +0 -2
- package/dist/plugins/package-link.js +0 -2
- package/dist/plugins/paths.js +0 -2
- package/dist/plugins/registry.js +0 -2
- package/dist/plugins/scaffold.js +0 -2
- package/dist/plugins/signal-lane.js +0 -2
- package/dist/process-memory-diagnostics.js +0 -2
- package/dist/processors/plan-rejection-abort.js +0 -2
- package/dist/providers/amazon-bedrock-gateway.js +0 -2
- package/dist/providers/amazon-bedrock.js +0 -2
- package/dist/providers/anthropic-prompt-cache.js +0 -2
- package/dist/providers/anthropic-thinking.js +0 -2
- package/dist/providers/claude-max.js +0 -2
- package/dist/providers/github-copilot-gateway.js +0 -2
- package/dist/providers/github-copilot.js +0 -2
- package/dist/providers/google-thinking.js +0 -2
- package/dist/providers/google-vertex-gateway.js +0 -2
- package/dist/providers/google-vertex.js +0 -2
- package/dist/providers/kimi-coding.js +0 -2
- package/dist/providers/model-ids.d.ts +22 -0
- package/dist/providers/model-ids.js +55 -3
- package/dist/providers/openai-codex.d.ts +5 -1
- package/dist/providers/openai-codex.js +7 -6
- package/dist/providers/provider-thinking.js +0 -2
- package/dist/providers/thinking-request.js +0 -2
- package/dist/providers/xai.js +0 -2
- package/dist/schedules/interval.js +0 -2
- package/dist/schedules/prompt.js +0 -2
- package/dist/schedules/run-script.js +0 -2
- package/dist/schedules/scheduler.js +0 -2
- package/dist/schedules/tools.js +0 -2
- package/dist/schema.js +0 -2
- package/dist/theme-palette.js +0 -2
- package/dist/thinking-catalog.d.ts +2 -2
- package/dist/thinking-catalog.js +5 -4
- package/dist/thinking.js +0 -2
- package/dist/tool-names.js +0 -2
- package/dist/tools/request-sandbox-access.js +0 -2
- package/dist/tools/utils.js +0 -2
- package/dist/tools/web-search.js +0 -2
- package/dist/tools/workflows/create-workflow.js +0 -2
- package/dist/tools/workflows/delete-workflow.js +0 -2
- package/dist/tools/workflows/ephemeral-memory.js +0 -2
- package/dist/tools/workflows/extract-json-schema.js +0 -2
- package/dist/tools/workflows/get-workflow.js +0 -2
- package/dist/tools/workflows/list-available-agents.js +0 -2
- package/dist/tools/workflows/list-available-classifiers.js +0 -2
- package/dist/tools/workflows/list-available-tools.js +0 -2
- package/dist/tools/workflows/list-available-workflows.js +0 -2
- package/dist/tools/workflows/list-workflows.js +0 -2
- package/dist/tools/workflows/run-workflow.js +0 -2
- package/dist/tools/workflows/save-workflow.js +0 -2
- package/dist/tools/workflows/tool-ids.js +0 -2
- package/dist/utils/binaries.js +0 -2
- package/dist/utils/debug-log.js +0 -2
- package/dist/utils/discarding-scores-storage.js +0 -2
- package/dist/utils/errors.js +0 -2
- package/dist/utils/gateway-sync.js +0 -2
- package/dist/utils/local-observability.js +0 -2
- package/dist/utils/maintenance-lock.js +0 -2
- package/dist/utils/notification-dispatch.js +0 -2
- package/dist/utils/open-url.js +0 -2
- package/dist/utils/path-security.js +0 -2
- package/dist/utils/plan-diff.js +0 -2
- package/dist/utils/plans.js +0 -2
- package/dist/utils/project.js +0 -2
- package/dist/utils/prune-cli.js +0 -2
- package/dist/utils/signals-pubsub.js +0 -2
- package/dist/utils/slash-command-loader.js +0 -2
- package/dist/utils/slash-command-processor.js +0 -2
- package/dist/utils/stdin-pipe.js +0 -2
- package/dist/utils/storage-factory.js +0 -2
- package/dist/utils/storage-maintenance.js +0 -2
- package/dist/utils/thread-lock.js +0 -2
- package/dist/utils/token-estimator.js +0 -2
- package/dist/utils/update-check.js +0 -2
- package/dist/utils/wake-session.js +0 -2
- package/dist/voice/stt-registry.js +0 -2
- package/dist/voice/transcribe.js +0 -2
- package/dist/workflows/register-primitives.js +0 -2
- package/dist/workflows/service.js +0 -2
- package/package.json +24 -23
- package/dist/acp/agent.d.ts.map +0 -1
- package/dist/acp/agent.js.map +0 -1
- package/dist/acp/errors.d.ts.map +0 -1
- package/dist/acp/errors.js.map +0 -1
- package/dist/acp/event-mapper.d.ts.map +0 -1
- package/dist/acp/event-mapper.js.map +0 -1
- package/dist/acp/index.d.ts.map +0 -1
- package/dist/acp/index.js.map +0 -1
- package/dist/acp/runtime.d.ts.map +0 -1
- package/dist/acp/runtime.js.map +0 -1
- package/dist/acp/server.d.ts.map +0 -1
- package/dist/acp/server.js.map +0 -1
- package/dist/acp/skills.d.ts.map +0 -1
- package/dist/acp/skills.js.map +0 -1
- package/dist/acp.d.ts.map +0 -1
- package/dist/agent-connections/messaging-processor.d.ts.map +0 -1
- package/dist/agent-connections/messaging-processor.js.map +0 -1
- package/dist/agent-connections/ownership.d.ts.map +0 -1
- package/dist/agent-connections/ownership.js.map +0 -1
- package/dist/agent-connections/registry.d.ts.map +0 -1
- package/dist/agent-connections/registry.js.map +0 -1
- package/dist/agent-connections/session-advertisement.d.ts.map +0 -1
- package/dist/agent-connections/session-advertisement.js.map +0 -1
- package/dist/agent-connections/signal-provider.d.ts.map +0 -1
- package/dist/agent-connections/signal-provider.js.map +0 -1
- package/dist/agent-connections/state-processor.d.ts.map +0 -1
- package/dist/agent-connections/state-processor.js.map +0 -1
- package/dist/agent-connections/thread-state.d.ts.map +0 -1
- package/dist/agent-connections/thread-state.js.map +0 -1
- package/dist/agent-connections/tools.d.ts.map +0 -1
- package/dist/agent-connections/tools.js.map +0 -1
- package/dist/agent-connections/types.d.ts.map +0 -1
- package/dist/agent-connections/types.js.map +0 -1
- package/dist/agent-connections/untrusted-text.d.ts.map +0 -1
- package/dist/agent-connections/untrusted-text.js.map +0 -1
- package/dist/agents/background-completion-events.d.ts.map +0 -1
- package/dist/agents/background-completion-events.js.map +0 -1
- package/dist/agents/background-completion.d.ts.map +0 -1
- package/dist/agents/background-completion.js.map +0 -1
- package/dist/agents/context-audit.d.ts.map +0 -1
- package/dist/agents/context-audit.js.map +0 -1
- package/dist/agents/credential-resolver.d.ts.map +0 -1
- package/dist/agents/credential-resolver.js.map +0 -1
- package/dist/agents/custom-provider-source.d.ts.map +0 -1
- package/dist/agents/custom-provider-source.js.map +0 -1
- package/dist/agents/fastembed-subprocess.d.ts.map +0 -1
- package/dist/agents/fastembed-subprocess.js.map +0 -1
- package/dist/agents/instructions.d.ts.map +0 -1
- package/dist/agents/instructions.js.map +0 -1
- package/dist/agents/mastracode-gateway.d.ts.map +0 -1
- package/dist/agents/mastracode-gateway.js.map +0 -1
- package/dist/agents/memory.d.ts.map +0 -1
- package/dist/agents/memory.js.map +0 -1
- package/dist/agents/model.d.ts.map +0 -1
- package/dist/agents/model.js.map +0 -1
- package/dist/agents/modes/build.d.ts.map +0 -1
- package/dist/agents/modes/build.js.map +0 -1
- package/dist/agents/modes/explore.d.ts.map +0 -1
- package/dist/agents/modes/explore.js.map +0 -1
- package/dist/agents/modes/plan.d.ts.map +0 -1
- package/dist/agents/modes/plan.js.map +0 -1
- package/dist/agents/prompts/agent-instructions.d.ts.map +0 -1
- package/dist/agents/prompts/agent-instructions.js.map +0 -1
- package/dist/agents/prompts/build.d.ts.map +0 -1
- package/dist/agents/prompts/build.js.map +0 -1
- package/dist/agents/prompts/fast.d.ts.map +0 -1
- package/dist/agents/prompts/fast.js.map +0 -1
- package/dist/agents/prompts/index.d.ts.map +0 -1
- package/dist/agents/prompts/index.js.map +0 -1
- package/dist/agents/prompts/model.d.ts.map +0 -1
- package/dist/agents/prompts/model.js.map +0 -1
- package/dist/agents/prompts/plan.d.ts.map +0 -1
- package/dist/agents/prompts/plan.js.map +0 -1
- package/dist/agents/prompts/tool-guidance.d.ts.map +0 -1
- package/dist/agents/prompts/tool-guidance.js.map +0 -1
- package/dist/agents/sandbox-filesystem.d.ts.map +0 -1
- package/dist/agents/sandbox-filesystem.js.map +0 -1
- package/dist/agents/subagents/execute.d.ts.map +0 -1
- package/dist/agents/subagents/execute.js.map +0 -1
- package/dist/agents/subagents/explore.d.ts.map +0 -1
- package/dist/agents/subagents/explore.js.map +0 -1
- package/dist/agents/subagents/index.d.ts.map +0 -1
- package/dist/agents/subagents/index.js.map +0 -1
- package/dist/agents/subagents/plan.d.ts.map +0 -1
- package/dist/agents/subagents/plan.js.map +0 -1
- package/dist/agents/thread-caveman-state.d.ts.map +0 -1
- package/dist/agents/thread-caveman-state.js.map +0 -1
- package/dist/agents/tool-availability.d.ts.map +0 -1
- package/dist/agents/tool-availability.js.map +0 -1
- package/dist/agents/tools.d.ts.map +0 -1
- package/dist/agents/tools.js.map +0 -1
- package/dist/agents/workflow-builder-agent.d.ts.map +0 -1
- package/dist/agents/workflow-builder-agent.js.map +0 -1
- package/dist/agents/workspace.d.ts.map +0 -1
- package/dist/agents/workspace.js.map +0 -1
- package/dist/analytics.d.ts.map +0 -1
- package/dist/analytics.js.map +0 -1
- package/dist/auth/account-rotation-processor.d.ts.map +0 -1
- package/dist/auth/account-rotation-processor.js.map +0 -1
- package/dist/auth/account-routing-context.d.ts.map +0 -1
- package/dist/auth/account-routing-context.js.map +0 -1
- package/dist/auth/authorization-input.d.ts.map +0 -1
- package/dist/auth/authorization-input.js.map +0 -1
- package/dist/auth/device-code.d.ts.map +0 -1
- package/dist/auth/device-code.js.map +0 -1
- package/dist/auth/index.d.ts.map +0 -1
- package/dist/auth/pkce.d.ts.map +0 -1
- package/dist/auth/pkce.js.map +0 -1
- package/dist/auth/provider-auth-error.d.ts.map +0 -1
- package/dist/auth/provider-auth-error.js.map +0 -1
- package/dist/auth/providers/anthropic.d.ts.map +0 -1
- package/dist/auth/providers/anthropic.js.map +0 -1
- package/dist/auth/providers/github-copilot.d.ts.map +0 -1
- package/dist/auth/providers/github-copilot.js.map +0 -1
- package/dist/auth/providers/kimi-coding.d.ts.map +0 -1
- package/dist/auth/providers/kimi-coding.js.map +0 -1
- package/dist/auth/providers/openai-codex.d.ts.map +0 -1
- package/dist/auth/providers/openai-codex.js.map +0 -1
- package/dist/auth/providers/xai.d.ts.map +0 -1
- package/dist/auth/providers/xai.js.map +0 -1
- package/dist/auth/storage.d.ts.map +0 -1
- package/dist/auth/storage.js.map +0 -1
- package/dist/auth/types.d.ts.map +0 -1
- package/dist/clipboard/index.d.ts.map +0 -1
- package/dist/clipboard/index.js.map +0 -1
- package/dist/constants.d.ts.map +0 -1
- package/dist/constants.js.map +0 -1
- package/dist/error-classification.d.ts.map +0 -1
- package/dist/error-classification.js.map +0 -1
- package/dist/evals/context-builder.d.ts.map +0 -1
- package/dist/evals/context-builder.js.map +0 -1
- package/dist/evals/index.d.ts.map +0 -1
- package/dist/evals/scorers/classify-command.d.ts.map +0 -1
- package/dist/evals/scorers/classify-command.js.map +0 -1
- package/dist/evals/scorers/efficiency.d.ts.map +0 -1
- package/dist/evals/scorers/efficiency.js.map +0 -1
- package/dist/evals/scorers/extract-tools.d.ts.map +0 -1
- package/dist/evals/scorers/extract-tools.js.map +0 -1
- package/dist/evals/scorers/index.d.ts.map +0 -1
- package/dist/evals/scorers/outcome.d.ts.map +0 -1
- package/dist/evals/scorers/outcome.js.map +0 -1
- package/dist/experimental-agent.d.ts.map +0 -1
- package/dist/experimental-agent.js.map +0 -1
- package/dist/factory/client.d.ts.map +0 -1
- package/dist/factory/client.js.map +0 -1
- package/dist/factory/remote-controller.d.ts.map +0 -1
- package/dist/factory/remote-controller.js.map +0 -1
- package/dist/factory/remote-session.d.ts.map +0 -1
- package/dist/factory/remote-session.js.map +0 -1
- package/dist/goal-manager.d.ts.map +0 -1
- package/dist/goal-manager.js.map +0 -1
- package/dist/goal-signal.d.ts.map +0 -1
- package/dist/goal-signal.js.map +0 -1
- package/dist/headless/cli.d.ts.map +0 -1
- package/dist/headless/cli.js.map +0 -1
- package/dist/headless/flags.d.ts.map +0 -1
- package/dist/headless/flags.js.map +0 -1
- package/dist/headless/format.d.ts.map +0 -1
- package/dist/headless/format.js.map +0 -1
- package/dist/headless/index.d.ts.map +0 -1
- package/dist/headless/policy.d.ts.map +0 -1
- package/dist/headless/policy.js.map +0 -1
- package/dist/headless/run-mc.d.ts.map +0 -1
- package/dist/headless/run-mc.js.map +0 -1
- package/dist/headless/types.d.ts.map +0 -1
- package/dist/headless/types.js.map +0 -1
- package/dist/hooks/config.d.ts.map +0 -1
- package/dist/hooks/config.js.map +0 -1
- package/dist/hooks/executor.d.ts.map +0 -1
- package/dist/hooks/executor.js.map +0 -1
- package/dist/hooks/index.d.ts.map +0 -1
- package/dist/hooks/manager.d.ts.map +0 -1
- package/dist/hooks/manager.js.map +0 -1
- package/dist/hooks/types.d.ts.map +0 -1
- package/dist/hooks/types.js.map +0 -1
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/ipc/ipc-reporter.d.ts.map +0 -1
- package/dist/ipc/ipc-reporter.js.map +0 -1
- package/dist/knowledge-inspector.d.ts.map +0 -1
- package/dist/knowledge-inspector.js.map +0 -1
- package/dist/knowledge-scope-id.d.ts.map +0 -1
- package/dist/knowledge-scope-id.js.map +0 -1
- package/dist/knowledge-scope.d.ts.map +0 -1
- package/dist/knowledge-scope.js.map +0 -1
- package/dist/lsp/client.d.ts.map +0 -1
- package/dist/lsp/client.js.map +0 -1
- package/dist/lsp/index.d.ts.map +0 -1
- package/dist/lsp/language.d.ts.map +0 -1
- package/dist/lsp/language.js.map +0 -1
- package/dist/lsp/manager.d.ts.map +0 -1
- package/dist/lsp/manager.js.map +0 -1
- package/dist/lsp/server.d.ts.map +0 -1
- package/dist/lsp/server.js.map +0 -1
- package/dist/lsp/workspace.d.ts.map +0 -1
- package/dist/lsp/workspace.js.map +0 -1
- package/dist/mcp/config.d.ts.map +0 -1
- package/dist/mcp/config.js.map +0 -1
- package/dist/mcp/index.d.ts.map +0 -1
- package/dist/mcp/manager.d.ts.map +0 -1
- package/dist/mcp/manager.js.map +0 -1
- package/dist/mcp/state.d.ts.map +0 -1
- package/dist/mcp/state.js.map +0 -1
- package/dist/mcp/types.d.ts.map +0 -1
- package/dist/onboarding/custom-packs.d.ts.map +0 -1
- package/dist/onboarding/custom-packs.js.map +0 -1
- package/dist/onboarding/custom-providers.d.ts.map +0 -1
- package/dist/onboarding/custom-providers.js.map +0 -1
- package/dist/onboarding/index.d.ts.map +0 -1
- package/dist/onboarding/om-settings.d.ts.map +0 -1
- package/dist/onboarding/om-settings.js.map +0 -1
- package/dist/onboarding/pack-activation.d.ts.map +0 -1
- package/dist/onboarding/pack-activation.js.map +0 -1
- package/dist/onboarding/packs.d.ts.map +0 -1
- package/dist/onboarding/packs.js.map +0 -1
- package/dist/onboarding/settings.d.ts.map +0 -1
- package/dist/onboarding/settings.js.map +0 -1
- package/dist/permissions.d.ts.map +0 -1
- package/dist/permissions.js.map +0 -1
- package/dist/platform/index.d.ts.map +0 -1
- package/dist/platform/index.js.map +0 -1
- package/dist/plugin.d.ts.map +0 -1
- package/dist/plugin.js.map +0 -1
- package/dist/plugins/dependencies.d.ts.map +0 -1
- package/dist/plugins/dependencies.js.map +0 -1
- package/dist/plugins/install.d.ts.map +0 -1
- package/dist/plugins/install.js.map +0 -1
- package/dist/plugins/loader.d.ts.map +0 -1
- package/dist/plugins/loader.js.map +0 -1
- package/dist/plugins/manager.d.ts.map +0 -1
- package/dist/plugins/manager.js.map +0 -1
- package/dist/plugins/manifest.d.ts.map +0 -1
- package/dist/plugins/manifest.js.map +0 -1
- package/dist/plugins/package-link.d.ts.map +0 -1
- package/dist/plugins/package-link.js.map +0 -1
- package/dist/plugins/paths.d.ts.map +0 -1
- package/dist/plugins/paths.js.map +0 -1
- package/dist/plugins/registry.d.ts.map +0 -1
- package/dist/plugins/registry.js.map +0 -1
- package/dist/plugins/scaffold.d.ts.map +0 -1
- package/dist/plugins/scaffold.js.map +0 -1
- package/dist/plugins/signal-lane.d.ts.map +0 -1
- package/dist/plugins/signal-lane.js.map +0 -1
- package/dist/plugins/types.d.ts.map +0 -1
- package/dist/process-memory-diagnostics.d.ts.map +0 -1
- package/dist/process-memory-diagnostics.js.map +0 -1
- package/dist/processors/plan-rejection-abort.d.ts.map +0 -1
- package/dist/processors/plan-rejection-abort.js.map +0 -1
- package/dist/providers/amazon-bedrock-gateway.d.ts.map +0 -1
- package/dist/providers/amazon-bedrock-gateway.js.map +0 -1
- package/dist/providers/amazon-bedrock.d.ts.map +0 -1
- package/dist/providers/amazon-bedrock.js.map +0 -1
- package/dist/providers/anthropic-prompt-cache.d.ts.map +0 -1
- package/dist/providers/anthropic-prompt-cache.js.map +0 -1
- package/dist/providers/anthropic-thinking.d.ts.map +0 -1
- package/dist/providers/anthropic-thinking.js.map +0 -1
- package/dist/providers/claude-max.d.ts.map +0 -1
- package/dist/providers/claude-max.js.map +0 -1
- package/dist/providers/github-copilot-gateway.d.ts.map +0 -1
- package/dist/providers/github-copilot-gateway.js.map +0 -1
- package/dist/providers/github-copilot.d.ts.map +0 -1
- package/dist/providers/github-copilot.js.map +0 -1
- package/dist/providers/google-thinking.d.ts.map +0 -1
- package/dist/providers/google-thinking.js.map +0 -1
- package/dist/providers/google-vertex-gateway.d.ts.map +0 -1
- package/dist/providers/google-vertex-gateway.js.map +0 -1
- package/dist/providers/google-vertex.d.ts.map +0 -1
- package/dist/providers/google-vertex.js.map +0 -1
- package/dist/providers/kimi-coding.d.ts.map +0 -1
- package/dist/providers/kimi-coding.js.map +0 -1
- package/dist/providers/model-ids.d.ts.map +0 -1
- package/dist/providers/model-ids.js.map +0 -1
- package/dist/providers/openai-codex.d.ts.map +0 -1
- package/dist/providers/openai-codex.js.map +0 -1
- package/dist/providers/provider-thinking.d.ts.map +0 -1
- package/dist/providers/provider-thinking.js.map +0 -1
- package/dist/providers/thinking-request.d.ts.map +0 -1
- package/dist/providers/thinking-request.js.map +0 -1
- package/dist/providers/xai.d.ts.map +0 -1
- package/dist/providers/xai.js.map +0 -1
- package/dist/schedules/index.d.ts.map +0 -1
- package/dist/schedules/interval.d.ts.map +0 -1
- package/dist/schedules/interval.js.map +0 -1
- package/dist/schedules/prompt.d.ts.map +0 -1
- package/dist/schedules/prompt.js.map +0 -1
- package/dist/schedules/run-script.d.ts.map +0 -1
- package/dist/schedules/run-script.js.map +0 -1
- package/dist/schedules/scheduler.d.ts.map +0 -1
- package/dist/schedules/scheduler.js.map +0 -1
- package/dist/schedules/tools.d.ts.map +0 -1
- package/dist/schedules/tools.js.map +0 -1
- package/dist/schema.d.ts.map +0 -1
- package/dist/schema.js.map +0 -1
- package/dist/theme-palette.d.ts.map +0 -1
- package/dist/theme-palette.js.map +0 -1
- package/dist/thinking-catalog.d.ts.map +0 -1
- package/dist/thinking-catalog.js.map +0 -1
- package/dist/thinking.d.ts.map +0 -1
- package/dist/thinking.js.map +0 -1
- package/dist/tool-names.d.ts.map +0 -1
- package/dist/tool-names.js.map +0 -1
- package/dist/tools/index.d.ts.map +0 -1
- package/dist/tools/request-sandbox-access.d.ts.map +0 -1
- package/dist/tools/request-sandbox-access.js.map +0 -1
- package/dist/tools/utils.d.ts.map +0 -1
- package/dist/tools/utils.js.map +0 -1
- package/dist/tools/web-search.d.ts.map +0 -1
- package/dist/tools/web-search.js.map +0 -1
- package/dist/tools/workflows/create-workflow.d.ts.map +0 -1
- package/dist/tools/workflows/create-workflow.js.map +0 -1
- package/dist/tools/workflows/delete-workflow.d.ts.map +0 -1
- package/dist/tools/workflows/delete-workflow.js.map +0 -1
- package/dist/tools/workflows/ephemeral-memory.d.ts.map +0 -1
- package/dist/tools/workflows/ephemeral-memory.js.map +0 -1
- package/dist/tools/workflows/extract-json-schema.d.ts.map +0 -1
- package/dist/tools/workflows/extract-json-schema.js.map +0 -1
- package/dist/tools/workflows/get-workflow.d.ts.map +0 -1
- package/dist/tools/workflows/get-workflow.js.map +0 -1
- package/dist/tools/workflows/list-available-agents.d.ts.map +0 -1
- package/dist/tools/workflows/list-available-agents.js.map +0 -1
- package/dist/tools/workflows/list-available-classifiers.d.ts.map +0 -1
- package/dist/tools/workflows/list-available-classifiers.js.map +0 -1
- package/dist/tools/workflows/list-available-tools.d.ts.map +0 -1
- package/dist/tools/workflows/list-available-tools.js.map +0 -1
- package/dist/tools/workflows/list-available-workflows.d.ts.map +0 -1
- package/dist/tools/workflows/list-available-workflows.js.map +0 -1
- package/dist/tools/workflows/list-workflows.d.ts.map +0 -1
- package/dist/tools/workflows/list-workflows.js.map +0 -1
- package/dist/tools/workflows/run-workflow.d.ts.map +0 -1
- package/dist/tools/workflows/run-workflow.js.map +0 -1
- package/dist/tools/workflows/save-workflow.d.ts.map +0 -1
- package/dist/tools/workflows/save-workflow.js.map +0 -1
- package/dist/tools/workflows/tool-ids.d.ts.map +0 -1
- package/dist/tools/workflows/tool-ids.js.map +0 -1
- package/dist/utils/binaries.d.ts.map +0 -1
- package/dist/utils/binaries.js.map +0 -1
- package/dist/utils/debug-log.d.ts.map +0 -1
- package/dist/utils/debug-log.js.map +0 -1
- package/dist/utils/discarding-scores-storage.d.ts.map +0 -1
- package/dist/utils/discarding-scores-storage.js.map +0 -1
- package/dist/utils/errors.d.ts.map +0 -1
- package/dist/utils/errors.js.map +0 -1
- package/dist/utils/gateway-sync.d.ts.map +0 -1
- package/dist/utils/gateway-sync.js.map +0 -1
- package/dist/utils/local-observability.d.ts.map +0 -1
- package/dist/utils/local-observability.js.map +0 -1
- package/dist/utils/maintenance-lock.d.ts.map +0 -1
- package/dist/utils/maintenance-lock.js.map +0 -1
- package/dist/utils/notification-dispatch.d.ts.map +0 -1
- package/dist/utils/notification-dispatch.js.map +0 -1
- package/dist/utils/open-url.d.ts.map +0 -1
- package/dist/utils/open-url.js.map +0 -1
- package/dist/utils/path-security.d.ts.map +0 -1
- package/dist/utils/path-security.js.map +0 -1
- package/dist/utils/plan-diff.d.ts.map +0 -1
- package/dist/utils/plan-diff.js.map +0 -1
- package/dist/utils/plans.d.ts.map +0 -1
- package/dist/utils/plans.js.map +0 -1
- package/dist/utils/project.d.ts.map +0 -1
- package/dist/utils/project.js.map +0 -1
- package/dist/utils/prune-cli.d.ts.map +0 -1
- package/dist/utils/prune-cli.js.map +0 -1
- package/dist/utils/signals-pubsub.d.ts.map +0 -1
- package/dist/utils/signals-pubsub.js.map +0 -1
- package/dist/utils/slash-command-loader.d.ts.map +0 -1
- package/dist/utils/slash-command-loader.js.map +0 -1
- package/dist/utils/slash-command-processor.d.ts.map +0 -1
- package/dist/utils/slash-command-processor.js.map +0 -1
- package/dist/utils/stdin-pipe.d.ts.map +0 -1
- package/dist/utils/stdin-pipe.js.map +0 -1
- package/dist/utils/storage-factory.d.ts.map +0 -1
- package/dist/utils/storage-factory.js.map +0 -1
- package/dist/utils/storage-maintenance.d.ts.map +0 -1
- package/dist/utils/storage-maintenance.js.map +0 -1
- package/dist/utils/thread-lock.d.ts.map +0 -1
- package/dist/utils/thread-lock.js.map +0 -1
- package/dist/utils/token-estimator.d.ts.map +0 -1
- package/dist/utils/token-estimator.js.map +0 -1
- package/dist/utils/update-check.d.ts.map +0 -1
- package/dist/utils/update-check.js.map +0 -1
- package/dist/utils/wake-session.d.ts.map +0 -1
- package/dist/utils/wake-session.js.map +0 -1
- package/dist/voice/stt-registry.d.ts.map +0 -1
- package/dist/voice/stt-registry.js.map +0 -1
- package/dist/voice/transcribe.d.ts.map +0 -1
- package/dist/voice/transcribe.js.map +0 -1
- package/dist/workflows/register-primitives.d.ts.map +0 -1
- package/dist/workflows/register-primitives.js.map +0 -1
- package/dist/workflows/service.d.ts.map +0 -1
- package/dist/workflows/service.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
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 {\n LoadedPlugin,\n PluginContribution,\n PluginErrorEvent,\n PluginProcessorEntries,\n PluginScope,\n} from './types.js';\n\nconst GITHUB_PLUGIN_POLL_INTERVAL_MS = 60_000;\n// Plugin errors kept for the first listener; a headless embedder never subscribes.\nconst MAX_UNHEARD_PLUGIN_ERRORS = 20;\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 readonly pluginErrorListeners = new Set<(event: PluginErrorEvent) => void>();\n private readonly unheardPluginErrors: PluginErrorEvent[] = [];\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 const previous = this.loadedPlugins;\n this.loadedPlugins = await loadPlugins({ ...this.options, runtime: this.runtime, previous });\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 // Before the reload listeners: one that rejects must not swallow the notice,\n // which is reported only once per distinct error.\n this.reportReloadFailures(previous, 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 /**\n * Notified of plugin problems the user should see. With no listener, they go to\n * `console.warn` so a headless embedder still has a trace, and the most recent\n * ones are handed to the first listener that subscribes: plugin signal providers\n * start while Mastra Code boots, before a UI exists to subscribe.\n */\n onPluginError(listener: (event: PluginErrorEvent) => void): () => void {\n this.pluginErrorListeners.add(listener);\n const unheard = this.unheardPluginErrors.splice(0);\n for (const event of unheard) this.notifyPluginErrorListener(listener, event);\n return () => this.pluginErrorListeners.delete(listener);\n }\n\n reportPluginError(event: PluginErrorEvent): void {\n if (this.pluginErrorListeners.size === 0) {\n console.warn(event.message);\n this.unheardPluginErrors.push(event);\n if (this.unheardPluginErrors.length > MAX_UNHEARD_PLUGIN_ERRORS) this.unheardPluginErrors.shift();\n return;\n }\n for (const listener of this.pluginErrorListeners) this.notifyPluginErrorListener(listener, event);\n }\n\n // A listener that throws must not stop the others, nor the reload or lane cleanup reporting through here.\n private notifyPluginErrorListener(listener: (event: PluginErrorEvent) => void, event: PluginErrorEvent): void {\n try {\n listener(event);\n } catch (error) {\n console.warn(`Plugin error listener failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Reports each reload that kept a plugin's previous load, once per distinct\n * error: a plugin that stays broken across later reloads (another plugin's\n * update, a config edit) must not repeat its notice on every one.\n */\n private reportReloadFailures(previous: LoadedPlugin[], plugins: LoadedPlugin[]): void {\n for (const plugin of plugins) {\n if (plugin.reloadError === undefined) continue;\n const before = previous.find(entry => entry.id === plugin.id && entry.scope === plugin.scope);\n if (before?.reloadError === plugin.reloadError) continue;\n // A kept load that ends up conflicted is not running, so only an active one\n // can say it still is.\n const outcome = plugin.status === 'active' ? ' Still running the previous version.' : '';\n this.reportPluginError({\n pluginId: plugin.id,\n message: `Plugin \"${plugin.name ?? plugin.id}\" failed to reload: ${plugin.reloadError}.${outcome}`,\n });\n }\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 // A kept previous load keeps its stamp too: the source moved, but the\n // contributions are the ones already running and must not be cycled.\n if (plugin.reloadError !== undefined) continue;\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. A plugin\n // whose update failed to load kept its previous version and reports that error instead.\n const updatedPluginNames = this.loadedPlugins\n .filter(\n plugin =>\n plugin.source === 'github' &&\n plugin.status !== 'inactive' &&\n plugin.status !== 'blocked' &&\n plugin.reloadError === undefined &&\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":";;;;;;;;;;AAuBA,MAAM,iCAAiC;AAEvC,MAAM,4BAA4B;AAElC,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;CAkBI;CAjB7B,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,uCAAwC,IAAI,IAAuC;CACnF,sBAA2D,CAAC;CAC5D;CAEA,YAAY,SAAgD;EAA/B,KAAA,UAAA;EAC3B,KAAK,UAAU,QAAQ;CACzB;;;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B,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 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.d.ts","sourceRoot":"","sources":["../../src/plugins/manifest.ts"],"names":[],"mappings":"AAGA,eAAO,MAAM,oBAAoB,4BAA4B,CAAC;AAE9D,MAAM,MAAM,mBAAmB,GAAG;IAChC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,OAAO,EAAE,mBAAmB,EAAE,CAAC;CAChC,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAoB9E;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,IAAI,CAElF;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,mBAAmB,GAAG,IAAI,CAU3F;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS,CAYxF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"manifest.js","names":[],"sources":["../../src/plugins/manifest.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nexport const PLUGIN_MANIFEST_FILE = '.mastracode-plugin.json';\n\nexport type PluginManifestEntry = {\n id: string;\n name?: string;\n entry: string;\n};\n\nexport type PluginManifest = {\n plugins: PluginManifestEntry[];\n};\n\nexport function loadPluginManifest(rootDir: string): PluginManifest | undefined {\n const manifestPath = path.join(rootDir, PLUGIN_MANIFEST_FILE);\n if (!fs.existsSync(manifestPath)) return undefined;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(\n `Could not parse ${PLUGIN_MANIFEST_FILE}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n\n if (!parsed || typeof parsed !== 'object' || !Array.isArray((parsed as { plugins?: unknown }).plugins)) {\n throw new Error(`${PLUGIN_MANIFEST_FILE} must contain a plugins array`);\n }\n\n return {\n plugins: (parsed as { plugins: unknown[] }).plugins.map((entry, index) => validateManifestEntry(entry, index)),\n };\n}\n\nexport function savePluginManifest(rootDir: string, manifest: PluginManifest): void {\n fs.writeFileSync(path.join(rootDir, PLUGIN_MANIFEST_FILE), `${JSON.stringify(manifest, null, 2)}\\n`);\n}\n\nexport function upsertPluginManifestEntry(rootDir: string, entry: PluginManifestEntry): void {\n const manifest = loadPluginManifest(rootDir) ?? { plugins: [] };\n const validatedEntry = validateManifestEntry(entry, manifest.plugins.length);\n const existingIndex = manifest.plugins.findIndex(plugin => plugin.id === validatedEntry.id);\n if (existingIndex >= 0) {\n manifest.plugins[existingIndex] = validateManifestEntry(validatedEntry, existingIndex);\n } else {\n manifest.plugins.push(validatedEntry);\n }\n savePluginManifest(rootDir, manifest);\n}\n\nexport function getSingleManifestPlugin(rootDir: string): PluginManifestEntry | undefined {\n const manifest = loadPluginManifest(rootDir);\n if (!manifest) return undefined;\n if (manifest.plugins.length === 0) return undefined;\n if (manifest.plugins.length > 1) {\n throw new Error(\n `${PLUGIN_MANIFEST_FILE} contains multiple plugins. Provide an entry path for one of: ${manifest.plugins\n .map(plugin => `${plugin.id} (${plugin.entry})`)\n .join(', ')}`,\n );\n }\n return manifest.plugins[0];\n}\n\nfunction validateManifestEntry(entry: unknown, index: number): PluginManifestEntry {\n if (!entry || typeof entry !== 'object') {\n throw new Error(`${PLUGIN_MANIFEST_FILE} plugin at index ${index} must be an object`);\n }\n const candidate = entry as { id?: unknown; name?: unknown; entry?: unknown };\n if (typeof candidate.id !== 'string' || candidate.id.length === 0) {\n throw new Error(`${PLUGIN_MANIFEST_FILE} plugin at index ${index} must include an id`);\n }\n if (typeof candidate.entry !== 'string' || candidate.entry.length === 0) {\n throw new Error(`${PLUGIN_MANIFEST_FILE} plugin ${candidate.id} must include an entry`);\n }\n if (candidate.name !== undefined && typeof candidate.name !== 'string') {\n throw new Error(`${PLUGIN_MANIFEST_FILE} plugin ${candidate.id} name must be a string`);\n }\n return {\n id: candidate.id,\n entry: candidate.entry,\n ...(candidate.name ? { name: candidate.name } : {}),\n };\n}\n"],"mappings":";;;AAGA,MAAa,uBAAuB;AAYpC,SAAgB,mBAAmB,SAA6C;CAC9E,MAAM,eAAe,KAAK,KAAK,SAAS,oBAAoB;CAC5D,IAAI,CAAC,GAAG,WAAW,YAAY,GAAG,OAAO,KAAA;CAEzC,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG,aAAa,cAAc,MAAM,CAAC;CAC3D,SAAS,OAAO;EACd,MAAM,IAAI,MACR,mBAAmB,qBAAqB,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,GACnG;CACF;CAEA,IAAI,CAAC,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAS,OAAiC,OAAO,GACnG,MAAM,IAAI,MAAM,GAAG,qBAAqB,8BAA8B;CAGxE,OAAO,EACL,SAAU,OAAkC,QAAQ,KAAK,OAAO,UAAU,sBAAsB,OAAO,KAAK,CAAC,EAC/G;AACF;AAEA,SAAgB,mBAAmB,SAAiB,UAAgC;CAClF,GAAG,cAAc,KAAK,KAAK,SAAS,oBAAoB,GAAG,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,GAAG;AACrG;AAEA,SAAgB,0BAA0B,SAAiB,OAAkC;CAC3F,MAAM,WAAW,mBAAmB,OAAO,KAAK,EAAE,SAAS,CAAC,EAAE;CAC9D,MAAM,iBAAiB,sBAAsB,OAAO,SAAS,QAAQ,MAAM;CAC3E,MAAM,gBAAgB,S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sourceRoot":"","sources":["../../src/plugins/package-link.ts"],"names":[],"mappings":"AA+BA,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CA4BlE;AAED,wBAAgB,2BAA2B,CAAC,SAAS,EAAE,MAAM,GAAG,IAAI,CAmBnE"}
|
|
@@ -1 +0,0 @@
|
|
|
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,CAAC;CAC1F;CAEF,OAAO;AACT;AAEA,SAAS,gBAAgB,KAAiC;CACxD,MAAM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AM,GAAG,aAAa,iBAAiB,MAAM,CAAC;CAMvE,OAAO,QACL,YAAY,cAAc,cAC1B,YAAY,iBAAiB,cAC7B,YAAY,sBAAsB,UACpC;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/plugins/paths.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,MAAM,iBAAiB,GAAG;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF,wBAAgB,aAAa,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAIpF;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAE5F;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,WAAW,EAAE,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAQpG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"paths.js","names":[],"sources":["../../src/plugins/paths.ts"],"sourcesContent":["import os from 'node:os';\nimport path from 'node:path';\n\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport type { PluginScope, PluginScopePaths } from './types.js';\n\nexport type PluginPathOptions = {\n projectRoot: string;\n configDir?: string;\n homeDir?: string;\n};\n\nexport function getPluginRoot(scope: PluginScope, options: PluginPathOptions): string {\n const configDir = options.configDir ?? DEFAULT_CONFIG_DIR;\n const baseDir = scope === 'project' ? options.projectRoot : (options.homeDir ?? os.homedir());\n return path.join(baseDir, configDir, 'plugins');\n}\n\nexport function getPluginRegistryPath(scope: PluginScope, options: PluginPathOptions): string {\n return path.join(getPluginRoot(scope, options), 'plugins.json');\n}\n\nexport function getPluginScopePaths(scope: PluginScope, options: PluginPathOptions): PluginScopePaths {\n const root = getPluginRoot(scope, options);\n return {\n scope,\n root,\n registryPath: path.join(root, 'plugins.json'),\n sourcesPath: path.join(root, 'sources'),\n };\n}\n"],"mappings":";;;;AAYA,SAAgB,cAAc,OAAoB,SAAoC;CACpF,MAAM,YAAY,QAAQ,aAAA;CAC1B,MAAM,UAAU,UAAU,YAAY,QAAQ,cAAe,QAAQ,WAAW,GAAG,QAAQ;CAC3F,OAAO,KAAK,KAAK,SAAS,WAAW,SAAS;AAChD;AAEA,SAAgB,sBAAsB,OAAoB,SAAoC;CAC5F,OAAO,KAAK,KAAK,cAAc,OAAO,OAAO,GAAG,cAAc;AAChE;AAEA,SAAgB,oBAAoB,OAAoB,SAA8C;CACpG,MAAM,OAAO,cAAc,OAAO,OAAO;CACzC,OAAO;EACL;EACA;EACA,cAAc,KAAK,KAAK,MAAM,cAAc;EAC5C,aAAa,KAAK,KAAK,MAAM,SAAS;CACxC;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/plugins/registry.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,qBAAqB,EAAE,cAAc,EAAE,2BAA2B,EAAE,MAAM,YAAY,CAAC;AAErG,eAAO,MAAM,qBAAqB,EAAE,cAAqD,CAAC;AAE1F,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,GAAG,cAAc,CAQvE;AAED,wBAAgB,kBAAkB,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,cAAc,GAAG,IAAI,CAGvF;AAED,wBAAgB,qBAAqB,CACnC,cAAc,EAAE,cAAc,EAC9B,eAAe,EAAE,cAAc,GAC9B,2BAA2B,EAAE,CAqB/B;AAED,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,cAAc,EACxB,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,qBAAqB,GAC5B,cAAc,CAQhB;AAED,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,GAAG,cAAc,CAI7F"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry.js","names":[],"sources":["../../src/plugins/registry.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\n\nimport type { InstalledPluginRecord, PluginRegistry, ScopedInstalledPluginRecord } from './types.js';\n\nexport const EMPTY_PLUGIN_REGISTRY: PluginRegistry = { plugins: {}, disabledPlugins: [] };\n\nexport function loadPluginRegistry(registryPath: string): PluginRegistry {\n try {\n if (!fs.existsSync(registryPath)) return { plugins: {}, disabledPlugins: [] };\n const raw = JSON.parse(fs.readFileSync(registryPath, 'utf-8')) as unknown;\n return validatePluginRegistry(raw);\n } catch {\n return { plugins: {}, disabledPlugins: [] };\n }\n}\n\nexport function savePluginRegistry(registryPath: string, registry: PluginRegistry): void {\n fs.mkdirSync(path.dirname(registryPath), { recursive: true });\n fs.writeFileSync(registryPath, `${JSON.stringify(validatePluginRegistry(registry), null, 2)}\\n`);\n}\n\nexport function mergePluginRegistries(\n globalRegistry: PluginRegistry,\n projectRegistry: PluginRegistry,\n): ScopedInstalledPluginRecord[] {\n const merged = new Map<string, ScopedInstalledPluginRecord>();\n const disabledPlugins = new Set([\n ...(globalRegistry.disabledPlugins ?? []),\n ...(projectRegistry.disabledPlugins ?? []),\n ]);\n\n for (const [id, record] of Object.entries(globalRegistry.plugins)) {\n merged.set(id, { id, scope: 'global', ...record });\n }\n\n for (const [id, record] of Object.entries(projectRegistry.plugins)) {\n merged.set(id, { id, scope: 'project', ...record });\n }\n\n return [...merged.values()]\n .map(record => (disabledPlugins.has(record.id) ? { ...record, blocked: true } : record))\n .sort((a, b) => {\n if (a.scope !== b.scope) return a.scope === 'project' ? -1 : 1;\n return a.id.localeCompare(b.id);\n });\n}\n\nexport function setPluginRecord(\n registry: PluginRegistry,\n pluginId: string,\n record: InstalledPluginRecord,\n): PluginRegistry {\n return {\n plugins: {\n ...registry.plugins,\n [pluginId]: record,\n },\n disabledPlugins: registry.disabledPlugins ?? [],\n };\n}\n\nexport function removePluginRecord(registry: PluginRegistry, pluginId: string): PluginRegistry {\n const plugins = { ...registry.plugins };\n delete plugins[pluginId];\n return { plugins, disabledPlugins: registry.disabledPlugins ?? [] };\n}\n\nfunction validatePluginRegistry(raw: unknown): PluginRegistry {\n if (!raw || typeof raw !== 'object') return { plugins: {}, disabledPlugins: [] };\n const plugins = (raw as { plugins?: unknown }).plugins;\n if (!plugins || typeof plugins !== 'object' || Array.isArray(plugins)) return { plugins: {}, disabledPlugins: [] };\n\n const disabledPlugins = (raw as { disabledPlugins?: unknown }).disabledPlugins;\n const validated: PluginRegistry = {\n plugins: {},\n disabledPlugins: Array.isArray(disabledPlugins)\n ? [...new Set(disabledPlugins.filter((pluginId): pluginId is string => typeof pluginId === 'string'))].sort()\n : [],\n };\n for (const [id, value] of Object.entries(plugins)) {\n if (typeof id !== 'string' || id.trim().length === 0) continue;\n if (!value || typeof value !== 'object' || Array.isArray(value)) continue;\n const record = value as Record<string, unknown>;\n if (typeof record.enabled !== 'boolean') continue;\n if (record.source !== 'local' && record.source !== 'github') continue;\n if (typeof record.specifier !== 'string') continue;\n if (typeof record.path !== 'string') continue;\n if (typeof record.entry !== 'string') continue;\n\n validated.plugins[id] = {\n enabled: record.enabled,\n source: record.source,\n specifier: record.specifier,\n path: record.path,\n entry: record.entry,\n ...(typeof record.ref === 'string' ? { ref: record.ref } : {}),\n ...(typeof record.version === 'string' ? { version: record.version } : {}),\n ...(record.config && typeof record.config === 'object' && !Array.isArray(record.config)\n ? { config: validatePluginConfigValues(record.config) }\n : {}),\n };\n }\n\n return validated;\n}\n\nfunction validatePluginConfigValues(raw: object): Record<string, string | boolean> {\n const values: Record<string, string | boolean> = {};\n for (const [key, value] of Object.entries(raw)) {\n if (typeof key !== 'string' || key.trim().length === 0) continue;\n if (typeof value === 'string' || typeof value === 'boolean') values[key] = value;\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0B,GAAG,MAAM,CA8D7F;AAqBD,wBAAgB,qBAAqB,CAAC,SAAS,EAAE,MAAM,GAAG,MAAM,CAY/D"}
|
|
@@ -1 +0,0 @@
|
|
|
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,S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yB,EAAE,CAE1D;IAED;;;;;;;;;;OAUG;IACH,IAAI,CAAC,aAAa,EAAE,kBAAkB,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,IAAI,CA8BtE;IAED;;;;;OAKG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,GAAG,IAAI,CAK5C;IAED;;;;;OAKG;IACH,OAAO,IAAI,IAAI,CAGd;CA+GF"}
|
|
@@ -1 +0,0 @@
|
|
|
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 /** Called with the id of the plugin that owns the failing provider. */\n onError?: (message: string, error: unknown, pluginId: string) => 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, pluginId: string) => 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 pluginId,\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(\n `Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to start:`,\n error,\n live.pluginId,\n );\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(\n `Plugin \"${live.pluginId}\" signal provider \"${live.provider.id}\" failed to stop:`,\n error,\n live.pluginId,\n );\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 live.pluginId,\n );\n }\n }\n this.#inputProcessors = input;\n this.#outputProcessors = output;\n }\n}\n"],"mappings":";;;;;;;;;;;AAoCA,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,O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IAAI,8BAA8B,CAY1C;IAED,KAAK,IAAI,OAAO,CAAC,8BAA8B,CAAC,CAyC/C;YAEa,QAAQ;YAkCR,qBAAqB;IAOnC,OAAO,CAAC,MAAM,GAAE,QAAQ,GAAG,UAAqB,GAAG,OAAO,CAAC,+BAA+B,CAAC,CAK1F;IAEK,IAAI,IAAI,OAAO,CAAC,8BAA8B,CAAC,CA0CpD;YAEa,eAAe;IA4B7B,OAAO,CAAC,SAAS;YAmCH,aAAa;YAUb,UAAU;IAmBxB,OAAO,CAAC,YAAY;IAIpB,OAAO,CAAC,iBAAiB;IAezB,OAAO,CAAC,cAAc;YAMR,YAAY;YA6DZ,2BAA2B;IASzC,OAAO,CAAC,WAAW;IAInB,OAAO,CAAC,sBAAsB;IAS9B,OAAO,CAAC,mBAAmB;YAWb,wBAAwB;CAYvC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"process-memory-diagnostics.js","names":["platform"],"sources":["../src/process-memory-diagnostics.ts"],"sourcesContent":["import { appendFile, chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';\nimport { Session } from 'node:inspector/promises';\nimport { homedir } from 'node:os';\nimport { join } from 'node:path';\nimport { PerformanceObserver } from 'node:perf_hooks';\nimport type { PerformanceEntry } from 'node:perf_hooks';\nimport { arch, platform } from 'node:process';\nimport { getHeapSpaceStatistics, getHeapStatistics } from 'node:v8';\n\nexport const PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS = {\n sampleIntervalMs: 10_000,\n captureIntervalMs: 300_000,\n allocationIntervalBytes: 524_288,\n} as const;\n\nexport const PROCESS_MEMORY_DIAGNOSTICS_MINIMUMS = {\n sampleIntervalMs: 1_000,\n captureIntervalMs: 10_000,\n allocationIntervalBytes: 32_768,\n} as const;\n\nconst MAX_TIMER_DELAY_MS = 2_147_483_647;\nconst MAX_PENDING_GC_EVENTS = 1_000;\n\nexport interface ProcessMemoryDiagnosticsConfig {\n parentDirectory: string;\n sampleIntervalMs: number;\n captureIntervalMs: number;\n allocationIntervalBytes: number;\n}\n\nexport interface ProcessMemoryDiagnosticsEnvironment {\n MASTRACODE_PROFILE?: string;\n MASTRACODE_PROFILE_DIR?: string;\n MASTRACODE_PROFILE_SAMPLE_INTERVAL_MS?: string;\n MASTRACODE_PROFILE_CAPTURE_INTERVAL_MS?: string;\n MASTRACODE_PROFILE_ALLOCATION_INTERVAL_BYTES?: string;\n}\n\nexport interface ProcessMemoryDiagnosticsMemorySample {\n timestamp: string;\n sequence: number;\n elapsedMs: number;\n memory: ReturnType<typeof process.memoryUsage>;\n resourceUsage: ReturnType<typeof process.resourceUsage>;\n heap: ReturnType<typeof getHeapStatistics>;\n heapSpaces: ReturnType<typeof getHeapSpaceStatistics>;\n}\n\nexport interface ProcessMemoryDiagnosticsStatus {\n state: 'inactive' | 'starting' | 'active' | 'stopping' | 'error';\n outputDirectory: string | null;\n config: ProcessMemoryDiagnosticsConfig;\n sampleCount: number;\n captureCount: number;\n gcEventCount: number;\n latestSample: ProcessMemoryDiagnosticsMemorySample | null;\n latestCapturePath: string | null;\n error: string | null;\n}\n\nexport interface ProcessMemoryDiagnosticsCapture {\n path: string;\n sequence: number;\n timestamp: string;\n reason: 'manual' | 'periodic' | 'stop';\n}\n\ninterface InspectorSessionAdapter {\n connect(): void;\n disconnect(): void;\n post(method: string, params?: Record<string, unknown>): Promise<Record<string, unknown>>;\n}\n\ninterface PerformanceObserverAdapter {\n observe(options: Parameters<PerformanceObserver['observe']>[0]): void;\n disconnect(): void;\n}\n\ninterface ProcessMemoryDiagnosticsDependencies {\n createInspectorSession?: () => InspectorSessionAdapter;\n createPerformanceObserver?: (callback: (entries: PerformanceEntry[]) => void) => PerformanceObserverAdapter;\n now?: () => Date;\n randomId?: () => string;\n}\n\nexport interface ProcessMemoryDiagnosticsSetup {\n diagnostics: ProcessMemoryDiagnostics;\n enabled: boolean;\n error: string | null;\n}\n\nexport class ProcessMemoryDiagnosticsConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'ProcessMemoryDiagnosticsConfigError';\n }\n}\n\nfunction isEnabled(value: string | undefined): boolean {\n return ['1', 'true', 'yes', 'on'].includes(value?.trim().toLowerCase() ?? '');\n}\n\nfunction parseBoundedInteger(\n env: ProcessMemoryDiagnosticsEnvironment,\n name: keyof ProcessMemoryDiagnosticsEnvironment,\n fallback: number,\n minimum: number,\n maximum?: number,\n): number {\n const raw = env[name];\n if (raw === undefined || raw.trim() === '') return fallback;\n const value = Number(raw);\n if (!Number.isSafeInteger(value) || value < minimum || (maximum !== undefined && value > maximum)) {\n const range = maximum === undefined ? `greater than or equal to ${minimum}` : `between ${minimum} and ${maximum}`;\n throw new ProcessMemoryDiagnosticsConfigError(\n `${name} must be an integer ${range}; received ${JSON.stringify(raw)}.`,\n );\n }\n return value;\n}\n\nfunction getDefaultProfileParentDirectory(): string {\n if (process.env.MASTRA_APP_DATA_DIR) return join(process.env.MASTRA_APP_DATA_DIR, 'profiles');\n\n const baseDirectory =\n platform === 'darwin'\n ? join(homedir(), 'Library', 'Application Support')\n : platform === 'win32'\n ? process.env.APPDATA || join(homedir(), 'AppData', 'Roaming')\n : process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share');\n return join(baseDirectory, 'mastracode', 'profiles');\n}\n\nexport function parseProcessMemoryDiagnosticsEnvironment(env: ProcessMemoryDiagnosticsEnvironment = process.env): {\n enabled: boolean;\n config: ProcessMemoryDiagnosticsConfig;\n} {\n return {\n enabled: isEnabled(env.MASTRACODE_PROFILE),\n config: {\n parentDirectory: env.MASTRACODE_PROFILE_DIR?.trim() || getDefaultProfileParentDirectory(),\n sampleIntervalMs: parseBoundedInteger(\n env,\n 'MASTRACODE_PROFILE_SAMPLE_INTERVAL_MS',\n PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS.sampleIntervalMs,\n PROCESS_MEMORY_DIAGNOSTICS_MINIMUMS.sampleIntervalMs,\n MAX_TIMER_DELAY_MS,\n ),\n captureIntervalMs: parseBoundedInteger(\n env,\n 'MASTRACODE_PROFILE_CAPTURE_INTERVAL_MS',\n PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS.captureIntervalMs,\n PROCESS_MEMORY_DIAGNOSTICS_MINIMUMS.captureIntervalMs,\n MAX_TIMER_DELAY_MS,\n ),\n allocationIntervalBytes: parseBoundedInteger(\n env,\n 'MASTRACODE_PROFILE_ALLOCATION_INTERVAL_BYTES',\n PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS.allocationIntervalBytes,\n PROCESS_MEMORY_DIAGNOSTICS_MINIMUMS.allocationIntervalBytes,\n ),\n },\n };\n}\n\nexport function createProcessMemoryDiagnosticsFromEnvironment(\n env: ProcessMemoryDiagnosticsEnvironment = process.env,\n dependencies: ProcessMemoryDiagnosticsDependencies = {},\n): ProcessMemoryDiagnosticsSetup {\n try {\n const { enabled, config } = parseProcessMemoryDiagnosticsEnvironment(env);\n return { diagnostics: new ProcessMemoryDiagnostics(config, dependencies), enabled, error: null };\n } catch (error) {\n const config: ProcessMemoryDiagnosticsConfig = {\n parentDirectory: env.MASTRACODE_PROFILE_DIR?.trim() || getDefaultProfileParentDirectory(),\n ...PROCESS_MEMORY_DIAGNOSTICS_DEFAULTS,\n };\n const message = error instanceof Error ? error.message : String(error);\n return {\n diagnostics: new ProcessMemoryDiagnostics(config, dependencies, message),\n enabled: isEnabled(env.MASTRACODE_PROFILE),\n error: message,\n };\n }\n}\n\nexport async function startConfiguredProcessMemoryDiagnostics(\n setup: ProcessMemoryDiagnosticsSetup,\n warn: (message: string) => void,\n): Promise<ProcessMemoryDiagnostics> {\n if (!setup.enabled) return setup.diagnostics;\n if (setup.error) {\n warn(`Process memory diagnostics were not started: ${setup.error}`);\n return setup.diagnostics;\n }\n\n const status = await setup.diagnostics.start();\n if (status.state !== 'active') {\n warn(`Process memory diagnostics were not started: ${status.error ?? 'unknown inspector error'}`);\n }\n return setup.diagnostics;\n}\n\nexport async function stopProcessMemoryDiagnosticsWithTimeout(\n diagnostics: ProcessMemoryDiagnostics,\n warn: (message: string) => void,\n timeoutMs = 5_000,\n): Promise<void> {\n let timeout: ReturnType<typeof setTimeout> | undefined;\n const timedOut = await Promise.race([\n diagnostics.stop().then(\n () => false,\n error => {\n warn(`Process memory diagnostics did not stop cleanly: ${errorMessage(error)}`);\n return false;\n },\n ),\n new Promise<true>(resolve => {\n timeout = setTimeout(() => resolve(true), timeoutMs);\n timeout.unref();\n }),\n ]);\n if (timeout) clearTimeout(timeout);\n if (timedOut)\n warn(`Process memory diagnostics did not stop within ${timeoutMs}ms; final artifacts may be incomplete.`);\n}\n\nfunction defaultInspectorSession(): InspectorSessionAdapter {\n const session = new Session();\n return {\n connect: () => session.connect(),\n disconnect: () => session.disconnect(),\n post: async (method, params) =>\n (await session.post(\n method as Parameters<Session['post']>[0],\n params as Parameters<Session['post']>[1],\n )) as unknown as Record<string, unknown>,\n };\n}\n\nfunction defaultPerformanceObserver(callback: (entries: PerformanceEntry[]) => void) {\n const observer = new PerformanceObserver(list => callback(list.getEntries()));\n return observer;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction safeTimestamp(date: Date): string {\n return date.toISOString().replaceAll(':', '-');\n}\n\nfunction unrefTimer(timer: ReturnType<typeof setInterval>): void {\n timer.unref?.();\n}\n\nexport class ProcessMemoryDiagnostics {\n readonly config: ProcessMemoryDiagnosticsConfig;\n\n private state: ProcessMemoryDiagnosticsStatus['state'] = 'inactive';\n private outputDirectory: string | null = null;\n private inspector: InspectorSessionAdapter | null = null;\n private observer: PerformanceObserverAdapter | null = null;\n private sampleTimer: ReturnType<typeof setInterval> | null = null;\n private captureTimer: ReturnType<typeof setInterval> | null = null;\n private startedAt: Date | null = null;\n private sampleCount = 0;\n private captureCount = 0;\n private gcEventCount = 0;\n private latestSample: ProcessMemoryDiagnosticsMemorySample | null = null;\n private latestCapturePath: string | null = null;\n private latestError: string | null;\n private samplingActive = false;\n private stopRequested = false;\n private startingPromise: Promise<ProcessMemoryDiagnosticsStatus> | null = null;\n private stoppingPromise: Promise<ProcessMemoryDiagnosticsStatus> | null = null;\n private restartAfterStopPromise: Promise<ProcessMemoryDiagnosticsStatus> | null = null;\n private restartRequested = false;\n private pendingGcEvents: Array<Record<string, unknown>> = [];\n private gcEventBufferOverflowed = false;\n private artifactWriteFailed = false;\n private captureQueue: Promise<unknown> = Promise.resolve();\n private writeQueue: Promise<unknown> = Promise.resolve();\n\n private readonly configError: string | null;\n private readonly createInspectorSession: () => InspectorSessionAdapter;\n private readonly createPerformanceObserver: NonNullable<\n ProcessMemoryDiagnosticsDependencies['createPerformanceObserver']\n >;\n private readonly now: () => Date;\n private readonly randomId: () => string;\n\n constructor(\n config: ProcessMemoryDiagnosticsConfig,\n dependencies: ProcessMemoryDiagnosticsDependencies = {},\n initialError: string | null = null,\n ) {\n this.config = { ...config };\n this.configError = initialError;\n this.latestError = initialError;\n this.createInspectorSession = dependencies.createInspectorSession ?? defaultInspectorSession;\n this.createPerformanceObserver = dependencies.createPerformanceObserver ?? defaultPerformanceObserver;\n this.now = dependencies.now ?? (() => new Date());\n this.randomId = dependencies.randomId ?? (() => globalThis.crypto.randomUUID());\n }\n\n getStatus(): ProcessMemoryDiagnosticsStatus {\n return {\n state: this.state,\n outputDirectory: this.outputDirectory,\n config: { ...this.config },\n sampleCount: this.sampleCount,\n captureCount: this.captureCount,\n gcEventCount: this.gcEventCount,\n latestSample: this.latestSample,\n latestCapturePath: this.latestCapturePath,\n error: this.latestError,\n };\n }\n\n start(): Promise<ProcessMemoryDiagnosticsStatus> {\n if (this.state === 'active') return Promise.resolve(this.getStatus());\n if (this.state === 'starting' && this.startingPromise) return this.startingPromise;\n if (this.state === 'stopping' && this.stoppingPromise) {\n this.restartRequested = true;\n this.restartAfterStopPromise ??= this.stoppingPromise.then(() => {\n this.restartAfterStopPromise = null;\n if (!this.restartRequested) return this.getStatus();\n this.restartRequested = false;\n return this.start();\n });\n return this.restartAfterStopPromise;\n }\n if (this.configError) {\n this.latestError = this.configError;\n this.state = 'error';\n return Promise.resolve(this.getStatus());\n }\n\n this.state = 'starting';\n this.stoppingPromise = null;\n this.restartRequested = false;\n this.stopRequested = false;\n this.outputDirectory = null;\n this.sampleCount = 0;\n this.captureCount = 0;\n this.gcEventCount = 0;\n this.pendingGcEvents = [];\n this.gcEventBufferOverflowed = false;\n this.artifactWriteFailed = false;\n this.latestSample = null;\n this.latestCapturePath = null;\n this.latestError = null;\n this.startedAt = this.now();\n\n const startingPromise = this.startRun();\n this.startingPromise = startingPromise;\n void startingPromise.finally(() => {\n if (this.startingPromise === startingPromise) this.startingPromise = null;\n });\n return startingPromise;\n }\n\n private async startRun(): Promise<ProcessMemoryDiagnosticsStatus> {\n try {\n await this.createArtifacts();\n if (await this.abortStartIfRequested()) return this.getStatus();\n\n this.observeGc();\n this.inspector = this.createInspectorSession();\n this.inspector.connect();\n await this.startSampling();\n if (await this.abortStartIfRequested()) return this.getStatus();\n\n await this.takeSample();\n if (await this.abortStartIfRequested()) return this.getStatus();\n\n this.sampleTimer = setInterval(() => {\n void this.takeSample().catch(error => this.recordError('Process sample failed', error));\n }, this.config.sampleIntervalMs);\n unrefTimer(this.sampleTimer);\n\n this.captureTimer = setInterval(() => {\n void this.capture('periodic').catch(error => this.recordError('Periodic allocation capture failed', error));\n }, this.config.captureIntervalMs);\n unrefTimer(this.captureTimer);\n\n this.state = 'active';\n return this.getStatus();\n } catch (error) {\n this.latestError = `Unable to start process memory diagnostics: ${errorMessage(error)}`;\n await this.cleanupAfterStartFailure();\n this.state = 'error';\n return this.getStatus();\n }\n }\n\n private async abortStartIfRequested(): Promise<boolean> {\n if (!this.stopRequested) return false;\n await this.cleanupAfterStartFailure();\n this.state = 'inactive';\n return true;\n }\n\n capture(reason: 'manual' | 'periodic' = 'manual'): Promise<ProcessMemoryDiagnosticsCapture> {\n if (this.state !== 'active') {\n return Promise.reject(new Error(this.latestError ?? 'Process memory diagnostics are not active.'));\n }\n return this.enqueueCapture(() => this.captureEpoch(reason, false));\n }\n\n async stop(): Promise<ProcessMemoryDiagnosticsStatus> {\n if (this.stoppingPromise) {\n this.restartRequested = false;\n return this.stoppingPromise;\n }\n if (this.state === 'inactive') return this.getStatus();\n if (this.state === 'error' && !this.inspector && !this.outputDirectory) return this.getStatus();\n\n const startingPromise = this.state === 'starting' ? this.startingPromise : null;\n this.stopRequested = true;\n this.state = 'stopping';\n this.clearTimersAndObserver();\n\n if (startingPromise) {\n this.stoppingPromise = startingPromise.then(() => this.getStatus());\n return this.stoppingPromise;\n }\n\n this.stoppingPromise = (async () => {\n let stopError: string | null = null;\n try {\n if (this.outputDirectory) await this.takeSample();\n await this.enqueueCapture(async () => {\n if (this.inspector && this.samplingActive) await this.captureEpoch('stop', true);\n });\n await this.writeQueue;\n if (this.gcEventBufferOverflowed) {\n throw new Error(`GC event buffer exceeded ${MAX_PENDING_GC_EVENTS} records before the next process sample.`);\n }\n if (this.artifactWriteFailed) throw new Error('One or more process memory diagnostic artifact writes failed.');\n this.latestError = null;\n } catch (error) {\n stopError = `Unable to stop process memory diagnostics cleanly: ${errorMessage(error)}`;\n this.latestError = stopError;\n } finally {\n this.disconnectInspector();\n this.state = stopError ? 'error' : 'inactive';\n }\n return this.getStatus();\n })();\n\n return this.stoppingPromise;\n }\n\n private async createArtifacts(): Promise<void> {\n await mkdir(this.config.parentDirectory, { recursive: true, mode: 0o700 });\n await chmod(this.config.parentDirectory, 0o700);\n const runName = `run-${safeTimestamp(this.startedAt!)}-${process.pid}-${this.randomId()\n .replaceAll(/[^a-zA-Z0-9-]/g, '')\n .slice(0, 12)}`;\n this.outputDirectory = join(this.config.parentDirectory, runName);\n await mkdir(this.outputDirectory, { mode: 0o700 });\n await chmod(this.outputDirectory, 0o700);\n\n const metadata = {\n schemaVersion: 1,\n runId: runName,\n startedAt: this.startedAt!.toISOString(),\n pid: process.pid,\n nodeVersion: process.version,\n platform,\n arch,\n config: this.config,\n };\n await writeFile(join(this.outputDirectory, 'metadata.json'), `${JSON.stringify(metadata, null, 2)}\\n`, {\n flag: 'wx',\n mode: 0o600,\n });\n await writeFile(join(this.outputDirectory, 'process-samples.jsonl'), '', { flag: 'wx', mode: 0o600 });\n await writeFile(join(this.outputDirectory, 'gc-events.jsonl'), '', { flag: 'wx', mode: 0o600 });\n }\n\n private observeGc(): void {\n const observer = this.createPerformanceObserver(entries => {\n const before = this.latestSample?.memory ?? null;\n const after = process.memoryUsage();\n const timestamp = this.now().toISOString();\n for (const entry of entries) {\n const gcEntry = entry as PerformanceEntry & {\n kind?: number;\n flags?: number;\n detail?: { kind?: number; flags?: number };\n };\n this.gcEventCount += 1;\n if (this.pendingGcEvents.length >= MAX_PENDING_GC_EVENTS) {\n this.gcEventBufferOverflowed = true;\n this.latestError = `GC event buffer exceeded ${MAX_PENDING_GC_EVENTS} records before the next process sample.`;\n continue;\n }\n this.pendingGcEvents.push({\n timestamp,\n sequence: this.gcEventCount,\n name: entry.name,\n startTime: entry.startTime,\n duration: entry.duration,\n kind: gcEntry.detail?.kind ?? gcEntry.kind ?? null,\n flags: gcEntry.detail?.flags ?? gcEntry.flags ?? null,\n before,\n after,\n latestSampleSequence: this.latestSample?.sequence ?? null,\n });\n }\n });\n observer.observe({ entryTypes: ['gc'] });\n this.observer = observer;\n }\n\n private async startSampling(): Promise<void> {\n if (!this.inspector) throw new Error('Inspector session is unavailable.');\n await this.inspector.post('HeapProfiler.startSampling', {\n samplingInterval: this.config.allocationIntervalBytes,\n includeObjectsCollectedByMajorGC: true,\n includeObjectsCollectedByMinorGC: true,\n });\n this.samplingActive = true;\n }\n\n private async takeSample(): Promise<ProcessMemoryDiagnosticsMemorySample> {\n if (!this.outputDirectory || !this.startedAt) throw new Error('Diagnostics output directory is unavailable.');\n const sample: ProcessMemoryDiagnosticsMemorySample = {\n timestamp: this.now().toISOString(),\n sequence: this.sampleCount + 1,\n elapsedMs: Math.max(0, this.now().getTime() - this.startedAt.getTime()),\n memory: process.memoryUsage(),\n resourceUsage: process.resourceUsage(),\n heap: getHeapStatistics(),\n heapSpaces: getHeapSpaceStatistics(),\n };\n this.sampleCount = sample.sequence;\n this.latestSample = sample;\n await this.enqueueWrite('process-samples.jsonl', sample);\n const gcEvents = this.pendingGcEvents.splice(0);\n if (gcEvents.length > 0) await this.enqueueWriteBatch('gc-events.jsonl', gcEvents);\n return sample;\n }\n\n private enqueueWrite(fileName: string, value: unknown): Promise<void> {\n return this.enqueueWriteBatch(fileName, [value]);\n }\n\n private enqueueWriteBatch(fileName: string, values: unknown[]): Promise<void> {\n const operation = this.writeQueue.then(async () => {\n if (!this.outputDirectory || values.length === 0) return;\n const lines = values.map(value => JSON.stringify(value)).join('\\n');\n try {\n await appendFile(join(this.outputDirectory, fileName), `${lines}\\n`, { mode: 0o600 });\n } catch (error) {\n this.artifactWriteFailed = true;\n throw error;\n }\n });\n this.writeQueue = operation.catch(() => undefined);\n return operation;\n }\n\n private enqueueCapture<T>(operation: () => Promise<T>): Promise<T> {\n const result = this.captureQueue.then(operation);\n this.captureQueue = result.catch(() => undefined);\n return result;\n }\n\n private async captureEpoch(\n reason: ProcessMemoryDiagnosticsCapture['reason'],\n final: boolean,\n ): Promise<ProcessMemoryDiagnosticsCapture> {\n if (!this.inspector || !this.samplingActive || !this.outputDirectory) {\n throw new Error(this.latestError ?? 'Allocation sampling is not active.');\n }\n\n let response: Record<string, unknown>;\n try {\n response = await this.inspector.post('HeapProfiler.stopSampling');\n this.samplingActive = false;\n } catch (error) {\n this.latestError = `Allocation capture failed: ${errorMessage(error)}`;\n if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();\n throw new Error(this.latestError, { cause: error });\n }\n\n const profile = response.profile;\n if (!profile || typeof profile !== 'object') {\n this.latestError = 'Allocation capture failed: inspector returned no profile.';\n if (!final && !this.stopRequested) await this.restartSamplingAfterFailure();\n throw new Error(this.latestError);\n }\n\n const sequence = this.captureCount + 1;\n const timestamp = this.now().toISOString();\n const filename = `allocation-${String(sequence).padStart(6, '0')}-${safeTimestamp(new Date(timestamp))}.heapprofile`;\n const finalPath = join(this.outputDirectory, filename);\n const temporaryPath = join(this.outputDirectory, `.${filename}.${this.randomId()}.tmp`);\n\n try {\n await writeFile(temporaryPath, `${JSON.stringify(profile)}\\n`, { flag: 'wx', mode: 0o600 });\n await chmod(temporaryPath, 0o600);\n await rename(temporaryPath, finalPath);\n await chmod(finalPath, 0o600);\n this.captureCount = sequence;\n this.latestCapturePath = finalPath;\n this.latestError = null;\n } catch (error) {\n this.artifactWriteFailed = true;\n this.latestError = `Unable to persist allocation capture: ${errorMessage(error)}`;\n throw new Error(this.latestError, { cause: error });\n } finally {\n if (!final && !this.stopRequested && this.state === 'active') {\n try {\n await this.startSampling();\n } catch (error) {\n this.latestError = `Unable to restart allocation sampling: ${errorMessage(error)}`;\n this.state = 'error';\n }\n }\n }\n\n if (!final && !this.stopRequested && !this.samplingActive) {\n throw new Error(this.latestError ?? 'Allocation sampling did not restart.');\n }\n\n return { path: finalPath, sequence, timestamp, reason };\n }\n\n private async restartSamplingAfterFailure(): Promise<void> {\n try {\n await this.startSampling();\n } catch (error) {\n this.latestError = `Unable to restart allocation sampling: ${errorMessage(error)}`;\n this.state = 'error';\n }\n }\n\n private recordError(prefix: string, error: unknown): void {\n this.latestError = `${prefix}: ${errorMessage(error)}`;\n }\n\n private clearTimersAndObserver(): void {\n if (this.sampleTimer) clearInterval(this.sampleTimer);\n if (this.captureTimer) clearInterval(this.captureTimer);\n this.sampleTimer = null;\n this.captureTimer = null;\n this.observer?.disconnect();\n this.observer = null;\n }\n\n private disconnectInspector(): void {\n this.samplingActive = false;\n if (!this.inspector) return;\n try {\n this.inspector.disconnect();\n } catch {\n // Best-effort cleanup after an inspector failure.\n }\n this.inspector = null;\n }\n\n private async cleanupAfterStartFailure(): Promise<void> {\n this.clearTimersAndObserver();\n this.disconnectInspector();\n await this.writeQueue;\n try {\n if (this.outputDirectory) await rm(this.outputDirectory, { recursive: true, force: true });\n } catch (error) {\n this.latestError = `${this.latestError} Failed to remove partial artifacts: ${error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K,cAAc,cAAc,KAAK,YAAY;EACtD,KAAK,cAAc;EACnB,KAAK,eAAe;EACpB,KAAK,UAAU,WAAW;EAC1B,KAAK,WAAW;CAClB;CAEA,sBAAoC;EAClC,KAAK,iBAAiB;EACtB,IAAI,CAAC,KAAK,WAAW;EACrB,IAAI;GACF,KAAK,UAAU,WAAW;EAC5B,QAAQ,CAER;EACA,KAAK,YAAY;CACnB;CAEA,MAAc,2BAA0C;EACtD,KAAK,uBAAuB;EAC5B,KAAK,oBAAoB;EACzB,MAAM,KAAK;EACX,IAAI;GACF,IAAI,KAAK,iBAAiB,MAAM,GAAG,KAAK,iBAAiB;IAAE,WAAW;IAAM,OAAO;GAAK,CAAC;EAC3F,SAAS,OAAO;GACd,KAAK,cAAc,GAAG,KAAK,YAAY,uCAAuC,aAAa,KAAK;EAClG,UAAU;GACR,KAAK,kBAAkB;EACzB;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan-rejection-abort.d.ts","sourceRoot":"","sources":["../../src/processors/plan-rejection-abort.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAkD/E,qBAAa,2BAA4B,YAAW,SAAS,CAAC,sBAAsB,CAAC;IACnF,EAAE,EAAG,sBAAsB,CAAU;IAE/B,gBAAgB,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,KAAK,EAAE,EAAE,oBAAoB,GAAG,OAAO,CAAC,SAAS,CAAC,CA4ChG;CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan-rejection-abort.js","names":[],"sources":["../../src/processors/plan-rejection-abort.ts"],"sourcesContent":["/**\n * Processor that aborts the agentic loop immediately after a `submit_plan` tool\n * returns a rejection without inline feedback. This prevents the model from\n * generating any text after the user clicks \"Request Changes\" — the tool result\n * is persisted in thread history (for context on the next run) but no follow-up\n * LLM call is made.\n *\n * A rejection that carries inline feedback is left alone: its result tells the\n * model to revise the plan and submit again, so the run must continue.\n */\nimport type { Processor, ProcessInputStepArgs } from '@mastra/core/processors';\n\nconst PLAN_REJECTED_PREFIX = 'Plan was not approved';\n\ntype ToolInvocation = {\n state?: string;\n toolName?: string;\n result?: unknown;\n};\n\ntype ToolResultPart = {\n type?: string;\n name?: string;\n result?: unknown;\n};\n\nfunction resultText(result: unknown): string {\n if (typeof result === 'string') return result;\n if (result && typeof result === 'object') {\n const content = (result as { content?: unknown }).content;\n if (typeof content === 'string') return content;\n }\n return '';\n}\n\nfunction hasInlineFeedback(result: unknown): boolean {\n if (result && typeof result === 'object') {\n const submittedPlan = (result as { submittedPlan?: { feedback?: unknown } }).submittedPlan;\n if (typeof submittedPlan?.feedback === 'string' && submittedPlan.feedback.length > 0) return true;\n }\n return resultText(result).includes('\\n\\nUser feedback: ');\n}\n\n/**\n * Returns true when the result is a `submit_plan` rejection that waits for the\n * user's next message rather than carrying feedback to revise against.\n */\nfunction isRejectionWithoutFeedback(result: unknown): boolean {\n return resultText(result).startsWith(PLAN_REJECTED_PREFIX) && !hasInlineFeedback(result);\n}\n\nfunction isPlanRejection(inv: ToolInvocation | undefined): boolean {\n if (!inv || inv.state !== 'result' || inv.toolName !== 'submit_plan') return false;\n return isRejectionWithoutFeedback(inv.result);\n}\n\nfunction isPlanRejectionResultPart(part: ToolResultPart): boolean {\n return part.type === 'tool_result' && part.name === 'submit_plan' && isRejectionWithoutFeedback(part.result);\n}\n\nexport class PlanRejectionAbortProcessor implements Processor<'plan-rejection-abort'> {\n id = 'plan-rejection-abort' as const;\n\n async processInputStep({ messages, stepNumber, abort }: ProcessInputStepArgs): Promise<undefined> {\n // Only act on continuation steps (stepNumber > 0) — step 0 is the initial\n // prompt where the model hasn't responded yet. After tool resume, the tool\n // result is part of step 0 and the loop advances to step 1 for the next\n // model call.\n if (stepNumber === 0) return undefined;\n\n // Walk messages from the end to find the last assistant message.\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (!msg || msg.role !== 'assistant') continue;\n\n // Check for a submit_plan rejection tool result. Handle the primary\n // `content.parts` shapes (tool-invocation and harness-style tool_result)\n // plus the legacy `content.toolInvocations` array.\n const content = msg.content as { parts?: unknown[]; toolInvocations?: unknown[] } | unknown[] | undefined;\n\n const parts = Array.isArray(content) ? content : Array.isArray(content?.parts) ? content.parts : [];\n for (const part of parts) {\n if (!part || typeof part !== 'object') continue;\n const p = part as { type?: string; toolInvocation?: ToolInvocation } & ToolResultPart;\n if (p.type === 'tool-invocation' && isPlanRejection(p.toolInvocation)) {\n abort('Plan rejected by user — no further response needed');\n return undefined;\n }\n if (isPlanRejectionResultPart(p)) {\n abort('Plan rejected by user — no further response needed');\n return undefined;\n }\n }\n\n const legacy = !Array.isArray(content) && Array.isArray(content?.toolInvocations) ? content.toolInvocations : [];\n for (const inv of legacy) {\n if (isPlanRejection(inv as ToolInvocation)) {\n abort('Plan rejected by user — no further response needed');\n return undefined;\n }\n }\n\n // Only check the most recent assistant message.\n break;\n }\n\n return undefined;\n }\n}\n"],"mappings":";AAYA,MAAM,uBAAuB;AAc7B,SAAS,WAAW,QAAyB;CAC3C,IAAI,OAAO,WAAW,UAAU,OAAO;CACvC,IAAI,UAAU,OAAO,WAAW,UAAU;EACxC,MAAM,UAAW,OAAiC;EAClD,IAAI,OAAO,YAAY,UAAU,OAAO;CAC1C;CACA,OAAO;AACT;AAEA,SAAS,kBAAkB,QAA0B;CACnD,IAAI,UAAU,OAAO,WAAW,UAAU;EACxC,MAAM,gBAAiB,OAAsD;EAC7E,IAAI,OAAO,eAAe,aAAa,YAAY,cAAc,SAAS,SAAS,GAAG,OAAO;CAC/F;CACA,OAAO,WAAW,MAAM,CAAC,CAAC,SAAS,qBAAqB;AAC1D;;;;;AAMA,SAAS,2BAA2B,QAA0B;CAC5D,OAAO,WAAW,MAAM,CAAC,CAAC,WAAW,oBAAoB,KAAK,CAAC,kBAAkB,MAAM;AACzF;AAE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,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,SAAS,CAAC,EAAE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB,CAEvB;CACF;AAED,wBAAgB,0BAA0B,IAAI,oBAAoB,CAEjE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"amazon-bedrock-gateway.js","names":[],"sources":["../../src/providers/amazon-bedrock-gateway.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { createAmazonBedrock } from '@ai-sdk/amazon-bedrock';\nimport { fromNodeProviderChain } from '@aws-sdk/credential-providers';\nimport { MastraModelGateway } from '@mastra/core/llm';\nimport type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, ProviderConfig } from '@mastra/core/llm';\nimport { getBedrockModelCatalog } from './amazon-bedrock.js';\n\ntype ModelRequestHeaders = Record<string, string>;\ntype BedrockModel = ReturnType<ReturnType<typeof createAmazonBedrock>>;\ntype BedrockPrompt = Parameters<BedrockModel['doGenerate']>[0]['prompt'];\n\n// Claude 3.x is a closed set: only these three variants support cachePoint on Bedrock.\n// claude-3-5-sonnet-20240620 is intentionally excluded (only the 20241022-v2:0 variant caches).\n// Every Claude 4+ and every named family (opus-5, sonnet-5, fable, mythos, …) supports it.\nconst CLAUDE_3_CACHEABLE = /claude-3-7-sonnet|claude-3-5-sonnet-20241022|claude-3-5-haiku/;\n\nexport function supportsBedrockPromptCaching(modelId: string): boolean {\n if (!modelId.includes('anthropic.claude')) return false;\n return /anthropic\\.claude-3-/.test(modelId) ? CLAUDE_3_CACHEABLE.test(modelId) : true;\n}\n\nexport function addBedrockCachePoints(prompt: BedrockPrompt): BedrockPrompt {\n const result = [...prompt];\n const markCachePoint = (message: (typeof result)[number]) => ({\n ...message,\n providerOptions: {\n ...message.providerOptions,\n bedrock: {\n ...message.providerOptions?.bedrock,\n cachePoint: { type: 'default' },\n },\n },\n });\n\n let lastSystemIndex = -1;\n for (let index = result.length - 1; index >= 0; index--) {\n if (result[index]!.role === 'system') {\n lastSystemIndex = index;\n break;\n }\n }\n\n if (lastSystemIndex >= 0) {\n result[lastSystemIndex] = markCachePoint(result[lastSystemIndex]!);\n }\n\n let lastNonSystemIndex = -1;\n for (let index = result.length - 1; index >= 0; index--) {\n if (result[index]!.role !== 'system') {\n lastNonSystemIndex = index;\n break;\n }\n }\n\n if (lastNonSystemIndex >= 0) {\n result[lastNonSystemIndex] = markCachePoint(result[lastNonSystemIndex]!);\n }\n\n return result;\n}\n\nexport function withBedrockCache(model: BedrockModel): BedrockModel {\n return new Proxy(model, {\n get(target, property, receiver) {\n if (property === 'doGenerate') {\n return (options: Parameters<BedrockModel['doGenerate']>[0]) =>\n target.doGenerate({ ...options, prompt: addBedrockCachePoints(options.prompt) });\n }\n if (property === 'doStream') {\n return (options: Parameters<BedrockModel['doStream']>[0]) =>\n target.doStream({ ...options, prompt: addBedrockCachePoints(options.prompt) });\n }\n return Reflect.get(target, property, receiver);\n },\n });\n}\n\nexport const AMAZON_BEDROCK_GATEWAY_ID = 'amazon-bedrock';\n\n/**\n * Whether AWS credentials look available for Bedrock.\n *\n * Amazon Bedrock authenticates with AWS SigV4 rather than a bearer API key, so\n * this only governs whether Bedrock models are offered as \"authenticated\" in the\n * picker. We look for the common signals (env vars, bearer token, a configured\n * profile, or a shared credentials/config file) rather than resolving\n * credentials here, since the auth checker must stay sync.\n */\nexport function hasAwsCredentials(): boolean {\n if (\n process.env.AWS_BEARER_TOKEN_BEDROCK ||\n (process.env.AWS_ACCESS_KEY_ID && process.env.AWS_SECRET_ACCESS_KEY) ||\n process.env.AWS_SHARED_CREDENTIALS_FILE ||\n process.env.AWS_CONFIG_FILE ||\n process.env.AWS_PROFILE ||\n process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI ||\n process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI ||\n process.env.AWS_WEB_IDENTITY_TOKEN_FILE\n ) {\n return true;\n }\n const home = process.env.HOME || process.env.USERPROFILE;\n if (home) {\n const awsDir = path.join(home, '.aws');\n const credentialsPath = process.env.AWS_SHARED_CREDENTIALS_FILE ?? path.join(awsDir, 'credentials');\n const configPath = process.env.AWS_CONFIG_FILE ?? path.join(awsDir, 'config');\n if (existsSync(credentialsPath) || existsSync(configPath)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Create an Amazon Bedrock model.\n *\n * Bedrock authenticates with AWS SigV4 rather than a bearer API key, so this\n * resolves credentials through the standard AWS provider chain\n * (`fromNodeProviderChain`): environment variables, shared `~/.aws` config and\n * SSO profiles, and container/instance roles — the same resolution order the AWS\n * CLI uses. The region falls back to `us-east-1` to match the AWS SDK default.\n *\n * When `AWS_BEARER_TOKEN_BEDROCK` is set, `@ai-sdk/amazon-bedrock` uses bearer\n * auth instead and ignores the credential provider, so we leave that path to the\n * SDK and only wire up SigV4 here.\n */\nfunction bedrockProvider(modelId: string, headers?: ModelRequestHeaders) {\n const region = process.env.AWS_REGION || process.env.AWS_DEFAULT_REGION || 'us-east-1';\n const bedrock = createAmazonBedrock({\n region,\n credentialProvider: fromNodeProviderChain(),\n headers,\n });\n const model = bedrock(modelId);\n return supportsBedrockPromptCaching(modelId) ? withBedrockCache(model) : model;\n}\n\n/**\n * Standalone Amazon Bedrock gateway.\n *\n * Bedrock is resolved directly via AWS SigV4 (not through the model router) and\n * its models are surfaced from the public models.dev catalog. It is exposed as\n * its own gateway/provider (`amazon-bedrock/...`) rather than nested under the\n * MastraCode gateway namespace.\n */\nexport class AmazonBedrockGateway extends MastraModelGateway {\n readonly id = AMAZON_BEDROCK_GATEWAY_ID;\n readonly name = 'Amazon Bedrock';\n\n shouldEnable(): boolean {\n return hasAwsCredentials();\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = {};\n try {\n const bedrockModels = await getBedrockModelCatalog();\n providers['amazon-bedrock'] = {\n name: 'Amazon Bedrock',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: bedrockModels.map(model => model.id),\n };\n } catch (error) {\n console.warn('Failed to load Amazon Bedrock model catalog:', error);\n }\n return providers;\n }\n\n buildUrl(_modelId: string): string | undefined {\n return undefined;\n }\n\n async getApiKey(_modelId: string): Promise<string> {\n return hasAwsCredentials() ? 'aws-credential-chain' : '';\n }\n\n resolveAuth(_request: GatewayAuthRequest): GatewayAuthResult | undefined {\n // Amazon Bedrock authenticates via the AWS credential chain rather than a\n // stored API key, so report it as authenticated whenever AWS credentials look\n // available. The actual SigV4 signing happens inside `bedrockProvider()`.\n if (hasAwsCredentials()) {\n return { apiKey: 'aws-credential-chain', source: 'gateway' };\n }\n return undefined;\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n return bedrockProvider(args.modelId, args.headers) as unknown as GatewayLanguageModel;\n }\n}\n\nexport function createAmazonBedrockGateway(): AmazonBedrockGateway {\n return new AmazonBedrockGateway();\n}\n"],"mappings":";;;;;;;AAeA,MAAM,qBAAqB;AAE3B,SAAgB,6BAA6B,SAA0B;CACrE,IAAI,CAAC,QAAQ,SAAS,kBAAkB,GAAG,OAAO;CAClD,OAAO,uBAAuB,KAAK,OAAO,IAAI,mBAAmB,KAAK,OAAO,IAAI;AACnF;AAEA,SAAgB,sBAAsB,QAAsC;CAC1E,MAAM,SAAS,CAAC,GAAG,MAAM;CACzB,MAAM,kBAAkB,aAAsC;EAC5D,GAAG;EACH,iBAAiB;GACf,GAAG,QAAQ;GACX,SAAS;IACP,GAAG,QAAQ,iBAAiB;IAC5B,YAAY,EAAE,MAAM,UAAU;GAChC;EACF;CACF;CAEA,IAAI,kBAAkB;CACtB,KAAK,IAAI,QAAQ,OAAO,SAAS,GAAG,SAAS,GAAG,SAC9C,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,CAAC;CACZ;AAyDD,8DAA8D;AAC9D,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C;AAiBD;;;;;;;;;;GAUG;AACH,wBAAsB,sBAAsB,IAAI,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAiC3E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"amazon-bedrock.js","names":[],"sources":["../../src/providers/amazon-bedrock.ts"],"sourcesContent":["/**\n * Amazon Bedrock model catalog.\n *\n * Bedrock is not part of mastracode's gateway-synced model router (it\n * authenticates with AWS SigV4 rather than an API key / base URL, so it is\n * resolved directly in `agents/model.ts`). To still offer Bedrock models in the\n * `/models` picker and packs, we fetch the public models.dev catalog — the same\n * source the model router uses — and expose the `amazon-bedrock` provider's\n * model list. This mirrors the GitHub Copilot catalog approach.\n */\n\nconst MODELS_DEV_API_URL = 'https://models.dev/api.json';\nconst BEDROCK_PROVIDER_ID = 'amazon-bedrock';\n\nconst CATALOG_TTL_MS = 60 * 60 * 1000;\nconst CATALOG_FAILURE_TTL_MS = 60 * 1000;\nconst CATALOG_FETCH_TIMEOUT_MS = 5_000;\n\nexport interface BedrockModelEntry {\n id: string;\n}\n\n/**\n * A models.dev catalog entry for one Bedrock model.\n *\n * Most entries carry no `provider` block: they are served by the SigV4\n * `bedrock-runtime` Converse API, which is what this catalog feeds. An entry\n * that *does* carry one is overriding that transport.\n */\ninterface BedrockCatalogEntry {\n provider?: {\n npm?: string;\n api?: string;\n shape?: string;\n };\n}\n\n/**\n * True when the catalog entry asks for a transport this catalog cannot serve.\n *\n * Every id returned here is handed to `createAmazonBedrock()(modelId)` by\n * `amazon-bedrock-gateway.ts`, i.e. the Converse API, unconditionally. A\n * `provider` override in the catalog means the model wants a different endpoint\n * and API shape: the nine `bedrock-mantle` models point at\n * `https://bedrock-mantle.${AWS_REGION}.api.aws/openai/v1` with\n * `shape: \"responses\"`. Advertising them makes them selectable in `/models` and\n * in packs even though the request that follows cannot reach them.\n *\n * Filtering is deliberately conservative: it hides what is currently unusable\n * rather than guessing at a transport. Routing these to Mantle properly is a\n * separate change and a design call for the maintainers.\n */\nfunction needsUnsupportedTransport(entry: unknown): boolean {\n const provider = (entry as BedrockCatalogEntry | null)?.provider;\n return Boolean(provider && (provider.npm || provider.api || provider.shape));\n}\n\n/**\n * A small, stable fallback so Bedrock packs keep working offline or when\n * models.dev is unreachable. Intentionally minimal — the live catalog is the\n * source of truth and supersedes this within one fetch.\n */\nconst BEDROCK_FALLBACK_MODELS: BedrockModelEntry[] = [\n { id: 'us.anthropic.claude-opus-4-6-v1' },\n { id: 'us.anthropic.claude-sonnet-4-5-20250929-v1:0' },\n { id: 'us.anthropic.claude-haiku-4-5-20251001-v1:0' },\n];\n\ninterface CatalogCacheEntry {\n fetchedAt: number;\n ttl: number;\n models: BedrockModelEntry[];\n}\n\nlet catalogCache: CatalogCacheEntry | null = null;\nlet inflightFetch: Promise<BedrockModelEntry[]> | null = null;\n\n/** Reset the in-process Bedrock catalog cache (test seam). */\nexport function clearBedrockCatalogCache(): void {\n catalogCache = null;\n inflightFetch = null;\n}\n\nasync function fetchBedrockModels(signal: AbortSignal): Promise<BedrockModelEntry[]> {\n const response = await fetch(MODELS_DEV_API_URL, { signal });\n if (!response.ok) {\n throw new Error(`models.dev returned ${response.status}`);\n }\n const data = (await response.json()) as Record<string, { models?: Record<string, unknown> }>;\n const provider = data[BEDROCK_PROVIDER_ID];\n const models = provider?.models ?? {};\n return Object.entries(models)\n .filter(([, entry]) => !needsUnsupportedTransport(entry))\n .map(([id]) => id)\n .sort()\n .map(id => ({ id }));\n}\n\n/**\n * Return the available Amazon Bedrock models.\n *\n * - Returns the cached list when a recent fetch succeeded.\n * - On cache miss / expiry, fetches the models.dev catalog with a 5s timeout and\n * caches it for an hour.\n * - On fetch failure, returns a small hard-coded fallback (so packs still work\n * offline) and caches that briefly to avoid hammering the network.\n *\n * Concurrent calls during a fetch share the inflight promise.\n */\nexport async function getBedrockModelCatalog(): Promise<BedrockModelEntry[]> {\n const now = Date.now();\n if (catalogCache && now - catalogCache.fetchedAt < catalogCache.ttl) {\n return catalogCache.models;\n }\n\n if (inflightFetch) return inflightFetch;\n\n inflightFetch = (async (): Promise<BedrockModelEntry[]> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);\n try {\n const models = await fetchBedrockModels(controller.signal);\n catalogCache = { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models };\n return models;\n } catch (error) {\n catalogCache = {\n fetchedAt: Date.now(),\n ttl: CATALOG_FAILURE_TTL_MS,\n models: BEDROCK_FALLBACK_MODELS,\n };\n console.warn(\n 'Failed to fetch live Amazon Bedrock models, using fallback list:',\n error instanceof Error ? error.message : error,\n );\n return BEDROCK_FALLBACK_MODELS;\n } finally {\n clearTimeout(timer);\n inflightFetch = null;\n }\n })();\n\n return inflightFetch;\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,qBAAqB;AAC3B,MAAM,sBAAsB;AAE5B,MAAM,iBAAiB;AACvB,MAAM,yBAAyB;AAC/B,MAAM,2BAA2B;;;;;;;;;;;;;;;;AAoCjC,SAAS,0BAA0B,OAAyB;CAC1D,MAAM,WAAY,OAAsC;CACxD,OAAO,QAAQ,aAAa,SAAS,OAAO,SAAS,OAAO,SAAS,MAAM;AAC7E;;;;;;AAOA,MAAM,0BAA+C;CACnD,EAAE,IAAI,kCAAkC;CACxC,EAAE,IAAI,+CAA+C;CACrD,EAAE,IAAI,8CAA8C;AACtD;AAQA,IAAI,eAAyC;AAC7C,IAAI,gBAAqD;;AAGzD,SAAgB,2BAAiC;CAC/C,eAAe;CACf,gBAAgB;AAClB;AAEA,eAAe,mBAAmB,QAAmD;CACnF,MAAM,WAAW,MAAM,MAAM,oBAAoB,EAAE,OAAO,CAAC;CAC3D,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,uBAAuB,SAAS,QAAQ;CAI1D,MAAM,UADW,MADG,SAAS,KAAK,EAAA,CACZ,oBACC,EAAE,UAAU,CAAC;CACpC,OAAO,OAAO,QAAQ,MAAM,CAAC,CAC1B,QAAQ,GAAG,WAAW,CAAC,0BAA0B,KAAK,CAAC,CAAC,CACxD,KAAK,CAAC,QAAQ,EAAE,CAAC,CACjB,KAAK,CAAC,CACN,KAAI,QAAO,EAAE,GAAG,EAAE;AACvB;;;;;;;;;;;;AAaA,eAAsB,yBAAuD;CAE3E,IAAI,gBADQ,KAAK,IACK,IAAI,aAAa,YAAY,aAAa,KAC9D,OAAO,aAAa;CAGtB,IAAI,eAAe,OAAO;CAE1B,iBAAiB,YAA0C;EACzD,MAAM,aAAa,IAAI,gBAAgB;EACvC,MAAM,QAAQ,iBAAiB,WAAW,MAAM,GAAG,wBAAwB;EAC3E,IAAI;GACF,MAAM,SAAS,MAAM,mBAAmB,WAAW,MAAM;GACzD,eAAe;IAAE,WAAW,KAAK,IAAI;IAAG,KAAK;IAAgB;GAAO;GACpE,OAAO;EACT,SAAS,OAAO;GACd,eAAe;IACb,WAAW,KAAK,IAAI;IACpB,KAAK;IACL,QAAQ;GACV;GACA,QAAQ,KACN,oEACA,iBAAiB,QAAQ,MAAM,UAAU,KAC3C;GACA,OAAO;EACT,UAAU;GACR,aAAa,KAAK;GAClB,gBAAgB;EAClB;CACF,EAAA,CAAG;CAEH,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-prompt-cache.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic-prompt-cache.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,EAAG,IAAa,CAAC;AAExD;;;;;;;;;;GAUG;AACH,MAAM,MAAM,yBAAyB,GAAG,cAAc,GAAG,QAAQ,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-prompt-cache.js","names":[],"sources":["../../src/providers/anthropic-prompt-cache.ts"],"sourcesContent":["/**\n * TTL for the main agent's Anthropic prompt-cache breakpoints.\n * Observational memory's idle activation for Anthropic is set to the same value,\n * so buffered observations don't activate while the cache is still warm.\n */\nexport const ANTHROPIC_PROMPT_CACHE_TTL = '1h' as const;\n\n/**\n * Which Anthropic prompt-cache breakpoints a model writes.\n *\n * - `conversation`: the last system message and the latest message, with\n * {@link ANTHROPIC_PROMPT_CACHE_TTL}. For the main agent, whose next request\n * extends the same conversation.\n * - `system`: the last system message only, with a 5-minute TTL. For background\n * calls (observer, reflector, thread titles) that share instructions across\n * calls but send different content each time, so caching the content is a\n * write that is never read.\n */\nexport type AnthropicPromptCacheScope = 'conversation' | 'system';\n"],"mappings":";;;;;;AAKA,MAAa,6BAA6B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-thinking.d.ts","sourceRoot":"","sources":["../../src/providers/anthropic-thinking.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAG1D,eAAO,MAAM,gCAAgC,EAAE,MAAM,CAAC,mBAAmB,EAAE,MAAM,CAMhF,CAAC;AAOF,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,QAAQ,GAAG,MAAM,CAK9F;AAED,wBAAgB,4BAA4B,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAErE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"anthropic-thinking.js","names":[],"sources":["../../src/providers/anthropic-thinking.ts"],"sourcesContent":["import type { ActiveThinkingLevel } from '../thinking.js';\n\n// counts toward max_tokens: stay under the 32k output cap of Opus 4.0/4.1\nexport const ANTHROPIC_THINKING_BUDGET_TOKENS: Record<ActiveThinkingLevel, number> = {\n low: 4096,\n medium: 8192,\n high: 16384,\n xhigh: 24576,\n max: 24576,\n};\n\nconst ANTHROPIC_XHIGH_EFFORT_RE = /claude-(?:opus-4-[78]|opus-5|sonnet-5|fable-5)/;\nconst ADAPTIVE_THINKING_RE = /claude-(?:sonnet-4-6|opus-4-[678]|opus-5|sonnet-5|fable-5)/;\nconst BUDGET_THINKING_RE = /claude-(?:3-7|sonnet-4|opus-4|haiku-4-5)/;\nconst NO_THINKING_RE = /claude-(?:instant|v?2(?:[-.:]|$)|3(?:[-.]|$)|3-5)/;\n\nexport function getAnthropicThinkingCapability(modelId: string): 'adaptive' | 'budget' | 'none' {\n if (ADAPTIVE_THINKING_RE.test(modelId)) return 'adaptive';\n if (BUDGET_THINKING_RE.test(modelId)) return 'budget';\n if (NO_THINKING_RE.test(modelId)) return 'none';\n return 'adaptive';\n}\n\nexport function supportsAnthropicXhighEffort(modelId: string): boolean {\n return ANTHROPIC_XHIGH_EFFORT_RE.test(modelId);\n}\n"],"mappings":";AAGA,MAAa,mCAAwE;CACnF,KAAK;CACL,QAAQ;CACR,MAAM;CACN,OAAO;CACP,KAAK;AACP;AAEA,MAAM,4BAA4B;AAClC,MAAM,uBAAuB;AAC7B,MAAM,qBAAqB;AAC3B,MAAM,iBAAiB;AAEvB,SAAgB,+BAA+B,SAAiD;CAC9F,IAAI,qBAAqB,KAAK,OAAO,GAAG,OAAO;CAC/C,IAAI,mBAAmB,KAAK,OAAO,GAAG,OAAO;CAC7C,IAAI,eAAe,KAAK,OAAO,GAAG,OAAO;CACzC,OAAO;AACT;AAEA,SAAgB,6BAA6B,SAA0B;CACrE,OAAO,0BAA0B,KAAK,OAAO;AAC/C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"claude-max.d.ts","sourceRoot":"","sources":["../../src/providers/claude-max.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,IAAI,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAsBvD;;GAEG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAED;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,uBAkBlC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,2BAA2B,UAAW,yBAAyB,KAAG,uBA8D7E,CAAC;AAMH;;;;;;;;;GASG;AACH,wBAAgB,iCAAiC,CAC/C,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,aAAa,GAC5B,uBAAuB,GAAG,SAAS,CAiCrC;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CA2CnG;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,MAA4B,EACrC,OAAO,CAAC,EAAE;IACR,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjC,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,gBAAgB,CAAC,EAAE,yBAAyB,CAAC;CAC9C,GACA,iBAAiB,CAgCnB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"claude-max.js","names":[],"sources":["../../src/providers/claude-max.ts"],"sourcesContent":["/**\n * Claude Max OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with Claude Max plan.\n * The OAuth endpoint requires a specific system message to be present.\n */\n\nimport { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from './anthropic-prompt-cache.js';\nimport type { AnthropicPromptCacheScope } from './anthropic-prompt-cache.js';\nimport { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability } from './anthropic-thinking.js';\nimport type { ThinkingLevel } from './openai-codex.js';\n\nconst PROVIDER_NAME = 'Anthropic';\n\n// Required for Claude Max plan OAuth - the endpoint checks for this system message\nconst claudeCodeIdentity = \"You are Claude Code, Anthropic's official CLI for Claude.\";\n\n// Betas required for Claude Max plan OAuth. Merged with (not replacing) any\n// betas the AI SDK already set on the request — e.g. the SDK adds\n// `server-side-fallback-2026-06-01` when `providerOptions.anthropic.fallbacks`\n// is configured; dropping it makes the API reject the `fallbacks` body field\n// with \"Extra inputs are not permitted\".\nconst OAUTH_REQUIRED_BETAS = [\n 'oauth-2025-04-20',\n 'claude-code-20250219',\n 'interleaved-thinking-2025-05-14',\n 'fine-grained-tool-streaming-2025-05-14',\n];\n\n// Singleton auth storage instance\nlet authStorageInstance: AuthStorage | null = null;\n\n/**\n * Get or create the shared AuthStorage instance\n */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/**\n * Set a custom AuthStorage instance (useful for TUI integration)\n */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Middleware that injects the Claude Code identity system message\n * Required for Claude Max OAuth authentication\n */\nexport const claudeCodeMiddleware: LanguageModelMiddleware = {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n // Prepend the Claude Code identity as the first system message\n const systemMessage = {\n role: 'system' as const,\n content: claudeCodeIdentity,\n };\n\n if (params.temperature) {\n delete params.topP;\n }\n\n return {\n ...params,\n prompt: [systemMessage, ...params.prompt],\n };\n },\n};\n\n/**\n * Prompt caching middleware for Anthropic\n *\n * Adds cache breakpoints at strategic locations:\n * 1. Last system message (end of static instructions + dynamic memory)\n * 2. Most recent user/assistant message (conversation context), `conversation` scope only\n *\n * This allows Anthropic to cache:\n * - System prompts and instructions (rarely change)\n * - Conversation history up to the last message\n */\nexport const createPromptCacheMiddleware = (scope: AnthropicPromptCacheScope): LanguageModelMiddleware => ({\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n const prompt = [...params.prompt];\n\n const cacheControl = {\n type: 'ephemeral' as const,\n ttl: scope === 'conversation' ? ANTHROPIC_PROMPT_CACHE_TTL : ('5m' as const),\n };\n\n // Helper to add cache control to a message's last content part\n const addCacheToMessage = (msg: any) => {\n // For system messages with string content\n if (typeof msg.content === 'string') {\n return {\n ...msg,\n providerOptions: {\n ...msg.providerOptions,\n anthropic: { ...msg.providerOptions?.anthropic, cacheControl },\n },\n };\n }\n\n // For messages with array content, add to last part\n if (Array.isArray(msg.content) && msg.content.length > 0) {\n const content = [...msg.content];\n const lastPart = content[content.length - 1];\n content[content.length - 1] = {\n ...lastPart,\n providerOptions: {\n ...lastPart.providerOptions,\n anthropic: { ...lastPart.providerOptions?.anthropic, cacheControl },\n },\n };\n return { ...msg, content };\n }\n\n return msg;\n };\n\n // Find the last system message index\n let lastSystemIdx = -1;\n for (let i = prompt.length - 1; i >= 0; i--) {\n if ((prompt[i] as any).role === 'system') {\n lastSystemIdx = i;\n break;\n }\n }\n\n // Add cache breakpoint to last system message\n if (lastSystemIdx >= 0) {\n prompt[lastSystemIdx] = addCacheToMessage(prompt[lastSystemIdx]);\n }\n\n // Add cache breakpoint to the most recent message (last in array)\n const lastIdx = prompt.length - 1;\n if (scope === 'conversation' && lastIdx >= 0 && lastIdx !== lastSystemIdx) {\n prompt[lastIdx] = addCacheToMessage(prompt[lastIdx]);\n }\n\n return { ...params, prompt };\n },\n});\n\nfunction runAnthropicRequestLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n return runCatalogThinkingLevel(`anthropic/${modelId}`, level);\n}\n\n/**\n * Middleware that maps the session thinking level onto Anthropic extended\n * thinking. Returns `undefined` (no middleware) when the level is `off` or the\n * model doesn't support thinking, preserving the previous request shape.\n *\n * - Adaptive-era models (Sonnet 4.6+/Opus 4.6+): `thinking: adaptive` plus\n * `output_config.effort`, the closest effort the model accepts.\n * - Budget-era models (Claude 3.7 – Opus 4.5): `thinking: enabled` with a\n * `budget_tokens` value derived from the level.\n */\nexport function createAnthropicThinkingMiddleware(\n modelId: string,\n thinkingLevel?: ThinkingLevel,\n): LanguageModelMiddleware | undefined {\n if (!thinkingLevel || thinkingLevel === 'off') return undefined;\n const capability = getAnthropicThinkingCapability(modelId);\n const level = runAnthropicRequestLevel(modelId, thinkingLevel);\n if (level === 'off') return undefined;\n\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n const anthropicOptions = (params.providerOptions?.anthropic ?? {}) as Record<string, unknown>;\n // Don't override explicit per-request thinking configuration.\n if (anthropicOptions.thinking !== undefined || anthropicOptions.effort !== undefined) {\n return params;\n }\n\n // Anthropic rejects sampling parameters when thinking is enabled.\n delete params.temperature;\n delete params.topP;\n delete params.topK;\n\n params.providerOptions = {\n ...params.providerOptions,\n anthropic: {\n ...anthropicOptions,\n ...(capability === 'adaptive'\n ? { thinking: { type: 'adaptive', display: 'summarized' }, effort: level }\n : { thinking: { type: 'enabled', budgetTokens: ANTHROPIC_THINKING_BUDGET_TOKENS[level] } }),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Build a fetch function that handles Anthropic OAuth.\n * Preserves non-auth headers from init (critical for gateway auth header to survive\n * when used with the gateway). Strips `authorization` and `x-api-key`.\n */\nexport function buildAnthropicOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const storedCred = storage.get('anthropic');\n if (storedCred?.type === 'api_key') {\n throw new Error('Anthropic API key credential is configured, but OAuth is required.');\n }\n\n const accessToken = await storage.getApiKey('anthropic');\n if (!accessToken) {\n throw storage.get('anthropic')?.type === 'oauth'\n ? ProviderAuthRequiredError.signInExpired(PROVIDER_NAME)\n : ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);\n }\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n const requestBetas = (headers.get('anthropic-beta') ?? '')\n .split(',')\n .map(beta => beta.trim())\n .filter(Boolean);\n headers.set('anthropic-beta', Array.from(new Set([...OAUTH_REQUIRED_BETAS, ...requestBetas])).join(','));\n headers.set('anthropic-version', '2023-06-01');\n\n const requestUrl = url instanceof URL ? url.toString() : typeof url === 'string' ? url : url.url;\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: PROVIDER_NAME,\n requestUrl,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, { requestUrl });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an Anthropic model using Claude Max OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n */\nexport function opencodeClaudeMaxProvider(\n modelId: string = 'claude-sonnet-5-5',\n options?: {\n headers?: Record<string, string>;\n authStorage?: CredentialStore;\n thinkingLevel?: ThinkingLevel;\n promptCacheScope?: AnthropicPromptCacheScope;\n },\n): MastraModelConfig {\n const headers = options?.headers;\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, options?.thinkingLevel);\n const middleware = [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(options?.promptCacheScope ?? 'conversation'),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ];\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const anthropic = createAnthropic({\n apiKey: 'test-api-key',\n headers,\n });\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n }\n\n const anthropic = createAnthropic({\n apiKey: 'oauth-placeholder',\n headers,\n fetch: buildAnthropicOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Wrap with middleware to inject Claude Code identity and enable prompt caching\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;AAoBA,MAAM,gBAAgB;AAGtB,MAAM,qBAAqB;AAO3B,MAAM,uBAAuB;CAC3B;CACA;CACA;CACA;AACF;AAGA,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;AAMA,MAAa,uBAAgD;CAC3D,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EAErC,MAAM,gBAAgB;GACpB,MAAM;GACN,SAAS;EACX;EAEA,IAAI,OAAO,aACT,OAAO,OAAO;EAGhB,OAAO;GACL,GAAG;GACH,QAAQ,CAAC,eAAe,GAAG,OAAO,MAAM;EAC1C;CACF;AACF;;;;;;;;;;;;AAaA,MAAa,+BAA+B,WAA+D;CACzG,sBAAsB;CACtB,iBAAiB,OAAO,EAAE,aAAa;EACrC,MAAM,SAAS,CAAC,GAAG,OAAO,MAAM;EAEhC,MAAM,eAAe;GACnB,MAAM;GACN,KAAK,UAAU,iBAAA,OAA+C;EAChE;EAGA,MAAM,qBAAqB,QAAa;GAEtC,IAAI,OAAO,IAAI,YAAY,UACzB,OAAO;IACL,GAAG;IACH,iBAAiB;KACf,GAAG,IA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AC;EACvG,QAAQ,IAAI,qBAAqB,YAAY;EAE7C,MAAM,aAAa,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAM,IAAI;EAC7F,IAAI;GACF,OAAO,MAAM,2BAA2B,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC,GAAG;IAC9E,cAAc;IACd;GACF,CAAC;EACH,SAAS,OAAO;GACd,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAkC,EAAE,WAAW,CAAC;GAEhE,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,0BACd,UAAkB,qBAClB,SAMmB;CACnB,MAAM,UAAU,SAAS;CACzB,MAAM,qBAAqB,kCAAkC,SAAS,SAAS,aAAa;CAC5F,MAAM,aAAa;EACjB;EACA,4BAA4B,SAAS,oBAAoB,cAAc;EACvE,GAAI,qBAAqB,CAAC,kBAAkB,IAAI,CAAC;CACnD;CAGA,IAAI,QAAQ,IAAI,aAAa,UAAU,QAAQ,IAAI,QAAQ;EACzD,MAAM,YAAY,gBAAgB;GAChC,QAAQ;GACR;EACF,CAAC;EACD,OAAO,kBAAkB;GACvB,OAAO,UAAU,OAAO;GACxB;EACF,CAAC;CACH;CAEA,MAAM,YAAY,gBAAgB;EAChC,QAAQ;EACR;EACA,OAAO,yBAAyB,EAAE,aAAa,SAAS,YAAY,CAAC;CACvE,CAAC;CAGD,OAAO,kBAAkB;EACvB,OAAO,UAAU,OAAO;EACxB;CACF,CAAC;AACH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot-gateway.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot-gateway.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AACpH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAGxD,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D;;;;;;GAMG;AACH,qBAAa,oBAAqB,SAAQ,kBAAkB;;IAC1D,QAAQ,CAAC,EAAE,oBAA6B;IACxC,QAAQ,CAAC,IAAI,oBAAoB;IAGjC,YAAY,OAAO,GAAE;QAAE,eAAe,CAAC,EAAE,eAAe,CAAA;KAAO,EAG9D;IAMK,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAC,CAgB9D;IAED,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAE7C;IAEK,SAAS,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAEjD;IAED,WAAW,CAAC,QAAQ,EAAE,kBAAkB,GAAG,iBAAiB,GAAG,SAAS,CAKvE;IAED,oBAAoB,CAAC,IAAI,EAAE;QACzB,OAAO,EAAE,MAAM,CAAC;QAChB,UAAU,EAAE,MAAM,CAAC;QACnB,MAAM,EAAE,MAAM,CAAC;QACf,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,SAAS,CAAC,EAAE,GAAG,CAAC;QAChB,kBAAkB,CAAC,EAAE,GAAG,CAAC;KAC1B,GAAG,oBAAoB,CAKvB;CACF;AAED,wBAAgB,0BAA0B,CAAC,OAAO,CAAC,EAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAAG,oBAAoB,CAEhH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot-gateway.js","names":[],"sources":["../../src/providers/github-copilot-gateway.ts"],"sourcesContent":["import { MastraModelGateway } from '@mastra/core/llm';\nimport type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, ProviderConfig } from '@mastra/core/llm';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getAuthStorage, getCopilotModelCatalog, githubCopilotProvider } from './github-copilot.js';\n\nexport const GITHUB_COPILOT_GATEWAY_ID = 'github-copilot';\n\n/**\n * Standalone GitHub Copilot gateway.\n *\n * models.dev excludes Copilot from the shared registry, so Mastra Code supplies\n * the provider itself. It is its own gateway so catalog ids are the canonical\n * `github-copilot/<model>` rather than `mastracode/github-copilot/<model>`.\n */\nexport class GitHubCopilotGateway extends MastraModelGateway {\n readonly id = GITHUB_COPILOT_GATEWAY_ID;\n readonly name = 'GitHub Copilot';\n readonly #credentials?: CredentialStore;\n\n constructor(options: { credentialStore?: CredentialStore } = {}) {\n super();\n this.#credentials = options.credentialStore;\n }\n\n get #store(): CredentialStore {\n return this.#credentials ?? getAuthStorage();\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n try {\n const models = await getCopilotModelCatalog({ authStorage: this.#store });\n return {\n [GITHUB_COPILOT_GATEWAY_ID]: {\n name: 'GitHub Copilot',\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models: models.map(model => model.id),\n },\n };\n } catch (error) {\n console.warn('Failed to load GitHub Copilot model catalog:', error);\n return {};\n }\n }\n\n buildUrl(_modelId: string): string | undefined {\n return undefined;\n }\n\n async getApiKey(_modelId: string): Promise<string> {\n return '';\n }\n\n resolveAuth(_request: GatewayAuthRequest): GatewayAuthResult | undefined {\n // The OAuth token is attached per request by the Copilot fetch wrapper.\n return this.#store.get(GITHUB_COPILOT_GATEWAY_ID)?.type === 'oauth'\n ? { bearerToken: 'oauth', source: 'gateway' }\n : undefined;\n }\n\n resolveLanguageModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#store,\n }) as unknown as GatewayLanguageModel;\n }\n}\n\nexport function createGitHubCopilotGateway(options?: { credentialStore?: CredentialStore }): GitHubCopilotGateway {\n return new GitHubCopilotGateway(options);\n}\n"],"mappings":";;;AAKA,MAAa,4BAA4B;;;;;;;;AASzC,IAAa,uBAAb,cAA0C,mBAAmB;CAC3D,KAAc;CACd,OAAgB;CAChB;CAEA,YAAY,UAAiD,CAAC,GAAG;EAC/D,MAAM;EACN,KAAK,eAAe,QAAQ;CAC9B;CAEA,IAAI,SAA0B;EAC5B,OAAO,KAAK,gBAAgB,eAAe;CAC7C;CAEA,MAAM,iBAA0D;EAC9D,IAAI;GACF,MAAM,SAAS,MAAM,uBAAuB,EAAE,aAAa,KAAK,OAAO,CAAC;GACxE,OAAO,GACJ,4BAA4B;IAC3B,MAAM;IACN,cAAc;IACd,cAAc;IACd,SAAS,KAAK;IACd,QAAQ,OAAO,KAAI,UAAS,MAAM,EAAE;GACtC,EACF;EACF,SAAS,OAAO;GACd,QAAQ,KAAK,gDAAgD,KAAK;GAClE,OAAO,CAAC;EACV;CACF;CAEA,SAAS,UAAsC,CAE/C;CAEA,MAAM,UAAU,UAAmC;EACjD,OAAO;CACT;CAEA,YAAY,UAA6D;EAEvE,OAAO,KAAK,OAAO,IAAA,gBAA6B,CAAC,EAAE,SAAS,UACxD;GAAE,aAAa;GAAS,QAAQ;EAAU,IAC1C,KAAA;CACN;CAEA,qBAAqB,MAOI;EACvB,OAAO,sBAAsB,KAAK,SAAS;GACzC,SAAS,KAAK;GACd,aAAa,KAAK;EACpB,CAAC;CACH;AACF;AAEA,SAAgB,2BAA2B,SAAuE;CAChH,OAAO,IAAI,qBAAqB,OAAO;AACzC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot.d.ts","sourceRoot":"","sources":["../../src/providers/github-copilot.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAO1D,OAAO,KAAK,EAAE,iBAAiB,EAA4B,MAAM,qCAAqC,CAAC;AACvG,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAmB,MAAM,kBAAkB,CAAC;AAQzE,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAqED;;;;;;GAMG;AACH,wBAAgB,4BAA4B,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAgFd;AAwED;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,GAAE,MAAkB,EAC3B,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,iBAAiB,CAiBnB;AAsDD,wFAAwF;AACxF,wBAAgB,wBAAwB,IAAI,IAAI,CAG/C;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAC1C,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAC3C,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA2F9B"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"github-copilot.js","names":[],"sources":["../../src/providers/github-copilot.ts"],"sourcesContent":["/**\n * GitHub Copilot OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with GitHub Copilot's chat API.\n * The Copilot API speaks an OpenAI-compatible chat format, so we plug\n * `@ai-sdk/openai-compatible` into Copilot's API URL and use a custom fetch to inject\n * the bearer token and Copilot-specific headers.\n *\n * Inspired by:\n * - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/copilot.ts\n * - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport type { JSONSchema7 } from '@mastra/schema-compat';\nimport { applyCompatLayer, GoogleSchemaCompatLayer } from '@mastra/schema-compat';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { COPILOT_HEADERS, fetchCopilotModels, getGitHubCopilotBaseUrl } from '../auth/providers/github-copilot.js';\nimport type { CopilotModelEntry, GitHubCopilotCredentials } from '../auth/providers/github-copilot.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore, OAuthCredential } from '../auth/types.js';\n\nconst COPILOT_PROVIDER_ID = 'github-copilot';\nconst COPILOT_PROVIDER_NAME = 'GitHub Copilot';\n\n// Singleton auth storage instance (shared with claude-max.ts / openai-codex.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Heuristic: did this request come from the agent (e.g. tool result follow-ups) rather\n * than a fresh user turn? Mirrors opencode's `isAgent` logic — Copilot bills these\n * differently via the `x-initiator` header.\n */\nfunction detectIsAgent(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const messages = obj.messages;\n if (Array.isArray(messages) && messages.length > 0) {\n const last = messages[messages.length - 1] as { role?: string; content?: unknown };\n if (last?.role && last.role !== 'user') return true;\n if (Array.isArray(last?.content)) {\n // If the last user turn carries any tool_result parts, treat it as an agent turn.\n const hasToolResult = last.content.some(\n (part: unknown) => part && typeof part === 'object' && (part as { type?: string }).type === 'tool_result',\n );\n if (hasToolResult) return true;\n }\n }\n\n const input = obj.input;\n if (Array.isArray(input) && input.length > 0) {\n const last = input[input.length - 1] as { role?: string };\n if (last?.role && last.role !== 'user') return true;\n }\n\n return false;\n}\n\n/** Detect image/vision content in a request body. */\nfunction detectIsVision(body: unknown): boolean {\n if (!body || typeof body !== 'object') return false;\n const obj = body as Record<string, unknown>;\n\n const matchPart = (part: unknown): boolean => {\n if (!part || typeof part !== 'object') return false;\n const t = (part as { type?: string }).type;\n return t === 'image' || t === 'image_url' || t === 'input_image';\n };\n\n const messages = obj.messages;\n if (Array.isArray(messages)) {\n return messages.some(\n (msg: unknown) =>\n msg &&\n typeof msg === 'object' &&\n Array.isArray((msg as { content?: unknown }).content) &&\n ((msg as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n const input = obj.input;\n if (Array.isArray(input)) {\n return input.some(\n (item: unknown) =>\n item &&\n typeof item === 'object' &&\n Array.isArray((item as { content?: unknown }).content) &&\n ((item as { content: unknown[] }).content as unknown[]).some(matchPart),\n );\n }\n\n return false;\n}\n\n/**\n * Build a fetch wrapper that authenticates with GitHub Copilot OAuth.\n *\n * - Injects the short-lived Copilot bearer token (auto-refreshed by AuthStorage).\n * - Adds the VS Code-like Copilot headers required by the API.\n * - Rewrites the request URL onto the per-token API base when `rewriteUrl` is true.\n */\nexport function buildGitHubCopilotOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(COPILOT_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(COPILOT_PROVIDER_NAME);\n }\n\n let accessToken: string | undefined;\n let activeCred: OAuthCredential | undefined;\n if (storage.getOAuthCredential) {\n activeCred = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n accessToken = activeCred?.access;\n } else {\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n storage.reload();\n const reloaded = storage.get(COPILOT_PROVIDER_ID);\n activeCred = reloaded?.type === 'oauth' ? { ...reloaded, access: accessToken ?? reloaded.access } : undefined;\n }\n if (!accessToken || !activeCred) throw ProviderAuthRequiredError.signInExpired(COPILOT_PROVIDER_NAME);\n const enterpriseUrl = (activeCred as GitHubCopilotCredentials).enterpriseUrl;\n\n let parsedBody: unknown;\n try {\n const body = await request.clone().text();\n parsedBody = body ? JSON.parse(body) : undefined;\n } catch {\n parsedBody = undefined;\n }\n const isAgent = detectIsAgent(parsedBody);\n const isVision = detectIsVision(parsedBody);\n\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('x-initiator', isAgent ? 'agent' : 'user');\n headers.set('Openai-Intent', 'conversation-edits');\n if (isVision) {\n headers.set('Copilot-Vision-Request', 'true');\n }\n for (const [key, value] of Object.entries(COPILOT_HEADERS)) {\n // Only set if caller didn't already provide it (allow overrides for tests).\n if (!headers.has(key)) {\n headers.set(key, value);\n }\n }\n\n const finalUrl =\n opts.rewriteUrl !== false ? rewriteToCopilotBase(request, accessToken, enterpriseUrl) : new URL(request.url);\n\n const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body;\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: COPILOT_PROVIDER_NAME,\n requestUrl: finalUrl.toString(),\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: finalUrl.toString(),\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\nfunction rewriteToCopilotBase(url: string | URL | Request, token: string, enterpriseDomain?: string): URL {\n const original = url instanceof URL ? url : new URL(typeof url === 'string' ? url : (url as Request).url);\n const base = new URL(getGitHubCopilotBaseUrl(token, enterpriseDomain));\n // Copilot's OpenAI-compatible API serves endpoints at the root of the base host\n // (`/chat/completions`, `/responses`, `/models`, ...) — not under a `/v1/` prefix\n // like api.openai.com does. The @ai-sdk/openai default baseURL is\n // `https://api.openai.com/v1`, so the SDK builds requests like\n // `https://api.openai.com/v1/chat/completions`. Strip the leading `/v1` segment\n // when rewriting onto the Copilot base or Copilot will return 404 Not Found.\n const pathname = original.pathname.replace(/^\\/v1(\\/|$)/, '/');\n return new URL(`${pathname}${original.search}`, base);\n}\n\nfunction isGeminiModel(modelId: string): boolean {\n return modelId.startsWith('gemini-');\n}\n\nfunction applyGeminiSchemaCompatToTools(modelId: string, tools: unknown): unknown {\n if (!Array.isArray(tools)) {\n return tools;\n }\n\n const compatLayer = new GoogleSchemaCompatLayer({\n provider: COPILOT_PROVIDER_ID,\n modelId,\n supportsStructuredOutputs: false,\n });\n\n return tools.map(tool => {\n if (!tool || typeof tool !== 'object' || (tool as { type?: unknown }).type !== 'function') {\n return tool;\n }\n\n const functionTool = tool as { inputSchema?: JSONSchema7 };\n if (!functionTool.inputSchema) {\n return tool;\n }\n\n return {\n ...functionTool,\n inputSchema: applyCompatLayer({\n schema: functionTool.inputSchema,\n compatLayers: [compatLayer],\n mode: 'aiSdkSchema',\n }).jsonSchema as JSONSchema7,\n };\n });\n}\n\n/** Middleware that prevents sending parameters Copilot's endpoint rejects. */\nfunction createCopilotMiddleware(modelId: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v4',\n transformParams: async ({ params }) => {\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n if (isGeminiModel(modelId)) {\n (params as { tools?: unknown }).tools = applyGeminiSchemaCompatToTools(\n modelId,\n (params as { tools?: unknown }).tools,\n );\n }\n\n return params;\n },\n };\n}\n\n/**\n * Creates a model that talks to GitHub Copilot using OAuth credentials.\n *\n * Copilot's `/chat/completions` endpoint is OpenAI-compatible, but GitHub Copilot\n * is not OpenAI. Use the generic OpenAI-compatible adapter with Copilot's base URL\n * instead of the OpenAI provider plus URL rewriting.\n */\nexport function githubCopilotProvider(\n modelId: string = 'gpt-4.1',\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const headers = options?.headers;\n const copilot = createOpenAICompatible({\n name: COPILOT_PROVIDER_ID,\n baseURL: 'https://api.githubcopilot.com',\n apiKey: process.env.NODE_ENV === 'test' || process.env.VITEST ? 'test-api-key' : 'oauth-placeholder',\n headers,\n fetch:\n process.env.NODE_ENV === 'test' || process.env.VITEST\n ? undefined\n : (buildGitHubCopilotOAuthFetch({ rewriteUrl: false, authStorage: options?.authStorage }) as any),\n });\n\n return wrapLanguageModel({\n model: copilot.chatModel(modelId),\n middleware: [createCopilotMiddleware(modelId)],\n });\n}\n\n// ---------------------------------------------------------------------------\n// Live model catalog\n// ---------------------------------------------------------------------------\n\n/**\n * Hard-coded fallback advertised when the live `/models` request fails (network\n * down, expired token, etc.). Keep this conservative because the live catalog is\n * the source of truth for the user's currently-enabled Copilot models.\n *\n * Available across all paid Copilot tiers and free of premium-request charges.\n */\nconst COPILOT_FALLBACK_MODELS: CopilotModelEntry[] = [\n {\n id: 'gpt-4.1',\n name: 'GPT-4.1',\n vendor: 'OpenAI',\n supportedEndpoints: ['/chat/completions'],\n isAnthropicShaped: false,\n supportsVision: true,\n supportsToolCalls: true,\n },\n];\n\nconst CATALOG_TTL_MS = 10 * 60 * 1000;\nconst CATALOG_FAILURE_TTL_MS = 60 * 1000;\nconst CATALOG_FETCH_TIMEOUT_MS = 5_000;\n\ninterface CatalogCacheEntry {\n fetchedAt: number;\n ttl: number;\n models: CopilotModelEntry[];\n}\n\nconst catalogCache = new Map<string, CatalogCacheEntry>();\nconst inflightFetches = new Map<string, Promise<CopilotModelEntry[]>>();\n\n/**\n * Resolve the account identity for a credential read through `getApiKey`, which\n * may await a refresh with a rotation landing inside it. The registry is\n * consulted on both sides of that await, and only an id that survived it names\n * the account that produced the token: an id that moved describes whichever\n * account is active *now*, so trusting it would file this fetch's models under\n * the wrong account and serve them to it. Unidentified is the safe answer — the\n * caller then skips the TTL cache, exactly as it does when the store exposes no\n * registry at all. (`AuthStorage` never needs this: its snapshots name their\n * account.)\n */\nfunction readStableAccountId(storage: CredentialStore, idBeforeToken: string | undefined): string | undefined {\n const idAfterToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n return idBeforeToken !== undefined && idBeforeToken === idAfterToken ? idAfterToken : undefined;\n}\n\n/** Reset the in-process Copilot catalog cache (test seam, also useful after logout). */\nexport function clearCopilotCatalogCache(): void {\n catalogCache.clear();\n inflightFetches.clear();\n}\n\n/**\n * Return the user's currently-available Copilot models.\n *\n * - Returns `[]` when the user is not logged in to GitHub Copilot.\n * - Returns the cached list when a recent fetch succeeded.\n * - On the cache-miss / expired path, fetches `/models` with a 5s timeout, filters\n * to picker-enabled and non-policy-disabled models, then caches for 10 minutes.\n * - On fetch failure, returns a small hard-coded fallback (so packs still work\n * offline) and caches that for 1 minute to avoid hammering the API.\n *\n * Concurrent calls during a fetch share the inflight promise.\n */\nexport async function getCopilotModelCatalog(\n opts: { authStorage?: CredentialStore } = {},\n): Promise<CopilotModelEntry[]> {\n const storage = opts.authStorage ?? getAuthStorage();\n\n // Resolve one coherent credential snapshot before consulting the cache so a\n // token can never be paired with another account's enterprise endpoint.\n // `getOAuthCredential` is optional (deployed stores have no local registry),\n // so fall back to the always-present `getApiKey`, taking any enterprise\n // endpoint from the same slot via `get()`.\n let accessToken: string | undefined;\n let accountInstanceId: string | undefined;\n let enterpriseUrl: string | undefined;\n if (storage.getOAuthCredential) {\n const credential = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') return [];\n accessToken = credential.access;\n // A snapshot that names its account is coherent by construction — the store\n // read the identity and the token in the same breath. One that does not\n // cannot be attributed to a registry entry we then read afterwards, because\n // a rotation may have landed in between; leave it unnamed so the caller\n // skips the TTL cache instead of guessing. (`AuthStorage` always stamps.)\n accountInstanceId = credential.accountInstanceId;\n enterpriseUrl = (credential as GitHubCopilotCredentials).enterpriseUrl;\n } else {\n // This store republishes its registry but not the OAuth snapshot API, so the\n // identity has to come from the registry. `getApiKey` may await a refresh and\n // a rotation can land inside it, so bracket the fetch: only an id that held\n // still names the account that produced this token.\n const idBeforeToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;\n accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);\n if (!accessToken) return [];\n accountInstanceId = readStableAccountId(storage, idBeforeToken);\n const stored = storage.get(COPILOT_PROVIDER_ID);\n if (stored?.type === 'oauth') {\n enterpriseUrl = (stored as GitHubCopilotCredentials).enterpriseUrl;\n }\n // The id is non-secret, and keying per account is what keeps entitlements\n // (per account, per `github-copilot-catalog.test.ts`) from leaking across a\n // rotation. Deriving the key from the token is what `cba11389e7` removed.\n }\n const baseUrl = getGitHubCopilotBaseUrl(accessToken, enterpriseUrl);\n // No identity means the store cannot name the account it just served, so the\n // TTL cache cannot be keyed per account — one entry would outlive the request\n // and serve those models to every other account of the store. The in-flight\n // map is no safer: two callers that resolved *different* accounts of an\n // unnamed store would otherwise collide on one key and share whichever\n // catalog was fetched first. So both caches are identified-only, and an\n // unnamed store pays one `/models` request per call.\n const credentialKey = accountInstanceId === undefined ? undefined : `${accountInstanceId}\\0${baseUrl}`;\n const dedupeKey = credentialKey;\n\n const now = Date.now();\n const cached = credentialKey ? catalogCache.get(credentialKey) : undefined;\n if (cached && now - cached.fetchedAt < cached.ttl) return cached.models;\n\n const existingFetch = dedupeKey === undefined ? undefined : inflightFetches.get(dedupeKey);\n if (existingFetch) return existingFetch;\n\n const fetchPromise = (async (): Promise<CopilotModelEntry[]> => {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);\n try {\n const models = await fetchCopilotModels({\n baseUrl,\n bearerToken: accessToken,\n signal: controller.signal,\n });\n if (credentialKey) catalogCache.set(credentialKey, { fetchedAt: Date.now(), ttl: CATALOG_TTL_MS, models });\n return models;\n } finally {\n clearTimeout(timer);\n }\n } catch (error) {\n if (credentialKey) {\n catalogCache.set(credentialKey, {\n fetchedAt: Date.now(),\n ttl: CATALOG_FAILURE_TTL_MS,\n models: COPILOT_FALLBACK_MODELS,\n });\n }\n console.warn(\n 'Failed to fetch live GitHub Copilot models, using fallback list:',\n error instanceof Error ? error.message : error,\n );\n return COPILOT_FALLBACK_MODELS;\n } finally {\n if (dedupeKey !== undefined) inflightFetches.delete(dedupeKey);\n }\n })();\n if (dedupeKey !== undefined) inflightFetches.set(dedupeKey, fetchPromise);\n return fetchPromise;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAyBA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAG9B,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAS,cAAc,MAAwB;CAC7C,IAAI,CAAC,QAAQ,OAAO,SAAS,UAAU,OAAO;CAC9C,MAAM,MAAM;CAEZ,MAAM,WAAW,IAAI;CACrB,IAAI,MAAM,QAAQ,QAAQ,KAAK,SAAS,SAAS,GAAG;EAClD,MAAM,OAAO,SAAS,SAAS,SAAS;EACxC,IAAI,MAAM,QAAQ,KAAK,SAAS,QAAQ,OAAO;EAC/C,IAAI,MAAM,QAAQ,MAAM,OAAO,GAEP;OAAA,KAAK,QAAQ,MAChC,SAAkB,QAAQ,OAAO,SAAS,YAAa,KAA2B,SA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