workos 0.17.1 → 0.18.0

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 (74) hide show
  1. package/README.md +3 -4
  2. package/dist/bin.js +54 -1
  3. package/dist/bin.js.map +1 -1
  4. package/dist/cli.config.d.ts +0 -2
  5. package/dist/cli.config.js +3 -3
  6. package/dist/cli.config.js.map +1 -1
  7. package/dist/commands/debug.d.ts +11 -0
  8. package/dist/commands/debug.js +24 -8
  9. package/dist/commands/debug.js.map +1 -1
  10. package/dist/commands/install.js +4 -0
  11. package/dist/commands/install.js.map +1 -1
  12. package/dist/commands/mcp.d.ts +14 -0
  13. package/dist/commands/mcp.js +108 -0
  14. package/dist/commands/mcp.js.map +1 -0
  15. package/dist/doctor/checks/ai-analysis.js +2 -1
  16. package/dist/doctor/checks/ai-analysis.js.map +1 -1
  17. package/dist/doctor/checks/mcp.d.ts +15 -0
  18. package/dist/doctor/checks/mcp.js +34 -0
  19. package/dist/doctor/checks/mcp.js.map +1 -0
  20. package/dist/doctor/index.js +7 -1
  21. package/dist/doctor/index.js.map +1 -1
  22. package/dist/doctor/issues.js +16 -0
  23. package/dist/doctor/issues.js.map +1 -1
  24. package/dist/doctor/output.js +16 -2
  25. package/dist/doctor/output.js.map +1 -1
  26. package/dist/doctor/types.d.ts +17 -0
  27. package/dist/doctor/types.js.map +1 -1
  28. package/dist/emulate/workos/index.js.map +1 -1
  29. package/dist/lib/agent-interface.js +4 -4
  30. package/dist/lib/agent-interface.js.map +1 -1
  31. package/dist/lib/ai-content.js +2 -1
  32. package/dist/lib/ai-content.js.map +1 -1
  33. package/dist/lib/constants.d.ts +9 -0
  34. package/dist/lib/constants.js +9 -0
  35. package/dist/lib/constants.js.map +1 -1
  36. package/dist/lib/installer-core.d.ts +20 -20
  37. package/dist/lib/mcp-clients.d.ts +39 -0
  38. package/dist/lib/mcp-clients.js +284 -0
  39. package/dist/lib/mcp-clients.js.map +1 -0
  40. package/dist/lib/mcp-notice.d.ts +72 -0
  41. package/dist/lib/mcp-notice.js +275 -0
  42. package/dist/lib/mcp-notice.js.map +1 -0
  43. package/dist/lib/preferences.d.ts +14 -0
  44. package/dist/lib/preferences.js +3 -0
  45. package/dist/lib/preferences.js.map +1 -1
  46. package/dist/lib/run-with-core.js +2 -1
  47. package/dist/lib/run-with-core.js.map +1 -1
  48. package/dist/lib/settings.d.ts +5 -14
  49. package/dist/lib/settings.js +5 -16
  50. package/dist/lib/settings.js.map +1 -1
  51. package/dist/lib/startup-notice-gate.d.ts +21 -0
  52. package/dist/lib/startup-notice-gate.js +29 -0
  53. package/dist/lib/startup-notice-gate.js.map +1 -0
  54. package/dist/lib/telemetry-notice.js +3 -0
  55. package/dist/lib/telemetry-notice.js.map +1 -1
  56. package/dist/lib/unclaimed-warning.js +3 -0
  57. package/dist/lib/unclaimed-warning.js.map +1 -1
  58. package/dist/utils/analytics.d.ts +1 -0
  59. package/dist/utils/analytics.js +5 -1
  60. package/dist/utils/analytics.js.map +1 -1
  61. package/dist/utils/help-json.js +38 -0
  62. package/dist/utils/help-json.js.map +1 -1
  63. package/dist/utils/interaction-mode.d.ts +1 -1
  64. package/dist/utils/interaction-mode.js +0 -3
  65. package/dist/utils/interaction-mode.js.map +1 -1
  66. package/dist/utils/output.d.ts +5 -3
  67. package/dist/utils/output.js +5 -5
  68. package/dist/utils/output.js.map +1 -1
  69. package/dist/utils/telemetry-types.d.ts +1 -1
  70. package/dist/utils/telemetry-types.js.map +1 -1
  71. package/dist/utils/urls.d.ts +9 -3
  72. package/dist/utils/urls.js +10 -4
  73. package/dist/utils/urls.js.map +1 -1
  74. package/package.json +11 -10
@@ -8,9 +8,9 @@ import { debug, logInfo, logWarn, logError, initLogFile, getLogFilePath } from '
8
8
  import { analytics } from '../utils/analytics.js';
