plugin-agent-orchestrator 1.1.4 → 1.1.6

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 (148) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  6. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  7. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +7 -8
  10. package/dist/locale/en-US.json +226 -170
  11. package/dist/locale/vi-VN.json +226 -170
  12. package/dist/locale/zh-CN.json +226 -170
  13. package/dist/server/collections/agent-execution-spans.js +8 -0
  14. package/dist/server/collections/agent-loop-action-approvals.js +1 -0
  15. package/dist/server/collections/agent-loop-runs.js +7 -1
  16. package/dist/server/collections/agent-loop-steps.js +7 -0
  17. package/dist/server/collections/skill-executions.js +8 -0
  18. package/dist/server/plugin.js +3 -1
  19. package/dist/server/resources/agent-harness-profile.js +117 -0
  20. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  21. package/dist/server/resources/agent-loop-approval.js +25 -0
  22. package/dist/server/resources/agent-loop.js +3 -1
  23. package/dist/server/services/AgentMemoryContextService.js +34 -0
  24. package/dist/server/services/HarnessCompiler.js +35 -2
  25. package/dist/server/services/HarnessProfileService.js +74 -9
  26. package/dist/server/services/HarnessSchema.js +30 -3
  27. package/dist/server/services/LoopPatternSchema.js +16 -1
  28. package/dist/server/services/LoopRunRepository.js +80 -0
  29. package/dist/server/services/LoopRunStateMachine.js +92 -3
  30. package/dist/server/services/LoopTriggerService.js +37 -0
  31. package/dist/server/services/LoopWorkerService.js +261 -23
  32. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  33. package/dist/server/services/PluginAiRuntimeAdapter.js +16 -5
  34. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  35. package/dist/server/services/VerificationService.js +66 -0
  36. package/dist/server/services/harness-runtime-policy.js +139 -0
  37. package/dist/server/skill-hub/plugin.js +36 -3
  38. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  39. package/package.json +53 -53
  40. package/src/client/ApprovalsTab.tsx +2 -0
  41. package/src/client/OrchestratorSettings.tsx +11 -0
  42. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  43. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  44. package/src/client/skill-hub/index.tsx +0 -52
  45. package/src/client-v2/components/AgentRunsTab.tsx +576 -576
  46. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  47. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -105
  48. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -141
  49. package/src/client-v2/components/TracingTab.tsx +515 -515
  50. package/src/client-v2/hooks/useApiRequest.ts +141 -141
  51. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  52. package/src/client-v2/plugin.tsx +6 -6
  53. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +5 -2
  54. package/src/locale/en-US.json +226 -174
  55. package/src/locale/vi-VN.json +226 -174
  56. package/src/locale/zh-CN.json +226 -174
  57. package/src/server/__tests__/circuit-breaker.test.ts +248 -248
  58. package/src/server/__tests__/harness-compiler.test.ts +83 -0
  59. package/src/server/__tests__/harness-profile-service.test.ts +51 -0
  60. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  61. package/src/server/__tests__/harness-tool-plan.test.ts +24 -0
  62. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  63. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  64. package/src/server/__tests__/loop-budget-service.test.ts +255 -255
  65. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -266
  66. package/src/server/__tests__/loop-pattern-schema.test.ts +18 -1
  67. package/src/server/__tests__/loop-pattern-service.test.ts +148 -148
  68. package/src/server/__tests__/loop-run-state-machine.test.ts +11 -0
  69. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  70. package/src/server/__tests__/loop-worker-claim.test.ts +341 -341
  71. package/src/server/__tests__/loop-worker-execution.test.ts +82 -1
  72. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  73. package/src/server/__tests__/path-lock-service.test.ts +254 -254
  74. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  75. package/src/server/__tests__/smoke.test.ts +162 -162
  76. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  77. package/src/server/collections/agent-execution-spans.ts +8 -0
  78. package/src/server/collections/agent-harness-profile-versions.ts +26 -26
  79. package/src/server/collections/agent-harness-profiles.ts +71 -71
  80. package/src/server/collections/agent-loop-action-approvals.ts +1 -0
  81. package/src/server/collections/agent-loop-artifacts.ts +25 -25
  82. package/src/server/collections/agent-loop-circuit-states.ts +23 -23
  83. package/src/server/collections/agent-loop-control-settings.ts +21 -21
  84. package/src/server/collections/agent-loop-events.ts +98 -98
  85. package/src/server/collections/agent-loop-path-locks.ts +27 -27
  86. package/src/server/collections/agent-loop-patterns.ts +42 -42
  87. package/src/server/collections/agent-loop-runs.ts +7 -1
  88. package/src/server/collections/agent-loop-steps.ts +7 -0
  89. package/src/server/collections/agent-loop-usage-buckets.ts +22 -22
  90. package/src/server/collections/agent-loop-worktrees.ts +25 -25
  91. package/src/server/collections/skill-executions.ts +8 -0
  92. package/src/server/migrations/20260427000002-change-packages-to-text.ts +52 -52
  93. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -47
  94. package/src/server/migrations/20260429000001-fix-inputargs-json-to-text.ts +45 -45
  95. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -33
  96. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -31
  97. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -293
  98. package/src/server/plugin.ts +3 -1
  99. package/src/server/resources/agent-harness-profile.ts +94 -0
  100. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  101. package/src/server/resources/agent-loop-approval.ts +32 -0
  102. package/src/server/resources/agent-loop-artifact.ts +56 -56
  103. package/src/server/resources/agent-loop-events-stream.ts +105 -105
  104. package/src/server/resources/agent-loop.ts +3 -1
  105. package/src/server/resources/resource-helpers.ts +33 -33
  106. package/src/server/resources/tracing.ts +266 -266
  107. package/src/server/services/AgentMemoryContextService.ts +44 -0
  108. package/src/server/services/DurableCircuitBreakerService.ts +239 -239
  109. package/src/server/services/ExecutionSpanService.ts +2 -0
  110. package/src/server/services/HarnessCompiler.ts +37 -0
  111. package/src/server/services/HarnessProfileService.ts +92 -10
  112. package/src/server/services/HarnessSchema.ts +31 -0
  113. package/src/server/services/LoopBudgetService.ts +275 -275
  114. package/src/server/services/LoopControlService.ts +124 -124
  115. package/src/server/services/LoopPatternSchema.ts +19 -1
  116. package/src/server/services/LoopPatternService.ts +143 -143
  117. package/src/server/services/LoopRunRepository.ts +99 -0
  118. package/src/server/services/LoopRunStateMachine.ts +100 -3
  119. package/src/server/services/LoopSchedulerService.ts +199 -199
  120. package/src/server/services/LoopTriggerService.ts +42 -0
  121. package/src/server/services/LoopWorkerService.ts +327 -27
  122. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  123. package/src/server/services/PathLockService.ts +321 -321
  124. package/src/server/services/PluginAiRuntimeAdapter.ts +24 -7
  125. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  126. package/src/server/services/VerificationSchema.ts +31 -31
  127. package/src/server/services/VerificationService.ts +81 -2
  128. package/src/server/services/harness-runtime-policy.ts +141 -0
  129. package/src/server/skill-hub/plugin.ts +41 -3
  130. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -235
  131. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -61
  132. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  133. package/src/server/utils/ensure-indexes.ts +96 -96
  134. package/src/server/utils/logging.ts +62 -62
  135. package/src/server/utils/loop-pattern-context.ts +20 -20
  136. package/dist/client-v2/214.b063f33ba044a808.js +0 -10
  137. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  138. package/dist/client-v2/418.58fa350f5496efd3.js +0 -10
  139. package/dist/client-v2/53.9a10455323390f14.js +0 -10
  140. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  141. package/dist/client-v2/925.e5925bf21ed68e7a.js +0 -10
  142. package/src/client/AIEmployeeSelect.tsx +0 -47
  143. package/src/client/AIEmployeesContext.tsx +0 -102
  144. package/src/client/RulesTab.tsx +0 -2
  145. package/src/client/TracingTab.tsx +0 -436
  146. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  147. package/src/client-v2/components/RulesTab.tsx +0 -2
  148. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
