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,124 +1,120 @@
1
- import type { Database, Model, Transaction } from '@nocobase/database';
2
-
3
- export type LoopControlState = 'running' | 'paused' | 'killed';
4
-
5
- export type LoopControlSnapshot = {
6
- id: number;
7
- acceptNewRuns: boolean;
8
- state: LoopControlState;
9
- reason: string;
10
- globalMaxConcurrency: number;
11
- dailyMaxTokens: number | null;
12
- dailyMaxCost: number | null;
13
- };
14
-
15
- function read(record: Model | Record<string, unknown>, key: string) {
16
- const model = record as Model & { get?: (name: string) => unknown };
17
- return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
18
- }
19
-
20
- function optionalLimit(value: unknown, label: string) {
21
- if (value === null || value === undefined) return null;
22
- const parsed = Number(value);
23
- if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`${label} is invalid.`);
24
- return parsed;
25
- }
26
-
27
- function snapshot(record: Model | Record<string, unknown>): LoopControlSnapshot {
28
- const id = Number(read(record, 'id'));
29
- const state = read(record, 'state');
30
- const maxConcurrency = Number(read(record, 'globalMaxConcurrency'));
31
- if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Global Loop Control settings have an invalid identifier.');
32
- if (state !== 'running' && state !== 'paused' && state !== 'killed') {
33
- throw new Error('Global Loop Control state is invalid.');
34
- }
35
- if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency <= 0) {
36
- throw new Error('Global Loop Control concurrency is invalid.');
37
- }
38
- return {
39
- id,
40
- acceptNewRuns: read(record, 'acceptNewRuns') === true,
41
- state,
42
- reason: typeof read(record, 'reason') === 'string' ? String(read(record, 'reason')) : '',
43
- globalMaxConcurrency: maxConcurrency,
44
- dailyMaxTokens: optionalLimit(read(record, 'dailyMaxTokens'), 'Global daily token limit'),
45
- dailyMaxCost: optionalLimit(read(record, 'dailyMaxCost'), 'Global daily cost limit'),
46
- };
47
- }
48
-
49
- export class LoopControlService {
50
- constructor(private readonly database: Database) {}
51
-
52
- async get(transaction?: Transaction) {
53
- const repository = this.database.getRepository('agentLoopControlSettings');
54
- let record = await repository.findOne({ filter: { key: 'global' }, transaction });
55
- if (!record) {
56
- record = await repository.create({
57
- values: {
58
- key: 'global',
59
- acceptNewRuns: true,
60
- state: 'running',
61
- globalMaxConcurrency: 5,
62
- createdAt: new Date(),
63
- updatedAt: new Date(),
64
- },
65
- transaction,
66
- });
67
- }
68
- return snapshot(record);
69
- }
70
-
71
- async getForUpdate(transaction: Transaction) {
72
- const repository = this.database.getRepository('agentLoopControlSettings');
73
- const record = await repository.findOne({
74
- filter: { key: 'global' },
75
- transaction,
76
- lock: transaction.LOCK.UPDATE,
77
- });
78
- if (!record) throw new Error('Global Loop Control settings were not found.');
79
- return snapshot(record);
80
- }
81
-
82
- async assertCanEnqueue(transaction?: Transaction) {
83
- const control = await this.get(transaction);
84
- if (!control.acceptNewRuns || control.state !== 'running') {
85
- throw new Error(control.reason || `Loop Control Plane is ${control.state}; new runs are disabled.`);
86
- }
87
- return control;
88
- }
89
-
90
- async assertCanExecute(transaction?: Transaction) {
91
- const control = await this.get(transaction);
92
- if (control.state !== 'running') {
93
- throw new Error(control.reason || `Loop Control Plane is ${control.state}.`);
94
- }
95
- return control;
96
- }
97
-
98
- async update(input: { state: LoopControlState; acceptNewRuns: boolean; reason: string; changedById?: number }) {
99
- return this.database.sequelize.transaction(async (transaction) => {
100
- const repository = this.database.getRepository('agentLoopControlSettings');
101
- const current = await this.get(transaction);
102
- const record = await repository.findOne({
103
- filterByTk: current.id,
104
- transaction,
105
- lock: transaction.LOCK.UPDATE,
106
- });
107
- if (!record) throw new Error('Global Loop Control settings were not found.');
108
- await repository.update({
109
- filterByTk: current.id,
110
- values: {
111
- state: input.state,
112
- acceptNewRuns: input.acceptNewRuns,
113
- reason: input.reason,
114
- changedById: input.changedById || null,
115
- changedAt: new Date(),
116
- },
117
- transaction,
118
- });
119
- const updated = await repository.findOne({ filterByTk: current.id, transaction });
120
- if (!updated) throw new Error('Global Loop Control settings were not found after update.');
121
- return snapshot(updated);
122
- });
123
- }
124
- }
1
+ import type { Database, Model, Transaction } from '@nocobase/database';
2
+ import { read } from '../utils/record-utils';
3
+
4
+ export type LoopControlState = 'running' | 'paused' | 'killed';
5
+
6
+ export type LoopControlSnapshot = {
7
+ id: number;
8
+ acceptNewRuns: boolean;
9
+ state: LoopControlState;
10
+ reason: string;
11
+ globalMaxConcurrency: number;
12
+ dailyMaxTokens: number | null;
13
+ dailyMaxCost: number | null;
14
+ };
15
+
16
+ function optionalLimit(value: unknown, label: string) {
17
+ if (value === null || value === undefined) return null;
18
+ const parsed = Number(value);
19
+ if (!Number.isFinite(parsed) || parsed < 0) throw new Error(`${label} is invalid.`);
20
+ return parsed;
21
+ }
22
+
23
+ function snapshot(record: Model | Record<string, unknown>): LoopControlSnapshot {
24
+ const id = Number(read(record, 'id'));
25
+ const state = read(record, 'state');
26
+ const maxConcurrency = Number(read(record, 'globalMaxConcurrency'));
27
+ if (!Number.isSafeInteger(id) || id <= 0) throw new Error('Global Loop Control settings have an invalid identifier.');
28
+ if (state !== 'running' && state !== 'paused' && state !== 'killed') {
29
+ throw new Error('Global Loop Control state is invalid.');
30
+ }
31
+ if (!Number.isSafeInteger(maxConcurrency) || maxConcurrency <= 0) {
32
+ throw new Error('Global Loop Control concurrency is invalid.');
33
+ }
34
+ return {
35
+ id,
36
+ acceptNewRuns: read(record, 'acceptNewRuns') === true,
37
+ state,
38
+ reason: typeof read(record, 'reason') === 'string' ? String(read(record, 'reason')) : '',
39
+ globalMaxConcurrency: maxConcurrency,
40
+ dailyMaxTokens: optionalLimit(read(record, 'dailyMaxTokens'), 'Global daily token limit'),
41
+ dailyMaxCost: optionalLimit(read(record, 'dailyMaxCost'), 'Global daily cost limit'),
42
+ };
43
+ }
44
+
45
+ export class LoopControlService {
46
+ constructor(private readonly database: Database) {}
47
+
48
+ async get(transaction?: Transaction) {
49
+ const repository = this.database.getRepository('agentLoopControlSettings');
50
+ let record = await repository.findOne({ filter: { key: 'global' }, transaction });
51
+ if (!record) {
52
+ record = await repository.create({
53
+ values: {
54
+ key: 'global',
55
+ acceptNewRuns: true,
56
+ state: 'running',
57
+ globalMaxConcurrency: 5,
58
+ createdAt: new Date(),
59
+ updatedAt: new Date(),
60
+ },
61
+ transaction,
62
+ });
63
+ }
64
+ return snapshot(record);
65
+ }
66
+
67
+ async getForUpdate(transaction: Transaction) {
68
+ const repository = this.database.getRepository('agentLoopControlSettings');
69
+ const record = await repository.findOne({
70
+ filter: { key: 'global' },
71
+ transaction,
72
+ lock: transaction.LOCK.UPDATE,
73
+ });
74
+ if (!record) throw new Error('Global Loop Control settings were not found.');
75
+ return snapshot(record);
76
+ }
77
+
78
+ async assertCanEnqueue(transaction?: Transaction) {
79
+ const control = await this.get(transaction);
80
+ if (!control.acceptNewRuns || control.state !== 'running') {
81
+ throw new Error(control.reason || `Loop Control Plane is ${control.state}; new runs are disabled.`);
82
+ }
83
+ return control;
84
+ }
85
+
86
+ async assertCanExecute(transaction?: Transaction) {
87
+ const control = await this.get(transaction);
88
+ if (control.state !== 'running') {
89
+ throw new Error(control.reason || `Loop Control Plane is ${control.state}.`);
90
+ }
91
+ return control;
92
+ }
93
+
94
+ async update(input: { state: LoopControlState; acceptNewRuns: boolean; reason: string; changedById?: number }) {
95
+ return this.database.sequelize.transaction(async (transaction) => {
96
+ const repository = this.database.getRepository('agentLoopControlSettings');
97
+ const current = await this.get(transaction);
98
+ const record = await repository.findOne({
99
+ filterByTk: current.id,
100
+ transaction,
101
+ lock: transaction.LOCK.UPDATE,
102
+ });
103
+ if (!record) throw new Error('Global Loop Control settings were not found.');
104
+ await repository.update({
105
+ filterByTk: current.id,
106
+ values: {
107
+ state: input.state,
108
+ acceptNewRuns: input.acceptNewRuns,
109
+ reason: input.reason,
110
+ changedById: input.changedById || null,
111
+ changedAt: new Date(),
112
+ },
113
+ transaction,
114
+ });
115
+ const updated = await repository.findOne({ filterByTk: current.id, transaction });
116
+ if (!updated) throw new Error('Global Loop Control settings were not found after update.');
117
+ return snapshot(updated);
118
+ });
119
+ }
120
+ }
@@ -51,6 +51,16 @@ export const loopPatternPolicySchema = z
51
51
  verification: z
