minovative-mind-cli 2.8.3 → 2.9.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.
@@ -1,8 +1,8 @@
1
- import { SchemaType, } from '@google/generative-ai';
1
+ import { SchemaType } from '@google/generative-ai';
2
2
  import { GEMINI_MODELS, DEFAULT_MODEL, MAX_OUTPUT_TOKENS, isByokEnabled } from '../utils/config.js';
3
3
  import { getToolDeclarations } from './agent-tools.js';
4
4
  import { getMetricCollector } from './metrics.js';
5
- import { getAuthorizedIdToken } from './auth.js';
5
+ import { getAuthorizedIdToken, checkByokSubscription } from './auth.js';
6
6
  import { debugLog } from '../utils/logger.js';
7
7
  import { readCache, writeCache } from '../utils/projectStorage.js';
8
8
  import { GENERAL_CHAT_INSTRUCTION, PLAN_EXECUTION_INSTRUCTION, PLAN_MODE_INSTRUCTION, CONTEXT_SYSTEM_INSTRUCTION, INTENT_ROUTER_SYSTEM_INSTRUCTION, WEB_SEARCH_SYSTEM_INSTRUCTION, EXECUTION_COMPLEXITY_SYSTEM_INSTRUCTION, INVESTIGATION_COMPLEXITY_SYSTEM_INSTRUCTION, HISTORY_SUMMARIZER_SYSTEM_INSTRUCTION, } from '../utils/systemPrompts.js';
