@mastra/code-sdk 0.0.0-agent-tags-alpha-20261125185303
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/LICENSE.md +32 -0
- package/README.md +284 -0
- package/dist/acp/agent.d.ts +48 -0
- package/dist/acp/agent.js +414 -0
- package/dist/acp/errors.d.ts +3 -0
- package/dist/acp/errors.js +11 -0
- package/dist/acp/event-mapper.d.ts +28 -0
- package/dist/acp/event-mapper.js +274 -0
- package/dist/acp/index.d.ts +9 -0
- package/dist/acp/index.js +21 -0
- package/dist/acp/runtime.d.ts +5 -0
- package/dist/acp/runtime.js +91 -0
- package/dist/acp/server.d.ts +4 -0
- package/dist/acp/server.js +35 -0
- package/dist/acp/skills.d.ts +6 -0
- package/dist/acp/skills.js +30 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.js +1 -0
- package/dist/agent-connections/messaging-processor.d.ts +17 -0
- package/dist/agent-connections/messaging-processor.js +131 -0
- package/dist/agent-connections/ownership.d.ts +24 -0
- package/dist/agent-connections/ownership.js +96 -0
- package/dist/agent-connections/registry.d.ts +20 -0
- package/dist/agent-connections/registry.js +167 -0
- package/dist/agent-connections/session-advertisement.d.ts +27 -0
- package/dist/agent-connections/session-advertisement.js +86 -0
- package/dist/agent-connections/signal-provider.d.ts +141 -0
- package/dist/agent-connections/signal-provider.js +35 -0
- package/dist/agent-connections/state-processor.d.ts +23 -0
- package/dist/agent-connections/state-processor.js +270 -0
- package/dist/agent-connections/thread-state.d.ts +41 -0
- package/dist/agent-connections/thread-state.js +157 -0
- package/dist/agent-connections/tools.d.ts +133 -0
- package/dist/agent-connections/tools.js +616 -0
- package/dist/agent-connections/types.d.ts +99 -0
- package/dist/agent-connections/types.js +4 -0
- package/dist/agent-connections/untrusted-text.d.ts +5 -0
- package/dist/agent-connections/untrusted-text.js +19 -0
- package/dist/agents/background-completion-events.d.ts +16 -0
- package/dist/agents/background-completion-events.js +16 -0
- package/dist/agents/background-completion.d.ts +22 -0
- package/dist/agents/background-completion.js +73 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.js +115 -0
- package/dist/agents/credential-resolver.d.ts +74 -0
- package/dist/agents/credential-resolver.js +142 -0
- package/dist/agents/custom-provider-source.d.ts +35 -0
- package/dist/agents/custom-provider-source.js +22 -0
- package/dist/agents/fastembed-subprocess.d.ts +52 -0
- package/dist/agents/fastembed-subprocess.js +282 -0
- package/dist/agents/instructions.d.ts +42 -0
- package/dist/agents/instructions.js +69 -0
- package/dist/agents/mastracode-gateway.d.ts +85 -0
- package/dist/agents/mastracode-gateway.js +500 -0
- package/dist/agents/memory.d.ts +36 -0
- package/dist/agents/memory.js +248 -0
- package/dist/agents/model.d.ts +158 -0
- package/dist/agents/model.js +382 -0
- package/dist/agents/modes/build.d.ts +12 -0
- package/dist/agents/modes/build.js +33 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.js +25 -0
- package/dist/agents/modes/plan.d.ts +8 -0
- package/dist/agents/modes/plan.js +43 -0
- package/dist/agents/prompts/agent-instructions.d.ts +122 -0
- package/dist/agents/prompts/agent-instructions.js +617 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.js +73 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.js +23 -0
- package/dist/agents/prompts/index.d.ts +61 -0
- package/dist/agents/prompts/index.js +141 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.js +20 -0
- package/dist/agents/prompts/plan.d.ts +11 -0
- package/dist/agents/prompts/plan.js +132 -0
- package/dist/agents/prompts/tool-guidance.d.ts +18 -0
- package/dist/agents/prompts/tool-guidance.js +158 -0
- package/dist/agents/sandbox-filesystem.d.ts +232 -0
- package/dist/agents/sandbox-filesystem.js +851 -0
- package/dist/agents/subagents/execute.d.ts +3 -0
- package/dist/agents/subagents/execute.js +24 -0
- package/dist/agents/subagents/explore.d.ts +3 -0
- package/dist/agents/subagents/explore.js +15 -0
- package/dist/agents/subagents/index.d.ts +6 -0
- package/dist/agents/subagents/index.js +15 -0
- package/dist/agents/subagents/plan.d.ts +3 -0
- package/dist/agents/subagents/plan.js +15 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.js +104 -0
- package/dist/agents/tool-availability.d.ts +17 -0
- package/dist/agents/tool-availability.js +134 -0
- package/dist/agents/tools.d.ts +37 -0
- package/dist/agents/tools.js +154 -0
- package/dist/agents/workflow-builder-agent.d.ts +2 -0
- package/dist/agents/workflow-builder-agent.js +79 -0
- package/dist/agents/workspace.d.ts +35 -0
- package/dist/agents/workspace.js +207 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.js +159 -0
- package/dist/auth/account-rotation-processor.d.ts +210 -0
- package/dist/auth/account-rotation-processor.js +662 -0
- package/dist/auth/account-routing-context.d.ts +17 -0
- package/dist/auth/account-routing-context.js +38 -0
- package/dist/auth/authorization-input.d.ts +16 -0
- package/dist/auth/authorization-input.js +39 -0
- package/dist/auth/device-code.d.ts +93 -0
- package/dist/auth/device-code.js +126 -0
- package/dist/auth/index.d.ts +13 -0
- package/dist/auth/index.js +9 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.js +29 -0
- package/dist/auth/provider-auth-error.d.ts +24 -0
- package/dist/auth/provider-auth-error.js +44 -0
- package/dist/auth/providers/anthropic.d.ts +40 -0
- package/dist/auth/providers/anthropic.js +117 -0
- package/dist/auth/providers/github-copilot.d.ts +154 -0
- package/dist/auth/providers/github-copilot.js +359 -0
- package/dist/auth/providers/kimi-coding.d.ts +38 -0
- package/dist/auth/providers/kimi-coding.js +225 -0
- package/dist/auth/providers/openai-codex.d.ts +141 -0
- package/dist/auth/providers/openai-codex.js +531 -0
- package/dist/auth/providers/xai.d.ts +64 -0
- package/dist/auth/providers/xai.js +223 -0
- package/dist/auth/storage.d.ts +222 -0
- package/dist/auth/storage.js +805 -0
- package/dist/auth/types.d.ts +164 -0
- package/dist/auth/types.js +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.js +224 -0
- package/dist/constants.d.ts +29 -0
- package/dist/constants.js +34 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.js +19 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.js +156 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.js +5 -0
- package/dist/evals/scorers/classify-command.d.ts +30 -0
- package/dist/evals/scorers/classify-command.js +61 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.js +256 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.js +57 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.js +3 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.js +360 -0
- package/dist/experimental-agent.d.ts +19 -0
- package/dist/experimental-agent.js +45 -0
- package/dist/factory/client.d.ts +44 -0
- package/dist/factory/client.js +110 -0
- package/dist/factory/remote-controller.d.ts +34 -0
- package/dist/factory/remote-controller.js +40 -0
- package/dist/factory/remote-session.d.ts +210 -0
- package/dist/factory/remote-session.js +415 -0
- package/dist/goal-manager.d.ts +114 -0
- package/dist/goal-manager.js +351 -0
- package/dist/goal-signal.d.ts +14 -0
- package/dist/goal-signal.js +14 -0
- package/dist/headless/cli.d.ts +55 -0
- package/dist/headless/cli.js +261 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.js +207 -0
- package/dist/headless/format.d.ts +41 -0
- package/dist/headless/format.js +94 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.js +6 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.js +39 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.js +438 -0
- package/dist/headless/types.d.ts +175 -0
- package/dist/headless/types.js +16 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.js +77 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.js +128 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/manager.d.ts +75 -0
- package/dist/hooks/manager.js +289 -0
- package/dist/hooks/types.d.ts +180 -0
- package/dist/hooks/types.js +5 -0
- package/dist/index.d.ts +537 -0
- package/dist/index.js +1399 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.js +18 -0
- package/dist/knowledge-inspector.d.ts +139 -0
- package/dist/knowledge-inspector.js +533 -0
- package/dist/knowledge-scope-id.d.ts +7 -0
- package/dist/knowledge-scope-id.js +10 -0
- package/dist/knowledge-scope.d.ts +41 -0
- package/dist/knowledge-scope.js +85 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.js +248 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.js +4 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.js +41 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.js +79 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.js +158 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.js +52 -0
- package/dist/mcp/config.d.ts +77 -0
- package/dist/mcp/config.js +313 -0
- package/dist/mcp/index.d.ts +6 -0
- package/dist/mcp/index.js +3 -0
- package/dist/mcp/manager.d.ts +104 -0
- package/dist/mcp/manager.js +693 -0
- package/dist/mcp/state.d.ts +35 -0
- package/dist/mcp/state.js +94 -0
- package/dist/mcp/types.d.ts +139 -0
- package/dist/mcp/types.js +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.js +17 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.js +27 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.js +3 -0
- package/dist/onboarding/om-settings.d.ts +47 -0
- package/dist/onboarding/om-settings.js +80 -0
- package/dist/onboarding/pack-activation.d.ts +43 -0
- package/dist/onboarding/pack-activation.js +105 -0
- package/dist/onboarding/packs.d.ts +106 -0
- package/dist/onboarding/packs.js +283 -0
- package/dist/onboarding/settings.d.ts +563 -0
- package/dist/onboarding/settings.js +1110 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.js +139 -0
- package/dist/platform/index.d.ts +74 -0
- package/dist/platform/index.js +199 -0
- package/dist/plugin.d.ts +156 -0
- package/dist/plugin.js +27 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.js +84 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.js +187 -0
- package/dist/plugins/loader.d.ts +25 -0
- package/dist/plugins/loader.js +264 -0
- package/dist/plugins/manager.d.ts +115 -0
- package/dist/plugins/manager.js +507 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.js +47 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.js +58 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.js +22 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.js +109 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.js +115 -0
- package/dist/plugins/signal-lane.d.ts +59 -0
- package/dist/plugins/signal-lane.js +163 -0
- package/dist/plugins/types.d.ts +95 -0
- package/dist/plugins/types.js +1 -0
- package/dist/process-memory-diagnostics.d.ts +136 -0
- package/dist/process-memory-diagnostics.js +497 -0
- package/dist/processors/plan-rejection-abort.d.ts +16 -0
- package/dist/processors/plan-rejection-abort.js +62 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
- package/dist/providers/amazon-bedrock-gateway.js +142 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.js +99 -0
- package/dist/providers/anthropic-prompt-cache.d.ts +19 -0
- package/dist/providers/anthropic-prompt-cache.js +8 -0
- package/dist/providers/anthropic-thinking.d.ts +5 -0
- package/dist/providers/anthropic-thinking.js +22 -0
- package/dist/providers/claude-max.d.ts +67 -0
- package/dist/providers/claude-max.js +232 -0
- package/dist/providers/github-copilot-gateway.d.ts +35 -0
- package/dist/providers/github-copilot-gateway.js +58 -0
- package/dist/providers/github-copilot.d.ts +60 -0
- package/dist/providers/github-copilot.js +320 -0
- package/dist/providers/google-thinking.d.ts +31 -0
- package/dist/providers/google-thinking.js +64 -0
- package/dist/providers/google-vertex-gateway.d.ts +23 -0
- package/dist/providers/google-vertex-gateway.js +49 -0
- package/dist/providers/google-vertex.d.ts +6 -0
- package/dist/providers/google-vertex.js +51 -0
- package/dist/providers/kimi-coding.d.ts +14 -0
- package/dist/providers/kimi-coding.js +80 -0
- package/dist/providers/model-ids.d.ts +53 -0
- package/dist/providers/model-ids.js +132 -0
- package/dist/providers/openai-codex.d.ts +114 -0
- package/dist/providers/openai-codex.js +427 -0
- package/dist/providers/provider-thinking.d.ts +23 -0
- package/dist/providers/provider-thinking.js +61 -0
- package/dist/providers/thinking-request.d.ts +14 -0
- package/dist/providers/thinking-request.js +87 -0
- package/dist/providers/xai.d.ts +33 -0
- package/dist/providers/xai.js +72 -0
- package/dist/schedules/index.d.ts +10 -0
- package/dist/schedules/index.js +6 -0
- package/dist/schedules/interval.d.ts +49 -0
- package/dist/schedules/interval.js +212 -0
- package/dist/schedules/prompt.d.ts +36 -0
- package/dist/schedules/prompt.js +36 -0
- package/dist/schedules/run-script.d.ts +8 -0
- package/dist/schedules/run-script.js +80 -0
- package/dist/schedules/scheduler.d.ts +101 -0
- package/dist/schedules/scheduler.js +167 -0
- package/dist/schedules/tools.d.ts +57 -0
- package/dist/schedules/tools.js +217 -0
- package/dist/schema.d.ts +499 -0
- package/dist/schema.js +131 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.js +18 -0
- package/dist/thinking-catalog.d.ts +4 -0
- package/dist/thinking-catalog.js +13 -0
- package/dist/thinking.d.ts +37 -0
- package/dist/thinking.js +134 -0
- package/dist/tool-names.d.ts +77 -0
- package/dist/tool-names.js +53 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.js +80 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.js +31 -0
- package/dist/tools/web-search.d.ts +116 -0
- package/dist/tools/web-search.js +158 -0
- package/dist/tools/workflows/create-workflow.d.ts +7 -0
- package/dist/tools/workflows/create-workflow.js +82 -0
- package/dist/tools/workflows/delete-workflow.d.ts +7 -0
- package/dist/tools/workflows/delete-workflow.js +18 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts +28 -0
- package/dist/tools/workflows/ephemeral-memory.js +41 -0
- package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
- package/dist/tools/workflows/extract-json-schema.js +19 -0
- package/dist/tools/workflows/get-workflow.d.ts +11 -0
- package/dist/tools/workflows/get-workflow.js +31 -0
- package/dist/tools/workflows/list-available-agents.d.ts +8 -0
- package/dist/tools/workflows/list-available-agents.js +29 -0
- package/dist/tools/workflows/list-available-classifiers.d.ts +19 -0
- package/dist/tools/workflows/list-available-classifiers.js +53 -0
- package/dist/tools/workflows/list-available-tools.d.ts +9 -0
- package/dist/tools/workflows/list-available-tools.js +37 -0
- package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-available-workflows.js +29 -0
- package/dist/tools/workflows/list-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-workflows.js +30 -0
- package/dist/tools/workflows/run-workflow.d.ts +9 -0
- package/dist/tools/workflows/run-workflow.js +49 -0
- package/dist/tools/workflows/save-workflow.d.ts +1125 -0
- package/dist/tools/workflows/save-workflow.js +25 -0
- package/dist/tools/workflows/tool-ids.d.ts +16 -0
- package/dist/tools/workflows/tool-ids.js +17 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.js +97 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.js +56 -0
- package/dist/utils/discarding-scores-storage.d.ts +33 -0
- package/dist/utils/discarding-scores-storage.js +51 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.js +215 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.js +58 -0
- package/dist/utils/local-observability.d.ts +19 -0
- package/dist/utils/local-observability.js +54 -0
- package/dist/utils/maintenance-lock.d.ts +42 -0
- package/dist/utils/maintenance-lock.js +196 -0
- package/dist/utils/notification-dispatch.d.ts +74 -0
- package/dist/utils/notification-dispatch.js +128 -0
- package/dist/utils/open-url.d.ts +10 -0
- package/dist/utils/open-url.js +27 -0
- package/dist/utils/path-security.d.ts +2 -0
- package/dist/utils/path-security.js +7 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.js +59 -0
- package/dist/utils/plans.d.ts +61 -0
- package/dist/utils/plans.js +120 -0
- package/dist/utils/project.d.ts +160 -0
- package/dist/utils/project.js +361 -0
- package/dist/utils/prune-cli.d.ts +24 -0
- package/dist/utils/prune-cli.js +124 -0
- package/dist/utils/signals-pubsub.d.ts +103 -0
- package/dist/utils/signals-pubsub.js +409 -0
- package/dist/utils/slash-command-loader.d.ts +52 -0
- package/dist/utils/slash-command-loader.js +139 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.js +106 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.js +93 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.js +118 -0
- package/dist/utils/storage-maintenance.d.ts +121 -0
- package/dist/utils/storage-maintenance.js +352 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.js +109 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.js +19 -0
- package/dist/utils/update-check.d.ts +151 -0
- package/dist/utils/update-check.js +430 -0
- package/dist/utils/wake-session.d.ts +44 -0
- package/dist/utils/wake-session.js +83 -0
- package/dist/voice/stt-registry.d.ts +67 -0
- package/dist/voice/stt-registry.js +144 -0
- package/dist/voice/transcribe.d.ts +10 -0
- package/dist/voice/transcribe.js +75 -0
- package/dist/workflows/register-primitives.d.ts +52 -0
- package/dist/workflows/register-primitives.js +40 -0
- package/dist/workflows/service.d.ts +64 -0
- package/dist/workflows/service.js +50 -0
- package/package.json +117 -0
|
@@ -0,0 +1,320 @@
|
|
|
1
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
2
|
+
import { COPILOT_HEADERS, fetchCopilotModels, getGitHubCopilotBaseUrl } from "../auth/providers/github-copilot.js";
|
|
3
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
4
|
+
import { wrapLanguageModel } from "ai";
|
|
5
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
6
|
+
import { GoogleSchemaCompatLayer, applyCompatLayer } from "@mastra/schema-compat";
|
|
7
|
+
// src/providers/github-copilot.ts
|
|
8
|
+
/**
|
|
9
|
+
* GitHub Copilot OAuth Provider
|
|
10
|
+
*
|
|
11
|
+
* Uses OAuth tokens from AuthStorage to authenticate with GitHub Copilot's chat API.
|
|
12
|
+
* The Copilot API speaks an OpenAI-compatible chat format, so we plug
|
|
13
|
+
* `@ai-sdk/openai-compatible` into Copilot's API URL and use a custom fetch to inject
|
|
14
|
+
* the bearer token and Copilot-specific headers.
|
|
15
|
+
*
|
|
16
|
+
* Inspired by:
|
|
17
|
+
* - opencode: https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/github-copilot/copilot.ts
|
|
18
|
+
* - pi-mono: https://github.com/badlogic/pi-mono/blob/main/packages/ai/src/utils/oauth/github-copilot.ts
|
|
19
|
+
*/
|
|
20
|
+
const COPILOT_PROVIDER_ID = "github-copilot";
|
|
21
|
+
const COPILOT_PROVIDER_NAME = "GitHub Copilot";
|
|
22
|
+
let authStorageInstance = null;
|
|
23
|
+
/** Get or create the shared AuthStorage instance. */
|
|
24
|
+
function getAuthStorage() {
|
|
25
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
26
|
+
return authStorageInstance;
|
|
27
|
+
}
|
|
28
|
+
/** Set a custom AuthStorage instance (useful for tests / TUI integration). */
|
|
29
|
+
function setAuthStorage(storage) {
|
|
30
|
+
authStorageInstance = storage ?? null;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Heuristic: did this request come from the agent (e.g. tool result follow-ups) rather
|
|
34
|
+
* than a fresh user turn? Mirrors opencode's `isAgent` logic — Copilot bills these
|
|
35
|
+
* differently via the `x-initiator` header.
|
|
36
|
+
*/
|
|
37
|
+
function detectIsAgent(body) {
|
|
38
|
+
if (!body || typeof body !== "object") return false;
|
|
39
|
+
const obj = body;
|
|
40
|
+
const messages = obj.messages;
|
|
41
|
+
if (Array.isArray(messages) && messages.length > 0) {
|
|
42
|
+
const last = messages[messages.length - 1];
|
|
43
|
+
if (last?.role && last.role !== "user") return true;
|
|
44
|
+
if (Array.isArray(last?.content)) {
|
|
45
|
+
if (last.content.some((part) => part && typeof part === "object" && part.type === "tool_result")) return true;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const input = obj.input;
|
|
49
|
+
if (Array.isArray(input) && input.length > 0) {
|
|
50
|
+
const last = input[input.length - 1];
|
|
51
|
+
if (last?.role && last.role !== "user") return true;
|
|
52
|
+
}
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
/** Detect image/vision content in a request body. */
|
|
56
|
+
function detectIsVision(body) {
|
|
57
|
+
if (!body || typeof body !== "object") return false;
|
|
58
|
+
const obj = body;
|
|
59
|
+
const matchPart = (part) => {
|
|
60
|
+
if (!part || typeof part !== "object") return false;
|
|
61
|
+
const t = part.type;
|
|
62
|
+
return t === "image" || t === "image_url" || t === "input_image";
|
|
63
|
+
};
|
|
64
|
+
const messages = obj.messages;
|
|
65
|
+
if (Array.isArray(messages)) return messages.some((msg) => msg && typeof msg === "object" && Array.isArray(msg.content) && msg.content.some(matchPart));
|
|
66
|
+
const input = obj.input;
|
|
67
|
+
if (Array.isArray(input)) return input.some((item) => item && typeof item === "object" && Array.isArray(item.content) && item.content.some(matchPart));
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Build a fetch wrapper that authenticates with GitHub Copilot OAuth.
|
|
72
|
+
*
|
|
73
|
+
* - Injects the short-lived Copilot bearer token (auto-refreshed by AuthStorage).
|
|
74
|
+
* - Adds the VS Code-like Copilot headers required by the API.
|
|
75
|
+
* - Rewrites the request URL onto the per-token API base when `rewriteUrl` is true.
|
|
76
|
+
*/
|
|
77
|
+
function buildGitHubCopilotOAuthFetch(opts = {}) {
|
|
78
|
+
return (async (url, init) => {
|
|
79
|
+
const { headers: initHeaders, ...requestInit } = init ?? {};
|
|
80
|
+
const request = new Request(url, requestInit);
|
|
81
|
+
const storage = opts.authStorage ?? getAuthStorage();
|
|
82
|
+
storage.reload();
|
|
83
|
+
const cred = storage.get(COPILOT_PROVIDER_ID);
|
|
84
|
+
if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(COPILOT_PROVIDER_NAME);
|
|
85
|
+
let accessToken;
|
|
86
|
+
let activeCred;
|
|
87
|
+
if (storage.getOAuthCredential) {
|
|
88
|
+
activeCred = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);
|
|
89
|
+
accessToken = activeCred?.access;
|
|
90
|
+
} else {
|
|
91
|
+
accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);
|
|
92
|
+
storage.reload();
|
|
93
|
+
const reloaded = storage.get(COPILOT_PROVIDER_ID);
|
|
94
|
+
activeCred = reloaded?.type === "oauth" ? {
|
|
95
|
+
...reloaded,
|
|
96
|
+
access: accessToken ?? reloaded.access
|
|
97
|
+
} : void 0;
|
|
98
|
+
}
|
|
99
|
+
if (!accessToken || !activeCred) throw ProviderAuthRequiredError.signInExpired(COPILOT_PROVIDER_NAME);
|
|
100
|
+
const enterpriseUrl = activeCred.enterpriseUrl;
|
|
101
|
+
let parsedBody;
|
|
102
|
+
try {
|
|
103
|
+
const body = await request.clone().text();
|
|
104
|
+
parsedBody = body ? JSON.parse(body) : void 0;
|
|
105
|
+
} catch {
|
|
106
|
+
parsedBody = void 0;
|
|
107
|
+
}
|
|
108
|
+
const isAgent = detectIsAgent(parsedBody);
|
|
109
|
+
const isVision = detectIsVision(parsedBody);
|
|
110
|
+
const headers = new Headers(url instanceof Request ? url.headers : void 0);
|
|
111
|
+
if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));
|
|
112
|
+
headers.delete("authorization");
|
|
113
|
+
headers.delete("x-api-key");
|
|
114
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
115
|
+
headers.set("x-initiator", isAgent ? "agent" : "user");
|
|
116
|
+
headers.set("Openai-Intent", "conversation-edits");
|
|
117
|
+
if (isVision) headers.set("Copilot-Vision-Request", "true");
|
|
118
|
+
for (const [key, value] of Object.entries(COPILOT_HEADERS)) if (!headers.has(key)) headers.set(key, value);
|
|
119
|
+
const finalUrl = opts.rewriteUrl !== false ? rewriteToCopilotBase(request, accessToken, enterpriseUrl) : new URL(request.url);
|
|
120
|
+
const body = request.method === "GET" || request.method === "HEAD" ? void 0 : request.body;
|
|
121
|
+
const finalRequest = new Request(finalUrl, {
|
|
122
|
+
method: request.method,
|
|
123
|
+
headers,
|
|
124
|
+
body,
|
|
125
|
+
signal: request.signal,
|
|
126
|
+
redirect: request.redirect,
|
|
127
|
+
integrity: request.integrity,
|
|
128
|
+
...body ? { duplex: "half" } : {}
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
return await rejectUnauthorizedResponse(await fetch(finalRequest), {
|
|
132
|
+
providerName: COPILOT_PROVIDER_NAME,
|
|
133
|
+
requestUrl: finalUrl.toString()
|
|
134
|
+
});
|
|
135
|
+
} catch (error) {
|
|
136
|
+
if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
function rewriteToCopilotBase(url, token, enterpriseDomain) {
|
|
142
|
+
const original = url instanceof URL ? url : new URL(typeof url === "string" ? url : url.url);
|
|
143
|
+
const base = new URL(getGitHubCopilotBaseUrl(token, enterpriseDomain));
|
|
144
|
+
const pathname = original.pathname.replace(/^\/v1(\/|$)/, "/");
|
|
145
|
+
return new URL(`${pathname}${original.search}`, base);
|
|
146
|
+
}
|
|
147
|
+
function isGeminiModel(modelId) {
|
|
148
|
+
return modelId.startsWith("gemini-");
|
|
149
|
+
}
|
|
150
|
+
function applyGeminiSchemaCompatToTools(modelId, tools) {
|
|
151
|
+
if (!Array.isArray(tools)) return tools;
|
|
152
|
+
const compatLayer = new GoogleSchemaCompatLayer({
|
|
153
|
+
provider: COPILOT_PROVIDER_ID,
|
|
154
|
+
modelId,
|
|
155
|
+
supportsStructuredOutputs: false
|
|
156
|
+
});
|
|
157
|
+
return tools.map((tool) => {
|
|
158
|
+
if (!tool || typeof tool !== "object" || tool.type !== "function") return tool;
|
|
159
|
+
const functionTool = tool;
|
|
160
|
+
if (!functionTool.inputSchema) return tool;
|
|
161
|
+
return {
|
|
162
|
+
...functionTool,
|
|
163
|
+
inputSchema: applyCompatLayer({
|
|
164
|
+
schema: functionTool.inputSchema,
|
|
165
|
+
compatLayers: [compatLayer],
|
|
166
|
+
mode: "aiSdkSchema"
|
|
167
|
+
}).jsonSchema
|
|
168
|
+
};
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Middleware that prevents sending parameters Copilot's endpoint rejects. */
|
|
172
|
+
function createCopilotMiddleware(modelId) {
|
|
173
|
+
return {
|
|
174
|
+
specificationVersion: "v4",
|
|
175
|
+
transformParams: async ({ params }) => {
|
|
176
|
+
if (params.temperature !== void 0 && params.temperature !== null) delete params.topP;
|
|
177
|
+
if (isGeminiModel(modelId)) params.tools = applyGeminiSchemaCompatToTools(modelId, params.tools);
|
|
178
|
+
return params;
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Creates a model that talks to GitHub Copilot using OAuth credentials.
|
|
184
|
+
*
|
|
185
|
+
* Copilot's `/chat/completions` endpoint is OpenAI-compatible, but GitHub Copilot
|
|
186
|
+
* is not OpenAI. Use the generic OpenAI-compatible adapter with Copilot's base URL
|
|
187
|
+
* instead of the OpenAI provider plus URL rewriting.
|
|
188
|
+
*/
|
|
189
|
+
function githubCopilotProvider(modelId = "gpt-4.1", options) {
|
|
190
|
+
const headers = options?.headers;
|
|
191
|
+
const copilot = createOpenAICompatible({
|
|
192
|
+
name: COPILOT_PROVIDER_ID,
|
|
193
|
+
baseURL: "https://api.githubcopilot.com",
|
|
194
|
+
apiKey: process.env.NODE_ENV === "test" || process.env.VITEST ? "test-api-key" : "oauth-placeholder",
|
|
195
|
+
headers,
|
|
196
|
+
fetch: process.env.NODE_ENV === "test" || process.env.VITEST ? void 0 : buildGitHubCopilotOAuthFetch({
|
|
197
|
+
rewriteUrl: false,
|
|
198
|
+
authStorage: options?.authStorage
|
|
199
|
+
})
|
|
200
|
+
});
|
|
201
|
+
return wrapLanguageModel({
|
|
202
|
+
model: copilot.chatModel(modelId),
|
|
203
|
+
middleware: [createCopilotMiddleware(modelId)]
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Hard-coded fallback advertised when the live `/models` request fails (network
|
|
208
|
+
* down, expired token, etc.). Keep this conservative because the live catalog is
|
|
209
|
+
* the source of truth for the user's currently-enabled Copilot models.
|
|
210
|
+
*
|
|
211
|
+
* Available across all paid Copilot tiers and free of premium-request charges.
|
|
212
|
+
*/
|
|
213
|
+
const COPILOT_FALLBACK_MODELS = [{
|
|
214
|
+
id: "gpt-4.1",
|
|
215
|
+
name: "GPT-4.1",
|
|
216
|
+
vendor: "OpenAI",
|
|
217
|
+
supportedEndpoints: ["/chat/completions"],
|
|
218
|
+
isAnthropicShaped: false,
|
|
219
|
+
supportsVision: true,
|
|
220
|
+
supportsToolCalls: true
|
|
221
|
+
}];
|
|
222
|
+
const CATALOG_TTL_MS = 6e5;
|
|
223
|
+
const CATALOG_FAILURE_TTL_MS = 6e4;
|
|
224
|
+
const CATALOG_FETCH_TIMEOUT_MS = 5e3;
|
|
225
|
+
const catalogCache = /* @__PURE__ */ new Map();
|
|
226
|
+
const inflightFetches = /* @__PURE__ */ new Map();
|
|
227
|
+
/**
|
|
228
|
+
* Resolve the account identity for a credential read through `getApiKey`, which
|
|
229
|
+
* may await a refresh with a rotation landing inside it. The registry is
|
|
230
|
+
* consulted on both sides of that await, and only an id that survived it names
|
|
231
|
+
* the account that produced the token: an id that moved describes whichever
|
|
232
|
+
* account is active *now*, so trusting it would file this fetch's models under
|
|
233
|
+
* the wrong account and serve them to it. Unidentified is the safe answer — the
|
|
234
|
+
* caller then skips the TTL cache, exactly as it does when the store exposes no
|
|
235
|
+
* registry at all. (`AuthStorage` never needs this: its snapshots name their
|
|
236
|
+
* account.)
|
|
237
|
+
*/
|
|
238
|
+
function readStableAccountId(storage, idBeforeToken) {
|
|
239
|
+
const idAfterToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;
|
|
240
|
+
return idBeforeToken !== void 0 && idBeforeToken === idAfterToken ? idAfterToken : void 0;
|
|
241
|
+
}
|
|
242
|
+
/** Reset the in-process Copilot catalog cache (test seam, also useful after logout). */
|
|
243
|
+
function clearCopilotCatalogCache() {
|
|
244
|
+
catalogCache.clear();
|
|
245
|
+
inflightFetches.clear();
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Return the user's currently-available Copilot models.
|
|
249
|
+
*
|
|
250
|
+
* - Returns `[]` when the user is not logged in to GitHub Copilot.
|
|
251
|
+
* - Returns the cached list when a recent fetch succeeded.
|
|
252
|
+
* - On the cache-miss / expired path, fetches `/models` with a 5s timeout, filters
|
|
253
|
+
* to picker-enabled and non-policy-disabled models, then caches for 10 minutes.
|
|
254
|
+
* - On fetch failure, returns a small hard-coded fallback (so packs still work
|
|
255
|
+
* offline) and caches that for 1 minute to avoid hammering the API.
|
|
256
|
+
*
|
|
257
|
+
* Concurrent calls during a fetch share the inflight promise.
|
|
258
|
+
*/
|
|
259
|
+
async function getCopilotModelCatalog(opts = {}) {
|
|
260
|
+
const storage = opts.authStorage ?? getAuthStorage();
|
|
261
|
+
let accessToken;
|
|
262
|
+
let accountInstanceId;
|
|
263
|
+
let enterpriseUrl;
|
|
264
|
+
if (storage.getOAuthCredential) {
|
|
265
|
+
const credential = await storage.getOAuthCredential(COPILOT_PROVIDER_ID);
|
|
266
|
+
if (!credential || credential.type !== "oauth") return [];
|
|
267
|
+
accessToken = credential.access;
|
|
268
|
+
accountInstanceId = credential.accountInstanceId;
|
|
269
|
+
enterpriseUrl = credential.enterpriseUrl;
|
|
270
|
+
} else {
|
|
271
|
+
const idBeforeToken = storage.getActiveAccount?.(COPILOT_PROVIDER_ID)?.id;
|
|
272
|
+
accessToken = await storage.getApiKey(COPILOT_PROVIDER_ID);
|
|
273
|
+
if (!accessToken) return [];
|
|
274
|
+
accountInstanceId = readStableAccountId(storage, idBeforeToken);
|
|
275
|
+
const stored = storage.get(COPILOT_PROVIDER_ID);
|
|
276
|
+
if (stored?.type === "oauth") enterpriseUrl = stored.enterpriseUrl;
|
|
277
|
+
}
|
|
278
|
+
const baseUrl = getGitHubCopilotBaseUrl(accessToken, enterpriseUrl);
|
|
279
|
+
const credentialKey = accountInstanceId === void 0 ? void 0 : `${accountInstanceId}\0${baseUrl}`;
|
|
280
|
+
const dedupeKey = credentialKey;
|
|
281
|
+
const now = Date.now();
|
|
282
|
+
const cached = credentialKey ? catalogCache.get(credentialKey) : void 0;
|
|
283
|
+
if (cached && now - cached.fetchedAt < cached.ttl) return cached.models;
|
|
284
|
+
const existingFetch = dedupeKey === void 0 ? void 0 : inflightFetches.get(dedupeKey);
|
|
285
|
+
if (existingFetch) return existingFetch;
|
|
286
|
+
const fetchPromise = (async () => {
|
|
287
|
+
try {
|
|
288
|
+
const controller = new AbortController();
|
|
289
|
+
const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);
|
|
290
|
+
try {
|
|
291
|
+
const models = await fetchCopilotModels({
|
|
292
|
+
baseUrl,
|
|
293
|
+
bearerToken: accessToken,
|
|
294
|
+
signal: controller.signal
|
|
295
|
+
});
|
|
296
|
+
if (credentialKey) catalogCache.set(credentialKey, {
|
|
297
|
+
fetchedAt: Date.now(),
|
|
298
|
+
ttl: CATALOG_TTL_MS,
|
|
299
|
+
models
|
|
300
|
+
});
|
|
301
|
+
return models;
|
|
302
|
+
} finally {
|
|
303
|
+
clearTimeout(timer);
|
|
304
|
+
}
|
|
305
|
+
} catch (error) {
|
|
306
|
+
if (credentialKey) catalogCache.set(credentialKey, {
|
|
307
|
+
fetchedAt: Date.now(),
|
|
308
|
+
ttl: CATALOG_FAILURE_TTL_MS,
|
|
309
|
+
models: COPILOT_FALLBACK_MODELS
|
|
310
|
+
});
|
|
311
|
+
console.warn("Failed to fetch live GitHub Copilot models, using fallback list:", error instanceof Error ? error.message : error);
|
|
312
|
+
return COPILOT_FALLBACK_MODELS;
|
|
313
|
+
} finally {
|
|
314
|
+
if (dedupeKey !== void 0) inflightFetches.delete(dedupeKey);
|
|
315
|
+
}
|
|
316
|
+
})();
|
|
317
|
+
if (dedupeKey !== void 0) inflightFetches.set(dedupeKey, fetchPromise);
|
|
318
|
+
return fetchPromise;
|
|
319
|
+
}
|
|
320
|
+
export { buildGitHubCopilotOAuthFetch, clearCopilotCatalogCache, getAuthStorage, getCopilotModelCatalog, githubCopilotProvider, setAuthStorage };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Google (Gemini) thinking-level middleware.
|
|
3
|
+
*
|
|
4
|
+
* Maps the Mastra Code session thinking level (`off|low|medium|high|xhigh|max`)
|
|
5
|
+
* onto the thinking control each Gemini family accepts:
|
|
6
|
+
* - Gemini 3+: `thinkingConfig.thinkingLevel` (Gemini 3 Pro only accepts `low|high`).
|
|
7
|
+
* - Gemini 2.5: `thinkingConfig.thinkingBudget` (token budget).
|
|
8
|
+
* Unknown model families get no thinking config, so requests are unchanged.
|
|
9
|
+
*/
|
|
10
|
+
import type { LanguageModelMiddleware } from 'ai';
|
|
11
|
+
import type { ActiveThinkingLevel, ThinkingLevelSetting } from '../thinking.js';
|
|
12
|
+
type GeminiLevel = 'low' | 'medium' | 'high';
|
|
13
|
+
type GoogleThinkingConfig = {
|
|
14
|
+
thinkingLevel: 'minimal' | GeminiLevel;
|
|
15
|
+
} | {
|
|
16
|
+
thinkingBudget: number;
|
|
17
|
+
};
|
|
18
|
+
export declare function runGeminiThinkingLevel(modelId: string, level: ActiveThinkingLevel): ThinkingLevelSetting;
|
|
19
|
+
/**
|
|
20
|
+
* Resolve the Google thinking config for a model and session level.
|
|
21
|
+
* Returns `undefined` for `off`, unset levels, and unrecognized model families.
|
|
22
|
+
*/
|
|
23
|
+
export declare function resolveGoogleThinkingConfig(modelId: string, level: ThinkingLevelSetting | undefined): GoogleThinkingConfig | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Create middleware that injects the resolved config into
|
|
26
|
+
* `providerOptions.google.thinkingConfig`. Returns `undefined` when there is
|
|
27
|
+
* nothing to inject, so callers wrap nothing.
|
|
28
|
+
*/
|
|
29
|
+
export declare function createGoogleThinkingMiddleware(modelId: string, level: ThinkingLevelSetting | undefined): LanguageModelMiddleware | undefined;
|
|
30
|
+
export {};
|
|
31
|
+
//# sourceMappingURL=google-thinking.d.ts.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// src/providers/google-thinking.ts
|
|
2
|
+
const GEMINI_25_BUDGETS = {
|
|
3
|
+
low: 1024,
|
|
4
|
+
medium: 8192,
|
|
5
|
+
high: 24576
|
|
6
|
+
};
|
|
7
|
+
function getGeminiThinkingFamily(modelId) {
|
|
8
|
+
const id = modelId.toLowerCase();
|
|
9
|
+
if (id.startsWith("gemini-2.5")) return "budget";
|
|
10
|
+
if (id.startsWith("gemini-3-pro")) return "low-high";
|
|
11
|
+
if (id.startsWith("gemini-3.1-flash-image") || id.startsWith("gemini-3.1-flash-lite-image")) return "minimal-high";
|
|
12
|
+
if (/^gemini-\d/.test(id) && !id.startsWith("gemini-1") && !id.startsWith("gemini-2")) return "levels";
|
|
13
|
+
}
|
|
14
|
+
function geminiLevelForFamily(family, level) {
|
|
15
|
+
const cappedAtHigh = level === "xhigh" || level === "max" ? "high" : level;
|
|
16
|
+
if ((family === "low-high" || family === "minimal-high") && cappedAtHigh === "medium") return "high";
|
|
17
|
+
return cappedAtHigh;
|
|
18
|
+
}
|
|
19
|
+
function runGeminiThinkingLevel(modelId, level) {
|
|
20
|
+
const family = getGeminiThinkingFamily(modelId);
|
|
21
|
+
return family ? geminiLevelForFamily(family, level) : "off";
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Resolve the Google thinking config for a model and session level.
|
|
25
|
+
* Returns `undefined` for `off`, unset levels, and unrecognized model families.
|
|
26
|
+
*/
|
|
27
|
+
function resolveGoogleThinkingConfig(modelId, level) {
|
|
28
|
+
if (!level || level === "off") return void 0;
|
|
29
|
+
const family = getGeminiThinkingFamily(modelId);
|
|
30
|
+
if (!family) return void 0;
|
|
31
|
+
const geminiLevel = geminiLevelForFamily(family, level);
|
|
32
|
+
if (family === "budget") return { thinkingBudget: GEMINI_25_BUDGETS[geminiLevel] };
|
|
33
|
+
if (family === "minimal-high") return { thinkingLevel: geminiLevel === "low" ? "minimal" : "high" };
|
|
34
|
+
return { thinkingLevel: geminiLevel };
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Create middleware that injects the resolved config into
|
|
38
|
+
* `providerOptions.google.thinkingConfig`. Returns `undefined` when there is
|
|
39
|
+
* nothing to inject, so callers wrap nothing.
|
|
40
|
+
*/
|
|
41
|
+
function createGoogleThinkingMiddleware(modelId, level) {
|
|
42
|
+
const config = resolveGoogleThinkingConfig(modelId, level);
|
|
43
|
+
if (!config) return void 0;
|
|
44
|
+
return {
|
|
45
|
+
specificationVersion: "v4",
|
|
46
|
+
transformParams: async ({ params }) => {
|
|
47
|
+
const google = params.providerOptions?.google ?? {};
|
|
48
|
+
const thinkingConfig = google.thinkingConfig ?? {};
|
|
49
|
+
if (thinkingConfig.thinkingBudget !== void 0 || thinkingConfig.thinkingLevel !== void 0) return params;
|
|
50
|
+
params.providerOptions = {
|
|
51
|
+
...params.providerOptions,
|
|
52
|
+
google: {
|
|
53
|
+
...google,
|
|
54
|
+
thinkingConfig: {
|
|
55
|
+
...thinkingConfig,
|
|
56
|
+
...config
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
return params;
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export { createGoogleThinkingMiddleware, resolveGoogleThinkingConfig, runGeminiThinkingLevel };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { MastraModelGateway } from '@mastra/core/llm';
|
|
2
|
+
import type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, ProviderConfig } from '@mastra/core/llm';
|
|
3
|
+
export declare const GOOGLE_VERTEX_GATEWAY_ID = "google-vertex";
|
|
4
|
+
export declare function hasGoogleVertexConfiguration(): boolean;
|
|
5
|
+
export declare class GoogleVertexGateway extends MastraModelGateway {
|
|
6
|
+
readonly id = "google-vertex";
|
|
7
|
+
readonly name = "Google Vertex AI";
|
|
8
|
+
shouldEnable(): boolean;
|
|
9
|
+
fetchProviders(): Promise<Record<string, ProviderConfig>>;
|
|
10
|
+
buildUrl(_modelId: string): string | undefined;
|
|
11
|
+
getApiKey(_modelId: string): Promise<string>;
|
|
12
|
+
resolveAuth(_request: GatewayAuthRequest): GatewayAuthResult | undefined;
|
|
13
|
+
resolveLanguageModel(args: {
|
|
14
|
+
modelId: string;
|
|
15
|
+
providerId: string;
|
|
16
|
+
apiKey: string;
|
|
17
|
+
headers?: Record<string, string>;
|
|
18
|
+
transport?: any;
|
|
19
|
+
responsesWebSocket?: any;
|
|
20
|
+
}): GatewayLanguageModel;
|
|
21
|
+
}
|
|
22
|
+
export declare function createGoogleVertexGateway(): GoogleVertexGateway;
|
|
23
|
+
//# sourceMappingURL=google-vertex-gateway.d.ts.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { getGoogleVertexModelCatalog } from "./google-vertex.js";
|
|
2
|
+
import { MastraModelGateway } from "@mastra/core/llm";
|
|
3
|
+
import { createVertex } from "@ai-sdk/google-vertex";
|
|
4
|
+
// src/providers/google-vertex-gateway.ts
|
|
5
|
+
const GOOGLE_VERTEX_GATEWAY_ID = "google-vertex";
|
|
6
|
+
function hasGoogleVertexConfiguration() {
|
|
7
|
+
return Boolean(process.env.GOOGLE_VERTEX_PROJECT?.trim() && process.env.GOOGLE_VERTEX_LOCATION?.trim());
|
|
8
|
+
}
|
|
9
|
+
function googleVertexProvider(modelId, headers) {
|
|
10
|
+
return createVertex({
|
|
11
|
+
project: process.env.GOOGLE_VERTEX_PROJECT?.trim(),
|
|
12
|
+
location: process.env.GOOGLE_VERTEX_LOCATION?.trim(),
|
|
13
|
+
headers
|
|
14
|
+
})(modelId);
|
|
15
|
+
}
|
|
16
|
+
var GoogleVertexGateway = class extends MastraModelGateway {
|
|
17
|
+
id = GOOGLE_VERTEX_GATEWAY_ID;
|
|
18
|
+
name = "Google Vertex AI";
|
|
19
|
+
shouldEnable() {
|
|
20
|
+
return hasGoogleVertexConfiguration();
|
|
21
|
+
}
|
|
22
|
+
async fetchProviders() {
|
|
23
|
+
const models = await getGoogleVertexModelCatalog();
|
|
24
|
+
return { [GOOGLE_VERTEX_GATEWAY_ID]: {
|
|
25
|
+
name: "Google Vertex AI",
|
|
26
|
+
apiKeyEnvVar: "",
|
|
27
|
+
apiKeyHeader: "Authorization",
|
|
28
|
+
gateway: this.id,
|
|
29
|
+
models: models.map((model) => model.id)
|
|
30
|
+
} };
|
|
31
|
+
}
|
|
32
|
+
buildUrl(_modelId) {}
|
|
33
|
+
async getApiKey(_modelId) {
|
|
34
|
+
return hasGoogleVertexConfiguration() ? "google-application-default-credentials" : "";
|
|
35
|
+
}
|
|
36
|
+
resolveAuth(_request) {
|
|
37
|
+
return hasGoogleVertexConfiguration() ? {
|
|
38
|
+
apiKey: "google-application-default-credentials",
|
|
39
|
+
source: "gateway"
|
|
40
|
+
} : void 0;
|
|
41
|
+
}
|
|
42
|
+
resolveLanguageModel(args) {
|
|
43
|
+
return googleVertexProvider(args.modelId, args.headers);
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
function createGoogleVertexGateway() {
|
|
47
|
+
return new GoogleVertexGateway();
|
|
48
|
+
}
|
|
49
|
+
export { GOOGLE_VERTEX_GATEWAY_ID, GoogleVertexGateway, createGoogleVertexGateway, hasGoogleVertexConfiguration };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// src/providers/google-vertex.ts
|
|
2
|
+
const MODELS_DEV_API_URL = "https://models.dev/api.json";
|
|
3
|
+
const GOOGLE_VERTEX_PROVIDER_ID = "google-vertex";
|
|
4
|
+
const CATALOG_TTL_MS = 36e5;
|
|
5
|
+
const CATALOG_FAILURE_TTL_MS = 6e4;
|
|
6
|
+
const CATALOG_FETCH_TIMEOUT_MS = 5e3;
|
|
7
|
+
const GOOGLE_VERTEX_FALLBACK_MODELS = [{ id: "gemini-3.8-flash" }];
|
|
8
|
+
let catalogCache = null;
|
|
9
|
+
let inflightFetch = null;
|
|
10
|
+
function clearGoogleVertexCatalogCache() {
|
|
11
|
+
catalogCache = null;
|
|
12
|
+
inflightFetch = null;
|
|
13
|
+
}
|
|
14
|
+
async function fetchGoogleVertexModels(signal) {
|
|
15
|
+
const response = await fetch(MODELS_DEV_API_URL, { signal });
|
|
16
|
+
if (!response.ok) throw new Error(`models.dev returned ${response.status}`);
|
|
17
|
+
const data = await response.json();
|
|
18
|
+
const models = Object.keys(data[GOOGLE_VERTEX_PROVIDER_ID]?.models ?? {}).sort().map((id) => ({ id }));
|
|
19
|
+
if (models.length === 0) throw new Error("models.dev returned no Google Vertex models");
|
|
20
|
+
return models;
|
|
21
|
+
}
|
|
22
|
+
async function getGoogleVertexModelCatalog() {
|
|
23
|
+
if (catalogCache && Date.now() - catalogCache.fetchedAt < catalogCache.ttl) return catalogCache.models;
|
|
24
|
+
if (inflightFetch) return inflightFetch;
|
|
25
|
+
inflightFetch = (async () => {
|
|
26
|
+
const controller = new AbortController();
|
|
27
|
+
const timer = setTimeout(() => controller.abort(), CATALOG_FETCH_TIMEOUT_MS);
|
|
28
|
+
try {
|
|
29
|
+
const models = await fetchGoogleVertexModels(controller.signal);
|
|
30
|
+
catalogCache = {
|
|
31
|
+
fetchedAt: Date.now(),
|
|
32
|
+
ttl: CATALOG_TTL_MS,
|
|
33
|
+
models
|
|
34
|
+
};
|
|
35
|
+
return models;
|
|
36
|
+
} catch (error) {
|
|
37
|
+
catalogCache = {
|
|
38
|
+
fetchedAt: Date.now(),
|
|
39
|
+
ttl: CATALOG_FAILURE_TTL_MS,
|
|
40
|
+
models: GOOGLE_VERTEX_FALLBACK_MODELS
|
|
41
|
+
};
|
|
42
|
+
console.warn("Failed to fetch live Google Vertex models, using fallback list:", error instanceof Error ? error.message : error);
|
|
43
|
+
return GOOGLE_VERTEX_FALLBACK_MODELS;
|
|
44
|
+
} finally {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
inflightFetch = null;
|
|
47
|
+
}
|
|
48
|
+
})();
|
|
49
|
+
return inflightFetch;
|
|
50
|
+
}
|
|
51
|
+
export { clearGoogleVertexCatalogCache, getGoogleVertexModelCatalog };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MastraModelConfig } from '@mastra/core/llm';
|
|
2
|
+
import { AuthStorage } from '../auth/storage.js';
|
|
3
|
+
import type { CredentialStore } from '../auth/types.js';
|
|
4
|
+
export declare function setAuthStorage(storage: AuthStorage | undefined): void;
|
|
5
|
+
export declare function buildKimiCodingOAuthFetch(options?: {
|
|
6
|
+
credentialStore?: CredentialStore;
|
|
7
|
+
}): typeof fetch;
|
|
8
|
+
export declare function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch;
|
|
9
|
+
export declare function kimiCodingProvider(modelId: string, options: {
|
|
10
|
+
apiKey: string;
|
|
11
|
+
headers?: Record<string, string>;
|
|
12
|
+
credentialStore?: CredentialStore;
|
|
13
|
+
}): MastraModelConfig;
|
|
14
|
+
//# sourceMappingURL=kimi-coding.d.ts.map
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
2
|
+
import { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from "../auth/providers/kimi-coding.js";
|
|
3
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
4
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
5
|
+
// src/providers/kimi-coding.ts
|
|
6
|
+
const PROVIDER_ID = "kimi-for-coding";
|
|
7
|
+
const PROVIDER_NAME = "Kimi For Coding";
|
|
8
|
+
const INVALID_CREDENTIALS_MESSAGE = `${PROVIDER_NAME} credentials are invalid. Please reconnect the account.`;
|
|
9
|
+
const BASE_URL = "https://api.kimi.com/coding/v1";
|
|
10
|
+
let authStorageInstance = null;
|
|
11
|
+
function setAuthStorage(storage) {
|
|
12
|
+
authStorageInstance = storage ?? null;
|
|
13
|
+
}
|
|
14
|
+
function getAuthStorage() {
|
|
15
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
16
|
+
return authStorageInstance;
|
|
17
|
+
}
|
|
18
|
+
function buildKimiCodingOAuthFetch(options = {}) {
|
|
19
|
+
return (async (input, init) => {
|
|
20
|
+
const store = options.credentialStore ?? getAuthStorage();
|
|
21
|
+
store.reload();
|
|
22
|
+
const credential = store.get(PROVIDER_ID);
|
|
23
|
+
if (!credential || credential.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(PROVIDER_NAME);
|
|
24
|
+
if (!isKimiCodingDeviceId(credential.deviceId)) throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);
|
|
25
|
+
let token;
|
|
26
|
+
let activeCredential = credential;
|
|
27
|
+
if (store.getOAuthCredential) {
|
|
28
|
+
activeCredential = await store.getOAuthCredential(PROVIDER_ID);
|
|
29
|
+
token = activeCredential?.access;
|
|
30
|
+
} else {
|
|
31
|
+
token = await store.getApiKey(PROVIDER_ID);
|
|
32
|
+
store.reload();
|
|
33
|
+
const reloaded = store.get(PROVIDER_ID);
|
|
34
|
+
activeCredential = reloaded?.type === "oauth" ? {
|
|
35
|
+
...reloaded,
|
|
36
|
+
access: token ?? reloaded.access
|
|
37
|
+
} : void 0;
|
|
38
|
+
}
|
|
39
|
+
if (!token) throw ProviderAuthRequiredError.signInExpired(PROVIDER_NAME);
|
|
40
|
+
if (!activeCredential || !isKimiCodingDeviceId(activeCredential.deviceId)) throw new ProviderAuthRequiredError(INVALID_CREDENTIALS_MESSAGE);
|
|
41
|
+
const deviceHeaders = getKimiCodingDeviceHeaders(activeCredential.deviceId);
|
|
42
|
+
const headers = new Headers(input instanceof Request ? input.headers : void 0);
|
|
43
|
+
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
44
|
+
for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);
|
|
45
|
+
headers.delete("authorization");
|
|
46
|
+
headers.delete("x-api-key");
|
|
47
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
48
|
+
return rejectUnauthorizedResponse(await fetch(input, {
|
|
49
|
+
...init,
|
|
50
|
+
headers
|
|
51
|
+
}), {
|
|
52
|
+
providerName: PROVIDER_NAME,
|
|
53
|
+
requestUrl: input instanceof URL ? input.toString() : typeof input === "string" ? input : input.url
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function buildKimiCodingApiKeyFetch(apiKey) {
|
|
58
|
+
return (async (input, init) => {
|
|
59
|
+
const headers = new Headers(input instanceof Request ? input.headers : void 0);
|
|
60
|
+
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
61
|
+
headers.delete("authorization");
|
|
62
|
+
headers.delete("x-api-key");
|
|
63
|
+
headers.set("Authorization", `Bearer ${apiKey}`);
|
|
64
|
+
return fetch(input, {
|
|
65
|
+
...init,
|
|
66
|
+
headers
|
|
67
|
+
});
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
function kimiCodingProvider(modelId, options) {
|
|
71
|
+
const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === "oauth";
|
|
72
|
+
return createAnthropic({
|
|
73
|
+
name: PROVIDER_ID,
|
|
74
|
+
apiKey: "auth-placeholder",
|
|
75
|
+
baseURL: BASE_URL,
|
|
76
|
+
headers: options.headers,
|
|
77
|
+
fetch: usesOAuth ? buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) : buildKimiCodingApiKeyFetch(options.apiKey)
|
|
78
|
+
})(modelId);
|
|
79
|
+
}
|
|
80
|
+
export { buildKimiCodingApiKeyFetch, buildKimiCodingOAuthFetch, kimiCodingProvider, setAuthStorage };
|