testchimp-runner-core 0.0.35 → 0.0.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/orchestrator/orchestrator-agent.d.ts.map +1 -1
  2. package/dist/orchestrator/orchestrator-agent.js +7 -4
  3. package/dist/orchestrator/orchestrator-agent.js.map +1 -1
  4. package/dist/orchestrator/orchestrator-prompts.d.ts.map +1 -1
  5. package/dist/orchestrator/orchestrator-prompts.js +73 -15
  6. package/dist/orchestrator/orchestrator-prompts.js.map +1 -1
  7. package/dist/orchestrator/page-som-handler.d.ts +1 -2
  8. package/dist/orchestrator/page-som-handler.d.ts.map +1 -1
  9. package/dist/orchestrator/page-som-handler.js +51 -25
  10. package/dist/orchestrator/page-som-handler.js.map +1 -1
  11. package/package.json +6 -1
  12. package/plandocs/BEFORE_AFTER_VERIFICATION.md +0 -148
  13. package/plandocs/COORDINATE_MODE_DIAGNOSIS.md +0 -144
  14. package/plandocs/CREDIT_CALLBACK_ARCHITECTURE.md +0 -253
  15. package/plandocs/HUMAN_LIKE_IMPROVEMENTS.md +0 -642
  16. package/plandocs/IMPLEMENTATION_STATUS.md +0 -108
  17. package/plandocs/INTEGRATION_COMPLETE.md +0 -322
  18. package/plandocs/MULTI_AGENT_ARCHITECTURE_REVIEW.md +0 -844
  19. package/plandocs/ORCHESTRATOR_MVP_SUMMARY.md +0 -539
  20. package/plandocs/PHASE1_ABSTRACTION_COMPLETE.md +0 -241
  21. package/plandocs/PHASE1_FINAL_STATUS.md +0 -210
  22. package/plandocs/PHASE_1_COMPLETE.md +0 -165
  23. package/plandocs/PHASE_1_SUMMARY.md +0 -184
  24. package/plandocs/PLANNING_SESSION_SUMMARY.md +0 -372
  25. package/plandocs/PROMPT_OPTIMIZATION_ANALYSIS.md +0 -120
  26. package/plandocs/PROMPT_SANITY_CHECK.md +0 -120
  27. package/plandocs/SCRIPT_CLEANUP_FEATURE.md +0 -201
  28. package/plandocs/SCRIPT_GENERATION_ARCHITECTURE.md +0 -364
  29. package/plandocs/SELECTOR_IMPROVEMENTS.md +0 -139
  30. package/plandocs/SESSION_SUMMARY_v0.0.33.md +0 -151
  31. package/plandocs/TROUBLESHOOTING_SESSION.md +0 -72
  32. package/plandocs/VISION_DIAGNOSTICS_IMPROVEMENTS.md +0 -336
  33. package/plandocs/VISUAL_AGENT_EVOLUTION_PLAN.md +0 -396
  34. package/plandocs/WHATS_NEW_v0.0.33.md +0 -183
  35. package/plandocs/exploratory-mode-support-v2.plan.md +0 -953
  36. package/plandocs/exploratory-mode-support.plan.md +0 -928
  37. package/plandocs/journey-id-tracking-addendum.md +0 -227
  38. package/releasenotes/RELEASE_0.0.26.md +0 -165
  39. package/releasenotes/RELEASE_0.0.27.md +0 -236
  40. package/releasenotes/RELEASE_0.0.28.md +0 -286
  41. package/src/auth-config.ts +0 -84
  42. package/src/credit-usage-service.ts +0 -188
  43. package/src/env-loader.ts +0 -103
  44. package/src/execution-service.ts +0 -996
  45. package/src/file-handler.ts +0 -104
  46. package/src/index.ts +0 -432
  47. package/src/llm-facade.ts +0 -821
  48. package/src/llm-provider.ts +0 -53
  49. package/src/model-constants.ts +0 -35
  50. package/src/orchestrator/decision-parser.ts +0 -139
  51. package/src/orchestrator/index.ts +0 -58
  52. package/src/orchestrator/orchestrator-agent.ts +0 -1282
  53. package/src/orchestrator/orchestrator-prompts.ts +0 -786
  54. package/src/orchestrator/page-som-handler.ts +0 -1565
  55. package/src/orchestrator/som-types.ts +0 -188
  56. package/src/orchestrator/tool-registry.ts +0 -184
  57. package/src/orchestrator/tools/check-page-ready.ts +0 -75
  58. package/src/orchestrator/tools/extract-data.ts +0 -92
  59. package/src/orchestrator/tools/index.ts +0 -15
  60. package/src/orchestrator/tools/inspect-page.ts +0 -42
  61. package/src/orchestrator/tools/recall-history.ts +0 -72
  62. package/src/orchestrator/tools/refresh-som-markers.ts +0 -69
  63. package/src/orchestrator/tools/take-screenshot.ts +0 -128
  64. package/src/orchestrator/tools/verify-action-result.ts +0 -159
  65. package/src/orchestrator/tools/view-previous-screenshot.ts +0 -103
  66. package/src/orchestrator/types.ts +0 -291
  67. package/src/playwright-mcp-service.ts +0 -224
  68. package/src/progress-reporter.ts +0 -144
  69. package/src/prompts.ts +0 -842
  70. package/src/providers/backend-proxy-llm-provider.ts +0 -91
  71. package/src/providers/local-llm-provider.ts +0 -38
  72. package/src/scenario-service.ts +0 -252
  73. package/src/scenario-worker-class.ts +0 -1110
  74. package/src/script-utils.ts +0 -203
  75. package/src/types.ts +0 -239
  76. package/src/utils/browser-utils.ts +0 -348
  77. package/src/utils/coordinate-converter.ts +0 -162
  78. package/src/utils/page-info-retry.ts +0 -65
  79. package/src/utils/page-info-utils.ts +0 -285
  80. package/testchimp-runner-core-0.0.35.tgz +0 -0
  81. package/tsconfig.json +0 -19
