@agentica/core 0.27.2 → 0.28.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.
Files changed (98) hide show
  1. package/README.md +17 -2
  2. package/lib/Agentica.d.ts +2 -1
  3. package/lib/Agentica.js +92 -60
  4. package/lib/Agentica.js.map +1 -1
  5. package/lib/MicroAgentica.d.ts +1 -0
  6. package/lib/MicroAgentica.js +88 -60
  7. package/lib/MicroAgentica.js.map +1 -1
  8. package/lib/constants/AgenticaDefaultPrompt.js +2 -18
  9. package/lib/constants/AgenticaDefaultPrompt.js.map +1 -1
  10. package/lib/context/AgenticaContext.d.ts +1 -1
  11. package/lib/context/MicroAgenticaContext.d.ts +2 -2
  12. package/lib/context/internal/AgenticaOperationComposer.spec.js +0 -2
  13. package/lib/context/internal/AgenticaOperationComposer.spec.js.map +1 -1
  14. package/lib/events/AgenticaEventBase.d.ts +9 -0
  15. package/lib/factory/events.d.ts +1 -2
  16. package/lib/factory/events.js +71 -7
  17. package/lib/factory/events.js.map +1 -1
  18. package/lib/factory/histories.js +27 -9
  19. package/lib/factory/histories.js.map +1 -1
  20. package/lib/functional/assertMcpController.d.ts +1 -1
  21. package/lib/functional/assertMcpController.js.map +1 -1
  22. package/lib/functional/validateMcpController.d.ts +1 -1
  23. package/lib/functional/validateMcpController.js.map +1 -1
  24. package/lib/histories/AgenticaCancelHistory.d.ts +1 -2
  25. package/lib/histories/AgenticaExecuteHistory.d.ts +0 -4
  26. package/lib/histories/AgenticaHistoryBase.d.ts +9 -0
  27. package/lib/histories/AgenticaSelectHistory.d.ts +1 -2
  28. package/lib/index.mjs +413 -380
  29. package/lib/index.mjs.map +1 -1
  30. package/lib/json/IAgenticaEventJson.d.ts +9 -1
  31. package/lib/json/IAgenticaHistoryJson.d.ts +11 -14
  32. package/lib/orchestrate/call.d.ts +2 -2
  33. package/lib/orchestrate/call.js +41 -70
  34. package/lib/orchestrate/call.js.map +1 -1
  35. package/lib/orchestrate/cancel.d.ts +1 -2
  36. package/lib/orchestrate/cancel.js +13 -38
  37. package/lib/orchestrate/cancel.js.map +1 -1
  38. package/lib/orchestrate/describe.d.ts +1 -2
  39. package/lib/orchestrate/describe.js +5 -17
  40. package/lib/orchestrate/describe.js.map +1 -1
  41. package/lib/orchestrate/execute.d.ts +1 -2
  42. package/lib/orchestrate/execute.js +9 -13
  43. package/lib/orchestrate/execute.js.map +1 -1
  44. package/lib/orchestrate/initialize.d.ts +1 -2
  45. package/lib/orchestrate/initialize.js +3 -11
  46. package/lib/orchestrate/initialize.js.map +1 -1
  47. package/lib/orchestrate/internal/{cancelFunction.js → cancelFunctionFromContext.js} +7 -7
  48. package/lib/orchestrate/internal/cancelFunctionFromContext.js.map +1 -0
  49. package/lib/orchestrate/internal/selectFunctionFromContext.js +24 -0
  50. package/lib/orchestrate/internal/selectFunctionFromContext.js.map +1 -0
  51. package/lib/orchestrate/select.d.ts +1 -2
  52. package/lib/orchestrate/select.js +20 -51
  53. package/lib/orchestrate/select.js.map +1 -1
  54. package/lib/structures/IAgenticaConfig.d.ts +1 -3
  55. package/lib/structures/IAgenticaController.d.ts +123 -88
  56. package/lib/structures/IAgenticaExecutor.d.ts +6 -7
  57. package/lib/structures/IAgenticaVendor.d.ts +14 -0
  58. package/lib/structures/IMicroAgenticaExecutor.d.ts +2 -3
  59. package/lib/transformers/transformHistory.js +13 -8
  60. package/lib/transformers/transformHistory.js.map +1 -1
  61. package/lib/utils/ChatGptCompletionMessageUtil.js +3 -3
  62. package/package.json +13 -11
  63. package/src/Agentica.ts +127 -87
  64. package/src/MicroAgentica.ts +118 -81
  65. package/src/constants/AgenticaDefaultPrompt.ts +3 -20
  66. package/src/context/AgenticaContext.ts +1 -1
  67. package/src/context/MicroAgenticaContext.ts +2 -2
  68. package/src/context/internal/AgenticaOperationComposer.spec.ts +1 -2
  69. package/src/events/AgenticaEventBase.ts +12 -0
  70. package/src/factory/events.ts +78 -8
  71. package/src/factory/histories.ts +41 -11
  72. package/src/functional/assertMcpController.ts +1 -4
  73. package/src/functional/validateMcpController.ts +1 -4
  74. package/src/histories/AgenticaCancelHistory.ts +1 -2
  75. package/src/histories/AgenticaExecuteHistory.ts +0 -5
  76. package/src/histories/AgenticaHistoryBase.ts +12 -0
  77. package/src/histories/AgenticaSelectHistory.ts +1 -2
  78. package/src/json/IAgenticaEventJson.ts +11 -1
  79. package/src/json/IAgenticaHistoryJson.ts +14 -17
  80. package/src/orchestrate/call.ts +57 -107
  81. package/src/orchestrate/cancel.ts +76 -99
  82. package/src/orchestrate/describe.ts +16 -36
  83. package/src/orchestrate/execute.ts +17 -37
  84. package/src/orchestrate/initialize.ts +36 -49
  85. package/src/orchestrate/internal/{cancelFunction.ts → cancelFunctionFromContext.ts} +11 -11
  86. package/src/orchestrate/internal/{selectFunction.ts → selectFunctionFromContext.ts} +18 -13
  87. package/src/orchestrate/select.ts +112 -151
  88. package/src/structures/IAgenticaConfig.ts +1 -3
  89. package/src/structures/IAgenticaController.ts +4 -0
  90. package/src/structures/IAgenticaExecutor.ts +10 -8
  91. package/src/structures/IAgenticaVendor.ts +15 -0
  92. package/src/structures/IMicroAgenticaExecutor.ts +2 -3
  93. package/src/transformers/transformHistory.ts +19 -20
  94. package/lib/orchestrate/internal/cancelFunction.js.map +0 -1
  95. package/lib/orchestrate/internal/selectFunction.js +0 -35
  96. package/lib/orchestrate/internal/selectFunction.js.map +0 -1
  97. /package/lib/orchestrate/internal/{cancelFunction.d.ts → cancelFunctionFromContext.d.ts} +0 -0
  98. /package/lib/orchestrate/internal/{selectFunction.d.ts → selectFunctionFromContext.d.ts} +0 -0
package/lib/index.mjs CHANGED
@@ -1,8 +1,10 @@
1
- import "typia";
1
+ import { is_node, Semaphore } from "tstl";
2
2
 
3
3
  import { v4 } from "uuid";
4
4
 
5
- import { HttpLlm, ChatGptTypeChecker, LlmTypeCheckerV3_1, OpenApi, McpLlm } from "@samchon/openapi";
5
+ import "typia";
6
+
7
+ import { ChatGptTypeChecker, LlmTypeCheckerV3_1, HttpLlm, OpenApi, McpLlm } from "@samchon/openapi";
6
8
 
7
9
  import * as __typia_transform__validateReport from "typia/lib/internal/_validateReport.js";
8
10
 
@@ -289,10 +291,10 @@ function decodeHistory(history) {
289
291
  function: {
290
292
  name: `${history.type}Functions`,
291
293
  arguments: JSON.stringify({
292
- functions: history.selections.map((s => ({
293
- name: s.operation.function.name,
294
- reason: s.reason
295
- })))
294
+ function: {
295
+ name: history.selection.operation.name,
296
+ reason: history.selection.reason
297
+ }
296
298
  })
297
299
  }
298
300
  } ]
