plugin-agent-orchestrator 1.1.6 → 1.1.8

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 (70) hide show
  1. package/dist/client/index.js +1 -1
  2. package/dist/client-v2/index.js +1 -1
  3. package/dist/externalVersion.js +7 -7
  4. package/dist/server/collections/agent-loop-runs.js +6 -0
  5. package/dist/server/collections/skill-metrics.js +66 -0
  6. package/dist/server/plugin.js +91 -2
  7. package/dist/server/resources/agent-loop-events-stream.js +1 -0
  8. package/dist/server/resources/agent-loop.js +1 -1
  9. package/dist/server/services/DurableCircuitBreakerService.js +9 -12
  10. package/dist/server/services/ExecutionSpanService.js +8 -3
  11. package/dist/server/services/HarnessProfileService.js +23 -26
  12. package/dist/server/services/LoopBudgetService.js +36 -39
  13. package/dist/server/services/LoopControlService.js +8 -11
  14. package/dist/server/services/LoopPatternSchema.js +51 -17
  15. package/dist/server/services/LoopPatternService.js +31 -11
  16. package/dist/server/services/LoopRunRepository.js +2 -5
  17. package/dist/server/services/LoopRunStateMachine.js +31 -34
  18. package/dist/server/services/LoopSchedulerService.js +4 -7
  19. package/dist/server/services/LoopTriggerService.js +11 -6
  20. package/dist/server/services/LoopWorkerService.js +88 -22
  21. package/dist/server/services/PathLockService.js +19 -22
  22. package/dist/server/services/PluginAiRuntimeAdapter.js +51 -8
  23. package/dist/server/services/RunEventBus.js +14 -2
  24. package/dist/server/services/SkillAccessService.js +50 -1
  25. package/dist/server/services/TokenTracker.js +17 -1
  26. package/dist/server/services/ToolLoopDetectionService.js +14 -17
  27. package/dist/server/services/VerificationService.js +47 -16
  28. package/dist/server/services/harness-runtime-policy.js +7 -12
  29. package/dist/server/skill-hub/plugin.js +34 -27
  30. package/dist/server/utils/ha-lock.js +73 -0
  31. package/dist/server/utils/loop-pattern-context.js +42 -5
  32. package/dist/server/utils/record-utils.js +44 -0
  33. package/package.json +1 -1
  34. package/src/client/OrchestratorSettings.tsx +2 -2
  35. package/src/client/plugin.tsx +2 -1
  36. package/src/client-v2/plugin.tsx +26 -13
  37. package/src/server/__tests__/tool-loop-detection.test.ts +1 -0
  38. package/src/server/collections/agent-loop-runs.ts +7 -0
  39. package/src/server/collections/skill-metrics.ts +36 -0
  40. package/src/server/plugin.ts +117 -1
  41. package/src/server/resources/agent-loop-events-stream.ts +108 -105
  42. package/src/server/resources/agent-loop.ts +1 -1
  43. package/src/server/resources/tracing.ts +267 -266
  44. package/src/server/services/DurableCircuitBreakerService.ts +235 -239
  45. package/src/server/services/ExecutionSpanService.ts +37 -12
  46. package/src/server/services/HarnessProfileService.ts +1 -5
  47. package/src/server/services/LoopBudgetService.ts +271 -275
  48. package/src/server/services/LoopControlService.ts +120 -124
  49. package/src/server/services/LoopPatternSchema.ts +60 -14
  50. package/src/server/services/LoopPatternService.ts +171 -143
  51. package/src/server/services/LoopRunRepository.ts +1 -5
  52. package/src/server/services/LoopRunStateMachine.ts +1 -5
  53. package/src/server/services/LoopSchedulerService.ts +195 -199
  54. package/src/server/services/LoopTriggerService.ts +7 -5
  55. package/src/server/services/LoopWorkerService.ts +102 -12
  56. package/src/server/services/PathLockService.ts +317 -321
  57. package/src/server/services/PluginAiRuntimeAdapter.ts +59 -4
  58. package/src/server/services/RunEventBus.ts +13 -0
  59. package/src/server/services/SkillAccessService.ts +80 -5
  60. package/src/server/services/TokenTracker.ts +59 -7
  61. package/src/server/services/ToolLoopDetectionService.ts +8 -11
  62. package/src/server/services/VerificationSchema.ts +31 -31
  63. package/src/server/services/VerificationService.ts +60 -11
  64. package/src/server/services/harness-runtime-policy.ts +2 -9
  65. package/src/server/skill-hub/plugin.ts +36 -28
  66. package/src/server/types.ts +5 -39
  67. package/src/server/utils/ensure-indexes.ts +96 -96
  68. package/src/server/utils/ha-lock.ts +80 -0
  69. package/src/server/utils/loop-pattern-context.ts +84 -20
  70. package/src/server/utils/record-utils.ts +19 -0
