workos 0.8.2 → 0.10.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 (70) hide show
  1. package/README.md +10 -8
  2. package/dist/bin.js +62 -27
  3. package/dist/bin.js.map +1 -1
  4. package/dist/commands/auth-status.d.ts +1 -0
  5. package/dist/commands/auth-status.js +56 -0
  6. package/dist/commands/auth-status.js.map +1 -0
  7. package/dist/commands/install-skill.d.ts +0 -1
  8. package/dist/commands/install-skill.js +2 -10
  9. package/dist/commands/install-skill.js.map +1 -1
  10. package/dist/commands/list-skills.d.ts +4 -0
  11. package/dist/commands/list-skills.js +52 -0
  12. package/dist/commands/list-skills.js.map +1 -0
  13. package/dist/commands/login.js +5 -4
  14. package/dist/commands/login.js.map +1 -1
  15. package/dist/commands/uninstall-skill.d.ts +11 -0
  16. package/dist/commands/uninstall-skill.js +116 -0
  17. package/dist/commands/uninstall-skill.js.map +1 -0
  18. package/dist/doctor/checks/ai-analysis.js +3 -3
  19. package/dist/doctor/checks/ai-analysis.js.map +1 -1
  20. package/dist/integrations/dotnet/index.js +7 -12
  21. package/dist/integrations/dotnet/index.js.map +1 -1
  22. package/dist/integrations/elixir/index.js +7 -13
  23. package/dist/integrations/elixir/index.js.map +1 -1
  24. package/dist/integrations/go/index.js +5 -11
  25. package/dist/integrations/go/index.js.map +1 -1
  26. package/dist/integrations/python/index.js +7 -13
  27. package/dist/integrations/python/index.js.map +1 -1
  28. package/dist/integrations/ruby/index.js +9 -14
  29. package/dist/integrations/ruby/index.js.map +1 -1
  30. package/dist/lib/adapters/cli-adapter.js +1 -1
  31. package/dist/lib/adapters/cli-adapter.js.map +1 -1
  32. package/dist/lib/agent-interface.js +10 -9
  33. package/dist/lib/agent-interface.js.map +1 -1
  34. package/dist/lib/agent-runner.js +24 -19
  35. package/dist/lib/agent-runner.js.map +1 -1
  36. package/dist/lib/credential-proxy.js +1 -1
  37. package/dist/lib/credential-proxy.js.map +1 -1
  38. package/dist/lib/ensure-auth.js +3 -3
  39. package/dist/lib/ensure-auth.js.map +1 -1
  40. package/dist/lib/run-with-core.js +1 -1
  41. package/dist/lib/run-with-core.js.map +1 -1
  42. package/dist/lib/token-refresh-client.js +1 -1
  43. package/dist/lib/token-refresh-client.js.map +1 -1
  44. package/dist/lib/token-refresh.js +1 -1
  45. package/dist/lib/token-refresh.js.map +1 -1
  46. package/dist/lib/version-check.js +2 -1
  47. package/dist/lib/version-check.js.map +1 -1
  48. package/dist/utils/exit-codes.js +1 -1
  49. package/dist/utils/exit-codes.js.map +1 -1
  50. package/dist/utils/help-json.js +62 -23
  51. package/dist/utils/help-json.js.map +1 -1
  52. package/package.json +2 -3
  53. package/.claude-plugin/plugin.json +0 -13
  54. package/skills/workos-authkit-base/SKILL.md +0 -123
  55. package/skills/workos-authkit-nextjs/SKILL.md +0 -247
  56. package/skills/workos-authkit-react/SKILL.md +0 -91
  57. package/skills/workos-authkit-react-router/SKILL.md +0 -107
  58. package/skills/workos-authkit-sveltekit/SKILL.md +0 -160
  59. package/skills/workos-authkit-tanstack-start/SKILL.md +0 -300
  60. package/skills/workos-authkit-vanilla-js/SKILL.md +0 -83
  61. package/skills/workos-dotnet/SKILL.md +0 -163
  62. package/skills/workos-elixir/SKILL.md +0 -194
  63. package/skills/workos-go/SKILL.md +0 -191
  64. package/skills/workos-kotlin/SKILL.md +0 -161
  65. package/skills/workos-management/SKILL.md +0 -250
  66. package/skills/workos-node/SKILL.md +0 -164
  67. package/skills/workos-php/SKILL.md +0 -127
  68. package/skills/workos-php-laravel/SKILL.md +0 -147
  69. package/skills/workos-python/SKILL.md +0 -159
  70. package/skills/workos-ruby/SKILL.md +0 -163