@@ -32,10 +32,14 @@ __export(NativeSubAgentObserver_exports, {
32
32
  });
33
33
  module.exports = __toCommonJS(NativeSubAgentObserver_exports);
34
34
  var import_crypto = require("crypto");
35
+ var import_fs = require("fs");
36
+ var import_path = require("path");
35
37
  var import_ExecutionSpanService = require("./ExecutionSpanService");
36
38
  var import_AgentMemoryContextService = require("./AgentMemoryContextService");
37
39
  var import_TokenTracker = require("./TokenTracker");
38
40
  var import_AgentExecutionContext = require("./AgentExecutionContext");
41
+ var import_HarnessCompiler = require("./HarnessCompiler");
42
+ var import_harness_runtime_policy = require("./harness-runtime-policy");
39
43
  var import_ctx_utils = require("../utils/ctx-utils");
40
44
  const WRAP_STATE_KEY = Symbol.for("plugin-agent-orchestrator.nativeSubAgentObserver");
41
45
  const NATIVE_SOURCE = "native-plugin-ai";
@@ -132,13 +136,23 @@ class NativeSubAgentObserver {
132
136
  return originalRun(task);
133
137
  }
134
138
  const parentSessionId = this.resolveParentSessionId(task) || void 0;
139
+ const parentConversation = await this.safeFindParentConversation(task.ctx, parentSessionId);
140
+ const parentRunId = this.controlPlaneRunIdOf(parentConversation);
141
+ const parentRunHarness = parentRunId ? await this.safeResolveParentRunHarness(
142
+ parentRunId,
143
+ normalizeString(readValue(parentConversation, "aiEmployeeUsername"))
144
+ ) : null;
145
+ const policy = this.compilePolicy(settings, parentRunHarness);
146
+ const spansEnabled = policy.observability.sharing !== "disabled";
135
147
  const subSessionId = normalizeString(task.sessionId) || void 0;
136
148
  const employeeUsername = modelUsername(task.employee);
137
149
  const userId = (0, import_ctx_utils.currentUserId)(task.ctx) || ((_c = (_b = (_a = task.ctx) == null ? void 0 : _a.auth) == null ? void 0 : _b.user) == null ? void 0 : _c.id);
