opencode-supertask 0.3.0 → 0.3.1
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/CHANGELOG.md +15 -0
- package/README.md +1 -0
- package/README.zh-CN.md +1 -0
- package/dist/cli/{chunk-NCT3ETTK.js → chunk-7BATA4DM.js} +20 -1
- package/dist/cli/chunk-7BATA4DM.js.map +1 -0
- package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
- package/dist/cli/{chunk-764OMIPC.js → chunk-OJLDJVHB.js} +2 -2
- package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
- package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
- package/dist/cli/{chunk-YB7MYTE5.js → chunk-XWTKMNNI.js} +3 -1
- package/dist/cli/chunk-XWTKMNNI.js.map +1 -0
- package/dist/cli/{chunk-USBQGFQZ.js → chunk-YADLWDYK.js} +2 -2
- package/dist/cli/{database-maintenance.service-VZCH7ZEV.js → database-maintenance.service-NQBZ5VJT.js} +4 -4
- package/dist/cli/{doctor-smoke-ZKWNHC3O.js → doctor-smoke-6VU2KCRK.js} +4 -4
- package/dist/cli/{gateway-HUXVEDMU.js → gateway-I2SQOXWB.js} +507 -14
- package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
- package/dist/cli/index.js +17 -17
- package/dist/cli/{logs-XNLR23TK.js → logs-HB5RV7HD.js} +4 -4
- package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
- package/dist/cli/{task-run.service-HCMHWOGW.js → task-run.service-R45W2VID.js} +4 -4
- package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
- package/dist/cli/{web-TQO6JLBN.js → web-4QWJ4Z5K.js} +9 -8
- package/dist/cli/web-4QWJ4Z5K.js.map +1 -0
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
- package/dist/gateway/index.d.ts +1 -0
- package/dist/gateway/index.js +535 -11
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.js +42 -1
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/web/index.js +24 -2
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +492 -1
- package/dist/worker/index.js +508 -8
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.js.map +1 -1
- package/package.json +1 -1
- package/dist/cli/chunk-LX5CBJLP.js.map +0 -1
- package/dist/cli/chunk-NCT3ETTK.js.map +0 -1
- package/dist/cli/chunk-YB7MYTE5.js.map +0 -1
- package/dist/cli/gateway-HUXVEDMU.js.map +0 -1
- package/dist/cli/web-TQO6JLBN.js.map +0 -1
- /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
- /package/dist/cli/{chunk-764OMIPC.js.map → chunk-OJLDJVHB.js.map} +0 -0
- /package/dist/cli/{chunk-USBQGFQZ.js.map → chunk-YADLWDYK.js.map} +0 -0
- /package/dist/cli/{database-maintenance.service-VZCH7ZEV.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
- /package/dist/cli/{doctor-smoke-ZKWNHC3O.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
- /package/dist/cli/{logs-XNLR23TK.js.map → logs-HB5RV7HD.js.map} +0 -0
- /package/dist/cli/{pm2-WY644BUO.js.map → pm2-YSCAIIBU.js.map} +0 -0
- /package/dist/cli/{task-run.service-HCMHWOGW.js.map → task-run.service-R45W2VID.js.map} +0 -0
- /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
package/dist/gateway/index.js
CHANGED
|
@@ -8244,12 +8244,13 @@ function isMatchingDrainProof(message, launchIdentity) {
|
|
|
8244
8244
|
const candidate = message;
|
|
8245
8245
|
return candidate.type === DRAIN_PROOF_MESSAGE_TYPE && candidate.identity === launchIdentity;
|
|
8246
8246
|
}
|
|
8247
|
-
var LEGACY_GUARDIAN_LAUNCH_PROTOCOL, TOKEN_GUARDIAN_LAUNCH_PROTOCOL, LAUNCH_IDENTITY_ARGUMENT, DRAIN_PROOF_MESSAGE_TYPE, DRAIN_PROOF_ACK_MESSAGE_TYPE, MANAGED_RUN_ENV, MANAGED_RUN_ENV_VALUE;
|
|
8247
|
+
var LEGACY_GUARDIAN_LAUNCH_PROTOCOL, TOKEN_GUARDIAN_LAUNCH_PROTOCOL, HTTP_RUNNER_LAUNCH_PROTOCOL, LAUNCH_IDENTITY_ARGUMENT, DRAIN_PROOF_MESSAGE_TYPE, DRAIN_PROOF_ACK_MESSAGE_TYPE, MANAGED_RUN_ENV, MANAGED_RUN_ENV_VALUE;
|
|
8248
8248
|
var init_launch_protocol = __esm({
|
|
8249
8249
|
"src/core/launch-protocol.ts"() {
|
|
8250
8250
|
"use strict";
|
|
8251
8251
|
LEGACY_GUARDIAN_LAUNCH_PROTOCOL = "gated-v2-guardian";
|
|
8252
8252
|
TOKEN_GUARDIAN_LAUNCH_PROTOCOL = "gated-v3-token-guardian";
|
|
8253
|
+
HTTP_RUNNER_LAUNCH_PROTOCOL = "runner:opencode-server";
|
|
8253
8254
|
LAUNCH_IDENTITY_ARGUMENT = "--supertask-launch-identity";
|
|
8254
8255
|
DRAIN_PROOF_MESSAGE_TYPE = "supertask-drained";
|
|
8255
8256
|
DRAIN_PROOF_ACK_MESSAGE_TYPE = "supertask-drained-ack";
|
|
@@ -9334,6 +9335,32 @@ var init_events = __esm({
|
|
|
9334
9335
|
}
|
|
9335
9336
|
});
|
|
9336
9337
|
|
|
9338
|
+
// src/core/env-sanitize.ts
|
|
9339
|
+
function sanitizedChildEnv(baseEnv = process.env, overrides = {}) {
|
|
9340
|
+
const env = { ...baseEnv };
|
|
9341
|
+
for (const key of GATEWAY_SECRET_ENV_KEYS) {
|
|
9342
|
+
delete env[key];
|
|
9343
|
+
}
|
|
9344
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
9345
|
+
if (value === void 0) delete env[key];
|
|
9346
|
+
else env[key] = value;
|
|
9347
|
+
}
|
|
9348
|
+
return env;
|
|
9349
|
+
}
|
|
9350
|
+
var GATEWAY_SECRET_ENV_KEYS;
|
|
9351
|
+
var init_env_sanitize = __esm({
|
|
9352
|
+
"src/core/env-sanitize.ts"() {
|
|
9353
|
+
"use strict";
|
|
9354
|
+
GATEWAY_SECRET_ENV_KEYS = [
|
|
9355
|
+
"SUPERTASK_API_TOKEN",
|
|
9356
|
+
"SUPERTASK_WEBHOOK_SECRET",
|
|
9357
|
+
"SUPERTASK_WEBHOOK_URL",
|
|
9358
|
+
"OPENCODE_PASSWORD",
|
|
9359
|
+
"OPENCODE_SERVER_PASSWORD"
|
|
9360
|
+
];
|
|
9361
|
+
}
|
|
9362
|
+
});
|
|
9363
|
+
|
|
9337
9364
|
// src/core/opencode-cli.ts
|
|
9338
9365
|
import { spawn, spawnSync } from "child_process";
|
|
9339
9366
|
function openCodeExecutable() {
|
|
@@ -9352,7 +9379,7 @@ function detectOpenCodeVersion(executable = openCodeExecutable(), options = {})
|
|
|
9352
9379
|
const result = new Promise((resolve4, reject) => {
|
|
9353
9380
|
const child = spawn(executable, ["--version"], {
|
|
9354
9381
|
cwd: options.cwd,
|
|
9355
|
-
env: process.env,
|
|
9382
|
+
env: sanitizedChildEnv(process.env),
|
|
9356
9383
|
stdio: ["ignore", "pipe", "pipe"]
|
|
9357
9384
|
});
|
|
9358
9385
|
let output = "";
|
|
@@ -9427,6 +9454,7 @@ var OpenCodeInvocationError, VERSION_TIMEOUT_MS, VERSION_CACHE_MS, versionCache;
|
|
|
9427
9454
|
var init_opencode_cli = __esm({
|
|
9428
9455
|
"src/core/opencode-cli.ts"() {
|
|
9429
9456
|
"use strict";
|
|
9457
|
+
init_env_sanitize();
|
|
9430
9458
|
OpenCodeInvocationError = class extends Error {
|
|
9431
9459
|
};
|
|
9432
9460
|
VERSION_TIMEOUT_MS = 15e3;
|
|
@@ -21174,7 +21202,7 @@ function runOpenCode(executable, args, cwd, timeoutMs) {
|
|
|
21174
21202
|
const child = spawn3(executable, args, {
|
|
21175
21203
|
cwd,
|
|
21176
21204
|
// OpenCode 以 PWD 优先解析项目目录(2.x run/api 与 1.x TUI 均如此),必须与 cwd 一致。
|
|
21177
|
-
env:
|
|
21205
|
+
env: sanitizedChildEnv(process.env, { PWD: cwd }),
|
|
21178
21206
|
stdio: ["ignore", "pipe", "pipe"],
|
|
21179
21207
|
detached: process.platform !== "win32"
|
|
21180
21208
|
});
|
|
@@ -21422,6 +21450,7 @@ var init_opencode_catalog = __esm({
|
|
|
21422
21450
|
"use strict";
|
|
21423
21451
|
init_task_working_directory();
|
|
21424
21452
|
init_opencode_cli();
|
|
21453
|
+
init_env_sanitize();
|
|
21425
21454
|
CATALOG_CACHE_MS = 3e4;
|
|
21426
21455
|
COMMAND_TIMEOUT_MS = 2e4;
|
|
21427
21456
|
MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
|
@@ -29748,6 +29777,7 @@ import { createHmac } from "crypto";
|
|
|
29748
29777
|
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
29749
29778
|
var DEFAULT_MAX_ATTEMPTS = 2;
|
|
29750
29779
|
var MAX_SUMMARY_CHARS = 2e3;
|
|
29780
|
+
var pendingWebhooks = /* @__PURE__ */ new Set();
|
|
29751
29781
|
function signWebhookPayload(secret, timestamp2, body) {
|
|
29752
29782
|
const digest = createHmac("sha256", secret).update(`${timestamp2}.${body}`).digest("hex");
|
|
29753
29783
|
return `sha256=${digest}`;
|
|
@@ -29767,6 +29797,8 @@ function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
|
|
|
29767
29797
|
} else if (event.type === "error") {
|
|
29768
29798
|
const msg = event.error?.data?.message || event.error?.message;
|
|
29769
29799
|
if (typeof msg === "string" && msg.trim()) texts.push(msg.trim());
|
|
29800
|
+
} else if (event.type === "tool_use" && event.part?.state?.status === "error" && typeof event.part.state.error === "string" && event.part.state.error.trim()) {
|
|
29801
|
+
texts.push(event.part.state.error.trim());
|
|
29770
29802
|
}
|
|
29771
29803
|
} catch {
|
|
29772
29804
|
if (!framed) texts.push(trimmed);
|
|
@@ -29807,7 +29839,15 @@ function buildTaskWebhookPayload(event, task, run, outputOverride) {
|
|
|
29807
29839
|
outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
|
|
29808
29840
|
};
|
|
29809
29841
|
}
|
|
29810
|
-
|
|
29842
|
+
function dispatchTaskWebhook(payload, options = {}) {
|
|
29843
|
+
const task = deliverTaskWebhook(payload, options);
|
|
29844
|
+
pendingWebhooks.add(task);
|
|
29845
|
+
void task.finally(() => {
|
|
29846
|
+
pendingWebhooks.delete(task);
|
|
29847
|
+
});
|
|
29848
|
+
return task;
|
|
29849
|
+
}
|
|
29850
|
+
async function deliverTaskWebhook(payload, options = {}) {
|
|
29811
29851
|
const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
|
|
29812
29852
|
if (!url) return false;
|
|
29813
29853
|
try {
|
|
@@ -29836,6 +29876,7 @@ async function dispatchTaskWebhook(payload, options = {}) {
|
|
|
29836
29876
|
method: "POST",
|
|
29837
29877
|
headers,
|
|
29838
29878
|
body,
|
|
29879
|
+
redirect: "error",
|
|
29839
29880
|
signal: AbortSignal.timeout(timeoutMs)
|
|
29840
29881
|
});
|
|
29841
29882
|
if (resp.ok) return true;
|
|
@@ -29850,6 +29891,18 @@ async function dispatchTaskWebhook(payload, options = {}) {
|
|
|
29850
29891
|
}));
|
|
29851
29892
|
return false;
|
|
29852
29893
|
}
|
|
29894
|
+
if (attempt >= maxAttempts) {
|
|
29895
|
+
console.warn(JSON.stringify({
|
|
29896
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
29897
|
+
level: "warn",
|
|
29898
|
+
msg: "task webhook delivery exhausted",
|
|
29899
|
+
event: payload.event,
|
|
29900
|
+
taskId: payload.task.id,
|
|
29901
|
+
status: resp.status,
|
|
29902
|
+
attempts: maxAttempts
|
|
29903
|
+
}));
|
|
29904
|
+
return false;
|
|
29905
|
+
}
|
|
29853
29906
|
} catch (err) {
|
|
29854
29907
|
if (attempt >= maxAttempts) {
|
|
29855
29908
|
console.warn(JSON.stringify({
|
|
@@ -29870,6 +29923,356 @@ async function dispatchTaskWebhook(payload, options = {}) {
|
|
|
29870
29923
|
return false;
|
|
29871
29924
|
}
|
|
29872
29925
|
|
|
29926
|
+
// src/worker/index.ts
|
|
29927
|
+
init_metadata();
|
|
29928
|
+
|
|
29929
|
+
// src/worker/runners/opencode-server.ts
|
|
29930
|
+
var MAX_SSE_BUFFER_CHARS = 2 * 1024 * 1024;
|
|
29931
|
+
function isLoopbackHost(hostname) {
|
|
29932
|
+
const h = hostname.toLowerCase();
|
|
29933
|
+
return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
|
|
29934
|
+
}
|
|
29935
|
+
function sanitizeErrorDetail(raw2, maxLen = 240) {
|
|
29936
|
+
if (!raw2) return "";
|
|
29937
|
+
return raw2.replace(/(authorization\s*[:=]\s*)(basic|bearer)\s+[^\s,;'"`]+/gi, "$1$2 [REDACTED]").replace(/(basic|bearer)\s+[A-Za-z0-9+/_=-]{12,}/gi, "$1 [REDACTED]").replace(/((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^\s"',;{}]+/gi, "$1[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "sk-[REDACTED]").replace(/\s+/g, " ").trim().slice(0, maxLen);
|
|
29938
|
+
}
|
|
29939
|
+
function parseModelSpec(rawModel, explicitVariant) {
|
|
29940
|
+
if (!rawModel || rawModel === "default") return null;
|
|
29941
|
+
let modelStr = rawModel.trim();
|
|
29942
|
+
let variant = explicitVariant?.trim() || void 0;
|
|
29943
|
+
const hashIdx = modelStr.indexOf("#");
|
|
29944
|
+
if (hashIdx > 0) {
|
|
29945
|
+
const embedded = modelStr.slice(hashIdx + 1).trim();
|
|
29946
|
+
modelStr = modelStr.slice(0, hashIdx).trim();
|
|
29947
|
+
if (!variant && embedded) variant = embedded;
|
|
29948
|
+
}
|
|
29949
|
+
const slashIdx = modelStr.indexOf("/");
|
|
29950
|
+
if (slashIdx <= 0 || slashIdx === modelStr.length - 1) return null;
|
|
29951
|
+
return {
|
|
29952
|
+
providerID: modelStr.slice(0, slashIdx),
|
|
29953
|
+
id: modelStr.slice(slashIdx + 1),
|
|
29954
|
+
...variant ? { variant } : {}
|
|
29955
|
+
};
|
|
29956
|
+
}
|
|
29957
|
+
var OpenCodeServerRunner = class {
|
|
29958
|
+
name = "opencode-server";
|
|
29959
|
+
baseUrl;
|
|
29960
|
+
password;
|
|
29961
|
+
defaultModel;
|
|
29962
|
+
allowInsecureHttp;
|
|
29963
|
+
fetchFn;
|
|
29964
|
+
constructor(options = {}) {
|
|
29965
|
+
const rawUrl = (options.baseUrl ?? process.env.OPENCODE_URL ?? "").trim();
|
|
29966
|
+
this.baseUrl = rawUrl.replace(/\/+$/, "");
|
|
29967
|
+
this.password = (options.password ?? process.env.OPENCODE_PASSWORD ?? "").trim();
|
|
29968
|
+
this.defaultModel = (options.defaultModel ?? process.env.SUPERTASK_DEFAULT_MODEL ?? process.env.DEFAULT_MODEL ?? "").trim();
|
|
29969
|
+
this.allowInsecureHttp = options.allowInsecureHttp ?? process.env.SUPERTASK_ALLOW_INSECURE_HTTP === "1";
|
|
29970
|
+
this.fetchFn = options.fetchImpl ?? fetch;
|
|
29971
|
+
}
|
|
29972
|
+
authHeaders(extra = {}) {
|
|
29973
|
+
const headers = { ...extra };
|
|
29974
|
+
if (this.password) {
|
|
29975
|
+
headers.authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
|
|
29976
|
+
}
|
|
29977
|
+
return headers;
|
|
29978
|
+
}
|
|
29979
|
+
async interruptSession(sessionId) {
|
|
29980
|
+
try {
|
|
29981
|
+
const resp = await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
|
|
29982
|
+
method: "POST",
|
|
29983
|
+
headers: this.authHeaders(),
|
|
29984
|
+
signal: AbortSignal.timeout(3e3)
|
|
29985
|
+
});
|
|
29986
|
+
return resp.ok;
|
|
29987
|
+
} catch {
|
|
29988
|
+
return false;
|
|
29989
|
+
}
|
|
29990
|
+
}
|
|
29991
|
+
async execute(ctx) {
|
|
29992
|
+
if (!this.baseUrl) {
|
|
29993
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_URL \u914D\u7F6E" };
|
|
29994
|
+
}
|
|
29995
|
+
if (!this.password) {
|
|
29996
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_PASSWORD \u914D\u7F6E" };
|
|
29997
|
+
}
|
|
29998
|
+
let parsedBaseUrl;
|
|
29999
|
+
try {
|
|
30000
|
+
parsedBaseUrl = new URL(this.baseUrl);
|
|
30001
|
+
} catch {
|
|
30002
|
+
return { ok: false, sessionId: null, errorMessage: "OPENCODE_URL \u4E0D\u662F\u6709\u6548\u7684 HTTP(S) \u5730\u5740" };
|
|
30003
|
+
}
|
|
30004
|
+
if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && (isLoopbackHost(parsedBaseUrl.hostname) || this.allowInsecureHttp))) {
|
|
30005
|
+
return {
|
|
30006
|
+
ok: false,
|
|
30007
|
+
sessionId: null,
|
|
30008
|
+
errorMessage: "\u5B89\u5168\u9650\u5236\uFF1A\u975E\u672C\u673A\u5730\u5740\u7981\u6B62\u901A\u8FC7\u660E\u6587 HTTP \u4F20\u8F93 OpenCode \u53E3\u4EE4\uFF08\u8BF7\u4F7F\u7528 HTTPS \u6216\u8BBE\u7F6E SUPERTASK_ALLOW_INSECURE_HTTP=1\uFF09"
|
|
30009
|
+
};
|
|
30010
|
+
}
|
|
30011
|
+
const explicitModel = ctx.model && ctx.model !== "default" ? ctx.model.trim() : null;
|
|
30012
|
+
const explicitVariant = ctx.variant && ctx.variant !== "default" ? ctx.variant.trim() : null;
|
|
30013
|
+
if (explicitModel && !parseModelSpec(explicitModel, explicitVariant)) {
|
|
30014
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6548\u7684\u6A21\u578B\u683C\u5F0F\uFF08\u9700\u8981 provider/model\uFF09\uFF1A${explicitModel}` };
|
|
30015
|
+
}
|
|
30016
|
+
let sessionId = null;
|
|
30017
|
+
let interruptedRemote = false;
|
|
30018
|
+
const ensureInterrupt = async (targetIds) => {
|
|
30019
|
+
if (interruptedRemote && !targetIds) return;
|
|
30020
|
+
const ids = /* @__PURE__ */ new Set();
|
|
30021
|
+
if (targetIds) {
|
|
30022
|
+
for (const id of targetIds) if (id) ids.add(id);
|
|
30023
|
+
}
|
|
30024
|
+
if (sessionId) ids.add(sessionId);
|
|
30025
|
+
if (ids.size === 0) return;
|
|
30026
|
+
interruptedRemote = true;
|
|
30027
|
+
await Promise.all([...ids].map((id) => this.interruptSession(id)));
|
|
30028
|
+
};
|
|
30029
|
+
const sseController = new AbortController();
|
|
30030
|
+
const onOuterAbort = () => {
|
|
30031
|
+
sseController.abort();
|
|
30032
|
+
};
|
|
30033
|
+
if (ctx.signal.aborted) {
|
|
30034
|
+
return { ok: false, sessionId: null, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
30035
|
+
}
|
|
30036
|
+
ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
30037
|
+
try {
|
|
30038
|
+
const agentUrl = new URL(`${this.baseUrl}/api/agent`);
|
|
30039
|
+
agentUrl.searchParams.set("location[directory]", ctx.cwd);
|
|
30040
|
+
let agentDef;
|
|
30041
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
30042
|
+
const agentResp = await this.fetchFn(agentUrl.toString(), {
|
|
30043
|
+
headers: this.authHeaders(),
|
|
30044
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
30045
|
+
});
|
|
30046
|
+
if (!agentResp.ok) {
|
|
30047
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6CD5\u8BFB\u53D6 OpenCode Agent \u6E05\u5355\uFF1AHTTP ${agentResp.status}` };
|
|
30048
|
+
}
|
|
30049
|
+
const payload = await agentResp.json();
|
|
30050
|
+
agentDef = Array.isArray(payload.data) ? payload.data.find((a) => a.id === ctx.agent) : void 0;
|
|
30051
|
+
if (agentDef) break;
|
|
30052
|
+
if (attempt < 3) await new Promise((r) => setTimeout(r, 250));
|
|
30053
|
+
}
|
|
30054
|
+
if (!agentDef || agentDef.hidden || agentDef.disabled || agentDef.mode === "subagent") {
|
|
30055
|
+
return { ok: false, sessionId: null, errorMessage: `\u4EFB\u52A1\u7684 Agent \u5DF2\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\uFF08${ctx.agent}\uFF09` };
|
|
30056
|
+
}
|
|
30057
|
+
const createResp = await this.fetchFn(`${this.baseUrl}/api/session`, {
|
|
30058
|
+
method: "POST",
|
|
30059
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
30060
|
+
body: JSON.stringify({
|
|
30061
|
+
agent: ctx.agent,
|
|
30062
|
+
location: { directory: ctx.cwd },
|
|
30063
|
+
metadata: {
|
|
30064
|
+
...ctx.metadata ?? {},
|
|
30065
|
+
supertaskTaskId: ctx.task.id,
|
|
30066
|
+
supertaskRunId: ctx.runId
|
|
30067
|
+
}
|
|
30068
|
+
}),
|
|
30069
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
30070
|
+
});
|
|
30071
|
+
if (!createResp.ok) {
|
|
30072
|
+
return { ok: false, sessionId: null, errorMessage: `\u521B\u5EFA OpenCode \u4F1A\u8BDD\u5931\u8D25\uFF1AHTTP ${createResp.status}` };
|
|
30073
|
+
}
|
|
30074
|
+
const created = await createResp.json();
|
|
30075
|
+
sessionId = created.data?.id ?? created.id ?? null;
|
|
30076
|
+
if (!sessionId) {
|
|
30077
|
+
return { ok: false, sessionId: null, errorMessage: "OpenCode \u672A\u8FD4\u56DE\u6709\u6548\u7684\u4F1A\u8BDD ID" };
|
|
30078
|
+
}
|
|
30079
|
+
ctx.onSessionId(sessionId);
|
|
30080
|
+
const cleanTitle = ctx.title.replace(/\s+/g, " ").trim().slice(0, 200);
|
|
30081
|
+
if (cleanTitle) {
|
|
30082
|
+
await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}`, {
|
|
30083
|
+
method: "PATCH",
|
|
30084
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
30085
|
+
body: JSON.stringify({ title: cleanTitle }),
|
|
30086
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
30087
|
+
}).catch(() => void 0);
|
|
30088
|
+
}
|
|
30089
|
+
let modelSpec = explicitModel ? parseModelSpec(explicitModel, explicitVariant) : null;
|
|
30090
|
+
if (!modelSpec && agentDef.model?.providerID && agentDef.model?.id) {
|
|
30091
|
+
const resolvedVariant = explicitVariant ?? (agentDef.model.variant && agentDef.model.variant !== "default" ? agentDef.model.variant : void 0);
|
|
30092
|
+
modelSpec = {
|
|
30093
|
+
providerID: agentDef.model.providerID,
|
|
30094
|
+
id: agentDef.model.id,
|
|
30095
|
+
...resolvedVariant ? { variant: resolvedVariant } : {}
|
|
30096
|
+
};
|
|
30097
|
+
}
|
|
30098
|
+
if (!modelSpec && this.defaultModel) {
|
|
30099
|
+
modelSpec = parseModelSpec(this.defaultModel, explicitVariant);
|
|
30100
|
+
}
|
|
30101
|
+
if (explicitVariant && !modelSpec) {
|
|
30102
|
+
return { ok: false, sessionId, errorMessage: "\u6307\u5B9A\u4E86 variant \u4F46\u672A\u914D\u7F6E\u53EF\u7528\u6A21\u578B" };
|
|
30103
|
+
}
|
|
30104
|
+
if (modelSpec) {
|
|
30105
|
+
const switchResp = await this.fetchFn(
|
|
30106
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/model`,
|
|
30107
|
+
{
|
|
30108
|
+
method: "POST",
|
|
30109
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
30110
|
+
body: JSON.stringify({ model: modelSpec }),
|
|
30111
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
30112
|
+
}
|
|
30113
|
+
);
|
|
30114
|
+
if (!switchResp.ok) {
|
|
30115
|
+
return { ok: false, sessionId, errorMessage: `\u5207\u6362 OpenCode \u6A21\u578B\u5931\u8D25\uFF1AHTTP ${switchResp.status}` };
|
|
30116
|
+
}
|
|
30117
|
+
}
|
|
30118
|
+
const sseResp = await this.fetchFn(`${this.baseUrl}/api/event`, {
|
|
30119
|
+
headers: this.authHeaders({ accept: "text/event-stream" }),
|
|
30120
|
+
signal: sseController.signal
|
|
30121
|
+
});
|
|
30122
|
+
const contentType = sseResp.headers.get("content-type") || "";
|
|
30123
|
+
if (!sseResp.ok || !sseResp.body || !contentType.toLowerCase().includes("text/event-stream")) {
|
|
30124
|
+
sseController.abort();
|
|
30125
|
+
return {
|
|
30126
|
+
ok: false,
|
|
30127
|
+
sessionId,
|
|
30128
|
+
errorMessage: `\u65E0\u6CD5\u8BA2\u9605 OpenCode \u4E8B\u4EF6\u6D41\uFF1AHTTP ${sseResp.status}${contentType ? ` (${contentType})` : ""}`
|
|
30129
|
+
};
|
|
30130
|
+
}
|
|
30131
|
+
const promptResp = await this.fetchFn(
|
|
30132
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/prompt`,
|
|
30133
|
+
{
|
|
30134
|
+
method: "POST",
|
|
30135
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
30136
|
+
body: JSON.stringify({ text: ctx.prompt }),
|
|
30137
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(15e3)])
|
|
30138
|
+
}
|
|
30139
|
+
);
|
|
30140
|
+
if (!promptResp.ok) {
|
|
30141
|
+
sseController.abort();
|
|
30142
|
+
const detail = sanitizeErrorDetail(await promptResp.text().catch(() => ""));
|
|
30143
|
+
return {
|
|
30144
|
+
ok: false,
|
|
30145
|
+
sessionId,
|
|
30146
|
+
errorMessage: `OpenCode \u63D0\u4EA4\u4EFB\u52A1\u5931\u8D25\uFF1AHTTP ${promptResp.status}${detail ? ` ${detail}` : ""}`
|
|
30147
|
+
};
|
|
30148
|
+
}
|
|
30149
|
+
const trackedSessionIds = /* @__PURE__ */ new Set([sessionId]);
|
|
30150
|
+
const reader = sseResp.body.getReader();
|
|
30151
|
+
const decoder = new TextDecoder();
|
|
30152
|
+
let buffer = "";
|
|
30153
|
+
let pendingText = "";
|
|
30154
|
+
const flushText = () => {
|
|
30155
|
+
if (!pendingText) return;
|
|
30156
|
+
ctx.onOutputChunk(`${JSON.stringify({ type: "text", sessionID: sessionId, part: { text: pendingText } })}
|
|
30157
|
+
`);
|
|
30158
|
+
pendingText = "";
|
|
30159
|
+
};
|
|
30160
|
+
const processEventPayload = async (rawData) => {
|
|
30161
|
+
let evt;
|
|
30162
|
+
try {
|
|
30163
|
+
evt = JSON.parse(rawData);
|
|
30164
|
+
} catch {
|
|
30165
|
+
return null;
|
|
30166
|
+
}
|
|
30167
|
+
const evtType = evt.type || "";
|
|
30168
|
+
if (evtType === "session.created") {
|
|
30169
|
+
const childId = evt.data?.id ?? evt.data?.session?.id ?? "";
|
|
30170
|
+
const parentId = evt.data?.parentID ?? evt.data?.session?.parentID ?? "";
|
|
30171
|
+
if (childId && parentId && trackedSessionIds.has(parentId)) {
|
|
30172
|
+
trackedSessionIds.add(childId);
|
|
30173
|
+
}
|
|
30174
|
+
return null;
|
|
30175
|
+
}
|
|
30176
|
+
const evtSessionId = evt.data?.sessionID ?? evt.data?.form?.sessionID ?? "";
|
|
30177
|
+
if (!evtSessionId || !trackedSessionIds.has(evtSessionId)) return null;
|
|
30178
|
+
if (evtType === "permission.asked" || evtType === "form.created") {
|
|
30179
|
+
flushText();
|
|
30180
|
+
const message = evtType === "permission.asked" ? "\u4EFB\u52A1\u9700\u8981\u4EBA\u5DE5\u6279\u51C6\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\uFF0C\u6216\u660E\u786E\u8C03\u6574\u8BE5Agent\u7684\u64CD\u4F5C\u6743\u9650\u540E\u91CD\u8BD5\u3002" : "\u4EFB\u52A1\u9700\u8981\u4F60\u56DE\u7B54\u95EE\u9898\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u8865\u5168\u4EFB\u52A1\u8BF4\u660E\u540E\u91CD\u8BD5\uFF0C\u6216\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\u3002";
|
|
30181
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
30182
|
+
type: "error",
|
|
30183
|
+
sessionID: sessionId,
|
|
30184
|
+
error: { name: "InteractionRequired", data: { message } }
|
|
30185
|
+
})}
|
|
30186
|
+
`);
|
|
30187
|
+
await ensureInterrupt(trackedSessionIds);
|
|
30188
|
+
return { ok: false, sessionId, errorMessage: message };
|
|
30189
|
+
}
|
|
30190
|
+
if (evtSessionId !== sessionId) return null;
|
|
30191
|
+
if (evtType === "session.text.delta") {
|
|
30192
|
+
const delta = typeof evt.data?.delta === "string" ? evt.data.delta : typeof evt.data?.text === "string" ? evt.data.text : "";
|
|
30193
|
+
if (delta) {
|
|
30194
|
+
pendingText += delta;
|
|
30195
|
+
if (pendingText.includes("\n") || pendingText.length >= 256) flushText();
|
|
30196
|
+
}
|
|
30197
|
+
return null;
|
|
30198
|
+
}
|
|
30199
|
+
if (evtType === "session.step.ended") {
|
|
30200
|
+
flushText();
|
|
30201
|
+
return null;
|
|
30202
|
+
}
|
|
30203
|
+
if (evtType === "session.execution.succeeded") {
|
|
30204
|
+
flushText();
|
|
30205
|
+
return { ok: true, sessionId };
|
|
30206
|
+
}
|
|
30207
|
+
if (evtType === "session.execution.failed") {
|
|
30208
|
+
flushText();
|
|
30209
|
+
const rawErr = evt.data?.error?.data?.message || evt.data?.error?.message || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
30210
|
+
const errMsg = sanitizeErrorDetail(rawErr, 400) || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
30211
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
30212
|
+
type: "error",
|
|
30213
|
+
sessionID: sessionId,
|
|
30214
|
+
error: { name: evt.data?.error?.name || "ExecutionError", data: { message: errMsg } }
|
|
30215
|
+
})}
|
|
30216
|
+
`);
|
|
30217
|
+
return { ok: false, sessionId, errorMessage: errMsg };
|
|
30218
|
+
}
|
|
30219
|
+
if (evtType === "session.execution.interrupted") {
|
|
30220
|
+
flushText();
|
|
30221
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u6267\u884C\u5DF2\u4E2D\u65AD" };
|
|
30222
|
+
}
|
|
30223
|
+
return null;
|
|
30224
|
+
};
|
|
30225
|
+
try {
|
|
30226
|
+
while (true) {
|
|
30227
|
+
const { done, value } = await reader.read();
|
|
30228
|
+
if (done) break;
|
|
30229
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
30230
|
+
if (buffer.length > MAX_SSE_BUFFER_CHARS) {
|
|
30231
|
+
buffer = buffer.slice(-MAX_SSE_BUFFER_CHARS);
|
|
30232
|
+
}
|
|
30233
|
+
let sepIdx = buffer.indexOf("\n\n");
|
|
30234
|
+
while (sepIdx >= 0) {
|
|
30235
|
+
const frame = buffer.slice(0, sepIdx);
|
|
30236
|
+
buffer = buffer.slice(sepIdx + 2);
|
|
30237
|
+
const dataLines = [];
|
|
30238
|
+
for (const line of frame.split("\n")) {
|
|
30239
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
30240
|
+
}
|
|
30241
|
+
if (dataLines.length > 0) {
|
|
30242
|
+
const terminal = await processEventPayload(dataLines.join("\n"));
|
|
30243
|
+
if (terminal) {
|
|
30244
|
+
sseController.abort();
|
|
30245
|
+
return terminal;
|
|
30246
|
+
}
|
|
30247
|
+
}
|
|
30248
|
+
sepIdx = buffer.indexOf("\n\n");
|
|
30249
|
+
}
|
|
30250
|
+
}
|
|
30251
|
+
} finally {
|
|
30252
|
+
reader.releaseLock();
|
|
30253
|
+
}
|
|
30254
|
+
flushText();
|
|
30255
|
+
if (ctx.signal.aborted) {
|
|
30256
|
+
await ensureInterrupt(trackedSessionIds);
|
|
30257
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
30258
|
+
}
|
|
30259
|
+
await ensureInterrupt(trackedSessionIds);
|
|
30260
|
+
return { ok: false, sessionId, errorMessage: "OpenCode \u4E8B\u4EF6\u6D41\u63D0\u524D\u65AD\u5F00\uFF0C\u5DF2\u4E2D\u6B62\u8FDC\u7AEF\u4F1A\u8BDD" };
|
|
30261
|
+
} catch (error) {
|
|
30262
|
+
if (ctx.signal.aborted) {
|
|
30263
|
+
await ensureInterrupt();
|
|
30264
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
30265
|
+
}
|
|
30266
|
+
if (sessionId) await ensureInterrupt();
|
|
30267
|
+
const msg = sanitizeErrorDetail(error instanceof Error ? error.message : String(error), 300) || "Runner \u6267\u884C\u5F02\u5E38";
|
|
30268
|
+
return { ok: false, sessionId, errorMessage: msg };
|
|
30269
|
+
} finally {
|
|
30270
|
+
sseController.abort();
|
|
30271
|
+
ctx.signal.removeEventListener("abort", onOuterAbort);
|
|
30272
|
+
}
|
|
30273
|
+
}
|
|
30274
|
+
};
|
|
30275
|
+
|
|
29873
30276
|
// src/worker/index.ts
|
|
29874
30277
|
init_process_control();
|
|
29875
30278
|
init_launch_protocol();
|
|
@@ -30012,12 +30415,14 @@ var WorkerEngine = class {
|
|
|
30012
30415
|
settlementRetryWakeups = /* @__PURE__ */ new Set();
|
|
30013
30416
|
cfg;
|
|
30014
30417
|
opencodeBin;
|
|
30418
|
+
runner;
|
|
30015
30419
|
maxOutputChars;
|
|
30016
30420
|
settlementRetryDelaysMs;
|
|
30017
30421
|
settlementRetryIntervalMs;
|
|
30018
30422
|
constructor(cfg, options = {}) {
|
|
30019
30423
|
this.cfg = cfg.worker;
|
|
30020
30424
|
this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
|
|
30425
|
+
this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
|
|
30021
30426
|
this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
30022
30427
|
this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
|
|
30023
30428
|
this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
|
|
@@ -30066,7 +30471,7 @@ var WorkerEngine = class {
|
|
|
30066
30471
|
if (this.pollCyclePromise) await this.pollCyclePromise;
|
|
30067
30472
|
if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
|
|
30068
30473
|
const deadline = Date.now() + gracePeriodMs;
|
|
30069
|
-
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
30474
|
+
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (!entry.child || entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
30070
30475
|
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
30071
30476
|
}
|
|
30072
30477
|
}
|
|
@@ -30151,7 +30556,7 @@ var WorkerEngine = class {
|
|
|
30151
30556
|
while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
|
|
30152
30557
|
const databaseRunningCount = await TaskService.countRunning();
|
|
30153
30558
|
if (databaseRunningCount >= this.cfg.maxConcurrency) break;
|
|
30154
|
-
const openCode = await detectOpenCodeVersion(this.opencodeBin);
|
|
30559
|
+
const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
|
|
30155
30560
|
if (this.stopped) break;
|
|
30156
30561
|
let task;
|
|
30157
30562
|
try {
|
|
@@ -30185,7 +30590,7 @@ var WorkerEngine = class {
|
|
|
30185
30590
|
workerPid: process.pid,
|
|
30186
30591
|
lockedAt: Date.now(),
|
|
30187
30592
|
lockedBy: launchIdentity,
|
|
30188
|
-
launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
30593
|
+
launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
30189
30594
|
});
|
|
30190
30595
|
runId = run.id;
|
|
30191
30596
|
if (this.stopped) {
|
|
@@ -30214,6 +30619,10 @@ var WorkerEngine = class {
|
|
|
30214
30619
|
this.releaseBatch(task);
|
|
30215
30620
|
continue;
|
|
30216
30621
|
}
|
|
30622
|
+
if (this.runner) {
|
|
30623
|
+
this.executeViaRunner(task, run.id, launchIdentity, this.runner);
|
|
30624
|
+
continue;
|
|
30625
|
+
}
|
|
30217
30626
|
let args;
|
|
30218
30627
|
try {
|
|
30219
30628
|
args = buildOpenCodeRunArgs(openCode.major, {
|
|
@@ -30272,6 +30681,96 @@ var WorkerEngine = class {
|
|
|
30272
30681
|
if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
|
|
30273
30682
|
return entry;
|
|
30274
30683
|
}
|
|
30684
|
+
executeViaRunner(task, runId, launchIdentity, runner) {
|
|
30685
|
+
const cwd = task.cwd || process.cwd();
|
|
30686
|
+
const abortController = new AbortController();
|
|
30687
|
+
const model = this.resolveModel(task.model);
|
|
30688
|
+
const variant = this.resolveVariant(task.variant);
|
|
30689
|
+
const entry = {
|
|
30690
|
+
task,
|
|
30691
|
+
runId,
|
|
30692
|
+
sessionId: null,
|
|
30693
|
+
launchIdentity,
|
|
30694
|
+
child: null,
|
|
30695
|
+
runnerAbort: abortController,
|
|
30696
|
+
commandContext: runCommandContext(`runner:${runner.name}`, [task.agent], cwd),
|
|
30697
|
+
output: new RunOutput(
|
|
30698
|
+
this.maxOutputChars,
|
|
30699
|
+
(sessionId) => {
|
|
30700
|
+
entry.sessionId = sessionId;
|
|
30701
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
30702
|
+
this.logError("sessionId update failed", err, task.id);
|
|
30703
|
+
});
|
|
30704
|
+
},
|
|
30705
|
+
(stream, line) => {
|
|
30706
|
+
gatewayEvents.emitRunLog(runId, task.id, stream, line);
|
|
30707
|
+
}
|
|
30708
|
+
),
|
|
30709
|
+
timeoutTimer: null,
|
|
30710
|
+
termination: null,
|
|
30711
|
+
terminationPromise: null,
|
|
30712
|
+
settlementPromise: null,
|
|
30713
|
+
guardianDrained: true,
|
|
30714
|
+
quarantined: false,
|
|
30715
|
+
settled: false
|
|
30716
|
+
};
|
|
30717
|
+
this.runningTasks.set(task.id, entry);
|
|
30718
|
+
gatewayEvents.emitRunStarted({
|
|
30719
|
+
runId,
|
|
30720
|
+
taskId: task.id,
|
|
30721
|
+
cwd: task.cwd,
|
|
30722
|
+
model,
|
|
30723
|
+
variant
|
|
30724
|
+
});
|
|
30725
|
+
const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
|
|
30726
|
+
if (timeoutMs > 0) {
|
|
30727
|
+
entry.timeoutTimer = setTimeout(() => {
|
|
30728
|
+
this.runDetached(
|
|
30729
|
+
this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
|
|
30730
|
+
"runner timeout termination failed",
|
|
30731
|
+
entry.task.id
|
|
30732
|
+
);
|
|
30733
|
+
}, timeoutMs);
|
|
30734
|
+
entry.timeoutTimer.unref?.();
|
|
30735
|
+
}
|
|
30736
|
+
const runnerPromise = runner.execute({
|
|
30737
|
+
task,
|
|
30738
|
+
runId,
|
|
30739
|
+
cwd,
|
|
30740
|
+
agent: task.agent,
|
|
30741
|
+
model,
|
|
30742
|
+
variant,
|
|
30743
|
+
prompt: task.prompt,
|
|
30744
|
+
title: task.name,
|
|
30745
|
+
metadata: parseTaskMetadata(task.metadata),
|
|
30746
|
+
signal: abortController.signal,
|
|
30747
|
+
onSessionId: (sessionId) => {
|
|
30748
|
+
entry.sessionId = sessionId;
|
|
30749
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
30750
|
+
this.logError("sessionId update failed", err, task.id);
|
|
30751
|
+
});
|
|
30752
|
+
},
|
|
30753
|
+
onOutputChunk: (chunk) => {
|
|
30754
|
+
entry.output.push("stdout", chunk);
|
|
30755
|
+
}
|
|
30756
|
+
}).then((result) => {
|
|
30757
|
+
if (entry.settled || entry.termination) return;
|
|
30758
|
+
this.runDetached(
|
|
30759
|
+
this.settleEntry(entry, result.ok ? 0 : 1, result.ok ? void 0 : result.errorMessage || "Runner \u6267\u884C\u5931\u8D25"),
|
|
30760
|
+
"runner settlement failed",
|
|
30761
|
+
entry.task.id
|
|
30762
|
+
);
|
|
30763
|
+
}).catch((error) => {
|
|
30764
|
+
if (entry.settled || entry.termination) return;
|
|
30765
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
30766
|
+
this.runDetached(
|
|
30767
|
+
this.settleEntry(entry, 1, `Runner \u6267\u884C\u5F02\u5E38\uFF1A${msg}`),
|
|
30768
|
+
"runner error settlement failed",
|
|
30769
|
+
entry.task.id
|
|
30770
|
+
);
|
|
30771
|
+
});
|
|
30772
|
+
entry.runnerDone = runnerPromise;
|
|
30773
|
+
}
|
|
30275
30774
|
async spawnTask(task, runId, launchIdentity, args) {
|
|
30276
30775
|
const cwd = task.cwd || process.cwd();
|
|
30277
30776
|
const childEnv = {
|
|
@@ -30438,7 +30937,7 @@ var WorkerEngine = class {
|
|
|
30438
30937
|
handleChildClose(entry, code, signal, spawnError) {
|
|
30439
30938
|
if (entry.settled || entry.termination) return;
|
|
30440
30939
|
if (!entry.guardianDrained) {
|
|
30441
|
-
const pid2 = entry.child
|
|
30940
|
+
const pid2 = entry.child?.pid;
|
|
30442
30941
|
const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
|
|
30443
30942
|
const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
|
|
30444
30943
|
if (presence !== "not-running") {
|
|
@@ -30461,7 +30960,7 @@ var WorkerEngine = class {
|
|
|
30461
30960
|
);
|
|
30462
30961
|
return;
|
|
30463
30962
|
}
|
|
30464
|
-
const pid = entry.child
|
|
30963
|
+
const pid = entry.child?.pid;
|
|
30465
30964
|
if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
|
|
30466
30965
|
if (entry.timeoutTimer) {
|
|
30467
30966
|
clearTimeout(entry.timeoutTimer);
|
|
@@ -30731,6 +31230,17 @@ ${output}` : ""}` : output;
|
|
|
30731
31230
|
}
|
|
30732
31231
|
}
|
|
30733
31232
|
async killEntry(entry, initialSignal = "SIGTERM") {
|
|
31233
|
+
if (entry.runnerAbort) {
|
|
31234
|
+
entry.runnerAbort.abort();
|
|
31235
|
+
if (entry.runnerDone) {
|
|
31236
|
+
await Promise.race([
|
|
31237
|
+
entry.runnerDone.catch(() => void 0),
|
|
31238
|
+
new Promise((resolve4) => setTimeout(resolve4, 5e3))
|
|
31239
|
+
]);
|
|
31240
|
+
}
|
|
31241
|
+
return true;
|
|
31242
|
+
}
|
|
31243
|
+
if (!entry.child) return true;
|
|
30734
31244
|
const pid = entry.child.pid;
|
|
30735
31245
|
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
|
|
30736
31246
|
if (!pid) return false;
|
|
@@ -30746,7 +31256,7 @@ ${output}` : ""}` : output;
|
|
|
30746
31256
|
return waitForSpawnedProcessTreeExit(pid, 2500);
|
|
30747
31257
|
}
|
|
30748
31258
|
signalEntry(entry, signal) {
|
|
30749
|
-
const pid = entry.child
|
|
31259
|
+
const pid = entry.child?.pid;
|
|
30750
31260
|
if (!pid) return "not-running";
|
|
30751
31261
|
return signalRecordedProcessTreeWithResult(
|
|
30752
31262
|
pid,
|
|
@@ -30812,7 +31322,7 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
|
|
|
30812
31322
|
if (shouldStop()) break;
|
|
30813
31323
|
if (isOwnedRun(run.taskId, run.runId)) continue;
|
|
30814
31324
|
try {
|
|
30815
|
-
if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
31325
|
+
if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== HTTP_RUNNER_LAUNCH_PROTOCOL) {
|
|
30816
31326
|
console.warn(JSON.stringify({
|
|
30817
31327
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
30818
31328
|
level: "warn",
|
|
@@ -30825,6 +31335,20 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
|
|
|
30825
31335
|
result.quarantinedRuns += 1;
|
|
30826
31336
|
continue;
|
|
30827
31337
|
}
|
|
31338
|
+
if (run.launchProtocol === HTTP_RUNNER_LAUNCH_PROTOCOL) {
|
|
31339
|
+
if (run.ownerAlive) {
|
|
31340
|
+
console.warn(JSON.stringify({
|
|
31341
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
31342
|
+
level: "warn",
|
|
31343
|
+
msg: "stale http runner run still has live owner pid; run remains quarantined",
|
|
31344
|
+
taskId: run.taskId,
|
|
31345
|
+
runId: run.runId,
|
|
31346
|
+
workerPid: run.workerPid
|
|
31347
|
+
}));
|
|
31348
|
+
result.quarantinedRuns += 1;
|
|
31349
|
+
continue;
|
|
31350
|
+
}
|
|
31351
|
+
}
|
|
30828
31352
|
if (run.childPid != null && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
30829
31353
|
if (run.childPid > 0 && !isProcessAlive(run.childPid) && inspectSpawnedProcessTreePresence(run.childPid) === "not-running") {
|
|
30830
31354
|
} else {
|