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
@@ -1,239 +1,235 @@
1
- import { createHash } from 'node:crypto';
2
- import type { Database, Model } from '@nocobase/database';
3
- import type { LoopPatternPolicy } from './LoopPatternSchema';
4
-
5
- type DistributedLock = {
6
- runExclusive<T>(key: string, operation: () => Promise<T>, ttl?: number): Promise<T>;
7
- };
8
-
9
- type CircuitSnapshot = {
10
- id: number;
11
- state: 'closed' | 'open' | 'half_open';
12
- attempts: number;
13
- consecutiveFailures: number;
14
- errorSignature: string;
15
- repeatedErrorCount: number;
16
- retryAt: Date | null;
17
- };
18
-
19
- function read(record: Model | Record<string, unknown>, key: string) {
20
- const model = record as Model & { get?: (name: string) => unknown };
21
- return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
22
- }
23
-
24
- function count(value: unknown, label: string) {
25
- if (value === null || value === undefined) return 0;
26
- const parsed = Number(value);
27
- if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(`${label} counter is invalid.`);
28
- return parsed;
29
- }
30
-
31
- function dateOrNull(value: unknown) {
32
- if (!value) return null;
33
- const date = value instanceof Date ? value : new Date(String(value));
34
- return Number.isNaN(date.getTime()) ? null : date;
35
- }
36
-
37
- function snapshot(record: Model | Record<string, unknown>): CircuitSnapshot {
38
- const id = Number(read(record, 'id'));
39
- const state = read(record, 'state');
40
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Circuit breaker state has an invalid identifier.');
41
- if (state !== 'closed' && state !== 'open' && state !== 'half_open') {
42
- throw new Error('Circuit breaker state is invalid.');
43
- }
44
- return {
45
- id,
46
- state,
47
- attempts: count(read(record, 'attempts'), 'Circuit attempt'),
48
- consecutiveFailures: count(read(record, 'consecutiveFailures'), 'Circuit consecutive failure'),
49
- errorSignature: typeof read(record, 'errorSignature') === 'string' ? String(read(record, 'errorSignature')) : '',
50
- repeatedErrorCount: count(read(record, 'repeatedErrorCount'), 'Circuit repeated error'),
51
- retryAt: dateOrNull(read(record, 'retryAt')),
52
- };
53
- }
54
-
55
- function normalizeScopeKey(scopeKey: string) {
56
- const normalized = scopeKey.trim();
57
- if (!normalized) throw new Error('Circuit breaker scope key is required.');
58
- if (normalized.length > 300) throw new Error('Circuit breaker scope key cannot exceed 300 characters.');
59
- return normalized;
60
- }
61
-
62
- export function normalizeErrorSignature(error: unknown) {
63
- const raw = error instanceof Error ? `${error.name}:${error.message}` : String(error);
64
- const normalized = raw
65
- .toLowerCase()
66
- .replace(/[a-z]:[\\/][^\s"']+/gi, '<path>')
67
- .replace(/\/(?:[^\s/]+\/)+[^\s"']*/g, '<path>')
68
- .replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi, '<uuid>')
69
- .replace(/\b\d+\b/g, '<n>')
70
- .replace(/\s+/g, ' ')
71
- .trim();
72
- return createHash('sha256')
73
- .update(normalized || 'unknown-error')
74
- .digest('hex');
75
- }
76
-
77
- export class DurableCircuitBreakerService {
78
- constructor(
79
- private readonly database: Database,
80
- private readonly distributedLock: DistributedLock,
81
- ) {}
82
-
83
- async authorizeAttempt(input: {
84
- patternId: number;
85
- scopeKey: string;
86
- policy: LoopPatternPolicy['circuit'];
87
- now?: Date;
88
- }) {
89
- const scopeKey = normalizeScopeKey(input.scopeKey);
90
- const now = input.now || new Date();
91
- return this.withScopeLock(input.patternId, scopeKey, async () => {
92
- const decision = await this.database.sequelize.transaction(async (transaction) => {
93
- const repository = this.database.getRepository('agentLoopCircuitStates');
94
- let record = await repository.findOne({
95
- filter: { patternId: input.patternId, scopeKey },
96
- transaction,
97
- lock: transaction.LOCK.UPDATE,
98
- });
99
- if (!record) {
100
- record = await repository.create({
101
- values: {
102
- patternId: input.patternId,
103
- scopeKey,
104
- state: 'closed',
105
- attempts: 0,
106
- consecutiveFailures: 0,
107
- repeatedErrorCount: 0,
108
- },
109
- transaction,
110
- });
111
- }
112
- const current = snapshot(record);
113
- if (current.state === 'half_open') {
114
- return { allowed: false as const, reason: 'probe' as const, retryAt: current.retryAt };
115
- }
116
- if (current.state === 'open' && (!current.retryAt || current.retryAt.getTime() > now.getTime())) {
117
- return { allowed: false as const, reason: 'open' as const, retryAt: current.retryAt };
118
- }
119
- if (current.state === 'closed' && current.attempts >= input.policy.maxAttempts) {
120
- const retryAt = new Date(now.getTime() + input.policy.cooldownMs);
121
- await repository.update({
122
- filterByTk: current.id,
123
- values: { state: 'open', openedAt: now, retryAt },
124
- transaction,
125
- });
126
- return { allowed: false as const, reason: 'attempts' as const, retryAt };
127
- }
128
- const nextState = current.state === 'open' ? 'half_open' : 'closed';
129
- await repository.update({
130
- filterByTk: current.id,
131
- values: { state: nextState, attempts: current.attempts + 1 },
132
- transaction,
133
- });
134
- return { allowed: true as const, state: nextState, attempt: current.attempts + 1 };
135
- });
136
- if (decision.allowed) return decision;
137
- if (decision.reason === 'probe') throw new Error('Circuit breaker probe is already in progress.');
138
- if (decision.reason === 'attempts') throw new Error('Circuit breaker maximum attempts reached.');
139
- throw new Error(`Circuit breaker is open until ${decision.retryAt?.toISOString() || 'manual reset'}.`);
140
- });
141
- }
142
-
143
- async recordSuccess(patternId: number, scopeKey: string, lastRunId?: number) {
144
- const normalizedScope = normalizeScopeKey(scopeKey);
145
- return this.withScopeLock(patternId, normalizedScope, async () =>
146
- this.database.sequelize.transaction(async (transaction) => {
147
- const repository = this.database.getRepository('agentLoopCircuitStates');
148
- const record = await repository.findOne({
149
- filter: { patternId, scopeKey: normalizedScope },
150
- transaction,
151
- lock: transaction.LOCK.UPDATE,
152
- });
153
- if (!record) return;
154
- await repository.update({
155
- filterByTk: read(record, 'id'),
156
- values: {
157
- state: 'closed',
158
- attempts: 0,
159
- consecutiveFailures: 0,
160
- errorSignature: null,
161
- repeatedErrorCount: 0,
162
- lastRunId: lastRunId || null,
163
- openedAt: null,
164
- retryAt: null,
165
- },
166
- transaction,
167
- });
168
- }),
169
- );
170
- }
171
-
172
- async recordFailure(input: {
173
- patternId: number;
174
- scopeKey: string;
175
- policy: LoopPatternPolicy['circuit'];
176
- error: unknown;
177
- lastRunId?: number;
178
- now?: Date;
179
- }) {
180
- const scopeKey = normalizeScopeKey(input.scopeKey);
181
- const signature = normalizeErrorSignature(input.error);
182
- const now = input.now || new Date();
183
- return this.withScopeLock(input.patternId, scopeKey, async () =>
184
- this.database.sequelize.transaction(async (transaction) => {
185
- const repository = this.database.getRepository('agentLoopCircuitStates');
186
- let record = await repository.findOne({
187
- filter: { patternId: input.patternId, scopeKey },
188
- transaction,
189
- lock: transaction.LOCK.UPDATE,
190
- });
191
- if (!record) {
192
- record = await repository.create({
193
- values: {
194
- patternId: input.patternId,
195
- scopeKey,
196
- state: 'closed',
197
- attempts: 1,
198
- consecutiveFailures: 0,
199
- repeatedErrorCount: 0,
200
- },
201
- transaction,
202
- });
203
- }
204
- const current = snapshot(record);
205
- const consecutiveFailures = current.consecutiveFailures + 1;
206
- const repeatedErrorCount = current.errorSignature === signature ? current.repeatedErrorCount + 1 : 1;
207
- const shouldOpen =
208
- current.state === 'half_open' ||
209
- current.attempts >= input.policy.maxAttempts ||
210
- consecutiveFailures >= input.policy.maxConsecutiveFailures ||
211
- repeatedErrorCount >= input.policy.maxRepeatedError;
212
- await repository.update({
213
- filterByTk: current.id,
214
- values: {
215
- state: shouldOpen ? 'open' : 'closed',
216
- consecutiveFailures,
217
- errorSignature: signature,
218
- repeatedErrorCount,
219
- lastRunId: input.lastRunId || null,
220
- openedAt: shouldOpen ? now : null,
221
- retryAt: shouldOpen ? new Date(now.getTime() + input.policy.cooldownMs) : null,
222
- },
223
- transaction,
224
- });
225
- return { open: shouldOpen, signature, consecutiveFailures, repeatedErrorCount };
226
- }),
227
- );
228
- }
229
-
230
- private withScopeLock<T>(patternId: number, scopeKey: string, operation: () => Promise<T>) {
231
- const normalizedScope = scopeKey.trim();
232
- if (!normalizedScope) throw new Error('Circuit breaker scope key is required.');
233
- return this.distributedLock.runExclusive(
234
- `agent-loop:circuit:${patternId}:${createHash('sha256').update(normalizedScope).digest('hex')}`,
235
- operation,
236
- 30_000,
237
- );
238
- }
239
- }
1
+ import { createHash } from 'node:crypto';
2
+ import type { Database, Model } from '@nocobase/database';
3
+ import type { LoopPatternPolicy } from './LoopPatternSchema';
4
+ import { read } from '../utils/record-utils';
5
+
6
+ type DistributedLock = {
7
+ runExclusive<T>(key: string, operation: () => Promise<T>, ttl?: number): Promise<T>;
8
+ };
9
+
10
+ type CircuitSnapshot = {
11
+ id: number;
12
+ state: 'closed' | 'open' | 'half_open';
13
+ attempts: number;
14
+ consecutiveFailures: number;
15
+ errorSignature: string;
16
+ repeatedErrorCount: number;
17
+ retryAt: Date | null;
18
+ };
19
+
20
+ function count(value: unknown, label: string) {
21
+ if (value === null || value === undefined) return 0;
22
+ const parsed = Number(value);
23
+ if (!Number.isSafeInteger(parsed) || parsed < 0) throw new Error(`${label} counter is invalid.`);
24
+ return parsed;
25
+ }
26
+
27
+ function dateOrNull(value: unknown) {
28
+ if (!value) return null;
29
+ const date = value instanceof Date ? value : new Date(String(value));
30
+ return Number.isNaN(date.getTime()) ? null : date;
31
+ }
32
+
33
+ function snapshot(record: Model | Record<string, unknown>): CircuitSnapshot {
34
+ const id = Number(read(record, 'id'));
35
+ const state = read(record, 'state');
36
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Circuit breaker state has an invalid identifier.');
37
+ if (state !== 'closed' && state !== 'open' && state !== 'half_open') {
38
+ throw new Error('Circuit breaker state is invalid.');
39
+ }
40
+ return {
41
+ id,
42
+ state,
43
+ attempts: count(read(record, 'attempts'), 'Circuit attempt'),
44
+ consecutiveFailures: count(read(record, 'consecutiveFailures'), 'Circuit consecutive failure'),
45
+ errorSignature: typeof read(record, 'errorSignature') === 'string' ? String(read(record, 'errorSignature')) : '',
46
+ repeatedErrorCount: count(read(record, 'repeatedErrorCount'), 'Circuit repeated error'),
47
+ retryAt: dateOrNull(read(record, 'retryAt')),
48
+ };
49
+ }
50
+
51
+ function normalizeScopeKey(scopeKey: string) {
52
+ const normalized = scopeKey.trim();
53
+ if (!normalized) throw new Error('Circuit breaker scope key is required.');
54
+ if (normalized.length > 300) throw new Error('Circuit breaker scope key cannot exceed 300 characters.');
55
+ return normalized;
56
+ }
57
+
58
+ export function normalizeErrorSignature(error: unknown) {
59
+ const raw = error instanceof Error ? `${error.name}:${error.message}` : String(error);
60
+ const normalized = raw
61
+ .toLowerCase()
62
+ .replace(/[a-z]:[\\/][^\s"']+/gi, '<path>')
63
+ .replace(/\/(?:[^\s/]+\/)+[^\s"']*/g, '<path>')
64
+ .replace(/\b[0-9a-f]{8}-[0-9a-f-]{27,}\b/gi, '<uuid>')
65
+ .replace(/\b\d+\b/g, '<n>')
66
+ .replace(/\s+/g, ' ')
67
+ .trim();
68
+ return createHash('sha256')
69
+ .update(normalized || 'unknown-error')
70
+ .digest('hex');
71
+ }
72
+
73
+ export class DurableCircuitBreakerService {
74
+ constructor(
75
+ private readonly database: Database,
76
+ private readonly distributedLock: DistributedLock,
77
+ ) {}
78
+
79
+ async authorizeAttempt(input: {
80
+ patternId: number;
81
+ scopeKey: string;
82
+ policy: LoopPatternPolicy['circuit'];
83
+ now?: Date;
84
+ }) {
85
+ const scopeKey = normalizeScopeKey(input.scopeKey);
86
+ const now = input.now || new Date();
87
+ return this.withScopeLock(input.patternId, scopeKey, async () => {
88
+ const decision = await this.database.sequelize.transaction(async (transaction) => {
89
+ const repository = this.database.getRepository('agentLoopCircuitStates');
90
+ let record = await repository.findOne({
91
+ filter: { patternId: input.patternId, scopeKey },
92
+ transaction,
93
+ lock: transaction.LOCK.UPDATE,
94
+ });
95
+ if (!record) {
96
+ record = await repository.create({
97
+ values: {
98
+ patternId: input.patternId,
99
+ scopeKey,
100
+ state: 'closed',
101
+ attempts: 0,
102
+ consecutiveFailures: 0,
103
+ repeatedErrorCount: 0,
104
+ },
105
+ transaction,
106
+ });
107
+ }
108
+ const current = snapshot(record);
109
+ if (current.state === 'half_open') {
110
+ return { allowed: false as const, reason: 'probe' as const, retryAt: current.retryAt };
111
+ }
112
+ if (current.state === 'open' && (!current.retryAt || current.retryAt.getTime() > now.getTime())) {
113
+ return { allowed: false as const, reason: 'open' as const, retryAt: current.retryAt };
114
+ }
115
+ if (current.state === 'closed' && current.attempts >= input.policy.maxAttempts) {
116
+ const retryAt = new Date(now.getTime() + input.policy.cooldownMs);
117
+ await repository.update({
118
+ filterByTk: current.id,
119
+ values: { state: 'open', openedAt: now, retryAt },
120
+ transaction,
121
+ });
122
+ return { allowed: false as const, reason: 'attempts' as const, retryAt };
123
+ }
124
+ const nextState = current.state === 'open' ? 'half_open' : 'closed';
125
+ await repository.update({
126
+ filterByTk: current.id,
127
+ values: { state: nextState, attempts: current.attempts + 1 },
128
+ transaction,
129
+ });
130
+ return { allowed: true as const, state: nextState, attempt: current.attempts + 1 };
131
+ });
132
+ if (decision.allowed) return decision;
133
+ if (decision.reason === 'probe') throw new Error('Circuit breaker probe is already in progress.');
134
+ if (decision.reason === 'attempts') throw new Error('Circuit breaker maximum attempts reached.');
135
+ throw new Error(`Circuit breaker is open until ${decision.retryAt?.toISOString() || 'manual reset'}.`);
136
+ });
137
+ }
138
+
139
+ async recordSuccess(patternId: number, scopeKey: string, lastRunId?: number) {
140
+ const normalizedScope = normalizeScopeKey(scopeKey);
141
+ return this.withScopeLock(patternId, normalizedScope, async () =>
142
+ this.database.sequelize.transaction(async (transaction) => {
143
+ const repository = this.database.getRepository('agentLoopCircuitStates');
144
+ const record = await repository.findOne({
145
+ filter: { patternId, scopeKey: normalizedScope },
146
+ transaction,
147
+ lock: transaction.LOCK.UPDATE,
148
+ });
149
+ if (!record) return;
150
+ await repository.update({
151
+ filterByTk: read(record, 'id'),
152
+ values: {
153
+ state: 'closed',
154
+ attempts: 0,
155
+ consecutiveFailures: 0,
156
+ errorSignature: null,
157
+ repeatedErrorCount: 0,
158
+ lastRunId: lastRunId || null,
159
+ openedAt: null,
160
+ retryAt: null,
161
+ },
162
+ transaction,
163
+ });
164
+ }),
165
+ );
166
+ }
167
+
168
+ async recordFailure(input: {
169
+ patternId: number;
170
+ scopeKey: string;
171
+ policy: LoopPatternPolicy['circuit'];
172
+ error: unknown;
173
+ lastRunId?: number;
174
+ now?: Date;
175
+ }) {
176
+ const scopeKey = normalizeScopeKey(input.scopeKey);
177
+ const signature = normalizeErrorSignature(input.error);
178
+ const now = input.now || new Date();
179
+ return this.withScopeLock(input.patternId, scopeKey, async () =>
180
+ this.database.sequelize.transaction(async (transaction) => {
181
+ const repository = this.database.getRepository('agentLoopCircuitStates');
182
+ let record = await repository.findOne({
183
+ filter: { patternId: input.patternId, scopeKey },
184
+ transaction,
185
+ lock: transaction.LOCK.UPDATE,
186
+ });
187
+ if (!record) {
188
+ record = await repository.create({
189
+ values: {
190
+ patternId: input.patternId,
191
+ scopeKey,
192
+ state: 'closed',
193
+ attempts: 1,
194
+ consecutiveFailures: 0,
195
+ repeatedErrorCount: 0,
196
+ },
197
+ transaction,
198
+ });
199
+ }
200
+ const current = snapshot(record);
201
+ const consecutiveFailures = current.consecutiveFailures + 1;
202
+ const repeatedErrorCount = current.errorSignature === signature ? current.repeatedErrorCount + 1 : 1;
203
+ const shouldOpen =
204
+ current.state === 'half_open' ||
205
+ current.attempts >= input.policy.maxAttempts ||
206
+ consecutiveFailures >= input.policy.maxConsecutiveFailures ||
207
+ repeatedErrorCount >= input.policy.maxRepeatedError;
208
+ await repository.update({
209
+ filterByTk: current.id,
210
+ values: {
211
+ state: shouldOpen ? 'open' : 'closed',
212
+ consecutiveFailures,
213
+ errorSignature: signature,
214
+ repeatedErrorCount,
215
+ lastRunId: input.lastRunId || null,
216
+ openedAt: shouldOpen ? now : null,
217
+ retryAt: shouldOpen ? new Date(now.getTime() + input.policy.cooldownMs) : null,
218
+ },
219
+ transaction,
220
+ });
221
+ return { open: shouldOpen, signature, consecutiveFailures, repeatedErrorCount };
222
+ }),
223
+ );
224
+ }
225
+
226
+ private withScopeLock<T>(patternId: number, scopeKey: string, operation: () => Promise<T>) {
227
+ const normalizedScope = scopeKey.trim();
228
+ if (!normalizedScope) throw new Error('Circuit breaker scope key is required.');
229
+ return this.distributedLock.runExclusive(
230
+ `agent-loop:circuit:${patternId}:${createHash('sha256').update(normalizedScope).digest('hex')}`,
231
+ operation,
232
+ 30_000,
233
+ );
234
+ }
235
+ }
@@ -31,7 +31,7 @@ type SpanValues = {
31
31
  employeeUsername?: string;
32
32
  toolName?: string;
33
33
  title?: string;
34
- input?: any;
34
+ input?: Record<string, unknown>;
35
35
  output?: string;
36
36
  error?: string;
37
37
  durationMs?: number;
@@ -39,12 +39,24 @@ type SpanValues = {
39
39
  endedAt?: Date;
40
40
  orchestratorLogId?: string | number;
41
41
  skillExecutionId?: string | number;
42
- metadata?: any;
42
+ metadata?: Record<string, unknown>;
43
43
  userId?: string | number;
44
44
  };
45
45
 
46
46
  export class ExecutionSpanService {
47
- constructor(private readonly plugin: any) {}
47
+ constructor(
48
+ private readonly plugin: {
49
+ app: { logger?: { warn?: (...args: unknown[]) => void } };
50
+ db: {
51
+ getRepository: (name: string) =>
52
+ | {
53
+ create: (opts: Record<string, unknown>) => Promise<unknown>;
54
+ update: (opts: Record<string, unknown>) => Promise<unknown>;
55
+ }
56
+ | undefined;
57
+ };
58
+ },
59
+ ) {}
48
60
 
49
61
  async create(values: SpanValues) {
50
62
  try {
@@ -65,7 +77,7 @@ export class ExecutionSpanService {
65
77
  }
66
78
  }
67
79
 
68
- async update(spanId: string | number | undefined, values: Record<string, any>) {
80
+ async update(spanId: string | number | undefined, values: Record<string, unknown>) {
69
81
  if (!spanId) return null;
70
82
  try {
71
83
  const repo = this.plugin.db.getRepository('agentExecutionSpans');
@@ -88,7 +100,7 @@ export class ExecutionSpanService {
88
100
  spanId: string | number | undefined,
89
101
  status: 'success' | 'error' | 'canceled' | 'timeout',
90
102
  startedAt: number,
91
- values: Record<string, any> = {},
103
+ values: Record<string, unknown> = {},
92
104
  ) {
93
105
  return this.update(spanId, {
94
106
  ...values,
@@ -99,23 +111,36 @@ export class ExecutionSpanService {
99
111
  }
100
112
  }
101
113
 
102
- export function getOrchestratorTraceContext(ctx: any): OrchestratorTraceContext | null {
114
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
115
+ type NocoCtx = Record<string, unknown> & { state?: Record<string, unknown>; runtime?: Record<string, unknown> };
116
+
117
+ function deepGet(obj: unknown, path: string): unknown {
118
+ return path.split('.').reduce<unknown>((current, key) => {
119
+ if (current && typeof current === 'object') return (current as Record<string, unknown>)[key];
120
+ return undefined;
121
+ }, obj);
122
+ }
123
+
124
+ export function getOrchestratorTraceContext(ctx: NocoCtx): OrchestratorTraceContext | null {
103
125
  const requestContext =
104
- ctx?.[ORCHESTRATOR_TRACE_CONTEXT_KEY] ||
105
- ctx?.state?.orchestratorTraceContext ||
106
- ctx?.runtime?.context?.orchestratorTraceContext ||
126
+ ctx[ORCHESTRATOR_TRACE_CONTEXT_KEY] ||
127
+ deepGet(ctx, 'state.orchestratorTraceContext') ||
128
+ deepGet(ctx, 'runtime.context.orchestratorTraceContext') ||
107
129
  null;
108
130
  const agentContext = getAgentExecutionContext();
109
131
  if (!requestContext && !agentContext) return null;
110
132
 
111
133
  return {
112
134
  ...(agentContext || {}),
113
- ...(requestContext || {}),
114
- toolCallId: ctx?.runtime?.toolCallId || requestContext?.toolCallId || agentContext?.toolCallId,
135
+ ...((requestContext as Record<string, unknown>) || {}),
136
+ toolCallId:
137
+ deepGet(ctx, 'runtime.toolCallId') ||
138
+ (requestContext as Record<string, unknown>)?.toolCallId ||
139
+ agentContext?.toolCallId,
115
140
  };
116
141
  }
117
142
 
118
- export function setOrchestratorTraceContext(ctx: any, traceContext: OrchestratorTraceContext) {
143
+ export function setOrchestratorTraceContext(ctx: NocoCtx, traceContext: OrchestratorTraceContext) {
119
144
  ctx[ORCHESTRATOR_TRACE_CONTEXT_KEY] = traceContext;
120
145
  return ctx;
121
146
  }
@@ -1,6 +1,7 @@
1
1
  import type { Database, Model, Transaction } from '@nocobase/database';
2
2
  import { parseHarnessSettings, validateHarnessSettings } from './HarnessSchema';
3
3
  import type { HarnessSettings } from './HarnessSchema';
4
+ import { read } from '../utils/record-utils';
4
5
 
5
6
  type HarnessProfileVersion = {
6
7
  id: number;
@@ -13,11 +14,6 @@ type HarnessProfileVersion = {
13
14
  publishedAt?: Date | null;
14
15
  };
15
16
 
16
- function read(record: Model | Record<string, unknown>, key: string) {
17
- const model = record as Model & { get?: (name: string) => unknown };
18
- return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
19
- }
20
-
21
17
  function positiveId(value: unknown, label: string) {
22
18
  const parsed = typeof value === 'number' ? value : Number(value);
23
19
  if (!Number.isSafeInteger(parsed) || parsed <= 0) {