138
150
  const dispatchToolMessage = await this.resolveDispatchToolMessage(task.ctx, parentSessionId, subSessionId);
139
151
  const toolCallId = dispatchToolMessage == null ? void 0 : dispatchToolMessage.toolCallId;
140
- const leaderUsername = await this.resolveLeaderUsername(task.ctx, parentSessionId);
152
+ const leaderUsername = this.leaderUsernameFor(task.ctx, parentConversation);
141
153
  const rootRunId = makeNativeRunId([parentSessionId, subSessionId, toolCallId, employeeUsername]);
154
+ const delegation = await this.resolveDelegationContext(parentSessionId);
155
+ const childDepth = delegation.depth + 1;
142
156
  const memory = await this.safeBuildMemoryContext({
143
157
  userId,
144
158
  aiEmployeeUsername: employeeUsername,
@@ -169,7 +183,8 @@ ${task.question}
169
183
  memoryContextApplied: Boolean(memory.context),
170
184
  memoryScopes: memory.appliedScopes,
171
185
  memoryContextChars: memory.chars,
172
- harnessTag: settings.harnessTag || "default"
186
+ harnessTag: settings.harnessTag || "default",
187
+ ...parentRunId ? { agentLoopRunId: parentRunId } : {}
173
188
  },
174
189
  parentSessionId,
175
190
  subSessionId,
@@ -177,10 +192,29 @@ ${task.question}
177
192
  leaderUsername,
178
193
  employeeUsername,
179
194
  userId,
195
+ policy,
180
196
  toolSpans: /* @__PURE__ */ new Map(),
181
197
  pending: /* @__PURE__ */ new Set()
182
198
  };
183
- await this.safeCreateRootSpan(state, task.question);
199
+ if (spansEnabled) {
200
+ await this.safeCreateRootSpan(state, task.question, {
201
+ depth: childDepth,
202
+ parentSpanId: delegation.parentSpanId,
203
+ agentLoopRunId: parentRunId
204
+ });
205
+ }
206
+ const maxDepth = policy.delegation.maxDepth;
207
+ if (maxDepth !== null && childDepth > maxDepth) {
208
+ const message = `Sub-agent delegation depth ${childDepth} exceeds the harness limit of ${maxDepth}.`;
209
+ await this.spanService.finish(state.rootSpanId, "error", state.rootStartedAt, {
210
+ error: message,
211
+ metadata: {
212
+ ...state.rootMetadata,
213
+ failedAt: (/* @__PURE__ */ new Date()).toISOString()
214
+ }
215
+ });
216
+ throw new Error(message);
217
+ }
184
218
  const originalWriter = task.writer;
