@mastra/code-sdk 0.0.0-livekit-beta-v3-20260709031728
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/CHANGELOG.md +41 -0
- package/LICENSE.md +30 -0
- package/README.md +50 -0
- package/dist/acp/agent.d.ts +35 -0
- package/dist/acp/agent.d.ts.map +1 -0
- package/dist/acp/agent.js +173 -0
- package/dist/acp/agent.js.map +1 -0
- package/dist/acp/event-mapper.d.ts +22 -0
- package/dist/acp/event-mapper.d.ts.map +1 -0
- package/dist/acp/event-mapper.js +166 -0
- package/dist/acp/event-mapper.js.map +1 -0
- package/dist/acp/index.d.ts +8 -0
- package/dist/acp/index.d.ts.map +1 -0
- package/dist/acp/index.js +54 -0
- package/dist/acp/index.js.map +1 -0
- package/dist/acp/server.d.ts +7 -0
- package/dist/acp/server.d.ts.map +1 -0
- package/dist/acp/server.js +34 -0
- package/dist/acp/server.js.map +1 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.d.ts.map +1 -0
- package/dist/acp.js +5 -0
- package/dist/acp.js.map +1 -0
- package/dist/agents/instructions.d.ts +6 -0
- package/dist/agents/instructions.d.ts.map +1 -0
- package/dist/agents/instructions.js +41 -0
- package/dist/agents/instructions.js.map +1 -0
- package/dist/agents/mastracode-gateway.d.ts +65 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -0
- package/dist/agents/mastracode-gateway.js +442 -0
- package/dist/agents/mastracode-gateway.js.map +1 -0
- package/dist/agents/memory.d.ts +13 -0
- package/dist/agents/memory.d.ts.map +1 -0
- package/dist/agents/memory.js +107 -0
- package/dist/agents/memory.js.map +1 -0
- package/dist/agents/model.d.ts +55 -0
- package/dist/agents/model.d.ts.map +1 -0
- package/dist/agents/model.js +115 -0
- package/dist/agents/model.js.map +1 -0
- package/dist/agents/modes/build.d.ts +10 -0
- package/dist/agents/modes/build.d.ts.map +1 -0
- package/dist/agents/modes/build.js +45 -0
- package/dist/agents/modes/build.js.map +1 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.d.ts.map +1 -0
- package/dist/agents/modes/explore.js +38 -0
- package/dist/agents/modes/explore.js.map +1 -0
- package/dist/agents/modes/plan.d.ts +6 -0
- package/dist/agents/modes/plan.d.ts.map +1 -0
- package/dist/agents/modes/plan.js +38 -0
- package/dist/agents/modes/plan.js.map +1 -0
- package/dist/agents/prompts/agent-instructions.d.ts +20 -0
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -0
- package/dist/agents/prompts/agent-instructions.js +82 -0
- package/dist/agents/prompts/agent-instructions.js.map +1 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.d.ts.map +1 -0
- package/dist/agents/prompts/build.js +73 -0
- package/dist/agents/prompts/build.js.map +1 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.d.ts.map +1 -0
- package/dist/agents/prompts/fast.js +22 -0
- package/dist/agents/prompts/fast.js.map +1 -0
- package/dist/agents/prompts/index.d.ts +19 -0
- package/dist/agents/prompts/index.d.ts.map +1 -0
- package/dist/agents/prompts/index.js +57 -0
- package/dist/agents/prompts/index.js.map +1 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.d.ts.map +1 -0
- package/dist/agents/prompts/model.js +22 -0
- package/dist/agents/prompts/model.js.map +1 -0
- package/dist/agents/prompts/plan.d.ts +6 -0
- package/dist/agents/prompts/plan.d.ts.map +1 -0
- package/dist/agents/prompts/plan.js +107 -0
- package/dist/agents/prompts/plan.js.map +1 -0
- package/dist/agents/prompts/tool-guidance.d.ts +13 -0
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -0
- package/dist/agents/prompts/tool-guidance.js +181 -0
- package/dist/agents/prompts/tool-guidance.js.map +1 -0
- package/dist/agents/sandbox-filesystem.d.ts +89 -0
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -0
- package/dist/agents/sandbox-filesystem.js +268 -0
- package/dist/agents/sandbox-filesystem.js.map +1 -0
- package/dist/agents/sandbox-reattach.d.ts +19 -0
- package/dist/agents/sandbox-reattach.d.ts.map +1 -0
- package/dist/agents/sandbox-reattach.js +17 -0
- package/dist/agents/sandbox-reattach.js.map +1 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.d.ts.map +1 -0
- package/dist/agents/thread-caveman-state.js +96 -0
- package/dist/agents/thread-caveman-state.js.map +1 -0
- package/dist/agents/tool-availability.d.ts +10 -0
- package/dist/agents/tool-availability.d.ts.map +1 -0
- package/dist/agents/tool-availability.js +105 -0
- package/dist/agents/tool-availability.js.map +1 -0
- package/dist/agents/tools.d.ts +18 -0
- package/dist/agents/tools.d.ts.map +1 -0
- package/dist/agents/tools.js +126 -0
- package/dist/agents/tools.js.map +1 -0
- package/dist/agents/workspace.d.ts +22 -0
- package/dist/agents/workspace.d.ts.map +1 -0
- package/dist/agents/workspace.js +194 -0
- package/dist/agents/workspace.js.map +1 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +152 -0
- package/dist/analytics.js.map +1 -0
- package/dist/auth/index.d.ts +9 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +11 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.d.ts.map +1 -0
- package/dist/auth/pkce.js +21 -0
- package/dist/auth/pkce.js.map +1 -0
- package/dist/auth/providers/anthropic.d.ts +17 -0
- package/dist/auth/providers/anthropic.d.ts.map +1 -0
- package/dist/auth/providers/anthropic.js +94 -0
- package/dist/auth/providers/anthropic.js.map +1 -0
- package/dist/auth/providers/github-copilot.d.ts +100 -0
- package/dist/auth/providers/github-copilot.d.ts.map +1 -0
- package/dist/auth/providers/github-copilot.js +302 -0
- package/dist/auth/providers/github-copilot.js.map +1 -0
- package/dist/auth/providers/openai-codex.d.ts +95 -0
- package/dist/auth/providers/openai-codex.d.ts.map +1 -0
- package/dist/auth/providers/openai-codex.js +527 -0
- package/dist/auth/providers/openai-codex.js.map +1 -0
- package/dist/auth/storage.d.ts +91 -0
- package/dist/auth/storage.d.ts.map +1 -0
- package/dist/auth/storage.js +187 -0
- package/dist/auth/storage.js.map +1 -0
- package/dist/auth/types.d.ts +68 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +1 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.d.ts.map +1 -0
- package/dist/clipboard/index.js +192 -0
- package/dist/clipboard/index.js.map +1 -0
- package/dist/constants.d.ts +10 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +23 -0
- package/dist/constants.js.map +1 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.d.ts.map +1 -0
- package/dist/error-classification.js +14 -0
- package/dist/error-classification.js.map +1 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.d.ts.map +1 -0
- package/dist/evals/context-builder.js +120 -0
- package/dist/evals/context-builder.js.map +1 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.d.ts.map +1 -0
- package/dist/evals/index.js +8 -0
- package/dist/evals/index.js.map +1 -0
- package/dist/evals/scorers/classify-command.d.ts +31 -0
- package/dist/evals/scorers/classify-command.d.ts.map +1 -0
- package/dist/evals/scorers/classify-command.js +52 -0
- package/dist/evals/scorers/classify-command.js.map +1 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.d.ts.map +1 -0
- package/dist/evals/scorers/efficiency.js +201 -0
- package/dist/evals/scorers/efficiency.js.map +1 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.d.ts.map +1 -0
- package/dist/evals/scorers/extract-tools.js +56 -0
- package/dist/evals/scorers/extract-tools.js.map +1 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.d.ts.map +1 -0
- package/dist/evals/scorers/index.js +7 -0
- package/dist/evals/scorers/index.js.map +1 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.d.ts.map +1 -0
- package/dist/evals/scorers/outcome.js +238 -0
- package/dist/evals/scorers/outcome.js.map +1 -0
- package/dist/headless/cli.d.ts +42 -0
- package/dist/headless/cli.d.ts.map +1 -0
- package/dist/headless/cli.js +196 -0
- package/dist/headless/cli.js.map +1 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.d.ts.map +1 -0
- package/dist/headless/flags.js +188 -0
- package/dist/headless/flags.js.map +1 -0
- package/dist/headless/format.d.ts +38 -0
- package/dist/headless/format.d.ts.map +1 -0
- package/dist/headless/format.js +85 -0
- package/dist/headless/format.js.map +1 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.d.ts.map +1 -0
- package/dist/headless/index.js +32 -0
- package/dist/headless/index.js.map +1 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.d.ts.map +1 -0
- package/dist/headless/policy.js +38 -0
- package/dist/headless/policy.js.map +1 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.d.ts.map +1 -0
- package/dist/headless/run-mc.js +296 -0
- package/dist/headless/run-mc.js.map +1 -0
- package/dist/headless/types.d.ts +134 -0
- package/dist/headless/types.d.ts.map +1 -0
- package/dist/headless/types.js +9 -0
- package/dist/headless/types.js.map +1 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.d.ts.map +1 -0
- package/dist/hooks/config.js +78 -0
- package/dist/hooks/config.js.map +1 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.d.ts.map +1 -0
- package/dist/hooks/executor.js +125 -0
- package/dist/hooks/executor.js.map +1 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +16 -0
- package/dist/hooks/index.js.map +1 -0
- package/dist/hooks/manager.d.ts +47 -0
- package/dist/hooks/manager.d.ts.map +1 -0
- package/dist/hooks/manager.js +284 -0
- package/dist/hooks/manager.js.map +1 -0
- package/dist/hooks/types.d.ts +152 -0
- package/dist/hooks/types.d.ts.map +1 -0
- package/dist/hooks/types.js +7 -0
- package/dist/hooks/types.js.map +1 -0
- package/dist/index.d.ts +241 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +712 -0
- package/dist/index.js.map +1 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.d.ts.map +1 -0
- package/dist/ipc/ipc-reporter.js +24 -0
- package/dist/ipc/ipc-reporter.js.map +1 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.d.ts.map +1 -0
- package/dist/lsp/client.js +309 -0
- package/dist/lsp/client.js.map +1 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.d.ts.map +1 -0
- package/dist/lsp/index.js +9 -0
- package/dist/lsp/index.js.map +1 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.d.ts.map +1 -0
- package/dist/lsp/language.js +48 -0
- package/dist/lsp/language.js.map +1 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.d.ts.map +1 -0
- package/dist/lsp/manager.js +97 -0
- package/dist/lsp/manager.js.map +1 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.d.ts.map +1 -0
- package/dist/lsp/server.js +128 -0
- package/dist/lsp/server.js.map +1 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.d.ts.map +1 -0
- package/dist/lsp/workspace.js +52 -0
- package/dist/lsp/workspace.js.map +1 -0
- package/dist/mcp/config.d.ts +34 -0
- package/dist/mcp/config.d.ts.map +1 -0
- package/dist/mcp/config.js +205 -0
- package/dist/mcp/config.js.map +1 -0
- package/dist/mcp/index.d.ts +5 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +49 -0
- package/dist/mcp/manager.d.ts.map +1 -0
- package/dist/mcp/manager.js +374 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/types.d.ts +85 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +1 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.d.ts.map +1 -0
- package/dist/onboarding/custom-packs.js +20 -0
- package/dist/onboarding/custom-packs.js.map +1 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.d.ts.map +1 -0
- package/dist/onboarding/custom-providers.js +28 -0
- package/dist/onboarding/custom-providers.js.map +1 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.d.ts.map +1 -0
- package/dist/onboarding/index.js +21 -0
- package/dist/onboarding/index.js.map +1 -0
- package/dist/onboarding/om-settings.d.ts +20 -0
- package/dist/onboarding/om-settings.d.ts.map +1 -0
- package/dist/onboarding/om-settings.js +26 -0
- package/dist/onboarding/om-settings.js.map +1 -0
- package/dist/onboarding/packs.d.ts +48 -0
- package/dist/onboarding/packs.d.ts.map +1 -0
- package/dist/onboarding/packs.js +111 -0
- package/dist/onboarding/packs.js.map +1 -0
- package/dist/onboarding/settings.d.ts +323 -0
- package/dist/onboarding/settings.d.ts.map +1 -0
- package/dist/onboarding/settings.js +594 -0
- package/dist/onboarding/settings.js.map +1 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +119 -0
- package/dist/permissions.js.map +1 -0
- package/dist/plugin.d.ts +81 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +30 -0
- package/dist/plugin.js.map +1 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.d.ts.map +1 -0
- package/dist/plugins/dependencies.js +141 -0
- package/dist/plugins/dependencies.js.map +1 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.d.ts.map +1 -0
- package/dist/plugins/install.js +200 -0
- package/dist/plugins/install.js.map +1 -0
- package/dist/plugins/loader.d.ts +15 -0
- package/dist/plugins/loader.d.ts.map +1 -0
- package/dist/plugins/loader.js +221 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/plugins/manager.d.ts +60 -0
- package/dist/plugins/manager.d.ts.map +1 -0
- package/dist/plugins/manager.js +378 -0
- package/dist/plugins/manager.js.map +1 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.d.ts.map +1 -0
- package/dist/plugins/manifest.js +75 -0
- package/dist/plugins/manifest.js.map +1 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.d.ts.map +1 -0
- package/dist/plugins/package-link.js +77 -0
- package/dist/plugins/package-link.js.map +1 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.d.ts.map +1 -0
- package/dist/plugins/paths.js +26 -0
- package/dist/plugins/paths.js.map +1 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.d.ts.map +1 -0
- package/dist/plugins/registry.js +96 -0
- package/dist/plugins/registry.js.map +1 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.d.ts.map +1 -0
- package/dist/plugins/scaffold.js +152 -0
- package/dist/plugins/scaffold.js.map +1 -0
- package/dist/plugins/types.d.ts +45 -0
- package/dist/plugins/types.d.ts.map +1 -0
- package/dist/plugins/types.js +1 -0
- package/dist/plugins/types.js.map +1 -0
- package/dist/processors/plan-rejection-abort.d.ts +12 -0
- package/dist/processors/plan-rejection-abort.d.ts.map +1 -0
- package/dist/processors/plan-rejection-abort.js +53 -0
- package/dist/processors/plan-rejection-abort.js.map +1 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +40 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock-gateway.js +79 -0
- package/dist/providers/amazon-bedrock-gateway.js.map +1 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock.js +62 -0
- package/dist/providers/amazon-bedrock.js.map +1 -0
- package/dist/providers/claude-max.d.ts +50 -0
- package/dist/providers/claude-max.d.ts.map +1 -0
- package/dist/providers/claude-max.js +151 -0
- package/dist/providers/claude-max.js.map +1 -0
- package/dist/providers/github-copilot.d.ts +58 -0
- package/dist/providers/github-copilot.d.ts.map +1 -0
- package/dist/providers/github-copilot.js +263 -0
- package/dist/providers/github-copilot.js.map +1 -0
- package/dist/providers/openai-codex.d.ts +70 -0
- package/dist/providers/openai-codex.d.ts.map +1 -0
- package/dist/providers/openai-codex.js +291 -0
- package/dist/providers/openai-codex.js.map +1 -0
- package/dist/schema.d.ts +167 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +92 -0
- package/dist/schema.js.map +1 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.d.ts.map +1 -0
- package/dist/theme-palette.js +17 -0
- package/dist/theme-palette.js.map +1 -0
- package/dist/tool-names.d.ts +73 -0
- package/dist/tool-names.d.ts.map +1 -0
- package/dist/tool-names.js +43 -0
- package/dist/tool-names.js.map +1 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +9 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.d.ts.map +1 -0
- package/dist/tools/request-sandbox-access.js +88 -0
- package/dist/tools/request-sandbox-access.js.map +1 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.d.ts.map +1 -0
- package/dist/tools/utils.js +22 -0
- package/dist/tools/utils.js.map +1 -0
- package/dist/tools/web-search.d.ts +35 -0
- package/dist/tools/web-search.d.ts.map +1 -0
- package/dist/tools/web-search.js +65 -0
- package/dist/tools/web-search.js.map +1 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.d.ts.map +1 -0
- package/dist/utils/binaries.js +74 -0
- package/dist/utils/binaries.js.map +1 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.d.ts.map +1 -0
- package/dist/utils/debug-log.js +55 -0
- package/dist/utils/debug-log.js.map +1 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +207 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.d.ts.map +1 -0
- package/dist/utils/gateway-sync.js +49 -0
- package/dist/utils/gateway-sync.js.map +1 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.d.ts.map +1 -0
- package/dist/utils/plan-diff.js +43 -0
- package/dist/utils/plan-diff.js.map +1 -0
- package/dist/utils/plans.d.ts +56 -0
- package/dist/utils/plans.d.ts.map +1 -0
- package/dist/utils/plans.js +99 -0
- package/dist/utils/plans.js.map +1 -0
- package/dist/utils/project.d.ts +161 -0
- package/dist/utils/project.d.ts.map +1 -0
- package/dist/utils/project.js +302 -0
- package/dist/utils/project.js.map +1 -0
- package/dist/utils/signals-pubsub.d.ts +41 -0
- package/dist/utils/signals-pubsub.d.ts.map +1 -0
- package/dist/utils/signals-pubsub.js +104 -0
- package/dist/utils/signals-pubsub.js.map +1 -0
- package/dist/utils/slash-command-loader.d.ts +48 -0
- package/dist/utils/slash-command-loader.d.ts.map +1 -0
- package/dist/utils/slash-command-loader.js +155 -0
- package/dist/utils/slash-command-loader.js.map +1 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.d.ts.map +1 -0
- package/dist/utils/slash-command-processor.js +96 -0
- package/dist/utils/slash-command-processor.js.map +1 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.d.ts.map +1 -0
- package/dist/utils/stdin-pipe.js +72 -0
- package/dist/utils/stdin-pipe.js.map +1 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.d.ts.map +1 -0
- package/dist/utils/storage-factory.js +98 -0
- package/dist/utils/storage-factory.js.map +1 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.d.ts.map +1 -0
- package/dist/utils/thread-lock.js +108 -0
- package/dist/utils/thread-lock.js.map +1 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.d.ts.map +1 -0
- package/dist/utils/token-estimator.js +21 -0
- package/dist/utils/token-estimator.js.map +1 -0
- package/dist/utils/update-check.d.ts +52 -0
- package/dist/utils/update-check.d.ts.map +1 -0
- package/dist/utils/update-check.js +177 -0
- package/dist/utils/update-check.js.map +1 -0
- package/dist/voice/stt-registry.d.ts +64 -0
- package/dist/voice/stt-registry.d.ts.map +1 -0
- package/dist/voice/stt-registry.js +126 -0
- package/dist/voice/stt-registry.js.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import fs, { existsSync } from "node:fs";
|
|
2
|
+
import os from "node:os";
|
|
3
|
+
import path, { dirname, join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from "@mastra/core/workspace";
|
|
6
|
+
import { DEFAULT_CONFIG_DIR } from "../constants.js";
|
|
7
|
+
import { loadSettings } from "../onboarding/settings.js";
|
|
8
|
+
import { getPlansDir } from "../utils/plans.js";
|
|
9
|
+
import { SandboxFilesystem } from "./sandbox-filesystem.js";
|
|
10
|
+
import { reattachProjectSandbox } from "./sandbox-reattach.js";
|
|
11
|
+
import { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from "./tool-availability.js";
|
|
12
|
+
function buildSandboxEnv() {
|
|
13
|
+
return {
|
|
14
|
+
...process.env,
|
|
15
|
+
// Explicit overrides for non-interactive subprocess execution
|
|
16
|
+
FORCE_COLOR: "1",
|
|
17
|
+
CLICOLOR_FORCE: "1",
|
|
18
|
+
TERM: process.env.TERM || "xterm-256color",
|
|
19
|
+
CI: "true",
|
|
20
|
+
NONINTERACTIVE: "1",
|
|
21
|
+
DEBIAN_FRONTEND: "noninteractive"
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
function collectSkillPaths(skillsDirs) {
|
|
25
|
+
const paths = [];
|
|
26
|
+
const seen = /* @__PURE__ */ new Set();
|
|
27
|
+
for (const skillsDir of skillsDirs) {
|
|
28
|
+
const resolved = path.resolve(skillsDir);
|
|
29
|
+
if (!seen.has(resolved)) {
|
|
30
|
+
seen.add(resolved);
|
|
31
|
+
paths.push(skillsDir);
|
|
32
|
+
}
|
|
33
|
+
if (!fs.existsSync(skillsDir)) continue;
|
|
34
|
+
try {
|
|
35
|
+
const entries = fs.readdirSync(skillsDir, { withFileTypes: true });
|
|
36
|
+
for (const entry of entries) {
|
|
37
|
+
if (entry.isSymbolicLink()) {
|
|
38
|
+
const linkPath = path.join(skillsDir, entry.name);
|
|
39
|
+
const realPath = fs.realpathSync(linkPath);
|
|
40
|
+
const stat = fs.statSync(realPath);
|
|
41
|
+
if (stat.isDirectory()) {
|
|
42
|
+
const realParent = path.dirname(realPath);
|
|
43
|
+
if (!seen.has(realParent)) {
|
|
44
|
+
seen.add(realParent);
|
|
45
|
+
paths.push(realParent);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
} catch {
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return paths;
|
|
54
|
+
}
|
|
55
|
+
function buildSkillPaths(projectPath, configDir, homeDir = os.homedir(), pluginSkillPaths = []) {
|
|
56
|
+
const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, "skills");
|
|
57
|
+
const claudeLocalSkillsPath = path.join(projectPath, ".claude", "skills");
|
|
58
|
+
const agentSkillsLocalPath = path.join(projectPath, ".agents", "skills");
|
|
59
|
+
const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, "skills");
|
|
60
|
+
const claudeGlobalSkillsPath = path.join(homeDir, ".claude", "skills");
|
|
61
|
+
const agentSkillsGlobalPath = path.join(homeDir, ".agents", "skills");
|
|
62
|
+
return collectSkillPaths([
|
|
63
|
+
mastraCodeLocalSkillsPath,
|
|
64
|
+
claudeLocalSkillsPath,
|
|
65
|
+
agentSkillsLocalPath,
|
|
66
|
+
mastraCodeGlobalSkillsPath,
|
|
67
|
+
claudeGlobalSkillsPath,
|
|
68
|
+
agentSkillsGlobalPath,
|
|
69
|
+
...pluginSkillPaths
|
|
70
|
+
]);
|
|
71
|
+
}
|
|
72
|
+
const DEFAULT_ALLOWED_PATHS = [os.tmpdir(), "/tmp", getPlansDir()].reduce((acc, p) => {
|
|
73
|
+
const resolved = path.resolve(p);
|
|
74
|
+
if (!acc.includes(resolved)) acc.push(resolved);
|
|
75
|
+
return acc;
|
|
76
|
+
}, []);
|
|
77
|
+
const WORKSPACE_ID_PREFIX = "mastra-code-workspace";
|
|
78
|
+
function detectPackageRunner(projectPath) {
|
|
79
|
+
if (existsSync(join(projectPath, "pnpm-lock.yaml"))) return "pnpm dlx";
|
|
80
|
+
if (existsSync(join(projectPath, "bun.lockb")) || existsSync(join(projectPath, "bun.lock"))) return "bunx";
|
|
81
|
+
if (existsSync(join(projectPath, "yarn.lock"))) return "yarn dlx";
|
|
82
|
+
if (existsSync(join(projectPath, "package-lock.json"))) return "npx --yes";
|
|
83
|
+
return "npx --yes";
|
|
84
|
+
}
|
|
85
|
+
async function getSandboxWorkspace({
|
|
86
|
+
githubProjectId,
|
|
87
|
+
sandboxId,
|
|
88
|
+
workdir,
|
|
89
|
+
worktreePath,
|
|
90
|
+
mastra
|
|
91
|
+
}) {
|
|
92
|
+
const boundWorkdir = worktreePath || workdir;
|
|
93
|
+
const workspaceId = `${WORKSPACE_ID_PREFIX}-gh-${githubProjectId}-${sandboxId}-${boundWorkdir}`;
|
|
94
|
+
try {
|
|
95
|
+
const existing = mastra?.getWorkspaceById(workspaceId);
|
|
96
|
+
if (existing) {
|
|
97
|
+
existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);
|
|
98
|
+
return existing;
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
}
|
|
102
|
+
const sandbox = await reattachProjectSandbox(sandboxId);
|
|
103
|
+
const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });
|
|
104
|
+
return new Workspace({
|
|
105
|
+
id: workspaceId,
|
|
106
|
+
name: "Mastra Code Sandbox Workspace",
|
|
107
|
+
filesystem,
|
|
108
|
+
sandbox,
|
|
109
|
+
tools: MASTRACODE_WORKSPACE_TOOLS
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
async function getDynamicWorkspace({
|
|
113
|
+
requestContext,
|
|
114
|
+
mastra
|
|
115
|
+
}) {
|
|
116
|
+
const ctx = requestContext.get("controller");
|
|
117
|
+
const state = ctx?.getState();
|
|
118
|
+
if (state?.githubProjectId && state.sandboxId && state.sandboxWorkdir) {
|
|
119
|
+
return getSandboxWorkspace({
|
|
120
|
+
githubProjectId: state.githubProjectId,
|
|
121
|
+
sandboxId: state.sandboxId,
|
|
122
|
+
workdir: state.sandboxWorkdir,
|
|
123
|
+
worktreePath: state.worktreePath,
|
|
124
|
+
mastra
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
const rawProjectPath = state?.projectPath;
|
|
128
|
+
if (!rawProjectPath) {
|
|
129
|
+
throw new Error("Project path is required");
|
|
130
|
+
}
|
|
131
|
+
const projectPath = path.resolve(rawProjectPath);
|
|
132
|
+
const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;
|
|
133
|
+
const skillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);
|
|
134
|
+
const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}`;
|
|
135
|
+
const sandboxPaths = state?.sandboxAllowedPaths ?? [];
|
|
136
|
+
const allowedPaths = [...skillPaths, ...DEFAULT_ALLOWED_PATHS, ...sandboxPaths.map((p) => path.resolve(p))];
|
|
137
|
+
const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;
|
|
138
|
+
let existing;
|
|
139
|
+
try {
|
|
140
|
+
existing = mastra?.getWorkspaceById(workspaceId);
|
|
141
|
+
} catch {
|
|
142
|
+
}
|
|
143
|
+
if (existing) {
|
|
144
|
+
existing.filesystem.setAllowedPaths(allowedPaths);
|
|
145
|
+
existing.setToolsConfig(workspaceTools);
|
|
146
|
+
return existing;
|
|
147
|
+
}
|
|
148
|
+
const userLsp = loadSettings().lsp ?? {};
|
|
149
|
+
const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), "..");
|
|
150
|
+
const lspConfig = {
|
|
151
|
+
...userLsp,
|
|
152
|
+
packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath),
|
|
153
|
+
// Detected runner is the fallback — user's packageRunner always wins
|
|
154
|
+
searchPaths: [mcModulePath, ...userLsp.searchPaths ?? []]
|
|
155
|
+
};
|
|
156
|
+
return new Workspace({
|
|
157
|
+
id: workspaceId,
|
|
158
|
+
name: "Mastra Code Workspace",
|
|
159
|
+
filesystem: new LocalFilesystem({
|
|
160
|
+
basePath: projectPath,
|
|
161
|
+
allowedPaths
|
|
162
|
+
}),
|
|
163
|
+
sandbox: new LocalSandbox({
|
|
164
|
+
workingDirectory: projectPath,
|
|
165
|
+
env: buildSandboxEnv()
|
|
166
|
+
}),
|
|
167
|
+
tools: workspaceTools,
|
|
168
|
+
...skillPaths.length > 0 ? { skills: skillPaths } : {},
|
|
169
|
+
lsp: lspConfig
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
async function getGoalJudgeTools({
|
|
173
|
+
requestContext,
|
|
174
|
+
mastra
|
|
175
|
+
}) {
|
|
176
|
+
let workspace;
|
|
177
|
+
try {
|
|
178
|
+
workspace = await getDynamicWorkspace({ requestContext, mastra });
|
|
179
|
+
} catch {
|
|
180
|
+
return void 0;
|
|
181
|
+
}
|
|
182
|
+
const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });
|
|
183
|
+
const readonly = {};
|
|
184
|
+
for (const name of GOAL_JUDGE_READONLY_TOOLS) {
|
|
185
|
+
if (allTools[name]) readonly[name] = allTools[name];
|
|
186
|
+
}
|
|
187
|
+
return Object.keys(readonly).length > 0 ? readonly : void 0;
|
|
188
|
+
}
|
|
189
|
+
export {
|
|
190
|
+
buildSkillPaths,
|
|
191
|
+
getDynamicWorkspace,
|
|
192
|
+
getGoalJudgeTools
|
|
193
|
+
};
|
|
194
|
+
//# sourceMappingURL=workspace.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/agents/workspace.ts"],"sourcesContent":["import fs, { existsSync } from 'node:fs';\nimport os from 'node:os';\nimport path, { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport type { AgentControllerRequestContext } from '@mastra/core/agent-controller';\nimport type { Mastra } from '@mastra/core/mastra';\nimport type { RequestContext } from '@mastra/core/request-context';\nimport { Workspace, LocalFilesystem, LocalSandbox, createWorkspaceTools } from '@mastra/core/workspace';\nimport type { LSPConfig } from '@mastra/core/workspace';\nimport { DEFAULT_CONFIG_DIR } from '../constants.js';\nimport { loadSettings } from '../onboarding/settings.js';\nimport type { MastraCodeState } from '../schema.js';\nimport { getPlansDir } from '../utils/plans.js';\nimport { SandboxFilesystem } from './sandbox-filesystem.js';\nimport { reattachProjectSandbox } from './sandbox-reattach.js';\nimport { GOAL_JUDGE_READONLY_TOOLS, MASTRACODE_WORKSPACE_TOOLS } from './tool-availability.js';\n\n// =============================================================================\n// Sandbox Environment\n// =============================================================================\n\nfunction buildSandboxEnv(): NodeJS.ProcessEnv {\n return {\n ...process.env,\n // Explicit overrides for non-interactive subprocess execution\n FORCE_COLOR: '1',\n CLICOLOR_FORCE: '1',\n TERM: process.env.TERM || 'xterm-256color',\n CI: 'true',\n NONINTERACTIVE: '1',\n DEBIAN_FRONTEND: 'noninteractive',\n };\n}\n\n// =============================================================================\n// Create Workspace with Skills\n// =============================================================================\n\n// We support multiple skill locations for compatibility:\n// 1. Project-local: <configDir>/skills (project-specific mastracode skills)\n// 2. Project-local: .claude/skills (Claude Code compatible skills)\n// 3. Project-local: .agents/skills (Agent Skills spec compatible)\n// 4. Global: ~/<configDir>/skills (user-wide mastracode skills)\n// 5. Global: ~/.claude/skills (user-wide Claude Code skills)\n// 6. Global: ~/.agents/skills (user-wide Agent Skills spec compatible)\n\n// Mastra's LocalSkillSource.readdir uses Node's Dirent.isDirectory() which\n// returns false for symlinks. Tools like `npx skills add` install skills as\n// symlinks, so we need to resolve them. For each symlinked skill directory,\n// we add the real (resolved) parent path as an additional skill scan path.\nfunction collectSkillPaths(skillsDirs: string[]): string[] {\n const paths: string[] = [];\n const seen = new Set<string>();\n\n for (const skillsDir of skillsDirs) {\n const resolved = path.resolve(skillsDir);\n if (!seen.has(resolved)) {\n seen.add(resolved);\n paths.push(skillsDir);\n }\n\n if (!fs.existsSync(skillsDir)) continue;\n\n try {\n const entries = fs.readdirSync(skillsDir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isSymbolicLink()) {\n const linkPath = path.join(skillsDir, entry.name);\n const realPath = fs.realpathSync(linkPath);\n const stat = fs.statSync(realPath);\n if (stat.isDirectory()) {\n const realParent = path.dirname(realPath);\n if (!seen.has(realParent)) {\n seen.add(realParent);\n paths.push(realParent);\n }\n }\n }\n }\n } catch {\n // Ignore errors during symlink resolution\n }\n }\n\n return paths;\n}\n\n// Build skill paths dynamically based on configDir and projectPath\nexport function buildSkillPaths(\n projectPath: string,\n configDir: string,\n homeDir = os.homedir(),\n pluginSkillPaths: string[] = [],\n): string[] {\n const mastraCodeLocalSkillsPath = path.join(projectPath, configDir, 'skills');\n const claudeLocalSkillsPath = path.join(projectPath, '.claude', 'skills');\n const agentSkillsLocalPath = path.join(projectPath, '.agents', 'skills');\n const mastraCodeGlobalSkillsPath = path.join(homeDir, configDir, 'skills');\n const claudeGlobalSkillsPath = path.join(homeDir, '.claude', 'skills');\n const agentSkillsGlobalPath = path.join(homeDir, '.agents', 'skills');\n\n return collectSkillPaths([\n mastraCodeLocalSkillsPath,\n claudeLocalSkillsPath,\n agentSkillsLocalPath,\n mastraCodeGlobalSkillsPath,\n claudeGlobalSkillsPath,\n agentSkillsGlobalPath,\n ...pluginSkillPaths,\n ]);\n}\n\n/**\n * Paths the agent is always allowed to access (in addition to the project root\n * and any per-thread sandboxAllowedPaths). The OS temp directory is included\n * so the agent can use it as a scratchpad without requesting access every time.\n */\nconst DEFAULT_ALLOWED_PATHS: string[] = [os.tmpdir(), '/tmp', getPlansDir()].reduce<string[]>((acc, p) => {\n const resolved = path.resolve(p);\n if (!acc.includes(resolved)) acc.push(resolved);\n return acc;\n}, []);\n\nconst WORKSPACE_ID_PREFIX = 'mastra-code-workspace';\n\n/**\n * Detect the project's package runner from lock files.\n * Used as a fallback packageRunner for LSP when no binary is found locally or on PATH.\n */\nfunction detectPackageRunner(projectPath: string): string | undefined {\n if (existsSync(join(projectPath, 'pnpm-lock.yaml'))) return 'pnpm dlx';\n if (existsSync(join(projectPath, 'bun.lockb')) || existsSync(join(projectPath, 'bun.lock'))) return 'bunx';\n if (existsSync(join(projectPath, 'yarn.lock'))) return 'yarn dlx';\n if (existsSync(join(projectPath, 'package-lock.json'))) return 'npx --yes';\n return 'npx --yes';\n}\n\n/**\n * Build (or reuse) a sandbox-backed Workspace for a GitHub project. The sandbox\n * is reattached by its persisted provider id and a `SandboxFilesystem` is layered\n * over the in-sandbox checkout so file tools and command tools share one VM.\n */\nasync function getSandboxWorkspace({\n githubProjectId,\n sandboxId,\n workdir,\n worktreePath,\n mastra,\n}: {\n githubProjectId: string;\n sandboxId: string;\n workdir: string;\n worktreePath?: string;\n mastra?: Mastra;\n}): Promise<Workspace> {\n // Bind the workspace to the active worktree when one is set, so file tools and\n // command tools operate inside the feature branch's working tree rather than\n // the base checkout. Falls back to the repo root when no worktree is active.\n const boundWorkdir = worktreePath || workdir;\n\n // Include the sandbox id *and* worktree path in the reuse key: a new sandbox\n // (e.g. the previous one expired) or a different worktree must each get a\n // fresh Workspace/ProcessManager instead of reusing one bound to a stale\n // sandbox or the wrong working tree.\n const workspaceId = `${WORKSPACE_ID_PREFIX}-gh-${githubProjectId}-${sandboxId}-${boundWorkdir}`;\n\n // Reuse the existing remote workspace if already registered (preserves the\n // reattached sandbox + ProcessManager state across re-opens).\n try {\n const existing = mastra?.getWorkspaceById(workspaceId) as Workspace | undefined;\n if (existing) {\n existing.setToolsConfig(MASTRACODE_WORKSPACE_TOOLS);\n return existing;\n }\n } catch {\n // Not registered yet.\n }\n\n const sandbox = await reattachProjectSandbox(sandboxId);\n const filesystem = new SandboxFilesystem({ sandbox, workdir: boundWorkdir });\n\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Sandbox Workspace',\n filesystem,\n sandbox: sandbox as unknown as ConstructorParameters<typeof Workspace>[0]['sandbox'],\n tools: MASTRACODE_WORKSPACE_TOOLS,\n });\n}\n\nexport async function getDynamicWorkspace({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}) {\n const ctx = requestContext.get('controller') as AgentControllerRequestContext<MastraCodeState> | undefined;\n const state = ctx?.getState();\n\n // GitHub/cloud-sandbox-backed project: the repo lives inside a remote sandbox,\n // not on the server host. Reattach to the already-provisioned + materialized\n // sandbox (the SPA called `.../ensure` first, persisting sandboxId/workdir on\n // controller state) and build a sandbox-backed Workspace. LSP/host skill paths\n // are skipped for these workspaces (follow-up).\n if (state?.githubProjectId && state.sandboxId && state.sandboxWorkdir) {\n return getSandboxWorkspace({\n githubProjectId: state.githubProjectId,\n sandboxId: state.sandboxId,\n workdir: state.sandboxWorkdir,\n worktreePath: state.worktreePath,\n mastra,\n });\n }\n\n const rawProjectPath = state?.projectPath;\n\n if (!rawProjectPath) {\n throw new Error('Project path is required');\n }\n\n const projectPath = path.resolve(rawProjectPath);\n const configDir = state?.configDir ?? DEFAULT_CONFIG_DIR;\n const skillPaths = buildSkillPaths(projectPath, configDir, state?.homeDir, state?.pluginSkillPaths ?? []);\n const workspaceId = `${WORKSPACE_ID_PREFIX}-${projectPath}`;\n const sandboxPaths = state?.sandboxAllowedPaths ?? [];\n const allowedPaths = [...skillPaths, ...DEFAULT_ALLOWED_PATHS, ...sandboxPaths.map((p: string) => path.resolve(p))];\n\n // All modes share the same workspace tool configuration. Per-mode tool\n // visibility is enforced at LLM-call time via `availableTools` /\n // `activeTools` on the AgentController, not by mutating workspace capabilities.\n const workspaceTools = MASTRACODE_WORKSPACE_TOOLS;\n\n // Reuse existing workspace if already registered (preserves ProcessManager state)\n let existing: Workspace<LocalFilesystem, LocalSandbox> | undefined;\n try {\n existing = mastra?.getWorkspaceById(workspaceId) as Workspace<LocalFilesystem, LocalSandbox>;\n } catch {\n // Not registered yet\n }\n\n if (existing) {\n existing.filesystem.setAllowedPaths(allowedPaths);\n existing.setToolsConfig(workspaceTools);\n return existing;\n }\n\n const userLsp = loadSettings().lsp ?? {};\n const mcModulePath = join(dirname(fileURLToPath(import.meta.url)), '..');\n const lspConfig: LSPConfig = {\n ...userLsp,\n packageRunner: userLsp.packageRunner || detectPackageRunner(projectPath), // Detected runner is the fallback — user's packageRunner always wins\n searchPaths: [mcModulePath, ...(userLsp.searchPaths ?? [])],\n };\n\n // First call for this project — create the workspace\n return new Workspace({\n id: workspaceId,\n name: 'Mastra Code Workspace',\n filesystem: new LocalFilesystem({\n basePath: projectPath,\n allowedPaths,\n }),\n sandbox: new LocalSandbox({\n workingDirectory: projectPath,\n env: buildSandboxEnv(),\n }),\n tools: workspaceTools,\n ...(skillPaths.length > 0 ? { skills: skillPaths } : {}),\n lsp: lspConfig,\n });\n}\n\n/**\n * Resolver for the agent's `goal.tools` config. Builds the request's workspace\n * (same per-request resolution as the agent's own tools) and returns only the\n * read-only verification subset, remapped to mastracode's tool names (`view`,\n * `search_content`, etc.). Returns `undefined` when no workspace can be resolved\n * (e.g. no project path), keeping the default judge text-only rather than\n * throwing inside the goal step.\n */\nexport async function getGoalJudgeTools({\n requestContext,\n mastra,\n}: {\n requestContext: RequestContext;\n mastra?: Mastra;\n}): Promise<ToolsInput | undefined> {\n let workspace: Workspace;\n try {\n workspace = await getDynamicWorkspace({ requestContext, mastra });\n } catch {\n return undefined;\n }\n\n const allTools = await createWorkspaceTools(workspace, { requestContext, workspace });\n const readonly: ToolsInput = {};\n for (const name of GOAL_JUDGE_READONLY_TOOLS) {\n if (allTools[name]) readonly[name] = allTools[name];\n }\n return Object.keys(readonly).length > 0 ? readonly : undefined;\n}\n"],"mappings":"AAAA,OAAO,MAAM,kBAAkB;AAC/B,OAAO,QAAQ;AACf,OAAO,QAAQ,SAAS,YAAY;AACpC,SAAS,qBAAqB;AAK9B,SAAS,WAAW,iBAAiB,cAAc,4BAA4B;AAE/E,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,SAAS,mBAAmB;AAC5B,SAAS,yBAAyB;AAClC,SAAS,8BAA8B;AACvC,SAAS,2BAA2B,kCAAkC;AAMtE,SAAS,kBAAqC;AAC5C,SAAO;AAAA,IACL,GAAG,QAAQ;AAAA;AAAA,IAEX,aAAa;AAAA,IACb,gBAAgB;AAAA,IAChB,MAAM,QAAQ,IAAI,QAAQ;AAAA,IAC1B,IAAI;AAAA,IACJ,gBAAgB;AAAA,IAChB,iBAAiB;AAAA,EACnB;AACF;AAkBA,SAAS,kBAAkB,YAAgC;AACzD,QAAM,QAAkB,CAAC;AACzB,QAAM,OAAO,oBAAI,IAAY;AAE7B,aAAW,aAAa,YAAY;AAClC,UAAM,WAAW,KAAK,QAAQ,SAAS;AACvC,QAAI,CAAC,KAAK,IAAI,QAAQ,GAAG;AACvB,WAA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KAAK,gBAAgB;AAAA,IACvB,CAAC;AAAA,IACD,OAAO;AAAA,IACP,GAAI,WAAW,SAAS,IAAI,EAAE,QAAQ,WAAW,IAAI,CAAC;AAAA,IACtD,KAAK;AAAA,EACP,CAAC;AACH;AAUA,eAAsB,kBAAkB;AAAA,EACtC;AAAA,EACA;AACF,GAGoC;AAClC,MAAI;AACJ,MAAI;AACF,gBAAY,MAAM,oBAAoB,EAAE,gBAAgB,OAAO,CAAC;AAAA,EAClE,QAAQ;AACN,WAAO;AAAA,EACT;AAEA,QAAM,WAAW,MAAM,qBAAqB,WAAW,EAAE,gBAAgB,UAAU,CAAC;AACpF,QAAM,WAAuB,CAAC;AAC9B,aAAW,QAAQ,2BAA2B;AAC5C,QAAI,SAAS,IAAI,EAAG,UAAS,IAAI,IAAI,SAAS,IAAI;AAAA,EACpD;AACA,SAAO,OAAO,KAAK,QAAQ,EAAE,SAAS,IAAI,WAAW;AACvD;","names":[]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare function getMastraAnalyticsDistinctId(configPath?: string): string;
|
|
2
|
+
export type MastraCodeAnalyticsEvent = 'mastracode_session_started' | 'mastracode_prompt_submitted' | 'mastracode_thread_changed' | 'mastracode_model_changed' | 'mastracode_command_used' | 'mastracode_interactive_prompt_shown';
|
|
3
|
+
export interface MastraCodeAnalytics {
|
|
4
|
+
capture(event: MastraCodeAnalyticsEvent, properties?: Record<string, unknown>): void;
|
|
5
|
+
trackCommand(command: string, properties?: Record<string, unknown>): void;
|
|
6
|
+
trackInteractivePrompt(promptType: string, properties?: Record<string, unknown>): void;
|
|
7
|
+
shutdown(): Promise<void>;
|
|
8
|
+
isEnabled(): boolean;
|
|
9
|
+
}
|
|
10
|
+
interface MastraCodeAnalyticsOptions {
|
|
11
|
+
version: string;
|
|
12
|
+
host?: string;
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
}
|
|
15
|
+
export declare function isTelemetryDisabled(env?: NodeJS.ProcessEnv): boolean;
|
|
16
|
+
export declare function createMastraCodeAnalytics(options: MastraCodeAnalyticsOptions): MastraCodeAnalytics;
|
|
17
|
+
export {};
|
|
18
|
+
//# sourceMappingURL=analytics.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../src/analytics.ts"],"names":[],"mappings":"AAsCA,wBAAgB,4BAA4B,CAAC,UAAU,SAAwB,GAAG,MAAM,CAmBvF;AAeD,MAAM,MAAM,wBAAwB,GAChC,4BAA4B,GAC5B,6BAA6B,GAC7B,2BAA2B,GAC3B,0BAA0B,GAC1B,yBAAyB,GACzB,qCAAqC,CAAC;AAE1C,MAAM,WAAW,mBAAmB;IAClC,OAAO,CAAC,KAAK,EAAE,wBAAwB,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACrF,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1E,sBAAsB,CAAC,UAAU,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACvF,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,SAAS,IAAI,OAAO,CAAC;CACtB;AAED,UAAU,0BAA0B;IAClC,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AA8FD,wBAAgB,mBAAmB,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAOjF;AAED,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,0BAA0B,GAAG,mBAAmB,CAOlG"}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { PostHog } from "posthog-node";
|
|
6
|
+
const POSTHOG_API_KEY = "phc_SBLpZVAB6jmHOct9CABq3PF0Yn5FU3G2FgT4xUr2XrT";
|
|
7
|
+
const POSTHOG_HOST = "https://us.posthog.com";
|
|
8
|
+
const MASTRA_SOURCE = "mastracode";
|
|
9
|
+
const TRUTHY_DISABLED_VALUES = /* @__PURE__ */ new Set(["1", "true", "yes", "on"]);
|
|
10
|
+
const ANALYTICS_CONFIG_PATH = path.join(os.homedir(), ".mastracode", "analytics.json");
|
|
11
|
+
function createMastraAnalyticsDistinctId() {
|
|
12
|
+
return `mastra-${randomUUID()}`;
|
|
13
|
+
}
|
|
14
|
+
function isHostnameDerivedDistinctId(distinctId, hostname = os.hostname()) {
|
|
15
|
+
return distinctId === `mastra-${hostname}`;
|
|
16
|
+
}
|
|
17
|
+
function isValidMastraAnalyticsDistinctId(distinctId) {
|
|
18
|
+
return /^mastra-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(distinctId);
|
|
19
|
+
}
|
|
20
|
+
function writeAnalyticsConfig(distinctId, configPath = ANALYTICS_CONFIG_PATH) {
|
|
21
|
+
try {
|
|
22
|
+
mkdirSync(path.dirname(configPath), { recursive: true });
|
|
23
|
+
writeFileSync(configPath, JSON.stringify({ distinctId }));
|
|
24
|
+
} catch {
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function getMastraAnalyticsDistinctId(configPath = ANALYTICS_CONFIG_PATH) {
|
|
28
|
+
try {
|
|
29
|
+
if (existsSync(configPath)) {
|
|
30
|
+
const config = JSON.parse(readFileSync(configPath, "utf-8"));
|
|
31
|
+
if (config.distinctId && isValidMastraAnalyticsDistinctId(config.distinctId) && !isHostnameDerivedDistinctId(config.distinctId)) {
|
|
32
|
+
return config.distinctId;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
} catch {
|
|
36
|
+
}
|
|
37
|
+
const distinctId = createMastraAnalyticsDistinctId();
|
|
38
|
+
writeAnalyticsConfig(distinctId, configPath);
|
|
39
|
+
return distinctId;
|
|
40
|
+
}
|
|
41
|
+
function isAnalyticsDebugEnabled() {
|
|
42
|
+
return TRUTHY_DISABLED_VALUES.has(process.env.MASTRACODE_ANALYTICS_DEBUG?.trim().toLowerCase() ?? "");
|
|
43
|
+
}
|
|
44
|
+
function debugAnalytics(message, properties) {
|
|
45
|
+
if (!isAnalyticsDebugEnabled()) {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const suffix = properties ? ` ${JSON.stringify(properties)}` : "";
|
|
49
|
+
process.stderr.write(`[mastracode analytics] ${message}${suffix}
|
|
50
|
+
`);
|
|
51
|
+
}
|
|
52
|
+
class NoopMastraCodeAnalytics {
|
|
53
|
+
capture(event) {
|
|
54
|
+
debugAnalytics("capture skipped: telemetry disabled", { event });
|
|
55
|
+
}
|
|
56
|
+
trackCommand(command) {
|
|
57
|
+
debugAnalytics("command skipped: telemetry disabled", { command });
|
|
58
|
+
}
|
|
59
|
+
trackInteractivePrompt(promptType) {
|
|
60
|
+
debugAnalytics("interactive prompt skipped: telemetry disabled", { promptType });
|
|
61
|
+
}
|
|
62
|
+
async shutdown() {
|
|
63
|
+
debugAnalytics("shutdown skipped: telemetry disabled");
|
|
64
|
+
}
|
|
65
|
+
isEnabled() {
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
class PostHogMastraCodeAnalytics {
|
|
70
|
+
client;
|
|
71
|
+
distinctId;
|
|
72
|
+
sessionId = randomUUID();
|
|
73
|
+
version;
|
|
74
|
+
constructor({ version, apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST }) {
|
|
75
|
+
this.version = version;
|
|
76
|
+
this.distinctId = getMastraAnalyticsDistinctId();
|
|
77
|
+
this.client = new PostHog(apiKey, {
|
|
78
|
+
host,
|
|
79
|
+
flushAt: 1,
|
|
80
|
+
flushInterval: 0,
|
|
81
|
+
disableGeoip: false
|
|
82
|
+
});
|
|
83
|
+
this.client.register({ mastraSource: MASTRA_SOURCE });
|
|
84
|
+
debugAnalytics("enabled", { host, distinctId: this.distinctId, version });
|
|
85
|
+
}
|
|
86
|
+
capture(event, properties) {
|
|
87
|
+
try {
|
|
88
|
+
const eventProperties = {
|
|
89
|
+
...this.getBaseProperties(),
|
|
90
|
+
...properties
|
|
91
|
+
};
|
|
92
|
+
debugAnalytics("capture", { event, properties: eventProperties });
|
|
93
|
+
this.client.capture({
|
|
94
|
+
distinctId: this.distinctId,
|
|
95
|
+
event,
|
|
96
|
+
properties: eventProperties
|
|
97
|
+
});
|
|
98
|
+
} catch (error) {
|
|
99
|
+
debugAnalytics("capture failed", { event, error: error instanceof Error ? error.message : String(error) });
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
trackCommand(command, properties) {
|
|
103
|
+
this.capture("mastracode_command_used", { command, ...properties });
|
|
104
|
+
}
|
|
105
|
+
trackInteractivePrompt(promptType, properties) {
|
|
106
|
+
this.capture("mastracode_interactive_prompt_shown", { promptType, ...properties });
|
|
107
|
+
}
|
|
108
|
+
async shutdown() {
|
|
109
|
+
try {
|
|
110
|
+
debugAnalytics("shutdown start");
|
|
111
|
+
await this.client.shutdown();
|
|
112
|
+
debugAnalytics("shutdown complete");
|
|
113
|
+
} catch (error) {
|
|
114
|
+
debugAnalytics("shutdown failed", { error: error instanceof Error ? error.message : String(error) });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
isEnabled() {
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
getBaseProperties() {
|
|
121
|
+
return {
|
|
122
|
+
mastraSource: MASTRA_SOURCE,
|
|
123
|
+
sessionId: this.sessionId,
|
|
124
|
+
version: this.version,
|
|
125
|
+
os: process.platform,
|
|
126
|
+
osVersion: os.release(),
|
|
127
|
+
nodeVersion: process.version,
|
|
128
|
+
platform: process.arch,
|
|
129
|
+
machineId: os.hostname()
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function isTelemetryDisabled(env = process.env) {
|
|
134
|
+
const value = env.MASTRA_TELEMETRY_DISABLED;
|
|
135
|
+
if (!value) {
|
|
136
|
+
return false;
|
|
137
|
+
}
|
|
138
|
+
return TRUTHY_DISABLED_VALUES.has(value.trim().toLowerCase());
|
|
139
|
+
}
|
|
140
|
+
function createMastraCodeAnalytics(options) {
|
|
141
|
+
if (isTelemetryDisabled()) {
|
|
142
|
+
debugAnalytics("disabled by MASTRA_TELEMETRY_DISABLED", { value: process.env.MASTRA_TELEMETRY_DISABLED });
|
|
143
|
+
return new NoopMastraCodeAnalytics();
|
|
144
|
+
}
|
|
145
|
+
return new PostHogMastraCodeAnalytics(options);
|
|
146
|
+
}
|
|
147
|
+
export {
|
|
148
|
+
createMastraCodeAnalytics,
|
|
149
|
+
getMastraAnalyticsDistinctId,
|
|
150
|
+
isTelemetryDisabled
|
|
151
|
+
};
|
|
152
|
+
//# sourceMappingURL=analytics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto';\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport { PostHog } from 'posthog-node';\n\nconst POSTHOG_API_KEY = 'phc_SBLpZVAB6jmHOct9CABq3PF0Yn5FU3G2FgT4xUr2XrT';\nconst POSTHOG_HOST = 'https://us.posthog.com';\nconst MASTRA_SOURCE = 'mastracode';\nconst TRUTHY_DISABLED_VALUES = new Set(['1', 'true', 'yes', 'on']);\nconst ANALYTICS_CONFIG_PATH = path.join(os.homedir(), '.mastracode', 'analytics.json');\n\ninterface AnalyticsConfig {\n distinctId?: string;\n}\n\nfunction createMastraAnalyticsDistinctId(): string {\n return `mastra-${randomUUID()}`;\n}\n\nfunction isHostnameDerivedDistinctId(distinctId: string, hostname = os.hostname()): boolean {\n return distinctId === `mastra-${hostname}`;\n}\n\nfunction isValidMastraAnalyticsDistinctId(distinctId: string): boolean {\n return /^mastra-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(distinctId);\n}\n\nfunction writeAnalyticsConfig(distinctId: string, configPath = ANALYTICS_CONFIG_PATH): void {\n try {\n mkdirSync(path.dirname(configPath), { recursive: true });\n writeFileSync(configPath, JSON.stringify({ distinctId }));\n } catch {\n // swallow analytics persistence errors\n }\n}\n\nexport function getMastraAnalyticsDistinctId(configPath = ANALYTICS_CONFIG_PATH): string {\n try {\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, 'utf-8')) as AnalyticsConfig;\n if (\n config.distinctId &&\n isValidMastraAnalyticsDistinctId(config.distinctId) &&\n !isHostnameDerivedDistinctId(config.distinctId)\n ) {\n return config.distinctId;\n }\n }\n } catch {\n // regenerate below\n }\n\n const distinctId = createMastraAnalyticsDistinctId();\n writeAnalyticsConfig(distinctId, configPath);\n return distinctId;\n}\n\nfunction isAnalyticsDebugEnabled(): boolean {\n return TRUTHY_DISABLED_VALUES.has(process.env.MASTRACODE_ANALYTICS_DEBUG?.trim().toLowerCase() ?? '');\n}\n\nfunction debugAnalytics(message: string, properties?: Record<string, unknown>): void {\n if (!isAnalyticsDebugEnabled()) {\n return;\n }\n\n const suffix = properties ? ` ${JSON.stringify(properties)}` : '';\n process.stderr.write(`[mastracode analytics] ${message}${suffix}\\n`);\n}\n\nexport type MastraCodeAnalyticsEvent =\n | 'mastracode_session_started'\n | 'mastracode_prompt_submitted'\n | 'mastracode_thread_changed'\n | 'mastracode_model_changed'\n | 'mastracode_command_used'\n | 'mastracode_interactive_prompt_shown';\n\nexport interface MastraCodeAnalytics {\n capture(event: MastraCodeAnalyticsEvent, properties?: Record<string, unknown>): void;\n trackCommand(command: string, properties?: Record<string, unknown>): void;\n trackInteractivePrompt(promptType: string, properties?: Record<string, unknown>): void;\n shutdown(): Promise<void>;\n isEnabled(): boolean;\n}\n\ninterface MastraCodeAnalyticsOptions {\n version: string;\n host?: string;\n apiKey?: string;\n}\n\nclass NoopMastraCodeAnalytics implements MastraCodeAnalytics {\n capture(event: MastraCodeAnalyticsEvent): void {\n debugAnalytics('capture skipped: telemetry disabled', { event });\n }\n trackCommand(command: string): void {\n debugAnalytics('command skipped: telemetry disabled', { command });\n }\n trackInteractivePrompt(promptType: string): void {\n debugAnalytics('interactive prompt skipped: telemetry disabled', { promptType });\n }\n async shutdown(): Promise<void> {\n debugAnalytics('shutdown skipped: telemetry disabled');\n }\n isEnabled(): boolean {\n return false;\n }\n}\n\nclass PostHogMastraCodeAnalytics implements MastraCodeAnalytics {\n private readonly client: PostHog;\n private readonly distinctId: string;\n private readonly sessionId = randomUUID();\n private readonly version: string;\n\n constructor({ version, apiKey = POSTHOG_API_KEY, host = POSTHOG_HOST }: MastraCodeAnalyticsOptions) {\n this.version = version;\n this.distinctId = getMastraAnalyticsDistinctId();\n this.client = new PostHog(apiKey, {\n host,\n flushAt: 1,\n flushInterval: 0,\n disableGeoip: false,\n });\n this.client.register({ mastraSource: MASTRA_SOURCE });\n debugAnalytics('enabled', { host, distinctId: this.distinctId, version });\n }\n\n capture(event: MastraCodeAnalyticsEvent, properties?: Record<string, unknown>): void {\n try {\n const eventProperties = {\n ...this.getBaseProperties(),\n ...properties,\n };\n debugAnalytics('capture', { event, properties: eventProperties });\n this.client.capture({\n distinctId: this.distinctId,\n event,\n properties: eventProperties,\n });\n } catch (error) {\n debugAnalytics('capture failed', { event, error: error instanceof Error ? error.message : String(error) });\n // swallow analytics errors\n }\n }\n\n trackCommand(command: string, properties?: Record<string, unknown>): void {\n this.capture('mastracode_command_used', { command, ...properties });\n }\n\n trackInteractivePrompt(promptType: string, properties?: Record<string, unknown>): void {\n this.capture('mastracode_interactive_prompt_shown', { promptType, ...properties });\n }\n\n async shutdown(): Promise<void> {\n try {\n debugAnalytics('shutdown start');\n await this.client.shutdown();\n debugAnalytics('shutdown complete');\n } catch (error) {\n debugAnalytics('shutdown failed', { error: error instanceof Error ? error.message : String(error) });\n // swallow analytics errors\n }\n }\n\n isEnabled(): boolean {\n return true;\n }\n\n private getBaseProperties(): Record<string, unknown> {\n return {\n mastraSource: MASTRA_SOURCE,\n sessionId: this.sessionId,\n version: this.version,\n os: process.platform,\n osVersion: os.release(),\n nodeVersion: process.version,\n platform: process.arch,\n machineId: os.hostname(),\n };\n }\n}\n\nexport function isTelemetryDisabled(env: NodeJS.ProcessEnv = process.env): boolean {\n const value = env.MASTRA_TELEMETRY_DISABLED;\n if (!value) {\n return false;\n }\n\n return TRUTHY_DISABLED_VALUES.has(value.trim().toLowerCase());\n}\n\nexport function createMastraCodeAnalytics(options: MastraCodeAnalyticsOptions): MastraCodeAnalytics {\n if (isTelemetryDisabled()) {\n debugAnalytics('disabled by MASTRA_TELEMETRY_DISABLED', { value: process.env.MASTRA_TELEMETRY_DISABLED });\n return new NoopMastraCodeAnalytics();\n }\n\n return new PostHogMastraCodeAnalytics(options);\n}\n"],"mappings":"AAAA,SAAS,kBAAkB;AAC3B,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,OAAO,QAAQ;AACf,OAAO,UAAU;AAEjB,SAAS,eAAe;AAExB,MAAM,kBAAkB;AACxB,MAAM,eAAe;AACrB,MAAM,gBAAgB;AACtB,MAAM,yBAAyB,oBAAI,IAAI,CAAC,KAAK,QAAQ,OAAO,IAAI,CAAC;AACjE,MAAM,wBAAwB,KAAK,KAAK,GAAG,QAAQ,GAAG,eAAe,gBAAgB;AAMrF,SAAS,kCAA0C;AACjD,SAAO,UAAU,WAAW,CAAC;AAC/B;AAEA,SAAS,4BAA4B,YAAoB,WAAW,GAAG,SAAS,GAAY;AAC1F,SAAO,eAAe,UAAU,QAAQ;AAC1C;AAEA,SAAS,iCAAiC,YAA6B;AACrE,SAAO,yEAAyE,KAA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EAAE,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;AAAA,IAErG;AAAA,EACF;AAAA,EAEA,YAAqB;AACnB,WAAO;AAAA,EACT;AAAA,EAEQ,oBAA6C;AACnD,WAAO;AAAA,MACL,cAAc;AAAA,MACd,WAAW,KAAK;AAAA,MAChB,SAAS,KAAK;AAAA,MACd,IAAI,QAAQ;AAAA,MACZ,WAAW,GAAG,QAAQ;AAAA,MACtB,aAAa,QAAQ;AAAA,MACrB,UAAU,QAAQ;AAAA,MAClB,WAAW,GAAG,SAAS;AAAA,IACzB;AAAA,EACF;AACF;AAEO,SAAS,oBAAoB,MAAyB,QAAQ,KAAc;AACjF,QAAM,QAAQ,IAAI;AAClB,MAAI,CAAC,OAAO;AACV,WAAO;AAAA,EACT;AAEA,SAAO,uBAAuB,IAAI,MAAM,KAAK,EAAE,YAAY,CAAC;AAC9D;AAEO,SAAS,0BAA0B,SAA0D;AAClG,MAAI,oBAAoB,GAAG;AACzB,mBAAe,yCAAyC,EAAE,OAAO,QAAQ,IAAI,0BAA0B,CAAC;AACxG,WAAO,IAAI,wBAAwB;AAAA,EACrC;AAEA,SAAO,IAAI,2BAA2B,OAAO;AAC/C;","names":[]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth credential management for AI providers.
|
|
3
|
+
*/
|
|
4
|
+
export * from './types.js';
|
|
5
|
+
export * from './storage.js';
|
|
6
|
+
export { anthropicOAuthProvider } from './providers/anthropic.js';
|
|
7
|
+
export { githubCopilotOAuthProvider } from './providers/github-copilot.js';
|
|
8
|
+
export { openaiCodexOAuthProvider } from './providers/openai-codex.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC;AAC7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,+BAA+B,CAAC;AAC3E,OAAO,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export * from "./types.js";
|
|
2
|
+
export * from "./storage.js";
|
|
3
|
+
import { anthropicOAuthProvider } from "./providers/anthropic.js";
|
|
4
|
+
import { githubCopilotOAuthProvider } from "./providers/github-copilot.js";
|
|
5
|
+
import { openaiCodexOAuthProvider } from "./providers/openai-codex.js";
|
|
6
|
+
export {
|
|
7
|
+
anthropicOAuthProvider,
|
|
8
|
+
githubCopilotOAuthProvider,
|
|
9
|
+
openaiCodexOAuthProvider
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/index.ts"],"sourcesContent":["/**\n * OAuth credential management for AI providers.\n */\n\nexport * from './types.js';\nexport * from './storage.js';\nexport { anthropicOAuthProvider } from './providers/anthropic.js';\nexport { githubCopilotOAuthProvider } from './providers/github-copilot.js';\nexport { openaiCodexOAuthProvider } from './providers/openai-codex.js';\n"],"mappings":"AAIA,cAAc;AACd,cAAc;AACd,SAAS,8BAA8B;AACvC,SAAS,kCAAkC;AAC3C,SAAS,gCAAgC;","names":[]}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PKCE utilities using Web Crypto API.
|
|
3
|
+
* Works in both Node.js 20+ and browsers.
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Generate PKCE code verifier and challenge.
|
|
7
|
+
* Uses Web Crypto API for cross-platform compatibility.
|
|
8
|
+
*/
|
|
9
|
+
export declare function generatePKCE(): Promise<{
|
|
10
|
+
verifier: string;
|
|
11
|
+
challenge: string;
|
|
12
|
+
}>;
|
|
13
|
+
//# sourceMappingURL=pkce.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pkce.d.ts","sourceRoot":"","sources":["../../src/auth/pkce.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH;;;GAGG;AACH,wBAAsB,YAAY,IAAI,OAAO,CAAC;IAC5C,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC,CAaD"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
function base64urlEncode(bytes) {
|
|
2
|
+
let binary = "";
|
|
3
|
+
for (const byte of bytes) {
|
|
4
|
+
binary += String.fromCharCode(byte);
|
|
5
|
+
}
|
|
6
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
|
|
7
|
+
}
|
|
8
|
+
async function generatePKCE() {
|
|
9
|
+
const verifierBytes = new Uint8Array(32);
|
|
10
|
+
crypto.getRandomValues(verifierBytes);
|
|
11
|
+
const verifier = base64urlEncode(verifierBytes);
|
|
12
|
+
const encoder = new TextEncoder();
|
|
13
|
+
const data = encoder.encode(verifier);
|
|
14
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
|
|
15
|
+
const challenge = base64urlEncode(new Uint8Array(hashBuffer));
|
|
16
|
+
return { verifier, challenge };
|
|
17
|
+
}
|
|
18
|
+
export {
|
|
19
|
+
generatePKCE
|
|
20
|
+
};
|
|
21
|
+
//# sourceMappingURL=pkce.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/auth/pkce.ts"],"sourcesContent":["/**\n * PKCE utilities using Web Crypto API.\n * Works in both Node.js 20+ and browsers.\n */\n\n/**\n * Encode bytes as base64url string.\n */\nfunction base64urlEncode(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=/g, '');\n}\n\n/**\n * Generate PKCE code verifier and challenge.\n * Uses Web Crypto API for cross-platform compatibility.\n */\nexport async function generatePKCE(): Promise<{\n verifier: string;\n challenge: string;\n}> {\n // Generate random verifier\n const verifierBytes = new Uint8Array(32);\n crypto.getRandomValues(verifierBytes);\n const verifier = base64urlEncode(verifierBytes);\n\n // Compute SHA-256 challenge\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const hashBuffer = await crypto.subtle.digest('SHA-256', data);\n const challenge = base64urlEncode(new Uint8Array(hashBuffer));\n\n return { verifier, challenge };\n}\n"],"mappings":"AAQA,SAAS,gBAAgB,OAA2B;AAClD,MAAI,SAAS;AACb,aAAW,QAAQ,OAAO;AACxB,cAAU,OAAO,aAAa,IAAI;AAAA,EACpC;AACA,SAAO,KAAK,MAAM,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,OAAO,GAAG,EAAE,QAAQ,MAAM,EAAE;AAC9E;AAMA,eAAsB,eAGnB;AAED,QAAM,gBAAgB,IAAI,WAAW,EAAE;AACvC,SAAO,gBAAgB,aAAa;AACpC,QAAM,WAAW,gBAAgB,aAAa;AAG9C,QAAM,UAAU,IAAI,YAAY;AAChC,QAAM,OAAO,QAAQ,OAAO,QAAQ;AACpC,QAAM,aAAa,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI;AAC7D,QAAM,YAAY,gBAAgB,IAAI,WAAW,UAAU,CAAC;AAE5D,SAAO,EAAE,UAAU,UAAU;AAC/B;","names":[]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic OAuth flow (Claude Pro/Max)
|
|
3
|
+
*
|
|
4
|
+
* Inspired by pi-mono's OAuth implementation:
|
|
5
|
+
* https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/anthropic.ts
|
|
6
|
+
*/
|
|
7
|
+
import type { OAuthCredentials, OAuthProviderInterface } from '../types.js';
|
|
8
|
+
/**
|
|
9
|
+
* Login with Anthropic OAuth (device code flow)
|
|
10
|
+
*/
|
|
11
|
+
export declare function loginAnthropic(onAuthUrl: (url: string) => void, onPromptCode: () => Promise<string>): Promise<OAuthCredentials>;
|
|
12
|
+
/**
|
|
13
|
+
* Refresh Anthropic OAuth token
|
|
14
|
+
*/
|
|
15
|
+
export declare function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredentials>;
|
|
16
|
+
export declare const anthropicOAuthProvider: OAuthProviderInterface;
|
|
17
|
+
//# sourceMappingURL=anthropic.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"anthropic.d.ts","sourceRoot":"","sources":["../../../src/auth/providers/anthropic.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAuB,sBAAsB,EAAE,MAAM,aAAa,CAAC;AASjG;;GAEG;AACH,wBAAsB,cAAc,CAClC,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,EAChC,YAAY,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,GAClC,OAAO,CAAC,gBAAgB,CAAC,CA6D3B;AAED;;GAEG;AACH,wBAAsB,qBAAqB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA2B3F;AAED,eAAO,MAAM,sBAAsB,EAAE,sBAkBpC,CAAC"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { generatePKCE } from "../pkce.js";
|
|
2
|
+
const decode = (s) => atob(s);
|
|
3
|
+
const CLIENT_ID = decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
|
|
4
|
+
const AUTHORIZE_URL = "https://claude.ai/oauth/authorize";
|
|
5
|
+
const TOKEN_URL = "https://console.anthropic.com/v1/oauth/token";
|
|
6
|
+
const REDIRECT_URI = "https://console.anthropic.com/oauth/code/callback";
|
|
7
|
+
const SCOPES = "org:create_api_key user:profile user:inference";
|
|
8
|
+
async function loginAnthropic(onAuthUrl, onPromptCode) {
|
|
9
|
+
const { verifier, challenge } = await generatePKCE();
|
|
10
|
+
const authParams = new URLSearchParams({
|
|
11
|
+
code: "true",
|
|
12
|
+
client_id: CLIENT_ID,
|
|
13
|
+
response_type: "code",
|
|
14
|
+
redirect_uri: REDIRECT_URI,
|
|
15
|
+
scope: SCOPES,
|
|
16
|
+
code_challenge: challenge,
|
|
17
|
+
code_challenge_method: "S256",
|
|
18
|
+
state: verifier
|
|
19
|
+
});
|
|
20
|
+
const authUrl = `${AUTHORIZE_URL}?${authParams.toString()}`;
|
|
21
|
+
onAuthUrl(authUrl);
|
|
22
|
+
const authCode = await onPromptCode();
|
|
23
|
+
const splits = authCode.split("#");
|
|
24
|
+
const code = splits[0];
|
|
25
|
+
const state = splits[1];
|
|
26
|
+
const tokenResponse = await fetch(TOKEN_URL, {
|
|
27
|
+
method: "POST",
|
|
28
|
+
headers: {
|
|
29
|
+
"Content-Type": "application/json"
|
|
30
|
+
},
|
|
31
|
+
body: JSON.stringify({
|
|
32
|
+
grant_type: "authorization_code",
|
|
33
|
+
client_id: CLIENT_ID,
|
|
34
|
+
code,
|
|
35
|
+
state,
|
|
36
|
+
redirect_uri: REDIRECT_URI,
|
|
37
|
+
code_verifier: verifier
|
|
38
|
+
})
|
|
39
|
+
});
|
|
40
|
+
if (!tokenResponse.ok) {
|
|
41
|
+
const error = await tokenResponse.text();
|
|
42
|
+
throw new Error(`Token exchange failed: ${error}`);
|
|
43
|
+
}
|
|
44
|
+
const tokenData = await tokenResponse.json();
|
|
45
|
+
const expiresAt = Date.now() + tokenData.expires_in * 1e3 - 5 * 60 * 1e3;
|
|
46
|
+
return {
|
|
47
|
+
refresh: tokenData.refresh_token,
|
|
48
|
+
access: tokenData.access_token,
|
|
49
|
+
expires: expiresAt
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
async function refreshAnthropicToken(refreshToken) {
|
|
53
|
+
const response = await fetch(TOKEN_URL, {
|
|
54
|
+
method: "POST",
|
|
55
|
+
headers: { "Content-Type": "application/json" },
|
|
56
|
+
body: JSON.stringify({
|
|
57
|
+
grant_type: "refresh_token",
|
|
58
|
+
client_id: CLIENT_ID,
|
|
59
|
+
refresh_token: refreshToken
|
|
60
|
+
})
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
const error = await response.text();
|
|
64
|
+
throw new Error(`Anthropic token refresh failed: ${error}`);
|
|
65
|
+
}
|
|
66
|
+
const data = await response.json();
|
|
67
|
+
return {
|
|
68
|
+
refresh: data.refresh_token,
|
|
69
|
+
access: data.access_token,
|
|
70
|
+
expires: Date.now() + data.expires_in * 1e3 - 5 * 60 * 1e3
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const anthropicOAuthProvider = {
|
|
74
|
+
id: "anthropic",
|
|
75
|
+
name: "Anthropic (Claude Pro/Max)",
|
|
76
|
+
async login(callbacks) {
|
|
77
|
+
return loginAnthropic(
|
|
78
|
+
(url) => callbacks.onAuth({ url }),
|
|
79
|
+
() => callbacks.onPrompt({ message: "Paste the authorization code:" })
|
|
80
|
+
);
|
|
81
|
+
},
|
|
82
|
+
async refreshToken(credentials) {
|
|
83
|
+
return refreshAnthropicToken(credentials.refresh);
|
|
84
|
+
},
|
|
85
|
+
getApiKey(credentials) {
|
|
86
|
+
return credentials.access;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
export {
|
|
90
|
+
anthropicOAuthProvider,
|
|
91
|
+
loginAnthropic,
|
|
92
|
+
refreshAnthropicToken
|
|
93
|
+
};
|
|
94
|
+
//# sourceMappingURL=anthropic.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/auth/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic OAuth flow (Claude Pro/Max)\n *\n * Inspired by pi-mono's OAuth implementation:\n * https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/anthropic.ts\n */\n\nimport { generatePKCE } from '../pkce.js';\nimport type { OAuthCredentials, OAuthLoginCallbacks, OAuthProviderInterface } from '../types.js';\n\nconst decode = (s: string) => atob(s);\nconst CLIENT_ID = decode('OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl');\nconst AUTHORIZE_URL = 'https://claude.ai/oauth/authorize';\nconst TOKEN_URL = 'https://console.anthropic.com/v1/oauth/token';\nconst REDIRECT_URI = 'https://console.anthropic.com/oauth/code/callback';\nconst SCOPES = 'org:create_api_key user:profile user:inference';\n\n/**\n * Login with Anthropic OAuth (device code flow)\n */\nexport async function loginAnthropic(\n onAuthUrl: (url: string) => void,\n onPromptCode: () => Promise<string>,\n): Promise<OAuthCredentials> {\n const { verifier, challenge } = await generatePKCE();\n\n // Build authorization URL\n const authParams = new URLSearchParams({\n code: 'true',\n client_id: CLIENT_ID,\n response_type: 'code',\n redirect_uri: REDIRECT_URI,\n scope: SCOPES,\n code_challenge: challenge,\n code_challenge_method: 'S256',\n state: verifier,\n });\n\n const authUrl = `${AUTHORIZE_URL}?${authParams.toString()}`;\n\n // Notify caller with URL to open\n onAuthUrl(authUrl);\n\n // Wait for user to paste authorization code (format: code#state)\n const authCode = await onPromptCode();\n const splits = authCode.split('#');\n const code = splits[0];\n const state = splits[1];\n\n // Exchange code for tokens\n const tokenResponse = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n grant_type: 'authorization_code',\n client_id: CLIENT_ID,\n code: code,\n state: state,\n redirect_uri: REDIRECT_URI,\n code_verifier: verifier,\n }),\n });\n\n if (!tokenResponse.ok) {\n const error = await tokenResponse.text();\n throw new Error(`Token exchange failed: ${error}`);\n }\n\n const tokenData = (await tokenResponse.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n // Calculate expiry time (current time + expires_in seconds - 5 min buffer)\n const expiresAt = Date.now() + tokenData.expires_in * 1000 - 5 * 60 * 1000;\n\n return {\n refresh: tokenData.refresh_token,\n access: tokenData.access_token,\n expires: expiresAt,\n };\n}\n\n/**\n * Refresh Anthropic OAuth token\n */\nexport async function refreshAnthropicToken(refreshToken: string): Promise<OAuthCredentials> {\n const response = await fetch(TOKEN_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n grant_type: 'refresh_token',\n client_id: CLIENT_ID,\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic token refresh failed: ${error}`);\n }\n\n const data = (await response.json()) as {\n access_token: string;\n refresh_token: string;\n expires_in: number;\n };\n\n return {\n refresh: data.refresh_token,\n access: data.access_token,\n expires: Date.now() + data.expires_in * 1000 - 5 * 60 * 1000,\n };\n}\n\nexport const anthropicOAuthProvider: OAuthProviderInterface = {\n id: 'anthropic',\n name: 'Anthropic (Claude Pro/Max)',\n\n async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {\n return loginAnthropic(\n url => callbacks.onAuth({ url }),\n () => callbacks.onPrompt({ message: 'Paste the authorization code:' }),\n );\n },\n\n async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {\n return refreshAnthropicToken(credentials.refresh);\n },\n\n getApiKey(credentials: OAuthCredentials): string {\n return credentials.access;\n },\n};\n"],"mappings":"AAOA,SAAS,oBAAoB;AAG7B,MAAM,SAAS,CAAC,MAAc,KAAK,CAAC;AACpC,MAAM,YAAY,OAAO,kDAAkD;AAC3E,MAAM,gBAAgB;AACtB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,SAAS;AAKf,eAAsB,eACpB,WACA,cAC2B;AAC3B,QAAM,EAAE,UAAU,UAAU,IAAI,MAAM,aAAa;AAGnD,QAAM,aAAa,IAAI,gBAAgB;AAAA,IACrC,MAAM;AAAA,IACN,WAAW;AAAA,IACX,eAAe;AAAA,IACf,cAAc;AAAA,IACd,OAAO;AAAA,IACP,gBAAgB;AAAA,IAChB,uBAAuB;AAAA,IACvB,OAAO;AAAA,EACT,CAAC;AAED,QAAM,U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