agent-swarm-kit 1.0.33 → 1.0.35

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
@@ -397,13 +397,11 @@ var CC_AGENT_DISALLOWED_SYMBOLS = [
397
397
  "}",
398
398
  ];
399
399
  var CC_KEEP_MESSAGES = 5;
400
- var CC_ANSWER_TIMEOUT = 120000;
401
400
  var CC_GET_AGENT_HISTORY = function () { return new functoolsKit.PubsubArrayAdapter(); };
402
401
  var GLOBAL_CONFIG = {
403
402
  CC_TOOL_CALL_EXCEPTION_PROMPT: CC_TOOL_CALL_EXCEPTION_PROMPT,
404
403
  CC_EMPTY_OUTPUT_PLACEHOLDERS: CC_EMPTY_OUTPUT_PLACEHOLDERS,
405
404
  CC_KEEP_MESSAGES: CC_KEEP_MESSAGES,
406
- CC_ANSWER_TIMEOUT: CC_ANSWER_TIMEOUT,
407
405
  CC_GET_AGENT_HISTORY: CC_GET_AGENT_HISTORY,
408
406
  CC_SWARM_AGENT_CHANGED: CC_SWARM_AGENT_CHANGED,
409
407
  CC_SWARM_DEFAULT_AGENT: CC_SWARM_DEFAULT_AGENT,
@@ -548,28 +546,28 @@ var ClientAgent = /** @class */ (function () {
548
546
  */
549
547
  this.getCompletion = function (mode) { return __awaiter(_this, void 0, void 0, function () {
550
548
  var messages, args, output;
551
- var _a;
552
- return __generator(this, function (_b) {
553
- switch (_b.label) {
549
+ var _a, _b, _c;
550
+ return __generator(this, function (_d) {
551
+ switch (_d.label) {
554
552
  case 0:
555
553
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " getCompletion"));
556
554
  return [4 /*yield*/, this.params.history.toArrayForAgent(this.params.prompt, this.params.system)];
557
555
  case 1:
558
- messages = _b.sent();
556
+ messages = _d.sent();
559
557
  args = {
560
558
  clientId: this.params.clientId,
561
559
  agentName: this.params.agentName,
562
560
  messages: messages,
563
561
  mode: mode,
564
562
  tools: (_a = this.params.tools) === null || _a === void 0 ? void 0 : _a.map(function (t) {
565
- return lodashEs.omit(t, "toolName", "call", "validate", "onCall", "onValidate");
563
+ return lodashEs.omit(t, "toolName", "call", "validate", "callbacks");
566
564
  }),
567
565
  };
568
566
  return [4 /*yield*/, this.params.completion.getCompletion(args)];
569
567
  case 2:
570
- output = _b.sent();
571
- this.params.completion.onComplete &&
572
- this.params.completion.onComplete(args, output);
568
+ output = _d.sent();
569
+ ((_b = this.params.completion.callbacks) === null || _b === void 0 ? void 0 : _b.onComplete) &&
570
+ ((_c = this.params.completion.callbacks) === null || _c === void 0 ? void 0 : _c.onComplete(args, output));
573
571
  return [2 /*return*/, output];
574
572
  }
575
573
  });
@@ -680,9 +678,9 @@ var ClientAgent = /** @class */ (function () {
680
678
  this.execute = functoolsKit.queued(function (incoming, mode) { return __awaiter(_this, void 0, void 0, function () {
681
679
  var message, _loop_1, this_1, _a, _b, tool, state_1, e_1_1, result, validation, result1;
682
680
  var e_1, _c;
683
- var _d;
684
- return __generator(this, function (_e) {
685
- switch (_e.label) {
681
+ var _d, _e, _f, _g, _h;
682
+ return __generator(this, function (_j) {
683
+ switch (_j.label) {
686
684
  case 0:
687
685
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute begin"), { incoming: incoming, mode: mode });
688
686
  this.params.onExecute &&
@@ -694,48 +692,49 @@ var ClientAgent = /** @class */ (function () {
694
692
  content: incoming.trim(),
695
693
  })];
696
694
  case 1:
697
- _e.sent();
695
+ _j.sent();
698
696
  return [4 /*yield*/, this.getCompletion(mode)];
699
697
  case 2:
700
- message = _e.sent();
698
+ message = _j.sent();
701
699
  if (!message.tool_calls) return [3 /*break*/, 11];
702
700
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " tool call begin"));
703
701
  _loop_1 = function (tool) {
704
702
  var targetFn, result_2, result_3;
705
- return __generator(this, function (_f) {
706
- switch (_f.label) {
703
+ return __generator(this, function (_k) {
704
+ switch (_k.label) {
707
705
  case 0:
708
706
  targetFn = (_d = this_1.params.tools) === null || _d === void 0 ? void 0 : _d.find(function (t) { return t.function.name === tool.function.name; });
709
707
  return [4 /*yield*/, this_1.params.history.push(__assign(__assign({}, message), { agentName: this_1.params.agentName }))];
710
708
  case 1:
711
- _f.sent();
709
+ _k.sent();
712
710
  if (!!targetFn) return [3 /*break*/, 4];
713
711
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool function not found"), this_1.params.tools);
714
712
  return [4 /*yield*/, this_1._resurrectModel(mode, "No target function for ".concat(tool.function.name))];
715
713
  case 2:
716
- result_2 = _f.sent();
714
+ result_2 = _k.sent();
717
715
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " execute end result=").concat(result_2));
718
716
  return [4 /*yield*/, this_1._emitOuput(mode, result_2)];
719
717
  case 3:
720
- _f.sent();
718
+ _k.sent();
721
719
  return [2 /*return*/, { value: void 0 }];
722
720
  case 4:
723
- targetFn.onValidate && targetFn.onValidate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments);
721
+ ((_e = targetFn.callbacks) === null || _e === void 0 ? void 0 : _e.onValidate) &&
722
+ ((_f = targetFn.callbacks) === null || _f === void 0 ? void 0 : _f.onValidate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments));
724
723
  return [4 /*yield*/, functoolsKit.not(targetFn.validate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments))];
725
724
  case 5:
726
- if (!_f.sent()) return [3 /*break*/, 8];
725
+ if (!_k.sent()) return [3 /*break*/, 8];
727
726
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool validation not passed"));
728
727
  return [4 /*yield*/, this_1._resurrectModel(mode, "Function validation failed: name=".concat(tool.function.name, " arguments=").concat(JSON.stringify(tool.function.arguments)))];
729
728
  case 6:
730
- result_3 = _f.sent();
729
+ result_3 = _k.sent();
731
730
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " execute end result=").concat(result_3));
732
731
  return [4 /*yield*/, this_1._emitOuput(mode, result_3)];
733
732
  case 7:
734
- _f.sent();
733
+ _k.sent();
735
734
  return [2 /*return*/, { value: void 0 }];
736
735
  case 8:
737
- targetFn.onCall &&
738
- targetFn.onCall(this_1.params.clientId, this_1.params.agentName, tool.function.arguments);
736
+ ((_g = targetFn.callbacks) === null || _g === void 0 ? void 0 : _g.onCall) &&
737
+ ((_h = targetFn.callbacks) === null || _h === void 0 ? void 0 : _h.onCall(this_1.params.clientId, this_1.params.agentName, tool.function.arguments));
739
738
  /**
740
739
  * @description Do not await to avoid deadlock! The tool can send the message to other agents by emulating user messages
741
740
  */
@@ -746,33 +745,33 @@ var ClientAgent = /** @class */ (function () {
746
745
  this_1._outputSubject.toPromise(),
747
746
  ])];
748
747
  case 9:
749
- _f.sent();
748
+ _k.sent();
750
749
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool call end"));
751
750
  return [2 /*return*/];
752
751
  }
753
752
  });
754
753
  };
755
754
  this_1 = this;
756
- _e.label = 3;
755
+ _j.label = 3;
757
756
  case 3:
758
- _e.trys.push([3, 8, 9, 10]);
757
+ _j.trys.push([3, 8, 9, 10]);
759
758
  _a = __values(message.tool_calls), _b = _a.next();
760
- _e.label = 4;
759
+ _j.label = 4;
761
760
  case 4:
762
761
  if (!!_b.done) return [3 /*break*/, 7];
763
762
  tool = _b.value;
764
763
  return [5 /*yield**/, _loop_1(tool)];
765
764
  case 5:
766
- state_1 = _e.sent();
765
+ state_1 = _j.sent();
767
766
  if (typeof state_1 === "object")
768
767
  return [2 /*return*/, state_1.value];
769
- _e.label = 6;
768
+ _j.label = 6;
770
769
  case 6:
771
770
  _b = _a.next();
772
771
  return [3 /*break*/, 4];
773
772
  case 7: return [3 /*break*/, 10];
774
773
  case 8:
775
- e_1_1 = _e.sent();
774
+ e_1_1 = _j.sent();
776
775
  e_1 = { error: e_1_1 };
777
776
  return [3 /*break*/, 10];
778
777
  case 9:
@@ -789,31 +788,44 @@ var ClientAgent = /** @class */ (function () {
789
788
  result = message.content;
790
789
  return [4 /*yield*/, this.params.history.push(__assign(__assign({}, message), { agentName: this.params.agentName }))];
791
790
  case 12:
792
- _e.sent();
791
+ _j.sent();
793
792
  validation = null;
794
793
  return [4 /*yield*/, this.params.validate(result)];
795
794
  case 13:
796
- if (!(validation = _e.sent())) return [3 /*break*/, 16];
795
+ if (!(validation = _j.sent())) return [3 /*break*/, 16];
797
796
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute invalid tool call detected: ").concat(validation), { result: result });
798
797
  return [4 /*yield*/, this._resurrectModel(mode, "Invalid model output: ".concat(result))];
799
798
  case 14:
800
- result1 = _e.sent();
799
+ result1 = _j.sent();
801
800
  return [4 /*yield*/, this._emitOuput(mode, result1)];
802
801
  case 15:
803
- _e.sent();
802
+ _j.sent();
804
803
  return [2 /*return*/];
805
804
  case 16:
806
805
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute end result=").concat(result));
807
806
  return [4 /*yield*/, this._emitOuput(mode, result)];
808
807
  case 17:
809
- _e.sent();
808
+ _j.sent();
810
809
  return [2 /*return*/];
811
810
  }
812
811
  });
813
812
  }); });
813
+ /**
814
+ * Should call on agent dispose
815
+ * @returns {Promise<void>}
816
+ */
817
+ this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
818
+ return __generator(this, function (_a) {
819
+ this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " dispose"));
820
+ this.params.onDispose &&
821
+ this.params.onDispose(this.params.clientId, this.params.agentName);
822
+ return [2 /*return*/];
823
+ });
824
+ }); };
814
825
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " CTOR"), {
815
826
  params: params,
816
827
  });
