plugin-agent-orchestrator 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/README.md +204 -114
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/117.7565cff57c39318a.js +10 -0
  4. package/dist/client-v2/214.106635011859dede.js +10 -0
  5. package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
  6. package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
  7. package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
  8. package/dist/client-v2/index.js +1 -1
  9. package/dist/externalVersion.js +7 -8
  10. package/dist/locale/en-US.json +226 -170
  11. package/dist/locale/vi-VN.json +226 -170
  12. package/dist/locale/zh-CN.json +226 -170
  13. package/dist/server/collections/agent-execution-spans.js +8 -0
  14. package/dist/server/collections/agent-loop-action-approvals.js +1 -0
  15. package/dist/server/collections/agent-loop-runs.js +7 -1
  16. package/dist/server/collections/agent-loop-steps.js +7 -0
  17. package/dist/server/collections/skill-executions.js +8 -0
  18. package/dist/server/plugin.js +3 -1
  19. package/dist/server/resources/agent-harness-profile.js +117 -0
  20. package/dist/server/resources/agent-knowledge-insights.js +1 -3
  21. package/dist/server/resources/agent-loop-approval.js +25 -0
  22. package/dist/server/resources/agent-loop.js +3 -1
  23. package/dist/server/services/AgentMemoryContextService.js +34 -0
  24. package/dist/server/services/HarnessCompiler.js +35 -2
  25. package/dist/server/services/HarnessProfileService.js +74 -9
  26. package/dist/server/services/HarnessSchema.js +30 -3
  27. package/dist/server/services/LoopPatternSchema.js +16 -1
  28. package/dist/server/services/LoopRunRepository.js +80 -0
  29. package/dist/server/services/LoopRunStateMachine.js +92 -3
  30. package/dist/server/services/LoopTriggerService.js +37 -0
  31. package/dist/server/services/LoopWorkerService.js +261 -23
  32. package/dist/server/services/NativeSubAgentObserver.js +165 -23
  33. package/dist/server/services/PluginAiRuntimeAdapter.js +16 -5
  34. package/dist/server/services/ToolLoopDetectionService.js +210 -0
  35. package/dist/server/services/VerificationService.js +66 -0
  36. package/dist/server/services/harness-runtime-policy.js +139 -0
  37. package/dist/server/skill-hub/plugin.js +36 -3
  38. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
  39. package/package.json +53 -53
  40. package/src/client/ApprovalsTab.tsx +2 -0
  41. package/src/client/OrchestratorSettings.tsx +11 -0
  42. package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
  43. package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
  44. package/src/client/skill-hub/index.tsx +0 -52
  45. package/src/client-v2/components/AgentRunsTab.tsx +576 -576
  46. package/src/client-v2/components/ApprovalsTab.tsx +337 -0
  47. package/src/client-v2/components/HarnessProfilesTab.tsx +385 -105
  48. package/src/client-v2/components/MemoryInspectorTab.tsx +141 -141
  49. package/src/client-v2/components/TracingTab.tsx +515 -515
  50. package/src/client-v2/hooks/useApiRequest.ts +141 -141
  51. package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
  52. package/src/client-v2/plugin.tsx +6 -6
  53. package/src/client-v2/skill-hub/components/SkillMetrics.tsx +5 -2
  54. package/src/locale/en-US.json +226 -174
  55. package/src/locale/vi-VN.json +226 -174
  56. package/src/locale/zh-CN.json +226 -174
  57. package/src/server/__tests__/circuit-breaker.test.ts +248 -248
  58. package/src/server/__tests__/harness-compiler.test.ts +83 -0
  59. package/src/server/__tests__/harness-profile-service.test.ts +51 -0
  60. package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
  61. package/src/server/__tests__/harness-tool-plan.test.ts +24 -0
  62. package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
  63. package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
  64. package/src/server/__tests__/loop-budget-service.test.ts +255 -255
  65. package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -266
  66. package/src/server/__tests__/loop-pattern-schema.test.ts +18 -1
  67. package/src/server/__tests__/loop-pattern-service.test.ts +148 -148
  68. package/src/server/__tests__/loop-run-state-machine.test.ts +11 -0
  69. package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
  70. package/src/server/__tests__/loop-worker-claim.test.ts +341 -341
  71. package/src/server/__tests__/loop-worker-execution.test.ts +82 -1
  72. package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
  73. package/src/server/__tests__/path-lock-service.test.ts +254 -254
  74. package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
  75. package/src/server/__tests__/smoke.test.ts +162 -162
  76. package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
  77. package/src/server/collections/agent-execution-spans.ts +8 -0
  78. package/src/server/collections/agent-harness-profile-versions.ts +26 -26
  79. package/src/server/collections/agent-harness-profiles.ts +71 -71
  80. package/src/server/collections/agent-loop-action-approvals.ts +1 -0
  81. package/src/server/collections/agent-loop-artifacts.ts +25 -25
  82. package/src/server/collections/agent-loop-circuit-states.ts +23 -23
  83. package/src/server/collections/agent-loop-control-settings.ts +21 -21
  84. package/src/server/collections/agent-loop-events.ts +98 -98
  85. package/src/server/collections/agent-loop-path-locks.ts +27 -27
  86. package/src/server/collections/agent-loop-patterns.ts +42 -42
  87. package/src/server/collections/agent-loop-runs.ts +7 -1
  88. package/src/server/collections/agent-loop-steps.ts +7 -0
  89. package/src/server/collections/agent-loop-usage-buckets.ts +22 -22
  90. package/src/server/collections/agent-loop-worktrees.ts +25 -25
  91. package/src/server/collections/skill-executions.ts +8 -0
  92. package/src/server/migrations/20260427000002-change-packages-to-text.ts +52 -52
  93. package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -47
  94. package/src/server/migrations/20260429000001-fix-inputargs-json-to-text.ts +45 -45
  95. package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -33
  96. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -31
  97. package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -293
  98. package/src/server/plugin.ts +3 -1
  99. package/src/server/resources/agent-harness-profile.ts +94 -0
  100. package/src/server/resources/agent-knowledge-insights.ts +5 -3
  101. package/src/server/resources/agent-loop-approval.ts +32 -0
  102. package/src/server/resources/agent-loop-artifact.ts +56 -56
  103. package/src/server/resources/agent-loop-events-stream.ts +105 -105
  104. package/src/server/resources/agent-loop.ts +3 -1
  105. package/src/server/resources/resource-helpers.ts +33 -33
  106. package/src/server/resources/tracing.ts +266 -266
  107. package/src/server/services/AgentMemoryContextService.ts +44 -0
  108. package/src/server/services/DurableCircuitBreakerService.ts +239 -239
  109. package/src/server/services/ExecutionSpanService.ts +2 -0
  110. package/src/server/services/HarnessCompiler.ts +37 -0
  111. package/src/server/services/HarnessProfileService.ts +92 -10
  112. package/src/server/services/HarnessSchema.ts +31 -0
  113. package/src/server/services/LoopBudgetService.ts +275 -275
  114. package/src/server/services/LoopControlService.ts +124 -124
  115. package/src/server/services/LoopPatternSchema.ts +19 -1
  116. package/src/server/services/LoopPatternService.ts +143 -143
  117. package/src/server/services/LoopRunRepository.ts +99 -0
  118. package/src/server/services/LoopRunStateMachine.ts +100 -3
  119. package/src/server/services/LoopSchedulerService.ts +199 -199
  120. package/src/server/services/LoopTriggerService.ts +42 -0
  121. package/src/server/services/LoopWorkerService.ts +327 -27
  122. package/src/server/services/NativeSubAgentObserver.ts +186 -21
  123. package/src/server/services/PathLockService.ts +321 -321
  124. package/src/server/services/PluginAiRuntimeAdapter.ts +24 -7
  125. package/src/server/services/ToolLoopDetectionService.ts +213 -0
  126. package/src/server/services/VerificationSchema.ts +31 -31
  127. package/src/server/services/VerificationService.ts +81 -2
  128. package/src/server/services/harness-runtime-policy.ts +141 -0
  129. package/src/server/skill-hub/plugin.ts +41 -3
  130. package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -235
  131. package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -61
  132. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
  133. package/src/server/utils/ensure-indexes.ts +96 -96
  134. package/src/server/utils/logging.ts +62 -62
  135. package/src/server/utils/loop-pattern-context.ts +20 -20
  136. package/dist/client-v2/214.b063f33ba044a808.js +0 -10
  137. package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
  138. package/dist/client-v2/418.58fa350f5496efd3.js +0 -10
  139. package/dist/client-v2/53.9a10455323390f14.js +0 -10
  140. package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
  141. package/dist/client-v2/925.e5925bf21ed68e7a.js +0 -10
  142. package/src/client/AIEmployeeSelect.tsx +0 -47
  143. package/src/client/AIEmployeesContext.tsx +0 -102
  144. package/src/client/RulesTab.tsx +0 -2
  145. package/src/client/TracingTab.tsx +0 -436
  146. package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
  147. package/src/client-v2/components/RulesTab.tsx +0 -2
  148. package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
