@mastra/code-sdk 1.21.0-alpha.0 → 1.21.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +0 -2
- package/dist/acp/errors.js +0 -2
- package/dist/acp/event-mapper.js +0 -2
- package/dist/acp/index.js +0 -2
- package/dist/acp/runtime.js +0 -2
- package/dist/acp/server.js +0 -2
- package/dist/acp/skills.js +0 -2
- package/dist/agent-connections/messaging-processor.js +0 -2
- package/dist/agent-connections/ownership.js +0 -2
- package/dist/agent-connections/registry.js +0 -2
- package/dist/agent-connections/session-advertisement.js +0 -2
- package/dist/agent-connections/signal-provider.js +0 -2
- package/dist/agent-connections/state-processor.js +0 -2
- package/dist/agent-connections/thread-state.js +0 -2
- package/dist/agent-connections/tools.js +0 -2
- package/dist/agent-connections/types.js +0 -2
- package/dist/agent-connections/untrusted-text.js +0 -2
- package/dist/agents/background-completion-events.js +0 -2
- package/dist/agents/background-completion.js +0 -2
- package/dist/agents/context-audit.js +0 -2
- package/dist/agents/credential-resolver.js +0 -2
- package/dist/agents/custom-provider-source.js +0 -2
- package/dist/agents/fastembed-subprocess.d.ts +21 -0
- package/dist/agents/fastembed-subprocess.js +88 -8
- package/dist/agents/instructions.js +0 -2
- package/dist/agents/mastracode-gateway.d.ts +3 -1
- package/dist/agents/mastracode-gateway.js +29 -6
- package/dist/agents/memory.js +0 -2
- package/dist/agents/model.js +15 -8
- package/dist/agents/modes/build.js +0 -2
- package/dist/agents/modes/explore.js +0 -2
- package/dist/agents/modes/plan.js +0 -2
- package/dist/agents/prompts/agent-instructions.js +0 -2
- package/dist/agents/prompts/build.js +0 -2
- package/dist/agents/prompts/fast.js +0 -2
- package/dist/agents/prompts/index.js +0 -2
- package/dist/agents/prompts/model.js +0 -2
- package/dist/agents/prompts/plan.js +0 -2
- package/dist/agents/prompts/tool-guidance.js +0 -2
- package/dist/agents/sandbox-filesystem.js +0 -2
- package/dist/agents/subagents/execute.js +0 -2
- package/dist/agents/subagents/explore.js +0 -2
- package/dist/agents/subagents/index.js +0 -2
- package/dist/agents/subagents/plan.js +0 -2
- package/dist/agents/thread-caveman-state.js +0 -2
- package/dist/agents/tool-availability.js +0 -2
- package/dist/agents/tools.d.ts +6 -6
- package/dist/agents/tools.js +0 -2
- package/dist/agents/workflow-builder-agent.js +0 -2
- package/dist/agents/workspace.js +1 -3
- package/dist/analytics.js +0 -2
- package/dist/auth/account-rotation-processor.js +3 -5
- package/dist/auth/account-routing-context.js +0 -2
- package/dist/auth/authorization-input.js +0 -2
- package/dist/auth/device-code.js +0 -2
- package/dist/auth/pkce.js +0 -2
- package/dist/auth/provider-auth-error.js +0 -2
- package/dist/auth/providers/anthropic.js +0 -2
- package/dist/auth/providers/github-copilot.js +0 -2
- package/dist/auth/providers/kimi-coding.js +0 -2
- package/dist/auth/providers/openai-codex.js +0 -2
- package/dist/auth/providers/xai.js +0 -2
- package/dist/auth/storage.js +0 -2
- package/dist/clipboard/index.js +0 -2
- package/dist/constants.js +0 -2
- package/dist/error-classification.js +0 -2
- package/dist/evals/context-builder.js +0 -2
- package/dist/evals/scorers/classify-command.js +0 -2
- package/dist/evals/scorers/efficiency.js +0 -2
- package/dist/evals/scorers/extract-tools.js +0 -2
- package/dist/evals/scorers/outcome.js +0 -2
- package/dist/experimental-agent.js +3 -4
- package/dist/factory/client.js +0 -2
- package/dist/factory/remote-controller.js +0 -2
- package/dist/factory/remote-session.js +0 -2
- package/dist/goal-manager.js +0 -2
- package/dist/goal-signal.js +0 -2
- package/dist/headless/cli.js +5 -2
- package/dist/headless/flags.js +0 -2
- package/dist/headless/format.js +0 -2
- package/dist/headless/policy.js +0 -2
- package/dist/headless/run-mc.js +7 -4
- package/dist/headless/types.js +0 -2
- package/dist/hooks/config.js +0 -2
- package/dist/hooks/executor.js +0 -2
- package/dist/hooks/manager.js +0 -2
- package/dist/hooks/types.js +0 -2
- package/dist/index.js +12 -7
- package/dist/ipc/ipc-reporter.js +0 -2
- package/dist/knowledge-inspector.js +0 -2
- package/dist/knowledge-scope-id.js +0 -2
- package/dist/knowledge-scope.js +0 -2
- package/dist/lsp/client.js +0 -2
- package/dist/lsp/language.js +0 -2
- package/dist/lsp/manager.js +0 -2
- package/dist/lsp/server.js +0 -2
- package/dist/lsp/workspace.js +0 -2
- package/dist/mcp/config.js +0 -2
- package/dist/mcp/manager.js +0 -2
- package/dist/mcp/state.js +0 -2
- package/dist/onboarding/custom-packs.js +0 -2
- package/dist/onboarding/custom-providers.js +0 -2
- package/dist/onboarding/om-settings.js +0 -2
- package/dist/onboarding/pack-activation.js +0 -2
- package/dist/onboarding/packs.js +0 -2
- package/dist/onboarding/settings.js +0 -2
- package/dist/permissions.js +0 -2
- package/dist/platform/index.js +0 -2
- package/dist/plugin.js +0 -2
- package/dist/plugins/dependencies.js +0 -2
- package/dist/plugins/install.js +0 -2
- package/dist/plugins/loader.js +0 -2
- package/dist/plugins/manager.js +0 -2
- package/dist/plugins/manifest.js +0 -2
- package/dist/plugins/package-link.js +0 -2
- package/dist/plugins/paths.js +0 -2
- package/dist/plugins/registry.js +0 -2
- package/dist/plugins/scaffold.js +0 -2
- package/dist/plugins/signal-lane.js +0 -2
- package/dist/process-memory-diagnostics.js +0 -2
- package/dist/processors/plan-rejection-abort.js +0 -2
- package/dist/providers/amazon-bedrock-gateway.js +0 -2
- package/dist/providers/amazon-bedrock.js +0 -2
- package/dist/providers/anthropic-prompt-cache.js +0 -2
- package/dist/providers/anthropic-thinking.js +0 -2
- package/dist/providers/claude-max.js +0 -2
- package/dist/providers/github-copilot-gateway.js +0 -2
- package/dist/providers/github-copilot.js +0 -2
- package/dist/providers/google-thinking.js +0 -2
- package/dist/providers/google-vertex-gateway.js +0 -2
- package/dist/providers/google-vertex.js +0 -2
- package/dist/providers/kimi-coding.js +0 -2
- package/dist/providers/model-ids.d.ts +22 -0
- package/dist/providers/model-ids.js +55 -3
- package/dist/providers/openai-codex.d.ts +5 -1
- package/dist/providers/openai-codex.js +7 -6
- package/dist/providers/provider-thinking.js +0 -2
- package/dist/providers/thinking-request.js +0 -2
- package/dist/providers/xai.js +0 -2
- package/dist/schedules/interval.js +0 -2
- package/dist/schedules/prompt.js +0 -2
- package/dist/schedules/run-script.js +0 -2
- package/dist/schedules/scheduler.js +0 -2
- package/dist/schedules/tools.js +0 -2
- package/dist/schema.js +0 -2
- package/dist/theme-palette.js +0 -2
- package/dist/thinking-catalog.d.ts +2 -2
- package/dist/thinking-catalog.js +5 -4
- package/dist/thinking.js +0 -2
- package/dist/tool-names.js +0 -2
- package/dist/tools/index.d.ts +1 -0
- package/dist/tools/index.js +2 -1
- package/dist/tools/request-sandbox-access.js +0 -2
- package/dist/tools/submit-plan.d.ts +28 -0
- package/dist/tools/submit-plan.js +104 -0
- 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.d.ts +19 -1
- package/dist/utils/plans.js +34 -19
- 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":"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,wBAAwB,GAAG,CAAC;AACxD;AAEA,eAAsB,6BAA6B,KAA8C;CAW/F,OAAO,wBAAwB,KAVf,IAAI,aAChB,MAAM,6BAA6B;EACjC,YAAY,IAAI;EAChB,kBAAkB,MAAM,QAAQ,IAAI,OAAO,gBAAgB,IAAI,IAAI,MAAM,mBAAmB,KAAA;EAC5F,WAAW,IAAI,OAAO;EACtB,mBAAmB,IAAI,OAAO,sBAAsB;EACpD,SAAS,OAAO,IAAI,OAAO,YAAY,WAAW,IAAI,MAAM,UAAU,K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AAI;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,IAAI,CAAC,OAAO,IAAI,SAAS,IAAI,GAC3B,UAAU,KAAK;IACf,SAAS,KAAK;;;;+BAIa,SAAS,WAAW,YAAY;CAG7D,IAAI,CAAC,OAAO,IAAI,SAAS,cAAc,GACrC,UAAU,KAAK;IACf,SAAS,eAAe;;;;;kCAKM;CAGhC,IAAI,CAAC,OAAO,IAAI,SAAS,UAAU,GACjC,UAAU,KAAK;IACf,SAAS,WAAW;;;;;uEAK+C;CAGrE,IAAI,CAAC,OAAO,IAAI,SAAS,eAAe,GACtC,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;IACH,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAyC;IAEjF,wGAAwG;IACxG,OAAO,CAAC,MAAM,CAAC,SAAS;IAkBxB;;;;;;;;;OASG;YACW,eAAe;YAqFf,iBAAiB;IAoD/B,OAAO,CAAC,aAAa;IAgBf,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAM3C;IAEK,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,QAAQ,CAAC,CA6C1C;IAIK,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAE1B;IAEK,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAE7B;IAEK,OAAO,IAAI,OAAO,CAAC,OAAO,CAAC,CAGhC;IAED,OAAO,IAAI,cAAc,CAQxB;IAED,eAAe,IAAI,MAAM,CAExB;CACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sandbox-filesystem.js","names":["posixPath"],"sources":["../../src/agents/sandbox-filesystem.ts"],"sourcesContent":["/**\n * SandboxFilesystem\n *\n * A `WorkspaceFilesystem` that stores files inside a remote `MastraSandbox`\n * (e.g. a Railway VM) rather than on the server host. File operations are\n * implemented by shelling out through the sandbox's `executeCommand`, so the\n * agent's file tools and command tools share one VM and one view of the repo.\n * When the sandbox exposes its own `filesystem`, file operations use it\n * instead, which takes one round trip rather than several commands; grep and\n * walks still run as shell commands.\n *\n * Paths are workspace-relative (`/src/foo.ts`) and resolve under the sandbox\n * working directory (`basePath`). A traversal guard rejects any path that\n * escapes the workdir, mirroring `LocalFilesystem`'s contained mode.\n *\n * Reads/writes use base64 over the wire so binary content survives the shell.\n */\n\nimport { posix as posixPath } from 'node:path';\nimport type {\n CopyOptions,\n FileContent,\n FileEntry,\n FileStat,\n FilesystemGrepMatch,\n FilesystemGrepOptions,\n FilesystemGrepResult,\n FilesystemInfo,\n ListOptions,\n ProviderStatus,\n ReadOptions,\n RemoveOptions,\n WalkEntry,\n WalkOptions,\n WorkspaceFilesystem,\n WriteOptions,\n} from '@mastra/core/workspace';\nimport {\n DirectoryNotFoundError,\n FileExistsError,\n FileNotFoundError,\n getMimeType,\n IsDirectoryError,\n LocalFilesystem,\n NotDirectoryError,\n UnsupportedGrepPatternError,\n} from '@mastra/core/workspace';\n\n/**\n * Sentinel exit codes used by guard clauses that run before the real command,\n * so shell failures can be mapped to typed filesystem errors.\n */\nconst EXIT_NOT_FOUND = 20;\nconst EXIT_IS_DIRECTORY = 21;\nconst EXIT_EXISTS = 22;\nconst EXIT_NOT_DIRECTORY = 23;\n\n/** Minimal command result shape we depend on. */\nexport interface SandboxCommandResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\n/** Minimal sandbox surface the filesystem needs. */\nexport interface SandboxExec {\n readonly id: string;\n /**\n * The sandbox's own file API, when it has one (`WorkspaceSandbox.filesystem`).\n * File operations go through it instead of shell commands.\n */\n readonly filesystem?: WorkspaceFilesystem;\n executeCommand(\n command: string,\n args?: string[],\n options?: { timeout?: number; maxRetainedBytes?: number },\n ): Promise<SandboxCommandResult>;\n}\n\nexport interface SandboxFilesystemOptions {\n /** Live sandbox to run commands in. */\n sandbox: SandboxExec;\n /**\n * Absolute path inside the sandbox that is the workspace root — or a lazy\n * resolver for it. The resolver form exists for sandboxes whose workspace\n * root is only knowable once the VM is running (e.g. `$HOME/<repo>` under\n * a provider-chosen home dir): it is awaited on the first file operation\n * (which itself may lazily start the VM) and the result is memoized.\n */\n workdir: string | (() => Promise<string> | string);\n /** Optional stable id; defaults to a sandbox-derived id. */\n id?: string;\n /**\n * Check that symlinks don't lead outside the workdir when using the\n * sandbox's native filesystem. Off by default: native file APIs follow\n * symlinks, and inside a sandbox the agent can read anything with a command\n * anyway. Turn it on when files are served to someone other than the agent.\n *\n * Each path is checked once per instance, so keep such instances\n * short-lived. Without a native filesystem the shell path always checks.\n */\n verifySymlinks?: boolean;\n /**\n * Additional file extensions to treat as text, extending (not replacing) the\n * built-in set. Affects which files tools like `grep` will search. Values are\n * normalized like `LocalFilesystem`'s option, so `'sas'`, `'.sas'` and\n * `'.SAS'` are equivalent.\n */\n textExtensions?: string[];\n}\n\ntype ContainmentCheck = 'target' | 'dest' | 'parent';\n\n/** Default per-command deadline so a hung sandbox can't block file tools forever. */\nconst COMMAND_TIMEOUT_MS = 30_000;\n\n/**\n * Explain why a native grep command failed so callers can tell a timeout or\n * broken toolchain apart from a pattern the engine cannot express.\n */\nfunction describeGrepFailure(result: SandboxCommandResult): string {\n if (result.exitCode === 124) return `timed out after ${COMMAND_TIMEOUT_MS / 1000}s`;\n const stderrLine = result.stderr\n .split('\\n')\n .map(line => line.trim())\n .find(Boolean);\n const detail = stderrLine ? `: ${stderrLine.length > 200 ? `${stderrLine.slice(0, 200)}…` : stderrLine}` : '';\n return `exit code ${result.exitCode}${detail}`;\n}\n\n/** Single-quote a string for safe POSIX shell interpolation. */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\ninterface SearchTools {\n rg: boolean;\n gnuGrep: boolean;\n git: boolean;\n /** `grep -P` works, and so does `git grep -P` when git is present. */\n pcre: boolean;\n}\n\n/** One command that reports which search tools the sandbox has, one name per line. */\nconst SEARCH_TOOLS_PROBE =\n 'command -v rg >/dev/null 2>&1 && echo rg; ' +\n \"grep --version 2>/dev/null | head -n 1 | grep -q 'GNU grep' && echo gnu-grep; \" +\n \"printf 'a1\\\\n' | grep -qP '\\\\d(?=)' 2>/dev/null && echo grep-pcre; \" +\n 'if command -v git >/dev/null 2>&1; then echo git; ' +\n // git can be built without PCRE; check it on a throwaway repository.\n 'd=$(mktemp -d 2>/dev/null) && { ' +\n \"(cd \\\"$d\\\" && git init -q && printf 'a1\\\\n' >f && git grep -q --untracked -P -e '\\\\d(?=)') >/dev/null 2>&1 && echo git-pcre; \" +\n 'rm -rf \"$d\"; }; fi; true';\n\nfunction isInsideNodeModules(path: string): boolean {\n return path.split('/').includes('node_modules');\n}\n\n/** Lines a grep engine printed for one file: matches plus surrounding context. */\ninterface GrepFileLines {\n matches: FilesystemGrepMatch[];\n linesByNumber: Map<number, string>;\n}\n\nfunction fileLines(files: Map<string, GrepFileLines>, filePath: string): GrepFileLines {\n let state = files.get(filePath);\n if (!state) {\n state = { matches: [], linesByNumber: new Map() };\n files.set(filePath, state);\n }\n return state;\n}\n\n/** Turn per-file lines into results relative to `abs`, attaching before/after context. */\nfunction toGrepResults(files: Map<string, GrepFileLines>, abs: string, contextLines: number): FilesystemGrepResult[] {\n const results: FilesystemGrepResult[] = [];\n for (const [filePath, state] of files) {\n if (state.matches.length === 0) continue;\n const rel = posixPath.relative(abs, filePath) || posixPath.basename(filePath);\n const matches = state.matches.map(match => {\n if (contextLines <= 0) return match;\n const before: string[] = [];\n for (let n = match.line - 1; n >= Math.max(1, match.line - contextLines); n--) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n before.unshift(text);\n }\n const after: string[] = [];\n for (let n = match.line + 1; n <= match.line + contextLines; n++) {\n const text = state.linesByNumber.get(n);\n if (text === undefined) break;\n after.push(text);\n }\n return { ...match, before, after };\n });\n results.push({ path: rel, matches });\n }\n return results;\n}\n\nfunction isFileContentString(content: FileContent): content is string {\n return typeof content === 'string';\n}\n\nfunction toBuffer(content: FileContent): Buffer {\n if (isFileContentString(content)) return Buffer.from(content, 'utf8');\n return Buffer.from(content);\n}\n\nexport class SandboxFilesystem implements WorkspaceFilesystem {\n readonly id: string;\n readonly name = 'SandboxFilesystem';\n readonly provider = 'sandbox';\n status: ProviderStatus = 'ready';\n\n private readonly sandbox: SandboxExec;\n private readonly workdirSource: string | (() => Promise<string> | string);\n private resolvedBase?: string;\n private resolvingBase?: Promise<string>;\n private readonly verifySymlinks: boolean;\n /**\n * Classifies file names as text: the built-in extensions plus\n * `textExtensions`, normalized exactly as `LocalFilesystem` does. Only its\n * `isTextFile` is ever called; it never touches a file.\n */\n private readonly textClassifier: LocalFilesystem;\n /** `check:absolutePath` keys that passed while the entry existed. */\n private readonly verified = new Set<string>();\n\n constructor(options: SandboxFilesystemOptions) {\n this.sandbox = options.sandbox;\n this.workdirSource = options.workdir;\n this.verifySymlinks = options.verifySymlinks ?? false;\n this.textClassifier = new LocalFilesystem({ basePath: '/', textExtensions: options.textExtensions });\n if (typeof options.workdir === 'string') this.resolvedBase = options.workdir;\n // Include the workdir when known: one sandbox can back several\n // filesystems rooted at different checkouts, and each needs a distinct\n // id. Lazy-workdir callers pass an explicit id.\n this.id =\n options.id ??\n (typeof options.workdir === 'string'\n ? `sandbox-fs:${options.sandbox.id}:${options.workdir}`\n : `sandbox-fs:${options.sandbox.id}`);\n }\n\n /** The resolved workspace root; empty until a lazy workdir first resolves. */\n get basePath(): string {\n return this.resolvedBase ?? '';\n }\n\n /**\n * The sandbox directory shell commands default to: the same root file paths\n * resolve against, so a relative path means the same thing to a shell command\n * and to a file tool. Non-empty whenever the workspace root is known.\n */\n async getCommandCwd(): Promise<string | undefined> {\n return (await this.base()) || undefined;\n }\n\n /**\n * Whether tools like `grep` should treat a file as text: the built-in text\n * extensions plus any `textExtensions` passed to the constructor.\n */\n isTextFile(filename: string): boolean {\n return this.textClassifier.isTextFile(filename);\n }\n\n /** Await (and memoize) the workspace root, resolving a lazy workdir once. */\n private async base(): Promise<string> {\n if (this.resolvedBase) return this.resolvedBase;\n const source = this.workdirSource;\n if (typeof source === 'string') return (this.resolvedBase = source);\n this.resolvingBase ??= Promise.resolve()\n .then(source)\n .then(resolved => {\n if (!resolved) throw new Error('Sandbox workspace root resolution returned an empty path');\n return (this.resolvedBase = resolved);\n })\n .finally(() => {\n this.resolvingBase = undefined;\n });\n return this.resolvingBase;\n }\n\n // ── Path handling ──────────────────────────────────────────────────────\n\n /**\n * Resolve a workspace path to an absolute path inside the sandbox, enforcing\n * that it stays within the workdir. Awaits the workspace root first, which\n * for a lazy workdir may start the VM.\n */\n private async resolveAsync(inputPath: string): Promise<string> {\n return this.resolveAgainst(await this.base(), inputPath);\n }\n\n /**\n * Resolve a workspace path against a known base, enforcing that it stays\n * within the workdir.\n *\n * Accepts both workspace-relative paths (`src/foo.ts`, `/src/foo.ts`) and\n * absolute sandbox paths that already live under the workdir — the agent's\n * prompt advertises the workdir as its working directory, so tools are\n * routinely called with fully-qualified paths like `<workdir>/src/foo.ts`.\n */\n private resolveAgainst(basePath: string, inputPath: string): string {\n const base = posixPath.normalize(basePath);\n const normalizedInput = posixPath.normalize(inputPath);\n const rel =\n normalizedInput === base\n ? ''\n : normalizedInput.startsWith(`${base}/`)\n ? normalizedInput.slice(base.length + 1)\n : inputPath.startsWith('/')\n ? inputPath.slice(1)\n : inputPath;\n const resolved = posixPath.normalize(posixPath.join(base, rel));\n if (resolved !== base && !resolved.startsWith(`${base}/`)) {\n throw new Error(`Path escapes workspace root: ${inputPath}`);\n }\n return resolved;\n }\n\n /**\n * A miss on an absolute path outside the workdir (e.g. `/tmp/x/a.ts`) that\n * does exist at that real sandbox path: the agent meant the sandbox path,\n * but it was remapped under the workdir. Explain that instead of a bare\n * not-found. Undefined when the path is inside the workdir or doesn't exist.\n */\n private async outsideWorkdirNotFound(inputPath: string, abs: string): Promise<FileNotFoundError | undefined> {\n const base = posixPath.normalize(this.basePath);\n const normalized = posixPath.normalize(inputPath);\n if (!inputPath.startsWith('/') || normalized === base || normalized.startsWith(`${base}/`)) return undefined;\n const probe = await this.exec(`test -e ${shellQuote(normalized)}`).catch(() => undefined);\n if (probe?.exitCode !== 0) return undefined;\n const error = new FileNotFoundError(inputPath);\n error.message = `File not found: ${inputPath} (resolved to ${abs}). File tools only reach files under ${base}; absolute paths are workspace-relative. Put scratch worktrees under ${base}/.worktrees/.`;\n return error;\n }\n\n resolveAbsolutePath(inputPath: string): string | undefined {\n // Sync interface: a lazy workdir that has not resolved yet has no\n // absolute form to offer.\n if (!this.resolvedBase) return undefined;\n return this.resolveAgainst(this.resolvedBase, inputPath);\n }\n\n // ── Command helper ─────────────────────────────────────────────────────\n\n private async exec(script: string): Promise<SandboxCommandResult> {\n // File reads come back as base64 on stdout and listings/grep are parsed\n // line by line, so dropping the oldest output would corrupt results.\n return this.sandbox.executeCommand('sh', ['-c', script], {\n timeout: COMMAND_TIMEOUT_MS,\n maxRetainedBytes: Infinity,\n });\n }\n\n /**\n * Lexical guard catches `..` traversal, but a symlink inside the workdir can\n * still point outside it. After resolving a path that refers to an existing\n * entry, verify its realpath is still contained in the workdir.\n *\n * Canonicalization tries `realpath`, then `readlink -f` (GNU/busybox), then\n * `cd && pwd -P` for directories — covering GNU hosts, macOS/BSD, and\n * busybox. If the path exists but cannot be canonicalized we fail CLOSED:\n * returning without a check would let a symlink bypass containment.\n */\n private async assertContainedRealpath(abs: string, inputPath: string): Promise<boolean> {\n const result = await this.exec(\n [\n `p=${shellQuote(abs)}`,\n `if [ ! -e \"$p\" ] && [ ! -L \"$p\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n // The workdir itself may contain symlinked components (/tmp on macOS),\n // so canonicalize it as the comparison root.\n `root=$(cd ${shellQuote(this.basePath)} 2>/dev/null && pwd -P)`,\n `[ -n \"$root\" ] || exit 1`,\n `rp=$(realpath \"$p\" 2>/dev/null) || rp=$(readlink -f \"$p\" 2>/dev/null) || { [ -d \"$p\" ] && rp=$(cd \"$p\" 2>/dev/null && pwd -P); }`,\n `[ -n \"$rp\" ] || exit 1`,\n `printf '%s\\\\n%s' \"$root\" \"$rp\"`,\n ].join('\\n'),\n );\n // Path doesn't exist yet: nothing to canonicalize (writes to a fresh leaf\n // are covered by assertContainedDest checking the parent directory).\n if (result.exitCode === EXIT_NOT_FOUND) return false;\n const [root, real] = result.stdout.split('\\n').map(s => s.trim());\n if (result.exitCode !== 0 || !root || !real) {\n throw new Error(`Unable to verify path stays within workspace root: ${inputPath}`);\n }\n if (real !== root && !real.startsWith(`${root}/`)) {\n throw new Error(`Path escapes workspace root (symlink): ${inputPath}`);\n }\n return true;\n }\n\n /**\n * Guard for write destinations. The lexical guard catches `..`, but a symlink\n * inside the workdir can redirect a write outside it. For an existing target\n * we check its realpath; for a not-yet-existing target we check the realpath\n * of its nearest existing ancestor directory, since a symlinked parent is the\n * escape vector (e.g. `link -> /etc` then writing `link/passwd`).\n */\n private async assertContainedDest(abs: string, inputPath: string): Promise<boolean> {\n // First check the target itself (covers overwriting an existing symlink).\n const exists = await this.assertContainedRealpath(abs, inputPath);\n // Then check the parent directory's realpath; readlink -f resolves the\n // nearest existing ancestor when the leaf doesn't exist yet.\n const parent = posixPath.dirname(abs);\n if (parent && parent !== abs) {\n await this.assertContainedRealpath(parent, inputPath);\n }\n return exists;\n }\n\n /**\n * Before a native filesystem call, run the containment check the shell path\n * runs for that operation, when `verifySymlinks` is on. A pass is remembered\n * only for an entry that exists: a missing path may later appear as a\n * symlink that leads outside the workdir.\n */\n private async verifyNative(check: ContainmentCheck, abs: string, inputPath: string): Promise<void> {\n if (!this.verifySymlinks) return;\n const key = `${check}:${abs}`;\n if (this.verified.has(key)) return;\n const existed =\n check === 'dest'\n ? await this.assertContainedDest(abs, inputPath)\n : await this.assertContainedRealpath(check === 'parent' ? posixPath.dirname(abs) : abs, inputPath);\n if (existed) this.verified.add(key);\n }\n\n private async execOk(script: string, context: string): Promise<SandboxCommandResult> {\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new Error(`${context} failed (exit ${result.exitCode}): ${result.stderr.trim() || result.stdout.trim()}`);\n }\n return result;\n }\n\n // ── File operations ────────────────────────────────────────────────────\n\n async readFile(path: string, options?: ReadOptions): Promise<string | Buffer> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n try {\n return await native.readFile(abs, options);\n } catch (error) {\n const isNotFound = error instanceof FileNotFoundError || (error as { code?: unknown })?.code === 'ENOENT';\n throw (isNotFound && (await this.outsideWorkdirNotFound(path, abs))) || error;\n }\n }\n await this.assertContainedRealpath(abs, path);\n // Guard clauses first: redirecting from a directory \"succeeds\" with empty\n // output on some shells, so classify before reading.\n const result = await this.exec(\n `if [ -d ${shellQuote(abs)} ]; then exit ${EXIT_IS_DIRECTORY}; elif [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; base64 < ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_IS_DIRECTORY) throw new IsDirectoryError(path);\n if (result.exitCode === EXIT_NOT_FOUND) {\n throw (await this.outsideWorkdirNotFound(path, abs)) ?? new FileNotFoundError(path);\n }\n if (result.exitCode !== 0) {\n throw new Error(`readFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const buffer = Buffer.from(result.stdout.replace(/\\s/g, ''), 'base64');\n if (options?.encoding) {\n return buffer.toString(options.encoding);\n }\n return buffer;\n }\n\n async writeFile(path: string, content: FileContent, options?: WriteOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.writeFile(abs, content, options);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n const dir = posixPath.dirname(abs);\n const mkdir = options?.recursive === false ? '' : `mkdir -p ${shellQuote(dir)} && `;\n if (options?.overwrite === false) {\n // `set -C` (noclobber) makes the redirect itself the exclusivity check —\n // no exists() pre-check that could race with a concurrent writer.\n const result = await this.exec(\n `${mkdir}{ (set -C; printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}) 2>/dev/null || { [ -e ${shellQuote(abs)} ] && exit ${EXIT_EXISTS} || exit 1; }; }`,\n );\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(path);\n if (result.exitCode !== 0) {\n throw new Error(`writeFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n await this.execOk(`${mkdir}printf %s ${shellQuote(b64)} | base64 -d > ${shellQuote(abs)}`, `writeFile ${path}`);\n }\n\n async appendFile(path: string, content: FileContent): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.appendFile(abs, content);\n }\n await this.assertContainedDest(abs, path);\n const b64 = toBuffer(content).toString('base64');\n await this.execOk(\n `mkdir -p ${shellQuote(posixPath.dirname(abs))} && printf %s ${shellQuote(b64)} | base64 -d >> ${shellQuote(abs)}`,\n `appendFile ${path}`,\n );\n }\n\n async deleteFile(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.deleteFile(abs, options);\n }\n // Contain the parent's realpath: deleting `link/file` where `link` points\n // outside the workdir must fail, while deleting a symlink entry itself\n // (which lives inside the workdir) stays allowed.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.force) {\n // `rm -f` already succeeds for a missing file, but still fails for\n // directories and permission errors — surface those.\n await this.execOk(`rm -f ${shellQuote(abs)}`, `deleteFile ${path}`);\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(abs)} ]; then exit ${EXIT_NOT_FOUND}; fi; rm ${shellQuote(abs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(path);\n if (result.exitCode !== 0) {\n throw new Error(`deleteFile ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async copyFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.copyFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n const recursive = options?.recursive ? '-r ' : '';\n if (options?.overwrite === false) {\n // Atomic no-clobber: directories claim the destination with an exclusive\n // mkdir; files copy to a temp name then hardlink into place (link(2)\n // fails if the destination exists). No racy exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `if [ -d \"$src\" ]; then`,\n ` mkdir \"$dest\" 2>/dev/null || exit ${EXIT_EXISTS}`,\n ` cp -R \"$src\"/. \"$dest\"/`,\n `else`,\n ` tmp=\"$dest.__cptmp$$\"`,\n ` cp \"$src\" \"$tmp\" || exit 1`,\n ` ln \"$tmp\" \"$dest\" 2>/dev/null || { rm -f \"$tmp\"; [ -e \"$dest\" ] && exit ${EXIT_EXISTS} || exit 1; }`,\n ` rm -f \"$tmp\"`,\n `fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && cp ${recursive}${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`copyFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n async moveFile(src: string, dest: string, options?: CopyOptions): Promise<void> {\n const srcAbs = await this.resolveAsync(src);\n const destAbs = await this.resolveAsync(dest);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', srcAbs, src);\n await this.verifyNative('dest', destAbs, dest);\n return native.moveFile(srcAbs, destAbs, options);\n }\n await this.assertContainedRealpath(srcAbs, src);\n await this.assertContainedDest(destAbs, dest);\n if (options?.overwrite === false) {\n // `mv -n` exits 0 even when it skips, so detect a skipped move by the\n // source surviving. The no-clobber rename itself is atomic; no racy\n // exists() pre-check.\n const result = await this.exec(\n [\n `src=${shellQuote(srcAbs)}`,\n `dest=${shellQuote(destAbs)}`,\n `if [ ! -e \"$src\" ] && [ ! -L \"$src\" ]; then exit ${EXIT_NOT_FOUND}; fi`,\n `mkdir -p ${shellQuote(posixPath.dirname(destAbs))} || exit 1`,\n `mv -n \"$src\" \"$dest\" 2>/dev/null || exit 1`,\n `if [ -e \"$src\" ] || [ -L \"$src\" ]; then exit ${EXIT_EXISTS}; fi`,\n ].join('\\n'),\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode === EXIT_EXISTS) throw new FileExistsError(dest);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n return;\n }\n const result = await this.exec(\n `if [ ! -e ${shellQuote(srcAbs)} ]; then exit ${EXIT_NOT_FOUND}; fi; mkdir -p ${shellQuote(posixPath.dirname(destAbs))} && mv ${shellQuote(srcAbs)} ${shellQuote(destAbs)}`,\n );\n if (result.exitCode === EXIT_NOT_FOUND) throw new FileNotFoundError(src);\n if (result.exitCode !== 0) {\n throw new Error(`moveFile ${src} -> ${dest} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n }\n\n // ── Directory operations ───────────────────────────────────────────────\n\n async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('dest', abs, path);\n return native.mkdir(abs, options);\n }\n await this.assertContainedDest(abs, path);\n const flag = options?.recursive === false ? '' : '-p ';\n await this.execOk(`mkdir ${flag}${shellQuote(abs)}`, `mkdir ${path}`);\n }\n\n async rmdir(path: string, options?: RemoveOptions): Promise<void> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('parent', abs, path);\n return native.rmdir(abs, options);\n }\n // Same parent containment as deleteFile — `rm -r` through a symlinked\n // parent would otherwise delete outside the workspace.\n await this.assertContainedRealpath(posixPath.dirname(abs), path);\n if (options?.recursive) {\n const force = options?.force ? '-f ' : '';\n await this.execOk(`rm -r ${force}${shellQuote(abs)}`, `rmdir ${path}`);\n return;\n }\n const result = await this.exec(`rmdir ${shellQuote(abs)}`);\n if (result.exitCode !== 0 && !options?.force) {\n throw new Error(`Directory not empty or not found: ${path}`);\n }\n }\n\n async readdir(path: string, options?: ListOptions): Promise<FileEntry[]> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n return native.readdir(abs, options);\n }\n await this.assertContainedRealpath(abs, path);\n if (options?.recursive) {\n // Recursive listing emitting \"type\\tpath\". `find -printf` is GNU-only\n // (fails on macOS/BSD hosts backing a local sandbox), so classify each\n // entry with a portable shell loop instead.\n const result = await this.exec(\n `test -d ${shellQuote(abs)} && find ${shellQuote(abs)} -mindepth 1 ${options.maxDepth ? `-maxdepth ${Number(options.maxDepth)} ` : ''}2>/dev/null | while IFS= read -r f; do if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseFindOutput(result.stdout, abs, options);\n }\n // Non-recursive: list with name + type via a portable loop. Use printf,\n // not echo — bash-as-/bin/sh (macOS local sandboxes) does not expand \\t\n // in echo arguments.\n const result = await this.exec(\n `cd ${shellQuote(abs)} 2>/dev/null && for f in * .[!.]*; do [ -e \"$f\" ] || continue; if [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`,\n );\n if (result.exitCode !== 0) throw new Error(`Directory not found: ${path}`);\n return this.parseListOutput(result.stdout, options);\n }\n\n private parseListOutput(stdout: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const name = line.slice(tab + 1);\n if (!name || name === '.' || name === '..') continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private parseFindOutput(stdout: string, base: string, options?: ListOptions): FileEntry[] {\n const entries: FileEntry[] = [];\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const type = line.slice(0, tab) === 'd' ? 'directory' : 'file';\n const fullPath = line.slice(tab + 1);\n const name = posixPath.relative(base, fullPath);\n if (!name) continue;\n if (type === 'file' && !this.matchesExtension(name, options?.extension)) continue;\n entries.push({ name, type });\n }\n return entries;\n }\n\n private matchesExtension(name: string, extension?: string | string[]): boolean {\n if (!extension) return true;\n const exts = Array.isArray(extension) ? extension : [extension];\n return exts.some(ext => name.endsWith(ext));\n }\n\n // ── Native walk / grep capabilities ────────────────────────────────────\n\n /**\n * Walk the tree in a single sandbox command instead of one readdir round\n * trip per directory. Uses `find` with a portable classification loop\n * (`find -printf` is GNU-only and fails on macOS/BSD hosts). `find` does\n * not follow symlinked directories by default, matching the host-side\n * walker's no-recursion-into-symlinks behavior.\n */\n async walk(path: string, options?: WalkOptions): Promise<WalkEntry[]> {\n const abs = await this.resolveAsync(path);\n await this.assertContainedRealpath(abs, path);\n const maxDepth =\n options?.maxDepth !== undefined && Number.isFinite(options.maxDepth)\n ? `-maxdepth ${Math.max(0, Math.floor(options.maxDepth))} `\n : '';\n // Prune hidden entries in-sandbox when not requested, so a huge hidden\n // tree (e.g. `.git`) doesn't inflate the response. `.gitignore` files\n // still come back when the caller applies them.\n const keepGitignore = options?.includeGitignoreFiles ? `! \\\\( -type f -name .gitignore \\\\) ` : '';\n const hiddenPrune = options?.includeHidden ? '' : `\\\\( -name '.*' ${keepGitignore}\\\\) -prune -o `;\n // Skip directories like node_modules entirely instead of listing them\n // only for the caller to filter them out.\n const skipNames = options?.skipDirectoryNames?.filter(Boolean) ?? [];\n const skipPrune = skipNames.length\n ? `\\\\( -type d \\\\( ${skipNames.map(name => `-name ${shellQuote(name)}`).join(' -o ')} \\\\) \\\\) -prune -o `\n : '';\n // Emit \"flag\\tpath[\\ttarget]\" — flag is d/f for regular entries, D/F for\n // symlinks (with the link target as a third field).\n const script =\n `root=${shellQuote(abs)}\\n` +\n `[ -e \"$root\" ] || [ -L \"$root\" ] || exit ${EXIT_NOT_FOUND}\\n` +\n `[ -d \"$root\" ] || exit ${EXIT_NOT_DIRECTORY}\\n` +\n `find \"$root\" -mindepth 1 ${maxDepth}${hiddenPrune}${skipPrune}-print 2>/dev/null | while IFS= read -r f; do ` +\n `if [ -L \"$f\" ]; then if [ -d \"$f\" ]; then t=D; else t=F; fi; printf '%s\\\\t%s\\\\t%s\\\\n' \"$t\" \"$f\" \"$(readlink \"$f\")\"; ` +\n `elif [ -d \"$f\" ]; then printf 'd\\\\t%s\\\\n' \"$f\"; else printf 'f\\\\t%s\\\\n' \"$f\"; fi; done`;\n const result = await this.exec(script);\n if (result.exitCode === EXIT_NOT_FOUND) throw new DirectoryNotFoundError(path);\n if (result.exitCode === EXIT_NOT_DIRECTORY) throw new NotDirectoryError(path);\n if (result.exitCode !== 0) {\n throw new Error(`walk ${path} failed (exit ${result.exitCode}): ${result.stderr.trim()}`);\n }\n const entries: WalkEntry[] = [];\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const tab = line.indexOf('\\t');\n if (tab < 0) continue;\n const flag = line.slice(0, tab);\n const isSymlink = flag === 'D' || flag === 'F';\n let fullPath = line.slice(tab + 1);\n let symlinkTarget: string | undefined;\n if (isSymlink) {\n const tab2 = fullPath.lastIndexOf('\\t');\n if (tab2 >= 0) {\n symlinkTarget = fullPath.slice(tab2 + 1) || undefined;\n fullPath = fullPath.slice(0, tab2);\n }\n }\n const rel = posixPath.relative(abs, fullPath);\n if (!rel || rel.startsWith('..')) continue;\n entries.push({\n name: posixPath.basename(rel),\n type: flag === 'd' || flag === 'D' ? 'directory' : 'file',\n ...(isSymlink ? { isSymlink: true, ...(symlinkTarget ? { symlinkTarget } : {}) } : {}),\n path: rel,\n });\n }\n return entries;\n }\n\n /**\n * Content search executed inside the sandbox in one command, using the best\n * engine the sandbox has: ripgrep, then GNU grep (with git choosing files\n * inside repositories), then POSIX `grep -rnE`. Patterns the grep engines\n * can't express (PCRE-style classes, word boundaries, lookarounds,\n * non-greedy quantifiers) throw {@link UnsupportedGrepPatternError} so\n * callers use their host-side walk.\n *\n * ripgrep and GNU grep apply every `.gitignore` in the tree, relative to the\n * directory that holds it, and skip `node_modules` unless the search path\n * is inside one. Callers still apply their own hidden/glob filtering.\n */\n async grep(options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const abs = await this.resolveAsync(options.path);\n await this.assertContainedRealpath(abs, options.path);\n const tools = await this.searchTools();\n if (tools.rg) return this.grepWithRipgrep(abs, options);\n if (tools.gnuGrep) return this.grepWithGnuGrep(abs, options, tools);\n return this.grepWithPosixGrep(abs, options);\n }\n\n private toolsCheck: Promise<SearchTools> | undefined;\n\n private searchTools(): Promise<SearchTools> {\n const check = (this.toolsCheck ??= this.exec(SEARCH_TOOLS_PROBE).then(result => {\n if (result.exitCode !== 0) throw new Error(`search tool probe exited with ${result.exitCode}`);\n const found = new Set(result.stdout.split('\\n').map(line => line.trim()));\n const git = found.has('git');\n return {\n rg: found.has('rg'),\n gnuGrep: found.has('gnu-grep'),\n git,\n pcre: found.has('grep-pcre') && (!git || found.has('git-pcre')),\n };\n }));\n // Only a successful probe is cached; a failed one (e.g. the sandbox wasn't\n // ready) is retried on the next search instead of pinning the slow path.\n return check.catch(() => {\n if (this.toolsCheck === check) this.toolsCheck = undefined;\n return { rg: false, gnuGrep: false, git: false, pcre: false };\n });\n }\n\n private async grepWithRipgrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const args = [\n // --no-require-git applies .gitignore files outside a git checkout too\n // (e.g. a multi-repo root). A path passed explicitly is searched even\n // when ignored, so targeting `dist/` or `node_modules/x` still works.\n 'rg --json --hidden --no-require-git',\n // .git is filtered host-side too; exclude it here so its object files\n // don't inflate the response.\n `-g ${shellQuote('!.git/**')}`,\n isInsideNodeModules(abs) ? '' : `-g ${shellQuote('!**/node_modules/**')}`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n options.contextLines ? `-C ${Math.max(0, Math.floor(options.contextLines))}` : '',\n `-e ${shellQuote(options.pattern)}`,\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n // rg exits 1 when there are no matches, 2 on any error. A bad pattern\n // produces no output at all, but a per-file error (e.g. an unreadable\n // file) also yields exit 2 while still emitting matches for every other\n // file. Keep those partial results; only treat \"error with no matches\"\n // as an unsupported pattern so the caller falls back to the host walk.\n if (result.exitCode === 1) return [];\n const results = this.parseRipgrepJson(result.stdout, abs, options);\n if (result.exitCode !== 0 && results.length === 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n return results;\n }\n\n private parseRipgrepJson(stdout: string, abs: string, options: FilesystemGrepOptions): FilesystemGrepResult[] {\n const files = new Map<string, GrepFileLines>();\n for (const line of stdout.split('\\n')) {\n if (!line) continue;\n let event: any;\n try {\n event = JSON.parse(line);\n } catch {\n continue;\n }\n if (event.type !== 'match' && event.type !== 'context') continue;\n const filePath: string | undefined = event.data?.path?.text;\n const lineNumber: number | undefined = event.data?.line_number;\n if (!filePath || !lineNumber) continue;\n const state = fileLines(files, filePath);\n const text: string = (event.data?.lines?.text ?? '').replace(/\\r?\\n$/, '');\n state.linesByNumber.set(lineNumber, text);\n if (event.type === 'match') {\n // rg submatch offsets are byte offsets into the line; convert to a\n // UTF-16 (JS string) index for the capability contract.\n const byteStart: number = event.data?.submatches?.[0]?.start ?? 0;\n const column = Buffer.from(text, 'utf8').subarray(0, byteStart).toString('utf8').length;\n state.matches.push({ line: lineNumber, column, text });\n }\n }\n return this.applyTotalCap(toGrepResults(files, abs, options.contextLines ?? 0), options.maxTotalMatches);\n }\n\n /**\n * Patterns whose meaning differs between POSIX ERE and JS RegExp. The grep\n * runs with ERE but match columns are recomputed with JS, so anything that\n * only one side understands (PCRE classes, lookarounds, lazy quantifiers,\n * POSIX bracket classes, GNU word anchors) must fall back to the host walk.\n */\n private static readonly ERE_UNSUPPORTED = /\\\\[dDwWsSbB<>]|\\(\\?|[*+?}]\\?|\\[:[a-z]+:\\]/;\n\n /**\n * Escapes that `grep -P` (PCRE) and JS RegExp (without the `u` flag) both\n * accept but read differently, e.g. `\\A` is \"start of subject\" in PCRE and\n * a literal `A` in JS, plus POSIX bracket classes. PCRE-only syntax that JS\n * rejects (inline flags, possessive quantifiers, atomic groups) already\n * fails the JS compile below.\n */\n private static readonly PCRE_UNSUPPORTED = /\\\\[AzZGKQEhHvVRXNCpPe]|\\[:[a-z]+:\\]/;\n\n /** Reject patterns grep can't run with the same meaning as JS; return the JS regex used for columns. */\n private static grepRegex(options: FilesystemGrepOptions, pcre = false): RegExp {\n if (\n pcre\n ? SandboxFilesystem.PCRE_UNSUPPORTED.test(options.pattern)\n : SandboxFilesystem.ERE_UNSUPPORTED.test(options.pattern)\n ) {\n throw new UnsupportedGrepPatternError(\n options.pattern,\n pcre ? 'grep -P reads this syntax differently from JavaScript' : 'POSIX ERE cannot express this syntax',\n );\n }\n try {\n return new RegExp(options.pattern, options.caseSensitive ? '' : 'i');\n } catch {\n throw new UnsupportedGrepPatternError(options.pattern, 'invalid regular expression');\n }\n }\n\n /**\n * GNU grep without ripgrep. Inside a git checkout, `git grep` picks the\n * files (tracked plus untracked, every `.gitignore` applied) and GNU grep\n * prints them with context. Outside a checkout (e.g. a multi-repo root),\n * each child repository is searched the same way and plain grep covers the\n * remaining files, skipping `node_modules`. `--null` ends each file name\n * with NUL, so match (`N:`) and context (`N-`) lines parse unambiguously.\n * When grep and git support it, patterns run as PCRE (`-P`), so `\\d`,\n * `\\w`, `\\s`, `\\b`, and lookarounds don't need the host walk.\n */\n private async grepWithGnuGrep(\n abs: string,\n options: FilesystemGrepOptions,\n tools: SearchTools,\n ): Promise<FilesystemGrepResult[]> {\n const hasGit = tools.git;\n const mode = tools.pcre ? '-P' : '-E';\n const jsRegex = SandboxFilesystem.grepRegex(options, tools.pcre);\n const contextLines = Math.max(0, Math.floor(options.contextLines ?? 0));\n const grepFlags = [\n `-HnI${mode.slice(1)} --null`,\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n contextLines > 0 ? `-C ${contextLines}` : '',\n ]\n .filter(Boolean)\n .join(' ');\n const skipNodeModules = !isInsideNodeModules(abs);\n const nodeModulesPathspec = skipNodeModules ? ` ${shellQuote(':(exclude,glob)**/node_modules/**')}` : '';\n const pruneNames = skipNodeModules ? '-name .git -o -name node_modules' : '-name .git';\n const script = [\n `pat=${shellQuote(options.pattern)}`,\n `root=${shellQuote(abs)}`,\n // xargs exit codes can't tell \"no match\" from \"bad pattern\"; check first.\n `grep ${mode} -e \"$pat\" </dev/null >/dev/null 2>&1`,\n 'if [ $? -eq 2 ]; then echo \"grep: invalid regular expression\" >&2; exit 2; fi',\n 'tmp=$(mktemp -d) || exit 1',\n `trap 'rm -rf \"$tmp\"' EXIT`,\n `search_files() { xargs -0 -r grep ${grepFlags} -e \"$pat\" -- 2>/dev/null; }`,\n // A line starting with NUL names the directory later paths are relative to.\n 'search_repo() {',\n ` git -C \"$1\" grep -l -z -I --untracked ${options.caseSensitive ? '' : '-i '}${mode} -e \"$pat\" -- .${nodeModulesPathspec} >\"$tmp/files\" 2>/dev/null`,\n ' [ $? -gt 1 ] && return 1',\n ` printf '\\\\0%s\\\\n' \"$1\"`,\n ' (cd \"$1\" && search_files) <\"$tmp/files\"',\n '}',\n ...(hasGit\n ? [\n 'if git -C \"$root\" rev-parse --is-inside-work-tree >/dev/null 2>&1 && ! git -C \"$root\" check-ignore -q . 2>/dev/null; then',\n ' search_repo \"$root\" && exit 0',\n 'fi',\n `find \"$root\" -mindepth 1 -maxdepth 3 \\\\( ${skipNodeModules ? '-name node_modules -prune' : '-false'} \\\\) -o \\\\( -name .git -prune -print \\\\) >\"$tmp/repos\" 2>/dev/null`,\n ': >\"$tmp/done\"',\n 'while IFS= read -r g; do',\n ' d=${g%/.git}',\n ' search_repo \"$d\" && printf \\'%s\\\\n\\' \"$d\" >>\"$tmp/done\"',\n 'done <\"$tmp/repos\"',\n 'set --',\n 'while IFS= read -r d; do set -- \"$@\" -o -path \"$d\"; done <\"$tmp/done\"',\n ]\n : ['set --']),\n `printf '\\\\0%s\\\\n' \"$root\"`,\n `find \"$root\" -mindepth 1 \\\\( ${pruneNames} \"$@\" \\\\) -prune -o -type f -print0 2>/dev/null | search_files`,\n 'exit 0',\n ].join('\\n');\n const result = await this.exec(script);\n if (result.exitCode !== 0) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n const files = new Map<string, GrepFileLines>();\n let base = abs;\n for (const line of result.stdout.split('\\n')) {\n if (!line || line === '--') continue;\n if (line.startsWith('\\0')) {\n base = line.slice(1);\n continue;\n }\n const nul = line.indexOf('\\0');\n if (nul <= 0) continue;\n const parsed = /^(\\d+)([:-])(.*)$/s.exec(line.slice(nul + 1));\n if (!parsed) continue;\n const lineNumber = Number(parsed[1]);\n const text = parsed[3]!;\n const state = fileLines(files, posixPath.resolve(base, line.slice(0, nul)));\n state.linesByNumber.set(lineNumber, text);\n if (parsed[2] !== ':') continue;\n const column = jsRegex.exec(text)?.index;\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n state.matches.push({ line: lineNumber, column, text });\n }\n return this.applyTotalCap(toGrepResults(files, abs, contextLines), options.maxTotalMatches);\n }\n\n private async grepWithPosixGrep(abs: string, options: FilesystemGrepOptions): Promise<FilesystemGrepResult[]> {\n const jsRegex = SandboxFilesystem.grepRegex(options);\n // Reconstructing per-match context from `grep -C` text output is not\n // reliable (separator lines are ambiguous); let the host walk handle it.\n if (options.contextLines) {\n throw new UnsupportedGrepPatternError(options.pattern, 'context lines are not supported by POSIX grep');\n }\n const args = [\n 'grep -rnIE',\n // .git is filtered host-side too; skip it so object files are not scanned.\n '--exclude-dir=.git',\n options.caseSensitive ? '' : '-i',\n options.maxCountPerFile !== undefined ? `-m ${Math.max(1, Math.floor(options.maxCountPerFile))}` : '',\n '--',\n shellQuote(options.pattern),\n shellQuote(abs),\n ]\n .filter(Boolean)\n .join(' ');\n const result = await this.exec(args);\n if (result.exitCode === 1) return [];\n // Like rg, grep exits 2 on per-file errors (e.g. an unreadable file) while\n // still printing matches for the rest; keep those partial results.\n if (result.exitCode !== 0 && !(result.exitCode === 2 && result.stdout.trim())) {\n throw new UnsupportedGrepPatternError(options.pattern, describeGrepFailure(result));\n }\n // grep -n has no column output; recompute with the JS regex host-side so\n // columns are UTF-16 indices, consistent with the fallback implementation.\n const byFile = new Map<string, FilesystemGrepMatch[]>();\n for (const line of result.stdout.split('\\n')) {\n if (!line) continue;\n const parsed = /^(.*?):(\\d+):(.*)$/.exec(line);\n if (!parsed) continue;\n const rel = posixPath.relative(abs, parsed[1]!) || posixPath.basename(parsed[1]!);\n const text = parsed[3]!;\n const column = jsRegex.exec(text)?.index;\n // grep matched this line but the JS regex did not: the two dialects\n // disagree on this pattern, so the columns would be wrong. Fall back.\n if (column === undefined) {\n throw new UnsupportedGrepPatternError(options.pattern, 'POSIX ERE and JS RegExp disagree on this pattern');\n }\n let matches = byFile.get(rel);\n if (!matches) {\n matches = [];\n byFile.set(rel, matches);\n }\n matches.push({ line: Number(parsed[2]), column, text });\n }\n const results = [...byFile.entries()].map(([path, matches]) => ({ path, matches }));\n return this.applyTotalCap(results, options.maxTotalMatches);\n }\n\n private applyTotalCap(results: FilesystemGrepResult[], maxTotal?: number): FilesystemGrepResult[] {\n if (maxTotal === undefined) return results;\n const capped: FilesystemGrepResult[] = [];\n let total = 0;\n for (const file of results) {\n if (total >= maxTotal) break;\n const remaining = maxTotal - total;\n const matches = file.matches.slice(0, remaining);\n total += matches.length;\n capped.push({ path: file.path, matches });\n }\n return capped;\n }\n\n // ── Path / metadata ────────────────────────────────────────────────────\n\n async exists(path: string): Promise<boolean> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) return native.exists(abs);\n const result = await this.exec(`test -e ${shellQuote(abs)}`);\n return result.exitCode === 0;\n }\n\n async stat(path: string): Promise<FileStat> {\n const abs = await this.resolveAsync(path);\n const native = this.sandbox.filesystem;\n if (native) {\n await this.verifyNative('target', abs, path);\n let info: Awaited<ReturnType<typeof native.stat>>;\n try {\n info = await native.stat(abs);\n } catch (error) {\n const isNotFound = error instanceof FileNotFoundError || (error as { code?: unknown })?.code === 'ENOENT';\n throw (isNotFound && (await this.outsideWorkdirNotFound(path, abs))) || error;\n }\n return {\n ...info,\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n mimeType: info.type === 'file' ? (info.mimeType ?? getMimeType(abs)) : info.mimeType,\n };\n }\n await this.assertContainedRealpath(abs, path);\n // GNU stat: %F=type, %s=size, %Y=mtime (epoch seconds), %W=birth (or -1).\n // BSD/macOS stat (local sandbox hosts) rejects `-c`; fall back to its\n // `-f` format with the same field order (%HT=type, %z=size, %m=mtime,\n // %B=birth). Delimit with `|` — neither stat interprets `\\t` escapes in\n // its format string. `-L` reports the symlink target, like LocalFilesystem.\n const result = await this.exec(\n `stat -L -c '%F|%s|%Y|%W' ${shellQuote(abs)} 2>/dev/null || stat -L -f '%HT|%z|%m|%B' ${shellQuote(abs)}`,\n );\n if (result.exitCode !== 0) {\n throw (await this.outsideWorkdirNotFound(path, abs)) ?? new FileNotFoundError(path);\n }\n const [kind, sizeStr, mtimeStr, ctimeStr] = result.stdout.trim().split('|');\n const type = kind && kind.toLowerCase().includes('directory') ? 'directory' : 'file';\n const size = Number(sizeStr) || 0;\n const mtime = Number(mtimeStr) || 0;\n const ctime = Number(ctimeStr);\n return {\n name: posixPath.basename(abs),\n path: `/${posixPath.relative(this.basePath, abs)}`,\n type,\n size: type === 'directory' ? 0 : size,\n modifiedAt: new Date(mtime * 1000),\n createdAt: new Date((ctime > 0 ? ctime : mtime) * 1000),\n mimeType: type === 'file' ? getMimeType(abs) : undefined,\n };\n }\n\n // ── Lifecycle ──────────────────────────────────────────────────────────\n\n async init(): Promise<void> {\n await this.execOk(`mkdir -p ${shellQuote(await this.base())}`, 'init workdir');\n }\n\n async destroy(): Promise<void> {\n // The sandbox lifecycle is owned by the caller; nothing to tear down here.\n }\n\n async isReady(): Promise<boolean> {\n const result = await this.exec(`test -d ${shellQuote(await this.base())}`);\n return result.exitCode === 0;\n }\n\n getInfo(): FilesystemInfo {\n return {\n id: this.id,\n name: this.name,\n provider: this.provider,\n status: this.status,\n metadata: { basePath: this.basePath, sandboxId: this.sandbox.id },\n };\n }\n\n getInstructions(): string {\n return `Files are stored in a remote sandbox at ${this.basePath}. Use absolute workspace paths like /src/index.ts. All reads, writes and commands run inside the same sandbox. Absolute paths are workspace-relative (/tmp/x resolves to ${this.basePath}/tmp/x), so file tools cannot reach files outside ${this.basePath}. Create scratch git worktrees under ${this.basePath}/.worktrees/, then, in a pnpm monorepo, run \\`pnpm install --prefer-offline --frozen-lockfile\\` in the worktree and build the workspace packages you test against (with Turborepo: \\`pnpm turbo build --filter=\"<package>^...\"\\`, which reuses the build cache).`;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAoDA,MAAM,iBAAiB;AACvB,MAAM,oBAAoB;AAC1B,MAAM,cAAc;AACpB,MAAM,qBAAqB;;AA2D3B,MAAM,qBAAqB;;;;;AAM3B,SAAS,oBAAoB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,MAAU,SAAS,KAAK,UAAU,GAAG;GAC/C;GACA,MAAM,SAAS,cAAc,IAAI;GACjC,4BAAY,IAAI,KAAK,QAAQ,GAAI;GACjC,2BAAW,IAAI,MAAM,QAAQ,IAAI,QAAQ,SAAS,GAAI;GACtD,UAAU,SAAS,SAAS,YAAY,GAAG,IAAI,KAAA;EACjD;CACF;CAIA,MAAM,OAAsB;EAC1B,MAAM,KAAK,OAAO,YAAY,WAAW,MAAM,KAAK,KAAK,CAAC,KAAK,cAAc;CAC/E;CAEA,MAAM,UAAyB,CAE/B;CAEA,MAAM,UAA4B;EAEhC,QAAO,MADc,KAAK,KAAK,WAAW,WAAW,MAAM,KAAK,KAAK,CAAC,GAAG,EAAA,CAC3D,aAAa;CAC7B;CAEA,UAA0B;EACxB,OAAO;GACL,IAAI,KAAK;GACT,MAAM,KAAK;GACX,UAAU,KAAK;GACf,QAAQ,KAAK;GACb,UAAU;IAAE,UAAU,KAAK;IAAU,WAAW,KAAK,QAAQ;GAAG;EAClE;CACF;CAEA,kBAA0B;EACxB,OAAO,2CAA2C,KAAK,SAAS,2KAA2K,KAAK,SAAS,oDAAoD,KAAK,SAAS,uCAAuC,KAAK,SAAS;CAClX;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/agents/subagents/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAG7E,eAAO,MAAM,eAAe,EAAE,uBAoB7B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"execute.js","names":[],"sources":["../../../src/agents/subagents/execute.ts"],"sourcesContent":["import type { AgentControllerSubagent } from '@mastra/core/agent-controller';\nimport { MC_TOOLS } from '../../tool-names.js';\n\nexport const executeSubagent: AgentControllerSubagent = {\n id: 'execute',\n name: 'Execute',\n description: 'Implement a focused task, run relevant checks, and report the result.',\n instructions: `You are a focused execution agent. Understand relevant code before editing it and follow existing conventions. Stay within the assigned task; do not make unrelated changes. Use workspace tools to edit files and execute commands to verify your changes. Do not delegate work or modify the parent task list. Return a concise summary of changed files, verification results, and any blockers. Never claim checks passed unless you ran them successfully.`,\n allowedWorkspaceTools: [\n MC_TOOLS.VIEW,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.WRITE_FILE,\n MC_TOOLS.STRING_REPLACE_LSP,\n MC_TOOLS.DELETE_FILE,\n MC_TOOLS.MKDIR,\n MC_TOOLS.AST_SMART_EDIT,\n MC_TOOLS.EXECUTE_COMMAND,\n MC_TOOLS.GET_PROCESS_OUTPUT,\n MC_TOOLS.KILL_PROCESS,\n MC_TOOLS.LSP_INSPECT,\n ],\n};\n"],"mappings":";;AAGA,MAAa,kBAA2C;CACtD,IAAI;CACJ,MAAM;CACN,aAAa;CACb,cAAc;CACd,uBAAuB;EACrB,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;EACT,SAAS;CACX;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"explore.d.ts","sourceRoot":"","sources":["../../../src/agents/subagents/explore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAG7E,eAAO,MAAM,eAAe,EAAE,uBAM7B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"explore.js","names":[],"sources":["../../../src/agents/subagents/explore.ts"],"sourcesContent":["import type { AgentControllerSubagent } from '@mastra/core/agent-controller';\nimport { MC_TOOLS } from '../../tool-names.js';\n\nexport const exploreSubagent: AgentControllerSubagent = {\n id: 'explore',\n name: 'Explore',\n description: 'Explore the codebase and answer focused questions without modifying files.',\n instructions: `You are a read-only codebase exploration agent. Read relevant files before drawing conclusions. Use view, find_files, search_content, and file_stat to investigate. Do not modify files or run shell commands. Return concise findings with file paths and line numbers, and clearly distinguish verified facts from assumptions.`,\n allowedWorkspaceTools: [MC_TOOLS.VIEW, MC_TOOLS.FIND_FILES, MC_TOOLS.SEARCH_CONTENT, MC_TOOLS.FILE_STAT],\n};\n"],"mappings":";;AAGA,MAAa,kBAA2C;CACtD,IAAI;CACJ,MAAM;CACN,aAAa;CACb,cAAc;CACd,uBAAuB;EAAC,SAAS;EAAM,SAAS;EAAY,SAAS;EAAgB,SAAS;CAAS;AACzG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/agents/subagents/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAK7E,uFAAuF;AACvF,eAAO,MAAM,gBAAgB,EAAE,SAAS,uBAAuB,EAAqD,CAAC;AAErH,sGAAsG;AACtG,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,OAAO,GAAG,uBAAuB,EAAE,CAEnF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../../src/agents/subagents/index.ts"],"sourcesContent":["import type { AgentControllerSubagent } from '@mastra/core/agent-controller';\nimport { executeSubagent } from './execute.js';\nimport { exploreSubagent } from './explore.js';\nimport { planSubagent } from './plan.js';\n\n/** The explore/plan/execute subagents. Not registered unless passed as `subagents`. */\nexport const builtinSubagents: readonly AgentControllerSubagent[] = [exploreSubagent, planSubagent, executeSubagent];\n\n/** Subagents for the `preferences.subagentsEnabled` setting: the built-ins when on, none when off. */\nexport function resolveSubagentsSetting(enabled: boolean): AgentControllerSubagent[] {\n return enabled ? [...builtinSubagents] : [];\n}\n"],"mappings":";;;;;AAMA,MAAa,mBAAuD;CAAC;CAAiB;CAAc;AAAe;;AAGnH,SAAgB,wBAAwB,SAA6C;CACnF,OAAO,UAAU,CAAC,GAAG,gBAAgB,IAAI,CAAC;AAC5C"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.d.ts","sourceRoot":"","sources":["../../../src/agents/subagents/plan.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AAG7E,eAAO,MAAM,YAAY,EAAE,uBAM1B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plan.js","names":[],"sources":["../../../src/agents/subagents/plan.ts"],"sourcesContent":["import type { AgentControllerSubagent } from '@mastra/core/agent-controller';\nimport { MC_TOOLS } from '../../tool-names.js';\n\nexport const planSubagent: AgentControllerSubagent = {\n id: 'plan',\n name: 'Plan',\n description: 'Investigate a task and propose an implementation plan without modifying files.',\n instructions: `You are a read-only planning agent. Inspect the relevant code using view, find_files, search_content, and file_stat before proposing changes. Do not modify files or run shell commands. Return a concise implementation plan with file paths, ordered steps, risks, and concrete verification criteria. State assumptions and unresolved questions.`,\n allowedWorkspaceTools: [MC_TOOLS.VIEW, MC_TOOLS.FIND_FILES, MC_TOOLS.SEARCH_CONTENT, MC_TOOLS.FILE_STAT],\n};\n"],"mappings":";;AAGA,MAAa,eAAwC;CACnD,IAAI;CACJ,MAAM;CACN,aAAa;CACb,cAAc;CACd,uBAAuB;EAAC,SAAS;EAAM,SAAS;EAAY,SAAS;EAAgB,SAAS;CAAS;AACzG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"thread-caveman-state.d.ts","sourceRoot":"","sources":["../../src/agents/thread-caveman-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAyB,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAkGpF;;;;;;;GAOG;AACH,wBAAgB,8BAA8B,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,IAAI,CAqB9F;AAED;;;;GAIG;AACH,wBAAsB,oCAAoC,CAAC,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAInH"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"thread-caveman-state.js","names":[],"sources":["../../src/agents/thread-caveman-state.ts"],"sourcesContent":["import type { AgentControllerThread, Session } from '@mastra/core/agent-controller';\n\ninterface ThreadStateSetting {\n key: string;\n isValid(value: unknown): boolean;\n seedMissingFromCurrentState?: boolean;\n clearValueWhenMissing?: unknown;\n}\n\nconst THREAD_STATE_SETTINGS: ThreadStateSetting[] = [\n {\n key: 'cavemanObservations',\n isValid: (value: unknown): value is boolean => typeof value === 'boolean',\n seedMissingFromCurrentState: true,\n },\n {\n key: 'observeAttachments',\n isValid: (value: unknown): value is 'auto' | boolean => value === 'auto' || typeof value === 'boolean',\n seedMissingFromCurrentState: true,\n },\n {\n key: 'sandboxAllowedPaths',\n isValid: (value: unknown): value is string[] =>\n Array.isArray(value) && value.every(item => typeof item === 'string'),\n clearValueWhenMissing: [],\n },\n];\n\nfunction getStateValue(session: Session<Record<string, unknown>>, setting: ThreadStateSetting): unknown {\n const value = session.state.get()[setting.key];\n return setting.isValid(value) ? value : undefined;\n}\n\nfunction stateValuesEqual(left: unknown, right: unknown): boolean {\n if (Array.isArray(left) && Array.isArray(right)) {\n return left.length === right.length && left.every((item, index) => item === right[index]);\n }\n return left === right;\n}\n\nasync function findThread(\n session: Session<Record<string, unknown>>,\n threadId: string,\n): Promise<AgentControllerThread | undefined> {\n const threads = await session.thread.list({ allResources: true });\n return threads.find(t => t.id === threadId);\n}\n\n/**\n * Restores MastraCode-owned per-thread state for the given thread:\n * - If the thread already has a valid value in metadata, mirror it into controller state.\n * - Otherwise, persist the current session.state value to the thread so future\n * sessions see the user's last-selected setting.\n */\nasync function restoreSettingsForThread(session: Session<Record<string, unknown>>, threadId: string): Promise<void> {\n const thread = await findThread(session, threadId);\n if (session.thread.getId() !== threadId) return;\n\n const updates: Record<string, unknown> = {};\n const settingsToSeed: Array<{ key: string; value: unknown }> = [];\n\n for (const setting of THREAD_STATE_SETTINGS) {\n const persisted = thread?.metadata?.[setting.key];\n\n if (setting.isValid(persisted)) {\n if (getStateValue(session, setting) !== persisted) {\n updates[setting.key] = persisted;\n }\n continue;\n }\n\n if (setting.clearValueWhenMissing !== undefined) {\n const current = getStateValue(session, setting);\n if (current !== undefined && !stateValuesEqual(current, setting.clearValueWhenMissing)) {\n updates[setting.key] = setting.clearValueWhenMissing;\n }\n continue;\n }\n\n if (setting.seedMissingFromCurrentState) {\n const current = getStateValue(session, setting);\n if (current !== undefined) {\n settingsToSeed.push({ key: setting.key, value: current });\n }\n }\n }\n\n if (Object.keys(updates).length > 0) {\n if (session.thread.getId() !== threadId) return;\n await session.state.set(updates);\n }\n\n for (const setting of settingsToSeed) {\n if (session.thread.getId() !== threadId) return;\n await session.thread.setSetting(setting);\n }\n}\n\n/**\n * Wires MastraCode-owned state into controller thread events so it persists\n * per-thread and new threads inherit the most recent value.\n *\n * This is intentionally implemented in mastracode rather than core: these\n * settings are mastracode-specific concepts, so persistence stays scoped to\n * the host.\n */\nexport function attachOMThreadStatePersistence(session: Session<Record<string, unknown>>): void {\n session.subscribe(event => {\n if (event.type === 'thread_changed' || event.type === 'thread_created') {\n const threadId = event.type === 'thread_changed' ? event.threadId : event.thread.id;\n void restoreSettingsForThread(session, threadId).catch(() => {\n // Persistence is best-effort; don't crash the TUI if storage hiccups.\n });\n return;\n }\n\n if (event.type === 'state_changed') {\n for (const setting of THREAD_STATE_SETTINGS) {\n if (!event.changedKeys.includes(setting.key)) continue;\n const value = event.state[setting.key];\n if (!setting.isValid(value)) continue;\n void session.thread.setSetting({ key: setting.key, value }).catch(() => {\n // Persistence is best-effort; don't crash the TUI if storage hiccups.\n });\n }\n }\n });\n}\n\n/**\n * Eagerly restores MastraCode-owned OM settings for the currently-selected\n * thread. Called once at TUI startup after the initial thread is selected,\n * since the subscription set up later misses the startup `thread_changed` event.\n */\nexport async function restoreOMThreadStateForCurrentThread(session: Session<Record<string, unknown>>): Promise<void> {\n const threadId = session.thread.getId();\n if (!threadId) return;\n await restoreSettingsForThread(session, threadId);\n}\n"],"mappings":";AASA,MAAM,wBAA8C;CAClD;EACE,KAAK;EACL,UAAU,UAAqC,OAAO,UAAU;EAChE,6BAA6B;CAC/B;CACA;EACE,KAAK;EACL,UAAU,UAA8C,UAAU,UAAU,OAAO,UAAU;EAC7F,6BAA6B;CAC/B;CACA;EACE,KAAK;EACL,UAAU,UACR,MAAM,QAAQ,KAAK,KAAK,MAAM,OAAM,SAAQ,OAAO,SAAS,QAAQ;EACtE,uBAAuB,CAAC;CAC1B;AACF;AAEA,SAAS,cAAc,SAA2C,SAAsC;CACtG,MAAM,QAAQ,QAAQ,MAAM,IAAI,CAAC,CAAC,QAAQ;CAC1C,OAAO,QAAQ,QAAQ,KAAK,IAAI,QAAQ,KAAA;AAC1C;AAEA,SAAS,iBAAiB,MAAe,OAAyB;CAChE,IAAI,MAAM,QAAQ,IAAI,KAAK,MAAM,QAAQ,KAAK,GAC5C,OAAO,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,MAAM,UAAU,SAAS,MAAM,MAAM;CAE1F,OAAO,SAAS;AAClB;AAEA,eAAe,WACb,SACA,UAC4C;CAE5C,QAAO,MADe,QAAQ,OAAO,KAAK,EAAE,cAAc,KAAK,CAAC,EAAA,CACjD,MAAK,MAAK,EAAE,OAAO,QAAQ;AAC5C;;;;;;;AAQA,eAAe,yBAAyB,SAA2C,UAAiC;CAClH,MAAM,SAAS,MAAM,WAAW,SAAS,QAAQ;CACjD,IAAI,QAAQ,OAAO,MAAM,MAAM,UAAU;CAEzC,MAAM,UAAmC,CAAC;CAC1C,MAAM,iBAAyD,CAAC;CAEhE,KAAK,MAAM,WAAW,uBAAuB;EAC3C,MAAM,YAAY,QAAQ,WAAW,QAA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,CAAC,YAAY,CAExE,CAAC;EACH;CAEJ,CAAC;AACH;;;;;;AAOA,eAAsB,qCAAqC,SAA0D;CACnH,MAAM,WAAW,QAAQ,OAAO,MAAM;CACtC,IAAI,CAAC,UAAU;CACf,MAAM,yBAAyB,SAAS,QAAQ;AAClD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-availability.d.ts","sourceRoot":"","sources":["../../src/agents/tool-availability.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,wBAAwB,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AA4D7F,wFAAwF;AACxF,wBAAgB,gCAAgC,CAAC,QAAQ,CAAC,EAAE,MAAM,iBAC3C,wBAAwB;;;cAC9C;AAED,eAAO,MAAM,2BAA2B,gBAHjB,wBAAwB;;;aAG8B,CAAC;AAgC9E,wBAAgB,8BAA8B,CAC5C,sBAAsB,UAAQ,EAC9B,QAAQ,CAAC,EAAE,MAAM,GAChB,oBAAoB,CAiCtB;AAED,wFAAwF;AACxF,eAAO,MAAM,0BAA0B,sBAAmC,CAAC;AAE3E,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAwBtD,CAAC;AAEF,eAAO,MAAM,4BAA4B,EAAE,SAAS,MAAM,EAUzD,CAAC;AAEF,eAAO,MAAM,yBAAyB,EAAE,SAAS,MAAM,EAMtD,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tool-availability.js","names":[],"sources":["../../src/agents/tool-availability.ts"],"sourcesContent":["import { WORKSPACE_TOOLS } from '@mastra/core/workspace';\nimport type { WorkspaceToolHookContext, WorkspaceToolsConfig } from '@mastra/core/workspace';\nimport { MC_TOOLS, TOOL_NAME_OVERRIDES } from '../tool-names.js';\nimport { getLocalPlansRelativeDir, isPlanFilePath } from '../utils/plans.js';\n\nconst PLAN_MODE_WRITE_TOOL_NAMES = new Set<string>([\n WORKSPACE_TOOLS.FILESYSTEM.WRITE_FILE,\n WORKSPACE_TOOLS.FILESYSTEM.EDIT_FILE,\n]);\n\nfunction getRequestContextValue(requestContext: unknown, key: string): unknown {\n if (!requestContext) return undefined;\n if (typeof (requestContext as { get?: unknown }).get === 'function') {\n return (requestContext as { get: (key: string) => unknown }).get(key);\n }\n return (requestContext as Record<string, unknown>)[key];\n}\n\n/**\n * Subset of the `AgentControllerRequestContext` the controller sets under the\n * `controller` request-context key. The mode is a string property\n * (`session.modeId`) and live state is read via `session.state.get()`.\n */\ninterface PlanModeGuardHarness {\n session?: {\n modeId?: unknown;\n state?: { get?: () => unknown };\n };\n}\n\nfunction getHarnessContext(context: unknown): PlanModeGuardHarness | undefined {\n const requestContext = (context as { requestContext?: unknown } | undefined)?.requestContext;\n const harness = getRequestContextValue(requestContext, 'controller');\n return harness && typeof harness === 'object' ? (harness as PlanModeGuardHarness) : undefined;\n}\n\nfunction getHarnessState(harness: PlanModeGuardHarness | undefined): Record<string, unknown> | undefined {\n const state = harness?.session?.state?.get?.();\n return state && typeof state === 'object' ? (state as Record<string, unknown>) : undefined;\n}\n\nfunction getHarnessModeId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const modeId = harness?.session?.modeId ?? getHarnessState(harness)?.modeId;\n return typeof modeId === 'string' ? modeId : undefined;\n}\n\nfunction getHarnessProjectPath(harness: PlanModeGuardHarness | undefined): string | undefined {\n const projectPath = getHarnessState(harness)?.projectPath;\n return typeof projectPath === 'string' ? projectPath : undefined;\n}\n\nfunction getHarnessFactoryProjectId(harness: PlanModeGuardHarness | undefined): string | undefined {\n const factoryProjectId = getHarnessState(harness)?.factoryProjectId;\n return typeof factoryProjectId === 'string' ? factoryProjectId : undefined;\n}\n\nfunction getToolInputPath(input: unknown): string | undefined {\n const toolPath = (input as { path?: unknown } | undefined)?.path;\n return typeof toolPath === 'string' ? toolPath : undefined;\n}\n\n/** Plan-mode write guard; `plansDir` is the host-configured plans directory, if any. */\nexport function createPlanModePlanFileWriteGuard(plansDir?: string) {\n return (hookContext: WorkspaceToolHookContext) => guardPlanFileWrite(hookContext, plansDir);\n}\n\nexport const guardPlanModePlanFileWrites = createPlanModePlanFileWriteGuard();\n\nfunction guardPlanFileWrite({ workspaceToolName, input, context }: WorkspaceToolHookContext, plansDir?: string) {\n if (!PLAN_MODE_WRITE_TOOL_NAMES.has(workspaceToolName)) return;\n\n const harness = getHarnessContext(context);\n if (getHarnessModeId(harness) !== 'plan') return;\n\n const factoryProjectId = getHarnessFactoryProjectId(harness);\n const planOptions = { factoryProjectId, plansDir };\n const planDirHint = `${getLocalPlansRelativeDir(planOptions)}/`;\n const projectPath = getHarnessProjectPath(harness);\n const inputPath = getToolInputPath(input);\n if (!projectPath || !inputPath) {\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}.`,\n };\n }\n\n // Plan mode may write any `.md` file directly inside the configured plan directory,\n // but nothing else in the project.\n if (isPlanFilePath(projectPath, inputPath, planOptions)) return;\n\n return {\n proceed: false as const,\n output: `Plan mode can only write plan files inside ${planDirHint}. Refusing to edit ${inputPath}.`,\n };\n}\n\nconst BACKGROUND_TOOL_CONFIG = { enabled: true, defaultDisposition: 'foreground' } as const;\n\nexport function createMastraCodeWorkspaceTools(\n backgroundToolsEnabled = false,\n plansDir?: string,\n): WorkspaceToolsConfig {\n const background = backgroundToolsEnabled ? BACKGROUND_TOOL_CONFIG : undefined;\n return {\n ...TOOL_NAME_OVERRIDES,\n // The TUI shows this description in place of the raw command.\n [WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.SANDBOX.EXECUTE_COMMAND],\n requireDescription: true,\n },\n [WORKSPACE_TOOLS.FILESYSTEM.READ_FILE]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.READ_FILE],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.LIST_FILES],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.FILE_STAT],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.FILESYSTEM.GREP]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.FILESYSTEM.GREP],\n ...(background ? { background } : {}),\n },\n [WORKSPACE_TOOLS.LSP.LSP_INSPECT]: {\n ...TOOL_NAME_OVERRIDES[WORKSPACE_TOOLS.LSP.LSP_INSPECT],\n ...(background ? { background } : {}),\n },\n hooks: {\n beforeToolCall: createPlanModePlanFileWriteGuard(plansDir),\n },\n };\n}\n\n/** Default foreground-only configuration for consumers without Mastra Code settings. */\nexport const MASTRACODE_WORKSPACE_TOOLS = createMastraCodeWorkspaceTools();\n\nexport const PLAN_MODE_AVAILABLE_TOOLS: readonly string[] = [\n // Read-only exploration tools\n MC_TOOLS.VIEW,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n // Plan file writing. Tool hooks enforce that these can only write `.md`\n // files inside the session's configured plan directory while in plan mode.\n MC_TOOLS.WRITE_FILE,\n MC_TOOLS.STRING_REPLACE_LSP,\n // Plan delivery tools\n 'ask_user',\n 'submit_plan',\n // Task tools for plan-stage tracking\n 'task_write',\n 'task_update',\n 'task_complete',\n 'task_check',\n // Notification access\n MC_TOOLS.NOTIFICATION_INBOX,\n // Read-only workflow inspection (no create/run/delete in plan mode).\n 'list-workflows',\n 'get-workflow',\n];\n\nexport const EXPLORE_MODE_AVAILABLE_TOOLS: readonly string[] = [\n MC_TOOLS.VIEW,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n 'ask_user',\n // Read-only workflow inspection (no create/run/delete in fast mode either).\n 'list-workflows',\n 'get-workflow',\n];\n\nexport const GOAL_JUDGE_READONLY_TOOLS: readonly string[] = [\n MC_TOOLS.VIEW,\n MC_TOOLS.SEARCH_CONTENT,\n MC_TOOLS.FIND_FILES,\n MC_TOOLS.FILE_STAT,\n MC_TOOLS.LSP_INSPECT,\n];\n"],"mappings":";;;;AAKA,MAAM,6CAA6B,IAAI,IAAY,CACjD,gBAAgB,WAAW,YAC3B,gBAAgB,WAAW,SAC7B,CAAC;AAED,SAAS,uBAAuB,gBAAyB,KAAsB;CAC7E,IAAI,CAAC,gBAAgB,OAAO,KAAA;CAC5B,IAAI,OAAQ,eAAqC,QAAQ,YACvD,OAAQ,eAAqD,IAAI,GAAG;CAEtE,OAAQ,eAA2C;AACrD;AAcA,SAAS,kBAAkB,SAAoD;CAC7E,MAAM,iBAAkB,SAAsD;CAC9E,MAAM,UAAU,uBAAuB,gBAAgB,YAAY;CACnE,OAAO,WAAW,OAAO,YAAY,WAAY,UAAmC,KAAA;AACtF;AAEA,SAAS,gBAAgB,SAAgF;CACvG,MAAM,QAAQ,SAAS,SAAS,OAAO,MAAM;CAC7C,OAAO,SAAS,OAAO,UAAU,WAAY,QAAoC,KAAA;AACnF;AAEA,SAAS,iBAAiB,SAA+D;CACvF,MAAM,SAAS,SAAS,SAAS,UAAU,gBAAgB,OAAO,CAAC,EAAE;CACrE,OAAO,OAAO,WAAW,WAAW,SAAS,KAAA;AAC/C;AAEA,SAAS,sBAAsB,SAA+D;CAC5F,MAAM,cAAc,gBAAgB,OAAO,CAAC,EAAE;CAC9C,OAAO,OAAO,gBAAgB,WAAW,cAAc,KAAA;AACzD;AAEA,SAAS,2BAA2B,SAA+D;CACjG,MAAM,mBAAmB,gBAAgB,OAAO,CAAC,EAAE;CACnD,OAAO,OAAO,qBAAqB,WAAW,mBAAmB,KAAA;AACnE;AAEA,SAAS,iBAAiB,OAAoC;CAC5D,MAAM,WAAY,OAA0C;CAC5D,OAAO,OA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C,MAAM,CAAC,MAAM,EAAE,QAAQ,GAAG,SAAS,CAAC,CAAC,CAAC,CAAC;AAwBhG,wBAAgB,kBAAkB,CAChC,UAAU,CAAC,EAAE,UAAU,EACvB,UAAU,CAAC,EAAE,mBAAmB,EAChC,aAAa,CAAC,EAAE,MAAM,EAAE,EACxB,OAAO,CAAC,EAAE,oBAAoB,EAC9B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,EACtC,sBAAsB,UAAQ,EAC9B,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,yBAIpC;IACD,cAAc,EAAE,cAAc,CAAC;CAChC,KAAG,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAqGrC"}
|
package/dist/agents/tools.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"tools.js","names":[],"sources":["../../src/agents/tools.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport { createNotificationInboxTool, NotificationsStorage } from '@mastra/core/notifications';\nimport type {\n CreateNotificationInput,\n ListDueNotificationsInput,\n ListNotificationsInput,\n UpdateNotificationInput,\n UpdateNotificationsStatusInput,\n} from '@mastra/core/notifications';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\nimport type { ToolAfterHookContext, ToolHooks } from '@mastra/core/tools';\nimport { jsonSchema } from 'ai';\nimport type { HookManager } from '../hooks/index.js';\nimport type { McpManager } from '../mcp/index.js';\nimport type { MastraCodeComposedState } from '../schema.js';\nimport { MC_TOOLS } from '../tool-names.js';\nimport { createConfiguredWebTools, requestSandboxAccessTool } from '../tools/index.js';\nimport { createWorkflowTool } from '../tools/workflows/create-workflow.js';\nimport { deleteWorkflowTool } from '../tools/workflows/delete-workflow.js';\nimport { getWorkflowTool } from '../tools/workflows/get-workflow.js';\nimport { listWorkflowsTool } from '../tools/workflows/list-workflows.js';\nimport { runWorkflowTool } from '../tools/workflows/run-workflow.js';\nimport { WORKFLOW_MANAGEMENT_TOOL_IDS } from '../tools/workflows/tool-ids.js';\nimport { prepareProviderWebSearchRoute, resolveProviderWebSearchRoute } from './model.js';\nimport type { ProviderWebSearchRoute } from './model.js';\n\n/** Minimal shape for tools passed to createDynamicTools. */\nexport type ToolLike = {\n execute?: (...args: any[]) => Promise<unknown> | unknown;\n} & Record<string, any>;\n\nfunction configurePluginTool(tool: ToolLike, backgroundToolsEnabled: boolean): ToolLike {\n if (backgroundToolsEnabled || !tool.background) return tool;\n return { ...tool, background: { ...tool.background, enabled: false } };\n}\n\nexport class LazyNotificationsStorage extends NotificationsStorage {\n constructor(private readonly storage: MastraCompositeStore) {\n super();\n }\n\n private async getNotificationsStorage(): Promise<NotificationsStorage> {\n const notifications = await this.storage.getStore('notifications');\n if (!notifications) {\n throw new Error('notification_inbox requires a notifications storage domain');\n }\n return notifications;\n }\n\n async createNotification(input: CreateNotificationInput) {\n return (await this.getNotificationsStorage()).createNotification(input);\n }\n\n async listNotifications(input: ListNotificationsInput) {\n return (await this.getNotificationsStorage()).listNotifications(input);\n }\n\n async listDueNotifications(input: ListDueNotificationsInput) {\n return (await this.getNotificationsStorage()).listDueNotifications(input);\n }\n\n async getNotification(input: { threadId: string; id: string }) {\n return (await this.getNotificationsStorage()).getNotification(input);\n }\n\n async updateNotification(input: UpdateNotificationInput) {\n return (await this.getNotificationsStorage()).updateNotification(input);\n }\n\n override async updateNotificationsStatus(input: UpdateNotificationsStatusInput) {\n return (await this.getNotificationsStorage()).updateNotificationsStatus(input);\n }\n\n async dangerouslyClearAll() {\n return (await this.getNotificationsStorage()).dangerouslyClearAll();\n }\n}\n\nexport type PostToolObserver = (context: ToolAfterHookContext) => void | Promise<void>;\n\nexport function createToolHooks(hookManager?: HookManager, postToolObserver?: PostToolObserver): ToolHooks | undefined {\n if (!hookManager && !postToolObserver) return undefined;\n\n return {\n beforeToolCall: async ({ toolName, input }) => {\n if (!hookManager) return;\n const preResult = await hookManager.runPreToolUse(toolName, input);\n if (!preResult.allowed) {\n return {\n proceed: false as const,\n output: {\n error: preResult.blockReason ?? `Blocked by PreToolUse hook for tool \"${toolName}\"`,\n },\n };\n }\n },\n afterToolCall: async context => {\n const { toolName, input, output, error } = context;\n if (hookManager) {\n const failed = error !== undefined;\n await hookManager\n .runPostToolUse(\n toolName,\n input,\n failed ? { error: error instanceof Error ? error.message : String(error) } : output,\n failed,\n )\n .catch(() => undefined);\n }\n await Promise.resolve()\n .then(() => postToolObserver?.(context))\n .catch(error => {\n console.warn(`[MastraCode] Post-tool observer failed for ${toolName}.`, error);\n });\n },\n };\n}\n\ntype DynamicToolProvider =\n | Record<string, ToolLike | undefined>\n | ((ctx: {\n requestContext: RequestContext;\n }) => Record<string, ToolLike | undefined> | Promise<Record<string, ToolLike | undefined>>);\n\n/**\n * The provider-executed search tool for a route. The Mastra gateway's OpenRouter\n * chat endpoint takes `openrouter:web_search` (the OpenRouter provider sends a\n * provider tool `openrouter.web_search` with that type), as Mastra's own\n * templates use against the gateway.\n */\nfunction createProviderWebSearchTool(route: ProviderWebSearchRoute): ToolLike {\n switch (route) {\n case 'anthropic':\n return createAnthropic({}).tools.webSearch_20250305();\n case 'openai':\n return createOpenAI({}).tools.webSearch();\n case 'mastra-gateway':\n return {\n type: 'provider',\n id: 'openrouter.web_search',\n args: {},\n inputSchema: jsonSchema({ type: 'object', properties: {} }),\n } as unknown as ToolLike;\n }\n}\n\nexport function createDynamicTools(\n mcpManager?: McpManager,\n extraTools?: DynamicToolProvider,\n disabledTools?: string[],\n storage?: MastraCompositeStore,\n pluginTools?: Record<string, ToolLike>,\n backgroundToolsEnabled = false,\n builtinTools?: Record<string, ToolLike>,\n) {\n return function getDynamicTools({\n requestContext,\n }: {\n requestContext: RequestContext;\n }): ToolsInput | Promise<ToolsInput> {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeComposedState> | undefined;\n const state = ctx?.getState();\n\n // In deployed Factory, the search route reads tenant credentials; prepare them first if needed.\n const preparing = prepareProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });\n if (preparing) return preparing.then(() => getDynamicTools({ requestContext }));\n const webSearchRoute = resolveProviderWebSearchRoute(ctx?.session?.modelId, { requestContext });\n\n // Filesystem, grep, glob, edit, write, execute_command, and process\n // management tools are now provided by the workspace (see workspace.ts).\n // Only tools without a workspace equivalent remain here.\n const tools: Record<string, ToolLike> = {\n request_access: requestSandboxAccessTool,\n // Workflow surface. `create-workflow` delegates to the workflow-builder\n // sub-agent; the other four are Dynamic Workflow management operations.\n // Permission categories live in permissions.ts (TOOL_CATEGORY_MAP).\n [WORKFLOW_MANAGEMENT_TOOL_IDS.createWorkflow]: createWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.listWorkflows]: listWorkflowsTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.getWorkflow]: getWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.runWorkflow]: runWorkflowTool,\n [WORKFLOW_MANAGEMENT_TOOL_IDS.deleteWorkflow]: deleteWorkflowTool,\n };\n\n // Opt-in built-ins (e.g. the experimental schedule tools).\n if (builtinTools) Object.assign(tools, builtinTools);\n\n if (storage) {\n tools[MC_TOOLS.NOTIFICATION_INBOX] = createNotificationInboxTool({\n storage: new LazyNotificationsStorage(storage),\n });\n }\n\n // Async only when a Tavily/Parallel key is set; otherwise the tool list stays synchronous.\n const configuredWebTools = createConfiguredWebTools();\n if (!configuredWebTools && webSearchRoute) {\n tools.web_search = createProviderWebSearchTool(webSearchRoute);\n }\n\n const mcpTools = mcpManager?.getTools();\n if (mcpTools) Object.assign(tools, mcpTools);\n\n const finish = (resolvedExtra: Record<string, ToolLike | undefined> | undefined) => {\n if (resolvedExtra) {\n for (const [name, tool] of Object.entries(resolvedExtra)) {\n if (tool && !(name in tools)) {\n tools[name] = tool;\n }\n }\n }\n\n if (pluginTools) {\n for (const [name, tool] of Object.entries(pluginTools)) {\n if (!(name in tools)) {\n tools[name] = configurePluginTool(tool, backgroundToolsEnabled);\n }\n }\n }\n\n // Remove tools explicitly disabled via config so the model never sees them.\n if (disabledTools?.length) {\n for (const toolName of disabledTools) {\n delete tools[toolName];\n }\n }\n\n // Remove tools that have a per-tool 'deny' policy so the model never sees them.\n const permissionRules = state?.permissionRules;\n if (permissionRules?.tools) {\n for (const [name, policy] of Object.entries(permissionRules.tools)) {\n if (policy === 'deny') {\n delete tools[name];\n }\n }\n }\n\n return tools as ToolsInput;\n };\n\n const resolveExtra = (): ToolsInput | Promise<ToolsInput> => {\n if (typeof extraTools === 'function') {\n const resolved = extraTools({ requestContext });\n // Stay synchronous for sync providers; only go async when the provider does.\n if (resolved && typeof (resolved as PromiseLike<unknown>).then === 'function') {\n return Promise.resolve(resolved).then(finish);\n }\n return finish(resolved as Record<string, ToolLike | undefined>);\n }\n return finish(extraTools);\n };\n\n if (configuredWebTools) {\n return configuredWebTools.then(webTools => {\n // MCP tools keep precedence over the web tools, as when both were assigned in order.\n Object.assign(tools, webTools, mcpTools);\n return resolveExtra();\n });\n }\n\n return resolveExtra();\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmCA,SAAS,oBAAoB,MAAgB,wBAA2C;CACtF,IAAI,0BAA0B,CAAC,KAAK,YAAY,OAAO;CACvD,OAAO;EAAE,GAAG;EAAM,YAAY;GAAE,GAAG,KAAK;GAAY,SAAS;EAAM;CAAE;AACvE;AAEA,IAAa,2BAAb,cAA8C,qBAAqB;CACpC;CAA7B,YAAY,SAAgD;EAC1D,MAAM;EADqB,KAAA,UAAA;CAE7B;CAEA,MAAc,0BAAyD;EACrE,MAAM,gBAAgB,MAAM,KAAK,QAAQ,SAAS,eAAe;EACjE,IAAI,CAAC,eACH,MAAM,IAAI,MAAM,4DAA4D;EAE9E,OAAO;CACT;CAEA,MAAM,m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4B,cAAc;EAG/D,MAAM,WAAW,YAAY,SAAS;EACtC,IAAI,UAAU,OAAO,OAAO,OAAO,QAAQ;EAE3C,MAAM,UAAU,kBAAoE;GAClF,IAAI,eACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,aAAa,GACrD,IAAI,QAAQ,EAAE,QAAQ,QACpB,MAAM,QAAQ;GAAA;GAKpB,IAAI,aACG;SAAA,MAAM,CAAC,MAAM,SAAS,OAAO,QAAQ,WAAW,GACnD,IAAI,EAAE,QAAQ,QACZ,MAAM,QAAQ,oBAAoB,MAAM,sBAAsB;GAAA;GAMpE,IAAI,eAAe,QACjB,KAAK,MAAM,YAAY,eACrB,OAAO,MAAM;GAKjB,MAAM,kBAAkB,OAAO;GAC/B,IAAI,iBAAiB,OACd;SAAA,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,gBAAgB,KAAK,GAC/D,IAAI,WAAW,QACb,OAAO,MAAM;GAAA;GAKnB,OAAO;EACT;EAEA,MAAM,qBAAuD;GAC3D,IAAI,OAAO,eAAe,YAAY;IACpC,MAAM,WAAW,WAAW,EAAE,eAAe,CAAC;IAE9C,IAAI,YAAY,OAAQ,SAAkC,SAAS,YACjE,OAAO,QAAQ,QAAQ,QAAQ,CAAC,CAAC,KAAK,MAAM;IAE9C,OAAO,OAAO,QAAgD;GAChE;GACA,OAAO,OAAO,UAAU;EAC1B;EAEA,IAAI,oBACF,OAAO,mBAAmB,MAAK,aAAY;GAEzC,OAAO,OAAO,OAAO,UAAU,QAAQ;GACvC,OAAO,aAAa;EACtB,CAAC;EAGH,OAAO,aAAa;CACtB;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-builder-agent.d.ts","sourceRoot":"","sources":["../../src/agents/workflow-builder-agent.ts"],"names":[],"mappings":"AAqBA,eAAO,MAAM,oBAAoB,6KA4D/B,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-builder-agent.js","names":[],"sources":["../../src/agents/workflow-builder-agent.ts"],"sourcesContent":["/**\n * Workflow Builder sub-agent.\n *\n * The parent code-agent (build/plan/explore modes) delegates to this agent\n * via the `create-workflow` tool. Keeping the long workflow-authoring system\n * prompt here — instead of inlining it into every parent mode — keeps the\n * parent modes lean and lets the same author logic ship to Studio later.\n *\n * The sub-agent's tool set is intentionally tiny: discover what's available,\n * construct the entire definition in one thought, save it. No setter loop,\n * no per-step mutations.\n */\nimport { createWorkflowBuilderAgent } from '@mastra/core/workflows/builder';\nimport { listAvailableAgentsTool } from '../tools/workflows/list-available-agents.js';\nimport { listAvailableClassifiersTool } from '../tools/workflows/list-available-classifiers.js';\nimport { listAvailableToolsTool } from '../tools/workflows/list-available-tools.js';\nimport { listAvailableWorkflowsTool } from '../tools/workflows/list-available-workflows.js';\nimport { saveWorkflowTool } from '../tools/workflows/save-workflow.js';\nimport { WORKFLOW_AUTHORING_TOOL_IDS } from '../tools/workflows/tool-ids.js';\nimport { getDynamicModel } from './model.js';\n\nexport const workflowBuilderAgent = createWorkflowBuilderAgent({\n id: 'workflow-builder',\n name: 'Workflow Builder',\n description: 'Turns plain-language workflow descriptions into runnable, persisted workflow definitions.',\n tools: {\n [WORKFLOW_AUTHORING_TOOL_IDS.listAgents]: listAvailableAgentsTool,\n [WORKFLOW_AUTHORING_TOOL_IDS.listClassifiers]: listAvailableClassifiersTool,\n [WORKFLOW_AUTHORING_TOOL_IDS.listTools]: listAvailableToolsTool,\n [WORKFLOW_AUTHORING_TOOL_IDS.listWorkflows]: listAvailableWorkflowsTool,\n [WORKFLOW_AUTHORING_TOOL_IDS.saveWorkflow]: saveWorkflowTool,\n },\n surfaceInstructions: `# Mastra Code authoring policy\n\nYour job: turn the user's verbatim plain-language request into a complete Dynamic Workflow definition and persist it with save-workflow. Success means save-workflow returned \\`{ ok: true, id }\\` for the workflow the user asked for; do not claim success before that result.\n\nSave each definition successfully **exactly once**: after \\`save-workflow\\` returns \\`{ ok: true, id }\\`, never save that workflow again. The workflow the user asked for is always saved LAST. You may save other workflows before it **only** when they are helper workflows the requested workflow references as \\`{ type: \"workflow\" }\\` entries — never to probe the schema or split one workflow into pieces the user did not ask for. A rejected save is not a successful save; correct the reported issues and make the one sequential corrected attempt permitted by the protocol below.\n\n# \\`code-agent\\` — when to use it as an agent step\n\nThe Mastra instance registers \\`code-agent\\` (mastracode's coding agent) alongside the workflow-builder. When discovery surfaces it in \\`list-available-agents\\`, know that under the hood it has full access to workspace tools (view / edit / run commands), MCP tools, and web search — and it *reasons* over a prompt to pick the right ones.\n\nUse it as an \\`agent\\` step when the workflow needs judgment or open-ended tool orchestration you can't hardcode — e.g. \"read these files and figure out what changed\", \"review these logs and summarise the failures\", \"call the right MCP tool to open a Linear issue based on this content\".\n\nWhen the workflow needs a **specific, deterministic** operation (like \\`execute_command wc -l file.ts\\` or a single fixed web-search call), prefer a plain \\`tool\\` step — cheaper, no LLM in the middle, and reproducible.\n\n# Workspace tool output shapes — read this before wiring a file-oriented workflow\n\nThe workspace tools you are most likely to compose with return **strings, not objects**, and the shared bridge-agent and \\`initData\\` re-threading guidance applies to them directly:\n\n- \\`find_files\\` returns a formatted \\`string\\` listing, and the entries are **bare basenames with no path prefix** (e.g. \\`app-tools.ts\\\\nserver.ts\\`). A downstream step told only \"summarise each file\" therefore has no idea which folder they live in.\n- \\`find_files\\` — inputSchema \\`{ path?: string, ... }\\`, outputSchema tree-formatted text (string).\n- \\`view\\` — inputSchema \\`{ path: string, ... }\\`, outputSchema \\`string | { __workspaceMedia: true, text: string, mediaType: string, data: string }\\`.\n\nTwo consequences, both covered by the shared playbook's worked examples:\n\n1. A string listing is not iterable, so \\`foreach\\` needs a bridge \\`agent\\` step with a top-level array \\`outputSchema\\` between the listing tool and the loop.\n2. Because the listing strips the folder path, the mapping that builds the bridge agent's prompt MUST re-thread the original path with \\`\\${initData.<pathField>}\\` alongside \\`\\${stepResults.<listing-step>}\\`. Skipping this is the most common cause of downstream \"file not found\" failures.\n\nAlways confirm these shapes against \\`list-available-tools\\` rather than trusting the summary above.\n\n# Mastra Code discovery notes\n\nThe four shared listing tools behave here exactly as the shared playbook describes; each row's \\`id\\` is the value you copy into \\`agentId\\` / \\`classifierId\\` / \\`toolId\\` / \\`workflowId\\`. \\`list-available-classifiers\\` includes configured question metadata and stable \\`values.<question>\\` paths for conditional routing. \\`list-available-workflows\\` includes both code-defined and Dynamic Workflows, and its catalog is always available on this surface.\n\nYour fifth tool is \\`save-workflow\\`, which persists and live-registers a definition. Make one sequential complete call per attempt, only after composition and the shared pre-action check.\n\n# Mastra Code execution and response protocol\n\n1. Complete discovery, composition, and the shared pre-action check before calling \\`save-workflow\\`.\n2. If the design needs helper workflows (for example, per-branch wrappers so \\`parallel\\` branches can consume different fields — see the shared nested-workflow guidance), save each helper FIRST, one complete definition per call, in dependency order. Each \\`save-workflow\\` success live-registers that helper, which makes it a valid \\`workflowId\\` for the next definition. Confirm with \\`list-available-workflows\\` before referencing it, and give each helper a real \\`id\\` and \\`description\\` — helpers are permanent, user-visible registry entries, not scratch space.\n3. Call \\`save-workflow\\` with one complete \\`{ id, description, inputSchema, outputSchema, graph }\\` definition for the requested workflow. There are no incremental setter tools and no parallel save attempts.\n4. Wait for the tool result. Success means exactly that \\`save-workflow\\` returned \\`{ ok: true, id }\\`; at that point the workflow is persisted and live-registered.\n5. If the tool rejects the definition, do not claim success. Use the returned diagnostics and authoritative discovery to correct every named issue, rerun the shared pre-action check, and make one sequential corrected complete save attempt. Do not rationalize a registry mismatch as a missing engine feature.\n6. After success, follow the shared summary rules and end with the concrete run command \\`/workflows run <id> {…}\\` for the requested workflow. If you saved helper workflows, name them so the user knows they now exist in the registry.\n`,\n // Same dynamic model resolver mastracode's main code-agent uses — picks up\n // the user's configured provider/model from session state. When the parent\n // code-agent delegates to this sub-agent (via `create-workflow`), the\n // request context propagates so the same model resolves.\n model: getDynamicModel,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAqBA,MAAa,uBAAuB,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AAc,CAAC,EAAE,uBAAuB,CAAC;IACzC,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC,wEAAwE;IACxE,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,gEA2EA;AAED;;;;;;;GAOG;AACH,wBAAsB,iBAAiB,CAAC,EACtC,cAAc,EACd,MAAM,GACP,EAAE;IACD,cAAc,EAAE,cAAc,CAAC;IAC/B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAclC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"workspace.js","names":[],"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig, SkillSource } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings, resolveLspSetting } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { isPathWithinRoot } from '../utils/path-security.js';\nimport { getPlansDir } from '../utils/plans.js';\n\nimport { createMastraCodeWorkspaceTools, GOAL_JUDGE_READONLY_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[], allowedRoot?: string): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n let realAllowedRoot: string | undefined;\n\n if (allowedRoot) {\n try {\n realAllowedRoot = fs.realpathSync(allowedRoot);\n } catch {\n return [];\n }\n }\n\n for (const skillsDir of skillsDirs) {\n const skillsDirExists = fs.existsSync(skillsDir);\n if (skillsDirExists && realAllowedRoot) {\n try {\n const realSkillsDir = fs.realpathSync(skillsDir);\n if (!isPathWithinRoot(realSkillsDir, realAllowedRoot)) continue;\n } catch {\n continue;\n }\n }\n\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!skillsDirExists) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n try {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n if (realAllowedRoot && !isPathWithinRoot(realPath, realAllowedRoot)) continue;\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (realAllowedRoot && !isPathWithinRoot(realParent, realAllowedRoot)) continue;\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n } catch {\n continue;\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n const paths = [\n ...collectSkillPaths([mastraCodeLocalSkillsPath, claudeLocalSkillsPath, agentSkillsLocalPath], projectPath),\n ...collectSkillPaths([mastraCodeGlobalSkillsPath, claudeGlobalSkillsPath, agentSkillsGlobalPath]),\n ...pluginSkillPaths.flatMap(pluginSkillPath => collectSkillPaths([pluginSkillPath], pluginSkillPath)),\n ];\n\n const seenPaths = new Set<string>();\n return paths.filter(skillPath => {\n let resolved: string;\n try {\n resolved = fs.realpathSync(skillPath);\n } catch {\n resolved = path.resolve(skillPath);\n }\n if (seenPaths.has(resolved)) return false;\n seenPaths.add(resolved);\n return true;\n });\n}\n\nexport interface WorkspaceSkillExtension {\n /** Distinguishes extended workspaces from the default resolver cache. */\n id: string;\n /** Additional read-only skill roots prepended to normal project/global skill roots. */\n paths: string[];\n /** Compose the additional roots with the workspace's normal skill source. */\n createSource: (fallback: SkillSource, fallbackSkillRoots: string[]) => SkillSource;\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n skillExtension,\n backgroundToolsEnabled = false,\n plansDir,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n skillExtension?: WorkspaceSkillExtension;\n backgroundToolsEnabled?: boolean;\n /** Host-configured plans directory the plan-mode write guard allows. */\n plansDir?: string;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const projectSkillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const skillPaths = [...(skillExtension?.paths ?? []), ...projectSkillPaths];\n const extensionId = skillExtension ? `-${skillExtension.id}` : '';\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}${extensionId}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [\n ...projectSkillPaths,\n ...DEFAULT_ALLOWED_PATHS,\n ...sandboxPaths.map((p: string) => path.resolve(p)),\n ];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = createMastraCodeWorkspaceTools(backgroundToolsEnabled, plansDir);\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n // LSP is opt-in. When disabled we pass `false` so core skips the dependency\n // check, the LSP manager, and the `lsp_inspect` tool entirely.\n const userLsp = resolveLspSetting(loadSettings().lsp);\n let lspConfig: LSPConfig | false = false;\n if (userLsp !== false) {\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n lspConfig = {\n maxOpenClients: 4,\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n }\n\n // First call for this project — create the workspace\n const filesystem = new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n });\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem,\n sandbox: new LocalSandbox({\n timeout: 30_000,\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n skills: skillPaths,\n ...(skillExtension ? { skillSource: skillExtension.createSource(filesystem, projectSkillPaths) } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":";;;;;;;;;;;AAsBA,SAAS,kBAAqC;CAC5C,OAAO;EACL,GAAG,QAAQ;EAEX,aAAa;EACb,gBAAgB;EAChB,MAAM,QAAQ,IAAI,QAAQ;EAC1B,IAAI;EACJ,gBAAgB;EAChB,iBAAiB;CACnB;AACF;AAkBA,SAAS,kBAAkB,YAAsB,aAAgC;CAC/E,MAAM,QAAkB,CAAC;CACzB,MAAM,uBAAO,IAAI,IAAY;CAC7B,IAAI;CAEJ,IAAI,aACF,IAAI;EACF,kBAAkB,GAAG,aAAa,WAAW;CAC/C,QAAQ;EACN,OAAO,CAAC;CACV;CAGF,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,kBAAkB,GAAG,WAAW,SAAS;EAC/C,IAAI,mBAAmB,iBACrB,IAAI;GACF,MAAM,gBAAgB,GAAG,aAAa,SAAS;GAC/C,IAAI,CAAC,iBAAiB,eAAe,eAAe,GAAG;EACzD,QAAQ;GACN;EACF;EAGF,MAAM,WAAW,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;GACvB,KAAK,IAAI,QAAQ;GACjB,MAAM,KAAK,SAAS;EACtB;EAEA,IAAI,CAAC,iBAAiB;EAEtB,IAAI;GACF,MAAM,UAAU,GAAG,YAAY,WAAW,EAAE,eAAe,KAAK,CAAC;GACjE,KAAK,MAAM,SAAS,SAClB,IAAI,MAAM,eAAe,GACvB,IAAI;IACF,MAAM,WAAW,KAAK,KAAK,WAAW,MAAM,IAAI;IAChD,MAAM,WAAW,GAAG,aAAa,QAAQ;IACzC,IAAI,mBAAmB,CA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ytics.d.ts","sourceRoot":"","sources":["../src/analytics.ts"],"names":[],"mappings":"AAqCA,wBAAgB,4BAA4B,CAAC,UAAU,SAAwB,GAAG,MAAM,CAmBvF;AAeD,MAAM,MAAM,wBAAwB,GAChC,4BAA4B,GAC5B,6BAA6B,GAC7B,2BAA2B,GAC3B,0BAA0B,GAC1B,yBAAyB,GACzB,qCAAqC,CAAC;AAE1C,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,KAAK,EAAE,wBAAwB,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACrF,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1E,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACvF,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,SAAS,IAAI,OAAO,CAAC;CACtB;AAED,UAAU,0BAA0B;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AA8FD,wBAAgB,mBAAmB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAOjF;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,GAAG,mBAAmB,CAOlG"}
|
package/dist/analytics.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.js","names":[],"sources":["../src/analytics.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { PostHog } from 'posthog-node';\n\nconst POSTHOG_API_KEY = 'phc_SBLpZVAB6jmHOct9CABq3PF0Yn5FU3G2FgT4xUr2XrT';\nconst POSTHOG_HOST = 'https://us.posthog.com';\nconst MASTRA_SOURCE = 'mastracode';\nconst TRUTHY_DISABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);\nconst ANALYTICS_CONFIG_PATH = path.join(os.homedir(), '.mastracode', 'analytics.json');\n\ninterface AnalyticsConfig {\n distinctId?: string;\n}\n\nfunction createMastraAnalyticsDistinctId(): string {\n return `mastra-${globalThis.crypto.randomUUID()}`;\n}\n\nfunction isHostnameDerivedDistinctId(distinctId: string, hostname = os.hostname()): boolean {\n return distinctId === `mastra-${hostname}`;\n}\n\nfunction isValidMastraAnalyticsDistinctId(distinctId: string): boolean {\n return /^mastra-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(distinctId);\n}\n\nfunction writeAnalyticsConfig(distinctId: string, configPath = ANALYTICS_CONFIG_PATH): void {\n try {\n mkdirSync(path.dirname(configPath), { recursive: true });\n writeFileSync(configPath, JSON.stringify({ distinctId }));\n } catch {\n // swallow analytics persistence errors\n }\n}\n\nexport function getMastraAnalyticsDistinctId(configPath = ANALYTICS_CONFIG_PATH): string {\n try {\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, 'utf-8')) as AnalyticsConfig;\n if (\n config.distinctId &&\n isValidMastraAnalyticsDistinctId(config.distinctId) &&\n !isHostnameDerivedDistinctId(config.distinctId)\n ) {\n return config.distinctId;\n }\n }\n } catch {\n // regenerate below\n }\n\n const distinctId = createMastraAnalyticsDistinctId();\n writeAnalyticsConfig(distinctId, configPath);\n return distinctId;\n}\n\nfunction isAnalyticsDebugEnabled(): boolean {\n return TRUTHY_DISABLED_VALUES.has(process.env.MASTRACODE_ANALYTICS_DEBUG?.trim().toLowerCase() ?? '');\n}\n\nfunction debugAnalytics(message: string, properties?: Record<string, unknown>): void {\n if (!isAnalyticsDebugEnabled()) {\n return;\n }\n\n const suffix = properties ? ` ${JSON.stringify(properties)}` : '';\n process.stderr.write(`[mastracode analytics] ${message}${suffix}\\n`);\n}\n\nexport type MastraCodeAnalyticsEvent =\n | 'mastracode_session_started'\n | 'mastracode_prompt_submitted'\n | 'mastracode_thread_changed'\n | 'mastracode_model_changed'\n | 'mastracode_command_used'\n | 'mastracode_interactive_prompt_shown';\n\nexport interface MastraCodeAnalytics {\n capture(event: MastraCodeAnalyticsEvent, properties?: Record<string, unknown>): void;\n trackCommand(command: string, properties?: Record<string, unknown>): void;\n trackInteractivePrompt(promptType: string, properties?: Record<string, unknown>): void;\n shutdown(): Promise<void>;\n isEnabled(): boolean;\n}\n\ninterface MastraCodeAnalyticsOptions {\n version: string;\n host?: string;\n apiKey?: string;\n}\n\nclass NoopMastraCodeAnalytics implements MastraCodeAnalytics {\n capture(event: MastraCodeAnalyticsEvent): void {\n debugAnalytics('capture skipped: telemetry disabled', { event });\n }\n trackCommand(command: string): void {\n debugAnalytics('command skipped: telemetry disabled', { command });\n }\n trackInteractivePrompt(promptType: string): void {\n debugAnalytics('interactive prompt skipped: telemetry disabled', { promptType });\n }\n async shutdown(): Promise<void> {\n debugAnalytics('shutdown skipped: telemetry disabled');\n }\n isEnabled(): boolean {\n return false;\n }\n}\n\nclass PostHogMastraCodeAnalytics implements MastraCodeAnalytics {\n private readonly client: PostHog;\n private readonly distinctId: string;\n private readonly sessionId = globalThis.crypto.randomUUID();\n private readonly version: string;\n\n constructor({ version, apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST }: MastraCodeAnalyticsOptions) {\n this.version = version;\n this.distinctId = getMastraAnalyticsDistinctId();\n this.client = new PostHog(apiKey, {\n host,\n flushAt: 1,\n flushInterval: 0,\n disableGeoip: false,\n });\n this.client.register({ mastraSource: MASTRA_SOURCE });\n debugAnalytics('enabled', { host, distinctId: this.distinctId, version });\n }\n\n capture(event: MastraCodeAnalyticsEvent, properties?: Record<string, unknown>): void {\n try {\n const eventProperties = {\n ...this.getBaseProperties(),\n ...properties,\n };\n debugAnalytics('capture', { event, properties: eventProperties });\n this.client.capture({\n distinctId: this.distinctId,\n event,\n properties: eventProperties,\n });\n } catch (error) {\n debugAnalytics('capture failed', { event, error: error instanceof Error ? error.message : String(error) });\n // swallow analytics errors\n }\n }\n\n trackCommand(command: string, properties?: Record<string, unknown>): void {\n this.capture('mastracode_command_used', { command, ...properties });\n }\n\n trackInteractivePrompt(promptType: string, properties?: Record<string, unknown>): void {\n this.capture('mastracode_interactive_prompt_shown', { promptType, ...properties });\n }\n\n async shutdown(): Promise<void> {\n try {\n debugAnalytics('shutdown start');\n await this.client.shutdown();\n debugAnalytics('shutdown complete');\n } catch (error) {\n debugAnalytics('shutdown failed', { error: error instanceof Error ? error.message : String(error) });\n // swallow analytics errors\n }\n }\n\n isEnabled(): boolean {\n return true;\n }\n\n private getBaseProperties(): Record<string, unknown> {\n return {\n mastraSource: MASTRA_SOURCE,\n sessionId: this.sessionId,\n version: this.version,\n os: process.platform,\n osVersion: os.release(),\n nodeVersion: process.version,\n platform: process.arch,\n machineId: os.hostname(),\n };\n }\n}\n\nexport function isTelemetryDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const value = env.MASTRA_TELEMETRY_DISABLED;\n if (!value) {\n return false;\n }\n\n return TRUTHY_DISABLED_VALUES.has(value.trim().toLowerCase());\n}\n\nexport function createMastraCodeAnalytics(options: MastraCodeAnalyticsOptions): MastraCodeAnalytics {\n if (isTelemetryDisabled()) {\n debugAnalytics('disabled by MASTRA_TELEMETRY_DISABLED', { value: process.env.MASTRA_TELEMETRY_DISABLED });\n return new NoopMastraCodeAnalytics();\n }\n\n return new PostHogMastraCodeAnalytics(options);\n}\n"],"mappings":";;;;;AAMA,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,yCAAyB,IAAI,IAAI;CAAC;CAAK;CAAQ;CAAO;AAAI,CAAC;AACjE,MAAM,wBAAwB,KAAK,KAAK,GAAG,QAAQ,GAAG,eAAe,gB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