plugin-agent-orchestrator 1.0.32 → 1.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +114 -114
  2. package/dist/externalVersion.js +6 -6
  3. package/dist/server/collections/skill-executions.js +21 -0
  4. package/dist/server/plugin.js +132 -3
  5. package/dist/server/resources/agent-loop.js +1 -2
  6. package/dist/server/services/AgentLoopController.js +39 -1
  7. package/dist/server/services/AgentLoopService.js +3 -0
  8. package/dist/server/services/AgentRuntimeLifecycle.js +70 -0
  9. package/dist/server/services/FileManager.js +12 -0
  10. package/dist/server/services/NativeSubAgentObserver.js +20 -0
  11. package/dist/server/services/PlanningPromptService.js +95 -0
  12. package/dist/server/services/SandboxRunner.js +251 -56
  13. package/dist/server/services/TokenTracker.js +20 -0
  14. package/dist/server/services/WorkerEnvManager.js +76 -10
  15. package/dist/server/services/pythonGuardTemplate.js +105 -0
  16. package/dist/server/services/sandboxCapabilities.js +286 -0
  17. package/dist/server/skill-hub/plugin.js +98 -24
  18. package/dist/server/skill-hub/tasks/SkillExecutionTask.js +53 -11
  19. package/dist/server/utils/skill-settings.js +1 -1
  20. package/package.json +47 -47
  21. package/src/client-v2/components/AgentRunsTab.tsx +494 -494
  22. package/src/client-v2/components/TracingTab.tsx +432 -432
  23. package/src/client-v2/hooks/useApiRequest.ts +121 -121
  24. package/src/server/__tests__/agent-runtime-lifecycle.test.ts +46 -0
  25. package/src/server/__tests__/planning-prompt-service.test.ts +23 -0
  26. package/src/server/__tests__/skill-sandbox-worker-mode.test.ts +15 -0
  27. package/src/server/collections/skill-executions.ts +21 -0
  28. package/src/server/plugin.ts +151 -0
  29. package/src/server/resources/agent-loop.ts +1 -2
  30. package/src/server/resources/agent-monitor.ts +482 -482
  31. package/src/server/services/AgentLoopController.ts +50 -1
  32. package/src/server/services/AgentLoopService.ts +4 -0
  33. package/src/server/services/AgentRuntimeLifecycle.ts +64 -0
  34. package/src/server/services/ExecutionSpanService.ts +110 -110
  35. package/src/server/services/FileManager.ts +16 -1
  36. package/src/server/services/NativeSubAgentObserver.ts +528 -507
  37. package/src/server/services/PlanningPromptService.ts +72 -0
  38. package/src/server/services/SandboxRunner.ts +341 -74
  39. package/src/server/services/TokenTracker.ts +26 -0
  40. package/src/server/services/WorkerEnvManager.ts +95 -9
  41. package/src/server/services/pythonGuardTemplate.ts +87 -0
  42. package/src/server/services/sandboxCapabilities.ts +348 -0
  43. package/src/server/skill-hub/plugin.ts +106 -23
  44. package/src/server/skill-hub/tasks/SkillExecutionTask.ts +51 -6
  45. package/src/server/utils/skill-settings.ts +1 -0
