plugin-agent-orchestrator 1.0.33 → 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.
- package/dist/externalVersion.js +6 -6
- package/dist/server/collections/skill-executions.js +21 -0
- package/dist/server/plugin.js +132 -3
- package/dist/server/resources/agent-loop.js +1 -2
- package/dist/server/services/AgentLoopController.js +39 -1
- package/dist/server/services/AgentLoopService.js +3 -0
- package/dist/server/services/AgentRuntimeLifecycle.js +70 -0
- package/dist/server/services/FileManager.js +12 -0
- package/dist/server/services/NativeSubAgentObserver.js +20 -0
- package/dist/server/services/PlanningPromptService.js +95 -0
- package/dist/server/services/SandboxRunner.js +251 -56
- package/dist/server/services/TokenTracker.js +20 -0
- package/dist/server/services/WorkerEnvManager.js +76 -10
- package/dist/server/services/pythonGuardTemplate.js +105 -0
- package/dist/server/services/sandboxCapabilities.js +286 -0
- package/dist/server/skill-hub/plugin.js +98 -24
- package/dist/server/skill-hub/tasks/SkillExecutionTask.js +53 -11
- package/dist/server/utils/skill-settings.js +1 -1
- package/package.json +47 -47
- package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -0
- package/src/server/__tests__/planning-prompt-service.test.ts +23 -0
- package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -0
- package/src/server/collections/skill-executions.ts +21 -0
- package/src/server/plugin.ts +151 -0
- package/src/server/resources/agent-loop.ts +1 -2
- package/src/server/services/AgentLoopController.ts +50 -1
- package/src/server/services/AgentLoopService.ts +4 -0
- package/src/server/services/AgentRuntimeLifecycle.ts +64 -0
- package/src/server/services/FileManager.ts +16 -1
- package/src/server/services/NativeSubAgentObserver.ts +21 -0
- package/src/server/services/PlanningPromptService.ts +72 -0
- package/src/server/services/SandboxRunner.ts +341 -74
- package/src/server/services/TokenTracker.ts +26 -0
- package/src/server/services/WorkerEnvManager.ts +95 -9
- package/src/server/services/pythonGuardTemplate.ts +87 -0
- package/src/server/services/sandboxCapabilities.ts +348 -0
- package/src/server/skill-hub/plugin.ts +1099 -1016
- package/src/server/skill-hub/tasks/SkillExecutionTask.ts +515 -470
- package/src/server/utils/skill-settings.ts +1 -0
package/dist/externalVersion.js
CHANGED
|
@@ -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.
|
|
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.
|
|
17
|
-
"@nocobase/server": "2.1.
|
|
18
|
-
"@nocobase/database": "2.1.
|
|
19
|
-
"@nocobase/ai": "2.1.
|
|
20
|
-
"@nocobase/actions": "2.1.
|
|
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",
|
package/dist/server/plugin.js
CHANGED
|
@@ -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.
|
|
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.
|
|
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.
|
|
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.
|
|
@@ -34,6 +34,7 @@ module.exports = __toCommonJS(NativeSubAgentObserver_exports);
|
|
|
34
34
|
var import_crypto = require("crypto");
|
|
35
35
|
var import_ExecutionSpanService = require("./ExecutionSpanService");
|
|
36
36
|
var import_AgentMemoryContextService = require("./AgentMemoryContextService");
|
|
37
|
+
var import_TokenTracker = require("./TokenTracker");
|
|
37
38
|
var import_ctx_utils = require("../utils/ctx-utils");
|
|
38
39
|
const WRAP_STATE_KEY = Symbol.for("plugin-agent-orchestrator.nativeSubAgentObserver");
|
|
39
40
|
const NATIVE_SOURCE = "native-plugin-ai";
|
|
@@ -65,9 +66,11 @@ class NativeSubAgentObserver {
|
|
|
65
66
|
this.plugin = plugin;
|
|
66
67
|
this.spanService = new import_ExecutionSpanService.ExecutionSpanService(plugin);
|
|
67
68
|
this.memoryService = new import_AgentMemoryContextService.AgentMemoryContextService(plugin);
|
|
69
|
+
this.tokenTracker = new import_TokenTracker.TokenTracker(plugin);
|
|
68
70
|
}
|
|
69
71
|
spanService;
|
|
70
72
|
memoryService;
|
|
73
|
+
tokenTracker;
|
|
71
74
|
install() {
|
|
72
75
|
var _a, _b, _c, _d, _e, _f;
|
|
73
76
|
const aiPlugin = (_b = (_a = this.plugin.app.pm) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "ai");
|
|
@@ -178,6 +181,12 @@ ${memory.context}`
|
|
|
178
181
|
completedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
179
182
|
}
|
|
180
183
|
});
|
|
184
|
+
await this.tokenTracker.estimateAndTrack(
|
|
185
|
+
state.rootSpanId,
|
|
186
|
+
task.question,
|
|
187
|
+
result,
|
|
188
|
+
state.rootMetadata.agentLoopRunId ? Number(state.rootMetadata.agentLoopRunId) : void 0
|
|
189
|
+
);
|
|
181
190
|
return result;
|
|
182
191
|
} catch (error) {
|
|
183
192
|
await this.flushPending(state);
|
|
@@ -188,6 +197,12 @@ ${memory.context}`
|
|
|
188
197
|
failedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
189
198
|
}
|
|
190
199
|
});
|
|
200
|
+
await this.tokenTracker.estimateAndTrack(
|
|
201
|
+
state.rootSpanId,
|
|
202
|
+
task.question,
|
|
203
|
+
errorMessage(error),
|
|
204
|
+
state.rootMetadata.agentLoopRunId ? Number(state.rootMetadata.agentLoopRunId) : void 0
|
|
205
|
+
);
|
|
191
206
|
throw error;
|
|
192
207
|
}
|
|
193
208
|
}
|
|
@@ -319,6 +334,11 @@ ${memory.context}`
|
|
|
319
334
|
messageId: toolCall.messageId
|
|
320
335
|
}
|
|
321
336
|
});
|
|
337
|
+
await this.tokenTracker.estimateAndTrack(
|
|
338
|
+
existing.spanId,
|
|
339
|
+
normalizeString(toolCall.name),
|
|
340
|
+
typeof output === "string" ? output : JSON.stringify(output)
|
|
341
|
+
);
|
|
322
342
|
}
|
|
323
343
|
resolveParentSessionId(task) {
|
|
324
344
|
var _a, _b, _c;
|
|
@@ -0,0 +1,95 @@
|
|
|
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 PlanningPromptService_exports = {};
|
|
28
|
+
__export(PlanningPromptService_exports, {
|
|
29
|
+
PlanningPromptService: () => PlanningPromptService
|
|
30
|
+
});
|
|
31
|
+
module.exports = __toCommonJS(PlanningPromptService_exports);
|
|
32
|
+
const PLAN_KEYWORDS = [
|
|
33
|
+
"k\u1EBF ho\u1EA1ch",
|
|
34
|
+
"l\u1EADp k\u1EBF ho\u1EA1ch",
|
|
35
|
+
"l\xEAn k\u1EBF ho\u1EA1ch",
|
|
36
|
+
"k\u1EBF ho\u1EA1ch h\xF3a",
|
|
37
|
+
"l\u1EADp plan",
|
|
38
|
+
"t\u1EA1o k\u1EBF ho\u1EA1ch",
|
|
39
|
+
"x\xE2y d\u1EF1ng k\u1EBF ho\u1EA1ch",
|
|
40
|
+
"planning",
|
|
41
|
+
"make a plan",
|
|
42
|
+
"create a plan"
|
|
43
|
+
];
|
|
44
|
+
const PLAN_WORD_PATTERN = /\bplan\b/i;
|
|
45
|
+
const PLANNING_PREFIX = `[PLAN MODE] The user's request may need a structured plan. First, analyze the request:
|
|
46
|
+
|
|
47
|
+
STEP 0 \u2014 Evaluate: Does this request truly require 3+ distinct steps (building, creating, deploying, researching, etc.)?
|
|
48
|
+
- NO \u2192 The user mentioned "plan" but this is a simple question or single action. Respond directly WITHOUT calling any agent_loop tools.
|
|
49
|
+
- YES \u2192 Proceed with the plan workflow below.
|
|
50
|
+
|
|
51
|
+
PLAN WORKFLOW (only if truly multi-step):
|
|
52
|
+
1. Call \`agent_loop_start\` with a concrete step-by-step plan. Use small, executable steps with clear planKey values and proper dependsOn chains. Structure the user's goal clearly in the "goal" field.
|
|
53
|
+
2. After the plan is approved, execute each step by calling \`agent_loop_update_step\` with status="running" before the action, then status="succeeded" or "failed" after.
|
|
54
|
+
3. If execution diverges, call \`agent_loop_replan\` to update remaining steps.
|
|
55
|
+
4. When all steps complete, call \`agent_loop_finish\`.
|
|
56
|
+
|
|
57
|
+
User request:
|
|
58
|
+
`;
|
|
59
|
+
class PlanningPromptService {
|
|
60
|
+
static getMessageText(content) {
|
|
61
|
+
if (typeof content === "string") return content;
|
|
62
|
+
if (content && typeof content === "object" && "content" in content) {
|
|
63
|
+
const nested = content.content;
|
|
64
|
+
return typeof nested === "string" ? nested : "";
|
|
65
|
+
}
|
|
66
|
+
return "";
|
|
67
|
+
}
|
|
68
|
+
shouldInjectPlanningPrompt(text) {
|
|
69
|
+
if (!text) return false;
|
|
70
|
+
const normalized = text.toLowerCase();
|
|
71
|
+
if (PLAN_WORD_PATTERN.test(normalized)) return true;
|
|
72
|
+
return PLAN_KEYWORDS.some((keyword) => normalized.includes(keyword));
|
|
73
|
+
}
|
|
74
|
+
getPlanningPrefix() {
|
|
75
|
+
return PLANNING_PREFIX;
|
|
76
|
+
}
|
|
77
|
+
getPlanningInstructions() {
|
|
78
|
+
return PLANNING_PREFIX.replace(/User request:\s*$/, "").trim();
|
|
79
|
+
}
|
|
80
|
+
applyPlanningContext(messages) {
|
|
81
|
+
const shouldInject = messages.some(
|
|
82
|
+
(message) => message.role === "user" && this.shouldInjectPlanningPrompt(PlanningPromptService.getMessageText(message.content))
|
|
83
|
+
);
|
|
84
|
+
if (!shouldInject) return false;
|
|
85
|
+
messages.unshift({
|
|
86
|
+
role: "system",
|
|
87
|
+
content: { type: "text", content: this.getPlanningInstructions() }
|
|
88
|
+
});
|
|
89
|
+
return true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
93
|
+
0 && (module.exports = {
|
|
94
|
+
PlanningPromptService
|
|
95
|
+
});
|