plugin-agent-orchestrator 1.1.2 → 1.1.4

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 (173) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/client-v2/214.b063f33ba044a808.js +10 -0
  3. package/dist/client-v2/253.59577b40d9875be0.js +10 -0
  4. package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
  5. package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
  6. package/dist/client-v2/418.58fa350f5496efd3.js +10 -0
  7. package/dist/client-v2/{53.7c29c28043e9112d.js → 53.9a10455323390f14.js} +1 -1
  8. package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
  9. package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
  10. package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
  11. package/dist/client-v2/925.e5925bf21ed68e7a.js +10 -0
  12. package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
  13. package/dist/client-v2/index.js +1 -1
  14. package/dist/externalVersion.js +8 -6
  15. package/dist/locale/en-US.json +48 -28
  16. package/dist/locale/vi-VN.json +48 -28
  17. package/dist/locale/zh-CN.json +48 -28
  18. package/dist/server/collections/agent-execution-spans.js +47 -0
  19. package/dist/server/collections/agent-harness-profile-versions.js +56 -0
  20. package/dist/server/collections/agent-harness-profiles.js +12 -0
  21. package/dist/server/collections/agent-loop-action-approvals.js +68 -0
  22. package/dist/server/collections/agent-loop-artifacts.js +55 -0
  23. package/dist/server/collections/agent-loop-circuit-states.js +53 -0
  24. package/dist/server/collections/agent-loop-control-settings.js +51 -0
  25. package/dist/server/collections/agent-loop-events.js +27 -0
  26. package/dist/server/collections/agent-loop-path-locks.js +57 -0
  27. package/dist/server/collections/agent-loop-patterns.js +72 -0
  28. package/dist/server/collections/agent-loop-runs.js +163 -2
  29. package/dist/server/collections/agent-loop-steps.js +69 -0
  30. package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
  31. package/dist/server/collections/agent-loop-worktrees.js +55 -0
  32. package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
  33. package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
  34. package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
  35. package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
  36. package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
  37. package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
  38. package/dist/server/plugin.js +52 -150
  39. package/dist/server/resources/agent-loop-approval.js +83 -0
  40. package/dist/server/resources/agent-loop-artifact.js +86 -0
  41. package/dist/server/resources/agent-loop-events-stream.js +130 -0
  42. package/dist/server/resources/agent-loop.js +181 -139
  43. package/dist/server/resources/resource-helpers.js +63 -0
  44. package/dist/server/resources/tracing.js +121 -107
  45. package/dist/server/services/DurableCircuitBreakerService.js +229 -0
  46. package/dist/server/services/HarnessCompiler.js +142 -0
  47. package/dist/server/services/HarnessProfileService.js +168 -0
  48. package/dist/server/services/HarnessSchema.js +167 -0
  49. package/dist/server/services/LoopBudgetService.js +269 -0
  50. package/dist/server/services/LoopControlService.js +139 -0
  51. package/dist/server/services/LoopPatternSchema.js +180 -0
  52. package/dist/server/services/LoopPatternService.js +132 -0
  53. package/dist/server/services/LoopRunRepository.js +205 -0
  54. package/dist/server/services/LoopRunStateMachine.js +389 -0
  55. package/dist/server/services/LoopSchedulerService.js +193 -0
  56. package/dist/server/services/LoopTriggerService.js +128 -0
  57. package/dist/server/services/LoopWorkerService.js +461 -0
  58. package/dist/server/services/PathLockService.js +288 -0
  59. package/dist/server/services/PluginAiRuntimeAdapter.js +215 -0
  60. package/dist/server/services/VerificationSchema.js +59 -0
  61. package/dist/server/services/VerificationService.js +169 -0
  62. package/dist/server/skill-hub/actions/git-import.js +13 -7
  63. package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
  64. package/dist/server/utils/ensure-indexes.js +111 -0
  65. package/dist/server/utils/loop-pattern-context.js +56 -0
  66. package/package.json +2 -2
  67. package/src/client/OrchestratorSettings.tsx +44 -0
  68. package/src/client-v2/components/AgentRunsTab.tsx +576 -494
  69. package/src/client-v2/components/HarnessProfilesTab.tsx +13 -8
  70. package/src/client-v2/components/MemoryInspectorTab.tsx +19 -3
  71. package/src/client-v2/components/TracingTab.tsx +515 -432
  72. package/src/client-v2/hooks/useApiRequest.ts +141 -121
  73. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +8 -6
  74. package/src/locale/en-US.json +52 -28
  75. package/src/locale/vi-VN.json +52 -28
  76. package/src/locale/zh-CN.json +52 -28
  77. package/src/server/__tests__/circuit-breaker.test.ts +225 -146
  78. package/src/server/__tests__/harness-compiler.test.ts +131 -0
  79. package/src/server/__tests__/harness-profile-service.test.ts +116 -0
  80. package/src/server/__tests__/harness-tool-plan.test.ts +148 -0
  81. package/src/server/__tests__/loop-budget-service.test.ts +255 -0
  82. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
  83. package/src/server/__tests__/loop-pattern-schema.test.ts +56 -0
  84. package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
  85. package/src/server/__tests__/loop-run-state-machine.test.ts +90 -0
  86. package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
  87. package/src/server/__tests__/loop-worker-execution.test.ts +236 -0
  88. package/src/server/__tests__/path-lock-service.test.ts +254 -0
  89. package/src/server/__tests__/smoke.test.ts +62 -21
  90. package/src/server/collections/agent-execution-spans.ts +47 -0
  91. package/src/server/collections/agent-harness-profile-versions.ts +26 -0
  92. package/src/server/collections/agent-harness-profiles.ts +12 -0
  93. package/src/server/collections/agent-loop-action-approvals.ts +38 -0
  94. package/src/server/collections/agent-loop-artifacts.ts +25 -0
  95. package/src/server/collections/agent-loop-circuit-states.ts +23 -0
  96. package/src/server/collections/agent-loop-control-settings.ts +21 -0
  97. package/src/server/collections/agent-loop-events.ts +27 -0
  98. package/src/server/collections/agent-loop-path-locks.ts +27 -0
  99. package/src/server/collections/agent-loop-patterns.ts +42 -0
  100. package/src/server/collections/agent-loop-runs.ts +163 -2
  101. package/src/server/collections/agent-loop-steps.ts +69 -0
  102. package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
  103. package/src/server/collections/agent-loop-worktrees.ts +25 -0
  104. package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +3 -0
  105. package/src/server/migrations/20260429000000-add-llm-fields.ts +3 -2
  106. package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +13 -6
  107. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +2 -1
  108. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +2 -1
  109. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
  110. package/src/server/plugin.ts +53 -167
  111. package/src/server/resources/agent-loop-approval.ts +52 -0
  112. package/src/server/resources/agent-loop-artifact.ts +56 -0
  113. package/src/server/resources/agent-loop-events-stream.ts +105 -0
  114. package/src/server/resources/agent-loop.ts +202 -143
  115. package/src/server/resources/agent-monitor.ts +482 -482
  116. package/src/server/resources/resource-helpers.ts +33 -0
  117. package/src/server/resources/tracing.ts +145 -137
  118. package/src/server/services/DurableCircuitBreakerService.ts +239 -0
  119. package/src/server/services/HarnessCompiler.ts +133 -0
  120. package/src/server/services/HarnessProfileService.ts +157 -0
  121. package/src/server/services/HarnessSchema.ts +163 -0
  122. package/src/server/services/LoopBudgetService.ts +275 -0
  123. package/src/server/services/LoopControlService.ts +124 -0
  124. package/src/server/services/LoopPatternSchema.ts +167 -0
  125. package/src/server/services/LoopPatternService.ts +143 -0
  126. package/src/server/services/LoopRunRepository.ts +237 -0
  127. package/src/server/services/LoopRunStateMachine.ts +432 -0
  128. package/src/server/services/LoopSchedulerService.ts +199 -0
  129. package/src/server/services/LoopTriggerService.ts +115 -0
  130. package/src/server/services/LoopWorkerService.ts +522 -0
  131. package/src/server/services/PathLockService.ts +321 -0
  132. package/src/server/services/PluginAiRuntimeAdapter.ts +315 -0
  133. package/src/server/services/VerificationSchema.ts +31 -0
  134. package/src/server/services/VerificationService.ts +185 -0
  135. package/src/server/skill-hub/actions/__tests__/git-import.test.ts +62 -0
  136. package/src/server/skill-hub/actions/git-import.ts +9 -3
  137. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +1 -5
  138. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +1 -3
  139. package/src/server/utils/ensure-indexes.ts +96 -0
  140. package/src/server/utils/logging.ts +0 -1
  141. package/src/server/utils/loop-pattern-context.ts +20 -0
  142. package/dist/client-v2/214.79650a549273f163.js +0 -10
  143. package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
  144. package/dist/client-v2/264.718a107e43fc163c.js +0 -10
  145. package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
  146. package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
  147. package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
  148. package/dist/server/services/AgentHarness.js +0 -81
  149. package/dist/server/services/AgentLoopController.js +0 -1023
  150. package/dist/server/services/AgentLoopRepository.js +0 -192
  151. package/dist/server/services/AgentLoopService.js +0 -142
  152. package/dist/server/services/AgentPlanValidator.js +0 -99
  153. package/dist/server/services/AgentPlannerService.js +0 -99
  154. package/dist/server/services/CircuitBreaker.js +0 -125
  155. package/dist/server/services/ContextAggregator.js +0 -201
  156. package/dist/server/services/PlanningPromptService.js +0 -95
  157. package/dist/server/tools/agent-loop.js +0 -373
  158. package/dist/server/tools/orchestrator-plan.js +0 -254
  159. package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
  160. package/src/server/__tests__/context-aggregator.test.ts +0 -222
  161. package/src/server/__tests__/parallel-execution.test.ts +0 -318
  162. package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
  163. package/src/server/services/AgentHarness.ts +0 -67
  164. package/src/server/services/AgentLoopController.ts +0 -1263
  165. package/src/server/services/AgentLoopRepository.ts +0 -178
  166. package/src/server/services/AgentLoopService.ts +0 -177
  167. package/src/server/services/AgentPlanValidator.ts +0 -73
  168. package/src/server/services/AgentPlannerService.ts +0 -80
  169. package/src/server/services/CircuitBreaker.ts +0 -126
  170. package/src/server/services/ContextAggregator.ts +0 -239
  171. package/src/server/services/PlanningPromptService.ts +0 -72
  172. package/src/server/tools/agent-loop.ts +0 -360
  173. package/src/server/tools/orchestrator-plan.ts +0 -255
