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.
Files changed (50) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +1 -0
  3. package/README.zh-CN.md +1 -0
  4. package/dist/cli/{chunk-NCT3ETTK.js → chunk-7BATA4DM.js} +20 -1
  5. package/dist/cli/chunk-7BATA4DM.js.map +1 -0
  6. package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
  7. package/dist/cli/{chunk-764OMIPC.js → chunk-OJLDJVHB.js} +2 -2
  8. package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
  9. package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
  10. package/dist/cli/{chunk-YB7MYTE5.js → chunk-XWTKMNNI.js} +3 -1
  11. package/dist/cli/chunk-XWTKMNNI.js.map +1 -0
  12. package/dist/cli/{chunk-USBQGFQZ.js → chunk-YADLWDYK.js} +2 -2
  13. package/dist/cli/{database-maintenance.service-VZCH7ZEV.js → database-maintenance.service-NQBZ5VJT.js} +4 -4
  14. package/dist/cli/{doctor-smoke-ZKWNHC3O.js → doctor-smoke-6VU2KCRK.js} +4 -4
  15. package/dist/cli/{gateway-HUXVEDMU.js → gateway-I2SQOXWB.js} +507 -14
  16. package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
  17. package/dist/cli/index.js +17 -17
  18. package/dist/cli/{logs-XNLR23TK.js → logs-HB5RV7HD.js} +4 -4
  19. package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
  20. package/dist/cli/{task-run.service-HCMHWOGW.js → task-run.service-R45W2VID.js} +4 -4
  21. package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
  22. package/dist/cli/{web-TQO6JLBN.js → web-4QWJ4Z5K.js} +9 -8
  23. package/dist/cli/web-4QWJ4Z5K.js.map +1 -0
  24. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
  25. package/dist/gateway/index.d.ts +1 -0
  26. package/dist/gateway/index.js +535 -11
  27. package/dist/gateway/index.js.map +1 -1
  28. package/dist/plugin/supertask.js +42 -1
  29. package/dist/plugin/supertask.js.map +1 -1
  30. package/dist/web/index.js +24 -2
  31. package/dist/web/index.js.map +1 -1
  32. package/dist/worker/index.d.ts +492 -1
  33. package/dist/worker/index.js +508 -8
  34. package/dist/worker/index.js.map +1 -1
  35. package/dist/worker/launcher.js.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/cli/chunk-LX5CBJLP.js.map +0 -1
  38. package/dist/cli/chunk-NCT3ETTK.js.map +0 -1
  39. package/dist/cli/chunk-YB7MYTE5.js.map +0 -1
  40. package/dist/cli/gateway-HUXVEDMU.js.map +0 -1
  41. package/dist/cli/web-TQO6JLBN.js.map +0 -1
  42. /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
  43. /package/dist/cli/{chunk-764OMIPC.js.map → chunk-OJLDJVHB.js.map} +0 -0
  44. /package/dist/cli/{chunk-USBQGFQZ.js.map → chunk-YADLWDYK.js.map} +0 -0
  45. /package/dist/cli/{database-maintenance.service-VZCH7ZEV.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
  46. /package/dist/cli/{doctor-smoke-ZKWNHC3O.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
  47. /package/dist/cli/{logs-XNLR23TK.js.map → logs-HB5RV7HD.js.map} +0 -0
  48. /package/dist/cli/{pm2-WY644BUO.js.map → pm2-YSCAIIBU.js.map} +0 -0
  49. /package/dist/cli/{task-run.service-HCMHWOGW.js.map → task-run.service-R45W2VID.js.map} +0 -0
  50. /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
@@ -13,10 +13,10 @@ import {
13
13
  buildOpenCodeRunArgs,
14
14
  detectOpenCodeVersion,
15
15
  openCodeExecutable
16
- } from "./chunk-LX5CBJLP.js";
16
+ } from "./chunk-WHGCKWMR.js";
17
17
  import {
18
18
  TaskRunService
19
- } from "./chunk-764OMIPC.js";
19
+ } from "./chunk-OJLDJVHB.js";
20
20
  import {
21
21
  DUE_TEMPLATE_BATCH_SIZE,
22
22
  cloneTaskFromTemplate,
@@ -32,8 +32,9 @@ import {
32
32
  isProcessAlive,
33
33
  signalRecordedProcessTreeWithResult,
34
34
  waitForSpawnedProcessTreeExit
35
- } from "./chunk-ZBH7YWXF.js";
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,7 +42,7 @@ import {
41
42
  TOKEN_GUARDIAN_LAUNCH_PROTOCOL,
42
43
  drainProofAckForIdentity,
43
44
  isMatchingDrainProof
44
- } from "./chunk-YB7MYTE5.js";
45
+ } from "./chunk-XWTKMNNI.js";
45
46
  import {
46
47
  TaskService,
47
48
  normalizeTaskBatchId,
@@ -75,6 +76,7 @@ import { createHmac } from "crypto";
75
76
  var DEFAULT_TIMEOUT_MS = 5e3;
76
77
  var DEFAULT_MAX_ATTEMPTS = 2;
77
78
  var MAX_SUMMARY_CHARS = 2e3;
79
+ var pendingWebhooks = /* @__PURE__ */ new Set();
78
80
  function signWebhookPayload(secret, timestamp, body) {
79
81
  const digest = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
80
82
  return `sha256=${digest}`;
@@ -94,6 +96,8 @@ function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
94
96
  } else if (event.type === "error") {
95
97
  const msg = event.error?.data?.message || event.error?.message;
96
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());
97
101
  }
