plugin-agent-orchestrator 1.0.20 → 1.0.22

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 (158) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/externalVersion.js +6 -6
  3. package/dist/server/collections/agent-execution-spans.js +24 -0
  4. package/dist/server/collections/agent-loop-runs.js +36 -0
  5. package/dist/server/collections/orchestrator-config.js +14 -0
  6. package/dist/server/migrations/20260601000000-add-token-fields.js +101 -0
  7. package/dist/server/plugin.js +56 -0
  8. package/dist/server/resources/agent-loop.js +33 -25
  9. package/dist/server/resources/tracing.js +5 -8
  10. package/dist/server/services/AgentHarness.js +56 -90
  11. package/dist/server/services/AgentLoopController.js +164 -125
  12. package/dist/server/services/AgentLoopRepository.js +16 -34
  13. package/dist/server/services/AgentLoopService.js +7 -1
  14. package/dist/server/services/AgentPlannerService.js +5 -25
  15. package/dist/server/services/AgentRegistryService.js +34 -24
  16. package/dist/server/services/CircuitBreaker.js +120 -0
  17. package/dist/server/services/ContextAggregator.js +201 -0
  18. package/dist/server/services/ExecutionSpanService.js +2 -5
  19. package/dist/server/services/RunEventBus.js +73 -0
  20. package/dist/server/services/TokenTracker.js +173 -0
  21. package/dist/server/tools/agent-loop.js +30 -63
  22. package/dist/server/tools/delegate-task.js +14 -72
  23. package/dist/server/tools/orchestrator-plan.js +10 -47
  24. package/dist/server/types.js +24 -0
  25. package/dist/server/utils/ctx-utils.js +152 -0
  26. package/dist/server/utils/logging.js +86 -0
  27. package/package.json +44 -44
  28. package/src/client/AgentRunsTab.tsx +764 -764
  29. package/src/client/HarnessProfilesTab.tsx +247 -247
  30. package/src/client/OrchestratorSettings.tsx +106 -106
  31. package/src/client/RulesTab.tsx +716 -716
  32. package/src/client/hooks/useRunEventStream.ts +76 -0
  33. package/src/client/index.tsx +2 -1
  34. package/src/client/plugin.tsx +27 -27
  35. package/src/client/skill-hub/components/LoopSettings.tsx +331 -331
  36. package/src/client/skill-hub/index.tsx +51 -51
  37. package/src/client/skill-hub/tools/InteractionSchemasProvider.tsx +99 -99
  38. package/src/client/skill-hub/tools/SkillHubCard.tsx +109 -109
  39. package/src/client/skill-hub/tools/loopTemplates.ts +52 -52
  40. package/src/client/skill-hub/tools/registerSkillLoopCards.ts +58 -58
  41. package/src/client/tools/PlanApprovalCard.tsx +175 -175
  42. package/src/client/tools/registerOrchestratorCards.ts +7 -7
  43. package/src/server/__tests__/agent-loop-controller.test.ts +375 -0
  44. package/src/server/__tests__/circuit-breaker.test.ts +169 -0
  45. package/src/server/__tests__/context-aggregator.test.ts +222 -0
  46. package/src/server/__tests__/parallel-execution.test.ts +318 -0
  47. package/src/server/__tests__/smoke.test.ts +120 -0
  48. package/src/server/collections/agent-execution-spans.ts +24 -0
  49. package/src/server/collections/agent-harness-profiles.ts +59 -59
  50. package/src/server/collections/agent-loop-events.ts +71 -71
  51. package/src/server/collections/agent-loop-runs.ts +38 -1
  52. package/src/server/collections/agent-loop-steps.ts +144 -144
  53. package/src/server/collections/orchestrator-config.ts +14 -0
  54. package/src/server/collections/skill-executions.ts +106 -106
  55. package/src/server/collections/skill-loop-configs.ts +65 -65
  56. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +30 -30
  57. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +142 -142
  58. package/src/server/migrations/20260601000000-add-token-fields.ts +89 -0
  59. package/src/server/plugin.ts +68 -0
  60. package/src/server/resources/agent-loop.ts +21 -12
  61. package/src/server/resources/tracing.ts +3 -7
  62. package/src/server/services/AgentHarness.ts +78 -116
  63. package/src/server/services/AgentLoopController.ts +197 -122
  64. package/src/server/services/AgentLoopRepository.ts +9 -25
  65. package/src/server/services/AgentLoopService.ts +13 -1
  66. package/src/server/services/AgentPlanValidator.ts +73 -73
  67. package/src/server/services/AgentPlannerService.ts +2 -25
  68. package/src/server/services/AgentRegistryService.ts +40 -31
  69. package/src/server/services/CircuitBreaker.ts +116 -0
  70. package/src/server/services/ContextAggregator.ts +239 -0
  71. package/src/server/services/ExecutionSpanService.ts +2 -4
  72. package/src/server/services/RunEventBus.ts +45 -0
  73. package/src/server/services/TokenTracker.ts +209 -0
  74. package/src/server/skill-hub/plugin.ts +898 -898
  75. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +460 -460
  76. package/src/server/tools/agent-loop.ts +18 -57
  77. package/src/server/tools/delegate-task.ts +11 -93
  78. package/src/server/tools/orchestrator-plan.ts +26 -50
  79. package/src/server/tools/skill-execute.ts +160 -160
  80. package/src/server/types.ts +55 -0
  81. package/src/server/utils/ctx-utils.ts +118 -0
  82. package/src/server/utils/logging.ts +63 -0
  83. package/dist/client/AIEmployeeSelect.d.ts +0 -11
  84. package/dist/client/AIEmployeesContext.d.ts +0 -30
  85. package/dist/client/AgentRunsTab.d.ts +0 -2
  86. package/dist/client/HarnessProfilesTab.d.ts +0 -2
  87. package/dist/client/OrchestratorSettings.d.ts +0 -3
  88. package/dist/client/RulesTab.d.ts +0 -2
  89. package/dist/client/TracingTab.d.ts +0 -2
  90. package/dist/client/index.d.ts +0 -1
  91. package/dist/client/plugin.d.ts +0 -6
  92. package/dist/client/skill-hub/components/ExecutionHistory.d.ts +0 -2
  93. package/dist/client/skill-hub/components/ExecutionProgress.d.ts +0 -20
  94. package/dist/client/skill-hub/components/GitSkillImport.d.ts +0 -7
  95. package/dist/client/skill-hub/components/LoopSettings.d.ts +0 -2
  96. package/dist/client/skill-hub/components/SkillEditor.d.ts +0 -7
  97. package/dist/client/skill-hub/components/SkillManager.d.ts +0 -2
  98. package/dist/client/skill-hub/components/SkillMetrics.d.ts +0 -2
  99. package/dist/client/skill-hub/components/SkillTestPanel.d.ts +0 -7
  100. package/dist/client/skill-hub/index.d.ts +0 -11
  101. package/dist/client/skill-hub/locale.d.ts +0 -3
  102. package/dist/client/skill-hub/tools/InteractionSchemasProvider.d.ts +0 -6
  103. package/dist/client/skill-hub/tools/SkillHubCard.d.ts +0 -3
  104. package/dist/client/skill-hub/tools/loopTemplates.d.ts +0 -22
  105. package/dist/client/skill-hub/tools/registerSkillLoopCards.d.ts +0 -1
  106. package/dist/client/skill-hub/utils/jsonFields.d.ts +0 -3
  107. package/dist/client/tools/PlanApprovalCard.d.ts +0 -3
  108. package/dist/client/tools/registerOrchestratorCards.d.ts +0 -1
  109. package/dist/index.d.ts +0 -2
  110. package/dist/server/collections/agent-execution-spans.d.ts +0 -9
  111. package/dist/server/collections/agent-harness-profiles.d.ts +0 -2
  112. package/dist/server/collections/agent-loop-events.d.ts +0 -2
  113. package/dist/server/collections/agent-loop-runs.d.ts +0 -2
  114. package/dist/server/collections/agent-loop-steps.d.ts +0 -2
  115. package/dist/server/collections/orchestrator-config.d.ts +0 -2
  116. package/dist/server/collections/orchestrator-logs.d.ts +0 -8
  117. package/dist/server/collections/skill-definitions.d.ts +0 -3
  118. package/dist/server/collections/skill-executions.d.ts +0 -3
  119. package/dist/server/collections/skill-loop-configs.d.ts +0 -3
  120. package/dist/server/collections/skill-worker-configs.d.ts +0 -3
  121. package/dist/server/index.d.ts +0 -1
  122. package/dist/server/migrations/20260423000000-add-progress-fields.d.ts +0 -4
  123. package/dist/server/migrations/20260425000000-add-interaction-schema.d.ts +0 -4
  124. package/dist/server/migrations/20260427000000-add-tracing-detail-fields.d.ts +0 -7
  125. package/dist/server/migrations/20260427000000-change-packages-to-text.d.ts +0 -4
  126. package/dist/server/migrations/20260427000001-change-other-json-to-text.d.ts +0 -4
  127. package/dist/server/migrations/20260429000000-add-llm-fields.d.ts +0 -7
  128. package/dist/server/migrations/20260429000000-fix-inputargs-json-to-text.d.ts +0 -16
  129. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.d.ts +0 -7
  130. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.d.ts +0 -7
  131. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.d.ts +0 -12
  132. package/dist/server/plugin.d.ts +0 -16
  133. package/dist/server/resources/agent-loop.d.ts +0 -3
  134. package/dist/server/resources/tracing.d.ts +0 -7
  135. package/dist/server/services/AgentHarness.d.ts +0 -42
  136. package/dist/server/services/AgentLoopController.d.ts +0 -205
  137. package/dist/server/services/AgentLoopRepository.d.ts +0 -20
  138. package/dist/server/services/AgentLoopService.d.ts +0 -149
  139. package/dist/server/services/AgentPlanValidator.d.ts +0 -4
  140. package/dist/server/services/AgentPlannerService.d.ts +0 -8
  141. package/dist/server/services/AgentRegistryService.d.ts +0 -13
  142. package/dist/server/services/CodeValidator.d.ts +0 -32
  143. package/dist/server/services/ExecutionSpanService.d.ts +0 -46
  144. package/dist/server/services/FileManager.d.ts +0 -28
  145. package/dist/server/services/SandboxRunner.d.ts +0 -41
  146. package/dist/server/services/SkillManager.d.ts +0 -6
  147. package/dist/server/services/SkillRepositoryService.d.ts +0 -22
  148. package/dist/server/services/WorkerEnvManager.d.ts +0 -26
  149. package/dist/server/skill-hub/actions/git-import.d.ts +0 -21
  150. package/dist/server/skill-hub/mcp/McpController.d.ts +0 -15
  151. package/dist/server/skill-hub/plugin.d.ts +0 -61
  152. package/dist/server/skill-hub/tasks/SkillExecutionTask.d.ts +0 -16
  153. package/dist/server/skill-hub/utils/json-fields.d.ts +0 -7
  154. package/dist/server/tools/agent-loop.d.ts +0 -235
  155. package/dist/server/tools/delegate-task.d.ts +0 -19
  156. package/dist/server/tools/external-rag-search.d.ts +0 -42
  157. package/dist/server/tools/orchestrator-plan.d.ts +0 -205
  158. package/dist/server/tools/skill-execute.d.ts +0 -36