52
52
  .object({
53
53
  requiredChecks: z.array(z.string().min(1)).min(1).default(['goal']),
54
+ // Risk-aware checks that are added to the verifier prompt based on runtime context
55
+ // (e.g. how many files the run touched, whether core paths were affected).
56
+ dynamicChecks: z
57
+ .object({
58
+ codeChangeThreshold: z.number().int().nonnegative().default(10),
59
+ riskPathPatterns: z.array(z.string().min(1)).default([]),
60
+ requireSecurityReview: z.boolean().default(false),
61
+ requirePerformanceReview: z.boolean().default(false),
62
+ })
63
+ .optional(),
54
64
  maxAttempts: z.number().int().positive().default(2),
55
65
  })
56
66
  .default({}),
@@ -104,22 +114,58 @@ export const loopPatternSchema = z
104
114
  baseRef: z.string().trim().min(1).max(200).default('main'),
105
115
  actingOn: z.array(z.string().trim().min(1)).default([]),
106
116
  policy: loopPatternPolicySchema.default({}),
117
+
118
+ // Dynamic role resolution strategies
119
+ roleResolution: z
120
+ .object({
121
+ enabled: z.boolean().default(false),
122
+ leaderStrategy: z.enum(['fixed', 'team-lead', 'round-robin', 'skill-match']).default('fixed'),
123
+ makerStrategy: z.enum(['fixed', 'team-members', 'auto-assign']).default('fixed'),
124
+ verifierStrategy: z.enum(['fixed', 'independent-only']).default('fixed'),
125
+ teamBindings: z
126
+ .array(
127
+ z.object({
128
+ teamKey: z.string().min(1),
129
+ role: z.enum(['leader', 'maker', 'verifier']),
130
+ employeeUsernames: z.array(z.string().min(1)).default([]),
131
+ }),
132
+ )
133
+ .default([]),
134
+ fallbackBehavior: z.enum(['skip', 'fail', 'assign-admin']).default('fail'),
135
+ })
136
+ .optional(),
107
137
  })