@@ -1,286 +0,0 @@
1
- # Runner-Core 0.0.28 Release - Scriptservice Integration
2
-
3
- ## Overview
4
-
5
- Extended runner-core with lifecycle callbacks and created SmartTestRunnerCoreV2 wrapper to enable scriptservice integration. This release makes runner-core a drop-in replacement for scriptservice's duplicated SmartTestRunnerCore.
6
-
7
- ## Changes
8
-
9
- ### 1. Extended ProgressReporter with Lifecycle Callbacks
10
-
11
- **File:** `src/progress-reporter.ts`
12
-
13
- Added optional lifecycle callbacks to ProgressReporter interface:
14
-
15
- ```typescript
16
- export interface StepInfo {
17
- stepId?: string;
18
- stepNumber: number;
19
- description: string;
20
- code?: string;
21
- }
22
-
23
- export interface ProgressReporter {
24
- // ... existing callbacks ...
25
-
26
- // NEW: Lifecycle callbacks (used by scriptservice, ignored by local clients)
27
- beforeStartTest?(page: any, browser: any, context: any): Promise<void>;
28
- beforeStepStart?(step: StepInfo, page: any): Promise<void>;
29
- afterEndTest?(status: 'passed' | 'failed', error?: string, page?: any): Promise<void>;
30
- }
31
- ```
32
-
33
- **Purpose:**
34
- - `beforeStartTest`: Initialize browser context, set up DB records (scriptservice only)
35
- - `beforeStepStart`: Update step status to IN_PROGRESS in DB (scriptservice only)
36
- - `afterEndTest`: Write final status to DB, cleanup resources (scriptservice only)
37
- - Local clients (vs-ext, github-action) can ignore these - they use return values
38
-
39
- ### 2. Integrated Lifecycle Callbacks
40
-
41
- **Files:**
42
- - `src/execution-service.ts` - RUN_EXACTLY and AI_REPAIR modes
43
- - `src/scenario-worker-class.ts` - Orchestrator mode
44
-
45
- **Integration Points:**
46
-
47
- **ExecutionService (RUN_EXACTLY):**
48
- ```typescript
49
- // Before script execution
50
- if (this.progressReporter?.beforeStartTest) {
51
- await this.progressReporter.beforeStartTest(page, browser, context);
52
- }
53
-
54
- // After execution (success or failure)
55
- if (this.progressReporter?.afterEndTest) {
56
- await this.progressReporter.afterEndTest(
57
- success ? 'passed' : 'failed',
58
- error,
59
- page
60
- );
61
- }
62
- ```
63
-
64
- **ExecutionService (AI_REPAIR):**
65
- ```typescript
66
- // Before each step
67
- if (this.progressReporter?.beforeStepStart) {
68
- await this.progressReporter.beforeStepStart(
69
- { stepNumber, description, code },
70
- page
71
- );
72
- }
73
- ```
74
-
75
- **ScenarioWorker (Orchestrator):**
76
- ```typescript
77
- // After browser initialization
78
- if (this.progressReporter?.beforeStartTest) {
79
- await this.progressReporter.beforeStartTest(page, browser, context);
80
- }
81
-
82
- // Before each orchestrator step
83
- if (this.progressReporter?.beforeStepStart) {
84
- await this.progressReporter.beforeStepStart({ stepNumber, description }, page);
85
- }
86
-
87
- // In finally block (before browser close)
88
- if (this.progressReporter?.afterEndTest) {
89
- await this.progressReporter.afterEndTest(
90
- overallSuccess ? 'passed' : 'failed',
91
- error,
92
- page
93
- );
94
- }
95
- ```
96
-
97
- ### 3. Version Bump
98
-
99
- **File:** `package.json`
100
-
101
- Updated version from `0.0.27` to `0.0.28`
102
-
103
- ## Scriptservice Integration
104
-
105
- ### 1. Created ScriptserviceLLMProvider
106
-
107
- **File:** `services/scriptservice/providers/scriptservice-llm-provider.ts` (NEW)
108
-
109
- Implements `LLMProvider` interface for scriptservice:
110
- - Wraps scriptservice's existing OpenAI client
111
- - Supports both text and vision prompts
112
- - Uses scriptservice's OpenAI API key from ConfigService
113
- - No backend proxy - all calls are local
114
- - No token tracking needed (scriptservice doesn't use this interface for tracking)
115
-
116
- ### 2. Created SmartTestRunnerCoreV2
117
-
118
- **File:** `services/scriptservice/smart-test-runner-core-v2.ts` (NEW)
119
-
120
- Drop-in replacement for SmartTestRunnerCore:
121
- - **Same Interface:** Maintains exact same constructor and methods (runExactly, runWithRepair)
122
- - **Uses runner-core:** Delegates to TestChimpService internally
123
- - **Callback Mapping:** Maps scriptservice callbacks to runner-core ProgressReporter
124
- - **Lifecycle Support:** Properly calls beforeStartTest, beforeStepStart, afterEndTest
125
- - **No Breaking Changes:** Can replace SmartTestRunnerCore with zero code changes
126
-
127
- **Key Features:**
128
- ```typescript
129
- export class SmartTestRunnerCoreV2 {
130
- constructor(config: RunnerConfig) {
131
- // Create local LLM provider (no backend)
132
- const llmProvider = new ScriptserviceLLMProvider();
133
-
134
- // Map callbacks to progress reporter
135
- const progressReporter: ProgressReporter = {
136
- onStepProgress: async (stepProgress) => {
137
- // Call scriptservice's onStepComplete
138
- },
139
- beforeStartTest: config.callbacks?.beforeStartTest,
140
- beforeStepStart: config.callbacks?.beforeStepStart,
141
- afterEndTest: config.callbacks?.afterEndTest
142
- };
143
-
144
- // Initialize runner-core (no auth, no backend)
145
- this.runnerCore = new TestChimpService(
146
- undefined, // No file handler
147
- undefined, // No auth
148
- undefined, // No backend URL
149
- 1, // Single worker
150
- llmProvider,
151
- progressReporter
152
- );
153
- }
154
-
155
- async runExactly(script: string): Promise<RunExactlyResult> { /* ... */ }
156
- async runWithRepair(steps: TestStepWithId[]): Promise<RunWithRepairResult> { /* ... */ }
157
- }
158
- ```
159
-
160
- ### 3. Updated Scriptservice Consumers
161
-
162
- **Files Updated:**
163
- - `services/scriptservice/smart-test-execution-handler.ts`
164
- - `services/scriptservice/workers/test-based-explorer.ts`
165
- - `services/scriptservice/package.json` - Added `testchimp-runner-core: ^0.0.28`
166
-
167
- **Migration Strategy:**
168
- ```typescript
169
- // Environment flag for gradual rollout
170
- const useV2 = process.env.USE_RUNNER_CORE_V2 !== 'false'; // Default: true
171
- const runner = useV2
172
- ? new SmartTestRunnerCoreV2(runnerConfig)
173
- : new SmartTestRunnerCore(runnerConfig);
174
- ```
175
-
176
- **Rollout Plan:**
177
- 1. Deploy with `USE_RUNNER_CORE_V2=true` (default)
178
- 2. Monitor scriptservice execution logs
179
- 3. If issues occur, set `USE_RUNNER_CORE_V2=false` to rollback
180
- 4. Once validated, remove flag and delete old SmartTestRunnerCore
181
-
182
- ## Benefits
183
-
184
- ### For Scriptservice:
185
- 1. **Zero Axios Calls:** All LLM calls local, all DB writes via callbacks
186
- 2. **Auto-Updates:** Automatically get runner-core improvements (better prompts, vision, orchestrator)
187
- 3. **Code Deduplication:** Remove ~600 lines of duplicated execution/repair logic
188
- 4. **Consistency:** Same prompts and logic as vs-extension and github-action
189
-
190
- ### For Runner-Core:
191
- 1. **Universal Library:** Works for both client-side (vs-ext) and server-side (scriptservice)
192
- 2. **Flexible Architecture:** Callbacks allow different execution patterns
193
- 3. **Backward Compatible:** Existing consumers unaffected (callbacks are optional)
194
-
195
- ## Testing
196
-
197
- ### Scriptservice Testing:
198
- ```bash
199
- # Test with V2 (default)
200
- USE_RUNNER_CORE_V2=true npm start
201
-
202
- # Test with V1 (legacy fallback)
203
- USE_RUNNER_CORE_V2=false npm start
204
- ```
205
-
206
- ### Expected Behavior:
207
- - V2: Logs show "using SmartTestRunnerCoreV2 (runner-core)"
208
- - V1: Logs show "using SmartTestRunnerCore (legacy)"
209
- - All callbacks (beforeStartTest, beforeStepStart, afterEndTest, onStepComplete) should fire
210
- - DB writes should happen via callbacks
211
- - Screenshots should upload to GCS
212
- - Journey reporting should work
213
-
214
- ## Publishing
215
-
216
- ### Prerequisites:
217
- 1. ✅ Build runner-core: `npm run build`
218
- 2. ✅ No lint errors
219
- 3. ✅ Version bumped to 0.0.28
220
- 4. ⏸️ **Awaiting user permission to publish to npm**
221
-
222
- ### Publish Command (when approved):
223
- ```bash
224
- cd /Users/nuwansam/IdeaProjects/AwareRepo/local/runner-core
225
- npm publish
226
- ```
227
-
228
- ### Post-Publish:
229
- 1. Install in scriptservice: `npm install testchimp-runner-core@0.0.28`
230
- 2. Install in vs-ext: Update to 0.0.28
231
- 3. Install in github-action: Update to 0.0.28
232
-
233
- ## Migration Checklist
234
-
235
- ### Phase 1: Deploy with V2 (Default)
236
- - [x] Add lifecycle callbacks to ProgressReporter
237
- - [x] Integrate callbacks in ExecutionService and ScenarioService
238
- - [x] Create ScriptserviceLLMProvider
239
- - [x] Create SmartTestRunnerCoreV2
240
- - [x] Update scriptservice consumers with environment flag
241
- - [ ] Publish runner-core 0.0.28 (needs user permission)
242
- - [ ] Install 0.0.28 in scriptservice
243
- - [ ] Deploy scriptservice with USE_RUNNER_CORE_V2=true
244
- - [ ] Monitor logs and execution results
245
-
246
- ### Phase 2: Validate (1-2 weeks)
247
- - [ ] Verify all smart test executions work
248
- - [ ] Verify explorer mode works
249
- - [ ] Verify script generation works
250
- - [ ] Check DB writes happen correctly
251
- - [ ] Check screenshot uploads work
252
- - [ ] Monitor for any errors or regressions
253
-
254
- ### Phase 3: Full Migration
255
- - [ ] Remove environment flag check
256
- - [ ] Replace all `new SmartTestRunnerCore` with `new SmartTestRunnerCoreV2`
257
- - [ ] Delete old `smart-test-runner-core.ts` file
258
- - [ ] Optional: Rename V2 to just `SmartTestRunnerCore`
259
-
260
- ## Breaking Changes
261
-
262
- None. All changes are backward compatible.
263
-
264
- ## Files Changed
265
-
266
- ### Runner-Core:
267
- - `src/progress-reporter.ts` - Added lifecycle callbacks
268
- - `src/execution-service.ts` - Integrated callbacks
269
- - `src/scenario-worker-class.ts` - Integrated callbacks
270
- - `package.json` - Version bump to 0.0.28
271
-
272
- ### Scriptservice:
273
- - `providers/scriptservice-llm-provider.ts` - NEW
274
- - `smart-test-runner-core-v2.ts` - NEW
275
- - `smart-test-execution-handler.ts` - Added V2 usage with flag
276
- - `workers/test-based-explorer.ts` - Added V2 usage with flag
277
- - `package.json` - Added testchimp-runner-core dependency
278
-
279
- ## Notes
280
-
281
- - Lifecycle callbacks are **optional** - local clients (vs-ext, github-action) don't need them
282
- - Scriptservice uses callbacks for DB writes and resource management
283
- - V2 wrapper uses existing page/browser/context (doesn't create new ones)
284
- - LLM calls in V2 are all local (no backend proxy)
285
- - No authentication needed for scriptservice (already authenticated at service level)
286
-
@@ -1,84 +0,0 @@
1
- /**
2
- * Authentication configuration for TestChimp services
3
- * Supports both user PAT and project API key authentication modes
4
- */
5
-
6
- export interface UserPATAuthConfig {
7
- mode: 'user_pat';
8
- userAuthKey: string;
9
- userMail: string;
10
- }
11
-
12
- export interface ProjectApiKeyAuthConfig {
13
- mode: 'project_api_key';
14
- apiKey: string;
15
- projectId: string;
16
- }
17
-
18
- export type AuthConfig = UserPATAuthConfig | ProjectApiKeyAuthConfig;
19
-
20
- /**
21
- * Helper function to create user PAT auth configuration
22
- */
23
- export function createUserPATAuth(userAuthKey: string, userMail: string): UserPATAuthConfig {
24
- return {
25
- mode: 'user_pat',
26
- userAuthKey,
27
- userMail
28
- };
29
- }
30
-
31
- /**
32
- * Helper function to create project API key auth configuration
33
- */
34
- export function createProjectApiKeyAuth(apiKey: string, projectId: string): ProjectApiKeyAuthConfig {
35
- return {
36
- mode: 'project_api_key',
37
- apiKey,
38
- projectId
39
- };
40
- }
41
-
42
- /**
43
- * Helper function to create auth configuration from environment variables
44
- * Supports both authentication modes based on available environment variables
45
- */
46
- export function createAuthConfigFromEnv(): AuthConfig | null {
47
- // Check for project API key authentication first (for CI/CD)
48
- const apiKey = process.env.TESTCHIMP_API_KEY;
49
- const projectId = process.env.TESTCHIMP_PROJECT_ID;
50
-
51
- if (apiKey && projectId) {
52
- return createProjectApiKeyAuth(apiKey, projectId);
53
- }
54
-
55
- // Fall back to user PAT authentication (for VS Code extension)
56
- const userAuthKey = process.env.TESTCHIMP_USER_AUTH_KEY;
57
- const userMail = process.env.TESTCHIMP_USER_MAIL;
58
-
59
- if (userAuthKey && userMail) {
60
- return createUserPATAuth(userAuthKey, userMail);
61
- }
62
-
63
- return null;
64
- }
65
-
66
- /**
67
- * Helper function to get authentication headers for HTTP requests
68
- */
69
- export function getAuthHeaders(authConfig: AuthConfig): Record<string, string> {
70
- switch (authConfig.mode) {
71
- case 'user_pat':
72
- return {
73
- 'user_auth_key': authConfig.userAuthKey,
74
- 'user_mail': authConfig.userMail
75
- };
76
- case 'project_api_key':
77
- return {
78
- 'TestChimp-Api-Key': authConfig.apiKey,
79
- 'project-id': authConfig.projectId
80
- };
81
- default:
82
- throw new Error('Invalid authentication configuration');
83
- }
84
- }
@@ -1,188 +0,0 @@
1
- import axios from 'axios';
2
- import { AuthConfig, getAuthHeaders } from './auth-config';
3
- import { loadEnvConfig } from './env-loader';
4
-
5
- export enum CreditUsageReason {
6
- UNKNOWN_CREDIT_USAGE_REASON = 0,
7
- EXPLORER_STEP = 1,
8
- TEST_REPAIR = 2,
9
- SCRIPT_GENERATE = 3
10
- }
11
-
12
- export interface InsertCreditUsageRequest {
13
- credits?: number;
14
- usage_reason?: CreditUsageReason;
15
- job_id?: string;
16
- }
17
-
18
- export interface InsertCreditUsageResponse {
19
- // Empty response as per the protobuf definition
20
- }
21
-
22
- /**
23
- * Credit usage information for callback
24
- */
25
- export interface CreditUsage {
26
- credits: number;
27
- usageReason: CreditUsageReason;
28
- jobId?: string;
29
- timestamp: number;
30
- }
31
-
32
- /**
33
- * Callback for credit usage reporting
34
- * Allows consumers to track credit usage in their own systems
35
- */
36
- export type CreditUsageCallback = (usage: CreditUsage) => void | Promise<void>;
37
-
38
- export class CreditUsageService {
39
- private backendUrl: string;
40
- private authConfig: AuthConfig | null;
41
- private logger?: (message: string, level?: 'log' | 'error' | 'warn') => void;
42
- private creditUsageCallback?: CreditUsageCallback;
43
-
44
- constructor(authConfig?: AuthConfig, backendUrl?: string, creditUsageCallback?: CreditUsageCallback) {
45
- // Use provided backend URL or fall back to environment configuration
46
- if (backendUrl) {
47
- this.backendUrl = backendUrl;
48
- } else {
49
- // Fall back to environment configuration for backward compatibility
50
- const envConfig = loadEnvConfig();
51
- this.backendUrl = envConfig.TESTCHIMP_BACKEND_URL;
52
- }
53
-
54
- this.authConfig = authConfig || null;
55
- this.creditUsageCallback = creditUsageCallback;
56
- }
57
-
58
- /**
59
- * Set a logger callback for capturing execution logs
60
- */
61
- setLogger(logger: (message: string, level?: 'log' | 'error' | 'warn') => void): void {
62
- this.logger = logger;
63
- }
64
-
65
- /**
66
- * Set credit usage callback
67
- * Allows consumers to track credit usage in their own systems
68
- */
69
- setCreditUsageCallback(callback: CreditUsageCallback): void {
70
- this.creditUsageCallback = callback;
71
- }
72
-
73
- /**
74
- * Log a message using the configured logger
75
- */
76
- private log(message: string, level: 'log' | 'error' | 'warn' = 'log'): void {
77
- if (this.logger) {
78
- this.logger(message, level);
79
- }
80
- // No console fallback - logs are routed to consumer
81
- }
82
-
83
- /**
84
- * Update authentication configuration
85
- */
86
- setAuthConfig(authConfig: AuthConfig): void {
87
- this.authConfig = authConfig;
88
- }
89
-
90
- /**
91
- * Get current authentication configuration
92
- */
93
- getAuthConfig(): AuthConfig | null {
94
- return this.authConfig;
95
- }
96
-
97
- /**
98
- * Report credit usage via callback and/or backend
99
- *
100
- * Behavior:
101
- * 1. If callback provided: Call callback (server-side uses this to update DB directly)
102
- * 2. If NO callback but auth configured: Make axios call to backend (client-side: vs-ext, github action)
103
- * 3. Server-side: Provides callback, no axios calls made
104
- * 4. Client-side: No callback, uses auth for axios calls to backend
105
- */
106
- async reportCreditUsage(
107
- credits: number = 1,
108
- usageReason: CreditUsageReason,
109
- jobId?: string
110
- ): Promise<InsertCreditUsageResponse> {
111
- const creditUsage: CreditUsage = {
112
- credits,
113
- usageReason,
114
- jobId,
115
- timestamp: Date.now()
116
- };
117
-
118
- // 1. If callback provided: Use callback (server-side path)
119
- if (this.creditUsageCallback) {
120
- try {
121
- await this.creditUsageCallback(creditUsage);
122
- this.log(`Credit usage reported via callback: ${credits} credits for ${CreditUsageReason[usageReason]}`);
123
- return {}; // Callback succeeded, no need for backend call
124
- } catch (error: any) {
125
- this.log(`Credit usage callback failed: ${error.message}`, 'error');
126
- throw error; // Callback failure is critical for server-side
127
- }
128
- }
129
-
130
- // 2. No callback: Make axios call if auth configured (client-side path: vs-ext, github action)
131
- if (this.authConfig) {
132
- try {
133
- const authHeaders = getAuthHeaders(this.authConfig);
134
- const url = `${this.backendUrl}/localagent/insert_credit_usage`;
135
-
136
- const request: InsertCreditUsageRequest = {
137
- credits,
138
- usage_reason: usageReason,
139
- job_id: jobId
140
- };
141
-
142
- const response = await axios.post(url, request, {
143
- headers: {
144
- ...authHeaders,
145
- 'Content-Type': 'application/json'
146
- },
147
- timeout: 10000 // 10 second timeout for credit usage calls
148
- });
149
-
150
- this.log(`Credit usage reported to backend: ${credits} credits for ${CreditUsageReason[usageReason]}`);
151
- return response.data;
152
- } catch (error: any) {
153
- this.log(`Credit usage backend report failed: ${error.message}`, 'error');
154
- throw error; // Backend failure is critical for client-side
155
- }
156
- }
157
-
158
- // 3. No callback and no auth - no credit tracking (development mode)
159
- this.log(`Credit usage not tracked (no callback or auth configured): ${credits} credits for ${CreditUsageReason[usageReason]}`, 'warn');
160
- return {};
161
- }
162
-
163
- /**
164
- * Report script generation credit usage
165
- */
166
- async reportScriptGenerationCredit(jobId?: string): Promise<void> {
167
- try {
168
- await this.reportCreditUsage(1, CreditUsageReason.SCRIPT_GENERATE, jobId);
169
- this.log(`Credit usage reported for script generation${jobId ? ` (job: ${jobId})` : ''}`);
170
- } catch (error) {
171
- this.log(`Failed to report script generation credit usage: ${error}`, 'error');
172
- // Don't throw - credit reporting should not break the main flow
173
- }
174
- }
175
-
176
- /**
177
- * Report AI repair credit usage
178
- */
179
- async reportAIRepairCredit(jobId?: string): Promise<void> {
180
- try {
181
- await this.reportCreditUsage(1, CreditUsageReason.TEST_REPAIR, jobId);
182
- this.log(`Credit usage reported for AI repair${jobId ? ` (job: ${jobId})` : ''}`);
183
- } catch (error) {
184
- this.log(`Failed to report AI repair credit usage: ${error}`, 'error');
185
- // Don't throw - credit reporting should not break the main flow
186
- }
187
- }
188
- }
package/src/env-loader.ts DELETED
@@ -1,103 +0,0 @@
1
- /**
2
- * Environment Configuration Loader
3
- *
4
- * This module loads environment configuration from packaged env files
5
- * instead of relying on process.env which may not be available in VS Code extensions
6
- */
7
-
8
- interface EnvConfig {
9
- TESTCHIMP_BACKEND_URL: string;
10
- }
11
-
12
- let cachedConfig: EnvConfig | null = null;
13
-
14
- /**
15
- * Load environment configuration from the packaged env file
16
- * Falls back to process.env if env file is not available
17
- */
18
- export function loadEnvConfig(): EnvConfig {
19
- if (cachedConfig) {
20
- return cachedConfig;
21
- }
22
-
23
- try {
24
- // Try multiple possible paths for the env file
25
- const possiblePaths = [
26
- require('path').join(String(__dirname), 'env'),
27
- require('path').join(String(__dirname), './env'),
28
- require('path').join(String(__dirname), '../env'),
29
- require('path').join(String(__dirname), '../../runner-core/env'),
30
- require('path').join(String(__dirname), '../../runner-core/dist/env'),
31
- require('path').join(String(process.cwd()), 'env'),
32
- require('path').join(String(process.cwd()), 'runner-core/env'),
33
- require('path').join(String(process.cwd()), 'runner-core/dist/env'),
34
- require('path').join(String(process.cwd()), 'local/runner-core/env'),
35
- require('path').join(String(process.cwd()), 'local/runner-core/dist/env')
36
- ];
37
-
38
- let envContent = '';
39
- let envPath = '';
40
-
41
- for (const path of possiblePaths) {
42
- try {
43
- envContent = require('fs').readFileSync(path, 'utf8');
44
- envPath = path;
45
- break;
46
- } catch (error) {
47
- // Silently continue to next path
48
- }
49
- }
50
-
51
- if (!envContent) {
52
- throw new Error('Could not find env file in any of the expected locations');
53
- }
54
-
55
- const config: Partial<EnvConfig> = {};
56
-
57
- envContent.split('\n').forEach((line: string) => {
58
- const trimmedLine = line.trim();
59
- if (trimmedLine && !trimmedLine.startsWith('#')) {
60
- const [key, value] = trimmedLine.split('=');
61
- if (key && value) {
62
- const trimmedKey = key.trim() as keyof EnvConfig;
63
- config[trimmedKey] = value.trim();
64
- }
65
- }
66
- });
67
-
68
- // Ensure required properties are present
69
- const finalConfig: EnvConfig = {
70
- TESTCHIMP_BACKEND_URL: config.TESTCHIMP_BACKEND_URL || 'https://featureservice.testchimp.io'
71
- };
72
-
73
- cachedConfig = finalConfig;
74
- return finalConfig;
75
- } catch (error) {
76
- // Fallback to process.env
77
- let backendUrl = process.env.TESTCHIMP_BACKEND_URL;
78
-
79
- // If no explicit backend URL, determine from TESTCHIMP_ENV
80
- if (!backendUrl) {
81
- const testchimpEnv = process.env.TESTCHIMP_ENV;
82
- if (testchimpEnv === 'staging') {
83
- backendUrl = 'https://featureservice-staging.testchimp.io';
84
- } else {
85
- backendUrl = 'https://featureservice.testchimp.io';
86
- }
87
- }
88
-
89
- const config: EnvConfig = {
90
- TESTCHIMP_BACKEND_URL: backendUrl
91
- };
92
- cachedConfig = config;
93
- return config;
94
- }
95
- }
96
-
97
- /**
98
- * Get a specific environment variable
99
- */
100
- export function getEnvVar(key: keyof EnvConfig): string | undefined {
101
- const config = loadEnvConfig();
102
- return config[key];
103
- }