-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathagent-runner.ts
More file actions
315 lines (263 loc) · 11.5 KB
/
agent-runner.ts
File metadata and controls
315 lines (263 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import { getReference } from '@workos/skills';
import { SPINNER_MESSAGE, type FrameworkConfig } from './framework-config.js';
import { validateInstallation, quickCheckValidateAndFormat } from './validation/index.js';
import type { InstallerOptions } from '../utils/types.js';
import {
ensurePackageIsInstalled,
getOrAskForWorkOSCredentials,
getPackageDotJson,
isUsingTypeScript,
} from '../utils/clack-utils.js';
import { analytics } from '../utils/analytics.js';
import { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';
import { initializeAgent, runAgent, type RetryConfig } from './agent-interface.js';
import { uploadEnvironmentVariablesStep } from '../steps/index.js';
import { autoConfigureWorkOSEnvironment } from './workos-management.js';
import { detectPort, getCallbackPath } from './port-detection.js';
import { writeEnvLocal } from './env-writer.js';
import { readFile, access } from 'node:fs/promises';
import { join } from 'node:path';
import { parseEnvFile } from '../utils/env-parser.js';
/**
* Universal agent-powered wizard runner.
* Handles the complete flow for any framework using WorkOS MCP integration.
*
* @returns A detailed summary of what was done and next steps
*/
export async function runAgentInstaller(config: FrameworkConfig, options: InstallerOptions): Promise<string> {
// Emit status for UI adapters to render
options.emitter?.emit('status', {
message: `Setting up WorkOS AuthKit for ${config.metadata.name}`,
});
const typeScriptDetected = isUsingTypeScript(options);
// Git check is now handled by the state machine - no need to check here
// Framework detection and version
const packageJson = await getPackageDotJson(options);
await ensurePackageIsInstalled(packageJson, config.detection.packageName, config.detection.packageDisplayName);
const frameworkVersion = config.detection.getVersion(packageJson);
// Set analytics tags for framework version
if (frameworkVersion && config.detection.getVersionBucket) {
const versionBucket = config.detection.getVersionBucket(frameworkVersion);
analytics.setTag(`${config.metadata.integration}-version`, versionBucket);
}
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'started agent integration',
integration: config.metadata.integration,
});
// Get WorkOS credentials (API key optional for client-only SDKs)
const { apiKey, clientId } = await getOrAskForWorkOSCredentials(options, config.environment.requiresApiKey);
// Check if caller (state machine) already configured WorkOS environment
// If credentials were passed via options, the caller handled config+env writing
const callerHandledConfig = Boolean(options.apiKey || options.clientId);
// Auto-configure WorkOS environment (redirect URI, CORS, homepage)
// Skip if caller already handled this (prevents duplicate dashboard config output)
if (!callerHandledConfig && apiKey && config.environment.requiresApiKey) {
const port = detectPort(config.metadata.integration, options.installDir);
await autoConfigureWorkOSEnvironment(apiKey, config.metadata.integration, port, {
homepageUrl: options.homepageUrl,
redirectUri: options.redirectUri,
});
}
// Gather framework-specific context (e.g., Next.js router, React Native platform)
const frameworkContext = config.metadata.gatherContext ? await config.metadata.gatherContext(options) : {};
// Write environment variables to .env.local BEFORE agent runs
// Skip if caller already handled this (prevents double-writing)
if (!callerHandledConfig) {
const port = detectPort(config.metadata.integration, options.installDir);
const callbackPath = getCallbackPath(config.metadata.integration);
const redirectUri = options.redirectUri || `http://localhost:${port}${callbackPath}`;
// Next.js requires NEXT_PUBLIC_ prefix for client-side env vars
const redirectUriKey =
config.metadata.integration === 'nextjs' ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI';
writeEnvLocal(options.installDir, {
...(apiKey ? { WORKOS_API_KEY: apiKey } : {}),
WORKOS_CLIENT_ID: clientId,
[redirectUriKey]: redirectUri,
});
}
// Set analytics tags from framework context
const contextTags = config.analytics.getTags(frameworkContext);
Object.entries(contextTags).forEach(([key, value]) => {
analytics.setTag(key, value);
});
// Build integration prompt (credentials are already in .env.local)
const integrationPrompt = await buildIntegrationPrompt(
config,
{
frameworkVersion: frameworkVersion || 'latest',
typescript: typeScriptDetected,
},
frameworkContext,
);
// Initialize and run agent
// Spinner is now handled by adapters listening to agent:start/agent:progress events
const agent = await initializeAgent(
{
workingDirectory: options.installDir,
workOSApiKey: apiKey,
workOSApiHost: 'https://api.workos.com',
},
options,
);
const retryConfig: RetryConfig | undefined = options.noValidate
? undefined
: {
maxRetries: options.maxRetries ?? 2,
validateAndFormat: quickCheckValidateAndFormat,
};
// Run agent with retry support — agent gets correction prompts on validation failure
const agentResult = await runAgent(
agent,
integrationPrompt,
options,
{
spinnerMessage: SPINNER_MESSAGE,
successMessage: config.ui.successMessage,
errorMessage: 'Integration failed',
},
options.emitter,
retryConfig,
);
// If agent returned an error, throw so state machine can handle it
if (agentResult.error) {
await analytics.shutdown('error');
const message = agentResult.errorMessage || agentResult.error;
throw new Error(`Agent SDK error: ${message}`);
}
// Track retry metrics
if (agentResult.retryCount !== undefined && agentResult.retryCount > 0) {
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'agent retry summary',
retry_count: agentResult.retryCount,
max_retries: options.maxRetries ?? 2,
passed_after_retry: true,
});
}
// Run full validation after agent (with retries) completes
// Quick checks already ran inside the retry loop — skip build
if (!options.noValidate) {
options.emitter?.emit('validation:start', { framework: config.metadata.integration });
const validationResult = await validateInstallation(config.metadata.integration, options.installDir, {
runBuild: false,
});
if (validationResult.issues.length > 0) {
options.emitter?.emit('validation:issues', { issues: validationResult.issues });
}
options.emitter?.emit('validation:complete', {
passed: validationResult.passed,
issueCount: validationResult.issues.length,
durationMs: validationResult.durationMs,
});
}
// Build environment variables from WorkOS credentials
const envVars = config.environment.getEnvVars(apiKey, clientId);
// Supplement with additional vars from .env.local (cookie password, redirect URI)
// These are generated by writeEnvLocal during configuration but not in getEnvVars.
// We read .env.local rather than changing the shared getEnvVars interface (used by 15+ integrations).
const envLocalPath = join(options.installDir, '.env.local');
try {
await access(envLocalPath);
const envLocal = parseEnvFile(await readFile(envLocalPath, 'utf-8'));
if (envLocal.WORKOS_COOKIE_PASSWORD) {
envVars.WORKOS_COOKIE_PASSWORD = envLocal.WORKOS_COOKIE_PASSWORD;
}
for (const key of Object.keys(envLocal)) {
if (key.endsWith('WORKOS_REDIRECT_URI') && !envVars[key]) {
envVars[key] = envLocal[key];
}
}
} catch {
// .env.local doesn't exist yet — vars will be written by agent
}
// Upload environment variables to hosting providers (if configured)
let uploadedEnvVars: string[] = [];
if (config.environment.uploadToHosting) {
uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {
integration: config.metadata.integration,
options,
});
}
const changes = [
...config.ui.getOutroChanges(frameworkContext),
Object.keys(envVars).length > 0 ? `Added environment variables to .env file` : '',
uploadedEnvVars.length > 0 ? `Uploaded environment variables to your hosting provider` : '',
].filter(Boolean);
const nextSteps = [
...config.ui.getOutroNextSteps(frameworkContext),
uploadedEnvVars.length === 0 && config.environment.uploadToHosting
? `Upload your WorkOS credentials to your hosting provider`
: '',
].filter(Boolean);
const summary = buildCompletionSummary(config, changes, nextSteps);
await analytics.shutdown('success');
return summary;
}
/**
* Build the integration prompt for the agent.
* Reads reference content from @workos/skills and injects it directly into the prompt.
* Note: Credentials are pre-written to .env.local, so not included in prompt.
*/
async function buildIntegrationPrompt(
config: FrameworkConfig,
context: {
frameworkVersion: string;
typescript: boolean;
},
frameworkContext: Record<string, any>,
): Promise<string> {
const additionalLines = config.prompts.getAdditionalContextLines
? config.prompts.getAdditionalContextLines(frameworkContext)
: [];
const additionalContext =
additionalLines.length > 0 ? '\n' + additionalLines.map((line) => `- ${line}`).join('\n') : '';
const skillName = config.metadata.skillName;
if (!skillName) {
throw new Error(`Framework ${config.metadata.name} missing skillName in config`);
}
// Read reference content from @workos/skills package
// Base template has JS-centric assumptions (node_modules, lockfiles, AuthKitProvider)
// so only load it for JavaScript integrations; backend SDKs bypass this entirely
const isJavaScript = config.metadata.language === 'javascript';
const [baseContent, refContent] = await Promise.all([
isJavaScript ? getReference('workos-authkit-base') : Promise.resolve(''),
getReference(skillName),
]);
// Build env var list dynamically based on what was actually configured
const envVars = [
...(config.environment.requiresApiKey ? ['WORKOS_API_KEY'] : []),
'WORKOS_CLIENT_ID',
config.metadata.integration === 'nextjs' ? 'NEXT_PUBLIC_WORKOS_REDIRECT_URI' : 'WORKOS_REDIRECT_URI',
'WORKOS_COOKIE_PASSWORD',
];
const envVarList = envVars.map((v) => `- ${v}`).join('\n');
return `You are integrating WorkOS AuthKit into this ${config.metadata.name} application.
## Project Context
- Framework: ${config.metadata.name} ${context.frameworkVersion}
- TypeScript: ${context.typescript ? 'Yes' : 'No'}${additionalContext}
## Environment
The following environment variables have been configured in .env.local:
${envVarList}
${baseContent ? `## General Guidelines\n\n${baseContent}\n\n` : ''}## Integration Instructions
${refContent}
Report your progress using [STATUS] prefixes.
Begin integration now.`;
}
function buildCompletionSummary(config: FrameworkConfig, changes: string[], nextSteps: string[]): string {
const lines: string[] = ['Successfully installed WorkOS AuthKit!', ''];
if (changes.length > 0) {
lines.push('What the agent did:');
for (const change of changes) lines.push(`• ${change}`);
lines.push('');
}
if (nextSteps.length > 0) {
lines.push('Next steps:');
for (const step of nextSteps) lines.push(`• ${step}`);
lines.push('');
}
lines.push(
`Learn more: ${config.metadata.docsUrl}`,
'',
'Note: This installer uses an LLM agent to analyze and modify your project. Please review the changes made.',
);
return lines.join('\n');
}