@probelabs/probe 0.6.0-rc278 → 0.6.0-rc279

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.
@@ -125,6 +125,27 @@ const MAX_HISTORY_MESSAGES = 100;
125
125
  // Maximum image file size (20MB) to prevent OOM attacks
126
126
  const MAX_IMAGE_FILE_SIZE = 20 * 1024 * 1024;
127
127
 
128
+ /**
129
+ * Truncate a string for debug logging, showing first and last portion.
130
+ */
131
+ export function debugTruncate(s, limit = 200) {
132
+ if (s.length <= limit) return s;
133
+ const half = Math.floor(limit / 2);
134
+ return s.substring(0, half) + ` ... [${s.length} chars] ... ` + s.substring(s.length - half);
135
+ }
136
+
137
+ /**
138
+ * Log tool results details for debug output.
139
+ */
140
+ export function debugLogToolResults(toolResults) {
141
+ if (!toolResults || toolResults.length === 0) return;
142
+ for (const tr of toolResults) {
143
+ const argsStr = JSON.stringify(tr.args || {});
144
+ const resultStr = typeof tr.result === 'string' ? tr.result : JSON.stringify(tr.result || '');
145
+ console.log(`[DEBUG] tool: ${tr.toolName} | args: ${debugTruncate(argsStr)} | result: ${debugTruncate(resultStr)}`);
146
+ }
147
+ }
148
+
128
149
  /**
129
150
  * ProbeAgent class to handle AI interactions with code search capabilities
130
151
  */
