plugin-agent-orchestrator 1.1.6 → 1.1.7

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 (69) 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/plugin.tsx +1 -1
  35. package/src/client-v2/plugin.tsx +14 -13
  36. package/src/server/__tests__/tool-loop-detection.test.ts +1 -0
  37. package/src/server/collections/agent-loop-runs.ts +7 -0
  38. package/src/server/collections/skill-metrics.ts +36 -0
  39. package/src/server/plugin.ts +117 -1
  40. package/src/server/resources/agent-loop-events-stream.ts +108 -105
  41. package/src/server/resources/agent-loop.ts +1 -1
  42. package/src/server/resources/tracing.ts +267 -266
  43. package/src/server/services/DurableCircuitBreakerService.ts +235 -239
  44. package/src/server/services/ExecutionSpanService.ts +37 -12
  45. package/src/server/services/HarnessProfileService.ts +1 -5
  46. package/src/server/services/LoopBudgetService.ts +271 -275
  47. package/src/server/services/LoopControlService.ts +120 -124
  48. package/src/server/services/LoopPatternSchema.ts +60 -14
  49. package/src/server/services/LoopPatternService.ts +171 -143
  50. package/src/server/services/LoopRunRepository.ts +1 -5
  51. package/src/server/services/LoopRunStateMachine.ts +1 -5
  52. package/src/server/services/LoopSchedulerService.ts +195 -199
  53. package/src/server/services/LoopTriggerService.ts +7 -5
  54. package/src/server/services/LoopWorkerService.ts +102 -12
  55. package/src/server/services/PathLockService.ts +317 -321
  56. package/src/server/services/PluginAiRuntimeAdapter.ts +59 -4
  57. package/src/server/services/RunEventBus.ts +13 -0
  58. package/src/server/services/SkillAccessService.ts +80 -5
  59. package/src/server/services/TokenTracker.ts +59 -7
  60. package/src/server/services/ToolLoopDetectionService.ts +8 -11
  61. package/src/server/services/VerificationSchema.ts +31 -31
  62. package/src/server/services/VerificationService.ts +60 -11
  63. package/src/server/services/harness-runtime-policy.ts +2 -9
  64. package/src/server/skill-hub/plugin.ts +36 -28
  65. package/src/server/types.ts +5 -39
  66. package/src/server/utils/ensure-indexes.ts +96 -96
  67. package/src/server/utils/ha-lock.ts +80 -0
  68. package/src/server/utils/loop-pattern-context.ts +84 -20
  69. package/src/server/utils/record-utils.ts +19 -0
@@ -29,10 +29,7 @@ __export(LoopSchedulerService_exports, {
29
29
  LoopSchedulerService: () => LoopSchedulerService
30
30
  });
31
31
  module.exports = __toCommonJS(LoopSchedulerService_exports);
