plugin-agent-orchestrator 1.0.28 → 1.0.32

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 (108) hide show
  1. package/README.md +9 -7
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/{214.723affb37c13bf7a.js → 214.79650a549273f163.js} +1 -1
  4. package/dist/client-v2/264.718a107e43fc163c.js +10 -0
  5. package/dist/client-v2/373.f5d5292e53c4e832.js +10 -0
  6. package/dist/client-v2/{41.1805b2edfaa4afe2.js → 41.ba6e080cc0488143.js} +1 -1
  7. package/dist/client-v2/418.29e713f79131eece.js +10 -0
  8. package/dist/client-v2/619.bd3c5698b40705c3.js +10 -0
  9. package/dist/client-v2/677.a991ce0250ff5c77.js +10 -0
  10. package/dist/client-v2/{70.a15d7fcec7c41768.js → 70.bda9518881c05360.js} +1 -1
  11. package/dist/client-v2/925.f5370de8f6632d65.js +10 -0
  12. package/dist/client-v2/index.js +1 -1
  13. package/dist/externalVersion.js +7 -10
  14. package/dist/locale/en-US.json +94 -25
  15. package/dist/locale/vi-VN.json +94 -25
  16. package/dist/locale/zh-CN.json +94 -25
  17. package/dist/server/collections/agent-execution-spans.js +37 -0
  18. package/dist/server/collections/agent-harness-profiles.js +2 -2
  19. package/dist/server/collections/agent-memory-contexts.js +125 -0
  20. package/dist/server/collections/orchestrator-logs.js +2 -2
  21. package/dist/server/migrations/20260425000000-add-interaction-schema.js +3 -1
  22. package/dist/server/migrations/20260427000000-change-packages-to-text.js +3 -1
  23. package/dist/server/migrations/20260427000001-change-other-json-to-text.js +6 -2
  24. package/dist/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.js +21 -19
  25. package/dist/server/migrations/20260621000000-native-policy-profile-defaults.js +193 -0
  26. package/dist/server/plugin.js +128 -74
  27. package/dist/server/resources/agent-monitor.js +454 -0
  28. package/dist/server/services/AgentHarness.js +24 -499
  29. package/dist/server/services/AgentMemoryContextService.js +216 -0
  30. package/dist/server/services/ExecutionSpanService.js +2 -2
  31. package/dist/server/services/NativeSubAgentObserver.js +413 -0
  32. package/dist/server/skill-hub/plugin.js +81 -5
  33. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +9 -3
  34. package/dist/server/tools/delegate-task.js +11 -589
  35. package/dist/server/utils/skill-settings.js +18 -1
  36. package/package.json +47 -49
  37. package/src/client/AIEmployeesContext.tsx +5 -18
  38. package/src/client/AgentRunsTab.tsx +2 -771
  39. package/src/client/HarnessProfilesTab.tsx +2 -257
  40. package/src/client/OrchestratorSettings.tsx +97 -106
  41. package/src/client/RulesTab.tsx +2 -788
  42. package/src/client/plugin.tsx +0 -2
  43. package/src/client/skill-hub/components/ExecutionHistory.tsx +200 -202
  44. package/src/client/skill-hub/components/ExecutionProgress.tsx +51 -55
  45. package/src/client/skill-hub/components/LoopSettings.tsx +331 -331
  46. package/src/client/skill-hub/components/SkillEditor.tsx +43 -39
  47. package/src/client/skill-hub/components/SkillManager.tsx +194 -181
  48. package/src/client/skill-hub/components/SkillTestPanel.tsx +141 -145
  49. package/src/client/skill-hub/locale.ts +16 -16
  50. package/src/client/skill-hub/tools/SkillHubCard.tsx +104 -109
  51. package/src/client/skill-hub/tools/loopTemplates.ts +52 -52
  52. package/src/client/skill-hub/utils/jsonFields.ts +7 -3
  53. package/src/client-v2/components/AIEmployeesContext.tsx +3 -16
  54. package/src/client-v2/components/AgentRunsTab.tsx +182 -455
  55. package/src/client-v2/components/HarnessProfilesTab.tsx +34 -31
  56. package/src/client-v2/components/RulesTab.tsx +2 -782
  57. package/src/client-v2/components/TracingTab.tsx +1 -1
  58. package/src/client-v2/hooks/useApiRequest.ts +8 -1
  59. package/src/client-v2/pages/RulesPage.tsx +2 -2
  60. package/src/client-v2/plugin.tsx +3 -3
  61. package/src/locale/en-US.json +94 -25
  62. package/src/locale/vi-VN.json +94 -25
  63. package/src/locale/zh-CN.json +94 -25
  64. package/src/server/__tests__/native-sub-agent-observer.test.ts +246 -0
  65. package/src/server/__tests__/skill-settings.test.ts +6 -6
  66. package/src/server/__tests__/smoke.test.ts +1 -0
  67. package/src/server/collections/agent-execution-spans.ts +37 -0
  68. package/src/server/collections/agent-harness-profiles.ts +59 -59
  69. package/src/server/collections/agent-loop-events.ts +71 -71
  70. package/src/server/collections/agent-loop-steps.ts +144 -144
  71. package/src/server/collections/agent-memory-contexts.ts +95 -0
  72. package/src/server/collections/orchestrator-logs.ts +4 -4
  73. package/src/server/collections/skill-definitions.ts +111 -111
  74. package/src/server/collections/skill-executions.ts +106 -106
  75. package/src/server/collections/skill-loop-configs.ts +65 -65
  76. package/src/server/migrations/20260423000000-add-progress-fields.ts +14 -14
  77. package/src/server/migrations/20260425000000-add-interaction-schema.ts +3 -1
  78. package/src/server/migrations/20260427000000-change-packages-to-text.ts +4 -2
  79. package/src/server/migrations/20260427000001-change-other-json-to-text.ts +9 -5
  80. package/src/server/migrations/20260524000000-add-agent-loop-fields-to-skill-executions.ts +30 -30
  81. package/src/server/migrations/20260524001000-add-plan-approval-and-harness-profiles.ts +145 -142
  82. package/src/server/migrations/20260615000000-normalize-ai-employee-tool-bindings.ts +2 -2
  83. package/src/server/migrations/20260621000000-native-policy-profile-defaults.ts +193 -0
  84. package/src/server/plugin.ts +151 -94
  85. package/src/server/resources/agent-monitor.ts +482 -0
  86. package/src/server/services/AgentHarness.ts +38 -623
  87. package/src/server/services/AgentMemoryContextService.ts +256 -0
  88. package/src/server/services/AgentPlanValidator.ts +73 -73
  89. package/src/server/services/ExecutionSpanService.ts +6 -2
  90. package/src/server/services/FileManager.ts +144 -144
  91. package/src/server/services/NativeSubAgentObserver.ts +507 -0
  92. package/src/server/services/SkillManager.ts +583 -583
  93. package/src/server/services/SkillRepositoryService.ts +5 -7
  94. package/src/server/services/TokenTracker.ts +3 -3
  95. package/src/server/services/WorkerEnvManager.ts +1 -2
  96. package/src/server/skill-hub/actions/git-import.ts +5 -7
  97. package/src/server/skill-hub/plugin.ts +89 -6
  98. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +470 -460
  99. package/src/server/skill-hub/utils/json-fields.ts +1 -1
  100. package/src/server/tools/delegate-task.ts +13 -847
  101. package/src/server/utils/skill-settings.ts +24 -6
  102. package/dist/client-v2/264.0533912e6c5ea2d7.js +0 -10
  103. package/dist/client-v2/418.5ae055abf141820e.js +0 -10
  104. package/dist/client-v2/619.d99d3c9e61c99064.js +0 -10
  105. package/dist/client-v2/892.72db4161511c8a16.js +0 -10
  106. package/dist/client-v2/926.87f660b670d85bcc.js +0 -10
  107. package/src/client/tools/PlanApprovalCard.tsx +0 -176
  108. package/src/client/tools/registerOrchestratorCards.ts +0 -17