@@ -0,0 +1,288 @@
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 PathLockService_exports = {};
28
+ __export(PathLockService_exports, {
29
+ PathLockService: () => PathLockService,
30
+ lockPathsOverlap: () => lockPathsOverlap,
31
+ normalizeLockPath: () => normalizeLockPath,
32
+ pathSetsOverlap: () => pathSetsOverlap,
33
+ waitGraphHasCycle: () => waitGraphHasCycle
34
+ });
35
+ module.exports = __toCommonJS(PathLockService_exports);
36
+ function read(record, key) {
37
+ const model = record;
38
+ return typeof model.get === "function" ? model.get(key) : record[key];
39
+ }
40
+ function positiveInteger(value) {
41
+ const parsed = Number(value);
42
+ return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
43
+ }
44
+ function asDate(value) {
45
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
46
+ if (typeof value === "string" || typeof value === "number") {
47
+ const parsed = new Date(value);
48
+ return Number.isNaN(parsed.getTime()) ? null : parsed;
49
+ }
50
+ return null;
51
+ }
52
+ function lockIsExpired(record, now) {
53
+ const expiresAt = asDate(read(record, "expiresAt"));
54
+ return !expiresAt || expiresAt.getTime() <= now.getTime();
55
+ }
56
+ function positiveTtl(ttlMs) {
57
+ if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {
58
+ throw new Error("Path lock TTL must be a positive number of milliseconds.");
59
+ }
60
+ return ttlMs;
61
+ }
62
+ function normalizeLockPath(value) {
63
+ const normalized = value.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/{2,}/g, "/");
64
+ if (!normalized || normalized.startsWith("/") || /^[a-zA-Z]:\//.test(normalized)) {
65
+ throw new Error(`Lock path must be repository-relative: ${value}`);
66
+ }
67
+ const segments = normalized.split("/");
68
+ if (segments.some((segment) => segment === ".." || segment === ".")) {
69
+ throw new Error(`Lock path cannot contain dot segments: ${value}`);
70
+ }
71
+ return normalized.replace(/\/$/, "");
72
+ }
73
+ function literalPrefix(pattern) {
74
+ const result = [];
75
+ for (const segment of normalizeLockPath(pattern).split("/")) {
76
+ if (/[*?{[\]]/.test(segment)) break;
77
+ result.push(segment);
78
+ }
79
+ return result;
80
+ }
81
+ function lockPathsOverlap(left, right) {
82
+ const leftNormalized = normalizeLockPath(left);
83
+ const rightNormalized = normalizeLockPath(right);
84
+ if (leftNormalized === rightNormalized) return true;
85
+ const leftPrefix = literalPrefix(leftNormalized);
86
+ const rightPrefix = literalPrefix(rightNormalized);
87
+ if (leftPrefix.length === 0 || rightPrefix.length === 0) return true;
88
+ const shared = Math.min(leftPrefix.length, rightPrefix.length);
89
+ for (let index = 0; index < shared; index += 1) {
90
+ if (leftPrefix[index] !== rightPrefix[index]) return false;
91
+ }
92
+ const leftHasPattern = leftPrefix.length < leftNormalized.split("/").length;
93
+ const rightHasPattern = rightPrefix.length < rightNormalized.split("/").length;
94
+ if (leftHasPattern || rightHasPattern) return true;
95
+ return leftPrefix.length !== rightPrefix.length;
96
+ }
97
+ function pathSetsOverlap(left, right) {
98
+ return left.some((leftPath) => right.some((rightPath) => lockPathsOverlap(leftPath, rightPath)));
99
+ }
100
+ function row(record) {
101
+ const status = read(record, "status");
102
+ return {
103
+ id: positiveInteger(read(record, "id")) || 0,
104
+ runId: positiveInteger(read(record, "runId")) || 0,
105
+ repositoryKey: String(read(record, "repositoryKey") || ""),
106
+ paths: Array.isArray(read(record, "paths")) ? read(record, "paths") : [],
107
+ status: status === "held" || status === "released" || status === "expired" ? status : "waiting",
108
+ blockerRunIds: Array.isArray(read(record, "blockerRunIds")) ? read(record, "blockerRunIds").map(positiveInteger).filter((value) => value !== null) : []
109
+ };
110
+ }
111
+ function waitGraphHasCycle(rows, runId, blockers) {
112
+ const graph = /* @__PURE__ */ new Map();
113
+ for (const lock of rows) {
114
+ if (lock.status === "waiting") graph.set(lock.runId, lock.blockerRunIds);
115
+ }
116
+ graph.set(runId, blockers);
117
+ const visiting = /* @__PURE__ */ new Set();
118
+ const visited = /* @__PURE__ */ new Set();
119
+ const visit = (node) => {
120
+ if (visiting.has(node)) return true;
121
+ if (visited.has(node)) return false;
122
+ visiting.add(node);
123
+ for (const blocker of graph.get(node) || []) {
124
+ if (visit(blocker)) return true;
125
+ }
126
+ visiting.delete(node);
127
+ visited.add(node);
128
+ return false;
129
+ };
130
+ return visit(runId);
131
+ }
132
+ class PathLockService {
133
+ constructor(database, distributedLock) {
134
+ this.database = database;
135
+ this.distributedLock = distributedLock;
136
+ }
137
+ async acquire(input) {
138
+ const paths = Array.from(new Set(input.paths.map(normalizeLockPath))).sort();
139
+ if (!paths.length) throw new Error("At least one repository path is required for a path lock.");
140
+ const repositoryKey = input.repositoryKey.trim();
141
+ if (!repositoryKey) throw new Error("Repository key is required for a path lock.");
142
+ const ttlMs = positiveTtl(input.ttlMs);
143
+ return this.distributedLock.runExclusive(
144
+ `agent-loop:path:${repositoryKey}`,
145
+ () => this.database.sequelize.transaction(async (transaction) => {
146
+ const repository = this.database.getRepository("agentLoopPathLocks");
147
+ const now = /* @__PURE__ */ new Date();
148
+ const existing = await repository.findOne({
149
+ filter: { runId: input.runId, repositoryKey },
150
+ transaction,
151
+ lock: transaction.LOCK.UPDATE
152
+ });
153
+ if (existing && read(existing, "status") === "held") {
154
+ const sameOwner = String(read(existing, "owner") || "") === input.owner;
155
+ const samePaths = JSON.stringify(row(existing).paths.slice().sort()) === JSON.stringify(paths);
156
+ if (sameOwner && samePaths && !lockIsExpired(existing, now)) {
157
+ return { acquired: true, lock: row(existing), blockers: [] };
158
+ }
159
+ }
160
+ const held = await repository.find({
161
+ filter: { repositoryKey, status: "held" },
162
+ transaction,
163
+ lock: transaction.LOCK.UPDATE
164
+ });
165
+ const active = [];
166
+ for (const lock of held) {
167
+ if (!lockIsExpired(lock, now)) {
168
+ active.push(lock);
169
+ continue;
170
+ }
171
+ await repository.update({
172
+ filterByTk: read(lock, "id"),
173
+ values: { status: "expired", releasedAt: now, blockerRunIds: [] },
174
+ transaction
175
+ });
176
+ }
177
+ const blockers = active.map(row).filter((lock) => lock.runId !== input.runId && pathSetsOverlap(paths, lock.paths)).map((lock) => lock.runId);
178
+ if (blockers.length) {
179
+ const waitingRows = (await repository.find({
180
+ filter: { repositoryKey, status: "waiting" },
181
+ transaction,
182
+ lock: transaction.LOCK.UPDATE
183
+ })).map(row);
184
+ if (waitGraphHasCycle(waitingRows, input.runId, blockers)) {
185
+ return { acquired: false, deadlocked: true, blockers };
186
+ }
187
+ const values2 = {
188
+ runId: input.runId,
189
+ repositoryKey,
190
+ owner: input.owner,
191
+ paths,
192
+ status: "waiting",
193
+ blockerRunIds: blockers,
194
+ waitUntil: input.waitUntil || null,
195
+ acquiredAt: null,
196
+ expiresAt: null,
197
+ releasedAt: null
198
+ };
199
+ if (existing) {
200
+ await repository.update({ filterByTk: read(existing, "id"), values: values2, transaction });
201
+ } else {
202
+ await repository.create({ values: values2, transaction });
203
+ }
204
+ return { acquired: false, deadlocked: false, blockers };
205
+ }
206
+ const values = {
207
+ runId: input.runId,
208
+ repositoryKey,
209
+ owner: input.owner,
210
+ paths,
211
+ status: "held",
212
+ blockerRunIds: [],
213
+ acquiredAt: now,
214
+ expiresAt: new Date(now.getTime() + ttlMs),
215
+ waitUntil: null,
216
+ releasedAt: null
217
+ };
218
+ const locked = existing ? await this.updateAndRead(repository, Number(read(existing, "id")), values, transaction) : await repository.create({ values, transaction });
219
+ return { acquired: true, lock: row(locked), blockers: [] };
220
+ }),
221
+ Math.max(ttlMs, 5e3)
222
+ );
223
+ }
224
+ async renew(runId, repositoryKey, ttlMs, owner) {
225
+ const ttl = positiveTtl(ttlMs);
226
+ return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
227
+ const repository = this.database.getRepository("agentLoopPathLocks");
228
+ const expired = await this.database.sequelize.transaction(async (transaction) => {
229
+ const lock = await repository.findOne({
230
+ filter: { runId, repositoryKey, status: "held" },
231
+ transaction,
232
+ lock: transaction.LOCK.UPDATE
233
+ });
234
+ if (!lock) throw new Error("Held path lock was not found.");
235
+ if (owner !== void 0 && String(read(lock, "owner") || "") !== owner) {
236
+ throw new Error("Path lock is no longer owned by this worker.");
237
+ }
238
+ const now = /* @__PURE__ */ new Date();
239
+ if (lockIsExpired(lock, now)) return { id: read(lock, "id"), at: now };
240
+ await repository.update({
241
+ filterByTk: read(lock, "id"),
242
+ values: { expiresAt: new Date(now.getTime() + ttl) },
243
+ transaction
244
+ });
245
+ return null;
246
+ });
247
+ if (expired) {
248
+ await this.database.sequelize.transaction(async (transaction) => {
249
+ await repository.update({
250
+ filterByTk: expired.id,
251
+ values: { status: "expired", releasedAt: expired.at, blockerRunIds: [] },
252
+ transaction
253
+ });
254
+ });
255
+ throw new Error("Path lock has expired and must be reacquired.");
256
+ }
257
+ });
258
+ }
259
+ // The owner token guards against a reclaimed run: once a stale worker's lease expires and another
260
+ // worker takes over the same run, the original worker must not free a lock the new owner now holds.
261
+ async release(runId, repositoryKey, owner) {
262
+ return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
263
+ const repository = this.database.getRepository("agentLoopPathLocks");
264
+ const lock = await repository.findOne({ filter: { runId, repositoryKey } });
265
+ if (!lock || ["released", "expired"].includes(String(read(lock, "status")))) return false;
266
+ if (owner !== void 0 && String(read(lock, "owner") || "") !== owner) return false;
267
+ await repository.update({
268
+ filterByTk: read(lock, "id"),
269
+ values: { status: "released", releasedAt: /* @__PURE__ */ new Date(), blockerRunIds: [] }
270
+ });
271
+ return true;
272
+ });
273
+ }
274
+ async updateAndRead(repository, id, values, transaction) {
275
+ await repository.update({ filterByTk: id, values, transaction });
276
+ const updated = await repository.findOne({ filterByTk: id, transaction });
277
+ if (!updated) throw new Error("Path lock disappeared during update.");
278
+ return updated;
279
+ }
280
+ }
281
+ // Annotate the CommonJS export names for ESM import in node:
282
+ 0 && (module.exports = {
283
+ PathLockService,
284
+ lockPathsOverlap,
285
+ normalizeLockPath,
286
+ pathSetsOverlap,
287
+ waitGraphHasCycle
288
+ });
@@ -0,0 +1,215 @@
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 PluginAiRuntimeAdapter_exports = {};
28
+ __export(PluginAiRuntimeAdapter_exports, {
29
+ PluginAiRuntimeAdapter: () => PluginAiRuntimeAdapter,
30
+ planHarnessTools: () => planHarnessTools
31
+ });
32
+ module.exports = __toCommonJS(PluginAiRuntimeAdapter_exports);
33
+ var import_server = require("@nocobase/plugin-ai/server");
34
+ var import_ai = require("@nocobase/ai");
35
+ var import_ai_manager = require("../utils/ai-manager");
36
+ var import_HarnessCompiler = require("./HarnessCompiler");
37
+ const SYSTEM_TOOL_WEB_SEARCH = "subAgentWebSearch";
38
+ const SYSTEM_TOOL_KNOWLEDGE_BASE = "knowledge-base-retrieve";
39
+ function read(record, key) {
40
+ const model = record;
41
+ return typeof model.get === "function" ? model.get(key) : record[key];
42
+ }
43
+ function textContent(messages) {
44
+ if (!Array.isArray(messages)) return "";
45
+ const last = messages[messages.length - 1];
46
+ if (typeof (last == null ? void 0 : last.content) === "string") return last.content;
47
+ if (Array.isArray(last == null ? void 0 : last.content)) {
48
+ return last.content.map(
49
+ (part) => typeof part === "object" && part && "text" in part ? String(part.text) : ""
50
+ ).join("");
51
+ }
52
+ return "";
53
+ }
54
+ function interruptedFrom(result) {
55
+ const interrupts = result.__interrupt__;
56
+ if (!Array.isArray(interrupts)) return [];
57
+ const calls = [];
58
+ for (const interrupt of interrupts) {
59
+ const value = interrupt.value ?? interrupt;
60
+ const record = value;
61
+ const toolCallId = String(record.toolCallId || record.tool_call_id || "");
62
+ if (!toolCallId) continue;
63
+ calls.push({
64
+ toolCallId,
65
+ toolName: String(record.name || record.toolName || ""),
66
+ args: record.args ?? record.input ?? {},
67
+ interruptId: String(interrupt.id || record.interruptId || "")
68
+ });
69
+ }
70
+ return calls;
71
+ }
72
+ function askIsEnforceable(entry) {
73
+ return (entry == null ? void 0 : entry.scope) === "CUSTOM" || (entry == null ? void 0 : entry.defaultPermission) !== "ALLOW";
74
+ }
75
+ async function planHarnessTools(app, harness, discovery) {
76
+ const toolsManager = (0, import_ai_manager.getAIToolsManager)(app);
77
+ const candidates = Array.from(/* @__PURE__ */ new Set([...harness.tools.allow, ...harness.tools.ask]));
78
+ const plan = { filter: [], employeeTools: [], withheld: [], blockedSystemTools: [] };
79
+ const filter = discovery ? { ctx: discovery.ctx, sessionId: discovery.sessionId } : void 0;
80
+ for (const name of candidates.sort()) {
81
+ const decision = (0, import_HarnessCompiler.decideTool)(harness, name);
82
+ if (decision === "deny") {
83
+ plan.withheld.push({ name, reason: "denied by harness" });
84
+ continue;
85
+ }
86
+ const entry = await toolsManager.getTools(name, filter);
87
+ if (!entry) {
88
+ plan.withheld.push({ name, reason: "not registered with plugin-ai" });
89
+ continue;
90
+ }
91
+ if (decision === "ask" && !askIsEnforceable(entry)) {
92
+ plan.withheld.push({ name, reason: "approval cannot be enforced for this tool" });
93
+ continue;
94
+ }
95
+ plan.filter.push(name);
96
+ plan.employeeTools.push({ name, autoCall: decision === "allow" });
97
+ }
98
+ const granted = new Set(plan.filter);
99
+ plan.blockedSystemTools = (0, import_ai.listSystemTools)().filter((name) => !granted.has(name)).sort();
100
+ return plan;
101
+ }
102
+ class PluginAiRuntimeAdapter {
103
+ constructor(app) {
104
+ this.app = app;
105
+ }
106
+ plugin() {
107
+ const plugin = this.app.pm.get("ai");
108
+ if (!(plugin == null ? void 0 : plugin.aiEmployeesManager) || !(plugin == null ? void 0 : plugin.aiConversationsManager)) {
109
+ throw new Error("The official @nocobase/plugin-ai plugin is required to execute Loop Control Plane runs.");
110
+ }
111
+ return plugin;
112
+ }
113
+ async createConversation(input) {
114
+ const conversation = await this.plugin().aiConversationsManager.create({
115
+ userId: input.userId,
116
+ aiEmployee: { username: input.username },
117
+ title: input.title,
118
+ category: "task",
119
+ options: { controlPlaneRunId: input.runId }
120
+ });
121
+ const sessionId = String(read(conversation, "sessionId") || "");
122
+ if (!sessionId) throw new Error("The AI conversation was created without a session identifier.");
123
+ return sessionId;
124
+ }
125
+ async invoke(input) {
126
+ const { aiEmployee } = await this.buildEmployee(input);
127
+ const result = await aiEmployee.invoke({
128
+ userMessages: [{ role: "user", content: input.prompt }],
129
+ signal: input.signal
130
+ });
131
+ return {
132
+ sessionId: input.sessionId,
133
+ messageId: String(result.messageId || ""),
134
+ interrupted: interruptedFrom(result),
135
+ content: textContent(result.messages)
136
+ };
137
+ }
138
+ // Resume mirrors the official workflow employee node: flip the persisted tool call to
139
+ // `waiting` with a decision, then re-invoke so plugin-ai resumes its own checkpoint.
140
+ async resume(input) {
141
+ const plugin = this.plugin();
142
+ await this.app.db.getModel("aiToolMessages").update(
143
+ { userDecision: input.decision, invokeStatus: "waiting" },
144
+ { where: { sessionId: input.sessionId, messageId: input.messageId, invokeStatus: "interrupted" } }
145
+ );
146
+ const userDecisions = await plugin.aiConversationsManager.getUserDecisions(input.messageId);
147
+ if (!userDecisions) throw new Error("The interrupted tool calls are not all ready to resume.");
148
+ const { aiEmployee } = await this.buildEmployee(input);
149
+ const result = await aiEmployee.invoke({
150
+ messageId: input.messageId,
151
+ userDecisions,
152
+ signal: input.signal
153
+ });
154
+ return {
155
+ sessionId: input.sessionId,
156
+ messageId: String(result.messageId || input.messageId),
157
+ interrupted: interruptedFrom(result),
158
+ content: textContent(result.messages)
159
+ };
160
+ }
161
+ // The employee model is re-read per invocation and mutated only in memory. `isAutoCall` reads
162
+ // `employee.skillSettings` off the Sequelize dataValues, so `set()` without `save()` gates this
163
+ // run's tool calls without touching the shared employee configuration.
164
+ async buildEmployee(input) {
165
+ const plugin = this.plugin();
166
+ const employee = await plugin.aiEmployeesManager.getEmployee(input.username);
167
+ if (!employee) throw new Error(`AI employee "${input.username}" was not found.`);
168
+ const model = await plugin.aiEmployeesManager.resolveModel(employee);
169
+ const currentRoles = await this.rolesFor(input.userId);
170
+ const ctx = {
171
+ app: this.app,
172
+ db: this.app.db,
173
+ log: this.app.log,
174
+ logger: this.app.log,
175
+ state: { currentRoles },
176
+ auth: { user: { id: input.userId } },
177
+ action: { params: { values: { sessionId: input.sessionId, model } } }
178
+ };
179
+ const plan = await planHarnessTools(this.app, input.harness, { ctx, sessionId: input.sessionId });
180
+ if (plan.withheld.length) {
181
+ this.app.logger.info(
182
+ `[AgentOrchestrator] Harness withheld ${plan.withheld.length} tool(s) from ${input.username}.`,
183
+ { withheld: plan.withheld }
184
+ );
185
+ }
186
+ const persisted = employee.get("skillSettings") || {};
187
+ employee.set("skillSettings", { ...persisted, tools: plan.employeeTools });
188
+ const blockedSystemTools = new Set(plan.blockedSystemTools);
189
+ if (blockedSystemTools.has(SYSTEM_TOOL_KNOWLEDGE_BASE)) {
190
+ employee.set("enableKnowledgeBase", false);
191
+ }
192
+ const aiEmployee = new import_server.AIEmployee({
193
+ ctx,
194
+ employee,
195
+ sessionId: input.sessionId,
196
+ systemMessage: input.systemMessage,
197
+ skillSettings: { skillsVersion: 2, toolsVersion: 2, skills: [], tools: plan.filter },
198
+ // Same reasoning for web search: the flag is what injects the system tool, so it is only
199
+ // ever enabled when the harness explicitly granted it.
200
+ webSearch: !blockedSystemTools.has(SYSTEM_TOOL_WEB_SEARCH),
201
+ model
202
+ });
203
+ return { aiEmployee, plan };
204
+ }
205
+ async rolesFor(userId) {
206
+ if (!userId) return [];
207
+ const rows = await this.app.db.getRepository("rolesUsers").find({ filter: { userId } });
208
+ return rows.map((row) => String(read(row, "roleName") || "")).filter(Boolean);
209
+ }
210
+ }
211
+ // Annotate the CommonJS export names for ESM import in node:
212
+ 0 && (module.exports = {
213
+ PluginAiRuntimeAdapter,
214
+ planHarnessTools
215
+ });
@@ -0,0 +1,59 @@
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 VerificationSchema_exports = {};
28
+ __export(VerificationSchema_exports, {
29
+ isPassingVerification: () => isPassingVerification,
30
+ parseVerificationVerdict: () => parseVerificationVerdict,
31
+ verificationVerdictSchema: () => verificationVerdictSchema
32
+ });
33
+ module.exports = __toCommonJS(VerificationSchema_exports);
34
+ var import_zod = require("zod");
35
+ const verificationVerdictSchema = import_zod.z.object({
36
+ verdict: import_zod.z.enum(["pass", "reject", "escalate"]),
37
+ summary: import_zod.z.string().min(1),
38
+ checks: import_zod.z.array(
39
+ import_zod.z.object({
40
+ name: import_zod.z.string().min(1),
41
+ status: import_zod.z.enum(["pass", "fail", "skipped"]),
42
+ evidenceArtifactIds: import_zod.z.array(import_zod.z.number().int().positive()).default([])
43
+ })
44
+ ).min(1),
45
+ residualRisks: import_zod.z.array(import_zod.z.string()).default([])
46
+ });
47
+ function parseVerificationVerdict(value) {
48
+ return verificationVerdictSchema.parse(value);
49
+ }
50
+ function isPassingVerification(value) {
51
+ const parsed = verificationVerdictSchema.safeParse(value);
52
+ return parsed.success && parsed.data.verdict === "pass" && parsed.data.checks.every((check) => check.status === "pass" && check.evidenceArtifactIds.length > 0);
53
+ }
54
+ // Annotate the CommonJS export names for ESM import in node:
55
+ 0 && (module.exports = {
56
+ isPassingVerification,
57
+ parseVerificationVerdict,
58
+ verificationVerdictSchema
59
+ });