828
+ this.params.onInit && this.params.onInit(params.clientId, params.agentName);
817
829
  }
818
830
  return ClientAgent;
819
831
  }());
@@ -842,26 +854,10 @@ var AgentConnectionService = /** @class */ (function () {
842
854
  var _b = __read(_a, 2), clientId = _b[0], agentName = _b[1];
843
855
  return "".concat(clientId, "-").concat(agentName);
844
856
  }, function (clientId, agentName) {
845
- var _a = _this.agentSchemaService.get(agentName), prompt = _a.prompt, system = _a.system, tools = _a.tools, onExecute = _a.onExecute, onOutput = _a.onOutput, onResurrect = _a.onResurrect, onSystemMessage = _a.onSystemMessage, onToolOutput = _a.onToolOutput, onUserMessage = _a.onUserMessage, completionName = _a.completion, _b = _a.validate, validate = _b === void 0 ? validateDefault : _b;
857
+ var _a = _this.agentSchemaService.get(agentName), prompt = _a.prompt, system = _a.system, tools = _a.tools, callbacks = _a.callbacks, completionName = _a.completion, _b = _a.validate, validate = _b === void 0 ? validateDefault : _b;
846
858
  var completion = _this.completionSchemaService.get(completionName);
847
859
  _this.sessionValidationService.addAgentUsage(clientId, agentName);
848
- return new ClientAgent({
849
- clientId: clientId,
850
- agentName: agentName,
851
- validate: validate,
852
- logger: _this.loggerService,
853
- history: _this.historyConnectionService.getHistory(clientId, agentName),
854
- prompt: prompt,
855
- system: system,
856
- tools: tools === null || tools === void 0 ? void 0 : tools.map(_this.toolSchemaService.get),
857
- completion: completion,
858
- onExecute: onExecute,
859
- onOutput: onOutput,
860
- onResurrect: onResurrect,
861
- onSystemMessage: onSystemMessage,
862
- onToolOutput: onToolOutput,
863
- onUserMessage: onUserMessage,
864
- });
860
+ return new ClientAgent(__assign({ clientId: clientId, agentName: agentName, validate: validate, logger: _this.loggerService, history: _this.historyConnectionService.getHistory(clientId, agentName), prompt: prompt, system: system, tools: tools === null || tools === void 0 ? void 0 : tools.map(_this.toolSchemaService.get), completion: completion }, callbacks));
865
861
  });
866
862
  /**
867
863
  * Executes an input command.
@@ -974,12 +970,18 @@ var AgentConnectionService = /** @class */ (function () {
974
970
  */
975
971
  this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
976
972
  return __generator(this, function (_a) {
977
- this.loggerService.log("agentConnectionService dispose", {
978
- context: this.contextService.context,
979
- });
980
- this.getAgent.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.agentName));
981
- this.sessionValidationService.removeAgentUsage(this.contextService.context.clientId, this.contextService.context.agentName);
982
- return [2 /*return*/];
973
+ switch (_a.label) {
974
+ case 0:
975
+ this.loggerService.log("agentConnectionService dispose", {
976
+ context: this.contextService.context,
977
+ });
978
+ return [4 /*yield*/, this.getAgent(this.contextService.context.clientId, this.contextService.context.agentName).dispose()];
979
+ case 1:
980
+ _a.sent();
981
+ this.getAgent.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.agentName));
982
+ this.sessionValidationService.removeAgentUsage(this.contextService.context.clientId, this.contextService.context.agentName);
983
+ return [2 /*return*/];
984
+ }
983
985
  });
984
986
  }); };
985
987
  }
@@ -1321,7 +1323,6 @@ var ToolSchemaService = /** @class */ (function () {
1321
1323
  return ToolSchemaService;
1322
1324
  }());
1323
1325
 
1324
- var AGENT_REF_CHANGED = Symbol("agent-ref-changed");
1325
1326
  var AGENT_NEED_FETCH = Symbol("agent-need-fetch");
