plugin-agent-orchestrator 1.1.2 → 1.1.4
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/dist/client/index.js +1 -1
- package/dist/client-v2/214.b063f33ba044a808.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.58fa350f5496efd3.js +10 -0
- package/dist/client-v2/{53.7c29c28043e9112d.js → 53.9a10455323390f14.js} +1 -1
- 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/925.e5925bf21ed68e7a.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 -6
- package/dist/locale/en-US.json +48 -28
- package/dist/locale/vi-VN.json +48 -28
- package/dist/locale/zh-CN.json +48 -28
- package/dist/server/collections/agent-execution-spans.js +47 -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 +68 -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 +163 -2
- package/dist/server/collections/agent-loop-steps.js +69 -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/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 +52 -150
- package/dist/server/resources/agent-loop-approval.js +83 -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 +181 -139
- package/dist/server/resources/resource-helpers.js +63 -0
- package/dist/server/resources/tracing.js +121 -107
- package/dist/server/services/DurableCircuitBreakerService.js +229 -0
- package/dist/server/services/HarnessCompiler.js +142 -0
- package/dist/server/services/HarnessProfileService.js +168 -0
- package/dist/server/services/HarnessSchema.js +167 -0
- package/dist/server/services/LoopBudgetService.js +269 -0
- package/dist/server/services/LoopControlService.js +139 -0
- package/dist/server/services/LoopPatternSchema.js +180 -0
- package/dist/server/services/LoopPatternService.js +132 -0
- package/dist/server/services/LoopRunRepository.js +205 -0
- package/dist/server/services/LoopRunStateMachine.js +389 -0
- package/dist/server/services/LoopSchedulerService.js +193 -0
- package/dist/server/services/LoopTriggerService.js +128 -0
- package/dist/server/services/LoopWorkerService.js +461 -0
- package/dist/server/services/PathLockService.js +288 -0
- package/dist/server/services/PluginAiRuntimeAdapter.js +215 -0
- package/dist/server/services/VerificationSchema.js +59 -0
- package/dist/server/services/VerificationService.js +169 -0
- package/dist/server/skill-hub/actions/git-import.js +13 -7
- package/dist/server/skill-hub/services/RegistrySkillSnapshotService.js +1 -5
- package/dist/server/utils/ensure-indexes.js +111 -0
- package/dist/server/utils/loop-pattern-context.js +56 -0
- package/package.json +2 -2
- package/src/client/OrchestratorSettings.tsx +44 -0
- package/src/client-v2/components/AgentRunsTab.tsx +576 -494
- package/src/client-v2/components/HarnessProfilesTab.tsx +13 -8
- package/src/client-v2/components/MemoryInspectorTab.tsx +19 -3
- package/src/client-v2/components/TracingTab.tsx +515 -432
- package/src/client-v2/hooks/useApiRequest.ts +141 -121
- package/src/client-v2/skill-hub/components/SkillMetrics.tsx +8 -6
- package/src/locale/en-US.json +52 -28
- package/src/locale/vi-VN.json +52 -28
- package/src/locale/zh-CN.json +52 -28
- package/src/server/__tests__/circuit-breaker.test.ts +225 -146
- package/src/server/__tests__/harness-compiler.test.ts +131 -0
- package/src/server/__tests__/harness-profile-service.test.ts +116 -0
- package/src/server/__tests__/harness-tool-plan.test.ts +148 -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 +56 -0
- package/src/server/__tests__/loop-pattern-service.test.ts +148 -0
- package/src/server/__tests__/loop-run-state-machine.test.ts +90 -0
- package/src/server/__tests__/loop-worker-claim.test.ts +341 -0
- package/src/server/__tests__/loop-worker-execution.test.ts +236 -0
- package/src/server/__tests__/path-lock-service.test.ts +254 -0
- package/src/server/__tests__/smoke.test.ts +62 -21
- package/src/server/collections/agent-execution-spans.ts +47 -0
- package/src/server/collections/agent-harness-profile-versions.ts +26 -0
- package/src/server/collections/agent-harness-profiles.ts +12 -0
- package/src/server/collections/agent-loop-action-approvals.ts +38 -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 +27 -0
- 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 +163 -2
- package/src/server/collections/agent-loop-steps.ts +69 -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/migrations/{20260427000000-change-packages-to-text.ts → 20260427000002-change-packages-to-text.ts} +3 -0
- package/src/server/migrations/20260429000000-add-llm-fields.ts +3 -2
- package/src/server/migrations/{20260429000000-fix-inputargs-json-to-text.ts → 20260429000001-fix-inputargs-json-to-text.ts} +13 -6
- package/src/server/migrations/20260503000000-add-orchestrator-trace-fields.ts +2 -1
- package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +2 -1
- package/src/server/migrations/20260803010000-backfill-loop-control-plane-data.ts +293 -0
- package/src/server/plugin.ts +53 -167
- package/src/server/resources/agent-loop-approval.ts +52 -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 +202 -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 +145 -137
- package/src/server/services/DurableCircuitBreakerService.ts +239 -0
- package/src/server/services/HarnessCompiler.ts +133 -0
- package/src/server/services/HarnessProfileService.ts +157 -0
- package/src/server/services/HarnessSchema.ts +163 -0
- package/src/server/services/LoopBudgetService.ts +275 -0
- package/src/server/services/LoopControlService.ts +124 -0
- package/src/server/services/LoopPatternSchema.ts +167 -0
- package/src/server/services/LoopPatternService.ts +143 -0
- package/src/server/services/LoopRunRepository.ts +237 -0
- package/src/server/services/LoopRunStateMachine.ts +432 -0
- package/src/server/services/LoopSchedulerService.ts +199 -0
- package/src/server/services/LoopTriggerService.ts +115 -0
- package/src/server/services/LoopWorkerService.ts +522 -0
- package/src/server/services/PathLockService.ts +321 -0
- package/src/server/services/PluginAiRuntimeAdapter.ts +315 -0
- package/src/server/services/VerificationSchema.ts +31 -0
- package/src/server/services/VerificationService.ts +185 -0
- package/src/server/skill-hub/actions/__tests__/git-import.test.ts +62 -0
- package/src/server/skill-hub/actions/git-import.ts +9 -3
- package/src/server/skill-hub/services/RegistrySkillSnapshotService.ts +1 -5
- package/src/server/skill-hub/services/__tests__/RegistrySkillSnapshotService.test.ts +1 -3
- package/src/server/utils/ensure-indexes.ts +96 -0
- package/src/server/utils/logging.ts +0 -1
- 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/418.ce8f5b2b8a229d1d.js +0 -10
- package/dist/client-v2/619.bd3c5698b40705c3.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/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,321 @@
|
|
|
1
|
+
import type { Database, Model, Transaction } from '@nocobase/database';
|
|
2
|
+
|
|
3
|
+
type DistributedLock = {
|
|
4
|
+
runExclusive<T>(key: string, operation: () => Promise<T>, ttl?: number): Promise<T>;
|
|
5
|
+
};
|
|
6
|
+
|
|
7
|
+
type PathLockRow = {
|
|
8
|
+
id: number;
|
|
9
|
+
runId: number;
|
|
10
|
+
repositoryKey: string;
|
|
11
|
+
paths: string[];
|
|
12
|
+
status: 'waiting' | 'held' | 'released' | 'expired';
|
|
13
|
+
blockerRunIds: number[];
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type PathLockAcquisition =
|
|
17
|
+
| { acquired: true; lock: PathLockRow; blockers: number[] }
|
|
18
|
+
| { acquired: false; deadlocked: boolean; blockers: number[] };
|
|
19
|
+
|
|
20
|
+
function read(record: Model | Record<string, unknown>, key: string) {
|
|
21
|
+
const model = record as Model & { get?: (name: string) => unknown };
|
|
22
|
+
return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function positiveInteger(value: unknown) {
|
|
26
|
+
const parsed = Number(value);
|
|
27
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function asDate(value: unknown): Date | null {
|
|
31
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
|
32
|
+
if (typeof value === 'string' || typeof value === 'number') {
|
|
33
|
+
const parsed = new Date(value);
|
|
34
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
35
|
+
}
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// A held lock without a readable expiry is treated as expired: a crashed worker must never
|
|
40
|
+
// leave a row that blocks every later run forever.
|
|
41
|
+
function lockIsExpired(record: Model | Record<string, unknown>, now: Date) {
|
|
42
|
+
const expiresAt = asDate(read(record, 'expiresAt'));
|
|
43
|
+
return !expiresAt || expiresAt.getTime() <= now.getTime();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function positiveTtl(ttlMs: number) {
|
|
47
|
+
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {
|
|
48
|
+
throw new Error('Path lock TTL must be a positive number of milliseconds.');
|
|
49
|
+
}
|
|
50
|
+
return ttlMs;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function normalizeLockPath(value: string) {
|
|
54
|
+
const normalized = value
|
|
55
|
+
.trim()
|
|
56
|
+
.replace(/\\/g, '/')
|
|
57
|
+
.replace(/^\.\//, '')
|
|
58
|
+
.replace(/\/{2,}/g, '/');
|
|
59
|
+
if (!normalized || normalized.startsWith('/') || /^[a-zA-Z]:\//.test(normalized)) {
|
|
60
|
+
throw new Error(`Lock path must be repository-relative: ${value}`);
|
|
61
|
+
}
|
|
62
|
+
const segments = normalized.split('/');
|
|
63
|
+
if (segments.some((segment) => segment === '..' || segment === '.')) {
|
|
64
|
+
throw new Error(`Lock path cannot contain dot segments: ${value}`);
|
|
65
|
+
}
|
|
66
|
+
return normalized.replace(/\/$/, '');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function literalPrefix(pattern: string) {
|
|
70
|
+
const result: string[] = [];
|
|
71
|
+
for (const segment of normalizeLockPath(pattern).split('/')) {
|
|
72
|
+
if (/[*?{[\]]/.test(segment)) break;
|
|
73
|
+
result.push(segment);
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function lockPathsOverlap(left: string, right: string) {
|
|
79
|
+
const leftNormalized = normalizeLockPath(left);
|
|
80
|
+
const rightNormalized = normalizeLockPath(right);
|
|
81
|
+
if (leftNormalized === rightNormalized) return true;
|
|
82
|
+
|
|
83
|
+
const leftPrefix = literalPrefix(leftNormalized);
|
|
84
|
+
const rightPrefix = literalPrefix(rightNormalized);
|
|
85
|
+
if (leftPrefix.length === 0 || rightPrefix.length === 0) return true;
|
|
86
|
+
const shared = Math.min(leftPrefix.length, rightPrefix.length);
|
|
87
|
+
for (let index = 0; index < shared; index += 1) {
|
|
88
|
+
if (leftPrefix[index] !== rightPrefix[index]) return false;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const leftHasPattern = leftPrefix.length < leftNormalized.split('/').length;
|
|
92
|
+
const rightHasPattern = rightPrefix.length < rightNormalized.split('/').length;
|
|
93
|
+
if (leftHasPattern || rightHasPattern) return true;
|
|
94
|
+
return leftPrefix.length !== rightPrefix.length;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function pathSetsOverlap(left: string[], right: string[]) {
|
|
98
|
+
return left.some((leftPath) => right.some((rightPath) => lockPathsOverlap(leftPath, rightPath)));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function row(record: Model | Record<string, unknown>): PathLockRow {
|
|
102
|
+
const status = read(record, 'status');
|
|
103
|
+
return {
|
|
104
|
+
id: positiveInteger(read(record, 'id')) || 0,
|
|
105
|
+
runId: positiveInteger(read(record, 'runId')) || 0,
|
|
106
|
+
repositoryKey: String(read(record, 'repositoryKey') || ''),
|
|
107
|
+
paths: Array.isArray(read(record, 'paths')) ? (read(record, 'paths') as string[]) : [],
|
|
108
|
+
status: status === 'held' || status === 'released' || status === 'expired' ? status : 'waiting',
|
|
109
|
+
blockerRunIds: Array.isArray(read(record, 'blockerRunIds'))
|
|
110
|
+
? (read(record, 'blockerRunIds') as unknown[])
|
|
111
|
+
.map(positiveInteger)
|
|
112
|
+
.filter((value): value is number => value !== null)
|
|
113
|
+
: [],
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function waitGraphHasCycle(rows: PathLockRow[], runId: number, blockers: number[]) {
|
|
118
|
+
const graph = new Map<number, number[]>();
|
|
119
|
+
for (const lock of rows) {
|
|
120
|
+
if (lock.status === 'waiting') graph.set(lock.runId, lock.blockerRunIds);
|
|
121
|
+
}
|
|
122
|
+
graph.set(runId, blockers);
|
|
123
|
+
const visiting = new Set<number>();
|
|
124
|
+
const visited = new Set<number>();
|
|
125
|
+
|
|
126
|
+
const visit = (node: number): boolean => {
|
|
127
|
+
if (visiting.has(node)) return true;
|
|
128
|
+
if (visited.has(node)) return false;
|
|
129
|
+
visiting.add(node);
|
|
130
|
+
for (const blocker of graph.get(node) || []) {
|
|
131
|
+
if (visit(blocker)) return true;
|
|
132
|
+
}
|
|
133
|
+
visiting.delete(node);
|
|
134
|
+
visited.add(node);
|
|
135
|
+
return false;
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
return visit(runId);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export class PathLockService {
|
|
142
|
+
constructor(
|
|
143
|
+
private readonly database: Database,
|
|
144
|
+
private readonly distributedLock: DistributedLock,
|
|
145
|
+
) {}
|
|
146
|
+
|
|
147
|
+
async acquire(input: {
|
|
148
|
+
runId: number;
|
|
149
|
+
repositoryKey: string;
|
|
150
|
+
owner: string;
|
|
151
|
+
paths: string[];
|
|
152
|
+
ttlMs: number;
|
|
153
|
+
waitUntil?: Date;
|
|
154
|
+
}): Promise<PathLockAcquisition> {
|
|
155
|
+
const paths = Array.from(new Set(input.paths.map(normalizeLockPath))).sort();
|
|
156
|
+
if (!paths.length) throw new Error('At least one repository path is required for a path lock.');
|
|
157
|
+
const repositoryKey = input.repositoryKey.trim();
|
|
158
|
+
if (!repositoryKey) throw new Error('Repository key is required for a path lock.');
|
|
159
|
+
const ttlMs = positiveTtl(input.ttlMs);
|
|
160
|
+
|
|
161
|
+
return this.distributedLock.runExclusive(
|
|
162
|
+
`agent-loop:path:${repositoryKey}`,
|
|
163
|
+
() =>
|
|
164
|
+
this.database.sequelize.transaction(async (transaction) => {
|
|
165
|
+
const repository = this.database.getRepository('agentLoopPathLocks');
|
|
166
|
+
const now = new Date();
|
|
167
|
+
const existing = await repository.findOne({
|
|
168
|
+
filter: { runId: input.runId, repositoryKey },
|
|
169
|
+
transaction,
|
|
170
|
+
lock: transaction.LOCK.UPDATE,
|
|
171
|
+
});
|
|
172
|
+
if (existing && read(existing, 'status') === 'held') {
|
|
173
|
+
const sameOwner = String(read(existing, 'owner') || '') === input.owner;
|
|
174
|
+
const samePaths = JSON.stringify(row(existing).paths.slice().sort()) === JSON.stringify(paths);
|
|
175
|
+
if (sameOwner && samePaths && !lockIsExpired(existing, now)) {
|
|
176
|
+
return { acquired: true, lock: row(existing), blockers: [] as number[] };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const held = await repository.find({
|
|
181
|
+
filter: { repositoryKey, status: 'held' },
|
|
182
|
+
transaction,
|
|
183
|
+
lock: transaction.LOCK.UPDATE,
|
|
184
|
+
});
|
|
185
|
+
const active: typeof held = [];
|
|
186
|
+
for (const lock of held) {
|
|
187
|
+
if (!lockIsExpired(lock, now)) {
|
|
188
|
+
active.push(lock);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
await repository.update({
|
|
192
|
+
filterByTk: read(lock, 'id'),
|
|
193
|
+
values: { status: 'expired', releasedAt: now, blockerRunIds: [] },
|
|
194
|
+
transaction,
|
|
195
|
+
});
|
|
196
|
+
}
|
|
197
|
+
const blockers = active
|
|
198
|
+
.map(row)
|
|
199
|
+
.filter((lock) => lock.runId !== input.runId && pathSetsOverlap(paths, lock.paths))
|
|
200
|
+
.map((lock) => lock.runId);
|
|
201
|
+
|
|
202
|
+
if (blockers.length) {
|
|
203
|
+
const waitingRows = (
|
|
204
|
+
await repository.find({
|
|
205
|
+
filter: { repositoryKey, status: 'waiting' },
|
|
206
|
+
transaction,
|
|
207
|
+
lock: transaction.LOCK.UPDATE,
|
|
208
|
+
})
|
|
209
|
+
).map(row);
|
|
210
|
+
if (waitGraphHasCycle(waitingRows, input.runId, blockers)) {
|
|
211
|
+
return { acquired: false, deadlocked: true, blockers };
|
|
212
|
+
}
|
|
213
|
+
const values = {
|
|
214
|
+
runId: input.runId,
|
|
215
|
+
repositoryKey,
|
|
216
|
+
owner: input.owner,
|
|
217
|
+
paths,
|
|
218
|
+
status: 'waiting',
|
|
219
|
+
blockerRunIds: blockers,
|
|
220
|
+
waitUntil: input.waitUntil || null,
|
|
221
|
+
acquiredAt: null,
|
|
222
|
+
expiresAt: null,
|
|
223
|
+
releasedAt: null,
|
|
224
|
+
};
|
|
225
|
+
if (existing) {
|
|
226
|
+
await repository.update({ filterByTk: read(existing, 'id'), values, transaction });
|
|
227
|
+
} else {
|
|
228
|
+
await repository.create({ values, transaction });
|
|
229
|
+
}
|
|
230
|
+
return { acquired: false, deadlocked: false, blockers };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const values = {
|
|
234
|
+
runId: input.runId,
|
|
235
|
+
repositoryKey,
|
|
236
|
+
owner: input.owner,
|
|
237
|
+
paths,
|
|
238
|
+
status: 'held',
|
|
239
|
+
blockerRunIds: [],
|
|
240
|
+
acquiredAt: now,
|
|
241
|
+
expiresAt: new Date(now.getTime() + ttlMs),
|
|
242
|
+
waitUntil: null,
|
|
243
|
+
releasedAt: null,
|
|
244
|
+
};
|
|
245
|
+
const locked = existing
|
|
246
|
+
? await this.updateAndRead(repository, Number(read(existing, 'id')), values, transaction)
|
|
247
|
+
: await repository.create({ values, transaction });
|
|
248
|
+
return { acquired: true, lock: row(locked), blockers: [] as number[] };
|
|
249
|
+
}),
|
|
250
|
+
Math.max(ttlMs, 5000),
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async renew(runId: number, repositoryKey: string, ttlMs: number, owner?: string) {
|
|
255
|
+
const ttl = positiveTtl(ttlMs);
|
|
256
|
+
return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
|
|
257
|
+
const repository = this.database.getRepository('agentLoopPathLocks');
|
|
258
|
+
// An expired lock is marked `expired` in its own committed transaction. Doing the audit
|
|
259
|
+
// write inside the renew transaction and then throwing would roll the mark back, leaving a
|
|
260
|
+
// stale `held` row that still reads as expired to the next acquirer but never audits it.
|
|
261
|
+
const expired = await this.database.sequelize.transaction(async (transaction) => {
|
|
262
|
+
const lock = await repository.findOne({
|
|
263
|
+
filter: { runId, repositoryKey, status: 'held' },
|
|
264
|
+
transaction,
|
|
265
|
+
lock: transaction.LOCK.UPDATE,
|
|
266
|
+
});
|
|
267
|
+
if (!lock) throw new Error('Held path lock was not found.');
|
|
268
|
+
if (owner !== undefined && String(read(lock, 'owner') || '') !== owner) {
|
|
269
|
+
throw new Error('Path lock is no longer owned by this worker.');
|
|
270
|
+
}
|
|
271
|
+
const now = new Date();
|
|
272
|
+
if (lockIsExpired(lock, now)) return { id: read(lock, 'id'), at: now };
|
|
273
|
+
await repository.update({
|
|
274
|
+
filterByTk: read(lock, 'id'),
|
|
275
|
+
values: { expiresAt: new Date(now.getTime() + ttl) },
|
|
276
|
+
transaction,
|
|
277
|
+
});
|
|
278
|
+
return null;
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
if (expired) {
|
|
282
|
+
await this.database.sequelize.transaction(async (transaction) => {
|
|
283
|
+
await repository.update({
|
|
284
|
+
filterByTk: expired.id,
|
|
285
|
+
values: { status: 'expired', releasedAt: expired.at, blockerRunIds: [] },
|
|
286
|
+
transaction,
|
|
287
|
+
});
|
|
288
|
+
});
|
|
289
|
+
throw new Error('Path lock has expired and must be reacquired.');
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// The owner token guards against a reclaimed run: once a stale worker's lease expires and another
|
|
295
|
+
// worker takes over the same run, the original worker must not free a lock the new owner now holds.
|
|
296
|
+
async release(runId: number, repositoryKey: string, owner?: string) {
|
|
297
|
+
return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
|
|
298
|
+
const repository = this.database.getRepository('agentLoopPathLocks');
|
|
299
|
+
const lock = await repository.findOne({ filter: { runId, repositoryKey } });
|
|
300
|
+
if (!lock || ['released', 'expired'].includes(String(read(lock, 'status')))) return false;
|
|
301
|
+
if (owner !== undefined && String(read(lock, 'owner') || '') !== owner) return false;
|
|
302
|
+
await repository.update({
|
|
303
|
+
filterByTk: read(lock, 'id'),
|
|
304
|
+
values: { status: 'released', releasedAt: new Date(), blockerRunIds: [] },
|
|
305
|
+
});
|
|
306
|
+
return true;
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private async updateAndRead(
|
|
311
|
+
repository: ReturnType<Database['getRepository']>,
|
|
312
|
+
id: number,
|
|
313
|
+
values: Record<string, unknown>,
|
|
314
|
+
transaction: Transaction,
|
|
315
|
+
) {
|
|
316
|
+
await repository.update({ filterByTk: id, values, transaction });
|
|
317
|
+
const updated = await repository.findOne({ filterByTk: id, transaction });
|
|
318
|
+
if (!updated) throw new Error('Path lock disappeared during update.');
|
|
319
|
+
return updated;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import type { Model } from '@nocobase/database';
|
|
2
|
+
import type { Application } from '@nocobase/server';
|
|
3
|
+
import { AIEmployee } from '@nocobase/plugin-ai/server';
|
|
4
|
+
import { listSystemTools } from '@nocobase/ai';
|
|
5
|
+
import { getAIToolsManager } from '../utils/ai-manager';
|
|
6
|
+
import { decideTool } from './HarnessCompiler';
|
|
7
|
+
import type { CompiledHarness } from './HarnessCompiler';
|
|
8
|
+
|
|
9
|
+
// plugin-ai keeps every tool whose name is in `listSystemTools()` regardless of the constructor
|
|
10
|
+
// tool filter (ai-employee.ts getAIEmployeeTools). The harness `filter` cannot remove them, so a
|
|
11
|
+
// denied system tool would still reach the model. The adapter neutralizes them at their source
|
|
12
|
+
// instead: web search via the `webSearch` constructor flag, knowledge-base retrieval via the
|
|
13
|
+
// in-memory `enableKnowledgeBase` employee flag. This maps each system tool to the switch that
|
|
14
|
+
// stops plugin-ai from ever adding it.
|
|
15
|
+
const SYSTEM_TOOL_WEB_SEARCH = 'subAgentWebSearch';
|
|
16
|
+
const SYSTEM_TOOL_KNOWLEDGE_BASE = 'knowledge-base-retrieve';
|
|
17
|
+
|
|
18
|
+
export type LoopRole = 'leader' | 'maker' | 'verifier';
|
|
19
|
+
|
|
20
|
+
export type InterruptedToolCall = {
|
|
21
|
+
toolCallId: string;
|
|
22
|
+
toolName: string;
|
|
23
|
+
args: unknown;
|
|
24
|
+
interruptId: string;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export type InvocationOutcome = {
|
|
28
|
+
sessionId: string;
|
|
29
|
+
messageId: string;
|
|
30
|
+
interrupted: InterruptedToolCall[];
|
|
31
|
+
content: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
type ConversationsManager = {
|
|
35
|
+
create(input: {
|
|
36
|
+
userId?: number;
|
|
37
|
+
aiEmployee: { username: string };
|
|
38
|
+
title?: string;
|
|
39
|
+
options?: Record<string, unknown>;
|
|
40
|
+
category?: string;
|
|
41
|
+
}): Promise<Model>;
|
|
42
|
+
getUserDecisions(messageId: string): Promise<{ interruptId?: string; decisions: unknown[] } | undefined>;
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
type EmployeesManager = {
|
|
46
|
+
getEmployee(username: string): Promise<Model | null>;
|
|
47
|
+
resolveModel(employee: Model, model?: unknown): Promise<{ llmService: string; model: string }>;
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
type PluginAi = {
|
|
51
|
+
aiConversationsManager: ConversationsManager;
|
|
52
|
+
aiEmployeesManager: EmployeesManager;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function read(record: Model | Record<string, unknown>, key: string) {
|
|
56
|
+
const model = record as Model & { get?: (name: string) => unknown };
|
|
57
|
+
return typeof model.get === 'function' ? model.get(key) : (record as Record<string, unknown>)[key];
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function textContent(messages: unknown): string {
|
|
61
|
+
if (!Array.isArray(messages)) return '';
|
|
62
|
+
const last = messages[messages.length - 1] as { content?: unknown } | undefined;
|
|
63
|
+
if (typeof last?.content === 'string') return last.content;
|
|
64
|
+
if (Array.isArray(last?.content)) {
|
|
65
|
+
return last.content
|
|
66
|
+
.map((part) =>
|
|
67
|
+
typeof part === 'object' && part && 'text' in part ? String((part as { text: unknown }).text) : '',
|
|
68
|
+
)
|
|
69
|
+
.join('');
|
|
70
|
+
}
|
|
71
|
+
return '';
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function interruptedFrom(result: Record<string, unknown>): InterruptedToolCall[] {
|
|
75
|
+
const interrupts = result.__interrupt__;
|
|
76
|
+
if (!Array.isArray(interrupts)) return [];
|
|
77
|
+
const calls: InterruptedToolCall[] = [];
|
|
78
|
+
for (const interrupt of interrupts) {
|
|
79
|
+
const value = (interrupt as { value?: unknown }).value ?? interrupt;
|
|
80
|
+
const record = value as Record<string, unknown>;
|
|
81
|
+
const toolCallId = String(record.toolCallId || record.tool_call_id || '');
|
|
82
|
+
if (!toolCallId) continue;
|
|
83
|
+
calls.push({
|
|
84
|
+
toolCallId,
|
|
85
|
+
toolName: String(record.name || record.toolName || ''),
|
|
86
|
+
args: record.args ?? record.input ?? {},
|
|
87
|
+
interruptId: String((interrupt as { id?: unknown }).id || record.interruptId || ''),
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return calls;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// plugin-ai reads the compiled harness through two different channels, and they disagree on shape:
|
|
94
|
+
//
|
|
95
|
+
// 1. `skillSettings.tools` on the AIEmployee constructor is a `string[]` name filter once
|
|
96
|
+
// `toolsVersion` is set (ai-employee.ts `getAIEmployeeTools`).
|
|
97
|
+
// 2. `employee.skillSettings.tools` on the persisted record is a `{ name, autoCall }[]` that both
|
|
98
|
+
// widens the candidate tool set and decides whether a call interrupts (`isAutoCall`).
|
|
99
|
+
//
|
|
100
|
+
// Passing objects to (1) silently filtered out every tool, because `string[].includes(object)` is
|
|
101
|
+
// always false. Both channels are populated here, from the same decision, so a tool is exposed only
|
|
102
|
+
// when the harness allows it and interrupts whenever the harness says `ask`.
|
|
103
|
+
export type HarnessToolPlan = {
|
|
104
|
+
filter: string[];
|
|
105
|
+
employeeTools: Array<{ name: string; autoCall: boolean }>;
|
|
106
|
+
withheld: Array<{ name: string; reason: string }>;
|
|
107
|
+
// System tools the harness does not grant. They ignore `filter`, so the caller has to disable
|
|
108
|
+
// the feature that injects them rather than relying on the filter to drop them.
|
|
109
|
+
blockedSystemTools: string[];
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
type ToolEntry = { scope?: string; defaultPermission?: string } | undefined;
|
|
113
|
+
|
|
114
|
+
// `isAutoCall` only consults the employee override for CUSTOM-scope tools; every other scope is
|
|
115
|
+
// governed by the tool's own `defaultPermission`. So an `ask` decision is only enforceable when one
|
|
116
|
+
// of those two is true. When it is not, the tool is withheld rather than exposed un-gated.
|
|
117
|
+
function askIsEnforceable(entry: ToolEntry) {
|
|
118
|
+
return entry?.scope === 'CUSTOM' || entry?.defaultPermission !== 'ALLOW';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// Tool discovery must run with the same context plugin-ai uses. `DefaultToolsManager.getTools`
|
|
122
|
+
// only consults dynamic providers when a filter is supplied, and the MCP provider registers a
|
|
123
|
+
// user's context-scoped tools solely when `filter.ctx` is present. Discovering without it reports
|
|
124
|
+
// every MCP tool as unregistered even though `AIEmployee.getToolsMap()` would find it at call time.
|
|
125
|
+
export async function planHarnessTools(
|
|
126
|
+
app: Application,
|
|
127
|
+
harness: CompiledHarness,
|
|
128
|
+
discovery?: { ctx?: unknown; sessionId?: string },
|
|
129
|
+
): Promise<HarnessToolPlan> {
|
|
130
|
+
const toolsManager = getAIToolsManager(app);
|
|
131
|
+
const candidates = Array.from(new Set([...harness.tools.allow, ...harness.tools.ask]));
|
|
132
|
+
const plan: HarnessToolPlan = { filter: [], employeeTools: [], withheld: [], blockedSystemTools: [] };
|
|
133
|
+
const filter = discovery ? { ctx: discovery.ctx, sessionId: discovery.sessionId } : undefined;
|
|
134
|
+
|
|
135
|
+
for (const name of candidates.sort()) {
|
|
136
|
+
const decision = decideTool(harness, name);
|
|
137
|
+
if (decision === 'deny') {
|
|
138
|
+
plan.withheld.push({ name, reason: 'denied by harness' });
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const entry = (await toolsManager.getTools(name, filter)) as ToolEntry;
|
|
142
|
+
if (!entry) {
|
|
143
|
+
plan.withheld.push({ name, reason: 'not registered with plugin-ai' });
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (decision === 'ask' && !askIsEnforceable(entry)) {
|
|
147
|
+
plan.withheld.push({ name, reason: 'approval cannot be enforced for this tool' });
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
plan.filter.push(name);
|
|
151
|
+
plan.employeeTools.push({ name, autoCall: decision === 'allow' });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const granted = new Set(plan.filter);
|
|
155
|
+
plan.blockedSystemTools = listSystemTools()
|
|
156
|
+
.filter((name) => !granted.has(name))
|
|
157
|
+
.sort();
|
|
158
|
+
return plan;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export class PluginAiRuntimeAdapter {
|
|
162
|
+
constructor(private readonly app: Application) {}
|
|
163
|
+
|
|
164
|
+
private plugin(): PluginAi {
|
|
165
|
+
const plugin = this.app.pm.get('ai') as unknown as PluginAi | undefined;
|
|
166
|
+
if (!plugin?.aiEmployeesManager || !plugin?.aiConversationsManager) {
|
|
167
|
+
throw new Error('The official @nocobase/plugin-ai plugin is required to execute Loop Control Plane runs.');
|
|
168
|
+
}
|
|
169
|
+
return plugin;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
async createConversation(input: { username: string; userId?: number; runId: number; title: string }) {
|
|
173
|
+
const conversation = await this.plugin().aiConversationsManager.create({
|
|
174
|
+
userId: input.userId,
|
|
175
|
+
aiEmployee: { username: input.username },
|
|
176
|
+
title: input.title,
|
|
177
|
+
category: 'task',
|
|
178
|
+
options: { controlPlaneRunId: input.runId },
|
|
179
|
+
});
|
|
180
|
+
const sessionId = String(read(conversation, 'sessionId') || '');
|
|
181
|
+
if (!sessionId) throw new Error('The AI conversation was created without a session identifier.');
|
|
182
|
+
return sessionId;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async invoke(input: {
|
|
186
|
+
username: string;
|
|
187
|
+
sessionId: string;
|
|
188
|
+
userId?: number;
|
|
189
|
+
systemMessage: string;
|
|
190
|
+
harness: CompiledHarness;
|
|
191
|
+
prompt: string;
|
|
192
|
+
signal: AbortSignal;
|
|
193
|
+
}): Promise<InvocationOutcome> {
|
|
194
|
+
const { aiEmployee } = await this.buildEmployee(input);
|
|
195
|
+
|
|
196
|
+
const result = (await aiEmployee.invoke({
|
|
197
|
+
userMessages: [{ role: 'user', content: input.prompt }],
|
|
198
|
+
signal: input.signal,
|
|
199
|
+
})) as Record<string, unknown>;
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
sessionId: input.sessionId,
|
|
203
|
+
messageId: String(result.messageId || ''),
|
|
204
|
+
interrupted: interruptedFrom(result),
|
|
205
|
+
content: textContent(result.messages),
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Resume mirrors the official workflow employee node: flip the persisted tool call to
|
|
210
|
+
// `waiting` with a decision, then re-invoke so plugin-ai resumes its own checkpoint.
|
|
211
|
+
async resume(input: {
|
|
212
|
+
username: string;
|
|
213
|
+
sessionId: string;
|
|
214
|
+
messageId: string;
|
|
215
|
+
userId?: number;
|
|
216
|
+
systemMessage: string;
|
|
217
|
+
harness: CompiledHarness;
|
|
218
|
+
decision: { type: 'approve' | 'reject'; message?: string; editedAction?: { name: string; args: unknown } };
|
|
219
|
+
signal: AbortSignal;
|
|
220
|
+
}): Promise<InvocationOutcome> {
|
|
221
|
+
const plugin = this.plugin();
|
|
222
|
+
|
|
223
|
+
await this.app.db
|
|
224
|
+
.getModel('aiToolMessages')
|
|
225
|
+
.update(
|
|
226
|
+
{ userDecision: input.decision, invokeStatus: 'waiting' },
|
|
227
|
+
{ where: { sessionId: input.sessionId, messageId: input.messageId, invokeStatus: 'interrupted' } },
|
|
228
|
+
);
|
|
229
|
+
const userDecisions = await plugin.aiConversationsManager.getUserDecisions(input.messageId);
|
|
230
|
+
if (!userDecisions) throw new Error('The interrupted tool calls are not all ready to resume.');
|
|
231
|
+
|
|
232
|
+
const { aiEmployee } = await this.buildEmployee(input);
|
|
233
|
+
|
|
234
|
+
const result = (await aiEmployee.invoke({
|
|
235
|
+
messageId: input.messageId,
|
|
236
|
+
userDecisions: userDecisions as { interruptId?: string; decisions: never[] },
|
|
237
|
+
signal: input.signal,
|
|
238
|
+
})) as Record<string, unknown>;
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
sessionId: input.sessionId,
|
|
242
|
+
messageId: String(result.messageId || input.messageId),
|
|
243
|
+
interrupted: interruptedFrom(result),
|
|
244
|
+
content: textContent(result.messages),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// The employee model is re-read per invocation and mutated only in memory. `isAutoCall` reads
|
|
249
|
+
// `employee.skillSettings` off the Sequelize dataValues, so `set()` without `save()` gates this
|
|
250
|
+
// run's tool calls without touching the shared employee configuration.
|
|
251
|
+
private async buildEmployee(input: {
|
|
252
|
+
username: string;
|
|
253
|
+
sessionId: string;
|
|
254
|
+
userId?: number;
|
|
255
|
+
systemMessage: string;
|
|
256
|
+
harness: CompiledHarness;
|
|
257
|
+
}) {
|
|
258
|
+
const plugin = this.plugin();
|
|
259
|
+
const employee = await plugin.aiEmployeesManager.getEmployee(input.username);
|
|
260
|
+
if (!employee) throw new Error(`AI employee "${input.username}" was not found.`);
|
|
261
|
+
const model = await plugin.aiEmployeesManager.resolveModel(employee);
|
|
262
|
+
const currentRoles = await this.rolesFor(input.userId);
|
|
263
|
+
|
|
264
|
+
const ctx = {
|
|
265
|
+
app: this.app,
|
|
266
|
+
db: this.app.db,
|
|
267
|
+
log: this.app.log,
|
|
268
|
+
logger: this.app.log,
|
|
269
|
+
state: { currentRoles },
|
|
270
|
+
auth: { user: { id: input.userId } },
|
|
271
|
+
action: { params: { values: { sessionId: input.sessionId, model } } },
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// Discovery runs with the same ctx the invocation will use, so context-scoped MCP tools
|
|
275
|
+
// resolve here exactly as they will when plugin-ai builds its tool map.
|
|
276
|
+
const plan = await planHarnessTools(this.app, input.harness, { ctx, sessionId: input.sessionId });
|
|
277
|
+
|
|
278
|
+
if (plan.withheld.length) {
|
|
279
|
+
this.app.logger.info(
|
|
280
|
+
`[AgentOrchestrator] Harness withheld ${plan.withheld.length} tool(s) from ${input.username}.`,
|
|
281
|
+
{ withheld: plan.withheld },
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const persisted = (employee.get('skillSettings') || {}) as Record<string, unknown>;
|
|
286
|
+
employee.set('skillSettings', { ...persisted, tools: plan.employeeTools });
|
|
287
|
+
|
|
288
|
+
// plugin-ai adds `knowledge-base-retrieve` whenever the employee has knowledge base enabled,
|
|
289
|
+
// and keeps it through the tool filter because it is a system tool. Clearing the in-memory flag
|
|
290
|
+
// is the only way a harness that does not grant it actually keeps it out of the model's hands.
|
|
291
|
+
const blockedSystemTools = new Set(plan.blockedSystemTools);
|
|
292
|
+
if (blockedSystemTools.has(SYSTEM_TOOL_KNOWLEDGE_BASE)) {
|
|
293
|
+
employee.set('enableKnowledgeBase', false);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const aiEmployee = new AIEmployee({
|
|
297
|
+
ctx: ctx as never,
|
|
298
|
+
employee,
|
|
299
|
+
sessionId: input.sessionId,
|
|
300
|
+
systemMessage: input.systemMessage,
|
|
301
|
+
skillSettings: { skillsVersion: 2, toolsVersion: 2, skills: [], tools: plan.filter },
|
|
302
|
+
// Same reasoning for web search: the flag is what injects the system tool, so it is only
|
|
303
|
+
// ever enabled when the harness explicitly granted it.
|
|
304
|
+
webSearch: !blockedSystemTools.has(SYSTEM_TOOL_WEB_SEARCH),
|
|
305
|
+
model,
|
|
306
|
+
});
|
|
307
|
+
return { aiEmployee, plan };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
private async rolesFor(userId?: number) {
|
|
311
|
+
if (!userId) return [];
|
|
312
|
+
const rows = await this.app.db.getRepository('rolesUsers').find({ filter: { userId } });
|
|
313
|
+
return rows.map((row) => String(read(row, 'roleName') || '')).filter(Boolean);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
export const verificationVerdictSchema = z.object({
|
|
4
|
+
verdict: z.enum(['pass', 'reject', 'escalate']),
|
|
5
|
+
summary: z.string().min(1),
|
|
6
|
+
checks: z
|
|
7
|
+
.array(
|
|
8
|
+
z.object({
|
|
9
|
+
name: z.string().min(1),
|
|
10
|
+
status: z.enum(['pass', 'fail', 'skipped']),
|
|
11
|
+
evidenceArtifactIds: z.array(z.number().int().positive()).default([]),
|
|
12
|
+
}),
|
|
13
|
+
)
|
|
14
|
+
.min(1),
|
|
15
|
+
residualRisks: z.array(z.string()).default([]),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
export type VerificationVerdict = z.infer<typeof verificationVerdictSchema>;
|
|
19
|
+
|
|
20
|
+
export function parseVerificationVerdict(value: unknown) {
|
|
21
|
+
return verificationVerdictSchema.parse(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isPassingVerification(value: unknown) {
|
|
25
|
+
const parsed = verificationVerdictSchema.safeParse(value);
|
|
26
|
+
return (
|
|
27
|
+
parsed.success &&
|
|
28
|
+
parsed.data.verdict === 'pass' &&
|
|
29
|
+
parsed.data.checks.every((check) => check.status === 'pass' && check.evidenceArtifactIds.length > 0)
|
|
30
|
+
);
|
|
31
|
+
}
|