agent-swarm-kit 3.1.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.
package/build/index.cjs CHANGED
@@ -293,33 +293,32 @@ const validateDefault = async (output) => {
293
293
  };
294
294
 
295
295
  /**
296
- * Removes XML tags and their contents from a string, cleaning up excess whitespace.
297
- * Strips all matched XML-like tags (e.g., `<tag>content</tag>`) and normalizes newlines, returning a trimmed result.
298
- *
299
- * Returns an empty string if the input is falsy.
296
+ * Removes XML-like blocks — the tags TOGETHER with everything between them — from a string, cleaning up excess whitespace.
297
+ * Any `<tag>content</tag>` pair is stripped entirely (tag and content), so only text outside such blocks survives.
298
+ * Returns an empty string if the input is falsy.
300
299
  *
301
300
  * @example
302
- * // Basic usage with XML tags
303
- * console.log(removeXmlTags("<p>Hello</p>")); // "Hello"
304
- * console.log(removeXmlTags("<div><span>Text</span></div>")); // "Text"
301
+ * // Whole blocks are removed, including their contents
302
+ * console.log(removeXmlTags("<p>Hello</p>")); // ""
303
+ * console.log(removeXmlTags("Text <tool>action</tool>")); // "Text"
305
304
  * console.log(removeXmlTags("No tags here")); // "No tags here"
306
305
  *
307
306
  * @example
308
- * // Handling multiline input and edge cases
309
- * console.log(removeXmlTags("<tag>\nLine1\nLine2\n</tag>")); // "Line1\nLine2"
310
- * console.log(removeXmlTags("<tag> <nested>Text</nested> </tag>")); // "Text"
307
+ * // Edge cases
308
+ * console.log(removeXmlTags("<think>\nreasoning\n</think>Answer")); // "Answer"
309
+ * console.log(removeXmlTags("<invalid>")); // "<invalid>" (unpaired tags are kept)
311
310
  * console.log(removeXmlTags("")); // ""
312
311
  * console.log(removeXmlTags(null)); // ""
313
312
  *
314
313
  * @remarks
315
314
  * This function:
316
315
  * - Returns an empty string (`""`) for falsy inputs (e.g., `null`, `undefined`, empty string) to ensure safe handling.
317
- * - Uses a regular expression (`/<[^>]+>[\s\S]*?<\/[^>]+>/g`) to match and remove XML tags and their contents, including nested tags,
318
- * where `[\s\S]*?` ensures non-greedy matching across newlines.
316
+ * - Uses a regular expression (`/<[^>]+>[\s\S]*?<\/[^>]+>/g`) to match an opening tag, its (non-greedy) contents across
317
+ * newlines, and a closing tag, removing the whole block; unpaired tags without a closing counterpart are left as-is.
319
318
  * - Collapses multiple consecutive newlines (`\n\s*\n`) into a single newline (`\n`) to clean up formatting.
320
319
  * - Trims leading and trailing whitespace from the final result for a polished output.
321
- * Useful in the agent swarm system for sanitizing model outputs, user inputs, or logs that may contain XML markup,
322
- * such as when processing tool call responses or cleaning structured text.
320
+ * Useful in the agent swarm system for stripping structured blocks from model outputs e.g., `<think>…</think>`
321
+ * reasoning sections or inline `<tool_call>…</tool_call>` artifacts leaving only the plain-text answer.
323
322
  *
324
323
  * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions|Regular Expressions}
325
324
  * for details on the regex patterns used.
@@ -337,6 +336,12 @@ const removeXmlTags = (input) => {
337
336
  };
338
337
 
339
338
  const IS_WINDOWS = os.platform() === "win32";
339
+ /**
340
+ * Default prefix for temporary files created during atomic writes.
341
+ * Exposed so directory scanners (e.g. PersistBase) can exclude in-flight
342
+ * or leftover temporary files from entity listings.
343
+ */
344
+ const TMP_FILE_PREFIX = ".tmp-";
340
345
  /**
341
346
  * Atomically writes data to a file, ensuring the operation either fully completes or leaves the original file unchanged.
342
347
  * Uses a temporary file with a rename strategy on POSIX systems for atomicity, or direct writing with sync on Windows (or when POSIX rename is skipped).
@@ -387,7 +392,7 @@ async function writeFileAtomic(file, data, options = {}) {
387
392
  else if (!options) {
388
393
  options = {};
389
394
  }
390
- const { encoding = "utf8", mode = 0o666, tmpPrefix = ".tmp-" } = options;
395
+ const { encoding = "utf8", mode = 0o666, tmpPrefix = TMP_FILE_PREFIX } = options;
391
396
  let fileHandle = null;
392
397
  if (IS_WINDOWS || GLOBAL_CONFIG.CC_SKIP_POSIX_RENAME) {
393
398
  try {
@@ -443,6 +448,13 @@ async function writeFileAtomic(file, data, options = {}) {
443
448
  }
444
449
 
445
450
  var _a$4, _b$1, _c, _d;
451
+ /**
452
+ * Checks whether a directory entry name represents a persisted entity file.
453
+ * Excludes temporary files produced by atomic writes so in-flight or leftover
454
+ * `.tmp-*` files are never listed, counted, read, or removed as entities.
455
+ * @private
456
+ */
457
+ const isEntityFileName = (name) => name.endsWith(".json") && !name.startsWith(TMP_FILE_PREFIX);
446
458
  /** @private Symbol for memoizing the wait-for-initialization operation in PersistBase*/
447
459
  const BASE_WAIT_FOR_INIT_SYMBOL = Symbol("wait-for-init");
448
460
  /** @private Symbol for creating a new key in a persistent list*/
@@ -545,6 +557,8 @@ const LIST_GET_LAST_KEY_FN_METHOD_NAME = "PersistList.getLastKeyFn";
545
557
  const BASE_UNLINK_RETRY_COUNT = 5;
546
558
  /** @private Delay for retry attempts for unlink in waitForInit (in milliseconds)*/
547
559
  const BASE_UNLINK_RETRY_DELAY = 1000;
560
+ /** @private Minimum age for a temporary atomic-write file to be reaped as a leftover in waitForInit (in milliseconds)*/
561
+ const BASE_STALE_TMP_FILE_AGE = 120000;
548
562
  /**
549
563
  * Attempts to remove a file if invalid JSON is detected during initialization.
550
564
  * Retries the operation multiple times with delays to handle transient errors, ensuring robust setup.
@@ -575,6 +589,21 @@ const BASE_WAIT_FOR_INIT_FN = async (self) => {
575
589
  directory: self._directory,
576
590
  });
577
591
  await fs.mkdir(self._directory, { recursive: true });
592
+ for await (const entry of await fs.opendir(self._directory)) {
593
+ if (entry.isFile() && entry.name.startsWith(TMP_FILE_PREFIX)) {
594
+ const filePath = path.join(self._directory, entry.name);
595
+ // An in-flight atomic write from a concurrent process also produces a
596
+ // temporary file here; only reap ones old enough to be true leftovers.
597
+ const stat = await fs.stat(filePath).catch(() => null);
598
+ if (!stat || Date.now() - stat.mtimeMs < BASE_STALE_TMP_FILE_AGE) {
599
+ continue;
600
+ }
601
+ console.error(`agent-swarm PersistBase found leftover temporary file for filePath=${filePath} entityName=${self.entityName}`);
602
+ if (await functoolsKit.not(BASE_WAIT_FOR_INIT_UNLINK_FN(filePath))) {
603
+ console.error(`agent-swarm PersistBase failed to remove leftover temporary file for filePath=${filePath} entityName=${self.entityName}`);
604
+ }
605
+ }
606
+ }
578
607
  for await (const key of self.keys()) {
579
608
  try {
580
609
  await self.readValue(key);
@@ -698,7 +727,11 @@ class PersistBase {
698
727
  * @private
699
728
  */
700
729
  _getFilePath(entityId) {
701
- return path.join(this.baseDir, this.entityName, `${entityId}.json`);
730
+ // entityId comes from clientId/stateName/etc. which may be attacker-supplied:
731
+ // strip path separators and traversal so a value like "../../x" cannot escape
732
+ // the entity directory and read/overwrite arbitrary files.
733
+ const safeId = String(entityId).replace(/[/\\]/g, "_").replace(/\.\./g, "_");
734
+ return path.join(this.baseDir, this.entityName, `${safeId}.json`);
702
735
  }
703
736
  /**
704
737
  * Initializes the storage directory, creating it if it doesn’t exist, and validates existing entities.
@@ -721,7 +754,7 @@ class PersistBase {
721
754
  async getCount() {
722
755
  let count = 0;
723
756
  for await (const entry of await fs.opendir(this._directory)) {
724
- if (entry.isFile() && entry.name.endsWith(".json")) {
757
+ if (entry.isFile() && isEntityFileName(entry.name)) {
725
758
  count++;
726
759
  }
727
760
  }
@@ -830,7 +863,7 @@ class PersistBase {
830
863
  try {
831
864
  const filesToRemove = [];
832
865
  for await (const entry of await fs.opendir(this._directory)) {
833
- if (entry.isFile() && entry.name.endsWith(".json")) {
866
+ if (entry.isFile() && isEntityFileName(entry.name)) {
834
867
  filesToRemove.push(entry.name);
835
868
  }
836
869
  }
@@ -856,7 +889,7 @@ class PersistBase {
856
889
  try {
857
890
  const entityIds = [];
858
891
  for await (const entry of await fs.opendir(this._directory)) {
859
- if (entry.isFile() && entry.name.endsWith(".json")) {
892
+ if (entry.isFile() && isEntityFileName(entry.name)) {
860
893
  entityIds.push(entry.name.slice(0, -5));
861
894
  }
862
895
  }
@@ -886,7 +919,7 @@ class PersistBase {
886
919
  try {
887
920
  const entityIds = [];
888
921
  for await (const entry of await fs.opendir(this._directory)) {
889
- if (entry.isFile() && entry.name.endsWith(".json")) {
922
+ if (entry.isFile() && isEntityFileName(entry.name)) {
890
923
  entityIds.push(entry.name.slice(0, -5));
891
924
  }
892
925
  }
@@ -1811,6 +1844,16 @@ class HistoryPersistInstance {
1811
1844
  this.callbacks.onRead(item, this.clientId, agentName);
1812
1845
  yield item;
1813
1846
  }
1847
+ if (this.callbacks.getSystemPrompt) {
1848
+ for (const content of await this.callbacks.getSystemPrompt(this.clientId, agentName)) {
1849
+ yield {
1850
+ role: "system",
1851
+ content,
1852
+ agentName,
1853
+ mode: "tool",
1854
+ };
1855
+ }
1856
+ }
1814
1857
  this.callbacks.onReadEnd &&
1815
1858
  this.callbacks.onReadEnd(this.clientId, agentName);
1816
1859
  return;
@@ -1992,6 +2035,16 @@ class HistoryMemoryInstance {
1992
2035
  this.callbacks.onRead(item, this.clientId, agentName);
1993
2036
  yield item;
1994
2037
  }
2038
+ if (this.callbacks.getSystemPrompt) {
2039
+ for (const content of await this.callbacks.getSystemPrompt(this.clientId, agentName)) {
2040
+ yield {
2041
+ role: "system",
2042
+ content,
2043
+ agentName,
2044
+ mode: "tool",
2045
+ };
2046
+ }
2047
+ }
1995
2048
  this.callbacks.onReadEnd &&
1996
2049
  this.callbacks.onReadEnd(this.clientId, agentName);
1997
2050
  return;
@@ -2751,7 +2804,7 @@ class OperatorUtils {
2751
2804
  isInitial && operator.init();
2752
2805
  return (message, next) => {
2753
2806
  operator.connectAnswer(next);
2754
- operator.recieveMessage(message);
2807
+ Promise.resolve(operator.recieveMessage(message)).catch((error) => console.error(`agent-swarm operator recieveMessage error clientId=${clientId} agentName=${agentName} error=${functoolsKit.getErrorMessage(error)}`));
2755
2808
  return async () => {
2756
2809
  this.getOperator.clear(`${clientId}-${agentName}`);
2757
2810
  await operator.dispose();
@@ -2856,6 +2909,9 @@ const CC_DEFAULT_CONNECT_OPERATOR = (clientId, agentName) => OperatorAdapter.con
2856
2909
  * Flag to enable operator timeout, used in `ClientOperator` for message processing.
2857
2910
  */
2858
2911
  const CC_ENABLE_OPERATOR_TIMEOUT = false;
2912
+ const CC_OPERATOR_SIGNAL_TIMEOUT = 90000;
2913
+ const CC_CHAT_INACTIVITY_CHECK = 60 * 1000;
2914
+ const CC_CHAT_INACTIVITY_TIMEOUT = 15 * 60 * 1000;
2859
2915
  /**
2860
2916
  * Disable fetch of data from all storages. Quite usefull for unit tests
2861
2917
  */
@@ -2915,6 +2971,9 @@ const GLOBAL_CONFIG = {
2915
2971
  CC_THROW_WHEN_NAVIGATION_RECURSION,
2916
2972
  CC_DEFAULT_CONNECT_OPERATOR,
2917
2973
  CC_ENABLE_OPERATOR_TIMEOUT,
2974
+ CC_OPERATOR_SIGNAL_TIMEOUT,
2975
+ CC_CHAT_INACTIVITY_CHECK,
2976
+ CC_CHAT_INACTIVITY_TIMEOUT,
2918
2977
  CC_STORAGE_DISABLE_GET_DATA,
2919
2978
  CC_MAX_NESTED_EXECUTIONS,
2920
2979
  };
@@ -3343,6 +3402,9 @@ const resolveTools = async (clientId, agentName, tools) => {
3343
3402
  })));
3344
3403
  };
3345
3404
 
3405
+ const disposeSubject = new functoolsKit.Subject();
3406
+ const errorSubject = new functoolsKit.Subject();
3407
+
3346
3408
  const CANCEL_OUTPUT_SYMBOL = Symbol("cancel-output");
3347
3409
  const AGENT_CHANGE_SYMBOL = Symbol("agent-change");
3348
3410
  const MODEL_RESQUE_SYMBOL = Symbol("model-resque");
@@ -3411,7 +3473,8 @@ const createPlaceholder = () => GLOBAL_CONFIG.CC_EMPTY_OUTPUT_PLACEHOLDERS[Math.
3411
3473
  * Emits events via subjects (e.g., _toolErrorSubject) to manage execution flow in ClientAgent.
3412
3474
  * Supports AgentConnectionService by executing tools defined in ToolSchemaService and referenced in AgentSchemaService.
3413
3475
  */
3414
- const createToolCall = async (idx, tool, toolCalls, targetFn, reason, self) => {
3476
+ const createToolCall = async (idx, tool, toolCalls, targetFn, reason, mode, outputEpoch, self) => {
3477
+ self._runningToolCalls += 1;
3415
3478
  try {
3416
3479
  await targetFn.call({
3417
3480
  toolId: tool.id,
@@ -3424,8 +3487,15 @@ const createToolCall = async (idx, tool, toolCalls, targetFn, reason, self) => {
3424
3487
  callReason: reason,
3425
3488
  toolCalls,
3426
3489
  });
3427
- targetFn.callbacks?.onAfterCall &&
3428
- targetFn.callbacks?.onAfterCall(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments);
3490
+ try {
3491
+ targetFn.callbacks?.onAfterCall &&
3492
+ targetFn.callbacks?.onAfterCall(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments);
3493
+ }
3494
+ catch (error) {
3495
+ // Callbacks are observers: a throwing onAfterCall must not turn a
3496
+ // successful tool call into a tool error.
3497
+ console.error(`agent-swarm onAfterCall callback error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`);
3498
+ }
3429
3499
  }
3430
3500
  catch (error) {
3431
3501
  console.error(`agent-swarm tool call error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`, {
@@ -3435,11 +3505,29 @@ const createToolCall = async (idx, tool, toolCalls, targetFn, reason, self) => {
3435
3505
  arguments: tool.function.arguments,
3436
3506
  error: functoolsKit.errorData(error),
3437
3507
  });
3438
- targetFn.callbacks?.onCallError &&
3439
- targetFn.callbacks?.onCallError(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments, error);
3440
- self.params.callbacks?.onToolError &&
3441
- self.params.callbacks.onToolError(self.params.clientId, self.params.agentName, targetFn.toolName, error);
3442
- self._toolErrorSubject.next(TOOL_ERROR_SYMBOL);
3508
+ try {
3509
+ targetFn.callbacks?.onCallError &&
3510
+ targetFn.callbacks?.onCallError(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments, error);
3511
+ self.params.onToolError &&
3512
+ self.params.onToolError(self.params.clientId, self.params.agentName, targetFn.toolName, error);
3513
+ }
3514
+ catch (callbackError) {
3515
+ // Error callbacks must not be able to suppress the TOOL_ERROR signal
3516
+ // below — otherwise the execution would never recover and hang.
3517
+ console.error(`agent-swarm onCallError callback error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(callbackError)}`);
3518
+ }
3519
+ await self._toolErrorSubject.next(TOOL_ERROR_SYMBOL);
3520
+ if (!self._activeToolChains) {
3521
+ // The status chain already consumed TOOL_COMMIT and finished, so nobody
3522
+ // handles this late error (e.g. changeToAgent recursion guard thrown after
3523
+ // commitToolOutput). Without a recovery emission the pending waitForOutput
3524
+ // of the enclosing execution would hang forever.
3525
+ const result = await self._resurrectModel(mode, `Late tool error after commit: name=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`);
3526
+ await self._emitOutput(mode, result, outputEpoch);
3527
+ }
3528
+ }
3529
+ finally {
3530
+ self._runningToolCalls -= 1;
3443
3531
  }
3444
3532
  };
3445
3533
  /**
@@ -3469,7 +3557,7 @@ const mapMcpToolCall = ({ name, description = name, inputSchema }, self) => {
3469
3557
  enum: e,
3470
3558
  },
3471
3559
  }), {}),
3472
- required: inputSchema.required,
3560
+ required: inputSchema?.required,
3473
3561
  },
3474
3562
  },
3475
3563
  call: async (dto) => {
@@ -3558,6 +3646,7 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3558
3646
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} maxToolCalls=${self.params.maxToolCalls} execute begin`, { incoming, mode });
3559
3647
  self.params.onExecute &&
3560
3648
  self.params.onExecute(self.params.clientId, self.params.agentName, incoming, mode);
3649
+ const outputEpoch = self._outputEpoch;
3561
3650
  await self.params.history.push({
3562
3651
  role: "user",
3563
3652
  mode,
@@ -3575,7 +3664,39 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3575
3664
  id: call.id ?? functoolsKit.randomString(),
3576
3665
  type: call.type ?? "function",
3577
3666
  })), self.params.clientId, self.params.agentName);
3578
- toolCalls = toolCalls.slice(-self.params.maxToolCalls);
3667
+ {
3668
+ const toolCallIds = new Set(toolCalls.map(({ id }) => id));
3669
+ if (toolCallIds.size !== toolCalls.length) {
3670
+ // Duplicate ids break the call-to-output linkage in history and mean
3671
+ // the model output is malformed: surface it as an exception to the
3672
+ // caller (via errorSubject) and recover the flow with a placeholder.
3673
+ const error = new Error(`agent-swarm duplicate tool call id detected agentName=${self.params.agentName} clientId=${self.params.clientId} ids=${JSON.stringify(toolCalls.map(({ id }) => id))}`);
3674
+ console.error(error.message);
3675
+ await errorSubject.next([self.params.clientId, error]);
3676
+ const result = await self._resurrectModel(mode, `Duplicate tool call id in model output`);
3677
+ await self._emitOutput(mode, result, outputEpoch);
3678
+ return;
3679
+ }
3680
+ }
3681
+ // slice(-0) === slice(0) returns the WHOLE array, so maxToolCalls=0 would
3682
+ // run every call instead of none — clamp explicitly.
3683
+ toolCalls =
3684
+ self.params.maxToolCalls > 0
3685
+ ? toolCalls.slice(-self.params.maxToolCalls)
3686
+ : [];
3687
+ if (!toolCalls.length) {
3688
+ // maxToolCalls=0 dropped every call: the model wanted tools but none may
3689
+ // run. Emit the (tool-stripped) content as the answer instead of leaving
3690
+ // the pending waitForOutput hanging forever.
3691
+ const result = await self.params.transform(message.content, self.params.clientId, self.params.agentName);
3692
+ await self.params.history.push({
3693
+ ...message,
3694
+ tool_calls: [],
3695
+ agentName: self.params.agentName,
3696
+ });
3697
+ await self._emitOutput(mode, result, outputEpoch);
3698
+ return;
3699
+ }
3579
3700
  {
3580
3701
  const priorityTool = toolCalls.find((call) => swarm$1.navigationSchemaService.hasTool(call.function.name) ||
3581
3702
  swarm$1.actionSchemaService.hasTool(call.function.name));
@@ -3583,11 +3704,15 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3583
3704
  toolCalls = [priorityTool];
3584
3705
  }
3585
3706
  }
3707
+ // Persist the normalized tool calls (ids ensured, sliced, priority-filtered)
3708
+ // so history keeps the call-to-output linkage even when the model omits ids.
3586
3709
  await self.params.history.push({
3587
3710
  ...message,
3711
+ tool_calls: toolCalls,
3588
3712
  agentName: self.params.agentName,
3589
3713
  });
3590
3714
  let lastToolStatusRef = Promise.resolve(null);
3715
+ self._activeToolChains += 1;
3591
3716
  const [runAwaiter, { resolve: run }] = functoolsKit.createAwaiter();
3592
3717
  for (let idx = 0; idx !== toolCalls.length; idx++) {
3593
3718
  const tool = toolCalls[idx];
@@ -3598,29 +3723,52 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3598
3723
  const result = await self._resurrectModel(mode, `No target function for ${tool.function.name}`);
3599
3724
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3600
3725
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} execute end result=${result}`);
3601
- await self._emitOutput(mode, result);
3726
+ await self._emitOutput(mode, result, outputEpoch);
3602
3727
  run(false);
3603
3728
  return;
3604
3729
  }
3605
- targetFn.callbacks?.onValidate &&
3606
- targetFn.callbacks?.onValidate(self.params.clientId, self.params.agentName, tool.function.arguments);
3607
- if (await functoolsKit.not(targetFn.validate({
3608
- clientId: self.params.clientId,
3609
- agentName: self.params.agentName,
3610
- params: tool.function.arguments,
3611
- toolCalls,
3612
- }))) {
3730
+ try {
3731
+ targetFn.callbacks?.onValidate &&
3732
+ targetFn.callbacks?.onValidate(self.params.clientId, self.params.agentName, tool.function.arguments);
3733
+ }
3734
+ catch (error) {
3735
+ // Callbacks are observers: a throwing onValidate must not reject the
3736
+ // queued EXECUTE_FN (unhandled rejection + hung waitForOutput).
3737
+ console.error(`agent-swarm onValidate callback error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`);
3738
+ }
3739
+ let validationPassed = false;
3740
+ try {
3741
+ validationPassed = !(await functoolsKit.not(targetFn.validate({
3742
+ clientId: self.params.clientId,
3743
+ agentName: self.params.agentName,
3744
+ params: tool.function.arguments,
3745
+ toolCalls,
3746
+ })));
3747
+ }
3748
+ catch (error) {
3749
+ // A throwing validate is a failed validation, not a crashed execution.
3750
+ console.error(`agent-swarm tool validate error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`);
3751
+ validationPassed = false;
3752
+ }
3753
+ if (!validationPassed) {
3613
3754
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3614
3755
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} tool validation not passed`);
3615
3756
  const result = await self._resurrectModel(mode, `Function validation failed: name=${tool.function.name} arguments=${JSON.stringify(tool.function.arguments)}`);
3616
3757
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3617
3758
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} execute end result=${result}`);
3618
- await self._emitOutput(mode, result);
3759
+ await self._emitOutput(mode, result, outputEpoch);
3619
3760
  run(false);
3620
3761
  return;
3621
3762
  }
3622
- targetFn.callbacks?.onBeforeCall &&
3623
- targetFn.callbacks?.onBeforeCall(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments);
3763
+ try {
3764
+ targetFn.callbacks?.onBeforeCall &&
3765
+ targetFn.callbacks?.onBeforeCall(tool.id, self.params.clientId, self.params.agentName, tool.function.arguments);
3766
+ }
3767
+ catch (error) {
3768
+ // Callbacks are observers: a throwing onBeforeCall must not reject the
3769
+ // queued EXECUTE_FN (unhandled rejection + hung waitForOutput).
3770
+ console.error(`agent-swarm onBeforeCall callback error functionName=${tool.function.name} error=${functoolsKit.getErrorMessage(error)}`);
3771
+ }
3624
3772
  /**
3625
3773
  * Do not await directly to avoid deadlock! The tool can send messages to other agents by emulating user messages.
3626
3774
  */
@@ -3658,33 +3806,33 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3658
3806
  console.warn(`agent-swarm no tool output after ${TOOL_NO_OUTPUT_WARNING_TIMEOUT}ms clientId=${self.params.clientId} agentName=${self.params.agentName} toolId=${tool.id} functionName=${tool.function.name}`);
3659
3807
  }
3660
3808
  });
3661
- createToolCall(idx, tool, toolCalls, targetFn, message.content || "", self);
3809
+ createToolCall(idx, tool, toolCalls, targetFn, message.content || "", mode, outputEpoch, self);
3662
3810
  const status = await statusAwaiter;
3663
3811
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3664
3812
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} tool call end`);
3665
3813
  if (status === MODEL_RESQUE_SYMBOL) {
3666
3814
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3667
3815
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} the next tool execution stopped due to the model resque`);
3668
- self.params.callbacks?.onAfterToolCalls &&
3669
- self.params.callbacks.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3816
+ self.params.onAfterToolCalls &&
3817
+ self.params.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3670
3818
  }
3671
3819
  if (status === AGENT_CHANGE_SYMBOL) {
3672
3820
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3673
3821
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} the next tool execution stopped due to the agent changed`);
3674
- self.params.callbacks?.onAfterToolCalls &&
3675
- self.params.callbacks.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3822
+ self.params.onAfterToolCalls &&
3823
+ self.params.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3676
3824
  }
3677
3825
  if (status === TOOL_STOP_SYMBOL) {
3678
3826
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3679
3827
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} the next tool execution stopped due to the commitStopTools call`);
3680
- self.params.callbacks?.onAfterToolCalls &&
3681
- self.params.callbacks.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3828
+ self.params.onAfterToolCalls &&
3829
+ self.params.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3682
3830
  }
3683
3831
  if (status === CANCEL_OUTPUT_SYMBOL) {
3684
3832
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3685
3833
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} functionName=${tool.function.name} the next tool execution stopped due to the commitCancelOutput call`);
3686
- self.params.callbacks?.onAfterToolCalls &&
3687
- self.params.callbacks.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3834
+ self.params.onAfterToolCalls &&
3835
+ self.params.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3688
3836
  }
3689
3837
  if (status === TOOL_ERROR_SYMBOL) {
3690
3838
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
@@ -3692,14 +3840,15 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3692
3840
  const result = await self._resurrectModel(mode, `Function call failed with error: name=${tool.function.name} arguments=${JSON.stringify(tool.function.arguments)}`);
3693
3841
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3694
3842
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} execute end result=${result}`);
3695
- await self._emitOutput(mode, result);
3843
+ await self._emitOutput(mode, result, outputEpoch);
3696
3844
  }
3697
3845
  return status;
3698
3846
  });
3699
3847
  }
3700
3848
  lastToolStatusRef.finally(() => {
3701
- self.params.callbacks?.onAfterToolCalls &&
3702
- self.params.callbacks.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3849
+ self._activeToolChains -= 1;
3850
+ self.params.onAfterToolCalls &&
3851
+ self.params.onAfterToolCalls(self.params.clientId, self.params.agentName, toolCalls);
3703
3852
  });
3704
3853
  run(true);
3705
3854
  return;