185
219
  observedTask.writer = (chunk) => {
186
220
  const pending = this.handleWriterChunk(state, chunk).catch((error) => {
@@ -191,7 +225,7 @@ ${task.question}
191
225
  return originalWriter == null ? void 0 : originalWriter(chunk);
192
226
  };
193
227
  try {
194
- const result = await (0, import_AgentExecutionContext.runWithAgentExecutionContext)(
228
+ const rawResult = await (0, import_AgentExecutionContext.runWithAgentExecutionContext)(
195
229
  {
196
230
  rootRunId,
197
231
  spanId: state.rootSpanId ? String(state.rootSpanId) : void 0,
@@ -202,9 +236,11 @@ ${task.question}
202
236
  },
203
237
  () => this.runWithKnowledgeBaseAgentContext(employeeUsername, () => originalRun(observedTask))
204
238
  );
239
+ const result = this.spillLargeResult(state, rawResult);
205
240
  await this.flushPending(state);
241
+ const capturedOutput = this.spanOutput(state, (0, import_ctx_utils.trimText)(result, 2e4));
206
242
  await this.spanService.finish(state.rootSpanId, "success", state.rootStartedAt, {
207
- output: (0, import_ctx_utils.trimText)(result, 2e4),
243
+ ...capturedOutput !== void 0 ? { output: capturedOutput } : {},
208
244
  metadata: {
209
245
  ...state.rootMetadata,
210
246
  completedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -219,8 +255,9 @@ ${task.question}
219
255
  return result;
220
256
  } catch (error) {
221
257
  await this.flushPending(state);
258
+ const capturedError = this.spanOutput(state, (0, import_ctx_utils.trimText)(errorMessage(error), 1e4));
222
259
  await this.spanService.finish(state.rootSpanId, "error", state.rootStartedAt, {
223
- error: (0, import_ctx_utils.trimText)(errorMessage(error), 1e4),
260
+ ...capturedError !== void 0 ? { error: capturedError } : {},
224
261
  metadata: {
225
262
  ...state.rootMetadata,
226
263
  failedAt: (/* @__PURE__ */ new Date()).toISOString()
@@ -244,6 +281,59 @@ ${task.question}
244
281
  return { harnessTag: "default" };
245
282
  }
246
283
  }
284
+ // Span payload gates: inputs are captured only under 'full' sharing, outputs under 'full' or
285
+ // 'feedback-only'. Redaction scrubs secret-looking keys on whatever is captured; free text is
286
+ // deliberately left alone.
287
+ spanInput(state, input) {
288
+ const observability = state.policy.observability;
289
+ if (observability.sharing !== "full" || !observability.captureInputs) return void 0;
290
+ return observability.redactSecrets ? (0, import_harness_runtime_policy.redactSecretsIn)(input) : input;
291
+ }
292
+ spanOutput(state, output) {
293
+ const observability = state.policy.observability;
294
+ if (observability.sharing === "disabled" || !observability.captureOutputs) return void 0;
295
+ return observability.redactSecrets ? (0, import_harness_runtime_policy.redactSecretsIn)(output) : output;
296
+ }
297
+ // Resolved settings are a raw profile record plus the harnessTag marker; the marker is not a
298
+ // schema field. On any compile trouble fall back to an empty (all-default) harness so the
299
+ // safety defaults — redaction on, sharing full — still govern the spans.
300
+ compilePolicy(settings, parentRunHarness) {
301
+ var _a, _b;
302
+ const tag = typeof settings.harnessTag === "string" && settings.harnessTag.trim() ? settings.harnessTag.trim() : "default";
303
+ const { harnessTag: _harnessTag, ...rest } = settings;
304
+ try {
305
+ const layers = [];
306
+ if (parentRunHarness) {
307
+ const { sources, ...inherited } = parentRunHarness;
308
+ layers.push({ source: `run-role:${sources.join("+") || "snapshot"}`, settings: inherited });
309
+ }
310
+ layers.push({ source: `profile:${tag}`, settings: rest });
311
+ return (0, import_HarnessCompiler.compileHarness)(layers);
312
+ } catch (error) {
313
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to compile observer harness policy", error);
314
+ return (0, import_HarnessCompiler.compileHarness)([{ source: "default", settings: {} }]);
315
+ }
316
+ }
317
+ // Oversized sub-agent results are stored on disk and replaced by a head/tail preview plus the
318
+ // file path, so the parent conversation can read the full text back with its file tools.
319
+ // Best effort: a spill failure keeps the original result inline.
320
+ spillLargeResult(state, result) {
321
+ var _a, _b;
322
+ const maxInlineBytes = state.policy.context.spill.maxInlineBytes;
323
+ if (!maxInlineBytes || typeof result !== "string") return result;
324
+ try {
325
+ const spillDir = (0, import_path.resolve)(process.cwd(), "storage", "plugin-agent-orchestrator", "spills");
326
+ (0, import_fs.mkdirSync)(spillDir, { recursive: true });
327
+ const spillPath = (0, import_path.resolve)(spillDir, `${state.rootRunId}-${Date.now()}.txt`);
328
+ const replaced = (0, import_harness_runtime_policy.spilledText)(result, maxInlineBytes, spillPath);
329
+ if (!replaced) return result;
330
+ (0, import_fs.writeFileSync)(spillPath, result, "utf8");
331
+ return replaced;
332
+ } catch (error) {
333
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Sub-agent result spill failed", error);
334
+ return result;
335
+ }
336
+ }
247
337
  async safeBuildMemoryContext(options) {
248
338
  var _a, _b;
249
339
  try {
@@ -253,10 +343,12 @@ ${task.question}
253
343
  return { context: "", appliedScopes: [], chars: 0 };
254
344
  }
255
345
  }
256
- async safeCreateRootSpan(state, question) {
346
+ async safeCreateRootSpan(state, question, delegationInfo) {
257
347
  const span = await this.spanService.create({
258
348
  rootRunId: state.rootRunId,
259
- parentSpanId: void 0,
349
+ parentSpanId: delegationInfo.parentSpanId,
350
+ depth: delegationInfo.depth,
351
+ agentLoopRunId: delegationInfo.agentLoopRunId,
260
352
  source: NATIVE_SOURCE,
261
353
  parentSessionId: state.parentSessionId,
262
354
  subSessionId: state.subSessionId,
@@ -267,11 +359,11 @@ ${task.question}
267
359
  employeeUsername: state.employeeUsername,
268
360
  toolName: "dispatch-sub-agent-task",
269
361
  title: `${state.leaderUsername || "main"} -> ${state.employeeUsername || "sub-agent"}`,
270
- input: {
362
+ input: this.spanInput(state, {
271
363
  question,
272
364
  parentSessionId: state.parentSessionId,
273
365
  subSessionId: state.subSessionId
274
- },
366
+ }),
275
367
  metadata: state.rootMetadata,
276
368
  userId: state.userId
277
369
  });
@@ -306,6 +398,7 @@ ${task.question}
306
398
  }
307
399
  }
308
400
  async handleBeforeToolCall(state, chunk) {
401
+ if (state.policy.observability.sharing === "disabled") return;
309
402
  const body = chunkBody(chunk);
310
403
  const toolCall = (0, import_ctx_utils.asObject)(body.toolCall);
311
404
  const toolCallId = normalizeString(toolCall.id);
@@ -331,7 +424,7 @@ ${task.question}
331
424
  employeeUsername: normalizeString(conversation.username) || state.employeeUsername,
332
425
  toolName,
333
426
  title: toolName || "tool call",
334
- input: (0, import_ctx_utils.asObject)(toolCall.args),
427
+ input: this.spanInput(state, (0, import_ctx_utils.asObject)(toolCall.args)),
335
428
  metadata: {
336
429
  source: NATIVE_SOURCE,
337
430
  currentConversation: conversation,
@@ -363,8 +456,8 @@ ${task.question}
363
456
  status,
364
457
  endedAt: /* @__PURE__ */ new Date(),
365
458
  durationMs,
366
- output: forceError ? void 0 : (0, import_ctx_utils.trimText)(output, 2e4),
367
- error: forceError ? (0, import_ctx_utils.trimText)(errorMessage(error), 1e4) : void 0,
459
+ output: forceError ? void 0 : this.spanOutput(state, (0, import_ctx_utils.trimText)(output, 2e4)),
460
+ error: forceError ? this.spanOutput(state, (0, import_ctx_utils.trimText)(errorMessage(error), 1e4)) : void 0,
368
461
  skillExecutionId,
369
462
  metadata: {
370
463
  source: NATIVE_SOURCE,
@@ -400,20 +493,69 @@ ${task.question}
400
493
  const values = ((_c = (_b = (_a = task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values) || {};
401
494
  return normalizeString(values.sessionId) || void 0;
402
495
  }
403
- async resolveLeaderUsername(ctx, parentSessionId) {
404
- var _a, _b, _c, _d, _e;
496
+ leaderUsernameFor(ctx, parentConversation) {
497
+ var _a, _b;
405
498
  const values = ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || {};
406
499
  const direct = normalizeString(values.aiEmployeeUsername) || normalizeString((0, import_ctx_utils.asObject)(values.aiEmployee).username);
407
- if (direct) return direct;
408
- if (!parentSessionId) return void 0;
500
+ return direct || normalizeString(readValue(parentConversation, "aiEmployeeUsername")) || void 0;
501
+ }
502
+ async safeFindParentConversation(ctx, parentSessionId) {
503
+ var _a, _b, _c;
504
+ if (!parentSessionId) return null;
409
505
  try {
410
- const repo = (_d = (_c = ctx.db) == null ? void 0 : _c.getRepository) == null ? void 0 : _d.call(_c, "aiConversations");
411
- const conversation = await ((_e = repo == null ? void 0 : repo.findOne) == null ? void 0 : _e.call(repo, {
412
- filter: { sessionId: parentSessionId }
413
- }));
414
- return normalizeString(readValue(conversation, "aiEmployeeUsername")) || void 0;
506
+ const repo = (_b = (_a = ctx.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "aiConversations");
507
+ const conversation = await ((_c = repo == null ? void 0 : repo.findOne) == null ? void 0 : _c.call(repo, { filter: { sessionId: parentSessionId } }));
508
+ return conversation || null;
415
509
  } catch {
416
- return void 0;
510
+ return null;
511
+ }
512
+ }
513
+ controlPlaneRunIdOf(conversation) {
514
+ const runId = Number((0, import_ctx_utils.asObject)(readValue(conversation, "options")).controlPlaneRunId);
515
+ return Number.isSafeInteger(runId) && runId > 0 ? runId : void 0;
516
+ }
517
+ async safeResolveParentRunHarness(runId, parentUsername) {
518
+ var _a, _b;
519
+ if (!parentUsername) return null;
520
+ try {
521
+ return await (0, import_harness_runtime_policy.resolveRunRoleHarness)(this.plugin.db, runId, parentUsername);
522
+ } catch (error) {
523
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to resolve parent run harness for delegation", error);
524
+ return null;
525
+ }
526
+ }
527
+ // The parent's persisted span is the authoritative depth source: it was recorded when the
528
+ // parent itself was dispatched, so a resumed child arrives with its true depth even though its
529
+ // in-process context is fresh. The runtime context can only confirm or deepen the count, never
530
+ // lower it.
531
+ async resolveDelegationContext(parentSessionId) {
532
+ var _a;
533
+ const candidates = [];
534
+ const context = (0, import_AgentExecutionContext.getAgentExecutionContext)();
535
+ if (context == null ? void 0 : context.spanId) {
536
+ const span = await this.safeFindSpan({ filterByTk: context.spanId });
537
+ if (span) candidates.push(span);
538
+ }
539
+ if (parentSessionId) {
540
+ const span = await this.safeFindSpan({
541
+ filter: { subSessionId: parentSessionId, type: "sub_agent" },
542
+ sort: ["-id"]
543
+ });
544
+ if (span) candidates.push(span);
545
+ }
546
+ const depth = candidates.reduce((deepest, span) => Math.max(deepest, Number(span.depth) || 0), 0);
547
+ const parentSpanId = (_a = candidates.find((span) => span.id !== void 0)) == null ? void 0 : _a.id;
548
+ return { parentSpanId: parentSpanId === void 0 ? void 0 : String(parentSpanId), depth };
549
+ }
550
+ async safeFindSpan(options) {
551
+ var _a, _b;
552
+ try {
553
+ const repo = this.plugin.db.getRepository("agentExecutionSpans");
554
+ if (!repo || typeof repo.findOne !== "function") return null;
555
+ return await repo.findOne(options) || null;
556
+ } catch (error) {
557
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to resolve delegation parent span", error);
558
+ return null;
417
559
  }
418
560
  }
419
561
  async resolveDispatchToolMessage(ctx, parentSessionId, subSessionId) {
@@ -74,7 +74,7 @@ function askIsEnforceable(entry) {
74
74
  }
75
75
  async function planHarnessTools(app, harness, discovery) {
76
76
  const toolsManager = (0, import_ai_manager.getAIToolsManager)(app);
77
- const candidates = Array.from(/* @__PURE__ */ new Set([...harness.tools.allow, ...harness.tools.ask]));
77
+ const candidates = Array.from(/* @__PURE__ */ new Set([...harness.tools.allow, ...harness.tools.ask, ...harness.tools.escalate]));
78
78
  const plan = { filter: [], employeeTools: [], withheld: [], blockedSystemTools: [] };
79
79
  const filter = discovery ? { ctx: discovery.ctx, sessionId: discovery.sessionId } : void 0;
80
80
  for (const name of candidates.sort()) {
@@ -137,12 +137,23 @@ class PluginAiRuntimeAdapter {
137
137
  }
138
138
  // Resume mirrors the official workflow employee node: flip the persisted tool call to
139
139
  // `waiting` with a decision, then re-invoke so plugin-ai resumes its own checkpoint.
140
+ // Decisions are per tool call: plugin-ai stores one `userDecision` per interrupted row and
141
+ // `getUserDecisions` only unblocks once every interrupted call of the message has one.
140
142
  async resume(input) {
141
143
  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
- );
144
+ for (const entry of input.decisions) {
145
+ await this.app.db.getModel("aiToolMessages").update(
146
+ { userDecision: entry.decision, invokeStatus: "waiting" },
147
+ {
148
+ where: {
149
+ sessionId: input.sessionId,
150
+ messageId: input.messageId,
151
+ toolCallId: entry.toolCallId,
152
+ invokeStatus: "interrupted"
153
+ }
154
+ }
155
+ );
156
+ }
146
157
  const userDecisions = await plugin.aiConversationsManager.getUserDecisions(input.messageId);
147
158
  if (!userDecisions) throw new Error("The interrupted tool calls are not all ready to resume.");
148
159
  const { aiEmployee } = await this.buildEmployee(input);
@@ -0,0 +1,210 @@
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 ToolLoopDetectionService_exports = {};
28
+ __export(ToolLoopDetectionService_exports, {
29
+ ToolLoopDetectionService: () => ToolLoopDetectionService,
30
+ countToolRepetitions: () => countToolRepetitions,
31
+ toolCallSignature: () => toolCallSignature,
32
+ toolLoopLevel: () => toolLoopLevel,
33
+ toolLoopNotice: () => toolLoopNotice,
34
+ toolLoopReason: () => toolLoopReason
35
+ });
36
+ module.exports = __toCommonJS(ToolLoopDetectionService_exports);
37
+ var import_node_crypto = require("node:crypto");
38
+ var import_RunEventBus = require("./RunEventBus");
39
+ function read(record, key) {
40
+ const model = record;
41
+ return typeof model.get === "function" ? model.get(key) : record[key];
42
+ }
43
+ function asObject(value) {
44
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
45
+ }
46
+ function canonicalize(value) {
47
+ if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
48
+ if (value && typeof value === "object") {
49
+ const source = value;
50
+ const ordered = {};
51
+ for (const key of Object.keys(source).sort()) ordered[key] = canonicalize(source[key]);
52
+ return ordered;
53
+ }
54
+ return value;
55
+ }
56
+ const NAME_ARGS_SEPARATOR = String.fromCharCode(0);
57
+ function toolCallSignature(name, args) {
58
+ return (0, import_node_crypto.createHash)("sha256").update(name + NAME_ARGS_SEPARATOR + JSON.stringify(canonicalize(args ?? null))).digest("hex");
59
+ }
60
+ function countToolRepetitions(calls) {
61
+ const counts = /* @__PURE__ */ new Map();
62
+ for (const call of calls) {
63
+ if (!call.name) continue;
64
+ const signature = toolCallSignature(call.name, call.args);
65
+ const entry = counts.get(signature) ?? {
66
+ toolName: call.name,
67
+ signature,
68
+ count: 0,
69
+ sampleArgs: asObject(call.args)
70
+ };
71
+ entry.count += 1;
72
+ counts.set(signature, entry);
73
+ }
74
+ return counts;
75
+ }
76
+ function toolLoopLevel(count, detection) {
77
+ if (!detection.enabled) return "none";
78
+ if (count >= detection.escalateAt) return "escalate";
79
+ if (count >= detection.blockAt) return "block";
80
+ if (count >= detection.warnAt) return "warn";
81
+ return "none";
82
+ }
83
+ function toolLoopReason(finding) {
84
+ return `Tool loop detected: "${finding.toolName}" was invoked ${finding.count} times with identical arguments.`;
85
+ }
86
+ function toolLoopNotice(toolName, count) {
87
+ return [
88
+ "<tool_loop_warning>",
89
+ `An earlier pass of this run invoked the tool "${toolName}" with identical arguments ${count} times.`,
90
+ "Do not repeat this pattern. If the tool did not return what you expected, change your approach or report the blocker explicitly instead of retrying the same call.",
91
+ "</tool_loop_warning>"
92
+ ].join("\n");
93
+ }
94
+ class ToolLoopDetectionService {
95
+ constructor(database) {
96
+ this.database = database;
97
+ }
98
+ // Scans every tool call the run has issued so far (across all pass sessions, which are linked
99
+ // through agentLoopSteps.sessionId) and returns the most repeated signature once it crosses the
100
+ // policy's warn threshold. Returns null while the run stays under every threshold.
101
+ async scanRun(runId, policy) {
102
+ const detection = policy.loopDetection;
103
+ if (!detection.enabled) return null;
104
+ const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
105
+ const sessionIds = /* @__PURE__ */ new Set();
106
+ for (const step of steps) {
107
+ const sessionId = read(step, "sessionId");
108
+ if (typeof sessionId === "string" && sessionId) sessionIds.add(sessionId);
109
+ }
110
+ if (!sessionIds.size) return null;
111
+ const messages = await this.database.getRepository("aiMessages").find({
112
+ filter: { sessionId: { $in: [...sessionIds] } }
113
+ });
114
+ const calls = [];
115
+ for (const message of messages) {
116
+ const toolCalls = read(message, "toolCalls");
117
+ if (!Array.isArray(toolCalls)) continue;
118
+ for (const toolCall of toolCalls) {
119
+ const entry = asObject(toolCall);
120
+ if (typeof entry.name === "string" && entry.name) calls.push({ name: entry.name, args: entry.args });
121
+ }
122
+ }
123
+ if (!calls.length) return null;
124
+ let worst = null;
125
+ for (const entry of countToolRepetitions(calls).values()) {
126
+ const level = toolLoopLevel(entry.count, detection);
127
+ if (level === "none") continue;
128
+ if (!worst || entry.count > worst.count) worst = { level, ...entry };
129
+ }
130
+ return worst;
131
+ }
132
+ // Persists the guard step and event for a finding, deduplicated by signature so a run records
133
+ // each loop once no matter how many subsequent passes observe it. Returns true when a new
134
+ // record was created.
135
+ async recordFinding(context, finding) {
136
+ const steps = this.database.getRepository("agentLoopSteps");
137
+ const existing = await steps.findOne({
138
+ filter: { runId: context.runId, kind: "guard", inputHash: finding.signature }
139
+ });
140
+ if (existing) return false;
141
+ const now = /* @__PURE__ */ new Date();
142
+ const runSteps = await steps.find({ filter: { runId: context.runId } });
143
+ const step = await steps.create({
144
+ values: {
145
+ runId: context.runId,
146
+ runtimeVersion: "control-plane-v2",
147
+ sequence: runSteps.length,
148
+ role: context.role,
149
+ kind: "guard",
150
+ type: "tool_loop",
151
+ employeeUsername: context.username,
152
+ toolName: finding.toolName,
153
+ inputHash: finding.signature,
154
+ title: `Tool loop ${finding.level}: ${finding.toolName} x${finding.count}`,
155
+ description: toolLoopReason(finding),
156
+ status: "succeeded",
157
+ metadata: { level: finding.level, count: finding.count, sampleArgs: finding.sampleArgs },
158
+ startedAt: now,
159
+ endedAt: now,
160
+ createdAt: now
161
+ }
162
+ });
163
+ const event = await this.database.getRepository("agentLoopEvents").create({
164
+ values: {
165
+ runId: context.runId,
166
+ stepId: read(step, "id"),
167
+ type: "tool_loop_detected",
168
+ title: `Tool loop ${finding.level}: ${finding.toolName}`,
169
+ content: toolLoopReason(finding),
170
+ status: context.runStatus,
171
+ payload: {
172
+ level: finding.level,
173
+ toolName: finding.toolName,
174
+ count: finding.count,
175
+ signature: finding.signature
176
+ },
177
+ actorType: context.actorType,
178
+ actorIdentity: context.actorIdentity,
179
+ correlationKey: `tool-loop:${finding.signature}`,
180
+ createdAt: now
181
+ }
182
+ });
183
+ (0, import_RunEventBus.getRunEventBus)().emit(context.runId, typeof event.toJSON === "function" ? event.toJSON() : event);
184
+ return true;
185
+ }
186
+ // Rebuilds the model-facing notices from guard steps recorded before the current worker claim,
187
+ // so a run that parked and resumed keeps warning later roles about an earlier loop.
188
+ async existingNotices(runId) {
189
+ const steps = await this.database.getRepository("agentLoopSteps").find({
190
+ filter: { runId, kind: "guard" }
191
+ });
192
+ const notices = [];
193
+ for (const step of steps) {
194
+ const toolName = String(read(step, "toolName") || "");
195
+ const count = Number(asObject(read(step, "metadata")).count) || 0;
196
+ if (!toolName || !count) continue;
197
+ notices.push(toolLoopNotice(toolName, count));
198
+ }
199
+ return notices;
200
+ }
201
+ }
202
+ // Annotate the CommonJS export names for ESM import in node:
203
+ 0 && (module.exports = {
204
+ ToolLoopDetectionService,
205
+ countToolRepetitions,
206
+ toolCallSignature,
207
+ toolLoopLevel,
208
+ toolLoopNotice,
209
+ toolLoopReason
210
+ });
@@ -29,6 +29,7 @@ __export(VerificationService_exports, {
29
29
  VerificationService: () => VerificationService
30
30
  });
31
31
  module.exports = __toCommonJS(VerificationService_exports);
32
+ var import_ToolLoopDetectionService = require("./ToolLoopDetectionService");
32
33
  var import_VerificationSchema = require("./VerificationSchema");
33
34
  function read(record, key) {
34
35
  const model = record;
@@ -58,6 +59,7 @@ function verifierPrompt(input, artifacts) {
58
59
  "",
59
60
  `Required checks: ${input.policy.verification.requiredChecks.join(", ")}`,
60
61
  "",
62
+ ...input.loopNotices ?? [],
61
63
  "Reply with a single JSON object and nothing else:",
62
64
  '{"verdict":"pass|reject|escalate","summary":"...","checks":[{"name":"...","status":"pass|fail|skipped",',
63
65
  '"evidenceArtifactIds":[<artifact ids from the list above>]}],"residualRisks":["..."]}',
@@ -70,11 +72,17 @@ class VerificationService {
70
72
  this.database = database;
71
73
  this.runtime = runtime;
72
74
  this.stateMachine = stateMachine;
75
+ this.loopGuard = new import_ToolLoopDetectionService.ToolLoopDetectionService(database);
73
76
  }
77
+ loopGuard;
74
78
  async verifyAndFinalize(input) {
75
79
  this.assertIndependentVerifier(input);
76
80
  const artifacts = await this.runArtifacts(input.runId);
77
81
  const verdict = await this.collectVerdict(input, artifacts);
82
+ const guard = await this.enforceToolLoopGuard(input);
83
+ if (guard === "halt") {
84
+ return { verdict, finalStatus: "halted" };
85
+ }
78
86
  await this.assertEvidenceBelongsToRun(verdict, artifacts, input.verifierUsername);
79
87
  const finalStatus = this.finalStatusFor(verdict, input.autonomyLevel);
80
88
  await this.stateMachine.transition({
@@ -102,6 +110,40 @@ class VerificationService {
102
110
  throw new Error("The verifier must be a different employee from the leader and every maker.");
103
111
  }
104
112
  }
113
+ async enforceToolLoopGuard(input) {
114
+ const finding = await this.loopGuard.scanRun(input.runId, input.policy);
115
+ if (!finding) return "continue";
116
+ await this.loopGuard.recordFinding(
117
+ {
118
+ runId: input.runId,
119
+ role: "verifier",
120
+ username: input.verifierUsername,
121
+ runStatus: "verifying",
122
+ actorType: "worker",
123
+ actorIdentity: input.workerId
124
+ },
125
+ finding
126
+ );
127
+ if (finding.level === "warn") return "continue";
128
+ const reason = (0, import_ToolLoopDetectionService.toolLoopReason)(finding);
129
+ await this.stateMachine.transition({
130
+ runId: input.runId,
131
+ to: finding.level === "block" ? "blocked" : "waiting_human",
132
+ actorType: "worker",
133
+ actorIdentity: input.workerId,
134
+ leaseToken: input.leaseToken,
135
+ eventType: finding.level === "block" ? "run_blocked" : "run_escalated",
136
+ title: finding.level === "block" ? "Run blocked by tool loop detection" : "Run escalated by tool loop detection",
137
+ content: reason,
138
+ correlationKey: `tool-loop-${finding.level}:${input.runId}:${finding.signature}`,
139
+ values: finding.level === "block" ? { blockedReason: reason } : { escalationReason: reason }
140
+ });
141
+ return "halt";
142
+ }
143
+ async nextSequence(runId) {
144
+ const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
145
+ return steps.length;
146
+ }
105
147
  async collectVerdict(input, artifacts) {
106
148
  const sessionId = await this.runtime.createConversation({
107
149
  username: input.verifierUsername,
@@ -109,6 +151,22 @@ class VerificationService {
109
151
  runId: input.runId,
110
152
  title: `Verification of run ${input.runId}`
111
153
  });
154
+ const step = await this.database.getRepository("agentLoopSteps").create({
155
+ values: {
156
+ runId: input.runId,
157
+ runtimeVersion: "control-plane-v2",
158
+ sequence: await this.nextSequence(input.runId),
159
+ role: "verifier",
160
+ kind: "invocation",
161
+ type: "verification",
162
+ employeeUsername: input.verifierUsername,
163
+ sessionId,
164
+ title: "verifier invocation",
165
+ status: "running",
166
+ startedAt: /* @__PURE__ */ new Date(),
167
+ createdAt: /* @__PURE__ */ new Date()
168
+ }
169
+ });
112
170
  const outcome = await this.runtime.invoke({
113
171
  username: input.verifierUsername,
114
172
  sessionId,
@@ -118,6 +176,14 @@ class VerificationService {
118
176
  prompt: verifierPrompt(input, artifacts),
119
177
  signal: input.signal
120
178
  });
179
+ await this.database.getRepository("agentLoopSteps").update({
180
+ filterByTk: read(step, "id"),
181
+ values: {
182
+ status: "succeeded",
183
+ output: { content: outcome.content },
184
+ endedAt: /* @__PURE__ */ new Date()
185
+ }
186
+ });
121
187
  if (outcome.interrupted.length) {
122
188
  throw new Error("The verifier requested an approval-gated tool; verification cannot complete.");
123
189
  }