plugin-agent-orchestrator 1.0.32 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +114 -114
  2. package/dist/externalVersion.js +6 -6
  3. package/dist/server/collections/skill-executions.js +21 -0
  4. package/dist/server/plugin.js +132 -3
  5. package/dist/server/resources/agent-loop.js +1 -2
  6. package/dist/server/services/AgentLoopController.js +39 -1
  7. package/dist/server/services/AgentLoopService.js +3 -0
  8. package/dist/server/services/AgentRuntimeLifecycle.js +70 -0
  9. package/dist/server/services/FileManager.js +12 -0
  10. package/dist/server/services/NativeSubAgentObserver.js +20 -0
  11. package/dist/server/services/PlanningPromptService.js +95 -0
  12. package/dist/server/services/SandboxRunner.js +251 -56
  13. package/dist/server/services/TokenTracker.js +20 -0
  14. package/dist/server/services/WorkerEnvManager.js +76 -10
  15. package/dist/server/services/pythonGuardTemplate.js +105 -0
  16. package/dist/server/services/sandboxCapabilities.js +286 -0
  17. package/dist/server/skill-hub/plugin.js +98 -24
  18. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +53 -11
  19. package/dist/server/utils/skill-settings.js +1 -1
  20. package/package.json +47 -47
  21. package/src/client-v2/components/AgentRunsTab.tsx +494 -494
  22. package/src/client-v2/components/TracingTab.tsx +432 -432
  23. package/src/client-v2/hooks/useApiRequest.ts +121 -121
  24. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -0
  25. package/src/server/__tests__/planning-prompt-service.test.ts +23 -0
  26. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -0
  27. package/src/server/collections/skill-executions.ts +21 -0
  28. package/src/server/plugin.ts +151 -0
  29. package/src/server/resources/agent-loop.ts +1 -2
  30. package/src/server/resources/agent-monitor.ts +482 -482
  31. package/src/server/services/AgentLoopController.ts +50 -1
  32. package/src/server/services/AgentLoopService.ts +4 -0
  33. package/src/server/services/AgentRuntimeLifecycle.ts +64 -0
  34. package/src/server/services/ExecutionSpanService.ts +110 -110
  35. package/src/server/services/FileManager.ts +16 -1
  36. package/src/server/services/NativeSubAgentObserver.ts +528 -507
  37. package/src/server/services/PlanningPromptService.ts +72 -0
  38. package/src/server/services/SandboxRunner.ts +341 -74
  39. package/src/server/services/TokenTracker.ts +26 -0
  40. package/src/server/services/WorkerEnvManager.ts +95 -9
  41. package/src/server/services/pythonGuardTemplate.ts +87 -0
  42. package/src/server/services/sandboxCapabilities.ts +348 -0
  43. package/src/server/skill-hub/plugin.ts +106 -23
  44. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +51 -6
  45. package/src/server/utils/skill-settings.ts +1 -0