@@ -0,0 +1,105 @@
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 pythonGuardTemplate_exports = {};
28
+ __export(pythonGuardTemplate_exports, {
29
+ PY_GUARD_SITECUSTOMIZE_SOURCE: () => PY_GUARD_SITECUSTOMIZE_SOURCE
30
+ });
31
+ module.exports = __toCommonJS(pythonGuardTemplate_exports);
32
+ const PY_GUARD_SITECUSTOMIZE_SOURCE = `"""NocoBase skill-hub sandbox guard (auto-generated; do not edit)."""
33
+ import os
34
+ import sys
35
+
36
+ _BLOCKED_EVENTS = frozenset((
37
+ "os.system",
38
+ "os.fork",
39
+ "os.forkpty",
40
+ "os.exec",
41
+ "os.spawn",
42
+ "os.posix_spawn",
43
+ "subprocess.Popen",
44
+ "_posixsubprocess.fork_exec",
45
+ "ctypes.dlopen",
46
+ "ctypes.dlsym",
47
+ "ctypes.dlsym/handle",
48
+ ))
49
+
50
+ _raw_roots = os.environ.get("SKILL_HUB_WRITE_ROOTS", "")
51
+ _WRITE_ROOTS = tuple(
52
+ os.path.realpath(root) for root in _raw_roots.split(os.pathsep) if root
53
+ )
54
+
55
+ _WRITE_FLAGS = (
56
+ os.O_WRONLY
57
+ | os.O_RDWR
58
+ | os.O_APPEND
59
+ | getattr(os, "O_CREAT", 0)
60
+ | getattr(os, "O_TRUNC", 0)
61
+ )
62
+
63
+
64
+ def _is_write_open(mode, flags):
65
+ if isinstance(mode, str):
66
+ return any(ch in mode for ch in ("w", "a", "x", "+"))
67
+ try:
68
+ return bool(int(flags) & _WRITE_FLAGS)
69
+ except (TypeError, ValueError):
70
+ return False
71
+
72
+
73
+ def _is_allowed_write_path(path):
74
+ try:
75
+ resolved = os.path.realpath(os.fspath(path))
76
+ except (TypeError, ValueError):
77
+ # fd-based or exotic targets cannot be path-scoped here
78
+ return True
79
+ for root in _WRITE_ROOTS:
80
+ if resolved == root or resolved.startswith(root + os.sep):
81
+ return True
82
+ return False
83
+
84
+
85
+ def _skill_hub_guard(event, args):
86
+ if event in _BLOCKED_EVENTS:
87
+ raise RuntimeError(
88
+ "skill-hub sandbox: blocked audited operation '%s'" % event
89
+ )
90
+ if _WRITE_ROOTS and event == "open" and len(args) >= 3:
91
+ path, mode, flags = args[0], args[1], args[2]
92
+ if path is not None and _is_write_open(mode, flags) and not _is_allowed_write_path(path):
93
+ # PermissionError (an OSError) so import machinery treats a denied
94
+ # bytecode-cache write as best-effort instead of aborting imports.
95
+ raise PermissionError(
96
+ "skill-hub sandbox: write outside allowed roots denied: %r" % (path,)
97
+ )
98
+
99
+
100
+ sys.addaudithook(_skill_hub_guard)
101
+ `;
102
+ // Annotate the CommonJS export names for ESM import in node:
103
+ 0 && (module.exports = {
104
+ PY_GUARD_SITECUSTOMIZE_SOURCE
105
+ });
@@ -0,0 +1,286 @@
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 sandboxCapabilities_exports = {};
28
+ __export(sandboxCapabilities_exports, {
29
+ ensureSandboxCapabilities: () => ensureSandboxCapabilities,
30
+ getPythonGuardDir: () => getPythonGuardDir,
31
+ getSandboxCapabilities: () => getSandboxCapabilities,
32
+ getSandboxUsername: () => getSandboxUsername,
33
+ refreshSandboxCapabilities: () => refreshSandboxCapabilities,
34
+ resolveSandboxIdentity: () => resolveSandboxIdentity,
35
+ runProbeCommand: () => runProbeCommand,
36
+ setSandboxCapabilities: () => setSandboxCapabilities
37
+ });
38
+ module.exports = __toCommonJS(sandboxCapabilities_exports);
39
+ var import_child_process = require("child_process");
40
+ var import_fs = require("fs");
41
+ var import_path = require("path");
42
+ const IS_WINDOWS = process.platform === "win32";
43
+ const DEFAULT_CAPABILITIES = {
44
+ isolationLevel: IS_WINDOWS ? "minimal" : "hardened-spawn",
45
+ privilegeDropAvailable: false,
46
+ sandboxIdentity: null,
47
+ nodePermissionModel: "unknown",
48
+ nodePermissionFlag: null,
49
+ nodePermissionAllowAddons: false,
50
+ pythonGuardActive: false,
51
+ bwrapMode: "unavailable",
52
+ network: "none"
53
+ };
54
+ let current = { ...DEFAULT_CAPABILITIES };
55
+ let detectPromise = null;
56
+ function getSandboxCapabilities() {
57
+ return current;
58
+ }
59
+ function setSandboxCapabilities(next) {
60
+ current = next;
61
+ }
62
+ function getSandboxUsername() {
63
+ return process.env.SKILL_HUB_SANDBOX_USER || "nocobase-sandbox";
64
+ }
65
+ function getPythonGuardDir(storagePath) {
66
+ return (0, import_path.resolve)(storagePath, "sandbox-workspace", "py-guard");
67
+ }
68
+ function runProbeCommand(command, args, timeoutMs = 1e4, options = {}) {
69
+ return new Promise((_resolve) => {
70
+ var _a, _b;
71
+ let stdout = "";
72
+ let stderr = "";
73
+ let settled = false;
74
+ let timer = null;
75
+ const finish = (result) => {
76
+ if (settled) return;
77
+ settled = true;
78
+ if (timer) clearTimeout(timer);
79
+ _resolve(result);
80
+ };
81
+ let child;
82
+ try {
83
+ child = (0, import_child_process.spawn)(command, args, {
84
+ stdio: ["ignore", "pipe", "pipe"],
85
+ uid: options.uid,
86
+ gid: options.gid
87
+ });
88
+ } catch (error) {
89
+ finish({ code: null, stdout: "", stderr: String(error.message || error), errorCode: "SPAWN" });
90
+ return;
91
+ }
92
+ timer = setTimeout(() => {
93
+ child.kill("SIGTERM");
94
+ finish({ code: null, stdout, stderr: `${stderr}
95
+ [probe timed out after ${timeoutMs}ms]` });
96
+ }, timeoutMs);
97
+ (_a = child.stdout) == null ? void 0 : _a.on("data", (chunk) => {
98
+ if (stdout.length < 4096) stdout += chunk.toString();
99
+ });
100
+ (_b = child.stderr) == null ? void 0 : _b.on("data", (chunk) => {
101
+ if (stderr.length < 4096) stderr += chunk.toString();
102
+ });
103
+ child.on("error", (error) => {
104
+ finish({ code: null, stdout, stderr: error.message, errorCode: error.code });
105
+ });
106
+ child.on("close", (code) => {
107
+ finish({ code, stdout, stderr });
108
+ });
109
+ });
110
+ }
111
+ function resolveBinaryPath(name) {
112
+ for (const dir of (process.env.PATH || "").split(import_path.delimiter)) {
113
+ if (!dir) continue;
114
+ const candidate = (0, import_path.join)(dir, name);
115
+ if ((0, import_fs.existsSync)(candidate)) return candidate;
116
+ }
117
+ return null;
118
+ }
119
+ function resolveSandboxIdentity(username) {
120
+ try {
121
+ const passwd = (0, import_fs.readFileSync)("/etc/passwd", "utf-8");
122
+ for (const line of passwd.split("\n")) {
123
+ const parts = line.split(":");
124
+ if (parts[0] === username && parts.length >= 4) {
125
+ const uid = Number(parts[2]);
126
+ const gid = Number(parts[3]);
127
+ if (Number.isInteger(uid) && uid >= 0 && Number.isInteger(gid) && gid >= 0) {
128
+ return { username, uid, gid };
129
+ }
130
+ }
131
+ }
132
+ } catch {
133
+ }
134
+ return null;
135
+ }
136
+ async function detectNodePermissionFlag(logger) {
137
+ const [majorRaw, minorRaw] = process.versions.node.split(".");
138
+ const major = Number(majorRaw);
139
+ const minor = Number(minorRaw);
140
+ let candidates;
141
+ if (major > 22 || major === 22 && minor >= 13) {
142
+ candidates = ["--permission", "--experimental-permission"];
143
+ } else if (major >= 20) {
144
+ candidates = ["--experimental-permission", "--permission"];
145
+ } else {
146
+ logger.info(`[skill-hub] Node ${process.versions.node} has no permission model; skipping that layer`);
147
+ return { model: "unavailable", flag: null, allowAddons: false };
148
+ }
149
+ for (const flag of candidates) {
150
+ const withAddons = await runProbeCommand(
151
+ "node",
152
+ [flag, "--allow-fs-read=/", "--allow-addons", "-e", "process.exit(0)"],
153
+ 15e3
154
+ );
155
+ if (withAddons.code === 0) {
156
+ return { model: flag === "--permission" ? "permission" : "experimental-permission", flag, allowAddons: true };
157
+ }
158
+ const bare = await runProbeCommand("node", [flag, "--allow-fs-read=/", "-e", "process.exit(0)"], 15e3);
159
+ if (bare.code === 0) {
160
+ return { model: flag === "--permission" ? "permission" : "experimental-permission", flag, allowAddons: false };
161
+ }
162
+ }
163
+ logger.warn("[skill-hub] Node permission model flags rejected by the local node binary; layer disabled");
164
+ return { model: "unavailable", flag: null, allowAddons: false };
165
+ }
166
+ const BWRAP_SMOKE_ARGS = [
167
+ "--unshare-user",
168
+ "--unshare-pid",
169
+ "--ro-bind",
170
+ "/",
171
+ "/",
172
+ "--dev",
173
+ "/dev",
174
+ "--proc",
175
+ "/proc",
176
+ "--",
177
+ "true"
178
+ ];
179
+ async function detectBwrap(logger, identity) {
180
+ var _a, _b;
181
+ if (process.platform !== "linux") return "unavailable";
182
+ const version = await runProbeCommand("bwrap", ["--version"], 5e3);
183
+ if (version.errorCode === "ENOENT") {
184
+ logger.info("[skill-hub] bwrap not installed; using hardened spawn isolation (Layer 1)");
185
+ return "unavailable";
186
+ }
187
+ const probeIds = identity && ((_a = process.getuid) == null ? void 0 : _a.call(process)) === 0 ? { uid: identity.uid, gid: identity.gid } : {};
188
+ const unprivileged = await runProbeCommand("bwrap", BWRAP_SMOKE_ARGS, 1e4, probeIds);
189
+ if (unprivileged.code === 0) return "unprivileged";
190
+ if (((_b = process.getuid) == null ? void 0 : _b.call(process)) === 0) {
191
+ const bwrapPath = resolveBinaryPath("bwrap");
192
+ if (bwrapPath) {
193
+ try {
194
+ const mode = (0, import_fs.statSync)(bwrapPath).mode;
195
+ if (!(mode & 2048)) {
196
+ (0, import_fs.chmodSync)(bwrapPath, mode & 4095 | 2048);
197
+ }
198
+ const retried = await runProbeCommand("bwrap", BWRAP_SMOKE_ARGS, 1e4, probeIds);
199
+ if (retried.code === 0) return "setuid";
200
+ logger.warn(
201
+ `[skill-hub] bwrap unusable even with setuid bit \u2014 likely unprivileged user namespaces disabled at the host kernel and no-new-privileges set on the container: ${retried.stderr.trim().slice(0, 200)}`
202
+ );
203
+ } catch (error) {
204
+ logger.warn(`[skill-hub] Could not apply setuid fallback to bwrap: ${error.message}`);
205
+ }
206
+ }
207
+ } else {
208
+ logger.warn(
209
+ `[skill-hub] bwrap installed but namespace creation failed (unprivileged userns disabled?): ${unprivileged.stderr.trim().slice(0, 200)}`
210
+ );
211
+ }
212
+ return "unavailable";
213
+ }
214
+ async function detectSandboxCapabilities(logger, storagePath) {
215
+ var _a, _b;
216
+ const network = process.env.SKILL_HUB_SANDBOX_NET === "inherit" ? "inherit" : "none";
217
+ const pythonGuardActive = process.env.SKILL_HUB_PY_GUARD !== "false" && (0, import_fs.existsSync)((0, import_path.join)(getPythonGuardDir(storagePath), "sitecustomize.py"));
218
+ let nodePermission;
219
+ try {
220
+ nodePermission = await detectNodePermissionFlag(logger);
221
+ } catch (error) {
222
+ logger.warn(`[skill-hub] Node permission model detection failed: ${error.message}`);
223
+ nodePermission = { model: "unavailable", flag: null, allowAddons: false };
224
+ }
225
+ let identity = null;
226
+ let privilegeDropAvailable = false;
227
+ let bwrapMode = "unavailable";
228
+ if (!IS_WINDOWS) {
229
+ identity = resolveSandboxIdentity(getSandboxUsername());
230
+ privilegeDropAvailable = ((_a = process.getuid) == null ? void 0 : _a.call(process)) === 0 && identity !== null;
231
+ if (!privilegeDropAvailable) {
232
+ logger.warn(
233
+ `[skill-hub] Privilege drop unavailable (root=${((_b = process.getuid) == null ? void 0 : _b.call(process)) === 0}, sandbox user "${getSandboxUsername()}" resolved=${identity !== null}); executions run as the worker user`
234
+ );
235
+ }
236
+ try {
237
+ bwrapMode = await detectBwrap(logger, privilegeDropAvailable ? identity : null);
238
+ } catch (error) {
239
+ logger.warn(`[skill-hub] bwrap detection failed: ${error.message}`);
240
+ bwrapMode = "unavailable";
241
+ }
242
+ }
243
+ const isolationLevel = bwrapMode !== "unavailable" ? "bwrap" : IS_WINDOWS ? "minimal" : "hardened-spawn";
244
+ const capabilities = {
245
+ isolationLevel,
246
+ privilegeDropAvailable,
247
+ sandboxIdentity: privilegeDropAvailable ? identity : null,
248
+ nodePermissionModel: nodePermission.model,
249
+ nodePermissionFlag: nodePermission.flag,
250
+ nodePermissionAllowAddons: nodePermission.allowAddons,
251
+ pythonGuardActive,
252
+ bwrapMode,
253
+ network
254
+ };
255
+ logger.info(
256
+ `[skill-hub] Sandbox isolation level: ${capabilities.isolationLevel} (privilege drop: ${capabilities.privilegeDropAvailable ? "active" : "off"}, node permission model: ${capabilities.nodePermissionModel}, python guard: ${capabilities.pythonGuardActive ? "active" : "off"}, bwrap: ${capabilities.bwrapMode}, network: ${capabilities.network})`
257
+ );
258
+ return capabilities;
259
+ }
260
+ function ensureSandboxCapabilities(logger, storagePath) {
261
+ if (!detectPromise) {
262
+ detectPromise = detectSandboxCapabilities(logger, storagePath).then((caps) => {
263
+ current = caps;
264
+ return caps;
265
+ });
266
+ }
267
+ return detectPromise;
268
+ }
269
+ function refreshSandboxCapabilities(logger, storagePath) {
270
+ detectPromise = detectSandboxCapabilities(logger, storagePath).then((caps) => {
271
+ current = caps;
272
+ return caps;
273
+ });
274
+ return detectPromise;
275
+ }
276
+ // Annotate the CommonJS export names for ESM import in node:
277
+ 0 && (module.exports = {
278
+ ensureSandboxCapabilities,
279
+ getPythonGuardDir,
280
+ getSandboxCapabilities,
281
+ getSandboxUsername,
282
+ refreshSandboxCapabilities,
283
+ resolveSandboxIdentity,
284
+ runProbeCommand,
285
+ setSandboxCapabilities
286
+ });
@@ -37,7 +37,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
37
37
  var plugin_exports = {};