@@ -3718,12 +3867,12 @@ const EXECUTE_FN = async (incoming, mode, self) => {
3718
3867
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3719
3868
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} execute invalid tool call detected: ${validation}`, { result });
3720
3869
  const result1 = await self._resurrectModel(mode, `Invalid model output: ${result}`);
3721
- await self._emitOutput(mode, result1);
3870
+ await self._emitOutput(mode, result1, outputEpoch);
3722
3871
  return;
3723
3872
  }
3724
3873
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3725
3874
  self.params.logger.debug(`ClientAgent agentName=${self.params.agentName} clientId=${self.params.clientId} execute end result=${result}`);
3726
- await self._emitOutput(mode, result);
3875
+ await self._emitOutput(mode, result, outputEpoch);
3727
3876
  };
3728
3877
  /**
3729
3878
  * Represents a client-side agent in the swarm system, implementing the IAgent interface.
@@ -3746,6 +3895,35 @@ class ClientAgent {
3746
3895
  * @readonly
3747
3896
  */
3748
3897
  this._toolAbortController = new ToolAbortController();
3898
+ /**
3899
+ * Count of tool calls currently executing for this agent.
3900
+ * Non-zero while any targetFn.call promise is pending; ClientSession uses it to
3901
+ * detect nested tool-mode executions that must join the parent output waiter.
3902
+ */
3903
+ this._runningToolCalls = 0;
3904
+ /**
3905
+ * Count of EXECUTE_FN tool status chains still consuming tool events.
3906
+ * While non-zero, tool errors are handled by the chain (stop + resurrect);
3907
+ * once it drops to zero a late tool error must recover on its own in
3908
+ * createToolCall, or the pending execution output would never be emitted.
3909
+ */
3910
+ this._activeToolChains = 0;
3911
+ /**
3912
+ * Count of EXECUTE_FN executions currently in flight for this agent instance.
3913
+ * dispose() checks it: tearing the instance down mid-execution (e.g. a
3914
+ * server-side changeToAgent while the completion is still running) must
3915
+ * resolve the pending output waiter with an empty result — otherwise the
3916
+ * waiter and the session busy lock would hang forever.
3917
+ */
3918
+ this._activeExecutions = 0;
3919
+ /**
3920
+ * Generation counter for output emissions. Bumped by commitCancelOutput and by
3921
+ * swarm-level output substitution (emit). Executions capture the epoch at start
3922
+ * and _emitOutput drops their result when the epoch moved on — otherwise the
3923
+ * stale output of a cancelled/substituted execution would resolve the waiter
3924
+ * of the NEXT message, poisoning that exchange.
3925
+ */
3926
+ this._outputEpoch = 0;
3749
3927
  /**
3750
3928
  * Subject for signaling agent changes, halting subsequent tool executions via commitAgentChange.
3751
3929
  * @readonly
@@ -3785,7 +3963,15 @@ class ClientAgent {
3785
3963
  * Executes the incoming message and processes tool calls if present, queued to prevent overlapping executions.
3786
3964
  * Implements IAgent.execute, delegating to EXECUTE_FN with queuing via functools-kit’s queued decorator.
3787
3965
  */
3788
- this.execute = functoolsKit.queued(async (incoming, mode) => await EXECUTE_FN(incoming, mode, this));
3966
+ this.execute = functoolsKit.queued(async (incoming, mode) => {
3967
+ this._activeExecutions += 1;
3968
+ try {
3969
+ return await EXECUTE_FN(incoming, mode, this);
3970
+ }
3971
+ finally {
3972
+ this._activeExecutions -= 1;
3973
+ }
3974
+ });
3789
3975
  /**
3790
3976
  * Runs a stateless completion for the incoming message, queued to prevent overlapping executions.
3791
3977
  * Implements IAgent.run, delegating to RUN_FN with queuing via functools-kit’s queued decorator.
@@ -3809,12 +3995,32 @@ class ClientAgent {
3809
3995
  if (this.params.tools) {
3810
3996
  await Promise.all(this.params.tools.map(async (tool) => {
3811
3997
  const { toolName, function: upperFn, isAvailable = TOOL_AVAILABLE_DEFAULT, ...other } = tool;
3812
- if (await functoolsKit.not(isAvailable(this.params.clientId, this.params.agentName, toolName))) {
3998
+ try {
3999
+ if (await functoolsKit.not(isAvailable(this.params.clientId, this.params.agentName, toolName))) {
4000
+ return;
4001
+ }
4002
+ }
4003
+ catch (error) {
4004
+ // A throwing isAvailable would reject the queued EXECUTE_FN and
4005
+ // hang the pending waitForOutput: treat it as "not available".
4006
+ console.error(`agent-swarm isAvailable error toolName=${toolName} error=${functoolsKit.getErrorMessage(error)}`);
4007
+ await errorSubject.next([this.params.clientId, error]);
4008
+ return;
4009
+ }
4010
+ let fn;
4011
+ try {
4012
+ fn =
4013
+ typeof upperFn === "function"
4014
+ ? await upperFn(this.params.clientId, this.params.agentName)
4015
+ : upperFn;
4016
+ }
4017
+ catch (error) {
4018
+ // Same rationale: a throwing dynamic tool schema must not crash
4019
+ // the execution — the tool is skipped for this completion.
4020
+ console.error(`agent-swarm dynamic tool function error toolName=${toolName} error=${functoolsKit.getErrorMessage(error)}`);
4021
+ await errorSubject.next([this.params.clientId, error]);
3813
4022
  return;
3814
4023
  }
3815
- const fn = typeof upperFn === "function"
3816
- ? await upperFn(this.params.clientId, this.params.agentName)
3817
- : upperFn;
3818
4024
  agentToolList.push({
3819
4025
  ...other,
3820
4026
  toolName,
@@ -3822,10 +4028,19 @@ class ClientAgent {
3822
4028
  });
3823
4029
  }));
3824
4030
  }
3825
- const mcpToolList = await this.params.mcp.listTools(this.params.clientId);
4031
+ let mcpToolList = [];
4032
+ try {
4033
+ mcpToolList = await this.params.mcp.listTools(this.params.clientId);
4034
+ }
4035
+ catch (error) {
4036
+ // A throwing MCP listTools would reject the queued EXECUTE_FN and hang
4037
+ // the pending waitForOutput: continue without MCP tools and surface the
4038
+ // error to the caller through errorSubject.
4039
+ console.error(`agent-swarm mcp listTools error agentName=${this.params.agentName} clientId=${this.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
4040
+ await errorSubject.next([this.params.clientId, error]);
4041
+ }
3826
4042
  if (mcpToolList.length) {
3827
4043
  let commitActionFound = false;
3828
- let navigationFound = false;
3829
4044
  return agentToolList
3830
4045
  .concat(mcpToolList.map((tool) => mapMcpToolCall(tool, this)))
3831
4046
  .filter(({ function: { name } }) => {
@@ -3841,13 +4056,11 @@ class ClientAgent {
3841
4056
  return aStarts === bStarts ? 0 : aStarts ? -1 : 1;
3842
4057
  })
3843
4058
  .filter((tool) => {
3844
- const isNavigation = swarm$1.navigationSchemaService.hasTool(tool.toolName);
3845
- if (isNavigation) {
3846
- if (navigationFound) {
3847
- return false;
3848
- }
3849
- navigationFound = true;
3850
- }
4059
+ // Do NOT collapse navigation tools to a single one: a router agent
4060
+ // legitimately exposes several (nav-to-sales/tech/human) and the model
4061
+ // must be able to call any of them. Only commit-action tools are
4062
+ // limited to one, since running multiple actions in one turn is
4063
+ // ambiguous.
3851
4064
  const isCommitAction = swarm$1.actionSchemaService.hasTool(tool.toolName);
3852
4065
  if (isCommitAction) {
3853
4066
  if (commitActionFound) {
@@ -3859,7 +4072,6 @@ class ClientAgent {
3859
4072
  });
3860
4073
  }
3861
4074
  let commitActionFound = false;
3862
- let navigationFound = false;
3863
4075
  return agentToolList
3864
4076
  .filter(({ function: { name } }) => {
3865
4077
  if (!seen.has(name)) {
@@ -3874,13 +4086,8 @@ class ClientAgent {
3874
4086
  return aStarts === bStarts ? 0 : aStarts ? -1 : 1;
3875
4087
  })
3876
4088
  .filter((tool) => {
3877
- const isNavigation = swarm$1.navigationSchemaService.hasTool(tool.toolName);
3878
- if (isNavigation) {
3879
- if (navigationFound) {
3880
- return false;
3881
- }
3882
- navigationFound = true;
3883
- }
4089
+ // See the MCP branch above: navigation tools are not deduplicated —
4090
+ // only commit-action tools are limited to one per turn.
3884
4091
  const isCommitAction = swarm$1.actionSchemaService.hasTool(tool.toolName);
3885
4092
  if (isCommitAction) {
3886
4093
  if (commitActionFound) {
@@ -3922,7 +4129,12 @@ class ClientAgent {
3922
4129
  * Supports SwarmConnectionService by broadcasting agent outputs within the swarm.
3923
4130
  * @throws {Error} If validation fails after model resurrection, indicating an unrecoverable state.
3924
4131
  **/
3925
- async _emitOutput(mode, rawResult) {
4132
+ async _emitOutput(mode, rawResult, outputEpoch = this._outputEpoch) {
4133
+ if (outputEpoch !== this._outputEpoch) {
4134
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4135
+ this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} _emitOutput skipped for stale execution (cancelled or substituted)`, { mode, rawResult });
4136
+ return;
4137
+ }
3926
4138
  const result = await this.params.transform(rawResult, this.params.clientId, this.params.agentName);
3927
4139
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
3928
4140
  this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} _emitOutput`, { mode, result, rawResult });
@@ -3933,6 +4145,9 @@ class ClientAgent {
3933
4145
  if ((validation = await this.params.validate(result))) {
3934
4146
  throw new Error(`agent-swarm-kit ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} model resurrect failed: ${validation}`);
3935
4147
  }
4148
+ if (outputEpoch !== this._outputEpoch) {
4149
+ return;
4150
+ }
3936
4151
  this.params.onOutput &&
3937
4152
  this.params.onOutput(this.params.clientId, this.params.agentName, result);
3938
4153
  this.params.onAssistantMessage &&
@@ -3955,6 +4170,9 @@ class ClientAgent {
3955
4170
  });
3956
4171
  return;
3957
4172
  }
4173
+ if (outputEpoch !== this._outputEpoch) {
4174
+ return;
4175
+ }
3958
4176
  this.params.onOutput &&
3959
4177
  this.params.onOutput(this.params.clientId, this.params.agentName, result);
3960
4178
  await this._outputSubject.next(result);
@@ -4048,6 +4266,16 @@ class ClientAgent {
4048
4266
  await this._resqueSubject.next(MODEL_RESQUE_SYMBOL);
4049
4267
  return placeholder;
4050
4268
  }
4269
+ /**
4270
+ * Marks in-flight executions as substituted: the swarm emitted a replacement
4271
+ * output (ClientSwarm.emit), so results of executions started earlier must not
4272
+ * reach _outputSubject — they would pair with the next waiter otherwise.
4273
+ */
4274
+ commitOutputSubstituted() {
4275
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4276
+ this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} commitOutputSubstituted`);
4277
+ this._outputEpoch += 1;
4278
+ }
4051
4279
  /**
4052
4280
  * Waits for the next output to be emitted via _outputSubject, typically after execute or run.
4053
4281
  * Useful for external consumers (e.g., SwarmConnectionService) awaiting agent responses.
@@ -4146,7 +4374,22 @@ class ClientAgent {
4146
4374
  }
4147
4375
  else if (GLOBAL_CONFIG.CC_RESQUE_STRATEGY === "custom") {
4148
4376
  console.warn(`agent-swarm model using custom resurrect for agentName=${this.params.agentName} clientId=${this.params.clientId} validation=${validation}`);
4149
- const output = await GLOBAL_CONFIG.CC_TOOL_CALL_EXCEPTION_CUSTOM_FUNCTION(this.params.clientId, this.params.agentName);
4377
+ let output;
4378
+ try {
4379
+ output = await GLOBAL_CONFIG.CC_TOOL_CALL_EXCEPTION_CUSTOM_FUNCTION(this.params.clientId, this.params.agentName);
4380
+ }
4381
+ catch (error) {
4382
+ // A throwing custom resque function must not reject the queued
4383
+ // EXECUTE_FN: degrade to a placeholder answer instead.
4384
+ console.error(`agent-swarm CC_TOOL_CALL_EXCEPTION_CUSTOM_FUNCTION error agentName=${this.params.agentName} error=${functoolsKit.getErrorMessage(error)}`);
4385
+ await errorSubject.next([this.params.clientId, error]);
4386
+ output = {
4387
+ agentName: this.params.agentName,
4388
+ mode: "tool",
4389
+ role: "assistant",
4390
+ content: createPlaceholder(),
4391
+ };
4392
+ }
4150
4393
  this.params.completion.callbacks?.onComplete &&
4151
4394
  this.params.completion.callbacks?.onComplete(args, output);
4152
4395
  return output;
@@ -4261,6 +4504,7 @@ class ClientAgent {
4261
4504
  async commitCancelOutput() {
4262
4505
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4263
4506
  this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} commitCancelOutput`);
4507
+ this._outputEpoch += 1;
4264
4508
  this._toolAbortController.abort();
4265
4509
  await this._cancelOutputSubject.next(CANCEL_OUTPUT_SYMBOL);
4266
4510
  await this.params.bus.emit(this.params.clientId, {
@@ -4429,6 +4673,14 @@ class ClientAgent {
4429
4673
  async dispose() {
4430
4674
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4431
4675
  this.params.logger.debug(`ClientAgent agentName=${this.params.agentName} clientId=${this.params.clientId} dispose`);
4676
+ if (this._activeExecutions > 0) {
4677
+ // The instance is being torn down while its execution is still running
4678
+ // (e.g. changeToAgent mid-completion). Resolve the pending waiter with an
4679
+ // empty output and invalidate the epoch so the late completion result of
4680
+ // the dying instance is dropped instead of poisoning the next waiter.
4681
+ this._outputEpoch += 1;
4682
+ await this._outputSubject.next("");
4683
+ }
4432
4684
  {
4433
4685
  this._agentChangeSubject.unsubscribeAll();
4434
4686
  this._resqueSubject.unsubscribeAll();
@@ -4444,8 +4696,6 @@ class ClientAgent {
4444
4696
  }
4445
4697
  }
4446
4698
 
4447
- /** Timeout duration for operator signal in milliseconds*/
4448
- const OPERATOR_SIGNAL_TIMEOUT = 90000;
4449
4699
  /** Symbol representing operator timeout*/
4450
4700
  const OPERATOR_SIGNAL_SYMBOL = Symbol("operator-timeout");
4451
4701
  /**
@@ -4477,8 +4727,9 @@ class OperatorSignal {
4477
4727
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4478
4728
  this.params.logger.debug(`OperatorSignal agentName=${this.params.agentName} clientId=${this.params.clientId} dispose`);
4479
4729
  if (this._disposeRef) {
4730
+ const disposeRef = this._disposeRef;
4480
4731
  this._disposeRef = null;
4481
- await this._disposeRef();
4732
+ await disposeRef();
4482
4733
  }
4483
4734
  }
4484
4735
  }
@@ -4513,10 +4764,13 @@ class ClientOperator {
4513
4764
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4514
4765
  this.params.logger.debug(`ClientOperator agentName=${this.params.agentName} clientId=${this.params.clientId} execute begin`, { input, mode });
4515
4766
  if (mode === "tool") {
4516
- console.warn(`ClientOperator: execute with tool mode should not be called for clientId=${this.params.clientId} agentName=${this.params.agentName}`);
4767
+ // A tool-mode execute reaching an operator is normal: navigation to an
4768
+ // operator agent ends with executeForce (mode "tool"). Forward it to the
4769
+ // human instead of returning silently — returning would leave the
4770
+ // enclosing waitForOutput hanging forever, making the operator agent
4771
+ // unreachable through navigation.
4517
4772
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4518
- this.params.logger.debug(`ClientOperator agentName=${this.params.agentName} clientId=${this.params.clientId} execute - tool mode not supported`);
4519
- return;
4773
+ this.params.logger.debug(`ClientOperator agentName=${this.params.agentName} clientId=${this.params.clientId} execute tool mode forwarded to operator`);
4520
4774
  }
4521
4775
  this._operatorSignal.sendMessage(input, this._outgoingSubject.next);
4522
4776
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
@@ -4533,11 +4787,11 @@ class ClientOperator {
4533
4787
  }
4534
4788
  const result = await Promise.race([
4535
4789
  this._outgoingSubject.toPromise(),
4536
- functoolsKit.sleep(OPERATOR_SIGNAL_TIMEOUT).then(() => OPERATOR_SIGNAL_SYMBOL),
4790
+ functoolsKit.sleep(GLOBAL_CONFIG.CC_OPERATOR_SIGNAL_TIMEOUT).then(() => OPERATOR_SIGNAL_SYMBOL),
4537
4791
  ]);
4538
4792
  if (typeof result === "symbol") {
4539
4793
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
4540
- this.params.logger.debug(`ClientOperator agentName=${this.params.agentName} clientId=${this.params.clientId} waitForOutput timeout after ${OPERATOR_SIGNAL_TIMEOUT}ms`);
4794
+ this.params.logger.debug(`ClientOperator agentName=${this.params.agentName} clientId=${this.params.clientId} waitForOutput timeout after ${GLOBAL_CONFIG.CC_OPERATOR_SIGNAL_TIMEOUT}ms`);
4541
4795
  await this._operatorSignal.dispose();
4542
4796
  return "";
4543
4797
  }
@@ -4644,26 +4898,26 @@ class ClientOperator {
4644
4898
  }
4645
4899
  }
4646
4900
 
4647
- const METHOD_NAME$1L = "function.commit.commitToolOutput";
4901
+ const METHOD_NAME$1M = "function.commit.commitToolOutput";
4648
4902
  /**
4649
4903
  * Function implementation
4650
4904
  */
4651
4905
  const commitToolOutputInternal = beginContext(async (toolId, content, clientId, agentName) => {
4652
4906
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
4653
4907
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4654
- swarm$1.loggerService.log(METHOD_NAME$1L, {
4908
+ swarm$1.loggerService.log(METHOD_NAME$1M, {
4655
4909
  toolId,
4656
4910
  content,
4657
4911
  clientId,
4658
4912
  agentName,
4659
4913
  });
4660
4914
  // Validate the agent, session, and swarm to ensure they exist and are accessible
4661
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1L);
4662
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1L);
4915
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1M);
4916
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1M);
4663
4917
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4664
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1L);
4918
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1M);
4665
4919
  // Check if the specified agent is still the active agent in the swarm session
4666
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1L, clientId, swarmName);
4920
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1M, clientId, swarmName);
4667
4921
  if (currentAgentName !== agentName) {
4668
4922
  // Log a skip message if the agent has changed during the operation
4669
4923
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
@@ -4676,7 +4930,7 @@ const commitToolOutputInternal = beginContext(async (toolId, content, clientId,
4676
4930
  return;
4677
4931
  }
4678
4932
  // Commit the tool output to the session via the session public service
4679
- await swarm$1.sessionPublicService.commitToolOutput(toolId, content, METHOD_NAME$1L, clientId, swarmName);
4933
+ await swarm$1.sessionPublicService.commitToolOutput(toolId, content, METHOD_NAME$1M, clientId, swarmName);
4680
4934
  });
4681
4935
  /**
4682
4936
  * Commits the output of a tool execution to the active agent in a swarm session.
@@ -4698,10 +4952,7 @@ async function commitToolOutput(toolId, content, clientId, agentName) {
4698
4952
  return await commitToolOutputInternal(toolId, content, clientId, agentName);
4699
4953
  }
4700
4954
 
4701
- const disposeSubject = new functoolsKit.Subject();
4702
- const errorSubject = new functoolsKit.Subject();
4703
-
4704
- const METHOD_NAME$1K = "function.target.execute";
4955
+ const METHOD_NAME$1L = "function.target.execute";
4705
4956
  /**
4706
4957
  * Function implementation
4707
4958
  */
@@ -4709,19 +4960,19 @@ const executeInternal = beginContext(async (content, clientId, agentName) => {
4709
4960
  const executionId = functoolsKit.randomString();
4710
4961
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
4711
4962
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4712
- swarm$1.loggerService.log(METHOD_NAME$1K, {
4963
+ swarm$1.loggerService.log(METHOD_NAME$1L, {
4713
4964
  content,
4714
4965
  clientId,
4715
4966
  agentName,
4716
4967
  executionId,
4717
4968
  });
4718
4969
  // Validate the agent, session, and swarm
4719
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1K);
4720
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1K);
4970
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1L);
4971
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1L);
4721
4972
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4722
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1K);
4973
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1L);
4723
4974
  // Check if the specified agent is still the active agent
4724
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1K, clientId, swarmName);
4975
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1L, clientId, swarmName);
4725
4976
  if (currentAgentName !== agentName) {
4726
4977
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4727
4978
  swarm$1.loggerService.log('function "execute" skipped due to the agent change', {
@@ -4747,7 +4998,7 @@ const executeInternal = beginContext(async (content, clientId, agentName) => {
4747
4998
  errorValue = error;
4748
4999
  }
4749
5000
  });
4750
- result = await swarm$1.sessionPublicService.execute(content, "tool", METHOD_NAME$1K, clientId, swarmName);
5001
+ result = await swarm$1.sessionPublicService.execute(content, "tool", METHOD_NAME$1L, clientId, swarmName);
4751
5002
  unError();
4752
5003
  if (errorValue) {
4753
5004
  throw errorValue;
@@ -4793,26 +5044,26 @@ async function execute(content, clientId, agentName) {
4793
5044
  }
4794
5045
 
4795
5046
  /** @private Constant defining the method name for logging and validation context*/
4796
- const METHOD_NAME$1J = "function.commit.commitFlush";
5047
+ const METHOD_NAME$1K = "function.commit.commitFlush";
4797
5048
  /**
4798
5049
  * Function implementation
4799
5050
  */
4800
5051
  const commitFlushInternal = beginContext(async (clientId, agentName) => {
4801
5052
  // Log the flush attempt if enabled
4802
5053
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4803
- swarm$1.loggerService.log(METHOD_NAME$1J, {
5054
+ swarm$1.loggerService.log(METHOD_NAME$1K, {
4804
5055
  clientId,
4805
5056
  agentName,
4806
5057
  });
4807
5058
  // Validate the agent exists
4808
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1J);
5059
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1K);
4809
5060
  // Validate the session exists and retrieve the associated swarm
4810
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1J);
5061
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1K);
4811
5062
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4812
5063
  // Validate the swarm configuration
4813
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1J);
5064
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1K);
4814
5065
  // Check if the current agent matches the provided agent
4815
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1J, clientId, swarmName);
5066
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1K, clientId, swarmName);
4816
5067
  if (currentAgentName !== agentName) {
4817
5068
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4818
5069
  swarm$1.loggerService.log('function "commitFlush" skipped due to the agent change', {
@@ -4823,7 +5074,7 @@ const commitFlushInternal = beginContext(async (clientId, agentName) => {
4823
5074
  return;
4824
5075
  }
4825
5076
  // Commit the flush of agent history via SessionPublicService
4826
- await swarm$1.sessionPublicService.commitFlush(METHOD_NAME$1J, clientId, swarmName);
5077
+ await swarm$1.sessionPublicService.commitFlush(METHOD_NAME$1K, clientId, swarmName);
4827
5078
  });
4828
5079
  /**
4829
5080
  * Commits a flush of agent history for a specific client and agent in the swarm system.
@@ -4842,25 +5093,25 @@ async function commitFlush(clientId, agentName) {
4842
5093
  return await commitFlushInternal(clientId, agentName);
4843
5094
  }
4844
5095
 
4845
- const METHOD_NAME$1I = "function.target.emit";
5096
+ const METHOD_NAME$1J = "function.target.emit";
4846
5097
  /**
4847
5098
  * Function implementation
4848
5099
  */
4849
5100
  const emitInternal = beginContext(async (content, clientId, agentName) => {
4850
5101
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
4851
5102
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4852
- swarm$1.loggerService.log(METHOD_NAME$1I, {
5103
+ swarm$1.loggerService.log(METHOD_NAME$1J, {
4853
5104
  content,
4854
5105
  clientId,
4855
5106
  agentName,
4856
5107
  });
4857
5108
  // Validate the agent, session, and swarm
4858
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1I);
4859
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1I);
5109
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1J);
5110
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1J);
4860
5111
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4861
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1I);
5112
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1J);
4862
5113
  // Check if the specified agent is still the active agent
4863
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1I, clientId, swarmName);
5114
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1J, clientId, swarmName);
4864
5115
  if (currentAgentName !== agentName) {
4865
5116
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4866
5117
  swarm$1.loggerService.log('function "emit" skipped due to the agent change', {
@@ -4871,21 +5122,21 @@ const emitInternal = beginContext(async (content, clientId, agentName) => {
4871
5122
  return;
4872
5123
  }
4873
5124
  // Emit the content directly via the session public service
4874
- return await swarm$1.sessionPublicService.emit(content, METHOD_NAME$1I, clientId, swarmName);
5125
+ return await swarm$1.sessionPublicService.emit(content, METHOD_NAME$1J, clientId, swarmName);
4875
5126
  });
4876
5127
  /**
4877
5128
  * Emits a string as model output without executing an incoming message, with agent activity validation.
4878
5129
  *
4879
- * This function directly emits a provided string as output from the swarm session, bypassing message execution, and is designed exclusively
4880
- * for sessions established via `makeConnection`. It validates the session, swarm, and specified agent, ensuring the agent is still active
4881
- * before emitting. If the active agent has changed, the operation is skipped. The execution is wrapped in `beginContext` for a clean environment,
4882
- * logs the operation if enabled, and throws an error if the session mode is not "makeConnection".
5130
+ * This function directly emits a provided string as output from the swarm session, bypassing message execution.
5131
+ * It validates the session, swarm, and specified agent, ensuring the agent is still active before emitting.
5132
+ * If the active agent has changed, the operation is skipped. The execution is wrapped in `beginContext` for a
5133
+ * clean environment and logs the operation if enabled. Works for any session mode.
4883
5134
  *
4884
5135
  *
4885
5136
  * @param {string} content - The content to be processed or stored.
4886
5137
  * @param {string} clientId - The unique identifier of the client session.
4887
5138
  * @param {AgentName} agentName - The name of the agent to use or reference.
4888
- * @throws {Error} If the session mode is not "makeConnection", or if agent, session, or swarm validation fails.
5139
+ * @throws {Error} If agent, session, or swarm validation fails.
4889
5140
  * @example
4890
5141
  * await emit("Direct output", "client-123", "AgentX"); // Emits "Direct output" if AgentX is active
4891
5142
  */
@@ -4893,22 +5144,22 @@ async function emit(content, clientId, agentName) {
4893
5144
  return await emitInternal(content, clientId, agentName);
4894
5145
  }
4895
5146
 
4896
- const METHOD_NAME$1H = "function.common.getAgentName";
5147
+ const METHOD_NAME$1I = "function.common.getAgentName";
4897
5148
  /**
4898
5149
  * Function implementation
4899
5150
  */
4900
5151
  const getAgentNameInternal = beginContext(async (clientId) => {
4901
5152
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
4902
5153
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4903
- swarm$1.loggerService.log(METHOD_NAME$1H, {
5154
+ swarm$1.loggerService.log(METHOD_NAME$1I, {
4904
5155
  clientId,
4905
5156
  });
4906
5157
  // Validate the session and swarm to ensure they exist and are accessible
4907
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1H);
5158
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1I);
4908
5159
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4909
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1H);
5160
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1I);
4910
5161
  // Retrieve the active agent name via the swarm public service
4911
- return await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1H, clientId, swarmName);
5162
+ return await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1I, clientId, swarmName);
4912
5163
  });
4913
5164
  /**
4914
5165
  * Retrieves the name of the active agent for a given client session in a swarm.
@@ -4929,26 +5180,26 @@ async function getAgentName(clientId) {
4929
5180
  }
4930
5181
 
4931
5182
  /** @private Constant defining the method name for logging and validation context*/
4932
- const METHOD_NAME$1G = "function.commit.commitStopTools";
5183
+ const METHOD_NAME$1H = "function.commit.commitStopTools";
4933
5184
  /**
4934
5185
  * Function implementation
4935
5186
  */
4936
5187
  const commitStopToolsInternal = beginContext(async (clientId, agentName) => {
4937
5188
  // Log the stop tools attempt if enabled
4938
5189
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4939
- swarm$1.loggerService.log(METHOD_NAME$1G, {
5190
+ swarm$1.loggerService.log(METHOD_NAME$1H, {
4940
5191
  clientId,
4941
5192
  agentName,
4942
5193
  });
4943
5194
  // Validate the agent exists
4944
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1G);
5195
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1H);
4945
5196
  // Validate the session exists and retrieve the associated swarm
4946
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1G);
5197
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1H);
4947
5198
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
4948
5199
  // Validate the swarm configuration
4949
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1G);
5200
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1H);
4950
5201
  // Check if the current agent matches the provided agent
