@posthog/wizard 1.31.0 β 1.31.2
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.
- package/dist/src/lib/__tests__/agent-interface.test.js +54 -0
- package/dist/src/lib/__tests__/agent-interface.test.js.map +1 -1
- package/dist/src/lib/agent-interface.js +17 -7
- package/dist/src/lib/agent-interface.js.map +1 -1
- package/dist/src/lib/agent-runner.js +4 -3
- package/dist/src/lib/agent-runner.js.map +1 -1
- package/dist/src/utils/clack-utils.js +1 -0
- package/dist/src/utils/clack-utils.js.map +1 -1
- package/package.json +1 -1
|
@@ -132,6 +132,60 @@ describe('runAgent', () => {
|
|
|
132
132
|
expect(result.error).toBe('WIZARD_API_ERROR');
|
|
133
133
|
expect(result.message).toContain('API Error');
|
|
134
134
|
});
|
|
135
|
+
it('should suppress user-facing errors when SDK yields error result after success', async () => {
|
|
136
|
+
// This test models actual SDK behavior where the SDK emits TWO result messages:
|
|
137
|
+
// 1. SDK yields success result (num_turns: 105, is_error: false)
|
|
138
|
+
// 2. SDK yields a SECOND result with is_error: true containing
|
|
139
|
+
// accumulated cleanup/telemetry errors
|
|
140
|
+
// 3. The errors should be logged to file but NOT shown to the user
|
|
141
|
+
//
|
|
142
|
+
// This differs from the thrown exception test above - here the SDK YIELDS
|
|
143
|
+
// an error result message instead of THROWING an exception.
|
|
144
|
+
function* mockGeneratorWithYieldedErrorAfterSuccess() {
|
|
145
|
+
yield {
|
|
146
|
+
type: 'system',
|
|
147
|
+
subtype: 'init',
|
|
148
|
+
model: 'claude-opus-4-5-20251101',
|
|
149
|
+
tools: [],
|
|
150
|
+
mcp_servers: [],
|
|
151
|
+
};
|
|
152
|
+
// First result: success (this is the real completion)
|
|
153
|
+
yield {
|
|
154
|
+
type: 'result',
|
|
155
|
+
subtype: 'success',
|
|
156
|
+
is_error: false,
|
|
157
|
+
num_turns: 105,
|
|
158
|
+
result: '[WIZARD-REMARK] Integration completed successfully',
|
|
159
|
+
session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',
|
|
160
|
+
total_cost_usd: 5.83,
|
|
161
|
+
};
|
|
162
|
+
// Second result: error (SDK cleanup noise - yielded, not thrown)
|
|
163
|
+
yield {
|
|
164
|
+
type: 'result',
|
|
165
|
+
subtype: 'error_during_execution',
|
|
166
|
+
is_error: true,
|
|
167
|
+
num_turns: 0,
|
|
168
|
+
session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',
|
|
169
|
+
total_cost_usd: 0,
|
|
170
|
+
errors: [
|
|
171
|
+
'only prompt commands are supported in streaming mode',
|
|
172
|
+
'Error: 1P event logging: 14 events failed to export',
|
|
173
|
+
'Error: 1P event logging: 13 events failed to export',
|
|
174
|
+
'Error: Failed to export 14 events',
|
|
175
|
+
],
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
mockQuery.mockReturnValue(mockGeneratorWithYieldedErrorAfterSuccess());
|
|
179
|
+
const result = await (0, agent_interface_1.runAgent)(defaultAgentConfig, 'test prompt', defaultOptions, mockSpinner, {
|
|
180
|
+
successMessage: 'Test success',
|
|
181
|
+
errorMessage: 'Test error',
|
|
182
|
+
});
|
|
183
|
+
// Should return success (empty object), not error
|
|
184
|
+
expect(result).toEqual({});
|
|
185
|
+
expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');
|
|
186
|
+
// clack.log.error should NOT have been called (errors suppressed for user)
|
|
187
|
+
expect(mockClack.log.error).not.toHaveBeenCalled();
|
|
188
|
+
});
|
|
135
189
|
});
|
|
136
190
|
});
|
|
137
191
|
//# sourceMappingURL=agent-interface.test.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-interface.test.js","sourceRoot":"","sources":["../../../../src/lib/__tests__/agent-interface.test.ts"],"names":[],"mappings":";;;;;AAAA,wDAA8C;AAG9C,oBAAoB;AACpB,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;AAC/B,IAAI,CAAC,IAAI,CAAC,uBAAuB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,EAC3B,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,WAA0D,EAC1D;gBACE,cAAc,EAAE,cAAc;gBAC9B,YAAY,EAAE,YAAY;aAC3B,CACF,CAAC;YAEF,uCAAuC;YACvC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;YAC9C,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QAChD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { runAgent } from '../agent-interface';\nimport type { WizardOptions } from '../../utils/types';\n\n// Mock dependencies\njest.mock('../../utils/clack');\njest.mock('../../utils/analytics');\njest.mock('../../utils/debug');\n\n// Mock the SDK module\nconst mockQuery = jest.fn();\njest.mock('@anthropic-ai/claude-agent-sdk', () => ({\n query: (...args: unknown[]) => mockQuery(...args),\n}));\n\n// Get mocked clack for spinner\nimport clack from '../../utils/clack';\nconst mockClack = clack as jest.Mocked<typeof clack>;\n\ndescribe('runAgent', () => {\n let mockSpinner: {\n start: jest.Mock;\n stop: jest.Mock;\n message: string;\n };\n\n const defaultOptions: WizardOptions = {\n debug: false,\n installDir: '/test/dir',\n forceInstall: false,\n default: false,\n signup: false,\n localMcp: false,\n ci: false,\n };\n\n const defaultAgentConfig = {\n workingDirectory: '/test/dir',\n mcpServers: {},\n model: 'claude-opus-4-5-20251101',\n };\n\n beforeEach(() => {\n jest.clearAllMocks();\n\n mockSpinner = {\n start: jest.fn(),\n stop: jest.fn(),\n message: '',\n };\n\n mockClack.spinner = jest.fn().mockReturnValue(mockSpinner);\n mockClack.log = {\n step: jest.fn(),\n success: jest.fn(),\n error: jest.fn(),\n warn: jest.fn(),\n warning: jest.fn(),\n info: jest.fn(),\n message: jest.fn(),\n };\n });\n\n describe('race condition handling', () => {\n it('should return success when agent completes successfully then SDK cleanup fails', async () => {\n // This simulates the race condition:\n // 1. Agent completes with success result\n // 2. signalDone() is called, completing the prompt generator\n // 3. SDK tries to send cleanup command while streaming is active\n // 4. SDK throws an error\n // The fix should recognize we already got a success and return success anyway\n\n function* mockGeneratorWithCleanupError() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n yield {\n type: 'result',\n subtype: 'success',\n is_error: false,\n result: 'Agent completed successfully',\n };\n\n // Simulate the SDK cleanup error that occurs after success\n throw new Error('only prompt commands are supported in streaming mode');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithCleanupError());\n\n const result = await runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n );\n\n // Should return success (empty object), not throw\n expect(result).toEqual({});\n expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');\n });\n\n it('should still throw when no success result was received before error', async () => {\n // If we never got a success result, errors should propagate normally\n\n function* mockGeneratorWithOnlyError() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n // No success result, just an error\n throw new Error('Actual SDK error');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithOnlyError());\n\n await expect(\n runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n ),\n ).rejects.toThrow('Actual SDK error');\n\n expect(mockSpinner.stop).toHaveBeenCalledWith('Test error');\n });\n\n it('should not treat error results as success', async () => {\n // A result with is_error: true should not count as success\n // Even if subtype is 'success', the is_error flag takes precedence\n\n function* mockGeneratorWithErrorResult() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n yield {\n type: 'result',\n subtype: 'success', // subtype can be success but is_error true\n is_error: true,\n result: 'API Error: 500 Internal Server Error',\n };\n\n throw new Error('Process exited with code 1');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithErrorResult());\n\n const result = await runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n );\n\n // Should return API error, not success\n expect(result.error).toBe('WIZARD_API_ERROR');\n expect(result.message).toContain('API Error');\n });\n });\n});\n"]}
|
|
1
|
+
{"version":3,"file":"agent-interface.test.js","sourceRoot":"","sources":["../../../../src/lib/__tests__/agent-interface.test.ts"],"names":[],"mappings":";;;;;AAAA,wDAA8C;AAG9C,oBAAoB;AACpB,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;AAC/B,IAAI,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;AACnC,IAAI,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;AAE/B,sBAAsB;AACtB,MAAM,SAAS,GAAG,IAAI,CAAC,EAAE,EAAE,CAAC;AAC5B,IAAI,CAAC,IAAI,CAAC,gCAAgC,EAAE,GAAG,EAAE,CAAC,CAAC;IACjD,KAAK,EAAE,CAAC,GAAG,IAAe,EAAE,EAAE,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC;CAClD,CAAC,CAAC,CAAC;AAEJ,+BAA+B;AAC/B,8DAAsC;AACtC,MAAM,SAAS,GAAG,eAAkC,CAAC;AAErD,QAAQ,CAAC,UAAU,EAAE,GAAG,EAAE;IACxB,IAAI,WAIH,CAAC;IAEF,MAAM,cAAc,GAAkB;QACpC,KAAK,EAAE,KAAK;QACZ,UAAU,EAAE,WAAW;QACvB,YAAY,EAAE,KAAK;QACnB,OAAO,EAAE,KAAK;QACd,MAAM,EAAE,KAAK;QACb,QAAQ,EAAE,KAAK;QACf,EAAE,EAAE,KAAK;KACV,CAAC;IAEF,MAAM,kBAAkB,GAAG;QACz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;gBAEF,sDAAsD;gBACtD,MAAM;oBACJ,IAAI,EAAE,QAAQ;oBACd,OAAO,EAAE,SAAS;oBAClB,QAAQ,EAAE,KAAK;oBACf,SAAS,EAAE,GAAG;oBACd,MAAM,EAAE,oDAAoD;oBAC5D,UAAU,EAAE,sCAAsC;oBAClD,cAAc,EAAE,IAAI;iBACrB,CAAC;gBAEF,iEAAiE;gBACjE,MAAM;oBACJ,IAAI,EAAE,QAAQ;oBACd,OAAO,EAAE,wBAAwB;oBACjC,QAAQ,EAAE,IAAI;oBACd,SAAS,EAAE,CAAC;oBACZ,UAAU,EAAE,sCAAsC;oBAClD,cAAc,EAAE,CAAC;oBACjB,MAAM,EAAE;wBACN,sDAAsD;wBACtD,qDAAqD;wBACrD,qDAAqD;wBACrD,mCAAmC;qBACpC;iBACF,CAAC;YACJ,CAAC;YAED,SAAS,CAAC,eAAe,CAAC,yCAAyC,EAAE,CAAC,CAAC;YAEvE,MAAM,MAAM,GAAG,MAAM,IAAA,0BAAQ,EAC3B,kBAAkB,EAClB,aAAa,EACb,cAAc,EACd,WAA0D,EAC1D;gBACE,cAAc,EAAE,cAAc;gBAC9B,YAAY,EAAE,YAAY;aAC3B,CACF,CAAC;YAEF,kDAAkD;YAClD,MAAM,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;YAC3B,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,oBAAoB,CAAC,cAAc,CAAC,CAAC;YAE9D,2EAA2E;YAC3E,MAAM,CAAC,SAAS,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACrD,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { runAgent } from '../agent-interface';\nimport type { WizardOptions } from '../../utils/types';\n\n// Mock dependencies\njest.mock('../../utils/clack');\njest.mock('../../utils/analytics');\njest.mock('../../utils/debug');\n\n// Mock the SDK module\nconst mockQuery = jest.fn();\njest.mock('@anthropic-ai/claude-agent-sdk', () => ({\n query: (...args: unknown[]) => mockQuery(...args),\n}));\n\n// Get mocked clack for spinner\nimport clack from '../../utils/clack';\nconst mockClack = clack as jest.Mocked<typeof clack>;\n\ndescribe('runAgent', () => {\n let mockSpinner: {\n start: jest.Mock;\n stop: jest.Mock;\n message: string;\n };\n\n const defaultOptions: WizardOptions = {\n debug: false,\n installDir: '/test/dir',\n forceInstall: false,\n default: false,\n signup: false,\n localMcp: false,\n ci: false,\n };\n\n const defaultAgentConfig = {\n workingDirectory: '/test/dir',\n mcpServers: {},\n model: 'claude-opus-4-5-20251101',\n };\n\n beforeEach(() => {\n jest.clearAllMocks();\n\n mockSpinner = {\n start: jest.fn(),\n stop: jest.fn(),\n message: '',\n };\n\n mockClack.spinner = jest.fn().mockReturnValue(mockSpinner);\n mockClack.log = {\n step: jest.fn(),\n success: jest.fn(),\n error: jest.fn(),\n warn: jest.fn(),\n warning: jest.fn(),\n info: jest.fn(),\n message: jest.fn(),\n };\n });\n\n describe('race condition handling', () => {\n it('should return success when agent completes successfully then SDK cleanup fails', async () => {\n // This simulates the race condition:\n // 1. Agent completes with success result\n // 2. signalDone() is called, completing the prompt generator\n // 3. SDK tries to send cleanup command while streaming is active\n // 4. SDK throws an error\n // The fix should recognize we already got a success and return success anyway\n\n function* mockGeneratorWithCleanupError() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n yield {\n type: 'result',\n subtype: 'success',\n is_error: false,\n result: 'Agent completed successfully',\n };\n\n // Simulate the SDK cleanup error that occurs after success\n throw new Error('only prompt commands are supported in streaming mode');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithCleanupError());\n\n const result = await runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n );\n\n // Should return success (empty object), not throw\n expect(result).toEqual({});\n expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');\n });\n\n it('should still throw when no success result was received before error', async () => {\n // If we never got a success result, errors should propagate normally\n\n function* mockGeneratorWithOnlyError() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n // No success result, just an error\n throw new Error('Actual SDK error');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithOnlyError());\n\n await expect(\n runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n ),\n ).rejects.toThrow('Actual SDK error');\n\n expect(mockSpinner.stop).toHaveBeenCalledWith('Test error');\n });\n\n it('should not treat error results as success', async () => {\n // A result with is_error: true should not count as success\n // Even if subtype is 'success', the is_error flag takes precedence\n\n function* mockGeneratorWithErrorResult() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n yield {\n type: 'result',\n subtype: 'success', // subtype can be success but is_error true\n is_error: true,\n result: 'API Error: 500 Internal Server Error',\n };\n\n throw new Error('Process exited with code 1');\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithErrorResult());\n\n const result = await runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n );\n\n // Should return API error, not success\n expect(result.error).toBe('WIZARD_API_ERROR');\n expect(result.message).toContain('API Error');\n });\n\n it('should suppress user-facing errors when SDK yields error result after success', async () => {\n // This test models actual SDK behavior where the SDK emits TWO result messages:\n // 1. SDK yields success result (num_turns: 105, is_error: false)\n // 2. SDK yields a SECOND result with is_error: true containing\n // accumulated cleanup/telemetry errors\n // 3. The errors should be logged to file but NOT shown to the user\n //\n // This differs from the thrown exception test above - here the SDK YIELDS\n // an error result message instead of THROWING an exception.\n\n function* mockGeneratorWithYieldedErrorAfterSuccess() {\n yield {\n type: 'system',\n subtype: 'init',\n model: 'claude-opus-4-5-20251101',\n tools: [],\n mcp_servers: [],\n };\n\n // First result: success (this is the real completion)\n yield {\n type: 'result',\n subtype: 'success',\n is_error: false,\n num_turns: 105,\n result: '[WIZARD-REMARK] Integration completed successfully',\n session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',\n total_cost_usd: 5.83,\n };\n\n // Second result: error (SDK cleanup noise - yielded, not thrown)\n yield {\n type: 'result',\n subtype: 'error_during_execution',\n is_error: true,\n num_turns: 0,\n session_id: '2ce14bda-6d86-4220-b5bb-ab24f7004290',\n total_cost_usd: 0,\n errors: [\n 'only prompt commands are supported in streaming mode',\n 'Error: 1P event logging: 14 events failed to export',\n 'Error: 1P event logging: 13 events failed to export',\n 'Error: Failed to export 14 events',\n ],\n };\n }\n\n mockQuery.mockReturnValue(mockGeneratorWithYieldedErrorAfterSuccess());\n\n const result = await runAgent(\n defaultAgentConfig,\n 'test prompt',\n defaultOptions,\n mockSpinner as unknown as ReturnType<typeof clack.spinner>,\n {\n successMessage: 'Test success',\n errorMessage: 'Test error',\n },\n );\n\n // Should return success (empty object), not error\n expect(result).toEqual({});\n expect(mockSpinner.stop).toHaveBeenCalledWith('Test success');\n\n // clack.log.error should NOT have been called (errors suppressed for user)\n expect(mockClack.log.error).not.toHaveBeenCalled();\n });\n });\n});\n"]}
|
|
@@ -255,7 +255,7 @@ function initializeAgent(config, options) {
|
|
|
255
255
|
(0, debug_1.logToFile)('Configured LLM gateway:', gatewayUrl);
|
|
256
256
|
// Configure MCP server with PostHog authentication
|
|
257
257
|
const mcpServers = {
|
|
258
|
-
posthog: {
|
|
258
|
+
'posthog-wizard': {
|
|
259
259
|
type: 'http',
|
|
260
260
|
url: config.posthogMcpUrl,
|
|
261
261
|
headers: {
|
|
@@ -436,7 +436,9 @@ async function runAgent(agentConfig, prompt, options, spinner, config) {
|
|
|
436
436
|
});
|
|
437
437
|
// Process the async generator
|
|
438
438
|
for await (const message of response) {
|
|
439
|
-
handleSDKMessage
|
|
439
|
+
// Pass receivedSuccessResult so handleSDKMessage can suppress user-facing error
|
|
440
|
+
// output for post-success cleanup errors while still logging them to file
|
|
441
|
+
handleSDKMessage(message, options, spinner, collectedText, receivedSuccessResult);
|
|
440
442
|
// Signal completion when result received
|
|
441
443
|
if (message.type === 'result') {
|
|
442
444
|
// Track successful results before any potential cleanup errors
|
|
@@ -509,8 +511,12 @@ async function runAgent(agentConfig, prompt, options, spinner, config) {
|
|
|
509
511
|
}
|
|
510
512
|
/**
|
|
511
513
|
* Handle SDK messages and provide user feedback
|
|
514
|
+
*
|
|
515
|
+
* @param receivedSuccessResult - If true, suppress user-facing error output for cleanup errors
|
|
516
|
+
* while still logging to file. The SDK may emit a second error
|
|
517
|
+
* result after success due to cleanup race conditions.
|
|
512
518
|
*/
|
|
513
|
-
function handleSDKMessage(message, options, spinner, collectedText) {
|
|
519
|
+
function handleSDKMessage(message, options, spinner, collectedText, receivedSuccessResult = false) {
|
|
514
520
|
(0, debug_1.logToFile)(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));
|
|
515
521
|
if (options.debug) {
|
|
516
522
|
(0, debug_1.debug)(`SDK Message type: ${message.type}`);
|
|
@@ -542,7 +548,10 @@ function handleSDKMessage(message, options, spinner, collectedText) {
|
|
|
542
548
|
if (typeof message.result === 'string') {
|
|
543
549
|
collectedText.push(message.result);
|
|
544
550
|
}
|
|
545
|
-
if
|
|
551
|
+
// Only show errors to user if we haven't already succeeded.
|
|
552
|
+
// Post-success errors are SDK cleanup noise (telemetry failures, streaming
|
|
553
|
+
// mode race conditions). Full message already logged above via JSON dump.
|
|
554
|
+
if (message.errors && !receivedSuccessResult) {
|
|
546
555
|
for (const err of message.errors) {
|
|
547
556
|
clack_1.default.log.error(`Error: ${err}`);
|
|
548
557
|
(0, debug_1.logToFile)('ERROR:', err);
|
|
@@ -556,9 +565,10 @@ function handleSDKMessage(message, options, spinner, collectedText) {
|
|
|
556
565
|
}
|
|
557
566
|
}
|
|
558
567
|
else {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
568
|
+
(0, debug_1.logToFile)('Agent result with error:', message.result);
|
|
569
|
+
// Error result - only show to user if we haven't already succeeded.
|
|
570
|
+
// Full message already logged above via JSON dump.
|
|
571
|
+
if (message.errors && !receivedSuccessResult) {
|
|
562
572
|
for (const err of message.errors) {
|
|
563
573
|
clack_1.default.log.error(`Error: ${err}`);
|
|
564
574
|
(0, debug_1.logToFile)('ERROR:', err);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AAuLH,4CAqGC;AAKD,0CAiEC;AAQD,4BAwQC;AAhnBD,gDAAwB;AACxB,2DAAmC;AACnC,0CAA8E;AAE9E,kDAA+C;AAC/C,2CAGqB;AACrB,wCAAyD;AACzD,6CAA6C;AAE7C,sCAAsC;AACtC,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,KAAK,UAAU,YAAY;IACzB,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,UAAU,GAAG,MAAM,MAAM,CAAC,gCAAgC,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;GAGG;AACH,SAAS,2BAA2B;IAClC,mFAAmF;IACnF,MAAM,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,gCAAgC,CAAC,CAAC;IACzE,OAAO,cAAI,CAAC,IAAI,CAAC,cAAI,CAAC,OAAO,CAAC,cAAc,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC3D,CAAC;AAOY,QAAA,YAAY,GAAG;IAC1B,iEAAiE;IACjE,MAAM,EAAE,UAAU;IAClB,yEAAyE;IACzE,iBAAiB,EAAE,qBAAqB;IACxC,q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,EAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared agent interface for PostHog wizards\n * Uses Claude Agent SDK directly with PostHog LLM gateway\n */\n\nimport path from 'path';\nimport clack from '../utils/clack';\nimport { debug, logToFile, initLogFile, LOG_FILE_PATH } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_INTERACTION_EVENT_NAME,\n WIZARD_REMARK_EVENT_NAME,\n} from './constants';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\n\n// Dynamic import cache for ESM module\nlet _sdkModule: any = null;\nasync function getSDKModule(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\n/**\n * Get the path to the bundled Claude Code CLI from the SDK package.\n * This ensures we use the SDK's bundled version rather than the user's installed Claude Code.\n */\nfunction getClaudeCodeExecutablePath(): string {\n // require.resolve finds the package's main entry, then we get cli.js from same dir\n const sdkPackagePath = require.resolve('@anthropic-ai/claude-agent-sdk');\n return path.join(path.dirname(sdkPackagePath), 'cli.js');\n}\n\n// Using `any` because typed imports from ESM modules require import attributes\n// syntax which prettier cannot parse. See PR discussion for details.\ntype SDKMessage = any;\ntype McpServersConfig = any;\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 PostHog 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 /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\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 PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n posthogMcpUrl: string;\n posthogApiKey: string;\n posthogApiHost: string;\n};\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n};\n\n/**\n * Package managers that can be used to run commands.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'pipenv',\n 'uv',\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];\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 * Note: `&&` is allowed for specific safe patterns like skill installation.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is a PostHog skill installation from MCP.\n * We control the MCP server, so we only need to verify:\n * 1. It installs to .claude/skills/\n * 2. It downloads from our GitHub releases or localhost (dev)\n */\nfunction isSkillInstallCommand(command: string): boolean {\n if (!command.startsWith('mkdir -p .claude/skills/')) return false;\n\n const urlMatch = command.match(/curl -sL ['\"]([^'\"]+)['\"]/);\n if (!urlMatch) return false;\n\n const url = urlMatch[1];\n return (\n url.startsWith('https://github.com/PostHog/examples/releases/') ||\n /^http:\\/\\/localhost:\\d+\\//.test(url)\n );\n}\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 * - PostHog skill installation commands from MCP\n */\nexport function wizardCanUseTool(\n toolName: string,\n input: Record<string, unknown>,\n):\n | { behavior: 'allow'; updatedInput: Record<string, unknown> }\n | { behavior: 'deny'; message: string } {\n // Allow all non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (\n typeof input.command === 'string' ? input.command : ''\n ).trim();\n\n // Check for PostHog skill installation command (before dangerous operator check)\n // These commands use && chaining but are generated by MCP with a strict format\n if (isSkillInstallCommand(command)) {\n logToFile(`Allowing skill installation command: ${command}`);\n debug(`Allowing skill installation command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logToFile(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(WIZARD_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 logToFile(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(WIZARD_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 logToFile(`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 logToFile(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(WIZARD_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 (package manager commands)\n if (matchesAllowedPrefix(normalized)) {\n logToFile(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logToFile(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(WIZARD_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 function initializeAgent(\n config: AgentConfig,\n options: WizardOptions,\n): AgentRunConfig {\n // Initialize log file for this run\n initLogFile();\n logToFile('Agent initialization starting');\n logToFile('Install directory:', options.installDir);\n\n clack.log.step('Initializing Claude agent...');\n\n try {\n // Configure LLM gateway environment variables (inherited by SDK subprocess)\n const gatewayUrl = getLlmGatewayUrlFromHost(config.posthogApiHost);\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = config.posthogApiKey;\n // Use CLAUDE_CODE_OAUTH_TOKEN to override any stored /login credentials\n process.env.CLAUDE_CODE_OAUTH_TOKEN = config.posthogApiKey;\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = 'true';\n\n logToFile('Configured LLM gateway:', gatewayUrl);\n\n // Configure MCP server with PostHog authentication\n const mcpServers: McpServersConfig = {\n posthog: {\n type: 'http',\n url: config.posthogMcpUrl,\n headers: {\n Authorization: `Bearer ${config.posthogApiKey}`,\n },\n },\n };\n\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers,\n model: 'claude-opus-4-5-20251101',\n };\n\n logToFile('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n\n if (options.debug) {\n debug('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n }\n\n clack.log.step(`Verbose logs: ${LOG_FILE_PATH}`);\n clack.log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n clack.log.error(`Failed to initialize agent: ${(error as Error).message}`);\n logToFile('Agent initialization error:', error);\n debug('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: spinner, execution, error handling\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: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n): Promise<{ error?: AgentErrorType; message?: string }> {\n const {\n estimatedDurationMinutes = 8,\n spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\n\n clack.log.step(\n `This whole process should take about ${estimatedDurationMinutes} minutes including error checking and fixes.\\n\\nGrab some coffee!`,\n );\n\n spinner.start(spinnerMessage);\n\n const cliPath = getClaudeCodeExecutablePath();\n logToFile('Starting agent run');\n logToFile('Claude Code executable:', cliPath);\n logToFile('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n // Track if we received a successful result (before any cleanup errors)\n let receivedSuccessResult = false;\n\n // Workaround for SDK bug: stdin closes before canUseTool responses can be sent.\n // The fix is to use an async generator for the prompt that stays open until\n // the result is received, keeping the stdin stream alive for permission responses.\n // See: https://github.com/anthropics/claude-code/issues/4775\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n let signalDone: () => void;\n const resultReceived = new Promise<void>((resolve) => {\n signalDone = resolve;\n });\n\n const createPromptStream = async function* () {\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n };\n await resultReceived;\n };\n\n // Helper to handle successful completion (used in normal path and race condition recovery)\n const completeWithSuccess = (\n suppressedError?: Error,\n ): { error?: AgentErrorType; message?: string } => {\n const durationMs = Date.now() - startTime;\n const durationSeconds = Math.round(durationMs / 1000);\n\n if (suppressedError) {\n logToFile(\n `Ignoring post-completion error, agent completed successfully in ${durationSeconds}s`,\n );\n logToFile('Suppressed error:', suppressedError.message);\n } else {\n logToFile(`Agent run completed in ${durationSeconds}s`);\n }\n\n // Extract and capture the agent's reflection on the run\n const outputText = collectedText.join('\\n');\n const remarkRegex = new RegExp(\n `${AgentSignals.WIZARD_REMARK.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)(?:\\\\n|$)`,\n 's',\n );\n const remarkMatch = outputText.match(remarkRegex);\n if (remarkMatch && remarkMatch[1]) {\n const remark = remarkMatch[1].trim();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: durationSeconds,\n });\n spinner.stop(successMessage);\n return {};\n };\n\n try {\n // Tools needed for the wizard:\n // - File operations: Read, Write, Edit\n // - Search: Glob, Grep\n // - Commands: Bash (with restrictions via canUseTool)\n // - MCP discovery: ListMcpResourcesTool (to find available skills)\n // - Skills: Skill (to load installed PostHog skills)\n // MCP tools (PostHog) come from mcpServers, not allowedTools\n const allowedTools = [\n 'Read',\n 'Write',\n 'Edit',\n 'Glob',\n 'Grep',\n 'Bash',\n 'ListMcpResourcesTool',\n 'Skill',\n ];\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 // Load skills from project's .claude/skills/ directory\n settingSources: ['project'],\n // Explicitly enable required tools including Skill\n allowedTools,\n env: {\n ...process.env,\n // Prevent user's Anthropic API key from overriding the wizard's OAuth token\n ANTHROPIC_API_KEY: undefined,\n },\n canUseTool: (toolName: string, input: unknown) => {\n logToFile('canUseTool called:', { toolName, input });\n const result = wizardCanUseTool(\n toolName,\n input as Record<string, unknown>,\n );\n logToFile('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logToFile('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n // Stop hook to have the agent reflect on its run\n hooks: {\n Stop: [\n {\n hooks: [\n (input: { stop_hook_active: boolean }) => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n });\n\n // Only ask for reflection on first stop (not after reflection is provided)\n if (input.stop_hook_active) {\n logToFile('Stop hook: allowing stop (already reflected)');\n return {}; // Allow stopping\n }\n\n logToFile('Stop hook: requesting reflection');\n return {\n decision: 'block',\n reason: `Before concluding, provide a brief remark about what information or guidance would have been useful to have in the integration prompt or documentation for this run. Specifically cite anything that would have prevented tool failures, erroneous edits, or other wasted turns. Format your response exactly as: ${AgentSignals.WIZARD_REMARK} Your remark here`,\n };\n },\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Process the async generator\n for await (const message of response) {\n handleSDKMessage(message, options, spinner, collectedText);\n // Signal completion when result received\n if (message.type === 'result') {\n // Track successful results before any potential cleanup errors\n // The SDK may emit a second error result during cleanup due to a race condition\n if (message.subtype === 'success' && !message.is_error) {\n receivedSuccessResult = true;\n }\n signalDone!();\n }\n }\n\n const outputText = collectedText.join('\\n');\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logToFile('Agent error: MCP_MISSING');\n spinner.stop('Agent could not access PostHog MCP');\n return { error: AgentErrorType.MCP_MISSING };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logToFile('Agent error: RESOURCE_MISSING');\n spinner.stop('Agent could not access setup resource');\n return { error: AgentErrorType.RESOURCE_MISSING };\n }\n\n // Check for API errors (rate limits, etc.)\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error: RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: outputText };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error: API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: outputText };\n }\n\n return completeWithSuccess();\n } catch (error) {\n // Signal done to unblock the async generator\n signalDone!();\n\n // If we already received a successful result, the error is from SDK cleanup\n // This happens due to a race condition: the SDK tries to send a cleanup command\n // after the prompt stream closes, but streaming mode is still active.\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n if (receivedSuccessResult) {\n return completeWithSuccess(error as Error);\n }\n\n // Check if we collected an API error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error (caught): RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error (caught): API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n // No API error found, re-throw the original exception\n spinner.stop(errorMessage);\n clack.log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n }\n}\n\n/**\n * Handle SDK messages and provide user feedback\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n collectedText: string[],\n): void {\n logToFile(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n if (options.debug) {\n debug(`SDK Message type: ${message.type}`);\n }\n\n switch (message.type) {\n case 'assistant': {\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 // Check for [STATUS] markers\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n spinner.stop(statusMatch[1].trim());\n spinner.start('Integrating PostHog...');\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // Check is_error flag - can be true even when subtype is 'success'\n if (message.is_error) {\n logToFile('Agent result with error:', message.result);\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n if (message.errors) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n } else if (message.subtype === 'success') {\n logToFile('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n // Error result\n logToFile('Agent error result:', message.subtype);\n if (message.errors) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logToFile('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}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-interface.js","sourceRoot":"","sources":["../../../src/lib/agent-interface.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;;;;AAuLH,4CAqGC;AAKD,0CAiEC;AAQD,4BAiRC;AAznBD,gDAAwB;AACxB,2DAAmC;AACnC,0CAA8E;AAE9E,kDAA+C;AAC/C,2CAGqB;AACrB,wCAAyD;AACzD,6CAA6C;AAE7C,sCAAsC;AACtC,IAAI,UAAU,GAAQ,IAAI,CAAC;AAC3B,KA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AAC,MAAM,IAAI,CAAC,qBAAqB,EAAE,CAAC;oBAC7C,KAAK,MAAM,GAAG,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;wBACjC,eAAK,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC;wBACjC,IAAA,iBAAS,EAAC,QAAQ,EAAE,GAAG,CAAC,CAAC;oBAC3B,CAAC;gBACH,CAAC;YACH,CAAC;YACD,MAAM;QACR,CAAC;QAED,KAAK,QAAQ,CAAC,CAAC,CAAC;YACd,IAAI,OAAO,CAAC,OAAO,KAAK,MAAM,EAAE,CAAC;gBAC/B,IAAA,iBAAS,EAAC,2BAA2B,EAAE;oBACrC,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,IAAA,aAAK,EAAC,2BAA2B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;YACnD,CAAC;YACD,MAAM;IACV,CAAC;AACH,CAAC","sourcesContent":["/**\n * Shared agent interface for PostHog wizards\n * Uses Claude Agent SDK directly with PostHog LLM gateway\n */\n\nimport path from 'path';\nimport clack from '../utils/clack';\nimport { debug, logToFile, initLogFile, LOG_FILE_PATH } from '../utils/debug';\nimport type { WizardOptions } from '../utils/types';\nimport { analytics } from '../utils/analytics';\nimport {\n WIZARD_INTERACTION_EVENT_NAME,\n WIZARD_REMARK_EVENT_NAME,\n} from './constants';\nimport { getLlmGatewayUrlFromHost } from '../utils/urls';\nimport { LINTING_TOOLS } from './safe-tools';\n\n// Dynamic import cache for ESM module\nlet _sdkModule: any = null;\nasync function getSDKModule(): Promise<any> {\n if (!_sdkModule) {\n _sdkModule = await import('@anthropic-ai/claude-agent-sdk');\n }\n return _sdkModule;\n}\n\n/**\n * Get the path to the bundled Claude Code CLI from the SDK package.\n * This ensures we use the SDK's bundled version rather than the user's installed Claude Code.\n */\nfunction getClaudeCodeExecutablePath(): string {\n // require.resolve finds the package's main entry, then we get cli.js from same dir\n const sdkPackagePath = require.resolve('@anthropic-ai/claude-agent-sdk');\n return path.join(path.dirname(sdkPackagePath), 'cli.js');\n}\n\n// Using `any` because typed imports from ESM modules require import attributes\n// syntax which prettier cannot parse. See PR discussion for details.\ntype SDKMessage = any;\ntype McpServersConfig = any;\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 PostHog 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 /** Signal emitted when the agent provides a remark about its run */\n WIZARD_REMARK: '[WIZARD-REMARK]',\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 PostHog MCP server */\n MCP_MISSING = 'WIZARD_MCP_MISSING',\n /** Agent could not access the setup resource */\n RESOURCE_MISSING = 'WIZARD_RESOURCE_MISSING',\n /** API rate limit exceeded */\n RATE_LIMIT = 'WIZARD_RATE_LIMIT',\n /** Generic API error */\n API_ERROR = 'WIZARD_API_ERROR',\n}\n\nexport type AgentConfig = {\n workingDirectory: string;\n posthogMcpUrl: string;\n posthogApiKey: string;\n posthogApiHost: string;\n};\n\n/**\n * Internal configuration object returned by initializeAgent\n */\ntype AgentRunConfig = {\n workingDirectory: string;\n mcpServers: McpServersConfig;\n model: string;\n};\n\n/**\n * Package managers that can be used to run commands.\n */\nconst PACKAGE_MANAGERS = [\n // JavaScript\n 'npm',\n 'pnpm',\n 'yarn',\n 'bun',\n 'npx',\n // Python\n 'pip',\n 'pip3',\n 'poetry',\n 'pipenv',\n 'uv',\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];\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 * Note: `&&` is allowed for specific safe patterns like skill installation.\n */\nconst DANGEROUS_OPERATORS = /[;`$()]/;\n\n/**\n * Check if command is a PostHog skill installation from MCP.\n * We control the MCP server, so we only need to verify:\n * 1. It installs to .claude/skills/\n * 2. It downloads from our GitHub releases or localhost (dev)\n */\nfunction isSkillInstallCommand(command: string): boolean {\n if (!command.startsWith('mkdir -p .claude/skills/')) return false;\n\n const urlMatch = command.match(/curl -sL ['\"]([^'\"]+)['\"]/);\n if (!urlMatch) return false;\n\n const url = urlMatch[1];\n return (\n url.startsWith('https://github.com/PostHog/examples/releases/') ||\n /^http:\\/\\/localhost:\\d+\\//.test(url)\n );\n}\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 * - PostHog skill installation commands from MCP\n */\nexport function wizardCanUseTool(\n toolName: string,\n input: Record<string, unknown>,\n):\n | { behavior: 'allow'; updatedInput: Record<string, unknown> }\n | { behavior: 'deny'; message: string } {\n // Allow all non-Bash tools\n if (toolName !== 'Bash') {\n return { behavior: 'allow', updatedInput: input };\n }\n\n const command = (\n typeof input.command === 'string' ? input.command : ''\n ).trim();\n\n // Check for PostHog skill installation command (before dangerous operator check)\n // These commands use && chaining but are generated by MCP with a strict format\n if (isSkillInstallCommand(command)) {\n logToFile(`Allowing skill installation command: ${command}`);\n debug(`Allowing skill installation command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n // Block definitely dangerous operators: ; ` $ ( )\n if (DANGEROUS_OPERATORS.test(command)) {\n logToFile(`Denying bash command with dangerous operators: ${command}`);\n debug(`Denying bash command with dangerous operators: ${command}`);\n analytics.capture(WIZARD_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 logToFile(`Denying bash command with multiple pipes: ${command}`);\n debug(`Denying bash command with multiple pipes: ${command}`);\n analytics.capture(WIZARD_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 logToFile(`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 logToFile(`Denying bash command with pipe/&: ${command}`);\n debug(`Denying bash command with pipe/&: ${command}`);\n analytics.capture(WIZARD_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 (package manager commands)\n if (matchesAllowedPrefix(normalized)) {\n logToFile(`Allowing bash command: ${command}`);\n debug(`Allowing bash command: ${command}`);\n return { behavior: 'allow', updatedInput: input };\n }\n\n logToFile(`Denying bash command: ${command}`);\n debug(`Denying bash command: ${command}`);\n analytics.capture(WIZARD_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 function initializeAgent(\n config: AgentConfig,\n options: WizardOptions,\n): AgentRunConfig {\n // Initialize log file for this run\n initLogFile();\n logToFile('Agent initialization starting');\n logToFile('Install directory:', options.installDir);\n\n clack.log.step('Initializing Claude agent...');\n\n try {\n // Configure LLM gateway environment variables (inherited by SDK subprocess)\n const gatewayUrl = getLlmGatewayUrlFromHost(config.posthogApiHost);\n process.env.ANTHROPIC_BASE_URL = gatewayUrl;\n process.env.ANTHROPIC_AUTH_TOKEN = config.posthogApiKey;\n // Use CLAUDE_CODE_OAUTH_TOKEN to override any stored /login credentials\n process.env.CLAUDE_CODE_OAUTH_TOKEN = config.posthogApiKey;\n // Disable experimental betas (like input_examples) that the LLM gateway doesn't support\n process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS = 'true';\n\n logToFile('Configured LLM gateway:', gatewayUrl);\n\n // Configure MCP server with PostHog authentication\n const mcpServers: McpServersConfig = {\n 'posthog-wizard': {\n type: 'http',\n url: config.posthogMcpUrl,\n headers: {\n Authorization: `Bearer ${config.posthogApiKey}`,\n },\n },\n };\n\n const agentRunConfig: AgentRunConfig = {\n workingDirectory: config.workingDirectory,\n mcpServers,\n model: 'claude-opus-4-5-20251101',\n };\n\n logToFile('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n\n if (options.debug) {\n debug('Agent config:', {\n workingDirectory: agentRunConfig.workingDirectory,\n posthogMcpUrl: config.posthogMcpUrl,\n gatewayUrl,\n apiKeyPresent: !!config.posthogApiKey,\n });\n }\n\n clack.log.step(`Verbose logs: ${LOG_FILE_PATH}`);\n clack.log.success(\"Agent initialized. Let's get cooking!\");\n return agentRunConfig;\n } catch (error) {\n clack.log.error(`Failed to initialize agent: ${(error as Error).message}`);\n logToFile('Agent initialization error:', error);\n debug('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: spinner, execution, error handling\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: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n config?: {\n estimatedDurationMinutes?: number;\n spinnerMessage?: string;\n successMessage?: string;\n errorMessage?: string;\n },\n): Promise<{ error?: AgentErrorType; message?: string }> {\n const {\n estimatedDurationMinutes = 8,\n spinnerMessage = 'Customizing your PostHog setup...',\n successMessage = 'PostHog integration complete',\n errorMessage = 'Integration failed',\n } = config ?? {};\n\n const { query } = await getSDKModule();\n\n clack.log.step(\n `This whole process should take about ${estimatedDurationMinutes} minutes including error checking and fixes.\\n\\nGrab some coffee!`,\n );\n\n spinner.start(spinnerMessage);\n\n const cliPath = getClaudeCodeExecutablePath();\n logToFile('Starting agent run');\n logToFile('Claude Code executable:', cliPath);\n logToFile('Prompt:', prompt);\n\n const startTime = Date.now();\n const collectedText: string[] = [];\n // Track if we received a successful result (before any cleanup errors)\n let receivedSuccessResult = false;\n\n // Workaround for SDK bug: stdin closes before canUseTool responses can be sent.\n // The fix is to use an async generator for the prompt that stays open until\n // the result is received, keeping the stdin stream alive for permission responses.\n // See: https://github.com/anthropics/claude-code/issues/4775\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n let signalDone: () => void;\n const resultReceived = new Promise<void>((resolve) => {\n signalDone = resolve;\n });\n\n const createPromptStream = async function* () {\n yield {\n type: 'user',\n session_id: '',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n };\n await resultReceived;\n };\n\n // Helper to handle successful completion (used in normal path and race condition recovery)\n const completeWithSuccess = (\n suppressedError?: Error,\n ): { error?: AgentErrorType; message?: string } => {\n const durationMs = Date.now() - startTime;\n const durationSeconds = Math.round(durationMs / 1000);\n\n if (suppressedError) {\n logToFile(\n `Ignoring post-completion error, agent completed successfully in ${durationSeconds}s`,\n );\n logToFile('Suppressed error:', suppressedError.message);\n } else {\n logToFile(`Agent run completed in ${durationSeconds}s`);\n }\n\n // Extract and capture the agent's reflection on the run\n const outputText = collectedText.join('\\n');\n const remarkRegex = new RegExp(\n `${AgentSignals.WIZARD_REMARK.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)(?:\\\\n|$)`,\n 's',\n );\n const remarkMatch = outputText.match(remarkRegex);\n if (remarkMatch && remarkMatch[1]) {\n const remark = remarkMatch[1].trim();\n if (remark) {\n analytics.capture(WIZARD_REMARK_EVENT_NAME, { remark });\n }\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'agent integration completed',\n duration_ms: durationMs,\n duration_seconds: durationSeconds,\n });\n spinner.stop(successMessage);\n return {};\n };\n\n try {\n // Tools needed for the wizard:\n // - File operations: Read, Write, Edit\n // - Search: Glob, Grep\n // - Commands: Bash (with restrictions via canUseTool)\n // - MCP discovery: ListMcpResourcesTool (to find available skills)\n // - Skills: Skill (to load installed PostHog skills)\n // MCP tools (PostHog) come from mcpServers, not allowedTools\n const allowedTools = [\n 'Read',\n 'Write',\n 'Edit',\n 'Glob',\n 'Grep',\n 'Bash',\n 'ListMcpResourcesTool',\n 'Skill',\n ];\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 // Load skills from project's .claude/skills/ directory\n settingSources: ['project'],\n // Explicitly enable required tools including Skill\n allowedTools,\n env: {\n ...process.env,\n // Prevent user's Anthropic API key from overriding the wizard's OAuth token\n ANTHROPIC_API_KEY: undefined,\n },\n canUseTool: (toolName: string, input: unknown) => {\n logToFile('canUseTool called:', { toolName, input });\n const result = wizardCanUseTool(\n toolName,\n input as Record<string, unknown>,\n );\n logToFile('canUseTool result:', result);\n return Promise.resolve(result);\n },\n tools: { type: 'preset', preset: 'claude_code' },\n // Capture stderr from CLI subprocess for debugging\n stderr: (data: string) => {\n logToFile('CLI stderr:', data);\n if (options.debug) {\n debug('CLI stderr:', data);\n }\n },\n // Stop hook to have the agent reflect on its run\n hooks: {\n Stop: [\n {\n hooks: [\n (input: { stop_hook_active: boolean }) => {\n logToFile('Stop hook triggered', {\n stop_hook_active: input.stop_hook_active,\n });\n\n // Only ask for reflection on first stop (not after reflection is provided)\n if (input.stop_hook_active) {\n logToFile('Stop hook: allowing stop (already reflected)');\n return {}; // Allow stopping\n }\n\n logToFile('Stop hook: requesting reflection');\n return {\n decision: 'block',\n reason: `Before concluding, provide a brief remark about what information or guidance would have been useful to have in the integration prompt or documentation for this run. Specifically cite anything that would have prevented tool failures, erroneous edits, or other wasted turns. Format your response exactly as: ${AgentSignals.WIZARD_REMARK} Your remark here`,\n };\n },\n ],\n timeout: 30,\n },\n ],\n },\n },\n });\n\n // Process the async generator\n for await (const message of response) {\n // Pass receivedSuccessResult so handleSDKMessage can suppress user-facing error\n // output for post-success cleanup errors while still logging them to file\n handleSDKMessage(\n message,\n options,\n spinner,\n collectedText,\n receivedSuccessResult,\n );\n\n // Signal completion when result received\n if (message.type === 'result') {\n // Track successful results before any potential cleanup errors\n // The SDK may emit a second error result during cleanup due to a race condition\n if (message.subtype === 'success' && !message.is_error) {\n receivedSuccessResult = true;\n }\n signalDone!();\n }\n }\n\n const outputText = collectedText.join('\\n');\n\n // Check for error markers in the agent's output\n if (outputText.includes(AgentSignals.ERROR_MCP_MISSING)) {\n logToFile('Agent error: MCP_MISSING');\n spinner.stop('Agent could not access PostHog MCP');\n return { error: AgentErrorType.MCP_MISSING };\n }\n\n if (outputText.includes(AgentSignals.ERROR_RESOURCE_MISSING)) {\n logToFile('Agent error: RESOURCE_MISSING');\n spinner.stop('Agent could not access setup resource');\n return { error: AgentErrorType.RESOURCE_MISSING };\n }\n\n // Check for API errors (rate limits, etc.)\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error: RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: outputText };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error: API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: outputText };\n }\n\n return completeWithSuccess();\n } catch (error) {\n // Signal done to unblock the async generator\n signalDone!();\n\n // If we already received a successful result, the error is from SDK cleanup\n // This happens due to a race condition: the SDK tries to send a cleanup command\n // after the prompt stream closes, but streaming mode is still active.\n // See: https://github.com/anthropics/claude-agent-sdk-typescript/issues/41\n if (receivedSuccessResult) {\n return completeWithSuccess(error as Error);\n }\n\n // Check if we collected an API error before the exception was thrown\n const outputText = collectedText.join('\\n');\n\n // Extract just the API error line(s), not the entire output\n const apiErrorMatch = outputText.match(/API Error: [^\\n]+/g);\n const apiErrorMessage = apiErrorMatch\n ? apiErrorMatch.join('\\n')\n : 'Unknown API error';\n\n if (outputText.includes('API Error: 429')) {\n logToFile('Agent error (caught): RATE_LIMIT');\n spinner.stop('Rate limit exceeded');\n return { error: AgentErrorType.RATE_LIMIT, message: apiErrorMessage };\n }\n\n if (outputText.includes('API Error:')) {\n logToFile('Agent error (caught): API_ERROR');\n spinner.stop('API error occurred');\n return { error: AgentErrorType.API_ERROR, message: apiErrorMessage };\n }\n\n // No API error found, re-throw the original exception\n spinner.stop(errorMessage);\n clack.log.error(`Error: ${(error as Error).message}`);\n logToFile('Agent run failed:', error);\n debug('Full error:', error);\n throw error;\n }\n}\n\n/**\n * Handle SDK messages and provide user feedback\n *\n * @param receivedSuccessResult - If true, suppress user-facing error output for cleanup errors\n * while still logging to file. The SDK may emit a second error\n * result after success due to cleanup race conditions.\n */\nfunction handleSDKMessage(\n message: SDKMessage,\n options: WizardOptions,\n spinner: ReturnType<typeof clack.spinner>,\n collectedText: string[],\n receivedSuccessResult = false,\n): void {\n logToFile(`SDK Message: ${message.type}`, JSON.stringify(message, null, 2));\n\n if (options.debug) {\n debug(`SDK Message type: ${message.type}`);\n }\n\n switch (message.type) {\n case 'assistant': {\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 // Check for [STATUS] markers\n const statusRegex = new RegExp(\n `^.*${AgentSignals.STATUS.replace(\n /[.*+?^${}()|[\\]\\\\]/g,\n '\\\\$&',\n )}\\\\s*(.+?)$`,\n 'm',\n );\n const statusMatch = block.text.match(statusRegex);\n if (statusMatch) {\n spinner.stop(statusMatch[1].trim());\n spinner.start('Integrating PostHog...');\n }\n }\n }\n }\n break;\n }\n\n case 'result': {\n // Check is_error flag - can be true even when subtype is 'success'\n if (message.is_error) {\n logToFile('Agent result with error:', message.result);\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n // Only show errors to user if we haven't already succeeded.\n // Post-success errors are SDK cleanup noise (telemetry failures, streaming\n // mode race conditions). Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n } else if (message.subtype === 'success') {\n logToFile('Agent completed successfully');\n if (typeof message.result === 'string') {\n collectedText.push(message.result);\n }\n } else {\n logToFile('Agent result with error:', message.result);\n // Error result - only show to user if we haven't already succeeded.\n // Full message already logged above via JSON dump.\n if (message.errors && !receivedSuccessResult) {\n for (const err of message.errors) {\n clack.log.error(`Error: ${err}`);\n logToFile('ERROR:', err);\n }\n }\n }\n break;\n }\n\n case 'system': {\n if (message.subtype === 'init') {\n logToFile('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}\n"]}
|
|
@@ -232,9 +232,10 @@ Project context:
|
|
|
232
232
|
|
|
233
233
|
Instructions (follow these steps IN ORDER - do not skip or reorder):
|
|
234
234
|
|
|
235
|
-
STEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool.
|
|
235
|
+
STEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool. If this tool is not available or you cannot access the MCP server, you must emit: ${agent_interface_1.AgentSignals.ERROR_MCP_MISSING} Could not access the PostHog MCP server and halt.
|
|
236
|
+
|
|
236
237
|
Review the skill descriptions and choose the one that best matches this project's framework and configuration.
|
|
237
|
-
If no suitable skill is found, or you cannot access the MCP server, emit: ${agent_interface_1.AgentSignals.ERROR_RESOURCE_MISSING} Could not find a suitable skill for this project.
|
|
238
|
+
If no suitable skill is found, or you cannot access the MCP server, you emit: ${agent_interface_1.AgentSignals.ERROR_RESOURCE_MISSING} Could not find a suitable skill for this project.
|
|
238
239
|
|
|
239
240
|
STEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).
|
|
240
241
|
The resource returns a shell command to install the skill.
|
|
@@ -249,7 +250,7 @@ STEP 5: Follow the skill's workflow files in sequence. Look for numbered workflo
|
|
|
249
250
|
|
|
250
251
|
STEP 6: Set up environment variables for PostHog in a .env file with the API key and host provided above, using the appropriate naming convention for ${config.metadata.name}. Make sure to use these environment variables in the code files you create instead of hardcoding the API key and host.
|
|
251
252
|
|
|
252
|
-
Important: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager. Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.
|
|
253
|
+
Important: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.
|
|
253
254
|
|
|
254
255
|
`;
|
|
255
256
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib/agent-runner.ts"],"names":[],"mappings":";;;;;AAsCA,wCA6QC;AAnTD,yDAI4B;AAE5B,sDAU8B;AAC9B,kDAA+C;AAC/C,2CAA4D;AAC5D,2DAAmC;AACnC,uDAK2B;AAC3B,wCAAsD;AACtD,kDAA0B;AAC1B,oCAGkB;AAClB,gEAA2E;AAE3E;;;GAGG;AACI,KAAK,UAAU,cAAc,CAClC,MAAuB,EACvB,OAAsB;IAEtB,cAAc;IACd,IAAA,0BAAY,EAAC,EAAE,UAAU,EAAE,IAAA,oCAAiB,EAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAEtE,eAAK,CAAC,GAAG,CAAC,IA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,CAAC,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE;EACxE,eAAK,CAAC,GAAG,CACT,yGAAyG,CAC1G;;EAEC,eAAK,CAAC,GAAG,CAAC,+DAA+D,CAAC,EAAE,CAAC;IAE7E,eAAK,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAE1B,MAAM,qBAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACtC,CAAC;AAED;;;GAGG;AACH,SAAS,sBAAsB,CAC7B,MAAuB,EACvB,OAKC,EACD,gBAAqC;IAErC,MAAM,eAAe,GAAG,MAAM,CAAC,OAAO,CAAC,yBAAyB;QAC9D,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,yBAAyB,CAAC,gBAAgB,CAAC;QAC5D,CAAC,CAAC,EAAE,CAAC;IAEP,MAAM,iBAAiB,GACrB,eAAe,CAAC,MAAM,GAAG,CAAC;QACxB,CAAC,CAAC,IAAI,GAAG,eAAe,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC;QAC9D,CAAC,CAAC,EAAE,CAAC;IAET,OAAO,kGACL,MAAM,CAAC,QAAQ,CAAC,IAClB;;;eAGa,MAAM,CAAC,QAAQ,CAAC,IAAI,IAAI,OAAO,CAAC,gBAAgB;gBAC/C,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;qBAC5B,OAAO,CAAC,aAAa;kBACxB,OAAO,CAAC,IAAI,GAAG,iBAAiB;;;;;;+EAO7C,8BAAY,CAAC,sBACf;;;;;;;;;;;;;wJAcC,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;CAID,CAAC;AACF,CAAC","sourcesContent":["import {\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_INTERACTION_EVENT_NAME } from './constants';\nimport clack from '../utils/clack';\nimport {\n initializeAgent,\n runAgent,\n AgentSignals,\n AgentErrorType,\n} from './agent-interface';\nimport { getCloudUrlFromRegion } from '../utils/urls';\nimport chalk from 'chalk';\nimport {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\n\n/**\n * Universal agent-powered wizard runner.\n * Handles the complete flow for any framework using PostHog MCP integration.\n */\nexport async function runAgentWizard(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<void> {\n // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n clack.log.info(\n `π§ The wizard has chosen you to try the next-generation agent integration for ${config.metadata.name}.\\n\\nStand by for the good stuff, and let the robot minders know how it goes:\\n\\nwizard@posthog.com`,\n );\n\n const aiConsent = await askForAIConsent(options);\n if (!aiConsent) {\n await abort(\n `This wizard uses an LLM agent to intelligently modify your project. Please view the docs to set up ${config.metadata.name} manually instead: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n // Check Anthropic/Claude service status before proceeding\n const statusOk = await checkAnthropicStatusWithPrompt({ ci: options.ci });\n if (!statusOk) {\n await abort(\n `Please try again later, or set up ${config.metadata.name} manually: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n // Framework detection and version\n // Only check package.json for Node.js/JavaScript frameworks\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let packageJson: any = null;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n packageJson = await getPackageDotJson(options);\n await ensurePackageIsInstalled(\n packageJson,\n config.detection.packageName,\n config.detection.packageDisplayName,\n );\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n // For non-Node frameworks (e.g., Django), version is handled differently\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Set analytics tags for framework version\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'started agent integration',\n integration: config.metadata.integration,\n });\n\n // Get PostHog credentials\n const { projectApiKey, host, accessToken } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Gather framework-specific context (e.g., Next.js router, React Native platform)\n const frameworkContext = config.metadata.gatherContext\n ? await config.metadata.gatherContext(options)\n : {};\n\n // Set analytics tags from framework context\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n // Build integration prompt\n const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n },\n frameworkContext,\n );\n\n // Initialize and run agent\n const spinner = clack.spinner();\n\n // Determine MCP URL: CLI flag > env var > production default\n // Use EU subdomain for EU users to work around Claude Code's OAuth bug\n // See: https://github.com/anthropics/claude-code/issues/2267\n const mcpUrl = options.localMcp\n ? 'http://localhost:8787/mcp'\n : process.env.MCP_URL ||\n (cloudRegion === 'eu'\n ? 'https://mcp-eu.posthog.com/mcp'\n : 'https://mcp.posthog.com/mcp');\n\n const agent = initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\n },\n options,\n );\n\n const agentResult = await runAgent(\n agent,\n integrationPrompt,\n options,\n spinner,\n {\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n errorMessage: 'Integration failed',\n },\n );\n\n // Handle error cases detected in agent output\n if (agentResult.error === AgentErrorType.MCP_MISSING) {\n analytics.captureException(\n new Error('Agent could not access PostHog MCP server'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.MCP_MISSING,\n signal: AgentSignals.ERROR_MCP_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('β Could not access the PostHog MCP server')}\n\nThe wizard was unable to connect to the PostHog MCP server.\nThis could be due to a network issue or a configuration problem.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (agentResult.error === AgentErrorType.RESOURCE_MISSING) {\n analytics.captureException(\n new Error('Agent could not access setup resource'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.RESOURCE_MISSING,\n signal: AgentSignals.ERROR_RESOURCE_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('β Could not access the setup resource')}\n\nThe wizard could not access the setup resource. This may indicate a version mismatch or a temporary service issue.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (\n agentResult.error === AgentErrorType.RATE_LIMIT ||\n agentResult.error === AgentErrorType.API_ERROR\n ) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'api error',\n integration: config.metadata.integration,\n error_type: agentResult.error,\n error_message: agentResult.message,\n });\n\n analytics.captureException(new Error(`API error: ${agentResult.message}`), {\n integration: config.metadata.integration,\n error_type: agentResult.error,\n });\n\n const errorMessage = `\n${chalk.red('β API Error')}\n\n${chalk.yellow(agentResult.message || 'Unknown error')}\n\nPlease report this error to: ${chalk.cyan('wizard@posthog.com')}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n // Build environment variables from OAuth credentials\n const envVars = config.environment.getEnvVars(projectApiKey, host);\n\n // Upload environment variables to hosting providers (if configured)\n let uploadedEnvVars: string[] = [];\n if (config.environment.uploadToHosting) {\n uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {\n integration: config.metadata.integration,\n options,\n });\n }\n\n // Add MCP server to clients\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: config.metadata.integration,\n ci: options.ci,\n });\n\n // Build outro message\n const continueUrl = options.signup\n ? `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`\n : undefined;\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? `Added environment variables to .env file`\n : '',\n uploadedEnvVars.length > 0\n ? `Uploaded environment variables to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const nextSteps = [\n ...config.ui.getOutroNextSteps(frameworkContext),\n uploadedEnvVars.length === 0 && config.environment.uploadToHosting\n ? `Upload your Project API key to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const outroMessage = `\n${chalk.green('Successfully installed PostHog!')}\n\n${chalk.cyan('What the agent did:')}\n${changes.map((change) => `β’ ${change}`).join('\\n')}\n\n${chalk.yellow('Next steps:')}\n${nextSteps.map((step) => `β’ ${step}`).join('\\n')}\n\nLearn more: ${chalk.cyan(config.metadata.docsUrl)}\n${continueUrl ? `\\nContinue onboarding: ${chalk.cyan(continueUrl)}\\n` : ``}\n${chalk.dim(\n 'Note: This wizard uses an LLM agent to analyze and modify your project. Please review the changes made.',\n)}\n\n${chalk.dim(`How did this work for you? Drop us a line: wizard@posthog.com`)}`;\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n\n/**\n * Build the integration prompt for the agent.\n * Uses shared base prompt with optional framework-specific addendum.\n */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n },\n frameworkContext: Record<string, any>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool.\n Review the skill descriptions and choose the one that best matches this project's framework and configuration.\n If no suitable skill is found, or you cannot access the MCP server, emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.\n\nSTEP 6: Set up environment variables for PostHog in a .env file with the API key and host provided above, using the appropriate naming convention for ${\n config.metadata.name\n }. Make sure to use these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager. Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.\n\n`;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"agent-runner.js","sourceRoot":"","sources":["../../../src/lib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,CAAC,QAAQ,CAAC,IAAI,IAAI,OAAO,CAAC,gBAAgB;gBAC/C,OAAO,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;qBAC5B,OAAO,CAAC,aAAa;kBACxB,OAAO,CAAC,IAAI,GAAG,iBAAiB;;;;0KAK9C,8BAAY,CAAC,iBACf;;;mFAIG,8BAAY,CAAC,sBACf;;;;;;;;;;;;;wJAcC,MAAM,CAAC,QAAQ,CAAC,IAClB;;;;CAID,CAAC;AACF,CAAC","sourcesContent":["import {\n getWelcomeMessage,\n SPINNER_MESSAGE,\n type FrameworkConfig,\n} from './framework-config';\nimport type { WizardOptions } from '../utils/types';\nimport {\n abort,\n askForAIConsent,\n confirmContinueIfNoOrDirtyGitRepo,\n ensurePackageIsInstalled,\n getOrAskForProjectData,\n getPackageDotJson,\n isUsingTypeScript,\n printWelcome,\n askForCloudRegion,\n} from '../utils/clack-utils';\nimport { analytics } from '../utils/analytics';\nimport { WIZARD_INTERACTION_EVENT_NAME } from './constants';\nimport clack from '../utils/clack';\nimport {\n initializeAgent,\n runAgent,\n AgentSignals,\n AgentErrorType,\n} from './agent-interface';\nimport { getCloudUrlFromRegion } from '../utils/urls';\nimport chalk from 'chalk';\nimport {\n addMCPServerToClientsStep,\n uploadEnvironmentVariablesStep,\n} from '../steps';\nimport { checkAnthropicStatusWithPrompt } from '../utils/anthropic-status';\n\n/**\n * Universal agent-powered wizard runner.\n * Handles the complete flow for any framework using PostHog MCP integration.\n */\nexport async function runAgentWizard(\n config: FrameworkConfig,\n options: WizardOptions,\n): Promise<void> {\n // Setup phase\n printWelcome({ wizardName: getWelcomeMessage(config.metadata.name) });\n\n clack.log.info(\n `π§ The wizard has chosen you to try the next-generation agent integration for ${config.metadata.name}.\\n\\nStand by for the good stuff, and let the robot minders know how it goes:\\n\\nwizard@posthog.com`,\n );\n\n const aiConsent = await askForAIConsent(options);\n if (!aiConsent) {\n await abort(\n `This wizard uses an LLM agent to intelligently modify your project. Please view the docs to set up ${config.metadata.name} manually instead: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n // Check Anthropic/Claude service status before proceeding\n const statusOk = await checkAnthropicStatusWithPrompt({ ci: options.ci });\n if (!statusOk) {\n await abort(\n `Please try again later, or set up ${config.metadata.name} manually: ${config.metadata.docsUrl}`,\n 0,\n );\n }\n\n const cloudRegion = options.cloudRegion ?? (await askForCloudRegion());\n const typeScriptDetected = isUsingTypeScript(options);\n\n await confirmContinueIfNoOrDirtyGitRepo(options);\n\n // Framework detection and version\n // Only check package.json for Node.js/JavaScript frameworks\n const usesPackageJson = config.detection.usesPackageJson !== false;\n let packageJson: any = null;\n let frameworkVersion: string | undefined;\n\n if (usesPackageJson) {\n packageJson = await getPackageDotJson(options);\n await ensurePackageIsInstalled(\n packageJson,\n config.detection.packageName,\n config.detection.packageDisplayName,\n );\n frameworkVersion = config.detection.getVersion(packageJson);\n } else {\n // For non-Node frameworks (e.g., Django), version is handled differently\n frameworkVersion = config.detection.getVersion(null);\n }\n\n // Set analytics tags for framework version\n if (frameworkVersion && config.detection.getVersionBucket) {\n const versionBucket = config.detection.getVersionBucket(frameworkVersion);\n analytics.setTag(`${config.metadata.integration}-version`, versionBucket);\n }\n\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'started agent integration',\n integration: config.metadata.integration,\n });\n\n // Get PostHog credentials\n const { projectApiKey, host, accessToken } = await getOrAskForProjectData({\n ...options,\n cloudRegion,\n });\n\n // Gather framework-specific context (e.g., Next.js router, React Native platform)\n const frameworkContext = config.metadata.gatherContext\n ? await config.metadata.gatherContext(options)\n : {};\n\n // Set analytics tags from framework context\n const contextTags = config.analytics.getTags(frameworkContext);\n Object.entries(contextTags).forEach(([key, value]) => {\n analytics.setTag(key, value);\n });\n\n // Build integration prompt\n const integrationPrompt = buildIntegrationPrompt(\n config,\n {\n frameworkVersion: frameworkVersion || 'latest',\n typescript: typeScriptDetected,\n projectApiKey,\n host,\n },\n frameworkContext,\n );\n\n // Initialize and run agent\n const spinner = clack.spinner();\n\n // Determine MCP URL: CLI flag > env var > production default\n // Use EU subdomain for EU users to work around Claude Code's OAuth bug\n // See: https://github.com/anthropics/claude-code/issues/2267\n const mcpUrl = options.localMcp\n ? 'http://localhost:8787/mcp'\n : process.env.MCP_URL ||\n (cloudRegion === 'eu'\n ? 'https://mcp-eu.posthog.com/mcp'\n : 'https://mcp.posthog.com/mcp');\n\n const agent = initializeAgent(\n {\n workingDirectory: options.installDir,\n posthogMcpUrl: mcpUrl,\n posthogApiKey: accessToken,\n posthogApiHost: host,\n },\n options,\n );\n\n const agentResult = await runAgent(\n agent,\n integrationPrompt,\n options,\n spinner,\n {\n estimatedDurationMinutes: config.ui.estimatedDurationMinutes,\n spinnerMessage: SPINNER_MESSAGE,\n successMessage: config.ui.successMessage,\n errorMessage: 'Integration failed',\n },\n );\n\n // Handle error cases detected in agent output\n if (agentResult.error === AgentErrorType.MCP_MISSING) {\n analytics.captureException(\n new Error('Agent could not access PostHog MCP server'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.MCP_MISSING,\n signal: AgentSignals.ERROR_MCP_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('β Could not access the PostHog MCP server')}\n\nThe wizard was unable to connect to the PostHog MCP server.\nThis could be due to a network issue or a configuration problem.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (agentResult.error === AgentErrorType.RESOURCE_MISSING) {\n analytics.captureException(\n new Error('Agent could not access setup resource'),\n {\n integration: config.metadata.integration,\n error_type: AgentErrorType.RESOURCE_MISSING,\n signal: AgentSignals.ERROR_RESOURCE_MISSING,\n },\n );\n\n const errorMessage = `\n${chalk.red('β Could not access the setup resource')}\n\nThe wizard could not access the setup resource. This may indicate a version mismatch or a temporary service issue.\n\nPlease try again, or set up ${\n config.metadata.name\n } manually by following our documentation:\n${chalk.cyan(config.metadata.docsUrl)}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n if (\n agentResult.error === AgentErrorType.RATE_LIMIT ||\n agentResult.error === AgentErrorType.API_ERROR\n ) {\n analytics.capture(WIZARD_INTERACTION_EVENT_NAME, {\n action: 'api error',\n integration: config.metadata.integration,\n error_type: agentResult.error,\n error_message: agentResult.message,\n });\n\n analytics.captureException(new Error(`API error: ${agentResult.message}`), {\n integration: config.metadata.integration,\n error_type: agentResult.error,\n });\n\n const errorMessage = `\n${chalk.red('β API Error')}\n\n${chalk.yellow(agentResult.message || 'Unknown error')}\n\nPlease report this error to: ${chalk.cyan('wizard@posthog.com')}`;\n\n clack.outro(errorMessage);\n await analytics.shutdown('error');\n process.exit(1);\n }\n\n // Build environment variables from OAuth credentials\n const envVars = config.environment.getEnvVars(projectApiKey, host);\n\n // Upload environment variables to hosting providers (if configured)\n let uploadedEnvVars: string[] = [];\n if (config.environment.uploadToHosting) {\n uploadedEnvVars = await uploadEnvironmentVariablesStep(envVars, {\n integration: config.metadata.integration,\n options,\n });\n }\n\n // Add MCP server to clients\n await addMCPServerToClientsStep({\n cloudRegion,\n integration: config.metadata.integration,\n ci: options.ci,\n });\n\n // Build outro message\n const continueUrl = options.signup\n ? `${getCloudUrlFromRegion(cloudRegion)}/products?source=wizard`\n : undefined;\n\n const changes = [\n ...config.ui.getOutroChanges(frameworkContext),\n Object.keys(envVars).length > 0\n ? `Added environment variables to .env file`\n : '',\n uploadedEnvVars.length > 0\n ? `Uploaded environment variables to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const nextSteps = [\n ...config.ui.getOutroNextSteps(frameworkContext),\n uploadedEnvVars.length === 0 && config.environment.uploadToHosting\n ? `Upload your Project API key to your hosting provider`\n : '',\n ].filter(Boolean);\n\n const outroMessage = `\n${chalk.green('Successfully installed PostHog!')}\n\n${chalk.cyan('What the agent did:')}\n${changes.map((change) => `β’ ${change}`).join('\\n')}\n\n${chalk.yellow('Next steps:')}\n${nextSteps.map((step) => `β’ ${step}`).join('\\n')}\n\nLearn more: ${chalk.cyan(config.metadata.docsUrl)}\n${continueUrl ? `\\nContinue onboarding: ${chalk.cyan(continueUrl)}\\n` : ``}\n${chalk.dim(\n 'Note: This wizard uses an LLM agent to analyze and modify your project. Please review the changes made.',\n)}\n\n${chalk.dim(`How did this work for you? Drop us a line: wizard@posthog.com`)}`;\n\n clack.outro(outroMessage);\n\n await analytics.shutdown('success');\n}\n\n/**\n * Build the integration prompt for the agent.\n * Uses shared base prompt with optional framework-specific addendum.\n */\nfunction buildIntegrationPrompt(\n config: FrameworkConfig,\n context: {\n frameworkVersion: string;\n typescript: boolean;\n projectApiKey: string;\n host: string;\n },\n frameworkContext: Record<string, any>,\n): string {\n const additionalLines = config.prompts.getAdditionalContextLines\n ? config.prompts.getAdditionalContextLines(frameworkContext)\n : [];\n\n const additionalContext =\n additionalLines.length > 0\n ? '\\n' + additionalLines.map((line) => `- ${line}`).join('\\n')\n : '';\n\n return `You have access to the PostHog MCP server which provides skills to integrate PostHog into this ${\n config.metadata.name\n } project.\n\nProject context:\n- Framework: ${config.metadata.name} ${context.frameworkVersion}\n- TypeScript: ${context.typescript ? 'Yes' : 'No'}\n- PostHog API Key: ${context.projectApiKey}\n- PostHog Host: ${context.host}${additionalContext}\n\nInstructions (follow these steps IN ORDER - do not skip or reorder):\n\nSTEP 1: List available skills from the PostHog MCP server using ListMcpResourcesTool. If this tool is not available or you cannot access the MCP server, you must emit: ${\n AgentSignals.ERROR_MCP_MISSING\n } Could not access the PostHog MCP server and halt.\n\n Review the skill descriptions and choose the one that best matches this project's framework and configuration.\n If no suitable skill is found, or you cannot access the MCP server, you emit: ${\n AgentSignals.ERROR_RESOURCE_MISSING\n } Could not find a suitable skill for this project.\n\nSTEP 2: Fetch the chosen skill resource (e.g., posthog://skills/{skill-id}).\n The resource returns a shell command to install the skill.\n\nSTEP 3: Run the installation command using Bash:\n - Execute the EXACT command returned by the resource (do not modify it)\n - This will download and extract the skill to .claude/skills/{skill-id}/\n\nSTEP 4: Load the installed skill's SKILL.md file to understand what references are available.\n\nSTEP 5: Follow the skill's workflow files in sequence. Look for numbered workflow files in the references (e.g., files with patterns like \"1.0-\", \"1.1-\", \"1.2-\"). Start with the first one and proceed through each step until completion. Each workflow file will tell you what to do and which file comes next.\n\nSTEP 6: Set up environment variables for PostHog in a .env file with the API key and host provided above, using the appropriate naming convention for ${\n config.metadata.name\n }. Make sure to use these environment variables in the code files you create instead of hardcoding the API key and host.\n\nImportant: Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager (excluding the contents of node_modules). Do not manually edit package.json. Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation. You must read a file immediately before attempting to write it, even if you have previously read it; failure to do so will cause a tool failure.\n\n`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clack-utils.js","sourceRoot":"","sources":["../../../src/utils/clack-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6DA,sBAKC;AAED,4CAyBC;AAED,oCAaC;AAED,8EAwDC;AAED,kCASC;AAED,wEAmBC;AAED,kDAmBC;AAED,kGAkDC;AAED,gDAmBC;AAQD,wCAgHC;AAYD,4DAuBC;AAED,8CA4BC;AAMD,8CAYC;AAED,oDAmBC;AAED,8CAiDC;AAED,8CAQC;AASD,wDA2DC;AAgGD,oDAkCC;AAwBD,8DAwBC;AAgCD,0CASC;AAmBD,kDA+BC;AAED,wDA+BC;AAED,0DAUC;AAED,kEAaC;AAED,0CA8BC;AAED,8CAsBC;AAtgCD,iEAAmD;AACnD,4CAA8B;AAC9B,4CAA8B;AAC9B,yCAAiE;AAEjE,kDAA0B;AAC1B,4CAAyC;AACzC,mCAAgC;AAChC,iDAA0E;AAC1E,uDAK2B;AAC3B,qCAAgD;AAEhD,iDAAmD;AACnD,gDAK0B;AAC1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,CAAC;AACL,CAAC","sourcesContent":["import * as childProcess from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { basename, isAbsolute, join, relative } from 'node:path';\n\nimport chalk from 'chalk';\nimport { traceStep } from '../telemetry';\nimport { debug } from './debug';\nimport { type PackageDotJson, hasPackageInstalled } from './package-json';\nimport {\n type PackageManager,\n detectAllPackageManagers,\n packageManagers,\n NPM as npm,\n} from './package-manager';\nimport { fulfillsVersionRange } from './semver';\nimport type { CloudRegion, Feature, WizardOptions } from './types';\nimport { getPackageVersion } from './package-json';\nimport {\n DEFAULT_HOST_URL,\n DUMMY_PROJECT_API_KEY,\n ISSUES_URL,\n type Integration,\n} from '../lib/constants';\nimport { analytics } from './analytics';\nimport clack from './clack';\nimport { getCloudUrlFromRegion, getHostFromRegion } from './urls';\nimport { INTEGRATION_CONFIG } from '../lib/config';\nimport { performOAuthFlow } from './oauth';\nimport { fetchUserData, fetchProjectData } from '../lib/api';\n\ninterface ProjectData {\n projectApiKey: string;\n accessToken: string;\n host: string;\n distinctId: string;\n projectId: number;\n}\n\nexport interface CliSetupConfig {\n filename: string;\n name: string;\n gitignore: boolean;\n\n likelyAlreadyHasAuthToken(contents: string): boolean;\n tokenContent(authToken: string): string;\n\n likelyAlreadyHasOrgAndProject(contents: string): boolean;\n orgAndProjContent(org: string, project: string): string;\n\n likelyAlreadyHasUrl?(contents: string): boolean;\n urlContent?(url: string): string;\n}\n\nexport interface CliSetupConfigContent {\n authToken: string;\n org?: string;\n project?: string;\n url?: string;\n}\n\nexport async function abort(message?: string, status?: number): Promise<never> {\n await analytics.shutdown('cancelled');\n\n clack.outro(message ?? 'Wizard setup cancelled.');\n return process.exit(status ?? 1);\n}\n\nexport async function abortIfCancelled<T>(\n input: T | Promise<T>,\n integration?: Integration,\n): Promise<Exclude<T, symbol>> {\n await analytics.shutdown('cancelled');\n const resolvedInput = await input;\n\n if (\n clack.isCancel(resolvedInput) ||\n (typeof resolvedInput === 'symbol' &&\n resolvedInput.description === 'clack:cancel')\n ) {\n const docsUrl = integration\n ? INTEGRATION_CONFIG[integration].docsUrl\n : 'https://posthog.com/docs';\n\n clack.cancel(\n `Wizard setup cancelled. You can read the documentation for ${\n integration ?? 'PostHog'\n } at ${chalk.cyan(docsUrl)} to continue with the setup manually.`,\n );\n process.exit(0);\n } else {\n return input as Exclude<T, symbol>;\n }\n}\n\nexport function printWelcome(options: {\n wizardName: string;\n message?: string;\n}): void {\n // eslint-disable-next-line no-console\n console.log('');\n clack.intro(chalk.inverse(` ${options.wizardName} `));\n\n const welcomeText =\n options.message ||\n `The ${options.wizardName} will help you set up PostHog for your application.\\nThank you for using PostHog :)`;\n\n clack.note(welcomeText);\n}\n\nexport async function confirmContinueIfNoOrDirtyGitRepo(\n options: Pick<WizardOptions, 'default' | 'ci'>,\n): Promise<void> {\n return traceStep('check-git-status', async () => {\n if (!isInGitRepo()) {\n // CI mode: auto-continue without git\n const continueWithoutGit =\n options.default || options.ci\n ? true\n : await abortIfCancelled(\n clack.confirm({\n message:\n 'You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?',\n }),\n );\n\n analytics.setTag('continue-without-git', continueWithoutGit);\n\n if (!continueWithoutGit) {\n await abort(undefined, 0);\n }\n // return early to avoid checking for uncommitted files\n return;\n }\n\n const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();\n if (uncommittedOrUntrackedFiles.length) {\n // CI mode: auto-continue with dirty repo\n if (options.ci) {\n clack.log.info(\n `CI mode: continuing with uncommitted/untracked files in repo`,\n );\n analytics.setTag('continue-with-dirty-repo', true);\n return;\n }\n\n clack.log.warn(\n `You have uncommitted or untracked files in your repo:\n\n${uncommittedOrUntrackedFiles.join('\\n')}\n\nThe wizard will create and update files.`,\n );\n const continueWithDirtyRepo = await abortIfCancelled(\n clack.confirm({\n message: 'Do you want to continue anyway?',\n }),\n );\n\n analytics.setTag('continue-with-dirty-repo', continueWithDirtyRepo);\n\n if (!continueWithDirtyRepo) {\n await abort(undefined, 0);\n }\n }\n });\n}\n\nexport function isInGitRepo() {\n try {\n childProcess.execSync('git rev-parse --is-inside-work-tree', {\n stdio: 'ignore',\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function getUncommittedOrUntrackedFiles(): string[] {\n try {\n const gitStatus = childProcess\n .execSync('git status --porcelain=v1', {\n // we only care about stdout\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .toString();\n\n const files = gitStatus\n .split(os.EOL)\n .map((line) => line.trim())\n .filter(Boolean)\n .map((f) => `- ${f.split(/\\s+/)[1]}`);\n\n return files;\n } catch {\n return [];\n }\n}\n\nexport async function askForItemSelection(\n items: string[],\n message: string,\n): Promise<{ value: string; index: number }> {\n const selection: { value: string; index: number } | symbol =\n await abortIfCancelled(\n clack.select({\n maxItems: 12,\n message: message,\n options: items.map((item, index) => {\n return {\n value: { value: item, index: index },\n label: item,\n };\n }),\n }),\n );\n\n return selection;\n}\n\nexport async function confirmContinueIfPackageVersionNotSupported({\n packageId,\n packageName,\n packageVersion,\n acceptableVersions,\n note,\n}: {\n packageId: string;\n packageName: string;\n packageVersion: string;\n acceptableVersions: string;\n note?: string;\n}): Promise<void> {\n return traceStep(`check-package-version`, async () => {\n analytics.setTag(`${packageName.toLowerCase()}-version`, packageVersion);\n const isSupportedVersion = fulfillsVersionRange({\n acceptableVersions,\n version: packageVersion,\n canBeLatest: true,\n });\n\n if (isSupportedVersion) {\n analytics.setTag(`${packageName.toLowerCase()}-supported`, true);\n return;\n }\n\n clack.log.warn(\n `You have an unsupported version of ${packageName} installed:\n\n ${packageId}@${packageVersion}`,\n );\n\n clack.note(\n note ??\n `Please upgrade to ${acceptableVersions} if you wish to use the PostHog wizard.`,\n );\n const continueWithUnsupportedVersion = await abortIfCancelled(\n clack.confirm({\n message: 'Do you want to continue anyway?',\n }),\n );\n analytics.setTag(\n `${packageName.toLowerCase()}-continue-with-unsupported-version`,\n continueWithUnsupportedVersion,\n );\n\n if (!continueWithUnsupportedVersion) {\n await abort(undefined, 0);\n }\n });\n}\n\nexport async function isReact19Installed({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<boolean> {\n try {\n const packageJson = await getPackageDotJson({ installDir });\n const reactVersion = getPackageVersion('react', packageJson);\n\n if (!reactVersion) {\n return false;\n }\n\n return fulfillsVersionRange({\n version: reactVersion,\n acceptableVersions: '>=19.0.0',\n canBeLatest: true,\n });\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Installs or updates a package with the user's package manager.\n *\n * IMPORTANT: This function modifies the `package.json`! Be sure to re-read\n * it if you make additional modifications to it after calling this function!\n */\nexport async function installPackage({\n packageName,\n alreadyInstalled,\n askBeforeUpdating = true,\n packageNameDisplayLabel,\n packageManager,\n forceInstall = false,\n integration,\n installDir,\n}: {\n /** The string that is passed to the package manager CLI as identifier to install (e.g. `posthog-js`, or `posthog-js@^1.100.0`) */\n packageName: string;\n alreadyInstalled: boolean;\n askBeforeUpdating?: boolean;\n /** Overrides what is shown in the installation logs in place of the `packageName` option. Useful if the `packageName` is ugly */\n packageNameDisplayLabel?: string;\n packageManager?: PackageManager;\n /** Add force install flag to command to skip install precondition fails */\n forceInstall?: boolean;\n /** The integration that is being used */\n integration?: string;\n /** The directory to install the package in */\n installDir: string;\n}): Promise<{ packageManager?: PackageManager }> {\n return traceStep('install-package', async () => {\n if (alreadyInstalled && askBeforeUpdating) {\n const shouldUpdatePackage = await abortIfCancelled(\n clack.confirm({\n message: `The ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} package is already installed. Do you want to update it to the latest version?`,\n }),\n );\n\n if (!shouldUpdatePackage) {\n return {};\n }\n }\n\n const sdkInstallSpinner = clack.spinner();\n\n const pkgManager =\n packageManager || (await getPackageManager({ installDir }));\n\n // Most packages aren't compatible with React 19 yet, skip strict peer dependency checks if needed.\n const isReact19 = await isReact19Installed({ installDir });\n const legacyPeerDepsFlag =\n isReact19 && pkgManager.name === 'npm' ? '--legacy-peer-deps' : '';\n\n sdkInstallSpinner.start(\n `${alreadyInstalled ? 'Updating' : 'Installing'} ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} with ${chalk.bold(pkgManager.label)}.`,\n );\n\n try {\n await new Promise<void>((resolve, reject) => {\n childProcess.exec(\n `${pkgManager.installCommand} ${packageName} ${pkgManager.flags} ${\n forceInstall ? pkgManager.forceInstallFlag : ''\n } ${legacyPeerDepsFlag}`.trim(),\n { cwd: installDir },\n (err, stdout, stderr) => {\n if (err) {\n // Write a log file so we can better troubleshoot issues\n fs.writeFileSync(\n join(\n process.cwd(),\n `posthog-wizard-installation-error-${Date.now()}.log`,\n ),\n JSON.stringify({\n stdout,\n stderr,\n }),\n { encoding: 'utf8' },\n );\n\n reject(err);\n } else {\n resolve();\n }\n },\n );\n });\n } catch (e) {\n sdkInstallSpinner.stop('Installation failed.');\n clack.log.error(\n `${chalk.red(\n 'Encountered the following error during installation:',\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n )}\\n\\n${e}\\n\\n${chalk.dim(\n `The wizard has created a \\`posthog-wizard-installation-error-*.log\\` file. If you think this issue is caused by the PostHog wizard, create an issue on GitHub and include the log file's content:\\n${ISSUES_URL}`,\n )}`,\n );\n await abort();\n }\n\n sdkInstallSpinner.stop(\n `${alreadyInstalled ? 'Updated' : 'Installed'} ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} with ${chalk.bold(pkgManager.label)}.`,\n );\n\n analytics.capture('wizard interaction', {\n action: 'package installed',\n package_name: packageName,\n package_manager: pkgManager.name,\n integration,\n });\n\n return { packageManager: pkgManager };\n });\n}\n\n/**\n * Checks if @param packageId is listed as a dependency in @param packageJson.\n * If not, it will ask users if they want to continue without the package.\n *\n * Use this function to check if e.g. a the framework of the SDK is installed\n *\n * @param packageJson the package.json object\n * @param packageId the npm name of the package\n * @param packageName a human readable name of the package\n */\nexport async function ensurePackageIsInstalled(\n packageJson: PackageDotJson,\n packageId: string,\n packageName: string,\n): Promise<void> {\n return traceStep('ensure-package-installed', async () => {\n const installed = hasPackageInstalled(packageId, packageJson);\n\n analytics.setTag(`${packageName.toLowerCase()}-installed`, installed);\n\n if (!installed) {\n const continueWithoutPackage = await abortIfCancelled(\n clack.confirm({\n message: `${packageName} does not seem to be installed. Do you still want to continue?`,\n initialValue: false,\n }),\n );\n\n if (!continueWithoutPackage) {\n await abort(undefined, 0);\n }\n }\n });\n}\n\nexport async function getPackageDotJson({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<PackageDotJson> {\n const packageJsonFileContents = await fs.promises\n .readFile(join(installDir, 'package.json'), 'utf8')\n .catch(() => {\n clack.log.error(\n 'Could not find package.json. Make sure to run the wizard in the root of your app!',\n );\n return abort();\n });\n\n let packageJson: PackageDotJson | undefined = undefined;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n packageJson = JSON.parse(packageJsonFileContents);\n } catch {\n clack.log.error(\n `Unable to parse your ${chalk.cyan(\n 'package.json',\n )}. Make sure it has a valid format!`,\n );\n\n await abort();\n }\n\n return packageJson || {};\n}\n\n/**\n * Try to get package.json, returning null if it doesn't exist.\n * Use this for detection purposes where missing package.json is expected (e.g., Python projects).\n */\nexport async function tryGetPackageJson({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<PackageDotJson | null> {\n try {\n const packageJsonFileContents = await fs.promises.readFile(\n join(installDir, 'package.json'),\n 'utf8',\n );\n return JSON.parse(packageJsonFileContents) as PackageDotJson;\n } catch {\n return null;\n }\n}\n\nexport async function updatePackageDotJson(\n packageDotJson: PackageDotJson,\n { installDir }: Pick<WizardOptions, 'installDir'>,\n): Promise<void> {\n try {\n await fs.promises.writeFile(\n join(installDir, 'package.json'),\n // TODO: maybe figure out the original indentation\n JSON.stringify(packageDotJson, null, 2),\n {\n encoding: 'utf8',\n flag: 'w',\n },\n );\n } catch {\n clack.log.error(`Unable to update your ${chalk.cyan('package.json')}.`);\n\n await abort();\n }\n}\n\nexport async function getPackageManager(\n options: Pick<WizardOptions, 'installDir'> & { ci?: boolean },\n): Promise<PackageManager> {\n const detectedPackageManagers = detectAllPackageManagers({\n installDir: options.installDir,\n });\n\n // If exactly one package manager detected, use it automatically\n if (detectedPackageManagers.length === 1) {\n const detectedPackageManager = detectedPackageManagers[0];\n analytics.setTag('package-manager', detectedPackageManager.name);\n return detectedPackageManager;\n }\n\n // CI mode: auto-select first detected or npm\n if (options.ci) {\n const selectedPackageManager =\n detectedPackageManagers.length > 0 ? detectedPackageManagers[0] : npm;\n clack.log.info(\n `CI mode: auto-selected package manager: ${selectedPackageManager.label}`,\n );\n analytics.setTag('package-manager', selectedPackageManager.name);\n return selectedPackageManager;\n }\n\n // If multiple or no package managers detected, prompt user to select\n const pkgOptions =\n detectedPackageManagers.length > 0\n ? detectedPackageManagers\n : packageManagers;\n\n const message =\n detectedPackageManagers.length > 1\n ? 'Multiple package managers detected. Please select one:'\n : 'Please select your package manager.';\n\n const selectedPackageManager: PackageManager | symbol =\n await abortIfCancelled(\n clack.select({\n message,\n options: pkgOptions.map((packageManager) => ({\n value: packageManager,\n label: packageManager.label,\n })),\n }),\n );\n\n analytics.setTag('package-manager', selectedPackageManager.name);\n return selectedPackageManager;\n}\n\nexport function isUsingTypeScript({\n installDir,\n}: Pick<WizardOptions, 'installDir'>) {\n try {\n return fs.existsSync(join(installDir, 'tsconfig.json'));\n } catch {\n return false;\n }\n}\n\n/**\n *\n * Use this function to get project data for the wizard.\n *\n * @param options wizard options\n * @returns project data (token, url)\n */\nexport async function getOrAskForProjectData(\n _options: Pick<WizardOptions, 'signup' | 'ci' | 'apiKey'> & {\n cloudRegion: CloudRegion;\n },\n): Promise<{\n host: string;\n projectApiKey: string;\n accessToken: string;\n projectId: number;\n}> {\n const cloudUrl = getCloudUrlFromRegion(_options.cloudRegion);\n\n // CI mode: bypass OAuth, use personal API key for LLM gateway\n if (_options.ci && _options.apiKey) {\n const host = getHostFromRegion(_options.cloudRegion);\n clack.log.info('Using provided API key (CI mode - OAuth bypassed)');\n\n const projectData = await fetchProjectDataWithApiKey(\n _options.apiKey,\n _options.cloudRegion,\n );\n\n return {\n host,\n projectApiKey: projectData.api_token, // Project API key for SDK config\n accessToken: _options.apiKey, // Personal API key for LLM gateway\n projectId: projectData.id,\n };\n }\n\n const { host, projectApiKey, accessToken, projectId } = await traceStep(\n 'login',\n () =>\n askForWizardLogin({\n cloudRegion: _options.cloudRegion,\n signup: _options.signup,\n }),\n );\n\n if (!projectApiKey) {\n clack.log.error(`Didn't receive a project API key. This shouldn't happen :(\n\nPlease let us know if you think this is a bug in the wizard:\n${chalk.cyan(ISSUES_URL)}`);\n\n clack.log\n .info(`In the meantime, we'll add a dummy project API key (${chalk.cyan(\n `\"${DUMMY_PROJECT_API_KEY}\"`,\n )}) for you to replace later.\nYou can find your Project API key here:\n${chalk.cyan(`${cloudUrl}/settings/project#variables`)}`);\n }\n\n return {\n accessToken,\n host: host || DEFAULT_HOST_URL,\n projectApiKey: projectApiKey || DUMMY_PROJECT_API_KEY,\n projectId,\n };\n}\n\n/**\n * Fetch project data using a personal API key (for CI mode)\n */\nasync function fetchProjectDataWithApiKey(\n apiKey: string,\n region: CloudRegion,\n): Promise<{ api_token: string; id: number }> {\n const cloudUrl = getCloudUrlFromRegion(region);\n const userData = await fetchUserData(apiKey, cloudUrl);\n const projectId = userData.team?.id;\n\n if (!projectId) {\n throw new Error(\n 'Could not determine project ID from API key. Please ensure your API key has access to a project in this cloud region.',\n );\n }\n\n const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);\n return {\n api_token: projectData.api_token,\n id: projectId,\n };\n}\n\nasync function askForWizardLogin(options: {\n cloudRegion: CloudRegion;\n signup: boolean;\n}): Promise<ProjectData> {\n const tokenResponse = await performOAuthFlow({\n cloudRegion: options.cloudRegion,\n scopes: [\n 'user:read',\n 'project:read',\n 'introspection',\n 'llm_gateway:read',\n 'dashboard:write',\n 'insight:write',\n ],\n signup: options.signup,\n });\n\n const projectId = tokenResponse.scoped_teams?.[0];\n\n if (projectId === undefined) {\n const error = new Error(\n 'No project access granted. Please authorize with project-level access.',\n );\n analytics.captureException(error, {\n step: 'wizard_login',\n has_scoped_teams: !!tokenResponse.scoped_teams,\n });\n clack.log.error(error.message);\n await abort();\n }\n\n const cloudUrl = getCloudUrlFromRegion(options.cloudRegion);\n const host = getHostFromRegion(options.cloudRegion);\n\n const projectData = await fetchProjectData(\n tokenResponse.access_token,\n projectId!,\n cloudUrl,\n );\n const userData = await fetchUserData(tokenResponse.access_token, cloudUrl);\n\n const data: ProjectData = {\n accessToken: tokenResponse.access_token,\n projectApiKey: projectData.api_token,\n host,\n distinctId: userData.distinct_id,\n projectId: projectId!,\n };\n\n clack.log.success(\n `Login complete. ${options.signup ? 'Welcome to PostHog! π' : ''}`,\n );\n analytics.setTag('opened-wizard-link', true);\n analytics.setDistinctId(data.distinctId);\n\n return data;\n}\n\n/**\n * Asks users if they have a config file for @param tool (e.g. Vite).\n * If yes, asks users to specify the path to their config file.\n *\n * Use this helper function as a fallback mechanism if the lookup for\n * a config file with its most usual location/name fails.\n *\n * @param toolName Name of the tool for which we're looking for the config file\n * @param configFileName Name of the most common config file name (e.g. vite.config.js)\n *\n * @returns a user path to the config file or undefined if the user doesn't have a config file\n */\nexport async function askForToolConfigPath(\n toolName: string,\n configFileName: string,\n): Promise<string | undefined> {\n const hasConfig = await abortIfCancelled(\n clack.confirm({\n message: `Do you have a ${toolName} config file (e.g. ${chalk.cyan(\n configFileName,\n )})?`,\n initialValue: true,\n }),\n );\n\n if (!hasConfig) {\n return undefined;\n }\n\n return await abortIfCancelled(\n clack.text({\n message: `Please enter the path to your ${toolName} config file:`,\n placeholder: join('.', configFileName),\n validate: (value) => {\n if (!value) {\n return 'Please enter a path.';\n }\n\n try {\n fs.accessSync(value);\n } catch {\n return 'Could not access the file at this path.';\n }\n },\n }),\n );\n}\n\n/**\n * Prints copy/paste-able instructions to the console.\n * Afterwards asks the user if they added the code snippet to their file.\n *\n * While there's no point in providing a \"no\" answer here, it gives users time to fulfill the\n * task before the wizard continues with additional steps.\n *\n * Use this function if you want to show users instructions on how to add/modify\n * code in their file. This is helpful if automatic insertion failed or is not possible/feasible.\n *\n * @param filename the name of the file to which the code snippet should be applied.\n * If a path is provided, only the filename will be used.\n *\n * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the\n * diff-like format for visually highlighting unchanged or modified lines of code.\n *\n * @param hint (optional) a hint to be printed after the main instruction to add\n * the code from @param codeSnippet to their @param filename.\n *\n * TODO: refactor copy paste instructions across different wizards to use this function.\n * this might require adding a custom message parameter to the function\n */\nexport async function showCopyPasteInstructions(\n filename: string,\n codeSnippet: string,\n hint?: string,\n): Promise<void> {\n clack.log.step(\n `Add the following code to your ${chalk.cyan(basename(filename))} file:${\n hint ? chalk.dim(` (${chalk.dim(hint)})`) : ''\n }`,\n );\n\n // Padding the code snippet to be printed with a \\n at the beginning and end\n // This makes it easier to distinguish the snippet from the rest of the output\n // Intentionally logging directly to console here so that the code can be copied/pasted directly\n // eslint-disable-next-line no-console\n console.log(`\\n${codeSnippet}\\n`);\n\n await abortIfCancelled(\n clack.select({\n message: 'Did you apply the snippet above?',\n options: [{ label: 'Yes, continue!', value: true }],\n initialValue: true,\n }),\n );\n}\n\n/**\n * Callback that exposes formatting helpers for a code snippet.\n * @param unchanged - Formats text as old code.\n * @param plus - Formats text as new code.\n * @param minus - Formats text as removed code.\n */\ntype CodeSnippetFormatter = (\n unchanged: (txt: string) => string,\n plus: (txt: string) => string,\n minus: (txt: string) => string,\n) => string;\n\n/**\n * Crafts a code snippet that can be used to e.g.\n * - print copy/paste instructions to the console\n * - create a new config file.\n *\n * @param colors set this to true if you want the final snippet to be colored.\n * This is useful for printing the snippet to the console as part of copy/paste instructions.\n *\n * @param callback the callback that returns the formatted code snippet.\n * It exposes takes the helper functions for marking code as unchanged, new or removed.\n * These functions no-op if no special formatting should be applied\n * and otherwise apply the appropriate formatting/coloring.\n * (@see {@link CodeSnippetFormatter})\n *\n * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console.\n *\n * @returns a string containing the final, formatted code snippet.\n */\nexport function makeCodeSnippet(\n colors: boolean,\n callback: CodeSnippetFormatter,\n): string {\n const unchanged = (txt: string) => (colors ? chalk.grey(txt) : txt);\n const plus = (txt: string) => (colors ? chalk.greenBright(txt) : txt);\n const minus = (txt: string) => (colors ? chalk.redBright(txt) : txt);\n\n return callback(unchanged, plus, minus);\n}\n\n/**\n * Creates a new config file with the given @param filepath and @param codeSnippet.\n *\n * Use this function to create a new config file for users. This is useful\n * when users answered that they don't yet have a config file for a tool.\n *\n * (This doesn't mean that they don't yet have some other way of configuring\n * their tool but we can leave it up to them to figure out how to merge configs\n * here.)\n *\n * @param filepath absolute path to the new config file\n * @param codeSnippet the snippet to be inserted into the file\n * @param moreInformation (optional) the message to be printed after the file was created\n * For example, this can be a link to more information about configuring the tool.\n *\n * @returns true on success, false otherwise\n */\nexport async function createNewConfigFile(\n filepath: string,\n codeSnippet: string,\n { installDir }: Pick<WizardOptions, 'installDir'>,\n moreInformation?: string,\n): Promise<boolean> {\n if (!isAbsolute(filepath)) {\n debug(`createNewConfigFile: filepath is not absolute: ${filepath}`);\n return false;\n }\n\n const prettyFilename = chalk.cyan(relative(installDir, filepath));\n\n try {\n await fs.promises.writeFile(filepath, codeSnippet);\n\n clack.log.success(`Added new ${prettyFilename} file.`);\n\n if (moreInformation) {\n clack.log.info(chalk.gray(moreInformation));\n }\n\n return true;\n } catch (e) {\n debug(e);\n clack.log.warn(\n `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`,\n );\n }\n\n return false;\n}\n\nexport async function featureSelectionPrompt<F extends ReadonlyArray<Feature>>(\n features: F,\n): Promise<{ [key in F[number]['id']]: boolean }> {\n return traceStep('feature-selection', async () => {\n const selectedFeatures: Record<string, boolean> = {};\n\n for (const feature of features) {\n const selected = await abortIfCancelled(\n clack.select({\n message: feature.prompt,\n initialValue: true,\n options: [\n {\n value: true,\n label: 'Yes',\n hint: feature.enabledHint,\n },\n {\n value: false,\n label: 'No',\n hint: feature.disabledHint,\n },\n ],\n }),\n );\n\n selectedFeatures[feature.id] = selected;\n }\n\n return selectedFeatures as { [key in F[number]['id']]: boolean };\n });\n}\n\nexport async function askShouldInstallPackage(\n pkgName: string,\n): Promise<boolean> {\n return traceStep(`ask-install-package`, () =>\n abortIfCancelled(\n clack.confirm({\n message: `Do you want to install ${chalk.cyan(pkgName)}?`,\n }),\n ),\n );\n}\n\nexport async function askShouldAddPackageOverride(\n pkgName: string,\n pkgVersion: string,\n): Promise<boolean> {\n return traceStep(`ask-add-package-override`, () =>\n abortIfCancelled(\n clack.confirm({\n message: `Do you want to add an override for ${chalk.cyan(\n pkgName,\n )} version ${chalk.cyan(pkgVersion)}?`,\n }),\n ),\n );\n}\n\nexport async function askForAIConsent(\n options: Pick<WizardOptions, 'default' | 'ci'>,\n) {\n return await traceStep('ask-for-ai-consent', async () => {\n // CI mode: auto-consent to AI\n const aiConsent =\n options.default || options.ci\n ? true\n : await abortIfCancelled(\n clack.select({\n message:\n 'This setup wizard uses AI, are you happy to continue? β¨',\n options: [\n {\n label: 'Yes',\n value: true,\n hint: 'We will use AI to help you setup PostHog quickly',\n },\n {\n label: 'No',\n value: false,\n hint: \"I don't like AI\",\n },\n ],\n initialValue: true,\n }),\n );\n\n return aiConsent;\n });\n}\n\nexport async function askForCloudRegion(): Promise<CloudRegion> {\n return await traceStep('ask-for-cloud-region', async () => {\n const cloudRegion: CloudRegion = await abortIfCancelled(\n clack.select({\n message: 'Select your PostHog Cloud region',\n options: [\n {\n label: 'US πΊπΈ',\n value: 'us',\n hint: 'Your data will be stored in the US',\n },\n {\n label: 'EU πͺπΊ',\n value: 'eu',\n hint: 'Your data will be stored in the EU',\n },\n ],\n }),\n );\n\n return cloudRegion;\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"clack-utils.js","sourceRoot":"","sources":["../../../src/utils/clack-utils.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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AAY,EAAE,IAAI;aACnB,CAAC,CACH,CAAC;QAER,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAEM,KAAK,UAAU,iBAAiB;IACrC,OAAO,MAAM,IAAA,qBAAS,EAAC,sBAAsB,EAAE,KAAK,IAAI,EAAE;QACxD,MAAM,WAAW,GAAgB,MAAM,gBAAgB,CACrD,eAAK,CAAC,MAAM,CAAC;YACX,OAAO,EAAE,kCAAkC;YAC3C,OAAO,EAAE;gBACP;oBACE,KAAK,EAAE,SAAS;oBAChB,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,oCAAoC;iBAC3C;gBACD;oBACE,KAAK,EAAE,SAAS;oBAChB,KAAK,EAAE,IAAI;oBACX,IAAI,EAAE,oCAAoC;iBAC3C;aACF;SACF,CAAC,CACH,CAAC;QAEF,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import * as childProcess from 'node:child_process';\nimport * as fs from 'node:fs';\nimport * as os from 'node:os';\nimport { basename, isAbsolute, join, relative } from 'node:path';\n\nimport chalk from 'chalk';\nimport { traceStep } from '../telemetry';\nimport { debug } from './debug';\nimport { type PackageDotJson, hasPackageInstalled } from './package-json';\nimport {\n type PackageManager,\n detectAllPackageManagers,\n packageManagers,\n NPM as npm,\n} from './package-manager';\nimport { fulfillsVersionRange } from './semver';\nimport type { CloudRegion, Feature, WizardOptions } from './types';\nimport { getPackageVersion } from './package-json';\nimport {\n DEFAULT_HOST_URL,\n DUMMY_PROJECT_API_KEY,\n ISSUES_URL,\n type Integration,\n} from '../lib/constants';\nimport { analytics } from './analytics';\nimport clack from './clack';\nimport { getCloudUrlFromRegion, getHostFromRegion } from './urls';\nimport { INTEGRATION_CONFIG } from '../lib/config';\nimport { performOAuthFlow } from './oauth';\nimport { fetchUserData, fetchProjectData } from '../lib/api';\n\ninterface ProjectData {\n projectApiKey: string;\n accessToken: string;\n host: string;\n distinctId: string;\n projectId: number;\n}\n\nexport interface CliSetupConfig {\n filename: string;\n name: string;\n gitignore: boolean;\n\n likelyAlreadyHasAuthToken(contents: string): boolean;\n tokenContent(authToken: string): string;\n\n likelyAlreadyHasOrgAndProject(contents: string): boolean;\n orgAndProjContent(org: string, project: string): string;\n\n likelyAlreadyHasUrl?(contents: string): boolean;\n urlContent?(url: string): string;\n}\n\nexport interface CliSetupConfigContent {\n authToken: string;\n org?: string;\n project?: string;\n url?: string;\n}\n\nexport async function abort(message?: string, status?: number): Promise<never> {\n await analytics.shutdown('cancelled');\n\n clack.outro(message ?? 'Wizard setup cancelled.');\n return process.exit(status ?? 1);\n}\n\nexport async function abortIfCancelled<T>(\n input: T | Promise<T>,\n integration?: Integration,\n): Promise<Exclude<T, symbol>> {\n await analytics.shutdown('cancelled');\n const resolvedInput = await input;\n\n if (\n clack.isCancel(resolvedInput) ||\n (typeof resolvedInput === 'symbol' &&\n resolvedInput.description === 'clack:cancel')\n ) {\n const docsUrl = integration\n ? INTEGRATION_CONFIG[integration].docsUrl\n : 'https://posthog.com/docs';\n\n clack.cancel(\n `Wizard setup cancelled. You can read the documentation for ${\n integration ?? 'PostHog'\n } at ${chalk.cyan(docsUrl)} to continue with the setup manually.`,\n );\n process.exit(0);\n } else {\n return input as Exclude<T, symbol>;\n }\n}\n\nexport function printWelcome(options: {\n wizardName: string;\n message?: string;\n}): void {\n // eslint-disable-next-line no-console\n console.log('');\n clack.intro(chalk.inverse(` ${options.wizardName} `));\n\n const welcomeText =\n options.message ||\n `The ${options.wizardName} will help you set up PostHog for your application.\\nThank you for using PostHog :)`;\n\n clack.note(welcomeText);\n}\n\nexport async function confirmContinueIfNoOrDirtyGitRepo(\n options: Pick<WizardOptions, 'default' | 'ci'>,\n): Promise<void> {\n return traceStep('check-git-status', async () => {\n if (!isInGitRepo()) {\n // CI mode: auto-continue without git\n const continueWithoutGit =\n options.default || options.ci\n ? true\n : await abortIfCancelled(\n clack.confirm({\n message:\n 'You are not inside a git repository. The wizard will create and update files. Do you want to continue anyway?',\n }),\n );\n\n analytics.setTag('continue-without-git', continueWithoutGit);\n\n if (!continueWithoutGit) {\n await abort(undefined, 0);\n }\n // return early to avoid checking for uncommitted files\n return;\n }\n\n const uncommittedOrUntrackedFiles = getUncommittedOrUntrackedFiles();\n if (uncommittedOrUntrackedFiles.length) {\n // CI mode: auto-continue with dirty repo\n if (options.ci) {\n clack.log.info(\n `CI mode: continuing with uncommitted/untracked files in repo`,\n );\n analytics.setTag('continue-with-dirty-repo', true);\n return;\n }\n\n clack.log.warn(\n `You have uncommitted or untracked files in your repo:\n\n${uncommittedOrUntrackedFiles.join('\\n')}\n\nThe wizard will create and update files.`,\n );\n const continueWithDirtyRepo = await abortIfCancelled(\n clack.confirm({\n message: 'Do you want to continue anyway?',\n }),\n );\n\n analytics.setTag('continue-with-dirty-repo', continueWithDirtyRepo);\n\n if (!continueWithDirtyRepo) {\n await abort(undefined, 0);\n }\n }\n });\n}\n\nexport function isInGitRepo() {\n try {\n childProcess.execSync('git rev-parse --is-inside-work-tree', {\n stdio: 'ignore',\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport function getUncommittedOrUntrackedFiles(): string[] {\n try {\n const gitStatus = childProcess\n .execSync('git status --porcelain=v1', {\n // we only care about stdout\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n .toString();\n\n const files = gitStatus\n .split(os.EOL)\n .map((line) => line.trim())\n .filter(Boolean)\n .map((f) => `- ${f.split(/\\s+/)[1]}`);\n\n return files;\n } catch {\n return [];\n }\n}\n\nexport async function askForItemSelection(\n items: string[],\n message: string,\n): Promise<{ value: string; index: number }> {\n const selection: { value: string; index: number } | symbol =\n await abortIfCancelled(\n clack.select({\n maxItems: 12,\n message: message,\n options: items.map((item, index) => {\n return {\n value: { value: item, index: index },\n label: item,\n };\n }),\n }),\n );\n\n return selection;\n}\n\nexport async function confirmContinueIfPackageVersionNotSupported({\n packageId,\n packageName,\n packageVersion,\n acceptableVersions,\n note,\n}: {\n packageId: string;\n packageName: string;\n packageVersion: string;\n acceptableVersions: string;\n note?: string;\n}): Promise<void> {\n return traceStep(`check-package-version`, async () => {\n analytics.setTag(`${packageName.toLowerCase()}-version`, packageVersion);\n const isSupportedVersion = fulfillsVersionRange({\n acceptableVersions,\n version: packageVersion,\n canBeLatest: true,\n });\n\n if (isSupportedVersion) {\n analytics.setTag(`${packageName.toLowerCase()}-supported`, true);\n return;\n }\n\n clack.log.warn(\n `You have an unsupported version of ${packageName} installed:\n\n ${packageId}@${packageVersion}`,\n );\n\n clack.note(\n note ??\n `Please upgrade to ${acceptableVersions} if you wish to use the PostHog wizard.`,\n );\n const continueWithUnsupportedVersion = await abortIfCancelled(\n clack.confirm({\n message: 'Do you want to continue anyway?',\n }),\n );\n analytics.setTag(\n `${packageName.toLowerCase()}-continue-with-unsupported-version`,\n continueWithUnsupportedVersion,\n );\n\n if (!continueWithUnsupportedVersion) {\n await abort(undefined, 0);\n }\n });\n}\n\nexport async function isReact19Installed({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<boolean> {\n try {\n const packageJson = await getPackageDotJson({ installDir });\n const reactVersion = getPackageVersion('react', packageJson);\n\n if (!reactVersion) {\n return false;\n }\n\n return fulfillsVersionRange({\n version: reactVersion,\n acceptableVersions: '>=19.0.0',\n canBeLatest: true,\n });\n } catch (error) {\n return false;\n }\n}\n\n/**\n * Installs or updates a package with the user's package manager.\n *\n * IMPORTANT: This function modifies the `package.json`! Be sure to re-read\n * it if you make additional modifications to it after calling this function!\n */\nexport async function installPackage({\n packageName,\n alreadyInstalled,\n askBeforeUpdating = true,\n packageNameDisplayLabel,\n packageManager,\n forceInstall = false,\n integration,\n installDir,\n}: {\n /** The string that is passed to the package manager CLI as identifier to install (e.g. `posthog-js`, or `posthog-js@^1.100.0`) */\n packageName: string;\n alreadyInstalled: boolean;\n askBeforeUpdating?: boolean;\n /** Overrides what is shown in the installation logs in place of the `packageName` option. Useful if the `packageName` is ugly */\n packageNameDisplayLabel?: string;\n packageManager?: PackageManager;\n /** Add force install flag to command to skip install precondition fails */\n forceInstall?: boolean;\n /** The integration that is being used */\n integration?: string;\n /** The directory to install the package in */\n installDir: string;\n}): Promise<{ packageManager?: PackageManager }> {\n return traceStep('install-package', async () => {\n if (alreadyInstalled && askBeforeUpdating) {\n const shouldUpdatePackage = await abortIfCancelled(\n clack.confirm({\n message: `The ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} package is already installed. Do you want to update it to the latest version?`,\n }),\n );\n\n if (!shouldUpdatePackage) {\n return {};\n }\n }\n\n const sdkInstallSpinner = clack.spinner();\n\n const pkgManager =\n packageManager || (await getPackageManager({ installDir }));\n\n // Most packages aren't compatible with React 19 yet, skip strict peer dependency checks if needed.\n const isReact19 = await isReact19Installed({ installDir });\n const legacyPeerDepsFlag =\n isReact19 && pkgManager.name === 'npm' ? '--legacy-peer-deps' : '';\n\n sdkInstallSpinner.start(\n `${alreadyInstalled ? 'Updating' : 'Installing'} ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} with ${chalk.bold(pkgManager.label)}.`,\n );\n\n try {\n await new Promise<void>((resolve, reject) => {\n childProcess.exec(\n `${pkgManager.installCommand} ${packageName} ${pkgManager.flags} ${\n forceInstall ? pkgManager.forceInstallFlag : ''\n } ${legacyPeerDepsFlag}`.trim(),\n { cwd: installDir },\n (err, stdout, stderr) => {\n if (err) {\n // Write a log file so we can better troubleshoot issues\n fs.writeFileSync(\n join(\n process.cwd(),\n `posthog-wizard-installation-error-${Date.now()}.log`,\n ),\n JSON.stringify({\n stdout,\n stderr,\n }),\n { encoding: 'utf8' },\n );\n\n reject(err);\n } else {\n resolve();\n }\n },\n );\n });\n } catch (e) {\n sdkInstallSpinner.stop('Installation failed.');\n clack.log.error(\n `${chalk.red(\n 'Encountered the following error during installation:',\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n )}\\n\\n${e}\\n\\n${chalk.dim(\n `The wizard has created a \\`posthog-wizard-installation-error-*.log\\` file. If you think this issue is caused by the PostHog wizard, create an issue on GitHub and include the log file's content:\\n${ISSUES_URL}`,\n )}`,\n );\n await abort();\n }\n\n sdkInstallSpinner.stop(\n `${alreadyInstalled ? 'Updated' : 'Installed'} ${chalk.bold.cyan(\n packageNameDisplayLabel ?? packageName,\n )} with ${chalk.bold(pkgManager.label)}.`,\n );\n\n analytics.capture('wizard interaction', {\n action: 'package installed',\n package_name: packageName,\n package_manager: pkgManager.name,\n integration,\n });\n\n return { packageManager: pkgManager };\n });\n}\n\n/**\n * Checks if @param packageId is listed as a dependency in @param packageJson.\n * If not, it will ask users if they want to continue without the package.\n *\n * Use this function to check if e.g. a the framework of the SDK is installed\n *\n * @param packageJson the package.json object\n * @param packageId the npm name of the package\n * @param packageName a human readable name of the package\n */\nexport async function ensurePackageIsInstalled(\n packageJson: PackageDotJson,\n packageId: string,\n packageName: string,\n): Promise<void> {\n return traceStep('ensure-package-installed', async () => {\n const installed = hasPackageInstalled(packageId, packageJson);\n\n analytics.setTag(`${packageName.toLowerCase()}-installed`, installed);\n\n if (!installed) {\n const continueWithoutPackage = await abortIfCancelled(\n clack.confirm({\n message: `${packageName} does not seem to be installed. Do you still want to continue?`,\n initialValue: false,\n }),\n );\n\n if (!continueWithoutPackage) {\n await abort(undefined, 0);\n }\n }\n });\n}\n\nexport async function getPackageDotJson({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<PackageDotJson> {\n const packageJsonFileContents = await fs.promises\n .readFile(join(installDir, 'package.json'), 'utf8')\n .catch(() => {\n clack.log.error(\n 'Could not find package.json. Make sure to run the wizard in the root of your app!',\n );\n return abort();\n });\n\n let packageJson: PackageDotJson | undefined = undefined;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n packageJson = JSON.parse(packageJsonFileContents);\n } catch {\n clack.log.error(\n `Unable to parse your ${chalk.cyan(\n 'package.json',\n )}. Make sure it has a valid format!`,\n );\n\n await abort();\n }\n\n return packageJson || {};\n}\n\n/**\n * Try to get package.json, returning null if it doesn't exist.\n * Use this for detection purposes where missing package.json is expected (e.g., Python projects).\n */\nexport async function tryGetPackageJson({\n installDir,\n}: Pick<WizardOptions, 'installDir'>): Promise<PackageDotJson | null> {\n try {\n const packageJsonFileContents = await fs.promises.readFile(\n join(installDir, 'package.json'),\n 'utf8',\n );\n return JSON.parse(packageJsonFileContents) as PackageDotJson;\n } catch {\n return null;\n }\n}\n\nexport async function updatePackageDotJson(\n packageDotJson: PackageDotJson,\n { installDir }: Pick<WizardOptions, 'installDir'>,\n): Promise<void> {\n try {\n await fs.promises.writeFile(\n join(installDir, 'package.json'),\n // TODO: maybe figure out the original indentation\n JSON.stringify(packageDotJson, null, 2),\n {\n encoding: 'utf8',\n flag: 'w',\n },\n );\n } catch {\n clack.log.error(`Unable to update your ${chalk.cyan('package.json')}.`);\n\n await abort();\n }\n}\n\nexport async function getPackageManager(\n options: Pick<WizardOptions, 'installDir'> & { ci?: boolean },\n): Promise<PackageManager> {\n const detectedPackageManagers = detectAllPackageManagers({\n installDir: options.installDir,\n });\n\n // If exactly one package manager detected, use it automatically\n if (detectedPackageManagers.length === 1) {\n const detectedPackageManager = detectedPackageManagers[0];\n analytics.setTag('package-manager', detectedPackageManager.name);\n return detectedPackageManager;\n }\n\n // CI mode: auto-select first detected or npm\n if (options.ci) {\n const selectedPackageManager =\n detectedPackageManagers.length > 0 ? detectedPackageManagers[0] : npm;\n clack.log.info(\n `CI mode: auto-selected package manager: ${selectedPackageManager.label}`,\n );\n analytics.setTag('package-manager', selectedPackageManager.name);\n return selectedPackageManager;\n }\n\n // If multiple or no package managers detected, prompt user to select\n const pkgOptions =\n detectedPackageManagers.length > 0\n ? detectedPackageManagers\n : packageManagers;\n\n const message =\n detectedPackageManagers.length > 1\n ? 'Multiple package managers detected. Please select one:'\n : 'Please select your package manager.';\n\n const selectedPackageManager: PackageManager | symbol =\n await abortIfCancelled(\n clack.select({\n message,\n options: pkgOptions.map((packageManager) => ({\n value: packageManager,\n label: packageManager.label,\n })),\n }),\n );\n\n analytics.setTag('package-manager', selectedPackageManager.name);\n return selectedPackageManager;\n}\n\nexport function isUsingTypeScript({\n installDir,\n}: Pick<WizardOptions, 'installDir'>) {\n try {\n return fs.existsSync(join(installDir, 'tsconfig.json'));\n } catch {\n return false;\n }\n}\n\n/**\n *\n * Use this function to get project data for the wizard.\n *\n * @param options wizard options\n * @returns project data (token, url)\n */\nexport async function getOrAskForProjectData(\n _options: Pick<WizardOptions, 'signup' | 'ci' | 'apiKey'> & {\n cloudRegion: CloudRegion;\n },\n): Promise<{\n host: string;\n projectApiKey: string;\n accessToken: string;\n projectId: number;\n}> {\n const cloudUrl = getCloudUrlFromRegion(_options.cloudRegion);\n\n // CI mode: bypass OAuth, use personal API key for LLM gateway\n if (_options.ci && _options.apiKey) {\n const host = getHostFromRegion(_options.cloudRegion);\n clack.log.info('Using provided API key (CI mode - OAuth bypassed)');\n\n const projectData = await fetchProjectDataWithApiKey(\n _options.apiKey,\n _options.cloudRegion,\n );\n\n return {\n host,\n projectApiKey: projectData.api_token, // Project API key for SDK config\n accessToken: _options.apiKey, // Personal API key for LLM gateway\n projectId: projectData.id,\n };\n }\n\n const { host, projectApiKey, accessToken, projectId } = await traceStep(\n 'login',\n () =>\n askForWizardLogin({\n cloudRegion: _options.cloudRegion,\n signup: _options.signup,\n }),\n );\n\n if (!projectApiKey) {\n clack.log.error(`Didn't receive a project API key. This shouldn't happen :(\n\nPlease let us know if you think this is a bug in the wizard:\n${chalk.cyan(ISSUES_URL)}`);\n\n clack.log\n .info(`In the meantime, we'll add a dummy project API key (${chalk.cyan(\n `\"${DUMMY_PROJECT_API_KEY}\"`,\n )}) for you to replace later.\nYou can find your Project API key here:\n${chalk.cyan(`${cloudUrl}/settings/project#variables`)}`);\n }\n\n return {\n accessToken,\n host: host || DEFAULT_HOST_URL,\n projectApiKey: projectApiKey || DUMMY_PROJECT_API_KEY,\n projectId,\n };\n}\n\n/**\n * Fetch project data using a personal API key (for CI mode)\n */\nasync function fetchProjectDataWithApiKey(\n apiKey: string,\n region: CloudRegion,\n): Promise<{ api_token: string; id: number }> {\n const cloudUrl = getCloudUrlFromRegion(region);\n const userData = await fetchUserData(apiKey, cloudUrl);\n const projectId = userData.team?.id;\n\n if (!projectId) {\n throw new Error(\n 'Could not determine project ID from API key. Please ensure your API key has access to a project in this cloud region.',\n );\n }\n\n const projectData = await fetchProjectData(apiKey, projectId, cloudUrl);\n return {\n api_token: projectData.api_token,\n id: projectId,\n };\n}\n\nasync function askForWizardLogin(options: {\n cloudRegion: CloudRegion;\n signup: boolean;\n}): Promise<ProjectData> {\n const tokenResponse = await performOAuthFlow({\n cloudRegion: options.cloudRegion,\n scopes: [\n 'user:read',\n 'project:read',\n 'introspection',\n 'llm_gateway:read',\n 'dashboard:write',\n 'insight:write',\n 'query:read',\n ],\n signup: options.signup,\n });\n\n const projectId = tokenResponse.scoped_teams?.[0];\n\n if (projectId === undefined) {\n const error = new Error(\n 'No project access granted. Please authorize with project-level access.',\n );\n analytics.captureException(error, {\n step: 'wizard_login',\n has_scoped_teams: !!tokenResponse.scoped_teams,\n });\n clack.log.error(error.message);\n await abort();\n }\n\n const cloudUrl = getCloudUrlFromRegion(options.cloudRegion);\n const host = getHostFromRegion(options.cloudRegion);\n\n const projectData = await fetchProjectData(\n tokenResponse.access_token,\n projectId!,\n cloudUrl,\n );\n const userData = await fetchUserData(tokenResponse.access_token, cloudUrl);\n\n const data: ProjectData = {\n accessToken: tokenResponse.access_token,\n projectApiKey: projectData.api_token,\n host,\n distinctId: userData.distinct_id,\n projectId: projectId!,\n };\n\n clack.log.success(\n `Login complete. ${options.signup ? 'Welcome to PostHog! π' : ''}`,\n );\n analytics.setTag('opened-wizard-link', true);\n analytics.setDistinctId(data.distinctId);\n\n return data;\n}\n\n/**\n * Asks users if they have a config file for @param tool (e.g. Vite).\n * If yes, asks users to specify the path to their config file.\n *\n * Use this helper function as a fallback mechanism if the lookup for\n * a config file with its most usual location/name fails.\n *\n * @param toolName Name of the tool for which we're looking for the config file\n * @param configFileName Name of the most common config file name (e.g. vite.config.js)\n *\n * @returns a user path to the config file or undefined if the user doesn't have a config file\n */\nexport async function askForToolConfigPath(\n toolName: string,\n configFileName: string,\n): Promise<string | undefined> {\n const hasConfig = await abortIfCancelled(\n clack.confirm({\n message: `Do you have a ${toolName} config file (e.g. ${chalk.cyan(\n configFileName,\n )})?`,\n initialValue: true,\n }),\n );\n\n if (!hasConfig) {\n return undefined;\n }\n\n return await abortIfCancelled(\n clack.text({\n message: `Please enter the path to your ${toolName} config file:`,\n placeholder: join('.', configFileName),\n validate: (value) => {\n if (!value) {\n return 'Please enter a path.';\n }\n\n try {\n fs.accessSync(value);\n } catch {\n return 'Could not access the file at this path.';\n }\n },\n }),\n );\n}\n\n/**\n * Prints copy/paste-able instructions to the console.\n * Afterwards asks the user if they added the code snippet to their file.\n *\n * While there's no point in providing a \"no\" answer here, it gives users time to fulfill the\n * task before the wizard continues with additional steps.\n *\n * Use this function if you want to show users instructions on how to add/modify\n * code in their file. This is helpful if automatic insertion failed or is not possible/feasible.\n *\n * @param filename the name of the file to which the code snippet should be applied.\n * If a path is provided, only the filename will be used.\n *\n * @param codeSnippet the snippet to be printed. Use {@link makeCodeSnippet} to create the\n * diff-like format for visually highlighting unchanged or modified lines of code.\n *\n * @param hint (optional) a hint to be printed after the main instruction to add\n * the code from @param codeSnippet to their @param filename.\n *\n * TODO: refactor copy paste instructions across different wizards to use this function.\n * this might require adding a custom message parameter to the function\n */\nexport async function showCopyPasteInstructions(\n filename: string,\n codeSnippet: string,\n hint?: string,\n): Promise<void> {\n clack.log.step(\n `Add the following code to your ${chalk.cyan(basename(filename))} file:${\n hint ? chalk.dim(` (${chalk.dim(hint)})`) : ''\n }`,\n );\n\n // Padding the code snippet to be printed with a \\n at the beginning and end\n // This makes it easier to distinguish the snippet from the rest of the output\n // Intentionally logging directly to console here so that the code can be copied/pasted directly\n // eslint-disable-next-line no-console\n console.log(`\\n${codeSnippet}\\n`);\n\n await abortIfCancelled(\n clack.select({\n message: 'Did you apply the snippet above?',\n options: [{ label: 'Yes, continue!', value: true }],\n initialValue: true,\n }),\n );\n}\n\n/**\n * Callback that exposes formatting helpers for a code snippet.\n * @param unchanged - Formats text as old code.\n * @param plus - Formats text as new code.\n * @param minus - Formats text as removed code.\n */\ntype CodeSnippetFormatter = (\n unchanged: (txt: string) => string,\n plus: (txt: string) => string,\n minus: (txt: string) => string,\n) => string;\n\n/**\n * Crafts a code snippet that can be used to e.g.\n * - print copy/paste instructions to the console\n * - create a new config file.\n *\n * @param colors set this to true if you want the final snippet to be colored.\n * This is useful for printing the snippet to the console as part of copy/paste instructions.\n *\n * @param callback the callback that returns the formatted code snippet.\n * It exposes takes the helper functions for marking code as unchanged, new or removed.\n * These functions no-op if no special formatting should be applied\n * and otherwise apply the appropriate formatting/coloring.\n * (@see {@link CodeSnippetFormatter})\n *\n * @see {@link showCopyPasteInstructions} for the helper with which to display the snippet in the console.\n *\n * @returns a string containing the final, formatted code snippet.\n */\nexport function makeCodeSnippet(\n colors: boolean,\n callback: CodeSnippetFormatter,\n): string {\n const unchanged = (txt: string) => (colors ? chalk.grey(txt) : txt);\n const plus = (txt: string) => (colors ? chalk.greenBright(txt) : txt);\n const minus = (txt: string) => (colors ? chalk.redBright(txt) : txt);\n\n return callback(unchanged, plus, minus);\n}\n\n/**\n * Creates a new config file with the given @param filepath and @param codeSnippet.\n *\n * Use this function to create a new config file for users. This is useful\n * when users answered that they don't yet have a config file for a tool.\n *\n * (This doesn't mean that they don't yet have some other way of configuring\n * their tool but we can leave it up to them to figure out how to merge configs\n * here.)\n *\n * @param filepath absolute path to the new config file\n * @param codeSnippet the snippet to be inserted into the file\n * @param moreInformation (optional) the message to be printed after the file was created\n * For example, this can be a link to more information about configuring the tool.\n *\n * @returns true on success, false otherwise\n */\nexport async function createNewConfigFile(\n filepath: string,\n codeSnippet: string,\n { installDir }: Pick<WizardOptions, 'installDir'>,\n moreInformation?: string,\n): Promise<boolean> {\n if (!isAbsolute(filepath)) {\n debug(`createNewConfigFile: filepath is not absolute: ${filepath}`);\n return false;\n }\n\n const prettyFilename = chalk.cyan(relative(installDir, filepath));\n\n try {\n await fs.promises.writeFile(filepath, codeSnippet);\n\n clack.log.success(`Added new ${prettyFilename} file.`);\n\n if (moreInformation) {\n clack.log.info(chalk.gray(moreInformation));\n }\n\n return true;\n } catch (e) {\n debug(e);\n clack.log.warn(\n `Could not create a new ${prettyFilename} file. Please create one manually and follow the instructions below.`,\n );\n }\n\n return false;\n}\n\nexport async function featureSelectionPrompt<F extends ReadonlyArray<Feature>>(\n features: F,\n): Promise<{ [key in F[number]['id']]: boolean }> {\n return traceStep('feature-selection', async () => {\n const selectedFeatures: Record<string, boolean> = {};\n\n for (const feature of features) {\n const selected = await abortIfCancelled(\n clack.select({\n message: feature.prompt,\n initialValue: true,\n options: [\n {\n value: true,\n label: 'Yes',\n hint: feature.enabledHint,\n },\n {\n value: false,\n label: 'No',\n hint: feature.disabledHint,\n },\n ],\n }),\n );\n\n selectedFeatures[feature.id] = selected;\n }\n\n return selectedFeatures as { [key in F[number]['id']]: boolean };\n });\n}\n\nexport async function askShouldInstallPackage(\n pkgName: string,\n): Promise<boolean> {\n return traceStep(`ask-install-package`, () =>\n abortIfCancelled(\n clack.confirm({\n message: `Do you want to install ${chalk.cyan(pkgName)}?`,\n }),\n ),\n );\n}\n\nexport async function askShouldAddPackageOverride(\n pkgName: string,\n pkgVersion: string,\n): Promise<boolean> {\n return traceStep(`ask-add-package-override`, () =>\n abortIfCancelled(\n clack.confirm({\n message: `Do you want to add an override for ${chalk.cyan(\n pkgName,\n )} version ${chalk.cyan(pkgVersion)}?`,\n }),\n ),\n );\n}\n\nexport async function askForAIConsent(\n options: Pick<WizardOptions, 'default' | 'ci'>,\n) {\n return await traceStep('ask-for-ai-consent', async () => {\n // CI mode: auto-consent to AI\n const aiConsent =\n options.default || options.ci\n ? true\n : await abortIfCancelled(\n clack.select({\n message:\n 'This setup wizard uses AI, are you happy to continue? β¨',\n options: [\n {\n label: 'Yes',\n value: true,\n hint: 'We will use AI to help you setup PostHog quickly',\n },\n {\n label: 'No',\n value: false,\n hint: \"I don't like AI\",\n },\n ],\n initialValue: true,\n }),\n );\n\n return aiConsent;\n });\n}\n\nexport async function askForCloudRegion(): Promise<CloudRegion> {\n return await traceStep('ask-for-cloud-region', async () => {\n const cloudRegion: CloudRegion = await abortIfCancelled(\n clack.select({\n message: 'Select your PostHog Cloud region',\n options: [\n {\n label: 'US πΊπΈ',\n value: 'us',\n hint: 'Your data will be stored in the US',\n },\n {\n label: 'EU πͺπΊ',\n value: 'eu',\n hint: 'Your data will be stored in the EU',\n },\n ],\n }),\n );\n\n return cloudRegion;\n });\n}\n"]}
|
package/package.json
CHANGED