108
138
  .superRefine((pattern, context) => {
109
- const makers = new Set(pattern.makerUsernames);
110
- if (pattern.verifierUsername === pattern.leaderUsername || makers.has(pattern.verifierUsername)) {
111
- context.addIssue({
112
- code: z.ZodIssueCode.custom,
113
- path: ['verifierUsername'],
114
- message: 'Verifier must be different from the leader and every maker.',
115
- });
116
- }
117
- if (makers.size !== pattern.makerUsernames.length) {
118
- context.addIssue({
119
- code: z.ZodIssueCode.custom,
120
- path: ['makerUsernames'],
121
- message: 'Maker usernames must be unique.',
122
- });
139
+ // Dynamic role resolution: validate strategy configuration, then skip only the
140
+ // static username checks below. All other validations (cron, L2/L3, etc.) always run.
141
+ if (pattern.roleResolution?.enabled === true) {
142
+ const hasStrategy =
143
+ pattern.roleResolution.leaderStrategy !== 'fixed' ||
144
+ pattern.roleResolution.makerStrategy !== 'fixed' ||
145
+ pattern.roleResolution.verifierStrategy !== 'fixed';
146
+ if (!hasStrategy && !pattern.roleResolution.teamBindings?.length) {
147
+ context.addIssue({
148
+ code: z.ZodIssueCode.custom,
149
+ path: ['roleResolution'],
150
+ message: 'Dynamic role resolution requires at least one non-fixed strategy or team bindings.',
151
+ });
152
+ }
153
+ } else {
154
+ const makers = new Set(pattern.makerUsernames);
155
+ if (pattern.verifierUsername === pattern.leaderUsername || makers.has(pattern.verifierUsername)) {
156
+ context.addIssue({
157
+ code: z.ZodIssueCode.custom,
158
+ path: ['verifierUsername'],
159
+ message: 'Verifier must be different from the leader and every maker.',
160
+ });
161
+ }
162
+ if (makers.size !== pattern.makerUsernames.length) {
163
+ context.addIssue({
164
+ code: z.ZodIssueCode.custom,
165
+ path: ['makerUsernames'],
166
+ message: 'Maker usernames must be unique.',
167
+ });
168
+ }
123
169
  }
124
170
  if (pattern.triggerType === 'cron') {
125
171
  const parts = pattern.cronExpression?.split(/\s+/).filter(Boolean) || [];