@@ -27,6 +27,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
27
27
  var TokenTracker_exports = {};
28
28
  __export(TokenTracker_exports, {
29
29
  TokenTracker: () => TokenTracker,
30
+ estimateCost: () => estimateCost,
30
31
  extractTokenUsage: () => extractTokenUsage
31
32
  });
32
33
  module.exports = __toCommonJS(TokenTracker_exports);
@@ -105,7 +106,9 @@ class TokenTracker {
105
106
  const spansRepo = this.db.getRepository("agentExecutionSpans");
106
107
  if (!spansRepo) return;
107
108
  const spans = await spansRepo.find({
108
- filter: { "metadata.agentLoopRunId": String(runId) }
109
+ filter: { agentLoopRunId: String(runId) },
110
+ fields: ["inputTokens", "outputTokens", "cost"],
111
+ limit: 1e4
109
112
  });
110
113
  let totalInput = 0;
111
114
  let totalOutput = 0;
@@ -165,6 +168,18 @@ class TokenTracker {
165
168
  return { allowed: true };
166
169
  }
167
170
  }
171
+ /**
172
+ * Track actual token usage from the LLM response on a span.
173
+ * This is preferred over estimateAndTrack when the LLM provides real usage metadata.
174
+ * Falls back to estimation if usage is null.
175
+ */
176
+ async trackActualUsage(spanId, tokenUsage, input, output, runId) {
177
+ if (tokenUsage && tokenUsage.totalTokens > 0) {
178
+ await this.trackSpan(spanId, tokenUsage, runId);
179
+ return;
180
+ }
181
+ await this.estimateAndTrack(spanId, input, output, runId);
182
+ }
168
183
  /**
169
184
  * Estimate tokens from text length and track on a span.
170
185
  * Rough heuristic: ~4 chars per token for English text.
@@ -189,5 +204,6 @@ class TokenTracker {
189
204
  // Annotate the CommonJS export names for ESM import in node:
190
205
  0 && (module.exports = {
191
206
  TokenTracker,
207
+ estimateCost,
192
208
  extractTokenUsage
193
209
  });
@@ -34,15 +34,10 @@ __export(ToolLoopDetectionService_exports, {
34
34
  toolLoopReason: () => toolLoopReason
35
35
  });
36
36
  module.exports = __toCommonJS(ToolLoopDetectionService_exports);
37
+ var import_ctx_utils = require("../utils/ctx-utils");
37
38
  var import_node_crypto = require("node:crypto");
38
39
  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
- }
40
+ var import_record_utils = require("../utils/record-utils");
46
41
  function canonicalize(value) {
47
42
  if (Array.isArray(value)) return value.map((entry) => canonicalize(entry));
48
43
  if (value && typeof value === "object") {
@@ -66,7 +61,7 @@ function countToolRepetitions(calls) {
66
61
  toolName: call.name,
67
62
  signature,
68
63
  count: 0,
69
- sampleArgs: asObject(call.args)
64
+ sampleArgs: (0, import_ctx_utils.asObject)(call.args)
70
65
  };
71
66
  entry.count += 1;
72
67
  counts.set(signature, entry);
@@ -104,19 +99,21 @@ class ToolLoopDetectionService {
104
99
  const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
105
100
  const sessionIds = /* @__PURE__ */ new Set();
106
101
  for (const step of steps) {
107
- const sessionId = read(step, "sessionId");
102
+ const sessionId = (0, import_record_utils.read)(step, "sessionId");
108
103
  if (typeof sessionId === "string" && sessionId) sessionIds.add(sessionId);
109
104
  }
110
105
  if (!sessionIds.size) return null;