package/README.md CHANGED
@@ -1,114 +1,114 @@
1
- # plugin-agent-orchestrator
2
-
3
- ## Overview
4
- Hierarchical Multi-Agent orchestration for NocoBase AI Employees. Enables Leader agents to delegate tasks to Sub-Agent employees, with detailed execution tracing and context/memory management.
5
-
6
- ## Features
7
- - **Hierarchical Delegation**: Allows AI Leader agents to break down complex tasks and assign them to specialized sub-agents via native dispatching.
8
- - **Seamless Integration**: Plugs directly into the existing AI Employee framework, capturing execution spans.
9
- - **Execution Tracking**: Monitor sub-agent task execution and nested tool calls in detail within the main chat interface.
10
- - **External RAG Search**: Exposes `external_rag_search` so leaders and sub-agents can retrieve context from NocoBase knowledge bases, including external RAG services.
11
-
12
- ## Usage
13
- 1. Enable the plugin in the NocoBase Plugin Manager.
14
- 2. Navigate to the AI Employee configuration page.
15
- 3. Configure a primary "Leader" agent and specialized "Sub-Agent" employees.
16
- 4. Add the built-in **AI employee task dispatching** (`dispatch-sub-agent-task`) tool to the Leader agent.
17
- 5. Ensure the user role has access to both the Leader and Sub-Agent employees (configured via employee roles mapping).
18
- 6. Interact with the Leader agent; it will automatically delegate tasks to the sub-agents when necessary.
19
-
20
-
21
- ## External RAG / Embedding service
22
-
23
- Recommended approach: keep source ownership in NocoBase and move chunking, embedding, vector storage, and retrieval to an external lightweight RAG service. This plugin should not own vector infrastructure directly. It delegates search to `plugin-knowledge-base`, which already supports knowledge bases of type `EXTERNAL_RAG`.
24
-
25
- ### Architecture
26
-
27
- 1. NocoBase stores the source metadata:
28
- - uploaded file attachment id, filename, storage id, URL, owner/role access, or
29
- - datasource/collection/record id for database-backed knowledge.
30
- 2. The external RAG service owns:
31
- - document fetching or receiving source payloads,
32
- - parsing/chunking,
33
- - embedding,
34
- - vector index,
35
- - retrieval.
36
- 3. NocoBase creates a knowledge base with `type = EXTERNAL_RAG` and `options` such as:
37
- - `ragProvider: "external-http"`
38
- - `ragApiUrl: "https://rag.example.com/search"`
39
- - `ragApiKey`
40
- - `ragNamespace`
41
- - `ragTopK`
42
- - `ragScoreThreshold`
43
- 4. Agents use the `external_rag_search` tool. The tool calls `plugin-knowledge-base.searchKnowledgeBases()`, so access control and mixed local/external search remain centralized.
44
-
45
- ### External search contract
46
-
47
- The built-in `external-http` strategy expects:
48
-
49
- ```http
50
- POST /search
51
- Authorization: Bearer <ragApiKey>
52
- Content-Type: application/json
53
- ```
54
-
55
- ```json
56
- {
57
- "query": "search text",
58
- "topK": 5,
59
- "scoreThreshold": 0.3,
60
- "namespace": "optional-kb-namespace",
61
- "filter": {}
62
- }
63
- ```
64
-
65
- Response:
66
-
67
- ```json
68
- {
69
- "results": [
70
- {
71
- "id": "chunk-or-source-id",
72
- "content": "matched text",
73
- "score": 0.82,
74
- "metadata": {
75
- "fileId": "123",
76
- "filename": "contract.pdf",
77
- "collection": "orders",
78
- "recordId": "456",
79
- "sourceUrl": "/api/attachments/123:download"
80
- }
81
- }
82
- ]
83
- }
84
- ```
85
-
86
- The important rule is that every result should return enough metadata for NocoBase to resolve the original source: `fileId`/`filename` for files, or `collection`/`recordId` for datasource records.
87
-
88
- ### Lightweight open-source service target
89
-
90
- For a small but useful deployment, use a standalone service with:
91
-
92
- - Qdrant or LanceDB for vector search.
93
- - FastAPI or Express for `/ingest`, `/delete`, and `/search`.
94
- - A small embedding model such as `BAAI/bge-small-en-v1.5`, `intfloat/multilingual-e5-small`, or another model matching the deployment language.
95
- - A namespace per NocoBase knowledge base.
96
-
97
- Minimum API surface:
98
-
99
- - `POST /ingest`: receive `{ namespace, source, content | fileUrl | storageRef, metadata }`.
100
- - `POST /delete`: receive `{ namespace, sourceId }`.
101
- - `POST /search`: implement the contract above.
102
-
103
- For NocoBase datasource knowledge, send each record as a source document with metadata `{ collection, recordId, fields, updatedAt }`; the RAG service chunks and embeds the selected text fields, then returns `collection` and `recordId` in search results.
104
-
105
- ### E5/OpenAI-compatible embedding
106
-
107
- If the external RAG service uses an E5 family model behind an OpenAI-compatible `/v1/embeddings` API, configure the NocoBase knowledge base with `ragProvider: "e5-http"`. `plugin-knowledge-base` will read the selected embedding LLM service and forward its `baseURL`, `apiKey`, and model to the RAG service.
108
-
109
- - embed user queries as `query: <question>`;
110
- - embed document chunks as `passage: <chunk>`;
111
- - use the same model for ingest and search;
112
- - recreate the vector collection when changing models or vector dimensions.
113
-
114
- The RAG service still owns chunking, embedding calls, vector storage, and metadata mapping. NocoBase owns the LLM service configuration and search authorization path.
1
+ # plugin-agent-orchestrator
2
+
3
+ ## Overview
4
+ Hierarchical Multi-Agent orchestration for NocoBase AI Employees. Enables Leader agents to delegate tasks to Sub-Agent employees, with detailed execution tracing and context/memory management.
5
+
6
+ ## Features
7
+ - **Hierarchical Delegation**: Allows AI Leader agents to break down complex tasks and assign them to specialized sub-agents via native dispatching.
8
+ - **Seamless Integration**: Plugs directly into the existing AI Employee framework, capturing execution spans.
9
+ - **Execution Tracking**: Monitor sub-agent task execution and nested tool calls in detail within the main chat interface.
10
+ - **External RAG Search**: Exposes `external_rag_search` so leaders and sub-agents can retrieve context from NocoBase knowledge bases, including external RAG services.
11
+
12
+ ## Usage
13
+ 1. Enable the plugin in the NocoBase Plugin Manager.
14
+ 2. Navigate to the AI Employee configuration page.
15
+ 3. Configure a primary "Leader" agent and specialized "Sub-Agent" employees.
16
+ 4. Add the built-in **AI employee task dispatching** (`dispatch-sub-agent-task`) tool to the Leader agent.
17
+ 5. Ensure the user role has access to both the Leader and Sub-Agent employees (configured via employee roles mapping).
18
+ 6. Interact with the Leader agent; it will automatically delegate tasks to the sub-agents when necessary.
19
+
20
+
21
+ ## External RAG / Embedding service
22
+
23
+ Recommended approach: keep source ownership in NocoBase and move chunking, embedding, vector storage, and retrieval to an external lightweight RAG service. This plugin should not own vector infrastructure directly. It delegates search to `plugin-knowledge-base`, which already supports knowledge bases of type `EXTERNAL_RAG`.
24
+
25
+ ### Architecture
26
+
27
+ 1. NocoBase stores the source metadata:
28
+ - uploaded file attachment id, filename, storage id, URL, owner/role access, or
29
+ - datasource/collection/record id for database-backed knowledge.
30
+ 2. The external RAG service owns:
31
+ - document fetching or receiving source payloads,
32
+ - parsing/chunking,
33
+ - embedding,
34
+ - vector index,
35
+ - retrieval.
36
+ 3. NocoBase creates a knowledge base with `type = EXTERNAL_RAG` and `options` such as:
37
+ - `ragProvider: "external-http"`
38
+ - `ragApiUrl: "https://rag.example.com/search"`
39
+ - `ragApiKey`
40
+ - `ragNamespace`
41
+ - `ragTopK`
42
+ - `ragScoreThreshold`
43
+ 4. Agents use the `external_rag_search` tool. The tool calls `plugin-knowledge-base.searchKnowledgeBases()`, so access control and mixed local/external search remain centralized.
44
+
45
+ ### External search contract
46
+
47
+ The built-in `external-http` strategy expects:
48
+
49
+ ```http
50
+ POST /search
51
+ Authorization: Bearer <ragApiKey>
52
+ Content-Type: application/json
53
+ ```
54
+
55
+ ```json
56
+ {
57
+ "query": "search text",
58
+ "topK": 5,
59
+ "scoreThreshold": 0.3,
60
+ "namespace": "optional-kb-namespace",
61
+ "filter": {}
62
+ }
63
+ ```
64
+
65
+ Response:
66
+
67
+ ```json
68
+ {
69
+ "results": [
70
+ {
71
+ "id": "chunk-or-source-id",
72
+ "content": "matched text",
73
+ "score": 0.82,
74
+ "metadata": {
75
+ "fileId": "123",
76
+ "filename": "contract.pdf",
77
+ "collection": "orders",
78
+ "recordId": "456",
79
+ "sourceUrl": "/api/attachments/123:download"
80
+ }
81
+ }
82
+ ]
83
+ }
84
+ ```
85
+
86
+ The important rule is that every result should return enough metadata for NocoBase to resolve the original source: `fileId`/`filename` for files, or `collection`/`recordId` for datasource records.
87
+
88
+ ### Lightweight open-source service target
89
+
90
+ For a small but useful deployment, use a standalone service with:
91
+
92
+ - Qdrant or LanceDB for vector search.
93
+ - FastAPI or Express for `/ingest`, `/delete`, and `/search`.
94
+ - A small embedding model such as `BAAI/bge-small-en-v1.5`, `intfloat/multilingual-e5-small`, or another model matching the deployment language.
95
+ - A namespace per NocoBase knowledge base.
96
+
97
+ Minimum API surface:
98
+
99
+ - `POST /ingest`: receive `{ namespace, source, content | fileUrl | storageRef, metadata }`.
100
+ - `POST /delete`: receive `{ namespace, sourceId }`.
101
+ - `POST /search`: implement the contract above.
102
+
103
+ For NocoBase datasource knowledge, send each record as a source document with metadata `{ collection, recordId, fields, updatedAt }`; the RAG service chunks and embeds the selected text fields, then returns `collection` and `recordId` in search results.
104
+
105
+ ### E5/OpenAI-compatible embedding
106
+
107
+ If the external RAG service uses an E5 family model behind an OpenAI-compatible `/v1/embeddings` API, configure the NocoBase knowledge base with `ragProvider: "e5-http"`. `plugin-knowledge-base` will read the selected embedding LLM service and forward its `baseURL`, `apiKey`, and model to the RAG service.
108
+
109
+ - embed user queries as `query: <question>`;
110
+ - embed document chunks as `passage: <chunk>`;
111
+ - use the same model for ingest and search;
112
+ - recreate the vector collection when changing models or vector dimensions.
113
+
114
+ The RAG service still owns chunking, embedding calls, vector storage, and metadata mapping. NocoBase owns the LLM service configuration and search authorization path.
@@ -10,12 +10,12 @@
10
10
  module.exports = {
11
11
  "react": "18.2.0",
12
12
  "ahooks": "3.7.8",
13
- "@nocobase/client-v2": "2.1.9",
13
+ "@nocobase/client-v2": "2.1.23",
14
14
  "antd": "5.24.2",
15
15
  "@ant-design/icons": "5.6.1",
16
- "@nocobase/client": "2.1.9",
17
- "@nocobase/server": "2.1.9",
18
- "@nocobase/database": "2.1.9",
19
- "@nocobase/ai": "2.1.9",
20
- "@nocobase/actions": "2.1.9"
16
+ "@nocobase/client": "2.1.23",
17
+ "@nocobase/server": "2.1.23",
18
+ "@nocobase/database": "2.1.23",
19
+ "@nocobase/ai": "2.1.23",
20
+ "@nocobase/actions": "2.1.23"
21
21
  };