4951
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1G, clientId, swarmName);
5202
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1H, clientId, swarmName);
4952
5203
  if (currentAgentName !== agentName) {
4953
5204
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
4954
5205
  swarm$1.loggerService.log('function "commitStopTools" skipped due to the agent change', {
@@ -4959,7 +5210,7 @@ const commitStopToolsInternal = beginContext(async (clientId, agentName) => {
4959
5210
  return;
4960
5211
  }
4961
5212
  // Commit the stop of the next tool execution via SessionPublicService
4962
- await swarm$1.sessionPublicService.commitStopTools(METHOD_NAME$1G, clientId, swarmName);
5213
+ await swarm$1.sessionPublicService.commitStopTools(METHOD_NAME$1H, clientId, swarmName);
4963
5214
  });
4964
5215
  /**
4965
5216
  * Prevents the next tool from being executed for a specific client and agent in the swarm system.
@@ -5178,6 +5429,63 @@ class MCPUtils {
5178
5429
  */
5179
5430
  const MCP = new MCPUtils();
5180
5431
 
5432
+ /**
5433
+ * Wraps schema observer callbacks (onExecute, onOutput, onInit, ...) so a throwing
5434
+ * callback cannot reject the queued agent execution. ClientAgent invokes these
5435
+ * fire-and-forget from EXECUTE_FN/RUN_FN: an uncaught throw there becomes an
5436
+ * unhandled rejection and the pending waitForOutput hangs forever.
5437
+ * Callbacks are observers — log the error and keep the flow running.
5438
+ */
5439
+ const guardAgentCallbacks = (callbacks, agentName) => {
5440
+ if (!callbacks) {
5441
+ return {};
5442
+ }
5443
+ const result = {};
5444
+ for (const [key, value] of Object.entries(callbacks)) {
5445
+ if (typeof value !== "function") {
5446
+ result[key] = value;
5447
+ continue;
5448
+ }
5449
+ result[key] = (...args) => {
5450
+ try {
5451
+ const output = value(...args);
5452
+ if (output && typeof output.catch === "function") {
5453
+ output.catch((error) => console.error(`agent-swarm ${key} agent callback error agentName=${agentName} error=${functoolsKit.getErrorMessage(error)}`));
5454
+ }
5455
+ return output;
5456
+ }
5457
+ catch (error) {
5458
+ console.error(`agent-swarm ${key} agent callback error agentName=${agentName} error=${functoolsKit.getErrorMessage(error)}`);
5459
+ }
5460
+ };
5461
+ }
5462
+ return result;
5463
+ };
5464
+ /**
5465
+ * Wraps a schema transformer hook (transform/map/mapToolCalls/prompt/systemDynamic).
5466
+ * A throwing transformer is a configuration error: it is surfaced to the caller
5467
+ * through errorSubject (session.complete/execute reject after the exchange), while
5468
+ * the flow continues with the untouched input value — falling back to an empty
5469
+ * result here would re-enter the resurrect path whose own transform call throws
5470
+ * again, deadlocking the execution.
5471
+ *
5472
+ * @param fn - The user transformer to guard.
5473
+ * @param name - Hook name for logging.
5474
+ * @param agentName - Owning agent name for logging.
5475
+ * @param getClientId - Extracts clientId from the call arguments for errorSubject.
5476
+ * @param getFallback - Produces the fallback result from the call arguments.
5477
+ */
5478
+ const guardAgentTransformer = (fn, name, agentName, getClientId, getFallback) => (async (...args) => {
5479
+ try {
5480
+ return await fn(...args);
5481
+ }
5482
+ catch (error) {
5483
+ console.error(`agent-swarm ${name} hook error agentName=${agentName} error=${functoolsKit.getErrorMessage(error)}`);
5484
+ await errorSubject.next([getClientId(...args), error]);
5485
+ return getFallback(...args);
5486
+ }
5487
+ });
5488
+
5181
5489
  /**
5182
5490
  * Service class for managing agent connections and operations in the swarm system.
5183
5491
  * Implements IAgent to provide an interface for agent instantiation, execution, message handling, and lifecycle management.
@@ -5266,10 +5574,12 @@ class AgentConnectionService {
5266
5574
  this.sessionValidationService.addAgentUsage(clientId, agentName);
5267
5575
  storages?.forEach((storageName) => this.storageConnectionService
5268
5576
  .getStorage(clientId, storageName)
5269
- .waitForInit());
5577
+ .waitForInit()
5578
+ .catch((error) => console.error(`agent-swarm storage waitForInit error storageName=${storageName} clientId=${clientId} error=${functoolsKit.getErrorMessage(error)}`)));
5270
5579
  states?.forEach((stateName) => this.stateConnectionService
5271
5580
  .getStateRef(clientId, stateName)
5272
- .waitForInit());
5581
+ .waitForInit()
5582
+ .catch((error) => console.error(`agent-swarm state waitForInit error stateName=${stateName} clientId=${clientId} error=${functoolsKit.getErrorMessage(error)}`)));
5273
5583
  if (operator) {
5274
5584
  return new ClientOperator({
5275
5585
  clientId,
@@ -5278,29 +5588,33 @@ class AgentConnectionService {
5278
5588
  history,
5279
5589
  logger: this.loggerService,
5280
5590
  connectOperator,
5281
- ...callbacks,
5591
+ ...guardAgentCallbacks(callbacks, agentName),
5282
5592
  });
5283
5593
  }
5284
5594
  return new ClientAgent({
5285
5595
  clientId,
5286
5596
  agentName,
5287
- validate,
5597
+ validate: guardAgentTransformer(validate, "validate", agentName, () => clientId, () => null),
5288
5598
  maxToolCalls,
5289
- mapToolCalls,
5599
+ mapToolCalls: guardAgentTransformer(mapToolCalls, "mapToolCalls", agentName, (_calls, callClientId) => callClientId, (calls) => calls),
5290
5600
  logger: this.loggerService,
5291
5601
  bus: this.busService,
5292
5602
  mcp: mcp
5293
5603
  ? new MergeMCP(mcp.map(this.mcpConnectionService.getMCP), agentName)
5294
5604
  : new NoopMCP(agentName),
5295
5605
  history,
5296
- prompt,
5606
+ prompt: typeof prompt === "function"
5607
+ ? guardAgentTransformer(prompt, "prompt", agentName, (callClientId) => callClientId, () => "")
5608
+ : prompt,
5297
5609
  systemStatic,
5298
- systemDynamic,
5299
- transform,
5300
- map,
5610
+ systemDynamic: systemDynamic
5611
+ ? guardAgentTransformer(systemDynamic, "systemDynamic", agentName, (callClientId) => callClientId, () => [])
5612
+ : systemDynamic,
5613
+ transform: guardAgentTransformer(transform, "transform", agentName, (_text, callClientId) => callClientId, (text) => text),
5614
+ map: guardAgentTransformer(map, "map", agentName, (_message, callClientId) => callClientId, (message) => message),
5301
5615
  tools: tools?.map(this.toolSchemaService.get),
5302
5616
  completion: this.completionSchemaService.get(completionName),
5303
- ...callbacks,
5617
+ ...guardAgentCallbacks(callbacks, agentName),
5304
5618
  });
5305
5619
  });
5306
5620
  /**
@@ -5473,12 +5787,12 @@ class AgentConnectionService {
5473
5787
  }
5474
5788
 
5475
5789
  /** @private Constant defining the method name for logging purposes*/
5476
- const METHOD_NAME$1F = "function.common.getPayload";
5790
+ const METHOD_NAME$1G = "function.common.getPayload";
5477
5791
  /**
5478
5792
  * Function implementation
5479
5793
  */
5480
5794
  const getPayloadInternal = () => {
5481
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1F);
5795
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1G);
5482
5796
  if (PayloadContextService.hasContext()) {
5483
5797
  const { payload } = swarm$1.payloadContextService.context;
5484
5798
  return payload;
@@ -5527,7 +5841,16 @@ class ClientHistory {
5527
5841
  if (message.mode === "user" && message.role === "user") {
5528
5842
  message = { ...message, payload: getPayload() };
5529
5843
  }
5530
- await this.params.items.push(message, this.params.clientId, this.params.agentName);
5844
+ try {
5845
+ await this.params.items.push(message, this.params.clientId, this.params.agentName);
5846
+ }
5847
+ catch (error) {
5848
+ // A throwing history adapter must not reject the queued EXECUTE_FN
5849
+ // (unhandled rejection + hung waitForOutput): drop the record, surface
5850
+ // the error through errorSubject so the caller's complete() rejects.
5851
+ console.error(`agent-swarm history push error agentName=${this.params.agentName} clientId=${this.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
5852
+ await errorSubject.next([this.params.clientId, error]);
5853
+ }
5531
5854
  await this.params.bus.emit(this.params.clientId, {
5532
5855
  type: "push",
5533
5856
  source: "history-bus",
@@ -5572,8 +5895,14 @@ class ClientHistory {
5572
5895
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
5573
5896
  this.params.logger.debug(`ClientHistory agentName=${this.params.agentName} toArrayForRaw`);
5574
5897
  const result = [];
5575
- for await (const item of this.params.items.iterate(this.params.clientId, this.params.agentName)) {
5576
- result.push(item);
5898
+ try {
5899
+ for await (const item of this.params.items.iterate(this.params.clientId, this.params.agentName)) {
5900
+ result.push(item);
5901
+ }
5902
+ }
5903
+ catch (error) {
5904
+ console.error(`agent-swarm history iterate error agentName=${this.params.agentName} clientId=${this.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
5905
+ await errorSubject.next([this.params.clientId, error]);
5577
5906
  }
5578
5907
  return result;
5579
5908
  }
@@ -5588,7 +5917,19 @@ class ClientHistory {
5588
5917
  this.params.logger.debug(`ClientHistory agentName=${this.params.agentName} toArrayForAgent`);
5589
5918
  const commonMessagesRaw = [];
5590
5919
  const systemMessagesRaw = [];
5591
- for await (const content of this.params.items.iterate(this.params.clientId, this.params.agentName)) {
5920
+ const iterated = [];
5921
+ try {
5922
+ for await (const content of this.params.items.iterate(this.params.clientId, this.params.agentName)) {
5923
+ iterated.push(content);
5924
+ }
5925
+ }
5926
+ catch (error) {
5927
+ // A throwing history adapter or filter must not reject getCompletion
5928
+ // inside the queued EXECUTE_FN: continue with what was collected.
5929
+ console.error(`agent-swarm history iterate error agentName=${this.params.agentName} clientId=${this.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
5930
+ await errorSubject.next([this.params.clientId, error]);
5931
+ }
5932
+ for (const content of iterated) {
5592
5933
  const message = content;
5593
5934
  if (message.role === "resque") {
5594
5935
  commonMessagesRaw.splice(0, commonMessagesRaw.length);
@@ -5611,15 +5952,27 @@ class ClientHistory {
5611
5952
  }
5612
5953
  }
5613
5954
  const systemMessages = systemMessagesRaw.filter(({ agentName }) => agentName === this.params.agentName);
5614
- const commonMessages = commonMessagesRaw
5955
+ const filteredCommonMessages = commonMessagesRaw
5615
5956
  .map(({ content, tool_calls, ...other }) => ({
5616
5957
  ...other,
5617
5958
  tool_calls,
5618
5959
  content: content || "",
5619
5960
  }))
5620
5961
  .filter(({ content, tool_calls }) => !!content || !!tool_calls?.length)
5621
- .filter(this._filterCondition)
5622
- .slice(-this.params.keepMessages);
5962
+ .filter((message) => {
5963
+ try {
5964
+ return this._filterCondition(message);
5965
+ }
5966
+ catch (error) {
5967
+ console.error(`agent-swarm history filter error agentName=${this.params.agentName} error=${functoolsKit.getErrorMessage(error)}`);
5968
+ return true;
5969
+ }
5970
+ });
5971
+ // slice(-0) === slice(0) keeps the WHOLE array, so keepMessages=0 would keep
5972
+ // all history instead of none — clamp explicitly to an empty window.
5973
+ const commonMessages = this.params.keepMessages > 0
5974
+ ? filteredCommonMessages.slice(-this.params.keepMessages)
5975
+ : [];
5623
5976
  const assistantToolOutputCallSet = new Set(commonMessages
5624
5977
  .filter(({ tool_call_id }) => !!tool_call_id)
5625
5978
  .map(({ tool_call_id }) => tool_call_id));
@@ -6207,10 +6560,50 @@ class ClientSwarm {
6207
6560
  */
6208
6561
  this._cancelOutputSubject = new functoolsKit.Subject();
6209
6562
  /**
6210
- * Waits for output from the active agent in a queued manner, delegating to WAIT_FOR_OUTPUT_FN.
6211
- * Ensures only one wait operation runs at a time, handling cancellation and agent changes, supporting ClientSession's output retrieval.
6563
+ * Chain of pending waitForOutput calls, reset to a resolved promise whenever
6564
+ * the most recently started waiter settles. See waitForOutput for the rationale.
6565
+ */
6566
+ this._lastOutputAwaiter = Promise.resolve();
6567
+ /**
6568
+ * Waiters created by waitForOutput that have not settled yet, in creation order.
6569
+ * joinOutput attaches nested tool executions to the head of this list.
6570
+ */
6571
+ this._pendingOutputAwaiters = [];
6572
+ /**
6573
+ * Waits for output from the active agent, delegating to WAIT_FOR_OUTPUT_FN.
6574
+ * Pending waiters run in FIFO order so each one consumes the next emitted output,
6575
+ * but once a started waiter settles the chain is reset: a waiter that subscribed
6576
+ * too late to observe its output stays pending without blocking waiters created
6577
+ * afterwards. Strict sequential queueing must be avoided here — a nested tool
6578
+ * execute whose output was already consumed would deadlock every later completion.
6212
6579
  */
6213
- this.waitForOutput = functoolsKit.queued(async () => await WAIT_FOR_OUTPUT_FN(this));
6580
+ this.waitForOutput = () => {
6581
+ const currentPromise = this._lastOutputAwaiter.then(async () => await WAIT_FOR_OUTPUT_FN(this));
6582
+ this._lastOutputAwaiter = currentPromise;
6583
+ this._pendingOutputAwaiters.push(currentPromise);
6584
+ const reset = () => {
6585
+ this._lastOutputAwaiter = Promise.resolve();
6586
+ const idx = this._pendingOutputAwaiters.indexOf(currentPromise);
6587
+ if (idx !== -1) {
6588
+ this._pendingOutputAwaiters.splice(idx, 1);
6589
+ }
6590
+ };
6591
+ currentPromise.then(reset, reset);
6592
+ return currentPromise;
6593
+ };
6594
+ /**
6595
+ * Awaits the same output as the oldest pending waitForOutput call, or starts a
6596
+ * fresh wait when none is pending. Nested executions triggered from inside a tool
6597
+ * (execute/executeForce with "tool" mode) must use this instead of waitForOutput:
6598
+ * their emitted output resolves the parent waiter, so queueing behind it would
6599
+ * leave the nested caller pending forever and skip the tool's onAfterCall.
6600
+ */
6601
+ this.joinOutput = () => {
6602
+ if (this._pendingOutputAwaiters.length) {
6603
+ return this._pendingOutputAwaiters[0];
6604
+ }
6605
+ return this.waitForOutput();
6606
+ };
6214
6607
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
6215
6608
  this.params.logger.debug(`ClientSwarm swarmName=${this.params.swarmName} clientId=${this.params.clientId} CTOR`, {
6216
6609
  params,
@@ -6224,6 +6617,13 @@ class ClientSwarm {
6224
6617
  async emit(message) {
6225
6618
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
6226
6619
  this.params.logger.debug(`ClientSwarm swarmName=${this.params.swarmName} clientId=${this.params.clientId} emit`);
6620
+ // The emitted message substitutes the output of any in-flight execution:
6621
+ // invalidate agents' pending emissions so a stale result cannot resolve
6622
+ // the waiter of the next message.
6623
+ for (const [, agent] of this._agentList) {
6624
+ const agentRef = agent;
6625
+ agentRef.commitOutputSubstituted?.();
6626
+ }
6227
6627
  await this._emitSubject.next({
6228
6628
  agentName: await this.getAgentName(),
6229
6629
  output: message,
@@ -6251,6 +6651,13 @@ class ClientSwarm {
6251
6651
  if (this._navigationStack === STACK_NEED_FETCH) {
6252
6652
  this._navigationStack = await this.params.getNavigationStack(this.params.clientId, this.params.swarmName);
6253
6653
  }
6654
+ // setAgentName pushes the NEW agent, so the top of the stack is the agent
6655
+ // we are currently on — drop it first, otherwise "previous" would resolve
6656
+ // to the active agent itself (self-navigation instead of going back).
6657
+ const activeAgent = await this.getAgentName();
6658
+ if (this._navigationStack[this._navigationStack.length - 1] === activeAgent) {
6659
+ this._navigationStack.pop();
6660
+ }
6254
6661
  const prevAgent = this._navigationStack.pop();
6255
6662
  await this.params.setNavigationStack(this.params.clientId, this._navigationStack, this.params.swarmName);
6256
6663
  return prevAgent ? prevAgent : this.params.defaultAgent;
@@ -6396,6 +6803,18 @@ class ClientSwarm {
6396
6803
  async dispose() {
6397
6804
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
6398
6805
  this.params.logger.debug(`ClientSession clientId=${this.params.clientId} dispose`);
6806
+ if (this._pendingOutputAwaiters.length) {
6807
+ // Resolve in-flight waitForOutput calls with an empty output (same
6808
+ // contract as cancelOutput) before unsubscribing — otherwise a complete()
6809
+ // pending at dispose time would never settle.
6810
+ const agentName = this._activeAgent === AGENT_NEED_FETCH
6811
+ ? this.params.defaultAgent
6812
+ : this._activeAgent;
6813
+ await this._cancelOutputSubject.next({
6814
+ agentName,
6815
+ output: "",
6816
+ });
6817
+ }
6399
6818
  {
6400
6819
  this._agentChangedSubject.unsubscribeAll();
6401
6820
  this._emitSubject.unsubscribeAll();
@@ -6779,10 +7198,10 @@ class CompletionSchemaService {
6779
7198
  throw new Error(`agent-swarm completion schema validation failed: missing getCompletion for completionName=${completionSchema.completionName}`);
6780
7199
  }
6781
7200
  if (completionSchema.flags && !Array.isArray(completionSchema.flags)) {
6782
- throw new Error(`agent-swarm completion schema validation failed: invalid flags for computeName=${completionSchema.completionName} flags=${completionSchema.flags}`);
7201
+ throw new Error(`agent-swarm completion schema validation failed: invalid flags for completionName=${completionSchema.completionName} flags=${completionSchema.flags}`);
6783
7202
  }
6784
7203
  if (completionSchema.flags?.some((value) => typeof value !== "string")) {
6785
- throw new Error(`agent-swarm completion schema validation failed: invalid flags for computeName=${completionSchema.completionName} flags=[${completionSchema.flags}]`);
7204
+ throw new Error(`agent-swarm completion schema validation failed: invalid flags for completionName=${completionSchema.completionName} flags=[${completionSchema.flags}]`);
6786
7205
  }
6787
7206
  };
6788
7207
  /**
@@ -6965,7 +7384,15 @@ class ClientSession {
6965
7384
  if (mode === "user") {
6966
7385
  await this.AQUIRE_LOCK(this);
6967
7386
  }
6968
- const outputAwaiter = this.params.swarm.waitForOutput();
7387
+ // A tool-mode execute issued while a tool call is still running is a nested
7388
+ // continuation of that execution: its output resolves the already pending
7389
+ // waiter, so it must join it. Standalone server-side tool-mode executes keep
7390
+ // the FIFO waitForOutput pairing.
7391
+ const isNestedToolExecution = mode === "tool" &&
7392
+ Object.values(this.params.swarm.params.agentMap).some((agentRef) => agentRef instanceof ClientAgent && agentRef._runningToolCalls > 0);
7393
+ const outputAwaiter = isNestedToolExecution
7394
+ ? this.params.swarm.joinOutput()
7395
+ : this.params.swarm.waitForOutput();
6969
7396
  agent.execute(message, mode);
6970
7397
  let output = "";
6971
7398
  try {
@@ -7249,12 +7676,19 @@ class ClientSession {
7249
7676
  clientId: this.params.clientId,
7250
7677
  });
7251
7678
  this._notifySubject.subscribe(async (data) => {
7252
- await swarm$1.executionValidationService.flushCount(this.params.clientId, this.params.swarmName);
7253
- await connector({
7254
- data,
7255
- agentName: await this.params.swarm.getAgentName(),
7256
- clientId: this.params.clientId,
7257
- });
7679
+ try {
7680
+ await swarm$1.executionValidationService.flushCount(this.params.clientId, this.params.swarmName);
7681
+ await connector({
7682
+ data,
7683
+ agentName: await this.params.swarm.getAgentName(),
7684
+ clientId: this.params.clientId,
7685
+ });
7686
+ }
7687
+ catch (error) {
7688
+ // A throwing connector must not reject the notify subject chain
7689
+ // (unhandled rejection that can crash the host process).
7690
+ console.error(`agent-swarm connector error clientId=${this.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
7691
+ }
7258
7692
  });
7259
7693
  return async (incoming) => {
7260
7694
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
@@ -9290,9 +9724,13 @@ class AgentValidationService {
9290
9724
  if (!agent) {
9291
9725
  throw new Error(`agent-swarm agent ${agentName} not found source=${source}`);
9292
9726
  }
9293
- const completionSchema = this.completionSchemaService.get(agent.completion);
9294
- if (completionSchema.json) {
9295
- throw new Error(`agent-swarm agent ${agentName} completion schema is JSON source=${source}`);
9727
+ // Operator agents may omit completion entirely (see validateShallow),
9728
+ // so the JSON-flag check only applies when a completion is configured.
9729
+ if (agent.completion) {
9730
+ const completionSchema = this.completionSchemaService.get(agent.completion);
9731
+ if (completionSchema.json) {
9732
+ throw new Error(`agent-swarm agent ${agentName} completion schema is JSON source=${source}`);
9733
+ }
9296
9734
  }
9297
9735
  if (!agent.operator) {
9298
9736
  this.completionValidationService.validate(agent.completion, source);
@@ -10300,12 +10738,21 @@ const WAIT_FOR_INIT_FN$1 = async (self) => {
10300
10738
  if (!self.params.getData) {
10301
10739
  return;
10302
10740
  }
10303
- const data = await self.params.getData(self.params.clientId, self.params.storageName, await self.params.getDefaultData(self.params.clientId, self.params.storageName));
10304
- await Promise.all(data.map(functoolsKit.execpool(self._createEmbedding, {
10305
- delay: STORAGE_POOL_DELAY,
10306
- maxExec: GLOBAL_CONFIG.CC_STORAGE_SEARCH_POOL,
10307
- })));
10308
- self._itemMap = new Map(data.map((item) => [item.id, item]));
10741
+ try {
10742
+ const data = await self.params.getData(self.params.clientId, self.params.storageName, await self.params.getDefaultData(self.params.clientId, self.params.storageName));
10743
+ await Promise.all(data.map(functoolsKit.execpool(self._createEmbedding, {
10744
+ delay: STORAGE_POOL_DELAY,
10745
+ maxExec: GLOBAL_CONFIG.CC_STORAGE_SEARCH_POOL,
10746
+ })));
10747
+ self._itemMap = new Map(data.map((item) => [item.id, item]));
10748
+ }
10749
+ catch (error) {
10750
+ // waitForInit is fired without await from AgentConnectionService.getAgent:
10751
+ // a rejecting persistence adapter would otherwise crash the host process.
10752
+ // Degrade to an empty storage and surface the error.
10753
+ console.error(`agent-swarm storage init error storageName=${self.params.storageName} clientId=${self.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
10754
+ await errorSubject.next([self.params.clientId, error]);
10755
+ }
10309
10756
  };
10310
10757
  /**
10311
10758
  * Upserts an item into the storage, updates embeddings, and persists the data via params.setData.
@@ -10469,9 +10916,11 @@ class ClientStorage {
10469
10916
  total,
10470
10917
  });
10471
10918
  const indexed = new functoolsKit.SortedArray();
10472
- let searchEmbeddings = await this.params.readEmbeddingCache(this.params.embedding, createSHA256Hash(search));
10919
+ const searchHash = createSHA256Hash(search);
10920
+ let searchEmbeddings = await this.params.readEmbeddingCache(this.params.embedding, searchHash);
10473
10921
  if (!searchEmbeddings) {
10474
10922
  searchEmbeddings = await this.params.createEmbedding(search, this.params.embedding);
10923
+ await this.params.writeEmbeddingCache(searchEmbeddings, this.params.embedding, searchHash);
10475
10924
  }
10476
10925
  if (this.params.onCreate) {
10477
10926
  this.params.onCreate(search, searchEmbeddings, this.params.clientId, this.params.embedding);
@@ -11299,7 +11748,15 @@ const DISPATCH_FN = async (action, self, payload) => {
11299
11748
  const WAIT_FOR_INIT_FN = async (self) => {
11300
11749
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
11301
11750
  self.params.logger.debug(`ClientState stateName=${self.params.stateName} clientId=${self.params.clientId} shared=${self.params.shared} waitForInit`);
11302
- self._state = await self.params.getState(self.params.clientId, self.params.stateName, await self.params.getDefaultState(self.params.clientId, self.params.stateName));
11751
+ try {
11752
+ self._state = await self.params.getState(self.params.clientId, self.params.stateName, await self.params.getDefaultState(self.params.clientId, self.params.stateName));
11753
+ }
11754
+ catch (error) {
11755
+ // waitForInit is fired without await from AgentConnectionService.getAgent:
11756
+ // a rejecting persistence adapter would otherwise crash the host process.
11757
+ console.error(`agent-swarm state init error stateName=${self.params.stateName} clientId=${self.params.clientId} error=${functoolsKit.getErrorMessage(error)}`);
11758
+ await errorSubject.next([self.params.clientId, error]);
11759
+ }
11303
11760
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
11304
11761
  self.params.logger.debug(`ClientState stateName=${self.params.stateName} clientId=${self.params.clientId} shared=${self.params.shared} waitForInit output`, { initialState: self._state });
11305
11762
  if (self.params.callbacks?.onLoad) {
@@ -11320,6 +11777,12 @@ class ClientState {
11320
11777
  constructor(params) {
11321
11778
  this.params = params;
11322
11779
  this.stateChanged = new functoolsKit.Subject();
11780
+ /**
11781
+ * True while a queued dispatch (read/write) is executing for this instance.
11782
+ * getState checks it to serve reentrant reads (getState inside a setState
11783
+ * dispatchFn) without re-entering the queue, which would deadlock.
11784
+ */
11785
+ this._inDispatch = false;
11323
11786
  /**
11324
11787
  * The current state data, initialized as null and set during waitForInit.
11325
11788
  * Updated by setState and clearState, persisted via params.setState if provided.
@@ -11329,7 +11792,15 @@ class ClientState {
11329
11792
  * Queued dispatch function to read or write the state, delegating to DISPATCH_FN.
11330
11793
  * Ensures thread-safe state operations, supporting concurrent access from ClientAgent or tools.
11331
11794
  */
11332
- this.dispatch = functoolsKit.queued(async (action, payload) => await DISPATCH_FN(action, this, payload));
11795
+ this.dispatch = functoolsKit.queued(async (action, payload) => {
11796
+ this._inDispatch = true;
11797
+ try {
11798
+ return await DISPATCH_FN(action, this, payload);
11799
+ }
11800
+ finally {
11801
+ this._inDispatch = false;
11802
+ }
11803
+ });
11333
11804
  /**
11334
11805
  * Waits for the state to initialize via WAIT_FOR_INIT_FN, ensuring it’s only called once using singleshot.
11335
11806
  * Loads the initial state into _state, supporting StateConnectionService’s lifecycle management.
@@ -11418,7 +11889,14 @@ class ClientState {
11418
11889
  async getState() {
11419
11890
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
11420
11891
  this.params.logger.debug(`ClientState stateName=${this.params.stateName} clientId=${this.params.clientId} shared=${this.params.shared} getState`);
11421
- await this.dispatch("read");
11892
+ // Reads normally go through the dispatch queue to observe writes in order.
11893
+ // A read issued from INSIDE a running write (getState within a setState
11894
+ // dispatchFn) would deadlock behind that write, so _inDispatch lets such a
11895
+ // reentrant read return the current field directly.
11896
+ if (this._inDispatch) ;
11897
+ else {
11898
+ await this.dispatch("read");
11899
+ }
11422
11900
  if (this.params.callbacks?.onRead) {
11423
11901
  this.params.callbacks.onRead(this._state, this.params.clientId, this.params.stateName);
11424
11902
  }
@@ -11722,8 +12200,27 @@ class StatePublicService {
11722
12200
  }
11723
12201
 
11724
12202
  /**
11725
- * Service class implementing the IBus interface to manage event subscriptions and emissions in the swarm system.
11726
- * Provides methods to subscribe to events (subscribe, once), emit events (emit, commitExecutionBegin, commitExecutionEnd), and dispose of subscriptions (dispose), using a memoized Subject per clientId and EventSource.
12203
+ * Wraps a bus listener so its exceptions cannot escape into the emit path.
12204
+ * ClientAgent awaits bus.emit inside executions: a throwing subscriber would
12205
+ * otherwise surface as an unhandled rejection (crashing the host process on
12206
+ * modern Node) or reject the execution itself.
12207
+ */
12208
+ const GUARD_LISTENER_FN = (fn, clientId, source) => (event) => {
12209
+ try {
12210
+ const output = fn(event);
12211
+ if (output &&
12212
+ typeof output.catch === "function") {
12213
+ output.catch((error) => console.error(`agent-swarm bus listener error clientId=${clientId} source=${source} error=${functoolsKit.getErrorMessage(error)}`));
12214
+ }
12215
+ return output;
12216
+ }
12217
+ catch (error) {
12218
+ console.error(`agent-swarm bus listener error clientId=${clientId} source=${source} error=${functoolsKit.getErrorMessage(error)}`);
12219
+ }
12220
+ };
12221
+ /**
12222
+ * Service class implementing the IBus interface to manage event subscriptions and emissions in the swarm system.
12223
+ * Provides methods to subscribe to events (subscribe, once), emit events (emit, commitExecutionBegin, commitExecutionEnd), and dispose of subscriptions (dispose), using a memoized Subject per clientId and EventSource.
11727
12224
  * Integrates with ClientAgent (e.g., execution events in EXECUTE_FN), PerfService (e.g., execution tracking via emit), and DocService (e.g., performance logging), leveraging LoggerService for info-level logging and SessionValidationService for session validation.
11728
12225
  * Supports wildcard subscriptions (clientId="*") and execution-specific event aliases, enhancing event-driven communication across the system.
11729
12226
  */
@@ -11775,7 +12272,7 @@ class BusService {
11775
12272
  this._eventWildcardMap.set(source, true);
11776
12273
  }
11777
12274
  this._eventSourceSet.add(source);
11778
- return this.getEventSubject(clientId, source).subscribe(fn);
12275
+ return this.getEventSubject(clientId, source).subscribe(GUARD_LISTENER_FN(fn, clientId, source));
11779
12276
  };
11780
12277
  /**
11781
12278
  * Subscribes to a single event for a specific client and event source, invoking the callback once when the filter condition is met.
@@ -11793,7 +12290,9 @@ class BusService {
11793
12290
  this._eventWildcardMap.set(source, true);
11794
12291
  }
11795
12292
  this._eventSourceSet.add(source);
11796
- return this.getEventSubject(clientId, source).filter(filterFn).once(fn);
12293
+ return this.getEventSubject(clientId, source)
12294
+ .filter(filterFn)
12295
+ .once(GUARD_LISTENER_FN(fn, clientId, source));
11797
12296
  };
11798
12297
  /**
11799
12298
  * Emits an event for a specific client, broadcasting to subscribers of the event’s source, including wildcard subscribers.
@@ -12758,7 +13257,7 @@ class DocService {
12758
13257
  }
12759
13258
  {
12760
13259
  result.push("");
12761
- result.push(`*Required:* [${fn.parameters.required.includes(key) ? "x" : " "}]`);
13260
+ result.push(`*Required:* [${fn.parameters.required?.includes(key) ? "x" : " "}]`);
12762
13261
  }
12763
13262
  });
12764
13263
  if (!entries.length) {
@@ -13599,7 +14098,7 @@ class MemorySchemaService {
13599
14098
  * console.log(msToTime(3600000)); // "01:00:00.0"
13600
14099
  * console.log(msToTime(61000)); // "00:01:01.0"
13601
14100
  * console.log(msToTime(500)); // "00:00:00.500"
13602
- * console.log(msToTime(0)); // ""
14101
+ * console.log(msToTime(0)); // "00:00:00.0"
13603
14102
  *
13604
14103
  * @example
13605
14104
  * // Edge cases
@@ -13611,8 +14110,7 @@ class MemorySchemaService {
13611
14110
  * - Breaks down milliseconds into hours, minutes, seconds, and remaining milliseconds using integer division and modulo operations.
13612
14111
  * - Pads hours, minutes, and seconds with leading zeros if they are single-digit (e.g., "5" becomes "05").
13613
14112
  * - Includes milliseconds with no leading zeros, fixed to zero decimal places for simplicity (e.g., "500" not "500.0").
13614
- * - Omits leading components (hours or minutes) if they are zero, but always includes seconds and milliseconds if any time is present.
13615
- * - Returns an empty string for an input of 0, treating it as no duration.
14113
+ * - Always includes all components, so an input of 0 yields "00:00:00.0".
13616
14114
  * Useful in the agent swarm system for logging execution times, profiling operations, or displaying human-readable durations.
13617
14115
  *
13618
14116
  * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed|Number.toFixed}
@@ -14452,6 +14950,15 @@ class ClientPolicy {
14452
14950
  * Updated by banClient and unbanClient, persisted if params.setBannedClients is provided.
14453
14951
  */
14454
14952
  this._banSet = BAN_NEED_FETCH;
14953
+ /**
14954
+ * Serializes the read-modify-write of _banSet shared by banClient/unbanClient.
14955
+ * Without it two concurrent bans of different clients both read the same ban
14956
+ * set, each adds only its own client, and the later setBannedClients overwrites
14957
+ * the earlier one — one ban is silently lost in memory and in the persisted
14958
+ * store. queued() runs the mutations one at a time so each observes the result
14959
+ * of the previous one.
14960
+ */
14961
+ this._banQueue = functoolsKit.queued(async (fn) => await fn());
14455
14962
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_DEBUG &&
14456
14963
  this.params.logger.debug(`ClientPolicy policyName=${this.params.policyName} CTOR`, {
14457
14964
  params,
@@ -14609,16 +15116,18 @@ class ClientPolicy {
14609
15116
  },
14610
15117
  clientId,
14611
15118
  });
14612
- if (this._banSet === BAN_NEED_FETCH) {
14613
- this._banSet = new Set(await this.params.getBannedClients(this.params.policyName, swarmName));
14614
- }
14615
- if (this._banSet.has(clientId)) {
14616
- return;
14617
- }
14618
- this._banSet = new Set(this._banSet).add(clientId);
14619
- if (this.params.setBannedClients) {
14620
- await this.params.setBannedClients([...this._banSet], this.params.policyName, swarmName);
14621
- }
15119
+ await this._banQueue(async () => {
15120
+ if (this._banSet === BAN_NEED_FETCH) {
15121
+ this._banSet = new Set(await this.params.getBannedClients(this.params.policyName, swarmName));
15122
+ }
15123
+ if (this._banSet.has(clientId)) {
15124
+ return;
15125
+ }
15126
+ this._banSet = new Set(this._banSet).add(clientId);
15127
+ if (this.params.setBannedClients) {
15128
+ await this.params.setBannedClients([...this._banSet], this.params.policyName, swarmName);
15129
+ }
15130
+ });
14622
15131
  }
14623
15132
  /**
14624
15133
  * Unbans a client, removing them from the ban set and persisting the change if params.setBannedClients is provided.
@@ -14645,20 +15154,22 @@ class ClientPolicy {
14645
15154
  },
14646
15155
  clientId,
14647
15156
  });
14648
- if (this._banSet === BAN_NEED_FETCH) {
14649
- this._banSet = new Set(await this.params.getBannedClients(this.params.policyName, swarmName));
14650
- }
14651
- if (!this._banSet.has(clientId)) {
14652
- return;
14653
- }
14654
- {
14655
- const banSet = new Set(this._banSet);
14656
- banSet.delete(clientId);
14657
- this._banSet = banSet;
14658
- }
14659
- if (this.params.setBannedClients) {
14660
- await this.params.setBannedClients([...this._banSet], this.params.policyName, swarmName);
14661
- }
15157
+ await this._banQueue(async () => {
15158
+ if (this._banSet === BAN_NEED_FETCH) {
15159
+ this._banSet = new Set(await this.params.getBannedClients(this.params.policyName, swarmName));
15160
+ }
15161
+ if (!this._banSet.has(clientId)) {
15162
+ return;
15163
+ }
15164
+ {
15165
+ const banSet = new Set(this._banSet);
15166
+ banSet.delete(clientId);
15167
+ this._banSet = banSet;
15168
+ }
15169
+ if (this.params.setBannedClients) {
15170
+ await this.params.setBannedClients([...this._banSet], this.params.policyName, swarmName);
15171
+ }
15172
+ });
14662
15173
  }
14663
15174
  }
14664
15175
 
@@ -15131,7 +15642,16 @@ class ClientMCP {
15131
15642
  if (this.params.callbacks?.onList) {
15132
15643
  this.params.callbacks.onList(clientId);
15133
15644
  }
15134
- const toolMap = await this.fetchTools(clientId);
15645
+ let toolMap;
15646
+ try {
15647
+ toolMap = await this.fetchTools(clientId);
15648
+ }
15649
+ catch (error) {
15650
+ // Never cache a rejected fetch: the memoized promise would keep this
15651
+ // client permanently broken even after the MCP recovers.
15652
+ this.fetchTools.clear(clientId);
15653
+ throw error;
15654
+ }
15135
15655
  return Array.from(toolMap.values());
15136
15656
  }
15137
15657
  /**
@@ -15143,7 +15663,14 @@ class ClientMCP {
15143
15663
  toolName,
15144
15664
  clientId,
15145
15665
  });
15146
- const toolMap = await this.fetchTools(clientId);
15666
+ let toolMap;
15667
+ try {
15668
+ toolMap = await this.fetchTools(clientId);
15669
+ }
15670
+ catch (error) {
15671
+ this.fetchTools.clear(clientId);
15672
+ throw error;
15673
+ }
15147
15674
  return toolMap.has(toolName);
15148
15675
  }
15149
15676
  /**
@@ -15229,12 +15756,13 @@ class MCPConnectionService {
15229
15756
  this.dispose = async (clientId) => {
15230
15757
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_INFO &&
15231
15758
  this.loggerService.info(`mcpConnectionService dispose`, { clientId });
15232
- const key = `${this.methodContextService.context.clientId}-${this.methodContextService.context.agentName}`;
15759
+ const key = `${this.methodContextService.context.mcpName}`;
15233
15760
  if (!this.getMCP.has(key)) {
15234
15761
  return;
15235
15762
  }
15763
+ // The ClientMCP instance is shared across clients (memoized by mcpName),
15764
+ // so only the client-scoped resources are released; the instance stays cached.
15236
15765
  await this.getMCP(this.methodContextService.context.mcpName).dispose(clientId);
15237
- this.getMCP.clear(clientId);
15238
15766
  };
15239
15767
  }
15240
15768
  /**
@@ -16132,7 +16660,7 @@ class SharedComputeConnectionService {
16132
16660
  * @throws {Error} If the compute is not marked as shared.
16133
16661
  */
16134
16662
  this.getComputeRef = functoolsKit.memoize(([computeName]) => `${computeName}`, (computeName) => {
16135
- const { getComputeData, dependsOn, middlewares = [], callbacks, shared = false, } = this.computeSchemaService.get(computeName);
16663
+ const { getComputeData, dependsOn = [], middlewares = [], callbacks, shared = false, } = this.computeSchemaService.get(computeName);
16136
16664
  if (!shared) {
16137
16665
  throw new Error(`agent-swarm compute not shared computeName=${computeName}`);
16138
16666
  }
@@ -17115,14 +17643,14 @@ const swarm = {
17115
17643
  init();
17116
17644
  var swarm$1 = swarm;
17117
17645
 
17118
- const METHOD_NAME$1E = "cli.dumpDocs";
17646
+ const METHOD_NAME$1F = "cli.dumpDocs";
17119
17647
  /**
17120
17648
  * Dumps the documentation for the agents and swarms.
17121
17649
  *
17122
17650
  */
17123
17651
  const dumpDocs = beginContext((prefix = "swarm", dirName = "./docs/chat", PlantUML, sanitizeMarkdown = (t) => t) => {
17124
17652
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17125
- swarm$1.loggerService.log(METHOD_NAME$1E, {
17653
+ swarm$1.loggerService.log(METHOD_NAME$1F, {
17126
17654
  dirName,
17127
17655
  });
17128
17656
  if (PlantUML) {
@@ -17132,10 +17660,10 @@ const dumpDocs = beginContext((prefix = "swarm", dirName = "./docs/chat", PlantU
17132
17660
  }
17133
17661
  swarm$1.agentValidationService
17134
17662
  .getAgentList()
17135
- .forEach((agentName) => swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1E));
17663
+ .forEach((agentName) => swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1F));
17136
17664
  swarm$1.swarmValidationService
17137
17665
  .getSwarmList()
17138
- .forEach((swarmName) => swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1E));
17666
+ .forEach((swarmName) => swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1F));
17139
17667
  swarm$1.agentValidationService.getAgentList().forEach((agentName) => {
17140
17668
  const { dependsOn } = swarm$1.agentSchemaService.get(agentName);
17141
17669
  if (!dependsOn) {
@@ -17144,39 +17672,39 @@ const dumpDocs = beginContext((prefix = "swarm", dirName = "./docs/chat", PlantU
17144
17672
  });
17145
17673
  swarm$1.outlineValidationService
17146
17674
  .getOutlineList()
17147
- .forEach((swarmName) => swarm$1.outlineValidationService.validate(swarmName, METHOD_NAME$1E));
17675
+ .forEach((swarmName) => swarm$1.outlineValidationService.validate(swarmName, METHOD_NAME$1F));
17148
17676
  return swarm$1.docService.dumpDocs(prefix, dirName, sanitizeMarkdown);
17149
17677
  });
17150
17678
 
17151
- const METHOD_NAME$1D = "cli.dumpAgent";
17679
+ const METHOD_NAME$1E = "cli.dumpAgent";
17152
17680
  /**
17153
17681
  * Dumps the agent information into PlantUML format.
17154
17682
  *
17155
17683
  */
17156
17684
  const dumpAgent = beginContext((agentName, { withSubtree = false } = {}) => {
17157
17685
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17158
- swarm$1.loggerService.log(METHOD_NAME$1D, {
17686
+ swarm$1.loggerService.log(METHOD_NAME$1E, {
17159
17687
  agentName,
17160
17688
  });
17161
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1D);
17689
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1E);
17162
17690
  return swarm$1.agentMetaService.toUML(agentName, withSubtree);
17163
17691
  });
17164
17692
 
17165
- const METHOD_NAME$1C = "cli.dumpSwarm";
17693
+ const METHOD_NAME$1D = "cli.dumpSwarm";
17166
17694
  /**
17167
17695
  * Dumps the swarm information into PlantUML format.
17168
17696
  *
17169
17697
  */
17170
17698
  const dumpSwarm = beginContext((swarmName) => {
17171
17699
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17172
- swarm$1.loggerService.log(METHOD_NAME$1C, {
17700
+ swarm$1.loggerService.log(METHOD_NAME$1D, {
17173
17701
  swarmName,
17174
17702
  });
17175
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1C);
17703
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1D);
17176
17704
  return swarm$1.swarmMetaService.toUML(swarmName);
17177
17705
  });
17178
17706
 
17179
- const METHOD_NAME$1B = "cli.dumpPerfomance";
17707
+ const METHOD_NAME$1C = "cli.dumpPerfomance";
17180
17708
  const METHOD_NAME_INTERNAL$1 = "cli.dumpPerfomance.internal";
17181
17709
  const METHOD_NAME_INTERVAL = "cli.dumpPerfomance.interval";
17182
17710
  /**
@@ -17193,7 +17721,7 @@ const dumpPerfomanceInternal = beginContext(async (dirName = "./dump/agent/meta"
17193
17721
  *
17194
17722
  */
17195
17723
  const dumpPerfomance = async (dirName = "./dump/agent/meta") => {
17196
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1B);
17724
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1C);
17197
17725
  await dumpPerfomanceInternal(dirName);
17198
17726
  };
17199
17727
  /**
@@ -17242,10 +17770,19 @@ const listenExecutionEvent = beginContext((clientId, fn) => {
17242
17770
  // Validate the client ID
17243
17771
  validateClientId$h(clientId);
17244
17772
  // Subscribe to execution events with a queued callback
17245
- return swarm$1.busService.subscribe(clientId, "execution-bus", functoolsKit.queued(async (e) => await fn(e)));
17773
+ return swarm$1.busService.subscribe(clientId, "execution-bus", functoolsKit.queued(async (e) => {
17774
+ try {
17775
+ // A throwing listener must not reject the queued chain: that surfaces
17776
+ // as an unhandled rejection and can crash the host process.
17777
+ return await fn(e);
17778
+ }
17779
+ catch (error) {
17780
+ console.error(`agent-swarm event listener error source=listenExecutionEvent error=${functoolsKit.getErrorMessage(error)}`);
17781
+ }
17782
+ }));
17246
17783
  });
17247
17784
 
17248
- const METHOD_NAME$1A = "cli.dumpClientPerformance";
17785
+ const METHOD_NAME$1B = "cli.dumpClientPerformance";
17249
17786
  const METHOD_NAME_INTERNAL = "cli.dumpClientPerformance.internal";
17250
17787
  const METHOD_NAME_EXECUTE = "cli.dumpClientPerformance.execute";
17251
17788
  /**
@@ -17263,7 +17800,7 @@ const dumpClientPerformanceInternal = beginContext(async (clientId, dirName = ".
17263
17800
  *
17264
17801
  */
17265
17802
  const dumpClientPerformance = async (clientId, dirName = "./dump/agent/client") => {
17266
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1A);
17803
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1B);
17267
17804
  await dumpClientPerformanceInternal(clientId, dirName);
17268
17805
  };
17269
17806
  /**
@@ -17411,24 +17948,24 @@ const dumpAdvisorResult = async (resultId, content) => {
17411
17948
  };
17412
17949
 
17413
17950
  /** @private Constant defining the method name for logging and validation context*/
17414
- const METHOD_NAME$1z = "function.commit.commitFlushForce";
17951
+ const METHOD_NAME$1A = "function.commit.commitFlushForce";
17415
17952
  /**
17416
17953
  * Function implementation
17417
17954
  */
17418
17955
  const commitFlushForceInternal = beginContext(async (clientId) => {
17419
17956
  // Log the flush attempt if enabled
17420
17957
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17421
- swarm$1.loggerService.log(METHOD_NAME$1z, {
17958
+ swarm$1.loggerService.log(METHOD_NAME$1A, {
17422
17959
  clientId,
17423
- METHOD_NAME: METHOD_NAME$1z,
17960
+ METHOD_NAME: METHOD_NAME$1A,
17424
17961
  });
17425
17962
  // Validate the session exists and retrieve the associated swarm
17426
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1z);
17963
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1A);
17427
17964
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17428
17965
  // Validate the swarm configuration
17429
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1z);
17966
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1A);
17430
17967
  // Commit the flush of agent history via SessionPublicService without agent checks
17431
- await swarm$1.sessionPublicService.commitFlush(METHOD_NAME$1z, clientId, swarmName);
17968
+ await swarm$1.sessionPublicService.commitFlush(METHOD_NAME$1A, clientId, swarmName);
17432
17969
  });
17433
17970
  /**
17434
17971
  * Forcefully commits a flush of agent history for a specific client in the swarm system, without checking the active agent.
@@ -17447,24 +17984,24 @@ async function commitFlushForce(clientId) {
17447
17984
  return await commitFlushForceInternal(clientId);
17448
17985
  }
17449
17986
 
17450
- const METHOD_NAME$1y = "function.commit.commitToolOutputForce";
17987
+ const METHOD_NAME$1z = "function.commit.commitToolOutputForce";
17451
17988
  /**
17452
17989
  * Function implementation
17453
17990
  */
17454
17991
  const commitToolOutputForceInternal = beginContext(async (toolId, content, clientId) => {
17455
17992
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17456
17993
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17457
- swarm$1.loggerService.log(METHOD_NAME$1y, {
17994
+ swarm$1.loggerService.log(METHOD_NAME$1z, {
17458
17995
  toolId,
17459
17996
  content,
17460
17997
  clientId,
17461
17998
  });
17462
17999
  // Validate the session and swarm to ensure they exist and are accessible
17463
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1y);
18000
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1z);
17464
18001
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17465
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1y);
18002
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1z);
17466
18003
  // Commit the tool output to the session via the session public service without checking the active agent
17467
- await swarm$1.sessionPublicService.commitToolOutput(toolId, content, METHOD_NAME$1y, clientId, swarmName);
18004
+ await swarm$1.sessionPublicService.commitToolOutput(toolId, content, METHOD_NAME$1z, clientId, swarmName);
17468
18005
  });
17469
18006
  /**
17470
18007
  * Commits the output of a tool execution to the active agent in a swarm session without checking the active agent.
@@ -17489,15 +18026,15 @@ async function commitToolOutputForce(toolId, content, clientId) {
17489
18026
  * @private Constant defining the method name for logging and validation purposes.
17490
18027
  * Used as an identifier in log messages and validation checks to track calls to `hasNavigation`.
17491
18028
  */
17492
- const METHOD_NAME$1x = "function.common.hasNavigation";
18029
+ const METHOD_NAME$1y = "function.common.hasNavigation";
17493
18030
  /**
17494
18031
  * Function implementation
17495
18032
  */
17496
18033
  const hasNavigationInternal = async (clientId, agentName) => {
17497
18034
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17498
- swarm$1.loggerService.log(METHOD_NAME$1x, { clientId });
17499
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1x);
17500
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1x);
18035
+ swarm$1.loggerService.log(METHOD_NAME$1y, { clientId });
18036
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1y);
18037
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1y);
17501
18038
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17502
18039
  return swarm$1.navigationValidationService
17503
18040
  .getNavigationRoute(clientId, swarmName)
@@ -17514,14 +18051,14 @@ async function hasNavigation(clientId, agentName) {
17514
18051
  return await hasNavigationInternal(clientId, agentName);
17515
18052
  }
17516
18053
 
17517
- const METHOD_NAME$1w = "function.history.getRawHistory";
18054
+ const METHOD_NAME$1x = "function.history.getRawHistory";
17518
18055
  /**
17519
18056
  * Function implementation
17520
18057
  */
17521
18058
  const getRawHistoryInternal = beginContext(async (clientId, methodName) => {
17522
18059
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17523
18060
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17524
- swarm$1.loggerService.log(METHOD_NAME$1w, {
18061
+ swarm$1.loggerService.log(METHOD_NAME$1x, {
17525
18062
  clientId,
17526
18063
  });
17527
18064
  // Validate the session and swarm
@@ -17549,21 +18086,21 @@ const getRawHistoryInternal = beginContext(async (clientId, methodName) => {
17549
18086
  * console.log(rawHistory); // Outputs the full raw history array
17550
18087
  */
17551
18088
  async function getRawHistory(clientId) {
17552
- return await getRawHistoryInternal(clientId, METHOD_NAME$1w);
18089
+ return await getRawHistoryInternal(clientId, METHOD_NAME$1x);
17553
18090
  }
17554
18091
 
17555
- const METHOD_NAME$1v = "function.history.getLastUserMessage";
18092
+ const METHOD_NAME$1w = "function.history.getLastUserMessage";
17556
18093
  /**
17557
18094
  * Function implementation
17558
18095
  */
17559
18096
  const getLastUserMessageInternal = beginContext(async (clientId) => {
17560
18097
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17561
18098
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17562
- swarm$1.loggerService.log(METHOD_NAME$1v, {
18099
+ swarm$1.loggerService.log(METHOD_NAME$1w, {
17563
18100
  clientId,
17564
18101
  });
17565
18102
  // Fetch raw history and find the last user message
17566
- const history = await getRawHistoryInternal(clientId, METHOD_NAME$1v);
18103
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$1w);
17567
18104
  const last = history.findLast(({ role, mode }) => role === "user" && mode === "user");
17568
18105
  return last?.content ? last.content : null;
17569
18106
  });
@@ -17585,7 +18122,7 @@ async function getLastUserMessage(clientId) {
17585
18122
  return await getLastUserMessageInternal(clientId);
17586
18123
  }
17587
18124
 
17588
- const METHOD_NAME$1u = "function.navigate.changeToDefaultAgent";
18125
+ const METHOD_NAME$1v = "function.navigate.changeToDefaultAgent";
17589
18126
  /**
17590
18127
  * Creates a change agent function with time-to-live (TTL) and queuing capabilities for switching to the default agent.
17591
18128
  *
@@ -17606,7 +18143,7 @@ const createChangeToDefaultAgent = functoolsKit.memoize(([clientId]) => `${clien
17606
18143
  }));
17607
18144
  {
17608
18145
  // Dispose of the current agent's resources and set up the new default agent
17609
- const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1u, clientId, swarmName);
18146
+ const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1v, clientId, swarmName);
17610
18147
  await swarm$1.agentPublicService.dispose(methodName, clientId, agentName);
17611
18148
  await swarm$1.historyPublicService.dispose(methodName, clientId, agentName);
17612
18149
  await swarm$1.swarmPublicService.setAgentRef(methodName, clientId, swarmName, agentName, await swarm$1.agentPublicService.createAgentRef(methodName, clientId, agentName));
@@ -17633,20 +18170,20 @@ const createGc$3 = functoolsKit.singleshot(async () => {
17633
18170
  const changeToDefaultAgentInternal = beginContext(async (clientId) => {
17634
18171
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17635
18172
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17636
- swarm$1.loggerService.log(METHOD_NAME$1u, {
18173
+ swarm$1.loggerService.log(METHOD_NAME$1v, {
17637
18174
  clientId,
17638
18175
  });
17639
18176
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17640
18177
  const { defaultAgent: agentName } = swarm$1.swarmSchemaService.get(swarmName);
17641
18178
  {
17642
18179
  // Validate session and default agent
17643
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1u);
17644
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1u);
18180
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1v);
18181
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1v);
17645
18182
  }
17646
18183
  // Execute the agent change with TTL and queuing
17647
18184
  const run = await createChangeToDefaultAgent(clientId);
17648
18185
  createGc$3();
17649
- return await run(METHOD_NAME$1u, agentName, swarmName);
18186
+ return await run(METHOD_NAME$1v, agentName, swarmName);
17650
18187
  });
17651
18188
  /**
17652
18189
  * Navigates back to the default agent for a given client session in a swarm.
@@ -17665,44 +18202,44 @@ async function changeToDefaultAgent(clientId) {
17665
18202
  return await changeToDefaultAgentInternal(clientId);
17666
18203
  }
17667
18204
 
17668
- const METHOD_NAME$1t = "function.target.emitForce";
18205
+ const METHOD_NAME$1u = "function.target.emitForce";
17669
18206
  /**
17670
18207
  * Function implementation
17671
18208
  */
17672
18209
  const emitForceInternal = beginContext(async (content, clientId) => {
17673
18210
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17674
18211
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17675
- swarm$1.loggerService.log(METHOD_NAME$1t, {
18212
+ swarm$1.loggerService.log(METHOD_NAME$1u, {
17676
18213
  content,
17677
18214
  clientId,
17678
18215
  });
17679
18216
  // Validate the session and swarm
17680
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1t);
18217
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1u);
17681
18218
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17682
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1t);
18219
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1u);
17683
18220
  // Emit the content directly via the session public service
17684
- return await swarm$1.sessionPublicService.emit(content, METHOD_NAME$1t, clientId, swarmName);
18221
+ return await swarm$1.sessionPublicService.emit(content, METHOD_NAME$1u, clientId, swarmName);
17685
18222
  });
17686
18223
  /**
17687
18224
  * Emits a string as model output without executing an incoming message or checking the active agent.
17688
18225
  *
17689
18226
  * This function directly emits a provided string as output from the swarm session, bypassing message execution and agent activity checks.
17690
- * It is designed exclusively for sessions established via `makeConnection`, ensuring compatibility with its connection model.
17691
- * The execution is wrapped in `beginContext` for a clean environment, validates the session and swarm, and throws an error if the session mode
17692
- * is not "makeConnection". The operation is logged if enabled, and resolves when the content is successfully emitted.
18227
+ * Unlike `emit`, it does not verify that a specific agent is still active, ensuring emission even after navigation.
18228
+ * The execution is wrapped in `beginContext` for a clean environment, validates the session and swarm,
18229
+ * logs the operation if enabled, and resolves when the content is successfully emitted. Works for any session mode.
17693
18230
  *
17694
18231
  *
17695
18232
  * @param {string} content - The content to be processed or stored.
17696
18233
  * @param {string} clientId - The unique identifier of the client session.
17697
- * @throws {Error} If the session mode is not "makeConnection", or if session or swarm validation fails.
18234
+ * @throws {Error} If session or swarm validation fails.
17698
18235
  * @example
17699
- * await emitForce("Direct output", "client-123"); // Emits "Direct output" in a makeConnection session
18236
+ * await emitForce("Direct output", "client-123"); // Emits "Direct output" regardless of the active agent
17700
18237
  */
17701
18238
  async function emitForce(content, clientId) {
17702
18239
  return await emitForceInternal(content, clientId);
17703
18240
  }
17704
18241
 
17705
- const METHOD_NAME$1s = "function.target.executeForce";
18242
+ const METHOD_NAME$1t = "function.target.executeForce";
17706
18243
  /**
17707
18244
  * Function implementation
17708
18245
  */
@@ -17710,15 +18247,15 @@ const executeForceInternal = beginContext(async (content, clientId) => {
17710
18247
  const executionId = functoolsKit.randomString();
17711
18248
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17712
18249
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17713
- swarm$1.loggerService.log(METHOD_NAME$1s, {
18250
+ swarm$1.loggerService.log(METHOD_NAME$1t, {
17714
18251
  content,
17715
18252
  clientId,
17716
18253
  executionId,
17717
18254
  });
17718
18255
  // Validate the session and swarm
17719
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1s);
18256
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1t);
17720
18257
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17721
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1s);
18258
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1t);
17722
18259
  // Execute the command within an execution context with performance tracking
17723
18260
  return ExecutionContextService.runInContext(async () => {
17724
18261
  let isFinished = false;
@@ -17732,7 +18269,7 @@ const executeForceInternal = beginContext(async (content, clientId) => {
17732
18269
  errorValue = error;
17733
18270
  }
17734
18271
  });
17735
- result = await swarm$1.sessionPublicService.execute(content, "tool", METHOD_NAME$1s, clientId, swarmName);
18272
+ result = await swarm$1.sessionPublicService.execute(content, "tool", METHOD_NAME$1t, clientId, swarmName);
17736
18273
  unError();
17737
18274
  if (errorValue) {
17738
18275
  throw errorValue;
@@ -17774,24 +18311,24 @@ async function executeForce(content, clientId) {
17774
18311
  }
17775
18312
 
17776
18313
  /** @private Constant defining the method name for logging and validation context*/
17777
- const METHOD_NAME$1r = "function.commit.commitStopToolsForce";
18314
+ const METHOD_NAME$1s = "function.commit.commitStopToolsForce";
17778
18315
  /**
17779
18316
  * Function implementation
17780
18317
  */
17781
18318
  const commitStopToolsForceInternal = beginContext(async (clientId) => {
17782
18319
  // Log the stop tools attempt if enabled
17783
18320
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17784
- swarm$1.loggerService.log(METHOD_NAME$1r, {
18321
+ swarm$1.loggerService.log(METHOD_NAME$1s, {
17785
18322
  clientId,
17786
- METHOD_NAME: METHOD_NAME$1r,
18323
+ METHOD_NAME: METHOD_NAME$1s,
17787
18324
  });
17788
18325
  // Validate the session exists and retrieve the associated swarm
17789
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1r);
18326
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1s);
17790
18327
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17791
18328
  // Validate the swarm configuration
17792
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1r);
18329
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$1s);
17793
18330
  // Commit the stop of the next tool execution via SessionPublicService without agent checks
17794
- await swarm$1.sessionPublicService.commitStopTools(METHOD_NAME$1r, clientId, swarmName);
18331
+ await swarm$1.sessionPublicService.commitStopTools(METHOD_NAME$1s, clientId, swarmName);
17795
18332
  });
17796
18333
  /**
17797
18334
  * Forcefully prevents the next tool from being executed for a specific client in the swarm system, without checking the active agent.
@@ -17810,7 +18347,7 @@ async function commitStopToolsForce(clientId) {
17810
18347
  return await commitStopToolsForceInternal(clientId);
17811
18348
  }
17812
18349
 
17813
- const METHOD_NAME$1q = "function.template.navigateToTriageAgent";
18350
+ const METHOD_NAME$1r = "function.template.navigateToTriageAgent";
17814
18351
  /**
17815
18352
  * Will send tool output directly to the model without any additions
17816
18353
  */
@@ -17852,7 +18389,7 @@ const createNavigateToTriageAgent = ({ flushMessage, beforeNavigate, lastMessage
17852
18389
  */
17853
18390
  return beginContext(async (toolId, clientId) => {
17854
18391
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17855
- swarm$1.loggerService.log(METHOD_NAME$1q, {
18392
+ swarm$1.loggerService.log(METHOD_NAME$1r, {
17856
18393
  clientId,
17857
18394
  toolId,
17858
18395
  });
@@ -17866,7 +18403,7 @@ const createNavigateToTriageAgent = ({ flushMessage, beforeNavigate, lastMessage
17866
18403
  beforeNavigate && await beforeNavigate(clientId, lastMessage, lastAgent, defaultAgent);
17867
18404
  await commitToolOutputForce(toolId, typeof toolOutputAccept === "string"
17868
18405
  ? toolOutputAccept
17869
- : await toolOutputAccept(clientId, lastAgent), clientId);
18406
+ : await toolOutputAccept(clientId, defaultAgent), clientId);
17870
18407
  await changeToDefaultAgent(clientId);
17871
18408
  await executeForce(lastMessage, clientId);
17872
18409
  return;
@@ -17887,7 +18424,7 @@ const createNavigateToTriageAgent = ({ flushMessage, beforeNavigate, lastMessage
17887
18424
  });
17888
18425
  };
17889
18426
 
17890
- const METHOD_NAME$1p = "function.navigate.changeToAgent";
18427
+ const METHOD_NAME$1q = "function.navigate.changeToAgent";
17891
18428
  /**
17892
18429
  * Creates a change agent function with time-to-live (TTL) and queuing capabilities.
17893
18430
  *
@@ -17909,7 +18446,7 @@ const createChangeToAgent = functoolsKit.memoize(([clientId]) => `${clientId}`,
17909
18446
  }));
17910
18447
  {
17911
18448
  // Dispose of the current agent's resources and set up the new agent
17912
- const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1p, clientId, swarmName);
18449
+ const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1q, clientId, swarmName);
17913
18450
  await swarm$1.agentPublicService.dispose(methodName, clientId, agentName);
17914
18451
  await swarm$1.historyPublicService.dispose(methodName, clientId, agentName);
17915
18452
  await swarm$1.swarmPublicService.setAgentRef(methodName, clientId, swarmName, agentName, await swarm$1.agentPublicService.createAgentRef(methodName, clientId, agentName));
@@ -17936,16 +18473,16 @@ const createGc$2 = functoolsKit.singleshot(async () => {
17936
18473
  const changeToAgentInternal = beginContext(async (agentName, clientId) => {
17937
18474
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
17938
18475
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
17939
- swarm$1.loggerService.log(METHOD_NAME$1p, {
18476
+ swarm$1.loggerService.log(METHOD_NAME$1q, {
17940
18477
  agentName,
17941
18478
  clientId,
17942
18479
  });
17943
18480
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
17944
18481
  {
17945
18482
  // Validate session, agent, and dependencies
17946
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1p);
17947
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1p);
17948
- const activeAgent = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1p, clientId, swarmName);
18483
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$1q);
18484
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$1q);
18485
+ const activeAgent = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1q, clientId, swarmName);
17949
18486
  if (!swarm$1.agentValidationService.hasDependency(activeAgent, agentName)) {
17950
18487
  console.error(`agent-swarm missing dependency detected for activeAgent=${activeAgent} dependencyAgent=${agentName}`);
17951
18488
  }
@@ -17963,7 +18500,7 @@ const changeToAgentInternal = beginContext(async (agentName, clientId) => {
17963
18500
  // Execute the agent change with TTL and queuing
17964
18501
  const run = await createChangeToAgent(clientId);
17965
18502
  createGc$2();
17966
- return await run(METHOD_NAME$1p, agentName, swarmName);
18503
+ return await run(METHOD_NAME$1q, agentName, swarmName);
17967
18504
  });
17968
18505
  /**
17969
18506
  * Changes the active agent for a given client session in a swarm.
@@ -17983,7 +18520,7 @@ async function changeToAgent(agentName, clientId) {
17983
18520
  return await changeToAgentInternal(agentName, clientId);
17984
18521
  }
17985
18522
 
17986
- const METHOD_NAME$1o = "function.template.navigateToAgent";
18523
+ const METHOD_NAME$1p = "function.template.navigateToAgent";
17987
18524
  /**
17988
18525
  * Will send tool output directly to the model without any additions
17989
18526
  */
@@ -18039,7 +18576,7 @@ const createNavigateToAgent = ({ beforeNavigate, lastMessage: lastMessageFn = DE
18039
18576
  */
18040
18577
  return beginContext(async (toolId, clientId, agentName) => {
18041
18578
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18042
- swarm$1.loggerService.log(METHOD_NAME$1o, {
18579
+ swarm$1.loggerService.log(METHOD_NAME$1p, {
18043
18580
  clientId,
18044
18581
  toolId,
18045
18582
  });
@@ -18077,7 +18614,7 @@ const createNavigateToAgent = ({ beforeNavigate, lastMessage: lastMessageFn = DE
18077
18614
  });
18078
18615
  };
18079
18616
 
18080
- const METHOD_NAME$1n = "function.template.commitAction";
18617
+ const METHOD_NAME$1o = "function.template.commitAction";
18081
18618
  /**
18082
18619
  * Creates a commit action handler that executes actions and modifies system state (WRITE pattern).
18083
18620
  *
@@ -18126,7 +18663,7 @@ const createCommitAction = ({ validateParams, executeAction, emptyContent, fallb
18126
18663
  return beginContext(async (toolId, clientId, agentName, toolName, params, toolCalls, isLast) => {
18127
18664
  let executeMessage = "";
18128
18665
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18129
- swarm$1.loggerService.log(METHOD_NAME$1n, {
18666
+ swarm$1.loggerService.log(METHOD_NAME$1o, {
18130
18667
  clientId,
18131
18668
  toolId,
18132
18669
  agentName,
@@ -18220,7 +18757,7 @@ const createCommitAction = ({ validateParams, executeAction, emptyContent, fallb
18220
18757
  });
18221
18758
  };
18222
18759
 
18223
- const METHOD_NAME$1m = "function.template.fetchInfo";
18760
+ const METHOD_NAME$1n = "function.template.fetchInfo";
18224
18761
  /**
18225
18762
  * Default message when content is empty.
18226
18763
  */
@@ -18266,7 +18803,7 @@ const createFetchInfo = ({ fetchContent, fallback, emptyContent = DEFAULT_EMPTY_
18266
18803
  return beginContext(async (toolId, clientId, agentName, toolName, params, isLast) => {
18267
18804
  let executeMessage = "";
18268
18805
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18269
- swarm$1.loggerService.log(METHOD_NAME$1m, {
18806
+ swarm$1.loggerService.log(METHOD_NAME$1n, {
18270
18807
  clientId,
18271
18808
  toolId,
18272
18809
  agentName,
@@ -18277,7 +18814,7 @@ const createFetchInfo = ({ fetchContent, fallback, emptyContent = DEFAULT_EMPTY_
18277
18814
  const currentAgentName = await getAgentName(clientId);
18278
18815
  if (currentAgentName !== agentName) {
18279
18816
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18280
- swarm$1.loggerService.log(`${METHOD_NAME$1m} skipped due to agent change`, {
18817
+ swarm$1.loggerService.log(`${METHOD_NAME$1n} skipped due to agent change`, {
18281
18818
  currentAgentName,
18282
18819
  agentName,
18283
18820
  clientId,
@@ -18312,14 +18849,14 @@ const createFetchInfo = ({ fetchContent, fallback, emptyContent = DEFAULT_EMPTY_
18312
18849
  });
18313
18850
  };
18314
18851
 
18315
- const METHOD_NAME$1l = "function.setup.addTool";
18852
+ const METHOD_NAME$1m = "function.setup.addTool";
18316
18853
  /**
18317
18854
  * Function implementation
18318
18855
  */
18319
18856
  const addToolInternal = beginContext((toolSchema) => {
18320
18857
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18321
18858
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18322
- swarm$1.loggerService.log(METHOD_NAME$1l, {
18859
+ swarm$1.loggerService.log(METHOD_NAME$1m, {
18323
18860
  toolSchema,
18324
18861
  });
18325
18862
  // Register the tool in the validation and schema services
@@ -18353,12 +18890,12 @@ function addTool(toolSchema) {
18353
18890
  * Adds navigation functionality to an agent by creating a tool that allows navigation to a specified agent.
18354
18891
  * @module addAgentNavigation
18355
18892
  */
18356
- const METHOD_NAME$1k = "function.alias.addAgentNavigation";
18893
+ const METHOD_NAME$1l = "function.alias.addAgentNavigation";
18357
18894
  /**
18358
18895
  * Function implementation
18359
18896
  */
18360
18897
  const addAgentNavigationInternal = beginContext(({ toolName, docNote, description, navigateTo, isAvailable, ...navigateProps }) => {
18361
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1k);
18898
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1l);
18362
18899
  const navigate = createNavigateToAgent(navigateProps);
18363
18900
  const toolSchema = addTool({
18364
18901
  toolName,
@@ -18397,12 +18934,12 @@ function addAgentNavigation(params) {
18397
18934
  * Adds triage navigation functionality to an agent by creating a tool that facilitates navigation to a triage agent.
18398
18935
  * @module addTriageNavigation
18399
18936
  */
18400
- const METHOD_NAME$1j = "function.alias.addTriageNavigation";
18937
+ const METHOD_NAME$1k = "function.alias.addTriageNavigation";
18401
18938
  /**
18402
18939
  * Function implementation
18403
18940
  */
18404
18941
  const addTriageNavigationInternal = beginContext(({ toolName, docNote, description, isAvailable, ...navigateProps }) => {
18405
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1j);
18942
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1k);
18406
18943
  const navigate = createNavigateToTriageAgent(navigateProps);
18407
18944
  const toolSchema = addTool({
18408
18945
  toolName,
@@ -18441,12 +18978,12 @@ function addTriageNavigation(params) {
18441
18978
  * Adds commit action functionality to an agent by creating a tool that validates and executes actions.
18442
18979
  * @module addCommitAction
18443
18980
  */
18444
- const METHOD_NAME$1i = "function.alias.addCommitAction";
18981
+ const METHOD_NAME$1j = "function.alias.addCommitAction";
18445
18982
  /**
18446
18983
  * Function implementation
18447
18984
  */
18448
18985
  const addCommitActionInternal = beginContext(({ toolName, docNote, function: functionSchema, isAvailable, ...actionProps }) => {
18449
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1i);
18986
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1j);
18450
18987
  const action = createCommitAction(actionProps);
18451
18988
  const toolSchema = addTool({
18452
18989
  toolName,
@@ -18523,12 +19060,12 @@ function addCommitAction(params) {
18523
19060
  * Adds fetch info functionality to an agent by creating a tool that fetches and provides information.
18524
19061
  * @module addFetchInfo
18525
19062
  */
18526
- const METHOD_NAME$1h = "function.alias.addFetchInfo";
19063
+ const METHOD_NAME$1i = "function.alias.addFetchInfo";
18527
19064
  /**
18528
19065
  * Function implementation
18529
19066
  */
18530
19067
  const addFetchInfoInternal = beginContext(({ toolName, docNote, function: functionSchema, isAvailable, validateParams: validate, ...fetchProps }) => {
18531
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1h);
19068
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$1i);
18532
19069
  const fetch = createFetchInfo(fetchProps);
18533
19070
  const toolSchema = addTool({
18534
19071
  toolName,
@@ -18594,13 +19131,13 @@ function addFetchInfo(params) {
18594
19131
  }
18595
19132
 
18596
19133
  /** @constant {string} METHOD_NAME - The name of the method used for logging*/
18597
- const METHOD_NAME$1g = "function.setup.addAdvisor";
19134
+ const METHOD_NAME$1h = "function.setup.addAdvisor";
18598
19135
  /**
18599
19136
  * Function implementation
18600
19137
  */
18601
19138
  const addAdvisorInternal = beginContext((advisorSchema) => {
18602
19139
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18603
- swarm$1.loggerService.log(METHOD_NAME$1g, {
19140
+ swarm$1.loggerService.log(METHOD_NAME$1h, {
18604
19141
  advisorSchema,
18605
19142
  });
18606
19143
  swarm$1.advisorValidationService.addAdvisor(advisorSchema.advisorName, advisorSchema);
@@ -18711,14 +19248,14 @@ const mapAgentSchema = ({ system, systemDynamic, systemStatic, ...schema }) => r
18711
19248
  : systemDynamic,
18712
19249
  });
18713
19250
 
18714
- const METHOD_NAME$1f = "function.setup.addAgent";
19251
+ const METHOD_NAME$1g = "function.setup.addAgent";
18715
19252
  /**
18716
19253
  * Function implementation
18717
19254
  */
18718
19255
  const addAgentInternal = beginContext((publicAgentSchema) => {
18719
19256
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18720
19257
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18721
- swarm$1.loggerService.log(METHOD_NAME$1f, {
19258
+ swarm$1.loggerService.log(METHOD_NAME$1g, {
18722
19259
  agentSchema: publicAgentSchema,
18723
19260
  });
18724
19261
  const agentSchema = mapAgentSchema(publicAgentSchema);
@@ -18754,8 +19291,26 @@ function addAgent(agentSchema) {
18754
19291
  * Also removes any undefined properties from the resulting schema object.
18755
19292
  *
18756
19293
  */
18757
- const mapCompletionSchema = ({ getCompletion, ...schema }) => removeUndefined({
19294
+ const mapCompletionSchema = ({ getCompletion, callbacks, ...schema }) => removeUndefined({
18758
19295
  ...schema,
19296
+ callbacks: callbacks
19297
+ ? {
19298
+ ...callbacks,
19299
+ onComplete: callbacks.onComplete
19300
+ ? (...args) => {
19301
+ try {
19302
+ // Observer callback: a throw here would reject getCompletion
19303
+ // inside the queued EXECUTE_FN and hang the pending
19304
+ // waitForOutput of the execution.
19305
+ return callbacks.onComplete(...args);
19306
+ }
19307
+ catch (error) {
19308
+ console.error(`agent-swarm onComplete completion callback error completionName=${schema.completionName} error=${functoolsKit.getErrorMessage(error)}`);
19309
+ }
19310
+ }
19311
+ : undefined,
19312
+ }
19313
+ : undefined,
18759
19314
  getCompletion: getCompletion
18760
19315
  ? async (args) => {
18761
19316
  try {
@@ -18777,14 +19332,14 @@ const mapCompletionSchema = ({ getCompletion, ...schema }) => removeUndefined({
18777
19332
  : undefined,
18778
19333
  });
18779
19334
 
18780
- const METHOD_NAME$1e = "function.setup.addCompletion";
19335
+ const METHOD_NAME$1f = "function.setup.addCompletion";
18781
19336
  /**
18782
19337
  * Function implementation
18783
19338
  */
18784
19339
  const addCompletionInternal = beginContext((completionPublicSchema) => {
18785
19340
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18786
19341
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18787
- swarm$1.loggerService.log(METHOD_NAME$1e, {
19342
+ swarm$1.loggerService.log(METHOD_NAME$1f, {
18788
19343
  completionSchema: completionPublicSchema,
18789
19344
  });
18790
19345
  const completionSchema = mapCompletionSchema(completionPublicSchema);
@@ -18814,14 +19369,14 @@ function addCompletion(completionSchema) {
18814
19369
  return addCompletionInternal(completionSchema);
18815
19370
  }
18816
19371
 
18817
- const METHOD_NAME$1d = "function.setup.addSwarm";
19372
+ const METHOD_NAME$1e = "function.setup.addSwarm";
18818
19373
  /**
18819
19374
  * Function implementation
18820
19375
  */
18821
19376
  const addSwarmInternal = beginContext((swarmSchema) => {
18822
19377
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18823
19378
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18824
- swarm$1.loggerService.log(METHOD_NAME$1d, {
19379
+ swarm$1.loggerService.log(METHOD_NAME$1e, {
18825
19380
  swarmSchema,
18826
19381
  });
18827
19382
  // Register the swarm in the validation and schema services
@@ -18850,13 +19405,13 @@ function addSwarm(swarmSchema) {
18850
19405
  return addSwarmInternal(swarmSchema);
18851
19406
  }
18852
19407
 
18853
- const METHOD_NAME$1c = "function.setup.addMCP";
19408
+ const METHOD_NAME$1d = "function.setup.addMCP";
18854
19409
  /**
18855
19410
  * Function implementation
18856
19411
  */
18857
19412
  const addMCPInternal = beginContext((mcpSchema) => {
18858
19413
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18859
- swarm$1.loggerService.log(METHOD_NAME$1c, {
19414
+ swarm$1.loggerService.log(METHOD_NAME$1d, {
18860
19415
  mcpSchema,
18861
19416
  });
18862
19417
  swarm$1.mcpValidationService.addMCP(mcpSchema.mcpName, mcpSchema);
@@ -18871,14 +19426,14 @@ function addMCP(mcpSchema) {
18871
19426
  return addMCPInternal(mcpSchema);
18872
19427
  }
18873
19428
 
18874
- const METHOD_NAME$1b = "function.setup.addState";
19429
+ const METHOD_NAME$1c = "function.setup.addState";
18875
19430
  /**
18876
19431
  * Function implementation
18877
19432
  */
18878
19433
  const addStateInternal = beginContext((stateSchema) => {
18879
19434
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18880
19435
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18881
- swarm$1.loggerService.log(METHOD_NAME$1b, {
19436
+ swarm$1.loggerService.log(METHOD_NAME$1c, {
18882
19437
  stateSchema,
18883
19438
  });
18884
19439
  // Register the policy with StateValidationService for runtime validation
@@ -18889,7 +19444,8 @@ const addStateInternal = beginContext((stateSchema) => {
18889
19444
  if (stateSchema.shared) {
18890
19445
  swarm$1.sharedStateConnectionService
18891
19446
  .getStateRef(stateSchema.stateName)
18892
- .waitForInit();
19447
+ .waitForInit()
19448
+ .catch((error) => console.error(`agent-swarm shared state waitForInit error error=${functoolsKit.getErrorMessage(error)}`));
18893
19449
  }
18894
19450
  // Return the state's name as confirmation of registration
18895
19451
  return stateSchema.stateName;
@@ -18916,14 +19472,14 @@ function addState(stateSchema) {
18916
19472
  return addStateInternal(stateSchema);
18917
19473
  }
18918
19474
 
18919
- const METHOD_NAME$1a = "function.setup.addEmbedding";
19475
+ const METHOD_NAME$1b = "function.setup.addEmbedding";
18920
19476
  /**
18921
19477
  * Function implementation
18922
19478
  */
18923
19479
  const addEmbeddingInternal = beginContext((embeddingSchema) => {
18924
19480
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18925
19481
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18926
- swarm$1.loggerService.log(METHOD_NAME$1a, {
19482
+ swarm$1.loggerService.log(METHOD_NAME$1b, {
18927
19483
  embeddingSchema,
18928
19484
  });
18929
19485
  // Register the embedding in the validation and schema services
@@ -18952,14 +19508,14 @@ function addEmbedding(embeddingSchema) {
18952
19508
  return addEmbeddingInternal(embeddingSchema);
18953
19509
  }
18954
19510
 
18955
- const METHOD_NAME$19 = "function.setup.addStorage";
19511
+ const METHOD_NAME$1a = "function.setup.addStorage";
18956
19512
  /**
18957
19513
  * Function implementation
18958
19514
  */
18959
19515
  const addStorageInternal = beginContext((storageSchema) => {
18960
19516
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
18961
19517
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
18962
- swarm$1.loggerService.log(METHOD_NAME$19, {
19518
+ swarm$1.loggerService.log(METHOD_NAME$1a, {
18963
19519
  storageSchema,
18964
19520
  });
18965
19521
  // Register the storage in the validation and schema services
@@ -18969,7 +19525,8 @@ const addStorageInternal = beginContext((storageSchema) => {
18969
19525
  if (storageSchema.shared) {
18970
19526
  swarm$1.sharedStorageConnectionService
18971
19527
  .getStorage(storageSchema.storageName)
18972
- .waitForInit();
19528
+ .waitForInit()
19529
+ .catch((error) => console.error(`agent-swarm shared storage waitForInit error error=${functoolsKit.getErrorMessage(error)}`));
18973
19530
  }
18974
19531
  // Return the storage's name as confirmation of registration
18975
19532
  return storageSchema.storageName;
@@ -18997,14 +19554,14 @@ function addStorage(storageSchema) {
18997
19554
  }
18998
19555
 
18999
19556
  /** @private Constant defining the method name for logging and validation context*/
19000
- const METHOD_NAME$18 = "function.setup.addPolicy";
19557
+ const METHOD_NAME$19 = "function.setup.addPolicy";
19001
19558
  /**
19002
19559
  * Function implementation
19003
19560
  */
19004
19561
  const addPolicyInternal = beginContext((policySchema) => {
19005
19562
  // Log the policy addition attempt if enabled
19006
19563
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19007
- swarm$1.loggerService.log(METHOD_NAME$18, {
19564
+ swarm$1.loggerService.log(METHOD_NAME$19, {
19008
19565
  policySchema,
19009
19566
  });
19010
19567
  // Register the policy with PolicyValidationService for runtime validation
@@ -19065,13 +19622,13 @@ function addCompute(computeSchema) {
19065
19622
  * Method name for the addPipeline operation.
19066
19623
  * @private
19067
19624
  */
19068
- const METHOD_NAME$17 = "function.setup.addPipeline";
19625
+ const METHOD_NAME$18 = "function.setup.addPipeline";
19069
19626
  /**
19070
19627
  * Function implementation
19071
19628
  */
19072
19629
  const addPipelineInternal = beginContext((pipelineSchema) => {
19073
19630
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19074
- swarm$1.loggerService.log(METHOD_NAME$17, {
19631
+ swarm$1.loggerService.log(METHOD_NAME$18, {
19075
19632
  pipelineSchema,
19076
19633
  });
19077
19634
  swarm$1.pipelineValidationService.addPipeline(pipelineSchema.pipelineName, pipelineSchema);
@@ -19094,7 +19651,7 @@ function addPipeline(pipelineSchema) {
19094
19651
  * @private
19095
19652
  * @constant {string}
19096
19653
  */
19097
- const METHOD_NAME$16 = "function.setup.addOutline";
19654
+ const METHOD_NAME$17 = "function.setup.addOutline";
19098
19655
  /**
19099
19656
  * Internal implementation of the outline addition logic, wrapped in a clean context.
19100
19657
  * Registers the outline schema with both the validation and schema services and logs the operation if enabled.
@@ -19102,7 +19659,7 @@ const METHOD_NAME$16 = "function.setup.addOutline";
19102
19659
  */
19103
19660
  const addOutlineInternal = beginContext((outlineSchema) => {
19104
19661
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19105
- swarm$1.loggerService.log(METHOD_NAME$16, {
19662
+ swarm$1.loggerService.log(METHOD_NAME$17, {
19106
19663
  outlineSchema,
19107
19664
  });
19108
19665
  swarm$1.outlineValidationService.addOutline(outlineSchema.outlineName, outlineSchema);
@@ -19121,16 +19678,16 @@ function addOutline(outlineSchema) {
19121
19678
  return addOutlineInternal(outlineSchema);
19122
19679
  }
19123
19680
 
19124
- const METHOD_NAME$15 = "function.test.overrideAgent";
19681
+ const METHOD_NAME$16 = "function.test.overrideAgent";
19125
19682
  /**
19126
19683
  * Function implementation
19127
19684
  */
19128
19685
  const overrideAgentInternal = beginContext(async (publicAgentSchema) => {
19129
19686
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19130
- swarm$1.loggerService.log(METHOD_NAME$15, {
19687
+ swarm$1.loggerService.log(METHOD_NAME$16, {
19131
19688
  agentSchema: publicAgentSchema,
19132
19689
  });
19133
- await swarm$1.agentValidationService.validate(publicAgentSchema.agentName, METHOD_NAME$15);
19690
+ await swarm$1.agentValidationService.validate(publicAgentSchema.agentName, METHOD_NAME$16);
19134
19691
  const agentSchema = mapAgentSchema(publicAgentSchema);
19135
19692
  return swarm$1.agentSchemaService.override(agentSchema.agentName, agentSchema);
19136
19693
  });
@@ -19157,16 +19714,16 @@ async function overrideAgent(agentSchema) {
19157
19714
  return await overrideAgentInternal(agentSchema);
19158
19715
  }
19159
19716
 
19160
- const METHOD_NAME$14 = "function.test.overrideCompletion";
19717
+ const METHOD_NAME$15 = "function.test.overrideCompletion";
19161
19718
  /**
19162
19719
  * Function implementation
19163
19720
  */
19164
19721
  const overrideCompletionInternal = beginContext(async (publicCompletionSchema) => {
19165
19722
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19166
- swarm$1.loggerService.log(METHOD_NAME$14, {
19723
+ swarm$1.loggerService.log(METHOD_NAME$15, {
19167
19724
  completionSchema: publicCompletionSchema,
19168
19725
  });
19169
- await swarm$1.completionValidationService.validate(publicCompletionSchema.completionName, METHOD_NAME$14);
19726
+ await swarm$1.completionValidationService.validate(publicCompletionSchema.completionName, METHOD_NAME$15);
19170
19727
  const completionSchema = mapCompletionSchema(publicCompletionSchema);
19171
19728
  return swarm$1.completionSchemaService.override(completionSchema.completionName, completionSchema);
19172
19729
  });
@@ -19194,16 +19751,16 @@ async function overrideCompletion(completionSchema) {
19194
19751
  return await overrideCompletionInternal(completionSchema);
19195
19752
  }
19196
19753
 
19197
- const METHOD_NAME$13 = "function.test.overrideEmbeding";
19754
+ const METHOD_NAME$14 = "function.test.overrideEmbedding";
19198
19755
  /**
19199
19756
  * Function implementation
19200
19757
  */
19201
- const overrideEmbedingInternal = beginContext(async (publicEmbeddingSchema) => {
19758
+ const overrideEmbeddingInternal = beginContext(async (publicEmbeddingSchema) => {
19202
19759
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19203
- swarm$1.loggerService.log(METHOD_NAME$13, {
19760
+ swarm$1.loggerService.log(METHOD_NAME$14, {
19204
19761
  embeddingSchema: publicEmbeddingSchema,
19205
19762
  });
19206
- await swarm$1.embeddingValidationService.validate(publicEmbeddingSchema.embeddingName, METHOD_NAME$13);
19763
+ await swarm$1.embeddingValidationService.validate(publicEmbeddingSchema.embeddingName, METHOD_NAME$14);
19207
19764
  const embeddingSchema = removeUndefined(publicEmbeddingSchema);
19208
19765
  return swarm$1.embeddingSchemaService.override(embeddingSchema.embeddingName, embeddingSchema);
19209
19766
  });
@@ -19219,7 +19776,7 @@ const overrideEmbedingInternal = beginContext(async (publicEmbeddingSchema) => {
19219
19776
  *
19220
19777
  * @example
19221
19778
  * // Override an embedding’s schema with new properties
19222
- * overrideEmbeding({
19779
+ * overrideEmbedding({
19223
19780
  * embeddingName: "TextEmbedding",
19224
19781
  * persist: true,
19225
19782
  * callbacks: {
@@ -19228,20 +19785,20 @@ const overrideEmbedingInternal = beginContext(async (publicEmbeddingSchema) => {
19228
19785
  * });
19229
19786
  * // Logs the operation (if enabled) and updates the embedding schema in the swarm.
19230
19787
  */
19231
- async function overrideEmbeding(embeddingSchema) {
19232
- return await overrideEmbedingInternal(embeddingSchema);
19788
+ async function overrideEmbedding(embeddingSchema) {
19789
+ return await overrideEmbeddingInternal(embeddingSchema);
19233
19790
  }
19234
19791
 
19235
- const METHOD_NAME$12 = "function.test.overridePolicy";
19792
+ const METHOD_NAME$13 = "function.test.overridePolicy";
19236
19793
  /**
19237
19794
  * Function implementation
19238
19795
  */
19239
19796
  const overridePolicyInternal = beginContext(async (publicPolicySchema) => {
19240
19797
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19241
- swarm$1.loggerService.log(METHOD_NAME$12, {
19798
+ swarm$1.loggerService.log(METHOD_NAME$13, {
19242
19799
  policySchema: publicPolicySchema,
19243
19800
  });
19244
- await swarm$1.policyValidationService.validate(publicPolicySchema.policyName, METHOD_NAME$12);
19801
+ await swarm$1.policyValidationService.validate(publicPolicySchema.policyName, METHOD_NAME$13);
19245
19802
  const policySchema = removeUndefined(publicPolicySchema);
19246
19803
  return swarm$1.policySchemaService.override(policySchema.policyName, policySchema);
19247
19804
  });
@@ -19268,16 +19825,16 @@ async function overridePolicy(policySchema) {
19268
19825
  return await overridePolicyInternal(policySchema);
19269
19826
  }
19270
19827
 
19271
- const METHOD_NAME$11 = "function.test.overrideState";
19828
+ const METHOD_NAME$12 = "function.test.overrideState";
19272
19829
  /**
19273
19830
  * Function implementation
19274
19831
  */
19275
19832
  const overrideStateInternal = beginContext(async (publicStateSchema) => {
19276
19833
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19277
- swarm$1.loggerService.log(METHOD_NAME$11, {
19834
+ swarm$1.loggerService.log(METHOD_NAME$12, {
19278
19835
  stateSchema: publicStateSchema,
19279
19836
  });
19280
- await swarm$1.stateValidationService.validate(publicStateSchema.stateName, METHOD_NAME$11);
19837
+ await swarm$1.stateValidationService.validate(publicStateSchema.stateName, METHOD_NAME$12);
19281
19838
  const stateSchema = removeUndefined(publicStateSchema);
19282
19839
  return swarm$1.stateSchemaService.override(stateSchema.stateName, stateSchema);
19283
19840
  });
@@ -19305,16 +19862,16 @@ async function overrideState(stateSchema) {
19305
19862
  return await overrideStateInternal(stateSchema);
19306
19863
  }
19307
19864
 
19308
- const METHOD_NAME$10 = "function.test.overrideStorage";
19865
+ const METHOD_NAME$11 = "function.test.overrideStorage";
19309
19866
  /**
19310
19867
  * Function implementation
19311
19868
  */
19312
19869
  const overrideStorageInternal = beginContext(async (publicStorageSchema) => {
19313
19870
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19314
- swarm$1.loggerService.log(METHOD_NAME$10, {
19871
+ swarm$1.loggerService.log(METHOD_NAME$11, {
19315
19872
  storageSchema: publicStorageSchema,
19316
19873
  });
19317
- await swarm$1.storageValidationService.validate(publicStorageSchema.storageName, METHOD_NAME$10);
19874
+ await swarm$1.storageValidationService.validate(publicStorageSchema.storageName, METHOD_NAME$11);
19318
19875
  const storageSchema = removeUndefined(publicStorageSchema);
19319
19876
  return swarm$1.storageSchemaService.override(storageSchema.storageName, storageSchema);
19320
19877
  });
@@ -19343,16 +19900,16 @@ async function overrideStorage(storageSchema) {
19343
19900
  return await overrideStorageInternal(storageSchema);
19344
19901
  }
19345
19902
 
19346
- const METHOD_NAME$$ = "function.test.overrideSwarm";
19903
+ const METHOD_NAME$10 = "function.test.overrideSwarm";
19347
19904
  /**
19348
19905
  * Function implementation
19349
19906
  */
19350
19907
  const overrideSwarmInternal = beginContext(async (publicSwarmSchema) => {
19351
19908
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19352
- swarm$1.loggerService.log(METHOD_NAME$$, {
19909
+ swarm$1.loggerService.log(METHOD_NAME$10, {
19353
19910
  swarmSchema: publicSwarmSchema,
19354
19911
  });
19355
- await swarm$1.swarmValidationService.validate(publicSwarmSchema.swarmName, METHOD_NAME$$);
19912
+ await swarm$1.swarmValidationService.validate(publicSwarmSchema.swarmName, METHOD_NAME$10);
19356
19913
  const swarmSchema = removeUndefined(publicSwarmSchema);
19357
19914
  return swarm$1.swarmSchemaService.override(swarmSchema.swarmName, swarmSchema);
19358
19915
  });
@@ -19379,16 +19936,16 @@ async function overrideSwarm(swarmSchema) {
19379
19936
  return await overrideSwarmInternal(swarmSchema);
19380
19937
  }
19381
19938
 
19382
- const METHOD_NAME$_ = "function.test.overrideTool";
19939
+ const METHOD_NAME$$ = "function.test.overrideTool";
19383
19940
  /**
19384
19941
  * Function implementation
19385
19942
  */
19386
19943
  const overrideToolInternal = beginContext(async (publicToolSchema) => {
19387
19944
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19388
- swarm$1.loggerService.log(METHOD_NAME$_, {
19945
+ swarm$1.loggerService.log(METHOD_NAME$$, {
19389
19946
  toolSchema: publicToolSchema,
19390
19947
  });
19391
- await swarm$1.toolValidationService.validate(publicToolSchema.toolName, METHOD_NAME$_);
19948
+ await swarm$1.toolValidationService.validate(publicToolSchema.toolName, METHOD_NAME$$);
19392
19949
  const toolSchema = removeUndefined(publicToolSchema);
19393
19950
  return swarm$1.toolSchemaService.override(toolSchema.toolName, toolSchema);
19394
19951
  });
@@ -19414,16 +19971,16 @@ async function overrideTool(toolSchema) {
19414
19971
  return await overrideToolInternal(toolSchema);
19415
19972
  }
19416
19973
 
19417
- const METHOD_NAME$Z = "function.test.overrideMCP";
19974
+ const METHOD_NAME$_ = "function.test.overrideMCP";
19418
19975
  /**
19419
19976
  * Function implementation
19420
19977
  */
19421
19978
  const overrideMCPInternal = beginContext(async (publicMcpSchema) => {
19422
19979
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19423
- swarm$1.loggerService.log(METHOD_NAME$Z, {
19980
+ swarm$1.loggerService.log(METHOD_NAME$_, {
19424
19981
  mcpSchema: publicMcpSchema,
19425
19982
  });
19426
- await swarm$1.mcpValidationService.validate(publicMcpSchema.mcpName, METHOD_NAME$Z);
19983
+ await swarm$1.mcpValidationService.validate(publicMcpSchema.mcpName, METHOD_NAME$_);
19427
19984
  const mcpSchema = removeUndefined(publicMcpSchema);
19428
19985
  return swarm$1.mcpSchemaService.override(mcpSchema.mcpName, mcpSchema);
19429
19986
  });
@@ -19435,16 +19992,16 @@ async function overrideMCP(mcpSchema) {
19435
19992
  return await overrideMCPInternal(mcpSchema);
19436
19993
  }
19437
19994
 
19438
- const METHOD_NAME$Y = "function.test.overrideAdvisor";
19995
+ const METHOD_NAME$Z = "function.test.overrideAdvisor";
19439
19996
  /**
19440
19997
  * Function implementation
19441
19998
  */
19442
19999
  const overrideAdvisorInternal = beginContext(async (publicAdvisorSchema) => {
19443
20000
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19444
- swarm$1.loggerService.log(METHOD_NAME$Y, {
20001
+ swarm$1.loggerService.log(METHOD_NAME$Z, {
19445
20002
  advisorSchema: publicAdvisorSchema,
19446
20003
  });
19447
- await swarm$1.advisorValidationService.validate(publicAdvisorSchema.advisorName, METHOD_NAME$Y);
20004
+ await swarm$1.advisorValidationService.validate(publicAdvisorSchema.advisorName, METHOD_NAME$Z);
19448
20005
  const advisorSchema = removeUndefined(publicAdvisorSchema);
19449
20006
  return swarm$1.advisorSchemaService.override(advisorSchema.advisorName, advisorSchema);
19450
20007
  });
@@ -19489,16 +20046,16 @@ async function overrideAdvisor(advisorSchema) {
19489
20046
  * Method name for the overrideCompute operation.
19490
20047
  * @private
19491
20048
  */
19492
- const METHOD_NAME$X = "function.test.overrideCompute";
20049
+ const METHOD_NAME$Y = "function.test.overrideCompute";
19493
20050
  /**
19494
20051
  * Function implementation
19495
20052
  */
19496
20053
  const overrideComputeInternal = beginContext(async (publicComputeSchema) => {
19497
20054
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19498
- swarm$1.loggerService.log(METHOD_NAME$X, {
20055
+ swarm$1.loggerService.log(METHOD_NAME$Y, {
19499
20056
  computeSchema: publicComputeSchema,
19500
20057
  });
19501
- await swarm$1.computeValidationService.validate(publicComputeSchema.computeName, METHOD_NAME$X);
20058
+ await swarm$1.computeValidationService.validate(publicComputeSchema.computeName, METHOD_NAME$Y);
19502
20059
  const computeSchema = removeUndefined(publicComputeSchema);
19503
20060
  return swarm$1.computeSchemaService.override(computeSchema.computeName, computeSchema);
19504
20061
  });
@@ -19520,16 +20077,16 @@ async function overrideCompute(computeSchema) {
19520
20077
  * Method name for the overridePipeline operation.
19521
20078
  * @private
19522
20079
  */
19523
- const METHOD_NAME$W = "function.test.overridePipeline";
20080
+ const METHOD_NAME$X = "function.test.overridePipeline";
19524
20081
  /**
19525
20082
  * Function implementation
19526
20083
  */
19527
20084
  const overridePipelineInternal = beginContext(async (publicPipelineSchema) => {
19528
20085
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19529
- swarm$1.loggerService.log(METHOD_NAME$W, {
20086
+ swarm$1.loggerService.log(METHOD_NAME$X, {
19530
20087
  pipelineSchema: publicPipelineSchema,
19531
20088
  });
19532
- await swarm$1.pipelineValidationService.validate(publicPipelineSchema.pipelineName, METHOD_NAME$W);
20089
+ await swarm$1.pipelineValidationService.validate(publicPipelineSchema.pipelineName, METHOD_NAME$X);
19533
20090
  const pipelineSchema = removeUndefined(publicPipelineSchema);
19534
20091
  return swarm$1.pipelineSchemaService.override(pipelineSchema.pipelineName, pipelineSchema);
19535
20092
  });
@@ -19549,7 +20106,7 @@ async function overridePipeline(pipelineSchema) {
19549
20106
  * @private
19550
20107
  * @constant {string}
19551
20108
  */
19552
- const METHOD_NAME$V = "function.test.overrideOutline";
20109
+ const METHOD_NAME$W = "function.test.overrideOutline";
19553
20110
  /**
19554
20111
  * Internal implementation of the outline override logic, wrapped in a clean context.
19555
20112
  * Updates the specified outline schema in the swarm's schema service and logs the operation if enabled.
@@ -19557,10 +20114,10 @@ const METHOD_NAME$V = "function.test.overrideOutline";
19557
20114
  */
19558
20115
  const overrideOutlineInternal = beginContext(async (publicOutlineSchema) => {
19559
20116
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19560
- swarm$1.loggerService.log(METHOD_NAME$V, {
20117
+ swarm$1.loggerService.log(METHOD_NAME$W, {
19561
20118
  outlineSchema: publicOutlineSchema,
19562
20119
  });
19563
- await swarm$1.outlineValidationService.validate(publicOutlineSchema.outlineName, METHOD_NAME$V);
20120
+ await swarm$1.outlineValidationService.validate(publicOutlineSchema.outlineName, METHOD_NAME$W);
19564
20121
  const outlineSchema = removeUndefined(publicOutlineSchema);
19565
20122
  return swarm$1.outlineSchemaService.override(outlineSchema.outlineName, outlineSchema);
19566
20123
  });
@@ -19576,23 +20133,23 @@ async function overrideOutline(outlineSchema) {
19576
20133
  return await overrideOutlineInternal(outlineSchema);
19577
20134
  }
19578
20135
 
19579
- const METHOD_NAME$U = "function.other.markOnline";
20136
+ const METHOD_NAME$V = "function.other.markOnline";
19580
20137
  /**
19581
20138
  * Function implementation
19582
20139
  */
19583
20140
  const markOnlineInternal = async (clientId, swarmName) => {
19584
20141
  // Log the operation if logging is enabled in the global configuration
19585
20142
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19586
- swarm.loggerService.log(METHOD_NAME$U, {
20143
+ swarm.loggerService.log(METHOD_NAME$V, {
19587
20144
  clientId,
19588
20145
  });
19589
20146
  // Validate the swarm name
19590
- swarm.swarmValidationService.validate(swarmName, METHOD_NAME$U);
20147
+ swarm.swarmValidationService.validate(swarmName, METHOD_NAME$V);
19591
20148
  // Run the operation in the method context
19592
20149
  return await MethodContextService.runInContext(async () => {
19593
- await swarm.aliveService.markOnline(clientId, swarmName, METHOD_NAME$U);
20150
+ await swarm.aliveService.markOnline(clientId, swarmName, METHOD_NAME$V);
19594
20151
  }, {
19595
- methodName: METHOD_NAME$U,
20152
+ methodName: METHOD_NAME$V,
19596
20153
  agentName: "",
19597
20154
  policyName: "",
19598
20155
  stateName: "",
@@ -19615,20 +20172,20 @@ async function markOnline(clientId, swarmName) {
19615
20172
  return await markOnlineInternal(clientId, swarmName);
19616
20173
  }
19617
20174
 
19618
- const METHOD_NAME$T = "function.other.markOffline";
20175
+ const METHOD_NAME$U = "function.other.markOffline";
19619
20176
  /**
19620
20177
  * Function implementation
19621
20178
  */
19622
20179
  const markOfflineInternal = async (clientId, swarmName) => {
19623
20180
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19624
- swarm.loggerService.log(METHOD_NAME$T, {
20181
+ swarm.loggerService.log(METHOD_NAME$U, {
19625
20182
  clientId,
19626
20183
  });
19627
- swarm.swarmValidationService.validate(swarmName, METHOD_NAME$T);
20184
+ swarm.swarmValidationService.validate(swarmName, METHOD_NAME$U);
19628
20185
  return await MethodContextService.runInContext(async () => {
19629
- await swarm.aliveService.markOffline(clientId, swarmName, METHOD_NAME$T);
20186
+ await swarm.aliveService.markOffline(clientId, swarmName, METHOD_NAME$U);
19630
20187
  }, {
19631
- methodName: METHOD_NAME$T,
20188
+ methodName: METHOD_NAME$U,
19632
20189
  agentName: "",
19633
20190
  policyName: "",
19634
20191
  stateName: "",
@@ -19656,27 +20213,27 @@ async function markOffline(clientId, swarmName) {
19656
20213
  }
19657
20214
 
19658
20215
  /** @private Constant defining the method name for logging and validation context*/
19659
- const METHOD_NAME$S = "function.commit.commitSystemMessage";
20216
+ const METHOD_NAME$T = "function.commit.commitSystemMessage";
19660
20217
  /**
19661
20218
  * Function implementation
19662
20219
  */
19663
20220
  const commitSystemMessageInternal = beginContext(async (content, clientId, agentName) => {
19664
20221
  // Log the commit attempt if enabled
19665
20222
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19666
- swarm$1.loggerService.log(METHOD_NAME$S, {
20223
+ swarm$1.loggerService.log(METHOD_NAME$T, {
19667
20224
  content,
19668
20225
  clientId,
19669
20226
  agentName,
19670
20227
  });
19671
20228
  // Validate the agent exists
19672
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$S);
20229
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$T);
19673
20230
  // Validate the session exists and retrieve the associated swarm
19674
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$S);
20231
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$T);
19675
20232
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19676
20233
  // Validate the swarm configuration
19677
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$S);
20234
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$T);
19678
20235
  // Check if the current agent matches the provided agent
19679
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$S, clientId, swarmName);
20236
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$T, clientId, swarmName);
19680
20237
  if (currentAgentName !== agentName) {
19681
20238
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19682
20239
  swarm$1.loggerService.log('function "commitSystemMessage" skipped due to the agent change', {
@@ -19687,7 +20244,7 @@ const commitSystemMessageInternal = beginContext(async (content, clientId, agent
19687
20244
  return;
19688
20245
  }
19689
20246
  // Commit the system message via SessionPublicService
19690
- await swarm$1.sessionPublicService.commitSystemMessage(content, METHOD_NAME$S, clientId, swarmName);
20247
+ await swarm$1.sessionPublicService.commitSystemMessage(content, METHOD_NAME$T, clientId, swarmName);
19691
20248
  });
19692
20249
  /**
19693
20250
  * Commits a system-generated message to the active agent in the swarm system.
@@ -19709,22 +20266,22 @@ async function commitSystemMessage(content, clientId, agentName) {
19709
20266
  }
19710
20267
 
19711
20268
  /** @private Constant defining the method name for logging and validation context*/
19712
- const METHOD_NAME$R = "function.commit.commitDeveloperMessage";
20269
+ const METHOD_NAME$S = "function.commit.commitDeveloperMessage";
19713
20270
  /**
19714
20271
  * Function implementation
19715
20272
  */
19716
20273
  const commitDeveloperMessageInternal = beginContext(async (content, clientId, agentName) => {
19717
20274
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19718
- swarm$1.loggerService.log(METHOD_NAME$R, {
20275
+ swarm$1.loggerService.log(METHOD_NAME$S, {
19719
20276
  content,
19720
20277
  clientId,
19721
20278
  agentName,
19722
20279
  });
19723
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$R);
19724
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$R);
20280
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$S);
20281
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$S);
19725
20282
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19726
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$R);
19727
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$R, clientId, swarmName);
20283
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$S);
20284
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$S, clientId, swarmName);
19728
20285
  if (currentAgentName !== agentName) {
19729
20286
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19730
20287
  swarm$1.loggerService.log('function "commitDeveloperMessage" skipped due to the agent change', {
@@ -19734,7 +20291,7 @@ const commitDeveloperMessageInternal = beginContext(async (content, clientId, ag
19734
20291
  });
19735
20292
  return;
19736
20293
  }
19737
- await swarm$1.sessionPublicService.commitDeveloperMessage(content, METHOD_NAME$R, clientId, swarmName);
20294
+ await swarm$1.sessionPublicService.commitDeveloperMessage(content, METHOD_NAME$S, clientId, swarmName);
19738
20295
  });
19739
20296
  /**
19740
20297
  * Commits a developer-generated message to the active agent in the swarm system.
@@ -19755,26 +20312,26 @@ async function commitDeveloperMessage(content, clientId, agentName) {
19755
20312
  return await commitDeveloperMessageInternal(content, clientId, agentName);
19756
20313
  }
19757
20314
 
19758
- const METHOD_NAME$Q = "function.commit.commitSystemMessage";
20315
+ const METHOD_NAME$R = "function.commit.commitUserMessage";
19759
20316
  /**
19760
20317
  * Function implementation
19761
20318
  */
19762
20319
  const commitUserMessageInternal = beginContext(async (content, mode, clientId, agentName, payload) => {
19763
20320
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
19764
20321
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19765
- swarm$1.loggerService.log(METHOD_NAME$Q, {
20322
+ swarm$1.loggerService.log(METHOD_NAME$R, {
19766
20323
  content,
19767
20324
  clientId,
19768
20325
  agentName,
19769
20326
  mode,
19770
20327
  });
19771
20328
  // Validate the agent, session, and swarm to ensure they exist and are accessible
19772
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$Q);
19773
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$Q);
20329
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$R);
20330
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$R);
19774
20331
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19775
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$Q);
20332
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$R);
19776
20333
  // Check if the specified agent is still the active agent in the swarm session
19777
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$Q, clientId, swarmName);
20334
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$R, clientId, swarmName);
19778
20335
  if (currentAgentName !== agentName) {
19779
20336
  // Log a skip message if the agent has changed during the operation
19780
20337
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
@@ -19787,14 +20344,14 @@ const commitUserMessageInternal = beginContext(async (content, mode, clientId, a
19787
20344
  }
19788
20345
  if (payload) {
19789
20346
  return await PayloadContextService.runInContext(async () => {
19790
- await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$Q, clientId, swarmName);
20347
+ await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$R, clientId, swarmName);
19791
20348
  }, {
19792
20349
  clientId,
19793
20350
  payload,
19794
20351
  });
19795
20352
  }
19796
20353
  // Commit the user message to the agent's history via the session public service
19797
- return await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$Q, clientId, swarmName);
20354
+ return await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$R, clientId, swarmName);
19798
20355
  });
19799
20356
  /**
19800
20357
  * Commits a user message to the active agent's history in a swarm session without triggering a response.
@@ -19818,24 +20375,24 @@ async function commitUserMessage(content, mode, clientId, agentName, payload) {
19818
20375
  }
19819
20376
 
19820
20377
  /** @private Constant defining the method name for logging and validation context*/
19821
- const METHOD_NAME$P = "function.commit.commitSystemMessageForce";
20378
+ const METHOD_NAME$Q = "function.commit.commitSystemMessageForce";
19822
20379
  /**
19823
20380
  * Function implementation
19824
20381
  */
19825
20382
  const commitSystemMessageForceInternal = beginContext(async (content, clientId) => {
19826
20383
  // Log the commit attempt if enabled
19827
20384
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19828
- swarm$1.loggerService.log(METHOD_NAME$P, {
20385
+ swarm$1.loggerService.log(METHOD_NAME$Q, {
19829
20386
  content,
19830
20387
  clientId,
19831
20388
  });
19832
20389
  // Validate the session exists and retrieve the associated swarm
19833
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$P);
20390
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$Q);
19834
20391
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19835
20392
  // Validate the swarm configuration
19836
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$P);
20393
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$Q);
19837
20394
  // Commit the system message via SessionPublicService without agent checks
19838
- await swarm$1.sessionPublicService.commitSystemMessage(content, METHOD_NAME$P, clientId, swarmName);
20395
+ await swarm$1.sessionPublicService.commitSystemMessage(content, METHOD_NAME$Q, clientId, swarmName);
19839
20396
  });
19840
20397
  /**
19841
20398
  * Forcefully commits a system-generated message to a session in the swarm system, without checking the active agent.
@@ -19856,7 +20413,7 @@ async function commitSystemMessageForce(content, clientId) {
19856
20413
  }
19857
20414
 
19858
20415
  /** @private Constant defining the method name for logging and validation context*/
19859
- const METHOD_NAME$O = "function.commit.commitDeveloperMessageForce";
20416
+ const METHOD_NAME$P = "function.commit.commitDeveloperMessageForce";
19860
20417
  /**
19861
20418
  * Internal implementation for forcefully committing a developer message to a session in the swarm system.
19862
20419
  * Logs the operation if enabled, validates the session and swarm, and commits the message via SessionPublicService.
@@ -19869,14 +20426,14 @@ const METHOD_NAME$O = "function.commit.commitDeveloperMessageForce";
19869
20426
  */
19870
20427
  const commitDeveloperMessageForceInternal = beginContext(async (content, clientId) => {
19871
20428
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19872
- swarm$1.loggerService.log(METHOD_NAME$O, {
20429
+ swarm$1.loggerService.log(METHOD_NAME$P, {
19873
20430
  content,
19874
20431
  clientId,
19875
20432
  });
19876
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$O);
20433
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$P);
19877
20434
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19878
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$O);
19879
- await swarm$1.sessionPublicService.commitDeveloperMessage(content, METHOD_NAME$O, clientId, swarmName);
20435
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$P);
20436
+ await swarm$1.sessionPublicService.commitDeveloperMessage(content, METHOD_NAME$P, clientId, swarmName);
19880
20437
  });
19881
20438
  /**
19882
20439
  * Forcefully commits a developer-generated message to a session in the swarm system, without checking the active agent.
@@ -19895,32 +20452,32 @@ async function commitDeveloperMessageForce(content, clientId) {
19895
20452
  return await commitDeveloperMessageForceInternal(content, clientId);
19896
20453
  }
19897
20454
 
19898
- const METHOD_NAME$N = "function.commit.commitSystemMessage";
20455
+ const METHOD_NAME$O = "function.commit.commitUserMessageForce";
19899
20456
  /**
19900
20457
  * Function implementation
19901
20458
  */
19902
20459
  const commitUserMessageForceInternal = beginContext(async (content, mode, clientId, payload) => {
19903
20460
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
19904
20461
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19905
- swarm$1.loggerService.log(METHOD_NAME$N, {
20462
+ swarm$1.loggerService.log(METHOD_NAME$O, {
19906
20463
  content,
19907
20464
  clientId,
19908
20465
  mode,
19909
20466
  });
19910
20467
  // Validate the session and swarm to ensure they exist and are accessible
19911
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$N);
20468
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$O);
19912
20469
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19913
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$N);
20470
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$O);
19914
20471
  if (payload) {
19915
20472
  return await PayloadContextService.runInContext(async () => {
19916
- await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$N, clientId, swarmName);
20473
+ await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$O, clientId, swarmName);
19917
20474
  }, {
19918
20475
  clientId,
19919
20476
  payload,
19920
20477
  });
19921
20478
  }
19922
20479
  // Commit the user message to the agent's history via the session public service without checking the active agent
19923
- return await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$N, clientId, swarmName);
20480
+ return await swarm$1.sessionPublicService.commitUserMessage(content, mode, METHOD_NAME$O, clientId, swarmName);
19924
20481
  });
19925
20482
  /**
19926
20483
  * Commits a user message to the active agent's history in a swarm session without triggering a response and without checking the active agent.
@@ -19943,27 +20500,27 @@ async function commitUserMessageForce(content, mode, clientId, payload) {
19943
20500
  }
19944
20501
 
19945
20502
  /** @private Constant defining the method name for logging and validation context*/
19946
- const METHOD_NAME$M = "function.commit.commitAssistantMessage";
20503
+ const METHOD_NAME$N = "function.commit.commitAssistantMessage";
19947
20504
  /**
19948
20505
  * Function implementation
19949
20506
  */
19950
20507
  const commitAssistantMessageInternal = beginContext(async (content, clientId, agentName) => {
19951
20508
  // Log the commit attempt if enabled
19952
20509
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19953
- swarm$1.loggerService.log(METHOD_NAME$M, {
20510
+ swarm$1.loggerService.log(METHOD_NAME$N, {
19954
20511
  content,
19955
20512
  clientId,
19956
20513
  agentName,
19957
20514
  });
19958
20515
  // Validate the agent exists
19959
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$M);
20516
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$N);
19960
20517
  // Validate the session exists and retrieve the associated swarm
19961
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$M);
20518
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$N);
19962
20519
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
19963
20520
  // Validate the swarm configuration
19964
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$M);
20521
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$N);
19965
20522
  // Check if the current agent matches the provided agent
19966
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$M, clientId, swarmName);
20523
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$N, clientId, swarmName);
19967
20524
  if (currentAgentName !== agentName) {
19968
20525
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
19969
20526
  swarm$1.loggerService.log('function "commitAssistantMessage" skipped due to the agent change', {
@@ -19974,7 +20531,7 @@ const commitAssistantMessageInternal = beginContext(async (content, clientId, ag
19974
20531
  return;
19975
20532
  }
19976
20533
  // Commit the assistant message via SessionPublicService
19977
- await swarm$1.sessionPublicService.commitAssistantMessage(content, METHOD_NAME$M, clientId, swarmName);
20534
+ await swarm$1.sessionPublicService.commitAssistantMessage(content, METHOD_NAME$N, clientId, swarmName);
19978
20535
  });
19979
20536
  /**
19980
20537
  * Commits an assistant-generated message to the active agent in the swarm system.
@@ -19995,24 +20552,24 @@ async function commitAssistantMessage(content, clientId, agentName) {
19995
20552
  }
19996
20553
 
19997
20554
  /** @private Constant defining the method name for logging and validation context*/
19998
- const METHOD_NAME$L = "function.commit.commitAssistantMessageForce";
20555
+ const METHOD_NAME$M = "function.commit.commitAssistantMessageForce";
19999
20556
  /**
20000
20557
  * Function implementation
20001
20558
  */
20002
20559
  const commitAssistantMessageForceInternal = beginContext(async (content, clientId) => {
20003
20560
  // Log the commit attempt if enabled
20004
20561
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20005
- swarm$1.loggerService.log(METHOD_NAME$L, {
20562
+ swarm$1.loggerService.log(METHOD_NAME$M, {
20006
20563
  content,
20007
20564
  clientId,
20008
20565
  });
20009
20566
  // Validate the session exists and retrieve the associated swarm
20010
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$L);
20567
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$M);
20011
20568
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20012
20569
  // Validate the swarm configuration
20013
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$L);
20570
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$M);
20014
20571
  // Commit the assistant message via SessionPublicService without agent checks
20015
- await swarm$1.sessionPublicService.commitAssistantMessage(content, METHOD_NAME$L, clientId, swarmName);
20572
+ await swarm$1.sessionPublicService.commitAssistantMessage(content, METHOD_NAME$M, clientId, swarmName);
20016
20573
  });
20017
20574
  /**
20018
20575
  * Forcefully commits an assistant-generated message to a session in the swarm system, without checking the active agent.
@@ -20033,26 +20590,26 @@ async function commitAssistantMessageForce(content, clientId) {
20033
20590
  }
20034
20591
 
20035
20592
  /** @private Constant defining the method name for logging and validation context*/
20036
- const METHOD_NAME$K = "function.commit.cancelOutput";
20593
+ const METHOD_NAME$L = "function.commit.cancelOutput";
20037
20594
  /**
20038
20595
  * Function implementation
20039
20596
  */
20040
20597
  const cancelOutputInternal = beginContext(async (clientId, agentName) => {
20041
20598
  // Log the cancellation attempt if enabled
20042
20599
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20043
- swarm$1.loggerService.log(METHOD_NAME$K, {
20600
+ swarm$1.loggerService.log(METHOD_NAME$L, {
20044
20601
  clientId,
20045
20602
  agentName,
20046
20603
  });
20047
20604
  // Validate the agent exists
20048
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$K);
20605
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$L);
20049
20606
  // Validate the session exists and retrieve the associated swarm
20050
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$K);
20607
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$L);
20051
20608
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20052
20609
  // Validate the swarm configuration
20053
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$K);
20610
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$L);
20054
20611
  // Check if the current agent matches the provided agent
20055
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$K, clientId, swarmName);
20612
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$L, clientId, swarmName);
20056
20613
  if (currentAgentName !== agentName) {
20057
20614
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20058
20615
  swarm$1.loggerService.log('function "cancelOutput" skipped due to the agent change', {
@@ -20063,7 +20620,7 @@ const cancelOutputInternal = beginContext(async (clientId, agentName) => {
20063
20620
  return;
20064
20621
  }
20065
20622
  // Perform the output cancellation via SwarmPublicService
20066
- await swarm$1.swarmPublicService.cancelOutput(METHOD_NAME$K, clientId, swarmName);
20623
+ await swarm$1.swarmPublicService.cancelOutput(METHOD_NAME$L, clientId, swarmName);
20067
20624
  });
20068
20625
  /**
20069
20626
  * Cancels the awaited output for a specific client and agent by emitting an empty string.
@@ -20082,23 +20639,23 @@ async function cancelOutput(clientId, agentName) {
20082
20639
  }
20083
20640
 
20084
20641
  /** @private Constant defining the method name for logging and validation context*/
20085
- const METHOD_NAME$J = "function.commit.cancelOutputForce";
20642
+ const METHOD_NAME$K = "function.commit.cancelOutputForce";
20086
20643
  /**
20087
20644
  * Function implementation
20088
20645
  */
20089
20646
  const cancelOutputForceInternal = beginContext(async (clientId) => {
20090
20647
  // Log the cancellation attempt if enabled
20091
20648
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20092
- swarm$1.loggerService.log(METHOD_NAME$J, {
20649
+ swarm$1.loggerService.log(METHOD_NAME$K, {
20093
20650
  clientId,
20094
20651
  });
20095
20652
  // Validate the session exists and retrieve the associated swarm
20096
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$J);
20653
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$K);
20097
20654
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20098
20655
  // Validate the swarm configuration
20099
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$J);
20656
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$K);
20100
20657
  // Perform the output cancellation via SwarmPublicService without agent checks
20101
- await swarm$1.swarmPublicService.cancelOutput(METHOD_NAME$J, clientId, swarmName);
20658
+ await swarm$1.swarmPublicService.cancelOutput(METHOD_NAME$K, clientId, swarmName);
20102
20659
  });
20103
20660
  /**
20104
20661
  * Forcefully cancels the awaited output for a specific client by emitting an empty string, without checking the active agent.
@@ -20116,22 +20673,22 @@ async function cancelOutputForce(clientId) {
20116
20673
  return await cancelOutputForceInternal(clientId);
20117
20674
  }
20118
20675
 
20119
- const METHOD_NAME$I = "function.commit.commitToolRequest";
20676
+ const METHOD_NAME$J = "function.commit.commitToolRequest";
20120
20677
  /**
20121
20678
  * Function implementation
20122
20679
  */
20123
20680
  const commitToolRequestInternal = beginContext(async (request, clientId, agentName) => {
20124
20681
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20125
- swarm$1.loggerService.log(METHOD_NAME$I, {
20682
+ swarm$1.loggerService.log(METHOD_NAME$J, {
20126
20683
  request,
20127
20684
  clientId,
20128
20685
  agentName,
20129
20686
  });
20130
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$I);
20131
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$I);
20687
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$J);
20688
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$J);
20132
20689
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20133
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$I);
20134
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$I, clientId, swarmName);
20690
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$J);
20691
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$J, clientId, swarmName);
20135
20692
  if (currentAgentName !== agentName) {
20136
20693
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20137
20694
  swarm$1.loggerService.log('function "commitToolRequest" skipped due to the agent change', {
@@ -20141,7 +20698,7 @@ const commitToolRequestInternal = beginContext(async (request, clientId, agentNa
20141
20698
  });
20142
20699
  return null;
20143
20700
  }
20144
- return await swarm$1.sessionPublicService.commitToolRequest(Array.isArray(request) ? request : [request], METHOD_NAME$I, clientId, swarmName);
20701
+ return await swarm$1.sessionPublicService.commitToolRequest(Array.isArray(request) ? request : [request], METHOD_NAME$J, clientId, swarmName);
20145
20702
  });
20146
20703
  /**
20147
20704
  * Commits a tool request to the active agent in the swarm system.
@@ -20156,21 +20713,21 @@ async function commitToolRequest(request, clientId, agentName) {
20156
20713
  return await commitToolRequestInternal(request, clientId, agentName);
20157
20714
  }
20158
20715
 
20159
- const METHOD_NAME$H = "function.commit.commitToolRequestForce";
20716
+ const METHOD_NAME$I = "function.commit.commitToolRequestForce";
20160
20717
  /**
20161
20718
  * Function implementation
20162
20719
  */
20163
20720
  const commitToolRequestForceInternal = beginContext(async (request, clientId) => {
20164
20721
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20165
- swarm$1.loggerService.log(METHOD_NAME$H, {
20722
+ swarm$1.loggerService.log(METHOD_NAME$I, {
20166
20723
  request,
20167
20724
  clientId,
20168
20725
  });
20169
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$H);
20726
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$I);
20170
20727
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20171
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$H);
20728
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$I);
20172
20729
  const requests = Array.isArray(request) ? request : [request];
20173
- return await swarm$1.sessionPublicService.commitToolRequest(requests, METHOD_NAME$H, clientId, swarmName);
20730
+ return await swarm$1.sessionPublicService.commitToolRequest(requests, METHOD_NAME$I, clientId, swarmName);
20174
20731
  });
20175
20732
  /**
20176
20733
  * Forcefully commits a tool request to the active agent in the swarm system.
@@ -20187,18 +20744,18 @@ async function commitToolRequestForce(request, clientId) {
20187
20744
  }
20188
20745
 
20189
20746
  /** @constant {string} METHOD_NAME - The name of the method used for logging and validation*/
20190
- const METHOD_NAME$G = "function.target.ask";
20747
+ const METHOD_NAME$H = "function.target.ask";
20191
20748
  /**
20192
20749
  * Function implementation
20193
20750
  */
20194
20751
  const askInternal = beginContext(async (message, advisorName) => {
20195
20752
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20196
- swarm$1.loggerService.log(METHOD_NAME$G, {
20753
+ swarm$1.loggerService.log(METHOD_NAME$H, {
20197
20754
  message,
20198
20755
  advisorName,
20199
20756
  });
20200
20757
  const resultId = functoolsKit.randomString();
20201
- swarm$1.advisorValidationService.validate(advisorName, METHOD_NAME$G);
20758
+ swarm$1.advisorValidationService.validate(advisorName, METHOD_NAME$H);
20202
20759
  const { getChat, callbacks } = swarm$1.advisorSchemaService.get(advisorName);
20203
20760
  if (callbacks?.onChat) {
20204
20761
  callbacks.onChat(message);
@@ -20241,7 +20798,7 @@ async function ask(message, advisorName) {
20241
20798
  return await askInternal(message, advisorName);
20242
20799
  }
20243
20800
 
20244
- const METHOD_NAME$F = "function.target.json";
20801
+ const METHOD_NAME$G = "function.target.json";
20245
20802
  const MAX_ATTEMPTS = 5;
20246
20803
  /**
20247
20804
  * A class implementing the IOutlineHistory interface to manage a history of outline messages.
@@ -20285,12 +20842,12 @@ class OutlineHistory {
20285
20842
  */
20286
20843
  const jsonInternal = beginContext(async (outlineName, ...params) => {
20287
20844
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20288
- swarm$1.loggerService.log(METHOD_NAME$F, {});
20289
- swarm$1.outlineValidationService.validate(outlineName, METHOD_NAME$F);
20845
+ swarm$1.loggerService.log(METHOD_NAME$G, {});
20846
+ swarm$1.outlineValidationService.validate(outlineName, METHOD_NAME$G);
20290
20847
  const resultId = functoolsKit.randomString();
20291
20848
  const clientId = `${resultId}_outline`;
20292
20849
  const { getOutlineHistory, completion, validations = [], maxAttempts = MAX_ATTEMPTS, format, prompt, system, callbacks: outlineCallbacks, } = swarm$1.outlineSchemaService.get(outlineName);
20293
- swarm$1.completionValidationService.validate(completion, METHOD_NAME$F);
20850
+ swarm$1.completionValidationService.validate(completion, METHOD_NAME$G);
20294
20851
  const completionSchema = swarm$1.completionSchemaService.get(completion);
20295
20852
  const { getCompletion, flags = [], callbacks: completionCallbacks, } = completionSchema;
20296
20853
  let errorMessage = "";
@@ -20423,7 +20980,7 @@ async function json(outlineName, ...params) {
20423
20980
  return await jsonInternal(outlineName, ...params);
20424
20981
  }
20425
20982
 
20426
- const METHOD_NAME$E = "function.target.chat";
20983
+ const METHOD_NAME$F = "function.target.chat";
20427
20984
  /**
20428
20985
  * Internal function to process a chat completion request.
20429
20986
  * Executes outside existing contexts using `beginContext` to ensure isolation.
@@ -20433,13 +20990,13 @@ const METHOD_NAME$E = "function.target.chat";
20433
20990
  */
20434
20991
  const chatInternal = beginContext(async (completionName, messages) => {
20435
20992
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20436
- swarm$1.loggerService.log(METHOD_NAME$E, {});
20437
- swarm$1.completionValidationService.validate(completionName, METHOD_NAME$E);
20993
+ swarm$1.loggerService.log(METHOD_NAME$F, {});
20994
+ swarm$1.completionValidationService.validate(completionName, METHOD_NAME$F);
20438
20995
  const resultId = functoolsKit.randomString();
20439
20996
  const clientId = `${resultId}_chat`;
20440
20997
  const completionSchema = swarm$1.completionSchemaService.get(completionName);
20441
20998
  if (completionSchema.json) {
20442
- throw new Error(`${METHOD_NAME$E} completion ${completionName} should not have json=true. Use a non-JSON completion for chat.`);
20999
+ throw new Error(`${METHOD_NAME$F} completion ${completionName} should not have json=true. Use a non-JSON completion for chat.`);
20443
21000
  }
20444
21001
  const { getCompletion } = completionSchema;
20445
21002
  let errorValue = null;
@@ -20479,7 +21036,7 @@ async function chat(completionName, messages) {
20479
21036
  return await chatInternal(completionName, messages);
20480
21037
  }
20481
21038
 
20482
- const METHOD_NAME$D = "function.target.disposeConnection";
21039
+ const METHOD_NAME$E = "function.target.disposeConnection";
20483
21040
  /**
20484
21041
  * Disposes of a client session and all related resources within a swarm.
20485
21042
  *
@@ -20492,10 +21049,10 @@ const METHOD_NAME$D = "function.target.disposeConnection";
20492
21049
  * @example
20493
21050
  * await disposeConnection("client-123", "TaskSwarm");
20494
21051
  */
20495
- const disposeConnection = beginContext(async (clientId, swarmName, methodName = METHOD_NAME$D) => {
21052
+ const disposeConnection = beginContext(async (clientId, swarmName, methodName = METHOD_NAME$E) => {
20496
21053
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20497
21054
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20498
- swarm$1.loggerService.log(METHOD_NAME$D, {
21055
+ swarm$1.loggerService.log(METHOD_NAME$E, {
20499
21056
  clientId,
20500
21057
  swarmName,
20501
21058
  });
@@ -20601,7 +21158,7 @@ const disposeConnection = beginContext(async (clientId, swarmName, methodName =
20601
21158
  PersistMemoryAdapter.dispose(clientId);
20602
21159
  });
20603
21160
 
20604
- const METHOD_NAME$C = "function.target.makeAutoDispose";
21161
+ const METHOD_NAME$D = "function.target.makeAutoDispose";
20605
21162
  /**
20606
21163
  * Default timeout in seconds before auto-dispose is triggered.
20607
21164
  * @constant {number}
@@ -20628,7 +21185,7 @@ const DEFAULT_TIMEOUT = 15 * 60;
20628
21185
  const makeAutoDispose = beginContext((clientId, swarmName, { timeoutSeconds = DEFAULT_TIMEOUT, onDestroy, } = {}) => {
20629
21186
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20630
21187
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20631
- swarm$1.loggerService.log(METHOD_NAME$C, {
21188
+ swarm$1.loggerService.log(METHOD_NAME$D, {
20632
21189
  clientId,
20633
21190
  swarmName,
20634
21191
  });
@@ -20661,30 +21218,30 @@ const makeAutoDispose = beginContext((clientId, swarmName, { timeoutSeconds = DE
20661
21218
  };
20662
21219
  });
20663
21220
 
20664
- const METHOD_NAME$B = "function.target.notify";
21221
+ const METHOD_NAME$C = "function.target.notify";
20665
21222
  /**
20666
21223
  * Function implementation
20667
21224
  */
20668
21225
  const notifyInternal = beginContext(async (content, clientId, agentName) => {
20669
21226
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20670
21227
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20671
- swarm$1.loggerService.log(METHOD_NAME$B, {
21228
+ swarm$1.loggerService.log(METHOD_NAME$C, {
20672
21229
  content,
20673
21230
  clientId,
20674
21231
  agentName,
20675
21232
  });
20676
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$B);
21233
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$C);
20677
21234
  // Check if the session mode is "makeConnection"
20678
21235
  if (swarm$1.sessionValidationService.getSessionMode(clientId) !==
20679
21236
  "makeConnection") {
20680
21237
  throw new Error(`agent-swarm-kit notify session is not makeConnection clientId=${clientId}`);
20681
21238
  }
20682
21239
  // Validate the agent, session, and swarm
20683
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$B);
21240
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$C);
20684
21241
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20685
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$B);
21242
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$C);
20686
21243
  // Check if the specified agent is still the active agent
20687
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$B, clientId, swarmName);
21244
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$C, clientId, swarmName);
20688
21245
  if (currentAgentName !== agentName) {
20689
21246
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20690
21247
  swarm$1.loggerService.log('function "notify" skipped due to the agent change', {
@@ -20695,7 +21252,7 @@ const notifyInternal = beginContext(async (content, clientId, agentName) => {
20695
21252
  return;
20696
21253
  }
20697
21254
  // Notify the content directly via the session public service
20698
- return await swarm$1.sessionPublicService.notify(content, METHOD_NAME$B, clientId, swarmName);
21255
+ return await swarm$1.sessionPublicService.notify(content, METHOD_NAME$C, clientId, swarmName);
20699
21256
  });
20700
21257
  /**
20701
21258
  * Sends a notification message as output from the swarm session without executing an incoming message.
@@ -20717,18 +21274,18 @@ async function notify(content, clientId, agentName) {
20717
21274
  return await notifyInternal(content, clientId, agentName);
20718
21275
  }
20719
21276
 
20720
- const METHOD_NAME$A = "function.target.notifyForce";
21277
+ const METHOD_NAME$B = "function.target.notifyForce";
20721
21278
  /**
20722
21279
  * Function implementation
20723
21280
  */
20724
21281
  const notifyForceInternal = beginContext(async (content, clientId) => {
20725
21282
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20726
21283
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20727
- swarm$1.loggerService.log(METHOD_NAME$A, {
21284
+ swarm$1.loggerService.log(METHOD_NAME$B, {
20728
21285
  content,
20729
21286
  clientId,
20730
21287
  });
20731
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$A);
21288
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$B);
20732
21289
  // Check if the session mode is "makeConnection"
20733
21290
  if (swarm$1.sessionValidationService.getSessionMode(clientId) !==
20734
21291
  "makeConnection") {
@@ -20736,9 +21293,9 @@ const notifyForceInternal = beginContext(async (content, clientId) => {
20736
21293
  }
20737
21294
  // Validate the agent, session, and swarm
20738
21295
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20739
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$A);
21296
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$B);
20740
21297
  // Notify the content directly via the session public service
20741
- return await swarm$1.sessionPublicService.notify(content, METHOD_NAME$A, clientId, swarmName);
21298
+ return await swarm$1.sessionPublicService.notify(content, METHOD_NAME$B, clientId, swarmName);
20742
21299
  });
20743
21300
  /**
20744
21301
  * Sends a notification message as output from the swarm session without executing an incoming message.
@@ -20759,7 +21316,7 @@ async function notifyForce(content, clientId) {
20759
21316
  return await notifyForceInternal(content, clientId);
20760
21317
  }
20761
21318
 
20762
- const METHOD_NAME$z = "function.target.runStateless";
21319
+ const METHOD_NAME$A = "function.target.runStateless";
20763
21320
  /**
20764
21321
  * Function implementation
20765
21322
  */
@@ -20767,19 +21324,19 @@ const runStatelessInternal = beginContext(async (content, clientId, agentName) =
20767
21324
  const executionId = functoolsKit.randomString();
20768
21325
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20769
21326
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20770
- swarm$1.loggerService.log(METHOD_NAME$z, {
21327
+ swarm$1.loggerService.log(METHOD_NAME$A, {
20771
21328
  content,
20772
21329
  clientId,
20773
21330
  agentName,
20774
21331
  executionId,
20775
21332
  });
20776
21333
  // Validate the agent, session, and swarm
20777
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$z);
20778
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$z);
21334
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$A);
21335
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$A);
20779
21336
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20780
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$z);
21337
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$A);
20781
21338
  // Check if the specified agent is still the active agent
20782
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$z, clientId, swarmName);
21339
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$A, clientId, swarmName);
20783
21340
  if (currentAgentName !== agentName) {
20784
21341
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20785
21342
  swarm$1.loggerService.log('function "runStateless" skipped due to the agent change', {
@@ -20805,7 +21362,7 @@ const runStatelessInternal = beginContext(async (content, clientId, agentName) =
20805
21362
  errorValue = error;
20806
21363
  }
20807
21364
  });
20808
- result = await swarm$1.sessionPublicService.run(content, METHOD_NAME$z, clientId, swarmName);
21365
+ result = await swarm$1.sessionPublicService.run(content, METHOD_NAME$A, clientId, swarmName);
20809
21366
  unError();
20810
21367
  if (errorValue) {
20811
21368
  throw errorValue;
@@ -20851,7 +21408,7 @@ async function runStateless(content, clientId, agentName) {
20851
21408
  return await runStatelessInternal(content, clientId, agentName);
20852
21409
  }
20853
21410
 
20854
- const METHOD_NAME$y = "function.target.runStatelessForce";
21411
+ const METHOD_NAME$z = "function.target.runStatelessForce";
20855
21412
  /**
20856
21413
  * Function implementation
20857
21414
  */
@@ -20859,15 +21416,15 @@ const runStatelessForceInternal = beginContext(async (content, clientId) => {
20859
21416
  const executionId = functoolsKit.randomString();
20860
21417
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20861
21418
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20862
- swarm$1.loggerService.log(METHOD_NAME$y, {
21419
+ swarm$1.loggerService.log(METHOD_NAME$z, {
20863
21420
  content,
20864
21421
  clientId,
20865
21422
  executionId,
20866
21423
  });
20867
21424
  // Validate the session and swarm
20868
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$y);
21425
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$z);
20869
21426
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
20870
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$y);
21427
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$z);
20871
21428
  // Execute the command statelessly within an execution context with performance tracking
20872
21429
  return ExecutionContextService.runInContext(async () => {
20873
21430
  let isFinished = false;
@@ -20881,7 +21438,7 @@ const runStatelessForceInternal = beginContext(async (content, clientId) => {
20881
21438
  errorValue = error;
20882
21439
  }
20883
21440
  });
20884
- result = await swarm$1.sessionPublicService.run(content, METHOD_NAME$y, clientId, swarmName);
21441
+ result = await swarm$1.sessionPublicService.run(content, METHOD_NAME$z, clientId, swarmName);
20885
21442
  unError();
20886
21443
  if (errorValue) {
20887
21444
  throw errorValue;
@@ -20932,7 +21489,7 @@ const SCHEDULED_DELAY$1 = 1000;
20932
21489
  * @constant {number}
20933
21490
  */
20934
21491
  const RATE_DELAY = 10000;
20935
- const METHOD_NAME$x = "function.target.makeConnection";
21492
+ const METHOD_NAME$y = "function.target.makeConnection";
20936
21493
  /**
20937
21494
  * Internal implementation of the connection factory for a client to a swarm.
20938
21495
  *
@@ -20943,21 +21500,21 @@ const METHOD_NAME$x = "function.target.makeConnection";
20943
21500
  const makeConnectionInternal = (connector, clientId, swarmName) => {
20944
21501
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
20945
21502
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
20946
- swarm$1.loggerService.log(METHOD_NAME$x, {
21503
+ swarm$1.loggerService.log(METHOD_NAME$y, {
20947
21504
  clientId,
20948
21505
  swarmName,
20949
21506
  });
20950
21507
  // Validate the swarm and initialize the session
20951
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$x);
21508
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$y);
20952
21509
  swarm$1.sessionValidationService.addSession(clientId, swarmName, "makeConnection");
20953
21510
  // Create a queued send function using the session public service
20954
- const send = functoolsKit.queued(swarm$1.sessionPublicService.connect(connector, METHOD_NAME$x, clientId, swarmName));
21511
+ const send = functoolsKit.queued(swarm$1.sessionPublicService.connect(connector, METHOD_NAME$y, clientId, swarmName));
20955
21512
  // Return a wrapped send function with validation and agent context
20956
21513
  return (async (outgoing) => {
20957
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$x);
21514
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$y);
20958
21515
  return await send({
20959
21516
  data: outgoing,
20960
- agentName: await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$x, clientId, swarmName),
21517
+ agentName: await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$y, clientId, swarmName),
20961
21518
  clientId,
20962
21519
  });
20963
21520
  });
@@ -21031,13 +21588,13 @@ makeConnection.scheduled = (connector, clientId, swarmName, { delay = SCHEDULED_
21031
21588
  await online();
21032
21589
  if (payload) {
21033
21590
  return await PayloadContextService.runInContext(async () => {
21034
- await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$x, clientId, swarmName);
21591
+ await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$y, clientId, swarmName);
21035
21592
  }, {
21036
21593
  clientId,
21037
21594
  payload,
21038
21595
  });
21039
21596
  }
21040
- await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$x, clientId, swarmName);
21597
+ await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$y, clientId, swarmName);
21041
21598
  }),
21042
21599
  delay,
21043
21600
  });
@@ -21095,7 +21652,7 @@ makeConnection.rate = (connector, clientId, swarmName, { delay = RATE_DELAY } =
21095
21652
  };
21096
21653
  };
21097
21654
 
21098
- const METHOD_NAME$w = "function.target.complete";
21655
+ const METHOD_NAME$x = "function.target.complete";
21099
21656
  /**
21100
21657
  * Creates a complete function with time-to-live (TTL) and queuing capabilities.
21101
21658
  *
@@ -21140,7 +21697,7 @@ const complete = beginContext(async (content, clientId, swarmName, payload = nul
21140
21697
  const executionId = functoolsKit.randomString();
21141
21698
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21142
21699
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21143
- swarm$1.loggerService.log(METHOD_NAME$w, {
21700
+ swarm$1.loggerService.log(METHOD_NAME$x, {
21144
21701
  content,
21145
21702
  clientId,
21146
21703
  executionId,
@@ -21158,7 +21715,7 @@ const complete = beginContext(async (content, clientId, swarmName, payload = nul
21158
21715
  swarm$1.navigationValidationService.beginMonit(clientId, swarmName);
21159
21716
  try {
21160
21717
  swarm$1.busService.commitExecutionBegin(clientId, { swarmName });
21161
- const result = await run(METHOD_NAME$w, content);
21718
+ const result = await run(METHOD_NAME$x, content);
21162
21719
  isFinished = swarm$1.perfService.endExecution(executionId, clientId, result.length);
21163
21720
  swarm$1.busService.commitExecutionEnd(clientId, { swarmName });
21164
21721
  return result;
@@ -21189,7 +21746,7 @@ const complete = beginContext(async (content, clientId, swarmName, payload = nul
21189
21746
  * @constant {number}
21190
21747
  */
21191
21748
  const SCHEDULED_DELAY = 1000;
21192
- const METHOD_NAME$v = "function.target.session";
21749
+ const METHOD_NAME$w = "function.target.session";
21193
21750
  /**
21194
21751
  * Internal implementation of the session factory for a client and swarm.
21195
21752
  *
@@ -21201,23 +21758,33 @@ const sessionInternal = (clientId, swarmName, { onDispose = () => { } } = {}) =>
21201
21758
  const executionId = functoolsKit.randomString();
21202
21759
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21203
21760
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21204
- swarm$1.loggerService.log(METHOD_NAME$v, {
21761
+ swarm$1.loggerService.log(METHOD_NAME$w, {
21205
21762
  clientId,
21206
21763
  swarmName,
21207
21764
  executionId,
21208
21765
  });
21209
21766
  // Validate the swarm and initialize the session
21210
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$v);
21767
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$w);
21211
21768
  swarm$1.sessionValidationService.addSession(clientId, swarmName, "session");
21212
21769
  const complete = functoolsKit.queued(async (content) => {
21213
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$v);
21770
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$w);
21214
21771
  return ExecutionContextService.runInContext(async () => {
21215
21772
  let isFinished = false;
21216
21773
  swarm$1.perfService.startExecution(executionId, clientId, content.length);
21217
21774
  swarm$1.navigationValidationService.beginMonit(clientId, swarmName);
21218
21775
  try {
21219
21776
  swarm$1.busService.commitExecutionBegin(clientId, { swarmName });
21220
- const result = await swarm$1.sessionPublicService.execute(content, "user", METHOD_NAME$v, clientId, swarmName);
21777
+ let errorValue = null;
21778
+ const unError = errorSubject.subscribe(([errorClientId, error]) => {
21779
+ if (clientId === errorClientId) {
21780
+ errorValue = error;
21781
+ }
21782
+ });
21783
+ const result = await swarm$1.sessionPublicService.execute(content, "user", METHOD_NAME$w, clientId, swarmName);
21784
+ unError();
21785
+ if (errorValue) {
21786
+ throw errorValue;
21787
+ }
21221
21788
  isFinished = swarm$1.perfService.endExecution(executionId, clientId, result.length);
21222
21789
  swarm$1.busService.commitExecutionEnd(clientId, { swarmName });
21223
21790
  return result;
@@ -21239,7 +21806,7 @@ const sessionInternal = (clientId, swarmName, { onDispose = () => { } } = {}) =>
21239
21806
  return await complete(content);
21240
21807
  }),
21241
21808
  dispose: async () => {
21242
- await disposeConnection(clientId, swarmName, METHOD_NAME$v);
21809
+ await disposeConnection(clientId, swarmName, METHOD_NAME$w);
21243
21810
  await onDispose();
21244
21811
  },
21245
21812
  };
@@ -21332,13 +21899,13 @@ session.scheduled = (clientId, swarmName, { delay = SCHEDULED_DELAY, onDispose }
21332
21899
  await online();
21333
21900
  if (payload) {
21334
21901
  return await PayloadContextService.runInContext(async () => {
21335
- return await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$v, clientId, swarmName);
21902
+ return await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$w, clientId, swarmName);
21336
21903
  }, {
21337
21904
  clientId,
21338
21905
  payload,
21339
21906
  });
21340
21907
  }
21341
- return await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$v, clientId, swarmName);
21908
+ return await swarm$1.sessionPublicService.commitUserMessage(content, "user", METHOD_NAME$w, clientId, swarmName);
21342
21909
  }),
21343
21910
  delay,
21344
21911
  });
@@ -21422,13 +21989,13 @@ session.rate = (clientId, swarmName, { delay = SCHEDULED_DELAY, onDispose } = {}
21422
21989
  * Method name for the scope operation.
21423
21990
  * @private
21424
21991
  */
21425
- const METHOD_NAME$u = "function.target.fork";
21992
+ const METHOD_NAME$v = "function.target.fork";
21426
21993
  /**
21427
21994
  * Function implementation
21428
21995
  */
21429
21996
  const forkInternal = beginContext(async (runFn, { clientId, swarmName, onError }) => {
21430
21997
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21431
- swarm$1.loggerService.log(METHOD_NAME$u, {
21998
+ swarm$1.loggerService.log(METHOD_NAME$v, {
21432
21999
  clientId,
21433
22000
  swarmName,
21434
22001
  });
@@ -21436,9 +22003,9 @@ const forkInternal = beginContext(async (runFn, { clientId, swarmName, onError }
21436
22003
  throw new Error(`agent-swarm scope Session already exists for clientId=${clientId}`);
21437
22004
  }
21438
22005
  swarm$1.sessionValidationService.addSession(clientId, swarmName, "scope");
21439
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$u);
21440
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$u);
21441
- const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$u, clientId, swarmName);
22006
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$v);
22007
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$v);
22008
+ const agentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$v, clientId, swarmName);
21442
22009
  let result = null;
21443
22010
  try {
21444
22011
  result = (await runFn(clientId, agentName));
@@ -21448,7 +22015,7 @@ const forkInternal = beginContext(async (runFn, { clientId, swarmName, onError }
21448
22015
  onError && onError(error);
21449
22016
  }
21450
22017
  finally {
21451
- await disposeConnection(clientId, swarmName, METHOD_NAME$u);
22018
+ await disposeConnection(clientId, swarmName, METHOD_NAME$v);
21452
22019
  }
21453
22020
  return result;
21454
22021
  });
@@ -21473,12 +22040,12 @@ async function fork(runFn, options) {
21473
22040
  * Method name for the scope operation.
21474
22041
  * @private
21475
22042
  */
21476
- const METHOD_NAME$t = "function.target.scope";
22043
+ const METHOD_NAME$u = "function.target.scope";
21477
22044
  /**
21478
22045
  * Function implementation
21479
22046
  */
21480
22047
  const scopeInternal = beginContext(async (runFn, { agentSchemaService = swarm$1.agentSchemaService.registry, completionSchemaService = swarm$1.completionSchemaService.registry, computeSchemaService = swarm$1.computeSchemaService.registry, embeddingSchemaService = swarm$1.embeddingSchemaService.registry, mcpSchemaService = swarm$1.mcpSchemaService.registry, pipelineSchemaService = swarm$1.pipelineSchemaService.registry, policySchemaService = swarm$1.policySchemaService.registry, stateSchemaService = swarm$1.stateSchemaService.registry, storageSchemaService = swarm$1.storageSchemaService.registry, swarmSchemaService = swarm$1.swarmSchemaService.registry, toolSchemaService = swarm$1.toolSchemaService.registry, advisorSchemaService = swarm$1.advisorSchemaService.registry, outlineSchemaService = swarm$1.outlineSchemaService.registry, } = {}) => {
21481
- GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$t);
22048
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG && swarm$1.loggerService.log(METHOD_NAME$u);
21482
22049
  return await SchemaContextService.runInContext(runFn, {
21483
22050
  registry: {
21484
22051
  agentSchemaService,
@@ -21517,20 +22084,20 @@ async function scope(runFn, options) {
21517
22084
  * Method name for the startPipeline operation.
21518
22085
  * @private
21519
22086
  */
21520
- const METHOD_NAME$s = "function.target.startPipeline";
22087
+ const METHOD_NAME$t = "function.target.startPipeline";
21521
22088
  /**
21522
22089
  * Function implementation
21523
22090
  */
21524
22091
  const startPipelineInternal = beginContext(async (clientId, pipelineName, agentName, payload = {}) => {
21525
22092
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21526
- swarm$1.loggerService.log(METHOD_NAME$s, {
22093
+ swarm$1.loggerService.log(METHOD_NAME$t, {
21527
22094
  clientId,
21528
22095
  pipelineName,
21529
22096
  });
21530
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$s);
21531
- swarm$1.pipelineValidationService.validate(pipelineName, METHOD_NAME$s);
21532
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$s);
21533
- const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$s, clientId, await swarm$1.sessionValidationService.getSwarm(clientId));
22097
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$t);
22098
+ swarm$1.pipelineValidationService.validate(pipelineName, METHOD_NAME$t);
22099
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$t);
22100
+ const currentAgentName = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$t, clientId, await swarm$1.sessionValidationService.getSwarm(clientId));
21534
22101
  if (currentAgentName !== agentName) {
21535
22102
  await changeToAgent(agentName, clientId);
21536
22103
  }
@@ -21575,13 +22142,13 @@ async function startPipeline(clientId, pipelineName, agentName, payload) {
21575
22142
  }
21576
22143
 
21577
22144
  /** @private Constant defining the method name for logging purposes*/
21578
- const METHOD_NAME$r = "function.common.hasSession";
22145
+ const METHOD_NAME$s = "function.common.hasSession";
21579
22146
  /**
21580
22147
  * Function implementation
21581
22148
  */
21582
22149
  const hasSessionInternal = (clientId) => {
21583
22150
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21584
- swarm$1.loggerService.log(METHOD_NAME$r, { clientId });
22151
+ swarm$1.loggerService.log(METHOD_NAME$s, { clientId });
21585
22152
  return swarm$1.sessionValidationService.hasSession(clientId);
21586
22153
  };
21587
22154
  /**
@@ -21596,22 +22163,22 @@ function hasSession(clientId) {
21596
22163
  return hasSessionInternal(clientId);
21597
22164
  }
21598
22165
 
21599
- const METHOD_NAME$q = "function.common.getCheckBusy";
22166
+ const METHOD_NAME$r = "function.common.getCheckBusy";
21600
22167
  /**
21601
22168
  * Function implementation
21602
22169
  */
21603
22170
  const getCheckBusyInternal = beginContext(async (clientId) => {
21604
22171
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21605
- swarm$1.loggerService.log(METHOD_NAME$q, {
22172
+ swarm$1.loggerService.log(METHOD_NAME$r, {
21606
22173
  clientId,
21607
22174
  });
21608
22175
  if (!swarm$1.sessionValidationService.hasSession(clientId)) {
21609
22176
  return false;
21610
22177
  }
21611
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$q);
22178
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$r);
21612
22179
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
21613
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$q);
21614
- return await swarm$1.swarmPublicService.getCheckBusy(METHOD_NAME$q, clientId, swarmName);
22180
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$r);
22181
+ return await swarm$1.swarmPublicService.getCheckBusy(METHOD_NAME$r, clientId, swarmName);
21615
22182
  });
21616
22183
  /**
21617
22184
  * Checks if the swarm associated with the given client ID is currently busy.
@@ -21622,20 +22189,20 @@ async function getCheckBusy(clientId) {
21622
22189
  return await getCheckBusyInternal(clientId);
21623
22190
  }
21624
22191
 
21625
- const METHOD_NAME$p = "function.common.getAgentHistory";
22192
+ const METHOD_NAME$q = "function.common.getAgentHistory";
21626
22193
  /**
21627
22194
  * Function implementation
21628
22195
  */
21629
22196
  const getAgentHistoryInternal = beginContext(async (clientId, agentName) => {
21630
22197
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21631
22198
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21632
- swarm$1.loggerService.log(METHOD_NAME$p, {
22199
+ swarm$1.loggerService.log(METHOD_NAME$q, {
21633
22200
  clientId,
21634
22201
  agentName,
21635
22202
  });
21636
22203
  // Validate the session and agent to ensure they exist and are accessible
21637
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$p);
21638
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$p);
22204
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$q);
22205
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$q);
21639
22206
  // Retrieve the agent's prompt configuration from the agent schema service
21640
22207
  const { prompt: upperPrompt } = swarm$1.agentSchemaService.get(agentName);
21641
22208
  const prompt = upperPrompt
@@ -21644,7 +22211,7 @@ const getAgentHistoryInternal = beginContext(async (clientId, agentName) => {
21644
22211
  : await upperPrompt(clientId, agentName)
21645
22212
  : "";
21646
22213
  // Fetch the agent's history using the prompt and rescue tweaks via the history public service
21647
- const history = await swarm$1.historyPublicService.toArrayForAgent(prompt, METHOD_NAME$p, clientId, agentName);
22214
+ const history = await swarm$1.historyPublicService.toArrayForAgent(prompt, METHOD_NAME$q, clientId, agentName);
21648
22215
  // Return a shallow copy of the history array
21649
22216
  return [...history];
21650
22217
  });
@@ -21667,17 +22234,17 @@ async function getAgentHistory(clientId, agentName) {
21667
22234
  return await getAgentHistoryInternal(clientId, agentName);
21668
22235
  }
21669
22236
 
21670
- const METHOD_NAME$o = "function.common.getSessionMode";
22237
+ const METHOD_NAME$p = "function.common.getSessionMode";
21671
22238
  const getSessionModeInternal = beginContext(async (clientId) => {
21672
22239
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21673
22240
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21674
- swarm$1.loggerService.log(METHOD_NAME$o, {
22241
+ swarm$1.loggerService.log(METHOD_NAME$p, {
21675
22242
  clientId,
21676
22243
  });
21677
22244
  // Validate the session and swarm to ensure they exist and are accessible
21678
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$o);
22245
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$p);
21679
22246
  const swarmName = swarm$1.sessionValidationService.getSwarm(clientId);
21680
- swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$o);
22247
+ swarm$1.swarmValidationService.validate(swarmName, METHOD_NAME$p);
21681
22248
  // Retrieve the session mode from the session validation service
21682
22249
  return swarm$1.sessionValidationService.getSessionMode(clientId);
21683
22250
  });
@@ -21699,14 +22266,14 @@ async function getSessionMode(clientId) {
21699
22266
  return await getSessionModeInternal(clientId);
21700
22267
  }
21701
22268
 
21702
- const METHOD_NAME$n = "function.common.getSessionContext";
22269
+ const METHOD_NAME$o = "function.common.getSessionContext";
21703
22270
  /**
21704
22271
  * Function implementation
21705
22272
  */
21706
22273
  const getSessionContextInternal = async () => {
21707
22274
  // Log the operation if logging is enabled in GLOBAL_CONFIG
21708
22275
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21709
- swarm$1.loggerService.log(METHOD_NAME$n);
22276
+ swarm$1.loggerService.log(METHOD_NAME$o);
21710
22277
  // Determine the method context, if active
21711
22278
  const methodContext = MethodContextService.hasContext()
21712
22279
  ? swarm$1.methodContextService.context
@@ -21745,17 +22312,17 @@ async function getSessionContext() {
21745
22312
  * @private Constant defining the method name for logging purposes.
21746
22313
  * Used as an identifier in log messages to track calls to `getNavigationRoute`.
21747
22314
  */
21748
- const METHOD_NAME$m = "function.common.getNavigationRoute";
22315
+ const METHOD_NAME$n = "function.common.getNavigationRoute";
21749
22316
  /**
21750
22317
  * Function implementation
21751
22318
  */
21752
22319
  const getNavigationRouteInternal = (clientId, swarmName) => {
21753
22320
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21754
- swarm$1.loggerService.log(METHOD_NAME$m, {
22321
+ swarm$1.loggerService.log(METHOD_NAME$n, {
21755
22322
  clientId,
21756
22323
  swarmName,
21757
22324
  });
21758
- swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$m);
22325
+ swarm$1.sessionValidationService.validate(clientId, METHOD_NAME$n);
21759
22326
  return swarm$1.navigationValidationService.getNavigationRoute(clientId, swarmName);
21760
22327
  };
21761
22328
  /**
@@ -21773,7 +22340,7 @@ function getNavigationRoute(clientId, swarmName) {
21773
22340
  * Provides a utility to retrieve the model-facing name of a tool for a given agent and client context.
21774
22341
  * Validates tool and agent existence, logs the operation if enabled, and supports both static and dynamic tool name resolution.
21775
22342
  */
21776
- const METHOD_NAME$l = "function.common.getToolNameForModel";
22343
+ const METHOD_NAME$m = "function.common.getToolNameForModel";
21777
22344
  /**
21778
22345
  * Internal implementation for resolving the model-facing tool name.
21779
22346
  * Validates the tool and agent, logs the operation, and invokes the tool schema's function property if dynamic.
@@ -21782,13 +22349,13 @@ const METHOD_NAME$l = "function.common.getToolNameForModel";
21782
22349
  */
21783
22350
  const getToolNameForModelInternal = beginContext(async (toolName, clientId, agentName) => {
21784
22351
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21785
- swarm$1.loggerService.log(METHOD_NAME$l, {
22352
+ swarm$1.loggerService.log(METHOD_NAME$m, {
21786
22353
  toolName,
21787
22354
  clientId,
21788
22355
  agentName,
21789
22356
  });
21790
- swarm$1.toolValidationService.validate(toolName, METHOD_NAME$l);
21791
- swarm$1.agentValidationService.validate(agentName, METHOD_NAME$l);
22357
+ swarm$1.toolValidationService.validate(toolName, METHOD_NAME$m);
22358
+ swarm$1.agentValidationService.validate(agentName, METHOD_NAME$m);
21792
22359
  const { function: fn } = swarm$1.toolSchemaService.get(toolName);
21793
22360
  if (typeof fn === "function") {
21794
22361
  const { name } = await fn(clientId, agentName);
@@ -21811,18 +22378,18 @@ async function getToolNameForModel(toolName, clientId, agentName) {
21811
22378
  return await getToolNameForModelInternal(toolName, clientId, agentName);
21812
22379
  }
21813
22380
 
21814
- const METHOD_NAME$k = "function.history.getUserHistory";
22381
+ const METHOD_NAME$l = "function.history.getUserHistory";
21815
22382
  /**
21816
22383
  * Function implementation
21817
22384
  */
21818
22385
  const getUserHistoryInternal = beginContext(async (clientId) => {
21819
22386
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21820
22387
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21821
- swarm$1.loggerService.log(METHOD_NAME$k, {
22388
+ swarm$1.loggerService.log(METHOD_NAME$l, {
21822
22389
  clientId,
21823
22390
  });
21824
22391
  // Fetch raw history and filter for user role and mode
21825
- const history = await getRawHistoryInternal(clientId, METHOD_NAME$k);
22392
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$l);
21826
22393
  return history.filter(({ role, mode }) => role === "user" && mode === "user");
21827
22394
  });
21828
22395
  /**
@@ -21843,18 +22410,18 @@ async function getUserHistory(clientId) {
21843
22410
  return await getUserHistoryInternal(clientId);
21844
22411
  }
21845
22412
 
21846
- const METHOD_NAME$j = "function.history.getAssistantHistory";
22413
+ const METHOD_NAME$k = "function.history.getAssistantHistory";
21847
22414
  /**
21848
22415
  * Function implementation
21849
22416
  */
21850
22417
  const getAssistantHistoryInternal = beginContext(async (clientId) => {
21851
22418
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21852
22419
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21853
- swarm$1.loggerService.log(METHOD_NAME$j, {
22420
+ swarm$1.loggerService.log(METHOD_NAME$k, {
21854
22421
  clientId,
21855
22422
  });
21856
22423
  // Fetch raw history and filter for assistant role
21857
- const history = await getRawHistoryInternal(clientId, METHOD_NAME$j);
22424
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$k);
21858
22425
  return history.filter(({ role }) => role === "assistant");
21859
22426
  });
21860
22427
  /**
@@ -21875,18 +22442,18 @@ async function getAssistantHistory(clientId) {
21875
22442
  return await getAssistantHistoryInternal(clientId);
21876
22443
  }
21877
22444
 
21878
- const METHOD_NAME$i = "function.history.getLastAssistantMessage";
22445
+ const METHOD_NAME$j = "function.history.getLastAssistantMessage";
21879
22446
  /**
21880
22447
  * Function implementation
21881
22448
  */
21882
22449
  const getLastAssistantMessageInternal = beginContext(async (clientId) => {
21883
22450
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21884
22451
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21885
- swarm$1.loggerService.log(METHOD_NAME$i, {
22452
+ swarm$1.loggerService.log(METHOD_NAME$j, {
21886
22453
  clientId,
21887
22454
  });
21888
22455
  // Fetch raw history and find the last assistant message
21889
- const history = await getRawHistoryInternal(clientId, METHOD_NAME$i);
22456
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$j);
21890
22457
  const last = history.findLast(({ role }) => role === "assistant");
21891
22458
  return last?.content ? last.content : null;
21892
22459
  });
@@ -21908,18 +22475,18 @@ async function getLastAssistantMessage(clientId) {
21908
22475
  return await getLastAssistantMessageInternal(clientId);
21909
22476
  }
21910
22477
 
21911
- const METHOD_NAME$h = "function.history.getLastSystemMessage";
22478
+ const METHOD_NAME$i = "function.history.getLastSystemMessage";
21912
22479
  /**
21913
22480
  * Function implementation
21914
22481
  */
21915
22482
  const getLastSystemMessageInternal = beginContext(async (clientId) => {
21916
22483
  // Log the operation details if logging is enabled in GLOBAL_CONFIG
21917
22484
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
21918
- swarm$1.loggerService.log(METHOD_NAME$h, {
22485
+ swarm$1.loggerService.log(METHOD_NAME$i, {
21919
22486
  clientId,
21920
22487
  });
21921
22488
  // Fetch raw history and find the last system message
21922
- const history = await getRawHistoryInternal(clientId, METHOD_NAME$h);
22489
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$i);
21923
22490
  const last = history.findLast(({ role }) => role === "system");
21924
22491
  return last ? last.content : null;
21925
22492
  });
@@ -21941,6 +22508,39 @@ async function getLastSystemMessage(clientId) {
21941
22508
  return await getLastSystemMessageInternal(clientId);
21942
22509
  }
21943
22510
 
22511
+ const METHOD_NAME$h = "function.history.getLastToolMessage";
22512
+ /**
22513
+ * Function implementation
22514
+ */
22515
+ const getLastToolMessageInternal = beginContext(async (clientId) => {
22516
+ // Log the operation details if logging is enabled in GLOBAL_CONFIG
22517
+ GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
22518
+ swarm$1.loggerService.log(METHOD_NAME$h, {
22519
+ clientId,
22520
+ });
22521
+ // Fetch raw history and find the last tool message
22522
+ const history = await getRawHistoryInternal(clientId, METHOD_NAME$h);
22523
+ const last = history.findLast(({ role }) => role === "tool");
22524
+ return last?.content ? last.content : null;
22525
+ });
22526
+ /**
22527
+ * Retrieves the content of the most recent tool message from a client's session history.
22528
+ *
22529
+ * This function fetches the raw history for a specified client using `getRawHistory` and finds the last entry where the role is "tool".
22530
+ * It is wrapped in `beginContext` for a clean execution environment and logs the operation if enabled via `GLOBAL_CONFIG`. The result is the content
22531
+ * of the last tool message as a string, or `null` if no tool message exists in the history.
22532
+ *
22533
+ *
22534
+ * @param {string} clientId - The unique identifier of the client session.
22535
+ * @throws {Error} If `getRawHistory` fails due to session validation or history retrieval issues.
22536
+ * @example
22537
+ * const lastMessage = await getLastToolMessage("client-123");
22538
+ * console.log(lastMessage); // Outputs the last tool message or null
22539
+ */
22540
+ async function getLastToolMessage(clientId) {
22541
+ return await getLastToolMessageInternal(clientId);
22542
+ }
22543
+
21944
22544
  const METHOD_NAME$g = "function.dump.getAgent";
21945
22545
  /**
21946
22546
  * Retrieves an agent schema by its name from the swarm's agent schema service.
@@ -21989,7 +22589,7 @@ function getCompute(computeName) {
21989
22589
  return swarm$1.computeSchemaService.get(computeName);
21990
22590
  }
21991
22591
 
21992
- const METHOD_NAME$d = "function.dump.getEmbeding";
22592
+ const METHOD_NAME$d = "function.dump.getEmbedding";
21993
22593
  /**
21994
22594
  * Retrieves an embedding schema by its name from the swarm's embedding schema service.
21995
22595
  * Logs the operation if logging is enabled in the global configuration.
@@ -21997,7 +22597,7 @@ const METHOD_NAME$d = "function.dump.getEmbeding";
21997
22597
  * @function getEmbedding
21998
22598
  * @param {EmbeddingName} embeddingName - The name of the embedding.
21999
22599
  */
22000
- function getEmbeding(embeddingName) {
22600
+ function getEmbedding(embeddingName) {
22001
22601
  GLOBAL_CONFIG.CC_LOGGER_ENABLE_LOG &&
22002
22602
  swarm$1.loggerService.log(METHOD_NAME$d, {
22003
22603
  embeddingName,
@@ -22133,7 +22733,7 @@ function getAdvisor(advisorName) {
22133
22733
  return swarm$1.advisorSchemaService.get(advisorName);
22134
22734
  }
22135
22735
 
22136
- const METHOD_NAME$4 = "function.event.listenEvent";
22736
+ const METHOD_NAME$4 = "function.event.event";
22137
22737
  /**
22138
22738
  * Set of reserved event source names that cannot be used for custom events.
22139
22739
  * @constant {Set<EventSource>}
@@ -22238,7 +22838,16 @@ const listenEventInternal = beginContext((clientId, topicName, fn) => {
22238
22838
  // Validate the client ID
22239
22839
  validateClientId$g(clientId);
22240
22840
  // Subscribe to the event with a queued callback
22241
- return swarm$1.busService.subscribe(clientId, topicName, functoolsKit.queued(async ({ payload }) => await fn(payload)));
22841
+ return swarm$1.busService.subscribe(clientId, topicName, functoolsKit.queued(async ({ payload }) => {
22842
+ try {
22843
+ // A throwing listener must not reject the queued chain: that surfaces
22844
+ // as an unhandled rejection and can crash the host process.
22845
+ return await fn(payload);
22846
+ }
22847
+ catch (error) {
22848
+ console.error(`agent-swarm event listener error source=${METHOD_NAME$3} error=${functoolsKit.getErrorMessage(error)}`);
22849
+ }
22850
+ }));
22242
22851
  });
22243
22852
  /**
22244
22853
  * Subscribes to a custom event on the swarm bus service and executes a callback when the event is received.
@@ -22311,7 +22920,16 @@ const listenEventOnceInternal = beginContext((clientId, topicName, filterFn, fn)
22311
22920
  // Validate the client ID
22312
22921
  validateClientId$f(clientId);
22313
22922
  // Subscribe to the event for one occurrence with a filter and queued callback
22314
- return swarm$1.busService.once(clientId, topicName, ({ payload }) => filterFn(payload), functoolsKit.queued(async ({ payload }) => await fn(payload)));
22923
+ return swarm$1.busService.once(clientId, topicName, ({ payload }) => filterFn(payload), functoolsKit.queued(async ({ payload }) => {
22924
+ try {
22925
+ // A throwing listener must not reject the queued chain: that surfaces
22926
+ // as an unhandled rejection and can crash the host process.
22927
+ return await fn(payload);
22928
+ }
22929
+ catch (error) {
22930
+ console.error(`agent-swarm event listener error source=${METHOD_NAME$2} error=${functoolsKit.getErrorMessage(error)}`);
22931
+ }
22932
+ }));
22315
22933
  });
22316
22934
  /**
22317
22935
  * Subscribes to a custom event on the swarm bus service for a single occurrence, executing a callback when the event matches a filter.
@@ -22352,7 +22970,11 @@ const METHOD_NAME$1 = "function.navigate.changeToPrevAgent";
22352
22970
  * @function
22353
22971
  */
22354
22972
  const createChangeToPrevAgent = functoolsKit.memoize(([clientId]) => `${clientId}`, (clientId) => functoolsKit.queued(async (methodName, agentName, swarmName) => {
22355
- if (!swarm$1.navigationValidationService.shouldNavigate(agentName, clientId, swarmName)) {
22973
+ // Going back is legitimate by definition and naturally bounded by the
22974
+ // depth of the navigation stack, so the recursion route guard does not
22975
+ // apply here. Only a no-op transition to the current agent is skipped.
22976
+ const activeAgent = await swarm$1.swarmPublicService.getAgentName(METHOD_NAME$1, clientId, swarmName);
22977
+ if (agentName === activeAgent) {
22356
22978
  return false;
22357
22979
  }
22358
22980
  // Notify all agents in the swarm of the change
@@ -22457,7 +23079,16 @@ const listenAgentEvent = beginContext((clientId, fn) => {
22457
23079
  // Validate the client ID
22458
23080
  validateClientId$e(clientId);
22459
23081
  // Subscribe to agent events with a queued callback
22460
- return swarm$1.busService.subscribe(clientId, "agent-bus", functoolsKit.queued(async (e) => await fn(e)));
23082
+ return swarm$1.busService.subscribe(clientId, "agent-bus", functoolsKit.queued(async (e) => {
23083
+ try {
23084
+ // A throwing listener must not reject the queued chain: that surfaces
23085
+ // as an unhandled rejection and can crash the host process.
23086
+ return await fn(e);
23087
+ }
23088
+ catch (error) {
23089
+ console.error(`agent-swarm event listener error source=listenAgentEvent error=${functoolsKit.getErrorMessage(error)}`);
23090
+ }
23091
+ }));
22461
23092
  });
22462
23093
 
22463
23094
  /**
@@ -22495,7 +23126,16 @@ const listenHistoryEvent = beginContext((clientId, fn) => {
22495
23126
  // Validate the client ID
22496
23127
  validateClientId$d(clientId);
22497
23128
  // Subscribe to history events with a queued callback
22498
- return swarm$1.busService.subscribe(clientId, "history-bus", functoolsKit.queued(async (e) => await fn(e)));
23129
+ return swarm$1.busService.subscribe(clientId, "history-bus", functoolsKit.queued(async (e) => {
23130
+ try {
23131
+ // A throwing listener must not reject the queued chain: that surfaces
23132
+ // as an unhandled rejection and can crash the host process.
23133
+ return await fn(e);
23134
+ }
23135
+ catch (error) {
23136
+ console.error(`agent-swarm event listener error source=listenHistoryEvent error=${functoolsKit.getErrorMessage(error)}`);
23137
+ }
23138
+ }));
22499
23139
  });
22500
23140
 
22501
23141
  /**
@@ -22533,7 +23173,16 @@ const listenSessionEvent = beginContext((clientId, fn) => {
22533
23173
  // Validate the client ID
22534
23174
  validateClientId$c(clientId);
22535
23175
  // Subscribe to session events with a queued callback
22536
- return swarm$1.busService.subscribe(clientId, "session-bus", functoolsKit.queued(async (e) => await fn(e)));
23176
+ return swarm$1.busService.subscribe(clientId, "session-bus", functoolsKit.queued(async (e) => {
23177
+ try {
23178
+ // A throwing listener must not reject the queued chain: that surfaces
23179
+ // as an unhandled rejection and can crash the host process.
23180
+ return await fn(e);
23181
+ }
23182
+ catch (error) {
23183
+ console.error(`agent-swarm event listener error source=listenSessionEvent error=${functoolsKit.getErrorMessage(error)}`);
23184
+ }
23185
+ }));
22537
23186
  });
22538
23187
 
22539
23188
  /**
@@ -22571,7 +23220,16 @@ const listenStateEvent = beginContext((clientId, fn) => {
22571
23220
  // Validate the client ID
22572
23221
  validateClientId$b(clientId);
22573
23222
  // Subscribe to state events with a queued callback
22574
- return swarm$1.busService.subscribe(clientId, "state-bus", functoolsKit.queued(async (e) => await fn(e)));
23223
+ return swarm$1.busService.subscribe(clientId, "state-bus", functoolsKit.queued(async (e) => {
23224
+ try {
23225
+ // A throwing listener must not reject the queued chain: that surfaces
23226
+ // as an unhandled rejection and can crash the host process.
23227
+ return await fn(e);
23228
+ }
23229
+ catch (error) {
23230
+ console.error(`agent-swarm event listener error source=listenStateEvent error=${functoolsKit.getErrorMessage(error)}`);
23231
+ }
23232
+ }));
22575
23233
  });
22576
23234
 
22577
23235
  /**
@@ -22609,7 +23267,16 @@ const listenStorageEvent = beginContext((clientId, fn) => {
22609
23267
  // Validate the client ID
22610
23268
  validateClientId$a(clientId);
22611
23269
  // Subscribe to storage events with a queued callback
22612
- return swarm$1.busService.subscribe(clientId, "storage-bus", functoolsKit.queued(async (e) => await fn(e)));
23270
+ return swarm$1.busService.subscribe(clientId, "storage-bus", functoolsKit.queued(async (e) => {
23271
+ try {
23272
+ // A throwing listener must not reject the queued chain: that surfaces
23273
+ // as an unhandled rejection and can crash the host process.
23274
+ return await fn(e);
23275
+ }
23276
+ catch (error) {
23277
+ console.error(`agent-swarm event listener error source=listenStorageEvent error=${functoolsKit.getErrorMessage(error)}`);
23278
+ }
23279
+ }));
22613
23280
  });
22614
23281
 
22615
23282
  /**
@@ -22647,7 +23314,16 @@ const listenSwarmEvent = beginContext((clientId, fn) => {
22647
23314
  // Validate the client ID
22648
23315
  validateClientId$9(clientId);
22649
23316
  // Subscribe to swarm events with a queued callback
22650
- return swarm$1.busService.subscribe(clientId, "swarm-bus", functoolsKit.queued(async (e) => await fn(e)));
23317
+ return swarm$1.busService.subscribe(clientId, "swarm-bus", functoolsKit.queued(async (e) => {
23318
+ try {
23319
+ // A throwing listener must not reject the queued chain: that surfaces
23320
+ // as an unhandled rejection and can crash the host process.
23321
+ return await fn(e);
23322
+ }
23323
+ catch (error) {
23324
+ console.error(`agent-swarm event listener error source=listenSwarmEvent error=${functoolsKit.getErrorMessage(error)}`);
23325
+ }
23326
+ }));
22651
23327
  });
22652
23328
 
22653
23329
  /**
@@ -22685,7 +23361,16 @@ const listenPolicyEvent = beginContext((clientId, fn) => {
22685
23361
  // Validate the client ID
22686
23362
  validateClientId$8(clientId);
22687
23363
  // Subscribe to policy events with a queued callback
22688
- return swarm$1.busService.subscribe(clientId, "policy-bus", functoolsKit.queued(async (e) => await fn(e)));
23364
+ return swarm$1.busService.subscribe(clientId, "policy-bus", functoolsKit.queued(async (e) => {
23365
+ try {
23366
+ // A throwing listener must not reject the queued chain: that surfaces
23367
+ // as an unhandled rejection and can crash the host process.
23368
+ return await fn(e);
23369
+ }
23370
+ catch (error) {
23371
+ console.error(`agent-swarm event listener error source=listenPolicyEvent error=${functoolsKit.getErrorMessage(error)}`);
23372
+ }
23373
+ }));
22689
23374
  });
22690
23375
 
22691
23376
  /**
@@ -22728,7 +23413,16 @@ const listenAgentEventOnce = beginContext((clientId, filterFn, fn) => {
22728
23413
  // Validate the client ID
22729
23414
  validateClientId$7(clientId);
22730
23415
  // Subscribe to agent events for one occurrence with a filter and queued callback
22731
- return swarm$1.busService.once(clientId, "agent-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23416
+ return swarm$1.busService.once(clientId, "agent-bus", filterFn, functoolsKit.queued(async (e) => {
23417
+ try {
23418
+ // A throwing listener must not reject the queued chain: that surfaces
23419
+ // as an unhandled rejection and can crash the host process.
23420
+ return await fn(e);
23421
+ }
23422
+ catch (error) {
23423
+ console.error(`agent-swarm event listener error source=listenAgentEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23424
+ }
23425
+ }));
22732
23426
  });
22733
23427
 
22734
23428
  /**
@@ -22771,7 +23465,16 @@ const listenHistoryEventOnce = beginContext((clientId, filterFn, fn) => {
22771
23465
  // Validate the client ID
22772
23466
  validateClientId$6(clientId);
22773
23467
  // Subscribe to history events for one occurrence with a filter and queued callback
22774
- return swarm$1.busService.once(clientId, "history-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23468
+ return swarm$1.busService.once(clientId, "history-bus", filterFn, functoolsKit.queued(async (e) => {
23469
+ try {
23470
+ // A throwing listener must not reject the queued chain: that surfaces
23471
+ // as an unhandled rejection and can crash the host process.
23472
+ return await fn(e);
23473
+ }
23474
+ catch (error) {
23475
+ console.error(`agent-swarm event listener error source=listenHistoryEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23476
+ }
23477
+ }));
22775
23478
  });
22776
23479
 
22777
23480
  /**
@@ -22814,7 +23517,16 @@ const listenSessionEventOnce = beginContext((clientId, filterFn, fn) => {
22814
23517
  // Validate the client ID
22815
23518
  validateClientId$5(clientId);
22816
23519
  // Subscribe to session events for one occurrence with a filter and queued callback
22817
- return swarm$1.busService.once(clientId, "session-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23520
+ return swarm$1.busService.once(clientId, "session-bus", filterFn, functoolsKit.queued(async (e) => {
23521
+ try {
23522
+ // A throwing listener must not reject the queued chain: that surfaces
23523
+ // as an unhandled rejection and can crash the host process.
23524
+ return await fn(e);
23525
+ }
23526
+ catch (error) {
23527
+ console.error(`agent-swarm event listener error source=listenSessionEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23528
+ }
23529
+ }));
22818
23530
  });
22819
23531
 
22820
23532
  /**
@@ -22857,7 +23569,16 @@ const listenStateEventOnce = beginContext((clientId, filterFn, fn) => {
22857
23569
  // Validate the client ID
22858
23570
  validateClientId$4(clientId);
22859
23571
  // Subscribe to state events for one occurrence with a filter and queued callback
22860
- return swarm$1.busService.once(clientId, "state-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23572
+ return swarm$1.busService.once(clientId, "state-bus", filterFn, functoolsKit.queued(async (e) => {
23573
+ try {
23574
+ // A throwing listener must not reject the queued chain: that surfaces
23575
+ // as an unhandled rejection and can crash the host process.
23576
+ return await fn(e);
23577
+ }
23578
+ catch (error) {
23579
+ console.error(`agent-swarm event listener error source=listenStateEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23580
+ }
23581
+ }));
22861
23582
  });
22862
23583
 
22863
23584
  /**
@@ -22900,7 +23621,16 @@ const listenStorageEventOnce = beginContext((clientId, filterFn, fn) => {
22900
23621
  // Validate the client ID
22901
23622
  validateClientId$3(clientId);
22902
23623
  // Subscribe to storage events for one occurrence with a filter and queued callback
22903
- return swarm$1.busService.once(clientId, "storage-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23624
+ return swarm$1.busService.once(clientId, "storage-bus", filterFn, functoolsKit.queued(async (e) => {
23625
+ try {
23626
+ // A throwing listener must not reject the queued chain: that surfaces
23627
+ // as an unhandled rejection and can crash the host process.
23628
+ return await fn(e);
23629
+ }
23630
+ catch (error) {
23631
+ console.error(`agent-swarm event listener error source=listenStorageEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23632
+ }
23633
+ }));
22904
23634
  });
22905
23635
 
22906
23636
  /**
@@ -22943,7 +23673,16 @@ const listenSwarmEventOnce = beginContext((clientId, filterFn, fn) => {
22943
23673
  // Validate the client ID
22944
23674
  validateClientId$2(clientId);
22945
23675
  // Subscribe to swarm events for one occurrence with a filter and queued callback
22946
- return swarm$1.busService.once(clientId, "swarm-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23676
+ return swarm$1.busService.once(clientId, "swarm-bus", filterFn, functoolsKit.queued(async (e) => {
23677
+ try {
23678
+ // A throwing listener must not reject the queued chain: that surfaces
23679
+ // as an unhandled rejection and can crash the host process.
23680
+ return await fn(e);
23681
+ }
23682
+ catch (error) {
23683
+ console.error(`agent-swarm event listener error source=listenSwarmEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23684
+ }
23685
+ }));
22947
23686
  });
22948
23687
 
22949
23688
  /**
@@ -22986,7 +23725,16 @@ const listenExecutionEventOnce = beginContext((clientId, filterFn, fn) => {
22986
23725
  // Validate the client ID
22987
23726
  validateClientId$1(clientId);
22988
23727
  // Subscribe to execution events for one occurrence with a filter and queued callback
22989
- return swarm$1.busService.once(clientId, "execution-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23728
+ return swarm$1.busService.once(clientId, "execution-bus", filterFn, functoolsKit.queued(async (e) => {
23729
+ try {
23730
+ // A throwing listener must not reject the queued chain: that surfaces
23731
+ // as an unhandled rejection and can crash the host process.
23732
+ return await fn(e);
23733
+ }
23734
+ catch (error) {
23735
+ console.error(`agent-swarm event listener error source=listenExecutionEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23736
+ }
23737
+ }));
22990
23738
  });
22991
23739
 
22992
23740
  /**
@@ -23029,7 +23777,16 @@ const listenPolicyEventOnce = beginContext((clientId, filterFn, fn) => {
23029
23777
  // Validate the client ID
23030
23778
  validateClientId(clientId);
23031
23779
  // Subscribe to policy events for one occurrence with a filter and queued callback
23032
- return swarm$1.busService.once(clientId, "policy-bus", filterFn, functoolsKit.queued(async (e) => await fn(e)));
23780
+ return swarm$1.busService.once(clientId, "policy-bus", filterFn, functoolsKit.queued(async (e) => {
23781
+ try {
23782
+ // A throwing listener must not reject the queued chain: that surfaces
23783
+ // as an unhandled rejection and can crash the host process.
23784
+ return await fn(e);
23785
+ }
23786
+ catch (error) {
23787
+ console.error(`agent-swarm event listener error source=listenPolicyEventOnce error=${functoolsKit.getErrorMessage(error)}`);
23788
+ }
23789
+ }));
23033
23790
  });
23034
23791
 
23035
23792
  /** @private Constant for logging the call method in RoundRobin*/
@@ -23343,10 +24100,6 @@ class SharedStateUtils {
23343
24100
  */
23344
24101
  const SharedState = new SharedStateUtils();
23345
24102
 
23346
- /** @constant {number} INACTIVITY_CHECK - Interval for checking inactivity in milliseconds (1 minute)*/
23347
- const INACTIVITY_CHECK = 60 * 1000;
23348
- /** @constant {number} INACTIVITY_TIMEOUT - Timeout duration for inactivity in milliseconds (15 minutes)*/
23349
- const INACTIVITY_TIMEOUT = 15 * 60 * 1000;
23350
24103
  /**
23351
24104
  * @constant {Function} BEGIN_CHAT_FN
23352
24105
  * Function to begin a chat session
@@ -23406,7 +24159,7 @@ class ChatInstance {
23406
24159
  clientId: this.clientId,
23407
24160
  swarmName: this.swarmName,
23408
24161
  });
23409
- const isActive = now - this._lastActivity <= INACTIVITY_TIMEOUT;
24162
+ const isActive = now - this._lastActivity <= GLOBAL_CONFIG.CC_CHAT_INACTIVITY_TIMEOUT;
23410
24163
  this.callbacks.onCheckActivity &&
23411
24164
  this.callbacks.onCheckActivity(this.clientId, this.swarmName, isActive, this._lastActivity);
23412
24165
  return isActive;
@@ -23473,13 +24226,20 @@ class ChatUtils {
23473
24226
  const handleCleanup = async () => {
23474
24227
  const now = Date.now();
23475
24228
  for (const chat of this._chats.values()) {
23476
- if (await chat.checkLastActivity(now)) {
23477
- continue;
24229
+ try {
24230
+ if (await chat.checkLastActivity(now)) {
24231
+ continue;
24232
+ }
24233
+ await chat.dispose();
24234
+ }
24235
+ catch (error) {
24236
+ // The cleanup interval is fire-and-forget: a throwing user callback
24237
+ // (onDispose, onCheckActivity) must not become an unhandled rejection.
24238
+ console.error(`agent-swarm chat cleanup error error=${functoolsKit.getErrorMessage(error)}`);
23478
24239
  }
23479
- await chat.dispose();
23480
24240
  }
23481
24241
  };
23482
- setInterval(handleCleanup, INACTIVITY_CHECK);
24242
+ setInterval(handleCleanup, GLOBAL_CONFIG.CC_CHAT_INACTIVITY_CHECK);
23483
24243
  });
23484
24244
  /**
23485
24245
  * Gets or creates a chat instance for a client
@@ -23721,8 +24481,18 @@ class StorageUtils {
23721
24481
  if (!swarm$1.agentValidationService.hasStorage(payload.agentName, payload.storageName)) {
23722
24482
  throw new Error(`agent-swarm StorageUtils ${payload.storageName} not registered in ${payload.agentName} (createNumericIndex)`);
23723
24483
  }
23724
- const { length } = await swarm$1.storagePublicService.list(METHOD_NAME_CREATE_NUMERIC_INDEX, payload.clientId, payload.storageName);
23725
- return length + 1;
24484
+ const items = await swarm$1.storagePublicService.list(METHOD_NAME_CREATE_NUMERIC_INDEX, payload.clientId, payload.storageName);
24485
+ // length + 1 collides with surviving ids once anything was removed
24486
+ // (items [1,2,3] minus 1 -> length 2 -> next "3" overwrites live item 3),
24487
+ // so the next index must come from the maximum numeric id instead.
24488
+ let maxId = 0;
24489
+ for (const { id } of items) {
24490
+ const numericId = Number(id);
24491
+ if (!Number.isNaN(numericId)) {
24492
+ maxId = Math.max(maxId, numericId);
24493
+ }
24494
+ }
24495
+ return maxId + 1;
23726
24496
  });
23727
24497
  /**
23728
24498
  * Clears all items from the storage for a given client and agent.
@@ -24037,18 +24807,15 @@ class SchemaUtils {
24037
24807
  data,
24038
24808
  });
24039
24809
  const { mapKey = GLOBAL_CONFIG.CC_NAME_TO_TITLE, mapValue = (_, value) => value.slice(0, 50), } = map;
24810
+ // objectFlat emits ["", ""] entries as structural separators; render them
24811
+ // as blank lines instead of leaking "undefined: " into the model prompt.
24812
+ const mapEntry = ([key, value]) => key ? `${mapKey(key)}: ${mapValue(key, String(value))}` : "";
24040
24813
  if (Array.isArray(data)) {
24041
24814
  return data
24042
- .map((item) => objectFlat(item)
24043
- .map(([key, value]) => [mapKey(key), mapValue(key, String(value))])
24044
- .map(([key, value]) => `${key}: ${value}`)
24045
- .join("\n"))
24815
+ .map((item) => objectFlat(item).map(mapEntry).join("\n"))
24046
24816
  .join(`\n\n\n\n`);
24047
24817
  }
24048
- return objectFlat(data)
24049
- .map(([key, value]) => [mapKey(key), mapValue(key, String(value))])
24050
- .map(([key, value]) => `${key}: ${value}`)
24051
- .join("\n");
24818
+ return objectFlat(data).map(mapEntry).join("\n");
24052
24819
  };
24053
24820
  }
24054
24821
  }
@@ -24889,6 +25656,7 @@ exports.SharedState = SharedState;
24889
25656
  exports.SharedStorage = SharedStorage;
24890
25657
  exports.State = State;
24891
25658
  exports.Storage = Storage;
25659
+ exports.TOOL_PROTOCOL_PROMPT = TOOL_PROTOCOL_PROMPT;
24892
25660
  exports.Utils = Utils;
24893
25661
  exports.addAdvisor = addAdvisor;
24894
25662
  exports.addAgent = addAgent;
@@ -24958,9 +25726,10 @@ exports.getAssistantHistory = getAssistantHistory;
24958
25726
  exports.getCheckBusy = getCheckBusy;
24959
25727
  exports.getCompletion = getCompletion;
24960
25728
  exports.getCompute = getCompute;
24961
- exports.getEmbeding = getEmbeding;
25729
+ exports.getEmbedding = getEmbedding;
24962
25730
  exports.getLastAssistantMessage = getLastAssistantMessage;
24963
25731
  exports.getLastSystemMessage = getLastSystemMessage;
25732
+ exports.getLastToolMessage = getLastToolMessage;
24964
25733
  exports.getLastUserMessage = getLastUserMessage;
24965
25734
  exports.getMCP = getMCP;
24966
25735
  exports.getNavigationRoute = getNavigationRoute;
@@ -25007,7 +25776,7 @@ exports.overrideAdvisor = overrideAdvisor;
25007
25776
  exports.overrideAgent = overrideAgent;
25008
25777
  exports.overrideCompletion = overrideCompletion;
25009
25778
  exports.overrideCompute = overrideCompute;
25010
- exports.overrideEmbeding = overrideEmbeding;
25779
+ exports.overrideEmbedding = overrideEmbedding;
25011
25780
  exports.overrideMCP = overrideMCP;
25012
25781
  exports.overrideOutline = overrideOutline;
25013
25782
  exports.overridePipeline = overridePipeline;