38
38
  __export(plugin_exports, {
39
39
  SkillHubSubFeature: () => SkillHubSubFeature,
40
- default: () => plugin_default
40
+ default: () => plugin_default,
41
+ shouldRunSkillSandbox: () => shouldRunSkillSandbox
41
42
  });
42
43
  module.exports = __toCommonJS(plugin_exports);
43
44
  var import_path = require("path");
@@ -57,6 +58,10 @@ var import_ExecutionSpanService = require("../services/ExecutionSpanService");
57
58
  var import_ai_manager = require("../utils/ai-manager");
58
59
  const SKILL_TASK_POLL_INTERVAL_MS = Number.parseInt(process.env.SKILL_HUB_TASK_POLL_INTERVAL_MS || "5000", 10);
59
60
  const SKILL_TASK_POLL_LIMIT = Number.parseInt(process.env.SKILL_HUB_TASK_POLL_LIMIT || "3", 10);
61
+ function positiveInteger(value, fallback) {
62
+ const parsed = Number.parseInt(value || "", 10);
63
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
64
+ }
60
65
  function normalizeToolRuntime(runtime) {
61
66
  if (!runtime) return void 0;
62
67
  if (typeof runtime === "string") {
@@ -141,6 +146,16 @@ class SkillHubSubFeature {
141
146
  parseInt(process.env.SKILL_HUB_RATE_LIMIT_WINDOW_MS || "60000", 10)
142
147
  );
143
148
  skillTemplates = /* @__PURE__ */ new Map();
149
+ afterStart = async () => {
150
+ this.registerAITools();
151
+ this.startCleanupInterval();
152
+ this.startSkillTaskPoller();
153
+ await this.subscribeInitEnvDone();
154
+ await this.skillManager.seedDefaults().catch((error) => {
155
+ const message = error instanceof Error ? error.message : String(error);
156
+ this.app.logger.error(`[skill-hub] Failed to seed default skills: ${message}`);
157
+ });
158
+ };
144
159
  get app() {
145
160
  return this.plugin.app;
146
161
  }
@@ -264,25 +279,19 @@ class SkillHubSubFeature {
264
279
  }
265
280
  }
266
281
  });
