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.
Files changed (80) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +10 -0
  3. package/README.zh-CN.md +10 -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-J34FWHQU.js → chunk-ETLJ4YXW.js} +3 -2
  7. package/dist/cli/chunk-ETLJ4YXW.js.map +1 -0
  8. package/dist/cli/{chunk-AZM76ISG.js → chunk-INW2NH3O.js} +6 -5
  9. package/dist/cli/chunk-INW2NH3O.js.map +1 -0
  10. package/dist/cli/{chunk-CMEP6IB4.js → chunk-K6UTYKN5.js} +19 -5
  11. package/dist/cli/{chunk-CMEP6IB4.js.map → chunk-K6UTYKN5.js.map} +1 -1
  12. package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
  13. package/dist/cli/{chunk-DF56RPNL.js → chunk-MZLIVCEU.js} +10 -2
  14. package/dist/cli/{chunk-DF56RPNL.js.map → chunk-MZLIVCEU.js.map} +1 -1
  15. package/dist/cli/{chunk-5VKFECHP.js → chunk-OJLDJVHB.js} +3 -3
  16. package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
  17. package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
  18. package/dist/cli/{chunk-EQWICVCJ.js → chunk-XUCZLWCB.js} +48 -6
  19. package/dist/cli/chunk-XUCZLWCB.js.map +1 -0
  20. package/dist/cli/{chunk-YB7MYTE5.js → chunk-XWTKMNNI.js} +3 -1
  21. package/dist/cli/chunk-XWTKMNNI.js.map +1 -0
  22. package/dist/cli/{chunk-DIJEKFBV.js → chunk-YADLWDYK.js} +4 -4
  23. package/dist/cli/{chunk-YGELD2E5.js → chunk-ZIR7RA5B.js} +7 -4
  24. package/dist/cli/{chunk-YGELD2E5.js.map → chunk-ZIR7RA5B.js.map} +1 -1
  25. package/dist/cli/database-maintenance.service-NQBZ5VJT.js +16 -0
  26. package/dist/cli/{db-H7GIFWS2.js → db-KWSXP22E.js} +2 -2
  27. package/dist/cli/{doctor-smoke-QXHF7UNN.js → doctor-smoke-6VU2KCRK.js} +7 -7
  28. package/dist/cli/{gateway-BYLLK72W.js → gateway-I2SQOXWB.js} +686 -24
  29. package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
  30. package/dist/cli/{gateway-wake-U4HTV56Q.js → gateway-wake-M5EXAIGD.js} +2 -2
  31. package/dist/cli/index.js +38 -38
  32. package/dist/cli/{job-templates-RPQJ4XXW.js → job-templates-FH7SGS34.js} +5 -5
  33. package/dist/cli/{logs-QD2N62KK.js → logs-HB5RV7HD.js} +7 -7
  34. package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
  35. package/dist/cli/task-run.service-R45W2VID.js +15 -0
  36. package/dist/cli/task-template.service-VA4WBJA4.js +12 -0
  37. package/dist/cli/{task.service-ZVDJ6VSQ.js → task.service-RB6RKV7T.js} +3 -3
  38. package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
  39. package/dist/cli/{web-J3FJ23FE.js → web-4QWJ4Z5K.js} +157 -17
  40. package/dist/cli/{web-J3FJ23FE.js.map → web-4QWJ4Z5K.js.map} +1 -1
  41. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
  42. package/dist/gateway/index.d.ts +1 -0
  43. package/dist/gateway/index.js +929 -31
  44. package/dist/gateway/index.js.map +1 -1
  45. package/dist/plugin/supertask.js +106 -11
  46. package/dist/plugin/supertask.js.map +1 -1
  47. package/dist/web/index.js +235 -16
  48. package/dist/web/index.js.map +1 -1
  49. package/dist/worker/index.d.ts +492 -1
  50. package/dist/worker/index.js +728 -20
  51. package/dist/worker/index.js.map +1 -1
  52. package/dist/worker/launcher.js.map +1 -1
  53. package/drizzle/0010_task_metadata.sql +2 -0
  54. package/drizzle/meta/0010_snapshot.json +695 -0
  55. package/drizzle/meta/_journal.json +7 -0
  56. package/package.json +1 -1
  57. package/dist/cli/chunk-AZM76ISG.js.map +0 -1
  58. package/dist/cli/chunk-EQWICVCJ.js.map +0 -1
  59. package/dist/cli/chunk-J34FWHQU.js.map +0 -1
  60. package/dist/cli/chunk-LX5CBJLP.js.map +0 -1
  61. package/dist/cli/chunk-NCT3ETTK.js.map +0 -1
  62. package/dist/cli/chunk-YB7MYTE5.js.map +0 -1
  63. package/dist/cli/database-maintenance.service-F3IZU52F.js +0 -16
  64. package/dist/cli/gateway-BYLLK72W.js.map +0 -1
  65. package/dist/cli/task-run.service-QMDINJKG.js +0 -15
  66. package/dist/cli/task-template.service-SZBKGLCB.js +0 -12
  67. /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
  68. /package/dist/cli/{chunk-5VKFECHP.js.map → chunk-OJLDJVHB.js.map} +0 -0
  69. /package/dist/cli/{chunk-DIJEKFBV.js.map → chunk-YADLWDYK.js.map} +0 -0
  70. /package/dist/cli/{database-maintenance.service-F3IZU52F.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
  71. /package/dist/cli/{db-H7GIFWS2.js.map → db-KWSXP22E.js.map} +0 -0
  72. /package/dist/cli/{doctor-smoke-QXHF7UNN.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
  73. /package/dist/cli/{gateway-wake-U4HTV56Q.js.map → gateway-wake-M5EXAIGD.js.map} +0 -0
  74. /package/dist/cli/{job-templates-RPQJ4XXW.js.map → job-templates-FH7SGS34.js.map} +0 -0
  75. /package/dist/cli/{logs-QD2N62KK.js.map → logs-HB5RV7HD.js.map} +0 -0
  76. /package/dist/cli/{pm2-WY644BUO.js.map → pm2-YSCAIIBU.js.map} +0 -0
  77. /package/dist/cli/{task-run.service-QMDINJKG.js.map → task-run.service-R45W2VID.js.map} +0 -0
  78. /package/dist/cli/{task-template.service-SZBKGLCB.js.map → task-template.service-VA4WBJA4.js.map} +0 -0
  79. /package/dist/cli/{task.service-ZVDJ6VSQ.js.map → task.service-RB6RKV7T.js.map} +0 -0
  80. /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
@@ -6068,7 +6068,9 @@ var init_schema = __esm({
6068
6068
  retryAfter: integer("retry_after"),
6069
6069
  timeoutMs: integer("timeout_ms"),
6070
6070
  templateId: integer("template_id"),
6071
- scheduledAt: integer("scheduled_at")
6071
+ scheduledAt: integer("scheduled_at"),
6072
+ // 调用方不透明元数据(JSON 对象字符串,供上层平台存储归属/应用标识等)
6073
+ metadata: text("metadata")
6072
6074
  }, (table) => [
6073
6075
  index("tasks_queue_idx").on(table.status, table.retryAfter, table.urgency, table.importance, table.createdAt, table.id),
6074
6076
  index("tasks_batch_status_idx").on(table.batchId, table.status),
@@ -6148,7 +6150,8 @@ var init_schema = __esm({
6148
6150
  nextRunAt: integer("next_run_at"),
6149
6151
  enabled: integer("enabled", { mode: "boolean" }).default(true),
6150
6152
  createdAt: integer("created_at").default(0),
6151
- updatedAt: integer("updated_at").default(0)
6153
+ updatedAt: integer("updated_at").default(0),
6154
+ metadata: text("metadata")
6152
6155
  }, (table) => [
6153
6156
  index("task_templates_due_idx").on(table.enabled, table.nextRunAt, table.id),
6154
6157
  index("task_templates_retention_idx").on(
@@ -6314,7 +6317,7 @@ var init_db2 = __esm({
6314
6317
  init_schema();
6315
6318
  DEFAULT_DB_PATH = join(homedir(), ".local/share/opencode/tasks.db");
6316
6319
  DB_FILE_PATH = process.env.SUPERTASK_DB_PATH || DEFAULT_DB_PATH;
6317
- EXPECTED_SCHEMA_USER_VERSION = 10;
6320
+ EXPECTED_SCHEMA_USER_VERSION = 11;
6318
6321
  _sqlite = null;
6319
6322
  _db = null;
6320
6323
  _migrationRan = false;
@@ -6554,6 +6557,47 @@ var init_model_variant = __esm({
6554
6557
  }
6555
6558
  });
6556
6559
 
6560
+ // src/core/metadata.ts
6561
+ function normalizeTaskMetadata(input) {
6562
+ if (input === void 0) return void 0;
6563
+ if (input === null || input === "") return null;
6564
+ let parsed = input;
6565
+ if (typeof input === "string") {
6566
+ const trimmed = input.trim();
6567
+ if (!trimmed) return null;
6568
+ try {
6569
+ parsed = JSON.parse(trimmed);
6570
+ } catch {
6571
+ throw new Error("metadata \u5FC5\u987B\u662F\u5408\u6CD5\u7684 JSON \u5BF9\u8C61");
6572
+ }
6573
+ }
6574
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
6575
+ throw new Error("metadata \u5FC5\u987B\u662F JSON \u5BF9\u8C61");
6576
+ }
6577
+ const serialized = JSON.stringify(parsed);
6578
+ if (Buffer.byteLength(serialized, "utf8") > MAX_METADATA_BYTES) {
6579
+ throw new Error(`metadata \u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7 ${MAX_METADATA_BYTES} \u5B57\u8282`);
6580
+ }
6581
+ return serialized;
6582
+ }
6583
+ function parseTaskMetadata(raw2) {
6584
+ if (!raw2 || typeof raw2 !== "string") return null;
6585
+ try {
6586
+ const parsed = JSON.parse(raw2);
6587
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
6588
+ return parsed;
6589
+ } catch {
6590
+ return null;
6591
+ }
6592
+ }
6593
+ var MAX_METADATA_BYTES;
6594
+ var init_metadata = __esm({
6595
+ "src/core/metadata.ts"() {
6596
+ "use strict";
6597
+ MAX_METADATA_BYTES = 16 * 1024;
6598
+ }
6599
+ });
6600
+
6557
6601
  // src/core/services/task.service.ts
6558
6602
  function validateIntegerField(name, value, min, max) {
6559
6603
  if (value === void 0 || value === null) return;
@@ -6836,6 +6880,7 @@ var init_task_service = __esm({
6836
6880
  init_task_working_directory();
6837
6881
  init_task_batch();
6838
6882
  init_model_variant();
6883
+ init_metadata();
6839
6884
  ({ tasks: tasks2, taskRuns: taskRuns2 } = schema_exports);
6840
6885
  cleanupInvocation = 0;
6841
6886
  TaskDeletionConflictError = class extends Error {
@@ -7035,7 +7080,8 @@ var init_task_service = __esm({
7035
7080
  const normalizedData = {
7036
7081
  ...data,
7037
7082
  batchId: normalizeTaskBatchId(data.batchId),
7038
- variant: normalizeModelVariant(data.variant)
7083
+ variant: normalizeModelVariant(data.variant),
7084
+ metadata: normalizeTaskMetadata(data.metadata) ?? null
7039
7085
  };
7040
7086
  this.validateNewTask(normalizedData);
7041
7087
  return db.transaction((tx) => {
@@ -7078,7 +7124,8 @@ var init_task_service = __esm({
7078
7124
  dependsOn: overrides.dependsOn === void 0 ? null : overrides.dependsOn,
7079
7125
  maxRetries: overrides.maxRetries ?? original.maxRetries ?? 3,
7080
7126
  retryBackoffMs: overrides.retryBackoffMs ?? original.retryBackoffMs ?? 3e4,
7081
- timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs
7127
+ timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs,
7128
+ metadata: overrides.metadata === void 0 ? original.metadata : overrides.metadata
7082
7129
  });
7083
7130
  }
7084
7131
  static async update(id, data, scope = {}) {
@@ -7086,7 +7133,8 @@ var init_task_service = __esm({
7086
7133
  const normalizedData = {
7087
7134
  ...data,
7088
7135
  ...data.batchId === void 0 ? {} : { batchId: normalizeTaskBatchId(data.batchId) ?? null },
7089
- ...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null }
7136
+ ...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null },
7137
+ ...data.metadata === void 0 ? {} : { metadata: normalizeTaskMetadata(data.metadata) ?? null }
7090
7138
  };
7091
7139
  return db.transaction((tx) => {
7092
7140
  const task = tx.select().from(tasks2).where(and(
@@ -7679,7 +7727,8 @@ var init_task_service = __esm({
7679
7727
  retryAfter: tasks2.retryAfter,
7680
7728
  timeoutMs: tasks2.timeoutMs,
7681
7729
  templateId: tasks2.templateId,
7682
- scheduledAt: tasks2.scheduledAt
7730
+ scheduledAt: tasks2.scheduledAt,
7731
+ metadata: tasks2.metadata
7683
7732
  }).from(tasks2) : db.select().from(tasks2)).$dynamic();
7684
7733
  if (conditions.length > 0) {
7685
7734
  query = query.where(and(...conditions));
@@ -7719,6 +7768,7 @@ var init_task_service = __esm({
7719
7768
  timeoutMs: tasks2.timeoutMs,
7720
7769
  templateId: tasks2.templateId,
7721
7770
  scheduledAt: tasks2.scheduledAt,
7771
+ metadata: tasks2.metadata,
7722
7772
  hasResultLog: sql`CASE WHEN ${tasks2.resultLog} IS NOT NULL AND length(${tasks2.resultLog}) > 0 THEN 1 ELSE 0 END`,
7723
7773
  resultLogPreview: sql`CASE WHEN ${tasks2.resultLog} IS NULL THEN NULL WHEN ${tasks2.status} IN ('failed', 'dead_letter') THEN substr(${tasks2.resultLog}, -512) ELSE substr(${tasks2.resultLog}, 1, 512) END`
7724
7774
  }).from(tasks2).$dynamic();
@@ -8194,12 +8244,13 @@ function isMatchingDrainProof(message, launchIdentity) {
8194
8244
  const candidate = message;
8195
8245
  return candidate.type === DRAIN_PROOF_MESSAGE_TYPE && candidate.identity === launchIdentity;
8196
8246
  }
8197
- var LEGACY_GUARDIAN_LAUNCH_PROTOCOL, TOKEN_GUARDIAN_LAUNCH_PROTOCOL, LAUNCH_IDENTITY_ARGUMENT, DRAIN_PROOF_MESSAGE_TYPE, DRAIN_PROOF_ACK_MESSAGE_TYPE, MANAGED_RUN_ENV, MANAGED_RUN_ENV_VALUE;
8247
+ var LEGACY_GUARDIAN_LAUNCH_PROTOCOL, TOKEN_GUARDIAN_LAUNCH_PROTOCOL, HTTP_RUNNER_LAUNCH_PROTOCOL, LAUNCH_IDENTITY_ARGUMENT, DRAIN_PROOF_MESSAGE_TYPE, DRAIN_PROOF_ACK_MESSAGE_TYPE, MANAGED_RUN_ENV, MANAGED_RUN_ENV_VALUE;
8198
8248
  var init_launch_protocol = __esm({
8199
8249
  "src/core/launch-protocol.ts"() {
8200
8250
  "use strict";
8201
8251
  LEGACY_GUARDIAN_LAUNCH_PROTOCOL = "gated-v2-guardian";
8202
8252
  TOKEN_GUARDIAN_LAUNCH_PROTOCOL = "gated-v3-token-guardian";
8253
+ HTTP_RUNNER_LAUNCH_PROTOCOL = "runner:opencode-server";
8203
8254
  LAUNCH_IDENTITY_ARGUMENT = "--supertask-launch-identity";
8204
8255
  DRAIN_PROOF_MESSAGE_TYPE = "supertask-drained";
8205
8256
  DRAIN_PROOF_ACK_MESSAGE_TYPE = "supertask-drained-ack";
@@ -9029,6 +9080,7 @@ function getGatewayHealth(now = Date.now()) {
9029
9080
  pid: process.pid,
9030
9081
  dbPath: DB_FILE_PATH,
9031
9082
  uptimeMs: state ? Math.max(0, now - state.startedAt) : 0,
9083
+ maxConcurrency: state?.config.workerMaxConcurrency ?? 0,
9032
9084
  lock,
9033
9085
  components: { worker, scheduler, watchdog, watchdogCleanup }
9034
9086
  };
@@ -9283,6 +9335,32 @@ var init_events = __esm({
9283
9335
  }
9284
9336
  });
9285
9337
 
9338
+ // src/core/env-sanitize.ts
9339
+ function sanitizedChildEnv(baseEnv = process.env, overrides = {}) {
9340
+ const env = { ...baseEnv };
9341
+ for (const key of GATEWAY_SECRET_ENV_KEYS) {
9342
+ delete env[key];
9343
+ }
9344
+ for (const [key, value] of Object.entries(overrides)) {
9345
+ if (value === void 0) delete env[key];
9346
+ else env[key] = value;
9347
+ }
9348
+ return env;
9349
+ }
9350
+ var GATEWAY_SECRET_ENV_KEYS;
9351
+ var init_env_sanitize = __esm({
9352
+ "src/core/env-sanitize.ts"() {
9353
+ "use strict";
9354
+ GATEWAY_SECRET_ENV_KEYS = [
9355
+ "SUPERTASK_API_TOKEN",
9356
+ "SUPERTASK_WEBHOOK_SECRET",
9357
+ "SUPERTASK_WEBHOOK_URL",
9358
+ "OPENCODE_PASSWORD",
9359
+ "OPENCODE_SERVER_PASSWORD"
9360
+ ];
9361
+ }
9362
+ });
9363
+
9286
9364
  // src/core/opencode-cli.ts
9287
9365
  import { spawn, spawnSync } from "child_process";
9288
9366
  function openCodeExecutable() {
@@ -9301,7 +9379,7 @@ function detectOpenCodeVersion(executable = openCodeExecutable(), options = {})
9301
9379
  const result = new Promise((resolve4, reject) => {
9302
9380
  const child = spawn(executable, ["--version"], {
9303
9381
  cwd: options.cwd,
9304
- env: process.env,
9382
+ env: sanitizedChildEnv(process.env),
9305
9383
  stdio: ["ignore", "pipe", "pipe"]
9306
9384
  });
9307
9385
  let output = "";
@@ -9376,6 +9454,7 @@ var OpenCodeInvocationError, VERSION_TIMEOUT_MS, VERSION_CACHE_MS, versionCache;
9376
9454
  var init_opencode_cli = __esm({
9377
9455
  "src/core/opencode-cli.ts"() {
9378
9456
  "use strict";
9457
+ init_env_sanitize();
9379
9458
  OpenCodeInvocationError = class extends Error {
9380
9459
  };
9381
9460
  VERSION_TIMEOUT_MS = 15e3;
@@ -18586,6 +18665,7 @@ var init_task_template_service = __esm({
18586
18665
  init_cron_parser();
18587
18666
  init_task_batch();
18588
18667
  init_model_variant();
18668
+ init_metadata();
18589
18669
  init_task_service();
18590
18670
  ({ taskTemplates: taskTemplates2 } = schema_exports);
18591
18671
  TaskTemplateService = class {
@@ -18593,7 +18673,8 @@ var init_task_template_service = __esm({
18593
18673
  const normalizedData = {
18594
18674
  ...data,
18595
18675
  batchId: normalizeTaskBatchId(data.batchId),
18596
- variant: normalizeModelVariant(data.variant)
18676
+ variant: normalizeModelVariant(data.variant),
18677
+ metadata: normalizeTaskMetadata(data.metadata) ?? null
18597
18678
  };
18598
18679
  this.validate(normalizedData);
18599
18680
  const now = Date.now();
@@ -18629,6 +18710,17 @@ var init_task_template_service = __esm({
18629
18710
  static async list(limit = 50, offset = 0) {
18630
18711
  return await db.select().from(taskTemplates2).orderBy(desc(taskTemplates2.createdAt), desc(taskTemplates2.id)).limit(limit).offset(offset);
18631
18712
  }
18713
+ static async listFiltered(options = {}) {
18714
+ const conditions = [];
18715
+ if (options.cwd) conditions.push(eq(taskTemplates2.cwd, options.cwd));
18716
+ if (options.enabled !== void 0) conditions.push(eq(taskTemplates2.enabled, options.enabled));
18717
+ let query = db.select().from(taskTemplates2).$dynamic();
18718
+ if (conditions.length > 0) query = query.where(and(...conditions));
18719
+ query = query.orderBy(desc(taskTemplates2.enabled), desc(taskTemplates2.id));
18720
+ if (options.limit) query = query.limit(options.limit);
18721
+ if (options.offset) query = query.offset(options.offset);
18722
+ return await query;
18723
+ }
18632
18724
  static async stats() {
18633
18725
  const result = await db.select({
18634
18726
  total: sql`count(*)`,
@@ -18646,7 +18738,8 @@ var init_task_template_service = __esm({
18646
18738
  const normalizedData = {
18647
18739
  ...data,
18648
18740
  batchId: normalizeTaskBatchId(data.batchId) ?? null,
18649
- ...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null }
18741
+ ...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null },
18742
+ ...data.metadata === void 0 ? {} : { metadata: normalizeTaskMetadata(data.metadata) ?? null }
18650
18743
  };
18651
18744
  this.validate(normalizedData);
18652
18745
  const now = Date.now();
@@ -18820,7 +18913,8 @@ function createTaskFromTemplate(templateId, options) {
18820
18913
  retryBackoffMs: tmpl.retryBackoffMs ?? 3e4,
18821
18914
  timeoutMs: tmpl.timeoutMs,
18822
18915
  templateId: tmpl.id,
18823
- scheduledAt: options.advanceSchedule ? tmpl.nextRunAt ?? nowMs : nowMs
18916
+ scheduledAt: options.advanceSchedule ? tmpl.nextRunAt ?? nowMs : nowMs,
18917
+ metadata: tmpl.metadata ?? null
18824
18918
  }).returning().get();
18825
18919
  if (options.advanceSchedule) {
18826
18920
  tx.update(taskTemplates3).set({
@@ -21108,7 +21202,7 @@ function runOpenCode(executable, args, cwd, timeoutMs) {
21108
21202
  const child = spawn3(executable, args, {
21109
21203
  cwd,
21110
21204
  // OpenCode 以 PWD 优先解析项目目录(2.x run/api 与 1.x TUI 均如此),必须与 cwd 一致。
21111
- env: { ...process.env, PWD: cwd },
21205
+ env: sanitizedChildEnv(process.env, { PWD: cwd }),
21112
21206
  stdio: ["ignore", "pipe", "pipe"],
21113
21207
  detached: process.platform !== "win32"
21114
21208
  });
@@ -21356,6 +21450,7 @@ var init_opencode_catalog = __esm({
21356
21450
  "use strict";
21357
21451
  init_task_working_directory();
21358
21452
  init_opencode_cli();
21453
+ init_env_sanitize();
21359
21454
  CATALOG_CACHE_MS = 3e4;
21360
21455
  COMMAND_TIMEOUT_MS = 2e4;
21361
21456
  MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
@@ -27499,7 +27594,8 @@ function parseTaskPayload(value) {
27499
27594
  urgency: integer2("urgency", 3),
27500
27595
  maxRetries: integer2("maxRetries", 3),
27501
27596
  retryBackoffMs: duration("retryBackoff", "30s", true),
27502
- timeoutMs: duration("timeout", null)
27597
+ timeoutMs: duration("timeout", null),
27598
+ ...Object.hasOwn(input, "metadata") ? { metadata: normalizeTaskMetadata(input.metadata) } : {}
27503
27599
  };
27504
27600
  }
27505
27601
  function editableTaskPayload(input) {
@@ -27515,7 +27611,8 @@ function editableTaskPayload(input) {
27515
27611
  urgency: input.urgency ?? 3,
27516
27612
  maxRetries: input.maxRetries ?? 3,
27517
27613
  retryBackoffMs: input.retryBackoffMs ?? 3e4,
27518
- timeoutMs: input.timeoutMs ?? null
27614
+ timeoutMs: input.timeoutMs ?? null,
27615
+ ...input.metadata === void 0 ? {} : { metadata: input.metadata }
27519
27616
  };
27520
27617
  }
27521
27618
  function parseCloneOverrides(value) {
@@ -27578,6 +27675,9 @@ function parseCloneOverrides(value) {
27578
27675
  if (Object.hasOwn(input, "timeout")) {
27579
27676
  overrides.timeoutMs = duration("timeout", null);
27580
27677
  }
27678
+ if (Object.hasOwn(input, "metadata")) {
27679
+ overrides.metadata = normalizeTaskMetadata(input.metadata);
27680
+ }
27581
27681
  return overrides;
27582
27682
  }
27583
27683
  function parseTemplatePayload(value) {
@@ -27604,7 +27704,8 @@ function parseTemplatePayload(value) {
27604
27704
  maxInstances: integer2("maxInstances", 1),
27605
27705
  maxRetries: integer2("maxRetries", 3),
27606
27706
  retryBackoffMs: duration("retryBackoff", "30s", true),
27607
- timeoutMs: duration("timeout", null)
27707
+ timeoutMs: duration("timeout", null),
27708
+ ...Object.hasOwn(input, "metadata") ? { metadata: normalizeTaskMetadata(input.metadata) } : {}
27608
27709
  };
27609
27710
  }
27610
27711
  function parseIdArray(value) {
@@ -27624,6 +27725,7 @@ var init_payload = __esm({
27624
27725
  "src/web/payload.ts"() {
27625
27726
  "use strict";
27626
27727
  init_duration();
27728
+ init_metadata();
27627
27729
  }
27628
27730
  });
27629
27731
 
@@ -28135,6 +28237,7 @@ __export(web_exports, {
28135
28237
  sessionCommand: () => sessionCommand,
28136
28238
  setDashboardRuntimeConfig: () => setDashboardRuntimeConfig
28137
28239
  });
28240
+ import { timingSafeEqual } from "crypto";
28138
28241
  import {
28139
28242
  existsSync as existsSync7,
28140
28243
  mkdirSync as mkdirSync3,
@@ -28340,6 +28443,15 @@ data: ${JSON.stringify(data)}
28340
28443
 
28341
28444
  `);
28342
28445
  }
28446
+ function isValidApiBearerToken(headerValue, expected) {
28447
+ if (!headerValue) return false;
28448
+ const match2 = /^Bearer\s+(.+)$/i.exec(headerValue.trim());
28449
+ if (!match2) return false;
28450
+ const provided = Buffer.from(match2[1], "utf8");
28451
+ const target = Buffer.from(expected, "utf8");
28452
+ if (provided.length !== target.length) return false;
28453
+ return timingSafeEqual(provided, target);
28454
+ }
28343
28455
  function canonicalizeDbPath(filePath) {
28344
28456
  if (filePath === ":memory:") return filePath;
28345
28457
  try {
@@ -28360,6 +28472,7 @@ var init_web = __esm({
28360
28472
  init_dist();
28361
28473
  init_drizzle_orm();
28362
28474
  init_db2();
28475
+ init_metadata();
28363
28476
  init_opencode_catalog();
28364
28477
  init_opencode_cli();
28365
28478
  init_task_batch();
@@ -28434,6 +28547,14 @@ var init_web = __esm({
28434
28547
  }
28435
28548
  return next();
28436
28549
  });
28550
+ app.use("/api/*", async (c, next) => {
28551
+ const configured = process.env.SUPERTASK_API_TOKEN?.trim();
28552
+ if (!configured) return next();
28553
+ if (!isValidApiBearerToken(c.req.header("Authorization"), configured)) {
28554
+ return c.json({ error: "Unauthorized" }, 401);
28555
+ }
28556
+ return next();
28557
+ });
28437
28558
  app.get("/assets/app.css", (c) => serveAppCss(c));
28438
28559
  app.get("/assets/app.js", (c) => serveAppJs(c));
28439
28560
  for (const locale of SUPPORTED_LOCALES) {
@@ -28450,6 +28571,7 @@ var init_web = __esm({
28450
28571
  return c.body(null, 204);
28451
28572
  });
28452
28573
  app.get("/api/events", (c) => {
28574
+ const scopeCwd = c.req.query("cwd")?.trim() || "";
28453
28575
  const encoder = new TextEncoder();
28454
28576
  let cleanup = null;
28455
28577
  const stream = new ReadableStream({
@@ -28464,6 +28586,10 @@ var init_web = __esm({
28464
28586
  }
28465
28587
  };
28466
28588
  const unsubscribe = gatewayEvents.subscribe((event) => {
28589
+ if (scopeCwd) {
28590
+ const eventCwd = "cwd" in event ? event.cwd : void 0;
28591
+ if (eventCwd !== void 0 && eventCwd !== scopeCwd) return;
28592
+ }
28467
28593
  safeEnqueue(formatSseFrame(event.type, event));
28468
28594
  }, { excludeRunLogs: true });
28469
28595
  const keepalive = setInterval(() => {
@@ -28811,12 +28937,28 @@ data: ${JSON.stringify({ ts: Date.now() })}
28811
28937
  TaskService.listCompact(listOptions),
28812
28938
  countFilteredTasks(listOptions)
28813
28939
  ]);
28814
- const latestRuns = await TaskRunService.getLatestMetaByTaskIds(tasks4.map((task) => task.id));
28940
+ const taskIds = tasks4.map((task) => task.id);
28941
+ const latestRuns = await TaskRunService.getLatestMetaByTaskIds(taskIds);
28942
+ const runCountMap = /* @__PURE__ */ new Map();
28943
+ if (taskIds.length > 0) {
28944
+ const placeholders = taskIds.map(() => "?").join(",");
28945
+ const countRows = sqlite.prepare(
28946
+ `SELECT task_id AS taskId, COUNT(*) AS cnt FROM task_runs WHERE task_id IN (${placeholders}) GROUP BY task_id`
28947
+ ).all(...taskIds);
28948
+ for (const row of countRows) {
28949
+ runCountMap.set(Number(row.taskId), Number(row.cnt));
28950
+ }
28951
+ }
28815
28952
  return c.json({
28816
28953
  tasks: tasks4.map((task) => {
28817
28954
  const run = latestRuns.get(task.id);
28955
+ const runCount = runCountMap.get(task.id) ?? 0;
28956
+ const actualRetries = Math.max(0, runCount - 1);
28957
+ const displayStatus = task.status === "cancelled" && run?.status === "running" ? "cancelling" : task.status ?? "pending";
28818
28958
  return {
28819
28959
  ...task,
28960
+ actualRetries,
28961
+ displayStatus,
28820
28962
  latestRun: run ? {
28821
28963
  id: run.id,
28822
28964
  status: run.status,
@@ -28835,6 +28977,98 @@ data: ${JSON.stringify({ ts: Date.now() })}
28835
28977
  totalPages: Math.max(1, Math.ceil(total / parsedLimit))
28836
28978
  });
28837
28979
  });
28980
+ app.get("/api/stats", (c) => {
28981
+ const cwd = c.req.query("cwd")?.trim() || "";
28982
+ const params = cwd ? [cwd] : [];
28983
+ const whereClause = cwd ? "WHERE cwd = ?" : "";
28984
+ const andClause = cwd ? "AND cwd = ?" : "";
28985
+ const joinAndClause = cwd ? "AND t.cwd = ?" : "";
28986
+ const byStatus = {};
28987
+ let total = 0;
28988
+ const statusRows = sqlite.prepare(
28989
+ `SELECT status, COUNT(*) AS c FROM tasks ${whereClause} GROUP BY status`
28990
+ ).all(...params);
28991
+ for (const row of statusRows) {
28992
+ const count = Number(row.c ?? 0);
28993
+ byStatus[String(row.status ?? "pending")] = count;
28994
+ total += count;
28995
+ }
28996
+ const avgRow = sqlite.prepare(
28997
+ `SELECT AVG((finished_at - started_at) * 1000) AS ms FROM tasks WHERE started_at > 0 AND finished_at > started_at ${andClause}`
28998
+ ).get(...params);
28999
+ const runRows = sqlite.prepare(
29000
+ `SELECT r.started_at AS startedAt, r.finished_at AS finishedAt, r.status AS status
29001
+ FROM task_runs r JOIN tasks t ON t.id = r.task_id
29002
+ WHERE r.started_at > 0 ${joinAndClause}
29003
+ ORDER BY r.started_at ASC, r.id ASC`
29004
+ ).all(...params);
29005
+ const points = [];
29006
+ const nowMs = Date.now();
29007
+ for (const row of runRows) {
29008
+ const s = Number(row.startedAt) * 1e3;
29009
+ const finished = row.finishedAt ? Number(row.finishedAt) * 1e3 : 0;
29010
+ const end = finished || (row.status === "running" ? nowMs : s);
29011
+ points.push({ t: s, delta: 1 });
29012
+ points.push({ t: Math.max(s + 1, end), delta: -1 });
29013
+ }
29014
+ points.sort((a, b) => a.t - b.t || a.delta - b.delta);
29015
+ let cur = 0;
29016
+ let peakConcurrency = 0;
29017
+ for (const point of points) {
29018
+ cur += point.delta;
29019
+ if (cur > peakConcurrency) peakConcurrency = cur;
29020
+ }
29021
+ const runningRow = sqlite.prepare(
29022
+ `SELECT COUNT(*) AS c FROM task_runs r JOIN tasks t ON t.id = r.task_id WHERE r.status = 'running' ${joinAndClause}`
29023
+ ).get(...params);
29024
+ return c.json({
29025
+ byStatus,
29026
+ total,
29027
+ running: Number(runningRow?.c ?? 0),
29028
+ peakConcurrency,
29029
+ avgDurationMs: Math.round(Number(avgRow?.ms ?? 0))
29030
+ });
29031
+ });
29032
+ app.get("/api/runs/by-session/:sessionId", (c) => {
29033
+ const sessionId = c.req.param("sessionId")?.trim() || "";
29034
+ if (!isValidSessionId(sessionId)) {
29035
+ return c.json({ error: "invalid sessionId" }, 400);
29036
+ }
29037
+ const row = sqlite.prepare(
29038
+ `SELECT r.id AS runId, r.task_id AS taskId, r.status AS runStatus,
29039
+ t.template_id AS templateId, t.cwd AS cwd, t.metadata AS metadata, t.status AS taskStatus
29040
+ FROM task_runs r
29041
+ JOIN tasks t ON t.id = r.task_id
29042
+ WHERE r.session_id = ?
29043
+ ORDER BY r.id DESC
29044
+ LIMIT 1`
29045
+ ).get(sessionId);
29046
+ if (!row) return c.json({ error: "not found" }, 404);
29047
+ const templateId = row.templateId != null && Number(row.templateId) > 0 ? Number(row.templateId) : null;
29048
+ return c.json({
29049
+ runId: Number(row.runId),
29050
+ taskId: Number(row.taskId),
29051
+ templateId,
29052
+ cwd: row.cwd ?? null,
29053
+ metadata: parseTaskMetadata(row.metadata),
29054
+ status: row.taskStatus ?? row.runStatus ?? "running"
29055
+ });
29056
+ });
29057
+ app.get("/api/templates", async (c) => {
29058
+ const cwd = c.req.query("cwd")?.trim() || void 0;
29059
+ const enabledParam = c.req.query("enabled");
29060
+ let enabled;
29061
+ if (enabledParam === "true" || enabledParam === "1") enabled = true;
29062
+ else if (enabledParam === "false" || enabledParam === "0") enabled = false;
29063
+ else if (enabledParam !== void 0 && enabledParam !== "") {
29064
+ return c.json({ error: "invalid enabled filter" }, 400);
29065
+ }
29066
+ const limitParam = c.req.query("limit") || "200";
29067
+ const limit = parsePositiveInteger(limitParam);
29068
+ if (limit === null || limit > 500) return c.json({ error: "invalid limit" }, 400);
29069
+ const templates = await TaskTemplateService.listFiltered({ cwd, enabled, limit });
29070
+ return c.json({ templates });
29071
+ });
28838
29072
  app.post("/api/tasks", async (c) => {
28839
29073
  try {
28840
29074
  const task = await TaskService.add(parseTaskPayload(await c.req.json()));
@@ -29535,11 +29769,515 @@ init_task_service();
29535
29769
  init_task_run_service();
29536
29770
  init_health();
29537
29771
  init_events();
29772
+ import { spawn as spawn2 } from "child_process";
29773
+
29774
+ // src/gateway/webhook.ts
29775
+ init_metadata();
29776
+ import { createHmac } from "crypto";
29777
+ var DEFAULT_TIMEOUT_MS = 5e3;
29778
+ var DEFAULT_MAX_ATTEMPTS = 2;
29779
+ var MAX_SUMMARY_CHARS = 2e3;
29780
+ var pendingWebhooks = /* @__PURE__ */ new Set();
29781
+ function signWebhookPayload(secret, timestamp2, body) {
29782
+ const digest = createHmac("sha256", secret).update(`${timestamp2}.${body}`).digest("hex");
29783
+ return `sha256=${digest}`;
29784
+ }
29785
+ function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
29786
+ if (!rawLog) return "";
29787
+ const texts = [];
29788
+ let framed = false;
29789
+ for (const line of rawLog.split("\n")) {
29790
+ const trimmed = line.trim();
29791
+ if (!trimmed) continue;
29792
+ try {
29793
+ const event = JSON.parse(trimmed);
29794
+ if (event.type) framed = true;
29795
+ if (event.type === "text" && typeof event.part?.text === "string" && event.part.text.trim()) {
29796
+ texts.push(event.part.text.trim());
29797
+ } else if (event.type === "error") {
29798
+ const msg = event.error?.data?.message || event.error?.message;
29799
+ if (typeof msg === "string" && msg.trim()) texts.push(msg.trim());
29800
+ } else if (event.type === "tool_use" && event.part?.state?.status === "error" && typeof event.part.state.error === "string" && event.part.state.error.trim()) {
29801
+ texts.push(event.part.state.error.trim());
29802
+ }
29803
+ } catch {
29804
+ if (!framed) texts.push(trimmed);
29805
+ }
29806
+ }
29807
+ const combined = texts.join("\n").trim();
29808
+ if (combined.length <= maxChars) return combined;
29809
+ return `${combined.slice(0, Math.max(0, maxChars - 1))}\u2026`;
29810
+ }
29811
+ function toMs(value) {
29812
+ if (value == null) return null;
29813
+ if (value instanceof Date) return value.getTime();
29814
+ if (typeof value === "number" && Number.isFinite(value)) return value;
29815
+ return null;
29816
+ }
29817
+ function buildTaskWebhookPayload(event, task, run, outputOverride) {
29818
+ const startedAt = toMs(task.startedAt);
29819
+ const finishedAt = toMs(task.finishedAt) ?? Date.now();
29820
+ const durationMs = startedAt != null && finishedAt > startedAt ? finishedAt - startedAt : 0;
29821
+ return {
29822
+ event,
29823
+ timestamp: Date.now(),
29824
+ task: {
29825
+ id: task.id,
29826
+ name: task.name,
29827
+ agent: task.agent,
29828
+ model: task.model ?? null,
29829
+ variant: task.variant ?? null,
29830
+ cwd: task.cwd ?? null,
29831
+ templateId: task.templateId ?? null,
29832
+ status: task.status ?? event.slice("task.".length),
29833
+ metadata: parseTaskMetadata(task.metadata),
29834
+ startedAt,
29835
+ finishedAt,
29836
+ durationMs
29837
+ },
29838
+ run,
29839
+ outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
29840
+ };
29841
+ }
29842
+ function dispatchTaskWebhook(payload, options = {}) {
29843
+ const task = deliverTaskWebhook(payload, options);
29844
+ pendingWebhooks.add(task);
29845
+ void task.finally(() => {
29846
+ pendingWebhooks.delete(task);
29847
+ });
29848
+ return task;
29849
+ }
29850
+ async function deliverTaskWebhook(payload, options = {}) {
29851
+ const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
29852
+ if (!url) return false;
29853
+ try {
29854
+ const parsed = new URL(url);
29855
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
29856
+ } catch {
29857
+ return false;
29858
+ }
29859
+ const secret = (options.secret ?? process.env.SUPERTASK_WEBHOOK_SECRET ?? "").trim();
29860
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
29861
+ const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
29862
+ const fetchFn = options.fetchImpl ?? fetch;
29863
+ const body = JSON.stringify(payload);
29864
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
29865
+ const ts = Date.now();
29866
+ const headers = {
29867
+ "content-type": "application/json",
29868
+ "x-supertask-event": payload.event,
29869
+ "x-supertask-timestamp": String(ts)
29870
+ };
29871
+ if (secret) {
29872
+ headers["x-supertask-signature"] = signWebhookPayload(secret, ts, body);
29873
+ }
29874
+ try {
29875
+ const resp = await fetchFn(url, {
29876
+ method: "POST",
29877
+ headers,
29878
+ body,
29879
+ redirect: "error",
29880
+ signal: AbortSignal.timeout(timeoutMs)
29881
+ });
29882
+ if (resp.ok) return true;
29883
+ if (resp.status >= 400 && resp.status < 500 && resp.status !== 429) {
29884
+ console.warn(JSON.stringify({
29885
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
29886
+ level: "warn",
29887
+ msg: "task webhook rejected",
29888
+ event: payload.event,
29889
+ taskId: payload.task.id,
29890
+ status: resp.status
29891
+ }));
29892
+ return false;
29893
+ }
29894
+ if (attempt >= maxAttempts) {
29895
+ console.warn(JSON.stringify({
29896
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
29897
+ level: "warn",
29898
+ msg: "task webhook delivery exhausted",
29899
+ event: payload.event,
29900
+ taskId: payload.task.id,
29901
+ status: resp.status,
29902
+ attempts: maxAttempts
29903
+ }));
29904
+ return false;
29905
+ }
29906
+ } catch (err) {
29907
+ if (attempt >= maxAttempts) {
29908
+ console.warn(JSON.stringify({
29909
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
29910
+ level: "warn",
29911
+ msg: "task webhook delivery failed",
29912
+ event: payload.event,
29913
+ taskId: payload.task.id,
29914
+ error: err instanceof Error ? err.message : String(err)
29915
+ }));
29916
+ return false;
29917
+ }
29918
+ }
29919
+ if (attempt < maxAttempts) {
29920
+ await new Promise((resolve4) => setTimeout(resolve4, 300 * attempt));
29921
+ }
29922
+ }
29923
+ return false;
29924
+ }
29925
+
29926
+ // src/worker/index.ts
29927
+ init_metadata();
29928
+
29929
+ // src/worker/runners/opencode-server.ts
29930
+ var MAX_SSE_BUFFER_CHARS = 2 * 1024 * 1024;
29931
+ function isLoopbackHost(hostname) {
29932
+ const h = hostname.toLowerCase();
29933
+ return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
29934
+ }
29935
+ function sanitizeErrorDetail(raw2, maxLen = 240) {
29936
+ if (!raw2) return "";
29937
+ return raw2.replace(/(authorization\s*[:=]\s*)(basic|bearer)\s+[^\s,;'"`]+/gi, "$1$2 [REDACTED]").replace(/(basic|bearer)\s+[A-Za-z0-9+/_=-]{12,}/gi, "$1 [REDACTED]").replace(/((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^\s"',;{}]+/gi, "$1[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "sk-[REDACTED]").replace(/\s+/g, " ").trim().slice(0, maxLen);
29938
+ }
29939
+ function parseModelSpec(rawModel, explicitVariant) {
29940
+ if (!rawModel || rawModel === "default") return null;
29941
+ let modelStr = rawModel.trim();
29942
+ let variant = explicitVariant?.trim() || void 0;
29943
+ const hashIdx = modelStr.indexOf("#");
29944
+ if (hashIdx > 0) {
29945
+ const embedded = modelStr.slice(hashIdx + 1).trim();
29946
+ modelStr = modelStr.slice(0, hashIdx).trim();
29947
+ if (!variant && embedded) variant = embedded;
29948
+ }
29949
+ const slashIdx = modelStr.indexOf("/");
29950
+ if (slashIdx <= 0 || slashIdx === modelStr.length - 1) return null;
29951
+ return {
29952
+ providerID: modelStr.slice(0, slashIdx),
29953
+ id: modelStr.slice(slashIdx + 1),
29954
+ ...variant ? { variant } : {}
29955
+ };
29956
+ }
29957
+ var OpenCodeServerRunner = class {
29958
+ name = "opencode-server";
29959
+ baseUrl;
29960
+ password;
29961
+ defaultModel;
29962
+ allowInsecureHttp;
29963
+ fetchFn;
29964
+ constructor(options = {}) {
29965
+ const rawUrl = (options.baseUrl ?? process.env.OPENCODE_URL ?? "").trim();
29966
+ this.baseUrl = rawUrl.replace(/\/+$/, "");
29967
+ this.password = (options.password ?? process.env.OPENCODE_PASSWORD ?? "").trim();
29968
+ this.defaultModel = (options.defaultModel ?? process.env.SUPERTASK_DEFAULT_MODEL ?? process.env.DEFAULT_MODEL ?? "").trim();
29969
+ this.allowInsecureHttp = options.allowInsecureHttp ?? process.env.SUPERTASK_ALLOW_INSECURE_HTTP === "1";
29970
+ this.fetchFn = options.fetchImpl ?? fetch;
29971
+ }
29972
+ authHeaders(extra = {}) {
29973
+ const headers = { ...extra };
29974
+ if (this.password) {
29975
+ headers.authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
29976
+ }
29977
+ return headers;
29978
+ }
29979
+ async interruptSession(sessionId) {
29980
+ try {
29981
+ const resp = await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
29982
+ method: "POST",
29983
+ headers: this.authHeaders(),
29984
+ signal: AbortSignal.timeout(3e3)
29985
+ });
29986
+ return resp.ok;
29987
+ } catch {
29988
+ return false;
29989
+ }
29990
+ }
29991
+ async execute(ctx) {
29992
+ if (!this.baseUrl) {
29993
+ return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_URL \u914D\u7F6E" };
29994
+ }
29995
+ if (!this.password) {
29996
+ return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_PASSWORD \u914D\u7F6E" };
29997
+ }
29998
+ let parsedBaseUrl;
29999
+ try {
30000
+ parsedBaseUrl = new URL(this.baseUrl);
30001
+ } catch {
30002
+ return { ok: false, sessionId: null, errorMessage: "OPENCODE_URL \u4E0D\u662F\u6709\u6548\u7684 HTTP(S) \u5730\u5740" };
30003
+ }
30004
+ if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && (isLoopbackHost(parsedBaseUrl.hostname) || this.allowInsecureHttp))) {
30005
+ return {
30006
+ ok: false,
30007
+ sessionId: null,
30008
+ errorMessage: "\u5B89\u5168\u9650\u5236\uFF1A\u975E\u672C\u673A\u5730\u5740\u7981\u6B62\u901A\u8FC7\u660E\u6587 HTTP \u4F20\u8F93 OpenCode \u53E3\u4EE4\uFF08\u8BF7\u4F7F\u7528 HTTPS \u6216\u8BBE\u7F6E SUPERTASK_ALLOW_INSECURE_HTTP=1\uFF09"
30009
+ };
30010
+ }
30011
+ const explicitModel = ctx.model && ctx.model !== "default" ? ctx.model.trim() : null;
30012
+ const explicitVariant = ctx.variant && ctx.variant !== "default" ? ctx.variant.trim() : null;
30013
+ if (explicitModel && !parseModelSpec(explicitModel, explicitVariant)) {
30014
+ return { ok: false, sessionId: null, errorMessage: `\u65E0\u6548\u7684\u6A21\u578B\u683C\u5F0F\uFF08\u9700\u8981 provider/model\uFF09\uFF1A${explicitModel}` };
30015
+ }
30016
+ let sessionId = null;
30017
+ let interruptedRemote = false;
30018
+ const ensureInterrupt = async (targetIds) => {
30019
+ if (interruptedRemote && !targetIds) return;
30020
+ const ids = /* @__PURE__ */ new Set();
30021
+ if (targetIds) {
30022
+ for (const id of targetIds) if (id) ids.add(id);
30023
+ }
30024
+ if (sessionId) ids.add(sessionId);
30025
+ if (ids.size === 0) return;
30026
+ interruptedRemote = true;
30027
+ await Promise.all([...ids].map((id) => this.interruptSession(id)));
30028
+ };
30029
+ const sseController = new AbortController();
30030
+ const onOuterAbort = () => {
30031
+ sseController.abort();
30032
+ };
30033
+ if (ctx.signal.aborted) {
30034
+ return { ok: false, sessionId: null, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
30035
+ }
30036
+ ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
30037
+ try {
30038
+ const agentUrl = new URL(`${this.baseUrl}/api/agent`);
30039
+ agentUrl.searchParams.set("location[directory]", ctx.cwd);
30040
+ let agentDef;
30041
+ for (let attempt = 0; attempt < 4; attempt += 1) {
30042
+ const agentResp = await this.fetchFn(agentUrl.toString(), {
30043
+ headers: this.authHeaders(),
30044
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
30045
+ });
30046
+ if (!agentResp.ok) {
30047
+ return { ok: false, sessionId: null, errorMessage: `\u65E0\u6CD5\u8BFB\u53D6 OpenCode Agent \u6E05\u5355\uFF1AHTTP ${agentResp.status}` };
30048
+ }
30049
+ const payload = await agentResp.json();
30050
+ agentDef = Array.isArray(payload.data) ? payload.data.find((a) => a.id === ctx.agent) : void 0;
30051
+ if (agentDef) break;
30052
+ if (attempt < 3) await new Promise((r) => setTimeout(r, 250));
30053
+ }
30054
+ if (!agentDef || agentDef.hidden || agentDef.disabled || agentDef.mode === "subagent") {
30055
+ return { ok: false, sessionId: null, errorMessage: `\u4EFB\u52A1\u7684 Agent \u5DF2\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\uFF08${ctx.agent}\uFF09` };
30056
+ }
30057
+ const createResp = await this.fetchFn(`${this.baseUrl}/api/session`, {
30058
+ method: "POST",
30059
+ headers: this.authHeaders({ "content-type": "application/json" }),
30060
+ body: JSON.stringify({
30061
+ agent: ctx.agent,
30062
+ location: { directory: ctx.cwd },
30063
+ metadata: {
30064
+ ...ctx.metadata ?? {},
30065
+ supertaskTaskId: ctx.task.id,
30066
+ supertaskRunId: ctx.runId
30067
+ }
30068
+ }),
30069
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
30070
+ });
30071
+ if (!createResp.ok) {
30072
+ return { ok: false, sessionId: null, errorMessage: `\u521B\u5EFA OpenCode \u4F1A\u8BDD\u5931\u8D25\uFF1AHTTP ${createResp.status}` };
30073
+ }
30074
+ const created = await createResp.json();
30075
+ sessionId = created.data?.id ?? created.id ?? null;
30076
+ if (!sessionId) {
30077
+ return { ok: false, sessionId: null, errorMessage: "OpenCode \u672A\u8FD4\u56DE\u6709\u6548\u7684\u4F1A\u8BDD ID" };
30078
+ }
30079
+ ctx.onSessionId(sessionId);
30080
+ const cleanTitle = ctx.title.replace(/\s+/g, " ").trim().slice(0, 200);
30081
+ if (cleanTitle) {
30082
+ await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}`, {
30083
+ method: "PATCH",
30084
+ headers: this.authHeaders({ "content-type": "application/json" }),
30085
+ body: JSON.stringify({ title: cleanTitle }),
30086
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
30087
+ }).catch(() => void 0);
30088
+ }
30089
+ let modelSpec = explicitModel ? parseModelSpec(explicitModel, explicitVariant) : null;
30090
+ if (!modelSpec && agentDef.model?.providerID && agentDef.model?.id) {
30091
+ const resolvedVariant = explicitVariant ?? (agentDef.model.variant && agentDef.model.variant !== "default" ? agentDef.model.variant : void 0);
30092
+ modelSpec = {
30093
+ providerID: agentDef.model.providerID,
30094
+ id: agentDef.model.id,
30095
+ ...resolvedVariant ? { variant: resolvedVariant } : {}
30096
+ };
30097
+ }
30098
+ if (!modelSpec && this.defaultModel) {
30099
+ modelSpec = parseModelSpec(this.defaultModel, explicitVariant);
30100
+ }
30101
+ if (explicitVariant && !modelSpec) {
30102
+ return { ok: false, sessionId, errorMessage: "\u6307\u5B9A\u4E86 variant \u4F46\u672A\u914D\u7F6E\u53EF\u7528\u6A21\u578B" };
30103
+ }
30104
+ if (modelSpec) {
30105
+ const switchResp = await this.fetchFn(
30106
+ `${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/model`,
30107
+ {
30108
+ method: "POST",
30109
+ headers: this.authHeaders({ "content-type": "application/json" }),
30110
+ body: JSON.stringify({ model: modelSpec }),
30111
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
30112
+ }
30113
+ );
30114
+ if (!switchResp.ok) {
30115
+ return { ok: false, sessionId, errorMessage: `\u5207\u6362 OpenCode \u6A21\u578B\u5931\u8D25\uFF1AHTTP ${switchResp.status}` };
30116
+ }
30117
+ }
30118
+ const sseResp = await this.fetchFn(`${this.baseUrl}/api/event`, {
30119
+ headers: this.authHeaders({ accept: "text/event-stream" }),
30120
+ signal: sseController.signal
30121
+ });
30122
+ const contentType = sseResp.headers.get("content-type") || "";
30123
+ if (!sseResp.ok || !sseResp.body || !contentType.toLowerCase().includes("text/event-stream")) {
30124
+ sseController.abort();
30125
+ return {
30126
+ ok: false,
30127
+ sessionId,
30128
+ errorMessage: `\u65E0\u6CD5\u8BA2\u9605 OpenCode \u4E8B\u4EF6\u6D41\uFF1AHTTP ${sseResp.status}${contentType ? ` (${contentType})` : ""}`
30129
+ };
30130
+ }
30131
+ const promptResp = await this.fetchFn(
30132
+ `${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/prompt`,
30133
+ {
30134
+ method: "POST",
30135
+ headers: this.authHeaders({ "content-type": "application/json" }),
30136
+ body: JSON.stringify({ text: ctx.prompt }),
30137
+ signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(15e3)])
30138
+ }
30139
+ );
30140
+ if (!promptResp.ok) {
30141
+ sseController.abort();
30142
+ const detail = sanitizeErrorDetail(await promptResp.text().catch(() => ""));
30143
+ return {
30144
+ ok: false,
30145
+ sessionId,
30146
+ errorMessage: `OpenCode \u63D0\u4EA4\u4EFB\u52A1\u5931\u8D25\uFF1AHTTP ${promptResp.status}${detail ? ` ${detail}` : ""}`
30147
+ };
30148
+ }
30149
+ const trackedSessionIds = /* @__PURE__ */ new Set([sessionId]);
30150
+ const reader = sseResp.body.getReader();
30151
+ const decoder = new TextDecoder();
30152
+ let buffer = "";
30153
+ let pendingText = "";
30154
+ const flushText = () => {
30155
+ if (!pendingText) return;
30156
+ ctx.onOutputChunk(`${JSON.stringify({ type: "text", sessionID: sessionId, part: { text: pendingText } })}
30157
+ `);
30158
+ pendingText = "";
30159
+ };
30160
+ const processEventPayload = async (rawData) => {
30161
+ let evt;
30162
+ try {
30163
+ evt = JSON.parse(rawData);
30164
+ } catch {
30165
+ return null;
30166
+ }
30167
+ const evtType = evt.type || "";
30168
+ if (evtType === "session.created") {
30169
+ const childId = evt.data?.id ?? evt.data?.session?.id ?? "";
30170
+ const parentId = evt.data?.parentID ?? evt.data?.session?.parentID ?? "";
30171
+ if (childId && parentId && trackedSessionIds.has(parentId)) {
30172
+ trackedSessionIds.add(childId);
30173
+ }
30174
+ return null;
30175
+ }
30176
+ const evtSessionId = evt.data?.sessionID ?? evt.data?.form?.sessionID ?? "";
30177
+ if (!evtSessionId || !trackedSessionIds.has(evtSessionId)) return null;
30178
+ if (evtType === "permission.asked" || evtType === "form.created") {
30179
+ flushText();
30180
+ const message = evtType === "permission.asked" ? "\u4EFB\u52A1\u9700\u8981\u4EBA\u5DE5\u6279\u51C6\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\uFF0C\u6216\u660E\u786E\u8C03\u6574\u8BE5Agent\u7684\u64CD\u4F5C\u6743\u9650\u540E\u91CD\u8BD5\u3002" : "\u4EFB\u52A1\u9700\u8981\u4F60\u56DE\u7B54\u95EE\u9898\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u8865\u5168\u4EFB\u52A1\u8BF4\u660E\u540E\u91CD\u8BD5\uFF0C\u6216\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\u3002";
30181
+ ctx.onOutputChunk(`${JSON.stringify({
30182
+ type: "error",
30183
+ sessionID: sessionId,
30184
+ error: { name: "InteractionRequired", data: { message } }
30185
+ })}
30186
+ `);
30187
+ await ensureInterrupt(trackedSessionIds);
30188
+ return { ok: false, sessionId, errorMessage: message };
30189
+ }
30190
+ if (evtSessionId !== sessionId) return null;
30191
+ if (evtType === "session.text.delta") {
30192
+ const delta = typeof evt.data?.delta === "string" ? evt.data.delta : typeof evt.data?.text === "string" ? evt.data.text : "";
30193
+ if (delta) {
30194
+ pendingText += delta;
30195
+ if (pendingText.includes("\n") || pendingText.length >= 256) flushText();
30196
+ }
30197
+ return null;
30198
+ }
30199
+ if (evtType === "session.step.ended") {
30200
+ flushText();
30201
+ return null;
30202
+ }
30203
+ if (evtType === "session.execution.succeeded") {
30204
+ flushText();
30205
+ return { ok: true, sessionId };
30206
+ }
30207
+ if (evtType === "session.execution.failed") {
30208
+ flushText();
30209
+ const rawErr = evt.data?.error?.data?.message || evt.data?.error?.message || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
30210
+ const errMsg = sanitizeErrorDetail(rawErr, 400) || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
30211
+ ctx.onOutputChunk(`${JSON.stringify({
30212
+ type: "error",
30213
+ sessionID: sessionId,
30214
+ error: { name: evt.data?.error?.name || "ExecutionError", data: { message: errMsg } }
30215
+ })}
30216
+ `);
30217
+ return { ok: false, sessionId, errorMessage: errMsg };
30218
+ }
30219
+ if (evtType === "session.execution.interrupted") {
30220
+ flushText();
30221
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u6267\u884C\u5DF2\u4E2D\u65AD" };
30222
+ }
30223
+ return null;
30224
+ };
30225
+ try {
30226
+ while (true) {
30227
+ const { done, value } = await reader.read();
30228
+ if (done) break;
30229
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
30230
+ if (buffer.length > MAX_SSE_BUFFER_CHARS) {
30231
+ buffer = buffer.slice(-MAX_SSE_BUFFER_CHARS);
30232
+ }
30233
+ let sepIdx = buffer.indexOf("\n\n");
30234
+ while (sepIdx >= 0) {
30235
+ const frame = buffer.slice(0, sepIdx);
30236
+ buffer = buffer.slice(sepIdx + 2);
30237
+ const dataLines = [];
30238
+ for (const line of frame.split("\n")) {
30239
+ if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
30240
+ }
30241
+ if (dataLines.length > 0) {
30242
+ const terminal = await processEventPayload(dataLines.join("\n"));
30243
+ if (terminal) {
30244
+ sseController.abort();
30245
+ return terminal;
30246
+ }
30247
+ }
30248
+ sepIdx = buffer.indexOf("\n\n");
30249
+ }
30250
+ }
30251
+ } finally {
30252
+ reader.releaseLock();
30253
+ }
30254
+ flushText();
30255
+ if (ctx.signal.aborted) {
30256
+ await ensureInterrupt(trackedSessionIds);
30257
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
30258
+ }
30259
+ await ensureInterrupt(trackedSessionIds);
30260
+ return { ok: false, sessionId, errorMessage: "OpenCode \u4E8B\u4EF6\u6D41\u63D0\u524D\u65AD\u5F00\uFF0C\u5DF2\u4E2D\u6B62\u8FDC\u7AEF\u4F1A\u8BDD" };
30261
+ } catch (error) {
30262
+ if (ctx.signal.aborted) {
30263
+ await ensureInterrupt();
30264
+ return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
30265
+ }
30266
+ if (sessionId) await ensureInterrupt();
30267
+ const msg = sanitizeErrorDetail(error instanceof Error ? error.message : String(error), 300) || "Runner \u6267\u884C\u5F02\u5E38";
30268
+ return { ok: false, sessionId, errorMessage: msg };
30269
+ } finally {
30270
+ sseController.abort();
30271
+ ctx.signal.removeEventListener("abort", onOuterAbort);
30272
+ }
30273
+ }
30274
+ };
30275
+
30276
+ // src/worker/index.ts
29538
30277
  init_process_control();
29539
30278
  init_launch_protocol();
29540
30279
  init_task_working_directory();
29541
30280
  init_task_batch();
29542
- import { spawn as spawn2 } from "child_process";
29543
30281
  import { fileURLToPath as fileURLToPath3 } from "url";
29544
30282
  import { existsSync as existsSync3 } from "fs";
29545
30283
  import { dirname as dirname3, join as join3 } from "path";
@@ -29677,12 +30415,14 @@ var WorkerEngine = class {
29677
30415
  settlementRetryWakeups = /* @__PURE__ */ new Set();
29678
30416
  cfg;
29679
30417
  opencodeBin;
30418
+ runner;
29680
30419
  maxOutputChars;
29681
30420
  settlementRetryDelaysMs;
29682
30421
  settlementRetryIntervalMs;
29683
30422
  constructor(cfg, options = {}) {
29684
30423
  this.cfg = cfg.worker;
29685
30424
  this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
30425
+ this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
29686
30426
  this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
29687
30427
  this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
29688
30428
  this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
@@ -29731,7 +30471,7 @@ var WorkerEngine = class {
29731
30471
  if (this.pollCyclePromise) await this.pollCyclePromise;
29732
30472
  if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
29733
30473
  const deadline = Date.now() + gracePeriodMs;
29734
- while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
30474
+ while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (!entry.child || entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
29735
30475
  await Bun.sleep(Math.min(50, deadline - Date.now()));
29736
30476
  }
29737
30477
  }
@@ -29816,7 +30556,7 @@ var WorkerEngine = class {
29816
30556
  while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
29817
30557
  const databaseRunningCount = await TaskService.countRunning();
29818
30558
  if (databaseRunningCount >= this.cfg.maxConcurrency) break;
29819
- const openCode = await detectOpenCodeVersion(this.opencodeBin);
30559
+ const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
29820
30560
  if (this.stopped) break;
29821
30561
  let task;
29822
30562
  try {
@@ -29850,7 +30590,7 @@ var WorkerEngine = class {
29850
30590
  workerPid: process.pid,
29851
30591
  lockedAt: Date.now(),
29852
30592
  lockedBy: launchIdentity,
29853
- launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
30593
+ launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
29854
30594
  });
29855
30595
  runId = run.id;
29856
30596
  if (this.stopped) {
@@ -29870,9 +30610,19 @@ var WorkerEngine = class {
29870
30610
  } catch (error) {
29871
30611
  const message = error instanceof Error ? error.message : String(error);
29872
30612
  await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
30613
+ void dispatchTaskWebhook(buildTaskWebhookPayload(
30614
+ "task.dead_letter",
30615
+ { ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
30616
+ { id: run.id, sessionId: null, status: "failed" },
30617
+ message
30618
+ ));
29873
30619
  this.releaseBatch(task);
29874
30620
  continue;
29875
30621
  }
30622
+ if (this.runner) {
30623
+ this.executeViaRunner(task, run.id, launchIdentity, this.runner);
30624
+ continue;
30625
+ }
29876
30626
  let args;
29877
30627
  try {
29878
30628
  args = buildOpenCodeRunArgs(openCode.major, {
@@ -29884,7 +30634,14 @@ var WorkerEngine = class {
29884
30634
  });
29885
30635
  } catch (error) {
29886
30636
  if (!(error instanceof OpenCodeInvocationError)) throw error;
29887
- await TaskService.failRun(task.id, run.id, `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`, { setDeadLetter: true });
30637
+ const message = `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`;
30638
+ await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
30639
+ void dispatchTaskWebhook(buildTaskWebhookPayload(
30640
+ "task.dead_letter",
30641
+ { ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
30642
+ { id: run.id, sessionId: null, status: "failed" },
30643
+ message
30644
+ ));
29888
30645
  this.releaseBatch(task);
29889
30646
  continue;
29890
30647
  }
@@ -29924,8 +30681,106 @@ var WorkerEngine = class {
29924
30681
  if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
29925
30682
  return entry;
29926
30683
  }
30684
+ executeViaRunner(task, runId, launchIdentity, runner) {
30685
+ const cwd = task.cwd || process.cwd();
30686
+ const abortController = new AbortController();
30687
+ const model = this.resolveModel(task.model);
30688
+ const variant = this.resolveVariant(task.variant);
30689
+ const entry = {
30690
+ task,
30691
+ runId,
30692
+ sessionId: null,
30693
+ launchIdentity,
30694
+ child: null,
30695
+ runnerAbort: abortController,
30696
+ commandContext: runCommandContext(`runner:${runner.name}`, [task.agent], cwd),
30697
+ output: new RunOutput(
30698
+ this.maxOutputChars,
30699
+ (sessionId) => {
30700
+ entry.sessionId = sessionId;
30701
+ TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
30702
+ this.logError("sessionId update failed", err, task.id);
30703
+ });
30704
+ },
30705
+ (stream, line) => {
30706
+ gatewayEvents.emitRunLog(runId, task.id, stream, line);
30707
+ }
30708
+ ),
30709
+ timeoutTimer: null,
30710
+ termination: null,
30711
+ terminationPromise: null,
30712
+ settlementPromise: null,
30713
+ guardianDrained: true,
30714
+ quarantined: false,
30715
+ settled: false
30716
+ };
30717
+ this.runningTasks.set(task.id, entry);
30718
+ gatewayEvents.emitRunStarted({
30719
+ runId,
30720
+ taskId: task.id,
30721
+ cwd: task.cwd,
30722
+ model,
30723
+ variant
30724
+ });
30725
+ const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
30726
+ if (timeoutMs > 0) {
30727
+ entry.timeoutTimer = setTimeout(() => {
30728
+ this.runDetached(
30729
+ this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
30730
+ "runner timeout termination failed",
30731
+ entry.task.id
30732
+ );
30733
+ }, timeoutMs);
30734
+ entry.timeoutTimer.unref?.();
30735
+ }
30736
+ const runnerPromise = runner.execute({
30737
+ task,
30738
+ runId,
30739
+ cwd,
30740
+ agent: task.agent,
30741
+ model,
30742
+ variant,
30743
+ prompt: task.prompt,
30744
+ title: task.name,
30745
+ metadata: parseTaskMetadata(task.metadata),
30746
+ signal: abortController.signal,
30747
+ onSessionId: (sessionId) => {
30748
+ entry.sessionId = sessionId;
30749
+ TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
30750
+ this.logError("sessionId update failed", err, task.id);
30751
+ });
30752
+ },
30753
+ onOutputChunk: (chunk) => {
30754
+ entry.output.push("stdout", chunk);
30755
+ }
30756
+ }).then((result) => {
30757
+ if (entry.settled || entry.termination) return;
30758
+ this.runDetached(
30759
+ this.settleEntry(entry, result.ok ? 0 : 1, result.ok ? void 0 : result.errorMessage || "Runner \u6267\u884C\u5931\u8D25"),
30760
+ "runner settlement failed",
30761
+ entry.task.id
30762
+ );
30763
+ }).catch((error) => {
30764
+ if (entry.settled || entry.termination) return;
30765
+ const msg = error instanceof Error ? error.message : String(error);
30766
+ this.runDetached(
30767
+ this.settleEntry(entry, 1, `Runner \u6267\u884C\u5F02\u5E38\uFF1A${msg}`),
30768
+ "runner error settlement failed",
30769
+ entry.task.id
30770
+ );
30771
+ });
30772
+ entry.runnerDone = runnerPromise;
30773
+ }
29927
30774
  async spawnTask(task, runId, launchIdentity, args) {
29928
30775
  const cwd = task.cwd || process.cwd();
30776
+ const childEnv = {
30777
+ ...process.env,
30778
+ PWD: cwd,
30779
+ [MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
30780
+ };
30781
+ delete childEnv.SUPERTASK_API_TOKEN;
30782
+ delete childEnv.SUPERTASK_WEBHOOK_SECRET;
30783
+ delete childEnv.SUPERTASK_WEBHOOK_URL;
29929
30784
  const child = spawn2(process.execPath, [
29930
30785
  this.launcherEntry(),
29931
30786
  LAUNCH_IDENTITY_ARGUMENT,
@@ -29934,23 +30789,21 @@ var WorkerEngine = class {
29934
30789
  ...args
29935
30790
  ], {
29936
30791
  cwd,
29937
- env: {
29938
- ...process.env,
29939
- PWD: cwd,
29940
- [MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
29941
- },
30792
+ env: childEnv,
29942
30793
  stdio: ["pipe", "pipe", "pipe", "ipc"],
29943
30794
  detached: process.platform !== "win32"
29944
30795
  });
29945
30796
  const entry = {
29946
30797
  task,
29947
30798
  runId,
30799
+ sessionId: null,
29948
30800
  launchIdentity,
29949
30801
  child,
29950
30802
  commandContext: runCommandContext(this.opencodeBin, args, cwd),
29951
30803
  output: new RunOutput(
29952
30804
  this.maxOutputChars,
29953
30805
  (sessionId) => {
30806
+ entry.sessionId = sessionId;
29954
30807
  TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
29955
30808
  this.logError("sessionId update failed", err, task.id);
29956
30809
  });
@@ -30084,7 +30937,7 @@ var WorkerEngine = class {
30084
30937
  handleChildClose(entry, code, signal, spawnError) {
30085
30938
  if (entry.settled || entry.termination) return;
30086
30939
  if (!entry.guardianDrained) {
30087
- const pid2 = entry.child.pid;
30940
+ const pid2 = entry.child?.pid;
30088
30941
  const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
30089
30942
  const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
30090
30943
  if (presence !== "not-running") {
@@ -30107,7 +30960,7 @@ var WorkerEngine = class {
30107
30960
  );
30108
30961
  return;
30109
30962
  }
30110
- const pid = entry.child.pid;
30963
+ const pid = entry.child?.pid;
30111
30964
  if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
30112
30965
  if (entry.timeoutTimer) {
30113
30966
  clearTimeout(entry.timeoutTimer);
@@ -30202,6 +31055,12 @@ ${output2}` : ""}`;
30202
31055
  status: "cancelled",
30203
31056
  reason: "run-cancelled"
30204
31057
  });
31058
+ void dispatchTaskWebhook(buildTaskWebhookPayload(
31059
+ "task.cancelled",
31060
+ { ...entry.task, status: "cancelled", finishedAt: /* @__PURE__ */ new Date(), resultLog: log2 },
31061
+ { id: entry.runId, sessionId: entry.sessionId, status: "failed" },
31062
+ log2
31063
+ ));
30205
31064
  console.log(JSON.stringify({
30206
31065
  ts: (/* @__PURE__ */ new Date()).toISOString(),
30207
31066
  level: "info",
@@ -30231,6 +31090,12 @@ ${output}` : ""}` : output;
30231
31090
  status: "done",
30232
31091
  reason: "run-done"
30233
31092
  });
31093
+ void dispatchTaskWebhook(buildTaskWebhookPayload(
31094
+ "task.done",
31095
+ { ...entry.task, status: "done", finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
31096
+ { id: entry.runId, sessionId: entry.sessionId, status: "done" },
31097
+ log
31098
+ ));
30234
31099
  console.log(JSON.stringify({
30235
31100
  ts: (/* @__PURE__ */ new Date()).toISOString(),
30236
31101
  level: "info",
@@ -30276,6 +31141,13 @@ ${output}` : ""}` : output;
30276
31141
  status: failed.status,
30277
31142
  reason: "run-failed"
30278
31143
  });
31144
+ const webhookEvent = failed.status === "dead_letter" ? "task.dead_letter" : "task.failed";
31145
+ void dispatchTaskWebhook(buildTaskWebhookPayload(
31146
+ webhookEvent,
31147
+ { ...entry.task, status: failed.status, finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
31148
+ { id: entry.runId, sessionId: entry.sessionId, status: "failed" },
31149
+ log
31150
+ ));
30279
31151
  console.error(JSON.stringify({
30280
31152
  ts: (/* @__PURE__ */ new Date()).toISOString(),
30281
31153
  level: "error",
@@ -30358,6 +31230,17 @@ ${output}` : ""}` : output;
30358
31230
  }
30359
31231
  }
30360
31232
  async killEntry(entry, initialSignal = "SIGTERM") {
31233
+ if (entry.runnerAbort) {
31234
+ entry.runnerAbort.abort();
31235
+ if (entry.runnerDone) {
31236
+ await Promise.race([
31237
+ entry.runnerDone.catch(() => void 0),
31238
+ new Promise((resolve4) => setTimeout(resolve4, 5e3))
31239
+ ]);
31240
+ }
31241
+ return true;
31242
+ }
31243
+ if (!entry.child) return true;
30361
31244
  const pid = entry.child.pid;
30362
31245
  if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
30363
31246
  if (!pid) return false;
@@ -30373,7 +31256,7 @@ ${output}` : ""}` : output;
30373
31256
  return waitForSpawnedProcessTreeExit(pid, 2500);
30374
31257
  }
30375
31258
  signalEntry(entry, signal) {
30376
- const pid = entry.child.pid;
31259
+ const pid = entry.child?.pid;
30377
31260
  if (!pid) return "not-running";
30378
31261
  return signalRecordedProcessTreeWithResult(
30379
31262
  pid,
@@ -30439,7 +31322,7 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
30439
31322
  if (shouldStop()) break;
30440
31323
  if (isOwnedRun(run.taskId, run.runId)) continue;
30441
31324
  try {
30442
- if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
31325
+ if (run.launchProtocol != null && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL && run.launchProtocol !== HTTP_RUNNER_LAUNCH_PROTOCOL) {
30443
31326
  console.warn(JSON.stringify({
30444
31327
  ts: (/* @__PURE__ */ new Date()).toISOString(),
30445
31328
  level: "warn",
@@ -30452,6 +31335,20 @@ async function checkHeartbeats(heartbeatTimeoutMs, isOwnedRun = () => false, sho
30452
31335
  result.quarantinedRuns += 1;
30453
31336
  continue;
30454
31337
  }
31338
+ if (run.launchProtocol === HTTP_RUNNER_LAUNCH_PROTOCOL) {
31339
+ if (run.ownerAlive) {
31340
+ console.warn(JSON.stringify({
31341
+ ts: (/* @__PURE__ */ new Date()).toISOString(),
31342
+ level: "warn",
31343
+ msg: "stale http runner run still has live owner pid; run remains quarantined",
31344
+ taskId: run.taskId,
31345
+ runId: run.runId,
31346
+ workerPid: run.workerPid
31347
+ }));
31348
+ result.quarantinedRuns += 1;
31349
+ continue;
31350
+ }
31351
+ }
30455
31352
  if (run.childPid != null && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
30456
31353
  if (run.childPid > 0 && !isProcessAlive(run.childPid) && inspectSpawnedProcessTreePresence(run.childPid) === "not-running") {
30457
31354
  } else {
@@ -31174,6 +32071,7 @@ async function runGatewayMain(deps = {}) {
31174
32071
  await resolveDeps();
31175
32072
  if (shuttingDown) return;
31176
32073
  initializeGatewayHealth({
32074
+ workerMaxConcurrency: cfg.worker.maxConcurrency,
31177
32075
  workerPollIntervalMs: cfg.worker.pollIntervalMs,
31178
32076
  schedulerEnabled: cfg.scheduler.enabled,
31179
32077
  schedulerCheckIntervalMs: cfg.scheduler.checkIntervalMs,