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
|
@@ -32,10 +32,14 @@ __export(NativeSubAgentObserver_exports, {
|
|
|
32
32
|
});
|
|
33
33
|
module.exports = __toCommonJS(NativeSubAgentObserver_exports);
|
|
34
34
|
var import_crypto = require("crypto");
|
|
35
|
+
var import_fs = require("fs");
|
|
36
|
+
var import_path = require("path");
|
|
35
37
|
var import_ExecutionSpanService = require("./ExecutionSpanService");
|
|
36
38
|
var import_AgentMemoryContextService = require("./AgentMemoryContextService");
|
|
37
39
|
var import_TokenTracker = require("./TokenTracker");
|
|
38
40
|
var import_AgentExecutionContext = require("./AgentExecutionContext");
|
|
41
|
+
var import_HarnessCompiler = require("./HarnessCompiler");
|
|
42
|
+
var import_harness_runtime_policy = require("./harness-runtime-policy");
|
|
39
43
|
var import_ctx_utils = require("../utils/ctx-utils");
|
|
40
44
|
const WRAP_STATE_KEY = Symbol.for("plugin-agent-orchestrator.nativeSubAgentObserver");
|
|
41
45
|
const NATIVE_SOURCE = "native-plugin-ai";
|
|
@@ -132,13 +136,23 @@ class NativeSubAgentObserver {
|
|
|
132
136
|
return originalRun(task);
|
|
133
137
|
}
|
|
134
138
|
const parentSessionId = this.resolveParentSessionId(task) || void 0;
|
|
139
|
+
const parentConversation = await this.safeFindParentConversation(task.ctx, parentSessionId);
|
|
140
|
+
const parentRunId = this.controlPlaneRunIdOf(parentConversation);
|
|
141
|
+
const parentRunHarness = parentRunId ? await this.safeResolveParentRunHarness(
|
|
142
|
+
parentRunId,
|
|
143
|
+
normalizeString(readValue(parentConversation, "aiEmployeeUsername"))
|
|
144
|
+
) : null;
|
|
145
|
+
const policy = this.compilePolicy(settings, parentRunHarness);
|
|
146
|
+
const spansEnabled = policy.observability.sharing !== "disabled";
|
|
135
147
|
const subSessionId = normalizeString(task.sessionId) || void 0;
|
|
136
148
|
const employeeUsername = modelUsername(task.employee);
|
|
137
149
|
const userId = (0, import_ctx_utils.currentUserId)(task.ctx) || ((_c = (_b = (_a = task.ctx) == null ? void 0 : _a.auth) == null ? void 0 : _b.user) == null ? void 0 : _c.id);
|
|
138
150
|
const dispatchToolMessage = await this.resolveDispatchToolMessage(task.ctx, parentSessionId, subSessionId);
|
|
139
151
|
const toolCallId = dispatchToolMessage == null ? void 0 : dispatchToolMessage.toolCallId;
|
|
140
|
-
const leaderUsername =
|
|
152
|
+
const leaderUsername = this.leaderUsernameFor(task.ctx, parentConversation);
|
|
141
153
|
const rootRunId = makeNativeRunId([parentSessionId, subSessionId, toolCallId, employeeUsername]);
|
|
154
|
+
const delegation = await this.resolveDelegationContext(parentSessionId);
|
|
155
|
+
const childDepth = delegation.depth + 1;
|
|
142
156
|
const memory = await this.safeBuildMemoryContext({
|
|
143
157
|
userId,
|
|
144
158
|
aiEmployeeUsername: employeeUsername,
|
|
@@ -169,7 +183,8 @@ ${task.question}
|
|
|
169
183
|
memoryContextApplied: Boolean(memory.context),
|
|
170
184
|
memoryScopes: memory.appliedScopes,
|
|
171
185
|
memoryContextChars: memory.chars,
|
|
172
|
-
harnessTag: settings.harnessTag || "default"
|
|
186
|
+
harnessTag: settings.harnessTag || "default",
|
|
187
|
+
...parentRunId ? { agentLoopRunId: parentRunId } : {}
|
|
173
188
|
},
|
|
174
189
|
parentSessionId,
|
|
175
190
|
subSessionId,
|
|
@@ -177,10 +192,29 @@ ${task.question}
|
|
|
177
192
|
leaderUsername,
|
|
178
193
|
employeeUsername,
|
|
179
194
|
userId,
|
|
195
|
+
policy,
|
|
180
196
|
toolSpans: /* @__PURE__ */ new Map(),
|
|
181
197
|
pending: /* @__PURE__ */ new Set()
|
|
182
198
|
};
|
|
183
|
-
|
|
199
|
+
if (spansEnabled) {
|
|
200
|
+
await this.safeCreateRootSpan(state, task.question, {
|
|
201
|
+
depth: childDepth,
|
|
202
|
+
parentSpanId: delegation.parentSpanId,
|
|
203
|
+
agentLoopRunId: parentRunId
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const maxDepth = policy.delegation.maxDepth;
|
|
207
|
+
if (maxDepth !== null && childDepth > maxDepth) {
|
|
208
|
+
const message = `Sub-agent delegation depth ${childDepth} exceeds the harness limit of ${maxDepth}.`;
|
|
209
|
+
await this.spanService.finish(state.rootSpanId, "error", state.rootStartedAt, {
|
|
210
|
+
error: message,
|
|
211
|
+
metadata: {
|
|
212
|
+
...state.rootMetadata,
|
|
213
|
+
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
throw new Error(message);
|
|
217
|
+
}
|
|
184
218
|
const originalWriter = task.writer;
|
|
185
219
|
observedTask.writer = (chunk) => {
|
|
186
220
|
const pending = this.handleWriterChunk(state, chunk).catch((error) => {
|
|
@@ -191,7 +225,7 @@ ${task.question}
|
|
|
191
225
|
return originalWriter == null ? void 0 : originalWriter(chunk);
|
|
192
226
|
};
|
|
193
227
|
try {
|
|
194
|
-
const
|
|
228
|
+
const rawResult = await (0, import_AgentExecutionContext.runWithAgentExecutionContext)(
|
|
195
229
|
{
|
|
196
230
|
rootRunId,
|
|
197
231
|
spanId: state.rootSpanId ? String(state.rootSpanId) : void 0,
|
|
@@ -202,9 +236,11 @@ ${task.question}
|
|
|
202
236
|
},
|
|
203
237
|
() => this.runWithKnowledgeBaseAgentContext(employeeUsername, () => originalRun(observedTask))
|
|
204
238
|
);
|
|
239
|
+
const result = this.spillLargeResult(state, rawResult);
|
|
205
240
|
await this.flushPending(state);
|
|
241
|
+
const capturedOutput = this.spanOutput(state, (0, import_ctx_utils.trimText)(result, 2e4));
|
|
206
242
|
await this.spanService.finish(state.rootSpanId, "success", state.rootStartedAt, {
|
|
207
|
-
output:
|
|
243
|
+
...capturedOutput !== void 0 ? { output: capturedOutput } : {},
|
|
208
244
|
metadata: {
|
|
209
245
|
...state.rootMetadata,
|
|
210
246
|
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -219,8 +255,9 @@ ${task.question}
|
|
|
219
255
|
return result;
|
|
220
256
|
} catch (error) {
|
|
221
257
|
await this.flushPending(state);
|
|
258
|
+
const capturedError = this.spanOutput(state, (0, import_ctx_utils.trimText)(errorMessage(error), 1e4));
|
|
222
259
|
await this.spanService.finish(state.rootSpanId, "error", state.rootStartedAt, {
|
|
223
|
-
|
|
260
|
+
...capturedError !== void 0 ? { error: capturedError } : {},
|
|
224
261
|
metadata: {
|
|
225
262
|
...state.rootMetadata,
|
|
226
263
|
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
@@ -244,6 +281,59 @@ ${task.question}
|
|
|
244
281
|
return { harnessTag: "default" };
|
|
245
282
|
}
|
|
246
283
|
}
|
|
284
|
+
// Span payload gates: inputs are captured only under 'full' sharing, outputs under 'full' or
|
|
285
|
+
// 'feedback-only'. Redaction scrubs secret-looking keys on whatever is captured; free text is
|
|
286
|
+
// deliberately left alone.
|
|
287
|
+
spanInput(state, input) {
|
|
288
|
+
const observability = state.policy.observability;
|
|
289
|
+
if (observability.sharing !== "full" || !observability.captureInputs) return void 0;
|
|
290
|
+
return observability.redactSecrets ? (0, import_harness_runtime_policy.redactSecretsIn)(input) : input;
|
|
291
|
+
}
|
|
292
|
+
spanOutput(state, output) {
|
|
293
|
+
const observability = state.policy.observability;
|
|
294
|
+
if (observability.sharing === "disabled" || !observability.captureOutputs) return void 0;
|
|
295
|
+
return observability.redactSecrets ? (0, import_harness_runtime_policy.redactSecretsIn)(output) : output;
|
|
296
|
+
}
|
|
297
|
+
// Resolved settings are a raw profile record plus the harnessTag marker; the marker is not a
|
|
298
|
+
// schema field. On any compile trouble fall back to an empty (all-default) harness so the
|
|
299
|
+
// safety defaults — redaction on, sharing full — still govern the spans.
|
|
300
|
+
compilePolicy(settings, parentRunHarness) {
|
|
301
|
+
var _a, _b;
|
|
302
|
+
const tag = typeof settings.harnessTag === "string" && settings.harnessTag.trim() ? settings.harnessTag.trim() : "default";
|
|
303
|
+
const { harnessTag: _harnessTag, ...rest } = settings;
|
|
304
|
+
try {
|
|
305
|
+
const layers = [];
|
|
306
|
+
if (parentRunHarness) {
|
|
307
|
+
const { sources, ...inherited } = parentRunHarness;
|
|
308
|
+
layers.push({ source: `run-role:${sources.join("+") || "snapshot"}`, settings: inherited });
|
|
309
|
+
}
|
|
310
|
+
layers.push({ source: `profile:${tag}`, settings: rest });
|
|
311
|
+
return (0, import_HarnessCompiler.compileHarness)(layers);
|
|
312
|
+
} catch (error) {
|
|
313
|
+
(_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to compile observer harness policy", error);
|
|
314
|
+
return (0, import_HarnessCompiler.compileHarness)([{ source: "default", settings: {} }]);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
// Oversized sub-agent results are stored on disk and replaced by a head/tail preview plus the
|
|
318
|
+
// file path, so the parent conversation can read the full text back with its file tools.
|
|
319
|
+
// Best effort: a spill failure keeps the original result inline.
|
|
320
|
+
spillLargeResult(state, result) {
|
|
321
|
+
var _a, _b;
|
|
322
|
+
const maxInlineBytes = state.policy.context.spill.maxInlineBytes;
|
|
323
|
+
if (!maxInlineBytes || typeof result !== "string") return result;
|
|
324
|
+
try {
|
|
325
|
+
const spillDir = (0, import_path.resolve)(process.cwd(), "storage", "plugin-agent-orchestrator", "spills");
|
|
326
|
+
(0, import_fs.mkdirSync)(spillDir, { recursive: true });
|
|
327
|
+
const spillPath = (0, import_path.resolve)(spillDir, `${state.rootRunId}-${Date.now()}.txt`);
|
|
328
|
+
const replaced = (0, import_harness_runtime_policy.spilledText)(result, maxInlineBytes, spillPath);
|
|
329
|
+
if (!replaced) return result;
|
|
330
|
+
(0, import_fs.writeFileSync)(spillPath, result, "utf8");
|
|
331
|
+
return replaced;
|
|
332
|
+
} catch (error) {
|
|
333
|
+
(_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Sub-agent result spill failed", error);
|
|
334
|
+
return result;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
247
337
|
async safeBuildMemoryContext(options) {
|
|
248
338
|
var _a, _b;
|
|
249
339
|
try {
|
|
@@ -253,10 +343,12 @@ ${task.question}
|
|
|
253
343
|
return { context: "", appliedScopes: [], chars: 0 };
|
|
254
344
|
}
|
|
255
345
|
}
|
|
256
|
-
async safeCreateRootSpan(state, question) {
|
|
346
|
+
async safeCreateRootSpan(state, question, delegationInfo) {
|
|
257
347
|
const span = await this.spanService.create({
|
|
258
348
|
rootRunId: state.rootRunId,
|
|
259
|
-
parentSpanId:
|
|
349
|
+
parentSpanId: delegationInfo.parentSpanId,
|
|
350
|
+
depth: delegationInfo.depth,
|
|
351
|
+
agentLoopRunId: delegationInfo.agentLoopRunId,
|
|
260
352
|
source: NATIVE_SOURCE,
|
|
261
353
|
parentSessionId: state.parentSessionId,
|
|
262
354
|
subSessionId: state.subSessionId,
|
|
@@ -267,11 +359,11 @@ ${task.question}
|
|
|
267
359
|
employeeUsername: state.employeeUsername,
|
|
268
360
|
toolName: "dispatch-sub-agent-task",
|
|
269
361
|
title: `${state.leaderUsername || "main"} -> ${state.employeeUsername || "sub-agent"}`,
|
|
270
|
-
input: {
|
|
362
|
+
input: this.spanInput(state, {
|
|
271
363
|
question,
|
|
272
364
|
parentSessionId: state.parentSessionId,
|
|
273
365
|
subSessionId: state.subSessionId
|
|
274
|
-
},
|
|
366
|
+
}),
|
|
275
367
|
metadata: state.rootMetadata,
|
|
276
368
|
userId: state.userId
|
|
277
369
|
});
|
|
@@ -306,6 +398,7 @@ ${task.question}
|
|
|
306
398
|
}
|
|
307
399
|
}
|
|
308
400
|
async handleBeforeToolCall(state, chunk) {
|
|
401
|
+
if (state.policy.observability.sharing === "disabled") return;
|
|
309
402
|
const body = chunkBody(chunk);
|
|
310
403
|
const toolCall = (0, import_ctx_utils.asObject)(body.toolCall);
|
|
311
404
|
const toolCallId = normalizeString(toolCall.id);
|
|
@@ -331,7 +424,7 @@ ${task.question}
|
|
|
331
424
|
employeeUsername: normalizeString(conversation.username) || state.employeeUsername,
|
|
332
425
|
toolName,
|
|
333
426
|
title: toolName || "tool call",
|
|
334
|
-
input: (0, import_ctx_utils.asObject)(toolCall.args),
|
|
427
|
+
input: this.spanInput(state, (0, import_ctx_utils.asObject)(toolCall.args)),
|
|
335
428
|
metadata: {
|
|
336
429
|
source: NATIVE_SOURCE,
|
|
337
430
|
currentConversation: conversation,
|
|
@@ -363,8 +456,8 @@ ${task.question}
|
|
|
363
456
|
status,
|
|
364
457
|
endedAt: /* @__PURE__ */ new Date(),
|
|
365
458
|
durationMs,
|
|
366
|
-
output: forceError ? void 0 : (0, import_ctx_utils.trimText)(output, 2e4),
|
|
367
|
-
error: forceError ? (0, import_ctx_utils.trimText)(errorMessage(error), 1e4) : void 0,
|
|
459
|
+
output: forceError ? void 0 : this.spanOutput(state, (0, import_ctx_utils.trimText)(output, 2e4)),
|
|
460
|
+
error: forceError ? this.spanOutput(state, (0, import_ctx_utils.trimText)(errorMessage(error), 1e4)) : void 0,
|
|
368
461
|
skillExecutionId,
|
|
369
462
|
metadata: {
|
|
370
463
|
source: NATIVE_SOURCE,
|
|
@@ -400,20 +493,69 @@ ${task.question}
|
|
|
400
493
|
const values = ((_c = (_b = (_a = task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values) || {};
|
|
401
494
|
return normalizeString(values.sessionId) || void 0;
|
|
402
495
|
}
|
|
403
|
-
|
|
404
|
-
var _a, _b
|
|
496
|
+
leaderUsernameFor(ctx, parentConversation) {
|
|
497
|
+
var _a, _b;
|
|
405
498
|
const values = ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || {};
|
|
406
499
|
const direct = normalizeString(values.aiEmployeeUsername) || normalizeString((0, import_ctx_utils.asObject)(values.aiEmployee).username);
|
|
407
|
-
|
|
408
|
-
|
|
500
|
+
return direct || normalizeString(readValue(parentConversation, "aiEmployeeUsername")) || void 0;
|
|
501
|
+
}
|
|
502
|
+
async safeFindParentConversation(ctx, parentSessionId) {
|
|
503
|
+
var _a, _b, _c;
|
|
504
|
+
if (!parentSessionId) return null;
|
|
409
505
|
try {
|
|
410
|
-
const repo = (
|
|
411
|
-
const conversation = await ((
|
|
412
|
-
|
|
413
|
-
}));
|
|
414
|
-
return normalizeString(readValue(conversation, "aiEmployeeUsername")) || void 0;
|
|
506
|
+
const repo = (_b = (_a = ctx.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "aiConversations");
|
|
507
|
+
const conversation = await ((_c = repo == null ? void 0 : repo.findOne) == null ? void 0 : _c.call(repo, { filter: { sessionId: parentSessionId } }));
|
|
508
|
+
return conversation || null;
|
|
415
509
|
} catch {
|
|
416
|
-
return
|
|
510
|
+
return null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
controlPlaneRunIdOf(conversation) {
|
|
514
|
+
const runId = Number((0, import_ctx_utils.asObject)(readValue(conversation, "options")).controlPlaneRunId);
|
|
515
|
+
return Number.isSafeInteger(runId) && runId > 0 ? runId : void 0;
|
|
516
|
+
}
|
|
517
|
+
async safeResolveParentRunHarness(runId, parentUsername) {
|
|
518
|
+
var _a, _b;
|
|
519
|
+
if (!parentUsername) return null;
|
|
520
|
+
try {
|
|
521
|
+
return await (0, import_harness_runtime_policy.resolveRunRoleHarness)(this.plugin.db, runId, parentUsername);
|
|
522
|
+
} catch (error) {
|
|
523
|
+
(_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to resolve parent run harness for delegation", error);
|
|
524
|
+
return null;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
// The parent's persisted span is the authoritative depth source: it was recorded when the
|
|
528
|
+
// parent itself was dispatched, so a resumed child arrives with its true depth even though its
|
|
529
|
+
// in-process context is fresh. The runtime context can only confirm or deepen the count, never
|
|
530
|
+
// lower it.
|
|
531
|
+
async resolveDelegationContext(parentSessionId) {
|
|
532
|
+
var _a;
|
|
533
|
+
const candidates = [];
|
|
534
|
+
const context = (0, import_AgentExecutionContext.getAgentExecutionContext)();
|
|
535
|
+
if (context == null ? void 0 : context.spanId) {
|
|
536
|
+
const span = await this.safeFindSpan({ filterByTk: context.spanId });
|
|
537
|
+
if (span) candidates.push(span);
|
|
538
|
+
}
|
|
539
|
+
if (parentSessionId) {
|
|
540
|
+
const span = await this.safeFindSpan({
|
|
541
|
+
filter: { subSessionId: parentSessionId, type: "sub_agent" },
|
|
542
|
+
sort: ["-id"]
|
|
543
|
+
});
|
|
544
|
+
if (span) candidates.push(span);
|
|
545
|
+
}
|
|
546
|
+
const depth = candidates.reduce((deepest, span) => Math.max(deepest, Number(span.depth) || 0), 0);
|
|
547
|
+
const parentSpanId = (_a = candidates.find((span) => span.id !== void 0)) == null ? void 0 : _a.id;
|
|
548
|
+
return { parentSpanId: parentSpanId === void 0 ? void 0 : String(parentSpanId), depth };
|
|
549
|
+
}
|
|
550
|
+
async safeFindSpan(options) {
|
|
551
|
+
var _a, _b;
|
|
552
|
+
try {
|
|
553
|
+
const repo = this.plugin.db.getRepository("agentExecutionSpans");
|
|
554
|
+
if (!repo || typeof repo.findOne !== "function") return null;
|
|
555
|
+
return await repo.findOne(options) || null;
|
|
556
|
+
} catch (error) {
|
|
557
|
+
(_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to resolve delegation parent span", error);
|
|
558
|
+
return null;
|
|
417
559
|
}
|
|
418
560
|
}
|
|
419
561
|
async resolveDispatchToolMessage(ctx, parentSessionId, subSessionId) {
|
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
var __defProp = Object.defineProperty;
|
|
11
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
12
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
13
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
14
|
+
var __export = (target, all) => {
|
|
15
|
+
for (var name in all)
|
|
16
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
17
|
+
};
|
|
18
|
+
var __copyProps = (to, from, except, desc) => {
|
|
19
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
20
|
+
for (let key of __getOwnPropNames(from))
|
|
21
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
22
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
23
|
+
}
|
|
24
|
+
return to;
|
|
25
|
+
};
|
|
26
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
27
|
+
var PathLockService_exports = {};
|
|
28
|
+
__export(PathLockService_exports, {
|
|
29
|
+
PathLockService: () => PathLockService,
|
|
30
|
+
lockPathsOverlap: () => lockPathsOverlap,
|
|
31
|
+
normalizeLockPath: () => normalizeLockPath,
|
|
32
|
+
pathSetsOverlap: () => pathSetsOverlap,
|
|
33
|
+
waitGraphHasCycle: () => waitGraphHasCycle
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(PathLockService_exports);
|
|
36
|
+
function read(record, key) {
|
|
37
|
+
const model = record;
|
|
38
|
+
return typeof model.get === "function" ? model.get(key) : record[key];
|
|
39
|
+
}
|
|
40
|
+
function positiveInteger(value) {
|
|
41
|
+
const parsed = Number(value);
|
|
42
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : null;
|
|
43
|
+
}
|
|
44
|
+
function asDate(value) {
|
|
45
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
|
|
46
|
+
if (typeof value === "string" || typeof value === "number") {
|
|
47
|
+
const parsed = new Date(value);
|
|
48
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
function lockIsExpired(record, now) {
|
|
53
|
+
const expiresAt = asDate(read(record, "expiresAt"));
|
|
54
|
+
return !expiresAt || expiresAt.getTime() <= now.getTime();
|
|
55
|
+
}
|
|
56
|
+
function positiveTtl(ttlMs) {
|
|
57
|
+
if (!Number.isSafeInteger(ttlMs) || ttlMs <= 0) {
|
|
58
|
+
throw new Error("Path lock TTL must be a positive number of milliseconds.");
|
|
59
|
+
}
|
|
60
|
+
return ttlMs;
|
|
61
|
+
}
|
|
62
|
+
function normalizeLockPath(value) {
|
|
63
|
+
const normalized = value.trim().replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/{2,}/g, "/");
|
|
64
|
+
if (!normalized || normalized.startsWith("/") || /^[a-zA-Z]:\//.test(normalized)) {
|
|
65
|
+
throw new Error(`Lock path must be repository-relative: ${value}`);
|
|
66
|
+
}
|
|
67
|
+
const segments = normalized.split("/");
|
|
68
|
+
if (segments.some((segment) => segment === ".." || segment === ".")) {
|
|
69
|
+
throw new Error(`Lock path cannot contain dot segments: ${value}`);
|
|
70
|
+
}
|
|
71
|
+
return normalized.replace(/\/$/, "");
|
|
72
|
+
}
|
|
73
|
+
function literalPrefix(pattern) {
|
|
74
|
+
const result = [];
|
|
75
|
+
for (const segment of normalizeLockPath(pattern).split("/")) {
|
|
76
|
+
if (/[*?{[\]]/.test(segment)) break;
|
|
77
|
+
result.push(segment);
|
|
78
|
+
}
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
function lockPathsOverlap(left, right) {
|
|
82
|
+
const leftNormalized = normalizeLockPath(left);
|
|
83
|
+
const rightNormalized = normalizeLockPath(right);
|
|
84
|
+
if (leftNormalized === rightNormalized) return true;
|
|
85
|
+
const leftPrefix = literalPrefix(leftNormalized);
|
|
86
|
+
const rightPrefix = literalPrefix(rightNormalized);
|
|
87
|
+
if (leftPrefix.length === 0 || rightPrefix.length === 0) return true;
|
|
88
|
+
const shared = Math.min(leftPrefix.length, rightPrefix.length);
|
|
89
|
+
for (let index = 0; index < shared; index += 1) {
|
|
90
|
+
if (leftPrefix[index] !== rightPrefix[index]) return false;
|
|
91
|
+
}
|
|
92
|
+
const leftHasPattern = leftPrefix.length < leftNormalized.split("/").length;
|
|
93
|
+
const rightHasPattern = rightPrefix.length < rightNormalized.split("/").length;
|
|
94
|
+
if (leftHasPattern || rightHasPattern) return true;
|
|
95
|
+
return leftPrefix.length !== rightPrefix.length;
|
|
96
|
+
}
|
|
97
|
+
function pathSetsOverlap(left, right) {
|
|
98
|
+
return left.some((leftPath) => right.some((rightPath) => lockPathsOverlap(leftPath, rightPath)));
|
|
99
|
+
}
|
|
100
|
+
function row(record) {
|
|
101
|
+
const status = read(record, "status");
|
|
102
|
+
return {
|
|
103
|
+
id: positiveInteger(read(record, "id")) || 0,
|
|
104
|
+
runId: positiveInteger(read(record, "runId")) || 0,
|
|
105
|
+
repositoryKey: String(read(record, "repositoryKey") || ""),
|
|
106
|
+
paths: Array.isArray(read(record, "paths")) ? read(record, "paths") : [],
|
|
107
|
+
status: status === "held" || status === "released" || status === "expired" ? status : "waiting",
|
|
108
|
+
blockerRunIds: Array.isArray(read(record, "blockerRunIds")) ? read(record, "blockerRunIds").map(positiveInteger).filter((value) => value !== null) : []
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function waitGraphHasCycle(rows, runId, blockers) {
|
|
112
|
+
const graph = /* @__PURE__ */ new Map();
|
|
113
|
+
for (const lock of rows) {
|
|
114
|
+
if (lock.status === "waiting") graph.set(lock.runId, lock.blockerRunIds);
|
|
115
|
+
}
|
|
116
|
+
graph.set(runId, blockers);
|
|
117
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
118
|
+
const visited = /* @__PURE__ */ new Set();
|
|
119
|
+
const visit = (node) => {
|
|
120
|
+
if (visiting.has(node)) return true;
|
|
121
|
+
if (visited.has(node)) return false;
|
|
122
|
+
visiting.add(node);
|
|
123
|
+
for (const blocker of graph.get(node) || []) {
|
|
124
|
+
if (visit(blocker)) return true;
|
|
125
|
+
}
|
|
126
|
+
visiting.delete(node);
|
|
127
|
+
visited.add(node);
|
|
128
|
+
return false;
|
|
129
|
+
};
|
|
130
|
+
return visit(runId);
|
|
131
|
+
}
|
|
132
|
+
class PathLockService {
|
|
133
|
+
constructor(database, distributedLock) {
|
|
134
|
+
this.database = database;
|
|
135
|
+
this.distributedLock = distributedLock;
|
|
136
|
+
}
|
|
137
|
+
async acquire(input) {
|
|
138
|
+
const paths = Array.from(new Set(input.paths.map(normalizeLockPath))).sort();
|
|
139
|
+
if (!paths.length) throw new Error("At least one repository path is required for a path lock.");
|
|
140
|
+
const repositoryKey = input.repositoryKey.trim();
|
|
141
|
+
if (!repositoryKey) throw new Error("Repository key is required for a path lock.");
|
|
142
|
+
const ttlMs = positiveTtl(input.ttlMs);
|
|
143
|
+
return this.distributedLock.runExclusive(
|
|
144
|
+
`agent-loop:path:${repositoryKey}`,
|
|
145
|
+
() => this.database.sequelize.transaction(async (transaction) => {
|
|
146
|
+
const repository = this.database.getRepository("agentLoopPathLocks");
|
|
147
|
+
const now = /* @__PURE__ */ new Date();
|
|
148
|
+
const existing = await repository.findOne({
|
|
149
|
+
filter: { runId: input.runId, repositoryKey },
|
|
150
|
+
transaction,
|
|
151
|
+
lock: transaction.LOCK.UPDATE
|
|
152
|
+
});
|
|
153
|
+
if (existing && read(existing, "status") === "held") {
|
|
154
|
+
const sameOwner = String(read(existing, "owner") || "") === input.owner;
|
|
155
|
+
const samePaths = JSON.stringify(row(existing).paths.slice().sort()) === JSON.stringify(paths);
|
|
156
|
+
if (sameOwner && samePaths && !lockIsExpired(existing, now)) {
|
|
157
|
+
return { acquired: true, lock: row(existing), blockers: [] };
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const held = await repository.find({
|
|
161
|
+
filter: { repositoryKey, status: "held" },
|
|
162
|
+
transaction,
|
|
163
|
+
lock: transaction.LOCK.UPDATE
|
|
164
|
+
});
|
|
165
|
+
const active = [];
|
|
166
|
+
for (const lock of held) {
|
|
167
|
+
if (!lockIsExpired(lock, now)) {
|
|
168
|
+
active.push(lock);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
await repository.update({
|
|
172
|
+
filterByTk: read(lock, "id"),
|
|
173
|
+
values: { status: "expired", releasedAt: now, blockerRunIds: [] },
|
|
174
|
+
transaction
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const blockers = active.map(row).filter((lock) => lock.runId !== input.runId && pathSetsOverlap(paths, lock.paths)).map((lock) => lock.runId);
|
|
178
|
+
if (blockers.length) {
|
|
179
|
+
const waitingRows = (await repository.find({
|
|
180
|
+
filter: { repositoryKey, status: "waiting" },
|
|
181
|
+
transaction,
|
|
182
|
+
lock: transaction.LOCK.UPDATE
|
|
183
|
+
})).map(row);
|
|
184
|
+
if (waitGraphHasCycle(waitingRows, input.runId, blockers)) {
|
|
185
|
+
return { acquired: false, deadlocked: true, blockers };
|
|
186
|
+
}
|
|
187
|
+
const values2 = {
|
|
188
|
+
runId: input.runId,
|
|
189
|
+
repositoryKey,
|
|
190
|
+
owner: input.owner,
|
|
191
|
+
paths,
|
|
192
|
+
status: "waiting",
|
|
193
|
+
blockerRunIds: blockers,
|
|
194
|
+
waitUntil: input.waitUntil || null,
|
|
195
|
+
acquiredAt: null,
|
|
196
|
+
expiresAt: null,
|
|
197
|
+
releasedAt: null
|
|
198
|
+
};
|
|
199
|
+
if (existing) {
|
|
200
|
+
await repository.update({ filterByTk: read(existing, "id"), values: values2, transaction });
|
|
201
|
+
} else {
|
|
202
|
+
await repository.create({ values: values2, transaction });
|
|
203
|
+
}
|
|
204
|
+
return { acquired: false, deadlocked: false, blockers };
|
|
205
|
+
}
|
|
206
|
+
const values = {
|
|
207
|
+
runId: input.runId,
|
|
208
|
+
repositoryKey,
|
|
209
|
+
owner: input.owner,
|
|
210
|
+
paths,
|
|
211
|
+
status: "held",
|
|
212
|
+
blockerRunIds: [],
|
|
213
|
+
acquiredAt: now,
|
|
214
|
+
expiresAt: new Date(now.getTime() + ttlMs),
|
|
215
|
+
waitUntil: null,
|
|
216
|
+
releasedAt: null
|
|
217
|
+
};
|
|
218
|
+
const locked = existing ? await this.updateAndRead(repository, Number(read(existing, "id")), values, transaction) : await repository.create({ values, transaction });
|
|
219
|
+
return { acquired: true, lock: row(locked), blockers: [] };
|
|
220
|
+
}),
|
|
221
|
+
Math.max(ttlMs, 5e3)
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
async renew(runId, repositoryKey, ttlMs, owner) {
|
|
225
|
+
const ttl = positiveTtl(ttlMs);
|
|
226
|
+
return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
|
|
227
|
+
const repository = this.database.getRepository("agentLoopPathLocks");
|
|
228
|
+
const expired = await this.database.sequelize.transaction(async (transaction) => {
|
|
229
|
+
const lock = await repository.findOne({
|
|
230
|
+
filter: { runId, repositoryKey, status: "held" },
|
|
231
|
+
transaction,
|
|
232
|
+
lock: transaction.LOCK.UPDATE
|
|
233
|
+
});
|
|
234
|
+
if (!lock) throw new Error("Held path lock was not found.");
|
|
235
|
+
if (owner !== void 0 && String(read(lock, "owner") || "") !== owner) {
|
|
236
|
+
throw new Error("Path lock is no longer owned by this worker.");
|
|
237
|
+
}
|
|
238
|
+
const now = /* @__PURE__ */ new Date();
|
|
239
|
+
if (lockIsExpired(lock, now)) return { id: read(lock, "id"), at: now };
|
|
240
|
+
await repository.update({
|
|
241
|
+
filterByTk: read(lock, "id"),
|
|
242
|
+
values: { expiresAt: new Date(now.getTime() + ttl) },
|
|
243
|
+
transaction
|
|
244
|
+
});
|
|
245
|
+
return null;
|
|
246
|
+
});
|
|
247
|
+
if (expired) {
|
|
248
|
+
await this.database.sequelize.transaction(async (transaction) => {
|
|
249
|
+
await repository.update({
|
|
250
|
+
filterByTk: expired.id,
|
|
251
|
+
values: { status: "expired", releasedAt: expired.at, blockerRunIds: [] },
|
|
252
|
+
transaction
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
throw new Error("Path lock has expired and must be reacquired.");
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
// The owner token guards against a reclaimed run: once a stale worker's lease expires and another
|
|
260
|
+
// worker takes over the same run, the original worker must not free a lock the new owner now holds.
|
|
261
|
+
async release(runId, repositoryKey, owner) {
|
|
262
|
+
return this.distributedLock.runExclusive(`agent-loop:path:${repositoryKey}`, async () => {
|
|
263
|
+
const repository = this.database.getRepository("agentLoopPathLocks");
|
|
264
|
+
const lock = await repository.findOne({ filter: { runId, repositoryKey } });
|
|
265
|
+
if (!lock || ["released", "expired"].includes(String(read(lock, "status")))) return false;
|
|
266
|
+
if (owner !== void 0 && String(read(lock, "owner") || "") !== owner) return false;
|
|
267
|
+
await repository.update({
|
|
268
|
+
filterByTk: read(lock, "id"),
|
|
269
|
+
values: { status: "released", releasedAt: /* @__PURE__ */ new Date(), blockerRunIds: [] }
|
|
270
|
+
});
|
|
271
|
+
return true;
|
|
272
|
+
});
|
|
273
|
+
}
|
|
274
|
+
async updateAndRead(repository, id, values, transaction) {
|
|
275
|
+
await repository.update({ filterByTk: id, values, transaction });
|
|
276
|
+
const updated = await repository.findOne({ filterByTk: id, transaction });
|
|
277
|
+
if (!updated) throw new Error("Path lock disappeared during update.");
|
|
278
|
+
return updated;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
282
|
+
0 && (module.exports = {
|
|
283
|
+
PathLockService,
|
|
284
|
+
lockPathsOverlap,
|
|
285
|
+
normalizeLockPath,
|
|
286
|
+
pathSetsOverlap,
|
|
287
|
+
waitGraphHasCycle
|
|
288
|
+
});
|