plugin-agent-orchestrator 1.0.17 → 1.0.19

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 (141) hide show
  1. package/dist/client/AIEmployeeSelect.d.ts +11 -0
  2. package/dist/client/AIEmployeesContext.d.ts +30 -0
  3. package/dist/client/AgentRunsTab.d.ts +2 -0
  4. package/dist/client/HarnessProfilesTab.d.ts +2 -0
  5. package/dist/client/OrchestratorSettings.d.ts +3 -0
  6. package/dist/client/RulesTab.d.ts +2 -0
  7. package/dist/client/TracingTab.d.ts +2 -0
  8. package/dist/client/index.d.ts +1 -0
  9. package/dist/client/index.js +1 -1
  10. package/dist/client/plugin.d.ts +6 -0
  11. package/dist/client/skill-hub/components/ExecutionHistory.d.ts +2 -0
  12. package/dist/client/skill-hub/components/ExecutionProgress.d.ts +20 -0
  13. package/dist/client/skill-hub/components/GitSkillImport.d.ts +7 -0
  14. package/dist/client/skill-hub/components/LoopSettings.d.ts +2 -0
  15. package/dist/client/skill-hub/components/SkillEditor.d.ts +7 -0
  16. package/dist/client/skill-hub/components/SkillManager.d.ts +2 -0
  17. package/dist/client/skill-hub/components/SkillMetrics.d.ts +2 -0
  18. package/dist/client/skill-hub/components/SkillTestPanel.d.ts +7 -0
  19. package/dist/client/skill-hub/index.d.ts +11 -0
  20. package/dist/client/skill-hub/locale.d.ts +3 -0
  21. package/dist/client/skill-hub/tools/InteractionSchemasProvider.d.ts +6 -0
  22. package/dist/client/skill-hub/tools/SkillHubCard.d.ts +3 -0
  23. package/dist/client/skill-hub/tools/loopTemplates.d.ts +22 -0
  24. package/dist/client/skill-hub/tools/registerSkillLoopCards.d.ts +1 -0
  25. package/dist/client/skill-hub/utils/jsonFields.d.ts +3 -0
  26. package/dist/client/tools/PlanApprovalCard.d.ts +3 -0
  27. package/dist/client/tools/registerOrchestratorCards.d.ts +1 -0
  28. package/dist/externalVersion.js +6 -6
  29. package/dist/index.d.ts +2 -0
  30. package/dist/server/collections/agent-execution-spans.d.ts +9 -0
  31. package/dist/server/collections/agent-harness-profiles.d.ts +2 -0
  32. package/dist/server/collections/agent-harness-profiles.js +89 -0
  33. package/dist/server/collections/agent-loop-events.d.ts +2 -0
  34. package/dist/server/collections/agent-loop-events.js +101 -0
  35. package/dist/server/collections/agent-loop-runs.d.ts +2 -0
  36. package/dist/server/collections/agent-loop-runs.js +188 -0
  37. package/dist/server/collections/agent-loop-steps.d.ts +2 -0
  38. package/dist/server/collections/agent-loop-steps.js +174 -0
  39. package/dist/server/collections/orchestrator-config.d.ts +2 -0
  40. package/dist/server/collections/orchestrator-config.js +7 -0
  41. package/dist/server/collections/orchestrator-logs.d.ts +8 -0
  42. package/dist/server/collections/skill-definitions.d.ts +3 -0
  43. package/dist/server/collections/skill-executions.d.ts +3 -0
  44. package/dist/server/collections/skill-executions.js +12 -0
  45. package/dist/server/collections/skill-loop-configs.d.ts +3 -0
  46. package/dist/server/collections/skill-loop-configs.js +94 -0
  47. package/dist/server/collections/skill-worker-configs.d.ts +3 -0
  48. package/dist/server/index.d.ts +1 -0
  49. package/dist/server/migrations/20260423000000-add-progress-fields.d.ts +4 -0
  50. package/dist/server/migrations/20260425000000-add-interaction-schema.d.ts +4 -0
  51. package/dist/server/migrations/20260427000000-add-tracing-detail-fields.d.ts +7 -0
  52. package/dist/server/migrations/20260427000000-change-packages-to-text.d.ts +4 -0
  53. package/dist/server/migrations/20260427000001-change-other-json-to-text.d.ts +4 -0
  54. package/dist/server/migrations/20260429000000-add-llm-fields.d.ts +7 -0
  55. package/dist/server/migrations/20260429000000-fix-inputargs-json-to-text.d.ts +16 -0
  56. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.d.ts +7 -0
  57. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.d.ts +7 -0
  58. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +55 -0
  59. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.d.ts +12 -0
  60. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.js +162 -0
  61. package/dist/server/plugin.d.ts +16 -0
  62. package/dist/server/plugin.js +13 -0
  63. package/dist/server/resources/agent-loop.d.ts +3 -0
  64. package/dist/server/resources/agent-loop.js +205 -0
  65. package/dist/server/resources/tracing.d.ts +7 -0
  66. package/dist/server/services/AgentHarness.d.ts +42 -0
  67. package/dist/server/services/AgentHarness.js +565 -0
  68. package/dist/server/services/AgentLoopController.d.ts +205 -0
  69. package/dist/server/services/AgentLoopController.js +940 -0
  70. package/dist/server/services/AgentLoopRepository.d.ts +20 -0
  71. package/dist/server/services/AgentLoopRepository.js +210 -0
  72. package/dist/server/services/AgentLoopService.d.ts +149 -0
  73. package/dist/server/services/AgentLoopService.js +133 -0
  74. package/dist/server/services/AgentPlanValidator.d.ts +4 -0
  75. package/dist/server/services/AgentPlanValidator.js +99 -0
  76. package/dist/server/services/AgentPlannerService.d.ts +8 -0
  77. package/dist/server/services/AgentPlannerService.js +119 -0
  78. package/dist/server/services/AgentRegistryService.d.ts +13 -0
  79. package/dist/server/services/AgentRegistryService.js +178 -0
  80. package/dist/server/services/CodeValidator.d.ts +32 -0
  81. package/dist/server/services/ExecutionSpanService.d.ts +46 -0
  82. package/dist/server/services/FileManager.d.ts +28 -0
  83. package/dist/server/services/SandboxRunner.d.ts +41 -0
  84. package/dist/server/services/SkillManager.d.ts +6 -0
  85. package/dist/server/services/SkillRepositoryService.d.ts +22 -0
  86. package/dist/server/services/WorkerEnvManager.d.ts +26 -0
  87. package/dist/server/skill-hub/actions/git-import.d.ts +21 -0
  88. package/dist/server/skill-hub/mcp/McpController.d.ts +15 -0
  89. package/dist/server/skill-hub/plugin.d.ts +61 -0
  90. package/dist/server/skill-hub/plugin.js +152 -54
  91. package/dist/server/skill-hub/tasks/SkillExecutionTask.d.ts +16 -0
  92. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +15 -0
  93. package/dist/server/skill-hub/utils/json-fields.d.ts +7 -0
  94. package/dist/server/tools/agent-loop.d.ts +235 -0
  95. package/dist/server/tools/agent-loop.js +406 -0
  96. package/dist/server/tools/delegate-task.d.ts +19 -0
  97. package/dist/server/tools/delegate-task.js +19 -368
  98. package/dist/server/tools/external-rag-search.d.ts +42 -0
  99. package/dist/server/tools/orchestrator-plan.d.ts +205 -0
  100. package/dist/server/tools/orchestrator-plan.js +291 -0
  101. package/dist/server/tools/skill-execute.d.ts +36 -0
  102. package/dist/server/tools/skill-execute.js +2 -0
  103. package/package.json +1 -1
  104. package/src/client/AgentRunsTab.tsx +764 -0
  105. package/src/client/HarnessProfilesTab.tsx +247 -0
  106. package/src/client/OrchestratorSettings.tsx +40 -2
  107. package/src/client/RulesTab.tsx +103 -6
  108. package/src/client/plugin.tsx +27 -54
  109. package/src/client/skill-hub/components/LoopSettings.tsx +331 -0
  110. package/src/client/skill-hub/index.tsx +51 -75
  111. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +56 -16
  112. package/src/client/skill-hub/tools/SkillHubCard.tsx +35 -4
  113. package/src/client/skill-hub/tools/loopTemplates.ts +52 -0
  114. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +58 -0
  115. package/src/client/tools/PlanApprovalCard.tsx +175 -0
  116. package/src/client/tools/registerOrchestratorCards.ts +7 -0
  117. package/src/server/collections/agent-harness-profiles.ts +59 -0
  118. package/src/server/collections/agent-loop-events.ts +71 -0
  119. package/src/server/collections/agent-loop-runs.ts +158 -0
  120. package/src/server/collections/agent-loop-steps.ts +144 -0
  121. package/src/server/collections/orchestrator-config.ts +7 -0
  122. package/src/server/collections/skill-executions.ts +63 -51
  123. package/src/server/collections/skill-loop-configs.ts +65 -0
  124. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +30 -0
  125. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +142 -0
  126. package/src/server/plugin.ts +15 -0
  127. package/src/server/resources/agent-loop.ts +183 -0
  128. package/src/server/services/AgentHarness.ts +663 -0
  129. package/src/server/services/AgentLoopController.ts +1128 -0
  130. package/src/server/services/AgentLoopRepository.ts +194 -0
  131. package/src/server/services/AgentLoopService.ts +161 -0
  132. package/src/server/services/AgentPlanValidator.ts +73 -0
  133. package/src/server/services/AgentPlannerService.ts +93 -0
  134. package/src/server/services/AgentRegistryService.ts +169 -0
  135. package/src/server/services/ExecutionSpanService.ts +2 -0
  136. package/src/server/skill-hub/plugin.ts +897 -771
  137. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +15 -0
  138. package/src/server/tools/agent-loop.ts +399 -0
  139. package/src/server/tools/delegate-task.ts +23 -485
  140. package/src/server/tools/orchestrator-plan.ts +279 -0
  141. package/src/server/tools/skill-execute.ts +68 -64