1326
1327
  /**
1327
1328
  * ClientSwarm class implements the ISwarm interface and manages agents within a swarm.
@@ -1342,47 +1343,53 @@ var ClientSwarm = /** @class */ (function () {
1342
1343
  * @throws {Error} - If the timeout is reached.
1343
1344
  */
1344
1345
  this.waitForOutput = functoolsKit.queued(function () { return __awaiter(_this, void 0, void 0, function () {
1345
- var START_TIME, _a, agentName, output, _b;
1346
+ var _a, awaiter, resolve, getOutput, handleOutput, un, _b, agentName, output, expectAgent;
1346
1347
  var _this = this;
1347
1348
  return __generator(this, function (_c) {
1348
1349
  switch (_c.label) {
1349
1350
  case 0:
1350
1351
  this.params.logger.debug("ClientSwarm swarmName=".concat(this.params.swarmName, " clientId=").concat(this.params.clientId, " waitForOutput"));
1351
- START_TIME = Date.now();
1352
- _c.label = 1;
1352
+ _a = __read(functoolsKit.createAwaiter(), 2), awaiter = _a[0], resolve = _a[1].resolve;
1353
+ getOutput = functoolsKit.cancelable(function () { return __awaiter(_this, void 0, void 0, function () {
1354
+ var _this = this;
1355
+ return __generator(this, function (_a) {
1356
+ switch (_a.label) {
1357
+ case 0: return [4 /*yield*/, Promise.race(this._agentList.map(function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
1358
+ var _c;
1359
+ var _d = __read(_b, 2), agentName = _d[0], agent = _d[1];
1360
+ return __generator(this, function (_e) {
1361
+ switch (_e.label) {
1362
+ case 0:
1363
+ _c = { agentName: agentName };
1364
+ return [4 /*yield*/, agent.waitForOutput()];
1365
+ case 1: return [2 /*return*/, (_c.output = _e.sent(), _c)];
1366
+ }
1367
+ });
1368
+ }); }))];
1369
+ case 1: return [2 /*return*/, _a.sent()];
1370
+ }
1371
+ });
1372
+ }); });
1373
+ handleOutput = function () {
1374
+ getOutput.cancel();
1375
+ getOutput().then(function (value) {
1376
+ if (value === functoolsKit.CANCELED_PROMISE_SYMBOL) {
1377
+ return;
1378
+ }
1379
+ resolve(value);
1380
+ });
1381
+ };
1382
+ un = this._agentChangedSubject.subscribe(handleOutput);
1383
+ handleOutput();
1384
+ return [4 /*yield*/, awaiter];
1353
1385
  case 1:
1354
- if (Date.now() - START_TIME >= GLOBAL_CONFIG.CC_ANSWER_TIMEOUT) {
1355
- throw new Error("agent-swarm ClientSwarm waitForOutput timeout reached for ".concat(this.params.swarmName));
1356
- }
1357
- return [4 /*yield*/, Promise.race(__spreadArray(__spreadArray([], __read(Object.entries(this.params.agentMap).map(function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
1358
- var _c;
1359
- var _d = __read(_b, 2), agentName = _d[0], agent = _d[1];
1360
- return __generator(this, function (_e) {
1361
- switch (_e.label) {
1362
- case 0:
1363
- _c = [agentName];
1364
- return [4 /*yield*/, agent.waitForOutput()];
1365
- case 1: return [2 /*return*/, _c.concat([_e.sent()])];
1366
- }
1367
- });
1368
- }); })), false), [
1369
- this._agentChangedSubject
1370
- .toPromise()
1371
- .then(function () { return [AGENT_REF_CHANGED]; }),
1372
- ], false))];
1373
- case 2:
1374
- _a = __read.apply(void 0, [_c.sent(), 2]), agentName = _a[0], output = _a[1];
1375
- if (agentName === AGENT_REF_CHANGED) {
1376
- return [3 /*break*/, 1];
1377
- }
1378
- _b = agentName;
1386
+ _b = _c.sent(), agentName = _b.agentName, output = _b.output;
1387
+ un();
1379
1388
  return [4 /*yield*/, this.getAgentName()];
1380
- case 3:
1381
- if (_b === (_c.sent())) {
1382
- return [2 /*return*/, output];
1383
- }
1384
- return [3 /*break*/, 1];
1385
- case 4: return [2 /*return*/];
1389
+ case 2:
1390
+ expectAgent = _c.sent();
1391
+ agentName !== expectAgent && this.params.logger.debug("ClientSwarm swarmName=".concat(this.params.swarmName, " clientId=").concat(this.params.clientId, " waitForAgent agent miss"), { agentName: agentName, expectAgent: expectAgent });
1392
+ return [2 /*return*/, output];
1386
1393
  }
1387
1394
  });
1388
1395
  }); });
@@ -1438,7 +1445,7 @@ var ClientSwarm = /** @class */ (function () {
1438
1445
  throw new Error("agent-swarm agent ".concat(agentName, " not in the swarm"));
1439
1446
  }
1440
1447
  this.params.agentMap[agentName] = agent;
1441
- return [4 /*yield*/, this._agentChangedSubject.next()];
1448
+ return [4 /*yield*/, this._agentChangedSubject.next([agentName, agent])];
1442
1449
  case 1:
1443
1450
  _a.sent();
1444
1451
  return [2 /*return*/];
@@ -1466,6 +1473,13 @@ var ClientSwarm = /** @class */ (function () {
1466
1473
  params: params,
1467
1474
  });
1468
1475
  }
1476
+ Object.defineProperty(ClientSwarm.prototype, "_agentList", {
1477
+ get: function () {
1478
+ return Object.entries(this.params.agentMap);
1479
+ },
1480
+ enumerable: false,
1481
+ configurable: true
1482
+ });
1469
1483
  return ClientSwarm;
1470
1484
  }());
1471
1485
 
@@ -1491,7 +1505,7 @@ var SwarmConnectionService = /** @class */ (function () {
1491
1505
  return "".concat(clientId, "-").concat(swarmName);
1492
1506
  }, function (clientId, swarmName) {
1493
1507
  var e_1, _a;
1494
- var _b = _this.swarmSchemaService.get(swarmName), agentList = _b.agentList, defaultAgent = _b.defaultAgent, onAgentChanged = _b.onAgentChanged;
1508
+ var _b = _this.swarmSchemaService.get(swarmName), agentList = _b.agentList, defaultAgent = _b.defaultAgent, callbacks = _b.callbacks;
1495
1509
  var agentMap = {};
1496
1510
  try {
1497
1511
  for (var agentList_1 = __values(agentList), agentList_1_1 = agentList_1.next(); !agentList_1_1.done; agentList_1_1 = agentList_1.next()) {
@@ -1517,7 +1531,9 @@ var SwarmConnectionService = /** @class */ (function () {
1517
1531
  return __generator(this, function (_a) {
1518
1532
  switch (_a.label) {
1519
1533
  case 0:
1520
- onAgentChanged && onAgentChanged(clientId, agentName, swarmName);
1534
+ if (callbacks && callbacks.onAgentChanged) {
1535
+ callbacks.onAgentChanged(clientId, agentName, swarmName);
1536
+ }
1521
1537
  return [4 /*yield*/, GLOBAL_CONFIG.CC_SWARM_AGENT_CHANGED(clientId, agentName, swarmName)];
1522
1538
  case 1:
1523
1539
  _a.sent();
@@ -1882,9 +1898,22 @@ var ClientSession = /** @class */ (function () {
1882
1898
  });
1883
1899
  }); };
1884
1900
  };
1901
+ /**
1902
+ * Should call on session dispose
1903
+ * @returns {Promise<void>}
1904
+ */
1905
+ this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
1906
+ return __generator(this, function (_a) {
1907
+ this.params.logger.debug("ClientSession clientId=".concat(this.params.clientId, " dispose"));
1908
+ this.params.onDispose &&
1909
+ this.params.onDispose(this.params.clientId, this.params.swarmName);
1910
+ return [2 /*return*/];
1911
+ });
1912
+ }); };
1885
1913
  this.params.logger.debug("ClientSession clientId=".concat(this.params.clientId, " CTOR"), {
1886
1914
  params: params,
1887
1915
  });
1916
+ this.params.onInit && this.params.onInit(params.clientId, params.swarmName);
1888
1917
  }
1889
1918
  return ClientSession;
1890
1919
  }());
@@ -1910,16 +1939,8 @@ var SessionConnectionService = /** @class */ (function () {
1910
1939
  var _b = __read(_a, 2), clientId = _b[0], swarmName = _b[1];
1911
1940
  return "".concat(clientId, "-").concat(swarmName);
1912
1941
  }, function (clientId, swarmName) {
1913
- var _a = _this.swarmSchemaService.get(swarmName), onConnect = _a.onConnect, onEmit = _a.onEmit, onExecute = _a.onExecute;
1914
- return new ClientSession({
1915
- clientId: clientId,
1916
- logger: _this.loggerService,
1917
- swarm: _this.swarmConnectionService.getSwarm(clientId, swarmName),
1918
- swarmName: swarmName,
1919
- onConnect: onConnect,
1920
- onEmit: onEmit,
1921
- onExecute: onExecute,
1922
- });
1942
+ var callbacks = _this.swarmSchemaService.get(swarmName).callbacks;
1943
+ return new ClientSession(__assign({ clientId: clientId, logger: _this.loggerService, swarm: _this.swarmConnectionService.getSwarm(clientId, swarmName), swarmName: swarmName }, callbacks));
1923
1944
  });