@@ -0,0 +1,173 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var TokenTracker_exports = {};
28
+ __export(TokenTracker_exports, {
29
+ TokenTracker: () => TokenTracker,
30
+ extractTokenUsage: () => extractTokenUsage
31
+ });
32
+ module.exports = __toCommonJS(TokenTracker_exports);
33
+ const PRICE_PER_1K_INPUT = Number(process.env.ORCHESTRATOR_PRICE_PER_1K_INPUT || 3e-3);
34
+ const PRICE_PER_1K_OUTPUT = Number(process.env.ORCHESTRATOR_PRICE_PER_1K_OUTPUT || 0.015);
35
+ function estimateCost(inputTokens, outputTokens) {
36
+ return inputTokens / 1e3 * PRICE_PER_1K_INPUT + outputTokens / 1e3 * PRICE_PER_1K_OUTPUT;
37
+ }
38
+ function extractTokenUsage(finalState) {
39
+ if (!(finalState == null ? void 0 : finalState.messages) || !Array.isArray(finalState.messages)) return null;
40
+ let totalInput = 0;
41
+ let totalOutput = 0;
42
+ let totalAll = 0;
43
+ for (const msg of finalState.messages) {
44
+ if (msg == null ? void 0 : msg.usage_metadata) {
45
+ const um = msg.usage_metadata;
46
+ totalInput += um.input_tokens || 0;
47
+ totalOutput += um.output_tokens || 0;
48
+ totalAll += um.total_tokens || 0;
49
+ }
50
+ }
51
+ if (totalAll === 0) return null;
52
+ return {
53
+ inputTokens: totalInput,
54
+ outputTokens: totalOutput,
55
+ totalTokens: totalAll,
56
+ cost: estimateCost(totalInput, totalOutput)
57
+ };
58
+ }
59
+ class TokenTracker {
60
+ constructor(plugin) {
61
+ this.plugin = plugin;
62
+ }
63
+ get db() {
64
+ return this.plugin.db;
65
+ }
66
+ get app() {
67
+ return this.plugin.app;
68
+ }
69
+ /**
70
+ * Track token usage for a single execution span.
71
+ * Updates the span record and accumulates into the parent run.
72
+ *
73
+ * @param spanId - The agentExecutionSpans.id to update
74
+ * @param usage - Parsed token usage from extractTokenUsage()
75
+ * @param runId - Optional agentLoopRuns.id to accumulate totals
76
+ */
77
+ async trackSpan(spanId, usage, runId) {
78
+ var _a, _b;
79
+ if (!spanId) return;
80
+ try {
81
+ const repo = this.db.getRepository("agentExecutionSpans");
82
+ if (!repo) return;
83
+ await repo.update({
84
+ filterByTk: spanId,
85
+ values: {
86
+ inputTokens: usage.inputTokens,
87
+ outputTokens: usage.outputTokens,
88
+ totalTokens: usage.totalTokens,
89
+ cost: usage.cost
90
+ }
91
+ });
92
+ if (runId != null) {
93
+ await this.accumulateToRun(runId);
94
+ }
95
+ } catch (e) {
96
+ (_b = (_a = this.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[TokenTracker] Failed to track span tokens", e);
97
+ }
98
+ }
99
+ /**
100
+ * Recalculate total token/cost for a run by summing all its spans.
101
+ */
102
+ async accumulateToRun(runId) {
103
+ var _a, _b, _c, _d, _e;
104
+ try {
105
+ const spansRepo = this.db.getRepository("agentExecutionSpans");
106
+ if (!spansRepo) return;
107
+ const spans = await spansRepo.find({
108
+ filter: { "metadata.agentLoopRunId": String(runId) }
109
+ });
110
+ let totalInput = 0;
111
+ let totalOutput = 0;
112
+ let totalCost = 0;
113
+ for (const span of spans) {
114
+ totalInput += Number(((_a = span.get) == null ? void 0 : _a.call(span, "inputTokens")) || span.inputTokens || 0);
115
+ totalOutput += Number(((_b = span.get) == null ? void 0 : _b.call(span, "outputTokens")) || span.outputTokens || 0);
116
+ totalCost += Number(((_c = span.get) == null ? void 0 : _c.call(span, "cost")) || span.cost || 0);
117
+ }
118
+ const runsRepo = this.db.getRepository("agentLoopRuns");
119
+ if (!runsRepo) return;
120
+ await runsRepo.update({
121
+ filterByTk: runId,
122
+ values: {
123
+ totalInputTokens: totalInput,
124
+ totalOutputTokens: totalOutput,
125
+ totalTokens: totalInput + totalOutput,
126
+ totalCost
127
+ }
128
+ });
129
+ } catch (e) {
130
+ (_e = (_d = this.app.log) == null ? void 0 : _d.warn) == null ? void 0 : _e.call(_d, "[TokenTracker] Failed to accumulate run totals", e);
131
+ }
132
+ }
133
+ /**
134
+ * Check if a run has exceeded its budget limits.
135
+ */
136
+ async checkBudget(runId) {
137
+ var _a, _b, _c, _d, _e, _f;
138
+ try {
139
+ const repo = this.db.getRepository("agentLoopRuns");
140
+ if (!repo) return { allowed: true };
141
+ const run = await repo.findOne({ filter: { id: runId } });
142
+ if (!run) return { allowed: true };
143
+ const budgetMaxTokens = Number(((_a = run.get) == null ? void 0 : _a.call(run, "budgetMaxTokens")) ?? 0);
144
+ const budgetMaxCost = Number(((_b = run.get) == null ? void 0 : _b.call(run, "budgetMaxCost")) ?? 0);
145
+ if (budgetMaxTokens <= 0 && budgetMaxCost <= 0) return { allowed: true };
146
+ const totalTokens = Number(((_c = run.get) == null ? void 0 : _c.call(run, "totalTokens")) || 0);
147
+ const totalCost = Number(((_d = run.get) == null ? void 0 : _d.call(run, "totalCost")) || 0);
148
+ if (budgetMaxTokens > 0 && totalTokens >= budgetMaxTokens) {
149
+ return {
150
+ allowed: false,
151
+ reason: `Budget exceeded: ${totalTokens}/${budgetMaxTokens} tokens used. Maximum allowed tokens for this run: ${budgetMaxTokens}.`
152
+ };
153
+ }
154
+ if (budgetMaxCost > 0 && totalCost >= budgetMaxCost) {
155
+ return {
156
+ allowed: false,
157
+ reason: `Budget exceeded: $${totalCost.toFixed(4)}/$${budgetMaxCost.toFixed(
158
+ 4
159
+ )} spent. Maximum allowed cost for this run: $${budgetMaxCost}.`
160
+ };
161
+ }
162
+ return { allowed: true };
163
+ } catch (e) {
164
+ (_f = (_e = this.app.log) == null ? void 0 : _e.warn) == null ? void 0 : _f.call(_e, "[TokenTracker] Budget check failed, allowing", e);
165
+ return { allowed: true };
166
+ }
167
+ }
168
+ }
169
+ // Annotate the CommonJS export names for ESM import in node:
170
+ 0 && (module.exports = {
171
+ TokenTracker,
172
+ extractTokenUsage
173
+ });
@@ -31,6 +31,7 @@ __export(agent_loop_exports, {
31
31
  module.exports = __toCommonJS(agent_loop_exports);
32
32
  var import_zod = require("zod");
33
33
  var import_ExecutionSpanService = require("../services/ExecutionSpanService");
34
+ var import_ctx_utils = require("../utils/ctx-utils");
34
35
  const stepSchema = import_zod.z.object({
35
36
  id: import_zod.z.string().optional(),
36
37
  key: import_zod.z.string().optional(),
@@ -58,46 +59,6 @@ function toolResult(status, payload) {
58
59
  content: typeof payload === "string" ? payload : JSON.stringify(payload)
59
60
  };
60
61
  }
61
- function valuesFromCtx(ctx) {
62
- var _a, _b;
63
- return ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || {};
64
- }
65
- function currentUserId(ctx) {
66
- var _a, _b, _c, _d;
67
- return ((_b = (_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentUser) == null ? void 0 : _b.id) || ((_d = (_c = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _c.user) == null ? void 0 : _d.id);
68
- }
69
- function resolveSessionId(ctx, args) {
70
- var _a, _b, _c;
71
- const values = valuesFromCtx(ctx);
72
- return (args == null ? void 0 : args.sessionId) || values.sessionId || ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.sessionId) || ((_c = ctx == null ? void 0 : ctx.state) == null ? void 0 : _c.sessionId);
73
- }
74
- function resolveMessageId(ctx, args) {
75
- var _a, _b;
76
- const values = valuesFromCtx(ctx);
77
- return (args == null ? void 0 : args.messageId) || values.messageId || ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.messageId);
78
- }
79
- function normalizeEmployeeUsername(raw) {
80
- if (!raw) return null;
81
- if (typeof raw === "string") return raw;
82
- return raw.username || raw.aiEmployeeUsername || raw.name || null;
83
- }
84
- async function resolveLeaderUsername(ctx, plugin, args) {
85
- var _a, _b, _c, _d, _e, _f;
86
- const values = valuesFromCtx(ctx);
87
- const direct = normalizeEmployeeUsername(
88
- (args == null ? void 0 : args.leaderUsername) || (ctx == null ? void 0 : ctx._currentAIEmployee) || ((_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentAIEmployee) || ((_c = (_b = ctx == null ? void 0 : ctx.runtime) == null ? void 0 : _b.context) == null ? void 0 : _c.currentAIEmployee) || values.aiEmployee
89
- );
90
- if (direct) return direct;
91
- const sessionId = resolveSessionId(ctx, args);
92
- if (!sessionId) return void 0;
93
- try {
94
- const repo = ((_e = (_d = ctx == null ? void 0 : ctx.db) == null ? void 0 : _d.getRepository) == null ? void 0 : _e.call(_d, "aiConversations")) || plugin.db.getRepository("aiConversations");
95
- const conversation = await repo.findOne({ filter: { sessionId } });
96
- return normalizeEmployeeUsername((conversation == null ? void 0 : conversation.aiEmployeeUsername) || ((_f = conversation == null ? void 0 : conversation.get) == null ? void 0 : _f.call(conversation, "aiEmployeeUsername")));
97
- } catch {
98
- return void 0;
99
- }
100
- }
101
62
  function setLoopTraceContext(ctx, snapshot, step) {
102
63
  if (!ctx || !(snapshot == null ? void 0 : snapshot.run)) return;
103
64
  const existing = (0, import_ExecutionSpanService.getOrchestratorTraceContext)(ctx) || {};
@@ -136,19 +97,20 @@ function createAgentLoopTools(plugin, service) {
136
97
  })
137
98
  },
138
99
  invoke: async (ctx, args) => {
100
+ var _a;
139
101
  try {
140
- const leaderUsername = await resolveLeaderUsername(ctx, plugin, args);
102
+ const leaderUsername = await (0, import_ctx_utils.resolveLeaderUsername)(ctx, plugin, args);
141
103
  const snapshot = await service.createRun({
142
104
  goal: args.goal,
143
105
  leaderUsername,
144
- sessionId: resolveSessionId(ctx, args),
145
- messageId: resolveMessageId(ctx, args),
146
- userId: currentUserId(ctx),
106
+ sessionId: (0, import_ctx_utils.resolveSessionId)(ctx, args),
107
+ messageId: (0, import_ctx_utils.resolveMessageId)(ctx, args),
108
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
147
109
  policy: args.policy,
148
110
  metadata: args.metadata,
149
111
  plan: planFromArgs(args.plan)
150
112
  });
151
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
113
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
152
114
  return toolResult("success", snapshot);
153
115
  } catch (error) {
154
116
  return toolResult("error", (error == null ? void 0 : error.message) || String(error));
@@ -161,19 +123,20 @@ function createAgentLoopTools(plugin, service) {
161
123
  defaultPermission: "ALLOW",
162
124
  introduction: {
163
125
  title: "Agent Loop - Status",
164
- about: "Read the current run, steps, and next executable step."
126
+ about: "Read the current run, steps, and next executable steps."
165
127
  },
166
128
  definition: {
167
129
  name: "agent_loop_status",
168
- description: "Fetch an agent loop run. Call this before executing the next step so subsequent skill/tool calls can be linked to the current loop step.",
130
+ description: "Fetch an agent loop run. Call this to check which steps are ready for execution.",
169
131
  schema: import_zod.z.object({
170
132
  runId: import_zod.z.union([import_zod.z.string(), import_zod.z.number()])
171
133
  })
172
134
  },
173
135
  invoke: async (ctx, args) => {
136
+ var _a;
174
137
  try {
175
138
  const snapshot = await service.getRunSnapshot(args.runId);
176
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
139
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
177
140
  return toolResult("success", snapshot);
178
141
  } catch (error) {
179
142
  return toolResult("error", (error == null ? void 0 : error.message) || String(error));
@@ -203,34 +166,35 @@ function createAgentLoopTools(plugin, service) {
203
166
  })
204
167
  },
205
168
  invoke: async (ctx, args) => {
169
+ var _a, _b, _c;
206
170
  try {
207
171
  let snapshot;
208
172
  if (args.status === "running") {
209
173
  snapshot = await service.startStep(args.stepId, {
210
- userId: currentUserId(ctx),
174
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
211
175
  agentExecutionSpanId: args.agentExecutionSpanId
212
176
  });
213
177
  const currentStep = snapshot.steps.find((step) => String(step.id) === String(args.stepId));
214
178
  setLoopTraceContext(ctx, snapshot, currentStep);
215
179
  } else if (args.status === "succeeded") {
216
180
  snapshot = await service.completeStep(args.stepId, args.output === void 0 ? {} : args.output, {
217
- userId: currentUserId(ctx),
181
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
218
182
  skillExecutionId: args.skillExecutionId,
219
183
  agentExecutionSpanId: args.agentExecutionSpanId,
220
184
  metadata: args.metadata
221
185
  });
222
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
186
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
223
187
  } else if (args.status === "failed") {
224
188
  snapshot = await service.failStep(args.stepId, args.error || "Step failed.", {
225
- userId: currentUserId(ctx),
189
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
226
190
  metadata: args.metadata
227
191
  });
228
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
192
+ setLoopTraceContext(ctx, snapshot, (_b = snapshot.nextSteps) == null ? void 0 : _b[0]);
229
193
  } else {
230
194
  snapshot = await service.skipStep(args.stepId, args.reason || "Skipped.", {
231
- userId: currentUserId(ctx)
195
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
232
196
  });
233
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
197
+ setLoopTraceContext(ctx, snapshot, (_c = snapshot.nextSteps) == null ? void 0 : _c[0]);
234
198
  }
235
199
  return toolResult("success", snapshot);
236
200
  } catch (error) {
@@ -257,14 +221,15 @@ function createAgentLoopTools(plugin, service) {
257
221
  })
258
222
  },
259
223
  invoke: async (ctx, args) => {
224
+ var _a;
260
225
  try {
261
226
  await service.replan(args.runId, args.plan, {
262
227
  reason: args.reason,
263
228
  mode: args.mode || "replace_pending",
264
- userId: currentUserId(ctx)
229
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
265
230
  });
266
231
  const snapshot = await service.getRunSnapshot(args.runId);
267
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
232
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
268
233
  return toolResult("success", snapshot);
269
234
  } catch (error) {
270
235
  return toolResult("error", (error == null ? void 0 : error.message) || String(error));
@@ -289,12 +254,13 @@ function createAgentLoopTools(plugin, service) {
289
254
  })
290
255
  },
291
256
  invoke: async (ctx, args) => {
257
+ var _a;
292
258
  try {
293
259
  const snapshot = await service.requestApproval(args.stepId, args.approval || {}, {
294
260
  reason: args.reason,
295
- userId: currentUserId(ctx)
261
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
296
262
  });
297
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
263
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
298
264
  return toolResult("success", snapshot);
299
265
  } catch (error) {
300
266
  return toolResult("error", (error == null ? void 0 : error.message) || String(error));
@@ -320,15 +286,16 @@ function createAgentLoopTools(plugin, service) {
320
286
  })
321
287
  },
322
288
  invoke: async (ctx, args) => {
289
+ var _a;
323
290
  try {
324
291
  const snapshot = await service.resumeRun(args.runId, {
325
292
  stepId: args.stepId,
326
293
  approved: args.approved,
327
294
  editedInput: args.editedInput,
328
- userId: currentUserId(ctx),
295
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
329
296
  ctx
330
297
  });
331
- setLoopTraceContext(ctx, snapshot, snapshot.nextStep);
298
+ setLoopTraceContext(ctx, snapshot, (_a = snapshot.nextSteps) == null ? void 0 : _a[0]);
332
299
  return toolResult("success", snapshot);
333
300
  } catch (error) {
334
301
  return toolResult("error", (error == null ? void 0 : error.message) || String(error));
@@ -360,7 +327,7 @@ function createAgentLoopTools(plugin, service) {
360
327
  status: args.status || "succeeded",
361
328
  summary: args.summary,
362
329
  evidence: args.evidence,
363
- userId: currentUserId(ctx)
330
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
364
331
  });
365
332
  setLoopTraceContext(ctx, snapshot);
366
333
  return toolResult("success", snapshot);
@@ -389,7 +356,7 @@ function createAgentLoopTools(plugin, service) {
389
356
  try {
390
357
  const snapshot = await service.cancelRun(args.runId, {
391
358
  reason: args.reason,
392
- userId: currentUserId(ctx)
359
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
393
360
  });
394
361
  setLoopTraceContext(ctx, snapshot);
395
362
  return toolResult("success", snapshot);
@@ -33,6 +33,8 @@ module.exports = __toCommonJS(delegate_task_exports);
33
33
  var import_zod = require("zod");
34
34
  var import_crypto = require("crypto");
35
35
  var import_ExecutionSpanService = require("../services/ExecutionSpanService");
36
+ var import_ctx_utils = require("../utils/ctx-utils");
37
+ var import_logging = require("../utils/logging");
36
38
  const ORCHESTRATOR_DEPTH_KEY = "__orchestratorDepth";
37
39
  const ORCHESTRATOR_PATH_KEY = "__orchestratorPath";
38
40
  const MAX_DISPATCH_CONCURRENCY = 5;
@@ -232,7 +234,7 @@ ${subAgentList}`
232
234
  leaderUsername,
233
235
  subAgentUsername: reportedSub,
234
236
  toolName,
235
- task: truncateText(args.tasks ?? [], 2e3),
237
+ task: (0, import_ctx_utils.trimText)(args.tasks ?? [], 2e3),
236
238
  result: "",
237
239
  status: "error",
238
240
  depth: ctx[ORCHESTRATOR_DEPTH_KEY] ?? 0,
@@ -251,7 +253,7 @@ ${subAgentList}`
251
253
  leaderUsername,
252
254
  subAgentUsername: reportedSub,
253
255
  toolName,
254
- task: truncateText(args.tasks ?? [], 2e3),
256
+ task: (0, import_ctx_utils.trimText)(args.tasks ?? [], 2e3),
255
257
  result: "",
256
258
  status: "error",
257
259
  depth: ctx[ORCHESTRATOR_DEPTH_KEY] ?? 0,
@@ -324,25 +326,11 @@ ${subAgentList}`
324
326
  }
325
327
  };
326
328
  }
327
- function captureCtxSnapshot(ctx) {
328
- var _a, _b, _c, _d;
329
- let userId;
330
- try {
331
- userId = ((_b = (_a = ctx.auth) == null ? void 0 : _a.user) == null ? void 0 : _b.id) || ((_d = (_c = ctx.state) == null ? void 0 : _c.currentUser) == null ? void 0 : _d.id);
332
- } catch {
333
- }
334
- return { userId };
335
- }
336
- function normalizeEmployeeUsername(raw) {
337
- if (!raw) return null;
338
- if (typeof raw === "string") return raw;
339
- return raw.username || raw.aiEmployeeUsername || raw.name || null;
340
- }
341
329
  async function resolveCallingEmployee(ctx, plugin) {
342
330
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
343
331
  const values = ((_b = (_a = ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || {};
344
332
  const raw = ctx._currentAIEmployee || ((_c = ctx.state) == null ? void 0 : _c.currentAIEmployee) || ((_e = (_d = ctx.runtime) == null ? void 0 : _d.context) == null ? void 0 : _e.currentAIEmployee) || values.aiEmployee;
345
- const direct = normalizeEmployeeUsername(raw);
333
+ const direct = (0, import_ctx_utils.normalizeEmployeeUsername)(raw);
346
334
  if (direct) return direct;
347
335
  const sessionId = values.sessionId || ((_g = (_f = ctx.action) == null ? void 0 : _f.params) == null ? void 0 : _g.sessionId);
348
336
  if (!sessionId) return null;
@@ -351,20 +339,12 @@ async function resolveCallingEmployee(ctx, plugin) {
351
339
  const conversation = await repo.findOne({
352
340
  filter: { sessionId }
353
341
  });
354
- return normalizeEmployeeUsername((conversation == null ? void 0 : conversation.aiEmployeeUsername) || ((_j = conversation == null ? void 0 : conversation.get) == null ? void 0 : _j.call(conversation, "aiEmployeeUsername")));
342
+ return (0, import_ctx_utils.normalizeEmployeeUsername)((conversation == null ? void 0 : conversation.aiEmployeeUsername) || ((_j = conversation == null ? void 0 : conversation.get) == null ? void 0 : _j.call(conversation, "aiEmployeeUsername")));
355
343
  } catch (e) {
356
344
  plugin.app.log.warn(`[AgentOrchestrator] Failed to resolve AI employee for session "${sessionId}"`, e);
357
345
  return null;
358
346
  }
359
347
  }
360
- function truncateText(value, maxLen) {
361
- const text = typeof value === "string" ? value : value == null ? "" : JSON.stringify(value);
362
- return text.length > maxLen ? `${text.slice(0, maxLen)}
363
- ...[truncated]` : text;
364
- }
365
- function nowIso() {
366
- return (/* @__PURE__ */ new Date()).toISOString();
367
- }
368
348
  function hasModelSettings(value) {
369
349
  return Boolean((value == null ? void 0 : value.llmService) && (value == null ? void 0 : value.model));
370
350
  }
@@ -568,7 +548,7 @@ async function invokeDelegateTask(ctx, plugin, options) {
568
548
  rootRunId: providedRootRunId,
569
549
  parentSpanId: providedParentSpanId
570
550
  } = options;
571
- const ctxSnapshot = captureCtxSnapshot(ctx);
551
+ const ctxSnapshot = (0, import_ctx_utils.captureCtxSnapshot)(ctx);
572
552
  const currentDepth = ctx[ORCHESTRATOR_DEPTH_KEY] ?? 0;
573
553
  const currentPath = ctx[ORCHESTRATOR_PATH_KEY] ?? [leaderUsername];
574
554
  if (currentPath.includes(subAgentUsername)) {
@@ -637,53 +617,15 @@ async function invokeDelegateTask(ctx, plugin, options) {
637
617
  });
638
618
  }
639
619
  async function logDelegation(ctx, plugin, data) {
640
- var _a, _b, _c, _d, _e, _f;
641
- try {
642
- const logsRepo = plugin.db.getRepository("orchestratorLogs");
643
- if (!logsRepo) {
644
- plugin.app.log.warn("[AgentOrchestrator] orchestratorLogs repository not found \u2014 skipping log");
645
- return;
646
- }
647
- let userId = (_a = data.snapshot) == null ? void 0 : _a.userId;
648
- if (userId == null) {
649
- try {
650
- userId = ((_c = (_b = ctx.auth) == null ? void 0 : _b.user) == null ? void 0 : _c.id) || ((_e = (_d = ctx.state) == null ? void 0 : _d.currentUser) == null ? void 0 : _e.id);
651
- } catch {
652
- }
653
- }
654
- const values = {
655
- leaderUsername: data.leaderUsername,
656
- subAgentUsername: data.subAgentUsername,
657
- toolName: data.toolName,
658
- task: truncateText(data.task, 1e4),
659
- context: truncateText(data.context || "", 1e4),
660
- result: truncateText(data.result || "", 5e4),
661
- status: data.status,
662
- depth: data.depth,
663
- durationMs: data.durationMs,
664
- error: truncateText(data.error || "", 1e4),
665
- trace: data.trace || [],
666
- messages: data.messages || [],
667
- userId,
668
- updatedAt: /* @__PURE__ */ new Date()
669
- };
670
- if (data.id) {
671
- await logsRepo.update({
672
- filterByTk: data.id,
673
- values
674
- });
675
- return { id: data.id };
620
+ var _a, _b, _c, _d, _e;
621
+ let userId = (_a = data.snapshot) == null ? void 0 : _a.userId;
622
+ if (userId == null) {
623
+ try {
624
+ userId = ((_c = (_b = ctx.auth) == null ? void 0 : _b.user) == null ? void 0 : _c.id) || ((_e = (_d = ctx.state) == null ? void 0 : _d.currentUser) == null ? void 0 : _e.id);
625
+ } catch {
676
626
  }
677
- const record = await logsRepo.create({
678
- values: {
679
- ...values,
680
- createdAt: /* @__PURE__ */ new Date()
681
- }
682
- });
683
- return ((_f = record == null ? void 0 : record.toJSON) == null ? void 0 : _f.call(record)) || record;
684
- } catch (e) {
685
- plugin.app.log.warn("[AgentOrchestrator] Failed to log delegation event", e);
686
627
  }
628
+ return (0, import_logging.logDelegation)(ctx, plugin, { ...data, userId });
687
629
  }
688
630
  // Annotate the CommonJS export names for ESM import in node:
689
631
  0 && (module.exports = {
@@ -30,6 +30,7 @@ __export(orchestrator_plan_exports, {
30
30
  });
31
31
  module.exports = __toCommonJS(orchestrator_plan_exports);
32
32
  var import_zod = require("zod");
33
+ var import_ctx_utils = require("../utils/ctx-utils");
33
34
  const stepSchema = import_zod.z.object({
34
35
  id: import_zod.z.string().optional(),
35
36
  key: import_zod.z.string().optional(),
@@ -58,46 +59,6 @@ function toolResult(status, payload) {
58
59
  content: typeof payload === "string" ? payload : JSON.stringify(payload)
59
60
  };
60
61
  }
61
- function valuesFromCtx(ctx) {
62
- var _a, _b, _c;
63
- return ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || ((_c = ctx == null ? void 0 : ctx.request) == null ? void 0 : _c.body) || {};
64
- }
65
- function currentUserId(ctx) {
66
- var _a, _b, _c, _d;
67
- return ((_b = (_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentUser) == null ? void 0 : _b.id) || ((_d = (_c = ctx == null ? void 0 : ctx.auth) == null ? void 0 : _c.user) == null ? void 0 : _d.id);
68
- }
69
- function resolveSessionId(ctx, args) {
70
- var _a, _b, _c;
71
- const values = valuesFromCtx(ctx);
72
- return (args == null ? void 0 : args.sessionId) || values.sessionId || ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.sessionId) || ((_c = ctx == null ? void 0 : ctx.state) == null ? void 0 : _c.sessionId);
73
- }
74
- function resolveMessageId(ctx, args) {
75
- var _a, _b;
76
- const values = valuesFromCtx(ctx);
77
- return (args == null ? void 0 : args.messageId) || values.messageId || ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.messageId);
78
- }
79
- function normalizeEmployeeUsername(raw) {
80
- if (!raw) return null;
81
- if (typeof raw === "string") return raw;
82
- return raw.username || raw.aiEmployeeUsername || raw.name || null;
83
- }
84
- async function resolveLeaderUsername(ctx, plugin, args) {
85
- var _a, _b, _c, _d, _e, _f;
86
- const values = valuesFromCtx(ctx);
87
- const direct = normalizeEmployeeUsername(
88
- (args == null ? void 0 : args.leaderUsername) || (ctx == null ? void 0 : ctx._currentAIEmployee) || ((_a = ctx == null ? void 0 : ctx.state) == null ? void 0 : _a.currentAIEmployee) || ((_c = (_b = ctx == null ? void 0 : ctx.runtime) == null ? void 0 : _b.context) == null ? void 0 : _c.currentAIEmployee) || values.aiEmployee
89
- );
90
- if (direct) return direct;
91
- const sessionId = resolveSessionId(ctx, args);
92
- if (!sessionId) return void 0;
93
- try {
94
- const repo = ((_e = (_d = ctx == null ? void 0 : ctx.db) == null ? void 0 : _d.getRepository) == null ? void 0 : _e.call(_d, "aiConversations")) || plugin.db.getRepository("aiConversations");
95
- const conversation = await repo.findOne({ filter: { sessionId } });
96
- return normalizeEmployeeUsername((conversation == null ? void 0 : conversation.aiEmployeeUsername) || ((_f = conversation == null ? void 0 : conversation.get) == null ? void 0 : _f.call(conversation, "aiEmployeeUsername")));
97
- } catch {
98
- return void 0;
99
- }
100
- }
101
62
  function summarizePlan(steps) {
102
63
  return (steps || []).map((step) => ({
103
64
  id: step.id,
@@ -159,21 +120,23 @@ function createOrchestratorPlanTools(plugin, service) {
159
120
  plannerModel: import_zod.z.string().optional(),
160
121
  policy: policySchema,
161
122
  metadata: import_zod.z.any().optional(),
162
- plan: import_zod.z.array(stepSchema).optional().describe("Draft plan steps. Tool/sub_agent steps should include target. Dependencies must reference planKey values.")
123
+ plan: import_zod.z.array(stepSchema).optional().describe(
124
+ "Draft plan steps. Tool/sub_agent steps should include target. Dependencies must reference planKey values."
125
+ )
163
126
  })
164
127
  },
165
128
  invoke: async (ctx, args) => {
166
129
  try {
167
- const leaderUsername = await resolveLeaderUsername(ctx, plugin, args);
130
+ const leaderUsername = await (0, import_ctx_utils.resolveLeaderUsername)(ctx, plugin, args);
168
131
  const targetAgent = inferTargetAgent(args);
169
132
  const harnessTag = await resolveHarnessTag(plugin, leaderUsername, targetAgent, args);
170
133
  const detail = await service.planGoal({
171
134
  goal: args.goal,
172
135
  runId: args.runId,
173
136
  leaderUsername,
174
- sessionId: resolveSessionId(ctx, args),
175
- messageId: resolveMessageId(ctx, args),
176
- userId: currentUserId(ctx),
137
+ sessionId: (0, import_ctx_utils.resolveSessionId)(ctx, args),
138
+ messageId: (0, import_ctx_utils.resolveMessageId)(ctx, args),
139
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
177
140
  policy: args.policy,
178
141
  metadata: args.metadata,
179
142
  plan: Array.isArray(args.plan) ? args.plan : void 0,
@@ -220,7 +183,7 @@ function createOrchestratorPlanTools(plugin, service) {
220
183
  invoke: async (ctx, args) => {
221
184
  try {
222
185
  const detail = await service.approvePlanAndExecute(args.runId, {
223
- userId: currentUserId(ctx),
186
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
224
187
  ctx,
225
188
  reason: args.reason
226
189
  });
@@ -275,7 +238,7 @@ function createOrchestratorPlanTools(plugin, service) {
275
238
  "success",
276
239
  await service.cancelRun(args.runId, {
277
240
  reason: args.reason,
278
- userId: currentUserId(ctx)
241
+ userId: (0, import_ctx_utils.currentUserId)(ctx)
279
242
  })
280
243
  );
281
244
  } catch (error) {
@@ -0,0 +1,24 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __copyProps = (to, from, except, desc) => {
15
+ if (from && typeof from === "object" || typeof from === "function") {
16
+ for (let key of __getOwnPropNames(from))
17
+ if (!__hasOwnProp.call(to, key) && key !== except)
18
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
19
+ }
20
+ return to;
21
+ };
22
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
23
+ var types_exports = {};
24
+ module.exports = __toCommonJS(types_exports);