98
102
  } catch {
99
103
  if (!framed) texts.push(trimmed);
@@ -134,7 +138,15 @@ function buildTaskWebhookPayload(event, task, run, outputOverride) {
134
138
  outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
135
139
  };
136
140
  }
137
- async function dispatchTaskWebhook(payload, options = {}) {
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 = {}) {
138
150
  const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
139
151
  if (!url) return false;
140
152
  try {
@@ -163,6 +175,7 @@ async function dispatchTaskWebhook(payload, options = {}) {
163
175
  method: "POST",
164
176
  headers,
165
177
  body,
178
+ redirect: "error",
166
179
  signal: AbortSignal.timeout(timeoutMs)
167
180
  });
168
181
  if (resp.ok) return true;
@@ -177,6 +190,18 @@ async function dispatchTaskWebhook(payload, options = {}) {
177
190
  }));
178
191
  return false;
179
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
+ }
180
205
  } catch (err) {
181
206
  if (attempt >= maxAttempts) {
182
207
  console.warn(JSON.stringify({
@@ -197,6 +222,353 @@ async function dispatchTaskWebhook(payload, options = {}) {
197
222
  return false;
198
223
  }
199
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
+
200
572
  // src/worker/index.ts
201
573
  import { fileURLToPath } from "url";
202
574
  import { existsSync } from "fs";
@@ -334,12 +706,14 @@ var WorkerEngine = class {
334
706
  settlementRetryWakeups = /* @__PURE__ */ new Set();
335
707
  cfg;
336
708
  opencodeBin;
709
+ runner;
337
710
  maxOutputChars;
338
711
  settlementRetryDelaysMs;
339
712
  settlementRetryIntervalMs;
340
713
  constructor(cfg, options = {}) {
341
714
  this.cfg = cfg.worker;
342
715
  this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
716
+ this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
343
717
  this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
344
718
  this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
345
719
  this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
@@ -388,7 +762,7 @@ var WorkerEngine = class {
388
762
  if (this.pollCyclePromise) await this.pollCyclePromise;
389
763
  if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
390
764
  const deadline = Date.now() + gracePeriodMs;
391
- 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) {
392
766
  await Bun.sleep(Math.min(50, deadline - Date.now()));
393
767
  }
394
768
  }
@@ -473,7 +847,7 @@ var WorkerEngine = class {
473
847
  while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
474
848
  const databaseRunningCount = await TaskService.countRunning();
475
849
  if (databaseRunningCount >= this.cfg.maxConcurrency) break;
476
- const openCode = await detectOpenCodeVersion(this.opencodeBin);
850
+ const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
477
851
  if (this.stopped) break;
478
852
  let task;
479
853
  try {
@@ -507,7 +881,7 @@ var WorkerEngine = class {
507
881
  workerPid: process.pid,
508
882
  lockedAt: Date.now(),
509
883
  lockedBy: launchIdentity,
510
- launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
884
+ launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
511
885
  });
512
886
  runId = run.id;
513
887
  if (this.stopped) {
@@ -536,6 +910,10 @@ var WorkerEngine = class {
536
910
  this.releaseBatch(task);
537
911
  continue;
538
912
  }
913
+ if (this.runner) {
914
+ this.executeViaRunner(task, run.id, launchIdentity, this.runner);
915
+ continue;
916
+ }
539
917
  let args;
540
918
  try {
541
919
  args = buildOpenCodeRunArgs(openCode.major, {
@@ -594,6 +972,96 @@ var WorkerEngine = class {
594
972
  if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
595
973
  return entry;
596
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
+ }
597
1065
  async spawnTask(task, runId, launchIdentity, args) {
598
1066
  const cwd = task.cwd || process.cwd();
599
1067
  const childEnv = {
@@ -760,7 +1228,7 @@ var WorkerEngine = class {
760
1228
  handleChildClose(entry, code, signal, spawnError) {
761
1229
  if (entry.settled || entry.termination) return;
762
1230
  if (!entry.guardianDrained) {
763
- const pid2 = entry.child.pid;
1231
+ const pid2 = entry.child?.pid;
764
1232
  const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
765
1233
  const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
766
1234
  if (presence !== "not-running") {
@@ -783,7 +1251,7 @@ var WorkerEngine = class {
783
1251
  );
784
1252
  return;
785
1253
  }
786
- const pid = entry.child.pid;
1254
+ const pid = entry.child?.pid;
787
1255
  if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
788
1256
  if (entry.timeoutTimer) {
789
1257
  clearTimeout(entry.timeoutTimer);
@@ -1053,6 +1521,17 @@ ${output}` : ""}` : output;
1053
1521
  }
1054
1522
  }
1055
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;
1056
1535
  const pid = entry.child.pid;
1057
1536
  if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
1058
1537
  if (!pid) return false;
@@ -1068,7 +1547,7 @@ ${output}` : ""}` : output;
1068
1547
  return waitForSpawnedProcessTreeExit(pid, 2500);
1069
1548
  }
1070
1549
  signalEntry(entry, signal) {
1071
- const pid = entry.child.pid;
1550
+ const pid = entry.child?.pid;
1072
1551
  if (!pid) return "not-running";
1073
1552
  return signalRecordedProcessTreeWithResult(
1074
1553
  pid,
@@ -1128,7 +1607,7 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
1128
1607
  if (shouldStop()) break;
1129
1608
  if (isOwnedRun(run.taskId, run.runId)) continue;
1130
1609
  try {
1131
- 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) {
1132
1611
  console.warn(JSON.stringify({
1133
1612
  ts: (/* @__PURE__ */ new Date()).toISOString(),
1134
1613
  level: "warn",
@@ -1141,6 +1620,20 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
1141
1620
  result.quarantinedRuns += 1;
1142
1621
  continue;
1143
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
+ }
1144
1637
  if (run.childPid != null && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
1145
1638
  if (run.childPid > 0 && !isProcessAlive(run.childPid) && inspectSpawnedProcessTreePresence(run.childPid) === "not-running") {
1146
1639
  } else {
@@ -1841,7 +2334,7 @@ async function runGatewayMain(deps = {}) {
1841
2334
  if (deps.startDashboard) {
1842
2335
  dashboardServer = await deps.startDashboard(cfg);
1843
2336
  } else {
1844
- const { dashboardApp, setDashboardRuntimeConfig } = await import("./web-TQO6JLBN.js");
2337
+ const { dashboardApp, setDashboardRuntimeConfig } = await import("./web-4QWJ4Z5K.js");
1845
2338
  if (shuttingDown) return;
1846
2339
  setDashboardRuntimeConfig(cfg);
1847
2340
  dashboardServer = Bun.serve({
@@ -1904,4 +2397,4 @@ export {
1904
2397
  updateLockHeartbeat,
1905
2398
  updateLockHeartbeatResult
1906
2399
  };
1907
- //# sourceMappingURL=gateway-HUXVEDMU.js.map
2400
+ //# sourceMappingURL=gateway-I2SQOXWB.js.map