1924
1945
  /**
1925
1946
  * Emits a message to the session.
@@ -2045,11 +2066,17 @@ var SessionConnectionService = /** @class */ (function () {
2045
2066
  */
2046
2067
  this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
2047
2068
  return __generator(this, function (_a) {
2048
- this.loggerService.log("sessionConnectionService dispose", {
2049
- context: this.contextService.context,
2050
- });
2051
- this.getSession.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.swarmName));
2052
- return [2 /*return*/];
2069
+ switch (_a.label) {
2070
+ case 0:
2071
+ this.loggerService.log("sessionConnectionService dispose", {
2072
+ context: this.contextService.context,
2073
+ });
2074
+ return [4 /*yield*/, this.getSession(this.contextService.context.clientId, this.contextService.context.swarmName).dispose()];
2075
+ case 1:
2076
+ _a.sent();
2077
+ this.getSession.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.swarmName));
2078
+ return [2 /*return*/];
2079
+ }
2053
2080
  });
2054
2081
  }); };
2055
2082
  }
package/build/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { scoped } from 'di-scoped';
2
- import { ToolRegistry, trycatch, sleep, PubsubArrayAdapter, Subject, queued, not, memoize, schedule, ttl, singleshot, Source } from 'functools-kit';
2
+ import { ToolRegistry, trycatch, sleep, PubsubArrayAdapter, Subject, queued, not, memoize, createAwaiter, cancelable, CANCELED_PROMISE_SYMBOL, schedule, ttl, singleshot, Source } from 'functools-kit';
3
3
  import { createActivator } from 'di-kit';
4
4
  import { omit } from 'lodash-es';
5
5
  import xml2js from 'xml2js';
@@ -395,13 +395,11 @@ var CC_AGENT_DISALLOWED_SYMBOLS = [
395
395
  "}",
396
396
  ];
397
397
  var CC_KEEP_MESSAGES = 5;
398
- var CC_ANSWER_TIMEOUT = 120000;
399
398
  var CC_GET_AGENT_HISTORY = function () { return new PubsubArrayAdapter(); };
400
399
  var GLOBAL_CONFIG = {
401
400
  CC_TOOL_CALL_EXCEPTION_PROMPT: CC_TOOL_CALL_EXCEPTION_PROMPT,
402
401
  CC_EMPTY_OUTPUT_PLACEHOLDERS: CC_EMPTY_OUTPUT_PLACEHOLDERS,
403
402
  CC_KEEP_MESSAGES: CC_KEEP_MESSAGES,
404
- CC_ANSWER_TIMEOUT: CC_ANSWER_TIMEOUT,
405
403
  CC_GET_AGENT_HISTORY: CC_GET_AGENT_HISTORY,
406
404
  CC_SWARM_AGENT_CHANGED: CC_SWARM_AGENT_CHANGED,
407
405
  CC_SWARM_DEFAULT_AGENT: CC_SWARM_DEFAULT_AGENT,
@@ -546,28 +544,28 @@ var ClientAgent = /** @class */ (function () {
546
544
  */
547
545
  this.getCompletion = function (mode) { return __awaiter(_this, void 0, void 0, function () {
548
546
  var messages, args, output;
549
- var _a;
550
- return __generator(this, function (_b) {
551
- switch (_b.label) {
547
+ var _a, _b, _c;
548
+ return __generator(this, function (_d) {
549
+ switch (_d.label) {
552
550
  case 0:
553
551
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " getCompletion"));
554
552
  return [4 /*yield*/, this.params.history.toArrayForAgent(this.params.prompt, this.params.system)];
555
553
  case 1:
556
- messages = _b.sent();
554
+ messages = _d.sent();
557
555
  args = {
558
556
  clientId: this.params.clientId,
559
557
  agentName: this.params.agentName,
560
558
  messages: messages,
561
559
  mode: mode,
562
560
  tools: (_a = this.params.tools) === null || _a === void 0 ? void 0 : _a.map(function (t) {
563
- return omit(t, "toolName", "call", "validate", "onCall", "onValidate");
561
+ return omit(t, "toolName", "call", "validate", "callbacks");
564
562
  }),
565
563
  };
566
564
  return [4 /*yield*/, this.params.completion.getCompletion(args)];
567
565
  case 2:
568
- output = _b.sent();
569
- this.params.completion.onComplete &&
570
- this.params.completion.onComplete(args, output);
566
+ output = _d.sent();
567
+ ((_b = this.params.completion.callbacks) === null || _b === void 0 ? void 0 : _b.onComplete) &&
568
+ ((_c = this.params.completion.callbacks) === null || _c === void 0 ? void 0 : _c.onComplete(args, output));
571
569
  return [2 /*return*/, output];
572
570
  }
573
571
  });
@@ -678,9 +676,9 @@ var ClientAgent = /** @class */ (function () {
678
676
  this.execute = queued(function (incoming, mode) { return __awaiter(_this, void 0, void 0, function () {
679
677
  var message, _loop_1, this_1, _a, _b, tool, state_1, e_1_1, result, validation, result1;
680
678
  var e_1, _c;
681
- var _d;
682
- return __generator(this, function (_e) {
683
- switch (_e.label) {
679
+ var _d, _e, _f, _g, _h;
680
+ return __generator(this, function (_j) {
681
+ switch (_j.label) {
684
682
  case 0:
685
683
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute begin"), { incoming: incoming, mode: mode });
686
684
  this.params.onExecute &&
@@ -692,48 +690,49 @@ var ClientAgent = /** @class */ (function () {
692
690
  content: incoming.trim(),
693
691
  })];
694
692
  case 1:
695
- _e.sent();
693
+ _j.sent();
696
694
  return [4 /*yield*/, this.getCompletion(mode)];
697
695
  case 2:
698
- message = _e.sent();
696
+ message = _j.sent();
699
697
  if (!message.tool_calls) return [3 /*break*/, 11];
700
698
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " tool call begin"));
701
699
  _loop_1 = function (tool) {
702
700
  var targetFn, result_2, result_3;
703
- return __generator(this, function (_f) {
704
- switch (_f.label) {
701
+ return __generator(this, function (_k) {
702
+ switch (_k.label) {
705
703
  case 0:
706
704
  targetFn = (_d = this_1.params.tools) === null || _d === void 0 ? void 0 : _d.find(function (t) { return t.function.name === tool.function.name; });
707
705
  return [4 /*yield*/, this_1.params.history.push(__assign(__assign({}, message), { agentName: this_1.params.agentName }))];
708
706
  case 1:
709
- _f.sent();
707
+ _k.sent();
710
708
  if (!!targetFn) return [3 /*break*/, 4];
711
709
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool function not found"), this_1.params.tools);
712
710
  return [4 /*yield*/, this_1._resurrectModel(mode, "No target function for ".concat(tool.function.name))];
713
711
  case 2:
714
- result_2 = _f.sent();
712
+ result_2 = _k.sent();
715
713
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " execute end result=").concat(result_2));
716
714
  return [4 /*yield*/, this_1._emitOuput(mode, result_2)];
717
715
  case 3:
718
- _f.sent();
716
+ _k.sent();
719
717
  return [2 /*return*/, { value: void 0 }];
720
718
  case 4:
721
- targetFn.onValidate && targetFn.onValidate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments);
719
+ ((_e = targetFn.callbacks) === null || _e === void 0 ? void 0 : _e.onValidate) &&
720
+ ((_f = targetFn.callbacks) === null || _f === void 0 ? void 0 : _f.onValidate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments));
722
721
  return [4 /*yield*/, not(targetFn.validate(this_1.params.clientId, this_1.params.agentName, tool.function.arguments))];
723
722
  case 5:
724
- if (!_f.sent()) return [3 /*break*/, 8];
723
+ if (!_k.sent()) return [3 /*break*/, 8];
725
724
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool validation not passed"));
726
725
  return [4 /*yield*/, this_1._resurrectModel(mode, "Function validation failed: name=".concat(tool.function.name, " arguments=").concat(JSON.stringify(tool.function.arguments)))];
727
726
  case 6:
728
- result_3 = _f.sent();
727
+ result_3 = _k.sent();
729
728
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " execute end result=").concat(result_3));
730
729
  return [4 /*yield*/, this_1._emitOuput(mode, result_3)];
731
730
  case 7:
732
- _f.sent();
731
+ _k.sent();
733
732
  return [2 /*return*/, { value: void 0 }];
734
733
  case 8:
735
- targetFn.onCall &&
736
- targetFn.onCall(this_1.params.clientId, this_1.params.agentName, tool.function.arguments);
734
+ ((_g = targetFn.callbacks) === null || _g === void 0 ? void 0 : _g.onCall) &&
735
+ ((_h = targetFn.callbacks) === null || _h === void 0 ? void 0 : _h.onCall(this_1.params.clientId, this_1.params.agentName, tool.function.arguments));
737
736
  /**
738
737
  * @description Do not await to avoid deadlock! The tool can send the message to other agents by emulating user messages
739
738
  */
@@ -744,33 +743,33 @@ var ClientAgent = /** @class */ (function () {
744
743
  this_1._outputSubject.toPromise(),
745
744
  ])];
746
745
  case 9:
747
- _f.sent();
746
+ _k.sent();
748
747
  this_1.params.logger.debug("ClientAgent agentName=".concat(this_1.params.agentName, " clientId=").concat(this_1.params.clientId, " functionName=").concat(tool.function.name, " tool call end"));
749
748
  return [2 /*return*/];
750
749
  }
751
750
  });
752
751
  };
753
752
  this_1 = this;
754
- _e.label = 3;
753
+ _j.label = 3;
755
754
  case 3:
756
- _e.trys.push([3, 8, 9, 10]);
755
+ _j.trys.push([3, 8, 9, 10]);
757
756
  _a = __values(message.tool_calls), _b = _a.next();
758
- _e.label = 4;
757
+ _j.label = 4;
759
758
  case 4:
760
759
  if (!!_b.done) return [3 /*break*/, 7];
761
760
  tool = _b.value;
762
761
  return [5 /*yield**/, _loop_1(tool)];
763
762
  case 5:
764
- state_1 = _e.sent();
763
+ state_1 = _j.sent();
765
764
  if (typeof state_1 === "object")
766
765
  return [2 /*return*/, state_1.value];
767
- _e.label = 6;
766
+ _j.label = 6;
768
767
  case 6:
769
768
  _b = _a.next();
770
769
  return [3 /*break*/, 4];
771
770
  case 7: return [3 /*break*/, 10];
772
771
  case 8:
773
- e_1_1 = _e.sent();
772
+ e_1_1 = _j.sent();
774
773
  e_1 = { error: e_1_1 };
775
774
  return [3 /*break*/, 10];
776
775
  case 9:
@@ -787,31 +786,44 @@ var ClientAgent = /** @class */ (function () {
787
786
  result = message.content;
788
787
  return [4 /*yield*/, this.params.history.push(__assign(__assign({}, message), { agentName: this.params.agentName }))];
789
788
  case 12:
790
- _e.sent();
789
+ _j.sent();
791
790
  validation = null;
792
791
  return [4 /*yield*/, this.params.validate(result)];
793
792
  case 13:
794
- if (!(validation = _e.sent())) return [3 /*break*/, 16];
793
+ if (!(validation = _j.sent())) return [3 /*break*/, 16];
795
794
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute invalid tool call detected: ").concat(validation), { result: result });
796
795
  return [4 /*yield*/, this._resurrectModel(mode, "Invalid model output: ".concat(result))];
797
796
  case 14:
798
- result1 = _e.sent();
797
+ result1 = _j.sent();
799
798
  return [4 /*yield*/, this._emitOuput(mode, result1)];
800
799
  case 15:
801
- _e.sent();
800
+ _j.sent();
802
801
  return [2 /*return*/];
803
802
  case 16:
804
803
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " execute end result=").concat(result));
805
804
  return [4 /*yield*/, this._emitOuput(mode, result)];
806
805
  case 17:
807
- _e.sent();
806
+ _j.sent();
808
807
  return [2 /*return*/];
809
808
  }
810
809
  });
811
810
  }); });
811
+ /**
812
+ * Should call on agent dispose
813
+ * @returns {Promise<void>}
814
+ */
815
+ this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
816
+ return __generator(this, function (_a) {
817
+ this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " dispose"));
818
+ this.params.onDispose &&
819
+ this.params.onDispose(this.params.clientId, this.params.agentName);
820
+ return [2 /*return*/];
821
+ });
822
+ }); };
812
823
  this.params.logger.debug("ClientAgent agentName=".concat(this.params.agentName, " clientId=").concat(this.params.clientId, " CTOR"), {
813
824
  params: params,
814
825
  });
