cto-ai-cli 3.2.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2803 @@
1
+ // src/gateway/server.ts
2
+ import { createServer, Agent as HttpAgent } from "http";
3
+ import { request as httpsRequest, Agent as HttpsAgent } from "https";
4
+ import { request as httpRequest } from "http";
5
+ import { URL } from "url";
6
+ import { lookup } from "dns/promises";
7
+
8
+ // src/gateway/types.ts
9
+ var DEFAULT_GATEWAY_CONFIG = {
10
+ port: 8787,
11
+ host: "127.0.0.1",
12
+ optimize: true,
13
+ projectPath: ".",
14
+ budget: 5e4,
15
+ redactSecrets: true,
16
+ blockOnSecrets: false,
17
+ apiKey: "",
18
+ allowedTargetDomains: [],
19
+ // Empty = default LLM provider allowlist
20
+ maxBodyBytes: 10 * 1024 * 1024,
21
+ // 10MB
22
+ upstreamTimeoutMs: 12e4,
23
+ // 2 minutes (streaming can be slow)
24
+ costTracking: true,
25
+ budgetDaily: 0,
26
+ budgetMonthly: 0,
27
+ alertThreshold: 0.8,
28
+ auditLog: true,
29
+ logDir: ".cto/gateway",
30
+ dashboard: true,
31
+ dashboardPath: "/__cto"
32
+ };
33
+ var DEFAULT_ALLOWED_DOMAINS = /* @__PURE__ */ new Set([
34
+ "api.openai.com",
35
+ "api.anthropic.com",
36
+ "generativelanguage.googleapis.com",
37
+ "aiplatform.googleapis.com"
38
+ // Azure uses custom subdomains: *.openai.azure.com
39
+ ]);
40
+ var PRIVATE_IP_PATTERNS = [
41
+ /^127\./,
42
+ // Loopback
43
+ /^10\./,
44
+ // Class A private
45
+ /^172\.(1[6-9]|2\d|3[01])\./,
46
+ // Class B private
47
+ /^192\.168\./,
48
+ // Class C private
49
+ /^169\.254\./,
50
+ // Link-local (AWS metadata!)
51
+ /^0\./,
52
+ // Current network
53
+ /^::1$/,
54
+ // IPv6 loopback
55
+ /^f[cd]/i,
56
+ // IPv6 private
57
+ /^fe80:/i
58
+ // IPv6 link-local
59
+ ];
60
+ function isPrivateIP(ip) {
61
+ return PRIVATE_IP_PATTERNS.some((p) => p.test(ip));
62
+ }
63
+ function isAllowedTarget(hostname, config) {
64
+ if (config.allowedTargetDomains.length > 0) {
65
+ return config.allowedTargetDomains.some(
66
+ (d) => hostname === d || hostname.endsWith("." + d)
67
+ );
68
+ }
69
+ if (DEFAULT_ALLOWED_DOMAINS.has(hostname)) return true;
70
+ if (hostname.endsWith(".openai.azure.com")) return true;
71
+ return false;
72
+ }
73
+
74
+ // src/gateway/providers.ts
75
+ var OPENAI_MODELS = [
76
+ { id: "gpt-4o", contextWindow: 128e3, costPerMInput: 2.5, costPerMOutput: 10, maxOutput: 16384 },
77
+ { id: "gpt-4o-mini", contextWindow: 128e3, costPerMInput: 0.15, costPerMOutput: 0.6, maxOutput: 16384 },
78
+ { id: "gpt-4-turbo", contextWindow: 128e3, costPerMInput: 10, costPerMOutput: 30, maxOutput: 4096 },
79
+ { id: "gpt-3.5-turbo", contextWindow: 16385, costPerMInput: 0.5, costPerMOutput: 1.5, maxOutput: 4096 },
80
+ { id: "o1", contextWindow: 2e5, costPerMInput: 15, costPerMOutput: 60, maxOutput: 1e5 },
81
+ { id: "o1-mini", contextWindow: 128e3, costPerMInput: 3, costPerMOutput: 12, maxOutput: 65536 },
82
+ { id: "o3-mini", contextWindow: 2e5, costPerMInput: 1.1, costPerMOutput: 4.4, maxOutput: 1e5 }
83
+ ];
84
+ var ANTHROPIC_MODELS = [
85
+ { id: "claude-sonnet-4-20250514", contextWindow: 2e5, costPerMInput: 3, costPerMOutput: 15, maxOutput: 64e3 },
86
+ { id: "claude-3-5-haiku-20241022", contextWindow: 2e5, costPerMInput: 0.8, costPerMOutput: 4, maxOutput: 8192 },
87
+ { id: "claude-3-opus-20240229", contextWindow: 2e5, costPerMInput: 15, costPerMOutput: 75, maxOutput: 4096 }
88
+ ];
89
+ var GOOGLE_MODELS = [
90
+ { id: "gemini-2.5-pro", contextWindow: 1e6, costPerMInput: 1.25, costPerMOutput: 10, maxOutput: 65536 },
91
+ { id: "gemini-2.0-flash", contextWindow: 1e6, costPerMInput: 0.1, costPerMOutput: 0.4, maxOutput: 8192 },
92
+ { id: "gemini-1.5-pro", contextWindow: 2e6, costPerMInput: 1.25, costPerMOutput: 5, maxOutput: 8192 }
93
+ ];
94
+ function parseOpenAIRequest(body) {
95
+ const messages = (body.messages || []).map((m) => ({
96
+ role: m.role || "user",
97
+ content: typeof m.content === "string" ? m.content : JSON.stringify(m.content)
98
+ }));
99
+ return {
100
+ model: body.model || "unknown",
101
+ messages,
102
+ stream: body.stream === true,
103
+ maxTokens: body.max_tokens ?? body.max_completion_tokens,
104
+ temperature: body.temperature
105
+ };
106
+ }
107
+ function parseOpenAIResponse(body, streaming) {
108
+ if (streaming) {
109
+ return {
110
+ model: body.model || "unknown",
111
+ inputTokens: body.usage?.prompt_tokens || 0,
112
+ outputTokens: body.usage?.completion_tokens || 0,
113
+ content: body.choices?.[0]?.message?.content || "",
114
+ finishReason: body.choices?.[0]?.finish_reason || "stop"
115
+ };
116
+ }
117
+ return {
118
+ model: body.model || "unknown",
119
+ inputTokens: body.usage?.prompt_tokens || 0,
120
+ outputTokens: body.usage?.completion_tokens || 0,
121
+ content: body.choices?.[0]?.message?.content || "",
122
+ finishReason: body.choices?.[0]?.finish_reason || "stop"
123
+ };
124
+ }
125
+ function parseAnthropicRequest(body) {
126
+ const messages = [];
127
+ if (body.system) {
128
+ messages.push({ role: "system", content: body.system });
129
+ }
130
+ for (const m of body.messages || []) {
131
+ messages.push({
132
+ role: m.role || "user",
133
+ content: typeof m.content === "string" ? m.content : m.content?.map((b) => b.text || "").join("\n") || ""
134
+ });
135
+ }
136
+ return {
137
+ model: body.model || "unknown",
138
+ messages,
139
+ stream: body.stream === true,
140
+ maxTokens: body.max_tokens,
141
+ temperature: body.temperature
142
+ };
143
+ }
144
+ function parseAnthropicResponse(body, _streaming) {
145
+ return {
146
+ model: body.model || "unknown",
147
+ inputTokens: body.usage?.input_tokens || 0,
148
+ outputTokens: body.usage?.output_tokens || 0,
149
+ content: body.content?.map((b) => b.text || "").join("\n") || "",
150
+ finishReason: body.stop_reason || "end_turn"
151
+ };
152
+ }
153
+ function parseGoogleRequest(body) {
154
+ const messages = [];
155
+ if (body.systemInstruction?.parts) {
156
+ messages.push({
157
+ role: "system",
158
+ content: body.systemInstruction.parts.map((p) => p.text || "").join("\n")
159
+ });
160
+ }
161
+ for (const item of body.contents || []) {
162
+ const role = item.role === "model" ? "assistant" : "user";
163
+ const content = item.parts?.map((p) => p.text || "").join("\n") || "";
164
+ messages.push({ role, content });
165
+ }
166
+ const model = body.model || body.modelId || "gemini-2.0-flash";
167
+ return {
168
+ model,
169
+ messages,
170
+ stream: body.stream === true,
171
+ maxTokens: body.generationConfig?.maxOutputTokens,
172
+ temperature: body.generationConfig?.temperature
173
+ };
174
+ }
175
+ function parseGoogleResponse(body, _streaming) {
176
+ const candidate = body.candidates?.[0];
177
+ return {
178
+ model: body.modelVersion || body.model || "gemini-2.0-flash",
179
+ inputTokens: body.usageMetadata?.promptTokenCount || 0,
180
+ outputTokens: body.usageMetadata?.candidatesTokenCount || 0,
181
+ content: candidate?.content?.parts?.map((p) => p.text || "").join("\n") || "",
182
+ finishReason: candidate?.finishReason || "STOP"
183
+ };
184
+ }
185
+ var PROVIDERS = {
186
+ openai: {
187
+ name: "openai",
188
+ displayName: "OpenAI",
189
+ baseUrl: "https://api.openai.com",
190
+ authHeader: "Authorization",
191
+ chatPath: "/v1/chat/completions",
192
+ models: OPENAI_MODELS,
193
+ parseRequest: parseOpenAIRequest,
194
+ parseResponse: parseOpenAIResponse,
195
+ detectProvider: (url, _headers) => url.includes("api.openai.com") || url.includes("/v1/chat/completions")
196
+ },
197
+ anthropic: {
198
+ name: "anthropic",
199
+ displayName: "Anthropic",
200
+ baseUrl: "https://api.anthropic.com",
201
+ authHeader: "x-api-key",
202
+ chatPath: "/v1/messages",
203
+ models: ANTHROPIC_MODELS,
204
+ parseRequest: parseAnthropicRequest,
205
+ parseResponse: parseAnthropicResponse,
206
+ detectProvider: (url, headers) => url.includes("api.anthropic.com") || url.includes("/v1/messages") || !!headers["x-api-key"] || !!headers["anthropic-version"]
207
+ },
208
+ google: {
209
+ name: "google",
210
+ displayName: "Google AI",
211
+ baseUrl: "https://generativelanguage.googleapis.com",
212
+ authHeader: "x-goog-api-key",
213
+ chatPath: "/v1beta/models",
214
+ models: GOOGLE_MODELS,
215
+ parseRequest: parseGoogleRequest,
216
+ parseResponse: parseGoogleResponse,
217
+ detectProvider: (url, _headers) => url.includes("generativelanguage.googleapis.com") || url.includes("aiplatform.googleapis.com")
218
+ },
219
+ "azure-openai": {
220
+ name: "azure-openai",
221
+ displayName: "Azure OpenAI",
222
+ baseUrl: "",
223
+ authHeader: "api-key",
224
+ chatPath: "/openai/deployments",
225
+ models: OPENAI_MODELS,
226
+ // Same models, different hosting
227
+ parseRequest: parseOpenAIRequest,
228
+ parseResponse: parseOpenAIResponse,
229
+ detectProvider: (url, headers) => url.includes(".openai.azure.com") || !!headers["api-key"]
230
+ },
231
+ custom: {
232
+ name: "custom",
233
+ displayName: "Custom (OpenAI-compatible)",
234
+ baseUrl: "",
235
+ authHeader: "Authorization",
236
+ chatPath: "/v1/chat/completions",
237
+ models: [],
238
+ parseRequest: parseOpenAIRequest,
239
+ parseResponse: parseOpenAIResponse,
240
+ detectProvider: () => false
241
+ // Fallback only
242
+ }
243
+ };
244
+ function detectProvider(url, headers) {
245
+ for (const provider of Object.values(PROVIDERS)) {
246
+ if (provider.name === "custom") continue;
247
+ if (provider.detectProvider(url, headers)) return provider;
248
+ }
249
+ return PROVIDERS.custom;
250
+ }
251
+ function getModelConfig(provider, modelId) {
252
+ const exact = provider.models.find((m) => m.id === modelId);
253
+ if (exact) return exact;
254
+ return provider.models.find((m) => modelId.startsWith(m.id) || m.id.startsWith(modelId));
255
+ }
256
+ function estimateCost(provider, modelId, inputTokens, outputTokens) {
257
+ const model = getModelConfig(provider, modelId);
258
+ if (!model) return 0;
259
+ const inputCost = inputTokens / 1e6 * model.costPerMInput;
260
+ const outputCost = outputTokens / 1e6 * model.costPerMOutput;
261
+ return Math.round((inputCost + outputCost) * 1e6) / 1e6;
262
+ }
263
+
264
+ // src/govern/secrets.ts
265
+ import { readFile } from "fs/promises";
266
+ import { readFileSync, existsSync, mkdirSync, writeFileSync } from "fs";
267
+ import { resolve, relative, join, dirname } from "path";
268
+ import { createHash } from "crypto";
269
+ var BUILTIN_PATTERNS = [
270
+ // API Keys
271
+ { type: "api-key", source: `(?:api[_-]?key|apikey)\\s*[:=]\\s*['"]?([a-zA-Z0-9_\\-]{20,})['"]?`, flags: "gi", severity: "critical", description: "API Key" },
272
+ { type: "api-key", source: "sk-[a-zA-Z0-9]{20,}", flags: "g", severity: "critical", description: "OpenAI/Anthropic API Key" },
273
+ { type: "api-key", source: "sk-ant-[a-zA-Z0-9\\-]{20,}", flags: "g", severity: "critical", description: "Anthropic API Key" },
274
+ // AWS
275
+ { type: "aws-key", source: "AKIA[0-9A-Z]{16}", flags: "g", severity: "critical", description: "AWS Access Key ID" },
276
+ { type: "aws-key", source: `(?:aws_secret_access_key|aws_secret)\\s*[:=]\\s*['"]?([a-zA-Z0-9/+=]{40})['"]?`, flags: "gi", severity: "critical", description: "AWS Secret Key" },
277
+ // Private Keys
278
+ { type: "private-key", source: "-----BEGIN (?:RSA |EC |DSA )?PRIVATE KEY-----", flags: "g", severity: "critical", description: "Private Key" },
279
+ { type: "private-key", source: "-----BEGIN OPENSSH PRIVATE KEY-----", flags: "g", severity: "critical", description: "SSH Private Key" },
280
+ // Passwords
281
+ { type: "password", source: `(?:password|passwd|pwd)\\s*[:=]\\s*['"]([^'"]{8,})['"](?!\\s*\\{)`, flags: "gi", severity: "high", description: "Hardcoded Password" },
282
+ { type: "password", source: `(?:DB_PASSWORD|DATABASE_PASSWORD|MYSQL_PASSWORD|POSTGRES_PASSWORD)\\s*[:=]\\s*['"]?([^'"{}\\s]{4,})['"]?`, flags: "gi", severity: "high", description: "Database Password" },
283
+ // Tokens
284
+ { type: "token", source: `(?:bearer|token|auth_token|access_token|refresh_token)\\s*[:=]\\s*['"]([a-zA-Z0-9_\\-.]{20,})['"](?!\\s*\\{)`, flags: "gi", severity: "high", description: "Auth Token" },
285
+ { type: "token", source: "ghp_[a-zA-Z0-9]{36}", flags: "g", severity: "critical", description: "GitHub Personal Access Token" },
286
+ { type: "token", source: "gho_[a-zA-Z0-9]{36}", flags: "g", severity: "critical", description: "GitHub OAuth Token" },
287
+ { type: "token", source: "glpat-[a-zA-Z0-9\\-]{20,}", flags: "g", severity: "critical", description: "GitLab Personal Access Token" },
288
+ { type: "token", source: "npm_[a-zA-Z0-9]{36}", flags: "g", severity: "high", description: "npm Token" },
289
+ // Connection strings
290
+ { type: "connection-string", source: `(?:mongodb(?:\\+srv)?|postgres(?:ql)?|mysql|redis|amqp):\\/\\/[^\\s'"]+:[^\\s'"]+@[^\\s'"]+`, flags: "gi", severity: "critical", description: "Database Connection String" },
291
+ { type: "connection-string", source: `(?:DATABASE_URL|REDIS_URL|MONGODB_URI)\\s*[:=]\\s*['"]?([^\\s'"]{10,})['"]?`, flags: "gi", severity: "high", description: "Database URL" },
292
+ // Environment variables with secrets
293
+ { type: "env-variable", source: `(?:SECRET|PRIVATE|ENCRYPTION)[_-]?(?:KEY|TOKEN|PASS)\\s*[:=]\\s*['"]?([^\\s'"]{8,})['"]?`, flags: "gi", severity: "high", description: "Secret Environment Variable" },
294
+ // Stripe
295
+ { type: "api-key", source: "sk_live_[a-zA-Z0-9]{24,}", flags: "g", severity: "critical", description: "Stripe Live Secret Key" },
296
+ { type: "api-key", source: "pk_live_[a-zA-Z0-9]{24,}", flags: "g", severity: "high", description: "Stripe Live Publishable Key" },
297
+ { type: "api-key", source: "rk_live_[a-zA-Z0-9]{24,}", flags: "g", severity: "critical", description: "Stripe Restricted Key" },
298
+ // Slack
299
+ { type: "token", source: "xoxb-[0-9]{10,}-[0-9]{10,}-[a-zA-Z0-9]{24,}", flags: "g", severity: "critical", description: "Slack Bot Token" },
300
+ { type: "token", source: "xoxp-[0-9]{10,}-[0-9]{10,}-[a-zA-Z0-9]{24,}", flags: "g", severity: "critical", description: "Slack User Token" },
301
+ { type: "api-key", source: "https://hooks\\.slack\\.com/services/T[a-zA-Z0-9_]+/B[a-zA-Z0-9_]+/[a-zA-Z0-9_]+", flags: "g", severity: "high", description: "Slack Webhook URL" },
302
+ // Google
303
+ { type: "api-key", source: "AIza[0-9A-Za-z_-]{35}", flags: "g", severity: "high", description: "Google API Key" },
304
+ { type: "token", source: "ya29\\.[0-9A-Za-z_-]+", flags: "g", severity: "high", description: "Google OAuth Token" },
305
+ // Azure
306
+ { type: "api-key", source: "(?:AccountKey|SharedAccessKey)\\s*=\\s*[a-zA-Z0-9+/=]{40,}", flags: "g", severity: "critical", description: "Azure Storage Key" },
307
+ // Twilio
308
+ { type: "api-key", source: "AC[a-f0-9]{32}", flags: "g", severity: "high", description: "Twilio Account SID" },
309
+ // SendGrid
310
+ { type: "api-key", source: "SG\\.[a-zA-Z0-9_-]{22}\\.[a-zA-Z0-9_-]{43}", flags: "g", severity: "critical", description: "SendGrid API Key" },
311
+ // JWT
312
+ { type: "token", source: "eyJ[a-zA-Z0-9_-]{10,}\\.eyJ[a-zA-Z0-9_-]{10,}\\.[a-zA-Z0-9_-]{10,}", flags: "g", severity: "high", description: "JSON Web Token" },
313
+ // Datadog
314
+ { type: "api-key", source: `(?:DD_API_KEY|DATADOG_API_KEY)\\s*[:=]\\s*['"]?([a-f0-9]{32})['"]?`, flags: "gi", severity: "critical", description: "Datadog API Key" },
315
+ { type: "api-key", source: `(?:DD_APP_KEY|DATADOG_APP_KEY)\\s*[:=]\\s*['"]?([a-f0-9]{40})['"]?`, flags: "gi", severity: "critical", description: "Datadog App Key" },
316
+ // Sentry
317
+ { type: "connection-string", source: "https://[a-f0-9]{32}@[a-z0-9]+\\.ingest\\.sentry\\.io/[0-9]+", flags: "g", severity: "high", description: "Sentry DSN" },
318
+ // Firebase
319
+ { type: "api-key", source: `(?:FIREBASE_API_KEY|FIREBASE_KEY)\\s*[:=]\\s*['"]?([a-zA-Z0-9_\\-]{30,})['"]?`, flags: "gi", severity: "high", description: "Firebase API Key" },
320
+ { type: "connection-string", source: `firebase[a-z]*:\\/\\/[^\\s'"]+`, flags: "gi", severity: "high", description: "Firebase URL" },
321
+ // Supabase
322
+ { type: "api-key", source: "sbp_[a-f0-9]{40}", flags: "g", severity: "critical", description: "Supabase Service Key" },
323
+ { type: "token", source: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9\\.[a-zA-Z0-9_-]{20,}\\.[a-zA-Z0-9_-]{20,}", flags: "g", severity: "high", description: "Supabase Anon/Service JWT" },
324
+ // Vercel
325
+ { type: "token", source: `(?:VERCEL_TOKEN|VERCEL_API_TOKEN)\\s*[:=]\\s*['"]?([a-zA-Z0-9]{24,})['"]?`, flags: "gi", severity: "critical", description: "Vercel Token" },
326
+ // Heroku
327
+ { type: "api-key", source: `(?:HEROKU_API_KEY|HEROKU_TOKEN)\\s*[:=]\\s*['"]?([a-f0-9\\-]{36,})['"]?`, flags: "gi", severity: "critical", description: "Heroku API Key" },
328
+ // DigitalOcean
329
+ { type: "token", source: "dop_v1_[a-f0-9]{64}", flags: "g", severity: "critical", description: "DigitalOcean Personal Access Token" },
330
+ { type: "token", source: "doo_v1_[a-f0-9]{64}", flags: "g", severity: "critical", description: "DigitalOcean OAuth Token" },
331
+ // Mailgun
332
+ { type: "api-key", source: "key-[a-zA-Z0-9]{32}", flags: "g", severity: "high", description: "Mailgun API Key" },
333
+ // PII
334
+ { type: "pii", source: "\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}\\b", flags: "g", severity: "medium", description: "Email Address (PII)" },
335
+ { type: "pii", source: "\\b(?!000|666|9\\d{2})(\\d{3})[-.]?(?!00)(\\d{2})[-.]?(?!0000)(\\d{4})\\b", flags: "g", severity: "high", description: "Possible SSN (PII)" }
336
+ ];
337
+ var _cachedBuiltinPatterns = null;
338
+ function getBuiltinPatterns() {
339
+ if (!_cachedBuiltinPatterns) {
340
+ _cachedBuiltinPatterns = BUILTIN_PATTERNS.map((def) => ({
341
+ type: def.type,
342
+ pattern: new RegExp(def.source, def.flags),
343
+ severity: def.severity,
344
+ description: def.description
345
+ }));
346
+ }
347
+ return _cachedBuiltinPatterns;
348
+ }
349
+ function buildPatterns(customPatterns = []) {
350
+ const builtins = getBuiltinPatterns();
351
+ if (customPatterns.length === 0) return builtins;
352
+ const patterns = [...builtins];
353
+ for (const custom of customPatterns) {
354
+ try {
355
+ patterns.push({
356
+ type: "custom",
357
+ pattern: new RegExp(custom, "gi"),
358
+ severity: "medium",
359
+ description: `Custom pattern: ${custom}`
360
+ });
361
+ } catch {
362
+ }
363
+ }
364
+ return patterns;
365
+ }
366
+ function scanContentForSecrets(content, filePath, customPatterns = [], extraPiiSafeDomains) {
367
+ const findings = [];
368
+ const lines = content.split("\n");
369
+ const allPatterns = buildPatterns(customPatterns);
370
+ for (const secretPattern of allPatterns) {
371
+ for (let i = 0; i < lines.length; i++) {
372
+ const line = lines[i];
373
+ secretPattern.pattern.lastIndex = 0;
374
+ let match;
375
+ while ((match = secretPattern.pattern.exec(line)) !== null) {
376
+ const matchText = match[0];
377
+ if (isTemplateOrPlaceholder(matchText)) continue;
378
+ if (secretPattern.type === "pii" && isSafeEmail(matchText, extraPiiSafeDomains)) continue;
379
+ findings.push({
380
+ type: secretPattern.type,
381
+ file: filePath,
382
+ line: i + 1,
383
+ match: matchText,
384
+ redacted: redactSecret(matchText),
385
+ severity: secretPattern.severity
386
+ });
387
+ }
388
+ }
389
+ }
390
+ return deduplicateFindings(findings);
391
+ }
392
+ async function scanFileForSecrets(filePath, projectPath, customPatterns = []) {
393
+ try {
394
+ const content = await readFile(filePath, "utf-8");
395
+ const relPath = relative(resolve(projectPath), resolve(filePath));
396
+ return scanContentForSecrets(content, relPath, customPatterns);
397
+ } catch {
398
+ return [];
399
+ }
400
+ }
401
+ function sanitizeContent(content, customPatterns = []) {
402
+ let sanitized = content;
403
+ const allPatterns = buildPatterns(customPatterns);
404
+ for (const secretPattern of allPatterns) {
405
+ sanitized = sanitized.replace(secretPattern.pattern, (match) => {
406
+ if (isTemplateOrPlaceholder(match)) return match;
407
+ return redactSecret(match);
408
+ });
409
+ }
410
+ return sanitized;
411
+ }
412
+ function redactSecret(value) {
413
+ if (value.length <= 8) return "***REDACTED***";
414
+ const prefix = value.substring(0, 4);
415
+ const suffix = value.substring(value.length - 2);
416
+ return `${prefix}${"*".repeat(Math.min(value.length - 6, 20))}${suffix}`;
417
+ }
418
+ function isTemplateOrPlaceholder(value) {
419
+ const placeholders = [
420
+ /\$\{.*\}/,
421
+ /\{\{.*\}\}/,
422
+ /%[sd]/,
423
+ /<[A-Z_]+>/,
424
+ /YOUR_.*_HERE/i,
425
+ /\bCHANGE_ME\b/i,
426
+ /\bPLACEHOLDER\b/i,
427
+ /\bexample\b/i,
428
+ /\bTODO\b/i,
429
+ /xxx+/i,
430
+ /\breplace.?me\b/i,
431
+ /\bdummy\b/i,
432
+ /\btest_?key\b/i,
433
+ /\bsample\b/i
434
+ ];
435
+ return placeholders.some((p) => p.test(value));
436
+ }
437
+ var PII_SAFE_EMAIL_DOMAINS = /* @__PURE__ */ new Set([
438
+ "example.com",
439
+ "example.org",
440
+ "example.net",
441
+ "test.com",
442
+ "test.org",
443
+ "test.net",
444
+ "localhost",
445
+ "localhost.localdomain",
446
+ "email.com",
447
+ "mail.com",
448
+ "foo.com",
449
+ "bar.com",
450
+ "baz.com",
451
+ "acme.com",
452
+ "company.com",
453
+ "corp.com",
454
+ "noreply.com",
455
+ "no-reply.com",
456
+ "users.noreply.github.com",
457
+ "placeholder.com"
458
+ ]);
459
+ function isSafeEmail(value, extraDomains) {
460
+ const match = value.match(/@([a-zA-Z0-9.-]+)$/);
461
+ if (!match) return false;
462
+ const domain = match[1].toLowerCase();
463
+ if (PII_SAFE_EMAIL_DOMAINS.has(domain)) return true;
464
+ if (extraDomains && extraDomains.has(domain)) return true;
465
+ return false;
466
+ }
467
+ function deduplicateFindings(findings) {
468
+ const seen = /* @__PURE__ */ new Set();
469
+ return findings.filter((f) => {
470
+ const key = `${f.file}:${f.line}:${f.type}:${f.match}`;
471
+ if (seen.has(key)) return false;
472
+ seen.add(key);
473
+ return true;
474
+ });
475
+ }
476
+
477
+ // src/engine/selector.ts
478
+ import { createHash as createHash2 } from "crypto";
479
+
480
+ // src/engine/pruner.ts
481
+ import { Project, SyntaxKind } from "ts-morph";
482
+ import { readFile as readFile3 } from "fs/promises";
483
+ import { existsSync as existsSync2 } from "fs";
484
+ import { join as join2 } from "path";
485
+
486
+ // src/engine/tokenizer.ts
487
+ import { encodingForModel } from "js-tiktoken";
488
+ import { readFile as readFile2, stat } from "fs/promises";
489
+ var CHARS_PER_TOKEN = 4;
490
+ var encoder = null;
491
+ function getEncoder() {
492
+ if (!encoder) {
493
+ encoder = encodingForModel("claude-3-5-sonnet-20241022");
494
+ }
495
+ return encoder;
496
+ }
497
+ function countTokensTiktoken(text) {
498
+ try {
499
+ const enc = getEncoder();
500
+ const tokens = enc.encode(text);
501
+ return tokens.length;
502
+ } catch {
503
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
504
+ }
505
+ }
506
+ function countTokensChars4(sizeInBytes) {
507
+ return Math.ceil(sizeInBytes / CHARS_PER_TOKEN);
508
+ }
509
+ function estimateTokens(content, sizeInBytes, method = "chars4") {
510
+ if (method === "tiktoken") {
511
+ return countTokensTiktoken(content);
512
+ }
513
+ return countTokensChars4(sizeInBytes);
514
+ }
515
+
516
+ // src/engine/pruner.ts
517
+ var TS_EXTENSIONS = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mts", "mjs"]);
518
+ async function pruneFile(file, level) {
519
+ if (level === "excluded") {
520
+ return emptyResult(file, "excluded");
521
+ }
522
+ if (level === "full") {
523
+ return fullContent(file);
524
+ }
525
+ const ext = file.extension.toLowerCase();
526
+ const isTS = TS_EXTENSIONS.has(ext);
527
+ if (isTS) {
528
+ return pruneTypeScript(file, level);
529
+ }
530
+ return pruneGeneric(file, level);
531
+ }
532
+ async function pruneTypeScript(file, level) {
533
+ let content;
534
+ try {
535
+ content = await readFile3(file.path, "utf-8");
536
+ } catch {
537
+ return emptyResult(file, level);
538
+ }
539
+ let project;
540
+ try {
541
+ const tsConfigPath = findTsConfig(file.path);
542
+ project = new Project({
543
+ tsConfigFilePath: tsConfigPath,
544
+ skipAddingFilesFromTsConfig: true,
545
+ compilerOptions: tsConfigPath ? void 0 : { allowJs: true, esModuleInterop: true }
546
+ });
547
+ project.createSourceFile(file.path, content, { overwrite: true });
548
+ } catch {
549
+ return pruneGenericFromContent(file, content, level);
550
+ }
551
+ const sourceFile = project.getSourceFiles()[0];
552
+ if (!sourceFile) {
553
+ return pruneGenericFromContent(file, content, level);
554
+ }
555
+ const prunedContent = level === "signatures" ? extractSignaturesAST(sourceFile) : extractSkeletonAST(sourceFile);
556
+ const prunedTokens = countTokensChars4(Buffer.byteLength(prunedContent, "utf-8"));
557
+ const savingsPercent = file.tokens > 0 ? (file.tokens - prunedTokens) / file.tokens * 100 : 0;
558
+ return {
559
+ relativePath: file.relativePath,
560
+ originalTokens: file.tokens,
561
+ prunedTokens,
562
+ pruneLevel: level,
563
+ content: prunedContent,
564
+ savingsPercent: Math.max(0, savingsPercent)
565
+ };
566
+ }
567
+ function extractSignaturesAST(sf) {
568
+ const parts = [];
569
+ for (const imp of sf.getImportDeclarations()) {
570
+ parts.push(imp.getText());
571
+ }
572
+ if (parts.length > 0) parts.push("");
573
+ for (const ta of sf.getTypeAliases()) {
574
+ addJSDoc(ta, parts);
575
+ parts.push(ta.getText());
576
+ }
577
+ for (const iface of sf.getInterfaces()) {
578
+ addJSDoc(iface, parts);
579
+ parts.push(iface.getText());
580
+ }
581
+ for (const en of sf.getEnums()) {
582
+ addJSDoc(en, parts);
583
+ parts.push(en.getText());
584
+ }
585
+ for (const fn of sf.getFunctions()) {
586
+ addJSDoc(fn, parts);
587
+ const isExported = fn.isExported();
588
+ const isAsync = fn.isAsync();
589
+ const name = fn.getName() ?? "<anonymous>";
590
+ const params = fn.getParameters().map((p) => p.getText()).join(", ");
591
+ const returnType = fn.getReturnTypeNode()?.getText();
592
+ const returnStr = returnType ? `: ${returnType}` : "";
593
+ const prefix = isExported ? "export " : "";
594
+ const asyncStr = isAsync ? "async " : "";
595
+ parts.push(`${prefix}${asyncStr}function ${name}(${params})${returnStr} { /* ... */ }`);
596
+ }
597
+ for (const stmt of sf.getVariableStatements()) {
598
+ for (const decl of stmt.getDeclarations()) {
599
+ const init = decl.getInitializer();
600
+ if (init && (init.getKind() === SyntaxKind.ArrowFunction || init.getKind() === SyntaxKind.FunctionExpression)) {
601
+ addJSDoc(stmt, parts);
602
+ const isExported = stmt.isExported();
603
+ const prefix = isExported ? "export " : "";
604
+ const kind = stmt.getDeclarationKind();
605
+ const name = decl.getName();
606
+ const typeNode = decl.getTypeNode()?.getText();
607
+ const typeStr = typeNode ? `: ${typeNode}` : "";
608
+ parts.push(`${prefix}${kind} ${name}${typeStr} = /* ... */;`);
609
+ } else {
610
+ addJSDoc(stmt, parts);
611
+ parts.push(stmt.getText());
612
+ }
613
+ }
614
+ }
615
+ for (const cls of sf.getClasses()) {
616
+ addJSDoc(cls, parts);
617
+ const isExported = cls.isExported();
618
+ const prefix = isExported ? "export " : "";
619
+ const name = cls.getName() ?? "<anonymous>";
620
+ const ext = cls.getExtends()?.getText();
621
+ const impl = cls.getImplements().map((i) => i.getText()).join(", ");
622
+ let header = `${prefix}class ${name}`;
623
+ if (ext) header += ` extends ${ext}`;
624
+ if (impl) header += ` implements ${impl}`;
625
+ header += " {";
626
+ parts.push(header);
627
+ for (const prop of cls.getProperties()) {
628
+ parts.push(` ${prop.getText()}`);
629
+ }
630
+ const ctor = cls.getConstructors()[0];
631
+ if (ctor) {
632
+ const ctorParams = ctor.getParameters().map((p) => p.getText()).join(", ");
633
+ parts.push(` constructor(${ctorParams}) { /* ... */ }`);
634
+ }
635
+ for (const method of cls.getMethods()) {
636
+ const isStatic = method.isStatic();
637
+ const isAsync = method.isAsync();
638
+ const methodName = method.getName();
639
+ const methodParams = method.getParameters().map((p) => p.getText()).join(", ");
640
+ const returnType = method.getReturnTypeNode()?.getText();
641
+ const returnStr = returnType ? `: ${returnType}` : "";
642
+ const staticStr = isStatic ? "static " : "";
643
+ const asyncStr = isAsync ? "async " : "";
644
+ parts.push(` ${staticStr}${asyncStr}${methodName}(${methodParams})${returnStr} { /* ... */ }`);
645
+ }
646
+ parts.push("}");
647
+ }
648
+ for (const exp of sf.getExportDeclarations()) {
649
+ parts.push(exp.getText());
650
+ }
651
+ for (const exp of sf.getExportAssignments()) {
652
+ parts.push(exp.getText());
653
+ }
654
+ return parts.join("\n");
655
+ }
656
+ function extractSkeletonAST(sf) {
657
+ const parts = [];
658
+ for (const imp of sf.getImportDeclarations()) {
659
+ parts.push(imp.getText());
660
+ }
661
+ if (parts.length > 0) parts.push("");
662
+ for (const ta of sf.getTypeAliases()) {
663
+ if (ta.isExported()) parts.push(ta.getText());
664
+ }
665
+ for (const iface of sf.getInterfaces()) {
666
+ if (!iface.isExported()) continue;
667
+ const ext = iface.getExtends().map((e) => e.getText());
668
+ const extStr = ext.length > 0 ? ` extends ${ext.join(", ")}` : "";
669
+ parts.push(`export interface ${iface.getName()}${extStr} { /* ${iface.getProperties().length} props */ }`);
670
+ }
671
+ for (const en of sf.getEnums()) {
672
+ if (!en.isExported()) continue;
673
+ const members = en.getMembers().map((m) => m.getName());
674
+ parts.push(`export enum ${en.getName()} { ${members.join(", ")} }`);
675
+ }
676
+ for (const fn of sf.getFunctions()) {
677
+ if (!fn.isExported()) continue;
678
+ const name = fn.getName() ?? "<anonymous>";
679
+ const params = fn.getParameters().map((p) => p.getText()).join(", ");
680
+ parts.push(`export function ${name}(${params});`);
681
+ }
682
+ for (const cls of sf.getClasses()) {
683
+ if (!cls.isExported()) continue;
684
+ const methods = cls.getMethods().map((m) => m.getName());
685
+ parts.push(`export class ${cls.getName()} { /* methods: ${methods.join(", ")} */ }`);
686
+ }
687
+ for (const exp of sf.getExportDeclarations()) {
688
+ parts.push(exp.getText());
689
+ }
690
+ return parts.join("\n");
691
+ }
692
+ async function pruneGeneric(file, level) {
693
+ let content;
694
+ try {
695
+ content = await readFile3(file.path, "utf-8");
696
+ } catch {
697
+ return emptyResult(file, level);
698
+ }
699
+ return pruneGenericFromContent(file, content, level);
700
+ }
701
+ function pruneGenericFromContent(file, content, level) {
702
+ const lines = content.split("\n");
703
+ let result;
704
+ if (level === "signatures") {
705
+ result = lines.filter((line) => {
706
+ const t = line.trim();
707
+ return t === "" || t.startsWith("#") || t.startsWith("//") || t.startsWith("import ") || t.startsWith("from ") || t.startsWith("export ") || t.startsWith("def ") || t.startsWith("async def ") || t.startsWith("class ") || t.startsWith("function ") || t.startsWith("const ") || t.startsWith("let ") || t.startsWith("var ") || /^(pub |fn |struct |enum |impl |mod |use )/.test(t);
708
+ });
709
+ } else {
710
+ result = lines.filter((line) => {
711
+ const t = line.trim();
712
+ return t.startsWith("import ") || t.startsWith("from ") || t.startsWith("export ") || t.startsWith("def ") || t.startsWith("class ") || t.startsWith("function ") || /^(pub |fn |struct |enum |mod |use )/.test(t);
713
+ });
714
+ }
715
+ const prunedContent = result.join("\n");
716
+ const prunedTokens = countTokensChars4(Buffer.byteLength(prunedContent, "utf-8"));
717
+ const savingsPercent = file.tokens > 0 ? (file.tokens - prunedTokens) / file.tokens * 100 : 0;
718
+ return {
719
+ relativePath: file.relativePath,
720
+ originalTokens: file.tokens,
721
+ prunedTokens,
722
+ pruneLevel: level,
723
+ content: prunedContent,
724
+ savingsPercent: Math.max(0, savingsPercent)
725
+ };
726
+ }
727
+ async function fullContent(file) {
728
+ let content = "";
729
+ try {
730
+ content = await readFile3(file.path, "utf-8");
731
+ } catch {
732
+ }
733
+ return {
734
+ relativePath: file.relativePath,
735
+ originalTokens: file.tokens,
736
+ prunedTokens: file.tokens,
737
+ pruneLevel: "full",
738
+ content,
739
+ savingsPercent: 0
740
+ };
741
+ }
742
+ function emptyResult(file, level) {
743
+ return {
744
+ relativePath: file.relativePath,
745
+ originalTokens: file.tokens,
746
+ prunedTokens: 0,
747
+ pruneLevel: level,
748
+ content: "",
749
+ savingsPercent: 100
750
+ };
751
+ }
752
+ function addJSDoc(node, parts) {
753
+ if (!node.getJsDocs) return;
754
+ const docs = node.getJsDocs();
755
+ if (docs.length > 0) {
756
+ parts.push(docs[0].getText());
757
+ }
758
+ }
759
+ function findTsConfig(filePath) {
760
+ let dir = filePath;
761
+ for (let i = 0; i < 10; i++) {
762
+ dir = join2(dir, "..");
763
+ const candidate = join2(dir, "tsconfig.json");
764
+ if (existsSync2(candidate)) return candidate;
765
+ }
766
+ return void 0;
767
+ }
768
+
769
+ // src/engine/graph-utils.ts
770
+ function buildAdjacencyList(edges) {
771
+ const forward = /* @__PURE__ */ new Map();
772
+ const reverse = /* @__PURE__ */ new Map();
773
+ for (const edge of edges) {
774
+ if (!forward.has(edge.from)) forward.set(edge.from, []);
775
+ forward.get(edge.from).push(edge.to);
776
+ if (!reverse.has(edge.to)) reverse.set(edge.to, []);
777
+ reverse.get(edge.to).push(edge.from);
778
+ }
779
+ return { forward, reverse };
780
+ }
781
+ function bfsBidirectional(seeds, adj, depth) {
782
+ const result = new Set(seeds);
783
+ let frontier = [...seeds];
784
+ const visited = /* @__PURE__ */ new Set();
785
+ for (let d = 0; d < depth; d++) {
786
+ const nextFrontier = [];
787
+ for (const node of frontier) {
788
+ if (visited.has(node)) continue;
789
+ visited.add(node);
790
+ const fwd = adj.forward.get(node);
791
+ if (fwd) {
792
+ for (const neighbor of fwd) {
793
+ if (!visited.has(neighbor)) {
794
+ result.add(neighbor);
795
+ nextFrontier.push(neighbor);
796
+ }
797
+ }
798
+ }
799
+ const rev = adj.reverse.get(node);
800
+ if (rev) {
801
+ for (const neighbor of rev) {
802
+ if (!visited.has(neighbor)) {
803
+ result.add(neighbor);
804
+ nextFrontier.push(neighbor);
805
+ }
806
+ }
807
+ }
808
+ }
809
+ frontier = nextFrontier;
810
+ }
811
+ return result;
812
+ }
813
+ function matchGlob(path, pattern) {
814
+ const regexStr = pattern.replace(/\./g, "\\.").replace(/\*\*/g, "\xA7\xA7").replace(/\*/g, "[^/]*").replace(/§§/g, ".*").replace(/\?/g, ".");
815
+ try {
816
+ return new RegExp(`^${regexStr}$`).test(path);
817
+ } catch {
818
+ return false;
819
+ }
820
+ }
821
+
822
+ // src/engine/coverage.ts
823
+ function calculateCoverage(targetPaths, includedPaths, allFiles, graph, depth = 2) {
824
+ const adj = buildAdjacencyList(graph.edges);
825
+ const relevantSet = targetPaths.length > 0 ? bfsBidirectional(targetPaths, adj, depth) : /* @__PURE__ */ new Set();
826
+ const includedSet = new Set(includedPaths);
827
+ const tempFileMap = new Map(allFiles.map((f) => [f.relativePath, f]));
828
+ for (const path of includedPaths) {
829
+ const file = tempFileMap.get(path);
830
+ if (!file) continue;
831
+ for (const imp of file.imports) {
832
+ const impFile = tempFileMap.get(imp);
833
+ if (impFile && impFile.kind === "type") {
834
+ relevantSet.add(imp);
835
+ }
836
+ }
837
+ }
838
+ const relevantFiles = Array.from(relevantSet);
839
+ const includedRelevant = relevantFiles.filter((f) => includedSet.has(f));
840
+ const missingRelevant = relevantFiles.filter((f) => !includedSet.has(f));
841
+ const missingCritical = missingRelevant.filter((f) => {
842
+ const file = tempFileMap.get(f);
843
+ return file && (file.exclusionImpact === "critical" || file.exclusionImpact === "high");
844
+ });
845
+ const fileMap = new Map(allFiles.map((f) => [f.relativePath, f]));
846
+ let totalRelevantRisk = 0;
847
+ let includedRelevantRisk = 0;
848
+ for (const f of relevantFiles) {
849
+ const risk = fileMap.get(f)?.riskScore ?? 1;
850
+ totalRelevantRisk += risk;
851
+ if (includedSet.has(f)) {
852
+ includedRelevantRisk += risk;
853
+ }
854
+ }
855
+ const score = totalRelevantRisk > 0 ? Math.round(includedRelevantRisk / totalRelevantRisk * 100) : relevantFiles.length > 0 ? Math.round(includedRelevant.length / relevantFiles.length * 100) : 100;
856
+ let explanation;
857
+ if (score >= 90) {
858
+ explanation = `Excellent coverage (${score}%): AI has nearly all relevant context.`;
859
+ } else if (score >= 70) {
860
+ explanation = `Good coverage (${score}%): Most relevant files included.`;
861
+ if (missingCritical.length > 0) {
862
+ explanation += ` Warning: ${missingCritical.length} critical file(s) missing.`;
863
+ }
864
+ } else if (score >= 50) {
865
+ explanation = `Partial coverage (${score}%): Significant context is missing.`;
866
+ if (missingCritical.length > 0) {
867
+ explanation += ` ${missingCritical.length} critical file(s) not included \u2014 AI quality will degrade.`;
868
+ }
869
+ } else {
870
+ explanation = `Low coverage (${score}%): Most relevant files are excluded. AI response quality will be poor.`;
871
+ }
872
+ return {
873
+ score,
874
+ relevantFiles,
875
+ includedRelevant,
876
+ missingRelevant,
877
+ missingCritical,
878
+ explanation
879
+ };
880
+ }
881
+
882
+ // src/engine/budget.ts
883
+ function getPruneLevelForRisk(riskScore) {
884
+ if (riskScore >= 80) return "full";
885
+ if (riskScore >= 60) return "full";
886
+ if (riskScore >= 30) return "signatures";
887
+ return "skeleton";
888
+ }
889
+
890
+ // src/engine/selector.ts
891
+ async function selectContext(input) {
892
+ const { task, analysis, budget, policies, depth = 2 } = input;
893
+ const decisions = [];
894
+ const targetPaths = identifyTargetFiles(task, analysis.files);
895
+ if (targetPaths.length > 0) {
896
+ decisions.push({
897
+ file: targetPaths.join(", "),
898
+ action: "include-full",
899
+ reason: `Target file(s) identified from task description`
900
+ });
901
+ }
902
+ const adj = buildAdjacencyList(analysis.graph.edges);
903
+ const expandedPaths = targetPaths.length > 0 ? Array.from(bfsBidirectional(targetPaths, adj, depth)) : [];
904
+ const expansionCount = expandedPaths.length - targetPaths.length;
905
+ if (expansionCount > 0) {
906
+ decisions.push({
907
+ file: `${expansionCount} dependencies`,
908
+ action: "include-full",
909
+ reason: `Expanded ${targetPaths.length} target(s) to ${expandedPaths.length} files via dependency graph (depth ${depth})`
910
+ });
911
+ }
912
+ const allFileMap = new Map(analysis.files.map((f) => [f.relativePath, f]));
913
+ if (targetPaths.length > 0) {
914
+ for (const path of expandedPaths) {
915
+ const file = allFileMap.get(path);
916
+ if (!file) continue;
917
+ for (const imp of file.imports) {
918
+ const impFile = allFileMap.get(imp);
919
+ if (impFile && impFile.kind === "type") {
920
+ expandedPaths.push(imp);
921
+ }
922
+ }
923
+ }
924
+ }
925
+ const { mustInclude, mustExclude } = applyPolicies(analysis.files, policies);
926
+ const candidateSet = /* @__PURE__ */ new Set([...expandedPaths, ...mustInclude]);
927
+ if (targetPaths.length === 0) {
928
+ for (const f of analysis.files) {
929
+ candidateSet.add(f.relativePath);
930
+ }
931
+ }
932
+ for (const ex of mustExclude) {
933
+ candidateSet.delete(ex);
934
+ decisions.push({
935
+ file: ex,
936
+ action: "exclude",
937
+ reason: "Excluded by policy"
938
+ });
939
+ }
940
+ const hasSecretBlock = policies?.rules.some(
941
+ (r) => r.type === "secret-block" && r.enabled
942
+ );
943
+ if (hasSecretBlock) {
944
+ for (const path of Array.from(candidateSet)) {
945
+ const file = allFileMap.get(path);
946
+ if (!file) continue;
947
+ const findings = await scanFileForSecrets(
948
+ file.path,
949
+ analysis.projectPath
950
+ );
951
+ if (findings.length > 0) {
952
+ candidateSet.delete(path);
953
+ decisions.push({
954
+ file: path,
955
+ action: "exclude",
956
+ reason: `Blocked: ${findings.length} secret(s) detected (${findings.map((f) => f.type).join(", ")})`
957
+ });
958
+ }
959
+ }
960
+ }
961
+ const candidates = Array.from(candidateSet).map((p) => allFileMap.get(p)).filter((f) => f !== void 0).sort((a, b) => {
962
+ const aIsTarget = targetPaths.includes(a.relativePath) ? 0 : 1;
963
+ const bIsTarget = targetPaths.includes(b.relativePath) ? 0 : 1;
964
+ if (aIsTarget !== bIsTarget) return aIsTarget - bIsTarget;
965
+ const aIsMust = mustInclude.has(a.relativePath) ? 0 : 1;
966
+ const bIsMust = mustInclude.has(b.relativePath) ? 0 : 1;
967
+ if (aIsMust !== bIsMust) return aIsMust - bIsMust;
968
+ return b.riskScore - a.riskScore;
969
+ });
970
+ const selectedFiles = [];
971
+ let usedTokens = 0;
972
+ for (const file of candidates) {
973
+ const isTarget = targetPaths.includes(file.relativePath);
974
+ const isMustInclude = mustInclude.has(file.relativePath);
975
+ const defaultLevel = isTarget ? "full" : getPruneLevelForRisk(file.riskScore);
976
+ const levels = getCascadeLevels(defaultLevel);
977
+ let included = false;
978
+ for (const level of levels) {
979
+ if (level === "excluded") break;
980
+ let tokens;
981
+ if (level === "full") {
982
+ tokens = file.tokens;
983
+ } else {
984
+ const pruned = await pruneFile(file, level);
985
+ tokens = pruned.prunedTokens;
986
+ }
987
+ if (usedTokens + tokens <= budget) {
988
+ usedTokens += tokens;
989
+ selectedFiles.push({
990
+ relativePath: file.relativePath,
991
+ tokens,
992
+ originalTokens: file.tokens,
993
+ pruneLevel: level,
994
+ riskScore: file.riskScore,
995
+ reason: buildReason(file, level, isTarget, isMustInclude)
996
+ });
997
+ if (level !== defaultLevel) {
998
+ decisions.push({
999
+ file: file.relativePath,
1000
+ action: `include-${level}`,
1001
+ reason: `Downgraded from ${defaultLevel} to ${level} due to budget constraint`,
1002
+ alternatives: `Would need ${file.tokens - tokens} more tokens for ${defaultLevel}`
1003
+ });
1004
+ }
1005
+ included = true;
1006
+ break;
1007
+ }
1008
+ }
1009
+ if (!included) {
1010
+ decisions.push({
1011
+ file: file.relativePath,
1012
+ action: "exclude",
1013
+ reason: `Budget exhausted (risk: ${file.riskScore}, needs ${file.tokens} tokens)`
1014
+ });
1015
+ }
1016
+ }
1017
+ const includedPaths = selectedFiles.map((f) => f.relativePath);
1018
+ const coverage = calculateCoverage(
1019
+ targetPaths,
1020
+ includedPaths,
1021
+ analysis.files,
1022
+ analysis.graph,
1023
+ depth
1024
+ );
1025
+ const includedSet = new Set(includedPaths);
1026
+ const excludedFiles = analysis.files.filter(
1027
+ (f) => !includedSet.has(f.relativePath)
1028
+ );
1029
+ const excludedRisk = excludedFiles.length > 0 ? Math.round(excludedFiles.reduce((s, f) => s + f.riskScore, 0) / excludedFiles.length) : 0;
1030
+ const hashInput = selectedFiles.map((f) => `${f.relativePath}:${f.pruneLevel}`).sort().join("|") + `|budget:${budget}`;
1031
+ const hash = createHash2("sha256").update(hashInput).digest("hex").substring(0, 16);
1032
+ return {
1033
+ files: selectedFiles,
1034
+ totalTokens: usedTokens,
1035
+ budget,
1036
+ usedPercent: budget > 0 ? Math.round(usedTokens / budget * 100 * 10) / 10 : 0,
1037
+ coverage,
1038
+ riskScore: excludedRisk,
1039
+ deterministic: true,
1040
+ hash,
1041
+ decisions
1042
+ };
1043
+ }
1044
+ function identifyTargetFiles(task, files) {
1045
+ const targets = [];
1046
+ const pathPattern = /(?:^|\s|["'`])([.\w/-]+\.[a-zA-Z]{1,4})(?:\s|$|["'`]|,|:)/g;
1047
+ let match;
1048
+ while ((match = pathPattern.exec(task)) !== null) {
1049
+ const candidate = match[1];
1050
+ const found = files.find(
1051
+ (f) => f.relativePath === candidate || f.relativePath.endsWith(candidate)
1052
+ );
1053
+ if (found && !targets.includes(found.relativePath)) {
1054
+ targets.push(found.relativePath);
1055
+ }
1056
+ }
1057
+ return targets;
1058
+ }
1059
+ function applyPolicies(files, policies) {
1060
+ const mustInclude = /* @__PURE__ */ new Set();
1061
+ const mustExclude = /* @__PURE__ */ new Set();
1062
+ if (!policies) return { mustInclude, mustExclude };
1063
+ for (const rule of policies.rules) {
1064
+ if (!rule.enabled) continue;
1065
+ if (rule.type === "include-always" && rule.pattern) {
1066
+ for (const file of files) {
1067
+ if (matchGlob(file.relativePath, rule.pattern)) {
1068
+ mustInclude.add(file.relativePath);
1069
+ }
1070
+ }
1071
+ }
1072
+ if (rule.type === "exclude-always" && rule.pattern) {
1073
+ for (const file of files) {
1074
+ if (matchGlob(file.relativePath, rule.pattern)) {
1075
+ mustExclude.add(file.relativePath);
1076
+ }
1077
+ }
1078
+ }
1079
+ }
1080
+ return { mustInclude, mustExclude };
1081
+ }
1082
+ function getCascadeLevels(startLevel) {
1083
+ const all = ["full", "signatures", "skeleton", "excluded"];
1084
+ const startIdx = all.indexOf(startLevel);
1085
+ return all.slice(startIdx);
1086
+ }
1087
+ function buildReason(file, level, isTarget, isMustInclude) {
1088
+ if (isTarget) return "Target file";
1089
+ if (isMustInclude) return "Required by policy";
1090
+ const impact = file.exclusionImpact;
1091
+ const levelStr = level === "full" ? "full content" : level;
1092
+ if (impact === "critical") return `Critical dependency (risk ${file.riskScore}) \u2014 ${levelStr}`;
1093
+ if (impact === "high") return `High-risk dependency (risk ${file.riskScore}) \u2014 ${levelStr}`;
1094
+ if (impact === "medium") return `Medium relevance (risk ${file.riskScore}) \u2014 ${levelStr}`;
1095
+ return `Low relevance (risk ${file.riskScore}) \u2014 ${levelStr}`;
1096
+ }
1097
+
1098
+ // src/gateway/interceptor.ts
1099
+ import { readFileSync as readFileSync2 } from "fs";
1100
+ import { resolve as resolve2 } from "path";
1101
+ function estimateTokensFromString(s) {
1102
+ return Math.ceil(Buffer.byteLength(s, "utf-8") / 4);
1103
+ }
1104
+ async function interceptRequest(messages, config, analysis) {
1105
+ const decisions = [];
1106
+ let secretsRedacted = 0;
1107
+ let secretsBlocked = false;
1108
+ let contextInjected = false;
1109
+ const originalTokens = messages.reduce((sum, m) => sum + estimateTokensFromString(m.content), 0);
1110
+ let processedMessages = messages;
1111
+ if (config.redactSecrets || config.blockOnSecrets) {
1112
+ const { messages: scannedMessages, redactedCount, blocked, scanDecisions } = scanMessages(messages, config);
1113
+ processedMessages = scannedMessages;
1114
+ secretsRedacted = redactedCount;
1115
+ secretsBlocked = blocked;
1116
+ decisions.push(...scanDecisions);
1117
+ if (blocked) {
1118
+ return {
1119
+ modified: true,
1120
+ messages: processedMessages,
1121
+ originalTokens,
1122
+ optimizedTokens: 0,
1123
+ secretsRedacted,
1124
+ secretsBlocked: true,
1125
+ contextInjected: false,
1126
+ decisions
1127
+ };
1128
+ }
1129
+ }
1130
+ if (config.optimize && analysis) {
1131
+ const { messages: optimizedMessages, injected, optimizeDecisions } = await optimizeContext(processedMessages, analysis, config);
1132
+ processedMessages = optimizedMessages;
1133
+ contextInjected = injected;
1134
+ decisions.push(...optimizeDecisions);
1135
+ }
1136
+ const optimizedTokens = processedMessages.reduce((sum, m) => sum + estimateTokensFromString(m.content), 0);
1137
+ return {
1138
+ modified: secretsRedacted > 0 || contextInjected,
1139
+ messages: processedMessages,
1140
+ originalTokens,
1141
+ optimizedTokens,
1142
+ secretsRedacted,
1143
+ secretsBlocked,
1144
+ contextInjected,
1145
+ decisions
1146
+ };
1147
+ }
1148
+ function scanMessages(messages, config) {
1149
+ const scanDecisions = [];
1150
+ let redactedCount = 0;
1151
+ let blocked = false;
1152
+ const scannedMessages = messages.map((msg) => {
1153
+ const findings = scanContentForSecrets(msg.content, `message:${msg.role}`);
1154
+ if (findings.length === 0) return msg;
1155
+ const criticalCount = findings.filter((f) => f.severity === "critical").length;
1156
+ if (config.blockOnSecrets && criticalCount > 0) {
1157
+ blocked = true;
1158
+ scanDecisions.push(
1159
+ `BLOCKED: ${criticalCount} critical secret(s) in ${msg.role} message. Types: ${[...new Set(findings.map((f) => f.type))].join(", ")}`
1160
+ );
1161
+ return msg;
1162
+ }
1163
+ const sanitized = sanitizeContent(msg.content);
1164
+ redactedCount += findings.length;
1165
+ scanDecisions.push(
1166
+ `Redacted ${findings.length} secret(s) in ${msg.role} message: ${[...new Set(findings.map((f) => f.type))].join(", ")}`
1167
+ );
1168
+ return { ...msg, content: sanitized };
1169
+ });
1170
+ return { messages: scannedMessages, redactedCount, blocked, scanDecisions };
1171
+ }
1172
+ async function optimizeContext(messages, analysis, config) {
1173
+ const optimizeDecisions = [];
1174
+ const lastUserMsg = [...messages].reverse().find((m) => m.role === "user");
1175
+ if (!lastUserMsg) {
1176
+ optimizeDecisions.push("No user message found \u2014 skipping optimization");
1177
+ return { messages, injected: false, optimizeDecisions };
1178
+ }
1179
+ const hasCtxContext = messages.some(
1180
+ (m) => m.role === "system" && m.content.includes("[CTO Context]")
1181
+ );
1182
+ if (hasCtxContext) {
1183
+ optimizeDecisions.push("CTO context already present \u2014 skipping injection");
1184
+ return { messages, injected: false, optimizeDecisions };
1185
+ }
1186
+ try {
1187
+ const selection = await selectContext({
1188
+ task: lastUserMsg.content.slice(0, 500),
1189
+ analysis,
1190
+ budget: config.budget
1191
+ });
1192
+ if (selection.files.length === 0) {
1193
+ optimizeDecisions.push("No relevant files found for task \u2014 skipping injection");
1194
+ return { messages, injected: false, optimizeDecisions };
1195
+ }
1196
+ const contentBudget = Math.floor(config.budget * 0.6);
1197
+ let usedTokens = 0;
1198
+ const contextLines = [
1199
+ "[CTO Context] Optimized project context (auto-injected by CTO Gateway)",
1200
+ "",
1201
+ `Project: ${analysis.projectName} (${analysis.totalFiles} files, ${Math.round(analysis.totalTokens / 1e3)}K tokens)`,
1202
+ `Selected: ${selection.files.length} files, ${selection.totalTokens.toLocaleString()} tokens (${selection.coverage.score}% coverage)`,
1203
+ ""
1204
+ ];
1205
+ const topFiles = selection.files.sort((a, b) => b.riskScore - a.riskScore);
1206
+ const injectedFiles = [];
1207
+ const skippedFiles = [];
1208
+ for (const f of topFiles) {
1209
+ if (usedTokens >= contentBudget) {
1210
+ skippedFiles.push(f.relativePath);
1211
+ continue;
1212
+ }
1213
+ try {
1214
+ const fullPath = resolve2(config.projectPath, f.relativePath);
1215
+ const content = readFileSync2(fullPath, "utf-8");
1216
+ const fileTokens = estimateTokensFromString(content);
1217
+ const remainingBudget = contentBudget - usedTokens;
1218
+ let fileContent;
1219
+ let truncated = false;
1220
+ if (fileTokens > remainingBudget) {
1221
+ const charLimit = remainingBudget * 4;
1222
+ fileContent = content.slice(0, charLimit);
1223
+ truncated = true;
1224
+ } else {
1225
+ fileContent = content;
1226
+ }
1227
+ const ext = f.relativePath.split(".").pop() || "";
1228
+ contextLines.push(`### ${f.relativePath}${truncated ? " [truncated]" : ""}`);
1229
+ contextLines.push("```" + ext);
1230
+ contextLines.push(fileContent);
1231
+ contextLines.push("```");
1232
+ contextLines.push("");
1233
+ usedTokens += estimateTokensFromString(fileContent);
1234
+ injectedFiles.push(f.relativePath);
1235
+ } catch {
1236
+ skippedFiles.push(f.relativePath);
1237
+ }
1238
+ }
1239
+ const typeFiles = analysis.files.filter((f) => f.kind === "type").map((f) => f.relativePath);
1240
+ if (typeFiles.length > 0) {
1241
+ contextLines.push("Type definitions (always import from these):");
1242
+ for (const tf of typeFiles.slice(0, 10)) {
1243
+ contextLines.push(` - ${tf}`);
1244
+ }
1245
+ contextLines.push("");
1246
+ }
1247
+ if (analysis.graph.hubs.length > 0) {
1248
+ contextLines.push("Hub files (central modules with many dependents):");
1249
+ for (const hub of analysis.graph.hubs.slice(0, 5)) {
1250
+ contextLines.push(` - ${hub.relativePath} (${hub.dependents} dependents)`);
1251
+ }
1252
+ contextLines.push("");
1253
+ }
1254
+ if (skippedFiles.length > 0) {
1255
+ contextLines.push(`Additional relevant files (not included due to token budget):`);
1256
+ for (const sf of skippedFiles.slice(0, 15)) {
1257
+ contextLines.push(` - ${sf}`);
1258
+ }
1259
+ if (skippedFiles.length > 15) {
1260
+ contextLines.push(` ... and ${skippedFiles.length - 15} more`);
1261
+ }
1262
+ }
1263
+ const contextBlock = contextLines.join("\n");
1264
+ const systemMsg = {
1265
+ role: "system",
1266
+ content: contextBlock
1267
+ };
1268
+ const existingSystemIdx = messages.findIndex((m) => m.role === "system");
1269
+ let optimizedMessages;
1270
+ if (existingSystemIdx >= 0) {
1271
+ optimizedMessages = [...messages];
1272
+ optimizedMessages[existingSystemIdx] = {
1273
+ ...optimizedMessages[existingSystemIdx],
1274
+ content: optimizedMessages[existingSystemIdx].content + "\n\n" + contextBlock
1275
+ };
1276
+ } else {
1277
+ optimizedMessages = [systemMsg, ...messages];
1278
+ }
1279
+ optimizeDecisions.push(
1280
+ `Injected CTO context: ${injectedFiles.length} files with contents (${usedTokens.toLocaleString()} tokens), ${skippedFiles.length} listed without contents, ${selection.coverage.score}% coverage`
1281
+ );
1282
+ return { messages: optimizedMessages, injected: true, optimizeDecisions };
1283
+ } catch (err) {
1284
+ optimizeDecisions.push(`Context optimization failed: ${err.message}`);
1285
+ return { messages, injected: false, optimizeDecisions };
1286
+ }
1287
+ }
1288
+
1289
+ // src/gateway/tracker.ts
1290
+ import { mkdirSync as mkdirSync2, appendFileSync, readFileSync as readFileSync3, readdirSync, existsSync as existsSync3 } from "fs";
1291
+ import { join as join3 } from "path";
1292
+ import { randomUUID } from "crypto";
1293
+ var UsageTracker = class {
1294
+ logDir;
1295
+ config;
1296
+ eventHandlers = [];
1297
+ cache = null;
1298
+ cacheMonth = null;
1299
+ // In-memory cost accumulators — survive async disk writes
1300
+ memRecords = [];
1301
+ constructor(config) {
1302
+ this.config = config;
1303
+ this.logDir = join3(config.logDir, "usage");
1304
+ mkdirSync2(this.logDir, { recursive: true });
1305
+ }
1306
+ // ===== EVENT SYSTEM =====
1307
+ onEvent(handler) {
1308
+ this.eventHandlers.push(handler);
1309
+ }
1310
+ emit(event) {
1311
+ for (const handler of this.eventHandlers) {
1312
+ try {
1313
+ handler(event);
1314
+ } catch {
1315
+ }
1316
+ }
1317
+ }
1318
+ // ===== RECORD =====
1319
+ record(params) {
1320
+ const record = {
1321
+ id: randomUUID().slice(0, 8),
1322
+ timestamp: /* @__PURE__ */ new Date(),
1323
+ ...params
1324
+ };
1325
+ const monthKey = this.getMonthKey(record.timestamp);
1326
+ const logFile = join3(this.logDir, `${monthKey}.jsonl`);
1327
+ const line = JSON.stringify({
1328
+ ...record,
1329
+ timestamp: record.timestamp.toISOString()
1330
+ });
1331
+ appendFileSync(logFile, line + "\n");
1332
+ this.memRecords.push(record);
1333
+ this.cache = null;
1334
+ this.emit({ type: "request", record });
1335
+ this.checkBudget(record.timestamp);
1336
+ return record;
1337
+ }
1338
+ // ===== BUDGET CHECKS =====
1339
+ checkBudget(now) {
1340
+ if (this.config.budgetDaily > 0) {
1341
+ const dailyCost = this.getDailyCost(now);
1342
+ const threshold = this.config.budgetDaily * this.config.alertThreshold;
1343
+ if (dailyCost >= this.config.budgetDaily) {
1344
+ this.emit({
1345
+ type: "budget-exceeded",
1346
+ current: dailyCost,
1347
+ limit: this.config.budgetDaily,
1348
+ period: "daily"
1349
+ });
1350
+ } else if (dailyCost >= threshold) {
1351
+ this.emit({
1352
+ type: "budget-alert",
1353
+ current: dailyCost,
1354
+ limit: this.config.budgetDaily,
1355
+ period: "daily"
1356
+ });
1357
+ }
1358
+ }
1359
+ if (this.config.budgetMonthly > 0) {
1360
+ const monthlyCost = this.getMonthlyCost(now);
1361
+ const threshold = this.config.budgetMonthly * this.config.alertThreshold;
1362
+ if (monthlyCost >= this.config.budgetMonthly) {
1363
+ this.emit({
1364
+ type: "budget-exceeded",
1365
+ current: monthlyCost,
1366
+ limit: this.config.budgetMonthly,
1367
+ period: "monthly"
1368
+ });
1369
+ } else if (monthlyCost >= threshold) {
1370
+ this.emit({
1371
+ type: "budget-alert",
1372
+ current: monthlyCost,
1373
+ limit: this.config.budgetMonthly,
1374
+ period: "monthly"
1375
+ });
1376
+ }
1377
+ }
1378
+ }
1379
+ isDailyBudgetExceeded(now = /* @__PURE__ */ new Date()) {
1380
+ if (this.config.budgetDaily <= 0) return false;
1381
+ return this.getDailyCost(now) >= this.config.budgetDaily;
1382
+ }
1383
+ isMonthlyBudgetExceeded(now = /* @__PURE__ */ new Date()) {
1384
+ if (this.config.budgetMonthly <= 0) return false;
1385
+ return this.getMonthlyCost(now) >= this.config.budgetMonthly;
1386
+ }
1387
+ // ===== QUERIES =====
1388
+ getDailyCost(date = /* @__PURE__ */ new Date()) {
1389
+ const dayStr = date.toISOString().split("T")[0];
1390
+ const diskRecords = this.getMonthRecords(date);
1391
+ const allRecords = this.mergeWithMemRecords(diskRecords);
1392
+ return allRecords.filter((r) => r.timestamp.toISOString().startsWith(dayStr)).reduce((sum, r) => sum + r.costUSD, 0);
1393
+ }
1394
+ getMonthlyCost(date = /* @__PURE__ */ new Date()) {
1395
+ const diskRecords = this.getMonthRecords(date);
1396
+ const allRecords = this.mergeWithMemRecords(diskRecords);
1397
+ return allRecords.reduce((sum, r) => sum + r.costUSD, 0);
1398
+ }
1399
+ mergeWithMemRecords(diskRecords) {
1400
+ if (this.memRecords.length === 0) return diskRecords;
1401
+ const diskIds = new Set(diskRecords.map((r) => r.id));
1402
+ const newRecords = this.memRecords.filter((r) => !diskIds.has(r.id));
1403
+ return [...diskRecords, ...newRecords];
1404
+ }
1405
+ getSummary(period = "month") {
1406
+ const now = /* @__PURE__ */ new Date();
1407
+ let records;
1408
+ switch (period) {
1409
+ case "day": {
1410
+ const dayStr = now.toISOString().split("T")[0];
1411
+ records = this.mergeWithMemRecords(this.getMonthRecords(now)).filter(
1412
+ (r) => r.timestamp.toISOString().startsWith(dayStr)
1413
+ );
1414
+ break;
1415
+ }
1416
+ case "week": {
1417
+ const weekAgo = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1e3);
1418
+ const weekAgoKey = this.getMonthKey(weekAgo);
1419
+ const nowKey = this.getMonthKey(now);
1420
+ const baseRecs = weekAgoKey !== nowKey ? [...this.getMonthRecordsByKey(weekAgoKey), ...this.getMonthRecords(now)] : this.getMonthRecords(now);
1421
+ records = this.mergeWithMemRecords(baseRecs).filter((r) => r.timestamp >= weekAgo);
1422
+ break;
1423
+ }
1424
+ case "month":
1425
+ records = this.mergeWithMemRecords(this.getMonthRecords(now));
1426
+ break;
1427
+ case "all":
1428
+ records = this.mergeWithMemRecords(this.getAllRecords());
1429
+ break;
1430
+ }
1431
+ const byModel = {};
1432
+ const byProvider = {};
1433
+ for (const r of records) {
1434
+ if (!byModel[r.model]) byModel[r.model] = { requests: 0, costUSD: 0, tokens: 0 };
1435
+ byModel[r.model].requests++;
1436
+ byModel[r.model].costUSD += r.costUSD;
1437
+ byModel[r.model].tokens += r.inputTokens + r.outputTokens;
1438
+ if (!byProvider[r.provider]) byProvider[r.provider] = { requests: 0, costUSD: 0 };
1439
+ byProvider[r.provider].requests++;
1440
+ byProvider[r.provider].costUSD += r.costUSD;
1441
+ }
1442
+ return {
1443
+ period,
1444
+ totalRequests: records.length,
1445
+ totalInputTokens: records.reduce((s, r) => s + r.inputTokens, 0),
1446
+ totalOutputTokens: records.reduce((s, r) => s + r.outputTokens, 0),
1447
+ totalCostUSD: records.reduce((s, r) => s + r.costUSD, 0),
1448
+ totalSavedTokens: records.reduce((s, r) => s + r.savedTokens, 0),
1449
+ totalSavedUSD: records.reduce((s, r) => s + r.savedUSD, 0),
1450
+ totalSecretsRedacted: records.reduce((s, r) => s + r.secretsRedacted, 0),
1451
+ byModel,
1452
+ byProvider
1453
+ };
1454
+ }
1455
+ // ===== STORAGE =====
1456
+ getMonthKey(date) {
1457
+ return date.toISOString().slice(0, 7);
1458
+ }
1459
+ getMonthRecordsByKey(monthKey) {
1460
+ const filePath = join3(this.logDir, `${monthKey}.jsonl`);
1461
+ if (!existsSync3(filePath)) return [];
1462
+ return readFileSync3(filePath, "utf-8").split("\n").filter((line) => line.trim()).map((line) => {
1463
+ try {
1464
+ const parsed = JSON.parse(line);
1465
+ parsed.timestamp = new Date(parsed.timestamp);
1466
+ return parsed;
1467
+ } catch {
1468
+ return null;
1469
+ }
1470
+ }).filter((r) => r !== null);
1471
+ }
1472
+ getMonthRecords(date) {
1473
+ const monthKey = this.getMonthKey(date);
1474
+ if (this.cache && this.cacheMonth === monthKey) return this.cache;
1475
+ const filePath = join3(this.logDir, `${monthKey}.jsonl`);
1476
+ if (!existsSync3(filePath)) return [];
1477
+ const records = readFileSync3(filePath, "utf-8").split("\n").filter((line) => line.trim()).map((line) => {
1478
+ try {
1479
+ const parsed = JSON.parse(line);
1480
+ parsed.timestamp = new Date(parsed.timestamp);
1481
+ return parsed;
1482
+ } catch {
1483
+ return null;
1484
+ }
1485
+ }).filter((r) => r !== null);
1486
+ this.cache = records;
1487
+ this.cacheMonth = monthKey;
1488
+ return records;
1489
+ }
1490
+ getAllRecords() {
1491
+ if (!existsSync3(this.logDir)) return [];
1492
+ const files = readdirSync(this.logDir).filter((f) => f.endsWith(".jsonl")).sort();
1493
+ const allRecords = [];
1494
+ for (const file of files) {
1495
+ const content = readFileSync3(join3(this.logDir, file), "utf-8");
1496
+ const records = content.split("\n").filter((line) => line.trim()).map((line) => {
1497
+ try {
1498
+ const parsed = JSON.parse(line);
1499
+ parsed.timestamp = new Date(parsed.timestamp);
1500
+ return parsed;
1501
+ } catch {
1502
+ return null;
1503
+ }
1504
+ }).filter((r) => r !== null);
1505
+ allRecords.push(...records);
1506
+ }
1507
+ return allRecords;
1508
+ }
1509
+ };
1510
+
1511
+ // src/engine/analyzer.ts
1512
+ import { readFile as readFile4, readdir, stat as stat2 } from "fs/promises";
1513
+ import { join as join5, extname, relative as relative3, resolve as resolve4, basename as basename2 } from "path";
1514
+ import { createHash as createHash3 } from "crypto";
1515
+
1516
+ // src/types/engine.ts
1517
+ var DEFAULT_RISK_WEIGHTS = {
1518
+ hub: 30,
1519
+ typeProvider: 25,
1520
+ complexity: 15,
1521
+ recency: 15,
1522
+ config: 10,
1523
+ churn: 5
1524
+ };
1525
+
1526
+ // src/types/config.ts
1527
+ var DEFAULT_CONFIG = {
1528
+ version: "2.0",
1529
+ analysis: {
1530
+ extensions: {
1531
+ code: ["ts", "tsx", "js", "jsx", "py", "go", "rs", "java", "kt", "rb", "php", "c", "cpp", "h", "hpp", "cs"],
1532
+ config: ["json", "yml", "yaml", "toml"],
1533
+ docs: ["md", "txt", "rst"]
1534
+ },
1535
+ ignore: {
1536
+ dirs: ["node_modules", "dist", "build", ".git", "coverage", "__pycache__", ".next", "vendor", ".cto"],
1537
+ patterns: ["*.min.js", "*.map", "*.lock", "*.generated.*"]
1538
+ },
1539
+ maxDepth: 20
1540
+ },
1541
+ risk: {
1542
+ weights: {
1543
+ hub: 30,
1544
+ typeProvider: 25,
1545
+ complexity: 15,
1546
+ recency: 15,
1547
+ config: 10,
1548
+ churn: 5
1549
+ }
1550
+ },
1551
+ interaction: {
1552
+ defaultBudget: 5e4,
1553
+ defaultModel: "claude-sonnet-4"
1554
+ },
1555
+ tokens: {
1556
+ method: "chars4"
1557
+ },
1558
+ governance: {
1559
+ auditEnabled: true,
1560
+ secretDetection: true,
1561
+ retentionDays: 90
1562
+ }
1563
+ };
1564
+
1565
+ // src/engine/graph.ts
1566
+ import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
1567
+ import { resolve as resolve3, relative as relative2, dirname as dirname2, join as join4 } from "path";
1568
+ import { existsSync as existsSync4 } from "fs";
1569
+ var TS_EXTENSIONS2 = /* @__PURE__ */ new Set(["ts", "tsx", "js", "jsx", "mts", "mjs", "cts", "cjs"]);
1570
+ function createProject(projectPath, filePaths) {
1571
+ const tsConfigPath = join4(projectPath, "tsconfig.json");
1572
+ const hasTsConfig = existsSync4(tsConfigPath);
1573
+ const project = new Project2({
1574
+ tsConfigFilePath: hasTsConfig ? tsConfigPath : void 0,
1575
+ skipAddingFilesFromTsConfig: true,
1576
+ compilerOptions: hasTsConfig ? void 0 : {
1577
+ allowJs: true,
1578
+ jsx: 4,
1579
+ // JsxEmit.ReactJSX
1580
+ esModuleInterop: true,
1581
+ moduleResolution: 100
1582
+ // Bundler
1583
+ }
1584
+ });
1585
+ const tsFiles = filePaths.filter((f) => {
1586
+ const ext = f.split(".").pop()?.toLowerCase() ?? "";
1587
+ return TS_EXTENSIONS2.has(ext);
1588
+ });
1589
+ for (const filePath of tsFiles) {
1590
+ try {
1591
+ project.addSourceFileAtPath(filePath);
1592
+ } catch {
1593
+ }
1594
+ }
1595
+ return project;
1596
+ }
1597
+ function buildProjectGraph(projectPath, files) {
1598
+ const absPath = resolve3(projectPath);
1599
+ const tsFiles = files.filter((f) => TS_EXTENSIONS2.has(f.extension)).map((f) => f.path);
1600
+ if (tsFiles.length === 0) {
1601
+ return emptyGraph(files);
1602
+ }
1603
+ let project;
1604
+ try {
1605
+ project = createProject(projectPath, tsFiles);
1606
+ } catch {
1607
+ return emptyGraph(files);
1608
+ }
1609
+ const edges = [];
1610
+ const nodeSet = /* @__PURE__ */ new Set();
1611
+ for (const sourceFile of project.getSourceFiles()) {
1612
+ const fromRel = relative2(absPath, sourceFile.getFilePath());
1613
+ if (fromRel.startsWith("..") || fromRel.includes("node_modules")) continue;
1614
+ nodeSet.add(fromRel);
1615
+ for (const imp of sourceFile.getImportDeclarations()) {
1616
+ const moduleSpecifier = imp.getModuleSpecifierValue();
1617
+ const resolved = resolveImport(sourceFile, moduleSpecifier, absPath);
1618
+ if (resolved) {
1619
+ nodeSet.add(resolved);
1620
+ edges.push({ from: fromRel, to: resolved, type: "import" });
1621
+ }
1622
+ }
1623
+ for (const exp of sourceFile.getExportDeclarations()) {
1624
+ const moduleSpecifier = exp.getModuleSpecifierValue();
1625
+ if (moduleSpecifier) {
1626
+ const resolved = resolveImport(sourceFile, moduleSpecifier, absPath);
1627
+ if (resolved) {
1628
+ nodeSet.add(resolved);
1629
+ edges.push({ from: fromRel, to: resolved, type: "re-export" });
1630
+ }
1631
+ }
1632
+ }
1633
+ }
1634
+ const nodes = Array.from(nodeSet);
1635
+ const importedByCount = /* @__PURE__ */ new Map();
1636
+ const importCount = /* @__PURE__ */ new Map();
1637
+ for (const edge of edges) {
1638
+ importedByCount.set(edge.to, (importedByCount.get(edge.to) ?? 0) + 1);
1639
+ importCount.set(edge.from, (importCount.get(edge.from) ?? 0) + 1);
1640
+ }
1641
+ const N = Math.max(nodes.length, 1);
1642
+ const hubs = nodes.map((node) => {
1643
+ const inDeg = importedByCount.get(node) ?? 0;
1644
+ const outDeg = importCount.get(node) ?? 0;
1645
+ const centrality = N > 1 ? inDeg / (N - 1) * 100 : 0;
1646
+ const score = Math.round(centrality + outDeg * (100 / (2 * N)));
1647
+ return {
1648
+ relativePath: node,
1649
+ dependents: inDeg,
1650
+ dependencies: outDeg,
1651
+ score: Math.min(100, score)
1652
+ };
1653
+ }).filter((h) => h.dependents >= 3 || h.score >= 15).sort((a, b) => b.score - a.score);
1654
+ const leaves = nodes.filter(
1655
+ (node) => (importedByCount.get(node) ?? 0) === 0 && (importCount.get(node) ?? 0) > 0
1656
+ );
1657
+ const connectedNodes = /* @__PURE__ */ new Set();
1658
+ for (const edge of edges) {
1659
+ connectedNodes.add(edge.from);
1660
+ connectedNodes.add(edge.to);
1661
+ }
1662
+ const allFileNodes = new Set(files.map((f) => f.relativePath));
1663
+ const orphans = Array.from(allFileNodes).filter((n) => !connectedNodes.has(n));
1664
+ const clusters = detectClusters(nodes, edges, files);
1665
+ enrichComplexity(project, absPath, files);
1666
+ return { nodes, edges, hubs, leaves, orphans, clusters };
1667
+ }
1668
+ var UnionFind = class {
1669
+ parent;
1670
+ rank;
1671
+ constructor(nodes) {
1672
+ this.parent = /* @__PURE__ */ new Map();
1673
+ this.rank = /* @__PURE__ */ new Map();
1674
+ for (const n of nodes) {
1675
+ this.parent.set(n, n);
1676
+ this.rank.set(n, 0);
1677
+ }
1678
+ }
1679
+ find(x) {
1680
+ const p = this.parent.get(x);
1681
+ if (p === void 0) return x;
1682
+ if (p !== x) {
1683
+ this.parent.set(x, this.find(p));
1684
+ }
1685
+ return this.parent.get(x);
1686
+ }
1687
+ union(a, b) {
1688
+ const ra = this.find(a);
1689
+ const rb = this.find(b);
1690
+ if (ra === rb) return;
1691
+ const rankA = this.rank.get(ra) ?? 0;
1692
+ const rankB = this.rank.get(rb) ?? 0;
1693
+ if (rankA < rankB) {
1694
+ this.parent.set(ra, rb);
1695
+ } else if (rankA > rankB) {
1696
+ this.parent.set(rb, ra);
1697
+ } else {
1698
+ this.parent.set(rb, ra);
1699
+ this.rank.set(ra, rankA + 1);
1700
+ }
1701
+ }
1702
+ };
1703
+ function detectClusters(nodes, edges, files) {
1704
+ const uf = new UnionFind(nodes);
1705
+ for (const edge of edges) {
1706
+ uf.union(edge.from, edge.to);
1707
+ }
1708
+ const components = /* @__PURE__ */ new Map();
1709
+ for (const node of nodes) {
1710
+ const root = uf.find(node);
1711
+ if (!components.has(root)) components.set(root, []);
1712
+ components.get(root).push(node);
1713
+ }
1714
+ const tokenMap = new Map(files.map((f) => [f.relativePath, f.tokens]));
1715
+ const clusters = [];
1716
+ for (const [, groupFiles] of components) {
1717
+ if (groupFiles.length < 2) continue;
1718
+ const name = commonPrefix(groupFiles);
1719
+ const fileSet = new Set(groupFiles);
1720
+ let internalEdges = 0;
1721
+ let externalEdges = 0;
1722
+ for (const edge of edges) {
1723
+ const fromIn = fileSet.has(edge.from);
1724
+ const toIn = fileSet.has(edge.to);
1725
+ if (fromIn && toIn) internalEdges++;
1726
+ else if (fromIn || toIn) externalEdges++;
1727
+ }
1728
+ const totalEdges = internalEdges + externalEdges;
1729
+ const cohesion = totalEdges > 0 ? internalEdges / totalEdges : 0;
1730
+ const totalTokens = groupFiles.reduce((s, f) => s + (tokenMap.get(f) ?? 0), 0);
1731
+ clusters.push({
1732
+ id: name.replace(/[^a-zA-Z0-9]/g, "-") || `cluster-${clusters.length}`,
1733
+ name: name || `cluster-${clusters.length}`,
1734
+ files: groupFiles,
1735
+ totalTokens,
1736
+ internalEdges,
1737
+ externalEdges,
1738
+ cohesion: Math.round(cohesion * 100) / 100
1739
+ });
1740
+ }
1741
+ return clusters.sort((a, b) => b.files.length - a.files.length);
1742
+ }
1743
+ function commonPrefix(paths) {
1744
+ if (paths.length === 0) return "";
1745
+ const parts = paths.map((p) => p.split("/"));
1746
+ const prefix = [];
1747
+ for (let i = 0; i < parts[0].length - 1; i++) {
1748
+ const segment = parts[0][i];
1749
+ if (parts.every((p) => p[i] === segment)) {
1750
+ prefix.push(segment);
1751
+ } else break;
1752
+ }
1753
+ return prefix.join("/") || parts[0][0];
1754
+ }
1755
+ function enrichComplexity(project, absPath, files) {
1756
+ const fileMap = new Map(files.map((f) => [f.relativePath, f]));
1757
+ for (const sourceFile of project.getSourceFiles()) {
1758
+ const relPath = relative2(absPath, sourceFile.getFilePath());
1759
+ if (relPath.startsWith("..") || relPath.includes("node_modules")) continue;
1760
+ const file = fileMap.get(relPath);
1761
+ if (!file) continue;
1762
+ let totalComplexity = 0;
1763
+ for (const func of sourceFile.getFunctions()) {
1764
+ totalComplexity += calculateCyclomaticComplexity(func);
1765
+ }
1766
+ for (const cls of sourceFile.getClasses()) {
1767
+ for (const method of cls.getMethods()) {
1768
+ totalComplexity += calculateCyclomaticComplexity(method);
1769
+ }
1770
+ }
1771
+ for (const varDecl of sourceFile.getVariableDeclarations()) {
1772
+ const init = varDecl.getInitializer();
1773
+ if (init && (init.getKind() === SyntaxKind2.ArrowFunction || init.getKind() === SyntaxKind2.FunctionExpression)) {
1774
+ totalComplexity += calculateCyclomaticComplexity(init);
1775
+ }
1776
+ }
1777
+ file.complexity = Math.max(1, totalComplexity);
1778
+ }
1779
+ }
1780
+ function calculateCyclomaticComplexity(node) {
1781
+ let complexity = 1;
1782
+ node.forEachDescendant((descendant) => {
1783
+ switch (descendant.getKind()) {
1784
+ case SyntaxKind2.IfStatement:
1785
+ case SyntaxKind2.ConditionalExpression:
1786
+ case SyntaxKind2.ForStatement:
1787
+ case SyntaxKind2.ForInStatement:
1788
+ case SyntaxKind2.ForOfStatement:
1789
+ case SyntaxKind2.WhileStatement:
1790
+ case SyntaxKind2.DoStatement:
1791
+ case SyntaxKind2.CaseClause:
1792
+ case SyntaxKind2.CatchClause:
1793
+ complexity++;
1794
+ break;
1795
+ case SyntaxKind2.BinaryExpression: {
1796
+ const opToken = descendant.getOperatorToken?.();
1797
+ if (opToken) {
1798
+ const kind = opToken.getKind();
1799
+ if (kind === SyntaxKind2.AmpersandAmpersandToken || kind === SyntaxKind2.BarBarToken || kind === SyntaxKind2.QuestionQuestionToken) {
1800
+ complexity++;
1801
+ }
1802
+ }
1803
+ break;
1804
+ }
1805
+ }
1806
+ });
1807
+ return complexity;
1808
+ }
1809
+ function resolveImport(sourceFile, moduleSpecifier, projectRoot) {
1810
+ if (!moduleSpecifier.startsWith(".")) return null;
1811
+ const sourceDir = dirname2(sourceFile.getFilePath());
1812
+ const basePath = resolve3(sourceDir, moduleSpecifier);
1813
+ const extensions = [".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.tsx", "/index.js", "/index.jsx"];
1814
+ for (const ext of extensions) {
1815
+ const candidate = basePath.endsWith(ext) ? basePath : basePath + ext;
1816
+ if (existsSync4(candidate)) {
1817
+ const rel = relative2(projectRoot, candidate);
1818
+ if (!rel.startsWith("..")) return rel;
1819
+ }
1820
+ }
1821
+ if (moduleSpecifier.endsWith(".js")) {
1822
+ const tsPath = basePath.replace(/\.js$/, ".ts");
1823
+ if (existsSync4(tsPath)) {
1824
+ const rel = relative2(projectRoot, tsPath);
1825
+ if (!rel.startsWith("..")) return rel;
1826
+ }
1827
+ }
1828
+ return null;
1829
+ }
1830
+ function emptyGraph(files) {
1831
+ return {
1832
+ nodes: files.map((f) => f.relativePath),
1833
+ edges: [],
1834
+ hubs: [],
1835
+ leaves: [],
1836
+ orphans: files.map((f) => f.relativePath),
1837
+ clusters: []
1838
+ };
1839
+ }
1840
+
1841
+ // src/engine/risk.ts
1842
+ function scoreAllFiles(files, graph, weights = DEFAULT_RISK_WEIGHTS) {
1843
+ const typeProviderUsage = computeTypeProviderUsage(files, graph);
1844
+ for (const file of files) {
1845
+ const factors = computeRiskFactors(file, graph, typeProviderUsage, weights);
1846
+ file.riskFactors = factors;
1847
+ file.riskScore = computeWeightedScore(factors);
1848
+ file.exclusionImpact = scoreToImpact(file.riskScore);
1849
+ }
1850
+ }
1851
+ function computeRiskFactors(file, graph, typeProviderUsage, weights) {
1852
+ const factors = [];
1853
+ factors.push(computeHubFactor(file, weights.hub));
1854
+ factors.push(computeTypeProviderFactor(file, typeProviderUsage, weights.typeProvider));
1855
+ factors.push(computeComplexityFactor(file, weights.complexity));
1856
+ factors.push(computeRecencyFactor(file, weights.recency));
1857
+ factors.push(computeConfigFactor(file, weights.config));
1858
+ factors.push(computeChurnFactor(file, weights.churn));
1859
+ return factors;
1860
+ }
1861
+ function computeHubFactor(file, weight) {
1862
+ const dependents = file.importedBy.length;
1863
+ const K = 12;
1864
+ const score = dependents === 0 ? 0 : Math.min(100, Math.round(100 * Math.log2(1 + dependents) / Math.log2(1 + K)));
1865
+ const detail = dependents === 0 ? "No dependents" : `Hub: ${dependents} file(s) depend on this (score ${score}/100)`;
1866
+ return { type: "hub", score, weight, detail };
1867
+ }
1868
+ function computeTypeProviderFactor(file, usage, weight) {
1869
+ const isTypeFile = file.kind === "type";
1870
+ const consumers = usage.get(file.relativePath) ?? 0;
1871
+ let score;
1872
+ let detail;
1873
+ if (isTypeFile && consumers >= 4) {
1874
+ score = 100;
1875
+ detail = `Type provider: used by ${consumers} files (critical type source)`;
1876
+ } else if (isTypeFile && consumers >= 1) {
1877
+ score = 50;
1878
+ detail = `Type provider: used by ${consumers} files`;
1879
+ } else if (isTypeFile) {
1880
+ score = 30;
1881
+ detail = "Type file (no detected consumers)";
1882
+ } else {
1883
+ score = 0;
1884
+ detail = "Not a type provider";
1885
+ }
1886
+ return { type: "type-provider", score, weight, detail };
1887
+ }
1888
+ function computeComplexityFactor(file, weight) {
1889
+ const c = file.complexity;
1890
+ const K = 30;
1891
+ const score = Math.min(100, Math.round(100 * Math.log(1 + c) / Math.log(1 + K)));
1892
+ const detail = c >= 30 ? `Very high complexity: ${c} (AI needs full context)` : c >= 10 ? `High complexity: ${c}` : `Complexity: ${c}`;
1893
+ return { type: "complexity", score, weight, detail };
1894
+ }
1895
+ function computeRecencyFactor(file, weight) {
1896
+ const now = Date.now();
1897
+ const modified = new Date(file.lastModified).getTime();
1898
+ const daysAgo = (now - modified) / (1e3 * 60 * 60 * 24);
1899
+ const HALF_LIFE = 7;
1900
+ const score = Math.round(100 * Math.pow(2, -daysAgo / HALF_LIFE));
1901
+ const detail = daysAgo <= 1 ? "Modified today" : `Modified ${Math.round(daysAgo)} days ago (decay score ${score})`;
1902
+ return { type: "recency", score, weight, detail };
1903
+ }
1904
+ function computeConfigFactor(file, weight) {
1905
+ let score;
1906
+ let detail;
1907
+ if (file.kind === "entry") {
1908
+ score = 90;
1909
+ detail = "Entry point \u2014 critical for understanding app structure";
1910
+ } else if (file.kind === "config") {
1911
+ score = 80;
1912
+ detail = "Configuration file \u2014 affects runtime behavior";
1913
+ } else {
1914
+ score = 0;
1915
+ detail = "Regular source file";
1916
+ }
1917
+ return { type: "config", score, weight, detail };
1918
+ }
1919
+ function computeChurnFactor(file, weight) {
1920
+ const complexitySignal = Math.min(file.complexity / 20, 1);
1921
+ const now = Date.now();
1922
+ const daysAgo = (now - new Date(file.lastModified).getTime()) / (1e3 * 60 * 60 * 24);
1923
+ const recencySignal = Math.pow(2, -daysAgo / 7);
1924
+ const score = Math.round(Math.sqrt(complexitySignal * recencySignal) * 100);
1925
+ const detail = score >= 50 ? "Likely under active development (complex + recent)" : score >= 20 ? "Some recent activity" : "Stable \u2014 low churn (proxy estimate)";
1926
+ return { type: "churn", score, weight, detail };
1927
+ }
1928
+ function computeWeightedScore(factors) {
1929
+ let totalWeightedScore = 0;
1930
+ let totalWeight = 0;
1931
+ for (const factor of factors) {
1932
+ totalWeightedScore += factor.score * factor.weight;
1933
+ totalWeight += factor.weight;
1934
+ }
1935
+ if (totalWeight === 0) return 0;
1936
+ return Math.round(totalWeightedScore / totalWeight);
1937
+ }
1938
+ function scoreToImpact(score) {
1939
+ if (score >= 80) return "critical";
1940
+ if (score >= 60) return "high";
1941
+ if (score >= 30) return "medium";
1942
+ if (score > 0) return "low";
1943
+ return "none";
1944
+ }
1945
+ function computeTypeProviderUsage(files, graph) {
1946
+ const usage = /* @__PURE__ */ new Map();
1947
+ const typeFiles = new Set(
1948
+ files.filter((f) => f.kind === "type").map((f) => f.relativePath)
1949
+ );
1950
+ for (const edge of graph.edges) {
1951
+ if (typeFiles.has(edge.to)) {
1952
+ usage.set(edge.to, (usage.get(edge.to) ?? 0) + 1);
1953
+ }
1954
+ }
1955
+ return usage;
1956
+ }
1957
+
1958
+ // src/engine/analyzer.ts
1959
+ function matchesPattern(filename, patterns) {
1960
+ for (const pattern of patterns) {
1961
+ if (pattern.startsWith("*.")) {
1962
+ const ext = pattern.slice(1);
1963
+ if (filename.endsWith(ext)) return true;
1964
+ } else if (filename === pattern) {
1965
+ return true;
1966
+ }
1967
+ }
1968
+ return false;
1969
+ }
1970
+ async function walkProject(rootPath, options) {
1971
+ const results = [];
1972
+ const { ignoreDirs, ignorePatterns, extensions, maxDepth = 20 } = options;
1973
+ const ignoreDirSet = new Set(ignoreDirs);
1974
+ async function walk(dir, depth) {
1975
+ if (depth > maxDepth) return;
1976
+ let entries;
1977
+ try {
1978
+ entries = await readdir(dir, { withFileTypes: true });
1979
+ } catch {
1980
+ return;
1981
+ }
1982
+ const promises = [];
1983
+ for (const entry of entries) {
1984
+ const fullPath = join5(dir, entry.name);
1985
+ if (entry.isDirectory()) {
1986
+ if (!ignoreDirSet.has(entry.name) && !entry.name.startsWith(".")) {
1987
+ promises.push(walk(fullPath, depth + 1));
1988
+ }
1989
+ } else if (entry.isFile()) {
1990
+ const ext = extname(entry.name).slice(1).toLowerCase();
1991
+ if (ext && extensions.includes(ext) && !matchesPattern(entry.name, ignorePatterns)) {
1992
+ promises.push(
1993
+ (async () => {
1994
+ const fileStat = await stat2(fullPath).catch(() => null);
1995
+ if (!fileStat) return;
1996
+ let lines = 0;
1997
+ try {
1998
+ const content = await readFile4(fullPath, "utf-8");
1999
+ lines = content.split("\n").length;
2000
+ } catch {
2001
+ lines = 0;
2002
+ }
2003
+ results.push({
2004
+ path: fullPath,
2005
+ relativePath: relative3(rootPath, fullPath),
2006
+ extension: ext,
2007
+ size: fileStat.size,
2008
+ lastModified: fileStat.mtime,
2009
+ lines
2010
+ });
2011
+ })()
2012
+ );
2013
+ }
2014
+ }
2015
+ }
2016
+ await Promise.all(promises);
2017
+ }
2018
+ await walk(rootPath, 0);
2019
+ return results;
2020
+ }
2021
+ var TYPE_PATTERNS = [/types?\//i, /\.d\.ts$/, /interfaces?\//i];
2022
+ var TEST_PATTERNS = [/\.test\.[jt]sx?$/, /\.spec\.[jt]sx?$/, /\/__tests__\//, /\/tests?\//];
2023
+ var CONFIG_PATTERNS = [/\.config\.[jt]s$/, /rc\.[jt]s$/, /\.env/, /tsconfig/, /package\.json$/, /\.yml$/, /\.yaml$/, /\.toml$/];
2024
+ var ENTRY_PATTERNS = [/^index\.[jt]sx?$/, /^main\.[jt]sx?$/, /^app\.[jt]sx?$/, /^server\.[jt]sx?$/];
2025
+ function classifyFileKind(relativePath) {
2026
+ const filename = basename2(relativePath);
2027
+ if (TYPE_PATTERNS.some((p) => p.test(relativePath))) return "type";
2028
+ if (TEST_PATTERNS.some((p) => p.test(relativePath))) return "test";
2029
+ if (CONFIG_PATTERNS.some((p) => p.test(relativePath) || p.test(filename))) return "config";
2030
+ if (ENTRY_PATTERNS.some((p) => p.test(filename))) return "entry";
2031
+ return "source";
2032
+ }
2033
+ function detectStack(files) {
2034
+ const stack = [];
2035
+ const extensions = new Set(files.map((f) => f.extension));
2036
+ const paths = files.map((f) => f.relativePath.toLowerCase());
2037
+ if (extensions.has("ts") || extensions.has("tsx")) stack.push("TypeScript");
2038
+ else if (extensions.has("js") || extensions.has("jsx")) stack.push("JavaScript");
2039
+ if (extensions.has("py")) stack.push("Python");
2040
+ if (extensions.has("go")) stack.push("Go");
2041
+ if (extensions.has("rs")) stack.push("Rust");
2042
+ if (extensions.has("java")) stack.push("Java");
2043
+ if (extensions.has("kt")) stack.push("Kotlin");
2044
+ if (extensions.has("rb")) stack.push("Ruby");
2045
+ if (extensions.has("php")) stack.push("PHP");
2046
+ if (extensions.has("cs")) stack.push("C#");
2047
+ if (extensions.has("c") || extensions.has("cpp")) stack.push("C/C++");
2048
+ if (paths.some((p) => p.includes("next.config"))) stack.push("Next.js");
2049
+ if (paths.some((p) => p.includes("nuxt.config"))) stack.push("Nuxt");
2050
+ if (paths.some((p) => p.includes("angular.json"))) stack.push("Angular");
2051
+ return stack;
2052
+ }
2053
+ async function analyzeProject(projectPath, config) {
2054
+ const absPath = resolve4(projectPath);
2055
+ const projectName = basename2(absPath);
2056
+ const mergedConfig = mergeConfig(DEFAULT_CONFIG, config);
2057
+ const allExtensions = [
2058
+ ...mergedConfig.analysis.extensions.code,
2059
+ ...mergedConfig.analysis.extensions.config,
2060
+ ...mergedConfig.analysis.extensions.docs
2061
+ ];
2062
+ const walkEntries = await walkProject(absPath, {
2063
+ ignoreDirs: mergedConfig.analysis.ignore.dirs,
2064
+ ignorePatterns: mergedConfig.analysis.ignore.patterns,
2065
+ extensions: allExtensions,
2066
+ maxDepth: mergedConfig.analysis.maxDepth
2067
+ });
2068
+ const tokenMethod = mergedConfig.tokens.method;
2069
+ const files = [];
2070
+ for (const entry of walkEntries) {
2071
+ let tokens;
2072
+ if (tokenMethod === "tiktoken") {
2073
+ try {
2074
+ const content = await readFile4(entry.path, "utf-8");
2075
+ tokens = estimateTokens(content, entry.size, "tiktoken");
2076
+ } catch {
2077
+ tokens = countTokensChars4(entry.size);
2078
+ }
2079
+ } else {
2080
+ tokens = countTokensChars4(entry.size);
2081
+ }
2082
+ files.push({
2083
+ path: entry.path,
2084
+ relativePath: entry.relativePath,
2085
+ extension: entry.extension,
2086
+ size: entry.size,
2087
+ tokens,
2088
+ lines: entry.lines,
2089
+ lastModified: entry.lastModified,
2090
+ kind: classifyFileKind(entry.relativePath),
2091
+ // Graph data — populated by graph analysis
2092
+ imports: [],
2093
+ importedBy: [],
2094
+ isHub: false,
2095
+ complexity: 0,
2096
+ // Risk data — populated by risk analysis
2097
+ riskScore: 0,
2098
+ riskFactors: [],
2099
+ exclusionImpact: "none"
2100
+ });
2101
+ }
2102
+ const graph = buildProjectGraph(absPath, files);
2103
+ for (const file of files) {
2104
+ const nodeImports = [];
2105
+ const nodeImportedBy = [];
2106
+ for (const edge of graph.edges) {
2107
+ if (edge.from === file.relativePath) nodeImports.push(edge.to);
2108
+ if (edge.to === file.relativePath) nodeImportedBy.push(edge.from);
2109
+ }
2110
+ file.imports = nodeImports;
2111
+ file.importedBy = nodeImportedBy;
2112
+ file.isHub = graph.hubs.some((h) => h.relativePath === file.relativePath);
2113
+ }
2114
+ const riskWeights = mergedConfig.risk.weights;
2115
+ scoreAllFiles(files, graph, riskWeights);
2116
+ const riskProfile = {
2117
+ distribution: {
2118
+ critical: files.filter((f) => f.riskScore >= 80).length,
2119
+ high: files.filter((f) => f.riskScore >= 60 && f.riskScore < 80).length,
2120
+ medium: files.filter((f) => f.riskScore >= 30 && f.riskScore < 60).length,
2121
+ low: files.filter((f) => f.riskScore < 30).length
2122
+ },
2123
+ topRiskFiles: [...files].sort((a, b) => b.riskScore - a.riskScore).slice(0, 10),
2124
+ overallComplexity: files.length > 0 ? files.reduce((s, f) => s + f.complexity, 0) / files.length : 0
2125
+ };
2126
+ const totalTokens = files.reduce((s, f) => s + f.tokens, 0);
2127
+ const hashInput = files.map((f) => `${f.relativePath}:${f.tokens}:${f.riskScore}`).sort().join("|");
2128
+ const hash = createHash3("sha256").update(hashInput).digest("hex").substring(0, 16);
2129
+ const stack = detectStack(walkEntries);
2130
+ return {
2131
+ projectPath: absPath,
2132
+ projectName,
2133
+ analyzedAt: /* @__PURE__ */ new Date(),
2134
+ hash,
2135
+ files,
2136
+ totalFiles: files.length,
2137
+ totalTokens,
2138
+ graph,
2139
+ riskProfile,
2140
+ stack,
2141
+ tokenMethod
2142
+ };
2143
+ }
2144
+ function mergeConfig(base, overrides) {
2145
+ if (!overrides) return base;
2146
+ return {
2147
+ ...base,
2148
+ ...overrides,
2149
+ analysis: {
2150
+ ...base.analysis,
2151
+ ...overrides.analysis,
2152
+ extensions: {
2153
+ ...base.analysis.extensions,
2154
+ ...overrides.analysis?.extensions
2155
+ },
2156
+ ignore: {
2157
+ ...base.analysis.ignore,
2158
+ ...overrides.analysis?.ignore
2159
+ }
2160
+ },
2161
+ risk: {
2162
+ ...base.risk,
2163
+ ...overrides.risk,
2164
+ weights: {
2165
+ ...base.risk.weights,
2166
+ ...overrides.risk?.weights
2167
+ }
2168
+ },
2169
+ interaction: {
2170
+ ...base.interaction,
2171
+ ...overrides.interaction
2172
+ },
2173
+ tokens: {
2174
+ ...base.tokens,
2175
+ ...overrides.tokens
2176
+ },
2177
+ governance: {
2178
+ ...base.governance,
2179
+ ...overrides.governance
2180
+ }
2181
+ };
2182
+ }
2183
+
2184
+ // src/gateway/server.ts
2185
+ var ContextGateway = class {
2186
+ config;
2187
+ tracker;
2188
+ analysis = null;
2189
+ analysisPromise = null;
2190
+ eventHandlers = [];
2191
+ server = null;
2192
+ httpAgent;
2193
+ httpsAgent;
2194
+ budgetLock = false;
2195
+ // Simple lock for budget reservation
2196
+ constructor(config = {}) {
2197
+ this.config = { ...DEFAULT_GATEWAY_CONFIG, ...config };
2198
+ this.tracker = new UsageTracker(this.config);
2199
+ this.httpAgent = new HttpAgent({ keepAlive: true, maxSockets: 50 });
2200
+ this.httpsAgent = new HttpsAgent({ keepAlive: true, maxSockets: 50 });
2201
+ this.tracker.onEvent((event) => this.emit(event));
2202
+ }
2203
+ // ===== EVENTS =====
2204
+ onEvent(handler) {
2205
+ this.eventHandlers.push(handler);
2206
+ }
2207
+ emit(event) {
2208
+ for (const handler of this.eventHandlers) {
2209
+ try {
2210
+ handler(event);
2211
+ } catch {
2212
+ }
2213
+ }
2214
+ }
2215
+ // ===== LIFECYCLE =====
2216
+ async start() {
2217
+ if (this.config.optimize) {
2218
+ this.analysisPromise = this.refreshAnalysis();
2219
+ }
2220
+ this.server = createServer((req, res) => this.handleRequest(req, res));
2221
+ return new Promise((resolve5) => {
2222
+ this.server.listen(this.config.port, this.config.host, () => {
2223
+ resolve5();
2224
+ });
2225
+ });
2226
+ }
2227
+ async stop() {
2228
+ return new Promise((resolve5) => {
2229
+ if (this.server) {
2230
+ this.server.close(() => resolve5());
2231
+ } else {
2232
+ resolve5();
2233
+ }
2234
+ });
2235
+ }
2236
+ getTracker() {
2237
+ return this.tracker;
2238
+ }
2239
+ // ===== ANALYSIS =====
2240
+ async refreshAnalysis() {
2241
+ try {
2242
+ const analysis = await analyzeProject(this.config.projectPath);
2243
+ this.analysis = analysis;
2244
+ return analysis;
2245
+ } catch (err) {
2246
+ this.emit({ type: "error", message: `Analysis failed: ${err.message}`, error: err });
2247
+ throw err;
2248
+ }
2249
+ }
2250
+ // ===== REQUEST HANDLER =====
2251
+ async handleRequest(req, res) {
2252
+ const startTime = Date.now();
2253
+ if (this.config.dashboard && req.url?.startsWith(this.config.dashboardPath)) {
2254
+ return this.serveDashboard(req, res);
2255
+ }
2256
+ if (req.url === "/health" || req.url === "/__cto/health") {
2257
+ res.writeHead(200, { "Content-Type": "application/json" });
2258
+ res.end(JSON.stringify({
2259
+ status: "ok",
2260
+ version: "4.0.0",
2261
+ uptime: process.uptime(),
2262
+ analysis: this.analysis ? "ready" : "loading"
2263
+ }));
2264
+ return;
2265
+ }
2266
+ if (this.config.apiKey) {
2267
+ const authHeader = req.headers["x-cto-key"] || req.headers["authorization"]?.replace(/^Bearer\s+/i, "") || "";
2268
+ if (authHeader !== this.config.apiKey) {
2269
+ res.writeHead(401, { "Content-Type": "application/json" });
2270
+ res.end(JSON.stringify({ error: "Unauthorized. Set x-cto-key header or Authorization: Bearer <key>" }));
2271
+ return;
2272
+ }
2273
+ }
2274
+ if (req.method !== "POST") {
2275
+ res.writeHead(405, { "Content-Type": "application/json" });
2276
+ res.end(JSON.stringify({ error: "Method not allowed. Gateway only proxies POST requests." }));
2277
+ return;
2278
+ }
2279
+ let body;
2280
+ try {
2281
+ body = await readBody(req, this.config.maxBodyBytes);
2282
+ } catch (err) {
2283
+ const status = err.message === "body-too-large" ? 413 : 400;
2284
+ res.writeHead(status, { "Content-Type": "application/json" });
2285
+ res.end(JSON.stringify({ error: status === 413 ? `Request body too large. Max: ${Math.round(this.config.maxBodyBytes / 1024 / 1024)}MB` : "Failed to read request body" }));
2286
+ return;
2287
+ }
2288
+ let parsedBody;
2289
+ try {
2290
+ parsedBody = JSON.parse(body);
2291
+ } catch {
2292
+ res.writeHead(400, { "Content-Type": "application/json" });
2293
+ res.end(JSON.stringify({ error: "Invalid JSON in request body" }));
2294
+ return;
2295
+ }
2296
+ const targetUrl = req.headers["x-cto-target"] || req.headers["x-target-url"] || "";
2297
+ if (!targetUrl) {
2298
+ res.writeHead(400, { "Content-Type": "application/json" });
2299
+ res.end(JSON.stringify({
2300
+ error: "Missing target URL. Set x-cto-target header to the provider API URL.",
2301
+ example: "x-cto-target: https://api.openai.com/v1/chat/completions"
2302
+ }));
2303
+ return;
2304
+ }
2305
+ let targetUrlParsed;
2306
+ try {
2307
+ targetUrlParsed = new URL(targetUrl);
2308
+ } catch {
2309
+ res.writeHead(400, { "Content-Type": "application/json" });
2310
+ res.end(JSON.stringify({ error: "Invalid target URL" }));
2311
+ return;
2312
+ }
2313
+ if (targetUrlParsed.protocol !== "https:" && targetUrlParsed.hostname !== "localhost") {
2314
+ res.writeHead(403, { "Content-Type": "application/json" });
2315
+ res.end(JSON.stringify({ error: "Only HTTPS targets allowed (SSRF protection)" }));
2316
+ return;
2317
+ }
2318
+ if (!isAllowedTarget(targetUrlParsed.hostname, this.config)) {
2319
+ res.writeHead(403, { "Content-Type": "application/json" });
2320
+ res.end(JSON.stringify({
2321
+ error: `Target domain not allowed: ${targetUrlParsed.hostname}`,
2322
+ allowed: this.config.allowedTargetDomains.length > 0 ? this.config.allowedTargetDomains : ["api.openai.com", "api.anthropic.com", "*.googleapis.com", "*.openai.azure.com"]
2323
+ }));
2324
+ return;
2325
+ }
2326
+ try {
2327
+ const resolved = await lookup(targetUrlParsed.hostname);
2328
+ if (isPrivateIP(resolved.address)) {
2329
+ res.writeHead(403, { "Content-Type": "application/json" });
2330
+ res.end(JSON.stringify({ error: "Target resolves to private IP (SSRF protection)" }));
2331
+ return;
2332
+ }
2333
+ } catch {
2334
+ }
2335
+ const headers = flattenHeaders(req.headers);
2336
+ const provider = detectProvider(targetUrl || req.url || "", headers);
2337
+ const parsed = provider.parseRequest(parsedBody);
2338
+ const now = /* @__PURE__ */ new Date();
2339
+ if (this.tracker.isDailyBudgetExceeded(now)) {
2340
+ res.writeHead(429, { "Content-Type": "application/json" });
2341
+ res.end(JSON.stringify({
2342
+ error: "Daily budget exceeded",
2343
+ budget: this.config.budgetDaily,
2344
+ current: this.tracker.getDailyCost(now)
2345
+ }));
2346
+ return;
2347
+ }
2348
+ if (this.tracker.isMonthlyBudgetExceeded(now)) {
2349
+ res.writeHead(429, { "Content-Type": "application/json" });
2350
+ res.end(JSON.stringify({
2351
+ error: "Monthly budget exceeded",
2352
+ budget: this.config.budgetMonthly,
2353
+ current: this.tracker.getMonthlyCost(now)
2354
+ }));
2355
+ return;
2356
+ }
2357
+ if (this.analysisPromise && !this.analysis) {
2358
+ try {
2359
+ await this.analysisPromise;
2360
+ } catch {
2361
+ }
2362
+ }
2363
+ const interceptResult = await interceptRequest(parsed.messages, this.config, this.analysis);
2364
+ if (interceptResult.secretsBlocked) {
2365
+ res.writeHead(403, { "Content-Type": "application/json" });
2366
+ res.end(JSON.stringify({
2367
+ error: "Request blocked: secrets detected in message content",
2368
+ decisions: interceptResult.decisions,
2369
+ secretsRedacted: interceptResult.secretsRedacted
2370
+ }));
2371
+ this.tracker.record({
2372
+ provider: provider.name,
2373
+ model: parsed.model,
2374
+ inputTokens: 0,
2375
+ outputTokens: 0,
2376
+ costUSD: 0,
2377
+ originalTokens: interceptResult.originalTokens,
2378
+ optimizedTokens: 0,
2379
+ savedTokens: 0,
2380
+ savedUSD: 0,
2381
+ secretsRedacted: interceptResult.secretsRedacted,
2382
+ secretsBlocked: true,
2383
+ projectPath: this.config.projectPath,
2384
+ latencyMs: Date.now() - startTime,
2385
+ stream: parsed.stream,
2386
+ error: "blocked:secrets"
2387
+ });
2388
+ return;
2389
+ }
2390
+ const modifiedBody = rebuildRequestBody(parsedBody, interceptResult.messages, provider.name);
2391
+ try {
2392
+ await this.proxyRequest(targetUrl, req, res, modifiedBody, provider, parsed, interceptResult, startTime);
2393
+ } catch (err) {
2394
+ if (!res.headersSent) {
2395
+ const status = err.message === "upstream-timeout" ? 504 : 502;
2396
+ res.writeHead(status, { "Content-Type": "application/json" });
2397
+ res.end(JSON.stringify({ error: status === 504 ? "Upstream provider timeout" : `Proxy error: ${err.message}` }));
2398
+ }
2399
+ this.emit({ type: "error", message: `Proxy error: ${err.message}`, error: err });
2400
+ }
2401
+ }
2402
+ // ===== PROXY =====
2403
+ async proxyRequest(targetUrl, clientReq, clientRes, body, provider, parsed, interceptResult, startTime) {
2404
+ const url = new URL(targetUrl);
2405
+ const isHttps = url.protocol === "https:";
2406
+ const requester = isHttps ? httpsRequest : httpRequest;
2407
+ const forwardHeaders = {};
2408
+ const stripHeaders = /* @__PURE__ */ new Set(["host", "content-length", "x-cto-target", "x-target-url", "x-cto-key"]);
2409
+ for (const [key, value] of Object.entries(clientReq.headers)) {
2410
+ if (stripHeaders.has(key)) continue;
2411
+ if (value) forwardHeaders[key] = Array.isArray(value) ? value[0] : value;
2412
+ }
2413
+ forwardHeaders["content-length"] = Buffer.byteLength(body).toString();
2414
+ return new Promise((resolve5, reject) => {
2415
+ const proxyReq = requester(
2416
+ {
2417
+ hostname: url.hostname,
2418
+ port: url.port || (isHttps ? 443 : 80),
2419
+ path: url.pathname + url.search,
2420
+ method: "POST",
2421
+ headers: forwardHeaders,
2422
+ agent: isHttps ? this.httpsAgent : this.httpAgent,
2423
+ // Connection pooling
2424
+ timeout: this.config.upstreamTimeoutMs
2425
+ },
2426
+ (proxyRes) => {
2427
+ if (parsed.stream && proxyRes.headers["content-type"]?.includes("text/event-stream")) {
2428
+ this.handleStreamResponse(
2429
+ proxyRes,
2430
+ clientRes,
2431
+ provider,
2432
+ parsed,
2433
+ interceptResult,
2434
+ startTime
2435
+ ).then(resolve5).catch(reject);
2436
+ } else {
2437
+ this.handleBufferedResponse(
2438
+ proxyRes,
2439
+ clientRes,
2440
+ provider,
2441
+ parsed,
2442
+ interceptResult,
2443
+ startTime
2444
+ ).then(resolve5).catch(reject);
2445
+ }
2446
+ }
2447
+ );
2448
+ proxyReq.on("timeout", () => {
2449
+ proxyReq.destroy();
2450
+ reject(new Error("upstream-timeout"));
2451
+ });
2452
+ proxyReq.on("error", reject);
2453
+ proxyReq.write(body);
2454
+ proxyReq.end();
2455
+ });
2456
+ }
2457
+ // ===== STREAM HANDLER =====
2458
+ async handleStreamResponse(proxyRes, clientRes, provider, parsed, interceptResult, startTime) {
2459
+ clientRes.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
2460
+ let fullContent2 = "";
2461
+ let inputTokens = 0;
2462
+ let outputTokens = 0;
2463
+ let sseBuffer = "";
2464
+ return new Promise((resolve5) => {
2465
+ proxyRes.on("data", (chunk) => {
2466
+ clientRes.write(chunk);
2467
+ sseBuffer += chunk.toString();
2468
+ const events = sseBuffer.split("\n\n");
2469
+ sseBuffer = events.pop() || "";
2470
+ for (const event of events) {
2471
+ for (const line of event.split("\n")) {
2472
+ if (!line.startsWith("data: ")) continue;
2473
+ const data = line.slice(6).trim();
2474
+ if (data === "[DONE]") continue;
2475
+ try {
2476
+ const obj = JSON.parse(data);
2477
+ const delta = obj.choices?.[0]?.delta?.content || obj.delta?.text || "";
2478
+ if (delta) fullContent2 += delta;
2479
+ if (obj.usage) {
2480
+ inputTokens = obj.usage.prompt_tokens || obj.usage.input_tokens || 0;
2481
+ outputTokens = obj.usage.completion_tokens || obj.usage.output_tokens || 0;
2482
+ }
2483
+ } catch {
2484
+ }
2485
+ }
2486
+ }
2487
+ });
2488
+ proxyRes.on("end", () => {
2489
+ if (sseBuffer.trim()) {
2490
+ for (const line of sseBuffer.split("\n")) {
2491
+ if (!line.startsWith("data: ")) continue;
2492
+ const data = line.slice(6).trim();
2493
+ if (data === "[DONE]") continue;
2494
+ try {
2495
+ const obj = JSON.parse(data);
2496
+ if (obj.usage) {
2497
+ inputTokens = obj.usage.prompt_tokens || obj.usage.input_tokens || 0;
2498
+ outputTokens = obj.usage.completion_tokens || obj.usage.output_tokens || 0;
2499
+ }
2500
+ } catch {
2501
+ }
2502
+ }
2503
+ }
2504
+ clientRes.end();
2505
+ if (inputTokens === 0) inputTokens = interceptResult.optimizedTokens;
2506
+ if (outputTokens === 0) outputTokens = Math.ceil(fullContent2.length / 4);
2507
+ const costUSD = estimateCost(provider, parsed.model, inputTokens, outputTokens);
2508
+ const originalCost = estimateCost(provider, parsed.model, interceptResult.originalTokens, outputTokens);
2509
+ this.tracker.record({
2510
+ provider: provider.name,
2511
+ model: parsed.model,
2512
+ inputTokens,
2513
+ outputTokens,
2514
+ costUSD,
2515
+ originalTokens: interceptResult.originalTokens,
2516
+ optimizedTokens: interceptResult.optimizedTokens,
2517
+ savedTokens: interceptResult.originalTokens - interceptResult.optimizedTokens,
2518
+ savedUSD: Math.max(0, originalCost - costUSD),
2519
+ secretsRedacted: interceptResult.secretsRedacted,
2520
+ secretsBlocked: false,
2521
+ projectPath: this.config.projectPath,
2522
+ latencyMs: Date.now() - startTime,
2523
+ stream: true
2524
+ });
2525
+ resolve5();
2526
+ });
2527
+ proxyRes.on("error", () => {
2528
+ clientRes.end();
2529
+ resolve5();
2530
+ });
2531
+ });
2532
+ }
2533
+ // ===== BUFFERED HANDLER =====
2534
+ async handleBufferedResponse(proxyRes, clientRes, provider, parsed, interceptResult, startTime) {
2535
+ return new Promise((resolve5) => {
2536
+ const chunks = [];
2537
+ proxyRes.on("data", (chunk) => chunks.push(chunk));
2538
+ proxyRes.on("end", () => {
2539
+ const responseBody = Buffer.concat(chunks).toString();
2540
+ clientRes.writeHead(proxyRes.statusCode || 200, proxyRes.headers);
2541
+ clientRes.end(responseBody);
2542
+ try {
2543
+ const responseJson = JSON.parse(responseBody);
2544
+ const parsedResponse = provider.parseResponse(responseJson, false);
2545
+ const costUSD = estimateCost(
2546
+ provider,
2547
+ parsedResponse.model || parsed.model,
2548
+ parsedResponse.inputTokens,
2549
+ parsedResponse.outputTokens
2550
+ );
2551
+ const originalCost = estimateCost(
2552
+ provider,
2553
+ parsed.model,
2554
+ interceptResult.originalTokens,
2555
+ parsedResponse.outputTokens
2556
+ );
2557
+ this.tracker.record({
2558
+ provider: provider.name,
2559
+ model: parsedResponse.model || parsed.model,
2560
+ inputTokens: parsedResponse.inputTokens,
2561
+ outputTokens: parsedResponse.outputTokens,
2562
+ costUSD,
2563
+ originalTokens: interceptResult.originalTokens,
2564
+ optimizedTokens: interceptResult.optimizedTokens,
2565
+ savedTokens: interceptResult.originalTokens - interceptResult.optimizedTokens,
2566
+ savedUSD: Math.max(0, originalCost - costUSD),
2567
+ secretsRedacted: interceptResult.secretsRedacted,
2568
+ secretsBlocked: false,
2569
+ projectPath: this.config.projectPath,
2570
+ latencyMs: Date.now() - startTime,
2571
+ stream: false
2572
+ });
2573
+ } catch {
2574
+ this.tracker.record({
2575
+ provider: provider.name,
2576
+ model: parsed.model,
2577
+ inputTokens: interceptResult.optimizedTokens,
2578
+ outputTokens: 0,
2579
+ costUSD: 0,
2580
+ originalTokens: interceptResult.originalTokens,
2581
+ optimizedTokens: interceptResult.optimizedTokens,
2582
+ savedTokens: interceptResult.originalTokens - interceptResult.optimizedTokens,
2583
+ savedUSD: 0,
2584
+ secretsRedacted: interceptResult.secretsRedacted,
2585
+ secretsBlocked: false,
2586
+ projectPath: this.config.projectPath,
2587
+ latencyMs: Date.now() - startTime,
2588
+ stream: false,
2589
+ error: "response-parse-failed"
2590
+ });
2591
+ }
2592
+ resolve5();
2593
+ });
2594
+ proxyRes.on("error", () => {
2595
+ clientRes.end();
2596
+ resolve5();
2597
+ });
2598
+ });
2599
+ }
2600
+ // ===== DASHBOARD =====
2601
+ serveDashboard(_req, res) {
2602
+ const summary = this.tracker.getSummary("month");
2603
+ const dailySummary = this.tracker.getSummary("day");
2604
+ const html = generateDashboardHTML(summary, dailySummary, this.config, this.analysis);
2605
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2606
+ res.end(html);
2607
+ }
2608
+ };
2609
+ function readBody(req, maxBytes = 0) {
2610
+ return new Promise((resolve5, reject) => {
2611
+ const chunks = [];
2612
+ let totalBytes = 0;
2613
+ req.on("data", (chunk) => {
2614
+ totalBytes += chunk.length;
2615
+ if (maxBytes > 0 && totalBytes > maxBytes) {
2616
+ req.destroy();
2617
+ reject(new Error("body-too-large"));
2618
+ return;
2619
+ }
2620
+ chunks.push(chunk);
2621
+ });
2622
+ req.on("end", () => resolve5(Buffer.concat(chunks).toString()));
2623
+ req.on("error", reject);
2624
+ });
2625
+ }
2626
+ function flattenHeaders(headers) {
2627
+ const flat = {};
2628
+ for (const [key, value] of Object.entries(headers)) {
2629
+ if (value) flat[key] = Array.isArray(value) ? value[0] : value;
2630
+ }
2631
+ return flat;
2632
+ }
2633
+ function rebuildRequestBody(original, messages, provider) {
2634
+ const body = { ...original };
2635
+ if (provider === "anthropic") {
2636
+ const systemMsg = messages.find((m) => m.role === "system");
2637
+ const otherMsgs = messages.filter((m) => m.role !== "system");
2638
+ if (systemMsg) body.system = systemMsg.content;
2639
+ body.messages = otherMsgs;
2640
+ } else if (provider === "google") {
2641
+ const systemMsg = messages.find((m) => m.role === "system");
2642
+ const otherMsgs = messages.filter((m) => m.role !== "system");
2643
+ if (systemMsg) {
2644
+ body.systemInstruction = { parts: [{ text: systemMsg.content }] };
2645
+ }
2646
+ body.contents = otherMsgs.map((m) => ({
2647
+ role: m.role === "assistant" ? "model" : "user",
2648
+ parts: [{ text: m.content }]
2649
+ }));
2650
+ } else {
2651
+ body.messages = messages;
2652
+ }
2653
+ return JSON.stringify(body);
2654
+ }
2655
+ function generateDashboardHTML(monthly, daily, config, analysis) {
2656
+ const modelRows = Object.entries(monthly.byModel).sort(([, a], [, b]) => b.costUSD - a.costUSD).map(
2657
+ ([model, data]) => `<tr><td>${model}</td><td>${data.requests}</td><td>${(data.tokens / 1e3).toFixed(1)}K</td><td>$${data.costUSD.toFixed(4)}</td></tr>`
2658
+ ).join("");
2659
+ const providerRows = Object.entries(monthly.byProvider).sort(([, a], [, b]) => b.costUSD - a.costUSD).map(
2660
+ ([provider, data]) => `<tr><td>${provider}</td><td>${data.requests}</td><td>$${data.costUSD.toFixed(4)}</td></tr>`
2661
+ ).join("");
2662
+ return `<!DOCTYPE html>
2663
+ <html lang="en">
2664
+ <head>
2665
+ <meta charset="utf-8">
2666
+ <meta name="viewport" content="width=device-width, initial-scale=1">
2667
+ <title>CTO Gateway Dashboard</title>
2668
+ <style>
2669
+ * { margin: 0; padding: 0; box-sizing: border-box; }
2670
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #0a0a0f; color: #e0e0e0; padding: 2rem; }
2671
+ h1 { font-size: 1.8rem; margin-bottom: 0.5rem; color: #fff; }
2672
+ h2 { font-size: 1.2rem; margin: 2rem 0 1rem; color: #8b8bff; }
2673
+ .subtitle { color: #666; margin-bottom: 2rem; }
2674
+ .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 1rem; margin-bottom: 2rem; }
2675
+ .card { background: #14141f; border: 1px solid #2a2a3a; border-radius: 12px; padding: 1.5rem; }
2676
+ .card .label { font-size: 0.75rem; text-transform: uppercase; color: #666; letter-spacing: 0.05em; }
2677
+ .card .value { font-size: 2rem; font-weight: 700; color: #fff; margin-top: 0.25rem; }
2678
+ .card .detail { font-size: 0.85rem; color: #888; margin-top: 0.25rem; }
2679
+ .card.green .value { color: #4ade80; }
2680
+ .card.red .value { color: #f87171; }
2681
+ .card.blue .value { color: #60a5fa; }
2682
+ .card.purple .value { color: #a78bfa; }
2683
+ table { width: 100%; border-collapse: collapse; margin-top: 0.5rem; }
2684
+ th { text-align: left; padding: 0.5rem; color: #666; font-size: 0.75rem; text-transform: uppercase; border-bottom: 1px solid #2a2a3a; }
2685
+ td { padding: 0.5rem; border-bottom: 1px solid #1a1a2a; font-size: 0.9rem; }
2686
+ .status { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 8px; }
2687
+ .status.on { background: #4ade80; }
2688
+ .status.off { background: #666; }
2689
+ .footer { margin-top: 3rem; color: #444; font-size: 0.75rem; }
2690
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 0.7rem; font-weight: 600; }
2691
+ .badge.critical { background: #7f1d1d; color: #fca5a5; }
2692
+ .badge.ok { background: #14532d; color: #86efac; }
2693
+ </style>
2694
+ </head>
2695
+ <body>
2696
+ <h1>\u26A1 CTO Context Gateway</h1>
2697
+ <p class="subtitle">Real-time AI proxy with context optimization, secret redaction, and cost tracking</p>
2698
+
2699
+ <h2>Today</h2>
2700
+ <div class="grid">
2701
+ <div class="card blue">
2702
+ <div class="label">Requests</div>
2703
+ <div class="value">${daily.totalRequests}</div>
2704
+ </div>
2705
+ <div class="card">
2706
+ <div class="label">Cost</div>
2707
+ <div class="value">$${daily.totalCostUSD.toFixed(2)}</div>
2708
+ ${config.budgetDaily > 0 ? `<div class="detail">Budget: $${config.budgetDaily}/day</div>` : ""}
2709
+ </div>
2710
+ <div class="card green">
2711
+ <div class="label">Tokens Saved</div>
2712
+ <div class="value">${(daily.totalSavedTokens / 1e3).toFixed(1)}K</div>
2713
+ <div class="detail">$${daily.totalSavedUSD.toFixed(2)} saved</div>
2714
+ </div>
2715
+ <div class="card ${daily.totalSecretsRedacted > 0 ? "red" : ""}">
2716
+ <div class="label">Secrets Redacted</div>
2717
+ <div class="value">${daily.totalSecretsRedacted}</div>
2718
+ </div>
2719
+ </div>
2720
+
2721
+ <h2>This Month</h2>
2722
+ <div class="grid">
2723
+ <div class="card blue">
2724
+ <div class="label">Total Requests</div>
2725
+ <div class="value">${monthly.totalRequests}</div>
2726
+ </div>
2727
+ <div class="card">
2728
+ <div class="label">Total Cost</div>
2729
+ <div class="value">$${monthly.totalCostUSD.toFixed(2)}</div>
2730
+ ${config.budgetMonthly > 0 ? `<div class="detail">Budget: $${config.budgetMonthly}/month</div>` : ""}
2731
+ </div>
2732
+ <div class="card green">
2733
+ <div class="label">Total Saved</div>
2734
+ <div class="value">$${monthly.totalSavedUSD.toFixed(2)}</div>
2735
+ <div class="detail">${(monthly.totalSavedTokens / 1e3).toFixed(0)}K tokens</div>
2736
+ </div>
2737
+ <div class="card purple">
2738
+ <div class="label">Tokens Processed</div>
2739
+ <div class="value">${((monthly.totalInputTokens + monthly.totalOutputTokens) / 1e3).toFixed(0)}K</div>
2740
+ <div class="detail">${(monthly.totalInputTokens / 1e3).toFixed(0)}K in / ${(monthly.totalOutputTokens / 1e3).toFixed(0)}K out</div>
2741
+ </div>
2742
+ </div>
2743
+
2744
+ <h2>Features</h2>
2745
+ <div class="grid">
2746
+ <div class="card">
2747
+ <div class="label">Context Optimization</div>
2748
+ <div class="value"><span class="status ${config.optimize ? "on" : "off"}"></span>${config.optimize ? "ON" : "OFF"}</div>
2749
+ ${analysis ? `<div class="detail">${analysis.totalFiles} files, ${(analysis.totalTokens / 1e3).toFixed(0)}K tokens</div>` : '<div class="detail">Loading analysis...</div>'}
2750
+ </div>
2751
+ <div class="card">
2752
+ <div class="label">Secret Redaction</div>
2753
+ <div class="value"><span class="status ${config.redactSecrets ? "on" : "off"}"></span>${config.redactSecrets ? "ON" : "OFF"}</div>
2754
+ ${config.blockOnSecrets ? '<span class="badge critical">BLOCKING</span>' : ""}
2755
+ </div>
2756
+ <div class="card">
2757
+ <div class="label">Cost Tracking</div>
2758
+ <div class="value"><span class="status ${config.costTracking ? "on" : "off"}"></span>${config.costTracking ? "ON" : "OFF"}</div>
2759
+ </div>
2760
+ <div class="card">
2761
+ <div class="label">Audit Log</div>
2762
+ <div class="value"><span class="status ${config.auditLog ? "on" : "off"}"></span>${config.auditLog ? "ON" : "OFF"}</div>
2763
+ <div class="detail">${config.logDir}</div>
2764
+ </div>
2765
+ </div>
2766
+
2767
+ ${modelRows ? `
2768
+ <h2>By Model</h2>
2769
+ <div class="card">
2770
+ <table>
2771
+ <thead><tr><th>Model</th><th>Requests</th><th>Tokens</th><th>Cost</th></tr></thead>
2772
+ <tbody>${modelRows}</tbody>
2773
+ </table>
2774
+ </div>` : ""}
2775
+
2776
+ ${providerRows ? `
2777
+ <h2>By Provider</h2>
2778
+ <div class="card">
2779
+ <table>
2780
+ <thead><tr><th>Provider</th><th>Requests</th><th>Cost</th></tr></thead>
2781
+ <tbody>${providerRows}</tbody>
2782
+ </table>
2783
+ </div>` : ""}
2784
+
2785
+ <div class="footer">
2786
+ CTO Context Gateway v4.0.0 \xB7 Listening on ${config.host}:${config.port} \xB7 <a href="/health" style="color:#666">Health</a>
2787
+ </div>
2788
+
2789
+ <script>setTimeout(() => location.reload(), 30000);</script>
2790
+ </body>
2791
+ </html>`;
2792
+ }
2793
+ export {
2794
+ ContextGateway,
2795
+ DEFAULT_GATEWAY_CONFIG,
2796
+ PROVIDERS,
2797
+ UsageTracker,
2798
+ detectProvider,
2799
+ estimateCost,
2800
+ getModelConfig,
2801
+ interceptRequest
2802
+ };
2803
+ //# sourceMappingURL=index.js.map