plugin-agent-orchestrator 1.0.33 → 1.0.36

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 (39) hide show
  1. package/dist/externalVersion.js +6 -6
  2. package/dist/server/collections/skill-executions.js +21 -0
  3. package/dist/server/plugin.js +153 -3
  4. package/dist/server/resources/agent-loop.js +1 -2
  5. package/dist/server/services/AgentLoopController.js +39 -1
  6. package/dist/server/services/AgentLoopService.js +3 -0
  7. package/dist/server/services/AgentRuntimeLifecycle.js +70 -0
  8. package/dist/server/services/FileManager.js +12 -0
  9. package/dist/server/services/NativeSubAgentObserver.js +20 -0
  10. package/dist/server/services/PlanningPromptService.js +95 -0
  11. package/dist/server/services/SandboxRunner.js +251 -56
  12. package/dist/server/services/TokenTracker.js +20 -0
  13. package/dist/server/services/WorkerEnvManager.js +76 -10
  14. package/dist/server/services/pythonGuardTemplate.js +105 -0
  15. package/dist/server/services/sandboxCapabilities.js +286 -0
  16. package/dist/server/skill-hub/plugin.js +123 -28
  17. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +53 -11
  18. package/dist/server/utils/skill-settings.js +1 -1
  19. package/package.json +47 -47
  20. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -0
  21. package/src/server/__tests__/planning-prompt-service.test.ts +23 -0
  22. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -0
  23. package/src/server/collections/skill-executions.ts +21 -0
  24. package/src/server/plugin.ts +178 -0
  25. package/src/server/resources/agent-loop.ts +1 -2
  26. package/src/server/services/AgentLoopController.ts +50 -1
  27. package/src/server/services/AgentLoopService.ts +4 -0
  28. package/src/server/services/AgentRuntimeLifecycle.ts +64 -0
  29. package/src/server/services/FileManager.ts +16 -1
  30. package/src/server/services/NativeSubAgentObserver.ts +21 -0
  31. package/src/server/services/PlanningPromptService.ts +72 -0
  32. package/src/server/services/SandboxRunner.ts +341 -74
  33. package/src/server/services/TokenTracker.ts +26 -0
  34. package/src/server/services/WorkerEnvManager.ts +95 -9
  35. package/src/server/services/pythonGuardTemplate.ts +87 -0
  36. package/src/server/services/sandboxCapabilities.ts +348 -0
  37. package/src/server/skill-hub/plugin.ts +1120 -1016
  38. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +515 -470
  39. package/src/server/utils/skill-settings.ts +1 -0
@@ -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,56 @@ 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
+ var _a2, _b2;
245
+ const { resourceName, actionName } = ctx.action || {};
246
+ if (resourceName === "aiConversations" && actionName === "sendMessages") {
247
+ const values = ctx.action.params.values || {};
248
+ const messages = values.messages;
249
+ if (Array.isArray(messages)) {
250
+ const runtimeContext2 = {
251
+ ctx,
252
+ source: "chat-ui",
253
+ employee: void 0,
254
+ sessionId: String(((_a2 = ctx.state) == null ? void 0 : _a2.sessionId) || ""),
255
+ userId: (0, import_ctx_utils.currentUserId)(ctx),
256
+ messages,
257
+ metadata: {}
258
+ };
259
+ await this.agentRuntimeLifecycle.runBeforeHooks(runtimeContext2);
260
+ ctx.state.agentRuntimeContext = runtimeContext2;
261
+ }
262
+ }
263
+ const runtimeContext = (_b2 = ctx.state) == null ? void 0 : _b2.agentRuntimeContext;
264
+ try {
265
+ await next();
266
+ } finally {
267
+ if (runtimeContext) {
268
+ await this.agentRuntimeLifecycle.runAfterHooks(runtimeContext, {
269
+ succeeded: ctx.status < 400,
270
+ value: ctx.body
271
+ });
272
+ }
273
+ }
274
+ },
275
+ { tag: "orchestrator-planning-prompt", after: "acl" }
276
+ );
223
277
  const toolsManager = (0, import_ai_manager.getAIToolsManager)(this.app);
224
278
  toolsManager.registerTools((0, import_external_rag_search.createExternalRagSearchTool)(this));
279
+ const agentLoopService = new import_AgentLoopService.AgentLoopService(this);
280
+ toolsManager.registerTools((0, import_agent_loop2.createAgentLoopTools)(this, agentLoopService));
281
+ (0, import_agent_loop.registerAgentLoopResource)(this, agentLoopService);
225
282
  (0, import_agent_monitor.registerAgentMonitorResource)(this);
226
283
  this.installNativeObserver();
227
284
  (_b = (_a = this.app).on) == null ? void 0 : _b.call(_a, "afterStart", this.installNativeObserver);
285
+ (_d = (_c = this.app).on) == null ? void 0 : _d.call(_c, "afterStart", this.recoverAfterCrash);
228
286
  (0, import_tracing.registerTracingResource)(this);