@@ -1 +1 @@
1
- {"version":3,"file":"cli-adapter.js","sourceRoot":"","sources":["../../../src/lib/adapters/cli-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,MAAM,sBAAsB,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,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AAG,CAAC,YAAY,CAAC,CAAC,CAAC;IACvC,CAAC,CAAC;CACH","sourcesContent":["import type { InstallerAdapter, AdapterConfig } from './types.js';\nimport type { InstallerEventEmitter, InstallerEvents } from '../events.js';\nimport clack from '../../utils/clack.js';\nimport chalk from 'chalk';\nimport { getConfig } from '../settings.js';\nimport { ProgressTracker } from '../progress-tracker.js';\nimport { renderCompletionSummary } from '../../utils/summary-box.js';\n\n/**\n * CLI adapter that renders wizard events via clack.\n *\n * Subscribes to InstallerEventEmitter and translates events into\n * clack UI operations (logs, spinners, prompts).\n */\nexport class CLIAdapter implements InstallerAdapter {\n readonly emitter: InstallerEventEmitter;\n private sendEvent: AdapterConfig['sendEvent'];\n private debug: boolean;\n private spinner: ReturnType<typeof clack.spinner> | null = null;\n private isStarted = false;\n private progress = new ProgressTracker();\n\n // Store bound handlers for cleanup\n private handlers = new Map<string, (...args: unknown[]) => void>();\n\n // Queue for logs while prompt is active (parallel state issue)\n private isPromptActive = false;\n private pendingLogs: Array<() => void> = [];\n\n // SIGINT handler for cleanup\n private sigIntHandler: (() => void) | null = null;\n\n // Long-running agent update interval\n private agentUpdateInterval: NodeJS.Timeout | null = null;\n\n constructor(config: AdapterConfig) {\n this.emitter = config.emitter;\n this.sendEvent = config.sendEvent;\n this.debug = config.debug ?? false;\n }\n\n /**\n * Queue a log call if a prompt is active, otherwise execute immediately.\n */\n private queueableLog(logFn: () => void): void {\n if (this.isPromptActive) {\n this.pendingLogs.push(logFn);\n } else {\n logFn();\n }\n }\n\n /**\n * Flush any queued logs after prompt completes.\n */\n private flushPendingLogs(): void {\n const logs = this.pendingLogs.splice(0);\n logs.forEach((fn) => fn());\n }\n\n async start(): Promise<void> {\n if (this.isStarted) return;\n this.isStarted = true;\n\n // Show intro\n const config = getConfig();\n if (config.branding.showAsciiArt) {\n const art = config.branding.useCompact ? config.branding.compactAsciiArt : config.branding.asciiArt;\n console.log(chalk.cyan(art));\n console.log();\n } else {\n clack.intro('Welcome to the WorkOS AuthKit installer');\n }\n\n // Handle Ctrl+C gracefully\n const handleSigInt = () => {\n if (this.spinner) {\n this.spinner.stop('Cancelled');\n this.spinner = null;\n }\n this.stopAgentUpdates();\n clack.log.warn('Installer cancelled');\n clack.outro('Your project was not modified');\n process.exit(0);\n };\n process.on('SIGINT', handleSigInt);\n this.sigIntHandler = handleSigInt;\n\n // Subscribe to state events for progress tracking\n this.subscribe('state:enter', this.handleStateEnter);\n this.subscribe('state:exit', this.handleStateExit);\n\n // Subscribe to events that require UI rendering\n this.subscribe('auth:success', this.handleAuthSuccess);\n this.subscribe('auth:failure', this.handleAuthFailure);\n this.subscribe('detection:complete', this.handleDetectionComplete);\n this.subscribe('detection:none', this.handleDetectionNone);\n this.subscribe('git:dirty', this.handleGitDirty);\n this.subscribe('credentials:found', this.handleCredentialsFound);\n this.subscribe('credentials:request', this.handleCredentialsRequest);\n this.subscribe('credentials:env:prompt', this.handleEnvScanPrompt);\n this.subscribe('device:started', this.handleDeviceStarted);\n this.subscribe('device:success', this.handleDeviceSuccess);\n this.subscribe('staging:fetching', this.handleStagingFetching);\n this.subscribe('staging:success', this.handleStagingSuccess);\n this.subscribe('credentials:env:found', this.handleEnvCredentialsFound);\n this.subscribe('config:complete', this.handleConfigComplete);\n this.subscribe('agent:start', this.handleAgentStart);\n this.subscribe('agent:progress', this.handleAgentProgress);\n this.subscribe('validation:start', this.handleValidationStart);\n this.subscribe('validation:issues', this.handleValidationIssues);\n this.subscribe('validation:complete', this.handleValidationComplete);\n this.subscribe('complete', this.handleComplete);\n this.subscribe('error', this.handleError);\n // Branch check events\n this.subscribe('branch:prompt', this.handleBranchPrompt);\n this.subscribe('branch:created', this.handleBranchCreated);\n\n // Post-install events\n this.subscribe('postinstall:changes', this.handlePostInstallChanges);\n this.subscribe('postinstall:commit:prompt', this.handleCommitPrompt);\n this.subscribe('postinstall:commit:generating', this.handleCommitGenerating);\n this.subscribe('postinstall:commit:success', this.handleCommitSuccess);\n this.subscribe('postinstall:commit:failed', this.handleCommitFailed);\n this.subscribe('postinstall:pr:prompt', this.handlePrPrompt);\n this.subscribe('postinstall:pr:generating', this.handlePrGenerating);\n this.subscribe('postinstall:pr:pushing', this.handlePrPushing);\n this.subscribe('postinstall:pr:success', this.handlePrSuccess);\n this.subscribe('postinstall:pr:failed', this.handlePrFailed);\n this.subscribe('postinstall:push:failed', this.handlePushFailed);\n this.subscribe('postinstall:manual', this.handleManualInstructions);\n }\n\n async stop(): Promise<void> {\n if (!this.isStarted) return;\n\n // Remove SIGINT handler\n if (this.sigIntHandler) {\n process.off('SIGINT', this.sigIntHandler);\n this.sigIntHandler = null;\n }\n\n // Stop agent updates\n this.stopAgentUpdates();\n\n // Unsubscribe from all events\n for (const [event, handler] of this.handlers) {\n this.emitter.off(event as keyof InstallerEvents, handler as never);\n }\n this.handlers.clear();\n\n // Stop any active spinner\n this.spinner?.stop();\n this.spinner = null;\n\n this.isStarted = false;\n }\n\n private stopAgentUpdates = (): void => {\n if (this.agentUpdateInterval) {\n clearInterval(this.agentUpdateInterval);\n this.agentUpdateInterval = null;\n }\n };\n\n private stopSpinner(message: string): void {\n if (this.spinner) {\n this.spinner.stop(message);\n this.spinner = null;\n }\n }\n\n /** Debug logging - only outputs when debug mode is enabled */\n private debugLog = (message: string): void => {\n if (this.debug) {\n console.log(chalk.dim(`[debug] ${message}`));\n }\n };\n\n /**\n * Helper to subscribe and track handlers for cleanup.\n */\n private subscribe<K extends keyof InstallerEvents>(\n event: K,\n handler: (payload: InstallerEvents[K]) => void | Promise<void>,\n ): void {\n const boundHandler = handler.bind(this);\n this.handlers.set(event, boundHandler as (...args: unknown[]) => void);\n this.emitter.on(event, boundHandler);\n }\n\n // ===== Event Handlers =====\n\n private handleStateEnter = ({ state }: InstallerEvents['state:enter']): void => {\n this.progress.enterPhase(state);\n };\n\n private handleStateExit = ({ state }: InstallerEvents['state:exit']): void => {\n this.progress.exitPhase(state);\n };\n\n private handleAuthSuccess = (): void => {\n clack.log.success('Authenticated');\n };\n\n private handleAuthFailure = ({ message }: InstallerEvents['auth:failure']): void => {\n clack.log.error(`Auth failed: ${message}`);\n clack.log.info('Visit https://dashboard.workos.com to verify your account');\n };\n\n private handleDetectionComplete = ({ integration }: InstallerEvents['detection:complete']): void => {\n this.queueableLog(() => clack.log.success(`Detected ${chalk.bold(integration)}`));\n };\n\n private handleDetectionNone = (): void => {\n this.queueableLog(() => clack.log.warn('Could not detect framework automatically'));\n };\n\n private handleCredentialsFound = (): void => {\n clack.log.success('Found existing WorkOS credentials in .env.local');\n };\n\n private handleEnvScanPrompt = async ({ files }: InstallerEvents['credentials:env:prompt']): Promise<void> => {\n this.isPromptActive = true;\n const fileList = files.length === 1 ? files[0] : files.slice(0, 2).join(', ');\n const confirmed = await clack.confirm({\n message: `Found ${fileList}. Check for existing WorkOS credentials?`,\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'ENV_SCAN_DECLINED' : 'ENV_SCAN_APPROVED',\n });\n };\n\n private handleDeviceStarted = ({ verificationUri, userCode }: InstallerEvents['device:started']): void => {\n clack.log.info(`\\nOpen this URL in your browser:\\n`);\n console.log(` ${chalk.cyan(verificationUri)}`);\n console.log(`\\nEnter code: ${chalk.bold(userCode)}\\n`);\n\n this.spinner = clack.spinner();\n this.spinner.start('Waiting for authentication...');\n };\n\n private handleDeviceSuccess = (): void => {\n // Spinner will be stopped by handleStagingFetching\n };\n\n private handleStagingFetching = (): void => {\n if (this.spinner) {\n this.spinner.stop('Authenticated');\n }\n this.spinner = clack.spinner();\n this.spinner.start('Fetching your WorkOS credentials...');\n };\n\n private handleStagingSuccess = (): void => {\n this.stopSpinner('Credentials fetched');\n clack.log.success('WorkOS credentials retrieved automatically');\n };\n\n private handleEnvCredentialsFound = ({ sourcePath }: InstallerEvents['credentials:env:found']): void => {\n clack.log.success(`Found existing WorkOS credentials in ${sourcePath}`);\n };\n\n private handleGitDirty = async ({ files }: InstallerEvents['git:dirty']): Promise<void> => {\n clack.log.warn('You have uncommitted or untracked files:');\n files.slice(0, 5).forEach((f) => clack.log.info(chalk.dim(` ${f}`)));\n if (files.length > 5) {\n clack.log.info(chalk.dim(` ... and ${files.length - 5} more`));\n }\n\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Continue anyway?',\n initialValue: false,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'GIT_CANCELLED' : 'GIT_CONFIRMED',\n });\n };\n\n private handleCredentialsRequest = async ({\n requiresApiKey,\n }: InstallerEvents['credentials:request']): Promise<void> => {\n clack.log.step(`Get your credentials from ${chalk.cyan('https://dashboard.workos.com')}`);\n\n const clientId = await clack.text({\n message: 'Enter your WorkOS Client ID:',\n placeholder: 'client_...',\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return 'Client ID is required';\n }\n if (!value.startsWith('client_')) {\n return 'Client ID should start with \"client_\"';\n }\n return undefined;\n },\n });\n\n if (clack.isCancel(clientId)) {\n this.sendEvent({ type: 'CANCEL' });\n return;\n }\n\n let apiKey = '';\n if (requiresApiKey) {\n clack.log.info(chalk.dim('ℹ️ Your API key will be hidden for security and saved to .env.local'));\n const apiKeyResult = await clack.password({\n message: 'Enter your WorkOS API Key:',\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return 'API Key is required';\n }\n if (!value.startsWith('sk_')) {\n return 'API Key should start with \"sk_\"';\n }\n return undefined;\n },\n });\n\n if (clack.isCancel(apiKeyResult)) {\n this.sendEvent({ type: 'CANCEL' });\n return;\n }\n apiKey = apiKeyResult as string;\n } else {\n clack.log.info(chalk.dim('ℹ️ Client-only SDK - API key not required'));\n }\n\n this.sendEvent({\n type: 'CREDENTIALS_SUBMITTED',\n apiKey,\n clientId: clientId as string,\n });\n };\n\n private handleConfigComplete = (): void => {\n clack.log.success('Environment configured');\n };\n\n private handleAgentStart = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Running AI agent...');\n\n // Periodic status updates for long-running operations\n let dots = 0;\n this.agentUpdateInterval = setInterval(() => {\n dots = (dots + 1) % 4;\n const dotStr = '.'.repeat(dots + 1);\n this.spinner?.message(`Running AI agent${dotStr}`);\n }, 2000);\n };\n\n private handleAgentProgress = ({ step, detail }: InstallerEvents['agent:progress']): void => {\n const message = detail ? `${step}: ${detail}` : step;\n this.spinner?.message(message);\n };\n\n private handleValidationStart = (): void => {\n this.stopAgentUpdates();\n this.stopSpinner('Agent completed');\n };\n\n private handleValidationIssues = ({ issues }: InstallerEvents['validation:issues']): void => {\n for (const issue of issues) {\n if (issue.severity === 'error') {\n clack.log.error(issue.message);\n } else {\n clack.log.warn(issue.message);\n }\n if (issue.hint) {\n clack.log.info(`Hint: ${issue.hint}`);\n }\n }\n };\n\n private handleValidationComplete = ({ passed, issueCount }: InstallerEvents['validation:complete']): void => {\n if (passed) {\n clack.log.success('Validation passed');\n } else {\n clack.log.warn(`Validation found ${issueCount} issue(s)`);\n }\n };\n\n private handleComplete = ({ success, summary }: InstallerEvents['complete']): void => {\n this.stopAgentUpdates();\n this.stopSpinner(success ? 'Done' : 'Failed');\n\n console.log('');\n console.log(renderCompletionSummary(success, summary));\n console.log('');\n };\n\n private handleError = ({ message, stack }: InstallerEvents['error']): void => {\n this.stopSpinner('Error');\n this.stopAgentUpdates();\n\n clack.log.error(message);\n\n // Add actionable hints for common errors\n if (message.includes('authentication') || message.includes('auth')) {\n clack.log.info('Try running: workos logout && workos install');\n }\n if (message.includes('ENOENT') || message.includes('not found')) {\n clack.log.info('Ensure you are in a project directory');\n }\n\n if (stack && this.debug) {\n this.debugLog(stack);\n }\n };\n\n private handleBranchPrompt = async ({ branch }: InstallerEvents['branch:prompt']): Promise<void> => {\n this.isPromptActive = true;\n const choice = await clack.select({\n message: `You are on ${chalk.bold(branch)}. Create a feature branch?`,\n options: [\n { value: 'create', label: 'Create feat/add-workos-authkit' },\n { value: 'continue', label: 'Continue on current branch' },\n { value: 'cancel', label: 'Cancel' },\n ],\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n if (clack.isCancel(choice) || choice === 'cancel') {\n this.sendEvent({ type: 'BRANCH_CANCEL' });\n } else if (choice === 'create') {\n this.sendEvent({ type: 'BRANCH_CREATE' });\n } else {\n this.sendEvent({ type: 'BRANCH_CONTINUE' });\n }\n };\n\n private handleBranchCreated = ({ branch }: InstallerEvents['branch:created']): void => {\n this.queueableLog(() => clack.log.success(`Created branch ${chalk.bold(branch)}`));\n };\n\n // ===== Post-install Event Handlers =====\n\n private handlePostInstallChanges = ({ files }: InstallerEvents['postinstall:changes']): void => {\n this.debugLog(`Post-install: ${files.length} changed files detected`);\n };\n\n private handleCommitPrompt = async (): Promise<void> => {\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Commit the changes?',\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'COMMIT_DECLINED' : 'COMMIT_APPROVED',\n });\n };\n\n private handleCommitGenerating = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Generating commit message...');\n };\n\n private handleCommitSuccess = ({ message }: InstallerEvents['postinstall:commit:success']): void => {\n this.stopSpinner('Committed');\n clack.log.success(`Committed: ${chalk.dim(message)}`);\n };\n\n private handleCommitFailed = ({ error }: InstallerEvents['postinstall:commit:failed']): void => {\n this.stopSpinner('Commit failed');\n clack.log.error(`Commit failed: ${error}`);\n };\n\n private handlePrPrompt = async (): Promise<void> => {\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Create a pull request?',\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'PR_DECLINED' : 'PR_APPROVED',\n });\n };\n\n private handlePrGenerating = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Generating PR description...');\n };\n\n private handlePrPushing = (): void => {\n if (this.spinner) {\n this.spinner.message('Pushing to remote...');\n } else {\n this.spinner = clack.spinner();\n this.spinner.start('Pushing to remote...');\n }\n };\n\n private handlePrSuccess = ({ url }: InstallerEvents['postinstall:pr:success']): void => {\n this.stopSpinner('PR created');\n clack.log.success(`Pull request created: ${chalk.cyan(url)}`);\n };\n\n private handlePrFailed = ({ error }: InstallerEvents['postinstall:pr:failed']): void => {\n this.stopSpinner('PR creation failed');\n clack.log.error(`PR creation failed: ${error}`);\n };\n\n private handlePushFailed = ({ error }: InstallerEvents['postinstall:push:failed']): void => {\n this.stopSpinner('Push failed');\n clack.log.error(`Push failed: ${error}`);\n };\n\n private handleManualInstructions = ({ instructions }: InstallerEvents['postinstall:manual']): void => {\n clack.log.info('GitHub CLI not found. Manual steps:');\n console.log(chalk.dim(instructions));\n };\n}\n"]}
1
+ {"version":3,"file":"cli-adapter.js","sourceRoot":"","sources":["../../../src/lib/adapters/cli-adapter.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,MAAM,sBAAsB,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAErE;;;;;GAKG;AACH,MAAM,OAAO,UAAU;IACZ,OAAO,CAAwB;IAChC,SAAS,CAA6B;IACtC,KAAK,CAAU;IACf,OAAO,GAA4C,IAAI,CAAC;IACxD,SAAS,GAAG,KAAK,CAAC;IAClB,QAAQ,GAAG,IAAI,eAAe,EAAE,CAAC;IAEzC,mCAAmC;IAC3B,QAAQ,GAAG,IAAI,GAAG,EAAwC,CAAC;IAEnE,+DAA+D;IACvD,cAAc,GAAG,KAAK,CAAC;IACvB,WAAW,GAAsB,EAAE,CAAC;IAE5C,6BAA6B;IACrB,aAAa,GAAwB,IAAI,CAAC;IAElD,qCAAqC;IAC7B,mBAA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,CAAC,GAAG,CAAC,OAAO,CAAC,yBAAyB,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IAChE,CAAC,CAAC;IAEM,cAAc,GAAG,CAAC,EAAE,KAAK,EAA4C,EAAQ,EAAE;QACrF,IAAI,CAAC,WAAW,CAAC,oBAAoB,CAAC,CAAC;QACvC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,uBAAuB,KAAK,EAAE,CAAC,CAAC;IAClD,CAAC,CAAC;IAEM,gBAAgB,GAAG,CAAC,EAAE,KAAK,EAA8C,EAAQ,EAAE;QACzF,IAAI,CAAC,WAAW,CAAC,aAAa,CAAC,CAAC;QAChC,KAAK,CAAC,GAAG,CAAC,KAAK,CAAC,gBAAgB,KAAK,EAAE,CAAC,CAAC;IAC3C,CAAC,CAAC;IAEM,wBAAwB,GAAG,CAAC,EAAE,YAAY,EAAyC,EAAQ,EAAE;QACnG,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,qCAAqC,CAAC,CAAC;QACtD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC,CAAC;IACvC,CAAC,CAAC;CACH","sourcesContent":["import type { InstallerAdapter, AdapterConfig } from './types.js';\nimport type { InstallerEventEmitter, InstallerEvents } from '../events.js';\nimport clack from '../../utils/clack.js';\nimport chalk from 'chalk';\nimport { getConfig } from '../settings.js';\nimport { ProgressTracker } from '../progress-tracker.js';\nimport { renderCompletionSummary } from '../../utils/summary-box.js';\n\n/**\n * CLI adapter that renders wizard events via clack.\n *\n * Subscribes to InstallerEventEmitter and translates events into\n * clack UI operations (logs, spinners, prompts).\n */\nexport class CLIAdapter implements InstallerAdapter {\n readonly emitter: InstallerEventEmitter;\n private sendEvent: AdapterConfig['sendEvent'];\n private debug: boolean;\n private spinner: ReturnType<typeof clack.spinner> | null = null;\n private isStarted = false;\n private progress = new ProgressTracker();\n\n // Store bound handlers for cleanup\n private handlers = new Map<string, (...args: unknown[]) => void>();\n\n // Queue for logs while prompt is active (parallel state issue)\n private isPromptActive = false;\n private pendingLogs: Array<() => void> = [];\n\n // SIGINT handler for cleanup\n private sigIntHandler: (() => void) | null = null;\n\n // Long-running agent update interval\n private agentUpdateInterval: NodeJS.Timeout | null = null;\n\n constructor(config: AdapterConfig) {\n this.emitter = config.emitter;\n this.sendEvent = config.sendEvent;\n this.debug = config.debug ?? false;\n }\n\n /**\n * Queue a log call if a prompt is active, otherwise execute immediately.\n */\n private queueableLog(logFn: () => void): void {\n if (this.isPromptActive) {\n this.pendingLogs.push(logFn);\n } else {\n logFn();\n }\n }\n\n /**\n * Flush any queued logs after prompt completes.\n */\n private flushPendingLogs(): void {\n const logs = this.pendingLogs.splice(0);\n logs.forEach((fn) => fn());\n }\n\n async start(): Promise<void> {\n if (this.isStarted) return;\n this.isStarted = true;\n\n // Show intro\n const config = getConfig();\n if (config.branding.showAsciiArt) {\n const art = config.branding.useCompact ? config.branding.compactAsciiArt : config.branding.asciiArt;\n console.log(chalk.cyan(art));\n console.log();\n } else {\n clack.intro('Welcome to the WorkOS AuthKit installer');\n }\n\n // Handle Ctrl+C gracefully\n const handleSigInt = () => {\n if (this.spinner) {\n this.spinner.stop('Cancelled');\n this.spinner = null;\n }\n this.stopAgentUpdates();\n clack.log.warn('Installer cancelled');\n clack.outro('Your project was not modified');\n process.exit(0);\n };\n process.on('SIGINT', handleSigInt);\n this.sigIntHandler = handleSigInt;\n\n // Subscribe to state events for progress tracking\n this.subscribe('state:enter', this.handleStateEnter);\n this.subscribe('state:exit', this.handleStateExit);\n\n // Subscribe to events that require UI rendering\n this.subscribe('auth:success', this.handleAuthSuccess);\n this.subscribe('auth:failure', this.handleAuthFailure);\n this.subscribe('detection:complete', this.handleDetectionComplete);\n this.subscribe('detection:none', this.handleDetectionNone);\n this.subscribe('git:dirty', this.handleGitDirty);\n this.subscribe('credentials:found', this.handleCredentialsFound);\n this.subscribe('credentials:request', this.handleCredentialsRequest);\n this.subscribe('credentials:env:prompt', this.handleEnvScanPrompt);\n this.subscribe('device:started', this.handleDeviceStarted);\n this.subscribe('device:success', this.handleDeviceSuccess);\n this.subscribe('staging:fetching', this.handleStagingFetching);\n this.subscribe('staging:success', this.handleStagingSuccess);\n this.subscribe('credentials:env:found', this.handleEnvCredentialsFound);\n this.subscribe('config:complete', this.handleConfigComplete);\n this.subscribe('agent:start', this.handleAgentStart);\n this.subscribe('agent:progress', this.handleAgentProgress);\n this.subscribe('validation:start', this.handleValidationStart);\n this.subscribe('validation:issues', this.handleValidationIssues);\n this.subscribe('validation:complete', this.handleValidationComplete);\n this.subscribe('complete', this.handleComplete);\n this.subscribe('error', this.handleError);\n // Branch check events\n this.subscribe('branch:prompt', this.handleBranchPrompt);\n this.subscribe('branch:created', this.handleBranchCreated);\n\n // Post-install events\n this.subscribe('postinstall:changes', this.handlePostInstallChanges);\n this.subscribe('postinstall:commit:prompt', this.handleCommitPrompt);\n this.subscribe('postinstall:commit:generating', this.handleCommitGenerating);\n this.subscribe('postinstall:commit:success', this.handleCommitSuccess);\n this.subscribe('postinstall:commit:failed', this.handleCommitFailed);\n this.subscribe('postinstall:pr:prompt', this.handlePrPrompt);\n this.subscribe('postinstall:pr:generating', this.handlePrGenerating);\n this.subscribe('postinstall:pr:pushing', this.handlePrPushing);\n this.subscribe('postinstall:pr:success', this.handlePrSuccess);\n this.subscribe('postinstall:pr:failed', this.handlePrFailed);\n this.subscribe('postinstall:push:failed', this.handlePushFailed);\n this.subscribe('postinstall:manual', this.handleManualInstructions);\n }\n\n async stop(): Promise<void> {\n if (!this.isStarted) return;\n\n // Remove SIGINT handler\n if (this.sigIntHandler) {\n process.off('SIGINT', this.sigIntHandler);\n this.sigIntHandler = null;\n }\n\n // Stop agent updates\n this.stopAgentUpdates();\n\n // Unsubscribe from all events\n for (const [event, handler] of this.handlers) {\n this.emitter.off(event as keyof InstallerEvents, handler as never);\n }\n this.handlers.clear();\n\n // Stop any active spinner\n this.spinner?.stop();\n this.spinner = null;\n\n this.isStarted = false;\n }\n\n private stopAgentUpdates = (): void => {\n if (this.agentUpdateInterval) {\n clearInterval(this.agentUpdateInterval);\n this.agentUpdateInterval = null;\n }\n };\n\n private stopSpinner(message: string): void {\n if (this.spinner) {\n this.spinner.stop(message);\n this.spinner = null;\n }\n }\n\n /** Debug logging - only outputs when debug mode is enabled */\n private debugLog = (message: string): void => {\n if (this.debug) {\n console.log(chalk.dim(`[debug] ${message}`));\n }\n };\n\n /**\n * Helper to subscribe and track handlers for cleanup.\n */\n private subscribe<K extends keyof InstallerEvents>(\n event: K,\n handler: (payload: InstallerEvents[K]) => void | Promise<void>,\n ): void {\n const boundHandler = handler.bind(this);\n this.handlers.set(event, boundHandler as (...args: unknown[]) => void);\n this.emitter.on(event, boundHandler);\n }\n\n // ===== Event Handlers =====\n\n private handleStateEnter = ({ state }: InstallerEvents['state:enter']): void => {\n this.progress.enterPhase(state);\n };\n\n private handleStateExit = ({ state }: InstallerEvents['state:exit']): void => {\n this.progress.exitPhase(state);\n };\n\n private handleAuthSuccess = (): void => {\n clack.log.success('Authenticated');\n };\n\n private handleAuthFailure = ({ message }: InstallerEvents['auth:failure']): void => {\n clack.log.error(`Auth failed: ${message}`);\n clack.log.info('Visit https://dashboard.workos.com to verify your account');\n };\n\n private handleDetectionComplete = ({ integration }: InstallerEvents['detection:complete']): void => {\n this.queueableLog(() => clack.log.success(`Detected ${chalk.bold(integration)}`));\n };\n\n private handleDetectionNone = (): void => {\n this.queueableLog(() => clack.log.warn('Could not detect framework automatically'));\n };\n\n private handleCredentialsFound = (): void => {\n clack.log.success('Found existing WorkOS credentials in .env.local');\n };\n\n private handleEnvScanPrompt = async ({ files }: InstallerEvents['credentials:env:prompt']): Promise<void> => {\n this.isPromptActive = true;\n const fileList = files.length === 1 ? files[0] : files.slice(0, 2).join(', ');\n const confirmed = await clack.confirm({\n message: `Found ${fileList}. Check for existing WorkOS credentials?`,\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'ENV_SCAN_DECLINED' : 'ENV_SCAN_APPROVED',\n });\n };\n\n private handleDeviceStarted = ({ verificationUri, userCode }: InstallerEvents['device:started']): void => {\n clack.log.info(`\\nOpen this URL in your browser:\\n`);\n console.log(` ${chalk.cyan(verificationUri)}`);\n console.log(`\\nEnter code: ${chalk.bold(userCode)}\\n`);\n\n this.spinner = clack.spinner();\n this.spinner.start('Waiting for authentication...');\n };\n\n private handleDeviceSuccess = (): void => {\n // Spinner will be stopped by handleStagingFetching\n };\n\n private handleStagingFetching = (): void => {\n if (this.spinner) {\n this.spinner.stop('Authenticated');\n }\n this.spinner = clack.spinner();\n this.spinner.start('Fetching your WorkOS credentials...');\n };\n\n private handleStagingSuccess = (): void => {\n this.stopSpinner('Credentials fetched');\n clack.log.success('WorkOS credentials retrieved automatically');\n };\n\n private handleEnvCredentialsFound = ({ sourcePath }: InstallerEvents['credentials:env:found']): void => {\n clack.log.success(`Found existing WorkOS credentials in ${sourcePath}`);\n };\n\n private handleGitDirty = async ({ files }: InstallerEvents['git:dirty']): Promise<void> => {\n clack.log.warn('You have uncommitted or untracked files:');\n files.slice(0, 5).forEach((f) => clack.log.info(chalk.dim(` ${f}`)));\n if (files.length > 5) {\n clack.log.info(chalk.dim(` ... and ${files.length - 5} more`));\n }\n\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Continue anyway?',\n initialValue: false,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'GIT_CANCELLED' : 'GIT_CONFIRMED',\n });\n };\n\n private handleCredentialsRequest = async ({\n requiresApiKey,\n }: InstallerEvents['credentials:request']): Promise<void> => {\n clack.log.step(`Get your credentials from ${chalk.cyan('https://dashboard.workos.com')}`);\n\n const clientId = await clack.text({\n message: 'Enter your WorkOS Client ID:',\n placeholder: 'client_...',\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return 'Client ID is required';\n }\n if (!value.startsWith('client_')) {\n return 'Client ID should start with \"client_\"';\n }\n return undefined;\n },\n });\n\n if (clack.isCancel(clientId)) {\n this.sendEvent({ type: 'CANCEL' });\n return;\n }\n\n let apiKey = '';\n if (requiresApiKey) {\n clack.log.info(chalk.dim('ℹ️ Your API key will be hidden for security and saved to .env.local'));\n const apiKeyResult = await clack.password({\n message: 'Enter your WorkOS API Key:',\n validate: (value) => {\n if (!value || value.trim().length === 0) {\n return 'API Key is required';\n }\n if (!value.startsWith('sk_')) {\n return 'API Key should start with \"sk_\"';\n }\n return undefined;\n },\n });\n\n if (clack.isCancel(apiKeyResult)) {\n this.sendEvent({ type: 'CANCEL' });\n return;\n }\n apiKey = apiKeyResult as string;\n } else {\n clack.log.info(chalk.dim('ℹ️ Client-only SDK - API key not required'));\n }\n\n this.sendEvent({\n type: 'CREDENTIALS_SUBMITTED',\n apiKey,\n clientId: clientId as string,\n });\n };\n\n private handleConfigComplete = (): void => {\n clack.log.success('Environment configured');\n };\n\n private handleAgentStart = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Running AI agent...');\n\n // Periodic status updates for long-running operations\n let dots = 0;\n this.agentUpdateInterval = setInterval(() => {\n dots = (dots + 1) % 4;\n const dotStr = '.'.repeat(dots + 1);\n this.spinner?.message(`Running AI agent${dotStr}`);\n }, 2000);\n };\n\n private handleAgentProgress = ({ step, detail }: InstallerEvents['agent:progress']): void => {\n const message = detail ? `${step}: ${detail}` : step;\n this.spinner?.message(message);\n };\n\n private handleValidationStart = (): void => {\n this.stopAgentUpdates();\n this.stopSpinner('Agent completed');\n };\n\n private handleValidationIssues = ({ issues }: InstallerEvents['validation:issues']): void => {\n for (const issue of issues) {\n if (issue.severity === 'error') {\n clack.log.error(issue.message);\n } else {\n clack.log.warn(issue.message);\n }\n if (issue.hint) {\n clack.log.info(`Hint: ${issue.hint}`);\n }\n }\n };\n\n private handleValidationComplete = ({ passed, issueCount }: InstallerEvents['validation:complete']): void => {\n if (passed) {\n clack.log.success('Validation passed');\n } else {\n clack.log.warn(`Validation found ${issueCount} issue(s)`);\n }\n };\n\n private handleComplete = ({ success, summary }: InstallerEvents['complete']): void => {\n this.stopAgentUpdates();\n this.stopSpinner(success ? 'Done' : 'Failed');\n\n console.log('');\n console.log(renderCompletionSummary(success, summary));\n console.log('');\n };\n\n private handleError = ({ message, stack }: InstallerEvents['error']): void => {\n this.stopSpinner('Error');\n this.stopAgentUpdates();\n\n clack.log.error(message);\n\n // Add actionable hints for common errors\n if (message.includes('authentication') || message.includes('auth')) {\n clack.log.info('Try running: workos auth logout && workos install');\n }\n if (message.includes('ENOENT') || message.includes('not found')) {\n clack.log.info('Ensure you are in a project directory');\n }\n\n if (stack && this.debug) {\n this.debugLog(stack);\n }\n };\n\n private handleBranchPrompt = async ({ branch }: InstallerEvents['branch:prompt']): Promise<void> => {\n this.isPromptActive = true;\n const choice = await clack.select({\n message: `You are on ${chalk.bold(branch)}. Create a feature branch?`,\n options: [\n { value: 'create', label: 'Create feat/add-workos-authkit' },\n { value: 'continue', label: 'Continue on current branch' },\n { value: 'cancel', label: 'Cancel' },\n ],\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n if (clack.isCancel(choice) || choice === 'cancel') {\n this.sendEvent({ type: 'BRANCH_CANCEL' });\n } else if (choice === 'create') {\n this.sendEvent({ type: 'BRANCH_CREATE' });\n } else {\n this.sendEvent({ type: 'BRANCH_CONTINUE' });\n }\n };\n\n private handleBranchCreated = ({ branch }: InstallerEvents['branch:created']): void => {\n this.queueableLog(() => clack.log.success(`Created branch ${chalk.bold(branch)}`));\n };\n\n // ===== Post-install Event Handlers =====\n\n private handlePostInstallChanges = ({ files }: InstallerEvents['postinstall:changes']): void => {\n this.debugLog(`Post-install: ${files.length} changed files detected`);\n };\n\n private handleCommitPrompt = async (): Promise<void> => {\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Commit the changes?',\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'COMMIT_DECLINED' : 'COMMIT_APPROVED',\n });\n };\n\n private handleCommitGenerating = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Generating commit message...');\n };\n\n private handleCommitSuccess = ({ message }: InstallerEvents['postinstall:commit:success']): void => {\n this.stopSpinner('Committed');\n clack.log.success(`Committed: ${chalk.dim(message)}`);\n };\n\n private handleCommitFailed = ({ error }: InstallerEvents['postinstall:commit:failed']): void => {\n this.stopSpinner('Commit failed');\n clack.log.error(`Commit failed: ${error}`);\n };\n\n private handlePrPrompt = async (): Promise<void> => {\n this.isPromptActive = true;\n const confirmed = await clack.confirm({\n message: 'Create a pull request?',\n initialValue: true,\n });\n this.isPromptActive = false;\n this.flushPendingLogs();\n\n this.sendEvent({\n type: clack.isCancel(confirmed) || !confirmed ? 'PR_DECLINED' : 'PR_APPROVED',\n });\n };\n\n private handlePrGenerating = (): void => {\n this.spinner = clack.spinner();\n this.spinner.start('Generating PR description...');\n };\n\n private handlePrPushing = (): void => {\n if (this.spinner) {\n this.spinner.message('Pushing to remote...');\n } else {\n this.spinner = clack.spinner();\n this.spinner.start('Pushing to remote...');\n }\n };\n\n private handlePrSuccess = ({ url }: InstallerEvents['postinstall:pr:success']): void => {\n this.stopSpinner('PR created');\n clack.log.success(`Pull request created: ${chalk.cyan(url)}`);\n };\n\n private handlePrFailed = ({ error }: InstallerEvents['postinstall:pr:failed']): void => {\n this.stopSpinner('PR creation failed');\n clack.log.error(`PR creation failed: ${error}`);\n };\n\n private handlePushFailed = ({ error }: InstallerEvents['postinstall:push:failed']): void => {\n this.stopSpinner('Push failed');\n clack.log.error(`Push failed: ${error}`);\n };\n\n private handleManualInstructions = ({ instructions }: InstallerEvents['postinstall:manual']): void => {\n clack.log.info('GitHub CLI not found. Manual steps:');\n console.log(chalk.dim(instructions));\n };\n}\n"]}
@@ -2,7 +2,8 @@
2
2
  * Shared agent interface for WorkOS wizards
3
3
  * Uses Claude Agent SDK directly with WorkOS MCP server
4
4
  */
5
- import { getPackageRoot } from '../utils/paths.js';
5
+ import { dirname } from 'path';
6
+ import { getSkillsDir as getSkillsPackageDir } from '@workos/skills';
6
7
  import { debug, logInfo, logWarn, logError, initLogFile, getLogFilePath } from '../utils/debug.js';
7
8
  import { analytics } from '../utils/analytics.js';
8
9
  import { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';
@@ -292,11 +293,11 @@ export async function initializeAgent(config, options) {
292
293
  // Check/refresh authentication for production (unless skipping auth)
293
294
  if (!options.skipAuth && !options.local) {
294
295
  if (!hasCredentials()) {
295
- throw new Error('Not authenticated. Run `workos login` to authenticate.');
296
+ throw new Error('Not authenticated. Run `workos auth login` to authenticate.');
296
297
  }
297
298
  const creds = getCredentials();
298
299
  if (!creds) {
299
- throw new Error('Not authenticated. Run `workos login` to authenticate.');
300
+ throw new Error('Not authenticated. Run `workos auth login` to authenticate.');
300
301
  }
301
302
  // Check if we have refresh token capability and proxy is not disabled
302
303
  if (creds.refreshToken && process.env.INSTALLER_DISABLE_PROXY !== '1') {
@@ -315,7 +316,7 @@ export async function initializeAgent(config, options) {
315
316
  onRefreshExpired: () => {
316
317
  logError('[agent-interface] Session expired, refresh token invalid');
317
318
  options.emitter?.emit('error', {
318
- message: 'Session expired. Run `workos login` to re-authenticate.',
319
+ message: 'Session expired. Run `workos auth login` to re-authenticate.',
319
320
  });
320
321
  },
321
322
  },
@@ -331,9 +332,9 @@ export async function initializeAgent(config, options) {
331
332
  // No refresh token OR proxy disabled - fall back to old behavior (5 min limit)
332
333
  if (!creds.refreshToken) {
333
334
  logWarn('[agent-interface] No refresh token available, session limited to 5 minutes');
334
- logWarn('[agent-interface] Run `workos login` to enable extended sessions');
335
+ logWarn('[agent-interface] Run `workos auth login` to enable extended sessions');
335
336
  options.emitter?.emit('status', {
336
- message: 'Note: Run `workos login` to enable extended sessions',
337
+ message: 'Note: Run `workos auth login` to enable extended sessions',
337
338
  });
338
339
  }
339
340
  else {
@@ -377,7 +378,7 @@ export async function initializeAgent(config, options) {
377
378
  },
378
379
  },
379
380
  model: getConfig().model,
380
- allowedTools: ['Skill', 'Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'WebFetch'],
381
+ allowedTools: ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'WebFetch'],
381
382
  sdkEnv,
382
383
  };
383
384
  const configInfo = { workingDirectory: agentRunConfig.workingDirectory, authMode, useMcp: false };
@@ -470,8 +471,8 @@ export async function runAgent(agentConfig, prompt, options, config, emitter, re
470
471
  }
471
472
  await currentTurnDone;
472
473
  };
473
- // Load plugin with bundled skills
474
- const pluginPath = getPackageRoot(import.meta.url);
474
+ // Load plugin from @workos/skills package
475
+ const pluginPath = dirname(getSkillsPackageDir());
475
476
  logInfo('Loading plugin from:', pluginPath);
476
477
  const response = query({
477
478
  prompt: createPromptStream(),
@@ -1 +1 @@
1
- {"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../src/lib/agent-interface.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,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,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,oBAAoB,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CAAC;oBAC3C,CAAC;oBACD,iCAAiC;oBACjC,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC3B,CAAC;gBACD,wEAAwE;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 { getPackageRoot } from '../utils/paths.js';\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 { getConfig } from './settings.js';\nimport { getCredentials, hasCredentials } from './credentials.js';\nimport { ensureValidToken } from './token-refresh.js';\nimport type { InstallerEventEmitter } from './events.js';\nimport { startCredentialProxy, type CredentialProxyHandle } from './credential-proxy.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/**\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}\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 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/refresh authentication for production (unless skipping auth)\n if (!options.skipAuth && !options.local) {\n if (!hasCredentials()) {\n throw new Error('Not authenticated. Run `workos login` to authenticate.');\n }\n\n const creds = getCredentials();\n if (!creds) {\n throw new Error('Not authenticated. Run `workos 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 `workos 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 // Proxy handles auth, so we don't set ANTHROPIC_AUTH_TOKEN\n delete sdkEnv.ANTHROPIC_AUTH_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 `workos login` to enable extended sessions');\n options.emitter?.emit('status', {\n message: 'Note: Run `workos 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 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 auth\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = `skip-auth:${gatewayUrl}`;\n logInfo('Skipping auth - no token sent to gateway');\n } else {\n // Local mode without auth\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = `local-gateway:${gatewayUrl}`;\n logInfo('Local mode - no token 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: ['Skill', '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 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 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 with bundled skills\n const pluginPath = getPackageRoot(import.meta.url);\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 }\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 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 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,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAC1C,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAClE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,OAAO,EAAE,oBAAoB,EA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iC;oBACjC,OAAO,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;gBAC3B,CAAC;gBACD,wEAAwE;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 { getConfig } from './settings.js';\nimport { getCredentials, hasCredentials } from './credentials.js';\nimport { ensureValidToken } from './token-refresh.js';\nimport type { InstallerEventEmitter } from './events.js';\nimport { startCredentialProxy, type CredentialProxyHandle } from './credential-proxy.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/**\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}\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 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/refresh authentication for production (unless skipping auth)\n if (!options.skipAuth && !options.local) {\n if (!hasCredentials()) {\n throw new Error('Not authenticated. Run `workos auth login` to authenticate.');\n }\n\n const creds = getCredentials();\n if (!creds) {\n throw new Error('Not authenticated. Run `workos 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 `workos 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 // Proxy handles auth, so we don't set ANTHROPIC_AUTH_TOKEN\n delete sdkEnv.ANTHROPIC_AUTH_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 `workos auth login` to enable extended sessions');\n options.emitter?.emit('status', {\n message: 'Note: Run `workos 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 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 auth\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = `skip-auth:${gatewayUrl}`;\n logInfo('Skipping auth - no token sent to gateway');\n } else {\n // Local mode without auth\n sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;\n delete sdkEnv.ANTHROPIC_AUTH_TOKEN;\n authMode = `local-gateway:${gatewayUrl}`;\n logInfo('Local mode - no token 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 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 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 }\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 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 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,3 +1,4 @@
1
+ import { getReference } from '@workos/skills';
1
2
  import { SPINNER_MESSAGE } from './framework-config.js';
2
3
  import { validateInstallation, quickCheckValidateAndFormat } from './validation/index.js';
3
4
  import { ensurePackageIsInstalled, getOrAskForWorkOSCredentials, getPackageDotJson, isUsingTypeScript, } from '../utils/clack-utils.js';
@@ -70,7 +71,7 @@ export async function runAgentInstaller(config, options) {
70
71
  analytics.setTag(key, value);
71
72
  });
72
73
  // Build integration prompt (credentials are already in .env.local)
73
- const integrationPrompt = buildIntegrationPrompt(config, {
74
+ const integrationPrompt = await buildIntegrationPrompt(config, {
74
75
  frameworkVersion: frameworkVersion || 'latest',
75
76
  typescript: typeScriptDetected,
76
77
  }, frameworkContext);
@@ -151,10 +152,10 @@ export async function runAgentInstaller(config, options) {
151
152
  }
152
153
  /**
153
154
  * Build the integration prompt for the agent.
154
- * Uses skill-based approach where agent invokes framework-specific skill.
155
+ * Reads reference content from @workos/skills and injects it directly into the prompt.
155
156
  * Note: Credentials are pre-written to .env.local, so not included in prompt.
156
157
  */
157
- function buildIntegrationPrompt(config, context, frameworkContext) {
158
+ async function buildIntegrationPrompt(config, context, frameworkContext) {
158
159
  const additionalLines = config.prompts.getAdditionalContextLines
159
160
  ? config.prompts.getAdditionalContextLines(frameworkContext)
160
161
  : [];
@@ -163,8 +164,22 @@ function buildIntegrationPrompt(config, context, frameworkContext) {
163
164
  if (!skillName) {
164
165
  throw new Error(`Framework ${config.metadata.name} missing skillName in config`);
165
166
  }
166
- // Next.js uses NEXT_PUBLIC_ prefix for redirect URI
167
- const redirectUriEnvVar = config.metadata.integration === 'nextjs' ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI';
167
+ // Read reference content from @workos/skills package
168
+ // Base template has JS-centric assumptions (node_modules, lockfiles, AuthKitProvider)
169
+ // so only load it for JavaScript integrations; backend SDKs bypass this entirely
170
+ const isJavaScript = config.metadata.language === 'javascript';
171
+ const [baseContent, refContent] = await Promise.all([
172
+ isJavaScript ? getReference('workos-authkit-base') : Promise.resolve(''),
173
+ getReference(skillName),
174
+ ]);
175
+ // Build env var list dynamically based on what was actually configured
176
+ const envVars = [
177
+ ...(config.environment.requiresApiKey ? ['WORKOS_API_KEY'] : []),
178
+ 'WORKOS_CLIENT_ID',
179
+ config.metadata.integration === 'nextjs' ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI',
180
+ 'WORKOS_COOKIE_PASSWORD',
181
+ ];
182
+ const envVarList = envVars.map((v) => `- ${v}`).join('\n');
168
183
  return `You are integrating WorkOS AuthKit into this ${config.metadata.name} application.
169
184
 
170
185
  ## Project Context
@@ -175,25 +190,15 @@ function buildIntegrationPrompt(config, context, frameworkContext) {
175
190
  ## Environment
176
191
 
177
192
  The following environment variables have been configured in .env.local:
178
- - WORKOS_API_KEY
179
- - WORKOS_CLIENT_ID
180
- - ${redirectUriEnvVar}
181
- - WORKOS_COOKIE_PASSWORD
193
+ ${envVarList}
182
194
 
183
- ## Your Task
195
+ ${baseContent ? `## General Guidelines\n\n${baseContent}\n\n` : ''}## Integration Instructions
184
196
 
185
- Use the \`${skillName}\` skill to integrate WorkOS AuthKit into this application.
186
-
187
- The skill contains step-by-step instructions including:
188
- 1. Fetching the SDK documentation
189
- 2. Installing the SDK
190
- 3. Creating the callback route
191
- 4. Setting up middleware/auth handling
192
- 5. Adding authentication UI to the home page
197
+ ${refContent}
193
198
 
194
199
  Report your progress using [STATUS] prefixes.
195
200
 
196
- Begin by invoking the ${skillName} skill.`;
201
+ Begin integration now.`;
197
202
  }
198
203
  function buildCompletionSummary(config, changes, nextSteps) {
199
204
  const lines = ['Successfully installed WorkOS AuthKit!', ''];