-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathagent-interface.ts
More file actions
971 lines (866 loc) · 34.2 KB
/
agent-interface.ts
File metadata and controls
971 lines (866 loc) · 34.2 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
/**
* Shared agent interface for WorkOS wizards
* Uses Claude Agent SDK directly with WorkOS MCP server
*/
import { dirname } from 'path';
import { getSkillsDir as getSkillsPackageDir } from '@workos/skills';
import { debug, logInfo, logWarn, logError, initLogFile, getLogFilePath } from '../utils/debug.js';
import type { InstallerOptions } from '../utils/types.js';
import { analytics } from '../utils/analytics.js';
import { INSTALLER_INTERACTION_EVENT_NAME } from './constants.js';
import { LINTING_TOOLS } from './safe-tools.js';
import { getLlmGatewayUrlFromHost } from '../utils/urls.js';
import { formatWorkOSCommand } from '../utils/command-invocation.js';
import { getConfig } from './settings.js';
import { getCredentials, hasCredentials } from './credentials.js';
import { ensureValidToken } from './token-refresh.js';
import type { InstallerEventEmitter } from './events.js';
import { startCredentialProxy, startClaimTokenProxy, type CredentialProxyHandle } from './credential-proxy.js';
import { getActiveEnvironment, isUnclaimedEnvironment } from './config-store.js';
import { getAuthkitDomain, getCliAuthClientId } from './settings.js';
import type {
SDKMessage,
SDKUserMessage,
Options as AgentSDKOptions,
PermissionResult,
query as queryFn,
} from '@anthropic-ai/claude-agent-sdk';
// File content cache for computing edit diffs
const fileContentCache = new Map<string, string>();
// Track pending Read operations by tool_use_id
const pendingReads = new Map<string, string>();
// Track tool start times by tool_use_id for telemetry
const pendingToolCalls = new Map<string, { toolName: string; startTime: number }>();
// Module-level variable to track proxy handle for cleanup
let activeProxyHandle: CredentialProxyHandle | null = null;
// Dynamic import cache for ESM module
let _sdkModule: { query: typeof queryFn } | null = null;
async function getSDKModule(): Promise<{ query: typeof queryFn }> {
if (!_sdkModule) {
_sdkModule = await import('@anthropic-ai/claude-agent-sdk');
}
return _sdkModule;
}
export const AgentSignals = {
/** Signal emitted when the agent reports progress to the user */
STATUS: '[STATUS]',
/** Signal emitted when the agent cannot access the WorkOS MCP server */
ERROR_MCP_MISSING: '[ERROR-MCP-MISSING]',
/** Signal emitted when the agent cannot access the setup resource */
ERROR_RESOURCE_MISSING: '[ERROR-RESOURCE-MISSING]',
} as const;
export type AgentSignal = (typeof AgentSignals)[keyof typeof AgentSignals];
/** Internal prefix used to tag service-unavailability errors from handleSDKMessage */
const SERVICE_UNAVAILABLE_PREFIX = '__SERVICE_UNAVAILABLE__';
/** Internal prefix used to tag rate-limit errors from handleSDKMessage */
const RATE_LIMITED_PREFIX = '__RATE_LIMITED__';
/**
* Error types that can be returned from agent execution.
* These correspond to the error signals that the agent emits.
*/
export enum AgentErrorType {
/** Agent could not access the WorkOS MCP server */
MCP_MISSING = 'INSTALLER_MCP_MISSING',
/** Agent could not access the setup resource */
RESOURCE_MISSING = 'INSTALLER_RESOURCE_MISSING',
/** Agent execution failed (API error, auth error, etc.) */
EXECUTION_ERROR = 'INSTALLER_EXECUTION_ERROR',
/** AI service is unavailable (API 500, outage, etc.) */
SERVICE_UNAVAILABLE = 'INSTALLER_SERVICE_UNAVAILABLE',
}
export type AgentConfig = {
workingDirectory: string;
workOSApiKey: string;
workOSApiHost: string;
};
export interface RetryConfig {
/** Max correction attempts after initial run. Default: 2 */
maxRetries: number;
/** Run between agent turns. Return null if passed, or error prompt if failed. */
validateAndFormat: (workingDirectory: string) => Promise<string | null>;
}
/**
* Configuration object for running the agent.
* Built by initializeAgent (production) or constructed directly (evals).
*/
export type AgentRunConfig = {
workingDirectory: string;
mcpServers: AgentSDKOptions['mcpServers'];
model: string;
allowedTools: string[];
sdkEnv: Record<string, string | undefined>;
};
/**
* Package managers that can be used to run commands.
* Includes JS and non-JS ecosystem package managers for multi-SDK support.
*/
const PACKAGE_MANAGERS = [
// JavaScript
'npm',
'pnpm',
'yarn',
'bun',
'npx',
'pnpx',
'bunx',
// Python
'pip',
'pip3',
'poetry',
'uv',
'pipx',
'python',
'python3',
// Ruby
'gem',
'bundle',
'bundler',
'ruby',
// PHP
'composer',
'php',
// Go
'go',
// .NET
'dotnet',
'nuget',
// Elixir
'mix',
'hex',
'elixir',
// Kotlin/Java
'gradle',
'gradlew',
'./gradlew',
'mvn',
];
/**
* Safe scripts/commands that can be run with any package manager.
* Uses startsWith matching, so 'build' matches 'build', 'build:prod', etc.
* Note: Linting tools are in LINTING_TOOLS and checked separately.
*/
const SAFE_SCRIPTS = [
// Package installation
'install',
'add',
'ci',
// Build
'build',
// Type checking (various naming conventions)
'tsc',
'typecheck',
'type-check',
'check-types',
'types',
// Linting/formatting script names (actual tools are in LINTING_TOOLS)
'lint',
'format',
// Common cross-language commands
'check',
'test',
'run',
'serve',
'dev',
'start',
'compile',
'vet',
// Python-specific
'manage.py',
'pytest',
// Ruby-specific
'rspec',
'rake',
'routes',
// PHP-specific
'artisan',
'phpunit',
// Elixir-specific
'deps.get',
'credo',
'dialyzer',
// .NET-specific
'restore',
];
/**
* Dangerous shell operators that could allow command injection.
* Note: We handle `2>&1` and `| tail/head` separately as safe patterns.
*/
const DANGEROUS_OPERATORS = /[;`$()]/;
/**
* Check if command is an allowed package manager command.
* Matches: <pkg-manager> [run|exec] <safe-script> [args...]
*/
function matchesAllowedPrefix(command: string): boolean {
const parts = command.split(/\s+/);
if (parts.length === 0 || !PACKAGE_MANAGERS.includes(parts[0])) {
return false;
}
// Skip 'run' or 'exec' if present
let scriptIndex = 1;
if (parts[scriptIndex] === 'run' || parts[scriptIndex] === 'exec') {
scriptIndex++;
}
// Get the script/command portion (may include args)
const scriptPart = parts.slice(scriptIndex).join(' ');
// Check if script starts with any safe script name or linting tool
return (
SAFE_SCRIPTS.some((safe) => scriptPart.startsWith(safe)) ||
LINTING_TOOLS.some((tool) => scriptPart.startsWith(tool))
);
}
/**
* Permission hook that allows only safe commands.
* - Package manager install commands
* - Build/typecheck/lint commands for verification
* - Piping to tail/head for output limiting is allowed
* - Stderr redirection (2>&1) is allowed
*/
export function installerCanUseTool(toolName: string, input: Record<string, unknown>): PermissionResult {
// Allow all non-Bash tools
if (toolName !== 'Bash') {
return { behavior: 'allow', updatedInput: input };
}
const command = (typeof input.command === 'string' ? input.command : '').trim();
// Block definitely dangerous operators: ; ` $ ( )
if (DANGEROUS_OPERATORS.test(command)) {
logWarn(`Denying bash command with dangerous operators: ${command}`);
debug(`Denying bash command with dangerous operators: ${command}`);
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'bash command denied',
reason: 'dangerous operators',
command,
});
return {
behavior: 'deny',
message: `Bash command not allowed. Shell operators like ; \` $ ( ) are not permitted.`,
};
}
// Normalize: remove safe stderr redirection (2>&1, 2>&2, etc.)
const normalized = command.replace(/\s*\d*>&\d+\s*/g, ' ').trim();
// Check for pipe to tail/head (safe output limiting)
const pipeMatch = normalized.match(/^(.+?)\s*\|\s*(tail|head)(\s+\S+)*\s*$/);
if (pipeMatch) {
const baseCommand = pipeMatch[1].trim();
// Block if base command has pipes or & (multiple chaining)
if (/[|&]/.test(baseCommand)) {
logWarn(`Denying bash command with multiple pipes: ${command}`);
debug(`Denying bash command with multiple pipes: ${command}`);
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'bash command denied',
reason: 'multiple pipes',
command,
});
return {
behavior: 'deny',
message: `Bash command not allowed. Only single pipe to tail/head is permitted.`,
};
}
if (matchesAllowedPrefix(baseCommand)) {
logInfo(`Allowing bash command with output limiter: ${command}`);
debug(`Allowing bash command with output limiter: ${command}`);
return { behavior: 'allow', updatedInput: input };
}
}
// Block remaining pipes and & (not covered by tail/head case above)
if (/[|&]/.test(normalized)) {
logWarn(`Denying bash command with pipe/&: ${command}`);
debug(`Denying bash command with pipe/&: ${command}`);
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'bash command denied',
reason: 'disallowed pipe',
command,
});
return {
behavior: 'deny',
message: `Bash command not allowed. Pipes are only permitted with tail/head for output limiting.`,
};
}
// Check if command starts with any allowed prefix
if (matchesAllowedPrefix(normalized)) {
logInfo(`Allowing bash command: ${command}`);
debug(`Allowing bash command: ${command}`);
return { behavior: 'allow', updatedInput: input };
}
logWarn(`Denying bash command: ${command}`);
debug(`Denying bash command: ${command}`);
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'bash command denied',
reason: 'not in allowlist',
command,
});
return {
behavior: 'deny',
message: `Bash command not allowed. Only install, build, typecheck, lint, and formatting commands are permitted.`,
};
}
/**
* Initialize agent configuration for the LLM gateway
*/
export async function initializeAgent(config: AgentConfig, options: InstallerOptions): Promise<AgentRunConfig> {
// Initialize log file for this run
initLogFile();
logInfo('Agent initialization starting');
logInfo('Install directory:', options.installDir);
// Emit status event for adapters to render
options.emitter?.emit('status', { message: 'Initializing Claude agent...' });
try {
let authMode: string;
// Build SDK env without mutating process.env
const sdkEnv: Record<string, string | undefined> = {
...process.env,
// Disable experimental betas (like input_examples) that the LLM gateway doesn't support
CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS: 'true',
// Disable SDK telemetry - our gateway doesn't proxy /api/event_logging/batch
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: 'true',
};
// Placeholder bearer token for the Claude Agent SDK. The SDK's CLI
// subprocess runs a local auth-source check at startup and exits with
// "Not logged in · Please run /login" if no credentials are present in
// its environment — even when a proxy is handling auth upstream. Setting
// this token puts the SDK in custom-backend mode so it skips that check;
// the credential proxy rewrites the Authorization header with the real
// WorkOS token before forwarding upstream.
const PROXY_PLACEHOLDER_TOKEN = 'workos-cli-proxy-placeholder';
if (options.direct) {
// Direct mode: use user's Anthropic API key, skip gateway
if (!process.env.ANTHROPIC_API_KEY) {
throw new Error(
'Direct mode requires ANTHROPIC_API_KEY environment variable.\n' +
'Set it with: export ANTHROPIC_API_KEY=sk-ant-...\n' +
'Get your key at: https://console.anthropic.com/settings/keys',
);
}
// SDK defaults to api.anthropic.com when no base URL set
delete sdkEnv.ANTHROPIC_BASE_URL;
delete sdkEnv.ANTHROPIC_AUTH_TOKEN;
authMode = 'direct:api.anthropic.com';
logInfo('Direct mode: using ANTHROPIC_API_KEY, bypassing llm-gateway');
// Set analytics tag for direct mode
analytics.setTag('api_mode', 'direct');
} else {
// Gateway mode (existing behavior)
const gatewayUrl = getLlmGatewayUrlFromHost();
// Check for unclaimed environment — use claim token auth
const activeEnv = getActiveEnvironment();
if (activeEnv && isUnclaimedEnvironment(activeEnv)) {
activeProxyHandle = await startClaimTokenProxy({
upstreamUrl: gatewayUrl,
claimToken: activeEnv.claimToken,
clientId: activeEnv.clientId,
});
sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;
// Prevent the user's personal Anthropic key (if any) from being sent
// to the WorkOS gateway; auth is injected by the claim-token proxy.
delete sdkEnv.ANTHROPIC_API_KEY;
sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;
authMode = `claim-token-proxy:${activeProxyHandle.url}→${gatewayUrl}`;
logInfo(`[agent-interface] Using claim token proxy for unclaimed environment`);
} else if (!options.skipAuth && !options.local) {
// Check/refresh authentication for production (unless skipping auth)
if (!hasCredentials()) {
throw new Error(`Not authenticated. Run \`${formatWorkOSCommand('auth login')}\` to authenticate.`);
}
const creds = getCredentials();
if (!creds) {
throw new Error(`Not authenticated. Run \`${formatWorkOSCommand('auth login')}\` to authenticate.`);
}
// Check if we have refresh token capability and proxy is not disabled
if (creds.refreshToken && process.env.INSTALLER_DISABLE_PROXY !== '1') {
// Start credential proxy with lazy refresh
logInfo('[agent-interface] Starting credential proxy with lazy refresh...');
const appConfig = getConfig();
activeProxyHandle = await startCredentialProxy({
upstreamUrl: gatewayUrl,
refresh: {
authkitDomain: getAuthkitDomain(),
clientId: getCliAuthClientId(),
refreshThresholdMs: appConfig.proxy.refreshThresholdMs,
onRefreshSuccess: () => {
options.emitter?.emit('status', { message: 'Session extended' });
},
onRefreshExpired: () => {
logError('[agent-interface] Session expired, refresh token invalid');
options.emitter?.emit('error', {
message: `Session expired. Run \`${formatWorkOSCommand('auth login')}\` to re-authenticate.`,
});
},
},
});
// Point SDK at proxy instead of direct gateway
sdkEnv.ANTHROPIC_BASE_URL = activeProxyHandle.url;
logInfo(`[agent-interface] Using credential proxy at ${activeProxyHandle.url}`);
// Prevent the user's personal Anthropic key (if any) from being
// sent to the WorkOS gateway; the credential proxy rewrites the
// Authorization header with the real WorkOS token.
delete sdkEnv.ANTHROPIC_API_KEY;
sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;
authMode = `proxy:${activeProxyHandle.url}→${gatewayUrl}`;
} else {
// No refresh token OR proxy disabled - fall back to old behavior (5 min limit)
if (!creds.refreshToken) {
logWarn('[agent-interface] No refresh token available, session limited to 5 minutes');
logWarn(`[agent-interface] Run \`${formatWorkOSCommand('auth login')}\` to enable extended sessions`);
options.emitter?.emit('status', {
message: `Note: Run \`${formatWorkOSCommand('auth login')}\` to enable extended sessions`,
});
} else {
logWarn('[agent-interface] Proxy disabled via INSTALLER_DISABLE_PROXY');
}
const refreshResult = await ensureValidToken();
if (!refreshResult.success) {
throw new Error(refreshResult.error || 'Authentication failed');
}
sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;
// Prevent the user's personal Anthropic key (if any) from being
// forwarded to the WorkOS gateway as an x-api-key header alongside
// the WorkOS access token we set below.
delete sdkEnv.ANTHROPIC_API_KEY;
sdkEnv.ANTHROPIC_AUTH_TOKEN = creds.accessToken;
authMode = options.local ? `local-gateway:${gatewayUrl}` : `workos-gateway:${gatewayUrl}`;
logInfo('Sending access token to gateway (legacy mode)');
}
} else if (options.skipAuth) {
// Skip auth mode - direct to gateway without a real token. The SDK's
// local auth-source check would otherwise fail with "Not logged in",
// so seed a placeholder bearer; the gateway is expected to accept
// unauthenticated requests here and ignore the placeholder value.
sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;
delete sdkEnv.ANTHROPIC_API_KEY;
sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;
authMode = `skip-auth:${gatewayUrl}`;
logInfo('Skipping auth - placeholder bearer sent to gateway');
} else {
// Local mode without auth - same rationale as skip-auth above.
sdkEnv.ANTHROPIC_BASE_URL = gatewayUrl;
delete sdkEnv.ANTHROPIC_API_KEY;
sdkEnv.ANTHROPIC_AUTH_TOKEN = PROXY_PLACEHOLDER_TOKEN;
authMode = `local-gateway:${gatewayUrl}`;
logInfo('Local mode - placeholder bearer sent to gateway');
}
logInfo('Configured LLM gateway:', sdkEnv.ANTHROPIC_BASE_URL);
// Set analytics tag for gateway mode
analytics.setTag('api_mode', activeProxyHandle ? 'gateway-proxy' : 'gateway');
}
// Configure WorkOS MCP docs server for accessing WorkOS documentation
const agentRunConfig: AgentRunConfig = {
workingDirectory: config.workingDirectory,
mcpServers: {
workos: {
command: 'npx',
args: ['-y', '@workos/mcp-docs-server'],
},
},
model: getConfig().model,
allowedTools: ['Read', 'Write', 'Edit', 'Bash', 'Glob', 'Grep', 'WebFetch'],
sdkEnv,
};
const configInfo = { workingDirectory: agentRunConfig.workingDirectory, authMode, useMcp: false };
logInfo('Agent config:', configInfo);
debug('Agent config:', configInfo);
// Emit status events for adapters to render
const currentLogPath = getLogFilePath();
if (currentLogPath) {
options.emitter?.emit('status', { message: `Verbose logs: ${currentLogPath}` });
}
options.emitter?.emit('status', { message: "Agent initialized. Let's get cooking!" });
return agentRunConfig;
} catch (error) {
// Clean up proxy if initialization fails
if (activeProxyHandle) {
logInfo('[agent-interface] Cleaning up proxy after init error');
await activeProxyHandle.stop();
activeProxyHandle = null;
}
logError('Agent initialization error:', error);
throw error;
}
}
/**
* Execute an agent with the provided prompt and options
* Handles the full lifecycle via event emissions - adapters handle UI rendering.
*
* @returns An object containing any error detected in the agent's output
*/
export async function runAgent(
agentConfig: AgentRunConfig,
prompt: string,
options: InstallerOptions,
config?: {
spinnerMessage?: string;
successMessage?: string;
errorMessage?: string;
},
emitter?: InstallerEventEmitter,
retryConfig?: RetryConfig,
onMessage?: (message: SDKMessage) => void,
): Promise<{ error?: AgentErrorType; errorMessage?: string; retryCount?: number }> {
const { spinnerMessage = 'Setting up WorkOS AuthKit...' } = config ?? {};
const { query } = await getSDKModule();
// Emit progress for adapters to handle (e.g., CLI adapter starts spinner)
emitter?.emit('agent:progress', { step: 'Starting', detail: 'This may take a few minutes. Grab some coffee!' });
emitter?.emit('agent:progress', { step: spinnerMessage });
logInfo('Starting agent run');
logInfo('Prompt:', prompt);
const startTime = Date.now();
const collectedText: string[] = [];
try {
let retryCount = 0;
const maxRetries = retryConfig?.maxRetries ?? 0;
// Turn completion signals — resolveCurrentTurn is called when a 'result'
// message arrives; the prompt generator awaits currentTurnDone between turns.
let resolveCurrentTurn!: () => void;
let currentTurnDone!: Promise<void>;
// Set by the message loop when a fatal SDK error is detected (e.g. service
// unavailability). The prompt stream checks this before yielding retry
// prompts so we fail fast instead of burning minutes on hopeless retries.
let abortRetries = false;
function resetTurnSignal() {
currentTurnDone = new Promise<void>((resolve) => {
resolveCurrentTurn = resolve;
});
}
resetTurnSignal();
const createPromptStream = async function* (): AsyncGenerator<SDKUserMessage> {
yield {
type: 'user' as const,
session_id: '',
message: { role: 'user' as const, content: prompt },
parent_tool_use_id: null,
};
if (retryConfig && maxRetries > 0) {
while (retryCount < maxRetries) {
await currentTurnDone;
// Don't send correction prompts when the service itself is down
if (abortRetries) {
logInfo('Skipping validation retries due to service error');
break;
}
emitter?.emit('validation:retry:start', { attempt: retryCount + 1 });
let validationPrompt: string | null;
try {
validationPrompt = await retryConfig.validateAndFormat(agentConfig.workingDirectory);
} catch (err) {
// Don't block on validation bugs — treat as passed
logError('validateAndFormat threw:', err);
validationPrompt = null;
}
emitter?.emit('validation:retry:complete', {
attempt: retryCount + 1,
passed: validationPrompt === null,
});
if (validationPrompt === null) break;
retryCount++;
emitter?.emit('agent:retry', { attempt: retryCount, maxRetries });
resetTurnSignal();
yield {
type: 'user',
session_id: '',
message: { role: 'user', content: validationPrompt },
parent_tool_use_id: null,
};
}
}
await currentTurnDone;
};
// Load plugin from @workos/skills package
const pluginPath = dirname(getSkillsPackageDir());
logInfo('Loading plugin from:', pluginPath);
const response = query({
prompt: createPromptStream(),
options: {
model: agentConfig.model,
cwd: agentConfig.workingDirectory,
permissionMode: 'acceptEdits',
mcpServers: agentConfig.mcpServers,
env: agentConfig.sdkEnv,
canUseTool: (toolName, input) => {
logInfo('canUseTool called:', { toolName, input });
const result = installerCanUseTool(toolName, input);
logInfo('canUseTool result:', result);
return Promise.resolve(result);
},
tools: { type: 'preset', preset: 'claude_code' },
allowedTools: agentConfig.allowedTools,
plugins: [{ type: 'local', path: pluginPath }],
// Capture stderr from CLI subprocess for debugging
stderr: (data: string) => {
logInfo('CLI stderr:', data);
if (options.debug) {
debug('CLI stderr:', data);
}
},
},
});
// Process the async generator
let sdkError: string | undefined;
for await (const message of response) {
const messageError = handleSDKMessage(message, options, collectedText, emitter);
if (messageError) {
sdkError = messageError;
// Signal the prompt stream to stop yielding retry prompts
abortRetries = true;
}
if (message.type === 'result') {
resolveCurrentTurn();
}
try {
onMessage?.(message);
} catch {
/* non-critical */
}
}
const durationMs = Date.now() - startTime;
const outputText = collectedText.join('\n');
// Check for SDK errors first (e.g., API errors, auth failures)
// Return error type + message - caller decides whether to throw or emit events
if (sdkError) {
if (sdkError.startsWith(SERVICE_UNAVAILABLE_PREFIX)) {
const detail = sdkError.slice(SERVICE_UNAVAILABLE_PREFIX.length);
logError('AI service unavailable:', detail);
return {
error: AgentErrorType.SERVICE_UNAVAILABLE,
errorMessage: 'The AI service is temporarily unavailable. Please try again in a few minutes.',
};
}
if (sdkError.startsWith(RATE_LIMITED_PREFIX)) {
const detail = sdkError.slice(RATE_LIMITED_PREFIX.length);
logError('AI service rate-limited:', detail);
return {
error: AgentErrorType.SERVICE_UNAVAILABLE,
errorMessage: 'The AI service is currently rate-limited. Please wait a minute and try again.',
};
}
logError('Agent SDK error:', sdkError);
return { error: AgentErrorType.EXECUTION_ERROR, errorMessage: sdkError };
}
// Check for error markers in the agent's output
if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {
logError('Agent error: MCP_MISSING');
return { error: AgentErrorType.MCP_MISSING, errorMessage: 'Could not access WorkOS MCP server' };
}
if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {
logError('Agent error: RESOURCE_MISSING');
return { error: AgentErrorType.RESOURCE_MISSING, errorMessage: 'Could not access setup resource' };
}
logInfo(`Agent run completed in ${Math.round(durationMs / 1000)}s (${retryCount} retries)`);
analytics.capture(INSTALLER_INTERACTION_EVENT_NAME, {
action: 'agent integration completed',
duration_ms: durationMs,
duration_seconds: Math.round(durationMs / 1000),
retry_count: retryCount,
max_retries: maxRetries,
passed_after_retry: retryCount > 0,
});
// Don't emit agent:success here - let the state machine handle lifecycle events
return { retryCount };
} catch (error) {
// Don't emit events here - just log and re-throw for state machine to handle
logError('Agent run failed:', error);
debug('Full error:', error);
throw error;
} finally {
// Always clean up proxy when agent run completes
if (activeProxyHandle) {
logInfo('[agent-interface] Stopping credential proxy');
analytics.capture('installer.proxy', {
action: 'stop',
port: activeProxyHandle.port,
});
await activeProxyHandle.stop();
activeProxyHandle = null;
}
}
}
/**
* Handle SDK messages and emit events for adapters to render.
* @returns Error message if this was an error result, undefined otherwise
*/
function handleSDKMessage(
message: SDKMessage,
options: InstallerOptions,
collectedText: string[],
emitter?: InstallerEventEmitter,
): string | undefined {
logInfo(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));
switch (message.type) {
case 'assistant': {
// Extract usage data from Anthropic API response for telemetry
const usage = message.message?.usage;
if (usage) {
const inputTokens = usage.input_tokens ?? 0;
const outputTokens = usage.output_tokens ?? 0;
const model = message.message?.model ?? 'unknown';
analytics.llmRequest(model, inputTokens, outputTokens);
analytics.incrementAgentIterations();
}
// Extract text content from assistant messages
const content = message.message?.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === 'text' && typeof block.text === 'string') {
collectedText.push(block.text);
// Emit output event for dashboard
emitter?.emit('output', { text: block.text });
// Check for [STATUS] markers and emit progress events
const statusRegex = new RegExp(
`^.*${AgentSignals.STATUS.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\s*(.+?)$`,
'm',
);
const statusMatch = block.text.match(statusRegex);
if (statusMatch) {
const statusText = statusMatch[1].trim();
// Emit progress event - adapters handle spinner updates
emitter?.emit('agent:progress', { step: statusText });
emitter?.emit('status', { message: statusText });
}
}
// Check for tool_use blocks (Write/Edit operations)
if (block.type === 'tool_use') {
const toolName = block.name as string;
const toolUseId = block.id as string;
const input = block.input as Record<string, unknown>;
// Log tool usage for debugging
logInfo(`Tool use: ${toolName}`);
// Track tool start time for telemetry
if (toolUseId) {
pendingToolCalls.set(toolUseId, { toolName, startTime: Date.now() });
}
// Emit file:write event for Write tool
if (toolName === 'Write' && input) {
const filePath = input.file_path as string;
const fileContent = input.content as string;
if (filePath && fileContent) {
emitter?.emit('file:write', { path: filePath, content: fileContent });
}
}
// Emit file:edit event for Edit tool
if (toolName === 'Edit' && input) {
const filePath = input.file_path as string;
const oldString = input.old_string as string;
const newString = input.new_string as string;
if (filePath && oldString !== undefined && newString !== undefined) {
// Emit the actual strings being replaced, not reconstructed full file
emitter?.emit('file:edit', {
path: filePath,
oldContent: oldString,
newContent: newString,
});
}
}
// Track Read operations for caching file content later
if (toolName === 'Read' && input && block.id) {
const filePath = input.file_path as string;
if (filePath) {
pendingReads.set(block.id as string, filePath);
}
}
}
}
}
break;
}
case 'user': {
// User messages contain tool results
const content = message.message?.content;
if (Array.isArray(content)) {
for (const block of content) {
// Tool results contain file content from Read operations
if (block.type === 'tool_result' && block.tool_use_id) {
const toolUseId = block.tool_use_id as string;
// Emit telemetry for completed tool call
const pendingTool = pendingToolCalls.get(toolUseId);
if (pendingTool) {
const durationMs = Date.now() - pendingTool.startTime;
// Check if tool result indicates error (is_error field or error in content)
const isError = block.is_error === true;
analytics.toolCalled(pendingTool.toolName, durationMs, !isError);
pendingToolCalls.delete(toolUseId);
}
const filePath = pendingReads.get(toolUseId);
if (filePath) {
// Extract content from the tool result
let resultContent = '';
if (typeof block.content === 'string') {
resultContent = block.content;
} else if (Array.isArray(block.content)) {
// Content might be array of text blocks
for (const item of block.content) {
if (item.type === 'text' && item.text) {
resultContent += item.text;
}
}
}
if (resultContent) {
fileContentCache.set(filePath, resultContent);
}
pendingReads.delete(toolUseId);
}
}
}
}
break;
}
case 'result': {
// The SDK may return subtype 'success' with is_error: true when API
// retries are exhausted (e.g., persistent 500s). Check is_error first.
const isResultError = (message as Record<string, unknown>).is_error === true;
if (isResultError) {
const resultText = typeof message.result === 'string' ? message.result : '';
logError('Agent result marked as error:', resultText);
// Detect rate limiting (429) — check before 5xx so it gets distinct messaging
if (/\b429\b/.test(resultText) || /rate.limit/i.test(resultText)) {
return `${RATE_LIMITED_PREFIX}${resultText}`;
}
// Detect service unavailability (API 500, upstream outage)
if (/\b50[0-9]\b/.test(resultText) || /server_error|internal_error|overloaded/.test(resultText)) {
return `${SERVICE_UNAVAILABLE_PREFIX}${resultText}`;
}
return resultText || 'Agent execution failed';
}
if (message.subtype === 'success') {
logInfo('Agent completed successfully');
if (typeof message.result === 'string') {
collectedText.push(message.result);
}
} else {
// Error result
logError('Agent error result:', message.subtype);
if (message.errors && message.errors.length > 0) {
for (const err of message.errors) {
logError('ERROR:', err);
// Emit error event - adapters handle rendering
emitter?.emit('error', { message: err });
}
// Return the first error message
return message.errors[0];
}
// Return generic error if subtype indicates failure but no errors array
return `Agent execution failed: ${message.subtype}`;
}
break;
}
case 'system': {
if (message.subtype === 'init') {
logInfo('Agent session initialized', {
model: message.model,
tools: message.tools?.length,
mcpServers: message.mcp_servers,
});
}
break;
}
default:
// Log other message types for debugging
if (options.debug) {
debug(`Unhandled message type: ${message.type}`);
}
break;
}
return undefined;
}
/**
* Get the active proxy handle (for testing/debugging).
*/
export function getActiveProxyHandle(): CredentialProxyHandle | null {
return activeProxyHandle;
}