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
@@ -8100,6 +8100,7 @@ import { createHmac } from "crypto";
8100
8100
  var DEFAULT_TIMEOUT_MS = 5e3;
8101
8101
  var DEFAULT_MAX_ATTEMPTS = 2;
8102
8102
  var MAX_SUMMARY_CHARS = 2e3;
8103
+ var pendingWebhooks = /* @__PURE__ */ new Set();
8103
8104
  function signWebhookPayload(secret, timestamp, body) {
8104
8105
  const digest = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
8105
8106
  return `sha256=${digest}`;
@@ -8119,6 +8120,8 @@ function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
8119
8120
  } else if (event.type === "error") {
8120
8121
  const msg = event.error?.data?.message || event.error?.message;
8121
8122
  if (typeof msg === "string" && msg.trim()) texts.push(msg.trim());
8123
+ } else if (event.type === "tool_use" && event.part?.state?.status === "error" && typeof event.part.state.error === "string" && event.part.state.error.trim()) {
8124
+ texts.push(event.part.state.error.trim());
8122
8125
  }
8123
8126
  } catch {
8124
8127
  if (!framed) texts.push(trimmed);
@@ -8159,7 +8162,15 @@ function buildTaskWebhookPayload(event, task, run, outputOverride) {
8159
8162
  outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
8160
8163
  };
8161
8164
  }
8162
- async function dispatchTaskWebhook(payload, options = {}) {
8165
+ function dispatchTaskWebhook(payload, options = {}) {
8166
+ const task = deliverTaskWebhook(payload, options);
8167
+ pendingWebhooks.add(task);
8168
+ void task.finally(() => {
8169
+ pendingWebhooks.delete(task);
8170
+ });
8171
+ return task;
8172
+ }
8173
+ async function deliverTaskWebhook(payload, options = {}) {
8163
8174
  const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
8164
8175
  if (!url) return false;
8165
8176
  try {
@@ -8188,6 +8199,7 @@ async function dispatchTaskWebhook(payload, options = {}) {
8188
8199
  method: "POST",
8189
8200
  headers,
8190
8201
  body,
8202
+ redirect: "error",
8191
8203
  signal: AbortSignal.timeout(timeoutMs)
8192
8204
  });
8193
8205
  if (resp.ok) return true;
@@ -8202,6 +8214,18 @@ async function dispatchTaskWebhook(payload, options = {}) {
8202
8214
  }));
8203
8215
  return false;
8204
8216
  }