826
+ this.params.onInit && this.params.onInit(params.clientId, params.agentName);
815
827
  }
816
828
  return ClientAgent;
817
829
  }());
@@ -840,26 +852,10 @@ var AgentConnectionService = /** @class */ (function () {
840
852
  var _b = __read(_a, 2), clientId = _b[0], agentName = _b[1];
841
853
  return "".concat(clientId, "-").concat(agentName);
842
854
  }, function (clientId, agentName) {
843
- var _a = _this.agentSchemaService.get(agentName), prompt = _a.prompt, system = _a.system, tools = _a.tools, onExecute = _a.onExecute, onOutput = _a.onOutput, onResurrect = _a.onResurrect, onSystemMessage = _a.onSystemMessage, onToolOutput = _a.onToolOutput, onUserMessage = _a.onUserMessage, completionName = _a.completion, _b = _a.validate, validate = _b === void 0 ? validateDefault : _b;
855
+ var _a = _this.agentSchemaService.get(agentName), prompt = _a.prompt, system = _a.system, tools = _a.tools, callbacks = _a.callbacks, completionName = _a.completion, _b = _a.validate, validate = _b === void 0 ? validateDefault : _b;
844
856
  var completion = _this.completionSchemaService.get(completionName);
845
857
  _this.sessionValidationService.addAgentUsage(clientId, agentName);
846
- return new ClientAgent({
847
- clientId: clientId,
848
- agentName: agentName,
849
- validate: validate,
850
- logger: _this.loggerService,
851
- history: _this.historyConnectionService.getHistory(clientId, agentName),
852
- prompt: prompt,
853
- system: system,
854
- tools: tools === null || tools === void 0 ? void 0 : tools.map(_this.toolSchemaService.get),
855
- completion: completion,
856
- onExecute: onExecute,
857
- onOutput: onOutput,
858
- onResurrect: onResurrect,
859
- onSystemMessage: onSystemMessage,
860
- onToolOutput: onToolOutput,
861
- onUserMessage: onUserMessage,
862
- });
858
+ return new ClientAgent(__assign({ clientId: clientId, agentName: agentName, validate: validate, logger: _this.loggerService, history: _this.historyConnectionService.getHistory(clientId, agentName), prompt: prompt, system: system, tools: tools === null || tools === void 0 ? void 0 : tools.map(_this.toolSchemaService.get), completion: completion }, callbacks));
863
859
  });
864
860
  /**
865
861
  * Executes an input command.
@@ -972,12 +968,18 @@ var AgentConnectionService = /** @class */ (function () {
972
968
  */
973
969
  this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
974
970
  return __generator(this, function (_a) {
975
- this.loggerService.log("agentConnectionService dispose", {
976
- context: this.contextService.context,
977
- });
978
- this.getAgent.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.agentName));
979
- this.sessionValidationService.removeAgentUsage(this.contextService.context.clientId, this.contextService.context.agentName);
980
- return [2 /*return*/];
971
+ switch (_a.label) {
972
+ case 0:
973
+ this.loggerService.log("agentConnectionService dispose", {
974
+ context: this.contextService.context,
975
+ });
976
+ return [4 /*yield*/, this.getAgent(this.contextService.context.clientId, this.contextService.context.agentName).dispose()];
977
+ case 1:
978
+ _a.sent();
979
+ this.getAgent.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.agentName));
980
+ this.sessionValidationService.removeAgentUsage(this.contextService.context.clientId, this.contextService.context.agentName);
981
+ return [2 /*return*/];
982
+ }
981
983
  });
982
984
  }); };
983
985
  }
@@ -1319,7 +1321,6 @@ var ToolSchemaService = /** @class */ (function () {
1319
1321
  return ToolSchemaService;
1320
1322
  }());
1321
1323
 
