@mastra/code-sdk 1.15.1-alpha.3 → 1.15.1-alpha.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp/agent.js +1 -2
- package/dist/acp/errors.js +1 -2
- package/dist/acp/event-mapper.js +1 -2
- package/dist/acp/index.js +1 -2
- package/dist/acp/runtime.js +1 -2
- package/dist/acp/server.js +1 -2
- package/dist/acp/skills.js +1 -2
- package/dist/agent-connections/messaging-processor.js +1 -2
- package/dist/agent-connections/ownership.js +1 -2
- package/dist/agent-connections/registry.js +1 -2
- package/dist/agent-connections/session-advertisement.js +1 -2
- package/dist/agent-connections/signal-provider.js +1 -2
- package/dist/agent-connections/state-processor.js +1 -2
- package/dist/agent-connections/thread-state.js +1 -2
- package/dist/agent-connections/tools.js +1 -2
- package/dist/agent-connections/types.js +1 -2
- package/dist/agent-connections/untrusted-text.js +1 -2
- package/dist/agents/background-completion-events.js +1 -2
- package/dist/agents/background-completion.js +1 -2
- package/dist/agents/context-audit.js +1 -2
- package/dist/agents/credential-resolver.js +1 -2
- package/dist/agents/custom-provider-source.js +1 -2
- package/dist/agents/instructions.js +1 -2
- package/dist/agents/mastracode-gateway.d.ts.map +1 -1
- package/dist/agents/mastracode-gateway.js +6 -5
- package/dist/agents/mastracode-gateway.js.map +1 -1
- package/dist/agents/memory.js +1 -2
- package/dist/agents/model.js +1 -2
- package/dist/agents/modes/build.js +1 -2
- package/dist/agents/modes/explore.js +1 -2
- package/dist/agents/modes/plan.js +1 -2
- package/dist/agents/prompts/agent-instructions.js +1 -2
- package/dist/agents/prompts/build.js +1 -2
- package/dist/agents/prompts/fast.js +1 -2
- package/dist/agents/prompts/index.js +1 -2
- package/dist/agents/prompts/model.js +1 -2
- package/dist/agents/prompts/plan.js +1 -2
- package/dist/agents/prompts/tool-guidance.js +1 -2
- package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
- package/dist/agents/sandbox-filesystem.js +9 -7
- package/dist/agents/sandbox-filesystem.js.map +1 -1
- package/dist/agents/subagents/execute.js +1 -2
- package/dist/agents/subagents/explore.js +1 -2
- package/dist/agents/subagents/plan.js +1 -2
- package/dist/agents/thread-caveman-state.js +1 -2
- package/dist/agents/tool-availability.js +1 -2
- package/dist/agents/tools.js +1 -2
- package/dist/agents/workflow-builder-agent.js +1 -2
- package/dist/agents/workspace.js +1 -2
- package/dist/analytics.js +1 -2
- package/dist/auth/account-rotation-processor.js +1 -2
- package/dist/auth/account-routing-context.js +1 -2
- package/dist/auth/authorization-input.js +1 -2
- package/dist/auth/device-code.js +1 -2
- package/dist/auth/pkce.js +1 -2
- package/dist/auth/provider-auth-error.d.ts +2 -0
- package/dist/auth/provider-auth-error.d.ts.map +1 -1
- package/dist/auth/provider-auth-error.js +8 -3
- package/dist/auth/provider-auth-error.js.map +1 -1
- package/dist/auth/providers/anthropic.js +1 -2
- package/dist/auth/providers/github-copilot.js +1 -2
- package/dist/auth/providers/kimi-coding.js +1 -2
- package/dist/auth/providers/openai-codex.js +1 -2
- package/dist/auth/providers/xai.js +1 -2
- package/dist/auth/storage.js +1 -2
- package/dist/clipboard/index.js +1 -2
- package/dist/constants.js +1 -2
- package/dist/error-classification.js +1 -2
- package/dist/evals/context-builder.js +1 -2
- package/dist/evals/scorers/classify-command.d.ts +1 -2
- package/dist/evals/scorers/classify-command.d.ts.map +1 -1
- package/dist/evals/scorers/classify-command.js +7 -17
- package/dist/evals/scorers/classify-command.js.map +1 -1
- package/dist/evals/scorers/efficiency.js +1 -2
- package/dist/evals/scorers/extract-tools.js +1 -2
- package/dist/evals/scorers/outcome.d.ts.map +1 -1
- package/dist/evals/scorers/outcome.js +36 -22
- package/dist/evals/scorers/outcome.js.map +1 -1
- package/dist/experimental-agent.js +1 -2
- package/dist/factory/client.js +1 -2
- package/dist/factory/remote-controller.js +1 -2
- package/dist/factory/remote-session.js +1 -2
- package/dist/goal-manager.js +1 -2
- package/dist/goal-signal.js +1 -2
- package/dist/headless/cli.js +1 -2
- package/dist/headless/flags.js +1 -2
- package/dist/headless/format.js +1 -2
- package/dist/headless/policy.js +1 -2
- package/dist/headless/run-mc.js +1 -2
- package/dist/headless/types.js +1 -2
- package/dist/hooks/config.js +1 -2
- package/dist/hooks/executor.js +1 -2
- package/dist/hooks/manager.js +1 -2
- package/dist/hooks/types.js +1 -2
- package/dist/index.js +1 -2
- package/dist/ipc/ipc-reporter.js +1 -2
- package/dist/knowledge-inspector.js +1 -2
- package/dist/knowledge-scope.js +1 -2
- package/dist/lsp/client.d.ts.map +1 -1
- package/dist/lsp/client.js +1 -2
- package/dist/lsp/client.js.map +1 -1
- package/dist/lsp/language.js +1 -2
- package/dist/lsp/manager.js +1 -2
- package/dist/lsp/server.js +1 -2
- package/dist/lsp/workspace.js +1 -2
- package/dist/mcp/config.js +1 -2
- package/dist/mcp/manager.js +1 -2
- package/dist/mcp/state.js +1 -2
- package/dist/onboarding/custom-packs.js +1 -2
- package/dist/onboarding/custom-providers.js +1 -2
- package/dist/onboarding/om-settings.js +1 -2
- package/dist/onboarding/pack-activation.js +1 -2
- package/dist/onboarding/packs.js +1 -2
- package/dist/onboarding/settings.js +1 -2
- package/dist/permissions.js +1 -2
- package/dist/platform/index.js +1 -2
- package/dist/plugin.js +1 -2
- package/dist/plugins/dependencies.js +1 -2
- package/dist/plugins/install.js +1 -2
- package/dist/plugins/loader.js +1 -2
- package/dist/plugins/manager.js +1 -2
- package/dist/plugins/manifest.js +1 -2
- package/dist/plugins/package-link.js +1 -2
- package/dist/plugins/paths.js +1 -2
- package/dist/plugins/registry.js +1 -2
- package/dist/plugins/scaffold.js +1 -2
- package/dist/plugins/signal-lane.js +1 -2
- package/dist/process-memory-diagnostics.js +1 -2
- package/dist/processors/plan-rejection-abort.js +1 -2
- package/dist/providers/amazon-bedrock-gateway.js +1 -2
- package/dist/providers/amazon-bedrock.js +1 -2
- package/dist/providers/anthropic-prompt-cache.js +1 -2
- package/dist/providers/anthropic-thinking.js +1 -2
- package/dist/providers/claude-max.d.ts.map +1 -1
- package/dist/providers/claude-max.js +4 -4
- package/dist/providers/claude-max.js.map +1 -1
- package/dist/providers/github-copilot-gateway.js +1 -2
- package/dist/providers/github-copilot.d.ts.map +1 -1
- package/dist/providers/github-copilot.js +5 -5
- package/dist/providers/github-copilot.js.map +1 -1
- package/dist/providers/google-thinking.js +1 -2
- package/dist/providers/kimi-coding.d.ts.map +1 -1
- package/dist/providers/kimi-coding.js +8 -7
- package/dist/providers/kimi-coding.js.map +1 -1
- package/dist/providers/model-ids.js +1 -2
- package/dist/providers/openai-codex.d.ts +15 -0
- package/dist/providers/openai-codex.d.ts.map +1 -1
- package/dist/providers/openai-codex.js +50 -11
- package/dist/providers/openai-codex.js.map +1 -1
- package/dist/providers/provider-thinking.js +1 -2
- package/dist/providers/thinking-request.js +1 -2
- package/dist/providers/xai.d.ts.map +1 -1
- package/dist/providers/xai.js +5 -5
- package/dist/providers/xai.js.map +1 -1
- package/dist/schedules/interval.js +1 -2
- package/dist/schedules/prompt.js +1 -2
- package/dist/schedules/run-script.js +1 -2
- package/dist/schedules/scheduler.js +1 -2
- package/dist/schedules/tools.js +1 -2
- package/dist/schema.js +1 -2
- package/dist/theme-palette.js +1 -2
- package/dist/thinking-catalog.js +1 -2
- package/dist/thinking.js +1 -2
- package/dist/tool-names.js +1 -2
- package/dist/tools/request-sandbox-access.js +1 -2
- package/dist/tools/utils.js +1 -2
- package/dist/tools/web-search.js +1 -2
- package/dist/tools/workflows/create-workflow.js +1 -2
- package/dist/tools/workflows/delete-workflow.js +1 -2
- package/dist/tools/workflows/ephemeral-memory.js +1 -2
- package/dist/tools/workflows/extract-json-schema.js +1 -2
- package/dist/tools/workflows/get-workflow.js +1 -2
- package/dist/tools/workflows/list-available-agents.js +1 -2
- package/dist/tools/workflows/list-available-classifiers.js +1 -2
- package/dist/tools/workflows/list-available-tools.js +1 -2
- package/dist/tools/workflows/list-available-workflows.js +1 -2
- package/dist/tools/workflows/list-workflows.js +1 -2
- package/dist/tools/workflows/run-workflow.js +1 -2
- package/dist/tools/workflows/save-workflow.js +1 -2
- package/dist/tools/workflows/tool-ids.js +1 -2
- package/dist/utils/binaries.js +1 -2
- package/dist/utils/debug-log.js +1 -2
- package/dist/utils/discarding-scores-storage.js +1 -2
- package/dist/utils/errors.js +1 -2
- package/dist/utils/gateway-sync.js +1 -2
- package/dist/utils/local-observability.js +1 -2
- package/dist/utils/maintenance-lock.js +1 -2
- package/dist/utils/notification-dispatch.js +1 -2
- package/dist/utils/open-url.js +1 -2
- package/dist/utils/path-security.js +1 -2
- package/dist/utils/plan-diff.js +1 -2
- package/dist/utils/plans.js +1 -2
- package/dist/utils/project.js +1 -2
- package/dist/utils/prune-cli.js +1 -2
- package/dist/utils/signals-pubsub.js +1 -2
- package/dist/utils/slash-command-loader.js +1 -2
- package/dist/utils/slash-command-processor.js +1 -2
- package/dist/utils/stdin-pipe.js +1 -2
- package/dist/utils/storage-factory.js +1 -2
- package/dist/utils/storage-maintenance.js +1 -2
- package/dist/utils/thread-lock.js +1 -2
- package/dist/utils/token-estimator.js +1 -2
- package/dist/utils/update-check.js +1 -2
- package/dist/utils/wake-session.js +1 -2
- package/dist/voice/stt-registry.js +1 -2
- package/dist/workflows/register-primitives.js +1 -2
- package/dist/workflows/service.js +1 -2
- package/package.json +36 -32
|
@@ -1 +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, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.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 const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === 'off' ? 'low' : level;\n return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent fitting\n// happens in 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 * Create middleware that forwards a resolved reasoning effort to an\n * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.\n *\n * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing\n * (e.g. thinking level `off`), leaving the wire request without a\n * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not\n * inject Codex-only options (instructions/store); it only sets reasoning\n * effort, keyed by the caller-supplied provider id.\n */\nexport function createReasoningEffortMiddleware(\n providerKey: string,\n reasoningEffort?: string,\n): LanguageModelMiddleware | undefined {\n if (!reasoningEffort) return undefined;\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n [providerKey]: {\n ...(params.providerOptions?.[providerKey] ?? {}),\n 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 let cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n\n if (storage.getOAuthCredential) {\n cred = await storage.getOAuthCredential('openai-codex');\n if (!cred) throw new ProviderAuthRequiredError('Failed to refresh the OpenAI Codex token.');\n } else 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 storage.reload();\n const reloaded = storage.get('openai-codex');\n if (!reloaded || reloaded.type !== 'oauth') {\n throw new ProviderAuthRequiredError('Not logged in to OpenAI Codex.');\n }\n cred = { ...reloaded, access: refreshedToken };\n }\n\n return { accessToken: cred.access, 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 const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\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 = new URL(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 const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body;\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: 'OpenAI Codex',\n requestUrl: finalUrl.toString(),\n });\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: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('Accept', 'text/event-stream');\n\n // Stagehand sends JSON; force stream: true while preserving Request bodies.\n let body = await request.clone().text();\n try {\n const parsed = JSON.parse(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 const upstream = await fetch(\n new Request(request, {\n headers,\n ...(request.method === 'GET' || request.method === 'HEAD' ? {} : { body }),\n }),\n );\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;;;;AAK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../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, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\nimport { runCatalogThinkingLevel } from '../thinking-catalog.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';\nconst CODEX_PROVIDER_NAME = 'OpenAI Codex';\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 const requestedLevel = GPT5_MODEL_RE.test(modelId) && level === 'off' ? 'low' : level;\n return runCatalogThinkingLevel(`openai/${modelId}`, requestedLevel);\n}\n\n// Map thinkingLevel state values to OpenAI reasoningEffort values.\n// undefined means omit the parameter (no reasoning). Model-dependent fitting\n// happens in 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 * The thread a model request belongs to, from the `x-thread-id` header that\n * model resolution adds for requests made inside a thread.\n */\nexport function getRequestThreadId(headers?: Record<string, string>): string | undefined {\n if (!headers) return undefined;\n for (const name in headers) {\n if (name.toLowerCase() === 'x-thread-id') return headers[name] || undefined;\n }\n return undefined;\n}\n\n/**\n * Create middleware that sends `prompt_cache_key` on OpenAI Responses requests.\n *\n * OpenAI routes a cached prompt by a hash of its start plus this key. Every\n * Mastra Code prompt starts with the same system prompt, so without a key all\n * threads compete for the same cache slot and consecutive steps of one run often\n * land on a machine that doesn't hold their prefix. Keying by thread keeps each\n * thread's requests together. A key the caller already set wins.\n */\nexport function createPromptCacheKeyMiddleware(promptCacheKey?: string): LanguageModelMiddleware | undefined {\n if (!promptCacheKey) return undefined;\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n openai: {\n promptCacheKey,\n ...(params.providerOptions?.openai ?? {}),\n },\n } as typeof params.providerOptions;\n\n return params;\n },\n };\n}\n\n/**\n * Create middleware that forwards a resolved reasoning effort to an\n * OpenAI-compatible provider as `providerOptions[providerKey].reasoningEffort`.\n *\n * Returns `undefined` when `reasoningEffort` is unset so callers wrap nothing\n * (e.g. thinking level `off`), leaving the wire request without a\n * `reasoning_effort` field. Unlike {@link createCodexMiddleware}, it does not\n * inject Codex-only options (instructions/store); it only sets reasoning\n * effort, keyed by the caller-supplied provider id.\n */\nexport function createReasoningEffortMiddleware(\n providerKey: string,\n reasoningEffort?: string,\n): LanguageModelMiddleware | undefined {\n if (!reasoningEffort) return undefined;\n return {\n specificationVersion: 'v3',\n transformParams: async ({ params }) => {\n params.providerOptions = {\n ...params.providerOptions,\n [providerKey]: {\n ...(params.providerOptions?.[providerKey] ?? {}),\n 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 let cred = storage.get('openai-codex');\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);\n }\n\n if (storage.getOAuthCredential) {\n cred = await storage.getOAuthCredential('openai-codex');\n if (!cred) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);\n } else if (Date.now() >= cred.expires) {\n const refreshedToken = await storage.getApiKey('openai-codex');\n if (!refreshedToken) throw ProviderAuthRequiredError.signInExpired(CODEX_PROVIDER_NAME);\n storage.reload();\n const reloaded = storage.get('openai-codex');\n if (!reloaded || reloaded.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(CODEX_PROVIDER_NAME);\n }\n cred = { ...reloaded, access: refreshedToken };\n }\n\n return { accessToken: cred.access, 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 const { headers: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n\n // Preserve Request headers and let explicit init headers override them.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\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 // Codex CLI sends its session on every request; send the thread the same way.\n const threadId = headers.get('x-thread-id');\n if (threadId) {\n if (!headers.has('session-id')) headers.set('session-id', threadId);\n if (!headers.has('thread-id')) headers.set('thread-id', threadId);\n }\n\n // URL rewriting — only when rewriteUrl !== false\n const parsed = new URL(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 const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : request.body;\n const finalRequest = new Request(finalUrl, {\n method: request.method,\n headers,\n body,\n signal: request.signal,\n redirect: request.redirect,\n integrity: request.integrity,\n ...(body ? ({ duplex: 'half' } as RequestInit) : {}),\n });\n try {\n return await rejectUnauthorizedResponse(await fetch(finalRequest), {\n providerName: CODEX_PROVIDER_NAME,\n requestUrl: finalUrl.toString(),\n });\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: initHeaders, ...requestInit } = init ?? {};\n const request = new Request(url, requestInit);\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (initHeaders) new Headers(initHeaders).forEach((value, key) => headers.set(key, value));\n headers.delete('authorization');\n headers.delete('x-api-key');\n headers.set('Authorization', `Bearer ${accessToken}`);\n headers.set('Accept', 'text/event-stream');\n\n // Stagehand sends JSON; force stream: true while preserving Request bodies.\n let body = await request.clone().text();\n try {\n const parsed = JSON.parse(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 const upstream = await fetch(\n new Request(request, {\n headers,\n ...(request.method === 'GET' || request.method === 'HEAD' ? {} : { body }),\n }),\n );\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 headers = options?.headers;\n const promptCacheKeyMiddleware = createPromptCacheKeyMiddleware(getRequestThreadId(headers));\n const middleware = [\n createCodexMiddleware(reasoningEffort),\n ...(promptCacheKeyMiddleware ? [promptCacheKeyMiddleware] : []),\n ];\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,\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,\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsBA,MAAM,qBAAqB;AAC3B,MAAM,mBAAmB;AACz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AK,UAAU,IAAI;AAC5B;;;;;;;;AASA,SAAgB,oBACd,UAAkB,qBAClB,SACmB;CAEnB,MAAM,iBAAiB,0BAA0B,SADX,SAAS,iBAAiB,QACQ;CACxE,MAAM,kBAAkB,mCAAmC;CAC3D,MAAM,UAAU,SAAS;CACzB,MAAM,2BAA2B,+BAA+B,mBAAmB,OAAO,CAAC;CAC3F,MAAM,aAAa,CACjB,sBAAsB,eAAe,GACrC,GAAI,2BAA2B,CAAC,wBAAwB,IAAI,CAAC,CAC/D;CAEA,MAAM,UAAU,QAAQ,IAAI;CAG5B,IAAI,QAAQ,IAAI,aAAa,UAAU,QAAQ,IAAI,QAAQ;EACzD,MAAM,SAAS,aAAa;GAC1B,QAAQ;GACR;GACA;EACF,CAAC;EACD,OAAO,kBAAkB;GACvB,OAAO,OAAO,UAAU,OAAO;GAC/B;EACF,CAAC;CACH;CAEA,MAAM,SAAS,aAAa;EAC1B,QAAQ;EACR;EACA;EACA,OAAO,2BAA2B,EAAE,aAAa,SAAS,YAAY,CAAC;CACzE,CAAC;CAID,OAAO,kBAAkB;EACvB,OAAO,OAAO,UAAU,OAAO;EAC/B;CACF,CAAC;AACH"}
|
|
@@ -2,7 +2,7 @@ import { thinkingRequestFormatFor } from "./thinking-request.js";
|
|
|
2
2
|
import { requestableReasoningOptions, runThinkingLevel } from "../thinking.js";
|
|
3
3
|
import { ModelRouterLanguageModel, getModelReasoningOptions } from "@mastra/core/llm";
|
|
4
4
|
import { wrapLanguageModel } from "ai";
|
|
5
|
-
|
|
5
|
+
// src/providers/provider-thinking.ts
|
|
6
6
|
function providerThinkingOptions(routedModelId, level) {
|
|
7
7
|
const format = thinkingRequestFormatFor(routedModelId);
|
|
8
8
|
if (!format || !level) return void 0;
|
|
@@ -58,7 +58,6 @@ var ModelRouterLanguageModelWithThinking = class extends ModelRouterLanguageMode
|
|
|
58
58
|
return super.doStream(withThinkingOptions(options, this.#thinking));
|
|
59
59
|
}
|
|
60
60
|
};
|
|
61
|
-
//#endregion
|
|
62
61
|
export { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel };
|
|
63
62
|
|
|
64
63
|
//# sourceMappingURL=provider-thinking.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MASTRA_GATEWAY_PREFIX, stripMastraGatewayPrefix } from "./model-ids.js";
|
|
2
|
-
|
|
2
|
+
// src/providers/thinking-request.ts
|
|
3
3
|
const LOW_TO_HIGH = [
|
|
4
4
|
"low",
|
|
5
5
|
"medium",
|
|
@@ -84,7 +84,6 @@ function thinkingRequestFormatFor(modelId) {
|
|
|
84
84
|
if (routedThroughMastraGateway) return OPENROUTER_FORMAT;
|
|
85
85
|
return REQUEST_FORMATS_BY_PROVIDER[provider.includes("alibaba") ? "alibaba" : provider];
|
|
86
86
|
}
|
|
87
|
-
//#endregion
|
|
88
87
|
export { isRoutedWithoutThinking, isThinkingAdapterProvider, thinkingRequestFormatFor };
|
|
89
88
|
|
|
90
89
|
//# sourceMappingURL=thinking-request.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../src/providers/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../src/providers/xai.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAGH,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AASxD,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,CAuC7F;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,UAAU,CAAC,wBAAwB,CAAC,WAAW,CAAC,CAAC,CASnD"}
|
package/dist/providers/xai.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
2
|
import { ProviderAuthRequiredError, rejectUnauthorizedResponse } from "../auth/provider-auth-error.js";
|
|
3
3
|
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
4
|
-
|
|
4
|
+
// src/providers/xai.ts
|
|
5
5
|
/**
|
|
6
6
|
* xAI (Grok) OAuth Provider
|
|
7
7
|
*
|
|
@@ -12,6 +12,7 @@ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
|
12
12
|
* access token.
|
|
13
13
|
*/
|
|
14
14
|
const XAI_PROVIDER_ID = "xai";
|
|
15
|
+
const XAI_PROVIDER_NAME = "xAI";
|
|
15
16
|
const XAI_BASE_URL = "https://api.x.ai/v1";
|
|
16
17
|
let authStorageInstance = null;
|
|
17
18
|
/** Get or create the shared AuthStorage instance. */
|
|
@@ -33,9 +34,9 @@ function buildXAIOAuthFetch(opts = {}) {
|
|
|
33
34
|
const storage = opts.authStorage ?? getAuthStorage();
|
|
34
35
|
storage.reload();
|
|
35
36
|
const cred = storage.get(XAI_PROVIDER_ID);
|
|
36
|
-
if (!cred || cred.type !== "oauth") throw
|
|
37
|
+
if (!cred || cred.type !== "oauth") throw ProviderAuthRequiredError.notSignedIn(XAI_PROVIDER_NAME);
|
|
37
38
|
const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);
|
|
38
|
-
if (!accessToken) throw
|
|
39
|
+
if (!accessToken) throw ProviderAuthRequiredError.signInExpired(XAI_PROVIDER_NAME);
|
|
39
40
|
const headers = new Headers(url instanceof Request ? url.headers : void 0);
|
|
40
41
|
if (init?.headers) new Headers(init.headers).forEach((value, key) => headers.set(key, value));
|
|
41
42
|
headers.delete("authorization");
|
|
@@ -46,7 +47,7 @@ function buildXAIOAuthFetch(opts = {}) {
|
|
|
46
47
|
...init,
|
|
47
48
|
headers
|
|
48
49
|
}), {
|
|
49
|
-
providerName:
|
|
50
|
+
providerName: XAI_PROVIDER_NAME,
|
|
50
51
|
requestUrl: url instanceof URL ? url.toString() : typeof url === "string" ? url : url.url
|
|
51
52
|
});
|
|
52
53
|
} catch (error) {
|
|
@@ -68,7 +69,6 @@ function xaiProvider(modelId, options) {
|
|
|
68
69
|
fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage })
|
|
69
70
|
}).chatModel(modelId);
|
|
70
71
|
}
|
|
71
|
-
//#endregion
|
|
72
72
|
export { buildXAIOAuthFetch, getAuthStorage, setAuthStorage, xaiProvider };
|
|
73
73
|
|
|
74
74
|
//# sourceMappingURL=xai.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"xai.js","names":[],"sources":["../../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI (Grok) OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.\n * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access\n * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`\n * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)\n * access token.\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst XAI_PROVIDER_ID = 'xai';\nconst XAI_BASE_URL = 'https://api.x.ai/v1';\n\n// Singleton auth storage instance (shared with claude-max.ts / github-copilot.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(XAI_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw
|
|
1
|
+
{"version":3,"file":"xai.js","names":[],"sources":["../../src/providers/xai.ts"],"sourcesContent":["/**\n * xAI (Grok) OAuth Provider\n *\n * Uses OAuth tokens from AuthStorage to authenticate with the xAI API.\n * The xAI API speaks an OpenAI-compatible chat format, and the OAuth access\n * token is accepted as a bearer API key, so we plug `@ai-sdk/openai-compatible`\n * into `https://api.x.ai/v1` with a custom fetch that injects the (auto-refreshed)\n * access token.\n */\n\nimport { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';\nimport { ProviderAuthRequiredError, rejectUnauthorizedResponse } from '../auth/provider-auth-error.js';\nimport { AuthStorage } from '../auth/storage.js';\nimport type { CredentialStore } from '../auth/types.js';\n\nconst XAI_PROVIDER_ID = 'xai';\nconst XAI_PROVIDER_NAME = 'xAI';\nconst XAI_BASE_URL = 'https://api.x.ai/v1';\n\n// Singleton auth storage instance (shared with claude-max.ts / github-copilot.ts when not overridden).\nlet authStorageInstance: AuthStorage | null = null;\n\n/** Get or create the shared AuthStorage instance. */\nexport function getAuthStorage(): AuthStorage {\n if (!authStorageInstance) {\n authStorageInstance = new AuthStorage();\n }\n return authStorageInstance;\n}\n\n/** Set a custom AuthStorage instance (useful for tests / TUI integration). */\nexport function setAuthStorage(storage: AuthStorage | undefined): void {\n authStorageInstance = storage ?? null;\n}\n\n/**\n * Build a fetch wrapper that authenticates with xAI OAuth.\n * Injects the access token (auto-refreshed by AuthStorage) as a bearer token,\n * preserving non-auth headers from the caller.\n */\nexport function buildXAIOAuthFetch(opts: { authStorage?: CredentialStore } = {}): typeof fetch {\n return (async (url: string | URL | Request, init?: Parameters<typeof fetch>[1]) => {\n const storage = opts.authStorage ?? getAuthStorage();\n storage.reload();\n\n const cred = storage.get(XAI_PROVIDER_ID);\n if (!cred || cred.type !== 'oauth') {\n throw ProviderAuthRequiredError.notSignedIn(XAI_PROVIDER_NAME);\n }\n\n // getApiKey() refreshes the access token if it has expired.\n const accessToken = await storage.getApiKey(XAI_PROVIDER_ID);\n if (!accessToken) throw ProviderAuthRequiredError.signInExpired(XAI_PROVIDER_NAME);\n\n // Preserve existing headers, strip auth-related ones. Explicit init\n // headers override headers carried by an incoming Request.\n const headers = new Headers(url instanceof Request ? url.headers : undefined);\n if (init?.headers) {\n new Headers(init.headers).forEach((value, key) => headers.set(key, value));\n }\n headers.delete('authorization');\n headers.delete('x-api-key');\n\n headers.set('Authorization', `Bearer ${accessToken}`);\n\n try {\n return await rejectUnauthorizedResponse(await fetch(url, { ...init, headers }), {\n providerName: XAI_PROVIDER_NAME,\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n } catch (error) {\n if (error && typeof error === 'object') {\n Object.assign(error as Record<string, unknown>, {\n requestUrl: url instanceof URL ? url.toString() : typeof url === 'string' ? url : (url as Request).url,\n });\n }\n throw error;\n }\n }) as typeof fetch;\n}\n\n/**\n * Creates an xAI model using OAuth authentication.\n * Uses OAuth tokens from AuthStorage (auto-refreshes when needed).\n */\nexport function xaiProvider(\n modelId: string,\n options?: { headers?: Record<string, string>; authStorage?: CredentialStore },\n): ReturnType<OpenAICompatibleProvider['chatModel']> {\n const provider = createOpenAICompatible({\n name: XAI_PROVIDER_ID,\n baseURL: XAI_BASE_URL,\n apiKey: 'oauth-placeholder', // real auth injected by the custom fetch\n headers: options?.headers,\n fetch: buildXAIOAuthFetch({ authStorage: options?.authStorage }),\n });\n return provider.chatModel(modelId);\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;AAC1B,MAAM,eAAe;AAGrB,IAAI,sBAA0C;;AAG9C,SAAgB,iBAA8B;CAC5C,IAAI,CAAC,qBACH,sBAAsB,IAAI,YAAY;CAExC,OAAO;AACT;;AAGA,SAAgB,eAAe,SAAwC;CACrE,sBAAsB,WAAW;AACnC;;;;;;AAOA,SAAgB,mBAAmB,OAA0C,CAAC,GAAiB;CAC7F,QAAQ,OAAO,KAA6B,SAAuC;EACjF,MAAM,UAAU,KAAK,eAAe,eAAe;EACnD,QAAQ,OAAO;EAEf,MAAM,OAAO,QAAQ,IAAI,eAAe;EACxC,IAAI,CAAC,QAAQ,KAAK,SAAS,SACzB,MAAM,0BAA0B,YAAY,iBAAiB;EAI/D,MAAM,cAAc,MAAM,QAAQ,UAAU,eAAe;EAC3D,IAAI,CAAC,aAAa,MAAM,0BAA0B,cAAc,iBAAiB;EAIjF,MAAM,UAAU,IAAI,QAAQ,eAAe,UAAU,IAAI,UAAU,KAAA,CAAS;EAC5E,IAAI,MAAM,SACR,IAAI,QAAQ,KAAK,OAAO,CAAC,CAAC,SAAS,OAAO,QAAQ,QAAQ,IAAI,KAAK,KAAK,CAAC;EAE3E,QAAQ,OAAO,eAAe;EAC9B,QAAQ,OAAO,WAAW;EAE1B,QAAQ,IAAI,iBAAiB,UAAU,aAAa;EAEpD,IAAI;GACF,OAAO,MAAM,2BAA2B,MAAM,MAAM,KAAK;IAAE,GAAG;IAAM;GAAQ,CAAC,GAAG;IAC9E,cAAc;IACd,YAAY,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAO,IAAgB;GACrG,CAAC;EACH,SAAS,OAAO;GACd,IAAI,SAAS,OAAO,UAAU,UAC5B,OAAO,OAAO,OAAkC,EAC9C,YAAY,eAAe,MAAM,IAAI,SAAS,IAAI,OAAO,QAAQ,WAAW,MAAO,IAAgB,IACrG,CAAC;GAEH,MAAM;EACR;CACF;AACF;;;;;AAMA,SAAgB,YACd,SACA,SACmD;CAQnD,OAPiB,uBAAuB;EACtC,MAAM;EACN,SAAS;EACT,QAAQ;EACR,SAAS,SAAS;EAClB,OAAO,mBAAmB,EAAE,aAAa,SAAS,YAAY,CAAC;CACjE,CACc,CAAC,CAAC,UAAU,OAAO;AACnC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/schedules/interval.ts
|
|
2
2
|
/**
|
|
3
3
|
* Interval parsing and fire-time math for `/schedules`.
|
|
4
4
|
*
|
|
@@ -209,7 +209,6 @@ function nextFireTime(intervalMs, after) {
|
|
|
209
209
|
while (hourSlotKey(cursor, stepHours) <= startSlot);
|
|
210
210
|
return cursor.getTime();
|
|
211
211
|
}
|
|
212
|
-
//#endregion
|
|
213
212
|
export { nextFireTime, parseInterval, validateInterval };
|
|
214
213
|
|
|
215
214
|
//# sourceMappingURL=interval.js.map
|
package/dist/schedules/prompt.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/schedules/prompt.ts
|
|
2
2
|
const SCRIPT_TIMEOUT_MS = 6e4;
|
|
3
3
|
function appendExtra(text, extra) {
|
|
4
4
|
return extra ? `${text}\n\n${extra}` : text;
|
|
@@ -33,7 +33,6 @@ async function assembleSchedulePrompt(spec, options) {
|
|
|
33
33
|
...outcome ? { outcome } : {}
|
|
34
34
|
};
|
|
35
35
|
}
|
|
36
|
-
//#endregion
|
|
37
36
|
export { SCRIPT_TIMEOUT_MS, assembleSchedulePrompt, formatScriptOutput };
|
|
38
37
|
|
|
39
38
|
//# sourceMappingURL=prompt.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as path$1 from "path";
|
|
2
2
|
import * as fs$1 from "fs";
|
|
3
3
|
import { execFile } from "child_process";
|
|
4
|
-
|
|
4
|
+
// src/schedules/run-script.ts
|
|
5
5
|
/**
|
|
6
6
|
* Runs a schedule's script file at fire time.
|
|
7
7
|
*
|
|
@@ -77,7 +77,6 @@ const runScript = async (absPath, { cwd, timeoutMs }) => {
|
|
|
77
77
|
});
|
|
78
78
|
});
|
|
79
79
|
};
|
|
80
|
-
//#endregion
|
|
81
80
|
export { isExecutableFile, resolveScriptCommand, runScript };
|
|
82
81
|
|
|
83
82
|
//# sourceMappingURL=run-script.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { nextFireTime, validateInterval } from "./interval.js";
|
|
2
2
|
import { randomUUID } from "crypto";
|
|
3
|
-
|
|
3
|
+
// src/schedules/scheduler.ts
|
|
4
4
|
/**
|
|
5
5
|
* Process-local scheduler behind `/schedules`.
|
|
6
6
|
*
|
|
@@ -163,7 +163,6 @@ function scheduleSignalAttributes(schedule, assembled = {}) {
|
|
|
163
163
|
...assembled.outcome ? { scheduleOutcome: assembled.outcome } : {}
|
|
164
164
|
};
|
|
165
165
|
}
|
|
166
|
-
//#endregion
|
|
167
166
|
export { LATE_FIRE_GRACE_MS, SCHEDULE_SIGNAL_SOURCE, ThreadScheduler, describeScheduleSource, scheduleSignalAttributes, shortScheduleId };
|
|
168
167
|
|
|
169
168
|
//# sourceMappingURL=scheduler.js.map
|
package/dist/schedules/tools.js
CHANGED
|
@@ -4,7 +4,7 @@ import { resolveScriptCommand } from "./run-script.js";
|
|
|
4
4
|
import * as path$1 from "path";
|
|
5
5
|
import { createTool } from "@mastra/core/tools";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
-
|
|
7
|
+
// src/schedules/tools.ts
|
|
8
8
|
/**
|
|
9
9
|
* Agent-facing tools for the process-local `/schedules` scheduler.
|
|
10
10
|
*
|
|
@@ -214,7 +214,6 @@ Pass exactly one source: "prompt" (text sent each fire), "promptFile" (a file re
|
|
|
214
214
|
[SCHEDULE_TOOL_IDS.run]: scheduleRunTool
|
|
215
215
|
};
|
|
216
216
|
}
|
|
217
|
-
//#endregion
|
|
218
217
|
export { SCHEDULE_TOOL_IDS, createScheduleTools };
|
|
219
218
|
|
|
220
219
|
//# sourceMappingURL=tools.js.map
|
package/dist/schema.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { DEFAULT_CONFIG_DIR } from "./constants.js";
|
|
2
2
|
import { THINKING_LEVEL_VALUES } from "./thinking.js";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/schema.ts
|
|
5
5
|
const stateSchema = z.object({
|
|
6
6
|
currentModelId: z.string().optional(),
|
|
7
7
|
modeId: z.string().optional(),
|
|
@@ -128,7 +128,6 @@ const stateSchema = z.object({
|
|
|
128
128
|
observerModelSelection: state.observerModelSelection ?? state.observerModelId ?? "auto",
|
|
129
129
|
reflectorModelSelection: state.reflectorModelSelection ?? state.reflectorModelId ?? "auto"
|
|
130
130
|
}));
|
|
131
|
-
//#endregion
|
|
132
131
|
export { stateSchema };
|
|
133
132
|
|
|
134
133
|
//# sourceMappingURL=schema.js.map
|
package/dist/theme-palette.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/theme-palette.ts
|
|
2
2
|
/**
|
|
3
3
|
* Mastra brand palette (immutable — stays constant regardless of theme).
|
|
4
4
|
*
|
|
@@ -15,7 +15,6 @@ const mastraBrand = {
|
|
|
15
15
|
red: "#DC5663",
|
|
16
16
|
yellow: "#e7e67b"
|
|
17
17
|
};
|
|
18
|
-
//#endregion
|
|
19
18
|
export { mastraBrand };
|
|
20
19
|
|
|
21
20
|
//# sourceMappingURL=theme-palette.js.map
|
package/dist/thinking-catalog.js
CHANGED
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
import { getAvailableThinkingLevelsForModel, runThinkingLevel } from "./thinking.js";
|
|
2
2
|
import { getModelReasoningOptions } from "@mastra/core/llm";
|
|
3
|
-
|
|
3
|
+
// src/thinking-catalog.ts
|
|
4
4
|
function runCatalogThinkingLevel(modelId, level) {
|
|
5
5
|
return runThinkingLevel(modelId, level, getModelReasoningOptions(modelId));
|
|
6
6
|
}
|
|
7
7
|
function getCatalogThinkingLevels(modelId) {
|
|
8
8
|
return getAvailableThinkingLevelsForModel(modelId, getModelReasoningOptions(modelId));
|
|
9
9
|
}
|
|
10
|
-
//#endregion
|
|
11
10
|
export { getCatalogThinkingLevels, runCatalogThinkingLevel };
|
|
12
11
|
|
|
13
12
|
//# sourceMappingURL=thinking-catalog.js.map
|
package/dist/thinking.js
CHANGED
|
@@ -2,7 +2,7 @@ import { ANTHROPIC_THINKING_BUDGET_TOKENS, getAnthropicThinkingCapability, suppo
|
|
|
2
2
|
import { runGeminiThinkingLevel } from "./providers/google-thinking.js";
|
|
3
3
|
import { normalizeAnthropicModelId, stripMastraGatewayPrefix } from "./providers/model-ids.js";
|
|
4
4
|
import { isRoutedWithoutThinking, isThinkingAdapterProvider, thinkingRequestFormatFor } from "./providers/thinking-request.js";
|
|
5
|
-
|
|
5
|
+
// src/thinking.ts
|
|
6
6
|
const THINKING_LEVEL_VALUES = [
|
|
7
7
|
"off",
|
|
8
8
|
"low",
|
|
@@ -131,7 +131,6 @@ function resolveDefaultThinkingLevel(defaults, mode) {
|
|
|
131
131
|
source: "global"
|
|
132
132
|
};
|
|
133
133
|
}
|
|
134
|
-
//#endregion
|
|
135
134
|
export { THINKING_LEVEL_VALUES, THINK_COMMAND_DESCRIPTOR, getAvailableThinkingLevelsForModel, isThinkingLevelSetting, parseThinkCommand, requestableReasoningOptions, resolveDefaultThinkingLevel, runThinkingLevel, supportsMaxReasoningEffort };
|
|
136
135
|
|
|
137
136
|
//# sourceMappingURL=thinking.js.map
|
package/dist/tool-names.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { WORKSPACE_TOOLS } from "@mastra/core/workspace";
|
|
2
|
-
|
|
2
|
+
// src/tool-names.ts
|
|
3
3
|
/**
|
|
4
4
|
* Mastracode tool name constants.
|
|
5
5
|
*
|
|
@@ -50,7 +50,6 @@ const TOOL_NAME_OVERRIDES = {
|
|
|
50
50
|
[WORKSPACE_TOOLS.SANDBOX.KILL_PROCESS]: { name: MC_TOOLS.KILL_PROCESS },
|
|
51
51
|
[WORKSPACE_TOOLS.LSP.LSP_INSPECT]: { name: MC_TOOLS.LSP_INSPECT }
|
|
52
52
|
};
|
|
53
|
-
//#endregion
|
|
54
53
|
export { MC_TOOLS, TOOL_NAME_OVERRIDES };
|
|
55
54
|
|
|
56
55
|
//# sourceMappingURL=tool-names.js.map
|
|
@@ -4,7 +4,7 @@ import * as os$1 from "os";
|
|
|
4
4
|
import { LocalFilesystem } from "@mastra/core/workspace";
|
|
5
5
|
import { createTool } from "@mastra/core/tools";
|
|
6
6
|
import { z } from "zod";
|
|
7
|
-
|
|
7
|
+
// src/tools/request-sandbox-access.ts
|
|
8
8
|
/**
|
|
9
9
|
* request_access tool — requests permission to access a directory outside the project root.
|
|
10
10
|
* The user can approve or deny the request via TUI dialog.
|
|
@@ -76,7 +76,6 @@ const requestSandboxAccessTool = createTool({
|
|
|
76
76
|
}
|
|
77
77
|
}
|
|
78
78
|
});
|
|
79
|
-
//#endregion
|
|
80
79
|
export { requestSandboxAccessTool };
|
|
81
80
|
|
|
82
81
|
//# sourceMappingURL=request-sandbox-access.js.map
|
package/dist/tools/utils.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import "../constants.js";
|
|
2
2
|
import { buildSkillPaths } from "../agents/workspace.js";
|
|
3
3
|
import * as path$1 from "path";
|
|
4
|
-
|
|
4
|
+
// src/tools/utils.ts
|
|
5
5
|
/**
|
|
6
6
|
* Check whether `targetPath` falls inside `projectRoot` or any of the
|
|
7
7
|
* additional `allowedPaths`. All arguments are expected to be absolute.
|
|
@@ -28,7 +28,6 @@ function getAllowedPathsFromContext(toolContext) {
|
|
|
28
28
|
const sandboxPaths = state?.sandboxAllowedPaths ?? [];
|
|
29
29
|
return [...skillPaths, ...sandboxPaths];
|
|
30
30
|
}
|
|
31
|
-
//#endregion
|
|
32
31
|
export { getAllowedPathsFromContext, isPathAllowed };
|
|
33
32
|
|
|
34
33
|
//# sourceMappingURL=utils.js.map
|
package/dist/tools/web-search.js
CHANGED
|
@@ -2,7 +2,7 @@ import { loadSettings } from "../onboarding/settings.js";
|
|
|
2
2
|
import { truncateStringForTokenEstimate } from "../utils/token-estimator.js";
|
|
3
3
|
import { createTool, isValidationError } from "@mastra/core/tools";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
|
|
5
|
+
// src/tools/web-search.ts
|
|
6
6
|
const MAX_WEB_SEARCH_TOKENS = 2e3;
|
|
7
7
|
const MAX_WEB_EXTRACT_TOKENS = 2e3;
|
|
8
8
|
const MIN_RELEVANCE_SCORE = .25;
|
|
@@ -155,7 +155,6 @@ async function loadWebTools(createSearch, createExtract) {
|
|
|
155
155
|
web_extract: await createExtract()
|
|
156
156
|
};
|
|
157
157
|
}
|
|
158
|
-
//#endregion
|
|
159
158
|
export { createConfiguredWebTools, createParallelWebExtractTool, createParallelWebSearchTool, createWebExtractTool, createWebSearchTool, hasParallelKey, hasTavilyKey, resolveWebSearchProvider };
|
|
160
159
|
|
|
161
160
|
//# sourceMappingURL=web-search.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
|
|
2
2
|
import { createTool } from "@mastra/core/tools";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/tools/workflows/create-workflow.ts
|
|
5
5
|
/**
|
|
6
6
|
* Coerce an unknown thrown value into a readable string. Sub-agent tool errors
|
|
7
7
|
* come through the stream in various shapes (Error, plain object, string) —
|
|
@@ -79,7 +79,6 @@ const createWorkflowTool = createTool({
|
|
|
79
79
|
};
|
|
80
80
|
}
|
|
81
81
|
});
|
|
82
|
-
//#endregion
|
|
83
82
|
export { createWorkflowTool };
|
|
84
83
|
|
|
85
84
|
//# sourceMappingURL=create-workflow.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { deleteWorkflow } from "../../workflows/service.js";
|
|
2
2
|
import { createTool } from "@mastra/core/tools";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/tools/workflows/delete-workflow.ts
|
|
5
5
|
const deleteWorkflowTool = createTool({
|
|
6
6
|
id: "delete-workflow",
|
|
7
7
|
description: "Remove a saved workflow from storage and unregister the live in-process Workflow instance. Idempotent. Subsequent save-workflow calls with the same id re-register cleanly.",
|
|
@@ -15,7 +15,6 @@ const deleteWorkflowTool = createTool({
|
|
|
15
15
|
return deleteWorkflow(mastra, id);
|
|
16
16
|
}
|
|
17
17
|
});
|
|
18
|
-
//#endregion
|
|
19
18
|
export { deleteWorkflowTool };
|
|
20
19
|
|
|
21
20
|
//# sourceMappingURL=delete-workflow.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY, RequestContext } from "@mastra/core/request-context";
|
|
2
|
-
|
|
2
|
+
// src/tools/workflows/ephemeral-memory.ts
|
|
3
3
|
/**
|
|
4
4
|
* Sub-invocations launched from a parent chat turn (workflow agent steps,
|
|
5
5
|
* sub-agent tool calls) must run under a fresh isolated Mastra memory scope
|
|
@@ -38,7 +38,6 @@ async function withEphemeralMemory(requestContext, fn, options = {}) {
|
|
|
38
38
|
else childRequestContext.delete(MASTRA_RESOURCE_ID_KEY);
|
|
39
39
|
return fn(childRequestContext);
|
|
40
40
|
}
|
|
41
|
-
//#endregion
|
|
42
41
|
export { withEphemeralMemory };
|
|
43
42
|
|
|
44
43
|
//# sourceMappingURL=ephemeral-memory.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/tools/workflows/extract-json-schema.ts
|
|
2
2
|
/**
|
|
3
3
|
* Extract a JSON Schema from a Mastra tool's schema field. Tools created via
|
|
4
4
|
* `createTool({...})` wrap their Zod schemas with `toStandardSchema`, exposing
|
|
@@ -16,7 +16,6 @@ function extractJsonSchema(maybeSchema, direction) {
|
|
|
16
16
|
return;
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
|
-
//#endregion
|
|
20
19
|
export { extractJsonSchema };
|
|
21
20
|
|
|
22
21
|
//# sourceMappingURL=extract-json-schema.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getWorkflow } from "../../workflows/service.js";
|
|
2
2
|
import { createTool } from "@mastra/core/tools";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/tools/workflows/get-workflow.ts
|
|
5
5
|
const getWorkflowTool = createTool({
|
|
6
6
|
id: "get-workflow",
|
|
7
7
|
description: "Return the full stored definition of a workflow (input/output schemas + the step graph).",
|
|
@@ -28,7 +28,6 @@ const getWorkflowTool = createTool({
|
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
30
|
});
|
|
31
|
-
//#endregion
|
|
32
31
|
export { getWorkflowTool };
|
|
33
32
|
|
|
34
33
|
//# sourceMappingURL=get-workflow.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createTool } from "@mastra/core/tools";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
|
|
3
|
+
// src/tools/workflows/list-available-agents.ts
|
|
4
4
|
/**
|
|
5
5
|
* Sub-agent tool: list agents the workflow-builder can reference in agent-step
|
|
6
6
|
* entries of a Dynamic Workflow graph. Read-only.
|
|
@@ -26,7 +26,6 @@ const listAvailableAgentsTool = createTool({
|
|
|
26
26
|
})) };
|
|
27
27
|
}
|
|
28
28
|
});
|
|
29
|
-
//#endregion
|
|
30
29
|
export { listAvailableAgentsTool };
|
|
31
30
|
|
|
32
31
|
//# sourceMappingURL=list-available-agents.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createTool } from "@mastra/core/tools";
|
|
2
2
|
import { z } from "zod";
|
|
3
|
-
|
|
3
|
+
// src/tools/workflows/list-available-classifiers.ts
|
|
4
4
|
function describeQuestions(questions) {
|
|
5
5
|
if (!questions) return void 0;
|
|
6
6
|
return Object.entries(questions).map(([id, question]) => ({
|
|
@@ -50,7 +50,6 @@ const listAvailableClassifiersTool = createTool({
|
|
|
50
50
|
})) };
|
|
51
51
|
}
|
|
52
52
|
});
|
|
53
|
-
//#endregion
|
|
54
53
|
export { listAvailableClassifiersTool };
|
|
55
54
|
|
|
56
55
|
//# sourceMappingURL=list-available-classifiers.js.map
|
|
@@ -2,7 +2,7 @@ import { WORKFLOW_BUILDER_NOISE_TOOL_IDS } from "./tool-ids.js";
|
|
|
2
2
|
import { extractJsonSchema } from "./extract-json-schema.js";
|
|
3
3
|
import { createTool } from "@mastra/core/tools";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
-
|
|
5
|
+
// src/tools/workflows/list-available-tools.ts
|
|
6
6
|
/**
|
|
7
7
|
* Sub-agent tool: list tools the workflow-builder can reference in tool-step
|
|
8
8
|
* entries of a Dynamic Workflow graph. Returns JSON Schema for inputs/outputs
|
|
@@ -34,7 +34,6 @@ const listAvailableToolsTool = createTool({
|
|
|
34
34
|
}) };
|
|
35
35
|
}
|
|
36
36
|
});
|
|
37
|
-
//#endregion
|
|
38
37
|
export { listAvailableToolsTool };
|
|
39
38
|
|
|
40
39
|
//# sourceMappingURL=list-available-tools.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { extractJsonSchema } from "./extract-json-schema.js";
|
|
2
2
|
import { createTool } from "@mastra/core/tools";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/tools/workflows/list-available-workflows.ts
|
|
5
5
|
const listAvailableWorkflowsTool = createTool({
|
|
6
6
|
id: "list-available-workflows",
|
|
7
7
|
description: "Returns the workflows currently registered on the Mastra instance (both code-defined and dynamic). The ids returned here are the only valid values you can put in `{ type: \"workflow\", workflowId }` graph entries. Each row includes `inputSchema` and `outputSchema` as JSON Schema — read them to know what shape the nested workflow expects and produces; never invent field names.",
|
|
@@ -26,7 +26,6 @@ const listAvailableWorkflowsTool = createTool({
|
|
|
26
26
|
}) };
|
|
27
27
|
}
|
|
28
28
|
});
|
|
29
|
-
//#endregion
|
|
30
29
|
export { listAvailableWorkflowsTool };
|
|
31
30
|
|
|
32
31
|
//# sourceMappingURL=list-available-workflows.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { listWorkflows } from "../../workflows/service.js";
|
|
2
2
|
import { createTool } from "@mastra/core/tools";
|
|
3
3
|
import { z } from "zod";
|
|
4
|
-
|
|
4
|
+
// src/tools/workflows/list-workflows.ts
|
|
5
5
|
const listWorkflowsTool = createTool({
|
|
6
6
|
id: "list-workflows",
|
|
7
7
|
description: "List active Dynamic Workflows persisted to storage. Returns id + description + status for each.",
|
|
@@ -27,7 +27,6 @@ const listWorkflowsTool = createTool({
|
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
29
|
});
|
|
30
|
-
//#endregion
|
|
31
30
|
export { listWorkflowsTool };
|
|
32
31
|
|
|
33
32
|
//# sourceMappingURL=list-workflows.js.map
|