@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,427 @@
|
|
|
1
|
+
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
2
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
3
|
+
import { runCatalogThinkingLevel } from "../thinking-catalog.js";
|
|
4
|
+
import { supportsMaxReasoningEffort } from "../thinking.js";
|
|
5
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
6
|
+
import { wrapLanguageModel } from "ai";
|
|
7
|
+
// src/providers/openai-codex.ts
|
|
8
|
+
/**
|
|
9
|
+
* OpenAI Codex OAuth Provider
|
|
10
|
+
*
|
|
11
|
+
* Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.
|
|
12
|
+
* This allows access to OpenAI models through the ChatGPT OAuth flow.
|
|
13
|
+
*
|
|
14
|
+
* Inspired by opencode's Codex plugin implementation:
|
|
15
|
+
* https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts
|
|
16
|
+
*/
|
|
17
|
+
const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
|
|
18
|
+
const CODEX_ORIGINATOR = "mastracode";
|
|
19
|
+
const CODEX_USER_AGENT = "mastracode";
|
|
20
|
+
const CODEX_PROVIDER_NAME = "OpenAI Codex";
|
|
21
|
+
let authStorageInstance = null;
|
|
22
|
+
/**
|
|
23
|
+
* Get or create the shared AuthStorage instance
|
|
24
|
+
*/
|
|
25
|
+
function getAuthStorage() {
|
|
26
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
27
|
+
return authStorageInstance;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Set a custom AuthStorage instance (useful for TUI integration)
|
|
31
|
+
*/
|
|
32
|
+
function setAuthStorage(storage) {
|
|
33
|
+
authStorageInstance = storage ?? null;
|
|
34
|
+
}
|
|
35
|
+
const CODEX_INSTRUCTIONS = `You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
|
|
36
|
+
|
|
37
|
+
IMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;
|
|
38
|
+
const GPT5_MODEL_RE = /^gpt-5(?:\.|-|$)/;
|
|
39
|
+
function getEffectiveThinkingLevel(modelId, level) {
|
|
40
|
+
const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === "off" ? "low" : level;
|
|
41
|
+
return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);
|
|
42
|
+
}
|
|
43
|
+
const THINKING_LEVEL_TO_REASONING_EFFORT = {
|
|
44
|
+
off: void 0,
|
|
45
|
+
low: "low",
|
|
46
|
+
medium: "medium",
|
|
47
|
+
high: "high",
|
|
48
|
+
xhigh: "xhigh",
|
|
49
|
+
max: "max"
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* Create Codex middleware with the given reasoning effort level.
|
|
53
|
+
*/
|
|
54
|
+
function createCodexMiddleware(reasoningEffort, oauthOptions) {
|
|
55
|
+
return {
|
|
56
|
+
specificationVersion: "v4",
|
|
57
|
+
transformParams: async ({ params }) => {
|
|
58
|
+
if (params.temperature !== void 0 && params.temperature !== null) delete params.topP;
|
|
59
|
+
const fast = oauthOptions && (oauthOptions.serviceTier === "fast" || params.providerOptions?.mastracode?.codexServiceTier === "fast");
|
|
60
|
+
params.providerOptions = {
|
|
61
|
+
...params.providerOptions,
|
|
62
|
+
openai: {
|
|
63
|
+
...params.providerOptions?.openai ?? {},
|
|
64
|
+
instructions: CODEX_INSTRUCTIONS,
|
|
65
|
+
store: false,
|
|
66
|
+
...reasoningEffort ? { reasoningEffort } : {},
|
|
67
|
+
...fast ? { serviceTier: "priority" } : {}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
return params;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The thread a model request belongs to, from the `x-thread-id` header that
|
|
76
|
+
* model resolution adds for requests made inside a thread.
|
|
77
|
+
*/
|
|
78
|
+
function getRequestThreadId(headers) {
|
|
79
|
+
if (!headers) return void 0;
|
|
80
|
+
for (const name in headers) if (name.toLowerCase() === "x-thread-id") return headers[name] || void 0;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Create middleware that sends `prompt_cache_key` on OpenAI Responses requests.
|
|
84
|
+
*
|
|
85
|
+
* OpenAI routes a cached prompt by a hash of its start plus this key. Every
|
|
86
|
+
* Mastra Code prompt starts with the same system prompt, so without a key all
|
|
87
|
+
* threads compete for the same cache slot and consecutive steps of one run often
|
|
88
|
+
* land on a machine that doesn't hold their prefix. Keying by thread keeps each
|
|
89
|
+
* thread's requests together. A key the caller already set wins.
|
|
90
|
+
*/
|
|
91
|
+
function createPromptCacheKeyMiddleware(promptCacheKey) {
|
|
92
|
+
if (!promptCacheKey) return void 0;
|
|
93
|
+
return {
|
|
94
|
+
specificationVersion: "v4",
|
|
95
|
+
transformParams: async ({ params }) => {
|
|
96
|
+
params.providerOptions = {
|
|
97
|
+
...params.providerOptions,
|
|
98
|
+
openai: {
|
|
99
|
+
promptCacheKey,
|
|
100
|
+
...params.providerOptions?.openai ?? {}
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
return params;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Create middleware that forwards a resolved reasoning effort to an
|
|
109
|
+
* OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.
|
|
110
|
+
*
|
|
111
|
+
* Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing
|
|
112
|
+
* (e.g. thinking level `off`), leaving the wire request without a
|
|
113
|
+
* `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not
|
|
114
|
+
* inject Codex-only options (instructions/store); it only sets reasoning
|
|
115
|
+
* effort, keyed by the caller-supplied provider id.
|
|
116
|
+
*/
|
|
117
|
+
function createReasoningEffortMiddleware(providerKey, reasoningEffort) {
|
|
118
|
+
if (!reasoningEffort) return void 0;
|
|
119
|
+
return {
|
|
120
|
+
specificationVersion: "v4",
|
|
121
|
+
transformParams: async ({ params }) => {
|
|
122
|
+
params.providerOptions = {
|
|
123
|
+
...params.providerOptions,
|
|
124
|
+
[providerKey]: {
|
|
125
|
+
...params.providerOptions?.[providerKey] ?? {},
|
|
126
|
+
reasoningEffort
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
return params;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Get a live OAuth bearer token for the Codex OAuth credential.
|
|
135
|
+
*
|
|
136
|
+
* Refreshes the token if it's expired, and returns the credential's
|
|
137
|
+
* accountId alongside the access token. Throws if the user isn't logged in
|
|
138
|
+
* or if the refresh fails.
|
|
139
|
+
*
|
|
140
|
+
* This is the only piece of Codex auth that is genuinely shared between
|
|
141
|
+
* the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand
|
|
142
|
+
* fetch (`buildCodexStagehandFetch`).
|
|
143
|
+
*/
|
|
144
|
+
async function getCodexBearer(authStorage) {
|
|
145
|
+
const storage = authStorage ?? getAuthStorage();
|
|
146
|
+
storage.reload();
|
|
147
|
+
let cred = storage.get("openai-codex");
|
|
148
|
+
if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
|
|
149
|
+
if (storage.getOAuthCredential) {
|
|
150
|
+
cred = await storage.getOAuthCredential("openai-codex");
|
|
151
|
+
if (!cred) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
|
|
152
|
+
} else if (Date.now() >= cred.expires) {
|
|
153
|
+
const refreshedToken = await storage.getApiKey("openai-codex");
|
|
154
|
+
if (!refreshedToken) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);
|
|
155
|
+
storage.reload();
|
|
156
|
+
const reloaded = storage.get("openai-codex");
|
|
157
|
+
if (!reloaded || reloaded.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);
|
|
158
|
+
cred = {
|
|
159
|
+
...reloaded,
|
|
160
|
+
access: refreshedToken
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
return {
|
|
164
|
+
accessToken: cred.access,
|
|
165
|
+
accountId: cred.accountId
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Make a Responses request body safe for Codex's stateless (`store: false`) mode.
|
|
170
|
+
*
|
|
171
|
+
* AI SDK replays earlier output items with their server ids (`rs_…`, `msg_…`,
|
|
172
|
+
* `fc_…`) even when `store` is false. Codex looks those ids up and answers
|
|
173
|
+
* 404 `Item with id 'rs_…' not found` once its short-lived item cache has
|
|
174
|
+
* expired, so every later request in the thread fails the same way. Like the
|
|
175
|
+
* Codex CLI, send items without ids (the encrypted reasoning content carries the
|
|
176
|
+
* reasoning chain) and drop `item_reference`s, which can never resolve.
|
|
177
|
+
*/
|
|
178
|
+
function stripCodexInputItemIds(body) {
|
|
179
|
+
let parsed;
|
|
180
|
+
try {
|
|
181
|
+
parsed = JSON.parse(body);
|
|
182
|
+
} catch {
|
|
183
|
+
return body;
|
|
184
|
+
}
|
|
185
|
+
if (!parsed || typeof parsed !== "object" || !Array.isArray(parsed.input)) return body;
|
|
186
|
+
const request = parsed;
|
|
187
|
+
if (request.store !== false) return body;
|
|
188
|
+
request.input = request.input.flatMap((item) => {
|
|
189
|
+
if (!item || typeof item !== "object") return [item];
|
|
190
|
+
const { id: _id, ...rest } = item;
|
|
191
|
+
if (rest.type === "item_reference") return [];
|
|
192
|
+
return [rest];
|
|
193
|
+
});
|
|
194
|
+
return JSON.stringify(request);
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Build a fetch function that handles OpenAI Codex OAuth.
|
|
198
|
+
* Preserves non-authorization headers from init.
|
|
199
|
+
* When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions
|
|
200
|
+
* to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the
|
|
201
|
+
* SDK already targets the correct URL.
|
|
202
|
+
*/
|
|
203
|
+
function buildOpenAICodexOAuthFetch(opts = {}) {
|
|
204
|
+
return (async (url, init) => {
|
|
205
|
+
const { accessToken, accountId } = await getCodexBearer(opts.authStorage);
|
|
206
|
+
const { headers: initHeaders, ...requestInit } = init ?? {};
|
|
207
|
+
const request = new Request(url, requestInit);
|
|
208
|
+
const headers = new Headers(url instanceof Request ? url.headers : void 0);
|
|
209
|
+
if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));
|
|
210
|
+
headers.delete("authorization");
|
|
211
|
+
headers.delete("x-api-key");
|
|
212
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
213
|
+
if (!headers.has("originator")) headers.set("originator", CODEX_ORIGINATOR);
|
|
214
|
+
if (!headers.has("User-Agent")) headers.set("User-Agent", CODEX_USER_AGENT);
|
|
215
|
+
if (accountId) headers.set("ChatGPT-Account-ID", accountId);
|
|
216
|
+
const threadId = headers.get("x-thread-id");
|
|
217
|
+
if (threadId) {
|
|
218
|
+
if (!headers.has("session-id")) headers.set("session-id", threadId);
|
|
219
|
+
if (!headers.has("thread-id")) headers.set("thread-id", threadId);
|
|
220
|
+
}
|
|
221
|
+
const parsed = new URL(request.url);
|
|
222
|
+
const finalUrl = opts.rewriteUrl !== false && (parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions")) ? new URL(CODEX_API_ENDPOINT) : parsed;
|
|
223
|
+
const hasBody = request.method !== "GET" && request.method !== "HEAD" && request.body !== null;
|
|
224
|
+
const isJson = headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() === "application/json";
|
|
225
|
+
let body;
|
|
226
|
+
if (hasBody && isJson) {
|
|
227
|
+
body = stripCodexInputItemIds(await request.text());
|
|
228
|
+
headers.delete("content-length");
|
|
229
|
+
} else if (hasBody) body = request.body;
|
|
230
|
+
const finalRequest = new Request(finalUrl, {
|
|
231
|
+
method: request.method,
|
|
232
|
+
headers,
|
|
233
|
+
body,
|
|
234
|
+
signal: request.signal,
|
|
235
|
+
redirect: request.redirect,
|
|
236
|
+
integrity: request.integrity,
|
|
237
|
+
...body instanceof ReadableStream ? { duplex: "half" } : {}
|
|
238
|
+
});
|
|
239
|
+
try {
|
|
240
|
+
return await rejectUnauthorizedResponse(await fetch(finalRequest), {
|
|
241
|
+
providerName: CODEX_PROVIDER_NAME,
|
|
242
|
+
requestUrl: finalUrl.toString()
|
|
243
|
+
});
|
|
244
|
+
} catch (error) {
|
|
245
|
+
if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
|
|
246
|
+
throw error;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Build a fetch function for Stagehand-on-Codex.
|
|
252
|
+
*
|
|
253
|
+
* The Codex backend has two requirements that AI SDK's non-streaming
|
|
254
|
+
* `generateText` path doesn't naturally satisfy:
|
|
255
|
+
*
|
|
256
|
+
* 1. `stream: true` must be set on every request body.
|
|
257
|
+
* 2. The response is delivered as Server-Sent Events; AI SDK's
|
|
258
|
+
* non-streaming code path expects a single JSON body.
|
|
259
|
+
*
|
|
260
|
+
* This fetch forces streaming on the outgoing request, collects the SSE
|
|
261
|
+
* events, and synthesizes the non-streaming JSON shape that
|
|
262
|
+
* `@ai-sdk/openai`'s Responses API parser expects.
|
|
263
|
+
*
|
|
264
|
+
* Headers, OAuth refresh, and URL targeting are handled by the caller via
|
|
265
|
+
* `baseURL` / `headers` on the AI SDK provider; this fetch only injects the
|
|
266
|
+
* live OAuth bearer per call.
|
|
267
|
+
*/
|
|
268
|
+
function buildCodexStagehandFetch(authStorage) {
|
|
269
|
+
return (async (url, init) => {
|
|
270
|
+
const { accessToken } = await getCodexBearer(authStorage);
|
|
271
|
+
const { headers: initHeaders, ...requestInit } = init ?? {};
|
|
272
|
+
const request = new Request(url, requestInit);
|
|
273
|
+
const headers = new Headers(url instanceof Request ? url.headers : void 0);
|
|
274
|
+
if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));
|
|
275
|
+
headers.delete("authorization");
|
|
276
|
+
headers.delete("x-api-key");
|
|
277
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
278
|
+
headers.set("Accept", "text/event-stream");
|
|
279
|
+
let body = await request.clone().text();
|
|
280
|
+
try {
|
|
281
|
+
const parsed = JSON.parse(body);
|
|
282
|
+
parsed.stream = true;
|
|
283
|
+
body = JSON.stringify(parsed);
|
|
284
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
285
|
+
} catch {}
|
|
286
|
+
const upstream = await fetch(new Request(request, {
|
|
287
|
+
headers,
|
|
288
|
+
...request.method === "GET" || request.method === "HEAD" ? {} : { body }
|
|
289
|
+
}));
|
|
290
|
+
if (!upstream.ok) return upstream;
|
|
291
|
+
const aggregated = await aggregateCodexStream(upstream);
|
|
292
|
+
return new Response(aggregated, {
|
|
293
|
+
status: 200,
|
|
294
|
+
headers: { "content-type": "application/json" }
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Read an SSE Response and reduce it to a single JSON string matching the
|
|
300
|
+
* non-streaming OpenAI Responses-API shape.
|
|
301
|
+
*
|
|
302
|
+
* Event vocabulary we care about (per OpenAI Responses API streaming):
|
|
303
|
+
* - response.created → carries `response` object (id, model, usage stub)
|
|
304
|
+
* - response.output_item.added/done → output items (message, reasoning, etc.)
|
|
305
|
+
* - response.output_text.delta → text chunks
|
|
306
|
+
* - response.completed → final `response` snapshot incl. usage
|
|
307
|
+
* - response.error / error → bubble up as a thrown body
|
|
308
|
+
*
|
|
309
|
+
* Reasoning events (`response.reasoning_summary.*`) are intentionally ignored
|
|
310
|
+
* for the non-streaming text response.
|
|
311
|
+
*/
|
|
312
|
+
async function aggregateCodexStream(response) {
|
|
313
|
+
if (!response.body) throw new Error("Codex streaming response had no body");
|
|
314
|
+
const reader = response.body.getReader();
|
|
315
|
+
const decoder = new TextDecoder("utf-8");
|
|
316
|
+
let buffer = "";
|
|
317
|
+
let finalResponse = null;
|
|
318
|
+
let createdResponse = null;
|
|
319
|
+
const items = /* @__PURE__ */ new Map();
|
|
320
|
+
const textBuffers = /* @__PURE__ */ new Map();
|
|
321
|
+
const handleEvent = (event) => {
|
|
322
|
+
if (!event.data || event.data === "[DONE]") return;
|
|
323
|
+
let payload;
|
|
324
|
+
try {
|
|
325
|
+
payload = JSON.parse(event.data);
|
|
326
|
+
} catch {
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
switch (payload.type ?? event.event ?? "") {
|
|
330
|
+
case "response.created":
|
|
331
|
+
createdResponse = payload.response ?? createdResponse;
|
|
332
|
+
break;
|
|
333
|
+
case "response.output_item.added":
|
|
334
|
+
if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
|
|
335
|
+
break;
|
|
336
|
+
case "response.output_item.done":
|
|
337
|
+
if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
|
|
338
|
+
break;
|
|
339
|
+
case "response.output_text.delta": {
|
|
340
|
+
const key = `${payload.output_index}:${payload.content_index ?? 0}`;
|
|
341
|
+
textBuffers.set(key, (textBuffers.get(key) ?? "") + (payload.delta ?? ""));
|
|
342
|
+
break;
|
|
343
|
+
}
|
|
344
|
+
case "response.completed":
|
|
345
|
+
finalResponse = payload.response ?? finalResponse;
|
|
346
|
+
break;
|
|
347
|
+
case "response.error":
|
|
348
|
+
case "error": throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);
|
|
349
|
+
}
|
|
350
|
+
};
|
|
351
|
+
const processChunk = (chunk) => {
|
|
352
|
+
buffer += chunk.replace(/\r\n/g, "\n");
|
|
353
|
+
let sepIdx;
|
|
354
|
+
while ((sepIdx = buffer.indexOf("\n\n")) !== -1) {
|
|
355
|
+
const raw = buffer.slice(0, sepIdx);
|
|
356
|
+
buffer = buffer.slice(sepIdx + 2);
|
|
357
|
+
const event = {};
|
|
358
|
+
const dataLines = [];
|
|
359
|
+
for (const line of raw.split("\n")) if (line.startsWith("event:")) event.event = line.slice(6).trim();
|
|
360
|
+
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
361
|
+
if (dataLines.length > 0) event.data = dataLines.join("\n");
|
|
362
|
+
handleEvent(event);
|
|
363
|
+
}
|
|
364
|
+
};
|
|
365
|
+
try {
|
|
366
|
+
while (true) {
|
|
367
|
+
const { value, done } = await reader.read();
|
|
368
|
+
if (done) break;
|
|
369
|
+
processChunk(decoder.decode(value, { stream: true }));
|
|
370
|
+
}
|
|
371
|
+
processChunk(decoder.decode());
|
|
372
|
+
} finally {
|
|
373
|
+
reader.releaseLock();
|
|
374
|
+
}
|
|
375
|
+
const base = finalResponse ?? createdResponse ?? { output: [] };
|
|
376
|
+
const finalItems = Array.from(items.entries()).sort(([a], [b]) => a - b).map(([index, item]) => {
|
|
377
|
+
if (item?.type === "message" && Array.isArray(item.content)) item.content = item.content.map((c, ci) => {
|
|
378
|
+
const key = `${index}:${ci}`;
|
|
379
|
+
if (textBuffers.has(key)) return {
|
|
380
|
+
...c,
|
|
381
|
+
text: textBuffers.get(key)
|
|
382
|
+
};
|
|
383
|
+
return c;
|
|
384
|
+
});
|
|
385
|
+
return item;
|
|
386
|
+
});
|
|
387
|
+
base.output = finalItems.length > 0 ? finalItems : base.output ?? [];
|
|
388
|
+
return JSON.stringify(base);
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Creates an OpenAI model using ChatGPT OAuth authentication
|
|
392
|
+
* Uses OAuth tokens from AuthStorage (auto-refreshes when needed)
|
|
393
|
+
*
|
|
394
|
+
* IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.
|
|
395
|
+
* URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.
|
|
396
|
+
*/
|
|
397
|
+
function openaiCodexProvider(modelId = "codex-mini-latest", options) {
|
|
398
|
+
const effectiveLevel = getEffectiveThinkingLevel(modelId, options?.thinkingLevel ?? "medium");
|
|
399
|
+
const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
|
|
400
|
+
const headers = options?.headers;
|
|
401
|
+
const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));
|
|
402
|
+
const useTestApiKey = process.env.NODE_ENV === "test" || Boolean(process.env.VITEST);
|
|
403
|
+
const middleware = [createCodexMiddleware(reasoningEffort, { serviceTier: options?.serviceTier }), ...promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : []];
|
|
404
|
+
const baseURL = process.env.OPENAI_BASE_URL;
|
|
405
|
+
if (useTestApiKey) {
|
|
406
|
+
const openai = createOpenAI({
|
|
407
|
+
apiKey: "test-api-key",
|
|
408
|
+
baseURL,
|
|
409
|
+
headers
|
|
410
|
+
});
|
|
411
|
+
return wrapLanguageModel({
|
|
412
|
+
model: openai.responses(modelId),
|
|
413
|
+
middleware
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
const openai = createOpenAI({
|
|
417
|
+
apiKey: "oauth-dummy-key",
|
|
418
|
+
baseURL,
|
|
419
|
+
headers,
|
|
420
|
+
fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage })
|
|
421
|
+
});
|
|
422
|
+
return wrapLanguageModel({
|
|
423
|
+
model: openai.responses(modelId),
|
|
424
|
+
middleware
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
export { THINKING_LEVEL_TO_REASONING_EFFORT, buildCodexStagehandFetch, buildOpenAICodexOAuthFetch, createCodexMiddleware, createPromptCacheKeyMiddleware, createReasoningEffortMiddleware, getAuthStorage, getEffectiveThinkingLevel, getRequestThreadId, openaiCodexProvider, setAuthStorage, stripCodexInputItemIds, supportsMaxReasoningEffort };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { ModelRouterLanguageModel } from '@mastra/core/llm';
|
|
2
|
+
import { wrapLanguageModel } from 'ai';
|
|
3
|
+
import type { JSONValue } from 'ai';
|
|
4
|
+
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
5
|
+
export interface ProviderThinkingOptions {
|
|
6
|
+
optionsKey: string;
|
|
7
|
+
options: Record<string, JSONValue>;
|
|
8
|
+
controlKeys: ReadonlySet<string>;
|
|
9
|
+
}
|
|
10
|
+
export declare function providerThinkingOptions(routedModelId: string, level: ThinkingLevelSetting | undefined): ProviderThinkingOptions | undefined;
|
|
11
|
+
type AiSdkLanguageModel = Parameters<typeof wrapLanguageModel>[0]['model'];
|
|
12
|
+
export declare function withThinkingOptionsModel<Model extends AiSdkLanguageModel>(model: Model, thinking: ProviderThinkingOptions | undefined): Model | ReturnType<typeof wrapLanguageModel>;
|
|
13
|
+
type RouterConfig = ConstructorParameters<typeof ModelRouterLanguageModel>[0];
|
|
14
|
+
type RouterCallOptions = Parameters<ModelRouterLanguageModel['doStream']>[0];
|
|
15
|
+
type RouterCallResult = ReturnType<ModelRouterLanguageModel['doStream']>;
|
|
16
|
+
export declare class ModelRouterLanguageModelWithThinking extends ModelRouterLanguageModel {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(config: RouterConfig, thinking: ProviderThinkingOptions | undefined);
|
|
19
|
+
doGenerate(options: RouterCallOptions): RouterCallResult;
|
|
20
|
+
doStream(options: RouterCallOptions): RouterCallResult;
|
|
21
|
+
}
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=provider-thinking.d.ts.map
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { requestableReasoningOptions, runThinkingLevel } from "../thinking.js";
|
|
2
|
+
import { thinkingRequestFormatFor } from "./thinking-request.js";
|
|
3
|
+
import { ModelRouterLanguageModel, getModelReasoningOptions } from "@mastra/core/llm";
|
|
4
|
+
import { wrapLanguageModel } from "ai";
|
|
5
|
+
// src/providers/provider-thinking.ts
|
|
6
|
+
function providerThinkingOptions(routedModelId, level) {
|
|
7
|
+
const format = thinkingRequestFormatFor(routedModelId);
|
|
8
|
+
if (!format || !level) return void 0;
|
|
9
|
+
const catalogOptions = getModelReasoningOptions(routedModelId);
|
|
10
|
+
const requestable = requestableReasoningOptions(routedModelId, catalogOptions);
|
|
11
|
+
const runLevel = runThinkingLevel(routedModelId, level, catalogOptions);
|
|
12
|
+
if (!requestable?.length || runLevel === "off") return void 0;
|
|
13
|
+
const effortOptions = format.sendEffort?.(runLevel);
|
|
14
|
+
const options = requestable.some((option) => option.type === "effort") ? effortOptions : format.enableThinking;
|
|
15
|
+
if (!options) return void 0;
|
|
16
|
+
const controlKeys = /* @__PURE__ */ new Set([...Object.keys(effortOptions ?? {}), ...Object.keys(format.enableThinking ?? {})]);
|
|
17
|
+
return {
|
|
18
|
+
optionsKey: format.optionsKey,
|
|
19
|
+
options,
|
|
20
|
+
controlKeys
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function withThinkingOptions(callOptions, thinking) {
|
|
24
|
+
if (!thinking) return callOptions;
|
|
25
|
+
const callerOptions = callOptions.providerOptions?.[thinking.optionsKey] ?? {};
|
|
26
|
+
if (Object.keys(callerOptions).some((key) => thinking.controlKeys.has(key))) return callOptions;
|
|
27
|
+
return {
|
|
28
|
+
...callOptions,
|
|
29
|
+
providerOptions: {
|
|
30
|
+
...callOptions.providerOptions,
|
|
31
|
+
[thinking.optionsKey]: {
|
|
32
|
+
...callerOptions,
|
|
33
|
+
...thinking.options
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
function withThinkingOptionsModel(model, thinking) {
|
|
39
|
+
if (!thinking) return model;
|
|
40
|
+
return wrapLanguageModel({
|
|
41
|
+
model,
|
|
42
|
+
middleware: {
|
|
43
|
+
specificationVersion: "v4",
|
|
44
|
+
transformParams: async ({ params }) => withThinkingOptions(params, thinking)
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
var ModelRouterLanguageModelWithThinking = class extends ModelRouterLanguageModel {
|
|
49
|
+
#thinking;
|
|
50
|
+
constructor(config, thinking) {
|
|
51
|
+
super(config);
|
|
52
|
+
this.#thinking = thinking;
|
|
53
|
+
}
|
|
54
|
+
doGenerate(options) {
|
|
55
|
+
return super.doGenerate(withThinkingOptions(options, this.#thinking));
|
|
56
|
+
}
|
|
57
|
+
doStream(options) {
|
|
58
|
+
return super.doStream(withThinkingOptions(options, this.#thinking));
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
export { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel };
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { JSONValue } from 'ai';
|
|
2
|
+
import type { ActiveThinkingLevel } from '../thinking.js';
|
|
3
|
+
type ThinkingProviderOptions = Record<string, JSONValue>;
|
|
4
|
+
export interface ThinkingRequestFormat {
|
|
5
|
+
optionsKey: string;
|
|
6
|
+
sendEffort?: (effort: ActiveThinkingLevel) => ThinkingProviderOptions;
|
|
7
|
+
acceptedEfforts?: readonly ActiveThinkingLevel[];
|
|
8
|
+
enableThinking?: ThinkingProviderOptions;
|
|
9
|
+
}
|
|
10
|
+
export declare function isThinkingAdapterProvider(provider: string): boolean;
|
|
11
|
+
export declare function isRoutedWithoutThinking(modelId: string): boolean;
|
|
12
|
+
export declare function thinkingRequestFormatFor(modelId: string): ThinkingRequestFormat | undefined;
|
|
13
|
+
export {};
|
|
14
|
+
//# sourceMappingURL=thinking-request.d.ts.map
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { MASTRA_GATEWAY_PREFIX, stripMastraGatewayPrefix } from "./model-ids.js";
|
|
2
|
+
// src/providers/thinking-request.ts
|
|
3
|
+
const LOW_TO_HIGH = [
|
|
4
|
+
"low",
|
|
5
|
+
"medium",
|
|
6
|
+
"high"
|
|
7
|
+
];
|
|
8
|
+
const sendReasoningEffort = (reasoningEffort) => ({ reasoningEffort });
|
|
9
|
+
const ENABLE_REASONING = { reasoning: { enabled: true } };
|
|
10
|
+
const OPENROUTER_FORMAT = {
|
|
11
|
+
optionsKey: "openrouter",
|
|
12
|
+
sendEffort: (effort) => ({ reasoning: { effort } }),
|
|
13
|
+
enableThinking: ENABLE_REASONING
|
|
14
|
+
};
|
|
15
|
+
const REQUEST_FORMATS_BY_PROVIDER = {
|
|
16
|
+
deepseek: {
|
|
17
|
+
optionsKey: "deepseek",
|
|
18
|
+
sendEffort: sendReasoningEffort,
|
|
19
|
+
enableThinking: { thinking: { type: "enabled" } }
|
|
20
|
+
},
|
|
21
|
+
openrouter: OPENROUTER_FORMAT,
|
|
22
|
+
alibaba: {
|
|
23
|
+
optionsKey: "alibaba",
|
|
24
|
+
enableThinking: { enableThinking: true }
|
|
25
|
+
},
|
|
26
|
+
groq: {
|
|
27
|
+
optionsKey: "groq",
|
|
28
|
+
sendEffort: sendReasoningEffort,
|
|
29
|
+
acceptedEfforts: LOW_TO_HIGH
|
|
30
|
+
},
|
|
31
|
+
mistral: {
|
|
32
|
+
optionsKey: "mistral",
|
|
33
|
+
sendEffort: sendReasoningEffort,
|
|
34
|
+
acceptedEfforts: ["high"]
|
|
35
|
+
},
|
|
36
|
+
xai: {
|
|
37
|
+
optionsKey: "xai",
|
|
38
|
+
sendEffort: sendReasoningEffort,
|
|
39
|
+
acceptedEfforts: [...LOW_TO_HIGH, "xhigh"]
|
|
40
|
+
},
|
|
41
|
+
togetherai: {
|
|
42
|
+
optionsKey: "togetherai",
|
|
43
|
+
sendEffort: sendReasoningEffort,
|
|
44
|
+
acceptedEfforts: LOW_TO_HIGH,
|
|
45
|
+
enableThinking: ENABLE_REASONING
|
|
46
|
+
},
|
|
47
|
+
deepinfra: {
|
|
48
|
+
optionsKey: "deepinfra",
|
|
49
|
+
sendEffort: sendReasoningEffort,
|
|
50
|
+
acceptedEfforts: LOW_TO_HIGH,
|
|
51
|
+
enableThinking: ENABLE_REASONING
|
|
52
|
+
},
|
|
53
|
+
cerebras: {
|
|
54
|
+
optionsKey: "cerebras",
|
|
55
|
+
sendEffort: sendReasoningEffort
|
|
56
|
+
},
|
|
57
|
+
perplexity: {
|
|
58
|
+
optionsKey: "perplexity",
|
|
59
|
+
sendEffort: (effort) => ({ reasoning_effort: effort })
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const THINKING_ADAPTER_PROVIDERS = /* @__PURE__ */ new Set([
|
|
63
|
+
"anthropic",
|
|
64
|
+
"openai",
|
|
65
|
+
"google"
|
|
66
|
+
]);
|
|
67
|
+
function isThinkingAdapterProvider(provider) {
|
|
68
|
+
return THINKING_ADAPTER_PROVIDERS.has(provider);
|
|
69
|
+
}
|
|
70
|
+
const PROVIDERS_ROUTED_WITHOUT_THINKING = /* @__PURE__ */ new Set([
|
|
71
|
+
"github-copilot",
|
|
72
|
+
"kimi-for-coding",
|
|
73
|
+
"moonshotai",
|
|
74
|
+
"amazon-bedrock"
|
|
75
|
+
]);
|
|
76
|
+
function isRoutedWithoutThinking(modelId) {
|
|
77
|
+
const [provider = ""] = stripMastraGatewayPrefix(modelId).split("/");
|
|
78
|
+
return PROVIDERS_ROUTED_WITHOUT_THINKING.has(provider);
|
|
79
|
+
}
|
|
80
|
+
function thinkingRequestFormatFor(modelId) {
|
|
81
|
+
const routedThroughMastraGateway = modelId.startsWith(MASTRA_GATEWAY_PREFIX);
|
|
82
|
+
const [provider = ""] = stripMastraGatewayPrefix(modelId).split("/");
|
|
83
|
+
if (isThinkingAdapterProvider(provider)) return void 0;
|
|
84
|
+
if (routedThroughMastraGateway) return OPENROUTER_FORMAT;
|
|
85
|
+
return REQUEST_FORMATS_BY_PROVIDER[provider.includes("alibaba") ? "alibaba" : provider];
|
|
86
|
+
}
|
|
87
|
+
export { isRoutedWithoutThinking, isThinkingAdapterProvider, thinkingRequestFormatFor };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xAI (Grok) OAuth Provider
|
|
3
|
+
*
|
|
4
|
+
* Uses OAuth tokens from AuthStorage to authenticate with the xAI API.
|
|
5
|
+
* The xAI API speaks an OpenAI-compatible chat format, and the OAuth access
|
|
6
|
+
* token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`
|
|
7
|
+
* into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)
|
|
8
|
+
* access token.
|
|
9
|
+
*/
|
|
10
|
+
import type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
|
|
11
|
+
import { AuthStorage } from '../auth/storage.js';
|
|
12
|
+
import type { CredentialStore } from '../auth/types.js';
|
|
13
|
+
/** Get or create the shared AuthStorage instance. */
|
|
14
|
+
export declare function getAuthStorage(): AuthStorage;
|
|
15
|
+
/** Set a custom AuthStorage instance (useful for tests / TUI integration). */
|
|
16
|
+
export declare function setAuthStorage(storage: AuthStorage | undefined): void;
|
|
17
|
+
/**
|
|
18
|
+
* Build a fetch wrapper that authenticates with xAI OAuth.
|
|
19
|
+
* Injects the access token (auto-refreshed by AuthStorage) as a bearer token,
|
|
20
|
+
* preserving non-auth headers from the caller.
|
|
21
|
+
*/
|
|
22
|
+
export declare function buildXAIOAuthFetch(opts?: {
|
|
23
|
+
authStorage?: CredentialStore;
|
|
24
|
+
}): typeof fetch;
|
|
25
|
+
/**
|
|
26
|
+
* Creates an xAI model using OAuth authentication.
|
|
27
|
+
* Uses OAuth tokens from AuthStorage (auto-refreshes when needed).
|
|
28
|
+
*/
|
|
29
|
+
export declare function xaiProvider(modelId: string, options?: {
|
|
30
|
+
headers?: Record<string, string>;
|
|
31
|
+
authStorage?: CredentialStore;
|
|
32
|
+
}): ReturnType<OpenAICompatibleProvider['chatModel']>;
|
|
33
|
+
//# sourceMappingURL=xai.d.ts.map
|