@@ -1,124 +1,124 @@
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
+
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
+ }
@@ -54,8 +54,26 @@ export const loopPatternPolicySchema = z
54
54
  maxAttempts: z.number().int().positive().default(2),
55
55
  })
56
56
  .default({}),
57
+ loopDetection: z
58
+ .object({
59
+ enabled: z.boolean().default(true),
60
+ warnAt: z.number().int().positive().default(3),
61
+ blockAt: z.number().int().positive().default(5),
62
+ escalateAt: z.number().int().positive().default(8),
63
+ })
64
+ .default({}),
57
65
  })
58
- .strict();
66
+ .strict()
67
+ .superRefine((policy, context) => {
68
+ const { warnAt, blockAt, escalateAt } = policy.loopDetection;
69
+ if (!(warnAt < blockAt && blockAt < escalateAt)) {
70
+ context.addIssue({
71
+ code: z.ZodIssueCode.custom,
72
+ path: ['loopDetection'],
73
+ message: 'Loop detection thresholds must satisfy warnAt < blockAt < escalateAt.',
74
+ });
75
+ }
76
+ });
59
77
 
60
78
  export const loopPatternSchema = z
61
79
  .object({
@@ -1,143 +1,143 @@
1
- import type { Database, Model } from '@nocobase/database';
2
- import { compileHarness } from './HarnessCompiler';
3
- import type { CompiledHarness, HarnessLayer } from './HarnessCompiler';
4
- import { HarnessProfileService } from './HarnessProfileService';
5
- import { parseLoopPattern } from './LoopPatternSchema';
6
- import type { LoopPattern } from './LoopPatternSchema';
7
-
8
- export type WorktreeCapability = {
9
- available: boolean;
10
- provider?: string;
11
- };
12
-
13
- export type EmployeeHarnessResolver = (username: string) => Promise<unknown>;
14
-
15
- export type HarnessSnapshot = {
16
- tag: string;
17
- versionId: number;
18
- version: number;
19
- schemaVersion: number;
20
- effective: CompiledHarness;
21
- };
22
-
23
- export type CompiledPatternSnapshot = {
24
- pattern: LoopPattern;
25
- roleBindings: {
26
- leader: string;
27
- makers: string[];
28
- verifier: string;
29
- };
30
- leaderHarness: HarnessSnapshot;
31
- makerHarnesses: Record<string, HarnessSnapshot>;
32
- verifierHarness: HarnessSnapshot;
33
- policy: LoopPattern['policy'];
34
- };
35
-
36
- const platformHarness = {
37
- tools: {},
38
- memory: { maxChars: 20_000 },
39
- delegation: { maxDepth: 8, maxCount: 100 },
40
- limits: { timeoutMs: 3_600_000, recursionLimit: 100, maxTotalTokens: 1_000_000, maxCost: 1000 },
41
- isolation: { networkAccess: 'allow' },
42
- observability: { tracingRetentionDays: 3650 },
43
- };
44
-
45
- function read(record: Model | Record<string, unknown>, key: string) {
46
- const model = record as Model & { get?: (name: string) => unknown };
47
- return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
48
- }
49
-
50
- function toPlain(record: Model | Record<string, unknown>) {
51
- return typeof (record as Model).toJSON === 'function'
52
- ? ((record as Model).toJSON() as Record<string, unknown>)
53
- : (record as Record<string, unknown>);
54
- }
55
-
56
- export class LoopPatternService {
57
- private readonly harnessProfiles: HarnessProfileService;
58
-
59
- constructor(
60
- private readonly database: Database,
61
- private readonly resolveEmployeeHarness: EmployeeHarnessResolver,
62
- private readonly worktreeCapability: () => Promise<WorktreeCapability>,
63
- ) {
64
- this.harnessProfiles = new HarnessProfileService(database);
65
- }
66
-
67
- async get(patternId: number) {
68
- const record = await this.database.getRepository('agentLoopPatterns').findOne({ filterByTk: patternId });
69
- if (!record) throw new Error(`Loop pattern ${patternId} was not found.`);
70
- return { id: Number(read(record, 'id')), pattern: parseLoopPattern(toPlain(record)) };
71
- }
72
-
73
- async validate(value: unknown) {
74
- const pattern = parseLoopPattern(value);
75
- await this.assertCapabilities(pattern);
76
- return pattern;
77
- }
78
-
79
- async compile(patternId: number, perRunHarness?: unknown): Promise<CompiledPatternSnapshot> {
80
- const { pattern } = await this.get(patternId);
81
- if (!pattern.enabled) throw new Error(`Loop pattern ${pattern.key} is disabled.`);
82
- await this.assertCapabilities(pattern);
83
-
84
- const makerUsernames = pattern.makerUsernames.length ? pattern.makerUsernames : [pattern.leaderUsername];
85
- const [leaderHarness, verifierHarness, ...makerSnapshots] = await Promise.all([
86
- this.compileRole(pattern.leaderHarnessTag, pattern.leaderUsername, pattern.policy.harness, perRunHarness),
87
- this.compileRole(pattern.verifierHarnessTag, pattern.verifierUsername, pattern.policy.harness, perRunHarness),
88
- // Every maker gets its own snapshot: employee-level harness overrides differ per username,
89
- // so reusing the first maker's compilation would grant or deny the wrong tools.
90
- ...makerUsernames.map((username) =>
91
- this.compileRole(pattern.makerHarnessTag, username, pattern.policy.harness, perRunHarness),
92
- ),
93
- ]);
94
- const makerHarnesses = Object.fromEntries(
95
- makerUsernames.map((username, index) => [username, makerSnapshots[index]]),
96
- );
97
-
98
- return {
99
- pattern,
100
- roleBindings: {
101
- leader: pattern.leaderUsername,
102
- // The effective list, not the raw pattern array. A pattern with no makers falls back to the
103
- // leader (line above), and `makerHarnesses` is keyed by that same list; returning the raw
104
- // empty array here would make the worker iterate zero makers while the harness map holds one,
105
- // so the execution phase would silently never run.
106
- makers: [...makerUsernames],
107
- verifier: pattern.verifierUsername,
108
- },
109
- leaderHarness,
110
- makerHarnesses,
111
- verifierHarness,
112
- policy: structuredClone(pattern.policy),
113
- };
114
- }
115
-
116
- private async compileRole(tag: string, username: string, patternHarness: unknown, perRunHarness?: unknown) {
117
- const published = await this.harnessProfiles.getPublishedByTag(tag);
118
- if (!published) throw new Error(`Harness profile "${tag}" has no published version.`);
119
- const employeeHarness = await this.resolveEmployeeHarness(username);
120
- const layers: HarnessLayer[] = [
121
- { source: 'platform', settings: platformHarness },
122
- { source: `profile:${tag}@${published.version}`, settings: published.settings },
123
- { source: 'pattern', settings: patternHarness },
124
- ];
125
- if (employeeHarness) layers.push({ source: `employee:${username}`, settings: employeeHarness });
126
- if (perRunHarness) layers.push({ source: 'run', settings: perRunHarness });
127
- return {
128
- tag,
129
- versionId: published.id,
130
- version: published.version,
131
- schemaVersion: published.schemaVersion,
132
- effective: compileHarness(layers),
133
- };
134
- }
135
-
136
- private async assertCapabilities(pattern: LoopPattern) {
137
- if (pattern.autonomyLevel === 'L1') return;
138
- const capability = await this.worktreeCapability();
139
- if (!capability.available) {
140
- throw new Error('L2 and L3 patterns require an available worktree provider.');
141
- }
142
- }
143
- }
1
+ import type { Database, Model } from '@nocobase/database';
2
+ import { compileHarness } from './HarnessCompiler';
3
+ import type { CompiledHarness, HarnessLayer } from './HarnessCompiler';
4
+ import { HarnessProfileService } from './HarnessProfileService';
5
+ import { parseLoopPattern } from './LoopPatternSchema';
6
+ import type { LoopPattern } from './LoopPatternSchema';
7
+
8
+ export type WorktreeCapability = {
9
+ available: boolean;
10
+ provider?: string;
11
+ };
12
+
13
+ export type EmployeeHarnessResolver = (username: string) => Promise<unknown>;
14
+
15
+ export type HarnessSnapshot = {
16
+ tag: string;
17
+ versionId: number;
18
+ version: number;
19
+ schemaVersion: number;
20
+ effective: CompiledHarness;
21
+ };
22
+
23
+ export type CompiledPatternSnapshot = {
24
+ pattern: LoopPattern;
25
+ roleBindings: {
26
+ leader: string;
27
+ makers: string[];
28
+ verifier: string;
29
+ };
30
+ leaderHarness: HarnessSnapshot;
31
+ makerHarnesses: Record<string, HarnessSnapshot>;
32
+ verifierHarness: HarnessSnapshot;
33
+ policy: LoopPattern['policy'];
34
+ };
35
+
36
+ const platformHarness = {
37
+ tools: {},
38
+ memory: { maxChars: 20_000 },
39
+ delegation: { maxDepth: 8, maxCount: 100 },
40
+ limits: { timeoutMs: 3_600_000, recursionLimit: 100, maxTotalTokens: 1_000_000, maxCost: 1000 },
41
+ isolation: { networkAccess: 'allow' },
42
+ observability: { tracingRetentionDays: 3650 },
43
+ };
44
+
45
+ function read(record: Model | Record<string, unknown>, key: string) {
46
+ const model = record as Model & { get?: (name: string) => unknown };
47
+ return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
48
+ }
49
+
50
+ function toPlain(record: Model | Record<string, unknown>) {
51
+ return typeof (record as Model).toJSON === 'function'
52
+ ? ((record as Model).toJSON() as Record<string, unknown>)
53
+ : (record as Record<string, unknown>);
54
+ }
55
+
56
+ export class LoopPatternService {
57
+ private readonly harnessProfiles: HarnessProfileService;
58
+
59
+ constructor(
60
+ private readonly database: Database,
61
+ private readonly resolveEmployeeHarness: EmployeeHarnessResolver,
62
+ private readonly worktreeCapability: () => Promise<WorktreeCapability>,
63
+ ) {
64
+ this.harnessProfiles = new HarnessProfileService(database);
65
+ }
66
+
67
+ async get(patternId: number) {
68
+ const record = await this.database.getRepository('agentLoopPatterns').findOne({ filterByTk: patternId });
69
+ if (!record) throw new Error(`Loop pattern ${patternId} was not found.`);
70
+ return { id: Number(read(record, 'id')), pattern: parseLoopPattern(toPlain(record)) };
71
+ }
72
+
73
+ async validate(value: unknown) {
74
+ const pattern = parseLoopPattern(value);
75
+ await this.assertCapabilities(pattern);
76
+ return pattern;
77
+ }
78
+
79
+ async compile(patternId: number, perRunHarness?: unknown): Promise<CompiledPatternSnapshot> {
80
+ const { pattern } = await this.get(patternId);
81
+ if (!pattern.enabled) throw new Error(`Loop pattern ${pattern.key} is disabled.`);
82
+ await this.assertCapabilities(pattern);
83
+
84
+ const makerUsernames = pattern.makerUsernames.length ? pattern.makerUsernames : [pattern.leaderUsername];
85
+ const [leaderHarness, verifierHarness, ...makerSnapshots] = await Promise.all([
86
+ this.compileRole(pattern.leaderHarnessTag, pattern.leaderUsername, pattern.policy.harness, perRunHarness),
87
+ this.compileRole(pattern.verifierHarnessTag, pattern.verifierUsername, pattern.policy.harness, perRunHarness),
88
+ // Every maker gets its own snapshot: employee-level harness overrides differ per username,
89
+ // so reusing the first maker's compilation would grant or deny the wrong tools.
90
+ ...makerUsernames.map((username) =>
91
+ this.compileRole(pattern.makerHarnessTag, username, pattern.policy.harness, perRunHarness),
92
+ ),
93
+ ]);
94
+ const makerHarnesses = Object.fromEntries(
95
+ makerUsernames.map((username, index) => [username, makerSnapshots[index]]),
96
+ );
97
+
98
+ return {
99
+ pattern,
100
+ roleBindings: {
101
+ leader: pattern.leaderUsername,
102
+ // The effective list, not the raw pattern array. A pattern with no makers falls back to the
103
+ // leader (line above), and `makerHarnesses` is keyed by that same list; returning the raw
104
+ // empty array here would make the worker iterate zero makers while the harness map holds one,
105
+ // so the execution phase would silently never run.
106
+ makers: [...makerUsernames],
107
+ verifier: pattern.verifierUsername,
108
+ },
109
+ leaderHarness,
110
+ makerHarnesses,
111
+ verifierHarness,
112
+ policy: structuredClone(pattern.policy),
113
+ };
114
+ }
115
+
116
+ private async compileRole(tag: string, username: string, patternHarness: unknown, perRunHarness?: unknown) {
117
+ const published = await this.harnessProfiles.getPublishedByTag(tag);
118
+ if (!published) throw new Error(`Harness profile "${tag}" has no published version.`);
119
+ const employeeHarness = await this.resolveEmployeeHarness(username);
120
+ const layers: HarnessLayer[] = [
121
+ { source: 'platform', settings: platformHarness },
122
+ { source: `profile:${tag}@${published.version}`, settings: published.settings },
123
+ { source: 'pattern', settings: patternHarness },
124
+ ];
125
+ if (employeeHarness) layers.push({ source: `employee:${username}`, settings: employeeHarness });
126
+ if (perRunHarness) layers.push({ source: 'run', settings: perRunHarness });
127
+ return {
128
+ tag,
129
+ versionId: published.id,
130
+ version: published.version,
131
+ schemaVersion: published.schemaVersion,
132
+ effective: compileHarness(layers),
133
+ };
134
+ }
135
+
136
+ private async assertCapabilities(pattern: LoopPattern) {
137
+ if (pattern.autonomyLevel === 'L1') return;
138
+ const capability = await this.worktreeCapability();
139
+ if (!capability.available) {
140
+ throw new Error('L2 and L3 patterns require an available worktree provider.');
141
+ }
142
+ }
143
+ }