@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
package/dist/auth/storage.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":[],"sources":["../../src/auth/storage.ts"],"sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n */\n\nimport { createHash } from 'node:crypto';\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { getAppDataDir } from '../utils/project.js';\nimport { anthropicOAuthProvider } from './providers/anthropic.js';\nimport { githubCopilotOAuthProvider } from './providers/github-copilot.js';\nimport { kimiCodingOAuthProvider } from './providers/kimi-coding.js';\nimport { openaiCodexOAuthProvider } from './providers/openai-codex.js';\nimport { xaiOAuthProvider } from './providers/xai.js';\nimport type {\n AuthCredential,\n AuthStorageData,\n OAuthAccountRecord,\n OAuthCredential,\n OAuthCredentialSnapshot,\n OAuthCredentials,\n OAuthLoginCallbacks,\n OAuthProviderId,\n OAuthProviderInterface,\n} from './types.js';\n\n/**\n * API keys this process exported to environment variables, keyed by variable name.\n * `previous` is the value the variable held before the first export, so removing the\n * key can restore it. Module-level because `process.env` is shared by every instance.\n */\nconst exportedApiKeys = new Map<string, { provider: string; key: string; previous: string | undefined }>();\n\nfunction exportApiKey(envVar: string, provider: string, key: string): void {\n const exported = exportedApiKeys.get(envVar);\n // Saving again keeps the value from before the first export.\n const previous = exported && process.env[envVar] === exported.key ? exported.previous : process.env[envVar];\n exportedApiKeys.set(envVar, { provider, key, previous });\n process.env[envVar] = key;\n}\n\n/**\n * Best/default models for each OAuth provider.\n * Used when auto-selecting a model after login.\n */\nexport const PROVIDER_DEFAULT_MODELS: Record<OAuthProviderId, string> = {\n anthropic: 'anthropic/claude-fable-5',\n 'openai-codex': 'openai/gpt-5.6-sol',\n // gpt-4.1 routes through `/chat/completions` (which our OpenAI-compatible\n // adapter handles); Anthropic-shaped Copilot models (Claude on `/v1/messages`)\n // are not yet wired up, so picking one as the post-login default would error.\n 'github-copilot': 'github-copilot/gpt-4.1',\n 'kimi-for-coding': 'kimi-code-plan-cn/kimi-for-coding',\n xai: 'xai/grok-4.5',\n};\n\n// Provider registry\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>([\n [anthropicOAuthProvider.id, anthropicOAuthProvider],\n [openaiCodexOAuthProvider.id, openaiCodexOAuthProvider],\n [githubCopilotOAuthProvider.id, githubCopilotOAuthProvider],\n [kimiCodingOAuthProvider.id, kimiCodingOAuthProvider],\n [xaiOAuthProvider.id, xaiOAuthProvider],\n]);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n return oauthProviderRegistry.get(id);\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n return Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * Mint an account instance id: `${providerId}:${randomUUID()}`.\n *\n * Assigned once, when the account is created, and never derived from\n * credentials. Deriving it from the refresh token (the pre-A13 scheme) looked\n * stable but was not: `persistRefreshedCredential` keeps an entry's key while\n * writing rotated tokens onto it, so every refresh left the id describing a\n * credential the account no longer had — and re-adding that same subscription\n * then failed to match its own entry and registered a second one for it.\n */\nfunction mintAccountId(providerId: string): string {\n return `${providerId}:${globalThis.crypto.randomUUID()}`;\n}\n\n/**\n * The pre-A13 id scheme: `${providerId}:${sha256(refresh).slice(0,8)}`.\n *\n * No longer used to assign ids, but still needed to recognize registries\n * written before A13 — both to match a re-authorized account onto its existing\n * entry, and to recognize entries whose fields the A13 migration must backfill.\n */\nfunction legacyAccountIdFor(providerId: string, refreshToken: string): string {\n return `${providerId}:${createHash('sha256').update(refreshToken).digest('hex').slice(0, 8)}`;\n}\n\n/**\n * Stable identity for the *subscription* behind an account, when the provider\n * exposes one (an account id, an email — anything that survives a refresh and\n * a re-authorization). Used to decide whether an added account is one we\n * already have. Providers whose credentials carry no such identifier return\n * undefined; for those, a re-authorization is indistinguishable from a new\n * account without spending a request.\n */\nfunction providerIdentity(provider: OAuthProviderInterface | undefined, creds: OAuthCredentials): string | undefined {\n try {\n const identity = provider?.getAccountIdentity?.(creds);\n return typeof identity === 'string' && identity.length > 0 ? identity : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isOAuthAccountRecord(value: unknown): value is OAuthAccountRecord {\n if (!value || typeof value !== 'object') return false;\n const v = value as Partial<OAuthAccountRecord>;\n return (\n v.type === 'oauth-account' &&\n typeof v.id === 'string' &&\n typeof v.label === 'string' &&\n typeof v.addedAt === 'string' &&\n typeof v.active === 'boolean' &&\n typeof v.refresh === 'string' &&\n typeof v.access === 'string' &&\n typeof v.expires === 'number'\n );\n}\n\n/** The credential fields of an account record — everything but registry identity. */\nfunction credentialFieldsOf(record: OAuthAccountRecord): OAuthCredentials {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n identity: _identity,\n ...creds\n } = record;\n return creds;\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n private data: AuthStorageData = {};\n private refreshPromises = new Map<string, Promise<OAuthCredentials | undefined>>();\n\n constructor(private authPath: string = join(getAppDataDir(), 'auth.json')) {\n this.reload();\n }\n\n /**\n * Reload credentials from disk.\n */\n reload(): void {\n if (!existsSync(this.authPath)) {\n this.data = {};\n return;\n }\n try {\n this.data = JSON.parse(readFileSync(this.authPath, 'utf-8'));\n } catch {\n this.data = {};\n }\n this.migrate();\n }\n\n /**\n * Bring auth.json up to the multi-account registry format. Runs on every\n * load; saves only when something actually changed.\n *\n * 1. A legacy OAuth slot with no registry gets one adopted active entry\n * (the slot's tokens stay put — the entry mirrors them).\n * 2. When the slot's refresh token differs from the active entry's, an\n * external writer (older build, another worktree) owns the slot — the\n * slot wins and its tokens are adopted onto the active entry.\n * 3. A registry with no active entry (hand-edited) self-heals to its first\n * entry; malformed `accounts:` values are skipped, never fatal.\n * 4. A registry whose legacy slot disappeared (partial write, an external\n * hand-edit) self-heals by mirroring the active entry's tokens back into\n * the slot, so `isLoggedIn()`/`getOAuthCredential()` keep agreeing with\n * `listAccounts()`. `remove()`/`logout()` clear the registry with the\n * slot, so they never leave the shape this heals.\n */\n private migrate(): void {\n let changed = false;\n for (const key of Object.keys(this.data)) {\n const slot = this.data[key];\n if (!slot || slot.type !== 'oauth') continue;\n const providerId = key;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) {\n this.adoptSlot(providerId, slot);\n changed = true;\n continue;\n }\n const active = entries.find(entry => entry.active);\n if (!active) {\n this.data[this.accountKeyFor(entries[0]!.id)] = { ...entries[0]!, active: true };\n changed = true;\n continue;\n }\n if (active.refresh !== slot.refresh) {\n // An external writer (older build, another worktree) owns the slot.\n // If its tokens belong to a different registered account, that\n // account is now the active one — re-point activation to it instead\n // of cloning the refresh token onto the current active entry.\n const matching = entries.find(entry => entry.id !== active.id && entry.refresh === slot.refresh);\n if (matching) {\n const { type: _t, ...slotCreds } = slot;\n this.data[this.accountKeyFor(matching.id)] = {\n ...matching,\n ...slotCreds,\n type: 'oauth-account',\n active: true,\n };\n this.data[this.accountKeyFor(active.id)] = { ...active, active: false };\n changed = true;\n } else {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(active.id)] = { ...active, ...slotCreds, type: 'oauth-account' };\n changed = true;\n }\n }\n }\n\n // Case 4: registry entries without a legacy slot (the slot loop above\n // only ever sees providers that still have one).\n const registeredProviders = new Set<string>();\n for (const key of Object.keys(this.data)) {\n if (!key.startsWith('accounts:')) continue;\n const providerId = key.slice('accounts:'.length).split(':')[0];\n if (providerId) registeredProviders.add(providerId);\n }\n for (const providerId of registeredProviders) {\n if (this.data[providerId]?.type === 'oauth') continue;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) continue;\n let active = entries.find(entry => entry.active);\n if (!active) {\n active = entries[0]!;\n this.data[this.accountKeyFor(active.id)] = { ...active, active: true };\n }\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(active) };\n changed = true;\n }\n\n // Case 5 (A13): backfill the stable account identity on entries that\n // predate it, so adding a subscription we already hold updates its entry\n // instead of registering a second one for it.\n //\n // Ids are deliberately left exactly as they are. Ids are minted once and\n // derive from nothing (A13), so there is nothing to repair — and re-keying\n // a live registry would invalidate every id persisted outside this file\n // (settings routing preferences, per-thread routing state) for no gain.\n for (const providerId of registeredProviders) {\n const provider = getOAuthProvider(providerId as OAuthProviderId);\n if (!provider?.getAccountIdentity) continue;\n for (const entry of this.accountEntries(providerId)) {\n if (entry.identity) continue;\n const identity = providerIdentity(provider, entry);\n if (!identity) continue;\n this.data[this.accountKeyFor(entry.id)] = { ...entry, identity };\n changed = true;\n }\n }\n\n if (changed) this.save();\n }\n\n /**\n * Save credentials to disk.\n */\n private save(): void {\n const dir = dirname(this.authPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n // Write to a sibling file, then atomically replace auth.json. Provider\n // fetch wrappers reload this file on every request, including in older\n // Mastra Code processes; writing in place lets them observe truncated JSON\n // and temporarily treat every provider as logged out.\n const tempPath = `${this.authPath}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, JSON.stringify(this.data, null, 2), { encoding: 'utf-8', mode: 0o600 });\n chmodSync(tempPath, 0o600);\n renameSync(tempPath, this.authPath);\n } finally {\n rmSync(tempPath, { force: true });\n }\n }\n\n /**\n * Get credential for a provider. Registry entries (type 'oauth-account')\n * live under `accounts:` keys and never surface here.\n */\n get(provider: string): AuthCredential | undefined {\n const cred = this.data[provider];\n return cred !== undefined && cred.type !== 'oauth-account' ? cred : undefined;\n }\n\n /**\n * Set credential for a provider.\n */\n set(provider: string, credential: AuthCredential): void {\n this.reload();\n this.data[provider] = credential;\n this.save();\n }\n\n /**\n * Remove credential for a provider, including its account registry.\n * Clearing only the slot would leave the registry behind, and the next\n * load's migration would heal the slot back from it — resurrecting the\n * provider the caller just signed out.\n */\n remove(provider: string): void {\n this.reload();\n delete this.data[provider];\n const prefix = this.accountPrefixFor(provider);\n for (const key of Object.keys(this.data)) {\n if (key.startsWith(prefix)) delete this.data[key];\n }\n this.save();\n }\n\n /**\n * List all providers with credentials.\n */\n list(): string[] {\n return Object.keys(this.data);\n }\n\n /**\n * Check if credentials exist for a provider.\n */\n has(provider: string): boolean {\n return provider in this.data;\n }\n\n /**\n * Check if logged in via OAuth for a provider.\n */\n isLoggedIn(provider: string): boolean {\n const cred = this.data[provider];\n return cred?.type === 'oauth';\n }\n\n /**\n * Check if a stored API key exists for a provider.\n * Keys are stored under `apikey:<provider>` in auth.json.\n */\n hasStoredApiKey(provider: string): boolean {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0;\n }\n\n /**\n * Get a stored API key for a provider, if any.\n */\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0 ? cred.key : undefined;\n }\n\n /**\n * Store an API key for a provider.\n * Also sets the corresponding environment variable so model resolution can find it.\n */\n setStoredApiKey(provider: string, key: string, envVar?: string): void {\n this.set(`apikey:${provider}`, { type: 'api_key', key });\n if (envVar) {\n exportApiKey(envVar, provider, key);\n }\n }\n\n /**\n * Remove a stored API key for a provider.\n * Also undoes the environment variable export done by {@link setStoredApiKey} or\n * {@link loadStoredApiKeysIntoEnv}: the variable gets back the value it had before\n * (for example the key the process was started with), or is unset if it had none.\n * A variable changed since the export is left alone.\n */\n removeStoredApiKey(provider: string): void {\n this.remove(`apikey:${provider}`);\n for (const [envVar, exported] of exportedApiKeys) {\n if (exported.provider !== provider) continue;\n exportedApiKeys.delete(envVar);\n if (process.env[envVar] !== exported.key) continue;\n if (exported.previous === undefined) delete process.env[envVar];\n else process.env[envVar] = exported.previous;\n }\n }\n\n /**\n * Load all stored API keys into process.env.\n * Called at startup so model resolution can find stored keys.\n * Only sets env vars that aren't already set (env vars take precedence).\n */\n loadStoredApiKeysIntoEnv(providerEnvVars: Record<string, string | undefined>): void {\n for (const [key, cred] of Object.entries(this.data)) {\n if (!key.startsWith('apikey:') || cred.type !== 'api_key' || !cred.key) continue;\n const provider = key.substring('apikey:'.length);\n const envVar = providerEnvVars[provider];\n if (envVar && !process.env[envVar]) {\n exportApiKey(envVar, provider, cred.key);\n }\n }\n }\n\n /**\n * Login to an OAuth provider. Resolves to the registered account record.\n * Pass `activate: false` to add the account without making it active (the\n * first account for a provider is always activated — a provider with\n * accounts must have an active one).\n */\n async login(\n providerId: OAuthProviderId,\n callbacks: OAuthLoginCallbacks,\n opts?: { replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n const provider = getOAuthProvider(providerId);\n if (!provider) {\n throw new Error(`Unknown OAuth provider: ${providerId}`);\n }\n\n const credentials = await provider.login(callbacks);\n // Route through the account registry: the new account is appended (or\n // updated in place — by id collision or an explicit replaceAccountId for\n // re-authentication) and becomes the active account unless activate:false.\n return this.addAccount(providerId, credentials, opts);\n }\n\n /**\n * Logout from a provider: remove the legacy slot and every registered account.\n */\n logout(provider: string): void {\n this.remove(provider);\n }\n\n // ---------------------------------------------------------------------------\n // Multi-account registry\n // ---------------------------------------------------------------------------\n\n private accountPrefixFor(providerId: string): string {\n return `accounts:${providerId}:`;\n }\n\n private accountKeyFor(id: string): string {\n return `accounts:${id}`;\n }\n\n /** Registry entries for a provider in JSON insertion order (malformed values skipped). */\n private accountEntries(providerId: string): OAuthAccountRecord[] {\n const prefix = this.accountPrefixFor(providerId);\n const out: OAuthAccountRecord[] = [];\n for (const [key, value] of Object.entries(this.data)) {\n if (key.startsWith(prefix) && isOAuthAccountRecord(value)) out.push(value);\n }\n return out;\n }\n\n /** Adopt a legacy slot credential as the registry's first active entry. */\n private adoptSlot(providerId: string, slot: OAuthCredential): OAuthAccountRecord {\n const id = mintAccountId(providerId);\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, slot);\n const record: OAuthAccountRecord = {\n ...slot,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: `${provider?.name ?? providerId} account 1`,\n addedAt: new Date().toISOString(),\n active: true,\n };\n this.data[this.accountKeyFor(id)] = record;\n return record;\n }\n\n /**\n * Registered OAuth accounts for a provider, in insertion order. Copies —\n * callers cannot corrupt unsaved storage state by mutating a record.\n */\n listAccounts(providerId: string): OAuthAccountRecord[] {\n return this.accountEntries(providerId).map(entry => ({ ...entry }));\n }\n\n /**\n * The provider's active registry entry, if a registry exists. A copy.\n */\n getActiveAccount(providerId: string): OAuthAccountRecord | undefined {\n const active = this.accountEntries(providerId).find(entry => entry.active);\n return active ? { ...active } : undefined;\n }\n\n /**\n * Register OAuth credentials as an account for a provider, making it active\n * unless `activate: false` is passed.\n *\n * With `replaceAccountId` (re-authentication of a picked account), the\n * target entry's tokens are replaced in place — id re-keyed to the new\n * refresh-token hash, label/position/addedAt preserved — because providers\n * rotate refresh tokens per authorization, so the picked account's old id\n * never matches the new token hash. Re-authentication keeps the target's\n * active state: an inactive account stays inactive and the currently active\n * account keeps the legacy slot. Otherwise, when the new credentials\n * hash to an existing entry's id (same refresh token), that entry is\n * updated in place; a genuinely new account is appended and activated.\n *\n * `activate: false` only applies to the plain add path: the new/updated entry\n * keeps the active state it had, and the previously active account stays\n * active. The first account of a provider is activated regardless.\n */\n async addAccount(\n providerId: string,\n creds: OAuthCredentials,\n opts?: { label?: string; replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n this.reload();\n const entries = this.accountEntries(providerId);\n\n if (opts?.replaceAccountId) {\n const target = entries.find(entry => entry.id === opts.replaceAccountId);\n if (!target) {\n throw new Error(`No account ${opts.replaceAccountId} for provider ${providerId}`);\n }\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds) ?? target.identity;\n // Re-authentication updates the account in place and **keeps its id**:\n // ids are minted once and never derived from credentials (A13), so the\n // entry's insertion position, the settings routing preference and any\n // thread routing state that name this id all stay valid.\n //\n // A stale entry for the *same* subscription is dropped in favor of the\n // picked account. Same-subscription is a matching stable identity, or —\n // for a registry written before A13, whose ids were the refresh-token\n // hash — the credentials' own legacy id, or an entry already holding\n // exactly these credentials (a re-authorization that returns the same\n // tokens, the only signal an identity-less provider gives). The survivor\n // inherits the collided entry's active state, so re-authenticating an\n // inactive account onto the active account's credentials cannot leave the\n // registry with no active entry.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const collided = entries.find(\n entry =>\n entry.id !== target.id &&\n ((identity !== undefined && entry.identity === identity) ||\n entry.id === legacyId ||\n entry.refresh === creds.refresh),\n );\n // Credential metadata (device id, enterprise URL, …) follows the tokens:\n // when the fresh response omits a field, the collided entry's value is the\n // coherent fallback, not the target's — pairing fresh tokens with another\n // subscription's stale endpoint would misroute requests. Fresh `creds`\n // win last; only the target's registry metadata (id, label, addedAt)\n // carries over.\n const replacement: OAuthAccountRecord = {\n ...target,\n ...(collided ? credentialFieldsOf(collided) : {}),\n ...creds,\n type: 'oauth-account',\n ...(identity ? { identity } : {}),\n label: opts.label ?? target.label,\n };\n const rebuilt: AuthStorageData = {};\n for (const [key, value] of Object.entries(this.data)) {\n if (key === this.accountKeyFor(target.id)) {\n rebuilt[key] = collided?.active ? { ...replacement, active: true } : replacement;\n } else if (collided && key === this.accountKeyFor(collided.id)) {\n continue;\n } else {\n rebuilt[key] = value;\n }\n }\n this.data = rebuilt;\n // Re-authentication preserves the account's active state: fixing a\n // secondary account's tokens must not hijack the active slot. The target\n // is activated when it was already active, when the entry it collided\n // with was active, or when the provider has no active account at all\n // (first account, or a self-healed gap).\n const wasActive =\n target.active === true ||\n collided?.active === true ||\n entries.some(entry => entry.active && entry.id !== target.id) === false;\n if (wasActive) {\n const activated = this.activateInMemory(providerId, target.id);\n if (!activated) {\n throw new Error(`Failed to activate account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n // Inactive target: tokens stay on the registry entry, the legacy slot\n // keeps the currently active account's credential untouched.\n const replacementEntry = this.accountEntries(providerId).find(entry => entry.id === target.id);\n if (!replacementEntry) {\n throw new Error(`Failed to store account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return replacementEntry;\n }\n\n // Resolve the label before the final reload+save: the provider hook may\n // hit the network, and a concurrent write during that await must not be\n // clobbered by a stale snapshot.\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds);\n const label = opts?.label ?? (await provider?.getAccountLabel?.(creds)) ?? null;\n this.reload();\n const freshEntries = this.accountEntries(providerId);\n\n // Is this a subscription we already hold? Match the provider's stable\n // account identity where it exposes one, then the pre-A13 id (the\n // refresh-token hash) so a pre-A13 registry still updates its entry rather\n // than gaining a second one for the same subscription, and finally an\n // entry already holding these exact credentials (a re-add of the same\n // account as returned, which is the only signal an identity-less provider\n // such as Anthropic gives us — a provider that cannot name its accounts\n // cannot say \"this is the same subscription, re-authorized\").\n //\n // Crucially this must not re-derive the id of a *minted* entry: after a\n // refresh such an entry's id no longer hashes its current token, and\n // treating that miss as \"new account\" is exactly how re-adding a\n // subscription used to create a duplicate entry for it.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const existing =\n (identity ? freshEntries.find(entry => entry.identity === identity) : undefined) ??\n freshEntries.find(entry => entry.id === legacyId) ??\n freshEntries.find(entry => entry.refresh === creds.refresh);\n const id = existing?.id ?? mintAccountId(providerId);\n if (existing) {\n this.data[this.accountKeyFor(id)] = {\n ...existing,\n ...creds,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n active: existing.active,\n };\n } else {\n const resolvedLabel = label ?? `${provider?.name ?? providerId} account ${freshEntries.length + 1}`;\n this.data[this.accountKeyFor(id)] = {\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: resolvedLabel,\n addedAt: new Date().toISOString(),\n active: false,\n ...creds,\n };\n }\n\n // activate:false (add-another): keep the current active account. The\n // first account of a provider always activates — a non-empty registry\n // must have an active entry. An id collision with the already-active\n // entry also falls through to activateInMemory so its fresh tokens move\n // into the legacy slot (tokens are single-homed).\n if (opts?.activate === false && freshEntries.length > 0 && !existing?.active) {\n this.save();\n return { ...(this.data[this.accountKeyFor(id)] as OAuthAccountRecord) };\n }\n\n const activated = this.activateInMemory(providerId, id);\n if (!activated) {\n throw new Error(`Failed to activate account ${id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n\n /**\n * Activate an account: move the active tokens out of the legacy slot back\n * into the previously active entry, and the target's tokens into the slot\n * (never copy — one home per token set). With no `instanceId`, rotate to\n * the next entry in insertion order, wrapping once to the front; returns\n * undefined when there is no other entry to rotate to.\n */\n activateAccount(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n this.reload();\n const activated = this.activateInMemory(providerId, instanceId);\n if (activated) this.save();\n return activated;\n }\n\n /**\n * Activate an account in memory only — the caller owns reload/save. Move the\n * active tokens out of the legacy slot back into the previously active\n * entry, and the target's tokens into the slot (never copy — one home per\n * token set). With no `instanceId`, rotate to the next entry in insertion\n * order, wrapping once to the front; returns undefined when there is no\n * other entry to rotate to.\n */\n private activateInMemory(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) return undefined;\n\n let target: OAuthAccountRecord | undefined;\n if (instanceId !== undefined) {\n target = entries.find(entry => entry.id === instanceId);\n if (!target) return undefined;\n } else {\n if (entries.length <= 1) return undefined;\n const currentIdx = entries.findIndex(entry => entry.active);\n const candidates =\n currentIdx >= 0 ? [...entries.slice(currentIdx + 1), ...entries.slice(0, currentIdx)] : [...entries];\n target = candidates[0]!;\n }\n if (!target) return undefined;\n\n const slot = this.data[providerId];\n const current = entries.find(entry => entry.active && entry.id !== target.id);\n\n // Move the slot's tokens back onto the previously active entry. Skipped\n // when the target is already active — its (possibly re-authenticated)\n // entry already holds the freshest tokens.\n if (current && slot?.type === 'oauth') {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(current.id)] = { ...current, ...slotCreds, type: 'oauth-account', active: false };\n }\n\n // Move the target's tokens into the legacy slot. The slot is rebuilt from\n // the target's own credentials only: carrying fields over from the\n // previously active account would pair this account's tokens with that\n // account's metadata (`deviceId`, `enterpriseUrl`, account id), and the\n // providers read those fields off the slot.\n this.data[providerId] = { ...credentialFieldsOf(target), type: 'oauth' };\n\n // Exactly the target stays active (self-heals multi-active states).\n this.data[this.accountKeyFor(target.id)] = { ...target, active: true };\n for (const entry of entries) {\n if (entry.id === target.id || entry.id === current?.id) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n\n return { ...target, active: true };\n }\n\n /**\n * Remove an account from the registry. If it was active, the next entry in\n * insertion order is activated; when it was the last one, the legacy slot\n * is removed too (full sign-out for that provider).\n */\n removeAccount(providerId: string, instanceId: string): void {\n this.reload();\n const entries = this.accountEntries(providerId);\n const target = entries.find(entry => entry.id === instanceId);\n if (!target) return;\n\n const wasActive = target.active;\n delete this.data[this.accountKeyFor(instanceId)];\n\n if (wasActive) {\n const idx = entries.indexOf(target);\n const next = entries[idx + 1] ?? entries.find(entry => entry.id !== instanceId);\n if (next) {\n // The removed account's tokens die with it — only move tokens in.\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(next) };\n this.data[this.accountKeyFor(next.id)] = { ...next, active: true };\n for (const entry of entries) {\n if (entry.id === next.id || entry.id === instanceId) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n } else {\n delete this.data[providerId];\n }\n }\n\n this.save();\n }\n\n /**\n * Rename an account's label.\n */\n renameAccount(providerId: string, instanceId: string, label: string): void {\n this.reload();\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, label };\n this.save();\n }\n\n /**\n * Persist refreshed credentials for the account that initiated the refresh.\n * The legacy slot is updated only if that account is still active when the\n * refresh completes; otherwise a delayed refresh could overwrite a newer\n * activation.\n */\n private persistRefreshedCredential(\n providerId: string,\n instanceId: string | undefined,\n creds: OAuthCredentials,\n ): void {\n this.reload();\n if (instanceId) {\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, ...creds, type: 'oauth-account' };\n if (entry.active) {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n } else {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n this.save();\n }\n\n /**\n * Refresh one account instance through the per-instance dedupe map. Used\n * for sibling refreshes during the rotation walk, so a concurrent\n * `getApiKey` that reloads storage mid-walk (after the candidate was\n * activated but before its refresh resolves) joins the same refresh\n * instead of double-spending a single-use refresh token.\n */\n private async refreshInstance(\n providerId: string,\n instanceId: string,\n creds: OAuthCredentials,\n ): Promise<OAuthCredentials | undefined> {\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const refreshKey = `${providerId}:${instanceId}`;\n const pending = this.refreshPromises.get(refreshKey);\n if (pending) return pending;\n const refresh = (async () => {\n try {\n const fresh = await provider.refreshToken(creds);\n this.persistRefreshedCredential(providerId, instanceId, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n this.refreshPromises.set(refreshKey, refresh);\n try {\n return await refresh;\n } finally {\n this.refreshPromises.delete(refreshKey);\n }\n }\n\n /**\n * Get a ready-to-use OAuth credential snapshot, auto-refreshing if needed.\n * A failed refresh leaves the active account unchanged and returns undefined;\n * the account-rotation processor owns switching so it can persist a visible\n * account-switch notice with the request that triggered the change.\n */\n async getOAuthCredential(\n providerId: string,\n accountInstanceId?: string,\n ): Promise<OAuthCredentialSnapshot | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.data[providerId];\n let credential: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n credential = accountCredential;\n // The active account's credentials live in both the legacy slot and its\n // registry entry, and a legacy writer (older build, another worktree) can\n // refresh the slot without rotating the refresh token. `migrate()` only\n // reconciles those when the refresh token changes, so the registry entry\n // can hold stale access/expiry. Prefer the slot for the active account\n // and keep the registry entry as the account identity.\n if (selectedEntry.active && slot?.type === 'oauth' && slot.refresh === selectedEntry.refresh) {\n const { type: _slotType, ...slotCredential } = slot;\n credential = { ...credential, ...slotCredential };\n }\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n credential = slot;\n }\n if (!credential) return undefined;\n\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const selectedInstanceId = selectedEntry?.id;\n const toSnapshot = (credentials: OAuthCredentials): OAuthCredentialSnapshot => ({\n type: 'oauth',\n ...credentials,\n accountInstanceId: selectedInstanceId,\n });\n\n if (Date.now() < credential.expires) return toSnapshot(credential);\n\n if (selectedInstanceId) {\n const refreshed = await this.refreshInstance(providerId, selectedInstanceId, credential);\n return refreshed ? toSnapshot(refreshed) : undefined;\n }\n\n const pendingRefresh = this.refreshPromises.get(providerId);\n const refresh =\n pendingRefresh ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(credential);\n this.persistRefreshedCredential(providerId, undefined, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pendingRefresh) this.refreshPromises.set(providerId, refresh);\n try {\n const refreshed = await refresh;\n return refreshed ? toSnapshot(refreshed) : undefined;\n } finally {\n if (!pendingRefresh) this.refreshPromises.delete(providerId);\n }\n }\n\n /** Get API key for a provider, refreshing OAuth tokens if needed. */\n async getApiKey(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const cred = this.data[providerId];\n // A provider slot holding an API key belongs to the provider, not to any one\n // subscription, so it is only the right credential for a request that did\n // not select an account. A routed request must resolve the account it asked\n // for — or nothing — rather than be served this key.\n if (accountInstanceId === undefined && cred?.type === 'api_key') return cred.key;\n\n const oauth = await this.getOAuthCredential(providerId, accountInstanceId);\n const provider = oauth ? getOAuthProvider(providerId) : undefined;\n return oauth && provider ? provider.getApiKey(oauth) : undefined;\n }\n\n /**\n * Force one refresh of the active OAuth account's tokens, regardless of\n * expiry. The account-rotation error processor calls this when a provider\n * rejects a not-yet-expired token (401/403) — server-side clock skew and\n * refresh-token races surface that way. Returns the fresh access token, or\n * undefined when the refresh fails or there is no OAuth credential.\n * Shares the per-instance refresh dedupe with `getApiKey`.\n */\n async forceRefreshActiveAccount(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.get(providerId);\n let cred: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n cred = accountCredential;\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n cred = slot;\n }\n if (!cred) return undefined;\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n\n const refreshKey = selectedEntry ? `${providerId}:${selectedEntry.id}` : providerId;\n const pending = this.refreshPromises.get(refreshKey);\n const refresh =\n pending ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(cred);\n this.persistRefreshedCredential(providerId, selectedEntry?.id, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pending) this.refreshPromises.set(refreshKey, refresh);\n try {\n const creds = await refresh;\n return creds ? provider.getApiKey(creds) : undefined;\n } finally {\n if (!pending)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G,cAAc,OAAO;EACzE,MAAM,UAAU,KAAK,gBAAgB,IAAI,UAAU;EACnD,MAAM,UACJ,YACC,YAAmD;GAClD,IAAI;IACF,MAAM,QAAQ,MAAM,SAAS,aAAa,IAAI;IAC9C,KAAK,2BAA2B,YAAY,eAAe,IAAI,KAAK;IACpE,OAAO;GACT,QAAQ;IACN;GACF;EACF,EAAA,CAAG;EACL,IAAI,CAAC,SAAS,KAAK,gBAAgB,IAAI,YAAY,OAAO;EAC1D,IAAI;GACF,MAAM,QAAQ,MAAM;GACpB,OAAO,QAAQ,SAAS,UAAU,KAAK,IAAI,KAAA;EAC7C,UAAU;GACR,IAAI,CAAC,SAAS,KAAK,gBAAgB,OAAO,UAAU;EACtD;CACF;AACF"}
|
package/dist/auth/types.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,MAAM,eAAe,GAAG,MAAM,CAAC;AAErC,MAAM,WAAW,aAAa;IAC5B,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED;;;;;;GAMG;AACH,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM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AAG,OAAO,CAAC,uBAAuB,GAAG,SAAS,CAAC,CAAC;IAEhH;;;OAGG;IACH,YAAY,CAAC,CAAC,UAAU,EAAE,MAAM,GAAG,kBAAkB,EAAE,CAAC;IAExD,kEAAkE;IAClE,gBAAgB,CAAC,CAAC,UAAU,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAAC;IAEtE;;;;;;OAMG;IACH,eAAe,CAAC,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAAC;IAE1F,mFAAmF;IACnF,aAAa,CAAC,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/clipboard/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAgChD;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CA+BtD;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,IAAI,cAAc,GAAG,IAAI,CAYzD"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/clipboard/index.ts"],"sourcesContent":["/**\n * Platform-specific clipboard image extraction.\n *\n * Checks the system clipboard for image data and returns it as base64.\n * Uses synchronous execution (execSync) since this only runs on paste events.\n */\n\nimport { execSync } from 'node:child_process';\nimport { readFileSync, unlinkSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface ClipboardImage {\n data: string; // base64-encoded image data or a remote image URL\n mimeType: string;\n}\n\n/**\n * Read plain text from the system clipboard.\n * Returns null if clipboard is empty or reading fails.\n */\nexport function getClipboardText(): string | null {\n try {\n if (process.platform === 'darwin') {\n const text = execSync('pbpaste', {\n encoding: 'utf-8',\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return text.length > 0 ? text : null;\n }\n if (process.platform === 'linux') {\n // Try xclip first, then wl-paste\n try {\n const text = execSync('xclip -selection clipboard -o', {\n encoding: 'utf-8',\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return text.length > 0 ? text : null;\n } catch {\n const text = execSync('wl-paste', {\n encoding: 'utf-8',\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return text.length > 0 ? text : null;\n }\n }\n return null;\n } catch {\n return null;\n }\n}\n\n/**\n * Write plain text to the system clipboard.\n * Returns true on success, false on failure.\n */\nexport function setClipboardText(text: string): boolean {\n try {\n if (process.platform === 'darwin') {\n execSync('pbcopy', {\n input: text,\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return true;\n }\n if (process.platform === 'linux') {\n try {\n execSync('xclip -selection clipboard', {\n input: text,\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return true;\n } catch {\n execSync('wl-copy', {\n input: text,\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n return true;\n }\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Check the system clipboard for image data and return it as base64.\n * Returns null if no image data is found or extraction fails.\n */\nexport function getClipboardImage(): ClipboardImage | null {\n try {\n if (process.platform === 'darwin') {\n return getMacClipboardImage();\n }\n if (process.platform === 'linux') {\n return getLinuxClipboardImage();\n }\n return null;\n } catch {\n return null;\n }\n}\n\n// =============================================================================\n// macOS\n// =============================================================================\n\nfunction getMacClipboardImage(): ClipboardImage | null {\n return (\n tryReadMacClipboardImage({\n coercion: '«class PNGf»',\n extension: 'png',\n mimeType: 'image/png',\n }) ??\n tryReadMacClipboardImage({\n coercion: 'TIFF picture',\n extension: 'tiff',\n mimeType: 'image/tiff',\n }) ??\n tryReadMacClipboardImage({\n coercion: '«class TIFF»',\n extension: 'tiff',\n mimeType: 'image/tiff',\n })\n );\n}\n\nfunction tryReadMacClipboardImage({\n coercion,\n extension,\n mimeType,\n}: {\n coercion: string;\n extension: string;\n mimeType: string;\n}): ClipboardImage | null {\n const tmpFile = join(tmpdir(), `mastra-clipboard-${Date.now()}.${extension}`);\n\n try {\n const script = `\n\t\t\tset theImage to the clipboard as ${coercion}\n\t\t\tset theFile to open for access POSIX file \"${tmpFile}\" with write permission\n\t\t\twrite theImage to theFile\n\t\t\tclose access theFile\n\t\t`;\n execSync(`osascript -e '${script.replace(/'/g, \"'\\\\''\")}'`, {\n timeout: 5000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n const buffer = readFileSync(tmpFile);\n if (!Buffer.isBuffer(buffer) || buffer.length === 0) {\n return null;\n }\n\n return {\n data: buffer.toString('base64'),\n mimeType,\n };\n } catch {\n return null;\n } finally {\n try {\n unlinkSync(tmpFile);\n } catch {\n // ignore cleanup errors\n }\n }\n}\n\n// =============================================================================\n// Linux\n// =============================================================================\n\nfunction getLinuxClipboardImage(): ClipboardImage | null {\n // Try xclip first, then wl-paste (Wayland)\n return getLinuxClipboardImageXclip() ?? getLinuxClipboardImageWlPaste();\n}\n\nfunction getLinuxClipboardImageXclip(): ClipboardImage | null {\n try {\n // Check available targets\n const targets = execSync('xclip -selection clipboard -target TARGETS -o', {\n encoding: 'utf-8',\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n if (!targets.includes('image/png')) {\n return null;\n }\n\n // Extract PNG data\n const buffer = execSync('xclip -selection clipboard -target image/png -o', {\n timeout: 5000,\n stdio: ['pipe', 'pipe', 'pipe'],\n maxBuffer: 50 * 1024 * 1024, // 50MB max\n });\n\n if (!Buffer.isBuffer(buffer) || buffer.length === 0) {\n return null;\n }\n\n return {\n data: buffer.toString('base64'),\n mimeType: 'image/png',\n };\n } catch {\n return null;\n }\n}\n\nfunction getLinuxClipboardImageWlPaste(): ClipboardImage | null {\n try {\n // Check if wl-paste is available and clipboard has image\n const types = execSync('wl-paste --list-types', {\n encoding: 'utf-8',\n timeout: 3000,\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n\n if (!types.includes('image/png')) {\n return null;\n }\n\n // Extract PNG data\n const buffer = execSync('wl-paste --type image/png', {\n timeout: 5000,\n stdio: ['pipe', 'pipe', 'pipe'],\n maxBuffer: 50 * 1024 * 1024,\n });\n\n if (!Buffer.isBuffer(buffer) || buffer.length === 0) {\n return null;\n }\n\n return {\n data: buffer.toString('base64'),\n mimeType: 'image/png',\n };\n } catch {\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,SAAgB,mBAAkC;CAChD,IAAI;EACF,IAAI,QAAQ,aAAa,UAAU;GACjC,MAAM,OAAO,SAAS,WAAW;IAC/B,UAAU;IACV,SAAS;IACT,OAAO;KAAC;KAAQ;KAAQ;IAAM;GAChC,CAAC;GACD,OAAO,KAAK,SAAS,IAAI,OAAO;EAClC;EACA,IAAI,QAAQ,aAAa,SAEvB,IAAI;GACF,MAAM,OAAO,SAAS,iCAAiC;IACrD,UAAU;IACV,SAAS;IACT,OAAO;KAAC;KAAQ;KAAQ;IAAM;GAChC,CAAC;GACD,OAAO,KAAK,SAAS,IAAI,OAAO;EAClC,QAAQ;GACN,MAAM,OAAO,SAAS,YAAY;IAChC,UAAU;IACV,SAAS;IACT,OAAO;KAAC;KAAQ;KAAQ;IAAM;GAChC,CAAC;GACD,OAAO,KAAK,SAAS,IAAI,OAAO;EAClC;EAEF,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;;;;AAMA,SAAgB,iBAAiB,MAAuB;CACtD,IAAI;EACF,IAAI,QAAQ,aAAa,UAAU;GACjC,SAAS,UAAU;IACjB,OAAO;IACP,SAAS;IACT,OAAO;KAAC;KAAQ;KAAQ;IAAM;GAChC,CAAC;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;AAC1C,eAAO,MAAM,4BAA4B,MAAM,CAAC;AAGhD,eAAO,MAAM,mBAAmB,QAA+D,CAAC;AAGhG,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAC5C,eAAO,MAAM,qBAAqB,QAAS,CAAC;AAE5C;;;;;GAKG;AACH,eAAO,MAAM,6BAA6B,OAAO,CAAC;AAElD;;;;;;GAMG;AACH,eAAO,MAAM,yBAAyB,QAAoC,CAAC;AAE3E,iFAAiF;AACjF,eAAO,MAAM,aAAa,eAAe,CAAC"}
|
package/dist/constants.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":["path"],"sources":["../src/constants.ts"],"sourcesContent":["import * as path from 'node:path';\n\n// Default config directory name used for all project-level and global config paths.\nexport const DEFAULT_CONFIG_DIR = '.mastracode';\n\n/**\n * Validate that a configDirName is a safe single directory name.\n * Rejects absolute paths, path separators, and traversal components.\n */\nexport function validateConfigDirName(configDirName: string): void {\n if (configDirName.trim().length === 0) {\n throw new Error('configDirName must be a non-empty directory name');\n }\n\n if (\n path.isAbsolute(configDirName) ||\n configDirName.includes('/') ||\n configDirName.includes('\\\\') ||\n configDirName === '..' ||\n configDirName === '.'\n ) {\n throw new Error(\n `configDirName must be a single directory name without path separators or traversal components, got: \"${configDirName}\"`,\n );\n }\n}\n\n// Model routes are persisted host input and eagerly resolved per request.\nexport const MODEL_ROUTE_MAX_ENTRIES = 32;\nexport const MODEL_ROUTE_MAX_FIELD_LENGTH = 512;\n\n// Default OM model - using gemini-3.5-flash for efficiency\nexport const DEFAULT_OM_MODEL_ID = process.env.DEFAULT_OM_MODEL_ID ?? 'google/gemini-3.5-flash';\n\n// Default OM thresholds — per-thread overrides are loaded from thread metadata\nexport const DEFAULT_OBS_THRESHOLD = 30_000;\nexport const DEFAULT_REF_THRESHOLD = 40_000;\n\n/**\n * Absolute token retention of the observation activation buffer\n * (`observation.bufferActivation`) for non-resource OM. `@mastra/memory` requires\n * the buffer to stay below `observation.messageTokens`, so a stored observation\n * threshold at or below this value fails the next memory init.\n */\nexport const OBSERVATION_ACTIVATION_TOKENS = 2000;\n\n/**\n * Smallest observation threshold the observer can actually run with: the\n * activation buffer above must stay strictly below `observation.messageTokens`.\n * A row saved before the settings route enforced that can hold a lower value, and\n * `@mastra/memory` rejects the config at init — so reads take the value up to this\n * floor rather than trusting the stored one.\n */\nexport const MIN_OBSERVATION_THRESHOLD = OBSERVATION_ACTIVATION_TOKENS + 1;\n\n/** Id of the coding agent Mastra Code registers; Factory board phases run it. */\nexport const CODE_AGENT_ID = 'code-agent';\n"],"mappings":";;AAGA,MAAa,qBAAqB;;;;;AAMlC,SAAgB,sBAAsB,eAA6B;CACjE,IAAI,cAAc,KAAK,CAAC,CAAC,WAAW,GAClC,MAAM,IAAI,MAAM,kDAAkD;CAGpE,IACEA,OAAK,WAAW,aAAa,KAC7B,cAAc,SAAS,GAAG,KAC1B,cAAc,SAAS,IAAI,KAC3B,kBAAkB,QAClB,kBAAkB,KAElB,MAAM,IAAI,MACR,wGAAwG,cAAc,EACxH;AAEJ;AAGA,MAAa,0BAA0B;AACvC,MAAa,+BAA+B;AAG5C,MAAa,sBAAsB,QAAQ,IAAI,uBAAuB;AAGtE,MAAa,wBAAwB;AACrC,MAAa,wBAAwB;;;;;;;AAQrC,MAAa,gCAAgC;;;;;;;;AAS7C,MAAa,4BAA4B;;AAGzC,MAAa,gBAAgB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-classification.d.ts","sourceRoot":"","sources":["../src/error-classification.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CAAC,GAAG,EAAE,OAAO,EAAE,KAAK,SAAI,GAAG,OAAO,CASvE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"error-classification.js","names":[],"sources":["../src/error-classification.ts"],"sourcesContent":["/**\n * Checks whether an error is an ERR_STREAM_DESTROYED error, which is a\n * non-fatal condition that occurs when code writes to a stream after it\n * has been closed (e.g., client disconnect, cancelled LLM stream, LSP\n * shutdown, killed subprocess).\n *\n * Walks the `.cause` chain up to a depth limit.\n */\nexport function isStreamDestroyedError(err: unknown, depth = 0): boolean {\n if (!err || depth > 5) return false;\n const e = err as any;\n if (e.code === 'ERR_STREAM_DESTROYED') return true;\n if (typeof e.message === 'string' && e.message.includes('stream was destroyed')) return true;\n if (e.cause && isStreamDestroyedError(e.cause, depth + 1)) return true;\n if (Array.isArray(e.errors) && e.errors.some((inner: unknown) => isStreamDestroyedError(inner, depth + 1)))\n return true;\n return false;\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,uBAAuB,KAAc,QAAQ,GAAY;CACvE,IAAI,CAAC,OAAO,QAAQ,GAAG,OAAO;CAC9B,MAAM,IAAI;CACV,IAAI,EAAE,SAAS,wBAAwB,OAAO;CAC9C,IAAI,OAAO,EAAE,YAAY,YAAY,EAAE,QAAQ,SAAS,sBAAsB,GAAG,OAAO;CACxF,IAAI,EAAE,SAAS,uBAAuB,EAAE,OAAO,QAAQ,CAAC,GAAG,OAAO;CAClE,IAAI,MAAM,QAAQ,EAAE,MAAM,KAAK,EAAE,OAAO,MAAM,UAAmB,uBAAuB,OAAO,QAAQ,CAAC,CAAC,GACvG,OAAO;CACT,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-builder.d.ts","sourceRoot":"","sources":["../../src/evals/context-builder.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,+BAA+B,CAAC;AAE9E,OAAO,KAAK,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAItG,MAAM,MAAM,qBAAqB,GAAG;IAClC,oEAAoE;IACpE,UAAU,EAAE,sBAAsB,CAAC;IACnC,yDAAyD;IACzD,WAAW,EAAE,uBAAuB,CAAC;IACrC,sDAAsD;IACtD,UAAU,EAAE,UAAU,GAAG,SAAS,CAAC;IACnC,4CAA4C;IAC5C,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACxC,gDAAgD;IAChD,QAAQ,EAAE,MAAM,CAAC;IACjB,6CAA6C;IAC7C,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAChC,oDAAoD;IACpD,UAAU,EAAE,eAAe,CAAC,GAAG,CAAC,CAAC;IACjC,0DAA0D;IAC1D,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,CAAC;IACtB,kEAAkE;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,0FAA0F;IAC1F,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,qBAAqB,CAAC,CAoCnG"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"context-builder.js","names":[],"sources":["../../src/evals/context-builder.ts"],"sourcesContent":["/**\n * Eval Context Builder for MastraCode\n *\n * Converts AgentController session data into scorer-compatible format.\n * Supports both agent-type scorers (ScorerRunInputForAgent) and\n * trajectory scorers (Trajectory).\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport type { AgentController, Session } from '@mastra/core/agent-controller';\nimport { extractTrajectoryFromTrace } from '@mastra/core/evals';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent, Trajectory } from '@mastra/core/evals';\nimport type { CoreMessage, CoreSystemMessage } from '@mastra/core/llm';\nimport type { MastraCompositeStore } from '@mastra/core/storage';\n\nexport type MastraCodeEvalContext = {\n /** Scorer-compatible agent input (messages, system prompt, etc.) */\n agentInput: ScorerRunInputForAgent;\n /** Scorer-compatible agent output (response messages) */\n agentOutput: ScorerRunOutputForAgent;\n /** Execution trajectory extracted from trace spans */\n trajectory: Trajectory | undefined;\n /** Request context with session metadata */\n requestContext: Record<string, unknown>;\n /** The thread ID this context was built from */\n threadId: string;\n /** The trace ID for observability linkage */\n traceId: string | undefined;\n};\n\nexport type BuildContextOptions = {\n /** AgentController instance to extract data from */\n controller: AgentController<any>;\n /** Session whose state/model/thread is being evaluated */\n session: Session<any>;\n /** Thread ID to build context for (defaults to current thread) */\n threadId?: string;\n /** Limit messages to the last N turns (user+assistant pairs). Undefined = all messages */\n lastNTurns?: number;\n};\n\n/**\n * Build an evaluation context from a AgentController session.\n *\n * This extracts messages from storage, builds trajectory from trace spans,\n * and packages everything into the format scorers expect.\n */\nexport async function buildEvalContext(options: BuildContextOptions): Promise<MastraCodeEvalContext> {\n const { controller, session, lastNTurns } = options;\n const threadId = options.threadId ?? session.thread.getId();\n\n if (!threadId) {\n throw new Error('No thread ID available. Start a session before building eval context.');\n }\n\n const mastra = controller.getMastra();\n const storage = mastra?.getStorage();\n\n // 1. Get raw MastraDB messages from memory storage\n const rawMessages = await getRawMessages(storage, threadId, lastNTurns);\n\n // 2. Split messages into input/output categories\n const { inputMessages, systemMessages, outputMessages } = categorizeMessages(rawMessages);\n\n // 3. Extract trajectory from observability traces\n const { trajectory, traceId } = await extractSessionTrajectory(storage, threadId);\n\n // 4. Build request context from AgentController state\n const requestContext = buildRequestContext(session, threadId);\n\n return {\n agentInput: {\n inputMessages,\n rememberedMessages: [], // AgentController doesn't separate these; memory recall is transparent\n systemMessages,\n taggedSystemMessages: {},\n },\n agentOutput: outputMessages,\n trajectory,\n requestContext,\n threadId,\n traceId,\n };\n}\n\n/**\n * Fetch raw MastraDBMessage[] from memory storage for a thread.\n */\nasync function getRawMessages(\n storage: MastraCompositeStore | undefined,\n threadId: string,\n lastNTurns?: number,\n): Promise<MastraDBMessage[]> {\n if (!storage) return [];\n\n const memoryStore = await storage.getStore('memory');\n if (!memoryStore) return [];\n\n const result = await memoryStore.listMessages({\n threadId,\n perPage: false,\n });\n\n let messages = result.messages;\n\n if (lastNTurns !== undefined && lastNTurns > 0) {\n messages = trimToLastNTurns(messages, lastNTurns);\n }\n\n return messages;\n}\n\n/**\n * Trim messages to the last N user-assistant turn pairs.\n */\nfunction trimToLastNTurns(messages: MastraDBMessage[], turns: number): MastraDBMessage[] {\n // Walk backward, counting user messages as turn boundaries.\n // When we find the Nth user message, slice from there to include\n // that turn and everything after it.\n let turnCount = 0;\n let cutoffIndex = 0;\n\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.role === 'user') {\n turnCount++;\n if (turnCount === turns) {\n cutoffIndex = i;\n break;\n }\n }\n }\n\n return messages.slice(cutoffIndex);\n}\n\n/**\n * Categorize messages into input (user), system, and output (assistant) groups.\n */\nfunction categorizeMessages(messages: MastraDBMessage[]): {\n inputMessages: MastraDBMessage[];\n systemMessages: CoreMessage[];\n outputMessages: MastraDBMessage[];\n} {\n const inputMessages: MastraDBMessage[] = [];\n const systemMessages: CoreSystemMessage[] = [];\n const outputMessages: MastraDBMessage[] = [];\n\n for (const msg of messages) {\n switch (msg.role) {\n case 'user':\n inputMessages.push(msg);\n break;\n case 'system':\n systemMessages.push({\n role: 'system',\n content: extractTextContent(msg),\n });\n break;\n case 'assistant':\n outputMessages.push(msg);\n break;\n }\n }\n\n return { inputMessages, systemMessages, outputMessages };\n}\n\n/**\n * Extract plain text content from a MastraDBMessage.\n */\nfunction extractTextContent(msg: MastraDBMessage): string {\n if (!msg.content?.parts) return '';\n\n return msg.content.parts\n .filter((p): p is { type: 'text'; text: string } => p.type === 'text' && 'text' in p)\n .map(p => p.text)\n .join('\\n');\n}\n\n/**\n * Extract trajectory from trace spans in observability storage.\n * Looks up traces by threadId metadata.\n */\nasync function extractSessionTrajectory(\n storage: MastraCompositeStore | undefined,\n threadId: string,\n): Promise<{ trajectory: Trajectory | undefined; traceId: string | undefined }> {\n if (!storage) return { trajectory: undefined, traceId: undefined };\n\n try {\n const observabilityStore = await storage.getStore('observability');\n if (!observabilityStore) return { trajectory: undefined, traceId: undefined };\n\n // Find traces associated with this thread\n const result = await observabilityStore.listTraces({\n filters: { threadId },\n pagination: { page: 0, perPage: 1 },\n orderBy: { field: 'startedAt', direction: 'DESC' },\n });\n\n if (!result?.spans?.length) return { trajectory: undefined, traceId: undefined };\n\n const traceId = result.spans[0]!.traceId;\n const trace = await observabilityStore.getTrace({ traceId });\n\n if (!trace?.spans?.length) return { trajectory: undefined, traceId };\n\n const trajectory = extractTrajectoryFromTrace(trace.spans);\n return { trajectory, traceId };\n } catch {\n // Trace extraction is best-effort\n return { trajectory: undefined, traceId: undefined };\n }\n}\n\n/**\n * Build request context from AgentController state for scorer evaluation.\n */\nfunction buildRequestContext(session: Session<any>, threadId: string): Record<string, unknown> {\n const state = session.state.get() as Record<string, unknown>;\n\n return {\n threadId,\n mode: state.currentMode ?? state.mode,\n modelId: session.model.get(),\n projectPath: state.projectPath,\n projectName: state.projectName,\n gitBranch: state.gitBranch,\n thinkingLevel: state.thinkingLevel,\n yolo: state.yolo,\n smartEditing: state.smartEditing,\n };\n}\n"],"mappings":";;;;;;;;AA+CA,eAAsB,iBAAiB,SAA8D;CACnG,MAAM,EAAE,YAAY,SAAS,eAAe;CAC5C,MAAM,WAAW,QAAQ,YAAY,QAAQ,OAAO,MAAM;CAE1D,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,uEAAuE;CAIzF,MAAM,UADS,WAAW,UACL,CAAC,EAAE,WAAW;CAMnC,MAAM,EAAE,eAAe,gBAAgB,mBAAmB,mBAAmB,MAHnD,eAAe,SAAS,UAAU,UAAU,CAGkB;CAGxF,MAAM,EAAE,YAAY,YAAY,MAAM,yBAAyB,SAAS,QAAQ;CAGhF,MAAM,iBAAiB,oBAAoB,SAAS,QAAQ;CAE5D,OAAO;EACL,YAAY;GACV;GACA,oBAAoB,CAAC;GACrB;GACA,sBAAsB,CAAC;EACzB;EACA,aAAa;EACb;EACA;EACA;EACA;CACF;AACF;;;;AAKA,eAAe,eACb,SACA,UACA,YAC4B;CA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AE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"classify-command.d.ts","sourceRoot":"","sources":["../../../src/evals/scorers/classify-command.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;;GAGG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAUvD;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,MAAM,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAgB1D;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,OAAO,GAAG,OAAO,CAQzE;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAGvE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"classify-command.js","names":[],"sources":["../../../src/evals/scorers/classify-command.ts"],"sourcesContent":["/**\n * Shared command classification utilities for scoring.\n *\n * Used by scorers to consistently identify build, test, and other command types.\n */\n\n/**\n * Check if a command string is a build/typecheck command.\n * Handles compound commands (e.g. `pnpm build && pnpm test`) by checking each segment.\n */\nexport function isBuildCommand(command: string): boolean {\n const segments = command.split(/\\s*(?:&&|\\|\\||;)\\s*/);\n return segments.some(seg => {\n const trimmed = seg.trim();\n if (!/\\b(tsc|typecheck|type-check|build)\\b/.test(trimmed)) return false;\n // Don't reject if \"test\" only appears as a substring (e.g. \"build-test-output\").\n // Only reject if a test runner is the primary verb of this segment.\n const primaryVerb = trimmed.replace(/^(?:pnpm|npm|yarn|npx|bunx?|turbo)\\s+(?:run\\s+)?/, '').split(/\\s/)[0] ?? '';\n return !/^(test|vitest|jest|mocha|pytest)$/.test(primaryVerb);\n });\n}\n\n/**\n * Check if a command string is a test command.\n */\nexport function isTestCommand(command: string): boolean {\n return /\\b(test|vitest|jest|mocha|pytest|spec)\\b/.test(command);\n}\n\n/**\n * Extract exit code from an `execute_command` result.\n * Only trusts explicit exitCode/code fields — no heuristic fallbacks.\n */\nexport function getExitCode(result: unknown): number | null {\n if (result == null) return null;\n\n if (typeof result === 'string') {\n const exitMatch = result.match(/(?:^|\\n)(?:exit code\\s*:?|process exited with code)\\s*(-?\\d+)\\s*$/i);\n if (exitMatch) return parseInt(exitMatch[1]!, 10);\n return null;\n }\n\n if (typeof result === 'object') {\n const obj = result as Record<string, unknown>;\n if ('exitCode' in obj && typeof obj.exitCode === 'number') return obj.exitCode;\n if ('code' in obj && typeof obj.code === 'number') return obj.code;\n }\n\n return null;\n}\n\n/**\n * Determine if a tool call result indicates success (exit code 0, no explicit error).\n * Works with both structured result objects and string results.\n */\nexport function isSuccessResult(result: unknown, error?: unknown): boolean {\n if (error || !result) return false;\n\n const exitCode = getExitCode(result);\n if (exitCode !== null) return exitCode === 0;\n\n // execute_command only appends an exit code when the command fails.\n return typeof result === 'string';\n}\n\n/**\n * Match a file path from tool output against an expected path.\n * Supports exact match and suffix match (e.g. \"src/foo.ts\" matches \"/abs/path/src/foo.ts\").\n */\nexport function matchFilePath(actual: string, expected: string): boolean {\n if (actual === expected) return true;\n return actual.endsWith(`/${expected}`) || expected.endsWith(`/${actual}`);\n}\n"],"mappings":";;;;;;;;;;AAUA,SAAgB,eAAe,SAA0B;CAEvD,OADiB,QAAQ,MAAM,qBACjB,CAAC,CAAC,MAAK,QAAO;EAC1B,MAAM,UAAU,IAAI,KAAK;EACzB,IAAI,CAAC,uCAAuC,KAAK,OAAO,GAAG,OAAO;EAGlE,MAAM,cAAc,QAAQ,QAAQ,oDAAoD,EAAE,CAAC,CAAC,MAAM,IAAI,CAAC,CAAC,MAAM;EAC9G,OAAO,CAAC,oCAAoC,KAAK,WAAW;CAC9D,CAAC;AACH;;;;AAKA,SAAgB,cAAc,SAA0B;CACtD,OAAO,2CAA2C,KAAK,OAAO;AAChE;;;;;AAMA,SAAgB,YAAY,QAAgC;CAC1D,IAAI,UAAU,MAAM,OAAO;CAE3B,IAAI,OAAO,WAAW,UAAU;EAC9B,MAAM,YAAY,OAAO,MAAM,oEAAoE;EACnG,IAAI,WAAW,OAAO,SAAS,UAAU,IAAK,EAAE;EAChD,OAAO;CACT;CAEA,IAAI,OAAO,WAAW,UAAU;EAC9B,MAAM,MAAM;EACZ,IAAI,cAAc,OAAO,OAAO,IAAI,aAAa,UAAU,OAAO,IAAI;EACtE,IAAI,UAAU,OAAO,OAAO,IAAI,SAAS,UAAU,OAAO,IAAI;CAChE;CAEA,OAAO;AACT;;;;;AAMA,SAAgB,gBAAgB,QAAiB,OAA0B;CACzE,IAAI,SAAS,CAAC,QAAQ,OAAO;CAE7B,MAAM,WAAW,YAAY,MAAM;CACnC,IAAI,aAAa,MAAM,OAAO,aAAa;CAG3C,OAAO,OAAO,WAAW;AAC3B;;;;;AAMA,SAAgB,cAAc,QAAgB,UAA2B;CACvE,IAAI,WAAW,UAAU,OAAO;CAChC,OAAO,OAAO,SAAS,IAAI,UAAU,KAAK,SAAS,SAAS,IAAI,QAAQ;AAC1E"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"efficiency.d.ts","sourceRoot":"","sources":["../../../src/evals/scorers/efficiency.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAsOH,wBAAgB,sBAAsB;;;;;;;;;;;eA7JyB,MAAM;eAAS,MAAM;gBAAU,MAAM;;;eAqCnD,MAAM;gBAAU,MAAM;;;eAqBH,MAAM;gBAAU,MAAM;;;eAuDvB,MAAM;gBAAU,MAAM;;;;6FA8GxF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"efficiency.js","names":[],"sources":["../../../src/evals/scorers/efficiency.ts"],"sourcesContent":["/**\n * MastraCode Efficiency Scorer (Code-based, Agent type, 30% sampling)\n *\n * Measures how efficiently the agent completes work through quantitative ratios.\n * Unlike the Outcome Scorer (which checks *what* happened), this checks\n * *how much work* it took.\n *\n * This scorer produces a score from 0-1 but also exposes raw metrics in the\n * reason text for trend analysis. The score represents \"how cleanly did the\n * agent work?\" — not whether it got the right answer.\n *\n * Sampled at 30% because it's slightly more expensive (analyzes message sequences).\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { createScorer, filterRun } from '@mastra/core/evals';\n\nimport type { ExtractedToolCall } from './extract-tools.js';\nimport { extractToolCalls } from './extract-tools.js';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// CONFIGURATION — Adjust weights and thresholds here\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Dimension weights (must sum to 1.0).\n *\n * - redundancy: Duplicate mutation tool calls with identical args.\n * - turnCount: Total assistant turns to complete the task.\n * - retryEfficiency: How quickly the agent recovers from tool failures.\n * - readBeforeEdit: Whether files are read before being edited.\n */\nconst WEIGHTS = {\n redundancy: 0.35,\n turnCount: 0.3,\n retryEfficiency: 0.2,\n readBeforeEdit: 0.15,\n} as const;\n\n/**\n * Scoring thresholds and multipliers.\n */\nconst THRESHOLDS = {\n /** Redundancy ratio below this is considered acceptable (no penalty). */\n redundancyAcceptableRate: 0.05,\n\n /** Penalty multiplier applied to redundancy ratio above the acceptable rate. */\n redundancyPenaltyMultiplier: 3,\n\n /** Turns at or below this is considered normal (score 1.0). */\n turnCountNormalMax: 8,\n\n /** Penalty per turn beyond the normal maximum (for turns 9–15). */\n turnCountPenaltyPerTurn: 0.04,\n\n /** Penalty per turn beyond 15. */\n turnCountExtendedPenaltyPerTurn: 0.03,\n\n /** Number of consecutive failures before a retry chain is \"excessive\". */\n retryExcessiveThreshold: 3,\n\n /** Tools considered \"edit\" tools that should be preceded by a read. */\n editTools: ['string_replace_lsp', 'ast_smart_edit'] as string[],\n\n /** Tools that satisfy read-before-edit (only `view` truly reads a specific file). */\n readTools: ['view'] as string[],\n\n /** Tools whose repeated identical calls are intentional (idempotent reads). */\n redundancyWhitelist: ['view', 'search_content', 'find_files', 'lsp_inspect', 'web_search', 'web_extract'] as string[],\n\n /** Minimum tool calls required to produce a meaningful score. */\n minToolCalls: 2,\n} as const;\n\n/**\n * Count assistant turns (messages with role === 'assistant').\n */\nfunction countAssistantTurns(messages: MastraDBMessage[]): number {\n return messages.filter(m => m.role === 'assistant').length;\n}\n\n/**\n * Calculate redundant call ratio.\n * Only counts mutation/action tools as redundant — reads are whitelisted.\n */\nfunction scoreRedundancy(calls: ExtractedToolCall[]): { score: number; ratio: number; detail: string } {\n if (calls.length < 2) return { score: 1, ratio: 0, detail: 'Too few calls' };\n\n // Only consider non-whitelisted (mutation) tools for redundancy\n const mutationCalls = calls.filter(c => !THRESHOLDS.redundancyWhitelist.includes(c.toolName));\n if (mutationCalls.length < 2) return { score: 1, ratio: 0, detail: 'No mutation tools to check' };\n\n const fingerprints = new Map<string, { count: number; successCount: number }>();\n for (const call of mutationCalls) {\n const fp = `${call.toolName}:${JSON.stringify(call.args)}`;\n const existing = fingerprints.get(fp) ?? { count: 0, successCount: 0 };\n existing.count++;\n if (!call.isError) existing.successCount++;\n fingerprints.set(fp, existing);\n }\n\n // Only count as redundant if the same successful call happened multiple times\n let redundantCount = 0;\n for (const { successCount } of fingerprints.values()) {\n if (successCount > 1) redundantCount += successCount - 1;\n }\n\n const ratio = redundantCount / mutationCalls.length;\n const acceptable = THRESHOLDS.redundancyAcceptableRate;\n const score =\n ratio <= acceptable ? 1 : Math.max(0, 1 - (ratio - acceptable) * THRESHOLDS.redundancyPenaltyMultiplier);\n return {\n score,\n ratio,\n detail: `${redundantCount}/${mutationCalls.length} redundant mutations (${(ratio * 100).toFixed(0)}%)`,\n };\n}\n\n/**\n * Score turn count efficiency.\n * Fewer turns to accomplish the task = more efficient.\n */\nfunction scoreTurnCount(turns: number): { score: number; detail: string } {\n const normalMax = THRESHOLDS.turnCountNormalMax;\n const penaltyPerTurn = THRESHOLDS.turnCountPenaltyPerTurn;\n const extendedPenalty = THRESHOLDS.turnCountExtendedPenaltyPerTurn;\n\n if (turns <= 1) return { score: 1, detail: `${turns} turn` };\n if (turns <= normalMax) return { score: 1, detail: `${turns} turns (within normal range)` };\n if (turns <= 15) {\n const score = 1 - (turns - normalMax) * penaltyPerTurn;\n return { score, detail: `${turns} turns (slightly extended)` };\n }\n\n const midPenalty = (15 - normalMax) * penaltyPerTurn;\n const score = Math.max(0, 1 - midPenalty - (turns - 15) * extendedPenalty);\n return { score, detail: `${turns} turns (extended session)` };\n}\n\n/**\n * Score failed-then-succeeded ratio.\n * Groups retry chains by tool name + target file path for more accurate detection.\n */\nfunction scoreRetryEfficiency(calls: ExtractedToolCall[]): { score: number; detail: string } {\n if (calls.length < 2) return { score: 1, detail: 'Too few calls' };\n\n // Group calls by tool name + target file path (if available)\n const groupKey = (call: ExtractedToolCall): string => {\n const path = String(call.args.path ?? call.args.command ?? '');\n return `${call.toolName}:${path}`;\n };\n\n const byGroup = new Map<string, ExtractedToolCall[]>();\n for (const call of calls) {\n const key = groupKey(call);\n const arr = byGroup.get(key) ?? [];\n arr.push(call);\n byGroup.set(key, arr);\n }\n\n let totalRetryChains = 0;\n let excessiveRetries = 0;\n const threshold = THRESHOLDS.retryExcessiveThreshold;\n\n for (const [, toolCalls] of byGroup) {\n let consecutiveFailures = 0;\n for (const call of toolCalls) {\n if (call.isError) {\n consecutiveFailures++;\n } else {\n if (consecutiveFailures > 0) {\n totalRetryChains++;\n if (consecutiveFailures >= threshold) excessiveRetries++;\n }\n consecutiveFailures = 0;\n }\n }\n // Count unrecovered retry chains (failures at end of group with no success)\n if (consecutiveFailures > 0) {\n totalRetryChains++;\n if (consecutiveFailures >= threshold) excessiveRetries++;\n }\n }\n\n if (totalRetryChains === 0) return { score: 1, detail: 'No retry chains' };\n if (excessiveRetries === 0) return { score: 0.9, detail: `${totalRetryChains} retry chain(s), all resolved quickly` };\n\n const score = Math.max(0, 0.8 - excessiveRetries * 0.2);\n return {\n score,\n detail: `${excessiveRetries} excessive retry chain(s) (${threshold}+ failures before success)`,\n };\n}\n\n/**\n * Score read-before-edit compliance.\n * Only `view` satisfies a read — search/find don't provide specific file content.\n */\nfunction scoreReadBeforeEdit(calls: ExtractedToolCall[]): { score: number; detail: string } {\n const editTools = THRESHOLDS.editTools;\n const readTools = THRESHOLDS.readTools;\n\n const edits = calls.filter(c => editTools.includes(c.toolName));\n if (edits.length === 0) return { score: 1, detail: 'No edits to check' };\n\n // Build set of files that were read before each edit.\n // Use suffix-normalized paths so that \"/abs/path/src/foo.ts\" and \"src/foo.ts\" match.\n const readPaths = new Set<string>();\n let compliant = 0;\n let total = 0;\n\n for (const call of calls) {\n const rawPath = String(call.args.path ?? '');\n if (!rawPath) continue;\n\n if (readTools.includes(call.toolName)) {\n readPaths.add(rawPath);\n } else if (editTools.includes(call.toolName)) {\n total++;\n if (hasReadPath(readPaths, rawPath)) {\n compliant++;\n }\n }\n }\n\n if (total === 0) return { score: 1, detail: 'No path-targeted edits' };\n\n const ratio = compliant / total;\n const violations = total - compliant;\n if (violations === 0) return { score: 1, detail: `All ${total} edits had prior reads` };\n return { score: ratio, detail: `${violations}/${total} edits without prior read` };\n}\n\n/** Check if any read path matches the edit path, using suffix matching for mixed abs/relative paths. */\nfunction hasReadPath(readPaths: Set<string>, editPath: string): boolean {\n if (readPaths.has(editPath)) return true;\n for (const rp of readPaths) {\n if (rp.endsWith(`/${editPath}`) || editPath.endsWith(`/${rp}`)) return true;\n }\n return false;\n}\n\nexport function createEfficiencyScorer() {\n return createScorer({\n id: 'mastracode-efficiency',\n name: 'MastraCode Efficiency',\n description:\n 'Measures coding session efficiency: redundancy, turn count, retry patterns, read-before-edit. 30% sampled.',\n type: 'agent',\n prepareRun: filterRun({ partTypes: ['tool-invocation', 'text'] }),\n })\n .preprocess(async ({ run }) => {\n const messages = (run.output ?? []) as MastraDBMessage[];\n const calls = extractToolCalls(messages);\n const turns = countAssistantTurns(messages);\n\n // H1: Empty sessions → score 0\n if (calls.length < THRESHOLDS.minToolCalls) {\n return { empty: true as const, totalCalls: calls.length, totalTurns: turns };\n }\n\n const redundancy = scoreRedundancy(calls);\n const turnCount = scoreTurnCount(turns);\n const retryEfficiency = scoreRetryEfficiency(calls);\n const readBeforeEdit = scoreReadBeforeEdit(calls);\n\n return {\n empty: false as const,\n redundancy,\n turnCount,\n retryEfficiency,\n readBeforeEdit,\n totalCalls: calls.length,\n totalTurns: turns,\n };\n })\n .generateScore(({ results }) => {\n const p = results.preprocessStepResult;\n if (p.empty) return 0;\n\n const score =\n p.redundancy.score * WEIGHTS.redundancy +\n p.turnCount.score * WEIGHTS.turnCount +\n p.retryEfficiency.score * WEIGHTS.retryEfficiency +\n p.readBeforeEdit.score * WEIGHTS.readBeforeEdit;\n\n return Math.round(score * 100) / 100;\n })\n .generateReason(({ results, score }) => {\n const p = results.preprocessStepResult;\n if (p.empty) {\n return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;\n }\n\n const pct = (w: number) => `${(w * 100).toFixed(0)}%`;\n const parts: string[] = [`Score: ${score} (${p.totalCalls} calls, ${p.totalTurns} turns)`];\n\n parts.push(`Redundancy (${pct(WEIGHTS.redundancy)}): ${p.redundancy.detail} [${p.redundancy.score}]`);\n parts.push(`Turn count (${pct(WEIGHTS.turnCount)}): ${p.turnCount.detail} [${p.turnCount.score}]`);\n parts.push(\n `Retry efficiency (${pct(WEIGHTS.retryEfficiency)}): ${p.retryEfficiency.detail} [${p.retryEfficiency.score}]`,\n );\n parts.push(\n `Read-before-edit (${pct(WEIGHTS.readBeforeEdit)}): ${p.readBeforeEdit.detail} [${p.readBeforeEdit.score}]`,\n );\n\n return parts.join('\\n');\n });\n}\n"],"mappings":";;;;;;;;;;;AAgCA,MAAM,UAAU;CACd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,EAAE;EACnD,MAAM,QAAkB,CAAC,UAAU,MAAM,IAAI,EAAE,WAAW,UAAU,EAAE,WAAW,QAAQ;EAEzF,MAAM,KAAK,eAAe,IAAI,QAAQ,UAAU,EAAE,KAAK,EAAE,WAAW,OAAO,IAAI,EAAE,WAAW,MAAM,EAAE;EACpG,MAAM,KAAK,eAAe,IAAI,QAAQ,SAAS,EAAE,KAAK,EAAE,UAAU,OAAO,IAAI,EAAE,UAAU,MAAM,EAAE;EACjG,MAAM,KACJ,qBAAqB,IAAI,QAAQ,eAAe,EAAE,KAAK,EAAE,gBAAgB,OAAO,IAAI,EAAE,gBAAgB,MAAM,EAC9G;EACA,MAAM,KACJ,qBAAqB,IAAI,QAAQ,cAAc,EAAE,KAAK,EAAE,eAAe,OAAO,IAAI,EAAE,eAAe,MAAM,EAC3G;EAEA,OAAO,MAAM,KAAK,IAAI;CACxB,CAAC;AACL"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"extract-tools.d.ts","sourceRoot":"","sources":["../../../src/evals/scorers/extract-tools.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAG1D,MAAM,MAAM,iBAAiB,GAAG;IAC9B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC9B,MAAM,EAAE,OAAO,CAAC;IAChB,OAAO,EAAE,OAAO,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAmBF;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,eAAe,EAAE,GAAG,iBAAiB,EAAE,CAoDjF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"extract-tools.js","names":[],"sources":["../../../src/evals/scorers/extract-tools.ts"],"sourcesContent":["/**\n * Shared tool invocation extraction from MastraDBMessages.\n *\n * Used by both the Outcome and Efficiency scorers to extract completed\n * tool calls from message content, handling both the `parts` array (primary)\n * and the legacy `toolInvocations` array.\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport type { MastraMessagePart, MastraToolInvocation } from '@mastra/core/agent/message-list';\n\nexport type ExtractedToolCall = {\n toolCallId?: string;\n toolName: string;\n args: Record<string, unknown>;\n result: unknown;\n isError: boolean;\n index: number;\n};\n\nfunction isToolInvocationPart(part: MastraMessagePart): part is MastraMessagePart & {\n type: 'tool-invocation';\n toolInvocation: MastraToolInvocation;\n} {\n return 'type' in part && part.type === 'tool-invocation' && 'toolInvocation' in part;\n}\n\nfunction isCompleted(inv: { state: string }): boolean {\n return (\n inv.state === 'result' || inv.state === 'error' || inv.state === 'output-error' || inv.state === 'output-denied'\n );\n}\n\nfunction isErrorState(inv: { state: string }): boolean {\n return inv.state === 'error' || inv.state === 'output-error' || inv.state === 'output-denied';\n}\n\n/**\n * Extract completed tool invocations from MastraDBMessages.\n *\n * Handles both:\n * - `content.parts` (primary format, MastraToolInvocationPart)\n * - `content.toolInvocations` (legacy format, AI SDK ToolInvocation[])\n */\nexport function extractToolCalls(messages: MastraDBMessage[]): ExtractedToolCall[] {\n const results: ExtractedToolCall[] = [];\n const seenToolCallIds = new Set<string>();\n let index = 0;\n\n for (const msg of messages) {\n if (!msg.content) continue;\n\n // Primary format: parts array with tool-invocation parts\n for (const part of msg.content.parts ?? []) {\n if (isToolInvocationPart(part)) {\n const inv = part.toolInvocation;\n if (isCompleted(inv)) {\n const toolCallId = 'toolCallId' in inv ? (inv.toolCallId as string) : undefined;\n if (toolCallId) seenToolCallIds.add(toolCallId);\n\n results.push({\n toolCallId,\n toolName: inv.toolName ?? '',\n args: (inv.args ?? {}) as Record<string, unknown>,\n result: inv.result,\n isError: isErrorState(inv),\n index: index++,\n });\n }\n }\n }\n\n // Legacy format: toolInvocations array (AI SDK ToolInvocation)\n // Only states here are 'partial-call' | 'call' | 'result' — no error state.\n if (msg.content.toolInvocations) {\n for (const inv of msg.content.toolInvocations) {\n if (inv.state === 'result') {\n // Skip if we already extracted this from parts (deduplicate by toolCallId)\n const toolCallId = 'toolCallId' in inv ? inv.toolCallId : undefined;\n if (toolCallId && seenToolCallIds.has(toolCallId)) continue;\n if (toolCallId) seenToolCallIds.add(toolCallId);\n\n results.push({\n toolCallId,\n toolName: inv.toolName ?? '',\n args: (inv.args ?? {}) as Record<string, unknown>,\n result: inv.result,\n isError: false,\n index: index++,\n });\n }\n }\n }\n }\n\n return results;\n}\n"],"mappings":";AAoBA,SAAS,qBAAqB,MAG5B;CACA,OAAO,UAAU,QAAQ,KAAK,SAAS,qBAAqB,oBAAoB;AAClF;AAEA,SAAS,YAAY,KAAiC;CACpD,OACE,IAAI,UAAU,YAAY,IAAI,UAAU,WAAW,IAAI,UAAU,kBAAkB,IAAI,UAAU;AAErG;AAEA,SAAS,aAAa,KAAiC;CACrD,OAAO,IAAI,UAAU,WAAW,IAAI,UAAU,kBAAkB,IAAI,UAAU;AAChF;;;;;;;;AASA,SAAgB,iBAAiB,UAAkD;CACjF,MAAM,UAA+B,CAAC;CACtC,MAAM,kCAAkB,IAAI,IAAY;CACxC,IAAI,QAAQ;CAEZ,KAAK,MAAM,OAAO,UAAU;EAC1B,IAAI,CAAC,IAAI,SAAS;EAGlB,KAAK,MAAM,QAAQ,IAAI,QAAQ,SAAS,CAAC,GACvC,IAAI,qBAAqB,IAAI,GAAG;GAC9B,MAAM,MAAM,KAAK;GACjB,IAAI,YAAY,GAAG,GAAG;IACpB,MAAM,aAAa,gBAAgB,MAAO,IAAI,aAAwB,KAAA;IACtE,IAAI,YAAY,gBAAgB,IAAI,UAAU;IAE9C,QAAQ,KAAK;KACX;KACA,UAAU,IAAI,YAAY;KAC1B,MAAO,IAAI,QAAQ,CAAC;KACpB,QAAQ,IAAI;KACZ,SAAS,aAAa,GAAG;KACzB,OAAO;IACT,CAAC;GACH;EACF;EAKF,IAAI,IAAI,QAAQ,iBACT;QAAA,MAAM,OAAO,IAAI,QAAQ,iBAC5B,IAAI,IAAI,UAAU,UAAU;IAE1B,MAAM,aAAa,gBAAgB,MAAM,IAAI,aAAa,KAAA;IAC1D,IAAI,cAAc,gBAAgB,IAAI,UAAU,GAAG;IACnD,IAAI,YAAY,gBAAgB,IAAI,UAAU;IAE9C,QAAQ,KAAK;KACX;KACA,UAAU,IAAI,YAAY;KAC1B,MAAO,IAAI,QAAQ,CAAC;KACpB,QAAQ,IAAI;KACZ,SAAS;KACT,OAAO;IACT,CAAC;GACH;;CAGN;CAEA,OAAO;AACT"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/evals/scorers/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"outcome.d.ts","sourceRoot":"","sources":["../../../src/evals/scorers/outcome.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AAsDH,KAAK,eAAe,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,CAAA;CAAE,CAAC;AAmO9E,wBAAgB,mBAAmB;;;;;;;;;;;;;;;;;;6FAkFlC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"outcome.js","names":[],"sources":["../../../src/evals/scorers/outcome.ts"],"sourcesContent":["/**\n * MastraCode Outcome Scorer (Code-based, Agent type, always-on)\n *\n * Grades the objective outcome of a coding session by checking hard facts:\n * - Did the build/typecheck pass?\n * - Did tests pass?\n * - What was the tool error rate?\n * - Did the agent get stuck in a loop?\n * - Was there a regression (build passed earlier, failed later)?\n * - Did the agent use ask_user unnecessarily? (autonomy)\n *\n * This scorer is always-on (no sampling) because it's cheap — it only\n * reads exit codes and error states from tool results already in the messages.\n *\n * Scoring philosophy (from Anthropic's eval guidance):\n * \"Grade outcomes, not paths\" — we check what happened, not how.\n * Partial credit: a session that passes build but fails tests scores\n * higher than one that fails build entirely.\n *\n * Dimensions that don't apply to a session (e.g. build for a docs-only task)\n * are excluded from the weighted average, so sessions aren't penalized for\n * irrelevant criteria.\n */\n\nimport type { MastraDBMessage } from '@mastra/core/agent';\nimport { createScorer, filterRun } from '@mastra/core/evals';\n\nimport { isBuildCommand, isTestCommand, getExitCode, isSuccessResult } from './classify-command.js';\nimport type { ExtractedToolCall } from './extract-tools.js';\nimport { extractToolCalls } from './extract-tools.js';\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n// CONFIGURATION — Adjust weights and thresholds here\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n/**\n * Dimension weights. Used to compute the weighted average of applicable dimensions.\n * Dimensions that don't apply (e.g. no build ran) are excluded from the average.\n */\nconst WEIGHTS = {\n build: 0.3,\n tests: 0.25,\n toolErrors: 0.2,\n loops: 0.1,\n regression: 0.1,\n autonomy: 0.05,\n} as const;\n\n/**\n * Scoring thresholds and multipliers.\n */\nconst THRESHOLDS = {\n /** Multiplier for tool error rate penalty. Score = max(0, 1 - rate × this). */\n toolErrorPenaltyMultiplier: 1.0,\n\n /** How many consecutive identical calls (or same-error repeats) before it's a \"loop\". */\n loopMinRepetitions: 3,\n\n /** Score penalty per detected loop. */\n loopPenaltyPerOccurrence: 0.3,\n\n /** Score deducted per ask_user call. */\n autonomyPenaltyPerAsk: 0.25,\n\n /** Score when a command ran but exit code is ambiguous. */\n ambiguousExitScore: 0.75,\n\n /** Minimum tool calls required to produce a meaningful score. */\n minToolCalls: 1,\n\n /** Tool names whose errors are expected/benign (not penalized). */\n benignErrorTools: ['search_content', 'find_files', 'lsp_inspect'] as string[],\n} as const;\n\n// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\ntype DimensionResult = { score: number; detail: string; applicable: boolean };\n\n/**\n * Check if the primary verb of an execute_command is a build/typecheck command.\n * Splits compound commands (&&, ;) and checks the first segment.\n */\n/** Extract command string from tool call args, then delegate to shared classifier. */\nfunction isBuildArgs(args: Record<string, unknown>): boolean {\n return isBuildCommand(String(args.command ?? ''));\n}\n\nfunction isTestArgs(args: Record<string, unknown>): boolean {\n return isTestCommand(String(args.command ?? ''));\n}\n\nfunction isForegroundCommand(result: ExtractedToolCall): boolean {\n return result.args.background !== true;\n}\n\n/**\n * Score build/typecheck outcome (final state).\n */\nfunction scoreBuild(execResults: ExtractedToolCall[]): DimensionResult {\n const builds = execResults.filter(\n r => r.toolName === 'execute_command' && isForegroundCommand(r) && isBuildArgs(r.args),\n );\n if (builds.length === 0) return { score: 0, detail: 'No build/typecheck ran', applicable: false };\n\n const last = builds[builds.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Build/typecheck tool errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Build failed (exit ${exitCode})`, applicable: true };\n if (typeof last.result === 'string') return { score: 1, detail: 'Build/typecheck passed', applicable: true };\n\n const text = JSON.stringify(last.result ?? '');\n if (/error TS\\d+|Cannot find module|is not assignable/i.test(text)) {\n return { score: 0, detail: 'Build failed (TypeScript errors in output)', applicable: true };\n }\n if (isSuccessResult(last.result)) return { score: 1, detail: 'Build/typecheck passed', applicable: true };\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Build ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score test outcome (final state).\n */\nfunction scoreTests(execResults: ExtractedToolCall[]): DimensionResult {\n const tests = execResults.filter(\n r => r.toolName === 'execute_command' && isForegroundCommand(r) && isTestArgs(r.args),\n );\n if (tests.length === 0) return { score: 0, detail: 'No tests ran', applicable: false };\n\n const last = tests[tests.length - 1]!;\n if (last.isError) return { score: 0, detail: 'Test command errored', applicable: true };\n\n const exitCode = getExitCode(last.result);\n if (exitCode !== null && exitCode !== 0)\n return { score: 0, detail: `Tests failed (exit ${exitCode})`, applicable: true };\n if (typeof last.result === 'string') return { score: 1, detail: 'Tests passed', applicable: true };\n\n const text = JSON.stringify(last.result ?? '');\n if (/\\bFAIL\\b|failed|✗|✘/i.test(text)) {\n return { score: 0, detail: 'Tests failed (inferred)', applicable: true };\n }\n if (/\\d+ (?:tests? )?passed|✓|PASS/i.test(text) && !/\\bfail(?:ed|ure)?\\b|\\berror\\b/i.test(text)) {\n return { score: 1, detail: 'Tests passed (inferred)', applicable: true };\n }\n if (isSuccessResult(last.result)) return { score: 1, detail: 'Tests passed', applicable: true };\n\n return { score: THRESHOLDS.ambiguousExitScore, detail: 'Tests ran, outcome unclear', applicable: true };\n}\n\n/**\n * Score tool error rate, excluding benign errors from expected-to-fail tools.\n */\nfunction scoreToolErrors(results: ExtractedToolCall[]): DimensionResult {\n if (results.length === 0) return { score: 1, detail: 'No tool calls', applicable: false };\n\n // Only count errors from non-benign tools\n const nonBenign = results.filter(r => !THRESHOLDS.benignErrorTools.includes(r.toolName));\n if (nonBenign.length === 0) return { score: 1, detail: 'All tool calls are benign-error tools', applicable: true };\n\n const errors = nonBenign.filter(r => r.isError);\n const rate = errors.length / nonBenign.length;\n\n if (rate === 0) return { score: 1, detail: 'No tool errors', applicable: true };\n\n const score = Math.max(0, 1 - rate * THRESHOLDS.toolErrorPenaltyMultiplier);\n return {\n score,\n detail: `${errors.length}/${nonBenign.length} tools errored (${(rate * 100).toFixed(0)}%)`,\n applicable: true,\n };\n}\n\n/**\n * Detect stuck loops: same tool + same args appearing 3+ times consecutively,\n * or same tool + same args erroring 3+ times total.\n */\nfunction scoreStuckLoops(results: ExtractedToolCall[]): DimensionResult {\n if (results.length < 3) return { score: 1, detail: 'Too few calls for loop detection', applicable: true };\n\n const fingerprint = (r: ExtractedToolCall) => `${r.toolName}:${JSON.stringify(r.args)}`;\n\n // Check consecutive identical calls\n let maxConsecutive = 1;\n let currentRun = 1;\n for (let i = 1; i < results.length; i++) {\n if (fingerprint(results[i]!) === fingerprint(results[i - 1]!)) {\n currentRun++;\n maxConsecutive = Math.max(maxConsecutive, currentRun);\n } else {\n currentRun = 1;\n }\n }\n\n // Check repeated error fingerprints\n const errorCounts = new Map<string, number>();\n for (const r of results) {\n if (!r.isError) continue;\n const fp = fingerprint(r);\n errorCounts.set(fp, (errorCounts.get(fp) ?? 0) + 1);\n }\n const maxErrorRepeat = Math.max(0, ...[...errorCounts.values()]);\n\n const minReps = THRESHOLDS.loopMinRepetitions;\n const loopSeverity = Math.max(\n maxConsecutive >= minReps ? maxConsecutive - (minReps - 1) : 0,\n maxErrorRepeat >= minReps ? maxErrorRepeat - (minReps - 1) : 0,\n );\n\n if (loopSeverity === 0) return { score: 1, detail: 'No stuck loops', applicable: true };\n\n const score = Math.max(0, 1 - loopSeverity * THRESHOLDS.loopPenaltyPerOccurrence);\n const details: string[] = [];\n if (maxConsecutive >= minReps) details.push(`${maxConsecutive} consecutive identical calls`);\n if (maxErrorRepeat >= minReps) details.push(`same error repeated ${maxErrorRepeat}x`);\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Detect regressions: build/test passed at some point, then failed later.\n * Gives partial credit if the agent recovered (final state passes).\n */\nfunction scoreRegression(execResults: ExtractedToolCall[]): DimensionResult {\n const regressions: { label: string; recovered: boolean }[] = [];\n\n for (const [label, filter] of [\n ['Build', isBuildArgs],\n ['Tests', isTestArgs],\n ] as const) {\n const cmds = execResults.filter(r => r.toolName === 'execute_command' && isForegroundCommand(r) && filter(r.args));\n if (cmds.length < 2) continue;\n\n let sawPass = false;\n let sawRegression = false;\n for (const cmd of cmds) {\n const exitCode = getExitCode(cmd.result);\n const passed = isSuccessResult(cmd.result, cmd.isError);\n const failed = cmd.isError || (exitCode !== null && exitCode !== 0);\n\n if (passed) {\n if (sawRegression) {\n // Recovered from regression\n regressions.push({ label, recovered: true });\n sawRegression = false;\n }\n sawPass = true;\n }\n if (sawPass && failed) {\n sawRegression = true;\n }\n }\n\n if (sawRegression) {\n // Regression persisted at end of session\n regressions.push({ label, recovered: false });\n }\n }\n\n if (regressions.length === 0) return { score: 1, detail: 'No regressions', applicable: true };\n\n // Persistent regressions are severe (0), recovered regressions get partial credit (0.5)\n const persistentCount = regressions.filter(r => !r.recovered).length;\n const recoveredCount = regressions.filter(r => r.recovered).length;\n const score = Math.max(0, 1 - persistentCount * 0.5 - recoveredCount * 0.1);\n const details = regressions.map(\n r => `${r.label} ${r.recovered ? 'regressed then recovered' : 'regressed (persisted)'}`,\n );\n return { score, detail: details.join('; '), applicable: true };\n}\n\n/**\n * Score autonomy: penalize ask_user calls.\n * 0 calls = 1.0, each call reduces by 0.25 (up to a floor of 0).\n */\nfunction scoreAutonomy(results: ExtractedToolCall[]): DimensionResult {\n const askUserCalls = results.filter(r => r.toolName === 'ask_user');\n const count = askUserCalls.length;\n\n if (count === 0) return { score: 1, detail: 'No ask_user calls (fully autonomous)', applicable: true };\n\n const score = Math.max(0, 1 - count * THRESHOLDS.autonomyPenaltyPerAsk);\n return { score, detail: `${count} ask_user call${count > 1 ? 's' : ''}`, applicable: true };\n}\n\n/**\n * Compute weighted average of only applicable dimensions.\n * Returns null if no dimensions are applicable.\n */\nfunction weightedAverage(dimensions: Record<string, DimensionResult>, weights: Record<string, number>): number | null {\n let totalWeight = 0;\n let weightedSum = 0;\n\n for (const [key, result] of Object.entries(dimensions)) {\n if (!result.applicable) continue;\n const weight = weights[key] ?? 0;\n totalWeight += weight;\n weightedSum += result.score * weight;\n }\n\n if (totalWeight === 0) return null;\n return weightedSum / totalWeight;\n}\n\nexport function createOutcomeScorer() {\n return createScorer({\n id: 'mastracode-outcome',\n name: 'MastraCode Outcome',\n description:\n 'Grades coding session outcomes: build/test pass, tool errors, stuck loops, regressions, autonomy. Always-on.',\n type: 'agent',\n prepareRun: filterRun({ partTypes: ['tool-invocation', 'text'] }),\n })\n .preprocess(async ({ run }) => {\n const messages = (run.output ?? []) as MastraDBMessage[];\n const allResults = extractToolCalls(messages);\n const totalCalls = allResults.length;\n\n // H1: Empty sessions or sessions with no tool calls → score 0\n if (totalCalls < THRESHOLDS.minToolCalls) {\n const empty: DimensionResult = { score: 0, detail: 'No tool calls', applicable: false };\n return {\n empty: true as const,\n build: empty,\n tests: empty,\n toolErrors: empty,\n loops: empty,\n regression: empty,\n autonomy: empty,\n totalCalls,\n };\n }\n\n const execResults = allResults.filter(r => r.toolName === 'execute_command');\n\n return {\n empty: false as const,\n build: scoreBuild(execResults),\n tests: scoreTests(execResults),\n toolErrors: scoreToolErrors(allResults),\n loops: scoreStuckLoops(allResults),\n regression: scoreRegression(execResults),\n autonomy: scoreAutonomy(allResults),\n totalCalls,\n };\n })\n .generateScore(({ results }) => {\n const p = results.preprocessStepResult;\n if (p.empty) return 0;\n\n const score = weightedAverage(\n {\n build: p.build,\n tests: p.tests,\n toolErrors: p.toolErrors,\n loops: p.loops,\n regression: p.regression,\n autonomy: p.autonomy,\n },\n WEIGHTS,\n );\n\n return score === null ? 0 : Math.round(score * 100) / 100;\n })\n .generateReason(({ results, score }) => {\n const p = results.preprocessStepResult;\n if (p.empty) {\n return `Score: 0 (${p.totalCalls} tool calls — below minimum threshold for scoring)`;\n }\n\n const pct = (w: number) => `${(w * 100).toFixed(0)}%`;\n const dimLine = (name: string, weight: number, r: DimensionResult) =>\n r.applicable\n ? `${name} (${pct(weight)}): ${r.detail} [${r.score}]`\n : `${name}: ${r.detail} [N/A — excluded from average]`;\n\n const parts: string[] = [`Score: ${score} (${p.totalCalls} tool calls total)`];\n parts.push(dimLine('Build', WEIGHTS.build, p.build));\n parts.push(dimLine('Tests', WEIGHTS.tests, p.tests));\n parts.push(dimLine('Tool errors', WEIGHTS.toolErrors, p.toolErrors));\n parts.push(dimLine('Loops', WEIGHTS.loops, p.loops));\n parts.push(dimLine('Regression', WEIGHTS.regression, p.regression));\n parts.push(dimLine('Autonomy', WEIGHTS.autonomy, p.autonomy));\n\n return parts.join('\\n');\n });\n}\n"],"mappings":";;;;;;;;AAuCA,MAAM,UAAU;CACd,OAAO;CACP,OAAO;CACP,YAAY;CACZ,OAAO;CACP,YAAY;CACZ,UAAU;AACZ;;;;AAKA,MAAM,aAAa;;CAEjB,4BAA4B;;CAG5B,oBAAoB;;CAGpB,0BAA0B;;CAG1B,uBAAuB;;CAGvB,oBAAoB;;CAGpB,cAAc;;CAGd,kBAAkB;EAAC;EAAkB;EAAc;CAAa;AAClE;;;;;;AAWA,SAAS,YAAY,MAAwC;CAC3D,OAAO,eAAe,OAAO,KAAK,WAAW,EAAE,CAAC;AAClD;AAEA,SAAS,WAAW,MAAwC;CAC1D,OAAO,cAAc,OAAO,KAAK,WAAW,EAAE,CAAC;AACjD;AAEA,SAAS,oBAAoB,QAAoC;CAC/D,OAAO,OAAO,KAAK,eAAe;AACpC;;;;AAKA,SAAS,WAAW,aAAmD;CACrE,MAAM,SAAS,YAAY,QACzB,MAAK,EAAE,aAAa,qBAAqB,oBAAoB,CAAC,KAAK,YAAY,EAAE,IAAI,CACvF;CACA,IAAI,OAAO,WAAW,GAAG,OAAO;EAAE,OAAO;EAAG,QAAQ;EAA0B,YAAY;CAAM;CAEhG,MAAM,OAAO,OAAO,OAAO,SAAS;CACpC,IAAI,KAAK,SAAS,OAAO;EAAE,OAAO;EAAG,QAAQ;EAAgC,YAAY;CAAK;CAE9F,MAAM,WAAW,YAAY,KAAK,MAAM;CACxC,IAAI,aAAa,QAAQ,aAAa,GACpC,OAAO;EAAE,OAAO;EAAG,QAAQ,sBAAsB,SAAS;EAAI,YAAY;CAAK;CACjF,IAAI,OAAO,KAAK,WAAW,UAAU,OAAO;EAAE,OAAO;EAAG,QAAQ;EAA0B,YA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G,GAAE;IAAE,wBAAwB,CAAC,EAAE,MAAM,CAAA;CAAgB,GAAG,OAAO,CAKxG;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,GAAG,IAAI,GAAG,KAAK,CAI9F;AAMD,wBAAgB,yBAAyB,CACvC,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,MAAM,GAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAmB,GAC/C,IAAI,CAiCN"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"experimental-agent.js","names":[],"sources":["../src/experimental-agent.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from '@mastra/core/agent/durable';\nimport type { Mastra } from '@mastra/core/mastra';\n\nimport { parseExperimentalAgentSetting } from './onboarding/settings.js';\nimport type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';\n\nexport interface ExperimentalAgentEnvironment {\n MASTRACODE_EXPERIMENTAL_AGENT?: string;\n}\n\nconst ACCEPTED_VALUES = '\"durable\", \"evented\", or unset';\n\nexport function parseExperimentalAgentEnvironment(\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const value = env.MASTRACODE_EXPERIMENTAL_AGENT;\n if (value === undefined || value === '') return null;\n if (value === 'durable' || value === 'evented') return value;\n throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);\n}\n\nexport function resolveExperimentalAgent(\n settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>,\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const environmentSelection = parseExperimentalAgentEnvironment(env);\n if (environmentSelection) return environmentSelection;\n\n return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);\n}\n\n/**\n * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing\n * its runs on a resumable stream; `on` or unset keeps the core default. Any other\n * value, including an empty string, throws so a typo can't silently leave streams on.\n */\nexport function resolveAgentStreamsOff(env: { MASTRACODE_AGENT_STREAMS?: string } = process.env): boolean {\n const value = env.MASTRACODE_AGENT_STREAMS;\n if (value === undefined || value === 'on') return false;\n if (value === 'off') return true;\n throw new Error(`Invalid MASTRACODE_AGENT_STREAMS value ${JSON.stringify(value)}. Expected \"on\", \"off\", or unset.`);\n}\n\nexport function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent {\n if (selection === 'durable') return createDurableAgent({ agent }) as unknown as Agent;\n if (selection === 'evented') return createEventedAgent({ agent }) as unknown as Agent;\n return agent;\n}\n\ninterface WorkflowBackedAgent extends Agent {\n getWorkflow(): { engineType?: string };\n}\n\nexport function validateExperimentalAgent(\n agent: Agent,\n mastra: Mastra | undefined,\n report: (message: string) => void = console.info,\n): void {\n const selection: ExperimentalAgent | null = isEventedAgent(agent)\n ? 'evented'\n : isDurableAgent(agent)\n ? 'durable'\n : null;\n if (!selection) return;\n\n if (selection === 'evented' && (!mastra || agent.getMastraInstance() !== mastra)) {\n throw new Error(\n 'Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.',\n );\n }\n\n const workflowsStore = mastra?.getStorage()?.stores?.workflows;\n if (!workflowsStore) {\n throw new Error(`Experimental agent \"${selection}\" requires a configured workflow storage domain.`);\n }\n if (selection === 'evented' && workflowsStore.supportsConcurrentUpdates?.() !== true) {\n throw new Error(\n 'Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).',\n );\n }\n\n const engineType = (agent as WorkflowBackedAgent).getWorkflow().engineType;\n const expectedEngine = selection === 'evented' ? 'evented' : 'default';\n if (engineType !== expectedEngine) {\n throw new Error(\n `Experimental agent \"${selection}\" resolved workflow engine ${JSON.stringify(engineType)} instead of \"${expectedEngine}\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;GAGG;AACH,wBAAsB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAY5F;AAoBD;;;GAGG;AACH,wBAAsB,wBAAwB,CAC5C,OAAO,EAAE,cAAc,EACvB,mBAAmB,EAAE,MAAM,EAC3B,KAAK,CAAC,EAAE,MAAM,GACb,OAAO,CAAC,kBAAkB,CAAC,CAO7B;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAC7B,OAAO,EAAE,cAAc,EACvB,OAAO,GAAE,MAAM,OAAO,CAAC,eAAe,GAAG,IAAI,CAAsB,EACnE,SAAS,GAAE,OAAO,KAAa,GAC9B,OAAO,KAAK,CAsBd;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,cAAc,GAAG,YAAY,CAGzE"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","names":[],"sources":["../../src/factory/client.ts"],"sourcesContent":["import { MastraClient } from '@mastra/client-js';\n\nimport { getPlatformSession } from '../platform/index.js';\nimport type { PlatformSession } from '../platform/index.js';\n\n/** The agent controller every Factory serves its coding sessions under. */\nexport const FACTORY_CONTROLLER_ID = 'code';\n\nconst ORGANIZATION_ID_HEADER = 'X-Mastra-Organization-Id';\n\nexport interface FactoryAddress {\n url: string;\n session: PlatformSession;\n}\n\nexport interface FactoryRepository {\n projectRepositoryId: string;\n slug: string;\n branch?: string;\n}\n\nexport interface FactoryProject {\n id: string;\n name: string;\n repositories: FactoryRepository[];\n}\n\nexport interface FactoryUserSession {\n sessionId: string;\n projectRepositoryId: string;\n title?: string;\n branch: string;\n updatedAt: string;\n}\n\nexport function factoryHeaders({ session }: FactoryAddress): Record<string, string> {\n return { Authorization: `Bearer ${session.token}`, [ORGANIZATION_ID_HEADER]: session.orgId };\n}\n\nasync function factoryFetch<T>(address: FactoryAddress, path: string, init?: { method?: string; body?: unknown }) {\n const res = await refreshingFetch(address)(`${address.url.replace(/\\/$/, '')}${path}`, {\n method: init?.method ?? 'GET',\n headers: {\n Accept: 'application/json',\n ...(init?.body !== undefined ? { 'content-type': 'application/json' } : {}),\n },\n body: init?.body !== undefined ? JSON.stringify(init.body) : undefined,\n });\n if (!res.ok) {\n const body = (await res.json().catch(() => ({}))) as { error?: string; message?: string };\n throw new Error(\n `Factory request ${path} failed (${res.status})${body.message || body.error ? `: ${body.message ?? body.error}` : ''}`,\n );\n }\n return (await res.json()) as T;\n}\n\ninterface ProjectConnectionPayload {\n repositories: Array<{\n id: string;\n branch: string | null;\n repository: { slug: string; defaultBranch: string } | null;\n }>;\n}\n\ninterface ProjectListRepositoryPayload {\n projectRepositoryId: string;\n slug: string | null;\n defaultBranch: string | null;\n branch: string | null;\n}\n\ninterface ProjectListPayload {\n projects: Array<{ id: string; name: string; repositories?: ProjectListRepositoryPayload[] }>;\n}\n\nfunction toFactoryRepository(projectName: string, repository: ProjectListRepositoryPayload): FactoryRepository {\n return {\n projectRepositoryId: repository.projectRepositoryId,\n slug: repository.slug ?? projectName,\n branch: repository.branch ?? repository.defaultBranch ?? undefined,\n };\n}\n\n/**\n * List the org's Factory projects with their linked repositories. Current servers return the repositories with the\n * project list; an older server, which does not, is asked once per project.\n */\nexport async function listFactoryProjects(address: FactoryAddress): Promise<FactoryProject[]> {\n const { projects } = await factoryFetch<ProjectListPayload>(address, '/web/factory/projects');\n return Promise.all(\n projects.map(async project => {\n const repositories = project.repositories ?? (await listProjectRepositories(address, project.id));\n return {\n id: project.id,\n name: project.name,\n repositories: repositories.map(repository => toFactoryRepository(project.name, repository)),\n };\n }),\n );\n}\n\nasync function listProjectRepositories(\n address: FactoryAddress,\n projectId: string,\n): Promise<ProjectListRepositoryPayload[]> {\n const { connections } = await factoryFetch<{ connections: ProjectConnectionPayload[] }>(\n address,\n `/web/factory/projects/${encodeURIComponent(projectId)}/source-control-connections`,\n );\n return connections.flatMap(connection =>\n connection.repositories.map(link => ({\n projectRepositoryId: link.id,\n slug: link.repository?.slug ?? null,\n defaultBranch: link.repository?.defaultBranch ?? null,\n branch: link.branch,\n })),\n );\n}\n\n/**\n * Create a Factory user session. Factory assigns the session ID and its\n * `user/session-<id>` branch, cut from the repository's default branch.\n */\nexport async function createFactoryUserSession(\n address: FactoryAddress,\n projectRepositoryId: string,\n title?: string,\n): Promise<FactoryUserSession> {\n const { session } = await factoryFetch<{ session: FactoryUserSession & { title?: string | null } }>(\n address,\n `/web/source-control/projects/${encodeURIComponent(projectRepositoryId)}/sessions`,\n { method: 'POST', body: title ? { title } : {} },\n );\n return { ...session, title: session.title ?? undefined };\n}\n\n/**\n * Platform access tokens expire while a long-lived TUI is open. On a 401,\n * refresh the session and replay the request once with the new token; a\n * rejected request never ran, so the replay cannot duplicate a command.\n */\nexport function refreshingFetch(\n address: FactoryAddress,\n refresh: () => Promise<PlatformSession | null> = getPlatformSession,\n baseFetch: typeof fetch = fetch,\n): typeof fetch {\n const withAuth = (init: RequestInit | undefined) => {\n const headers = new Headers(init?.headers);\n for (const [key, value] of Object.entries(factoryHeaders(address))) headers.set(key, value);\n return { ...init, headers };\n };\n // Concurrent 401s share one refresh so the token is not rotated repeatedly.\n let refreshing: Promise<PlatformSession | null> | undefined;\n return async (input, init) => {\n const sentToken = address.session.token;\n const res = await baseFetch(input, withAuth(init));\n if (res.status !== 401) return res;\n if (address.session.token === sentToken) {\n refreshing ??= refresh().finally(() => {\n refreshing = undefined;\n });\n const session = await refreshing;\n if (!session || session.token === sentToken) return res;\n address.session = session;\n }\n return baseFetch(input, withAuth(init));\n };\n}\n\nexport function createFactoryClient(address: FactoryAddress): MastraClient {\n // Session commands are not idempotent; a silent retry would duplicate messages.\n return new MastraClient({ baseUrl: address.url.replace(/\\/$/, ''), retries: 0, fetch: refreshingFetch(address) });\n}\n"],"mappings":";;;;AAMA,MAAa,wBAAwB;AAErC,MAAM,yBAAyB;AA2B/B,SAAgB,eAAe,EAAE,WAAmD;CAClF,OAAO;EAAE,eAAe,UAAU,QAAQ;GAAU,yBAAyB,QAAQ;CAAM;AA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3,"file":"remote-controller.js","names":[],"sources":["../../src/factory/remote-controller.ts"],"sourcesContent":["import type { AvailableModel, ModelAuthStatus } from '@mastra/core/agent-controller';\n\nimport type { FactoryAddress } from './client.js';\nimport { createFactoryClient, FACTORY_CONTROLLER_ID } from './client.js';\n\nexport interface RemoteMode {\n id: string;\n name?: string;\n description?: string;\n default?: boolean;\n defaultModelId?: string;\n metadata?: Record<string, unknown>;\n}\n\ntype ControllerHandle = ReturnType<ReturnType<typeof createFactoryClient>['getAgentController']>;\n\n/**\n * The Factory-side counterpart to the local agent controller. Modes, models, and\n * provider auth come from the Factory, never from local settings or auth storage.\n */\nexport class RemoteController {\n readonly id = FACTORY_CONTROLLER_ID;\n readonly #remote: ControllerHandle;\n #modes: RemoteMode[] = [];\n #models: Promise<AvailableModel[]> | undefined;\n\n constructor(address: FactoryAddress, remote?: ControllerHandle) {\n this.#remote = remote ?? createFactoryClient(address).getAgentController(FACTORY_CONTROLLER_ID);\n }\n\n /** Load the mode list; `listModes()` is synchronous so it must be primed. */\n async connect(): Promise<void> {\n this.#modes = (await this.#remote.listModes()) as RemoteMode[];\n }\n\n listModes(): RemoteMode[] {\n return this.#modes;\n }\n\n listAvailableModels(): Promise<AvailableModel[]> {\n this.#models ??= this.#remote.listModels().then(models => models as AvailableModel[]);\n this.#models.catch(() => (this.#models = undefined));\n return this.#models;\n }\n\n invalidateAvailableModelsCache(): void {\n this.#models = undefined;\n }\n\n /** Auth is the Factory's: report what it reports, or assume ok and let the run surface errors. */\n async getCurrentModelAuthStatus(session: { model: { get(): string } }): Promise<ModelAuthStatus> {\n const modelId = session.model.get();\n const models = await this.listAvailableModels().catch(() => []);\n const model = models.find(m => m.id === modelId);\n return model ? { hasAuth: model.hasApiKey, apiKeyEnvVar: model.apiKeyEnvVar } : { hasAuth: true };\n }\n}\n"],"mappings":";;;;;;AAoBA,IAAa,mBAAb,MAA8B;CAC5B,KAAc;CACd;CACA,SAAuB,CAAC;CACxB;CAEA,YAAY,SAAyB,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],"sources":["../../src/factory/remote-session.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\n\nimport type { AgentControllerEvent as ClientEvent, AgentControllerModeInfo } from '@mastra/client-js';\nimport type {\n AgentControllerDisplayState,\n AgentControllerEvent,\n AgentControllerEventListener,\n AgentControllerRequestStateUpdater,\n AgentControllerThread,\n PermissionRules,\n Session,\n} from '@mastra/core/agent-controller';\nimport { defaultDisplayState } from '@mastra/core/agent-controller';\n\nimport type { FactoryAddress } from './client.js';\nimport { createFactoryClient, FACTORY_CONTROLLER_ID } from './client.js';\n\ntype RemoteHandle = ReturnType<ReturnType<ReturnType<typeof createFactoryClient>['getAgentController']>['session']>;\ntype RemoteMode = AgentControllerModeInfo;\ntype Files = Array<{ data: string; mediaType: string; filename?: string }>;\n\nconst MAP_FIELDS = [\n 'activeTools',\n 'toolInputBuffers',\n 'pendingSuspensions',\n 'pendingApprovals',\n 'activeSubagents',\n 'modifiedFiles',\n] as const;\n\n/** The wire flattens the display state's Maps to objects; restore them. */\nfunction hydrateDisplayState(wire: Record<string, unknown>): AgentControllerDisplayState {\n const state: Record<string, unknown> = { ...defaultDisplayState(), ...wire };\n for (const field of MAP_FIELDS) {\n const value = wire[field];\n state[field] = value instanceof Map ? value : new Map(Object.entries((value as object | undefined) ?? {}));\n }\n return state as unknown as AgentControllerDisplayState;\n}\n\n/** The wire flattens errors to `{ name, message }`; restore them. */\nfunction hydrateEvent(event: ClientEvent): AgentControllerEvent {\n const out: Record<string, unknown> = { ...event };\n if (out.displayState && typeof out.displayState === 'object') {\n out.displayState = hydrateDisplayState(out.displayState as Record<string, unknown>);\n }\n const error = out.error as { name?: string; message?: string } | undefined;\n if (error && typeof error === 'object' && !(error instanceof Error)) {\n out.error = Object.assign(new Error(error.message ?? 'Remote error'), { name: error.name ?? 'Error' });\n }\n return out as unknown as AgentControllerEvent;\n}\n\nfunction toThread(\n thread: { id: string; title?: string; resourceId?: string; createdAt?: unknown; updatedAt?: unknown },\n resourceId: string,\n): AgentControllerThread {\n const date = (value: unknown) => (value ? new Date(value as string) : new Date());\n return {\n id: thread.id,\n resourceId: thread.resourceId ?? resourceId,\n title: thread.title ?? '',\n createdAt: date(thread.createdAt),\n updatedAt: date(thread.updatedAt),\n } as AgentControllerThread;\n}\n\n/**\n * Stands in for an in-process `Session` while the agent, tools, and storage\n * run inside a Factory. Reads are served from state mirrored off the session's\n * event stream; every action is forwarded to the Factory over HTTP.\n *\n * Only the surface the TUI drives is implemented. Anything else resolves to a\n * no-op so local-only features (thread locks, grants) degrade instead of crash.\n */\nexport class RemoteSession {\n readonly #remote: RemoteHandle;\n readonly #sessionId: string;\n /** Whose threads and memory the session works on; the Factory reports it when the session is created. */\n #resourceId: string;\n readonly #listeners = new Set<AgentControllerEventListener>();\n #unsubscribe: (() => void) | undefined;\n #threadId: string | null = null;\n #modeId = '';\n #modelId = '';\n #running = false;\n #state: Record<string, unknown> = {};\n #displayState: AgentControllerDisplayState = defaultDisplayState();\n #modes: RemoteMode[] = [];\n #permissionRules: PermissionRules = { categories: {}, tools: {} };\n #pendingUserIds: string[] = [];\n readonly #userIdMap = new Map<string, string>();\n\n constructor(address: FactoryAddress, sessionId: string, remote?: RemoteHandle) {\n this.#sessionId = sessionId;\n this.#resourceId = sessionId;\n this.#remote = remote ?? createFactoryClient(address).getAgentController(FACTORY_CONTROLLER_ID).session(sessionId);\n }\n\n /** Create/resume the remote session, hydrate the mirror, and open the event stream. */\n async connect(): Promise<void> {\n const created = await this.#remote.create();\n if (created?.resourceId) this.#resourceId = created.resourceId;\n await Promise.all([this.#hydrate(), this.#refreshPermissions()]);\n const subscription = await this.#remote.subscribe({\n reconnect: true,\n onEvent: event => this.#receive(hydrateEvent(event)),\n // The server does not replay missed events; resync after a drop.\n onReconnect: () => void this.#hydrate().catch(() => {}),\n });\n this.#unsubscribe = subscription.unsubscribe;\n }\n\n /** Modes come from the controller; used to resolve the current mode's name and color. */\n setModes(modes: RemoteMode[]): void {\n this.#modes = modes;\n }\n\n disconnect(): void {\n this.#unsubscribe?.();\n this.#unsubscribe = undefined;\n }\n\n async #hydrate(): Promise<void> {\n const snapshot = await this.#remote.state();\n this.#threadId = snapshot.threadId ?? null;\n this.#modeId = snapshot.modeId;\n this.#modelId = snapshot.modelId;\n this.#running = Boolean(snapshot.running);\n // Settings (yolo, thinkingLevel, notifications, smartEditing) are session\n // state; the TUI reads them through state.get().\n if (snapshot.settings) this.#state = { ...this.#state, ...snapshot.settings };\n this.#displayState = {\n ...this.#displayState,\n ...(snapshot.tasks ? { tasks: snapshot.tasks } : {}),\n ...(snapshot.tokenUsage ? { tokenUsage: snapshot.tokenUsage } : {}),\n } as AgentControllerDisplayState;\n }\n\n async #refreshPermissions(): Promise<void> {\n const rules = await this.#remote.getPermissions();\n this.#permissionRules = {\n categories: (rules.categories ?? {}) as PermissionRules['categories'],\n tools: rules.tools ?? {},\n };\n }\n\n /** Surface a failed remote command in the transcript instead of dropping it. */\n #emitError(message: string): void {\n this.#receive({ type: 'error', error: new Error(message) } as AgentControllerEvent);\n }\n\n /**\n * The TUI renders a user message as soon as it is sent, keyed by the id\n * `sendSignal` returned. The Factory echoes it back under its own id, so map\n * that echo onto the local id to keep it from rendering twice.\n */\n #adoptLocalUserId(e: Record<string, any>): void {\n const message = e.message as\n | { id?: string; role?: string; content?: { metadata?: { signal?: { type?: string } } } }\n | undefined;\n const isUser =\n message?.role === 'user' || (message?.role === 'signal' && message.content?.metadata?.signal?.type === 'user');\n if (!message?.id || !isUser) return;\n let localId = this.#userIdMap.get(message.id);\n if (!localId && e.type === 'message_start') {\n localId = this.#pendingUserIds.shift();\n if (localId) this.#userIdMap.set(message.id, localId);\n }\n if (localId) e.message = { ...message, id: localId };\n }\n\n #receive(event: AgentControllerEvent): void {\n const e = event as AgentControllerEvent & Record<string, any>;\n if (e.type === 'message_start' || e.type === 'message_update' || e.type === 'message_end') {\n this.#adoptLocalUserId(e);\n }\n switch (e.type) {\n case 'mode_changed':\n this.#modeId = e.modeId;\n break;\n case 'model_changed':\n this.#modelId = e.modelId;\n break;\n case 'thread_changed':\n this.#threadId = e.threadId;\n break;\n case 'thread_created':\n this.#threadId = e.thread.id;\n break;\n case 'state_changed':\n this.#state = { ...this.#state, ...e.state };\n break;\n case 'display_state_changed':\n this.#displayState = e.displayState;\n break;\n case 'agent_start':\n this.#running = true;\n break;\n case 'agent_end':\n this.#running = false;\n break;\n }\n for (const listener of this.#listeners) {\n void Promise.resolve(listener(event)).catch(() => {});\n }\n }\n\n subscribe(listener: AgentControllerEventListener): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n onBeforeAgentEnd(): () => void {\n return () => {};\n }\n\n readonly identity = {\n getResourceId: () => this.#resourceId,\n getDefaultResourceId: () => this.#resourceId,\n getId: () => this.#sessionId,\n getOwnerId: () => this.#sessionId,\n setResourceId: () => {},\n };\n\n readonly thread = (() => {\n const remote = () => this.#remote;\n const resourceId = () => this.#resourceId;\n return {\n getId: () => this.#threadId,\n isSet: () => this.#threadId !== null,\n requireId: () => {\n if (!this.#threadId) throw new Error('No active thread');\n return this.#threadId;\n },\n ensureId: async () => {\n if (!this.#threadId) await this.thread.create();\n return this.#threadId!;\n },\n list: async () => (await remote().listThreads()).map(t => toThread(t, resourceId())),\n getById: async ({ threadId }: { threadId: string }) =>\n (await this.thread.list()).find(t => t.id === threadId) ?? null,\n create: async ({ title }: { title?: string } = {}) => {\n const created = await remote().createThread(title);\n const thread = toThread(created as any, resourceId());\n this.#threadId = thread.id;\n return thread;\n },\n switch: async ({ threadId }: { threadId: string }) => {\n await remote().switchThread(threadId);\n this.#threadId = threadId;\n },\n clone: async ({ sourceThreadId, title }: { sourceThreadId?: string; title?: string } = {}) => {\n const created = await remote().cloneThread({ sourceThreadId, title });\n const thread = toThread(created as any, resourceId());\n this.#threadId = thread.id;\n return thread;\n },\n rename: async ({ title }: { title: string }) => {\n if (this.#threadId) await remote().renameThread(this.#threadId, title);\n },\n delete: async ({ threadId }: { threadId: string }) => {\n await remote().deleteThread(threadId);\n if (this.#threadId === threadId) this.#threadId = null;\n },\n listMessages: ({ threadId, limit }: { threadId: string; limit?: number }) =>\n remote().listMessages(threadId, limit),\n listActiveMessages: async ({ limit }: { limit?: number } = {}) =>\n this.#threadId ? remote().listMessages(this.#threadId, limit) : [],\n firstUserMessage: async () => null,\n firstUserMessages: async () => new Map(),\n // Thread settings live in the Factory; local overrides are not persisted.\n getSetting: async () => undefined,\n getSettingOn: async () => undefined,\n setSetting: async () => {},\n setSettingOn: async () => {},\n deleteSetting: async () => {},\n cleanupSubscription: () => {},\n detachFromCurrent: () => {},\n clear: () => {\n this.#threadId = null;\n },\n clearAndReleaseLock: async () => {},\n cloneToCurrentResource: async ({ sourceThreadId }: { sourceThreadId: string }) =>\n this.thread.clone({ sourceThreadId }),\n loadMetadata: async () => {},\n };\n })();\n\n readonly mode = {\n get: () => this.#modeId,\n hasSelection: () => Boolean(this.#modeId),\n resolve: () => this.#modes.find(mode => mode.id === this.#modeId) ?? { id: this.#modeId, name: this.#modeId },\n set: ({ modeId }: { modeId: string }) => {\n this.#modeId = modeId;\n },\n switch: async ({ modeId }: { modeId: string }) => {\n await this.#remote.switchMode(modeId);\n this.#modeId = modeId;\n },\n };\n\n readonly model = {\n get: () => this.#modelId,\n hasSelection: () => Boolean(this.#modelId),\n displayName: () => this.#modelId,\n set: ({ modelId }: { modelId: string }) => {\n this.#modelId = modelId;\n },\n switch: async (modelId: string, options: { thinkingLevel?: any } = {}) => {\n await this.#remote.switchModel(modelId, options);\n this.#modelId = modelId;\n },\n syncFromPersisted: async () => {},\n };\n\n readonly state = {\n get: () => this.#state,\n set: async (updates: Record<string, unknown>) => {\n this.#state = { ...this.#state, ...updates };\n await this.#remote.setState(updates);\n },\n setIf: async (updates: Record<string, unknown>, shouldApply: () => boolean) => {\n if (!shouldApply()) return false;\n await this.state.set(updates);\n return true;\n },\n update: async <TResult>(updater: AgentControllerRequestStateUpdater<any, TResult>): Promise<TResult> => {\n const { updates, result } = await updater(this.#state);\n if (updates) await this.state.set(updates);\n return result;\n },\n };\n\n readonly displayState = {\n get: () => this.#displayState,\n clearModifiedFiles: () => {\n this.#displayState = { ...this.#displayState, modifiedFiles: new Map() };\n },\n restoreTasks: () => {},\n clearPendingSuspensions: () => {},\n deletePendingSuspension: () => {},\n clearPendingApprovals: () => {},\n resetThread: () => {},\n apply: () => {},\n };\n\n readonly run = {\n isRunning: () => this.#running,\n getRunId: () => null,\n getTraceId: () => null,\n };\n\n readonly stream = { isActive: () => this.#running, isOpen: () => this.#running };\n\n readonly suspensions = {\n hasPending: () => this.#displayState.pendingSuspensions.size > 0,\n get: ({ toolCallId }: { toolCallId: string }) => this.#displayState.pendingSuspensions.get(toolCallId),\n has: ({ toolCallId }: { toolCallId: string }) => this.#displayState.pendingSuspensions.has(toolCallId),\n delete: () => {},\n };\n\n readonly permissions = {\n getRules: () => this.#permissionRules,\n setForCategory: async ({ category, policy }: { category: any; policy: any }) => {\n await this.#remote.setPermissionForCategory(category, policy);\n await this.#refreshPermissions();\n },\n setForTool: async ({ toolName, policy }: { toolName: string; policy: any }) => {\n await this.#remote.setPermissionForTool(toolName, policy);\n await this.#refreshPermissions();\n },\n };\n\n getCurrentRunId(): string | null {\n return null;\n }\n\n getTags(): Record<string, string> {\n return {};\n }\n\n getTokenUsage() {\n return this.#displayState.tokenUsage;\n }\n\n getGrants() {\n return { categories: [], tools: [] };\n }\n\n async sendMessage({ content, files }: { content: string; files?: Files }) {\n await this.#remote.sendMessage({ content, files });\n }\n\n async queueMessage({ content }: { content: string }) {\n await this.#remote.followUp(content);\n }\n\n sendSignal(input: Parameters<Session['sendSignal']>[0]) {\n const content: unknown = 'content' in input ? input.content : undefined;\n const text =\n typeof content === 'string'\n ? content\n : Array.isArray(content)\n ? content.map(part => (typeof part === 'string' ? part : ((part as { text?: string })?.text ?? ''))).join('')\n : JSON.stringify(content);\n const files = 'files' in input ? (input.files as Files | undefined) : undefined;\n const message = files?.length ? { content: text, files } : text;\n const id = randomUUID();\n this.#pendingUserIds.push(id);\n const sent = this.#running ? this.#remote.followUp(message) : this.#remote.sendMessage(message);\n sent.catch(() => {\n this.#pendingUserIds = this.#pendingUserIds.filter(pending => pending !== id);\n });\n const accepted = sent.then(() => ({ accepted: true as const }));\n accepted.catch(() => {});\n return { id, type: 'user' as const, accepted, persisted: sent };\n }\n\n async steer({ content }: { content: string }) {\n await this.#remote.steer(content);\n }\n\n async followUp({ content }: { content: string }) {\n await this.#remote.followUp(content);\n }\n\n respondToToolApproval({\n decision,\n toolCallId,\n }: {\n decision: 'approve' | 'decline' | 'always_allow_category';\n toolCallId: string;\n }) {\n void (async () => {\n const ack = await this.#remote.approveTool(toolCallId, decision !== 'decline', {\n alwaysAllowCategory: decision === 'always_allow_category',\n });\n if (ack && 'accepted' in ack && ack.accepted === false) {\n this.#emitError(`Tool approval was not applied: ${(ack as { reason?: string }).reason ?? 'rejected'}`);\n }\n })().catch(error =>\n this.#emitError(`Tool approval failed: ${error instanceof Error ? error.message : String(error)}`),\n );\n return { accepted: true as const };\n }\n\n async respondToToolSuspension({ resumeData, toolCallId }: { resumeData: unknown; toolCallId?: string }) {\n const id = toolCallId ?? this.#displayState.pendingSuspensions.keys().next().value;\n if (!id) throw new Error('No pending tool suspension to respond to');\n await this.#remote.respondToToolSuspension(\n id,\n resumeData as Parameters<RemoteHandle['respondToToolSuspension']>[1],\n );\n }\n\n claimToolResponse(): boolean {\n return true;\n }\n\n releaseToolResponse(): void {}\n\n abort(): void {\n void this.#remote\n .abort()\n .catch(error => this.#emitError(`Abort failed: ${error instanceof Error ? error.message : String(error)}`));\n }\n\n abortRun(): void {\n this.abort();\n }\n}\n"],"mappings":";;;;AAqBA,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,SAAS,oBAAoB,MAA4D;CACvF,MAAM,QAAiC;EAAE,GAAG,oBAAoB;EAAG,GAAG;CAAK;CAC3E,KAAK,MAAM,SAAS,YAAY;EAC9B,MAAM,QAAQ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