@@ -193,6 +214,7 @@ export class ProbeAgent {
193
214
  this.enableExecutePlan = !!options.enableExecutePlan;
194
215
  this.debug = options.debug || process.env.DEBUG === '1';
195
216
  this.cancelled = false;
217
+ this._abortController = new AbortController();
196
218
  this.tracer = options.tracer || null;
197
219
  this.outline = !!options.outline;
198
220
  this.searchDelegate = options.searchDelegate !== undefined ? !!options.searchDelegate : true;
@@ -792,6 +814,7 @@ export class ProbeAgent {
792
814
  searchDelegateProvider: this.searchDelegateProvider,
793
815
  searchDelegateModel: this.searchDelegateModel,
794
816
  delegationManager: this.delegationManager, // Per-instance delegation limits
817
+ parentAbortSignal: this._abortController.signal, // Propagate cancellation to delegations
795
818
  outputBuffer: this._outputBuffer,
796
819
  concurrencyLimiter: this.concurrencyLimiter, // Global AI concurrency limiter
797
820
  isToolAllowed,
@@ -1362,6 +1385,19 @@ export class ProbeAgent {
1362
1385
  const controller = new AbortController();
1363
1386
  const timeoutState = { timeoutId: null };
1364
1387
 
1388
+ // Link agent-level abort to this operation's controller
1389
+ // so that cancel() / cleanup() stops the current streamText call
1390
+ if (this._abortController.signal.aborted) {
1391
+ controller.abort();
1392
+ } else {
1393
+ const onAgentAbort = () => controller.abort();
1394
+ this._abortController.signal.addEventListener('abort', onAgentAbort, { once: true });
1395
+ // Clean up listener when this controller aborts (from any source)
1396
+ controller.signal.addEventListener('abort', () => {
1397
+ this._abortController.signal.removeEventListener('abort', onAgentAbort);
1398
+ }, { once: true });
1399
+ }
1400
+
1365
1401
  // Set up overall operation timeout (default 5 minutes)
1366
1402
  if (this.maxOperationTimeout && this.maxOperationTimeout > 0) {
1367
1403
  timeoutState.timeoutId = setTimeout(() => {
@@ -1729,7 +1765,8 @@ export class ProbeAgent {
1729
1765
  allowEdit: this.allowEdit,
1730
1766
  allowedTools: allowedToolsForDelegate,
1731
1767
  debug: this.debug,
1732
- tracer: this.tracer
1768
+ tracer: this.tracer,
1769
+ parentAbortSignal: this._abortController.signal
1733
1770
  };
1734
1771
 
1735
1772
  if (this.debug) {
@@ -3369,6 +3406,11 @@ Follow these instructions carefully:
3369
3406
  completionAttempted = true;
3370
3407
  }, toolContext);
3371
3408
 
3409
+ if (this.debug) {
3410
+ const toolNames = Object.keys(tools);
3411
+ console.log(`[DEBUG] Agent tools registered (${toolNames.length}): ${toolNames.join(', ')}`);
3412
+ }
3413
+
3372
3414
  let maxResponseTokens = this.maxResponseTokens;
3373
3415
  if (!maxResponseTokens) {
3374
3416
  maxResponseTokens = 4000;
@@ -3418,6 +3460,7 @@ Follow these instructions carefully:
3418
3460
 
3419
3461
  if (this.debug) {
3420
3462
  console.log(`[DEBUG] Step ${currentIteration}/${maxIterations} finished (reason: ${finishReason}, tools: ${toolResults?.length || 0})`);
3463
+ debugLogToolResults(toolResults);
3421
3464
  }
3422
3465
  }
3423
3466
  };
@@ -3629,6 +3672,7 @@ Double-check your response based on the criteria above. If everything looks good
3629
3672
  }
3630
3673
  if (this.debug) {
3631
3674
  console.log(`[DEBUG] Completion prompt step finished (reason: ${finishReason}, tools: ${toolResults?.length || 0})`);
3675
+ debugLogToolResults(toolResults);
3632
3676
  }
3633
3677
  }
3634
3678
  };
@@ -4545,6 +4589,11 @@ Convert your previous response content into actual JSON data that follows this s
4545
4589
  * Clean up resources (including MCP connections)
4546
4590
  */
4547
4591
  async cleanup() {
4592
+ // Abort any in-flight operations (delegations, streaming, etc.)
4593
+ if (!this._abortController.signal.aborted) {
4594
+ this._abortController.abort();
4595
+ }
4596
+
4548
4597
  // Clean up MCP bridge
4549
4598
  if (this.mcpBridge) {
4550
4599
  try {
@@ -4574,12 +4623,24 @@ Convert your previous response content into actual JSON data that follows this s
4574
4623
  }
4575
4624
 
4576
4625
  /**
4577
- * Cancel the current request
4626
+ * Cancel the current request and all in-flight delegations.
4627
+ * Aborts the internal AbortController so streamText, subagents,
4628
+ * and any code checking the signal will stop.
4578
4629
  */
4579
4630
  cancel() {
4580
4631
  this.cancelled = true;
4632
+ this._abortController.abort();
4581
4633
  if (this.debug) {
4582
4634
  console.log(`[DEBUG] Agent cancelled for session ${this.sessionId}`);
4583
4635
  }
4584
4636
  }
4637
+
4638
+ /**
4639
+ * Get the abort signal for this agent.
4640
+ * Delegations and subagents should check this signal.
4641
+ * @returns {AbortSignal}
4642
+ */
4643
+ get abortSignal() {
4644
+ return this._abortController.signal;
4645
+ }
4585
4646
  }
package/src/delegate.js CHANGED
@@ -386,12 +386,18 @@ export async function delegate({
386
386
  mcpConfig = null,
387
387
  mcpConfigPath = null,
388
388
  delegationManager = null, // Optional per-instance manager, falls back to default singleton
389
- concurrencyLimiter = null // Optional global AI concurrency limiter
389
+ concurrencyLimiter = null, // Optional global AI concurrency limiter
390
+ parentAbortSignal = null // Optional AbortSignal from parent to cancel this delegation
390
391
  }) {
391
392
  if (!task || typeof task !== 'string') {
392
393
  throw new Error('Task parameter is required and must be a string');
393
394
  }
394
395
 
396
+ // Check if parent has already been cancelled
397
+ if (parentAbortSignal?.aborted) {
398
+ throw new Error('Delegation cancelled: parent operation was aborted');
399
+ }
400
+
395
401
  // Support runtime timeout override via environment variables when timeout not explicitly passed
396
402
  // This allows operators to configure delegation timeouts without code changes
397
403
  // Priority: DELEGATION_TIMEOUT_MS (milliseconds) > DELEGATION_TIMEOUT_SECONDS > DELEGATION_TIMEOUT (seconds)
@@ -481,24 +487,47 @@ export async function delegate({
481
487
  console.error(`[DELEGATE] Subagent config: promptType=${promptType}, enableDelegate=false, maxIterations=${remainingIterations}`);
482
488
  }
483
489
 
484
- // Set up timeout with proper cleanup
485
- // TODO: Implement AbortController support in ProbeAgent.answer() for proper cancellation
486
- // Current limitation: When timeout occurs, subagent.answer() continues running in background
487
- // This is acceptable since:
488
- // 1. The promise will eventually resolve/reject and be garbage collected
489
- // 2. The delegation slot is properly released on timeout
490
- // 3. The parent receives timeout error and can handle it
491
- // Future improvement: Add signal parameter to ProbeAgent.answer(task, [], { signal })
490
+ // Set up timeout and parent abort handling.
491
+ // When timeout fires or parent aborts, we cancel the subagent so it
492
+ // stops making API calls and releases resources promptly.
492
493
  const timeoutPromise = new Promise((_, reject) => {
493
494
  timeoutId = setTimeout(() => {
495
+ subagent.cancel();
494
496
  reject(new Error(`Delegation timed out after ${timeout} seconds`));
495
497
  }, timeout * 1000);
496
498
  });
497
499
 
498
- // Execute the task with timeout
500
+ // Listen for parent abort signal
501
+ let parentAbortHandler;
502
+ const parentAbortPromise = new Promise((_, reject) => {
503
+ if (parentAbortSignal) {
504
+ if (parentAbortSignal.aborted) {
505
+ subagent.cancel();
506
+ reject(new Error('Delegation cancelled: parent operation was aborted'));
507
+ return;
508
+ }
509
+ parentAbortHandler = () => {
510
+ subagent.cancel();
511
+ reject(new Error('Delegation cancelled: parent operation was aborted'));
512
+ };
513
+ parentAbortSignal.addEventListener('abort', parentAbortHandler, { once: true });
514
+ }
515
+ });
516
+
517
+ // Execute the task with timeout and parent abort
499
518
  const answerOptions = schema ? { schema } : undefined;
500
519
  const answerPromise = answerOptions ? subagent.answer(task, [], answerOptions) : subagent.answer(task);
501
- const response = await Promise.race([answerPromise, timeoutPromise]);
520
+ const racers = [answerPromise, timeoutPromise];
521
+ if (parentAbortSignal) racers.push(parentAbortPromise);
522
+ let response;
523
+ try {
524
+ response = await Promise.race(racers);
525
+ } finally {
526
+ // Clean up parent abort listener to prevent memory leaks
527
+ if (parentAbortHandler && parentAbortSignal) {
528
+ parentAbortSignal.removeEventListener('abort', parentAbortHandler);
529
+ }
530
+ }
502
531
 
503
532
  // Clear timeout immediately after race completes to prevent memory leak
504
533
  // Note: timeoutId is always set by this point (synchronous in Promise constructor)
@@ -192,7 +192,8 @@ Instructions:
192
192
  promptType: 'code-researcher',
193
193
  allowedTools: ['extract'],
194
194
  maxIterations: 5,
195
- delegationManager: options.delegationManager // Per-instance delegation limits
195
+ delegationManager: options.delegationManager, // Per-instance delegation limits
196
+ parentAbortSignal: options.parentAbortSignal || null
196
197
  // timeout removed - inherit default from delegate (300s)
197
198
  });
198
199
 
@@ -328,7 +329,8 @@ Organize all findings into clear categories with items listed under each.${compl
328
329
  promptType: 'code-researcher',
329
330
  allowedTools: [],
330
331
  maxIterations: 5,
331
- delegationManager: options.delegationManager // Per-instance delegation limits
332
+ delegationManager: options.delegationManager, // Per-instance delegation limits
333
+ parentAbortSignal: options.parentAbortSignal || null
332
334
  // timeout removed - inherit default from delegate (300s)
333
335
  });
334
336
 
@@ -404,7 +406,8 @@ CRITICAL: Do NOT guess keywords. Actually run searches and see what returns resu
404
406
  promptType: 'code-researcher',
405
407
  // Full tool access for exploration and experimentation
406
408
  maxIterations: 15,
407
- delegationManager: options.delegationManager // Per-instance delegation limits
409
+ delegationManager: options.delegationManager, // Per-instance delegation limits
410
+ parentAbortSignal: options.parentAbortSignal || null
408
411
  // timeout removed - inherit default from delegate (300s)
409
412
  });
