opencode-supertask 0.2.1 → 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 +34 -0
- package/README.md +10 -0
- package/README.zh-CN.md +10 -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-J34FWHQU.js → chunk-ETLJ4YXW.js} +3 -2
- package/dist/cli/chunk-ETLJ4YXW.js.map +1 -0
- package/dist/cli/{chunk-AZM76ISG.js → chunk-INW2NH3O.js} +6 -5
- package/dist/cli/chunk-INW2NH3O.js.map +1 -0
- package/dist/cli/{chunk-CMEP6IB4.js → chunk-K6UTYKN5.js} +19 -5
- package/dist/cli/{chunk-CMEP6IB4.js.map → chunk-K6UTYKN5.js.map} +1 -1
- package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
- package/dist/cli/{chunk-DF56RPNL.js → chunk-MZLIVCEU.js} +10 -2
- package/dist/cli/{chunk-DF56RPNL.js.map → chunk-MZLIVCEU.js.map} +1 -1
- package/dist/cli/{chunk-5VKFECHP.js → chunk-OJLDJVHB.js} +3 -3
- package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
- package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
- package/dist/cli/{chunk-EQWICVCJ.js → chunk-XUCZLWCB.js} +48 -6
- package/dist/cli/chunk-XUCZLWCB.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-DIJEKFBV.js → chunk-YADLWDYK.js} +4 -4
- package/dist/cli/{chunk-YGELD2E5.js → chunk-ZIR7RA5B.js} +7 -4
- package/dist/cli/{chunk-YGELD2E5.js.map → chunk-ZIR7RA5B.js.map} +1 -1
- package/dist/cli/database-maintenance.service-NQBZ5VJT.js +16 -0
- package/dist/cli/{db-H7GIFWS2.js → db-KWSXP22E.js} +2 -2
- package/dist/cli/{doctor-smoke-QXHF7UNN.js → doctor-smoke-6VU2KCRK.js} +7 -7
- package/dist/cli/{gateway-BYLLK72W.js → gateway-I2SQOXWB.js} +686 -24
- package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
- package/dist/cli/{gateway-wake-U4HTV56Q.js → gateway-wake-M5EXAIGD.js} +2 -2
- package/dist/cli/index.js +38 -38
- package/dist/cli/{job-templates-RPQJ4XXW.js → job-templates-FH7SGS34.js} +5 -5
- package/dist/cli/{logs-QD2N62KK.js → logs-HB5RV7HD.js} +7 -7
- package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
- package/dist/cli/task-run.service-R45W2VID.js +15 -0
- package/dist/cli/task-template.service-VA4WBJA4.js +12 -0
- package/dist/cli/{task.service-ZVDJ6VSQ.js → task.service-RB6RKV7T.js} +3 -3
- package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
- package/dist/cli/{web-J3FJ23FE.js → web-4QWJ4Z5K.js} +157 -17
- package/dist/cli/{web-J3FJ23FE.js.map → web-4QWJ4Z5K.js.map} +1 -1
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
- package/dist/gateway/index.d.ts +1 -0
- package/dist/gateway/index.js +929 -31
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.js +106 -11
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/web/index.js +235 -16
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +492 -1
- package/dist/worker/index.js +728 -20
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.js.map +1 -1
- package/drizzle/0010_task_metadata.sql +2 -0
- package/drizzle/meta/0010_snapshot.json +695 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +1 -1
- package/dist/cli/chunk-AZM76ISG.js.map +0 -1
- package/dist/cli/chunk-EQWICVCJ.js.map +0 -1
- package/dist/cli/chunk-J34FWHQU.js.map +0 -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/database-maintenance.service-F3IZU52F.js +0 -16
- package/dist/cli/gateway-BYLLK72W.js.map +0 -1
- package/dist/cli/task-run.service-QMDINJKG.js +0 -15
- package/dist/cli/task-template.service-SZBKGLCB.js +0 -12
- /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
- /package/dist/cli/{chunk-5VKFECHP.js.map → chunk-OJLDJVHB.js.map} +0 -0
- /package/dist/cli/{chunk-DIJEKFBV.js.map → chunk-YADLWDYK.js.map} +0 -0
- /package/dist/cli/{database-maintenance.service-F3IZU52F.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
- /package/dist/cli/{db-H7GIFWS2.js.map → db-KWSXP22E.js.map} +0 -0
- /package/dist/cli/{doctor-smoke-QXHF7UNN.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
- /package/dist/cli/{gateway-wake-U4HTV56Q.js.map → gateway-wake-M5EXAIGD.js.map} +0 -0
- /package/dist/cli/{job-templates-RPQJ4XXW.js.map → job-templates-FH7SGS34.js.map} +0 -0
- /package/dist/cli/{logs-QD2N62KK.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-QMDINJKG.js.map → task-run.service-R45W2VID.js.map} +0 -0
- /package/dist/cli/{task-template.service-SZBKGLCB.js.map → task-template.service-VA4WBJA4.js.map} +0 -0
- /package/dist/cli/{task.service-ZVDJ6VSQ.js.map → task.service-RB6RKV7T.js.map} +0 -0
- /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
|
@@ -7,33 +7,34 @@ import {
|
|
|
7
7
|
markGatewayFailure,
|
|
8
8
|
markGatewaySuccess,
|
|
9
9
|
resetGatewayHealth
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-ETLJ4YXW.js";
|
|
11
11
|
import {
|
|
12
12
|
OpenCodeInvocationError,
|
|
13
13
|
buildOpenCodeRunArgs,
|
|
14
14
|
detectOpenCodeVersion,
|
|
15
15
|
openCodeExecutable
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-WHGCKWMR.js";
|
|
17
17
|
import {
|
|
18
18
|
TaskRunService
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-OJLDJVHB.js";
|
|
20
20
|
import {
|
|
21
21
|
DUE_TEMPLATE_BATCH_SIZE,
|
|
22
22
|
cloneTaskFromTemplate,
|
|
23
23
|
getDueTemplates,
|
|
24
24
|
initializeNextRunAt
|
|
25
|
-
} from "./chunk-
|
|
25
|
+
} from "./chunk-INW2NH3O.js";
|
|
26
26
|
import {
|
|
27
27
|
TaskTemplateService
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-K6UTYKN5.js";
|
|
29
29
|
import {
|
|
30
30
|
identifyGatewayProcess,
|
|
31
31
|
inspectSpawnedProcessTreePresence,
|
|
32
32
|
isProcessAlive,
|
|
33
33
|
signalRecordedProcessTreeWithResult,
|
|
34
34
|
waitForSpawnedProcessTreeExit
|
|
35
|
-
} from "./chunk-
|
|
35
|
+
} from "./chunk-KC34M3F3.js";
|
|
36
36
|
import {
|
|
37
|
+
HTTP_RUNNER_LAUNCH_PROTOCOL,
|
|
37
38
|
LAUNCH_IDENTITY_ARGUMENT,
|
|
38
39
|
LEGACY_GUARDIAN_LAUNCH_PROTOCOL,
|
|
39
40
|
MANAGED_RUN_ENV,
|
|
@@ -41,12 +42,13 @@ import {
|
|
|
41
42
|
TOKEN_GUARDIAN_LAUNCH_PROTOCOL,
|
|
42
43
|
drainProofAckForIdentity,
|
|
43
44
|
isMatchingDrainProof
|
|
44
|
-
} from "./chunk-
|
|
45
|
+
} from "./chunk-XWTKMNNI.js";
|
|
45
46
|
import {
|
|
46
47
|
TaskService,
|
|
47
48
|
normalizeTaskBatchId,
|
|
49
|
+
parseTaskMetadata,
|
|
48
50
|
validateTaskWorkingDirectory
|
|
49
|
-
} from "./chunk-
|
|
51
|
+
} from "./chunk-XUCZLWCB.js";
|
|
50
52
|
import {
|
|
51
53
|
and,
|
|
52
54
|
asc,
|
|
@@ -57,7 +59,7 @@ import {
|
|
|
57
59
|
isNull,
|
|
58
60
|
schema_exports,
|
|
59
61
|
sqlite
|
|
60
|
-
} from "./chunk-
|
|
62
|
+
} from "./chunk-ZIR7RA5B.js";
|
|
61
63
|
import {
|
|
62
64
|
getPackageVersion
|
|
63
65
|
} from "./chunk-DYXFSX5J.js";
|
|
@@ -68,6 +70,506 @@ import "./chunk-3PIYMBV3.js";
|
|
|
68
70
|
|
|
69
71
|
// src/worker/index.ts
|
|
70
72
|
import { spawn } from "child_process";
|
|
73
|
+
|
|
74
|
+
// src/gateway/webhook.ts
|
|
75
|
+
import { createHmac } from "crypto";
|
|
76
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
77
|
+
var DEFAULT_MAX_ATTEMPTS = 2;
|
|
78
|
+
var MAX_SUMMARY_CHARS = 2e3;
|
|
79
|
+
var pendingWebhooks = /* @__PURE__ */ new Set();
|
|
80
|
+
function signWebhookPayload(secret, timestamp, body) {
|
|
81
|
+
const digest = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
82
|
+
return `sha256=${digest}`;
|
|
83
|
+
}
|
|
84
|
+
function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
|
|
85
|
+
if (!rawLog) return "";
|
|
86
|
+
const texts = [];
|
|
87
|
+
let framed = false;
|
|
88
|
+
for (const line of rawLog.split("\n")) {
|
|
89
|
+
const trimmed = line.trim();
|
|
90
|
+
if (!trimmed) continue;
|
|
91
|
+
try {
|
|
92
|
+
const event = JSON.parse(trimmed);
|
|
93
|
+
if (event.type) framed = true;
|
|
94
|
+
if (event.type === "text" && typeof event.part?.text === "string" && event.part.text.trim()) {
|
|
95
|
+
texts.push(event.part.text.trim());
|
|
96
|
+
} else if (event.type === "error") {
|
|
97
|
+
const msg = event.error?.data?.message || event.error?.message;
|
|
98
|
+
if (typeof msg === "string" && msg.trim()) texts.push(msg.trim());
|
|
99
|
+
} else if (event.type === "tool_use" && event.part?.state?.status === "error" && typeof event.part.state.error === "string" && event.part.state.error.trim()) {
|
|
100
|
+
texts.push(event.part.state.error.trim());
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
if (!framed) texts.push(trimmed);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const combined = texts.join("\n").trim();
|
|
107
|
+
if (combined.length <= maxChars) return combined;
|
|
108
|
+
return `${combined.slice(0, Math.max(0, maxChars - 1))}\u2026`;
|
|
109
|
+
}
|
|
110
|
+
function toMs(value) {
|
|
111
|
+
if (value == null) return null;
|
|
112
|
+
if (value instanceof Date) return value.getTime();
|
|
113
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
function buildTaskWebhookPayload(event, task, run, outputOverride) {
|
|
117
|
+
const startedAt = toMs(task.startedAt);
|
|
118
|
+
const finishedAt = toMs(task.finishedAt) ?? Date.now();
|
|
119
|
+
const durationMs = startedAt != null && finishedAt > startedAt ? finishedAt - startedAt : 0;
|
|
120
|
+
return {
|
|
121
|
+
event,
|
|
122
|
+
timestamp: Date.now(),
|
|
123
|
+
task: {
|
|
124
|
+
id: task.id,
|
|
125
|
+
name: task.name,
|
|
126
|
+
agent: task.agent,
|
|
127
|
+
model: task.model ?? null,
|
|
128
|
+
variant: task.variant ?? null,
|
|
129
|
+
cwd: task.cwd ?? null,
|
|
130
|
+
templateId: task.templateId ?? null,
|
|
131
|
+
status: task.status ?? event.slice("task.".length),
|
|
132
|
+
metadata: parseTaskMetadata(task.metadata),
|
|
133
|
+
startedAt,
|
|
134
|
+
finishedAt,
|
|
135
|
+
durationMs
|
|
136
|
+
},
|
|
137
|
+
run,
|
|
138
|
+
outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
function dispatchTaskWebhook(payload, options = {}) {
|
|
142
|
+
const task = deliverTaskWebhook(payload, options);
|
|
143
|
+
pendingWebhooks.add(task);
|
|
144
|
+
void task.finally(() => {
|
|
145
|
+
pendingWebhooks.delete(task);
|
|
146
|
+
});
|
|
147
|
+
return task;
|
|
148
|
+
}
|
|
149
|
+
async function deliverTaskWebhook(payload, options = {}) {
|
|
150
|
+
const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
|
|
151
|
+
if (!url) return false;
|
|
152
|
+
try {
|
|
153
|
+
const parsed = new URL(url);
|
|
154
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
|
155
|
+
} catch {
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
const secret = (options.secret ?? process.env.SUPERTASK_WEBHOOK_SECRET ?? "").trim();
|
|
159
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
160
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
|
|
161
|
+
const fetchFn = options.fetchImpl ?? fetch;
|
|
162
|
+
const body = JSON.stringify(payload);
|
|
163
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
164
|
+
const ts = Date.now();
|
|
165
|
+
const headers = {
|
|
166
|
+
"content-type": "application/json",
|
|
167
|
+
"x-supertask-event": payload.event,
|
|
168
|
+
"x-supertask-timestamp": String(ts)
|
|
169
|
+
};
|
|
170
|
+
if (secret) {
|
|
171
|
+
headers["x-supertask-signature"] = signWebhookPayload(secret, ts, body);
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
const resp = await fetchFn(url, {
|
|
175
|
+
method: "POST",
|
|
176
|
+
headers,
|
|
177
|
+
body,
|
|
178
|
+
redirect: "error",
|
|
179
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
180
|
+
});
|
|
181
|
+
if (resp.ok) return true;
|
|
182
|
+
if (resp.status >= 400 && resp.status < 500 && resp.status !== 429) {
|
|
183
|
+
console.warn(JSON.stringify({
|
|
184
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
185
|
+
level: "warn",
|
|
186
|
+
msg: "task webhook rejected",
|
|
187
|
+
event: payload.event,
|
|
188
|
+
taskId: payload.task.id,
|
|
189
|
+
status: resp.status
|
|
190
|
+
}));
|
|
191
|
+
return false;
|
|
192
|
+
}
|
|
193
|
+
if (attempt >= maxAttempts) {
|
|
194
|
+
console.warn(JSON.stringify({
|
|
195
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
196
|
+
level: "warn",
|
|
197
|
+
msg: "task webhook delivery exhausted",
|
|
198
|
+
event: payload.event,
|
|
199
|
+
taskId: payload.task.id,
|
|
200
|
+
status: resp.status,
|
|
201
|
+
attempts: maxAttempts
|
|
202
|
+
}));
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
} catch (err) {
|
|
206
|
+
if (attempt >= maxAttempts) {
|
|
207
|
+
console.warn(JSON.stringify({
|
|
208
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
209
|
+
level: "warn",
|
|
210
|
+
msg: "task webhook delivery failed",
|
|
211
|
+
event: payload.event,
|
|
212
|
+
taskId: payload.task.id,
|
|
213
|
+
error: err instanceof Error ? err.message : String(err)
|
|
214
|
+
}));
|
|
215
|
+
return false;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (attempt < maxAttempts) {
|
|
219
|
+
await new Promise((resolve) => setTimeout(resolve, 300 * attempt));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// src/worker/runners/opencode-server.ts
|
|
226
|
+
var MAX_SSE_BUFFER_CHARS = 2 * 1024 * 1024;
|
|
227
|
+
function isLoopbackHost(hostname) {
|
|
228
|
+
const h = hostname.toLowerCase();
|
|
229
|
+
return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
|
|
230
|
+
}
|
|
231
|
+
function sanitizeErrorDetail(raw, maxLen = 240) {
|
|
232
|
+
if (!raw) return "";
|
|
233
|
+
return raw.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);
|
|
234
|
+
}
|
|
235
|
+
function parseModelSpec(rawModel, explicitVariant) {
|
|
236
|
+
if (!rawModel || rawModel === "default") return null;
|
|
237
|
+
let modelStr = rawModel.trim();
|
|
238
|
+
let variant = explicitVariant?.trim() || void 0;
|
|
239
|
+
const hashIdx = modelStr.indexOf("#");
|
|
240
|
+
if (hashIdx > 0) {
|
|
241
|
+
const embedded = modelStr.slice(hashIdx + 1).trim();
|
|
242
|
+
modelStr = modelStr.slice(0, hashIdx).trim();
|
|
243
|
+
if (!variant && embedded) variant = embedded;
|
|
244
|
+
}
|
|
245
|
+
const slashIdx = modelStr.indexOf("/");
|
|
246
|
+
if (slashIdx <= 0 || slashIdx === modelStr.length - 1) return null;
|
|
247
|
+
return {
|
|
248
|
+
providerID: modelStr.slice(0, slashIdx),
|
|
249
|
+
id: modelStr.slice(slashIdx + 1),
|
|
250
|
+
...variant ? { variant } : {}
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
var OpenCodeServerRunner = class {
|
|
254
|
+
name = "opencode-server";
|
|
255
|
+
baseUrl;
|
|
256
|
+
password;
|
|
257
|
+
defaultModel;
|
|
258
|
+
allowInsecureHttp;
|
|
259
|
+
fetchFn;
|
|
260
|
+
constructor(options = {}) {
|
|
261
|
+
const rawUrl = (options.baseUrl ?? process.env.OPENCODE_URL ?? "").trim();
|
|
262
|
+
this.baseUrl = rawUrl.replace(/\/+$/, "");
|
|
263
|
+
this.password = (options.password ?? process.env.OPENCODE_PASSWORD ?? "").trim();
|
|
264
|
+
this.defaultModel = (options.defaultModel ?? process.env.SUPERTASK_DEFAULT_MODEL ?? process.env.DEFAULT_MODEL ?? "").trim();
|
|
265
|
+
this.allowInsecureHttp = options.allowInsecureHttp ?? process.env.SUPERTASK_ALLOW_INSECURE_HTTP === "1";
|
|
266
|
+
this.fetchFn = options.fetchImpl ?? fetch;
|
|
267
|
+
}
|
|
268
|
+
authHeaders(extra = {}) {
|
|
269
|
+
const headers = { ...extra };
|
|
270
|
+
if (this.password) {
|
|
271
|
+
headers.authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
|
|
272
|
+
}
|
|
273
|
+
return headers;
|
|
274
|
+
}
|
|
275
|
+
async interruptSession(sessionId) {
|
|
276
|
+
try {
|
|
277
|
+
const resp = await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
|
|
278
|
+
method: "POST",
|
|
279
|
+
headers: this.authHeaders(),
|
|
280
|
+
signal: AbortSignal.timeout(3e3)
|
|
281
|
+
});
|
|
282
|
+
return resp.ok;
|
|
283
|
+
} catch {
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
async execute(ctx) {
|
|
288
|
+
if (!this.baseUrl) {
|
|
289
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_URL \u914D\u7F6E" };
|
|
290
|
+
}
|
|
291
|
+
if (!this.password) {
|
|
292
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_PASSWORD \u914D\u7F6E" };
|
|
293
|
+
}
|
|
294
|
+
let parsedBaseUrl;
|
|
295
|
+
try {
|
|
296
|
+
parsedBaseUrl = new URL(this.baseUrl);
|
|
297
|
+
} catch {
|
|
298
|
+
return { ok: false, sessionId: null, errorMessage: "OPENCODE_URL \u4E0D\u662F\u6709\u6548\u7684 HTTP(S) \u5730\u5740" };
|
|
299
|
+
}
|
|
300
|
+
if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && (isLoopbackHost(parsedBaseUrl.hostname) || this.allowInsecureHttp))) {
|
|
301
|
+
return {
|
|
302
|
+
ok: false,
|
|
303
|
+
sessionId: null,
|
|
304
|
+
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"
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
const explicitModel = ctx.model && ctx.model !== "default" ? ctx.model.trim() : null;
|
|
308
|
+
const explicitVariant = ctx.variant && ctx.variant !== "default" ? ctx.variant.trim() : null;
|
|
309
|
+
if (explicitModel && !parseModelSpec(explicitModel, explicitVariant)) {
|
|
310
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6548\u7684\u6A21\u578B\u683C\u5F0F\uFF08\u9700\u8981 provider/model\uFF09\uFF1A${explicitModel}` };
|
|
311
|
+
}
|
|
312
|
+
let sessionId = null;
|
|
313
|
+
let interruptedRemote = false;
|
|
314
|
+
const ensureInterrupt = async (targetIds) => {
|
|
315
|
+
if (interruptedRemote && !targetIds) return;
|
|
316
|
+
const ids = /* @__PURE__ */ new Set();
|
|
317
|
+
if (targetIds) {
|
|
318
|
+
for (const id of targetIds) if (id) ids.add(id);
|
|
319
|
+
}
|
|
320
|
+
if (sessionId) ids.add(sessionId);
|
|
321
|
+
if (ids.size === 0) return;
|
|
322
|
+
interruptedRemote = true;
|
|
323
|
+
await Promise.all([...ids].map((id) => this.interruptSession(id)));
|
|
324
|
+
};
|
|
325
|
+
const sseController = new AbortController();
|
|
326
|
+
const onOuterAbort = () => {
|
|
327
|
+
sseController.abort();
|
|
328
|
+
};
|
|
329
|
+
if (ctx.signal.aborted) {
|
|
330
|
+
return { ok: false, sessionId: null, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
331
|
+
}
|
|
332
|
+
ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
333
|
+
try {
|
|
334
|
+
const agentUrl = new URL(`${this.baseUrl}/api/agent`);
|
|
335
|
+
agentUrl.searchParams.set("location[directory]", ctx.cwd);
|
|
336
|
+
let agentDef;
|
|
337
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
338
|
+
const agentResp = await this.fetchFn(agentUrl.toString(), {
|
|
339
|
+
headers: this.authHeaders(),
|
|
340
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
341
|
+
});
|
|
342
|
+
if (!agentResp.ok) {
|
|
343
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6CD5\u8BFB\u53D6 OpenCode Agent \u6E05\u5355\uFF1AHTTP ${agentResp.status}` };
|
|
344
|
+
}
|
|
345
|
+
const payload = await agentResp.json();
|
|
346
|
+
agentDef = Array.isArray(payload.data) ? payload.data.find((a) => a.id === ctx.agent) : void 0;
|
|
347
|
+
if (agentDef) break;
|
|
348
|
+
if (attempt < 3) await new Promise((r) => setTimeout(r, 250));
|
|
349
|
+
}
|
|
350
|
+
if (!agentDef || agentDef.hidden || agentDef.disabled || agentDef.mode === "subagent") {
|
|
351
|
+
return { ok: false, sessionId: null, errorMessage: `\u4EFB\u52A1\u7684 Agent \u5DF2\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\uFF08${ctx.agent}\uFF09` };
|
|
352
|
+
}
|
|
353
|
+
const createResp = await this.fetchFn(`${this.baseUrl}/api/session`, {
|
|
354
|
+
method: "POST",
|
|
355
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
356
|
+
body: JSON.stringify({
|
|
357
|
+
agent: ctx.agent,
|
|
358
|
+
location: { directory: ctx.cwd },
|
|
359
|
+
metadata: {
|
|
360
|
+
...ctx.metadata ?? {},
|
|
361
|
+
supertaskTaskId: ctx.task.id,
|
|
362
|
+
supertaskRunId: ctx.runId
|
|
363
|
+
}
|
|
364
|
+
}),
|
|
365
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
366
|
+
});
|
|
367
|
+
if (!createResp.ok) {
|
|
368
|
+
return { ok: false, sessionId: null, errorMessage: `\u521B\u5EFA OpenCode \u4F1A\u8BDD\u5931\u8D25\uFF1AHTTP ${createResp.status}` };
|
|
369
|
+
}
|
|
370
|
+
const created = await createResp.json();
|
|
371
|
+
sessionId = created.data?.id ?? created.id ?? null;
|
|
372
|
+
if (!sessionId) {
|
|
373
|
+
return { ok: false, sessionId: null, errorMessage: "OpenCode \u672A\u8FD4\u56DE\u6709\u6548\u7684\u4F1A\u8BDD ID" };
|
|
374
|
+
}
|
|
375
|
+
ctx.onSessionId(sessionId);
|
|
376
|
+
const cleanTitle = ctx.title.replace(/\s+/g, " ").trim().slice(0, 200);
|
|
377
|
+
if (cleanTitle) {
|
|
378
|
+
await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}`, {
|
|
379
|
+
method: "PATCH",
|
|
380
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
381
|
+
body: JSON.stringify({ title: cleanTitle }),
|
|
382
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
383
|
+
}).catch(() => void 0);
|
|
384
|
+
}
|
|
385
|
+
let modelSpec = explicitModel ? parseModelSpec(explicitModel, explicitVariant) : null;
|
|
386
|
+
if (!modelSpec && agentDef.model?.providerID && agentDef.model?.id) {
|
|
387
|
+
const resolvedVariant = explicitVariant ?? (agentDef.model.variant && agentDef.model.variant !== "default" ? agentDef.model.variant : void 0);
|
|
388
|
+
modelSpec = {
|
|
389
|
+
providerID: agentDef.model.providerID,
|
|
390
|
+
id: agentDef.model.id,
|
|
391
|
+
...resolvedVariant ? { variant: resolvedVariant } : {}
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
if (!modelSpec && this.defaultModel) {
|
|
395
|
+
modelSpec = parseModelSpec(this.defaultModel, explicitVariant);
|
|
396
|
+
}
|
|
397
|
+
if (explicitVariant && !modelSpec) {
|
|
398
|
+
return { ok: false, sessionId, errorMessage: "\u6307\u5B9A\u4E86 variant \u4F46\u672A\u914D\u7F6E\u53EF\u7528\u6A21\u578B" };
|
|
399
|
+
}
|
|
400
|
+
if (modelSpec) {
|
|
401
|
+
const switchResp = await this.fetchFn(
|
|
402
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/model`,
|
|
403
|
+
{
|
|
404
|
+
method: "POST",
|
|
405
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
406
|
+
body: JSON.stringify({ model: modelSpec }),
|
|
407
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
408
|
+
}
|
|
409
|
+
);
|
|
410
|
+
if (!switchResp.ok) {
|
|
411
|
+
return { ok: false, sessionId, errorMessage: `\u5207\u6362 OpenCode \u6A21\u578B\u5931\u8D25\uFF1AHTTP ${switchResp.status}` };
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const sseResp = await this.fetchFn(`${this.baseUrl}/api/event`, {
|
|
415
|
+
headers: this.authHeaders({ accept: "text/event-stream" }),
|
|
416
|
+
signal: sseController.signal
|
|
417
|
+
});
|
|
418
|
+
const contentType = sseResp.headers.get("content-type") || "";
|
|
419
|
+
if (!sseResp.ok || !sseResp.body || !contentType.toLowerCase().includes("text/event-stream")) {
|
|
420
|
+
sseController.abort();
|
|
421
|
+
return {
|
|
422
|
+
ok: false,
|
|
423
|
+
sessionId,
|
|
424
|
+
errorMessage: `\u65E0\u6CD5\u8BA2\u9605 OpenCode \u4E8B\u4EF6\u6D41\uFF1AHTTP ${sseResp.status}${contentType ? ` (${contentType})` : ""}`
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
const promptResp = await this.fetchFn(
|
|
428
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/prompt`,
|
|
429
|
+
{
|
|
430
|
+
method: "POST",
|
|
431
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
432
|
+
body: JSON.stringify({ text: ctx.prompt }),
|
|
433
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(15e3)])
|
|
434
|
+
}
|
|
435
|
+
);
|
|
436
|
+
if (!promptResp.ok) {
|
|
437
|
+
sseController.abort();
|
|
438
|
+
const detail = sanitizeErrorDetail(await promptResp.text().catch(() => ""));
|
|
439
|
+
return {
|
|
440
|
+
ok: false,
|
|
441
|
+
sessionId,
|
|
442
|
+
errorMessage: `OpenCode \u63D0\u4EA4\u4EFB\u52A1\u5931\u8D25\uFF1AHTTP ${promptResp.status}${detail ? ` ${detail}` : ""}`
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
const trackedSessionIds = /* @__PURE__ */ new Set([sessionId]);
|
|
446
|
+
const reader = sseResp.body.getReader();
|
|
447
|
+
const decoder = new TextDecoder();
|
|
448
|
+
let buffer = "";
|
|
449
|
+
let pendingText = "";
|
|
450
|
+
const flushText = () => {
|
|
451
|
+
if (!pendingText) return;
|
|
452
|
+
ctx.onOutputChunk(`${JSON.stringify({ type: "text", sessionID: sessionId, part: { text: pendingText } })}
|
|
453
|
+
`);
|
|
454
|
+
pendingText = "";
|
|
455
|
+
};
|
|
456
|
+
const processEventPayload = async (rawData) => {
|
|
457
|
+
let evt;
|
|
458
|
+
try {
|
|
459
|
+
evt = JSON.parse(rawData);
|
|
460
|
+
} catch {
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
const evtType = evt.type || "";
|
|
464
|
+
if (evtType === "session.created") {
|
|
465
|
+
const childId = evt.data?.id ?? evt.data?.session?.id ?? "";
|
|
466
|
+
const parentId = evt.data?.parentID ?? evt.data?.session?.parentID ?? "";
|
|
467
|
+
if (childId && parentId && trackedSessionIds.has(parentId)) {
|
|
468
|
+
trackedSessionIds.add(childId);
|
|
469
|
+
}
|
|
470
|
+
return null;
|
|
471
|
+
}
|
|
472
|
+
const evtSessionId = evt.data?.sessionID ?? evt.data?.form?.sessionID ?? "";
|
|
473
|
+
if (!evtSessionId || !trackedSessionIds.has(evtSessionId)) return null;
|
|
474
|
+
if (evtType === "permission.asked" || evtType === "form.created") {
|
|
475
|
+
flushText();
|
|
476
|
+
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";
|
|
477
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
478
|
+
type: "error",
|
|
479
|
+
sessionID: sessionId,
|
|
480
|
+
error: { name: "InteractionRequired", data: { message } }
|
|
481
|
+
})}
|
|
482
|
+
`);
|
|
483
|
+
await ensureInterrupt(trackedSessionIds);
|
|
484
|
+
return { ok: false, sessionId, errorMessage: message };
|
|
485
|
+
}
|
|
486
|
+
if (evtSessionId !== sessionId) return null;
|
|
487
|
+
if (evtType === "session.text.delta") {
|
|
488
|
+
const delta = typeof evt.data?.delta === "string" ? evt.data.delta : typeof evt.data?.text === "string" ? evt.data.text : "";
|
|
489
|
+
if (delta) {
|
|
490
|
+
pendingText += delta;
|
|
491
|
+
if (pendingText.includes("\n") || pendingText.length >= 256) flushText();
|
|
492
|
+
}
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
if (evtType === "session.step.ended") {
|
|
496
|
+
flushText();
|
|
497
|
+
return null;
|
|
498
|
+
}
|
|
499
|
+
if (evtType === "session.execution.succeeded") {
|
|
500
|
+
flushText();
|
|
501
|
+
return { ok: true, sessionId };
|
|
502
|
+
}
|
|
503
|
+
if (evtType === "session.execution.failed") {
|
|
504
|
+
flushText();
|
|
505
|
+
const rawErr = evt.data?.error?.data?.message || evt.data?.error?.message || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
506
|
+
const errMsg = sanitizeErrorDetail(rawErr, 400) || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
507
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
508
|
+
type: "error",
|
|
509
|
+
sessionID: sessionId,
|
|
510
|
+
error: { name: evt.data?.error?.name || "ExecutionError", data: { message: errMsg } }
|
|
511
|
+
})}
|
|
512
|
+
`);
|
|
513
|
+
return { ok: false, sessionId, errorMessage: errMsg };
|
|
514
|
+
}
|
|
515
|
+
if (evtType === "session.execution.interrupted") {
|
|
516
|
+
flushText();
|
|
517
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u6267\u884C\u5DF2\u4E2D\u65AD" };
|
|
518
|
+
}
|
|
519
|
+
return null;
|
|
520
|
+
};
|
|
521
|
+
try {
|
|
522
|
+
while (true) {
|
|
523
|
+
const { done, value } = await reader.read();
|
|
524
|
+
if (done) break;
|
|
525
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
526
|
+
if (buffer.length > MAX_SSE_BUFFER_CHARS) {
|
|
527
|
+
buffer = buffer.slice(-MAX_SSE_BUFFER_CHARS);
|
|
528
|
+
}
|
|
529
|
+
let sepIdx = buffer.indexOf("\n\n");
|
|
530
|
+
while (sepIdx >= 0) {
|
|
531
|
+
const frame = buffer.slice(0, sepIdx);
|
|
532
|
+
buffer = buffer.slice(sepIdx + 2);
|
|
533
|
+
const dataLines = [];
|
|
534
|
+
for (const line of frame.split("\n")) {
|
|
535
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
536
|
+
}
|
|
537
|
+
if (dataLines.length > 0) {
|
|
538
|
+
const terminal = await processEventPayload(dataLines.join("\n"));
|
|
539
|
+
if (terminal) {
|
|
540
|
+
sseController.abort();
|
|
541
|
+
return terminal;
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
sepIdx = buffer.indexOf("\n\n");
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
} finally {
|
|
548
|
+
reader.releaseLock();
|
|
549
|
+
}
|
|
550
|
+
flushText();
|
|
551
|
+
if (ctx.signal.aborted) {
|
|
552
|
+
await ensureInterrupt(trackedSessionIds);
|
|
553
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
554
|
+
}
|
|
555
|
+
await ensureInterrupt(trackedSessionIds);
|
|
556
|
+
return { ok: false, sessionId, errorMessage: "OpenCode \u4E8B\u4EF6\u6D41\u63D0\u524D\u65AD\u5F00\uFF0C\u5DF2\u4E2D\u6B62\u8FDC\u7AEF\u4F1A\u8BDD" };
|
|
557
|
+
} catch (error) {
|
|
558
|
+
if (ctx.signal.aborted) {
|
|
559
|
+
await ensureInterrupt();
|
|
560
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
561
|
+
}
|
|
562
|
+
if (sessionId) await ensureInterrupt();
|
|
563
|
+
const msg = sanitizeErrorDetail(error instanceof Error ? error.message : String(error), 300) || "Runner \u6267\u884C\u5F02\u5E38";
|
|
564
|
+
return { ok: false, sessionId, errorMessage: msg };
|
|
565
|
+
} finally {
|
|
566
|
+
sseController.abort();
|
|
567
|
+
ctx.signal.removeEventListener("abort", onOuterAbort);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
|
|
572
|
+
// src/worker/index.ts
|
|
71
573
|
import { fileURLToPath } from "url";
|
|
72
574
|
import { existsSync } from "fs";
|
|
73
575
|
import { dirname, join } from "path";
|
|
@@ -204,12 +706,14 @@ var WorkerEngine = class {
|
|
|
204
706
|
settlementRetryWakeups = /* @__PURE__ */ new Set();
|
|
205
707
|
cfg;
|
|
206
708
|
opencodeBin;
|
|
709
|
+
runner;
|
|
207
710
|
maxOutputChars;
|
|
208
711
|
settlementRetryDelaysMs;
|
|
209
712
|
settlementRetryIntervalMs;
|
|
210
713
|
constructor(cfg, options = {}) {
|
|
211
714
|
this.cfg = cfg.worker;
|
|
212
715
|
this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
|
|
716
|
+
this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
|
|
213
717
|
this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
214
718
|
this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
|
|
215
719
|
this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
|
|
@@ -258,7 +762,7 @@ var WorkerEngine = class {
|
|
|
258
762
|
if (this.pollCyclePromise) await this.pollCyclePromise;
|
|
259
763
|
if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
|
|
260
764
|
const deadline = Date.now() + gracePeriodMs;
|
|
261
|
-
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
765
|
+
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (!entry.child || entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
262
766
|
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
263
767
|
}
|
|
264
768
|
}
|
|
@@ -343,7 +847,7 @@ var WorkerEngine = class {
|
|
|
343
847
|
while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
|
|
344
848
|
const databaseRunningCount = await TaskService.countRunning();
|
|
345
849
|
if (databaseRunningCount >= this.cfg.maxConcurrency) break;
|
|
346
|
-
const openCode = await detectOpenCodeVersion(this.opencodeBin);
|
|
850
|
+
const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
|
|
347
851
|
if (this.stopped) break;
|
|
348
852
|
let task;
|
|
349
853
|
try {
|
|
@@ -377,7 +881,7 @@ var WorkerEngine = class {
|
|
|
377
881
|
workerPid: process.pid,
|
|
378
882
|
lockedAt: Date.now(),
|
|
379
883
|
lockedBy: launchIdentity,
|
|
380
|
-
launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
884
|
+
launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
381
885
|
});
|
|
382
886
|
runId = run.id;
|
|
383
887
|
if (this.stopped) {
|
|
@@ -397,9 +901,19 @@ var WorkerEngine = class {
|
|
|
397
901
|
} catch (error) {
|
|
398
902
|
const message = error instanceof Error ? error.message : String(error);
|
|
399
903
|
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
904
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
905
|
+
"task.dead_letter",
|
|
906
|
+
{ ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
|
|
907
|
+
{ id: run.id, sessionId: null, status: "failed" },
|
|
908
|
+
message
|
|
909
|
+
));
|
|
400
910
|
this.releaseBatch(task);
|
|
401
911
|
continue;
|
|
402
912
|
}
|
|
913
|
+
if (this.runner) {
|
|
914
|
+
this.executeViaRunner(task, run.id, launchIdentity, this.runner);
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
403
917
|
let args;
|
|
404
918
|
try {
|
|
405
919
|
args = buildOpenCodeRunArgs(openCode.major, {
|
|
@@ -411,7 +925,14 @@ var WorkerEngine = class {
|
|
|
411
925
|
});
|
|
412
926
|
} catch (error) {
|
|
413
927
|
if (!(error instanceof OpenCodeInvocationError)) throw error;
|
|
414
|
-
|
|
928
|
+
const message = `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`;
|
|
929
|
+
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
930
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
931
|
+
"task.dead_letter",
|
|
932
|
+
{ ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
|
|
933
|
+
{ id: run.id, sessionId: null, status: "failed" },
|
|
934
|
+
message
|
|
935
|
+
));
|
|
415
936
|
this.releaseBatch(task);
|
|
416
937
|
continue;
|
|
417
938
|
}
|
|
@@ -451,8 +972,106 @@ var WorkerEngine = class {
|
|
|
451
972
|
if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
|
|
452
973
|
return entry;
|
|
453
974
|
}
|
|
975
|
+
executeViaRunner(task, runId, launchIdentity, runner) {
|
|
976
|
+
const cwd = task.cwd || process.cwd();
|
|
977
|
+
const abortController = new AbortController();
|
|
978
|
+
const model = this.resolveModel(task.model);
|
|
979
|
+
const variant = this.resolveVariant(task.variant);
|
|
980
|
+
const entry = {
|
|
981
|
+
task,
|
|
982
|
+
runId,
|
|
983
|
+
sessionId: null,
|
|
984
|
+
launchIdentity,
|
|
985
|
+
child: null,
|
|
986
|
+
runnerAbort: abortController,
|
|
987
|
+
commandContext: runCommandContext(`runner:${runner.name}`, [task.agent], cwd),
|
|
988
|
+
output: new RunOutput(
|
|
989
|
+
this.maxOutputChars,
|
|
990
|
+
(sessionId) => {
|
|
991
|
+
entry.sessionId = sessionId;
|
|
992
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
993
|
+
this.logError("sessionId update failed", err, task.id);
|
|
994
|
+
});
|
|
995
|
+
},
|
|
996
|
+
(stream, line) => {
|
|
997
|
+
gatewayEvents.emitRunLog(runId, task.id, stream, line);
|
|
998
|
+
}
|
|
999
|
+
),
|
|
1000
|
+
timeoutTimer: null,
|
|
1001
|
+
termination: null,
|
|
1002
|
+
terminationPromise: null,
|
|
1003
|
+
settlementPromise: null,
|
|
1004
|
+
guardianDrained: true,
|
|
1005
|
+
quarantined: false,
|
|
1006
|
+
settled: false
|
|
1007
|
+
};
|
|
1008
|
+
this.runningTasks.set(task.id, entry);
|
|
1009
|
+
gatewayEvents.emitRunStarted({
|
|
1010
|
+
runId,
|
|
1011
|
+
taskId: task.id,
|
|
1012
|
+
cwd: task.cwd,
|
|
1013
|
+
model,
|
|
1014
|
+
variant
|
|
1015
|
+
});
|
|
1016
|
+
const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
|
|
1017
|
+
if (timeoutMs > 0) {
|
|
1018
|
+
entry.timeoutTimer = setTimeout(() => {
|
|
1019
|
+
this.runDetached(
|
|
1020
|
+
this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
|
|
1021
|
+
"runner timeout termination failed",
|
|
1022
|
+
entry.task.id
|
|
1023
|
+
);
|
|
1024
|
+
}, timeoutMs);
|
|
1025
|
+
entry.timeoutTimer.unref?.();
|
|
1026
|
+
}
|
|
1027
|
+
const runnerPromise = runner.execute({
|
|
1028
|
+
task,
|
|
1029
|
+
runId,
|
|
1030
|
+
cwd,
|
|
1031
|
+
agent: task.agent,
|
|
1032
|
+
model,
|
|
1033
|
+
variant,
|
|
1034
|
+
prompt: task.prompt,
|
|
1035
|
+
title: task.name,
|
|
1036
|
+
metadata: parseTaskMetadata(task.metadata),
|
|
1037
|
+
signal: abortController.signal,
|
|
1038
|
+
onSessionId: (sessionId) => {
|
|
1039
|
+
entry.sessionId = sessionId;
|
|
1040
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
1041
|
+
this.logError("sessionId update failed", err, task.id);
|
|
1042
|
+
});
|
|
1043
|
+
},
|
|
1044
|
+
onOutputChunk: (chunk) => {
|
|
1045
|
+
entry.output.push("stdout", chunk);
|
|
1046
|
+
}
|
|
1047
|
+
}).then((result) => {
|
|
1048
|
+
if (entry.settled || entry.termination) return;
|
|
1049
|
+
this.runDetached(
|
|
1050
|
+
this.settleEntry(entry, result.ok ? 0 : 1, result.ok ? void 0 : result.errorMessage || "Runner \u6267\u884C\u5931\u8D25"),
|
|
1051
|
+
"runner settlement failed",
|
|
1052
|
+
entry.task.id
|
|
1053
|
+
);
|
|
1054
|
+
}).catch((error) => {
|
|
1055
|
+
if (entry.settled || entry.termination) return;
|
|
1056
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
1057
|
+
this.runDetached(
|
|
1058
|
+
this.settleEntry(entry, 1, `Runner \u6267\u884C\u5F02\u5E38\uFF1A${msg}`),
|
|
1059
|
+
"runner error settlement failed",
|
|
1060
|
+
entry.task.id
|
|
1061
|
+
);
|
|
1062
|
+
});
|
|
1063
|
+
entry.runnerDone = runnerPromise;
|
|
1064
|
+
}
|
|
454
1065
|
async spawnTask(task, runId, launchIdentity, args) {
|
|
455
1066
|
const cwd = task.cwd || process.cwd();
|
|
1067
|
+
const childEnv = {
|
|
1068
|
+
...process.env,
|
|
1069
|
+
PWD: cwd,
|
|
1070
|
+
[MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
|
|
1071
|
+
};
|
|
1072
|
+
delete childEnv.SUPERTASK_API_TOKEN;
|
|
1073
|
+
delete childEnv.SUPERTASK_WEBHOOK_SECRET;
|
|
1074
|
+
delete childEnv.SUPERTASK_WEBHOOK_URL;
|
|
456
1075
|
const child = spawn(process.execPath, [
|
|
457
1076
|
this.launcherEntry(),
|
|
458
1077
|
LAUNCH_IDENTITY_ARGUMENT,
|
|
@@ -461,23 +1080,21 @@ var WorkerEngine = class {
|
|
|
461
1080
|
...args
|
|
462
1081
|
], {
|
|
463
1082
|
cwd,
|
|
464
|
-
env:
|
|
465
|
-
...process.env,
|
|
466
|
-
PWD: cwd,
|
|
467
|
-
[MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
|
|
468
|
-
},
|
|
1083
|
+
env: childEnv,
|
|
469
1084
|
stdio: ["pipe", "pipe", "pipe", "ipc"],
|
|
470
1085
|
detached: process.platform !== "win32"
|
|
471
1086
|
});
|
|
472
1087
|
const entry = {
|
|
473
1088
|
task,
|
|
474
1089
|
runId,
|
|
1090
|
+
sessionId: null,
|
|
475
1091
|
launchIdentity,
|
|
476
1092
|
child,
|
|
477
1093
|
commandContext: runCommandContext(this.opencodeBin, args, cwd),
|
|
478
1094
|
output: new RunOutput(
|
|
479
1095
|
this.maxOutputChars,
|
|
480
1096
|
(sessionId) => {
|
|
1097
|
+
entry.sessionId = sessionId;
|
|
481
1098
|
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
482
1099
|
this.logError("sessionId update failed", err, task.id);
|
|
483
1100
|
});
|
|
@@ -611,7 +1228,7 @@ var WorkerEngine = class {
|
|
|
611
1228
|
handleChildClose(entry, code, signal, spawnError) {
|
|
612
1229
|
if (entry.settled || entry.termination) return;
|
|
613
1230
|
if (!entry.guardianDrained) {
|
|
614
|
-
const pid2 = entry.child
|
|
1231
|
+
const pid2 = entry.child?.pid;
|
|
615
1232
|
const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
|
|
616
1233
|
const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
|
|
617
1234
|
if (presence !== "not-running") {
|
|
@@ -634,7 +1251,7 @@ var WorkerEngine = class {
|
|
|
634
1251
|
);
|
|
635
1252
|
return;
|
|
636
1253
|
}
|
|
637
|
-
const pid = entry.child
|
|
1254
|
+
const pid = entry.child?.pid;
|
|
638
1255
|
if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
|
|
639
1256
|
if (entry.timeoutTimer) {
|
|
640
1257
|
clearTimeout(entry.timeoutTimer);
|
|
@@ -729,6 +1346,12 @@ ${output2}` : ""}`;
|
|
|
729
1346
|
status: "cancelled",
|
|
730
1347
|
reason: "run-cancelled"
|
|
731
1348
|
});
|
|
1349
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
1350
|
+
"task.cancelled",
|
|
1351
|
+
{ ...entry.task, status: "cancelled", finishedAt: /* @__PURE__ */ new Date(), resultLog: log2 },
|
|
1352
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "failed" },
|
|
1353
|
+
log2
|
|
1354
|
+
));
|
|
732
1355
|
console.log(JSON.stringify({
|
|
733
1356
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
734
1357
|
level: "info",
|
|
@@ -758,6 +1381,12 @@ ${output}` : ""}` : output;
|
|
|
758
1381
|
status: "done",
|
|
759
1382
|
reason: "run-done"
|
|
760
1383
|
});
|
|
1384
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
1385
|
+
"task.done",
|
|
1386
|
+
{ ...entry.task, status: "done", finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
|
|
1387
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "done" },
|
|
1388
|
+
log
|
|
1389
|
+
));
|
|
761
1390
|
console.log(JSON.stringify({
|
|
762
1391
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
763
1392
|
level: "info",
|
|
@@ -803,6 +1432,13 @@ ${output}` : ""}` : output;
|
|
|
803
1432
|
status: failed.status,
|
|
804
1433
|
reason: "run-failed"
|
|
805
1434
|
});
|
|
1435
|
+
const webhookEvent = failed.status === "dead_letter" ? "task.dead_letter" : "task.failed";
|
|
1436
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
1437
|
+
webhookEvent,
|
|
1438
|
+
{ ...entry.task, status: failed.status, finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
|
|
1439
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "failed" },
|
|
1440
|
+
log
|
|
1441
|
+
));
|
|
806
1442
|
console.error(JSON.stringify({
|
|
807
1443
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
808
1444
|
level: "error",
|
|
@@ -885,6 +1521,17 @@ ${output}` : ""}` : output;
|
|
|
885
1521
|
}
|
|
886
1522
|
}
|
|
887
1523
|
async killEntry(entry, initialSignal = "SIGTERM") {
|
|
1524
|
+
if (entry.runnerAbort) {
|
|
1525
|
+
entry.runnerAbort.abort();
|
|
1526
|
+
if (entry.runnerDone) {
|
|
1527
|
+
await Promise.race([
|
|
1528
|
+
entry.runnerDone.catch(() => void 0),
|
|
1529
|
+
new Promise((resolve) => setTimeout(resolve, 5e3))
|
|
1530
|
+
]);
|
|
1531
|
+
}
|
|
1532
|
+
return true;
|
|
1533
|
+
}
|
|
1534
|
+
if (!entry.child) return true;
|
|
888
1535
|
const pid = entry.child.pid;
|
|
889
1536
|
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
|
|
890
1537
|
if (!pid) return false;
|
|
@@ -900,7 +1547,7 @@ ${output}` : ""}` : output;
|
|
|
900
1547
|
return waitForSpawnedProcessTreeExit(pid, 2500);
|
|
901
1548
|
}
|
|
902
1549
|
signalEntry(entry, signal) {
|
|
903
|
-
const pid = entry.child
|
|
1550
|
+
const pid = entry.child?.pid;
|
|
904
1551
|
if (!pid) return "not-running";
|
|
905
1552
|
return signalRecordedProcessTreeWithResult(
|
|
906
1553
|
pid,
|
|
@@ -960,7 +1607,7 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
|
|
|
960
1607
|
if (shouldStop()) break;
|
|
961
1608
|
if (isOwnedRun(run.taskId, run.runId)) continue;
|
|
962
1609
|
try {
|
|
963
|
-
if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
1610
|
+
if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== HTTP_RUNNER_LAUNCH_PROTOCOL) {
|
|
964
1611
|
console.warn(JSON.stringify({
|
|
965
1612
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
966
1613
|
level: "warn",
|
|
@@ -973,6 +1620,20 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
|
|
|
973
1620
|
result.quarantinedRuns += 1;
|
|
974
1621
|
continue;
|
|
975
1622
|
}
|
|
1623
|
+
if (run.launchProtocol === HTTP_RUNNER_LAUNCH_PROTOCOL) {
|
|
1624
|
+
if (run.ownerAlive) {
|
|
1625
|
+
console.warn(JSON.stringify({
|
|
1626
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1627
|
+
level: "warn",
|
|
1628
|
+
msg: "stale http runner run still has live owner pid; run remains quarantined",
|
|
1629
|
+
taskId: run.taskId,
|
|
1630
|
+
runId: run.runId,
|
|
1631
|
+
workerPid: run.workerPid
|
|
1632
|
+
}));
|
|
1633
|
+
result.quarantinedRuns += 1;
|
|
1634
|
+
continue;
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
976
1637
|
if (run.childPid != null && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
977
1638
|
if (run.childPid > 0 && !isProcessAlive(run.childPid) && inspectSpawnedProcessTreePresence(run.childPid) === "not-running") {
|
|
978
1639
|
} else {
|
|
@@ -1660,6 +2321,7 @@ async function runGatewayMain(deps = {}) {
|
|
|
1660
2321
|
await resolveDeps();
|
|
1661
2322
|
if (shuttingDown) return;
|
|
1662
2323
|
initializeGatewayHealth({
|
|
2324
|
+
workerMaxConcurrency: cfg.worker.maxConcurrency,
|
|
1663
2325
|
workerPollIntervalMs: cfg.worker.pollIntervalMs,
|
|
1664
2326
|
schedulerEnabled: cfg.scheduler.enabled,
|
|
1665
2327
|
schedulerCheckIntervalMs: cfg.scheduler.checkIntervalMs,
|
|
@@ -1672,7 +2334,7 @@ async function runGatewayMain(deps = {}) {
|
|
|
1672
2334
|
if (deps.startDashboard) {
|
|
1673
2335
|
dashboardServer = await deps.startDashboard(cfg);
|
|
1674
2336
|
} else {
|
|
1675
|
-
const { dashboardApp, setDashboardRuntimeConfig } = await import("./web-
|
|
2337
|
+
const { dashboardApp, setDashboardRuntimeConfig } = await import("./web-4QWJ4Z5K.js");
|
|
1676
2338
|
if (shuttingDown) return;
|
|
1677
2339
|
setDashboardRuntimeConfig(cfg);
|
|
1678
2340
|
dashboardServer = Bun.serve({
|
|
@@ -1735,4 +2397,4 @@ export {
|
|
|
1735
2397
|
updateLockHeartbeat,
|
|
1736
2398
|
updateLockHeartbeatResult
|
|
1737
2399
|
};
|
|
1738
|
-
//# sourceMappingURL=gateway-
|
|
2400
|
+
//# sourceMappingURL=gateway-I2SQOXWB.js.map
|