@@ -0,0 +1,216 @@
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 AgentMemoryContextService_exports = {};
28
+ __export(AgentMemoryContextService_exports, {
29
+ AgentMemoryContextService: () => AgentMemoryContextService
30
+ });
31
+ module.exports = __toCommonJS(AgentMemoryContextService_exports);
32
+ var import_ctx_utils = require("../utils/ctx-utils");
33
+ const DEFAULT_MEMORY_SCOPES = ["public", "user", "agent_user"];
34
+ const DEFAULT_MAX_CONTEXT_CHARS = 6e3;
35
+ function readModelValue(record, key) {
36
+ const model = record;
37
+ return typeof (model == null ? void 0 : model.get) === "function" ? model.get(key) : model == null ? void 0 : model[key];
38
+ }
39
+ function normalizeScopes(value) {
40
+ if (!Array.isArray(value)) return DEFAULT_MEMORY_SCOPES;
41
+ const scopes = value.filter(
42
+ (item) => item === "public" || item === "user" || item === "agent_user"
43
+ );
44
+ return scopes.length ? scopes : DEFAULT_MEMORY_SCOPES;
45
+ }
46
+ function normalizeText(value) {
47
+ return typeof value === "string" ? value.trim() : "";
48
+ }
49
+ function formatRecordSection(record) {
50
+ const content = normalizeText(record.contentMd);
51
+ const graph = normalizeText(record.graphMd);
52
+ return [content, graph ? `## Graph
53
+ ${graph}` : ""].filter(Boolean).join("\n\n").trim();
54
+ }
55
+ class AgentMemoryContextService {
56
+ constructor(plugin) {
57
+ this.plugin = plugin;
58
+ }
59
+ async resolvePolicySettings(task) {
60
+ var _a, _b, _c;
61
+ const directSettings = (0, import_ctx_utils.asObject)(task == null ? void 0 : task.skillSettings);
62
+ const employeeSettings = (0, import_ctx_utils.asObject)(readModelValue(task == null ? void 0 : task.employee, "skillSettings"));
63
+ const values = (0, import_ctx_utils.asObject)((_c = (_b = (_a = task == null ? void 0 : task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values);
64
+ const tag = normalizeText(values.harnessTag) || normalizeText(values.orchestratorHarnessTag) || normalizeText(directSettings.harnessTag) || normalizeText(directSettings.orchestratorHarnessTag) || normalizeText(employeeSettings.harnessTag) || normalizeText(employeeSettings.orchestratorHarnessTag) || "default";
65
+ const profile = await this.findHarnessProfile(tag);
66
+ const fallbackProfile = profile || (tag === "default" ? null : await this.findHarnessProfile("default"));
67
+ const profileSettings = (0, import_ctx_utils.asObject)(fallbackProfile ? readModelValue(fallbackProfile, "settings") : {});
68
+ return {
69
+ ...profileSettings,
70
+ harnessTag: tag
71
+ };
72
+ }
73
+ async buildContext(options) {
74
+ const { userId, aiEmployeeUsername } = options;
75
+ const settings = options.settings || {};
76
+ if (!userId || settings.memoryInjectionEnabled === false) {
77
+ return {
78
+ context: "",
79
+ appliedScopes: [],
80
+ chars: 0
81
+ };
82
+ }
83
+ const sections = [];
84
+ const scopes = normalizeScopes(settings.memoryScopes);
85
+ if (scopes.includes("public")) {
86
+ sections.push(...await this.loadStoredSections("public", userId, aiEmployeeUsername));
87
+ }
88
+ if (scopes.includes("user")) {
89
+ const userMemory = await this.loadUserMemory(userId);
90
+ if (userMemory) {
91
+ sections.push({
92
+ scope: "user-memory",
93
+ title: "User Memory",
94
+ body: userMemory
95
+ });
96
+ }
97
+ sections.push(...await this.loadStoredSections("user", userId, aiEmployeeUsername));
98
+ }
99
+ if (scopes.includes("agent_user")) {
100
+ sections.push(...await this.loadStoredSections("agent_user", userId, aiEmployeeUsername));
101
+ }
102
+ if (!sections.length) {
103
+ return {
104
+ context: "",
105
+ appliedScopes: [],
106
+ chars: 0
107
+ };
108
+ }
109
+ const body = sections.map((section) => `### ${section.title}
110
+ ${section.body}`).join("\n\n").trim();
111
+ const maxChars = Number(settings.maxMemoryContextChars || settings.maxContextChars || DEFAULT_MAX_CONTEXT_CHARS);
112
+ const context = `<agent_memory_context>
113
+ ${(0, import_ctx_utils.trimText)(
114
+ body,
115
+ Number.isFinite(maxChars) ? maxChars : DEFAULT_MAX_CONTEXT_CHARS
116
+ )}
117
+ </agent_memory_context>`;
118
+ return {
119
+ context,
120
+ appliedScopes: Array.from(new Set(sections.map((section) => section.scope))),
121
+ chars: context.length
122
+ };
123
+ }
124
+ async findHarnessProfile(tag) {
125
+ var _a, _b;
126
+ try {
127
+ const repo = this.plugin.db.getRepository("agentHarnessProfiles");
128
+ if (!repo) return null;
129
+ return repo.findOne({
130
+ filter: {
131
+ tag,
132
+ enabled: true
133
+ }
134
+ });
135
+ } catch (error) {
136
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to load policy profile", error);
137
+ return null;
138
+ }
139
+ }
140
+ async loadStoredSections(scope, userId, aiEmployeeUsername) {
141
+ var _a, _b;
142
+ try {
143
+ const repo = this.plugin.db.getRepository("agentMemoryContexts");
144
+ if (!repo) return [];
145
+ const filter = {
146
+ scope,
147
+ enabled: true
148
+ };
149
+ if (scope === "public") {
150
+ filter.userId = null;
151
+ } else if (userId) {
152
+ filter.userId = userId;
153
+ }
154
+ const records = await repo.find({
155
+ filter,
156
+ sort: ["scope", "aiEmployeeUsername", "updatedAt"]
157
+ });
158
+ return records.map((record) => (0, import_ctx_utils.toPlain)(record)).filter((record) => {
159
+ if (scope === "agent_user") {
160
+ return String(record.userId || "") === String(userId || "") && normalizeText(record.aiEmployeeUsername) === normalizeText(aiEmployeeUsername);
161
+ }
162
+ const username = normalizeText(record.aiEmployeeUsername);
163
+ return !username || username === normalizeText(aiEmployeeUsername);
164
+ }).map((record) => ({
165
+ scope,
166
+ title: this.sectionTitle(scope, record.aiEmployeeUsername),
167
+ body: formatRecordSection(record)
168
+ })).filter((section) => section.body);
169
+ } catch (error) {
170
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `[AgentOrchestrator] Failed to load ${scope} memory context`, error);
171
+ return [];
172
+ }
173
+ }
174
+ async loadUserMemory(userId) {
175
+ var _a, _b, _c, _d, _e;
176
+ try {
177
+ const pluginManager = this.plugin.app.pm;
178
+ const candidates = ["plugin-user-memory", "@nocobase/plugin-user-memory", "user-memory"];
179
+ let userMemoryPlugin = null;
180
+ for (const name of candidates) {
181
+ try {
182
+ const candidate = (_a = pluginManager == null ? void 0 : pluginManager.get) == null ? void 0 : _a.call(pluginManager, name);
183
+ if ((_b = candidate == null ? void 0 : candidate.memoryInjector) == null ? void 0 : _b.getMemoryPromptSection) {
184
+ userMemoryPlugin = candidate;
185
+ break;
186
+ }
187
+ } catch {
188
+ }
189
+ }
190
+ if (!userMemoryPlugin && typeof (pluginManager == null ? void 0 : pluginManager.getPlugins) === "function") {
191
+ for (const [, candidate] of pluginManager.getPlugins()) {
192
+ if ((_c = candidate == null ? void 0 : candidate.memoryInjector) == null ? void 0 : _c.getMemoryPromptSection) {
193
+ userMemoryPlugin = candidate;
194
+ break;
195
+ }
196
+ }
197
+ }
198
+ const injector = userMemoryPlugin == null ? void 0 : userMemoryPlugin.memoryInjector;
199
+ if (!(injector == null ? void 0 : injector.getMemoryPromptSection)) return "";
200
+ return normalizeText(await injector.getMemoryPromptSection(Number(userId)));
201
+ } catch (error) {
202
+ (_e = (_d = this.plugin.app.logger) == null ? void 0 : _d.warn) == null ? void 0 : _e.call(_d, "[AgentOrchestrator] Failed to read plugin-user-memory context", error);
203
+ return "";
204
+ }
205
+ }
206
+ sectionTitle(scope, aiEmployeeUsername) {
207
+ const suffix = aiEmployeeUsername ? ` (${aiEmployeeUsername})` : "";
208
+ if (scope === "public") return `Public Agent Knowledge${suffix}`;
209
+ if (scope === "user") return `User Context${suffix}`;
210
+ return `Private Agent/User Context${suffix}`;
211
+ }
212
+ }
213
+ // Annotate the CommonJS export names for ESM import in node:
214
+ 0 && (module.exports = {
215
+ AgentMemoryContextService
216
+ });
@@ -52,7 +52,7 @@ class ExecutionSpanService {
52
52
  });
53
53
  return (0, import_ctx_utils.toPlain)(record);
54
54
  } catch (error) {
55
- (_b = (_a = this.plugin.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to create execution span", error);
55
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to create execution span", error);
56
56
  return null;
57
57
  }
58
58
  }
@@ -71,7 +71,7 @@ class ExecutionSpanService {
71
71
  });