@@ -396,9 +398,13 @@ function decodeUserMessageContent(content) {
396
398
  function createUserMessageHistory(props) {
397
399
  return {
398
400
  type: "userMessage",
401
+ id: props.id,
402
+ created_at: props.created_at,
399
403
  contents: props.contents,
400
404
  toJSON: () => ({
401
405
  type: "userMessage",
406
+ id: props.id,
407
+ created_at: props.created_at,
402
408
  contents: props.contents
403
409
  })
404
410
  };
@@ -407,6 +413,8 @@ function createUserMessageHistory(props) {
407
413
  function createAssistantMessageHistory(props) {
408
414
  const prompt = {
409
415
  type: "assistantMessage",
416
+ id: props.id,
417
+ created_at: props.created_at,
410
418
  text: props.text
411
419
  };
412
420
  return {
@@ -418,6 +426,8 @@ function createAssistantMessageHistory(props) {
418
426
  function createSystemMessageHistory(props) {
419
427
  const prompt = {
420
428
  type: "systemMessage",
429
+ id: props.id,
430
+ created_at: props.created_at,
421
431
  text: props.text
422
432
  };
423
433
  return {
@@ -429,10 +439,14 @@ function createSystemMessageHistory(props) {
429
439
  function createDescribeHistory(props) {
430
440
  return {
431
441
  type: "describe",
442
+ id: props.id,
443
+ created_at: props.created_at,
432
444
  text: props.text,
433
445
  executes: props.executes,
434
446
  toJSON: () => ({
435
447
  type: "describe",
448
+ id: props.id,
449
+ created_at: props.created_at,
436
450
  text: props.text,
437
451
  executes: props.executes.map((execute => execute.toJSON()))
438
452
  })
@@ -443,11 +457,13 @@ function createSelectHistory(props) {
443
457
  return {
444
458
  type: "select",
445
459
  id: props.id,
446
- selections: props.selections,
460
+ selection: props.selection,
461
+ created_at: props.created_at,
447
462
  toJSON: () => ({
448
463
  type: "select",
449
464
  id: props.id,
450
- selections: props.selections.map((selection => selection.toJSON()))
465
+ created_at: props.created_at,
466
+ selection: props.selection.toJSON()
451
467
  })
452
468
  };
453
469
  }
@@ -456,11 +472,13 @@ function createCancelHistory(props) {
456
472
  return {
457
473
  type: "cancel",
458
474
  id: props.id,
459
- selections: props.selections,
475
+ created_at: props.created_at,
476
+ selection: props.selection,
460
477
  toJSON: () => ({
461
478
  type: "cancel",
462
479
  id: props.id,
463
- selections: props.selections.map((selection => selection.toJSON()))
480
+ created_at: props.created_at,
481
+ selection: props.selection.toJSON()
464
482
  })
465
483
  };
466
484
  }
@@ -470,13 +488,15 @@ function createExecuteHistory(props) {
470
488
  type: "execute",
471
489
  protocol: props.operation.protocol,
472
490
  id: props.id,
491
+ created_at: props.created_at,
473
492
  operation: props.operation,
474
493
  arguments: props.arguments,
475
494
  value: props.value,
476
495
  toJSON: () => ({
477
496
  type: "execute",
478
- protocol: props.operation.protocol,
479
497
  id: props.id,
498
+ created_at: props.created_at,
499
+ protocol: props.operation.protocol,
480
500
  operation: props.operation.toJSON(),
481
501
  arguments: props.arguments,
482
502
  value: props.value
@@ -486,49 +506,69 @@ function createExecuteHistory(props) {
486
506
 
487
507
  function createInitializeEvent() {
488
508
  const event = {
489
- type: "initialize"
509
+ id: v4(),
510
+ type: "initialize",
511
+ created_at: (new Date).toISOString()
490
512
  };
491
513
  return {
514
+ id: event.id,
492
515
  type: event.type,
516
+ created_at: event.created_at,
493
517
  toJSON: () => event
494
518
  };
495
519
  }
496
520
 
497
521
  function createSelectEvent(props) {
522
+ const id = v4();
523
+ const created_at = (new Date).toISOString();
498
524
  return {
499
525
  type: "select",
526
+ id,
527
+ created_at,
500
528
  selection: props.selection,
501
529
  toJSON: () => ({
502
530
  type: "select",
531
+ id,
532
+ created_at,
503
533
  selection: props.selection.toJSON()
504
534
  }),
505
535
  toHistory: () => createSelectHistory({
506
- id: v4(),
507
- selections: [ props.selection ]
536
+ id,
537
+ created_at,
538
+ selection: props.selection
508
539
  })
509
540
  };
510
541
  }
511
542
 
512
543
  function createCancelEvent(props) {
544
+ const id = v4();
545
+ const created_at = (new Date).toISOString();
513
546
  return {
514
547
  type: "cancel",
548
+ id,
549
+ created_at,
515
550
  selection: props.selection,
516
551
  toJSON: () => ({
517
552
  type: "cancel",
553
+ id,
554
+ created_at,
518
555
  selection: props.selection.toJSON()
519
556
  })
520
557
  };
521
558
  }
522
559
 
523
560
  function createCallEvent(props) {
561
+ const created_at = (new Date).toISOString();
524
562
  return {
525
563
  type: "call",
526
564
  id: props.id,
565
+ created_at,
527
566
  operation: props.operation,
528
567
  arguments: props.arguments,
529
568
  toJSON: () => ({
530
569
  type: "call",
531
570
  id: props.id,
571
+ created_at,
532
572
  operation: props.operation.toJSON(),
533
573
  arguments: props.arguments
534
574
  })
@@ -536,14 +576,17 @@ function createCallEvent(props) {
536
576
  }
537
577
 
538
578
  function createValidateEvent(props) {
579
+ const created_at = (new Date).toISOString();
539
580
  return {
540
581
  type: "validate",
541
582
  id: props.id,
583
+ created_at,
542
584
  operation: props.operation,
543
585
  result: props.result,
544
586
  toJSON: () => ({
545
587
  type: "validate",
546
588
  id: props.id,
589
+ created_at,
547
590
  operation: props.operation.toJSON(),
548
591
  result: props.result
549
592
  })
@@ -551,54 +594,80 @@ function createValidateEvent(props) {
551
594
  }
552
595
 
553
596
  function createExecuteEvent(props) {
597
+ const id = v4();
598
+ const created_at = (new Date).toISOString();
554
599
  return {
555
600
  type: "execute",
601
+ id,
602
+ created_at,
556
603
  protocol: props.operation.protocol,
557
- id: props.id,
558
604
  operation: props.operation,
559
605
  arguments: props.arguments,
560
606
  value: props.value,
561
607
  toJSON: () => ({
562
608
  type: "execute",
609
+ id,
610
+ created_at,
563
611
  protocol: props.operation.protocol,
564
- id: props.id,
565
612
  operation: props.operation.toJSON(),
566
613
  arguments: props.arguments,
567
614
  value: props.value
568
615
  }),
569
- toHistory: () => createExecuteHistory(props)
616
+ toHistory: () => createExecuteHistory({
617
+ id,
618
+ created_at,
619
+ ...props
620
+ })
570
621
  };
571
622
  }
572
623
 
573
624
  function createUserMessageEvent(props) {
625
+ const id = v4();
626
+ const created_at = (new Date).toISOString();
574
627
  return {
575
628
  type: "userMessage",
629
+ id,
630
+ created_at,
576
631
  contents: props.contents,
577
632
  toJSON: () => ({
578
633
  type: "userMessage",
634
+ id,
635
+ created_at,
579
636
  contents: props.contents
580
637
  }),
581
638
  toHistory: () => createUserMessageHistory({
639
+ id,
640
+ created_at,
582
641
  contents: props.contents
583
642
  })
584
643
  };
585
644
  }
586
645
 
587
- function creatAssistantEvent(props) {
646
+ function creatAssistantMessageEvent(props) {
647
+ const id = v4();
648
+ const created_at = (new Date).toISOString();
588
649
  return {
589
650
  type: "assistantMessage",
651
+ id,
652
+ created_at,
590
653
  stream: props.stream,
591
654
  join: props.join,
592
655
  toJSON: () => ({
593
656
  type: "assistantMessage",
657
+ id,
658
+ created_at,
594
659
  done: props.done(),
595
660
  text: props.get()
596
661
  }),
597
662
  toHistory: () => ({
598
663
  type: "assistantMessage",
664
+ id,
665
+ created_at,
599
666
  text: props.get(),
600
667
  toJSON: () => ({
601
668
  type: "assistantMessage",
669
+ id,
670
+ created_at,
602
671
  text: props.get()
603
672
  })
604
673
  })
@@ -606,23 +675,33 @@ function creatAssistantEvent(props) {
606
675
  }
607
676
 
608
677
  function createDescribeEvent(props) {
678
+ const id = v4();
679
+ const created_at = (new Date).toISOString();
609
680
  return {
610
681
  type: "describe",
682
+ id,
683
+ created_at,
611
684
  executes: props.executes,
612
685
  stream: props.stream,
613
686
  join: props.join,
614
687
  toJSON: () => ({
615
688
  type: "describe",
689
+ id,
690
+ created_at,
616
691
  executes: props.executes.map((execute => execute.toJSON())),
617
692
  done: props.done(),
618
693
  text: props.get()
619
694
  }),
620
695
  toHistory: () => ({
621
696
  type: "describe",
697
+ id,
698
+ created_at,
622
699
  executes: props.executes,
623
700
  text: props.get(),
624
701
  toJSON: () => ({
625
702
  type: "describe",
703
+ id,
704
+ created_at,
626
705
  executes: props.executes.map((execute => execute.toJSON())),
627
706
  text: props.get()
628
707
  })
@@ -631,8 +710,12 @@ function createDescribeEvent(props) {
631
710
  }
632
711
 
633
712
  function createRequestEvent(props) {
713
+ const id = v4();
714
+ const created_at = (new Date).toISOString();
634
715
  return {
635
716
  type: "request",
717
+ id,
718
+ created_at,
636
719
  source: props.source,
637
720
  body: props.body,
638
721
  options: props.options
@@ -640,8 +723,12 @@ function createRequestEvent(props) {
640
723
  }
641
724
 
642
725
  function createResponseEvent(props) {
726
+ const id = v4();
727
+ const created_at = (new Date).toISOString();
643
728
  return {
644
729
  type: "response",
730
+ id,
731
+ created_at,
645
732
  source: props.source,
646
733
  body: props.body,
647
734
  options: props.options,
@@ -650,42 +737,6 @@ function createResponseEvent(props) {
650
737
  };
651
738
  }
652
739
 
653
- function createOperationSelection(props) {
654
- return {
655
- operation: props.operation,
656
- reason: props.reason,
657
- toJSON: () => ({
658
- operation: props.operation.toJSON(),
659
- reason: props.reason
660
- })
661
- };
662
- }
663
-
664
- var index$2 = Object.freeze({
665
- __proto__: null,
666
- creatAssistantEvent,
667
- createAssistantMessageHistory,
668
- createCallEvent,
669
- createCancelEvent,
670
- createCancelHistory,
671
- createDescribeEvent,
672
- createDescribeHistory,
673
- createExecuteEvent,
674
- createExecuteHistory,
675
- createInitializeEvent,
676
- createOperationSelection,
677
- createRequestEvent,
678
- createResponseEvent,
679
- createSelectEvent,
680
- createSelectHistory,
681
- createSystemMessageHistory,
682
- createUserMessageEvent,
683
- createUserMessageHistory,
684
- createValidateEvent,
685
- decodeHistory,
686
- decodeUserMessageContent
687
- });
688
-
689
740
  var AgenticaConstant;
690
741
 
691
742
  (function(AgenticaConstant) {
@@ -717,12 +768,7 @@ const AgenticaSystemPrompt = {
717
768
  SELECT: "You are a helpful assistant for selecting functions to call.\n\nUse the supplied tools to select some functions of `getApiFunctions()` returned.\n\nWhen selecting functions to call, pay attention to the relationship between functions. In particular, check the prerequisites between each function.\n\nIf you can't find any proper function to select, just type your own message. By the way, when typing your own message, please consider the user's language locale code. If your message is different with the user's language, please translate it to the user's."
718
769
  };
719
770
 
720
- const isNode = new Singleton((() => {
721
- const isObject = obj => typeof obj === "object" && obj !== null;
722
- return typeof global === "object" && isObject(global) && isObject(global.process) && isObject(global.process.versions) && typeof global.process.versions.node !== "undefined";
723
- }));
724
-
725
- const getLocale = new Singleton((() => isNode.get() ? process.env.LANG?.split(".")[0] ?? "en-US" : navigator.language));
771
+ const getLocale = new Singleton((() => is_node() ? process.env.LANG?.split(".")[0] ?? "en-US" : navigator.language));
726
772
 
727
773
  const getTimezone = new Singleton((() => Intl.DateTimeFormat().resolvedOptions().timeZone));
728
774
 
@@ -801,7 +847,7 @@ function transformCompletionChunk(source) {
801
847
  const str = source instanceof Uint8Array ? ByteArrayUtil.toUtf8(source) : source;
802
848
  const result = JSON.parse(str);
803
849
  const valid = (() => {
804
- const _io0 = input => "string" === typeof input.id && (Array.isArray(input.choices) && input.choices.every((elem => "object" === typeof elem && null !== elem && _io1(elem)))) && "number" === typeof input.created && "string" === typeof input.model && "chat.completion.chunk" === input.object && (null === input.service_tier || undefined === input.service_tier || "scale" === input.service_tier || "default" === input.service_tier) && (undefined === input.system_fingerprint || "string" === typeof input.system_fingerprint) && (null === input.usage || undefined === input.usage || "object" === typeof input.usage && null !== input.usage && _io9(input.usage));
850
+ const _io0 = input => "string" === typeof input.id && (Array.isArray(input.choices) && input.choices.every((elem => "object" === typeof elem && null !== elem && _io1(elem)))) && "number" === typeof input.created && "string" === typeof input.model && "chat.completion.chunk" === input.object && (null === input.service_tier || undefined === input.service_tier || "auto" === input.service_tier || "default" === input.service_tier || "flex" === input.service_tier) && (undefined === input.system_fingerprint || "string" === typeof input.system_fingerprint) && (null === input.usage || undefined === input.usage || "object" === typeof input.usage && null !== input.usage && _io9(input.usage));
805
851
  const _io1 = input => "object" === typeof input.delta && null !== input.delta && false === Array.isArray(input.delta) && _io2(input.delta) && (null === input.finish_reason || "length" === input.finish_reason || "function_call" === input.finish_reason || "stop" === input.finish_reason || "tool_calls" === input.finish_reason || "content_filter" === input.finish_reason) && "number" === typeof input.index && (null === input.logprobs || undefined === input.logprobs || "object" === typeof input.logprobs && null !== input.logprobs && _io6(input.logprobs));
806
852
  const _io2 = input => (null === input.content || undefined === input.content || "string" === typeof input.content) && (undefined === input.function_call || "object" === typeof input.function_call && null !== input.function_call && false === Array.isArray(input.function_call) && _io3(input.function_call)) && (null === input.refusal || undefined === input.refusal || "string" === typeof input.refusal) && (undefined === input.role || "user" === input.role || "developer" === input.role || "system" === input.role || "assistant" === input.role || "tool" === input.role) && (undefined === input.tool_calls || Array.isArray(input.tool_calls) && input.tool_calls.every((elem => "object" === typeof elem && null !== elem && _io4(elem))));
807
853
  const _io3 = input => (undefined === input.arguments || "string" === typeof input.arguments) && (undefined === input.name || "string" === typeof input.name);
@@ -845,9 +891,9 @@ function transformCompletionChunk(source) {
845
891
  path: _path + ".object",
846
892
  expected: '"chat.completion.chunk"',
847
893
  value: input.object
848
- }), null === input.service_tier || undefined === input.service_tier || "scale" === input.service_tier || "default" === input.service_tier || _report(_exceptionable, {
894
+ }), null === input.service_tier || undefined === input.service_tier || "auto" === input.service_tier || "default" === input.service_tier || "flex" === input.service_tier || _report(_exceptionable, {
849
895
  path: _path + ".service_tier",
850
- expected: '("default" | "scale" | null | undefined)',
896
+ expected: '("auto" | "default" | "flex" | null | undefined)',
851
897
  value: input.service_tier
852
898
  }), undefined === input.system_fingerprint || "string" === typeof input.system_fingerprint || _report(_exceptionable, {
853
899
  path: _path + ".system_fingerprint",
@@ -1343,20 +1389,31 @@ const StreamUtil = {
1343
1389
  transform
1344
1390
  };
1345
1391
 
1346
- function cancelFunction(ctx, reference) {
1392
+ function createOperationSelection(props) {
1393
+ return {
1394
+ operation: props.operation,
1395
+ reason: props.reason,
1396
+ toJSON: () => ({
1397
+ operation: props.operation.toJSON(),
1398
+ reason: props.reason
1399
+ })
1400
+ };
1401
+ }
1402
+
1403
+ function cancelFunctionFromContext(ctx, reference) {
1347
1404
  const index = ctx.stack.findIndex((item => item.operation.name === reference.name));
1348
1405
  if (index === -1) {
1349
- return null;
1406
+ return;
1350
1407
  }
1351
1408
  const item = ctx.stack[index];
1352
1409
  ctx.stack.splice(index, 1);
1353
- ctx.dispatch(createCancelEvent({
1410
+ const event = createCancelEvent({
1354
1411
  selection: createOperationSelection({
1355
1412
  operation: item.operation,
1356
1413
  reason: reference.reason
1357
1414
  })
1358
- })).catch((() => {}));
1359
- return item;
1415
+ });
1416
+ ctx.dispatch(event);
1360
1417
  }
1361
1418
 
1362
1419
  async function call(ctx, operations) {
@@ -1388,9 +1445,9 @@ async function call(ctx, operations) {
1388
1445
  tool_choice: "auto",
1389
1446
  parallel_tool_calls: false
1390
1447
  });
1391
- const closures = [];
1392
1448
  const chunks = await StreamUtil.readAll(completionStream);
1393
1449
  const completion = ChatGptCompletionMessageUtil.merge(chunks);
1450
+ const executes = [];
1394
1451
  for (const choice of completion.choices) {
1395
1452
  for (const tc of choice.message.tool_calls ?? []) {
1396
1453
  if (tc.type === "function") {
@@ -1398,59 +1455,41 @@ async function call(ctx, operations) {
1398
1455
  if (operation === undefined) {
1399
1456
  continue;
1400
1457
  }
1401
- closures.push((async () => {
1402
- const call = createCallEvent({
1403
- id: tc.id,
1404
- operation,
1405
- arguments: JSON.parse(tc.function.arguments)
1406
- });
1407
- if (call.operation.protocol === "http") {
1408
- fillHttpArguments({
1409
- operation: call.operation,
1410
- arguments: call.arguments
1411
- });
1412
- }
1413
- await ctx.dispatch(call);
1414
- const execute = await propagate(ctx, call, 0);
1415
- ctx.dispatch(createExecuteEvent({
1416
- id: call.id,
1458
+ const call = createCallEvent({
1459
+ id: tc.id,
1460
+ operation,
1461
+ arguments: JSON.parse(tc.function.arguments)
1462
+ });
1463
+ if (call.operation.protocol === "http") {
1464
+ fillHttpArguments({
1417
1465
  operation: call.operation,
1418
- arguments: execute.arguments,
1419
- value: execute.value
1420
- })).catch((() => {}));
1421
- if (isAgenticaContext(ctx)) {
1422
- cancelFunction(ctx, {
1423
- name: call.operation.name,
1424
- reason: "completed"
1425
- });
1426
- return [ execute, createCancelHistory({
1427
- id: call.id,
1428
- selections: [ createOperationSelection({
1429
- operation: call.operation,
1430
- reason: "complete"
1431
- }) ]
1432
- }) ];
1433
- }
1434
- return [ execute ];
1435
- }));
1466
+ arguments: call.arguments
1467
+ });
1468
+ }
1469
+ ctx.dispatch(call);
1470
+ const exec = await propagate(ctx, call, 0);
1471
+ ctx.dispatch(exec);
1472
+ executes.push(exec);
1473
+ if (isAgenticaContext(ctx)) {
1474
+ cancelFunctionFromContext(ctx, {
1475
+ name: call.operation.name,
1476
+ reason: "completed"
1477
+ });
1478
+ }
1436
1479
  }
1437
1480
  }
1438
1481
  if (choice.message.role === "assistant" && choice.message.content != null && choice.message.content.length !== 0) {
1439
- closures.push((async () => {
1440
- const value = createAssistantMessageHistory({
1441
- text: choice.message.content
1442
- });
1443
- ctx.dispatch(creatAssistantEvent({
1444
- get: () => value.text,
1445
- done: () => true,
1446
- stream: toAsyncGenerator(value.text),
1447
- join: async () => Promise.resolve(value.text)
1448
- })).catch((() => {}));
1449
- return [ value ];
1450
- }));
1482
+ const text = choice.message.content;
1483
+ const event = creatAssistantMessageEvent({
1484
+ get: () => text,
1485
+ done: () => true,
1486
+ stream: toAsyncGenerator(text),
1487
+ join: async () => Promise.resolve(text)
1488
+ });
1489
+ ctx.dispatch(event);
1451
1490
  }
1452
1491
  }
1453
- return (await Promise.all(closures.map((async fn => fn())))).flat();
1492
+ return executes;
1454
1493
  }
1455
1494
 
1456
1495
  async function propagate(ctx, call, retry) {
@@ -1500,7 +1539,7 @@ async function propagateHttp(props) {
1500
1539
  id: props.call.id,
1501
1540
  operation: props.operation,
1502
1541
  result: check
1503
- })).catch((() => {}));
1542
+ }));
1504
1543
  if (props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY)) {
1505
1544
  const trial = await correct(props.ctx, props.call, props.retry, check.errors);
1506
1545
  if (trial !== null) {
@@ -1511,16 +1550,14 @@ async function propagateHttp(props) {
1511
1550
  try {
1512
1551
  const response = await executeHttpOperation(props.operation, props.call.arguments);
1513
1552
  const success = ((response.status === 400 || response.status === 404 || response.status === 422) && props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY) && typeof response.body) === false;
1514
- return (success === false ? await correct(props.ctx, props.call, props.retry, response.body) : null) ?? createExecuteHistory({
1553
+ return (success === false ? await correct(props.ctx, props.call, props.retry, response.body) : null) ?? createExecuteEvent({
1515
1554
  operation: props.call.operation,
1516
- id: props.call.id,
1517
1555
  arguments: props.call.arguments,
1518
1556
  value: response
1519
1557
  });
1520
1558
  } catch (error) {
1521
- return createExecuteHistory({
1559
+ return createExecuteEvent({
1522
1560
  operation: props.call.operation,
1523
- id: props.call.id,
1524
1561
  arguments: props.call.arguments,
1525
1562
  value: {
1526
1563
  status: 500,
@@ -1542,9 +1579,8 @@ async function propagateClass(props) {
1542
1579
  id: props.call.id,
1543
1580
  operation: props.call.operation,
1544
1581
  result: check
1545
- })).catch((() => {}));
1546
- return (props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY) ? await correct(props.ctx, props.call, props.retry, check.errors) : null) ?? createExecuteHistory({
1547
- id: props.call.id,
1582
+ }));
1583
+ return (props.retry++ < (props.ctx.config?.retry ?? AgenticaConstant.RETRY) ? await correct(props.ctx, props.call, props.retry, check.errors) : null) ?? createExecuteEvent({
1548
1584
  operation: props.call.operation,
1549
1585
  arguments: props.call.arguments,
1550
1586
  value: {
@@ -1556,15 +1592,13 @@ async function propagateClass(props) {
1556
1592
  }
1557
1593
  try {
1558
1594
  const value = await executeClassOperation(props.operation, props.call.arguments);
1559
- return createExecuteHistory({
1560
- id: props.call.id,
1595
+ return createExecuteEvent({
1561
1596
  operation: props.call.operation,
1562
1597
  arguments: props.call.arguments,
1563
1598
  value
1564
1599
  });
1565
1600
  } catch (error) {
1566
- return createExecuteHistory({
1567
- id: props.call.id,
1601
+ return createExecuteEvent({
1568
1602
  operation: props.call.operation,
1569
1603
  arguments: props.call.arguments,
1570
1604
  value: error instanceof Error ? {
@@ -1579,15 +1613,13 @@ async function propagateClass(props) {
1579
1613
  async function propagateMcp(props) {
1580
1614
  try {
1581
1615
  const value = await executeMcpOperation(props.operation, props.call.arguments);
1582
- return createExecuteHistory({
1583
- id: props.call.id,
1616
+ return createExecuteEvent({
1584
1617
  operation: props.call.operation,
1585
1618
  arguments: props.call.arguments,
1586
1619
  value
1587
1620
  });
1588
1621
  } catch (error) {
1589
- return createExecuteHistory({
1590
- id: props.call.id,
1622
+ return createExecuteEvent({
1591
1623
  operation: props.call.operation,
1592
1624
  arguments: props.call.arguments,
1593
1625
  value: error instanceof Error ? {
@@ -1820,32 +1852,20 @@ async function cancel(ctx) {
1820
1852
  }
1821
1853
  const stacks = ctx.operations.divided.map((() => []));
1822
1854
  const events = [];
1823
- const prompts = await Promise.all(ctx.operations.divided.map((async (operations, i) => step$1({
1855
+ await Promise.all(ctx.operations.divided.map((async (operations, i) => step$1({
1824
1856
  ...ctx,
1825
1857
  stack: stacks[i],
1826
- dispatch: async e => {
1858
+ dispatch: e => {
1827
1859
  events.push(e);
1860
+ return e;
1828
1861
  }
1829
1862
  }, operations, 0))));
1830
- if (stacks.every((s => s.length === 0))) {
1831
- return prompts[0];
1832
- } else if ((ctx.config?.eliticism ?? AgenticaConstant.ELITICISM) === true) {
1863
+ if ((ctx.config?.eliticism ?? AgenticaConstant.ELITICISM) === true && stacks.some((s => s.length !== 0))) {
1833
1864
  return step$1(ctx, stacks.flat().map((s => ctx.operations.group.get(s.operation.controller.name).get(s.operation.function.name))), 0);
1865
+ } else {
1866
+ const cancelled = events.filter((e => e.type === "cancel"));
1867
+ (cancelled.length !== 0 ? cancelled : events).forEach(ctx.dispatch);
1834
1868
  }
1835
- const collection = createCancelHistory({
1836
- id: v4(),
1837
- selections: []
1838
- });
1839
- for (const e of events) {
1840
- if (e.type === "select") {
1841
- collection.selections.push(e.selection);
1842
- cancelFunction(ctx, {
1843
- name: e.selection.operation.name,
1844
- reason: e.selection.reason
1845
- });
1846
- }
1847
- }
1848
- return [ collection ];
1849
1869
  }
1850
1870
 
1851
1871
  async function step$1(ctx, operations, retry, failures) {
@@ -1982,14 +2002,12 @@ async function step$1(ctx, operations, retry, failures) {
1982
2002
  return step$1(ctx, operations, retry, failures);
1983
2003
  }
1984
2004
  }
1985
- const prompts = [];
1986
2005
  for (const choice of completion.choices) {
1987
2006
  if (choice.message.tool_calls != null) {
1988
2007
  for (const tc of choice.message.tool_calls) {
1989
2008
  if (tc.type !== "function") {
1990
2009
  continue;
1991
- }
1992
- if (tc.function.name !== "cancelFunctions") {
2010
+ } else if (tc.function.name !== "cancelFunctions") {
1993
2011
  continue;
1994
2012
  }
1995
2013
  const input = (() => {
@@ -2004,23 +2022,12 @@ async function step$1(ctx, operations, retry, failures) {
2004
2022
  if (input === null) {
2005
2023
  continue;
2006
2024
  }
2007
- const collection = createCancelHistory({
2008
- id: tc.id,
2009
- selections: []
2010
- });
2011
2025
  for (const reference of input.functions) {
2012
- const operation = cancelFunction(ctx, reference);
2013
- if (operation !== null) {
2014
- collection.selections.push(operation);
2015
- }
2016
- }
2017
- if (collection.selections.length !== 0) {
2018
- prompts.push(collection);
2026
+ cancelFunctionFromContext(ctx, reference);
2019
2027
  }
2020
2028
  }
2021
2029
  }
2022
2030
  }
2023
- return prompts;
2024
2031
  }
2025
2032
 
2026
2033
  function emendMessages$1(failures) {
@@ -2167,7 +2174,7 @@ class MPSC {
2167
2174
 
2168
2175
  async function describe(ctx, histories) {
2169
2176
  if (histories.length === 0) {
2170
- return [];
2177
+ return;
2171
2178
  }
2172
2179
  const completionStream = await ctx.request("describe", {
2173
2180
  messages: [ {
@@ -2179,7 +2186,7 @@ async function describe(ctx, histories) {
2179
2186
  } ]
2180
2187
  });
2181
2188
  const describeContext = [];
2182
- const completion = await StreamUtil.reduce(completionStream, (async (accPromise, chunk) => {
2189
+ await StreamUtil.reduce(completionStream, (async (accPromise, chunk) => {
2183
2190
  const acc = await accPromise;
2184
2191
  const registerContext = choices => {
2185
2192
  for (const choice of choices) {
@@ -2201,7 +2208,7 @@ async function describe(ctx, histories) {
2201
2208
  mpsc
2202
2209
  };
2203
2210
  mpsc.produce(choice.delta.content);
2204
- ctx.dispatch(createDescribeEvent({
2211
+ const event = createDescribeEvent({
2205
2212
  executes: histories,
2206
2213
  stream: streamDefaultReaderToAsyncGenerator(mpsc.consumer.getReader()),
2207
2214
  done: () => mpsc.done(),
@@ -2210,7 +2217,8 @@ async function describe(ctx, histories) {
2210
2217
  await mpsc.waitClosed();
2211
2218
  return describeContext[choice.index].content;
2212
2219
  }
2213
- })).catch((() => {}));
2220
+ });
2221
+ ctx.dispatch(event);
2214
2222
  }
2215
2223
  };
2216
2224
  if (acc.object === "chat.completion.chunk") {
@@ -2220,14 +2228,6 @@ async function describe(ctx, histories) {
2220
2228
  registerContext(chunk.choices);
2221
2229
  return ChatGptCompletionMessageUtil.accumulate(acc, chunk);
2222
2230
  }));
2223
- if (completion == null) {
2224
- throw new Error("No completion received");
2225
- }
2226
- const descriptions = completion.choices.map((choice => choice.message.role === "assistant" ? choice.message.content : null)).filter((str => str !== null)).map((content => createDescribeHistory({
2227
- executes: histories,
2228
- text: content
2229
- })));
2230
- return descriptions;
2231
2231
  }
2232
2232
 
2233
2233
  const ChatGptDescribeFunctionAgent = {
@@ -3918,7 +3918,7 @@ async function initialize(ctx) {
3918
3918
  mpsc
3919
3919
  };
3920
3920
  mpsc.produce(choice.delta.content);
3921
- ctx.dispatch(creatAssistantEvent({
3921
+ const event = creatAssistantMessageEvent({
3922
3922
  stream: streamDefaultReaderToAsyncGenerator(mpsc.consumer.getReader()),
3923
3923
  done: () => mpsc.done(),
3924
3924
  get: () => textContext[choice.index].content,
@@ -3926,7 +3926,8 @@ async function initialize(ctx) {
3926
3926
  await mpsc.waitClosed();
3927
3927
  return textContext[choice.index].content;
3928
3928
  }
3929
- })).catch((() => {}));
3929
+ });
3930
+ ctx.dispatch(event);
3930
3931
  }
3931
3932
  };
3932
3933
  if (acc.object === "chat.completion.chunk") {
@@ -3939,34 +3940,25 @@ async function initialize(ctx) {
3939
3940
  if (completion === null) {
3940
3941
  throw new Error("No completion received");
3941
3942
  }
3942
- const prompts = [];
3943
- for (const choice of completion.choices) {
3944
- if (choice.message.role === "assistant" && choice.message.content != null && choice.message.content.length !== 0) {
3945
- prompts.push(createAssistantMessageHistory({
3946
- text: choice.message.content
3947
- }));
3948
- }
3949
- }
3950
3943
  if (completion.choices.some((c => c.message.tool_calls != null && c.message.tool_calls.some((tc => tc.type === "function" && tc.function.name === FUNCTION.name))))) {
3951
3944
  await ctx.initialize();
3952
3945
  }
3953
- return prompts;
3954
3946
  }
3955
3947
 
3956
- async function selectFunction(ctx, reference) {
3948
+ function selectFunctionFromContext(ctx, reference) {
3957
3949
  const operation = ctx.operations.flat.get(reference.name);
3958
3950
  if (operation === undefined) {
3959
- return null;
3951
+ return;
3960
3952
  }
3961
3953
  const selection = createOperationSelection({
3962
3954
  operation,
3963
3955
  reason: reference.reason
3964
3956
  });
3965
3957
  ctx.stack.push(selection);
3966
- ctx.dispatch(createSelectEvent({
3958
+ const event = createSelectEvent({
3967
3959
  selection
3968
- })).catch((() => {}));
3969
- return operation;
3960
+ });
3961
+ ctx.dispatch(event);
3970
3962
  }
3971
3963
 
3972
3964
  const CONTAINER = {
@@ -4074,32 +4066,20 @@ async function select(ctx) {
4074
4066
  }
4075
4067
  const stacks = ctx.operations.divided.map((() => []));
4076
4068
  const events = [];
4077
- const prompts = await Promise.all(ctx.operations.divided.map((async (operations, i) => step({
4069
+ await Promise.all(ctx.operations.divided.map((async (operations, i) => step({
4078
4070
  ...ctx,
4079
4071
  stack: stacks[i],
4080
- dispatch: async e => {
4072
+ dispatch: e => {
4081
4073
  events.push(e);
4074
+ return e;
4082
4075
  }
4083
4076
  }, operations, 0))));
4084
- if (stacks.every((s => s.length === 0))) {
4085
- return prompts[0];
4086
- } else if ((ctx.config?.eliticism ?? AgenticaConstant.ELITICISM) === true) {
4077
+ if ((ctx.config?.eliticism ?? AgenticaConstant.ELITICISM) === true && stacks.some((s => s.length !== 0))) {
4087
4078
  return step(ctx, stacks.flat().map((s => ctx.operations.group.get(s.operation.controller.name).get(s.operation.function.name))), 0);
4079
+ } else {
4080
+ const selected = events.filter((e => e.type === "select"));
4081
+ (selected.length !== 0 ? selected : events).forEach(ctx.dispatch);
4088
4082
  }
4089
- const collection = createSelectHistory({
4090
- id: v4(),
4091
- selections: []
4092
- });
4093
- for (const e of events) {
4094
- if (e.type === "select") {
4095
- collection.selections.push(e.selection);
4096
- await selectFunction(ctx, {
4097
- name: e.selection.operation.name,
4098
- reason: e.selection.reason
4099
- });
4100
- }
4101
- }
4102
- return [ collection ];
4103
4083
  }
4104
4084
 
4105
4085
  async function step(ctx, operations, retry, failures) {
@@ -4236,14 +4216,12 @@ async function step(ctx, operations, retry, failures) {
4236
4216
  return step(ctx, operations, retry, failures);
4237
4217
  }
4238
4218
  }
4239
- const prompts = [];
4240
4219
  for (const choice of completion.choices) {
4241
4220
  if (choice.message.tool_calls != null) {
4242
4221
  for (const tc of choice.message.tool_calls) {
4243
4222
  if (tc.type !== "function") {
4244
4223
  continue;
4245
- }
4246
- if (tc.function.name !== "selectFunctions") {
4224
+ } else if (tc.function.name !== "selectFunctions") {
4247
4225
  continue;
4248
4226
  }
4249
4227
  const input = (() => {
@@ -4258,39 +4236,21 @@ async function step(ctx, operations, retry, failures) {
4258
4236
  if (input === null) {
4259
4237
  continue;
4260
4238
  }
4261
- const collection = createSelectHistory({
4262
- id: tc.id,
4263
- selections: []
4264
- });
4265
4239
  for (const reference of input.functions) {
4266
- const operation = await selectFunction(ctx, reference);
4267
- if (operation === null) {
4268
- continue;
4269
- }
4270
- collection.selections.push(createOperationSelection({
4271
- operation,
4272
- reason: reference.reason
4273
- }));
4274
- }
4275
- if (collection.selections.length !== 0) {
4276
- prompts.push(collection);
4240
+ selectFunctionFromContext(ctx, reference);
4277
4241
  }
4278
4242
  }
4279
4243
  }
4280
4244
  if (choice.message.role === "assistant" && choice.message.content != null && choice.message.content.length !== 0) {
4281
- const text = createAssistantMessageHistory({
4282
- text: choice.message.content
4283
- });
4284
- prompts.push(text);
4285
- ctx.dispatch(creatAssistantEvent({
4286
- stream: toAsyncGenerator(text.text),
4287
- join: async () => Promise.resolve(text.text),
4245
+ const event = creatAssistantMessageEvent({
4246
+ stream: toAsyncGenerator(choice.message.content),
4247
+ join: async () => Promise.resolve(choice.message.content),
4288
4248
  done: () => true,
4289
- get: () => text.text
4290
- })).catch((() => {}));
4249
+ get: () => choice.message.content
4250
+ });
4251
+ ctx.dispatch(event);
4291
4252
  }
4292
4253
  }
4293
- return prompts;
4294
4254
  }
4295
4255
 
4296
4256
  function emendMessages(failures) {
@@ -4316,36 +4276,32 @@ function emendMessages(failures) {
4316
4276
 
4317
4277
  function execute(executor) {
4318
4278
  return async ctx => {
4319
- const histories = [];
4320
4279
  if (ctx.ready() === false) {
4321
4280
  if (executor?.initialize !== true && typeof executor?.initialize !== "function") {
4322
4281
  await ctx.initialize();
4323
4282
  } else {
4324
- histories.push(...await (typeof executor?.initialize === "function" ? executor.initialize : initialize)(ctx));
4283
+ await (typeof executor?.initialize === "function" ? executor.initialize : initialize)(ctx);
4325
4284
  if (ctx.ready() === false) {
4326
- return histories;
4285
+ return;
4327
4286
  }
4328
4287
  }
4329
4288
  }
4330
4289
  if (ctx.stack.length !== 0) {
4331
- histories.push(...await (executor?.cancel ?? cancel)(ctx));
4290
+ await (executor?.cancel ?? cancel)(ctx);
4332
4291
  }
4333
- histories.push(...await (executor?.select ?? select)(ctx));
4292
+ await (executor?.select ?? select)(ctx);
4334
4293
  if (ctx.stack.length === 0) {
4335
- return histories;
4294
+ return;
4336
4295
  }
4337
4296
  while (true) {
4338
- const prompts = await (executor?.call ?? call)(ctx, ctx.stack.map((s => s.operation)));
4339
- histories.push(...prompts);
4340
- const executes = prompts.filter((prompt => prompt.type === "execute"));
4297
+ const executes = await (executor?.call ?? call)(ctx, ctx.stack.map((s => s.operation)));
4341
4298
  if (executor?.describe !== null && executor?.describe !== false) {
4342
- histories.push(...await (typeof executor?.describe === "function" ? executor.describe : describe)(ctx, executes));
4299
+ await (typeof executor?.describe === "function" ? executor.describe : describe)(ctx, executes);
4343
4300
  }
4344
4301
  if (executes.length === 0 || ctx.stack.length === 0) {
4345
4302
  break;
4346
4303
  }
4347
4304
  }
4348
- return histories;
4349
4305
  };
4350
4306
  }
4351
4307
 
@@ -4399,32 +4355,35 @@ function transformUserMessage(props) {
4399
4355
  function transformSelect(props) {
4400
4356
  return createSelectHistory({
4401
4357
  id: props.history.id,
4402
- selections: props.history.selections.map((select => createOperationSelection({
4358
+ created_at: props.history.created_at,
4359
+ selection: createOperationSelection({
4403
4360
  operation: findOperation({
4404
4361
  operations: props.operations,
4405
- input: select.operation
4362
+ input: props.history.selection.operation
4406
4363
  }),
4407
- reason: select.reason
4408
- })))
4364
+ reason: props.history.selection.reason
4365
+ })
4409
4366
  });
4410
4367
  }
4411
4368
 
4412
4369
  function transformCancel(props) {
4413
4370
  return createCancelHistory({
4414
4371
  id: props.history.id,
4415
- selections: props.history.selections.map((select => createOperationSelection({
4372
+ created_at: props.history.created_at,
4373
+ selection: createOperationSelection({
4416
4374
  operation: findOperation({
4417
4375
  operations: props.operations,
4418
- input: select.operation
4376
+ input: props.history.selection.operation
4419
4377
  }),
4420
- reason: select.reason
4421
- })))
4378
+ reason: props.history.selection.reason
4379
+ })
4422
4380
  });
4423
4381
  }
4424
4382
 
4425
4383
  function transformExecute(props) {
4426
4384
  return createExecuteHistory({
4427
4385
  id: props.history.id,
4386
+ created_at: props.history.created_at,
4428
4387
  operation: findOperation({
4429
4388
  operations: props.operations,
4430
4389
  input: props.history.operation
@@ -4436,6 +4395,8 @@ function transformExecute(props) {
4436
4395
 
4437
4396
  function transformDescribe(props) {
4438
4397
  return createDescribeHistory({
4398
+ id: props.history.id,
4399
+ created_at: props.history.created_at,
4439
4400
  text: props.history.text,
4440
4401
  executes: props.history.executes.map((next => transformExecute({
4441
4402
  operations: props.operations,
@@ -4465,9 +4426,10 @@ class Agentica {
4465
4426
  operations: this.operations_.group,
4466
4427
  history: input
4467
4428
  })));
4429
+ this.executor_ = typeof props.config?.executor === "function" ? props.config.executor : execute(props.config?.executor ?? null);
4430
+ this.semaphore_ = props.vendor.semaphore != null ? typeof props.vendor.semaphore === "object" ? props.vendor.semaphore : new Semaphore(props.vendor.semaphore) : null;
4468
4431
  this.token_usage_ = this.props.tokenUsage !== undefined ? this.props.tokenUsage instanceof AgenticaTokenUsage ? this.props.tokenUsage : new AgenticaTokenUsage(this.props.tokenUsage) : AgenticaTokenUsage.zero();
4469
4432
  this.ready_ = false;
4470
- this.executor_ = typeof props.config?.executor === "function" ? props.config.executor : execute(props.config?.executor ?? null);
4471
4433
  }
4472
4434
  clone() {
4473
4435
  return new Agentica({
@@ -4476,22 +4438,36 @@ class Agentica {
4476
4438
  });
4477
4439
  }
4478
4440
  async conversate(content, options = {}) {
4479
- const prompt = createUserMessageHistory({
4441
+ const historyGetters = [];
4442
+ const dispatch = event => {
4443
+ this.dispatch(event).catch((() => {}));
4444
+ if ("toHistory" in event) {
4445
+ if ("join" in event) {
4446
+ historyGetters.push((async () => {
4447
+ await event.join();
4448
+ return event.toHistory();
4449
+ }));
4450
+ } else {
4451
+ historyGetters.push((async () => event.toHistory()));
4452
+ }
4453
+ }
4454
+ };
4455
+ const prompt = createUserMessageEvent({
4480
4456
  contents: Array.isArray(content) ? content : typeof content === "string" ? [ {
4481
4457
  type: "text",
4482
4458
  text: content
4483
4459
  } ] : [ content ]
4484
4460
  });
4485
- this.dispatch(createUserMessageEvent({
4486
- contents: prompt.contents
4487
- })).catch((() => {}));
4488
- const newbie = await this.executor_(this.getContext({
4489
- prompt,
4461
+ dispatch(prompt);
4462
+ await this.executor_(this.getContext({
4463
+ dispatch,
4464
+ prompt: prompt.toHistory(),
4490
4465
  abortSignal: options.abortSignal,
4491
4466
  usage: this.token_usage_
4492
4467
  }));
4493
- this.histories_.push(prompt, ...newbie);
4494
- return [ prompt, ...newbie ];
4468
+ const completed = await Promise.all(historyGetters.map((async h => h())));
4469
+ this.histories_.push(...completed);
4470
+ return completed;
4495
4471
  }
4496
4472
  getConfig() {
4497
4473
  return this.props.config;
@@ -4512,7 +4488,58 @@ class Agentica {
4512
4488
  return this.token_usage_;
4513
4489
  }
4514
4490
  getContext(props) {
4515
- const dispatch = async event => this.dispatch(event);
4491
+ const request = async (source, body) => {
4492
+ const event = createRequestEvent({
4493
+ source,
4494
+ body: {
4495
+ ...body,
4496
+ model: this.props.vendor.model,
4497
+ stream: true,
4498
+ stream_options: {
4499
+ include_usage: true
4500
+ }
4501
+ },
4502
+ options: {
4503
+ ...this.props.vendor.options,
4504
+ signal: props.abortSignal
4505
+ }
4506
+ });
4507
+ props.dispatch(event);
4508
+ const completion = await this.props.vendor.api.chat.completions.create(event.body, event.options);
4509
+ const [streamForEvent, temporaryStream] = StreamUtil.transform(completion.toReadableStream(), (value => ChatGptCompletionMessageUtil.transformCompletionChunk(value))).tee();
4510
+ const [streamForAggregate, streamForReturn] = temporaryStream.tee();
4511
+ (async () => {
4512
+ const reader = streamForAggregate.getReader();
4513
+ while (true) {
4514
+ const chunk = await reader.read();
4515
+ if (chunk.done) {
4516
+ break;
4517
+ }
4518
+ if (chunk.value.usage != null) {
4519
+ AgenticaTokenUsageAggregator.aggregate({
4520
+ kind: source,
4521
+ completionUsage: chunk.value.usage,
4522
+ usage: props.usage
4523
+ });
4524
+ }
4525
+ }
4526
+ })().catch((() => {}));
4527
+ const [streamForStream, streamForJoin] = streamForEvent.tee();
4528
+ props.dispatch({
4529
+ id: v4(),
4530
+ type: "response",
4531
+ source,
4532
+ stream: streamDefaultReaderToAsyncGenerator(streamForStream.getReader()),
4533
+ body: event.body,
4534
+ options: event.options,
4535
+ join: async () => {
4536
+ const chunks = await StreamUtil.readAll(streamForJoin);
4537
+ return ChatGptCompletionMessageUtil.merge(chunks);
4538
+ },
4539
+ created_at: (new Date).toISOString()
4540
+ });
4541
+ return streamForReturn;
4542
+ };
4516
4543
  return {
4517
4544
  operations: this.operations_,
4518
4545
  config: this.props.config,
@@ -4521,60 +4548,18 @@ class Agentica {
4521
4548
  ready: () => this.ready_,
4522
4549
  prompt: props.prompt,
4523
4550
  abortSignal: props.abortSignal,
4524
- dispatch: async event => this.dispatch(event),
4525
- request: async (source, body) => {
4526
- const event = createRequestEvent({
4527
- source,
4528
- body: {
4529
- ...body,
4530
- model: this.props.vendor.model,
4531
- stream: true,
4532
- stream_options: {
4533
- include_usage: true
4534
- }
4535
- },
4536
- options: {
4537
- ...this.props.vendor.options,
4538
- signal: props.abortSignal
4539
- }
4540
- });
4541
- await dispatch(event);
4542
- const completion = await this.props.vendor.api.chat.completions.create(event.body, event.options);
4543
- const [streamForEvent, temporaryStream] = StreamUtil.transform(completion.toReadableStream(), (value => ChatGptCompletionMessageUtil.transformCompletionChunk(value))).tee();
4544
- const [streamForAggregate, streamForReturn] = temporaryStream.tee();
4545
- (async () => {
4546
- const reader = streamForAggregate.getReader();
4547
- while (true) {
4548
- const chunk = await reader.read();
4549
- if (chunk.done) {
4550
- break;
4551
- }
4552
- if (chunk.value.usage != null) {
4553
- AgenticaTokenUsageAggregator.aggregate({
4554
- kind: source,
4555
- completionUsage: chunk.value.usage,
4556
- usage: props.usage
4557
- });
4558
- }
4559
- }
4560
- })().catch((() => {}));
4561
- const [streamForStream, streamForJoin] = streamForEvent.tee();
4562
- await dispatch({
4563
- type: "response",
4564
- source,
4565
- stream: streamDefaultReaderToAsyncGenerator(streamForStream.getReader()),
4566
- body: event.body,
4567
- options: event.options,
4568
- join: async () => {
4569
- const chunks = await StreamUtil.readAll(streamForJoin);
4570
- return ChatGptCompletionMessageUtil.merge(chunks);
4571
- }
4572
- });
4573
- return streamForReturn;
4551
+ dispatch: props.dispatch,
4552
+ request: this.semaphore_ === null ? request : async (source, body) => {
4553
+ await this.semaphore_.acquire();
4554
+ try {
4555
+ return await request(source, body);
4556
+ } finally {
4557
+ void this.semaphore_.release().catch((() => {}));
4558
+ }
4574
4559
  },
4575
4560
  initialize: async () => {
4576
4561
  this.ready_ = true;
4577
- await dispatch(createInitializeEvent());
4562
+ props.dispatch(createInitializeEvent());
4578
4563
  }
4579
4564
  };
4580
4565
  }
@@ -4604,6 +4589,31 @@ class Agentica {
4604
4589
  }
4605
4590
  }
4606
4591
 
4592
+ var index$2 = Object.freeze({
4593
+ __proto__: null,
4594
+ creatAssistantMessageEvent,
4595
+ createAssistantMessageHistory,
4596
+ createCallEvent,
4597
+ createCancelEvent,
4598
+ createCancelHistory,
4599
+ createDescribeEvent,
4600
+ createDescribeHistory,
4601
+ createExecuteEvent,
4602
+ createExecuteHistory,
4603
+ createInitializeEvent,
4604
+ createOperationSelection,
4605
+ createRequestEvent,
4606
+ createResponseEvent,
4607
+ createSelectEvent,
4608
+ createSelectHistory,
4609
+ createSystemMessageHistory,
4610
+ createUserMessageEvent,
4611
+ createUserMessageHistory,
4612
+ createValidateEvent,
4613
+ decodeHistory,
4614
+ decodeUserMessageContent
4615
+ });
4616
+
4607
4617
  function assertHttpController(props) {
4608
4618
  const document = OpenApi.convert((() => {
4609
4619
  const _io0 = input => null !== input.swagger && undefined !== input.swagger && ("2.0" === input.swagger || "string" === typeof input.swagger && RegExp(/^2\.0\.[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/).test(input.swagger)) && (undefined === input.info || "object" === typeof input.info && null !== input.info && _io1(input.info)) && (undefined === input.host || "string" === typeof input.host) && (undefined === input.basePath || "string" === typeof input.basePath) && (undefined === input.consumes || Array.isArray(input.consumes) && input.consumes.every((elem => "string" === typeof elem))) && (undefined === input.produces || Array.isArray(input.produces) && input.produces.every((elem => "string" === typeof elem))) && (undefined === input.definitions || "object" === typeof input.definitions && null !== input.definitions && false === Array.isArray(input.definitions) && _io4(input.definitions)) && (undefined === input.parameters || "object" === typeof input.parameters && null !== input.parameters && false === Array.isArray(input.parameters) && _io16(input.parameters)) && (undefined === input.responses || "object" === typeof input.responses && null !== input.responses && false === Array.isArray(input.responses) && _io29(input.responses)) && (undefined === input.securityDefinitions || "object" === typeof input.securityDefinitions && null !== input.securityDefinitions && false === Array.isArray(input.securityDefinitions) && _io31(input.securityDefinitions)) && (undefined === input.security || Array.isArray(input.security) && input.security.every((elem => "object" === typeof elem && null !== elem && false === Array.isArray(elem) && _io39(elem)))) && (undefined === input.paths || "object" === typeof input.paths && null !== input.paths && false === Array.isArray(input.paths) && _io40(input.paths)) && (undefined === input.tags || Array.isArray(input.tags) && input.tags.every((elem => "object" === typeof elem && null !== elem && _io47(elem))));
@@ -43280,6 +43290,7 @@ class MicroAgentica {
43280
43290
  })));
43281
43291
  this.token_usage_ = this.props.tokenUsage !== undefined ? this.props.tokenUsage instanceof AgenticaTokenUsage ? this.props.tokenUsage : new AgenticaTokenUsage(this.props.tokenUsage) : AgenticaTokenUsage.zero();
43282
43292
  this.listeners_ = new Map;
43293
+ this.semaphore_ = props.vendor.semaphore != null ? typeof props.vendor.semaphore === "object" ? props.vendor.semaphore : new Semaphore(props.vendor.semaphore) : null;
43283
43294
  }
43284
43295
  clone() {
43285
43296
  return new MicroAgentica({
@@ -43288,26 +43299,39 @@ class MicroAgentica {
43288
43299
  });
43289
43300
  }
43290
43301
  async conversate(content) {
43291
- const talk = createUserMessageHistory({
43302
+ const histories = [];
43303
+ const dispatch = event => {
43304
+ this.dispatch(event).catch((() => {}));
43305
+ if ("toHistory" in event) {
43306
+ if ("join" in event) {
43307
+ histories.push((async () => {
43308
+ await event.join();
43309
+ return event.toHistory();
43310
+ }));
43311
+ } else {
43312
+ histories.push((async () => event.toHistory()));
43313
+ }
43314
+ }
43315
+ };
43316
+ const prompt = createUserMessageEvent({
43292
43317
  contents: Array.isArray(content) ? content : typeof content === "string" ? [ {
43293
43318
  type: "text",
43294
43319
  text: content
43295
43320
  } ] : [ content ]
43296
43321
  });
43297
- this.dispatch(createUserMessageEvent({
43298
- contents: talk.contents
43299
- })).catch((() => {}));
43322
+ dispatch(prompt);
43300
43323
  const ctx = this.getContext({
43301
- prompt: talk,
43324
+ prompt,
43325
+ dispatch,
43302
43326
  usage: this.token_usage_
43303
43327
  });
43304
- const histories = await call(ctx, this.operations_.array);
43305
- const executes = histories.filter((p => p.type === "execute"));
43306
- if (executes.length && ctx.config?.executor?.describe !== null && ctx.config?.executor?.describe !== false) {
43307
- histories.push(...await describe(ctx, executes));
43328
+ const executes = await call(ctx, this.operations_.array);
43329
+ if (executes.length) {
43330
+ await describe(ctx, executes);
43308
43331
  }
43309
- this.histories_.push(talk, ...histories);
43310
- return histories;
43332
+ const completed = await Promise.all(histories.map((async h => h())));
43333
+ this.histories_.push(...completed);
43334
+ return completed;
43311
43335
  }
43312
43336
  getConfig() {
43313
43337
  return this.props.config;
@@ -43328,59 +43352,68 @@ class MicroAgentica {
43328
43352
  return this.token_usage_;
43329
43353
  }
43330
43354
  getContext(props) {
43331
- const dispatch = this.dispatch.bind(this);
43355
+ const request = async (source, body) => {
43356
+ const event = createRequestEvent({
43357
+ source,
43358
+ body: {
43359
+ ...body,
43360
+ model: this.props.vendor.model,
43361
+ stream: true,
43362
+ stream_options: {
43363
+ include_usage: true
43364
+ }
43365
+ },
43366
+ options: this.props.vendor.options
43367
+ });
43368
+ props.dispatch(event);
43369
+ const completion = await this.props.vendor.api.chat.completions.create(event.body, event.options);
43370
+ const [streamForEvent, temporaryStream] = StreamUtil.transform(completion.toReadableStream(), (value => ChatGptCompletionMessageUtil.transformCompletionChunk(value))).tee();
43371
+ const [streamForAggregate, streamForReturn] = temporaryStream.tee();
43372
+ void (async () => {
43373
+ const reader = streamForAggregate.getReader();
43374
+ while (true) {
43375
+ const chunk = await reader.read();
43376
+ if (chunk.done) {
43377
+ break;
43378
+ }
43379
+ if (chunk.value.usage != null) {
43380
+ AgenticaTokenUsageAggregator.aggregate({
43381
+ kind: source,
43382
+ completionUsage: chunk.value.usage,
43383
+ usage: props.usage
43384
+ });
43385
+ }
43386
+ }
43387
+ })().catch((() => {}));
43388
+ const [streamForStream, streamForJoin] = streamForEvent.tee();
43389
+ props.dispatch({
43390
+ id: v4(),
43391
+ type: "response",
43392
+ source,
43393
+ stream: streamDefaultReaderToAsyncGenerator(streamForStream.getReader()),
43394
+ body: event.body,
43395
+ options: event.options,
43396
+ join: async () => {
43397
+ const chunks = await StreamUtil.readAll(streamForJoin);
43398
+ return ChatGptCompletionMessageUtil.merge(chunks);
43399
+ },
43400
+ created_at: (new Date).toISOString()
43401
+ });
43402
+ return streamForReturn;
43403
+ };
43332
43404
  return {
43333
43405
  operations: this.operations_,
43334
43406
  config: this.props.config,
43335
43407
  histories: this.histories_,
43336
43408
  prompt: props.prompt,
43337
- dispatch,
43338
- request: async (source, body) => {
43339
- const event = createRequestEvent({
43340
- source,
43341
- body: {
43342
- ...body,
43343
- model: this.props.vendor.model,
43344
- stream: true,
43345
- stream_options: {
43346
- include_usage: true
43347
- }
43348
- },
43349
- options: this.props.vendor.options
43350
- });
43351
- await dispatch(event);
43352
- const completion = await this.props.vendor.api.chat.completions.create(event.body, event.options);
43353
- const [streamForEvent, temporaryStream] = StreamUtil.transform(completion.toReadableStream(), (value => ChatGptCompletionMessageUtil.transformCompletionChunk(value))).tee();
43354
- const [streamForAggregate, streamForReturn] = temporaryStream.tee();
43355
- void (async () => {
43356
- const reader = streamForAggregate.getReader();
43357
- while (true) {
43358
- const chunk = await reader.read();
43359
- if (chunk.done) {
43360
- break;
43361
- }
43362
- if (chunk.value.usage != null) {
43363
- AgenticaTokenUsageAggregator.aggregate({
43364
- kind: source,
43365
- completionUsage: chunk.value.usage,
43366
- usage: props.usage
43367
- });
43368
- }
43369
- }
43370
- })();
43371
- const [streamForStream, streamForJoin] = streamForEvent.tee();
43372
- await dispatch({
43373
- type: "response",
43374
- source,
43375
- stream: streamDefaultReaderToAsyncGenerator(streamForStream.getReader()),
43376
- body: event.body,
43377
- options: event.options,
43378
- join: async () => {
43379
- const chunks = await StreamUtil.readAll(streamForJoin);
43380
- return ChatGptCompletionMessageUtil.merge(chunks);
43381
- }
43382
- });
43383
- return streamForReturn;
43409
+ dispatch: props.dispatch,
43410
+ request: this.semaphore_ === null ? request : async (source, body) => {
43411
+ await this.semaphore_.acquire();
43412
+ try {
43413
+ return await request(source, body);
43414
+ } finally {
43415
+ void this.semaphore_.release().catch((() => {}));
43416
+ }
43384
43417
  }
43385
43418
  };
43386
43419
  }