267
- this.skillTaskCallback = async (payload) => {
268
- if (process.env.SKILL_HUB_SANDBOX === "false") return;
269
- await this.onQueueTask(payload);
270
- };
271
- this.app.pubSubManager.subscribe("skill-hub.task", this.skillTaskCallback);
272
- this.initEnvTaskCallback = async (payload) => {
273
- if (process.env.SKILL_HUB_SANDBOX === "false") return;
274
- await this.workerEnvManager.executeInit(payload);
275
- };
276
- this.app.pubSubManager.subscribe("skill-hub.init-env", this.initEnvTaskCallback);
277
- this.app.on("afterStart", async () => {
278
- this.registerAITools();
279
- this.startCleanupInterval();
280
- this.startSkillTaskPoller();
281
- await this.subscribeInitEnvDone();
282
- await this.skillManager.seedDefaults().catch((e) => {
283
- this.app.logger.error(`[skill-hub] Failed to seed default skills: ${e.message}`);
284
- });
285
- });
282
+ if (shouldRunSkillSandbox()) {
283
+ this.skillTaskCallback = async (payload) => {
284
+ await this.onQueueTask(payload);
285
+ };
286
+ this.app.pubSubManager.subscribe("skill-hub.task", this.skillTaskCallback);
287
+ }
288
+ if (shouldRunSkillSandbox()) {
289
+ this.initEnvTaskCallback = async (payload) => {
290
+ await this.workerEnvManager.executeInit(payload);
291
+ };
292
+ this.app.pubSubManager.subscribe("skill-hub.init-env", this.initEnvTaskCallback);
293
+ }
294
+ this.app.on("afterStart", this.afterStart);
286
295
  }