1322
- var AGENT_REF_CHANGED = Symbol("agent-ref-changed");
1323
1324
  var AGENT_NEED_FETCH = Symbol("agent-need-fetch");
1324
1325
  /**
1325
1326
  * ClientSwarm class implements the ISwarm interface and manages agents within a swarm.
@@ -1340,47 +1341,53 @@ var ClientSwarm = /** @class */ (function () {
1340
1341
  * @throws {Error} - If the timeout is reached.
1341
1342
  */
1342
1343
  this.waitForOutput = queued(function () { return __awaiter(_this, void 0, void 0, function () {
1343
- var START_TIME, _a, agentName, output, _b;
1344
+ var _a, awaiter, resolve, getOutput, handleOutput, un, _b, agentName, output, expectAgent;
1344
1345
  var _this = this;
1345
1346
  return __generator(this, function (_c) {
1346
1347
  switch (_c.label) {
1347
1348
  case 0:
1348
1349
  this.params.logger.debug("ClientSwarm swarmName=".concat(this.params.swarmName, " clientId=").concat(this.params.clientId, " waitForOutput"));
1349
- START_TIME = Date.now();
1350
- _c.label = 1;
1350
+ _a = __read(createAwaiter(), 2), awaiter = _a[0], resolve = _a[1].resolve;
1351
+ getOutput = cancelable(function () { return __awaiter(_this, void 0, void 0, function () {
1352
+ var _this = this;
1353
+ return __generator(this, function (_a) {
1354
+ switch (_a.label) {
1355
+ case 0: return [4 /*yield*/, Promise.race(this._agentList.map(function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
1356
+ var _c;
1357
+ var _d = __read(_b, 2), agentName = _d[0], agent = _d[1];
1358
+ return __generator(this, function (_e) {
1359
+ switch (_e.label) {
1360
+ case 0:
1361
+ _c = { agentName: agentName };
1362
+ return [4 /*yield*/, agent.waitForOutput()];
1363
+ case 1: return [2 /*return*/, (_c.output = _e.sent(), _c)];
1364
+ }
1365
+ });
1366
+ }); }))];
1367
+ case 1: return [2 /*return*/, _a.sent()];
1368
+ }
1369
+ });
1370
+ }); });
1371
+ handleOutput = function () {
1372
+ getOutput.cancel();
1373
+ getOutput().then(function (value) {
1374
+ if (value === CANCELED_PROMISE_SYMBOL) {
1375
+ return;
1376
+ }
1377
+ resolve(value);
1378
+ });
1379
+ };
1380
+ un = this._agentChangedSubject.subscribe(handleOutput);
1381
+ handleOutput();
1382
+ return [4 /*yield*/, awaiter];
1351
1383
  case 1:
1352
- if (Date.now() - START_TIME >= GLOBAL_CONFIG.CC_ANSWER_TIMEOUT) {
1353
- throw new Error("agent-swarm ClientSwarm waitForOutput timeout reached for ".concat(this.params.swarmName));
1354
- }
1355
- return [4 /*yield*/, Promise.race(__spreadArray(__spreadArray([], __read(Object.entries(this.params.agentMap).map(function (_a) { return __awaiter(_this, [_a], void 0, function (_b) {
1356
- var _c;
1357
- var _d = __read(_b, 2), agentName = _d[0], agent = _d[1];
1358
- return __generator(this, function (_e) {
1359
- switch (_e.label) {
1360
- case 0:
1361
- _c = [agentName];
1362
- return [4 /*yield*/, agent.waitForOutput()];
1363
- case 1: return [2 /*return*/, _c.concat([_e.sent()])];
1364
- }
1365
- });
1366
- }); })), false), [
1367
- this._agentChangedSubject
1368
- .toPromise()
1369
- .then(function () { return [AGENT_REF_CHANGED]; }),
1370
- ], false))];
1371
- case 2:
1372
- _a = __read.apply(void 0, [_c.sent(), 2]), agentName = _a[0], output = _a[1];
1373
- if (agentName === AGENT_REF_CHANGED) {
1374
- return [3 /*break*/, 1];
1375
- }
1376
- _b = agentName;
1384
+ _b = _c.sent(), agentName = _b.agentName, output = _b.output;
1385
+ un();
1377
1386
  return [4 /*yield*/, this.getAgentName()];
1378
- case 3:
1379
- if (_b === (_c.sent())) {
1380
- return [2 /*return*/, output];
1381
- }
1382
- return [3 /*break*/, 1];
1383
- case 4: return [2 /*return*/];
1387
+ case 2:
1388
+ expectAgent = _c.sent();
1389
+ agentName !== expectAgent && this.params.logger.debug("ClientSwarm swarmName=".concat(this.params.swarmName, " clientId=").concat(this.params.clientId, " waitForAgent agent miss"), { agentName: agentName, expectAgent: expectAgent });
1390
+ return [2 /*return*/, output];
1384
1391
  }
1385
1392
  });
1386
1393
  }); });
@@ -1436,7 +1443,7 @@ var ClientSwarm = /** @class */ (function () {
1436
1443
  throw new Error("agent-swarm agent ".concat(agentName, " not in the swarm"));
1437
1444
  }
1438
1445
  this.params.agentMap[agentName] = agent;
1439
- return [4 /*yield*/, this._agentChangedSubject.next()];
1446
+ return [4 /*yield*/, this._agentChangedSubject.next([agentName, agent])];
1440
1447
  case 1:
1441
1448
  _a.sent();
1442
1449
  return [2 /*return*/];
@@ -1464,6 +1471,13 @@ var ClientSwarm = /** @class */ (function () {
1464
1471
  params: params,
1465
1472
  });
1466
1473
  }
1474
+ Object.defineProperty(ClientSwarm.prototype, "_agentList", {
1475
+ get: function () {
1476
+ return Object.entries(this.params.agentMap);
1477
+ },
1478
+ enumerable: false,
1479
+ configurable: true
1480
+ });
1467
1481
  return ClientSwarm;
1468
1482
  }());
1469
1483
 
@@ -1489,7 +1503,7 @@ var SwarmConnectionService = /** @class */ (function () {
1489
1503
  return "".concat(clientId, "-").concat(swarmName);
1490
1504
  }, function (clientId, swarmName) {
1491
1505
  var e_1, _a;
1492
- var _b = _this.swarmSchemaService.get(swarmName), agentList = _b.agentList, defaultAgent = _b.defaultAgent, onAgentChanged = _b.onAgentChanged;
1506
+ var _b = _this.swarmSchemaService.get(swarmName), agentList = _b.agentList, defaultAgent = _b.defaultAgent, callbacks = _b.callbacks;
1493
1507
  var agentMap = {};
1494
1508
  try {
1495
1509
  for (var agentList_1 = __values(agentList), agentList_1_1 = agentList_1.next(); !agentList_1_1.done; agentList_1_1 = agentList_1.next()) {
@@ -1515,7 +1529,9 @@ var SwarmConnectionService = /** @class */ (function () {
1515
1529
  return __generator(this, function (_a) {
1516
1530
  switch (_a.label) {
1517
1531
  case 0:
1518
- onAgentChanged && onAgentChanged(clientId, agentName, swarmName);
1532
+ if (callbacks && callbacks.onAgentChanged) {
1533
+ callbacks.onAgentChanged(clientId, agentName, swarmName);
1534
+ }
1519
1535
  return [4 /*yield*/, GLOBAL_CONFIG.CC_SWARM_AGENT_CHANGED(clientId, agentName, swarmName)];
1520
1536
  case 1:
1521
1537
  _a.sent();
@@ -1880,9 +1896,22 @@ var ClientSession = /** @class */ (function () {
1880
1896
  });
1881
1897
  }); };
1882
1898
  };
1899
+ /**
1900
+ * Should call on session dispose
1901
+ * @returns {Promise<void>}
1902
+ */
1903
+ this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
1904
+ return __generator(this, function (_a) {
1905
+ this.params.logger.debug("ClientSession clientId=".concat(this.params.clientId, " dispose"));
1906
+ this.params.onDispose &&
1907
+ this.params.onDispose(this.params.clientId, this.params.swarmName);
1908
+ return [2 /*return*/];
1909
+ });
1910
+ }); };
1883
1911
  this.params.logger.debug("ClientSession clientId=".concat(this.params.clientId, " CTOR"), {
1884
1912
  params: params,
1885
1913
  });
1914
+ this.params.onInit && this.params.onInit(params.clientId, params.swarmName);
1886
1915
  }
1887
1916
  return ClientSession;
1888
1917
  }());
