@mastra/code-sdk 1.19.0-alpha.1 → 1.19.0-alpha.10

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.
Files changed (66) hide show
  1. package/dist/acp/runtime.d.ts.map +1 -1
  2. package/dist/acp/runtime.js +1 -0
  3. package/dist/acp/runtime.js.map +1 -1
  4. package/dist/agent-connections/tools.d.ts.map +1 -1
  5. package/dist/agent-connections/tools.js +67 -2
  6. package/dist/agent-connections/tools.js.map +1 -1
  7. package/dist/agents/fastembed-subprocess.d.ts +31 -0
  8. package/dist/agents/fastembed-subprocess.d.ts.map +1 -0
  9. package/dist/agents/fastembed-subprocess.js +202 -0
  10. package/dist/agents/fastembed-subprocess.js.map +1 -0
  11. package/dist/agents/instructions.d.ts +5 -2
  12. package/dist/agents/instructions.d.ts.map +1 -1
  13. package/dist/agents/instructions.js +4 -2
  14. package/dist/agents/instructions.js.map +1 -1
  15. package/dist/agents/mastracode-gateway.d.ts.map +1 -1
  16. package/dist/agents/mastracode-gateway.js +2 -2
  17. package/dist/agents/mastracode-gateway.js.map +1 -1
  18. package/dist/agents/memory.d.ts.map +1 -1
  19. package/dist/agents/memory.js +4 -6
  20. package/dist/agents/memory.js.map +1 -1
  21. package/dist/agents/model.d.ts.map +1 -1
  22. package/dist/agents/model.js +10 -5
  23. package/dist/agents/model.js.map +1 -1
  24. package/dist/agents/modes/build.js +1 -1
  25. package/dist/agents/modes/build.js.map +1 -1
  26. package/dist/agents/modes/plan.js +1 -1
  27. package/dist/agents/modes/plan.js.map +1 -1
  28. package/dist/agents/prompts/index.d.ts.map +1 -1
  29. package/dist/agents/prompts/index.js +1 -0
  30. package/dist/agents/prompts/index.js.map +1 -1
  31. package/dist/agents/prompts/plan.d.ts +2 -0
  32. package/dist/agents/prompts/plan.d.ts.map +1 -1
  33. package/dist/agents/prompts/plan.js +10 -8
  34. package/dist/agents/prompts/plan.js.map +1 -1
  35. package/dist/agents/sandbox-filesystem.d.ts +25 -0
  36. package/dist/agents/sandbox-filesystem.d.ts.map +1 -1
  37. package/dist/agents/sandbox-filesystem.js +47 -6
  38. package/dist/agents/sandbox-filesystem.js.map +1 -1
  39. package/dist/auth/account-rotation-processor.d.ts +23 -0
  40. package/dist/auth/account-rotation-processor.d.ts.map +1 -1
  41. package/dist/auth/account-rotation-processor.js +63 -1
  42. package/dist/auth/account-rotation-processor.js.map +1 -1
  43. package/dist/auth/index.js +2 -2
  44. package/dist/auth/storage.d.ts +8 -0
  45. package/dist/auth/storage.d.ts.map +1 -1
  46. package/dist/auth/storage.js +37 -3
  47. package/dist/auth/storage.js.map +1 -1
  48. package/dist/experimental-agent.d.ts +8 -0
  49. package/dist/experimental-agent.d.ts.map +1 -1
  50. package/dist/experimental-agent.js +12 -1
  51. package/dist/experimental-agent.js.map +1 -1
  52. package/dist/headless/cli.d.ts.map +1 -1
  53. package/dist/headless/cli.js +2 -1
  54. package/dist/headless/cli.js.map +1 -1
  55. package/dist/index.d.ts +2 -0
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +10 -3
  58. package/dist/index.js.map +1 -1
  59. package/dist/onboarding/settings.d.ts +4 -0
  60. package/dist/onboarding/settings.d.ts.map +1 -1
  61. package/dist/onboarding/settings.js +6 -2
  62. package/dist/onboarding/settings.js.map +1 -1
  63. package/dist/utils/token-estimator.d.ts.map +1 -1
  64. package/dist/utils/token-estimator.js +2 -1
  65. package/dist/utils/token-estimator.js.map +1 -1
  66. package/package.json +11 -11
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","names":[],"sources":["../../src/auth/storage.ts"],"sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n */\n\nimport { createHash } from 'node:crypto';\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { getAppDataDir } from '../utils/project.js';\nimport { anthropicOAuthProvider } from './providers/anthropic.js';\nimport { githubCopilotOAuthProvider } from './providers/github-copilot.js';\nimport { kimiCodingOAuthProvider } from './providers/kimi-coding.js';\nimport { openaiCodexOAuthProvider } from './providers/openai-codex.js';\nimport { xaiOAuthProvider } from './providers/xai.js';\nimport type {\n AuthCredential,\n AuthStorageData,\n OAuthAccountRecord,\n OAuthCredential,\n OAuthCredentialSnapshot,\n OAuthCredentials,\n OAuthLoginCallbacks,\n OAuthProviderId,\n OAuthProviderInterface,\n} from './types.js';\n\n/**\n * Best/default models for each OAuth provider.\n * Used when auto-selecting a model after login.\n */\nexport const PROVIDER_DEFAULT_MODELS: Record<OAuthProviderId, string> = {\n anthropic: 'anthropic/claude-fable-5',\n 'openai-codex': 'openai/gpt-5.6-sol',\n // gpt-4.1 routes through `/chat/completions` (which our OpenAI-compatible\n // adapter handles); Anthropic-shaped Copilot models (Claude on `/v1/messages`)\n // are not yet wired up, so picking one as the post-login default would error.\n 'github-copilot': 'github-copilot/gpt-4.1',\n 'kimi-for-coding': 'kimi-code-plan-cn/kimi-for-coding',\n xai: 'xai/grok-4.5',\n};\n\n// Provider registry\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>([\n [anthropicOAuthProvider.id, anthropicOAuthProvider],\n [openaiCodexOAuthProvider.id, openaiCodexOAuthProvider],\n [githubCopilotOAuthProvider.id, githubCopilotOAuthProvider],\n [kimiCodingOAuthProvider.id, kimiCodingOAuthProvider],\n [xaiOAuthProvider.id, xaiOAuthProvider],\n]);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n return oauthProviderRegistry.get(id);\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n return Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * Mint an account instance id: `${providerId}:${randomUUID()}`.\n *\n * Assigned once, when the account is created, and never derived from\n * credentials. Deriving it from the refresh token (the pre-A13 scheme) looked\n * stable but was not: `persistRefreshedCredential` keeps an entry's key while\n * writing rotated tokens onto it, so every refresh left the id describing a\n * credential the account no longer had — and re-adding that same subscription\n * then failed to match its own entry and registered a second one for it.\n */\nfunction mintAccountId(providerId: string): string {\n return `${providerId}:${globalThis.crypto.randomUUID()}`;\n}\n\n/**\n * The pre-A13 id scheme: `${providerId}:${sha256(refresh).slice(0,8)}`.\n *\n * No longer used to assign ids, but still needed to recognize registries\n * written before A13 — both to match a re-authorized account onto its existing\n * entry, and to recognize entries whose fields the A13 migration must backfill.\n */\nfunction legacyAccountIdFor(providerId: string, refreshToken: string): string {\n return `${providerId}:${createHash('sha256').update(refreshToken).digest('hex').slice(0, 8)}`;\n}\n\n/**\n * Stable identity for the *subscription* behind an account, when the provider\n * exposes one (an account id, an email — anything that survives a refresh and\n * a re-authorization). Used to decide whether an added account is one we\n * already have. Providers whose credentials carry no such identifier return\n * undefined; for those, a re-authorization is indistinguishable from a new\n * account without spending a request.\n */\nfunction providerIdentity(provider: OAuthProviderInterface | undefined, creds: OAuthCredentials): string | undefined {\n try {\n const identity = provider?.getAccountIdentity?.(creds);\n return typeof identity === 'string' && identity.length > 0 ? identity : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isOAuthAccountRecord(value: unknown): value is OAuthAccountRecord {\n if (!value || typeof value !== 'object') return false;\n const v = value as Partial<OAuthAccountRecord>;\n return (\n v.type === 'oauth-account' &&\n typeof v.id === 'string' &&\n typeof v.label === 'string' &&\n typeof v.addedAt === 'string' &&\n typeof v.active === 'boolean' &&\n typeof v.refresh === 'string' &&\n typeof v.access === 'string' &&\n typeof v.expires === 'number'\n );\n}\n\n/** The credential fields of an account record — everything but registry identity. */\nfunction credentialFieldsOf(record: OAuthAccountRecord): OAuthCredentials {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n identity: _identity,\n ...creds\n } = record;\n return creds;\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n private data: AuthStorageData = {};\n private refreshPromises = new Map<string, Promise<OAuthCredentials | undefined>>();\n\n constructor(private authPath: string = join(getAppDataDir(), 'auth.json')) {\n this.reload();\n }\n\n /**\n * Reload credentials from disk.\n */\n reload(): void {\n if (!existsSync(this.authPath)) {\n this.data = {};\n return;\n }\n try {\n this.data = JSON.parse(readFileSync(this.authPath, 'utf-8'));\n } catch {\n this.data = {};\n }\n this.migrate();\n }\n\n /**\n * Bring auth.json up to the multi-account registry format. Runs on every\n * load; saves only when something actually changed.\n *\n * 1. A legacy OAuth slot with no registry gets one adopted active entry\n * (the slot's tokens stay put — the entry mirrors them).\n * 2. When the slot's refresh token differs from the active entry's, an\n * external writer (older build, another worktree) owns the slot — the\n * slot wins and its tokens are adopted onto the active entry.\n * 3. A registry with no active entry (hand-edited) self-heals to its first\n * entry; malformed `accounts:` values are skipped, never fatal.\n * 4. A registry whose legacy slot disappeared (partial write, an external\n * hand-edit) self-heals by mirroring the active entry's tokens back into\n * the slot, so `isLoggedIn()`/`getOAuthCredential()` keep agreeing with\n * `listAccounts()`. `remove()`/`logout()` clear the registry with the\n * slot, so they never leave the shape this heals.\n */\n private migrate(): void {\n let changed = false;\n for (const key of Object.keys(this.data)) {\n const slot = this.data[key];\n if (!slot || slot.type !== 'oauth') continue;\n const providerId = key;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) {\n this.adoptSlot(providerId, slot);\n changed = true;\n continue;\n }\n const active = entries.find(entry => entry.active);\n if (!active) {\n this.data[this.accountKeyFor(entries[0]!.id)] = { ...entries[0]!, active: true };\n changed = true;\n continue;\n }\n if (active.refresh !== slot.refresh) {\n // An external writer (older build, another worktree) owns the slot.\n // If its tokens belong to a different registered account, that\n // account is now the active one — re-point activation to it instead\n // of cloning the refresh token onto the current active entry.\n const matching = entries.find(entry => entry.id !== active.id && entry.refresh === slot.refresh);\n if (matching) {\n const { type: _t, ...slotCreds } = slot;\n this.data[this.accountKeyFor(matching.id)] = {\n ...matching,\n ...slotCreds,\n type: 'oauth-account',\n active: true,\n };\n this.data[this.accountKeyFor(active.id)] = { ...active, active: false };\n changed = true;\n } else {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(active.id)] = { ...active, ...slotCreds, type: 'oauth-account' };\n changed = true;\n }\n }\n }\n\n // Case 4: registry entries without a legacy slot (the slot loop above\n // only ever sees providers that still have one).\n const registeredProviders = new Set<string>();\n for (const key of Object.keys(this.data)) {\n if (!key.startsWith('accounts:')) continue;\n const providerId = key.slice('accounts:'.length).split(':')[0];\n if (providerId) registeredProviders.add(providerId);\n }\n for (const providerId of registeredProviders) {\n if (this.data[providerId]?.type === 'oauth') continue;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) continue;\n let active = entries.find(entry => entry.active);\n if (!active) {\n active = entries[0]!;\n this.data[this.accountKeyFor(active.id)] = { ...active, active: true };\n }\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(active) };\n changed = true;\n }\n\n // Case 5 (A13): backfill the stable account identity on entries that\n // predate it, so adding a subscription we already hold updates its entry\n // instead of registering a second one for it.\n //\n // Ids are deliberately left exactly as they are. Ids are minted once and\n // derive from nothing (A13), so there is nothing to repair — and re-keying\n // a live registry would invalidate every id persisted outside this file\n // (settings routing preferences, per-thread routing state) for no gain.\n for (const providerId of registeredProviders) {\n const provider = getOAuthProvider(providerId as OAuthProviderId);\n if (!provider?.getAccountIdentity) continue;\n for (const entry of this.accountEntries(providerId)) {\n if (entry.identity) continue;\n const identity = providerIdentity(provider, entry);\n if (!identity) continue;\n this.data[this.accountKeyFor(entry.id)] = { ...entry, identity };\n changed = true;\n }\n }\n\n if (changed) this.save();\n }\n\n /**\n * Save credentials to disk.\n */\n private save(): void {\n const dir = dirname(this.authPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n // Write to a sibling file, then atomically replace auth.json. Provider\n // fetch wrappers reload this file on every request, including in older\n // Mastra Code processes; writing in place lets them observe truncated JSON\n // and temporarily treat every provider as logged out.\n const tempPath = `${this.authPath}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, JSON.stringify(this.data, null, 2), { encoding: 'utf-8', mode: 0o600 });\n chmodSync(tempPath, 0o600);\n renameSync(tempPath, this.authPath);\n } finally {\n rmSync(tempPath, { force: true });\n }\n }\n\n /**\n * Get credential for a provider. Registry entries (type 'oauth-account')\n * live under `accounts:` keys and never surface here.\n */\n get(provider: string): AuthCredential | undefined {\n const cred = this.data[provider];\n return cred !== undefined && cred.type !== 'oauth-account' ? cred : undefined;\n }\n\n /**\n * Set credential for a provider.\n */\n set(provider: string, credential: AuthCredential): void {\n this.reload();\n this.data[provider] = credential;\n this.save();\n }\n\n /**\n * Remove credential for a provider, including its account registry.\n * Clearing only the slot would leave the registry behind, and the next\n * load's migration would heal the slot back from it — resurrecting the\n * provider the caller just signed out.\n */\n remove(provider: string): void {\n this.reload();\n delete this.data[provider];\n const prefix = this.accountPrefixFor(provider);\n for (const key of Object.keys(this.data)) {\n if (key.startsWith(prefix)) delete this.data[key];\n }\n this.save();\n }\n\n /**\n * List all providers with credentials.\n */\n list(): string[] {\n return Object.keys(this.data);\n }\n\n /**\n * Check if credentials exist for a provider.\n */\n has(provider: string): boolean {\n return provider in this.data;\n }\n\n /**\n * Check if logged in via OAuth for a provider.\n */\n isLoggedIn(provider: string): boolean {\n const cred = this.data[provider];\n return cred?.type === 'oauth';\n }\n\n /**\n * Check if a stored API key exists for a provider.\n * Keys are stored under `apikey:<provider>` in auth.json.\n */\n hasStoredApiKey(provider: string): boolean {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0;\n }\n\n /**\n * Get a stored API key for a provider, if any.\n */\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0 ? cred.key : undefined;\n }\n\n /**\n * Store an API key for a provider.\n * Also sets the corresponding environment variable so model resolution can find it.\n */\n setStoredApiKey(provider: string, key: string, envVar?: string): void {\n this.set(`apikey:${provider}`, { type: 'api_key', key });\n if (envVar) {\n process.env[envVar] = key;\n }\n }\n\n /**\n * Load all stored API keys into process.env.\n * Called at startup so model resolution can find stored keys.\n * Only sets env vars that aren't already set (env vars take precedence).\n */\n loadStoredApiKeysIntoEnv(providerEnvVars: Record<string, string | undefined>): void {\n for (const [key, cred] of Object.entries(this.data)) {\n if (!key.startsWith('apikey:') || cred.type !== 'api_key' || !cred.key) continue;\n const provider = key.substring('apikey:'.length);\n const envVar = providerEnvVars[provider];\n if (envVar && !process.env[envVar]) {\n process.env[envVar] = cred.key;\n }\n }\n }\n\n /**\n * Login to an OAuth provider. Resolves to the registered account record.\n * Pass `activate: false` to add the account without making it active (the\n * first account for a provider is always activated — a provider with\n * accounts must have an active one).\n */\n async login(\n providerId: OAuthProviderId,\n callbacks: OAuthLoginCallbacks,\n opts?: { replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n const provider = getOAuthProvider(providerId);\n if (!provider) {\n throw new Error(`Unknown OAuth provider: ${providerId}`);\n }\n\n const credentials = await provider.login(callbacks);\n // Route through the account registry: the new account is appended (or\n // updated in place — by id collision or an explicit replaceAccountId for\n // re-authentication) and becomes the active account unless activate:false.\n return this.addAccount(providerId, credentials, opts);\n }\n\n /**\n * Logout from a provider: remove the legacy slot and every registered account.\n */\n logout(provider: string): void {\n this.remove(provider);\n }\n\n // ---------------------------------------------------------------------------\n // Multi-account registry\n // ---------------------------------------------------------------------------\n\n private accountPrefixFor(providerId: string): string {\n return `accounts:${providerId}:`;\n }\n\n private accountKeyFor(id: string): string {\n return `accounts:${id}`;\n }\n\n /** Registry entries for a provider in JSON insertion order (malformed values skipped). */\n private accountEntries(providerId: string): OAuthAccountRecord[] {\n const prefix = this.accountPrefixFor(providerId);\n const out: OAuthAccountRecord[] = [];\n for (const [key, value] of Object.entries(this.data)) {\n if (key.startsWith(prefix) && isOAuthAccountRecord(value)) out.push(value);\n }\n return out;\n }\n\n /** Adopt a legacy slot credential as the registry's first active entry. */\n private adoptSlot(providerId: string, slot: OAuthCredential): OAuthAccountRecord {\n const id = mintAccountId(providerId);\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, slot);\n const record: OAuthAccountRecord = {\n ...slot,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: `${provider?.name ?? providerId} account 1`,\n addedAt: new Date().toISOString(),\n active: true,\n };\n this.data[this.accountKeyFor(id)] = record;\n return record;\n }\n\n /**\n * Registered OAuth accounts for a provider, in insertion order. Copies —\n * callers cannot corrupt unsaved storage state by mutating a record.\n */\n listAccounts(providerId: string): OAuthAccountRecord[] {\n return this.accountEntries(providerId).map(entry => ({ ...entry }));\n }\n\n /**\n * The provider's active registry entry, if a registry exists. A copy.\n */\n getActiveAccount(providerId: string): OAuthAccountRecord | undefined {\n const active = this.accountEntries(providerId).find(entry => entry.active);\n return active ? { ...active } : undefined;\n }\n\n /**\n * Register OAuth credentials as an account for a provider, making it active\n * unless `activate: false` is passed.\n *\n * With `replaceAccountId` (re-authentication of a picked account), the\n * target entry's tokens are replaced in place — id re-keyed to the new\n * refresh-token hash, label/position/addedAt preserved — because providers\n * rotate refresh tokens per authorization, so the picked account's old id\n * never matches the new token hash. Re-authentication keeps the target's\n * active state: an inactive account stays inactive and the currently active\n * account keeps the legacy slot. Otherwise, when the new credentials\n * hash to an existing entry's id (same refresh token), that entry is\n * updated in place; a genuinely new account is appended and activated.\n *\n * `activate: false` only applies to the plain add path: the new/updated entry\n * keeps the active state it had, and the previously active account stays\n * active. The first account of a provider is activated regardless.\n */\n async addAccount(\n providerId: string,\n creds: OAuthCredentials,\n opts?: { label?: string; replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n this.reload();\n const entries = this.accountEntries(providerId);\n\n if (opts?.replaceAccountId) {\n const target = entries.find(entry => entry.id === opts.replaceAccountId);\n if (!target) {\n throw new Error(`No account ${opts.replaceAccountId} for provider ${providerId}`);\n }\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds) ?? target.identity;\n // Re-authentication updates the account in place and **keeps its id**:\n // ids are minted once and never derived from credentials (A13), so the\n // entry's insertion position, the settings routing preference and any\n // thread routing state that name this id all stay valid.\n //\n // A stale entry for the *same* subscription is dropped in favor of the\n // picked account. Same-subscription is a matching stable identity, or —\n // for a registry written before A13, whose ids were the refresh-token\n // hash — the credentials' own legacy id, or an entry already holding\n // exactly these credentials (a re-authorization that returns the same\n // tokens, the only signal an identity-less provider gives). The survivor\n // inherits the collided entry's active state, so re-authenticating an\n // inactive account onto the active account's credentials cannot leave the\n // registry with no active entry.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const collided = entries.find(\n entry =>\n entry.id !== target.id &&\n ((identity !== undefined && entry.identity === identity) ||\n entry.id === legacyId ||\n entry.refresh === creds.refresh),\n );\n // Credential metadata (device id, enterprise URL, …) follows the tokens:\n // when the fresh response omits a field, the collided entry's value is the\n // coherent fallback, not the target's — pairing fresh tokens with another\n // subscription's stale endpoint would misroute requests. Fresh `creds`\n // win last; only the target's registry metadata (id, label, addedAt)\n // carries over.\n const replacement: OAuthAccountRecord = {\n ...target,\n ...(collided ? credentialFieldsOf(collided) : {}),\n ...creds,\n type: 'oauth-account',\n ...(identity ? { identity } : {}),\n label: opts.label ?? target.label,\n };\n const rebuilt: AuthStorageData = {};\n for (const [key, value] of Object.entries(this.data)) {\n if (key === this.accountKeyFor(target.id)) {\n rebuilt[key] = collided?.active ? { ...replacement, active: true } : replacement;\n } else if (collided && key === this.accountKeyFor(collided.id)) {\n continue;\n } else {\n rebuilt[key] = value;\n }\n }\n this.data = rebuilt;\n // Re-authentication preserves the account's active state: fixing a\n // secondary account's tokens must not hijack the active slot. The target\n // is activated when it was already active, when the entry it collided\n // with was active, or when the provider has no active account at all\n // (first account, or a self-healed gap).\n const wasActive =\n target.active === true ||\n collided?.active === true ||\n entries.some(entry => entry.active && entry.id !== target.id) === false;\n if (wasActive) {\n const activated = this.activateInMemory(providerId, target.id);\n if (!activated) {\n throw new Error(`Failed to activate account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n // Inactive target: tokens stay on the registry entry, the legacy slot\n // keeps the currently active account's credential untouched.\n const replacementEntry = this.accountEntries(providerId).find(entry => entry.id === target.id);\n if (!replacementEntry) {\n throw new Error(`Failed to store account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return replacementEntry;\n }\n\n // Resolve the label before the final reload+save: the provider hook may\n // hit the network, and a concurrent write during that await must not be\n // clobbered by a stale snapshot.\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds);\n const label = opts?.label ?? (await provider?.getAccountLabel?.(creds)) ?? null;\n this.reload();\n const freshEntries = this.accountEntries(providerId);\n\n // Is this a subscription we already hold? Match the provider's stable\n // account identity where it exposes one, then the pre-A13 id (the\n // refresh-token hash) so a pre-A13 registry still updates its entry rather\n // than gaining a second one for the same subscription, and finally an\n // entry already holding these exact credentials (a re-add of the same\n // account as returned, which is the only signal an identity-less provider\n // such as Anthropic gives us — a provider that cannot name its accounts\n // cannot say \"this is the same subscription, re-authorized\").\n //\n // Crucially this must not re-derive the id of a *minted* entry: after a\n // refresh such an entry's id no longer hashes its current token, and\n // treating that miss as \"new account\" is exactly how re-adding a\n // subscription used to create a duplicate entry for it.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const existing =\n (identity ? freshEntries.find(entry => entry.identity === identity) : undefined) ??\n freshEntries.find(entry => entry.id === legacyId) ??\n freshEntries.find(entry => entry.refresh === creds.refresh);\n const id = existing?.id ?? mintAccountId(providerId);\n if (existing) {\n this.data[this.accountKeyFor(id)] = {\n ...existing,\n ...creds,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n active: existing.active,\n };\n } else {\n const resolvedLabel = label ?? `${provider?.name ?? providerId} account ${freshEntries.length + 1}`;\n this.data[this.accountKeyFor(id)] = {\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: resolvedLabel,\n addedAt: new Date().toISOString(),\n active: false,\n ...creds,\n };\n }\n\n // activate:false (add-another): keep the current active account. The\n // first account of a provider always activates — a non-empty registry\n // must have an active entry. An id collision with the already-active\n // entry also falls through to activateInMemory so its fresh tokens move\n // into the legacy slot (tokens are single-homed).\n if (opts?.activate === false && freshEntries.length > 0 && !existing?.active) {\n this.save();\n return { ...(this.data[this.accountKeyFor(id)] as OAuthAccountRecord) };\n }\n\n const activated = this.activateInMemory(providerId, id);\n if (!activated) {\n throw new Error(`Failed to activate account ${id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n\n /**\n * Activate an account: move the active tokens out of the legacy slot back\n * into the previously active entry, and the target's tokens into the slot\n * (never copy — one home per token set). With no `instanceId`, rotate to\n * the next entry in insertion order, wrapping once to the front; returns\n * undefined when there is no other entry to rotate to.\n */\n activateAccount(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n this.reload();\n const activated = this.activateInMemory(providerId, instanceId);\n if (activated) this.save();\n return activated;\n }\n\n /**\n * Activate an account in memory only — the caller owns reload/save. Move the\n * active tokens out of the legacy slot back into the previously active\n * entry, and the target's tokens into the slot (never copy — one home per\n * token set). With no `instanceId`, rotate to the next entry in insertion\n * order, wrapping once to the front; returns undefined when there is no\n * other entry to rotate to.\n */\n private activateInMemory(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) return undefined;\n\n let target: OAuthAccountRecord | undefined;\n if (instanceId !== undefined) {\n target = entries.find(entry => entry.id === instanceId);\n if (!target) return undefined;\n } else {\n if (entries.length <= 1) return undefined;\n const currentIdx = entries.findIndex(entry => entry.active);\n const candidates =\n currentIdx >= 0 ? [...entries.slice(currentIdx + 1), ...entries.slice(0, currentIdx)] : [...entries];\n target = candidates[0]!;\n }\n if (!target) return undefined;\n\n const slot = this.data[providerId];\n const current = entries.find(entry => entry.active && entry.id !== target.id);\n\n // Move the slot's tokens back onto the previously active entry. Skipped\n // when the target is already active — its (possibly re-authenticated)\n // entry already holds the freshest tokens.\n if (current && slot?.type === 'oauth') {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(current.id)] = { ...current, ...slotCreds, type: 'oauth-account', active: false };\n }\n\n // Move the target's tokens into the legacy slot. The slot is rebuilt from\n // the target's own credentials only: carrying fields over from the\n // previously active account would pair this account's tokens with that\n // account's metadata (`deviceId`, `enterpriseUrl`, account id), and the\n // providers read those fields off the slot.\n this.data[providerId] = { ...credentialFieldsOf(target), type: 'oauth' };\n\n // Exactly the target stays active (self-heals multi-active states).\n this.data[this.accountKeyFor(target.id)] = { ...target, active: true };\n for (const entry of entries) {\n if (entry.id === target.id || entry.id === current?.id) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n\n return { ...target, active: true };\n }\n\n /**\n * Remove an account from the registry. If it was active, the next entry in\n * insertion order is activated; when it was the last one, the legacy slot\n * is removed too (full sign-out for that provider).\n */\n removeAccount(providerId: string, instanceId: string): void {\n this.reload();\n const entries = this.accountEntries(providerId);\n const target = entries.find(entry => entry.id === instanceId);\n if (!target) return;\n\n const wasActive = target.active;\n delete this.data[this.accountKeyFor(instanceId)];\n\n if (wasActive) {\n const idx = entries.indexOf(target);\n const next = entries[idx + 1] ?? entries.find(entry => entry.id !== instanceId);\n if (next) {\n // The removed account's tokens die with it — only move tokens in.\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(next) };\n this.data[this.accountKeyFor(next.id)] = { ...next, active: true };\n for (const entry of entries) {\n if (entry.id === next.id || entry.id === instanceId) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n } else {\n delete this.data[providerId];\n }\n }\n\n this.save();\n }\n\n /**\n * Rename an account's label.\n */\n renameAccount(providerId: string, instanceId: string, label: string): void {\n this.reload();\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, label };\n this.save();\n }\n\n /**\n * Persist refreshed credentials for the account that initiated the refresh.\n * The legacy slot is updated only if that account is still active when the\n * refresh completes; otherwise a delayed refresh could overwrite a newer\n * activation.\n */\n private persistRefreshedCredential(\n providerId: string,\n instanceId: string | undefined,\n creds: OAuthCredentials,\n ): void {\n this.reload();\n if (instanceId) {\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, ...creds, type: 'oauth-account' };\n if (entry.active) {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n } else {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n this.save();\n }\n\n /**\n * Refresh one account instance through the per-instance dedupe map. Used\n * for sibling refreshes during the rotation walk, so a concurrent\n * `getApiKey` that reloads storage mid-walk (after the candidate was\n * activated but before its refresh resolves) joins the same refresh\n * instead of double-spending a single-use refresh token.\n */\n private async refreshInstance(\n providerId: string,\n instanceId: string,\n creds: OAuthCredentials,\n ): Promise<OAuthCredentials | undefined> {\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const refreshKey = `${providerId}:${instanceId}`;\n const pending = this.refreshPromises.get(refreshKey);\n if (pending) return pending;\n const refresh = (async () => {\n try {\n const fresh = await provider.refreshToken(creds);\n this.persistRefreshedCredential(providerId, instanceId, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n this.refreshPromises.set(refreshKey, refresh);\n try {\n return await refresh;\n } finally {\n this.refreshPromises.delete(refreshKey);\n }\n }\n\n /**\n * Get a ready-to-use OAuth credential snapshot, auto-refreshing if needed.\n * A failed refresh leaves the active account unchanged and returns undefined;\n * the account-rotation processor owns switching so it can persist a visible\n * account-switch notice with the request that triggered the change.\n */\n async getOAuthCredential(\n providerId: string,\n accountInstanceId?: string,\n ): Promise<OAuthCredentialSnapshot | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.data[providerId];\n let credential: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n credential = accountCredential;\n // The active account's credentials live in both the legacy slot and its\n // registry entry, and a legacy writer (older build, another worktree) can\n // refresh the slot without rotating the refresh token. `migrate()` only\n // reconciles those when the refresh token changes, so the registry entry\n // can hold stale access/expiry. Prefer the slot for the active account\n // and keep the registry entry as the account identity.\n if (selectedEntry.active && slot?.type === 'oauth' && slot.refresh === selectedEntry.refresh) {\n const { type: _slotType, ...slotCredential } = slot;\n credential = { ...credential, ...slotCredential };\n }\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n credential = slot;\n }\n if (!credential) return undefined;\n\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const selectedInstanceId = selectedEntry?.id;\n const toSnapshot = (credentials: OAuthCredentials): OAuthCredentialSnapshot => ({\n type: 'oauth',\n ...credentials,\n accountInstanceId: selectedInstanceId,\n });\n\n if (Date.now() < credential.expires) return toSnapshot(credential);\n\n if (selectedInstanceId) {\n const refreshed = await this.refreshInstance(providerId, selectedInstanceId, credential);\n return refreshed ? toSnapshot(refreshed) : undefined;\n }\n\n const pendingRefresh = this.refreshPromises.get(providerId);\n const refresh =\n pendingRefresh ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(credential);\n this.persistRefreshedCredential(providerId, undefined, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pendingRefresh) this.refreshPromises.set(providerId, refresh);\n try {\n const refreshed = await refresh;\n return refreshed ? toSnapshot(refreshed) : undefined;\n } finally {\n if (!pendingRefresh) this.refreshPromises.delete(providerId);\n }\n }\n\n /** Get API key for a provider, refreshing OAuth tokens if needed. */\n async getApiKey(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const cred = this.data[providerId];\n // A provider slot holding an API key belongs to the provider, not to any one\n // subscription, so it is only the right credential for a request that did\n // not select an account. A routed request must resolve the account it asked\n // for — or nothing — rather than be served this key.\n if (accountInstanceId === undefined && cred?.type === 'api_key') return cred.key;\n\n const oauth = await this.getOAuthCredential(providerId, accountInstanceId);\n const provider = oauth ? getOAuthProvider(providerId) : undefined;\n return oauth && provider ? provider.getApiKey(oauth) : undefined;\n }\n\n /**\n * Force one refresh of the active OAuth account's tokens, regardless of\n * expiry. The account-rotation error processor calls this when a provider\n * rejects a not-yet-expired token (401/403) — server-side clock skew and\n * refresh-token races surface that way. Returns the fresh access token, or\n * undefined when the refresh fails or there is no OAuth credential.\n * Shares the per-instance refresh dedupe with `getApiKey`.\n */\n async forceRefreshActiveAccount(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.get(providerId);\n let cred: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n cred = accountCredential;\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n cred = slot;\n }\n if (!cred) return undefined;\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n\n const refreshKey = selectedEntry ? `${providerId}:${selectedEntry.id}` : providerId;\n const pending = this.refreshPromises.get(refreshKey);\n const refresh =\n pending ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(cred);\n this.persistRefreshedCredential(providerId, selectedEntry?.id, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pending) this.refreshPromises.set(refreshKey, refresh);\n try {\n const creds = await refresh;\n return creds ? provider.getApiKey(creds) : undefined;\n } finally {\n if (!pending) this.refreshPromises.delete(refreshKey);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA8BA,MAAa,0BAA2D;CACtE,WAAW;CACX,gBAAgB;CAIhB,kBAAkB;CAClB,mBAAmB;CACnB,KAAK;AACP;AAGA,MAAM,wCAAwB,IAAI,IAAoC;CACpE,CAAC,uBAAuB,IAAI,sBAAsB;CAClD,CAAC,yBAAyB,IAAI,wBAAwB;CACtD,CAAC,2BAA2B,IAAI,0BAA0B;CAC1D,CAAC,wBAAwB,IAAI,uBAAuB;CACpD,CAAC,iBAAiB,IAAI,gBAAgB;AACxC,CAAC;;;;AAKD,SAAgB,iBAAiB,IAAyD;CACxF,OAAO,sBAAsB,IAAI,EAAE;AACrC;;;;AAKA,SAAgB,oBAA8C;CAC5D,OAAO,MAAM,KAAK,sBAAsB,OAAO,CAAC;AAClD;;;;;;;;;;;AAYA,SAAS,cAAc,YAA4B;CACjD,OAAO,GAAG,WAAW,GAAG,WAAW,OAAO,WAAW;AACvD;;;;;;;;AASA,SAAS,mBAAmB,YAAoB,cAA8B;CAC5E,OAAO,GAAG,WAAW,GAAG,WAAW,QAAQ,CAAC,CAAC,OAAO,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC;AAC5F;;;;;;;;;AAUA,SAAS,iBAAiB,UAA8C,OAA6C;CACnH,IAAI;EACF,MAAM,WAAW,UAAU,qBAAqB,KAAK;EACrD,OAAO,OAAO,aAAa,YAAY,SAAS,SAAS,IAAI,WAAW,KAAA;CAC1E,QAAQ;EACN;CACF;AACF;AAEA,SAAS,qBAAqB,OAA6C;CACzE,IAAI,CAAC,SAAS,OAAO,UAAU,UAAU,OAAO;CAChD,MAAM,IAAI;CACV,OACE,EAAE,SAAS,mBACX,OAAO,EAAE,OAAO,YAChB,OAAO,EAAE,UAAU,YACnB,OAAO,EAAE,YAAY,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WAAW,QAAQ,iBAAiB,UAAU,IAAI,KAAA;EACxD,OAAO,SAAS,WAAW,SAAS,UAAU,KAAK,IAAI,KAAA;CACzD;;;;;;;;;CAUA,MAAM,0BAA0B,YAAoB,mBAAyD;EAC3G,KAAK,OAAO;EACZ,MAAM,cAAc,KAAK,iBAAiB,UAAU;EACpD,MAAM,gBAAgB,oBAClB,KAAK,eAAe,UAAU,CAAC,CAAC,MAAK,UAAS,MAAM,OAAO,iBAAiB,IAC5E;EACJ,MAAM,OAAO,KAAK,IAAI,UAAU;EAChC,IAAI;EACJ,IAAI,eAAe;GACjB,MAAM,EACJ,MAAM,OACN,IAAI,KACJ,OAAO,QACP,SAAS,UACT,QAAQ,SACR,GAAG,sBACD;GACJ,OAAO;EACT,OAAO,IAAI,CAAC,qBAAqB,MAAM,SAAS,SAC9C,OAAO;EAET,IAAI,CAAC,MAAM,OAAO,KAAA;EAClB,MAAM,WAAW,iBAAiB,UAAU;EAC5C,IAAI,CAAC,UAAU,OAAO,KAAA;EAEtB,MAAM,aAAa,gBAAgB,GAAG,WAAW,GAAG,cAAc,OAAO;EACzE,MAAM,UAAU,KAAK,gBAAgB,IAAI,UAAU;EACnD,MAAM,UACJ,YACC,YAAmD;GAClD,IAAI;IACF,MAAM,QAAQ,MAAM,SAAS,aAAa,IAAI;IAC9C,KAAK,2BAA2B,YAAY,eAAe,IAAI,KAAK;IACpE,OAAO;GACT,QAAQ;IACN;GACF;EACF,EAAA,CAAG;EACL,IAAI,CAAC,SAAS,KAAK,gBAAgB,IAAI,YAAY,OAAO;EAC1D,IAAI;GACF,MAAM,QAAQ,MAAM;GACpB,OAAO,QAAQ,SAAS,UAAU,KAAK,IAAI,KAAA;EAC7C,UAAU;GACR,IAAI,CAAC,SAAS,KAAK,gBAAgB,OAAO,UAAU;EACtD;CACF;AACF"}
1
+ {"version":3,"file":"storage.js","names":[],"sources":["../../src/auth/storage.ts"],"sourcesContent":["/**\n * Credential storage for API keys and OAuth tokens.\n * Handles loading, saving, and refreshing credentials from auth.json.\n */\n\nimport { createHash } from 'node:crypto';\nimport { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { getAppDataDir } from '../utils/project.js';\nimport { anthropicOAuthProvider } from './providers/anthropic.js';\nimport { githubCopilotOAuthProvider } from './providers/github-copilot.js';\nimport { kimiCodingOAuthProvider } from './providers/kimi-coding.js';\nimport { openaiCodexOAuthProvider } from './providers/openai-codex.js';\nimport { xaiOAuthProvider } from './providers/xai.js';\nimport type {\n AuthCredential,\n AuthStorageData,\n OAuthAccountRecord,\n OAuthCredential,\n OAuthCredentialSnapshot,\n OAuthCredentials,\n OAuthLoginCallbacks,\n OAuthProviderId,\n OAuthProviderInterface,\n} from './types.js';\n\n/**\n * API keys this process exported to environment variables, keyed by variable name.\n * `previous` is the value the variable held before the first export, so removing the\n * key can restore it. Module-level because `process.env` is shared by every instance.\n */\nconst exportedApiKeys = new Map<string, { provider: string; key: string; previous: string | undefined }>();\n\nfunction exportApiKey(envVar: string, provider: string, key: string): void {\n const exported = exportedApiKeys.get(envVar);\n // Saving again keeps the value from before the first export.\n const previous = exported && process.env[envVar] === exported.key ? exported.previous : process.env[envVar];\n exportedApiKeys.set(envVar, { provider, key, previous });\n process.env[envVar] = key;\n}\n\n/**\n * Best/default models for each OAuth provider.\n * Used when auto-selecting a model after login.\n */\nexport const PROVIDER_DEFAULT_MODELS: Record<OAuthProviderId, string> = {\n anthropic: 'anthropic/claude-fable-5',\n 'openai-codex': 'openai/gpt-5.6-sol',\n // gpt-4.1 routes through `/chat/completions` (which our OpenAI-compatible\n // adapter handles); Anthropic-shaped Copilot models (Claude on `/v1/messages`)\n // are not yet wired up, so picking one as the post-login default would error.\n 'github-copilot': 'github-copilot/gpt-4.1',\n 'kimi-for-coding': 'kimi-code-plan-cn/kimi-for-coding',\n xai: 'xai/grok-4.5',\n};\n\n// Provider registry\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>([\n [anthropicOAuthProvider.id, anthropicOAuthProvider],\n [openaiCodexOAuthProvider.id, openaiCodexOAuthProvider],\n [githubCopilotOAuthProvider.id, githubCopilotOAuthProvider],\n [kimiCodingOAuthProvider.id, kimiCodingOAuthProvider],\n [xaiOAuthProvider.id, xaiOAuthProvider],\n]);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n return oauthProviderRegistry.get(id);\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n return Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * Mint an account instance id: `${providerId}:${randomUUID()}`.\n *\n * Assigned once, when the account is created, and never derived from\n * credentials. Deriving it from the refresh token (the pre-A13 scheme) looked\n * stable but was not: `persistRefreshedCredential` keeps an entry's key while\n * writing rotated tokens onto it, so every refresh left the id describing a\n * credential the account no longer had — and re-adding that same subscription\n * then failed to match its own entry and registered a second one for it.\n */\nfunction mintAccountId(providerId: string): string {\n return `${providerId}:${globalThis.crypto.randomUUID()}`;\n}\n\n/**\n * The pre-A13 id scheme: `${providerId}:${sha256(refresh).slice(0,8)}`.\n *\n * No longer used to assign ids, but still needed to recognize registries\n * written before A13 — both to match a re-authorized account onto its existing\n * entry, and to recognize entries whose fields the A13 migration must backfill.\n */\nfunction legacyAccountIdFor(providerId: string, refreshToken: string): string {\n return `${providerId}:${createHash('sha256').update(refreshToken).digest('hex').slice(0, 8)}`;\n}\n\n/**\n * Stable identity for the *subscription* behind an account, when the provider\n * exposes one (an account id, an email — anything that survives a refresh and\n * a re-authorization). Used to decide whether an added account is one we\n * already have. Providers whose credentials carry no such identifier return\n * undefined; for those, a re-authorization is indistinguishable from a new\n * account without spending a request.\n */\nfunction providerIdentity(provider: OAuthProviderInterface | undefined, creds: OAuthCredentials): string | undefined {\n try {\n const identity = provider?.getAccountIdentity?.(creds);\n return typeof identity === 'string' && identity.length > 0 ? identity : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction isOAuthAccountRecord(value: unknown): value is OAuthAccountRecord {\n if (!value || typeof value !== 'object') return false;\n const v = value as Partial<OAuthAccountRecord>;\n return (\n v.type === 'oauth-account' &&\n typeof v.id === 'string' &&\n typeof v.label === 'string' &&\n typeof v.addedAt === 'string' &&\n typeof v.active === 'boolean' &&\n typeof v.refresh === 'string' &&\n typeof v.access === 'string' &&\n typeof v.expires === 'number'\n );\n}\n\n/** The credential fields of an account record — everything but registry identity. */\nfunction credentialFieldsOf(record: OAuthAccountRecord): OAuthCredentials {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n identity: _identity,\n ...creds\n } = record;\n return creds;\n}\n\n/**\n * Credential storage backed by a JSON file.\n */\nexport class AuthStorage {\n private data: AuthStorageData = {};\n private refreshPromises = new Map<string, Promise<OAuthCredentials | undefined>>();\n\n constructor(private authPath: string = join(getAppDataDir(), 'auth.json')) {\n this.reload();\n }\n\n /**\n * Reload credentials from disk.\n */\n reload(): void {\n if (!existsSync(this.authPath)) {\n this.data = {};\n return;\n }\n try {\n this.data = JSON.parse(readFileSync(this.authPath, 'utf-8'));\n } catch {\n this.data = {};\n }\n this.migrate();\n }\n\n /**\n * Bring auth.json up to the multi-account registry format. Runs on every\n * load; saves only when something actually changed.\n *\n * 1. A legacy OAuth slot with no registry gets one adopted active entry\n * (the slot's tokens stay put — the entry mirrors them).\n * 2. When the slot's refresh token differs from the active entry's, an\n * external writer (older build, another worktree) owns the slot — the\n * slot wins and its tokens are adopted onto the active entry.\n * 3. A registry with no active entry (hand-edited) self-heals to its first\n * entry; malformed `accounts:` values are skipped, never fatal.\n * 4. A registry whose legacy slot disappeared (partial write, an external\n * hand-edit) self-heals by mirroring the active entry's tokens back into\n * the slot, so `isLoggedIn()`/`getOAuthCredential()` keep agreeing with\n * `listAccounts()`. `remove()`/`logout()` clear the registry with the\n * slot, so they never leave the shape this heals.\n */\n private migrate(): void {\n let changed = false;\n for (const key of Object.keys(this.data)) {\n const slot = this.data[key];\n if (!slot || slot.type !== 'oauth') continue;\n const providerId = key;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) {\n this.adoptSlot(providerId, slot);\n changed = true;\n continue;\n }\n const active = entries.find(entry => entry.active);\n if (!active) {\n this.data[this.accountKeyFor(entries[0]!.id)] = { ...entries[0]!, active: true };\n changed = true;\n continue;\n }\n if (active.refresh !== slot.refresh) {\n // An external writer (older build, another worktree) owns the slot.\n // If its tokens belong to a different registered account, that\n // account is now the active one — re-point activation to it instead\n // of cloning the refresh token onto the current active entry.\n const matching = entries.find(entry => entry.id !== active.id && entry.refresh === slot.refresh);\n if (matching) {\n const { type: _t, ...slotCreds } = slot;\n this.data[this.accountKeyFor(matching.id)] = {\n ...matching,\n ...slotCreds,\n type: 'oauth-account',\n active: true,\n };\n this.data[this.accountKeyFor(active.id)] = { ...active, active: false };\n changed = true;\n } else {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(active.id)] = { ...active, ...slotCreds, type: 'oauth-account' };\n changed = true;\n }\n }\n }\n\n // Case 4: registry entries without a legacy slot (the slot loop above\n // only ever sees providers that still have one).\n const registeredProviders = new Set<string>();\n for (const key of Object.keys(this.data)) {\n if (!key.startsWith('accounts:')) continue;\n const providerId = key.slice('accounts:'.length).split(':')[0];\n if (providerId) registeredProviders.add(providerId);\n }\n for (const providerId of registeredProviders) {\n if (this.data[providerId]?.type === 'oauth') continue;\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) continue;\n let active = entries.find(entry => entry.active);\n if (!active) {\n active = entries[0]!;\n this.data[this.accountKeyFor(active.id)] = { ...active, active: true };\n }\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(active) };\n changed = true;\n }\n\n // Case 5 (A13): backfill the stable account identity on entries that\n // predate it, so adding a subscription we already hold updates its entry\n // instead of registering a second one for it.\n //\n // Ids are deliberately left exactly as they are. Ids are minted once and\n // derive from nothing (A13), so there is nothing to repair — and re-keying\n // a live registry would invalidate every id persisted outside this file\n // (settings routing preferences, per-thread routing state) for no gain.\n for (const providerId of registeredProviders) {\n const provider = getOAuthProvider(providerId as OAuthProviderId);\n if (!provider?.getAccountIdentity) continue;\n for (const entry of this.accountEntries(providerId)) {\n if (entry.identity) continue;\n const identity = providerIdentity(provider, entry);\n if (!identity) continue;\n this.data[this.accountKeyFor(entry.id)] = { ...entry, identity };\n changed = true;\n }\n }\n\n if (changed) this.save();\n }\n\n /**\n * Save credentials to disk.\n */\n private save(): void {\n const dir = dirname(this.authPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n }\n // Write to a sibling file, then atomically replace auth.json. Provider\n // fetch wrappers reload this file on every request, including in older\n // Mastra Code processes; writing in place lets them observe truncated JSON\n // and temporarily treat every provider as logged out.\n const tempPath = `${this.authPath}.${process.pid}.${globalThis.crypto.randomUUID()}.tmp`;\n try {\n writeFileSync(tempPath, JSON.stringify(this.data, null, 2), { encoding: 'utf-8', mode: 0o600 });\n chmodSync(tempPath, 0o600);\n renameSync(tempPath, this.authPath);\n } finally {\n rmSync(tempPath, { force: true });\n }\n }\n\n /**\n * Get credential for a provider. Registry entries (type 'oauth-account')\n * live under `accounts:` keys and never surface here.\n */\n get(provider: string): AuthCredential | undefined {\n const cred = this.data[provider];\n return cred !== undefined && cred.type !== 'oauth-account' ? cred : undefined;\n }\n\n /**\n * Set credential for a provider.\n */\n set(provider: string, credential: AuthCredential): void {\n this.reload();\n this.data[provider] = credential;\n this.save();\n }\n\n /**\n * Remove credential for a provider, including its account registry.\n * Clearing only the slot would leave the registry behind, and the next\n * load's migration would heal the slot back from it — resurrecting the\n * provider the caller just signed out.\n */\n remove(provider: string): void {\n this.reload();\n delete this.data[provider];\n const prefix = this.accountPrefixFor(provider);\n for (const key of Object.keys(this.data)) {\n if (key.startsWith(prefix)) delete this.data[key];\n }\n this.save();\n }\n\n /**\n * List all providers with credentials.\n */\n list(): string[] {\n return Object.keys(this.data);\n }\n\n /**\n * Check if credentials exist for a provider.\n */\n has(provider: string): boolean {\n return provider in this.data;\n }\n\n /**\n * Check if logged in via OAuth for a provider.\n */\n isLoggedIn(provider: string): boolean {\n const cred = this.data[provider];\n return cred?.type === 'oauth';\n }\n\n /**\n * Check if a stored API key exists for a provider.\n * Keys are stored under `apikey:<provider>` in auth.json.\n */\n hasStoredApiKey(provider: string): boolean {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0;\n }\n\n /**\n * Get a stored API key for a provider, if any.\n */\n getStoredApiKey(provider: string): string | undefined {\n const cred = this.data[`apikey:${provider}`];\n return cred?.type === 'api_key' && cred.key.length > 0 ? cred.key : undefined;\n }\n\n /**\n * Store an API key for a provider.\n * Also sets the corresponding environment variable so model resolution can find it.\n */\n setStoredApiKey(provider: string, key: string, envVar?: string): void {\n this.set(`apikey:${provider}`, { type: 'api_key', key });\n if (envVar) {\n exportApiKey(envVar, provider, key);\n }\n }\n\n /**\n * Remove a stored API key for a provider.\n * Also undoes the environment variable export done by {@link setStoredApiKey} or\n * {@link loadStoredApiKeysIntoEnv}: the variable gets back the value it had before\n * (for example the key the process was started with), or is unset if it had none.\n * A variable changed since the export is left alone.\n */\n removeStoredApiKey(provider: string): void {\n this.remove(`apikey:${provider}`);\n for (const [envVar, exported] of exportedApiKeys) {\n if (exported.provider !== provider) continue;\n exportedApiKeys.delete(envVar);\n if (process.env[envVar] !== exported.key) continue;\n if (exported.previous === undefined) delete process.env[envVar];\n else process.env[envVar] = exported.previous;\n }\n }\n\n /**\n * Load all stored API keys into process.env.\n * Called at startup so model resolution can find stored keys.\n * Only sets env vars that aren't already set (env vars take precedence).\n */\n loadStoredApiKeysIntoEnv(providerEnvVars: Record<string, string | undefined>): void {\n for (const [key, cred] of Object.entries(this.data)) {\n if (!key.startsWith('apikey:') || cred.type !== 'api_key' || !cred.key) continue;\n const provider = key.substring('apikey:'.length);\n const envVar = providerEnvVars[provider];\n if (envVar && !process.env[envVar]) {\n exportApiKey(envVar, provider, cred.key);\n }\n }\n }\n\n /**\n * Login to an OAuth provider. Resolves to the registered account record.\n * Pass `activate: false` to add the account without making it active (the\n * first account for a provider is always activated — a provider with\n * accounts must have an active one).\n */\n async login(\n providerId: OAuthProviderId,\n callbacks: OAuthLoginCallbacks,\n opts?: { replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n const provider = getOAuthProvider(providerId);\n if (!provider) {\n throw new Error(`Unknown OAuth provider: ${providerId}`);\n }\n\n const credentials = await provider.login(callbacks);\n // Route through the account registry: the new account is appended (or\n // updated in place — by id collision or an explicit replaceAccountId for\n // re-authentication) and becomes the active account unless activate:false.\n return this.addAccount(providerId, credentials, opts);\n }\n\n /**\n * Logout from a provider: remove the legacy slot and every registered account.\n */\n logout(provider: string): void {\n this.remove(provider);\n }\n\n // ---------------------------------------------------------------------------\n // Multi-account registry\n // ---------------------------------------------------------------------------\n\n private accountPrefixFor(providerId: string): string {\n return `accounts:${providerId}:`;\n }\n\n private accountKeyFor(id: string): string {\n return `accounts:${id}`;\n }\n\n /** Registry entries for a provider in JSON insertion order (malformed values skipped). */\n private accountEntries(providerId: string): OAuthAccountRecord[] {\n const prefix = this.accountPrefixFor(providerId);\n const out: OAuthAccountRecord[] = [];\n for (const [key, value] of Object.entries(this.data)) {\n if (key.startsWith(prefix) && isOAuthAccountRecord(value)) out.push(value);\n }\n return out;\n }\n\n /** Adopt a legacy slot credential as the registry's first active entry. */\n private adoptSlot(providerId: string, slot: OAuthCredential): OAuthAccountRecord {\n const id = mintAccountId(providerId);\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, slot);\n const record: OAuthAccountRecord = {\n ...slot,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: `${provider?.name ?? providerId} account 1`,\n addedAt: new Date().toISOString(),\n active: true,\n };\n this.data[this.accountKeyFor(id)] = record;\n return record;\n }\n\n /**\n * Registered OAuth accounts for a provider, in insertion order. Copies —\n * callers cannot corrupt unsaved storage state by mutating a record.\n */\n listAccounts(providerId: string): OAuthAccountRecord[] {\n return this.accountEntries(providerId).map(entry => ({ ...entry }));\n }\n\n /**\n * The provider's active registry entry, if a registry exists. A copy.\n */\n getActiveAccount(providerId: string): OAuthAccountRecord | undefined {\n const active = this.accountEntries(providerId).find(entry => entry.active);\n return active ? { ...active } : undefined;\n }\n\n /**\n * Register OAuth credentials as an account for a provider, making it active\n * unless `activate: false` is passed.\n *\n * With `replaceAccountId` (re-authentication of a picked account), the\n * target entry's tokens are replaced in place — id re-keyed to the new\n * refresh-token hash, label/position/addedAt preserved — because providers\n * rotate refresh tokens per authorization, so the picked account's old id\n * never matches the new token hash. Re-authentication keeps the target's\n * active state: an inactive account stays inactive and the currently active\n * account keeps the legacy slot. Otherwise, when the new credentials\n * hash to an existing entry's id (same refresh token), that entry is\n * updated in place; a genuinely new account is appended and activated.\n *\n * `activate: false` only applies to the plain add path: the new/updated entry\n * keeps the active state it had, and the previously active account stays\n * active. The first account of a provider is activated regardless.\n */\n async addAccount(\n providerId: string,\n creds: OAuthCredentials,\n opts?: { label?: string; replaceAccountId?: string; activate?: boolean },\n ): Promise<OAuthAccountRecord> {\n this.reload();\n const entries = this.accountEntries(providerId);\n\n if (opts?.replaceAccountId) {\n const target = entries.find(entry => entry.id === opts.replaceAccountId);\n if (!target) {\n throw new Error(`No account ${opts.replaceAccountId} for provider ${providerId}`);\n }\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds) ?? target.identity;\n // Re-authentication updates the account in place and **keeps its id**:\n // ids are minted once and never derived from credentials (A13), so the\n // entry's insertion position, the settings routing preference and any\n // thread routing state that name this id all stay valid.\n //\n // A stale entry for the *same* subscription is dropped in favor of the\n // picked account. Same-subscription is a matching stable identity, or —\n // for a registry written before A13, whose ids were the refresh-token\n // hash — the credentials' own legacy id, or an entry already holding\n // exactly these credentials (a re-authorization that returns the same\n // tokens, the only signal an identity-less provider gives). The survivor\n // inherits the collided entry's active state, so re-authenticating an\n // inactive account onto the active account's credentials cannot leave the\n // registry with no active entry.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const collided = entries.find(\n entry =>\n entry.id !== target.id &&\n ((identity !== undefined && entry.identity === identity) ||\n entry.id === legacyId ||\n entry.refresh === creds.refresh),\n );\n // Credential metadata (device id, enterprise URL, …) follows the tokens:\n // when the fresh response omits a field, the collided entry's value is the\n // coherent fallback, not the target's — pairing fresh tokens with another\n // subscription's stale endpoint would misroute requests. Fresh `creds`\n // win last; only the target's registry metadata (id, label, addedAt)\n // carries over.\n const replacement: OAuthAccountRecord = {\n ...target,\n ...(collided ? credentialFieldsOf(collided) : {}),\n ...creds,\n type: 'oauth-account',\n ...(identity ? { identity } : {}),\n label: opts.label ?? target.label,\n };\n const rebuilt: AuthStorageData = {};\n for (const [key, value] of Object.entries(this.data)) {\n if (key === this.accountKeyFor(target.id)) {\n rebuilt[key] = collided?.active ? { ...replacement, active: true } : replacement;\n } else if (collided && key === this.accountKeyFor(collided.id)) {\n continue;\n } else {\n rebuilt[key] = value;\n }\n }\n this.data = rebuilt;\n // Re-authentication preserves the account's active state: fixing a\n // secondary account's tokens must not hijack the active slot. The target\n // is activated when it was already active, when the entry it collided\n // with was active, or when the provider has no active account at all\n // (first account, or a self-healed gap).\n const wasActive =\n target.active === true ||\n collided?.active === true ||\n entries.some(entry => entry.active && entry.id !== target.id) === false;\n if (wasActive) {\n const activated = this.activateInMemory(providerId, target.id);\n if (!activated) {\n throw new Error(`Failed to activate account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n // Inactive target: tokens stay on the registry entry, the legacy slot\n // keeps the currently active account's credential untouched.\n const replacementEntry = this.accountEntries(providerId).find(entry => entry.id === target.id);\n if (!replacementEntry) {\n throw new Error(`Failed to store account ${target.id} for provider ${providerId}`);\n }\n this.save();\n return replacementEntry;\n }\n\n // Resolve the label before the final reload+save: the provider hook may\n // hit the network, and a concurrent write during that await must not be\n // clobbered by a stale snapshot.\n const provider = getOAuthProvider(providerId);\n const identity = providerIdentity(provider, creds);\n const label = opts?.label ?? (await provider?.getAccountLabel?.(creds)) ?? null;\n this.reload();\n const freshEntries = this.accountEntries(providerId);\n\n // Is this a subscription we already hold? Match the provider's stable\n // account identity where it exposes one, then the pre-A13 id (the\n // refresh-token hash) so a pre-A13 registry still updates its entry rather\n // than gaining a second one for the same subscription, and finally an\n // entry already holding these exact credentials (a re-add of the same\n // account as returned, which is the only signal an identity-less provider\n // such as Anthropic gives us — a provider that cannot name its accounts\n // cannot say \"this is the same subscription, re-authorized\").\n //\n // Crucially this must not re-derive the id of a *minted* entry: after a\n // refresh such an entry's id no longer hashes its current token, and\n // treating that miss as \"new account\" is exactly how re-adding a\n // subscription used to create a duplicate entry for it.\n const legacyId = legacyAccountIdFor(providerId, creds.refresh);\n const existing =\n (identity ? freshEntries.find(entry => entry.identity === identity) : undefined) ??\n freshEntries.find(entry => entry.id === legacyId) ??\n freshEntries.find(entry => entry.refresh === creds.refresh);\n const id = existing?.id ?? mintAccountId(providerId);\n if (existing) {\n this.data[this.accountKeyFor(id)] = {\n ...existing,\n ...creds,\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n active: existing.active,\n };\n } else {\n const resolvedLabel = label ?? `${provider?.name ?? providerId} account ${freshEntries.length + 1}`;\n this.data[this.accountKeyFor(id)] = {\n type: 'oauth-account',\n id,\n ...(identity ? { identity } : {}),\n label: resolvedLabel,\n addedAt: new Date().toISOString(),\n active: false,\n ...creds,\n };\n }\n\n // activate:false (add-another): keep the current active account. The\n // first account of a provider always activates — a non-empty registry\n // must have an active entry. An id collision with the already-active\n // entry also falls through to activateInMemory so its fresh tokens move\n // into the legacy slot (tokens are single-homed).\n if (opts?.activate === false && freshEntries.length > 0 && !existing?.active) {\n this.save();\n return { ...(this.data[this.accountKeyFor(id)] as OAuthAccountRecord) };\n }\n\n const activated = this.activateInMemory(providerId, id);\n if (!activated) {\n throw new Error(`Failed to activate account ${id} for provider ${providerId}`);\n }\n this.save();\n return activated;\n }\n\n /**\n * Activate an account: move the active tokens out of the legacy slot back\n * into the previously active entry, and the target's tokens into the slot\n * (never copy — one home per token set). With no `instanceId`, rotate to\n * the next entry in insertion order, wrapping once to the front; returns\n * undefined when there is no other entry to rotate to.\n */\n activateAccount(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n this.reload();\n const activated = this.activateInMemory(providerId, instanceId);\n if (activated) this.save();\n return activated;\n }\n\n /**\n * Activate an account in memory only — the caller owns reload/save. Move the\n * active tokens out of the legacy slot back into the previously active\n * entry, and the target's tokens into the slot (never copy — one home per\n * token set). With no `instanceId`, rotate to the next entry in insertion\n * order, wrapping once to the front; returns undefined when there is no\n * other entry to rotate to.\n */\n private activateInMemory(providerId: string, instanceId?: string): OAuthAccountRecord | undefined {\n const entries = this.accountEntries(providerId);\n if (entries.length === 0) return undefined;\n\n let target: OAuthAccountRecord | undefined;\n if (instanceId !== undefined) {\n target = entries.find(entry => entry.id === instanceId);\n if (!target) return undefined;\n } else {\n if (entries.length <= 1) return undefined;\n const currentIdx = entries.findIndex(entry => entry.active);\n const candidates =\n currentIdx >= 0 ? [...entries.slice(currentIdx + 1), ...entries.slice(0, currentIdx)] : [...entries];\n target = candidates[0]!;\n }\n if (!target) return undefined;\n\n const slot = this.data[providerId];\n const current = entries.find(entry => entry.active && entry.id !== target.id);\n\n // Move the slot's tokens back onto the previously active entry. Skipped\n // when the target is already active — its (possibly re-authenticated)\n // entry already holds the freshest tokens.\n if (current && slot?.type === 'oauth') {\n const { type: _type, ...slotCreds } = slot;\n this.data[this.accountKeyFor(current.id)] = { ...current, ...slotCreds, type: 'oauth-account', active: false };\n }\n\n // Move the target's tokens into the legacy slot. The slot is rebuilt from\n // the target's own credentials only: carrying fields over from the\n // previously active account would pair this account's tokens with that\n // account's metadata (`deviceId`, `enterpriseUrl`, account id), and the\n // providers read those fields off the slot.\n this.data[providerId] = { ...credentialFieldsOf(target), type: 'oauth' };\n\n // Exactly the target stays active (self-heals multi-active states).\n this.data[this.accountKeyFor(target.id)] = { ...target, active: true };\n for (const entry of entries) {\n if (entry.id === target.id || entry.id === current?.id) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n\n return { ...target, active: true };\n }\n\n /**\n * Remove an account from the registry. If it was active, the next entry in\n * insertion order is activated; when it was the last one, the legacy slot\n * is removed too (full sign-out for that provider).\n */\n removeAccount(providerId: string, instanceId: string): void {\n this.reload();\n const entries = this.accountEntries(providerId);\n const target = entries.find(entry => entry.id === instanceId);\n if (!target) return;\n\n const wasActive = target.active;\n delete this.data[this.accountKeyFor(instanceId)];\n\n if (wasActive) {\n const idx = entries.indexOf(target);\n const next = entries[idx + 1] ?? entries.find(entry => entry.id !== instanceId);\n if (next) {\n // The removed account's tokens die with it — only move tokens in.\n this.data[providerId] = { type: 'oauth', ...credentialFieldsOf(next) };\n this.data[this.accountKeyFor(next.id)] = { ...next, active: true };\n for (const entry of entries) {\n if (entry.id === next.id || entry.id === instanceId) continue;\n if (entry.active) {\n this.data[this.accountKeyFor(entry.id)] = { ...entry, active: false };\n }\n }\n } else {\n delete this.data[providerId];\n }\n }\n\n this.save();\n }\n\n /**\n * Rename an account's label.\n */\n renameAccount(providerId: string, instanceId: string, label: string): void {\n this.reload();\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, label };\n this.save();\n }\n\n /**\n * Persist refreshed credentials for the account that initiated the refresh.\n * The legacy slot is updated only if that account is still active when the\n * refresh completes; otherwise a delayed refresh could overwrite a newer\n * activation.\n */\n private persistRefreshedCredential(\n providerId: string,\n instanceId: string | undefined,\n creds: OAuthCredentials,\n ): void {\n this.reload();\n if (instanceId) {\n const key = this.accountKeyFor(instanceId);\n const entry = this.data[key];\n if (!isOAuthAccountRecord(entry)) return;\n this.data[key] = { ...entry, ...creds, type: 'oauth-account' };\n if (entry.active) {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n } else {\n const slot = this.data[providerId];\n this.data[providerId] =\n slot?.type === 'oauth' ? { ...slot, ...creds, type: 'oauth' } : { type: 'oauth', ...creds };\n }\n this.save();\n }\n\n /**\n * Refresh one account instance through the per-instance dedupe map. Used\n * for sibling refreshes during the rotation walk, so a concurrent\n * `getApiKey` that reloads storage mid-walk (after the candidate was\n * activated but before its refresh resolves) joins the same refresh\n * instead of double-spending a single-use refresh token.\n */\n private async refreshInstance(\n providerId: string,\n instanceId: string,\n creds: OAuthCredentials,\n ): Promise<OAuthCredentials | undefined> {\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const refreshKey = `${providerId}:${instanceId}`;\n const pending = this.refreshPromises.get(refreshKey);\n if (pending) return pending;\n const refresh = (async () => {\n try {\n const fresh = await provider.refreshToken(creds);\n this.persistRefreshedCredential(providerId, instanceId, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n this.refreshPromises.set(refreshKey, refresh);\n try {\n return await refresh;\n } finally {\n this.refreshPromises.delete(refreshKey);\n }\n }\n\n /**\n * Get a ready-to-use OAuth credential snapshot, auto-refreshing if needed.\n * A failed refresh leaves the active account unchanged and returns undefined;\n * the account-rotation processor owns switching so it can persist a visible\n * account-switch notice with the request that triggered the change.\n */\n async getOAuthCredential(\n providerId: string,\n accountInstanceId?: string,\n ): Promise<OAuthCredentialSnapshot | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.data[providerId];\n let credential: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n credential = accountCredential;\n // The active account's credentials live in both the legacy slot and its\n // registry entry, and a legacy writer (older build, another worktree) can\n // refresh the slot without rotating the refresh token. `migrate()` only\n // reconciles those when the refresh token changes, so the registry entry\n // can hold stale access/expiry. Prefer the slot for the active account\n // and keep the registry entry as the account identity.\n if (selectedEntry.active && slot?.type === 'oauth' && slot.refresh === selectedEntry.refresh) {\n const { type: _slotType, ...slotCredential } = slot;\n credential = { ...credential, ...slotCredential };\n }\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n credential = slot;\n }\n if (!credential) return undefined;\n\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n const selectedInstanceId = selectedEntry?.id;\n const toSnapshot = (credentials: OAuthCredentials): OAuthCredentialSnapshot => ({\n type: 'oauth',\n ...credentials,\n accountInstanceId: selectedInstanceId,\n });\n\n if (Date.now() < credential.expires) return toSnapshot(credential);\n\n if (selectedInstanceId) {\n const refreshed = await this.refreshInstance(providerId, selectedInstanceId, credential);\n return refreshed ? toSnapshot(refreshed) : undefined;\n }\n\n const pendingRefresh = this.refreshPromises.get(providerId);\n const refresh =\n pendingRefresh ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(credential);\n this.persistRefreshedCredential(providerId, undefined, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pendingRefresh) this.refreshPromises.set(providerId, refresh);\n try {\n const refreshed = await refresh;\n return refreshed ? toSnapshot(refreshed) : undefined;\n } finally {\n if (!pendingRefresh) this.refreshPromises.delete(providerId);\n }\n }\n\n /** Get API key for a provider, refreshing OAuth tokens if needed. */\n async getApiKey(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const cred = this.data[providerId];\n // A provider slot holding an API key belongs to the provider, not to any one\n // subscription, so it is only the right credential for a request that did\n // not select an account. A routed request must resolve the account it asked\n // for — or nothing — rather than be served this key.\n if (accountInstanceId === undefined && cred?.type === 'api_key') return cred.key;\n\n const oauth = await this.getOAuthCredential(providerId, accountInstanceId);\n const provider = oauth ? getOAuthProvider(providerId) : undefined;\n return oauth && provider ? provider.getApiKey(oauth) : undefined;\n }\n\n /**\n * Force one refresh of the active OAuth account's tokens, regardless of\n * expiry. The account-rotation error processor calls this when a provider\n * rejects a not-yet-expired token (401/403) — server-side clock skew and\n * refresh-token races surface that way. Returns the fresh access token, or\n * undefined when the refresh fails or there is no OAuth credential.\n * Shares the per-instance refresh dedupe with `getApiKey`.\n */\n async forceRefreshActiveAccount(providerId: string, accountInstanceId?: string): Promise<string | undefined> {\n this.reload();\n const activeEntry = this.getActiveAccount(providerId);\n const selectedEntry = accountInstanceId\n ? this.accountEntries(providerId).find(entry => entry.id === accountInstanceId)\n : activeEntry;\n const slot = this.get(providerId);\n let cred: OAuthCredentials | undefined;\n if (selectedEntry) {\n const {\n type: _type,\n id: _id,\n label: _label,\n addedAt: _addedAt,\n active: _active,\n ...accountCredential\n } = selectedEntry;\n cred = accountCredential;\n } else if (!accountInstanceId && slot?.type === 'oauth') {\n cred = slot;\n }\n if (!cred) return undefined;\n const provider = getOAuthProvider(providerId);\n if (!provider) return undefined;\n\n const refreshKey = selectedEntry ? `${providerId}:${selectedEntry.id}` : providerId;\n const pending = this.refreshPromises.get(refreshKey);\n const refresh =\n pending ??\n (async (): Promise<OAuthCredentials | undefined> => {\n try {\n const fresh = await provider.refreshToken(cred);\n this.persistRefreshedCredential(providerId, selectedEntry?.id, fresh);\n return fresh;\n } catch {\n return undefined;\n }\n })();\n if (!pending) this.refreshPromises.set(refreshKey, refresh);\n try {\n const creds = await refresh;\n return creds ? provider.getApiKey(creds) : undefined;\n } finally {\n if (!pending) this.refreshPromises.delete(refreshKey);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA+BA,MAAM,kCAAkB,IAAI,IAA6E;AAEzG,SAAS,aAAa,QAAgB,UAAkB,KAAmB;CACzE,MAAM,WAAW,gBAAgB,IAAI,MAAM;CAE3C,MAAM,WAAW,YAAY,QAAQ,IAAI,YAAY,SAAS,MAAM,SAAS,WAAW,QAAQ,IAAI;CACpG,gBAAgB,I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AAI,YAAY,OAAO;EAC1D,IAAI;GACF,MAAM,QAAQ,MAAM;GACpB,OAAO,QAAQ,SAAS,UAAU,KAAK,IAAI,KAAA;EAC7C,UAAU;GACR,IAAI,CAAC,SAAS,KAAK,gBAAgB,OAAO,UAAU;EACtD;CACF;AACF"}
@@ -6,6 +6,14 @@ export interface ExperimentalAgentEnvironment {
6
6
  }
7
7
  export declare function parseExperimentalAgentEnvironment(env?: ExperimentalAgentEnvironment): ExperimentalAgent | null;
8
8
  export declare function resolveExperimentalAgent(settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>, env?: ExperimentalAgentEnvironment): ExperimentalAgent | null;
9
+ /**
10
+ * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing
11
+ * its runs on a resumable stream; `on` or unset keeps the core default. Any other
12
+ * value, including an empty string, throws so a typo can't silently leave streams on.
13
+ */
14
+ export declare function resolveAgentStreamsOff(env?: {
15
+ MASTRACODE_AGENT_STREAMS?: string;
16
+ }): boolean;
9
17
  export declare function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent;
10
18
  export declare function validateExperimentalAgent(agent: Agent, mastra: Mastra | undefined, report?: (message: string) => void): void;
11
19
  //# sourceMappingURL=experimental-agent.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"experimental-agent.d.ts","sourceRoot":"","sources":["../src/experimental-agent.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAElF,MAAM,WAAW,4BAA4B;IAC3C,6BAA6B,CAAC,EAAE,MAAM,CAAC;CACxC;AAID,wBAAgB,iCAAiC,CAC/C,GAAG,GAAE,4BAA0C,GAC9C,iBAAiB,GAAG,IAAI,CAK1B;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,yBAAyB,CACvC,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,MAAM,GAAG,SAAS,EAC1B,MAAM,GAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAmB,GAC/C,IAAI,CAiCN"}
@@ -13,6 +13,17 @@ function resolveExperimentalAgent(settings, env = process.env) {
13
13
  if (environmentSelection) return environmentSelection;
14
14
  return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);
15
15
  }
16
+ /**
17
+ * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing
18
+ * its runs on a resumable stream; `on` or unset keeps the core default. Any other
19
+ * value, including an empty string, throws so a typo can't silently leave streams on.
20
+ */
21
+ function resolveAgentStreamsOff(env = process.env) {
22
+ const value = env.MASTRACODE_AGENT_STREAMS;
23
+ if (value === void 0 || value === "on") return false;
24
+ if (value === "off") return true;
25
+ throw new Error(`Invalid MASTRACODE_AGENT_STREAMS value ${JSON.stringify(value)}. Expected "on", "off", or unset.`);
26
+ }
16
27
  function wrapExperimentalAgent(agent, selection) {
17
28
  if (selection === "durable") return createDurableAgent({ agent });
18
29
  if (selection === "evented") return createEventedAgent({ agent });
@@ -30,6 +41,6 @@ function validateExperimentalAgent(agent, mastra, report = console.info) {
30
41
  if (engineType !== expectedEngine) throw new Error(`Experimental agent "${selection}" resolved workflow engine ${JSON.stringify(engineType)} instead of "${expectedEngine}".`);
31
42
  report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);
32
43
  }
33
- export { parseExperimentalAgentEnvironment, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent };
44
+ export { parseExperimentalAgentEnvironment, resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent };
34
45
 
35
46
  //# sourceMappingURL=experimental-agent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"experimental-agent.js","names":[],"sources":["../src/experimental-agent.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from '@mastra/core/agent/durable';\nimport type { Mastra } from '@mastra/core/mastra';\n\nimport { parseExperimentalAgentSetting } from './onboarding/settings.js';\nimport type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';\n\nexport interface ExperimentalAgentEnvironment {\n MASTRACODE_EXPERIMENTAL_AGENT?: string;\n}\n\nconst ACCEPTED_VALUES = '\"durable\", \"evented\", or unset';\n\nexport function parseExperimentalAgentEnvironment(\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const value = env.MASTRACODE_EXPERIMENTAL_AGENT;\n if (value === undefined || value === '') return null;\n if (value === 'durable' || value === 'evented') return value;\n throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);\n}\n\nexport function resolveExperimentalAgent(\n settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>,\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const environmentSelection = parseExperimentalAgentEnvironment(env);\n if (environmentSelection) return environmentSelection;\n\n return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);\n}\n\nexport function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent {\n if (selection === 'durable') return createDurableAgent({ agent }) as unknown as Agent;\n if (selection === 'evented') return createEventedAgent({ agent }) as unknown as Agent;\n return agent;\n}\n\ninterface WorkflowBackedAgent extends Agent {\n getWorkflow(): { engineType?: string };\n}\n\nexport function validateExperimentalAgent(\n agent: Agent,\n mastra: Mastra | undefined,\n report: (message: string) => void = console.info,\n): void {\n const selection: ExperimentalAgent | null = isEventedAgent(agent)\n ? 'evented'\n : isDurableAgent(agent)\n ? 'durable'\n : null;\n if (!selection) return;\n\n if (selection === 'evented' && (!mastra || agent.getMastraInstance() !== mastra)) {\n throw new Error(\n 'Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.',\n );\n }\n\n const workflowsStore = mastra?.getStorage()?.stores?.workflows;\n if (!workflowsStore) {\n throw new Error(`Experimental agent \"${selection}\" requires a configured workflow storage domain.`);\n }\n if (selection === 'evented' && workflowsStore.supportsConcurrentUpdates?.() !== true) {\n throw new Error(\n 'Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).',\n );\n }\n\n const engineType = (agent as WorkflowBackedAgent).getWorkflow().engineType;\n const expectedEngine = selection === 'evented' ? 'evented' : 'default';\n if (engineType !== expectedEngine) {\n throw new Error(\n `Experimental agent \"${selection}\" resolved workflow engine ${JSON.stringify(engineType)} instead of \"${expectedEngine}\".`,\n );\n }\n\n report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);\n}\n"],"mappings":";;;AAWA,MAAM,kBAAkB;AAExB,SAAgB,kCACd,MAAoC,QAAQ,KAClB;CAC1B,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO;CAChD,IAAI,UAAU,aAAa,UAAU,WAAW,OAAO;CACvD,MAAM,IAAI,MAAM,+CAA+C,KAAK,UAAU,KAAK,EAAE,aAAa,gBAAgB,EAAE;AACtH;AAEA,SAAgB,yBACd,UACA,MAAoC,QAAQ,KAClB;CAC1B,MAAM,uBAAuB,kCAAkC,GAAG;CAClE,IAAI,sBAAsB,OAAO;CAEjC,OAAO,8BAA8B,SAAS,mBAAmB,SAAS,8BAA8B;AAC1G;AAEA,SAAgB,sBAAsB,OAAc,WAA4C;CAC9F,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,OAAO;AACT;AAMA,SAAgB,0BACd,OACA,QACA,SAAoC,QAAQ,MACtC;CACN,MAAM,YAAsC,eAAe,KAAK,IAC5D,YACA,eAAe,KAAK,IAClB,YACA;CACN,IAAI,CAAC,WAAW;CAEhB,IAAI,cAAc,cAAc,CAAC,UAAU,MAAM,kBAAkB,MAAM,SACvE,MAAM,IAAI,MACR,4GACF;CAGF,MAAM,iBAAiB,QAAQ,WAAW,CAAC,EAAE,QAAQ;CACrD,IAAI,CAAC,gBACH,MAAM,IAAI,MAAM,uBAAuB,UAAU,iDAAiD;CAEpG,IAAI,cAAc,aAAa,eAAe,4BAA4B,MAAM,MAC9E,MAAM,IAAI,MACR,yIACF;CAGF,MAAM,aAAc,MAA8B,YAAY,CAAC,CAAC;CAChE,MAAM,iBAAiB,cAAc,YAAY,YAAY;CAC7D,IAAI,eAAe,gBACjB,MAAM,IAAI,MACR,uBAAuB,UAAU,6BAA6B,KAAK,UAAU,UAAU,EAAE,eAAe,eAAe,GACzH;CAGF,OAAO,uBAAuB,UAAU,qBAAqB,WAAW,EAAE;AAC5E"}
1
+ {"version":3,"file":"experimental-agent.js","names":[],"sources":["../src/experimental-agent.ts"],"sourcesContent":["import type { Agent } from '@mastra/core/agent';\nimport { createDurableAgent, createEventedAgent, isDurableAgent, isEventedAgent } from '@mastra/core/agent/durable';\nimport type { Mastra } from '@mastra/core/mastra';\n\nimport { parseExperimentalAgentSetting } from './onboarding/settings.js';\nimport type { ExperimentalAgent, GlobalSettings } from './onboarding/settings.js';\n\nexport interface ExperimentalAgentEnvironment {\n MASTRACODE_EXPERIMENTAL_AGENT?: string;\n}\n\nconst ACCEPTED_VALUES = '\"durable\", \"evented\", or unset';\n\nexport function parseExperimentalAgentEnvironment(\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const value = env.MASTRACODE_EXPERIMENTAL_AGENT;\n if (value === undefined || value === '') return null;\n if (value === 'durable' || value === 'evented') return value;\n throw new Error(`Invalid MASTRACODE_EXPERIMENTAL_AGENT value ${JSON.stringify(value)}. Expected ${ACCEPTED_VALUES}.`);\n}\n\nexport function resolveExperimentalAgent(\n settings: Pick<GlobalSettings, 'experimentalAgent' | '_experimentalAgentSettingsPath'>,\n env: ExperimentalAgentEnvironment = process.env,\n): ExperimentalAgent | null {\n const environmentSelection = parseExperimentalAgentEnvironment(env);\n if (environmentSelection) return environmentSelection;\n\n return parseExperimentalAgentSetting(settings.experimentalAgent, settings._experimentalAgentSettingsPath);\n}\n\n/**\n * Reads `MASTRACODE_AGENT_STREAMS`. `off` stops the plain coding agent publishing\n * its runs on a resumable stream; `on` or unset keeps the core default. Any other\n * value, including an empty string, throws so a typo can't silently leave streams on.\n */\nexport function resolveAgentStreamsOff(env: { MASTRACODE_AGENT_STREAMS?: string } = process.env): boolean {\n const value = env.MASTRACODE_AGENT_STREAMS;\n if (value === undefined || value === 'on') return false;\n if (value === 'off') return true;\n throw new Error(`Invalid MASTRACODE_AGENT_STREAMS value ${JSON.stringify(value)}. Expected \"on\", \"off\", or unset.`);\n}\n\nexport function wrapExperimentalAgent(agent: Agent, selection: ExperimentalAgent | null): Agent {\n if (selection === 'durable') return createDurableAgent({ agent }) as unknown as Agent;\n if (selection === 'evented') return createEventedAgent({ agent }) as unknown as Agent;\n return agent;\n}\n\ninterface WorkflowBackedAgent extends Agent {\n getWorkflow(): { engineType?: string };\n}\n\nexport function validateExperimentalAgent(\n agent: Agent,\n mastra: Mastra | undefined,\n report: (message: string) => void = console.info,\n): void {\n const selection: ExperimentalAgent | null = isEventedAgent(agent)\n ? 'evented'\n : isDurableAgent(agent)\n ? 'durable'\n : null;\n if (!selection) return;\n\n if (selection === 'evented' && (!mastra || agent.getMastraInstance() !== mastra)) {\n throw new Error(\n 'Experimental agent \"evented\" requires the coding agent to be registered on a Mastra host before startup.',\n );\n }\n\n const workflowsStore = mastra?.getStorage()?.stores?.workflows;\n if (!workflowsStore) {\n throw new Error(`Experimental agent \"${selection}\" requires a configured workflow storage domain.`);\n }\n if (selection === 'evented' && workflowsStore.supportsConcurrentUpdates?.() !== true) {\n throw new Error(\n 'Experimental agent \"evented\" requires workflow storage with atomic concurrent updates (supportsConcurrentUpdates() must return true).',\n );\n }\n\n const engineType = (agent as WorkflowBackedAgent).getWorkflow().engineType;\n const expectedEngine = selection === 'evented' ? 'evented' : 'default';\n if (engineType !== expectedEngine) {\n throw new Error(\n `Experimental agent \"${selection}\" resolved workflow engine ${JSON.stringify(engineType)} instead of \"${expectedEngine}\".`,\n );\n }\n\n report(`Experimental agent: ${selection} (workflow engine: ${engineType})`);\n}\n"],"mappings":";;;AAWA,MAAM,kBAAkB;AAExB,SAAgB,kCACd,MAAoC,QAAQ,KAClB;CAC1B,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,IAAI,OAAO;CAChD,IAAI,UAAU,aAAa,UAAU,WAAW,OAAO;CACvD,MAAM,IAAI,MAAM,+CAA+C,KAAK,UAAU,KAAK,EAAE,aAAa,gBAAgB,EAAE;AACtH;AAEA,SAAgB,yBACd,UACA,MAAoC,QAAQ,KAClB;CAC1B,MAAM,uBAAuB,kCAAkC,GAAG;CAClE,IAAI,sBAAsB,OAAO;CAEjC,OAAO,8BAA8B,SAAS,mBAAmB,SAAS,8BAA8B;AAC1G;;;;;;AAOA,SAAgB,uBAAuB,MAA6C,QAAQ,KAAc;CACxG,MAAM,QAAQ,IAAI;CAClB,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,IAAI,UAAU,OAAO,OAAO;CAC5B,MAAM,IAAI,MAAM,0CAA0C,KAAK,UAAU,KAAK,EAAE,kCAAkC;AACpH;AAEA,SAAgB,sBAAsB,OAAc,WAA4C;CAC9F,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,IAAI,cAAc,WAAW,OAAO,mBAAmB,EAAE,MAAM,CAAC;CAChE,OAAO;AACT;AAMA,SAAgB,0BACd,OACA,QACA,SAAoC,QAAQ,MACtC;CACN,MAAM,YAAsC,eAAe,KAAK,IAC5D,YACA,eAAe,KAAK,IAClB,YACA;CACN,IAAI,CAAC,WAAW;CAEhB,IAAI,cAAc,cAAc,CAAC,UAAU,MAAM,kBAAkB,MAAM,SACvE,MAAM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IAAI,CAAC,EAAE,OAAO,CAAC;IACf,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,OAAO,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,gFAAgF;IAChF,cAAc,CAAC,EAAE,cAAc,CAAC;CACjC;AAKD;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAcvD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,YAAY,CAsC9D;AAED,wBAAgB,kBAAkB,IAAI,IAAI,CA+BzC;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC,CAShE;AAED;;;GAGG;AACH,wBAAsB,QAAQ,CAC5B,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,EAC/B,OAAO,CAAC,EAAE;IAAE,QAAQ,CAAC,EAAE;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;CAAE,GACzD,OAAO,CAAC,KAAK,CAAC,CA8LhB"}
@@ -170,7 +170,8 @@ async function runMCCli(predrainedInput, options) {
170
170
  boot = await createMastraCode({
171
171
  settingsPath: args.settings,
172
172
  coAuthor: options?.coAuthor,
173
- subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled)
173
+ subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled),
174
+ planApprovalStartsGoal: false
174
175
  });