229
287
  this.app.cronJobManager.addJob({
230
288
  cronTime: "0 30 2 * * *",
@@ -261,12 +319,104 @@ class PluginAgentOrchestratorServer extends import_server.Plugin {
261
319
  async remove() {
262
320
  }
263
321
  async beforeStop() {
264
- var _a, _b, _c, _d, _e;
322
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
265
323
  (_b = (_a = this.app).off) == null ? void 0 : _b.call(_a, "afterStart", this.installNativeObserver);
266
324
  (_d = (_c = this.app).removeListener) == null ? void 0 : _d.call(_c, "afterStart", this.installNativeObserver);
267
- (_e = this.nativeObserver) == null ? void 0 : _e.uninstall();
325
+ (_f = (_e = this.app).off) == null ? void 0 : _f.call(_e, "afterStart", this.recoverAfterCrash);
326
+ (_h = (_g = this.app).removeListener) == null ? void 0 : _h.call(_g, "afterStart", this.recoverAfterCrash);
327
+ (_i = this.nativeObserver) == null ? void 0 : _i.uninstall();
268
328
  await this.skillHub.beforeStop();
269
329
  }
330
+ // --- Crash Recovery ---
331
+ // Scans for agentLoopSteps stuck in "running" status from a previous crash
332
+ // and resets them to "pending". Also cleans up orphaned agentLoopRuns where
333
+ // all steps have reached terminal states but the run itself wasn't finalized.
334
+ recoverAfterCrash = async () => {
335
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
336
+ const timeoutMs = Number(process.env.ORCHESTRATOR_CRASH_RECOVERY_TIMEOUT_MS || 6e5);
337
+ const cutoff = new Date(Date.now() - timeoutMs);
338
+ try {
339
+ const stepsRepo = this.db.getRepository("agentLoopSteps");
340
+ const runsRepo = this.db.getRepository("agentLoopRuns");
341
+ if (stepsRepo) {
342
+ const staleSteps = await stepsRepo.find({
343
+ filter: {
344
+ status: "running",
345
+ startedAt: { $lt: cutoff.toISOString() }
346
+ }
347
+ });
348
+ for (const step of staleSteps) {
349
+ const stepId = readModelValue(step, "id");
350
+ const runId = readModelValue(step, "runId");
351
+ await stepsRepo.update({
352
+ filterByTk: stepId,
353
+ values: {
354
+ status: "pending",
355
+ startedAt: null,
356
+ error: `Recovered after crash at ${(/* @__PURE__ */ new Date()).toISOString()}`
357
+ }
358
+ });
359
+ (_b = (_a = this.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(
360
+ _a,
361
+ `[AgentOrchestrator] Crash recovery: reset step ${stepId} (run ${runId}) from running to pending`
362
+ );
363
+ }
364
+ if (staleSteps.length > 0) {
365
+ (_d = (_c = this.app.logger) == null ? void 0 : _c.info) == null ? void 0 : _d.call(
366
+ _c,
367
+ `[AgentOrchestrator] Crash recovery: reset ${staleSteps.length} stale running step(s)`
368
+ );
369
+ }
370
+ }
371
+ if (runsRepo) {
372
+ const runningRuns = await runsRepo.find({
373
+ filter: { status: "running" }
374
+ });
375
+ for (const run of runningRuns) {
376
+ const runId = readModelValue(run, "id");
377
+ const steps = await (stepsRepo == null ? void 0 : stepsRepo.find({
378
+ filter: { runId }
379
+ }));
380
+ if (!steps || steps.length === 0) {
381
+ await runsRepo.update({
382
+ filterByTk: runId,
383
+ values: {
384
+ status: "failed",
385
+ endedAt: /* @__PURE__ */ new Date(),
386
+ summary: "Run was orphaned after server crash (no steps found)."
387
+ }
388
+ });
389
+ (_f = (_e = this.app.logger) == null ? void 0 : _e.warn) == null ? void 0 : _f.call(
390
+ _e,
391
+ `[AgentOrchestrator] Crash recovery: marked orphaned run ${runId} as failed (no steps)`
392
+ );
393
+ continue;
394
+ }
395
+ const allTerminal = steps.every((s) => {
396
+ const st = readModelValue(s, "status");
397
+ return st === "succeeded" || st === "failed" || st === "skipped";
398
+ });
399
+ if (!allTerminal) continue;
400
+ const anyFailed = steps.some((s) => readModelValue(s, "status") === "failed");
401
+ const finalStatus = anyFailed ? "failed" : "succeeded";
402
+ await runsRepo.update({
403
+ filterByTk: runId,
404
+ values: {
405
+ status: finalStatus,
406
+ endedAt: /* @__PURE__ */ new Date(),
407
+ summary: `Run finalized as ${finalStatus} after server crash recovery.`
408
+ }
409
+ });
410
+ (_h = (_g = this.app.logger) == null ? void 0 : _g.warn) == null ? void 0 : _h.call(
411
+ _g,
412
+ `[AgentOrchestrator] Crash recovery: finalized orphaned run ${runId} as ${finalStatus}`
413
+ );
414
+ }
415
+ }
416
+ } catch (error) {
417
+ (_j = (_i = this.app.logger) == null ? void 0 : _i.error) == null ? void 0 : _j.call(_i, "[AgentOrchestrator] Crash recovery scan failed", error);
418
+ }
419
+ };
270
420
  }
271
421
  var plugin_default = PluginAgentOrchestratorServer;
272
422
  // 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.
@@ -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
+ });