8217
+ if (attempt >= maxAttempts) {
8218
+ console.warn(JSON.stringify({
8219
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
8220
+ level: "warn",
8221
+ msg: "task webhook delivery exhausted",
8222
+ event: payload.event,
8223
+ taskId: payload.task.id,
8224
+ status: resp.status,
8225
+ attempts: maxAttempts
8226
+ }));
8227
+ return false;
8228
+ }
8205
8229
  } catch (err) {
8206
8230
  if (attempt >= maxAttempts) {
8207
8231
  console.warn(JSON.stringify({
@@ -8222,6 +8246,353 @@ async function dispatchTaskWebhook(payload, options = {}) {
8222
8246
  return false;
8223
8247
  }
8224
8248
 
8249
+ // src/worker/runners/opencode-server.ts
8250
+ var MAX_SSE_BUFFER_CHARS = 2 * 1024 * 1024;
8251
+ function isLoopbackHost(hostname) {
8252
+ const h = hostname.toLowerCase();
8253
+ return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
8254
+ }
8255
+ function sanitizeErrorDetail(raw, maxLen = 240) {
8256
+ if (!raw) return "";
8257
+ 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);
8258
+ }
8259
+ function parseModelSpec(rawModel, explicitVariant) {
8260
+ if (!rawModel || rawModel === "default") return null;
8261
+ let modelStr = rawModel.trim();
8262
+ let variant = explicitVariant?.trim() || void 0;
8263
+ const hashIdx = modelStr.indexOf("#");
8264
+ if (hashIdx > 0) {
8265
+ const embedded = modelStr.slice(hashIdx + 1).trim();
8266
+ modelStr = modelStr.slice(0, hashIdx).trim();
8267
+ if (!variant && embedded) variant = embedded;
8268
+ }
8269
+ const slashIdx = modelStr.indexOf("/");
8270
+ if (slashIdx <= 0 || slashIdx === modelStr.length - 1) return null;
8271
+ return {
8272
+ providerID: modelStr.slice(0, slashIdx),
8273
+ id: modelStr.slice(slashIdx + 1),
8274
+ ...variant ? { variant } : {}
8275
+ };
8276
+ }
8277
+ var OpenCodeServerRunner = class {
8278
+ name = "opencode-server";
8279
+ baseUrl;
8280
+ password;
8281
+ defaultModel;
8282
+ allowInsecureHttp;
8283
+ fetchFn;
8284
+ constructor(options = {}) {
8285
+ const rawUrl = (options.baseUrl ?? process.env.OPENCODE_URL ?? "").trim();
8286
+ this.baseUrl = rawUrl.replace(/\/+$/, "");
8287
+ this.password = (options.password ?? process.env.OPENCODE_PASSWORD ?? "").trim();
8288
+ this.defaultModel = (options.defaultModel ?? process.env.SUPERTASK_DEFAULT_MODEL ?? process.env.DEFAULT_MODEL ?? "").trim();
8289
+ this.allowInsecureHttp = options.allowInsecureHttp ?? process.env.SUPERTASK_ALLOW_INSECURE_HTTP === "1";
8290
+ this.fetchFn = options.fetchImpl ?? fetch;
8291
+ }
8292
+ authHeaders(extra = {}) {
8293
+ const headers = { ...extra };
8294
+ if (this.password) {
8295
+ headers.authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
8296
+ }
8297
+ return headers;
8298
+ }
8299
+ async interruptSession(sessionId) {
8300
+ try {
8301
+ const resp = await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
8302
+ method: "POST",
8303
+ headers: this.authHeaders(),
8304
+ signal: AbortSignal.timeout(3e3)
8305
+ });
8306
+ return resp.ok;
8307
+ } catch {
8308
+ return false;
8309
+ }
8310
+ }
8311
+ async execute(ctx) {
8312
+ if (!this.baseUrl) {
8313
+ return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_URL \u914D\u7F6E" };
8314
+ }
8315
+ if (!this.password) {
8316
+ return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_PASSWORD \u914D\u7F6E" };
8317
+ }
8318
+ let parsedBaseUrl;
8319
+ try {
8320
+ parsedBaseUrl = new URL(this.baseUrl);
8321
+ } catch {
8322
+ return { ok: false, sessionId: null, errorMessage: "OPENCODE_URL \u4E0D\u662F\u6709\u6548\u7684 HTTP(S) \u5730\u5740" };
8323
+ }
8324
+ if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && (isLoopbackHost(parsedBaseUrl.hostname) || this.allowInsecureHttp))) {
8325
+ return {
8326
+ ok: false,
8327
+ sessionId: null,
8328
+ 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"
8329
+ };
8330
+ }
8331
+ const explicitModel = ctx.model && ctx.model !== "default" ? ctx.model.trim() : null;
8332
+ const explicitVariant = ctx.variant && ctx.variant !== "default" ? ctx.variant.trim() : null;
8333
+ if (explicitModel && !parseModelSpec(explicitModel, explicitVariant)) {
8334
+ return { ok: false, sessionId: null, errorMessage: `\u65E0\u6548\u7684\u6A21\u578B\u683C\u5F0F\uFF08\u9700\u8981 provider/model\uFF09\uFF1A${explicitModel}` };
8335
+ }
8336
+ let sessionId = null;
8337
+ let interruptedRemote = false;
8338
+ const ensureInterrupt = async (targetIds) => {
8339
+ if (interruptedRemote && !targetIds) return;
8340
+ const ids = /* @__PURE__ */ new Set();
8341
+ if (targetIds) {
8342
+ for (const id of targetIds) if (id) ids.add(id);
8343
+ }
8344
+ if (sessionId) ids.add(sessionId);
8345
+ if (ids.size === 0) return;
8346
+ interruptedRemote = true;
8347
+ await Promise.all([...ids].map((id) => this.interruptSession(id)));
8348
+ };
8349
+ const sseController = new AbortController();
8350
+ const onOuterAbort = () => {
8351
+ sseController.abort();
8352
+ };
8353
+ if (ctx.signal.aborted) {
8354
+ return { ok: false, sessionId: null, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
8355
+ }
8356
+ ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
8357
+ try {
8358
+ const agentUrl = new URL(`${this.baseUrl}/api/agent`);
8359
+ agentUrl.searchParams.set("location[directory]", ctx.cwd);
8360
+ let agentDef;
8361
+ for (let attempt = 0; attempt < 4; attempt += 1) {
8362
+ const agentResp = await this.fetchFn(agentUrl.toString(), {
8363
+ headers: this.authHeaders(),
8364
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
8365
+ });
8366
+ if (!agentResp.ok) {
8367
+ return { ok: false, sessionId: null, errorMessage: `\u65E0\u6CD5\u8BFB\u53D6 OpenCode Agent \u6E05\u5355\uFF1AHTTP ${agentResp.status}` };
8368
+ }
8369
+ const payload = await agentResp.json();
8370
+ agentDef = Array.isArray(payload.data) ? payload.data.find((a) => a.id === ctx.agent) : void 0;
8371
+ if (agentDef) break;
8372
+ if (attempt < 3) await new Promise((r) => setTimeout(r, 250));
8373
+ }
8374
+ if (!agentDef || agentDef.hidden || agentDef.disabled || agentDef.mode === "subagent") {
8375
+ return { ok: false, sessionId: null, errorMessage: `\u4EFB\u52A1\u7684 Agent \u5DF2\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\uFF08${ctx.agent}\uFF09` };
8376
+ }
8377
+ const createResp = await this.fetchFn(`${this.baseUrl}/api/session`, {
8378
+ method: "POST",
8379
+ headers: this.authHeaders({ "content-type": "application/json" }),
8380
+ body: JSON.stringify({
8381
+ agent: ctx.agent,
8382
+ location: { directory: ctx.cwd },
8383
+ metadata: {
8384
+ ...ctx.metadata ?? {},
8385
+ supertaskTaskId: ctx.task.id,
8386
+ supertaskRunId: ctx.runId
8387
+ }
8388
+ }),
8389
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
8390
+ });
8391
+ if (!createResp.ok) {
8392
+ return { ok: false, sessionId: null, errorMessage: `\u521B\u5EFA OpenCode \u4F1A\u8BDD\u5931\u8D25\uFF1AHTTP ${createResp.status}` };
8393
+ }
8394
+ const created = await createResp.json();
8395
+ sessionId = created.data?.id ?? created.id ?? null;
8396
+ if (!sessionId) {
8397
+ return { ok: false, sessionId: null, errorMessage: "OpenCode \u672A\u8FD4\u56DE\u6709\u6548\u7684\u4F1A\u8BDD ID" };
8398
+ }
8399
+ ctx.onSessionId(sessionId);
8400
+ const cleanTitle = ctx.title.replace(/\s+/g, " ").trim().slice(0, 200);
8401
+ if (cleanTitle) {
8402
+ await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}`, {
8403
+ method: "PATCH",
8404
+ headers: this.authHeaders({ "content-type": "application/json" }),
8405
+ body: JSON.stringify({ title: cleanTitle }),
8406
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
8407
+ }).catch(() => void 0);
8408
+ }
8409
+ let modelSpec = explicitModel ? parseModelSpec(explicitModel, explicitVariant) : null;
8410
+ if (!modelSpec && agentDef.model?.providerID && agentDef.model?.id) {
8411
+ const resolvedVariant = explicitVariant ?? (agentDef.model.variant && agentDef.model.variant !== "default" ? agentDef.model.variant : void 0);
8412
+ modelSpec = {
8413
+ providerID: agentDef.model.providerID,
8414
+ id: agentDef.model.id,
8415
+ ...resolvedVariant ? { variant: resolvedVariant } : {}
8416
+ };
8417
+ }
8418
+ if (!modelSpec && this.defaultModel) {
8419
+ modelSpec = parseModelSpec(this.defaultModel, explicitVariant);
8420
+ }
8421
+ if (explicitVariant && !modelSpec) {
8422
+ return { ok: false, sessionId, errorMessage: "\u6307\u5B9A\u4E86 variant \u4F46\u672A\u914D\u7F6E\u53EF\u7528\u6A21\u578B" };
8423
+ }
8424
+ if (modelSpec) {
8425
+ const switchResp = await this.fetchFn(
8426
+ `${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/model`,
8427
+ {
8428
+ method: "POST",
8429
+ headers: this.authHeaders({ "content-type": "application/json" }),
8430
+ body: JSON.stringify({ model: modelSpec }),
8431
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
8432
+ }
8433
+ );
8434
+ if (!switchResp.ok) {
8435
+ return { ok: false, sessionId, errorMessage: `\u5207\u6362 OpenCode \u6A21\u578B\u5931\u8D25\uFF1AHTTP ${switchResp.status}` };
8436
+ }
8437
+ }
8438
+ const sseResp = await this.fetchFn(`${this.baseUrl}/api/event`, {
8439
+ headers: this.authHeaders({ accept: "text/event-stream" }),
8440
+ signal: sseController.signal
8441
+ });
8442
+ const contentType = sseResp.headers.get("content-type") || "";
8443
+ if (!sseResp.ok || !sseResp.body || !contentType.toLowerCase().includes("text/event-stream")) {
8444
+ sseController.abort();
8445
+ return {
8446
+ ok: false,
8447
+ sessionId,
8448
+ errorMessage: `\u65E0\u6CD5\u8BA2\u9605 OpenCode \u4E8B\u4EF6\u6D41\uFF1AHTTP ${sseResp.status}${contentType ? ` (${contentType})` : ""}`
8449
+ };
8450
+ }
8451
+ const promptResp = await this.fetchFn(
8452
+ `${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/prompt`,
8453
+ {
8454
+ method: "POST",
8455
+ headers: this.authHeaders({ "content-type": "application/json" }),
8456
+ body: JSON.stringify({ text: ctx.prompt }),
8457
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(15e3)])
8458
+ }
8459
+ );
8460
+ if (!promptResp.ok) {
8461
+ sseController.abort();
8462
+ const detail = sanitizeErrorDetail(await promptResp.text().catch(() => ""));
8463
+ return {
8464
+ ok: false,
8465
+ sessionId,
8466
+ errorMessage: `OpenCode \u63D0\u4EA4\u4EFB\u52A1\u5931\u8D25\uFF1AHTTP ${promptResp.status}${detail ? ` ${detail}` : ""}`
8467
+ };
8468
+ }
8469
+ const trackedSessionIds = /* @__PURE__ */ new Set([sessionId]);
8470
+ const reader = sseResp.body.getReader();
8471
+ const decoder = new TextDecoder();
8472
+ let buffer = "";
8473
+ let pendingText = "";
8474
+ const flushText = () => {
8475
+ if (!pendingText) return;
8476
+ ctx.onOutputChunk(`${JSON.stringify({ type: "text", sessionID: sessionId, part: { text: pendingText } })}
8477
+ `);
8478
+ pendingText = "";
8479
+ };
8480
+ const processEventPayload = async (rawData) => {
8481
+ let evt;
8482
+ try {
8483
+ evt = JSON.parse(rawData);
8484
+ } catch {
8485
+ return null;
8486
+ }
8487
+ const evtType = evt.type || "";
8488
+ if (evtType === "session.created") {
8489
+ const childId = evt.data?.id ?? evt.data?.session?.id ?? "";
8490
+ const parentId = evt.data?.parentID ?? evt.data?.session?.parentID ?? "";
8491
+ if (childId && parentId && trackedSessionIds.has(parentId)) {
8492
+ trackedSessionIds.add(childId);
8493
+ }
8494
+ return null;
8495
+ }
8496
+ const evtSessionId = evt.data?.sessionID ?? evt.data?.form?.sessionID ?? "";
8497
+ if (!evtSessionId || !trackedSessionIds.has(evtSessionId)) return null;
8498
+ if (evtType === "permission.asked" || evtType === "form.created") {
8499
+ flushText();
8500
+ 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";
8501
+ ctx.onOutputChunk(`${JSON.stringify({
8502
+ type: "error",
8503
+ sessionID: sessionId,
8504
+ error: { name: "InteractionRequired", data: { message } }
8505
+ })}
8506
+ `);
8507
+ await ensureInterrupt(trackedSessionIds);
8508
+ return { ok: false, sessionId, errorMessage: message };
8509
+ }
8510
+ if (evtSessionId !== sessionId) return null;
8511
+ if (evtType === "session.text.delta") {
8512
+ const delta = typeof evt.data?.delta === "string" ? evt.data.delta : typeof evt.data?.text === "string" ? evt.data.text : "";
8513
+ if (delta) {
8514
+ pendingText += delta;
8515
+ if (pendingText.includes("\n") || pendingText.length >= 256) flushText();
8516
+ }
8517
+ return null;
8518
+ }
8519
+ if (evtType === "session.step.ended") {
8520
+ flushText();
8521
+ return null;
8522
+ }
8523
+ if (evtType === "session.execution.succeeded") {
8524
+ flushText();
8525
+ return { ok: true, sessionId };
8526
+ }
8527
+ if (evtType === "session.execution.failed") {
8528
+ flushText();
8529
+ const rawErr = evt.data?.error?.data?.message || evt.data?.error?.message || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
8530
+ const errMsg = sanitizeErrorDetail(rawErr, 400) || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
8531
+ ctx.onOutputChunk(`${JSON.stringify({
8532
+ type: "error",
8533
+ sessionID: sessionId,
8534
+ error: { name: evt.data?.error?.name || "ExecutionError", data: { message: errMsg } }
8535
+ })}
8536
+ `);
8537
+ return { ok: false, sessionId, errorMessage: errMsg };
8538
+ }
8539
+ if (evtType === "session.execution.interrupted") {
8540
+ flushText();
8541
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u6267\u884C\u5DF2\u4E2D\u65AD" };
8542
+ }
8543
+ return null;
8544
+ };
8545
+ try {
8546
+ while (true) {
8547
+ const { done, value } = await reader.read();
8548
+ if (done) break;
8549
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
8550
+ if (buffer.length > MAX_SSE_BUFFER_CHARS) {
8551
+ buffer = buffer.slice(-MAX_SSE_BUFFER_CHARS);
8552
+ }
8553
+ let sepIdx = buffer.indexOf("\n\n");
8554
+ while (sepIdx >= 0) {
8555
+ const frame = buffer.slice(0, sepIdx);
8556
+ buffer = buffer.slice(sepIdx + 2);
8557
+ const dataLines = [];
8558
+ for (const line of frame.split("\n")) {
8559
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
8560
+ }
8561
+ if (dataLines.length > 0) {
8562
+ const terminal = await processEventPayload(dataLines.join("\n"));
8563
+ if (terminal) {
8564
+ sseController.abort();
8565
+ return terminal;
8566
+ }
8567
+ }
8568
+ sepIdx = buffer.indexOf("\n\n");
8569
+ }
8570
+ }
8571
+ } finally {
8572
+ reader.releaseLock();
8573
+ }
8574
+ flushText();
8575
+ if (ctx.signal.aborted) {
8576
+ await ensureInterrupt(trackedSessionIds);
8577
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
8578
+ }
8579
+ await ensureInterrupt(trackedSessionIds);
8580
+ return { ok: false, sessionId, errorMessage: "OpenCode \u4E8B\u4EF6\u6D41\u63D0\u524D\u65AD\u5F00\uFF0C\u5DF2\u4E2D\u6B62\u8FDC\u7AEF\u4F1A\u8BDD" };
8581
+ } catch (error) {
8582
+ if (ctx.signal.aborted) {
8583
+ await ensureInterrupt();
8584
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
8585
+ }
8586
+ if (sessionId) await ensureInterrupt();
8587
+ const msg = sanitizeErrorDetail(error instanceof Error ? error.message : String(error), 300) || "Runner \u6267\u884C\u5F02\u5E38";
8588
+ return { ok: false, sessionId, errorMessage: msg };
8589
+ } finally {
8590
+ sseController.abort();
8591
+ ctx.signal.removeEventListener("abort", onOuterAbort);
8592
+ }
8593
+ }
8594
+ };
8595
+
8225
8596
  // src/worker/index.ts
8226
8597
  import { fileURLToPath as fileURLToPath3 } from "url";
8227
8598
  import { existsSync as existsSync2 } from "fs";
@@ -8329,6 +8700,28 @@ function topLevelSessionId(event) {
8329
8700
 
8330
8701
  // src/core/opencode-cli.ts
8331
8702
  import { spawn, spawnSync } from "child_process";
8703
+
8704
+ // src/core/env-sanitize.ts
8705
+ var GATEWAY_SECRET_ENV_KEYS = [
8706
+ "SUPERTASK_API_TOKEN",
8707
+ "SUPERTASK_WEBHOOK_SECRET",
8708
+ "SUPERTASK_WEBHOOK_URL",
8709
+ "OPENCODE_PASSWORD",
8710
+ "OPENCODE_SERVER_PASSWORD"
8711
+ ];
8712
+ function sanitizedChildEnv(baseEnv = process.env, overrides = {}) {
8713
+ const env = { ...baseEnv };
8714
+ for (const key of GATEWAY_SECRET_ENV_KEYS) {
8715
+ delete env[key];
8716
+ }
8717
+ for (const [key, value] of Object.entries(overrides)) {
8718
+ if (value === void 0) delete env[key];
8719
+ else env[key] = value;
8720
+ }
8721
+ return env;
8722
+ }
8723
+
8724
+ // src/core/opencode-cli.ts
8332
8725
  var OpenCodeInvocationError = class extends Error {
8333
8726
  };
8334
8727
  var VERSION_TIMEOUT_MS = 15e3;
@@ -8350,7 +8743,7 @@ function detectOpenCodeVersion(executable = openCodeExecutable(), options = {})
8350
8743
  const result = new Promise((resolve2, reject) => {
8351
8744
  const child = spawn(executable, ["--version"], {
8352
8745
  cwd: options.cwd,
8353
- env: process.env,
8746
+ env: sanitizedChildEnv(process.env),
8354
8747
  stdio: ["ignore", "pipe", "pipe"]
8355
8748
  });
8356
8749
  let output = "";
@@ -8454,12 +8847,14 @@ var WorkerEngine = class {
8454
8847
  settlementRetryWakeups = /* @__PURE__ */ new Set();
8455
8848
  cfg;
8456
8849
  opencodeBin;
8850
+ runner;
8457
8851
  maxOutputChars;
8458
8852
  settlementRetryDelaysMs;
8459
8853
  settlementRetryIntervalMs;
8460
8854
  constructor(cfg, options = {}) {
8461
8855
  this.cfg = cfg.worker;
8462
8856
  this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
8857
+ this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
8463
8858
  this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
8464
8859
  this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
8465
8860
  this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
@@ -8508,7 +8903,7 @@ var WorkerEngine = class {
8508
8903
  if (this.pollCyclePromise) await this.pollCyclePromise;
8509
8904
  if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
8510
8905
  const deadline = Date.now() + gracePeriodMs;
8511
- while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
8906
+ while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (!entry.child || entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
8512
8907
  await Bun.sleep(Math.min(50, deadline - Date.now()));
8513
8908
  }
8514
8909
  }
@@ -8593,7 +8988,7 @@ var WorkerEngine = class {
8593
8988
  while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
8594
8989
  const databaseRunningCount = await TaskService.countRunning();
8595
8990
  if (databaseRunningCount >= this.cfg.maxConcurrency) break;
8596
- const openCode = await detectOpenCodeVersion(this.opencodeBin);
8991
+ const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
8597
8992
  if (this.stopped) break;
8598
8993
  let task;
8599
8994
  try {
@@ -8627,7 +9022,7 @@ var WorkerEngine = class {
8627
9022
  workerPid: process.pid,
8628
9023
  lockedAt: Date.now(),
8629
9024
  lockedBy: launchIdentity,
8630
- launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
9025
+ launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
8631
9026
  });
8632
9027
  runId = run.id;
8633
9028
  if (this.stopped) {
@@ -8656,6 +9051,10 @@ var WorkerEngine = class {
8656
9051
  this.releaseBatch(task);
8657
9052
  continue;
8658
9053
  }
9054
+ if (this.runner) {
9055
+ this.executeViaRunner(task, run.id, launchIdentity, this.runner);
9056
+ continue;
9057
+ }
8659
9058
  let args;
8660
9059
  try {
8661
9060
  args = buildOpenCodeRunArgs(openCode.major, {
@@ -8714,6 +9113,96 @@ var WorkerEngine = class {
8714
9113
  if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
8715
9114
  return entry;
8716
9115
  }
9116
+ executeViaRunner(task, runId, launchIdentity, runner) {
9117
+ const cwd = task.cwd || process.cwd();
9118
+ const abortController = new AbortController();
9119
+ const model = this.resolveModel(task.model);
9120
+ const variant = this.resolveVariant(task.variant);
9121
+ const entry = {
9122
+ task,
9123
+ runId,
9124
+ sessionId: null,
9125
+ launchIdentity,
9126
+ child: null,
9127
+ runnerAbort: abortController,
9128
+ commandContext: runCommandContext(`runner:${runner.name}`, [task.agent], cwd),
9129
+ output: new RunOutput(
9130
+ this.maxOutputChars,
9131
+ (sessionId) => {
9132
+ entry.sessionId = sessionId;
9133
+ TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
9134
+ this.logError("sessionId update failed", err, task.id);
9135
+ });
9136
+ },
9137
+ (stream, line) => {
9138
+ gatewayEvents.emitRunLog(runId, task.id, stream, line);
9139
+ }
9140
+ ),
9141
+ timeoutTimer: null,
9142
+ termination: null,
9143
+ terminationPromise: null,
9144
+ settlementPromise: null,
9145
+ guardianDrained: true,
9146
+ quarantined: false,
9147
+ settled: false
9148
+ };
9149
+ this.runningTasks.set(task.id, entry);
9150
+ gatewayEvents.emitRunStarted({
9151
+ runId,
9152
+ taskId: task.id,
9153
+ cwd: task.cwd,
9154
+ model,
9155
+ variant
9156
+ });
9157
+ const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
9158
+ if (timeoutMs > 0) {
9159
+ entry.timeoutTimer = setTimeout(() => {
9160
+ this.runDetached(
9161
+ this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
9162
+ "runner timeout termination failed",
9163
+ entry.task.id
9164
+ );
9165
+ }, timeoutMs);
9166
+ entry.timeoutTimer.unref?.();
9167
+ }
9168
+ const runnerPromise = runner.execute({
9169
+ task,
9170
+ runId,
9171
+ cwd,
9172
+ agent: task.agent,
9173
+ model,
9174
+ variant,
9175
+ prompt: task.prompt,
9176
+ title: task.name,
9177
+ metadata: parseTaskMetadata(task.metadata),
9178
+ signal: abortController.signal,
9179
+ onSessionId: (sessionId) => {
9180
+ entry.sessionId = sessionId;
9181
+ TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
9182
+ this.logError("sessionId update failed", err, task.id);
9183
+ });
9184
+ },
9185
+ onOutputChunk: (chunk) => {
9186
+ entry.output.push("stdout", chunk);
9187
+ }
9188
+ }).then((result) => {
9189
+ if (entry.settled || entry.termination) return;
9190
+ this.runDetached(
9191
+ this.settleEntry(entry, result.ok ? 0 : 1, result.ok ? void 0 : result.errorMessage || "Runner \u6267\u884C\u5931\u8D25"),
9192
+ "runner settlement failed",
9193
+ entry.task.id
9194
+ );
9195
+ }).catch((error) => {
9196
+ if (entry.settled || entry.termination) return;
9197
+ const msg = error instanceof Error ? error.message : String(error);
9198
+ this.runDetached(
9199
+ this.settleEntry(entry, 1, `Runner \u6267\u884C\u5F02\u5E38\uFF1A${msg}`),
9200
+ "runner error settlement failed",
9201
+ entry.task.id
9202
+ );
9203
+ });
9204
+ entry.runnerDone = runnerPromise;
9205
+ }
8717
9206
  async spawnTask(task, runId, launchIdentity, args) {
8718
9207
  const cwd = task.cwd || process.cwd();
8719
9208
  const childEnv = {
@@ -8880,7 +9369,7 @@ var WorkerEngine = class {
8880
9369
  handleChildClose(entry, code, signal, spawnError) {
8881
9370
  if (entry.settled || entry.termination) return;
8882
9371
  if (!entry.guardianDrained) {
8883
- const pid2 = entry.child.pid;
9372
+ const pid2 = entry.child?.pid;
8884
9373
  const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
8885
9374
  const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
8886
9375
  if (presence !== "not-running") {
@@ -8903,7 +9392,7 @@ var WorkerEngine = class {
8903
9392
  );
8904
9393
  return;
8905
9394
  }
8906
- const pid = entry.child.pid;
9395
+ const pid = entry.child?.pid;
8907
9396
  if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
8908
9397
  if (entry.timeoutTimer) {
8909
9398
  clearTimeout(entry.timeoutTimer);
@@ -9173,6 +9662,17 @@ ${output}` : ""}` : output;
9173
9662
  }
9174
9663
  }
9175
9664
  async killEntry(entry, initialSignal = "SIGTERM") {
9665
+ if (entry.runnerAbort) {
9666
+ entry.runnerAbort.abort();
9667
+ if (entry.runnerDone) {
9668
+ await Promise.race([
9669
+ entry.runnerDone.catch(() => void 0),
9670
+ new Promise((resolve2) => setTimeout(resolve2, 5e3))
9671
+ ]);
9672
+ }
9673
+ return true;
9674
+ }
9675
+ if (!entry.child) return true;
9176
9676
  const pid = entry.child.pid;
9177
9677
  if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
9178
9678
  if (!pid) return false;
@@ -9188,7 +9688,7 @@ ${output}` : ""}` : output;
9188
9688
  return waitForSpawnedProcessTreeExit(pid, 2500);
9189
9689
  }
9190
9690
  signalEntry(entry, signal) {
9191
- const pid = entry.child.pid;
9691
+ const pid = entry.child?.pid;
9192
9692
  if (!pid) return "not-running";
9193
9693
  return signalRecordedProcessTreeWithResult(
9194
9694
  pid,