111
106
  const messages = await this.database.getRepository("aiMessages").find({
112
- filter: { sessionId: { $in: [...sessionIds] } }
107
+ filter: { sessionId: { $in: [...sessionIds] } },
108
+ fields: ["toolCalls"],
109
+ limit: 5e3
113
110
  });
114
111
  const calls = [];
115
112
  for (const message of messages) {
116
- const toolCalls = read(message, "toolCalls");
113
+ const toolCalls = (0, import_record_utils.read)(message, "toolCalls");
117
114
  if (!Array.isArray(toolCalls)) continue;
118
115
  for (const toolCall of toolCalls) {
119
- const entry = asObject(toolCall);
116
+ const entry = (0, import_ctx_utils.asObject)(toolCall);
120
117
  if (typeof entry.name === "string" && entry.name) calls.push({ name: entry.name, args: entry.args });
121
118
  }
122
119
  }
@@ -139,12 +136,12 @@ class ToolLoopDetectionService {
139
136
  });
140
137
  if (existing) return false;
141
138
  const now = /* @__PURE__ */ new Date();
142
- const runSteps = await steps.find({ filter: { runId: context.runId } });
139
+ const stepCount = await steps.count({ filter: { runId: context.runId } });
143
140
  const step = await steps.create({
144
141
  values: {
145
142
  runId: context.runId,
146
143
  runtimeVersion: "control-plane-v2",
147
- sequence: runSteps.length,
144
+ sequence: stepCount,
148
145
  role: context.role,
149
146
  kind: "guard",
150
147
  type: "tool_loop",
@@ -163,7 +160,7 @@ class ToolLoopDetectionService {
163
160
  const event = await this.database.getRepository("agentLoopEvents").create({
164
161
  values: {
165
162
  runId: context.runId,
166
- stepId: read(step, "id"),
163
+ stepId: (0, import_record_utils.read)(step, "id"),
167
164
  type: "tool_loop_detected",
168
165
  title: `Tool loop ${finding.level}: ${finding.toolName}`,
169
166
  content: toolLoopReason(finding),
@@ -191,8 +188,8 @@ class ToolLoopDetectionService {
191
188
  });
192
189
  const notices = [];
193
190
  for (const step of steps) {
194
- const toolName = String(read(step, "toolName") || "");
195
- const count = Number(asObject(read(step, "metadata")).count) || 0;
191
+ const toolName = String((0, import_record_utils.read)(step, "toolName") || "");
192
+ const count = Number((0, import_ctx_utils.asObject)((0, import_record_utils.read)(step, "metadata")).count) || 0;
196
193
  if (!toolName || !count) continue;
197
194
  notices.push(toolLoopNotice(toolName, count));
198
195
  }
@@ -31,10 +31,7 @@ __export(VerificationService_exports, {
31
31
  module.exports = __toCommonJS(VerificationService_exports);
32
32
  var import_ToolLoopDetectionService = require("./ToolLoopDetectionService");
33
33
  var import_VerificationSchema = require("./VerificationSchema");
34
- function read(record, key) {
35
- const model = record;
36
- return typeof model.get === "function" ? model.get(key) : record[key];
37
- }
34
+ var import_record_utils = require("../utils/record-utils");
38
35
  function extractVerdictObject(content) {
39
36
  const fenced = content.match(/```(?:json)?\s*([\s\S]*?)```/i);
40
37
  const candidate = fenced ? fenced[1] : content;
@@ -45,7 +42,33 @@ function extractVerdictObject(content) {
45
42
  }
46
43
  return JSON.parse(candidate.slice(start, end + 1));
47
44
  }
48
- function verifierPrompt(input, artifacts) {
45
+ function dynamicChecksFor(input) {
46
+ var _a, _b;
47
+ const config = input.policy.verification.dynamicChecks;
48
+ if (!config) return [];
49
+ const extra = [];
50
+ const affectedCount = ((_a = input.actingOn) == null ? void 0 : _a.length) ?? 0;
51
+ if (affectedCount >= config.codeChangeThreshold) {
52
+ extra.push("broad_change_review");
53
+ }
54
+ if (config.riskPathPatterns.length > 0 && ((_b = input.actingOn) == null ? void 0 : _b.length)) {
55
+ const hasRiskPath = input.actingOn.some(
56
+ (path) => config.riskPathPatterns.some((pattern) => path.startsWith(pattern) || path.includes(pattern))
57
+ );
58
+ if (hasRiskPath) {
59
+ extra.push("risk_path_review");
60
+ }
61
+ }
62
+ if (config.requireSecurityReview) {
63
+ extra.push("security_review");
64
+ }
65
+ if (config.requirePerformanceReview) {
66
+ extra.push("performance_review");
67
+ }
68
+ return [...new Set(extra)];
69
+ }
70
+ function verifierPrompt(input, artifacts, dynamicChecks) {
71
+ const allChecks = [.../* @__PURE__ */ new Set([...input.policy.verification.requiredChecks, ...dynamicChecks])];
49
72
  const catalogue = artifacts.length ? artifacts.map((artifact) => `- id=${artifact.id} kind=${artifact.kind} title=${artifact.title || ""}`).join("\n") : "- (none)";
50
73
  return [
51
74
  "You are the independent verifier for an autonomous run. You did not produce this work.",
@@ -57,7 +80,7 @@ function verifierPrompt(input, artifacts) {
57
80
  "Evidence artifacts recorded for this run:",
58
81
  catalogue,
59
82
  "",
60
- `Required checks: ${input.policy.verification.requiredChecks.join(", ")}`,
83
+ `Required checks: ${allChecks.join(", ")}`,
61
84
  "",
62
85
  ...input.loopNotices ?? [],
63
86
  "Reply with a single JSON object and nothing else:",
@@ -68,10 +91,11 @@ function verifierPrompt(input, artifacts) {
68
91
  ].join("\n");
69
92
  }
70
93
  class VerificationService {
71
- constructor(database, runtime, stateMachine) {
94
+ constructor(database, runtime, stateMachine, tokenTracker) {
72
95
  this.database = database;
73
96
  this.runtime = runtime;
74
97
  this.stateMachine = stateMachine;
98
+ this.tokenTracker = tokenTracker;
75
99
  this.loopGuard = new import_ToolLoopDetectionService.ToolLoopDetectionService(database);
76
100
  }
77
101
  loopGuard;
@@ -141,8 +165,7 @@ class VerificationService {
141
165
  return "halt";
142
166
  }
143
167
  async nextSequence(runId) {
144
- const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
145
- return steps.length;
168
+ return this.database.getRepository("agentLoopSteps").count({ filter: { runId } });
146
169
  }
147
170
  async collectVerdict(input, artifacts) {
148
171
  const sessionId = await this.runtime.createConversation({
@@ -173,11 +196,18 @@ class VerificationService {
173
196
  userId: input.userId,
174
197
  systemMessage: "You verify completed work against its stated goal using only recorded evidence. You never modify anything.",
175
198
  harness: input.verifierHarness,
176
- prompt: verifierPrompt(input, artifacts),
199
+ prompt: verifierPrompt(input, artifacts, dynamicChecksFor(input)),
177
200
  signal: input.signal
178
201
  });
202
+ await this.tokenTracker.trackActualUsage(
203
+ (0, import_record_utils.read)(step, "id"),
204
+ outcome.tokenUsage ?? null,
205
+ verifierPrompt(input, artifacts, dynamicChecksFor(input)),
206
+ outcome.content,
207
+ input.runId
208
+ );
179
209
  await this.database.getRepository("agentLoopSteps").update({
180
- filterByTk: read(step, "id"),
210
+ filterByTk: (0, import_record_utils.read)(step, "id"),
181
211
  values: {
182
212
  status: "succeeded",
183
213
  output: { content: outcome.content },
@@ -188,7 +218,8 @@ class VerificationService {
188
218
  throw new Error("The verifier requested an approval-gated tool; verification cannot complete.");
189
219
  }
190
220
  const verdict = (0, import_VerificationSchema.parseVerificationVerdict)(extractVerdictObject(outcome.content));
191
- const required = new Set(input.policy.verification.requiredChecks);
221
+ const dynamicChecks = dynamicChecksFor(input);
222
+ const required = /* @__PURE__ */ new Set([...input.policy.verification.requiredChecks, ...dynamicChecks]);
192
223
  for (const check of verdict.checks) required.delete(check.name);
193
224
  if (required.size) {
194
225
  throw new Error(`The verifier omitted required checks: ${Array.from(required).join(", ")}.`);
@@ -222,10 +253,10 @@ class VerificationService {
222
253
  async runArtifacts(runId) {
223
254
  const rows = await this.database.getRepository("agentLoopArtifacts").find({ filter: { runId } });
224
255
  return rows.map((row) => ({
225
- id: Number(read(row, "id")),
226
- kind: String(read(row, "kind") || ""),
227
- title: String(read(row, "title") || ""),
228
- producerUsername: String(read(row, "producerUsername") || "")
256
+ id: Number((0, import_record_utils.read)(row, "id")),
257
+ kind: String((0, import_record_utils.read)(row, "kind") || ""),
258
+ title: String((0, import_record_utils.read)(row, "title") || ""),
259
+ producerUsername: String((0, import_record_utils.read)(row, "producerUsername") || "")
229
260
  }));
230
261
  }
231
262
  }
@@ -34,28 +34,23 @@ __export(harness_runtime_policy_exports, {
34
34
  spilledText: () => spilledText
35
35
  });
36
36
  module.exports = __toCommonJS(harness_runtime_policy_exports);
37
+ var import_ctx_utils = require("../utils/ctx-utils");
37
38
  var import_HarnessCompiler = require("./HarnessCompiler");
38
39
  var import_HarnessProfileService = require("./HarnessProfileService");
39
40
  var import_HarnessSchema = require("./HarnessSchema");
40
- function read(record, key) {
41
- const model = record;
42
- return typeof (model == null ? void 0 : model.get) === "function" ? model.get(key) : model == null ? void 0 : model[key];
43
- }
44
- function asObject(value) {
45
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
46
- }
41
+ var import_record_utils = require("../utils/record-utils");
47
42
  function compiledFromSnapshot(snapshot) {
48
- const effective = asObject(asObject(snapshot).effective);
43
+ const effective = (0, import_ctx_utils.asObject)((0, import_ctx_utils.asObject)(snapshot).effective);
49
44
  if (!effective.tools) return null;
50
45
  const { sources: _sources, ...settings } = effective;
51
46
  return (0, import_HarnessCompiler.compileHarness)([{ source: "run-snapshot", settings: (0, import_HarnessSchema.parseHarnessSettings)(settings) }]);
52
47
  }
53
48
  function snapshotForEmployee(run, username) {
54
- const bindings = asObject(run.roleBindingsSnapshot);
49
+ const bindings = (0, import_ctx_utils.asObject)(run.roleBindingsSnapshot);
55
50
  if (!username) return null;
56
51
  if (bindings.leader === username) return run.leaderHarnessSnapshot;
57
52
  if (bindings.verifier === username) return run.verifierHarnessSnapshot;
58
- const makers = asObject(run.makerHarnessSnapshot);
53
+ const makers = (0, import_ctx_utils.asObject)(run.makerHarnessSnapshot);
59
54
  return makers[username] ?? null;
60
55
  }
61
56
  async function resolveRunRoleHarness(database, runId, username) {
@@ -63,7 +58,7 @@ async function resolveRunRoleHarness(database, runId, username) {
63
58
  if (!Number.isSafeInteger(runId) || runId <= 0 || !username) return null;
64
59
  const run = await database.getRepository("agentLoopRuns").findOne({ filterByTk: runId });
65
60
  if (!run) return null;
66
- const snapshot = snapshotForEmployee(asObject(((_a = run.toJSON) == null ? void 0 : _a.call(run)) ?? run), username);
61
+ const snapshot = snapshotForEmployee((0, import_ctx_utils.asObject)(((_a = run.toJSON) == null ? void 0 : _a.call(run)) ?? run), username);
67
62
  return compiledFromSnapshot(snapshot);
68
63
  }
69
64
  async function resolveTraceHarness(database, trace) {
@@ -74,7 +69,7 @@ async function resolveTraceHarness(database, trace) {
74
69
  filter: { username: trace.employeeUsername }
75
70
  });
76
71
  if (!employee) return null;
77
- const settings = asObject(read(employee, "skillSettings"));
72
+ const settings = (0, import_ctx_utils.asObject)((0, import_record_utils.read)(employee, "skillSettings"));
78
73
  const tag = typeof settings.harnessTag === "string" && settings.harnessTag.trim() ? settings.harnessTag.trim() : "default";
79
74
  const profiles = new import_HarnessProfileService.HarnessProfileService(database);
80
75
  const version = await profiles.getPublishedByTag(tag) || (tag !== "default" ? await profiles.getPublishedByTag("default") : null);
@@ -57,6 +57,7 @@ var import_git_import_request_method_policy = require("./middlewares/git-import-
57
57
  var import_json_fields = require("./utils/json-fields");
58
58
  var import_ExecutionSpanService = require("../services/ExecutionSpanService");
59
59
  var import_harness_runtime_policy = require("../services/harness-runtime-policy");
60
+ var import_ha_lock = require("../utils/ha-lock");
60
61
  var import_ai_manager = require("../utils/ai-manager");
61
62
  var import_SkillAccessService = require("../services/SkillAccessService");
62
63
  var import_InputSchemaValidator = require("../services/InputSchemaValidator");
@@ -352,17 +353,18 @@ class SkillHubSubFeature {
352
353
  return affected > 0;
353
354
  }
354
355
  startSkillTaskPoller() {
355
- var _a, _b;
356
356
  if (!shouldRunSkillSandbox() || this.skillTaskPoller) {
357
357
  return;
358
358
  }
359
- const tick = () => {
360
- this.processSkillExecutionQueue().catch((error) => {
361
- this.app.logger.warn(`[skill-hub] Pending task poll failed: ${(error == null ? void 0 : error.message) || error}`);
362
- });
359
+ const tick = async () => {
360
+ await this.processSkillExecutionQueue();
363
361
  };
364
- this.skillTaskPoller = setInterval(tick, SKILL_TASK_POLL_INTERVAL_MS);
365
- (_b = (_a = this.skillTaskPoller).unref) == null ? void 0 : _b.call(_a);
362
+ this.skillTaskPoller = (0, import_ha_lock.runWithDistributedLock)(
363
+ this.app,
364
+ "skill-hub:task-poller",
365
+ tick,
366
+ SKILL_TASK_POLL_INTERVAL_MS
367
+ );
366
368
  setTimeout(tick, 1e3);
367
369
  }
368
370
  async processSkillExecutionQueue() {
@@ -870,29 +872,34 @@ IMPORTANT: This skill is bound to a Skill Hub human-in-the-loop review template.
870
872
  startCleanupInterval() {
871
873
  if (this.cleanupInterval) return;
872
874
  const CLEANUP_INTERVAL = 60 * 60 * 1e3;
873
- this.cleanupInterval = setInterval(async () => {
874
- try {
875
- const config = await this.db.getRepository("skillWorkerConfigs").findOne();
876
- const hours = config ? config.get("retentionHours") : 24;
877
- if (hours && hours > 0) {
878
- const MAX_AGE_MS = hours * 60 * 60 * 1e3;
879
- const cutoff = new Date(Date.now() - MAX_AGE_MS);
880
- const repo = this.db.getRepository("skillExecutions");
881
- const outdated = await repo.find({
882
- filter: { createdAt: { $lt: cutoff } }
883
- });
884
- if (outdated.length > 0) {
885
- for (const record of outdated) {
886
- await record.destroy();
875
+ this.cleanupInterval = (0, import_ha_lock.runWithDistributedLock)(
876
+ this.app,
877
+ "skill-hub:cleanup",
878
+ async () => {
879
+ try {
880
+ const config = await this.db.getRepository("skillWorkerConfigs").findOne();
881
+ const hours = config ? config.get("retentionHours") : 24;
882
+ if (hours && hours > 0) {
883
+ const MAX_AGE_MS = hours * 60 * 60 * 1e3;
884
+ const cutoff = new Date(Date.now() - MAX_AGE_MS);
885
+ const repo = this.db.getRepository("skillExecutions");
886
+ const outdated = await repo.find({
887
+ filter: { createdAt: { $lt: cutoff } }
888
+ });
889
+ if (outdated.length > 0) {
890
+ for (const record of outdated) {
891
+ await record.destroy();
892
+ }
893
+ this.app.logger.info(`[skill-hub] Auto-cleaned up ${outdated.length} expired execution records`);
887
894
  }
888
- this.app.logger.info(`[skill-hub] Auto-cleaned up ${outdated.length} expired execution records`);
889
895
  }
896
+ } catch (err) {
897
+ this.app.logger.warn("[skill-hub] Auto Cleanup error:", err);
890
898
  }
891
- } catch (err) {
892
- this.app.logger.warn("[skill-hub] Auto Cleanup error:", err);
893
- }
894
- this.rateLimiter.cleanup();
895
- }, CLEANUP_INTERVAL);
899
+ this.rateLimiter.cleanup();
900
+ },
901
+ CLEANUP_INTERVAL
902
+ );
896
903
  }
897
904
  async beforeStop() {
898
905
  var _a, _b, _c, _d;
@@ -0,0 +1,73 @@
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 ha_lock_exports = {};
28
+ __export(ha_lock_exports, {
29
+ runWithDistributedLock: () => runWithDistributedLock
30
+ });
31
+ module.exports = __toCommonJS(ha_lock_exports);
32
+ function isLockAcquireError(error) {
33
+ var _a;
34
+ if (!error) return false;
35
+ if (typeof error === "object" && typeof error.constructor === "function") {
36
+ const name = (_a = error.constructor) == null ? void 0 : _a.name;
37
+ if (name === "LockAcquireError" || name === "LockAbortError") return true;
38
+ }
39
+ const message = error instanceof Error ? error.message : String(error);
40
+ return /lock (is locked|acquire timed out|acquire timeout)/i.test(message);
41
+ }
42
+ function runWithDistributedLock(app, key, task, intervalMs, ttlMs = Math.max(1e3, Math.min(intervalMs - 1, 3e5))) {
43
+ var _a;
44
+ const timer = setInterval(async () => {
45
+ var _a2, _b, _c, _d;
46
+ const lockKey = `ha:${key}`;
47
+ const lockManager = app.lockManager;
48
+ try {
49
+ if (!(lockManager == null ? void 0 : lockManager.tryAcquire)) {
50
+ await task();
51
+ return;
52
+ }
53
+ const lock = await lockManager.tryAcquire(lockKey, 0);
54
+ await lock.runExclusive(async () => {
55
+ await task();
56
+ }, ttlMs);
57
+ } catch (error) {
58
+ if (isLockAcquireError(error)) {
59
+ const message2 = error instanceof Error ? error.message : String(error);
60
+ (_b = (_a2 = app.logger) == null ? void 0 : _a2.debug) == null ? void 0 : _b.call(_a2, `[ha-lock] skipped "${key}" (${message2})`);
61
+ return;
62
+ }
63
+ const message = error instanceof Error ? error.message : String(error);
64
+ (_d = (_c = app.logger) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(_c, `[ha-lock] error on "${key}": ${message}`);
65
+ }
66
+ }, intervalMs);
67
+ (_a = timer.unref) == null ? void 0 : _a.call(timer);
68
+ return timer;
69
+ }
70
+ // Annotate the CommonJS export names for ESM import in node:
71
+ 0 && (module.exports = {
72
+ runWithDistributedLock
73
+ });
@@ -42,11 +42,48 @@ function worktreeCapability(plugin) {
42
42
  }
43
43
  function employeeHarnessResolver(plugin) {
44
44
  return async (username) => {
45
- var _a, _b;
46
- const employee = await ((_a = plugin.db.getRepository("aiEmployees")) == null ? void 0 : _a.findOne({ filter: { username } }));
47
- if (!employee) return void 0;
48
- const skillSettings = (0, import_ctx_utils.asObject)((_b = employee.get) == null ? void 0 : _b.call(employee, "skillSettings"));
49
- return skillSettings.orchestratorHarness;
45
+ var _a, _b, _c, _d, _e, _f, _g, _h;
46
+ const db = plugin.db;
47
+ try {
48
+ const employee = await ((_a = db.getRepository("aiEmployees")) == null ? void 0 : _a.findOne({ filter: { username } }));
49
+ if (employee) {
50
+ const skillSettings = (0, import_ctx_utils.asObject)((_b = employee.get) == null ? void 0 : _b.call(employee, "skillSettings"));
51
+ const directOverride = skillSettings.orchestratorHarness;
52
+ if (directOverride && typeof directOverride === "object" && Object.keys(directOverride).length > 0) {
53
+ return directOverride;
54
+ }
55
+ }
56
+ } catch {
57
+ }
58
+ try {
59
+ const config = await ((_c = db.getRepository("orchestratorConfig")) == null ? void 0 : _c.findOne({
60
+ filter: { subAgentUsername: username, enabled: true }
61
+ }));
62
+ if (config) {
63
+ const harnessTag = ((_d = config.get) == null ? void 0 : _d.call(config, "harnessTag")) || config.harnessTag;
64
+ if (typeof harnessTag === "string" && harnessTag.trim()) {
65
+ const profile = await ((_e = db.getRepository("agentHarnessProfiles")) == null ? void 0 : _e.findOne({
66
+ filter: { tag: harnessTag.trim(), enabled: true }
67
+ }));
68
+ if (profile) {
69
+ const currentVersionId = Number(((_f = profile.get) == null ? void 0 : _f.call(profile, "currentVersionId")) || 0);
70
+ if (currentVersionId > 0) {
71
+ const version = await ((_g = db.getRepository("agentHarnessProfileVersions")) == null ? void 0 : _g.findOne({
72
+ filter: { id: currentVersionId, status: "published" }
73
+ }));
74
+ if (version) {
75
+ const settings = (_h = version.get) == null ? void 0 : _h.call(version, "settings");
76
+ if (settings && typeof settings === "object" && Object.keys(settings).length > 0) {
77
+ return settings;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ } catch {
85
+ }
86
+ return void 0;
50
87
  };
51
88
  }
52
89
  // Annotate the CommonJS export names for ESM import in node:
@@ -0,0 +1,44 @@
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 record_utils_exports = {};
28
+ __export(record_utils_exports, {
29
+ asRecord: () => asRecord,
30
+ read: () => read
31
+ });
32
+ module.exports = __toCommonJS(record_utils_exports);
33
+ function read(record, key) {
34
+ const model = record;
35
+ return typeof (model == null ? void 0 : model.get) === "function" ? model.get(key) : model == null ? void 0 : model[key];
36
+ }
37
+ function asRecord(value) {
38
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
39
+ }
40
+ // Annotate the CommonJS export names for ESM import in node:
41
+ 0 && (module.exports = {
42
+ asRecord,
43
+ read
44
+ });
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "displayName.zh-CN": "代理协调器",
5
5
  "displayName.vi-VN": "Điều phối Agent",
6
6
  "description": "Native AI Employee sub-agent monitoring, policy, and memory context layer for NocoBase plugin-ai.",
7
- "version": "1.1.6",
7
+ "version": "1.1.8",
8
8
  "license": "Apache-2.0",
9
9
  "main": "dist/server/index.js",
10
10
  "keywords": [
@@ -25,12 +25,12 @@ import { AIEmployeesProvider } from '../client-v2/components/AIEmployeesContext'
25
25
  import { useT } from './skill-hub/locale';
26
26
  import { SkillManager, ExecutionHistory, SkillMetrics, LoopSettings } from './skill-hub';
27
27
 
28
- const OrchestratorSettings: React.FC = () => {
28
+ const OrchestratorSettings: React.FC<{ embedded?: boolean }> = ({ embedded } = {}) => {
29
29
  const t = useT();
30
30
 
31
31
  return (
32
32
  <AIEmployeesProvider>
33
- <div style={{ padding: '0 24px 24px' }}>
33
+ <div style={embedded ? undefined : { padding: '0 24px 24px' }}>
34
34
  <Tabs
35
35
  defaultActiveKey="native-monitor"
36
36
  items={[
@@ -8,10 +8,11 @@ export class PluginAgentOrchestratorClient extends Plugin {
8
8
  (this as any).app.use(InteractionSchemasProvider);
9
9
 
10
10
  // Register under the "AI" settings group for consistency with other AI plugins
11
- (this as any).app.pluginSettingsManager.add('ai.orchestrator', {
11
+ (this as any).app.pluginSettingsManager.add('ai-orchestrator', {
12
12
  title: 'Agent Orchestrator',
13
13
  icon: 'ApartmentOutlined',
14
14
  Component: OrchestratorSettings,
15
+ aclSnippet: 'pm.ai-orchestrator',
15
16
  });
16
17
 
17
18
  (this as any).app.eventBus?.addEventListener?.('auth:tokenChanged', (event: Event) => {