410
413
 
@@ -475,7 +478,8 @@ When done, use the attempt_completion tool with your answer as the result.`;
475
478
  promptType: 'code-researcher',
476
479
  allowedTools: [],
477
480
  maxIterations: 5,
478
- delegationManager: options.delegationManager // Per-instance delegation limits
481
+ delegationManager: options.delegationManager, // Per-instance delegation limits
482
+ parentAbortSignal: options.parentAbortSignal || null
479
483
  // timeout removed - inherit default from delegate (300s)
480
484
  });
481
485
 
@@ -277,7 +277,8 @@ export const searchTool = (options = {}) => {
277
277
  promptType: 'code-searcher',
278
278
  allowedTools: ['search', 'extract', 'listFiles', 'attempt_completion'],
279
279
  searchDelegate: false,
280
- schema: CODE_SEARCH_SCHEMA
280
+ schema: CODE_SEARCH_SCHEMA,
281
+ parentAbortSignal: options.parentAbortSignal || null
281
282
  });
282
283
 
283
284
  const delegateResult = options.tracer?.withSpan
@@ -581,7 +582,7 @@ export const delegateTool = (options = {}) => {
581
582
  name: 'delegate',
582
583
  description: delegateDescription,
583
584
  inputSchema: delegateSchema,
584
- execute: async ({ task, currentIteration, maxIterations, parentSessionId, path, provider, model, tracer, searchDelegate }) => {
585
+ execute: async ({ task, currentIteration, maxIterations, parentSessionId, path, provider, model, tracer, searchDelegate, parentAbortSignal }) => {
585
586
  // Validate required parameters - throw errors for consistency
586
587
  if (!task || typeof task !== 'string') {
587
588
  throw new Error('Task parameter is required and must be a non-empty string');
@@ -673,7 +674,8 @@ export const delegateTool = (options = {}) => {
673
674
  enableMcp,
674
675
  mcpConfig,
675
676
  mcpConfigPath,
676
- delegationManager // Per-instance delegation limits
677
+ delegationManager, // Per-instance delegation limits
678
+ parentAbortSignal
677
679
  });
678
680
 
679
681
  return result;
@@ -733,7 +735,8 @@ export const analyzeAllTool = (options = {}) => {
733
735
  provider: options.provider,
734
736
  model: options.model,
735
737
  tracer: options.tracer,
736
- delegationManager // Per-instance delegation limits
738
+ delegationManager, // Per-instance delegation limits
739
+ parentAbortSignal: options.parentAbortSignal || null
737
740
  });
738
741
 
739
742
  return result;