@@ -1908,16 +1937,8 @@ var SessionConnectionService = /** @class */ (function () {
1908
1937
  var _b = __read(_a, 2), clientId = _b[0], swarmName = _b[1];
1909
1938
  return "".concat(clientId, "-").concat(swarmName);
1910
1939
  }, function (clientId, swarmName) {
1911
- var _a = _this.swarmSchemaService.get(swarmName), onConnect = _a.onConnect, onEmit = _a.onEmit, onExecute = _a.onExecute;
1912
- return new ClientSession({
1913
- clientId: clientId,
1914
- logger: _this.loggerService,
1915
- swarm: _this.swarmConnectionService.getSwarm(clientId, swarmName),
1916
- swarmName: swarmName,
1917
- onConnect: onConnect,
1918
- onEmit: onEmit,
1919
- onExecute: onExecute,
1920
- });
1940
+ var callbacks = _this.swarmSchemaService.get(swarmName).callbacks;
1941
+ return new ClientSession(__assign({ clientId: clientId, logger: _this.loggerService, swarm: _this.swarmConnectionService.getSwarm(clientId, swarmName), swarmName: swarmName }, callbacks));
1921
1942
  });
1922
1943
  /**
1923
1944
  * Emits a message to the session.
@@ -2043,11 +2064,17 @@ var SessionConnectionService = /** @class */ (function () {
2043
2064
  */
2044
2065
  this.dispose = function () { return __awaiter(_this, void 0, void 0, function () {
2045
2066
  return __generator(this, function (_a) {
2046
- this.loggerService.log("sessionConnectionService dispose", {
2047
- context: this.contextService.context,
2048
- });
2049
- this.getSession.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.swarmName));
2050
- return [2 /*return*/];
2067
+ switch (_a.label) {
2068
+ case 0:
2069
+ this.loggerService.log("sessionConnectionService dispose", {
2070
+ context: this.contextService.context,
2071
+ });
2072
+ return [4 /*yield*/, this.getSession(this.contextService.context.clientId, this.contextService.context.swarmName).dispose()];
2073
+ case 1:
2074
+ _a.sent();
2075
+ this.getSession.clear("".concat(this.contextService.context.clientId, "-").concat(this.contextService.context.swarmName));
2076
+ return [2 /*return*/];
2077
+ }
2051
2078
  });
2052
2079
  }); };
2053
2080
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-swarm-kit",
3
- "version": "1.0.33",
3
+ "version": "1.0.35",
4
4
  "description": "A TypeScript library for building orchestrated framework-agnostic multi-agent AI systems",
