@mastra/code-sdk 0.0.0-client-tool-results-20260912062135
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 +37 -0
- package/dist/acp/agent.d.ts +35 -0
- package/dist/acp/agent.d.ts.map +1 -0
- package/dist/acp/agent.js +161 -0
- package/dist/acp/agent.js.map +1 -0
- package/dist/acp/event-mapper.d.ts +22 -0
- package/dist/acp/event-mapper.d.ts.map +1 -0
- package/dist/acp/event-mapper.js +214 -0
- package/dist/acp/event-mapper.js.map +1 -0
- package/dist/acp/index.d.ts +8 -0
- package/dist/acp/index.d.ts.map +1 -0
- package/dist/acp/index.js +65 -0
- package/dist/acp/index.js.map +1 -0
- package/dist/acp/server.d.ts +7 -0
- package/dist/acp/server.d.ts.map +1 -0
- package/dist/acp/server.js +35 -0
- package/dist/acp/server.js.map +1 -0
- package/dist/acp.d.ts +2 -0
- package/dist/acp.d.ts.map +1 -0
- package/dist/acp.js +2 -0
- package/dist/agents/context-audit.d.ts +84 -0
- package/dist/agents/context-audit.d.ts.map +1 -0
- package/dist/agents/context-audit.js +118 -0
- package/dist/agents/context-audit.js.map +1 -0
- package/dist/agents/credential-resolver.d.ts +63 -0
- package/dist/agents/credential-resolver.d.ts.map +1 -0
- package/dist/agents/credential-resolver.js +97 -0
- package/dist/agents/credential-resolver.js.map +1 -0
- package/dist/agents/custom-provider-source.d.ts +35 -0
- package/dist/agents/custom-provider-source.d.ts.map +1 -0
- package/dist/agents/custom-provider-source.js +25 -0
- package/dist/agents/custom-provider-source.js.map +1 -0
- package/dist/agents/instructions.d.ts +29 -0
- package/dist/agents/instructions.d.ts.map +1 -0
- package/dist/agents/instructions.js +58 -0
- package/dist/agents/instructions.js.map +1 -0
- package/dist/agents/mastracode-gateway.d.ts +74 -0
- package/dist/agents/mastracode-gateway.d.ts.map +1 -0
- package/dist/agents/mastracode-gateway.js +431 -0
- package/dist/agents/mastracode-gateway.js.map +1 -0
- package/dist/agents/memory.d.ts +30 -0
- package/dist/agents/memory.d.ts.map +1 -0
- package/dist/agents/memory.js +171 -0
- package/dist/agents/memory.js.map +1 -0
- package/dist/agents/model.d.ts +81 -0
- package/dist/agents/model.d.ts.map +1 -0
- package/dist/agents/model.js +155 -0
- package/dist/agents/model.js.map +1 -0
- package/dist/agents/modes/build.d.ts +10 -0
- package/dist/agents/modes/build.d.ts.map +1 -0
- package/dist/agents/modes/build.js +49 -0
- package/dist/agents/modes/build.js.map +1 -0
- package/dist/agents/modes/explore.d.ts +10 -0
- package/dist/agents/modes/explore.d.ts.map +1 -0
- package/dist/agents/modes/explore.js +42 -0
- package/dist/agents/modes/explore.js.map +1 -0
- package/dist/agents/modes/plan.d.ts +6 -0
- package/dist/agents/modes/plan.d.ts.map +1 -0
- package/dist/agents/modes/plan.js +42 -0
- package/dist/agents/modes/plan.js.map +1 -0
- package/dist/agents/prompts/agent-instructions.d.ts +70 -0
- package/dist/agents/prompts/agent-instructions.d.ts.map +1 -0
- package/dist/agents/prompts/agent-instructions.js +211 -0
- package/dist/agents/prompts/agent-instructions.js.map +1 -0
- package/dist/agents/prompts/build.d.ts +12 -0
- package/dist/agents/prompts/build.d.ts.map +1 -0
- package/dist/agents/prompts/build.js +76 -0
- package/dist/agents/prompts/build.js.map +1 -0
- package/dist/agents/prompts/fast.d.ts +5 -0
- package/dist/agents/prompts/fast.d.ts.map +1 -0
- package/dist/agents/prompts/fast.js +26 -0
- package/dist/agents/prompts/fast.js.map +1 -0
- package/dist/agents/prompts/index.d.ts +50 -0
- package/dist/agents/prompts/index.d.ts.map +1 -0
- package/dist/agents/prompts/index.js +119 -0
- package/dist/agents/prompts/index.js.map +1 -0
- package/dist/agents/prompts/model.d.ts +5 -0
- package/dist/agents/prompts/model.d.ts.map +1 -0
- package/dist/agents/prompts/model.js +23 -0
- package/dist/agents/prompts/model.js.map +1 -0
- package/dist/agents/prompts/plan.d.ts +6 -0
- package/dist/agents/prompts/plan.d.ts.map +1 -0
- package/dist/agents/prompts/plan.js +111 -0
- package/dist/agents/prompts/plan.js.map +1 -0
- package/dist/agents/prompts/tool-guidance.d.ts +18 -0
- package/dist/agents/prompts/tool-guidance.d.ts.map +1 -0
- package/dist/agents/prompts/tool-guidance.js +180 -0
- package/dist/agents/prompts/tool-guidance.js.map +1 -0
- package/dist/agents/sandbox-filesystem.d.ts +117 -0
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -0
- package/dist/agents/sandbox-filesystem.js +356 -0
- package/dist/agents/sandbox-filesystem.js.map +1 -0
- package/dist/agents/subagents/execute.d.ts +3 -0
- package/dist/agents/subagents/execute.d.ts.map +1 -0
- package/dist/agents/subagents/execute.js +27 -0
- package/dist/agents/subagents/execute.js.map +1 -0
- package/dist/agents/subagents/explore.d.ts +3 -0
- package/dist/agents/subagents/explore.d.ts.map +1 -0
- package/dist/agents/subagents/explore.js +18 -0
- package/dist/agents/subagents/explore.js.map +1 -0
- package/dist/agents/subagents/plan.d.ts +3 -0
- package/dist/agents/subagents/plan.d.ts.map +1 -0
- package/dist/agents/subagents/plan.js +18 -0
- package/dist/agents/subagents/plan.js.map +1 -0
- package/dist/agents/thread-caveman-state.d.ts +17 -0
- package/dist/agents/thread-caveman-state.d.ts.map +1 -0
- package/dist/agents/thread-caveman-state.js +107 -0
- package/dist/agents/thread-caveman-state.js.map +1 -0
- package/dist/agents/tool-availability.d.ts +10 -0
- package/dist/agents/tool-availability.d.ts.map +1 -0
- package/dist/agents/tool-availability.js +96 -0
- package/dist/agents/tool-availability.js.map +1 -0
- package/dist/agents/tools.d.ts +36 -0
- package/dist/agents/tools.d.ts.map +1 -0
- package/dist/agents/tools.js +117 -0
- package/dist/agents/tools.js.map +1 -0
- package/dist/agents/workflow-builder-agent.d.ts +2 -0
- package/dist/agents/workflow-builder-agent.d.ts.map +1 -0
- package/dist/agents/workflow-builder-agent.js +80 -0
- package/dist/agents/workflow-builder-agent.js.map +1 -0
- package/dist/agents/workspace.d.ts +32 -0
- package/dist/agents/workspace.d.ts.map +1 -0
- package/dist/agents/workspace.js +208 -0
- package/dist/agents/workspace.js.map +1 -0
- package/dist/analytics.d.ts +18 -0
- package/dist/analytics.d.ts.map +1 -0
- package/dist/analytics.js +163 -0
- package/dist/analytics.js.map +1 -0
- package/dist/auth/authorization-input.d.ts +16 -0
- package/dist/auth/authorization-input.d.ts.map +1 -0
- package/dist/auth/authorization-input.js +42 -0
- package/dist/auth/authorization-input.js.map +1 -0
- package/dist/auth/device-code.d.ts +93 -0
- package/dist/auth/device-code.d.ts.map +1 -0
- package/dist/auth/device-code.js +129 -0
- package/dist/auth/device-code.js.map +1 -0
- package/dist/auth/index.d.ts +12 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +8 -0
- package/dist/auth/pkce.d.ts +13 -0
- package/dist/auth/pkce.d.ts.map +1 -0
- package/dist/auth/pkce.js +32 -0
- package/dist/auth/pkce.js.map +1 -0
- package/dist/auth/provider-auth-error.d.ts +12 -0
- package/dist/auth/provider-auth-error.d.ts.map +1 -0
- package/dist/auth/provider-auth-error.js +16 -0
- package/dist/auth/provider-auth-error.js.map +1 -0
- package/dist/auth/providers/anthropic.d.ts +40 -0
- package/dist/auth/providers/anthropic.d.ts.map +1 -0
- package/dist/auth/providers/anthropic.js +126 -0
- package/dist/auth/providers/anthropic.js.map +1 -0
- package/dist/auth/providers/github-copilot.d.ts +154 -0
- package/dist/auth/providers/github-copilot.d.ts.map +1 -0
- package/dist/auth/providers/github-copilot.js +340 -0
- package/dist/auth/providers/github-copilot.js.map +1 -0
- package/dist/auth/providers/kimi-coding.d.ts +38 -0
- package/dist/auth/providers/kimi-coding.d.ts.map +1 -0
- package/dist/auth/providers/kimi-coding.js +232 -0
- package/dist/auth/providers/kimi-coding.js.map +1 -0
- package/dist/auth/providers/openai-codex.d.ts +139 -0
- package/dist/auth/providers/openai-codex.d.ts.map +1 -0
- package/dist/auth/providers/openai-codex.js +519 -0
- package/dist/auth/providers/openai-codex.js.map +1 -0
- package/dist/auth/providers/xai.d.ts +64 -0
- package/dist/auth/providers/xai.d.ts.map +1 -0
- package/dist/auth/providers/xai.js +205 -0
- package/dist/auth/providers/xai.js.map +1 -0
- package/dist/auth/storage.d.ts +92 -0
- package/dist/auth/storage.d.ts.map +1 -0
- package/dist/auth/storage.js +211 -0
- package/dist/auth/storage.js.map +1 -0
- package/dist/auth/types.d.ts +89 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +1 -0
- package/dist/clipboard/index.d.ts +26 -0
- package/dist/clipboard/index.d.ts.map +1 -0
- package/dist/clipboard/index.js +226 -0
- package/dist/clipboard/index.js.map +1 -0
- package/dist/constants.d.ts +10 -0
- package/dist/constants.d.ts.map +1 -0
- package/dist/constants.js +18 -0
- package/dist/constants.js.map +1 -0
- package/dist/error-classification.d.ts +10 -0
- package/dist/error-classification.d.ts.map +1 -0
- package/dist/error-classification.js +22 -0
- package/dist/error-classification.js.map +1 -0
- package/dist/evals/context-builder.d.ts +41 -0
- package/dist/evals/context-builder.d.ts.map +1 -0
- package/dist/evals/context-builder.js +161 -0
- package/dist/evals/context-builder.js.map +1 -0
- package/dist/evals/index.d.ts +4 -0
- package/dist/evals/index.d.ts.map +1 -0
- package/dist/evals/index.js +5 -0
- package/dist/evals/scorers/classify-command.d.ts +31 -0
- package/dist/evals/scorers/classify-command.d.ts.map +1 -0
- package/dist/evals/scorers/classify-command.js +73 -0
- package/dist/evals/scorers/classify-command.js.map +1 -0
- package/dist/evals/scorers/efficiency.d.ts +44 -0
- package/dist/evals/scorers/efficiency.d.ts.map +1 -0
- package/dist/evals/scorers/efficiency.js +259 -0
- package/dist/evals/scorers/efficiency.js.map +1 -0
- package/dist/evals/scorers/extract-tools.d.ts +25 -0
- package/dist/evals/scorers/extract-tools.d.ts.map +1 -0
- package/dist/evals/scorers/extract-tools.js +60 -0
- package/dist/evals/scorers/extract-tools.js.map +1 -0
- package/dist/evals/scorers/index.d.ts +3 -0
- package/dist/evals/scorers/index.d.ts.map +1 -0
- package/dist/evals/scorers/index.js +3 -0
- package/dist/evals/scorers/outcome.d.ts +49 -0
- package/dist/evals/scorers/outcome.d.ts.map +1 -0
- package/dist/evals/scorers/outcome.js +347 -0
- package/dist/evals/scorers/outcome.js.map +1 -0
- package/dist/goal-manager.d.ts +78 -0
- package/dist/goal-manager.d.ts.map +1 -0
- package/dist/goal-manager.js +273 -0
- package/dist/goal-manager.js.map +1 -0
- package/dist/goal-signal.d.ts +14 -0
- package/dist/goal-signal.d.ts.map +1 -0
- package/dist/goal-signal.js +17 -0
- package/dist/goal-signal.js.map +1 -0
- package/dist/headless/cli.d.ts +42 -0
- package/dist/headless/cli.d.ts.map +1 -0
- package/dist/headless/cli.js +209 -0
- package/dist/headless/cli.js.map +1 -0
- package/dist/headless/flags.d.ts +33 -0
- package/dist/headless/flags.d.ts.map +1 -0
- package/dist/headless/flags.js +190 -0
- package/dist/headless/flags.js.map +1 -0
- package/dist/headless/format.d.ts +38 -0
- package/dist/headless/format.d.ts.map +1 -0
- package/dist/headless/format.js +89 -0
- package/dist/headless/format.js.map +1 -0
- package/dist/headless/index.d.ts +25 -0
- package/dist/headless/index.d.ts.map +1 -0
- package/dist/headless/index.js +6 -0
- package/dist/headless/policy.d.ts +17 -0
- package/dist/headless/policy.d.ts.map +1 -0
- package/dist/headless/policy.js +42 -0
- package/dist/headless/policy.js.map +1 -0
- package/dist/headless/run-mc.d.ts +7 -0
- package/dist/headless/run-mc.d.ts.map +1 -0
- package/dist/headless/run-mc.js +346 -0
- package/dist/headless/run-mc.js.map +1 -0
- package/dist/headless/types.d.ts +158 -0
- package/dist/headless/types.d.ts.map +1 -0
- package/dist/headless/types.js +19 -0
- package/dist/headless/types.js.map +1 -0
- package/dist/hooks/config.d.ts +11 -0
- package/dist/hooks/config.d.ts.map +1 -0
- package/dist/hooks/config.js +73 -0
- package/dist/hooks/config.js.map +1 -0
- package/dist/hooks/executor.d.ts +13 -0
- package/dist/hooks/executor.d.ts.map +1 -0
- package/dist/hooks/executor.js +129 -0
- package/dist/hooks/executor.js.map +1 -0
- package/dist/hooks/index.d.ts +6 -0
- package/dist/hooks/index.d.ts.map +1 -0
- package/dist/hooks/index.js +5 -0
- package/dist/hooks/manager.d.ts +54 -0
- package/dist/hooks/manager.d.ts.map +1 -0
- package/dist/hooks/manager.js +241 -0
- package/dist/hooks/manager.js.map +1 -0
- package/dist/hooks/types.d.ts +172 -0
- package/dist/hooks/types.d.ts.map +1 -0
- package/dist/hooks/types.js +8 -0
- package/dist/hooks/types.js.map +1 -0
- package/dist/index.d.ts +341 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +919 -0
- package/dist/index.js.map +1 -0
- package/dist/ipc/ipc-reporter.d.ts +14 -0
- package/dist/ipc/ipc-reporter.d.ts.map +1 -0
- package/dist/ipc/ipc-reporter.js +21 -0
- package/dist/ipc/ipc-reporter.js.map +1 -0
- package/dist/knowledge-inspector.d.ts +119 -0
- package/dist/knowledge-inspector.d.ts.map +1 -0
- package/dist/knowledge-inspector.js +508 -0
- package/dist/knowledge-inspector.js.map +1 -0
- package/dist/knowledge-scope.d.ts +35 -0
- package/dist/knowledge-scope.d.ts.map +1 -0
- package/dist/knowledge-scope.js +47 -0
- package/dist/knowledge-scope.js.map +1 -0
- package/dist/lsp/client.d.ts +56 -0
- package/dist/lsp/client.d.ts.map +1 -0
- package/dist/lsp/client.js +251 -0
- package/dist/lsp/client.js.map +1 -0
- package/dist/lsp/index.d.ts +4 -0
- package/dist/lsp/index.d.ts.map +1 -0
- package/dist/lsp/index.js +4 -0
- package/dist/lsp/language.d.ts +9 -0
- package/dist/lsp/language.d.ts.map +1 -0
- package/dist/lsp/language.js +44 -0
- package/dist/lsp/language.js.map +1 -0
- package/dist/lsp/manager.d.ts +34 -0
- package/dist/lsp/manager.d.ts.map +1 -0
- package/dist/lsp/manager.js +82 -0
- package/dist/lsp/manager.js.map +1 -0
- package/dist/lsp/server.d.ts +27 -0
- package/dist/lsp/server.d.ts.map +1 -0
- package/dist/lsp/server.js +159 -0
- package/dist/lsp/server.js.map +1 -0
- package/dist/lsp/workspace.d.ts +9 -0
- package/dist/lsp/workspace.d.ts.map +1 -0
- package/dist/lsp/workspace.js +55 -0
- package/dist/lsp/workspace.js.map +1 -0
- package/dist/mcp/config.d.ts +62 -0
- package/dist/mcp/config.d.ts.map +1 -0
- package/dist/mcp/config.js +301 -0
- package/dist/mcp/config.js.map +1 -0
- package/dist/mcp/index.d.ts +6 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +3 -0
- package/dist/mcp/manager.d.ts +101 -0
- package/dist/mcp/manager.d.ts.map +1 -0
- package/dist/mcp/manager.js +644 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/state.d.ts +35 -0
- package/dist/mcp/state.d.ts.map +1 -0
- package/dist/mcp/state.js +97 -0
- package/dist/mcp/state.js.map +1 -0
- package/dist/mcp/types.d.ts +125 -0
- package/dist/mcp/types.d.ts.map +1 -0
- package/dist/mcp/types.js +1 -0
- package/dist/onboarding/custom-packs.d.ts +7 -0
- package/dist/onboarding/custom-packs.d.ts.map +1 -0
- package/dist/onboarding/custom-packs.js +17 -0
- package/dist/onboarding/custom-packs.js.map +1 -0
- package/dist/onboarding/custom-providers.d.ts +4 -0
- package/dist/onboarding/custom-providers.d.ts.map +1 -0
- package/dist/onboarding/custom-providers.js +30 -0
- package/dist/onboarding/custom-providers.js.map +1 -0
- package/dist/onboarding/index.d.ts +5 -0
- package/dist/onboarding/index.d.ts.map +1 -0
- package/dist/onboarding/index.js +3 -0
- package/dist/onboarding/om-settings.d.ts +25 -0
- package/dist/onboarding/om-settings.d.ts.map +1 -0
- package/dist/onboarding/om-settings.js +47 -0
- package/dist/onboarding/om-settings.js.map +1 -0
- package/dist/onboarding/packs.d.ts +49 -0
- package/dist/onboarding/packs.d.ts.map +1 -0
- package/dist/onboarding/packs.js +182 -0
- package/dist/onboarding/packs.js.map +1 -0
- package/dist/onboarding/settings.d.ts +438 -0
- package/dist/onboarding/settings.d.ts.map +1 -0
- package/dist/onboarding/settings.js +847 -0
- package/dist/onboarding/settings.js.map +1 -0
- package/dist/permissions.d.ts +55 -0
- package/dist/permissions.d.ts.map +1 -0
- package/dist/permissions.js +137 -0
- package/dist/permissions.js.map +1 -0
- package/dist/plugin.d.ts +144 -0
- package/dist/plugin.d.ts.map +1 -0
- package/dist/plugin.js +30 -0
- package/dist/plugin.js.map +1 -0
- package/dist/plugins/dependencies.d.ts +9 -0
- package/dist/plugins/dependencies.d.ts.map +1 -0
- package/dist/plugins/dependencies.js +88 -0
- package/dist/plugins/dependencies.js.map +1 -0
- package/dist/plugins/install.d.ts +21 -0
- package/dist/plugins/install.d.ts.map +1 -0
- package/dist/plugins/install.js +190 -0
- package/dist/plugins/install.js.map +1 -0
- package/dist/plugins/loader.d.ts +19 -0
- package/dist/plugins/loader.d.ts.map +1 -0
- package/dist/plugins/loader.js +258 -0
- package/dist/plugins/loader.js.map +1 -0
- package/dist/plugins/manager.d.ts +98 -0
- package/dist/plugins/manager.d.ts.map +1 -0
- package/dist/plugins/manager.js +456 -0
- package/dist/plugins/manager.js.map +1 -0
- package/dist/plugins/manifest.d.ts +14 -0
- package/dist/plugins/manifest.d.ts.map +1 -0
- package/dist/plugins/manifest.js +50 -0
- package/dist/plugins/manifest.js.map +1 -0
- package/dist/plugins/package-link.d.ts +3 -0
- package/dist/plugins/package-link.d.ts.map +1 -0
- package/dist/plugins/package-link.js +61 -0
- package/dist/plugins/package-link.js.map +1 -0
- package/dist/plugins/paths.d.ts +10 -0
- package/dist/plugins/paths.d.ts.map +1 -0
- package/dist/plugins/paths.js +25 -0
- package/dist/plugins/paths.js.map +1 -0
- package/dist/plugins/registry.d.ts +8 -0
- package/dist/plugins/registry.d.ts.map +1 -0
- package/dist/plugins/registry.js +112 -0
- package/dist/plugins/registry.js.map +1 -0
- package/dist/plugins/scaffold.d.ts +10 -0
- package/dist/plugins/scaffold.d.ts.map +1 -0
- package/dist/plugins/scaffold.js +116 -0
- package/dist/plugins/scaffold.js.map +1 -0
- package/dist/plugins/signal-lane.d.ts +58 -0
- package/dist/plugins/signal-lane.d.ts.map +1 -0
- package/dist/plugins/signal-lane.js +166 -0
- package/dist/plugins/signal-lane.js.map +1 -0
- package/dist/plugins/types.d.ts +81 -0
- package/dist/plugins/types.d.ts.map +1 -0
- package/dist/plugins/types.js +1 -0
- package/dist/process-memory-diagnostics.d.ts +135 -0
- package/dist/process-memory-diagnostics.d.ts.map +1 -0
- package/dist/process-memory-diagnostics.js +500 -0
- package/dist/process-memory-diagnostics.js.map +1 -0
- package/dist/processors/plan-rejection-abort.d.ts +12 -0
- package/dist/processors/plan-rejection-abort.d.ts.map +1 -0
- package/dist/processors/plan-rejection-abort.js +54 -0
- package/dist/processors/plan-rejection-abort.js.map +1 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts +47 -0
- package/dist/providers/amazon-bedrock-gateway.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock-gateway.js +153 -0
- package/dist/providers/amazon-bedrock-gateway.js.map +1 -0
- package/dist/providers/amazon-bedrock.d.ts +28 -0
- package/dist/providers/amazon-bedrock.d.ts.map +1 -0
- package/dist/providers/amazon-bedrock.js +102 -0
- package/dist/providers/amazon-bedrock.js.map +1 -0
- package/dist/providers/claude-max.d.ts +65 -0
- package/dist/providers/claude-max.d.ts.map +1 -0
- package/dist/providers/claude-max.js +252 -0
- package/dist/providers/claude-max.js.map +1 -0
- package/dist/providers/github-copilot.d.ts +60 -0
- package/dist/providers/github-copilot.d.ts.map +1 -0
- package/dist/providers/github-copilot.js +266 -0
- package/dist/providers/github-copilot.js.map +1 -0
- package/dist/providers/kimi-coding.d.ts +15 -0
- package/dist/providers/kimi-coding.d.ts.map +1 -0
- package/dist/providers/kimi-coding.js +69 -0
- package/dist/providers/kimi-coding.js.map +1 -0
- package/dist/providers/openai-codex.d.ts +73 -0
- package/dist/providers/openai-codex.d.ts.map +1 -0
- package/dist/providers/openai-codex.js +306 -0
- package/dist/providers/openai-codex.js.map +1 -0
- package/dist/providers/xai.d.ts +33 -0
- package/dist/providers/xai.d.ts.map +1 -0
- package/dist/providers/xai.js +71 -0
- package/dist/providers/xai.js.map +1 -0
- package/dist/schema.d.ts +200 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +92 -0
- package/dist/schema.js.map +1 -0
- package/dist/theme-palette.d.ts +17 -0
- package/dist/theme-palette.d.ts.map +1 -0
- package/dist/theme-palette.js +21 -0
- package/dist/theme-palette.js.map +1 -0
- package/dist/thinking.d.ts +33 -0
- package/dist/thinking.d.ts.map +1 -0
- package/dist/thinking.js +58 -0
- package/dist/thinking.js.map +1 -0
- package/dist/tool-names.d.ts +73 -0
- package/dist/tool-names.d.ts.map +1 -0
- package/dist/tool-names.js +52 -0
- package/dist/tool-names.js.map +1 -0
- package/dist/tools/index.d.ts +6 -0
- package/dist/tools/index.d.ts.map +1 -0
- package/dist/tools/index.js +3 -0
- package/dist/tools/request-sandbox-access.d.ts +6 -0
- package/dist/tools/request-sandbox-access.d.ts.map +1 -0
- package/dist/tools/request-sandbox-access.js +79 -0
- package/dist/tools/request-sandbox-access.js.map +1 -0
- package/dist/tools/utils.d.ts +20 -0
- package/dist/tools/utils.d.ts.map +1 -0
- package/dist/tools/utils.js +32 -0
- package/dist/tools/utils.js.map +1 -0
- package/dist/tools/web-search.d.ts +114 -0
- package/dist/tools/web-search.d.ts.map +1 -0
- package/dist/tools/web-search.js +155 -0
- package/dist/tools/web-search.js.map +1 -0
- package/dist/tools/workflows/create-workflow.d.ts +7 -0
- package/dist/tools/workflows/create-workflow.d.ts.map +1 -0
- package/dist/tools/workflows/create-workflow.js +81 -0
- package/dist/tools/workflows/create-workflow.js.map +1 -0
- package/dist/tools/workflows/delete-workflow.d.ts +7 -0
- package/dist/tools/workflows/delete-workflow.d.ts.map +1 -0
- package/dist/tools/workflows/delete-workflow.js +21 -0
- package/dist/tools/workflows/delete-workflow.js.map +1 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts +7 -0
- package/dist/tools/workflows/ephemeral-memory.d.ts.map +1 -0
- package/dist/tools/workflows/ephemeral-memory.js +45 -0
- package/dist/tools/workflows/ephemeral-memory.js.map +1 -0
- package/dist/tools/workflows/extract-json-schema.d.ts +12 -0
- package/dist/tools/workflows/extract-json-schema.d.ts.map +1 -0
- package/dist/tools/workflows/extract-json-schema.js +22 -0
- package/dist/tools/workflows/extract-json-schema.js.map +1 -0
- package/dist/tools/workflows/get-workflow.d.ts +11 -0
- package/dist/tools/workflows/get-workflow.d.ts.map +1 -0
- package/dist/tools/workflows/get-workflow.js +34 -0
- package/dist/tools/workflows/get-workflow.js.map +1 -0
- package/dist/tools/workflows/list-available-agents.d.ts +8 -0
- package/dist/tools/workflows/list-available-agents.d.ts.map +1 -0
- package/dist/tools/workflows/list-available-agents.js +32 -0
- package/dist/tools/workflows/list-available-agents.js.map +1 -0
- package/dist/tools/workflows/list-available-tools.d.ts +9 -0
- package/dist/tools/workflows/list-available-tools.d.ts.map +1 -0
- package/dist/tools/workflows/list-available-tools.js +40 -0
- package/dist/tools/workflows/list-available-tools.js.map +1 -0
- package/dist/tools/workflows/list-available-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-available-workflows.d.ts.map +1 -0
- package/dist/tools/workflows/list-available-workflows.js +32 -0
- package/dist/tools/workflows/list-available-workflows.js.map +1 -0
- package/dist/tools/workflows/list-workflows.d.ts +9 -0
- package/dist/tools/workflows/list-workflows.d.ts.map +1 -0
- package/dist/tools/workflows/list-workflows.js +33 -0
- package/dist/tools/workflows/list-workflows.js.map +1 -0
- package/dist/tools/workflows/run-workflow.d.ts +9 -0
- package/dist/tools/workflows/run-workflow.d.ts.map +1 -0
- package/dist/tools/workflows/run-workflow.js +52 -0
- package/dist/tools/workflows/run-workflow.js.map +1 -0
- package/dist/tools/workflows/save-workflow.d.ts +1015 -0
- package/dist/tools/workflows/save-workflow.d.ts.map +1 -0
- package/dist/tools/workflows/save-workflow.js +28 -0
- package/dist/tools/workflows/save-workflow.js.map +1 -0
- package/dist/tools/workflows/tool-ids.d.ts +15 -0
- package/dist/tools/workflows/tool-ids.d.ts.map +1 -0
- package/dist/tools/workflows/tool-ids.js +19 -0
- package/dist/tools/workflows/tool-ids.js.map +1 -0
- package/dist/utils/binaries.d.ts +7 -0
- package/dist/utils/binaries.d.ts.map +1 -0
- package/dist/utils/binaries.js +78 -0
- package/dist/utils/binaries.js.map +1 -0
- package/dist/utils/debug-log.d.ts +12 -0
- package/dist/utils/debug-log.d.ts.map +1 -0
- package/dist/utils/debug-log.js +59 -0
- package/dist/utils/debug-log.js.map +1 -0
- package/dist/utils/errors.d.ts +36 -0
- package/dist/utils/errors.d.ts.map +1 -0
- package/dist/utils/errors.js +196 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/gateway-sync.d.ts +26 -0
- package/dist/utils/gateway-sync.d.ts.map +1 -0
- package/dist/utils/gateway-sync.js +61 -0
- package/dist/utils/gateway-sync.js.map +1 -0
- package/dist/utils/path-security.d.ts +2 -0
- package/dist/utils/path-security.d.ts.map +1 -0
- package/dist/utils/path-security.js +10 -0
- package/dist/utils/path-security.js.map +1 -0
- package/dist/utils/plan-diff.d.ts +25 -0
- package/dist/utils/plan-diff.d.ts.map +1 -0
- package/dist/utils/plan-diff.js +62 -0
- package/dist/utils/plan-diff.js.map +1 -0
- package/dist/utils/plans.d.ts +59 -0
- package/dist/utils/plans.d.ts.map +1 -0
- package/dist/utils/plans.js +117 -0
- package/dist/utils/plans.js.map +1 -0
- package/dist/utils/project.d.ts +160 -0
- package/dist/utils/project.d.ts.map +1 -0
- package/dist/utils/project.js +364 -0
- package/dist/utils/project.js.map +1 -0
- package/dist/utils/signals-pubsub.d.ts +41 -0
- package/dist/utils/signals-pubsub.d.ts.map +1 -0
- package/dist/utils/signals-pubsub.js +122 -0
- package/dist/utils/signals-pubsub.js.map +1 -0
- package/dist/utils/slash-command-loader.d.ts +52 -0
- package/dist/utils/slash-command-loader.d.ts.map +1 -0
- package/dist/utils/slash-command-loader.js +142 -0
- package/dist/utils/slash-command-loader.js.map +1 -0
- package/dist/utils/slash-command-processor.d.ts +14 -0
- package/dist/utils/slash-command-processor.d.ts.map +1 -0
- package/dist/utils/slash-command-processor.js +109 -0
- package/dist/utils/slash-command-processor.js.map +1 -0
- package/dist/utils/stdin-pipe.d.ts +33 -0
- package/dist/utils/stdin-pipe.d.ts.map +1 -0
- package/dist/utils/stdin-pipe.js +96 -0
- package/dist/utils/stdin-pipe.js.map +1 -0
- package/dist/utils/storage-factory.d.ts +50 -0
- package/dist/utils/storage-factory.d.ts.map +1 -0
- package/dist/utils/storage-factory.js +121 -0
- package/dist/utils/storage-factory.js.map +1 -0
- package/dist/utils/storage-maintenance.d.ts +103 -0
- package/dist/utils/storage-maintenance.d.ts.map +1 -0
- package/dist/utils/storage-maintenance.js +274 -0
- package/dist/utils/storage-maintenance.js.map +1 -0
- package/dist/utils/thread-lock.d.ts +26 -0
- package/dist/utils/thread-lock.d.ts.map +1 -0
- package/dist/utils/thread-lock.js +112 -0
- package/dist/utils/thread-lock.js.map +1 -0
- package/dist/utils/token-estimator.d.ts +3 -0
- package/dist/utils/token-estimator.d.ts.map +1 -0
- package/dist/utils/token-estimator.js +21 -0
- package/dist/utils/token-estimator.js.map +1 -0
- package/dist/utils/update-check.d.ts +101 -0
- package/dist/utils/update-check.d.ts.map +1 -0
- package/dist/utils/update-check.js +383 -0
- package/dist/utils/update-check.js.map +1 -0
- package/dist/voice/stt-registry.d.ts +64 -0
- package/dist/voice/stt-registry.d.ts.map +1 -0
- package/dist/voice/stt-registry.js +144 -0
- package/dist/voice/stt-registry.js.map +1 -0
- package/dist/workflows/register-primitives.d.ts +52 -0
- package/dist/workflows/register-primitives.d.ts.map +1 -0
- package/dist/workflows/register-primitives.js +40 -0
- package/dist/workflows/register-primitives.js.map +1 -0
- package/dist/workflows/service.d.ts +64 -0
- package/dist/workflows/service.d.ts.map +1 -0
- package/dist/workflows/service.js +53 -0
- package/dist/workflows/service.js.map +1 -0
- package/package.json +97 -0
|
@@ -0,0 +1,15 @@
|
|
|
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 const KIMI_CODING_MODELS: readonly ["k3", "k3-256k", "kimi-for-coding", "kimi-for-coding-highspeed"];
|
|
5
|
+
export declare function setAuthStorage(storage: AuthStorage | undefined): void;
|
|
6
|
+
export declare function buildKimiCodingOAuthFetch(options?: {
|
|
7
|
+
credentialStore?: CredentialStore;
|
|
8
|
+
}): typeof fetch;
|
|
9
|
+
export declare function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch;
|
|
10
|
+
export declare function kimiCodingProvider(modelId: string, options: {
|
|
11
|
+
apiKey: string;
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
credentialStore?: CredentialStore;
|
|
14
|
+
}): MastraModelConfig;
|
|
15
|
+
//# sourceMappingURL=kimi-coding.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kimi-coding.d.ts","sourceRoot":"","sources":["../../src/providers/kimi-coding.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAG1D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAOxD,eAAO,MAAM,kBAAkB,4EAA6E,CAAC;AAI7G,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAOD,wBAAgB,yBAAyB,CAAC,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAuB3G;AAED,wBAAgB,0BAA0B,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,KAAK,CASvE;AAED,wBAAgB,kBAAkB,CAChC,OAAO,EAAE,MAAM,EACf,OAAO,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,eAAe,CAAC,EAAE,eAAe,CAAA;CAAE,GAC/F,iBAAiB,CAWnB"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from "../auth/providers/kimi-coding.js";
|
|
2
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
3
|
+
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
4
|
+
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
5
|
+
//#region src/providers/kimi-coding.ts
|
|
6
|
+
const PROVIDER_ID = "kimi-for-coding";
|
|
7
|
+
const BASE_URL = "https://api.kimi.com/coding/v1";
|
|
8
|
+
const KIMI_CODING_MODELS = [
|
|
9
|
+
"k3",
|
|
10
|
+
"k3-256k",
|
|
11
|
+
"kimi-for-coding",
|
|
12
|
+
"kimi-for-coding-highspeed"
|
|
13
|
+
];
|
|
14
|
+
let authStorageInstance = null;
|
|
15
|
+
function setAuthStorage(storage) {
|
|
16
|
+
authStorageInstance = storage ?? null;
|
|
17
|
+
}
|
|
18
|
+
function getAuthStorage() {
|
|
19
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
20
|
+
return authStorageInstance;
|
|
21
|
+
}
|
|
22
|
+
function buildKimiCodingOAuthFetch(options = {}) {
|
|
23
|
+
return (async (input, init) => {
|
|
24
|
+
const store = options.credentialStore ?? getAuthStorage();
|
|
25
|
+
store.reload();
|
|
26
|
+
const credential = store.get(PROVIDER_ID);
|
|
27
|
+
if (!credential || credential.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to Kimi For Coding.");
|
|
28
|
+
if (!isKimiCodingDeviceId(credential.deviceId)) throw new ProviderAuthRequiredError("Kimi For Coding credentials are invalid. Please reconnect the account.");
|
|
29
|
+
const deviceHeaders = getKimiCodingDeviceHeaders(credential.deviceId);
|
|
30
|
+
const token = await store.getApiKey(PROVIDER_ID);
|
|
31
|
+
if (!token) throw new ProviderAuthRequiredError("Failed to refresh the Kimi For Coding token.");
|
|
32
|
+
const headers = new Headers(input instanceof Request ? input.headers : void 0);
|
|
33
|
+
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
34
|
+
for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);
|
|
35
|
+
headers.delete("authorization");
|
|
36
|
+
headers.delete("x-api-key");
|
|
37
|
+
headers.set("Authorization", `Bearer ${token}`);
|
|
38
|
+
return fetch(input, {
|
|
39
|
+
...init,
|
|
40
|
+
headers
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function buildKimiCodingApiKeyFetch(apiKey) {
|
|
45
|
+
return (async (input, init) => {
|
|
46
|
+
const headers = new Headers(input instanceof Request ? input.headers : void 0);
|
|
47
|
+
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
48
|
+
headers.delete("authorization");
|
|
49
|
+
headers.delete("x-api-key");
|
|
50
|
+
headers.set("Authorization", `Bearer ${apiKey}`);
|
|
51
|
+
return fetch(input, {
|
|
52
|
+
...init,
|
|
53
|
+
headers
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function kimiCodingProvider(modelId, options) {
|
|
58
|
+
const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === "oauth";
|
|
59
|
+
return createAnthropic({
|
|
60
|
+
apiKey: "auth-placeholder",
|
|
61
|
+
baseURL: BASE_URL,
|
|
62
|
+
headers: options.headers,
|
|
63
|
+
fetch: usesOAuth ? buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) : buildKimiCodingApiKeyFetch(options.apiKey)
|
|
64
|
+
})(modelId);
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
export { KIMI_CODING_MODELS, buildKimiCodingApiKeyFetch, buildKimiCodingOAuthFetch, kimiCodingProvider, setAuthStorage };
|
|
68
|
+
|
|
69
|
+
//# sourceMappingURL=kimi-coding.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"kimi-coding.js","names":[],"sources":["../../src/providers/kimi-coding.ts"],"sourcesContent":["import { createAnthropic } from '@ai-sdk/anthropic';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport { getKimiCodingDeviceHeaders, isKimiCodingDeviceId } from '../auth/providers/kimi-coding.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst PROVIDER_ID = 'kimi-for-coding';\n// Pi's provider root is https://api.kimi.com/coding. The AI SDK expects the\n// versioned Anthropic base URL and appends /messages itself.\nconst BASE_URL = 'https://api.kimi.com/coding/v1';\n\nexport const KIMI_CODING_MODELS = ['k3', 'k3-256k', 'kimi-for-coding', 'kimi-for-coding-highspeed'] as const;\n\nlet authStorageInstance: AuthStorage | null = null;\n\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\nfunction getAuthStorage(): AuthStorage {\n if (!authStorageInstance) authStorageInstance = new AuthStorage();\n return authStorageInstance;\n}\n\nexport function buildKimiCodingOAuthFetch(options: { credentialStore?: CredentialStore } = {}): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const store = options.credentialStore ?? getAuthStorage();\n store.reload();\n const credential = store.get(PROVIDER_ID);\n if (!credential || credential.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to Kimi For Coding.');\n }\n if (!isKimiCodingDeviceId(credential.deviceId)) {\n throw new ProviderAuthRequiredError('Kimi For Coding credentials are invalid. Please reconnect the account.');\n }\n const deviceHeaders = getKimiCodingDeviceHeaders(credential.deviceId);\n const token = await store.getApiKey(PROVIDER_ID);\n if (!token) throw new ProviderAuthRequiredError('Failed to refresh the Kimi For Coding token.');\n\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n for (const [key, value] of Object.entries(deviceHeaders)) headers.set(key, value);\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${token}`);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport function buildKimiCodingApiKeyFetch(apiKey: string): typeof fetch {\n return (async (input: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const headers = new Headers(input instanceof Request ? input.headers : undefined);\n if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${apiKey}`);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport function kimiCodingProvider(\n modelId: string,\n options: { apiKey: string; headers?: Record<string, string>; credentialStore?: CredentialStore },\n): MastraModelConfig {\n const usesOAuth = options.credentialStore?.get(PROVIDER_ID)?.type === 'oauth';\n const provider = createAnthropic({\n apiKey: 'auth-placeholder',\n baseURL: BASE_URL,\n headers: options.headers,\n fetch: usesOAuth\n ? (buildKimiCodingOAuthFetch({ credentialStore: options.credentialStore }) as any)\n : (buildKimiCodingApiKeyFetch(options.apiKey) as any),\n });\n return provider(modelId) as unknown as MastraModelConfig;\n}\n"],"mappings":";;;;;AAOA,MAAM,cAAc;AAGpB,MAAM,WAAW;AAEjB,MAAa,qBAAqB;CAAC;CAAM;CAAW;CAAmB;AAA2B;AAElG,IAAI,sBAA0C;AAE9C,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAEA,SAAS,iBAA8B;CACrC,IAAI,CAAC,qBAAqB,sBAAsB,IAAI,YAAY;CAChE,OAAO;AACT;AAEA,SAAgB,0BAA0B,UAAiD,CAAC,GAAiB;CAC3G,QAAQ,O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C1C;AACF;AAEA,SAAgB,mBACd,SACA,SACmB;CACnB,MAAM,YAAY,QAAQ,iBAAiB,IAAI,WAAW,CAAC,EAAE,SAAS;CAStE,OARiB,gBAAgB;EAC/B,QAAQ;EACR,SAAS;EACT,SAAS,QAAQ;EACjB,OAAO,YACF,0BAA0B,EAAE,iBAAiB,QAAQ,gBAAgB,CAAC,IACtE,2BAA2B,QAAQ,MAAM;CAChD,CACc,CAAC,CAAC,OAAO;AACzB"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Codex OAuth Provider
|
|
3
|
+
*
|
|
4
|
+
* Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.
|
|
5
|
+
* This allows access to OpenAI models through the ChatGPT OAuth flow.
|
|
6
|
+
*
|
|
7
|
+
* Inspired by opencode's Codex plugin implementation:
|
|
8
|
+
* https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts
|
|
9
|
+
*/
|
|
10
|
+
import type { MastraModelConfig } from '@mastra/core/llm';
|
|
11
|
+
import type { LanguageModelMiddleware } from 'ai';
|
|
12
|
+
import { AuthStorage } from '../auth/storage.js';
|
|
13
|
+
import type { CredentialStore } from '../auth/types.js';
|
|
14
|
+
import type { ThinkingLevelSetting } from '../thinking.js';
|
|
15
|
+
export { supportsMaxReasoningEffort } from '../thinking.js';
|
|
16
|
+
/**
|
|
17
|
+
* Get or create the shared AuthStorage instance
|
|
18
|
+
*/
|
|
19
|
+
export declare function getAuthStorage(): AuthStorage;
|
|
20
|
+
/**
|
|
21
|
+
* Set a custom AuthStorage instance (useful for TUI integration)
|
|
22
|
+
*/
|
|
23
|
+
export declare function setAuthStorage(storage: AuthStorage | undefined): void;
|
|
24
|
+
export type ThinkingLevel = ThinkingLevelSetting;
|
|
25
|
+
export declare function getEffectiveThinkingLevel(modelId: string, level: ThinkingLevel): ThinkingLevel;
|
|
26
|
+
export declare const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, string | undefined>;
|
|
27
|
+
/**
|
|
28
|
+
* Create Codex middleware with the given reasoning effort level.
|
|
29
|
+
*/
|
|
30
|
+
export declare function createCodexMiddleware(reasoningEffort?: string): LanguageModelMiddleware;
|
|
31
|
+
/**
|
|
32
|
+
* Build a fetch function that handles OpenAI Codex OAuth.
|
|
33
|
+
* Preserves non-authorization headers from init.
|
|
34
|
+
* When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions
|
|
35
|
+
* to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the
|
|
36
|
+
* SDK already targets the correct URL.
|
|
37
|
+
*/
|
|
38
|
+
export declare function buildOpenAICodexOAuthFetch(opts?: {
|
|
39
|
+
authStorage?: CredentialStore;
|
|
40
|
+
rewriteUrl?: boolean;
|
|
41
|
+
}): typeof fetch;
|
|
42
|
+
/**
|
|
43
|
+
* Build a fetch function for Stagehand-on-Codex.
|
|
44
|
+
*
|
|
45
|
+
* The Codex backend has two requirements that AI SDK's non-streaming
|
|
46
|
+
* `generateText` path doesn't naturally satisfy:
|
|
47
|
+
*
|
|
48
|
+
* 1. `stream: true` must be set on every request body.
|
|
49
|
+
* 2. The response is delivered as Server-Sent Events; AI SDK's
|
|
50
|
+
* non-streaming code path expects a single JSON body.
|
|
51
|
+
*
|
|
52
|
+
* This fetch forces streaming on the outgoing request, collects the SSE
|
|
53
|
+
* events, and synthesizes the non-streaming JSON shape that
|
|
54
|
+
* `@ai-sdk/openai`'s Responses API parser expects.
|
|
55
|
+
*
|
|
56
|
+
* Headers, OAuth refresh, and URL targeting are handled by the caller via
|
|
57
|
+
* `baseURL` / `headers` on the AI SDK provider; this fetch only injects the
|
|
58
|
+
* live OAuth bearer per call.
|
|
59
|
+
*/
|
|
60
|
+
export declare function buildCodexStagehandFetch(authStorage: AuthStorage): typeof fetch;
|
|
61
|
+
/**
|
|
62
|
+
* Creates an OpenAI model using ChatGPT OAuth authentication
|
|
63
|
+
* Uses OAuth tokens from AuthStorage (auto-refreshes when needed)
|
|
64
|
+
*
|
|
65
|
+
* IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.
|
|
66
|
+
* URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.
|
|
67
|
+
*/
|
|
68
|
+
export declare function openaiCodexProvider(modelId?: string, options?: {
|
|
69
|
+
thinkingLevel?: ThinkingLevel;
|
|
70
|
+
headers?: Record<string, string>;
|
|
71
|
+
authStorage?: CredentialStore;
|
|
72
|
+
}): MastraModelConfig;
|
|
73
|
+
//# sourceMappingURL=openai-codex.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-codex.d.ts","sourceRoot":"","sources":["../../src/providers/openai-codex.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,IAAI,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAExD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gBAAgB,CAAC;AAU5D;;GAEG;AACH,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAOD,MAAM,MAAM,aAAa,GAAG,oBAAoB,CAAC;AAIjD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,aAAa,GAAG,aAAa,CAY9F;AAMD,eAAO,MAAM,kCAAkC,EAAE,MAAM,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAOxF,CAAC;AAEF;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,eAAe,CAAC,EAAE,MAAM,GAAG,uBAAuB,CA4BvF;AAqCD;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAC;IAAC,UAAU,CAAC,EAAE,OAAO,CAAA;CAAO,GACjE,OAAO,KAAK,CAyDd;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,wBAAwB,CAAC,WAAW,EAAE,WAAW,GAAG,OAAO,KAAK,CAgC/E;AAwID;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,GAAE,MAA4B,EACrC,OAAO,CAAC,EAAE;IAAE,aAAa,CAAC,EAAE,aAAa,CAAC;IAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC3G,iBAAiB,CAmCnB"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
2
|
+
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
|
+
import { supportsMaxReasoningEffort } from "../thinking.js";
|
|
4
|
+
import { createOpenAI } from "@ai-sdk/openai";
|
|
5
|
+
import { wrapLanguageModel } from "ai";
|
|
6
|
+
//#region src/providers/openai-codex.ts
|
|
7
|
+
/**
|
|
8
|
+
* OpenAI Codex OAuth Provider
|
|
9
|
+
*
|
|
10
|
+
* Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.
|
|
11
|
+
* This allows access to OpenAI models through the ChatGPT OAuth flow.
|
|
12
|
+
*
|
|
13
|
+
* Inspired by opencode's Codex plugin implementation:
|
|
14
|
+
* https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts
|
|
15
|
+
*/
|
|
16
|
+
const CODEX_API_ENDPOINT = "https://chatgpt.com/backend-api/codex/responses";
|
|
17
|
+
const CODEX_ORIGINATOR = "mastracode";
|
|
18
|
+
const CODEX_USER_AGENT = "mastracode";
|
|
19
|
+
let authStorageInstance = null;
|
|
20
|
+
/**
|
|
21
|
+
* Get or create the shared AuthStorage instance
|
|
22
|
+
*/
|
|
23
|
+
function getAuthStorage() {
|
|
24
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
25
|
+
return authStorageInstance;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Set a custom AuthStorage instance (useful for TUI integration)
|
|
29
|
+
*/
|
|
30
|
+
function setAuthStorage(storage) {
|
|
31
|
+
authStorageInstance = storage ?? null;
|
|
32
|
+
}
|
|
33
|
+
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.
|
|
34
|
+
|
|
35
|
+
IMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;
|
|
36
|
+
const GPT5_MODEL_RE = /^gpt-5(?:\.|-|$)/;
|
|
37
|
+
function getEffectiveThinkingLevel(modelId, level) {
|
|
38
|
+
if (GPT5_MODEL_RE.test(modelId) && level === "off") return "low";
|
|
39
|
+
if (level === "max" && !supportsMaxReasoningEffort(modelId)) return "xhigh";
|
|
40
|
+
return level;
|
|
41
|
+
}
|
|
42
|
+
const THINKING_LEVEL_TO_REASONING_EFFORT = {
|
|
43
|
+
off: void 0,
|
|
44
|
+
low: "low",
|
|
45
|
+
medium: "medium",
|
|
46
|
+
high: "high",
|
|
47
|
+
xhigh: "xhigh",
|
|
48
|
+
max: "max"
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Create Codex middleware with the given reasoning effort level.
|
|
52
|
+
*/
|
|
53
|
+
function createCodexMiddleware(reasoningEffort) {
|
|
54
|
+
return {
|
|
55
|
+
specificationVersion: "v3",
|
|
56
|
+
transformParams: async ({ params }) => {
|
|
57
|
+
if (params.temperature !== void 0 && params.temperature !== null) delete params.topP;
|
|
58
|
+
params.providerOptions = {
|
|
59
|
+
...params.providerOptions,
|
|
60
|
+
openai: {
|
|
61
|
+
...params.providerOptions?.openai ?? {},
|
|
62
|
+
instructions: CODEX_INSTRUCTIONS,
|
|
63
|
+
store: false,
|
|
64
|
+
...reasoningEffort ? { reasoningEffort } : {}
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
return params;
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Get a live OAuth bearer token for the Codex OAuth credential.
|
|
73
|
+
*
|
|
74
|
+
* Refreshes the token if it's expired, and returns the credential's
|
|
75
|
+
* accountId alongside the access token. Throws if the user isn't logged in
|
|
76
|
+
* or if the refresh fails.
|
|
77
|
+
*
|
|
78
|
+
* This is the only piece of Codex auth that is genuinely shared between
|
|
79
|
+
* the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand
|
|
80
|
+
* fetch (`buildCodexStagehandFetch`).
|
|
81
|
+
*/
|
|
82
|
+
async function getCodexBearer(authStorage) {
|
|
83
|
+
const storage = authStorage ?? getAuthStorage();
|
|
84
|
+
storage.reload();
|
|
85
|
+
const cred = storage.get("openai-codex");
|
|
86
|
+
if (!cred || cred.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to OpenAI Codex.");
|
|
87
|
+
let accessToken = cred.access;
|
|
88
|
+
if (Date.now() >= cred.expires) {
|
|
89
|
+
const refreshedToken = await storage.getApiKey("openai-codex");
|
|
90
|
+
if (!refreshedToken) throw new ProviderAuthRequiredError("Failed to refresh the OpenAI Codex token.");
|
|
91
|
+
accessToken = refreshedToken;
|
|
92
|
+
storage.reload();
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
accessToken,
|
|
96
|
+
accountId: cred.accountId
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Build a fetch function that handles OpenAI Codex OAuth.
|
|
101
|
+
* Preserves non-authorization headers from init.
|
|
102
|
+
* When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions
|
|
103
|
+
* to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the
|
|
104
|
+
* SDK already targets the correct URL.
|
|
105
|
+
*/
|
|
106
|
+
function buildOpenAICodexOAuthFetch(opts = {}) {
|
|
107
|
+
return (async (url, init) => {
|
|
108
|
+
const { accessToken, accountId } = await getCodexBearer(opts.authStorage);
|
|
109
|
+
const headers = new Headers();
|
|
110
|
+
if (init?.headers) {
|
|
111
|
+
if (init.headers instanceof Headers) init.headers.forEach((value, key) => {
|
|
112
|
+
if (key.toLowerCase() !== "authorization") headers.set(key, value);
|
|
113
|
+
});
|
|
114
|
+
else if (Array.isArray(init.headers)) {
|
|
115
|
+
for (const [key, value] of init.headers) if (key.toLowerCase() !== "authorization" && value !== void 0) headers.set(key, String(value));
|
|
116
|
+
} else for (const [key, value] of Object.entries(init.headers)) if (key.toLowerCase() !== "authorization" && value !== void 0) headers.set(key, String(value));
|
|
117
|
+
}
|
|
118
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
119
|
+
if (!headers.has("originator")) headers.set("originator", CODEX_ORIGINATOR);
|
|
120
|
+
if (!headers.has("User-Agent")) headers.set("User-Agent", CODEX_USER_AGENT);
|
|
121
|
+
if (accountId) headers.set("ChatGPT-Account-ID", accountId);
|
|
122
|
+
const parsed = url instanceof URL ? url : new URL(typeof url === "string" ? url : url.url);
|
|
123
|
+
const finalUrl = opts.rewriteUrl !== false && (parsed.pathname.includes("/v1/responses") || parsed.pathname.includes("/chat/completions")) ? new URL(CODEX_API_ENDPOINT) : parsed;
|
|
124
|
+
try {
|
|
125
|
+
return await fetch(finalUrl, {
|
|
126
|
+
...init,
|
|
127
|
+
headers
|
|
128
|
+
});
|
|
129
|
+
} catch (error) {
|
|
130
|
+
if (error && typeof error === "object") Object.assign(error, { requestUrl: finalUrl.toString() });
|
|
131
|
+
throw error;
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
/**
|
|
136
|
+
* Build a fetch function for Stagehand-on-Codex.
|
|
137
|
+
*
|
|
138
|
+
* The Codex backend has two requirements that AI SDK's non-streaming
|
|
139
|
+
* `generateText` path doesn't naturally satisfy:
|
|
140
|
+
*
|
|
141
|
+
* 1. `stream: true` must be set on every request body.
|
|
142
|
+
* 2. The response is delivered as Server-Sent Events; AI SDK's
|
|
143
|
+
* non-streaming code path expects a single JSON body.
|
|
144
|
+
*
|
|
145
|
+
* This fetch forces streaming on the outgoing request, collects the SSE
|
|
146
|
+
* events, and synthesizes the non-streaming JSON shape that
|
|
147
|
+
* `@ai-sdk/openai`'s Responses API parser expects.
|
|
148
|
+
*
|
|
149
|
+
* Headers, OAuth refresh, and URL targeting are handled by the caller via
|
|
150
|
+
* `baseURL` / `headers` on the AI SDK provider; this fetch only injects the
|
|
151
|
+
* live OAuth bearer per call.
|
|
152
|
+
*/
|
|
153
|
+
function buildCodexStagehandFetch(authStorage) {
|
|
154
|
+
return (async (url, init) => {
|
|
155
|
+
const { accessToken } = await getCodexBearer(authStorage);
|
|
156
|
+
const headers = new Headers(init?.headers);
|
|
157
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
158
|
+
headers.set("Accept", "text/event-stream");
|
|
159
|
+
let body = init?.body;
|
|
160
|
+
if (typeof init?.body === "string") try {
|
|
161
|
+
const parsed = JSON.parse(init.body);
|
|
162
|
+
parsed.stream = true;
|
|
163
|
+
body = JSON.stringify(parsed);
|
|
164
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
165
|
+
} catch {}
|
|
166
|
+
const upstream = await fetch(url, {
|
|
167
|
+
...init,
|
|
168
|
+
headers,
|
|
169
|
+
body
|
|
170
|
+
});
|
|
171
|
+
if (!upstream.ok) return upstream;
|
|
172
|
+
const aggregated = await aggregateCodexStream(upstream);
|
|
173
|
+
return new Response(aggregated, {
|
|
174
|
+
status: 200,
|
|
175
|
+
headers: { "content-type": "application/json" }
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Read an SSE Response and reduce it to a single JSON string matching the
|
|
181
|
+
* non-streaming OpenAI Responses-API shape.
|
|
182
|
+
*
|
|
183
|
+
* Event vocabulary we care about (per OpenAI Responses API streaming):
|
|
184
|
+
* - response.created → carries `response` object (id, model, usage stub)
|
|
185
|
+
* - response.output_item.added/done → output items (message, reasoning, etc.)
|
|
186
|
+
* - response.output_text.delta → text chunks
|
|
187
|
+
* - response.completed → final `response` snapshot incl. usage
|
|
188
|
+
* - response.error / error → bubble up as a thrown body
|
|
189
|
+
*
|
|
190
|
+
* Reasoning events (`response.reasoning_summary.*`) are intentionally ignored
|
|
191
|
+
* for the non-streaming text response.
|
|
192
|
+
*/
|
|
193
|
+
async function aggregateCodexStream(response) {
|
|
194
|
+
if (!response.body) throw new Error("Codex streaming response had no body");
|
|
195
|
+
const reader = response.body.getReader();
|
|
196
|
+
const decoder = new TextDecoder("utf-8");
|
|
197
|
+
let buffer = "";
|
|
198
|
+
let finalResponse = null;
|
|
199
|
+
let createdResponse = null;
|
|
200
|
+
const items = /* @__PURE__ */ new Map();
|
|
201
|
+
const textBuffers = /* @__PURE__ */ new Map();
|
|
202
|
+
const handleEvent = (event) => {
|
|
203
|
+
if (!event.data || event.data === "[DONE]") return;
|
|
204
|
+
let payload;
|
|
205
|
+
try {
|
|
206
|
+
payload = JSON.parse(event.data);
|
|
207
|
+
} catch {
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
switch (payload.type ?? event.event ?? "") {
|
|
211
|
+
case "response.created":
|
|
212
|
+
createdResponse = payload.response ?? createdResponse;
|
|
213
|
+
break;
|
|
214
|
+
case "response.output_item.added":
|
|
215
|
+
if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
|
|
216
|
+
break;
|
|
217
|
+
case "response.output_item.done":
|
|
218
|
+
if (typeof payload.output_index === "number" && payload.item) items.set(payload.output_index, payload.item);
|
|
219
|
+
break;
|
|
220
|
+
case "response.output_text.delta": {
|
|
221
|
+
const key = `${payload.output_index}:${payload.content_index ?? 0}`;
|
|
222
|
+
textBuffers.set(key, (textBuffers.get(key) ?? "") + (payload.delta ?? ""));
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case "response.completed":
|
|
226
|
+
finalResponse = payload.response ?? finalResponse;
|
|
227
|
+
break;
|
|
228
|
+
case "response.error":
|
|
229
|
+
case "error": throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);
|
|
230
|
+
default: break;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const processChunk = (chunk) => {
|
|
234
|
+
buffer += chunk.replace(/\r\n/g, "\n");
|
|
235
|
+
let sepIdx;
|
|
236
|
+
while ((sepIdx = buffer.indexOf("\n\n")) !== -1) {
|
|
237
|
+
const raw = buffer.slice(0, sepIdx);
|
|
238
|
+
buffer = buffer.slice(sepIdx + 2);
|
|
239
|
+
const event = {};
|
|
240
|
+
const dataLines = [];
|
|
241
|
+
for (const line of raw.split("\n")) if (line.startsWith("event:")) event.event = line.slice(6).trim();
|
|
242
|
+
else if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
243
|
+
if (dataLines.length > 0) event.data = dataLines.join("\n");
|
|
244
|
+
handleEvent(event);
|
|
245
|
+
}
|
|
246
|
+
};
|
|
247
|
+
try {
|
|
248
|
+
while (true) {
|
|
249
|
+
const { value, done } = await reader.read();
|
|
250
|
+
if (done) break;
|
|
251
|
+
processChunk(decoder.decode(value, { stream: true }));
|
|
252
|
+
}
|
|
253
|
+
processChunk(decoder.decode());
|
|
254
|
+
} finally {
|
|
255
|
+
reader.releaseLock();
|
|
256
|
+
}
|
|
257
|
+
const base = finalResponse ?? createdResponse ?? { output: [] };
|
|
258
|
+
const finalItems = Array.from(items.entries()).sort(([a], [b]) => a - b).map(([index, item]) => {
|
|
259
|
+
if (item?.type === "message" && Array.isArray(item.content)) item.content = item.content.map((c, ci) => {
|
|
260
|
+
const key = `${index}:${ci}`;
|
|
261
|
+
if (textBuffers.has(key)) return {
|
|
262
|
+
...c,
|
|
263
|
+
text: textBuffers.get(key)
|
|
264
|
+
};
|
|
265
|
+
return c;
|
|
266
|
+
});
|
|
267
|
+
return item;
|
|
268
|
+
});
|
|
269
|
+
base.output = finalItems.length > 0 ? finalItems : base.output ?? [];
|
|
270
|
+
return JSON.stringify(base);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Creates an OpenAI model using ChatGPT OAuth authentication
|
|
274
|
+
* Uses OAuth tokens from AuthStorage (auto-refreshes when needed)
|
|
275
|
+
*
|
|
276
|
+
* IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.
|
|
277
|
+
* URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.
|
|
278
|
+
*/
|
|
279
|
+
function openaiCodexProvider(modelId = "codex-mini-latest", options) {
|
|
280
|
+
const effectiveLevel = getEffectiveThinkingLevel(modelId, options?.thinkingLevel ?? "medium");
|
|
281
|
+
const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];
|
|
282
|
+
const middleware = createCodexMiddleware(reasoningEffort);
|
|
283
|
+
const headers = options?.headers;
|
|
284
|
+
const baseURL = process.env.OPENAI_BASE_URL;
|
|
285
|
+
if (process.env.NODE_ENV === "test" || process.env.VITEST) return wrapLanguageModel({
|
|
286
|
+
model: createOpenAI({
|
|
287
|
+
apiKey: "test-api-key",
|
|
288
|
+
baseURL,
|
|
289
|
+
headers
|
|
290
|
+
}).responses(modelId),
|
|
291
|
+
middleware: [middleware]
|
|
292
|
+
});
|
|
293
|
+
return wrapLanguageModel({
|
|
294
|
+
model: createOpenAI({
|
|
295
|
+
apiKey: "oauth-dummy-key",
|
|
296
|
+
baseURL,
|
|
297
|
+
headers,
|
|
298
|
+
fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage })
|
|
299
|
+
}).responses(modelId),
|
|
300
|
+
middleware: [middleware]
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
export { THINKING_LEVEL_TO_REASONING_EFFORT, buildCodexStagehandFetch, buildOpenAICodexOAuthFetch, createCodexMiddleware, getAuthStorage, getEffectiveThinkingLevel, openaiCodexProvider, setAuthStorage, supportsMaxReasoningEffort };
|
|
305
|
+
|
|
306
|
+
//# sourceMappingURL=openai-codex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai-codex.js","names":[],"sources":["../../src/providers/openai-codex.ts"],"sourcesContent":["/**\n * OpenAI Codex OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with ChatGPT Plus/Pro subscription.\n * This allows access to OpenAI models through the ChatGPT OAuth flow.\n *\n * Inspired by opencode's Codex plugin implementation:\n * https://github.com/sst/opencode/blob/main/packages/opencode/src/plugin/codex.ts\n */\n\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { MastraModelConfig } from '@mastra/core/llm';\nimport { wrapLanguageModel } from 'ai';\nimport type { LanguageModelMiddleware } from 'ai';\nimport { ProviderAuthRequiredError } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { supportsMaxReasoningEffort } from '../thinking.js';\nimport type { ThinkingLevelSetting } from '../thinking.js';\nexport { supportsMaxReasoningEffort } from '../thinking.js';\n\n// Codex API endpoint (not standard OpenAI API)\nconst CODEX_API_ENDPOINT = 'https://chatgpt.com/backend-api/codex/responses';\nconst CODEX_ORIGINATOR = 'mastracode';\nconst CODEX_USER_AGENT = 'mastracode';\n\n// Singleton auth storage instance (shared with claude-max.ts)\nlet authStorageInstance: AuthStorage | null = null;\n\n/**\n * Get or create the shared AuthStorage instance\n */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/**\n * Set a custom AuthStorage instance (useful for TUI integration)\n */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n// Default instructions for Codex API (required)\nconst 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.\n\nIMPORTANT: You should be concise, direct, and helpful. Focus on solving the user's problem efficiently.`;\n\nexport type ThinkingLevel = ThinkingLevelSetting;\n\nconst GPT5_MODEL_RE = /^gpt-5(?:\\.|-|$)/;\n\nexport function getEffectiveThinkingLevel(modelId: string, level: ThinkingLevel): ThinkingLevel {\n // GPT-5.* models on Codex require at least low reasoning.\n if (GPT5_MODEL_RE.test(modelId) && level === 'off') {\n return 'low';\n }\n\n // Clamp `max` to `xhigh` only for models whose effort scale tops out there.\n if (level === 'max' && !supportsMaxReasoningEffort(modelId)) {\n return 'xhigh';\n }\n\n return level;\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent clamping\n// (e.g. `max` → `xhigh` for pre-GPT-5.6 models) happens in\n// getEffectiveThinkingLevel before this lookup.\nexport const THINKING_LEVEL_TO_REASONING_EFFORT: Record<ThinkingLevel, string | undefined> = {\n off: undefined,\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'xhigh',\n max: 'max',\n};\n\n/**\n * Create Codex middleware with the given reasoning effort level.\n */\nexport function createCodexMiddleware(reasoningEffort?: string): LanguageModelMiddleware {\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n // Remove topP if temperature is set (OpenAI doesn't like both)\n if (params.temperature !== undefined && params.temperature !== null) {\n delete params.topP;\n }\n\n // Codex API requires specific settings via providerOptions\n // Use type assertion to satisfy JSONValue constraints\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n ...(params.providerOptions?.openai ?? {}),\n instructions: CODEX_INSTRUCTIONS,\n // Codex API requires store to be false\n store: false,\n // Enable reasoning for Codex models — without this, the model\n // skips the reasoning/action phase and goes straight to final_answer,\n // resulting in narration instead of tool calls.\n ...(reasoningEffort ? { reasoningEffort } : {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Get a live OAuth bearer token for the Codex OAuth credential.\n *\n * Refreshes the token if it's expired, and returns the credential's\n * accountId alongside the access token. Throws if the user isn't logged in\n * or if the refresh fails.\n *\n * This is the only piece of Codex auth that is genuinely shared between\n * the main agent's fetch (`buildOpenAICodexOAuthFetch`) and the Stagehand\n * fetch (`buildCodexStagehandFetch`).\n */\nasync function getCodexBearer(\n authStorage?: CredentialStore,\n): Promise<{ accessToken: string; accountId: string | undefined }> {\n const storage = authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n\n let accessToken = cred.access;\n if (Date.now() >= cred.expires) {\n const refreshedToken = await storage.getApiKey('openai-codex');\n if (!refreshedToken) {\n throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n }\n accessToken = refreshedToken;\n storage.reload();\n }\n\n return { accessToken, accountId: (cred as any).accountId as string | undefined };\n}\n\n/**\n * Build a fetch function that handles OpenAI Codex OAuth.\n * Preserves non-authorization headers from init.\n * When rewriteUrl is true (default), rewrites /v1/responses and /chat/completions\n * to the Codex API endpoint. Set rewriteUrl: false for gateway usage where the\n * SDK already targets the correct URL.\n */\nexport function buildOpenAICodexOAuthFetch(\n opts: { authStorage?: CredentialStore; rewriteUrl?: boolean } = {},\n): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const { accessToken, accountId } = await getCodexBearer(opts.authStorage);\n\n // Preserve non-authorization headers\n const headers = new Headers();\n if (init?.headers) {\n if (init.headers instanceof Headers) {\n init.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'authorization') {\n headers.set(key, value);\n }\n });\n } else if (Array.isArray(init.headers)) {\n for (const [key, value] of init.headers) {\n if (key!.toLowerCase() !== 'authorization' && value !== undefined) {\n headers.set(key!, String(value));\n }\n }\n } else {\n for (const [key, value] of Object.entries(init.headers)) {\n if (key.toLowerCase() !== 'authorization' && value !== undefined) {\n headers.set(key, String(value));\n }\n }\n }\n }\n\n headers.set('Authorization', `Bearer ${accessToken}`);\n if (!headers.has('originator')) {\n headers.set('originator', CODEX_ORIGINATOR);\n }\n if (!headers.has('User-Agent')) {\n headers.set('User-Agent', CODEX_USER_AGENT);\n }\n if (accountId) {\n headers.set('ChatGPT-Account-ID', accountId);\n }\n\n // URL rewriting — only when rewriteUrl !== false\n const parsed = url instanceof URL ? url : new URL(typeof url === 'string' ? url : (url as Request).url);\n const shouldRewrite =\n opts.rewriteUrl !== false &&\n (parsed.pathname.includes('/v1/responses') || parsed.pathname.includes('/chat/completions'));\n const finalUrl = shouldRewrite ? new URL(CODEX_API_ENDPOINT) : parsed;\n\n try {\n return await fetch(finalUrl, { ...init, headers });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: finalUrl.toString(),\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Build a fetch function for Stagehand-on-Codex.\n *\n * The Codex backend has two requirements that AI SDK's non-streaming\n * `generateText` path doesn't naturally satisfy:\n *\n * 1. `stream: true` must be set on every request body.\n * 2. The response is delivered as Server-Sent Events; AI SDK's\n * non-streaming code path expects a single JSON body.\n *\n * This fetch forces streaming on the outgoing request, collects the SSE\n * events, and synthesizes the non-streaming JSON shape that\n * `@ai-sdk/openai`'s Responses API parser expects.\n *\n * Headers, OAuth refresh, and URL targeting are handled by the caller via\n * `baseURL` / `headers` on the AI SDK provider; this fetch only injects the\n * live OAuth bearer per call.\n */\nexport function buildCodexStagehandFetch(authStorage: AuthStorage): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n // Refresh + inject the OAuth bearer per call\n const { accessToken } = await getCodexBearer(authStorage);\n const headers = new Headers(init?.headers);\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('Accept', 'text/event-stream');\n\n // Force stream: true on the request body\n type FetchBody = NonNullable<Parameters<typeof fetch>[1]>['body'];\n let body: FetchBody | undefined = init?.body;\n if (typeof init?.body === 'string') {\n try {\n const parsed = JSON.parse(init.body) as Record<string, unknown>;\n parsed.stream = true;\n body = JSON.stringify(parsed);\n if (!headers.has('content-type')) headers.set('content-type', 'application/json');\n } catch {\n // Not JSON; leave as-is\n }\n }\n\n const upstream = await fetch(url, { ...init, headers, body });\n if (!upstream.ok) return upstream;\n\n // Aggregate SSE -> synthesized non-streaming Response\n const aggregated = await aggregateCodexStream(upstream);\n return new Response(aggregated, {\n status: 200,\n headers: { 'content-type': 'application/json' },\n });\n }) as typeof fetch;\n}\n\n/**\n * Read an SSE Response and reduce it to a single JSON string matching the\n * non-streaming OpenAI Responses-API shape.\n *\n * Event vocabulary we care about (per OpenAI Responses API streaming):\n * - response.created → carries `response` object (id, model, usage stub)\n * - response.output_item.added/done → output items (message, reasoning, etc.)\n * - response.output_text.delta → text chunks\n * - response.completed → final `response` snapshot incl. usage\n * - response.error / error → bubble up as a thrown body\n *\n * Reasoning events (`response.reasoning_summary.*`) are intentionally ignored\n * for the non-streaming text response.\n */\nasync function aggregateCodexStream(response: Response): Promise<string> {\n if (!response.body) {\n throw new Error('Codex streaming response had no body');\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder('utf-8');\n let buffer = '';\n\n let finalResponse: any = null;\n let createdResponse: any = null;\n // Track output_items by index so we can rebuild the final array\n const items = new Map<number, any>();\n // Accumulate output_text deltas keyed by item_index + content_index\n const textBuffers = new Map<string, string>();\n\n const handleEvent = (event: { event?: string; data?: string }) => {\n if (!event.data || event.data === '[DONE]') return;\n let payload: any;\n try {\n payload = JSON.parse(event.data);\n } catch {\n return;\n }\n const type: string = payload.type ?? event.event ?? '';\n\n switch (type) {\n case 'response.created': {\n createdResponse = payload.response ?? createdResponse;\n break;\n }\n case 'response.output_item.added': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_item.done': {\n if (typeof payload.output_index === 'number' && payload.item) {\n items.set(payload.output_index, payload.item);\n }\n break;\n }\n case 'response.output_text.delta': {\n const key = `${payload.output_index}:${payload.content_index ?? 0}`;\n textBuffers.set(key, (textBuffers.get(key) ?? '') + (payload.delta ?? ''));\n break;\n }\n case 'response.completed': {\n finalResponse = payload.response ?? finalResponse;\n break;\n }\n case 'response.error':\n case 'error': {\n throw new Error(`Codex stream error: ${JSON.stringify(payload.error ?? payload)}`);\n }\n default:\n // Ignore reasoning / unknown events\n break;\n }\n };\n\n // SSE parser: events separated by blank line; lines like \"event: x\" / \"data: y\"\n // Normalize CRLF→LF so \\r\\n\\r\\n event boundaries parse correctly (SSE spec allows CRLF).\n const processChunk = (chunk: string) => {\n buffer += chunk.replace(/\\r\\n/g, '\\n');\n let sepIdx: number;\n while ((sepIdx = buffer.indexOf('\\n\\n')) !== -1) {\n const raw = buffer.slice(0, sepIdx);\n buffer = buffer.slice(sepIdx + 2);\n const event: { event?: string; data?: string } = {};\n const dataLines: string[] = [];\n for (const line of raw.split('\\n')) {\n if (line.startsWith('event:')) {\n event.event = line.slice(6).trim();\n } else if (line.startsWith('data:')) {\n dataLines.push(line.slice(5).trimStart());\n }\n }\n if (dataLines.length > 0) {\n event.data = dataLines.join('\\n');\n }\n handleEvent(event);\n }\n };\n\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n processChunk(decoder.decode(value, { stream: true }));\n }\n processChunk(decoder.decode());\n } finally {\n reader.releaseLock();\n }\n\n // Stitch accumulated text deltas back into their items\n const base = finalResponse ?? createdResponse ?? { output: [] };\n const finalItems = Array.from(items.entries())\n .sort(([a], [b]) => a - b)\n .map(([index, item]) => {\n // Patch message-type items' content text using buffered deltas\n if (item?.type === 'message' && Array.isArray(item.content)) {\n item.content = item.content.map((c: any, ci: number) => {\n const key = `${index}:${ci}`;\n if (textBuffers.has(key)) {\n return { ...c, text: textBuffers.get(key) };\n }\n return c;\n });\n }\n return item;\n });\n\n base.output = finalItems.length > 0 ? finalItems : (base.output ?? []);\n\n return JSON.stringify(base);\n}\n\n/**\n * Creates an OpenAI model using ChatGPT OAuth authentication\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed)\n *\n * IMPORTANT: This uses the Codex API endpoint, not the standard OpenAI API.\n * URLs are rewritten from /v1/responses or /chat/completions to the Codex endpoint.\n */\nexport function openaiCodexProvider(\n modelId: string = 'codex-mini-latest',\n options?: { thinkingLevel?: ThinkingLevel; headers?: Record<string, string>; authStorage?: CredentialStore },\n): MastraModelConfig {\n const requestedLevel: ThinkingLevel = options?.thinkingLevel ?? 'medium';\n const effectiveLevel = getEffectiveThinkingLevel(modelId, requestedLevel);\n const reasoningEffort = THINKING_LEVEL_TO_REASONING_EFFORT[effectiveLevel];\n const middleware = createCodexMiddleware(reasoningEffort);\n const headers = options?.headers;\n\n const baseURL = process.env.OPENAI_BASE_URL;\n\n // Test environment: use API key\n if (process.env.NODE_ENV === 'test' || process.env.VITEST) {\n const openai = createOpenAI({\n apiKey: 'test-api-key',\n baseURL,\n headers,\n });\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n }\n\n const openai = createOpenAI({\n apiKey: 'oauth-dummy-key',\n baseURL,\n headers,\n fetch: buildOpenAICodexOAuthFetch({ authStorage: options?.authStorage }) as any,\n });\n\n // Use the responses API for Codex models\n // Wrap with middleware\n return wrapLanguageModel({\n model: openai.responses(modelId),\n middleware: [middleware],\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAGzB,IAAI,sBAA0C;;;;AAK9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;;;AAKA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;AAGA,MAAM,qBAAqB;;;AAM3B,MAAM,gBAAgB;AAEtB,SAAgB,0BAA0B,SA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O;EAC/B,YAAY,CAAC,UAAU;CACzB,CAAC;AACH"}
|
|
@@ -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 { MastraModelConfig } from '@mastra/core/llm';
|
|
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
|
+
}): MastraModelConfig;
|
|
33
|
+
//# sourceMappingURL=xai.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../src/providers/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAE1D,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAQxD,qDAAqD;AACrD,wBAAgB,cAAc,IAAI,WAAW,CAK5C;AAED,8EAA8E;AAC9E,wBAAgB,cAAc,CAAC,OAAO,EAAE,WAAW,GAAG,SAAS,GAAG,IAAI,CAErE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,IAAI,GAAE;IAAE,WAAW,CAAC,EAAE,eAAe,CAAA;CAAO,GAAG,OAAO,KAAK,CAsC7F;AAED;;;GAGG;AACH,wBAAgB,WAAW,CACzB,OAAO,EAAE,MAAM,EACf,OAAO,CAAC,EAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAAC,WAAW,CAAC,EAAE,eAAe,CAAA;CAAE,GAC5E,iBAAiB,CASnB"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { AuthStorage } from "../auth/storage.js";
|
|
2
|
+
import { ProviderAuthRequiredError } from "../auth/provider-auth-error.js";
|
|
3
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
4
|
+
//#region src/providers/xai.ts
|
|
5
|
+
/**
|
|
6
|
+
* xAI (Grok) OAuth Provider
|
|
7
|
+
*
|
|
8
|
+
* Uses OAuth tokens from AuthStorage to authenticate with the xAI API.
|
|
9
|
+
* The xAI API speaks an OpenAI-compatible chat format, and the OAuth access
|
|
10
|
+
* token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`
|
|
11
|
+
* into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)
|
|
12
|
+
* access token.
|
|
13
|
+
*/
|
|
14
|
+
const XAI_PROVIDER_ID = "xai";
|
|
15
|
+
const XAI_BASE_URL = "https://api.x.ai/v1";
|
|
16
|
+
let authStorageInstance = null;
|
|
17
|
+
/** Get or create the shared AuthStorage instance. */
|
|
18
|
+
function getAuthStorage() {
|
|
19
|
+
if (!authStorageInstance) authStorageInstance = new AuthStorage();
|
|
20
|
+
return authStorageInstance;
|
|
21
|
+
}
|
|
22
|
+
/** Set a custom AuthStorage instance (useful for tests / TUI integration). */
|
|
23
|
+
function setAuthStorage(storage) {
|
|
24
|
+
authStorageInstance = storage ?? null;
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Build a fetch wrapper that authenticates with xAI OAuth.
|
|
28
|
+
* Injects the access token (auto-refreshed by AuthStorage) as a bearer token,
|
|
29
|
+
* preserving non-auth headers from the caller.
|
|
30
|
+
*/
|
|
31
|
+
function buildXAIOAuthFetch(opts = {}) {
|
|
32
|
+
return (async (url, init) => {
|
|
33
|
+
const storage = opts.authStorage ?? getAuthStorage();
|
|
34
|
+
storage.reload();
|
|
35
|
+
const cred = storage.get(XAI_PROVIDER_ID);
|
|
36
|
+
if (!cred || cred.type !== "oauth") throw new ProviderAuthRequiredError("Not logged in to xAI.");
|
|
37
|
+
const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);
|
|
38
|
+
if (!accessToken) throw new ProviderAuthRequiredError("Failed to refresh the xAI token.");
|
|
39
|
+
const headers = new Headers(url instanceof Request ? url.headers : void 0);
|
|
40
|
+
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
41
|
+
headers.delete("authorization");
|
|
42
|
+
headers.delete("x-api-key");
|
|
43
|
+
headers.set("Authorization", `Bearer ${accessToken}`);
|
|
44
|
+
try {
|
|
45
|
+
return await fetch(url, {
|
|
46
|
+
...init,
|
|
47
|
+
headers
|
|
48
|
+
});
|
|
49
|
+
} catch (error) {
|
|
50
|
+
if (error && typeof error === "object") Object.assign(error, { requestUrl: url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url });
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Creates an xAI model using OAuth authentication.
|
|
57
|
+
* Uses OAuth tokens from AuthStorage (auto-refreshes when needed).
|
|
58
|
+
*/
|
|
59
|
+
function xaiProvider(modelId, options) {
|
|
60
|
+
return createOpenAICompatible({
|
|
61
|
+
name: XAI_PROVIDER_ID,
|
|
62
|
+
baseURL: XAI_BASE_URL,
|
|
63
|
+
apiKey: "oauth-placeholder",
|
|
64
|
+
headers: options?.headers,
|
|
65
|
+
fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage })
|
|
66
|
+
}).chatModel(modelId);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
export { buildXAIOAuthFetch, getAuthStorage, setAuthStorage, xaiProvider };
|
|
70
|
+
|
|
71
|
+
//# sourceMappingURL=xai.js.map
|