@@ -186,6 +186,14 @@ export class ProxyChatSession {
186
186
  if (!idToken) {
187
187
  throw new Error('You are not signed in. Please run `minovative-mind-cli login` first.');
188
188
  }
189
+ const byokEnabled = await isByokEnabled();
190
+ if (byokEnabled) {
191
+ const subCheck = await checkByokSubscription();
192
+ if (!subCheck.active) {
193
+ throw new Error(subCheck.message ||
194
+ 'A $3.99/month BYOK Subscription is required to use your own API key. Please visit https://www.minovativemind.dev/pricing to subscribe. The $3.99 is to cover account maintance for you.');
195
+ }
196
+ }
189
197
  // Convert message to Part, truncating text to prevent memory blowout
190
198
  let newParts;
191
199
  if (typeof message === 'string') {
@@ -228,7 +236,6 @@ export class ProxyChatSession {
228
236
  // Prune old history before sending to keep payload bounded
229
237
  await this.pruneHistory();
230
238
  const effectiveGenerationConfig = { ...this.generationConfig };
231
- const byokEnabled = await isByokEnabled();
232
239
  let result;
233
240
  if (byokEnabled) {
234
241
  const creds = await loadCredentials();
@@ -341,9 +348,11 @@ export function getPlanModeConfig() {
341
348
  * Compresses a large string of text using gemini-3.5-flash-lite.
342
349
  * Used for shrinking context payloads to prevent OOM/choking.
343
350
  */
344
- export async function compressTextUsingFlashLite(text, instruction = "<directives>\nSummarize the following text concisely. Preserve the most critical technical details, function names, and architecture logic. Make sure it's understandable without the fluff.\n</directives>", inlineData, force = false) {
351
+ export async function compressTextUsingFlashLite(text, instruction = "<directives>\nSummarize the following text concisely. Preserve the most critical technical details, function names, and architecture logic. Make sure it's understandable without the fluff.\n</directives>", inlineData, force = false, abortSignal) {
345
352
  if (!text || (!force && text.length < 1000 && !inlineData))
346
353
  return text; // Don't compress tiny texts unless forced
354
+ if (abortSignal?.aborted)
355
+ return text;
347
356
  try {
348
357
  const idToken = await getAuthorizedIdToken();
349
358
  if (!idToken)
@@ -357,13 +366,19 @@ export async function compressTextUsingFlashLite(text, instruction = "<directive
357
366
  const byokEnabled = await isByokEnabled();
358
367
  let result;
359
368
  if (byokEnabled) {
369
+ const subCheck = await checkByokSubscription();
370
+ if (!subCheck.active) {
371
+ throw new Error(subCheck.message ||
372
+ 'A $3.99/month BYOK Subscription is required. Visit https://www.minovativemind.dev/pricing');
373
+ }
360
374
  const creds = await loadCredentials();
361
375
  result = await proxyClient.generateViaBYOK(creds.geminiApiKey, model, contents, [], // no tools
362
- undefined, instruction, { temperature: 0.2 });
376
+ undefined, instruction, { temperature: 0.2 }, undefined, abortSignal);
363
377
  }
364
378
  else {
365
379
  result = await proxyClient.generateFunctionCallViaProxy(idToken, model, contents, [], // no tools
366
- undefined, instruction, { temperature: 0.2 });
380
+ undefined, instruction, { temperature: 0.2 }, // low temp for factual summary
381
+ undefined, abortSignal);
367
382
  }
368
383
  let textPart = '';
369
384
  if (result.parts) {
@@ -379,6 +394,9 @@ export async function compressTextUsingFlashLite(text, instruction = "<directive
379
394
  return summary ? summary : text;
380
395
  }
381
396
  catch (error) {
397
+ if (abortSignal?.aborted || error?.name === 'AbortError' || error?.message?.includes('abort')) {
398
+ return text;
399
+ }
382
400
  debugLog(`Failed to compress text using flash-lite: ${error}`);
383
401
  if (error?.status === 401 ||
384
402
  error?.status === 403 ||
@@ -483,7 +501,7 @@ export function getContextToolDeclarations() {
483
501
  },
484
502
  {
485
503
  name: 'run_analysis_script',
486
- description: "Write and execute a disposable analysis script to structurally map code in the workspace. Use this to get exact line ranges for functions, classes, and variables by leveraging the language's native AST parser (e.g., TypeScript compiler API, Python ast module, go/parser). You can also use this to probe the development environment — detecting available runtimes (e.g., node --version, python3 --version), checking if ports are in use, identifying project type (monorepo, package manager), or diagnosing system-level issues (disk space, memory) that may affect execution. For complex investigation tasks, you can write lightweight ML scripts (e.g., TF-IDF cosine similarity to rank file relevance, Z-score outlier detection for anomalous log lines, K-Means clustering, or Naive Bayes classification). Default to \"node\" for generic math/analysis as a safe baseline, but act like a native inhabitant of the host environment — if Python, Go, Rust, or specialized libraries are available in the project context, leverage the host's native runtimes and standard libraries for maximum efficiency. The script is executed from a temporary directory and automatically cleaned up after execution. Output should be structured JSON to stdout. Use the results to make precise read_file calls with exact startLine/endLine instead of guessing. CRITICAL: Do not use this tool on binary, document, or non-code files (e.g. PDF, image, audio, docx).",
504
+ description: 'Write and execute a disposable analysis script to structurally map code in the workspace. Use this to get exact line ranges for functions, classes, and variables by leveraging the language\'s native AST parser (e.g., TypeScript compiler API, Python ast module, go/parser). You can also use this to probe the development environment — detecting available runtimes (e.g., node --version, python3 --version), checking if ports are in use, identifying project type (monorepo, package manager), or diagnosing system-level issues (disk space, memory) that may affect execution. For complex investigation tasks, you can write lightweight ML scripts (e.g., TF-IDF cosine similarity to rank file relevance, Z-score outlier detection for anomalous log lines, K-Means clustering, or Naive Bayes classification). Default to "node" for generic math/analysis as a safe baseline, but act like a native inhabitant of the host environment — if Python, Go, Rust, or specialized libraries are available in the project context, leverage the host\'s native runtimes and standard libraries for maximum efficiency. The script is executed from a temporary directory and automatically cleaned up after execution. Output should be structured JSON to stdout. Use the results to make precise read_file calls with exact startLine/endLine instead of guessing. CRITICAL: Do not use this tool on binary, document, or non-code files (e.g. PDF, image, audio, docx).',
487
505
  parameters: {
488
506
  type: SchemaType.OBJECT,
489
507
  properties: {
@@ -587,22 +605,35 @@ export function createHistorySummarizerSession() {
587
605
  let model = getGlobalActiveModel();
588
606
  if (model === 'auto' || model.includes('claude'))
589
607
  model = GEMINI_MODELS.FLASH_LITE;
590
- return new ProxyChatSession(model, HISTORY_SUMMARIZER_SYSTEM_INSTRUCTION, [], { temperature: 0.2, maxOutputTokens: MAX_OUTPUT_TOKENS });
608
+ return new ProxyChatSession(model, HISTORY_SUMMARIZER_SYSTEM_INSTRUCTION, [], {
609
+ temperature: 0.2,
610
+ maxOutputTokens: MAX_OUTPUT_TOKENS,
611
+ });
591
612
  }
592
613
  /**
593
614
  * Summarizes an array of Content history entries using Gemini Flash Lite.
594
615
  */
595
- export async function summarizeChatHistory(history) {
616
+ export async function summarizeChatHistory(history, abortSignal) {
596
617
  if (!history || history.length === 0) {
597
618
  return '';
598
619
  }
620
+ if (abortSignal?.aborted) {
621
+ const err = new Error('Operation aborted');
622
+ err.name = 'AbortError';
623
+ throw err;
624
+ }
599
625
  try {
600
626
  const session = createHistorySummarizerSession();
601
627
  session.loadRawHistory(JSON.parse(JSON.stringify(history)));
602
- const result = await session.sendMessage('Summarize the preceding conversation history following your compression rules.');
628
+ const result = await session.sendMessage('Summarize the preceding conversation history following your compression rules.', undefined, abortSignal);
603
629
  return result.response.text() || '';
604
630
  }
605
631
  catch (error) {
632
+ if (abortSignal?.aborted || error?.name === 'AbortError' || error?.message?.includes('abort')) {
633
+ const err = new Error('Operation aborted');
634
+ err.name = 'AbortError';
635
+ throw err;
636
+ }
606
637
  debugLog(`Failed to summarize chat history: ${error?.message || error}`);
607
638
  return '';
608
639
  }
@@ -610,10 +641,12 @@ export async function summarizeChatHistory(history) {
610
641
  /**
611
642
  * Generates a concise title for a chat session based on the user's first message.
612
643
  */
613
- export async function generateChatTitle(firstMessage) {
644
+ export async function generateChatTitle(firstMessage, abortSignal) {
614
645
  const maxLength = 60;
615
646
  if (!firstMessage || firstMessage.trim().length === 0)
616
647
  return 'New Chat';
648
+ if (abortSignal?.aborted)
649
+ return firstMessage.substring(0, maxLength);
617
650
  try {
618
651
  const idToken = await getAuthorizedIdToken();
619
652
  if (!idToken)
@@ -626,13 +659,17 @@ export async function generateChatTitle(firstMessage) {
626
659
  const byokEnabled = await isByokEnabled();
627
660
  let result;
628
661
  if (byokEnabled) {
662
+ const subCheck = await checkByokSubscription();
663
+ if (!subCheck.active) {
664
+ return firstMessage.substring(0, maxLength);
665
+ }
629
666
  const creds = await loadCredentials();
630
667
  result = await proxyClient.generateViaBYOK(creds.geminiApiKey, model, contents, [], // no tools
631
- undefined, instruction, { temperature: 0.2 });
668
+ undefined, instruction, { temperature: 0.2 }, undefined, abortSignal);
632
669
  }
633
670
  else {
634
671
  result = await proxyClient.generateFunctionCallViaProxy(idToken, model, contents, [], // no tools
635
- undefined, instruction, { temperature: 0.2 });
672
+ undefined, instruction, { temperature: 0.2 }, undefined, abortSignal);
636
673
  }
637
674
  let title = '';
638
675
  if (result.parts) {
@@ -1,3 +1,10 @@
1
1
  export declare function login(): Promise<boolean>;
2
2
  export declare function logout(): Promise<void>;
3
3
  export declare function getAuthorizedIdToken(): Promise<string | undefined>;
4
+ /**
5
+ * Checks if the signed-in CLI user has an active $3.99/month BYOK subscription.
6
+ */
7
+ export declare function checkByokSubscription(): Promise<{
8
+ active: boolean;
9
+ message?: string;
10
+ }>;
@@ -160,3 +160,44 @@ export async function getAuthorizedIdToken() {
160
160
  }
161
161
  return undefined;
162
162
  }
163
+ /**
164
+ * Checks if the signed-in CLI user has an active $3.99/month BYOK subscription.
165
+ */
166
+ export async function checkByokSubscription() {
167
+ const idToken = await getAuthorizedIdToken();
168
+ if (!idToken) {
169
+ return {
170
+ active: false,
171
+ message: "Authentication Required: You must be logged into minovative-mind-cli to use BYOK mode. Run 'minovative-mind-cli login' first, then subscribe at https://www.minovativemind.dev/pricing ($3.99/month).",
172
+ };
173
+ }
174
+ try {
175
+ const res = await fetch('https://verifysubscription-6obg3e4zwa-uc.a.run.app', {
176
+ method: 'POST',
177
+ headers: {
178
+ 'Content-Type': 'application/json',
179
+ 'X-Firebase-Auth': `Bearer ${idToken}`,
180
+ },
181
+ });
182
+ if (!res.ok) {
183
+ return {
184
+ active: false,
185
+ message: 'A $3.99/month BYOK Subscription is required to use your own API key. Please visit https://www.minovativemind.dev/pricing to subscribe. The $3.99 is to cover account maintance for you.',
186
+ };
187
+ }
188
+ const data = (await res.json());
189
+ if (!data.hasActiveSubscription) {
190
+ return {
191
+ active: false,
192
+ message: 'A $3.99/month BYOK Subscription is required to use your own API key. Please visit https://www.minovativemind.dev/pricing to subscribe. The $3.99 is to cover account maintance for you.',
193
+ };
194
+ }
195
+ return { active: true };
196
+ }
197
+ catch {
198
+ return {
199
+ active: false,
200
+ message: 'Failed to verify BYOK subscription status. Please check your network connection or visit https://www.minovativemind.dev/pricing to subscribe ($3.99/month).',
201
+ };
202
+ }
203
+ }
@@ -14,8 +14,8 @@ export interface IntentRoute {
14
14
  needsContext: boolean;
15
15
  targetAgent: 'CHAT' | 'EXECUTE';
16
16
  }
17
- export declare function routeIntent(userRequest: string, chatHistory?: string): Promise<IntentRoute>;
18
- export declare function evaluateExecutionComplexity(userRequest: string, investigationSummary: string | undefined, numRelevantFiles: number, chatHistory?: string): Promise<'EASY' | 'HARD'>;
17
+ export declare function routeIntent(userRequest: string, chatHistory?: string, abortSignal?: AbortSignal): Promise<IntentRoute>;
18
+ export declare function evaluateExecutionComplexity(userRequest: string, investigationSummary: string | undefined, numRelevantFiles: number, chatHistory?: string, abortSignal?: AbortSignal): Promise<'EASY' | 'HARD'>;
19
19
  export declare function gatherContext(workspaceRoot: string, userRequest: string, chatHistory: string | undefined, inputHandler: {
20
20
  getAndClear: () => string;
21
21
  waitForPrompt: () => Promise<void>;
@@ -139,14 +139,19 @@ async function detectProjectType(workspaceRoot) {
139
139
  }
140
140
  return types.join(' / ');
141
141
  }
142
- export async function routeIntent(userRequest, chatHistory = '') {
142
+ export async function routeIntent(userRequest, chatHistory = '', abortSignal) {
143
+ if (abortSignal?.aborted) {
144
+ const err = new Error('Operation aborted');
145
+ err.name = 'AbortError';
146
+ throw err;
147
+ }
143
148
  try {
144
149
  const session = createIntentRouterSession();
145
150
  let prompt = `User Request: "${userRequest}"`;
146
151
  if (chatHistory) {
147
152
  prompt = `Previous Conversation Context:\n${chatHistory}\n\n${prompt}`;
148
153
  }
149
- const result = await session.sendMessage(prompt);
154
+ const result = await session.sendMessage(prompt, undefined, abortSignal);
150
155
  const text = result.response.text()?.trim() || '{}';
151
156
  const parsed = JSON.parse(text);
152
157
  debugLog(`Intent Router Parsed: ${JSON.stringify(parsed)}`);
@@ -156,12 +161,22 @@ export async function routeIntent(userRequest, chatHistory = '') {
156
161
  };
157
162
  }
158
163
  catch (e) {
164
+ if (abortSignal?.aborted || e?.name === 'AbortError' || e?.message?.includes('abort')) {
165
+ const err = new Error('Operation aborted');
166
+ err.name = 'AbortError';
167
+ throw err;
168
+ }
159
169
  debugLog(`Intent Router failed to parse JSON, falling back to EXECUTE. Error: ${String(e)}`);
160
170
  // Fallback to searching if the router fails
161
171
  return { needsContext: true, targetAgent: 'EXECUTE' };
162
172
  }
163
173
  }
164
- export async function evaluateExecutionComplexity(userRequest, investigationSummary, numRelevantFiles, chatHistory = '') {
174
+ export async function evaluateExecutionComplexity(userRequest, investigationSummary, numRelevantFiles, chatHistory = '', abortSignal) {
175
+ if (abortSignal?.aborted) {
176
+ const err = new Error('Operation aborted');
177
+ err.name = 'AbortError';
178
+ throw err;
179
+ }
165
180
  try {
166
181
  const session = createExecutionComplexitySession();
167
182
  let prompt = `User Request: "${userRequest}"
@@ -170,24 +185,39 @@ Number of Relevant Files: ${numRelevantFiles}`;
170
185
  if (chatHistory) {
171
186
  prompt = `Previous Conversation Context:\n${chatHistory}\n\n${prompt}`;
172
187
  }
173
- const result = await session.sendMessage(prompt);
188
+ const result = await session.sendMessage(prompt, undefined, abortSignal);
174
189
  const text = result.response.text()?.trim() || '{}';
175
190
  const parsed = JSON.parse(text);
176
191
  debugLog(`Execution Complexity Parsed: ${JSON.stringify(parsed)}`);
177
192
  return parsed.complexity === 'EASY' ? 'EASY' : 'HARD';
178
193
  }
179
194
  catch (e) {
195
+ if (abortSignal?.aborted || e?.name === 'AbortError' || e?.message?.includes('abort')) {
196
+ const err = new Error('Operation aborted');
197
+ err.name = 'AbortError';
198
+ throw err;
199
+ }
180
200
  debugLog(`Execution Complexity Router failed, falling back to HARD. Error: ${String(e)}`);
181
201
  return 'HARD';
182
202
  }
183
203
  }
184
204
  export async function gatherContext(workspaceRoot, userRequest, chatHistory = '', inputHandler, abortSignal, onProgress, onToolCall) {
205
+ if (abortSignal.aborted) {
206
+ const err = new Error('Operation aborted');
207
+ err.name = 'AbortError';
208
+ throw err;
209
+ }
185
210
  // Always skip slash commands for zero latency
186
211
  if (userRequest.startsWith('/')) {
187
212
  return { contextResult: null, targetAgent: 'EXECUTE', chainedMessages: [] };
188
213
  }
189
214
  // Use the AI Intent Router to decide if we need to search
190
- const { needsContext, targetAgent } = await routeIntent(userRequest, chatHistory);
215
+ const { needsContext, targetAgent } = await routeIntent(userRequest, chatHistory, abortSignal);
216
+ if (abortSignal.aborted) {
217
+ const err = new Error('Operation aborted');
218
+ err.name = 'AbortError';
219
+ throw err;
220
+ }
191
221
  debugLog(`GatherContext Route: needsContext=${needsContext}, targetAgent=${targetAgent}`);
192
222
  if (!needsContext) {
193
223
  return { contextResult: null, targetAgent, chainedMessages: [] };
@@ -197,17 +227,22 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
197
227
  let projectTree = '';
198
228
  let primaryProjectType = 'Unknown';
199
229
  for (const { alias, root } of allRoots) {
230
+ if (abortSignal.aborted) {
231
+ const err = new Error('Operation aborted');
232
+ err.name = 'AbortError';
233
+ throw err;
234
+ }
200
235
  const label = alias ? `@${alias} (${root})` : `Primary Workspace (${root})`;
201
236
  const treeResult = await executeTool(root, 'list_directory', { dirPath: '.', maxDepth: 10 });
202
237
  let tree = treeResult.output;
203
238
  if (tree.length > 30000) {
204
- tree = tree.substring(0, 30000) + '\\n... (Project tree truncated due to size)';
239
+ tree = tree.substring(0, 30000) + '\n... (Project tree truncated due to size)';
205
240
  }
206
241
  const type = await detectProjectType(root);
207
242
  if (!alias) {
208
243
  primaryProjectType = type;
209
244
  }
210
- projectTree += `=== ${label} ===\\nProject Type: ${type}\\n${tree}\\n\\n`;
245
+ projectTree += `=== ${label} ===\nProject Type: ${type}\n${tree}\n\n`;
211
246
  }
212
247
  const projectType = primaryProjectType;
213
248
  const { lookupInvestigation, saveInvestigation } = await import('./orchestration/investigationCache.js');
@@ -217,6 +252,11 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
217
252
  onProgress(`⚡ Memory Bank HIT — loaded ${cacheHit.entry.relevantFiles.length} files from cache`);
218
253
  const cachedFiles = new Map();
219
254
  for (const filePath of cacheHit.entry.relevantFiles) {
255
+ if (abortSignal.aborted) {
256
+ const err = new Error('Operation aborted');
257
+ err.name = 'AbortError';
258
+ throw err;
259
+ }
220
260
  const readResult = await executeTool(workspaceRoot, 'read_file', { filePath });
221
261
  if (!readResult.error) {
222
262
  cachedFiles.set(filePath, { text: readResult.output, inlineData: readResult.inlineData });
@@ -227,11 +267,15 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
227
267
  const { resolveAndValidateMultiWorkspacePath } = await import('../utils/pathSecurity.js');
228
268
  const autoDiscovered = new Set();
229
269
  for (const filePath of cacheHit.entry.relevantFiles) {
270
+ if (abortSignal.aborted)
271
+ break;
230
272
  try {
231
273
  const resolved = resolveAndValidateMultiWorkspacePath(workspaceRoot, filePath);
232
274
  const graph = await buildDependencyGraph(resolved.workspaceRoot);
233
275
  const reverseDeps = graph.getImportedBy(resolved.relativePath);
234
276
  for (const dep of reverseDeps) {
277
+ if (abortSignal.aborted)
278
+ break;
235
279
  if (cachedFiles.has(dep) || autoDiscovered.has(dep))
236
280
  continue;
237
281
  if (cachedFiles.size + autoDiscovered.size >= MAX_TOTAL_FILES)
@@ -265,7 +309,7 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
265
309
  if (isSubAgentsEnabled()) {
266
310
  // Determine complexity and domain breakdown
267
311
  const approxFiles = projectTree.split('\n').length;
268
- const complexity = await evaluateInvestigationComplexity(userRequest, projectType, approxFiles, chatHistory);
312
+ const complexity = await evaluateInvestigationComplexity(userRequest, projectType, approxFiles, chatHistory, abortSignal);
269
313
  if (complexity.strategy === 'PARALLEL' && complexity.agentAssignments.length > 0) {
270
314
  const orchestrator = new InvestigationOrchestrator();
271
315
  const parallelResult = await orchestrator.runParallelInvestigation(userRequest, complexity.agentAssignments, workspaceRoot, projectTree, projectType, chatHistory, abortSignal, onProgress, onToolCall);
@@ -292,6 +336,11 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
292
336
  currentMessage += `\n\nStart investigating to find relevant files.`;
293
337
  const MAX_TURNS = Infinity;
294
338
  for (let turn = 0; turn < MAX_TURNS; turn++) {
339
+ if (abortSignal.aborted) {
340
+ const err = new Error('Operation aborted');
341
+ err.name = 'AbortError';
342
+ throw err;
343
+ }
295
344
  await inputHandler.waitForPrompt();
296
345
  const queuedMsg = inputHandler.getAndClear();
297
346
  let additionalText = undefined;
@@ -308,8 +357,10 @@ export async function gatherContext(workspaceRoot, userRequest, chatHistory = ''
308
357
  result = await session.sendMessage(currentMessage, additionalText, abortSignal);
309
358
  }
310
359
  catch (e) {
311
- if (e.name === 'AbortError' || e.message?.includes('abort')) {
312
- break;
360
+ if (abortSignal.aborted || e.name === 'AbortError' || e.message?.includes('abort')) {
361
+ const err = new Error('Operation aborted');
362
+ err.name = 'AbortError';
363
+ throw err;
313
364
  }
314
365
  throw e;
315
366
  }
@@ -42,4 +42,4 @@ export interface InvestigationComplexityResult {
42
42
  * @param chatHistory - Recent conversation history for context.
43
43
  * @returns The complexity classification with domain decomposition.
44
44
  */
45
- export declare function evaluateInvestigationComplexity(userRequest: string, projectType: string, approximateFileCount: number, chatHistory?: string): Promise<InvestigationComplexityResult>;
45
+ export declare function evaluateInvestigationComplexity(userRequest: string, projectType: string, approximateFileCount: number, chatHistory?: string, abortSignal?: AbortSignal): Promise<InvestigationComplexityResult>;
@@ -27,7 +27,12 @@ import { debugLog } from '../utils/logger.js';
27
27
  * @param chatHistory - Recent conversation history for context.
28
28
  * @returns The complexity classification with domain decomposition.
29
29
  */
30
- export async function evaluateInvestigationComplexity(userRequest, projectType, approximateFileCount, chatHistory = '') {
30
+ export async function evaluateInvestigationComplexity(userRequest, projectType, approximateFileCount, chatHistory = '', abortSignal) {
31
+ if (abortSignal?.aborted) {
32
+ const err = new Error('Operation aborted');
33
+ err.name = 'AbortError';
34
+ throw err;
35
+ }
31
36
  try {
32
37
  const session = createInvestigationComplexitySession();
33
38
  let prompt = `User Request: "${userRequest}"
@@ -36,7 +41,7 @@ Approximate File Count: ${approximateFileCount}`;
36
41
  if (chatHistory) {
37
42
  prompt = `Previous Conversation Context:\n${chatHistory}\n\n${prompt}`;
38
43
  }
39
- const result = await session.sendMessage(prompt);
44
+ const result = await session.sendMessage(prompt, undefined, abortSignal);
40
45
  const text = result.response.text()?.trim() || '{}';
41
46
  const parsed = JSON.parse(text);
42
47
  debugLog(`Investigation Complexity Parsed: ${JSON.stringify(parsed)}`);
@@ -80,6 +85,11 @@ Approximate File Count: ${approximateFileCount}`;
80
85
  };
81
86
  }
82
87
  catch (e) {
88
+ if (abortSignal?.aborted || e?.name === 'AbortError' || e?.message?.includes('abort')) {
89
+ const err = new Error('Operation aborted');
90
+ err.name = 'AbortError';
91
+ throw err;
92
+ }
83
93
  debugLog(`Investigation Complexity Router failed, falling back to SINGLE. Error: ${String(e)}`);
84
94
  return {
85
95
  strategy: 'SINGLE',
@@ -2,7 +2,7 @@
2
2
  * @fileoverview Main Orchestrator for Sub-Agent Dispatch and Coordination.
3
3
  *
4
4
  * The orchestrator acts as the "PM Kernel", responsible for:
5
- * 1. Task Decomposition (using gemini-3.6-flash)
5
+ * 1. Task Decomposition (using gemini-3.7-flash)
6
6
  * 2. Graph Validation (Cycle detection via Kahn's algorithm)
7
7
  * 3. Lock Ordering (Conflict resolution across parallel waves)
8
8
  * 4. Parallel Dispatch (Executing waves sequentially, agents in parallel)
@@ -2,7 +2,7 @@
2
2
  * @fileoverview Main Orchestrator for Sub-Agent Dispatch and Coordination.
3
3
  *
4
4
  * The orchestrator acts as the "PM Kernel", responsible for:
5
- * 1. Task Decomposition (using gemini-3.6-flash)
5
+ * 1. Task Decomposition (using gemini-3.7-flash)
6
6
  * 2. Graph Validation (Cycle detection via Kahn's algorithm)
7
7
  * 3. Lock Ordering (Conflict resolution across parallel waves)
8
8
  * 4. Parallel Dispatch (Executing waves sequentially, agents in parallel)
@@ -43,7 +43,7 @@ export class SubAgentRunner {
43
43
  let model = getGlobalActiveModel();
44
44
  if (model === GEMINI_MODELS.AUTO)
45
45
  model = GEMINI_MODELS.FLASH;
46
- // Sub-agents default to flash-3.6 for better reasoning capabilities
46
+ // Sub-agents default to flash-3.7 for better reasoning capabilities
47
47
  this.chat = new ProxyChatSession(model, this.buildSystemInstruction(), [{ functionDeclarations: getScopedToolDeclarations() }], {
48
48
  maxOutputTokens: MAX_OUTPUT_TOKENS,
49
49
  temperature: 0.3, // Lower temperature for more focused execution
@@ -22,12 +22,14 @@ async function delay(ms, abortSignal) {
22
22
  let timeout;
23
23
  const abortHandler = () => {
24
24
  clearTimeout(timeout);
25
- reject(new Error('Operation aborted'));
25
+ const err = new Error('Operation aborted');
26
+ err.name = 'AbortError';
27
+ reject(err);
26
28
  };
27
29
  if (abortSignal?.aborted) {
28
30
  return abortHandler();
29
31
  }
30
- abortSignal?.addEventListener('abort', abortHandler);
32
+ abortSignal?.addEventListener('abort', abortHandler, { once: true });
31
33
  timeout = setTimeout(() => {
32
34
  abortSignal?.removeEventListener('abort', abortHandler);
33
35
  resolve();
@@ -97,6 +99,11 @@ export class ProxyClient {
97
99
  const MAX_DELAY_MS = 30000;
98
100
  let attempt = 0;
99
101
  retryLoop: while (true) {
102
+ if (abortSignal?.aborted) {
103
+ const err = new Error('Operation aborted');
104
+ err.name = 'AbortError';
105
+ throw err;
106
+ }
100
107
  const response = await fetch(this.PROXY_URL, {
101
108
  method: 'POST',
102
109
  headers: {
@@ -115,11 +122,21 @@ export class ProxyClient {
115
122
  });
116
123
  debugLog(`Proxy Request to ${modelName} complete. Status: ${response.status} ${response.statusText}`);
117
124
  if ((response.status === 429 || response.status === 503 || response.status === 502 || response.status === 500 || response.status === 504) && attempt < MAX_RETRIES) {
125
+ if (abortSignal?.aborted) {
126
+ const err = new Error('Operation aborted');
127
+ err.name = 'AbortError';
128
+ throw err;
129
+ }
118
130
  const exponentialDelay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * Math.pow(2, attempt));
119
131
  const delayTime = Math.round(exponentialDelay * (1.0 + Math.random() * 0.5));
120
132
  process.stdout.write('\n');
121
133
  console.warn(`Server error or rate limit hit (${response.status}). Retrying in ${(delayTime / 1000).toFixed(1)}s... (Attempt ${attempt + 1}/${MAX_RETRIES})`);
122
134
  await delay(delayTime, abortSignal);
135
+ if (abortSignal?.aborted) {
136
+ const err = new Error('Operation aborted');
137
+ err.name = 'AbortError';
138
+ throw err;
139
+ }
123
140
  attempt++;
124
141
  continue;
125
142
  }
@@ -231,6 +248,11 @@ export class ProxyClient {
231
248
  }
232
249
  }
233
250
  catch (streamError) {
251
+ if (abortSignal?.aborted || streamError.name === 'AbortError' || streamError.message?.includes('abort')) {
252
+ const err = new Error('Operation aborted');
253
+ err.name = 'AbortError';
254
+ throw err;
255
+ }
234
256
  if (streamError.message?.includes('429') ||
235
257
  streamError.message?.includes('502') ||
236
258
  streamError.message?.includes('503') ||
@@ -245,6 +267,11 @@ export class ProxyClient {
245
267
  process.stdout.write('\n');
246
268
  console.warn(`Server error or rate limit hit during stream. Retrying in ${(delayTime / 1000).toFixed(1)}s... (Attempt ${attempt + 1}/${MAX_RETRIES})`);
247
269
  await delay(delayTime, abortSignal);
270
+ if (abortSignal?.aborted) {
271
+ const err = new Error('Operation aborted');
272
+ err.name = 'AbortError';
273
+ throw err;
274
+ }
248
275
  attempt++;
249
276
  continue retryLoop;
250
277
  }
@@ -287,6 +314,11 @@ export class ProxyClient {
287
314
  const MAX_DELAY_MS = 30000;
288
315
  let attempt = 0;
289
316
  while (true) {
317
+ if (abortSignal?.aborted) {
318
+ const err = new Error('Operation aborted');
319
+ err.name = 'AbortError';
320
+ throw err;
321
+ }
290
322
  const response = await fetch(url, {
291
323
  method: 'POST',
292
324
  headers: { 'Content-Type': 'application/json' },
@@ -300,11 +332,21 @@ export class ProxyClient {
300
332
  response.status === 500 ||
301
333
  response.status === 504) &&
302
334
  attempt < MAX_RETRIES) {
335
+ if (abortSignal?.aborted) {
336
+ const err = new Error('Operation aborted');
337
+ err.name = 'AbortError';
338
+ throw err;
339
+ }
303
340
  const exponentialDelay = Math.min(MAX_DELAY_MS, BASE_DELAY_MS * Math.pow(2, attempt));
304
341
  const delayTime = Math.round(exponentialDelay * (1.0 + Math.random() * 0.5));
305
342
  process.stdout.write('\n');
306
343
  console.warn(`Server error or rate limit hit (${response.status}). Retrying in ${(delayTime / 1000).toFixed(1)}s... (Attempt ${attempt + 1}/${MAX_RETRIES})`);
307
344
  await delay(delayTime, abortSignal);
345
+ if (abortSignal?.aborted) {
346
+ const err = new Error('Operation aborted');
347
+ err.name = 'AbortError';
348
+ throw err;
349
+ }
308
350
  attempt++;
309
351
  continue;
310
352
  }
@@ -17,7 +17,9 @@ export declare const GEMINI_MODELS: {
17
17
  readonly CLAUDE_OPUS: "claude-opus-5";
18
18
  readonly PRO: "gemini-3.1-pro-preview";
19
19
  readonly CLAUDE_SONNET: "claude-sonnet-5";
20
- readonly FLASH: "gemini-3.6-flash";
20
+ readonly FLASH_3_7: "gemini-3.7-flash";
21
+ readonly FLASH: "gemini-3.7-flash";
22
+ readonly FLASH_3_6: "gemini-3.6-flash";
21
23
  readonly FLASH_LITE: "gemini-3.5-flash-lite";
22
24
  readonly AUTO: "auto";
23
25
  };
@@ -17,7 +17,9 @@ export const GEMINI_MODELS = {
17
17
  CLAUDE_OPUS: 'claude-opus-5',
18
18
  PRO: 'gemini-3.1-pro-preview',
19
19
  CLAUDE_SONNET: 'claude-sonnet-5',
20
- FLASH: 'gemini-3.6-flash',
20
+ FLASH_3_7: 'gemini-3.7-flash',
21
+ FLASH: 'gemini-3.7-flash',
22
+ FLASH_3_6: 'gemini-3.6-flash',
21
23
  FLASH_LITE: 'gemini-3.5-flash-lite',
22
24
  AUTO: 'auto',
23
25
  };
@@ -1,6 +1,33 @@
1
+ /**
2
+ * Represents an extracted symbol's location within a source file.
3
+ */
1
4
  export interface ExtractedSymbol {
5
+ /** The name of the symbol (function, class, variable, etc.) */
2
6
  symbol: string;
7
+ /** The 0-indexed starting line number of the symbol declaration/block */
3
8
  startLine: number;
9
+ /** The 0-indexed ending line number of the symbol block */
4
10
  endLine: number;
5
11
  }
12
+ /**
13
+ * Extracts specified target symbols from source file content and returns their line number ranges and names.
14
+ *
15
+ * @param content - The full raw string content of the source file
16
+ * @param filePath - The file path (used to determine language syntax rules via file extension)
17
+ * @param targetElements - An array of symbol names to extract
18
+ * @returns Array of ExtractedSymbol objects containing symbol name, startLine, and endLine
19
+ */
20
+ export declare function extractSymbolMetadata(content: string, filePath: string, targetElements: string[]): ExtractedSymbol[];
21
+ /**
22
+ * Extracts specified target symbols (functions, classes, variables, interfaces, etc.) from source file content
23
+ * using multi-language regex declarations, doc/decorator context gathering, and balanced brace/indentation block parsing.
24
+ *
25
+ * This function significantly reduces token usage when reading large files by returning only the requested symbols
26
+ * along with their context and omission separators.
27
+ *
28
+ * @param content - The full raw string content of the source file
29
+ * @param filePath - The file path (used to determine language syntax rules via file extension)
30
+ * @param targetElements - An array of symbol names to extract (e.g. `['extractSymbols', 'ExtractedSymbol']`)
31
+ * @returns The filtered source string containing only the matched symbol blocks and omission markers
32
+ */
6
33
  export declare function extractSymbols(content: string, filePath: string, targetElements: string[]): string;