175
176
  const { controller, session, mcpManager } = boot;
176
177
  const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../../src/headless/cli.ts"],"sourcesContent":["/**\n * CLI adapter for headless MastraCode runs.\n *\n * This is the only headless layer that touches the process: it parses argv,\n * reads stdin, bootstraps MastraCode via `createMastraCode`, drives `runMC`,\n * renders events/results to stdout/stderr through the pure formatters, maps the\n * result to an exit code, and owns teardown + `process.exit`.\n */\nimport { existsSync } from 'node:fs';\nimport type { Writable } from 'node:stream';\nimport { parseArgs } from 'node:util';\n\nimport { resolveSubagentsSetting } from '../agents/subagents/index.js';\nimport { createMastraCode } from '../index.js';\nimport { activateModePackInSettings, resolveModePackArg, resolvePackSelection } from '../onboarding/pack-activation.js';\nimport { listBuiltinModePacks } from '../onboarding/packs.js';\nimport { loadSettings, resolveModelDefaults, saveSettings } from '../onboarding/settings.js';\nimport {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n stopProcessMemoryDiagnosticsWithTimeout,\n} from '../process-memory-diagnostics.js';\nimport { setupDebugLogging } from '../utils/debug-log.js';\nimport { releaseAllThreadLocks } from '../utils/thread-lock.js';\n\nimport { buildParseArgsOptions, FLAGS, renderFlagUsage } from './flags.js';\nimport { createHumanFormatState, formatHuman, formatJsonl, isJsonlEvent, renderJsonResult } from './format.js';\nimport { permissionModeToPolicy } from './policy.js';\nimport { runMC } from './run-mc.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\n\n/** Consolidated output mode (replaces the old `--format` + `--output-format`). */\nexport type OutputMode = 'human' | 'json' | 'jsonl';\n\nexport interface HeadlessArgs {\n prompt?: string;\n /** Timeout in seconds (CLI surface); converted to ms before `runMC`. */\n timeout?: number;\n output: OutputMode;\n continue_: boolean;\n model?: string;\n pack?: string;\n mode?: RunMode;\n thinkingLevel?: ThinkingLevel;\n settings?: string;\n thread?: string;\n title?: string;\n cloneThread: boolean;\n resourceId?: string;\n /** Max agentic turns before the run aborts with exit code 1. */\n maxTurns?: number;\n /** Named permission mode resolving to a built-in policy. Defaults to `auto`. */\n permissionMode?: PermissionMode;\n}\n\nconst parseArgsOptions = buildParseArgsOptions();\nconst STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS = 2_000;\n\n/**\n * Returns true if `argv` selects headless mode. This must agree with what\n * {@link parseHeadlessArgs} (and `runMCCli`) accept as a prompt: `--prompt`/`-p`\n * or a bare positional prompt (e.g. `mastracode \"Fix the bug\"`). Note that a\n * prompt piped via stdin without a flag is handled separately by the caller.\n */\nexport function hasHeadlessFlag(argv: string[]): boolean {\n if (argv.some(a => a === '--prompt' || a === '-p')) return true;\n try {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n // A positional prompt only counts when not asking for help.\n return positionals.length > 0 && !values.help;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse CLI arguments for headless mode. The flag table in `flags.ts` is the\n * single source of truth: each flag carries its own coercion/validation, so this\n * function just walks {@link FLAGS} and assembles the typed {@link HeadlessArgs}.\n */\nexport function parseHeadlessArgs(argv: string[]): HeadlessArgs {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n\n // Seed defaults; per-flag values below override these.\n const args: HeadlessArgs = {\n output: 'human',\n continue_: false,\n cloneThread: false,\n };\n const sink = args as unknown as Record<string, unknown>;\n\n for (const flag of FLAGS) {\n if (!flag.field) continue; // e.g. --help, handled by the caller\n const raw = values[flag.key];\n if (raw === undefined) continue;\n\n if (flag.type === 'boolean') {\n sink[flag.field] = Boolean(raw);\n } else if (typeof raw === 'string') {\n sink[flag.field] = flag.coerce ? flag.coerce(raw) : raw;\n }\n }\n\n // A bare positional acts as the prompt when --prompt/-p is absent.\n if (args.prompt === undefined && positionals[0] !== undefined) {\n args.prompt = positionals[0];\n }\n\n if (args.continue_ && args.thread) {\n throw new Error('--continue and --thread cannot be used together');\n }\n\n return args;\n}\n\nexport function printHeadlessUsage(): void {\n process.stdout.write(`\nUsage: mastracode --prompt <text> [options]\n\nHeadless (non-interactive) mode options:\n${renderFlagUsage()}\n\nThread behavior:\n By default, a new thread is created for each run.\n Use --continue to resume the most recent thread, or --thread to target a specific one.\n Use --clone-thread to branch off a copy before running.\n\nSettings file:\n Uses the same settings.json as the interactive TUI. Pass --settings to use\n a custom settings file (e.g., settings-ci.json for CI). All model, pack,\n subagent, and OM configuration is resolved from settings at startup.\n\nExit codes:\n 0 Agent completed successfully\n 1 Error, aborted, or max turns reached\n 2 Timeout\n\nExamples:\n mastracode --prompt \"Fix the bug in auth.ts\"\n mastracode --prompt \"Add tests\" --timeout 300 --output json\n mastracode --prompt \"Refactor\" --output jsonl\n mastracode --prompt \"Review this PR\" --permission-mode deny --max-turns 10\n mastracode --settings ./settings-ci.json --prompt \"Run tests\"\n mastracode -c --prompt \"Continue where you left off\"\n echo \"Summarize the repo\" | mastracode --prompt -\n`);\n}\n\n/**\n * Wait until everything written to `stream` has been handed to the OS, since\n * `process.exit()` drops writes a pipe has not accepted yet. Resolves `false`\n * if the stream fails or closes first; never rejects or hangs on a gone reader.\n */\nexport function flushWritable(stream: Writable): Promise<boolean> {\n if (stream.destroyed || stream.errored) return Promise.resolve(false);\n if (stream.writableLength === 0) return Promise.resolve(true);\n return new Promise(resolve => {\n // Left attached: a stream can emit `error` after failing pending callbacks.\n stream.once('error', () => resolve(false));\n stream.once('close', () => resolve(false));\n stream.write('', error => resolve(!error));\n });\n}\n\n/**\n * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,\n * run via `runMC`, render output, and exit with the mapped code.\n */\nexport async function runMCCli(\n predrainedInput?: string | null,\n options?: { coAuthor?: { name?: string; email?: string } },\n): Promise<never> {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n printHeadlessUsage();\n process.exit(0);\n }\n\n let args: HeadlessArgs;\n try {\n args = parseHeadlessArgs(process.argv);\n } catch (e) {\n process.stderr.write(`Error: ${(e as Error).message}\\n`);\n process.exit(1);\n }\n\n let prompt = args.prompt;\n if (predrainedInput !== undefined) {\n prompt = predrainedInput ?? '';\n } else if (prompt === '-' || (!prompt && !process.stdin.isTTY)) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n prompt = Buffer.concat(chunks).toString('utf-8').trim();\n }\n\n if (!prompt) {\n printHeadlessUsage();\n process.stderr.write('Error: --prompt is required (or pipe via stdin)\\n');\n process.exit(1);\n }\n\n if (args.settings && !existsSync(args.settings)) {\n process.stderr.write(`Error: Settings file not found: ${args.settings}\\n`);\n process.exit(1);\n }\n\n // Resolve --pack up front: an unknown pack fails fast with the valid list,\n // before MastraCode boots. The selection itself is resolved inside runMC\n // after thread selection, because a resumed thread restores its persisted\n // mode — the mode that decides whether the pack has a model for this run.\n // Activation (which mirrors /models → Activate and becomes the global\n // default pack in settings) is saved via onApplied only once the pack has\n // actually been applied to the session — a rejected pack must not change\n // the persisted default on its way out.\n const settings = loadSettings(args.settings);\n let packId: string | undefined;\n if (args.pack !== undefined) {\n const resolved = resolveModePackArg(settings, args.pack);\n if ('error' in resolved) {\n process.stderr.write(`Error: ${resolved.error}\\n`);\n process.exit(1);\n }\n packId = resolved.packId;\n }\n\n const diagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment(process.env);\n const processMemoryDiagnostics = await startConfiguredProcessMemoryDiagnostics(diagnosticsSetup, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n\n let boot: Awaited<ReturnType<typeof createMastraCode>> | undefined;\n // Default to a non-zero exit so an unexpected throw before the run resolves\n // still surfaces as a failure to the caller / CI.\n let exitCode = 1;\n try {\n boot = await createMastraCode({\n settingsPath: args.settings,\n coAuthor: options?.coAuthor,\n subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled),\n });\n const { controller, session, mcpManager } = boot;\n\n const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());\n\n if (mcpManager?.hasServers()) {\n try {\n await mcpManager.initInBackground();\n } catch (err) {\n process.stderr.write(`Warning: MCP server initialization failed: ${(err as Error).message ?? err}\\n`);\n }\n }\n\n setupDebugLogging();\n\n const humanState = createHumanFormatState();\n const run = runMC({\n controller,\n session,\n prompt,\n model: args.model,\n mode: args.mode,\n modeDefaults: effectiveDefaults,\n ...(packId\n ? {\n pack: {\n id: packId,\n resolve: (modeId: string) => resolvePackSelection(settings, packId, modeId),\n onApplied: () => {\n activateModePackInSettings(settings, packId);\n saveSettings(settings, args.settings);\n },\n },\n }\n : {}),\n thinkingLevel: args.thinkingLevel,\n thread: { id: args.thread, continueLatest: args.continue_, clone: args.cloneThread },\n resourceId: args.resourceId,\n title: args.title,\n timeoutMs: args.timeout ? args.timeout * 1000 : undefined,\n maxTurns: args.maxTurns,\n policy: args.permissionMode ? permissionModeToPolicy(args.permissionMode) : undefined,\n });\n\n // Stream live events for human + jsonl modes. (json mode prints only the final object.)\n for await (const event of run) {\n if (args.output === 'human') {\n const out = formatHuman(event, humanState);\n if (out.stdout) process.stdout.write(out.stdout);\n if (out.stderr) process.stderr.write(out.stderr);\n } else if (args.output === 'jsonl' && isJsonlEvent(event)) {\n process.stdout.write(JSON.stringify(formatJsonl(event)) + '\\n');\n }\n }\n\n const result = await run.result;\n exitCode = result.exitCode;\n\n if (args.output === 'json') {\n process.stdout.write(renderJsonResult(result));\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify({ type: 'result', ...result }) + '\\n');\n }\n\n if (result.status === 'timeout') {\n process.stderr.write(`\\nTimeout elapsed. Aborted.\\n`);\n } else if (result.error && args.output === 'human') {\n process.stderr.write(`Error: ${result.error.message}\\n`);\n }\n } catch (err) {\n process.stderr.write(`Error: ${(err as Error).message ?? err}\\n`);\n exitCode = 1;\n } finally {\n // --- Teardown (always runs, even on a thrown error) ---\n releaseAllThreadLocks();\n if (boot) {\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down. Release thread\n // claims first so a restarted process need not wait out this teardown.\n try {\n boot.releaseThreadClaims();\n } catch {\n // Best-effort — the process is exiting.\n }\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const { controller, mcpManager } = boot;\n // Release notification dispatch leases before the pubsub that holds them\n // closes. Headless has no shutdown deadline, so don't let a stalled\n // in-flight dispatch hold up exit.\n await Promise.race([\n boot.stopNotificationDispatch?.().catch(() => {}),\n new Promise<void>(resolve => setTimeout(resolve, STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS).unref()),\n ]);\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller.stopIntervals(),\n ]);\n // The signals pubsub is Mastra's event bus, so close it after the workers\n // stop. Call close() on the object; a detached method loses `this` and\n // rejects silently, leaving socket files behind.\n const signalsPubSub = boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([signalsPubSub?.close?.()]);\n }\n await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n }\n\n // Let piped output (the final result line in particular) reach the reader\n // before exiting. Output that never arrived must not count as success.\n const [stdoutFlushed] = await Promise.all([flushWritable(process.stdout), flushWritable(process.stderr)]);\n if (!stdoutFlushed && exitCode === 0) exitCode = 1;\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,mBAAmB,sBAAsB;AAC/C,MAAM,wCAAwC;;;;;;;AAQ9C,SAAgB,gBAAgB,MAAyB;CACvD,IAAI,KAAK,MAAK,MAAK,MAAM,cAAc,MAAM,IAAI,GAAG,OAAO;CAC3D,IAAI;EACF,MAAM,EAAE,QAAQ,gBAAgB,UAAU;GACxC,MAAM,KAAK,MAAM,CAAC;GAClB,SAAS;GACT,QAAQ;GACR,kBAAkB;EACpB,CAAC;EAED,OAAO,YAAY,SAAS,KAAK,CAAC,OAAO;CAC3C,QAAQ;EACN,OAAO;CAC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AW;CACjD,QAAQ,KAAK,QAAQ;AACvB"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../../src/headless/cli.ts"],"sourcesContent":["/**\n * CLI adapter for headless MastraCode runs.\n *\n * This is the only headless layer that touches the process: it parses argv,\n * reads stdin, bootstraps MastraCode via `createMastraCode`, drives `runMC`,\n * renders events/results to stdout/stderr through the pure formatters, maps the\n * result to an exit code, and owns teardown + `process.exit`.\n */\nimport { existsSync } from 'node:fs';\nimport type { Writable } from 'node:stream';\nimport { parseArgs } from 'node:util';\n\nimport { resolveSubagentsSetting } from '../agents/subagents/index.js';\nimport { createMastraCode } from '../index.js';\nimport { activateModePackInSettings, resolveModePackArg, resolvePackSelection } from '../onboarding/pack-activation.js';\nimport { listBuiltinModePacks } from '../onboarding/packs.js';\nimport { loadSettings, resolveModelDefaults, saveSettings } from '../onboarding/settings.js';\nimport {\n createProcessMemoryDiagnosticsFromEnvironment,\n startConfiguredProcessMemoryDiagnostics,\n stopProcessMemoryDiagnosticsWithTimeout,\n} from '../process-memory-diagnostics.js';\nimport { setupDebugLogging } from '../utils/debug-log.js';\nimport { releaseAllThreadLocks } from '../utils/thread-lock.js';\n\nimport { buildParseArgsOptions, FLAGS, renderFlagUsage } from './flags.js';\nimport { createHumanFormatState, formatHuman, formatJsonl, isJsonlEvent, renderJsonResult } from './format.js';\nimport { permissionModeToPolicy } from './policy.js';\nimport { runMC } from './run-mc.js';\nimport type { PermissionMode, RunMode, ThinkingLevel } from './types.js';\n\n/** Consolidated output mode (replaces the old `--format` + `--output-format`). */\nexport type OutputMode = 'human' | 'json' | 'jsonl';\n\nexport interface HeadlessArgs {\n prompt?: string;\n /** Timeout in seconds (CLI surface); converted to ms before `runMC`. */\n timeout?: number;\n output: OutputMode;\n continue_: boolean;\n model?: string;\n pack?: string;\n mode?: RunMode;\n thinkingLevel?: ThinkingLevel;\n settings?: string;\n thread?: string;\n title?: string;\n cloneThread: boolean;\n resourceId?: string;\n /** Max agentic turns before the run aborts with exit code 1. */\n maxTurns?: number;\n /** Named permission mode resolving to a built-in policy. Defaults to `auto`. */\n permissionMode?: PermissionMode;\n}\n\nconst parseArgsOptions = buildParseArgsOptions();\nconst STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS = 2_000;\n\n/**\n * Returns true if `argv` selects headless mode. This must agree with what\n * {@link parseHeadlessArgs} (and `runMCCli`) accept as a prompt: `--prompt`/`-p`\n * or a bare positional prompt (e.g. `mastracode \"Fix the bug\"`). Note that a\n * prompt piped via stdin without a flag is handled separately by the caller.\n */\nexport function hasHeadlessFlag(argv: string[]): boolean {\n if (argv.some(a => a === '--prompt' || a === '-p')) return true;\n try {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n // A positional prompt only counts when not asking for help.\n return positionals.length > 0 && !values.help;\n } catch {\n return false;\n }\n}\n\n/**\n * Parse CLI arguments for headless mode. The flag table in `flags.ts` is the\n * single source of truth: each flag carries its own coercion/validation, so this\n * function just walks {@link FLAGS} and assembles the typed {@link HeadlessArgs}.\n */\nexport function parseHeadlessArgs(argv: string[]): HeadlessArgs {\n const { values, positionals } = parseArgs({\n args: argv.slice(2),\n options: parseArgsOptions,\n strict: false,\n allowPositionals: true,\n });\n\n // Seed defaults; per-flag values below override these.\n const args: HeadlessArgs = {\n output: 'human',\n continue_: false,\n cloneThread: false,\n };\n const sink = args as unknown as Record<string, unknown>;\n\n for (const flag of FLAGS) {\n if (!flag.field) continue; // e.g. --help, handled by the caller\n const raw = values[flag.key];\n if (raw === undefined) continue;\n\n if (flag.type === 'boolean') {\n sink[flag.field] = Boolean(raw);\n } else if (typeof raw === 'string') {\n sink[flag.field] = flag.coerce ? flag.coerce(raw) : raw;\n }\n }\n\n // A bare positional acts as the prompt when --prompt/-p is absent.\n if (args.prompt === undefined && positionals[0] !== undefined) {\n args.prompt = positionals[0];\n }\n\n if (args.continue_ && args.thread) {\n throw new Error('--continue and --thread cannot be used together');\n }\n\n return args;\n}\n\nexport function printHeadlessUsage(): void {\n process.stdout.write(`\nUsage: mastracode --prompt <text> [options]\n\nHeadless (non-interactive) mode options:\n${renderFlagUsage()}\n\nThread behavior:\n By default, a new thread is created for each run.\n Use --continue to resume the most recent thread, or --thread to target a specific one.\n Use --clone-thread to branch off a copy before running.\n\nSettings file:\n Uses the same settings.json as the interactive TUI. Pass --settings to use\n a custom settings file (e.g., settings-ci.json for CI). All model, pack,\n subagent, and OM configuration is resolved from settings at startup.\n\nExit codes:\n 0 Agent completed successfully\n 1 Error, aborted, or max turns reached\n 2 Timeout\n\nExamples:\n mastracode --prompt \"Fix the bug in auth.ts\"\n mastracode --prompt \"Add tests\" --timeout 300 --output json\n mastracode --prompt \"Refactor\" --output jsonl\n mastracode --prompt \"Review this PR\" --permission-mode deny --max-turns 10\n mastracode --settings ./settings-ci.json --prompt \"Run tests\"\n mastracode -c --prompt \"Continue where you left off\"\n echo \"Summarize the repo\" | mastracode --prompt -\n`);\n}\n\n/**\n * Wait until everything written to `stream` has been handed to the OS, since\n * `process.exit()` drops writes a pipe has not accepted yet. Resolves `false`\n * if the stream fails or closes first; never rejects or hangs on a gone reader.\n */\nexport function flushWritable(stream: Writable): Promise<boolean> {\n if (stream.destroyed || stream.errored) return Promise.resolve(false);\n if (stream.writableLength === 0) return Promise.resolve(true);\n return new Promise(resolve => {\n // Left attached: a stream can emit `error` after failing pending callbacks.\n stream.once('error', () => resolve(false));\n stream.once('close', () => resolve(false));\n stream.write('', error => resolve(!error));\n });\n}\n\n/**\n * Headless CLI entry point: parse arguments, read stdin, initialize MastraCode,\n * run via `runMC`, render output, and exit with the mapped code.\n */\nexport async function runMCCli(\n predrainedInput?: string | null,\n options?: { coAuthor?: { name?: string; email?: string } },\n): Promise<never> {\n if (process.argv.includes('--help') || process.argv.includes('-h')) {\n printHeadlessUsage();\n process.exit(0);\n }\n\n let args: HeadlessArgs;\n try {\n args = parseHeadlessArgs(process.argv);\n } catch (e) {\n process.stderr.write(`Error: ${(e as Error).message}\\n`);\n process.exit(1);\n }\n\n let prompt = args.prompt;\n if (predrainedInput !== undefined) {\n prompt = predrainedInput ?? '';\n } else if (prompt === '-' || (!prompt && !process.stdin.isTTY)) {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n prompt = Buffer.concat(chunks).toString('utf-8').trim();\n }\n\n if (!prompt) {\n printHeadlessUsage();\n process.stderr.write('Error: --prompt is required (or pipe via stdin)\\n');\n process.exit(1);\n }\n\n if (args.settings && !existsSync(args.settings)) {\n process.stderr.write(`Error: Settings file not found: ${args.settings}\\n`);\n process.exit(1);\n }\n\n // Resolve --pack up front: an unknown pack fails fast with the valid list,\n // before MastraCode boots. The selection itself is resolved inside runMC\n // after thread selection, because a resumed thread restores its persisted\n // mode — the mode that decides whether the pack has a model for this run.\n // Activation (which mirrors /models → Activate and becomes the global\n // default pack in settings) is saved via onApplied only once the pack has\n // actually been applied to the session — a rejected pack must not change\n // the persisted default on its way out.\n const settings = loadSettings(args.settings);\n let packId: string | undefined;\n if (args.pack !== undefined) {\n const resolved = resolveModePackArg(settings, args.pack);\n if ('error' in resolved) {\n process.stderr.write(`Error: ${resolved.error}\\n`);\n process.exit(1);\n }\n packId = resolved.packId;\n }\n\n const diagnosticsSetup = createProcessMemoryDiagnosticsFromEnvironment(process.env);\n const processMemoryDiagnostics = await startConfiguredProcessMemoryDiagnostics(diagnosticsSetup, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n\n let boot: Awaited<ReturnType<typeof createMastraCode>> | undefined;\n // Default to a non-zero exit so an unexpected throw before the run resolves\n // still surfaces as a failure to the caller / CI.\n let exitCode = 1;\n try {\n boot = await createMastraCode({\n settingsPath: args.settings,\n coAuthor: options?.coAuthor,\n subagents: resolveSubagentsSetting(settings.preferences.subagentsEnabled),\n // Headless approves submit_plan without starting a goal.\n planApprovalStartsGoal: false,\n });\n const { controller, session, mcpManager } = boot;\n\n const effectiveDefaults = resolveModelDefaults(settings, listBuiltinModePacks());\n\n if (mcpManager?.hasServers()) {\n try {\n await mcpManager.initInBackground();\n } catch (err) {\n process.stderr.write(`Warning: MCP server initialization failed: ${(err as Error).message ?? err}\\n`);\n }\n }\n\n setupDebugLogging();\n\n const humanState = createHumanFormatState();\n const run = runMC({\n controller,\n session,\n prompt,\n model: args.model,\n mode: args.mode,\n modeDefaults: effectiveDefaults,\n ...(packId\n ? {\n pack: {\n id: packId,\n resolve: (modeId: string) => resolvePackSelection(settings, packId, modeId),\n onApplied: () => {\n activateModePackInSettings(settings, packId);\n saveSettings(settings, args.settings);\n },\n },\n }\n : {}),\n thinkingLevel: args.thinkingLevel,\n thread: { id: args.thread, continueLatest: args.continue_, clone: args.cloneThread },\n resourceId: args.resourceId,\n title: args.title,\n timeoutMs: args.timeout ? args.timeout * 1000 : undefined,\n maxTurns: args.maxTurns,\n policy: args.permissionMode ? permissionModeToPolicy(args.permissionMode) : undefined,\n });\n\n // Stream live events for human + jsonl modes. (json mode prints only the final object.)\n for await (const event of run) {\n if (args.output === 'human') {\n const out = formatHuman(event, humanState);\n if (out.stdout) process.stdout.write(out.stdout);\n if (out.stderr) process.stderr.write(out.stderr);\n } else if (args.output === 'jsonl' && isJsonlEvent(event)) {\n process.stdout.write(JSON.stringify(formatJsonl(event)) + '\\n');\n }\n }\n\n const result = await run.result;\n exitCode = result.exitCode;\n\n if (args.output === 'json') {\n process.stdout.write(renderJsonResult(result));\n } else if (args.output === 'jsonl') {\n process.stdout.write(JSON.stringify({ type: 'result', ...result }) + '\\n');\n }\n\n if (result.status === 'timeout') {\n process.stderr.write(`\\nTimeout elapsed. Aborted.\\n`);\n } else if (result.error && args.output === 'human') {\n process.stderr.write(`Error: ${result.error.message}\\n`);\n }\n } catch (err) {\n process.stderr.write(`Error: ${(err as Error).message ?? err}\\n`);\n exitCode = 1;\n } finally {\n // --- Teardown (always runs, even on a thrown error) ---\n releaseAllThreadLocks();\n if (boot) {\n // Stop plugin-contributed signal providers (and the plugin reload listener)\n // before quiescing workers: a provider that keeps polling past this point\n // could dispatch into a controller that is shutting down. Release thread\n // claims first so a restarted process need not wait out this teardown.\n try {\n boot.releaseThreadClaims();\n } catch {\n // Best-effort — the process is exiting.\n }\n try {\n boot.stopPluginSignalProviders();\n } catch {\n // Best-effort — the process is exiting.\n }\n const { controller, mcpManager } = boot;\n // Release notification dispatch leases before the pubsub that holds them\n // closes. Headless has no shutdown deadline, so don't let a stalled\n // in-flight dispatch hold up exit.\n await Promise.race([\n boot.stopNotificationDispatch?.().catch(() => {}),\n new Promise<void>(resolve => setTimeout(resolve, STOP_NOTIFICATION_DISPATCH_TIMEOUT_MS).unref()),\n ]);\n await Promise.allSettled([\n mcpManager?.disconnect(),\n controller.getMastra()?.stopWorkers(),\n controller.stopIntervals(),\n ]);\n // The signals pubsub is Mastra's event bus, so close it after the workers\n // stop. Call close() on the object; a detached method loses `this` and\n // rejects silently, leaving socket files behind.\n const signalsPubSub = boot.signalsPubSub as { close?: () => Promise<void> | void } | undefined;\n await Promise.allSettled([signalsPubSub?.close?.()]);\n }\n await stopProcessMemoryDiagnosticsWithTimeout(processMemoryDiagnostics, warning => {\n process.stderr.write(`Warning: ${warning}\\n`);\n });\n }\n\n // Let piped output (the final result line in particular) reach the reader\n // before exiting. Output that never arrived must not count as success.\n const [stdoutFlushed] = await Promise.all([flushWritable(process.stdout), flushWritable(process.stderr)]);\n if (!stdoutFlushed && exitCode === 0) exitCode = 1;\n process.exit(exitCode);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuDA,MAAM,mBAAmB,sBAAsB;AAC/C,MAAM,wCAAwC;;;;;;;AAQ9C,SAAgB,gBAAgB,MAAyB;CACvD,IAAI,KAAK,MAAK,MAAK,MAAM,cAAc,MAAM,IAAI,GAAG,OAAO;CAC3D,IAAI;EACF,MAAM,EAAE,QAAQ,gBAAgB,UAAU;GACxC,MAAM,KAAK,MAAM,CAAC;GAClB,SAAS;GACT,QAAQ;GACR,kBAAkB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AAc,QAAQ,MAAM,GAAG,cAAc,QAAQ,MAAM,CAAC,CAAC;CACxG,IAAI,CAAC,iBAAiB,aAAa,GAAG,WAAW;CACjD,QAAQ,KAAK,QAAQ;AACvB"}