72
72
  return { id: spanId };
73
73
  } catch (error) {
74
- (_b = (_a = this.plugin.app.log) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `[AgentOrchestrator] Failed to update execution span ${spanId}`, error);
74
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, `[AgentOrchestrator] Failed to update execution span ${spanId}`, error);
75
75
  return null;
76
76
  }
77
77
  }
@@ -0,0 +1,413 @@
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 NativeSubAgentObserver_exports = {};
28
+ __export(NativeSubAgentObserver_exports, {
29
+ NATIVE_SOURCE: () => NATIVE_SOURCE,
30
+ NativeSubAgentObserver: () => NativeSubAgentObserver,
31
+ makeNativeRunId: () => makeNativeRunId
32
+ });
33
+ module.exports = __toCommonJS(NativeSubAgentObserver_exports);
34
+ var import_crypto = require("crypto");
35
+ var import_ExecutionSpanService = require("./ExecutionSpanService");
36
+ var import_AgentMemoryContextService = require("./AgentMemoryContextService");
37
+ var import_ctx_utils = require("../utils/ctx-utils");
38
+ const WRAP_STATE_KEY = Symbol.for("plugin-agent-orchestrator.nativeSubAgentObserver");
39
+ const NATIVE_SOURCE = "native-plugin-ai";
40
+ function readValue(record, key) {
41
+ const model = record;
42
+ return typeof (model == null ? void 0 : model.get) === "function" ? model.get(key) : model == null ? void 0 : model[key];
43
+ }
44
+ function normalizeString(value) {
45
+ return typeof value === "string" ? value.trim() : "";
46
+ }
47
+ function modelUsername(model) {
48
+ return normalizeString(readValue(model, "username")) || normalizeString(readValue(model, "aiEmployeeUsername")) || normalizeString(readValue(model, "name")) || void 0;
49
+ }
50
+ function makeNativeRunId(parts) {
51
+ const source = parts.map((part) => String(part || "")).join("|");
52
+ return `native_${(0, import_crypto.createHash)("sha1").update(source || String(Date.now())).digest("hex").slice(0, 24)}`;
53
+ }
54
+ function errorMessage(error) {
55
+ return error instanceof Error ? error.message : String(error || "Unknown error");
56
+ }
57
+ function chunkBody(chunk) {
58
+ return (0, import_ctx_utils.asObject)(chunk.body);
59
+ }
60
+ function chunkCurrentConversation(chunk) {
61
+ return (0, import_ctx_utils.asObject)(chunk.currentConversation);
62
+ }
63
+ class NativeSubAgentObserver {
64
+ constructor(plugin) {
65
+ this.plugin = plugin;
66
+ this.spanService = new import_ExecutionSpanService.ExecutionSpanService(plugin);
67
+ this.memoryService = new import_AgentMemoryContextService.AgentMemoryContextService(plugin);
68
+ }
69
+ spanService;
70
+ memoryService;
71
+ install() {
72
+ var _a, _b, _c, _d, _e, _f;
73
+ const aiPlugin = (_b = (_a = this.plugin.app.pm) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "ai");
74
+ const dispatcher = aiPlugin == null ? void 0 : aiPlugin.subAgentsDispatcher;
75
+ if (!(dispatcher == null ? void 0 : dispatcher.run)) {
76
+ (_d = (_c = this.plugin.app.logger) == null ? void 0 : _c.warn) == null ? void 0 : _d.call(
77
+ _c,
78
+ "[AgentOrchestrator] plugin-ai subAgentsDispatcher not available; observer skipped."
79
+ );
80
+ return false;
81
+ }
82
+ const existing = dispatcher[WRAP_STATE_KEY];
83
+ if ((existing == null ? void 0 : existing.wrappedRun) === dispatcher.run) {
84
+ return false;
85
+ }
86
+ const originalRun = (existing == null ? void 0 : existing.originalRun) || dispatcher.run.bind(dispatcher);
87
+ const observer = this;
88
+ const wrappedRun = async function wrappedNativeSubAgentRun(task) {
89
+ return observer.runObserved(originalRun, task);
90
+ };
91
+ dispatcher.run = wrappedRun;
92
+ dispatcher[WRAP_STATE_KEY] = {
93
+ originalRun,
94
+ wrappedRun
95
+ };
96
+ (_f = (_e = this.plugin.app.logger) == null ? void 0 : _e.info) == null ? void 0 : _f.call(_e, "[AgentOrchestrator] Native plugin-ai sub-agent observer installed.");
97
+ return true;
98
+ }
99
+ uninstall() {
100
+ var _a, _b, _c, _d;
101
+ const aiPlugin = (_b = (_a = this.plugin.app.pm) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "ai");
102
+ const dispatcher = aiPlugin == null ? void 0 : aiPlugin.subAgentsDispatcher;
103
+ const existing = dispatcher == null ? void 0 : dispatcher[WRAP_STATE_KEY];
104
+ if (!(dispatcher == null ? void 0 : dispatcher.run) || !existing || existing.wrappedRun !== dispatcher.run) {
105
+ return false;
106
+ }
107
+ dispatcher.run = existing.originalRun;
108
+ delete dispatcher[WRAP_STATE_KEY];
109
+ (_d = (_c = this.plugin.app.logger) == null ? void 0 : _c.info) == null ? void 0 : _d.call(_c, "[AgentOrchestrator] Native plugin-ai sub-agent observer uninstalled.");
110
+ return true;
111
+ }
112
+ async runObserved(originalRun, task) {
113
+ var _a, _b, _c;
114
+ const settings = await this.safeResolvePolicy(task);
115
+ if (settings.nativeObserverEnabled === false) {
116
+ return originalRun(task);
117
+ }
118
+ const parentSessionId = this.resolveParentSessionId(task) || void 0;
119
+ const subSessionId = normalizeString(task.sessionId) || void 0;
120
+ const employeeUsername = modelUsername(task.employee);
121
+ 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);
122
+ const dispatchToolMessage = await this.resolveDispatchToolMessage(task.ctx, parentSessionId, subSessionId);
123
+ const toolCallId = dispatchToolMessage == null ? void 0 : dispatchToolMessage.toolCallId;
124
+ const leaderUsername = await this.resolveLeaderUsername(task.ctx, parentSessionId);
125
+ const rootRunId = makeNativeRunId([parentSessionId, subSessionId, toolCallId, employeeUsername]);
126
+ const memory = await this.safeBuildMemoryContext({
127
+ userId,
128
+ aiEmployeeUsername: employeeUsername,
129
+ settings
130
+ });
131
+ const observedTask = memory.context ? {
132
+ ...task,
133
+ question: `${task.question}
134
+
135
+ ${memory.context}`
136
+ } : task;
137
+ const state = {
138
+ rootRunId,
139
+ rootStartedAt: Date.now(),
140
+ rootMetadata: {
141
+ source: NATIVE_SOURCE,
142
+ parentSessionId,
143
+ subSessionId,
144
+ toolCallId,
145
+ dispatchToolMessageId: dispatchToolMessage == null ? void 0 : dispatchToolMessage.id,
146
+ dispatchMessageId: dispatchToolMessage == null ? void 0 : dispatchToolMessage.messageId,
147
+ memoryContextApplied: Boolean(memory.context),
148
+ memoryScopes: memory.appliedScopes,
149
+ memoryContextChars: memory.chars,
150
+ harnessTag: settings.harnessTag || "default"
151
+ },
152
+ parentSessionId,
153
+ subSessionId,
154
+ toolCallId,
155
+ leaderUsername,
156
+ employeeUsername,
157
+ userId,
158
+ toolSpans: /* @__PURE__ */ new Map(),
159
+ pending: /* @__PURE__ */ new Set()
160
+ };
161
+ await this.safeCreateRootSpan(state, task.question);
162
+ const originalWriter = task.writer;
163
+ observedTask.writer = (chunk) => {
164
+ const pending = this.handleWriterChunk(state, chunk).catch((error) => {
165
+ var _a2, _b2;
166
+ (_b2 = (_a2 = this.plugin.app.logger) == null ? void 0 : _a2.warn) == null ? void 0 : _b2.call(_a2, "[AgentOrchestrator] Native writer observer failed", error);
167
+ });
168
+ state.pending.add(pending);
169
+ return originalWriter == null ? void 0 : originalWriter(chunk);
170
+ };
171
+ try {
172
+ const result = await originalRun(observedTask);
173
+ await this.flushPending(state);
174
+ await this.spanService.finish(state.rootSpanId, "success", state.rootStartedAt, {
175
+ output: (0, import_ctx_utils.trimText)(result, 2e4),
176
+ metadata: {
177
+ ...state.rootMetadata,
178
+ completedAt: (/* @__PURE__ */ new Date()).toISOString()
179
+ }
180
+ });
181
+ return result;
182
+ } catch (error) {
183
+ await this.flushPending(state);
184
+ await this.spanService.finish(state.rootSpanId, "error", state.rootStartedAt, {
185
+ error: (0, import_ctx_utils.trimText)(errorMessage(error), 1e4),
186
+ metadata: {
187
+ ...state.rootMetadata,
188
+ failedAt: (/* @__PURE__ */ new Date()).toISOString()
189
+ }
190
+ });
191
+ throw error;
192
+ }
193
+ }
194
+ async safeResolvePolicy(task) {
195
+ var _a, _b;
196
+ try {
197
+ return await this.memoryService.resolvePolicySettings(task);
198
+ } catch (error) {
199
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to resolve native observer policy", error);
200
+ return { harnessTag: "default" };
201
+ }
202
+ }
203
+ async safeBuildMemoryContext(options) {
204
+ var _a, _b;
205
+ try {
206
+ return await this.memoryService.buildContext(options);
207
+ } catch (error) {
208
+ (_b = (_a = this.plugin.app.logger) == null ? void 0 : _a.warn) == null ? void 0 : _b.call(_a, "[AgentOrchestrator] Failed to build agent memory context", error);
209
+ return { context: "", appliedScopes: [], chars: 0 };
210
+ }
211
+ }
212
+ async safeCreateRootSpan(state, question) {
213
+ const span = await this.spanService.create({
214
+ rootRunId: state.rootRunId,
215
+ parentSpanId: void 0,
216
+ source: NATIVE_SOURCE,
217
+ parentSessionId: state.parentSessionId,
218
+ subSessionId: state.subSessionId,
219
+ toolCallId: state.toolCallId,
220
+ type: "sub_agent",
221
+ status: "running",
222
+ leaderUsername: state.leaderUsername,
223
+ employeeUsername: state.employeeUsername,
224
+ toolName: "dispatch-sub-agent-task",
225
+ title: `${state.leaderUsername || "main"} -> ${state.employeeUsername || "sub-agent"}`,
226
+ input: {
227
+ question,
228
+ parentSessionId: state.parentSessionId,
229
+ subSessionId: state.subSessionId
230
+ },
231
+ metadata: state.rootMetadata,
232
+ userId: state.userId
233
+ });
234
+ state.rootSpanId = span == null ? void 0 : span.id;
235
+ }
236
+ async handleWriterChunk(state, chunk) {
237
+ const action = chunk.action;
238
+ if (action === "beforeToolCall") {
239
+ await this.handleBeforeToolCall(state, chunk);
240
+ return;
241
+ }
242
+ if (action === "afterToolCall") {
243
+ await this.handleAfterToolCall(state, chunk, false);
244
+ return;
245
+ }
246
+ if (action === "afterToolCallError") {
247
+ await this.handleAfterToolCall(state, chunk, true);
248
+ return;
249
+ }
250
+ if (action === "afterSubAgentInvoke") {
251
+ state.rootMetadata = {
252
+ ...state.rootMetadata,
253
+ afterSubAgentInvokeAt: (/* @__PURE__ */ new Date()).toISOString()
254
+ };
255
+ await this.spanService.update(state.rootSpanId, { metadata: state.rootMetadata });
256
+ }
257
+ }
258
+ async handleBeforeToolCall(state, chunk) {
259
+ const body = chunkBody(chunk);
260
+ const toolCall = (0, import_ctx_utils.asObject)(body.toolCall);
261
+ const toolCallId = normalizeString(toolCall.id);
262
+ if (!toolCallId || state.toolSpans.has(toolCallId)) return;
263
+ const conversation = chunkCurrentConversation(chunk);
264
+ const startedAt = Date.now();
265
+ const toolSpan = {
266
+ startedAt,
267
+ ready: Promise.resolve()
268
+ };
269
+ state.toolSpans.set(toolCallId, toolSpan);
270
+ toolSpan.ready = this.spanService.create({
271
+ rootRunId: state.rootRunId,
272
+ parentSpanId: state.rootSpanId ? String(state.rootSpanId) : void 0,
273
+ source: NATIVE_SOURCE,
274
+ parentSessionId: state.parentSessionId || void 0,
275
+ subSessionId: normalizeString(conversation.sessionId) || state.subSessionId || void 0,
276
+ toolCallId,
277
+ type: normalizeString(toolCall.name) === "dispatch-sub-agent-task" ? "dispatch" : "tool",
278
+ status: "running",
279
+ leaderUsername: state.leaderUsername,
280
+ employeeUsername: normalizeString(conversation.username) || state.employeeUsername,
281
+ toolName: normalizeString(toolCall.name),
282
+ title: normalizeString(toolCall.name) || "tool call",
283
+ input: (0, import_ctx_utils.asObject)(toolCall.args),
284
+ metadata: {
285
+ source: NATIVE_SOURCE,
286
+ currentConversation: conversation,
287
+ messageId: toolCall.messageId
288
+ },
289
+ userId: state.userId
290
+ }).then((span) => {
291
+ toolSpan.spanId = span == null ? void 0 : span.id;
292
+ });
293
+ await toolSpan.ready;
294
+ }
295
+ async handleAfterToolCall(state, chunk, forceError) {
296
+ const body = chunkBody(chunk);
297
+ const toolCall = (0, import_ctx_utils.asObject)(body.toolCall);
298
+ const toolCallId = normalizeString(toolCall.id);
299
+ const existing = toolCallId ? state.toolSpans.get(toolCallId) : void 0;
300
+ if (!existing) return;
301
+ await existing.ready;
302
+ const result = (0, import_ctx_utils.asObject)((0, import_ctx_utils.toPlain)(body.toolCallResult));
303
+ const error = body.error;
304
+ const status = forceError || result.status === "error" ? "error" : "success";
305
+ const output = result.content ?? result.result ?? result;
306
+ const invokeStart = Number(result.invokeStartTime);
307
+ const invokeEnd = Number(result.invokeEndTime);
308
+ const durationMs = Number.isFinite(invokeStart) && Number.isFinite(invokeEnd) && invokeEnd >= invokeStart ? invokeEnd - invokeStart : Date.now() - existing.startedAt;
309
+ await this.spanService.update(existing.spanId, {
310
+ status,
311
+ endedAt: /* @__PURE__ */ new Date(),
312
+ durationMs,
313
+ output: forceError ? void 0 : (0, import_ctx_utils.trimText)(output, 2e4),
314
+ error: forceError ? (0, import_ctx_utils.trimText)(errorMessage(error), 1e4) : void 0,
315
+ metadata: {
316
+ source: NATIVE_SOURCE,
317
+ toolCallResultStatus: result.status,
318
+ invokeStatus: result.invokeStatus,
319
+ messageId: toolCall.messageId
320
+ }
321
+ });
322
+ }
323
+ resolveParentSessionId(task) {
324
+ var _a, _b, _c;
325
+ const values = ((_c = (_b = (_a = task.ctx) == null ? void 0 : _a.action) == null ? void 0 : _b.params) == null ? void 0 : _c.values) || {};
326
+ return normalizeString(values.sessionId) || void 0;
327
+ }
328
+ async resolveLeaderUsername(ctx, parentSessionId) {
329
+ var _a, _b, _c, _d, _e;
330
+ const values = ((_b = (_a = ctx == null ? void 0 : ctx.action) == null ? void 0 : _a.params) == null ? void 0 : _b.values) || {};
331
+ const direct = normalizeString(values.aiEmployeeUsername) || normalizeString((0, import_ctx_utils.asObject)(values.aiEmployee).username);
332
+ if (direct) return direct;
333
+ if (!parentSessionId) return void 0;
334
+ try {
335
+ const repo = (_d = (_c = ctx.db) == null ? void 0 : _c.getRepository) == null ? void 0 : _d.call(_c, "aiConversations");
336
+ const conversation = await ((_e = repo == null ? void 0 : repo.findOne) == null ? void 0 : _e.call(repo, {
337
+ filter: { sessionId: parentSessionId }
338
+ }));
339
+ return normalizeString(readValue(conversation, "aiEmployeeUsername")) || void 0;
340
+ } catch {
341
+ return void 0;
342
+ }
343
+ }
344
+ async resolveDispatchToolMessage(ctx, parentSessionId, subSessionId) {
345
+ var _a, _b, _c;
346
+ if (!parentSessionId) return null;
347
+ try {
348
+ const fromMetadata = await this.resolveDispatchToolMessageFromMetadata(ctx, parentSessionId, subSessionId);
349
+ if (fromMetadata) {
350
+ return fromMetadata;
351
+ }
352
+ const repo = (_b = (_a = ctx.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "aiToolMessages");
353
+ const record = await ((_c = repo == null ? void 0 : repo.findOne) == null ? void 0 : _c.call(repo, {
354
+ filter: {
355
+ sessionId: parentSessionId,
356
+ toolName: "dispatch-sub-agent-task",
357
+ invokeStatus: {
358
+ $ne: "confirmed"
359
+ }
360
+ },
361
+ sort: ["-id"]
362
+ }));
363
+ return (0, import_ctx_utils.toPlain)(record);
364
+ } catch {
365
+ return null;
366
+ }
367
+ }
368
+ async resolveDispatchToolMessageFromMetadata(ctx, parentSessionId, subSessionId) {
369
+ var _a, _b, _c, _d, _e, _f;
370
+ if (!parentSessionId || !subSessionId) return null;
371
+ const messageRepo = (_b = (_a = ctx.db) == null ? void 0 : _a.getRepository) == null ? void 0 : _b.call(_a, "aiMessages");
372
+ const toolRepo = (_d = (_c = ctx.db) == null ? void 0 : _c.getRepository) == null ? void 0 : _d.call(_c, "aiToolMessages");
373
+ const messages = await ((_e = messageRepo == null ? void 0 : messageRepo.find) == null ? void 0 : _e.call(messageRepo, {
374
+ filter: { sessionId: parentSessionId },
375
+ sort: ["-messageId"],
376
+ limit: 20
377
+ }));
378
+ if (!Array.isArray(messages)) return null;
379
+ for (const rawMessage of messages) {
380
+ const message = (0, import_ctx_utils.toPlain)(rawMessage);
381
+ const conversations = (0, import_ctx_utils.asObject)(message == null ? void 0 : message.metadata).subAgentConversations;
382
+ if (!Array.isArray(conversations)) continue;
383
+ const matched = conversations.find((item) => normalizeString(item == null ? void 0 : item.sessionId) === subSessionId);
384
+ const toolCallId = normalizeString(matched == null ? void 0 : matched.toolCallId);
385
+ if (!toolCallId) continue;
386
+ const toolMessage = await ((_f = toolRepo == null ? void 0 : toolRepo.findOne) == null ? void 0 : _f.call(toolRepo, {
387
+ filter: {
388
+ sessionId: parentSessionId,
389
+ toolCallId
390
+ }
391
+ }));
392
+ return {
393
+ ...(0, import_ctx_utils.toPlain)(toolMessage) || {},
394
+ toolCallId,
395
+ messageId: readValue(toolMessage, "messageId") || (message == null ? void 0 : message.messageId),
396
+ sessionId: parentSessionId,
397
+ status: matched == null ? void 0 : matched.status
398
+ };
399
+ }
400
+ return null;
401
+ }
402
+ async flushPending(state) {
403
+ const pending = Array.from(state.pending);
404
+ if (!pending.length) return;
405
+ await Promise.allSettled(pending);
406
+ }
407
+ }
408
+ // Annotate the CommonJS export names for ESM import in node:
409
+ 0 && (module.exports = {
410
+ NATIVE_SOURCE,
411
+ NativeSubAgentObserver,
412
+ makeNativeRunId
413
+ });