32
- function read(record, key) {
33
- const model = record;
34
- return typeof model.get === "function" ? model.get(key) : record[key];
35
- }
32
+ var import_record_utils = require("../utils/record-utils");
36
33
  function positiveInteger(value) {
37
34
  const parsed = Number(value);
38
35
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
@@ -95,7 +92,7 @@ class LoopSchedulerService {
95
92
  const records = await this.plugin.db.getRepository("agentLoopPatterns").find({ fields: ["id"] });
96
93
  const patternIds = /* @__PURE__ */ new Set();
97
94
  for (const record of records) {
98
- const patternId = positiveInteger(read(record, "id"));
95
+ const patternId = positiveInteger((0, import_record_utils.read)(record, "id"));
99
96
  if (!patternId) continue;
100
97
  patternIds.add(patternId);
101
98
  await this.resyncPattern(patternId);
@@ -108,7 +105,7 @@ class LoopSchedulerService {
108
105
  var _a;
109
106
  if (!this.started) return;
110
107
  const record = await this.plugin.db.getRepository("agentLoopPatterns").findOne({ filterByTk: patternId });
111
- if (!record || read(record, "enabled") !== true || read(record, "triggerType") !== "cron") {
108
+ if (!record || (0, import_record_utils.read)(record, "enabled") !== true || (0, import_record_utils.read)(record, "triggerType") !== "cron") {
112
109
  this.remove(patternId);
113
110
  return;
114
111
  }
@@ -135,7 +132,7 @@ class LoopSchedulerService {
135
132
  }
136
133
  }
137
134
  onPatternChanged = async (record, options = {}) => {
138
- const patternId = positiveInteger(read(record, "id"));
135
+ const patternId = positiveInteger((0, import_record_utils.read)(record, "id"));
139
136
  if (!patternId) return;
140
137
  const apply = async () => {
141
138
  await this.resyncPattern(patternId);
@@ -31,10 +31,7 @@ __export(LoopTriggerService_exports, {
31
31
  module.exports = __toCommonJS(LoopTriggerService_exports);
32
32
  var import_node_crypto = require("node:crypto");
33
33
  var import_LoopControlService = require("./LoopControlService");
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 plain(record) {
39
36
  return typeof record.toJSON === "function" ? record.toJSON() : record;
40
37
  }
@@ -54,13 +51,15 @@ function harnessAppliedEvents(compiled) {
54
51
  return roles.filter((entry) => entry.snapshot);
55
52
  }
56
53
  class LoopTriggerService {
57
- constructor(database, patterns) {
54
+ constructor(database, patterns, logger) {
58
55
  this.database = database;
59
56
  this.patterns = patterns;
57
+ this.logger = logger;
60
58
  this.control = new import_LoopControlService.LoopControlService(database);
61
59
  }
62
60
  control;
63
61
  async enqueue(input) {
62
+ var _a, _b, _c;
64
63
  const triggerKey = input.triggerKey.trim();
65
64
  if (!triggerKey) throw new Error("Trigger key is required.");
66
65
  await this.control.assertCanEnqueue();
@@ -105,7 +104,7 @@ class LoopTriggerService {
105
104
  },
106
105
  transaction
107
106
  });
108
- const runId = Number(read(run, "id"));
107
+ const runId = Number((0, import_record_utils.read)(run, "id"));
109
108
  await this.database.getRepository("agentLoopEvents").create({
110
109
  values: {
111
110
  runId,
@@ -155,6 +154,12 @@ class LoopTriggerService {
155
154
  filter: { patternId: input.patternId, triggerKey }
156
155
  });
157
156
  if (!existing) throw error;
157
+ (_c = (_a = this.logger) == null ? void 0 : _a.debug) == null ? void 0 : _c.call(
158
+ _a,
159
+ `[LoopTrigger] Deduplicated trigger key "${triggerKey}" for pattern ${input.patternId}: run ${Number(
160
+ ((_b = existing.get) == null ? void 0 : _b.call(existing, "id")) || existing.id
161
+ )} already exists.`
162
+ );
158
163
  return { created: false, run: plain(existing) };
159
164
  }
160
165
  }
@@ -39,7 +39,10 @@ var import_LoopRunStateMachine = require("./LoopRunStateMachine");
39
39
  var import_PathLockService = require("./PathLockService");
40
40
  var import_PluginAiRuntimeAdapter = require("./PluginAiRuntimeAdapter");
41
41
  var import_ToolLoopDetectionService = require("./ToolLoopDetectionService");
42
+ var import_TokenTracker = require("./TokenTracker");
42
43
  var import_VerificationService = require("./VerificationService");
44
+ var import_record_utils = require("../utils/record-utils");
45
+ var import_ctx_utils = require("../utils/ctx-utils");
43
46
  const POLL_INTERVAL_MS = 3e3;
44
47
  const LEASE_MS = 12e4;
45
48
  const HEARTBEAT_MS = 3e4;
@@ -49,12 +52,17 @@ const MAKER_SYSTEM_MESSAGE = "You are a maker on an autonomous run. Do the work
49
52
  function loopWorkerAbortMessage(runId) {
50
53
  return { type: "loop-run-abort-requested", runId };
51
54
  }
52
- function read(record, key) {
53
- const model = record;
54
- return typeof model.get === "function" ? model.get(key) : record[key];
55
- }
56
- function asObject(value) {
57
- return value && typeof value === "object" && !Array.isArray(value) ? value : {};
55
+ function buildProgress(phase, totalPhases, completedPhases, stepTitle, role, startedAt) {
56
+ return {
57
+ currentPhase: phase,
58
+ totalPhases,
59
+ completedPhases,
60
+ currentStepTitle: stepTitle,
61
+ currentRole: role,
62
+ estimatedMsRemaining: null,
63
+ startedAt: startedAt.toISOString(),
64
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
65
+ };
58
66
  }
59
67
  function asStringArray(value) {
60
68
  return Array.isArray(value) ? value.map((item) => String(item)).filter(Boolean) : [];
@@ -63,13 +71,13 @@ function autonomyLevel(value) {
63
71
  return value === "L2" || value === "L3" ? value : "L1";
64
72
  }
65
73
  function harnessFrom(value) {
66
- const snapshot = asObject(value);
67
- const effective = asObject(snapshot.effective);
74
+ const snapshot = (0, import_ctx_utils.asObject)(value);
75
+ const effective = (0, import_ctx_utils.asObject)(snapshot.effective);
68
76
  if (!effective.tools) throw new Error("The run harness snapshot is missing its compiled settings.");
69
77
  return effective;
70
78
  }
71
79
  function resumeContextFrom(value) {
72
- const context = asObject(value);
80
+ const context = (0, import_ctx_utils.asObject)(value);
73
81
  if (!context) return null;
74
82
  const role = context.role === "leader" || context.role === "maker" ? context.role : null;
75
83
  const username = typeof context.username === "string" ? context.username : "";
@@ -101,7 +109,8 @@ class LoopWorkerService {
101
109
  this.circuits = new import_DurableCircuitBreakerService.DurableCircuitBreakerService(database, distributedLock);
102
110
  this.pathLocks = new import_PathLockService.PathLockService(database, distributedLock);
103
111
  this.runtime = new import_PluginAiRuntimeAdapter.PluginAiRuntimeAdapter(app);
104
- this.verification = new import_VerificationService.VerificationService(database, this.runtime, this.stateMachine);
112
+ this.tokenTracker = new import_TokenTracker.TokenTracker({ app, db: database });
113
+ this.verification = new import_VerificationService.VerificationService(database, this.runtime, this.stateMachine, this.tokenTracker);
105
114
  this.loopGuard = new import_ToolLoopDetectionService.ToolLoopDetectionService(database);
106
115
  this.workerId = `${app.name}:${process.pid}:${(0, import_node_crypto.randomUUID)()}`;
107
116
  }
@@ -113,6 +122,7 @@ class LoopWorkerService {
113
122
  runtime;
114
123
  verification;
115
124
  loopGuard;
125
+ tokenTracker;
116
126
  workerId;
117
127
  active = /* @__PURE__ */ new Map();
118
128
  heldPathLocks = /* @__PURE__ */ new Map();
@@ -162,6 +172,15 @@ class LoopWorkerService {
162
172
  if (!claimed) return;
163
173
  await this.execute(claimed);
164
174
  }
175
+ async updateProgress(runId, progress) {
176
+ await this.database.getRepository("agentLoopRuns").update({
177
+ filterByTk: runId,
178
+ values: { progress }
179
+ }).catch((error) => {
180
+ var _a, _b;
181
+ (_b = (_a = this.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `[AgentOrchestrator] Failed to update progress for run ${runId}`, { error });
182
+ });
183
+ }
165
184
  async execute(claimed) {
166
185
  const runId = Number(claimed.run.id);
167
186
  const controller = new AbortController();
@@ -232,6 +251,8 @@ class LoopWorkerService {
232
251
  values: { currentRole: snapshot.resumeContext ? snapshot.resumeContext.role : "leader" }
233
252
  });
234
253
  const loopNotices = await this.loopGuard.existingNotices(snapshot.id);
254
+ const totalPhases = 1 + snapshot.makerUsernames.length + 1;
255
+ const runStartedAt = /* @__PURE__ */ new Date();
235
256
  let makerReports;
236
257
  let makerQueue;
237
258
  if (snapshot.resumeContext) {
@@ -279,6 +300,10 @@ ${resumed.content}`];
279
300
  loopNotices
280
301
  );
281
302
  if (leaderGuard === "halt") return;
303
+ await this.updateProgress(
304
+ snapshot.id,
305
+ buildProgress("leader", totalPhases, 1, "Leader plan complete", "leader", runStartedAt)
306
+ );
282
307
  if (leader.interrupted.length) {
283
308
  await this.parkForApproval(snapshot, leader, leaseToken, {
284
309
  role: "leader",
@@ -330,6 +355,11 @@ ${resumed.content}`];
330
355
  }
331
356
  makerReports.push(`# ${username}
332
357
  ${maker.content}`);
358
+ const completedMakers = snapshot.makerUsernames.length - makerQueue.length + 1;
359
+ await this.updateProgress(
360
+ snapshot.id,
361
+ buildProgress("maker", totalPhases, 1 + completedMakers, `Maker "${username}" complete`, "maker", runStartedAt)
362
+ );
333
363
  makerQueue = makerQueue.slice(1);
334
364
  }
335
365
  const makerSummary = makerReports.join("\n\n");
@@ -345,6 +375,17 @@ ${maker.content}`);
345
375
  correlationKey: `verifying:${snapshot.id}`,
346
376
  values: { currentRole: "verifier", finalAnswer: makerSummary }
347
377
  });
378
+ await this.updateProgress(
379
+ snapshot.id,
380
+ buildProgress(
381
+ "verifying",
382
+ totalPhases,
383
+ totalPhases - 1,
384
+ `Verifier "${snapshot.verifierUsername}" reviewing`,
385
+ "verifier",
386
+ runStartedAt
387
+ )
388
+ );
348
389
  await this.budgets.reserve({
349
390
  runId: snapshot.id,
350
391
  patternId: snapshot.patternId,
@@ -361,6 +402,7 @@ ${maker.content}`);
361
402
  verifierHarness: snapshot.verifierHarness,
362
403
  policy: snapshot.policy,
363
404
  makerSummary,
405
+ actingOn: snapshot.actingOn,
364
406
  userId: snapshot.userId,
365
407
  workerId: this.workerId,
366
408
  leaseToken,
@@ -379,6 +421,17 @@ ${maker.content}`);
379
421
  return;
380
422
  }
381
423
  await this.circuits.recordSuccess(snapshot.patternId, `pattern:${snapshot.patternId}`, snapshot.id);
424
+ await this.updateProgress(
425
+ snapshot.id,
426
+ buildProgress(
427
+ "complete",
428
+ totalPhases,
429
+ totalPhases,
430
+ "Run completed successfully",
431
+ snapshot.currentRole || "verifier",
432
+ runStartedAt
433
+ )
434
+ );
382
435
  }
383
436
  async acquirePaths(snapshot, leaseToken) {
384
437
  if (!snapshot.repositoryKey || !snapshot.actingOn.length) return true;
@@ -447,8 +500,15 @@ ${maker.content}`);
447
500
  prompt: input.prompt,
448
501
  signal: input.signal
449
502
  });
503
+ await this.tokenTracker.trackActualUsage(
504
+ (0, import_record_utils.read)(step, "id"),
505
+ outcome.tokenUsage ?? null,
506
+ input.prompt,
507
+ outcome.content,
508
+ snapshot.id
509
+ );
450
510
  await this.database.getRepository("agentLoopSteps").update({
451
- filterByTk: read(step, "id"),
511
+ filterByTk: (0, import_record_utils.read)(step, "id"),
452
512
  values: {
453
513
  status: outcome.interrupted.length ? "waiting_user" : "succeeded",
454
514
  output: { content: outcome.content },
@@ -500,8 +560,15 @@ ${maker.content}`);
500
560
  decisions,
501
561
  signal
502
562
  });
563
+ await this.tokenTracker.trackActualUsage(
564
+ (0, import_record_utils.read)(step, "id"),
565
+ outcome.tokenUsage ?? null,
566
+ resume.role === "leader" ? LEADER_SYSTEM_MESSAGE : MAKER_SYSTEM_MESSAGE,
567
+ outcome.content,
568
+ snapshot.id
569
+ );
503
570
  await this.database.getRepository("agentLoopSteps").update({
504
- filterByTk: read(step, "id"),
571
+ filterByTk: (0, import_record_utils.read)(step, "id"),
505
572
  values: {
506
573
  status: outcome.interrupted.length ? "waiting_user" : "succeeded",
507
574
  output: { content: outcome.content },
@@ -558,13 +625,13 @@ ${maker.content}`);
558
625
  const decisions = [];
559
626
  const now = /* @__PURE__ */ new Date();
560
627
  for (const approval of approvals) {
561
- const status = String(read(approval, "status"));
628
+ const status = String((0, import_record_utils.read)(approval, "status"));
562
629
  if (status !== "approved" && status !== "rejected") continue;
563
- if (read(approval, "consumedAt")) continue;
564
- const editedInput = read(approval, "editedInput");
565
- const decision = status === "approved" ? editedInput ? { type: "edit", editedAction: { name: String(read(approval, "toolName")), args: editedInput } } : { type: "approve" } : { type: "reject", message: String(read(approval, "decisionNote") || "") || void 0 };
566
- decisions.push({ toolCallId: String(read(approval, "toolCallId")), decision });
567
- await repository.update({ filterByTk: Number(read(approval, "id")), values: { consumedAt: now } });
630
+ if ((0, import_record_utils.read)(approval, "consumedAt")) continue;
631
+ const editedInput = (0, import_record_utils.read)(approval, "editedInput");
632
+ const decision = status === "approved" ? editedInput ? { type: "edit", editedAction: { name: String((0, import_record_utils.read)(approval, "toolName")), args: editedInput } } : { type: "approve" } : { type: "reject", message: String((0, import_record_utils.read)(approval, "decisionNote") || "") || void 0 };
633
+ decisions.push({ toolCallId: String((0, import_record_utils.read)(approval, "toolCallId")), decision });
634
+ await repository.update({ filterByTk: Number((0, import_record_utils.read)(approval, "id")), values: { consumedAt: now } });
568
635
  }
569
636
  if (!decisions.length) throw new Error("The resumed run has no recorded approval decisions.");
570
637
  return decisions;
@@ -659,16 +726,15 @@ ${maker.content}`);
659
726
  }
660
727
  }
661
728
  async nextSequence(runId) {
662
- const steps = await this.database.getRepository("agentLoopSteps").find({ filter: { runId } });
663
- return steps.length;
729
+ return this.database.getRepository("agentLoopSteps").count({ filter: { runId } });
664
730
  }
665
731
  snapshotFrom(run) {
666
732
  const patternId = Number(run.patternId);
667
733
  if (!Number.isSafeInteger(patternId) || patternId <= 0) {
668
734
  throw new Error("The claimed run has no pattern snapshot.");
669
735
  }
670
- const roleBindings = asObject(run.roleBindingsSnapshot);
671
- const makerSnapshots = asObject(run.makerHarnessSnapshot);
736
+ const roleBindings = (0, import_ctx_utils.asObject)(run.roleBindingsSnapshot);
737
+ const makerSnapshots = (0, import_ctx_utils.asObject)(run.makerHarnessSnapshot);
672
738
  const approvalStatus = String(run.approvalStatus || "none");
673
739
  return {
674
740
  id: Number(run.id),
@@ -33,10 +33,7 @@ __export(PathLockService_exports, {
33
33
  waitGraphHasCycle: () => waitGraphHasCycle
34
34
  });
35
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
- }
36
+ var import_record_utils = require("../utils/record-utils");
40
37
  function positiveInteger(value) {
41
38
  const parsed = Number(value);
42
39
  return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
@@ -50,7 +47,7 @@ function asDate(value) {
50
47
  return null;
51
48
  }
52
49
  function lockIsExpired(record, now) {
53
- const expiresAt = asDate(read(record, "expiresAt"));
50
+ const expiresAt = asDate((0, import_record_utils.read)(record, "expiresAt"));
54
51
  return !expiresAt || expiresAt.getTime() <= now.getTime();
55
52
  }
56
53
  function positiveTtl(ttlMs) {
@@ -98,14 +95,14 @@ function pathSetsOverlap(left, right) {
98
95
  return left.some((leftPath) => right.some((rightPath) => lockPathsOverlap(leftPath, rightPath)));
99
96
  }
100
97
  function row(record) {
101
- const status = read(record, "status");
98
+ const status = (0, import_record_utils.read)(record, "status");
102
99
  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") : [],
100
+ id: positiveInteger((0, import_record_utils.read)(record, "id")) || 0,
101
+ runId: positiveInteger((0, import_record_utils.read)(record, "runId")) || 0,
102
+ repositoryKey: String((0, import_record_utils.read)(record, "repositoryKey") || ""),
103
+ paths: Array.isArray((0, import_record_utils.read)(record, "paths")) ? (0, import_record_utils.read)(record, "paths") : [],
107
104
  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) : []
105
+ blockerRunIds: Array.isArray((0, import_record_utils.read)(record, "blockerRunIds")) ? (0, import_record_utils.read)(record, "blockerRunIds").map(positiveInteger).filter((value) => value !== null) : []
109
106
  };
110
107
  }
111
108
  function waitGraphHasCycle(rows, runId, blockers) {
@@ -150,8 +147,8 @@ class PathLockService {
150
147
  transaction,
151
148
  lock: transaction.LOCK.UPDATE
152
149
  });
153
- if (existing && read(existing, "status") === "held") {
154
- const sameOwner = String(read(existing, "owner") || "") === input.owner;
150
+ if (existing && (0, import_record_utils.read)(existing, "status") === "held") {
151
+ const sameOwner = String((0, import_record_utils.read)(existing, "owner") || "") === input.owner;
155
152
  const samePaths = JSON.stringify(row(existing).paths.slice().sort()) === JSON.stringify(paths);
156
153
  if (sameOwner && samePaths && !lockIsExpired(existing, now)) {
157
154
  return { acquired: true, lock: row(existing), blockers: [] };
@@ -169,7 +166,7 @@ class PathLockService {
169
166
  continue;
170
167
  }
171
168
  await repository.update({
172
- filterByTk: read(lock, "id"),
169
+ filterByTk: (0, import_record_utils.read)(lock, "id"),
173
170
  values: { status: "expired", releasedAt: now, blockerRunIds: [] },
174
171
  transaction
175
172
  });
@@ -197,7 +194,7 @@ class PathLockService {
197
194
  releasedAt: null
198
195
  };
199
196
  if (existing) {
200
- await repository.update({ filterByTk: read(existing, "id"), values: values2, transaction });
197
+ await repository.update({ filterByTk: (0, import_record_utils.read)(existing, "id"), values: values2, transaction });
201
198
  } else {
202
199
  await repository.create({ values: values2, transaction });
203
200
  }
@@ -215,7 +212,7 @@ class PathLockService {
215
212
  waitUntil: null,
216
213
  releasedAt: null
217
214
  };
218
- const locked = existing ? await this.updateAndRead(repository, Number(read(existing, "id")), values, transaction) : await repository.create({ values, transaction });
215
+ const locked = existing ? await this.updateAndRead(repository, Number((0, import_record_utils.read)(existing, "id")), values, transaction) : await repository.create({ values, transaction });
219
216
  return { acquired: true, lock: row(locked), blockers: [] };
220
217
  }),
221
218
  Math.max(ttlMs, 5e3)
@@ -232,13 +229,13 @@ class PathLockService {
232
229
  lock: transaction.LOCK.UPDATE
233
230
  });
234
231
  if (!lock) throw new Error("Held path lock was not found.");
235
- if (owner !== void 0 && String(read(lock, "owner") || "") !== owner) {
232
+ if (owner !== void 0 && String((0, import_record_utils.read)(lock, "owner") || "") !== owner) {
236
233
  throw new Error("Path lock is no longer owned by this worker.");
237
234
  }
238
235
  const now = /* @__PURE__ */ new Date();
239
- if (lockIsExpired(lock, now)) return { id: read(lock, "id"), at: now };
236
+ if (lockIsExpired(lock, now)) return { id: (0, import_record_utils.read)(lock, "id"), at: now };
240
237
  await repository.update({
241
- filterByTk: read(lock, "id"),
238
+ filterByTk: (0, import_record_utils.read)(lock, "id"),
242
239
  values: { expiresAt: new Date(now.getTime() + ttl) },
243
240
  transaction
244
241
  });
@@ -262,10 +259,10 @@ class PathLockService {
262
259
  return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
263
260
  const repository = this.database.getRepository("agentLoopPathLocks");
264
261
  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;
262
+ if (!lock || ["released", "expired"].includes(String((0, import_record_utils.read)(lock, "status")))) return false;
263
+ if (owner !== void 0 && String((0, import_record_utils.read)(lock, "owner") || "") !== owner) return false;
267
264
  await repository.update({
268
- filterByTk: read(lock, "id"),
265
+ filterByTk: (0, import_record_utils.read)(lock, "id"),
269
266
  values: { status: "released", releasedAt: /* @__PURE__ */ new Date(), blockerRunIds: [] }
270
267
  });
271
268
  return true;
@@ -32,13 +32,50 @@ __export(PluginAiRuntimeAdapter_exports, {
32
32
  module.exports = __toCommonJS(PluginAiRuntimeAdapter_exports);
33
33
  var import_server = require("@nocobase/plugin-ai/server");
34
34
  var import_ai = require("@nocobase/ai");
35
+ var import_TokenTracker = require("./TokenTracker");
35
36
  var import_ai_manager = require("../utils/ai-manager");
36
37
  var import_HarnessCompiler = require("./HarnessCompiler");
38
+ var import_record_utils = require("../utils/record-utils");
37
39
  const SYSTEM_TOOL_WEB_SEARCH = "subAgentWebSearch";
38
40
  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];
41
+ function extractTokenUsageFromResult(result) {
42
+ const messages = result.messages;
43
+ if (Array.isArray(messages)) {
44
+ let totalInput = 0;
45
+ let totalOutput = 0;
46
+ let totalAll = 0;
47
+ for (const msg of messages) {
48
+ const um = msg == null ? void 0 : msg.usage_metadata;
49
+ if (um) {
50
+ totalInput += Number(um.input_tokens || 0);
51
+ totalOutput += Number(um.output_tokens || 0);
52
+ totalAll += Number(um.total_tokens || 0);
53
+ }
54
+ }
55
+ if (totalAll > 0) {
56
+ return {
57
+ inputTokens: totalInput,
58
+ outputTokens: totalOutput,
59
+ totalTokens: totalAll,
60
+ cost: (0, import_TokenTracker.estimateCost)(totalInput, totalOutput)
61
+ };
62
+ }
63
+ }
64
+ const usage = result.usage;
65
+ if (usage) {
66
+ const inputTokens = Number(usage.prompt_tokens || usage.input_tokens || 0);
67
+ const outputTokens = Number(usage.completion_tokens || usage.output_tokens || 0);
68
+ const totalTokens = Number(usage.total_tokens || inputTokens + outputTokens);
69
+ if (totalTokens > 0) {
70
+ return {
71
+ inputTokens,
72
+ outputTokens,
73
+ totalTokens,
74
+ cost: (0, import_TokenTracker.estimateCost)(inputTokens, outputTokens)
75
+ };
76
+ }
77
+ }
78
+ return null;
42
79
  }
43
80
  function textContent(messages) {
44
81
  if (!Array.isArray(messages)) return "";
@@ -118,7 +155,7 @@ class PluginAiRuntimeAdapter {
118
155
  category: "task",
119
156
  options: { controlPlaneRunId: input.runId }
120
157
  });
121
- const sessionId = String(read(conversation, "sessionId") || "");
158
+ const sessionId = String((0, import_record_utils.read)(conversation, "sessionId") || "");
122
159
  if (!sessionId) throw new Error("The AI conversation was created without a session identifier.");
123
160
  return sessionId;
124
161
  }
@@ -132,7 +169,8 @@ class PluginAiRuntimeAdapter {
132
169
  sessionId: input.sessionId,
133
170
  messageId: String(result.messageId || ""),
134
171
  interrupted: interruptedFrom(result),
135
- content: textContent(result.messages)
172
+ content: textContent(result.messages),
173
+ tokenUsage: extractTokenUsageFromResult(result)
136
174
  };
137
175
  }
138
176
  // Resume mirrors the official workflow employee node: flip the persisted tool call to
@@ -166,7 +204,8 @@ class PluginAiRuntimeAdapter {
166
204
  sessionId: input.sessionId,
167
205
  messageId: String(result.messageId || input.messageId),
168
206
  interrupted: interruptedFrom(result),
169
- content: textContent(result.messages)
207
+ content: textContent(result.messages),
208
+ tokenUsage: extractTokenUsageFromResult(result)
170
209
  };
171
210
  }
172
211
  // The employee model is re-read per invocation and mutated only in memory. `isAutoCall` reads
@@ -183,7 +222,11 @@ class PluginAiRuntimeAdapter {
183
222
  db: this.app.db,
184
223
  log: this.app.log,
185
224
  logger: this.app.log,
186
- state: { currentRoles },
225
+ state: {
226
+ currentRoles,
227
+ // Populate currentUser so currentUserId(ctx) resolves correctly.
228
+ currentUser: input.userId ? { id: input.userId } : void 0
229
+ },
187
230
  auth: { user: { id: input.userId } },
188
231
  action: { params: { values: { sessionId: input.sessionId, model } } }
189
232
  };
@@ -216,7 +259,7 @@ class PluginAiRuntimeAdapter {
216
259
  async rolesFor(userId) {
217
260
  if (!userId) return [];
218
261
  const rows = await this.app.db.getRepository("rolesUsers").find({ filter: { userId } });
219
- return rows.map((row) => String(read(row, "roleName") || "")).filter(Boolean);
262
+ return rows.map((row) => String((0, import_record_utils.read)(row, "roleName") || "")).filter(Boolean);
220
263
  }
221
264
  }
222
265
  // Annotate the CommonJS export names for ESM import in node:
@@ -26,7 +26,8 @@ var __copyProps = (to, from, except, desc) => {
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
  var RunEventBus_exports = {};
28
28
  __export(RunEventBus_exports, {
29
- getRunEventBus: () => getRunEventBus
29
+ getRunEventBus: () => getRunEventBus,
30
+ resetRunEventBus: () => resetRunEventBus
30
31
  });
31
32
  module.exports = __toCommonJS(RunEventBus_exports);
32
33
  class RunEventBusImpl {
@@ -59,6 +60,10 @@ class RunEventBusImpl {
59
60
  var _a;
60
61
  return ((_a = this.listeners.get(runId)) == null ? void 0 : _a.size) || 0;
61
62
  }
63
+ /** Remove all listeners for all runs. Call during plugin shutdown. */
64
+ destroy() {
65
+ this.listeners.clear();
66
+ }
62
67
  }
63
68
  let instance = null;
64
69
  function getRunEventBus() {
@@ -67,7 +72,14 @@ function getRunEventBus() {
67
72
  }
68
73
  return instance;
69
74
  }
75
+ function resetRunEventBus() {
76
+ if (instance) {
77
+ instance.destroy();
78
+ instance = null;
79
+ }
80
+ }
70
81
  // Annotate the CommonJS export names for ESM import in node:
71
82
  0 && (module.exports = {
72
- getRunEventBus
83
+ getRunEventBus,
84
+ resetRunEventBus
73
85
  });
@@ -91,7 +91,7 @@ class SkillAccessService {
91
91
  return skills.filter((_skill, index) => checks[index]);
92
92
  }
93
93
  async findAgentUsernamesUsingTool(toolName) {
94
- const employees = await this.plugin.db.getRepository("aiEmployees").find({});
94
+ const employees = await this.plugin.db.getRepository("aiEmployees").find({ limit: 500 });
95
95
  const usernames = [];
96
96
  for (const employee of employees || []) {
97
97
  const settings = (0, import_ctx_utils.asObject)((0, import_skill_tool_name.readRecordValue)(employee, "skillSettings"));
@@ -102,6 +102,55 @@ class SkillAccessService {
102
102
  }
103
103
  return usernames;
104
104
  }
105
+ /**
106
+ * Cascade-disable a skill across all AI employee bindings.
107
+ *
108
+ * When a skill is disabled or deleted, this method removes its tool from every employee's
109
+ * `skillSettings.tools` array. This prevents stale bindings from allowing execution of
110
+ * skills that are no longer available.
111
+ *
112
+ * Returns the list of affected employee usernames for audit logging.
113
+ */
114
+ async cascadeDisableSkill(skillToolName) {
115
+ const affectedUsernames = [];
116
+ const employees = await this.plugin.db.getRepository("aiEmployees").find({ limit: 500 });
117
+ const updates = [];
118
+ for (const employee of employees || []) {
119
+ const skillSettings = (0, import_ctx_utils.asObject)((0, import_skill_tool_name.readRecordValue)(employee, "skillSettings"));
120
+ const tools = Array.isArray(skillSettings.tools) ? skillSettings.tools : [];
121
+ const filteredTools = tools.filter((binding) => bindingName(binding) !== skillToolName);
122
+ if (filteredTools.length === tools.length) continue;
123
+ const username = (0, import_ctx_utils.normalizeEmployeeUsername)((0, import_skill_tool_name.readRecordValue)(employee, "username"));
124
+ if (!username) continue;
125
+ updates.push({
126
+ username,
127
+ skillSettings: {
128
+ ...skillSettings,
129
+ tools: filteredTools
130
+ }
131
+ });
132
+ }
133
+ const BATCH_SIZE = 10;
134
+ for (let i = 0; i < updates.length; i += BATCH_SIZE) {
135
+ const batch = updates.slice(i, i + BATCH_SIZE);
136
+ await Promise.all(
137
+ batch.map(
138
+ (update) => this.plugin.db.getRepository("aiEmployees").update({
139
+ filter: { username: update.username },
140
+ values: { skillSettings: update.skillSettings }
141
+ }).then(() => {
142
+ var _a, _b, _c;
143
+ affectedUsernames.push(update.username);
144
+ (_c = (_b = (_a = this.plugin.app) == null ? void 0 : _a.logger) == null ? void 0 : _b.info) == null ? void 0 : _c.call(
145
+ _b,
146
+ `[SkillAccess] Cascade-removed skill tool "${skillToolName}" from employee "${update.username}".`
147
+ );
148
+ })
149
+ )
150
+ );
151
+ }
152
+ return affectedUsernames;
153
+ }
105
154
  }
106
155
  // Annotate the CommonJS export names for ESM import in node:
107
156
  0 && (module.exports = {