plugin-agent-orchestrator 1.1.3 → 1.1.5
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.
- package/README.md +204 -114
- package/dist/client/index.js +1 -1
- package/dist/client-v2/117.7565cff57c39318a.js +10 -0
- package/dist/client-v2/214.106635011859dede.js +10 -0
- package/dist/client-v2/253.59577b40d9875be0.js +10 -0
- package/dist/client-v2/264.7ed8bee71fa5935c.js +10 -0
- package/dist/client-v2/{41.ba6e080cc0488143.js → 41.3deb9e57a0f64fc4.js} +1 -1
- package/dist/client-v2/418.41ed200e7d6da332.js +10 -0
- package/dist/client-v2/53.349fff8db80b19d4.js +10 -0
- package/dist/client-v2/619.0a2144aaffefe018.js +10 -0
- package/dist/client-v2/{70.bda9518881c05360.js → 70.ffff2997c10fd4b0.js} +1 -1
- package/dist/client-v2/{794.9bbb8d3a61b2bdf2.js → 794.a67a2614405ba627.js} +1 -1
- package/dist/client-v2/981.e4a1f41cfc94a856.js +10 -0
- package/dist/client-v2/{993.82778b6fd6db3cb1.js → 993.b0688fdc5ccb000a.js} +1 -1
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +8 -7
- package/dist/locale/en-US.json +199 -123
- package/dist/locale/vi-VN.json +199 -123
- package/dist/locale/zh-CN.json +199 -123
- package/dist/server/collections/agent-execution-spans.js +55 -0
- package/dist/server/collections/agent-harness-profile-versions.js +56 -0
- package/dist/server/collections/agent-harness-profiles.js +12 -0
- package/dist/server/collections/agent-loop-action-approvals.js +69 -0
- package/dist/server/collections/agent-loop-artifacts.js +55 -0
- package/dist/server/collections/agent-loop-circuit-states.js +53 -0
- package/dist/server/collections/agent-loop-control-settings.js +51 -0
- package/dist/server/collections/agent-loop-events.js +27 -0
- package/dist/server/collections/agent-loop-path-locks.js +57 -0
- package/dist/server/collections/agent-loop-patterns.js +72 -0
- package/dist/server/collections/agent-loop-runs.js +170 -3
- package/dist/server/collections/agent-loop-steps.js +76 -0
- package/dist/server/collections/agent-loop-usage-buckets.js +52 -0
- package/dist/server/collections/agent-loop-worktrees.js +55 -0
- package/dist/server/collections/skill-executions.js +8 -0
- package/dist/server/migrations/{20260427000000-change-packages-to-text.js → 20260427000002-change-packages-to-text.js} +2 -0
- package/dist/server/migrations/20260429000000-add-llm-fields.js +3 -2
- package/dist/server/migrations/{20260429000000-fix-inputargs-json-to-text.js → 20260429000001-fix-inputargs-json-to-text.js} +14 -6
- package/dist/server/migrations/20260503000000-add-orchestrator-trace-fields.js +2 -1
- package/dist/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.js +2 -1
- package/dist/server/migrations/20260803010000-backfill-loop-control-plane-data.js +262 -0
- package/dist/server/plugin.js +54 -150
- package/dist/server/resources/agent-harness-profile.js +117 -0
- package/dist/server/resources/agent-knowledge-insights.js +1 -3
- package/dist/server/resources/agent-loop-approval.js +108 -0
- package/dist/server/resources/agent-loop-artifact.js +86 -0
- package/dist/server/resources/agent-loop-events-stream.js +130 -0
- package/dist/server/resources/agent-loop.js +183 -139
- package/dist/server/resources/resource-helpers.js +63 -0
- package/dist/server/resources/tracing.js +121 -107
- package/dist/server/services/AgentMemoryContextService.js +34 -0
- package/dist/server/services/DurableCircuitBreakerService.js +229 -0
- package/dist/server/services/HarnessCompiler.js +175 -0
- package/dist/server/services/HarnessProfileService.js +233 -0
- package/dist/server/services/HarnessSchema.js +194 -0
- package/dist/server/services/LoopBudgetService.js +269 -0
- package/dist/server/services/LoopControlService.js +139 -0
- package/dist/server/services/LoopPatternSchema.js +195 -0
- package/dist/server/services/LoopPatternService.js +132 -0
- package/dist/server/services/LoopRunRepository.js +285 -0
- package/dist/server/services/LoopRunStateMachine.js +478 -0
- package/dist/server/services/LoopSchedulerService.js +193 -0
- package/dist/server/services/LoopTriggerService.js +165 -0
- package/dist/server/services/LoopWorkerService.js +699 -0
- package/dist/server/services/NativeSubAgentObserver.js +165 -23
- package/dist/server/services/PathLockService.js +288 -0
- package/dist/server/services/PluginAiRuntimeAdapter.js +226 -0
- package/dist/server/services/ToolLoopDetectionService.js +210 -0
- package/dist/server/services/VerificationSchema.js +59 -0
- package/dist/server/services/VerificationService.js +235 -0
- package/dist/server/services/harness-runtime-policy.js +139 -0
- package/dist/server/skill-hub/actions/git-import.js +13 -7
- package/dist/server/skill-hub/plugin.js +36 -3
- package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
- package/dist/server/skill-hub/tasks/SkillExecutionTask.js +29 -0
- package/dist/server/utils/ensure-indexes.js +111 -0
- package/dist/server/utils/loop-pattern-context.js +56 -0
- package/package.json +53 -53
- package/src/client/ApprovalsTab.tsx +2 -0
- package/src/client/OrchestratorSettings.tsx +55 -0
- package/src/client/skill-hub/components/GitSkillImport.tsx +3 -3
- package/src/client/skill-hub/components/SkillMetrics.tsx +15 -10
- package/src/client/skill-hub/index.tsx +0 -52
- package/src/client-v2/components/AgentRunsTab.tsx +100 -18
- package/src/client-v2/components/ApprovalsTab.tsx +337 -0
- package/src/client-v2/components/HarnessProfilesTab.tsx +385 -100
- package/src/client-v2/components/MemoryInspectorTab.tsx +141 -125
- package/src/client-v2/components/TracingTab.tsx +160 -77
- package/src/client-v2/hooks/useApiRequest.ts +28 -8
- package/src/client-v2/pages/ApprovalsPage.tsx +10 -0
- package/src/client-v2/plugin.tsx +6 -6
- package/src/client-v2/skill-hub/components/SkillMetrics.tsx +11 -6
- package/src/locale/en-US.json +199 -123
- package/src/locale/vi-VN.json +199 -123
- package/src/locale/zh-CN.json +199 -123
- package/src/server/__tests__/circuit-breaker.test.ts +248 -169
- package/src/server/__tests__/harness-compiler.test.ts +214 -0
- package/src/server/__tests__/harness-profile-service.test.ts +167 -0
- package/src/server/__tests__/harness-runtime-policy.test.ts +293 -0
- package/src/server/__tests__/harness-tool-plan.test.ts +172 -0
- package/src/server/__tests__/loop-approval-decision.test.ts +512 -0
- package/src/server/__tests__/loop-approval-expiry.test.ts +258 -0
- package/src/server/__tests__/loop-budget-service.test.ts +255 -0
- package/src/server/__tests__/loop-control-plane-backfill.test.ts +266 -0
- package/src/server/__tests__/loop-pattern-schema.test.ts +73 -0
- package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
- package/src/server/__tests__/loop-run-state-machine.test.ts +101 -0
- package/src/server/__tests__/loop-trigger-service.test.ts +148 -0
- package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
- package/src/server/__tests__/loop-worker-execution.test.ts +317 -0
- package/src/server/__tests__/native-sub-agent-observer.test.ts +288 -4
- package/src/server/__tests__/path-lock-service.test.ts +254 -0
- package/src/server/__tests__/skill-execution-task-policy.test.ts +140 -0
- package/src/server/__tests__/smoke.test.ts +162 -121
- package/src/server/__tests__/tool-loop-detection.test.ts +275 -0
- package/src/server/collections/agent-execution-spans.ts +55 -0
- package/src/server/collections/agent-harness-profile-versions.ts +26 -0
- package/src/server/collections/agent-harness-profiles.ts +71 -59
- package/src/server/collections/agent-loop-action-approvals.ts +39 -0
- package/src/server/collections/agent-loop-artifacts.ts +25 -0
- package/src/server/collections/agent-loop-circuit-states.ts +23 -0
- package/src/server/collections/agent-loop-control-settings.ts +21 -0
- package/src/server/collections/agent-loop-events.ts +98 -71
- package/src/server/collections/agent-loop-path-locks.ts +27 -0
- package/src/server/collections/agent-loop-patterns.ts +42 -0
- package/src/server/collections/agent-loop-runs.ts +170 -3
- package/src/server/collections/agent-loop-steps.ts +76 -0
- package/src/server/collections/agent-loop-usage-buckets.ts +22 -0
- package/src/server/collections/agent-loop-worktrees.ts +25 -0
- package/src/server/collections/skill-executions.ts +8 -0
- package/src/server/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +52 -49
- package/src/server/migrations/20260429000000-add-llm-fields.ts +47 -46
- package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +45 -38
- package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +33 -32
- package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +31 -30
- package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
- package/src/server/plugin.ts +55 -167
- package/src/server/resources/agent-harness-profile.ts +94 -0
- package/src/server/resources/agent-knowledge-insights.ts +5 -3
- package/src/server/resources/agent-loop-approval.ts +84 -0
- package/src/server/resources/agent-loop-artifact.ts +56 -0
- package/src/server/resources/agent-loop-events-stream.ts +105 -0
- package/src/server/resources/agent-loop.ts +204 -143
- package/src/server/resources/agent-monitor.ts +482 -482
- package/src/server/resources/resource-helpers.ts +33 -0
- package/src/server/resources/tracing.ts +266 -258
- package/src/server/services/AgentMemoryContextService.ts +44 -0
- package/src/server/services/DurableCircuitBreakerService.ts +239 -0
- package/src/server/services/ExecutionSpanService.ts +2 -0
- package/src/server/services/HarnessCompiler.ts +170 -0
- package/src/server/services/HarnessProfileService.ts +239 -0
- package/src/server/services/HarnessSchema.ts +194 -0
- package/src/server/services/LoopBudgetService.ts +275 -0
- package/src/server/services/LoopControlService.ts +124 -0
- package/src/server/services/LoopPatternSchema.ts +185 -0
- package/src/server/services/LoopPatternService.ts +143 -0
- package/src/server/services/LoopRunRepository.ts +336 -0
- package/src/server/services/LoopRunStateMachine.ts +529 -0
- package/src/server/services/LoopSchedulerService.ts +199 -0
- package/src/server/services/LoopTriggerService.ts +157 -0
- package/src/server/services/LoopWorkerService.ts +822 -0
- package/src/server/services/NativeSubAgentObserver.ts +186 -21
- package/src/server/services/PathLockService.ts +321 -0
- package/src/server/services/PluginAiRuntimeAdapter.ts +332 -0
- package/src/server/services/ToolLoopDetectionService.ts +213 -0
- package/src/server/services/VerificationSchema.ts +31 -0
- package/src/server/services/VerificationService.ts +264 -0
- package/src/server/services/harness-runtime-policy.ts +141 -0
- package/src/server/skill-hub/actions/__tests__/git-import.test.ts +15 -1
- package/src/server/skill-hub/actions/git-import.ts +9 -3
- package/src/server/skill-hub/plugin.ts +41 -3
- package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +235 -239
- package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +61 -63
- package/src/server/skill-hub/tasks/SkillExecutionTask.ts +43 -2
- package/src/server/utils/ensure-indexes.ts +96 -0
- package/src/server/utils/logging.ts +62 -63
- package/src/server/utils/loop-pattern-context.ts +20 -0
- package/dist/client-v2/214.79650a549273f163.js +0 -10
- package/dist/client-v2/253.9f0537713cee9e6c.js +0 -10
- package/dist/client-v2/264.718a107e43fc163c.js +0 -10
- package/dist/client-v2/373.f5d5292e53c4e832.js +0 -10
- package/dist/client-v2/418.ce8f5b2b8a229d1d.js +0 -10
- package/dist/client-v2/53.7c29c28043e9112d.js +0 -10
- package/dist/client-v2/619.bd3c5698b40705c3.js +0 -10
- package/dist/client-v2/677.a991ce0250ff5c77.js +0 -10
- package/dist/client-v2/925.f5370de8f6632d65.js +0 -10
- package/dist/server/services/AgentHarness.js +0 -81
- package/dist/server/services/AgentLoopController.js +0 -1023
- package/dist/server/services/AgentLoopRepository.js +0 -192
- package/dist/server/services/AgentLoopService.js +0 -142
- package/dist/server/services/AgentPlanValidator.js +0 -99
- package/dist/server/services/AgentPlannerService.js +0 -99
- package/dist/server/services/CircuitBreaker.js +0 -125
- package/dist/server/services/ContextAggregator.js +0 -201
- package/dist/server/services/PlanningPromptService.js +0 -95
- package/dist/server/tools/agent-loop.js +0 -373
- package/dist/server/tools/orchestrator-plan.js +0 -254
- package/src/client/AIEmployeeSelect.tsx +0 -47
- package/src/client/AIEmployeesContext.tsx +0 -102
- package/src/client/RulesTab.tsx +0 -2
- package/src/client/TracingTab.tsx +0 -436
- package/src/client/skill-hub/components/ExecutionProgress.tsx +0 -51
- package/src/client-v2/components/RulesTab.tsx +0 -2
- package/src/client-v2/pages/AgentRunsPage.tsx +0 -13
- package/src/server/__tests__/agent-loop-controller.test.ts +0 -375
- package/src/server/__tests__/context-aggregator.test.ts +0 -222
- package/src/server/__tests__/parallel-execution.test.ts +0 -318
- package/src/server/__tests__/planning-prompt-service.test.ts +0 -23
- package/src/server/services/AgentHarness.ts +0 -67
- package/src/server/services/AgentLoopController.ts +0 -1263
- package/src/server/services/AgentLoopRepository.ts +0 -178
- package/src/server/services/AgentLoopService.ts +0 -177
- package/src/server/services/AgentPlanValidator.ts +0 -73
- package/src/server/services/AgentPlannerService.ts +0 -80
- package/src/server/services/CircuitBreaker.ts +0 -126
- package/src/server/services/ContextAggregator.ts +0 -239
- package/src/server/services/PlanningPromptService.ts +0 -72
- package/src/server/tools/agent-loop.ts +0 -360
- package/src/server/tools/orchestrator-plan.ts +0 -255
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { harnessSettingsSchema } from './HarnessSchema';
|
|
3
|
+
|
|
4
|
+
const finiteLimit = z.number().finite().nonnegative().nullable().default(null);
|
|
5
|
+
const countLimit = z.number().int().nonnegative().nullable().default(null);
|
|
6
|
+
|
|
7
|
+
export const loopPatternPolicySchema = z
|
|
8
|
+
.object({
|
|
9
|
+
harness: harnessSettingsSchema.default({}),
|
|
10
|
+
maxConcurrency: z.number().int().positive().default(1),
|
|
11
|
+
perRun: z
|
|
12
|
+
.object({
|
|
13
|
+
maxInvocations: countLimit,
|
|
14
|
+
maxToolCalls: countLimit,
|
|
15
|
+
maxDelegations: countLimit,
|
|
16
|
+
maxVerifications: countLimit,
|
|
17
|
+
maxTokens: countLimit,
|
|
18
|
+
maxCost: finiteLimit,
|
|
19
|
+
})
|
|
20
|
+
.default({}),
|
|
21
|
+
daily: z
|
|
22
|
+
.object({
|
|
23
|
+
maxInvocations: countLimit,
|
|
24
|
+
maxToolCalls: countLimit,
|
|
25
|
+
maxDelegations: countLimit,
|
|
26
|
+
maxTokens: countLimit,
|
|
27
|
+
maxCost: finiteLimit,
|
|
28
|
+
})
|
|
29
|
+
.default({}),
|
|
30
|
+
circuit: z
|
|
31
|
+
.object({
|
|
32
|
+
maxAttempts: z.number().int().positive().default(3),
|
|
33
|
+
maxConsecutiveFailures: z.number().int().positive().default(3),
|
|
34
|
+
maxRepeatedError: z.number().int().positive().default(2),
|
|
35
|
+
cooldownMs: z.number().int().positive().default(300_000),
|
|
36
|
+
})
|
|
37
|
+
.default({}),
|
|
38
|
+
paths: z
|
|
39
|
+
.object({
|
|
40
|
+
maxFiles: z.number().int().positive().nullable().default(null),
|
|
41
|
+
deny: z.array(z.string().min(1)).default([]),
|
|
42
|
+
})
|
|
43
|
+
.default({}),
|
|
44
|
+
actions: z
|
|
45
|
+
.object({
|
|
46
|
+
autoAllowlist: z.array(z.string().min(1)).default([]),
|
|
47
|
+
approvalAssigneeIds: z.array(z.number().int().positive()).default([]),
|
|
48
|
+
approvalTimeoutMs: z.number().int().positive().default(86_400_000),
|
|
49
|
+
})
|
|
50
|
+
.default({}),
|
|
51
|
+
verification: z
|
|
52
|
+
.object({
|
|
53
|
+
requiredChecks: z.array(z.string().min(1)).min(1).default(['goal']),
|
|
54
|
+
maxAttempts: z.number().int().positive().default(2),
|
|
55
|
+
})
|
|
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({}),
|
|
65
|
+
})
|
|
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
|
+
});
|
|
77
|
+
|
|
78
|
+
export const loopPatternSchema = z
|
|
79
|
+
.object({
|
|
80
|
+
key: z
|
|
81
|
+
.string()
|
|
82
|
+
.trim()
|
|
83
|
+
.min(1)
|
|
84
|
+
.max(120)
|
|
85
|
+
.regex(/^[a-z0-9][a-z0-9._-]*$/),
|
|
86
|
+
title: z.string().trim().min(1).max(240),
|
|
87
|
+
description: z.string().default(''),
|
|
88
|
+
goalTemplate: z.string().trim().min(1),
|
|
89
|
+
enabled: z.boolean().default(false),
|
|
90
|
+
autonomyLevel: z.enum(['L1', 'L2', 'L3']).default('L1'),
|
|
91
|
+
triggerType: z.enum(['manual', 'cron', 'event']).default('manual'),
|
|
92
|
+
cronExpression: z.string().trim().max(120).nullable().default(null),
|
|
93
|
+
timezone: z.string().trim().max(80).nullable().default(null),
|
|
94
|
+
eventKey: z.string().trim().max(160).nullable().default(null),
|
|
95
|
+
triggerConfig: z.record(z.unknown()).default({}),
|
|
96
|
+
leaderUsername: z.string().trim().min(1).max(100),
|
|
97
|
+
makerUsernames: z.array(z.string().trim().min(1).max(100)).default([]),
|
|
98
|
+
verifierUsername: z.string().trim().min(1).max(100),
|
|
99
|
+
leaderHarnessTag: z.string().trim().min(1).max(100).default('default'),
|
|
100
|
+
makerHarnessTag: z.string().trim().min(1).max(100).default('default'),
|
|
101
|
+
verifierHarnessTag: z.string().trim().min(1).max(100).default('safe'),
|
|
102
|
+
repositoryKey: z.string().trim().max(200).nullable().default(null),
|
|
103
|
+
repositoryRoot: z.string().trim().max(1000).nullable().default(null),
|
|
104
|
+
baseRef: z.string().trim().min(1).max(200).default('main'),
|
|
105
|
+
actingOn: z.array(z.string().trim().min(1)).default([]),
|
|
106
|
+
policy: loopPatternPolicySchema.default({}),
|
|
107
|
+
})
|
|
108
|
+
.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
|
+
});
|
|
123
|
+
}
|
|
124
|
+
if (pattern.triggerType === 'cron') {
|
|
125
|
+
const parts = pattern.cronExpression?.split(/\s+/).filter(Boolean) || [];
|
|
126
|
+
if (parts.length !== 5 && parts.length !== 6) {
|
|
127
|
+
context.addIssue({
|
|
128
|
+
code: z.ZodIssueCode.custom,
|
|
129
|
+
path: ['cronExpression'],
|
|
130
|
+
message: 'Cron patterns require a 5- or 6-field cron expression.',
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
if (!pattern.timezone) {
|
|
134
|
+
context.addIssue({
|
|
135
|
+
code: z.ZodIssueCode.custom,
|
|
136
|
+
path: ['timezone'],
|
|
137
|
+
message: 'Cron patterns require an explicit timezone.',
|
|
138
|
+
});
|
|
139
|
+
} else {
|
|
140
|
+
try {
|
|
141
|
+
new Intl.DateTimeFormat('en-US', { timeZone: pattern.timezone });
|
|
142
|
+
} catch {
|
|
143
|
+
context.addIssue({
|
|
144
|
+
code: z.ZodIssueCode.custom,
|
|
145
|
+
path: ['timezone'],
|
|
146
|
+
message: 'Cron pattern timezone is invalid.',
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (pattern.triggerType === 'event' && !pattern.eventKey) {
|
|
152
|
+
context.addIssue({
|
|
153
|
+
code: z.ZodIssueCode.custom,
|
|
154
|
+
path: ['eventKey'],
|
|
155
|
+
message: 'Event patterns require an event key.',
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
if (pattern.autonomyLevel !== 'L1') {
|
|
159
|
+
if (!pattern.repositoryKey || !pattern.repositoryRoot || pattern.actingOn.length === 0) {
|
|
160
|
+
context.addIssue({
|
|
161
|
+
code: z.ZodIssueCode.custom,
|
|
162
|
+
path: ['repositoryKey'],
|
|
163
|
+
message: 'L2 and L3 patterns require repository identity, root, and declared actingOn paths.',
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
if (!pattern.policy.harness.isolation.requireWorktree) {
|
|
167
|
+
context.addIssue({
|
|
168
|
+
code: z.ZodIssueCode.custom,
|
|
169
|
+
path: ['policy', 'harness', 'isolation', 'requireWorktree'],
|
|
170
|
+
message: 'L2 and L3 patterns must require a worktree.',
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
export type LoopPattern = z.infer<typeof loopPatternSchema>;
|
|
177
|
+
export type LoopPatternPolicy = z.infer<typeof loopPatternPolicySchema>;
|
|
178
|
+
|
|
179
|
+
export function parseLoopPattern(value: unknown) {
|
|
180
|
+
return loopPatternSchema.parse(value);
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function validateLoopPattern(value: unknown) {
|
|
184
|
+
return loopPatternSchema.safeParse(value);
|
|
185
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import type { Database, Model } from '@nocobase/database';
|
|
2
|
+
import { getRunEventBus } from './RunEventBus';
|
|
3
|
+
|
|
4
|
+
export type LoopRunRecord = Record<string, unknown>;
|
|
5
|
+
|
|
6
|
+
export class LoopRunAccessError extends Error {
|
|
7
|
+
constructor(
|
|
8
|
+
public readonly status: 401 | 403 | 404 | 409,
|
|
9
|
+
message: string,
|
|
10
|
+
) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'LoopRunAccessError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function read(record: Model | LoopRunRecord, key: string) {
|
|
17
|
+
const model = record as Model & { get?: (name: string) => unknown };
|
|
18
|
+
return typeof model.get === 'function' ? model.get(key) : (record as LoopRunRecord)[key];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function plain(record: Model | LoopRunRecord): LoopRunRecord {
|
|
22
|
+
return typeof (record as Model).toJSON === 'function'
|
|
23
|
+
? ((record as Model).toJSON() as LoopRunRecord)
|
|
24
|
+
: structuredClone(record as LoopRunRecord);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function positiveId(value: unknown, label: string) {
|
|
28
|
+
const parsed = typeof value === 'number' ? value : Number(value);
|
|
29
|
+
if (!Number.isSafeInteger(parsed) || parsed <= 0) {
|
|
30
|
+
throw new LoopRunAccessError(404, `${label} was not found.`);
|
|
31
|
+
}
|
|
32
|
+
return parsed;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function requireUserId(userId: number | undefined) {
|
|
36
|
+
if (!Number.isSafeInteger(userId) || Number(userId) <= 0) {
|
|
37
|
+
throw new LoopRunAccessError(401, 'Authentication is required.');
|
|
38
|
+
}
|
|
39
|
+
return Number(userId);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function mergeFilter(filter: Record<string, unknown>, required: Record<string, unknown>) {
|
|
43
|
+
return Object.keys(filter).length > 0 ? { $and: [filter, required] } : required;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class LoopRunRepository {
|
|
47
|
+
constructor(private readonly database: Database) {}
|
|
48
|
+
|
|
49
|
+
async requireRun(runId: string | number) {
|
|
50
|
+
const id = positiveId(runId, 'Agent loop run');
|
|
51
|
+
const record = await this.database.getRepository('agentLoopRuns').findOne({ filterByTk: id });
|
|
52
|
+
if (!record) throw new LoopRunAccessError(404, `Agent loop run ${id} was not found.`);
|
|
53
|
+
return plain(record);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async requireOwnedRun(runId: string | number, userId: number | undefined, isAdmin: boolean) {
|
|
57
|
+
const authenticatedUserId = requireUserId(userId);
|
|
58
|
+
const run = await this.requireRun(runId);
|
|
59
|
+
if (!isAdmin && Number(run.userId) !== authenticatedUserId) {
|
|
60
|
+
throw new LoopRunAccessError(403, 'You cannot access this agent loop run.');
|
|
61
|
+
}
|
|
62
|
+
return run;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async requireMutableV2Run(runId: string | number, userId: number | undefined, isAdmin: boolean) {
|
|
66
|
+
const run = await this.requireOwnedRun(runId, userId, isAdmin);
|
|
67
|
+
if (run.runtimeVersion !== 'control-plane-v2') {
|
|
68
|
+
throw new LoopRunAccessError(409, 'Historical plan-era runs are read-only.');
|
|
69
|
+
}
|
|
70
|
+
return run;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
async listOwnedRuns(input: {
|
|
74
|
+
userId: number | undefined;
|
|
75
|
+
isAdmin: boolean;
|
|
76
|
+
filter?: Record<string, unknown>;
|
|
77
|
+
sort?: string[];
|
|
78
|
+
page?: number;
|
|
79
|
+
pageSize?: number;
|
|
80
|
+
}) {
|
|
81
|
+
const userId = requireUserId(input.userId);
|
|
82
|
+
const page = Number.isSafeInteger(input.page) && Number(input.page) > 0 ? Number(input.page) : 1;
|
|
83
|
+
const pageSize =
|
|
84
|
+
Number.isSafeInteger(input.pageSize) && Number(input.pageSize) > 0 ? Math.min(Number(input.pageSize), 100) : 20;
|
|
85
|
+
const requestedFilter = input.filter || {};
|
|
86
|
+
const filter = input.isAdmin ? requestedFilter : mergeFilter(requestedFilter, { userId });
|
|
87
|
+
const [rows, count] = await this.database.getRepository('agentLoopRuns').findAndCount({
|
|
88
|
+
filter,
|
|
89
|
+
sort: input.sort || ['-createdAt'],
|
|
90
|
+
offset: (page - 1) * pageSize,
|
|
91
|
+
limit: pageSize,
|
|
92
|
+
});
|
|
93
|
+
return {
|
|
94
|
+
rows: rows.map(plain),
|
|
95
|
+
count,
|
|
96
|
+
page,
|
|
97
|
+
pageSize,
|
|
98
|
+
totalPage: Math.ceil(count / pageSize),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async listOwnedRunIds(userId: number | undefined, isAdmin: boolean) {
|
|
103
|
+
const authenticatedUserId = requireUserId(userId);
|
|
104
|
+
const repository = this.database.getRepository('agentLoopRuns');
|
|
105
|
+
const filter = isAdmin ? {} : { userId: authenticatedUserId };
|
|
106
|
+
const pageSize = 5_000;
|
|
107
|
+
const ids: number[] = [];
|
|
108
|
+
for (let page = 1; ; page += 1) {
|
|
109
|
+
const rows = await repository.find({ filter, fields: ['id'], sort: ['id'], page, pageSize });
|
|
110
|
+
for (const row of rows) {
|
|
111
|
+
ids.push(positiveId(read(row, 'id'), 'Agent loop run'));
|
|
112
|
+
}
|
|
113
|
+
if (rows.length < pageSize) break;
|
|
114
|
+
}
|
|
115
|
+
return ids;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async getOwnedRunDetail(runId: string | number, userId: number | undefined, isAdmin: boolean) {
|
|
119
|
+
const run = await this.requireOwnedRun(runId, userId, isAdmin);
|
|
120
|
+
const id = positiveId(run.id, 'Agent loop run');
|
|
121
|
+
const rootRunId = typeof run.rootRunId === 'string' ? run.rootRunId : '';
|
|
122
|
+
const [steps, events, spans, artifacts, approvals, skillExecutions] = await Promise.all([
|
|
123
|
+
this.database.getRepository('agentLoopSteps').find({ filter: { runId: id }, sort: ['index', 'createdAt'] }),
|
|
124
|
+
this.database.getRepository('agentLoopEvents').find({ filter: { runId: id }, sort: ['id'], pageSize: 1000 }),
|
|
125
|
+
this.database
|
|
126
|
+
.getRepository('agentExecutionSpans')
|
|
127
|
+
.find({ filter: { agentLoopRunId: id }, sort: ['createdAt'], pageSize: 1000 }),
|
|
128
|
+
this.database.getRepository('agentLoopArtifacts').find({ filter: { runId: id }, sort: ['createdAt'] }),
|
|
129
|
+
this.database.getRepository('agentLoopActionApprovals').find({ filter: { runId: id }, sort: ['createdAt'] }),
|
|
130
|
+
this.database.getRepository('skillExecutions')
|
|
131
|
+
? this.database
|
|
132
|
+
.getRepository('skillExecutions')
|
|
133
|
+
.find({ filter: { agentLoopRunId: String(id) }, sort: ['createdAt'], pageSize: 1000 })
|
|
134
|
+
: [],
|
|
135
|
+
]);
|
|
136
|
+
return {
|
|
137
|
+
run: {
|
|
138
|
+
...run,
|
|
139
|
+
historical: run.runtimeVersion !== 'control-plane-v2',
|
|
140
|
+
readOnly: run.runtimeVersion !== 'control-plane-v2',
|
|
141
|
+
},
|
|
142
|
+
steps: steps.map(plain),
|
|
143
|
+
events: events.map(plain),
|
|
144
|
+
spans: spans.map(plain),
|
|
145
|
+
artifacts: artifacts.map(plain),
|
|
146
|
+
approvals: approvals.map(plain),
|
|
147
|
+
skillExecutions: skillExecutions.map(plain),
|
|
148
|
+
rootRunId,
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async listApprovals(input: {
|
|
153
|
+
userId: number | undefined;
|
|
154
|
+
isAdmin: boolean;
|
|
155
|
+
filter?: Record<string, unknown>;
|
|
156
|
+
sort?: string[];
|
|
157
|
+
page?: number;
|
|
158
|
+
pageSize?: number;
|
|
159
|
+
}) {
|
|
160
|
+
const userId = requireUserId(input.userId);
|
|
161
|
+
// Scope via the run association so ownership holds for any number of runs
|
|
162
|
+
// (a materialized id list would silently truncate for prolific users).
|
|
163
|
+
const accessible = input.isAdmin
|
|
164
|
+
? {}
|
|
165
|
+
: {
|
|
166
|
+
$or: [{ assignedToId: userId }, { 'run.userId': userId }],
|
|
167
|
+
};
|
|
168
|
+
return this.findAndCount('agentLoopActionApprovals', input, accessible);
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async requireAccessibleApproval(approvalId: string | number, userId: number | undefined, isAdmin: boolean) {
|
|
172
|
+
const authenticatedUserId = requireUserId(userId);
|
|
173
|
+
const id = positiveId(approvalId, 'Agent loop approval');
|
|
174
|
+
const record = await this.database.getRepository('agentLoopActionApprovals').findOne({ filterByTk: id });
|
|
175
|
+
if (!record) throw new LoopRunAccessError(404, `Agent loop approval ${id} was not found.`);
|
|
176
|
+
const approval = plain(record);
|
|
177
|
+
const run = await this.requireRun(positiveId(approval.runId, 'Agent loop run'));
|
|
178
|
+
if (
|
|
179
|
+
!isAdmin &&
|
|
180
|
+
Number(run.userId) !== authenticatedUserId &&
|
|
181
|
+
Number(approval.assignedToId) !== authenticatedUserId
|
|
182
|
+
) {
|
|
183
|
+
throw new LoopRunAccessError(403, 'You cannot access this agent loop approval.');
|
|
184
|
+
}
|
|
185
|
+
return approval;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Records a human decision on one approval and requeues the run once every pending approval of
|
|
189
|
+
// the run has been decided. Fail-closed throughout: an expired window, a decided row, or a run
|
|
190
|
+
// that moved on all reject the decision instead of guessing what the human meant.
|
|
191
|
+
async decideApproval(input: {
|
|
192
|
+
approvalId: string | number;
|
|
193
|
+
userId: number | undefined;
|
|
194
|
+
isAdmin: boolean;
|
|
195
|
+
decision: 'approved' | 'rejected';
|
|
196
|
+
note?: string;
|
|
197
|
+
editedInput?: unknown;
|
|
198
|
+
}) {
|
|
199
|
+
const decidedById = requireUserId(input.userId);
|
|
200
|
+
const id = positiveId(input.approvalId, 'Agent loop approval');
|
|
201
|
+
// Fast access check before taking row locks; the transaction re-reads the rows anyway.
|
|
202
|
+
await this.requireAccessibleApproval(id, input.userId, input.isAdmin);
|
|
203
|
+
|
|
204
|
+
const committed = await this.database.sequelize.transaction(async (transaction) => {
|
|
205
|
+
const approvals = this.database.getRepository('agentLoopActionApprovals');
|
|
206
|
+
const runs = this.database.getRepository('agentLoopRuns');
|
|
207
|
+
const record = await approvals.findOne({ filterByTk: id, transaction, lock: transaction.LOCK.UPDATE });
|
|
208
|
+
if (!record) throw new LoopRunAccessError(404, `Agent loop approval ${id} was not found.`);
|
|
209
|
+
const approval = plain(record);
|
|
210
|
+
|
|
211
|
+
if (approval.status !== 'pending') {
|
|
212
|
+
throw new LoopRunAccessError(409, `This approval has already been ${String(approval.status)}.`);
|
|
213
|
+
}
|
|
214
|
+
const expiresAt = approval.expiresAt ? new Date(String(approval.expiresAt)) : null;
|
|
215
|
+
if (expiresAt && !Number.isNaN(expiresAt.getTime()) && expiresAt.getTime() <= Date.now()) {
|
|
216
|
+
throw new LoopRunAccessError(409, 'The approval window has expired. Retry the run to request approval again.');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const runId = positiveId(approval.runId, 'Agent loop run');
|
|
220
|
+
const runRecord = await runs.findOne({ filterByTk: runId, transaction, lock: transaction.LOCK.UPDATE });
|
|
221
|
+
if (!runRecord) throw new LoopRunAccessError(404, `Agent loop run ${runId} was not found.`);
|
|
222
|
+
const run = plain(runRecord);
|
|
223
|
+
if (run.runtimeVersion !== 'control-plane-v2') {
|
|
224
|
+
throw new LoopRunAccessError(409, 'Historical plan-era runs are read-only.');
|
|
225
|
+
}
|
|
226
|
+
// A paused run keeps its decisions; the human resume requeues it later. Any other status
|
|
227
|
+
// means the run moved on and the decision can no longer be applied.
|
|
228
|
+
if (run.status !== 'waiting_approval' && run.status !== 'paused') {
|
|
229
|
+
throw new LoopRunAccessError(409, 'The run is no longer waiting for approval.');
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
const now = new Date();
|
|
233
|
+
await approvals.update({
|
|
234
|
+
filterByTk: id,
|
|
235
|
+
values: {
|
|
236
|
+
status: input.decision,
|
|
237
|
+
decidedById,
|
|
238
|
+
decidedAt: now,
|
|
239
|
+
decisionNote: input.note || null,
|
|
240
|
+
...(input.decision === 'approved' && input.editedInput !== undefined
|
|
241
|
+
? { editedInput: input.editedInput }
|
|
242
|
+
: {}),
|
|
243
|
+
},
|
|
244
|
+
transaction,
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
const remaining = await approvals.find({ filter: { runId, status: 'pending' }, transaction });
|
|
248
|
+
let requeued = false;
|
|
249
|
+
let event: LoopRunRecord | null = null;
|
|
250
|
+
if (!remaining.length && run.status === 'waiting_approval') {
|
|
251
|
+
await runs.update({
|
|
252
|
+
filterByTk: runId,
|
|
253
|
+
values: { status: 'queued', approvalStatus: 'decided' },
|
|
254
|
+
transaction,
|
|
255
|
+
});
|
|
256
|
+
const created = await this.database.getRepository('agentLoopEvents').create({
|
|
257
|
+
values: {
|
|
258
|
+
runId,
|
|
259
|
+
type: 'run_approval_decided',
|
|
260
|
+
title: 'Approvals decided',
|
|
261
|
+
content: 'All pending action approvals were decided. Run requeued to resume.',
|
|
262
|
+
status: 'queued',
|
|
263
|
+
payload: { decision: input.decision },
|
|
264
|
+
actorType: 'human',
|
|
265
|
+
actorIdentity: String(decidedById),
|
|
266
|
+
correlationKey: `approval-decided:${runId}`,
|
|
267
|
+
createdAt: now,
|
|
268
|
+
},
|
|
269
|
+
transaction,
|
|
270
|
+
});
|
|
271
|
+
event = typeof created.toJSON === 'function' ? created.toJSON() : created;
|
|
272
|
+
requeued = true;
|
|
273
|
+
}
|
|
274
|
+
return { approval, runId, requeued, event };
|
|
275
|
+
});
|
|
276
|
+
|
|
277
|
+
if (committed.requeued && committed.event) getRunEventBus().emit(committed.runId, committed.event);
|
|
278
|
+
return {
|
|
279
|
+
...committed.approval,
|
|
280
|
+
status: input.decision,
|
|
281
|
+
decidedById,
|
|
282
|
+
requeued: committed.requeued,
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
async listArtifacts(input: {
|
|
287
|
+
userId: number | undefined;
|
|
288
|
+
isAdmin: boolean;
|
|
289
|
+
filter?: Record<string, unknown>;
|
|
290
|
+
sort?: string[];
|
|
291
|
+
page?: number;
|
|
292
|
+
pageSize?: number;
|
|
293
|
+
}) {
|
|
294
|
+
const userId = requireUserId(input.userId);
|
|
295
|
+
const accessible = input.isAdmin ? {} : { 'run.userId': userId };
|
|
296
|
+
return this.findAndCount('agentLoopArtifacts', input, accessible);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async requireOwnedArtifact(artifactId: string | number, userId: number | undefined, isAdmin: boolean) {
|
|
300
|
+
const id = positiveId(artifactId, 'Agent loop artifact');
|
|
301
|
+
const record = await this.database.getRepository('agentLoopArtifacts').findOne({ filterByTk: id });
|
|
302
|
+
if (!record) throw new LoopRunAccessError(404, `Agent loop artifact ${id} was not found.`);
|
|
303
|
+
const artifact = plain(record);
|
|
304
|
+
await this.requireOwnedRun(positiveId(artifact.runId, 'Agent loop run'), userId, isAdmin);
|
|
305
|
+
return artifact;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
private async findAndCount(
|
|
309
|
+
collection: string,
|
|
310
|
+
input: {
|
|
311
|
+
filter?: Record<string, unknown>;
|
|
312
|
+
sort?: string[];
|
|
313
|
+
page?: number;
|
|
314
|
+
pageSize?: number;
|
|
315
|
+
},
|
|
316
|
+
accessible: Record<string, unknown>,
|
|
317
|
+
) {
|
|
318
|
+
const page = Number.isSafeInteger(input.page) && Number(input.page) > 0 ? Number(input.page) : 1;
|
|
319
|
+
const pageSize =
|
|
320
|
+
Number.isSafeInteger(input.pageSize) && Number(input.pageSize) > 0 ? Math.min(Number(input.pageSize), 100) : 20;
|
|
321
|
+
const filter = mergeFilter(input.filter || {}, accessible);
|
|
322
|
+
const [rows, count] = await this.database.getRepository(collection).findAndCount({
|
|
323
|
+
filter,
|
|
324
|
+
sort: input.sort || ['-createdAt'],
|
|
325
|
+
offset: (page - 1) * pageSize,
|
|
326
|
+
limit: pageSize,
|
|
327
|
+
});
|
|
328
|
+
return {
|
|
329
|
+
rows: rows.map(plain),
|
|
330
|
+
count,
|
|
331
|
+
page,
|
|
332
|
+
pageSize,
|
|
333
|
+
totalPage: Math.ceil(count / pageSize),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
}
|