package/dist/index.d.ts CHANGED
@@ -129,6 +129,8 @@ export interface MastraCodeConfig {
129
129
  hostInstructions?: string | ((ctx: {
130
130
  requestContext: RequestContext;
131
131
  }) => string | undefined | Promise<string | undefined>);
132
+ /** Whether approving a plan starts it as a goal in this host's clients. Set false when plan approval does not start a goal (Factory). Default: true */
133
+ planApprovalStartsGoal?: boolean;
132
134
  /** Commit co-author identity included in coding-agent commit guidance. Unspecified fields use core defaults. */
133
135
  coAuthor?: {
134
136
  name?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,eAAe,EAAkC,MAAM,+BAA+B,CAAC;AAChG,OAAO,KAAK,EACV,eAAe,EACf,qBAAqB,EAErB,mBAAmB,EACnB,uBAAuB,EAEvB,aAAa,EACb,OAAO,EACR,MAAM,+BAA+B,CAAC;AAGvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,SAAS,EAAyB,MAAM,wBAAwB,CAAC;AAG1E,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAU7C,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAa,MAAM,yBAAyB,CAAC;AAC1F,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAC;AAGpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AAGxD,OAAO,EAAE,aAAa,EAA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,EAAE,CAAC;IACjH,iBAAiB,CAAC,EAAE,CAAC,IAAI,EAAE;QACzB,UAAU,EAAE,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAC5C,WAAW,EAAE,WAAW,CAAC;KAC1B,KAAK,IAAI,CAAC,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,WAAW,CAAC,CAAC;CACzF,GACA,OAAO,CAAC;IACT,IAAI,EAAE,OAAO,CAAC,UAAU,CAAC,OAAO,+BAA+B,CAAC,CAAC,CAAC;IAClE,UAAU,EAAE,WAAW,CAAC,qBAAqB,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACjE,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B,CAAC,CAqED;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,iCAA2B,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACxF,cAAc,0BAA0B,CAAC;AACzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE9D;;;;GAIG;AACH,OAAO,EACL,KAAK,EACL,QAAQ,EACR,eAAe,EACf,iBAAiB,EACjB,UAAU,EACV,sBAAsB,EACtB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,YAAY,EACV,YAAY,EACZ,WAAW,EACX,WAAW,EACX,UAAU,EACV,aAAa,EACb,eAAe,EACf,UAAU,EACV,kBAAkB,EAClB,KAAK,EACL,gBAAgB,EAChB,cAAc,GACf,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -14,12 +14,12 @@ import { builtinSubagents, resolveSubagentsSetting } from "./agents/subagents/in
14
14
  import { attachOMThreadStatePersistence, restoreOMThreadStateForCurrentThread } from "./agents/thread-caveman-state.js";
15
15
  import { createDynamicTools, createToolHooks } from "./agents/tools.js";
16
16
  import { getDynamicWorkspace, getGoalJudgeTools } from "./agents/workspace.js";
17
- import { AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_STATE_KEY } from "./auth/account-rotation-processor.js";
17
+ import { AccountRotationProcessor, AccountStartNoticeProcessor, MODEL_FALLBACK_STATE_KEY, isStreamCutAfterResponse } from "./auth/account-rotation-processor.js";
18
18
  import { isKimiCodingDeviceId } from "./auth/providers/kimi-coding.js";
19
19
  import { AuthStorage } from "./auth/storage.js";
20
20
  import { CODE_AGENT_ID, DEFAULT_OM_MODEL_ID, validateConfigDirName } from "./constants.js";
21
21
  import "./evals/scorers/index.js";
22
- import { resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent } from "./experimental-agent.js";
22
+ import { resolveAgentStreamsOff, resolveExperimentalAgent, validateExperimentalAgent, wrapExperimentalAgent } from "./experimental-agent.js";
23
23
  import "./hooks/index.js";
24
24
  import { KnowledgeInspectorError, createKnowledgeInspector } from "./knowledge-inspector.js";
25
25
  import { LOCAL_KNOWLEDGE_ORG_ID, knowledgeUnresolvedScopes, resolveKnowledgeSessionScopes } from "./knowledge-scope.js";
@@ -257,10 +257,11 @@ async function createMastraCodeAgentController(config) {
257
257
  const authStorage = createAuthStorage();
258
258
  const globalSettings = loadSettings(config?.settingsPath);
259
259
  const experimentalAgent = resolveExperimentalAgent(globalSettings);
260
+ const agentStreamsOff = resolveAgentStreamsOff();
260
261
  const backgroundToolsEnabled = globalSettings.backgroundTools?.enabled ?? false;
261
262
  const storedGatewayKey = authStorage.getStoredApiKey(MASTRA_GATEWAY_PROVIDER);
262
263
  const storedGatewayUrl = globalSettings.memoryGateway?.baseUrl;
263
- if (storedGatewayKey) process.env["MASTRA_GATEWAY_API_KEY"] ??= storedGatewayKey;
264
+ if (storedGatewayKey) authStorage.loadStoredApiKeysIntoEnv({ [MASTRA_GATEWAY_PROVIDER]: "MASTRA_GATEWAY_API_KEY" });
264
265
  if (storedGatewayUrl) process.env["MASTRA_GATEWAY_URL"] ??= storedGatewayUrl;
265
266
  if (!hasCredentialStoreProvider()) try {
266
267
  const registry = PROVIDER_REGISTRY;
@@ -709,6 +710,7 @@ async function createMastraCodeAgentController(config) {
709
710
  const baseCodeAgent = createCodingAgent({
710
711
  id: CODE_AGENT_ID,
711
712
  name: "Code Agent",
713
+ ...agentStreamsOff ? { durable: false } : {},
712
714
  workspace: void 0,
713
715
  ...knowledge ? {
714
716
  knowledge,
@@ -727,6 +729,7 @@ async function createMastraCodeAgentController(config) {
727
729
  coAuthor: config?.coAuthor,
728
730
  hasSubagents: subagents.length > 0,
729
731
  disabledBuiltinTools: config?.disableBuiltinTools,
732
+ planApprovalStartsGoal: config?.planApprovalStartsGoal,
730
733
  plansDir: config?.plansDir,
731
734
  disabledTools: config?.disabledTools
732
735
  });
@@ -828,6 +831,10 @@ async function createMastraCodeAgentController(config) {
828
831
  new ProviderHistoryCompat(),
829
832
  new CyberRefusalHandler(),
830
833
  new StreamErrorRetryProcessor({ matchers: [
834
+ {
835
+ match: isStreamCutAfterResponse,
836
+ maxRetries: 0
837
+ },
831
838
  {
832
839
  match: isBadRequestError,
833
840
  maxRetries: 1,