@@ -32,9 +32,6 @@ __export(delegate_task_exports, {
32
32
  module.exports = __toCommonJS(delegate_task_exports);
33
33
  var import_zod = require("zod");
34
34
  var import_crypto = require("crypto");
35
- var import_prebuilt = require("@langchain/langgraph/prebuilt");
36
- var import_tools = require("@langchain/core/tools");
37
- var import_messages = require("@langchain/core/messages");
38
35
  var import_ExecutionSpanService = require("../services/ExecutionSpanService");
39
36
  const ORCHESTRATOR_DEPTH_KEY = "__orchestratorDepth";
40
37
  const ORCHESTRATOR_PATH_KEY = "__orchestratorPath";
@@ -97,7 +94,7 @@ function createDelegateToolOptions(plugin, options) {
97
94
  return {
98
95
  scope: "CUSTOM",
99
96
  execution: "backend",
100
- defaultPermission: "ALLOW",
97
+ defaultPermission: "ASK",
101
98
  silence: false,
102
99
  introduction: {
103
100
  title: `[${leaderUsername}] ${subAgentEmployee.nickname || subAgentUsername}${legacyAlias ? " (legacy)" : ""}`,
@@ -206,7 +203,7 @@ ${subAgentList}`
206
203
  return {
207
204
  scope: "CUSTOM",
208
205
  execution: "backend",
209
- defaultPermission: "ALLOW",
206
+ defaultPermission: "ASK",
210
207
  silence: false,
211
208
  introduction: {
212
209
  title: `[${leaderUsername}] Dispatch sub-agents`,
@@ -555,7 +552,6 @@ function invalidateDelegateToolsCache() {
555
552
  registeredDelegateNamesByPlugin = /* @__PURE__ */ new WeakMap();
556
553
  }
557
554
  async function invokeDelegateTask(ctx, plugin, options) {
558
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
559
555
  const {
560
556
  leaderUsername,
561
557
  subAgentUsername,
@@ -614,320 +610,31 @@ async function invokeDelegateTask(ctx, plugin, options) {
614
610
  content: `Delegation depth limit reached (${currentDepth}/${maxDepth}). Sub-agent "${subAgentUsername}" cannot delegate further.`
615
611
  };
616
612
  }
617
- const spanService = new import_ExecutionSpanService.ExecutionSpanService(plugin);
618
613
  const upstreamTraceContext = (0, import_ExecutionSpanService.getOrchestratorTraceContext)(ctx);
619
614
  const rootRunId = providedRootRunId || (upstreamTraceContext == null ? void 0 : upstreamTraceContext.rootRunId) || createRootRunId(`${leaderUsername}:${subAgentUsername}`);
620
615
  const parentSpanId = providedParentSpanId || (upstreamTraceContext == null ? void 0 : upstreamTraceContext.spanId) || (upstreamTraceContext == null ? void 0 : upstreamTraceContext.parentSpanId);
621
- const startTime = Date.now();
622
- const trace = [
623
- {
624
- type: "start",
625
- at: nowIso(),
626
- title: `Delegation started: ${leaderUsername} -> ${subAgentUsername}`,
627
- content: task
628
- }
629
- ];
630
- const executionSpan = await spanService.create({
631
- rootRunId,
632
- parentSpanId,
633
- type: "sub_agent",
634
- status: "running",
635
- leaderUsername,
636
- employeeUsername: subAgentUsername,
637
- title: `Delegation: ${leaderUsername} -> ${subAgentUsername}`,
638
- input: { task, context },
639
- metadata: {
640
- depth: currentDepth,
641
- maxDepth,
642
- toolName,
643
- recursionLimit,
644
- llmOverride: llmService && model ? { llmService, model } : void 0
645
- },
646
- userId: ctxSnapshot.userId
647
- });
648
- const executionSpanId = (executionSpan == null ? void 0 : executionSpan.id) ? String(executionSpan.id) : void 0;
649
- const logRecord = await logDelegation(ctx, plugin, {
616
+ const agentLoopRunId = upstreamTraceContext == null ? void 0 : upstreamTraceContext.agentLoopRunId;
617
+ const agentLoopStepId = upstreamTraceContext == null ? void 0 : upstreamTraceContext.agentLoopStepId;
618
+ return plugin.agentLoopService.harness.runSubAgent(ctx, {
650
619
  leaderUsername,
651
620
  subAgentUsername,
652
- toolName,
621
+ subAgentEmployee,
653
622
  task,
654
623
  context,
655
- result: "",
656
- status: "running",
657
- depth: currentDepth,
658
- durationMs: 0,
659
- trace,
660
- snapshot: ctxSnapshot
624
+ currentDepth,
625
+ currentPath,
626
+ maxDepth,
627
+ timeout,
628
+ toolCallId,
629
+ toolName,
630
+ llmService,
631
+ model,
632
+ recursionLimit,
633
+ rootRunId,
634
+ parentSpanId,
635
+ agentLoopRunId,
636
+ agentLoopStepId
661
637
  });
662
- if (executionSpanId && (logRecord == null ? void 0 : logRecord.id)) {
663
- await spanService.update(executionSpanId, { orchestratorLogId: logRecord.id });
664
- }
665
- try {
666
- const aiPlugin = ctx.app.pm.get("ai");
667
- if (!aiPlugin) {
668
- throw new Error("Plugin AI is not installed or enabled");
669
- }
670
- let modelSettings = hasModelSettings(subAgentEmployee.modelSettings) ? subAgentEmployee.modelSettings : void 0;
671
- if (llmService && model) {
672
- modelSettings = { llmService, model };
673
- }
674
- if (!hasModelSettings(modelSettings)) {
675
- const leaderEmployee = await plugin.db.getRepository("aiEmployees").findOne({
676
- filter: { username: leaderUsername }
677
- });
678
- const dynamicModel = (_c = (_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) == null ? void 0 : _c.model;
679
- modelSettings = hasModelSettings(leaderEmployee == null ? void 0 : leaderEmployee.modelSettings) ? leaderEmployee.modelSettings : hasModelSettings(dynamicModel) ? dynamicModel : void 0;
680
- if (!hasModelSettings(modelSettings)) {
681
- throw new Error(
682
- `Sub-agent "${subAgentUsername}" has no LLM model configured (and leader fallback failed). Please configure a model in the Orchestrator Config or AI Employee settings.`
683
- );
684
- }
685
- }
686
- const { provider } = await aiPlugin.aiManager.getLLMService({
687
- llmService: modelSettings.llmService,
688
- model: modelSettings.model
689
- });
690
- const chatModel = provider.createModel();
691
- const coreToolsManager = ctx.app.aiManager.toolsManager;
692
- const allTools = await coreToolsManager.listTools();
693
- const employeeSkills = (((_d = subAgentEmployee.skillSettings) == null ? void 0 : _d.skills) ?? []).map(
694
- (s) => typeof s === "string" ? { name: s, autoCall: false } : { name: s == null ? void 0 : s.name, autoCall: (s == null ? void 0 : s.autoCall) === true }
695
- ).filter((s) => Boolean(s.name));
696
- const employeeSkillMap = new Map(employeeSkills.map((skill) => [skill.name, skill]));
697
- const langchainTools = [];
698
- for (const toolEntry of allTools) {
699
- const entryName = toolEntry.definition.name;
700
- if (!entryName) continue;
701
- const employeeSkill = employeeSkillMap.get(entryName);
702
- if (!employeeSkill || isDelegateToolName(plugin, entryName) || employeeSkill.autoCall !== true) {
703
- continue;
704
- }
705
- langchainTools.push(
706
- new import_tools.DynamicStructuredTool({
707
- name: entryName.replace(/[^a-zA-Z0-9_-]/g, "_"),
708
- description: toolEntry.definition.description || entryName,
709
- schema: toolEntry.definition.schema || import_zod.z.object({}),
710
- func: async (toolArgs) => {
711
- var _a2;
712
- const invokeCtx = Object.create(ctx);
713
- invokeCtx[ORCHESTRATOR_DEPTH_KEY] = currentDepth + 1;
714
- invokeCtx[ORCHESTRATOR_PATH_KEY] = [...currentPath, subAgentUsername];
715
- invokeCtx._currentAIEmployee = subAgentUsername;
716
- if (ctx.state) {
717
- invokeCtx.state = Object.create(ctx.state);
718
- invokeCtx.state.currentAIEmployee = subAgentUsername;
719
- }
720
- const toolStartedAt = Date.now();
721
- const isSkillHubTool = entryName === "skill_hub_execute" || entryName.startsWith("skill_hub_");
722
- const toolSpan = await spanService.create({
723
- rootRunId,
724
- parentSpanId: executionSpanId,
725
- type: isSkillHubTool ? "skill" : "tool",
726
- status: "running",
727
- leaderUsername,
728
- employeeUsername: subAgentUsername,
729
- toolName: toolEntry.definition.name,
730
- title: isSkillHubTool ? `Skill: ${toolEntry.definition.name}` : `Tool: ${toolEntry.definition.name}`,
731
- input: toolArgs,
732
- metadata: {
733
- depth: currentDepth + 1,
734
- toolCallId: `orch-${toolCallId}`,
735
- defaultPermission: toolEntry.defaultPermission
736
- },
737
- userId: ctxSnapshot.userId
738
- });
739
- const toolSpanId = (toolSpan == null ? void 0 : toolSpan.id) ? String(toolSpan.id) : void 0;
740
- (0, import_ExecutionSpanService.setOrchestratorTraceContext)(invokeCtx, {
741
- rootRunId,
742
- spanId: toolSpanId,
743
- parentSpanId: executionSpanId,
744
- toolCallId: `orch-${toolCallId}`,
745
- leaderUsername,
746
- employeeUsername: subAgentUsername,
747
- toolName: toolEntry.definition.name
748
- });
749
- trace.push({
750
- type: "tool_call",
751
- at: nowIso(),
752
- title: `Calling tool: ${toolEntry.definition.name}`,
753
- toolName: toolEntry.definition.name,
754
- args: toolArgs
755
- });
756
- try {
757
- const res = await toolEntry.invoke(invokeCtx, toolArgs, `orch-${toolCallId}`);
758
- const output = truncateText((res == null ? void 0 : res.content) ?? (res == null ? void 0 : res.result) ?? res, 5e4);
759
- trace.push({
760
- type: "tool_result",
761
- at: nowIso(),
762
- title: `Tool finished: ${toolEntry.definition.name}`,
763
- toolName: toolEntry.definition.name,
764
- status: (res == null ? void 0 : res.status) || "success",
765
- content: truncateText(output, 2e3)
766
- });
767
- if ((res == null ? void 0 : res.status) === "error") {
768
- await spanService.finish(toolSpanId, "error", toolStartedAt, {
769
- output,
770
- error: truncateText(res.content || output, 1e4)
771
- });
772
- throw new Error(`Tool <${toolEntry.definition.name}> failed: ${res.content}`);
773
- }
774
- await spanService.finish(toolSpanId, "success", toolStartedAt, {
775
- output,
776
- skillExecutionId: ((_a2 = res == null ? void 0 : res.result) == null ? void 0 : _a2.execId) || (res == null ? void 0 : res.execId)
777
- });
778
- return typeof (res == null ? void 0 : res.content) === "string" ? res.content : JSON.stringify(res);
779
- } catch (e) {
780
- trace.push({
781
- type: "tool_error",
782
- at: nowIso(),
783
- title: `Tool failed: ${toolEntry.definition.name}`,
784
- toolName: toolEntry.definition.name,
785
- status: "error",
786
- content: e.message
787
- });
788
- await spanService.finish(toolSpanId, "error", toolStartedAt, {
789
- error: truncateText(e.message, 1e4)
790
- });
791
- throw e;
792
- }
793
- }
794
- })
795
- );
796
- }
797
- const abortController = new AbortController();
798
- const executor = (0, import_prebuilt.createReactAgent)({
799
- llm: chatModel,
800
- tools: langchainTools
801
- });
802
- let systemPrompt = ((_e = subAgentEmployee.chatSettings) == null ? void 0 : _e.systemPrompt) || subAgentEmployee.bio || `You are an AI assistant named "${subAgentEmployee.nickname || subAgentUsername}". ${subAgentEmployee.about || ""}`;
803
- try {
804
- const kbPlugin = ctx.app.pm.get("plugin-knowledge-base");
805
- if (kbPlugin == null ? void 0 : kbPlugin.sessionContext) {
806
- const sessionId = ((_h = (_g = (_f = ctx.action) == null ? void 0 : _f.params) == null ? void 0 : _g.values) == null ? void 0 : _h.sessionId) || ((_j = (_i = ctx.action) == null ? void 0 : _i.params) == null ? void 0 : _j.sessionId) || ((_k = ctx.state) == null ? void 0 : _k.sessionId);
807
- const contextSummary = await kbPlugin.sessionContext.buildSummary(
808
- { rootRunId, ...sessionId ? { sessionId } : {} },
809
- 6e3
810
- );
811
- if (contextSummary) {
812
- systemPrompt += `
813
-
814
- <shared_context>
815
- The following context was shared by other agents in this workflow. Use it to avoid redundant work:
816
- ${contextSummary}
817
- </shared_context>`;
818
- }
819
- }
820
- } catch (e) {
821
- (_m = (_l = ctx.app.log) == null ? void 0 : _l.debug) == null ? void 0 : _m.call(_l, `[AgentOrchestrator] Shared context injection skipped: ${e.message}`);
822
- }
823
- const combinedTask = context ? `Task: ${task}
824
-
825
- Context Provided:
826
- ${context}` : `Task: ${task}`;
827
- const effectiveRecursionLimit = Number.isFinite(recursionLimit) && recursionLimit > 0 ? recursionLimit : 50;
828
- const invokePromise = executeAgent(
829
- executor,
830
- systemPrompt,
831
- combinedTask,
832
- abortController.signal,
833
- effectiveRecursionLimit
834
- );
835
- const timeoutHandle = createTimeout(timeout, subAgentUsername, abortController);
836
- let result;
837
- try {
838
- result = await Promise.race([invokePromise, timeoutHandle.promise]);
839
- } finally {
840
- timeoutHandle.cancel();
841
- }
842
- const content = result.content || "Sub-agent completed the task but produced no output.";
843
- trace.push({
844
- type: "finish",
845
- at: nowIso(),
846
- title: `Delegation finished: ${subAgentUsername}`,
847
- status: "success",
848
- content: truncateText(content, 2e3)
849
- });
850
- await logDelegation(ctx, plugin, {
851
- id: logRecord == null ? void 0 : logRecord.id,
852
- leaderUsername,
853
- subAgentUsername,
854
- toolName,
855
- task,
856
- context,
857
- result: content,
858
- status: "success",
859
- depth: currentDepth,
860
- durationMs: Date.now() - startTime,
861
- trace,
862
- messages: result.messages,
863
- snapshot: ctxSnapshot
864
- });
865
- await spanService.finish(executionSpanId, "success", startTime, {
866
- output: content,
867
- metadata: {
868
- depth: currentDepth,
869
- maxDepth,
870
- toolName,
871
- recursionLimit,
872
- messages: result.messages,
873
- traceCount: trace.length
874
- }
875
- });
876
- return {
877
- status: "success",
878
- content
879
- };
880
- } catch (e) {
881
- plugin.app.log.error(`[AgentOrchestrator] Sub-agent ${subAgentUsername} failed`, e);
882
- await logDelegation(ctx, plugin, {
883
- id: logRecord == null ? void 0 : logRecord.id,
884
- leaderUsername,
885
- subAgentUsername,
886
- toolName,
887
- task,
888
- context,
889
- result: "",
890
- status: "error",
891
- depth: currentDepth,
892
- durationMs: Date.now() - startTime,
893
- error: e.message,
894
- trace: [
895
- ...trace,
896
- {
897
- type: "error",
898
- at: nowIso(),
899
- title: `Delegation failed: ${subAgentUsername}`,
900
- status: "error",
901
- content: e.message
902
- }
903
- ],
904
- snapshot: ctxSnapshot
905
- }).catch((logErr) => {
906
- plugin.app.log.warn("[AgentOrchestrator] Failed to save error log for delegation", logErr);
907
- });
908
- await spanService.finish(executionSpanId, "error", startTime, {
909
- error: truncateText(e.message, 1e4),
910
- metadata: {
911
- depth: currentDepth,
912
- maxDepth,
913
- toolName,
914
- recursionLimit,
915
- traceCount: trace.length + 1
916
- }
917
- });
918
- const diagnosticTrace = trace.filter((t) => t.type === "tool_error" || t.type === "error").map((t) => `[${t.toolName ? `Tool: ${t.toolName}` : "Sub-agent"}] Error: ${t.content || t.title}`).join("\n");
919
- const formattedError = [
920
- `Sub-agent "${subAgentUsername}" failed execution: ${e.message}`,
921
- diagnosticTrace ? `
922
- Diagnostic Details of internal failures:
923
- ${diagnosticTrace}` : "",
924
- `Suggestion: Review the tool parameters above or try dividing the task into simpler independent tasks.`
925
- ].filter(Boolean).join("\n");
926
- return {
927
- status: "error",
928
- content: formattedError
929
- };
930
- }
931
638
  }
932
639
  async function logDelegation(ctx, plugin, data) {
933
640
  var _a, _b, _c, _d, _e, _f;
@@ -978,62 +685,6 @@ async function logDelegation(ctx, plugin, data) {
978
685
  plugin.app.log.warn("[AgentOrchestrator] Failed to log delegation event", e);
979
686
  }
980
687
  }
981
- async function executeAgent(executor, systemPrompt, task, signal, recursionLimit = 50) {
982
- const config = { recursionLimit };
983
- if (signal) {
984
- config.signal = signal;
985
- }
986
- const finalState = await executor.invoke(
987
- {
988
- messages: [new import_messages.SystemMessage(systemPrompt), new import_messages.HumanMessage(task)]
989
- },
990
- config
991
- );
992
- const messages = (finalState == null ? void 0 : finalState.messages) || [];
993
- const lastAIMessage = [...messages].reverse().find((m) => m.getType() === "ai");
994
- if (!lastAIMessage || !lastAIMessage.content) {
995
- return { content: "", messages: serializeMessages(messages) };
996
- }
997
- let content = "";
998
- if (typeof lastAIMessage.content === "string") {
999
- content = lastAIMessage.content;
1000
- } else if (Array.isArray(lastAIMessage.content)) {
1001
- content = lastAIMessage.content.map((c) => c.text || JSON.stringify(c)).join("\n");
1002
- } else {
1003
- content = String(lastAIMessage.content);
1004
- }
1005
- return { content, messages: serializeMessages(messages) };
1006
- }
1007
- function serializeMessages(messages) {
1008
- return (messages || []).map((message, index) => {
1009
- const type = typeof message.getType === "function" ? message.getType() : message.type;
1010
- return {
1011
- index,
1012
- type,
1013
- name: message.name,
1014
- content: truncateText(message.content, 1e4),
1015
- toolCalls: message.tool_calls || message.toolCalls || [],
1016
- toolCallId: message.tool_call_id,
1017
- additionalKwargs: message.additional_kwargs,
1018
- responseMetadata: message.response_metadata
1019
- };
1020
- });
1021
- }
1022
- function createTimeout(ms, agentName, abortController) {
1023
- let timer;
1024
- const promise = new Promise((_resolve, reject) => {
1025
- timer = setTimeout(() => {
1026
- abortController == null ? void 0 : abortController.abort();
1027
- reject(new Error(`Sub-agent "${agentName}" timed out after ${ms / 1e3}s`));
1028
- }, ms);
1029
- });
1030
- return {
1031
- promise,
1032
- cancel: () => {
1033
- if (timer) clearTimeout(timer);
1034
- }
1035
- };
1036
- }
1037
688
  // Annotate the CommonJS export names for ESM import in node:
1038
689
  0 && (module.exports = {
1039
690
  createDelegateToolsProvider,
@@ -0,0 +1,42 @@
1
+ import { z } from 'zod';
2
+ export declare function createExternalRagSearchTool(plugin: any): {
3
+ scope: "CUSTOM";
4
+ execution: "backend";
5
+ defaultPermission: "ALLOW";
6
+ introduction: {
7
+ title: string;
8
+ about: string;
9
+ };
10
+ definition: {
11
+ name: string;
12
+ description: string;
13
+ schema: z.ZodObject<{
14
+ query: z.ZodString;
15
+ knowledgeBaseIds: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
16
+ topK: z.ZodOptional<z.ZodNumber>;
17
+ scoreThreshold: z.ZodOptional<z.ZodNumber>;
18
+ }, "strip", z.ZodTypeAny, {
19
+ query?: string;
20
+ knowledgeBaseIds?: string[];
21
+ topK?: number;
22
+ scoreThreshold?: number;
23
+ }, {
24
+ query?: string;
25
+ knowledgeBaseIds?: string[];
26
+ topK?: number;
27
+ scoreThreshold?: number;
28
+ }>;
29
+ };
30
+ invoke: (ctx: any, args: {
31
+ query?: string;
32
+ knowledgeBaseIds?: string[];
33
+ topK?: number;
34
+ scoreThreshold?: number;
35
+ }) => Promise<{
36
+ status: "error";
37
+ content: string;
38
+ } | {
39
+ status: "success";
40
+ content: string;
41
+ }>;
42
+ };
@@ -0,0 +1,205 @@
1
+ import { z } from 'zod';
2
+ import { AgentLoopService } from '../services/AgentLoopService';
3
+ export declare function createOrchestratorPlanTools(plugin: any, service: AgentLoopService): ({
4
+ scope: "CUSTOM";
5
+ execution: "backend";
6
+ defaultPermission: "ALLOW";
7
+ introduction: {
8
+ title: string;
9
+ about: string;
10
+ };
11
+ definition: {
12
+ name: string;
13
+ description: string;
14
+ schema: z.ZodObject<{
15
+ goal: z.ZodString;
16
+ runId: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
17
+ leaderUsername: z.ZodOptional<z.ZodString>;
18
+ sessionId: z.ZodOptional<z.ZodString>;
19
+ messageId: z.ZodOptional<z.ZodString>;
20
+ harnessTag: z.ZodDefault<z.ZodOptional<z.ZodString>>;
21
+ targetAgent: z.ZodOptional<z.ZodString>;
22
+ plannerModel: z.ZodOptional<z.ZodString>;
23
+ policy: z.ZodOptional<z.ZodObject<{
24
+ maxIterations: z.ZodOptional<z.ZodNumber>;
25
+ maxStepAttempts: z.ZodOptional<z.ZodNumber>;
26
+ allowReplan: z.ZodOptional<z.ZodBoolean>;
27
+ requireVerification: z.ZodOptional<z.ZodBoolean>;
28
+ stopOnApprovalRequired: z.ZodOptional<z.ZodBoolean>;
29
+ }, "strip", z.ZodTypeAny, {
30
+ maxIterations?: number;
31
+ maxStepAttempts?: number;
32
+ allowReplan?: boolean;
33
+ requireVerification?: boolean;
34
+ stopOnApprovalRequired?: boolean;
35
+ }, {
36
+ maxIterations?: number;
37
+ maxStepAttempts?: number;
38
+ allowReplan?: boolean;
39
+ requireVerification?: boolean;
40
+ stopOnApprovalRequired?: boolean;
41
+ }>>;
42
+ metadata: z.ZodOptional<z.ZodAny>;
43
+ plan: z.ZodOptional<z.ZodArray<z.ZodObject<{
44
+ id: z.ZodOptional<z.ZodString>;
45
+ key: z.ZodOptional<z.ZodString>;
46
+ planKey: z.ZodOptional<z.ZodString>;
47
+ parentStepId: z.ZodOptional<z.ZodUnion<[z.ZodString, z.ZodNumber]>>;
48
+ title: z.ZodOptional<z.ZodString>;
49
+ description: z.ZodOptional<z.ZodString>;
50
+ type: z.ZodOptional<z.ZodEnum<["reasoning", "skill", "tool", "sub_agent", "verification"]>>;
51
+ target: z.ZodOptional<z.ZodString>;
52
+ input: z.ZodOptional<z.ZodAny>;
53
+ dependsOn: z.ZodOptional<z.ZodArray<z.ZodString, "many">>;
54
+ dependencyPolicy: z.ZodOptional<z.ZodEnum<["require_success", "allow_skipped"]>>;
55
+ maxAttempts: z.ZodOptional<z.ZodNumber>;
56
+ metadata: z.ZodOptional<z.ZodAny>;
57
+ }, "strip", z.ZodTypeAny, {
58
+ type?: "reasoning" | "skill" | "tool" | "sub_agent" | "verification";
59
+ key?: string;
60
+ title?: string;
61
+ description?: string;
62
+ metadata?: any;
63
+ input?: any;
64
+ planKey?: string;
65
+ target?: string;
66
+ dependsOn?: string[];
67
+ id?: string;
68
+ parentStepId?: string | number;
69
+ dependencyPolicy?: "require_success" | "allow_skipped";
70
+ maxAttempts?: number;
71
+ }, {
72
+ type?: "reasoning" | "skill" | "tool" | "sub_agent" | "verification";
73
+ key?: string;
74
+ title?: string;
75
+ description?: string;
76
+ metadata?: any;
77
+ input?: any;
78
+ planKey?: string;
79
+ target?: string;
80
+ dependsOn?: string[];
81
+ id?: string;
82
+ parentStepId?: string | number;
83
+ dependencyPolicy?: "require_success" | "allow_skipped";
84
+ maxAttempts?: number;
85
+ }>, "many">>;
86
+ }, "strip", z.ZodTypeAny, {
87
+ leaderUsername?: string;
88
+ metadata?: any;
89
+ runId?: string | number;
90
+ sessionId?: string;
91
+ goal?: string;
92
+ messageId?: string;
93
+ policy?: {
94
+ maxIterations?: number;
95
+ maxStepAttempts?: number;
96
+ allowReplan?: boolean;
97
+ requireVerification?: boolean;
98
+ stopOnApprovalRequired?: boolean;
99
+ };
100
+ harnessTag?: string;
101
+ targetAgent?: string;
102
+ plannerModel?: string;
103
+ plan?: {
104
+ type?: "reasoning" | "skill" | "tool" | "sub_agent" | "verification";
105
+ key?: string;
106
+ title?: string;
107
+ description?: string;
108
+ metadata?: any;
109
+ input?: any;
110
+ planKey?: string;
111
+ target?: string;
112
+ dependsOn?: string[];
113
+ id?: string;
114
+ parentStepId?: string | number;
115
+ dependencyPolicy?: "require_success" | "allow_skipped";
116
+ maxAttempts?: number;
117
+ }[];
118
+ }, {
119
+ leaderUsername?: string;
120
+ metadata?: any;
121
+ runId?: string | number;
122
+ sessionId?: string;
123
+ goal?: string;
124
+ messageId?: string;
125
+ policy?: {
126
+ maxIterations?: number;
127
+ maxStepAttempts?: number;
128
+ allowReplan?: boolean;
129
+ requireVerification?: boolean;
130
+ stopOnApprovalRequired?: boolean;
131
+ };
132
+ harnessTag?: string;
133
+ targetAgent?: string;
134
+ plannerModel?: string;
135
+ plan?: {
136
+ type?: "reasoning" | "skill" | "tool" | "sub_agent" | "verification";
137
+ key?: string;
138
+ title?: string;
139
+ description?: string;
140
+ metadata?: any;
141
+ input?: any;
142
+ planKey?: string;
143
+ target?: string;
144
+ dependsOn?: string[];
145
+ id?: string;
146
+ parentStepId?: string | number;
147
+ dependencyPolicy?: "require_success" | "allow_skipped";
148
+ maxAttempts?: number;
149
+ }[];
150
+ }>;
151
+ };
152
+ invoke: (ctx: any, args: any) => Promise<{
153
+ status: "success" | "error";
154
+ content: string;
155
+ }>;
156
+ } | {
157
+ scope: "CUSTOM";
158
+ execution: "backend";
159
+ defaultPermission: "ALLOW";
160
+ introduction: {
161
+ title: string;
162
+ about: string;
163
+ };
164
+ definition: {
165
+ name: string;
166
+ description: string;
167
+ schema: z.ZodObject<{
168
+ runId: z.ZodUnion<[z.ZodString, z.ZodNumber]>;
169
+ }, "strip", z.ZodTypeAny, {
170
+ runId?: string | number;
171
+ }, {
172
+ runId?: string | number;
173
+ }>;
174
+ };
175
+ invoke: (_ctx: any, args: any) => Promise<{
176
+ status: "success" | "error";
177
+ content: string;
178
+ }>;
179
+ } | {
180
+ scope: "CUSTOM";
181
+ execution: "backend";
182
+ defaultPermission: "ASK";
183
+ introduction: {
184
+ title: string;
185
+ about: string;
186
+ };
187
+ definition: {
188
+ name: string;
189
+ description: string;
190
+ schema: z.ZodObject<{
191
+ runId: z.ZodUnion<[z.ZodString, z.ZodNumber]>;
192
+ reason: z.ZodOptional<z.ZodString>;
193
+ }, "strip", z.ZodTypeAny, {
194
+ runId?: string | number;
195
+ reason?: string;
196
+ }, {
197
+ runId?: string | number;
198
+ reason?: string;
199
+ }>;
200
+ };
201
+ invoke: (ctx: any, args: any) => Promise<{
202
+ status: "success" | "error";
203
+ content: string;
204
+ }>;
205
+ })[];