9
9
  import { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';
10
10
  import { LINTING_TOOLS } from './safe-tools.js';
11
- import { getLlmGatewayUrlFromHost } from '../utils/urls.js';
12
11
  import { formatWorkOSCommand } from '../utils/command-invocation.js';
13
12
  import { getConfig } from './settings.js';
13
+ import { getLlmGatewayUrl } from '../utils/urls.js';
14
14
  import { getCredentials, hasCredentials } from './credentials.js';
15
15
  import { ensureValidToken } from './token-refresh.js';
16
16
  import { startCredentialProxy, startClaimTokenProxy } from './credential-proxy.js';
@@ -305,7 +305,7 @@ export async function initializeAgent(config, options) {
305
305
  }
306
306
  else {
307
307
  // Gateway mode (existing behavior)
308
- const gatewayUrl = getLlmGatewayUrlFromHost();
308
+ const gatewayUrl = getLlmGatewayUrl();
309
309
  // Check for unclaimed environment — use claim token auth
310
310
  const activeEnv = getActiveEnvironment();
311
311
  if (activeEnv && isUnclaimedEnvironment(activeEnv)) {
@@ -332,7 +332,7 @@ export async function initializeAgent(config, options) {
332
332
  throw new Error(`Not authenticated. Run \`${formatWorkOSCommand('auth login')}\` to authenticate.`);
333
333
  }
334
334
  // Check if we have refresh token capability and proxy is not disabled
335
- if (creds.refreshToken && process.env.INSTALLER_DISABLE_PROXY !== '1') {
335
+ if (creds.refreshToken && process.env.WORKOS_DISABLE_PROXY !== '1') {
336
336
  // Start credential proxy with lazy refresh
337
337
  logInfo('[agent-interface] Starting credential proxy with lazy refresh...');
338
338
  const appConfig = getConfig();
@@ -373,7 +373,7 @@ export async function initializeAgent(config, options) {
373
373
  });
374
374
  }
375
375
  else {
376
- logWarn('[agent-interface] Proxy disabled via INSTALLER_DISABLE_PROXY');
376
+ logWarn('[agent-interface] Proxy disabled via WORKOS_DISABLE_PROXY');
377
377
  }
378
378
  const refreshResult = await ensureValidToken();
379
379
  if (!refreshResult.success) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../src/lib/agent-interface.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,YAAY,IAAI,mBAAmB,EAAE,MAAM,gBAAgB,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E;gBACxE,OAAO,2BAA2B,OAAO,CAAC,OAAO,EAAE,CAAC;YACtD,CAAC;YACD,MAAM;QACR,CAAC;QAED,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,IAAI,OAAO,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;gBAC/B,OAAO,CAAC,2BAA2B,EAAE;oBACnC,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM;oBAC5B,UAAU,EAAE,OAAO,CAAC,WAAW;iBAChC,CAAC,CAAC;YACL,CAAC;YACD,MAAM;QACR,CAAC;QAED;YACE,wCAAwC;YACxC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,KAAK,CAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,iBAAiB,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * Shared agent interface for WorkOS wizards\n * Uses Claude Agent SDK directly with WorkOS MCP server\n */\n\nimport { dirname } from 'path';\nimport { getSkillsDir as getSkillsPackageDir } from '@workos/skills';\nimport { debug, logInfo, logWarn, logError, initLogFile, getLogFilePath } from '../utils/debug.js';\nimport type { InstallerOptions } from '../utils/types.js';\nimport { analytics } from '../utils/analytics.js';\nimport { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';\nimport { LINTING_TOOLS } from './safe-tools.js';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls.js';\nimport { formatWorkOSCommand } from '../utils/command-invocation.js';\nimport { getConfig } from './settings.js';\nimport { getCredentials, hasCredentials } from './credentials.js';\nimport { ensureValidToken } from './token-refresh.js';\nimport type { InstallerEventEmitter } from './events.js';\nimport { startCredentialProxy, startClaimTokenProxy, type CredentialProxyHandle } from './credential-proxy.js';\nimport { getActiveEnvironment, isUnclaimedEnvironment } from './config-store.js';\nimport { getAuthkitDomain, getCliAuthClientId } from './settings.js';\nimport type {\n SDKMessage,\n SDKUserMessage,\n Options as AgentSDKOptions,\n PermissionResult,\n query as queryFn,\n} from '@anthropic-ai/claude-agent-sdk';\n\n// File content cache for computing edit diffs\nconst fileContentCache = new Map<string, string>();\n// Track pending Read operations by tool_use_id\nconst pendingReads = new Map<string, string>();\n// Track tool start times by tool_use_id for telemetry\nconst pendingToolCalls = new Map<string, { toolName: string; startTime: number }>();\n\n// Module-level variable to track proxy handle for cleanup\nlet activeProxyHandle: CredentialProxyHandle | null = null;\n\n// Dynamic import cache for ESM module\nlet _sdkModule: { query: typeof queryFn } | null = null;\nasync function getSDKModule(): Promise<{ query: typeof queryFn }> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the WorkOS MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/** Internal prefix used to tag service-unavailability errors from handleSDKMessage */\nconst SERVICE_UNAVAILABLE_PREFIX = '__SERVICE_UNAVAILABLE__';\n\n/** Internal prefix used to tag rate-limit errors from handleSDKMessage */\nconst RATE_LIMITED_PREFIX = '__RATE_LIMITED__';\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** Agent could not access the WorkOS MCP server */\n MCP_MISSING = 'INSTALLER_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'INSTALLER_RESOURCE_MISSING',\n /** Agent execution failed (API error, auth error, etc.) */\n EXECUTION_ERROR = 'INSTALLER_EXECUTION_ERROR',\n /** AI service is unavailable (API 500, outage, etc.) */\n SERVICE_UNAVAILABLE = 'INSTALLER_SERVICE_UNAVAILABLE',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n workOSApiKey: string;\n workOSApiHost: string;\n};\n\nexport interface RetryConfig {\n /** Max correction attempts after initial run. Default: 2 */\n maxRetries: number;\n /** Run between agent turns. Return null if passed, or error prompt if failed. */\n validateAndFormat: (workingDirectory: string) => Promise<string | null>;\n}\n\n/**\n * Configuration object for running the agent.\n * Built by initializeAgent (production) or constructed directly (evals).\n */\nexport type AgentRunConfig = {\n workingDirectory: string;\n mcpServers: AgentSDKOptions['mcpServers'];\n model: string;\n allowedTools: string[];\n sdkEnv: Record<string, string | undefined>;\n};\n\n/**\n * Package managers that can be used to run commands.\n * Includes JS and non-JS ecosystem package managers for multi-SDK support.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n 'pnpx',\n 'bunx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'uv',\n 'pipx',\n 'python',\n 'python3',\n // Ruby\n 'gem',\n 'bundle',\n 'bundler',\n 'ruby',\n // PHP\n 'composer',\n 'php',\n // Go\n 'go',\n // .NET\n 'dotnet',\n 'nuget',\n // Elixir\n 'mix',\n 'hex',\n 'elixir',\n // Kotlin/Java\n 'gradle',\n 'gradlew',\n './gradlew',\n 'mvn',\n];\n\n/**\n * Safe scripts/commands that can be run with any package manager.\n * Uses startsWith matching, so 'build' matches 'build', 'build:prod', etc.\n * Note: Linting tools are in LINTING_TOOLS and checked separately.\n */\nconst SAFE_SCRIPTS = [\n // Package installation\n 'install',\n 'add',\n 'ci',\n // Build\n 'build',\n // Type checking (various naming conventions)\n 'tsc',\n 'typecheck',\n 'type-check',\n 'check-types',\n 'types',\n // Linting/formatting script names (actual tools are in LINTING_TOOLS)\n 'lint',\n 'format',\n // Common cross-language commands\n 'check',\n 'test',\n 'run',\n 'serve',\n 'dev',\n 'start',\n 'compile',\n 'vet',\n // Python-specific\n 'manage.py',\n 'pytest',\n // Ruby-specific\n 'rspec',\n 'rake',\n 'routes',\n // PHP-specific\n 'artisan',\n 'phpunit',\n // Elixir-specific\n 'deps.get',\n 'credo',\n 'dialyzer',\n // .NET-specific\n 'restore',\n];\n\n/**\n * Dangerous shell operators that could allow command injection.\n * Note: We handle `2>&1` and `| tail/head` separately as safe patterns.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is an allowed package manager command.\n * Matches: <pkg-manager> [run|exec] <safe-script> [args...]\n */\nfunction matchesAllowedPrefix(command: string): boolean {\n const parts = command.split(/\\s+/);\n if (parts.length === 0 || !PACKAGE_MANAGERS.includes(parts[0])) {\n return false;\n }\n\n // Skip 'run' or 'exec' if present\n let scriptIndex = 1;\n if (parts[scriptIndex] === 'run' || parts[scriptIndex] === 'exec') {\n scriptIndex++;\n }\n\n // Get the script/command portion (may include args)\n const scriptPart = parts.slice(scriptIndex).join(' ');\n\n // Check if script starts with any safe script name or linting tool\n return (\n SAFE_SCRIPTS.some((safe) => scriptPart.startsWith(safe)) ||\n LINTING_TOOLS.some((tool) => scriptPart.startsWith(tool))\n );\n}\n\n/**\n * Permission hook that allows only safe commands.\n * - Package manager install commands\n * - Build/typecheck/lint commands for verification\n * - Piping to tail/head for output limiting is allowed\n * - Stderr redirection (2>&1) is allowed\n */\nexport function installerCanUseTool(toolName: string, input: Record<string, unknown>): PermissionResult {\n // Allow all non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (typeof input.command === 'string' ? input.command : '').trim();\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logWarn(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'dangerous operators',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Shell operators like ; \\` $ ( ) are not permitted.`,\n };\n }\n\n // Normalize: remove safe stderr redirection (2>&1, 2>&2, etc.)\n const normalized = command.replace(/\\s*\\d*>&\\d+\\s*/g, ' ').trim();\n\n // Check for pipe to tail/head (safe output limiting)\n const pipeMatch = normalized.match(/^(.+?)\\s*\\|\\s*(tail|head)(\\s+\\S+)*\\s*$/);\n if (pipeMatch) {\n const baseCommand = pipeMatch[1].trim();\n\n // Block if base command has pipes or & (multiple chaining)\n if (/[|&]/.test(baseCommand)) {\n logWarn(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'multiple pipes',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only single pipe to tail/head is permitted.`,\n };\n }\n\n if (matchesAllowedPrefix(baseCommand)) {\n logInfo(`Allowing bash command with output limiter: ${command}`);\n debug(`Allowing bash command with output limiter: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n }\n\n // Block remaining pipes and & (not covered by tail/head case above)\n if (/[|&]/.test(normalized)) {\n logWarn(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'disallowed pipe',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Pipes are only permitted with tail/head for output limiting.`,\n };\n }\n\n // Check if command starts with any allowed prefix\n if (matchesAllowedPrefix(normalized)) {\n logInfo(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logWarn(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'not in allowlist',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only install, build, typecheck, lint, and formatting commands are permitted.`,\n };\n}\n\n/**\n * Initialize agent configuration for the LLM gateway\n */\nexport async function initializeAgent(config: AgentConfig, options: InstallerOptions): Promise<AgentRunConfig> {\n // Initialize log file for this run\n initLogFile();\n logInfo('Agent initialization starting');\n logInfo('Install directory:', options.installDir);\n\n // Emit status event for adapters to render\n options.emitter?.emit('status', { message: 'Initializing Claude agent...' });\n\n try {\n let authMode: string;\n // Build SDK env without mutating process.env\n const sdkEnv: Record<string, string | undefined> = {\n ...process.env,\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: 'true',\n // Disable SDK telemetry - our gateway doesn't proxy /api/event_logging/batch\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: 'true',\n };\n\n // Placeholder bearer token for the Claude Agent SDK. The SDK's CLI\n // subprocess runs a local auth-source check at startup and exits with\n // \"Not logged in · Please run /login\" if no credentials are present in\n // its environment — even when a proxy is handling auth upstream. Setting\n // this token puts the SDK in custom-backend mode so it skips that check;\n // the credential proxy rewrites the Authorization header with the real\n // WorkOS token before forwarding upstream.\n const PROXY_PLACEHOLDER_TOKEN = 'workos-cli-proxy-placeholder';\n\n if (options.direct) {\n // Direct mode: use user's Anthropic API key, skip gateway\n if (!process.env.ANTHROPIC_API_KEY) {\n throw new Error(\n 'Direct mode requires ANTHROPIC_API_KEY environment variable.\\n' +\n 'Set it with: export ANTHROPIC_API_KEY=sk-ant-...\\n' +\n 'Get your key at: https://console.anthropic.com/settings/keys',\n );\n }\n\n // SDK defaults to api.anthropic.com when no base URL set\n delete sdkEnv.ANTHROPIC_BASE_URL;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = 'direct:api.anthropic.com';\n logInfo('Direct mode: using ANTHROPIC_API_KEY, bypassing llm-gateway');\n\n // Set analytics tag for direct mode\n analytics.setTag('api_mode', 'direct');\n } else {\n // Gateway mode (existing behavior)\n const gatewayUrl = getLlmGatewayUrlFromHost();\n\n // Check for unclaimed environment — use claim token auth\n const activeEnv = getActiveEnvironment();\n if (activeEnv && isUnclaimedEnvironment(activeEnv)) {\n activeProxyHandle = await startClaimTokenProxy({\n upstreamUrl: gatewayUrl,\n claimToken: activeEnv.claimToken,\n clientId: activeEnv.clientId,\n });\n\n sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;\n // Prevent the user's personal Anthropic key (if any) from being sent\n // to the WorkOS gateway; auth is injected by the claim-token proxy.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `claim-token-proxy:${activeProxyHandle.url}→${gatewayUrl}`;\n logInfo(`[agent-interface] Using claim token proxy for unclaimed environment`);\n } else if (!options.skipAuth && !options.local) {\n // Check/refresh authentication for production (unless skipping auth)\n if (!hasCredentials()) {\n throw new Error(`Not authenticated. Run \\`${formatWorkOSCommand('auth login')}\\` to authenticate.`);\n }\n\n const creds = getCredentials();\n if (!creds) {\n throw new Error(`Not authenticated. Run \\`${formatWorkOSCommand('auth login')}\\` to authenticate.`);\n }\n\n // Check if we have refresh token capability and proxy is not disabled\n if (creds.refreshToken && process.env.INSTALLER_DISABLE_PROXY !== '1') {\n // Start credential proxy with lazy refresh\n logInfo('[agent-interface] Starting credential proxy with lazy refresh...');\n const appConfig = getConfig();\n\n activeProxyHandle = await startCredentialProxy({\n upstreamUrl: gatewayUrl,\n refresh: {\n authkitDomain: getAuthkitDomain(),\n clientId: getCliAuthClientId(),\n refreshThresholdMs: appConfig.proxy.refreshThresholdMs,\n onRefreshSuccess: () => {\n options.emitter?.emit('status', { message: 'Session extended' });\n },\n onRefreshExpired: () => {\n logError('[agent-interface] Session expired, refresh token invalid');\n options.emitter?.emit('error', {\n message: `Session expired. Run \\`${formatWorkOSCommand('auth login')}\\` to re-authenticate.`,\n });\n },\n },\n });\n\n // Point SDK at proxy instead of direct gateway\n sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;\n logInfo(`[agent-interface] Using credential proxy at ${activeProxyHandle.url}`);\n\n // Prevent the user's personal Anthropic key (if any) from being\n // sent to the WorkOS gateway; the credential proxy rewrites the\n // Authorization header with the real WorkOS token.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `proxy:${activeProxyHandle.url}→${gatewayUrl}`;\n } else {\n // No refresh token OR proxy disabled - fall back to old behavior (5 min limit)\n if (!creds.refreshToken) {\n logWarn('[agent-interface] No refresh token available, session limited to 5 minutes');\n logWarn(`[agent-interface] Run \\`${formatWorkOSCommand('auth login')}\\` to enable extended sessions`);\n options.emitter?.emit('status', {\n message: `Note: Run \\`${formatWorkOSCommand('auth login')}\\` to enable extended sessions`,\n });\n } else {\n logWarn('[agent-interface] Proxy disabled via INSTALLER_DISABLE_PROXY');\n }\n\n const refreshResult = await ensureValidToken();\n if (!refreshResult.success) {\n throw new Error(refreshResult.error || 'Authentication failed');\n }\n\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n // Prevent the user's personal Anthropic key (if any) from being\n // forwarded to the WorkOS gateway as an x-api-key header alongside\n // the WorkOS access token we set below.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = creds.accessToken;\n authMode = options.local ? `local-gateway:${gatewayUrl}` : `workos-gateway:${gatewayUrl}`;\n logInfo('Sending access token to gateway (legacy mode)');\n }\n } else if (options.skipAuth) {\n // Skip auth mode - direct to gateway without a real token. The SDK's\n // local auth-source check would otherwise fail with \"Not logged in\",\n // so seed a placeholder bearer; the gateway is expected to accept\n // unauthenticated requests here and ignore the placeholder value.\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `skip-auth:${gatewayUrl}`;\n logInfo('Skipping auth - placeholder bearer sent to gateway');\n } else {\n // Local mode without auth - same rationale as skip-auth above.\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `local-gateway:${gatewayUrl}`;\n logInfo('Local mode - placeholder bearer sent to gateway');\n }\n\n logInfo('Configured LLM gateway:', sdkEnv.ANTHROPIC_BASE_URL);\n\n // Set analytics tag for gateway mode\n analytics.setTag('api_mode', activeProxyHandle ? 'gateway-proxy' : 'gateway');\n }\n\n // Configure WorkOS MCP docs server for accessing WorkOS documentation\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers: {\n workos: {\n command: 'npx',\n args: ['-y', '@workos/mcp-docs-server'],\n },\n },\n model: getConfig().model,\n allowedTools: ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'WebFetch'],\n sdkEnv,\n };\n\n const configInfo = { workingDirectory: agentRunConfig.workingDirectory, authMode, useMcp: false };\n logInfo('Agent config:', configInfo);\n debug('Agent config:', configInfo);\n\n // Emit status events for adapters to render\n const currentLogPath = getLogFilePath();\n if (currentLogPath) {\n options.emitter?.emit('status', { message: `Verbose logs: ${currentLogPath}` });\n }\n options.emitter?.emit('status', { message: \"Agent initialized. Let's get cooking!\" });\n\n return agentRunConfig;\n } catch (error) {\n // Clean up proxy if initialization fails\n if (activeProxyHandle) {\n logInfo('[agent-interface] Cleaning up proxy after init error');\n await activeProxyHandle.stop();\n activeProxyHandle = null;\n }\n logError('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Execute an agent with the provided prompt and options\n * Handles the full lifecycle via event emissions - adapters handle UI rendering.\n *\n * @returns An object containing any error detected in the agent's output\n */\nexport async function runAgent(\n agentConfig: AgentRunConfig,\n prompt: string,\n options: InstallerOptions,\n config?: {\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n emitter?: InstallerEventEmitter,\n retryConfig?: RetryConfig,\n onMessage?: (message: SDKMessage) => void,\n): Promise<{ error?: AgentErrorType; errorMessage?: string; retryCount?: number }> {\n const { spinnerMessage = 'Setting up WorkOS AuthKit...' } = config ?? {};\n\n const { query } = await getSDKModule();\n\n // Emit progress for adapters to handle (e.g., CLI adapter starts spinner)\n emitter?.emit('agent:progress', { step: 'Starting', detail: 'This may take a few minutes. Grab some coffee!' });\n emitter?.emit('agent:progress', { step: spinnerMessage });\n\n logInfo('Starting agent run');\n logInfo('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n\n try {\n let retryCount = 0;\n const maxRetries = retryConfig?.maxRetries ?? 0;\n\n // Turn completion signals — resolveCurrentTurn is called when a 'result'\n // message arrives; the prompt generator awaits currentTurnDone between turns.\n let resolveCurrentTurn!: () => void;\n let currentTurnDone!: Promise<void>;\n\n // Set by the message loop when a fatal SDK error is detected (e.g. service\n // unavailability). The prompt stream checks this before yielding retry\n // prompts so we fail fast instead of burning minutes on hopeless retries.\n let abortRetries = false;\n\n function resetTurnSignal() {\n currentTurnDone = new Promise<void>((resolve) => {\n resolveCurrentTurn = resolve;\n });\n }\n resetTurnSignal();\n\n const createPromptStream = async function* (): AsyncGenerator<SDKUserMessage> {\n yield {\n type: 'user' as const,\n session_id: '',\n message: { role: 'user' as const, content: prompt },\n parent_tool_use_id: null,\n };\n\n if (retryConfig && maxRetries > 0) {\n while (retryCount < maxRetries) {\n await currentTurnDone;\n\n // Don't send correction prompts when the service itself is down\n if (abortRetries) {\n logInfo('Skipping validation retries due to service error');\n break;\n }\n\n emitter?.emit('validation:retry:start', { attempt: retryCount + 1 });\n\n let validationPrompt: string | null;\n try {\n validationPrompt = await retryConfig.validateAndFormat(agentConfig.workingDirectory);\n } catch (err) {\n // Don't block on validation bugs — treat as passed\n logError('validateAndFormat threw:', err);\n validationPrompt = null;\n }\n\n emitter?.emit('validation:retry:complete', {\n attempt: retryCount + 1,\n passed: validationPrompt === null,\n });\n\n if (validationPrompt === null) break;\n\n retryCount++;\n emitter?.emit('agent:retry', { attempt: retryCount, maxRetries });\n\n resetTurnSignal();\n\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: validationPrompt },\n parent_tool_use_id: null,\n };\n }\n }\n\n await currentTurnDone;\n };\n\n // Load plugin from @workos/skills package\n\n const pluginPath = dirname(getSkillsPackageDir());\n logInfo('Loading plugin from:', pluginPath);\n\n const response = query({\n prompt: createPromptStream(),\n options: {\n model: agentConfig.model,\n cwd: agentConfig.workingDirectory,\n permissionMode: 'acceptEdits',\n mcpServers: agentConfig.mcpServers,\n env: agentConfig.sdkEnv,\n canUseTool: (toolName, input) => {\n logInfo('canUseTool called:', { toolName, input });\n const result = installerCanUseTool(toolName, input);\n logInfo('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n allowedTools: agentConfig.allowedTools,\n plugins: [{ type: 'local', path: pluginPath }],\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logInfo('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n },\n });\n\n // Process the async generator\n let sdkError: string | undefined;\n for await (const message of response) {\n const messageError = handleSDKMessage(message, options, collectedText, emitter);\n if (messageError) {\n sdkError = messageError;\n // Signal the prompt stream to stop yielding retry prompts\n abortRetries = true;\n }\n if (message.type === 'result') {\n resolveCurrentTurn();\n }\n try {\n onMessage?.(message);\n } catch {\n /* non-critical */\n }\n }\n\n const durationMs = Date.now() - startTime;\n const outputText = collectedText.join('\\n');\n\n // Check for SDK errors first (e.g., API errors, auth failures)\n // Return error type + message - caller decides whether to throw or emit events\n if (sdkError) {\n if (sdkError.startsWith(SERVICE_UNAVAILABLE_PREFIX)) {\n const detail = sdkError.slice(SERVICE_UNAVAILABLE_PREFIX.length);\n logError('AI service unavailable:', detail);\n return {\n error: AgentErrorType.SERVICE_UNAVAILABLE,\n errorMessage: 'The AI service is temporarily unavailable. Please try again in a few minutes.',\n };\n }\n if (sdkError.startsWith(RATE_LIMITED_PREFIX)) {\n const detail = sdkError.slice(RATE_LIMITED_PREFIX.length);\n logError('AI service rate-limited:', detail);\n return {\n error: AgentErrorType.SERVICE_UNAVAILABLE,\n errorMessage: 'The AI service is currently rate-limited. Please wait a minute and try again.',\n };\n }\n logError('Agent SDK error:', sdkError);\n return { error: AgentErrorType.EXECUTION_ERROR, errorMessage: sdkError };\n }\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logError('Agent error: MCP_MISSING');\n return { error: AgentErrorType.MCP_MISSING, errorMessage: 'Could not access WorkOS MCP server' };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logError('Agent error: RESOURCE_MISSING');\n return { error: AgentErrorType.RESOURCE_MISSING, errorMessage: 'Could not access setup resource' };\n }\n\n logInfo(`Agent run completed in ${Math.round(durationMs / 1000)}s (${retryCount} retries)`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: Math.round(durationMs / 1000),\n retry_count: retryCount,\n max_retries: maxRetries,\n passed_after_retry: retryCount > 0,\n });\n\n // Don't emit agent:success here - let the state machine handle lifecycle events\n return { retryCount };\n } catch (error) {\n // Don't emit events here - just log and re-throw for state machine to handle\n logError('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n } finally {\n // Always clean up proxy when agent run completes\n if (activeProxyHandle) {\n logInfo('[agent-interface] Stopping credential proxy');\n\n analytics.capture('installer.proxy', {\n action: 'stop',\n port: activeProxyHandle.port,\n });\n\n await activeProxyHandle.stop();\n activeProxyHandle = null;\n }\n }\n}\n\n/**\n * Handle SDK messages and emit events for adapters to render.\n * @returns Error message if this was an error result, undefined otherwise\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: InstallerOptions,\n collectedText: string[],\n emitter?: InstallerEventEmitter,\n): string | undefined {\n logInfo(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n switch (message.type) {\n case 'assistant': {\n // Extract usage data from Anthropic API response for telemetry\n const usage = message.message?.usage;\n if (usage) {\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const model = message.message?.model ?? 'unknown';\n analytics.llmRequest(model, inputTokens, outputTokens);\n analytics.incrementAgentIterations();\n }\n\n // Extract text content from assistant messages\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n collectedText.push(block.text);\n\n // Emit output event for dashboard\n emitter?.emit('output', { text: block.text });\n\n // Check for [STATUS] markers and emit progress events\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n const statusText = statusMatch[1].trim();\n // Emit progress event - adapters handle spinner updates\n emitter?.emit('agent:progress', { step: statusText });\n emitter?.emit('status', { message: statusText });\n }\n }\n\n // Check for tool_use blocks (Write/Edit operations)\n if (block.type === 'tool_use') {\n const toolName = block.name as string;\n const toolUseId = block.id as string;\n const input = block.input as Record<string, unknown>;\n\n // Log tool usage for debugging\n logInfo(`Tool use: ${toolName}`);\n\n // Track tool start time for telemetry\n if (toolUseId) {\n pendingToolCalls.set(toolUseId, { toolName, startTime: Date.now() });\n }\n\n // Emit file:write event for Write tool\n if (toolName === 'Write' && input) {\n const filePath = input.file_path as string;\n const fileContent = input.content as string;\n if (filePath && fileContent) {\n emitter?.emit('file:write', { path: filePath, content: fileContent });\n }\n }\n\n // Emit file:edit event for Edit tool\n if (toolName === 'Edit' && input) {\n const filePath = input.file_path as string;\n const oldString = input.old_string as string;\n const newString = input.new_string as string;\n if (filePath && oldString !== undefined && newString !== undefined) {\n // Emit the actual strings being replaced, not reconstructed full file\n emitter?.emit('file:edit', {\n path: filePath,\n oldContent: oldString,\n newContent: newString,\n });\n }\n }\n\n // Track Read operations for caching file content later\n if (toolName === 'Read' && input && block.id) {\n const filePath = input.file_path as string;\n if (filePath) {\n pendingReads.set(block.id as string, filePath);\n }\n }\n }\n }\n }\n break;\n }\n\n case 'user': {\n // User messages contain tool results\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n // Tool results contain file content from Read operations\n if (block.type === 'tool_result' && block.tool_use_id) {\n const toolUseId = block.tool_use_id as string;\n\n // Emit telemetry for completed tool call\n const pendingTool = pendingToolCalls.get(toolUseId);\n if (pendingTool) {\n const durationMs = Date.now() - pendingTool.startTime;\n // Check if tool result indicates error (is_error field or error in content)\n const isError = block.is_error === true;\n analytics.toolCalled(pendingTool.toolName, durationMs, !isError);\n pendingToolCalls.delete(toolUseId);\n }\n\n const filePath = pendingReads.get(toolUseId);\n if (filePath) {\n // Extract content from the tool result\n let resultContent = '';\n if (typeof block.content === 'string') {\n resultContent = block.content;\n } else if (Array.isArray(block.content)) {\n // Content might be array of text blocks\n for (const item of block.content) {\n if (item.type === 'text' && item.text) {\n resultContent += item.text;\n }\n }\n }\n if (resultContent) {\n fileContentCache.set(filePath, resultContent);\n }\n pendingReads.delete(toolUseId);\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // The SDK may return subtype 'success' with is_error: true when API\n // retries are exhausted (e.g., persistent 500s). Check is_error first.\n const isResultError = (message as Record<string, unknown>).is_error === true;\n\n if (isResultError) {\n const resultText = typeof message.result === 'string' ? message.result : '';\n logError('Agent result marked as error:', resultText);\n\n // Detect rate limiting (429) — check before 5xx so it gets distinct messaging\n if (/\\b429\\b/.test(resultText) || /rate.limit/i.test(resultText)) {\n return `${RATE_LIMITED_PREFIX}${resultText}`;\n }\n\n // Detect service unavailability (API 500, upstream outage)\n if (/\\b50[0-9]\\b/.test(resultText) || /server_error|internal_error|overloaded/.test(resultText)) {\n return `${SERVICE_UNAVAILABLE_PREFIX}${resultText}`;\n }\n return resultText || 'Agent execution failed';\n }\n\n if (message.subtype === 'success') {\n logInfo('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n // Error result\n logError('Agent error result:', message.subtype);\n if (message.errors && message.errors.length > 0) {\n for (const err of message.errors) {\n logError('ERROR:', err);\n // Emit error event - adapters handle rendering\n emitter?.emit('error', { message: err });\n }\n // Return the first error message\n return message.errors[0];\n }\n // Return generic error if subtype indicates failure but no errors array\n return `Agent execution failed: ${message.subtype}`;\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logInfo('Agent session initialized', {\n model: message.model,\n tools: message.tools?.length,\n mcpServers: message.mcp_servers,\n });\n }\n break;\n }\n\n default:\n // Log other message types for debugging\n if (options.debug) {\n debug(`Unhandled message type: ${message.type}`);\n }\n break;\n }\n return undefined;\n}\n\n/**\n * Get the active proxy handle (for testing/debugging).\n */\nexport function getActiveProxyHandle(): CredentialProxyHandle | null {\n return activeProxyHandle;\n}\n"]}
1
+ {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../src/lib/agent-interface.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,YAAY,IAAI,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrE,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnG,OAAO,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,EAAE,gCAAgC,EAAE,MAAM,gBAAgB,CAAC;AAClE,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,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AED;YACE,wCAAwC;YACxC,IAAI,OAAO,CAAC,KAAK,EAAE,CAAC;gBAClB,KAAK,CAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,oBAAoB;IAClC,OAAO,iBAAiB,CAAC;AAC3B,CAAC","sourcesContent":["/**\n * Shared agent interface for WorkOS wizards\n * Uses Claude Agent SDK directly with WorkOS MCP server\n */\n\nimport { dirname } from 'path';\nimport { getSkillsDir as getSkillsPackageDir } from '@workos/skills';\nimport { debug, logInfo, logWarn, logError, initLogFile, getLogFilePath } from '../utils/debug.js';\nimport type { InstallerOptions } from '../utils/types.js';\nimport { analytics } from '../utils/analytics.js';\nimport { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';\nimport { LINTING_TOOLS } from './safe-tools.js';\nimport { formatWorkOSCommand } from '../utils/command-invocation.js';\nimport { getConfig } from './settings.js';\nimport { getLlmGatewayUrl } from '../utils/urls.js';\nimport { getCredentials, hasCredentials } from './credentials.js';\nimport { ensureValidToken } from './token-refresh.js';\nimport type { InstallerEventEmitter } from './events.js';\nimport { startCredentialProxy, startClaimTokenProxy, type CredentialProxyHandle } from './credential-proxy.js';\nimport { getActiveEnvironment, isUnclaimedEnvironment } from './config-store.js';\nimport { getAuthkitDomain, getCliAuthClientId } from './settings.js';\nimport type {\n SDKMessage,\n SDKUserMessage,\n Options as AgentSDKOptions,\n PermissionResult,\n query as queryFn,\n} from '@anthropic-ai/claude-agent-sdk';\n\n// File content cache for computing edit diffs\nconst fileContentCache = new Map<string, string>();\n// Track pending Read operations by tool_use_id\nconst pendingReads = new Map<string, string>();\n// Track tool start times by tool_use_id for telemetry\nconst pendingToolCalls = new Map<string, { toolName: string; startTime: number }>();\n\n// Module-level variable to track proxy handle for cleanup\nlet activeProxyHandle: CredentialProxyHandle | null = null;\n\n// Dynamic import cache for ESM module\nlet _sdkModule: { query: typeof queryFn } | null = null;\nasync function getSDKModule(): Promise<{ query: typeof queryFn }> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\nexport const AgentSignals = {\n /** Signal emitted when the agent reports progress to the user */\n STATUS: '[STATUS]',\n /** Signal emitted when the agent cannot access the WorkOS MCP server */\n ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',\n /** Signal emitted when the agent cannot access the setup resource */\n ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',\n} as const;\n\nexport type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];\n\n/** Internal prefix used to tag service-unavailability errors from handleSDKMessage */\nconst SERVICE_UNAVAILABLE_PREFIX = '__SERVICE_UNAVAILABLE__';\n\n/** Internal prefix used to tag rate-limit errors from handleSDKMessage */\nconst RATE_LIMITED_PREFIX = '__RATE_LIMITED__';\n\n/**\n * Error types that can be returned from agent execution.\n * These correspond to the error signals that the agent emits.\n */\nexport enum AgentErrorType {\n /** Agent could not access the WorkOS MCP server */\n MCP_MISSING = 'INSTALLER_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'INSTALLER_RESOURCE_MISSING',\n /** Agent execution failed (API error, auth error, etc.) */\n EXECUTION_ERROR = 'INSTALLER_EXECUTION_ERROR',\n /** AI service is unavailable (API 500, outage, etc.) */\n SERVICE_UNAVAILABLE = 'INSTALLER_SERVICE_UNAVAILABLE',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n workOSApiKey: string;\n workOSApiHost: string;\n};\n\nexport interface RetryConfig {\n /** Max correction attempts after initial run. Default: 2 */\n maxRetries: number;\n /** Run between agent turns. Return null if passed, or error prompt if failed. */\n validateAndFormat: (workingDirectory: string) => Promise<string | null>;\n}\n\n/**\n * Configuration object for running the agent.\n * Built by initializeAgent (production) or constructed directly (evals).\n */\nexport type AgentRunConfig = {\n workingDirectory: string;\n mcpServers: AgentSDKOptions['mcpServers'];\n model: string;\n allowedTools: string[];\n sdkEnv: Record<string, string | undefined>;\n};\n\n/**\n * Package managers that can be used to run commands.\n * Includes JS and non-JS ecosystem package managers for multi-SDK support.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n 'pnpx',\n 'bunx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'uv',\n 'pipx',\n 'python',\n 'python3',\n // Ruby\n 'gem',\n 'bundle',\n 'bundler',\n 'ruby',\n // PHP\n 'composer',\n 'php',\n // Go\n 'go',\n // .NET\n 'dotnet',\n 'nuget',\n // Elixir\n 'mix',\n 'hex',\n 'elixir',\n // Kotlin/Java\n 'gradle',\n 'gradlew',\n './gradlew',\n 'mvn',\n];\n\n/**\n * Safe scripts/commands that can be run with any package manager.\n * Uses startsWith matching, so 'build' matches 'build', 'build:prod', etc.\n * Note: Linting tools are in LINTING_TOOLS and checked separately.\n */\nconst SAFE_SCRIPTS = [\n // Package installation\n 'install',\n 'add',\n 'ci',\n // Build\n 'build',\n // Type checking (various naming conventions)\n 'tsc',\n 'typecheck',\n 'type-check',\n 'check-types',\n 'types',\n // Linting/formatting script names (actual tools are in LINTING_TOOLS)\n 'lint',\n 'format',\n // Common cross-language commands\n 'check',\n 'test',\n 'run',\n 'serve',\n 'dev',\n 'start',\n 'compile',\n 'vet',\n // Python-specific\n 'manage.py',\n 'pytest',\n // Ruby-specific\n 'rspec',\n 'rake',\n 'routes',\n // PHP-specific\n 'artisan',\n 'phpunit',\n // Elixir-specific\n 'deps.get',\n 'credo',\n 'dialyzer',\n // .NET-specific\n 'restore',\n];\n\n/**\n * Dangerous shell operators that could allow command injection.\n * Note: We handle `2>&1` and `| tail/head` separately as safe patterns.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is an allowed package manager command.\n * Matches: <pkg-manager> [run|exec] <safe-script> [args...]\n */\nfunction matchesAllowedPrefix(command: string): boolean {\n const parts = command.split(/\\s+/);\n if (parts.length === 0 || !PACKAGE_MANAGERS.includes(parts[0])) {\n return false;\n }\n\n // Skip 'run' or 'exec' if present\n let scriptIndex = 1;\n if (parts[scriptIndex] === 'run' || parts[scriptIndex] === 'exec') {\n scriptIndex++;\n }\n\n // Get the script/command portion (may include args)\n const scriptPart = parts.slice(scriptIndex).join(' ');\n\n // Check if script starts with any safe script name or linting tool\n return (\n SAFE_SCRIPTS.some((safe) => scriptPart.startsWith(safe)) ||\n LINTING_TOOLS.some((tool) => scriptPart.startsWith(tool))\n );\n}\n\n/**\n * Permission hook that allows only safe commands.\n * - Package manager install commands\n * - Build/typecheck/lint commands for verification\n * - Piping to tail/head for output limiting is allowed\n * - Stderr redirection (2>&1) is allowed\n */\nexport function installerCanUseTool(toolName: string, input: Record<string, unknown>): PermissionResult {\n // Allow all non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (typeof input.command === 'string' ? input.command : '').trim();\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logWarn(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'dangerous operators',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Shell operators like ; \\` $ ( ) are not permitted.`,\n };\n }\n\n // Normalize: remove safe stderr redirection (2>&1, 2>&2, etc.)\n const normalized = command.replace(/\\s*\\d*>&\\d+\\s*/g, ' ').trim();\n\n // Check for pipe to tail/head (safe output limiting)\n const pipeMatch = normalized.match(/^(.+?)\\s*\\|\\s*(tail|head)(\\s+\\S+)*\\s*$/);\n if (pipeMatch) {\n const baseCommand = pipeMatch[1].trim();\n\n // Block if base command has pipes or & (multiple chaining)\n if (/[|&]/.test(baseCommand)) {\n logWarn(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'multiple pipes',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only single pipe to tail/head is permitted.`,\n };\n }\n\n if (matchesAllowedPrefix(baseCommand)) {\n logInfo(`Allowing bash command with output limiter: ${command}`);\n debug(`Allowing bash command with output limiter: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n }\n\n // Block remaining pipes and & (not covered by tail/head case above)\n if (/[|&]/.test(normalized)) {\n logWarn(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'disallowed pipe',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Pipes are only permitted with tail/head for output limiting.`,\n };\n }\n\n // Check if command starts with any allowed prefix\n if (matchesAllowedPrefix(normalized)) {\n logInfo(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logWarn(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'bash command denied',\n reason: 'not in allowlist',\n command,\n });\n return {\n behavior: 'deny',\n message: `Bash command not allowed. Only install, build, typecheck, lint, and formatting commands are permitted.`,\n };\n}\n\n/**\n * Initialize agent configuration for the LLM gateway\n */\nexport async function initializeAgent(config: AgentConfig, options: InstallerOptions): Promise<AgentRunConfig> {\n // Initialize log file for this run\n initLogFile();\n logInfo('Agent initialization starting');\n logInfo('Install directory:', options.installDir);\n\n // Emit status event for adapters to render\n options.emitter?.emit('status', { message: 'Initializing Claude agent...' });\n\n try {\n let authMode: string;\n // Build SDK env without mutating process.env\n const sdkEnv: Record<string, string | undefined> = {\n ...process.env,\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: 'true',\n // Disable SDK telemetry - our gateway doesn't proxy /api/event_logging/batch\n CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: 'true',\n };\n\n // Placeholder bearer token for the Claude Agent SDK. The SDK's CLI\n // subprocess runs a local auth-source check at startup and exits with\n // \"Not logged in · Please run /login\" if no credentials are present in\n // its environment — even when a proxy is handling auth upstream. Setting\n // this token puts the SDK in custom-backend mode so it skips that check;\n // the credential proxy rewrites the Authorization header with the real\n // WorkOS token before forwarding upstream.\n const PROXY_PLACEHOLDER_TOKEN = 'workos-cli-proxy-placeholder';\n\n if (options.direct) {\n // Direct mode: use user's Anthropic API key, skip gateway\n if (!process.env.ANTHROPIC_API_KEY) {\n throw new Error(\n 'Direct mode requires ANTHROPIC_API_KEY environment variable.\\n' +\n 'Set it with: export ANTHROPIC_API_KEY=sk-ant-...\\n' +\n 'Get your key at: https://console.anthropic.com/settings/keys',\n );\n }\n\n // SDK defaults to api.anthropic.com when no base URL set\n delete sdkEnv.ANTHROPIC_BASE_URL;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = 'direct:api.anthropic.com';\n logInfo('Direct mode: using ANTHROPIC_API_KEY, bypassing llm-gateway');\n\n // Set analytics tag for direct mode\n analytics.setTag('api_mode', 'direct');\n } else {\n // Gateway mode (existing behavior)\n const gatewayUrl = getLlmGatewayUrl();\n\n // Check for unclaimed environment — use claim token auth\n const activeEnv = getActiveEnvironment();\n if (activeEnv && isUnclaimedEnvironment(activeEnv)) {\n activeProxyHandle = await startClaimTokenProxy({\n upstreamUrl: gatewayUrl,\n claimToken: activeEnv.claimToken,\n clientId: activeEnv.clientId,\n });\n\n sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;\n // Prevent the user's personal Anthropic key (if any) from being sent\n // to the WorkOS gateway; auth is injected by the claim-token proxy.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `claim-token-proxy:${activeProxyHandle.url}→${gatewayUrl}`;\n logInfo(`[agent-interface] Using claim token proxy for unclaimed environment`);\n } else if (!options.skipAuth && !options.local) {\n // Check/refresh authentication for production (unless skipping auth)\n if (!hasCredentials()) {\n throw new Error(`Not authenticated. Run \\`${formatWorkOSCommand('auth login')}\\` to authenticate.`);\n }\n\n const creds = getCredentials();\n if (!creds) {\n throw new Error(`Not authenticated. Run \\`${formatWorkOSCommand('auth login')}\\` to authenticate.`);\n }\n\n // Check if we have refresh token capability and proxy is not disabled\n if (creds.refreshToken && process.env.WORKOS_DISABLE_PROXY !== '1') {\n // Start credential proxy with lazy refresh\n logInfo('[agent-interface] Starting credential proxy with lazy refresh...');\n const appConfig = getConfig();\n\n activeProxyHandle = await startCredentialProxy({\n upstreamUrl: gatewayUrl,\n refresh: {\n authkitDomain: getAuthkitDomain(),\n clientId: getCliAuthClientId(),\n refreshThresholdMs: appConfig.proxy.refreshThresholdMs,\n onRefreshSuccess: () => {\n options.emitter?.emit('status', { message: 'Session extended' });\n },\n onRefreshExpired: () => {\n logError('[agent-interface] Session expired, refresh token invalid');\n options.emitter?.emit('error', {\n message: `Session expired. Run \\`${formatWorkOSCommand('auth login')}\\` to re-authenticate.`,\n });\n },\n },\n });\n\n // Point SDK at proxy instead of direct gateway\n sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;\n logInfo(`[agent-interface] Using credential proxy at ${activeProxyHandle.url}`);\n\n // Prevent the user's personal Anthropic key (if any) from being\n // sent to the WorkOS gateway; the credential proxy rewrites the\n // Authorization header with the real WorkOS token.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `proxy:${activeProxyHandle.url}→${gatewayUrl}`;\n } else {\n // No refresh token OR proxy disabled - fall back to old behavior (5 min limit)\n if (!creds.refreshToken) {\n logWarn('[agent-interface] No refresh token available, session limited to 5 minutes');\n logWarn(`[agent-interface] Run \\`${formatWorkOSCommand('auth login')}\\` to enable extended sessions`);\n options.emitter?.emit('status', {\n message: `Note: Run \\`${formatWorkOSCommand('auth login')}\\` to enable extended sessions`,\n });\n } else {\n logWarn('[agent-interface] Proxy disabled via WORKOS_DISABLE_PROXY');\n }\n\n const refreshResult = await ensureValidToken();\n if (!refreshResult.success) {\n throw new Error(refreshResult.error || 'Authentication failed');\n }\n\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n // Prevent the user's personal Anthropic key (if any) from being\n // forwarded to the WorkOS gateway as an x-api-key header alongside\n // the WorkOS access token we set below.\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = creds.accessToken;\n authMode = options.local ? `local-gateway:${gatewayUrl}` : `workos-gateway:${gatewayUrl}`;\n logInfo('Sending access token to gateway (legacy mode)');\n }\n } else if (options.skipAuth) {\n // Skip auth mode - direct to gateway without a real token. The SDK's\n // local auth-source check would otherwise fail with \"Not logged in\",\n // so seed a placeholder bearer; the gateway is expected to accept\n // unauthenticated requests here and ignore the placeholder value.\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `skip-auth:${gatewayUrl}`;\n logInfo('Skipping auth - placeholder bearer sent to gateway');\n } else {\n // Local mode without auth - same rationale as skip-auth above.\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_API_KEY;\n sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;\n authMode = `local-gateway:${gatewayUrl}`;\n logInfo('Local mode - placeholder bearer sent to gateway');\n }\n\n logInfo('Configured LLM gateway:', sdkEnv.ANTHROPIC_BASE_URL);\n\n // Set analytics tag for gateway mode\n analytics.setTag('api_mode', activeProxyHandle ? 'gateway-proxy' : 'gateway');\n }\n\n // Configure WorkOS MCP docs server for accessing WorkOS documentation\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers: {\n workos: {\n command: 'npx',\n args: ['-y', '@workos/mcp-docs-server'],\n },\n },\n model: getConfig().model,\n allowedTools: ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'WebFetch'],\n sdkEnv,\n };\n\n const configInfo = { workingDirectory: agentRunConfig.workingDirectory, authMode, useMcp: false };\n logInfo('Agent config:', configInfo);\n debug('Agent config:', configInfo);\n\n // Emit status events for adapters to render\n const currentLogPath = getLogFilePath();\n if (currentLogPath) {\n options.emitter?.emit('status', { message: `Verbose logs: ${currentLogPath}` });\n }\n options.emitter?.emit('status', { message: \"Agent initialized. Let's get cooking!\" });\n\n return agentRunConfig;\n } catch (error) {\n // Clean up proxy if initialization fails\n if (activeProxyHandle) {\n logInfo('[agent-interface] Cleaning up proxy after init error');\n await activeProxyHandle.stop();\n activeProxyHandle = null;\n }\n logError('Agent initialization error:', error);\n throw error;\n }\n}\n\n/**\n * Execute an agent with the provided prompt and options\n * Handles the full lifecycle via event emissions - adapters handle UI rendering.\n *\n * @returns An object containing any error detected in the agent's output\n */\nexport async function runAgent(\n agentConfig: AgentRunConfig,\n prompt: string,\n options: InstallerOptions,\n config?: {\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n emitter?: InstallerEventEmitter,\n retryConfig?: RetryConfig,\n onMessage?: (message: SDKMessage) => void,\n): Promise<{ error?: AgentErrorType; errorMessage?: string; retryCount?: number }> {\n const { spinnerMessage = 'Setting up WorkOS AuthKit...' } = config ?? {};\n\n const { query } = await getSDKModule();\n\n // Emit progress for adapters to handle (e.g., CLI adapter starts spinner)\n emitter?.emit('agent:progress', { step: 'Starting', detail: 'This may take a few minutes. Grab some coffee!' });\n emitter?.emit('agent:progress', { step: spinnerMessage });\n\n logInfo('Starting agent run');\n logInfo('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n\n try {\n let retryCount = 0;\n const maxRetries = retryConfig?.maxRetries ?? 0;\n\n // Turn completion signals — resolveCurrentTurn is called when a 'result'\n // message arrives; the prompt generator awaits currentTurnDone between turns.\n let resolveCurrentTurn!: () => void;\n let currentTurnDone!: Promise<void>;\n\n // Set by the message loop when a fatal SDK error is detected (e.g. service\n // unavailability). The prompt stream checks this before yielding retry\n // prompts so we fail fast instead of burning minutes on hopeless retries.\n let abortRetries = false;\n\n function resetTurnSignal() {\n currentTurnDone = new Promise<void>((resolve) => {\n resolveCurrentTurn = resolve;\n });\n }\n resetTurnSignal();\n\n const createPromptStream = async function* (): AsyncGenerator<SDKUserMessage> {\n yield {\n type: 'user' as const,\n session_id: '',\n message: { role: 'user' as const, content: prompt },\n parent_tool_use_id: null,\n };\n\n if (retryConfig && maxRetries > 0) {\n while (retryCount < maxRetries) {\n await currentTurnDone;\n\n // Don't send correction prompts when the service itself is down\n if (abortRetries) {\n logInfo('Skipping validation retries due to service error');\n break;\n }\n\n emitter?.emit('validation:retry:start', { attempt: retryCount + 1 });\n\n let validationPrompt: string | null;\n try {\n validationPrompt = await retryConfig.validateAndFormat(agentConfig.workingDirectory);\n } catch (err) {\n // Don't block on validation bugs — treat as passed\n logError('validateAndFormat threw:', err);\n validationPrompt = null;\n }\n\n emitter?.emit('validation:retry:complete', {\n attempt: retryCount + 1,\n passed: validationPrompt === null,\n });\n\n if (validationPrompt === null) break;\n\n retryCount++;\n emitter?.emit('agent:retry', { attempt: retryCount, maxRetries });\n\n resetTurnSignal();\n\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: validationPrompt },\n parent_tool_use_id: null,\n };\n }\n }\n\n await currentTurnDone;\n };\n\n // Load plugin from @workos/skills package\n\n const pluginPath = dirname(getSkillsPackageDir());\n logInfo('Loading plugin from:', pluginPath);\n\n const response = query({\n prompt: createPromptStream(),\n options: {\n model: agentConfig.model,\n cwd: agentConfig.workingDirectory,\n permissionMode: 'acceptEdits',\n mcpServers: agentConfig.mcpServers,\n env: agentConfig.sdkEnv,\n canUseTool: (toolName, input) => {\n logInfo('canUseTool called:', { toolName, input });\n const result = installerCanUseTool(toolName, input);\n logInfo('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n allowedTools: agentConfig.allowedTools,\n plugins: [{ type: 'local', path: pluginPath }],\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logInfo('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n },\n });\n\n // Process the async generator\n let sdkError: string | undefined;\n for await (const message of response) {\n const messageError = handleSDKMessage(message, options, collectedText, emitter);\n if (messageError) {\n sdkError = messageError;\n // Signal the prompt stream to stop yielding retry prompts\n abortRetries = true;\n }\n if (message.type === 'result') {\n resolveCurrentTurn();\n }\n try {\n onMessage?.(message);\n } catch {\n /* non-critical */\n }\n }\n\n const durationMs = Date.now() - startTime;\n const outputText = collectedText.join('\\n');\n\n // Check for SDK errors first (e.g., API errors, auth failures)\n // Return error type + message - caller decides whether to throw or emit events\n if (sdkError) {\n if (sdkError.startsWith(SERVICE_UNAVAILABLE_PREFIX)) {\n const detail = sdkError.slice(SERVICE_UNAVAILABLE_PREFIX.length);\n logError('AI service unavailable:', detail);\n return {\n error: AgentErrorType.SERVICE_UNAVAILABLE,\n errorMessage: 'The AI service is temporarily unavailable. Please try again in a few minutes.',\n };\n }\n if (sdkError.startsWith(RATE_LIMITED_PREFIX)) {\n const detail = sdkError.slice(RATE_LIMITED_PREFIX.length);\n logError('AI service rate-limited:', detail);\n return {\n error: AgentErrorType.SERVICE_UNAVAILABLE,\n errorMessage: 'The AI service is currently rate-limited. Please wait a minute and try again.',\n };\n }\n logError('Agent SDK error:', sdkError);\n return { error: AgentErrorType.EXECUTION_ERROR, errorMessage: sdkError };\n }\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logError('Agent error: MCP_MISSING');\n return { error: AgentErrorType.MCP_MISSING, errorMessage: 'Could not access WorkOS MCP server' };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logError('Agent error: RESOURCE_MISSING');\n return { error: AgentErrorType.RESOURCE_MISSING, errorMessage: 'Could not access setup resource' };\n }\n\n logInfo(`Agent run completed in ${Math.round(durationMs / 1000)}s (${retryCount} retries)`);\n analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: Math.round(durationMs / 1000),\n retry_count: retryCount,\n max_retries: maxRetries,\n passed_after_retry: retryCount > 0,\n });\n\n // Don't emit agent:success here - let the state machine handle lifecycle events\n return { retryCount };\n } catch (error) {\n // Don't emit events here - just log and re-throw for state machine to handle\n logError('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n } finally {\n // Always clean up proxy when agent run completes\n if (activeProxyHandle) {\n logInfo('[agent-interface] Stopping credential proxy');\n\n analytics.capture('installer.proxy', {\n action: 'stop',\n port: activeProxyHandle.port,\n });\n\n await activeProxyHandle.stop();\n activeProxyHandle = null;\n }\n }\n}\n\n/**\n * Handle SDK messages and emit events for adapters to render.\n * @returns Error message if this was an error result, undefined otherwise\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: InstallerOptions,\n collectedText: string[],\n emitter?: InstallerEventEmitter,\n): string | undefined {\n logInfo(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n switch (message.type) {\n case 'assistant': {\n // Extract usage data from Anthropic API response for telemetry\n const usage = message.message?.usage;\n if (usage) {\n const inputTokens = usage.input_tokens ?? 0;\n const outputTokens = usage.output_tokens ?? 0;\n const model = message.message?.model ?? 'unknown';\n analytics.llmRequest(model, inputTokens, outputTokens);\n analytics.incrementAgentIterations();\n }\n\n // Extract text content from assistant messages\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block.type === 'text' && typeof block.text === 'string') {\n collectedText.push(block.text);\n\n // Emit output event for dashboard\n emitter?.emit('output', { text: block.text });\n\n // Check for [STATUS] markers and emit progress events\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n const statusText = statusMatch[1].trim();\n // Emit progress event - adapters handle spinner updates\n emitter?.emit('agent:progress', { step: statusText });\n emitter?.emit('status', { message: statusText });\n }\n }\n\n // Check for tool_use blocks (Write/Edit operations)\n if (block.type === 'tool_use') {\n const toolName = block.name as string;\n const toolUseId = block.id as string;\n const input = block.input as Record<string, unknown>;\n\n // Log tool usage for debugging\n logInfo(`Tool use: ${toolName}`);\n\n // Track tool start time for telemetry\n if (toolUseId) {\n pendingToolCalls.set(toolUseId, { toolName, startTime: Date.now() });\n }\n\n // Emit file:write event for Write tool\n if (toolName === 'Write' && input) {\n const filePath = input.file_path as string;\n const fileContent = input.content as string;\n if (filePath && fileContent) {\n emitter?.emit('file:write', { path: filePath, content: fileContent });\n }\n }\n\n // Emit file:edit event for Edit tool\n if (toolName === 'Edit' && input) {\n const filePath = input.file_path as string;\n const oldString = input.old_string as string;\n const newString = input.new_string as string;\n if (filePath && oldString !== undefined && newString !== undefined) {\n // Emit the actual strings being replaced, not reconstructed full file\n emitter?.emit('file:edit', {\n path: filePath,\n oldContent: oldString,\n newContent: newString,\n });\n }\n }\n\n // Track Read operations for caching file content later\n if (toolName === 'Read' && input && block.id) {\n const filePath = input.file_path as string;\n if (filePath) {\n pendingReads.set(block.id as string, filePath);\n }\n }\n }\n }\n }\n break;\n }\n\n case 'user': {\n // User messages contain tool results\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n // Tool results contain file content from Read operations\n if (block.type === 'tool_result' && block.tool_use_id) {\n const toolUseId = block.tool_use_id as string;\n\n // Emit telemetry for completed tool call\n const pendingTool = pendingToolCalls.get(toolUseId);\n if (pendingTool) {\n const durationMs = Date.now() - pendingTool.startTime;\n // Check if tool result indicates error (is_error field or error in content)\n const isError = block.is_error === true;\n analytics.toolCalled(pendingTool.toolName, durationMs, !isError);\n pendingToolCalls.delete(toolUseId);\n }\n\n const filePath = pendingReads.get(toolUseId);\n if (filePath) {\n // Extract content from the tool result\n let resultContent = '';\n if (typeof block.content === 'string') {\n resultContent = block.content;\n } else if (Array.isArray(block.content)) {\n // Content might be array of text blocks\n for (const item of block.content) {\n if (item.type === 'text' && item.text) {\n resultContent += item.text;\n }\n }\n }\n if (resultContent) {\n fileContentCache.set(filePath, resultContent);\n }\n pendingReads.delete(toolUseId);\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // The SDK may return subtype 'success' with is_error: true when API\n // retries are exhausted (e.g., persistent 500s). Check is_error first.\n const isResultError = (message as Record<string, unknown>).is_error === true;\n\n if (isResultError) {\n const resultText = typeof message.result === 'string' ? message.result : '';\n logError('Agent result marked as error:', resultText);\n\n // Detect rate limiting (429) — check before 5xx so it gets distinct messaging\n if (/\\b429\\b/.test(resultText) || /rate.limit/i.test(resultText)) {\n return `${RATE_LIMITED_PREFIX}${resultText}`;\n }\n\n // Detect service unavailability (API 500, upstream outage)\n if (/\\b50[0-9]\\b/.test(resultText) || /server_error|internal_error|overloaded/.test(resultText)) {\n return `${SERVICE_UNAVAILABLE_PREFIX}${resultText}`;\n }\n return resultText || 'Agent execution failed';\n }\n\n if (message.subtype === 'success') {\n logInfo('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n // Error result\n logError('Agent error result:', message.subtype);\n if (message.errors && message.errors.length > 0) {\n for (const err of message.errors) {\n logError('ERROR:', err);\n // Emit error event - adapters handle rendering\n emitter?.emit('error', { message: err });\n }\n // Return the first error message\n return message.errors[0];\n }\n // Return generic error if subtype indicates failure but no errors array\n return `Agent execution failed: ${message.subtype}`;\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logInfo('Agent session initialized', {\n model: message.model,\n tools: message.tools?.length,\n mcpServers: message.mcp_servers,\n });\n }\n break;\n }\n\n default:\n // Log other message types for debugging\n if (options.debug) {\n debug(`Unhandled message type: ${message.type}`);\n }\n break;\n }\n return undefined;\n}\n\n/**\n * Get the active proxy handle (for testing/debugging).\n */\nexport function getActiveProxyHandle(): CredentialProxyHandle | null {\n return activeProxyHandle;\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import Anthropic from '@anthropic-ai/sdk';
2
2
  import { startCredentialProxy } from './credential-proxy.js';
3
- import { getLlmGatewayUrl, getAuthkitDomain, getCliAuthClientId, getConfig } from './settings.js';
3
+ import { getAuthkitDomain, getCliAuthClientId, getConfig } from './settings.js';
4
+ import { getLlmGatewayUrl } from '../utils/urls.js';
4
5
  import { getCredentials } from './credentials.js';
5
6
  import { logInfo, logError } from '../utils/debug.js';
6
7
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"ai-content.js","sourceRoot":"","sources":["../../src/lib/ai-content.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAClG,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAOtD;;;GAGG;AACH,KAAK,UAAU,SAAS,CAAI,EAAqC;IAC/D,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;IACtC,MAAM,KAAK,GAAG,cAAc,EAAE,CAAC;IAE/B,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,CAAC;QACzB,4DAA4D;QAC5D,OAAO,CAAC,2DAA2D,CAAC,CAAC;QACrE,MAAM,MAAM,GAAG,IAAI,SAAS,CAAC;YAC3B,OAAO,EAAE,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UAAU,EAAE,GAAG;gBACf,QAAQ,EAAE;oBACR;wBACE,IAAI,EAAE,MAAM;wBACZ,OAAO,EAAE,0CAA0C,aAAa;;aAE/D,WAAW;iBACP,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;kCAOC;qBACvB;iBACF;aACF,CAAC,CAAC;YAEH,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACjC,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACzB,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAC1B,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,QAAQ,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO;uCAC4B,WAAW;;;EAGhD,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;;;wCAGC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\nimport { startCredentialProxy } from './credential-proxy.js';\nimport { getLlmGatewayUrl, getAuthkitDomain, getCliAuthClientId, getConfig } from './settings.js';\nimport { getCredentials } from './credentials.js';\nimport { logInfo, logError } from '../utils/debug.js';\n\nexport interface AiContentOptions {\n /** Use direct Anthropic API instead of llm-gateway */\n direct?: boolean;\n}\n\n/**\n * Execute an API call through a short-lived credential proxy.\n * Handles proxy lifecycle automatically.\n */\nasync function withProxy<T>(fn: (client: Anthropic) => Promise<T>): Promise<T> {\n const gatewayUrl = getLlmGatewayUrl();\n const creds = getCredentials();\n\n if (!creds?.refreshToken) {\n // No refresh token - use credentials directly (legacy mode)\n logInfo('[ai-content] No refresh token, using credentials directly');\n const client = new Anthropic({\n baseURL: gatewayUrl,\n apiKey: 'gateway', // SDK requires something, gateway uses Authorization header\n defaultHeaders: creds?.accessToken ? { Authorization: `Bearer ${creds.accessToken}` } : undefined,\n });\n return fn(client);\n }\n\n // Start short-lived proxy\n const proxy = await startCredentialProxy({\n upstreamUrl: gatewayUrl,\n refresh: {\n authkitDomain: getAuthkitDomain(),\n clientId: getCliAuthClientId(),\n refreshThresholdMs: getConfig().proxy.refreshThresholdMs,\n },\n });\n\n logInfo(`[ai-content] Started proxy at ${proxy.url}`);\n\n try {\n const client = new Anthropic({\n baseURL: proxy.url,\n apiKey: 'proxy', // SDK requires something, proxy handles real auth\n });\n return await fn(client);\n } finally {\n await proxy.stop();\n logInfo('[ai-content] Stopped proxy');\n }\n}\n\n/**\n * Execute an API call directly to Anthropic (--direct mode).\n */\nasync function withDirect<T>(fn: (client: Anthropic) => Promise<T>): Promise<T> {\n // SDK reads ANTHROPIC_API_KEY from env automatically\n const client = new Anthropic();\n return fn(client);\n}\n\n/**\n * Generate a concise commit message for the AuthKit integration.\n * Falls back to a default message if AI generation fails.\n */\nexport async function generateCommitMessage(\n integration: string,\n files: string[],\n options: AiContentOptions = {},\n): Promise<string> {\n const executor = options.direct ? withDirect : withProxy;\n\n try {\n return await executor(async (client) => {\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 100,\n messages: [\n {\n role: 'user',\n content: `Generate a concise git commit message for adding WorkOS AuthKit to a ${integration} project. Changed files: ${files.slice(0, 10).join(', ')}. Use conventional commit format (feat:). One line only, under 72 chars.`,\n },\n ],\n });\n\n const text = response.content[0];\n if (text.type === 'text') {\n return text.text.trim();\n }\n throw new Error('Unexpected response format');\n });\n } catch (error) {\n logError('[ai-content] Failed to generate commit message:', error);\n return `feat: add WorkOS AuthKit integration for ${integration}`;\n }\n}\n\n/**\n * Generate a PR description for the AuthKit integration.\n * Falls back to a default template if AI generation fails.\n */\nexport async function generatePrDescription(\n integration: string,\n files: string[],\n commitMessage: string,\n options: AiContentOptions = {},\n): Promise<string> {\n const executor = options.direct ? withDirect : withProxy;\n\n try {\n return await executor(async (client) => {\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 500,\n messages: [\n {\n role: 'user',\n content: `Generate a GitHub PR description for: \"${commitMessage}\"\n\nFramework: ${integration}\nFiles changed: ${files.join(', ')}\n\nInclude:\n- Brief summary (2-3 sentences)\n- Key changes bullet list\n- Link to WorkOS AuthKit docs: https://workos.com/docs/user-management\n\nKeep it concise. Markdown format.`,\n },\n ],\n });\n\n const text = response.content[0];\n if (text.type === 'text') {\n return text.text.trim();\n }\n throw new Error('Unexpected response format');\n });\n } catch (error) {\n logError('[ai-content] Failed to generate PR description:', error);\n return `## Summary\nAdded WorkOS AuthKit integration for ${integration}.\n\n## Changes\n${files.map((f) => `- ${f}`).join('\\n')}\n\n## Documentation\nhttps://workos.com/docs/user-management`;\n }\n}\n"]}
1
+ {"version":3,"file":"ai-content.js","sourceRoot":"","sources":["../../src/lib/ai-content.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAChF,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAOtD;;;GAGG;AACH,KAAK,UAAU,SAAS,CAAI,EAAqC;IAC/D,MAAM,UAAU,GAAG,gBAAgB,EAAE,CAAC;IACtC,MAAM,KAAK,GAAG,cAAc,EAAE,CAAC;IAE/B,IAAI,CAAC,KAAK,EAAE,YAAY,EAAE,CAAC;QACzB,4DAA4D;QAC5D,OAAO,CAAC,2DAA2D,CAAC,CAAC;QACrE,MAAM,MAA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AM,CAAC;gBAC5C,KAAK,EAAE,0BAA0B;gBACjC,UAAU,EAAE,GAAG;gBACf,QAAQ,EAAE;oBACR;wBACE,IAAI,EAAE,MAAM;wBACZ,OAAO,EAAE,0CAA0C,aAAa;;aAE/D,WAAW;iBACP,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC;;;;;;;kCAOC;qBACvB;iBACF;aACF,CAAC,CAAC;YAEH,MAAM,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YACjC,IAAI,IAAI,CAAC,IAAI,KAAK,MAAM,EAAE,CAAC;gBACzB,OAAO,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC;YAC1B,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4BAA4B,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,QAAQ,CAAC,iDAAiD,EAAE,KAAK,CAAC,CAAC;QACnE,OAAO;uCAC4B,WAAW;;;EAGhD,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;;;wCAGC,CAAC;IACvC,CAAC;AACH,CAAC","sourcesContent":["import Anthropic from '@anthropic-ai/sdk';\nimport { startCredentialProxy } from './credential-proxy.js';\nimport { getAuthkitDomain, getCliAuthClientId, getConfig } from './settings.js';\nimport { getLlmGatewayUrl } from '../utils/urls.js';\nimport { getCredentials } from './credentials.js';\nimport { logInfo, logError } from '../utils/debug.js';\n\nexport interface AiContentOptions {\n /** Use direct Anthropic API instead of llm-gateway */\n direct?: boolean;\n}\n\n/**\n * Execute an API call through a short-lived credential proxy.\n * Handles proxy lifecycle automatically.\n */\nasync function withProxy<T>(fn: (client: Anthropic) => Promise<T>): Promise<T> {\n const gatewayUrl = getLlmGatewayUrl();\n const creds = getCredentials();\n\n if (!creds?.refreshToken) {\n // No refresh token - use credentials directly (legacy mode)\n logInfo('[ai-content] No refresh token, using credentials directly');\n const client = new Anthropic({\n baseURL: gatewayUrl,\n apiKey: 'gateway', // SDK requires something, gateway uses Authorization header\n defaultHeaders: creds?.accessToken ? { Authorization: `Bearer ${creds.accessToken}` } : undefined,\n });\n return fn(client);\n }\n\n // Start short-lived proxy\n const proxy = await startCredentialProxy({\n upstreamUrl: gatewayUrl,\n refresh: {\n authkitDomain: getAuthkitDomain(),\n clientId: getCliAuthClientId(),\n refreshThresholdMs: getConfig().proxy.refreshThresholdMs,\n },\n });\n\n logInfo(`[ai-content] Started proxy at ${proxy.url}`);\n\n try {\n const client = new Anthropic({\n baseURL: proxy.url,\n apiKey: 'proxy', // SDK requires something, proxy handles real auth\n });\n return await fn(client);\n } finally {\n await proxy.stop();\n logInfo('[ai-content] Stopped proxy');\n }\n}\n\n/**\n * Execute an API call directly to Anthropic (--direct mode).\n */\nasync function withDirect<T>(fn: (client: Anthropic) => Promise<T>): Promise<T> {\n // SDK reads ANTHROPIC_API_KEY from env automatically\n const client = new Anthropic();\n return fn(client);\n}\n\n/**\n * Generate a concise commit message for the AuthKit integration.\n * Falls back to a default message if AI generation fails.\n */\nexport async function generateCommitMessage(\n integration: string,\n files: string[],\n options: AiContentOptions = {},\n): Promise<string> {\n const executor = options.direct ? withDirect : withProxy;\n\n try {\n return await executor(async (client) => {\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 100,\n messages: [\n {\n role: 'user',\n content: `Generate a concise git commit message for adding WorkOS AuthKit to a ${integration} project. Changed files: ${files.slice(0, 10).join(', ')}. Use conventional commit format (feat:). One line only, under 72 chars.`,\n },\n ],\n });\n\n const text = response.content[0];\n if (text.type === 'text') {\n return text.text.trim();\n }\n throw new Error('Unexpected response format');\n });\n } catch (error) {\n logError('[ai-content] Failed to generate commit message:', error);\n return `feat: add WorkOS AuthKit integration for ${integration}`;\n }\n}\n\n/**\n * Generate a PR description for the AuthKit integration.\n * Falls back to a default template if AI generation fails.\n */\nexport async function generatePrDescription(\n integration: string,\n files: string[],\n commitMessage: string,\n options: AiContentOptions = {},\n): Promise<string> {\n const executor = options.direct ? withDirect : withProxy;\n\n try {\n return await executor(async (client) => {\n const response = await client.messages.create({\n model: 'claude-sonnet-4-20250514',\n max_tokens: 500,\n messages: [\n {\n role: 'user',\n content: `Generate a GitHub PR description for: \"${commitMessage}\"\n\nFramework: ${integration}\nFiles changed: ${files.join(', ')}\n\nInclude:\n- Brief summary (2-3 sentences)\n- Key changes bullet list\n- Link to WorkOS AuthKit docs: https://workos.com/docs/user-management\n\nKeep it concise. Markdown format.`,\n },\n ],\n });\n\n const text = response.content[0];\n if (text.type === 'text') {\n return text.text.trim();\n }\n throw new Error('Unexpected response format');\n });\n } catch (error) {\n logError('[ai-content] Failed to generate PR description:', error);\n return `## Summary\nAdded WorkOS AuthKit integration for ${integration}.\n\n## Changes\n${files.map((f) => `- ${f}`).join('\\n')}\n\n## Documentation\nhttps://workos.com/docs/user-management`;\n }\n}\n"]}
@@ -27,6 +27,15 @@ export declare const ISSUES_URL: string;
27
27
  export declare const ANALYTICS_ENABLED: boolean;
28
28
  export declare const INSTALLER_INTERACTION_EVENT_NAME: string;
29
29
  export declare const OAUTH_PORT: number;
30
+ /**
31
+ * WorkOS MCP server identity, shared by the `mcp` command group and the
32
+ * per-client writers in `lib/mcp-clients.ts`.
33
+ *
34
+ * The server is secret-free: HTTP transport with OAuth handled by each client
35
+ * on first connect, so configuring it never requires CLI auth.
36
+ */
37
+ export declare const MCP_SERVER_NAME = "workos";
38
+ export declare const MCP_SERVER_URL = "https://mcp.workos.com/mcp";
30
39
  /**
31
40
  * Common glob patterns to ignore when searching for files.
32
41
  * Used by multiple integrations.
@@ -19,6 +19,15 @@ export const ISSUES_URL = settings.documentation.issuesUrl;
19
19
  export const ANALYTICS_ENABLED = settings.telemetry.enabled;
20
20
  export const INSTALLER_INTERACTION_EVENT_NAME = settings.telemetry.eventName;
21
21
  export const OAUTH_PORT = settings.legacy.oauthPort;
22
+ /**
23
+ * WorkOS MCP server identity, shared by the `mcp` command group and the
24
+ * per-client writers in `lib/mcp-clients.ts`.
25
+ *
26
+ * The server is secret-free: HTTP transport with OAuth handled by each client
27
+ * on first connect, so configuring it never requires CLI auth.
28
+ */
29
+ export const MCP_SERVER_NAME = 'workos';
30
+ export const MCP_SERVER_URL = 'https://mcp.workos.com/mcp';
22
31
  /**
23
32
  * Common glob patterns to ignore when searching for files.
24
33
  * Used by multiple integrations.
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAS1C;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;IACd,aAAa,EAAE,gBAAgB;IAC/B,WAAW,EAAE,cAAc;IAC3B,SAAS,EAAE,YAAY;CACf,CAAC;AAOX,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAEnF,MAAM,QAAQ,GAAG,SAAS,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC;AAChD,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC,aAAa,CAAC;AACpE,MAAM,CAAC,MAAM,oBAAoB,GAAG,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC;AACxE,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC;AAC3D,MAAM,CAAC,MAAM,iBAAiB,GAAG,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC;AAC5D,MAAM,CAAC,MAAM,gCAAgC,GAAG,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;AAC7E,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC;AAEpD;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAa;IACvC,oBAAoB;IACpB,YAAY;IACZ,aAAa;IACb,cAAc;IACd,aAAa;CACd,CAAC","sourcesContent":["import { getConfig } from './settings.js';\n\n/**\n * Integration identifier type.\n * No longer an enum — each integration self-registers via the auto-discovery registry.\n * The string value matches the integration directory name (e.g., 'nextjs', 'react-router').\n */\nexport type Integration = string;\n\n/**\n * Well-known integration names for backwards compatibility.\n * New integrations do NOT need to be added here — they're auto-discovered.\n */\nexport const KNOWN_INTEGRATIONS = {\n nextjs: 'nextjs',\n react: 'react',\n tanstackStart: 'tanstack-start',\n reactRouter: 'react-router',\n vanillaJs: 'vanilla-js',\n} as const;\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\nexport const IS_DEV = ['test', 'development'].includes(process.env.NODE_ENV ?? '');\n\nconst settings = getConfig();\n\nexport const DEBUG = settings.logging.debugMode;\nexport const WORKOS_DOCS_URL = settings.documentation.workosDocsUrl;\nexport const WORKOS_DASHBOARD_URL = settings.documentation.dashboardUrl;\nexport const ISSUES_URL = settings.documentation.issuesUrl;\nexport const ANALYTICS_ENABLED = settings.telemetry.enabled;\nexport const INSTALLER_INTERACTION_EVENT_NAME = settings.telemetry.eventName;\nexport const OAUTH_PORT = settings.legacy.oauthPort;\n\n/**\n * Common glob patterns to ignore when searching for files.\n * Used by multiple integrations.\n */\nexport const IGNORE_PATTERNS: string[] = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/public/**',\n '**/.next/**',\n];\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/lib/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAS1C;;;GAGG;AACH,MAAM,CAAC,MAAM,kBAAkB,GAAG;IAChC,MAAM,EAAE,QAAQ;IAChB,KAAK,EAAE,OAAO;IACd,aAAa,EAAE,gBAAgB;IAC/B,WAAW,EAAE,cAAc;IAC3B,SAAS,EAAE,YAAY;CACf,CAAC;AAOX,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,EAAE,CAAC,CAAC;AAEnF,MAAM,QAAQ,GAAG,SAAS,EAAE,CAAC;AAE7B,MAAM,CAAC,MAAM,KAAK,GAAG,QAAQ,CAAC,OAAO,CAAC,SAAS,CAAC;AAChD,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC,aAAa,CAAC,aAAa,CAAC;AACpE,MAAM,CAAC,MAAM,oBAAoB,GAAG,QAAQ,CAAC,aAAa,CAAC,YAAY,CAAC;AACxE,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,aAAa,CAAC,SAAS,CAAC;AAC3D,MAAM,CAAC,MAAM,iBAAiB,GAAG,QAAQ,CAAC,SAAS,CAAC,OAAO,CAAC;AAC5D,MAAM,CAAC,MAAM,gCAAgC,GAAG,QAAQ,CAAC,SAAS,CAAC,SAAS,CAAC;AAC7E,MAAM,CAAC,MAAM,UAAU,GAAG,QAAQ,CAAC,MAAM,CAAC,SAAS,CAAC;AAEpD;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,eAAe,GAAG,QAAQ,CAAC;AACxC,MAAM,CAAC,MAAM,cAAc,GAAG,4BAA4B,CAAC;AAE3D;;;GAGG;AACH,MAAM,CAAC,MAAM,eAAe,GAAa;IACvC,oBAAoB;IACpB,YAAY;IACZ,aAAa;IACb,cAAc;IACd,aAAa;CACd,CAAC","sourcesContent":["import { getConfig } from './settings.js';\n\n/**\n * Integration identifier type.\n * No longer an enum — each integration self-registers via the auto-discovery registry.\n * The string value matches the integration directory name (e.g., 'nextjs', 'react-router').\n */\nexport type Integration = string;\n\n/**\n * Well-known integration names for backwards compatibility.\n * New integrations do NOT need to be added here — they're auto-discovered.\n */\nexport const KNOWN_INTEGRATIONS = {\n nextjs: 'nextjs',\n react: 'react',\n tanstackStart: 'tanstack-start',\n reactRouter: 'react-router',\n vanillaJs: 'vanilla-js',\n} as const;\n\nexport interface Args {\n debug: boolean;\n integration: Integration;\n}\n\nexport const IS_DEV = ['test', 'development'].includes(process.env.NODE_ENV ?? '');\n\nconst settings = getConfig();\n\nexport const DEBUG = settings.logging.debugMode;\nexport const WORKOS_DOCS_URL = settings.documentation.workosDocsUrl;\nexport const WORKOS_DASHBOARD_URL = settings.documentation.dashboardUrl;\nexport const ISSUES_URL = settings.documentation.issuesUrl;\nexport const ANALYTICS_ENABLED = settings.telemetry.enabled;\nexport const INSTALLER_INTERACTION_EVENT_NAME = settings.telemetry.eventName;\nexport const OAUTH_PORT = settings.legacy.oauthPort;\n\n/**\n * WorkOS MCP server identity, shared by the `mcp` command group and the\n * per-client writers in `lib/mcp-clients.ts`.\n *\n * The server is secret-free: HTTP transport with OAuth handled by each client\n * on first connect, so configuring it never requires CLI auth.\n */\nexport const MCP_SERVER_NAME = 'workos';\nexport const MCP_SERVER_URL = 'https://mcp.workos.com/mcp';\n\n/**\n * Common glob patterns to ignore when searching for files.\n * Used by multiple integrations.\n */\nexport const IGNORE_PATTERNS: string[] = [\n '**/node_modules/**',\n '**/dist/**',\n '**/build/**',\n '**/public/**',\n '**/.next/**',\n];\n"]}
@@ -42,54 +42,54 @@ export declare const installerMachine: import("xstate").StateMachine<InstallerMa
42
42
  } | {
43
43
  type: "PR_DECLINED";
44
44
  }, {
45
- [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<string, {
46
- title: string;
47
- body: string;
48
- cwd: string;
49
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<boolean, {
45
+ [x: string]: import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<boolean, {
50
46
  options: InstallerOptions;
51
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<WorkspaceCheckOutput, {
47
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<WorkspaceCheckOutput, {
52
48
  options: InstallerOptions;
53
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, {
49
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<void, {
54
50
  context: InstallerMachineContext;
55
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<DetectionOutput, {
51
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<DetectionOutput, {
56
52
  options: InstallerOptions;
57
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<GitCheckOutput, {
53
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<GitCheckOutput, {
58
54
  installDir: string;
59
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, {
55
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<void, {
60
56
  context: InstallerMachineContext;
61
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<AgentOutput, {
57
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<AgentOutput, {
62
58
  context: InstallerMachineContext;
63
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<EnvFileInfo, {
59
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<EnvFileInfo, {
64
60
  installDir: string;
65
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<DiscoveryResult, {
61
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<DiscoveryResult, {
66
62
  installDir: string;
67
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<boolean, void, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<{
63
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<boolean, void, import("xstate").EventObject> | import("xstate").PromiseActorLogic<{
68
64
  result: DeviceAuthResult;
69
65
  deviceAuth: DeviceAuthResponse;
70
66
  }, {
71
67
  emitter: InstallerMachineContext["emitter"];
72
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<StagingCredentials, void, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<BranchCheckOutput, void, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<{
68
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<StagingCredentials, void, import("xstate").EventObject> | import("xstate").PromiseActorLogic<BranchCheckOutput, void, import("xstate").EventObject> | import("xstate").PromiseActorLogic<{
73
69
  branch: string;
74
70
  }, {
75
71
  name: string;
76
72
  fallbackName: string;
77
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<{
73
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<{
78
74
  hasChanges: boolean;
79
75
  files: string[];
80
- }, void, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<string, {
76
+ }, void, import("xstate").EventObject> | import("xstate").PromiseActorLogic<string, {
81
77
  integration: string;
82
78
  files: string[];
83
79
  direct?: boolean;
84
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, {
80
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<void, {
85
81
  message: string;
86
82
  cwd: string;
87
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<string, {
83
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<string, {
88
84
  integration: string;
89
85
  files: string[];
90
86
  commitMessage: string;
91
87
  direct?: boolean;
92
- }, import("xstate").EventObject>> | import("xstate").ActorRefFromLogic<import("xstate").PromiseActorLogic<void, {
88
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<void, {
89
+ cwd: string;
90
+ }, import("xstate").EventObject> | import("xstate").PromiseActorLogic<string, {
91
+ title: string;
92
+ body: string;
93
93
  cwd: string;
94
94
  }, import("xstate").EventObject>> | undefined;
95
95
  }, {
@@ -0,0 +1,39 @@
1
+ export type McpAgentKey = 'claude-code' | 'codex' | 'cursor';
2
+ export type McpOutcome = 'installed' | 'already-installed' | 'removed' | 'not-installed' | 'skipped' | 'failed';
3
+ export interface McpClientResult {
4
+ agent: McpAgentKey;
5
+ displayName: string;
6
+ outcome: McpOutcome;
7
+ /** stderr/message excerpt when `outcome === 'failed'`. */
8
+ error?: string;
9
+ }
10
+ export interface McpClientTarget {
11
+ key: McpAgentKey;
12
+ displayName: string;
13
+ /** Agent is usable on this machine (config dir present AND, for CLI clients, binary runnable). */
14
+ isAvailable(): Promise<boolean>;
15
+ /** The WorkOS server is present in this client's config. */
16
+ isInstalled(): Promise<boolean>;
17
+ add(): Promise<McpClientResult>;
18
+ remove(): Promise<McpClientResult>;
19
+ }
20
+ /** Stable list of known agent keys, for `--agent` validation by callers. */
21
+ export declare const MCP_AGENT_KEYS: McpAgentKey[];
22
+ /** The three client targets, in a stable order. */
23
+ export declare function createMcpClients(): McpClientTarget[];
24
+ /**
25
+ * The URL the WorkOS server is configured with in Cursor's `~/.cursor/mcp.json`,
26
+ * or null when the file/entry is absent, unreadable, or unparseable.
27
+ *
28
+ * Cursor is the only client whose config we read directly (the CLI clients don't
29
+ * expose per-entry URLs), so this powers doctor's URL-drift ("misconfigured")
30
+ * check without a second jsonc reader duplicating the config schema. Read-only
31
+ * and never throws — a problem reading just yields null.
32
+ */
33
+ export declare function getCursorConfiguredUrl(): Promise<string | null>;
34
+ /**
35
+ * Return only the clients available on this machine, optionally narrowed to
36
+ * `agentFilter` keys. Availability is probed in parallel. An unknown filter key
37
+ * simply matches nothing here — callers validate keys and surface the error.
38
+ */
39
+ export declare function detectMcpClients(agentFilter?: string[]): Promise<McpClientTarget[]>;