287
296
  async onQueueTask(message) {
288
297
  this.app.logger.info(`[skill-hub] Worker received queue task: ${message.id}`);
@@ -313,8 +322,14 @@ class SkillHubSubFeature {
313
322
  }
314
323
  async claimSkillExecution(id) {
315
324
  const model = this.db.getModel("skillExecutions");
325
+ const now = /* @__PURE__ */ new Date();
316
326
  const [affected] = await model.update(
317
- { status: "running" },
327
+ {
328
+ status: "running",
329
+ startedAt: now,
330
+ heartbeatAt: now,
331
+ workerId: `${process.env.HOSTNAME || process.env.COMPUTERNAME || "worker"}:${process.pid}`
332
+ },
318
333
  {
319
334
  where: {
320
335
  id,
@@ -326,11 +341,11 @@ class SkillHubSubFeature {
326
341
  }
327
342
  startSkillTaskPoller() {
328
343
  var _a, _b;
329
- if (process.env.SKILL_HUB_SANDBOX === "false" || this.skillTaskPoller) {
344
+ if (!shouldRunSkillSandbox() || this.skillTaskPoller) {
330
345
  return;
331
346
  }
332
347
  const tick = () => {
333
- this.processPendingSkillExecutions().catch((error) => {
348
+ this.processSkillExecutionQueue().catch((error) => {
334
349
  this.app.logger.warn(`[skill-hub] Pending task poll failed: ${(error == null ? void 0 : error.message) || error}`);
335
350
  });
336
351
  };
@@ -338,6 +353,51 @@ class SkillHubSubFeature {
338
353
  (_b = (_a = this.skillTaskPoller).unref) == null ? void 0 : _b.call(_a);
339
354
  setTimeout(tick, 1e3);
340
355
  }
356
+ async processSkillExecutionQueue() {
357
+ await this.recoverStaleSkillExecutions();
358
+ await this.processPendingSkillExecutions();
359
+ }
360
+ async recoverStaleSkillExecutions() {
361
+ const staleAfterMs = positiveInteger(process.env.SKILL_HUB_STALE_EXECUTION_MS, 12e4);
362
+ const maxRetries = positiveInteger(process.env.SKILL_HUB_MAX_EXECUTION_RETRIES, 2);
363
+ const cutoff = new Date(Date.now() - staleAfterMs);
364
+ const repo = this.db.getRepository("skillExecutions");
365
+ const model = this.db.getModel("skillExecutions");
366
+ const staleExecutions = await repo.find({
367
+ filter: {
368
+ status: "running",
369
+ $or: [{ heartbeatAt: null }, { heartbeatAt: { $lt: cutoff } }]
370
+ },
371
+ limit: SKILL_TASK_POLL_LIMIT
372
+ });
373
+ for (const execution of staleExecutions) {
374
+ const id = execution.get("id");
375
+ const retryCount = Number(execution.get("retryCount") || 0);
376
+ const failed = retryCount >= maxRetries;
377
+ const Op = model.sequelize.Sequelize.Op;
378
+ const [affected] = await model.update(
379
+ {
380
+ status: failed ? "failed" : "pending",
381
+ retryCount: retryCount + 1,
382
+ workerId: null,
383
+ heartbeatAt: null,
384
+ stderr: failed ? `Execution abandoned after ${retryCount + 1} worker attempts.` : execution.get("stderr")
385
+ },
386
+ {
387
+ where: {
388
+ id,
389
+ status: "running",
390
+ [Op.or]: [{ heartbeatAt: null }, { heartbeatAt: { [Op.lt]: cutoff } }]
391
+ }
392
+ }
393
+ );
394
+ if (affected > 0) {
395
+ this.app.logger.warn(
396
+ `[skill-hub] Recovered stale execution ${id}: ${failed ? "failed" : "returned to pending"}.`
397
+ );
398
+ }
399
+ }
400
+ }
341
401
  async processPendingSkillExecutions() {
342
402
  if (this.skillTaskPolling) return;
343
403
  this.skillTaskPolling = true;
@@ -700,6 +760,7 @@ IMPORTANT: This skill is bound to a Skill Hub human-in-the-loop review template.
700
760
  }
701
761
  }
702
762
  startCleanupInterval() {
763
+ if (this.cleanupInterval) return;
703
764
  const CLEANUP_INTERVAL = 60 * 60 * 1e3;
704
765
  this.cleanupInterval = setInterval(async () => {
705
766
  try {
@@ -726,6 +787,9 @@ IMPORTANT: This skill is bound to a Skill Hub human-in-the-loop review template.
726
787
  }, CLEANUP_INTERVAL);
727
788
  }
728
789
  async beforeStop() {
790
+ var _a, _b, _c, _d;
791
+ (_b = (_a = this.app).off) == null ? void 0 : _b.call(_a, "afterStart", this.afterStart);
792
+ (_d = (_c = this.app).removeListener) == null ? void 0 : _d.call(_c, "afterStart", this.afterStart);
729
793
  if (this.skillTaskCallback) {
730
794
  try {
731
795
  await this.app.pubSubManager.unsubscribe("skill-hub.task", this.skillTaskCallback);
@@ -889,7 +953,17 @@ ${inlineInstructions}` : ""].filter(Boolean).join("\n\n");
889
953
  }
890
954
  }
891
955
  var plugin_default = SkillHubSubFeature;
956
+ function shouldRunSkillSandbox(env = process.env) {
957
+ if (env.SKILL_HUB_SANDBOX === "false") return false;
958
+ const workerMode = String(env.WORKER_MODE || "").trim();
959
+ if (!workerMode) return true;
960
+ if (workerMode === "*" || workerMode.split(",").map((value) => value.trim()).includes("skill-hub:sandbox")) {
961
+ return true;
962
+ }
963
+ return workerMode.split(",").map((value) => value.trim()).includes("skill-hub.task");
964
+ }
892
965
  // Annotate the CommonJS export names for ESM import in node:
893
966
  0 && (module.exports = {
894
- SkillHubSubFeature
967
+ SkillHubSubFeature,
968
+ shouldRunSkillSandbox
895
969
  });