@mastra/code-sdk 1.21.0-alpha.5 → 1.21.0-alpha.7
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.js +0 -2
- package/dist/agents/memory.js +0 -2
- package/dist/agents/model.js +0 -2
- 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 +0 -2
- 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 +0 -2
- 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 +0 -2
- 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.js +0 -2
- package/dist/providers/openai-codex.js +0 -2
- 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.js +0 -2
- 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 +22 -21
- 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":"mastracode-gateway.js","names":[],"sources":["../../src/agents/mastracode-gateway.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { CustomAvailableModel, CustomModelCatalogProvider } from '@mastra/core/agent-controller';\nimport {\n GATEWAY_AUTH_HEADER,\n MastraGateway,\n MastraModelGateway,\n ModelRouterLanguageModel,\n PROVIDER_REGISTRY,\n} from '@mastra/core/llm';\nimport type {\n GatewayAuthRequest,\n GatewayAuthResult,\n GatewayLanguageModel,\n MastraModelGatewayInterface,\n ProviderConfig,\n} from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { getCustomProviderId, loadSettings, MASTRA_GATEWAY_PROVIDER } from '../onboarding/settings.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport {\n buildAnthropicOAuthFetch,\n claudeCodeMiddleware,\n createAnthropicThinkingMiddleware,\n createPromptCacheMiddleware,\n opencodeClaudeMaxProvider,\n} from '../providers/claude-max.js';\nimport { githubCopilotProvider } from '../providers/github-copilot.js';\nimport { createGoogleThinkingMiddleware } from '../providers/google-thinking.js';\nimport { kimiCodingProvider } from '../providers/kimi-coding.js';\nimport {\n getCredentialProviderId,\n KIMI_CODING_CREDENTIAL_ID,\n KIMI_CODING_PROVIDER_ID,\n normalizeAnthropicModelId,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\nimport {\n buildOpenAICodexOAuthFetch,\n createCodexMiddleware,\n createPromptCacheKeyMiddleware,\n createReasoningEffortMiddleware,\n getEffectiveThinkingLevel,\n getRequestThreadId,\n openaiCodexProvider,\n THINKING_LEVEL_TO_REASONING_EFFORT,\n} from '../providers/openai-codex.js';\nimport type { ThinkingLevel } from '../providers/openai-codex.js';\nimport {\n ModelRouterLanguageModelWithThinking,\n providerThinkingOptions,\n withThinkingOptionsModel,\n} from '../providers/provider-thinking.js';\nimport { xaiProvider } from '../providers/xai.js';\nimport { getAppDataDir } from '../utils/project.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\n\nconst PROVIDERS: Record<string, ProviderConfig> = PROVIDER_REGISTRY;\n\nexport {\n MASTRA_GATEWAY_PREFIX,\n OPENAI_PREFIX,\n remapOpenAIModelForCodexOAuth,\n stripMastraGatewayPrefix,\n} from '../providers/model-ids.js';\n\nexport const MASTRACODE_GATEWAY_ID = 'mastracode';\n\n/** Gateway request header. `false` lets the gateway drop prompt cache controls no route can serve instead of refusing the request. */\nconst GATEWAY_STRICT_CAPABILITIES_HEADER = 'x-gateway-strict-capabilities';\n\n/** Organization keys reach the gateway that leaves memory, and so the prompt, to the client. */\nfunction isOrganizationGatewayKey(apiKey: string): boolean {\n return apiKey.startsWith('msk-gateway-') || apiKey.startsWith('mskv2_');\n}\n\ntype ModelRequestHeaders = Record<string, string>;\n\nexport type MastraCodeCustomProvider = { name: string; url: string; apiKey?: string; models?: string[] };\n\nexport type MastraCodeGatewayOptions = {\n mastraGatewayBaseUrl: string;\n mastraGatewayApiKey?: string;\n routeThroughMastraGateway: boolean;\n thinkingLevel?: ThinkingLevel;\n /** Anthropic prompt-cache breakpoints to write. Defaults to `conversation`. */\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n customProviders?: MastraCodeCustomProvider[];\n settingsPath?: string;\n /**\n * Per-tenant credential source for this gateway instance. Defaults to the\n * server-global file-backed `AuthStorage`; deployed web passes the calling\n * tenant's store so model calls use the caller's own credentials.\n */\n credentialStore?: CredentialStore;\n};\n\n/**\n * Global file-backed credential store for local (TUI) model resolution.\n *\n * Constructed lazily, NOT at module scope: `AuthStorage`'s default path is\n * resolved from `MASTRA_APP_DATA_DIR` at construction, and this module is\n * routinely imported before test harnesses / embedders point that variable at\n * an isolated directory — an import-time construction would permanently pin\n * the developer's real app-data dir for every credential read.\n */\nlet authStorageSingleton: AuthStorage | undefined;\nlet authStorageSingletonDir: string | undefined;\n\nexport function getGlobalAuthStorage(): AuthStorage {\n // Keyed by the resolved app-data dir: in-process harnesses re-point\n // MASTRA_APP_DATA_DIR per run inside one long-lived worker, so a store\n // pinned to a previous dir must be discarded, not reused.\n const dir = getAppDataDir();\n if (!authStorageSingleton || authStorageSingletonDir !== dir) {\n authStorageSingleton = new AuthStorage();\n authStorageSingletonDir = dir;\n }\n return authStorageSingleton;\n}\n\nexport function reloadAuthStorage() {\n getGlobalAuthStorage().reload();\n}\n\n/**\n * Resolve the Anthropic API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getAnthropicApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('anthropic');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('anthropic')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false\n ? undefined\n : process.env.ANTHROPIC_API_KEY?.trim() || undefined;\n}\n\n/**\n * Resolve the OpenAI API key.\n * Main slot → dedicated apikey: slot → env var.\n */\nexport function getOpenAIApiKey(credentials: CredentialStore = getGlobalAuthStorage()): string | undefined {\n const storedCred = credentials.get('openai-codex');\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey('openai-codex')?.trim();\n if (dedicatedKey) return dedicatedKey;\n return credentials.allowEnvironmentFallback === false ? undefined : process.env.OPENAI_API_KEY?.trim() || undefined;\n}\n\nfunction anthropicApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers: ModelRequestHeaders | undefined,\n thinkingLevel: ThinkingLevel | undefined,\n promptCacheScope: AnthropicPromptCacheScope,\n) {\n const anthropic = createAnthropic({ apiKey, headers });\n const thinkingMiddleware = createAnthropicThinkingMiddleware(modelId, thinkingLevel);\n return wrapLanguageModel({\n model: anthropic(modelId),\n middleware: [createPromptCacheMiddleware(promptCacheScope), ...(thinkingMiddleware ? [thinkingMiddleware] : [])],\n });\n}\n\nfunction openaiApiKeyProvider(\n modelId: string,\n apiKey: string,\n headers?: ModelRequestHeaders,\n thinkingLevel?: ThinkingLevel,\n) {\n const openai = createOpenAI({ apiKey, baseURL: process.env.OPENAI_BASE_URL, headers });\n const middleware =\n thinkingLevel && thinkingLevel !== 'off'\n ? createReasoningEffortMiddleware(\n 'openai',\n THINKING_LEVEL_TO_REASONING_EFFORT[getEffectiveThinkingLevel(modelId, thinkingLevel)],\n )\n : undefined;\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [...(middleware ? [middleware] : []), ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n}\n\nfunction getProviderAuthKey(\n providerId: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n): string | undefined {\n const authProviderId = getCredentialProviderId(providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return storedCred.key.trim();\n }\n const dedicatedKey = credentials.getStoredApiKey(authProviderId)?.trim();\n if (dedicatedKey) return dedicatedKey;\n // `/api-keys` stores keys under the catalog provider id (`kimi-code-plan-cn`),\n // which can differ from the credential id.\n const catalogKey = authProviderId !== providerId ? credentials.getStoredApiKey(providerId)?.trim() : undefined;\n if (catalogKey) return catalogKey;\n if (credentials.allowEnvironmentFallback === false) return undefined;\n return authProviderId === KIMI_CODING_CREDENTIAL_ID ? process.env.KIMI_API_KEY?.trim() || undefined : undefined;\n}\n\nexport function resolveAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string): GatewayAuthResult | undefined {\n return MastraCodeGateway.resolveProviderAuth(request, mastraGatewayApiKey);\n}\n\nfunction getGatewayProviderKey(gatewayId: string, providerId: string): string {\n if (gatewayId === 'models.dev') return providerId;\n return providerId === gatewayId ? gatewayId : `${gatewayId}/${providerId}`;\n}\n\nfunction parseGatewayRouterId(\n routerId: string,\n gateway: MastraModelGatewayInterface,\n): { gatewayId: string; providerId: string; modelId: string } {\n const [firstPart = '', secondPart = '', ...restParts] = routerId.split('/');\n const gatewayId = gateway.id;\n\n if (firstPart === gatewayId && secondPart) {\n return {\n gatewayId,\n providerId: secondPart,\n modelId: restParts.join('/'),\n };\n }\n\n return {\n gatewayId,\n providerId: firstPart,\n modelId: [secondPart, ...restParts].filter(Boolean).join('/'),\n };\n}\n\nfunction hasResolvedAuth(auth: GatewayAuthResult | undefined): boolean {\n if (!auth) return false;\n if (auth.apiKey || auth.bearerToken) return true;\n return auth.headers ? Object.keys(auth.headers).length > 0 : false;\n}\n\nasync function resolveGatewayProviderAuth(\n gateway: MastraModelGatewayInterface,\n routerId: string,\n): Promise<GatewayAuthResult | undefined> {\n if (!gateway.resolveAuth) return undefined;\n\n const parsed = parseGatewayRouterId(routerId, gateway);\n try {\n const result = await gateway.resolveAuth({\n gatewayId: parsed.gatewayId,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId,\n });\n return hasResolvedAuth(result) ? result : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function getMastraCodeProviderConfigs(\n gateway: MastraModelGatewayInterface,\n): Promise<Record<string, ProviderConfig>> {\n const providers: Record<string, ProviderConfig> = { ...PROVIDERS };\n\n try {\n const gatewayProviders = await gateway.fetchProviders();\n for (const [providerId, config] of Object.entries(gatewayProviders)) {\n providers[getGatewayProviderKey(gateway.id, providerId)] = {\n ...config,\n gateway: gateway.id,\n };\n }\n } catch (error) {\n console.warn(`Failed to load providers from gateway ${gateway.id}:`, error);\n }\n\n return providers;\n}\n\nfunction getApiKeyEnvVar(providerConfig: Pick<ProviderConfig, 'apiKeyEnvVar'> | undefined): string | undefined {\n const envVars = providerConfig?.apiKeyEnvVar;\n return Array.isArray(envVars) ? envVars[0] : envVars;\n}\n\nexport function providerApiKeyEnvVar(providerId: string): string | undefined {\n return getApiKeyEnvVar(PROVIDERS[providerId]);\n}\n\n/**\n * Whether the process environment has a key for a models.dev provider. Checks every\n * env var the registry lists, as the models.dev gateway does when `resolveModel`\n * gets no gateway credential (e.g. `GOOGLE_API_KEY` or `GOOGLE_GENERATIVE_AI_API_KEY`).\n */\nexport function hasProviderEnvironmentKey(providerId: string): boolean {\n const envVars = PROVIDERS[providerId]?.apiKeyEnvVar;\n if (!envVars) return false;\n return (Array.isArray(envVars) ? envVars : [envVars]).some(envVar => Boolean(process.env[envVar]?.trim()));\n}\n\n/** Servers call custom endpoints too: a redirect could aim that call at an address the saved URL never named. */\nconst fetchWithoutRedirects: typeof fetch = (input, init) => fetch(input, { ...init, redirect: 'error' });\n\nexport class MastraCodeGateway extends MastraModelGateway {\n readonly id = MASTRACODE_GATEWAY_ID;\n readonly name = 'MastraCode Gateway';\n\n readonly #mastraGateway: MastraGateway;\n readonly #mastraGatewayBaseUrl: string;\n readonly #mastraGatewayApiKey?: string;\n readonly #routeThroughMastraGateway: boolean;\n readonly #thinkingLevel?: ThinkingLevel;\n readonly #anthropicPromptCacheScope: AnthropicPromptCacheScope;\n readonly #customProviders?: MastraCodeCustomProvider[];\n readonly #settingsPath?: string;\n readonly #credentials: CredentialStore;\n\n constructor({\n mastraGatewayBaseUrl,\n mastraGatewayApiKey,\n routeThroughMastraGateway,\n thinkingLevel,\n anthropicPromptCacheScope,\n customProviders,\n settingsPath,\n credentialStore,\n }: MastraCodeGatewayOptions) {\n super();\n this.#mastraGateway = new MastraGateway({ baseUrl: mastraGatewayBaseUrl });\n this.#mastraGatewayBaseUrl = mastraGatewayBaseUrl;\n this.#mastraGatewayApiKey = mastraGatewayApiKey;\n this.#routeThroughMastraGateway = routeThroughMastraGateway;\n this.#thinkingLevel = thinkingLevel;\n this.#anthropicPromptCacheScope = anthropicPromptCacheScope ?? 'conversation';\n this.#customProviders = customProviders;\n this.#settingsPath = settingsPath;\n this.#credentials = credentialStore ?? getGlobalAuthStorage();\n }\n\n static getMastraGatewayApiKey(): string | undefined {\n return getGlobalAuthStorage().getStoredApiKey(MASTRA_GATEWAY_PROVIDER) ?? process.env['MASTRA_GATEWAY_API_KEY'];\n }\n\n /** @deprecated Renamed to {@link MastraCodeGateway.getMastraGatewayApiKey}. */\n static getMemoryGatewayApiKey(): string | undefined {\n return MastraCodeGateway.getMastraGatewayApiKey();\n }\n\n /**\n * Claim an unprefixed model id (e.g. a bare `anthropic/...`) when this gateway\n * can authenticate it via OAuth or a stored/env credential. This lets the\n * shared gateway router select MastraCode for auth resolution, so the status\n * bar and `/api-keys` reflect OAuth logins instead of only checking env vars.\n */\n handlesModel(modelId: string): boolean {\n const parsed = parseGatewayRouterId(modelId, this);\n if (!parsed.providerId || !parsed.modelId) return false;\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) return true;\n if (this.#customProvider(parsed.providerId)) return true;\n return hasResolvedAuth(\n MastraCodeGateway.resolveProviderAuth(\n {\n gatewayId: this.id,\n providerId: parsed.providerId,\n modelId: parsed.modelId,\n routerId: modelId,\n },\n undefined,\n this.#credentials,\n ),\n );\n }\n\n static resolveProviderAuth(\n request: GatewayAuthRequest,\n mastraGatewayApiKey?: string,\n credentials: CredentialStore = getGlobalAuthStorage(),\n ): GatewayAuthResult | undefined {\n if (request.gatewayId === 'mastra' && mastraGatewayApiKey) {\n return { apiKey: mastraGatewayApiKey, source: 'gateway' };\n }\n\n const authProviderId = getCredentialProviderId(request.providerId);\n const storedCred = credentials.get(authProviderId);\n if (storedCred?.type === 'oauth') {\n return { bearerToken: 'oauth', source: 'gateway' };\n }\n\n const apiKey = getProviderAuthKey(request.providerId, credentials);\n return apiKey ? { apiKey, source: 'gateway' } : undefined;\n }\n\n static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider {\n return async () => {\n const registry = await getMastraCodeProviderConfigs(gateway);\n const models: CustomAvailableModel[] = [];\n\n for (const [provider, providerConfig] of Object.entries(registry)) {\n const apiKeyEnvVar = getApiKeyEnvVar(providerConfig);\n const hasEnvKey = apiKeyEnvVar ? Boolean(process.env[apiKeyEnvVar]) : false;\n const modelNames = providerConfig.models;\n if (!Array.isArray(modelNames)) continue;\n\n const gatewayAuth = modelNames[0]\n ? await resolveGatewayProviderAuth(gateway, `${provider}/${modelNames[0]}`)\n : undefined;\n\n for (const modelName of modelNames) {\n const id = `${provider}/${modelName}`;\n models.push({\n id,\n provider,\n modelName,\n hasApiKey: hasEnvKey || Boolean(gatewayAuth),\n apiKeyEnvVar: apiKeyEnvVar || undefined,\n });\n }\n }\n\n return models;\n };\n }\n\n createModelCatalogProvider(): CustomModelCatalogProvider {\n return MastraCodeGateway.createModelCatalogProvider(this);\n }\n\n #getCustomProviders(): MastraCodeCustomProvider[] {\n // Explicit constructor list wins; then a registered source (deployed web,\n // DB-backed — authoritative, so settings.json is never consulted); then\n // the local file-backed settings.\n return this.#customProviders ?? resolveCustomProviders() ?? loadSettings(this.#settingsPath).customProviders;\n }\n\n /**\n * The custom provider a provider id refers to, if any. Every method that\n * resolves a model or its credentials goes through this lookup, so a custom\n * endpoint only ever authenticates with its own key: it is never handed a\n * credential saved for another provider, even when the ids collide. A model\n * routed through the Mastra gateway is never a custom provider.\n */\n #customProvider(providerId: string): MastraCodeCustomProvider | undefined {\n if (this.#routeThroughMastraGateway) return undefined;\n return this.#getCustomProviders().find(provider => providerId === getCustomProviderId(provider.name));\n }\n\n async fetchProviders(): Promise<Record<string, ProviderConfig>> {\n // Catalog auth (`handlesModel`, `resolveAuth`) reads this store, while\n // `/api-keys` and logins write through other AuthStorage instances. Pick\n // up their changes on every catalog refresh.\n this.#credentials.reload();\n const providers: Record<string, ProviderConfig> = {};\n for (const provider of this.#getCustomProviders()) {\n const models = provider.models ?? [];\n if (!models.length) continue;\n providers[getCustomProviderId(provider.name)] = {\n name: provider.name,\n url: provider.url,\n apiKeyEnvVar: '',\n apiKeyHeader: 'Authorization',\n gateway: this.id,\n models,\n };\n }\n\n // Subscription providers are not listed here: catalog ids from this gateway\n // are namespaced (`mastracode/<provider>/...`). Kimi augments the models.dev\n // `kimi-code-plan-cn` provider (claimed via `handlesModel`), and Copilot,\n // which models.dev excludes, has its own `github-copilot` gateway.\n return providers;\n }\n\n buildUrl(modelId: string): string | undefined | Promise<string | undefined> {\n return this.#routeThroughMastraGateway ? this.#mastraGateway.buildUrl(modelId) : modelId;\n }\n\n async getApiKey(modelId: string): Promise<string> {\n // The model router passes its gateway-qualified id (`mastracode/<provider>/<model>`).\n const { providerId } = parseGatewayRouterId(stripMastraGatewayPrefix(modelId), this);\n if (this.#routeThroughMastraGateway) return this.#mastraGatewayApiKey ?? '';\n if (!providerId) return '';\n const customProvider = this.#customProvider(providerId);\n if (customProvider) return customProvider.apiKey ?? '';\n return getProviderAuthKey(providerId, this.#credentials) ?? '';\n }\n\n resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined {\n if (this.#routeThroughMastraGateway && this.#mastraGatewayApiKey) {\n return { apiKey: this.#mastraGatewayApiKey, source: 'gateway' };\n }\n\n const customProvider = this.#customProvider(request.providerId);\n if (customProvider) {\n return customProvider.apiKey ? { apiKey: customProvider.apiKey, source: 'gateway' } : { source: 'gateway' };\n }\n\n return MastraCodeGateway.resolveProviderAuth(request, undefined, this.#credentials);\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 const customProvider = this.#customProvider(args.providerId);\n if (customProvider) {\n const provider = createOpenAICompatible({\n name: args.providerId,\n baseURL: customProvider.url,\n apiKey: args.apiKey,\n headers: args.headers,\n fetch: fetchWithoutRedirects,\n });\n const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : undefined;\n const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);\n if (!middleware) {\n return provider.chatModel(args.modelId);\n }\n return wrapLanguageModel({\n model: provider.chatModel(args.modelId),\n middleware: [middleware],\n });\n }\n\n if (args.providerId === 'github-copilot') {\n return githubCopilotProvider(args.modelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n // A gateway model's key is the gateway's: it must not go to Moonshot's own API.\n if (args.providerId === 'moonshotai' && !this.#routeThroughMastraGateway) {\n // Prefer the gateway-resolved key (stored credentials), then the canonical\n // registry env var. Keep the legacy typo name as a fallback for anyone who\n // set it because of the previous error message.\n const apiKey =\n args.apiKey?.trim() || process.env.MOONSHOT_API_KEY?.trim() || process.env.MOONSHOT_AI_API_KEY?.trim();\n if (!apiKey) {\n throw new Error('Need MOONSHOT_API_KEY');\n }\n return createAnthropic({\n apiKey,\n baseURL: 'https://api.moonshot.ai/anthropic/v1',\n name: 'moonshotai.anthropicv1',\n headers: args.headers,\n })(args.modelId);\n }\n\n if (args.providerId === 'anthropic') {\n return this.#resolveAnthropicModel(args);\n }\n\n if (args.providerId === 'openai') {\n const openaiModel = this.#resolveOpenAIModel(args);\n if (openaiModel) return openaiModel;\n }\n\n if (args.providerId === 'xai' && this.#credentials.get('xai')?.type === 'oauth') {\n return withThinkingOptionsModel(\n xaiProvider(args.modelId, { headers: args.headers, authStorage: this.#credentials }),\n providerThinkingOptions(`xai/${args.modelId}`, this.#thinkingLevel),\n );\n }\n\n if (this.#routeThroughMastraGateway) return this.#mastraGateway.resolveLanguageModel(args);\n\n if (args.providerId === 'google') {\n return this.#resolveGoogleModel(args);\n }\n\n if (args.providerId === KIMI_CODING_PROVIDER_ID || args.providerId === KIMI_CODING_CREDENTIAL_ID) {\n return kimiCodingProvider(args.modelId, {\n apiKey: args.apiKey,\n headers: args.headers,\n credentialStore: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const routedModelId: `${string}/${string}` = `${args.providerId}/${args.modelId}`;\n return new ModelRouterLanguageModelWithThinking(\n { id: routedModelId, apiKey: args.apiKey, headers: args.headers },\n providerThinkingOptions(routedModelId, this.#thinkingLevel),\n ) as unknown as GatewayLanguageModel;\n }\n\n #resolveAnthropicModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const bareModelId = normalizeAnthropicModelId(args.modelId);\n const storedCred = this.#credentials.get('anthropic');\n const thinkingMiddleware = createAnthropicThinkingMiddleware(bareModelId, this.#thinkingLevel);\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const anthropic = createAnthropic({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildAnthropicOAuthFetch({ authStorage: this.#credentials }),\n });\n\n return wrapLanguageModel({\n model: anthropic(bareModelId),\n middleware: [\n claudeCodeMiddleware,\n createPromptCacheMiddleware(this.#anthropicPromptCacheScope),\n ...(thinkingMiddleware ? [thinkingMiddleware] : []),\n ],\n });\n }\n\n // Project keys (`msk_…`) get server-side memory: that gateway rewrites the prompt, so it owns the cache layout.\n if (!isOrganizationGatewayKey(args.apiKey)) {\n return this.#mastraGateway.resolveLanguageModel({ ...args, modelId: bareModelId });\n }\n\n // Anthropic caches only on request, so this route needs the same breakpoints\n // as the direct ones. The gateway refuses a cache request no route can serve\n // unless the caller opts out of strict matching; opting out lets such a\n // model run uncached. The opt-out covers prompt cache controls only.\n return wrapLanguageModel({\n model: this.#mastraGateway.resolveLanguageModel({\n ...args,\n modelId: bareModelId,\n headers: { ...args.headers, [GATEWAY_STRICT_CAPABILITIES_HEADER]: 'false' },\n }),\n middleware: [createPromptCacheMiddleware(this.#anthropicPromptCacheScope)],\n });\n }\n\n if (storedCred?.type === 'oauth') {\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n if (storedCred?.type === 'api_key' && storedCred.key.trim().length > 0) {\n return anthropicApiKeyProvider(\n bareModelId,\n storedCred.key.trim(),\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n const apiKey = getAnthropicApiKey(this.#credentials);\n if (apiKey) {\n return anthropicApiKeyProvider(\n bareModelId,\n apiKey,\n args.headers,\n this.#thinkingLevel,\n this.#anthropicPromptCacheScope,\n );\n }\n\n // No stored credentials: use the OAuth-backed provider so the first request can trigger login.\n return opencodeClaudeMaxProvider(bareModelId, {\n headers: args.headers,\n authStorage: this.#credentials,\n thinkingLevel: this.#thinkingLevel,\n promptCacheScope: this.#anthropicPromptCacheScope,\n }) as unknown as GatewayLanguageModel;\n }\n\n #resolveOpenAIModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel | undefined {\n const storedCred = this.#credentials.get('openai-codex');\n\n if (this.#routeThroughMastraGateway) {\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n const resolvedBareModelId = resolvedModelId.substring(OPENAI_PREFIX.length);\n const effectiveLevel = getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel ?? 'medium');\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(args.headers));\n const openai = createOpenAI({\n apiKey: 'oauth-gateway-placeholder',\n baseURL: `${this.#mastraGatewayBaseUrl}/v1`,\n headers: {\n [GATEWAY_AUTH_HEADER]: `Bearer ${args.apiKey}`,\n ...args.headers,\n },\n fetch: buildOpenAICodexOAuthFetch({ authStorage: this.#credentials, rewriteUrl: false }),\n });\n\n return wrapLanguageModel({\n model: openai.responses(resolvedBareModelId),\n middleware: [middleware, ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : [])],\n });\n }\n\n return this.#mastraGateway.resolveLanguageModel(args);\n }\n\n if (storedCred?.type === 'oauth') {\n const resolvedModelId = remapOpenAIModelForCodexOAuth(`openai/${args.modelId}`);\n return openaiCodexProvider(resolvedModelId.substring(OPENAI_PREFIX.length), {\n thinkingLevel: this.#thinkingLevel && getEffectiveThinkingLevel(args.modelId, this.#thinkingLevel),\n headers: args.headers,\n authStorage: this.#credentials,\n }) as unknown as GatewayLanguageModel;\n }\n\n const apiKey = getOpenAIApiKey(this.#credentials);\n if (apiKey) {\n return openaiApiKeyProvider(args.modelId, apiKey, args.headers, this.#thinkingLevel);\n }\n\n return undefined;\n }\n\n #resolveGoogleModel(args: {\n modelId: string;\n providerId: string;\n apiKey: string;\n headers?: Record<string, string>;\n transport?: any;\n responsesWebSocket?: any;\n }): GatewayLanguageModel {\n const routerModel = new ModelRouterLanguageModel({\n id: `${args.providerId}/${args.modelId}`,\n apiKey: args.apiKey,\n headers: args.headers,\n }) as unknown as GatewayLanguageModel;\n const thinkingMiddleware = createGoogleThinkingMiddleware(args.modelId, this.#thinkingLevel);\n if (!thinkingMiddleware) return routerModel;\n\n return wrapLanguageModel({\n model: routerModel as any,\n middleware: [thinkingMiddleware],\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8DA,MAAM,YAA4C;AASlD,MAAa,wBAAwB;;AAGrC,MAAM,qCAAqC;;AAG3C,SAAS,yBAAyB,QAAyB;CACzD,OAAO,OAAO,WAAW,cAAc,KAAK,OAAO,WAAW,QAAQ;AACxE;;;;;;;;;;AAgCA,IAAI;AACJ,IAAI;AAEJ,SAAgB,uBAAoC;CAIlD,MAAM,MAAM,cAAc;CAC1B,IAAI,CAAC,wBAAwB,4BAA4B,KAAK;EAC5D,uBAAuB,IAAI,YAAY;EACvC,0BAA0B;CAC5B;CACA,OAAO;AACT;AAEA,SAAgB,oBAAoB;CAClC,qBAAqB,CAAC,CAAC,OAAO;AAChC;;;;;AAMA,SAAgB,mBAAmB,cAA+B,qBAAqB,GAAuB;CAC5G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B,YAAY,CAAC,EAAE,MAAM,EACrB,OAAO,CAAC,EAAE;IACR,qBAAqB,CAAC,EAAE,OAAO,CAAC;IAChC,+GAA+G;IAC/G,QAAQ,CAAC,EAAE,cAAc,CAAC;IAC1B,gFAAgF;IAChF,eAAe,CAAC,EAAE,sBAAsB,CAAC;CAC1C,yBA4B0C;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE;IAoI3E;;;OAGG;eACc,OAAO,CAAC,IAAI,CAAC;EAKjC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"memory.js","names":[],"sources":["../../src/agents/memory.ts"],"sourcesContent":["import type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { ModelRouterEmbeddingModel } from '@mastra/core/llm';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { MastraEmbeddingModel, MastraEmbeddingOptions, MastraVector } from '@mastra/core/vector';\nimport type { fastembed } from '@mastra/fastembed';\nimport { Memory } from '@mastra/memory';\nimport { DEFAULT_OBS_THRESHOLD, DEFAULT_REF_THRESHOLD, MIN_OBSERVATION_THRESHOLD } from '../constants.js';\nimport { LOCAL_KNOWLEDGE_ORG_ID } from '../knowledge-scope.js';\nimport { MASTRACODE_AUTO_OM_MODELS, resolveAutoOMModelId } from '../onboarding/packs.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport { ANTHROPIC_PROMPT_CACHE_TTL } from '../providers/anthropic-prompt-cache.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getOmScope } from '../utils/project.js';\nimport { embedInSubprocess } from './fastembed-subprocess.js';\nimport { canUseProvider, getActiveMemoryRoute, resolveModel } from './model.js';\n\n/**\n * `fastembed.small`, run in a reusable child process (see `FastembedWorker`) so ONNX Runtime and the model\n * never load into the agent process.\n */\nconst lazyFastembedSmall: typeof fastembed.small = {\n specificationVersion: 'v3',\n provider: 'fastembed',\n modelId: 'bge-small-en-v1.5',\n maxEmbeddingsPerCall: 256,\n supportsParallelCalls: true,\n doEmbed: options => embedInSubprocess(options),\n};\n\n/** A recall embedder: a `provider/model` router string or an AI SDK embedding model. */\nexport type MemoryEmbedder = string | MastraEmbeddingModel<string>;\n\n/** Route-backed OM fallback entry. */\ntype MemoryModelRouteEntry = { id: string; model: ReturnType<typeof resolveModel> };\n\n/**\n * Resolve the active model route's memory models, starting at a same-thread\n * pending fallback hop. Returns `'auto'` when the route's first memory model is\n * Auto, and `undefined` when the route sets no memory model.\n */\nfunction resolveRouteMemoryModels(\n state: MastraCodeState | undefined,\n threadId: string | null | undefined,\n resolve: (modelId: string) => ReturnType<typeof resolveModel>,\n): MemoryModelRouteEntry[] | 'auto' | undefined {\n const memoryRoute = getActiveMemoryRoute(state, threadId);\n if (memoryRoute[0]?.memoryModelId === 'auto') return 'auto';\n const seenModelIds = new Set<string>();\n const appearances = new Map<string, number>();\n const entries: MemoryModelRouteEntry[] = [];\n for (const entry of memoryRoute) {\n if (!entry.memoryModelId || entry.memoryModelId === 'auto' || seenModelIds.has(entry.memoryModelId)) continue;\n seenModelIds.add(entry.memoryModelId);\n const occurrence = (appearances.get(entry.id) ?? 0) + 1;\n appearances.set(entry.id, occurrence);\n try {\n entries.push({\n id: `${entry.id}:memory${occurrence === 1 ? '' : `#${occurrence}`}`,\n model: resolve(entry.memoryModelId),\n });\n } catch {\n break;\n }\n }\n return entries.length > 0 ? entries : undefined;\n}\n\n/**\n * The authoritative per-caller Factory memory-settings row, placed on the request\n * context before Factory's model-dependent processors run. `null` means the row\n * exists but is empty (every role auto). An unavailable sentinel or a missing\n * value on a Factory-owned session falls back to Auto roles and default\n * thresholds/attachments, so memory keeps working while Factory reports the error.\n */\ninterface FactoryMemorySettings {\n observerModelId: string | null;\n reflectorModelId: string | null;\n observationThreshold: number | null;\n reflectionThreshold: number | null;\n observeAttachments: 'auto' | boolean | null;\n}\n\ntype FactoryMemorySettingsContext =\n | FactoryMemorySettings\n | null\n | { status: 'unavailable'; reason: string }\n | undefined;\n\nfunction getFactoryMemorySettingsContext(requestContext: RequestContext): FactoryMemorySettingsContext {\n return requestContext.get('mastra__factoryMemorySettings') as FactoryMemorySettingsContext;\n}\n\nfunction isFactoryMemorySettingsUnavailable(\n settings: FactoryMemorySettingsContext,\n): settings is { status: 'unavailable'; reason: string } {\n return settings !== null && typeof settings === 'object' && 'status' in settings && settings.status === 'unavailable';\n}\n\nfunction getMainModelId(requestContext: RequestContext): string | undefined {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n return controller?.session.modelId || (controller?.getState()?.currentModelId as string | undefined);\n}\n\n/**\n * Resolve one OM role's model for this invocation. Returns `'auto'` for Memory's\n * auto policy, or a concrete model. Factory's DB row is authoritative for\n * Factory sessions (an unreadable row falls back to auto). Otherwise the active\n * model route's memory models win, then the per-role selection, then legacy\n * concrete settings.\n */\nfunction resolveOmRoleModelForRequest(\n role: 'observer' | 'reflector',\n requestContext: RequestContext,\n settingsPath?: string,\n options?: { disableSettingsOmSeed?: boolean },\n): 'auto' | ReturnType<typeof resolveModel> | MemoryModelRouteEntry[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const resolveOptions = { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' } as const;\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const isFactory = typeof state?.factoryProjectId === 'string';\n\n const useModel = (modelId: string) => {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, modelId);\n return resolveModel(modelId, resolveOptions);\n };\n const useAuto = () => {\n requestContext.set(`om.${role}.selectionMode`, 'auto');\n // These two keys are declared in the span-context allowlist\n // (`mastracode/sdk/src/index.ts`), so traces can report intent separately from\n // the effective concrete model without either being mistaken for a model ID.\n requestContext.set(\n `om.${role}.effectiveModelId`,\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n );\n return 'auto' as const;\n };\n\n if (\n isFactoryMemorySettingsUnavailable(factorySettingsContext) ||\n (factorySettingsContext === undefined && isFactory)\n ) {\n return useAuto();\n }\n if (factorySettingsContext !== undefined) {\n const factoryModelId = factorySettingsContext?.[`${role}ModelId`];\n return factoryModelId ? useModel(factoryModelId) : useAuto();\n }\n\n // The configured settings file, not the default one: a caller that points the\n // agent at another settings path must get the same override resolution for\n // observational memory as it does for the main model. Hosts that disable the\n // settings seed never read it.\n const settings = options?.disableSettingsOmSeed ? undefined : loadSettings(settingsPath);\n const routeMemory = resolveRouteMemoryModels(state, controller?.threadId, modelId =>\n resolveModel(modelId, resolveOptions),\n );\n if (routeMemory === 'auto') return useAuto();\n if (routeMemory) {\n requestContext.set(`om.${role}.selectionMode`, 'model');\n requestContext.set(`om.${role}.effectiveModelId`, routeMemory[0]?.model.modelId);\n return routeMemory.length === 1 ? routeMemory[0]!.model : routeMemory;\n }\n\n const selection: unknown = state?.[`${role}ModelSelection`];\n if (selection === 'auto') return useAuto();\n if (typeof selection === 'string' && selection) return useModel(selection);\n if (\n selection &&\n typeof selection === 'object' &&\n 'modelId' in selection &&\n typeof selection.modelId === 'string' &&\n selection.modelId\n ) {\n return useModel(selection.modelId);\n }\n\n const roleOverride =\n role === 'observer' ? settings?.models?.observerModelOverride : settings?.models?.reflectorModelOverride;\n if (roleOverride) return useModel(roleOverride);\n const legacyModelId = state?.[`${role}ModelId`];\n if (typeof legacyModelId === 'string' && legacyModelId) return useModel(legacyModelId);\n return useAuto();\n}\n\nconst DYNAMIC_AGENTS_MD_INSTRUCTION =\n 'Messages wrapped in <system-reminder type=\"dynamic-agents-md\" ...>...</system-reminder> are ephemeral project-context instructions injected from files on disk. Do NOT observe or extract information from these messages — they are reloaded automatically when needed and should not be stored in memory.';\n\n// Derived from https://github.com/JuliusBrussee/caveman and adapted for OM use with fixed full-level compression.\nconst CAVEMAN_OM_INSTRUCTION = `Respond terse like smart caveman. All technical substance stay. Only fluff die.\n\nUse full caveman compression style.\n\nDrop: articles (a/an/the), filler (just/really/basically/actually/simply), pleasantries (sure/certainly/of course/happy to), hedging. Fragments OK. Short synonyms (big not extensive, fix not \"implement a solution for\"). Technical terms exact. Code blocks unchanged. Errors quoted exact. Leave out the words \"agent\" and \"assistant\" at the start of each observation line, it is assumed each line is referring to the assistant unless it specifically says it was about the user. Leave out parenthesis and other text characters like * that would not contribute to understanding the observations.\n\nPattern: \\`[thing] [action] [reason]. [next step]\\`\n\nNot: \"Sure! I'd be happy to help you with that. The issue you're experiencing is likely caused by...\"\nYes: \"Bug in auth middleware. Token expiry check use < not <=. Fix:\"\n\nExample 1\n🔴 14:31 user asks why React component rerenders\n🟡 14:32 saw inline object prop create new ref each render, cause rerender\n✅ 14:34 fixed render issue by wrap object in useMemo\n\nExample 2\n🟡 15:10 explained pool reuse DB connections, skip repeat handshake overhead\n\nDon't say \"Agent did x\", say \"did x\". It will be assumed the agent did what was observed. The who should only be specified for the user or other third parties: \"user asked x\"\n\nDrop caveman for: security warnings, irreversible action confirmations, multi-step sequences where fragment order risks misread, user asks to clarify or repeats question, and anything that requires remembering verbatim content. Resume caveman after clear part done`;\n\nexport { LOCAL_KNOWLEDGE_ORG_ID };\n\n/**\n * Mastra Code's own title instructions: session lists show one narrow line per\n * title. They differ from Core's default in three ways: the title is 3 to 5\n * words instead of up to 80 characters, it names the topic instead of\n * summarising the message, and it does not end with a period.\n */\nexport const TITLE_INSTRUCTIONS = `\n - you will generate a short title based on a conversation transcript between a user and an assistant\n - the transcript lines are prefixed with \"User:\" and \"Assistant:\" — never reply to, answer, or continue the transcript\n - always produce a title, even when the transcript is only a greeting or trivial exchange\n - the title must be 3 to 5 words long\n - the title should name the topic of the user's message, not repeat or answer it\n - do not use quotes or colons, and do not end with a period\n - the entire text you return will be used as the title`;\n\n/**\n * Dynamic memory factory function.\n * Reads OM thresholds from controller state via requestContext.\n * Model functions also read from requestContext (no mutable bridge needed).\n */\nexport function getDynamicMemory(\n storage: MastraCompositeStore,\n vector?: MastraVector,\n settingsPath?: string,\n options?: {\n disableSettingsOmSeed?: boolean;\n /** Recall embedder, used only with `vector`. Omitted → local `fastembed.small` (bge-small, 384 dimensions). */\n embedder?: MemoryEmbedder;\n /** Options passed to every embedding call, e.g. provider options or headers. */\n embedderOptions?: MastraEmbeddingOptions;\n },\n) {\n // Built now, so a missing provider key throws here rather than on the first embed.\n const embedder = !vector\n ? undefined\n : typeof options?.embedder === 'string'\n ? new ModelRouterEmbeddingModel(options.embedder)\n : (options?.embedder ?? lazyFastembedSmall);\n // Cache is scoped per storage instance (per getDynamicMemory call) so a\n // Memory bound to one storage is never reused after storage changes.\n let cachedMemory: Memory | null = null;\n let cachedMemoryKey: string | null = null;\n // Instances replaced by a config change may still have background work in flight.\n const retiredMemories = new Set<Memory>();\n\n // Observer/reflector model functions — read the current model ID from\n // controller state via requestContext (propagated by OM's agent.generate).\n // Bound here so the configured settings path reaches role overrides and pack\n // memory-model resolution.\n const getObserverModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('observer', requestContext, settingsPath, options);\n const getReflectorModel = ({ requestContext }: { requestContext: RequestContext }) =>\n resolveOmRoleModelForRequest('reflector', requestContext, settingsPath, options);\n // Routes the concrete model Memory's `'auto'` picks through Mastra Code's\n // credential-aware resolver, like every other Mastra Code model.\n const resolveMemoryModel = (modelId: string, { requestContext }: { requestContext?: RequestContext }) =>\n resolveModel(modelId, { remapForCodexOAuth: true, requestContext, anthropicPromptCacheScope: 'system' });\n\n const resolveMemory = ({ requestContext }: { requestContext: RequestContext }) => {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = controller?.getState() as MastraCodeState | undefined;\n const factoryProjectId = state?.factoryProjectId;\n const isFactory = typeof factoryProjectId === 'string' && factoryProjectId.trim().length > 0;\n\n // Factory sessions share a memory resource across a Factory's runs and a\n // user's sessions, so their scope is fixed to thread: one shared record would\n // hand every run the others' work and invalidate their prompt caches. Recall\n // search still reaches the whole resource. Neither session state, the env\n // var, nor a repository's database.json can switch it.\n const omScope = isFactory ? 'thread' : (state?.omScope ?? getOmScope(state?.projectPath));\n const isResourceScope = omScope === 'resource';\n\n // The Factory row is authoritative and read per invocation, so a stored\n // threshold/attachment change reaches the running Memory without a session.\n const factorySettingsContext = getFactoryMemorySettingsContext(requestContext);\n const factorySettingsUnavailable =\n isFactoryMemorySettingsUnavailable(factorySettingsContext) || (factorySettingsContext === undefined && isFactory);\n const factorySettings = factorySettingsUnavailable ? null : factorySettingsContext;\n // Rows saved before validation can still hold a thread-scope threshold that\n // @mastra/memory refuses because it does not exceed the activation buffer.\n // Resource scope has no activation buffer and keeps its saved value.\n const storedObsThreshold =\n factorySettings !== undefined\n ? (factorySettings?.observationThreshold ?? DEFAULT_OBS_THRESHOLD)\n : (state?.observationThreshold ?? DEFAULT_OBS_THRESHOLD);\n const obsThreshold = isResourceScope ? storedObsThreshold : Math.max(storedObsThreshold, MIN_OBSERVATION_THRESHOLD);\n const refThreshold =\n factorySettings !== undefined\n ? (factorySettings?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD)\n : (state?.reflectionThreshold ?? DEFAULT_REF_THRESHOLD);\n const caveman = state?.cavemanObservations ?? false;\n\n const observerPreviousObservationTokens = 1000;\n // The row is authoritative: an absent value means the user left it on Auto,\n // which the config API reports as 'auto' and Memory resolves by model\n // capability.\n const observeAttachments =\n factorySettings !== undefined ? (factorySettings?.observeAttachments ?? 'auto') : state?.observeAttachments;\n // Factory sessions get a factory-only config, so the cache key carries\n // Factory presence to keep those configs from cross-serving.\n const cacheKey = `${obsThreshold}:${refThreshold}:${omScope}:${observerPreviousObservationTokens}:${caveman ? 1 : 0}:${observeAttachments}:${isFactory ? 1 : 0}`;\n if (cachedMemory && cachedMemoryKey === cacheKey) {\n return cachedMemory;\n }\n\n const observerInstruction = caveman\n ? `${DYNAMIC_AGENTS_MD_INSTRUCTION}\\n\\n${CAVEMAN_OM_INSTRUCTION}`\n : DYNAMIC_AGENTS_MD_INSTRUCTION;\n const reflectionInstruction = caveman ? CAVEMAN_OM_INSTRUCTION : undefined;\n\n if (cachedMemory) {\n const retired = cachedMemory;\n retiredMemories.add(retired);\n // settled() rejects if the instance's OM engine failed to start; that must not surface as\n // an unhandled rejection from a background retirement.\n void retired\n .settled()\n .catch(() => {})\n .finally(() => retiredMemories.delete(retired));\n }\n\n cachedMemory = new Memory({\n storage,\n vector: vector || false,\n embedder,\n embedderOptions: options?.embedderOptions,\n options: {\n // Generate a durable title from the first user message. Every client uses\n // the same title in its thread list and active-session chrome. Title\n // generation takes the primary OM model only — its model field does not\n // accept fallback arrays.\n generateTitle:\n process.env.MASTRACODE_DISABLE_TITLE_GENERATION === '1'\n ? false\n : {\n instructions: TITLE_INSTRUCTIONS,\n model: ({ requestContext }) => {\n const resolved = getObserverModel({ requestContext });\n if (resolved === 'auto') {\n return resolveMemoryModel(\n resolveAutoOMModelId(getMainModelId(requestContext), providerId =>\n canUseProvider(providerId, { requestContext }),\n ),\n { requestContext },\n );\n }\n return Array.isArray(resolved) ? resolved[0]!.model : resolved;\n },\n },\n observationalMemory:\n process.env.MASTRACODE_DISABLE_OBSERVATIONAL_MEMORY === '1'\n ? false\n : {\n enabled: true,\n autoModels: MASTRACODE_AUTO_OM_MODELS,\n canUseProvider,\n resolveModel: resolveMemoryModel,\n temporalMarkers: true,\n retrieval: vector ? { vector: true } : true,\n scope: omScope,\n // The main agent writes Anthropic cache entries with this TTL; 'auto' can't see it.\n activateAfterIdle: { default: 'auto', anthropic: ANTHROPIC_PROMPT_CACHE_TTL },\n activateOnProviderChange: true,\n observation: {\n bufferTokens: isResourceScope ? false : 1 / 5,\n bufferActivation: isResourceScope ? undefined : 2000,\n model: getObserverModel,\n messageTokens: obsThreshold,\n blockAfter: 2,\n previousObserverTokens: observerPreviousObservationTokens,\n threadTitle: true,\n instruction: observerInstruction,\n observeAttachments,\n },\n reflection: {\n bufferActivation: isResourceScope ? undefined : 1 / 2,\n blockAfter: 1.1,\n model: getReflectorModel,\n observationTokens: refThreshold,\n instruction: reflectionInstruction,\n },\n },\n },\n });\n cachedMemoryKey = cacheKey;\n\n return cachedMemory;\n };\n\n return Object.assign(resolveMemory, {\n /**\n * Wait for background memory work (buffered observations, reflections, indexing) in every\n * instance this factory created. Await before closing storage.\n */\n async settled(): Promise<void> {\n // Drain every instance even if one rejects, so teardown can still close storage.\n await Promise.allSettled([cachedMemory?.settled(), ...[...retiredMemories].map(memory => memory.settled())]);\n },\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAM,qBAA6C;CACjD,sBAAsB;CACtB,UAAU;CACV,SAAS;CACT,sBAAsB;CACtB,uBAAuB;CACvB,UAAS,YAAW,kBAAkB,OAAO;AAC/C;;;;;;AAaA,SAAS,yBACP,OACA,UACA,SAC8C;CAC9C,MAAM,cAAc,qBAAqB,OAAO,QAAQ;CACxD,IAAI,YAAY,EAAE,EAAE,kBAAkB,QAAQ,OAAO;CACrD,MAAM,+BAAe,IAAI,IAAY;CACrC,MAAM,8BAAc,IAAI,IAAoB;CAC5C,MAAM,UAAmC,CAAC;CAC1C,KAAK,MAAM,SAAS,aAAa;EAC/B,IAAI,CAAC,MAAM,iBAAiB,MAAM,kBAAkB,UAAU,aAAa,IAAI,MAAM,aAAa,GAAG;EACrG,aAAa,IAAI,MAAM,aAAa;EACpC,MAAM,cAAc,YAAY,IAAI,MAAM,EAAE,KAAK,KAAK;EACtD,YAAY,IAAI,MAAM,IAAI,UAAU;EACpC,IAAI;GACF,QAAQ,KAAK;IACX,IAAI,GAAG,MAAM,GAAG,SAAS,eAAe,IAAI,KAAK,IAAI;IACrD,OAAO,QAAQ,MAAM,aAAa;GACpC,CAAC;EACH,QAAQ;GACN;EACF;CACF;CACA,OAAO,QAAQ,SAAS,IAAI,UAAU,KAAA;AACxC;AAuBA,SAAS,gCAAgC,gBAA8D;CACrG,OAAO,eAAe,IAAI,+BAA+B;AAC3D;AAEA,SAAS,m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AAG,IAAI,GACvB,MAAM,GAAG,SAAS,CAQpB;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAC/B,EAAE,cAAc,EAAE,EAAE;IAAE,cAAc,EAAE,cAAc,CAAA;CAAE,EACtD,YAAY,CAAC,EAAE,MAAM,GACpB,aAAa,GAAG,SAAS,CAI3B"}
|
package/dist/agents/model.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../src/agents/model.ts"],"sourcesContent":["import type { ModelWithRetries } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { ModelRouterLanguageModel } from '@mastra/core/llm';\nimport type { GatewayLanguageModel, IdentifiedModelConfig, MastraModelGatewayInterface } from '@mastra/core/llm';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { getRequestAccountSelection, isRequestAccountRoutingExhausted } from '../auth/account-routing-context.js';\nimport type { RequestContextReader } from '../auth/account-routing-context.js';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport type { CredentialStore, OAuthAccountRecord } from '../auth/types.js';\nimport { MODEL_ROUTE_MAX_ENTRIES } from '../constants.js';\nimport { toMemoryModelId } from '../onboarding/packs.js';\nimport {\n loadSettings,\n MASTRA_GATEWAY_PROVIDER,\n resolveDefaultThinkingLevel,\n stripMastraCodeCustomProviderPrefix,\n} from '../onboarding/settings.js';\nimport { AMAZON_BEDROCK_GATEWAY_ID, createAmazonBedrockGateway } from '../providers/amazon-bedrock-gateway.js';\nimport type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';\nimport { GOOGLE_VERTEX_GATEWAY_ID, createGoogleVertexGateway } from '../providers/google-vertex-gateway.js';\nimport { normalizeLegacyModelId } from '../providers/model-ids.js';\nimport { isThinkingLevelSetting } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nimport {\n hasCredentialTenantResolver,\n prepareCredentialTenant,\n resolveCredentialScope,\n resolveCredentialStore,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nimport { resolveCustomProviders } from './custom-provider-source.js';\nimport {\n MASTRA_GATEWAY_PREFIX,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n getGlobalAuthStorage,\n hasProviderEnvironmentKey,\n reloadAuthStorage,\n stripMastraGatewayPrefix,\n} from './mastracode-gateway.js';\nimport type { MastraCodeGatewayOptions } from './mastracode-gateway.js';\n\nexport {\n getAnthropicApiKey,\n getOpenAIApiKey,\n MASTRACODE_GATEWAY_ID,\n MastraCodeGateway,\n remapOpenAIModelForCodexOAuth,\n resolveAuth,\n} from './mastracode-gateway.js';\nexport type { MastraCodeCustomProvider, MastraCodeGatewayOptions } from './mastracode-gateway.js';\nexport {\n setCredentialStoreProvider,\n hasCredentialStoreProvider,\n resolveTenantFromRequestContext,\n} from './credential-resolver.js';\nexport type { CredentialTenant, CredentialStoreProvider } from './credential-resolver.js';\nexport {\n setCustomProvidersSource,\n hasCustomProvidersSource,\n resolveCustomProviders,\n} from './custom-provider-source.js';\nexport type { CustomProvidersSource } from './custom-provider-source.js';\n\ntype ResolvedModel = GatewayLanguageModel | ModelRouterLanguageModel;\ntype ModelRequestHeaders = Record<string, string>;\n\nfunction getAgentControllerHeaders(requestContext?: RequestContext): ModelRequestHeaders | undefined {\n const agentControllerContext = requestContext?.get('controller') as AgentControllerRequestContext<any> | undefined;\n const headers = {\n ...(agentControllerContext?.threadId ? { 'x-thread-id': agentControllerContext.threadId } : {}),\n ...(agentControllerContext?.resourceId ? { 'x-resource-id': agentControllerContext.resourceId } : {}),\n };\n\n return Object.keys(headers).length > 0 ? headers : undefined;\n}\n\nfunction accountCredential(account: OAuthAccountRecord) {\n const { type: _type, id: _id, label: _label, addedAt: _addedAt, active: _active, ...credential } = account;\n return { type: 'oauth' as const, ...credential };\n}\n\nexport function createRequestScopedCredentialStore(\n base: CredentialStore,\n requestContext?: RequestContextReader,\n): CredentialStore {\n const selectedId = (providerId: string) => getRequestAccountSelection(requestContext, providerId);\n const selectedAccount = (providerId: string) => {\n const accountInstanceId = selectedId(providerId);\n return accountInstanceId\n ? base.listAccounts?.(providerId).find(account => account.id === accountInstanceId)\n : undefined;\n };\n // Routing rejected every account for this provider on this request. Fail\n // closed on every credential read: falling through to `base` would use the\n // provider's active account — the exhausted one routing just refused.\n const rejectAll = (providerId: string) => isRequestAccountRoutingExhausted(requestContext, providerId);\n\n return {\n allowEnvironmentFallback: base.allowEnvironmentFallback,\n reload: () => base.reload(),\n get: providerId => {\n if (rejectAll(providerId)) return undefined;\n // A selection that no longer resolves (the account was removed between\n // routing and the credential read) must not fall through to the active\n // account — that is the account routing deliberately passed over.\n const accountInstanceId = selectedId(providerId);\n if (accountInstanceId === undefined) return base.get(providerId);\n const selected = selectedAccount(providerId);\n return selected ? accountCredential(selected) : undefined;\n },\n getStoredApiKey: providerId => {\n if (rejectAll(providerId)) return undefined;\n // The provider-wide `apikey:` slot is never the credential routing\n // selected, so serving it to a routed request is an OAuth -> API-key\n // fallback of the same provider — the one combination this feature\n // forbids. Unlike `get`, this read has no account argument to pass\n // through, so a selection fails it closed instead.\n if (selectedId(providerId) !== undefined) return undefined;\n return base.getStoredApiKey(providerId);\n },\n getApiKey: providerId =>\n rejectAll(providerId) ? Promise.resolve(undefined) : base.getApiKey(providerId, selectedId(providerId)),\n getOAuthCredential: base.getOAuthCredential\n ? providerId =>\n rejectAll(providerId)\n ? Promise.resolve(undefined)\n : base.getOAuthCredential!(providerId, selectedId(providerId))\n : undefined,\n listAccounts: base.listAccounts ? providerId => base.listAccounts!(providerId) : undefined,\n getActiveAccount: base.getActiveAccount ? providerId => base.getActiveAccount!(providerId) : undefined,\n activateAccount: base.activateAccount\n ? (providerId, accountInstanceId) => base.activateAccount!(providerId, accountInstanceId)\n : undefined,\n removeAccount: base.removeAccount\n ? (providerId, accountInstanceId) => base.removeAccount!(providerId, accountInstanceId)\n : undefined,\n };\n}\n\nexport function createMastraCodeGateway(options: MastraCodeGatewayOptions): MastraCodeGateway {\n return new MastraCodeGateway(options);\n}\n\nexport function createMastraCodeModelCatalogProvider(gateway: MastraModelGatewayInterface) {\n return gateway instanceof MastraCodeGateway\n ? gateway.createModelCatalogProvider()\n : MastraCodeGateway.createModelCatalogProvider(gateway);\n}\n\n/**\n * Placeholder for future model ID normalization.\n * Currently returns the input unchanged, but exists as a seam\n * for aliasing, casing fixes, or validation in the future.\n */\nexport function resolveModelId(modelId: string): string {\n return modelId;\n}\n\n/**\n * Resolve a model ID to the correct provider instance.\n * Shared by the main agent, observer, and reflector.\n *\n * - For anthropic/* models: Uses stored OAuth credentials when present, otherwise direct API key\n * - For openai/* models: Uses OAuth when configured, otherwise direct API key from AuthStorage\n * - For moonshotai/* models: Uses Moonshot AI Anthropic-compatible endpoint\n * - For all other providers: Uses Mastra's model router (models.dev gateway)\n */\nexport function resolveModel(\n modelId: string,\n options?: {\n thinkingLevel?: ThinkingLevelSetting;\n remapForCodexOAuth?: boolean;\n requestContext?: RequestContext;\n anthropicPromptCacheScope?: AnthropicPromptCacheScope;\n },\n): ResolvedModel {\n if (!hasCredentialTenantResolver()) return resolveModelForRequest(modelId, options);\n const createRequestModel = () => {\n const requestContext = options?.requestContext ? new RequestContext(options.requestContext.entries()) : undefined;\n // The router supplies stable SDK metadata and adapts whichever provider the refreshed policy selects.\n // Each invocation owns its policy context and model cache, including concurrent OM and subagent calls.\n return new ModelRouterLanguageModel({ id: `${MASTRACODE_GATEWAY_ID}/${modelId}` }, [\n {\n id: MASTRACODE_GATEWAY_ID,\n name: 'Request-scoped MastraCode',\n fetchProviders: async () => ({}),\n buildUrl: () => undefined,\n getApiKey: async () => '',\n resolveAuth: () => ({ apiKey: 'request-scoped' }),\n resolveLanguageModel: async () => {\n await prepareCredentialTenant(requestContext);\n return resolveModelForRequest(modelId, { ...options, requestContext });\n },\n },\n ]);\n };\n let currentModel = createRequestModel();\n return new Proxy(currentModel, {\n get(_target, property) {\n if (property === 'supportedUrls') return createRequestModel().supportedUrls;\n if (property === 'doStream' || property === 'doGenerate') {\n return async (...args: unknown[]) => {\n const refreshed = createRequestModel();\n currentModel = refreshed;\n return Reflect.apply(Reflect.get(refreshed, property), refreshed, args);\n };\n }\n const value = Reflect.get(currentModel, property, currentModel);\n return typeof value === 'function' ? value.bind(currentModel) : value;\n },\n });\n}\n\nfunction resolveModelForRequest(modelId: string, options?: Parameters<typeof resolveModel>[1]): GatewayLanguageModel {\n reloadAuthStorage();\n const headers = getAgentControllerHeaders(options?.requestContext);\n const settings = loadSettings();\n // Older versions cataloged Bedrock, Copilot and Kimi under the MastraCode\n // gateway namespace, and Kimi under its own `kimi-for-coding` provider. Map\n // already-saved ids (packs, OM settings, thread metadata) to current ids.\n const legacyNormalizedInput = normalizeLegacyModelId(modelId);\n // Deployed web registers a custom providers source (DB-backed, tenant\n // scoped); when registered it is authoritative and settings.json custom\n // providers are ignored. Undefined = local settings-based behavior.\n const customProviders = resolveCustomProviders(options?.requestContext) ?? settings.customProviders;\n // Ids selected from the shared /models catalog were previously persisted in\n // the gateway-qualified `mastracode/<customProviderId>/<model>` form, which\n // parses the provider as `mastracode` and breaks provider config lookup.\n // Normalize at resolution time (in addition to stripping at selection time)\n // so already-saved ids and any surface that persists the raw catalog id\n // still resolve to the custom provider.\n const normalizedInput = stripMastraCodeCustomProviderPrefix(legacyNormalizedInput, customProviders);\n const isMastraGatewayModel = normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX);\n const normalizedModelId = stripMastraGatewayPrefix(normalizedInput);\n const [providerId, ...modelParts] = normalizedModelId.split('/');\n const bareModelId = modelParts.join('/');\n if (!providerId || !bareModelId) {\n throw new Error(`Invalid model id: ${modelId}`);\n }\n\n // Deployed hosts resolve exactly the trusted policy's credential scope.\n // Only local mode falls back to global AuthStorage.\n const tenantCredentialStore = resolveCredentialStore(options?.requestContext);\n const baseCredentialStore = tenantCredentialStore ?? getGlobalAuthStorage();\n\n if (providerId === AMAZON_BEDROCK_GATEWAY_ID) {\n // Bedrock authenticates through the server process's AWS credential chain,\n // never a tenant credential. A tenant store only lets it through when the\n // operator opted the deployment in.\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(AMAZON_BEDROCK_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Amazon Bedrock is not enabled for this Factory deployment. The operator must provide AWS credentials to the server and set FACTORY_DEPLOYMENT_MODEL_PROVIDERS=amazon-bedrock.',\n );\n }\n const bedrockGateway = createAmazonBedrockGateway();\n const routerId = `${AMAZON_BEDROCK_GATEWAY_ID}/${bareModelId}`;\n const auth = bedrockGateway.resolveAuth({\n gatewayId: AMAZON_BEDROCK_GATEWAY_ID,\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n routerId,\n });\n return bedrockGateway.resolveLanguageModel({\n providerId: AMAZON_BEDROCK_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n }\n\n if (providerId === GOOGLE_VERTEX_GATEWAY_ID) {\n if (\n tenantCredentialStore?.allowEnvironmentFallback === false &&\n !tenantCredentialStore.allowsDeploymentCredentials?.(GOOGLE_VERTEX_GATEWAY_ID)\n ) {\n throw new ProviderAuthRequiredError(\n 'Google Vertex AI is not enabled for this Factory deployment. The operator must configure Application Default Credentials, GOOGLE_VERTEX_PROJECT, GOOGLE_VERTEX_LOCATION, and FACTORY_DEPLOYMENT_MODEL_PROVIDERS=google-vertex.',\n );\n }\n\n const vertexGateway = createGoogleVertexGateway();\n const auth = vertexGateway.resolveAuth({\n gatewayId: GOOGLE_VERTEX_GATEWAY_ID,\n providerId: GOOGLE_VERTEX_GATEWAY_ID,\n modelId: bareModelId,\n routerId: normalizedModelId,\n });\n if (!auth) {\n throw new Error(\n 'Google Vertex ADC requires GOOGLE_VERTEX_PROJECT and GOOGLE_VERTEX_LOCATION. Configure Application Default Credentials in the deployment environment.',\n );\n }\n\n return vertexGateway.resolveLanguageModel({\n providerId: GOOGLE_VERTEX_GATEWAY_ID,\n modelId: bareModelId,\n apiKey: auth.apiKey ?? '',\n headers,\n });\n }\n\n const routerId = `${MASTRACODE_GATEWAY_ID}/${normalizedModelId}`;\n\n const mgApiKey = mastraGatewayApiKey(tenantCredentialStore);\n const rawGatewayBase =\n settings.memoryGateway?.baseUrl ?? process.env['MASTRA_GATEWAY_URL'] ?? 'https://gateway-api.mastra.ai';\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: rawGatewayBase.replace(/\\/+$/, '').replace(/\\/v1$/, ''),\n mastraGatewayApiKey: mgApiKey,\n routeThroughMastraGateway: Boolean(mgApiKey && isMastraGatewayModel),\n thinkingLevel: options?.thinkingLevel,\n anthropicPromptCacheScope: options?.anthropicPromptCacheScope,\n // A `mastra/...` model was chosen for the gateway. Without a gateway key it\n // falls back to the built-in provider, never to a custom endpoint that\n // happens to share the provider id.\n customProviders: isMastraGatewayModel ? [] : customProviders,\n credentialStore,\n });\n\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: bareModelId,\n routerId,\n });\n\n if (!auth && credentialStore?.allowEnvironmentFallback === false) {\n // Scopes are exclusive, so name the one in effect: otherwise a user with a\n // personal sign-in can't tell why an organization-scoped Factory fails.\n throw new ProviderAuthRequiredError(\n resolveCredentialScope(options?.requestContext) === 'factory'\n ? `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses organization credentials only, so personal provider sign-ins don't apply. Add an organization credential, then try again.`\n : `No usable ${providerId} credential is available for ${normalizedModelId}. This Factory uses personal credentials only, so organization credentials don't apply. Connect the provider, then try again.`,\n );\n }\n\n return gateway.resolveLanguageModel({\n providerId,\n modelId: bareModelId,\n apiKey: auth?.apiKey ?? '',\n headers,\n });\n}\n\n/** A tenant's own gateway key wins over the server's, so each org is billed to its own Mastra account. */\nfunction mastraGatewayApiKey(tenantCredentialStore: CredentialStore | undefined): string | undefined {\n return (\n tenantCredentialStore?.getStoredApiKey(MASTRA_GATEWAY_PROVIDER)?.trim() ||\n MastraCodeGateway.getMastraGatewayApiKey()\n );\n}\n\n/**\n * Which provider-executed web search tool fits the transport a model resolves to:\n * - `anthropic` / `openai`: the native provider API (direct keys, and Claude or\n * Codex OAuth, which keep the native API even through the Mastra gateway).\n * - `mastra-gateway`: a `mastra/` alias with a gateway key and no OAuth, which\n * `resolveModelForRequest` sends to the gateway's OpenRouter chat endpoint.\n * Other providers have no built-in search. Mirrors the routing in\n * `resolveModelForRequest` and `MastraCodeGateway`, so the registered tool and\n * the prompt guidance follow the request the model will actually make.\n */\nexport type ProviderWebSearchRoute = 'anthropic' | 'openai' | 'mastra-gateway';\n\n/** Credential ids whose OAuth sign-in keeps the native provider API through the gateway. */\nconst NATIVE_OAUTH_CREDENTIAL_IDS = { anthropic: 'anthropic', openai: 'openai-codex' } as const;\n\n/** The provider whose credentials decide a gateway alias's route, or its fixed route otherwise. */\nfunction classifyWebSearchModel(\n modelId: string | undefined,\n): { route: ProviderWebSearchRoute | undefined } | { gatewayProvider: keyof typeof NATIVE_OAUTH_CREDENTIAL_IDS } {\n if (!modelId) return { route: undefined };\n const normalizedInput = normalizeLegacyModelId(modelId);\n const providerId = stripMastraGatewayPrefix(normalizedInput).split('/')[0];\n if (providerId !== 'anthropic' && providerId !== 'openai') return { route: undefined };\n return normalizedInput.startsWith(MASTRA_GATEWAY_PREFIX) ? { gatewayProvider: providerId } : { route: providerId };\n}\n\n/**\n * Prepares tenant credential policy when the web search route depends on it and the\n * request hasn't been prepared yet. Model resolution prepares its own context only when\n * the model is invoked, after tools and instructions are built. Returns undefined when\n * there is nothing to prepare, so callers can stay synchronous.\n */\nexport function prepareProviderWebSearchRoute(\n modelId: string | undefined,\n options?: { requestContext?: RequestContextReader },\n): Promise<void> | undefined {\n const requestContext = options?.requestContext;\n if (!hasCredentialTenantResolver() || !(requestContext instanceof RequestContext)) return undefined;\n if (resolveTenantFromRequestContext(requestContext)) return undefined;\n if (!('gatewayProvider' in classifyWebSearchModel(modelId))) return undefined;\n return prepareCredentialTenant(requestContext);\n}\n\nexport function resolveProviderWebSearchRoute(\n modelId: string | undefined,\n options?: { requestContext?: RequestContextReader },\n): ProviderWebSearchRoute | undefined {\n const model = classifyWebSearchModel(modelId);\n if (!('gatewayProvider' in model)) return model.route;\n const providerId = model.gatewayProvider;\n\n reloadAuthStorage();\n const tenantCredentialStore = resolveCredentialStore(options?.requestContext);\n const credentialStore = createRequestScopedCredentialStore(\n tenantCredentialStore ?? getGlobalAuthStorage(),\n options?.requestContext,\n );\n if (credentialStore.get(NATIVE_OAUTH_CREDENTIAL_IDS[providerId])?.type === 'oauth') return providerId;\n return mastraGatewayApiKey(tenantCredentialStore) ? 'mastra-gateway' : providerId;\n}\n\n/**\n * Whether `resolveModel` can authenticate a provider for this request, using the\n * same credential lookup: the tenant store in deployed Factory (no environment\n * keys), otherwise local auth and then the provider's environment keys.\n */\nexport function canUseProvider(providerId: string, options?: { requestContext?: RequestContext }): boolean {\n reloadAuthStorage();\n const baseCredentialStore = resolveCredentialStore(options?.requestContext) ?? getGlobalAuthStorage();\n const credentialStore = createRequestScopedCredentialStore(baseCredentialStore, options?.requestContext);\n const gateway = createMastraCodeGateway({\n mastraGatewayBaseUrl: '',\n routeThroughMastraGateway: false,\n customProviders: resolveCustomProviders(options?.requestContext) ?? loadSettings().customProviders,\n credentialStore,\n });\n const auth = gateway.resolveAuth({\n gatewayId: MASTRACODE_GATEWAY_ID,\n providerId,\n modelId: '',\n routerId: `${MASTRACODE_GATEWAY_ID}/${providerId}`,\n });\n if (auth) return true;\n // resolveModel lets the models.dev gateway read environment keys only when the store allows it.\n return credentialStore.allowEnvironmentFallback !== false && hasProviderEnvironmentKey(providerId);\n}\n\nexport interface ThinkingRequestContext {\n state?: { thinkingLevel?: unknown };\n session?: { modeId?: string };\n}\n/**\n * Resolve the effective thinking level for the current request.\n *\n * Precedence:\n * 1. Session override (`state.thinkingLevel`, set via /think or the session\n * settings panel).\n * 2. The host's default for this request (`hostDefault`), when the host\n * stores thinking defaults itself (the Factory keeps one per Factory).\n * 3. Per-mode default from settings (`models.modeThinkingDefaults[mode]`),\n * only when the context carries a session mode.\n * 4. Global default (`preferences.thinkingLevel`).\n *\n * Resolved per-request (not seeded at session start) so configuration changes\n * apply to the next request of every session — including automated\n * (rule-driven) Factory runs that nobody ever opens interactively.\n */\nexport function resolveRequestThinkingLevel(\n agentControllerContext: ThinkingRequestContext | undefined,\n settingsPath?: string,\n hostDefault?: ThinkingLevelSetting,\n): ThinkingLevelSetting {\n const override = agentControllerContext?.state?.thinkingLevel;\n if (isThinkingLevelSetting(override)) return override;\n if (hostDefault) return hostDefault;\n const modeId = agentControllerContext?.session?.modeId;\n return resolveDefaultThinkingLevel(loadSettings(settingsPath), modeId).level;\n}\n\n/**\n * Dynamic model function that reads the current model and optional ordered\n * fallback route from controller state. Route entry ids are opaque host-owned\n * identifiers; repeated ids receive occurrence suffixes because core tracks the\n * active fallback index by id across agentic steps.\n */\nexport function getDynamicModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n { modeless = false, defaultThinkingLevel }: { modeless?: boolean; defaultThinkingLevel?: ThinkingLevelSetting } = {},\n): IdentifiedModelConfig | ModelWithRetries[] {\n const controller = requestContext.get('controller') as AgentControllerRequestContext<any> | undefined;\n const state = controller?.getState?.() as\n | {\n modelRoute?: {\n entries?: Array<{ id?: unknown; modelId?: unknown }>;\n };\n mastracodePendingModelFallback?: { toEntryId?: unknown; toModelId?: unknown; threadId?: unknown } | null;\n }\n | undefined;\n const pendingState = state?.mastracodePendingModelFallback;\n const pendingFallback =\n pendingState &&\n (pendingState.threadId === undefined ||\n (typeof pendingState.threadId === 'string' && pendingState.threadId === controller?.threadId))\n ? pendingState\n : undefined;\n const pendingModelId =\n pendingFallback && typeof pendingFallback.toModelId === 'string' && pendingFallback.toModelId.length > 0\n ? pendingFallback.toModelId\n : undefined;\n const modelId = pendingModelId ?? controller?.session?.modelId;\n if (!modelId) {\n if (!controller) {\n throw new Error(\n 'No model available: this run started without a controller session context, so no model selection could be resolved.',\n );\n }\n throw new Error('No model selected. Use /models to select a model first.');\n }\n\n const thinkingLevel = resolveRequestThinkingLevel(\n modeless ? { state: controller?.state } : controller,\n settingsPath,\n defaultThinkingLevel,\n );\n const resolveOptions = { thinkingLevel, remapForCodexOAuth: true, requestContext } as const;\n // Label each resolved model with its full ID: the resolved gateway model only\n // knows its bare provider model, and Memory's `'auto'` reads this label.\n const primary = identifyModel(modelId, resolveModel(modelId, resolveOptions));\n const route = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES);\n const pendingEntryId =\n pendingFallback && typeof pendingFallback.toEntryId === 'string' ? pendingFallback.toEntryId : undefined;\n const startIndex = pendingEntryId ? route?.findIndex(entry => entry.id === pendingEntryId) : 0;\n const activeRoute = route && startIndex !== undefined && startIndex >= 0 ? route.slice(startIndex) : undefined;\n if (!activeRoute || activeRoute.length < 2 || activeRoute[0]?.modelId !== modelId) return primary;\n\n const firstId =\n typeof activeRoute[0]?.id === 'string' && activeRoute[0].id.length > 0 ? activeRoute[0].id : undefined;\n if (!firstId) return primary;\n\n const entries: ModelWithRetries[] = [{ id: firstId, model: primary }];\n const appearances = new Map<string, number>([[firstId, 1]]);\n for (const routeEntry of activeRoute.slice(1)) {\n if (\n typeof routeEntry.id !== 'string' ||\n routeEntry.id.length === 0 ||\n typeof routeEntry.modelId !== 'string' ||\n routeEntry.modelId.length === 0\n ) {\n break;\n }\n let entryModel: ResolvedModel;\n try {\n entryModel = resolveModel(routeEntry.modelId, resolveOptions);\n } catch {\n break;\n }\n const occurrence = (appearances.get(routeEntry.id) ?? 0) + 1;\n appearances.set(routeEntry.id, occurrence);\n entries.push({\n id: occurrence === 1 ? routeEntry.id : `${routeEntry.id}#${occurrence}`,\n model: identifyModel(routeEntry.modelId, entryModel),\n });\n }\n\n return entries.length < 2 ? primary : entries;\n}\n\nfunction identifyModel(modelId: string, model: ResolvedModel): IdentifiedModelConfig {\n return { model, id: toMemoryModelId(modelId) };\n}\n\ntype MemoryRouteState = {\n modelRoute?: { entries?: Array<{ id?: unknown; memoryModelId?: unknown }> };\n mastracodePendingModelFallback?: { toEntryId?: unknown; threadId?: unknown } | null;\n};\n\n/**\n * The active model route for memory: the session route, starting at a pending\n * fallback hop captured for this thread.\n */\nexport function getActiveMemoryRoute<TEntry extends { id?: unknown; memoryModelId?: unknown }>(\n state:\n | {\n modelRoute?: { entries?: TEntry[] };\n mastracodePendingModelFallback?: MemoryRouteState['mastracodePendingModelFallback'];\n }\n | undefined,\n threadId?: string | null,\n): TEntry[] {\n const pending = state?.mastracodePendingModelFallback;\n const sameThreadPending =\n pending && (pending.threadId === undefined || pending.threadId === threadId) ? pending : undefined;\n const routeEntries = state?.modelRoute?.entries?.slice(0, MODEL_ROUTE_MAX_ENTRIES) ?? [];\n const pendingIndex = sameThreadPending\n ? routeEntries.findIndex(entry => entry.id === sameThreadPending.toEntryId)\n : -1;\n return pendingIndex >= 0 ? routeEntries.slice(pendingIndex) : routeEntries;\n}\n\n/**\n * The memory model the active route applies to both OM roles: `'auto'`, the\n * first concrete memory model, or `undefined` when the route sets none (both\n * roles then follow their `/om` settings).\n */\nexport function getActiveRouteMemoryModelId(\n state: Readonly<Record<string, unknown>> | undefined,\n threadId?: string | null,\n): string | undefined {\n const route = getActiveMemoryRoute(state as MemoryRouteState | undefined, threadId);\n if (route[0]?.memoryModelId === 'auto') return 'auto';\n const entry = route.find(\n candidate =>\n typeof candidate.memoryModelId === 'string' && candidate.memoryModelId && candidate.memoryModelId !== 'auto',\n );\n return entry?.memoryModelId as string | undefined;\n}\n\n/**\n * Goal judge model resolver for the agent's `goal.judge` config. Resolves the\n * configured goal judge model through mastracode's gateway so provider\n * credentials (stored in auth storage, not just env) are injected — a bare model\n * id handed to core's default model router would fail to find the API key.\n *\n * Returns `undefined` when no judge model is configured, which keeps the goal\n * step a complete no-op (the goal mechanism requires a judge to do anything).\n *\n * `settingsPath` must be the same source `createMastraCode()` reads from so the\n * judge model and the goal budget (`goalMaxTurns`) come from one config — with a\n * custom `settingsPath` a bare `loadSettings()` here could read a different file\n * and silently turn the goal step into a no-op.\n */\nexport function getGoalJudgeModel(\n { requestContext }: { requestContext: RequestContext },\n settingsPath?: string,\n): ResolvedModel | undefined {\n const judgeModelId = loadSettings(settingsPath).models.goalJudgeModel;\n if (!judgeModelId) return undefined;\n return resolveModel(judgeModelId, { remapForCodexOAuth: true, requestContext });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAmEA,SAAS,0BAA0B,gBAAkE;CACnG,MAAM,yBAAyB,gBAAgB,IAAI,YAAY;CAC/D,MAAM,UAAU;EACd,GAAI,wBAAwB,WAAW,EAAE,eAAe,uBAAuB,SAAS,IAAI,CAAC;EAC7F,GAAI,wBAAwB,aAAa,EAAE,iBAAiB,uBAAuB,WAAW,IAAI,CAAC;CACrG;CAEA,OAAO,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AACrD;AAEA,SAAS,kBAAkB,SAA6B;CACtD,MAAM,EAAE,MAAM,OAAO,IAAI,KAAK,OAAO,QAAQ,SAAS,UAAU,QAAQ,SAAS,GAAG,eAAe;CACnG,OAAO;EAAE,MAAM;EAAkB,GAAG;CAAW;AACjD;AAEA,SAAgB,mCACd,MACA,gBACiB;CACjB,MAAM,cAAc,eAAuB,2BAA2B,gBAAgB,UAAU;CAChG,MAAM,mBAAmB,eAAuB;EAC9C,MAAM,oBAAoB,WAAW,UAAU;EAC/C,OAAO,oBACH,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,YAAW,QAAQ,OAAO,iBAAiB,IAChF,KAAA;CACN;CAIA,MAAM,aAAa,eAAuB,iCAAiC,gBAAgB,UAAU;CAErG,OAAO;EACL,0BAA0B,KAAK;EAC/B,cAAc,KAAK,OAAO;EAC1B,MAAK,eAAc;GACjB,IAAI,UAA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1B,OAAO,aAAa,cAAc;EAAE,oBAAoB;EAAM;CAAe,CAAC;AAChF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build.d.ts","sourceRoot":"","sources":["../../../src/agents/modes/build.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEzE,eAAO,MAAM,SAAS,EAAE,mBAiCvB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../../../src/agents/modes/build.ts"],"sourcesContent":["/**\n * Build mode — interactive task execution with write capabilities.\n *\n * The default top-level mode for implementing features, fixing bugs, and\n * making changes directly in conversation with the user. Full read/write\n * access within the task's scope. (Not to be confused with the separate\n * `executeSubagent`, which has its own concise, parent-reporting\n * instructions for when work is delegated to a sub-agent.)\n */\nimport type { AgentControllerMode } from '@mastra/core/agent-controller';\n\nexport const buildMode: AgentControllerMode = {\n id: 'build',\n name: 'Build',\n description:\n \"Task execution with write capabilities. Use for 'implement feature X', 'fix bug Y', 'refactor module Z'.\",\n instructions: `You are a focused execution agent. Your job is to complete a specific, well-defined task by making the necessary changes to the codebase.\n\n## Rules\n- You have FULL ACCESS to read, write, and execute within your task scope.\n- Stay focused on the specific task given. Do not make unrelated changes.\n- Understand the relevant code before modifying it, then use string_replace_lsp or write_file.\n- Verify your changes work by running relevant tests or checking for errors.\n\n## Tool Strategy\n- **Understand first**: Know what a file contains before editing it, however you read it\n- **Edit precisely**: Use string_replace_lsp with enough context to match uniquely\n- **Use specialized tools**: Prefer view/search_content/find_files over shell commands for reading\n- **Parallelize**: Make independent tool calls together (e.g., view multiple files at once)\n\n## Workflow\n. Understand the task and explore relevant code\n. For complex tasks (3+ steps): track progress internally and summarize it in your final answer\n. Make changes incrementally — verify each change before moving on\n. Run tests or type-check to verify\n\n## Workflows\n- To build a workflow: call \\`create-workflow\\` with the user's request verbatim. A focused sub-agent handles discovery, composition, and saving — don't try to do it inline.\n- To run an existing workflow: call \\`run-workflow\\` with { workflowId, inputData }. Returns { status, result, error? }.\n- To inspect or manage: \\`list-workflows\\`, \\`get-workflow\\`, \\`delete-workflow\\`.`,\n defaultModelId: 'openai/gpt-5.6-sol',\n metadata: {\n default: true,\n },\n};\n"],"mappings":";AAWA,MAAa,YAAiC;CAC5C,IAAI;CACJ,MAAM;CACN,aACE;CACF,cAAc;;;;;;;;;;;;;;;;;;;;;;;;CAwBd,gBAAgB;CAChB,UAAU,EACR,SAAS,KACX;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"explore.d.ts","sourceRoot":"","sources":["../../../src/agents/modes/explore.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAGzE,eAAO,MAAM,QAAQ,EAAE,mBAuBtB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"explore.js","names":[],"sources":["../../../src/agents/modes/explore.ts"],"sourcesContent":["/**\n * Explore mode — interactive, read-only codebase exploration.\n *\n * The top-level mode for questions like \"find all usages of X\" or \"how\n * does module Y work\". Read-only; answers the user directly in\n * conversation rather than reporting back to a parent agent.\n */\nimport type { AgentControllerMode } from '@mastra/core/agent-controller';\nimport { EXPLORE_MODE_AVAILABLE_TOOLS } from '../tool-availability.js';\n\nexport const fastMode: AgentControllerMode = {\n id: 'fast',\n name: 'Explore',\n description:\n \"Read-only codebase exploration. Use for questions like 'find all usages of X', 'how does module Y work'.\",\n defaultModelId: 'openai/gpt-5.4-mini',\n instructions: `You are an expert code explorer. Your job is to investigate a codebase and answer a specific question or gather specific information.\n\n## Rules\n- You have READ-ONLY access. You cannot modify files or run commands.\n- Be thorough — search broadly first, then drill into relevant files.\n- After gathering enough information, produce a clear, concise summary of your findings.\n\n## Tool Strategy\n- **Start broad**: Use find_files (glob) to understand project structure\n- **Search smart**: Use search_content (grep) with specific patterns — avoid overly broad searches\n- **Read efficiently**: Use view with view_range for large files — don't read entire files if you only need a section\n- **Parallelize**: Make multiple independent tool calls in one round when exploring different areas\n\n## Workflows\n- You can use \\`list-workflows\\` and \\`get-workflow\\` to inspect saved workflows. You cannot create, run, or delete in this mode.`,\n\n availableTools: [...EXPLORE_MODE_AVAILABLE_TOOLS],\n};\n"],"mappings":";;AAUA,MAAa,WAAgC;CAC3C,IAAI;CACJ,MAAM;CACN,aACE;CACF,gBAAgB;CAChB,cAAc;;;;;;;;;;;;;;;CAgBd,gBAAgB,CAAC,GAAG,4BAA4B;AAClD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../src/agents/modes/plan.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAGzE,iGAAiG;AACjG,wBAAgB,cAAc,CAAC,mBAAmB,UAAO,GAAG,mBAAmB,CA0C9E;AAED,eAAO,MAAM,QAAQ,EAAE,mBAAsC,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/modes/plan.ts"],"sourcesContent":["/**\n * Plan mode — read-only analysis and planning.\n */\nimport type { AgentControllerMode } from '@mastra/core/agent-controller';\nimport { PLAN_MODE_AVAILABLE_TOOLS } from '../tool-availability.js';\n\n/** Plan mode; pass `false` when the host removed `submit_plan` so the mode never asks for it. */\nexport function createPlanMode(submitPlanAvailable = true): AgentControllerMode {\n return {\n id: 'plan',\n name: 'Plan',\n transitionsTo: 'build',\n defaultModelId: 'openai/gpt-5.6-sol',\n description:\n \"Read-only analysis and planning. Use for 'create an implementation plan for X', 'analyze the architecture of Y'.\",\n instructions: `You are an expert software architect and planner. Your job is to analyze a codebase and produce a detailed implementation plan for a given task.\n\n## Rules\n- You have READ-ONLY access to the project. You cannot modify project files or run commands.\n- The one exception is plan files: you can create and edit markdown files inside the session-specific plan directory identified in your system prompt using \\`write_file\\`, \\`view\\`, and \\`string_replace_lsp\\`. You may not write anywhere else.\n- First, explore the codebase to understand existing patterns, architecture, and conventions.\n- Produce a concrete, actionable plan — not vague suggestions.\n\n## Tool Strategy\n- **Discover structure**: Use find_files (glob) to understand project layout and find relevant files\n- **Find patterns**: Use search_content (grep) to locate existing implementations, imports, and conventions\n- **Understand deeply**: Use view with view_range to read specific sections of key files\n- **Parallelize**: Make multiple independent tool calls when exploring different areas\n\n## Plan Delivery\n- Write your plan to a markdown file in the session-specific plan directory identified in your system prompt using \\`write_file\\`, ${submitPlanAvailable ? 'then call `submit_plan({ path })` with the path to that file (never the plan body).' : 'then hand off the plan file as described in your system prompt (never the plan body).'}\n- Start the file with a \\`# Title\\` heading describing the plan.\n- Reuse the same file while iterating on the same plan; only create a new file for a genuinely different plan so each plan stays available to review.\n- Do NOT output the plan as text — it MUST live in the plan file.\n- Be concise: reference files by path and line number, don't include raw contents.\n- Focus on actionable details, not general observations.\n- To revise after \"Request changes\", edit the same file in place with \\`string_replace_lsp\\`, ${submitPlanAvailable ? 'and call `submit_plan` again with the same path.' : 'then hand off the same file again.'}\n\n## Workflows\n- You can INSPECT saved workflows via \\`list-workflows\\` and \\`get-workflow\\`.\n- You CANNOT build, run, or delete workflows in this mode.\n- If the user asks for a workflow design, include it in the implementation plan stored at the session-specific plan path, ${submitPlanAvailable ? 'then call `submit_plan({ path })` as required above. After approval, build mode can save and run it.' : 'then hand off the plan file as described in your system prompt.'}`,\n\n metadata: {\n default: false,\n },\n\n availableTools: [...PLAN_MODE_AVAILABLE_TOOLS],\n };\n}\n\nexport const planMode: AgentControllerMode = createPlanMode();\n"],"mappings":";;;AAOA,SAAgB,eAAe,sBAAsB,MAA2B;CAC9E,OAAO;EACL,IAAI;EACJ,MAAM;EACN,eAAe;EACf,gBAAgB;EAChB,aACE;EACF,cAAc;;;;;;;;;;;;;;;qIAemH,sBAA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,CAAA;CAAO,GACpD,iBAAiB,EAAE,CAwDrB;AAED,wBAAgB,mCAAmC,CACjD,WAAW,EAAE,MAAM,EACnB,aAAa,SAAqB,EAClC,aAAa,CAAC,EAAE,qBAAqB,GACpC,MAAM,EAAE,CAEV;AAED;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,EAAE,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAG1G;AAED;;;;;;;GAOG;AACH,wBAAgB,uBAAuB,CAAC,EACtC,UAAU,EACV,gBAAgB,EAChB,SAAS,EACT,iBAAyB,EACzB,OAAO,EACP,UAAkB,GACnB,EAAE;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACrC,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB,GAAG,iBAAiB,EAAE,CAatB;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,iBAAiB,EAAE,EAAE,KAAK,EAAE,SAAS,MAAM,EAAE,GAAG,MAAM,EAAE,CAYvG;AAED,kFAAkF;AAClF,eAAO,MAAM,0BAA0B,yBAAyB,CAAC;AAEjE;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,GAAG,MAAM,CAIzE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,iBAAiB,EAAE,GAAG,MAAM,CAM5E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"agent-instructions.js","names":[],"sources":["../../../src/agents/prompts/agent-instructions.ts"],"sourcesContent":["/**\n * Load project and global agent instruction files (AGENTS.md, CLAUDE.md).\n * Prefers AGENTS.md over CLAUDE.md when multiple exist at the same location.\n */\n\nimport { execFileSync, spawn } from 'node:child_process';\nimport { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';\nimport { readFile, realpath, stat } from 'node:fs/promises';\nimport { homedir } from 'node:os';\nimport { dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';\nimport { DEFAULT_CONFIG_DIR } from '../../constants.js';\n\n// Filenames to check, in order of preference\nconst INSTRUCTION_FILES = ['AGENTS.md', 'CLAUDE.md'];\n\n// Locations to scan (relative to project root or home)\nconst PROJECT_LOCATIONS = [\n '', // project root\n '.claude',\n '.mastracode',\n];\n\nconst GLOBAL_LOCATIONS = ['.claude', '.mastracode', '.config/claude', '.config/mastracode'];\n\nexport interface InstructionSource {\n path: string;\n content: string;\n scope: 'global' | 'project';\n /** Git ref the content was read from, when not read off the working tree. */\n ref?: string;\n}\n\n/**\n * Reads project-scope instruction files. The default implementation reads the\n * working tree via `fs`; alternative readers can serve content from another\n * source (e.g. a trusted git ref) while keeping working-tree paths as the\n * addressing scheme.\n */\nexport interface InstructionFileReader {\n exists(path: string): boolean;\n read(path: string): string;\n /** Git ref backing this reader, recorded on the loaded sources. */\n ref?: string;\n}\n\nconst fsInstructionReader: InstructionFileReader = {\n exists: path => existsSync(path),\n read: path => readFileSync(path, 'utf-8'),\n};\n\nfunction realpathOrResolved(path: string): string {\n try {\n return realpathSync(path);\n } catch {\n return resolve(path);\n }\n}\n\nfunction createProjectPathResolver(projectPath: string): (path: string) => string | null {\n const canonicalRoot = realpathOrResolved(projectPath);\n return path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n\n // Match an alias of the project root, not the target of a checkout-controlled\n // descendant symlink. Missing descendants must still resolve against the ref.\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if (realpathOrResolved(ancestor) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\n// Keys count towards the limit too: a path a folder lacks is cached as an empty listing.\nconst GIT_OBJECT_CACHE_MAX_CHARS = 16 * 1024 * 1024;\nconst gitObjectOutputs = new Map<string, string>();\nlet gitObjectCacheChars = 0;\n\n// The cache is shared by every checkout in the process, so a read is kept only once it is known to\n// match its id: git checks the tree it is asked to list, and `matchesId` covers what git does not check.\n// A blobless clone fetches file content over the network, so a failed read is never cached.\nfunction gitObjectRead(\n projectPath: string,\n args: string[],\n matchesId: (output: Buffer) => boolean = () => true,\n): string | null {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n try {\n const raw = execFileSync('git', ['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args], {\n stdio: ['ignore', 'pipe', 'ignore'],\n maxBuffer: 1024 * 1024,\n });\n if (!matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n } catch {\n return null;\n }\n}\n\nfunction blobMatchesId(id: string, content: Buffer): boolean {\n const hash = createHash(id.length === 40 ? 'sha1' : 'sha256');\n return hash.update(`blob ${content.length}\\0`).update(content).digest('hex') === id;\n}\n\nfunction createGitRefLookup(projectPath: string, ref: string) {\n // Resolved on first use and kept, so a lookup reads the ref as it stood then: build one per model step.\n let trees: string[] | undefined;\n const resolveTrees = (): string[] => {\n // A ref name never holds a space or control character, and each line of the batch below names\n // one object, so a line break in `ref` would add names of its own, such as the checkout's `HEAD`.\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n try {\n const output = execFileSync('git', ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'], {\n encoding: 'utf-8',\n input: `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n stdio: ['pipe', 'pipe', 'ignore'],\n });\n return [...new Set(output.split('\\n').filter(line => /^[0-9a-f]+$/.test(line)))];\n } catch {\n return [];\n }\n };\n // One folder level per call: git hash-checks the tree it lists, not the trees it walks through.\n const entryAt = (tree: string, rel: string): string[] => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry = gitObjectRead(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name])?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type] = entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: (rel: string): string | null => {\n for (const tree of (trees ??= resolveTrees())) {\n const [, type, blob] = entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = gitObjectRead(projectPath, ['cat-file', 'blob', blob], raw => blobMatchesId(blob, raw));\n if (content !== null) return content;\n }\n return null;\n },\n };\n}\n\n/**\n * Create a reader that serves instruction files from a git ref instead of the\n * working tree. Paths are still addressed as working-tree paths under\n * `projectPath`; content comes from the blob at `<ref>:<relpath>` so an untrusted\n * checkout (e.g. a PR branch under review) cannot influence what is loaded.\n * Tries `origin/<ref>` first (remote truth), then the local ref. Any git\n * failure (missing ref, missing file, no repo) reports the file as absent.\n */\nexport function createGitRefInstructionReader(projectPath: string, ref: string): InstructionFileReader {\n const toRelative = createProjectPathResolver(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const show = (path: string): string | null => {\n const rel = toRelative(path);\n return rel ? lookup.show(rel) : null;\n };\n return {\n ref,\n exists: path => show(path) !== null,\n read: path => {\n const content = show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\n/**\n * Reader for the reactive reminder channel (AgentsMDInjector) that serves\n * paths under `projectPath` from a trusted git ref. Paths outside the project\n * fall back to the operator machine's filesystem (those are trusted); paths\n * inside the project are only ever resolved against the ref, never the\n * working tree, so an untrusted checkout cannot feed content in.\n */\nexport function createGitRefReminderReader(\n projectPath: string,\n ref: string,\n): {\n pathExists: (path: string) => boolean;\n isDirectory: (path: string) => boolean;\n readFile: (path: string) => string;\n getPathIdentity: (path: string) => string;\n} {\n const toRelative = createProjectPathResolver(projectPath);\n const canonicalRoot = realpathOrResolved(projectPath);\n const lookup = createGitRefLookup(projectPath, ref);\n const objectType = (rel: string): string | null => {\n if (rel === '') return 'tree'; // project root\n return lookup.type(rel);\n };\n return {\n pathExists: path => {\n const rel = toRelative(path);\n if (rel === null) return existsSync(path);\n return objectType(rel) !== null;\n },\n isDirectory: path => {\n const rel = toRelative(path);\n if (rel === null) {\n try {\n return statSync(path).isDirectory();\n } catch {\n return false;\n }\n }\n return objectType(rel) === 'tree';\n },\n readFile: path => {\n const rel = toRelative(path);\n if (rel === null) return readFileSync(path, 'utf-8');\n const content = rel ? lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: path => {\n const rel = toRelative(path);\n // Only canonicalize the project root: checkout symlinks do not define\n // file identity in the trusted ref, including files missing on disk.\n return rel === null ? realpathOrResolved(path) : join(canonicalRoot, rel);\n },\n };\n}\n\n// Keep in-flight object reads shared across concurrent prompt and reminder lookups.\nconst pendingGitObjects = new Map<string, Promise<string | null>>();\n\nfunction gitAsync(args: string[], input?: string): Promise<Buffer | null> {\n return new Promise(resolveOutput => {\n let child: ReturnType<typeof spawn>;\n try {\n child = spawn('git', args, { stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'ignore'] });\n } catch {\n resolveOutput(null);\n return;\n }\n const chunks: Buffer[] = [];\n let size = 0;\n let failed = false;\n child.stdout?.on('data', (chunk: Buffer) => {\n size += chunk.length;\n if (size > 1024 * 1024) {\n failed = true;\n child.kill();\n } else chunks.push(chunk);\n });\n child.on('error', () => {\n failed = true;\n });\n child.on('close', code => resolveOutput(!failed && code === 0 ? Buffer.concat(chunks) : null));\n if (input !== undefined) {\n child.stdin?.on('error', () => {\n failed = true;\n });\n child.stdin?.end(input);\n }\n });\n}\n\nasync function gitObjectReadAsync(\n projectPath: string,\n args: string[],\n matchesId: (raw: Buffer) => boolean = () => true,\n): Promise<string | null> {\n const key = args.join('\\0');\n const cached = gitObjectOutputs.get(key);\n if (cached !== undefined) return cached;\n const pendingKey = `${projectPath}\\0${key}`;\n let pending = pendingGitObjects.get(pendingKey);\n if (!pending) {\n pending = (async () => {\n const raw = await gitAsync(['--no-replace-objects', '-C', projectPath, '--literal-pathspecs', ...args]);\n if (!raw || !matchesId(raw)) return null;\n const output = raw.toString('utf-8');\n gitObjectOutputs.set(key, output);\n gitObjectCacheChars += key.length + output.length;\n for (const [oldest, evicted] of gitObjectOutputs) {\n if (gitObjectCacheChars <= GIT_OBJECT_CACHE_MAX_CHARS) break;\n gitObjectOutputs.delete(oldest);\n gitObjectCacheChars -= oldest.length + evicted.length;\n }\n return output;\n })();\n pendingGitObjects.set(pendingKey, pending);\n void pending.then(\n () => pendingGitObjects.delete(pendingKey),\n () => pendingGitObjects.delete(pendingKey),\n );\n }\n return pending;\n}\n\nasync function realpathOrResolvedAsync(path: string): Promise<string> {\n try {\n return await realpath(path);\n } catch {\n return resolve(path);\n }\n}\n\nasync function createProjectPathResolverAsync(projectPath: string): Promise<(path: string) => Promise<string | null>> {\n const canonicalRoot = await realpathOrResolvedAsync(projectPath);\n return async path => {\n const rel = relative(projectPath, path);\n if (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel)) return rel.split(sep).join('/');\n let ancestor = resolve(path);\n let projectRelativePath: string | null = null;\n while (true) {\n if ((await realpathOrResolvedAsync(ancestor)) === canonicalRoot) {\n projectRelativePath = relative(ancestor, path).split(sep).join('/');\n }\n const parent = dirname(ancestor);\n if (parent === ancestor) return projectRelativePath;\n ancestor = parent;\n }\n };\n}\n\nfunction createGitRefLookupAsync(projectPath: string, ref: string) {\n let trees: Promise<string[]> | undefined;\n const resolveTrees = async (): Promise<string[]> => {\n if ([...ref].some(char => char <= ' ' || char === '\\x7f')) return [];\n const raw = await gitAsync(\n ['-C', projectPath, 'cat-file', '--batch-check=%(objectname)'],\n `origin/${ref}^{tree}\\n${ref}^{tree}\\n`,\n );\n return raw\n ? [\n ...new Set(\n raw\n .toString('utf-8')\n .split('\\n')\n .filter(line => /^[0-9a-f]+$/.test(line)),\n ),\n ]\n : [];\n };\n const entryAt = async (tree: string, rel: string): Promise<string[]> => {\n let entry = ['', 'tree', tree];\n for (const name of rel.split('/')) {\n if (entry[1] !== 'tree') return [];\n entry =\n (await gitObjectReadAsync(projectPath, ['ls-tree', '--full-tree', entry[2]!, '--', name]))?.split(/\\s/) ?? [];\n }\n return entry;\n };\n return {\n type: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type] = await entryAt(tree, rel);\n if (type) return type;\n }\n return null;\n },\n show: async (rel: string): Promise<string | null> => {\n for (const tree of await (trees ??= resolveTrees())) {\n const [, type, blob] = await entryAt(tree, rel);\n if (type !== 'blob' || !blob) continue;\n const content = await gitObjectReadAsync(projectPath, ['cat-file', 'blob', blob], raw =>\n blobMatchesId(blob, raw),\n );\n if (content !== null) return content;\n }\n return null;\n },\n };\n}\n\nexport async function createGitRefInstructionReaderAsync(\n projectPath: string,\n ref: string,\n): Promise<AsyncInstructionFileReader> {\n const toRelative = await createProjectPathResolverAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const show = async (path: string) => {\n const rel = await toRelative(path);\n return rel ? lookup.show(rel) : null;\n };\n return {\n ref,\n exists: async path => (await show(path)) !== null,\n read: async path => {\n const content = await show(path);\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n };\n}\n\nexport function createGitRefReminderReaderAsync(projectPath: string, ref: string) {\n const toRelative = createProjectPathResolverAsync(projectPath);\n const canonicalRoot = realpathOrResolvedAsync(projectPath);\n const lookup = createGitRefLookupAsync(projectPath, ref);\n const objectType = (rel: string) => (rel === '' ? Promise.resolve('tree') : lookup.type(rel));\n return {\n pathExists: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) !== null;\n },\n isDirectory: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) {\n try {\n return (await stat(path)).isDirectory();\n } catch {\n return false;\n }\n }\n return (await objectType(rel)) === 'tree';\n },\n readFile: async (path: string) => {\n const rel = await (await toRelative)(path);\n if (rel === null) return readFile(path, 'utf-8');\n const content = rel ? await lookup.show(rel) : null;\n if (content === null) throw new Error(`Not found at ref ${ref}: ${path}`);\n return content;\n },\n getPathIdentity: async (path: string) => {\n const rel = await (await toRelative)(path);\n return rel === null ? realpathOrResolvedAsync(path) : join(await canonicalRoot, rel);\n },\n };\n}\n\nexport interface AsyncInstructionFileReader {\n exists(path: string): Promise<boolean>;\n read(path: string): Promise<string>;\n ref?: string;\n}\n\nconst fsInstructionReaderAsync: AsyncInstructionFileReader = {\n exists: async path => {\n try {\n await stat(path);\n return true;\n } catch {\n return false;\n }\n },\n read: path => readFile(path, 'utf-8'),\n};\n\nexport async function loadAgentInstructionsAsync(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: AsyncInstructionFileReader = fsInstructionReaderAsync,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): Promise<InstructionSource[]> {\n const sources: InstructionSource[] = [];\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n for (const location of globalLocations) {\n const base = join(homedir(), location);\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await fsInstructionReaderAsync.exists(path))) continue;\n try {\n const content = (await fsInstructionReaderAsync.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'global' });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.length) break;\n }\n for (const location of projectLocations) {\n const base = location ? join(projectPath, location) : projectPath;\n for (const filename of INSTRUCTION_FILES) {\n const path = join(base, filename);\n if (!(await projectReader.exists(path))) continue;\n try {\n const content = (await projectReader.read(path)).trim();\n if (content) {\n sources.push({ path, content, scope: 'project', ...(projectReader.ref ? { ref: projectReader.ref } : {}) });\n break;\n }\n } catch {\n /* Skip unreadable instructions. */\n }\n break;\n }\n if (sources.some(source => source.scope === 'project')) break;\n }\n return sources;\n}\n\nexport async function loadSessionInstructionsAsync({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): Promise<InstructionSource[]> {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const reader = untrustedCheckout\n ? baseRef\n ? await createGitRefInstructionReaderAsync(primary!, baseRef)\n : { exists: async () => false, read: async () => '' }\n : undefined;\n const sources = await loadAgentInstructionsAsync(primary!, configDir, reader, { skipGlobal });\n if (!untrustedCheckout) {\n for (const root of others)\n sources.push(...(await loadAgentInstructionsAsync(root, configDir, undefined, { skipGlobal: true })));\n }\n return sources;\n}\n\n/**\n * Find the first existing instruction file at a given base path.\n * Prefers AGENTS.md over CLAUDE.md.\n */\nfunction findInstructionFile(basePath: string, reader: InstructionFileReader = fsInstructionReader): string | null {\n for (const filename of INSTRUCTION_FILES) {\n const fullPath = join(basePath, filename);\n if (reader.exists(fullPath)) {\n return fullPath;\n }\n }\n return null;\n}\n\n/**\n * Load all agent instruction files from global and project locations.\n * Returns an array of instruction sources, with global ones first.\n *\n * `projectReader` controls where project-scope content comes from (defaults to\n * the working tree). Global instructions read the operator machine's\n * filesystem, unless `skipGlobal` keeps them out entirely.\n */\nexport function loadAgentInstructions(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader: InstructionFileReader = fsInstructionReader,\n { skipGlobal = false }: { skipGlobal?: boolean } = {},\n): InstructionSource[] {\n const sources: InstructionSource[] = [];\n const home = homedir();\n\n // Derive location arrays from the base constants, substituting the config dir name\n const projectLocations = PROJECT_LOCATIONS.map(loc => (loc === '.mastracode' ? configDirName : loc));\n const globalLocations = skipGlobal\n ? []\n : GLOBAL_LOCATIONS.map(loc => {\n if (loc === '.mastracode') return configDirName;\n // XDG-style path (~/.config/<name>): strip the leading dot since the\n // .config/ prefix already signals a hidden/config directory.\n if (loc === '.config/mastracode') return '.config/' + configDirName.replace(/^\\./, '');\n return loc;\n });\n\n // Load global instructions first\n for (const location of globalLocations) {\n const basePath = join(home, location);\n const filePath = findInstructionFile(basePath);\n if (filePath) {\n try {\n const content = readFileSync(filePath, 'utf-8').trim();\n if (content) {\n sources.push({ path: filePath, content, scope: 'global' });\n break; // Only use first found global instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n // Load project instructions\n for (const location of projectLocations) {\n const basePath = location ? join(projectPath, location) : projectPath;\n const filePath = findInstructionFile(basePath, projectReader);\n if (filePath) {\n try {\n const content = projectReader.read(filePath).trim();\n if (content) {\n sources.push({\n path: filePath,\n content,\n scope: 'project',\n ...(projectReader.ref ? { ref: projectReader.ref } : {}),\n });\n break; // Only use first found project instruction file\n }\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n return sources;\n}\n\nexport function getStaticallyLoadedInstructionPaths(\n projectPath: string,\n configDirName = DEFAULT_CONFIG_DIR,\n projectReader?: InstructionFileReader,\n): string[] {\n return instructionSourcePaths(loadAgentInstructions(projectPath, configDirName, projectReader), [projectPath]);\n}\n\n/**\n * Directories a session's project instructions load from: the host's\n * `instructionRoots` (resolved against the working directory, the session's\n * own checkout first) when it sets any, else the working directory itself.\n */\nexport function sessionInstructionRoots(workingDir: string, instructionRoots?: readonly string[]): string[] {\n if (!instructionRoots?.length) return [workingDir];\n return [...new Set(instructionRoots.map(root => resolve(workingDir, root)))];\n}\n\n/**\n * The instruction files a session's system prompt carries. Global files load\n * once (unless `skipGlobal`), then each instruction root's project files, in\n * root order. An untrusted checkout never reads project files off the working\n * tree: with a `baseRef` the first root (the session's own checkout) is served\n * from that ref and the other roots are skipped; without one no project files\n * load.\n */\nexport function loadSessionInstructions({\n workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout = false,\n baseRef,\n skipGlobal = false,\n}: {\n workingDir: string;\n instructionRoots?: readonly string[];\n configDir?: string;\n untrustedCheckout?: boolean;\n baseRef?: string;\n skipGlobal?: boolean;\n}): InstructionSource[] {\n const [primary, ...others] = sessionInstructionRoots(workingDir, instructionRoots);\n const primaryReader = untrustedCheckout\n ? baseRef\n ? createGitRefInstructionReader(primary!, baseRef)\n : { exists: () => false, read: () => '' }\n : undefined;\n const sources = loadAgentInstructions(primary!, configDir, primaryReader, { skipGlobal });\n if (untrustedCheckout) return sources;\n for (const root of others) {\n sources.push(...loadAgentInstructions(root, configDir, undefined, { skipGlobal: true }));\n }\n return sources;\n}\n\n/**\n * Paths of loaded instruction sources, each project source also under its\n * root's canonical path, so reactive reminders never repeat a file the\n * system prompt already carries.\n */\nexport function instructionSourcePaths(sources: InstructionSource[], roots: readonly string[]): string[] {\n return sources.flatMap(source => {\n const path = normalize(source.path);\n if (source.scope !== 'project') return [path];\n const root = roots.find(candidate => {\n const rel = relative(candidate, path);\n return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);\n });\n if (!root) return [path];\n const canonicalPath = join(realpathOrResolved(root), relative(root, path));\n return path === canonicalPath ? [path] : [path, canonicalPath];\n });\n}\n\n/** Heading the agent-instructions block is introduced by in the system prompt. */\nexport const AGENT_INSTRUCTIONS_HEADING = '# Agent Instructions';\n\n/**\n * Format a single instruction source as it appears in the system prompt.\n *\n * Exported so callers that attribute prompt cost per source (the `/context`\n * audit) measure the exact block that is sent rather than reconstructing it.\n */\nexport function formatInstructionSource(source: InstructionSource): string {\n const label = source.scope === 'global' ? 'Global' : 'Project';\n const origin = source.ref ? `${source.path} (at ref ${source.ref})` : source.path;\n return `<!-- ${label} instructions from ${origin} -->\\n${source.content}`;\n}\n\n/**\n * Format loaded instructions into a string for the system prompt.\n */\nexport function formatAgentInstructions(sources: InstructionSource[]): string {\n if (sources.length === 0) return '';\n\n const sections = sources.map(formatInstructionSource);\n\n return `\\n${AGENT_INSTRUCTIONS_HEADING}\\n\\n${sections.join('\\n\\n')}\\n`;\n}\n"],"mappings":";;;;;;;;;;;;AAcA,MAAM,oBAAoB,CAAC,aAAa,WAAW;AAGnD,MAAM,oBAAoB;CACxB;CACA;CACA;AACF;AAEA,MAAM,mBAAmB;CAAC;CAAW;CAAe;CAAkB;AAAoB;AAuB1F,MAAM,sBAA6C;CACjD,SAAQ,SAAQ,WAAW,IAAI;CAC/B,OAAM,SAAQ,aAAa,MAAM,OAAO;AAC1C;AAEA,SAAS,mBAAmB,MAAsB;CAChD,IAAI;EACF,OAAO,aAAa,IAAI;CAC1B,QAAQ;EACN,OAAO,QAAQ,IAAI;CACrB;AACF;AAEA,SAAS,0BAA0B,aAAsD;CACvF,MAAM,gBAAgB,mBAAmB,WAAW;CACpD,QAAO,SAAQ;EACb,MAAM,MAAM,SAAS,aAAa,IAAI;EACtC,IAAI,QAAQ,QAAQ,CAAC,IAAI,WAAW,KAAK,KAAK,KAAK,CAAC,WAAW,GAAG,GAAG,OAAO,IAAI,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;EAInG,IAAI,WAAW,QAAQ,IAAI;EAC3B,IAAI,sBAAqC;EACzC,OAAO,MAAM;GACX,IAAI,mBAAmB,QAAQ,MAAM,eACnC,sBAAsB,SAAS,UAAU,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;GAEpE,MAA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AAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAiB5D;AAED,eAAO,MAAM,eAAe,00EAmD3B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"build.js","names":[],"sources":["../../../src/agents/prompts/build.ts"],"sourcesContent":["/**\n * Build mode prompt — full tool access, make changes and verify.\n */\n\nimport type { PromptContext } from './index.js';\n\n/**\n * Dynamic build mode prompt function.\n * When an approved plan exists in state, prepends it so the agent\n * knows exactly what to implement.\n */\nexport function buildModePromptFn(ctx: PromptContext): string {\n if (ctx.activePlan) {\n return (\n `# Approved Plan\n\n**${ctx.activePlan.title}**\n\n${ctx.activePlan.plan}\n\n---\n\nImplement the approved plan above. Follow the steps in order and verify each step works before moving on.\n\n` + buildModePrompt\n );\n }\n return buildModePrompt;\n}\n\nexport const buildModePrompt = `\n# Build Mode\n\nYou are in BUILD mode. You have full access to all tools and can read, write, edit, and execute commands.\n\n## Working Style\n\n**For simple tasks** (typo fixes, small edits, single-file changes):\n- Just do it. No need to explain your plan first.\n\n**For non-trivial tasks** (3+ files, architectural decisions, unclear requirements):\n- Use the available task-management tools to create and update your task list\n- Work on ONE step at a time — complete it and verify it works before moving on\n- If multiple approaches are plausible and the choice would materially affect scope, behavior, or risk, stop and ask the user\n\n## The Implementation Loop\n\nFor each change you make:\n\n1. **Understand** — Read the relevant code. Check how similar things are done elsewhere.\n2. **Implement** — Make the change. Follow existing patterns and conventions.\n3. **Verify** — Test that it works. Don't assume — actually run it.\n4. **Prove** — Proactively prove that the change is good, makes sense in context, is a positive contribution, and works fully. The burden of proof is on YOU.\n5. **Clean up** — Ensure no broken code, no debug statements, no half-done features.\n\nOnly move to the next change after the current one is verified and proved to be working.\n\n## Verification is Required\n\nBefore considering any task complete:\n- Run relevant tests (check package.json for test scripts)\n- For TypeScript, run \\`tsc --noEmit\\` to catch type errors\n- If there are no automated tests, manually verify the behavior works as expected\n- Confirm the result makes sense in the codebase and improves the requested behavior\n- Use available task-checking tools to ensure all tracked tasks are done\n\n**Don't mark something as done until you've verified and proved it actually works.**\n\n## Error Recovery\n\nWhen something breaks:\n1. Read the full error output carefully — don't guess\n2. Find the root cause, not just the symptom\n3. Fix it properly — no casts or suppressions to hide errors\n4. Re-run to confirm the fix\n5. If progress is blocked after reasonable attempts, briefly explain the blocker, what you've tried, and the next best option\n\n## Git in Build Mode\n\n- Before committing, verify the code compiles and passes lint\n- Use descriptive branch names: \\`feat/...\\`, \\`fix/...\\`, \\`refactor/...\\`\n`;\n"],"mappings":";;;;;;AAWA,SAAgB,kBAAkB,KAA4B;CAC5D,IAAI,IAAI,YACN,OACE;;IAEF,IAAI,WAAW,MAAM;;EAEvB,IAAI,WAAW,KAAK;;;;;;IAMlB;CAGF,OAAO;AACT;AAEA,MAAa,kBAAkB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fast.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/fast.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,eAAO,MAAM,cAAc,6zBAiB1B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"fast.js","names":[],"sources":["../../../src/agents/prompts/fast.ts"],"sourcesContent":["/**\n * Fast mode prompt — quick answers and small edits, minimal overhead.\n */\n\nexport const fastModePrompt = `\n# Fast Mode\n\nYou are in FAST mode. Optimize for speed and brevity.\n\n## Rules\n- Keep responses short. Under 200 words unless the task genuinely requires more.\n- Skip planning. Just do the task directly.\n- For questions: give the direct answer, not a tutorial.\n- For edits: make the change, show what you did, move on.\n- Don't explore the codebase more than necessary for the immediate task.\n\n## When to Use Tools vs. Just Answer\n- If the user asks a general programming question, answer directly from knowledge. Don't search the codebase.\n- If the user asks about THIS project's code, use tools to look it up — don't guess.\n- If the user asks for a quick edit and you know the file, read it and edit it. Don't ask for confirmation.\n- One tool call to read + one to edit is ideal. Minimize round trips.\n`;\n"],"mappings":";;;;AAIA,MAAa,iBAAiB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAC3C,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C,OAAO,KAAK,EAAE,aAAa,IAAI,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AACpF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAYlF,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAQjE,MAAM,WAAW,aAAc,SAAQ,IAAI,CAAC,iBAAiB,EAAE,cAAc,CAAC;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,GAAG,CAAC;IACZ,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,0FAA0F;IAC1F,cAAc,CAAC,EAAE,oBAAoB,CAAC;IACtC,sFAAsF;IACtF,oBAAoB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACzC,4FAA4F;IAC5F,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sFAAsF;IACtF,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC,6FAA6F;IAC7F,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;CACpB;AAQD;;;;;;;;;;GAUG;AACH,MAAM,WAAW,aAAa;IAC5B,uDAAuD;IACvD,EAAE,EAAE,MAAM,CAAC;IACX,wCAAwC;IACxC,KAAK,EAAE,MAAM,CAAC;IACd,4DAA4D;IAC5D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,gDAAgD;IAChD,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,QAAQ,EAAE,aAAa,EAAE,GAAG,MAAM,CAKpE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,aAAa,GAAG,MAAM,CAE1D;AAED,wBAAsB,4BAA4B,CAAC,GAAG,EAAE,aAAa,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC,CAY/F;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,aAAa,EAAE,kBAAkB,CAAC,EAAE,iBAAiB,EAAE,GAAG,aAAa,EAAE,CAgIrH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/prompts/index.ts"],"sourcesContent":["/**\n * Prompt system — exports the prompt builder and mode-specific prompts.\n */\n\nexport { buildModePrompt, buildModePromptFn } from './build.js';\nexport { planModePrompt } from './plan.js';\nexport { fastModePrompt } from './fast.js';\n\nimport { buildBasePrompt } from '@mastra/core/coding-agent';\nimport type { PromptContext as BasePromptContext } from '@mastra/core/coding-agent';\nimport type { RequestContextReader } from '../../auth/account-routing-context.js';\nimport { loadSettings, resolveLspSetting } from '../../onboarding/settings.js';\nimport { MC_TOOLS } from '../../tool-names.js';\nimport { hasParallelKey, hasTavilyKey } from '../../tools/index.js';\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\nimport { resolveProviderWebSearchRoute } from '../model.js';\nimport {\n loadSessionInstructions,\n loadSessionInstructionsAsync,\n formatInstructionSource,\n AGENT_INSTRUCTIONS_HEADING,\n} from './agent-instructions.js';\nimport type { InstructionSource } from './agent-instructions.js';\nimport { buildModePromptFn } from './build.js';\nimport { fastModePrompt } from './fast.js';\nimport { modelSpecificPrompts } from './model.js';\nimport { planModePrompt } from './plan.js';\nimport { buildToolGuidance } from './tool-guidance.js';\n\n// Extended prompt context that includes runtime information\nexport interface PromptContext extends Omit<BasePromptContext, 'toolGuidance'> {\n modeId: string;\n state?: any;\n hostInstructions?: string;\n /** Request whose credentials decide the model's transport, and so its web search tool. */\n requestContext?: RequestContextReader;\n /** Controller built-in tools removed via `disableBuiltinTools`; treated as denied. */\n disabledBuiltinTools?: readonly string[];\n /** Host-configured workspace-relative plans directory (see `MastraCodeConfig.plansDir`). */\n plansDir?: string;\n /** Agent tools removed via `disabledTools` (e.g. `web_search`); treated as denied. */\n disabledTools?: readonly string[];\n /** Resolved in `buildFullPromptSections`; false when `submit_plan` is denied or disabled. */\n submitPlanAvailable?: boolean;\n currentDate: string;\n workingDir: string;\n}\n\nconst modePrompts: Record<string, string | ((ctx: PromptContext) => string)> = {\n build: buildModePromptFn,\n plan: planModePrompt,\n fast: fastModePrompt,\n};\n\n/**\n * One labeled piece of the assembled system prompt.\n *\n * The system prompt is a single string by the time it reaches the model, which\n * makes it impossible to say which configuration source is responsible for\n * which share of the context window. Building it as labeled sections and\n * joining them at the end keeps that attribution available to the `/context`\n * audit while guaranteeing the audit measures the exact text that is sent —\n * a parallel \"describe the prompt\" path would drift and report numbers for a\n * prompt that is no longer assembled this way.\n */\nexport interface PromptSection {\n /** Stable identifier, unique within a single build. */\n id: string;\n /** Human-readable label for display. */\n label: string;\n /** Optional provenance (e.g. the instruction file path). */\n detail?: string;\n /** The exact text contributed to the prompt. */\n content: string;\n}\n\n/** Join prompt sections into the final system prompt string. */\nexport function joinPromptSections(sections: PromptSection[]): string {\n return sections\n .map(section => section.content)\n .filter(Boolean)\n .join('\\n\\n');\n}\n\n/**\n * Build the full system prompt for a given mode and context.\n * Combines the base prompt with mode-specific instructions.\n */\nexport function buildFullPrompt(ctx: PromptContext): string {\n return joinPromptSections(buildFullPromptSections(ctx));\n}\n\nexport async function buildFullPromptSectionsAsync(ctx: PromptContext): Promise<PromptSection[]> {\n const sources = ctx.workingDir\n ? await loadSessionInstructionsAsync({\n workingDir: ctx.workingDir,\n instructionRoots: Array.isArray(ctx.state?.instructionRoots) ? ctx.state.instructionRoots : undefined,\n configDir: ctx.state?.configDir,\n untrustedCheckout: ctx.state?.untrustedCheckout === true,\n baseRef: typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined,\n skipGlobal: ctx.state?.skipGlobalInstructions === true,\n })\n : [];\n return buildFullPromptSections(ctx, sources);\n}\n\n/**\n * Build the system prompt as labeled sections. `buildFullPrompt` is the join of\n * these, so the two can never disagree about what the model receives.\n */\nexport function buildFullPromptSections(ctx: PromptContext, loadedInstructions?: InstructionSource[]): PromptSection[] {\n // Determine whether web search tools are available\n // Parallel/Tavily register web_search and web_extract; provider search registers only web_search.\n const hasWebExtract = hasParallelKey() || hasTavilyKey();\n const hasWebSearch =\n hasWebExtract || resolveProviderWebSearchRoute(ctx.modelId, { requestContext: ctx.requestContext }) !== undefined;\n\n // Collect per-tool deny rules so guidance omits denied tools\n const deniedTools = new Set<string>();\n const permRules = ctx.state?.permissionRules as { tools?: Record<string, string> } | undefined;\n if (permRules?.tools) {\n for (const [name, policy] of Object.entries(permRules.tools)) {\n if (policy === 'deny') deniedTools.add(name);\n }\n }\n\n // Disabled built-ins are never registered, so they are denied for guidance too.\n for (const name of ctx.disabledBuiltinTools ?? []) deniedTools.add(name);\n // `createDynamicTools` drops disabled agent tools (such as web_search), so omit their guidance too.\n for (const name of ctx.disabledTools ?? []) deniedTools.add(name);\n\n // LSP is opt-in — when it is off the tool is never registered, so its\n // guidance must not be advertised either.\n if (resolveLspSetting(loadSettings().lsp) === false) deniedTools.add(MC_TOOLS.LSP_INSPECT);\n\n // Build mode-aware tool guidance\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const toolGuidance = buildToolGuidance(ctx.modeId, {\n hasWebSearch,\n hasWebExtract,\n hasSubagents: ctx.hasSubagents,\n deniedTools,\n plansDir: getLocalPlansRelativeDir({ factoryProjectId, plansDir: ctx.plansDir }),\n });\n\n // Map new context to base context\n const baseCtx: BasePromptContext = {\n projectPath: ctx.workingDir || '(no workspace attached)',\n projectName: ctx.projectName || 'unknown',\n gitBranch: ctx.gitBranch,\n platform: process.platform,\n commonBinaries: ctx.commonBinaries,\n date: ctx.currentDate,\n mode: ctx.modeId,\n modelId: ctx.modelId,\n coAuthorName: ctx.coAuthorName,\n coAuthorEmail: ctx.coAuthorEmail,\n activePlan: ctx.state?.activePlan,\n hasSubagents: ctx.hasSubagents !== false && !deniedTools.has('subagent'),\n planApprovalStartsGoal: ctx.planApprovalStartsGoal,\n toolGuidance,\n };\n\n const base = buildBasePrompt(baseCtx);\n const entry = modePrompts[ctx.modeId] || modePrompts.build;\n const modeSpecific =\n (typeof entry === 'function' ? entry({ ...ctx, submitPlanAvailable: !deniedTools.has('submit_plan') }) : entry) ??\n '';\n const modelSpecific = ctx.modelId\n ? (modelSpecificPrompts[ctx.modelId as keyof typeof modelSpecificPrompts] ?? '')\n : '';\n\n // The current task list is carried on the agent state-signal lane (see\n // TaskStateProcessor) rather than injected into the cached system prompt. This\n // keeps the prompt prefix stable across task updates (preserving prompt cache)\n // while still surviving observational-memory truncation.\n\n // Load and inject agent instructions from AGENTS.md/CLAUDE.md files.\n // Untrusted checkouts (e.g. a PR branch under review) never read\n // project-scope files off the working tree: their AGENTS.md is\n // attacker-writable and would otherwise land in the system prompt as\n // trusted configuration. When the session carries a trusted base ref, the\n // project instructions are served from that ref instead (`git show`);\n // without one, project-scope files are skipped entirely. Home-directory\n // (global) instructions belong to whoever owns the machine, so hosts that\n // run sessions for someone else opt out of them entirely.\n // A host booting several checkouts under one working directory names them\n // as `instructionRoots`, so each checkout's own files load.\n const configDir = ctx.state?.configDir as string | undefined;\n const baseRef = typeof ctx.state?.baseRef === 'string' ? ctx.state.baseRef : undefined;\n const instructionRoots = Array.isArray(ctx.state?.instructionRoots)\n ? (ctx.state.instructionRoots as string[])\n : undefined;\n // No working directory means a hosted session with no project attached:\n // load NO instruction files at all — project locations would resolve\n // against the server's own cwd, and global locations against the server's\n // homedir. Neither belongs in a hosted session's prompt.\n const instructionSources =\n loadedInstructions ??\n (ctx.workingDir\n ? loadSessionInstructions({\n workingDir: ctx.workingDir,\n instructionRoots,\n configDir,\n untrustedCheckout: ctx.state?.untrustedCheckout === true,\n baseRef,\n skipGlobal: ctx.state?.skipGlobalInstructions === true,\n })\n : []);\n // Emitted per source so each AGENTS.md/CLAUDE.md can be costed individually.\n // The heading rides on the first source's section, which is exactly how\n // `formatAgentInstructions` lays the block out, so joining the sections\n // reproduces its output byte for byte.\n const instructionSections: PromptSection[] = instructionSources.map((source, index) => {\n const isFirst = index === 0;\n const isLast = index === instructionSources.length - 1;\n let content = formatInstructionSource(source);\n if (isFirst) content = `${AGENT_INSTRUCTIONS_HEADING}\\n\\n${content}`;\n // The block as a whole used to be trimmed, which only ever affected the\n // trailing whitespace of the final source's content.\n if (isLast) content = content.trimEnd();\n return {\n id: `agent-instructions:${source.path}:${index}`,\n label: `${source.scope === 'global' ? 'Global' : 'Project'} instructions`,\n detail: source.ref ? `${source.path} (at ref ${source.ref})` : source.path,\n content,\n };\n });\n\n const hostInstructions = ctx.hostInstructions?.trim() ?? '';\n\n return [\n { id: 'base-prompt', label: 'Base system prompt', content: base },\n { id: 'host-instructions', label: 'Host instructions', content: hostInstructions },\n ...instructionSections,\n { id: 'model-prompt', label: 'Model-specific prompt', detail: ctx.modelId, content: modelSpecific.trim() },\n { id: 'mode-prompt', label: 'Mode prompt', detail: ctx.modeId, content: modeSpecific.trim() },\n ].filter(section => Boolean(section.content));\n}\n"],"mappings":";;;;;;;;;;;;;;AAgDA,MAAM,cAAyE;CAC7E,OAAO;CACP,MAAM;CACN,MAAM;AACR;;AAyBA,SAAgB,mBAAmB,UAAmC;CACpE,OAAO,SACJ,KAAI,YAAW,QAAQ,OAAO,CAAC,CAC/B,OAAO,OAAO,CAAC,CACf,KAAK,MAAM;AAChB;;;;;AAMA,SAAgB,gBAAgB,KAA4B;CAC1D,OAAO,mBAAmB,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AAW,WAAW,UAAU;GAC3D,QAAQ,OAAO,MAAM,GAAG,OAAO,KAAK,WAAW,OAAO,IAAI,KAAK,OAAO;GACtE;EACF;CACF,CAAC;CAED,MAAM,mBAAmB,IAAI,kBAAkB,KAAK,KAAK;CAEzD,OAAO;EACL;GAAE,IAAI;GAAe,OAAO;GAAsB,SAAS;EAAK;EAChE;GAAE,IAAI;GAAqB,OAAO;GAAqB,SAAS;EAAiB;EACjF,GAAG;EACH;GAAE,IAAI;GAAgB,OAAO;GAAyB,QAAQ,IAAI;GAAS,SAAS,cAAc,KAAK;EAAE;EACzG;GAAE,IAAI;GAAe,OAAO;GAAe,QAAQ,IAAI;GAAQ,SAAS,aAAa,KAAK;EAAE;CAC9F,CAAC,CAAC,QAAO,YAAW,QAAQ,QAAQ,OAAO,CAAC;AAC9C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/model.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,oBAAoB;IAC/B,gBAAgB;IAMhB,gBAAgB;CAUjB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"model.js","names":[],"sources":["../../../src/agents/prompts/model.ts"],"sourcesContent":["export const modelSpecificPrompts = {\n 'openai/gpt-5.4': `<autonomy_and_persistence>\nPersist until the task is fully handled end-to-end within the current turn whenever feasible: do not stop at analysis or partial fixes; carry changes through implementation, verification, and a clear explanation of outcomes unless the user explicitly pauses or redirects you.\n\nUnless the user explicitly asks for a plan, asks a question about the code, is brainstorming potential solutions, or some other intent that makes it clear that code should not be written, assume the user wants you to make code changes or run tools to solve the user's problem. In these cases, it's bad to output your proposed solution in a message, you should go ahead and actually implement the change. If you encounter challenges or blockers, you should attempt to resolve them yourself.\n</autonomy_and_persistence>\n`,\n 'openai/gpt-5.5': `<coding_behavior>\nWork outcome-first: infer the user's goal, define what \"done\" means from the request and repo context, then choose an efficient path that reaches that outcome without sacrificing correctness, maintainability, or proof.\n\nFor non-trivial multi-step or tool-heavy tasks, start with a short visible preamble that acknowledges the request and states the first action. Skip the preamble for direct answers and tiny edits. Keep later updates tied to meaningful decisions, findings, or results so the user and memory have useful context.\n\nUse efficient retrieval. Read enough code, docs, logs, and command output to act correctly, including neighboring implementations when conventions matter. Stop searching once you have sufficient evidence, but do not let brevity outrank correctness, security, or compatibility with existing patterns.\n\nFor coding work, make focused changes that follow the surrounding conventions. Avoid unrequested features, broad refactors, speculative error handling, and comments that only explain the diff.\n</coding_behavior>\n`,\n};\n"],"mappings":";AAAA,MAAa,uBAAuB;CAClC,kBAAkB;;;;;;CAMlB,kBAAkB;;;;;;;;;;AAUpB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/plan.ts"],"names":[],"mappings":"AAKA,UAAU,iBAAiB;IACzB,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mFAAmF;IACnF,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,8FAA8F;IAC9F,sBAAsB,CAAC,EAAE,OAAO,CAAC;CAClC;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,iBAAiB,GAAG,MAAM,CAoE7D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/prompts/plan.ts"],"sourcesContent":["/**\n * Plan mode prompt — read-only exploration and planning.\n */\nimport { getLocalPlansRelativeDir } from '../../utils/plans.js';\n\ninterface PlanPromptContext {\n state?: Record<string, unknown>;\n plansDir?: string;\n /** False when the host disabled or denied `submit_plan`; defaults to available. */\n submitPlanAvailable?: boolean;\n /** False when the host does not start a goal on plan approval (Factory); defaults to true. */\n planApprovalStartsGoal?: boolean;\n}\n\nexport function planModePrompt(ctx: PlanPromptContext): string {\n const factoryProjectId = typeof ctx.state?.factoryProjectId === 'string' ? ctx.state.factoryProjectId : undefined;\n const plansDir = getLocalPlansRelativeDir({ factoryProjectId, plansDir: ctx.plansDir });\n const examplePath = `${plansDir}/add-dark-mode.md`;\n const submitPlanAvailable = ctx.submitPlanAvailable !== false;\n const planApprovalStartsGoal = ctx.planApprovalStartsGoal !== false;\n\n return `\n# Plan Mode — READ-ONLY (except plan files)\n\nYou are in PLAN mode. Your job is to explore the codebase and design an implementation plan — NOT to make changes to the project.\n\n## CRITICAL: Read-Only Mode (project files)\n\nThis mode is **read-only for project files**. You must NOT modify the project.\n\n- Do NOT modify, create, or delete project files\n- Do NOT run commands that change state (no git commit, no npm install, no file creation)\n- Do NOT run build commands, tests, or scripts that have side effects\n\nThe ONE exception is plan files: you CAN create and edit markdown files inside \\`${plansDir}/\\` (e.g. \\`${examplePath}\\`). You may NOT write anywhere else.\n\nIf the user asks you to make changes while in Plan mode, explain that you're in read-only mode and they should switch to Build mode (\\`/mode build\\`) first.\n\n## Exploration Strategy\n\nBefore writing any plan, build a mental model of the codebase:\n1. Start with the directory structure (\\`view\\` on the project root or relevant subdirectory).\n2. Find the relevant entry points and core files using \\`search_content\\` and \\`find_files\\`.\n3. Read the actual code — don't assume based on file names alone.\n4. Trace data flow: where does input come from, how is it transformed, where does it go?\n5. Identify existing patterns the codebase uses (naming, structure, error handling, testing).\n\n${submitPlanAvailable ? goalReadySection(planApprovalStartsGoal) : ''}## Your Plan Output\n\nProduce a clear, step-by-step plan with this structure:\n\n### Overview\nOne paragraph: what the change does and why.\n\n### Complexity Estimate\n- **Size**: Small (1-2 files) / Medium (3-5 files) / Large (6+ files)\n- **Risk**: Low (additive, no breaking changes) / Medium (modifies existing behavior) / High (architectural, affects many consumers)\n- **Dependencies**: List any new packages, external services, or migration steps needed.\n\n### Steps\nFor each step:\n1. **File**: path to create or modify\n2. **Change**: what to add/modify/remove, with enough specificity to implement directly\n3. **Why**: brief rationale connecting this step to the overall goal\n\n### Verification\n- What tests to run\n- What to check manually\n- What could go wrong\n\n## Plan File Workflow\n\nWrite each plan to its own markdown file under \\`${plansDir}/\\` (e.g. \\`${examplePath}\\`). Start the file with a \\`# Title\\` heading describing the plan.\n\n1. **${submitPlanAvailable ? 'First submission' : 'Writing'}**: Write your plan to a file under \\`${plansDir}/\\` using \\`write_file\\`${submitPlanAvailable ? ', then call \\`submit_plan\\` with the \\`path\\` to that file' : ''}.\n2. **Reading**: Use \\`view\\` to read a plan file.\n3. **Editing**: Use \\`string_replace_lsp\\` for targeted edits to specific sections.\n\n**Reuse the same file while you keep iterating on the same plan.** Only create a NEW file when you're starting a genuinely different plan — that keeps each plan available to look back at and keeps revision diffs meaningful.\n\n${submitPlanAvailable ? submitPlanSection(plansDir, examplePath, planApprovalStartsGoal) : planFileOnlySection(plansDir)}Do NOT start implementing until the plan is approved.\n`;\n}\n\nfunction goalReadySection(planApprovalStartsGoal: boolean): string {\n const intro = planApprovalStartsGoal\n ? 'Approving a plan in the submit_plan approval UI starts it as a persistent goal. Write plans so they can be carried out as a goal:'\n : 'Write plans so they can be carried out autonomously after approval:';\n return `## ${planApprovalStartsGoal ? 'Goal-Ready Plans' : 'Executable Plans'}\n\n${intro}\n- Make the desired outcome explicit and verifiable.\n- Break work into ordered, actionable steps that can be executed autonomously.\n- Include constraints, risks, blockers, and decision points that may require user input.\n- Include concrete verification criteria so ${planApprovalStartsGoal ? 'the goal judge' : 'you'} can tell when the work is done.\n\n`;\n}\n\nfunction submitPlanSection(plansDir: string, examplePath: string, planApprovalStartsGoal: boolean): string {\n const approveOutcome = planApprovalStartsGoal\n ? 'switches to Build mode and starts the plan as a goal, so the agent keeps working toward the plan until judged complete, paused, or waiting for user input'\n : 'switches to Build mode for implementation';\n return `## IMMEDIATE ACTION: Write plan file, then call submit_plan\n\nAs soon as your plan is complete:\n1. Write it to a file under \\`${plansDir}/\\` using \\`write_file\\`\n2. Call \\`submit_plan\\` with the \\`path\\` to that file\n\n**CRITICAL:** Do NOT generate a long text response describing your plan. The plan content belongs in the plan file, not in your text output or the \\`submit_plan\\` arguments.\n\n\\`\\`\\`javascript\nsubmit_plan({\n path: \"${examplePath}\"\n})\n\\`\\`\\`\n\nThe user will see the plan rendered inline and can:\n- **Approve** — ${approveOutcome}\n- **Request changes** — rejects the plan; the agent stops immediately and the user provides revision feedback in their next chat message\n\n## Revision Workflow\n\nIf the user requests changes, you will be stopped immediately. Wait for their next message — it will contain their revision feedback. When you receive it:\n1. Use \\`view\\` to read the SAME plan file\n2. Use \\`string_replace_lsp\\` to make targeted edits based on feedback\n3. Use \\`view\\` to re-read the updated file\n4. Call \\`submit_plan\\` again with the same \\`path\\` — editing the file alone does NOT resubmit it\n\nThe user will see a diff of what changed between the previous and revised plan. Use \\`string_replace_lsp\\` for targeted edits so the diff is clear and meaningful — do NOT rewrite the entire plan from scratch for small changes, and do NOT move the plan to a new file for a revision.\n\n`;\n}\n\nfunction planFileOnlySection(plansDir: string): string {\n return `## When the plan is complete\n\nPlan approval is not available in this session — there is no \\`submit_plan\\` tool. As soon as your plan is complete:\n1. Write it to a file under \\`${plansDir}/\\` using \\`write_file\\`\n2. Follow any host or session instructions for handing the plan off; otherwise reply with a brief summary and the plan file path\n\n**CRITICAL:** Do NOT generate a long text response describing your plan. The plan content belongs in the plan file.\n\nWhen you receive revision feedback, edit the SAME plan file with \\`string_replace_lsp\\` rather than rewriting it or moving it to a new file.\n\n`;\n}\n"],"mappings":";;;;;AAcA,SAAgB,eAAe,KAAgC;CAC7D,MAAM,mBAAmB,OAAO,IAAI,OAAO,qBAAqB,WAAW,IAAI,MAAM,mBAAmB,KAAA;CACxG,MAAM,WAAW,yBAAyB;EAAE;EAAkB,UAAU,IAAI;CAAS,CAAC;CACtF,MAAM,cAAc,GAAG,SAAS;CAChC,MAAM,sBAAsB,IAAI,wBAAwB;CACxD,MAAM,yBAAyB,IAAI,2BAA2B;CAE9D,OAAO;;;;;;;;;;;;;mFAa0E,SAAS,cAAc,YAAY;;;;;;;;;;;;;EAapH,sBAAsB,iBAAiB,sBAAsB,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;mDAyBnB,SAAS,cAAc,YAAY;;OAE/E,sBAAsB,qBAAqB,UAAU,wCAAwC,SAAS,0BAA0B,sBAAsB,2DAA+D,GAAG;;;;;;EAM7N,sBAAsB,kBAAkB,UAAU,aAAa,sBAAsB,IAAI,oBAAoB,QAAQ,EAAE;;AAEzH;AAEA,SAAS,iBAAiB,wBAAyC;CAIjE,OAAO,MAAM,yBAAyB,qBAAqB,mBAAmB;;EAHhE,yBACV,sIACA,sEAGE;;;;8CAIsC,yBAAyB,mBAAmB,MAAM;;;AAGhG;AAEA,SAAS,kBAAkB,UAAkB,aAAqB,wBAAyC;CAIzG,OAAO;;;gCAGuB,SAAS;;;;;;;WAO9B,YAAY;;;;;kBAbE,yBACnB,8JACA,4CAgB2B;;;;;;;;;;;;;;AAcjC;AAEA,SAAS,oBAAoB,UAA0B;CACrD,OAAO;;;gCAGuB,SAAS;;;;;;;;AAQzC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-guidance.d.ts","sourceRoot":"","sources":["../../../src/agents/prompts/tool-guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAMH,UAAU,mBAAmB;IAC3B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,mGAAmG;IACnG,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,uEAAuE;IACvE,WAAW,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1B,oEAAoE;IACpE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,mBAAwB,GAAG,MAAM,CAqP3F"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-guidance.js","names":[],"sources":["../../../src/agents/prompts/tool-guidance.ts"],"sourcesContent":["/**\n * Mode-specific tool behavioral guidance.\n * Generates tool usage instructions that match the actual registered tool names\n * and are scoped to what's available in the current mode.\n */\n\nimport { MC_TOOLS } from '../../tool-names.js';\n\nconst DEFAULT_PLANS_DIR = '.mastracode/plans';\n\ninterface ToolGuidanceOptions {\n hasWebSearch?: boolean;\n /** `web_extract` is registered (Parallel/Tavily); provider-executed search has no extract tool. */\n hasWebExtract?: boolean;\n hasSubagents?: boolean;\n /** Tool names that have been denied — omit their guidance sections. */\n deniedTools?: Set<string>;\n /** Workspace-relative directory where plan mode can write plans. */\n plansDir?: string;\n}\n\nexport function buildToolGuidance(modeId: string, options: ToolGuidanceOptions = {}): string {\n const denied = options.deniedTools ?? new Set<string>();\n // Name the dir with `/` so the win32 default (`.mastracode\\plans`) still matches DEFAULT_PLANS_DIR.\n const plansDir = (options.plansDir ?? DEFAULT_PLANS_DIR).replaceAll('\\\\', '/');\n const sections: string[] = [];\n\n sections.push(`# Tool Usage Rules\n\nIMPORTANT: You can ONLY call tools by their exact registered names listed below. Shell commands like \\`git\\`, \\`npm\\`, \\`ls\\`, etc. are NOT tools — they must be run via the \\`execute_command\\` tool.\n\nYou have access to the following tools. Use the RIGHT tool for the job:`);\n\n // --- Read tools (all modes) ---\n\n const readTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.VIEW)) {\n readTools.push(`\n**${MC_TOOLS.VIEW}** — Read file contents\n- Use this to read file contents. Don't propose changes to code you haven't seen; reading with shell commands (cat, sed, rg) also works.\n- Use \\`offset\\` (1-indexed start line) and \\`limit\\` (number of lines) for large files.\n- Example: Read lines 50-100: \\`{ path: \"src/big-file.ts\", offset: 50, limit: 51 }\\`\n- To list directories, use \\`${MC_TOOLS.FIND_FILES}\\` instead.`);\n }\n\n if (!denied.has(MC_TOOLS.SEARCH_CONTENT)) {\n readTools.push(`\n**${MC_TOOLS.SEARCH_CONTENT}** — Search file contents using regex\n- Preferred for content search (finding functions, variables, error messages, imports, etc.)\n- Use \\`path\\` to filter by directory or glob pattern. Supports \\`contextLines\\`, \\`caseSensitive\\`, and \\`maxCount\\`.\n- Example: Find a function: \\`{ pattern: \"function handleSubmit\", path: \"**/*.ts\" }\\`\n- Example: Find imports: \\`{ pattern: \"from ['\\\\\"\\\\]express['\\\\\"\\\\]\", path: \"**/*.ts\" }\\`\n- Respects .gitignore by default.`);\n }\n\n if (!denied.has(MC_TOOLS.FIND_FILES)) {\n readTools.push(`\n**${MC_TOOLS.FIND_FILES}** — List files and directories as a tree\n- Preferred for exploring project structure and finding files by pattern.\n- Returns tree-style output. Respects .gitignore by default.\n- Example: List project root: \\`{ path: \"./\" }\\`\n- Example: Find test files: \\`{ path: \"./src\", pattern: \"**/*.test.ts\" }\\`\n- Example: Find config files: \\`{ pattern: \"*.config.{js,ts,json}\" }\\``);\n }\n\n if (!denied.has(MC_TOOLS.EXECUTE_COMMAND)) {\n readTools.push(`\n**${MC_TOOLS.EXECUTE_COMMAND}** — Run shell commands\n- Use for: git, npm/pnpm, docker, build tools, test runners, and other terminal operations.\n- Prefer dedicated tools for: file reading (${MC_TOOLS.VIEW}), file search (${MC_TOOLS.SEARCH_CONTENT}/${MC_TOOLS.FIND_FILES}), file editing (${MC_TOOLS.STRING_REPLACE_LSP}/${MC_TOOLS.WRITE_FILE}).\n- Commands have a 30-second default timeout. Use \\`timeout\\` for longer commands, \\`cwd\\` for working directory.\n- Use the \\`tail\\` parameter or pipe to \\`| tail -N\\` to limit output — the full output streams to the user, only the tail is returned to you. If you're building any kind of package you should be tailing.\n- Always set \\`description\\` to a 5-10 word summary of what the command does; the user sees it instead of the raw command. Put it first in the arguments, before \\`command\\`, so the user sees it while the rest of the call streams in. Write each one as the next step in a running narrative that can lean on earlier commands (e.g. \"Searching open PRs for failing CI\", then \"Drilling into the first of 15 failures\").\n- Good: Run independent commands in parallel when possible.\n- Bad: Running \\`cat file.txt\\` — use the ${MC_TOOLS.VIEW} tool instead.`);\n }\n\n if (!denied.has(MC_TOOLS.LSP_INSPECT)) {\n readTools.push(`\n**${MC_TOOLS.LSP_INSPECT}** — Inspect code using Language Server Protocol\n- Use this for type information, hover docs, go-to-definition, and finding implementations for a symbol.\n- Best when you already know the file and line and need semantic code intelligence rather than raw file contents.\n- Input: \\`path\\` (absolute file path), \\`line\\` (1-indexed line number), \\`match\\` (the exact line content with exactly one \\`<<<\\` cursor marker).\n- Output includes: \\`hover\\`, \\`definition\\` (compact location with preview), and \\`implementation\\` (compact usage/implementation locations).\n- Example: \\`{ path: \"/abs/path/src/foo.ts\", line: 10, match: \"const foo = <<<bar()\" }\\` — inspect the symbol at the \\`<<<\\` position.\n- Use \\`${MC_TOOLS.VIEW}\\` when you need to read the implementation or surrounding code.\n- Use \\`${MC_TOOLS.SEARCH_CONTENT}\\` or \\`${MC_TOOLS.FIND_FILES}\\` first if you do not yet know where the symbol is.`);\n }\n\n if (!denied.has(MC_TOOLS.NOTIFICATION_INBOX)) {\n readTools.push(`\n**${MC_TOOLS.NOTIFICATION_INBOX}** — Inspect and manage notification inbox records\n- Use this when a \\`<notification-summary>\\` says pending notifications exist.\n- Use \\`{ \"action\": \"list\", \"status\": \"pending\" }\\` or \\`{ \"action\": \"search\", \"query\": \"...\" }\\` to find notification records for the current thread.\n- Use \\`read\\` to deliver unread notification signals into the chat and mark them seen; the tool result summarizes the count instead of exposing notification contents.\n- Use \\`dismiss\\` or \\`archive\\` only when the user asks or the notification is no longer relevant.`);\n }\n\n if (readTools.length > 0) {\n sections.push(readTools.join('\\n'));\n }\n\n // --- Write/edit tools (build & fast only) ---\n\n if (modeId !== 'plan') {\n const writeTools: string[] = [];\n\n if (!denied.has(MC_TOOLS.STRING_REPLACE_LSP)) {\n writeTools.push(`\n**${MC_TOOLS.STRING_REPLACE_LSP}** — Edit files by replacing exact text\n- \\`old_string\\` must be an exact match of existing text in the file.\n- Provide enough surrounding context in \\`old_string\\` to make it unique.\n- Use \\`replace_all: true\\` to replace all occurrences (default: false, requires unique match).\n- For creating new files, use \\`${MC_TOOLS.WRITE_FILE}\\` instead.\n- Good: Include 2-3 lines of surrounding context to ensure uniqueness.\n- Bad: Using just \\`return true;\\` — too common, will match multiple places.`);\n }\n\n if (!denied.has(MC_TOOLS.WRITE_FILE)) {\n writeTools.push(`\n**${MC_TOOLS.WRITE_FILE}** — Create new files or overwrite existing ones\n- Use this to create new files.\n- Overwriting replaces the whole file, so make sure you know its current contents first.\n- Prefer editing existing files over creating new ones.`);\n }\n\n if (writeTools.length > 0) {\n sections.push(writeTools.join('\\n'));\n }\n }\n\n // --- Web tools (all modes, conditionally available) ---\n\n if (options.hasWebSearch) {\n const webTools: string[] = [];\n if (!denied.has('web_search')) webTools.push('**web_search**');\n if (options.hasWebExtract && !denied.has('web_extract')) webTools.push('**web_extract**');\n if (webTools.length > 0) {\n const purpose =\n webTools.length === 2\n ? 'Search the web / extract page content'\n : webTools[0] === '**web_search**'\n ? 'Search the web'\n : 'Extract page content';\n sections.push(`\n${webTools.join(' / ')} — ${purpose}\n- Use for looking up documentation, error messages, package APIs.`);\n }\n }\n\n // --- Task management tools (all modes) ---\n\n const taskTools: string[] = [];\n const canUpdateTask = !denied.has('task_update');\n const canCompleteTask = !denied.has('task_complete');\n const canCheckTasks = !denied.has('task_check');\n const canWriteTasks = !denied.has('task_write');\n const patchToolGuidance =\n canUpdateTask && canCompleteTask\n ? '- Prefer task_update or task_complete when changing one existing task.'\n : canUpdateTask\n ? '- Prefer task_update when changing one existing task.'\n : canCompleteTask\n ? '- Prefer task_complete when marking one existing task completed.'\n : '- Use task_write with the full task list when changing existing tasks.';\n\n if (canWriteTasks) {\n taskTools.push(`\n**task_write** — Track tasks for complex multi-step work\n- Use when a task requires 3 or more distinct steps or actions.\n- Use task_write to create the initial task list or replace the whole list after replanning.\n- Each task has: id (stable identifier), content (imperative form), status (pending, in_progress, or completed), activeForm (present continuous form shown during execution).\n- Keep task IDs stable across updates. If you omit IDs, the tool result returns generated IDs.\n${patchToolGuidance}\n- Mark tasks \\`in_progress\\` BEFORE starting work. Only ONE task should be \\`in_progress\\` at a time.\n- Mark tasks \\`completed\\` IMMEDIATELY after finishing each task. Do not batch completions.`);\n }\n\n if (canUpdateTask) {\n taskTools.push(`\n**task_update** — Patch one tracked task by ID\n- Use this for targeted changes to one existing task.\n- Provide the task ID and only the fields that changed: content, status, or activeForm.`);\n }\n\n if (canCompleteTask) {\n const idSource = canCheckTasks\n ? 'Use task_check if you need the current IDs before completing a task.'\n : canWriteTasks\n ? 'Use IDs returned by task_write.'\n : 'Use only task IDs already visible in the current task list.';\n taskTools.push(`\n**task_complete** — Mark one tracked task completed by ID\n- Use this immediately after finishing a tracked task.\n- ${idSource}`);\n }\n\n if (canCheckTasks) {\n taskTools.push(`\n**task_check** — Check completion status of tasks\n- Use this BEFORE finishing tracked work to verify all tasks are completed.\n- Returns a readable status summary plus structured fields: tasks, summary, incompleteTasks, and isError.\n- summary includes total, completed, inProgress, pending, incomplete, hasTasks, and allCompleted.\n- Use summary.allCompleted to decide whether tracked work is complete; if summary.hasTasks is false, no task list is currently tracked.\n- If any tasks remain incomplete, continue working on them.\n- IMPORTANT: Always check task completion before ending work on a complex task.`);\n }\n\n if (!denied.has('ask_user')) {\n taskTools.push(`\n**ask_user** — Ask the user a structured question\n- Use when you need clarification, want to validate assumptions, or need the user to make a decision.\n- Provide clear, specific questions. End with a question mark.\n- Include options (2-4 choices) for structured decisions. Omit options for open-ended questions.\n- Don't use this for simple yes/no — just ask in your text response.`);\n }\n\n if (taskTools.length > 0) {\n sections.push(taskTools.join('\\n'));\n }\n\n // --- Plan tools (plan mode) ---\n\n if (modeId === 'plan' && !denied.has('submit_plan')) {\n sections.push(`\n**submit_plan** — Submit a completed implementation plan for user review\n- Call this tool when your plan is complete. Do NOT just describe your plan in text — you MUST call this tool.\n- The plan will be rendered as markdown and the user can approve, reject, or request changes.\n- On approval, the system automatically switches to the default mode so you can implement.\n- Takes one argument: \\`path\\` (the plan markdown file you wrote under \\`${plansDir}/\\`). Do NOT pass the plan body — it lives in the file.`);\n }\n\n // Outside plan mode nothing else names the plans directory (the submit_plan\n // tool example is directory-neutral), so state it here. Explore (`fast`) mode\n // is read-only and has neither submit_plan nor file writes.\n if (modeId !== 'plan' && modeId !== 'fast' && !denied.has('submit_plan')) {\n const elsewhere =\n plansDir === DEFAULT_PLANS_DIR\n ? ''\n : `, never under \\`${DEFAULT_PLANS_DIR}/\\`. Plans anywhere else cannot be shown to the user`;\n sections.push(`\n**submit_plan** — Submit a plan for user review\n- Write plan files under \\`${plansDir}/\\` (e.g. \\`${plansDir}/add-dark-mode.md\\`)${elsewhere}.\n- Pass that file's \\`path\\` to \\`submit_plan\\`. Do NOT pass the plan body — it lives in the file.`);\n }\n\n if (modeId === 'plan') {\n sections.push(`\n**Plan file access** — Your plan lives in a markdown file under \\`${plansDir}/\\` (e.g. \\`add-dark-mode-toggle.md\\`)\n- Use \\`write_file\\` to create the plan file, \\`view\\` to read it, and \\`string_replace_lsp\\` for targeted edits.\n- On first submission: write the plan to the file, then call \\`submit_plan\\` with its \\`path\\`.\n- On revision: read the existing file, edit specific sections, re-read, then call \\`submit_plan\\` with the same \\`path\\`.\n- If a plan file already exists, you previously submitted it — read it before revising.`);\n }\n\n // --- Subagent tool (all modes) ---\n\n if (options.hasSubagents !== false && !denied.has('subagent')) {\n sections.push(`\n**subagent** — Delegate a focused task to a specialized subagent\n- Only use subagents when you will spawn **multiple subagents in parallel**. If you only need one task done, do it yourself.\n- Subagent outputs are **untrusted**. Always review and verify the results.`);\n }\n\n return sections.join('\\n');\n}\n"],"mappings":";;;;;;;AAQA,MAAM,oBAAoB;AAa1B,SAAgB,kBAAkB,QAAgB,UAA+B,CAAC,GAAW;CAC3F,MAAM,SAAS,QAAQ,+BAAe,IAAI,IAAY;CAEtD,MAAM,YAAY,QAAQ,YAAY,kBAAA,CAAmB,WAAW,MAAM,GAAG;CAC7E,MAAM,WAAqB,CAAC;CAE5B,SAAS,KAAK;;;;wEAIwD;CAItE,MAAM,YAAsB,CAAC;CAE7B,IA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