5
5
  "author": {
6
6
  "name": "Petr Tripolsky",
package/types.d.ts CHANGED
@@ -53,7 +53,7 @@ interface ILogger {
53
53
  debug(...args: any[]): void;
54
54
  }
55
55
 
56
- interface ISwarmSession {
56
+ interface ISwarmSessionCallbacks {
57
57
  /**
58
58
  * Callback triggered when a client connects.
59
59
  * @param clientId - The ID of the client.
@@ -75,6 +75,25 @@ interface ISwarmSession {
75
75
  * @param message - The message to emit.
76
76
  */
77
77
  onEmit?: (clientId: string, swarmName: SwarmName, message: string) => void;
78
+ /**
79
+ * Callback triggered when a session being connected
80
+ * @param clientId - The ID of the client.
81
+ * @param swarmName - The name of the swarm.
82
+ */
83
+ onInit?: (clientId: string, swarmName: SwarmName) => void;
84
+ /**
85
+ * Callback triggered when a session being disponnected
86
+ * @param clientId - The ID of the client.
87
+ * @param swarmName - The name of the swarm.
88
+ */
89
+ onDispose?: (clientId: string, swarmName: SwarmName) => void;
90
+ }
91
+ /**
92
+ * Lifecycle callbacks of initialized swarm
93
+ */
94
+ interface ISwarmCallbacks extends ISwarmSessionCallbacks {
95
+ /** Emit the callback on agent change */
96
+ onAgentChanged: (clientId: string, agentName: AgentName, swarmName: SwarmName) => Promise<void>;
78
97
  }
79
98
  /**
80
99
  * Parameters for initializing a swarm.
@@ -84,29 +103,27 @@ interface ISwarmSession {
84
103
  interface ISwarmParams extends Omit<ISwarmSchema, keyof {
85
104
  agentList: never;
86
105
  onAgentChanged: never;
87
- }> {
106
+ }>, ISwarmCallbacks {
88
107
  /** Client identifier */
89
108
  clientId: string;
90
109
  /** Logger instance */
91
110
  logger: ILogger;
92
111
  /** Map of agent names to agent instances */
93
112
  agentMap: Record<AgentName, IAgent>;
94
- /** Emit the callback on agent change */
95
- onAgentChanged: (clientId: string, agentName: AgentName, swarmName: SwarmName) => Promise<void>;
96
113
  }
97
114
  /**
98
115
  * Schema for defining a swarm.
99
116
  * @interface
100
117
  */
101
- interface ISwarmSchema extends ISwarmSession {
118
+ interface ISwarmSchema {
102
119
  /** Default agent name */
103
120
  defaultAgent: AgentName;
104
121
  /** Name of the swarm */
105
122
  swarmName: string;
106
123
  /** List of agent names */
107
124
  agentList: string[];
108
- /** Emit the callback on agent change */
109
- onAgentChanged?: (clientId: string, agentName: AgentName, swarmName: SwarmName) => void;
125
+ /** Lifecycle callbacks*/
126
+ callbacks?: Partial<ISwarmCallbacks>;
110
127
  }
111
128
  /**
112
129
  * Interface for a swarm.
@@ -149,7 +166,7 @@ type SwarmName = string;
149
166
  * Parameters required to create a session.
150
167
  * @interface
151
168
  */
152
- interface ISessionParams extends ISessionSchema, ISwarmSession {
169
+ interface ISessionParams extends ISessionSchema, ISwarmSessionCallbacks {
153
170
  clientId: string;
154
171
  logger: ILogger;
155
172
  swarm: ISwarm;
@@ -430,6 +447,17 @@ interface ICompletionArgs {
430
447
  */
431
448
  tools?: ITool[];
432
449
  }
450
+ /**
451
+ * Completion lifecycle callbacks
452
+ */
453
+ interface ICompletionCallbacks {
454
+ /**
455
+ * Callback fired after complete.
456
+ * @param args - Arguments passed to complete
457
+ * @param output - Output of the model
458
+ */
459
+ onComplete?: (args: ICompletionArgs, output: IModelMessage) => void;
460
+ }
433
461
  /**
434
462
  * Schema for a completion.
435
463
  */
@@ -445,11 +473,9 @@ interface ICompletionSchema {
445
473
  */
446
474
  getCompletion(args: ICompletionArgs): Promise<IModelMessage>;
447
475
  /**
448
- * Callback fired after complete.
449
- * @param args - Arguments passed to complete
450
- * @param output - Output of the model
476
+ * Completion lifecycle callbacks
451
477
  */
452
- onComplete?: (args: ICompletionArgs, output: IModelMessage) => void;
478
+ callbacks?: Partial<ICompletionCallbacks>;
453
479
  }
454
480
  /**
455
481
  * Type representing the name of a completion.
@@ -457,44 +483,52 @@ interface ICompletionSchema {
457
483
  type CompletionName = string;
458
484
 
459
485
  /**
460
- * Interface representing a tool used by an agent.
486
+ * Interface representing lifecycle callbacks of a tool
461
487
  * @template T - The type of the parameters for the tool.
462
488
  */
463
- interface IAgentTool<T = Record<string, unknown>> extends ITool {
464
- /** The name of the tool. */
465
- toolName: ToolName;
489
+ interface IAgentToolCallbacks<T = Record<string, unknown>> {
466
490
  /**
467
- * Calls the tool with the specified parameters.
491
+ * Callback triggered when the tool is called.
468
492
  * @param clientId - The ID of the client.
469
493
  * @param agentName - The name of the agent.
470
494
  * @param params - The parameters for the tool.
471
495
  * @returns A promise that resolves when the tool call is complete.
472
496
  */
473
- call(clientId: string, agentName: AgentName, params: T): Promise<void>;
497
+ onCall?: (clientId: string, agentName: AgentName, params: T) => Promise<void>;
474
498
  /**
475
- * Validates the parameters for the tool.
499
+ * Callback triggered when the tool parameters are validated.
476
500
  * @param clientId - The ID of the client.
477
501
  * @param agentName - The name of the agent.
478
502
  * @param params - The parameters for the tool.
479
- * @returns A promise that resolves to a boolean indicating whether the parameters are valid, or a boolean.
503
+ * @returns A promise that resolves to a boolean indicating whether the parameters are valid.
480
504
  */
481
- validate(clientId: string, agentName: AgentName, params: T): Promise<boolean> | boolean;
505
+ onValidate?: (clientId: string, agentName: AgentName, params: T) => Promise<boolean>;
506
+ }
507
+ /**
508
+ * Interface representing a tool used by an agent.
509
+ * @template T - The type of the parameters for the tool.
510
+ */
511
+ interface IAgentTool<T = Record<string, unknown>> extends ITool {
512
+ /** The name of the tool. */
513
+ toolName: ToolName;
482
514
  /**
483
- * Callback triggered when the tool is called.
515
+ * Calls the tool with the specified parameters.
484
516
  * @param clientId - The ID of the client.
485
517
  * @param agentName - The name of the agent.
486
518
  * @param params - The parameters for the tool.
487
519
  * @returns A promise that resolves when the tool call is complete.
488
520
  */
489
- onCall?: (clientId: string, agentName: AgentName, params: T) => Promise<void>;
521
+ call(clientId: string, agentName: AgentName, params: T): Promise<void>;
490
522
  /**
491
- * Callback triggered when the tool parameters are validated.
523
+ * Validates the parameters for the tool.
492
524
  * @param clientId - The ID of the client.
493
525
  * @param agentName - The name of the agent.
494
526
  * @param params - The parameters for the tool.
495
- * @returns A promise that resolves to a boolean indicating whether the parameters are valid.
527
+ * @returns A promise that resolves to a boolean indicating whether the parameters are valid, or a boolean.
496
528
  */
497
- onValidate?: (clientId: string, agentName: AgentName, params: T) => Promise<boolean>;
529
+ validate(clientId: string, agentName: AgentName, params: T): Promise<boolean> | boolean;
530
+ /** The name of the tool. */
531
+ callbacks?: Partial<IAgentToolCallbacks>;
498
532
  }
499
533
  /**
500
534
  * Interface representing the parameters for an agent.
@@ -503,7 +537,7 @@ interface IAgentParams extends Omit<IAgentSchema, keyof {
503
537
  tools: never;
504
538
  completion: never;
505
539
  validate: never;
506
- }> {
540
+ }>, IAgentSchemaCallbacks {
507
541
  /** The ID of the client. */
508
542
  clientId: string;
509
543
  /** The logger instance. */
@@ -522,25 +556,9 @@ interface IAgentParams extends Omit<IAgentSchema, keyof {
522
556
  validate: (output: string) => Promise<string | null>;
523
557
  }
524
558
  /**
525
- * Interface representing the schema for an agent.
559
+ * Interface representing the lifecycle callbacks of an agent
526
560
  */
527
- interface IAgentSchema {
528
- /** The name of the agent. */
529
- agentName: AgentName;
530
- /** The name of the completion. */
531
- completion: CompletionName;
532
- /** The prompt for the agent. */
533
- prompt: string;
534
- /** The system prompt. Usually used for tool calling protocol. */
535
- system?: string[];
536
- /** The names of the tools used by the agent. */
537
- tools?: ToolName[];
538
- /**
539
- * Validates the output.
540
- * @param output - The output to validate.
541
- * @returns A promise that resolves to a string or null.
542
- */
543
- validate?: (output: string) => Promise<string | null>;
561
+ interface IAgentSchemaCallbacks {
544
562
  /**
545
563
  * Callback triggered when the agent executes.
546
564
  * @param clientId - The ID of the client.
@@ -591,6 +609,41 @@ interface IAgentSchema {
591
609
  * @param reason - The reason for the resurrection.
592
610
  */
593
611
  onResurrect?: (clientId: string, agentName: AgentName, mode: ExecutionMode, reason?: string) => void;
612
+ /**
613
+ * Callback triggered when agent is initialized
614
+ * @param clientId - The ID of the client.
615
+ * @param agentName - The name of the agent.
616
+ */
617
+ onInit?: (clientId: string, agentName: AgentName) => void;
618
+ /**
619
+ * Callback triggered when agent is disposed
620
+ * @param clientId - The ID of the client.
621
+ * @param agentName - The name of the agent.
622
+ */
623
+ onDispose?: (clientId: string, agentName: AgentName) => void;
624
+ }
625
+ /**
626
+ * Interface representing the schema for an agent.
627
+ */
628
+ interface IAgentSchema {
629
+ /** The name of the agent. */
630
+ agentName: AgentName;
631
+ /** The name of the completion. */
632
+ completion: CompletionName;
633
+ /** The prompt for the agent. */
634
+ prompt: string;
635
+ /** The system prompt. Usually used for tool calling protocol. */
636
+ system?: string[];
637
+ /** The names of the tools used by the agent. */
638
+ tools?: ToolName[];
639
+ /**
640
+ * Validates the output.
641
+ * @param output - The output to validate.
642
+ * @returns A promise that resolves to a string or null.
643
+ */
644
+ validate?: (output: string) => Promise<string | null>;
645
+ /** The lifecycle calbacks of the agent. */
646
+ callbacks?: Partial<IAgentSchemaCallbacks>;
594
647
  }
595
648
  /**
596
649
  * Interface representing an agent.
@@ -745,6 +798,11 @@ declare class ClientAgent implements IAgent {
745
798
  * @returns {Promise<void>}
746
799
  */
747
800
  execute: IAgent["execute"];
801
+ /**
802
+ * Should call on agent dispose
803
+ * @returns {Promise<void>}
804
+ */
805
+ dispose: () => Promise<void>;
748
806
  }
749
807
 
750
808
  /**
@@ -931,6 +989,7 @@ declare class ClientSwarm implements ISwarm {
931
989
  readonly params: ISwarmParams;
932
990
  private _agentChangedSubject;
933
991
  private _activeAgent;
992
+ get _agentList(): [string, IAgent][];
934
993
  /**
935
994
  * Creates an instance of ClientSwarm.
936
995
  * @param {ISwarmParams} params - The parameters for the swarm.
@@ -1110,6 +1169,11 @@ declare class ClientSession implements ISession {
1110
1169
  * @returns {ReceiveMessageFn} - The function to receive messages.
1111
1170
  */
1112
1171
  connect: (connector: SendMessageFn$1) => ReceiveMessageFn;
1172
+ /**
1173
+ * Should call on session dispose
1174
+ * @returns {Promise<void>}
1175
+ */
1176
+ dispose: () => Promise<void>;
1113
1177
  }
1114
1178
 
1115
1179
  /**
@@ -1976,7 +2040,6 @@ declare const GLOBAL_CONFIG: {
1976
2040
  CC_TOOL_CALL_EXCEPTION_PROMPT: string;
1977
2041
  CC_EMPTY_OUTPUT_PLACEHOLDERS: string[];
1978
2042
  CC_KEEP_MESSAGES: number;
1979
- CC_ANSWER_TIMEOUT: number;
1980
2043
  CC_GET_AGENT_HISTORY: (clientId: string, agentName: AgentName) => IPubsubArray<IModelMessage>;
1981
2044
  CC_SWARM_AGENT_CHANGED: (clientId: string, agentName: AgentName, swarmName: SwarmName) => Promise<void>;
1982
2045
  CC_SWARM_DEFAULT_AGENT: (clientId: string, swarmName: SwarmName, defaultAgent: AgentName) => Promise<AgentName>;