@@ -79,6 +79,27 @@ var skill_executions_default = {
79
79
  name: "durationMs",
80
80
  type: "integer"
81
81
  },
82
+ {
83
+ name: "startedAt",
84
+ type: "date",
85
+ allowNull: true
86
+ },
87
+ {
88
+ name: "heartbeatAt",
89
+ type: "date",
90
+ allowNull: true
91
+ },
92
+ {
93
+ name: "workerId",
94
+ type: "string",
95
+ length: 200,
96
+ allowNull: true
97
+ },
98
+ {
99
+ name: "retryCount",
100
+ type: "integer",
101
+ defaultValue: 0
102
+ },
82
103
  {
83
104
  name: "sessionId",
84
105
  type: "string",
@@ -45,10 +45,15 @@ var import_path = __toESM(require("path"));
45
45
  var import_external_rag_search = require("./tools/external-rag-search");
46
46
  var import_tracing = require("./resources/tracing");
47
47
  var import_agent_monitor = require("./resources/agent-monitor");
48
+ var import_agent_loop = require("./resources/agent-loop");
48
49
  var import_plugin = __toESM(require("./skill-hub/plugin"));
49
50
  var import_NativeSubAgentObserver = require("./services/NativeSubAgentObserver");
51
+ var import_AgentLoopService = require("./services/AgentLoopService");
52
+ var import_agent_loop2 = require("./tools/agent-loop");
53
+ var import_PlanningPromptService = require("./services/PlanningPromptService");
50
54
  var import_ctx_utils = require("./utils/ctx-utils");
51
55
  var import_ai_manager = require("./utils/ai-manager");
56
+ var import_AgentRuntimeLifecycle = require("./services/AgentRuntimeLifecycle");
52
57
  function normalizeOptionalString(value) {
53
58
  return typeof value === "string" ? value.trim() : "";
54
59
  }
@@ -148,6 +153,7 @@ async function resolveTracingRetentionDays(plugin) {
148
153
  class PluginAgentOrchestratorServer extends import_server.Plugin {
149
154
  skillHub;
150
155
  nativeObserver;
156
+ agentRuntimeLifecycle;
151
157
  installNativeObserver = () => {
152
158
  var _a;
153
159
  (_a = this.nativeObserver) == null ? void 0 : _a.install();
@@ -155,6 +161,12 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
155
161
  async afterAdd() {
156
162
  this.skillHub = new import_plugin.default(this);
157
163
  this.nativeObserver = new import_NativeSubAgentObserver.NativeSubAgentObserver(this);
164
+ this.agentRuntimeLifecycle = new import_AgentRuntimeLifecycle.AgentRuntimeLifecycle((hookType, name, error) => {
165
+ this.app.logger.warn(`[AgentOrchestrator] ${hookType} hook "${name}" failed; continuing agent execution.`, {
166
+ error
167
+ });
168
+ });
169
+ this.app.agentRuntimeLifecycle = this.agentRuntimeLifecycle;
158
170
  }
159
171
  async beforeLoad() {
160
172
  this.db.import({ directory: import_path.default.resolve(__dirname, "collections") });
@@ -165,7 +177,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
165
177
  });
166
178
  }
167
179
  async load() {
168
- var _a, _b;
180
+ var _a, _b, _c, _d;
169
181
  await this.skillHub.load();
170
182
  this.app.acl.registerSnippet({
171
183
  name: `pm.${this.name}`,
@@ -196,6 +208,7 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
196
208
  this.app.acl.allow("skillHub", "download", "loggedIn");
197
209
  this.app.acl.allow("skillHub", "listTemplates", "loggedIn");
198
210
  this.app.acl.allow("agentMonitor", ["list", "get"], "loggedIn");
211
+ this.app.acl.allow("agentLoops", ["list", "get"], "loggedIn");
199
212
  this.app.resourceManager.use(
200
213
  async (ctx, next) => {
201
214
  const { resourceName, actionName } = ctx.action || {};
@@ -220,11 +233,35 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
220
233
  },
221
234
  { tag: "orchestrator-agent-memory-context-policy", after: "acl" }
222
235
  );
236
+ const planningPrompt = new import_PlanningPromptService.PlanningPromptService();
237
+ this.agentRuntimeLifecycle.registerBeforeRunHook("orchestrator-planning", (context) => {
238
+ if (planningPrompt.applyPlanningContext(context.messages)) {
239
+ context.metadata.planningPromptInjected = true;
240
+ }
241
+ });
242
+ this.app.resourceManager.use(
243
+ async (ctx, next) => {
244
+ const { resourceName, actionName } = ctx.action || {};
245
+ if (resourceName === "aiConversations" && actionName === "sendMessages") {
246
+ const values = ctx.action.params.values || {};
247
+ const messages = values.messages;
248
+ if (Array.isArray(messages)) {
249
+ planningPrompt.applyPlanningContext(messages);
250
+ }
251
+ }
252
+ await next();
253
+ },
254
+ { tag: "orchestrator-planning-prompt", after: "acl" }
255
+ );
223
256
  const toolsManager = (0, import_ai_manager.getAIToolsManager)(this.app);
224
257
  toolsManager.registerTools((0, import_external_rag_search.createExternalRagSearchTool)(this));
258
+ const agentLoopService = new import_AgentLoopService.AgentLoopService(this);
259
+ toolsManager.registerTools((0, import_agent_loop2.createAgentLoopTools)(this, agentLoopService));
260
+ (0, import_agent_loop.registerAgentLoopResource)(this, agentLoopService);
225
261
  (0, import_agent_monitor.registerAgentMonitorResource)(this);
226
262
  this.installNativeObserver();
227
263
  (_b = (_a = this.app).on) == null ? void 0 : _b.call(_a, "afterStart", this.installNativeObserver);
264
+ (_d = (_c = this.app).on) == null ? void 0 : _d.call(_c, "afterStart", this.recoverAfterCrash);
228
265
  (0, import_tracing.registerTracingResource)(this);
229
266
  this.app.cronJobManager.addJob({
230
267
  cronTime: "0 30 2 * * *",
@@ -261,12 +298,104 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
261
298
  async remove() {
262
299
  }
263
300
  async beforeStop() {
264
- var _a, _b, _c, _d, _e;
301
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
265
302
  (_b = (_a = this.app).off) == null ? void 0 : _b.call(_a, "afterStart", this.installNativeObserver);
266
303
  (_d = (_c = this.app).removeListener) == null ? void 0 : _d.call(_c, "afterStart", this.installNativeObserver);
267
- (_e = this.nativeObserver) == null ? void 0 : _e.uninstall();
304
+ (_f = (_e = this.app).off) == null ? void 0 : _f.call(_e, "afterStart", this.recoverAfterCrash);
305
+ (_h = (_g = this.app).removeListener) == null ? void 0 : _h.call(_g, "afterStart", this.recoverAfterCrash);
306
+ (_i = this.nativeObserver) == null ? void 0 : _i.uninstall();
268
307
  await this.skillHub.beforeStop();
269
308
  }
309
+ // --- Crash Recovery ---
310
+ // Scans for agentLoopSteps stuck in "running" status from a previous crash
311
+ // and resets them to "pending". Also cleans up orphaned agentLoopRuns where
312
+ // all steps have reached terminal states but the run itself wasn't finalized.
313
+ recoverAfterCrash = async () => {
314
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
315
+ const timeoutMs = Number(process.env.ORCHESTRATOR_CRASH_RECOVERY_TIMEOUT_MS || 6e5);
316
+ const cutoff = new Date(Date.now() - timeoutMs);
317
+ try {
318
+ const stepsRepo = this.db.getRepository("agentLoopSteps");
319
+ const runsRepo = this.db.getRepository("agentLoopRuns");
320
+ if (stepsRepo) {
321
+ const staleSteps = await stepsRepo.find({
322
+ filter: {
323
+ status: "running",
324
+ startedAt: { $lt: cutoff.toISOString() }
325
+ }
326
+ });
327
+ for (const step of staleSteps) {
328
+ const stepId = readModelValue(step, "id");
329
+ const runId = readModelValue(step, "runId");
330
+ await stepsRepo.update({
331
+ filterByTk: stepId,
332
+ values: {
333
+ status: "pending",
334
+ startedAt: null,
335
+ error: `Recovered after crash at ${(/* @__PURE__ */ new Date()).toISOString()}`
336
+ }
337
+ });
338
+ (_b = (_a = this.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(
339
+ _a,
340
+ `[AgentOrchestrator] Crash recovery: reset step ${stepId} (run ${runId}) from running to pending`
341
+ );
342
+ }
343
+ if (staleSteps.length > 0) {
344
+ (_d = (_c = this.app.logger) == null ? void 0 : _c.info) == null ? void 0 : _d.call(
345
+ _c,
346
+ `[AgentOrchestrator] Crash recovery: reset ${staleSteps.length} stale running step(s)`
347
+ );
348
+ }
349
+ }
350
+ if (runsRepo) {
351
+ const runningRuns = await runsRepo.find({
352
+ filter: { status: "running" }
353
+ });
354
+ for (const run of runningRuns) {
355
+ const runId = readModelValue(run, "id");
356
+ const steps = await (stepsRepo == null ? void 0 : stepsRepo.find({
357
+ filter: { runId }
358
+ }));
359
+ if (!steps || steps.length === 0) {
360
+ await runsRepo.update({
361
+ filterByTk: runId,
362
+ values: {
363
+ status: "failed",
364
+ endedAt: /* @__PURE__ */ new Date(),
365
+ summary: "Run was orphaned after server crash (no steps found)."
366
+ }
367
+ });
368
+ (_f = (_e = this.app.logger) == null ? void 0 : _e.warn) == null ? void 0 : _f.call(
369
+ _e,
370
+ `[AgentOrchestrator] Crash recovery: marked orphaned run ${runId} as failed (no steps)`
371
+ );
372
+ continue;
373
+ }
374
+ const allTerminal = steps.every((s) => {
375
+ const st = readModelValue(s, "status");
376
+ return st === "succeeded" || st === "failed" || st === "skipped";
377
+ });
378
+ if (!allTerminal) continue;
379
+ const anyFailed = steps.some((s) => readModelValue(s, "status") === "failed");
380
+ const finalStatus = anyFailed ? "failed" : "succeeded";
381
+ await runsRepo.update({
382
+ filterByTk: runId,
383
+ values: {
384
+ status: finalStatus,
385
+ endedAt: /* @__PURE__ */ new Date(),
386
+ summary: `Run finalized as ${finalStatus} after server crash recovery.`
387
+ }
388
+ });
389
+ (_h = (_g = this.app.logger) == null ? void 0 : _g.warn) == null ? void 0 : _h.call(
390
+ _g,
391
+ `[AgentOrchestrator] Crash recovery: finalized orphaned run ${runId} as ${finalStatus}`
392
+ );
393
+ }
394
+ }
395
+ } catch (error) {
396
+ (_j = (_i = this.app.logger) == null ? void 0 : _i.error) == null ? void 0 : _j.call(_i, "[AgentOrchestrator] Crash recovery scan failed", error);
397
+ }
398
+ };
270
399
  }
271
400
  var plugin_default = PluginAgentOrchestratorServer;
272
401
  // Annotate the CommonJS export names for ESM import in node:
@@ -119,9 +119,8 @@ function registerAgentLoopResource(plugin, service) {
119
119
  return;
120
120
  }
121
121
  ctx.body = {
122
- data: await service.approvePlanAndExecute(runId, {
122
+ data: await service.approvePlan(runId, {
123
123
  userId: (0, import_ctx_utils.currentUserId)(ctx),
124
- ctx,
125
124
  reason: body.reason
126
125
  })
127
126
  };
@@ -235,6 +235,38 @@ class AgentLoopController {
235
235
  });
236
236
  return this.getRunDetail(run.id);
237
237
  }
238
+ async approvePlan(runId, options = {}) {
239
+ const run = await this.repository.requireRun(runId);
240
+ if (TERMINAL_RUN_STATUSES.has(run.status)) {
241
+ throw new Error(`Agent loop run ${run.id} is already ${run.status}.`);
242
+ }
243
+ if (!["waiting_plan_approval", "approved", "needs_replan"].includes(run.status)) {
244
+ throw new Error(`Run ${run.id} is not waiting for plan approval.`);
245
+ }
246
+ await this.repository.updateRun(run.id, {
247
+ status: "approved",
248
+ approvalStatus: "approved",
249
+ approvedById: options.userId,
250
+ approvedAt: now(),
251
+ rejectionReason: "",
252
+ changeRequest: "",
253
+ updatedAt: now()
254
+ });
255
+ await this.repository.createEvent({
256
+ runId: run.id,
257
+ type: "plan_approved",
258
+ title: "Plan approved",
259
+ content: options.reason || "",
260
+ status: "approved",
261
+ userId: options.userId,
262
+ payload: { planVersion: run.planVersion || 1 }
263
+ });
264
+ return this.getRunDetail(run.id);
265
+ }
266
+ /**
267
+ * @deprecated Use approvePlan() instead. Auto-execution via AgentHarness is retired;
268
+ * step execution is now driven by the AI via agent_loop_update_step tools.
269
+ */
238
270
  async approvePlanAndExecute(runId, options = {}) {
239
271
  const run = await this.repository.requireRun(runId);
240
272
  if (TERMINAL_RUN_STATUSES.has(run.status)) {
@@ -498,6 +530,9 @@ class AgentLoopController {
498
530
  status: "succeeded",
499
531
  userId: options.userId
500
532
  });
533
+ if (step.type === "sub_agent" && step.target && run.leaderUsername) {
534
+ (0, import_CircuitBreaker.getCircuitBreaker)().recordSuccess((0, import_CircuitBreaker.subAgentCircuitKey)(run.leaderUsername, step.target));
535
+ }
501
536
  return this.getRunSnapshot(run.id);
502
537
  }
503
538
  async failStep(stepId, error, options = {}) {
@@ -533,6 +568,9 @@ class AgentLoopController {
533
568
  retryable: Number(step.attempt || 0) < Number(step.maxAttempts || policy.maxStepAttempts)
534
569
  }
535
570
  });
571
+ if (step.type === "sub_agent" && step.target && run.leaderUsername) {
572
+ (0, import_CircuitBreaker.getCircuitBreaker)().recordFailure((0, import_CircuitBreaker.subAgentCircuitKey)(run.leaderUsername, step.target));
573
+ }
536
574
  return this.getRunSnapshot(run.id);
537
575
  }
538
576
  async skipStep(stepId, reason = "Skipped", options = {}) {
@@ -647,7 +685,7 @@ class AgentLoopController {
647
685
  }
648
686
  });
649
687
  if (options.approved) {
650
- return this.executeApprovedPlan(run.id, { userId: options.userId, ctx: options.ctx });
688
+ return this.getRunSnapshot(run.id);
651
689
  }
652
690
  return this.getRunSnapshot(run.id);
653
691
  }
@@ -75,6 +75,9 @@ class AgentLoopService {
75
75
  async revisePlanGoal(runId, plan, options = {}) {
76
76
  return this.controller.revisePlanGoal(runId, plan, options);
77
77
  }
78
+ async approvePlan(runId, options = {}) {
79
+ return this.controller.approvePlan(runId, options);
80
+ }
78
81
  async approvePlanAndExecute(runId, options = {}) {
79
82
  return this.controller.approvePlanAndExecute(runId, options);
80
83
  }
@@ -0,0 +1,70 @@
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 AgentRuntimeLifecycle_exports = {};
28
+ __export(AgentRuntimeLifecycle_exports, {
29
+ AgentRuntimeLifecycle: () => AgentRuntimeLifecycle
30
+ });
31
+ module.exports = __toCommonJS(AgentRuntimeLifecycle_exports);
32
+ class AgentRuntimeLifecycle {
33
+ constructor(onHookError) {
34
+ this.onHookError = onHookError;
35
+ }
36
+ beforeRunHooks = /* @__PURE__ */ new Map();
37
+ afterRunHooks = /* @__PURE__ */ new Map();
38
+ registerBeforeRunHook(name, hook) {
39
+ this.beforeRunHooks.set(name, hook);
40
+ return () => this.beforeRunHooks.delete(name);
41
+ }
42
+ registerAfterRunHook(name, hook) {
43
+ this.afterRunHooks.set(name, hook);
44
+ return () => this.afterRunHooks.delete(name);
45
+ }
46
+ async runBeforeHooks(context) {
47
+ var _a;
48
+ for (const [name, hook] of this.beforeRunHooks) {
49
+ try {
50
+ await hook(context);
51
+ } catch (error) {
52
+ (_a = this.onHookError) == null ? void 0 : _a.call(this, "beforeRun", name, error instanceof Error ? error : new Error(String(error)));
53
+ }
54
+ }
55
+ }
56
+ async runAfterHooks(context, result) {
57
+ var _a;
58
+ for (const [name, hook] of this.afterRunHooks) {
59
+ try {
60
+ await hook(context, result);
61
+ } catch (error) {
62
+ (_a = this.onHookError) == null ? void 0 : _a.call(this, "afterRun", name, error instanceof Error ? error : new Error(String(error)));
63
+ }
64
+ }
65
+ }
66
+ }
67
+ // Annotate the CommonJS export names for ESM import in node:
68
+ 0 && (module.exports = {
69
+ AgentRuntimeLifecycle
70
+ });
@@ -70,6 +70,18 @@ class FileManager {
70
70
  getOutputDir(execId) {
71
71
  return (0, import_path.resolve)(this.executionsDir, execId, "output");
72
72
  }
73
+ /**
74
+ * Hand the execution directory to the dropped-privilege sandbox user so the
75
+ * child can read its script and write output. Requires root (chown), which
76
+ * matches the only case privilege drop is active.
77
+ */
78
+ chownExecDir(execId, uid, gid) {
79
+ const dir = (0, import_path.resolve)(this.executionsDir, execId);
80
+ (0, import_fs.chownSync)(dir, uid, gid);
81
+ for (const entry of (0, import_fs.readdirSync)(dir)) {
82
+ (0, import_fs.chownSync)((0, import_path.resolve)(dir, entry), uid, gid);
83
+ }
84
+ }
73
85
  /**
74
86
  * Returns absolute path to an output file, or null if invalid/not found.
75
87
  * Includes path traversal protection.